forked from mit-pdos/xv6-public
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spinlock.c
65 lines (52 loc) · 1.24 KB
/
spinlock.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include "types.h"
#include "defs.h"
#include "x86.h"
#include "mmu.h"
#include "param.h"
#include "proc.h"
#include "spinlock.h"
#define DEBUG 0
extern use_printf_lock;
int getcallerpc(void *v) {
return ((int*)v)[-1];
}
void
acquire(struct spinlock * lock)
{
unsigned who;
if(curproc[cpu()])
who = (unsigned) curproc[cpu()];
else
who = cpu() + 1;
if(DEBUG) cprintf("cpu%d: acquiring at %x\n", cpu(), getcallerpc(&lock));
if (lock->who == who && lock->locked){
lock->count += 1;
} else {
cli();
// if we get the lock, eax will be zero
// if we don't get the lock, eax will be one
while ( cmpxchg(0, 1, &lock->locked) == 1 ) { ; }
lock->locker_pc = getcallerpc(&lock);
lock->count = 1;
lock->who = who;
}
if(DEBUG) cprintf("cpu%d: acquired at %x\n", cpu(), getcallerpc(&lock));
}
void
release(struct spinlock * lock)
{
unsigned who;
if(curproc[cpu()])
who = (unsigned) curproc[cpu()];
else
who = cpu() + 1;
if(DEBUG) cprintf ("cpu%d: releasing at %x\n", cpu(), getcallerpc(&lock));
if(lock->who != who || lock->count < 1 || lock->locked != 1)
panic("release");
lock->count -= 1;
if(lock->count < 1){
lock->who = 0;
cmpxchg(1, 0, &lock->locked);
sti();
}
}