1 #include "../lv_conf_internal.h"
2 #if LV_MEM_CUSTOM == 0
3 
4 #include <limits.h>
5 #include "lv_tlsf.h"
6 #include "lv_mem.h"
7 #include "lv_log.h"
8 #include "lv_assert.h"
9 
10 #undef  printf
11 #define printf LV_LOG_ERROR
12 
13 #define TLSF_MAX_POOL_SIZE LV_MEM_SIZE
14 
15 #if !defined(_DEBUG)
16     #define _DEBUG 0
17 #endif
18 
19 #if defined(__cplusplus)
20     #define tlsf_decl inline
21 #else
22     #define tlsf_decl static
23 #endif
24 
25 /*
26 ** Architecture-specific bit manipulation routines.
27 **
28 ** TLSF achieves O(1) cost for malloc and free operations by limiting
29 ** the search for a free block to a free list of guaranteed size
30 ** adequate to fulfill the request, combined with efficient free list
31 ** queries using bitmasks and architecture-specific bit-manipulation
32 ** routines.
33 **
34 ** Most modern processors provide instructions to count leading zeroes
35 ** in a word, find the lowest and highest set bit, etc. These
36 ** specific implementations will be used when available, falling back
37 ** to a reasonably efficient generic implementation.
38 **
39 ** NOTE: TLSF spec relies on ffs/fls returning value 0..31.
40 ** ffs/fls return 1-32 by default, returning 0 for error.
41 */
42 
43 /*
44 ** Detect whether or not we are building for a 32- or 64-bit (LP/LLP)
45 ** architecture. There is no reliable portable method at compile-time.
46 */
47 #if defined (__alpha__) || defined (__ia64__) || defined (__x86_64__) \
48     || defined (_WIN64) || defined (__LP64__) || defined (__LLP64__)
49     #define TLSF_64BIT
50 #endif
51 
52 /*
53 ** Returns one plus the index of the most significant 1-bit of n,
54 ** or if n is zero, returns zero.
55 */
56 #ifdef TLSF_64BIT
57     #define TLSF_FLS(n) ((n) & 0xffffffff00000000ull ? 32 + TLSF_FLS32((size_t)(n) >> 32) : TLSF_FLS32(n))
58 #else
59     #define TLSF_FLS(n) TLSF_FLS32(n)
60 #endif
61 
62 #define TLSF_FLS32(n) ((n) & 0xffff0000 ? 16 + TLSF_FLS16((n) >> 16) : TLSF_FLS16(n))
63 #define TLSF_FLS16(n) ((n) & 0xff00     ?  8 + TLSF_FLS8 ((n) >>  8) : TLSF_FLS8 (n))
64 #define TLSF_FLS8(n)  ((n) & 0xf0       ?  4 + TLSF_FLS4 ((n) >>  4) : TLSF_FLS4 (n))
65 #define TLSF_FLS4(n)  ((n) & 0xc        ?  2 + TLSF_FLS2 ((n) >>  2) : TLSF_FLS2 (n))
66 #define TLSF_FLS2(n)  ((n) & 0x2        ?  1 + TLSF_FLS1 ((n) >>  1) : TLSF_FLS1 (n))
67 #define TLSF_FLS1(n)  ((n) & 0x1        ?  1 : 0)
68 
69 /*
70 ** Returns round up value of log2(n).
71 ** Note: it is used at compile time.
72 */
73 #define TLSF_LOG2_CEIL(n) ((n) & (n - 1) ? TLSF_FLS(n) : TLSF_FLS(n) - 1)
74 
75 /*
76 ** gcc 3.4 and above have builtin support, specialized for architecture.
77 ** Some compilers masquerade as gcc; patchlevel test filters them out.
78 */
79 #if defined (__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) \
80     && defined (__GNUC_PATCHLEVEL__)
81 
82 #if defined (__SNC__)
83 /* SNC for Playstation 3. */
84 
tlsf_ffs(unsigned int word)85 tlsf_decl int tlsf_ffs(unsigned int word)
86 {
87     const unsigned int reverse = word & (~word + 1);
88     const int bit = 32 - __builtin_clz(reverse);
89     return bit - 1;
90 }
91 
92 #else
93 
tlsf_ffs(unsigned int word)94 tlsf_decl int tlsf_ffs(unsigned int word)
95 {
96     return __builtin_ffs(word) - 1;
97 }
98 
99 #endif
100 
tlsf_fls(unsigned int word)101 tlsf_decl int tlsf_fls(unsigned int word)
102 {
103     const int bit = word ? 32 - __builtin_clz(word) : 0;
104     return bit - 1;
105 }
106 
107 #elif defined (_MSC_VER) && (_MSC_VER >= 1400) && (defined (_M_IX86) || defined (_M_X64))
108 /* Microsoft Visual C++ support on x86/X64 architectures. */
109 
110 #include <intrin.h>
111 
112 #pragma intrinsic(_BitScanReverse)
113 #pragma intrinsic(_BitScanForward)
114 
tlsf_fls(unsigned int word)115 tlsf_decl int tlsf_fls(unsigned int word)
116 {
117     unsigned long index;
118     return _BitScanReverse(&index, word) ? index : -1;
119 }
120 
tlsf_ffs(unsigned int word)121 tlsf_decl int tlsf_ffs(unsigned int word)
122 {
123     unsigned long index;
124     return _BitScanForward(&index, word) ? index : -1;
125 }
126 
127 #elif defined (_MSC_VER) && defined (_M_PPC)
128 /* Microsoft Visual C++ support on PowerPC architectures. */
129 
130 #include <ppcintrinsics.h>
131 
tlsf_fls(unsigned int word)132 tlsf_decl int tlsf_fls(unsigned int word)
133 {
134     const int bit = 32 - _CountLeadingZeros(word);
135     return bit - 1;
136 }
137 
tlsf_ffs(unsigned int word)138 tlsf_decl int tlsf_ffs(unsigned int word)
139 {
140     const unsigned int reverse = word & (~word + 1);
141     const int bit = 32 - _CountLeadingZeros(reverse);
142     return bit - 1;
143 }
144 
145 #elif defined (__ARMCC_VERSION)
146 /* RealView Compilation Tools for ARM */
147 
tlsf_ffs(unsigned int word)148 tlsf_decl int tlsf_ffs(unsigned int word)
149 {
150     const unsigned int reverse = word & (~word + 1);
151     const int bit = 32 - __clz(reverse);
152     return bit - 1;
153 }
154 
tlsf_fls(unsigned int word)155 tlsf_decl int tlsf_fls(unsigned int word)
156 {
157     const int bit = word ? 32 - __clz(word) : 0;
158     return bit - 1;
159 }
160 
161 #elif defined (__ghs__)
162 /* Green Hills support for PowerPC */
163 
164 #include <ppc_ghs.h>
165 
tlsf_ffs(unsigned int word)166 tlsf_decl int tlsf_ffs(unsigned int word)
167 {
168     const unsigned int reverse = word & (~word + 1);
169     const int bit = 32 - __CLZ32(reverse);
170     return bit - 1;
171 }
172 
tlsf_fls(unsigned int word)173 tlsf_decl int tlsf_fls(unsigned int word)
174 {
175     const int bit = word ? 32 - __CLZ32(word) : 0;
176     return bit - 1;
177 }
178 
179 #else
180 /* Fall back to generic implementation. */
181 
182 /* Implement ffs in terms of fls. */
tlsf_ffs(unsigned int word)183 tlsf_decl int tlsf_ffs(unsigned int word)
184 {
185     const unsigned int reverse = word & (~word + 1);
186     return TLSF_FLS32(reverse) - 1;
187 }
188 
tlsf_fls(unsigned int word)189 tlsf_decl int tlsf_fls(unsigned int word)
190 {
191     return TLSF_FLS32(word) - 1;
192 }
193 
194 #endif
195 
196 /* Possibly 64-bit version of tlsf_fls. */
197 #if defined (TLSF_64BIT)
tlsf_fls_sizet(size_t size)198 tlsf_decl int tlsf_fls_sizet(size_t size)
199 {
200     int high = (int)(size >> 32);
201     int bits = 0;
202     if(high) {
203         bits = 32 + tlsf_fls(high);
204     }
205     else {
206         bits = tlsf_fls((int)size & 0xffffffff);
207 
208     }
209     return bits;
210 }
211 #else
212 #define tlsf_fls_sizet tlsf_fls
213 #endif
214 
215 #undef tlsf_decl
216 
217 /*
218 ** Constants.
219 */
220 
221 /* Public constants: may be modified. */
222 enum tlsf_public {
223     /* log2 of number of linear subdivisions of block sizes. Larger
224     ** values require more memory in the control structure. Values of
225     ** 4 or 5 are typical.
226     */
227     SL_INDEX_COUNT_LOG2 = 5,
228 };
229 
230 /* Private constants: do not modify. */
231 enum tlsf_private {
232 #if defined (TLSF_64BIT)
233     /* All allocation sizes and addresses are aligned to 8 bytes. */
234     ALIGN_SIZE_LOG2 = 3,
235 #else
236     /* All allocation sizes and addresses are aligned to 4 bytes. */
237     ALIGN_SIZE_LOG2 = 2,
238 #endif
239     ALIGN_SIZE = (1 << ALIGN_SIZE_LOG2),
240 
241     /*
242     ** We support allocations of sizes up to (1 << FL_INDEX_MAX) bits.
243     ** However, because we linearly subdivide the second-level lists, and
244     ** our minimum size granularity is 4 bytes, it doesn't make sense to
245     ** create first-level lists for sizes smaller than SL_INDEX_COUNT * 4,
246     ** or (1 << (SL_INDEX_COUNT_LOG2 + 2)) bytes, as there we will be
247     ** trying to split size ranges into more slots than we have available.
248     ** Instead, we calculate the minimum threshold size, and place all
249     ** blocks below that size into the 0th first-level list.
250     */
251 
252 #if defined (TLSF_MAX_POOL_SIZE)
253     FL_INDEX_MAX = TLSF_LOG2_CEIL(TLSF_MAX_POOL_SIZE),
254 #elif defined (TLSF_64BIT)
255     /*
256     ** TODO: We can increase this to support larger sizes, at the expense
257     ** of more overhead in the TLSF structure.
258     */
259     FL_INDEX_MAX = 32,
260 #else
261     FL_INDEX_MAX = 30,
262 #endif
263     SL_INDEX_COUNT = (1 << SL_INDEX_COUNT_LOG2),
264     FL_INDEX_SHIFT = (SL_INDEX_COUNT_LOG2 + ALIGN_SIZE_LOG2),
265     FL_INDEX_COUNT = (FL_INDEX_MAX - FL_INDEX_SHIFT + 1),
266 
267     SMALL_BLOCK_SIZE = (1 << FL_INDEX_SHIFT),
268 };
269 
270 /*
271 ** Cast and min/max macros.
272 */
273 
274 #define tlsf_cast(t, exp)   ((t) (exp))
275 #define tlsf_min(a, b)      ((a) < (b) ? (a) : (b))
276 #define tlsf_max(a, b)      ((a) > (b) ? (a) : (b))
277 
278 /*
279 ** Set assert macro, if it has not been provided by the user.
280 */
281 #define tlsf_assert LV_ASSERT
282 
283 #if !defined (tlsf_assert)
284     #define tlsf_assert assert
285 #endif
286 
287 /*
288 ** Static assertion mechanism.
289 */
290 
291 #define _tlsf_glue2(x, y) x ## y
292 #define _tlsf_glue(x, y) _tlsf_glue2(x, y)
293 #define tlsf_static_assert(exp) \
294     typedef char _tlsf_glue(static_assert, __LINE__) [(exp) ? 1 : -1]
295 
296 /* This code has been tested on 32- and 64-bit (LP/LLP) architectures. */
297 tlsf_static_assert(sizeof(int) * CHAR_BIT == 32);
298 tlsf_static_assert(sizeof(size_t) * CHAR_BIT >= 32);
299 tlsf_static_assert(sizeof(size_t) * CHAR_BIT <= 64);
300 
301 /* SL_INDEX_COUNT must be <= number of bits in sl_bitmap's storage type. */
302 tlsf_static_assert(sizeof(unsigned int) * CHAR_BIT >= SL_INDEX_COUNT);
303 
304 /* Ensure we've properly tuned our sizes. */
305 tlsf_static_assert(ALIGN_SIZE == SMALL_BLOCK_SIZE / SL_INDEX_COUNT);
306 
307 /*
308 ** Data structures and associated constants.
309 */
310 
311 /*
312 ** Block header structure.
313 **
314 ** There are several implementation subtleties involved:
315 ** - The prev_phys_block field is only valid if the previous block is free.
316 ** - The prev_phys_block field is actually stored at the end of the
317 **   previous block. It appears at the beginning of this structure only to
318 **   simplify the implementation.
319 ** - The next_free / prev_free fields are only valid if the block is free.
320 */
321 typedef struct block_header_t {
322     /* Points to the previous physical block. */
323     struct block_header_t * prev_phys_block;
324 
325     /* The size of this block, excluding the block header. */
326     size_t size;
327 
328     /* Next and previous free blocks. */
329     struct block_header_t * next_free;
330     struct block_header_t * prev_free;
331 } block_header_t;
332 
333 /*
334 ** Since block sizes are always at least a multiple of 4, the two least
335 ** significant bits of the size field are used to store the block status:
336 ** - bit 0: whether block is busy or free
337 ** - bit 1: whether previous block is busy or free
338 */
339 static const size_t block_header_free_bit = 1 << 0;
340 static const size_t block_header_prev_free_bit = 1 << 1;
341 
342 /*
343 ** The size of the block header exposed to used blocks is the size field.
344 ** The prev_phys_block field is stored *inside* the previous free block.
345 */
346 static const size_t block_header_overhead = sizeof(size_t);
347 
348 /* User data starts directly after the size field in a used block. */
349 static const size_t block_start_offset =
350     offsetof(block_header_t, size) + sizeof(size_t);
351 
352 /*
353 ** A free block must be large enough to store its header minus the size of
354 ** the prev_phys_block field, and no larger than the number of addressable
355 ** bits for FL_INDEX.
356 */
357 static const size_t block_size_min =
358     sizeof(block_header_t) - sizeof(block_header_t *);
359 static const size_t block_size_max = tlsf_cast(size_t, 1) << FL_INDEX_MAX;
360 
361 /* The TLSF control structure. */
362 typedef struct control_t {
363     /* Empty lists point at this block to indicate they are free. */
364     block_header_t block_null;
365 
366     /* Bitmaps for free lists. */
367     unsigned int fl_bitmap;
368     unsigned int sl_bitmap[FL_INDEX_COUNT];
369 
370     /* Head of free lists. */
371     block_header_t * blocks[FL_INDEX_COUNT][SL_INDEX_COUNT];
372 } control_t;
373 
374 /* A type used for casting when doing pointer arithmetic. */
375 typedef ptrdiff_t tlsfptr_t;
376 
377 /*
378 ** block_header_t member functions.
379 */
380 
block_size(const block_header_t * block)381 static size_t block_size(const block_header_t * block)
382 {
383     return block->size & ~(block_header_free_bit | block_header_prev_free_bit);
384 }
385 
block_set_size(block_header_t * block,size_t size)386 static void block_set_size(block_header_t * block, size_t size)
387 {
388     const size_t oldsize = block->size;
389     block->size = size | (oldsize & (block_header_free_bit | block_header_prev_free_bit));
390 }
391 
block_is_last(const block_header_t * block)392 static int block_is_last(const block_header_t * block)
393 {
394     return block_size(block) == 0;
395 }
396 
block_is_free(const block_header_t * block)397 static int block_is_free(const block_header_t * block)
398 {
399     return tlsf_cast(int, block->size & block_header_free_bit);
400 }
401 
block_set_free(block_header_t * block)402 static void block_set_free(block_header_t * block)
403 {
404     block->size |= block_header_free_bit;
405 }
406 
block_set_used(block_header_t * block)407 static void block_set_used(block_header_t * block)
408 {
409     block->size &= ~block_header_free_bit;
410 }
411 
block_is_prev_free(const block_header_t * block)412 static int block_is_prev_free(const block_header_t * block)
413 {
414     return tlsf_cast(int, block->size & block_header_prev_free_bit);
415 }
416 
block_set_prev_free(block_header_t * block)417 static void block_set_prev_free(block_header_t * block)
418 {
419     block->size |= block_header_prev_free_bit;
420 }
421 
block_set_prev_used(block_header_t * block)422 static void block_set_prev_used(block_header_t * block)
423 {
424     block->size &= ~block_header_prev_free_bit;
425 }
426 
block_from_ptr(const void * ptr)427 static block_header_t * block_from_ptr(const void * ptr)
428 {
429     return tlsf_cast(block_header_t *,
430                      tlsf_cast(unsigned char *, ptr) - block_start_offset);
431 }
432 
block_to_ptr(const block_header_t * block)433 static void * block_to_ptr(const block_header_t * block)
434 {
435     return tlsf_cast(void *,
436                      tlsf_cast(unsigned char *, block) + block_start_offset);
437 }
438 
439 /* Return location of next block after block of given size. */
offset_to_block(const void * ptr,size_t size)440 static block_header_t * offset_to_block(const void * ptr, size_t size)
441 {
442     return tlsf_cast(block_header_t *, tlsf_cast(tlsfptr_t, ptr) + size);
443 }
444 
445 /* Return location of previous block. */
block_prev(const block_header_t * block)446 static block_header_t * block_prev(const block_header_t * block)
447 {
448     tlsf_assert(block_is_prev_free(block) && "previous block must be free");
449     return block->prev_phys_block;
450 }
451 
452 /* Return location of next existing block. */
block_next(const block_header_t * block)453 static block_header_t * block_next(const block_header_t * block)
454 {
455     block_header_t * next = offset_to_block(block_to_ptr(block),
456                                             block_size(block) - block_header_overhead);
457     tlsf_assert(!block_is_last(block));
458     return next;
459 }
460 
461 /* Link a new block with its physical neighbor, return the neighbor. */
block_link_next(block_header_t * block)462 static block_header_t * block_link_next(block_header_t * block)
463 {
464     block_header_t * next = block_next(block);
465     next->prev_phys_block = block;
466     return next;
467 }
468 
block_mark_as_free(block_header_t * block)469 static void block_mark_as_free(block_header_t * block)
470 {
471     /* Link the block to the next block, first. */
472     block_header_t * next = block_link_next(block);
473     block_set_prev_free(next);
474     block_set_free(block);
475 }
476 
block_mark_as_used(block_header_t * block)477 static void block_mark_as_used(block_header_t * block)
478 {
479     block_header_t * next = block_next(block);
480     block_set_prev_used(next);
481     block_set_used(block);
482 }
483 
align_up(size_t x,size_t align)484 static size_t align_up(size_t x, size_t align)
485 {
486     tlsf_assert(0 == (align & (align - 1)) && "must align to a power of two");
487     return (x + (align - 1)) & ~(align - 1);
488 }
489 
align_down(size_t x,size_t align)490 static size_t align_down(size_t x, size_t align)
491 {
492     tlsf_assert(0 == (align & (align - 1)) && "must align to a power of two");
493     return x - (x & (align - 1));
494 }
495 
align_ptr(const void * ptr,size_t align)496 static void * align_ptr(const void * ptr, size_t align)
497 {
498     const tlsfptr_t aligned =
499         (tlsf_cast(tlsfptr_t, ptr) + (align - 1)) & ~(align - 1);
500     tlsf_assert(0 == (align & (align - 1)) && "must align to a power of two");
501     return tlsf_cast(void *, aligned);
502 }
503 
504 /*
505 ** Adjust an allocation size to be aligned to word size, and no smaller
506 ** than internal minimum.
507 */
adjust_request_size(size_t size,size_t align)508 static size_t adjust_request_size(size_t size, size_t align)
509 {
510     size_t adjust = 0;
511     if(size) {
512         const size_t aligned = align_up(size, align);
513 
514         /* aligned sized must not exceed block_size_max or we'll go out of bounds on sl_bitmap */
515         if(aligned < block_size_max) {
516             adjust = tlsf_max(aligned, block_size_min);
517         }
518     }
519     return adjust;
520 }
521 
522 /*
523 ** TLSF utility functions. In most cases, these are direct translations of
524 ** the documentation found in the white paper.
525 */
526 
mapping_insert(size_t size,int * fli,int * sli)527 static void mapping_insert(size_t size, int * fli, int * sli)
528 {
529     int fl, sl;
530     if(size < SMALL_BLOCK_SIZE) {
531         /* Store small blocks in first list. */
532         fl = 0;
533         sl = tlsf_cast(int, size) / (SMALL_BLOCK_SIZE / SL_INDEX_COUNT);
534     }
535     else {
536         fl = tlsf_fls_sizet(size);
537         sl = tlsf_cast(int, size >> (fl - SL_INDEX_COUNT_LOG2)) ^ (1 << SL_INDEX_COUNT_LOG2);
538         fl -= (FL_INDEX_SHIFT - 1);
539     }
540     *fli = fl;
541     *sli = sl;
542 }
543 
544 /* This version rounds up to the next block size (for allocations) */
mapping_search(size_t size,int * fli,int * sli)545 static void mapping_search(size_t size, int * fli, int * sli)
546 {
547     if(size >= SMALL_BLOCK_SIZE) {
548         const size_t round = (1 << (tlsf_fls_sizet(size) - SL_INDEX_COUNT_LOG2)) - 1;
549         size += round;
550     }
551     mapping_insert(size, fli, sli);
552 }
553 
search_suitable_block(control_t * control,int * fli,int * sli)554 static block_header_t * search_suitable_block(control_t * control, int * fli, int * sli)
555 {
556     int fl = *fli;
557     int sl = *sli;
558 
559     /*
560     ** First, search for a block in the list associated with the given
561     ** fl/sl index.
562     */
563     unsigned int sl_map = control->sl_bitmap[fl] & (~0U << sl);
564     if(!sl_map) {
565         /* No block exists. Search in the next largest first-level list. */
566         const unsigned int fl_map = control->fl_bitmap & (~0U << (fl + 1));
567         if(!fl_map) {
568             /* No free blocks available, memory has been exhausted. */
569             return 0;
570         }
571 
572         fl = tlsf_ffs(fl_map);
573         *fli = fl;
574         sl_map = control->sl_bitmap[fl];
575     }
576     tlsf_assert(sl_map && "internal error - second level bitmap is null");
577     sl = tlsf_ffs(sl_map);
578     *sli = sl;
579 
580     /* Return the first block in the free list. */
581     return control->blocks[fl][sl];
582 }
583 
584 /* Remove a free block from the free list.*/
remove_free_block(control_t * control,block_header_t * block,int fl,int sl)585 static void remove_free_block(control_t * control, block_header_t * block, int fl, int sl)
586 {
587     block_header_t * prev = block->prev_free;
588     block_header_t * next = block->next_free;
589     tlsf_assert(prev && "prev_free field can not be null");
590     tlsf_assert(next && "next_free field can not be null");
591     next->prev_free = prev;
592     prev->next_free = next;
593 
594     /* If this block is the head of the free list, set new head. */
595     if(control->blocks[fl][sl] == block) {
596         control->blocks[fl][sl] = next;
597 
598         /* If the new head is null, clear the bitmap. */
599         if(next == &control->block_null) {
600             control->sl_bitmap[fl] &= ~(1U << sl);
601 
602             /* If the second bitmap is now empty, clear the fl bitmap. */
603             if(!control->sl_bitmap[fl]) {
604                 control->fl_bitmap &= ~(1U << fl);
605             }
606         }
607     }
608 }
609 
610 /* Insert a free block into the free block list. */
insert_free_block(control_t * control,block_header_t * block,int fl,int sl)611 static void insert_free_block(control_t * control, block_header_t * block, int fl, int sl)
612 {
613     block_header_t * current = control->blocks[fl][sl];
614     tlsf_assert(current && "free list cannot have a null entry");
615     tlsf_assert(block && "cannot insert a null entry into the free list");
616     block->next_free = current;
617     block->prev_free = &control->block_null;
618     current->prev_free = block;
619 
620     tlsf_assert(block_to_ptr(block) == align_ptr(block_to_ptr(block), ALIGN_SIZE)
621                 && "block not aligned properly");
622     /*
623     ** Insert the new block at the head of the list, and mark the first-
624     ** and second-level bitmaps appropriately.
625     */
626     control->blocks[fl][sl] = block;
627     control->fl_bitmap |= (1U << fl);
628     control->sl_bitmap[fl] |= (1U << sl);
629 }
630 
631 /* Remove a given block from the free list. */
block_remove(control_t * control,block_header_t * block)632 static void block_remove(control_t * control, block_header_t * block)
633 {
634     int fl, sl;
635     mapping_insert(block_size(block), &fl, &sl);
636     remove_free_block(control, block, fl, sl);
637 }
638 
639 /* Insert a given block into the free list. */
block_insert(control_t * control,block_header_t * block)640 static void block_insert(control_t * control, block_header_t * block)
641 {
642     int fl, sl;
643     mapping_insert(block_size(block), &fl, &sl);
644     insert_free_block(control, block, fl, sl);
645 }
646 
block_can_split(block_header_t * block,size_t size)647 static int block_can_split(block_header_t * block, size_t size)
648 {
649     return block_size(block) >= sizeof(block_header_t) + size;
650 }
651 
652 /* Split a block into two, the second of which is free. */
block_split(block_header_t * block,size_t size)653 static block_header_t * block_split(block_header_t * block, size_t size)
654 {
655     /* Calculate the amount of space left in the remaining block. */
656     block_header_t * remaining =
657         offset_to_block(block_to_ptr(block), size - block_header_overhead);
658 
659     const size_t remain_size = block_size(block) - (size + block_header_overhead);
660 
661     tlsf_assert(block_to_ptr(remaining) == align_ptr(block_to_ptr(remaining), ALIGN_SIZE)
662                 && "remaining block not aligned properly");
663 
664     tlsf_assert(block_size(block) == remain_size + size + block_header_overhead);
665     block_set_size(remaining, remain_size);
666     tlsf_assert(block_size(remaining) >= block_size_min && "block split with invalid size");
667 
668     block_set_size(block, size);
669     block_mark_as_free(remaining);
670 
671     return remaining;
672 }
673 
674 /* Absorb a free block's storage into an adjacent previous free block. */
block_absorb(block_header_t * prev,block_header_t * block)675 static block_header_t * block_absorb(block_header_t * prev, block_header_t * block)
676 {
677     tlsf_assert(!block_is_last(prev) && "previous block can't be last");
678     /* Note: Leaves flags untouched. */
679     prev->size += block_size(block) + block_header_overhead;
680     block_link_next(prev);
681     return prev;
682 }
683 
684 /* Merge a just-freed block with an adjacent previous free block. */
block_merge_prev(control_t * control,block_header_t * block)685 static block_header_t * block_merge_prev(control_t * control, block_header_t * block)
686 {
687     if(block_is_prev_free(block)) {
688         block_header_t * prev = block_prev(block);
689         tlsf_assert(prev && "prev physical block can't be null");
690         tlsf_assert(block_is_free(prev) && "prev block is not free though marked as such");
691         block_remove(control, prev);
692         block = block_absorb(prev, block);
693     }
694 
695     return block;
696 }
697 
698 /* Merge a just-freed block with an adjacent free block. */
block_merge_next(control_t * control,block_header_t * block)699 static block_header_t * block_merge_next(control_t * control, block_header_t * block)
700 {
701     block_header_t * next = block_next(block);
702     tlsf_assert(next && "next physical block can't be null");
703 
704     if(block_is_free(next)) {
705         tlsf_assert(!block_is_last(block) && "previous block can't be last");
706         block_remove(control, next);
707         block = block_absorb(block, next);
708     }
709 
710     return block;
711 }
712 
713 /* Trim any trailing block space off the end of a block, return to pool. */
block_trim_free(control_t * control,block_header_t * block,size_t size)714 static void block_trim_free(control_t * control, block_header_t * block, size_t size)
715 {
716     tlsf_assert(block_is_free(block) && "block must be free");
717     if(block_can_split(block, size)) {
718         block_header_t * remaining_block = block_split(block, size);
719         block_link_next(block);
720         block_set_prev_free(remaining_block);
721         block_insert(control, remaining_block);
722     }
723 }
724 
725 /* Trim any trailing block space off the end of a used block, return to pool. */
block_trim_used(control_t * control,block_header_t * block,size_t size)726 static void block_trim_used(control_t * control, block_header_t * block, size_t size)
727 {
728     tlsf_assert(!block_is_free(block) && "block must be used");
729     if(block_can_split(block, size)) {
730         /* If the next block is free, we must coalesce. */
731         block_header_t * remaining_block = block_split(block, size);
732         block_set_prev_used(remaining_block);
733 
734         remaining_block = block_merge_next(control, remaining_block);
735         block_insert(control, remaining_block);
736     }
737 }
738 
block_trim_free_leading(control_t * control,block_header_t * block,size_t size)739 static block_header_t * block_trim_free_leading(control_t * control, block_header_t * block, size_t size)
740 {
741     block_header_t * remaining_block = block;
742     if(block_can_split(block, size)) {
743         /* We want the 2nd block. */
744         remaining_block = block_split(block, size - block_header_overhead);
745         block_set_prev_free(remaining_block);
746 
747         block_link_next(block);
748         block_insert(control, block);
749     }
750 
751     return remaining_block;
752 }
753 
block_locate_free(control_t * control,size_t size)754 static block_header_t * block_locate_free(control_t * control, size_t size)
755 {
756     int fl = 0, sl = 0;
757     block_header_t * block = 0;
758 
759     if(size) {
760         mapping_search(size, &fl, &sl);
761 
762         /*
763         ** mapping_search can futz with the size, so for excessively large sizes it can sometimes wind up
764         ** with indices that are off the end of the block array.
765         ** So, we protect against that here, since this is the only callsite of mapping_search.
766         ** Note that we don't need to check sl, since it comes from a modulo operation that guarantees it's always in range.
767         */
768         if(fl < FL_INDEX_COUNT) {
769             block = search_suitable_block(control, &fl, &sl);
770         }
771     }
772 
773     if(block) {
774         tlsf_assert(block_size(block) >= size);
775         remove_free_block(control, block, fl, sl);
776     }
777 
778     return block;
779 }
780 
block_prepare_used(control_t * control,block_header_t * block,size_t size)781 static void * block_prepare_used(control_t * control, block_header_t * block, size_t size)
782 {
783     void * p = 0;
784     if(block) {
785         tlsf_assert(size && "size must be non-zero");
786         block_trim_free(control, block, size);
787         block_mark_as_used(block);
788         p = block_to_ptr(block);
789     }
790     return p;
791 }
792 
793 /* Clear structure and point all empty lists at the null block. */
control_constructor(control_t * control)794 static void control_constructor(control_t * control)
795 {
796     int i, j;
797 
798     control->block_null.next_free = &control->block_null;
799     control->block_null.prev_free = &control->block_null;
800 
801     control->fl_bitmap = 0;
802     for(i = 0; i < FL_INDEX_COUNT; ++i) {
803         control->sl_bitmap[i] = 0;
804         for(j = 0; j < SL_INDEX_COUNT; ++j) {
805             control->blocks[i][j] = &control->block_null;
806         }
807     }
808 }
809 
810 /*
811 ** Debugging utilities.
812 */
813 
814 typedef struct integrity_t {
815     int prev_status;
816     int status;
817 } integrity_t;
818 
819 #define tlsf_insist(x) { tlsf_assert(x); if (!(x)) { status--; } }
820 
integrity_walker(void * ptr,size_t size,int used,void * user)821 static void integrity_walker(void * ptr, size_t size, int used, void * user)
822 {
823     block_header_t * block = block_from_ptr(ptr);
824     integrity_t * integ = tlsf_cast(integrity_t *, user);
825     const int this_prev_status = block_is_prev_free(block) ? 1 : 0;
826     const int this_status = block_is_free(block) ? 1 : 0;
827     const size_t this_block_size = block_size(block);
828 
829     int status = 0;
830     LV_UNUSED(used);
831     tlsf_insist(integ->prev_status == this_prev_status && "prev status incorrect");
832     tlsf_insist(size == this_block_size && "block size incorrect");
833 
834     integ->prev_status = this_status;
835     integ->status += status;
836 }
837 
lv_tlsf_check(lv_tlsf_t tlsf)838 int lv_tlsf_check(lv_tlsf_t tlsf)
839 {
840     int i, j;
841 
842     control_t * control = tlsf_cast(control_t *, tlsf);
843     int status = 0;
844 
845     /* Check that the free lists and bitmaps are accurate. */
846     for(i = 0; i < FL_INDEX_COUNT; ++i) {
847         for(j = 0; j < SL_INDEX_COUNT; ++j) {
848             const int fl_map = control->fl_bitmap & (1U << i);
849             const int sl_list = control->sl_bitmap[i];
850             const int sl_map = sl_list & (1U << j);
851             const block_header_t * block = control->blocks[i][j];
852 
853             /* Check that first- and second-level lists agree. */
854             if(!fl_map) {
855                 tlsf_insist(!sl_map && "second-level map must be null");
856             }
857 
858             if(!sl_map) {
859                 tlsf_insist(block == &control->block_null && "block list must be null");
860                 continue;
861             }
862 
863             /* Check that there is at least one free block. */
864             tlsf_insist(sl_list && "no free blocks in second-level map");
865             tlsf_insist(block != &control->block_null && "block should not be null");
866 
867             while(block != &control->block_null) {
868                 int fli, sli;
869                 tlsf_insist(block_is_free(block) && "block should be free");
870                 tlsf_insist(!block_is_prev_free(block) && "blocks should have coalesced");
871                 tlsf_insist(!block_is_free(block_next(block)) && "blocks should have coalesced");
872                 tlsf_insist(block_is_prev_free(block_next(block)) && "block should be free");
873                 tlsf_insist(block_size(block) >= block_size_min && "block not minimum size");
874 
875                 mapping_insert(block_size(block), &fli, &sli);
876                 tlsf_insist(fli == i && sli == j && "block size indexed in wrong list");
877                 block = block->next_free;
878             }
879         }
880     }
881 
882     return status;
883 }
884 
885 #undef tlsf_insist
886 
default_walker(void * ptr,size_t size,int used,void * user)887 static void default_walker(void * ptr, size_t size, int used, void * user)
888 {
889     LV_UNUSED(user);
890     printf("\t%p %s size: %x (%p)\n", ptr, used ? "used" : "free", (unsigned int)size, (void *)block_from_ptr(ptr));
891 }
892 
lv_tlsf_walk_pool(lv_pool_t pool,lv_tlsf_walker walker,void * user)893 void lv_tlsf_walk_pool(lv_pool_t pool, lv_tlsf_walker walker, void * user)
894 {
895     lv_tlsf_walker pool_walker = walker ? walker : default_walker;
896     block_header_t * block =
897         offset_to_block(pool, -(int)block_header_overhead);
898 
899     while(block && !block_is_last(block)) {
900         pool_walker(
901             block_to_ptr(block),
902             block_size(block),
903             !block_is_free(block),
904             user);
905         block = block_next(block);
906     }
907 }
908 
lv_tlsf_block_size(void * ptr)909 size_t lv_tlsf_block_size(void * ptr)
910 {
911     size_t size = 0;
912     if(ptr) {
913         const block_header_t * block = block_from_ptr(ptr);
914         size = block_size(block);
915     }
916     return size;
917 }
918 
lv_tlsf_check_pool(lv_pool_t pool)919 int lv_tlsf_check_pool(lv_pool_t pool)
920 {
921     /* Check that the blocks are physically correct. */
922     integrity_t integ = { 0, 0 };
923     lv_tlsf_walk_pool(pool, integrity_walker, &integ);
924 
925     return integ.status;
926 }
927 
928 /*
929 ** Size of the TLSF structures in a given memory block passed to
930 ** lv_tlsf_create, equal to the size of a control_t
931 */
lv_tlsf_size(void)932 size_t lv_tlsf_size(void)
933 {
934     return sizeof(control_t);
935 }
936 
lv_tlsf_align_size(void)937 size_t lv_tlsf_align_size(void)
938 {
939     return ALIGN_SIZE;
940 }
941 
lv_tlsf_block_size_min(void)942 size_t lv_tlsf_block_size_min(void)
943 {
944     return block_size_min;
945 }
946 
lv_tlsf_block_size_max(void)947 size_t lv_tlsf_block_size_max(void)
948 {
949     return block_size_max;
950 }
951 
952 /*
953 ** Overhead of the TLSF structures in a given memory block passed to
954 ** lv_tlsf_add_pool, equal to the overhead of a free block and the
955 ** sentinel block.
956 */
lv_tlsf_pool_overhead(void)957 size_t lv_tlsf_pool_overhead(void)
958 {
959     return 2 * block_header_overhead;
960 }
961 
lv_tlsf_alloc_overhead(void)962 size_t lv_tlsf_alloc_overhead(void)
963 {
964     return block_header_overhead;
965 }
966 
lv_tlsf_add_pool(lv_tlsf_t tlsf,void * mem,size_t bytes)967 lv_pool_t lv_tlsf_add_pool(lv_tlsf_t tlsf, void * mem, size_t bytes)
968 {
969     block_header_t * block;
970     block_header_t * next;
971 
972     const size_t pool_overhead = lv_tlsf_pool_overhead();
973     const size_t pool_bytes = align_down(bytes - pool_overhead, ALIGN_SIZE);
974 
975     if(((ptrdiff_t)mem % ALIGN_SIZE) != 0) {
976         printf("lv_tlsf_add_pool: Memory must be aligned by %u bytes.\n",
977                (unsigned int)ALIGN_SIZE);
978         return 0;
979     }
980 
981     if(pool_bytes < block_size_min || pool_bytes > block_size_max) {
982 #if defined (TLSF_64BIT)
983         printf("lv_tlsf_add_pool: Memory size must be between 0x%x and 0x%x00 bytes.\n",
984                (unsigned int)(pool_overhead + block_size_min),
985                (unsigned int)((pool_overhead + block_size_max) / 256));
986 #else
987         printf("lv_tlsf_add_pool: Memory size must be between %u and %u bytes.\n",
988                (unsigned int)(pool_overhead + block_size_min),
989                (unsigned int)(pool_overhead + block_size_max));
990 #endif
991         return 0;
992     }
993 
994     /*
995     ** Create the main free block. Offset the start of the block slightly
996     ** so that the prev_phys_block field falls outside of the pool -
997     ** it will never be used.
998     */
999     block = offset_to_block(mem, -(tlsfptr_t)block_header_overhead);
1000     block_set_size(block, pool_bytes);
1001     block_set_free(block);
1002     block_set_prev_used(block);
1003     block_insert(tlsf_cast(control_t *, tlsf), block);
1004 
1005     /* Split the block to create a zero-size sentinel block. */
1006     next = block_link_next(block);
1007     block_set_size(next, 0);
1008     block_set_used(next);
1009     block_set_prev_free(next);
1010 
1011     return mem;
1012 }
1013 
lv_tlsf_remove_pool(lv_tlsf_t tlsf,lv_pool_t pool)1014 void lv_tlsf_remove_pool(lv_tlsf_t tlsf, lv_pool_t pool)
1015 {
1016     control_t * control = tlsf_cast(control_t *, tlsf);
1017     block_header_t * block = offset_to_block(pool, -(int)block_header_overhead);
1018 
1019     int fl = 0, sl = 0;
1020 
1021     tlsf_assert(block_is_free(block) && "block should be free");
1022     tlsf_assert(!block_is_free(block_next(block)) && "next block should not be free");
1023     tlsf_assert(block_size(block_next(block)) == 0 && "next block size should be zero");
1024 
1025     mapping_insert(block_size(block), &fl, &sl);
1026     remove_free_block(control, block, fl, sl);
1027 }
1028 
1029 /*
1030 ** TLSF main interface.
1031 */
1032 
1033 #if _DEBUG
test_ffs_fls()1034 int test_ffs_fls()
1035 {
1036     /* Verify ffs/fls work properly. */
1037     int rv = 0;
1038     rv += (tlsf_ffs(0) == -1) ? 0 : 0x1;
1039     rv += (tlsf_fls(0) == -1) ? 0 : 0x2;
1040     rv += (tlsf_ffs(1) == 0) ? 0 : 0x4;
1041     rv += (tlsf_fls(1) == 0) ? 0 : 0x8;
1042     rv += (tlsf_ffs(0x80000000) == 31) ? 0 : 0x10;
1043     rv += (tlsf_ffs(0x80008000) == 15) ? 0 : 0x20;
1044     rv += (tlsf_fls(0x80000008) == 31) ? 0 : 0x40;
1045     rv += (tlsf_fls(0x7FFFFFFF) == 30) ? 0 : 0x80;
1046 
1047 #if defined (TLSF_64BIT)
1048     rv += (tlsf_fls_sizet(0x80000000) == 31) ? 0 : 0x100;
1049     rv += (tlsf_fls_sizet(0x100000000) == 32) ? 0 : 0x200;
1050     rv += (tlsf_fls_sizet(0xffffffffffffffff) == 63) ? 0 : 0x400;
1051 #endif
1052 
1053     if(rv) {
1054         printf("test_ffs_fls: %x ffs/fls tests failed.\n", rv);
1055     }
1056     return rv;
1057 }
1058 #endif
1059 
lv_tlsf_create(void * mem)1060 lv_tlsf_t lv_tlsf_create(void * mem)
1061 {
1062 #if _DEBUG
1063     if(test_ffs_fls()) {
1064         return 0;
1065     }
1066 #endif
1067 
1068     if(((tlsfptr_t)mem % ALIGN_SIZE) != 0) {
1069         printf("lv_tlsf_create: Memory must be aligned to %u bytes.\n",
1070                (unsigned int)ALIGN_SIZE);
1071         return 0;
1072     }
1073 
1074     control_constructor(tlsf_cast(control_t *, mem));
1075 
1076     return tlsf_cast(lv_tlsf_t, mem);
1077 }
1078 
lv_tlsf_create_with_pool(void * mem,size_t bytes)1079 lv_tlsf_t lv_tlsf_create_with_pool(void * mem, size_t bytes)
1080 {
1081     lv_tlsf_t tlsf = lv_tlsf_create(mem);
1082     lv_tlsf_add_pool(tlsf, (char *)mem + lv_tlsf_size(), bytes - lv_tlsf_size());
1083     return tlsf;
1084 }
1085 
lv_tlsf_destroy(lv_tlsf_t tlsf)1086 void lv_tlsf_destroy(lv_tlsf_t tlsf)
1087 {
1088     /* Nothing to do. */
1089     LV_UNUSED(tlsf);
1090 }
1091 
lv_tlsf_get_pool(lv_tlsf_t tlsf)1092 lv_pool_t lv_tlsf_get_pool(lv_tlsf_t tlsf)
1093 {
1094     return tlsf_cast(lv_pool_t, (char *)tlsf + lv_tlsf_size());
1095 }
1096 
lv_tlsf_malloc(lv_tlsf_t tlsf,size_t size)1097 void * lv_tlsf_malloc(lv_tlsf_t tlsf, size_t size)
1098 {
1099     control_t * control = tlsf_cast(control_t *, tlsf);
1100     const size_t adjust = adjust_request_size(size, ALIGN_SIZE);
1101     block_header_t * block = block_locate_free(control, adjust);
1102     return block_prepare_used(control, block, adjust);
1103 }
1104 
lv_tlsf_memalign(lv_tlsf_t tlsf,size_t align,size_t size)1105 void * lv_tlsf_memalign(lv_tlsf_t tlsf, size_t align, size_t size)
1106 {
1107     control_t * control = tlsf_cast(control_t *, tlsf);
1108     const size_t adjust = adjust_request_size(size, ALIGN_SIZE);
1109 
1110     /*
1111     ** We must allocate an additional minimum block size bytes so that if
1112     ** our free block will leave an alignment gap which is smaller, we can
1113     ** trim a leading free block and release it back to the pool. We must
1114     ** do this because the previous physical block is in use, therefore
1115     ** the prev_phys_block field is not valid, and we can't simply adjust
1116     ** the size of that block.
1117     */
1118     const size_t gap_minimum = sizeof(block_header_t);
1119     const size_t size_with_gap = adjust_request_size(adjust + align + gap_minimum, align);
1120 
1121     /*
1122     ** If alignment is less than or equals base alignment, we're done.
1123     ** If we requested 0 bytes, return null, as lv_tlsf_malloc(0) does.
1124     */
1125     const size_t aligned_size = (adjust && align > ALIGN_SIZE) ? size_with_gap : adjust;
1126 
1127     block_header_t * block = block_locate_free(control, aligned_size);
1128 
1129     /* This can't be a static assert. */
1130     tlsf_assert(sizeof(block_header_t) == block_size_min + block_header_overhead);
1131 
1132     if(block) {
1133         void * ptr = block_to_ptr(block);
1134         void * aligned = align_ptr(ptr, align);
1135         size_t gap = tlsf_cast(size_t,
1136                                tlsf_cast(tlsfptr_t, aligned) - tlsf_cast(tlsfptr_t, ptr));
1137 
1138         /* If gap size is too small, offset to next aligned boundary. */
1139         if(gap && gap < gap_minimum) {
1140             const size_t gap_remain = gap_minimum - gap;
1141             const size_t offset = tlsf_max(gap_remain, align);
1142             const void * next_aligned = tlsf_cast(void *,
1143                                                   tlsf_cast(tlsfptr_t, aligned) + offset);
1144 
1145             aligned = align_ptr(next_aligned, align);
1146             gap = tlsf_cast(size_t,
1147                             tlsf_cast(tlsfptr_t, aligned) - tlsf_cast(tlsfptr_t, ptr));
1148         }
1149 
1150         if(gap) {
1151             tlsf_assert(gap >= gap_minimum && "gap size too small");
1152             block = block_trim_free_leading(control, block, gap);
1153         }
1154     }
1155 
1156     return block_prepare_used(control, block, adjust);
1157 }
1158 
lv_tlsf_free(lv_tlsf_t tlsf,const void * ptr)1159 size_t lv_tlsf_free(lv_tlsf_t tlsf, const void * ptr)
1160 {
1161     size_t size = 0;
1162     /* Don't attempt to free a NULL pointer. */
1163     if(ptr) {
1164         control_t * control = tlsf_cast(control_t *, tlsf);
1165         block_header_t * block = block_from_ptr(ptr);
1166         tlsf_assert(!block_is_free(block) && "block already marked as free");
1167         size = block->size;
1168         block_mark_as_free(block);
1169         block = block_merge_prev(control, block);
1170         block = block_merge_next(control, block);
1171         block_insert(control, block);
1172     }
1173 
1174     return size;
1175 }
1176 
1177 /*
1178 ** The TLSF block information provides us with enough information to
1179 ** provide a reasonably intelligent implementation of realloc, growing or
1180 ** shrinking the currently allocated block as required.
1181 **
1182 ** This routine handles the somewhat esoteric edge cases of realloc:
1183 ** - a non-zero size with a null pointer will behave like malloc
1184 ** - a zero size with a non-null pointer will behave like free
1185 ** - a request that cannot be satisfied will leave the original buffer
1186 **   untouched
1187 ** - an extended buffer size will leave the newly-allocated area with
1188 **   contents undefined
1189 */
lv_tlsf_realloc(lv_tlsf_t tlsf,void * ptr,size_t size)1190 void * lv_tlsf_realloc(lv_tlsf_t tlsf, void * ptr, size_t size)
1191 {
1192     control_t * control = tlsf_cast(control_t *, tlsf);
1193     void * p = 0;
1194 
1195     /* Zero-size requests are treated as free. */
1196     if(ptr && size == 0) {
1197         lv_tlsf_free(tlsf, ptr);
1198     }
1199     /* Requests with NULL pointers are treated as malloc. */
1200     else if(!ptr) {
1201         p = lv_tlsf_malloc(tlsf, size);
1202     }
1203     else {
1204         block_header_t * block = block_from_ptr(ptr);
1205         block_header_t * next = block_next(block);
1206 
1207         const size_t cursize = block_size(block);
1208         const size_t combined = cursize + block_size(next) + block_header_overhead;
1209         const size_t adjust = adjust_request_size(size, ALIGN_SIZE);
1210         if(size > cursize && adjust == 0) {
1211             /* The request is probably too large, fail */
1212             return NULL;
1213         }
1214 
1215         tlsf_assert(!block_is_free(block) && "block already marked as free");
1216 
1217         /*
1218         ** If the next block is used, or when combined with the current
1219         ** block, does not offer enough space, we must reallocate and copy.
1220         */
1221         if(adjust > cursize && (!block_is_free(next) || adjust > combined)) {
1222             p = lv_tlsf_malloc(tlsf, size);
1223             if(p) {
1224                 const size_t minsize = tlsf_min(cursize, size);
1225                 lv_memcpy(p, ptr, minsize);
1226                 lv_tlsf_free(tlsf, ptr);
1227             }
1228         }
1229         else {
1230             /* Do we need to expand to the next block? */
1231             if(adjust > cursize) {
1232                 block_merge_next(control, block);
1233                 block_mark_as_used(block);
1234             }
1235 
1236             /* Trim the resulting block and return the original pointer. */
1237             block_trim_used(control, block, adjust);
1238             p = ptr;
1239         }
1240     }
1241 
1242     return p;
1243 }
1244 
1245 #endif /* LV_MEM_CUSTOM == 0 */
1246