-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathtbbmalloc_internal.h
More file actions
763 lines (644 loc) · 23.9 KB
/
tbbmalloc_internal.h
File metadata and controls
763 lines (644 loc) · 23.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
/*
Copyright (c) 2005-2024 Intel Corporation
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.
*/
#ifndef __TBB_tbbmalloc_internal_H
#define __TBB_tbbmalloc_internal_H
#include "TypeDefinitions.h" /* Also includes customization layer Customize.h */
#if USE_PTHREAD
// Some pthreads documentation says that <pthreads.h> must be first header.
#include <pthread.h>
typedef pthread_key_t tls_key_t;
#elif USE_WINTHREAD
#include <windows.h>
typedef DWORD tls_key_t;
#else
#error Must define USE_PTHREAD or USE_WINTHREAD
#endif
#include <atomic>
// TODO: *BSD also has it
#define BACKEND_HAS_MREMAP __linux__
#define CHECK_ALLOCATION_RANGE MALLOC_DEBUG || MALLOC_ZONE_OVERLOAD_ENABLED || MALLOC_UNIXLIKE_OVERLOAD_ENABLED
#include "oneapi/tbb/detail/_config.h" // for __TBB_LIBSTDCPP_EXCEPTION_HEADERS_BROKEN
#include "oneapi/tbb/detail/_template_helpers.h"
#if __TBB_LIBSTDCPP_EXCEPTION_HEADERS_BROKEN
#define _EXCEPTION_PTR_H /* prevents exception_ptr.h inclusion */
#define _GLIBCXX_NESTED_EXCEPTION_H /* prevents nested_exception.h inclusion */
#endif
#include <stdio.h>
#include <stdlib.h>
#include <limits.h> // for CHAR_BIT
#include <string.h> // for memset
#if MALLOC_CHECK_RECURSION
#include <new> /* for placement new */
#endif
#include "oneapi/tbb/scalable_allocator.h"
#include "tbbmalloc_internal_api.h"
/********* Various compile-time options **************/
#if !__TBB_DEFINE_MIC && __TBB_MIC_NATIVE
#error Intel(R) Many Integrated Core Compiler does not define __MIC__ anymore.
#endif
#define MALLOC_TRACE 0
#if MALLOC_TRACE
#define TRACEF(x) printf x
#else
#define TRACEF(x) ((void)0)
#endif /* MALLOC_TRACE */
#define ASSERT_TEXT nullptr
#define COLLECT_STATISTICS ( MALLOC_DEBUG && MALLOCENV_COLLECT_STATISTICS )
#ifndef USE_INTERNAL_TID
#define USE_INTERNAL_TID COLLECT_STATISTICS || MALLOC_TRACE
#endif
#include "Statistics.h"
// call yield for whitebox testing, skip in real library
#ifndef WhiteboxTestingYield
#define WhiteboxTestingYield() ((void)0)
#endif
/********* End compile-time options **************/
namespace rml {
namespace internal {
#if __TBB_MALLOC_LOCACHE_STAT
extern intptr_t mallocCalls, cacheHits;
extern intptr_t memAllocKB, memHitKB;
#endif
//! Utility template function to prevent "unused" warnings by various compilers.
template<typename T>
void suppress_unused_warning( const T& ) {}
/********** Various global default constants ********/
/*
* Default huge page size
*/
#if defined __loongarch64
static const size_t HUGE_PAGE_SIZE = 32 * 1024 * 1024;
#else
static const size_t HUGE_PAGE_SIZE = 2 * 1024 * 1024;
#endif
/********** End of global default constants *********/
/********** Various numeric parameters controlling allocations ********/
/*
* slabSize - the size of a block for allocation of small objects,
* it must be larger than maxSegregatedObjectSize.
*/
const uintptr_t slabSize = 16*1024;
/*
* Large blocks cache cleanup frequency.
* It should be power of 2 for the fast checking.
*/
const unsigned cacheCleanupFreq = 256;
/*
* Alignment of large (>= minLargeObjectSize) objects.
*/
const size_t largeObjectAlignment = estimatedCacheLineSize;
/*
* This number of bins in the TLS that leads to blocks that we can allocate in.
*/
const uint32_t numBlockBinLimit = 31;
/********** End of numeric parameters controlling allocations *********/
class BlockI;
class Block;
struct LargeMemoryBlock;
struct ExtMemoryPool;
struct MemRegion;
class FreeBlock;
class TLSData;
class Backend;
class MemoryPool;
struct CacheBinOperation;
extern const uint32_t minLargeObjectSize;
enum DecreaseOrIncrease {
decrease, increase
};
class TLSKey {
tls_key_t TLS_pointer_key;
public:
bool init();
bool destroy();
TLSData* getThreadMallocTLS() const;
void setThreadMallocTLS( TLSData * newvalue );
TLSData* createTLS(MemoryPool *memPool, Backend *backend);
};
template<typename Arg, typename Compare>
inline void AtomicUpdate(std::atomic<Arg>& location, Arg newVal, const Compare &cmp)
{
static_assert(sizeof(Arg) == sizeof(intptr_t), "Type of argument must match AtomicCompareExchange type.");
Arg old = location.load(std::memory_order_acquire);
for (; cmp(old, newVal); ) {
if (location.compare_exchange_strong(old, newVal))
break;
// TODO: do we need backoff after unsuccessful CAS?
//old = val;
}
}
// TODO: make BitMaskBasic more general
// TODO: check that BitMaskBasic is not used for synchronization
// (currently, it fits BitMaskMin well, but not as suitable for BitMaskMax)
template<unsigned NUM>
class BitMaskBasic {
static const unsigned SZ = (NUM-1)/(CHAR_BIT*sizeof(uintptr_t))+1;
static const unsigned WORD_LEN = CHAR_BIT*sizeof(uintptr_t);
std::atomic<uintptr_t> mask[SZ];
protected:
void set(size_t idx, bool val) {
MALLOC_ASSERT(idx<NUM, ASSERT_TEXT);
size_t i = idx / WORD_LEN;
int pos = WORD_LEN - idx % WORD_LEN - 1;
if (val) {
mask[i].fetch_or(1ULL << pos);
} else {
mask[i].fetch_and(~(1ULL << pos));
}
}
int getMinTrue(unsigned startIdx) const {
unsigned idx = startIdx / WORD_LEN;
int pos;
if (startIdx % WORD_LEN) {
// only interested in part of a word, clear bits before startIdx
pos = WORD_LEN - startIdx % WORD_LEN;
uintptr_t actualMask = mask[idx].load(std::memory_order_relaxed) & (((uintptr_t)1<<pos) - 1);
idx++;
if (-1 != (pos = BitScanRev(actualMask)))
return idx*WORD_LEN - pos - 1;
}
while (idx<SZ)
if (-1 != (pos = BitScanRev(mask[idx++].load(std::memory_order_relaxed))))
return idx*WORD_LEN - pos - 1;
return -1;
}
public:
void reset() { for (unsigned i=0; i<SZ; i++) mask[i].store(0, std::memory_order_relaxed); }
};
template<unsigned NUM>
class BitMaskMin : public BitMaskBasic<NUM> {
public:
void set(size_t idx, bool val) { BitMaskBasic<NUM>::set(idx, val); }
int getMinTrue(unsigned startIdx) const {
return BitMaskBasic<NUM>::getMinTrue(startIdx);
}
};
template<unsigned NUM>
class BitMaskMax : public BitMaskBasic<NUM> {
public:
void set(size_t idx, bool val) {
MALLOC_ASSERT(NUM >= idx + 1, ASSERT_TEXT);
BitMaskBasic<NUM>::set(NUM - 1 - idx, val);
}
int getMaxTrue(unsigned startIdx) const {
MALLOC_ASSERT(NUM >= startIdx + 1, ASSERT_TEXT);
int p = BitMaskBasic<NUM>::getMinTrue(NUM-startIdx-1);
return -1==p? -1 : (int)NUM - 1 - p;
}
};
// The part of thread-specific data that can be modified by other threads.
// Such modifications must be protected by AllLocalCaches::listLock.
struct TLSRemote {
TLSRemote *next,
*prev;
};
// The list of all thread-local data; supporting cleanup of thread caches
class AllLocalCaches {
TLSRemote *head;
MallocMutex listLock; // protects operations in the list
public:
void registerThread(TLSRemote *tls);
void unregisterThread(TLSRemote *tls);
bool cleanup(bool cleanOnlyUnused);
void markUnused();
void reset() { head = nullptr; }
};
class LifoList {
public:
inline LifoList();
inline void push(Block *block);
inline Block *pop();
inline Block *grab();
private:
std::atomic<Block*> top;
MallocMutex lock;
};
/*
* When a block that is not completely free is returned for reuse by other threads
* this is where the block goes.
*
* LifoList assumes zero initialization; so below its constructors are omitted,
* to avoid linking with C++ libraries on Linux.
*/
class OrphanedBlocks {
LifoList bins[numBlockBinLimit];
public:
Block *get(TLSData *tls, unsigned int size);
void put(intptr_t binTag, Block *block);
void reset();
bool cleanup(Backend* backend);
};
/* Large objects entities */
#include "large_objects.h"
// select index size for BackRefMain based on word size: default is uint32_t,
// uint16_t for 32-bit platforms
template<bool>
struct MainIndexSelect {
typedef uint32_t main_type;
};
template<>
struct MainIndexSelect<false> {
typedef uint16_t main_type;
};
class BackRefIdx { // composite index to backreference array
public:
typedef MainIndexSelect<4 < sizeof(uintptr_t)>::main_type main_t;
private:
static const main_t invalid = ~main_t(0);
main_t main; // index in BackRefMain
uint16_t largeObj:1; // is this object "large"?
uint16_t offset :15; // offset from beginning of BackRefBlock
public:
BackRefIdx() : main(invalid), largeObj(0), offset(0) {}
bool isInvalid() const { return main == invalid; }
bool isLargeObject() const { return largeObj; }
main_t getMain() const { return main; }
uint16_t getOffset() const { return offset; }
#if __TBB_USE_THREAD_SANITIZER
friend
__attribute__((no_sanitize("thread")))
BackRefIdx dereference(const BackRefIdx* ptr) {
BackRefIdx idx;
idx.main = ptr->main;
idx.largeObj = ptr->largeObj;
idx.offset = ptr->offset;
return idx;
}
#else
friend
BackRefIdx dereference(const BackRefIdx* ptr) {
return *ptr;
}
#endif
// only newBackRef can modify BackRefIdx
static BackRefIdx newBackRef(bool largeObj);
};
// Block header is used during block coalescing
// and must be preserved in used blocks.
class BlockI {
#if __clang__ && !__INTEL_COMPILER
// #pragma clang diagnostic push
// #pragma clang diagnostic ignored "-Wunused-private-field"
#endif
intptr_t blockState[2];
#if __clang__ && !__INTEL_COMPILER
// #pragma clang diagnostic pop // "-Wunused-private-field"
#endif
};
struct LargeMemoryBlock : public BlockI {
MemoryPool *pool; // owner pool
LargeMemoryBlock *next, // ptrs in list of cached blocks
*prev,
// 2-linked list of pool's large objects
// Used to destroy backrefs on pool destroy (backrefs are global)
// and for object releasing during pool reset.
*gPrev,
*gNext;
uintptr_t age; // age of block while in cache
size_t objectSize; // the size requested by a client
size_t unalignedSize; // the size requested from backend
BackRefIdx backRefIdx; // cached here, used copy is in LargeObjectHdr
};
// Classes and methods for backend.cpp
#include "backend.h"
// An TBB allocator mode that can be controlled by user
// via API/environment variable. Must be placed in zero-initialized memory.
// External synchronization assumed.
// TODO: TBB_VERSION support
class AllocControlledMode {
intptr_t val;
bool setDone;
public:
intptr_t get() const {
MALLOC_ASSERT(setDone, ASSERT_TEXT);
return val;
}
// Note: set() can be called before init()
void set(intptr_t newVal) {
val = newVal;
setDone = true;
}
bool ready() const {
return setDone;
}
// envName - environment variable to get controlled mode
void initReadEnv(const char *envName, intptr_t defaultVal) {
if (!setDone) {
// unreferenced formal parameter warning
tbb::detail::suppress_unused_warning(envName);
#if !__TBB_WIN8UI_SUPPORT
// TODO: use strtol to get the actual value of the envirable
const char *envVal = getenv(envName);
if (envVal && !strcmp(envVal, "1"))
val = 1;
else
#endif
val = defaultVal;
setDone = true;
}
}
};
// Page type to be used inside MapMemory.
// Regular (4KB aligned), Huge and Transparent Huge Pages (2MB aligned).
enum PageType {
REGULAR = 0,
PREALLOCATED_HUGE_PAGE,
TRANSPARENT_HUGE_PAGE
};
// init() and printStatus() is called only under global initialization lock.
// Race is possible between registerAllocation() and registerReleasing(),
// harm is that up to single huge page releasing is missed (because failure
// to get huge page is registered only 1st time), that is negligible.
// setMode is also can be called concurrently.
// Object must reside in zero-initialized memory
// TODO: can we check for huge page presence during every 10th mmap() call
// in case huge page is released by another process?
class HugePagesStatus {
private:
AllocControlledMode requestedMode; // changed only by user
// to keep enabled and requestedMode consistent
MallocMutex setModeLock;
size_t pageSize;
std::atomic<intptr_t> needActualStatusPrint;
static void doPrintStatus(bool state, const char *stateName) {
// Under macOS* fprintf/snprintf acquires an internal lock, so when
// 1st allocation is done under the lock, we got a deadlock.
// Do not use fprintf etc during initialization.
fputs("TBBmalloc: huge pages\t", stderr);
if (!state)
fputs("not ", stderr);
fputs(stateName, stderr);
fputs("\n", stderr);
}
void parseSystemMemInfo() {
bool hpAvailable = false;
bool thpAvailable = false;
long long hugePageSize = -1;
#if __unix__
// Check huge pages existence
long long meminfoHugePagesTotal = 0;
parseFileItem meminfoItems[] = {
// Parse system huge page size
{ "Hugepagesize: %lld kB", hugePageSize },
// Check if there are preallocated huge pages on the system
// https://www.kernel.org/doc/Documentation/vm/hugetlbpage.txt
{ "HugePages_Total: %lld", meminfoHugePagesTotal } };
parseFile</*BUFF_SIZE=*/100>("/proc/meminfo", meminfoItems);
// Double check another system information regarding preallocated
// huge pages if there are no information in /proc/meminfo
long long vmHugePagesTotal = 0;
parseFileItem vmItem[] = { { "%lld", vmHugePagesTotal } };
// We parse a counter number, it can't be huge
parseFile</*BUFF_SIZE=*/100>("/proc/sys/vm/nr_hugepages", vmItem);
if (hugePageSize > -1 && (meminfoHugePagesTotal > 0 || vmHugePagesTotal > 0)) {
MALLOC_ASSERT(hugePageSize != 0, "Huge Page size can't be zero if we found preallocated.");
// Any non zero value clearly states that there are preallocated
// huge pages on the system
hpAvailable = true;
}
// Check if there is transparent huge pages support on the system
long long thpPresent = 'n';
parseFileItem thpItem[] = { { "[alwa%cs] madvise never\n", thpPresent } };
parseFile</*BUFF_SIZE=*/100>("/sys/kernel/mm/transparent_hugepage/enabled", thpItem);
if (hugePageSize > -1 && thpPresent == 'y') {
MALLOC_ASSERT(hugePageSize != 0, "Huge Page size can't be zero if we found thp existence.");
thpAvailable = true;
}
#endif
MALLOC_ASSERT(!pageSize, "Huge page size can't be set twice. Double initialization.");
// Initialize object variables
if (hugePageSize > -1) {
pageSize = hugePageSize * 1024; // was read in KB from meminfo
} else {
pageSize = 0;
}
isHPAvailable = hpAvailable;
isTHPAvailable = thpAvailable;
}
public:
// System information
bool isHPAvailable;
bool isTHPAvailable;
// User defined value
bool isEnabled;
void init() {
parseSystemMemInfo();
MallocMutex::scoped_lock lock(setModeLock);
requestedMode.initReadEnv("TBB_MALLOC_USE_HUGE_PAGES", 0);
isEnabled = (isHPAvailable || isTHPAvailable) && requestedMode.get();
}
// Could be set from user code at any place.
// If we didn't call init() at this place, isEnabled will be false
void setMode(intptr_t newVal) {
MallocMutex::scoped_lock lock(setModeLock);
requestedMode.set(newVal);
isEnabled = (isHPAvailable || isTHPAvailable) && newVal;
}
void reset() {
needActualStatusPrint.store(0, std::memory_order_relaxed);
pageSize = 0;
isEnabled = isHPAvailable = isTHPAvailable = false;
}
// If memory mapping size is a multiple of huge page size, some OS kernels
// can use huge pages transparently. Use this when huge pages are requested.
size_t getGranularity() const {
if (requestedMode.ready())
return requestedMode.get() ? pageSize : 0;
else
return HUGE_PAGE_SIZE; // the mode is not yet known; assume typical 2MB huge pages
}
void printStatus() {
doPrintStatus(requestedMode.get(), "requested");
if (requestedMode.get()) { // report actual status iff requested
if (pageSize)
needActualStatusPrint.store(1, std::memory_order_release);
else
doPrintStatus(/*state=*/false, "available");
}
}
};
class AllLargeBlocksList {
MallocMutex largeObjLock;
LargeMemoryBlock *loHead;
public:
void add(LargeMemoryBlock *lmb);
void remove(LargeMemoryBlock *lmb);
template<bool poolDestroy> void releaseAll(Backend *backend);
};
struct ExtMemoryPool {
Backend backend;
LargeObjectCache loc;
AllLocalCaches allLocalCaches;
OrphanedBlocks orphanedBlocks;
intptr_t poolId;
// To find all large objects. Used during user pool destruction,
// to release all backreferences in large blocks (slab blocks do not have them).
AllLargeBlocksList lmbList;
// Callbacks to be used instead of MapMemory/UnmapMemory.
rawAllocType rawAlloc;
rawFreeType rawFree;
size_t granularity;
bool keepAllMemory,
delayRegsReleasing,
// TODO: implements fixedPool with calling rawFree on destruction
fixedPool;
TLSKey tlsPointerKey; // per-pool TLS key
std::atomic<int> softCachesCleanupInProgress;
std::atomic<int> hardCachesCleanupInProgress;
bool init(intptr_t poolId, rawAllocType rawAlloc, rawFreeType rawFree,
size_t granularity, bool keepAllMemory, bool fixedPool);
bool initTLS();
// i.e., not system default pool for scalable_malloc/scalable_free
bool userPool() const { return rawAlloc; }
// true if something has been released
bool softCachesCleanup();
bool releaseAllLocalCaches();
bool hardCachesCleanup(bool wait);
void *remap(void *ptr, size_t oldSize, size_t newSize, size_t alignment);
bool reset() {
loc.reset();
allLocalCaches.reset();
orphanedBlocks.reset();
bool ret = tlsPointerKey.destroy();
backend.reset();
return ret;
}
bool destroy() {
MALLOC_ASSERT(isPoolValid(),
"Possible double pool_destroy or heap corruption");
if (!userPool()) {
loc.reset();
allLocalCaches.reset();
}
// pthread_key_dtors must be disabled before memory unmapping
// TODO: race-free solution
bool ret = tlsPointerKey.destroy();
if (rawFree || !userPool())
ret &= backend.destroy();
// pool is not valid after this point
granularity = 0;
return ret;
}
void delayRegionsReleasing(bool mode) { delayRegsReleasing = mode; }
inline bool regionsAreReleaseable() const;
LargeMemoryBlock *mallocLargeObject(MemoryPool *pool, size_t allocationSize);
void freeLargeObject(LargeMemoryBlock *lmb);
void freeLargeObjectList(LargeMemoryBlock *head);
#if MALLOC_DEBUG
// use granulatity as marker for pool validity
bool isPoolValid() const { return granularity; }
#endif
};
inline bool Backend::inUserPool() const { return extMemPool->userPool(); }
struct LargeObjectHdr {
LargeMemoryBlock *memoryBlock;
/* Backreference points to LargeObjectHdr.
Duplicated in LargeMemoryBlock to reuse in subsequent allocations. */
BackRefIdx backRefIdx;
};
struct FreeObject {
FreeObject *next;
};
/******* A helper class to support overriding malloc with scalable_malloc *******/
#if MALLOC_CHECK_RECURSION
class RecursiveMallocCallProtector {
// pointer to an automatic data of holding thread
static std::atomic<void*> autoObjPtr;
static MallocMutex rmc_mutex;
static std::atomic<pthread_t> owner_thread;
/* Under FreeBSD 8.0 1st call to any pthread function including pthread_self
leads to pthread initialization, that causes malloc calls. As 1st usage of
RecursiveMallocCallProtector can be before pthread initialized, pthread calls
can't be used in 1st instance of RecursiveMallocCallProtector.
RecursiveMallocCallProtector is used 1st time in checkInitialization(),
so there is a guarantee that on 2nd usage pthread is initialized.
No such situation observed with other supported OSes.
*/
#if __FreeBSD__
static bool canUsePthread;
#else
static const bool canUsePthread = true;
#endif
/*
The variable modified in checkInitialization,
so can be read without memory barriers.
*/
static bool mallocRecursionDetected;
MallocMutex::scoped_lock* lock_acquired;
char scoped_lock_space[sizeof(MallocMutex::scoped_lock)+1];
public:
RecursiveMallocCallProtector() : lock_acquired(nullptr) {
lock_acquired = new (scoped_lock_space) MallocMutex::scoped_lock( rmc_mutex );
if (canUsePthread)
owner_thread.store(pthread_self(), std::memory_order_relaxed);
autoObjPtr.store(&scoped_lock_space, std::memory_order_relaxed);
}
RecursiveMallocCallProtector(RecursiveMallocCallProtector&) = delete;
RecursiveMallocCallProtector& operator=(RecursiveMallocCallProtector) = delete;
~RecursiveMallocCallProtector() {
if (lock_acquired) {
autoObjPtr.store(nullptr, std::memory_order_relaxed);
lock_acquired->~scoped_lock();
}
}
static bool sameThreadActive() {
if (!autoObjPtr.load(std::memory_order_relaxed)) // fast path
return false;
// Some thread has an active recursive call protector; check if the current one.
// Exact pthread_self based test
if (canUsePthread) {
if (pthread_equal( owner_thread.load(std::memory_order_relaxed), pthread_self() )) {
mallocRecursionDetected = true;
return true;
} else
return false;
}
// inexact stack size based test
const uintptr_t threadStackSz = 2*1024*1024;
int dummy;
uintptr_t xi = (uintptr_t)autoObjPtr.load(std::memory_order_relaxed), yi = (uintptr_t)&dummy;
uintptr_t diffPtr = xi > yi ? xi - yi : yi - xi;
return diffPtr < threadStackSz;
}
/* The function is called on 1st scalable_malloc call to check if malloc calls
scalable_malloc (nested call must set mallocRecursionDetected). */
static void detectNaiveOverload() {
if (!malloc_proxy) {
#if __FreeBSD__
/* If !canUsePthread, we can't call pthread_self() before, but now pthread
is already on, so can do it. */
if (!canUsePthread) {
canUsePthread = true;
owner_thread.store(pthread_self(), std::memory_order_relaxed);
}
#endif
free(malloc(1));
}
}
};
#else
class RecursiveMallocCallProtector {
public:
RecursiveMallocCallProtector() {}
~RecursiveMallocCallProtector() {}
};
#endif /* MALLOC_CHECK_RECURSION */
unsigned int getThreadId();
bool initBackRefMain(Backend *backend);
void destroyBackRefMain(Backend *backend);
void removeBackRef(BackRefIdx backRefIdx);
void setBackRef(BackRefIdx backRefIdx, void *newPtr);
void *getBackRef(BackRefIdx backRefIdx);
} // namespace internal
} // namespace rml
#endif // __TBB_tbbmalloc_internal_H