Memory.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. // Copyright (C) 2009-2022, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Util/Memory.h>
  6. #include <AnKi/Util/Functions.h>
  7. #include <AnKi/Util/Assert.h>
  8. #include <AnKi/Util/Thread.h>
  9. #include <AnKi/Util/Atomic.h>
  10. #include <AnKi/Util/Logger.h>
  11. #include <cstdlib>
  12. #include <cstring>
  13. #include <cstdio>
  14. namespace anki {
  15. #if ANKI_MEM_EXTRA_CHECKS
  16. static PoolSignature computePoolSignature(void* ptr)
  17. {
  18. ANKI_ASSERT(ptr);
  19. PtrSize sig64 = ptrToNumber(ptr);
  20. PoolSignature sig = PoolSignature(sig64);
  21. sig ^= 0x5bd1e995;
  22. sig ^= sig << 24;
  23. ANKI_ASSERT(sig != 0);
  24. return sig;
  25. }
  26. class AllocationHeader
  27. {
  28. public:
  29. PtrSize m_allocationSize;
  30. PoolSignature m_signature;
  31. };
  32. constexpr U32 kExtraChecksMaxAlignment = 64;
  33. constexpr U32 kAllocationHeaderSize = getAlignedRoundUp(kExtraChecksMaxAlignment, sizeof(AllocationHeader));
  34. #endif
  35. #define ANKI_CREATION_OOM_ACTION() ANKI_UTIL_LOGF("Out of memory")
  36. #define ANKI_OOM_ACTION() ANKI_UTIL_LOGE("Out of memory. Expect segfault")
  37. template<typename TPtr, typename TSize>
  38. static void invalidateMemory([[maybe_unused]] TPtr ptr, [[maybe_unused]] TSize size)
  39. {
  40. #if ANKI_MEM_EXTRA_CHECKS
  41. memset(static_cast<void*>(ptr), 0xCC, size);
  42. #endif
  43. }
  44. void* mallocAligned(PtrSize size, PtrSize alignmentBytes)
  45. {
  46. ANKI_ASSERT(size > 0);
  47. ANKI_ASSERT(alignmentBytes > 0);
  48. #if ANKI_POSIX
  49. # if !ANKI_OS_ANDROID
  50. void* out = nullptr;
  51. PtrSize alignment = getAlignedRoundUp(alignmentBytes, sizeof(void*));
  52. int err = posix_memalign(&out, alignment, size);
  53. if(ANKI_LIKELY(!err))
  54. {
  55. ANKI_ASSERT(out != nullptr);
  56. // Make sure it's aligned
  57. ANKI_ASSERT(isAligned(alignmentBytes, out));
  58. }
  59. else
  60. {
  61. ANKI_UTIL_LOGE("mallocAligned() failed");
  62. }
  63. return out;
  64. # else
  65. void* out = memalign(getAlignedRoundUp(alignmentBytes, sizeof(void*)), size);
  66. if(out)
  67. {
  68. // Make sure it's aligned
  69. ANKI_ASSERT(isAligned(alignmentBytes, out));
  70. }
  71. else
  72. {
  73. ANKI_UTIL_LOGE("memalign() failed");
  74. }
  75. return out;
  76. # endif
  77. #elif ANKI_OS_WINDOWS
  78. void* out = _aligned_malloc(size, alignmentBytes);
  79. if(out)
  80. {
  81. // Make sure it's aligned
  82. ANKI_ASSERT(isAligned(alignmentBytes, out));
  83. }
  84. else
  85. {
  86. ANKI_UTIL_LOGE("_aligned_malloc() failed. Size %zu, alignment %zu", size, alignmentBytes);
  87. }
  88. return out;
  89. #else
  90. # error "Unimplemented"
  91. #endif
  92. }
  93. void freeAligned(void* ptr)
  94. {
  95. #if ANKI_POSIX
  96. ::free(ptr);
  97. #elif ANKI_OS_WINDOWS
  98. _aligned_free(ptr);
  99. #else
  100. # error "Unimplemented"
  101. #endif
  102. }
  103. void* allocAligned([[maybe_unused]] void* userData, void* ptr, PtrSize size, PtrSize alignment)
  104. {
  105. void* out;
  106. if(ptr == nullptr)
  107. {
  108. // Allocate
  109. ANKI_ASSERT(size > 0);
  110. out = mallocAligned(size, alignment);
  111. }
  112. else
  113. {
  114. // Deallocate
  115. ANKI_ASSERT(size == 0);
  116. ANKI_ASSERT(alignment == 0);
  117. freeAligned(ptr);
  118. out = nullptr;
  119. }
  120. return out;
  121. }
  122. BaseMemoryPool::BaseMemoryPool(Type type, AllocAlignedCallback allocCb, void* allocCbUserData, const char* name)
  123. : m_allocCb(allocCb)
  124. , m_allocCbUserData(allocCbUserData)
  125. , m_type(type)
  126. {
  127. ANKI_ASSERT(allocCb != nullptr);
  128. I64 len;
  129. if(name && (len = strlen(name)) > 0)
  130. {
  131. m_name = static_cast<char*>(malloc(len + 1));
  132. memcpy(m_name, name, len + 1);
  133. }
  134. }
  135. BaseMemoryPool::~BaseMemoryPool()
  136. {
  137. ANKI_ASSERT(m_refcount.load() == 0 && "Refcount should be zero");
  138. }
  139. HeapMemoryPool::HeapMemoryPool(AllocAlignedCallback allocCb, void* allocCbUserDataconst, const char* name)
  140. : BaseMemoryPool(Type::kHeap, allocCb, allocCbUserDataconst, name)
  141. {
  142. #if ANKI_MEM_EXTRA_CHECKS
  143. m_signature = computePoolSignature(this);
  144. #endif
  145. }
  146. HeapMemoryPool::~HeapMemoryPool()
  147. {
  148. const U32 count = m_allocationCount.load();
  149. if(count != 0)
  150. {
  151. ANKI_UTIL_LOGE("Memory pool destroyed before all memory being released (%u deallocations missed): %s", count,
  152. getName());
  153. }
  154. }
  155. void* HeapMemoryPool::allocate(PtrSize size, PtrSize alignment)
  156. {
  157. ANKI_ASSERT(size > 0);
  158. #if ANKI_MEM_EXTRA_CHECKS
  159. ANKI_ASSERT(alignment <= kExtraChecksMaxAlignment && "Wrong assumption");
  160. size += kAllocationHeaderSize;
  161. #endif
  162. void* mem = m_allocCb(m_allocCbUserData, nullptr, size, alignment);
  163. if(mem != nullptr)
  164. {
  165. m_allocationCount.fetchAdd(1);
  166. #if ANKI_MEM_EXTRA_CHECKS
  167. memset(mem, 0, kAllocationHeaderSize);
  168. AllocationHeader& header = *static_cast<AllocationHeader*>(mem);
  169. header.m_signature = m_signature;
  170. header.m_allocationSize = size;
  171. mem = static_cast<void*>(static_cast<U8*>(mem) + kAllocationHeaderSize);
  172. #endif
  173. }
  174. else
  175. {
  176. ANKI_OOM_ACTION();
  177. }
  178. return mem;
  179. }
  180. void HeapMemoryPool::free(void* ptr)
  181. {
  182. if(ANKI_UNLIKELY(ptr == nullptr))
  183. {
  184. return;
  185. }
  186. #if ANKI_MEM_EXTRA_CHECKS
  187. U8* memU8 = static_cast<U8*>(ptr) - kAllocationHeaderSize;
  188. AllocationHeader& header = *reinterpret_cast<AllocationHeader*>(memU8);
  189. if(header.m_signature != m_signature)
  190. {
  191. ANKI_UTIL_LOGE("Signature missmatch on free");
  192. }
  193. ptr = static_cast<void*>(memU8);
  194. invalidateMemory(ptr, header.m_allocationSize);
  195. #endif
  196. m_allocationCount.fetchSub(1);
  197. m_allocCb(m_allocCbUserData, ptr, 0, 0);
  198. }
  199. Error StackMemoryPool::StackAllocatorBuilderInterface::allocateChunk(PtrSize size, Chunk*& out)
  200. {
  201. ANKI_ASSERT(size > 0);
  202. const PtrSize fullChunkSize = offsetof(Chunk, m_memoryStart) + size;
  203. void* mem = m_parent->m_allocCb(m_parent->m_allocCbUserData, nullptr, fullChunkSize, kMaxAlignment);
  204. if(ANKI_LIKELY(mem))
  205. {
  206. out = static_cast<Chunk*>(mem);
  207. invalidateMemory(&out->m_memoryStart[0], size);
  208. }
  209. else
  210. {
  211. ANKI_OOM_ACTION();
  212. return Error::kOutOfMemory;
  213. }
  214. return Error::kNone;
  215. }
  216. void StackMemoryPool::StackAllocatorBuilderInterface::freeChunk(Chunk* chunk)
  217. {
  218. ANKI_ASSERT(chunk);
  219. m_parent->m_allocCb(m_parent->m_allocCbUserData, chunk, 0, 0);
  220. }
  221. void StackMemoryPool::StackAllocatorBuilderInterface::recycleChunk(Chunk& chunk)
  222. {
  223. ANKI_ASSERT(chunk.m_chunkSize > 0);
  224. invalidateMemory(&chunk.m_memoryStart[0], chunk.m_chunkSize);
  225. }
  226. StackMemoryPool::StackMemoryPool(AllocAlignedCallback allocCb, void* allocCbUserData, PtrSize initialChunkSize,
  227. F64 nextChunkScale, PtrSize nextChunkBias, Bool ignoreDeallocationErrors,
  228. U32 alignmentBytes, const char* name)
  229. : BaseMemoryPool(Type::kStack, allocCb, allocCbUserData, name)
  230. {
  231. ANKI_ASSERT(initialChunkSize > 0);
  232. ANKI_ASSERT(nextChunkScale >= 1.0);
  233. ANKI_ASSERT(alignmentBytes > 0 && alignmentBytes <= kMaxAlignment);
  234. m_builder.getInterface().m_parent = this;
  235. m_builder.getInterface().m_alignmentBytes = alignmentBytes;
  236. m_builder.getInterface().m_ignoreDeallocationErrors = ignoreDeallocationErrors;
  237. m_builder.getInterface().m_initialChunkSize = initialChunkSize;
  238. m_builder.getInterface().m_nextChunkScale = nextChunkScale;
  239. m_builder.getInterface().m_nextChunkBias = nextChunkBias;
  240. }
  241. StackMemoryPool::~StackMemoryPool()
  242. {
  243. }
  244. void* StackMemoryPool::allocate(PtrSize size, PtrSize alignment)
  245. {
  246. ANKI_ASSERT(size > 0);
  247. Chunk* chunk;
  248. PtrSize offset;
  249. if(m_builder.allocate(size, alignment, chunk, offset))
  250. {
  251. return nullptr;
  252. }
  253. m_allocationCount.fetchAdd(1);
  254. const PtrSize address = ptrToNumber(&chunk->m_memoryStart[0]) + offset;
  255. return numberToPtr<void*>(address);
  256. }
  257. void StackMemoryPool::free(void* ptr)
  258. {
  259. if(ANKI_UNLIKELY(ptr == nullptr))
  260. {
  261. return;
  262. }
  263. [[maybe_unused]] const U32 count = m_allocationCount.fetchSub(1);
  264. ANKI_ASSERT(count > 0);
  265. m_builder.free();
  266. }
  267. void StackMemoryPool::reset()
  268. {
  269. m_builder.reset();
  270. m_allocationCount.store(0);
  271. }
  272. ChainMemoryPool::ChainMemoryPool(AllocAlignedCallback allocCb, void* allocCbUserData, PtrSize initialChunkSize,
  273. F32 nextChunkScale, PtrSize nextChunkBias, PtrSize alignmentBytes, const char* name)
  274. : BaseMemoryPool(Type::kChain, allocCb, allocCbUserData, name)
  275. {
  276. ANKI_ASSERT(initialChunkSize > 0);
  277. ANKI_ASSERT(nextChunkScale >= 1.0);
  278. ANKI_ASSERT(alignmentBytes > 0);
  279. // Set all values
  280. m_alignmentBytes = alignmentBytes;
  281. m_initSize = initialChunkSize;
  282. m_scale = nextChunkScale;
  283. m_bias = nextChunkBias;
  284. m_headerSize = max<PtrSize>(m_alignmentBytes, sizeof(Chunk*));
  285. // Initial size should be > 0
  286. ANKI_ASSERT(m_initSize > 0 && "Wrong arg");
  287. // On fixed initial size is the same as the max
  288. if(m_scale == 0.0 && m_bias == 0)
  289. {
  290. ANKI_ASSERT(0 && "Wrong arg");
  291. }
  292. }
  293. ChainMemoryPool::~ChainMemoryPool()
  294. {
  295. if(m_allocationCount.load() != 0)
  296. {
  297. ANKI_UTIL_LOGE("Memory pool destroyed before all memory being released");
  298. }
  299. Chunk* ch = m_headChunk;
  300. while(ch)
  301. {
  302. Chunk* next = ch->m_next;
  303. destroyChunk(ch);
  304. ch = next;
  305. }
  306. }
  307. void* ChainMemoryPool::allocate(PtrSize size, PtrSize alignment)
  308. {
  309. ANKI_ASSERT(size > 0);
  310. Chunk* ch;
  311. void* mem = nullptr;
  312. LockGuard<SpinLock> lock(m_lock);
  313. // Get chunk
  314. ch = m_tailChunk;
  315. // Create new chunk if needed
  316. if(ch == nullptr || (mem = allocateFromChunk(ch, size, alignment)) == nullptr)
  317. {
  318. // Create new chunk
  319. PtrSize chunkSize = computeNewChunkSize(size);
  320. ch = createNewChunk(chunkSize);
  321. // Chunk creation failed
  322. if(ch == nullptr)
  323. {
  324. return mem;
  325. }
  326. }
  327. if(mem == nullptr)
  328. {
  329. mem = allocateFromChunk(ch, size, alignment);
  330. ANKI_ASSERT(mem != nullptr && "The chunk should have space");
  331. }
  332. m_allocationCount.fetchAdd(1);
  333. return mem;
  334. }
  335. void ChainMemoryPool::free(void* ptr)
  336. {
  337. if(ANKI_UNLIKELY(ptr == nullptr))
  338. {
  339. return;
  340. }
  341. // Get the chunk
  342. U8* mem = static_cast<U8*>(ptr);
  343. mem -= m_headerSize;
  344. Chunk* chunk = *reinterpret_cast<Chunk**>(mem);
  345. ANKI_ASSERT(chunk != nullptr);
  346. ANKI_ASSERT((mem >= chunk->m_memory && mem < (chunk->m_memory + chunk->m_memsize)) && "Wrong chunk");
  347. LockGuard<SpinLock> lock(m_lock);
  348. // Decrease the deallocation refcount and if it's zero delete the chunk
  349. ANKI_ASSERT(chunk->m_allocationCount > 0);
  350. if(--chunk->m_allocationCount == 0)
  351. {
  352. // Chunk is empty. Delete it
  353. destroyChunk(chunk);
  354. }
  355. m_allocationCount.fetchSub(1);
  356. }
  357. PtrSize ChainMemoryPool::getChunksCount() const
  358. {
  359. PtrSize count = 0;
  360. Chunk* ch = m_headChunk;
  361. while(ch)
  362. {
  363. ++count;
  364. ch = ch->m_next;
  365. }
  366. return count;
  367. }
  368. PtrSize ChainMemoryPool::getAllocatedSize() const
  369. {
  370. PtrSize sum = 0;
  371. Chunk* ch = m_headChunk;
  372. while(ch)
  373. {
  374. sum += ch->m_top - ch->m_memory;
  375. ch = ch->m_next;
  376. }
  377. return sum;
  378. }
  379. PtrSize ChainMemoryPool::computeNewChunkSize(PtrSize size) const
  380. {
  381. size += m_headerSize;
  382. PtrSize crntMaxSize;
  383. if(m_tailChunk != nullptr)
  384. {
  385. // Get the size of previous
  386. crntMaxSize = m_tailChunk->m_memsize;
  387. // Compute new size
  388. crntMaxSize = PtrSize(F32(crntMaxSize) * m_scale) + m_bias;
  389. }
  390. else
  391. {
  392. // No chunks. Choose initial size
  393. ANKI_ASSERT(m_headChunk == nullptr);
  394. crntMaxSize = m_initSize;
  395. }
  396. crntMaxSize = max(crntMaxSize, size);
  397. ANKI_ASSERT(crntMaxSize > 0);
  398. return crntMaxSize;
  399. }
  400. ChainMemoryPool::Chunk* ChainMemoryPool::createNewChunk(PtrSize size)
  401. {
  402. ANKI_ASSERT(size > 0);
  403. // Allocate memory and chunk in one go
  404. PtrSize chunkAllocSize = getAlignedRoundUp(m_alignmentBytes, sizeof(Chunk));
  405. PtrSize memAllocSize = getAlignedRoundUp(m_alignmentBytes, size);
  406. PtrSize allocationSize = chunkAllocSize + memAllocSize;
  407. Chunk* chunk = reinterpret_cast<Chunk*>(m_allocCb(m_allocCbUserData, nullptr, allocationSize, m_alignmentBytes));
  408. if(chunk)
  409. {
  410. invalidateMemory(chunk, allocationSize);
  411. // Construct it
  412. memset(chunk, 0, sizeof(Chunk));
  413. // Initialize it
  414. chunk->m_memory = reinterpret_cast<U8*>(chunk) + chunkAllocSize;
  415. chunk->m_memsize = memAllocSize;
  416. chunk->m_top = chunk->m_memory;
  417. // Register it
  418. if(m_tailChunk)
  419. {
  420. m_tailChunk->m_next = chunk;
  421. chunk->m_prev = m_tailChunk;
  422. m_tailChunk = chunk;
  423. }
  424. else
  425. {
  426. ANKI_ASSERT(m_headChunk == nullptr);
  427. m_headChunk = m_tailChunk = chunk;
  428. }
  429. }
  430. else
  431. {
  432. ANKI_OOM_ACTION();
  433. }
  434. return chunk;
  435. }
  436. void* ChainMemoryPool::allocateFromChunk(Chunk* ch, PtrSize size, [[maybe_unused]] PtrSize alignment)
  437. {
  438. ANKI_ASSERT(ch);
  439. ANKI_ASSERT(ch->m_top <= ch->m_memory + ch->m_memsize);
  440. U8* mem = ch->m_top;
  441. PtrSize memV = ptrToNumber(mem);
  442. alignRoundUp(m_alignmentBytes, memV);
  443. mem = numberToPtr<U8*>(memV);
  444. U8* newTop = mem + m_headerSize + size;
  445. if(newTop <= ch->m_memory + ch->m_memsize)
  446. {
  447. *reinterpret_cast<Chunk**>(mem) = ch;
  448. mem += m_headerSize;
  449. ch->m_top = newTop;
  450. ++ch->m_allocationCount;
  451. }
  452. else
  453. {
  454. // Chunk is full. Need a new one
  455. mem = nullptr;
  456. }
  457. return mem;
  458. }
  459. void ChainMemoryPool::destroyChunk(Chunk* ch)
  460. {
  461. ANKI_ASSERT(ch);
  462. if(ch == m_tailChunk)
  463. {
  464. m_tailChunk = ch->m_prev;
  465. }
  466. if(ch == m_headChunk)
  467. {
  468. m_headChunk = ch->m_next;
  469. }
  470. if(ch->m_prev)
  471. {
  472. ANKI_ASSERT(ch->m_prev->m_next == ch);
  473. ch->m_prev->m_next = ch->m_next;
  474. }
  475. if(ch->m_next)
  476. {
  477. ANKI_ASSERT(ch->m_next->m_prev == ch);
  478. ch->m_next->m_prev = ch->m_prev;
  479. }
  480. invalidateMemory(ch, getAlignedRoundUp(m_alignmentBytes, sizeof(Chunk)) + ch->m_memsize);
  481. m_allocCb(m_allocCbUserData, ch, 0, 0);
  482. }
  483. } // end namespace anki