/
cpu_cache_test.cc
1656 lines (1414 loc) · 55.7 KB
/
cpu_cache_test.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 The TCMalloc Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "tcmalloc/cpu_cache.h"
#include <sys/mman.h>
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <iostream>
#include <limits>
#include <new>
#include <optional>
#include <string>
#include <thread> // NOLINT(build/c++11)
#include <tuple>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/optimization.h"
#include "absl/random/bit_gen_ref.h"
#include "absl/random/random.h"
#include "absl/synchronization/mutex.h"
#include "absl/time/time.h"
#include "absl/types/span.h"
#include "tcmalloc/common.h"
#include "tcmalloc/internal/affinity.h"
#include "tcmalloc/internal/logging.h"
#include "tcmalloc/internal/optimization.h"
#include "tcmalloc/internal/percpu_tcmalloc.h"
#include "tcmalloc/internal/sysinfo.h"
#include "tcmalloc/mock_transfer_cache.h"
#include "tcmalloc/parameters.h"
#include "tcmalloc/sizemap.h"
#include "tcmalloc/static_vars.h"
#include "tcmalloc/tcmalloc_policy.h"
#include "tcmalloc/testing/testutil.h"
#include "tcmalloc/testing/thread_manager.h"
#include "tcmalloc/transfer_cache.h"
namespace tcmalloc {
namespace tcmalloc_internal {
class CpuCachePeer {
public:
template <typename CpuCache>
static uint8_t GetSlabShift(const CpuCache& cpu_cache) {
return cpu_cache.freelist_.GetShift();
}
template <typename CpuCache>
static void IncrementCacheMisses(CpuCache& cpu_cache) {
cpu_cache.RecordCacheMissStat(/*cpu=*/0, /*is_alloc=*/true);
cpu_cache.RecordCacheMissStat(/*cpu=*/0, /*is_alloc=*/false);
}
// Validate that we're using >90% of the available slab bytes.
template <typename CpuCache>
static void ValidateSlabBytes(const CpuCache& cpu_cache) {
cpu_cache_internal::SlabShiftBounds bounds =
cpu_cache.GetPerCpuSlabShiftBounds();
for (uint8_t shift = bounds.initial_shift;
shift <= bounds.max_shift &&
shift > cpu_cache_internal::kInitialBasePerCpuShift;
++shift) {
const auto [bytes_required, bytes_available] =
EstimateSlabBytes(cpu_cache.GetMaxCapacityFunctor(shift));
EXPECT_GT(bytes_required * 10, bytes_available * 9)
<< bytes_required << " " << bytes_available << " " << kNumaPartitions
<< " " << kNumBaseClasses << " " << kNumClasses;
EXPECT_LE(bytes_required, bytes_available);
}
}
template <typename CpuCache>
static size_t ResizeInfoSize() {
return sizeof(typename CpuCache::ResizeInfo);
}
};
namespace {
enum class DynamicSlab { kGrow, kShrink, kNoop };
class TestStaticForwarder {
public:
TestStaticForwarder() : sharded_manager_(&owner_, &cpu_layout_) {
numa_topology_.Init();
}
void InitializeShardedManager(int num_shards) {
PageHeapSpinLockHolder l;
cpu_layout_.Init(num_shards);
sharded_manager_.Init();
}
static void* Alloc(size_t size, std::align_val_t alignment) {
return mmap(nullptr, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
}
void* AllocReportedImpending(size_t size, std::align_val_t alignment) {
arena_reported_impending_bytes_ -= static_cast<int64_t>(size);
return mmap(nullptr, size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
}
static void Dealloc(void* ptr, size_t size, std::align_val_t /*alignment*/) {
munmap(ptr, size);
}
void ArenaUpdateAllocatedAndNonresident(int64_t allocated,
int64_t nonresident) {
if (nonresident == 0) {
arena_reported_impending_bytes_ += allocated;
} else {
arena_reported_impending_bytes_ = 0;
}
arena_reported_nonresident_bytes_ += nonresident;
}
void ShrinkToUsageLimit() {
EXPECT_GT(arena_reported_impending_bytes_, 0);
++shrink_to_usage_limit_calls_;
}
bool per_cpu_caches_dynamic_slab_enabled() { return dynamic_slab_enabled_; }
double per_cpu_caches_dynamic_slab_grow_threshold() {
if (dynamic_slab_grow_threshold_ >= 0) return dynamic_slab_grow_threshold_;
return dynamic_slab_ == DynamicSlab::kGrow
? -1.0
: std::numeric_limits<double>::max();
}
double per_cpu_caches_dynamic_slab_shrink_threshold() {
if (dynamic_slab_shrink_threshold_ >= 0)
return dynamic_slab_shrink_threshold_;
return dynamic_slab_ == DynamicSlab::kShrink
? std::numeric_limits<double>::max()
: -1.0;
}
size_t class_to_size(int size_class) const {
if (size_map_.has_value()) {
return size_map_->class_to_size(size_class);
} else {
return transfer_cache_.class_to_size(size_class);
}
}
absl::Span<const size_t> cold_size_classes() const {
if (size_map_.has_value()) {
return size_map_->ColdSizeClasses();
} else {
return {};
}
}
size_t num_objects_to_move(int size_class) const {
if (size_map_.has_value()) {
return size_map_->num_objects_to_move(size_class);
} else {
return transfer_cache_.num_objects_to_move(size_class);
}
}
size_t max_capacity(int size_class) const {
if (size_map_.has_value()) {
return size_map_->max_capacity(size_class);
} else {
return 2048;
}
}
const NumaTopology<kNumaPartitions, kNumBaseClasses>& numa_topology() const {
return numa_topology_;
}
bool UseWiderSlabs() const { return wider_slabs_enabled_; }
bool ConfigureSizeClassMaxCapacity() const {
return configure_size_class_max_capacity_;
}
using ShardedManager =
ShardedTransferCacheManagerBase<FakeShardedTransferCacheManager,
FakeCpuLayout,
MinimalFakeCentralFreeList>;
ShardedManager& sharded_transfer_cache() { return sharded_manager_; }
const ShardedManager& sharded_transfer_cache() const {
return sharded_manager_;
}
TwoSizeClassManager<FakeCentralFreeList,
internal_transfer_cache::TransferCache>&
transfer_cache() {
return transfer_cache_;
}
bool UseGenericShardedCache() const { return owner_.UseGenericCache(); }
void SetGenericShardedCache(bool value) { owner_.SetGenericCache(value); }
bool UseShardedCacheForLargeClassesOnly() const {
return owner_.EnableCacheForLargeClassesOnly();
}
void SetShardedCacheForLargeClassesOnly(bool value) {
owner_.SetCacheForLargeClassesOnly(value);
}
size_t arena_reported_nonresident_bytes_ = 0;
int64_t arena_reported_impending_bytes_ = 0;
size_t shrink_to_usage_limit_calls_ = 0;
bool dynamic_slab_enabled_ = false;
double dynamic_slab_grow_threshold_ = -1;
double dynamic_slab_shrink_threshold_ = -1;
bool wider_slabs_enabled_ = false;
bool configure_size_class_max_capacity_ = false;
DynamicSlab dynamic_slab_ = DynamicSlab::kNoop;
std::optional<SizeMap> size_map_;
private:
NumaTopology<kNumaPartitions, kNumBaseClasses> numa_topology_;
FakeShardedTransferCacheManager owner_;
FakeCpuLayout cpu_layout_;
ShardedManager sharded_manager_;
TwoSizeClassManager<FakeCentralFreeList,
internal_transfer_cache::TransferCache>
transfer_cache_;
};
using CpuCache = cpu_cache_internal::CpuCache<TestStaticForwarder>;
using MissCount = CpuCache::MissCount;
using PerClassMissType = CpuCache::PerClassMissType;
TEST(CpuCacheTest, MinimumShardsForGenericCache) {
if (!subtle::percpu::IsFast()) {
return;
}
CpuCache cache;
cache.Activate();
using ShardedManager = TestStaticForwarder::ShardedManager;
TestStaticForwarder& forwarder = cache.forwarder();
forwarder.SetShardedCacheForLargeClassesOnly(false);
forwarder.SetGenericShardedCache(true);
ShardedManager& sharded_transfer_cache = forwarder.sharded_transfer_cache();
constexpr int kNumShards = ShardedManager::kMinShardsAllowed - 1;
TC_ASSERT_GT(kNumShards, 0);
forwarder.InitializeShardedManager(kNumShards);
constexpr int kCpuId = 0;
ScopedFakeCpuId fake_cpu_id(kCpuId);
EXPECT_FALSE(sharded_transfer_cache.shard_initialized(0));
EXPECT_EQ(sharded_transfer_cache.NumActiveShards(), 0);
EXPECT_EQ(forwarder.transfer_cache().tc_length(kSizeClass), 0);
constexpr size_t kSizeClass = 1;
const size_t num_to_move = cache.forwarder().num_objects_to_move(kSizeClass);
// Allocate an object. As we are using less than kMinShardsAllowed number of
// shards, we should bypass sharded transfer cache entirely.
void* ptr = cache.Allocate(kSizeClass);
for (int size_class = 1; size_class < kNumClasses; ++size_class) {
EXPECT_FALSE(sharded_transfer_cache.should_use(size_class));
EXPECT_EQ(sharded_transfer_cache.GetStats(size_class).capacity, 0);
EXPECT_EQ(sharded_transfer_cache.GetStats(size_class).max_capacity, 0);
}
// No requests are sent to sharded transfer cache. So, it should stay
// uninitialized.
EXPECT_EQ(sharded_transfer_cache.tc_length(kCpuId, kSizeClass), 0);
EXPECT_FALSE(sharded_transfer_cache.shard_initialized(0));
EXPECT_EQ(sharded_transfer_cache.NumActiveShards(), 0);
EXPECT_EQ(forwarder.transfer_cache().tc_length(kSizeClass), 0);
cache.Deallocate(ptr, kSizeClass);
cache.Reclaim(0);
EXPECT_EQ(sharded_transfer_cache.tc_length(kCpuId, kSizeClass), 0);
EXPECT_FALSE(sharded_transfer_cache.shard_initialized(0));
EXPECT_EQ(sharded_transfer_cache.NumActiveShards(), 0);
// We should deallocate directly to the LIFO transfer cache.
EXPECT_EQ(forwarder.transfer_cache().tc_length(kSizeClass),
num_to_move / 2 + 1);
}
TEST(CpuCacheTest, UsesShardedAsBackingCache) {
if (!subtle::percpu::IsFast()) {
return;
}
CpuCache cache;
cache.Activate();
using ShardedManager = TestStaticForwarder::ShardedManager;
TestStaticForwarder& forwarder = cache.forwarder();
forwarder.SetShardedCacheForLargeClassesOnly(false);
forwarder.SetGenericShardedCache(true);
ShardedManager& sharded_transfer_cache = forwarder.sharded_transfer_cache();
constexpr int kNumShards = ShardedManager::kMinShardsAllowed;
TC_ASSERT_GT(kNumShards, 0);
forwarder.InitializeShardedManager(kNumShards);
ScopedFakeCpuId fake_cpu_id(0);
EXPECT_FALSE(sharded_transfer_cache.shard_initialized(0));
EXPECT_EQ(sharded_transfer_cache.NumActiveShards(), 0);
constexpr size_t kSizeClass = 1;
TransferCacheStats sharded_stats =
sharded_transfer_cache.GetStats(kSizeClass);
EXPECT_EQ(sharded_stats.remove_hits, 0);
EXPECT_EQ(sharded_stats.remove_misses, 0);
EXPECT_EQ(sharded_stats.insert_hits, 0);
EXPECT_EQ(sharded_stats.insert_misses, 0);
// Allocate an object and make sure that we allocate from the sharded transfer
// cache and that the sharded cache has been initialized.
void* ptr = cache.Allocate(kSizeClass);
sharded_stats = sharded_transfer_cache.GetStats(kSizeClass);
EXPECT_EQ(sharded_stats.remove_hits, 0);
EXPECT_EQ(sharded_stats.remove_misses, 1);
EXPECT_EQ(sharded_stats.insert_hits, 0);
EXPECT_EQ(sharded_stats.insert_misses, 0);
EXPECT_TRUE(sharded_transfer_cache.shard_initialized(0));
EXPECT_EQ(sharded_transfer_cache.NumActiveShards(), 1);
// Free objects to confirm that they are indeed released back to the sharded
// transfer cache.
cache.Deallocate(ptr, kSizeClass);
cache.Reclaim(0);
sharded_stats = sharded_transfer_cache.GetStats(kSizeClass);
EXPECT_EQ(sharded_stats.insert_hits, 1);
EXPECT_EQ(sharded_stats.insert_misses, 0);
// Ensure that we never use legacy transfer cache by checking that hits and
// misses are zero.
TransferCacheStats tc_stats = forwarder.transfer_cache().GetStats(kSizeClass);
EXPECT_EQ(tc_stats.remove_hits, 0);
EXPECT_EQ(tc_stats.remove_misses, 0);
EXPECT_EQ(tc_stats.insert_hits, 0);
EXPECT_EQ(tc_stats.insert_misses, 0);
forwarder.SetGenericShardedCache(false);
cache.Deactivate();
}
TEST(CpuCacheTest, ResizeInfoNoFalseSharing) {
const size_t resize_info_size = CpuCachePeer::ResizeInfoSize<CpuCache>();
EXPECT_EQ(resize_info_size % ABSL_CACHELINE_SIZE, 0) << resize_info_size;
}
TEST(CpuCacheTest, Metadata) {
if (!subtle::percpu::IsFast()) {
return;
}
const int num_cpus = NumCPUs();
CpuCache cache;
cache.Activate();
cpu_cache_internal::SlabShiftBounds shift_bounds =
cache.GetPerCpuSlabShiftBounds();
PerCPUMetadataState r = cache.MetadataMemoryUsage();
size_t slabs_size = subtle::percpu::GetSlabsAllocSize(
subtle::percpu::ToShiftType(shift_bounds.max_shift), num_cpus);
size_t resize_size = num_cpus * sizeof(bool);
size_t begins_size = kNumClasses * sizeof(std::atomic<uint16_t>);
EXPECT_EQ(r.virtual_size, slabs_size + resize_size + begins_size);
EXPECT_EQ(r.resident_size, 0);
auto count_cores = [&]() {
int populated_cores = 0;
for (int i = 0; i < num_cpus; i++) {
if (cache.HasPopulated(i)) {
populated_cores++;
}
}
return populated_cores;
};
EXPECT_EQ(0, count_cores());
int allowed_cpu_id;
const size_t kSizeClass = 2;
const size_t num_to_move = cache.forwarder().num_objects_to_move(kSizeClass);
const size_t virtual_cpu_id_offset = subtle::percpu::UsingFlatVirtualCpus()
? offsetof(kernel_rseq, vcpu_id)
: offsetof(kernel_rseq, cpu_id);
void* ptr;
{
// Restrict this thread to a single core while allocating and processing the
// slow path.
//
// TODO(b/151313823): Without this restriction, we may access--for reading
// only--other slabs if we end up being migrated. These may cause huge
// pages to be faulted for those cores, leading to test flakiness.
tcmalloc_internal::ScopedAffinityMask mask(
tcmalloc_internal::AllowedCpus()[0]);
allowed_cpu_id =
subtle::percpu::GetCurrentVirtualCpuUnsafe(virtual_cpu_id_offset);
ptr = cache.Allocate(kSizeClass);
if (mask.Tampered() ||
allowed_cpu_id !=
subtle::percpu::GetCurrentVirtualCpuUnsafe(virtual_cpu_id_offset)) {
return;
}
}
EXPECT_NE(ptr, nullptr);
EXPECT_EQ(1, count_cores());
r = cache.MetadataMemoryUsage();
EXPECT_EQ(
r.virtual_size,
resize_size + begins_size +
subtle::percpu::GetSlabsAllocSize(
subtle::percpu::ToShiftType(shift_bounds.max_shift), num_cpus));
// We expect to fault in a single core, but we may end up faulting an
// entire hugepage worth of memory when we touch that core and another when
// touching the header.
const size_t core_slab_size = r.virtual_size / num_cpus;
const size_t upper_bound =
((core_slab_size + kHugePageSize - 1) & ~(kHugePageSize - 1)) +
kHugePageSize;
// A single core may be less than the full slab (core_slab_size), since we
// do not touch every page within the slab.
EXPECT_GT(r.resident_size, 0);
EXPECT_LE(r.resident_size, upper_bound)
<< count_cores() << " " << core_slab_size << " " << kHugePageSize;
// This test is much more sensitive to implementation details of the per-CPU
// cache. It may need to be updated from time to time. These numbers were
// calculated by MADV_NOHUGEPAGE'ing the memory used for the slab and
// measuring the resident size.
switch (shift_bounds.max_shift) {
case 12:
EXPECT_GE(r.resident_size, 4096);
break;
case 18:
EXPECT_GE(r.resident_size, 8192);
break;
default:
ASSUME(false);
break;
}
// Read stats from the CPU caches. This should not impact resident_size.
const size_t max_cpu_cache_size = Parameters::max_per_cpu_cache_size();
size_t total_used_bytes = 0;
for (int cpu = 0; cpu < num_cpus; ++cpu) {
size_t used_bytes = cache.UsedBytes(cpu);
total_used_bytes += used_bytes;
if (cpu == allowed_cpu_id) {
EXPECT_GT(used_bytes, 0);
EXPECT_TRUE(cache.HasPopulated(cpu));
} else {
EXPECT_EQ(used_bytes, 0);
EXPECT_FALSE(cache.HasPopulated(cpu));
}
EXPECT_LE(cache.Unallocated(cpu), max_cpu_cache_size);
EXPECT_EQ(cache.Capacity(cpu), max_cpu_cache_size);
EXPECT_EQ(cache.Allocated(cpu) + cache.Unallocated(cpu),
cache.Capacity(cpu));
}
for (int size_class = 1; size_class < kNumClasses; ++size_class) {
// This is sensitive to the current growth policies of CpuCache. It may
// require updating from time-to-time.
EXPECT_EQ(cache.TotalObjectsOfClass(size_class),
(size_class == kSizeClass ? num_to_move - 1 : 0))
<< size_class;
}
EXPECT_EQ(cache.TotalUsedBytes(), total_used_bytes);
PerCPUMetadataState post_stats = cache.MetadataMemoryUsage();
// Confirm stats are within expected bounds.
EXPECT_GT(post_stats.resident_size, 0);
EXPECT_LE(post_stats.resident_size, upper_bound) << count_cores();
// Confirm stats are unchanged.
EXPECT_EQ(r.resident_size, post_stats.resident_size);
// Tear down.
cache.Deallocate(ptr, kSizeClass);
cache.Deactivate();
}
TEST(CpuCacheTest, CacheMissStats) {
if (!subtle::percpu::IsFast()) {
return;
}
const int num_cpus = NumCPUs();
CpuCache cache;
cache.Activate();
// The number of underflows and overflows must be zero for all the caches.
for (int cpu = 0; cpu < num_cpus; ++cpu) {
CpuCache::CpuCacheMissStats total_misses =
cache.GetTotalCacheMissStats(cpu);
CpuCache::CpuCacheMissStats shuffle_misses =
cache.GetIntervalCacheMissStats(cpu, MissCount::kShuffle);
EXPECT_EQ(total_misses.underflows, 0);
EXPECT_EQ(total_misses.overflows, 0);
EXPECT_EQ(shuffle_misses.underflows, 0);
EXPECT_EQ(shuffle_misses.overflows, 0);
}
int allowed_cpu_id;
const size_t kSizeClass = 2;
const size_t virtual_cpu_id_offset = subtle::percpu::UsingFlatVirtualCpus()
? offsetof(kernel_rseq, vcpu_id)
: offsetof(kernel_rseq, cpu_id);
void* ptr;
{
// Restrict this thread to a single core while allocating and processing the
// slow path.
//
// TODO(b/151313823): Without this restriction, we may access--for reading
// only--other slabs if we end up being migrated. These may cause huge
// pages to be faulted for those cores, leading to test flakiness.
tcmalloc_internal::ScopedAffinityMask mask(
tcmalloc_internal::AllowedCpus()[0]);
allowed_cpu_id =
subtle::percpu::GetCurrentVirtualCpuUnsafe(virtual_cpu_id_offset);
ptr = cache.Allocate(kSizeClass);
if (mask.Tampered() ||
allowed_cpu_id !=
subtle::percpu::GetCurrentVirtualCpuUnsafe(virtual_cpu_id_offset)) {
return;
}
}
for (int cpu = 0; cpu < num_cpus; ++cpu) {
CpuCache::CpuCacheMissStats total_misses =
cache.GetTotalCacheMissStats(cpu);
CpuCache::CpuCacheMissStats shuffle_misses =
cache.GetIntervalCacheMissStats(cpu, MissCount::kShuffle);
if (cpu == allowed_cpu_id) {
EXPECT_EQ(total_misses.underflows, 1);
EXPECT_EQ(shuffle_misses.underflows, 1);
} else {
EXPECT_EQ(total_misses.underflows, 0);
EXPECT_EQ(shuffle_misses.underflows, 0);
}
EXPECT_EQ(total_misses.overflows, 0);
EXPECT_EQ(shuffle_misses.overflows, 0);
}
// Tear down.
cache.Deallocate(ptr, kSizeClass);
cache.Deactivate();
}
static void ResizeSizeClasses(CpuCache& cache, const std::atomic<bool>& stop) {
if (!subtle::percpu::IsFast()) {
return;
}
// Wake up every 10ms to resize size classes. Let miss stats acummulate over
// those 10ms.
while (!stop.load(std::memory_order_acquire)) {
cache.ResizeSizeClasses();
absl::SleepFor(absl::Milliseconds(10));
}
}
static void ShuffleThread(CpuCache& cache, const std::atomic<bool>& stop) {
if (!subtle::percpu::IsFast()) {
return;
}
// Wake up every 10ms to shuffle the caches so that we can allow misses to
// accumulate during that interval
while (!stop.load(std::memory_order_acquire)) {
cache.ShuffleCpuCaches();
absl::SleepFor(absl::Milliseconds(10));
}
}
static void StressThread(CpuCache& cache, size_t thread_id,
const std::atomic<bool>& stop) {
if (!subtle::percpu::IsFast()) {
return;
}
std::vector<std::pair<size_t, void*>> blocks;
absl::InsecureBitGen rnd;
while (!stop.load(std::memory_order_acquire)) {
const int what = absl::Uniform<int32_t>(rnd, 0, 2);
if (what) {
// Allocate an object for a class
size_t size_class = absl::Uniform<int32_t>(rnd, 1, 3);
void* ptr = cache.Allocate(size_class);
blocks.emplace_back(std::make_pair(size_class, ptr));
} else {
// Deallocate an object for a class
if (!blocks.empty()) {
cache.Deallocate(blocks.back().second, blocks.back().first);
blocks.pop_back();
}
}
}
// Cleaup. Deallocate rest of the allocated memory.
for (int i = 0; i < blocks.size(); i++) {
cache.Deallocate(blocks[i].second, blocks[i].first);
}
}
TEST(CpuCacheTest, StressSizeClassResize) {
if (!subtle::percpu::IsFast()) {
return;
}
CpuCache cache;
cache.Activate();
std::vector<std::thread> threads;
std::thread resize_thread;
const int n_threads = NumCPUs();
std::atomic<bool> stop(false);
for (size_t t = 0; t < n_threads; ++t) {
threads.push_back(
std::thread(StressThread, std::ref(cache), t, std::ref(stop)));
}
resize_thread =
std::thread(ResizeSizeClasses, std::ref(cache), std::ref(stop));
absl::SleepFor(absl::Seconds(5));
stop = true;
for (auto& t : threads) {
t.join();
}
resize_thread.join();
// Check that the total capacity is preserved after the stress test.
size_t capacity = 0;
const int num_cpus = NumCPUs();
const size_t kTotalCapacity = num_cpus * Parameters::max_per_cpu_cache_size();
for (int cpu = 0; cpu < num_cpus; ++cpu) {
EXPECT_EQ(cache.Allocated(cpu) + cache.Unallocated(cpu),
cache.Capacity(cpu));
capacity += cache.Capacity(cpu);
}
EXPECT_EQ(capacity, kTotalCapacity);
cache.Deactivate();
}
TEST(CpuCacheTest, StealCpuCache) {
if (!subtle::percpu::IsFast()) {
return;
}
CpuCache cache;
cache.Activate();
std::vector<std::thread> threads;
std::thread shuffle_thread;
const int n_threads = NumCPUs();
std::atomic<bool> stop(false);
for (size_t t = 0; t < n_threads; ++t) {
threads.push_back(
std::thread(StressThread, std::ref(cache), t, std::ref(stop)));
}
shuffle_thread = std::thread(ShuffleThread, std::ref(cache), std::ref(stop));
absl::SleepFor(absl::Seconds(5));
stop = true;
for (auto& t : threads) {
t.join();
}
shuffle_thread.join();
// Check that the total capacity is preserved after the shuffle.
size_t capacity = 0;
const int num_cpus = NumCPUs();
const size_t kTotalCapacity = num_cpus * Parameters::max_per_cpu_cache_size();
for (int cpu = 0; cpu < num_cpus; ++cpu) {
EXPECT_EQ(cache.Allocated(cpu) + cache.Unallocated(cpu),
cache.Capacity(cpu));
capacity += cache.Capacity(cpu);
}
EXPECT_EQ(capacity, kTotalCapacity);
cache.Deactivate();
}
// Test that when dynamic slab is enabled, nothing goes horribly wrong and that
// arena non-resident bytes increases as expected.
TEST(CpuCacheTest, DynamicSlab) {
if (!subtle::percpu::IsFast()) {
return;
}
CpuCache cache;
TestStaticForwarder& forwarder = cache.forwarder();
size_t prev_reported_nonresident_bytes =
forwarder.arena_reported_nonresident_bytes_;
EXPECT_EQ(forwarder.arena_reported_impending_bytes_, 0);
size_t prev_shrink_to_usage_limit_calls =
forwarder.shrink_to_usage_limit_calls_;
forwarder.dynamic_slab_enabled_ = true;
forwarder.dynamic_slab_ = DynamicSlab::kNoop;
cache.Activate();
std::vector<std::thread> threads;
const int n_threads = NumCPUs();
std::atomic<bool> stop(false);
for (size_t t = 0; t < n_threads; ++t) {
threads.push_back(
std::thread(StressThread, std::ref(cache), t, std::ref(stop)));
}
cpu_cache_internal::SlabShiftBounds shift_bounds =
cache.GetPerCpuSlabShiftBounds();
int shift = shift_bounds.initial_shift;
const auto repeat_dynamic_slab_ops = [&](DynamicSlab op, int shift_update,
int end_shift) {
const DynamicSlab ops[2] = {DynamicSlab::kNoop, op};
int iters = end_shift > shift ? end_shift - shift : shift - end_shift;
iters += 2; // Test that we don't resize past end_shift.
for (int i = 0; i < iters; ++i) {
for (DynamicSlab dynamic_slab : ops) {
EXPECT_EQ(shift, CpuCachePeer::GetSlabShift(cache));
absl::SleepFor(absl::Milliseconds(100));
forwarder.dynamic_slab_ = dynamic_slab;
// If there were no misses in the current resize interval, then we may
// not resize so we ensure non-zero misses.
CpuCachePeer::IncrementCacheMisses(cache);
cache.ResizeSlabIfNeeded();
if (dynamic_slab != DynamicSlab::kNoop && shift != end_shift) {
EXPECT_LT(prev_reported_nonresident_bytes,
forwarder.arena_reported_nonresident_bytes_);
EXPECT_EQ(forwarder.shrink_to_usage_limit_calls_,
1 + prev_shrink_to_usage_limit_calls);
shift += shift_update;
} else {
EXPECT_EQ(prev_reported_nonresident_bytes,
forwarder.arena_reported_nonresident_bytes_);
}
prev_reported_nonresident_bytes =
forwarder.arena_reported_nonresident_bytes_;
EXPECT_EQ(forwarder.arena_reported_impending_bytes_, 0);
prev_shrink_to_usage_limit_calls =
forwarder.shrink_to_usage_limit_calls_;
}
}
};
// First grow the slab to max size, then shrink it to min size.
repeat_dynamic_slab_ops(DynamicSlab::kGrow, /*shift_update=*/1,
shift_bounds.max_shift);
repeat_dynamic_slab_ops(DynamicSlab::kShrink, /*shift_update=*/-1,
shift_bounds.initial_shift);
stop = true;
for (auto& t : threads) {
t.join();
}
cache.Deactivate();
}
void AllocateThenDeallocate(CpuCache& cache, int cpu, size_t size_class,
int ops) {
std::vector<void*> objects;
ScopedFakeCpuId fake_cpu_id(cpu);
for (int i = 0; i < ops; ++i) {
void* ptr = cache.Allocate(size_class);
objects.push_back(ptr);
}
for (auto* ptr : objects) {
cache.Deallocate(ptr, size_class);
}
objects.clear();
}
// In this test, we check if we can resize size classes based on the number of
// misses they encounter. First, we exhaust cache capacity by filling up
// larger size class as much as possible. Then, we try to allocate objects for
// the smaller size class. This should result in misses as we do not resize its
// capacity in the foreground when the feature is enabled. We confirm that it
// indeed encounters a capacity miss. When then resize size classes and allocate
// small size class objects again. We should be able to utilize an increased
// capacity for the size class to allocate and deallocate these objects. We also
// confirm that we do not lose the overall cpu cache capacity when we resize
// size class capacities.
TEST(CpuCacheTest, ResizeSizeClassesTest) {
if (!subtle::percpu::IsFast()) {
return;
}
CpuCache cache;
// Reduce cache capacity so that it will see need in stealing and rebalancing.
const size_t max_cpu_cache_size = 128 << 10;
cache.SetCacheLimit(max_cpu_cache_size);
cache.Activate();
// Temporarily fake being on the given CPU.
constexpr int kCpuId = 0;
constexpr int kCpuId1 = 1;
constexpr int kSmallClass = 1;
constexpr int kLargeClass = 2;
const int kMaxCapacity = cache.forwarder().max_capacity(kLargeClass);
const size_t large_class_size = cache.forwarder().class_to_size(kLargeClass);
ASSERT_GT(large_class_size * kMaxCapacity, max_cpu_cache_size);
const size_t batch_size_small =
cache.forwarder().num_objects_to_move(kSmallClass);
const size_t batch_size_large =
cache.forwarder().num_objects_to_move(kLargeClass);
size_t ops = 0;
while (true) {
// We allocate and deallocate additional batch_size number of objects each
// time so that cpu cache suffers successive underflow and overflow, and it
// can grow.
ops += batch_size_large;
if (ops > kMaxCapacity || cache.Allocated(kCpuId) == max_cpu_cache_size)
break;
AllocateThenDeallocate(cache, kCpuId, kLargeClass, ops);
}
EXPECT_EQ(cache.Unallocated(kCpuId), 0);
EXPECT_EQ(cache.Allocated(kCpuId), max_cpu_cache_size);
EXPECT_EQ(cache.TotalObjectsOfClass(kSmallClass), 0);
size_t interval_misses = cache.GetIntervalSizeClassMisses(
kCpuId, kSmallClass, PerClassMissType::kResize);
EXPECT_EQ(interval_misses, 0);
AllocateThenDeallocate(cache, kCpuId, kSmallClass, batch_size_small);
interval_misses = cache.GetIntervalSizeClassMisses(kCpuId, kSmallClass,
PerClassMissType::kResize);
EXPECT_EQ(interval_misses, 2 * batch_size_small);
EXPECT_EQ(cache.Unallocated(kCpuId), 0);
EXPECT_EQ(cache.Allocated(kCpuId), max_cpu_cache_size);
EXPECT_EQ(cache.TotalObjectsOfClass(kSmallClass), 0);
const int num_resizes = NumCPUs() / CpuCache::kNumCpuCachesToResize;
{
ScopedFakeCpuId fake_cpu_id_1(kCpuId1);
for (int i = 0; i < num_resizes; ++i) {
cache.ResizeSizeClasses();
}
}
// Since we just resized size classes, we started a new interval. So, miss
// this interval should be zero.
interval_misses = cache.GetIntervalSizeClassMisses(kCpuId, kSmallClass,
PerClassMissType::kResize);
EXPECT_EQ(interval_misses, 0);
AllocateThenDeallocate(cache, kCpuId, kSmallClass, batch_size_small);
interval_misses = cache.GetIntervalSizeClassMisses(kCpuId, kSmallClass,
PerClassMissType::kResize);
EXPECT_EQ(interval_misses, 0);
EXPECT_EQ(cache.Unallocated(kCpuId), 0);
EXPECT_EQ(cache.Allocated(kCpuId), max_cpu_cache_size);
EXPECT_EQ(cache.TotalObjectsOfClass(kSmallClass), batch_size_small);
// Reclaim caches.
cache.Deactivate();
}
// Runs a single allocate and deallocate operation to warm up the cache. Once a
// few objects are allocated in the cold cache, we can shuffle cpu caches to
// steal that capacity from the cold cache to the hot cache.
static void ColdCacheOperations(CpuCache& cache, int cpu_id,
size_t size_class) {
// Temporarily fake being on the given CPU.
ScopedFakeCpuId fake_cpu_id(cpu_id);
void* ptr = cache.Allocate(size_class);
cache.Deallocate(ptr, size_class);
}
// Runs multiple allocate and deallocate operation on the cpu cache to collect
// misses. Once we collect enough misses on this cache, we can shuffle cpu
// caches to steal capacity from colder caches to the hot cache.
static void HotCacheOperations(CpuCache& cache, int cpu_id) {
constexpr size_t kPtrs = 4096;
std::vector<void*> ptrs;
ptrs.resize(kPtrs);
// Temporarily fake being on the given CPU.
ScopedFakeCpuId fake_cpu_id(cpu_id);
// Allocate and deallocate objects to make sure we have enough misses on the
// cache. This will make sure we have sufficient disparity in misses between
// the hotter and colder cache, and that we may be able to steal bytes from
// the colder cache.
for (size_t size_class = 1; size_class <= 2; ++size_class) {
for (auto& ptr : ptrs) {
ptr = cache.Allocate(size_class);
}
for (void* ptr : ptrs) {
cache.Deallocate(ptr, size_class);
}
}
// We reclaim the cache to reset it so that we record underflows/overflows the
// next time we allocate and deallocate objects. Without reclaim, the cache
// would stay warmed up and it would take more time to drain the colder cache.
cache.Reclaim(cpu_id);
}
class DynamicWideSlabTest
: public testing::TestWithParam<
std::tuple<bool /* use_wider_slab */,
bool /* configure_size_class_max_capacity */>> {
public:
bool use_wider_slab() { return std::get<0>(GetParam()); }
bool configure_size_class_max_capacity() { return std::get<1>(GetParam()); }
};
INSTANTIATE_TEST_SUITE_P(TestDynamicWideSlab, DynamicWideSlabTest,
testing::Combine(testing::Bool(), testing::Bool()));
// Test that we are complying with the threshold when we grow the slab.
// When wider slab is enabled, we check if overflow/underflow ratio is above the
// threshold for individual cpu caches.
TEST_P(DynamicWideSlabTest, DynamicSlabThreshold) {
if (!subtle::percpu::IsFast()) {
return;
}
constexpr double kDynamicSlabGrowThreshold = 0.9;
CpuCache cache;
TestStaticForwarder& forwarder = cache.forwarder();
forwarder.dynamic_slab_enabled_ = true;
forwarder.dynamic_slab_grow_threshold_ = kDynamicSlabGrowThreshold;
forwarder.wider_slabs_enabled_ = use_wider_slab();
SizeMap size_map;
size_map.Init(kSizeClasses.classes);
forwarder.size_map_ = size_map;
cache.Activate();
constexpr int kCpuId0 = 0;
constexpr int kCpuId1 = 1;
// Accumulate overflows and underflows for kCpuId0.
HotCacheOperations(cache, kCpuId0);
CpuCache::CpuCacheMissStats interval_misses =
cache.GetIntervalCacheMissStats(kCpuId0, MissCount::kSlabResize);
// Make sure that overflows/underflows ratio is greater than the threshold
// for kCpuId0 cache.
ASSERT_GT(interval_misses.overflows,
interval_misses.underflows * kDynamicSlabGrowThreshold);
// Perform allocations on kCpuId1 so that we accumulate only underflows.
// Reclaim after each allocation such that we have no objects in the cache
// for the next allocation.
for (int i = 0; i < 1024; ++i) {
ColdCacheOperations(cache, kCpuId1, /*size_class=*/1);
cache.Reclaim(kCpuId1);
}
// Total overflows/underflows ratio must be less than grow threshold now.
CpuCache::CpuCacheMissStats total_misses =
cache.GetIntervalCacheMissStats(kCpuId0, MissCount::kSlabResize);
total_misses +=
cache.GetIntervalCacheMissStats(kCpuId1, MissCount::kSlabResize);
ASSERT_LT(total_misses.overflows,