From 8728adbd0baa0af10e4cbacfff59d24b69a513be Mon Sep 17 00:00:00 2001 From: ridethepig Date: Thu, 2 Feb 2023 14:36:27 +0000 Subject: [PATCH] Memory allocator ok --- kernel/kalloc.c | 49 +++++++++++++++++++++++++++++++++++-------------- 1 file changed, 35 insertions(+), 14 deletions(-) diff --git a/kernel/kalloc.c b/kernel/kalloc.c index 0699e7e..6656411 100644 --- a/kernel/kalloc.c +++ b/kernel/kalloc.c @@ -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;