-
Notifications
You must be signed in to change notification settings - Fork 42
/
ybc.c
2628 lines (2202 loc) · 74.3 KB
/
ybc.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
#include "platform.h" /* Platform-specific functions' implementation. */
#include "config.h" /* Static configuration macros and constants. */
#include "ybc.h"
#include <assert.h> /* assert */
#include <stddef.h> /* size_t */
#include <stdint.h> /* uint*_t */
#include <stdlib.h> /* rand */
#include <string.h> /* memcpy, memcmp, memset */
/*******************************************************************************
* Cache implementation.
*
* Naming conventions:
* - public functions and structures must start with ybc_
* - public macros and constants must start with YBC_
* - private functions and structures must start with m_
* - private macros and constants must start with M_
* - platform-specific functions and structures must start with p_.
* - static configuration macros and constants defined in config.h
* must start with C_.
* Such functions and structures must be defined in platform/<platform_name>.c
* files.
*
* Coding rules:
* - All variables, which are expected to be immutable in the given code block,
* MUST be declared as constants! This provides the following benefits:
* + It prevents from accidental modification of the given variable.
* + It may help dumb compilers with 'constant propagation' optimizations.
******************************************************************************/
/*******************************************************************************
* Aux API.
******************************************************************************/
/*
* Calculates hash for size bytes starting from ptr using
* the given seed.
*/
static uint64_t m_hash_get(const uint64_t seed, const void *const ptr,
const size_t size)
{
/*
* Simple Jenkin's hash.
* See http://en.wikipedia.org/wiki/Jenkins_hash_function .
*
* TODO: use SpookyHash instead. It could be faster and have better
* output distribution.
* See http://www.burtleburtle.net/bob/hash/spooky.html .
*/
const unsigned char *const v = ptr;
uint64_t hash = seed;
for (size_t i = 0; i < size; ++i) {
hash += v[i];
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
return hash;
}
/*******************************************************************************
* File API.
******************************************************************************/
static void m_file_remove_if_exists(const char *const filename)
{
if (filename != NULL && p_file_exists(filename)) {
p_file_remove(filename);
}
}
/*
* Tries opening the given file with the given size.
*
* If force is set, then creates new file with the given size if it doesn't
* exist. Force also leads to file size adjustment on its' mismatch.
*
* If filename is NULL and force is set, then creates an anonymous file,
* which will be automatically deleted after the file is closed.
*
* Returns non-zero on success, zero on failre.
* Sets is_file_created to 1 if new file has been created (including
* anonymous file).
*/
static int m_file_open_or_create(struct p_file *const file,
const char *const filename, const size_t expected_file_size,
const int force, int *const is_file_created)
{
size_t actual_file_size;
*is_file_created = 0;
if (filename == NULL) {
if (!force) {
return 0;
}
/*
* Though we could just dynamically allocate memory
* with expected_file_size instead of creating an anonymous file,
* memory mapped from anonymous file is better than dynamically allocated
* memory due to the following reasons:
* - The memory backed by anonymous file doesn't increase process'
* commit charge ( http://en.wikipedia.org/wiki/Commit_charge ).
* - Sequential VM pages backed by anonymous file are mapped to sequential
* pages in the anonymous file. This eliminates random I/O during
* sequential access to the mapped memory. Of course this is true only
* if the file isn't fragmented. See p_file_resize_and_preallocate() call,
* which is aimed towards reducing file fragmentation.
*/
p_file_create_anonymous(file);
*is_file_created = 1;
}
else if (!p_file_exists(filename)) {
if (!force) {
return 0;
}
p_file_create(file, filename);
*is_file_created = 1;
}
else {
p_file_open(file, filename);
}
p_file_get_size(file, &actual_file_size);
if (actual_file_size != expected_file_size) {
if (!force) {
assert(!*is_file_created);
p_file_close(file);
return 0;
}
/*
* Pre-allocate file space at the moment in order to minimize file
* fragmentation in the future.
*/
p_file_resize_and_preallocate(file, expected_file_size);
}
return 1;
}
/*******************************************************************************
* Storage API.
******************************************************************************/
/*
* Cursor points to the position in the storage.
*/
struct m_storage_cursor
{
/*
* Whenever the offset wraps storage size, the wrap_count is incremented.
*/
size_t wrap_count;
/*
* An offset in the storage for the given cursor.
*/
size_t offset;
};
/*
* Payload points to an item stored in the storage.
*/
struct m_storage_payload
{
/*
* A pointer to the value in the storage.
*/
struct m_storage_cursor cursor;
/* Item's expiration time in milliseconds starting from unix epoch. */
uint64_t expiration_time;
/*
* Size of the item in the storage.
*/
size_t size;
};
/*
* Storage for cached items.
*
* Storage is a circular buffer. New items are appended in the front
* of the storage. Items added into the storage become immutable until the next
* storage wrap.
*
* This layout should result in high write speeds on both HDDs and SSDs.
*/
struct m_storage
{
/*
* A pointer to the next free memory in the storage.
*/
struct m_storage_cursor *next_cursor;
/*
* Storage size in bytes.
*/
size_t size;
/*
* A copy of hash seed from index file.
*
* Each item contains a copy of hash seed in its' metadata for validation
* purposes. See m_storage_metadata_check() for details.
*/
uint64_t hash_seed;
/*
* A pointer to the beginning of the storage.
*/
char *data;
};
/*
* An item acquired from the cache.
*
* Items returned from the cache are wrapped into ybc_item.
* This wrapping prevents items' content to be overwritten while in use.
*/
struct ybc_item
{
/*
* An associated cache handler.
*/
struct ybc *cache;
/*
* Key size for the given item.
*/
size_t key_size;
/*
* All acquired items are organized into doubly linked skiplist with a head
* at ybc->acquired_items_head and a tail at ybc->acquired_items_tail.
*
* The skiplist helps quickly (in O(ln(n)) time, where n is the number
* of currently acquired items) determining the location for newly added item
* in the storage, so the item doesn't corrupt currently acquired items.
*/
/*
* Pointers to the next and previous items in the skiplist.
*
* Pointers to previous items are used for speeding up acquired items'
* release.
*/
struct ybc_item *next[C_ITEM_SKIPLIST_HEIGHT];
struct ybc_item *prev[C_ITEM_SKIPLIST_HEIGHT];
/*
* Item's value location.
*/
struct m_storage_payload payload;
/*
* The flag indicating whether this item is being used in set transaction
* and didn't commited yet.
*/
int is_set_txn;
};
static void m_item_assert_less_equal(const struct ybc_item *const a,
const struct ybc_item *const b)
{
(void)a;
(void)b;
assert(a != b);
assert(a->payload.cursor.offset <= b->payload.cursor.offset);
}
static void m_item_skiplist_init(struct ybc_item *const acquired_items_head,
struct ybc_item *const acquired_items_tail, const size_t storage_size)
{
acquired_items_head->payload.cursor.offset = 0;
acquired_items_head->payload.size = 0;
acquired_items_tail->payload.cursor.offset = storage_size;
acquired_items_tail->payload.size = 0;
for (size_t i = 0; i < C_ITEM_SKIPLIST_HEIGHT; ++i) {
acquired_items_head->next[i] = acquired_items_tail;
acquired_items_head->prev[i] = NULL;
acquired_items_tail->next[i] = NULL;
acquired_items_tail->prev[i] = acquired_items_head;
}
}
static void m_item_skiplist_destroy(struct ybc_item *const acquired_items_head,
struct ybc_item *const acquired_items_tail, const size_t storage_size)
{
(void)acquired_items_head;
(void)acquired_items_tail;
(void)storage_size;
assert(acquired_items_head->payload.cursor.offset == 0);
assert(acquired_items_head->payload.size == 0);
assert(acquired_items_tail->payload.cursor.offset == storage_size);
assert(acquired_items_tail->payload.size == 0);
for (size_t i = 0; i < C_ITEM_SKIPLIST_HEIGHT; ++i) {
assert(acquired_items_head->next[i] == acquired_items_tail);
assert(acquired_items_head->prev[i] == NULL);
assert(acquired_items_tail->next[i] == NULL);
assert(acquired_items_tail->prev[i] == acquired_items_head);
}
}
static void m_item_skiplist_assert_valid(const struct ybc_item *const item,
const size_t i)
{
if (item->next[i] != NULL) {
assert(item == item->next[i]->prev[i]);
m_item_assert_less_equal(item, item->next[i]);
}
if (item->prev[i] != NULL) {
assert(item == item->prev[i]->next[i]);
m_item_assert_less_equal(item->prev[i], item);
}
}
static void m_item_skiplist_get_prevs(
struct ybc_item *const acquired_items_head, struct ybc_item **const prevs,
const size_t offset)
{
struct ybc_item *prev = acquired_items_head;
for (size_t i = 0; i < C_ITEM_SKIPLIST_HEIGHT; ++i) {
assert(prev->payload.cursor.offset <= offset);
struct ybc_item *next = prev->next[i];
while (offset > next->payload.cursor.offset) {
m_item_skiplist_assert_valid(next, i);
prev = next;
next = next->next[i];
}
m_item_skiplist_assert_valid(next, i);
prevs[i] = prev;
}
}
static void m_item_skiplist_add(struct ybc_item *const item) {
const size_t offset = item->payload.cursor.offset;
uint64_t h = m_hash_get(0, &offset, sizeof(offset));
for (size_t i = C_ITEM_SKIPLIST_HEIGHT; i > 0; ) {
--i;
struct ybc_item *const prev = item->next[i];
m_item_assert_less_equal(prev, item);
m_item_assert_less_equal(item, prev->next[i]);
item->next[i] = prev->next[i];
item->prev[i] = prev;
prev->next[i]->prev[i] = item;
prev->next[i] = item;
if (!(h & 1)) {
while (i > 0) {
--i;
item->next[i] = NULL;
item->prev[i] = NULL;
}
return;
}
h >>= 1;
}
}
static void m_item_skiplist_del(struct ybc_item *const item)
{
for (size_t i = C_ITEM_SKIPLIST_HEIGHT; i > 0; ) {
--i;
if (item->next[i] == NULL) {
return;
}
m_item_skiplist_assert_valid(item, i);
item->prev[i]->next[i] = item->next[i];
item->next[i]->prev[i] = item->prev[i];
}
}
static void m_item_skiplist_relocate(struct ybc_item *const dst,
struct ybc_item *const src)
{
*dst = *src;
for (size_t i = C_ITEM_SKIPLIST_HEIGHT; i > 0; ) {
--i;
if (src->next[i] == NULL) {
return;
}
m_item_skiplist_assert_valid(src, i);
src->prev[i]->next[i] = dst;
src->next[i]->prev[i] = dst;
}
}
static void m_storage_fix_size(size_t *const size)
{
if (*size < C_STORAGE_MIN_SIZE) {
*size = C_STORAGE_MIN_SIZE;
}
}
static int m_storage_open(struct m_storage *const storage,
struct p_file *const storage_file,
const char *const filename, const int force, int *const is_file_created)
{
void *ptr;
if (!m_file_open_or_create(storage_file, filename, storage->size, force,
is_file_created)) {
return 0;
}
/*
* Do not cache storage file contents into RAM at the moment, because it can
* be much bigger than RAM size. Allow the OS dealing with storage file
* caching.
*/
p_memory_map(&ptr, storage_file, storage->size);
assert((uintptr_t)storage->size <= UINTPTR_MAX - (uintptr_t)ptr);
storage->data = ptr;
/*
* Do not verify correctness of storage data at the moment due
* to the following reasons:
* - It can take a lot of time if storage file is too big.
* - The cache invalidates items with incorrect keys on the fly.
* - The cache code is designed in the way, which prevents inconsistencies
* in data file under normal mode of operation and even under unexpected
* process termination.
*
* Library users can verify data correctness by embedding and verifiyng
* checksums into item's values (see ybc_simple_set() / ybc_simple_get()
* for example).
*/
return 1;
}
static void m_storage_close(struct m_storage *const storage,
struct p_file *const storage_file)
{
p_memory_unmap(storage->data, storage->size);
p_file_close(storage_file);
}
static void *m_storage_get_ptr(const struct m_storage *const storage,
const size_t offset)
{
assert(offset <= storage->size);
assert((uintptr_t)offset <= UINTPTR_MAX - (uintptr_t)storage->data);
return storage->data + offset;
}
static void m_storage_payload_assert_valid(
const struct m_storage_payload *const payload, const size_t storage_size)
{
(void)payload;
(void)storage_size;
assert(payload->size <= storage_size);
assert(payload->cursor.offset <= storage_size);
assert(payload->cursor.offset <= storage_size - payload->size);
}
static int m_storage_find_free_hole(struct ybc_item *const acquired_items_head,
struct ybc_item *const item, struct m_storage_cursor *const next_cursor,
const size_t item_size, const size_t storage_size)
{
m_item_skiplist_get_prevs(acquired_items_head, item->next,
next_cursor->offset);
const size_t N = C_ITEM_SKIPLIST_HEIGHT - 1;
const struct ybc_item *tmp = item->next[N];
/*
* It is expected that item's properties are already verified
* in ybc_item_get(), so use only assertions here.
*/
m_storage_payload_assert_valid(&tmp->payload, storage_size);
if (next_cursor->offset >= tmp->payload.cursor.offset + tmp->payload.size) {
tmp = tmp->next[N];
m_storage_payload_assert_valid(&tmp->payload, storage_size);
assert(next_cursor->offset <= storage_size - item_size);
if (next_cursor->offset + item_size <= tmp->payload.cursor.offset) {
return 1;
}
}
next_cursor->offset = tmp->payload.cursor.offset + tmp->payload.size;
return 0;
}
/*
* Allocates storage space for the given item with the given item->payload.size.
*
* On success returns non-zero, sets up item->cursor to point to the allocated
* space in the storage.
* Registers the item in acquired_items skiplist if has_overwrite_protection
* is set.
*
* On failure returns zero.
*/
static int m_storage_allocate(struct m_storage *const storage,
struct ybc_item *const acquired_items_head, struct ybc_item *const item,
const int has_overwrite_protection)
{
const size_t item_size = item->payload.size;
assert(item_size > 0);
const size_t storage_size = storage->size;
if (item_size > storage_size) {
return 0;
}
struct m_storage_cursor next_cursor = *storage->next_cursor;
assert(next_cursor.offset <= storage_size);
const size_t initial_offset = next_cursor.offset;
int is_storage_wrapped = 0;
for (;;) {
if (next_cursor.offset > storage_size - item_size) {
/* Hit the end of storage. Wrap the cursor. */
++next_cursor.wrap_count;
next_cursor.offset = 0;
is_storage_wrapped = 1;
}
if (!has_overwrite_protection) {
break;
}
if (m_storage_find_free_hole(acquired_items_head, item, &next_cursor,
item_size, storage_size)) {
break;
}
if (is_storage_wrapped && next_cursor.offset >= initial_offset) {
/* Couldn't find a hole with appropriate size in the storage. */
return 0;
}
}
/*
* Set up item->payload.cursor and register the item
* in acquired_items skiplist.
*/
assert(next_cursor.offset < storage_size);
item->payload.cursor = next_cursor;
if (has_overwrite_protection) {
m_item_skiplist_add(item);
}
/* Update storage->next_cursor */
assert(next_cursor.offset <= storage_size - item_size);
next_cursor.offset += item_size;
*storage->next_cursor = next_cursor;
/*
* Optimization trick: touch the first byte of the item in the allocated space
* under the cache->lock, so the OS pre-fetches this memory
* from the underlying file in-order.
*/
char *const ptr = m_storage_get_ptr(storage, item->payload.cursor.offset);
assert(ptr < storage->data + storage_size);
ptr[0] = 0;
return 1;
}
/*
* Checks payload correctness.
*
* Doesn't check item's key, which is stored in the storage, due to performance
* reasons (avoids random memory access).
*
* See also m_storage_metadata_check().
*
* Returns non-zero on successful check, zero on failure.
*/
static int m_storage_payload_check(const struct m_storage *const storage,
const struct m_storage_cursor *const next_cursor,
const struct m_storage_payload *const payload, const uint64_t current_time)
{
size_t max_offset = next_cursor->offset;
if (payload->expiration_time < current_time) {
/* The item has been expired. */
return 0;
}
if (payload->cursor.wrap_count != next_cursor->wrap_count) {
if (payload->cursor.wrap_count != next_cursor->wrap_count - 1) {
/* The item is oudated or it has invalid wrap_count. */
return 0;
}
if (payload->cursor.offset < next_cursor->offset) {
/* The item is outdated. */
return 0;
}
max_offset = storage->size;
}
if (payload->cursor.offset > max_offset) {
/* The item has invalid offset. */
return 0;
}
if (payload->size > max_offset - payload->cursor.offset) {
/* The item has invalid size. */
return 0;
}
return 1;
}
static size_t m_storage_metadata_get_size(const size_t key_size) {
/*
* Payload metadata contains the following fields:
* - digest (key size ^ payload size ^ hash seed)
* - key data
*/
static const size_t const_metadata_size = sizeof(size_t);
assert(key_size <= SIZE_MAX - const_metadata_size);
return key_size + const_metadata_size;
}
static size_t m_storage_metadata_get_digest(const uint64_t hash_seed,
const size_t key_size, const size_t payload_size)
{
return (size_t)hash_seed ^ key_size ^ payload_size;
}
static void m_storage_metadata_save(
const struct m_storage *const storage,
const struct m_storage_payload *const payload,
const struct ybc_key *const key)
{
const size_t metadata_size = m_storage_metadata_get_size(key->size);
char *ptr = m_storage_get_ptr(storage, payload->cursor.offset);
assert(((uintptr_t)ptr) <= UINTPTR_MAX - metadata_size);
(void)metadata_size;
const size_t digest = m_storage_metadata_get_digest(storage->hash_seed,
key->size, payload->size);
memcpy(ptr, &digest, sizeof(digest));
ptr += sizeof(digest);
memcpy(ptr, key->ptr, key->size);
}
static void m_storage_metadata_update_payload_size(
const struct m_storage *const storage,
const struct m_storage_payload *const payload,
const size_t old_payload_size, const size_t key_size)
{
const size_t metadata_size = m_storage_metadata_get_size(key_size);
char *ptr = m_storage_get_ptr(storage, payload->cursor.offset);
assert(((uintptr_t)ptr) <= UINTPTR_MAX - metadata_size);
(void)metadata_size;
size_t digest;
memcpy(&digest, ptr, sizeof(digest));
digest ^= old_payload_size ^ payload->size;
memcpy(ptr, &digest, sizeof(digest));
}
/*
* Checks metadata correctness for an item with the given payload.
*
* The function is slower than m_storage_payload_check(), because it accesses
* random location in the storage. Use this function only if you really need it.
*
* Returns non-zero on successful check, zero on failure.
*/
static int m_storage_metadata_check(const struct m_storage *const storage,
const struct m_storage_payload *const payload,
const struct ybc_key *const key)
{
const size_t metadata_size = m_storage_metadata_get_size(key->size);
if (payload->size < metadata_size) {
/*
* Payload's size cannot be smaller than the size of metadata,
* because payload includes the metadata.
*/
return 0;
}
const char *ptr = m_storage_get_ptr(storage, payload->cursor.offset);
assert(((uintptr_t)ptr) <= UINTPTR_MAX - metadata_size);
const size_t digest = m_storage_metadata_get_digest(storage->hash_seed,
key->size, payload->size);
if (memcmp(ptr, &digest, sizeof(digest))) {
/* Invalid digest. */
return 0;
}
ptr += sizeof(digest);
if (memcmp(ptr, key->ptr, key->size)) {
/* Invalid key data. */
return 0;
}
return 1;
}
/*******************************************************************************
* Working set defragmentation API.
*
* The defragmentation tries minimizing working set fragmentation by packing
* frequently accessed items into a contiguous memory area.
*
* The defragmentation can reduce working set size for caches containing
* a lot of items with sizes smaller than VM page size. For instance, a VM page
* can contain up to 32 items each with 128 bytes size. Suppose each
* page contains only one frequently requested item. Then the storage
* effectively wastes 31*128 bytes per VM page. The defragmentation would
* compact frequently accessed items (aka 'working set') into a contiguous
* memory area, which will occupy only 1/32s (~3%) of initial VM space.
*
* The defragmentation also may prolong life for frequently requested small
* items. Such items are always maintained in the front of storage, so they
* won't be deleted on storage space wrap.
*
* The defragmentation won't help for caches containing a lot of large items
* with sizes much larger than VM page size (hundreds of KBs or larger).
*
* TODO: automatically adjust estimated working set size in runtime. Currently
* it can be set only at cache opening.
******************************************************************************/
static void m_ws_fix_hot_data_size(size_t *const hot_data_size,
const size_t storage_size)
{
if (*hot_data_size > storage_size / 2) {
*hot_data_size = storage_size / 2;
}
}
/*
* Defragments the given item, i.e. moves it into the front of storage's
* free space.
*
* There is a race condition possible when another thread adds new item
* with the given key before the defragmentation for this item is complete.
* In this case new item will become overwritten by the old item after
* the defragmentation is complete. But since this is a cache, not a persistent
* storage, this should be OK - subsequent readers should notice old value
* and overwrite it with new value.
*
* Since this operation can be quite costly, avoid performing it in hot paths.
*/
static void m_ws_defragment(struct ybc *const cache,
const struct ybc_item *const item, const struct ybc_key *const key)
{
struct ybc_value value;
ybc_item_get_value(item, &value);
(void)ybc_item_set(cache, key, &value);
}
/*
* Checks whether the item pointed by the given payload should be defragmented.
*
* Returns 1 if the item should be defragmented, i.e. should be moved
* to the front of the storage. Otherwise returns 0.
*/
static int m_ws_should_defragment(const struct m_storage *const storage,
const struct m_storage_cursor *const next_cursor,
const struct m_storage_payload *const payload, const size_t hot_data_size)
{
if (hot_data_size == 0) {
/* Defragmentation is disabled. */
return 0;
}
const size_t distance =
(next_cursor->offset >= payload->cursor.offset) ?
(next_cursor->offset - payload->cursor.offset) :
(storage->size - (payload->cursor.offset - next_cursor->offset));
if (distance < hot_data_size) {
/* Do not defragment recently added or defragmented items. */
return 0;
}
if (payload->size > C_WS_MAX_MOVABLE_ITEM_SIZE) {
/* Do not defragment large items. */
return 0;
}
/*
* It is OK using non-thread-safe and non-reentrant rand() here,
* since we do not need reproducible sequence of random values.
*/
if ((rand() % 100) >= C_WS_DEFRAGMENT_PROBABILITY) {
/*
* Probabalistically skip items to be defragmented.
* This way one-off items (i.e. items requested only once) are likely
* to be skipped, while frequently accessed items will be eventually
* defragmented.
*/
return 0;
}
return 1;
}
/*******************************************************************************
* Key digest API.
*
* TODO: probably remove this level of abstraction?
******************************************************************************/
/*
* A digest of cache key.
*/
struct m_key_digest
{
uint64_t digest;
};
static const struct m_key_digest M_KEY_DIGEST_EMPTY = {
.digest = 0,
};
static int m_key_digest_equal(const struct m_key_digest *const first,
const struct m_key_digest *const second)
{
return first->digest == second->digest;
}
static int m_key_digest_is_empty(const struct m_key_digest *const key_digest)
{
return m_key_digest_equal(key_digest, &M_KEY_DIGEST_EMPTY);
}
static void m_key_digest_clear(struct m_key_digest *const key_digest)
{
*key_digest = M_KEY_DIGEST_EMPTY;
}
static void m_key_digest_get(struct m_key_digest *const key_digest,
const uint64_t hash_seed, const struct ybc_key *const key)
{
key_digest->digest = m_hash_get(hash_seed, key->ptr, key->size);
if (m_key_digest_is_empty(key_digest)) {
++key_digest->digest;
}
}
static size_t m_key_digest_mod(const struct m_key_digest *const key_digest,
const size_t n)
{
assert(!m_key_digest_is_empty(key_digest));
return key_digest->digest % n;
}
/*******************************************************************************
* Map API.
******************************************************************************/
/*
* It is expected that C_MAP_BUCKET_SIZE is a power of 2.
*/
static const size_t M_MAP_BUCKET_MASK = C_MAP_BUCKET_SIZE - 1;
/*
* The size of a compound map item, which consists of key digest
* and storage payload.
*/
#define M_MAP_ITEM_SIZE (sizeof(struct m_key_digest) + \
sizeof(struct m_storage_payload))
/*
* The size of aux data in the map file.
*
* Aux data consists of the following items:
* - m_storage_cursor
* - hash_seed
*/
#define M_MAP_AUX_DATA_SIZE (sizeof(struct m_storage_cursor) + sizeof(uint64_t))
/*
* The maximum allowed number of slots in the map.
*/
static const size_t M_MAP_SLOTS_COUNT_LIMIT = (SIZE_MAX - M_MAP_AUX_DATA_SIZE) /
M_MAP_ITEM_SIZE;
/*
* Hash map, which maps key digests to cache items from the storage.
*
* The code below intentionally omits serialization of concurrent access
* to key_digests and payloads, i.e. it intentially allows race conditions,
* which may lead to broken key_digest and/or payload values.
* Such breakage is expected - it is automatically recovered by clearing broken
* slots. m_storage_payload_check() and m_storage_metadata_check() are used
* for detecting broken slots in the map.
*/
struct m_map
{
/*
* The number of slots in the map.
*/
size_t slots_count;
/*
* Slots' key digests.
*/
struct m_key_digest *key_digests;
/*
* Slots' payloads.
*/
struct m_storage_payload *payloads;
};
static void m_map_fix_slots_count(size_t *const slots_count,
const size_t data_file_size)
{
/*
* Preserve the order of conditions below!
* This guarantees that the resulting slots_count will be between
* C_MAP_BUCKET_SIZE and M_MAP_SLOTS_COUNT_LIMIT and
* is divided by C_MAP_BUCKET_SIZE.
*/
if (*slots_count > data_file_size) {
/*
* The number of slots cannot exceed the size of data file, because
* each slot requires at least one byte in the data file for one-byte key.
*/
*slots_count = data_file_size;
}
if (*slots_count < C_MAP_BUCKET_SIZE) {
*slots_count = C_MAP_BUCKET_SIZE;
}
if (*slots_count > M_MAP_SLOTS_COUNT_LIMIT) {
*slots_count = M_MAP_SLOTS_COUNT_LIMIT;
}
if (*slots_count % C_MAP_BUCKET_SIZE) {
*slots_count += C_MAP_BUCKET_SIZE - (*slots_count % C_MAP_BUCKET_SIZE);
}
}
static void m_map_init(struct m_map *const map, const size_t slots_count,
struct m_key_digest *const key_digests,
struct m_storage_payload *const payloads)
{
assert(C_MAP_BUCKET_SIZE == M_MAP_BUCKET_MASK + 1);
assert((C_MAP_BUCKET_SIZE & M_MAP_BUCKET_MASK) == 0);
map->slots_count = slots_count;
map->key_digests = key_digests;
map->payloads = payloads;
}
static void m_map_destroy(struct m_map *const map)
{
map->slots_count = 0;
map->key_digests = NULL;
map->payloads = NULL;
}
/*
* Looks up slot index for the given key digest.
*
* Sets start_index to the index of the first slot in the bucket,
* which contains the given key digest.
*
* Sets slot_index to the index of the slot containing the given key.
*