MIT6828-HW7-locking

在这个作业中,我们将探究中断和锁之间的一些关系。

Don’t do this

xv6执行下面的代码时,会发生什么?

1
2
3
4
struct spinlock lk;
initlock(&lk, "test lock");
acquire(&lk);
acquire(&lk);

重复上锁,第二个锁会panic。acquire的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Acquire the lock.
// Loops (spins) until the lock is acquired.
// Holding a lock for a long time may cause
// other CPUs to waste time spinning to acquire it.
void
acquire(struct spinlock *lk)
{
pushcli(); // disable interrupts to avoid deadlock.
if(holding(lk)) // 如果锁已经被holding了,那么会panic
panic("acquire");

// The xchg is atomic.
while(xchg(&lk->locked, 1) != 0);

// Tell the C compiler and the processor to not move loads or stores
// past this point, to ensure that the critical section's memory
// references happen after the lock is acquired.
__sync_synchronize();

// Record info about lock acquisition for debugging.
lk->cpu = mycpu();
getcallerpcs(&lk, lk->pcs);
}

ide.c中的中断

An acquire ensures that interrupts are off on the local processor using the cli instruction (via pushcli()), and that interrupts remain off until the release of the last lock held by that processor (at which point they are enabled using sti).

Let’s see what happens if we turn on interrupts while holding the ide lock. In iderw in ide.c, add a call to sti() after the acquire(), and a call to cli() just before the release(). Rebuild the kernel and boot it in QEMU. Chances are the kernel will panic soon after boot; try booting QEMU a few times if it doesn’t.

在iderw中加锁和释放锁部分开启中断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void
iderw(struct buf *b)
{

acquire(&idelock); //DOC:acquire-lock

// HW7: Add sti
sti();

...
// HW7: add cli just before releasing the lock
cli();
release(&idelock);
}

在添加了sticli后,如果编译并启动内核,系统会panic。

sticli的作用

sti开启中断,cli关闭中断,也就是说我们在acquirerelease之间开启了中断。

原因分析

系统提示的错误信息如下:

1
2
3
sb: size 1000 nblocks 941 ninodes 200 nlog 30 logstart 2 inodestart 32 bmap start 58
lapicid 1: panic: acquire
801043ed 80102053 80105985 801056fc 80100183 80102ae5 801036c0 801056ff 0 0

最下方一行数字为系统调用栈情况,根据调用栈,

参考文献

0%