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