added base src
[xv6-db.git] / kalloc.c
blob191a839cc66e05f7a8f100fc20cb778edb42983b
1 // Physical memory allocator, intended to allocate
2 // memory for user processes, kernel stacks, page table pages,
3 // and pipe buffers. Allocates 4096-byte pages.
5 #include "types.h"
6 #include "defs.h"
7 #include "param.h"
8 #include "mmu.h"
9 #include "spinlock.h"
11 struct run {
12 struct run *next;
15 struct {
16 struct spinlock lock;
17 struct run *freelist;
18 } kmem;
20 extern char end[]; // first address after kernel loaded from ELF file
22 // Initialize free list of physical pages.
23 void
24 kinit(void)
26 char *p;
28 initlock(&kmem.lock, "kmem");
29 p = (char*)PGROUNDUP((uint)end);
30 for(; p + PGSIZE <= (char*)PHYSTOP; p += PGSIZE)
31 kfree(p);
34 // Free the page of physical memory pointed at by v,
35 // which normally should have been returned by a
36 // call to kalloc(). (The exception is when
37 // initializing the allocator; see kinit above.)
38 void
39 kfree(char *v)
41 struct run *r;
43 if((uint)v % PGSIZE || v < end || (uint)v >= PHYSTOP)
44 panic("kfree");
46 // Fill with junk to catch dangling refs.
47 memset(v, 1, PGSIZE);
49 acquire(&kmem.lock);
50 r = (struct run*)v;
51 r->next = kmem.freelist;
52 kmem.freelist = r;
53 release(&kmem.lock);
56 // Allocate one 4096-byte page of physical memory.
57 // Returns a pointer that the kernel can use.
58 // Returns 0 if the memory cannot be allocated.
59 char*
60 kalloc(void)
62 struct run *r;
64 acquire(&kmem.lock);
65 r = kmem.freelist;
66 if(r)
67 kmem.freelist = r->next;
68 release(&kmem.lock);
69 return (char*)r;