-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathzmap.h
More file actions
3341 lines (2984 loc) · 130 KB
/
zmap.h
File metadata and controls
3341 lines (2984 loc) · 130 KB
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) 2020, Bacoo Zhao - zhaoyanbin@bigo.sg/bacoo_zh@163.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Includes work from parallel-hashmap (https://github.com/greg7mdp/parallel-hashmap)
// with modifications.
// ---------------------------------------------------------------------------
#ifndef _ZMAP_H_
#define _ZMAP_H_
#include <set>
#include <mutex>
#include <atomic>
#include <string>
#include <vector>
#include <thread>
#include <memory>
#include <random>
#include <sstream>
#include <fstream>
#include <algorithm>
#include <fcntl.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <immintrin.h>
#define ZMAP_PREDICT_FALSE(x) (__builtin_expect(!!(x), 0))
#define ZMAP_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
#ifdef NDEBUG
#define zmap_perror(err)
#else
#define zmap_perror(err) fprintf(stderr, "%s: %s(errno: %d)\n", (err), \
(0 == errno ? "Error in user codes" : strerror(errno)), errno), errno = 0
#endif
namespace zmap {
struct DefaultHasher {
static inline uint64_t umul128(uint64_t a, uint64_t b, uint64_t* high) {
__extension__ typedef unsigned __int128 __uint128;
auto result = static_cast<__uint128>(a) * static_cast<__uint128>(b);
*high = static_cast<uint64_t>(result >> 64);
return static_cast<uint64_t>(result);
}
inline uint64_t operator()(uint64_t key) {
// very fast mixing (similar to Abseil)
static constexpr uint64_t k = 0xde5fb9d2630458e9ULL;
uint64_t h = 0;
uint64_t l = umul128(key, k, &h);
return static_cast<size_t>(h + l);
}
};
template<typename ... Args>
std::string string_printf(const std::string& fmt, Args ... args) {
size_t size = std::snprintf(nullptr, 0, fmt.data(), args ...) + 1; // include '\0'
auto buf = std::make_unique<char[]>(size);
std::snprintf(buf.get(), size, fmt.data(), args ...);
return std::string(buf.get(), size - 1); // remove '\0'
}
inline std::string string_printf(const std::string& fmt) { return fmt; }
inline size_t rand64() {
static std::mt19937_64 mt((unsigned)time(nullptr));
return mt();
}
inline bool string_ends_with(const std::string& str, const std::string& suffix) {
if (suffix.size() > str.size()) return false;
return std::equal(suffix.rbegin(), suffix.rend(), str.rbegin());
}
inline std::vector<std::string> list_files_under_dir(const std::string& path,
const std::string& suffix = "", bool recursive = false) {
std::vector<std::string> ret;
if (path.empty()) return ret;
const std::string& dir_path = (path.size() > 1 && '/' == path.back()) ?
path.substr(0, path.size() - 1) : path;
DIR* dir = opendir(dir_path.data());
for(struct dirent entry, *p = &entry; dir && 0 == readdir_r(dir, &entry, &p) && p;) {
if ('.' == *entry.d_name) continue;
if (DT_DIR == entry.d_type) {
if (!recursive) continue;
auto&& sub_ret = list_files_under_dir(dir_path + "/" + entry.d_name, suffix, true);
ret.insert(ret.end(), sub_ret.begin(), sub_ret.end());
} else if (string_ends_with(entry.d_name, suffix)) {
ret.emplace_back(dir_path + "/" + entry.d_name);
}
}
closedir(dir);
if (!dir && 0 == access(path.data(), F_OK)) ret.emplace_back(path);
return ret;
}
constexpr static const uint8_t WRITABLE = 0;
constexpr static const uint8_t WRITE_LOCKED = -1;
#define MIN_TABLE_SIZE 10000
struct atomic_flag {
inline bool test_and_set() {
uint8_t writable_flag = WRITABLE;
return __atomic_compare_exchange_n(&_flag, &writable_flag, WRITE_LOCKED,
false, __ATOMIC_RELEASE, __ATOMIC_RELAXED);
}
inline void do_set() { while (!test_and_set()); }
inline void clear() { __atomic_store_n(&_flag, WRITABLE, __ATOMIC_RELEASE); }
inline explicit operator bool() const { return __atomic_load_n(&_flag, __ATOMIC_CONSUME); }
private:
volatile uint8_t _flag = 0;
};
struct MmapUtility {
constexpr static size_t min_size_for_malloc_with_mmap = 0x10000000; // 64MB
static inline constexpr size_t round_up(size_t n) {
constexpr size_t m = 0xFffFF; // 1MB
return (n + m) & (~m);
};
static void* malloc(size_t size, bool not_dump = true, bool prior_use_hugepage = false) {
void* addr = nullptr;
auto alloc_size = size + 8; // reserve header space
if (alloc_size < min_size_for_malloc_with_mmap) {
// madvise requires memalign with pagesize
if (not_dump) {
if (0 != posix_memalign(&addr, 4096, alloc_size)) addr = nullptr;
}
if (!addr) addr = ::malloc(alloc_size);
} else {
alloc_size = round_up(alloc_size);
addr = ::mmap(nullptr, alloc_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | (prior_use_hugepage ? MAP_HUGETLB : 0), -1, 0);
if (MAP_FAILED == addr && prior_use_hugepage) {
addr = ::mmap(nullptr, alloc_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
}
if (MAP_FAILED == addr) { zmap_perror("mmap failed"); return nullptr; }
}
if (not_dump && madvise(addr, alloc_size, MADV_DONTDUMP) != 0) zmap_perror("madvise failed");
*(size_t*)addr = alloc_size;
return (size_t*)addr + 1;
}
static void free(void* p) {
if (!p) return;
p = (size_t*)p - 1;
size_t size = *(size_t*)p;
if (size < min_size_for_malloc_with_mmap) {
::free(p);
return;
}
constexpr static size_t step = (1UL << 30); // 1GB
while (size > step) {
void* addr = mremap(p, size, size - step, 0);
if (addr == MAP_FAILED) break;
size -= step;
if (addr != p) { p = addr; break; }
}
if (0 != ::munmap(p, size)) zmap_perror("munmap failed");
}
static void* mmap(int fd, size_t size, bool write_mode = false, bool not_dump = true,
bool prior_use_hugepage = false) {
if (fd < 0 || size == 0) return nullptr;
auto mmap_helper = [](size_t length, int prot, int flags, int fd, off_t offset) {
void* ret = ::mmap(nullptr, length, prot, flags, fd, offset);
if (MAP_FAILED == ret && (flags & MAP_HUGETLB) && EINVAL == errno) {
flags &= ~MAP_HUGETLB;
return ::mmap(nullptr, length, prot, flags, fd, offset);
}
return ret;
};
void* addr = nullptr;
if (write_mode) {
addr = mmap_helper(size, PROT_READ | PROT_WRITE, (0 == getuid() ? MAP_LOCKED : 0) |
(prior_use_hugepage ? MAP_HUGETLB : 0) | MAP_SHARED | MAP_POPULATE, fd, 0);
} else {
addr = mmap_helper(size, PROT_READ, (0 == getuid() ? MAP_LOCKED : 0) |
(prior_use_hugepage ? MAP_HUGETLB : 0) | MAP_PRIVATE | MAP_POPULATE, fd, 0);
}
if (MAP_FAILED != addr && not_dump && madvise(addr, size, MADV_DONTDUMP) != 0)
zmap_perror("madvise failed");
return MAP_FAILED == addr ? nullptr : addr;
}
static void munmap(void* addr, size_t size, bool need_sync = false) {
// msync's too slow, and there's no need to msync if munmap is called subsequently at once
// if (need_sync && addr && 0 != msync(addr, size, MS_SYNC)) zmap_perror("msync failed");
if (addr && 0 != ::munmap(addr, size)) zmap_perror("munmap failed");
}
};
struct FileDataNode : public std::pair<void*, size_t> {
enum MmapMode {
FDNM_NO_MMAP = 0,
FDNM_MMAP_READ = 1,
FDNM_MMAP_WRITE = 2,
};
FileDataNode(void* addr, size_t sz, MmapMode mmap_mode = FDNM_NO_MMAP):
std::pair<void*, size_t>(addr, sz), _mmap_mode(mmap_mode) {}
FileDataNode(FileDataNode&& t): std::pair<void*, size_t>(t.first, t.second),
_mmap_mode(t._mmap_mode) { t.first = nullptr; }
FileDataNode& operator=(const FileDataNode&) = delete;
~FileDataNode() {
FDNM_NO_MMAP == _mmap_mode ? MmapUtility::free(first) :
MmapUtility::munmap(first, second, FDNM_MMAP_WRITE == _mmap_mode);
}
private:
MmapMode _mmap_mode = FDNM_NO_MMAP;
};
struct DumpWriter {
virtual ~DumpWriter() {};
virtual bool init_index(const std::string& index_file) = 0;
virtual size_t write_index(const void* addr, size_t len) = 0;
virtual bool init_data(const std::string& data_file) = 0;
virtual size_t write_data(const void* addr, size_t len) = 0;
};
// we suggest you'd better avoid using mmap to load/dump, since it will degrade performance
// based our tests.
struct FileIOUtility {
struct FileBaton {
FileBaton(const std::string& path, bool write_mode, size_t size = 0, bool use_mmap = false):
_write_mode(write_mode), _file_len(size) {
_fd = open(path.data(), _write_mode ? (O_RDWR | O_CREAT) : O_RDONLY, 0666);
if (-1 == _fd) { zmap_perror("open error"); return; }
if (!_write_mode || 0 == _file_len) {
struct stat st;
if (-1 == fstat(_fd, &st)) zmap_perror("fstat error");
else if (st.st_size > 0) _file_len = st.st_size;
}
if (_write_mode && use_mmap) {
if (0 == _file_len) { zmap_perror("invalid file length"); return; }
else if (-1 == ftruncate(_fd, _file_len)) zmap_perror("ftruncate error");
}
if (use_mmap) _mmap_addr = MmapUtility::mmap(_fd, _file_len, write_mode);
}
FileBaton(const FileBaton&) = delete;
FileBaton& operator=(const FileBaton&) = delete;
~FileBaton() {
MmapUtility::munmap(_mmap_addr, _file_len, _write_mode);
if (-1 != _fd) close(_fd);
}
inline operator bool() { return -1 != _fd; }
inline bool eof() const { return _off >= _file_len; }
inline size_t size() const { return _file_len; }
// if you wanna use raw pointer of mmap out of FileBaton, use can call
// mmap_dismiss() after you've got the pointer via mmap_addr()
inline void* mmap_addr() { return _mmap_addr; }
inline void mmap_dismiss() { _mmap_addr = nullptr; }
FileBaton& read(void* addr, size_t len) {
if (_write_mode || _off + len > _file_len) return *this;
char* data = (char*)addr;
for (size_t i = 0, step = 1024 * 1024, n = std::min(step, len - i); i < len;
i += step, data += n, _off += n, n = std::min(step, len - i)) {
if (_mmap_addr) memcpy(data, (char*)_mmap_addr + _off, n);
else if ((ssize_t)n != ::read(_fd, data, n)) { zmap_perror("read error"); break; }
}
return *this;
}
FileBaton& write(const void* addr, size_t len) {
if (!_write_mode || (_mmap_addr && _off + len > _file_len)) return *this;
char* data = (char*)addr;
for (size_t i = 0, step = 1024 * 1024, n = std::min(step, len - i); i < len;
i += step, data += n, _off += n, n = std::min(step, len - i)) {
if (_mmap_addr) memcpy((char*)_mmap_addr + _off, data, n);
else if ((ssize_t)n != ::write(_fd, data, n)) { zmap_perror("write error"); break; }
}
if (!_mmap_addr) _file_len = std::max(_file_len, _off);
return *this;
}
private:
int _fd = -1;
bool _write_mode = false;
size_t _file_len = 0;
size_t _off = 0;
void* _mmap_addr = nullptr;
};
// allocate memory for the whole content
static FileDataNode load(const std::string& path, bool prior_load_via_mmap = true) {
FileBaton baton(path, false, 0, prior_load_via_mmap);
size_t size = baton.size();
if (!baton || 0 == size) return {nullptr, 0};
void* addr = MmapUtility::malloc(size);
baton.read(addr, size);
return {addr, size};
}
// multiple load, usage:
// auto baton = mload(path);
// while (baton && !baton.eof()) {
// baton.read(addr, len);
// }
static FileBaton mload(const std::string& path, bool use_mmap = false) {
return {path, false, 0, use_mmap};
}
static bool dump(const std::string& path, void* data, size_t len,
bool prior_dump_via_mmap = true) {
FileBaton baton(path, true, len, prior_dump_via_mmap);
return baton.write(data, len);
}
// multiple dump, usage:
// auto baton = mdump(path);
// while (baton) {
// baton.write(addr, len);
// }
static FileBaton mdump(const std::string& path, bool use_mmap = false, size_t len = -1) {
return {path, true, len, use_mmap};
}
static FileDataNode mmap_whole_file(const std::string& path, bool write_mode) {
FileBaton baton(path, write_mode, 0, true);
auto addr = baton.mmap_addr();
baton.mmap_dismiss();
return {addr, baton.size(),
write_mode ? FileDataNode::FDNM_MMAP_WRITE : FileDataNode::FDNM_MMAP_READ};
}
};
template <typename KeyType>
struct KeyValueReader {
virtual ~KeyValueReader() {}
virtual bool next(KeyType& key, const void*& val, size_t* val_len, bool& erase_flag) = 0;
// read should start from the beginning after clone
virtual KeyValueReader* clone() = 0;
};
// key{delim}value: insert/update
// key: erase
// key{delim}: insert/update with empty value
// {delim}value: skip
template <typename KeyType>
struct KeyValueReaderFromFile : public KeyValueReader<KeyType> {
~KeyValueReaderFromFile() {
free(_line);
fclose(_stream);
}
void init(const std::string& file, char delim = '\t') {
_file = file;
_delim = delim;
_stream = fopen(_file.data(), "r");
}
virtual bool next(KeyType& key, const void*& val, size_t* val_len, bool& erase_flag) {
ssize_t n_read = 0;
do {
size_t line_len = 0;
if (-1 == (n_read = getline(&_line, &line_len, _stream))) return false;
if (n_read > 0 && '\n' == _line[n_read - 1]) {
--n_read;
_line[n_read] = '\0';
}
} while (n_read <= 0 || _delim == *_line);
char* pend = strchr(_line, _delim);
if (!parse_key(key, _line, pend ? pend - _line : n_read)) {
zmap_perror(string_printf("parse key failed, line: %s", _line).data());
return next(key, val, val_len, erase_flag);
}
val = nullptr;
erase_flag = false;
if (pend && _delim == *pend) {
val = ++pend;
if (val_len) *val_len = n_read - (pend - _line);
} else {
erase_flag = true;
}
return true;
}
virtual KeyValueReader<KeyType>* clone() {
auto reader = new KeyValueReaderFromFile();
reader->init(_file, _delim);
return reader;
}
private:
template <typename T>
static bool parse_key(T& key, const void* key_ptr, size_t key_len) {
if (!key_ptr || 0 == key_len) return false;
std::istringstream iss(std::string((const char*)key_ptr, key_len));
iss >> key;
return -1 == iss.tellg();
}
static bool parse_key(uint64_t& key, const void* key_ptr, size_t key_len) {
if (!key_ptr || 0 == key_len) return false;
char* key_end = nullptr;
key = strtoul((const char*)key_ptr, &key_end, 10);
return key_end && key_end == (const char*)key_ptr + key_len;
}
static bool parse_key(std::string& key, const void* key_ptr, size_t key_len) {
if (!key_ptr || 0 == key_len) return false;
key.assign((const char*)key_ptr, key_len);
return true;
}
private:
std::string _file;
char _delim = '\t';
FILE* _stream = nullptr;
char* _line = nullptr;
};
template <typename KeyType, typename FileReader = KeyValueReaderFromFile<KeyType>>
struct KeyValueReaderFromDir : public KeyValueReader<KeyType> {
KeyValueReaderFromDir(const std::string& dir_path, char delim = '\t',
const std::string& suffix = "") {
for (const auto& file : list_files_under_dir(dir_path, suffix)) {
auto reader = std::make_shared<FileReader>();
reader->init(file, delim);
_file_readers.push_back(reader);
}
}
virtual bool next(KeyType& key, const void*& val, size_t* val_len, bool& erase_flag) {
while (!_file_readers[_file_reader_idx]->next(key, val, val_len, erase_flag)) {
if (++_file_reader_idx >= _file_readers.size()) {
return false;
}
}
return true;
}
virtual KeyValueReader<KeyType>* clone() {
auto copy = new KeyValueReaderFromDir(*this);
copy->_file_reader_idx = 0;
for (auto& reader : copy->_file_readers) {
reader.reset(reader->clone());
}
return copy;
}
private:
std::vector<std::shared_ptr<KeyValueReader<KeyType>>> _file_readers;
size_t _file_reader_idx = 0;
};
constexpr static double MAX_LOAD_FACTOR = 7.0 / 8;
// return the real max_size in zmap based on the one that user expects
static inline uint64_t calc_max_size(uint64_t max_size) {
uint64_t result = ~size_t{} >> __builtin_clzl(max_size);
if (result * MAX_LOAD_FACTOR < max_size) {
result <<= 1;
result += 1;
}
return result * MAX_LOAD_FACTOR;
}
namespace internal {
inline std::string get_zmap_path(const std::string& path,
const std::vector<std::string>& suffixes, bool allow_suffix_in_middle = false) {
struct stat st;
if (0 == stat(path.data(), &st) && S_ISDIR(st.st_mode)) {
const auto& files = list_files_under_dir(path);
for (const auto& suffix : suffixes) {
for (const auto& file : files) {
if (allow_suffix_in_middle) {
size_t pos = std::string::npos;
if (std::string::npos != (pos = file.find(suffix))) {
return file.substr(0, pos) + suffix;
}
} else if (string_ends_with(file, suffix)) return file;
}
}
} else {
for (const auto& suffix : suffixes) {
if (allow_suffix_in_middle) {
size_t pos = std::string::npos;
if (std::string::npos != (pos = path.find(suffix))) {
return path.substr(0, pos) + suffix;
}
} else if (string_ends_with(path, suffix)) return path;
}
}
return path + (suffixes.empty() ? "" : suffixes.front());
}
// use murmurhash for string, which refers to
// https://sites.google.com/site/murmurhash/, and the source code
// is from https://sites.google.com/site/murmurhash/MurmurHash2_64.cpp
inline uint64_t MurmurHash64A(const void* key, int len, unsigned int seed = 0x5f5b463) {
const uint64_t m = 0xc6a4a7935bd1e995;
const int r = 47;
uint64_t h = seed ^ (len * m);
const uint64_t * data = (const uint64_t *)key;
const uint64_t * end = data + (len/8);
while(data != end) {
uint64_t k = *data++;
k *= m; k ^= k >> r; k *= m;
h ^= k; h *= m;
}
const unsigned char* data2 = (const unsigned char*)data;
switch(len & 7) {
case 7: h ^= uint64_t(data2[6]) << 48;
case 6: h ^= uint64_t(data2[5]) << 40;
case 5: h ^= uint64_t(data2[4]) << 32;
case 4: h ^= uint64_t(data2[3]) << 24;
case 3: h ^= uint64_t(data2[2]) << 16;
case 2: h ^= uint64_t(data2[1]) << 8;
case 1: h ^= uint64_t(data2[0]); h *= m;
};
h ^= h >> r; h *= m; h ^= h >> r;
return h;
}
using ctrl_t = char;
using h2_t = uint8_t;
using offset_t = size_t;
constexpr static size_t INVALID_OFFSET = -1;
enum Ctrl : ctrl_t {
// kEmpty must be -128 if we want to use _mm_sign_epi8
kEmpty = -128, // 0b1000 0000
kDeleted = -127, // 0b1000 0001
kSentinel = 0, // 0b0000 0000
};
static ctrl_t h2_table[256];
#ifdef ZMAP_PROFILER
struct ZmapProfiler {
ZmapProfiler() {
for (auto& x : h2_hit_count_for_find) x = 0;
}
~ZmapProfiler() { debug(); }
void record_probe(size_t jump_cnt) {
total_jump += jump_cnt;
atomic_max(max_jump_in_one_probe, jump_cnt);
++probe_count;
if (jump_cnt > 1) ++slowprobe_count;
}
void record_find(h2_t h2, uint64_t match_count, bool match) {
++h2_hit_count_for_find[h2];
total_match_count += match_count;
atomic_max(max_match_count_in_one_find, match_count);
++total_find;
if (match) ++total_hit_find;
}
void debug(std::ostream* out = nullptr) {
std::ostringstream oss;
std::ostream* pout = out ? out : &oss;
*pout << "\nzmap profiler:\n\n"
<< "insert related statistics:\n"
<< string_printf("\ttotal probe count: %lu\n", probe_count.load())
<< string_printf("\ttotal jump count: %lu\n", total_jump.load())
<< string_printf("\tmax jump count in one probe: %lu\n",
max_jump_in_one_probe.load())
<< string_printf("\tslow jump count: %lu\n", slowprobe_count.load())
<< string_printf("\tavg jump in one probe: %f\n",
probe_count ? total_jump * 1.0 / probe_count : 0.0)
<< "\n"
<< "find related statistics:\n"
<< string_printf("\ttotal find count: %lu\n", total_find.load())
<< string_printf("\ttotal hit count: %lu\n", total_hit_find.load())
<< string_printf("\thit rate: %f\n",
total_find ? total_hit_find * 1.0 / total_find : 0.0)
<< string_printf("\ttotal match count: %lu\n", total_match_count.load())
<< string_printf("\tmax match count in one find: %lu\n",
max_match_count_in_one_find.load())
<< string_printf("\tavg match count in one find: %f\n",
total_find ? total_match_count * 1.0 / total_find : 0.0)
<< "\n"
<< "h2 hit count:\n";
for (size_t i = 0; i < h2_hit_count_for_find.size(); ++i) {
*pout << string_printf("\th2[%lu]=%lu\n", i, h2_hit_count_for_find[i].load());
}
*pout << "\n";
if (!out) printf("%s", oss.str().data());
}
static void atomic_max(std::atomic<uint64_t>& val, uint64_t new_val) {
for (uint64_t n = val.load(std::memory_order_consume);
new_val > n && val.compare_exchange_strong(n, new_val, std::memory_order_acq_rel);
n = val.load(std::memory_order_consume));
}
// insert related statistics
std::atomic<uint64_t> total_jump = {0};
std::atomic<uint64_t> max_jump_in_one_probe = {0};
std::atomic<uint64_t> probe_count = {0};
std::atomic<uint64_t> slowprobe_count = {0};
// find related statistics
std::array<std::atomic<uint64_t>, 256> h2_hit_count_for_find;
std::atomic<uint64_t> total_match_count = {0};
std::atomic<uint64_t> max_match_count_in_one_find = {0};
std::atomic<uint64_t> total_find = {0};
std::atomic<uint64_t> total_hit_find = {0};
} g_profiler;
#endif
inline bool is_empty_or_deleted(ctrl_t c) { return c <= kDeleted; }
struct Header {
uint32_t val_len;
uint8_t group_width;
uint8_t reserve1;
uint8_t reserve2;
uint8_t reserve3;
size_t size;
size_t deleted;
size_t capacity;
};
template <size_t SIGNIFICANT_BITS>
struct BitMask {
inline explicit BitMask(uint64_t n) : _n(n & _mask) {}
inline BitMask& operator++() {
_n &= (_n - 1);
return *this;
}
inline explicit operator bool() const { return _n != 0; }
inline BitMask operator&(BitMask other) const { return BitMask(_n | other._n); }
inline int lowest_bit_set() const { return trailing_zeros(); }
inline int trailing_zeros() const {
return _n ? __builtin_ctzl(_n) : SIGNIFICANT_BITS;
}
inline int leading_zeros() const {
return _n ? __builtin_clzl(_n << (64 - SIGNIFICANT_BITS)) : SIGNIFICANT_BITS;
}
private:
uint64_t _n;
constexpr static uint64_t _mask = ((1UL << SIGNIFICANT_BITS) - 1);
};
// Groups without empty slots (but maybe with deleted slots) extend the probe
// sequence. The probing algorithm is quadratic. Given N the number of groups,
// the probing function for the i'th probe is:
//
// P(0) = H1 % N
//
// P(i) = (P(i - 1) + i) % N
//
// This probing function guarantees that after N probes, all the groups of the
// table will be probed exactly once.
class ProbeSeq {
public:
inline ProbeSeq(size_t hash, size_t mask): _mask(mask), _offset(hash & mask) {
assert(((mask + 1) & mask) == 0 && "invalid mask");
}
#ifdef ZMAP_PROFILER
~ProbeSeq() { g_profiler.record_probe(_jump); }
#endif
inline size_t offset() const { return _offset; }
inline size_t offset(size_t i) const { return (_offset + i) & _mask; }
inline void reset(size_t hash) {
_offset = hash & _mask;
_index = 0;
#ifdef ZMAP_PROFILER
g_profiler.record_probe(_jump);
_jump = 0;
#endif
}
inline void next(size_t group_width) {
_index += group_width;
_offset += _index;
_offset &= _mask;
#ifdef ZMAP_PROFILER
++_jump;
#endif
}
private:
size_t _mask = 0;
size_t _offset = 0;
size_t _index = 0;
#ifdef ZMAP_PROFILER
size_t _jump = 0;
#endif
};
// We don't want to define a base class like ProbeGroup using polymorphism,
// since it will degrade performance dramatically.
#define PROBE_GROUP_COMMON_PARTS(Type) \
enum { kWidth = sizeof(Type) }; \
inline auto match(h2_t hash) const { \
return BitMask<kWidth>(match_internal(gen_type(hash), _ctrl)); \
} \
inline int match_first_empty() const { \
static Type s_empty = gen_type(kEmpty); \
auto r = match_internal(s_empty, _ctrl); \
return r ? __builtin_ctzl(r) : -1; \
} \
inline int match_first_empty_or_deleted() const { \
auto r = match_empty_or_deleted(); \
return r ? __builtin_ctzl(r) : -1; \
} \
inline auto match_empty() const { \
static Type s_empty = gen_type(kEmpty); \
return BitMask<kWidth>(match_internal(s_empty, _ctrl)); \
} \
inline uint32_t count_leading_empty_or_deleted() const { \
BitMask<kWidth> mask(match_empty_or_deleted() + 1); \
return mask ? mask.trailing_zeros() : kWidth; \
} \
private: \
Type _ctrl
struct ProbeGroup128 {
inline void reset(const ctrl_t* pos) {
_ctrl = _mm_loadu_si128(reinterpret_cast<const __m128i*>(pos));
}
static inline __m128i gen_type(h2_t hash) { return _mm_set1_epi8(hash); }
inline int match_empty_or_deleted() const {
static __m128i s_threshold = gen_type(kDeleted + 1);
return _mm_movemask_epi8(_mm_cmplt_epi8(_ctrl, s_threshold));
}
static inline int match_internal(__m128i l, __m128i r) {
return _mm_movemask_epi8(_mm_cmpeq_epi8(l, r));
}
PROBE_GROUP_COMMON_PARTS(__m128i);
};
// compile with -mavx2
#if defined(__AVX__) && defined(__AVX2__)
struct ProbeGroup256 {
inline void reset(const ctrl_t* pos) {
_ctrl = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(pos));
}
static inline __m256i gen_type(h2_t hash) { return _mm256_set1_epi8(hash); }
inline int match_empty_or_deleted() const {
static __m256i s_threshold = gen_type(kDeleted + 1);
return _mm256_movemask_epi8(_mm256_cmpgt_epi8(s_threshold, _ctrl));
}
static inline int match_internal(__m256i l, __m256i r) {
return _mm256_movemask_epi8(_mm256_cmpeq_epi8(l, r));
}
PROBE_GROUP_COMMON_PARTS(__m256i);
};
#endif
// compile with -march=skylake-avx512
#if defined(__AVX512F__) && defined(__AVX512BW__) && __GNUC__ >= 6
struct ProbeGroup512 {
inline void reset(const ctrl_t* pos) {
_ctrl = _mm512_loadu_si512(reinterpret_cast<const __m512i*>(pos));
}
static inline __m512i gen_type(h2_t hash) { return _mm512_set1_epi8(hash); }
inline int match_empty_or_deleted() const {
static __m512i s_threshold = gen_type(kDeleted + 1);
return _mm512_cmplt_epi8_mask(_ctrl, s_threshold));
}
static inline uint64_t match_internal(__m512i l, __m512i r) {
return _mm512_cmpeq_epi8_mask(l, r);
}
PROBE_GROUP_COMMON_PARTS(__m512i);
};
#endif
#undef PROBE_GROUP_COMMON_PARTS
template <typename, typename, typename> class ElasticZmapImpl;
template <typename, typename> class StringZmapImpl;
template <typename, size_t> struct ParallelZmapImpl;
// ----------------------------------------------------------------------------
// Z M A P
// ----------------------------------------------------------------------------
// An open-addressing hashtable with quadratic probing.
//
// ABOUT THE NAME
// 'Z' is first alpha of my surname 'Zhao', and meanwhile 'Z' is the last alpha
// in alphabet, expecting it's the final solution for everyone.
//
// IMPLEMENTATION DETAILS
//
// The table stores elements inline in a slot array. In addition to the slot
// array the table maintains some control state per slot. The extra state is one
// byte per slot and stores empty or deleted marks, or alternatively 8 bits from
// the hash of an occupied slot. The table is split into logical groups of
// slots, like so:
//
// Group 1 Group 2 Group 3
// +---------------+---------------+---------------+
// | | | ... | | | | | | ... | | | | | | ... | | | |
// +---------------+---------------+---------------+
//
// On lookup the hash is split into two parts:
// - H2: control part
// - H1: index part
// The groups are probed using H1. For each group the slots are matched to H2 in
// parallel. Because H2 is 8 bits (factually 253 states) and the number of slots
// per group is low (16 or 32/64), in almost all cases a match in H2 is also
// a lookup hit.
//
// On insert, once the right group is found (as in lookup), its slots are
// filled in order.
//
// On erase a slot is cleared. In case the group did not have any empty slots
// before the erase, the erased slot is marked as deleted (or empty under some
// conditions).
template <typename ProbeGroupType, size_t ValueLength, typename Hasher = DefaultHasher>
class ZmapImpl {
template <bool IS_WRITE_MODE>
struct ScopedLock {
ScopedLock(uint8_t* d): _data(d) {
if (!_data) return;
if (IS_WRITE_MODE) {
for (uint8_t n = WRITABLE; !__atomic_compare_exchange_n(_data, &n,
WRITE_LOCKED, false, __ATOMIC_RELEASE, __ATOMIC_RELAXED); n = WRITABLE);
} else {
for (uint8_t n = __atomic_load_n(_data, __ATOMIC_CONSUME);
!(n < WRITE_LOCKED - 1 && __atomic_compare_exchange_n(_data, &n, n + 1,
false, __ATOMIC_RELEASE, __ATOMIC_RELAXED));
n = __atomic_load_n(_data, __ATOMIC_CONSUME));
}
}
ScopedLock(const ScopedLock&) = delete;
ScopedLock& operator=(const ScopedLock&) = delete;
~ScopedLock() {
if (!_data) return;
if (IS_WRITE_MODE) {
assert(WRITE_LOCKED == *_data);
__atomic_store_n(_data, WRITABLE, __ATOMIC_RELEASE);
} else {
assert(WRITE_LOCKED != *_data && WRITABLE != *_data);
__atomic_sub_fetch(_data, 1, __ATOMIC_ACQ_REL);
}
}
private:
volatile uint8_t* _data;
};
using ScopedReadLock = ScopedLock<false>;
using ScopedWriteLock = ScopedLock<true>;
struct __attribute__((packed, aligned(1))) Slot {
union {
uint64_t key;
uint64_t first; // alias for key
};
union {
uint8_t val[ValueLength];
uint8_t second[ValueLength]; // alias for value
};
};
public:
typedef uint64_t KeyType;
typedef typename std::remove_cv<typename std::remove_reference<KeyType>::type>::type RawKeyType;
typedef Hasher HasherType;
ZmapImpl() { memset(&_header, 0, sizeof(_header)); }
// build a new zmap
ZmapImpl(uint64_t max_size) {
bool init_result = init(max_size);
assert(init_result && "init failed");
(void)init_result;
}
// load an existed zmap
ZmapImpl(const std::string& path, bool use_mmap = false) {
bool load_result = load(path, use_mmap);
assert(load_result && "load failed");
(void)load_result;
}
bool init(uint64_t max_size, size_t sub_idx = -1) {
if (NULL != _ctrl) {
zmap_perror("already init ok");
return false;
}
{ // It's ok even if init by multiple threads
for (int i = 0; i < 256; ++i) {
h2_table[i] = i;
}
h2_table[(uint8_t)kEmpty] = (ctrl_t)251;
h2_table[(uint8_t)kDeleted] = (ctrl_t)241;
h2_table[(uint8_t)kSentinel] = (ctrl_t)239;
}
memset(&_header, 0, sizeof(_header));
if (max_size < MIN_TABLE_SIZE) max_size = MIN_TABLE_SIZE;
// rounds up to the next power of 2 minus 1
_header.capacity = ~size_t{} >> __builtin_clzl(max_size);
if (_header.capacity * MAX_LOAD_FACTOR < max_size) {
_header.capacity <<= 1;
_header.capacity += 1;
}
_header.group_width = ProbeGroupType::kWidth;
_header.val_len = ValueLength;
_max_size = _header.capacity * MAX_LOAD_FACTOR;
void* addr = MmapUtility::malloc(sizeof(Header) + _header.capacity +
ProbeGroupType::kWidth + 1 + sizeof(Slot) * _header.capacity);
if (NULL == addr) {
zmap_perror("malloc error");
return false;
}
_allocated_datas.emplace_back(addr, [](void* addr) { MmapUtility::free(addr); });
_ctrl = (ctrl_t*)addr + sizeof(Header);
memset(_ctrl, kEmpty, _header.capacity + ProbeGroupType::kWidth + 1);
_ctrl[_header.capacity] = kSentinel;
_ctrl_end = _ctrl + _header.capacity;
_mtxs = (uint8_t*)MmapUtility::malloc(_header.capacity);
if (NULL == _mtxs) {
zmap_perror("malloc error");
return false;
}
_allocated_datas.emplace_back(_mtxs, [](void* addr) { MmapUtility::free(addr); });
memset(_mtxs, WRITABLE, _header.capacity);
_slots = reinterpret_cast<Slot*>(_ctrl_end + ProbeGroupType::kWidth + 1);
return true;
}
// If use_mmap is true, the disk file will be consistent with modifications in memory and
// there's no need to dump at the end.
// What's more, it's not necessary that path_raw ends with a suffix like ".zmap_*".
bool load(const std::string& path_raw, bool use_mmap = false) {
if (NULL != _ctrl) {
zmap_perror("already load ok");
return false;
}
{ // It's ok even if init by multiple threads
for (int i = 0; i < 256; ++i) {
h2_table[i] = i;
}
h2_table[(uint8_t)kEmpty] = (ctrl_t)251;
h2_table[(uint8_t)kDeleted] = (ctrl_t)241;
h2_table[(uint8_t)kSentinel] = (ctrl_t)239;
}
memset(&_header, 0, sizeof(_header));
const std::string& path = get_zmap_path(path_raw, {".zmap_one", ".zmap_idx"});
if (use_mmap) {
_loaded_data = std::make_unique<FileDataNode>(FileIOUtility::mmap_whole_file(path, true));
_mmap_file = path;
} else {
_loaded_data = std::make_unique<FileDataNode>(FileIOUtility::load(path, false));
}
auto addr = (uint8_t*)_loaded_data->first;
if (!addr) return false;
Header* header = (Header*)addr;