heap_tlsf.c 29 KB

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