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