xref: /xv6-public/spinlock.c (revision bc8221a5)
1 // Mutual exclusion spin locks.
2 
3 #include "types.h"
4 #include "defs.h"
5 #include "param.h"
6 #include "x86.h"
7 #include "memlayout.h"
8 #include "mmu.h"
9 #include "proc.h"
10 #include "spinlock.h"
11 
12 void
13 initlock(struct spinlock *lk, char *name)
14 {
15   lk->name = name;
16   lk->locked = 0;
17   lk->cpu = 0;
18 }
19 
20 // Acquire the lock.
21 // Loops (spins) until the lock is acquired.
22 // Holding a lock for a long time may cause
23 // other CPUs to waste time spinning to acquire it.
24 void
25 acquire(struct spinlock *lk)
26 {
27   pushcli(); // disable interrupts to avoid deadlock.
28   if(holding(lk))
29     panic("acquire");
30 
31   // The xchg is atomic.
32   while(xchg(&lk->locked, 1) != 0)
33     ;
34 
35   // Tell the C compiler and the processor to not move loads or stores
36   // past this point, to ensure that the critical section's memory
37   // references happen after the lock is acquired.
38   __sync_synchronize();
39 
40   // Record info about lock acquisition for debugging.
41   lk->cpu = cpu;
42   getcallerpcs(&lk, lk->pcs);
43 }
44 
45 // Release the lock.
46 void
47 release(struct spinlock *lk)
48 {
49   if(!holding(lk))
50     panic("release");
51 
52   lk->pcs[0] = 0;
53   lk->cpu = 0;
54 
55   // Tell the C compiler and the processor to not move loads or stores
56   // past this point, to ensure that all the stores in the critical
57   // section are visible to other cores before the lock is released.
58   // Both the C compiler and the hardware may re-order loads and
59   // stores; __sync_synchronize() tells them both to not re-order.
60   __sync_synchronize();
61 
62   // Release the lock.
63   lk->locked = 0;
64 
65   popcli();
66 }
67 
68 // Record the current call stack in pcs[] by following the %ebp chain.
69 void
70 getcallerpcs(void *v, uint pcs[])
71 {
72   uint *ebp;
73   int i;
74 
75   ebp = (uint*)v - 2;
76   for(i = 0; i < 10; i++){
77     if(ebp == 0 || ebp < (uint*)KERNBASE || ebp == (uint*)0xffffffff)
78       break;
79     pcs[i] = ebp[1];     // saved %eip
80     ebp = (uint*)ebp[0]; // saved %ebp
81   }
82   for(; i < 10; i++)
83     pcs[i] = 0;
84 }
85 
86 // Check whether this cpu is holding the lock.
87 int
88 holding(struct spinlock *lock)
89 {
90   return lock->locked && lock->cpu == cpu;
91 }
92 
93 
94 // Pushcli/popcli are like cli/sti except that they are matched:
95 // it takes two popcli to undo two pushcli.  Also, if interrupts
96 // are off, then pushcli, popcli leaves them off.
97 
98 void
99 pushcli(void)
100 {
101   int eflags;
102 
103   eflags = readeflags();
104   cli();
105   if(cpu->ncli == 0)
106     cpu->intena = eflags & FL_IF;
107   cpu->ncli += 1;
108 }
109 
110 void
111 popcli(void)
112 {
113   if(readeflags()&FL_IF)
114     panic("popcli - interruptible");
115   if(--cpu->ncli < 0)
116     panic("popcli");
117   if(cpu->ncli == 0 && cpu->intena)
118     sti();
119 }
120 
121