]> git.sur5r.net Git - openldap/blob - libraries/libmdb/mdb.c
7a9804dc5ec9eb64d19ea980557a8d3673b3012c
[openldap] / libraries / libmdb / mdb.c
1 #include <sys/types.h>
2 #include <sys/stat.h>
3 #include <sys/queue.h>
4 #include <sys/param.h>
5 #include <sys/uio.h>
6 #include <sys/mman.h>
7 #ifdef HAVE_SYS_FILE_H
8 #include <sys/file.h>
9 #endif
10 #include <fcntl.h>
11
12 #include <assert.h>
13 #include <err.h>
14 #include <errno.h>
15 #include <fcntl.h>
16 #include <stddef.h>
17 #include <stdint.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <time.h>
22 #include <unistd.h>
23 #include <pthread.h>
24
25 #include "mdb.h"
26
27 #define ULONG           unsigned long
28 typedef ULONG           pgno_t;
29
30 #include "idl.h"
31
32 #ifndef DEBUG
33 #define DEBUG 1
34 #endif
35
36 #if (DEBUG +0) && defined(__GNUC__)
37 # define DPRINTF(fmt, ...) \
38         fprintf(stderr, "%s:%d: " fmt "\n", __func__, __LINE__, ##__VA_ARGS__)
39 #else
40 # define DPRINTF(...)   ((void) 0)
41 #endif
42
43 #define PAGESIZE         4096
44 #define MDB_MINKEYS      4
45 #define MDB_MAGIC        0xBEEFC0DE
46 #define MDB_VERSION      1
47 #define MAXKEYSIZE       255
48
49 #define P_INVALID        (~0UL)
50
51 #define F_ISSET(w, f)    (((w) & (f)) == (f))
52
53 typedef uint16_t         indx_t;
54
55 #define DEFAULT_READERS 126
56 #define DEFAULT_MAPSIZE 1048576
57
58 /* Lock descriptor stuff */
59 #define RXBODY  \
60         ULONG           mr_txnid; \
61         pid_t           mr_pid; \
62         pthread_t       mr_tid
63 typedef struct MDB_rxbody {
64         RXBODY;
65 } MDB_rxbody;
66
67 #ifndef CACHELINE
68 #define CACHELINE       64      /* most CPUs. Itanium uses 128 */
69 #endif
70
71 typedef struct MDB_reader {
72         RXBODY;
73         /* cache line alignment */
74         char pad[CACHELINE-sizeof(MDB_rxbody)];
75 } MDB_reader;
76
77 #define TXBODY \
78         uint32_t        mt_magic;       \
79         uint32_t        mt_version;     \
80         pthread_mutex_t mt_mutex;       \
81         ULONG           mt_txnid;       \
82         uint32_t        mt_numreaders
83 typedef struct MDB_txbody {
84         TXBODY;
85 } MDB_txbody;
86
87 typedef struct MDB_txninfo {
88         TXBODY;
89         char pad[CACHELINE-sizeof(MDB_txbody)];
90         pthread_mutex_t mt_wmutex;
91         char pad2[CACHELINE-sizeof(pthread_mutex_t)];
92         MDB_reader      mt_readers[1];
93 } MDB_txninfo;
94
95 /* Common header for all page types. Overflow pages
96  * occupy a number of contiguous pages with no
97  * headers on any page after the first.
98  */
99 typedef struct MDB_page {               /* represents a page of storage */
100         pgno_t          mp_pgno;                /* page number */
101 #define P_BRANCH         0x01           /* branch page */
102 #define P_LEAF           0x02           /* leaf page */
103 #define P_OVERFLOW       0x04           /* overflow page */
104 #define P_META           0x08           /* meta page */
105 #define P_DIRTY          0x10           /* dirty page */
106         uint32_t        mp_flags;
107 #define mp_lower        mp_pb.pb.pb_lower
108 #define mp_upper        mp_pb.pb.pb_upper
109 #define mp_pages        mp_pb.pb_pages
110         union page_bounds {
111                 struct {
112                         indx_t          pb_lower;               /* lower bound of free space */
113                         indx_t          pb_upper;               /* upper bound of free space */
114                 } pb;
115                 uint32_t        pb_pages;       /* number of overflow pages */
116         } mp_pb;
117         indx_t          mp_ptrs[1];             /* dynamic size */
118 } MDB_page;
119
120 #define PAGEHDRSZ        ((unsigned) offsetof(MDB_page, mp_ptrs))
121
122 #define NUMKEYS(p)       (((p)->mp_lower - PAGEHDRSZ) >> 1)
123 #define SIZELEFT(p)      (indx_t)((p)->mp_upper - (p)->mp_lower)
124 #define PAGEFILL(env, p) (1000L * ((env)->me_meta.mm_psize - PAGEHDRSZ - SIZELEFT(p)) / \
125                                 ((env)->me_meta.mm_psize - PAGEHDRSZ))
126 #define IS_LEAF(p)       F_ISSET((p)->mp_flags, P_LEAF)
127 #define IS_BRANCH(p)     F_ISSET((p)->mp_flags, P_BRANCH)
128 #define IS_OVERFLOW(p)   F_ISSET((p)->mp_flags, P_OVERFLOW)
129
130 #define OVPAGES(size, psize)    (PAGEHDRSZ + size + psize - 1) / psize;
131
132 typedef struct MDB_meta {                       /* meta (footer) page content */
133         uint32_t        mm_magic;
134         uint32_t        mm_version;
135         void            *mm_address;            /* address for fixed mapping */
136         size_t          mm_mapsize;                     /* size of mmap region */
137         pgno_t          mm_last_pg;                     /* last used page in file */
138         ULONG           mm_txnid;                       /* txnid that committed this page */
139         uint32_t        mm_psize;
140         uint16_t        mm_flags;
141         uint16_t        mm_depth;
142         ULONG           mm_branch_pages;
143         ULONG           mm_leaf_pages;
144         ULONG           mm_overflow_pages;
145         ULONG           mm_entries;
146         pgno_t          mm_root;
147 } MDB_meta;
148
149 typedef struct MDB_dhead {                                      /* a dirty page */
150         SIMPLEQ_ENTRY(MDB_dpage)         md_next;       /* queue of dirty pages */
151         MDB_page        *md_parent;
152         unsigned        md_pi;                          /* parent index */
153         int                     md_num;
154 } MDB_dhead;
155
156 typedef struct MDB_dpage {
157         MDB_dhead       h;
158         MDB_page        p;
159 } MDB_dpage;
160
161 SIMPLEQ_HEAD(dirty_queue, MDB_dpage);
162
163 typedef struct MDB_oldpages {
164         struct MDB_oldpages *mo_next;
165         ULONG           mo_txnid;
166         pgno_t          mo_pages[1];    /* dynamic */
167 } MDB_oldpages;
168
169 typedef struct MDB_pageparent {
170         MDB_page *mp_page;
171         MDB_page *mp_parent;
172         unsigned mp_pi;
173 } MDB_pageparent;
174
175 static MDB_dpage *mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num);
176 static int              mdb_touch(MDB_txn *txn, MDB_pageparent *mp);
177
178 typedef struct MDB_ppage {                                      /* ordered list of pages */
179         SLIST_ENTRY(MDB_ppage)   mp_entry;
180         MDB_page                *mp_page;
181         unsigned int    mp_ki;          /* cursor index on page */
182 } MDB_ppage;
183 SLIST_HEAD(page_stack, MDB_ppage);
184
185 #define CURSOR_EMPTY(c)          SLIST_EMPTY(&(c)->mc_stack)
186 #define CURSOR_TOP(c)            SLIST_FIRST(&(c)->mc_stack)
187 #define CURSOR_POP(c)            SLIST_REMOVE_HEAD(&(c)->mc_stack, mp_entry)
188 #define CURSOR_PUSH(c,p)         SLIST_INSERT_HEAD(&(c)->mc_stack, p, mp_entry)
189
190 struct MDB_cursor {
191         MDB_txn         *mc_txn;
192         struct page_stack        mc_stack;              /* stack of parent pages */
193         MDB_dbi         mc_dbi;
194         short           mc_initialized; /* 1 if initialized */
195         short           mc_eof;         /* 1 if end is reached */
196 };
197
198 #define METAHASHLEN      offsetof(MDB_meta, mm_hash)
199 #define METADATA(p)      ((void *)((char *)p + PAGEHDRSZ))
200
201 typedef struct MDB_node {
202 #define mn_pgno          mn_p.np_pgno
203 #define mn_dsize         mn_p.np_dsize
204         union {
205                 pgno_t           np_pgno;       /* child page number */
206                 uint32_t         np_dsize;      /* leaf data size */
207         } mn_p;
208         unsigned int    mn_flags:4;
209         unsigned int    mn_ksize:12;                    /* key size */
210 #define F_BIGDATA        0x01                   /* data put on overflow page */
211         char            mn_data[1];
212 } MDB_node;
213
214 typedef struct MDB_dbx {
215         char            *md_name;
216         MDB_cmp_func    *md_cmp;                /* user compare function */
217         MDB_rel_func    *md_rel;                /* user relocate function */
218 } MDB_dbx;
219
220 typedef struct MDB_db {
221         uint32_t        md_pad;
222         uint16_t        md_flags;
223         uint16_t        md_depth;
224         ULONG           md_branch_pages;
225         ULONG           md_leaf_pages;
226         ULONG           md_overflow_pages;
227         ULONG           md_entries;
228         pgno_t          md_root;
229 } MDB_db;
230
231 struct MDB_txn {
232         pgno_t          mt_root;                /* current / new root page */
233         pgno_t          mt_next_pgno;   /* next unallocated page */
234         ULONG           mt_txnid;
235         ULONG           mt_oldest;
236         MDB_env         *mt_env;        
237         pgno_t          *mt_free_pgs;   /* this is an IDL */
238         union {
239                 struct dirty_queue      *dirty_queue;   /* modified pages */
240                 MDB_reader      *reader;
241         } mt_u;
242         MDB_dbx         *mt_dbxs;               /* array */
243         MDB_db          **mt_dbs;               /* array of ptrs */
244         unsigned int    mt_numdbs;
245
246 #define MDB_TXN_RDONLY           0x01           /* read-only transaction */
247 #define MDB_TXN_ERROR            0x02           /* an error has occurred */
248 #define MDB_TXN_METOGGLE        0x04            /* used meta page 1 */
249         unsigned int             mt_flags;
250 };
251
252 struct MDB_env {
253         int                     me_fd;
254         int                     me_lfd;
255         uint32_t        me_flags;
256         unsigned int                    me_maxreaders;
257         char            *me_path;
258         char            *me_map;
259         MDB_txninfo     *me_txns;
260         MDB_meta        me_meta;
261         MDB_txn         *me_txn;                /* current write transaction */
262         size_t          me_mapsize;
263         off_t           me_size;                /* current file size */
264         pthread_key_t   me_txkey;       /* thread-key for readers */
265         MDB_oldpages *me_pghead;
266         MDB_oldpages *me_pgtail;
267         MDB_dbx         *me_dbxs;               /* array */
268         MDB_db          **me_dbs;               /* array of ptrs */
269         unsigned int    me_numdbs;
270 };
271
272 #define NODESIZE         offsetof(MDB_node, mn_data)
273
274 #define INDXSIZE(k)      (NODESIZE + ((k) == NULL ? 0 : (k)->mv_size))
275 #define LEAFSIZE(k, d)   (NODESIZE + (k)->mv_size + (d)->mv_size)
276 #define NODEPTR(p, i)    ((MDB_node *)((char *)(p) + (p)->mp_ptrs[i]))
277 #define NODEKEY(node)    (void *)((node)->mn_data)
278 #define NODEDATA(node)   (void *)((char *)(node)->mn_data + (node)->mn_ksize)
279 #define NODEPGNO(node)   ((node)->mn_pgno)
280 #define NODEDSZ(node)    ((node)->mn_dsize)
281
282 #define MDB_COMMIT_PAGES         64     /* max number of pages to write in one commit */
283 #define MDB_MAXCACHE_DEF         1024   /* max number of pages to keep in cache  */
284
285 static int  mdb_search_page_root(MDB_txn *txn,
286                             MDB_dbi dbi, MDB_val *key,
287                             MDB_cursor *cursor, int modify,
288                             MDB_pageparent *mpp);
289 static int  mdb_search_page(MDB_txn *txn,
290                             MDB_dbi dbi, MDB_val *key,
291                             MDB_cursor *cursor, int modify,
292                             MDB_pageparent *mpp);
293
294 static int  mdbenv_read_header(MDB_env *env);
295 static int  mdb_check_meta_page(MDB_page *p);
296 static int  mdbenv_read_meta(MDB_env *env, int *which);
297 static int  mdbenv_write_meta(MDB_txn *txn);
298 static MDB_page *mdbenv_get_page(MDB_env *env, pgno_t pgno);
299
300 static MDB_node *mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
301                             MDB_val *key, int *exactp, unsigned int *kip);
302 static int  mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp,
303                             indx_t indx, MDB_val *key, MDB_val *data,
304                             pgno_t pgno, uint8_t flags);
305 static void mdb_del_node(MDB_page *mp, indx_t indx);
306 static int  mdb_read_data(MDB_env *env, MDB_node *leaf, MDB_val *data);
307
308 static int               mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mp);
309 static int               mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key);
310 static int               mdb_move_node(MDB_txn *txn, MDB_dbi dbi, 
311                                 MDB_pageparent *src, indx_t srcindx,
312                                 MDB_pageparent *dst, indx_t dstindx);
313 static int               mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src,
314                             MDB_pageparent *dst);
315 static int               mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp,
316                             unsigned int *newindxp, MDB_val *newkey,
317                             MDB_val *newdata, pgno_t newpgno);
318 static MDB_dpage *mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num);
319
320 static void              cursor_pop_page(MDB_cursor *cursor);
321 static MDB_ppage *cursor_push_page(MDB_cursor *cursor,
322                             MDB_page *mp);
323
324 static int               mdb_set_key(MDB_node *node, MDB_val *key);
325 static int               mdb_sibling(MDB_cursor *cursor, int move_right);
326 static int               mdb_cursor_next(MDB_cursor *cursor,
327                             MDB_val *key, MDB_val *data);
328 static int               mdb_cursor_set(MDB_cursor *cursor,
329                             MDB_val *key, MDB_val *data, int *exactp);
330 static int               mdb_cursor_first(MDB_cursor *cursor,
331                             MDB_val *key, MDB_val *data);
332
333 static size_t            mdb_leaf_size(MDB_env *env, MDB_val *key,
334                             MDB_val *data);
335 static size_t            mdb_branch_size(MDB_env *env, MDB_val *key);
336
337 static int               memncmp(const void *s1, size_t n1,
338                                  const void *s2, size_t n2);
339 static int               memnrcmp(const void *s1, size_t n1,
340                                   const void *s2, size_t n2);
341
342 static int
343 memncmp(const void *s1, size_t n1, const void *s2, size_t n2)
344 {
345         int diff, len_diff = -1;
346
347         if (n1 >= n2) {
348                 len_diff = (n1 > n2);
349                 n1 = n2;
350         }
351         diff = memcmp(s1, s2, n1);
352         return diff ? diff : len_diff;
353 }
354
355 static int
356 memnrcmp(const void *s1, size_t n1, const void *s2, size_t n2)
357 {
358         const unsigned char     *p1, *p2, *p1_lim;
359
360         if (n2 == 0)
361                 return n1 != 0;
362         if (n1 == 0)
363                 return -1;
364
365         p1 = (const unsigned char *)s1 + n1 - 1;
366         p2 = (const unsigned char *)s2 + n2 - 1;
367
368         for (p1_lim = (n1 <= n2 ? s1 : s2);  *p1 == *p2;  p1--, p2--) {
369                 if (p1 == p1_lim)
370                         return (p1 != s1) ? (p1 != p2) : (p2 != s2) ? -1 : 0;
371         }
372         return *p1 - *p2;
373 }
374
375 int
376 mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *a, const MDB_val *b)
377 {
378         return txn->mt_dbxs[dbi].md_cmp(a, b);
379 }
380
381 static int
382 _mdb_cmp(MDB_txn *txn, MDB_dbi dbi, const MDB_val *key1, const MDB_val *key2)
383 {
384         if (F_ISSET(txn->mt_dbs[dbi]->md_flags, MDB_REVERSEKEY))
385                 return memnrcmp(key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
386         else
387                 return memncmp((char *)key1->mv_data, key1->mv_size, key2->mv_data, key2->mv_size);
388 }
389
390 /* Allocate new page(s) for writing */
391 static MDB_dpage *
392 mdb_alloc_page(MDB_txn *txn, MDB_page *parent, unsigned int parent_idx, int num)
393 {
394         MDB_dpage *dp;
395         pgno_t pgno = P_INVALID;
396
397         if (txn->mt_env->me_pghead) {
398                 ULONG oldest = txn->mt_txnid - 2;
399                 unsigned int i;
400                 for (i=0; i<txn->mt_env->me_txns->mt_numreaders; i++) {
401                         if (txn->mt_env->me_txns->mt_readers[i].mr_txnid < oldest)
402                                 oldest = txn->mt_env->me_txns->mt_readers[i].mr_txnid;
403                 }
404                 if (oldest > txn->mt_env->me_pghead->mo_txnid) {
405                         MDB_oldpages *mop = txn->mt_env->me_pghead;
406                         txn->mt_oldest = oldest;
407                         if (num > 1) {
408                                 /* FIXME: For now, always use fresh pages. We
409                                  * really ought to search the free list for a
410                                  * contiguous range.
411                                  */
412                                 ;
413                         } else {
414                                 /* peel pages off tail, so we only have to truncate the list */
415                                 pgno = MDB_IDL_LAST(mop->mo_pages);
416                                 if (MDB_IDL_IS_RANGE(mop->mo_pages)) {
417                                         mop->mo_pages[2]++;
418                                         if (mop->mo_pages[2] > mop->mo_pages[1])
419                                                 mop->mo_pages[0] = 0;
420                                 } else {
421                                         mop->mo_pages[0]--;
422                                 }
423                                 if (MDB_IDL_IS_ZERO(mop->mo_pages)) {
424                                         txn->mt_env->me_pghead = mop->mo_next;
425                                         if (!txn->mt_env->me_pghead)
426                                                 txn->mt_env->me_pgtail = NULL;
427                                         free(mop);
428                                 }
429                         }
430                 }
431         }
432
433         if ((dp = malloc(txn->mt_env->me_meta.mm_psize * num + sizeof(MDB_dhead))) == NULL)
434                 return NULL;
435         dp->h.md_num = num;
436         dp->h.md_parent = parent;
437         dp->h.md_pi = parent_idx;
438         SIMPLEQ_INSERT_TAIL(txn->mt_u.dirty_queue, dp, h.md_next);
439         if (pgno == P_INVALID) {
440                 dp->p.mp_pgno = txn->mt_next_pgno;
441                 txn->mt_next_pgno += num;
442         } else {
443                 dp->p.mp_pgno = pgno;
444         }
445
446         return dp;
447 }
448
449 /* Touch a page: make it dirty and re-insert into tree with updated pgno.
450  */
451 static int
452 mdb_touch(MDB_txn *txn, MDB_pageparent *pp)
453 {
454         MDB_page *mp = pp->mp_page;
455         pgno_t  pgno;
456         assert(txn != NULL);
457         assert(pp != NULL);
458
459         if (!F_ISSET(mp->mp_flags, P_DIRTY)) {
460                 MDB_dpage *dp;
461                 if ((dp = mdb_alloc_page(txn, pp->mp_parent, pp->mp_pi, 1)) == NULL)
462                         return ENOMEM;
463                 DPRINTF("touched page %lu -> %lu", mp->mp_pgno, dp->p.mp_pgno);
464                 mdb_idl_insert(txn->mt_free_pgs, mp->mp_pgno);
465                 pgno = dp->p.mp_pgno;
466                 memcpy(&dp->p, mp, txn->mt_env->me_meta.mm_psize);
467                 mp = &dp->p;
468                 mp->mp_pgno = pgno;
469                 mp->mp_flags |= P_DIRTY;
470
471                 /* Update the page number to new touched page. */
472                 if (pp->mp_parent != NULL)
473                         NODEPGNO(NODEPTR(pp->mp_parent, pp->mp_pi)) = mp->mp_pgno;
474                 pp->mp_page = mp;
475         }
476         return 0;
477 }
478
479 int
480 mdbenv_sync(MDB_env *env)
481 {
482         int rc = 0;
483         if (!F_ISSET(env->me_flags, MDB_NOSYNC)) {
484                 if (fsync(env->me_fd))
485                         rc = errno;
486         }
487         return rc;
488 }
489
490 #define DBX_CHUNK       16      /* space for 16 DBs at a time */
491
492 int
493 mdb_txn_begin(MDB_env *env, int rdonly, MDB_txn **ret)
494 {
495         MDB_txn *txn;
496         int rc, toggle;
497
498         if ((txn = calloc(1, sizeof(*txn))) == NULL) {
499                 DPRINTF("calloc: %s", strerror(errno));
500                 return ENOMEM;
501         }
502
503         if (rdonly) {
504                 txn->mt_flags |= MDB_TXN_RDONLY;
505         } else {
506                 txn->mt_u.dirty_queue = calloc(1, sizeof(*txn->mt_u.dirty_queue));
507                 if (txn->mt_u.dirty_queue == NULL) {
508                         free(txn);
509                         return ENOMEM;
510                 }
511                 SIMPLEQ_INIT(txn->mt_u.dirty_queue);
512
513                 pthread_mutex_lock(&env->me_txns->mt_wmutex);
514                 env->me_txns->mt_txnid++;
515                 txn->mt_free_pgs = malloc(MDB_IDL_UM_SIZEOF);
516                 if (txn->mt_free_pgs == NULL) {
517                         free(txn->mt_u.dirty_queue);
518                         free(txn);
519                         return ENOMEM;
520                 }
521                 txn->mt_free_pgs[0] = 0;
522         }
523         /* Copy the DB arrays */
524         txn->mt_numdbs = env->me_numdbs;
525         rc = (txn->mt_numdbs % DBX_CHUNK) + 1;
526         txn->mt_dbxs = malloc(rc * DBX_CHUNK * sizeof(MDB_dbx));
527         txn->mt_dbs = malloc(rc * DBX_CHUNK * sizeof(MDB_db *));
528         memcpy(txn->mt_dbxs, env->me_dbxs, txn->mt_numdbs * sizeof(MDB_dbx));
529         memcpy(txn->mt_dbs, env->me_dbs, txn->mt_numdbs * sizeof(MDB_db *));
530
531         txn->mt_txnid = env->me_txns->mt_txnid;
532         if (rdonly) {
533                 MDB_reader *r = pthread_getspecific(env->me_txkey);
534                 if (!r) {
535                         unsigned int i;
536                         pthread_mutex_lock(&env->me_txns->mt_mutex);
537                         for (i=0; i<env->me_maxreaders; i++) {
538                                 if (env->me_txns->mt_readers[i].mr_pid == 0) {
539                                         env->me_txns->mt_readers[i].mr_pid = getpid();
540                                         env->me_txns->mt_readers[i].mr_tid = pthread_self();
541                                         r = &env->me_txns->mt_readers[i];
542                                         pthread_setspecific(env->me_txkey, r);
543                                         if (i >= env->me_txns->mt_numreaders)
544                                                 env->me_txns->mt_numreaders = i+1;
545                                         break;
546                                 }
547                         }
548                         pthread_mutex_unlock(&env->me_txns->mt_mutex);
549                         if (i == env->me_maxreaders) {
550                                 return ENOSPC;
551                         }
552                 }
553                 r->mr_txnid = txn->mt_txnid;
554                 txn->mt_u.reader = r;
555         } else {
556                 env->me_txn = txn;
557         }
558
559         txn->mt_env = env;
560
561         if ((rc = mdbenv_read_meta(env, &toggle)) != MDB_SUCCESS) {
562                 mdb_txn_abort(txn);
563                 return rc;
564         }
565
566         if (toggle)
567                 txn->mt_flags |= MDB_TXN_METOGGLE;
568
569         txn->mt_next_pgno = env->me_meta.mm_last_pg+1;
570         txn->mt_root = env->me_meta.mm_root;
571         DPRINTF("begin transaction %lu on mdbenv %p, root page %lu",
572                 txn->mt_txnid, (void *) env, txn->mt_root);
573
574         *ret = txn;
575         return MDB_SUCCESS;
576 }
577
578 void
579 mdb_txn_abort(MDB_txn *txn)
580 {
581         MDB_dpage *dp;
582         MDB_env *env;
583
584         if (txn == NULL)
585                 return;
586
587         env = txn->mt_env;
588         DPRINTF("abort transaction %lu on mdbenv %p, root page %lu",
589                 txn->mt_txnid, (void *) env, txn->mt_root);
590
591         free(txn->mt_dbs);
592         free(txn->mt_dbxs);
593
594         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
595                 txn->mt_u.reader->mr_txnid = 0;
596         } else {
597                 /* Discard all dirty pages. Return any re-used pages
598                  * to the free list.
599                  */
600                 MDB_IDL_ZERO(txn->mt_free_pgs);
601                 while (!SIMPLEQ_EMPTY(txn->mt_u.dirty_queue)) {
602                         dp = SIMPLEQ_FIRST(txn->mt_u.dirty_queue);
603                         SIMPLEQ_REMOVE_HEAD(txn->mt_u.dirty_queue, h.md_next);
604                         if (dp->p.mp_pgno <= env->me_meta.mm_last_pg)
605                                 mdb_idl_insert(txn->mt_free_pgs, dp->p.mp_pgno);
606                         free(dp);
607                 }
608                 /* put back to head of free list */
609                 if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
610                         MDB_oldpages *mop;
611
612                         mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(txn->mt_free_pgs) - sizeof(pgno_t));
613                         mop->mo_next = env->me_pghead;
614                         mop->mo_txnid = txn->mt_oldest - 1;
615                         if (!env->me_pghead) {
616                                 env->me_pgtail = mop;
617                         }
618                         env->me_pghead = mop;
619                         memcpy(mop->mo_pages, txn->mt_free_pgs, MDB_IDL_SIZEOF(txn->mt_free_pgs));
620                 }
621
622                 free(txn->mt_free_pgs);
623                 free(txn->mt_u.dirty_queue);
624                 env->me_txn = NULL;
625                 env->me_txns->mt_txnid--;
626                 pthread_mutex_unlock(&env->me_txns->mt_wmutex);
627         }
628
629         free(txn);
630 }
631
632 int
633 mdb_txn_commit(MDB_txn *txn)
634 {
635         int              n, done;
636         ssize_t          rc;
637         off_t            size;
638         MDB_dpage       *dp;
639         MDB_env *env;
640         pgno_t  next;
641         struct iovec     iov[MDB_COMMIT_PAGES];
642
643         assert(txn != NULL);
644         assert(txn->mt_env != NULL);
645
646         env = txn->mt_env;
647
648         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
649                 DPRINTF("attempt to commit read-only transaction");
650                 mdb_txn_abort(txn);
651                 return EPERM;
652         }
653
654         if (txn != env->me_txn) {
655                 DPRINTF("attempt to commit unknown transaction");
656                 mdb_txn_abort(txn);
657                 return EINVAL;
658         }
659
660         if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
661                 DPRINTF("error flag is set, can't commit");
662                 mdb_txn_abort(txn);
663                 return EINVAL;
664         }
665
666         if (SIMPLEQ_EMPTY(txn->mt_u.dirty_queue))
667                 goto done;
668
669         DPRINTF("committing transaction %lu on mdbenv %p, root page %lu",
670             txn->mt_txnid, (void *) env, txn->mt_root);
671
672         /* Commit up to MDB_COMMIT_PAGES dirty pages to disk until done.
673          */
674         next = 0;
675         do {
676                 n = 0;
677                 done = 1;
678                 size = 0;
679                 SIMPLEQ_FOREACH(dp, txn->mt_u.dirty_queue, h.md_next) {
680                         if (dp->p.mp_pgno != next) {
681                                 if (n) {
682                                         DPRINTF("committing %u dirty pages", n);
683                                         rc = writev(env->me_fd, iov, n);
684                                         if (rc != size) {
685                                                 n = errno;
686                                                 if (rc > 0)
687                                                         DPRINTF("short write, filesystem full?");
688                                                 else
689                                                         DPRINTF("writev: %s", strerror(errno));
690                                                 mdb_txn_abort(txn);
691                                                 return n;
692                                         }
693                                         n = 0;
694                                         size = 0;
695                                 }
696                                 lseek(env->me_fd, dp->p.mp_pgno * env->me_meta.mm_psize, SEEK_SET);
697                                 next = dp->p.mp_pgno;
698                         }
699                         DPRINTF("committing page %lu", dp->p.mp_pgno);
700                         iov[n].iov_len = env->me_meta.mm_psize * dp->h.md_num;
701                         iov[n].iov_base = &dp->p;
702                         size += iov[n].iov_len;
703                         next = dp->p.mp_pgno + dp->h.md_num;
704                         /* clear dirty flag */
705                         dp->p.mp_flags &= ~P_DIRTY;
706                         if (++n >= MDB_COMMIT_PAGES) {
707                                 done = 0;
708                                 break;
709                         }
710                 }
711
712                 if (n == 0)
713                         break;
714
715                 DPRINTF("committing %u dirty pages", n);
716                 rc = writev(env->me_fd, iov, n);
717                 if (rc != size) {
718                         n = errno;
719                         if (rc > 0)
720                                 DPRINTF("short write, filesystem full?");
721                         else
722                                 DPRINTF("writev: %s", strerror(errno));
723                         mdb_txn_abort(txn);
724                         return n;
725                 }
726
727         } while (!done);
728
729         /* Drop the dirty pages.
730          */
731         while (!SIMPLEQ_EMPTY(txn->mt_u.dirty_queue)) {
732                 dp = SIMPLEQ_FIRST(txn->mt_u.dirty_queue);
733                 SIMPLEQ_REMOVE_HEAD(txn->mt_u.dirty_queue, h.md_next);
734                 free(dp);
735         }
736
737         if ((n = mdbenv_sync(env)) != 0 ||
738             (n = mdbenv_write_meta(txn)) != MDB_SUCCESS ||
739             (n = mdbenv_sync(env)) != 0) {
740                 mdb_txn_abort(txn);
741                 return n;
742         }
743         env->me_txn = NULL;
744
745         {
746                 MDB_dbx *p1 = env->me_dbxs;
747                 MDB_db **p2 = env->me_dbs;
748
749                 env->me_dbxs = txn->mt_dbxs;
750                 env->me_dbs = txn->mt_dbs;
751
752                 free(p2);
753                 free(p1);
754         }
755
756         /* add to tail of free list */
757         if (!MDB_IDL_IS_ZERO(txn->mt_free_pgs)) {
758                 MDB_oldpages *mop;
759
760                 mop = malloc(sizeof(MDB_oldpages) + MDB_IDL_SIZEOF(txn->mt_free_pgs) - sizeof(pgno_t));
761                 mop->mo_next = NULL;
762                 if (env->me_pghead) {
763                         env->me_pgtail->mo_next = mop;
764                 } else {
765                         env->me_pghead = mop;
766                 }
767                 env->me_pgtail = mop;
768                 memcpy(mop->mo_pages, txn->mt_free_pgs, MDB_IDL_SIZEOF(txn->mt_free_pgs));
769                 mop->mo_txnid = txn->mt_txnid;
770         }
771
772         pthread_mutex_unlock(&env->me_txns->mt_wmutex);
773         free(txn->mt_free_pgs);
774         free(txn->mt_u.dirty_queue);
775         free(txn);
776         txn = NULL;
777
778 done:
779         mdb_txn_abort(txn);
780
781         return MDB_SUCCESS;
782 }
783
784 static int
785 mdbenv_read_header(MDB_env *env)
786 {
787         char             page[PAGESIZE];
788         MDB_page        *p;
789         MDB_meta        *m;
790         int              rc;
791
792         assert(env != NULL);
793
794         /* We don't know the page size yet, so use a minimum value.
795          */
796
797         if ((rc = pread(env->me_fd, page, PAGESIZE, 0)) == 0) {
798                 return ENOENT;
799         } else if (rc != PAGESIZE) {
800                 if (rc > 0)
801                         errno = EINVAL;
802                 DPRINTF("read: %s", strerror(errno));
803                 return errno;
804         }
805
806         p = (MDB_page *)page;
807
808         if (!F_ISSET(p->mp_flags, P_META)) {
809                 DPRINTF("page %lu not a meta page", p->mp_pgno);
810                 return EINVAL;
811         }
812
813         m = METADATA(p);
814         if (m->mm_magic != MDB_MAGIC) {
815                 DPRINTF("meta has invalid magic");
816                 return EINVAL;
817         }
818
819         if (m->mm_version != MDB_VERSION) {
820                 DPRINTF("database is version %u, expected version %u",
821                     m->mm_version, MDB_VERSION);
822                 return EINVAL;
823         }
824
825         memcpy(&env->me_meta, m, sizeof(*m));
826         return 0;
827 }
828
829 static int
830 mdbenv_init_meta(MDB_env *env)
831 {
832         MDB_page *p, *q;
833         MDB_meta *meta;
834         int rc;
835         unsigned int     psize;
836
837         DPRINTF("writing new meta page");
838         psize = sysconf(_SC_PAGE_SIZE);
839
840         env->me_meta.mm_magic = MDB_MAGIC;
841         env->me_meta.mm_version = MDB_VERSION;
842         env->me_meta.mm_psize = psize;
843         env->me_meta.mm_flags = env->me_flags & 0xffff;
844         env->me_meta.mm_root = P_INVALID;
845         env->me_meta.mm_last_pg = 1;
846
847         p = calloc(2, psize);
848         p->mp_pgno = 0;
849         p->mp_flags = P_META;
850
851         meta = METADATA(p);
852         memcpy(meta, &env->me_meta, sizeof(*meta));
853
854         q = (MDB_page *)((char *)p + psize);
855
856         q->mp_pgno = 1;
857         q->mp_flags = P_META;
858
859         meta = METADATA(q);
860         memcpy(meta, &env->me_meta, sizeof(*meta));
861
862         rc = write(env->me_fd, p, psize * 2);
863         free(p);
864         return (rc == (int)psize * 2) ? MDB_SUCCESS : errno;
865 }
866
867 static int
868 mdbenv_write_meta(MDB_txn *txn)
869 {
870         MDB_env *env;
871         MDB_meta        meta;
872         off_t off;
873         int rc, len;
874         char *ptr;
875
876         assert(txn != NULL);
877         assert(txn->mt_env != NULL);
878
879         DPRINTF("writing meta page for root page %lu", txn->mt_root);
880
881         env = txn->mt_env;
882
883         ptr = (char *)&meta;
884         off = offsetof(MDB_meta, mm_depth);
885         len = sizeof(MDB_meta) - off;
886
887         ptr += off;
888         meta.mm_depth = txn->mt_dbs[0]->md_depth;
889         meta.mm_branch_pages = txn->mt_dbs[0]->md_branch_pages;
890         meta.mm_leaf_pages = txn->mt_dbs[0]->md_leaf_pages;
891         meta.mm_overflow_pages = txn->mt_dbs[0]->md_overflow_pages;
892         meta.mm_entries = txn->mt_dbs[0]->md_entries;
893         meta.mm_root = txn->mt_root;
894         meta.mm_last_pg = txn->mt_next_pgno - 1;
895         meta.mm_txnid = txn->mt_txnid;
896
897         if (!F_ISSET(txn->mt_flags, MDB_TXN_METOGGLE))
898                 off += env->me_meta.mm_psize;
899         off += PAGEHDRSZ;
900
901         lseek(env->me_fd, off, SEEK_SET);
902         rc = write(env->me_fd, ptr, len);
903         if (rc != len) {
904                 DPRINTF("write failed, disk error?");
905                 return errno;
906         }
907
908         return MDB_SUCCESS;
909 }
910
911 /* Returns true if page p is a valid meta page, false otherwise.
912  */
913 static int
914 mdb_check_meta_page(MDB_page *p)
915 {
916         if (!F_ISSET(p->mp_flags, P_META)) {
917                 DPRINTF("page %lu not a meta page", p->mp_pgno);
918                 return EINVAL;
919         }
920
921         return 0;
922 }
923
924 static int
925 mdbenv_read_meta(MDB_env *env, int *which)
926 {
927         MDB_page        *mp0, *mp1;
928         MDB_meta        *meta[2];
929         int toggle = 0, rc;
930
931         assert(env != NULL);
932
933         if ((mp0 = mdbenv_get_page(env, 0)) == NULL ||
934                 (mp1 = mdbenv_get_page(env, 1)) == NULL)
935                 return EIO;
936
937         rc = mdb_check_meta_page(mp0);
938         if (rc) return rc;
939
940         rc = mdb_check_meta_page(mp1);
941         if (rc) return rc;
942
943         meta[0] = METADATA(mp0);
944         meta[1] = METADATA(mp1);
945
946         if (meta[0]->mm_txnid < meta[1]->mm_txnid)
947                 toggle = 1;
948
949         if (meta[toggle]->mm_txnid > env->me_meta.mm_txnid) {
950                 memcpy(&env->me_meta, meta[toggle], sizeof(env->me_meta));
951                 if (which)
952                         *which = toggle;
953         }
954
955         DPRINTF("Using meta page %d", toggle);
956
957         return MDB_SUCCESS;
958 }
959
960 int
961 mdbenv_create(MDB_env **env)
962 {
963         MDB_env *e;
964
965         e = calloc(1, sizeof(*e));
966         if (!e) return ENOMEM;
967
968         e->me_meta.mm_mapsize = DEFAULT_MAPSIZE;
969         e->me_maxreaders = DEFAULT_READERS;
970         e->me_fd = -1;
971         e->me_lfd = -1;
972         *env = e;
973         return MDB_SUCCESS;
974 }
975
976 int
977 mdbenv_set_mapsize(MDB_env *env, size_t size)
978 {
979         if (env->me_map)
980                 return EINVAL;
981         env->me_mapsize = env->me_meta.mm_mapsize = size;
982         return MDB_SUCCESS;
983 }
984
985 int
986 mdbenv_set_maxreaders(MDB_env *env, int readers)
987 {
988         env->me_maxreaders = readers;
989         return MDB_SUCCESS;
990 }
991
992 int
993 mdbenv_get_maxreaders(MDB_env *env, int *readers)
994 {
995         if (!env || !readers)
996                 return EINVAL;
997         *readers = env->me_maxreaders;
998         return MDB_SUCCESS;
999 }
1000
1001 int
1002 mdbenv_open2(MDB_env *env, unsigned int flags)
1003 {
1004         int i, newenv = 0;
1005
1006         env->me_flags = flags;
1007
1008         if ((i = mdbenv_read_header(env)) != 0) {
1009                 if (i != ENOENT)
1010                         return i;
1011                 DPRINTF("new mdbenv");
1012                 newenv = 1;
1013         }
1014
1015         if (!env->me_mapsize)
1016                 env->me_mapsize = env->me_meta.mm_mapsize;
1017
1018         i = MAP_SHARED;
1019         if (env->me_meta.mm_address && (flags & MDB_FIXEDMAP))
1020                 i |= MAP_FIXED;
1021         env->me_map = mmap(env->me_meta.mm_address, env->me_mapsize, PROT_READ, i,
1022                 env->me_fd, 0);
1023         if (env->me_map == MAP_FAILED)
1024                 return errno;
1025
1026         if (newenv) {
1027                 env->me_meta.mm_mapsize = env->me_mapsize;
1028                 if (flags & MDB_FIXEDMAP)
1029                         env->me_meta.mm_address = env->me_map;
1030                 i = mdbenv_init_meta(env);
1031                 if (i != MDB_SUCCESS) {
1032                         munmap(env->me_map, env->me_mapsize);
1033                         return i;
1034                 }
1035         }
1036
1037         if ((i = mdbenv_read_meta(env, NULL)) != 0)
1038                 return i;
1039
1040         DPRINTF("opened database version %u, pagesize %u",
1041             env->me_meta.mm_version, env->me_meta.mm_psize);
1042         DPRINTF("depth: %u", env->me_meta.mm_depth);
1043         DPRINTF("entries: %lu", env->me_meta.mm_entries);
1044         DPRINTF("branch pages: %lu", env->me_meta.mm_branch_pages);
1045         DPRINTF("leaf pages: %lu", env->me_meta.mm_leaf_pages);
1046         DPRINTF("overflow pages: %lu", env->me_meta.mm_overflow_pages);
1047         DPRINTF("root: %lu", env->me_meta.mm_root);
1048
1049         return MDB_SUCCESS;
1050 }
1051
1052 static void
1053 mdbenv_reader_dest(void *ptr)
1054 {
1055         MDB_reader *reader = ptr;
1056
1057         reader->mr_txnid = 0;
1058         reader->mr_pid = 0;
1059         reader->mr_tid = 0;
1060 }
1061
1062 static void
1063 mdbenv_share_locks(MDB_env *env)
1064 {
1065         struct flock lock_info;
1066
1067         env->me_txns->mt_txnid = env->me_meta.mm_txnid;
1068
1069         memset((void *)&lock_info, 0, sizeof(lock_info));
1070         lock_info.l_type = F_RDLCK;
1071         lock_info.l_whence = SEEK_SET;
1072         lock_info.l_start = 0;
1073         lock_info.l_len = 1;
1074         fcntl(env->me_lfd, F_SETLK, &lock_info);
1075 }
1076
1077 static int
1078 mdbenv_setup_locks(MDB_env *env, char *lpath, int mode, int *excl)
1079 {
1080         int rc;
1081         off_t size, rsize;
1082         struct flock lock_info;
1083
1084         *excl = 0;
1085
1086         if ((env->me_lfd = open(lpath, O_RDWR|O_CREAT, mode)) == -1) {
1087                 rc = errno;
1088                 return rc;
1089         }
1090         /* Try to get exclusive lock. If we succeed, then
1091          * nobody is using the lock region and we should initialize it.
1092          */
1093         memset((void *)&lock_info, 0, sizeof(lock_info));
1094         lock_info.l_type = F_WRLCK;
1095         lock_info.l_whence = SEEK_SET;
1096         lock_info.l_start = 0;
1097         lock_info.l_len = 1;
1098         rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1099         if (rc == 0) {
1100                 *excl = 1;
1101         } else {
1102                 lock_info.l_type = F_RDLCK;
1103                 rc = fcntl(env->me_lfd, F_SETLK, &lock_info);
1104                 if (rc) {
1105                         rc = errno;
1106                         goto fail;
1107                 }
1108         }
1109         size = lseek(env->me_lfd, 0, SEEK_END);
1110         rsize = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1111         if (size < rsize && *excl) {
1112                 if (ftruncate(env->me_lfd, rsize) != 0) {
1113                         rc = errno;
1114                         goto fail;
1115                 }
1116         } else {
1117                 rsize = size;
1118                 size = rsize - sizeof(MDB_txninfo);
1119                 env->me_maxreaders = size/sizeof(MDB_reader) + 1;
1120         }
1121         env->me_txns = mmap(0, rsize, PROT_READ|PROT_WRITE, MAP_SHARED,
1122                 env->me_lfd, 0);
1123         if (env->me_txns == MAP_FAILED) {
1124                 rc = errno;
1125                 goto fail;
1126         }
1127         if (*excl) {
1128                 pthread_mutexattr_t mattr;
1129
1130                 pthread_mutexattr_init(&mattr);
1131                 pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
1132                 pthread_mutex_init(&env->me_txns->mt_mutex, &mattr);
1133                 pthread_mutex_init(&env->me_txns->mt_wmutex, &mattr);
1134                 env->me_txns->mt_version = MDB_VERSION;
1135                 env->me_txns->mt_magic = MDB_MAGIC;
1136                 env->me_txns->mt_txnid = 0;
1137                 env->me_txns->mt_numreaders = 0;
1138
1139         } else {
1140                 if (env->me_txns->mt_magic != MDB_MAGIC) {
1141                         DPRINTF("lock region has invalid magic");
1142                         errno = EINVAL;
1143                 }
1144                 if (env->me_txns->mt_version != MDB_VERSION) {
1145                         DPRINTF("lock region is version %u, expected version %u",
1146                                 env->me_txns->mt_version, MDB_VERSION);
1147                         errno = EINVAL;
1148                 }
1149                 if (errno != EACCES && errno != EAGAIN) {
1150                         rc = errno;
1151                         goto fail;
1152                 }
1153         }
1154         return MDB_SUCCESS;
1155
1156 fail:
1157         close(env->me_lfd);
1158         return rc;
1159
1160 }
1161
1162 int
1163 mdbenv_open(MDB_env *env, const char *path, unsigned int flags, mode_t mode)
1164 {
1165         int             oflags, rc, len, excl;
1166         char *lpath, *dpath;
1167
1168         len = strlen(path);
1169         lpath = malloc(len + sizeof("/lock.mdb") + len + sizeof("/data.db"));
1170         if (!lpath)
1171                 return ENOMEM;
1172         dpath = lpath + len + sizeof("/lock.mdb");
1173         sprintf(lpath, "%s/lock.mdb", path);
1174         sprintf(dpath, "%s/data.mdb", path);
1175
1176         rc = mdbenv_setup_locks(env, lpath, mode, &excl);
1177         if (rc)
1178                 goto leave;
1179
1180         if (F_ISSET(flags, MDB_RDONLY))
1181                 oflags = O_RDONLY;
1182         else
1183                 oflags = O_RDWR | O_CREAT;
1184
1185         if ((env->me_fd = open(dpath, oflags, mode)) == -1)
1186                 return errno;
1187
1188         if ((rc = mdbenv_open2(env, flags)) != MDB_SUCCESS) {
1189                 close(env->me_fd);
1190                 env->me_fd = -1;
1191         } else {
1192                 env->me_path = strdup(path);
1193                 DPRINTF("opened dbenv %p", (void *) env);
1194                 pthread_key_create(&env->me_txkey, mdbenv_reader_dest);
1195                 if (excl)
1196                         mdbenv_share_locks(env);
1197                 env->me_dbxs = calloc(DBX_CHUNK, sizeof(MDB_dbx));
1198                 env->me_dbs = calloc(DBX_CHUNK, sizeof(MDB_db *));
1199                 env->me_numdbs = 1;
1200                 env->me_dbs[0] = (MDB_db *)&env->me_meta.mm_psize;
1201         }
1202
1203
1204 leave:
1205         free(lpath);
1206         return rc;
1207 }
1208
1209 void
1210 mdbenv_close(MDB_env *env)
1211 {
1212         if (env == NULL)
1213                 return;
1214
1215         free(env->me_path);
1216
1217         if (env->me_map) {
1218                 munmap(env->me_map, env->me_mapsize);
1219         }
1220         close(env->me_fd);
1221         if (env->me_txns) {
1222                 size_t size = (env->me_maxreaders-1) * sizeof(MDB_reader) + sizeof(MDB_txninfo);
1223                 munmap(env->me_txns, size);
1224         }
1225         close(env->me_lfd);
1226         free(env);
1227 }
1228
1229 /* Search for key within a leaf page, using binary search.
1230  * Returns the smallest entry larger or equal to the key.
1231  * If exactp is non-null, stores whether the found entry was an exact match
1232  * in *exactp (1 or 0).
1233  * If kip is non-null, stores the index of the found entry in *kip.
1234  * If no entry larger or equal to the key is found, returns NULL.
1235  */
1236 static MDB_node *
1237 mdb_search_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, MDB_val *key,
1238     int *exactp, unsigned int *kip)
1239 {
1240         unsigned int     i = 0;
1241         int              low, high;
1242         int              rc = 0;
1243         MDB_node        *node;
1244         MDB_val  nodekey;
1245
1246         DPRINTF("searching %u keys in %s page %lu",
1247             NUMKEYS(mp),
1248             IS_LEAF(mp) ? "leaf" : "branch",
1249             mp->mp_pgno);
1250
1251         assert(NUMKEYS(mp) > 0);
1252
1253         memset(&nodekey, 0, sizeof(nodekey));
1254
1255         low = IS_LEAF(mp) ? 0 : 1;
1256         high = NUMKEYS(mp) - 1;
1257         while (low <= high) {
1258                 i = (low + high) >> 1;
1259                 node = NODEPTR(mp, i);
1260
1261                 nodekey.mv_size = node->mn_ksize;
1262                 nodekey.mv_data = NODEKEY(node);
1263
1264                 if (txn->mt_dbxs[dbi].md_cmp)
1265                         rc = txn->mt_dbxs[dbi].md_cmp(key, &nodekey);
1266                 else
1267                         rc = _mdb_cmp(txn, dbi, key, &nodekey);
1268
1269                 if (IS_LEAF(mp))
1270                         DPRINTF("found leaf index %u [%.*s], rc = %i",
1271                             i, (int)nodekey.mv_size, (char *)nodekey.mv_data, rc);
1272                 else
1273                         DPRINTF("found branch index %u [%.*s -> %lu], rc = %i",
1274                             i, (int)node->mn_ksize, (char *)NODEKEY(node),
1275                             node->mn_pgno, rc);
1276
1277                 if (rc == 0)
1278                         break;
1279                 if (rc > 0)
1280                         low = i + 1;
1281                 else
1282                         high = i - 1;
1283         }
1284
1285         if (rc > 0) {   /* Found entry is less than the key. */
1286                 i++;    /* Skip to get the smallest entry larger than key. */
1287                 if (i >= NUMKEYS(mp))
1288                         /* There is no entry larger or equal to the key. */
1289                         return NULL;
1290         }
1291         if (exactp)
1292                 *exactp = (rc == 0);
1293         if (kip)        /* Store the key index if requested. */
1294                 *kip = i;
1295
1296         return NODEPTR(mp, i);
1297 }
1298
1299 static void
1300 cursor_pop_page(MDB_cursor *cursor)
1301 {
1302         MDB_ppage       *top;
1303
1304         top = CURSOR_TOP(cursor);
1305         CURSOR_POP(cursor);
1306
1307         DPRINTF("popped page %lu off cursor %p", top->mp_page->mp_pgno, (void *) cursor);
1308
1309         free(top);
1310 }
1311
1312 static MDB_ppage *
1313 cursor_push_page(MDB_cursor *cursor, MDB_page *mp)
1314 {
1315         MDB_ppage       *ppage;
1316
1317         DPRINTF("pushing page %lu on cursor %p", mp->mp_pgno, (void *) cursor);
1318
1319         if ((ppage = calloc(1, sizeof(*ppage))) == NULL)
1320                 return NULL;
1321         ppage->mp_page = mp;
1322         CURSOR_PUSH(cursor, ppage);
1323         return ppage;
1324 }
1325
1326 static MDB_page *
1327 mdbenv_get_page(MDB_env *env, pgno_t pgno)
1328 {
1329         MDB_page *p = NULL;
1330         MDB_txn *txn = env->me_txn;
1331         int found = 0;
1332
1333         if (txn && !SIMPLEQ_EMPTY(txn->mt_u.dirty_queue)) {
1334                 MDB_dpage *dp;
1335                 SIMPLEQ_FOREACH(dp, txn->mt_u.dirty_queue, h.md_next) {
1336                         if (dp->p.mp_pgno == pgno) {
1337                                 p = &dp->p;
1338                                 found = 1;
1339                                 break;
1340                         }
1341                 }
1342         }
1343         if (!found) {
1344                 p = (MDB_page *)(env->me_map + env->me_meta.mm_psize * pgno);
1345         }
1346         return p;
1347 }
1348
1349 static int
1350 mdb_search_page_root(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1351     MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1352 {
1353         MDB_page        *mp = mpp->mp_page;
1354         int rc;
1355
1356         if (cursor && cursor_push_page(cursor, mp) == NULL)
1357                 return MDB_FAIL;
1358
1359         while (IS_BRANCH(mp)) {
1360                 unsigned int     i = 0;
1361                 MDB_node        *node;
1362
1363                 DPRINTF("branch page %lu has %u keys", mp->mp_pgno, NUMKEYS(mp));
1364                 assert(NUMKEYS(mp) > 1);
1365                 DPRINTF("found index 0 to page %lu", NODEPGNO(NODEPTR(mp, 0)));
1366
1367                 if (key == NULL)        /* Initialize cursor to first page. */
1368                         i = 0;
1369                 else {
1370                         int      exact;
1371                         node = mdb_search_node(txn, dbi, mp, key, &exact, &i);
1372                         if (node == NULL)
1373                                 i = NUMKEYS(mp) - 1;
1374                         else if (!exact) {
1375                                 assert(i > 0);
1376                                 i--;
1377                         }
1378                 }
1379
1380                 if (key)
1381                         DPRINTF("following index %u for key %.*s",
1382                             i, (int)key->mv_size, (char *)key->mv_data);
1383                 assert(i < NUMKEYS(mp));
1384                 node = NODEPTR(mp, i);
1385
1386                 if (cursor)
1387                         CURSOR_TOP(cursor)->mp_ki = i;
1388
1389                 mpp->mp_parent = mp;
1390                 if ((mp = mdbenv_get_page(txn->mt_env, NODEPGNO(node))) == NULL)
1391                         return MDB_FAIL;
1392                 mpp->mp_pi = i;
1393                 mpp->mp_page = mp;
1394
1395                 if (cursor && cursor_push_page(cursor, mp) == NULL)
1396                         return MDB_FAIL;
1397
1398                 if (modify) {
1399                         MDB_dhead *dh = ((MDB_dhead *)mp)-1;
1400                         if ((rc = mdb_touch(txn, mpp)) != 0)
1401                                 return rc;
1402                         dh = ((MDB_dhead *)mpp->mp_page)-1;
1403                         dh->md_parent = mpp->mp_parent;
1404                         dh->md_pi = mpp->mp_pi;
1405                 }
1406
1407                 mp = mpp->mp_page;
1408         }
1409
1410         if (!IS_LEAF(mp)) {
1411                 DPRINTF("internal error, index points to a %02X page!?",
1412                     mp->mp_flags);
1413                 return MDB_FAIL;
1414         }
1415
1416         DPRINTF("found leaf page %lu for key %.*s", mp->mp_pgno,
1417             key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL);
1418
1419         return MDB_SUCCESS;
1420 }
1421
1422 /* Search for the page a given key should be in.
1423  * Stores a pointer to the found page in *mpp.
1424  * If key is NULL, search for the lowest page (used by mdb_cursor_first).
1425  * If cursor is non-null, pushes parent pages on the cursor stack.
1426  * If modify is true, visited pages are updated with new page numbers.
1427  */
1428 static int
1429 mdb_search_page(MDB_txn *txn, MDB_dbi dbi, MDB_val *key,
1430     MDB_cursor *cursor, int modify, MDB_pageparent *mpp)
1431 {
1432         int              rc;
1433         pgno_t           root;
1434
1435         /* Choose which root page to start with. If a transaction is given
1436          * use the root page from the transaction, otherwise read the last
1437          * committed root page.
1438          */
1439         if (F_ISSET(txn->mt_flags, MDB_TXN_ERROR)) {
1440                 DPRINTF("transaction has failed, must abort");
1441                 return EINVAL;
1442         } else
1443                 root = txn->mt_root;
1444
1445         if (root == P_INVALID) {                /* Tree is empty. */
1446                 DPRINTF("tree is empty");
1447                 return ENOENT;
1448         }
1449
1450         if ((mpp->mp_page = mdbenv_get_page(txn->mt_env, root)) == NULL)
1451                 return MDB_FAIL;
1452
1453         DPRINTF("root page has flags 0x%X", mpp->mp_page->mp_flags);
1454
1455         if (modify && !F_ISSET(mpp->mp_page->mp_flags, P_DIRTY)) {
1456                 mpp->mp_parent = NULL;
1457                 mpp->mp_pi = 0;
1458                 if ((rc = mdb_touch(txn, mpp)))
1459                         return rc;
1460                 txn->mt_root = mpp->mp_page->mp_pgno;
1461         }
1462
1463         return mdb_search_page_root(txn, dbi, key, cursor, modify, mpp);
1464 }
1465
1466 static int
1467 mdb_read_data(MDB_env *env, MDB_node *leaf, MDB_val *data)
1468 {
1469         MDB_page        *omp;           /* overflow mpage */
1470         pgno_t           pgno;
1471
1472         if (!F_ISSET(leaf->mn_flags, F_BIGDATA)) {
1473                 data->mv_size = leaf->mn_dsize;
1474                 data->mv_data = NODEDATA(leaf);
1475                 return MDB_SUCCESS;
1476         }
1477
1478         /* Read overflow data.
1479          */
1480         data->mv_size = leaf->mn_dsize;
1481         memcpy(&pgno, NODEDATA(leaf), sizeof(pgno));
1482         if ((omp = mdbenv_get_page(env, pgno)) == NULL) {
1483                 DPRINTF("read overflow page %lu failed", pgno);
1484                 return MDB_FAIL;
1485         }
1486         data->mv_data = omp;
1487
1488         return MDB_SUCCESS;
1489 }
1490
1491 int
1492 mdb_get(MDB_txn *txn, MDB_dbi dbi,
1493     MDB_val *key, MDB_val *data)
1494 {
1495         int              rc, exact;
1496         MDB_node        *leaf;
1497         MDB_pageparent mpp;
1498
1499         assert(key);
1500         assert(data);
1501         DPRINTF("===> get key [%.*s]", (int)key->mv_size, (char *)key->mv_data);
1502
1503         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1504                 return EINVAL;
1505         }
1506
1507         if ((rc = mdb_search_page(txn, dbi, key, NULL, 0, &mpp)) != MDB_SUCCESS)
1508                 return rc;
1509
1510         leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, NULL);
1511         if (leaf && exact)
1512                 rc = mdb_read_data(txn->mt_env, leaf, data);
1513         else {
1514                 rc = ENOENT;
1515         }
1516
1517         return rc;
1518 }
1519
1520 static int
1521 mdb_sibling(MDB_cursor *cursor, int move_right)
1522 {
1523         int              rc;
1524         MDB_node        *indx;
1525         MDB_ppage       *parent, *top;
1526         MDB_page        *mp;
1527
1528         top = CURSOR_TOP(cursor);
1529         if ((parent = SLIST_NEXT(top, mp_entry)) == NULL) {
1530                 return ENOENT;          /* root has no siblings */
1531         }
1532
1533         DPRINTF("parent page is page %lu, index %u",
1534             parent->mp_page->mp_pgno, parent->mp_ki);
1535
1536         cursor_pop_page(cursor);
1537         if (move_right ? (parent->mp_ki + 1 >= NUMKEYS(parent->mp_page))
1538                        : (parent->mp_ki == 0)) {
1539                 DPRINTF("no more keys left, moving to %s sibling",
1540                     move_right ? "right" : "left");
1541                 if ((rc = mdb_sibling(cursor, move_right)) != MDB_SUCCESS)
1542                         return rc;
1543                 parent = CURSOR_TOP(cursor);
1544         } else {
1545                 if (move_right)
1546                         parent->mp_ki++;
1547                 else
1548                         parent->mp_ki--;
1549                 DPRINTF("just moving to %s index key %u",
1550                     move_right ? "right" : "left", parent->mp_ki);
1551         }
1552         assert(IS_BRANCH(parent->mp_page));
1553
1554         indx = NODEPTR(parent->mp_page, parent->mp_ki);
1555         if ((mp = mdbenv_get_page(cursor->mc_txn->mt_env, indx->mn_pgno)) == NULL)
1556                 return MDB_FAIL;
1557 #if 0
1558         mp->parent = parent->mp_page;
1559         mp->parent_index = parent->mp_ki;
1560 #endif
1561
1562         cursor_push_page(cursor, mp);
1563
1564         return MDB_SUCCESS;
1565 }
1566
1567 static int
1568 mdb_set_key(MDB_node *node, MDB_val *key)
1569 {
1570         if (key == NULL)
1571                 return 0;
1572
1573         key->mv_size = node->mn_ksize;
1574         key->mv_data = NODEKEY(node);
1575
1576         return 0;
1577 }
1578
1579 static int
1580 mdb_cursor_next(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1581 {
1582         MDB_ppage       *top;
1583         MDB_page        *mp;
1584         MDB_node        *leaf;
1585
1586         if (cursor->mc_eof) {
1587                 return ENOENT;
1588         }
1589
1590         assert(cursor->mc_initialized);
1591
1592         top = CURSOR_TOP(cursor);
1593         mp = top->mp_page;
1594
1595         DPRINTF("cursor_next: top page is %lu in cursor %p", mp->mp_pgno, (void *) cursor);
1596
1597         if (top->mp_ki + 1 >= NUMKEYS(mp)) {
1598                 DPRINTF("=====> move to next sibling page");
1599                 if (mdb_sibling(cursor, 1) != MDB_SUCCESS) {
1600                         cursor->mc_eof = 1;
1601                         return ENOENT;
1602                 }
1603                 top = CURSOR_TOP(cursor);
1604                 mp = top->mp_page;
1605                 DPRINTF("next page is %lu, key index %u", mp->mp_pgno, top->mp_ki);
1606         } else
1607                 top->mp_ki++;
1608
1609         DPRINTF("==> cursor points to page %lu with %u keys, key index %u",
1610             mp->mp_pgno, NUMKEYS(mp), top->mp_ki);
1611
1612         assert(IS_LEAF(mp));
1613         leaf = NODEPTR(mp, top->mp_ki);
1614
1615         if (data && mdb_read_data(cursor->mc_txn->mt_env, leaf, data) != MDB_SUCCESS)
1616                 return MDB_FAIL;
1617
1618         return mdb_set_key(leaf, key);
1619 }
1620
1621 static int
1622 mdb_cursor_set(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1623     int *exactp)
1624 {
1625         int              rc;
1626         MDB_node        *leaf;
1627         MDB_ppage       *top;
1628         MDB_pageparent mpp;
1629
1630         assert(cursor);
1631         assert(key);
1632         assert(key->mv_size > 0);
1633
1634         rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, key, cursor, 0, &mpp);
1635         if (rc != MDB_SUCCESS)
1636                 return rc;
1637         assert(IS_LEAF(mpp.mp_page));
1638
1639         top = CURSOR_TOP(cursor);
1640         leaf = mdb_search_node(cursor->mc_txn, cursor->mc_dbi, mpp.mp_page, key, exactp, &top->mp_ki);
1641         if (exactp != NULL && !*exactp) {
1642                 /* MDB_CURSOR_EXACT specified and not an exact match. */
1643                 return ENOENT;
1644         }
1645
1646         if (leaf == NULL) {
1647                 DPRINTF("===> inexact leaf not found, goto sibling");
1648                 if ((rc = mdb_sibling(cursor, 1)) != MDB_SUCCESS)
1649                         return rc;              /* no entries matched */
1650                 top = CURSOR_TOP(cursor);
1651                 top->mp_ki = 0;
1652                 mpp.mp_page = top->mp_page;
1653                 assert(IS_LEAF(mpp.mp_page));
1654                 leaf = NODEPTR(mpp.mp_page, 0);
1655         }
1656
1657         cursor->mc_initialized = 1;
1658         cursor->mc_eof = 0;
1659
1660         if (data && (rc = mdb_read_data(cursor->mc_txn->mt_env, leaf, data)) != MDB_SUCCESS)
1661                 return rc;
1662
1663         rc = mdb_set_key(leaf, key);
1664         if (rc == MDB_SUCCESS) {
1665                 DPRINTF("==> cursor placed on key %.*s",
1666                         (int)key->mv_size, (char *)key->mv_data);
1667                 ;
1668         }
1669
1670         return rc;
1671 }
1672
1673 static int
1674 mdb_cursor_first(MDB_cursor *cursor, MDB_val *key, MDB_val *data)
1675 {
1676         int              rc;
1677         MDB_pageparent  mpp;
1678         MDB_node        *leaf;
1679
1680         rc = mdb_search_page(cursor->mc_txn, cursor->mc_dbi, NULL, cursor, 0, &mpp);
1681         if (rc != MDB_SUCCESS)
1682                 return rc;
1683         assert(IS_LEAF(mpp.mp_page));
1684
1685         leaf = NODEPTR(mpp.mp_page, 0);
1686         cursor->mc_initialized = 1;
1687         cursor->mc_eof = 0;
1688
1689         if (data && (rc = mdb_read_data(cursor->mc_txn->mt_env, leaf, data)) != MDB_SUCCESS)
1690                 return rc;
1691
1692         return mdb_set_key(leaf, key);
1693 }
1694
1695 int
1696 mdb_cursor_get(MDB_cursor *cursor, MDB_val *key, MDB_val *data,
1697     MDB_cursor_op op)
1698 {
1699         int              rc;
1700         int              exact = 0;
1701
1702         assert(cursor);
1703
1704         switch (op) {
1705         case MDB_CURSOR:
1706         case MDB_CURSOR_EXACT:
1707                 while (CURSOR_TOP(cursor) != NULL)
1708                         cursor_pop_page(cursor);
1709                 if (key == NULL || key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
1710                         rc = EINVAL;
1711                 } else if (op == MDB_CURSOR_EXACT)
1712                         rc = mdb_cursor_set(cursor, key, data, &exact);
1713                 else
1714                         rc = mdb_cursor_set(cursor, key, data, NULL);
1715                 break;
1716         case MDB_NEXT:
1717                 if (!cursor->mc_initialized)
1718                         rc = mdb_cursor_first(cursor, key, data);
1719                 else
1720                         rc = mdb_cursor_next(cursor, key, data);
1721                 break;
1722         case MDB_FIRST:
1723                 while (CURSOR_TOP(cursor) != NULL)
1724                         cursor_pop_page(cursor);
1725                 rc = mdb_cursor_first(cursor, key, data);
1726                 break;
1727         default:
1728                 DPRINTF("unhandled/unimplemented cursor operation %u", op);
1729                 rc = EINVAL;
1730                 break;
1731         }
1732
1733         return rc;
1734 }
1735
1736 /* Allocate a page and initialize it
1737  */
1738 static MDB_dpage *
1739 mdb_new_page(MDB_txn *txn, MDB_dbi dbi, uint32_t flags, int num)
1740 {
1741         MDB_dpage       *dp;
1742
1743         if ((dp = mdb_alloc_page(txn, NULL, 0, num)) == NULL)
1744                 return NULL;
1745         DPRINTF("allocated new mpage %lu, page size %u",
1746             dp->p.mp_pgno, txn->mt_env->me_meta.mm_psize);
1747         dp->p.mp_flags = flags | P_DIRTY;
1748         dp->p.mp_lower = PAGEHDRSZ;
1749         dp->p.mp_upper = txn->mt_env->me_meta.mm_psize;
1750
1751         if (IS_BRANCH(&dp->p))
1752                 txn->mt_dbs[dbi]->md_branch_pages++;
1753         else if (IS_LEAF(&dp->p))
1754                 txn->mt_dbs[dbi]->md_leaf_pages++;
1755         else if (IS_OVERFLOW(&dp->p)) {
1756                 txn->mt_dbs[dbi]->md_overflow_pages += num;
1757                 dp->p.mp_pages = num;
1758         }
1759
1760         return dp;
1761 }
1762
1763 static size_t
1764 mdb_leaf_size(MDB_env *env, MDB_val *key, MDB_val *data)
1765 {
1766         size_t           sz;
1767
1768         sz = LEAFSIZE(key, data);
1769         if (data->mv_size >= env->me_meta.mm_psize / MDB_MINKEYS) {
1770                 /* put on overflow page */
1771                 sz -= data->mv_size - sizeof(pgno_t);
1772         }
1773
1774         return sz + sizeof(indx_t);
1775 }
1776
1777 static size_t
1778 mdb_branch_size(MDB_env *env, MDB_val *key)
1779 {
1780         size_t           sz;
1781
1782         sz = INDXSIZE(key);
1783         if (sz >= env->me_meta.mm_psize / MDB_MINKEYS) {
1784                 /* put on overflow page */
1785                 /* not implemented */
1786                 /* sz -= key->size - sizeof(pgno_t); */
1787         }
1788
1789         return sz + sizeof(indx_t);
1790 }
1791
1792 static int
1793 mdb_add_node(MDB_txn *txn, MDB_dbi dbi, MDB_page *mp, indx_t indx,
1794     MDB_val *key, MDB_val *data, pgno_t pgno, uint8_t flags)
1795 {
1796         unsigned int     i;
1797         size_t           node_size = NODESIZE;
1798         indx_t           ofs;
1799         MDB_node        *node;
1800         MDB_dpage       *ofp = NULL;            /* overflow page */
1801
1802         assert(mp->mp_upper >= mp->mp_lower);
1803
1804         DPRINTF("add node [%.*s] to %s page %lu at index %i, key size %zu",
1805             key ? (int)key->mv_size : 0, key ? (char *)key->mv_data : NULL,
1806             IS_LEAF(mp) ? "leaf" : "branch",
1807             mp->mp_pgno, indx, key ? key->mv_size : 0);
1808
1809         if (key != NULL)
1810                 node_size += key->mv_size;
1811
1812         if (IS_LEAF(mp)) {
1813                 assert(data);
1814                 if (F_ISSET(flags, F_BIGDATA)) {
1815                         /* Data already on overflow page. */
1816                         node_size += sizeof(pgno_t);
1817                 } else if (data->mv_size >= txn->mt_env->me_meta.mm_psize / MDB_MINKEYS) {
1818                         int ovpages = OVPAGES(data->mv_size, txn->mt_env->me_meta.mm_psize);
1819                         /* Put data on overflow page. */
1820                         DPRINTF("data size is %zu, put on overflow page",
1821                             data->mv_size);
1822                         node_size += sizeof(pgno_t);
1823                         if ((ofp = mdb_new_page(txn, dbi, P_OVERFLOW, ovpages)) == NULL)
1824                                 return MDB_FAIL;
1825                         DPRINTF("allocated overflow page %lu", ofp->p.mp_pgno);
1826                         flags |= F_BIGDATA;
1827                 } else {
1828                         node_size += data->mv_size;
1829                 }
1830         }
1831
1832         if (node_size + sizeof(indx_t) > SIZELEFT(mp)) {
1833                 DPRINTF("not enough room in page %lu, got %u ptrs",
1834                     mp->mp_pgno, NUMKEYS(mp));
1835                 DPRINTF("upper - lower = %u - %u = %u", mp->mp_upper, mp->mp_lower,
1836                     mp->mp_upper - mp->mp_lower);
1837                 DPRINTF("node size = %zu", node_size);
1838                 return ENOSPC;
1839         }
1840
1841         /* Move higher pointers up one slot. */
1842         for (i = NUMKEYS(mp); i > indx; i--)
1843                 mp->mp_ptrs[i] = mp->mp_ptrs[i - 1];
1844
1845         /* Adjust free space offsets. */
1846         ofs = mp->mp_upper - node_size;
1847         assert(ofs >= mp->mp_lower + sizeof(indx_t));
1848         mp->mp_ptrs[indx] = ofs;
1849         mp->mp_upper = ofs;
1850         mp->mp_lower += sizeof(indx_t);
1851
1852         /* Write the node data. */
1853         node = NODEPTR(mp, indx);
1854         node->mn_ksize = (key == NULL) ? 0 : key->mv_size;
1855         node->mn_flags = flags;
1856         if (IS_LEAF(mp))
1857                 node->mn_dsize = data->mv_size;
1858         else
1859                 node->mn_pgno = pgno;
1860
1861         if (key)
1862                 memcpy(NODEKEY(node), key->mv_data, key->mv_size);
1863
1864         if (IS_LEAF(mp)) {
1865                 assert(key);
1866                 if (ofp == NULL) {
1867                         if (F_ISSET(flags, F_BIGDATA))
1868                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
1869                                     sizeof(pgno_t));
1870                         else
1871                                 memcpy(node->mn_data + key->mv_size, data->mv_data,
1872                                     data->mv_size);
1873                 } else {
1874                         memcpy(node->mn_data + key->mv_size, &ofp->p.mp_pgno,
1875                             sizeof(pgno_t));
1876                         memcpy(METADATA(&ofp->p), data->mv_data, data->mv_size);
1877                 }
1878         }
1879
1880         return MDB_SUCCESS;
1881 }
1882
1883 static void
1884 mdb_del_node(MDB_page *mp, indx_t indx)
1885 {
1886         unsigned int     sz;
1887         indx_t           i, j, numkeys, ptr;
1888         MDB_node        *node;
1889         char            *base;
1890
1891         DPRINTF("delete node %u on %s page %lu", indx,
1892             IS_LEAF(mp) ? "leaf" : "branch", mp->mp_pgno);
1893         assert(indx < NUMKEYS(mp));
1894
1895         node = NODEPTR(mp, indx);
1896         sz = NODESIZE + node->mn_ksize;
1897         if (IS_LEAF(mp)) {
1898                 if (F_ISSET(node->mn_flags, F_BIGDATA))
1899                         sz += sizeof(pgno_t);
1900                 else
1901                         sz += NODEDSZ(node);
1902         }
1903
1904         ptr = mp->mp_ptrs[indx];
1905         numkeys = NUMKEYS(mp);
1906         for (i = j = 0; i < numkeys; i++) {
1907                 if (i != indx) {
1908                         mp->mp_ptrs[j] = mp->mp_ptrs[i];
1909                         if (mp->mp_ptrs[i] < ptr)
1910                                 mp->mp_ptrs[j] += sz;
1911                         j++;
1912                 }
1913         }
1914
1915         base = (char *)mp + mp->mp_upper;
1916         memmove(base + sz, base, ptr - mp->mp_upper);
1917
1918         mp->mp_lower -= sizeof(indx_t);
1919         mp->mp_upper += sz;
1920 }
1921
1922 int
1923 mdb_cursor_open(MDB_txn *txn, MDB_dbi dbi, MDB_cursor **ret)
1924 {
1925         MDB_cursor      *cursor;
1926
1927         if (txn == NULL || ret == NULL)
1928                 return EINVAL;
1929
1930         if ((cursor = calloc(1, sizeof(*cursor))) != NULL) {
1931                 SLIST_INIT(&cursor->mc_stack);
1932                 cursor->mc_dbi = dbi;
1933                 cursor->mc_txn = txn;
1934         }
1935
1936         *ret = cursor;
1937
1938         return MDB_SUCCESS;
1939 }
1940
1941 void
1942 mdb_cursor_close(MDB_cursor *cursor)
1943 {
1944         if (cursor != NULL) {
1945                 while (!CURSOR_EMPTY(cursor))
1946                         cursor_pop_page(cursor);
1947
1948 /*              btree_close(cursor->bt); */
1949                 free(cursor);
1950         }
1951 }
1952
1953 static int
1954 mdb_update_key(MDB_page *mp, indx_t indx, MDB_val *key)
1955 {
1956         indx_t                   ptr, i, numkeys;
1957         int                      delta;
1958         size_t                   len;
1959         MDB_node                *node;
1960         char                    *base;
1961
1962         node = NODEPTR(mp, indx);
1963         ptr = mp->mp_ptrs[indx];
1964         DPRINTF("update key %u (ofs %u) [%.*s] to [%.*s] on page %lu",
1965             indx, ptr,
1966             (int)node->mn_ksize, (char *)NODEKEY(node),
1967             (int)key->mv_size, (char *)key->mv_data,
1968             mp->mp_pgno);
1969
1970         delta = key->mv_size - node->mn_ksize;
1971         if (delta) {
1972                 if (delta > 0 && SIZELEFT(mp) < delta) {
1973                         DPRINTF("OUCH! Not enough room, delta = %d", delta);
1974                         return ENOSPC;
1975                 }
1976
1977                 numkeys = NUMKEYS(mp);
1978                 for (i = 0; i < numkeys; i++) {
1979                         if (mp->mp_ptrs[i] <= ptr)
1980                                 mp->mp_ptrs[i] -= delta;
1981                 }
1982
1983                 base = (char *)mp + mp->mp_upper;
1984                 len = ptr - mp->mp_upper + NODESIZE;
1985                 memmove(base - delta, base, len);
1986                 mp->mp_upper -= delta;
1987
1988                 node = NODEPTR(mp, indx);
1989                 node->mn_ksize = key->mv_size;
1990         }
1991
1992         memcpy(NODEKEY(node), key->mv_data, key->mv_size);
1993
1994         return MDB_SUCCESS;
1995 }
1996
1997 /* Move a node from src to dst.
1998  */
1999 static int
2000 mdb_move_node(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, indx_t srcindx,
2001     MDB_pageparent *dst, indx_t dstindx)
2002 {
2003         int                      rc;
2004         MDB_node                *srcnode;
2005         MDB_val          key, data;
2006
2007         srcnode = NODEPTR(src->mp_page, srcindx);
2008         DPRINTF("moving %s node %u [%.*s] on page %lu to node %u on page %lu",
2009             IS_LEAF(src->mp_page) ? "leaf" : "branch",
2010             srcindx,
2011             (int)srcnode->mn_ksize, (char *)NODEKEY(srcnode),
2012             src->mp_page->mp_pgno,
2013             dstindx, dst->mp_page->mp_pgno);
2014
2015         /* Mark src and dst as dirty. */
2016         if ((rc = mdb_touch(txn, src)) ||
2017             (rc = mdb_touch(txn, dst)))
2018                 return rc;;
2019
2020         /* Add the node to the destination page.
2021          */
2022         key.mv_size = srcnode->mn_ksize;
2023         key.mv_data = NODEKEY(srcnode);
2024         data.mv_size = NODEDSZ(srcnode);
2025         data.mv_data = NODEDATA(srcnode);
2026         rc = mdb_add_node(txn, dbi, dst->mp_page, dstindx, &key, &data, NODEPGNO(srcnode),
2027             srcnode->mn_flags);
2028         if (rc != MDB_SUCCESS)
2029                 return rc;
2030
2031         /* Delete the node from the source page.
2032          */
2033         mdb_del_node(src->mp_page, srcindx);
2034
2035         /* Update the parent separators.
2036          */
2037         if (srcindx == 0 && src->mp_pi != 0) {
2038                 DPRINTF("update separator for source page %lu to [%.*s]",
2039                     src->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2040                 if ((rc = mdb_update_key(src->mp_parent, src->mp_pi,
2041                     &key)) != MDB_SUCCESS)
2042                         return rc;
2043         }
2044
2045         if (srcindx == 0 && IS_BRANCH(src->mp_page)) {
2046                 MDB_val  nullkey;
2047                 nullkey.mv_size = 0;
2048                 assert(mdb_update_key(src->mp_page, 0, &nullkey) == MDB_SUCCESS);
2049         }
2050
2051         if (dstindx == 0 && dst->mp_pi != 0) {
2052                 DPRINTF("update separator for destination page %lu to [%.*s]",
2053                     dst->mp_page->mp_pgno, (int)key.mv_size, (char *)key.mv_data);
2054                 if ((rc = mdb_update_key(dst->mp_parent, dst->mp_pi,
2055                     &key)) != MDB_SUCCESS)
2056                         return rc;
2057         }
2058
2059         if (dstindx == 0 && IS_BRANCH(dst->mp_page)) {
2060                 MDB_val  nullkey;
2061                 nullkey.mv_size = 0;
2062                 assert(mdb_update_key(dst->mp_page, 0, &nullkey) == MDB_SUCCESS);
2063         }
2064
2065         return MDB_SUCCESS;
2066 }
2067
2068 static int
2069 mdb_merge(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *src, MDB_pageparent *dst)
2070 {
2071         int                      rc;
2072         indx_t                   i;
2073         MDB_node                *srcnode;
2074         MDB_val          key, data;
2075         MDB_pageparent  mpp;
2076         MDB_dhead *dh;
2077
2078         DPRINTF("merging page %lu and %lu", src->mp_page->mp_pgno, dst->mp_page->mp_pgno);
2079
2080         assert(txn != NULL);
2081         assert(src->mp_parent); /* can't merge root page */
2082         assert(dst->mp_parent);
2083
2084         /* Mark src and dst as dirty. */
2085         if ((rc = mdb_touch(txn, src)) ||
2086             (rc = mdb_touch(txn, dst)))
2087                 return rc;
2088
2089         /* Move all nodes from src to dst.
2090          */
2091         for (i = 0; i < NUMKEYS(src->mp_page); i++) {
2092                 srcnode = NODEPTR(src->mp_page, i);
2093
2094                 key.mv_size = srcnode->mn_ksize;
2095                 key.mv_data = NODEKEY(srcnode);
2096                 data.mv_size = NODEDSZ(srcnode);
2097                 data.mv_data = NODEDATA(srcnode);
2098                 rc = mdb_add_node(txn, dbi, dst->mp_page, NUMKEYS(dst->mp_page), &key,
2099                     &data, NODEPGNO(srcnode), srcnode->mn_flags);
2100                 if (rc != MDB_SUCCESS)
2101                         return rc;
2102         }
2103
2104         DPRINTF("dst page %lu now has %u keys (%.1f%% filled)",
2105             dst->mp_page->mp_pgno, NUMKEYS(dst->mp_page), (float)PAGEFILL(txn->mt_env, dst->mp_page) / 10);
2106
2107         /* Unlink the src page from parent.
2108          */
2109         mdb_del_node(src->mp_parent, src->mp_pi);
2110         if (src->mp_pi == 0) {
2111                 key.mv_size = 0;
2112                 if ((rc = mdb_update_key(src->mp_parent, 0, &key)) != MDB_SUCCESS)
2113                         return rc;
2114         }
2115
2116         if (IS_LEAF(src->mp_page))
2117                 txn->mt_dbs[dbi]->md_leaf_pages--;
2118         else
2119                 txn->mt_dbs[dbi]->md_branch_pages--;
2120
2121         mpp.mp_page = src->mp_parent;
2122         dh = (MDB_dhead *)src->mp_parent;
2123         dh--;
2124         mpp.mp_parent = dh->md_parent;
2125         mpp.mp_pi = dh->md_pi;
2126
2127         return mdb_rebalance(txn, dbi, &mpp);
2128 }
2129
2130 #define FILL_THRESHOLD   250
2131
2132 static int
2133 mdb_rebalance(MDB_txn *txn, MDB_dbi dbi, MDB_pageparent *mpp)
2134 {
2135         MDB_node        *node;
2136         MDB_page        *root;
2137         MDB_pageparent npp;
2138         indx_t           si = 0, di = 0;
2139
2140         assert(txn != NULL);
2141         assert(mpp != NULL);
2142
2143         DPRINTF("rebalancing %s page %lu (has %u keys, %.1f%% full)",
2144             IS_LEAF(mpp->mp_page) ? "leaf" : "branch",
2145             mpp->mp_page->mp_pgno, NUMKEYS(mpp->mp_page), (float)PAGEFILL(txn->mt_env, mpp->mp_page) / 10);
2146
2147         if (PAGEFILL(txn->mt_env, mpp->mp_page) >= FILL_THRESHOLD) {
2148                 DPRINTF("no need to rebalance page %lu, above fill threshold",
2149                     mpp->mp_page->mp_pgno);
2150                 return MDB_SUCCESS;
2151         }
2152
2153         if (mpp->mp_parent == NULL) {
2154                 if (NUMKEYS(mpp->mp_page) == 0) {
2155                         DPRINTF("tree is completely empty");
2156                         txn->mt_dbs[dbi]->md_root = P_INVALID;
2157                         txn->mt_dbs[dbi]->md_depth--;
2158                         txn->mt_dbs[dbi]->md_leaf_pages--;
2159                 } else if (IS_BRANCH(mpp->mp_page) && NUMKEYS(mpp->mp_page) == 1) {
2160                         DPRINTF("collapsing root page!");
2161                         txn->mt_dbs[dbi]->md_root = NODEPGNO(NODEPTR(mpp->mp_page, 0));
2162                         if ((root = mdbenv_get_page(txn->mt_env, txn->mt_dbs[dbi]->md_root)) == NULL)
2163                                 return MDB_FAIL;
2164                         txn->mt_dbs[dbi]->md_depth--;
2165                         txn->mt_dbs[dbi]->md_branch_pages--;
2166                 } else
2167                         DPRINTF("root page doesn't need rebalancing");
2168                 return MDB_SUCCESS;
2169         }
2170
2171         /* The parent (branch page) must have at least 2 pointers,
2172          * otherwise the tree is invalid.
2173          */
2174         assert(NUMKEYS(mpp->mp_parent) > 1);
2175
2176         /* Leaf page fill factor is below the threshold.
2177          * Try to move keys from left or right neighbor, or
2178          * merge with a neighbor page.
2179          */
2180
2181         /* Find neighbors.
2182          */
2183         if (mpp->mp_pi == 0) {
2184                 /* We're the leftmost leaf in our parent.
2185                  */
2186                 DPRINTF("reading right neighbor");
2187                 node = NODEPTR(mpp->mp_parent, mpp->mp_pi + 1);
2188                 if ((npp.mp_page = mdbenv_get_page(txn->mt_env, NODEPGNO(node))) == NULL)
2189                         return MDB_FAIL;
2190                 npp.mp_pi = mpp->mp_pi + 1;
2191                 si = 0;
2192                 di = NUMKEYS(mpp->mp_page);
2193         } else {
2194                 /* There is at least one neighbor to the left.
2195                  */
2196                 DPRINTF("reading left neighbor");
2197                 node = NODEPTR(mpp->mp_parent, mpp->mp_pi - 1);
2198                 if ((npp.mp_page = mdbenv_get_page(txn->mt_env, NODEPGNO(node))) == NULL)
2199                         return MDB_FAIL;
2200                 npp.mp_pi = mpp->mp_pi - 1;
2201                 si = NUMKEYS(npp.mp_page) - 1;
2202                 di = 0;
2203         }
2204         npp.mp_parent = mpp->mp_parent;
2205
2206         DPRINTF("found neighbor page %lu (%u keys, %.1f%% full)",
2207             npp.mp_page->mp_pgno, NUMKEYS(npp.mp_page), (float)PAGEFILL(txn->mt_env, npp.mp_page) / 10);
2208
2209         /* If the neighbor page is above threshold and has at least two
2210          * keys, move one key from it.
2211          *
2212          * Otherwise we should try to merge them.
2213          */
2214         if (PAGEFILL(txn->mt_env, npp.mp_page) >= FILL_THRESHOLD && NUMKEYS(npp.mp_page) >= 2)
2215                 return mdb_move_node(txn, dbi, &npp, si, mpp, di);
2216         else { /* FIXME: if (has_enough_room()) */
2217                 if (mpp->mp_pi == 0)
2218                         return mdb_merge(txn, dbi, &npp, mpp);
2219                 else
2220                         return mdb_merge(txn, dbi, mpp, &npp);
2221         }
2222 }
2223
2224 int
2225 mdb_del(MDB_txn *txn, MDB_dbi dbi,
2226     MDB_val *key, MDB_val *data)
2227 {
2228         int              rc, exact;
2229         unsigned int     ki;
2230         MDB_node        *leaf;
2231         MDB_pageparent  mpp;
2232
2233         DPRINTF("========> delete key %.*s", (int)key->mv_size, (char *)key->mv_data);
2234
2235         assert(key != NULL);
2236
2237         if (txn == NULL || dbi >= txn->mt_numdbs)
2238                 return EINVAL;
2239
2240         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2241                 return EINVAL;
2242         }
2243
2244         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2245                 return EINVAL;
2246         }
2247
2248         if ((rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp)) != MDB_SUCCESS)
2249                 return rc;
2250
2251         leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2252         if (leaf == NULL || !exact) {
2253                 return ENOENT;
2254         }
2255
2256         if (data && (rc = mdb_read_data(txn->mt_env, leaf, data)) != MDB_SUCCESS)
2257                 return rc;
2258
2259         mdb_del_node(mpp.mp_page, ki);
2260         /* add overflow pages to free list */
2261         if (F_ISSET(leaf->mn_flags, F_BIGDATA)) {
2262                 int i, ovpages;
2263                 pgno_t pg;
2264
2265                 memcpy(&pg, NODEDATA(leaf), sizeof(pg));
2266                 ovpages = OVPAGES(NODEDSZ(leaf), txn->mt_env->me_meta.mm_psize);
2267                 for (i=0; i<ovpages; i++) {
2268                         mdb_idl_insert(txn->mt_free_pgs, pg);
2269                         pg++;
2270                 }
2271         }
2272         txn->mt_dbs[dbi]->md_entries--;
2273         rc = mdb_rebalance(txn, dbi, &mpp);
2274         if (rc != MDB_SUCCESS)
2275                 txn->mt_flags |= MDB_TXN_ERROR;
2276
2277         return rc;
2278 }
2279
2280 /* Split page <*mpp>, and insert <key,(data|newpgno)> in either left or
2281  * right sibling, at index <*newindxp> (as if unsplit). Updates *mpp and
2282  * *newindxp with the actual values after split, ie if *mpp and *newindxp
2283  * refer to a node in the new right sibling page.
2284  */
2285 static int
2286 mdb_split(MDB_txn *txn, MDB_dbi dbi, MDB_page **mpp, unsigned int *newindxp,
2287     MDB_val *newkey, MDB_val *newdata, pgno_t newpgno)
2288 {
2289         uint8_t          flags;
2290         int              rc = MDB_SUCCESS, ins_new = 0;
2291         indx_t           newindx;
2292         pgno_t           pgno = 0;
2293         unsigned int     i, j, split_indx;
2294         MDB_node        *node;
2295         MDB_val  sepkey, rkey, rdata;
2296         MDB_page        *copy;
2297         MDB_dpage       *mdp, *rdp, *pdp;
2298         MDB_dhead *dh;
2299
2300         assert(txn != NULL);
2301
2302         dh = ((MDB_dhead *)*mpp) - 1;
2303         mdp = (MDB_dpage *)dh;
2304         newindx = *newindxp;
2305
2306         DPRINTF("-----> splitting %s page %lu and adding [%.*s] at index %i",
2307             IS_LEAF(&mdp->p) ? "leaf" : "branch", mdp->p.mp_pgno,
2308             (int)newkey->mv_size, (char *)newkey->mv_data, *newindxp);
2309
2310         if (mdp->h.md_parent == NULL) {
2311                 if ((pdp = mdb_new_page(txn, dbi, P_BRANCH, 1)) == NULL)
2312                         return MDB_FAIL;
2313                 mdp->h.md_pi = 0;
2314                 mdp->h.md_parent = &pdp->p;
2315                 txn->mt_dbs[dbi]->md_root = pdp->p.mp_pgno;
2316                 if (!dbi)
2317                         txn->mt_root = pdp->p.mp_pgno;
2318                 DPRINTF("root split! new root = %lu", pdp->p.mp_pgno);
2319                 txn->mt_dbs[dbi]->md_depth++;
2320
2321                 /* Add left (implicit) pointer. */
2322                 if (mdb_add_node(txn, dbi, &pdp->p, 0, NULL, NULL,
2323                     mdp->p.mp_pgno, 0) != MDB_SUCCESS)
2324                         return MDB_FAIL;
2325         } else {
2326                 DPRINTF("parent branch page is %lu", mdp->h.md_parent->mp_pgno);
2327         }
2328
2329         /* Create a right sibling. */
2330         if ((rdp = mdb_new_page(txn, dbi, mdp->p.mp_flags, 1)) == NULL)
2331                 return MDB_FAIL;
2332         rdp->h.md_parent = mdp->h.md_parent;
2333         rdp->h.md_pi = mdp->h.md_pi + 1;
2334         DPRINTF("new right sibling: page %lu", rdp->p.mp_pgno);
2335
2336         /* Move half of the keys to the right sibling. */
2337         if ((copy = malloc(txn->mt_env->me_meta.mm_psize)) == NULL)
2338                 return MDB_FAIL;
2339         memcpy(copy, &mdp->p, txn->mt_env->me_meta.mm_psize);
2340         memset(&mdp->p.mp_ptrs, 0, txn->mt_env->me_meta.mm_psize - PAGEHDRSZ);
2341         mdp->p.mp_lower = PAGEHDRSZ;
2342         mdp->p.mp_upper = txn->mt_env->me_meta.mm_psize;
2343
2344         split_indx = NUMKEYS(copy) / 2 + 1;
2345
2346         /* First find the separating key between the split pages.
2347          */
2348         memset(&sepkey, 0, sizeof(sepkey));
2349         if (newindx == split_indx) {
2350                 sepkey.mv_size = newkey->mv_size;
2351                 sepkey.mv_data = newkey->mv_data;
2352         } else {
2353                 node = NODEPTR(copy, split_indx);
2354                 sepkey.mv_size = node->mn_ksize;
2355                 sepkey.mv_data = NODEKEY(node);
2356         }
2357
2358         DPRINTF("separator is [%.*s]", (int)sepkey.mv_size, (char *)sepkey.mv_data);
2359
2360         /* Copy separator key to the parent.
2361          */
2362         if (SIZELEFT(rdp->h.md_parent) < mdb_branch_size(txn->mt_env, &sepkey)) {
2363                 rc = mdb_split(txn, dbi, &rdp->h.md_parent, &rdp->h.md_pi,
2364                     &sepkey, NULL, rdp->p.mp_pgno);
2365
2366                 /* Right page might now have changed parent.
2367                  * Check if left page also changed parent.
2368                  */
2369                 if (rdp->h.md_parent != mdp->h.md_parent &&
2370                     mdp->h.md_pi >= NUMKEYS(mdp->h.md_parent)) {
2371                         mdp->h.md_parent = rdp->h.md_parent;
2372                         mdp->h.md_pi = rdp->h.md_pi - 1;
2373                 }
2374         } else {
2375                 rc = mdb_add_node(txn, dbi, rdp->h.md_parent, rdp->h.md_pi,
2376                     &sepkey, NULL, rdp->p.mp_pgno, 0);
2377         }
2378         if (rc != MDB_SUCCESS) {
2379                 free(copy);
2380                 return MDB_FAIL;
2381         }
2382
2383         for (i = j = 0; i <= NUMKEYS(copy); j++) {
2384                 if (i < split_indx) {
2385                         /* Re-insert in left sibling. */
2386                         pdp = mdp;
2387                 } else {
2388                         /* Insert in right sibling. */
2389                         if (i == split_indx)
2390                                 /* Reset insert index for right sibling. */
2391                                 j = (i == newindx && ins_new);
2392                         pdp = rdp;
2393                 }
2394
2395                 if (i == newindx && !ins_new) {
2396                         /* Insert the original entry that caused the split. */
2397                         rkey.mv_data = newkey->mv_data;
2398                         rkey.mv_size = newkey->mv_size;
2399                         if (IS_LEAF(&mdp->p)) {
2400                                 rdata.mv_data = newdata->mv_data;
2401                                 rdata.mv_size = newdata->mv_size;
2402                         } else
2403                                 pgno = newpgno;
2404                         flags = 0;
2405
2406                         ins_new = 1;
2407
2408                         /* Update page and index for the new key. */
2409                         *newindxp = j;
2410                         *mpp = &pdp->p;
2411                 } else if (i == NUMKEYS(copy)) {
2412                         break;
2413                 } else {
2414                         node = NODEPTR(copy, i);
2415                         rkey.mv_data = NODEKEY(node);
2416                         rkey.mv_size = node->mn_ksize;
2417                         if (IS_LEAF(&mdp->p)) {
2418                                 rdata.mv_data = NODEDATA(node);
2419                                 rdata.mv_size = node->mn_dsize;
2420                         } else
2421                                 pgno = node->mn_pgno;
2422                         flags = node->mn_flags;
2423
2424                         i++;
2425                 }
2426
2427                 if (!IS_LEAF(&mdp->p) && j == 0) {
2428                         /* First branch index doesn't need key data. */
2429                         rkey.mv_size = 0;
2430                 }
2431
2432                 rc = mdb_add_node(txn, dbi, &pdp->p, j, &rkey, &rdata, pgno,flags);
2433         }
2434
2435         free(copy);
2436         return rc;
2437 }
2438
2439 int
2440 mdb_put(MDB_txn *txn, MDB_dbi dbi,
2441     MDB_val *key, MDB_val *data, unsigned int flags)
2442 {
2443         int              rc = MDB_SUCCESS, exact;
2444         unsigned int     ki;
2445         MDB_node        *leaf;
2446         MDB_pageparent  mpp;
2447
2448         assert(key != NULL);
2449         assert(data != NULL);
2450
2451         if (txn == NULL)
2452                 return EINVAL;
2453
2454         if (F_ISSET(txn->mt_flags, MDB_TXN_RDONLY)) {
2455                 return EINVAL;
2456         }
2457
2458         if (txn->mt_env->me_txn != txn) {
2459                 return EINVAL;
2460         }
2461
2462         if (key->mv_size == 0 || key->mv_size > MAXKEYSIZE) {
2463                 return EINVAL;
2464         }
2465
2466         DPRINTF("==> put key %.*s, size %zu, data size %zu",
2467                 (int)key->mv_size, (char *)key->mv_data, key->mv_size, data->mv_size);
2468
2469         rc = mdb_search_page(txn, dbi, key, NULL, 1, &mpp);
2470         if (rc == MDB_SUCCESS) {
2471                 leaf = mdb_search_node(txn, dbi, mpp.mp_page, key, &exact, &ki);
2472                 if (leaf && exact) {
2473                         if (F_ISSET(flags, MDB_NOOVERWRITE)) {
2474                                 DPRINTF("duplicate key %.*s",
2475                                     (int)key->mv_size, (char *)key->mv_data);
2476                                 return EEXIST;
2477                         }
2478                         mdb_del_node(mpp.mp_page, ki);
2479                 }
2480                 if (leaf == NULL) {             /* append if not found */
2481                         ki = NUMKEYS(mpp.mp_page);
2482                         DPRINTF("appending key at index %i", ki);
2483                 }
2484         } else if (rc == ENOENT) {
2485                 MDB_dpage *dp;
2486                 /* new file, just write a root leaf page */
2487                 DPRINTF("allocating new root leaf page");
2488                 if ((dp = mdb_new_page(txn, dbi, P_LEAF, 1)) == NULL) {
2489                         return ENOMEM;
2490                 }
2491                 mpp.mp_page = &dp->p;
2492                 txn->mt_dbs[dbi]->md_root = mpp.mp_page->mp_pgno;
2493                 if (!dbi)
2494                         txn->mt_root = mpp.mp_page->mp_pgno;
2495                 txn->mt_dbs[dbi]->md_depth++;
2496                 ki = 0;
2497         }
2498         else
2499                 goto done;
2500
2501         assert(IS_LEAF(mpp.mp_page));
2502         DPRINTF("there are %u keys, should insert new key at index %i",
2503                 NUMKEYS(mpp.mp_page), ki);
2504
2505         if (SIZELEFT(mpp.mp_page) < mdb_leaf_size(txn->mt_env, key, data)) {
2506                 rc = mdb_split(txn, dbi, &mpp.mp_page, &ki, key, data, P_INVALID);
2507         } else {
2508                 /* There is room already in this leaf page. */
2509                 rc = mdb_add_node(txn, dbi, mpp.mp_page, ki, key, data, 0, 0);
2510         }
2511
2512         if (rc != MDB_SUCCESS)
2513                 txn->mt_flags |= MDB_TXN_ERROR;
2514         else
2515                 txn->mt_dbs[dbi]->md_entries++;
2516
2517 done:
2518         return rc;
2519 }
2520
2521 int
2522 mdbenv_get_flags(MDB_env *env, unsigned int *arg)
2523 {
2524         if (!env || !arg)
2525                 return EINVAL;
2526
2527         *arg = env->me_flags;
2528         return MDB_SUCCESS;
2529 }
2530
2531 int
2532 mdbenv_get_path(MDB_env *env, const char **arg)
2533 {
2534         if (!env || !arg)
2535                 return EINVAL;
2536
2537         *arg = env->me_path;
2538         return MDB_SUCCESS;
2539 }
2540
2541 int
2542 mdbenv_stat(MDB_env *env, MDB_stat *arg)
2543 {
2544         if (env == NULL || arg == NULL)
2545                 return EINVAL;
2546
2547         arg->ms_psize = env->me_meta.mm_psize;
2548         arg->ms_depth = env->me_meta.mm_depth;
2549         arg->ms_branch_pages = env->me_meta.mm_branch_pages;
2550         arg->ms_leaf_pages = env->me_meta.mm_leaf_pages;
2551         arg->ms_overflow_pages = env->me_meta.mm_overflow_pages;
2552         arg->ms_entries = env->me_meta.mm_entries;
2553
2554         return MDB_SUCCESS;
2555 }
2556
2557 int mdb_open(MDB_txn *txn, const char *name, unsigned int flags, MDB_dbi *dbi)
2558 {
2559         MDB_val key, data;
2560         MDB_dbi i;
2561         int rc;
2562
2563         /* main DB? */
2564         if (!name) {
2565                 *dbi = 0;
2566                 return MDB_SUCCESS;
2567         }
2568
2569         /* Is the DB already open? */
2570         for (i=0; i<txn->mt_numdbs; i++) {
2571                 if (!strcmp(name, txn->mt_dbxs[i].md_name)) {
2572                         *dbi = i;
2573                         return MDB_SUCCESS;
2574                 }
2575         }
2576
2577         /* Find the DB info */
2578         key.mv_size = strlen(name);
2579         key.mv_data = (void *)name;
2580         rc = mdb_get(txn, 0, &key, &data);
2581
2582         /* Create if requested */
2583         if (rc == ENOENT && (flags & MDB_CREATE)) {
2584                 MDB_db dummy;
2585                 data.mv_size = sizeof(MDB_db);
2586                 data.mv_data = &dummy;
2587                 memset(&dummy, 0, sizeof(dummy));
2588                 dummy.md_root = P_INVALID;
2589                 rc = mdb_put(txn, 0, &key, &data, 0);
2590                 if (rc == MDB_SUCCESS)
2591                         rc = mdb_get(txn, 0, &key, &data);
2592         }
2593
2594         /* OK, got info, add to table */
2595         if (rc == MDB_SUCCESS) {
2596                 /* Is there a free slot? */
2597                 if ((txn->mt_numdbs & (DBX_CHUNK-1)) == 0) {
2598                         MDB_dbx *p1;
2599                         MDB_db **p2;
2600                         int i;
2601                         i = txn->mt_numdbs + DBX_CHUNK;
2602                         p1 = realloc(txn->mt_dbxs, i * sizeof(MDB_dbx));
2603                         if (p1 == NULL)
2604                                 return ENOMEM;
2605                         txn->mt_dbxs = p1;
2606                         p2 = realloc(txn->mt_dbs, i * sizeof(MDB_db *));
2607                         if (p2 == NULL)
2608                                 return ENOMEM;
2609                         txn->mt_dbs = p2;
2610                 }
2611                 txn->mt_dbxs[txn->mt_numdbs].md_name = strdup(name);
2612                 txn->mt_dbxs[txn->mt_numdbs].md_cmp = NULL;
2613                 txn->mt_dbxs[txn->mt_numdbs].md_rel = NULL;
2614                 txn->mt_dbs[txn->mt_numdbs] = data.mv_data;
2615                 *dbi = txn->mt_numdbs;
2616                 txn->mt_numdbs++;
2617         }
2618
2619         return rc;
2620 }
2621
2622 int mdb_stat(MDB_txn *txn, MDB_dbi dbi, MDB_stat *arg)
2623 {
2624         if (txn == NULL || arg == NULL)
2625                 return EINVAL;
2626
2627         arg->ms_psize = txn->mt_env->me_meta.mm_psize;
2628         arg->ms_depth = txn->mt_dbs[dbi]->md_depth;
2629         arg->ms_branch_pages = txn->mt_dbs[dbi]->md_branch_pages;
2630         arg->ms_leaf_pages = txn->mt_dbs[dbi]->md_leaf_pages;
2631         arg->ms_overflow_pages = txn->mt_dbs[dbi]->md_overflow_pages;
2632         arg->ms_entries = txn->mt_dbs[dbi]->md_entries;
2633
2634         return MDB_SUCCESS;
2635 }
2636
2637 void mdb_close(MDB_txn *txn, MDB_dbi dbi)
2638 {
2639         if (dbi >= txn->mt_numdbs)
2640                 return;
2641         free(txn->mt_dbxs[dbi].md_name);
2642         txn->mt_dbxs[dbi].md_name = NULL;
2643 }