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