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