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