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