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