Allocate a small/medium sized memory block from the given heap
| 609 | |
| 610 | //! Allocate a small/medium sized memory block from the given heap |
| 611 | static void* |
| 612 | _memory_allocate_from_heap(heap_t* heap, size_t size) { |
| 613 | #if ENABLE_STATISTICS |
| 614 | //For statistics we need to store the requested size in the memory block |
| 615 | size += sizeof(size_t); |
| 616 | #endif |
| 617 | |
| 618 | //Calculate the size class index and do a dependent lookup of the final class index (in case of merged classes) |
| 619 | const size_t class_idx = _memory_size_class[(size <= SMALL_SIZE_LIMIT) ? |
| 620 | ((size + (SMALL_GRANULARITY - 1)) >> SMALL_GRANULARITY_SHIFT) - 1 : |
| 621 | SMALL_CLASS_COUNT + ((size - SMALL_SIZE_LIMIT + (MEDIUM_GRANULARITY - 1)) >> MEDIUM_GRANULARITY_SHIFT) - 1].class_idx; |
| 622 | |
| 623 | span_block_t* active_block = heap->active_block + class_idx; |
| 624 | size_class_t* size_class = _memory_size_class + class_idx; |
| 625 | const count_t class_size = size_class->size; |
| 626 | |
| 627 | #if ENABLE_STATISTICS |
| 628 | heap->allocated += class_size; |
| 629 | heap->requested += size; |
| 630 | #endif |
| 631 | |
| 632 | //Step 1: Try to get a block from the currently active span. The span block bookkeeping |
| 633 | // data for the active span is stored in the heap for faster access |
| 634 | use_active: |
| 635 | if (active_block->free_count) { |
| 636 | //Happy path, we have a span with at least one free block |
| 637 | span_t* span = heap->active_span[class_idx]; |
| 638 | count_t offset = class_size * active_block->free_list; |
| 639 | uint32_t* block = pointer_offset(span, SPAN_HEADER_SIZE + offset); |
| 640 | assert(span); |
| 641 | |
| 642 | --active_block->free_count; |
| 643 | if (!active_block->free_count) { |
| 644 | //Span is now completely allocated, set the bookkeeping data in the |
| 645 | //span itself and reset the active span pointer in the heap |
| 646 | span->data.block.free_count = 0; |
| 647 | span->data.block.first_autolink = (uint16_t)size_class->block_count; |
| 648 | heap->active_span[class_idx] = 0; |
| 649 | } |
| 650 | else { |
| 651 | //Get the next free block, either from linked list or from auto link |
| 652 | if (active_block->free_list < active_block->first_autolink) { |
| 653 | active_block->free_list = (uint16_t)(*block); |
| 654 | } |
| 655 | else { |
| 656 | ++active_block->free_list; |
| 657 | ++active_block->first_autolink; |
| 658 | } |
| 659 | assert(active_block->free_list < size_class->block_count); |
| 660 | } |
| 661 | |
| 662 | #if ENABLE_STATISTICS |
| 663 | //Store the requested size for statistics |
| 664 | *(size_t*)pointer_offset(block, class_size - sizeof(size_t)) = size; |
| 665 | #endif |
| 666 | |
| 667 | return block; |
| 668 | } |
no test coverage detected