neptune/kern/libkern/freelist.c
2025-09-08 09:16:40 +02:00

102 lines
2.4 KiB
C

#include "freelist.h"
#include "stddef.h"
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct FreeListBlock {
struct FreeListBlock *next;
};
/* Initialize the FreeList */
int fl_init(FreeList *fl, uintptr_t start, uintptr_t end, size_t itemsize) {
size_t size = ALIGN(itemsize);
if (!fl || end <= start)
return EXIT_FAILURE;
fl->start = start;
fl->end = end;
fl->size = size;
fl->allocated = 0;
FreeListBlock *block = (FreeListBlock *)start;
for (size_t i = 0; i < fl_capacity(fl); i++) {
block->next = (FreeListBlock *)((void *)block + size);
block = block->next;
}
block->next = NULL;
fl->free = (FreeListBlock *)start;
return EXIT_SUCCESS;
}
/* Allocate some memory from the FreeList */
void *fl_alloc(FreeList *fl) {
if (!fl->free)
return NULL;
FreeListBlock *m = fl->free;
fl->free = fl->free->next;
fl->allocated++;
memset((void *)m, 0, sizeof(FreeListBlock));
return ((void *)m);
}
/* Return some memory to the FreeList */
int fl_free(FreeList *fl, void *ptr) {
if (!fl_is_managed(fl, ptr)) {
return EXIT_FAILURE; /* We cant free memory we do not own */
}
FreeListBlock *block = (FreeListBlock *)(uintptr_t)ptr;
block->next = fl->free;
fl->free = block;
fl->allocated--;
return EXIT_SUCCESS;
}
/* Returns how many slots are occupied */
size_t fl_allocated(FreeList *fl) {
return fl->allocated;
}
/* Returns how many free slots are available (O(1)) */
size_t fl_available(FreeList *fl) {
return fl_capacity(fl) - fl->allocated;
}
/* Returns the total amount of items the freelist will hold */
size_t fl_capacity(FreeList *fl) {
return (fl->end - fl->start) / fl->size;
}
/* Check if a piece of memory is managed by the FreeList */
int fl_is_managed(FreeList *fl, void *ptr) {
return ((uintptr_t)ptr >= fl->start && (uintptr_t)ptr < fl->end);
}
/* Returns the ratio of metadata versus data as a scalar in range 0..1 */
float fl_utilization(FreeList *fl, size_t itemsize) {
return (float)itemsize / fl->size;
}
/* Walks the free pages/slots, returns total count (O(n), given no cycles) */
size_t fl_check(FreeList *fl) {
int avail = 0;
FreeListBlock *cursor = fl->free;
while (cursor->next != NULL) {
avail++;
cursor = cursor->next;
}
return avail;
}