-
Notifications
You must be signed in to change notification settings - Fork 24
/
sst.c
5018 lines (4488 loc) · 136 KB
/
sst.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
/*
* Copyright (c) 2016--2021 Wu, Xingbo <[email protected]>
*
* All rights reserved. No warranty, explicit or implicit, provided.
*/
#define _GNU_SOURCE
// headers {{{
#include "lib.h"
#include "ctypes.h"
#include "kv.h"
#include <assert.h> // static_assert
#include <dirent.h> // dirfd
#include <stdarg.h> // va_start
#include <sys/uio.h> // writev
#include "sst.h"
// }}} headers
// define {{{
#define SST_MAX_BLKPGNR ((16)) // 16 pages
#define SST_MAX_BLKSZ ((PGSZ * SST_MAX_BLKPGNR)) // 64kB
#define SST_MAX_KVSZ ((SST_MAX_BLKSZ - (sizeof(u16) * 2)))
#define SST_MAX_BLKID ((UINT16_MAX - SST_MAX_BLKPGNR))
#define MSST_NWAY ((16)) // 16 levels
#define SSTY_STALE ((0x80u))
#define SSTY_TOMBSTONE ((0x40u))
#define SSTY_RANK ((0x3fu))
#define SSTY_INVALID ((0xffu))
// 4 for 16; 5 for 32; TODO: 6 for 64
#define SSTY_DBITS ((5))
#define SSTY_DIST ((1u << SSTY_DBITS))
static_assert(SSTY_DBITS >= 4 && SSTY_DBITS <= 5, "Supported SSTY_DBITS: 4,5; TODO: 6");
#if defined(__linux__)
#define SSTY_MMAP_FLAGS ((MAP_PRIVATE|MAP_POPULATE))
#else
#define SSTY_MMAP_FLAGS ((MAP_PRIVATE))
#endif
// turn on IO-optimized binary search by default
#define MSSTY_SEEK_BISECT_OPT
#define MSSTZ_DIST ((32))
#define MSSTZ_NBLKS ((20400)) // slightly smaller than 20480
// approx. table size must be smaller
#define MSSTZ_TSZ ((MSSTZ_NBLKS * PGSZ))
#define MSSTZ_MINSZ ((MSSTZ_TSZ >> 2)) // 1/4 of the maximum table size
#define MSSTZ_ETSZ ((MSSTZ_NBLKS * ((PGSZ - 256))))
#define MSSTZ_NWAY_MINOR ((8))
#define MSSTZ_NWAY_MAJOR ((2))
#define MSSTZ_NWAY_SAFE ((12))
static_assert(MSSTZ_NWAY_MINOR <= MSST_NWAY, "nway");
static_assert(MSSTZ_NBLKS <= SST_MAX_BLKID, "nblks");
// }}} define
// kv {{{
inline size_t
sst_kv_vi128_estimate(const struct kv * const kv)
{
return vi128_estimate_u32(kv->klen) + vi128_estimate_u32(kv->vlen) + kv->klen + (kv->vlen & SST_VLEN_MASK);
}
inline u8 *
sst_kv_vi128_encode(u8 * ptr, const struct kv * const kv)
{
ptr = vi128_encode_u32(ptr, kv->klen);
ptr = vi128_encode_u32(ptr, kv->vlen);
const u32 kvlen = kv->klen + (kv->vlen & SST_VLEN_MASK);
memcpy(ptr, kv->kv, kvlen);
return ptr + kvlen;
}
inline size_t
sst_kv_size(const struct kv * const kv)
{
return sizeof(*kv) + kv->klen + (kv->vlen & SST_VLEN_MASK);
}
// estimate the size of kvs in a range
u64
sst_kvmap_estimate(const struct kvmap_api * const api, void * const map,
const struct kref * const k0, const struct kref * const kz)
{
void * const ref = kvmap_ref(api, map);
void * const iter = api->iter_create(ref);
u64 est = 0;
struct kv * kz_inp = NULL;
if (kz) {
api->iter_seek(iter, kz);
api->iter_inp(iter, kvmap_inp_steal_kv, &kz_inp);
}
api->iter_seek(iter, k0);
while (api->iter_valid(iter)) {
struct kv * kv_inp = NULL;
api->iter_inp(iter, kvmap_inp_steal_kv, &kv_inp);
if (kv_inp == kz_inp)
break;
est += sst_kv_vi128_estimate(kv_inp);
est += sizeof(u16);
api->iter_skip(iter, 1);
}
api->iter_destroy(iter);
kvmap_unref(api, ref);
return est;
}
struct kv *
sst_kvref_dup2_kv(struct kvref * const kvref, struct kv * const out)
{
const size_t sz = sst_kv_size(&kvref->hdr);
struct kv * const new = out ? out : malloc(sz);
if (new) {
*new = kvref->hdr;
memcpy(new->kv, kvref->kptr, new->klen);
memcpy(new->kv + new->klen, kvref->vptr, new->vlen & SST_VLEN_MASK);
}
return new;
}
// }}} kv
// mm {{{
struct kv *
kvmap_mm_in_ts(struct kv * const kv, void * const priv)
{
(void)priv;
if (kv == NULL)
return NULL;
const size_t sz = sst_kv_size(kv);
struct kv * const new = malloc(sz);
if (new)
memcpy(new, kv, sz);
return new;
}
struct kv *
kvmap_mm_out_ts(struct kv * const kv, struct kv * const out)
{
if (kv == NULL)
return NULL;
const size_t sz = sst_kv_size(kv);
struct kv * const new = out ? out : malloc(sz);
if (new)
memcpy(new, kv, sz);
return new;
}
// for memtable
const struct kvmap_mm kvmap_mm_ts = {
.in = kvmap_mm_in_ts,
.out = kvmap_mm_out_ts,
.free = kvmap_mm_free_free,
.priv = NULL,
};
// }}} mm
// sst {{{
struct sst_blkmeta { // the first two bytes in each block
u8 nkeys; // number of keys
u8 nblks; // number of 4K pages
};
struct sst_meta {
u32 inr; // == 0 for empty sst in the place of bms[0]
u32 nblks;
u64 seq; // <= the file's seq after linking
u32 way; // this should be always valid after linking
u32 totkv;
u32 bmsoff;
u32 ioffsoff;
u32 ckeysoff;
u32 ckeyssz;
};
struct sst {
const struct sst_blkmeta * bms; // block metadata (2-byte each)
u32 inr; // number of index keys in ioffs
u32 nblks; // number of 4kB data blocks
int fd;
u32 refcnt; // not atomic; only msstz can change it; should close/unmap only when == 1
struct rcache * rc;
const u32 * ioffs; // offsets of the index keys
u8 * mem; // pointer to the mmap area
u32 fsize;
u32 totkv;
};
static bool
sst_init(const char * const dirname, const u64 seq, const u32 way, struct sst * const sst)
{
char * const fn = malloc(strlen(dirname) + 30);
const u64 magic = seq * 100lu + way;
sprintf(fn, "%s/%03lu.sstx", dirname, magic);
//const int fd = open(fn, O_RDONLY|O_DIRECT);
const int fd = open(fn, O_RDONLY);
free(fn);
if (fd < 0)
return false;
const size_t fsize = fdsize(fd);
if (fsize == 0 || fsize >= UINT32_MAX) {
close(fd);
return false;
}
// Hugepages make replacement hard; some file systems don't support hugepages
//MAP_HUGETLB|MAP_HUGE_2MB
u8 * const mem = mmap(NULL, fsize, PROT_READ, MAP_PRIVATE, fd, 0);
if (mem == MAP_FAILED)
return false;
sst->mem = mem;
sst->fsize = (u32)fsize;
const struct sst_meta * const meta = sst_meta(sst);
debug_assert((meta->seq < seq) || ((meta->seq == seq) && (meta->way == way)));
sst->bms = (typeof(sst->bms))(mem + meta->bmsoff);
sst->inr = meta->inr;
sst->nblks = meta->nblks;
sst->fd = fd; // keep fd open
sst->refcnt = 1;
sst->rc = NULL;
sst->ioffs = (typeof(sst->ioffs))(mem + meta->ioffsoff);
sst->totkv = meta->totkv;
//const u32 datasz = PGSZ * sst->nblks;
//madvise(mem, datasz, MADV_RANDOM);
//pages_lock(mem + datasz, fsize - datasz); // mlock the metadata area; not necessary with ssty
pages_lock((void *)sst->bms, sizeof(sst->bms[0]) * meta->nblks); // mlock the bms
return true;
}
const struct sst_meta *
sst_meta(struct sst * const sst)
{
const struct sst_meta * const meta = (typeof(meta))(sst->mem + sst->fsize - sizeof(*meta));
return meta;
}
inline void
sst_rcache(struct sst * const sst, struct rcache * const rc)
{
sst->rc = rc;
}
struct sst *
sst_open(const char * const dirname, const u64 seq, const u32 way)
{
struct sst * const sst = yalloc(sizeof(*sst));
if (sst == NULL)
return NULL;
if (sst_init(dirname, seq, way, sst)) {
return sst;
} else {
free(sst);
return NULL;
}
}
static inline u32
k128_search_le(const u8 * const base, const u32 * const ioffs,
const struct kref * const key, const size_t headersize, u32 l, u32 r)
{
while ((l + 1) < r) {
const u32 m = (l + r) >> 1;
const int cmp = kref_k128_compare(key, base + headersize + ioffs[m]);
if (cmp < 0) // search-key < [m]
r = m;
else if (cmp > 0) // search-key > [m]
l = m;
else
return m;
}
return l;
}
static u16
sst_search_blkid(struct sst * const map, const struct kref * const key)
{
const u32 ikeyid = k128_search_le(map->mem, map->ioffs, key, sizeof(u16), 0, map->inr);
const u16 blkid = *(const u16 *)(map->mem + map->ioffs[ikeyid]);
return blkid;
}
// access data blocks from here
static inline const u8 *
sst_blk_acquire(struct sst * const map, const u16 blkid)
{
if (map->rc && (map->bms[blkid].nblks == 1)) {
const u8 * const ptr = rcache_acquire(map->rc, map->fd, blkid);
return ptr;
}
return map->mem + (PGSZ * blkid);
}
static inline u64
sst_blk_retain(struct rcache * const rc, const u8 * blk)
{
debug_assert(blk && (((u64)blk) & 0xffflu) == 0);
if (rc && (blk[1] == 1))
rcache_retain(rc, blk);
return (u64)blk;
}
static inline void
sst_blk_release(struct rcache * const rc, const u8 * blk)
{
debug_assert(blk && (((u64)blk) & 0xffflu) == 0);
if (rc && (blk[1] == 1))
rcache_release(rc, blk);
}
// the highest bit is set if there is a match
// return 0 to nkeys (low bits)
static u32
sst_search_block_ge(const u8 * const blk, const struct kref * const key)
{
const u16 * const offs = (typeof(offs))(blk+sizeof(u16));
u32 l = 0;
u32 r = ((struct sst_blkmeta *)blk)->nkeys; // blkmeta.nkeys
while (l < r) {
const u32 m = (l + r) >> 1;
const int cmp = kref_kv128_compare(key, blk + offs[m]);
if (cmp < 0)
r = m;
else if (cmp > 0)
l = m + 1;
else
return m | (1u << 31); // match
}
return l;
}
static inline const u8 *
sst_blk_get_kvptr(const u8 * const blk, const u32 id)
{
debug_assert(id < blk[0]);
const u16 * const offs = (typeof(offs))(blk + sizeof(u8) + sizeof(u8));
return blk + offs[id];
}
struct kv *
sst_get(struct sst * const map, const struct kref * const key, struct kv * const out)
{
const u16 blkid = sst_search_blkid(map, key);
// search in the block
const u8 * const blk = sst_blk_acquire(map, blkid);
debug_assert(blk);
const u32 r = sst_search_block_ge(blk, key);
if ((r >> 31) == 0) { // not found
sst_blk_release(map->rc, blk);
return NULL;
}
// found
const u8 * ptr = sst_blk_get_kvptr(blk, r & 0xffffu);
u32 klen, vlen;
ptr = vi128_decode_u32(ptr, &klen);
ptr = vi128_decode_u32(ptr, &vlen);
const u32 vlen1 = vlen & SST_VLEN_MASK;
const u32 kvlen = klen + vlen1;
struct kv * const ret = out ? out : malloc(sizeof(*ret) + kvlen);
ret->klen = klen;
ret->vlen = vlen;
memcpy(ret->kv, ptr, kvlen);
sst_blk_release(map->rc, blk);
return ret;
}
bool
sst_probe(struct sst * const map, const struct kref * const key)
{
const u16 blkid = sst_search_blkid(map, key);
// search in the block
const u8 * const blk = sst_blk_acquire(map, blkid);
debug_assert(blk);
const u32 r = sst_search_block_ge(blk, key);
sst_blk_release(map->rc, blk);
return (r >> 31);
}
struct kv *
sst_first_key(struct sst * const map, struct kv * const out)
{
if (map->nblks == 0)
return NULL;
const u8 * const blk = sst_blk_acquire(map, 0);
const u8 * ptr = sst_blk_get_kvptr(blk, 0);
u32 klen, vlen;
ptr = vi128_decode_u32(ptr, &klen);
ptr = vi128_decode_u32(ptr, &vlen);
struct kv * const ret = out ? out : malloc(sizeof(*ret) + klen);
ret->klen = klen;
ret->vlen = 0;
memcpy(ret->kv, ptr, klen);
sst_blk_release(map->rc, blk);
return ret;
}
struct kv *
sst_last_key(struct sst * const map, struct kv * const out)
{
if (map->nblks == 0)
return NULL;
u32 bmsi = map->nblks-1;
while (map->bms[bmsi].nblks == 0)
bmsi--;
debug_assert(bmsi < map->nblks);
const u8 * const blk = sst_blk_acquire(map, bmsi);
const u8 * ptr = sst_blk_get_kvptr(blk, map->bms[bmsi].nkeys-1);
u32 klen, vlen;
ptr = vi128_decode_u32(ptr, &klen);
ptr = vi128_decode_u32(ptr, &vlen);
struct kv * const ret = out ? out : malloc(sizeof(*ret) + klen);
ret->klen = klen;
ret->vlen = 0;
memcpy(ret->kv, ptr, klen);
sst_blk_release(map->rc, blk);
return ret;
}
static void
sst_deinit(struct sst * const map)
{
if (map->refcnt == 1) {
debug_assert(map->mem);
munmap((void *)map->mem, map->fsize);
if (map->rc)
rcache_close(map->rc, map->fd);
else
close(map->fd);
} else {
map->refcnt--;
}
}
static void
sst_deinit_lazy(struct sst * const map)
{
if (map->refcnt == 1) {
debug_assert(map->mem);
munmap((void *)map->mem, map->fsize);
if (map->rc)
rcache_close_lazy(map->rc, map->fd);
else
close(map->fd);
} else {
map->refcnt--;
}
}
void
sst_destroy(struct sst * const map)
{
sst_deinit(map);
free(map);
}
void
sst_fprint(struct sst * const map, FILE * const out)
{
fprintf(out, "%s totkv %u inr %u nblks %u filesz %u\n",
__func__, map->totkv, map->inr, map->nblks, map->fsize);
}
// }}} sst
// kvenc {{{
// 2MB * 63 = 126 MB
#define KVENC_BUFSZ ((1u << 21))
#define KVENC_BUFNR ((63))
struct kvenc {
u32 idx;
u32 off;
u8 * bufs[KVENC_BUFNR];
};
static struct kvenc *
kvenc_create(void)
{
return calloc(1, sizeof(struct kvenc));
}
static void
kvenc_append_raw(struct kvenc * const enc, const void * const data, const u32 size)
{
u32 off = 0;
u32 rem = size;
while (rem) {
const u32 bufidx = enc->idx;
debug_assert(bufidx < KVENC_BUFNR);
if (enc->bufs[bufidx] == NULL)
enc->bufs[bufidx] = malloc(KVENC_BUFSZ);
const u32 cpsz = (rem <= (KVENC_BUFSZ - enc->off)) ? rem : (KVENC_BUFSZ - enc->off);
if (data)
memcpy(enc->bufs[bufidx] + enc->off, ((u8 *)data) + off, cpsz);
else
memset(enc->bufs[bufidx] + enc->off, 0, cpsz);
rem -= cpsz;
off += cpsz;
enc->off += cpsz;
if (enc->off == KVENC_BUFSZ) {
enc->idx = bufidx + 1;
enc->off = 0;
}
}
}
static void
kvenc_append_bool(struct kvenc * const enc, const bool v)
{
kvenc_append_raw(enc, &v, sizeof(bool));
}
static inline void
kvenc_append_u32(struct kvenc * const enc, const u32 val)
{
kvenc_append_raw(enc, &val, sizeof(val));
}
static inline u32 *
kvenc_append_u32_backref(struct kvenc * const enc)
{
const u32 idx = enc->idx;
const u32 off = enc->off;
debug_assert((off + sizeof(u32)) <= KVENC_BUFSZ);
debug_assert((off % sizeof(u32)) == 0);
kvenc_append_raw(enc, NULL, sizeof(u32));
return (u32 *)(enc->bufs[idx] + off);
}
static inline void
kvenc_append_u16(struct kvenc * const enc, const u16 val)
{
kvenc_append_raw(enc, &val, sizeof(val));
}
static inline void
kvenc_append_vi128(struct kvenc * const enc, const u32 val)
{
u8 buf[8];
u8 * const end = vi128_encode_u32(buf, val);
kvenc_append_raw(enc, buf, (u32)(end - buf));
}
static inline void
kvenc_append_padding(struct kvenc * const enc, const u32 power)
{
debug_assert(power <= 12);
const u32 p2 = 1u << power;
const u32 off = enc->off & (p2 - 1);
if (off)
kvenc_append_raw(enc, NULL, p2 - off);
}
static u32
kvenc_size(struct kvenc * const enc)
{
return KVENC_BUFSZ * enc->idx + enc->off;
}
static ssize_t
kvenc_write(struct kvenc * const enc, const int fd)
{
struct iovec vec[KVENC_BUFNR+1];
const u32 nr = enc->idx;
for (u32 i = 0; i < nr; i++) {
vec[i].iov_base = enc->bufs[i];
vec[i].iov_len = KVENC_BUFSZ;
}
vec[nr].iov_base = enc->bufs[nr];
vec[nr].iov_len = enc->off;
return writev(fd, vec, enc->off ? (nr + 1) : nr);
}
static void
kvenc_reset(struct kvenc * const enc)
{
for (u32 i = 0; i < KVENC_BUFNR; i++) {
if (enc->bufs[i])
free(enc->bufs[i]);
else
break;
}
memset(enc, 0, sizeof(*enc));
}
static void
kvenc_destroy(struct kvenc * const enc)
{
const u32 nr = enc->idx;
for (u32 i = 0; i < nr; i++)
free(enc->bufs[i]);
if (enc->off)
free(enc->bufs[nr]);
free(enc);
}
// }}} kvenc
// sst_build {{{
// from k0 (inclusive) to kz (exclusive)
// warning: all iters in miter must handle the tombstone (vlen >= SST_VLEN_TS)
// return the output file size (in bytes)
u64
sst_build(struct miter * const miter, const char * const dirname,
const u64 seq, const u32 way, const u32 maxblks, const bool del, const bool ckeys,
const struct kv * const k0, const struct kv * const kz)
{
char * const fn = malloc(strlen(dirname) + 30);
const u64 magic = seq * 100lu + way;
sprintf(fn, "%s/%03lu.sstx", dirname, magic);
const int fdout = open(fn, O_WRONLY|O_CREAT|O_TRUNC, 00644);
free(fn);
if (fdout < 0)
return 0;
struct kv * const tmp0 = malloc(SST_MAX_BLKSZ);
kv_refill(tmp0, "", 0, "", 0);
struct kv * const tmp1 = malloc(SST_MAX_BLKSZ);
u8 * const blkbuf = malloc(SST_MAX_BLKSZ); // kv block
u8 * kvcsr = blkbuf; // cursor
u16 * const bmbuf = malloc(256 * sizeof(bmbuf[0])); // offsets of all keys in a block
u16 * const kvoffs = bmbuf+1;
// max number of 4kB data blocks
debug_assert(maxblks && (maxblks <= SST_MAX_BLKID));
struct sst_blkmeta * const bms = calloc(1, sizeof(bms[0]) * (maxblks + SST_MAX_BLKPGNR));
u32 keyid = 0; // number of keys in current block
u32 blkid = 0;
u32 totkv = 0;
struct kvenc * const aenc = kvenc_create();
struct kvenc * const kenc = kvenc_create();
// at most 65536 ikeys
u32 * const ioffs = malloc(sizeof(ioffs[0]) * (1lu << 16)); // offsets of ikeys
u32 inr = 0;
if (k0)
miter_kv_seek(miter, k0);
do {
// key in tmp1
struct kv * curr = miter_peek(miter, tmp1);
// skip tombstone; need tests!
if (del) {
while (curr && (curr->vlen == SST_VLEN_TS)) {
miter_skip_unique(miter);
curr = miter_peek(miter, tmp1);
}
}
// check for termination
if (curr && kz && (kv_compare(curr, kz) >= 0))
curr = NULL;
const size_t est1 = curr ? ((u32)sst_kv_vi128_estimate(curr) + sizeof(u16)) : 0;
if (est1 > SST_MAX_KVSZ) {
fprintf(stderr, "skip very long kv: size == %zu\n", est1);
miter_skip_unique(miter);
continue;
}
// estimate the size if curr is added to the current block
const u32 metasz = sizeof(u16) * (keyid + 1);
const u32 datasz = (u32)(kvcsr - blkbuf);
const u32 totsz = metasz + datasz;
const u32 esttot = totsz + (u32)est1;
// close and write current block if:
// no more new data: curr == NULL
// or: the new keys is not the first key AND total size is more than one page
// or: current block has too many keys (254)
// NOTE: a huge key (need 2+ pages) exclusively ocuppy a multi-page block
if (curr == NULL || (keyid && (esttot > PGSZ)) || (keyid == 254)) {
if (keyid == 0)
break;
// blksize: whole pages
const u32 blksize = (u32)bits_round_up(metasz + datasz, 12);
const u8 blknr = (u8)(blksize >> 12);
debug_assert(blksize <= SST_MAX_BLKSZ);
// fix the offsets: add metadata size to kv offsets
for (u32 i = 0; i < keyid; i++)
kvoffs[i] += (sizeof(u16) * (keyid + 1));
// write all metadata: metasz bytes
// save in the buffer
struct sst_blkmeta * const pblkmeta = &(bms[blkid]);
pblkmeta->nkeys = keyid; // 1 byte # of keys
pblkmeta->nblks = blknr; // 1byte # of 4kB blocks
bmbuf[0] = *(u16 *)pblkmeta;
memset(kvcsr, 0, blksize - metasz - datasz);
struct iovec vec[2] = {{bmbuf, metasz}, {blkbuf, blksize - metasz}};
writev(fdout, vec, 2); // ignore I/O errors
keyid = 0;
kvcsr = blkbuf;
blkid += (blksize / PGSZ);
// stop processing the next block; break the do-while loop
if ((curr == NULL) || (blkid >= maxblks))
break;
}
// the beginning of a block: build anchor key for every head key of block
if (keyid == 0) {
ioffs[inr] = kvenc_size(aenc);
// block id
debug_assert(blkid <= SST_MAX_BLKID);
kvenc_append_u16(aenc, (u16)blkid);
// anchor key
const u32 alen = tmp0->klen ? (kv_key_lcp(tmp0, curr)+1) : 0;
debug_assert(alen <= curr->klen);
// encode index key
kvenc_append_vi128(aenc, alen);
kvenc_append_raw(aenc, curr->kv, alen);
inr++;
}
// append kv to data block
kvoffs[keyid++] = (u16)(kvcsr - blkbuf);
kvcsr = sst_kv_vi128_encode(kvcsr, curr);
totkv++;
// copy keys for faster remix rebuilding
if (ckeys) {
const u32 lcp = kv_key_lcp(curr, tmp0);
const u32 slen = curr->klen - lcp;
kvenc_append_vi128(kenc, lcp); // prefix length
kvenc_append_vi128(kenc, slen); // suffix length
kvenc_append_bool(kenc, curr->vlen == SST_VLEN_TS);
kvenc_append_raw(kenc, curr->kv + lcp, slen);
}
// remember last key in tmp0
kv_dup2_key(curr, tmp0);
miter_skip_unique(miter);
} while (true);
debug_assert(inr < UINT16_MAX);
// place bms immediately after data blocks
const u32 bmsoff = PGSZ * blkid;
const u32 bmssz = sizeof(bms[0]) * blkid;
// now all data blocks have been written; write one big index block
// calculate index-key offsets
const u32 ikeysoff = bmsoff + bmssz; // index keys
for (u64 i = 0; i < inr; i++)
ioffs[i] += ikeysoff;
// write: index keys; all index-key offsets; # of index-keys
kvenc_append_padding(aenc, 4);
kvenc_append_padding(kenc, 4);
const u32 ikeyssz = kvenc_size(aenc);
const u32 ioffsoff = ikeysoff + ikeyssz;
const u32 ioffssz = sizeof(ioffs[0]) * inr;
const u32 ckeysoff = ioffsoff + ioffssz;
const u32 ckeyssz = kvenc_size(kenc);
// metadata
struct sst_meta endmeta = {.inr = inr, .nblks = blkid, .seq = seq, .way = way, .totkv = totkv,
.bmsoff = bmsoff, .ioffsoff = ioffsoff, .ckeysoff = ckeysoff, .ckeyssz = ckeyssz, };
const u32 endsz = sizeof(endmeta);
const u64 totsz = ckeysoff + ckeyssz + endsz;
// sst file layout:
// 0: data blocks 4kB x blkid +bmsoff==blkssz
// bmsoff: blockmetas (bms) +bmssz[0]
// ikeysoff: index keys (ikeys) +ikeyssz[1]
// ioffsoff: index offsets (ioffs) +ioffssz[2]
// ?: endmeta +endsz[3]
// totsz is file size
const ssize_t nwbms = write(fdout, bms, bmssz);
const ssize_t nwanc = kvenc_write(aenc, fdout);
const ssize_t nwiof = write(fdout, ioffs, ioffssz);
const ssize_t nwcpy = kvenc_write(kenc, fdout);
const ssize_t nwmeta = write(fdout, &endmeta, endsz);
const bool wok = (bmssz + ikeyssz + ioffssz + ckeyssz + endsz) == (nwbms + nwanc + nwiof + nwcpy + nwmeta);
// done
fsync(fdout);
close(fdout);
kvenc_destroy(aenc);
kvenc_destroy(kenc);
free(tmp0);
free(tmp1);
free(blkbuf);
free(bms);
free(bmbuf);
free(ioffs);
return wok ? totsz : 0;
}
// }}} sst_build
// sst_iter {{{
struct sst_ptr {
u16 blkid; // xth 4kb-block in the table
u16 keyid; // xth key in the block // MAX == invalid
};
struct sst_iter { // 32 bytes
struct sst * sst;
u32 rank; // pure rank value < nway
struct sst_ptr ptr;
u32 klen;
u32 vlen;
const u8 * kvdata;
};
static int
sst_iter_compare(struct sst_iter * const i1, struct sst_iter * const i2)
{
debug_assert(i1->ptr.keyid != UINT16_MAX);
debug_assert(i2->ptr.keyid != UINT16_MAX);
const u32 len = i1->klen < i2->klen ? i1->klen : i2->klen;
const int cmp = memcmp(i1->kvdata, i2->kvdata, len);
return cmp ? cmp : (((int)i1->klen) - ((int)i2->klen));
}
// i1 must be valid
// key can be NULL
static int
sst_iter_compare_kref(struct sst_iter * const iter, const struct kref * const key)
{
debug_assert(iter->ptr.keyid != UINT16_MAX);
debug_assert(key);
const u32 len = (iter->klen < key->len) ? iter->klen : key->len;
const int cmp = memcmp(iter->kvdata, key->ptr, len);
if (cmp != 0) {
return cmp;
} else {
return ((int)iter->klen) - ((int)key->len);
}
}
static inline bool
sst_iter_match_kref(const struct sst_iter * const i1, const struct kref * const key)
{
debug_assert(i1->ptr.keyid != UINT16_MAX);
return (i1->klen == key->len) && (!memcmp(i1->kvdata, key->ptr, i1->klen));
}
static inline const u8 *
sst_iter_blk_addr(struct sst_iter * const iter)
{
debug_assert(iter->kvdata);
const u64 addr = ((u64)iter->kvdata) >> 12 << 12;
return (const u8 *)addr;
}
static inline void
sst_iter_blk_release(struct sst_iter * const iter)
{
if (iter->kvdata) {
// get page address
const u8 * const blk = sst_iter_blk_addr(iter);
sst_blk_release(iter->sst->rc, blk);
iter->kvdata = NULL;
}
}
// sst only
// call this function when iter has been moved
static void
sst_iter_fix_ptr(struct sst_iter * const iter)
{
const struct sst_blkmeta blkmeta = iter->sst->bms[iter->ptr.blkid];
sst_iter_blk_release(iter);
// will fix kvdata in peek()
if (iter->ptr.keyid >= blkmeta.nkeys) { // beyond the current block
iter->ptr.blkid += blkmeta.nblks;
if (iter->ptr.blkid >= iter->sst->nblks) {
iter->ptr.keyid = UINT16_MAX; // invalid
return;
}
iter->ptr.keyid = 0;
}
}
static void
sst_iter_fix_kv_reuse(struct sst_iter * const iter)
{
// reuse the kvdata and keyid
debug_assert(iter->kvdata);
const u8 * const blk = sst_iter_blk_addr(iter);
const u8 * ptr = sst_blk_get_kvptr(blk, iter->ptr.keyid);
ptr = vi128_decode_u32(ptr, &iter->klen);
iter->kvdata = vi128_decode_u32(ptr, &iter->vlen);
}
// make kvdata current with the iter; acquire blk
// also used by mssty
static void
sst_iter_fix_kv(struct sst_iter * const iter)
{
// don't fix if invalid or already has the ->kvdata
if ((!sst_iter_valid(iter)) || iter->kvdata)
return;
const u8 * blk = sst_blk_acquire(iter->sst, iter->ptr.blkid);
const u8 * ptr = sst_blk_get_kvptr(blk, iter->ptr.keyid);
ptr = vi128_decode_u32(ptr, &iter->klen);
iter->kvdata = vi128_decode_u32(ptr, &iter->vlen);
}
// points to the first key; invalid for empty sst
static inline void
sst_iter_init(struct sst_iter * const iter, struct sst * const sst, const u32 rank)
{
debug_assert(rank < MSST_NWAY);
iter->sst = sst;
iter->rank = rank;
iter->ptr.blkid = sst->nblks;
iter->ptr.keyid = UINT16_MAX;
// klen, vlen are ignored
iter->kvdata = NULL;
}
struct sst_iter *
sst_iter_create(struct sst * const sst)
{
struct sst_iter * const iter = calloc(1, sizeof(*iter));
if (iter == NULL)
return NULL;
sst_iter_init(iter, sst, 0);
return iter;
}
void
sst_iter_seek(struct sst_iter * const iter, const struct kref * const key)
{
// first, find the block
iter->ptr.blkid = sst_search_blkid(iter->sst, key);
if (iter->ptr.blkid < iter->sst->nblks) {
// second, find search in the block
const u8 * const blk = sst_blk_acquire(iter->sst, iter->ptr.blkid);
iter->ptr.keyid = (u16)sst_search_block_ge(blk, key); // ignoring the high bits
sst_blk_release(iter->sst->rc, blk);
sst_iter_fix_ptr(iter);
} else {
debug_assert(iter->ptr.keyid == UINT16_MAX);
}
}
inline void
sst_iter_seek_null(struct sst_iter * const iter)
{
iter->ptr.blkid = 0;
if (iter->sst->nblks) {
iter->ptr.keyid = 0;
sst_iter_fix_ptr(iter);
debug_assert(iter->ptr.keyid != UINT16_MAX);
} else {
iter->ptr.keyid = UINT16_MAX;
}
}
inline bool
sst_iter_valid(struct sst_iter * const iter)
{
return iter->ptr.keyid != UINT16_MAX;
}
// test if iter points to a tombstone
inline bool
sst_iter_ts(struct sst_iter * const iter)
{
sst_iter_fix_kv(iter);
return iter->vlen == SST_VLEN_TS;
}
struct kv *
sst_iter_peek(struct sst_iter * const iter, struct kv * const out)
{
if (!sst_iter_valid(iter))
return NULL;
sst_iter_fix_kv(iter);
const u32 vlen1 = iter->vlen & SST_VLEN_MASK;
const u32 kvlen = iter->klen + vlen1;
struct kv * const ret = out ? out : malloc(sizeof(*ret) + kvlen);
ret->klen = iter->klen;
ret->vlen = iter->vlen;
memcpy(ret->kv, iter->kvdata, kvlen);
return ret;
}
bool
sst_iter_kref(struct sst_iter * const iter, struct kref * const kref)
{
if (!sst_iter_valid(iter))
return false;
sst_iter_fix_kv(iter);