Memory allocator ok
This commit is contained in:
parent
ad57ec8cb9
commit
8728adbd0b
@ -19,14 +19,19 @@ struct run {
|
||||
};
|
||||
|
||||
struct {
|
||||
struct spinlock lock;
|
||||
struct run *freelist;
|
||||
struct spinlock lock[NCPU];
|
||||
struct run *freelist[NCPU];
|
||||
} kmem;
|
||||
|
||||
static char kmem_lock_names [NCPU][10]; // ugly but have-to impl
|
||||
|
||||
void
|
||||
kinit()
|
||||
{
|
||||
initlock(&kmem.lock, "kmem");
|
||||
for (int i = 0; i < NCPU; ++ i) {
|
||||
snprintf(kmem_lock_names[i], NELEM(kmem_lock_names[0]), "kmem%d", i);
|
||||
initlock(&kmem.lock[i], kmem_lock_names[i]);
|
||||
}
|
||||
freerange(end, (void*)PHYSTOP);
|
||||
}
|
||||
|
||||
@ -55,11 +60,13 @@ kfree(void *pa)
|
||||
memset(pa, 1, PGSIZE);
|
||||
|
||||
r = (struct run*)pa;
|
||||
|
||||
acquire(&kmem.lock);
|
||||
r->next = kmem.freelist;
|
||||
kmem.freelist = r;
|
||||
release(&kmem.lock);
|
||||
push_off();
|
||||
int _cpu = cpuid();
|
||||
acquire(&kmem.lock[_cpu]);
|
||||
r->next = kmem.freelist[_cpu];
|
||||
kmem.freelist[_cpu] = r;
|
||||
release(&kmem.lock[_cpu]);
|
||||
pop_off();
|
||||
}
|
||||
|
||||
// Allocate one 4096-byte page of physical memory.
|
||||
@ -69,13 +76,27 @@ void *
|
||||
kalloc(void)
|
||||
{
|
||||
struct run *r;
|
||||
|
||||
acquire(&kmem.lock);
|
||||
r = kmem.freelist;
|
||||
push_off();
|
||||
int _cpu = cpuid();
|
||||
acquire(&kmem.lock[_cpu]);
|
||||
r = kmem.freelist[_cpu];
|
||||
if(r)
|
||||
kmem.freelist = r->next;
|
||||
release(&kmem.lock);
|
||||
|
||||
kmem.freelist[_cpu] = r->next;
|
||||
else {
|
||||
for (int i = 0, found = 0; i < NCPU && !found; ++ i) {
|
||||
if (i != _cpu) {
|
||||
acquire(&kmem.lock[i]);
|
||||
if (kmem.freelist[i]) {
|
||||
r = kmem.freelist[i];
|
||||
kmem.freelist[i] = r->next;
|
||||
found = 1;
|
||||
}
|
||||
release(&kmem.lock[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
release(&kmem.lock[_cpu]);
|
||||
pop_off();
|
||||
if(r)
|
||||
memset((char*)r, 5, PGSIZE); // fill with junk
|
||||
return (void*)r;
|
||||
|
||||
Loading…
Reference in New Issue
Block a user