-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathxdb.c
1593 lines (1383 loc) · 40.6 KB
/
xdb.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
#include "xdb.h"
#include "ctypes.h"
#include "kv.h"
#include "wh.h"
#include "sst.h"
#include "blkio.h"
// defs {{{
#define XDB_COMP_CONC ((4)) // maximum compaction threads
#define XDB_REJECT_SIZE_SHIFT ((4)) // reject up to 6.25%
#define WAL_BLKSZ ((PGSZ << 6)) // 256KB
// }}} defs
// struct {{{
struct mt_pair {
union {
void * wmt;
struct wormhole * wmt_wh;
};
union {
void * imt;
struct wormhole * imt_wh;
};
struct mt_pair * next; // next version
};
struct wal {
u8 * buf; // wring_acquire()-ed; change on I/O
u64 bufoff; // in bytes <= WAL_BLKSZ; change on append
u64 woff; // a multiple of 4K (PGSZ); change on I/O
u64 soff; // last sync offset, <= woff; change on sync or every multiple I/O
u64 write_user; // stat on append
u64 write_nbytes; // stat on append
u64 version; // change on compaction
int fds[2]; // fixed
struct wring * wring; // fixed
u64 maxsz; // max file size; fixed
};
// map
struct xdb {
// 1st line
struct mt_pair * volatile mt_view;
u64 padding1[7];
u64 mtsz; // memtable size; frequently changed by writers
struct wal wal; // frequently changed by writers
// not actively accessed
void * mt1;
void * mt2;
u32 nr_workers;
u32 co_per_worker;
char * worker_cores;
pthread_t comp_pid;
// read-only
u64 max_mtsz;
u64 max_rejsz;
struct qsbr * qsbr;
struct msstz * z;
struct mt_pair mt_views[4];
int logfd;
volatile bool running;
bool tags; // use tags
bool padding2[2];
u64 padding3[7];
spinlock lock;
};
struct xdb_ref {
struct xdb * xdb;
struct msstv * v;
struct msstv_ref * vref;
union {
void * imt_ref;
struct wormhole * imt_ref_raw;
};
union {
void * wmt_ref;
struct wormref * wmt_ref_wh;
};
union {
struct mt_pair * mt_view;
struct qsbr_ref qref;
};
};
struct xdb_iter {
struct xdb_ref * db_ref;
struct mt_pair * mt_view; // the version used to create the miter
struct miter * miter;
struct coq * coq_parked; // parked coq
};
// }}} struct
// misc {{{
static const struct kvmap_api * wmt_api = &kvmap_api_wormhole;
static const struct kvmap_api * imt_api = &kvmap_api_whunsafe;
static inline void
xdb_lock(struct xdb * const xdb)
{
spinlock_lock(&xdb->lock);
}
static inline void
xdb_unlock(struct xdb * const xdb)
{
spinlock_unlock(&xdb->lock);
}
static inline bool
xdb_mt_wal_full(struct xdb * const xdb)
{
// mt is full OR wal is full
// when this is true: writers must wait; compaction should start
return (xdb->mtsz >= xdb->max_mtsz) || (xdb->wal.woff >= xdb->wal.maxsz);
}
// }}} misc
// wal {{{
// call with lock, see below
static void
wal_flush(struct wal * const wal)
{
if (wal->bufoff == 0)
return;
const size_t wsize = bits_round_up(wal->bufoff, 12); // whole pages
debug_assert(wsize <= WAL_BLKSZ);
memset(wal->buf + wal->bufoff, 0, wsize - wal->bufoff);
wring_write_partial(wal->wring, (off_t)wal->woff, wal->buf, 0, (u32)wsize);
wal->buf = wring_acquire(wal->wring);
debug_assert(wal->buf);
wal->bufoff = 0;
wal->woff += wsize;
wal->write_nbytes += wsize;
#define XDB_SYNC_SIZE ((1lu<<26)) // 64MB
if ((wal->woff - wal->soff) >= XDB_SYNC_SIZE) {
// queue the fsync but does not wait for completion (not required by a user)
wring_fsync(wal->wring);
wal->soff = wal->woff;
}
}
// must call with lock
static void
wal_flush_sync(struct wal * const wal)
{
wal_flush(wal);
if (wal->woff != wal->soff) {
wring_fsync(wal->wring);
wal->soff = wal->woff;
}
}
static void
wal_io_complete(struct wal * const wal)
{
wring_flush(wal->wring);
}
static void
wal_flush_sync_wait(struct wal * const wal)
{
wal_flush_sync(wal);
// wait for completion
wal_io_complete(wal);
}
// must call with xdb->lock locked
static void
wal_append(struct wal * const wal, const struct kv * const kv)
{
debug_assert(kv);
// kv+crc32c
const size_t estsz = sst_kv_vi128_estimate(kv) + sizeof(u32);
if ((estsz + wal->bufoff) > WAL_BLKSZ)
wal_flush(wal);
debug_assert(wal->buf);
// write kv
u8 * const ptr = sst_kv_vi128_encode(wal->buf + wal->bufoff, kv);
// write the crc of the key after the value
*(u32 *)ptr = kv->hashlo;
wal->bufoff += estsz;
debug_assert(wal->bufoff <= WAL_BLKSZ);
}
static bool
wal_open(struct wal * const wal, const char * const path)
{
char * const fn = malloc(strlen(path) + 10);
if (!fn)
return false;
sprintf(fn, "%s/wal1", path);
const int fd1 = open(fn, O_RDWR|O_CREAT, 00644);
if (fd1 < 0) {
fprintf(stderr, "%s open %s failed\n", __func__, fn);
goto fail_open1;
}
wal->fds[0] = fd1;
sprintf(fn, "%s/wal2", path);
const int fd2 = open(fn, O_RDWR|O_CREAT, 00644);
if (fd2 < 0) {
fprintf(stderr, "%s open %s failed\n", __func__, fn);
goto fail_open2;
}
wal->fds[1] = fd2;
// fd can be replaced during recovery
wal->wring = wring_create(fd1, WAL_BLKSZ, 32);
if (!wal->wring)
goto fail_wring;
wal->buf = wring_acquire(wal->wring);
if (!wal->buf)
goto fail_buf;
free(fn);
return true;
fail_buf:
wring_destroy(wal->wring);
wal->wring = NULL;
fail_wring:
close(fd2);
fail_open2:
close(fd1);
fail_open1:
free(fn);
return false;
}
// must call with lock
// return the old wal size
static u64
wal_switch(struct wal * const wal, const u64 version)
{
wal_flush_sync_wait(wal);
const u64 woff0 = wal->woff;
// bufoff already set to 0
wal->woff = 0;
wal->soff = 0;
// swap fds
const int fd1 = wal->fds[0];
wal->fds[0] = wal->fds[1];
wal->fds[1] = fd1;
wring_update_fd(wal->wring, wal->fds[0]);
memcpy(wal->buf, &version, sizeof(version));
wal->bufoff = sizeof(version);
wal->version = version;
return woff0;
}
static void
wal_close(struct wal * const wal)
{
wal_flush_sync_wait(wal);
wring_destroy(wal->wring); // destroy will call wring_flush
close(wal->fds[0]);
close(wal->fds[1]);
}
// }}} wal
// kv-alloc {{{
// allocate one extra byte for refcnt
static struct kv *
xdb_new_ts(const struct kref * const kref)
{
const size_t sz = sizeof(struct kv) + kref->len; // no value
struct kv * const new = malloc(sz);
debug_assert(new);
new->klen = kref->len;
new->vlen = SST_VLEN_TS;
memcpy(new->kv, kref->ptr, kref->len);
new->hash = kv_crc32c_extend(kref->hash32); // why fix this?
return new;
}
static struct kv *
xdb_dup_kv(const struct kv * const kv)
{
const size_t sz = sst_kv_size(kv);
struct kv * const new = malloc(sz);
debug_assert(new);
memcpy(new, kv, sz);
return new;
}
// }}} kv-alloc
// xdb_ref {{{
static inline void
xdb_ref_enter(struct xdb_ref * const ref)
{
if (ref->wmt_ref)
wmt_api->resume(ref->wmt_ref);
}
static inline void
xdb_ref_leave(struct xdb_ref * const ref)
{
if (ref->wmt_ref)
wmt_api->park(ref->wmt_ref);
}
static void
xdb_unref_all(struct xdb_ref * const ref)
{
if (ref->v) {
msstv_unref(ref->vref);
msstz_putv(ref->xdb->z, ref->v);
ref->v = NULL;
ref->vref = NULL;
}
if (ref->imt_ref) {
kvmap_unref(imt_api, ref->imt_ref);
ref->imt_ref = NULL;
}
if (ref->wmt_ref) {
kvmap_unref(wmt_api, ref->wmt_ref);
ref->wmt_ref = NULL;
}
cpu_cfence();
ref->mt_view = NULL;
// don't need to clear memory
}
// must already released everything when calling this function
static void
xdb_ref_all(struct xdb_ref * const ref)
{
ref->mt_view = ref->xdb->mt_view;
ref->v = msstz_getv(ref->xdb->z);
ref->vref = msstv_ref(ref->v);
ref->wmt_ref = kvmap_ref(wmt_api, ref->mt_view->wmt);
debug_assert(ref->wmt_ref);
if (ref->mt_view->imt) {
ref->imt_ref = kvmap_ref(imt_api, ref->mt_view->imt);
debug_assert(ref->imt_ref);
}
xdb_ref_leave(ref);
}
static inline void
xdb_ref_update_version(struct xdb_ref * const ref)
{
if (unlikely(ref->xdb->mt_view != ref->mt_view)) {
xdb_unref_all(ref);
xdb_ref_all(ref);
}
}
struct xdb_ref *
xdb_ref(struct xdb * const xdb)
{
struct xdb_ref * ref = calloc(1, sizeof(*ref));
ref->xdb = xdb;
qsbr_register(xdb->qsbr, &ref->qref);
xdb_ref_all(ref);
return ref;
}
struct xdb *
xdb_unref(struct xdb_ref * const ref)
{
struct xdb * xdb = ref->xdb;
xdb_unref_all(ref);
qsbr_unregister(xdb->qsbr, &ref->qref);
free(ref);
return xdb;
}
// }}} xdb_ref
// reinsert {{{
struct xdb_reinsert_merge_ctx {
struct kv * kv;
struct xdb * xdb;
};
static struct kv *
xdb_mt_reinsert_func(struct kv * const kv0, void * const priv)
{
struct xdb_reinsert_merge_ctx * const ctx = priv;
if (kv0 == NULL) {
struct kv * const ret = xdb_dup_kv(ctx->kv);
debug_assert(ret);
const size_t incsz = sst_kv_size(ret);
struct xdb * const xdb = ctx->xdb;
xdb_lock(xdb);
xdb->mtsz += incsz;
wal_append(&xdb->wal, ret);
xdb_unlock(xdb);
return ret;
} else { // don't overwrite
return kv0;
}
}
// insert rejected keys from imt into wmt; vlen == 1 marks a rejected partition
static void
xdb_reinsert_rejected(struct xdb * const xdb, void * const wmt_map, void * const imt_map, struct kv ** const anchors)
{
void * const wmt_ref = kvmap_ref(wmt_api, wmt_map);
void * const rej_ref = kvmap_ref(imt_api, imt_map);
void * const rej_iter = imt_api->iter_create(rej_ref);
struct xdb_reinsert_merge_ctx ctx = {.xdb = xdb}; // only use newkv and success
for (u32 i = 0; anchors[i]; i++) {
if (anchors[i]->vlen == 0) // skip accepted partitions
continue;
// find the end of the current partition
if (anchors[i+1]) {
struct kv * const kz = anchors[i+1];
struct kref krefz;
kref_ref_kv_hash32(&krefz, kz);
imt_api->iter_seek(rej_iter, &krefz);
}
// peek and next does not make any copies; see mm_mt.out
struct kv * const end = anchors[i+1] ? imt_api->iter_peek(rej_iter, NULL) : NULL;
struct kv * const k0 = anchors[i];
struct kref kref0;
kref_ref_kv_hash32(&kref0, k0);
imt_api->iter_seek(rej_iter, &kref0);
while (imt_api->iter_valid(rej_iter)) {
struct kv * const curr = imt_api->iter_next(rej_iter, NULL); // no copy
if (curr == end)
break;
if (!curr)
debug_die();
ctx.kv = curr;
bool s = kvmap_kv_merge(wmt_api, wmt_ref, curr, xdb_mt_reinsert_func, &ctx);
if (!s)
debug_die();
}
}
imt_api->iter_destroy(rej_iter);
kvmap_unref(imt_api, rej_ref);
kvmap_unref(wmt_api, wmt_ref);
}
// }}} reinsert
// comp {{{
// compaction process:
// -** lock(xdb)
// - switch memtable mode from wmt-only to wmt+imt (very quick)
// - sync-flush and switch the log
// -** unlock(xdb)
// - qsbr_wait for users to leave the now imt
// - save an old version until the new version is ready for access
// - call msstz_comp
// - release the data in WAL
// - for each rejected key, if it's still fresh, reinsert it to wmt and append it to the new WAL
// -** lock(xdb)/unlock(xdb) for each fresh rejected key
// -** lock(xdb)
// - flush the new WAL and send an asynchronous fsync (non-block)
// -** unlock(xdb)
// - free the anchors array and release the old version
// - switch to the normal mode (wmt only) because keys in the imt are either in wmt or partitions
// - qsbr_wait for users to leave the imt
// - clean the imt (will be used as the new wmt in the next compaction); TODO: this is expensive
// -** lock(xdb)
// - wait for the fsync completion; this secures the rejected keys in the new WAL
// -** unlock(xdb)
// - truncate the old WAL; all its data have been safely stored in z or the new WAL
// - done
static void
xdb_do_comp(struct xdb * const xdb, const u64 max_rejsz)
{
const double t0 = time_sec();
xdb_lock(xdb);
// switch mt_view
struct mt_pair * const v_comp = xdb->mt_view->next;
xdb->mt_view = v_comp; // wmt => wmt+imt
// switch the log
const u64 walsz0 = wal_switch(&xdb->wal, msstz_version(xdb->z) + 1); // match the next version
const u64 mtsz0 = xdb->mtsz;
xdb->mtsz = 0; // reset mtsz while holding the lock
xdb_unlock(xdb);
void * const wmt_map = v_comp->wmt;
void * const imt_map = v_comp->imt;
// unlocked
qsbr_wait(xdb->qsbr, (u64)v_comp);
struct msstv * const oldv = msstz_getv(xdb->z); // keep oldv alive
const double t_prep = time_sec();
// compaction
msstz_comp(xdb->z, imt_api, imt_map, xdb->nr_workers, xdb->co_per_worker, max_rejsz);
const double t_comp = time_sec();
struct kv ** const anchors = msstv_anchors(oldv);
xdb_reinsert_rejected(xdb, wmt_map, imt_map, anchors);
const double t_reinsert = time_sec();
// flush and sync: the old WAL will be truncated
xdb_lock(xdb);
wal_flush_sync(&xdb->wal);
xdb_unlock(xdb);
free(anchors);
msstz_putv(xdb->z, oldv);
struct mt_pair * const v_normal = v_comp->next;
xdb->mt_view = v_normal;
qsbr_wait(xdb->qsbr, (u64)v_normal);
const double t_wait2 = time_sec();
// after qsbr_wait
imt_api->clean(imt_map);
const double t_clean = time_sec();
xdb_lock(xdb);
wal_io_complete(&xdb->wal); // wait for the sync to complete
xdb_unlock(xdb);
// truncate old WAL after the io completion
logger_printf(xdb->logfd, "%s discard wal fd %d sz0 %lu\n", __func__, xdb->wal.fds[1], walsz0);
ftruncate(xdb->wal.fds[1], 0);
fdatasync(xdb->wal.fds[1]);
const double t_sync = time_sec();
// I/O stats
const size_t usr_write = xdb->wal.write_user;
const size_t wal_write = xdb->wal.write_nbytes;
const size_t sst_write = msstz_stat_writes(xdb->z);
const size_t sst_read = msstz_stat_reads(xdb->z); // read I/O (>> disk I/O). TODO: count ckeys read I/O
// WA, RA
const double sys_wa = (double)(wal_write + sst_write) / (double)usr_write;
const double comp_ra = (double)sst_read / (double)usr_write;
const u64 mb = 1lu<<20;
logger_printf(xdb->logfd, "%s mtsz %lu walsz %lu write-mb usr %lu wal %lu sst %lu WA %.4lf comp-read-mb %lu RA %.4lf\n",
__func__, mtsz0, walsz0, usr_write/mb, wal_write/mb, sst_write/mb, sys_wa, sst_read/mb, comp_ra);
logger_printf(xdb->logfd, "%s times-ms total %.3lf prep %.3lf comp %.3lf reinsert %.3lf wait2 %.3lf clean %.3lf sync %.3lf\n",
__func__, t_clean-t0, t_prep-t0, t_comp-t_prep, t_reinsert-t_comp, t_wait2-t_reinsert, t_clean-t_wait2, t_sync-t_clean);
}
static void
xdb_compaction_worker_pin(struct xdb * const xdb)
{
if (!strcmp(xdb->worker_cores, "auto")) { // auto detect
u32 cores[64];
const u32 ncores = process_getaffinity_list(64, cores);
if (ncores < xdb->nr_workers)
logger_printf(xdb->logfd, "%s WARNING: too few cores: %u cores < %u workers\n", __func__, ncores, xdb->nr_workers);
const u32 nr = (ncores < XDB_COMP_CONC) ? ncores : XDB_COMP_CONC;
if (nr == 0) { // does this really happen?
logger_printf(xdb->logfd, "%s no cores\n", __func__);
} else if (nr < ncores) { // need to update affinity list
u32 cpus[XDB_COMP_CONC];
for (u32 i = 0; i < nr; i++)
cpus[i] = cores[ncores - nr + i];
thread_setaffinity_list(nr, cpus);
logger_printf(xdb->logfd, "%s cpus %u first %u (auto)\n", __func__, nr, cpus[0]);
} else {
logger_printf(xdb->logfd, "%s inherited\n", __func__);
}
} else if (strcmp(xdb->worker_cores, "dont")) { // not "dont"
char ** const tokens = strtoks(xdb->worker_cores, ",");
u32 nr = 0;
u32 cpus[XDB_COMP_CONC];
while ((nr < XDB_COMP_CONC) && tokens[nr]) {
cpus[nr] = a2u32(tokens[nr]);
nr++;
}
free(tokens);
thread_setaffinity_list(nr, cpus);
logger_printf(xdb->logfd, "%s pinning cpus %u arg %s\n", __func__, nr, xdb->worker_cores);
} else {
logger_printf(xdb->logfd, "%s unpinned (dont)\n", __func__);
}
thread_set_name(pthread_self(), "xdb_comp");
}
static void *
xdb_compaction_worker(void * const ptr)
{
struct xdb * const xdb = (typeof(xdb))ptr;
xdb_compaction_worker_pin(xdb);
while (true) {
// while running and does not need compaction
const u64 t0 = time_nsec();
// wait until (1) the mt is full or (2) the log file is full
while (xdb->running && !xdb_mt_wal_full(xdb))
usleep(10); // 1ms
if (!xdb->running)
break;
const u64 dt = time_diff_nsec(t0);
logger_printf(xdb->logfd, "%s compaction worker wait-ms %lu\n", __func__, dt / 1000000);
xdb_do_comp(xdb, xdb->max_rejsz);
}
pthread_exit(NULL);
}
// }}} comp
// recover {{{
struct wal_kv {
struct kref kref;
u32 vlen;
u32 kvlen;
};
// Format: [klen-vi128, vlen-vi128, key-data, value-data, crc32c]
// return the ptr after the decoded data if successful, otherwise return NULL
static const u8 *
wal_vi128_decode(const u8 * ptr, const u8 * const end, struct wal_kv * const wal_kv)
{
const u32 safelen = (u32)((end - ptr) < 10 ? (end - ptr) : 10);
u32 count = 0;
for (u32 i = 0; i < safelen; i++) {
if ((ptr[i] & 0x80) == 0)
count++;
}
// can decode klen and vlen
if (count < 2)
return NULL;
u32 klen, vlen;
ptr = vi128_decode_u32(ptr, &klen);
ptr = vi128_decode_u32(ptr, &vlen);
const u32 kvlen = klen + (vlen & SST_VLEN_MASK);
// size
if ((ptr + kvlen + sizeof(u32)) > end)
return NULL;
// checksum
const u32 sum1 = kv_crc32c(ptr, klen);
const u32 sum2 = *(const u32 *)(ptr + kvlen);
if (sum1 != sum2)
return NULL;
wal_kv->kref.len = klen;
wal_kv->kref.hash32 = sum2;
wal_kv->kref.ptr = ptr;
wal_kv->vlen = vlen;
wal_kv->kvlen = kvlen;
return ptr + kvlen + sizeof(u32);
}
struct xdb_recover_merge_ctx {
struct kv * newkv;
u64 mtsz;
};
// kv_merge_func
// call with lock
static struct kv *
xdb_recover_update_func(struct kv * const kv0, void * const priv)
{
struct xdb_recover_merge_ctx * const ctx = priv;
const size_t newsz = sst_kv_size(ctx->newkv);
const size_t oldsz = kv0 ? sst_kv_size(kv0) : 0;
const size_t diffsz = newsz - oldsz;
debug_assert(ctx->mtsz >= oldsz);
ctx->mtsz += diffsz;
return ctx->newkv;
}
// use xdb->mt1, xdb->mtsz, xdb->z (for loggging)
static u64
xdb_recover_fd(struct xdb * const xdb, const int fd)
{
const u64 fsize = fdsize(fd);
if (!fsize)
return 0;
u8 * const mem = mmap(NULL, fsize, PROT_READ, MAP_PRIVATE, fd, 0);
if (mem == MAP_FAILED)
return 0; // abort recovery
void * const wmt_ref = wmt_api->ref(xdb->mt1);
const u8 * iter = mem + sizeof(u64); // skip the version
const u8 * const end = mem + fsize;
u64 nkeys = 0;
struct xdb_recover_merge_ctx ctx = {.mtsz = xdb->mtsz};
while ((iter < end) && ((*iter) == 0))
iter++;
while (iter < end) {
struct wal_kv wal_kv;
const u8 * const iter1 = wal_vi128_decode(iter, end, &wal_kv);
// stop
if (!iter1)
break;
// insert
struct kv * const kv = malloc(sizeof(struct kv) + wal_kv.kvlen);
debug_assert(kv);
kv->klen = wal_kv.kref.len;
kv->vlen = wal_kv.vlen;
kv->hash = kv_crc32c_extend(wal_kv.kref.hash32);
memcpy(kv->kv, wal_kv.kref.ptr, wal_kv.kvlen);
ctx.newkv = kv;
bool s = wmt_api->merge(wmt_ref, &wal_kv.kref, xdb_recover_update_func, &ctx);
if (!s)
debug_die();
iter = iter1;
nkeys++;
// skip padding zeroes
while ((iter < end) && ((*iter) == 0))
iter++;
}
xdb->mtsz = ctx.mtsz;
wmt_api->unref(wmt_ref);
munmap(mem, fsize);
const u64 rsize = (u64)(iter - mem);
logger_printf(xdb->logfd, "%s fd %d fsize %lu rsize %lu nkeys %lu\n", __func__, fd, fsize, rsize, nkeys);
return rsize;
}
// xdb must have everything in wal initialized as zero
static void
xdb_wal_recover(struct xdb * const xdb)
{
struct wal * const wal = &xdb->wal;
u64 vs[2] = {};
for (u32 i = 0; i < 2; i++) {
if (fdsize(wal->fds[i]) > sizeof(u64))
pread(wal->fds[i], &vs[i], sizeof(vs[i]), 0);
}
const bool two = vs[0] && vs[1]; // both are non-zero
const u64 v0 = msstz_version(xdb->z);
debug_assert(v0);
logger_printf(xdb->logfd, "%s wal1 %lu wal2 %lu zv %lu\n", __func__, vs[0], vs[1], v0);
// will recover fds[1] fist, then fds[0] if necessary, then keep using fds[0] since it's probably still half-full
if (vs[0] < vs[1]) { // swap
logger_printf(xdb->logfd, "%s use wal2 %lu\n", __func__, vs[1]);
wal->version = vs[1];
const int fd1 = wal->fds[0];
wal->fds[0]= wal->fds[1];
wal->fds[1] = fd1;
wring_update_fd(wal->wring, wal->fds[0]);
} else {
logger_printf(xdb->logfd, "%s use wal1 %lu\n", __func__, vs[0]);
wal->version = vs[0];
}
debug_assert(wal->wring && wal->buf);
if (two) { // do compaction now
if (vs[0] == vs[1])
debug_die(); // wals must have differnet versions
const u64 r1 = xdb_recover_fd(xdb, wal->fds[1]); // scan the older
const u64 r0 = xdb_recover_fd(xdb, wal->fds[0]); // scan the newer
// compact everything, no rejections
msstz_comp(xdb->z, imt_api, xdb->mt1, xdb->nr_workers, xdb->co_per_worker, 0);
// now the new version is safe
ftruncate(wal->fds[1], 0);
fdatasync(wal->fds[1]);
ftruncate(wal->fds[0], 0);
fdatasync(wal->fds[0]);
imt_api->clean(xdb->mt1);
xdb->mtsz = 0;
// a fresh start
const u64 v1 = msstz_version(xdb->z);
memcpy(wal->buf, &v1, sizeof(v1));
wal->bufoff = sizeof(v1);
wal->version = v1;
logger_printf(xdb->logfd, "%s wal comp zv0 %lu zv1 %lu rec %lu %lu mtsz %lu fd0 %d\n",
__func__, v0, v1, r1, r0, xdb->mtsz, wal->fds[0]);
} else { // one or no valid logs
const u64 rsize = xdb_recover_fd(xdb, wal->fds[0]);
if (rsize == 0) { // set version for an empty wal file
memcpy(wal->buf, &v0, sizeof(v0));
wal->bufoff = sizeof(v0);
wal->version = v0;
logger_printf(xdb->logfd, "%s wal empty v %lu mtsz %lu fd %d\n", __func__, v0, xdb->mtsz, wal->fds[0]);
} else { // reuse the existing wal
// only one WAL: WAL version <= Z version
if (wal->version > v0)
debug_die();
// woff must be aligned
wal->woff = bits_round_up(rsize, 12);
if (wal->woff > rsize) { // need to fill the gap with zeroes
const u64 nr = wal->woff - rsize;
u8 zeroes[PGSZ];
memset(zeroes, 0, nr);
pwrite(wal->fds[0], zeroes, nr, (off_t)rsize);
fdatasync(wal->fds[0]);
}
logger_printf(xdb->logfd, "%s wal rsize %lu woff %lu mtsz %lu fd %d\n", __func__, rsize, wal->woff, xdb->mtsz, wal->fds[0]);
}
ftruncate(wal->fds[1], 0); // truncate the second wal anyway
fdatasync(wal->fds[1]);
}
wal->soff = wal->woff;
}
// }}} recover
// open close {{{
struct xdb *
xdb_open(const char * const dir, const size_t cache_size_mb, const size_t mt_size_mb, const size_t wal_size_mb,
const bool ckeys, const bool tags, const u32 nr_workers, const u32 co_per_worker, const char * const worker_cores)
{
mkdir(dir, 00755);
struct xdb * const xdb = yalloc(sizeof(*xdb));
if (!xdb)
return NULL;
memset(xdb, 0, sizeof(*xdb));
const struct kvmap_mm mm_mt = { .in = kvmap_mm_in_noop, .out = kvmap_mm_out_noop, .free = kvmap_mm_free_free};
xdb->mt1 = wormhole_create(&mm_mt);
xdb->mt2 = wormhole_create(&mm_mt);
xdb->mt_views[0] = (struct mt_pair){.wmt = xdb->mt1, .next = &xdb->mt_views[1]};
xdb->mt_views[1] = (struct mt_pair){.wmt = xdb->mt2, .imt = xdb->mt1, .next = &xdb->mt_views[2]};
xdb->mt_views[2] = (struct mt_pair){.wmt = xdb->mt2, .next = &xdb->mt_views[3]};
xdb->mt_views[3] = (struct mt_pair){.wmt = xdb->mt1, .imt = xdb->mt2, .next = &xdb->mt_views[0]};
xdb->mt_view = xdb->mt_views; // [0]
xdb->z = msstz_open(dir, cache_size_mb, ckeys, tags);
xdb->qsbr = qsbr_create();
// just a warning
if ((mt_size_mb * 2) > wal_size_mb)
fprintf(stderr, "%s wal_size < mt_size*2\n", __func__);
// sz
xdb->max_mtsz = mt_size_mb << 20;
xdb->wal.maxsz = wal_size_mb << 20;
xdb->max_rejsz = xdb->max_mtsz >> XDB_REJECT_SIZE_SHIFT;
spinlock_init(&xdb->lock);
xdb->nr_workers = nr_workers; // internal parallelism
xdb->co_per_worker = co_per_worker;
xdb->worker_cores = strdup(worker_cores);
xdb->logfd = msstz_logfd(xdb->z);
xdb->running = true;
const bool wal_ok = wal_open(&xdb->wal, dir);
const bool all_ok = xdb->mt1 && xdb->mt2 && xdb->z && xdb->qsbr && wal_ok;
if (all_ok) {
xdb_wal_recover(xdb); // no errors in recover
// start the main compaction worker
pthread_create(&xdb->comp_pid, NULL, xdb_compaction_worker, xdb); // should return 0
return xdb;
} else { // failed
if (xdb->mt1)
wmt_api->destroy(xdb->mt1);
if (xdb->mt2)
wmt_api->destroy(xdb->mt2);
if (xdb->z)
msstz_destroy(xdb->z);
if (xdb->qsbr)
qsbr_destroy(xdb->qsbr);
if (wal_ok)
wal_close(&xdb->wal);
free(xdb);
return NULL;
}
}
// destroy
void
xdb_close(struct xdb * xdb)
{
xdb->running = false;
pthread_join(xdb->comp_pid, NULL);
// assume all users have left
qsbr_destroy(xdb->qsbr);
msstz_destroy(xdb->z);
wal_close(&xdb->wal);
wmt_api->destroy(xdb->mt1);
wmt_api->destroy(xdb->mt2);
free(xdb->worker_cores);
free(xdb);
}
// }}} open close
// get probe {{{
struct xdb_get_info {
struct kv * out;
struct kv * ret;
};
static void
xdb_inp_get(struct kv * const kv, void * const priv)
{
// copy when looking at this key
// to avoid consistency problems after get returns
struct xdb_get_info * const info = (typeof(info))priv;
if (kv && kv->vlen != SST_VLEN_TS) {
info->ret = kvmap_mm_out_ts(kv, info->out);
} else {
info->ret = NULL;
}
}
struct kv *
xdb_get(struct xdb_ref * const ref, const struct kref * const kref, struct kv * const out)
{
xdb_ref_update_version(ref);
xdb_ref_enter(ref);
// wmt
struct xdb_get_info info = {out, NULL};
if (wmt_api->inpr(ref->wmt_ref, kref, xdb_inp_get, &info)) {
xdb_ref_leave(ref);
return info.ret;
}
xdb_ref_leave(ref);
// imt
if (ref->imt_ref) {
if (imt_api->inpr(ref->imt_ref, kref, xdb_inp_get, &info))
return info.ret;
}
// not in log, maybe in ssts
return msstv_get_ts(ref->vref, kref, out);
}
static void
xdb_inp_probe(struct kv * const kv, void * const priv)
{
// copy when looking at this key
// to avoid consistency problems after get returns
*(bool *)priv = kv && (kv->vlen != SST_VLEN_TS);
}
bool
xdb_probe(struct xdb_ref * const ref, const struct kref * const kref)
{
xdb_ref_update_version(ref);
xdb_ref_enter(ref);
bool is_valid;
if (wmt_api->inpr(ref->wmt_ref, kref, xdb_inp_probe, &is_valid)) {
xdb_ref_leave(ref);
return is_valid;
}
xdb_ref_leave(ref);
if (ref->imt_ref) {
if (imt_api->inpr(ref->imt_ref, kref, xdb_inp_probe, &is_valid))
return is_valid;
}
return msstv_probe_ts(ref->vref, kref);
}
// }}} get probe
// put del {{{
// this is so long
static void
xdb_write_enter(struct xdb_ref * const ref)
{
struct xdb * const xdb = ref->xdb;
while (xdb_mt_wal_full(xdb)) {
xdb_ref_update_version(ref);
usleep(10);
}
}
struct xdb_mt_merge_ctx {
struct kv * newkv;
struct xdb * xdb;
struct mt_pair * mt_view;