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