source: libcfa/src/heap.cfa@ 5657de9

ADT ast-experimental
Last change on this file since 5657de9 was 0bdfcc3, checked in by Peter A. Buhr <pabuhr@…>, 3 years ago

formatting

  • Property mode set to 100644
File size: 66.9 KB
RevLine 
[73abe95]1//
[c4f68dc]2// Cforall Version 1.0.0 Copyright (C) 2017 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
[73abe95]6//
[92aca37]7// heap.cfa --
[73abe95]8//
[c4f68dc]9// Author : Peter A. Buhr
10// Created On : Tue Dec 19 21:58:35 2017
11// Last Modified By : Peter A. Buhr
[0bdfcc3]12// Last Modified On : Sun Oct 30 20:56:20 2022
13// Update Count : 1584
[73abe95]14//
[c4f68dc]15
[116a2ea]16#include <stdio.h>
[1e034d9]17#include <string.h> // memset, memcpy
[1076d05]18#include <limits.h> // ULONG_MAX
[31a5f418]19#include <stdlib.h> // EXIT_FAILURE
20#include <errno.h> // errno, ENOMEM, EINVAL
21#include <unistd.h> // STDERR_FILENO, sbrk, sysconf
[ada0246d]22#include <malloc.h> // memalign, malloc_usable_size
[c4f68dc]23#include <sys/mman.h> // mmap, munmap
[116a2ea]24extern "C" {
[31a5f418]25#include <sys/sysinfo.h> // get_nprocs
[116a2ea]26} // extern "C"
[c4f68dc]27
[92aca37]28#include "bits/align.hfa" // libAlign
[bcb14b5]29#include "bits/defs.hfa" // likely, unlikely
[116a2ea]30#include "concurrency/kernel/fwd.hfa" // __POLL_PREEMPTION
[73abe95]31#include "startup.hfa" // STARTUP_PRIORITY_MEMORY
[116a2ea]32#include "math.hfa" // ceiling, min
[7cfef0d]33#include "bitmanip.hfa" // is_pow2, ceiling2
[c4f68dc]34
[116a2ea]35// supported mallopt options
36#ifndef M_MMAP_THRESHOLD
37#define M_MMAP_THRESHOLD (-1)
38#endif // M_MMAP_THRESHOLD
39
40#ifndef M_TOP_PAD
41#define M_TOP_PAD (-2)
42#endif // M_TOP_PAD
43
44#define FASTLOOKUP // use O(1) table lookup from allocation size to bucket size
45#define OWNERSHIP // return freed memory to owner thread
[7a2057a]46#define RETURNSPIN // toggle spinlock / lockfree queue
47#if ! defined( OWNERSHIP ) && defined( RETURNSPIN )
48#warning "RETURNSPIN is ignored without OWNERSHIP; suggest commenting out RETURNSPIN"
49#endif // ! OWNERSHIP && RETURNSPIN
[116a2ea]50
51#define CACHE_ALIGN 64
52#define CALIGN __attribute__(( aligned(CACHE_ALIGN) ))
53
54#define TLSMODEL __attribute__(( tls_model("initial-exec") ))
55
56//#define __STATISTICS__
57
58enum {
59 // The default extension heap amount in units of bytes. When the current heap reaches the brk address, the brk
60 // address is extended by the extension amount.
61 __CFA_DEFAULT_HEAP_EXPANSION__ = 10 * 1024 * 1024,
62
63 // The mmap crossover point during allocation. Allocations less than this amount are allocated from buckets; values
64 // greater than or equal to this value are mmap from the operating system.
65 __CFA_DEFAULT_MMAP_START__ = 512 * 1024 + 1,
66
67 // The default unfreed storage amount in units of bytes. When the uC++ program ends it subtracts this amount from
68 // the malloc/free counter to adjust for storage the program does not free.
69 __CFA_DEFAULT_HEAP_UNFREED__ = 0
70}; // enum
71
72
73//####################### Heap Trace/Print ####################
[31a5f418]74
75
[93c2e0a]76static bool traceHeap = false;
[d46ed6e]77
[032234bd]78inline bool traceHeap() libcfa_public { return traceHeap; }
[d46ed6e]79
[032234bd]80bool traceHeapOn() libcfa_public {
[93c2e0a]81 bool temp = traceHeap;
[d46ed6e]82 traceHeap = true;
83 return temp;
84} // traceHeapOn
85
[032234bd]86bool traceHeapOff() libcfa_public {
[93c2e0a]87 bool temp = traceHeap;
[d46ed6e]88 traceHeap = false;
89 return temp;
90} // traceHeapOff
91
[032234bd]92bool traceHeapTerm() libcfa_public { return false; }
[baf608a]93
[d46ed6e]94
[95eb7cf]95static bool prtFree = false;
[d46ed6e]96
[116a2ea]97bool prtFree() {
[95eb7cf]98 return prtFree;
99} // prtFree
[5d4fa18]100
[116a2ea]101bool prtFreeOn() {
[95eb7cf]102 bool temp = prtFree;
103 prtFree = true;
[5d4fa18]104 return temp;
[95eb7cf]105} // prtFreeOn
[5d4fa18]106
[116a2ea]107bool prtFreeOff() {
[95eb7cf]108 bool temp = prtFree;
109 prtFree = false;
[5d4fa18]110 return temp;
[95eb7cf]111} // prtFreeOff
[5d4fa18]112
113
[7a2057a]114//######################### Helpers #########################
115
116
117// generic Bsearchl does not inline, so substitute with hand-coded binary-search.
118inline __attribute__((always_inline))
119static size_t Bsearchl( unsigned int key, const unsigned int vals[], size_t dim ) {
120 size_t l = 0, m, h = dim;
121 while ( l < h ) {
122 m = (l + h) / 2;
123 if ( (unsigned int &)(vals[m]) < key ) { // cast away const
124 l = m + 1;
125 } else {
126 h = m;
127 } // if
128 } // while
129 return l;
130} // Bsearchl
[1e034d9]131
[dd23e66]132
[116a2ea]133// pause to prevent excess processor bus usage
134#if defined( __i386 ) || defined( __x86_64 )
135 #define Pause() __asm__ __volatile__ ( "pause" : : : )
136#elif defined(__ARM_ARCH)
137 #define Pause() __asm__ __volatile__ ( "YIELD" : : : )
138#else
139 #error unsupported architecture
140#endif
141
142typedef volatile uintptr_t SpinLock_t CALIGN; // aligned addressable word-size
143
144static inline __attribute__((always_inline)) void lock( volatile SpinLock_t & slock ) {
145 enum { SPIN_START = 4, SPIN_END = 64 * 1024, };
146 unsigned int spin = SPIN_START;
147
148 for ( unsigned int i = 1;; i += 1 ) {
149 if ( slock == 0 && __atomic_test_and_set( &slock, __ATOMIC_SEQ_CST ) == 0 ) break; // Fence
150 for ( volatile unsigned int s = 0; s < spin; s += 1 ) Pause(); // exponential spin
151 spin += spin; // powers of 2
152 //if ( i % 64 == 0 ) spin += spin; // slowly increase by powers of 2
153 if ( spin > SPIN_END ) spin = SPIN_END; // cap spinning
154 } // for
155} // spin_lock
156
157static inline __attribute__((always_inline)) void unlock( volatile SpinLock_t & slock ) {
158 __atomic_clear( &slock, __ATOMIC_SEQ_CST ); // Fence
159} // spin_unlock
[e723100]160
161
[433905a]162//####################### Heap Statistics ####################
[d46ed6e]163
164
[433905a]165#ifdef __STATISTICS__
166enum { CntTriples = 12 }; // number of counter triples
167enum { MALLOC, AALLOC, CALLOC, MEMALIGN, AMEMALIGN, CMEMALIGN, RESIZE, REALLOC, FREE };
[bcb14b5]168
[433905a]169struct StatsOverlay { // overlay for iteration
170 unsigned int calls, calls_0;
171 unsigned long long int request, alloc;
172};
[d46ed6e]173
[433905a]174// Heap statistics counters.
175union HeapStatistics {
176 struct { // minimum qualification
177 unsigned int malloc_calls, malloc_0_calls;
178 unsigned long long int malloc_storage_request, malloc_storage_alloc;
179 unsigned int aalloc_calls, aalloc_0_calls;
180 unsigned long long int aalloc_storage_request, aalloc_storage_alloc;
181 unsigned int calloc_calls, calloc_0_calls;
182 unsigned long long int calloc_storage_request, calloc_storage_alloc;
183 unsigned int memalign_calls, memalign_0_calls;
184 unsigned long long int memalign_storage_request, memalign_storage_alloc;
185 unsigned int amemalign_calls, amemalign_0_calls;
186 unsigned long long int amemalign_storage_request, amemalign_storage_alloc;
187 unsigned int cmemalign_calls, cmemalign_0_calls;
188 unsigned long long int cmemalign_storage_request, cmemalign_storage_alloc;
189 unsigned int resize_calls, resize_0_calls;
190 unsigned long long int resize_storage_request, resize_storage_alloc;
191 unsigned int realloc_calls, realloc_0_calls;
192 unsigned long long int realloc_storage_request, realloc_storage_alloc;
193 unsigned int free_calls, free_null_calls;
194 unsigned long long int free_storage_request, free_storage_alloc;
[116a2ea]195 unsigned int return_pulls, return_pushes;
196 unsigned long long int return_storage_request, return_storage_alloc;
[433905a]197 unsigned int mmap_calls, mmap_0_calls; // no zero calls
198 unsigned long long int mmap_storage_request, mmap_storage_alloc;
199 unsigned int munmap_calls, munmap_0_calls; // no zero calls
200 unsigned long long int munmap_storage_request, munmap_storage_alloc;
201 };
202 struct StatsOverlay counters[CntTriples]; // overlay for iteration
203}; // HeapStatistics
[1e034d9]204
[433905a]205static_assert( sizeof(HeapStatistics) == CntTriples * sizeof(StatsOverlay),
[116a2ea]206 "Heap statistics counter-triplets does not match with array size" );
[433905a]207
208static void HeapStatisticsCtor( HeapStatistics & stats ) {
209 memset( &stats, '\0', sizeof(stats) ); // very fast
210 // for ( unsigned int i = 0; i < CntTriples; i += 1 ) {
211 // stats.counters[i].calls = stats.counters[i].calls_0 = stats.counters[i].request = stats.counters[i].alloc = 0;
212 // } // for
213} // HeapStatisticsCtor
214
215static HeapStatistics & ?+=?( HeapStatistics & lhs, const HeapStatistics & rhs ) {
216 for ( unsigned int i = 0; i < CntTriples; i += 1 ) {
217 lhs.counters[i].calls += rhs.counters[i].calls;
218 lhs.counters[i].calls_0 += rhs.counters[i].calls_0;
219 lhs.counters[i].request += rhs.counters[i].request;
220 lhs.counters[i].alloc += rhs.counters[i].alloc;
221 } // for
222 return lhs;
223} // ?+=?
224#endif // __STATISTICS__
[e723100]225
226
227// Recursive definitions: HeapManager needs size of bucket array and bucket area needs sizeof HeapManager storage.
[31a5f418]228// Break recursion by hardcoding number of buckets and statically checking number is correct after bucket array defined.
[95eb7cf]229enum { NoBucketSizes = 91 }; // number of buckets sizes
[d46ed6e]230
[31a5f418]231struct Heap {
[c4f68dc]232 struct Storage {
[bcb14b5]233 struct Header { // header
[c4f68dc]234 union Kind {
235 struct RealHeader {
236 union {
[bcb14b5]237 struct { // 4-byte word => 8-byte header, 8-byte word => 16-byte header
[c4f68dc]238 union {
[31a5f418]239 // 2nd low-order bit => zero filled, 3rd low-order bit => mmapped
[9c438546]240 // FreeHeader * home; // allocated block points back to home locations (must overlay alignment)
[c4f68dc]241 void * home; // allocated block points back to home locations (must overlay alignment)
242 size_t blockSize; // size for munmap (must overlay alignment)
[31a5f418]243 Storage * next; // freed block points to next freed block of same size
[c4f68dc]244 };
[9c438546]245 size_t size; // allocation size in bytes
[c4f68dc]246 };
247 };
[93c2e0a]248 } real; // RealHeader
[9c438546]249
[c4f68dc]250 struct FakeHeader {
[31a5f418]251 uintptr_t alignment; // 1st low-order bit => fake header & alignment
252 uintptr_t offset;
[93c2e0a]253 } fake; // FakeHeader
254 } kind; // Kind
[bcb14b5]255 } header; // Header
[31a5f418]256
[95eb7cf]257 char pad[libAlign() - sizeof( Header )];
[bcb14b5]258 char data[0]; // storage
[c4f68dc]259 }; // Storage
260
[31a5f418]261 static_assert( libAlign() >= sizeof( Storage ), "minimum alignment < sizeof( Storage )" );
[c4f68dc]262
[116a2ea]263 struct __attribute__(( aligned (8) )) FreeHeader {
264 size_t blockSize __attribute__(( aligned(8) )); // size of allocations on this list
265 #ifdef OWNERSHIP
266 #ifdef RETURNSPIN
267 SpinLock_t returnLock;
268 #endif // RETURNSPIN
269 Storage * returnList; // other thread return list
270 #endif // OWNERSHIP
[7a2057a]271
[116a2ea]272 Storage * freeList; // thread free list
273 Heap * homeManager; // heap owner (free storage to bucket, from bucket to heap)
274 }; // FreeHeader
[c4f68dc]275
276 FreeHeader freeLists[NoBucketSizes]; // buckets for different allocation sizes
[116a2ea]277 void * heapBuffer; // start of free storage in buffer
278 size_t heapReserve; // amount of remaining free storage in buffer
[c4f68dc]279
[116a2ea]280 #if defined( __STATISTICS__ ) || defined( __CFA_DEBUG__ )
281 Heap * nextHeapManager; // intrusive link of existing heaps; traversed to collect statistics or check unfreed storage
282 #endif // __STATISTICS__ || __CFA_DEBUG__
283 Heap * nextFreeHeapManager; // intrusive link of free heaps from terminated threads; reused by new threads
284
285 #ifdef __CFA_DEBUG__
286 int64_t allocUnfreed; // running total of allocations minus frees; can be negative
287 #endif // __CFA_DEBUG__
288
289 #ifdef __STATISTICS__
290 HeapStatistics stats; // local statistic table for this heap
291 #endif // __STATISTICS__
[31a5f418]292}; // Heap
[c4f68dc]293
[116a2ea]294
295struct HeapMaster {
296 SpinLock_t extLock; // protects allocation-buffer extension
297 SpinLock_t mgrLock; // protects freeHeapManagersList, heapManagersList, heapManagersStorage, heapManagersStorageEnd
298
299 void * heapBegin; // start of heap
300 void * heapEnd; // logical end of heap
301 size_t heapRemaining; // amount of storage not allocated in the current chunk
302 size_t pageSize; // architecture pagesize
303 size_t heapExpand; // sbrk advance
304 size_t mmapStart; // cross over point for mmap
305 unsigned int maxBucketsUsed; // maximum number of buckets in use
306
307 Heap * heapManagersList; // heap-list head
308 Heap * freeHeapManagersList; // free-list head
309
310 // Heap superblocks are not linked; heaps in superblocks are linked via intrusive links.
311 Heap * heapManagersStorage; // next heap to use in heap superblock
312 Heap * heapManagersStorageEnd; // logical heap outside of superblock's end
313
314 #ifdef __STATISTICS__
315 HeapStatistics stats; // global stats for thread-local heaps to add there counters when exiting
316 unsigned long int threads_started, threads_exited; // counts threads that have started and exited
317 unsigned long int reused_heap, new_heap; // counts reusability of heaps
318 unsigned int sbrk_calls;
319 unsigned long long int sbrk_storage;
320 int stats_fd;
321 #endif // __STATISTICS__
322}; // HeapMaster
[5d4fa18]323
[e723100]324
[31a5f418]325#ifdef FASTLOOKUP
[116a2ea]326enum { LookupSizes = 65_536 + sizeof(Heap.Storage) }; // number of fast lookup sizes
[31a5f418]327static unsigned char lookup[LookupSizes]; // O(1) lookup for small sizes
328#endif // FASTLOOKUP
329
[116a2ea]330static volatile bool heapMasterBootFlag = false; // trigger for first heap
331static HeapMaster heapMaster @= {}; // program global
332
333static void heapMasterCtor();
334static void heapMasterDtor();
335static Heap * getHeap();
[31a5f418]336
[5d4fa18]337
[c1f38e6c]338// Size of array must harmonize with NoBucketSizes and individual bucket sizes must be multiple of 16.
[d5d3a90]339// Smaller multiples of 16 and powers of 2 are common allocation sizes, so make them generate the minimum required bucket size.
340// malloc(0) returns 0p, so no bucket is necessary for 0 bytes returning an address that can be freed.
[e723100]341static const unsigned int bucketSizes[] @= { // different bucket sizes
[31a5f418]342 16 + sizeof(Heap.Storage), 32 + sizeof(Heap.Storage), 48 + sizeof(Heap.Storage), 64 + sizeof(Heap.Storage), // 4
343 96 + sizeof(Heap.Storage), 112 + sizeof(Heap.Storage), 128 + sizeof(Heap.Storage), // 3
344 160, 192, 224, 256 + sizeof(Heap.Storage), // 4
345 320, 384, 448, 512 + sizeof(Heap.Storage), // 4
346 640, 768, 896, 1_024 + sizeof(Heap.Storage), // 4
347 1_536, 2_048 + sizeof(Heap.Storage), // 2
348 2_560, 3_072, 3_584, 4_096 + sizeof(Heap.Storage), // 4
349 6_144, 8_192 + sizeof(Heap.Storage), // 2
350 9_216, 10_240, 11_264, 12_288, 13_312, 14_336, 15_360, 16_384 + sizeof(Heap.Storage), // 8
351 18_432, 20_480, 22_528, 24_576, 26_624, 28_672, 30_720, 32_768 + sizeof(Heap.Storage), // 8
352 36_864, 40_960, 45_056, 49_152, 53_248, 57_344, 61_440, 65_536 + sizeof(Heap.Storage), // 8
353 73_728, 81_920, 90_112, 98_304, 106_496, 114_688, 122_880, 131_072 + sizeof(Heap.Storage), // 8
354 147_456, 163_840, 180_224, 196_608, 212_992, 229_376, 245_760, 262_144 + sizeof(Heap.Storage), // 8
355 294_912, 327_680, 360_448, 393_216, 425_984, 458_752, 491_520, 524_288 + sizeof(Heap.Storage), // 8
356 655_360, 786_432, 917_504, 1_048_576 + sizeof(Heap.Storage), // 4
357 1_179_648, 1_310_720, 1_441_792, 1_572_864, 1_703_936, 1_835_008, 1_966_080, 2_097_152 + sizeof(Heap.Storage), // 8
358 2_621_440, 3_145_728, 3_670_016, 4_194_304 + sizeof(Heap.Storage), // 4
[5d4fa18]359};
[e723100]360
[c1f38e6c]361static_assert( NoBucketSizes == sizeof(bucketSizes) / sizeof(bucketSizes[0] ), "size of bucket array wrong" );
[e723100]362
[5d4fa18]363
[116a2ea]364// extern visibility, used by runtime kernel
365libcfa_public size_t __page_size; // architecture pagesize
366libcfa_public int __map_prot; // common mmap/mprotect protection
[c4f68dc]367
[19e5d65d]368
[116a2ea]369// Thread-local storage is allocated lazily when the storage is accessed.
370static __thread size_t PAD1 CALIGN TLSMODEL __attribute__(( unused )); // protect false sharing
371static __thread Heap * volatile heapManager CALIGN TLSMODEL;
372static __thread size_t PAD2 CALIGN TLSMODEL __attribute__(( unused )); // protect further false sharing
[19e5d65d]373
[31a5f418]374
[116a2ea]375// declare helper functions for HeapMaster
376void noMemory(); // forward, called by "builtin_new" when malloc returns 0
377
378
379void heapMasterCtor() with( heapMaster ) {
380 // Singleton pattern to initialize heap master
381
382 verify( bucketSizes[0] == (16 + sizeof(Heap.Storage)) );
383
384 __page_size = sysconf( _SC_PAGESIZE );
385 __map_prot = PROT_READ | PROT_WRITE | PROT_EXEC;
386
[7a2057a]387 extLock = 0;
388 mgrLock = 0;
[116a2ea]389
390 char * end = (char *)sbrk( 0 );
391 heapBegin = heapEnd = sbrk( (char *)ceiling2( (long unsigned int)end, libAlign() ) - end ); // move start of heap to multiple of alignment
392 heapRemaining = 0;
393 heapExpand = malloc_expansion();
394 mmapStart = malloc_mmap_start();
395
396 // find the closest bucket size less than or equal to the mmapStart size
397 maxBucketsUsed = Bsearchl( mmapStart, bucketSizes, NoBucketSizes ); // binary search
398
399 verify( (mmapStart >= pageSize) && (bucketSizes[NoBucketSizes - 1] >= mmapStart) );
400 verify( maxBucketsUsed < NoBucketSizes ); // subscript failure ?
401 verify( mmapStart <= bucketSizes[maxBucketsUsed] ); // search failure ?
402
403 heapManagersList = 0p;
404 freeHeapManagersList = 0p;
405
406 heapManagersStorage = 0p;
407 heapManagersStorageEnd = 0p;
408
409 #ifdef __STATISTICS__
410 HeapStatisticsCtor( stats ); // clear statistic counters
411 threads_started = threads_exited = 0;
412 reused_heap = new_heap = 0;
413 sbrk_calls = sbrk_storage = 0;
414 stats_fd = STDERR_FILENO;
415 #endif // __STATISTICS__
416
417 #ifdef FASTLOOKUP
418 for ( unsigned int i = 0, idx = 0; i < LookupSizes; i += 1 ) {
419 if ( i > bucketSizes[idx] ) idx += 1;
420 lookup[i] = idx;
421 verify( i <= bucketSizes[idx] );
422 verify( (i <= 32 && idx == 0) || (i > bucketSizes[idx - 1]) );
423 } // for
424 #endif // FASTLOOKUP
425
426 heapMasterBootFlag = true;
427} // heapMasterCtor
428
429
[7671c6d]430#define NO_MEMORY_MSG "**** Error **** insufficient heap memory available to allocate %zd new bytes."
[116a2ea]431
432Heap * getHeap() with( heapMaster ) {
433 Heap * heap;
434 if ( freeHeapManagersList ) { // free heap for reused ?
435 heap = freeHeapManagersList;
436 freeHeapManagersList = heap->nextFreeHeapManager;
437
438 #ifdef __STATISTICS__
439 reused_heap += 1;
440 #endif // __STATISTICS__
441 } else { // free heap not found, create new
442 // Heap size is about 12K, FreeHeader (128 bytes because of cache alignment) * NoBucketSizes (91) => 128 heaps *
443 // 12K ~= 120K byte superblock. Where 128-heap superblock handles a medium sized multi-processor server.
444 size_t remaining = heapManagersStorageEnd - heapManagersStorage; // remaining free heaps in superblock
445 if ( ! heapManagersStorage || remaining != 0 ) {
446 // Each block of heaps is a multiple of the number of cores on the computer.
447 int HeapDim = get_nprocs(); // get_nprocs_conf does not work
448 size_t size = HeapDim * sizeof( Heap );
449
450 heapManagersStorage = (Heap *)mmap( 0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0 );
451 if ( unlikely( heapManagersStorage == (Heap *)MAP_FAILED ) ) { // failed ?
452 if ( errno == ENOMEM ) abort( NO_MEMORY_MSG, size ); // no memory
453 // Do not call strerror( errno ) as it may call malloc.
[7671c6d]454 abort( "**** Error **** attempt to allocate block of heaps of size %zu bytes and mmap failed with errno %d.", size, errno );
[116a2ea]455 } // if
456 heapManagersStorageEnd = &heapManagersStorage[HeapDim]; // outside array
457 } // if
458
459 heap = heapManagersStorage;
460 heapManagersStorage = heapManagersStorage + 1; // bump next heap
461
462 #if defined( __STATISTICS__ ) || defined( __CFA_DEBUG__ )
463 heap->nextHeapManager = heapManagersList;
464 #endif // __STATISTICS__ || __CFA_DEBUG__
465 heapManagersList = heap;
466
467 #ifdef __STATISTICS__
468 new_heap += 1;
469 #endif // __STATISTICS__
470
471 with( *heap ) {
472 for ( unsigned int j = 0; j < NoBucketSizes; j += 1 ) { // initialize free lists
473 #ifdef OWNERSHIP
474 #ifdef RETURNSPIN
[7a2057a]475 freeLists[j].returnLock = 0;
[116a2ea]476 freeLists[j].returnList = 0p;
[7a2057a]477 #endif // RETURNSPIN
[116a2ea]478 #endif // OWNERSHIP
[7a2057a]479
[116a2ea]480 freeLists[j].freeList = 0p;
481 freeLists[j].homeManager = heap;
482 freeLists[j].blockSize = bucketSizes[j];
483 } // for
[88ac843e]484
[116a2ea]485 heapBuffer = 0p;
486 heapReserve = 0;
487 nextFreeHeapManager = 0p;
488 #ifdef __CFA_DEBUG__
489 allocUnfreed = 0;
490 #endif // __CFA_DEBUG__
491 } // with
[433905a]492 } // if
[5951956]493
[116a2ea]494 return heap;
495} // getHeap
496
497
498void heapManagerCtor() libcfa_public {
499 if ( unlikely( ! heapMasterBootFlag ) ) heapMasterCtor();
500
[0bdfcc3]501 lock( heapMaster.mgrLock ); // protect heapMaster counters
[116a2ea]502
503 // get storage for heap manager
504
505 heapManager = getHeap();
506
507 #ifdef __STATISTICS__
508 HeapStatisticsCtor( heapManager->stats ); // heap local
509 heapMaster.threads_started += 1;
510 #endif // __STATISTICS__
511
512 unlock( heapMaster.mgrLock );
513} // heapManagerCtor
514
515
516void heapManagerDtor() libcfa_public {
517 lock( heapMaster.mgrLock );
518
519 // place heap on list of free heaps for reusability
520 heapManager->nextFreeHeapManager = heapMaster.freeHeapManagersList;
521 heapMaster.freeHeapManagersList = heapManager;
522
523 #ifdef __STATISTICS__
524 heapMaster.threads_exited += 1;
525 #endif // __STATISTICS__
526
527 // Do not set heapManager to NULL because it is used after Cforall is shutdown but before the program shuts down.
528
529 unlock( heapMaster.mgrLock );
530} // heapManagerDtor
531
532
533//####################### Memory Allocation Routines Helpers ####################
534
[31a5f418]535
[433905a]536extern int cfa_main_returned; // from interpose.cfa
537extern "C" {
[116a2ea]538 void memory_startup( void ) {
539 if ( ! heapMasterBootFlag ) heapManagerCtor(); // sanity check
540 } // memory_startup
541
542 void memory_shutdown( void ) {
543 heapManagerDtor();
544 } // memory_shutdown
545
[433905a]546 void heapAppStart() { // called by __cfaabi_appready_startup
[116a2ea]547 verify( heapManager );
548 #ifdef __CFA_DEBUG__
549 heapManager->allocUnfreed = 0; // clear prior allocation counts
550 #endif // __CFA_DEBUG__
551
552 #ifdef __STATISTICS__
553 HeapStatisticsCtor( heapManager->stats ); // clear prior statistic counters
554 #endif // __STATISTICS__
[433905a]555 } // heapAppStart
[31a5f418]556
[433905a]557 void heapAppStop() { // called by __cfaabi_appready_startdown
[116a2ea]558 fclose( stdin ); fclose( stdout ); // free buffer storage
559 if ( ! cfa_main_returned ) return; // do not check unfreed storage if exit called
560
561 #ifdef __CFA_DEBUG__
562 // allocUnfreed is set to 0 when a heap is created and it accumulates any unfreed storage during its multiple thread
563 // usages. At the end, add up each heap allocUnfreed value across all heaps to get the total unfreed storage.
[5951956]564 int64_t allocUnfreed = 0;
[116a2ea]565 for ( Heap * heap = heapMaster.heapManagersList; heap; heap = heap->nextHeapManager ) {
566 allocUnfreed += heap->allocUnfreed;
567 } // for
568
569 allocUnfreed -= malloc_unfreed(); // subtract any user specified unfreed storage
570 if ( allocUnfreed > 0 ) {
571 // DO NOT USE STREAMS AS THEY MAY BE UNAVAILABLE AT THIS POINT.
572 char helpText[512];
573 __cfaabi_bits_print_buffer( STDERR_FILENO, helpText, sizeof(helpText),
[80fbdc9]574 "CFA warning (UNIX pid:%ld) : program terminating with %ju(0x%jx) bytes of storage allocated but not freed.\n"
[116a2ea]575 "Possible cause is unfreed storage allocated by the program or system/library routines called from the program.\n",
576 (long int)getpid(), allocUnfreed, allocUnfreed ); // always print the UNIX pid
577 } // if
578 #endif // __CFA_DEBUG__
[433905a]579 } // heapAppStop
580} // extern "C"
[31a5f418]581
582
[433905a]583#ifdef __STATISTICS__
[31a5f418]584static HeapStatistics stats; // zero filled
[c4f68dc]585
[31a5f418]586#define prtFmt \
587 "\nHeap statistics: (storage request / allocation)\n" \
588 " malloc >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \
589 " aalloc >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \
590 " calloc >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \
591 " memalign >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \
592 " amemalign >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \
593 " cmemalign >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \
594 " resize >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \
595 " realloc >0 calls %'u; 0 calls %'u; storage %'llu / %'llu bytes\n" \
596 " free !null calls %'u; null calls %'u; storage %'llu / %'llu bytes\n" \
[116a2ea]597 " return pulls %'u; pushes %'u; storage %'llu / %'llu bytes\n" \
598 " sbrk calls %'u; storage %'llu bytes\n" \
599 " mmap calls %'u; storage %'llu / %'llu bytes\n" \
600 " munmap calls %'u; storage %'llu / %'llu bytes\n" \
601 " threads started %'lu; exited %'lu\n" \
602 " heaps new %'lu; reused %'lu\n"
[31a5f418]603
[c4f68dc]604// Use "write" because streams may be shutdown when calls are made.
[116a2ea]605static int printStats( HeapStatistics & stats ) with( heapMaster, stats ) { // see malloc_stats
[31a5f418]606 char helpText[sizeof(prtFmt) + 1024]; // space for message and values
[116a2ea]607 return __cfaabi_bits_print_buffer( stats_fd, helpText, sizeof(helpText), prtFmt,
608 malloc_calls, malloc_0_calls, malloc_storage_request, malloc_storage_alloc,
609 aalloc_calls, aalloc_0_calls, aalloc_storage_request, aalloc_storage_alloc,
610 calloc_calls, calloc_0_calls, calloc_storage_request, calloc_storage_alloc,
611 memalign_calls, memalign_0_calls, memalign_storage_request, memalign_storage_alloc,
612 amemalign_calls, amemalign_0_calls, amemalign_storage_request, amemalign_storage_alloc,
613 cmemalign_calls, cmemalign_0_calls, cmemalign_storage_request, cmemalign_storage_alloc,
614 resize_calls, resize_0_calls, resize_storage_request, resize_storage_alloc,
615 realloc_calls, realloc_0_calls, realloc_storage_request, realloc_storage_alloc,
616 free_calls, free_null_calls, free_storage_request, free_storage_alloc,
617 return_pulls, return_pushes, return_storage_request, return_storage_alloc,
[31a5f418]618 sbrk_calls, sbrk_storage,
[116a2ea]619 mmap_calls, mmap_storage_request, mmap_storage_alloc,
620 munmap_calls, munmap_storage_request, munmap_storage_alloc,
621 threads_started, threads_exited,
622 new_heap, reused_heap
[c4f68dc]623 );
[d46ed6e]624} // printStats
[c4f68dc]625
[31a5f418]626#define prtFmtXML \
627 "<malloc version=\"1\">\n" \
628 "<heap nr=\"0\">\n" \
629 "<sizes>\n" \
630 "</sizes>\n" \
631 "<total type=\"malloc\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
632 "<total type=\"aalloc\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
633 "<total type=\"calloc\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
634 "<total type=\"memalign\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
635 "<total type=\"amemalign\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
636 "<total type=\"cmemalign\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
637 "<total type=\"resize\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
638 "<total type=\"realloc\" >0 count=\"%'u;\" 0 count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
639 "<total type=\"free\" !null=\"%'u;\" 0 null=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
[116a2ea]640 "<total type=\"return\" pulls=\"%'u;\" 0 pushes=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
[31a5f418]641 "<total type=\"sbrk\" count=\"%'u;\" size=\"%'llu\"/> bytes\n" \
642 "<total type=\"mmap\" count=\"%'u;\" size=\"%'llu / %'llu\" / > bytes\n" \
643 "<total type=\"munmap\" count=\"%'u;\" size=\"%'llu / %'llu\"/> bytes\n" \
[116a2ea]644 "<total type=\"threads\" started=\"%'lu;\" exited=\"%'lu\"/>\n" \
645 "<total type=\"heaps\" new=\"%'lu;\" reused=\"%'lu\"/>\n" \
[31a5f418]646 "</malloc>"
647
[116a2ea]648static int printStatsXML( HeapStatistics & stats, FILE * stream ) with( heapMaster, stats ) { // see malloc_info
[31a5f418]649 char helpText[sizeof(prtFmtXML) + 1024]; // space for message and values
650 return __cfaabi_bits_print_buffer( fileno( stream ), helpText, sizeof(helpText), prtFmtXML,
[116a2ea]651 malloc_calls, malloc_0_calls, malloc_storage_request, malloc_storage_alloc,
652 aalloc_calls, aalloc_0_calls, aalloc_storage_request, aalloc_storage_alloc,
653 calloc_calls, calloc_0_calls, calloc_storage_request, calloc_storage_alloc,
654 memalign_calls, memalign_0_calls, memalign_storage_request, memalign_storage_alloc,
655 amemalign_calls, amemalign_0_calls, amemalign_storage_request, amemalign_storage_alloc,
656 cmemalign_calls, cmemalign_0_calls, cmemalign_storage_request, cmemalign_storage_alloc,
657 resize_calls, resize_0_calls, resize_storage_request, resize_storage_alloc,
658 realloc_calls, realloc_0_calls, realloc_storage_request, realloc_storage_alloc,
659 free_calls, free_null_calls, free_storage_request, free_storage_alloc,
660 return_pulls, return_pushes, return_storage_request, return_storage_alloc,
[31a5f418]661 sbrk_calls, sbrk_storage,
[116a2ea]662 mmap_calls, mmap_storage_request, mmap_storage_alloc,
663 munmap_calls, munmap_storage_request, munmap_storage_alloc,
664 threads_started, threads_exited,
665 new_heap, reused_heap
[c4f68dc]666 );
[d46ed6e]667} // printStatsXML
[95eb7cf]668
[116a2ea]669static HeapStatistics & collectStats( HeapStatistics & stats ) with( heapMaster ) {
670 lock( mgrLock );
[433905a]671
[116a2ea]672 stats += heapMaster.stats;
673 for ( Heap * heap = heapManagersList; heap; heap = heap->nextHeapManager ) {
674 stats += heap->stats;
675 } // for
[433905a]676
[116a2ea]677 unlock( mgrLock );
678 return stats;
679} // collectStats
680#endif // __STATISTICS__
[1e034d9]681
682
[116a2ea]683static bool setMmapStart( size_t value ) with( heapMaster ) { // true => mmapped, false => sbrk
[ad2dced]684 if ( value < __page_size || bucketSizes[NoBucketSizes - 1] < value ) return false;
[95eb7cf]685 mmapStart = value; // set global
686
687 // find the closest bucket size less than or equal to the mmapStart size
[116a2ea]688 maxBucketsUsed = Bsearchl( mmapStart, bucketSizes, NoBucketSizes ); // binary search
[7a2057a]689
[116a2ea]690 verify( maxBucketsUsed < NoBucketSizes ); // subscript failure ?
691 verify( mmapStart <= bucketSizes[maxBucketsUsed] ); // search failure ?
[1076d05]692 return true;
[95eb7cf]693} // setMmapStart
694
695
[cfbc703d]696// <-------+----------------------------------------------------> bsize (bucket size)
697// |header |addr
698//==================================================================================
699// align/offset |
700// <-----------------<------------+-----------------------------> bsize (bucket size)
701// |fake-header | addr
[19e5d65d]702#define HeaderAddr( addr ) ((Heap.Storage.Header *)( (char *)addr - sizeof(Heap.Storage) ))
703#define RealHeader( header ) ((Heap.Storage.Header *)((char *)header - header->kind.fake.offset))
[cfbc703d]704
705// <-------<<--------------------- dsize ---------------------->> bsize (bucket size)
706// |header |addr
707//==================================================================================
708// align/offset |
709// <------------------------------<<---------- dsize --------->>> bsize (bucket size)
710// |fake-header |addr
[19e5d65d]711#define DataStorage( bsize, addr, header ) (bsize - ( (char *)addr - (char *)header ))
[cfbc703d]712
713
[116a2ea]714inline __attribute__((always_inline))
715static void checkAlign( size_t alignment ) {
[19e5d65d]716 if ( unlikely( alignment < libAlign() || ! is_pow2( alignment ) ) ) {
717 abort( "**** Error **** alignment %zu for memory allocation is less than %d and/or not a power of 2.", alignment, libAlign() );
[cfbc703d]718 } // if
719} // checkAlign
720
721
[116a2ea]722inline __attribute__((always_inline))
723static void checkHeader( bool check, const char name[], void * addr ) {
[b6830d74]724 if ( unlikely( check ) ) { // bad address ?
[19e5d65d]725 abort( "**** Error **** attempt to %s storage %p with address outside the heap.\n"
[bcb14b5]726 "Possible cause is duplicate free on same block or overwriting of memory.",
727 name, addr );
[b6830d74]728 } // if
[c4f68dc]729} // checkHeader
730
[95eb7cf]731
[19e5d65d]732// Manipulate sticky bits stored in unused 3 low-order bits of an address.
733// bit0 => alignment => fake header
734// bit1 => zero filled (calloc)
735// bit2 => mapped allocation versus sbrk
736#define StickyBits( header ) (((header)->kind.real.blockSize & 0x7))
737#define ClearStickyBits( addr ) (typeof(addr))((uintptr_t)(addr) & ~7)
738#define MarkAlignmentBit( align ) ((align) | 1)
739#define AlignmentBit( header ) ((((header)->kind.fake.alignment) & 1))
740#define ClearAlignmentBit( header ) (((header)->kind.fake.alignment) & ~1)
741#define ZeroFillBit( header ) ((((header)->kind.real.blockSize) & 2))
742#define ClearZeroFillBit( header ) ((((header)->kind.real.blockSize) &= ~2))
743#define MarkZeroFilledBit( header ) ((header)->kind.real.blockSize |= 2)
744#define MmappedBit( header ) ((((header)->kind.real.blockSize) & 4))
745#define MarkMmappedBit( size ) ((size) | 4)
746
747
[116a2ea]748inline __attribute__((always_inline))
749static void fakeHeader( Heap.Storage.Header *& header, size_t & alignment ) {
[19e5d65d]750 if ( unlikely( AlignmentBit( header ) ) ) { // fake header ?
751 alignment = ClearAlignmentBit( header ); // clear flag from value
[c4f68dc]752 #ifdef __CFA_DEBUG__
753 checkAlign( alignment ); // check alignment
754 #endif // __CFA_DEBUG__
[19e5d65d]755 header = RealHeader( header ); // backup from fake to real header
[d5d3a90]756 } else {
[c1f38e6c]757 alignment = libAlign(); // => no fake header
[b6830d74]758 } // if
[c4f68dc]759} // fakeHeader
760
[95eb7cf]761
[116a2ea]762inline __attribute__((always_inline))
763static bool headers( const char name[] __attribute__(( unused )), void * addr, Heap.Storage.Header *& header,
764 Heap.FreeHeader *& freeHead, size_t & size, size_t & alignment ) with( heapMaster, *heapManager ) {
[19e5d65d]765 header = HeaderAddr( addr );
[c4f68dc]766
767 #ifdef __CFA_DEBUG__
[31a5f418]768 checkHeader( header < (Heap.Storage.Header *)heapBegin, name, addr ); // bad low address ?
[c4f68dc]769 #endif // __CFA_DEBUG__
[b6830d74]770
[19e5d65d]771 if ( likely( ! StickyBits( header ) ) ) { // no sticky bits ?
772 freeHead = (Heap.FreeHeader *)(header->kind.real.home);
773 alignment = libAlign();
774 } else {
775 fakeHeader( header, alignment );
[433905a]776 if ( unlikely( MmappedBit( header ) ) ) { // mmapped ?
777 verify( addr < heapBegin || heapEnd < addr );
[19e5d65d]778 size = ClearStickyBits( header->kind.real.blockSize ); // mmap size
779 return true;
780 } // if
781
782 freeHead = (Heap.FreeHeader *)(ClearStickyBits( header->kind.real.home ));
783 } // if
784 size = freeHead->blockSize;
785
[c4f68dc]786 #ifdef __CFA_DEBUG__
[31a5f418]787 checkHeader( header < (Heap.Storage.Header *)heapBegin || (Heap.Storage.Header *)heapEnd < header, name, addr ); // bad address ? (offset could be + or -)
[c4f68dc]788
[116a2ea]789 Heap * homeManager;
[433905a]790 if ( unlikely( freeHead == 0p || // freed and only free-list node => null link
791 // freed and link points at another free block not to a bucket in the bucket array.
[116a2ea]792 (homeManager = freeHead->homeManager, freeHead < &homeManager->freeLists[0] ||
793 &homeManager->freeLists[NoBucketSizes] <= freeHead ) ) ) {
[433905a]794 abort( "**** Error **** attempt to %s storage %p with corrupted header.\n"
795 "Possible cause is duplicate free on same block or overwriting of header information.",
796 name, addr );
797 } // if
[c4f68dc]798 #endif // __CFA_DEBUG__
[19e5d65d]799
[bcb14b5]800 return false;
[c4f68dc]801} // headers
802
803
[116a2ea]804static void * master_extend( size_t size ) with( heapMaster ) {
805 lock( extLock );
[19e5d65d]806
[b6830d74]807 ptrdiff_t rem = heapRemaining - size;
[19e5d65d]808 if ( unlikely( rem < 0 ) ) {
[c4f68dc]809 // If the size requested is bigger than the current remaining storage, increase the size of the heap.
810
[116a2ea]811 size_t increase = ceiling2( size > heapExpand ? size : heapExpand, libAlign() );
812 if ( unlikely( sbrk( increase ) == (void *)-1 ) ) { // failed, no memory ?
813 unlock( extLock );
[0bdfcc3]814 abort( NO_MEMORY_MSG, size ); // give up
[92aca37]815 } // if
[7671c6d]816
817 // Make storage executable for thunks.
818 if ( mprotect( (char *)heapEnd + heapRemaining, increase, __map_prot ) ) {
819 unlock( extLock );
820 abort( "**** Error **** attempt to make heap storage executable for thunks and mprotect failed with errno %d.", errno );
821 } // if
822
[116a2ea]823 rem = heapRemaining + increase - size;
[19e5d65d]824
[bcb14b5]825 #ifdef __STATISTICS__
[c4f68dc]826 sbrk_calls += 1;
827 sbrk_storage += increase;
[bcb14b5]828 #endif // __STATISTICS__
[b6830d74]829 } // if
[c4f68dc]830
[31a5f418]831 Heap.Storage * block = (Heap.Storage *)heapEnd;
[b6830d74]832 heapRemaining = rem;
833 heapEnd = (char *)heapEnd + size;
[116a2ea]834
835 unlock( extLock );
836 return block;
837} // master_extend
838
839
840__attribute__(( noinline ))
841static void * manager_extend( size_t size ) with( *heapManager ) {
842 ptrdiff_t rem = heapReserve - size;
843
844 if ( unlikely( rem < 0 ) ) { // negative
845 // If the size requested is bigger than the current remaining reserve, use the current reserve to populate
846 // smaller freeLists, and increase the reserve.
847
848 rem = heapReserve; // positive
849
850 if ( rem >= bucketSizes[0] ) { // minimal size ? otherwise ignore
851 size_t bucket;
852 #ifdef FASTLOOKUP
853 if ( likely( rem < LookupSizes ) ) bucket = lookup[rem];
854 #endif // FASTLOOKUP
855 bucket = Bsearchl( rem, bucketSizes, heapMaster.maxBucketsUsed );
856 verify( 0 <= bucket && bucket <= heapMaster.maxBucketsUsed );
857 Heap.FreeHeader * freeHead = &(freeLists[bucket]);
858
859 // The remaining storage many not be bucket size, whereas all other allocations are. Round down to previous
860 // bucket size in this case.
861 if ( unlikely( freeHead->blockSize > (size_t)rem ) ) freeHead -= 1;
862 Heap.Storage * block = (Heap.Storage *)heapBuffer;
863
864 block->header.kind.real.next = freeHead->freeList; // push on stack
865 freeHead->freeList = block;
866 } // if
867
868 size_t increase = ceiling( size > ( heapMaster.heapExpand / 10 ) ? size : ( heapMaster.heapExpand / 10 ), libAlign() );
869 heapBuffer = master_extend( increase );
870 rem = increase - size;
871 } // if
872
873 Heap.Storage * block = (Heap.Storage *)heapBuffer;
874 heapReserve = rem;
875 heapBuffer = (char *)heapBuffer + size;
876
[b6830d74]877 return block;
[116a2ea]878} // manager_extend
879
880
881#define BOOT_HEAP_MANAGER \
882 if ( unlikely( ! heapMasterBootFlag ) ) { \
883 heapManagerCtor(); /* trigger for first heap */ \
884 } /* if */
885
886#ifdef __STATISTICS__
887#define STAT_NAME __counter
888#define STAT_PARM , unsigned int STAT_NAME
889#define STAT_ARG( name ) , name
890#define STAT_0_CNT( counter ) stats.counters[counter].calls_0 += 1
891#else
892#define STAT_NAME
893#define STAT_PARM
894#define STAT_ARG( name )
895#define STAT_0_CNT( counter )
896#endif // __STATISTICS__
897
898#define PROLOG( counter, ... ) \
899 BOOT_HEAP_MANAGER; \
900 if ( unlikely( size == 0 ) || /* 0 BYTE ALLOCATION RETURNS NULL POINTER */ \
901 unlikely( size > ULONG_MAX - sizeof(Heap.Storage) ) ) { /* error check */ \
902 STAT_0_CNT( counter ); \
903 __VA_ARGS__; \
904 return 0p; \
905 } /* if */
906
[c4f68dc]907
[116a2ea]908#define SCRUB_SIZE 1024lu
909// Do not use '\xfe' for scrubbing because dereferencing an address composed of it causes a SIGSEGV *without* a valid IP
910// pointer in the interrupt frame.
911#define SCRUB '\xff'
[c4f68dc]912
[116a2ea]913static void * doMalloc( size_t size STAT_PARM ) libcfa_nopreempt with( *heapManager ) {
914 PROLOG( STAT_NAME );
915
916 verify( heapManager );
917 Heap.Storage * block; // pointer to new block of storage
[c4f68dc]918
[b6830d74]919 // Look up size in the size list. Make sure the user request includes space for the header that must be allocated
920 // along with the block and is a multiple of the alignment size.
[31a5f418]921 size_t tsize = size + sizeof(Heap.Storage);
[19e5d65d]922
[116a2ea]923 #ifdef __STATISTICS__
924 stats.counters[STAT_NAME].calls += 1;
925 stats.counters[STAT_NAME].request += size;
926 #endif // __STATISTICS__
927
928 #ifdef __CFA_DEBUG__
929 allocUnfreed += size;
930 #endif // __CFA_DEBUG__
931
932 if ( likely( tsize < heapMaster.mmapStart ) ) { // small size => sbrk
933 size_t bucket;
[e723100]934 #ifdef FASTLOOKUP
[116a2ea]935 if ( likely( tsize < LookupSizes ) ) bucket = lookup[tsize];
[e723100]936 else
937 #endif // FASTLOOKUP
[116a2ea]938 bucket = Bsearchl( tsize, bucketSizes, heapMaster.maxBucketsUsed );
939 verify( 0 <= bucket && bucket <= heapMaster.maxBucketsUsed );
940 Heap.FreeHeader * freeHead = &freeLists[bucket];
941
942 verify( freeHead <= &freeLists[heapMaster.maxBucketsUsed] ); // subscripting error ?
943 verify( tsize <= freeHead->blockSize ); // search failure ?
944
945 tsize = freeHead->blockSize; // total space needed for request
946 #ifdef __STATISTICS__
947 stats.counters[STAT_NAME].alloc += tsize;
948 #endif // __STATISTICS__
[c4f68dc]949
[116a2ea]950 block = freeHead->freeList; // remove node from stack
[95eb7cf]951 if ( unlikely( block == 0p ) ) { // no free block ?
[7a2057a]952 // Freelist for this size is empty, so check return list (OWNERSHIP), carve it out of the heap, if there
953 // is enough left, or get some more heap storage and carve it off.
[116a2ea]954 #ifdef OWNERSHIP
[7a2057a]955 if ( unlikely( freeHead->returnList ) ) { // race, get next time if lose race
956 #ifdef RETURNSPIN
957 lock( freeHead->returnLock );
958 block = freeHead->returnList;
959 freeHead->returnList = 0p;
960 unlock( freeHead->returnLock );
961 #else
962 block = __atomic_exchange_n( &freeHead->returnList, 0p, __ATOMIC_SEQ_CST );
963 #endif // RETURNSPIN
964
965 verify( block );
966 #ifdef __STATISTICS__
967 stats.return_pulls += 1;
968 #endif // __STATISTICS__
969
970 // OK TO BE PREEMPTED HERE AS heapManager IS NO LONGER ACCESSED.
[116a2ea]971
[7a2057a]972 freeHead->freeList = block->header.kind.real.next; // merge returnList into freeHead
973 } else {
[116a2ea]974 #endif // OWNERSHIP
975 // Do not leave kernel thread as manager_extend accesses heapManager.
976 disable_interrupts();
977 block = (Heap.Storage *)manager_extend( tsize ); // mutual exclusion on call
978 enable_interrupts( false );
979
980 // OK TO BE PREEMPTED HERE AS heapManager IS NO LONGER ACCESSED.
981
982 #ifdef __CFA_DEBUG__
[7a2057a]983 // Scrub new memory so subsequent uninitialized usages might fail. Only scrub the first SCRUB_SIZE bytes.
[116a2ea]984 memset( block->data, SCRUB, min( SCRUB_SIZE, tsize - sizeof(Heap.Storage) ) );
985 #endif // __CFA_DEBUG__
986 #ifdef OWNERSHIP
987 } // if
988 #endif // OWNERSHIP
[c4f68dc]989 } else {
[116a2ea]990 // Memory is scrubbed in doFree.
991 freeHead->freeList = block->header.kind.real.next;
[c4f68dc]992 } // if
993
[116a2ea]994 block->header.kind.real.home = freeHead; // pointer back to free list of apropriate size
[bcb14b5]995 } else { // large size => mmap
[ad2dced]996 if ( unlikely( size > ULONG_MAX - __page_size ) ) return 0p;
997 tsize = ceiling2( tsize, __page_size ); // must be multiple of page size
[7a2057a]998
[c4f68dc]999 #ifdef __STATISTICS__
[116a2ea]1000 stats.counters[STAT_NAME].alloc += tsize;
1001 stats.mmap_calls += 1;
1002 stats.mmap_storage_request += size;
1003 stats.mmap_storage_alloc += tsize;
[c4f68dc]1004 #endif // __STATISTICS__
[92aca37]1005
[116a2ea]1006 disable_interrupts();
1007 block = (Heap.Storage *)mmap( 0, tsize, __map_prot, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0 );
1008 enable_interrupts( false );
1009
1010 // OK TO BE PREEMPTED HERE AS heapManager IS NO LONGER ACCESSED.
1011
1012 if ( unlikely( block == (Heap.Storage *)MAP_FAILED ) ) { // failed ?
[92aca37]1013 if ( errno == ENOMEM ) abort( NO_MEMORY_MSG, tsize ); // no memory
[c4f68dc]1014 // Do not call strerror( errno ) as it may call malloc.
[7a2057a]1015 abort( "**** Error **** attempt to allocate large object (> %zu) of size %zu bytes and mmap failed with errno %d.",
1016 size, heapMaster.mmapStart, errno );
[116a2ea]1017 } // if
1018 block->header.kind.real.blockSize = MarkMmappedBit( tsize ); // storage size for munmap
1019
[bcb14b5]1020 #ifdef __CFA_DEBUG__
[7a2057a]1021 // Scrub new memory so subsequent uninitialized usages might fail. Only scrub the first SCRUB_SIZE bytes. The
1022 // rest of the storage set to 0 by mmap.
[116a2ea]1023 memset( block->data, SCRUB, min( SCRUB_SIZE, tsize - sizeof(Heap.Storage) ) );
[bcb14b5]1024 #endif // __CFA_DEBUG__
1025 } // if
[c4f68dc]1026
[9c438546]1027 block->header.kind.real.size = size; // store allocation size
[95eb7cf]1028 void * addr = &(block->data); // adjust off header to user bytes
[c1f38e6c]1029 verify( ((uintptr_t)addr & (libAlign() - 1)) == 0 ); // minimum alignment ?
[c4f68dc]1030
1031 #ifdef __CFA_DEBUG__
[bcb14b5]1032 if ( traceHeap() ) {
[433905a]1033 char helpText[64];
1034 __cfaabi_bits_print_buffer( STDERR_FILENO, helpText, sizeof(helpText),
1035 "%p = Malloc( %zu ) (allocated %zu)\n", addr, size, tsize ); // print debug/nodebug
[bcb14b5]1036 } // if
[c4f68dc]1037 #endif // __CFA_DEBUG__
1038
[116a2ea]1039// poll_interrupts(); // call rollforward
1040
[95eb7cf]1041 return addr;
[c4f68dc]1042} // doMalloc
1043
1044
[116a2ea]1045static void doFree( void * addr ) libcfa_nopreempt with( *heapManager ) {
1046 verify( addr );
1047
1048 // detect free after thread-local storage destruction and use global stats in that case
[c4f68dc]1049
[31a5f418]1050 Heap.Storage.Header * header;
[116a2ea]1051 Heap.FreeHeader * freeHead;
1052 size_t size, alignment;
1053
1054 bool mapped = headers( "free", addr, header, freeHead, size, alignment );
1055 #if defined( __STATISTICS__ ) || defined( __CFA_DEBUG__ )
1056 size_t rsize = header->kind.real.size; // optimization
1057 #endif // __STATISTICS__ || __CFA_DEBUG__
1058
1059 #ifdef __STATISTICS__
1060 stats.free_storage_request += rsize;
1061 stats.free_storage_alloc += size;
1062 #endif // __STATISTICS__
1063
1064 #ifdef __CFA_DEBUG__
1065 allocUnfreed -= rsize;
1066 #endif // __CFA_DEBUG__
[c4f68dc]1067
[116a2ea]1068 if ( unlikely( mapped ) ) { // mmapped ?
[c4f68dc]1069 #ifdef __STATISTICS__
[116a2ea]1070 stats.munmap_calls += 1;
1071 stats.munmap_storage_request += rsize;
1072 stats.munmap_storage_alloc += size;
[c4f68dc]1073 #endif // __STATISTICS__
[116a2ea]1074
1075 // OK TO BE PREEMPTED HERE AS heapManager IS NO LONGER ACCESSED.
1076
1077 // Does not matter where this storage is freed.
1078 if ( unlikely( munmap( header, size ) == -1 ) ) {
1079 // Do not call strerror( errno ) as it may call malloc.
[5951956]1080 abort( "**** Error **** attempt to deallocate large object %p and munmap failed with errno %d.\n"
[116a2ea]1081 "Possible cause is invalid delete pointer: either not allocated or with corrupt header.",
1082 addr, errno );
[c4f68dc]1083 } // if
[bcb14b5]1084 } else {
[c4f68dc]1085 #ifdef __CFA_DEBUG__
[116a2ea]1086 // memset is NOT always inlined!
1087 disable_interrupts();
1088 // Scrub old memory so subsequent usages might fail. Only scrub the first/last SCRUB_SIZE bytes.
1089 char * data = ((Heap.Storage *)header)->data; // data address
1090 size_t dsize = size - sizeof(Heap.Storage); // data size
1091 if ( dsize <= SCRUB_SIZE * 2 ) {
1092 memset( data, SCRUB, dsize ); // scrub all
1093 } else {
1094 memset( data, SCRUB, SCRUB_SIZE ); // scrub front
1095 memset( data + dsize - SCRUB_SIZE, SCRUB, SCRUB_SIZE ); // scrub back
1096 } // if
1097 enable_interrupts( false );
[c4f68dc]1098 #endif // __CFA_DEBUG__
1099
[7a2057a]1100 #ifdef OWNERSHIP
[116a2ea]1101 if ( likely( heapManager == freeHead->homeManager ) ) { // belongs to this thread
1102 header->kind.real.next = freeHead->freeList; // push on stack
1103 freeHead->freeList = (Heap.Storage *)header;
1104 } else { // return to thread owner
1105 verify( heapManager );
1106
1107 #ifdef RETURNSPIN
1108 lock( freeHead->returnLock );
1109 header->kind.real.next = freeHead->returnList; // push to bucket return list
1110 freeHead->returnList = (Heap.Storage *)header;
1111 unlock( freeHead->returnLock );
1112 #else // lock free
1113 header->kind.real.next = freeHead->returnList; // link new node to top node
1114 // CAS resets header->kind.real.next = freeHead->returnList on failure
[7a2057a]1115 while ( ! __atomic_compare_exchange_n( &freeHead->returnList, &header->kind.real.next, (Heap.Storage *)header,
[116a2ea]1116 false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST ) );
1117 #endif // RETURNSPIN
[7a2057a]1118 } // if
[116a2ea]1119
[7a2057a]1120 #else // no OWNERSHIP
[116a2ea]1121
[7a2057a]1122 // kind.real.home is address in owner thread's freeLists, so compute the equivalent position in this thread's freeList.
1123 freeHead = &freeLists[ClearStickyBits( (Heap.FreeHeader *)(header->kind.real.home) ) - &freeHead->homeManager->freeLists[0]];
1124 header->kind.real.next = freeHead->freeList; // push on stack
1125 freeHead->freeList = (Heap.Storage *)header;
1126 #endif // ! OWNERSHIP
[116a2ea]1127
[7a2057a]1128 #ifdef __U_STATISTICS__
1129 stats.return_pushes += 1;
1130 stats.return_storage_request += rsize;
1131 stats.return_storage_alloc += size;
1132 #endif // __U_STATISTICS__
[116a2ea]1133
[7a2057a]1134 // OK TO BE PREEMPTED HERE AS heapManager IS NO LONGER ACCESSED.
[bcb14b5]1135 } // if
[c4f68dc]1136
1137 #ifdef __CFA_DEBUG__
[bcb14b5]1138 if ( traceHeap() ) {
[92aca37]1139 char helpText[64];
[433905a]1140 __cfaabi_bits_print_buffer( STDERR_FILENO, helpText, sizeof(helpText),
1141 "Free( %p ) size:%zu\n", addr, size ); // print debug/nodebug
[bcb14b5]1142 } // if
[c4f68dc]1143 #endif // __CFA_DEBUG__
[116a2ea]1144
1145// poll_interrupts(); // call rollforward
[c4f68dc]1146} // doFree
1147
1148
[116a2ea]1149size_t prtFree( Heap & manager ) with( manager ) {
[b6830d74]1150 size_t total = 0;
[c4f68dc]1151 #ifdef __STATISTICS__
[95eb7cf]1152 __cfaabi_bits_acquire();
1153 __cfaabi_bits_print_nolock( STDERR_FILENO, "\nBin lists (bin size : free blocks on list)\n" );
[c4f68dc]1154 #endif // __STATISTICS__
[116a2ea]1155 for ( unsigned int i = 0; i < heapMaster.maxBucketsUsed; i += 1 ) {
[d46ed6e]1156 size_t size = freeLists[i].blockSize;
1157 #ifdef __STATISTICS__
1158 unsigned int N = 0;
1159 #endif // __STATISTICS__
[b6830d74]1160
[31a5f418]1161 for ( Heap.Storage * p = freeLists[i].freeList; p != 0p; p = p->header.kind.real.next ) {
[d46ed6e]1162 total += size;
1163 #ifdef __STATISTICS__
1164 N += 1;
1165 #endif // __STATISTICS__
[b6830d74]1166 } // for
1167
[d46ed6e]1168 #ifdef __STATISTICS__
[95eb7cf]1169 __cfaabi_bits_print_nolock( STDERR_FILENO, "%7zu, %-7u ", size, N );
1170 if ( (i + 1) % 8 == 0 ) __cfaabi_bits_print_nolock( STDERR_FILENO, "\n" );
[d46ed6e]1171 #endif // __STATISTICS__
1172 } // for
1173 #ifdef __STATISTICS__
[95eb7cf]1174 __cfaabi_bits_print_nolock( STDERR_FILENO, "\ntotal free blocks:%zu\n", total );
1175 __cfaabi_bits_release();
[d46ed6e]1176 #endif // __STATISTICS__
[116a2ea]1177 return (char *)heapMaster.heapEnd - (char *)heapMaster.heapBegin - total;
[95eb7cf]1178} // prtFree
1179
1180
[116a2ea]1181#ifdef __STATISTICS__
[5951956]1182static void incCalls( intptr_t statName ) libcfa_nopreempt {
[116a2ea]1183 heapManager->stats.counters[statName].calls += 1;
1184} // incCalls
[d5d3a90]1185
[5951956]1186static void incZeroCalls( intptr_t statName ) libcfa_nopreempt {
[116a2ea]1187 heapManager->stats.counters[statName].calls_0 += 1;
1188} // incZeroCalls
1189#endif // __STATISTICS__
[c4f68dc]1190
[116a2ea]1191#ifdef __CFA_DEBUG__
[5951956]1192static void incUnfreed( intptr_t offset ) libcfa_nopreempt {
[116a2ea]1193 heapManager->allocUnfreed += offset;
1194} // incUnfreed
1195#endif // __CFA_DEBUG__
[c4f68dc]1196
[d5d3a90]1197
[116a2ea]1198static void * memalignNoStats( size_t alignment, size_t size STAT_PARM ) {
[b6830d74]1199 checkAlign( alignment ); // check alignment
[c4f68dc]1200
[116a2ea]1201 // if alignment <= default alignment or size == 0, do normal malloc as two headers are unnecessary
1202 if ( unlikely( alignment <= libAlign() || size == 0 ) ) return doMalloc( size STAT_ARG( STAT_NAME ) );
[b6830d74]1203
1204 // Allocate enough storage to guarantee an address on the alignment boundary, and sufficient space before it for
1205 // administrative storage. NOTE, WHILE THERE ARE 2 HEADERS, THE FIRST ONE IS IMPLICITLY CREATED BY DOMALLOC.
1206 // .-------------v-----------------v----------------v----------,
1207 // | Real Header | ... padding ... | Fake Header | data ... |
1208 // `-------------^-----------------^-+--------------^----------'
1209 // |<--------------------------------' offset/align |<-- alignment boundary
1210
1211 // subtract libAlign() because it is already the minimum alignment
1212 // add sizeof(Storage) for fake header
[116a2ea]1213 size_t offset = alignment - libAlign() + sizeof(Heap.Storage);
1214 char * addr = (char *)doMalloc( size + offset STAT_ARG( STAT_NAME ) );
[b6830d74]1215
1216 // address in the block of the "next" alignment address
[31a5f418]1217 char * user = (char *)ceiling2( (uintptr_t)(addr + sizeof(Heap.Storage)), alignment );
[b6830d74]1218
1219 // address of header from malloc
[116a2ea]1220 Heap.Storage.Header * realHeader = HeaderAddr( addr );
1221 realHeader->kind.real.size = size; // correct size to eliminate above alignment offset
1222 #ifdef __CFA_DEBUG__
1223 incUnfreed( -offset ); // adjustment off the offset from call to doMalloc
1224 #endif // __CFA_DEBUG__
1225
1226 // address of fake header *before* the alignment location
[19e5d65d]1227 Heap.Storage.Header * fakeHeader = HeaderAddr( user );
[116a2ea]1228
[b6830d74]1229 // SKULLDUGGERY: insert the offset to the start of the actual storage block and remember alignment
[116a2ea]1230 fakeHeader->kind.fake.offset = (char *)fakeHeader - (char *)realHeader;
[69ec0fb]1231 // SKULLDUGGERY: odd alignment implies fake header
[19e5d65d]1232 fakeHeader->kind.fake.alignment = MarkAlignmentBit( alignment );
[b6830d74]1233
1234 return user;
[bcb14b5]1235} // memalignNoStats
[c4f68dc]1236
1237
[19e5d65d]1238//####################### Memory Allocation Routines ####################
1239
1240
[c4f68dc]1241extern "C" {
[61248a4]1242 // Allocates size bytes and returns a pointer to the allocated memory. The contents are undefined. If size is 0,
1243 // then malloc() returns a unique pointer value that can later be successfully passed to free().
[032234bd]1244 void * malloc( size_t size ) libcfa_public {
[116a2ea]1245 return doMalloc( size STAT_ARG( MALLOC ) );
[bcb14b5]1246 } // malloc
[c4f68dc]1247
[76e2113]1248
[61248a4]1249 // Same as malloc() except size bytes is an array of dim elements each of elemSize bytes.
[032234bd]1250 void * aalloc( size_t dim, size_t elemSize ) libcfa_public {
[116a2ea]1251 return doMalloc( dim * elemSize STAT_ARG( AALLOC ) );
[76e2113]1252 } // aalloc
1253
1254
[61248a4]1255 // Same as aalloc() with memory set to zero.
[032234bd]1256 void * calloc( size_t dim, size_t elemSize ) libcfa_public {
[709b812]1257 size_t size = dim * elemSize;
[116a2ea]1258 char * addr = (char *)doMalloc( size STAT_ARG( CALLOC ) );
[c4f68dc]1259
[116a2ea]1260 if ( unlikely( addr == NULL ) ) return NULL; // stop further processing if 0p is returned
[709b812]1261
[31a5f418]1262 Heap.Storage.Header * header;
[116a2ea]1263 Heap.FreeHeader * freeHead;
[709b812]1264 size_t bsize, alignment;
1265
1266 #ifndef __CFA_DEBUG__
1267 bool mapped =
1268 #endif // __CFA_DEBUG__
[116a2ea]1269 headers( "calloc", addr, header, freeHead, bsize, alignment );
[709b812]1270
1271 #ifndef __CFA_DEBUG__
1272 // Mapped storage is zero filled, but in debug mode mapped memory is scrubbed in doMalloc, so it has to be reset to zero.
[116a2ea]1273 if ( likely( ! mapped ) )
[709b812]1274 #endif // __CFA_DEBUG__
1275 // <-------0000000000000000000000000000UUUUUUUUUUUUUUUUUUUUUUUUU> bsize (bucket size) U => undefined
1276 // `-header`-addr `-size
1277 memset( addr, '\0', size ); // set to zeros
1278
[19e5d65d]1279 MarkZeroFilledBit( header ); // mark as zero fill
[709b812]1280 return addr;
[bcb14b5]1281 } // calloc
[c4f68dc]1282
[92aca37]1283
[61248a4]1284 // Change the size of the memory block pointed to by oaddr to size bytes. The contents are undefined. If oaddr is
1285 // 0p, then the call is equivalent to malloc(size), for all values of size; if size is equal to zero, and oaddr is
1286 // not 0p, then the call is equivalent to free(oaddr). Unless oaddr is 0p, it must have been returned by an earlier
1287 // call to malloc(), alloc(), calloc() or realloc(). If the area pointed to was moved, a free(oaddr) is done.
[032234bd]1288 void * resize( void * oaddr, size_t size ) libcfa_public {
[116a2ea]1289 if ( unlikely( oaddr == 0p ) ) { // => malloc( size )
1290 return doMalloc( size STAT_ARG( RESIZE ) );
[709b812]1291 } // if
[cfbc703d]1292
[116a2ea]1293 PROLOG( RESIZE, doFree( oaddr ) ); // => free( oaddr )
[cfbc703d]1294
[31a5f418]1295 Heap.Storage.Header * header;
[116a2ea]1296 Heap.FreeHeader * freeHead;
[92aca37]1297 size_t bsize, oalign;
[116a2ea]1298 headers( "resize", oaddr, header, freeHead, bsize, oalign );
[92847f7]1299
[19e5d65d]1300 size_t odsize = DataStorage( bsize, oaddr, header ); // data storage available in bucket
[cfbc703d]1301 // same size, DO NOT preserve STICKY PROPERTIES.
[92847f7]1302 if ( oalign == libAlign() && size <= odsize && odsize <= size * 2 ) { // allow 50% wasted storage for smaller size
[19e5d65d]1303 ClearZeroFillBit( header ); // no alignment and turn off 0 fill
[116a2ea]1304 #ifdef __CFA_DEBUG__
1305 incUnfreed( size - header->kind.real.size ); // adjustment off the size difference
1306 #endif // __CFA_DEBUG__
[d5d3a90]1307 header->kind.real.size = size; // reset allocation size
[116a2ea]1308 #ifdef __STATISTICS__
1309 incCalls( RESIZE );
1310 #endif // __STATISTICS__
[cfbc703d]1311 return oaddr;
1312 } // if
[0f89d4f]1313
[cfbc703d]1314 // change size, DO NOT preserve STICKY PROPERTIES.
[116a2ea]1315 doFree( oaddr ); // free previous storage
1316
1317 return doMalloc( size STAT_ARG( RESIZE ) ); // create new area
[cfbc703d]1318 } // resize
1319
1320
[61248a4]1321 // Same as resize() but the contents are unchanged in the range from the start of the region up to the minimum of
[cfbc703d]1322 // the old and new sizes.
[032234bd]1323 void * realloc( void * oaddr, size_t size ) libcfa_public {
[116a2ea]1324 if ( unlikely( oaddr == 0p ) ) { // => malloc( size )
1325 return doMalloc( size STAT_ARG( REALLOC ) );
[709b812]1326 } // if
[c4f68dc]1327
[116a2ea]1328 PROLOG( REALLOC, doFree( oaddr ) ); // => free( oaddr )
[c4f68dc]1329
[31a5f418]1330 Heap.Storage.Header * header;
[116a2ea]1331 Heap.FreeHeader * freeHead;
[92aca37]1332 size_t bsize, oalign;
[116a2ea]1333 headers( "realloc", oaddr, header, freeHead, bsize, oalign );
[95eb7cf]1334
[19e5d65d]1335 size_t odsize = DataStorage( bsize, oaddr, header ); // data storage available in bucket
[d5d3a90]1336 size_t osize = header->kind.real.size; // old allocation size
[19e5d65d]1337 bool ozfill = ZeroFillBit( header ); // old allocation zero filled
[92847f7]1338 if ( unlikely( size <= odsize ) && odsize <= size * 2 ) { // allow up to 50% wasted storage
[116a2ea]1339 #ifdef __CFA_DEBUG__
1340 incUnfreed( size - header->kind.real.size ); // adjustment off the size difference
1341 #endif // __CFA_DEBUG__
1342 header->kind.real.size = size; // reset allocation size
[d5d3a90]1343 if ( unlikely( ozfill ) && size > osize ) { // previous request zero fill and larger ?
[e4b6b7d3]1344 memset( (char *)oaddr + osize, '\0', size - osize ); // initialize added storage
[d5d3a90]1345 } // if
[116a2ea]1346 #ifdef __STATISTICS__
1347 incCalls( REALLOC );
1348 #endif // __STATISTICS__
[95eb7cf]1349 return oaddr;
[c4f68dc]1350 } // if
1351
[95eb7cf]1352 // change size and copy old content to new storage
1353
1354 void * naddr;
[116a2ea]1355 if ( likely( oalign <= libAlign() ) ) { // previous request not aligned ?
1356 naddr = doMalloc( size STAT_ARG( REALLOC ) ); // create new area
[c4f68dc]1357 } else {
[116a2ea]1358 naddr = memalignNoStats( oalign, size STAT_ARG( REALLOC ) ); // create new aligned area
[c4f68dc]1359 } // if
[1e034d9]1360
[116a2ea]1361 headers( "realloc", naddr, header, freeHead, bsize, oalign );
1362 // To preserve prior fill, the entire bucket must be copied versus the size.
[47dd0d2]1363 memcpy( naddr, oaddr, min( osize, size ) ); // copy bytes
[116a2ea]1364 doFree( oaddr ); // free previous storage
[d5d3a90]1365
1366 if ( unlikely( ozfill ) ) { // previous request zero fill ?
[19e5d65d]1367 MarkZeroFilledBit( header ); // mark new request as zero filled
[d5d3a90]1368 if ( size > osize ) { // previous request larger ?
[e4b6b7d3]1369 memset( (char *)naddr + osize, '\0', size - osize ); // initialize added storage
[d5d3a90]1370 } // if
1371 } // if
[95eb7cf]1372 return naddr;
[b6830d74]1373 } // realloc
[c4f68dc]1374
[c1f38e6c]1375
[19e5d65d]1376 // Same as realloc() except the new allocation size is large enough for an array of nelem elements of size elsize.
[032234bd]1377 void * reallocarray( void * oaddr, size_t dim, size_t elemSize ) libcfa_public {
[19e5d65d]1378 return realloc( oaddr, dim * elemSize );
1379 } // reallocarray
1380
1381
[61248a4]1382 // Same as malloc() except the memory address is a multiple of alignment, which must be a power of two. (obsolete)
[032234bd]1383 void * memalign( size_t alignment, size_t size ) libcfa_public {
[116a2ea]1384 return memalignNoStats( alignment, size STAT_ARG( MEMALIGN ) );
[bcb14b5]1385 } // memalign
[c4f68dc]1386
[95eb7cf]1387
[76e2113]1388 // Same as aalloc() with memory alignment.
[032234bd]1389 void * amemalign( size_t alignment, size_t dim, size_t elemSize ) libcfa_public {
[116a2ea]1390 return memalignNoStats( alignment, dim * elemSize STAT_ARG( AMEMALIGN ) );
[76e2113]1391 } // amemalign
1392
1393
[ca7949b]1394 // Same as calloc() with memory alignment.
[032234bd]1395 void * cmemalign( size_t alignment, size_t dim, size_t elemSize ) libcfa_public {
[709b812]1396 size_t size = dim * elemSize;
[116a2ea]1397 char * addr = (char *)memalignNoStats( alignment, size STAT_ARG( CMEMALIGN ) );
[95eb7cf]1398
[116a2ea]1399 if ( unlikely( addr == NULL ) ) return NULL; // stop further processing if 0p is returned
[709b812]1400
[31a5f418]1401 Heap.Storage.Header * header;
[116a2ea]1402 Heap.FreeHeader * freeHead;
[709b812]1403 size_t bsize;
1404
1405 #ifndef __CFA_DEBUG__
1406 bool mapped =
1407 #endif // __CFA_DEBUG__
[116a2ea]1408 headers( "cmemalign", addr, header, freeHead, bsize, alignment );
[709b812]1409
1410 // Mapped storage is zero filled, but in debug mode mapped memory is scrubbed in doMalloc, so it has to be reset to zero.
1411 #ifndef __CFA_DEBUG__
1412 if ( ! mapped )
1413 #endif // __CFA_DEBUG__
1414 // <-------0000000000000000000000000000UUUUUUUUUUUUUUUUUUUUUUUUU> bsize (bucket size) U => undefined
1415 // `-header`-addr `-size
1416 memset( addr, '\0', size ); // set to zeros
1417
[19e5d65d]1418 MarkZeroFilledBit( header ); // mark as zero filled
[709b812]1419 return addr;
[95eb7cf]1420 } // cmemalign
1421
[13fece5]1422
[ca7949b]1423 // Same as memalign(), but ISO/IEC 2011 C11 Section 7.22.2 states: the value of size shall be an integral multiple
[19e5d65d]1424 // of alignment. This requirement is universally ignored.
[032234bd]1425 void * aligned_alloc( size_t alignment, size_t size ) libcfa_public {
[c4f68dc]1426 return memalign( alignment, size );
[b6830d74]1427 } // aligned_alloc
[c4f68dc]1428
1429
[ca7949b]1430 // Allocates size bytes and places the address of the allocated memory in *memptr. The address of the allocated
1431 // memory shall be a multiple of alignment, which must be a power of two and a multiple of sizeof(void *). If size
1432 // is 0, then posix_memalign() returns either 0p, or a unique pointer value that can later be successfully passed to
1433 // free(3).
[032234bd]1434 int posix_memalign( void ** memptr, size_t alignment, size_t size ) libcfa_public {
[69ec0fb]1435 if ( unlikely( alignment < libAlign() || ! is_pow2( alignment ) ) ) return EINVAL; // check alignment
[19e5d65d]1436 *memptr = memalign( alignment, size );
[c4f68dc]1437 return 0;
[b6830d74]1438 } // posix_memalign
[c4f68dc]1439
[13fece5]1440
[ca7949b]1441 // Allocates size bytes and returns a pointer to the allocated memory. The memory address shall be a multiple of the
1442 // page size. It is equivalent to memalign(sysconf(_SC_PAGESIZE),size).
[032234bd]1443 void * valloc( size_t size ) libcfa_public {
[ad2dced]1444 return memalign( __page_size, size );
[b6830d74]1445 } // valloc
[c4f68dc]1446
1447
[ca7949b]1448 // Same as valloc but rounds size to multiple of page size.
[032234bd]1449 void * pvalloc( size_t size ) libcfa_public {
[19e5d65d]1450 return memalign( __page_size, ceiling2( size, __page_size ) ); // round size to multiple of page size
[ca7949b]1451 } // pvalloc
1452
1453
1454 // Frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc()
[1076d05]1455 // or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behaviour occurs. If ptr is
[ca7949b]1456 // 0p, no operation is performed.
[032234bd]1457 void free( void * addr ) libcfa_public {
[116a2ea]1458// verify( heapManager );
1459
[95eb7cf]1460 if ( unlikely( addr == 0p ) ) { // special case
[709b812]1461 #ifdef __STATISTICS__
[116a2ea]1462 if ( heapManager )
1463 incZeroCalls( FREE );
[709b812]1464 #endif // __STATISTICS__
[c4f68dc]1465 return;
[116a2ea]1466 } // if
1467
1468 #ifdef __STATISTICS__
1469 incCalls( FREE );
1470 #endif // __STATISTICS__
[c4f68dc]1471
[116a2ea]1472 doFree( addr ); // handles heapManager == nullptr
[b6830d74]1473 } // free
[93c2e0a]1474
[c4f68dc]1475
[76e2113]1476 // Returns the alignment of an allocation.
[032234bd]1477 size_t malloc_alignment( void * addr ) libcfa_public {
[95eb7cf]1478 if ( unlikely( addr == 0p ) ) return libAlign(); // minimum alignment
[19e5d65d]1479 Heap.Storage.Header * header = HeaderAddr( addr );
1480 if ( unlikely( AlignmentBit( header ) ) ) { // fake header ?
1481 return ClearAlignmentBit( header ); // clear flag from value
[c4f68dc]1482 } else {
[cfbc703d]1483 return libAlign(); // minimum alignment
[c4f68dc]1484 } // if
[bcb14b5]1485 } // malloc_alignment
[c4f68dc]1486
[92aca37]1487
[76e2113]1488 // Returns true if the allocation is zero filled, e.g., allocated by calloc().
[032234bd]1489 bool malloc_zero_fill( void * addr ) libcfa_public {
[95eb7cf]1490 if ( unlikely( addr == 0p ) ) return false; // null allocation is not zero fill
[19e5d65d]1491 Heap.Storage.Header * header = HeaderAddr( addr );
1492 if ( unlikely( AlignmentBit( header ) ) ) { // fake header ?
1493 header = RealHeader( header ); // backup from fake to real header
[c4f68dc]1494 } // if
[19e5d65d]1495 return ZeroFillBit( header ); // zero filled ?
[bcb14b5]1496 } // malloc_zero_fill
[c4f68dc]1497
[19e5d65d]1498
1499 // Returns original total allocation size (not bucket size) => array size is dimension * sizeof(T).
[032234bd]1500 size_t malloc_size( void * addr ) libcfa_public {
[849fb370]1501 if ( unlikely( addr == 0p ) ) return 0; // null allocation has zero size
[19e5d65d]1502 Heap.Storage.Header * header = HeaderAddr( addr );
1503 if ( unlikely( AlignmentBit( header ) ) ) { // fake header ?
1504 header = RealHeader( header ); // backup from fake to real header
[cfbc703d]1505 } // if
[9c438546]1506 return header->kind.real.size;
[76e2113]1507 } // malloc_size
1508
[cfbc703d]1509
[ca7949b]1510 // Returns the number of usable bytes in the block pointed to by ptr, a pointer to a block of memory allocated by
1511 // malloc or a related function.
[032234bd]1512 size_t malloc_usable_size( void * addr ) libcfa_public {
[95eb7cf]1513 if ( unlikely( addr == 0p ) ) return 0; // null allocation has 0 size
[31a5f418]1514 Heap.Storage.Header * header;
[116a2ea]1515 Heap.FreeHeader * freeHead;
[95eb7cf]1516 size_t bsize, alignment;
1517
[116a2ea]1518 headers( "malloc_usable_size", addr, header, freeHead, bsize, alignment );
[19e5d65d]1519 return DataStorage( bsize, addr, header ); // data storage in bucket
[95eb7cf]1520 } // malloc_usable_size
1521
1522
[ca7949b]1523 // Prints (on default standard error) statistics about memory allocated by malloc and related functions.
[032234bd]1524 void malloc_stats( void ) libcfa_public {
[c4f68dc]1525 #ifdef __STATISTICS__
[116a2ea]1526 HeapStatistics stats;
1527 HeapStatisticsCtor( stats );
1528 if ( printStats( collectStats( stats ) ) == -1 ) {
1529 #else
1530 #define MALLOC_STATS_MSG "malloc_stats statistics disabled.\n"
1531 if ( write( STDERR_FILENO, MALLOC_STATS_MSG, sizeof( MALLOC_STATS_MSG ) - 1 /* size includes '\0' */ ) == -1 ) {
[c4f68dc]1532 #endif // __STATISTICS__
[5951956]1533 abort( "**** Error **** write failed in malloc_stats" );
[116a2ea]1534 } // if
[bcb14b5]1535 } // malloc_stats
[c4f68dc]1536
[92aca37]1537
[19e5d65d]1538 // Changes the file descriptor where malloc_stats() writes statistics.
[032234bd]1539 int malloc_stats_fd( int fd __attribute__(( unused )) ) libcfa_public {
[c4f68dc]1540 #ifdef __STATISTICS__
[116a2ea]1541 int temp = heapMaster.stats_fd;
1542 heapMaster.stats_fd = fd;
[bcb14b5]1543 return temp;
[c4f68dc]1544 #else
[19e5d65d]1545 return -1; // unsupported
[c4f68dc]1546 #endif // __STATISTICS__
[bcb14b5]1547 } // malloc_stats_fd
[c4f68dc]1548
[95eb7cf]1549
[19e5d65d]1550 // Prints an XML string that describes the current state of the memory-allocation implementation in the caller.
1551 // The string is printed on the file stream stream. The exported string includes information about all arenas (see
1552 // malloc).
[032234bd]1553 int malloc_info( int options, FILE * stream __attribute__(( unused )) ) libcfa_public {
[19e5d65d]1554 if ( options != 0 ) { errno = EINVAL; return -1; }
1555 #ifdef __STATISTICS__
[116a2ea]1556 HeapStatistics stats;
1557 HeapStatisticsCtor( stats );
1558 return printStatsXML( collectStats( stats ), stream ); // returns bytes written or -1
[19e5d65d]1559 #else
1560 return 0; // unsupported
1561 #endif // __STATISTICS__
1562 } // malloc_info
1563
1564
[1076d05]1565 // Adjusts parameters that control the behaviour of the memory-allocation functions (see malloc). The param argument
[ca7949b]1566 // specifies the parameter to be modified, and value specifies the new value for that parameter.
[032234bd]1567 int mallopt( int option, int value ) libcfa_public {
[19e5d65d]1568 if ( value < 0 ) return 0;
[95eb7cf]1569 choose( option ) {
1570 case M_TOP_PAD:
[116a2ea]1571 heapMaster.heapExpand = ceiling2( value, __page_size );
[19e5d65d]1572 return 1;
[95eb7cf]1573 case M_MMAP_THRESHOLD:
1574 if ( setMmapStart( value ) ) return 1;
[19e5d65d]1575 } // choose
[95eb7cf]1576 return 0; // error, unsupported
1577 } // mallopt
1578
[c1f38e6c]1579
[ca7949b]1580 // Attempt to release free memory at the top of the heap (by calling sbrk with a suitable argument).
[032234bd]1581 int malloc_trim( size_t ) libcfa_public {
[95eb7cf]1582 return 0; // => impossible to release memory
1583 } // malloc_trim
1584
1585
[ca7949b]1586 // Records the current state of all malloc internal bookkeeping variables (but not the actual contents of the heap
1587 // or the state of malloc_hook functions pointers). The state is recorded in a system-dependent opaque data
1588 // structure dynamically allocated via malloc, and a pointer to that data structure is returned as the function
1589 // result. (The caller must free this memory.)
[032234bd]1590 void * malloc_get_state( void ) libcfa_public {
[95eb7cf]1591 return 0p; // unsupported
[c4f68dc]1592 } // malloc_get_state
1593
[bcb14b5]1594
[ca7949b]1595 // Restores the state of all malloc internal bookkeeping variables to the values recorded in the opaque data
1596 // structure pointed to by state.
[032234bd]1597 int malloc_set_state( void * ) libcfa_public {
[bcb14b5]1598 return 0; // unsupported
[c4f68dc]1599 } // malloc_set_state
[31a5f418]1600
[19e5d65d]1601
[31a5f418]1602 // Sets the amount (bytes) to extend the heap when there is insufficent free storage to service an allocation.
[032234bd]1603 __attribute__((weak)) size_t malloc_expansion() libcfa_public { return __CFA_DEFAULT_HEAP_EXPANSION__; }
[31a5f418]1604
1605 // Sets the crossover point between allocations occuring in the sbrk area or separately mmapped.
[032234bd]1606 __attribute__((weak)) size_t malloc_mmap_start() libcfa_public { return __CFA_DEFAULT_MMAP_START__; }
[31a5f418]1607
1608 // Amount subtracted to adjust for unfreed program storage (debug only).
[032234bd]1609 __attribute__((weak)) size_t malloc_unfreed() libcfa_public { return __CFA_DEFAULT_HEAP_UNFREED__; }
[c4f68dc]1610} // extern "C"
1611
1612
[95eb7cf]1613// Must have CFA linkage to overload with C linkage realloc.
[032234bd]1614void * resize( void * oaddr, size_t nalign, size_t size ) libcfa_public {
[116a2ea]1615 if ( unlikely( oaddr == 0p ) ) { // => malloc( size )
1616 return memalignNoStats( nalign, size STAT_ARG( RESIZE ) );
[709b812]1617 } // if
[95eb7cf]1618
[116a2ea]1619 PROLOG( RESIZE, doFree( oaddr ) ); // => free( oaddr )
[cfbc703d]1620
[92847f7]1621 // Attempt to reuse existing alignment.
[19e5d65d]1622 Heap.Storage.Header * header = HeaderAddr( oaddr );
1623 bool isFakeHeader = AlignmentBit( header ); // old fake header ?
[92847f7]1624 size_t oalign;
[19e5d65d]1625
1626 if ( unlikely( isFakeHeader ) ) {
[116a2ea]1627 checkAlign( nalign ); // check alignment
[19e5d65d]1628 oalign = ClearAlignmentBit( header ); // old alignment
1629 if ( unlikely( (uintptr_t)oaddr % nalign == 0 // lucky match ?
[92847f7]1630 && ( oalign <= nalign // going down
1631 || (oalign >= nalign && oalign <= 256) ) // little alignment storage wasted ?
[19e5d65d]1632 ) ) {
1633 HeaderAddr( oaddr )->kind.fake.alignment = MarkAlignmentBit( nalign ); // update alignment (could be the same)
[116a2ea]1634 Heap.FreeHeader * freeHead;
[92847f7]1635 size_t bsize, oalign;
[116a2ea]1636 headers( "resize", oaddr, header, freeHead, bsize, oalign );
[19e5d65d]1637 size_t odsize = DataStorage( bsize, oaddr, header ); // data storage available in bucket
[a3ade94]1638
[92847f7]1639 if ( size <= odsize && odsize <= size * 2 ) { // allow 50% wasted data storage
[19e5d65d]1640 HeaderAddr( oaddr )->kind.fake.alignment = MarkAlignmentBit( nalign ); // update alignment (could be the same)
1641 ClearZeroFillBit( header ); // turn off 0 fill
[116a2ea]1642 #ifdef __CFA_DEBUG__
1643 incUnfreed( size - header->kind.real.size ); // adjustment off the size difference
1644 #endif // __CFA_DEBUG__
[92847f7]1645 header->kind.real.size = size; // reset allocation size
[116a2ea]1646 #ifdef __STATISTICS__
1647 incCalls( RESIZE );
1648 #endif // __STATISTICS__
[92847f7]1649 return oaddr;
1650 } // if
[cfbc703d]1651 } // if
[92847f7]1652 } else if ( ! isFakeHeader // old real header (aligned on libAlign) ?
1653 && nalign == libAlign() ) { // new alignment also on libAlign => no fake header needed
[113d785]1654 return resize( oaddr, size ); // duplicate special case checks
[cfbc703d]1655 } // if
1656
[dd23e66]1657 // change size, DO NOT preserve STICKY PROPERTIES.
[116a2ea]1658 doFree( oaddr ); // free previous storage
1659 return memalignNoStats( nalign, size STAT_ARG( RESIZE ) ); // create new aligned area
[cfbc703d]1660} // resize
1661
1662
[032234bd]1663void * realloc( void * oaddr, size_t nalign, size_t size ) libcfa_public {
[116a2ea]1664 if ( unlikely( oaddr == 0p ) ) { // => malloc( size )
1665 return memalignNoStats( nalign, size STAT_ARG( REALLOC ) );
[709b812]1666 } // if
1667
[116a2ea]1668 PROLOG( REALLOC, doFree( oaddr ) ); // => free( oaddr )
[c86f587]1669
[92847f7]1670 // Attempt to reuse existing alignment.
[19e5d65d]1671 Heap.Storage.Header * header = HeaderAddr( oaddr );
1672 bool isFakeHeader = AlignmentBit( header ); // old fake header ?
[92847f7]1673 size_t oalign;
[19e5d65d]1674 if ( unlikely( isFakeHeader ) ) {
[116a2ea]1675 checkAlign( nalign ); // check alignment
[19e5d65d]1676 oalign = ClearAlignmentBit( header ); // old alignment
1677 if ( unlikely( (uintptr_t)oaddr % nalign == 0 // lucky match ?
[92847f7]1678 && ( oalign <= nalign // going down
1679 || (oalign >= nalign && oalign <= 256) ) // little alignment storage wasted ?
[19e5d65d]1680 ) ) {
1681 HeaderAddr( oaddr )->kind.fake.alignment = MarkAlignmentBit( nalign ); // update alignment (could be the same)
1682 return realloc( oaddr, size ); // duplicate special case checks
[92847f7]1683 } // if
1684 } else if ( ! isFakeHeader // old real header (aligned on libAlign) ?
[19e5d65d]1685 && nalign == libAlign() ) { // new alignment also on libAlign => no fake header needed
1686 return realloc( oaddr, size ); // duplicate special case checks
1687 } // if
[cfbc703d]1688
[116a2ea]1689 Heap.FreeHeader * freeHead;
[92847f7]1690 size_t bsize;
[116a2ea]1691 headers( "realloc", oaddr, header, freeHead, bsize, oalign );
[92847f7]1692
1693 // change size and copy old content to new storage
1694
[dd23e66]1695 size_t osize = header->kind.real.size; // old allocation size
[19e5d65d]1696 bool ozfill = ZeroFillBit( header ); // old allocation zero filled
[dd23e66]1697
[116a2ea]1698 void * naddr = memalignNoStats( nalign, size STAT_ARG( REALLOC ) ); // create new aligned area
[95eb7cf]1699
[116a2ea]1700 headers( "realloc", naddr, header, freeHead, bsize, oalign );
[47dd0d2]1701 memcpy( naddr, oaddr, min( osize, size ) ); // copy bytes
[116a2ea]1702 doFree( oaddr ); // free previous storage
[d5d3a90]1703
1704 if ( unlikely( ozfill ) ) { // previous request zero fill ?
[19e5d65d]1705 MarkZeroFilledBit( header ); // mark new request as zero filled
[d5d3a90]1706 if ( size > osize ) { // previous request larger ?
[e4b6b7d3]1707 memset( (char *)naddr + osize, '\0', size - osize ); // initialize added storage
[d5d3a90]1708 } // if
1709 } // if
[1e034d9]1710 return naddr;
[95eb7cf]1711} // realloc
1712
1713
[116a2ea]1714void * reallocarray( void * oaddr, size_t nalign, size_t dim, size_t elemSize ) __THROW {
1715 return realloc( oaddr, nalign, dim * elemSize );
1716} // reallocarray
1717
1718
[c4f68dc]1719// Local Variables: //
1720// tab-width: 4 //
[f8cd310]1721// compile-command: "cfa -nodebug -O2 heap.cfa" //
[c4f68dc]1722// End: //
Note: See TracBrowser for help on using the repository browser.