Skip to content

Commit

Permalink
lib: sbi: Implement aligned memory allocators
Browse files Browse the repository at this point in the history
This change adds a simple implementation of sbi_memalign(), for future use in
allocating aligned memory for SMMTT tables.
  • Loading branch information
grg-haas committed Jul 10, 2024
1 parent 7e97061 commit e576ed0
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
5 changes: 5 additions & 0 deletions include/sbi/sbi_heap.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ struct sbi_scratch;
void *sbi_malloc(size_t size);
void *sbi_malloc_from(struct heap_control *hpctrl, size_t size);

/** Allocate aligned from heap area */
void *sbi_memalign(size_t alignment, size_t size);
void *sbi_memalign_from(struct heap_control *hpctrl, size_t alignment,
size_t size);

/** Zero allocate from heap area */
void *sbi_zalloc(size_t size);
void *sbi_zalloc_from(struct heap_control *hpctrl, size_t size);
Expand Down
37 changes: 34 additions & 3 deletions lib/sbi/sbi_heap.c
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,17 @@ struct heap_control {

static struct heap_control global_hpctrl;

void *sbi_malloc_from(struct heap_control *hpctrl, size_t size)
static void *alloc_with_align(struct heap_control *hpctrl,
size_t align, size_t size)
{
void *ret = NULL;
struct heap_node *n, *np;

if (!size)
return NULL;

size += HEAP_ALLOC_ALIGN - 1;
size &= ~((unsigned long)HEAP_ALLOC_ALIGN - 1);
size += align - 1;
size &= ~((unsigned long)align - 1);

spin_lock(&hpctrl->lock);

Expand Down Expand Up @@ -80,11 +81,41 @@ void *sbi_malloc_from(struct heap_control *hpctrl, size_t size)
return ret;
}

void *sbi_malloc_from(struct heap_control *hpctrl, size_t size)
{
return alloc_with_align(hpctrl, HEAP_ALLOC_ALIGN, size);
}

void *sbi_malloc(size_t size)
{
return sbi_malloc_from(&global_hpctrl, size);
}

void *sbi_memalign_from(struct heap_control *hpctrl, size_t alignment,
size_t size)
{
if(alignment < HEAP_ALLOC_ALIGN) {
alignment = HEAP_ALLOC_ALIGN;
}

// Make sure alignment is power of two
if((alignment & (alignment - 1)) != 0) {
return NULL;
}

// Make sure size is multiple of alignment
if(size % alignment != 0) {
return NULL;
}

return alloc_with_align(hpctrl, alignment, size);
}

void *sbi_memalign(size_t alignment, size_t size)
{
return sbi_memalign_from(&global_hpctrl, alignment, size);
}

void *sbi_zalloc_from(struct heap_control *hpctrl, size_t size)
{
void *ret = sbi_malloc_from(hpctrl, size);
Expand Down

0 comments on commit e576ed0

Please sign in to comment.