-
Notifications
You must be signed in to change notification settings - Fork 5
/
mutexes.c
101 lines (81 loc) · 2.07 KB
/
mutexes.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
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
//
// Created by Vladimir Schneider on 2018-01-30.
//
#include "multitasker.h"
const uint16_t mutexDescriptionSize = sizeof(MutexDescription);
void _InitMutexInX(Mutex *mutex)__naked
{
(void) mutex;
// mutex->owner = 0;
// QInitNode((QNode *) mutex);
// @formatter:off
__asm
clrw y
ldw (MUTEX_OWNER,x),y
jp __InitQNodeInX
__endasm;
// @formatter:on
}
void LockMutex(Mutex *mutex)__naked {
(void) mutex;
// @formatter:off
__asm
sim
ldw x,(3,sp) ; get mutex, sp: pch, pcl, ev.h, ev.l
ldw y,x
ldw y,(MUTEX_OWNER,y)
jrne lockmutex.check ; has owner, see if it is this owner
; no owner, this task becomes the owner
ldw y,_currentTask
ldw (MUTEX_OWNER,x),y
clr (MUTEX_LOCKS,x)
jra lockmutex.done
lockmutex.check:
cpw y,_currentTask
jreq lockmutex.owner
; x is already the mutex
ldw y,#__QNodeLinkTailInXY
jp __YieldToXatYStack
lockmutex.owner:
; increment count
inc (MUTEX_LOCKS,x)
; jrne lockmutex.done
; problem now after next lock, the unlock will make mutex think it is unlocked
lockmutex.done:
rim
ret
__endasm;
// @formatter:on
}
void UnlockMutex(Mutex *mutex)__naked {
(void) mutex;
// @formatter:off
__asm
push cc
sim
ldw x,(3,sp) ; get mutex sp: pch, pcl, ev.h, ev.l
ldw y,x
ldw y,(MUTEX_OWNER,y)
jreq unlock.done ; no owner
cpw y,_currentTask
jrne unlock.done ; not the owner
; decrement lock count and if zero release it
dec (MUTEX_LOCKS,x)
jrne unlock.done ; not yet
clrw y
ldw (MUTEX_OWNER,x),y ; clear owner
; if there is a process waiting we will move it to ready queue and give it ownership
ldw y,x
cpw y,(QHEAD,x)
jreq unlock.done ; no waiters
; transfer head to ready queue
ldw y,(QHEAD,y)
ldw (MUTEX_OWNER,x),y ; give it ownership
ldw x,#_readyTasks
call __QNodeLinkTailInXY
unlock.done:
pop cc
ret
__endasm;
// @formatter:on
}