raz / lib / Thread.linux-x86_64.raz

267 lines · 8.8 KiB · raw · history · last change e0d008cd

1(* Threads, made with the clone system call in a program without C.
2 Each runs on a stack of its own, mmaped, with a page below it that
3 can't be touched, so that running off the stack stops the program
4 rather than spoiling what lies below; above it, a little stack for
5 Rt's signal handlers, so that they can say so. join waits on the
6 thread's id, which the kernel clears, and wakes it for, when the
7 thread ends; a Mutex sleeps on a futex.
8
9 A program that uses C makes them with C's pthread_create instead,
10 since C keeps things of each thread's own, errno and its buffers,
11 that a thread clone makes wouldn't have. The compiler's entry point
12 finds cCreate and cJoin by name and stores C's calls in them, as it
13 stores C's exit in Rt.cExit; so this module uses no C itself, and
14 serves both kinds of program. C's thread has a stack and a guard
15 page of C's; the mapping here holds only the handlers' stack and
16 the Thread. Its test uses Check. *)
17module Thread;
18import Sys, Rt, Check;
19import SYSTEM;
20
21const
22 Failed*: ERROR = "can't start a thread";
23 Stack = 1 shl 20;
24 Alt = 16384; (* the signal handlers' stack *)
25 Page = 4096;
26 (* clone: share memory, files, signal handlers, the thread group;
27 write the id to tid, and clear it at the end *)
28 Flags = 350F00H;
29 FutexWait = 0;
30 FutexWake = 1;
31 Private = 128;
32
33type
34 (* A thread, as spawn gives it, until join. *)
35 Thread* = record
36 tid: INT; (* the kernel's id, until the thread ends; or C's pthread_t *)
37 ktid: INT; (* in a C thread, the kernel's id: 0 until it starts, -1 once it ends *)
38 base: ^U8; (* its stack's mapping, the guard page first *)
39 size: INT;
40 fn: proc(arg: ^U8); (* what it runs, and with what *)
41 arg: ^U8;
42 end;
43 (* What sigaltstack takes *)
44 AltStack = record sp: ^U8; flags, size: INT; end;
45 (* A lock whose waiters sleep, free when zeroed. Its state is 0
46 free, 1 taken, 2 taken with a thread waiting. *)
47 Mutex* = record state: INT; end;
48
49var
50 (* C's pthread_create and pthread_join, in a program that uses C;
51 nil in one that doesn't *)
52 cCreate: proc(t: ^UINT; attr: ^U8; start: proc(arg: ^U8): ^U8; arg: ^U8): I32;
53 cJoin: proc(t: UINT; result: ^^U8): I32;
54
55(* clone(flags, stack, tid, tid), the new thread starting with fn(arg)
56 on stack and ending, when fn returns, with the exit system call.
57 fn and arg go on the new stack first, since the new thread has no
58 registers but rsp of its own to find them by. Returns the new
59 thread's id, or minus an errno. *)
60proc start(flags: INT; stack: ^U8; ptid, ctid: ^INT; fn: proc(arg: ^U8); arg: ^U8): INT;
61code
62 sub rsi, 16;
63 mov [rsi], r8;
64 mov [rsi + 8], r9;
65 mov r10, rcx;
66 xor r8d, r8d; (* no tls *)
67 mov eax, 56; (* clone *)
68 syscall;
69 test rax, rax;
70 jnz parent;
71 pop rax; (* fn *)
72 pop rdi; (* arg *)
73 xor ebp, ebp; (* the first frame: Rt's report of the calls stops here *)
74 call rax;
75 xor edi, edi;
76 mov eax, 60; (* exit, this thread only *)
77 syscall;
78 parent:
79 ret;
80end start;
81
82proc futex(word: ^INT; op, val: INT): INT;
83begin
84 return SYSTEM.SYSCALL(202, word, op, val, 0);
85end;
86
87(* Where a new thread starts: the signal handlers' stack is a thread's
88 own, so it is set here, below t; then the thread runs its procedure. *)
89proc run(arg: ^U8);
90var t: ^Thread; alt: AltStack;
91begin
92 t := ^Thread(arg);
93 alt := {sp: ^U8(t) - Alt, size: Alt};
94 _ := SYSTEM.SYSCALL(131, SYSTEM.ADR(alt), 0); (* sigaltstack *)
95 t^.fn(t^.arg);
96end;
97
98(* Where a thread C makes starts, as pthread_create calls it. C keeps
99 the kernel's id of its thread to itself, so the thread notes its
100 own, for signal, and marks it gone as it ends. *)
101proc cRun(arg: ^U8): ^U8;
102var t: ^Thread;
103begin
104 t := ^Thread(arg);
105 _ := XCHG(t^.ktid, SYSTEM.SYSCALL(186)); (* gettid *)
106 run(arg);
107 _ := XCHG(t^.ktid, -1);
108 return nil;
109end;
110
111(* Starts p(arg) in a new thread. *)
112proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR);
113var base: ^U8; t: ^Thread; size: INT; tid: UINT;
114begin
115 size := Page + Stack + Alt + Page;
116 if cCreate # nil then size := Alt + Page; end; (* C gives the stack *)
117 base := Sys.mmap(size);
118 if base = nil then return nil, Failed; end;
119 (* from the top: the Thread in the last page, the handlers' stack,
120 then the thread's, starting on a page *)
121 t := ^Thread(base + size - Page);
122 t^.base := base;
123 t^.size := size;
124 t^.fn := p;
125 t^.arg := arg;
126 if cCreate # nil then
127 if cCreate(SYSTEM.ADR(tid), nil, cRun, ^U8(t)) # 0 then
128 Sys.munmap(base, size);
129 return nil, Failed;
130 end;
131 t^.tid := INT(tid);
132 return t, nil;
133 end;
134 (* mprotect: the guard page, no access; it fails when the process
135 has as many mappings as it may *)
136 if (SYSTEM.SYSCALL(10, base, Page, 0) < 0)
137 or (start(Flags, base + Page + Stack, SYSTEM.ADR(t^.tid), SYSTEM.ADR(t^.tid), run, ^U8(t)) < 0) then
138 Sys.munmap(base, size);
139 return nil, Failed;
140 end;
141 return t, nil;
142end;
143
144(* Waits for t to end, then frees its stack. *)
145proc join*(t: ^Thread);
146var tid: ^VOLATILE INT; v: INT; base: ^U8; size: INT;
147begin
148 if cJoin # nil then
149 _ := cJoin(UINT(t^.tid), nil);
150 else
151 tid := SYSTEM.ADR(t^.tid);
152 v := tid^;
153 while v # 0 do
154 _ := futex(SYSTEM.ADR(t^.tid), FutexWait, v);
155 v := tid^;
156 end;
157 end;
158 base := t^.base;
159 size := t^.size;
160 Sys.munmap(base, size);
161end;
162
163(* Sends the signal sig to t alone, not to any thread of the program
164 as Sys.kill does: 0, or minus an errno, -3 (ESRCH) if t has ended.
165 With Sys.handle(sig), a system call t waits in fails with -4, so
166 another thread can break into a read. tgkill, in a program with C
167 too, since pthread_kill is tgkill with C's id for the thread: a C
168 thread that hasn't noted its id yet is waited for. *)
169proc signal*(t: ^Thread; sig: INT): INT;
170var tid: ^VOLATILE INT; k: INT;
171begin
172 if cCreate # nil then
173 tid := SYSTEM.ADR(t^.ktid);
174 k := tid^;
175 while k = 0 do Sys.yield; k := tid^; end;
176 else
177 tid := SYSTEM.ADR(t^.tid);
178 k := tid^;
179 end;
180 if k <= 0 then return -3; end;
181 return SYSTEM.SYSCALL(234, Sys.pid(), k, sig); (* tgkill *)
182end;
183
184(* Takes m, sleeping while another thread holds it. *)
185proc lock*(var m: Mutex);
186var c: INT;
187begin
188 if CAS(m.state, 0, 1) then return; end;
189 c := XCHG(m.state, 2);
190 while c # 0 do
191 _ := futex(SYSTEM.ADR(m.state), FutexWait + Private, 2);
192 c := XCHG(m.state, 2);
193 end;
194end;
195
196(* Gives up m, which the caller holds, waking a thread that waits
197 for it. *)
198proc unlock*(var m: Mutex);
199begin
200 if XADD(m.state, -1) # 1 then
201 _ := XCHG(m.state, 0);
202 _ := futex(SYSTEM.ADR(m.state), FutexWake + Private, 1);
203 end;
204end;
205
206(* The module's test, and make stress's. It starts n threads, in waves
207 of up to alive at a time, all waiting on one Mutex the test holds
208 until the wave is out; each, given it, adds one to a count. Every
209 thread is joined, so that a stack join didn't free would, over
210 enough of them, run the process out of mappings. With "fail", it
211 starts threads, all waiting, until spawn fails, which it must do
212 with Failed: make stress and make check run it with little memory.
213 Thread [n alive], Thread fail *)
214var
215 testLock: Mutex;
216 testCount: INT;
217 wave: [1000]^Thread;
218
219proc testWork(_arg: ^U8);
220begin
221 lock(testLock);
222 INC(testCount);
223 unlock(testLock);
224end;
225
226proc testArg(i: INT): INT;
227var s: ^U8; n, v: INT;
228begin
229 s := SYSTEM.ARGV()[i];
230 v := 0;
231 n := 0;
232 while s[n] # 0 do v := v * 10 + INT(s[n]) - '0'; INC(n); end;
233 return v;
234end;
235
236(* The module's test: starts threads in waves, and counts that each ran. *)
237proc main*;
238var n, alive, started, k, i: INT; t: ^Thread; err: ERROR; fail: BOOL;
239begin
240 n := 2000; alive := 50;
241 fail := (ARGC() = 2) and (SYSTEM.ARGV()[1][0] = 'f');
242 if ARGC() = 3 then n := testArg(1); alive := testArg(2); end;
243 if fail then n := LEN(wave); alive := LEN(wave); end;
244 if (alive < 1) or (alive > LEN(wave)) then Rt.stop("Thread: alive is 1 to 1000"); end;
245 started := 0;
246 while started < n do
247 lock(testLock);
248 k := 0;
249 while (k < alive) and (started + k < n) do
250 t, err := spawn(testWork, nil);
251 if err # nil then
252 if not fail or (err # Failed) then Rt.stop("Thread.spawn failed"); end;
253 n := started + k;
254 break;
255 end;
256 wave[k] := t;
257 INC(k);
258 end;
259 unlock(testLock);
260 for i := 0 to k - 1 do join(wave[i]); end;
261 started := started + k;
262 end;
263 Check.int("Thread: every thread ran", testCount, started);
264 Check.ok(not (fail and (started = LEN(wave))), "Thread: spawn never failed");
265end;
266
267end Thread.