Skip to content
Snippets Groups Projects
kalloc.c 1.44 KiB
Newer Older
rsc's avatar
rsc committed
// Physical memory allocator, intended to allocate
// memory for user processes, kernel stacks, page table pages,
// and pipe buffers. Allocates 4096-byte pages.
rtm's avatar
rtm committed

#include "types.h"
#include "defs.h"
#include "param.h"
rtm's avatar
rtm committed
#include "spinlock.h"

rtm's avatar
rtm committed
struct run {
  struct run *next;
};
rsc's avatar
 
rsc committed

struct {
  struct spinlock lock;
  struct run *freelist;
} kmem;
rtm's avatar
rtm committed

Robert Morris's avatar
Robert Morris committed
extern char end[]; // first address after kernel loaded from ELF file

rsc's avatar
rsc committed
// Initialize free list of physical pages.
rtm's avatar
rtm committed
void
rtm's avatar
rtm committed
{
Russ Cox's avatar
Russ Cox committed
  char *p;

rsc's avatar
 
rsc committed
  initlock(&kmem.lock, "kmem");
Russ Cox's avatar
Russ Cox committed
  p = (char*)PGROUNDUP((uint)end);
  for(; p + PGSIZE - 1 < (char*)PHYSTOP; p += PGSIZE)
rtm's avatar
rtm committed
}

Austin Clements's avatar
Austin Clements committed
//PAGEBREAK: 21
// Free the page of physical memory pointed at by v,
rsc's avatar
rsc committed
// which normally should have been returned by a
// call to kalloc().  (The exception is when
rsc's avatar
rsc committed
// initializing the allocator; see kinit above.)
rtm's avatar
rtm committed
void
kfree(char *v)
rtm's avatar
rtm committed
{
  struct run *r;
rtm's avatar
rtm committed

Russ Cox's avatar
Russ Cox committed
  if((uint)v % PGSIZE || v < end || (uint)v >= PHYSTOP) 
rtm's avatar
rtm committed
    panic("kfree");

rsc's avatar
rsc committed
  // Fill with junk to catch dangling refs.
  memset(v, 1, PGSIZE);
rsc's avatar
 
rsc committed
  acquire(&kmem.lock);
Russ Cox's avatar
Russ Cox committed
  r = (struct run*)v;
  r->next = kmem.freelist;
  kmem.freelist = r;
rsc's avatar
 
rsc committed
  release(&kmem.lock);
rtm's avatar
rtm committed
}

// Allocate one 4096-byte page of physical memory.
// Returns a pointer that the kernel can use.
rsc's avatar
rsc committed
// Returns 0 if the memory cannot be allocated.
rsc's avatar
rsc committed
char*
Russ Cox's avatar
Russ Cox committed
kalloc(void)
rtm's avatar
rtm committed
{
  struct run *r;
rtm's avatar
rtm committed

rsc's avatar
 
rsc committed
  acquire(&kmem.lock);
  r = kmem.freelist;
  if(r)
    kmem.freelist = r->next;
rsc's avatar
 
rsc committed
  release(&kmem.lock);
Russ Cox's avatar
Russ Cox committed
  return (char*)r;
rtm's avatar
rtm committed
}