tlsf.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. /*
  2. * SPDX-FileCopyrightText: 2006-2016 Matthew Conte
  3. *
  4. * SPDX-License-Identifier: BSD-3-Clause
  5. */
  6. #include <string.h>
  7. #include <limits.h>
  8. #include <stdio.h>
  9. #include <stdint.h>
  10. #include "tlsf.h"
  11. #undef printf
  12. #define printf(...)
  13. #include "tlsf_block_functions.h"
  14. #include "tlsf_control_functions.h"
  15. /*
  16. ** Static assertion mechanism.
  17. */
  18. #define _tlsf_glue2(x, y) x##y
  19. #define _tlsf_glue(x, y) _tlsf_glue2(x, y)
  20. #define tlsf_static_assert(exp) typedef char _tlsf_glue(static_assert, __LINE__)[(exp) ? 1 : -1]
  21. /* This code has been tested on 32- and 64-bit (LP/LLP) architectures. */
  22. tlsf_static_assert(sizeof(int) * CHAR_BIT == 32);
  23. tlsf_static_assert(sizeof(size_t) * CHAR_BIT >= 32);
  24. tlsf_static_assert(sizeof(size_t) * CHAR_BIT <= 64);
  25. /* Clear structure and point all empty lists at the null block. */
  26. static control_t *control_construct(control_t *control, size_t bytes)
  27. {
  28. // check that the requested size can at least hold the control_t. This will allow us
  29. // to fill in the field of control_t necessary to determine the final size of
  30. // the metadata overhead and check that the requested size can hold
  31. // this data and at least a block of minimum size
  32. if (bytes < sizeof(control_t)) { return NULL; }
  33. /* Find the closest power of two for first layer */
  34. control->fl_index_max = 32 - __builtin_clz(bytes);
  35. /* Adapt second layer to the pool */
  36. if (bytes <= 64 * 1024) { control->sl_index_count_log2 = 3; }
  37. else if (bytes <= 256 * 1024) { control->sl_index_count_log2 = 4; }
  38. else
  39. {
  40. control->sl_index_count_log2 = 5;
  41. }
  42. control->fl_index_shift = (control->sl_index_count_log2 + ALIGN_SIZE_LOG2);
  43. control->sl_index_count = 1 << control->sl_index_count_log2;
  44. control->fl_index_count = control->fl_index_max - control->fl_index_shift + 1;
  45. control->small_block_size = 1 << control->fl_index_shift;
  46. // the total size fo the metadata overhead is the size of the control_t
  47. // added to the size of the sl_bitmaps and the size of blocks
  48. control->size = sizeof(control_t) + (sizeof(*control->sl_bitmap) * control->fl_index_count) +
  49. (sizeof(*control->blocks) * (control->fl_index_count * control->sl_index_count));
  50. // check that the requested size can hold the whole control structure and
  51. // a small block at least
  52. if (bytes < control->size + block_size_min) { return NULL; }
  53. control->block_null.next_free = &control->block_null;
  54. control->block_null.prev_free = &control->block_null;
  55. control->fl_bitmap = 0;
  56. control->sl_bitmap = align_ptr(control + 1, sizeof(*control->sl_bitmap));
  57. control->blocks = align_ptr(control->sl_bitmap + control->fl_index_count, sizeof(*control->blocks));
  58. /* SL_INDEX_COUNT must be <= number of bits in sl_bitmap's storage type. */
  59. tlsf_assert(sizeof(unsigned int) * CHAR_BIT >= control->sl_index_count && "CHAR_BIT less than sl_index_count");
  60. /* Ensure we've properly tuned our sizes. */
  61. tlsf_assert(ALIGN_SIZE == control->small_block_size / control->sl_index_count); // ALIGN_SIZE does not match");
  62. for (int i = 0; i < control->fl_index_count; ++i)
  63. {
  64. control->sl_bitmap[i] = 0;
  65. for (int j = 0; j < control->sl_index_count; ++j)
  66. {
  67. control->blocks[i * control->sl_index_count + j] = &control->block_null;
  68. }
  69. }
  70. return control;
  71. }
  72. /*
  73. ** Debugging utilities.
  74. */
  75. typedef struct integrity_t
  76. {
  77. int prev_status;
  78. int status;
  79. } integrity_t;
  80. #define tlsf_insist(x) \
  81. { \
  82. if (!(x)) { status--; } \
  83. }
  84. static bool integrity_walker(void *ptr, size_t size, int used, void *user)
  85. {
  86. block_header_t *block = block_from_ptr(ptr);
  87. integrity_t *integ = tlsf_cast(integrity_t *, user);
  88. const int this_prev_status = block_is_prev_free(block) ? 1 : 0;
  89. const int this_status = block_is_free(block) ? 1 : 0;
  90. const size_t this_block_size = block_size(block);
  91. int status = 0;
  92. tlsf_insist(integ->prev_status == this_prev_status && "prev status incorrect");
  93. tlsf_insist(size == this_block_size && "block size incorrect");
  94. if (tlsf_check_hook != NULL)
  95. {
  96. /* block_size(block) returns the size of the usable memory when the block is allocated.
  97. * As the block under test is free, we need to subtract to the block size the next_free
  98. * and prev_free fields of the block header as they are not a part of the usable memory
  99. * when the block is free. In addition, we also need to subtract the size of prev_phys_block
  100. * as this field is in fact part of the current free block and not part of the next (allocated)
  101. * block. Check the comments in block_split function for more details.
  102. */
  103. const size_t actual_free_block_size =
  104. used ? this_block_size : this_block_size - offsetof(block_header_t, next_free) - block_header_overhead;
  105. void *ptr_block = used ? (void *)block + block_start_offset : (void *)block + sizeof(block_header_t);
  106. tlsf_insist(tlsf_check_hook(ptr_block, actual_free_block_size, !used));
  107. }
  108. integ->prev_status = this_status;
  109. integ->status += status;
  110. return true;
  111. }
  112. int tlsf_check(tlsf_t tlsf)
  113. {
  114. int i, j;
  115. control_t *control = tlsf_cast(control_t *, tlsf);
  116. int status = 0;
  117. /* Check that the free lists and bitmaps are accurate. */
  118. for (i = 0; i < control->fl_index_count; ++i)
  119. {
  120. for (j = 0; j < control->sl_index_count; ++j)
  121. {
  122. const int fl_map = control->fl_bitmap & (1U << i);
  123. const int sl_list = control->sl_bitmap[i];
  124. const int sl_map = sl_list & (1U << j);
  125. const block_header_t *block = control->blocks[i * control->sl_index_count + j];
  126. /* Check that first- and second-level lists agree. */
  127. if (!fl_map) { tlsf_insist(!sl_map && "second-level map must be null"); }
  128. if (!sl_map)
  129. {
  130. tlsf_insist(block == &control->block_null && "block list must be null");
  131. continue;
  132. }
  133. /* Check that there is at least one free block. */
  134. tlsf_insist(sl_list && "no free blocks in second-level map");
  135. tlsf_insist(block != &control->block_null && "block should not be null");
  136. while (block != &control->block_null)
  137. {
  138. int fli, sli;
  139. const bool is_block_free = block_is_free(block);
  140. tlsf_insist(is_block_free && "block should be free");
  141. tlsf_insist(!block_is_prev_free(block) && "blocks should have coalesced");
  142. tlsf_insist(!block_is_free(block_next(block)) && "blocks should have coalesced");
  143. tlsf_insist(block_is_prev_free(block_next(block)) && "block should be free");
  144. tlsf_insist(block_size(block) >= block_size_min && "block not minimum size");
  145. mapping_insert(control, block_size(block), &fli, &sli);
  146. tlsf_insist(fli == i && sli == j && "block size indexed in wrong list");
  147. block = block->next_free;
  148. }
  149. }
  150. }
  151. return status;
  152. }
  153. #undef tlsf_insist
  154. static bool default_walker(void *ptr, size_t size, int used, void *user)
  155. {
  156. (void)user;
  157. printf("\t%p %s size: %x (%p)\n", ptr, used ? "used" : "free", (unsigned int)size, block_from_ptr(ptr));
  158. return true;
  159. }
  160. void tlsf_walk_pool(pool_t pool, tlsf_walker walker, void *user)
  161. {
  162. tlsf_walker pool_walker = walker ? walker : default_walker;
  163. block_header_t *block = offset_to_block(pool, -(int)block_header_overhead);
  164. bool ret_val = true;
  165. while (block && !block_is_last(block) && ret_val == true)
  166. {
  167. ret_val = pool_walker(block_to_ptr(block), block_size(block), !block_is_free(block), user);
  168. if (ret_val == true) { block = block_next(block); }
  169. }
  170. }
  171. size_t tlsf_block_size(void *ptr)
  172. {
  173. size_t size = 0;
  174. if (ptr)
  175. {
  176. const block_header_t *block = block_from_ptr(ptr);
  177. size = block_size(block);
  178. }
  179. return size;
  180. }
  181. int tlsf_check_pool(pool_t pool)
  182. {
  183. /* Check that the blocks are physically correct. */
  184. integrity_t integ = {0, 0};
  185. tlsf_walk_pool(pool, integrity_walker, &integ);
  186. return integ.status;
  187. }
  188. size_t tlsf_fit_size(tlsf_t tlsf, size_t size)
  189. {
  190. if (size == 0 || tlsf == NULL) { return 0; }
  191. control_t *control = tlsf_cast(control_t *, tlsf);
  192. if (size < control->small_block_size) { return adjust_request_size(tlsf, size, ALIGN_SIZE); }
  193. /* because it's GoodFit, allocable size is one range lower */
  194. size_t sl_interval;
  195. sl_interval = (1 << (32 - __builtin_clz(size) - 1)) / control->sl_index_count;
  196. return size & ~(sl_interval - 1);
  197. }
  198. /*
  199. ** Size of the TLSF structures in a given memory block passed to
  200. ** tlsf_create, equal to the size of a control_t
  201. */
  202. size_t tlsf_size(tlsf_t tlsf)
  203. {
  204. if (tlsf == NULL) { return 0; }
  205. control_t *control = tlsf_cast(control_t *, tlsf);
  206. return control->size;
  207. }
  208. /*
  209. ** Overhead of the TLSF structures in a given memory block passed to
  210. ** tlsf_add_pool, equal to the overhead of a free block and the
  211. ** sentinel block.
  212. */
  213. size_t tlsf_pool_overhead(void) { return 2 * block_header_overhead; }
  214. size_t tlsf_alloc_overhead(void) { return block_header_overhead; }
  215. pool_t tlsf_add_pool(tlsf_t tlsf, void *mem, size_t bytes)
  216. {
  217. block_header_t *block;
  218. block_header_t *next;
  219. const size_t pool_overhead = tlsf_pool_overhead();
  220. const size_t pool_bytes = align_down(bytes - pool_overhead, ALIGN_SIZE);
  221. if (((ptrdiff_t)mem % ALIGN_SIZE) != 0)
  222. {
  223. printf("tlsf_add_pool: Memory must be aligned by %u bytes.\n", (unsigned int)ALIGN_SIZE);
  224. return 0;
  225. }
  226. if (pool_bytes < block_size_min || pool_bytes > tlsf_block_size_max(tlsf))
  227. {
  228. #if defined(TLSF_64BIT)
  229. printf("tlsf_add_pool: Memory size must be between 0x%x and 0x%x00 bytes.\n",
  230. (unsigned int)(pool_overhead + block_size_min), (unsigned int)((pool_overhead + tlsf_block_size_max(tlsf)) / 256));
  231. #else
  232. printf("tlsf_add_pool: Memory size must be between %u and %u bytes.\n", (unsigned int)(pool_overhead + block_size_min),
  233. (unsigned int)(pool_overhead + tlsf_block_size_max(tlsf)));
  234. #endif
  235. return 0;
  236. }
  237. /*
  238. ** Create the main free block. Offset the start of the block slightly
  239. ** so that the prev_phys_block field falls outside of the pool -
  240. ** it will never be used.
  241. */
  242. block = offset_to_block(mem, -(tlsfptr_t)block_header_overhead);
  243. block_set_size(block, pool_bytes);
  244. block_set_free(block);
  245. block_set_prev_used(block);
  246. block_insert(tlsf_cast(control_t *, tlsf), block);
  247. /* Split the block to create a zero-size sentinel block. */
  248. next = block_link_next(block);
  249. block_set_size(next, 0);
  250. block_set_used(next);
  251. block_set_prev_free(next);
  252. return mem;
  253. }
  254. void tlsf_remove_pool(tlsf_t tlsf, pool_t pool)
  255. {
  256. control_t *control = tlsf_cast(control_t *, tlsf);
  257. block_header_t *block = offset_to_block(pool, -(int)block_header_overhead);
  258. int fl = 0, sl = 0;
  259. tlsf_assert(block_is_free(block) && "block should be free");
  260. tlsf_assert(!block_is_free(block_next(block)) && "next block should not be free");
  261. tlsf_assert(block_size(block_next(block)) == 0 && "next block size should be zero");
  262. mapping_insert(control, block_size(block), &fl, &sl);
  263. remove_free_block(control, block, fl, sl);
  264. }
  265. /*
  266. ** TLSF main interface.
  267. */
  268. #if _DEBUG
  269. int test_ffs_fls()
  270. {
  271. /* Verify ffs/fls work properly. */
  272. int rv = 0;
  273. rv += (tlsf_ffs(0) == -1) ? 0 : 0x1;
  274. rv += (tlsf_fls(0) == -1) ? 0 : 0x2;
  275. rv += (tlsf_ffs(1) == 0) ? 0 : 0x4;
  276. rv += (tlsf_fls(1) == 0) ? 0 : 0x8;
  277. rv += (tlsf_ffs(0x80000000) == 31) ? 0 : 0x10;
  278. rv += (tlsf_ffs(0x80008000) == 15) ? 0 : 0x20;
  279. rv += (tlsf_fls(0x80000008) == 31) ? 0 : 0x40;
  280. rv += (tlsf_fls(0x7FFFFFFF) == 30) ? 0 : 0x80;
  281. #if defined(TLSF_64BIT)
  282. rv += (tlsf_fls_sizet(0x80000000) == 31) ? 0 : 0x100;
  283. rv += (tlsf_fls_sizet(0x100000000) == 32) ? 0 : 0x200;
  284. rv += (tlsf_fls_sizet(0xffffffffffffffff) == 63) ? 0 : 0x400;
  285. #endif
  286. if (rv) { printf("test_ffs_fls: %x ffs/fls tests failed.\n", rv); }
  287. return rv;
  288. }
  289. #endif
  290. tlsf_t tlsf_create(void *mem, size_t max_bytes)
  291. {
  292. #if _DEBUG
  293. if (test_ffs_fls()) { return NULL; }
  294. #endif
  295. if (mem == NULL) { return NULL; }
  296. if (((tlsfptr_t)mem % ALIGN_SIZE) != 0)
  297. {
  298. printf("tlsf_create: Memory must be aligned to %u bytes.\n", (unsigned int)ALIGN_SIZE);
  299. return NULL;
  300. }
  301. control_t *control_ptr = control_construct(tlsf_cast(control_t *, mem), max_bytes);
  302. return tlsf_cast(tlsf_t, control_ptr);
  303. }
  304. tlsf_t tlsf_create_with_pool(void *mem, size_t pool_bytes, size_t max_bytes)
  305. {
  306. tlsf_t tlsf = tlsf_create(mem, max_bytes ? max_bytes : pool_bytes);
  307. if (tlsf != NULL)
  308. {
  309. tlsf_add_pool(tlsf, (char *)mem + tlsf_size(tlsf), pool_bytes - tlsf_size(tlsf));
  310. control_t *control = tlsf_cast(control_t *, tlsf);
  311. control->mem_rec.total = pool_bytes - tlsf_size(tlsf) - tlsf_pool_overhead();
  312. control->mem_rec.used = 0;
  313. control->mem_rec.max_used = 0;
  314. }
  315. return tlsf;
  316. }
  317. void tlsf_destroy(tlsf_t tlsf)
  318. {
  319. /* Nothing to do. */
  320. (void)tlsf;
  321. }
  322. pool_t tlsf_get_pool(tlsf_t tlsf) { return tlsf_cast(pool_t, (char *)tlsf + tlsf_size(tlsf)); }
  323. void *tlsf_malloc(tlsf_t tlsf, size_t size)
  324. {
  325. control_t *control = tlsf_cast(control_t *, tlsf);
  326. size_t adjust = adjust_request_size(tlsf, size, ALIGN_SIZE);
  327. // Returned size is 0 when the requested size is larger than the max block
  328. // size.
  329. if (adjust == 0) { return NULL; }
  330. // block_locate_free() may adjust our allocated size further.
  331. block_header_t *block = block_locate_free(control, &adjust);
  332. return block_prepare_used(control, block, adjust);
  333. }
  334. /**
  335. * @brief Allocate memory of at least `size` bytes at a given address in the pool.
  336. *
  337. * @param tlsf TLSF structure to allocate memory from.
  338. * @param size Minimum size, in bytes, of the memory to allocate
  339. * @param address address at which the allocation must be done
  340. *
  341. * @return pointer to free memory or NULL in case of incapacity to perform the malloc
  342. */
  343. void *tlsf_malloc_addr(tlsf_t tlsf, size_t size, void *address)
  344. {
  345. control_t *control = tlsf_cast(control_t *, tlsf);
  346. /* adjust the address to be ALIGN_SIZE bytes aligned. */
  347. const uintptr_t addr_adjusted = align_down(tlsf_cast(uintptr_t, address), ALIGN_SIZE);
  348. /* adjust the size to be ALIGN_SIZE bytes aligned. Add to the size the difference
  349. * between the requested address and the address_adjusted. */
  350. size_t size_adjusted = align_up(size + (tlsf_cast(uintptr_t, address) - addr_adjusted), ALIGN_SIZE);
  351. /* find the free block that starts before the address in the pool and is big enough
  352. * to support the size of allocation at the given address */
  353. block_header_t *block = offset_to_block(tlsf_get_pool(tlsf), -(int)block_header_overhead);
  354. const char *alloc_start = tlsf_cast(char *, addr_adjusted);
  355. const char *alloc_end = alloc_start + size_adjusted;
  356. bool block_found = false;
  357. do
  358. {
  359. const char *block_start = tlsf_cast(char *, block_to_ptr(block));
  360. const char *block_end = tlsf_cast(char *, block_to_ptr(block)) + block_size(block);
  361. if (block_start <= alloc_start && block_end > alloc_start)
  362. {
  363. /* A: block_end >= alloc_end. B: block is free */
  364. if (block_end < alloc_end || !block_is_free(block))
  365. {
  366. /* not(A) || not(B)
  367. * We won't find another suitable block from this point on
  368. * so we can break and return NULL */
  369. break;
  370. }
  371. /* A && B
  372. * The block can fit the alloc and is located at a position allowing for the alloc
  373. * to be placed at the given address. We can return from the while */
  374. block_found = true;
  375. }
  376. else if (!block_is_last(block))
  377. {
  378. /* the block doesn't match the expected criteria, continue with the next block */
  379. block = block_next(block);
  380. }
  381. } while (!block_is_last(block) && block_found == false);
  382. if (!block_found) { return NULL; }
  383. /* remove block from the free list since a part of it will be used */
  384. block_remove(control, block);
  385. /* trim any leading space or add the leading space to the overall requested size
  386. * if the leading space is not big enough to store a block of minimum size */
  387. const size_t space_before_addr_adjusted = addr_adjusted - tlsf_cast(uintptr_t, block_to_ptr(block));
  388. block_header_t *return_block = block;
  389. if (space_before_addr_adjusted >= block_size_min)
  390. {
  391. return_block = block_trim_free_leading(control, block, space_before_addr_adjusted);
  392. }
  393. else
  394. {
  395. size_adjusted += space_before_addr_adjusted;
  396. }
  397. /* trim trailing space if any and return a pointer to the first usable byte allocated */
  398. return block_prepare_used(control, return_block, size_adjusted);
  399. }
  400. /**
  401. * @brief Allocate memory of at least `size` bytes where byte at `data_offset` will be aligned to `alignment`.
  402. *
  403. * This function will allocate memory pointed by `ptr`. However, the byte at `data_offset` of
  404. * this piece of memory (i.e., byte at `ptr` + `data_offset`) will be aligned to `alignment`.
  405. * This function is useful for allocating memory that will internally have a header, and the
  406. * usable memory following the header (i.e. `ptr` + `data_offset`) must be aligned.
  407. *
  408. * For example, a call to `multi_heap_aligned_alloc_impl_offs(heap, 64, 256, 20)` will return a
  409. * pointer `ptr` to free memory of minimum 64 bytes, where `ptr + 20` is aligned on `256`.
  410. * So `(ptr + 20) % 256` equals 0.
  411. *
  412. * @param tlsf TLSF structure to allocate memory from.
  413. * @param align Alignment for the returned pointer's offset.
  414. * @param size Minimum size, in bytes, of the memory to allocate INCLUDING
  415. * `data_offset` bytes.
  416. * @param data_offset Offset to be aligned on `alignment`. This can be 0, in
  417. * this case, the returned pointer will be aligned on
  418. * `alignment`. If it is not a multiple of CPU word size,
  419. * it will be aligned up to the closest multiple of it.
  420. *
  421. * @return pointer to free memory.
  422. */
  423. void *tlsf_memalign_offs(tlsf_t tlsf, size_t align, size_t size, size_t data_offset)
  424. {
  425. control_t *control = tlsf_cast(control_t *, tlsf);
  426. const size_t adjust = adjust_request_size(tlsf, size, ALIGN_SIZE);
  427. const size_t off_adjust = align_up(data_offset, ALIGN_SIZE);
  428. /*
  429. ** We must allocate an additional minimum block size bytes so that if
  430. ** our free block will leave an alignment gap which is smaller, we can
  431. ** trim a leading free block and release it back to the pool. We must
  432. ** do this because the previous physical block is in use, therefore
  433. ** the prev_phys_block field is not valid, and we can't simply adjust
  434. ** the size of that block.
  435. */
  436. const size_t gap_minimum = sizeof(block_header_t) + off_adjust;
  437. /* The offset is included in both `adjust` and `gap_minimum`, so we
  438. ** need to subtract it once.
  439. */
  440. const size_t size_with_gap = adjust_request_size(tlsf, adjust + align + gap_minimum - off_adjust, align);
  441. /*
  442. ** If alignment is less than or equal to base alignment, we're done, because
  443. ** we are guaranteed that the size is at least sizeof(block_header_t), enough
  444. ** to store next blocks' metadata. Plus, all pointers allocated will all be
  445. ** aligned on a 4-byte bound, so ptr + data_offset will also have this
  446. ** alignment constraint. Thus, the gap is not required.
  447. ** If we requested 0 bytes, return null, as tlsf_malloc(0) does.
  448. */
  449. size_t aligned_size = (adjust && align > ALIGN_SIZE) ? size_with_gap : adjust;
  450. block_header_t *block = block_locate_free(control, &aligned_size);
  451. /* This can't be a static assert. */
  452. tlsf_assert(sizeof(block_header_t) == block_size_min + block_header_overhead);
  453. if (block)
  454. {
  455. void *ptr = block_to_ptr(block);
  456. void *aligned = align_ptr(ptr, align);
  457. size_t gap = tlsf_cast(size_t, tlsf_cast(tlsfptr_t, aligned) - tlsf_cast(tlsfptr_t, ptr));
  458. /*
  459. ** If gap size is too small or if there is no gap but we need one,
  460. ** offset to next aligned boundary.
  461. ** NOTE: No need for a gap if the alignment required is less than or is
  462. ** equal to ALIGN_SIZE.
  463. */
  464. if ((gap && gap < gap_minimum) || (!gap && off_adjust && align > ALIGN_SIZE))
  465. {
  466. const size_t gap_remain = gap_minimum - gap;
  467. const size_t offset = tlsf_max(gap_remain, align);
  468. const void *next_aligned = tlsf_cast(void *, tlsf_cast(tlsfptr_t, aligned) + offset);
  469. aligned = align_ptr(next_aligned, align);
  470. gap = tlsf_cast(size_t, tlsf_cast(tlsfptr_t, aligned) - tlsf_cast(tlsfptr_t, ptr));
  471. }
  472. if (gap)
  473. {
  474. tlsf_assert(gap >= gap_minimum && "gap size too small");
  475. block = block_trim_free_leading(control, block, gap - off_adjust);
  476. }
  477. }
  478. /* Preparing the block will also the trailing free memory. */
  479. return block_prepare_used(control, block, adjust);
  480. }
  481. /**
  482. * @brief Same as `tlsf_memalign_offs` function but with a 0 offset.
  483. * The pointer returned is aligned on `align`.
  484. */
  485. void *tlsf_memalign(tlsf_t tlsf, size_t align, size_t size) { return tlsf_memalign_offs(tlsf, align, size, 0); }
  486. void tlsf_memory_info(tlsf_t tlsf, size_t *total, size_t *used, size_t *max_used)
  487. {
  488. control_t *control = tlsf_cast(control_t *, tlsf);
  489. if (total) { *total = control->mem_rec.total; }
  490. if (used) { *used = control->mem_rec.used; }
  491. if (max_used) { *max_used = control->mem_rec.max_used; }
  492. }
  493. void tlsf_free(tlsf_t tlsf, void *ptr)
  494. {
  495. /* Don't attempt to free a NULL pointer. */
  496. if (ptr)
  497. {
  498. control_t *control = tlsf_cast(control_t *, tlsf);
  499. block_header_t *block = block_from_ptr(ptr);
  500. tlsf_assert(!block_is_free(block) && "block already marked as free");
  501. control->mem_rec.used -= (block_size(block) + tlsf_alloc_overhead());
  502. block_mark_as_free(block);
  503. block = block_merge_prev(control, block);
  504. block = block_merge_next(control, block);
  505. block_insert(control, block);
  506. }
  507. }
  508. /*
  509. ** The TLSF block information provides us with enough information to
  510. ** provide a reasonably intelligent implementation of realloc, growing or
  511. ** shrinking the currently allocated block as required.
  512. **
  513. ** This routine handles the somewhat esoteric edge cases of realloc:
  514. ** - a non-zero size with a null pointer will behave like malloc
  515. ** - a zero size with a non-null pointer will behave like free
  516. ** - a request that cannot be satisfied will leave the original buffer
  517. ** untouched
  518. ** - an extended buffer size will leave the newly-allocated area with
  519. ** contents undefined
  520. */
  521. void *tlsf_realloc(tlsf_t tlsf, void *ptr, size_t size)
  522. {
  523. control_t *control = tlsf_cast(control_t *, tlsf);
  524. void *p = 0;
  525. /* Zero-size requests are treated as free. */
  526. if (ptr && size == 0) { tlsf_free(tlsf, ptr); }
  527. /* Requests with NULL pointers are treated as malloc. */
  528. else if (!ptr) { p = tlsf_malloc(tlsf, size); }
  529. else
  530. {
  531. block_header_t *block = block_from_ptr(ptr);
  532. block_header_t *next = block_next(block);
  533. const size_t cursize = block_size(block);
  534. const size_t combined = cursize + block_size(next) + block_header_overhead;
  535. const size_t adjust = adjust_request_size(tlsf, size, ALIGN_SIZE);
  536. // if adjust if equal to 0, the size is too big
  537. if (adjust == 0) { return p; }
  538. tlsf_assert(!block_is_free(block) && "block already marked as free");
  539. /*
  540. ** If the next block is used, or when combined with the current
  541. ** block, does not offer enough space, we must reallocate and copy.
  542. */
  543. if (adjust > cursize && (!block_is_free(next) || adjust > combined))
  544. {
  545. p = tlsf_malloc(tlsf, size);
  546. if (p)
  547. {
  548. const size_t minsize = tlsf_min(cursize, size);
  549. rt_memcpy(p, ptr, minsize);
  550. tlsf_free(tlsf, ptr);
  551. }
  552. }
  553. else
  554. {
  555. /* Do we need to expand to the next block? */
  556. if (adjust > cursize)
  557. {
  558. block_merge_next(control, block);
  559. block_mark_as_used(block);
  560. }
  561. /* Trim the resulting block and return the original pointer. */
  562. block_trim_used(control, block, adjust);
  563. p = ptr;
  564. /* 更新统计信息:原地调整时需要修正 used */
  565. control->mem_rec.used += block_size(block);
  566. control->mem_rec.used -= cursize;
  567. if(control->mem_rec.used > control->mem_rec.max_used)
  568. control->mem_rec.max_used = control->mem_rec.used;
  569. }
  570. }
  571. return p;
  572. }
  573. void *tlsf_find_containing_block(pool_t pool, void *ptr)
  574. {
  575. block_header_t *block = offset_to_block(pool, -(int)block_header_overhead);
  576. while (block && !block_is_last(block))
  577. {
  578. if (!block_is_free(block))
  579. {
  580. void *block_end = block_to_ptr(block) + block_size(block);
  581. if (block_to_ptr(block) <= ptr && block_end > ptr)
  582. {
  583. // we found the containing block, return
  584. return block_to_ptr(block);
  585. }
  586. }
  587. block = block_next(block);
  588. }
  589. return NULL;
  590. }