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