xref: /xv6-public/spinlock.c (revision 943fd378)
1 // Mutual exclusion spin locks.
2 
3 #include "types.h"
4 #include "defs.h"
5 #include "param.h"
6 #include "x86.h"
7 #include "mmu.h"
8 #include "proc.h"
9 #include "spinlock.h"
10 
11 extern int use_console_lock;
12 
13 void
14 initlock(struct spinlock *lock, char *name)
15 {
16   lock->name = name;
17   lock->locked = 0;
18   lock->cpu = 0xffffffff;
19 }
20 
21 // Acquire the lock.
22 // Loops (spins) until the lock is acquired.
23 // Holding a lock for a long time may cause
24 // other CPUs to waste time spinning to acquire it.
25 void
26 acquire(struct spinlock *lock)
27 {
28   pushcli();
29   if(holding(lock))
30     panic("acquire");
31 
32   // The xchg is atomic.
33   // It also serializes, so that reads after acquire are not
34   // reordered before it.
35   while(xchg(&lock->locked, 1) == 1)
36     ;
37 
38   // Record info about lock acquisition for debugging.
39   // The +10 is only so that we can tell the difference
40   // between forgetting to initialize lock->cpu
41   // and holding a lock on cpu 0.
42   lock->cpu = cpu() + 10;
43   getcallerpcs(&lock, lock->pcs);
44 }
45 
46 // Release the lock.
47 void
48 release(struct spinlock *lock)
49 {
50   if(!holding(lock))
51     panic("release");
52 
53   lock->pcs[0] = 0;
54   lock->cpu = 0xffffffff;
55 
56   // The xchg serializes, so that reads before release are
57   // not reordered after it.  (This reordering would be allowed
58   // by the Intel manuals, but does not happen on current
59   // Intel processors.  The xchg being asm volatile also keeps
60   // gcc from delaying the above assignments.)
61   xchg(&lock->locked, 0);
62 
63   popcli();
64 }
65 
66 // Record the current call stack in pcs[] by following the %ebp chain.
67 void
68 getcallerpcs(void *v, uint pcs[])
69 {
70   uint *ebp;
71   int i;
72 
73   ebp = (uint*)v - 2;
74   for(i = 0; i < 10; i++){
75     if(ebp == 0 || ebp == (uint*)0xffffffff)
76       break;
77     pcs[i] = ebp[1];     // saved %eip
78     ebp = (uint*)ebp[0]; // saved %ebp
79   }
80   for(; i < 10; i++)
81     pcs[i] = 0;
82 }
83 
84 // Check whether this cpu is holding the lock.
85 int
86 holding(struct spinlock *lock)
87 {
88   return lock->locked && lock->cpu == cpu() + 10;
89 }
90 
91 
92 // Pushcli/popcli are like cli/sti except that they are matched:
93 // it takes two popcli to undo two pushcli.  Also, if interrupts
94 // are off, then pushcli, popcli leaves them off.
95 
96 void
97 pushcli(void)
98 {
99   int eflags;
100 
101   eflags = read_eflags();
102   cli();
103   if(cpus[cpu()].ncli++ == 0)
104     cpus[cpu()].intena = eflags & FL_IF;
105 }
106 
107 void
108 popcli(void)
109 {
110   if(read_eflags()&FL_IF)
111     panic("popcli - interruptible");
112   if(--cpus[cpu()].ncli < 0)
113     panic("popcli");
114   if(cpus[cpu()].ncli == 0 && cpus[cpu()].intena)
115     sti();
116 }
117 
118