source: asp3_tinet_ecnl_rx/trunk/asp3_dcre/syssvc/tlsf/tlsf.c@ 387

Last change on this file since 387 was 387, checked in by coas-nagasima, 5 years ago

ファイルディスクリプタ処理を更新

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc;charset=UTF-8
File size: 32.7 KB
Line 
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#include <stdio.h>
8#include <t_syslog.h>
9
10#include "tlsf.h"
11
12#undef _MSC_VER
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(high);
190 }
191 else
192 {
193 bits = tlsf_fls((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(block_to_ptr(block),
444 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(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(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 && size < block_size_max)
500 {
501 const size_t aligned = align_up(size, align);
502 adjust = tlsf_max(aligned, block_size_min);
503 }
504 return adjust;
505}
506
507/*
508** TLSF utility functions. In most cases, these are direct translations of
509** the documentation found in the white paper.
510*/
511
512static void mapping_insert(size_t size, int* fli, int* sli)
513{
514 int fl, sl;
515 if (size < SMALL_BLOCK_SIZE)
516 {
517 /* Store small blocks in first list. */
518 fl = 0;
519 sl = tlsf_cast(int, size) / (SMALL_BLOCK_SIZE / SL_INDEX_COUNT);
520 }
521 else
522 {
523 fl = tlsf_fls_sizet(size);
524 sl = tlsf_cast(int, size >> (fl - SL_INDEX_COUNT_LOG2)) ^ (1 << SL_INDEX_COUNT_LOG2);
525 fl -= (FL_INDEX_SHIFT - 1);
526 }
527 *fli = fl;
528 *sli = sl;
529}
530
531/* This version rounds up to the next block size (for allocations) */
532static void mapping_search(size_t size, int* fli, int* sli)
533{
534 if (size >= SMALL_BLOCK_SIZE)
535 {
536 const size_t round = (1 << (tlsf_fls_sizet(size) - SL_INDEX_COUNT_LOG2)) - 1;
537 size += round;
538 }
539 mapping_insert(size, fli, sli);
540}
541
542static block_header_t* search_suitable_block(control_t* control, int* fli, int* sli)
543{
544 int fl = *fli;
545 int sl = *sli;
546
547 /*
548 ** First, search for a block in the list associated with the given
549 ** fl/sl index.
550 */
551 unsigned int sl_map = control->sl_bitmap[fl] & (~0U << sl);
552 if (!sl_map)
553 {
554 /* No block exists. Search in the next largest first-level list. */
555 const unsigned int fl_map = control->fl_bitmap & (~0U << (fl + 1));
556 if (!fl_map)
557 {
558 /* No free blocks available, memory has been exhausted. */
559 return 0;
560 }
561
562 fl = tlsf_ffs(fl_map);
563 *fli = fl;
564 sl_map = control->sl_bitmap[fl];
565 }
566 tlsf_assert(sl_map && "internal error - second level bitmap is null");
567 sl = tlsf_ffs(sl_map);
568 *sli = sl;
569
570 /* Return the first block in the free list. */
571 return control->blocks[fl][sl];
572}
573
574/* Remove a free block from the free list.*/
575static void remove_free_block(control_t* control, block_header_t* block, int fl, int sl)
576{
577 block_header_t* prev = block->prev_free;
578 block_header_t* next = block->next_free;
579 tlsf_assert(prev && "prev_free field can not be null");
580 tlsf_assert(next && "next_free field can not be null");
581 next->prev_free = prev;
582 prev->next_free = next;
583
584 /* If this block is the head of the free list, set new head. */
585 if (control->blocks[fl][sl] == block)
586 {
587 control->blocks[fl][sl] = next;
588
589 /* If the new head is null, clear the bitmap. */
590 if (next == &control->block_null)
591 {
592 control->sl_bitmap[fl] &= ~(1 << sl);
593
594 /* If the second bitmap is now empty, clear the fl bitmap. */
595 if (!control->sl_bitmap[fl])
596 {
597 control->fl_bitmap &= ~(1 << fl);
598 }
599 }
600 }
601}
602
603/* Insert a free block into the free block list. */
604static void insert_free_block(control_t* control, block_header_t* block, int fl, int sl)
605{
606 block_header_t* current = control->blocks[fl][sl];
607 tlsf_assert(current && "free list cannot have a null entry");
608 tlsf_assert(block && "cannot insert a null entry into the free list");
609 block->next_free = current;
610 block->prev_free = &control->block_null;
611 current->prev_free = block;
612
613 tlsf_assert(block_to_ptr(block) == align_ptr(block_to_ptr(block), ALIGN_SIZE)
614 && "block not aligned properly");
615 /*
616 ** Insert the new block at the head of the list, and mark the first-
617 ** and second-level bitmaps appropriately.
618 */
619 control->blocks[fl][sl] = block;
620 control->fl_bitmap |= (1 << fl);
621 control->sl_bitmap[fl] |= (1 << sl);
622}
623
624/* Remove a given block from the free list. */
625static void block_remove(control_t* control, block_header_t* block)
626{
627 int fl, sl;
628 mapping_insert(block_size(block), &fl, &sl);
629 remove_free_block(control, block, fl, sl);
630}
631
632/* Insert a given block into the free list. */
633static void block_insert(control_t* control, block_header_t* block)
634{
635 int fl, sl;
636 mapping_insert(block_size(block), &fl, &sl);
637 insert_free_block(control, block, fl, sl);
638}
639
640static int block_can_split(block_header_t* block, size_t size)
641{
642 return block_size(block) >= sizeof(block_header_t) + size;
643}
644
645/* Split a block into two, the second of which is free. */
646static block_header_t* block_split(block_header_t* block, size_t size)
647{
648 /* Calculate the amount of space left in the remaining block. */
649 block_header_t* remaining =
650 offset_to_block(block_to_ptr(block), size - block_header_overhead);
651
652 const size_t remain_size = block_size(block) - (size + block_header_overhead);
653
654 tlsf_assert(block_to_ptr(remaining) == align_ptr(block_to_ptr(remaining), ALIGN_SIZE)
655 && "remaining block not aligned properly");
656
657 tlsf_assert(block_size(block) == remain_size + size + block_header_overhead);
658 block_set_size(remaining, remain_size);
659 tlsf_assert(block_size(remaining) >= block_size_min && "block split with invalid size");
660
661 block_set_size(block, size);
662 block_mark_as_free(remaining);
663
664 return remaining;
665}
666
667/* Absorb a free block's storage into an adjacent previous free block. */
668static block_header_t* block_absorb(block_header_t* prev, block_header_t* block)
669{
670 tlsf_assert(!block_is_last(prev) && "previous block can't be last");
671 /* Note: Leaves flags untouched. */
672 prev->size += block_size(block) + block_header_overhead;
673 block_link_next(prev);
674 return prev;
675}
676
677/* Merge a just-freed block with an adjacent previous free block. */
678static block_header_t* block_merge_prev(control_t* control, block_header_t* block)
679{
680 if (block_is_prev_free(block))
681 {
682 block_header_t* prev = block_prev(block);
683 tlsf_assert(prev && "prev physical block can't be null");
684 tlsf_assert(block_is_free(prev) && "prev block is not free though marked as such");
685 block_remove(control, prev);
686 block = block_absorb(prev, block);
687 }
688
689 return block;
690}
691
692/* Merge a just-freed block with an adjacent free block. */
693static block_header_t* block_merge_next(control_t* control, block_header_t* block)
694{
695 block_header_t* next = block_next(block);
696 tlsf_assert(next && "next physical block can't be null");
697
698 if (block_is_free(next))
699 {
700 tlsf_assert(!block_is_last(block) && "previous block can't be last");
701 block_remove(control, next);
702 block = block_absorb(block, next);
703 }
704
705 return block;
706}
707
708/* Trim any trailing block space off the end of a block, return to pool. */
709static void block_trim_free(control_t* control, block_header_t* block, size_t size)
710{
711 tlsf_assert(block_is_free(block) && "block must be free");
712 if (block_can_split(block, size))
713 {
714 block_header_t* remaining_block = block_split(block, size);
715 block_link_next(block);
716 block_set_prev_free(remaining_block);
717 block_insert(control, remaining_block);
718 }
719}
720
721/* Trim any trailing block space off the end of a used block, return to pool. */
722static void block_trim_used(control_t* control, block_header_t* block, size_t size)
723{
724 tlsf_assert(!block_is_free(block) && "block must be used");
725 if (block_can_split(block, size))
726 {
727 /* If the next block is free, we must coalesce. */
728 block_header_t* remaining_block = block_split(block, size);
729 block_set_prev_used(remaining_block);
730
731 remaining_block = block_merge_next(control, remaining_block);
732 block_insert(control, remaining_block);
733 }
734}
735
736static block_header_t* block_trim_free_leading(control_t* control, block_header_t* block, size_t size)
737{
738 block_header_t* remaining_block = block;
739 if (block_can_split(block, size))
740 {
741 /* We want the 2nd block. */
742 remaining_block = block_split(block, size - block_header_overhead);
743 block_set_prev_free(remaining_block);
744
745 block_link_next(block);
746 block_insert(control, block);
747 }
748
749 return remaining_block;
750}
751
752static block_header_t* block_locate_free(control_t* control, size_t size)
753{
754 int fl = 0, sl = 0;
755 block_header_t* block = 0;
756
757 if (size)
758 {
759 mapping_search(size, &fl, &sl);
760 block = search_suitable_block(control, &fl, &sl);
761 }
762
763 if (block)
764 {
765 tlsf_assert(block_size(block) >= size);
766 remove_free_block(control, block, fl, sl);
767 }
768
769 return block;
770}
771
772static void* block_prepare_used(control_t* control, block_header_t* block, size_t size)
773{
774 void* p = 0;
775 if (block)
776 {
777 tlsf_assert(size && "size must be non-zero");
778 block_trim_free(control, block, size);
779 block_mark_as_used(block);
780 p = block_to_ptr(block);
781 }
782 return p;
783}
784
785/* Clear structure and point all empty lists at the null block. */
786static void control_construct(control_t* control)
787{
788 int i, j;
789
790 control->block_null.next_free = &control->block_null;
791 control->block_null.prev_free = &control->block_null;
792
793 control->fl_bitmap = 0;
794 for (i = 0; i < FL_INDEX_COUNT; ++i)
795 {
796 control->sl_bitmap[i] = 0;
797 for (j = 0; j < SL_INDEX_COUNT; ++j)
798 {
799 control->blocks[i][j] = &control->block_null;
800 }
801 }
802}
803
804/*
805** Debugging utilities.
806*/
807
808typedef struct integrity_t
809{
810 int prev_status;
811 int status;
812} integrity_t;
813
814#define tlsf_insist(x) { tlsf_assert(x); if (!(x)) { status--; } }
815
816static void integrity_walker(void* ptr, size_t size, int used, void* user)
817{
818 block_header_t* block = block_from_ptr(ptr);
819 integrity_t* integ = tlsf_cast(integrity_t*, user);
820 const int this_prev_status = block_is_prev_free(block) ? 1 : 0;
821 const int this_status = block_is_free(block) ? 1 : 0;
822 const size_t this_block_size = block_size(block);
823
824 int status = 0;
825 (void)used;
826 tlsf_insist(integ->prev_status == this_prev_status && "prev status incorrect");
827 tlsf_insist(size == this_block_size && "block size incorrect");
828
829 integ->prev_status = this_status;
830 integ->status += status;
831}
832
833int tlsf_check(tlsf_t tlsf)
834{
835 int i, j;
836
837 control_t* control = tlsf_cast(control_t*, tlsf);
838 int status = 0;
839
840 /* Check that the free lists and bitmaps are accurate. */
841 for (i = 0; i < FL_INDEX_COUNT; ++i)
842 {
843 for (j = 0; j < SL_INDEX_COUNT; ++j)
844 {
845 const int fl_map = control->fl_bitmap & (1 << i);
846 const int sl_list = control->sl_bitmap[i];
847 const int sl_map = sl_list & (1 << j);
848 const block_header_t* block = control->blocks[i][j];
849
850 /* Check that first- and second-level lists agree. */
851 if (!fl_map)
852 {
853 tlsf_insist(!sl_map && "second-level map must be null");
854 }
855
856 if (!sl_map)
857 {
858 tlsf_insist(block == &control->block_null && "block list must be null");
859 continue;
860 }
861
862 /* Check that there is at least one free block. */
863 tlsf_insist(sl_list && "no free blocks in second-level map");
864 tlsf_insist(block != &control->block_null && "block should not be null");
865
866 while (block != &control->block_null)
867 {
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
887static void default_walker(void* ptr, size_t size, int used, void* user)
888{
889 (void)user;
890 syslog(LOG_NOTICE, "\t%p %s size: %x (%p)", ptr, used ? "used" : "free", (unsigned int)size, block_from_ptr(ptr));
891}
892
893void tlsf_walk_pool(pool_t pool, tlsf_walker walker, void* user)
894{
895 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 {
901 pool_walker(
902 block_to_ptr(block),
903 block_size(block),
904 !block_is_free(block),
905 user);
906 block = block_next(block);
907 }
908}
909
910size_t tlsf_block_size(void* ptr)
911{
912 size_t size = 0;
913 if (ptr)
914 {
915 const block_header_t* block = block_from_ptr(ptr);
916 size = block_size(block);
917 }
918 return size;
919}
920
921int tlsf_check_pool(pool_t pool)
922{
923 /* Check that the blocks are physically correct. */
924 integrity_t integ = { 0, 0 };
925 tlsf_walk_pool(pool, integrity_walker, &integ);
926
927 return integ.status;
928}
929
930/*
931** Size of the TLSF structures in a given memory block passed to
932** tlsf_create, equal to the size of a control_t
933*/
934size_t tlsf_size(void)
935{
936 return sizeof(control_t);
937}
938
939size_t tlsf_align_size(void)
940{
941 return ALIGN_SIZE;
942}
943
944size_t tlsf_block_size_min(void)
945{
946 return block_size_min;
947}
948
949size_t tlsf_block_size_max(void)
950{
951 return block_size_max;
952}
953
954/*
955** Overhead of the TLSF structures in a given memory block passed to
956** tlsf_add_pool, equal to the overhead of a free block and the
957** sentinel block.
958*/
959size_t tlsf_pool_overhead(void)
960{
961 return 2 * block_header_overhead;
962}
963
964size_t tlsf_alloc_overhead(void)
965{
966 return block_header_overhead;
967}
968
969pool_t tlsf_add_pool(tlsf_t tlsf, void* mem, size_t bytes)
970{
971 block_header_t* block;
972 block_header_t* next;
973
974 const size_t pool_overhead = tlsf_pool_overhead();
975 const size_t pool_bytes = align_down(bytes - pool_overhead, ALIGN_SIZE);
976
977 if (((ptrdiff_t)mem % ALIGN_SIZE) != 0)
978 {
979 syslog(LOG_NOTICE, "tlsf_add_pool: Memory must be aligned by %u bytes.",
980 (unsigned int)ALIGN_SIZE);
981 return 0;
982 }
983
984 if (pool_bytes < block_size_min || pool_bytes > block_size_max)
985 {
986#if defined (TLSF_64BIT)
987 syslog(LOG_NOTICE, "tlsf_add_pool: Memory size must be between 0x%x and 0x%x00 bytes.",
988 (unsigned int)(pool_overhead + block_size_min),
989 (unsigned int)((pool_overhead + block_size_max) / 256));
990#else
991 syslog(LOG_NOTICE, "tlsf_add_pool: Memory size must be between %u and %u bytes.",
992 (unsigned int)(pool_overhead + block_size_min),
993 (unsigned int)(pool_overhead + block_size_max));
994#endif
995 return 0;
996 }
997
998 /*
999 ** Create the main free block. Offset the start of the block slightly
1000 ** so that the prev_phys_block field falls outside of the pool -
1001 ** it will never be used.
1002 */
1003 block = offset_to_block(mem, -(tlsfptr_t)block_header_overhead);
1004 block_set_size(block, pool_bytes);
1005 block_set_free(block);
1006 block_set_prev_used(block);
1007 block_insert(tlsf_cast(control_t*, tlsf), block);
1008
1009 /* Split the block to create a zero-size sentinel block. */
1010 next = block_link_next(block);
1011 block_set_size(next, 0);
1012 block_set_used(next);
1013 block_set_prev_free(next);
1014
1015 return mem;
1016}
1017
1018void tlsf_remove_pool(tlsf_t tlsf, pool_t pool)
1019{
1020 control_t* control = tlsf_cast(control_t*, tlsf);
1021 block_header_t* block = offset_to_block(pool, -(int)block_header_overhead);
1022
1023 int fl = 0, sl = 0;
1024
1025 tlsf_assert(block_is_free(block) && "block should be free");
1026 tlsf_assert(!block_is_free(block_next(block)) && "next block should not be free");
1027 tlsf_assert(block_size(block_next(block)) == 0 && "next block size should be zero");
1028
1029 mapping_insert(block_size(block), &fl, &sl);
1030 remove_free_block(control, block, fl, sl);
1031}
1032
1033/*
1034** TLSF main interface.
1035*/
1036
1037#if _DEBUG
1038int test_ffs_fls()
1039{
1040 /* Verify ffs/fls work properly. */
1041 int rv = 0;
1042 rv += (tlsf_ffs(0) == -1) ? 0 : 0x1;
1043 rv += (tlsf_fls(0) == -1) ? 0 : 0x2;
1044 rv += (tlsf_ffs(1) == 0) ? 0 : 0x4;
1045 rv += (tlsf_fls(1) == 0) ? 0 : 0x8;
1046 rv += (tlsf_ffs(0x80000000) == 31) ? 0 : 0x10;
1047 rv += (tlsf_ffs(0x80008000) == 15) ? 0 : 0x20;
1048 rv += (tlsf_fls(0x80000008) == 31) ? 0 : 0x40;
1049 rv += (tlsf_fls(0x7FFFFFFF) == 30) ? 0 : 0x80;
1050
1051#if defined (TLSF_64BIT)
1052 rv += (tlsf_fls_sizet(0x80000000) == 31) ? 0 : 0x100;
1053 rv += (tlsf_fls_sizet(0x100000000) == 32) ? 0 : 0x200;
1054 rv += (tlsf_fls_sizet(0xffffffffffffffff) == 63) ? 0 : 0x400;
1055#endif
1056
1057 if (rv)
1058 {
1059 syslog(LOG_NOTICE, "test_ffs_fls: %x ffs/fls tests failed.", rv);
1060 }
1061 return rv;
1062}
1063#endif
1064
1065tlsf_t tlsf_create(void* mem)
1066{
1067#if _DEBUG
1068 if (test_ffs_fls())
1069 {
1070 return 0;
1071 }
1072#endif
1073
1074 if (((tlsfptr_t)mem % ALIGN_SIZE) != 0)
1075 {
1076 syslog(LOG_NOTICE, "tlsf_create: Memory must be aligned to %u bytes.",
1077 (unsigned int)ALIGN_SIZE);
1078 return 0;
1079 }
1080
1081 control_construct(tlsf_cast(control_t*, mem));
1082
1083 return tlsf_cast(tlsf_t, mem);
1084}
1085
1086tlsf_t tlsf_create_with_pool(void* mem, size_t bytes)
1087{
1088 tlsf_t tlsf = tlsf_create(mem);
1089 tlsf_add_pool(tlsf, (char*)mem + tlsf_size(), bytes - tlsf_size());
1090 return tlsf;
1091}
1092
1093void tlsf_destroy(tlsf_t tlsf)
1094{
1095 /* Nothing to do. */
1096 (void)tlsf;
1097}
1098
1099pool_t tlsf_get_pool(tlsf_t tlsf)
1100{
1101 return tlsf_cast(pool_t, (char*)tlsf + tlsf_size());
1102}
1103
1104void* tlsf_malloc(tlsf_t tlsf, size_t size)
1105{
1106 control_t* control = tlsf_cast(control_t*, tlsf);
1107 const size_t adjust = adjust_request_size(size, ALIGN_SIZE);
1108 block_header_t* block = block_locate_free(control, adjust);
1109 return block_prepare_used(control, block, adjust);
1110}
1111
1112void* tlsf_memalign(tlsf_t tlsf, size_t align, size_t size)
1113{
1114 control_t* control = tlsf_cast(control_t*, tlsf);
1115 const size_t adjust = adjust_request_size(size, ALIGN_SIZE);
1116
1117 /*
1118 ** We must allocate an additional minimum block size bytes so that if
1119 ** our free block will leave an alignment gap which is smaller, we can
1120 ** trim a leading free block and release it back to the pool. We must
1121 ** do this because the previous physical block is in use, therefore
1122 ** the prev_phys_block field is not valid, and we can't simply adjust
1123 ** the size of that block.
1124 */
1125 const size_t gap_minimum = sizeof(block_header_t);
1126 const size_t size_with_gap = adjust_request_size(adjust + align + gap_minimum, align);
1127
1128 /*
1129 ** If alignment is less than or equals base alignment, we're done.
1130 ** If we requested 0 bytes, return null, as tlsf_malloc(0) does.
1131 */
1132 const size_t aligned_size = (adjust && align > ALIGN_SIZE) ? size_with_gap : adjust;
1133
1134 block_header_t* block = block_locate_free(control, aligned_size);
1135
1136 /* This can't be a static assert. */
1137 tlsf_assert(sizeof(block_header_t) == block_size_min + block_header_overhead);
1138
1139 if (block)
1140 {
1141 void* ptr = block_to_ptr(block);
1142 void* aligned = align_ptr(ptr, align);
1143 size_t gap = tlsf_cast(size_t,
1144 tlsf_cast(tlsfptr_t, aligned) - tlsf_cast(tlsfptr_t, ptr));
1145
1146 /* If gap size is too small, offset to next aligned boundary. */
1147 if (gap && gap < gap_minimum)
1148 {
1149 const size_t gap_remain = gap_minimum - gap;
1150 const size_t offset = tlsf_max(gap_remain, align);
1151 const void* next_aligned = tlsf_cast(void*,
1152 tlsf_cast(tlsfptr_t, aligned) + offset);
1153
1154 aligned = align_ptr(next_aligned, align);
1155 gap = tlsf_cast(size_t,
1156 tlsf_cast(tlsfptr_t, aligned) - tlsf_cast(tlsfptr_t, ptr));
1157 }
1158
1159 if (gap)
1160 {
1161 tlsf_assert(gap >= gap_minimum && "gap size too small");
1162 block = block_trim_free_leading(control, block, gap);
1163 }
1164 }
1165
1166 return block_prepare_used(control, block, adjust);
1167}
1168
1169void tlsf_free(tlsf_t tlsf, void* ptr)
1170{
1171 /* Don't attempt to free a NULL pointer. */
1172 if (ptr)
1173 {
1174 control_t* control = tlsf_cast(control_t*, tlsf);
1175 block_header_t* block = block_from_ptr(ptr);
1176 tlsf_assert(!block_is_free(block) && "block already marked as free");
1177 block_mark_as_free(block);
1178 block = block_merge_prev(control, block);
1179 block = block_merge_next(control, block);
1180 block_insert(control, block);
1181 }
1182}
1183
1184/*
1185** The TLSF block information provides us with enough information to
1186** provide a reasonably intelligent implementation of realloc, growing or
1187** shrinking the currently allocated block as required.
1188**
1189** This routine handles the somewhat esoteric edge cases of realloc:
1190** - a non-zero size with a null pointer will behave like malloc
1191** - a zero size with a non-null pointer will behave like free
1192** - a request that cannot be satisfied will leave the original buffer
1193** untouched
1194** - an extended buffer size will leave the newly-allocated area with
1195** contents undefined
1196*/
1197void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size)
1198{
1199 control_t* control = tlsf_cast(control_t*, tlsf);
1200 void* p = 0;
1201
1202 /* Zero-size requests are treated as free. */
1203 if (ptr && size == 0)
1204 {
1205 tlsf_free(tlsf, ptr);
1206 }
1207 /* Requests with NULL pointers are treated as malloc. */
1208 else if (!ptr)
1209 {
1210 p = tlsf_malloc(tlsf, size);
1211 }
1212 else
1213 {
1214 block_header_t* block = block_from_ptr(ptr);
1215 block_header_t* next = block_next(block);
1216
1217 const size_t cursize = block_size(block);
1218 const size_t combined = cursize + block_size(next) + block_header_overhead;
1219 const size_t adjust = adjust_request_size(size, ALIGN_SIZE);
1220
1221 tlsf_assert(!block_is_free(block) && "block already marked as free");
1222
1223 /*
1224 ** If the next block is used, or when combined with the current
1225 ** block, does not offer enough space, we must reallocate and copy.
1226 */
1227 if (adjust > cursize && (!block_is_free(next) || adjust > combined))
1228 {
1229 p = tlsf_malloc(tlsf, size);
1230 if (p)
1231 {
1232 const size_t minsize = tlsf_min(cursize, size);
1233 memcpy(p, ptr, minsize);
1234 tlsf_free(tlsf, ptr);
1235 }
1236 }
1237 else
1238 {
1239 /* Do we need to expand to the next block? */
1240 if (adjust > cursize)
1241 {
1242 block_merge_next(control, block);
1243 block_mark_as_used(block);
1244 }
1245
1246 /* Trim the resulting block and return the original pointer. */
1247 block_trim_used(control, block, adjust);
1248 p = ptr;
1249 }
1250 }
1251
1252 return p;
1253}
Note: See TracBrowser for help on using the repository browser.