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