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