-
Notifications
You must be signed in to change notification settings - Fork 1
/
btree.c
3180 lines (2705 loc) · 74.8 KB
/
btree.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* $OpenBSD: btree.c,v 1.30 2010/09/01 12:13:21 martinh Exp $ */
/*
* Copyright (c) 2009, 2010 Martin Hedenfalk <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "compat.h"
#include <sys/types.h>
#include <sys/tree.h>
#include <sys/stat.h>
#include <sys/queue.h>
#include <sys/param.h>
#include <sys/uio.h>
#ifdef HAVE_SYS_FILE_H
#include <sys/file.h>
#endif
#include <assert.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "btree.h"
/* #define DEBUG */
#ifdef DEBUG
# define DPRINTF(...) do { fprintf(stderr, "%s:%d: ", __func__, __LINE__); \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n"); } while(0)
#else
# define DPRINTF(...)
#endif
#define PAGESIZE 4096
#define BT_MINKEYS 4
#define BT_MAGIC 0xB3DBB3DB
#define BT_VERSION 4
#define MAXKEYSIZE 255
#define P_INVALID 0xFFFFFFFF
#define F_ISSET(w, f) (((w) & (f)) == (f))
typedef uint32_t pgno_t;
typedef uint16_t indx_t;
/* There are four page types: meta, index, leaf and overflow.
* They all share the same page header.
*/
struct page { /* represents an on-disk page */
pgno_t pgno; /* page number */
#define P_BRANCH 0x01 /* branch page */
#define P_LEAF 0x02 /* leaf page */
#define P_OVERFLOW 0x04 /* overflow page */
#define P_META 0x08 /* meta page */
#define P_HEAD 0x10 /* header page */
uint32_t flags;
#define lower b.fb.fb_lower
#define upper b.fb.fb_upper
#define p_next_pgno b.pb_next_pgno
union page_bounds {
struct {
indx_t fb_lower; /* lower bound of free space */
indx_t fb_upper; /* upper bound of free space */
} fb;
pgno_t pb_next_pgno; /* overflow page linked list */
} b;
indx_t ptrs[1]; /* dynamic size */
} __packed;
#define PAGEHDRSZ offsetof(struct page, ptrs)
#define NUMKEYSP(p) (((p)->lower - PAGEHDRSZ) >> 1)
#define NUMKEYS(mp) (((mp)->page->lower - PAGEHDRSZ) >> 1)
#define SIZELEFT(mp) (indx_t)((mp)->page->upper - (mp)->page->lower)
#define PAGEFILL(bt, mp) (1000 * ((bt)->head.psize - PAGEHDRSZ - SIZELEFT(mp)) / \
((bt)->head.psize - PAGEHDRSZ))
#define IS_LEAF(mp) F_ISSET((mp)->page->flags, P_LEAF)
#define IS_BRANCH(mp) F_ISSET((mp)->page->flags, P_BRANCH)
#define IS_OVERFLOW(mp) F_ISSET((mp)->page->flags, P_OVERFLOW)
struct bt_head { /* header page content */
uint32_t magic;
uint32_t version;
uint32_t flags;
uint32_t psize; /* page size */
} __packed;
struct bt_meta { /* meta (footer) page content */
#define BT_TOMBSTONE 0x01 /* file is replaced */
uint32_t flags;
pgno_t root; /* page number of root page */
pgno_t prev_meta; /* previous meta page number */
time_t created_at;
uint32_t branch_pages;
uint32_t leaf_pages;
uint32_t overflow_pages;
uint32_t revisions;
uint32_t depth;
uint64_t entries;
unsigned char hash[SHA_DIGEST_LENGTH];
} __packed;
struct btkey {
size_t len;
char str[MAXKEYSIZE];
};
struct mpage { /* an in-memory cached page */
RB_ENTRY(mpage) entry; /* page cache entry */
SIMPLEQ_ENTRY(mpage) next; /* queue of dirty pages */
TAILQ_ENTRY(mpage) lru_next; /* LRU queue */
struct mpage *parent; /* NULL if root */
unsigned int parent_index; /* keep track of node index */
struct btkey prefix;
struct page *page;
pgno_t pgno; /* copy of page->pgno */
short ref; /* increased by cursors */
short dirty; /* 1 if on dirty queue */
};
RB_HEAD(page_cache, mpage);
SIMPLEQ_HEAD(dirty_queue, mpage);
TAILQ_HEAD(lru_queue, mpage);
static int mpage_cmp(struct mpage *a, struct mpage *b);
static struct mpage *mpage_lookup(struct btree *bt, pgno_t pgno);
static void mpage_add(struct btree *bt, struct mpage *mp);
static void mpage_free(struct mpage *mp);
static void mpage_del(struct btree *bt, struct mpage *mp);
static void mpage_flush(struct btree *bt);
static struct mpage *mpage_copy(struct btree *bt, struct mpage *mp);
static void mpage_prune(struct btree *bt);
static void mpage_dirty(struct btree *bt, struct mpage *mp);
static struct mpage *mpage_touch(struct btree *bt, struct mpage *mp);
RB_PROTOTYPE(page_cache, mpage, entry, mpage_cmp);
RB_GENERATE(page_cache, mpage, entry, mpage_cmp);
struct ppage { /* ordered list of pages */
SLIST_ENTRY(ppage) entry;
struct mpage *mpage;
unsigned int ki; /* cursor index on page */
};
SLIST_HEAD(page_stack, ppage);
#define CURSOR_EMPTY(c) SLIST_EMPTY(&(c)->stack)
#define CURSOR_TOP(c) SLIST_FIRST(&(c)->stack)
#define CURSOR_POP(c) SLIST_REMOVE_HEAD(&(c)->stack, entry)
#define CURSOR_PUSH(c,p) SLIST_INSERT_HEAD(&(c)->stack, p, entry)
struct cursor {
struct btree *bt;
struct btree_txn *txn;
struct page_stack stack; /* stack of parent pages */
short initialized; /* 1 if initialized */
short eof; /* 1 if end is reached */
};
#define METAHASHLEN offsetof(struct bt_meta, hash)
#define METADATA(p) ((void *)((char *)p + PAGEHDRSZ))
struct node {
#define n_pgno p.np_pgno
#define n_dsize p.np_dsize
union {
pgno_t np_pgno; /* child page number */
uint32_t np_dsize; /* leaf data size */
} p;
uint16_t ksize; /* key size */
#define F_BIGDATA 0x01 /* data put on overflow page */
uint8_t flags;
char data[1];
} __packed;
struct btree_txn {
pgno_t root; /* current / new root page */
pgno_t next_pgno; /* next unallocated page */
struct btree *bt; /* btree is ref'd */
struct dirty_queue *dirty_queue; /* modified pages */
#define BT_TXN_RDONLY 0x01 /* read-only transaction */
#define BT_TXN_ERROR 0x02 /* an error has occurred */
unsigned int flags;
};
struct btree {
int fd;
char *path;
#define BT_FIXPADDING 0x01 /* internal */
unsigned int flags;
bt_cmp_func cmp; /* user compare function */
struct bt_head head;
struct bt_meta meta;
struct page_cache *page_cache;
struct lru_queue *lru_queue;
struct btree_txn *txn; /* current write transaction */
int ref; /* increased by cursors & txn */
struct btree_stat stat;
off_t size; /* current file size */
};
#define NODESIZE offsetof(struct node, data)
#define INDXSIZE(k) (NODESIZE + ((k) == NULL ? 0 : (k)->size))
#define LEAFSIZE(k, d) (NODESIZE + (k)->size + (d)->size)
#define NODEPTRP(p, i) ((struct node *)((char *)(p) + (p)->ptrs[i]))
#define NODEPTR(mp, i) NODEPTRP((mp)->page, i)
#define NODEKEY(node) (void *)((node)->data)
#define NODEDATA(node) (void *)((char *)(node)->data + (node)->ksize)
#define NODEPGNO(node) ((node)->p.np_pgno)
#define NODEDSZ(node) ((node)->p.np_dsize)
#define BT_COMMIT_PAGES 64 /* max number of pages to write in one commit */
#define BT_MAXCACHE_DEF 1024 /* max number of pages to keep in cache */
static int btree_read_page(struct btree *bt, pgno_t pgno,
struct page *page);
static struct mpage *btree_get_mpage(struct btree *bt, pgno_t pgno);
static int btree_search_page_root(struct btree *bt,
struct mpage *root, struct btval *key,
struct cursor *cursor, int modify,
struct mpage **mpp);
static int btree_search_page(struct btree *bt,
struct btree_txn *txn, struct btval *key,
struct cursor *cursor, int modify,
struct mpage **mpp);
static int btree_write_header(struct btree *bt, int fd);
static int btree_read_header(struct btree *bt);
static int btree_is_meta_page(struct page *p);
static int btree_read_meta(struct btree *bt, pgno_t *p_next);
static int btree_write_meta(struct btree *bt, pgno_t root,
unsigned int flags);
static void btree_ref(struct btree *bt);
static struct node *btree_search_node(struct btree *bt, struct mpage *mp,
struct btval *key, int *exactp, unsigned int *kip);
static int btree_add_node(struct btree *bt, struct mpage *mp,
indx_t indx, struct btval *key, struct btval *data,
pgno_t pgno, uint8_t flags);
static void btree_del_node(struct btree *bt, struct mpage *mp,
indx_t indx);
static int btree_read_data(struct btree *bt, struct mpage *mp,
struct node *leaf, struct btval *data);
static int btree_rebalance(struct btree *bt, struct mpage *mp);
static int btree_update_key(struct btree *bt, struct mpage *mp,
indx_t indx, struct btval *key);
static int btree_adjust_prefix(struct btree *bt,
struct mpage *src, int delta);
static int btree_move_node(struct btree *bt, struct mpage *src,
indx_t srcindx, struct mpage *dst, indx_t dstindx);
static int btree_merge(struct btree *bt, struct mpage *src,
struct mpage *dst);
static int btree_split(struct btree *bt, struct mpage **mpp,
unsigned int *newindxp, struct btval *newkey,
struct btval *newdata, pgno_t newpgno);
static struct mpage *btree_new_page(struct btree *bt, uint32_t flags);
static int btree_write_overflow_data(struct btree *bt,
struct page *p, struct btval *data);
static void cursor_pop_page(struct cursor *cursor);
static struct ppage *cursor_push_page(struct cursor *cursor,
struct mpage *mp);
static int bt_set_key(struct btree *bt, struct mpage *mp,
struct node *node, struct btval *key);
static int btree_sibling(struct cursor *cursor, int move_right);
static int btree_cursor_next(struct cursor *cursor,
struct btval *key, struct btval *data);
static int btree_cursor_set(struct cursor *cursor,
struct btval *key, struct btval *data, int *exactp);
static int btree_cursor_first(struct cursor *cursor,
struct btval *key, struct btval *data);
static void bt_reduce_separator(struct btree *bt, struct node *min,
struct btval *sep);
static void remove_prefix(struct btree *bt, struct btval *key,
size_t pfxlen);
static void expand_prefix(struct btree *bt, struct mpage *mp,
indx_t indx, struct btkey *expkey);
static void concat_prefix(struct btree *bt, char *s1, size_t n1,
char *s2, size_t n2, char *cs, size_t *cn);
static void common_prefix(struct btree *bt, struct btkey *min,
struct btkey *max, struct btkey *pfx);
static void find_common_prefix(struct btree *bt, struct mpage *mp);
static size_t bt_leaf_size(struct btree *bt, struct btval *key,
struct btval *data);
static size_t bt_branch_size(struct btree *bt, struct btval *key);
static pgno_t btree_compact_tree(struct btree *bt, pgno_t pgno,
struct btree *btc);
static int memncmp(const void *s1, size_t n1,
const void *s2, size_t n2);
static int memnrcmp(const void *s1, size_t n1,
const void *s2, size_t n2);
static int
memncmp(const void *s1, size_t n1, const void *s2, size_t n2)
{
if (n1 < n2) {
if (memcmp(s1, s2, n1) == 0)
return -1;
}
else if (n1 > n2) {
if (memcmp(s1, s2, n2) == 0)
return 1;
}
return memcmp(s1, s2, n1);
}
static int
memnrcmp(const void *s1, size_t n1, const void *s2, size_t n2)
{
const unsigned char *p1;
const unsigned char *p2;
if (n1 == 0)
return n2 == 0 ? 0 : -1;
if (n2 == 0)
return n1 == 0 ? 0 : 1;
p1 = (const unsigned char *)s1 + n1 - 1;
p2 = (const unsigned char *)s2 + n2 - 1;
while (*p1 == *p2) {
if (p1 == s1)
return (p2 == s2) ? 0 : -1;
if (p2 == s2)
return (p1 == p2) ? 0 : 1;
p1--;
p2--;
}
return *p1 - *p2;
}
int
btree_cmp(struct btree *bt, const struct btval *a, const struct btval *b)
{
return bt->cmp(a, b);
}
static void
common_prefix(struct btree *bt, struct btkey *min, struct btkey *max,
struct btkey *pfx)
{
size_t n = 0;
char *p1;
char *p2;
if (min->len == 0 || max->len == 0) {
pfx->len = 0;
return;
}
if (F_ISSET(bt->flags, BT_REVERSEKEY)) {
p1 = min->str + min->len - 1;
p2 = max->str + max->len - 1;
while (*p1 == *p2) {
if (p1 < min->str || p2 < max->str)
break;
p1--;
p2--;
n++;
}
assert(n <= (int)sizeof(pfx->str));
pfx->len = n;
bcopy(p2 + 1, pfx->str, n);
} else {
p1 = min->str;
p2 = max->str;
while (*p1 == *p2) {
if (n == min->len || n == max->len)
break;
p1++;
p2++;
n++;
}
assert(n <= (int)sizeof(pfx->str));
pfx->len = n;
bcopy(max->str, pfx->str, n);
}
}
static void
remove_prefix(struct btree *bt, struct btval *key, size_t pfxlen)
{
if (pfxlen == 0 || bt->cmp != NULL)
return;
DPRINTF("removing %zu bytes of prefix from key [%.*s]", pfxlen,
(int)key->size, (char *)key->data);
assert(pfxlen <= key->size);
key->size -= pfxlen;
if (!F_ISSET(bt->flags, BT_REVERSEKEY))
key->data = (char *)key->data + pfxlen;
}
static void
expand_prefix(struct btree *bt, struct mpage *mp, indx_t indx,
struct btkey *expkey)
{
struct node *node;
node = NODEPTR(mp, indx);
expkey->len = sizeof(expkey->str);
concat_prefix(bt, mp->prefix.str, mp->prefix.len,
NODEKEY(node), node->ksize, expkey->str, &expkey->len);
}
static int
bt_cmp(struct btree *bt, const struct btval *key1, const struct btval *key2,
struct btkey *pfx)
{
if (F_ISSET(bt->flags, BT_REVERSEKEY))
return memnrcmp(key1->data, key1->size - pfx->len,
key2->data, key2->size);
else
return memncmp((char *)key1->data + pfx->len, key1->size - pfx->len,
key2->data, key2->size);
}
void
btval_reset(struct btval *btv)
{
if (btv) {
if (btv->mp)
btv->mp->ref--;
if (btv->free_data)
free(btv->data);
bzero(btv, sizeof(*btv));
}
}
static int
mpage_cmp(struct mpage *a, struct mpage *b)
{
if (a->pgno > b->pgno)
return 1;
if (a->pgno < b->pgno)
return -1;
return 0;
}
static struct mpage *
mpage_lookup(struct btree *bt, pgno_t pgno)
{
struct mpage find, *mp;
find.pgno = pgno;
mp = RB_FIND(page_cache, bt->page_cache, &find);
if (mp) {
bt->stat.hits++;
/* Update LRU queue. Move page to the end. */
TAILQ_REMOVE(bt->lru_queue, mp, lru_next);
TAILQ_INSERT_TAIL(bt->lru_queue, mp, lru_next);
}
return mp;
}
static void
mpage_add(struct btree *bt, struct mpage *mp)
{
assert(RB_INSERT(page_cache, bt->page_cache, mp) == NULL);
bt->stat.cache_size++;
TAILQ_INSERT_TAIL(bt->lru_queue, mp, lru_next);
}
static void
mpage_free(struct mpage *mp)
{
if (mp != NULL) {
free(mp->page);
free(mp);
}
}
static void
mpage_del(struct btree *bt, struct mpage *mp)
{
assert(RB_REMOVE(page_cache, bt->page_cache, mp) == mp);
assert(bt->stat.cache_size > 0);
bt->stat.cache_size--;
TAILQ_REMOVE(bt->lru_queue, mp, lru_next);
}
static void
mpage_flush(struct btree *bt)
{
struct mpage *mp;
while ((mp = RB_MIN(page_cache, bt->page_cache)) != NULL) {
mpage_del(bt, mp);
mpage_free(mp);
}
}
static struct mpage *
mpage_copy(struct btree *bt, struct mpage *mp)
{
struct mpage *copy;
if ((copy = calloc(1, sizeof(*copy))) == NULL)
return NULL;
if ((copy->page = malloc(bt->head.psize)) == NULL) {
free(copy);
return NULL;
}
bcopy(mp->page, copy->page, bt->head.psize);
bcopy(&mp->prefix, ©->prefix, sizeof(mp->prefix));
copy->parent = mp->parent;
copy->parent_index = mp->parent_index;
copy->pgno = mp->pgno;
return copy;
}
/* Remove the least recently used memory pages until the cache size is
* within the configured bounds. Pages referenced by cursors or returned
* key/data are not pruned.
*/
static void
mpage_prune(struct btree *bt)
{
struct mpage *mp, *next;
for (mp = TAILQ_FIRST(bt->lru_queue); mp; mp = next) {
if (bt->stat.cache_size <= bt->stat.max_cache)
break;
next = TAILQ_NEXT(mp, lru_next);
if (!mp->dirty && mp->ref <= 0) {
mpage_del(bt, mp);
mpage_free(mp);
}
}
}
/* Mark a page as dirty and push it on the dirty queue.
*/
static void
mpage_dirty(struct btree *bt, struct mpage *mp)
{
assert(bt != NULL);
assert(bt->txn != NULL);
if (!mp->dirty) {
mp->dirty = 1;
SIMPLEQ_INSERT_TAIL(bt->txn->dirty_queue, mp, next);
}
}
/* Touch a page: make it dirty and re-insert into tree with updated pgno.
*/
static struct mpage *
mpage_touch(struct btree *bt, struct mpage *mp)
{
assert(bt != NULL);
assert(bt->txn != NULL);
assert(mp != NULL);
if (!mp->dirty) {
DPRINTF("touching page %u -> %u", mp->pgno, bt->txn->next_pgno);
if (mp->ref == 0)
mpage_del(bt, mp);
else {
if ((mp = mpage_copy(bt, mp)) == NULL)
return NULL;
}
mp->pgno = mp->page->pgno = bt->txn->next_pgno++;
mpage_dirty(bt, mp);
mpage_add(bt, mp);
/* Update the page number to new touched page. */
if (mp->parent != NULL)
NODEPGNO(NODEPTR(mp->parent,
mp->parent_index)) = mp->pgno;
}
return mp;
}
static int
btree_read_page(struct btree *bt, pgno_t pgno, struct page *page)
{
ssize_t rc;
DPRINTF("reading page %u", pgno);
bt->stat.reads++;
if ((rc = pread(bt->fd, page, bt->head.psize, (off_t)pgno*bt->head.psize)) == 0) {
DPRINTF("page %u doesn't exist", pgno);
errno = ENOENT;
return BT_FAIL;
} else if (rc != (ssize_t)bt->head.psize) {
if (rc > 0)
errno = EINVAL;
DPRINTF("read: %s", strerror(errno));
return BT_FAIL;
}
if (page->pgno != pgno) {
DPRINTF("page numbers don't match: %u != %u", pgno, page->pgno);
errno = EINVAL;
return BT_FAIL;
}
DPRINTF("page %u has flags 0x%X", pgno, page->flags);
return BT_SUCCESS;
}
int
btree_sync(struct btree *bt)
{
if (!F_ISSET(bt->flags, BT_NOSYNC))
return fsync(bt->fd);
return 0;
}
struct btree_txn *
btree_txn_begin(struct btree *bt, int rdonly)
{
struct btree_txn *txn;
if (!rdonly && bt->txn != NULL) {
DPRINTF("write transaction already begun");
errno = EBUSY;
return NULL;
}
if ((txn = calloc(1, sizeof(*txn))) == NULL) {
DPRINTF("calloc: %s", strerror(errno));
return NULL;
}
if (rdonly) {
txn->flags |= BT_TXN_RDONLY;
} else {
txn->dirty_queue = calloc(1, sizeof(*txn->dirty_queue));
if (txn->dirty_queue == NULL) {
free(txn);
return NULL;
}
SIMPLEQ_INIT(txn->dirty_queue);
DPRINTF("taking write lock on txn %p", txn);
if (flock(bt->fd, LOCK_EX | LOCK_NB) != 0) {
DPRINTF("flock: %s", strerror(errno));
errno = EBUSY;
free(txn->dirty_queue);
free(txn);
return NULL;
}
bt->txn = txn;
}
txn->bt = bt;
btree_ref(bt);
if (btree_read_meta(bt, &txn->next_pgno) != BT_SUCCESS) {
btree_txn_abort(txn);
return NULL;
}
txn->root = bt->meta.root;
DPRINTF("begin transaction on btree %p, root page %u", bt, txn->root);
return txn;
}
void
btree_txn_abort(struct btree_txn *txn)
{
struct mpage *mp;
struct btree *bt;
if (txn == NULL)
return;
bt = txn->bt;
DPRINTF("abort transaction on btree %p, root page %u", bt, txn->root);
if (!F_ISSET(txn->flags, BT_TXN_RDONLY)) {
/* Discard all dirty pages.
*/
while (!SIMPLEQ_EMPTY(txn->dirty_queue)) {
mp = SIMPLEQ_FIRST(txn->dirty_queue);
assert(mp->ref == 0); /* cursors should be closed */
mpage_del(bt, mp);
SIMPLEQ_REMOVE_HEAD(txn->dirty_queue, next);
mpage_free(mp);
}
DPRINTF("releasing write lock on txn %p", txn);
txn->bt->txn = NULL;
if (flock(txn->bt->fd, LOCK_UN) != 0) {
DPRINTF("failed to unlock fd %d: %s",
txn->bt->fd, strerror(errno));
}
free(txn->dirty_queue);
}
btree_close(txn->bt);
free(txn);
}
int
btree_txn_commit(struct btree_txn *txn)
{
int n, done;
ssize_t rc;
off_t size;
struct mpage *mp;
struct btree *bt;
struct iovec iov[BT_COMMIT_PAGES];
assert(txn != NULL);
assert(txn->bt != NULL);
bt = txn->bt;
if (F_ISSET(txn->flags, BT_TXN_RDONLY)) {
DPRINTF("attempt to commit read-only transaction");
btree_txn_abort(txn);
errno = EPERM;
return BT_FAIL;
}
if (txn != bt->txn) {
DPRINTF("attempt to commit unknown transaction");
btree_txn_abort(txn);
errno = EINVAL;
return BT_FAIL;
}
if (F_ISSET(txn->flags, BT_TXN_ERROR)) {
DPRINTF("error flag is set, can't commit");
btree_txn_abort(txn);
errno = EINVAL;
return BT_FAIL;
}
if (SIMPLEQ_EMPTY(txn->dirty_queue))
goto done;
if (F_ISSET(bt->flags, BT_FIXPADDING)) {
size = lseek(bt->fd, 0, SEEK_END);
size += bt->head.psize - (size % bt->head.psize);
DPRINTF("extending to multiple of page size: %llu", size);
if (ftruncate(bt->fd, size) != 0) {
DPRINTF("ftruncate: %s", strerror(errno));
btree_txn_abort(txn);
return BT_FAIL;
}
bt->flags &= ~BT_FIXPADDING;
}
DPRINTF("committing transaction on btree %p, root page %u",
bt, txn->root);
/* Commit up to BT_COMMIT_PAGES dirty pages to disk until done.
*/
do {
n = 0;
done = 1;
SIMPLEQ_FOREACH(mp, txn->dirty_queue, next) {
DPRINTF("commiting page %u", mp->pgno);
iov[n].iov_len = bt->head.psize;
iov[n].iov_base = mp->page;
if (++n >= BT_COMMIT_PAGES) {
done = 0;
break;
}
}
if (n == 0)
break;
DPRINTF("commiting %u dirty pages", n);
rc = writev(bt->fd, iov, n);
if (rc != (ssize_t)bt->head.psize*n) {
if (rc > 0)
DPRINTF("short write, filesystem full?");
else
DPRINTF("writev: %s", strerror(errno));
btree_txn_abort(txn);
return BT_FAIL;
}
/* Remove the dirty flag from the written pages.
*/
while (!SIMPLEQ_EMPTY(txn->dirty_queue)) {
mp = SIMPLEQ_FIRST(txn->dirty_queue);
mp->dirty = 0;
SIMPLEQ_REMOVE_HEAD(txn->dirty_queue, next);
if (--n == 0)
break;
}
} while (!done);
if (btree_sync(bt) != 0 ||
btree_write_meta(bt, txn->root, 0) != BT_SUCCESS ||
btree_sync(bt) != 0) {
btree_txn_abort(txn);
return BT_FAIL;
}
done:
mpage_prune(bt);
btree_txn_abort(txn);
return BT_SUCCESS;
}
static int
btree_write_header(struct btree *bt, int fd)
{
struct stat sb;
struct bt_head *h;
struct page *p;
ssize_t rc;
unsigned int psize;
DPRINTF("writing header page");
assert(bt != NULL);
/* Ask stat for 'optimal blocksize for I/O'.
*/
if (fstat(fd, &sb) == 0)
psize = sb.st_blksize;
else
psize = PAGESIZE;
if ((p = calloc(1, psize)) == NULL)
return -1;
p->flags = P_HEAD;
h = METADATA(p);
h->magic = BT_MAGIC;
h->version = BT_VERSION;
h->psize = psize;
bcopy(h, &bt->head, sizeof(*h));
rc = write(fd, p, bt->head.psize);
free(p);
if (rc != (ssize_t)bt->head.psize) {
if (rc > 0)
DPRINTF("short write, filesystem full?");
return BT_FAIL;
}
return BT_SUCCESS;
}
static int
btree_read_header(struct btree *bt)
{
char page[PAGESIZE];
struct page *p;
struct bt_head *h;
int rc;
assert(bt != NULL);
/* We don't know the page size yet, so use a minimum value.
*/
if ((rc = pread(bt->fd, page, PAGESIZE, 0)) == 0) {
errno = ENOENT;
return -1;
} else if (rc != PAGESIZE) {
if (rc > 0)
errno = EINVAL;
DPRINTF("read: %s", strerror(errno));
return -1;
}
p = (struct page *)page;
if (!F_ISSET(p->flags, P_HEAD)) {
DPRINTF("page %d not a header page", p->pgno);
errno = EINVAL;
return -1;
}
h = METADATA(p);
if (h->magic != BT_MAGIC) {
DPRINTF("header has invalid magic");
errno = EINVAL;
return -1;
}
if (h->version != BT_VERSION) {
DPRINTF("database is version %u, expected version %u",
bt->head.version, BT_VERSION);
errno = EINVAL;
return -1;
}
bcopy(h, &bt->head, sizeof(*h));
return 0;
}
static int
btree_write_meta(struct btree *bt, pgno_t root, unsigned int flags)
{
struct mpage *mp;
struct bt_meta *meta;
ssize_t rc;
DPRINTF("writing meta page for root page %u", root);
assert(bt != NULL);
assert(bt->txn != NULL);
if ((mp = btree_new_page(bt, P_META)) == NULL)
return -1;
bt->meta.prev_meta = bt->meta.root;
bt->meta.root = root;
bt->meta.flags = flags;
bt->meta.created_at = time(0);
bt->meta.revisions++;
SHA1((unsigned char *)&bt->meta, METAHASHLEN, bt->meta.hash);
/* Copy the meta data changes to the new meta page. */
meta = METADATA(mp->page);
bcopy(&bt->meta, meta, sizeof(*meta));
rc = write(bt->fd, mp->page, bt->head.psize);
mp->dirty = 0;
SIMPLEQ_REMOVE_HEAD(bt->txn->dirty_queue, next);
if (rc != (ssize_t)bt->head.psize) {
if (rc > 0)
DPRINTF("short write, filesystem full?");
return BT_FAIL;
}
if ((bt->size = lseek(bt->fd, 0, SEEK_END)) == -1) {
DPRINTF("failed to update file size: %s", strerror(errno));
bt->size = 0;
}
return BT_SUCCESS;
}
/* Returns true if page p is a valid meta page, false otherwise.
*/
static int
btree_is_meta_page(struct page *p)
{
struct bt_meta *m;
unsigned char hash[SHA_DIGEST_LENGTH];
m = METADATA(p);
if (!F_ISSET(p->flags, P_META)) {
DPRINTF("page %d not a meta page", p->pgno);
errno = EINVAL;
return 0;
}
if (m->root >= p->pgno && m->root != P_INVALID) {
DPRINTF("page %d points to an invalid root page", p->pgno);
errno = EINVAL;
return 0;
}
SHA1((unsigned char *)m, METAHASHLEN, hash);
if (bcmp(hash, m->hash, SHA_DIGEST_LENGTH) != 0) {
DPRINTF("page %d has an invalid digest", p->pgno);
errno = EINVAL;
return 0;
}