[kutil] Protect heap allocation with a spinlock

Don't allow multiple cores to access the heap datastructures at once.
This commit is contained in:
Justin C. Miller
2021-04-07 23:02:40 -07:00
parent 19a799656a
commit 6190b05a13
2 changed files with 7 additions and 0 deletions

View File

@@ -89,6 +89,8 @@ heap_allocator::allocate(size_t length)
if (order > max_order)
return nullptr;
scoped_lock lock {m_lock};
mem_header *header = pop_free(order);
header->set_used(true);
m_allocated_size += (1 << order);
@@ -104,6 +106,8 @@ heap_allocator::free(void *p)
kassert(addr >= m_start && addr < m_end,
"Attempt to free non-heap pointer");
scoped_lock lock {m_lock};
mem_header *header = reinterpret_cast<mem_header *>(p);
header -= 1; // p points after the header
header->set_used(false);

View File

@@ -3,6 +3,7 @@
/// A buddy allocator for a memory heap
#include <stddef.h>
#include "kutil/spinlock.h"
namespace kutil {
@@ -57,6 +58,8 @@ protected:
mem_header *m_free[max_order - min_order + 1];
size_t m_allocated_size;
spinlock m_lock;
heap_allocator(const heap_allocator &) = delete;
};