forked from mit-pdos/xv6-public
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspinlock.c
52 lines (43 loc) · 1.29 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
#include "types.h"
#include "defs.h"
#include "x86.h"
#include "mmu.h"
#define LOCK_FREE -1
#define DEBUG 0
uint32_t kernel_lock = LOCK_FREE;
int getcallerpc(void *v) {
return ((int*)v)[-1];
}
// lock = LOCK_FREE if free, else = cpu_id of owner CPU
void
acquire_spinlock(uint32_t* lock)
{
int cpu_id = cpu();
// on a real machine there would be a memory barrier here
if(DEBUG) cprintf("cpu%d: acquiring at %x\n", cpu_id, getcallerpc(&lock));
write_eflags(read_eflags() & ~FL_IF);
if (*lock == cpu_id)
panic("recursive lock");
while ( cmpxchg(LOCK_FREE, cpu_id, lock) != cpu_id ) { ; }
if(DEBUG) cprintf("cpu%d: acquired at %x\n", cpu_id, getcallerpc(&lock));
}
void
release_spinlock(uint32_t* lock)
{
int cpu_id = cpu();
if(DEBUG) cprintf ("cpu%d: releasing at %x\n", cpu_id, getcallerpc(&lock));
if (*lock != cpu_id)
panic("release_spinlock: releasing a lock that i don't own\n");
*lock = LOCK_FREE;
// on a real machine there would be a memory barrier here
write_eflags(read_eflags() | FL_IF);
}
void
release_grant_spinlock(uint32_t* lock, int c)
{
int cpu_id = cpu();
if(DEBUG) cprintf ("cpu%d: release_grant to %d at %x\n", cpu_id, c, getcallerpc(&lock));
if (*lock != cpu_id)
panic("release_spinlock: releasing a lock that i don't own\n");
*lock = c;
}