75 lines
1.6 KiB
C
75 lines
1.6 KiB
C
#include <kalloc.h>
|
|
#include <memory.h>
|
|
#include <panic.h>
|
|
#include <riscv.h>
|
|
#include <spinlock.h>
|
|
#include <string.h>
|
|
#include <types.h>
|
|
|
|
// Physical memory allocator, for user processes,
|
|
// kernel stacks, page-table pages,
|
|
// and pipe buffers. Allocates whole 4096-byte pages.
|
|
|
|
/** Free list of physical pages. */
|
|
void freerange(void *physaddr_start, void *physaddr_end);
|
|
|
|
/** First address after kernel. Provided kernel.ld */
|
|
extern char kernel_end[];
|
|
|
|
/** A run is a node in the free list. */
|
|
struct Run {
|
|
struct Run *next;
|
|
};
|
|
|
|
/** Kernel memory allocator. */
|
|
struct {
|
|
struct Spinlock lock;
|
|
struct Run *freelist;
|
|
} kmem;
|
|
|
|
void kalloc_init() {
|
|
initlock(&kmem.lock, "kmem");
|
|
freerange(kernel_end, (void *)PHYSTOP);
|
|
}
|
|
|
|
void freerange(void *physaddr_start, void *physaddr_end) {
|
|
char *p;
|
|
p = (char *)PGROUNDUP((u64)physaddr_start);
|
|
for (; p + PGSIZE <= (char *)physaddr_end; p += PGSIZE) kfree(p);
|
|
}
|
|
|
|
void kfree(void *pa) {
|
|
struct Run *r;
|
|
|
|
// Assert that page is a ligned to a page boundary and that its correctly
|
|
// sized
|
|
if (((u64)pa % PGSIZE) != 0 || (char *)pa < kernel_end ||
|
|
(u64)pa >= PHYSTOP)
|
|
panic("kfree");
|
|
|
|
// Fill with junk to catch dangling refs.
|
|
memset(pa, 1, PGSIZE);
|
|
|
|
r = (struct Run *)pa;
|
|
|
|
acquire(&kmem.lock);
|
|
r->next = kmem.freelist;
|
|
kmem.freelist = r;
|
|
release(&kmem.lock);
|
|
}
|
|
|
|
void *kalloc(void) {
|
|
struct Run *r;
|
|
|
|
acquire(&kmem.lock);
|
|
|
|
r = kmem.freelist;
|
|
|
|
if (r)
|
|
kmem.freelist = r->next;
|
|
release(&kmem.lock);
|
|
if (r)
|
|
memset((char *)r, 5, PGSIZE); // fill with junk
|
|
|
|
return (void *)r;
|
|
}
|