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