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