heap_tlsf.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. /*
  2. ** Two Level Segregated Fit memory allocator, version 3.1.
  3. ** Written by Matthew Conte
  4. ** http://tlsf.baisoku.org
  5. **
  6. ** Based on the original documentation by Miguel Masmano:
  7. ** http://www.gii.upv.es/tlsf/main/docs
  8. **
  9. ** This implementation was written to the specification
  10. ** of the document, therefore no GPL restrictions apply.
  11. **
  12. ** Copyright (c) 2006-2016, Matthew Conte
  13. ** All rights reserved.
  14. **
  15. ** Redistribution and use in source and binary forms, with or without
  16. ** modification, are permitted provided that the following conditions are met:
  17. ** * Redistributions of source code must retain the above copyright
  18. ** notice, this list of conditions and the following disclaimer.
  19. ** * Redistributions in binary form must reproduce the above copyright
  20. ** notice, this list of conditions and the following disclaimer in the
  21. ** documentation and/or other materials provided with the distribution.
  22. ** * Neither the name of the copyright holder nor the
  23. ** names of its contributors may be used to endorse or promote products
  24. ** derived from this software without specific prior written permission.
  25. **
  26. ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  27. ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  28. ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  29. ** DISCLAIMED. IN NO EVENT SHALL MATTHEW CONTE BE LIABLE FOR ANY
  30. ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  31. ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  32. ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  33. ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  34. ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  35. ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  36. */
  37. #include "multi_heap_config.h"
  38. #include "multi_heap.h"
  39. #include "multi_heap_internal.h"
  40. #include "heap_tlsf_config.h"
  41. #include "heap_tlsf.h"
  42. #include "esp_log.h"
  43. /*
  44. ** Architecture-specific bit manipulation routines.
  45. **
  46. ** TLSF achieves O(1) cost for malloc and free operations by limiting
  47. ** the search for a free block to a free list of guaranteed size
  48. ** adequate to fulfill the request, combined with efficient free list
  49. ** queries using bitmasks and architecture-specific bit-manipulation
  50. ** routines.
  51. **
  52. ** Most modern processors provide instructions to count leading zeroes
  53. ** in a word, find the lowest and highest set bit, etc. These
  54. ** specific implementations will be used when available, falling back
  55. ** to a reasonably efficient generic implementation.
  56. **
  57. ** NOTE: TLSF spec relies on ffs/fls returning value 0..31.
  58. ** ffs/fls return 1-32 by default, returning 0 for error.
  59. */
  60. /* The TLSF control structure. */
  61. typedef struct control_t
  62. {
  63. /* Empty lists point at this block to indicate they are free. */
  64. block_header_t block_null;
  65. /* Local parameter for the pool */
  66. unsigned int fl_index_count;
  67. unsigned int fl_index_shift;
  68. unsigned int fl_index_max;
  69. unsigned int sl_index_count;
  70. unsigned int sl_index_count_log2;
  71. unsigned int small_block_size;
  72. size_t size;
  73. /* Bitmaps for free lists. */
  74. unsigned int fl_bitmap;
  75. unsigned int *sl_bitmap;
  76. /* Head of free lists. */
  77. block_header_t** blocks;
  78. } control_t;
  79. static inline __attribute__((__always_inline__)) int tlsf_ffs(unsigned int word)
  80. {
  81. const unsigned int reverse = word & (~word + 1);
  82. const int bit = 32 - __builtin_clz(reverse);
  83. return bit - 1;
  84. }
  85. static inline __attribute__((__always_inline__)) int tlsf_fls(unsigned int word)
  86. {
  87. const int bit = word ? 32 - __builtin_clz(word) : 0;
  88. return bit - 1;
  89. }
  90. /*
  91. ** Set assert macro, if it has not been provided by the user.
  92. */
  93. #if !defined (tlsf_assert)
  94. #define tlsf_assert assert
  95. #endif
  96. /*
  97. ** Static assertion mechanism.
  98. */
  99. #define _tlsf_glue2(x, y) x ## y
  100. #define _tlsf_glue(x, y) _tlsf_glue2(x, y)
  101. #define tlsf_static_assert(exp) \
  102. typedef char _tlsf_glue(static_assert, __LINE__) [(exp) ? 1 : -1]
  103. /* This code has been tested on 32- and 64-bit (LP/LLP) architectures. */
  104. tlsf_static_assert(sizeof(int) * CHAR_BIT == 32);
  105. tlsf_static_assert(sizeof(size_t) * CHAR_BIT >= 32);
  106. tlsf_static_assert(sizeof(size_t) * CHAR_BIT <= 64);
  107. static inline __attribute__((__always_inline__)) size_t align_up(size_t x, size_t align)
  108. {
  109. tlsf_assert(0 == (align & (align - 1)) && "must align to a power of two");
  110. return (x + (align - 1)) & ~(align - 1);
  111. }
  112. static inline __attribute__((__always_inline__)) size_t align_down(size_t x, size_t align)
  113. {
  114. tlsf_assert(0 == (align & (align - 1)) && "must align to a power of two");
  115. return x - (x & (align - 1));
  116. }
  117. static inline __attribute__((__always_inline__)) void* align_ptr(const void* ptr, size_t align)
  118. {
  119. const tlsfptr_t aligned =
  120. (tlsf_cast(tlsfptr_t, ptr) + (align - 1)) & ~(align - 1);
  121. tlsf_assert(0 == (align & (align - 1)) && "must align to a power of two");
  122. return tlsf_cast(void*, aligned);
  123. }
  124. /*
  125. ** Adjust an allocation size to be aligned to word size, and no smaller
  126. ** than internal minimum.
  127. */
  128. static inline __attribute__((__always_inline__)) size_t adjust_request_size(tlsf_t tlsf, size_t size, size_t align)
  129. {
  130. size_t adjust = 0;
  131. if (size)
  132. {
  133. const size_t aligned = align_up(size, align);
  134. /* aligned sized must not exceed block_size_max or we'll go out of bounds on sl_bitmap */
  135. if (aligned < tlsf_block_size_max(tlsf))
  136. {
  137. adjust = tlsf_max(aligned, block_size_min);
  138. }
  139. }
  140. return adjust;
  141. }
  142. /*
  143. ** TLSF utility functions. In most cases, these are direct translations of
  144. ** the documentation found in the white paper.
  145. */
  146. static inline __attribute__((__always_inline__)) void mapping_insert(control_t *control, size_t size, int* fli, int* sli)
  147. {
  148. int fl, sl;
  149. if (size < control->small_block_size)
  150. {
  151. /* Store small blocks in first list. */
  152. fl = 0;
  153. sl = tlsf_cast(int, size) >> 2;
  154. }
  155. else
  156. {
  157. fl = tlsf_fls(size);
  158. sl = tlsf_cast(int, size >> (fl - control->sl_index_count_log2)) ^ (1 << control->sl_index_count_log2);
  159. fl -= (control->fl_index_shift - 1);
  160. }
  161. *fli = fl;
  162. *sli = sl;
  163. }
  164. /* This version rounds up to the next block size (for allocations) */
  165. static inline __attribute__((__always_inline__)) void mapping_search(control_t *control, size_t size, int* fli, int* sli)
  166. {
  167. if (size >= control->small_block_size)
  168. {
  169. const size_t round = (1 << (tlsf_fls(size) - control->sl_index_count_log2)) - 1;
  170. size += round;
  171. }
  172. mapping_insert(control, size, fli, sli);
  173. }
  174. static inline __attribute__((__always_inline__)) block_header_t* search_suitable_block(control_t* control, int* fli, int* sli)
  175. {
  176. int fl = *fli;
  177. int sl = *sli;
  178. /*
  179. ** First, search for a block in the list associated with the given
  180. ** fl/sl index.
  181. */
  182. unsigned int sl_map = control->sl_bitmap[fl] & (~0U << sl);
  183. if (!sl_map)
  184. {
  185. /* No block exists. Search in the next largest first-level list. */
  186. const unsigned int fl_map = control->fl_bitmap & (~0U << (fl + 1));
  187. if (!fl_map)
  188. {
  189. /* No free blocks available, memory has been exhausted. */
  190. return 0;
  191. }
  192. fl = tlsf_ffs(fl_map);
  193. *fli = fl;
  194. sl_map = control->sl_bitmap[fl];
  195. }
  196. tlsf_assert(sl_map && "internal error - second level bitmap is null");
  197. sl = tlsf_ffs(sl_map);
  198. *sli = sl;
  199. /* Return the first block in the free list. */
  200. return control->blocks[fl*control->sl_index_count + sl];
  201. }
  202. /* Remove a free block from the free list.*/
  203. static inline __attribute__((__always_inline__)) void remove_free_block(control_t* control, block_header_t* block, int fl, int sl)
  204. {
  205. block_header_t* prev = block->prev_free;
  206. block_header_t* next = block->next_free;
  207. tlsf_assert(prev && "prev_free field can not be null");
  208. tlsf_assert(next && "next_free field can not be null");
  209. next->prev_free = prev;
  210. prev->next_free = next;
  211. /* If this block is the head of the free list, set new head. */
  212. if (control->blocks[fl*control->sl_index_count + sl] == block)
  213. {
  214. control->blocks[fl*control->sl_index_count + sl] = next;
  215. /* If the new head is null, clear the bitmap. */
  216. if (next == &control->block_null)
  217. {
  218. control->sl_bitmap[fl] &= ~(1 << sl);
  219. /* If the second bitmap is now empty, clear the fl bitmap. */
  220. if (!control->sl_bitmap[fl])
  221. {
  222. control->fl_bitmap &= ~(1 << fl);
  223. }
  224. }
  225. }
  226. }
  227. /* Insert a free block into the free block list. */
  228. static inline __attribute__((__always_inline__)) void insert_free_block(control_t* control, block_header_t* block, int fl, int sl)
  229. {
  230. block_header_t* current = control->blocks[fl*control->sl_index_count + sl];
  231. tlsf_assert(current && "free list cannot have a null entry");
  232. tlsf_assert(block && "cannot insert a null entry into the free list");
  233. block->next_free = current;
  234. block->prev_free = &control->block_null;
  235. current->prev_free = block;
  236. tlsf_assert(block_to_ptr(block) == align_ptr(block_to_ptr(block), ALIGN_SIZE)
  237. && "block not aligned properly");
  238. /*
  239. ** Insert the new block at the head of the list, and mark the first-
  240. ** and second-level bitmaps appropriately.
  241. */
  242. control->blocks[fl*control->sl_index_count + sl] = block;
  243. control->fl_bitmap |= (1 << fl);
  244. control->sl_bitmap[fl] |= (1 << sl);
  245. }
  246. /* Remove a given block from the free list. */
  247. static inline __attribute__((__always_inline__)) void block_remove(control_t* control, block_header_t* block)
  248. {
  249. int fl, sl;
  250. mapping_insert(control, block_size(block), &fl, &sl);
  251. remove_free_block(control, block, fl, sl);
  252. }
  253. /* Insert a given block into the free list. */
  254. static inline __attribute__((__always_inline__)) void block_insert(control_t* control, block_header_t* block)
  255. {
  256. int fl, sl;
  257. mapping_insert(control, block_size(block), &fl, &sl);
  258. insert_free_block(control, block, fl, sl);
  259. }
  260. static inline __attribute__((__always_inline__)) int block_can_split(block_header_t* block, size_t size)
  261. {
  262. return block_size(block) >= sizeof(block_header_t) + size;
  263. }
  264. /* Split a block into two, the second of which is free. */
  265. static inline __attribute__((__always_inline__)) block_header_t* block_split(block_header_t* block, size_t size)
  266. {
  267. /* Calculate the amount of space left in the remaining block.
  268. * REMINDER: remaining pointer's first field is `prev_phys_block` but this field is part of the
  269. * previous physical block. */
  270. block_header_t* remaining =
  271. offset_to_block(block_to_ptr(block), size - block_header_overhead);
  272. /* `size` passed as an argument is the first block's new size, thus, the remaining block's size
  273. * is `block_size(block) - size`. However, the block's data must be precedeed by the data size.
  274. * This field is NOT part of the size, so it has to be substracted from the calculation. */
  275. const size_t remain_size = block_size(block) - (size + block_header_overhead);
  276. tlsf_assert(block_to_ptr(remaining) == align_ptr(block_to_ptr(remaining), ALIGN_SIZE)
  277. && "remaining block not aligned properly");
  278. tlsf_assert(block_size(block) == remain_size + size + block_header_overhead);
  279. block_set_size(remaining, remain_size);
  280. tlsf_assert(block_size(remaining) >= block_size_min && "block split with invalid size");
  281. block_set_size(block, size);
  282. block_mark_as_free(remaining);
  283. /**
  284. * Here is the final outcome of this function:
  285. *
  286. * block remaining (block_ptr + size - BHO)
  287. * + +
  288. * | |
  289. * v v
  290. * +----------------------------------------------------------------------+
  291. * |0000| |xxxxxxxxxxxxxxxxxxxxxx|xxxx| |###########################|
  292. * |0000| |xxxxxxxxxxxxxxxxxxxxxx|xxxx| |###########################|
  293. * |0000| |xxxxxxxxxxxxxxxxxxxxxx|xxxx| |###########################|
  294. * |0000| |xxxxxxxxxxxxxxxxxxxxxx|xxxx| |###########################|
  295. * +----------------------------------------------------------------------+
  296. * | | | |
  297. * + +<------------------------->+ +<------------------------->
  298. * BHO `size` (argument) bytes BHO `remain_size` bytes
  299. *
  300. * Where BHO = block_header_overhead,
  301. * 0: part of the memory owned by a `block`'s previous neighbour,
  302. * x: part of the memory owned by `block`.
  303. * #: part of the memory owned by `remaining`.
  304. */
  305. return remaining;
  306. }
  307. /* Absorb a free block's storage into an adjacent previous free block. */
  308. static inline __attribute__((__always_inline__)) block_header_t* block_absorb(block_header_t* prev, block_header_t* block)
  309. {
  310. tlsf_assert(!block_is_last(prev) && "previous block can't be last");
  311. /* Note: Leaves flags untouched. */
  312. prev->size += block_size(block) + block_header_overhead;
  313. block_link_next(prev);
  314. #ifdef MULTI_HEAP_POISONING_SLOW
  315. /* next_block header needs to be replaced with a fill pattern */
  316. multi_heap_internal_poison_fill_region(block, sizeof(block_header_t), true /* free */);
  317. #endif
  318. return prev;
  319. }
  320. /* Merge a just-freed block with an adjacent previous free block. */
  321. static inline __attribute__((__always_inline__)) block_header_t* block_merge_prev(control_t* control, block_header_t* block)
  322. {
  323. if (block_is_prev_free(block))
  324. {
  325. block_header_t* prev = block_prev(block);
  326. tlsf_assert(prev && "prev physical block can't be null");
  327. tlsf_assert(block_is_free(prev) && "prev block is not free though marked as such");
  328. block_remove(control, prev);
  329. block = block_absorb(prev, block);
  330. }
  331. return block;
  332. }
  333. /* Merge a just-freed block with an adjacent free block. */
  334. static inline __attribute__((__always_inline__)) block_header_t* block_merge_next(control_t* control, block_header_t* block)
  335. {
  336. block_header_t* next = block_next(block);
  337. tlsf_assert(next && "next physical block can't be null");
  338. if (block_is_free(next))
  339. {
  340. tlsf_assert(!block_is_last(block) && "previous block can't be last");
  341. block_remove(control, next);
  342. block = block_absorb(block, next);
  343. }
  344. return block;
  345. }
  346. /* Trim any trailing block space off the end of a block, return to pool. */
  347. static inline __attribute__((__always_inline__)) void block_trim_free(control_t* control, block_header_t* block, size_t size)
  348. {
  349. tlsf_assert(block_is_free(block) && "block must be free");
  350. if (block_can_split(block, size))
  351. {
  352. block_header_t* remaining_block = block_split(block, size);
  353. block_link_next(block);
  354. block_set_prev_free(remaining_block);
  355. block_insert(control, remaining_block);
  356. }
  357. }
  358. /* Trim any trailing block space off the end of a used block, return to pool. */
  359. static inline __attribute__((__always_inline__)) void block_trim_used(control_t* control, block_header_t* block, size_t size)
  360. {
  361. tlsf_assert(!block_is_free(block) && "block must be used");
  362. if (block_can_split(block, size))
  363. {
  364. /* If the next block is free, we must coalesce. */
  365. block_header_t* remaining_block = block_split(block, size);
  366. block_set_prev_used(remaining_block);
  367. remaining_block = block_merge_next(control, remaining_block);
  368. block_insert(control, remaining_block);
  369. }
  370. }
  371. static inline __attribute__((__always_inline__)) block_header_t* block_trim_free_leading(control_t* control, block_header_t* block, size_t size)
  372. {
  373. block_header_t* remaining_block = block;
  374. if (block_can_split(block, size))
  375. {
  376. /* We want to split `block` in two: the first block will be freed and the
  377. * second block will be returned. */
  378. remaining_block = block_split(block, size - block_header_overhead);
  379. /* `remaining_block` is the second block, mark its predecessor (first
  380. * block) as free. */
  381. block_set_prev_free(remaining_block);
  382. block_link_next(block);
  383. /* Put back the first block into the free memory list. */
  384. block_insert(control, block);
  385. }
  386. return remaining_block;
  387. }
  388. static inline __attribute__((__always_inline__)) block_header_t* block_locate_free(control_t* control, size_t size)
  389. {
  390. int fl = 0, sl = 0;
  391. block_header_t* block = 0;
  392. if (size)
  393. {
  394. mapping_search(control, size, &fl, &sl);
  395. /*
  396. ** mapping_search can futz with the size, so for excessively large sizes it can sometimes wind up
  397. ** with indices that are off the end of the block array.
  398. ** So, we protect against that here, since this is the only callsite of mapping_search.
  399. ** Note that we don't need to check sl, since it comes from a modulo operation that guarantees it's always in range.
  400. */
  401. if (fl < control->fl_index_count)
  402. {
  403. block = search_suitable_block(control, &fl, &sl);
  404. }
  405. }
  406. if (block)
  407. {
  408. tlsf_assert(block_size(block) >= size);
  409. remove_free_block(control, block, fl, sl);
  410. }
  411. return block;
  412. }
  413. static inline __attribute__((__always_inline__)) void* block_prepare_used(control_t* control, block_header_t* block, size_t size)
  414. {
  415. void* p = 0;
  416. if (block)
  417. {
  418. tlsf_assert(size && "size must be non-zero");
  419. block_trim_free(control, block, size);
  420. block_mark_as_used(block);
  421. p = block_to_ptr(block);
  422. }
  423. return p;
  424. }
  425. /* Clear structure and point all empty lists at the null block. */
  426. static void control_construct(control_t* control, size_t bytes)
  427. {
  428. int i, j;
  429. control->block_null.next_free = &control->block_null;
  430. control->block_null.prev_free = &control->block_null;
  431. /* find the closest ^2 for first layer */
  432. i = (bytes - 1) / (16 * 1024);
  433. control->fl_index_max = FL_INDEX_MAX_MIN + sizeof(i) * 8 - __builtin_clz(i);
  434. /* adapt second layer to the pool */
  435. if (bytes <= 16 * 1024) control->sl_index_count_log2 = 3;
  436. else if (bytes <= 256 * 1024) control->sl_index_count_log2 = 4;
  437. else control->sl_index_count_log2 = 5;
  438. control->fl_index_shift = (control->sl_index_count_log2 + ALIGN_SIZE_LOG2);
  439. control->sl_index_count = 1 << control->sl_index_count_log2;
  440. control->fl_index_count = control->fl_index_max - control->fl_index_shift + 1;
  441. control->small_block_size = 1 << control->fl_index_shift;
  442. control->fl_bitmap = 0;
  443. control->sl_bitmap = align_ptr(control + 1, sizeof(*control->sl_bitmap));
  444. control->blocks = align_ptr(control->sl_bitmap + control->fl_index_count, sizeof(*control->blocks));
  445. control->size = (void*) (control->blocks + control->sl_index_count * control->fl_index_count) - (void*) control;
  446. ESP_EARLY_LOGW( "REMOVE", "NEW POOL of %d bytes, ctrl_size: %d sli_c:%d fli_c:%d small_b %d max_b:%d",
  447. bytes,
  448. control->size, control->sl_index_count, control->fl_index_count,
  449. control->small_block_size, 1 << control->fl_index_max );
  450. /* SL_INDEX_COUNT must be <= number of bits in sl_bitmap's storage type. */
  451. tlsf_assert(sizeof(unsigned int) * CHAR_BIT >= control->sl_index_count && "CHAR_BIT less than sl_index_count");
  452. /* Ensure we've properly tuned our sizes. */
  453. tlsf_assert(ALIGN_SIZE == control->small_block_size / control->sl_index_count && "ALIGN_SIZE does not match");
  454. for (i = 0; i < control->fl_index_count; ++i)
  455. {
  456. control->sl_bitmap[i] = 0;
  457. for (j = 0; j < control->sl_index_count; ++j)
  458. {
  459. control->blocks[i*control->sl_index_count + j] = &control->block_null;
  460. }
  461. }
  462. }
  463. /*
  464. ** Debugging utilities.
  465. */
  466. typedef struct integrity_t
  467. {
  468. int prev_status;
  469. int status;
  470. } integrity_t;
  471. #define tlsf_insist(x) { tlsf_assert(x); if (!(x)) { status--; } }
  472. static void integrity_walker(void* ptr, size_t size, int used, void* user)
  473. {
  474. block_header_t* block = block_from_ptr(ptr);
  475. integrity_t* integ = tlsf_cast(integrity_t*, user);
  476. const int this_prev_status = block_is_prev_free(block) ? 1 : 0;
  477. const int this_status = block_is_free(block) ? 1 : 0;
  478. const size_t this_block_size = block_size(block);
  479. int status = 0;
  480. (void)used;
  481. tlsf_insist(integ->prev_status == this_prev_status && "prev status incorrect");
  482. tlsf_insist(size == this_block_size && "block size incorrect");
  483. integ->prev_status = this_status;
  484. integ->status += status;
  485. }
  486. int tlsf_check(tlsf_t tlsf)
  487. {
  488. int i, j;
  489. control_t* control = tlsf_cast(control_t*, tlsf);
  490. int status = 0;
  491. /* Check that the free lists and bitmaps are accurate. */
  492. for (i = 0; i < control->fl_index_count; ++i)
  493. {
  494. for (j = 0; j < control->sl_index_count; ++j)
  495. {
  496. const int fl_map = control->fl_bitmap & (1 << i);
  497. const int sl_list = control->sl_bitmap[i];
  498. const int sl_map = sl_list & (1 << j);
  499. const block_header_t* block = control->blocks[i*control->sl_index_count + j];
  500. /* Check that first- and second-level lists agree. */
  501. if (!fl_map)
  502. {
  503. tlsf_insist(!sl_map && "second-level map must be null");
  504. }
  505. if (!sl_map)
  506. {
  507. tlsf_insist(block == &control->block_null && "block list must be null");
  508. continue;
  509. }
  510. /* Check that there is at least one free block. */
  511. tlsf_insist(sl_list && "no free blocks in second-level map");
  512. tlsf_insist(block != &control->block_null && "block should not be null");
  513. while (block != &control->block_null)
  514. {
  515. int fli, sli;
  516. tlsf_insist(block_is_free(block) && "block should be free");
  517. tlsf_insist(!block_is_prev_free(block) && "blocks should have coalesced");
  518. tlsf_insist(!block_is_free(block_next(block)) && "blocks should have coalesced");
  519. tlsf_insist(block_is_prev_free(block_next(block)) && "block should be free");
  520. tlsf_insist(block_size(block) >= block_size_min && "block not minimum size");
  521. mapping_insert(control, block_size(block), &fli, &sli);
  522. tlsf_insist(fli == i && sli == j && "block size indexed in wrong list");
  523. block = block->next_free;
  524. }
  525. }
  526. }
  527. return status;
  528. }
  529. #undef tlsf_insist
  530. static void default_walker(void* ptr, size_t size, int used, void* user)
  531. {
  532. (void)user;
  533. printf("\t%p %s size: %x (%p)\n", ptr, used ? "used" : "free", (unsigned int)size, block_from_ptr(ptr));
  534. }
  535. void tlsf_walk_pool(pool_t pool, tlsf_walker walker, void* user)
  536. {
  537. tlsf_walker pool_walker = walker ? walker : default_walker;
  538. block_header_t* block =
  539. offset_to_block(pool, -(int)block_header_overhead);
  540. while (block && !block_is_last(block))
  541. {
  542. pool_walker(
  543. block_to_ptr(block),
  544. block_size(block),
  545. !block_is_free(block),
  546. user);
  547. block = block_next(block);
  548. }
  549. }
  550. size_t tlsf_block_size(void* ptr)
  551. {
  552. size_t size = 0;
  553. if (ptr)
  554. {
  555. const block_header_t* block = block_from_ptr(ptr);
  556. size = block_size(block);
  557. }
  558. return size;
  559. }
  560. int tlsf_check_pool(pool_t pool)
  561. {
  562. /* Check that the blocks are physically correct. */
  563. integrity_t integ = { 0, 0 };
  564. tlsf_walk_pool(pool, integrity_walker, &integ);
  565. return integ.status;
  566. }
  567. size_t tlsf_fit_size(tlsf_t tlsf, size_t size)
  568. {
  569. /* because it's GoodFit, allocable size is one range lower */
  570. if (size)
  571. {
  572. control_t* control = tlsf_cast(control_t*, tlsf);
  573. size_t sl_interval = (1 << ((sizeof(size_t) * 8 - 1) - __builtin_clz(size))) / control->sl_index_count;
  574. return size & ~(sl_interval - 1);
  575. }
  576. return 0;
  577. }
  578. /*
  579. ** Size of the TLSF structures in a given memory block passed to
  580. ** tlsf_create, equal to the size of a control_t
  581. */
  582. size_t tlsf_size(tlsf_t tlsf)
  583. {
  584. if (tlsf)
  585. {
  586. control_t* control = tlsf_cast(control_t*, tlsf);
  587. return control->size;
  588. }
  589. /* no tlsf, we'll just return a min size */
  590. return sizeof(control_t) +
  591. sizeof(int) * SL_INDEX_COUNT_MIN +
  592. sizeof(block_header_t*) * SL_INDEX_COUNT_MIN * FL_INDEX_COUNT_MIN;
  593. }
  594. size_t tlsf_align_size(void)
  595. {
  596. return ALIGN_SIZE;
  597. }
  598. size_t tlsf_block_size_min(void)
  599. {
  600. return block_size_min;
  601. }
  602. size_t tlsf_block_size_max(tlsf_t tlsf)
  603. {
  604. control_t* control = tlsf_cast(control_t*, tlsf);
  605. return tlsf_cast(size_t, 1) << control->fl_index_max;
  606. }
  607. /*
  608. ** Overhead of the TLSF structures in a given memory block passed to
  609. ** tlsf_add_pool, equal to the overhead of a free block and the
  610. ** sentinel block.
  611. */
  612. size_t tlsf_pool_overhead(void)
  613. {
  614. return 2 * block_header_overhead;
  615. }
  616. size_t tlsf_alloc_overhead(void)
  617. {
  618. return block_header_overhead;
  619. }
  620. pool_t tlsf_add_pool(tlsf_t tlsf, void* mem, size_t bytes)
  621. {
  622. block_header_t* block;
  623. block_header_t* next;
  624. const size_t pool_overhead = tlsf_pool_overhead();
  625. const size_t pool_bytes = align_down(bytes - pool_overhead, ALIGN_SIZE);
  626. if (((ptrdiff_t)mem % ALIGN_SIZE) != 0)
  627. {
  628. printf("tlsf_add_pool: Memory must be aligned by %u bytes.\n",
  629. (unsigned int)ALIGN_SIZE);
  630. return 0;
  631. }
  632. if (pool_bytes < block_size_min || pool_bytes > tlsf_block_size_max(tlsf))
  633. {
  634. #if defined (TLSF_64BIT)
  635. printf("tlsf_add_pool: Memory size must be between 0x%x and 0x%x00 bytes.\n",
  636. (unsigned int)(pool_overhead + block_size_min),
  637. (unsigned int)((pool_overhead + tlsf_block_size_max(tlsf)) / 256));
  638. #else
  639. printf("tlsf_add_pool: Memory size must be between %u and %u bytes.\n",
  640. (unsigned int)(pool_overhead + block_size_min),
  641. (unsigned int)(pool_overhead + tlsf_block_size_max(tlsf)));
  642. #endif
  643. return 0;
  644. }
  645. /*
  646. ** Create the main free block. Offset the start of the block slightly
  647. ** so that the prev_phys_block field falls outside of the pool -
  648. ** it will never be used.
  649. */
  650. block = offset_to_block(mem, -(tlsfptr_t)block_header_overhead);
  651. block_set_size(block, pool_bytes);
  652. block_set_free(block);
  653. block_set_prev_used(block);
  654. block_insert(tlsf_cast(control_t*, tlsf), block);
  655. /* Split the block to create a zero-size sentinel block. */
  656. next = block_link_next(block);
  657. block_set_size(next, 0);
  658. block_set_used(next);
  659. block_set_prev_free(next);
  660. return mem;
  661. }
  662. void tlsf_remove_pool(tlsf_t tlsf, pool_t pool)
  663. {
  664. control_t* control = tlsf_cast(control_t*, tlsf);
  665. block_header_t* block = offset_to_block(pool, -(int)block_header_overhead);
  666. int fl = 0, sl = 0;
  667. tlsf_assert(block_is_free(block) && "block should be free");
  668. tlsf_assert(!block_is_free(block_next(block)) && "next block should not be free");
  669. tlsf_assert(block_size(block_next(block)) == 0 && "next block size should be zero");
  670. mapping_insert(control, block_size(block), &fl, &sl);
  671. remove_free_block(control, block, fl, sl);
  672. }
  673. /*
  674. ** TLSF main interface.
  675. */
  676. tlsf_t tlsf_create(void* mem, size_t max_bytes)
  677. {
  678. #if _DEBUG
  679. if (test_ffs_fls())
  680. {
  681. return 0;
  682. }
  683. #endif
  684. if (((tlsfptr_t)mem % ALIGN_SIZE) != 0)
  685. {
  686. printf("tlsf_create: Memory must be aligned to %u bytes.\n",
  687. (unsigned int)ALIGN_SIZE);
  688. return 0;
  689. }
  690. control_construct(tlsf_cast(control_t*, mem), max_bytes);
  691. return tlsf_cast(tlsf_t, mem);
  692. }
  693. pool_t tlsf_get_pool(tlsf_t tlsf)
  694. {
  695. return tlsf_cast(pool_t, (char*)tlsf + tlsf_size(tlsf));
  696. }
  697. tlsf_t tlsf_create_with_pool(void* mem, size_t pool_bytes, size_t max_bytes)
  698. {
  699. tlsf_t tlsf = tlsf_create(mem, max_bytes ? max_bytes : pool_bytes);
  700. tlsf_add_pool(tlsf, (char*)mem + tlsf_size(tlsf), pool_bytes - tlsf_size(tlsf));
  701. return tlsf;
  702. }
  703. void* tlsf_malloc(tlsf_t tlsf, size_t size)
  704. {
  705. control_t* control = tlsf_cast(control_t*, tlsf);
  706. size_t adjust = adjust_request_size(tlsf, size, ALIGN_SIZE);
  707. block_header_t* block = block_locate_free(control, adjust);
  708. return block_prepare_used(control, block, adjust);
  709. }
  710. /**
  711. * @brief Allocate memory of at least `size` bytes where byte at `data_offset` will be aligned to `alignment`.
  712. *
  713. * This function will allocate memory pointed by `ptr`. However, the byte at `data_offset` of
  714. * this piece of memory (i.e., byte at `ptr` + `data_offset`) will be aligned to `alignment`.
  715. * This function is useful for allocating memory that will internally have a header, and the
  716. * usable memory following the header (i.e. `ptr` + `data_offset`) must be aligned.
  717. *
  718. * For example, a call to `multi_heap_aligned_alloc_impl_offs(heap, 64, 256, 20)` will return a
  719. * pointer `ptr` to free memory of minimum 64 bytes, where `ptr + 20` is aligned on `256`.
  720. * So `(ptr + 20) % 256` equals 0.
  721. *
  722. * @param tlsf TLSF structure to allocate memory from.
  723. * @param align Alignment for the returned pointer's offset.
  724. * @param size Minimum size, in bytes, of the memory to allocate INCLUDING
  725. * `data_offset` bytes.
  726. * @param data_offset Offset to be aligned on `alignment`. This can be 0, in
  727. * this case, the returned pointer will be aligned on
  728. * `alignment`. If it is not a multiple of CPU word size,
  729. * it will be aligned up to the closest multiple of it.
  730. *
  731. * @return pointer to free memory.
  732. */
  733. void* tlsf_memalign_offs(tlsf_t tlsf, size_t align, size_t size, size_t data_offset)
  734. {
  735. control_t* control = tlsf_cast(control_t*, tlsf);
  736. const size_t adjust = adjust_request_size(tlsf, size, ALIGN_SIZE);
  737. const size_t off_adjust = align_up(data_offset, ALIGN_SIZE);
  738. /*
  739. ** We must allocate an additional minimum block size bytes so that if
  740. ** our free block will leave an alignment gap which is smaller, we can
  741. ** trim a leading free block and release it back to the pool. We must
  742. ** do this because the previous physical block is in use, therefore
  743. ** the prev_phys_block field is not valid, and we can't simply adjust
  744. ** the size of that block.
  745. */
  746. const size_t gap_minimum = sizeof(block_header_t) + off_adjust;
  747. /* The offset is included in both `adjust` and `gap_minimum`, so we
  748. ** need to subtract it once.
  749. */
  750. const size_t size_with_gap = adjust_request_size(tlsf, adjust + align + gap_minimum - off_adjust, align);
  751. /*
  752. ** If alignment is less than or equals base alignment, we're done.
  753. ** If we requested 0 bytes, return null, as tlsf_malloc(0) does.
  754. */
  755. const size_t aligned_size = (adjust && align > ALIGN_SIZE) ? size_with_gap : adjust;
  756. block_header_t* block = block_locate_free(control, aligned_size);
  757. /* This can't be a static assert. */
  758. tlsf_assert(sizeof(block_header_t) == block_size_min + block_header_overhead);
  759. if (block)
  760. {
  761. void* ptr = block_to_ptr(block);
  762. void* aligned = align_ptr(ptr, align);
  763. size_t gap = tlsf_cast(size_t,
  764. tlsf_cast(tlsfptr_t, aligned) - tlsf_cast(tlsfptr_t, ptr));
  765. /*
  766. ** If gap size is too small or if there is not gap but we need one,
  767. ** offset to next aligned boundary.
  768. */
  769. if ((gap && gap < gap_minimum) || (!gap && off_adjust))
  770. {
  771. const size_t gap_remain = gap_minimum - gap;
  772. const size_t offset = tlsf_max(gap_remain, align);
  773. const void* next_aligned = tlsf_cast(void*,
  774. tlsf_cast(tlsfptr_t, aligned) + offset);
  775. aligned = align_ptr(next_aligned, align);
  776. gap = tlsf_cast(size_t,
  777. tlsf_cast(tlsfptr_t, aligned) - tlsf_cast(tlsfptr_t, ptr));
  778. }
  779. if (gap)
  780. {
  781. tlsf_assert(gap >= gap_minimum && "gap size too small");
  782. block = block_trim_free_leading(control, block, gap - off_adjust);
  783. }
  784. }
  785. /* Preparing the block will also the trailing free memory. */
  786. return block_prepare_used(control, block, adjust);
  787. }
  788. /**
  789. * @brief Same as `tlsf_memalign_offs` function but with a 0 offset.
  790. * The pointer returned is aligned on `align`.
  791. */
  792. void* tlsf_memalign(tlsf_t tlsf, size_t align, size_t size)
  793. {
  794. return tlsf_memalign_offs(tlsf, align, size, 0);
  795. }
  796. void tlsf_free(tlsf_t tlsf, void* ptr)
  797. {
  798. /* Don't attempt to free a NULL pointer. */
  799. if (ptr)
  800. {
  801. control_t* control = tlsf_cast(control_t*, tlsf);
  802. block_header_t* block = block_from_ptr(ptr);
  803. tlsf_assert(!block_is_free(block) && "block already marked as free");
  804. block_mark_as_free(block);
  805. block = block_merge_prev(control, block);
  806. block = block_merge_next(control, block);
  807. block_insert(control, block);
  808. }
  809. }
  810. /*
  811. ** The TLSF block information provides us with enough information to
  812. ** provide a reasonably intelligent implementation of realloc, growing or
  813. ** shrinking the currently allocated block as required.
  814. **
  815. ** This routine handles the somewhat esoteric edge cases of realloc:
  816. ** - a non-zero size with a null pointer will behave like malloc
  817. ** - a zero size with a non-null pointer will behave like free
  818. ** - a request that cannot be satisfied will leave the original buffer
  819. ** untouched
  820. ** - an extended buffer size will leave the newly-allocated area with
  821. ** contents undefined
  822. */
  823. void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size)
  824. {
  825. control_t* control = tlsf_cast(control_t*, tlsf);
  826. void* p = 0;
  827. /* Zero-size requests are treated as free. */
  828. if (ptr && size == 0)
  829. {
  830. tlsf_free(tlsf, ptr);
  831. }
  832. /* Requests with NULL pointers are treated as malloc. */
  833. else if (!ptr)
  834. {
  835. p = tlsf_malloc(tlsf, size);
  836. }
  837. else
  838. {
  839. block_header_t* block = block_from_ptr(ptr);
  840. block_header_t* next = block_next(block);
  841. const size_t cursize = block_size(block);
  842. const size_t combined = cursize + block_size(next) + block_header_overhead;
  843. const size_t adjust = adjust_request_size(tlsf, size, ALIGN_SIZE);
  844. tlsf_assert(!block_is_free(block) && "block already marked as free");
  845. /*
  846. ** If the next block is used, or when combined with the current
  847. ** block, does not offer enough space, we must reallocate and copy.
  848. */
  849. if (adjust > cursize && (!block_is_free(next) || adjust > combined))
  850. {
  851. p = tlsf_malloc(tlsf, size);
  852. if (p)
  853. {
  854. const size_t minsize = tlsf_min(cursize, size);
  855. memcpy(p, ptr, minsize);
  856. tlsf_free(tlsf, ptr);
  857. }
  858. }
  859. else
  860. {
  861. /* Do we need to expand to the next block? */
  862. if (adjust > cursize)
  863. {
  864. block_merge_next(control, block);
  865. block_mark_as_used(block);
  866. }
  867. /* Trim the resulting block and return the original pointer. */
  868. block_trim_used(control, block, adjust);
  869. p = ptr;
  870. }
  871. }
  872. return p;
  873. }