~kris/9p

9hist

ref: 3cfbb8523f7fdef04a8e53f148ca62a15d0c5c90 9hist/gnot/lock.c -rw-r--r-- 1.5 KiB
3cfbb852 — David du Colombier Plan 9 from Bell Labs 1991-04-27 35 years ago
                                                                                
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include "u.h"
#include "lib.h"
#include "mem.h"
#include "dat.h"
#include "fns.h"

#define PCOFF -1

/*
 *  N.B.  Ken's compiler generates a TAS instruction for the sequence:
 *
 *  	if(l->key >= 0){
 *		l->key |= 0x80;
 *		...
 *
 *	DO NOT TAKE THE ADDRESS OF l->key or the TAS will disappear.
 */
void
lock(Lock *l)
{
	Lock *ll = l;	/* do NOT take the address of ll */
	int i;

	/*
	 * Try the fast grab first
	 */
    	if(ll->key >= 0){
		ll->key |= 0x80;
		ll->pc = ((ulong*)&l)[PCOFF];
		return;
	}
	for(i=0; i<10000000; i++)
    		if(ll->key >= 0){
			ll->key |= 0x80;
			ll->pc = ((ulong*)&l)[PCOFF];
			return;
		}
	ll->key = 0;
	print("lock loop %lux pc %lux held by pc %lux\n", l, ((ulong*)&l)[PCOFF], l->pc);
}

int
canlock(Lock *l)
{
	Lock *ll = l;	/* do NOT take the address of ll */
	if(ll->key >= 0){
		ll->key |= 0x80;
		ll->pc = ((ulong*)&l)[PCOFF];
		return 1;
	}
	return 0;
}

void
unlock(Lock *l)
{
	l->pc = 0;
	l->key = 0;
}

void
qlock(QLock *q)
{
	Proc *p;

	if(canlock(&q->use))
		return;
	lock(&q->queue);
	if(canlock(&q->use)){
		unlock(&q->queue);
		return;
	}
	p = q->tail;
	if(p == 0)
		q->head = u->p;
	else
		p->qnext = u->p;
	q->tail = u->p;
	u->p->qnext = 0;
	u->p->state = Queueing;
	u->p->qlock = q;	/* DEBUG */
	unlock(&q->queue);
	sched();
}

int
canqlock(QLock *q)
{
	return canlock(&q->use);
}

void
qunlock(QLock *q)
{
	Proc *p;

	lock(&q->queue);
	if(u)
		u->p->qlock = 0;
	if(q->head){
		p = q->head;
		q->head = p->qnext;
		if(q->head == 0)
			q->tail = 0;
		unlock(&q->queue);
		ready(p);
	}else{
		unlock(&q->use);
		unlock(&q->queue);
	}
}