Skip to content
Snippets Groups Projects
spinlock.c 1.05 KiB
Newer Older
#include "types.h"
#include "defs.h"
#include "x86.h"
#include "mmu.h"
rtm's avatar
rtm committed
#include "param.h"
#include "proc.h"
#include "spinlock.h"
rsc's avatar
 
rsc committed
// Can't call cprintf from inside these routines,
// because cprintf uses them itself.
rtm's avatar
rtm committed
//#define cprintf dont_use_cprintf
extern int use_console_lock;
rsc's avatar
 
rsc committed
int
getcallerpc(void *v)
{
	return ((int*)v)[-1];
rsc's avatar
rsc committed
acquire(struct spinlock * lock)
rtm's avatar
rtm committed
  if(holding(lock)){
    extern use_console_lock;
    use_console_lock = 0;
    cprintf("lock %s pc %x\n", lock->name ? lock->name : "", lock->pc);
rsc's avatar
rsc committed
		panic("acquire");
rtm's avatar
rtm committed
  }
rsc's avatar
rsc committed

rsc's avatar
 
rsc committed
	if(cpus[cpu()].nlock++ == 0)
		cli();
	while(cmpxchg(0, 1, &lock->locked) == 1)
		;
	cpuid(0, 0, 0, 0, 0);	// memory barrier
rsc's avatar
rsc committed
	lock->pc = getcallerpc(&lock);
	lock->cpu = cpu();
rtm's avatar
rtm committed
        cpus[cpu()].lastacquire = lock;
rsc's avatar
rsc committed
release(struct spinlock * lock)
rsc's avatar
rsc committed
	if(!holding(lock))
		panic("release");

rtm's avatar
rtm committed
        cpus[cpu()].lastrelease = lock;
rsc's avatar
 
rsc committed
	cpuid(0, 0, 0, 0, 0);	// memory barrier
	lock->locked = 0;
	if(--cpus[cpu()].nlock == 0)
rsc's avatar
 
rsc committed
		sti();
rtm's avatar
rtm committed
}

rsc's avatar
rsc committed
int
holding(struct spinlock *lock)
{
	return lock->locked && lock->cpu == cpu();
}