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