attempting to finish kalloc.c but met some trouble

This commit is contained in:
whatever 2024-11-23 21:35:55 +08:00
parent fc27289d78
commit 1e6d8a660f
3 changed files with 37 additions and 16 deletions

View File

@ -61,7 +61,7 @@ endif
# riscv64-unknown-elf- or riscv64-linux-gnu-
# perhaps in /opt/riscv/bin
#TOOLPREFIX =
TOOLPREFIX = /opt/riscv/bin/riscv64-unknown-elf-
# Try to infer the correct TOOLPREFIX if not set
ifndef TOOLPREFIX

BIN
fs.img.bk Normal file

Binary file not shown.

View File

@ -21,12 +21,13 @@ struct run {
struct {
struct spinlock lock;
struct run *freelist;
} kmem;
} kmem[NCPU];
void
void
kinit()
{
initlock(&kmem.lock, "kmem");
for(int i=0;i<NCPU;++i)
initlock(&kmem[i].lock, "kmem");
freerange(end, (void*)PHYSTOP);
}
@ -45,7 +46,9 @@ freerange(void *pa_start, void *pa_end)
// initializing the allocator; see kinit above.)
void
kfree(void *pa)
{
{
push_off();
const int cpu=cpuid();
struct run *r;
if(((uint64)pa % PGSIZE) != 0 || (char*)pa < end || (uint64)pa >= PHYSTOP)
@ -55,11 +58,11 @@ kfree(void *pa)
memset(pa, 1, PGSIZE);
r = (struct run*)pa;
acquire(&kmem.lock);
r->next = kmem.freelist;
kmem.freelist = r;
release(&kmem.lock);
acquire(&kmem[cpu].lock);
r->next = kmem[cpu].freelist;
kmem[cpu].freelist = r;
release(&kmem[cpu].lock);
pop_off();
}
// Allocate one 4096-byte page of physical memory.
@ -68,15 +71,33 @@ kfree(void *pa)
void *
kalloc(void)
{
push_off();
struct run *r;
acquire(&kmem.lock);
r = kmem.freelist;
const int cpu=cpuid();
acquire(&kmem[cpu].lock);
r = kmem[cpu].freelist;
if(r)
kmem.freelist = r->next;
release(&kmem.lock);
kmem[cpu].freelist = r->next;
while(!r)
for(int i=0;i<NCPU;++i){
if(i==cpu)
continue;
if(kmem[i].lock.locked)
continue;
acquire(&kmem[i].lock);
r=kmem[i].freelist;
if(r){
kmem[i].freelist = r->next;
goto fine;
}
release(&kmem[i].lock);
continue;
fine:
break;
}
release(&kmem[cpu].lock);
if(r)
memset((char*)r, 5, PGSIZE); // fill with junk
pop_off();
return (void*)r;
}