-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathpogocache.c
More file actions
2149 lines (2029 loc) · 64.3 KB
/
Copy pathpogocache.c
File metadata and controls
2149 lines (2029 loc) · 64.3 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
// https://github.com/tidwall/pogocache
//
// Copyright 2025 Polypoint Labs, LLC. All rights reserved.
// This file is part of the Pogocache project.
// Use of this source code is governed by the MIT that can be found in
// the LICENSE file.
//
// For alternative licensing options or general questions, please contact
// us at licensing@polypointlabs.com.
//
// Unit pogocache.c is the primary caching engine library which is designed
// to be standalone and embeddable.
#include <stdbool.h>
#include <inttypes.h>
#include <stdatomic.h>
#include <errno.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include "pogocache.h"
#define MINLOADFACTOR_RH 55 // 55%
#define MAXLOADFACTOR_RH 95 // 95%
#define DEFLOADFACTOR 75 // 75%
#define SHRINKAT 10 // 10%
#define DEFSHARDS 4096 // default number of shards
#define INITCAP 64 // intial number of buckets per shard
// #define NOSIXPACK
// #define DBGCHECKENTRY
// #define NO48BITPTRS
#if INTPTR_MAX == INT64_MAX
#ifdef NO48BITPTRS
#define PTRSIZE 8
#else
#define PTRSIZE 6
#endif
#elif INTPTR_MAX == INT32_MAX
#define PTRSIZE 4
#else
#error Unknown pointer size
#endif
#if defined(__x86_64__) || defined(__i386__)
#define cpu_yield() __builtin_ia32_pause()
#elif defined(__aarch64__) || defined(__arm__)
#define cpu_yield() __asm__ __volatile__("yield")
#else
#define cpu_yield()
#endif
static struct pogocache_count_opts defcountopts = { 0 };
static struct pogocache_total_opts deftotalopts = { 0 };
static struct pogocache_size_opts defsizeopts = { 0 };
static struct pogocache_sweep_opts defsweepopts = { 0 };
static struct pogocache_clear_opts defclearopts = { 0 };
static struct pogocache_store_opts defstoreopts = { 0 };
static struct pogocache_load_opts defloadopts = { 0 };
static struct pogocache_delete_opts defdeleteopts = { 0 };
static struct pogocache_iter_opts defiteropts = { 0 };
static struct pogocache_sweep_poll_opts defsweeppollopts = { 0 };
static int64_t nanotime(struct timespec *ts) {
int64_t x = ts->tv_sec;
x *= 1000000000;
x += ts->tv_nsec;
return x;
}
// returns monotonic nanoseconds of the CPU clock.
static int64_t gettime(void) {
struct timespec now = { 0 };
#ifdef __linux__
clock_gettime(CLOCK_BOOTTIME, &now);
#elif defined(__APPLE__)
clock_gettime(CLOCK_UPTIME_RAW, &now);
#else
clock_gettime(CLOCK_MONOTONIC, &now);
#endif
return nanotime(&now);
}
// returns offset of system clock since first call in thread.
static int64_t getnow(void) {
return gettime();
}
// https://github.com/tidwall/th64
static uint64_t th64(const void *data, size_t len, uint64_t seed) {
uint8_t*p=(uint8_t*)data,*e=p+len;
uint64_t r=0x14020a57acced8b7,x,h=seed;
while(p+8<=e)memcpy(&x,p,8),x*=r,p+=8,x=x<<31|x>>33,h=h*r^x,h=h<<31|h>>33;
while(p<e)h=h*r^*(p++);
return(h=h*r+len,h^=h>>31,h*=r,h^=h>>31,h*=r,h^=h>>31,h*=r,h);
}
// Load a pointer from an unaligned memory.
static void *load_ptr(const uint8_t data[PTRSIZE]) {
#if PTRSIZE == 4
uint32_t uptr;
memcpy(&uptr, data, 4);
return (void*)(uintptr_t)uptr;
#elif PTRSIZE == 6
uint64_t uptr = 0;
uptr |= ((uint64_t)data[0])<<0;
uptr |= ((uint64_t)data[1])<<8;
uptr |= ((uint64_t)data[2])<<16;
uptr |= ((uint64_t)data[3])<<24;
uptr |= ((uint64_t)data[4])<<32;
uptr |= ((uint64_t)data[5])<<40;
return (void*)(uintptr_t)uptr;
#elif PTRSIZE == 8
uint64_t uptr;
memcpy(&uptr, data, 8);
return (void*)(uintptr_t)uptr;
#endif
}
// Store a pointer into unaligned memory.
static void store_ptr(uint8_t data[PTRSIZE], void *ptr) {
#if PTRSIZE == 4
uint32_t uptr = (uintptr_t)(void*)ptr;
memcpy(data, &uptr, 4);
#elif PTRSIZE == 6
uint64_t uptr = (uintptr_t)(void*)ptr;
data[0] = (uptr>>0)&0xFF;
data[1] = (uptr>>8)&0xFF;
data[2] = (uptr>>16)&0xFF;
data[3] = (uptr>>24)&0xFF;
data[4] = (uptr>>32)&0xFF;
data[5] = (uptr>>40)&0xFF;
#elif PTRSIZE == 8
uint64_t uptr = (uintptr_t)(void*)ptr;
memcpy(data, &uptr, 8);
#endif
}
// https://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html
static uint64_t mix13(uint64_t key) {
key ^= (key >> 30);
key *= UINT64_C(0xbf58476d1ce4e5b9);
key ^= (key >> 27);
key *= UINT64_C(0x94d049bb133111eb);
key ^= (key >> 31);
return key;
}
// Sixpack compression algorithm
// - Converts a simple 8-bit string into 6-bit string.
// - Intended to be used on small strings that only use characters commonly
// used for keys in KV data stores.
// - Allows the following 64 item character set:
// -.0123456789:ABCDEFGHIJKLMNOPRSTUVWXY_abcdefghijklmnopqrstuvwxy
// Note that the characters "QZz" are not included.
// - Sortable and comparable using memcmp.
static char tosix[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0-15
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16-31
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, // 32-47
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0, 0, 0, 0, 0, // 48-63
0, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, // 64-79
29, 0, 30, 31, 32, 33, 34, 35, 36, 37, 0, 0, 0, 0, 0, 38, // 80-95
0, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, // 96-111
54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 0, 0, 0, 0, 0, 0, // 112-127
};
static char fromsix[] = {
0, '-', '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', '_', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y'
};
// 0: [000000..] bitpos: 0
// 1: [00000011][1111....] bitpos: 6
// 2: [00000011][11112222][22......] bitpos: 12
// 3: [00000011][11112222][22333333] bitpos: 18
// Sixpack data
// Fills the data in dst and returns the number of bytes filled.
// Returns 0 if not a sixpackable.
// The dst array must be large enough to hold packed value
static int sixpack(const char *data, int len, char dst[]){
const unsigned char *bytes = (unsigned char*)data;
int j = 0;
for (int i = 0; i < len; i++) {
int k6v = tosix[bytes[i]];
if (k6v == 0) {
return 0;
}
if (i%4 == 0) {
dst[j++] = k6v<<2;
} else if (i%4 == 1) {
dst[j-1] |= k6v>>4;
dst[j++] = k6v<<4;
} else if (i%4 == 2) {
dst[j-1] |= k6v>>2;
dst[j++] = k6v<<6;
} else {
dst[j-1] |= k6v;
}
}
return j;
}
// (Un)sixpack data.
// Fills the data in dst and returns the len of original data.
// The data must be sixpacked and len must be > 0.
// The dst array must be large enough to hold unpacked value
static int unsixpack(const char *data, int len, char dst[]) {
const unsigned char *bytes = (unsigned char*)data;
int j = 0;
int k = 0;
for (int i = 0; i < len; i++) {
if (k == 0) {
dst[j++] = fromsix[bytes[i]>>2];
k++;
} else if (k == 1) {
dst[j++] = fromsix[((bytes[i-1]<<4)|(bytes[i]>>4))&63];
k++;
} else {
dst[j++] = fromsix[((bytes[i-1]<<2)|(bytes[i]>>6))&63];
dst[j++] = fromsix[bytes[i]&63];
k = 0;
}
}
if (j > 0 && dst[j-1] == 0) {
j--;
}
return j;
}
// Safely adds two int64_t values, clamping on overflow.
static int64_t int64_add_clamp(int64_t a, int64_t b) {
if (!((a ^ b) < 0)) { // Opposite signs can't overflow
if (a > 0) {
if (b > INT64_MAX - a) {
return INT64_MAX;
}
} else if (b < INT64_MIN - a) {
return INT64_MIN;
}
}
return a + b;
}
/// https://github.com/tidwall/varint.c
static int varint_write_u64(void *data, uint64_t x) {
uint8_t *bytes = data;
if (x < 128) {
*bytes = x;
return 1;
}
int n = 0;
do {
bytes[n++] = (uint8_t)x | 128;
x >>= 7;
} while (x >= 128);
bytes[n++] = (uint8_t)x;
return n;
}
static int varint_read_u64(const void *data, uint64_t *x) {
const uint8_t *bytes = data;
if (bytes[0] < 128) {
*x = bytes[0];
return 1;
}
uint64_t b;
*x = 0;
size_t i = 0;
while (1) {
b = bytes[i];
*x |= (b & 127) << (7 * i);
if (b < 128) {
return i + 1;
}
i++;
}
}
// Mostly a copy of the pogocache_opts, but used internally
// See the opts_to_ctx function for translation.
struct pgctx {
void *(*malloc)(size_t);
void (*free)(void*);
size_t (*malloc_size)(void*);
void (*yield)(void *udata);
void *udata;
void (*evicted)(int shard, int reason, int64_t time, const void *key,
size_t keylen, const void *val, size_t vallen, int64_t expires,
uint32_t flags, uint64_t cas, void *udata);
void (*notify)(int shard, int64_t time, struct pogocache_entry *new_entry,
struct pogocache_entry *old_entry, void *udata);
bool usenotify;
bool usecas;
bool nosixpack;
bool noevict;
bool allowshrink;
bool usethreadbatch;
int nshards;
double loadfactor;
double shrinkfactor;
uint64_t seed;
};
// The entry structure is a simple allocation with all the fields, being
// variable in size, slammed together contiguously. There's a timestamp,
// reference counter, and various fields the describe the contents of data.
// The data field contains the variable sized data, including key, value,
// expiration, flags, etc. The size of the entire allocation of the entry is
// stored as a prefix in the data field, and it can be 1, 2, 4, or 8 bytes.
struct entry {
int64_t time; // entry timestamp
atomic_int rc; // reference counter
unsigned memszsz:2; // memory size field size, 0=1, 1=2, 2=4, 3=8
unsigned has_expires:1; // has 64-bit expiration
unsigned has_flags:1; // has 32-bit flags
unsigned has_sixpack:1; // key is sixpack encoded
uint8_t data[];
};
static size_t entry_memsize(const struct entry *entry) {
if (entry->memszsz == 0) {
return *entry->data;
}
if (entry->memszsz == 1) {
uint16_t x;
memcpy(&x, entry->data, 2);
return x;
}
if (entry->memszsz == 2) {
uint32_t x;
memcpy(&x, entry->data, 4);
return x;
}
uint64_t x;
memcpy(&x, entry->data, 8);
return x;
}
static int64_t entry_expires(const struct entry *entry) {
if (!entry->has_expires) {
return 0;
}
int64_t expires = 0;
const uint8_t *p = entry->data;
p += 1<<entry->memszsz;
memcpy(&expires, p, 8);
return expires;
}
static int64_t entry_time(struct entry *entry) {
return entry->time;
}
static void entry_settime(struct entry *entry, int64_t time) {
entry->time = time;
}
static bool entry_alive_exp(int64_t expires, int64_t now) {
return expires == 0 || expires > now;
}
static bool entry_alive(struct entry *entry, int64_t now) {
return entry_alive_exp(entry_expires(entry), now);
}
static uint64_t entry_cas(const struct entry *entry, struct pgctx *ctx) {
if (!ctx->usecas) {
return 0;
}
uint64_t cas = 0;
const uint8_t *p = entry->data;
p += 1<<entry->memszsz; // memsize
p += (entry->has_expires&1)<<3; // expires
p += (entry->has_flags&1)<<2; // flags
memcpy(&cas, p, 8); // cas
return cas;
}
// returns the raw key. sixpack will be returned in it's raw format
static const char *entry_rawkey(const struct entry *entry, size_t *keylen_out,
struct pgctx *ctx)
{
uint64_t keylen;
const uint8_t *p = entry->data;
p += 1<<entry->memszsz; // memsize
p += (entry->has_expires&1)<<3; // expires
p += (entry->has_flags&1)<<2; // flags
p += (ctx->usecas&1)<<3; // cas
p += varint_read_u64(p, &keylen); // keylen
*keylen_out = keylen;
return (const char*)p;
}
// returns the key. If using sixpack make sure to copy the result asap.
static const char *entry_key(const struct entry *entry, size_t *keylen_out,
char buf[128], struct pgctx *ctx)
{
size_t keylen;
const char *key = entry_rawkey(entry, &keylen, ctx);
if (entry->has_sixpack) {
keylen = unsixpack(key, (int)keylen, buf);
key = buf;
}
*keylen_out = keylen;
return key;
}
// returns the value.
static const char *entry_value(const struct entry *entry, size_t *vallen_out,
struct pgctx *ctx)
{
size_t size = entry_memsize(entry);
size_t keylen;
const uint8_t *p = (uint8_t*)entry_rawkey(entry, &keylen, ctx);
p += keylen;
*vallen_out = size-(p-entry->data)-sizeof(struct entry);
return (const char*)p;
}
static bool entry_sixpacked(const struct entry *entry) {
return entry->has_sixpack;
}
static size_t entry_extract(const struct entry *entry, const char **key,
size_t *keylen, char buf[128], const char **val, size_t *vallen,
int64_t *expires, uint32_t *flags, uint64_t *cas,
struct pgctx *ctx)
{
(void)ctx;
const uint8_t *p = entry->data;
size_t memsize = entry_memsize(entry);
p += 1<<entry->memszsz;
if (entry->has_expires) {
if (expires) {
memcpy(expires, p, 8);
}
p += 8; // expires
} else {
if (expires) {
*expires = 0;
}
}
if (entry->has_flags) {
if (flags) {
memcpy(flags, p, 4);
}
p += 4; // flags
} else {
if (flags) {
*flags = 0;
}
}
if (ctx->usecas) {
if (cas) {
memcpy(cas, p, 8);
}
p += 8; // cas
} else {
if (cas) {
*cas = 0;
}
}
uint64_t x;
p += varint_read_u64(p, &x); // keylen
if (key) {
*key = (char*)p;
*keylen = x;
if (entry->has_sixpack) {
*keylen = unsixpack(*key, (int)*keylen, buf);
*key = buf;
}
}
p += x; // key
if (val) {
*val = (char*)p;
*vallen = memsize-(p-entry->data)-sizeof(struct entry);
}
return memsize;
}
// The 'cas' param should always be set to zero unless loading from disk.
// Setting to zero will set a new unique cas to the entry.
static struct entry *entry_new(const char *key, size_t keylen, const char *val,
size_t vallen, int64_t expires, uint32_t flags, uint64_t cas,
struct pgctx *ctx)
{
#ifdef NOSIXPACK
bool usesixpack = false;
#else
bool usesixpack = !ctx->nosixpack;
#endif
#ifdef DBGCHECKENTRY
// printf("entry_new(key=[%.*s], keylen=%zu, val=[%.*s], vallen=%zu, "
// "expires=%" PRId64 ", flags=%" PRId32 ", cas=%" PRIu64 ", "
// "usesixpack=%d\n", (int)keylen, key, keylen, (int)vallen, key, vallen,
// expires, flags, cas, usesixpack);
int64_t oexpires = expires;
uint32_t oflags = flags;
uint64_t ocas = cas;
const char *okey = key;
size_t okeylen = keylen;
const char *oval = val;
size_t ovallen = vallen;
#endif
uint8_t keylenbuf[10];
size_t prefixlen = 0;
if (expires > 0) {
prefixlen += 8;
}
if (flags > 0) {
prefixlen += 4;
}
if (ctx->usecas) {
prefixlen += 8;
}
bool has_sixpack = 0;
char buf[128];
if (usesixpack && keylen <= 128) {
size_t len = sixpack(key, keylen, buf);
if (len > 0) {
has_sixpack = 1;
keylen = len;
key = buf;
}
}
size_t nkeylen = varint_write_u64(keylenbuf, keylen);
struct entry *entry_out = 0;
size_t size = sizeof(struct entry)+prefixlen+nkeylen+keylen+vallen;
// Calculate the number of bytes needed to store the size of the entire
// allocation.
int memszsz;
if (size <= 0xFF-1) {
memszsz = 0;
size += 1;
} else if (size <= 0xFFFF-2) {
memszsz = 1;
size += 2;
} else if (size <= 0xFFFFFFFF-4) {
memszsz = 2;
size += 4;
} else {
memszsz = 3;
size += 8;
}
// printf("malloc=%p size=%zu, ctx=%p\n", ctx->malloc, size, ctx);
void *mem = ctx->malloc(size);
struct entry *entry = mem;
if (!entry) {
return 0;
}
entry->time = 0;
atomic_init(&entry->rc, 1);
entry->memszsz = memszsz;
entry->has_expires = expires > 0;
entry->has_flags = flags > 0;
entry->has_sixpack = has_sixpack;
uint8_t *p = (void*)entry->data;
if (memszsz == 0) {
*p = size;
p++;
} else if (memszsz == 1) {
uint16_t x = size;
memcpy(p, &x, 2);
p += 2;
} else if (memszsz == 2) {
uint32_t x = size;
memcpy(p, &x, 4);
p += 4;
} else {
uint64_t x = size;
memcpy(p, &x, 8);
p += 8;
}
if (expires > 0) {
memcpy(p, &expires, 8);
p += 8;
}
if (flags > 0) {
memcpy(p, &flags, 4);
p += 4;
}
if (ctx->usecas) {
memcpy(p, &cas, 8);
p += 8;
}
memcpy(p, keylenbuf, nkeylen);
p += nkeylen;
memcpy(p, key, keylen);
p += keylen;
memcpy(p, val, vallen);
p += vallen;
entry_out = entry;
#ifdef DBGCHECKENTRY
// check the key
const char *key2, *val2;
size_t keylen2, vallen2;
int64_t expires2;
uint32_t flags2;
uint64_t cas2;
char buf1[256];
entry_extract(entry_out, &key2, &keylen2, buf1, &val2, &vallen2, &expires2,
&flags2, &cas2, ctx);
assert(expires2 == oexpires);
assert(flags2 == oflags);
if (ctx->usecas) {
assert(cas2 == ocas);
}
assert(keylen2 == okeylen);
assert(memcmp(key2, okey, okeylen) == 0);
assert(vallen2 == ovallen);
assert(memcmp(val2, oval, ovallen) == 0);
// printf("%zu\n", size);
assert(entry_memsize(entry_out) == size);
key2 = entry_key(entry, &keylen2, buf1, ctx);
assert(keylen2 == okeylen);
assert(memcmp(key2, okey, okeylen) == 0);
const char *val3;
size_t vallen3;
val3 = entry_value(entry, &vallen3, ctx);
assert(val3 == val2);
assert(vallen3 == ovallen);
assert(memcmp(val3, oval, ovallen) == 0);
#endif
return entry_out;
}
static void entry_free(struct entry *entry, struct pgctx *ctx) {
if (atomic_fetch_sub(&entry->rc, 1) > 1) {
return;
}
ctx->free(entry);
}
static struct entry *entry_clone(struct entry *entry) {
atomic_fetch_add(&entry->rc, 1);
return entry;
}
static int entry_compare(const struct entry *a, const struct entry *b,
struct pgctx *ctx)
{
size_t akeylen, bkeylen;
char buf1[256], buf2[256];
const char *akey;
const char *bkey;
if (entry_sixpacked(a) == entry_sixpacked(b)) {
akey = entry_rawkey(a, &akeylen, ctx);
bkey = entry_rawkey(b, &bkeylen, ctx);
} else {
akey = entry_key(a, &akeylen, buf1, ctx);
bkey = entry_key(b, &bkeylen, buf2, ctx);
}
size_t size = akeylen < bkeylen ? akeylen : bkeylen;
int cmp = memcmp(akey, bkey, size);
if (cmp == 0) {
cmp = akeylen < bkeylen ? -1 : akeylen > bkeylen;
}
return cmp;
}
#ifndef HASHSIZE
#define HASHSIZE 3
#endif
#if HASHSIZE < 1 || HASHSIZE > 4
#error bad hash size
#endif
struct bucket {
uint8_t entry[PTRSIZE]; // 48-bit pointer
uint8_t hash[HASHSIZE]; // 24-bit hash
uint8_t dib; // distance to bucket
};
static_assert(sizeof(struct bucket) == PTRSIZE+HASHSIZE+1, "bad bucket size");
struct map {
int cap; // initial capacity
int nbuckets; // number of buckets
int count; // current entry count
int mask; // bit mask for
int growat;
int shrinkat;
struct bucket *buckets;
uint64_t total; // current entry count
size_t entsize; // memory size of all entries
};
struct shard {
atomic_uintptr_t lock; // spinlock (batch pointer)
uint64_t cas; // compare and store value
struct map map; // robinhood hashmap
// for batch linked list only
struct shard *next;
};
static void lock_init(struct shard *shard) {
atomic_init(&shard->lock, 0);
}
struct batch {
struct pogocache *cache; // associated cache.
struct shard *shard; // first locked shard
int64_t time; // timestamp
};
struct pogocache {
bool isbatch;
union {
struct pgctx ctx;
struct batch batch;
};
struct shard shards[];
};
static struct entry *get_entry(struct bucket *bucket) {
return load_ptr(bucket->entry);
}
static void set_entry(struct bucket *bucket, struct entry *entry) {
store_ptr(bucket->entry, entry);
}
#if HASHSIZE == 1
static uint32_t clip_hash(uint32_t hash) {
return hash&0xFF;
}
static void write_hash(uint8_t data[1], uint32_t hash) {
data[0] = (hash>>0)&0xFF;
}
static uint32_t read_hash(uint8_t data[1]) {
uint32_t hash = 0;
hash |= ((uint64_t)data[0])<<0;
return hash;
}
#elif HASHSIZE == 2
static uint32_t clip_hash(uint32_t hash) {
return hash&0xFFFF;
}
static void write_hash(uint8_t data[2], uint32_t hash) {
data[0] = (hash>>0)&0xFF;
data[1] = (hash>>8)&0xFF;
}
static uint32_t read_hash(uint8_t data[2]) {
uint32_t hash = 0;
hash |= ((uint64_t)data[0])<<0;
hash |= ((uint64_t)data[1])<<8;
return hash;
}
#elif HASHSIZE == 3
static uint32_t clip_hash(uint32_t hash) {
return hash&0xFFFFFF;
}
static void write_hash(uint8_t data[3], uint32_t hash) {
data[0] = (hash>>0)&0xFF;
data[1] = (hash>>8)&0xFF;
data[2] = (hash>>16)&0xFF;
}
static uint32_t read_hash(uint8_t data[3]) {
uint32_t hash = 0;
hash |= ((uint64_t)data[0])<<0;
hash |= ((uint64_t)data[1])<<8;
hash |= ((uint64_t)data[2])<<16;
return hash;
}
#else
static uint32_t clip_hash(uint32_t hash) {
return hash;
}
static void write_hash(uint8_t data[4], uint32_t hash) {
data[0] = (hash>>0)&0xFF;
data[1] = (hash>>8)&0xFF;
data[2] = (hash>>16)&0xFF;
data[3] = (hash>>24)&0xFF;
}
static uint32_t read_hash(uint8_t data[4]) {
uint32_t hash = 0;
hash |= ((uint64_t)data[0])<<0;
hash |= ((uint64_t)data[1])<<8;
hash |= ((uint64_t)data[2])<<16;
hash |= ((uint64_t)data[3])<<24;
return hash;
}
#endif
static uint32_t get_hash(struct bucket *bucket) {
return read_hash(bucket->hash);
}
static void set_hash(struct bucket *bucket, uint32_t hash) {
write_hash(bucket->hash, hash);
}
static uint8_t get_dib(struct bucket *bucket) {
return bucket->dib;
}
static void set_dib(struct bucket *bucket, uint8_t dib) {
bucket->dib = dib;
}
static bool map_init(struct map *map, size_t cap, struct pgctx *ctx) {
memset(map, 0, sizeof(struct map));
map->cap = cap;
map->nbuckets = cap;
map->mask = map->nbuckets-1;
map->growat = map->nbuckets * ctx->loadfactor;
map->shrinkat = map->nbuckets * ctx->shrinkfactor;
size_t size = sizeof(struct bucket)*map->nbuckets;
map->buckets = ctx->malloc(size);
if (!map->buckets) {
// nomem
memset(map, 0, sizeof(struct map));
return false;
}
memset(map->buckets, 0, size);
return true;
}
static bool resize(struct map *map, size_t new_cap, struct pgctx *ctx) {
struct map map2;
if (!map_init(&map2, new_cap, ctx)) {
return false;
}
for (int i = 0; i < map->nbuckets; i++) {
struct bucket ebkt = map->buckets[i];
if (get_dib(&ebkt)) {
set_dib(&ebkt, 1);
size_t j = get_hash(&ebkt) & map2.mask;
while (1) {
if (get_dib(&map2.buckets[j]) == 0) {
map2.buckets[j] = ebkt;
break;
}
if (get_dib(&map2.buckets[j]) < get_dib(&ebkt)) {
struct bucket tmp = map2.buckets[j];
map2.buckets[j] = ebkt;
ebkt = tmp;
}
j = (j + 1) & map2.mask;
set_dib(&ebkt, get_dib(&ebkt)+1);
}
}
}
size_t org_entsize = map->entsize;
uint64_t org_total = map->total;
int org_cap = map->cap;
int org_count = map->count;
ctx->free(map->buckets);
memcpy(map, &map2, sizeof(struct map));
map->cap = org_cap;
map->count = org_count;
map->entsize = org_entsize;
map->total = org_total;
return true;
}
static bool map_insert(struct map *map, struct entry *entry, uint32_t hash,
struct entry **old, struct pgctx *ctx)
{
hash = clip_hash(hash);
if (map->count >= map->growat) {
if (!resize(map, map->nbuckets*2, ctx)) {
*old = 0;
return false;
}
}
map->entsize += entry_memsize(entry);
struct bucket ebkt;
set_entry(&ebkt, entry);
set_hash(&ebkt, hash);
set_dib(&ebkt, 1);
size_t i = hash & map->mask;
while (1) {
if (get_dib(&map->buckets[i]) == 0) {
// new entry
map->buckets[i] = ebkt;
map->count++;
map->total++;
*old = 0;
return true;
}
if (get_hash(&ebkt) == get_hash(&map->buckets[i]) &&
entry_compare(get_entry(&ebkt), get_entry(&map->buckets[i]),
ctx) == 0)
{
// replaced
*old = get_entry(&map->buckets[i]);
map->entsize -= entry_memsize(*old);
set_entry(&map->buckets[i], get_entry(&ebkt));
return true;
}
if (get_dib(&map->buckets[i]) < get_dib(&ebkt)) {
struct bucket tmp = map->buckets[i];
map->buckets[i] = ebkt;
ebkt = tmp;
}
i = (i + 1) & map->mask;
set_dib(&ebkt, get_dib(&ebkt)+1);
}
}
static bool bucket_eq(struct map *map, size_t i, const char *key,
size_t keylen, uint32_t hash, struct pgctx *ctx)
{
if (get_hash(&map->buckets[i]) != hash) {
return false;
}
size_t keylen2;
char buf[128];
const char *key2 = entry_key(get_entry(&map->buckets[i]), &keylen2, buf,
ctx);
return keylen == keylen2 && memcmp(key, key2, keylen) == 0;
}
// Returns the bucket index for key, or -1 if not found.
static int map_get_bucket(struct map *map, const char *key, size_t keylen,
uint32_t hash, struct pgctx *ctx)
{
hash = clip_hash(hash);
size_t i = hash & map->mask;
while (1) {
struct bucket *bkt = &map->buckets[i];
if (get_dib(bkt) == 0) {
return -1;
}
if (bucket_eq(map, i, key, keylen, hash, ctx)) {
return i;
}
i = (i + 1) & map->mask;
}
}
// This deletes entry from bucket and adjusts the dibs buckets to right, if
// needed.
static void delbkt(struct map *map, size_t i) {
set_dib(&map->buckets[i], 0);
while (1) {
size_t h = i;
i = (i + 1) & map->mask;
if (get_dib(&map->buckets[i]) <= 1) {
set_dib(&map->buckets[h], 0);
break;
}
map->buckets[h] = map->buckets[i];
set_dib(&map->buckets[h], get_dib(&map->buckets[h])-1);
}
map->count--;
}
static bool needsshrink(struct map *map, struct pgctx *ctx) {
return ctx->allowshrink && map->nbuckets > map->cap &&
map->count <= map->shrinkat;
}
// Try to shrink the hashmap. If needed, this will allocate a new hashmap that
// has fewer buckets and move all existing entries into the smaller map.
// If the resize fails due to an allocation error then the existing hashmap
// will be retained.
static void tryshrink(struct map *map, struct pgctx *ctx) {
if (!needsshrink(map, ctx)) {
return;
}
// Determine the capacity (minimum number of buckets) needed to store all
// entries. The capactiry must be a power of two.
size_t count = map->count;
size_t cap = map->cap;
size_t growat = cap * ctx->loadfactor;
while (count >= growat) {
cap *= 2;
growat = cap * ctx->loadfactor;
}
resize(map, cap, ctx);
}
// Delete an entry at bucket position. Not called directly
static struct entry *delentry_at_bkt(struct map *map, size_t i) {
struct entry *old = get_entry(&map->buckets[i]);
assert(old);
map->entsize -= entry_memsize(old);
delbkt(map, i);
return old;
}
// Delete an entry from the map and return it, or return null if not found.
// This operation will not shrink the map. Call tryshrink to explicitly