-
Notifications
You must be signed in to change notification settings - Fork 1
/
shardmap.cc
1641 lines (1421 loc) · 44.5 KB
/
shardmap.cc
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
/*
* Shardmap fast lightweight key value store
* (c) 2012 - 2019, Daniel Phillips
* License: GPL v3
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include "shardmap.h"
extern "C" {
#include "debug.h"
#include "utility.h"
#include "pmem.h"
}
#define warn trace_on
#define tracedump_on hexdump
#define tracedump trace_off
#define trace_geom trace_on
#define trace trace_off
#ifndef SIDELOG
#define SIDELOG
#endif
namespace fixsize {
#include "recops.c"
struct recops recops = {
.init = rb_init,
.big = rb_big,
.more = rb_more,
.dump = rb_dump,
.key = rb_key,
.check = rb_check,
.lookup = rb_lookup,
.varlookup = rb_varlookup,
.create = rb_create,
.remove = rb_remove,
.walk = rb_walk,
};
}
void errno_exit(unsigned exitcode);
void error_exit(unsigned exitcode, const char *reason, ...);
void hexdump(const void *data, unsigned size);
enum {PAGEBITS = 12, PAGE_SIZE = 1 << PAGEBITS};
enum {countshift = 2};
static const cell_t high64 = 1LL << 63;
static unsigned fls(unsigned n)
{
unsigned bits = 32;
if (!(n & 0xffff0000u)) { n <<= 16; bits -= 16; }
if (!(n & 0xff000000u)) { n <<= 8; bits -= 8; }
if (!(n & 0xf0000000u)) { n <<= 4; bits -= 4; }
if (!(n & 0xc0000000u)) { n <<= 2; bits -= 2; }
if (!(n & 0x80000000u)) { n <<= 1; bits -= 1; }
if (!n) bits -= 1;
return bits;
}
static unsigned log2_ceiling(unsigned n) { return fls(n - 1); }
static fixed8 mul8(fixed8 a, unsigned b) { return (a * b) >> 8; }
static u64 power2(unsigned power, u64 value) { return value << power; }
enum {split_order = 0, totalentries_order = 26};
#include <algorithm> // min
#include <utility> // swap
#include <string>
/* Variable width field packing */
typedef cell_t duo_t1;
typedef loc_t duo_t2;
static struct duopack new_duo(const unsigned bits0) { return {bitmask(bits0), bits0}; }
static u64 duo_pack(const struct duopack *duo, const duo_t1 a, const duo_t2 b) { return (power2(duo->bits0, b)) | a; }
static duo_t1 duo_first(const struct duopack *duo, const u64 packed) { return packed & duo->mask; }
static duo_t2 duo_second(const struct duopack *duo, const u64 packed) { return packed >> duo->bits0; }
static void duo_unpack(const struct duopack *duo, const u64 packed, duo_t1 &a, duo_t2 &b) { a = duo_first(duo, packed); b = duo_second(duo, packed); }
typedef u32 tri_t1;
typedef u32 tri_t2;
typedef u64 tri_t3;
struct tripack new_tri(const unsigned bits0, const unsigned bits1) { return {bitmask(bits0 + bits1), bits0, bits1}; }
static u64 tri_pack(const struct tripack *tri, const tri_t1 a, const tri_t2 b, const tri_t3 c) { return power2(tri->bits0 + tri->bits1, c) | ((u64)b << tri->bits0) | a; }
static tri_t1 tri_first(const struct tripack *tri, const u64 packed) { return packed & (tri->mask2 >> tri->bits1); }
static tri_t2 tri_second(const struct tripack *tri, const u64 packed) { return (packed & tri->mask2) >> tri->bits0; }
static tri_t3 tri_third(const struct tripack *tri, const u64 packed) { return packed >> (tri->bits0 + tri->bits1); }
static void tri_unpack(const struct tripack *tri, const u64 packed, tri_t1 &a, tri_t2 &b, tri_t3 &c) { a = tri_first(tri, packed); b = tri_second(tri, packed); c = tri_third(tri, packed); }
static void tri_set_first(const struct tripack *tri, u64 &packed, const tri_t1 value) { packed = (packed & ~(tri->mask2 >> tri->bits1)) | value; }
/* Persistent memory */
#ifdef SIDELOG
struct sidelog
{
u64 duo;
u32 at;
u8 ix; // countmap index
u8 rx; // relative tier index
u8 flags;
u8 unused;
};
enum {sidelog_size = logsize * sizeof(struct sidelog)};
#endif
/* Memory layout setup */
void layout::do_maps(int fd)
{
unsigned count = map.size();
if (verbose)
printf("%i regions:\n", count);
loff_t pos = 0;
for (unsigned i = 0; i < count; pos += map[i++].size) {
if (!map[i].size)
continue;
pos = align(pos, map[i].align);
if (verbose)
printf("%i: %lx/%lx\n", i, pos, map[i].size);
if (!map[i].pos)
continue;
*map[i].pos = pos;
}
size = align(pos, PAGEBITS);
if (verbose)
printf("*: %lx\n", size);
void *base;
if (single_map)
base = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
pos = 0;
for (unsigned i = 0; i < count; pos += map[i++].size) {
if (map[i].size) {
if (!map[i].mem)
continue;
if (single_map) {
*map[i].mem = (char *)base + pos;
continue;
}
void *mem = mmap(NULL,
align(map[i].size, PAGEBITS),
PROT_READ|PROT_WRITE,
MAP_SHARED, fd, pos);
if (mem == MAP_FAILED)
errno_exit(1);
*map[i].mem = mem;
}
}
if (ftruncate(fd, size))
errno_exit(1);
}
void layout::redo_maps(int fd)
{
assert(single_map);
if (munmap(*map[0].mem, size) == -1)
errno_exit(1);
do_maps(fd);
}
tier::tier(const struct header &header, const struct header::tierhead &tierhead) :
duo(new_duo(tierhead.sigbits)),
mapbits(tierhead.mapbits),
stridebits(tierhead.stridebits),
locbits(tierhead.locbits),
sigbits(tierhead.sigbits),
countbuf(tierhead.is_empty() ? NULL : getbuf(power2(mapbits + countshift))),
countmap(NULL),
shardmap(NULL),
countmap_pos(0), shardmap_pos(0)
{}
#if 0
tier::~tier()
{
trace_off("destroy %p countbuf %p", this, countbuf);
}
#endif
unsigned tier::shards() const { return power2(mapbits); }
bool tier::is_empty() const { return !stridebits; }
void tier::cleanup()
{
trace("free countbuf %p", countbuf);
free(countbuf);
countbuf = NULL;
}
count_t *tier::getbuf(unsigned size)
{
count_t *buf = (count_t *)aligned_alloc(size, size); // check null!!!
trace("tier %p countbuf %p", this, buf);
memset(buf, 0, size);
return buf;
}
cell_t *tier::at(unsigned ix, unsigned i) const
{
assert(ix < 1U << mapbits);
assert(i < 1U << (stridebits - cellshift));
return shardmap + power2(stridebits - cellshift, ix) + i;
}
void tier::store(unsigned ix, unsigned i, cell_t entry) const
{
if (1)
ntstore64(at(ix, i), entry);
else
*at(ix, i) = entry;
}
struct fifo
{
cell_t *base, *tail, *top;
fifo(cell_t *base, unsigned size) : base(base), tail(base), top(base + size) {}
bool full() { return tail == top; }
unsigned size() { return tail - base; }
void push(cell_t entry)
{
assert(!full());
*tail++ = entry;
}
};
struct media_fifo : fifo // what is this??
{
media_fifo(const struct tier &tier, const unsigned i) :
fifo(tier.at(i, 0), power2(tier.stridebits - cellshift))
{}
};
unsigned shard::buckets() { return power2(tablebits); }
bool shard::bucket_used(const unsigned i) { return table[i].key_loc_link != noentry; }
unsigned shard::next_entry(const unsigned link) { return tri_first(&tri, table[link].key_loc_link); }
void shard::set_link(unsigned prev, unsigned link) { tri_set_first(&tri, table[prev].key_loc_link, link); }
unsigned shard::stride() const { return power2(tier().stridebits); } // hardly used!
void shard::empty()
{
unsigned n = used = buckets();
for (unsigned i = 0; i < n; i++)
table[i].key_loc_link = noentry;
free = count = 0;
}
#if 0
void shard::rewind()
{
fifo.tail = fifo.base + 1;
}
#endif
count_t &shard::mediacount() const { return tier().countbuf[ix]; }
unsigned shard::buckets() const { return power2(tablebits); }
void shard::imprint()
{
struct {char a[4]; u16 b[2];} magic = {
{'f', 'i', 'f', 'o'},
{ix, tier().shards()}};
memcpy(tier().at(ix, 0), &magic, 8);
mediacount() = 1;
}
#if 0
void shard::append(cell_t value) // hardly used!
{
count_t &count = mediacount();
assert(count < top); // wrong!!!
if (1) {
assert(tier().at(ix, count) == fifo.tail);
fifo.push(value);
} else
tier().store(ix, count, value);
count++;
}
#endif
void shard::walk_bucket(std::function<void(hashkey_t key, loc_t loc)> fn, unsigned bucket)
{
for (unsigned link = bucket;;) {
u64 lowkey;
u32 next, loc;
tri_unpack(&tri, table[link].key_loc_link, next, loc, lowkey);
fn(power2(lowbits, bucket) | lowkey, loc);
if (next == endlist)
break;
link = next;
}
}
void shard::walk_buckets(std::function<void(unsigned bucket)> fn)
{
for (unsigned bucket = 0; bucket < buckets(); bucket++)
if (bucket_used(bucket))
fn(bucket);
}
void shard::walk(std::function<void(hashkey_t key, loc_t loc)> fn)
{
for (unsigned bucket = 0; bucket < buckets(); bucket++)
if (bucket_used(bucket))
walk_bucket(fn, bucket);
}
void shard::dump(const unsigned flags, const char *tag)
{
printf("%sshard %i:%i ", tag, is_lower(), ix);
unsigned tablesize = buckets(), found = 0, empty = tablesize;
if (flags & 1)
printf("buckets %u entries %u used %u top %u lowbits %u\n",
tablesize, count, used, top, lowbits);
if (flags & (2|4)) {
auto f2 = [flags, &found](hashkey_t key, loc_t loc) {
if (flags & 2)
printf("%lx:%x ", key, loc);
found++;
};
auto f1 = [this, f2, flags, tag, tablesize, &empty](unsigned bucket) {
if (flags & 2)
printf("%s(%x/%x) ", tag, bucket, tablesize);
walk_bucket(f2, bucket);
empty--;
};
walk_buckets(f1);
if (flags & 2)
printf("\n");
}
if (flags & 4)
printf("(%u entries, %u buckets empty)\n", found, empty);
if (flags & 10) {
if (free) {
printf("free:");
for (unsigned link = free; link; link = next_entry(link))
printf(" %u", link);
printf("\n");
}
}
if (flags & (2|4))
assert(found == count);
}
int shard::load_from_media()
{
enum {verbose = 0};
unsigned n = mediacount();
trace("%i entries", n);
cell_t *media = tier().at(ix, 0);
for (unsigned j = 1; j < n; j++) {
cell_t entry = media[j];
bool is_insert = !(entry & high64);
entry &= ~high64;
u64 key;
loc_t loc;
duo_unpack(&tier().duo, entry, key, loc);
if (verbose)
printf("%c%lx:%x%c", "-+"[is_insert], key, loc, " \n"[!(j % 10)]);
if (!entry && j + 1 < n && !media[j + 1]) {
/*
* Zero is actually a valid entry (key 0, block 0, delete)
* so paranoia check for two successive zeroes. Possibly a
* legal collision, but nearly certain to be corruption.
*/
warn("\nNull entry %i/%i", j, n);
hexdump(media + j, 64);
BREAK;
}
if (is_insert)
insert(key, loc);
else
remove(key, loc);
}
if (verbose)
printf("\n");
if (0)
fprintf(stderr, ".");
return 0;
}
/*
* Rewrite a media shard from cache to squeeze out tombstones
*/
int shard::flatten()
{
trace("shard %u buckets %u entries %u", ix, buckets(), count);
struct media_fifo media(tier(), ix);
for (unsigned bucket = 0; bucket < buckets(); bucket++) {
if (bucket_used(bucket)) {
unsigned link = bucket;
while (1) {
u64 lowkey;
u32 next, loc;
tri_unpack(&tri, table[link].key_loc_link, next, loc, lowkey);
hashkey_t key = power2(lowbits, bucket) | lowkey;
trace_off("[%x] %lx => %lx", bucket, key, loc);
media.push(duo_pack(&tier().duo, key, loc));
if (!next)
break;
link = next;
}
}
}
mediacount() = media.size();
assert(mediacount() <= count + 1);
if (0)
hexdump(tier().at(ix, 0), power2(cellshift, mediacount()));
return 0;
}
void shard::reshard_part(struct shard *out, unsigned more_shards, unsigned part)
{
unsigned partbits = tablebits - more_shards;
trace("reshard x%li buckets %u entries %u", power2(more_shards), out->buckets(), count);
for (unsigned bucket = part << partbits; bucket < (part + 1) << partbits; bucket++) {
assert(bucket < buckets());
if (bucket_used(bucket)) {
unsigned link = bucket;
while (1) {
u64 lowkey;
u32 next, loc;
tri_unpack(&tri, table[link].key_loc_link, next, loc, lowkey);
hashkey_t key = power2(lowbits, bucket) | lowkey;
trace_off("[%x] %lx => %lx", bucket, key, loc);
out->insert(key, loc);
if (!next)
break;
link = next;
}
}
}
}
shard::~shard() { ::free(table); }
// is there a better place to put these???
unsigned guess_linkbits(const unsigned tablebits, const fixed8 loadfactor)
{
assert(loadfactor >= one_fixed8); // load factor less than one not supported yet
//log2_ceiling(mul8(map->loadfactor, 2 << map->head.maxtablebits)) + cache_entry_bits;
unsigned linkbits = tablebits + log2_ceiling(loadfactor) - 8 + 1; // fake mul8, obscure!
trace_off("linkbits %u", linkbits);
return linkbits;
}
loc_t choose_maploc(const unsigned mapbits, const unsigned stridebits, const unsigned blocksize, const unsigned blocks)
{
enum {nominal_large_entry_size = 108}; // needs work!
u64 max_entries_below = power2(mapbits + stridebits - cellshift);
loc_t likely_entries_per_block = blocksize / nominal_large_entry_size;
loc_t likely_blocks = max_entries_below / likely_entries_per_block;
return std::max(likely_blocks, 2 * blocks);
}
unsigned calc_sigbits(const unsigned tablebits, const fixed8 loadfactor, const unsigned locbits)
{
unsigned linkbits = guess_linkbits(tablebits, loadfactor);
unsigned sigbits = 64 - linkbits + tablebits - locbits;
trace_geom("tablebits %u locbits %u linkbits %u = %u", tablebits, locbits, linkbits, sigbits);
return sigbits;
}
static unsigned mapid = 1; // could be different every run, is that ok??
keymap::keymap(struct header &header, const int fd, struct recops &recops, unsigned reclen) :
bigmap(), // unfortunately impossible to initialize bigmap members here
map(0), tiers({{header, header.upper}, {header, header.lower}}),
tablebits(header.tablebits),
shards(power2(upper->mapbits)), pending(0),
loadfactor(header.loadfactor),
peek({NULL, -1}),
header(header),
recops(recops),
sinkbh{power2(header.blockbits), reclen, 0, 0, this},
peekbh{power2(header.blockbits), reclen, 0, 0, this},
fd(fd), id(mapid++), Private(0)
{
printf("upper mapbits %u stridebits %u locbits %u sigbits %u\n",
upper->mapbits, upper->stridebits, upper->locbits, upper->sigbits);
map = mapalloc();
blockbits = header.blockbits; // cannot initialize aggregate in
blocksize = power2(blockbits); // initializer list only because
bigmap::reclen = reclen; // the standard is lame.
keymask = bitmask(upper->mapbits + (sigbits = upper->sigbits)); // need redundant sigbits field???
mapmask = bitmask(upper->mapbits); // need redundant mapmask field???
if (fd > 0) {
define_layout(layout.map);
layout.do_maps(fd);
bigmap_open(this);
u8 *frontbuf = (u8 *)aligned_alloc(power2(cellshift, blockcells), blocksize);
path[0].map = (struct datamap){.data = frontbuf};
maxblocks = layout.map[map_rbspace].size >> blockbits;
add_new_rec_block(this);
recops.init(&sinkinfo());
log_clear(microlog);
#ifdef SIDELOG
Private = (struct sidelog *)calloc(1, sidelog_size);
#endif
}
if (0)
populate_all();
}
struct shard *keymap::new_shard(const struct tier *tier, unsigned i, unsigned tablebits, bool virgin)
{
struct shard *shard = new struct shard(this, tier, i, tablebits, guess_linkbits(tablebits, loadfactor));
if (virgin)
shard->imprint();
return shard;
}
struct shard **keymap::mapalloc()
{
unsigned bytes = shards * sizeof *map;
struct shard **map = (struct shard **)malloc(bytes);
memset(map, 0, bytes);
return map;
}
keymap::~keymap()
{
for (unsigned i = 0; i < levels; i++)
free(path[i].map.data); // danger!!! We assume these are front buffers
for (unsigned i = 0; i < shards; i++) {
struct shard *shard = map[i];
if (shard) {
spam(NULL, shard->ix, tiershift(tier(shard)));
delete shard; // only delete lower tier shard once
}
}
tiers[0].cleanup();
tiers[1].cleanup();
free(map);
#ifdef SIDELOG
free(Private);
#endif
}
struct recinfo &keymap::sinkinfo()
{
sinkbh.data = path[0].map.data; // would like to get rid of this assignment
return sinkbh; // maybe by using struct ri directly in path[] and losing datamap
}
struct recinfo &keymap::peekinfo(loc_t loc)
{
if (loc == path[0].map.loc)
return sinkinfo();
peek = (struct datamap){.data = peekbh.data = ext_bigmap_mem(this, loc), .loc = loc};
return peekbh;
}
void keymap::spam(struct shard *shard)
{
spam(shard, shard->ix, tiershift(tier(shard)));
}
void keymap::spam(struct shard *shard_or_null, unsigned ix, unsigned shift)
{
for (unsigned i = ix << shift, n = power2(shift), j = i + n; i < j; i++)
map[i] = shard_or_null;
}
void keymap::dump(unsigned flags)
{
if (1) {
printf("map: ");
for (unsigned i = 0; i < shards; i++)
printf("%c", "+*-"[!map[i] ? 2 : map[i]->is_lower()]);
printf("\n");
if (0)
return;
}
for (unsigned i = 0; i < shards; i++) {
struct shard *shard = map[i];
if (!shard)
continue;
unsigned tiermask = bitmask(tiershift(tier(shard)));
if (shard->is_lower()) {
unsigned j = i & tiermask;
if (j) {
if (map[i & ~tiermask] == shard)
continue;
printf("*** wrong *** ");
}
}
map[i]->dump(flags, "");
}
}
unsigned keymap::burst() { return (logtail - loghead) & logmask; }
const struct tier &keymap::tier(const struct shard *shard) const { return tiers[shard->tx]; }
unsigned keymap::tiershift(const struct tier &tier) const { return upper->mapbits - tier.mapbits; }
bool keymap::single_tier() const { return !pending; }
struct shard *keymap::populate(unsigned i, bool for_insert)
{
assert(!map[i]);
struct tier *tier = single_tier() || upper->countbuf[i] ? upper : lower;
unsigned count = tier->countbuf[i >> tiershift(*tier)];
if (!count && !for_insert)
return NULL;
struct shard *shard = new_shard(tier, i, tablebits, !count);
trace("shard %i:%i/%i", shard->is_lower(), i, count);
shard->load_from_media();
spam(shard);
return shard;
}
void keymap::populate_all()
{
for (unsigned i = 0; i < shards; i++)
populate(i, 1);
}
struct shard *keymap::getshard(unsigned i, bool for_insert)
{
assert(i < shards);
return map[i] ? map[i] : populate(i, for_insert);
}
struct shard *keymap::setshard(const unsigned i, struct shard *shard)
{
assert(shard->ix = i >> tiershift(tier(shard)));
assert(!map[i]);
trace("map[%i] = %p", i, shard);
return map[i] = shard;
}
u64 keymap::shardmap_size(struct tier *tier)
{
return power2(tier->stridebits + tier->mapbits) + power2(tier->stridebits);
}
void keymap::define_layout(std::vector<region> &map)
{
u64 rbspace_size = power2(12 + 20);
u64 upper_countmap_size = power2(upper->mapbits + countshift);
u64 upper_shardmap_size = shardmap_size(upper);
void **microlog_mem = (void **)µlog;
upper_microlog = NULL;
map.push_back({rbspace_size, 12, (void **)&rbspace, &rbspace_pos});
if (!lower->is_empty()) {
u64 lower_countmap_size = power2(lower->mapbits + countshift);
u64 lower_shardmap_size = shardmap_size(lower);
map.push_back({microlog_size, 12, microlog_mem, NULL});
map.push_back({lower_countmap_size, 12, (void **)&lower->countmap, &lower->countmap_pos});
map.push_back({lower_shardmap_size, 12, (void **)&lower->shardmap, &lower->shardmap_pos});
microlog_mem = NULL;
}
map.push_back({microlog_size, 12, microlog_mem ? : (void **)&upper_microlog, NULL});
map.push_back({upper_countmap_size, 12, (void **)&upper->countmap, &upper->countmap_pos});
map.push_back({upper_shardmap_size, 12, (void **)&upper->shardmap, &upper->shardmap_pos});
}
int keymap::rehash(const unsigned i, const unsigned more)
{
trace_geom("[%u] shard %u buckets 2^%u -> 2^%u", id, i, tablebits, tablebits + more);
unsigned out_tablebits = header.tablebits = tablebits = tablebits + more; // quietly adjusts default tablebits!
struct shard *shard = map[i];
struct shard *newshard = new_shard(&tier(shard), i, out_tablebits, 0);
trace("entries %u locbits %u linkbits %u", shard->count, tiers[newshard->tx].locbits, newshard->trio.bits0);
shard->reshard_part(newshard, 0, 0);
assert(newshard->count == shard->count);
spam(newshard); // support lower tier rehash even though it should never happen
delete shard;
return 0;
}
int keymap::reshard(const unsigned i, const unsigned more_shards, const unsigned more_buckets)
{
struct shard *shard = map[i];
assert(shard->is_lower());
unsigned more_per_shard = more_buckets - more_shards;
unsigned out_tablebits = tablebits + more_per_shard;
trace("reshard %u 2^%i (2^%i buckets per shard)", i, more_shards, out_tablebits);
for (unsigned part = 0, parts = power2(more_shards); part < parts; part++) {
unsigned j = i + part;
struct shard *newshard = new_shard(upper, j, out_tablebits);
trace("map[%i] part %i", j, part);
shard->reshard_part(newshard, more_shards, part);
assert(map[j] == shard);
map[j] = newshard;
newshard->flatten();
}
shard->mediacount() = 0;
// shard_unmap(shard);
delete shard;
return 0;
}
void keymap::force_pending() // untested
{
if (pending) {
trace_on("force %u pending", pending);
unsigned more = upper->mapbits - lower->mapbits;
for (unsigned i = 0; i < shards; i += power2(more)) {
struct shard *shard = getshard(i, 0);
if (shard && shard->is_lower()) {
reshard(i, more, more); // error return!
pending--;
}
}
assert(!pending);
drop_tier();
}
}
/*
* Significant bits is the sum of tablebits and explicitly stored hash
* bits. We want as many significant bits as possible to maximize the
* chance that key existence can be determined from the hash index alone.
* Each new level, significant bits are expected to decrease because the
* block location field gets bigger, roughly tracking the increase in
* shards, but this is only approximate because it depends on the average
* record size, which can change systematically over time.
*
* So we expect that significant bits will always decrease, roughly at
* the same rate that shards increase. Because some hash bits are
* implied by the shard index, hash precision stays nearly the same,
* but is never allowed to increase because existing index entries would
* then become inaccessible due to not storing the additional hash bits.
*
* We use the current blocks count to estimate the number of blocks
* the next index level will have, a multiple of the current level. If
* the estimate is too high, hash precision will be lost. However, this
* loss of precision will not accumulate per level because the next
* estimate will be based on the actual blocks used. If the estimate is
* too low then the blocks field will fill up, and we will be forced to
* add a new tier on short notice, skipping the nicety of incremental
* reshard. Likewise, the block storage region may run into the bottom
* of the index, which we try to place relatively low in the file for
* esthetic and efficiency reasons.
*/
int keymap::add_tier(const unsigned more)
{
unsigned locbits = log2_ceiling(blocks << (more + 1));
if (locbits < upper->locbits) {
/*
* Block address bits must never decrease because hash precision
* would increase, so lookup would fail for existing entries.
*/
warn("*** force non decreasing block address bits");
locbits = upper->locbits;
}
unsigned sigbits = calc_sigbits(tablebits, loadfactor, locbits);
unsigned maxsig = upper->sigbits - more;
if (sigbits > maxsig)
sigbits = maxsig;
unsigned mapbits = upper->mapbits + more, stridebits = upper->stridebits;
loc_t maploc = choose_maploc(mapbits, stridebits, blocksize, blocks);
assert(lower->is_empty()); // Will swap then overwrite empty tier
std::swap(lower, upper); // Existing references from shard remain valid
header.lower = header.upper; // Update persistent part by overwrite
header.upper = { // Define new upper tier
.mapbits = mapbits,
.stridebits = stridebits,
.locbits = locbits,
.sigbits = sigbits,
.maploc = maploc };
*upper = {header, header.upper}; // overwrite empty former lower tier
layout.map.clear();
define_layout(layout.map);
layout.redo_maps(fd);
trace_geom("mapbits %u maploc %x mapsize %lx filesize %lx sigbits %u locbits %u",
mapbits, maploc, layout.size - upper->countmap_pos, layout.size,
upper->sigbits, upper->locbits);
return 0;
}
void keymap::drop_tier()
{
trace_geom("drop tier");
assert(!pending);
unify(); // retire any lower tier updates still in flight
unsigned any = 0;
for (unsigned i = 0; i < lower->shards(); i++)
any += lower->countbuf[i];
assert(!any);
free(lower->countbuf);
*lower = (struct tier){};
header.lower = (struct header::tierhead){};
assert(loghead == logtail);
microlog = upper_microlog;
}
int keymap::grow_map(const unsigned more)
{
trace_geom("expand map x%u to 2^%u", 1 << more, upper->mapbits + more);
assert(!pending);
pending = shards;
shards <<= more;
sigbits -= more; // because shard index implies additional hash bits
struct shard **oldmap = map, **newmap = mapalloc();
for (unsigned i = 0; i < shards; i++) // unnecessary to zero in alloc
newmap[i] = oldmap[i >> more];
free(oldmap);
map = newmap;
return add_tier(more);
}
int keymap::reshard_and_grow(unsigned i)
{
unsigned more_shards = header.reshard;
struct shard *shard = map[i];
int err;
if (!single_tier() && !shard->is_lower()) {
/*
* A nonuniform hash distribution could cause an upper tier shard to become
* much larger than lower tier shards not yet split, so the upper tier shard
* must be split, but first split all remaining lower tier shards.
*/
warn("*** unbalanced shard size forced shard splits");
force_pending();
}
if (pending) {
assert(upper->mapbits);
more_shards = upper->mapbits - lower->mapbits;
i &= ~bitmask(more_shards);
} else {
tablebits = header.tablebits = header.maxtablebits;
grow_map(more_shards);
i <<= more_shards;
}
int more_buckets = more_shards + header.maxtablebits - tablebits;
if (more_buckets < 0) {
/*
* At the transition from (ing to resharding some combination of geometry
* parameters and load could result in trying to reduce number of buckets at
* reshard, which is not supported.
*/
warn("*** more_buckets was negative");
more_buckets = 0;
}
trace("reshard %i:%u pending %u", shard->is_lower(), i, pending);
if ((err = reshard(i, more_shards, more_buckets)))
return err;
assert(pending);
if (!--pending)
drop_tier();
return 0;
}
int keymap::insert_and_grow(struct shard *&shard, const hashkey_t key, const loc_t loc)
{
assert(!(key & ~keymask));
trace_off("%i:%u(%u) <= %lx:%x", shard->tx, shard->ix, shard->mediacount(), key, loc);
if (shard->count == shard->limit) {
trace("media %u:%u fullness %u/%u", shard->is_lower(), shard->ix, shard->mediacount(), shard->limit);
trace("shards %u tablebits %u header.maxtablebits %u", shards, tablebits, header.maxtablebits);
bool should_rehash = shards == 1 && header.maxtablebits > tablebits;
unsigned more = std::min((unsigned)header.rehash, header.maxtablebits - tablebits);
unsigned i = key >> sigbits;
int err = should_rehash ? rehash(i, more) : reshard_and_grow(i);
if (err)
return err;
shard = map[key >> sigbits]; // shard always changes; reshard changes sigbits
}
assert(shard->count < shard->limit);
return shard->insert(key, loc);
}
rec_t *keymap::lookup(const char *key, unsigned len)
{
return lookup((const u8 *)key, len);
}
rec_t *keymap::insert(const char *key, unsigned len, const void *data, bool unique)
{
return insert((const u8 *)key, len, data, unique);
}
int keymap::remove(const char *key, unsigned len)
{
return remove((const u8 *)key, len);
}
rec_t *keymap::lookup(const void *key, unsigned len)
{
hashkey_t hash = keyhash(key, len) & keymask;
struct shard *shard = getshard(hash >> sigbits, 0);
return shard ? shard->lookup(key, len, hash) : NULL;
}
shard::shard(struct keymap *map, const struct tier *tier, unsigned i, unsigned tablebits, unsigned linkbits) :
free(endlist), top(power2(linkbits)), // should depend on limit!!!
count(0), limit(mul8(map->loadfactor, power2(tablebits))), // must not be more than cells(stride) - 1 (magic)
tablebits(tablebits), lowbits(tier->sigbits - tablebits), tx(tier - map->tiers), ix(i >> map->tiershift(*tier)),
map(map), tri(new_tri(linkbits, tier->locbits))
{
assert(tablebits <= linkbits);
assert(power2(cellshift, top) <= power2(tier->stridebits));
table = (struct shard_entry *)malloc(top * sizeof *table);
assert(table); // do something!
trace("buckets %i limit %i top %i lowbits %u linkbits %u", (int)power2(tablebits), limit, top, lowbits, tablebits);
empty();
}
const struct tier &shard::tier() const { return map->tiers[tx]; }
bool shard::is_lower() { return tx == map->lower - map->tiers; }
unsigned long tests = 0, probes = 0;
rec_t *shard::lookup(const void *key, unsigned len, hashkey_t hash)
{
trace("find '%s'", cprinz(key, len));
cell_t lowhash = hash & bitmask(lowbits);
unsigned link = (hash >> lowbits) & bitmask(tablebits);
trace("hash %lx ix %i:%x bucket %x", hash, is_lower(), ix, link);
if (bucket_used(link)) {
tests++;
do {
const cell_t &entry = table[link].key_loc_link;
if (tri_third(&tri, entry) == lowhash) {
loc_t loc = tri_second(&tri, entry);
trace("probe block %i:%x", map->id, loc);
probes++;
struct recinfo &ri = map->peekinfo(loc);
rec_t *rec = map->recops.lookup((struct recinfo *)&ri, key, len, hash);
if (rec)
return rec;
}
link = next_entry(link);
} while (link != endlist);
}
return NULL;
}
int shard::insert(const hashkey_t key, const loc_t loc)
{
const unsigned bucket = (key >> lowbits) & bitmask(tablebits);
trace("insert key %lx ix %i:%i:%x bucket %x loc %x", key, map->id, is_lower(), ix, bucket, loc);
assert(bucket < buckets());
assert(!((loc + 1) & ~bitmask(tier().locbits))); // overflow paranoia
unsigned next = endlist;
if (bucket_used(bucket)) {
if (free != endlist) {
trace("reuse 0x%x", free);
next = free;
free = next_entry(free);
} else {
if (used == top) {
trace_on("out of room at %i", count);