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