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

source code of qtmultimedia/src/3rdparty/tlsf/tlsf.cpp