-
Notifications
You must be signed in to change notification settings - Fork 276
/
Copy pathCacheAllocator-inl.h
3697 lines (3190 loc) · 130 KB
/
CacheAllocator-inl.h
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) Meta Platforms, Inc. and affiliates.
*
* 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
*
* http://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.
*/
#pragma once
namespace facebook {
namespace cachelib {
template <typename CacheTrait>
CacheAllocator<CacheTrait>::CacheAllocator(Config config)
: CacheAllocator(InitMemType::kNone, config) {
initCommon(false);
}
template <typename CacheTrait>
CacheAllocator<CacheTrait>::CacheAllocator(SharedMemNewT, Config config)
: CacheAllocator(InitMemType::kMemNew, config) {
initCommon(false);
shmManager_->removeShm(detail::kShmInfoName);
}
template <typename CacheTrait>
CacheAllocator<CacheTrait>::CacheAllocator(SharedMemAttachT, Config config)
: CacheAllocator(InitMemType::kMemAttach, config) {
for (auto pid : *metadata_.compactCachePools()) {
isCompactCachePool_[pid] = true;
}
initCommon(true);
// We will create a new info shm segment on shutDown(). If we don't remove
// this info shm segment here and the new info shm segment's size is larger
// than this one, creating new one will fail.
shmManager_->removeShm(detail::kShmInfoName);
}
template <typename CacheTrait>
CacheAllocator<CacheTrait>::CacheAllocator(
typename CacheAllocator<CacheTrait>::InitMemType type, Config config)
: isOnShm_{type != InitMemType::kNone ? true
: config.memMonitoringEnabled()},
config_(config.validate()),
tempShm_(type == InitMemType::kNone && isOnShm_
? std::make_unique<TempShmMapping>(config_.size)
: nullptr),
privMemManager_(type == InitMemType::kNone && !isOnShm_
? std::make_unique<PrivateMemoryManager>()
: nullptr),
shmManager_(type != InitMemType::kNone
? std::make_unique<ShmManager>(config_.cacheDir,
config_.usePosixShm)
: nullptr),
deserializer_(type == InitMemType::kMemAttach ? createDeserializer()
: nullptr),
metadata_{type == InitMemType::kMemAttach
? deserializeCacheAllocatorMetadata(*deserializer_)
: serialization::CacheAllocatorMetadata{}},
allocator_(initAllocator(type)),
compactCacheManager_(type != InitMemType::kMemAttach
? std::make_unique<CCacheManager>(*allocator_)
: restoreCCacheManager()),
compressor_(createPtrCompressor()),
mmContainers_(type == InitMemType::kMemAttach
? deserializeMMContainers(*deserializer_, compressor_)
: MMContainers{}),
accessContainer_(initAccessContainer(
type, detail::kShmHashTableName, config.accessConfig)),
chainedItemAccessContainer_(
initAccessContainer(type,
detail::kShmChainedItemHashTableName,
config.chainedItemAccessConfig)),
chainedItemLocks_(config_.chainedItemsLockPower,
std::make_shared<MurmurHash2>()),
cacheCreationTime_{
type != InitMemType::kMemAttach
? util::getCurrentTimeSec()
: static_cast<uint32_t>(*metadata_.cacheCreationTime())},
cacheInstanceCreationTime_{type != InitMemType::kMemAttach
? cacheCreationTime_
: util::getCurrentTimeSec()},
// Pass in cacheInstnaceCreationTime_ as the current time to keep
// nvmCacheState's current time in sync
nvmCacheState_{cacheInstanceCreationTime_, config_.cacheDir,
config_.isNvmCacheEncryptionEnabled(),
config_.isNvmCacheTruncateAllocSizeEnabled()} {}
template <typename CacheTrait>
CacheAllocator<CacheTrait>::~CacheAllocator() {
XLOG(DBG, "destructing CacheAllocator");
// Stop all workers. In case user didn't call shutDown, we want to
// terminate all background workers and nvmCache before member variables
// go out of scope.
stopWorkers();
nvmCache_.reset();
}
template <typename CacheTrait>
ShmSegmentOpts CacheAllocator<CacheTrait>::createShmCacheOpts() {
ShmSegmentOpts opts;
opts.alignment = sizeof(Slab);
auto memoryTierConfigs = config_.getMemoryTierConfigs();
// TODO: we support single tier so far
XDCHECK_EQ(memoryTierConfigs.size(), 1ul);
opts.memBindNumaNodes = memoryTierConfigs[0].getMemBind();
return opts;
}
template <typename CacheTrait>
PrivateSegmentOpts CacheAllocator<CacheTrait>::createPrivateSegmentOpts() {
PrivateSegmentOpts opts;
opts.alignment = sizeof(Slab);
auto memoryTierConfigs = config_.getMemoryTierConfigs();
// TODO: we support single tier so far
XDCHECK_EQ(memoryTierConfigs.size(), 1ul);
opts.memBindNumaNodes = memoryTierConfigs[0].getMemBind();
return opts;
}
template <typename CacheTrait>
std::unique_ptr<MemoryAllocator>
CacheAllocator<CacheTrait>::createNewMemoryAllocator() {
return std::make_unique<MemoryAllocator>(
getAllocatorConfig(config_),
shmManager_
->createShm(detail::kShmCacheName, config_.size,
config_.slabMemoryBaseAddr, createShmCacheOpts())
.addr,
config_.size);
}
template <typename CacheTrait>
std::unique_ptr<MemoryAllocator>
CacheAllocator<CacheTrait>::restoreMemoryAllocator() {
return std::make_unique<MemoryAllocator>(
deserializer_->deserialize<MemoryAllocator::SerializationType>(),
shmManager_
->attachShm(detail::kShmCacheName, config_.slabMemoryBaseAddr,
createShmCacheOpts())
.addr,
config_.size,
config_.disableFullCoredump);
}
template <typename CacheTrait>
std::unique_ptr<CCacheManager>
CacheAllocator<CacheTrait>::restoreCCacheManager() {
return std::make_unique<CCacheManager>(
deserializer_->deserialize<CCacheManager::SerializationType>(),
*allocator_);
}
template <typename CacheTrait>
void CacheAllocator<CacheTrait>::initCommon(bool dramCacheAttached) {
if (config_.nvmConfig.has_value()) {
if (config_.nvmCacheAP) {
nvmAdmissionPolicy_ = config_.nvmCacheAP;
} else if (config_.rejectFirstAPNumEntries) {
nvmAdmissionPolicy_ = std::make_shared<RejectFirstAP<CacheT>>(
config_.rejectFirstAPNumEntries, config_.rejectFirstAPNumSplits,
config_.rejectFirstSuffixIgnoreLength,
config_.rejectFirstUseDramHitSignal);
}
if (config_.nvmAdmissionMinTTL > 0) {
if (!nvmAdmissionPolicy_) {
nvmAdmissionPolicy_ = std::make_shared<NvmAdmissionPolicy<CacheT>>();
}
nvmAdmissionPolicy_->initMinTTL(config_.nvmAdmissionMinTTL);
}
}
initStats();
initNvmCache(dramCacheAttached);
if (!config_.delayCacheWorkersStart) {
initWorkers();
}
}
template <typename CacheTrait>
void CacheAllocator<CacheTrait>::initNvmCache(bool dramCacheAttached) {
if (!config_.nvmConfig.has_value()) {
return;
}
// for some usecases that create pools, restoring nvmcache when dram cache
// is not persisted is not supported.
const bool shouldDrop = config_.dropNvmCacheOnShmNew && !dramCacheAttached;
// if we are dealing with persistency, cache directory should be enabled
const bool truncate = config_.cacheDir.empty() ||
nvmCacheState_.shouldStartFresh() || shouldDrop;
if (truncate) {
nvmCacheState_.markTruncated();
}
nvmCache_ = std::make_unique<NvmCacheT>(*this, *config_.nvmConfig, truncate,
config_.itemDestructor);
if (!config_.cacheDir.empty()) {
nvmCacheState_.clearPrevState();
}
}
template <typename CacheTrait>
void CacheAllocator<CacheTrait>::initWorkers() {
if (config_.poolResizingEnabled() && !poolResizer_) {
startNewPoolResizer(config_.poolResizeInterval,
config_.poolResizeSlabsPerIter,
config_.poolResizeStrategy);
}
if (config_.poolRebalancingEnabled() && !poolRebalancer_) {
startNewPoolRebalancer(config_.poolRebalanceInterval,
config_.defaultPoolRebalanceStrategy,
config_.poolRebalancerFreeAllocThreshold);
}
if (config_.memMonitoringEnabled() && !memMonitor_) {
if (!isOnShm_) {
throw std::invalid_argument(
"Memory monitoring is not supported for cache on heap. It is "
"supported "
"for cache on a shared memory segment only.");
}
startNewMemMonitor(config_.memMonitorInterval,
config_.memMonitorConfig,
config_.poolAdviseStrategy);
}
if (config_.itemsReaperEnabled() && !reaper_) {
startNewReaper(config_.reaperInterval, config_.reaperConfig);
}
if (config_.poolOptimizerEnabled() && !poolOptimizer_) {
startNewPoolOptimizer(config_.regularPoolOptimizeInterval,
config_.compactCacheOptimizeInterval,
config_.poolOptimizeStrategy,
config_.ccacheOptimizeStepSizePercent);
}
}
template <typename CacheTrait>
std::unique_ptr<MemoryAllocator> CacheAllocator<CacheTrait>::initAllocator(
InitMemType type) {
if (type == InitMemType::kNone) {
if (isOnShm_ == true) {
return std::make_unique<MemoryAllocator>(
getAllocatorConfig(config_), tempShm_->getAddr(), config_.size);
} else {
return std::make_unique<MemoryAllocator>(
getAllocatorConfig(config_),
privMemManager_->createMapping(config_.size,
createPrivateSegmentOpts()),
config_.size);
}
} else if (type == InitMemType::kMemNew) {
return createNewMemoryAllocator();
} else if (type == InitMemType::kMemAttach) {
return restoreMemoryAllocator();
}
// Invalid type
throw std::runtime_error(folly::sformat(
"Cannot initialize memory allocator, unknown InitMemType: {}.",
static_cast<int>(type)));
}
template <typename CacheTrait>
std::unique_ptr<typename CacheAllocator<CacheTrait>::AccessContainer>
CacheAllocator<CacheTrait>::initAccessContainer(InitMemType type,
const std::string name,
AccessConfig config) {
if (type == InitMemType::kNone) {
return std::make_unique<AccessContainer>(
config, compressor_,
[this](Item* it) -> WriteHandle { return acquire(it); });
} else if (type == InitMemType::kMemNew) {
return std::make_unique<AccessContainer>(
config,
shmManager_
->createShm(
name,
AccessContainer::getRequiredSize(config.getNumBuckets()),
nullptr,
ShmSegmentOpts(config.getPageSize()))
.addr,
compressor_,
[this](Item* it) -> WriteHandle { return acquire(it); });
} else if (type == InitMemType::kMemAttach) {
return std::make_unique<AccessContainer>(
deserializer_->deserialize<AccessSerializationType>(),
config,
shmManager_->attachShm(name),
compressor_,
[this](Item* it) -> WriteHandle { return acquire(it); });
}
// Invalid type
throw std::runtime_error(folly::sformat(
"Cannot initialize access container, unknown InitMemType: {}.",
static_cast<int>(type)));
}
template <typename CacheTrait>
std::unique_ptr<Deserializer> CacheAllocator<CacheTrait>::createDeserializer() {
auto infoAddr = shmManager_->attachShm(detail::kShmInfoName);
return std::make_unique<Deserializer>(
reinterpret_cast<uint8_t*>(infoAddr.addr),
reinterpret_cast<uint8_t*>(infoAddr.addr) + infoAddr.size);
}
template <typename CacheTrait>
typename CacheAllocator<CacheTrait>::WriteHandle
CacheAllocator<CacheTrait>::allocate(PoolId poolId,
typename Item::Key key,
uint32_t size,
uint32_t ttlSecs,
uint32_t creationTime) {
if (creationTime == 0) {
creationTime = util::getCurrentTimeSec();
}
return allocateInternal(poolId, key, size, creationTime,
ttlSecs == 0 ? 0 : creationTime + ttlSecs);
}
template <typename CacheTrait>
typename CacheAllocator<CacheTrait>::WriteHandle
CacheAllocator<CacheTrait>::allocateInternal(PoolId pid,
typename Item::Key key,
uint32_t size,
uint32_t creationTime,
uint32_t expiryTime) {
util::LatencyTracker tracker{stats().allocateLatency_};
SCOPE_FAIL { stats_.invalidAllocs.inc(); };
// number of bytes required for this item
const auto requiredSize = Item::getRequiredSize(key, size);
// the allocation class in our memory allocator.
const auto cid = allocator_->getAllocationClassId(pid, requiredSize);
(*stats_.allocAttempts)[pid][cid].inc();
void* memory = allocator_->allocate(pid, requiredSize);
if (memory == nullptr) {
memory = findEviction(pid, cid);
}
WriteHandle handle;
if (memory != nullptr) {
// At this point, we have a valid memory allocation that is ready for use.
// Ensure that when we abort from here under any circumstances, we free up
// the memory. Item's handle could throw because the key size was invalid
// for example.
SCOPE_FAIL {
// free back the memory to the allocator since we failed.
allocator_->free(memory);
};
handle = acquire(new (memory) Item(key, size, creationTime, expiryTime));
if (handle) {
handle.markNascent();
(*stats_.fragmentationSize)[pid][cid].add(
util::getFragmentation(*this, *handle));
}
} else { // failed to allocate memory.
(*stats_.allocFailures)[pid][cid].inc();
// wake up rebalancer
if (!config_.poolRebalancerDisableForcedWakeUp && poolRebalancer_) {
poolRebalancer_->wakeUp();
}
}
if (auto eventTracker = getEventTracker()) {
const auto result =
handle ? AllocatorApiResult::ALLOCATED : AllocatorApiResult::FAILED;
eventTracker->record(AllocatorApiEvent::ALLOCATE, key, result, size,
expiryTime ? expiryTime - creationTime : 0);
}
return handle;
}
template <typename CacheTrait>
typename CacheAllocator<CacheTrait>::WriteHandle
CacheAllocator<CacheTrait>::allocateChainedItem(const ReadHandle& parent,
uint32_t size) {
if (!parent) {
throw std::invalid_argument(
"Cannot call allocate chained item with a empty parent handle!");
}
auto it = allocateChainedItemInternal(parent, size);
if (auto eventTracker = getEventTracker()) {
const auto result =
it ? AllocatorApiResult::ALLOCATED : AllocatorApiResult::FAILED;
eventTracker->record(AllocatorApiEvent::ALLOCATE_CHAINED, parent->getKey(),
result, size, parent->getConfiguredTTL().count());
}
return it;
}
template <typename CacheTrait>
typename CacheAllocator<CacheTrait>::WriteHandle
CacheAllocator<CacheTrait>::allocateChainedItemInternal(
const ReadHandle& parent, uint32_t size) {
util::LatencyTracker tracker{stats().allocateLatency_};
SCOPE_FAIL { stats_.invalidAllocs.inc(); };
// number of bytes required for this item
const auto requiredSize = ChainedItem::getRequiredSize(size);
const auto pid = allocator_->getAllocInfo(parent->getMemory()).poolId;
const auto cid = allocator_->getAllocationClassId(pid, requiredSize);
(*stats_.allocAttempts)[pid][cid].inc();
void* memory = allocator_->allocate(pid, requiredSize);
if (memory == nullptr) {
memory = findEviction(pid, cid);
}
if (memory == nullptr) {
(*stats_.allocFailures)[pid][cid].inc();
return WriteHandle{};
}
SCOPE_FAIL { allocator_->free(memory); };
auto child = acquire(
new (memory) ChainedItem(compressor_.compress(parent.getInternal()), size,
util::getCurrentTimeSec()));
if (child) {
child.markNascent();
(*stats_.fragmentationSize)[pid][cid].add(
util::getFragmentation(*this, *child));
}
return child;
}
template <typename CacheTrait>
void CacheAllocator<CacheTrait>::addChainedItem(WriteHandle& parent,
WriteHandle child) {
if (!parent || !child || !child->isChainedItem()) {
throw std::invalid_argument(
folly::sformat("Invalid parent or child. parent: {}, child: {}",
parent ? parent->toString() : "nullptr",
child ? child->toString() : "nullptr"));
}
auto l = chainedItemLocks_.lockExclusive(parent->getKey());
// Insert into secondary lookup table for chained allocation
auto oldHead = chainedItemAccessContainer_->insertOrReplace(*child);
if (oldHead) {
child->asChainedItem().appendChain(oldHead->asChainedItem(), compressor_);
}
// Count an item that just became a new parent
if (!parent->hasChainedItem()) {
stats_.numChainedParentItems.inc();
}
// Parent needs to be marked before inserting child into MM container
// so the parent-child relationship is established before an eviction
// can be triggered from the child
parent->markHasChainedItem();
// Count a new child
stats_.numChainedChildItems.inc();
insertInMMContainer(*child);
// Increment refcount since this chained item is now owned by the parent
// Parent will decrement the refcount upon release. Since this is an
// internal refcount, we dont include it in active handle tracking.
child->incRef();
XDCHECK_EQ(2u, child->getRefCount());
invalidateNvm(*parent);
if (auto eventTracker = getEventTracker()) {
eventTracker->record(AllocatorApiEvent::ADD_CHAINED, parent->getKey(),
AllocatorApiResult::INSERTED, child->getSize(),
child->getConfiguredTTL().count());
}
}
template <typename CacheTrait>
typename CacheAllocator<CacheTrait>::WriteHandle
CacheAllocator<CacheTrait>::popChainedItem(WriteHandle& parent) {
if (!parent || !parent->hasChainedItem()) {
throw std::invalid_argument(folly::sformat(
"Invalid parent {}", parent ? parent->toString() : nullptr));
}
WriteHandle head;
{ // scope of chained item lock.
auto l = chainedItemLocks_.lockExclusive(parent->getKey());
head = findChainedItem(*parent);
if (head->asChainedItem().getNext(compressor_) != nullptr) {
chainedItemAccessContainer_->insertOrReplace(
*head->asChainedItem().getNext(compressor_));
} else {
chainedItemAccessContainer_->remove(*head);
parent->unmarkHasChainedItem();
stats_.numChainedParentItems.dec();
}
head->asChainedItem().setNext(nullptr, compressor_);
invalidateNvm(*parent);
}
const auto res = removeFromMMContainer(*head);
XDCHECK(res == true);
// decrement the refcount to indicate this item is unlinked from its parent
head->decRef();
stats_.numChainedChildItems.dec();
if (auto eventTracker = getEventTracker()) {
eventTracker->record(AllocatorApiEvent::POP_CHAINED, parent->getKey(),
AllocatorApiResult::REMOVED, head->getSize(),
head->getConfiguredTTL().count());
}
return head;
}
template <typename CacheTrait>
typename CacheAllocator<CacheTrait>::Key
CacheAllocator<CacheTrait>::getParentKey(const Item& chainedItem) {
XDCHECK(chainedItem.isChainedItem());
if (!chainedItem.isChainedItem()) {
throw std::invalid_argument(folly::sformat(
"Item must be chained item! Item: {}", chainedItem.toString()));
}
return reinterpret_cast<const ChainedItem&>(chainedItem)
.getParentItem(compressor_)
.getKey();
}
template <typename CacheTrait>
void CacheAllocator<CacheTrait>::transferChainLocked(WriteHandle& parent,
WriteHandle& newParent) {
// parent must be in a state to not have concurrent readers. Eviction code
// paths rely on holding the last item handle. Since we hold on to an item
// handle here, the chain will not be touched by any eviction code path.
XDCHECK(parent);
XDCHECK(newParent);
XDCHECK_EQ(parent->getKey(), newParent->getKey());
XDCHECK(parent->hasChainedItem());
if (newParent->hasChainedItem()) {
throw std::invalid_argument(folly::sformat(
"New Parent {} has invalid state", newParent->toString()));
}
auto headHandle = findChainedItem(*parent);
XDCHECK(headHandle);
// remove from the access container since we are changing the key
chainedItemAccessContainer_->remove(*headHandle);
// change the key of the chain to have them belong to the new parent.
ChainedItem* curr = &headHandle->asChainedItem();
const auto newParentPtr = compressor_.compress(newParent.get());
while (curr) {
XDCHECK_EQ(curr == headHandle.get() ? 2u : 1u, curr->getRefCount());
XDCHECK(curr->isInMMContainer());
curr->changeKey(newParentPtr);
curr = curr->getNext(compressor_);
}
newParent->markHasChainedItem();
auto oldHead = chainedItemAccessContainer_->insertOrReplace(*headHandle);
if (oldHead) {
throw std::logic_error(
folly::sformat("Did not expect to find an existing chain for {}",
newParent->toString(), oldHead->toString()));
}
parent->unmarkHasChainedItem();
}
template <typename CacheTrait>
void CacheAllocator<CacheTrait>::transferChainAndReplace(
WriteHandle& parent, WriteHandle& newParent) {
if (!parent || !newParent) {
throw std::invalid_argument("invalid parent or new parent");
}
{ // scope for chained item lock
auto l = chainedItemLocks_.lockExclusive(parent->getKey());
transferChainLocked(parent, newParent);
}
if (replaceIfAccessible(*parent, *newParent)) {
newParent.unmarkNascent();
}
invalidateNvm(*parent);
}
template <typename CacheTrait>
bool CacheAllocator<CacheTrait>::replaceIfAccessible(Item& oldItem,
Item& newItem) {
XDCHECK(!newItem.isAccessible());
// Inside the access container's lock, this checks if the old item is
// accessible, and only in that case replaces it. If the old item is not
// accessible anymore, it may have been replaced or removed earlier and there
// is no point in proceeding with a move.
if (!accessContainer_->replaceIfAccessible(oldItem, newItem)) {
return false;
}
// Inside the MM container's lock, this checks if the old item exists to
// make sure that no other thread removed it, and only then replaces it.
if (!replaceInMMContainer(oldItem, newItem)) {
accessContainer_->remove(newItem);
return false;
}
// Replacing into the MM container was successful, but someone could have
// called insertOrReplace() or remove() before or after the
// replaceInMMContainer() operation, which would invalidate newItem.
if (!newItem.isAccessible()) {
removeFromMMContainer(newItem);
return false;
}
return true;
}
template <typename CacheTrait>
typename CacheAllocator<CacheTrait>::WriteHandle
CacheAllocator<CacheTrait>::replaceChainedItem(Item& oldItem,
WriteHandle newItemHandle,
Item& parent) {
if (!newItemHandle) {
throw std::invalid_argument("Empty handle for newItem");
}
auto l = chainedItemLocks_.lockExclusive(parent.getKey());
if (!oldItem.isChainedItem() || !newItemHandle->isChainedItem() ||
&oldItem.asChainedItem().getParentItem(compressor_) !=
&newItemHandle->asChainedItem().getParentItem(compressor_) ||
&oldItem.asChainedItem().getParentItem(compressor_) != &parent ||
newItemHandle->isInMMContainer() || !oldItem.isInMMContainer()) {
throw std::invalid_argument(folly::sformat(
"Invalid args for replaceChainedItem. oldItem={}, newItem={}, "
"parent={}",
oldItem.toString(), newItemHandle->toString(), parent.toString()));
}
auto oldItemHdl =
replaceChainedItemLocked(oldItem, std::move(newItemHandle), parent);
invalidateNvm(parent);
return oldItemHdl;
}
template <typename CacheTrait>
typename CacheAllocator<CacheTrait>::WriteHandle
CacheAllocator<CacheTrait>::replaceChainedItemLocked(Item& oldItem,
WriteHandle newItemHdl,
const Item& parent) {
XDCHECK(newItemHdl != nullptr);
XDCHECK_GE(1u, oldItem.getRefCount());
// grab the handle to the old item so that we can return this. Also, we need
// to drop the refcount the parent holds on oldItem by manually calling
// decRef. To do that safely we need to have a proper outstanding handle.
auto oldItemHdl = acquire(&oldItem);
// Replace the old chained item with new item in the MMContainer before we
// actually replace the old item in the chain
if (!replaceChainedItemInMMContainer(oldItem, *newItemHdl)) {
// This should never happen since we currently hold an valid
// parent handle. None of its chained items can be removed
throw std::runtime_error(folly::sformat(
"chained item cannot be replaced in MM container, oldItem={}, "
"newItem={}, parent={}",
oldItem.toString(), newItemHdl->toString(), parent.toString()));
}
XDCHECK(!oldItem.isInMMContainer());
XDCHECK(newItemHdl->isInMMContainer());
auto head = findChainedItem(parent);
XDCHECK(head != nullptr);
XDCHECK_EQ(reinterpret_cast<uintptr_t>(
&head->asChainedItem().getParentItem(compressor_)),
reinterpret_cast<uintptr_t>(&parent));
// if old item is the head, replace the head in the chain and insert into
// the access container and append its chain.
if (head.get() == &oldItem) {
chainedItemAccessContainer_->insertOrReplace(*newItemHdl);
} else {
// oldItem is in the middle of the chain, find its previous and fix the
// links
auto* prev = &head->asChainedItem();
auto* curr = prev->getNext(compressor_);
while (curr != nullptr && curr != &oldItem) {
prev = curr;
curr = curr->getNext(compressor_);
}
XDCHECK(curr != nullptr);
prev->setNext(&newItemHdl->asChainedItem(), compressor_);
}
newItemHdl->asChainedItem().setNext(
oldItem.asChainedItem().getNext(compressor_), compressor_);
oldItem.asChainedItem().setNext(nullptr, compressor_);
// this should not result in 0 refcount. We are bumping down the internal
// refcount. If it did, we would leak an item.
oldItem.decRef();
XDCHECK_LT(0u, oldItem.getRefCount()) << oldItem.toString();
// increment refcount to indicate parent owns this similar to addChainedItem
// Since this is an internal refcount, we dont include it in active handle
// tracking.
newItemHdl->incRef();
return oldItemHdl;
}
template <typename CacheTrait>
typename CacheAllocator<CacheTrait>::ReleaseRes
CacheAllocator<CacheTrait>::releaseBackToAllocator(Item& it,
RemoveContext ctx,
bool nascent,
const Item* toRecycle) {
if (!it.isDrained()) {
throw std::runtime_error(
folly::sformat("cannot release this item: {}", it.toString()));
}
const auto allocInfo = allocator_->getAllocInfo(it.getMemory());
if (ctx == RemoveContext::kEviction) {
const auto timeNow = util::getCurrentTimeSec();
const auto refreshTime = timeNow - it.getLastAccessTime();
const auto lifeTime = timeNow - it.getCreationTime();
stats_.ramEvictionAgeSecs_.trackValue(refreshTime);
stats_.ramItemLifeTimeSecs_.trackValue(lifeTime);
stats_.perPoolEvictionAgeSecs_[allocInfo.poolId].trackValue(refreshTime);
}
(*stats_.fragmentationSize)[allocInfo.poolId][allocInfo.classId].sub(
util::getFragmentation(*this, it));
// Chained items can only end up in this place if the user has allocated
// memory for a chained item but has decided not to insert the chained item
// to a parent item and instead drop the chained item handle. In this case,
// we free the chained item directly without calling remove callback.
if (it.isChainedItem()) {
if (toRecycle) {
throw std::runtime_error(
folly::sformat("Can not recycle a chained item {}, toRecyle",
it.toString(), toRecycle->toString()));
}
allocator_->free(&it);
return ReleaseRes::kReleased;
}
// nascent items represent items that were allocated but never inserted into
// the cache. We should not be executing removeCB for them since they were
// not initialized from the user perspective and never part of the cache.
if (!nascent && config_.removeCb) {
config_.removeCb(RemoveCbData{ctx, it, viewAsChainedAllocsRange(it)});
}
// only skip destructor for evicted items that are either in the queue to put
// into nvm or already in nvm
bool skipDestructor =
nascent || (ctx == RemoveContext::kEviction &&
// When this item is queued for NvmCache, it will be marked
// as clean and the NvmEvicted bit will also be set to false.
// Refer to NvmCache::put()
it.isNvmClean() && !it.isNvmEvicted());
if (!skipDestructor) {
if (ctx == RemoveContext::kEviction) {
stats().numCacheEvictions.inc();
}
// execute ItemDestructor
if (config_.itemDestructor) {
try {
config_.itemDestructor(DestructorData{
ctx, it, viewAsChainedAllocsRange(it), allocInfo.poolId});
stats().numRamDestructorCalls.inc();
} catch (const std::exception& e) {
stats().numDestructorExceptions.inc();
XLOG_EVERY_N(INFO, 100)
<< "Catch exception from user's item destructor: " << e.what();
}
}
}
// If no `toRecycle` is set, then the result is kReleased
// Because this function cannot fail to release "it"
ReleaseRes res =
toRecycle == nullptr ? ReleaseRes::kReleased : ReleaseRes::kNotRecycled;
// Free chained allocs if there are any
if (it.hasChainedItem()) {
// At this point, the parent is only accessible within this thread
// and thus no one else can add or remove any chained items associated
// with this parent. So we're free to go through the list and free
// chained items one by one.
auto headHandle = findChainedItem(it);
ChainedItem* head = &headHandle.get()->asChainedItem();
headHandle.reset();
if (head == nullptr || &head->getParentItem(compressor_) != &it) {
throw std::runtime_error(folly::sformat(
"Mismatch parent pointer. This should not happen. Key: {}",
it.getKey()));
}
if (!chainedItemAccessContainer_->remove(*head)) {
throw std::runtime_error(folly::sformat(
"Chained item associated with {} cannot be removed from hash table "
"This should not happen here.",
it.getKey()));
}
while (head) {
auto next = head->getNext(compressor_);
const auto childInfo =
allocator_->getAllocInfo(static_cast<const void*>(head));
(*stats_.fragmentationSize)[childInfo.poolId][childInfo.classId].sub(
util::getFragmentation(*this, *head));
removeFromMMContainer(*head);
// If this chained item is marked as moving, we will not free it.
// We must capture the moving state before we do the decRef when
// we know the item must still be valid
const bool wasMoving = head->isMoving();
XDCHECK(!head->isMarkedForEviction());
// Decref and check if we were the last reference. Now if the item
// was marked moving, after decRef, it will be free to be released
// by slab release thread
const auto childRef = head->decRef();
// If the item is already moving and we already decremented the
// refcount, we don't need to free this item. We'll let the slab
// release thread take care of that
if (!wasMoving) {
if (childRef != 0) {
throw std::runtime_error(folly::sformat(
"chained item refcount is not zero. We cannot proceed! "
"Ref: {}, Chained Item: {}",
childRef, head->toString()));
}
// Item is not moving and refcount is 0, we can proceed to
// free it or recylce the memory
if (head == toRecycle) {
XDCHECK(ReleaseRes::kReleased != res);
res = ReleaseRes::kRecycled;
} else {
allocator_->free(head);
}
}
stats_.numChainedChildItems.dec();
head = next;
}
stats_.numChainedParentItems.dec();
}
if (&it == toRecycle) {
XDCHECK(ReleaseRes::kReleased != res);
res = ReleaseRes::kRecycled;
} else {
XDCHECK(it.isDrained());
allocator_->free(&it);
}
return res;
}
template <typename CacheTrait>
bool CacheAllocator<CacheTrait>::incRef(Item& it) {
if (it.incRef()) {
++handleCount_.tlStats();
return true;
}
return false;
}
template <typename CacheTrait>
RefcountWithFlags::Value CacheAllocator<CacheTrait>::decRef(Item& it) {
const auto ret = it.decRef();
// do this after we ensured that we incremented a reference.
--handleCount_.tlStats();
return ret;
}
template <typename CacheTrait>
typename CacheAllocator<CacheTrait>::WriteHandle
CacheAllocator<CacheTrait>::acquire(Item* it) {
if (UNLIKELY(!it)) {
return WriteHandle{};
}
SCOPE_FAIL { stats_.numRefcountOverflow.inc(); };
if (LIKELY(incRef(*it))) {
return WriteHandle{it, *this};
} else {
// item is being evicted
return WriteHandle{};
}
}
template <typename CacheTrait>
void CacheAllocator<CacheTrait>::release(Item* it, bool isNascent) {
// decrement the reference and if it drops to 0, release it back to the
// memory allocator, and invoke the removal callback if there is one.
if (UNLIKELY(!it)) {
return;
}
const auto ref = decRef(*it);
if (UNLIKELY(ref == 0)) {
const auto res =
releaseBackToAllocator(*it, RemoveContext::kNormal, isNascent);
XDCHECK(res == ReleaseRes::kReleased);
}
}
template <typename CacheTrait>
bool CacheAllocator<CacheTrait>::removeFromMMContainer(Item& item) {
// remove it from the mm container.
if (item.isInMMContainer()) {
auto& mmContainer = getMMContainer(item);
return mmContainer.remove(item);
}
return false;
}
template <typename CacheTrait>
bool CacheAllocator<CacheTrait>::replaceInMMContainer(Item& oldItem,
Item& newItem) {
auto& oldContainer = getMMContainer(oldItem);
auto& newContainer = getMMContainer(newItem);
if (&oldContainer == &newContainer) {
return oldContainer.replace(oldItem, newItem);
} else {
return oldContainer.remove(oldItem) && newContainer.add(newItem);
}
}
template <typename CacheTrait>
bool CacheAllocator<CacheTrait>::replaceChainedItemInMMContainer(
Item& oldItem, Item& newItem) {
auto& oldMMContainer = getMMContainer(oldItem);
auto& newMMContainer = getMMContainer(newItem);
if (&oldMMContainer == &newMMContainer) {
return oldMMContainer.replace(oldItem, newItem);
} else {
if (!oldMMContainer.remove(oldItem)) {
return false;
}
// This cannot fail because a new item should not have been inserted
const auto newRes = newMMContainer.add(newItem);
XDCHECK(newRes);
return true;
}
}
template <typename CacheTrait>
void CacheAllocator<CacheTrait>::insertInMMContainer(Item& item) {
XDCHECK(!item.isInMMContainer());
auto& mmContainer = getMMContainer(item);
if (!mmContainer.add(item)) {
throw std::runtime_error(folly::sformat(
"Invalid state. Node {} was already in the container.", &item));