forked from scylladb/seastar
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmemory.cc
2339 lines (2047 loc) · 70.9 KB
/
memory.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
/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
/// \cond internal
//
// Seastar memory allocator
//
// This is a share-nothing allocator (memory allocated on one cpu must
// be freed on the same cpu).
//
// Inspired by gperftools' tcmalloc.
//
// Memory map:
//
// 0x0000'sccc'vvvv'vvvv
//
// 0000 - required by architecture (only 48 bits of address space)
// s - chosen to satisfy system allocator (1-7)
// ccc - cpu number (0-12 bits allocated vary according to system)
// v - virtual address within cpu (32-44 bits, according to how much ccc
// leaves us
//
// Each page has a page structure that describes it. Within a cpu's
// memory pool, the page array starts at offset 0, describing all pages
// within that pool. Page 0 does not describe a valid page.
//
// Each pool can contain at most 2^32 pages (or 44 address bits), so we can
// use a 32-bit integer to identify a page.
//
// Runs of pages are organized into spans. Free spans are organized into lists,
// by size. When spans are broken up or coalesced, they may move into new lists.
// Spans have a size that is a power-of-two and are naturally aligned (aka buddy
// allocator)
#include <seastar/core/cacheline.hh>
#include <seastar/core/memory.hh>
#include <seastar/core/print.hh>
#include <seastar/util/alloc_failure_injector.hh>
#include <seastar/util/memory_diagnostics.hh>
#include <seastar/util/std-compat.hh>
#include <seastar/util/log.hh>
#include <seastar/core/aligned_buffer.hh>
#include <unordered_set>
#include <iostream>
#include <thread>
#include <dlfcn.h>
namespace seastar {
extern seastar::logger seastar_logger;
void* internal::allocate_aligned_buffer_impl(size_t size, size_t align) {
void *ret;
auto r = posix_memalign(&ret, align, size);
if (r == ENOMEM) {
throw std::bad_alloc();
} else if (r == EINVAL) {
throw std::runtime_error(format("Invalid alignment of {:d}; allocating {:d} bytes", align, size));
} else {
assert(r == 0);
return ret;
}
}
namespace memory {
// We always create the logger object for memory disagnostics, even in
// in SEASTAR_DEFAULT_ALLOCATOR builds, though it only logs when the
// seastar allocator is enabled.
seastar::logger seastar_memory_logger("seastar_memory");
static thread_local int abort_on_alloc_failure_suppressed = 0;
disable_abort_on_alloc_failure_temporarily::disable_abort_on_alloc_failure_temporarily() {
++abort_on_alloc_failure_suppressed;
}
disable_abort_on_alloc_failure_temporarily::~disable_abort_on_alloc_failure_temporarily() noexcept {
--abort_on_alloc_failure_suppressed;
}
static std::pmr::polymorphic_allocator<char> static_malloc_allocator{std::pmr::get_default_resource()};;
std::pmr::polymorphic_allocator<char>* malloc_allocator{&static_malloc_allocator};
namespace internal {
#ifdef __cpp_constinit
#define SEASTAR_CONSTINIT constinit
#else
#define SEASTAR_CONSTINIT
#endif
#ifdef SEASTAR_ENABLE_ALLOC_FAILURE_INJECTION
#ifdef __cpp_constinit
thread_local constinit volatile int critical_alloc_section = 0;
#else
__thread volatile int critical_alloc_section = 0;
#endif
#endif // SEASTAR_ENABLE_ALLOC_FAILURE_INJECTION
} // namespace internal
}
}
#ifndef SEASTAR_DEFAULT_ALLOCATOR
#include <seastar/core/bitops.hh>
#include <seastar/core/align.hh>
#include <seastar/core/posix.hh>
#include <seastar/core/shared_ptr.hh>
#include <new>
#include <cstdint>
#include <algorithm>
#include <limits>
#include <cassert>
#include <atomic>
#include <mutex>
#include <seastar/util/std-compat.hh>
#include <functional>
#include <cstring>
#include <boost/intrusive/list.hpp>
#include <sys/mman.h>
#include <seastar/util/backtrace.hh>
#ifdef SEASTAR_HAVE_NUMA
#include <numaif.h>
#endif
namespace seastar {
struct allocation_site {
mutable size_t count = 0; // number of live objects allocated at backtrace.
mutable size_t size = 0; // amount of bytes in live objects allocated at backtrace.
mutable const allocation_site* next = nullptr;
saved_backtrace backtrace;
bool operator==(const allocation_site& o) const {
return backtrace == o.backtrace;
}
bool operator!=(const allocation_site& o) const {
return !(*this == o);
}
};
}
namespace std {
template<>
struct hash<seastar::allocation_site> {
size_t operator()(const seastar::allocation_site& bi) const {
return std::hash<seastar::saved_backtrace>()(bi.backtrace);
}
};
}
#if FMT_VERSION >= 90000
namespace seastar::memory {
struct human_readable_value;
}
template <> struct fmt::formatter<struct seastar::memory::human_readable_value> : fmt::ostream_formatter {};
#endif
namespace seastar {
using allocation_site_ptr = const allocation_site*;
namespace memory {
[[gnu::unused]]
static allocation_site_ptr get_allocation_site();
static void on_allocation_failure(size_t size);
static constexpr unsigned cpu_id_shift = 36; // FIXME: make dynamic
static constexpr unsigned max_cpus = 256;
static constexpr uintptr_t cpu_id_and_mem_base_mask = ~((uintptr_t(1) << cpu_id_shift) - 1);
using pageidx = uint32_t;
struct page;
class page_list;
static std::atomic<bool> live_cpus[max_cpus];
using std::optional;
// is_reactor_thread gets set to true when memory::configure() gets called
// it is used to identify seastar threads and hence use system memory allocator
// for those threads
static thread_local bool is_reactor_thread = false;
namespace alloc_stats {
enum class types { allocs, frees, cross_cpu_frees, reclaims, large_allocs, failed_allocs,
foreign_mallocs, foreign_frees, foreign_cross_frees, enum_size };
using stats_array = std::array<uint64_t, static_cast<std::size_t>(types::enum_size)>;
using stats_atomic_array = std::array<std::atomic_uint64_t, static_cast<std::size_t>(types::enum_size)>;
static thread_local SEASTAR_CONSTINIT stats_array stats{};
std::array<stats_atomic_array, max_cpus> alien_stats{};
static void increment_local(types stat_type, uint64_t size = 1) {
stats[static_cast<std::size_t>(stat_type)] += size;
}
static void increment(types stat_type, uint64_t size=1)
{
// fast path, reactor threads takes thread local statistics
if (is_reactor_thread) {
increment_local(stat_type, size);
} else {
auto hash = std::hash<std::thread::id>()(std::this_thread::get_id());
auto i = static_cast<std::size_t>(stat_type);
alien_stats[hash % alien_stats.size()][i].fetch_add(size, std::memory_order_relaxed);
}
}
static uint64_t get(types stat_type)
{
auto i = static_cast<std::size_t>(stat_type);
// fast path, reactor threads takes thread local statistics
if (is_reactor_thread) {
return stats[i];
} else {
auto hash = std::hash<std::thread::id>()(std::this_thread::get_id());
return alien_stats[hash % alien_stats.size()][i].load();
}
}
}
// original memory allocator support
// note: allocations before calling the constructor would use seastar allocator
using malloc_func_type = void * (*)(size_t);
using free_func_type = void * (*)(void *);
using realloc_func_type = void * (*)(void *, size_t);
using aligned_alloc_type = void * (*)(size_t alignment, size_t size);
using malloc_trim_type = int (*)(size_t);
using malloc_usable_size_type = size_t (*)(void *);
malloc_func_type original_malloc_func = reinterpret_cast<malloc_func_type>(dlsym(RTLD_NEXT, "malloc"));
free_func_type original_free_func = reinterpret_cast<free_func_type>(dlsym(RTLD_NEXT, "free"));
realloc_func_type original_realloc_func = reinterpret_cast<realloc_func_type>(dlsym(RTLD_NEXT, "realloc"));
aligned_alloc_type original_aligned_alloc_func = reinterpret_cast<aligned_alloc_type>(dlsym(RTLD_NEXT, "aligned_alloc"));
malloc_trim_type original_malloc_trim_func = reinterpret_cast<malloc_trim_type>(dlsym(RTLD_NEXT, "malloc_trim"));
malloc_usable_size_type original_malloc_usable_size_func = reinterpret_cast<malloc_usable_size_type>(dlsym(RTLD_NEXT, "malloc_usable_size"));
using allocate_system_memory_fn
= std::function<mmap_area (void* where, size_t how_much)>;
namespace bi = boost::intrusive;
static thread_local uintptr_t local_expected_cpu_id = std::numeric_limits<uintptr_t>::max();
inline
unsigned object_cpu_id(const void* ptr) {
return (reinterpret_cast<uintptr_t>(ptr) >> cpu_id_shift) & 0xff;
}
class page_list_link {
uint32_t _prev;
uint32_t _next;
friend class page_list;
friend seastar::internal::log_buf::inserter_iterator do_dump_memory_diagnostics(seastar::internal::log_buf::inserter_iterator);
};
constexpr size_t mem_base_alloc = size_t(1) << 44;
static char* mem_base() {
static char* known;
static std::once_flag flag;
std::call_once(flag, [] {
auto r = ::mmap(NULL, 2 * mem_base_alloc,
PROT_NONE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
-1, 0);
if (r == MAP_FAILED) {
abort();
}
::madvise(r, 2 * mem_base_alloc, MADV_DONTDUMP);
auto cr = reinterpret_cast<char*>(r);
known = align_up(cr, mem_base_alloc);
::munmap(cr, known - cr);
::munmap(known + mem_base_alloc, cr + 2 * mem_base_alloc - (known + mem_base_alloc));
});
return known;
}
bool is_seastar_memory(void * ptr)
{
auto begin = mem_base();
auto end = begin + mem_base_alloc;
return ptr >= begin && ptr < end;
}
constexpr bool is_page_aligned(size_t size) {
return (size & (page_size - 1)) == 0;
}
constexpr size_t next_page_aligned(size_t size) {
return (size + (page_size - 1)) & ~(page_size - 1);
}
class small_pool;
struct free_object {
free_object* next;
};
struct page {
bool free;
uint8_t offset_in_span;
uint16_t nr_small_alloc;
uint32_t span_size; // in pages, if we're the head or the tail
page_list_link link;
small_pool* pool; // if used in a small_pool
free_object* freelist;
#ifdef SEASTAR_HEAPPROF
allocation_site_ptr alloc_site; // for objects whose size is multiple of page size, valid for head only
#endif
};
class page_list {
uint32_t _front = 0;
uint32_t _back = 0;
public:
page& front(page* ary) { return ary[_front]; }
page& back(page* ary) { return ary[_back]; }
bool empty() const { return !_front; }
void erase(page* ary, page& span) {
if (span.link._next) {
ary[span.link._next].link._prev = span.link._prev;
} else {
_back = span.link._prev;
}
if (span.link._prev) {
ary[span.link._prev].link._next = span.link._next;
} else {
_front = span.link._next;
}
}
void push_front(page* ary, page& span) {
auto idx = &span - ary;
if (_front) {
ary[_front].link._prev = idx;
} else {
_back = idx;
}
span.link._next = _front;
span.link._prev = 0;
_front = idx;
}
void pop_front(page* ary) {
if (ary[_front].link._next) {
ary[ary[_front].link._next].link._prev = 0;
} else {
_back = 0;
}
_front = ary[_front].link._next;
}
friend seastar::internal::log_buf::inserter_iterator do_dump_memory_diagnostics(seastar::internal::log_buf::inserter_iterator);
};
class small_pool {
struct span_sizes {
uint8_t preferred;
uint8_t fallback;
};
unsigned _object_size;
span_sizes _span_sizes;
free_object* _free = nullptr;
size_t _free_count = 0;
unsigned _min_free;
unsigned _max_free;
unsigned _pages_in_use = 0;
page_list _span_list;
static constexpr unsigned idx_frac_bits = 2;
public:
explicit small_pool(unsigned object_size) noexcept;
~small_pool();
void* allocate();
void deallocate(void* object);
unsigned object_size() const { return _object_size; }
bool objects_page_aligned() const { return is_page_aligned(_object_size); }
static constexpr unsigned size_to_idx(unsigned size);
static constexpr unsigned idx_to_size(unsigned idx);
allocation_site_ptr& alloc_site_holder(void* ptr);
private:
void add_more_objects();
void trim_free_list();
friend seastar::internal::log_buf::inserter_iterator do_dump_memory_diagnostics(seastar::internal::log_buf::inserter_iterator);
};
// index 0b0001'1100 -> size (1 << 4) + 0b11 << (4 - 2)
constexpr unsigned
small_pool::idx_to_size(unsigned idx) {
size_t s = (((1 << idx_frac_bits) | (idx & ((1 << idx_frac_bits) - 1)))
<< (idx >> idx_frac_bits))
>> idx_frac_bits;
// If size is larger than max_align_t, force it to be a multiple of
// max_align_t. Clang relies in this property to use aligned mov
// instructions (e.g. movaps)
//
// Note this function is used at initialization time only, so it doesn't
// need to be especially fast.
if (s > alignof(std::max_align_t)) {
s = align_up(s, alignof(std::max_align_t));
}
return s;
}
constexpr unsigned
small_pool::size_to_idx(unsigned size) {
return ((log2floor(size) << idx_frac_bits) - ((1 << idx_frac_bits) - 1))
+ ((size - 1) >> (log2floor(size) - idx_frac_bits));
}
class small_pool_array {
public:
static constexpr unsigned nr_small_pools = small_pool::size_to_idx(4 * page_size) + 1;
private:
union u {
small_pool a[nr_small_pools];
u() {
for (unsigned i = 0; i < nr_small_pools; ++i) {
new (&a[i]) small_pool(small_pool::idx_to_size(i));
}
}
~u() {
// cannot really call destructor, since other
// objects may be freed after we are gone.
}
} _u;
public:
small_pool& operator[](unsigned idx) { return _u.a[idx]; }
};
static constexpr size_t max_small_allocation
= small_pool::idx_to_size(small_pool_array::nr_small_pools - 1);
constexpr size_t object_size_with_alloc_site(size_t size) {
#ifdef SEASTAR_HEAPPROF
// For page-aligned sizes, allocation_site* lives in page::alloc_site, not with the object.
static_assert(is_page_aligned(max_small_allocation), "assuming that max_small_allocation is page aligned so that we"
" don't need to add allocation_site_ptr to objects of size close to it");
size_t next_page_aligned_size = next_page_aligned(size);
if (next_page_aligned_size - size > sizeof(allocation_site_ptr)) {
size += sizeof(allocation_site_ptr);
} else {
return next_page_aligned_size;
}
#endif
return size;
}
#ifdef SEASTAR_HEAPPROF
// Ensure that object_size_with_alloc_site() does not exceed max_small_allocation
static_assert(object_size_with_alloc_site(max_small_allocation) == max_small_allocation, "");
static_assert(object_size_with_alloc_site(max_small_allocation - 1) == max_small_allocation, "");
static_assert(object_size_with_alloc_site(max_small_allocation - sizeof(allocation_site_ptr) + 1) == max_small_allocation, "");
static_assert(object_size_with_alloc_site(max_small_allocation - sizeof(allocation_site_ptr)) == max_small_allocation, "");
static_assert(object_size_with_alloc_site(max_small_allocation - sizeof(allocation_site_ptr) - 1) == max_small_allocation - 1, "");
static_assert(object_size_with_alloc_site(max_small_allocation - sizeof(allocation_site_ptr) - 2) == max_small_allocation - 2, "");
#endif
struct cross_cpu_free_item {
cross_cpu_free_item* next;
};
struct cpu_pages {
uint32_t min_free_pages = 20000000 / page_size;
char* memory;
page* pages;
uint32_t nr_pages;
uint32_t nr_free_pages;
uint32_t current_min_free_pages = 0;
size_t large_allocation_warning_threshold = std::numeric_limits<size_t>::max();
unsigned cpu_id = -1U;
std::function<void (std::function<void ()>)> reclaim_hook;
std::vector<reclaimer*> reclaimers;
static constexpr unsigned nr_span_lists = 32;
page_list free_spans[nr_span_lists]; // contains aligned spans with span_size == 2^idx
small_pool_array small_pools;
alignas(seastar::cache_line_size) std::atomic<cross_cpu_free_item*> xcpu_freelist;
static std::atomic<unsigned> cpu_id_gen;
static cpu_pages* all_cpus[max_cpus];
union asu {
using alloc_sites_type = std::unordered_set<allocation_site>;
asu() : alloc_sites{} {
}
~asu() {} // alloc_sites live forever
alloc_sites_type alloc_sites;
} asu;
allocation_site_ptr alloc_site_list_head = nullptr; // For easy traversal of asu.alloc_sites from scylla-gdb.py
bool collect_backtrace = false;
char* mem() { return memory; }
void link(page_list& list, page* span);
void unlink(page_list& list, page* span);
struct trim {
unsigned offset;
unsigned nr_pages;
};
void maybe_reclaim();
void* allocate_large_and_trim(unsigned nr_pages);
void* allocate_large(unsigned nr_pages);
void* allocate_large_aligned(unsigned align_pages, unsigned nr_pages);
page* find_and_unlink_span(unsigned nr_pages);
page* find_and_unlink_span_reclaiming(unsigned n_pages);
void free_large(void* ptr);
bool grow_span(pageidx& start, uint32_t& nr_pages, unsigned idx);
void free_span(pageidx start, uint32_t nr_pages);
void free_span_no_merge(pageidx start, uint32_t nr_pages);
void free_span_unaligned(pageidx start, uint32_t nr_pages);
void* allocate_small(unsigned size);
void free(void* ptr);
void free(void* ptr, size_t size);
static bool try_foreign_free(void* ptr);
void shrink(void* ptr, size_t new_size);
static void free_cross_cpu(unsigned cpu_id, void* ptr);
bool drain_cross_cpu_freelist();
size_t object_size(void* ptr);
page* to_page(void* p) {
return &pages[(reinterpret_cast<char*>(p) - mem()) / page_size];
}
bool is_initialized() const;
bool initialize();
reclaiming_result run_reclaimers(reclaimer_scope, size_t pages_to_reclaim);
void schedule_reclaim();
void set_reclaim_hook(std::function<void (std::function<void ()>)> hook);
void set_min_free_pages(size_t pages);
void resize(size_t new_size, allocate_system_memory_fn alloc_sys_mem);
void do_resize(size_t new_size, allocate_system_memory_fn alloc_sys_mem);
void replace_memory_backing(allocate_system_memory_fn alloc_sys_mem);
void check_large_allocation(size_t size);
void warn_large_allocation(size_t size);
memory::memory_layout memory_layout();
~cpu_pages();
};
static thread_local cpu_pages cpu_mem;
std::atomic<unsigned> cpu_pages::cpu_id_gen;
cpu_pages* cpu_pages::all_cpus[max_cpus];
static cpu_pages& get_cpu_mem();
#ifdef SEASTAR_HEAPPROF
void set_heap_profiling_enabled(bool enable) {
bool is_enabled = get_cpu_mem().collect_backtrace;
if (enable) {
if (!is_enabled) {
seastar_logger.info("Enabling heap profiler");
}
} else {
if (is_enabled) {
seastar_logger.info("Disabling heap profiler");
}
}
get_cpu_mem().collect_backtrace = enable;
}
static thread_local int64_t scoped_heap_profiling_embed_count = 0;
scoped_heap_profiling::scoped_heap_profiling() noexcept {
++scoped_heap_profiling_embed_count;
set_heap_profiling_enabled(true);
}
scoped_heap_profiling::~scoped_heap_profiling() {
if (!--scoped_heap_profiling_embed_count) {
set_heap_profiling_enabled(false);
}
}
#else
void set_heap_profiling_enabled(bool enable) {
seastar_logger.warn("Seastar compiled without heap profiling support, heap profiler not supported;"
" compile with the Seastar_HEAP_PROFILING=ON CMake option to add heap profiling support");
}
scoped_heap_profiling::scoped_heap_profiling() noexcept {
set_heap_profiling_enabled(true); // let it print the warning
}
scoped_heap_profiling::~scoped_heap_profiling() {
}
#endif
// Smallest index i such that all spans stored in the index are >= pages.
static inline
unsigned index_of(unsigned pages) {
if (pages == 1) {
return 0;
}
return std::numeric_limits<unsigned>::digits - count_leading_zeros(pages - 1);
}
void
cpu_pages::unlink(page_list& list, page* span) {
list.erase(pages, *span);
}
void
cpu_pages::link(page_list& list, page* span) {
list.push_front(pages, *span);
}
void cpu_pages::free_span_no_merge(uint32_t span_start, uint32_t nr_pages) {
assert(nr_pages);
nr_free_pages += nr_pages;
auto span = &pages[span_start];
auto span_end = &pages[span_start + nr_pages - 1];
span->free = span_end->free = true;
span->span_size = span_end->span_size = nr_pages;
auto idx = index_of(nr_pages);
link(free_spans[idx], span);
}
bool cpu_pages::grow_span(uint32_t& span_start, uint32_t& nr_pages, unsigned idx) {
auto which = (span_start >> idx) & 1; // 0=lower, 1=upper
// locate first page of upper buddy or last page of lower buddy
// examples: span_start = 0x10 nr_pages = 0x08 -> buddy = 0x18 (which = 0)
// span_start = 0x18 nr_pages = 0x08 -> buddy = 0x17 (which = 1)
// delta = which ? -1u : nr_pages
auto delta = ((which ^ 1) << idx) | -which;
auto buddy = span_start + delta;
if (pages[buddy].free && pages[buddy].span_size == nr_pages) {
unlink(free_spans[idx], &pages[span_start ^ nr_pages]);
nr_free_pages -= nr_pages; // free_span_no_merge() will restore
span_start &= ~nr_pages;
nr_pages *= 2;
return true;
}
return false;
}
void cpu_pages::free_span(uint32_t span_start, uint32_t nr_pages) {
auto idx = index_of(nr_pages);
while (grow_span(span_start, nr_pages, idx)) {
++idx;
}
free_span_no_merge(span_start, nr_pages);
}
// Internal, used during startup. Span is not aligned so needs to be broken up
void cpu_pages::free_span_unaligned(uint32_t span_start, uint32_t nr_pages) {
while (nr_pages) {
auto start_nr_bits = span_start ? count_trailing_zeros(span_start) : 32;
auto size_nr_bits = count_trailing_zeros(nr_pages);
auto now = 1u << std::min(start_nr_bits, size_nr_bits);
free_span(span_start, now);
span_start += now;
nr_pages -= now;
}
}
page*
cpu_pages::find_and_unlink_span(unsigned n_pages) {
auto idx = index_of(n_pages);
if (n_pages >= (2u << idx)) {
return nullptr;
}
while (idx < nr_span_lists && free_spans[idx].empty()) {
++idx;
}
if (idx == nr_span_lists) {
if (initialize()) {
return find_and_unlink_span(n_pages);
}
return nullptr;
}
auto& list = free_spans[idx];
page* span = &list.front(pages);
unlink(list, span);
return span;
}
page*
cpu_pages::find_and_unlink_span_reclaiming(unsigned n_pages) {
while (true) {
auto span = find_and_unlink_span(n_pages);
if (span) {
return span;
}
if (run_reclaimers(reclaimer_scope::sync, n_pages) == reclaiming_result::reclaimed_nothing) {
return nullptr;
}
}
}
void cpu_pages::maybe_reclaim() {
if (nr_free_pages < current_min_free_pages) {
drain_cross_cpu_freelist();
if (nr_free_pages < current_min_free_pages) {
run_reclaimers(reclaimer_scope::sync, current_min_free_pages - nr_free_pages);
}
if (nr_free_pages < current_min_free_pages) {
schedule_reclaim();
}
}
}
void*
cpu_pages::allocate_large_and_trim(unsigned n_pages) {
// Avoid exercising the reclaimers for requests we'll not be able to satisfy
// nr_pages might be zero during startup, so check for that too
if (nr_pages && n_pages >= nr_pages) {
return nullptr;
}
page* span = find_and_unlink_span_reclaiming(n_pages);
if (!span) {
return nullptr;
}
auto span_size = span->span_size;
auto span_idx = span - pages;
nr_free_pages -= span->span_size;
while (span_size >= n_pages * 2) {
span_size /= 2;
auto other_span_idx = span_idx + span_size;
free_span_no_merge(other_span_idx, span_size);
}
auto span_end = &pages[span_idx + span_size - 1];
span->free = span_end->free = false;
span->span_size = span_end->span_size = span_size;
span->pool = nullptr;
#ifdef SEASTAR_HEAPPROF
auto alloc_site = get_allocation_site();
span->alloc_site = alloc_site;
if (alloc_site) {
++alloc_site->count;
alloc_site->size += span->span_size * page_size;
}
#endif
maybe_reclaim();
return mem() + span_idx * page_size;
}
void
cpu_pages::warn_large_allocation(size_t size) {
alloc_stats::increment_local(alloc_stats::types::large_allocs);
seastar_memory_logger.warn("oversized allocation: {} bytes. This is non-fatal, but could lead to latency and/or fragmentation issues. Please report: at {}", size, current_backtrace());
large_allocation_warning_threshold *= 1.618; // prevent spam
}
void
inline
cpu_pages::check_large_allocation(size_t size) {
if (size >= large_allocation_warning_threshold) {
warn_large_allocation(size);
}
}
void*
cpu_pages::allocate_large(unsigned n_pages) {
check_large_allocation(n_pages * page_size);
return allocate_large_and_trim(n_pages);
}
void*
cpu_pages::allocate_large_aligned(unsigned align_pages, unsigned n_pages) {
check_large_allocation(n_pages * page_size);
// buddy allocation is always aligned
return allocate_large_and_trim(n_pages);
}
disable_backtrace_temporarily::disable_backtrace_temporarily() {
_old = get_cpu_mem().collect_backtrace;
get_cpu_mem().collect_backtrace = false;
}
disable_backtrace_temporarily::~disable_backtrace_temporarily() {
get_cpu_mem().collect_backtrace = _old;
}
static
saved_backtrace get_backtrace() noexcept {
disable_backtrace_temporarily dbt;
return current_backtrace();
}
static
allocation_site_ptr get_allocation_site() {
if (!cpu_mem.is_initialized() || !cpu_mem.collect_backtrace) {
return nullptr;
}
disable_backtrace_temporarily dbt;
allocation_site new_alloc_site;
new_alloc_site.backtrace = get_backtrace();
auto insert_result = cpu_mem.asu.alloc_sites.insert(std::move(new_alloc_site));
allocation_site_ptr alloc_site = &*insert_result.first;
if (insert_result.second) {
alloc_site->next = cpu_mem.alloc_site_list_head;
cpu_mem.alloc_site_list_head = alloc_site;
}
return alloc_site;
}
#ifdef SEASTAR_HEAPPROF
allocation_site_ptr&
small_pool::alloc_site_holder(void* ptr) {
if (objects_page_aligned()) {
return get_cpu_mem().to_page(ptr)->alloc_site;
} else {
return *reinterpret_cast<allocation_site_ptr*>(reinterpret_cast<char*>(ptr) + _object_size - sizeof(allocation_site_ptr));
}
}
#endif
void*
cpu_pages::allocate_small(unsigned size) {
auto idx = small_pool::size_to_idx(size);
auto& pool = small_pools[idx];
assert(size <= pool.object_size());
auto ptr = pool.allocate();
#ifdef SEASTAR_HEAPPROF
if (!ptr) {
return nullptr;
}
allocation_site_ptr alloc_site = get_allocation_site();
if (alloc_site) {
++alloc_site->count;
alloc_site->size += pool.object_size();
}
new (&pool.alloc_site_holder(ptr)) allocation_site_ptr{alloc_site};
#endif
return ptr;
}
void cpu_pages::free_large(void* ptr) {
pageidx idx = (reinterpret_cast<char*>(ptr) - mem()) / page_size;
page* span = &pages[idx];
#ifdef SEASTAR_HEAPPROF
auto alloc_site = span->alloc_site;
if (alloc_site) {
--alloc_site->count;
alloc_site->size -= span->span_size * page_size;
}
#endif
free_span(idx, span->span_size);
}
size_t cpu_pages::object_size(void* ptr) {
page* span = to_page(ptr);
if (span->pool) {
auto s = span->pool->object_size();
#ifdef SEASTAR_HEAPPROF
// We must not allow the object to be extended onto the allocation_site_ptr field.
if (!span->pool->objects_page_aligned()) {
s -= sizeof(allocation_site_ptr);
}
#endif
return s;
} else {
return size_t(span->span_size) * page_size;
}
}
void cpu_pages::free_cross_cpu(unsigned cpu_id, void* ptr) {
if (!live_cpus[cpu_id].load(std::memory_order_relaxed)) {
// Thread was destroyed; leak object
// should only happen for boost unit-tests.
return;
}
auto p = reinterpret_cast<cross_cpu_free_item*>(ptr);
auto& list = all_cpus[cpu_id]->xcpu_freelist;
auto old = list.load(std::memory_order_relaxed);
do {
p->next = old;
} while (!list.compare_exchange_weak(old, p, std::memory_order_release, std::memory_order_relaxed));
alloc_stats::increment(alloc_stats::types::cross_cpu_frees);
}
bool cpu_pages::drain_cross_cpu_freelist() {
if (!xcpu_freelist.load(std::memory_order_relaxed)) {
return false;
}
auto p = xcpu_freelist.exchange(nullptr, std::memory_order_acquire);
while (p) {
auto n = p->next;
alloc_stats::increment_local(alloc_stats::types::frees);
free(p);
p = n;
}
return true;
}
void cpu_pages::free(void* ptr) {
page* span = to_page(ptr);
if (span->pool) {
small_pool& pool = *span->pool;
#ifdef SEASTAR_HEAPPROF
allocation_site_ptr alloc_site = pool.alloc_site_holder(ptr);
if (alloc_site) {
--alloc_site->count;
alloc_site->size -= pool.object_size();
}
#endif
pool.deallocate(ptr);
} else {
free_large(ptr);
}
}
void cpu_pages::free(void* ptr, size_t size) {
// match action on allocate() so hit the right pool
if (size <= sizeof(free_object)) {
size = sizeof(free_object);
}
if (size <= max_small_allocation) {
size = object_size_with_alloc_site(size);
auto pool = &small_pools[small_pool::size_to_idx(size)];
#ifdef SEASTAR_HEAPPROF
allocation_site_ptr alloc_site = pool->alloc_site_holder(ptr);
if (alloc_site) {
--alloc_site->count;
alloc_site->size -= pool->object_size();
}
#endif
pool->deallocate(ptr);
} else {
free_large(ptr);
}
}
bool
cpu_pages::try_foreign_free(void* ptr) {
// fast path for local free
if (__builtin_expect((reinterpret_cast<uintptr_t>(ptr) & cpu_id_and_mem_base_mask) == local_expected_cpu_id, true)) {
return false;
}
if (!is_seastar_memory(ptr)) {
if (is_reactor_thread) {
alloc_stats::increment_local(alloc_stats::types::foreign_cross_frees);
} else {
alloc_stats::increment(alloc_stats::types::foreign_frees);
}
original_free_func(ptr);
return true;
}
free_cross_cpu(object_cpu_id(ptr), ptr);
return true;
}
void cpu_pages::shrink(void* ptr, size_t new_size) {
auto obj_cpu = object_cpu_id(ptr);
assert(obj_cpu == cpu_id);
page* span = to_page(ptr);
if (span->pool) {
return;
}
auto old_size_pages = span->span_size;
size_t new_size_pages = old_size_pages;
while (new_size_pages / 2 * page_size >= new_size) {
new_size_pages /= 2;
}
if (new_size_pages == old_size_pages) {
return;
}
#ifdef SEASTAR_HEAPPROF
auto alloc_site = span->alloc_site;
if (alloc_site) {
alloc_site->size -= span->span_size * page_size;
alloc_site->size += new_size_pages * page_size;