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