1 | // |
---|
2 | // Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo |
---|
3 | // |
---|
4 | // The contents of this file are covered under the licence agreement in the |
---|
5 | // file "LICENCE" distributed with Cforall. |
---|
6 | // |
---|
7 | // kernel.c -- |
---|
8 | // |
---|
9 | // Author : Thierry Delisle |
---|
10 | // Created On : Tue Jan 17 12:27:26 2017 |
---|
11 | // Last Modified By : Peter A. Buhr |
---|
12 | // Last Modified On : Tue Feb 4 13:03:15 2020 |
---|
13 | // Update Count : 58 |
---|
14 | // |
---|
15 | |
---|
16 | #define __cforall_thread__ |
---|
17 | |
---|
18 | //C Includes |
---|
19 | #include <stddef.h> |
---|
20 | #include <errno.h> |
---|
21 | #include <string.h> |
---|
22 | extern "C" { |
---|
23 | #include <stdio.h> |
---|
24 | #include <fenv.h> |
---|
25 | #include <sys/resource.h> |
---|
26 | #include <signal.h> |
---|
27 | #include <unistd.h> |
---|
28 | #include <limits.h> // PTHREAD_STACK_MIN |
---|
29 | #include <sys/mman.h> // mprotect |
---|
30 | } |
---|
31 | |
---|
32 | //CFA Includes |
---|
33 | #include "time.hfa" |
---|
34 | #include "kernel_private.hfa" |
---|
35 | #include "preemption.hfa" |
---|
36 | #include "startup.hfa" |
---|
37 | |
---|
38 | //Private includes |
---|
39 | #define __CFA_INVOKE_PRIVATE__ |
---|
40 | #include "invoke.h" |
---|
41 | |
---|
42 | //----------------------------------------------------------------------------- |
---|
43 | // Some assembly required |
---|
44 | #if defined( __i386 ) |
---|
45 | #define CtxGet( ctx ) \ |
---|
46 | __asm__ volatile ( \ |
---|
47 | "movl %%esp,%0\n"\ |
---|
48 | "movl %%ebp,%1\n"\ |
---|
49 | : "=rm" (ctx.SP),\ |
---|
50 | "=rm" (ctx.FP) \ |
---|
51 | ) |
---|
52 | |
---|
53 | // mxcr : SSE Status and Control bits (control bits are preserved across function calls) |
---|
54 | // fcw : X87 FPU control word (preserved across function calls) |
---|
55 | #define __x87_store \ |
---|
56 | uint32_t __mxcr; \ |
---|
57 | uint16_t __fcw; \ |
---|
58 | __asm__ volatile ( \ |
---|
59 | "stmxcsr %0\n" \ |
---|
60 | "fnstcw %1\n" \ |
---|
61 | : "=m" (__mxcr),\ |
---|
62 | "=m" (__fcw) \ |
---|
63 | ) |
---|
64 | |
---|
65 | #define __x87_load \ |
---|
66 | __asm__ volatile ( \ |
---|
67 | "fldcw %1\n" \ |
---|
68 | "ldmxcsr %0\n" \ |
---|
69 | ::"m" (__mxcr),\ |
---|
70 | "m" (__fcw) \ |
---|
71 | ) |
---|
72 | |
---|
73 | #elif defined( __x86_64 ) |
---|
74 | #define CtxGet( ctx ) \ |
---|
75 | __asm__ volatile ( \ |
---|
76 | "movq %%rsp,%0\n"\ |
---|
77 | "movq %%rbp,%1\n"\ |
---|
78 | : "=rm" (ctx.SP),\ |
---|
79 | "=rm" (ctx.FP) \ |
---|
80 | ) |
---|
81 | |
---|
82 | #define __x87_store \ |
---|
83 | uint32_t __mxcr; \ |
---|
84 | uint16_t __fcw; \ |
---|
85 | __asm__ volatile ( \ |
---|
86 | "stmxcsr %0\n" \ |
---|
87 | "fnstcw %1\n" \ |
---|
88 | : "=m" (__mxcr),\ |
---|
89 | "=m" (__fcw) \ |
---|
90 | ) |
---|
91 | |
---|
92 | #define __x87_load \ |
---|
93 | __asm__ volatile ( \ |
---|
94 | "fldcw %1\n" \ |
---|
95 | "ldmxcsr %0\n" \ |
---|
96 | :: "m" (__mxcr),\ |
---|
97 | "m" (__fcw) \ |
---|
98 | ) |
---|
99 | |
---|
100 | |
---|
101 | #elif defined( __ARM_ARCH ) |
---|
102 | #define CtxGet( ctx ) __asm__ ( \ |
---|
103 | "mov %0,%%sp\n" \ |
---|
104 | "mov %1,%%r11\n" \ |
---|
105 | : "=rm" (ctx.SP), "=rm" (ctx.FP) ) |
---|
106 | #else |
---|
107 | #error unknown hardware architecture |
---|
108 | #endif |
---|
109 | |
---|
110 | //----------------------------------------------------------------------------- |
---|
111 | //Start and stop routine for the kernel, declared first to make sure they run first |
---|
112 | static void __kernel_startup (void) __attribute__(( constructor( STARTUP_PRIORITY_KERNEL ) )); |
---|
113 | static void __kernel_shutdown(void) __attribute__(( destructor ( STARTUP_PRIORITY_KERNEL ) )); |
---|
114 | |
---|
115 | //----------------------------------------------------------------------------- |
---|
116 | // Kernel storage |
---|
117 | KERNEL_STORAGE(cluster, mainCluster); |
---|
118 | KERNEL_STORAGE(processor, mainProcessor); |
---|
119 | KERNEL_STORAGE($thread, mainThread); |
---|
120 | KERNEL_STORAGE(__stack_t, mainThreadCtx); |
---|
121 | |
---|
122 | cluster * mainCluster; |
---|
123 | processor * mainProcessor; |
---|
124 | $thread * mainThread; |
---|
125 | |
---|
126 | extern "C" { |
---|
127 | struct { __dllist_t(cluster) list; __spinlock_t lock; } __cfa_dbg_global_clusters; |
---|
128 | } |
---|
129 | |
---|
130 | size_t __page_size = 0; |
---|
131 | |
---|
132 | //----------------------------------------------------------------------------- |
---|
133 | // Global state |
---|
134 | thread_local struct KernelThreadData kernelTLS __attribute__ ((tls_model ( "initial-exec" ))) = { |
---|
135 | NULL, // cannot use 0p |
---|
136 | NULL, |
---|
137 | { 1, false, false }, |
---|
138 | 6u //this should be seeded better but due to a bug calling rdtsc doesn't work |
---|
139 | }; |
---|
140 | |
---|
141 | //----------------------------------------------------------------------------- |
---|
142 | // Struct to steal stack |
---|
143 | struct current_stack_info_t { |
---|
144 | __stack_t * storage; // pointer to stack object |
---|
145 | void * base; // base of stack |
---|
146 | void * limit; // stack grows towards stack limit |
---|
147 | void * context; // address of cfa_context_t |
---|
148 | }; |
---|
149 | |
---|
150 | void ?{}( current_stack_info_t & this ) { |
---|
151 | __stack_context_t ctx; |
---|
152 | CtxGet( ctx ); |
---|
153 | this.base = ctx.FP; |
---|
154 | |
---|
155 | rlimit r; |
---|
156 | getrlimit( RLIMIT_STACK, &r); |
---|
157 | size_t size = r.rlim_cur; |
---|
158 | |
---|
159 | this.limit = (void *)(((intptr_t)this.base) - size); |
---|
160 | this.context = &storage_mainThreadCtx; |
---|
161 | } |
---|
162 | |
---|
163 | //----------------------------------------------------------------------------- |
---|
164 | // Main thread construction |
---|
165 | |
---|
166 | void ?{}( $coroutine & this, current_stack_info_t * info) with( this ) { |
---|
167 | stack.storage = info->storage; |
---|
168 | with(*stack.storage) { |
---|
169 | limit = info->limit; |
---|
170 | base = info->base; |
---|
171 | } |
---|
172 | __attribute__((may_alias)) intptr_t * istorage = (intptr_t*) &stack.storage; |
---|
173 | *istorage |= 0x1; |
---|
174 | name = "Main Thread"; |
---|
175 | state = Start; |
---|
176 | starter = 0p; |
---|
177 | last = 0p; |
---|
178 | cancellation = 0p; |
---|
179 | } |
---|
180 | |
---|
181 | void ?{}( $thread & this, current_stack_info_t * info) with( this ) { |
---|
182 | state = Start; |
---|
183 | self_cor{ info }; |
---|
184 | curr_cor = &self_cor; |
---|
185 | curr_cluster = mainCluster; |
---|
186 | self_mon.owner = &this; |
---|
187 | self_mon.recursion = 1; |
---|
188 | self_mon_p = &self_mon; |
---|
189 | next = 0p; |
---|
190 | |
---|
191 | node.next = 0p; |
---|
192 | node.prev = 0p; |
---|
193 | doregister(curr_cluster, this); |
---|
194 | |
---|
195 | monitors{ &self_mon_p, 1, (fptr_t)0 }; |
---|
196 | } |
---|
197 | |
---|
198 | //----------------------------------------------------------------------------- |
---|
199 | // Processor coroutine |
---|
200 | void ?{}(processorCtx_t & this) { |
---|
201 | |
---|
202 | } |
---|
203 | |
---|
204 | // Construct the processor context of non-main processors |
---|
205 | static void ?{}(processorCtx_t & this, processor * proc, current_stack_info_t * info) { |
---|
206 | (this.__cor){ info }; |
---|
207 | this.proc = proc; |
---|
208 | } |
---|
209 | |
---|
210 | static void * __invoke_processor(void * arg); |
---|
211 | |
---|
212 | void ?{}(processor & this, const char name[], cluster & cltr) with( this ) { |
---|
213 | this.name = name; |
---|
214 | this.cltr = &cltr; |
---|
215 | terminated{ 0 }; |
---|
216 | destroyer = 0p; |
---|
217 | do_terminate = false; |
---|
218 | preemption_alarm = 0p; |
---|
219 | pending_preemption = false; |
---|
220 | runner.proc = &this; |
---|
221 | |
---|
222 | idleLock{}; |
---|
223 | |
---|
224 | __cfaabi_dbg_print_safe("Kernel : Starting core %p\n", &this); |
---|
225 | |
---|
226 | this.stack = __create_pthread( &this.kernel_thread, __invoke_processor, (void *)&this ); |
---|
227 | |
---|
228 | __cfaabi_dbg_print_safe("Kernel : core %p started\n", &this); |
---|
229 | } |
---|
230 | |
---|
231 | void ^?{}(processor & this) with( this ){ |
---|
232 | if( ! __atomic_load_n(&do_terminate, __ATOMIC_ACQUIRE) ) { |
---|
233 | __cfaabi_dbg_print_safe("Kernel : core %p signaling termination\n", &this); |
---|
234 | |
---|
235 | __atomic_store_n(&do_terminate, true, __ATOMIC_RELAXED); |
---|
236 | wake( &this ); |
---|
237 | |
---|
238 | P( terminated ); |
---|
239 | verify( kernelTLS.this_processor != &this); |
---|
240 | } |
---|
241 | |
---|
242 | pthread_join( kernel_thread, 0p ); |
---|
243 | free( this.stack ); |
---|
244 | } |
---|
245 | |
---|
246 | void ?{}(cluster & this, const char name[], Duration preemption_rate) with( this ) { |
---|
247 | this.name = name; |
---|
248 | this.preemption_rate = preemption_rate; |
---|
249 | ready_queue{}; |
---|
250 | ready_queue_lock{}; |
---|
251 | |
---|
252 | procs{ __get }; |
---|
253 | idles{ __get }; |
---|
254 | threads{ __get }; |
---|
255 | |
---|
256 | doregister(this); |
---|
257 | } |
---|
258 | |
---|
259 | void ^?{}(cluster & this) { |
---|
260 | unregister(this); |
---|
261 | } |
---|
262 | |
---|
263 | //============================================================================================= |
---|
264 | // Kernel Scheduling logic |
---|
265 | //============================================================================================= |
---|
266 | static $thread * __next_thread(cluster * this); |
---|
267 | static void __run_thread(processor * this, $thread * dst); |
---|
268 | static void __halt(processor * this); |
---|
269 | |
---|
270 | //Main of the processor contexts |
---|
271 | void main(processorCtx_t & runner) { |
---|
272 | // Because of a bug, we couldn't initialized the seed on construction |
---|
273 | // Do it here |
---|
274 | kernelTLS.rand_seed ^= rdtscl(); |
---|
275 | |
---|
276 | processor * this = runner.proc; |
---|
277 | verify(this); |
---|
278 | |
---|
279 | __cfaabi_dbg_print_safe("Kernel : core %p starting\n", this); |
---|
280 | |
---|
281 | doregister(this->cltr, this); |
---|
282 | |
---|
283 | { |
---|
284 | // Setup preemption data |
---|
285 | preemption_scope scope = { this }; |
---|
286 | |
---|
287 | __cfaabi_dbg_print_safe("Kernel : core %p started\n", this); |
---|
288 | |
---|
289 | $thread * readyThread = 0p; |
---|
290 | for( unsigned int spin_count = 0; ! __atomic_load_n(&this->do_terminate, __ATOMIC_SEQ_CST); spin_count++ ) { |
---|
291 | readyThread = __next_thread( this->cltr ); |
---|
292 | |
---|
293 | if(readyThread) { |
---|
294 | /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); |
---|
295 | /* paranoid */ verifyf( readyThread->state == Inactive || readyThread->state == Start || readyThread->preempted != __NO_PREEMPTION, "state : %d, preempted %d\n", readyThread->state, readyThread->preempted); |
---|
296 | /* paranoid */ verifyf( readyThread->next == 0p, "Expected null got %p", readyThread->next ); |
---|
297 | |
---|
298 | __run_thread(this, readyThread); |
---|
299 | |
---|
300 | /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); |
---|
301 | |
---|
302 | spin_count = 0; |
---|
303 | } else { |
---|
304 | // spin(this, &spin_count); |
---|
305 | __halt(this); |
---|
306 | } |
---|
307 | } |
---|
308 | |
---|
309 | __cfaabi_dbg_print_safe("Kernel : core %p stopping\n", this); |
---|
310 | } |
---|
311 | |
---|
312 | unregister(this->cltr, this); |
---|
313 | |
---|
314 | V( this->terminated ); |
---|
315 | |
---|
316 | __cfaabi_dbg_print_safe("Kernel : core %p terminated\n", this); |
---|
317 | } |
---|
318 | |
---|
319 | static int * __volatile_errno() __attribute__((noinline)); |
---|
320 | static int * __volatile_errno() { asm(""); return &errno; } |
---|
321 | |
---|
322 | // KERNEL ONLY |
---|
323 | // runThread runs a thread by context switching |
---|
324 | // from the processor coroutine to the target thread |
---|
325 | static void __run_thread(processor * this, $thread * thrd_dst) { |
---|
326 | $coroutine * proc_cor = get_coroutine(this->runner); |
---|
327 | |
---|
328 | // Update global state |
---|
329 | kernelTLS.this_thread = thrd_dst; |
---|
330 | |
---|
331 | // set state of processor coroutine to inactive |
---|
332 | verify(proc_cor->state == Active); |
---|
333 | proc_cor->state = Inactive; |
---|
334 | |
---|
335 | // Actually run the thread |
---|
336 | RUNNING: while(true) { |
---|
337 | if(unlikely(thrd_dst->preempted)) { |
---|
338 | thrd_dst->preempted = __NO_PREEMPTION; |
---|
339 | verify(thrd_dst->state == Active || thrd_dst->state == Rerun); |
---|
340 | } else { |
---|
341 | verify(thrd_dst->state == Start || thrd_dst->state == Primed || thrd_dst->state == Inactive); |
---|
342 | thrd_dst->state = Active; |
---|
343 | } |
---|
344 | |
---|
345 | /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); |
---|
346 | |
---|
347 | // set context switch to the thread that the processor is executing |
---|
348 | verify( thrd_dst->context.SP ); |
---|
349 | __cfactx_switch( &proc_cor->context, &thrd_dst->context ); |
---|
350 | // when __cfactx_switch returns we are back in the processor coroutine |
---|
351 | |
---|
352 | /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); |
---|
353 | |
---|
354 | |
---|
355 | // We just finished running a thread, there are a few things that could have happened. |
---|
356 | // 1 - Regular case : the thread has blocked and now one has scheduled it yet. |
---|
357 | // 2 - Racy case : the thread has blocked but someone has already tried to schedule it. |
---|
358 | // 3 - Polite Racy case : the thread has blocked, someone has already tried to schedule it, but the thread is nice and wants to go through the ready-queue any way |
---|
359 | // 4 - Preempted |
---|
360 | // In case 1, we may have won a race so we can't write to the state again. |
---|
361 | // In case 2, we lost the race so we now own the thread. |
---|
362 | // In case 3, we lost the race but can just reschedule the thread. |
---|
363 | |
---|
364 | if(unlikely(thrd_dst->preempted != __NO_PREEMPTION)) { |
---|
365 | // The thread was preempted, reschedule it and reset the flag |
---|
366 | __schedule_thread( thrd_dst ); |
---|
367 | break RUNNING; |
---|
368 | } |
---|
369 | |
---|
370 | // set state of processor coroutine to active and the thread to inactive |
---|
371 | static_assert(sizeof(thrd_dst->state) == sizeof(int)); |
---|
372 | enum coroutine_state old_state = __atomic_exchange_n(&thrd_dst->state, Inactive, __ATOMIC_SEQ_CST); |
---|
373 | switch(old_state) { |
---|
374 | case Halted: |
---|
375 | // The thread has halted, it should never be scheduled/run again, leave it back to Halted and move on |
---|
376 | thrd_dst->state = Halted; |
---|
377 | |
---|
378 | // We may need to wake someone up here since |
---|
379 | unpark( this->destroyer ); |
---|
380 | this->destroyer = 0p; |
---|
381 | break RUNNING; |
---|
382 | case Active: |
---|
383 | // This is case 1, the regular case, nothing more is needed |
---|
384 | break RUNNING; |
---|
385 | case Rerun: |
---|
386 | // This is case 2, the racy case, someone tried to run this thread before it finished blocking |
---|
387 | // In this case, just run it again. |
---|
388 | continue RUNNING; |
---|
389 | default: |
---|
390 | // This makes no sense, something is wrong abort |
---|
391 | abort("Finished running a thread that was Inactive/Start/Primed %d\n", old_state); |
---|
392 | } |
---|
393 | } |
---|
394 | |
---|
395 | // Just before returning to the processor, set the processor coroutine to active |
---|
396 | proc_cor->state = Active; |
---|
397 | } |
---|
398 | |
---|
399 | // KERNEL_ONLY |
---|
400 | void returnToKernel() { |
---|
401 | /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); |
---|
402 | $coroutine * proc_cor = get_coroutine(kernelTLS.this_processor->runner); |
---|
403 | $thread * thrd_src = kernelTLS.this_thread; |
---|
404 | |
---|
405 | // Run the thread on this processor |
---|
406 | { |
---|
407 | int local_errno = *__volatile_errno(); |
---|
408 | #if defined( __i386 ) || defined( __x86_64 ) |
---|
409 | __x87_store; |
---|
410 | #endif |
---|
411 | verify( proc_cor->context.SP ); |
---|
412 | __cfactx_switch( &thrd_src->context, &proc_cor->context ); |
---|
413 | #if defined( __i386 ) || defined( __x86_64 ) |
---|
414 | __x87_load; |
---|
415 | #endif |
---|
416 | *__volatile_errno() = local_errno; |
---|
417 | } |
---|
418 | |
---|
419 | /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); |
---|
420 | } |
---|
421 | |
---|
422 | // KERNEL_ONLY |
---|
423 | // Context invoker for processors |
---|
424 | // This is the entry point for processors (kernel threads) |
---|
425 | // It effectively constructs a coroutine by stealing the pthread stack |
---|
426 | static void * __invoke_processor(void * arg) { |
---|
427 | processor * proc = (processor *) arg; |
---|
428 | kernelTLS.this_processor = proc; |
---|
429 | kernelTLS.this_thread = 0p; |
---|
430 | kernelTLS.preemption_state.[enabled, disable_count] = [false, 1]; |
---|
431 | // SKULLDUGGERY: We want to create a context for the processor coroutine |
---|
432 | // which is needed for the 2-step context switch. However, there is no reason |
---|
433 | // to waste the perfectly valid stack create by pthread. |
---|
434 | current_stack_info_t info; |
---|
435 | __stack_t ctx; |
---|
436 | info.storage = &ctx; |
---|
437 | (proc->runner){ proc, &info }; |
---|
438 | |
---|
439 | __cfaabi_dbg_print_safe("Coroutine : created stack %p\n", get_coroutine(proc->runner)->stack.storage); |
---|
440 | |
---|
441 | //Set global state |
---|
442 | kernelTLS.this_thread = 0p; |
---|
443 | |
---|
444 | //We now have a proper context from which to schedule threads |
---|
445 | __cfaabi_dbg_print_safe("Kernel : core %p created (%p, %p)\n", proc, &proc->runner, &ctx); |
---|
446 | |
---|
447 | // SKULLDUGGERY: Since the coroutine doesn't have its own stack, we can't |
---|
448 | // resume it to start it like it normally would, it will just context switch |
---|
449 | // back to here. Instead directly call the main since we already are on the |
---|
450 | // appropriate stack. |
---|
451 | get_coroutine(proc->runner)->state = Active; |
---|
452 | main( proc->runner ); |
---|
453 | get_coroutine(proc->runner)->state = Halted; |
---|
454 | |
---|
455 | // Main routine of the core returned, the core is now fully terminated |
---|
456 | __cfaabi_dbg_print_safe("Kernel : core %p main ended (%p)\n", proc, &proc->runner); |
---|
457 | |
---|
458 | return 0p; |
---|
459 | } |
---|
460 | |
---|
461 | static void Abort( int ret, const char func[] ) { |
---|
462 | if ( ret ) { // pthread routines return errno values |
---|
463 | abort( "%s : internal error, error(%d) %s.", func, ret, strerror( ret ) ); |
---|
464 | } // if |
---|
465 | } // Abort |
---|
466 | |
---|
467 | void * __create_pthread( pthread_t * pthread, void * (*start)(void *), void * arg ) { |
---|
468 | pthread_attr_t attr; |
---|
469 | |
---|
470 | Abort( pthread_attr_init( &attr ), "pthread_attr_init" ); // initialize attribute |
---|
471 | |
---|
472 | size_t stacksize; |
---|
473 | // default stack size, normally defined by shell limit |
---|
474 | Abort( pthread_attr_getstacksize( &attr, &stacksize ), "pthread_attr_getstacksize" ); |
---|
475 | assert( stacksize >= PTHREAD_STACK_MIN ); |
---|
476 | |
---|
477 | void * stack; |
---|
478 | __cfaabi_dbg_debug_do( |
---|
479 | stack = memalign( __page_size, stacksize + __page_size ); |
---|
480 | // pthread has no mechanism to create the guard page in user supplied stack. |
---|
481 | if ( mprotect( stack, __page_size, PROT_NONE ) == -1 ) { |
---|
482 | abort( "mprotect : internal error, mprotect failure, error(%d) %s.", errno, strerror( errno ) ); |
---|
483 | } // if |
---|
484 | ); |
---|
485 | __cfaabi_dbg_no_debug_do( |
---|
486 | stack = malloc( stacksize ); |
---|
487 | ); |
---|
488 | |
---|
489 | Abort( pthread_attr_setstack( &attr, stack, stacksize ), "pthread_attr_setstack" ); |
---|
490 | |
---|
491 | Abort( pthread_create( pthread, &attr, start, arg ), "pthread_create" ); |
---|
492 | return stack; |
---|
493 | } |
---|
494 | |
---|
495 | // KERNEL_ONLY |
---|
496 | static void __kernel_first_resume( processor * this ) { |
---|
497 | $thread * src = mainThread; |
---|
498 | $coroutine * dst = get_coroutine(this->runner); |
---|
499 | |
---|
500 | verify( ! kernelTLS.preemption_state.enabled ); |
---|
501 | |
---|
502 | kernelTLS.this_thread->curr_cor = dst; |
---|
503 | __stack_prepare( &dst->stack, 65000 ); |
---|
504 | __cfactx_start(main, dst, this->runner, __cfactx_invoke_coroutine); |
---|
505 | |
---|
506 | verify( ! kernelTLS.preemption_state.enabled ); |
---|
507 | |
---|
508 | dst->last = &src->self_cor; |
---|
509 | dst->starter = dst->starter ? dst->starter : &src->self_cor; |
---|
510 | |
---|
511 | // set state of current coroutine to inactive |
---|
512 | src->state = src->state == Halted ? Halted : Inactive; |
---|
513 | |
---|
514 | // context switch to specified coroutine |
---|
515 | verify( dst->context.SP ); |
---|
516 | __cfactx_switch( &src->context, &dst->context ); |
---|
517 | // when __cfactx_switch returns we are back in the src coroutine |
---|
518 | |
---|
519 | mainThread->curr_cor = &mainThread->self_cor; |
---|
520 | |
---|
521 | // set state of new coroutine to active |
---|
522 | src->state = Active; |
---|
523 | |
---|
524 | verify( ! kernelTLS.preemption_state.enabled ); |
---|
525 | } |
---|
526 | |
---|
527 | // KERNEL_ONLY |
---|
528 | static void __kernel_last_resume( processor * this ) { |
---|
529 | $coroutine * src = &mainThread->self_cor; |
---|
530 | $coroutine * dst = get_coroutine(this->runner); |
---|
531 | |
---|
532 | verify( ! kernelTLS.preemption_state.enabled ); |
---|
533 | verify( dst->starter == src ); |
---|
534 | verify( dst->context.SP ); |
---|
535 | |
---|
536 | // context switch to the processor |
---|
537 | __cfactx_switch( &src->context, &dst->context ); |
---|
538 | } |
---|
539 | |
---|
540 | //----------------------------------------------------------------------------- |
---|
541 | // Scheduler routines |
---|
542 | // KERNEL ONLY |
---|
543 | void __schedule_thread( $thread * thrd ) with( *thrd->curr_cluster ) { |
---|
544 | /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); |
---|
545 | /* paranoid */ #if defined( __CFA_WITH_VERIFY__ ) |
---|
546 | /* paranoid */ if( thrd->state == Inactive || thrd->state == Start ) assertf( thrd->preempted == __NO_PREEMPTION, |
---|
547 | "Error inactive thread marked as preempted, state %d, preemption %d\n", thrd->state, thrd->preempted ); |
---|
548 | /* paranoid */ if( thrd->preempted != __NO_PREEMPTION ) assertf(thrd->state == Active || thrd->state == Rerun, |
---|
549 | "Error preempted thread marked as not currently running, state %d, preemption %d\n", thrd->state, thrd->preempted ); |
---|
550 | /* paranoid */ #endif |
---|
551 | /* paranoid */ verifyf( thrd->next == 0p, "Expected null got %p", thrd->next ); |
---|
552 | |
---|
553 | lock ( ready_queue_lock __cfaabi_dbg_ctx2 ); |
---|
554 | bool was_empty = !(ready_queue != 0); |
---|
555 | append( ready_queue, thrd ); |
---|
556 | unlock( ready_queue_lock ); |
---|
557 | |
---|
558 | if(was_empty) { |
---|
559 | lock (proc_list_lock __cfaabi_dbg_ctx2); |
---|
560 | if(idles) { |
---|
561 | wake_fast(idles.head); |
---|
562 | } |
---|
563 | unlock (proc_list_lock); |
---|
564 | } |
---|
565 | else if( struct processor * idle = idles.head ) { |
---|
566 | wake_fast(idle); |
---|
567 | } |
---|
568 | |
---|
569 | /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); |
---|
570 | } |
---|
571 | |
---|
572 | // KERNEL ONLY |
---|
573 | static $thread * __next_thread(cluster * this) with( *this ) { |
---|
574 | /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); |
---|
575 | |
---|
576 | lock( ready_queue_lock __cfaabi_dbg_ctx2 ); |
---|
577 | $thread * head = pop_head( ready_queue ); |
---|
578 | unlock( ready_queue_lock ); |
---|
579 | |
---|
580 | /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); |
---|
581 | return head; |
---|
582 | } |
---|
583 | |
---|
584 | void unpark( $thread * thrd ) { |
---|
585 | if( !thrd ) return; |
---|
586 | |
---|
587 | disable_interrupts(); |
---|
588 | static_assert(sizeof(thrd->state) == sizeof(int)); |
---|
589 | enum coroutine_state old_state = __atomic_exchange_n(&thrd->state, Rerun, __ATOMIC_SEQ_CST); |
---|
590 | switch(old_state) { |
---|
591 | case Active: |
---|
592 | // Wake won the race, the thread will reschedule/rerun itself |
---|
593 | break; |
---|
594 | case Inactive: |
---|
595 | /* paranoid */ verify( ! thrd->preempted != __NO_PREEMPTION ); |
---|
596 | |
---|
597 | // Wake lost the race, |
---|
598 | thrd->state = Inactive; |
---|
599 | __schedule_thread( thrd ); |
---|
600 | break; |
---|
601 | case Rerun: |
---|
602 | abort("More than one thread attempted to schedule thread %p\n", thrd); |
---|
603 | break; |
---|
604 | case Halted: |
---|
605 | case Start: |
---|
606 | case Primed: |
---|
607 | default: |
---|
608 | // This makes no sense, something is wrong abort |
---|
609 | abort(); |
---|
610 | } |
---|
611 | enable_interrupts( __cfaabi_dbg_ctx ); |
---|
612 | } |
---|
613 | |
---|
614 | void park( void ) { |
---|
615 | /* paranoid */ verify( kernelTLS.preemption_state.enabled ); |
---|
616 | disable_interrupts(); |
---|
617 | /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); |
---|
618 | /* paranoid */ verify( kernelTLS.this_thread->preempted == __NO_PREEMPTION ); |
---|
619 | |
---|
620 | returnToKernel(); |
---|
621 | |
---|
622 | /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); |
---|
623 | enable_interrupts( __cfaabi_dbg_ctx ); |
---|
624 | /* paranoid */ verify( kernelTLS.preemption_state.enabled ); |
---|
625 | |
---|
626 | } |
---|
627 | |
---|
628 | // KERNEL ONLY |
---|
629 | void __leave_thread() { |
---|
630 | /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); |
---|
631 | returnToKernel(); |
---|
632 | abort(); |
---|
633 | } |
---|
634 | |
---|
635 | // KERNEL ONLY |
---|
636 | bool force_yield( __Preemption_Reason reason ) { |
---|
637 | /* paranoid */ verify( kernelTLS.preemption_state.enabled ); |
---|
638 | disable_interrupts(); |
---|
639 | /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); |
---|
640 | |
---|
641 | $thread * thrd = kernelTLS.this_thread; |
---|
642 | /* paranoid */ verify(thrd->state == Active || thrd->state == Rerun); |
---|
643 | |
---|
644 | // SKULLDUGGERY: It is possible that we are preempting this thread just before |
---|
645 | // it was going to park itself. If that is the case and it is already using the |
---|
646 | // intrusive fields then we can't use them to preempt the thread |
---|
647 | // If that is the case, abandon the preemption. |
---|
648 | bool preempted = false; |
---|
649 | if(thrd->next == 0p) { |
---|
650 | preempted = true; |
---|
651 | thrd->preempted = reason; |
---|
652 | returnToKernel(); |
---|
653 | } |
---|
654 | |
---|
655 | /* paranoid */ verify( ! kernelTLS.preemption_state.enabled ); |
---|
656 | enable_interrupts_noPoll(); |
---|
657 | /* paranoid */ verify( kernelTLS.preemption_state.enabled ); |
---|
658 | |
---|
659 | return preempted; |
---|
660 | } |
---|
661 | |
---|
662 | //============================================================================================= |
---|
663 | // Kernel Setup logic |
---|
664 | //============================================================================================= |
---|
665 | //----------------------------------------------------------------------------- |
---|
666 | // Kernel boot procedures |
---|
667 | static void __kernel_startup(void) { |
---|
668 | verify( ! kernelTLS.preemption_state.enabled ); |
---|
669 | __cfaabi_dbg_print_safe("Kernel : Starting\n"); |
---|
670 | |
---|
671 | __page_size = sysconf( _SC_PAGESIZE ); |
---|
672 | |
---|
673 | __cfa_dbg_global_clusters.list{ __get }; |
---|
674 | __cfa_dbg_global_clusters.lock{}; |
---|
675 | |
---|
676 | // Initialize the main cluster |
---|
677 | mainCluster = (cluster *)&storage_mainCluster; |
---|
678 | (*mainCluster){"Main Cluster"}; |
---|
679 | |
---|
680 | __cfaabi_dbg_print_safe("Kernel : Main cluster ready\n"); |
---|
681 | |
---|
682 | // Start by initializing the main thread |
---|
683 | // SKULLDUGGERY: the mainThread steals the process main thread |
---|
684 | // which will then be scheduled by the mainProcessor normally |
---|
685 | mainThread = ($thread *)&storage_mainThread; |
---|
686 | current_stack_info_t info; |
---|
687 | info.storage = (__stack_t*)&storage_mainThreadCtx; |
---|
688 | (*mainThread){ &info }; |
---|
689 | |
---|
690 | __cfaabi_dbg_print_safe("Kernel : Main thread ready\n"); |
---|
691 | |
---|
692 | |
---|
693 | |
---|
694 | // Construct the processor context of the main processor |
---|
695 | void ?{}(processorCtx_t & this, processor * proc) { |
---|
696 | (this.__cor){ "Processor" }; |
---|
697 | this.__cor.starter = 0p; |
---|
698 | this.proc = proc; |
---|
699 | } |
---|
700 | |
---|
701 | void ?{}(processor & this) with( this ) { |
---|
702 | name = "Main Processor"; |
---|
703 | cltr = mainCluster; |
---|
704 | terminated{ 0 }; |
---|
705 | do_terminate = false; |
---|
706 | preemption_alarm = 0p; |
---|
707 | pending_preemption = false; |
---|
708 | kernel_thread = pthread_self(); |
---|
709 | |
---|
710 | runner{ &this }; |
---|
711 | __cfaabi_dbg_print_safe("Kernel : constructed main processor context %p\n", &runner); |
---|
712 | } |
---|
713 | |
---|
714 | // Initialize the main processor and the main processor ctx |
---|
715 | // (the coroutine that contains the processing control flow) |
---|
716 | mainProcessor = (processor *)&storage_mainProcessor; |
---|
717 | (*mainProcessor){}; |
---|
718 | |
---|
719 | //initialize the global state variables |
---|
720 | kernelTLS.this_processor = mainProcessor; |
---|
721 | kernelTLS.this_thread = mainThread; |
---|
722 | |
---|
723 | // Enable preemption |
---|
724 | kernel_start_preemption(); |
---|
725 | |
---|
726 | // Add the main thread to the ready queue |
---|
727 | // once resume is called on mainProcessor->runner the mainThread needs to be scheduled like any normal thread |
---|
728 | __schedule_thread(mainThread); |
---|
729 | |
---|
730 | // SKULLDUGGERY: Force a context switch to the main processor to set the main thread's context to the current UNIX |
---|
731 | // context. Hence, the main thread does not begin through __cfactx_invoke_thread, like all other threads. The trick here is that |
---|
732 | // mainThread is on the ready queue when this call is made. |
---|
733 | __kernel_first_resume( kernelTLS.this_processor ); |
---|
734 | |
---|
735 | |
---|
736 | |
---|
737 | // THE SYSTEM IS NOW COMPLETELY RUNNING |
---|
738 | __cfaabi_dbg_print_safe("Kernel : Started\n--------------------------------------------------\n\n"); |
---|
739 | |
---|
740 | verify( ! kernelTLS.preemption_state.enabled ); |
---|
741 | enable_interrupts( __cfaabi_dbg_ctx ); |
---|
742 | verify( TL_GET( preemption_state.enabled ) ); |
---|
743 | } |
---|
744 | |
---|
745 | static void __kernel_shutdown(void) { |
---|
746 | __cfaabi_dbg_print_safe("\n--------------------------------------------------\nKernel : Shutting down\n"); |
---|
747 | |
---|
748 | verify( TL_GET( preemption_state.enabled ) ); |
---|
749 | disable_interrupts(); |
---|
750 | verify( ! kernelTLS.preemption_state.enabled ); |
---|
751 | |
---|
752 | // SKULLDUGGERY: Notify the mainProcessor it needs to terminates. |
---|
753 | // When its coroutine terminates, it return control to the mainThread |
---|
754 | // which is currently here |
---|
755 | __atomic_store_n(&mainProcessor->do_terminate, true, __ATOMIC_RELEASE); |
---|
756 | __kernel_last_resume( kernelTLS.this_processor ); |
---|
757 | mainThread->self_cor.state = Halted; |
---|
758 | |
---|
759 | // THE SYSTEM IS NOW COMPLETELY STOPPED |
---|
760 | |
---|
761 | // Disable preemption |
---|
762 | kernel_stop_preemption(); |
---|
763 | |
---|
764 | // Destroy the main processor and its context in reverse order of construction |
---|
765 | // These were manually constructed so we need manually destroy them |
---|
766 | ^(mainProcessor->runner){}; |
---|
767 | ^(mainProcessor){}; |
---|
768 | |
---|
769 | // Final step, destroy the main thread since it is no longer needed |
---|
770 | // Since we provided a stack to this taxk it will not destroy anything |
---|
771 | ^(mainThread){}; |
---|
772 | |
---|
773 | ^(__cfa_dbg_global_clusters.list){}; |
---|
774 | ^(__cfa_dbg_global_clusters.lock){}; |
---|
775 | |
---|
776 | __cfaabi_dbg_print_safe("Kernel : Shutdown complete\n"); |
---|
777 | } |
---|
778 | |
---|
779 | //============================================================================================= |
---|
780 | // Kernel Quiescing |
---|
781 | //============================================================================================= |
---|
782 | static void __halt(processor * this) with( *this ) { |
---|
783 | // verify( ! __atomic_load_n(&do_terminate, __ATOMIC_SEQ_CST) ); |
---|
784 | |
---|
785 | with( *cltr ) { |
---|
786 | lock (proc_list_lock __cfaabi_dbg_ctx2); |
---|
787 | remove (procs, *this); |
---|
788 | push_front(idles, *this); |
---|
789 | unlock (proc_list_lock); |
---|
790 | } |
---|
791 | |
---|
792 | __cfaabi_dbg_print_safe("Kernel : Processor %p ready to sleep\n", this); |
---|
793 | |
---|
794 | wait( idleLock ); |
---|
795 | |
---|
796 | __cfaabi_dbg_print_safe("Kernel : Processor %p woke up and ready to run\n", this); |
---|
797 | |
---|
798 | with( *cltr ) { |
---|
799 | lock (proc_list_lock __cfaabi_dbg_ctx2); |
---|
800 | remove (idles, *this); |
---|
801 | push_front(procs, *this); |
---|
802 | unlock (proc_list_lock); |
---|
803 | } |
---|
804 | } |
---|
805 | |
---|
806 | //============================================================================================= |
---|
807 | // Unexpected Terminating logic |
---|
808 | //============================================================================================= |
---|
809 | static __spinlock_t kernel_abort_lock; |
---|
810 | static bool kernel_abort_called = false; |
---|
811 | |
---|
812 | void * kernel_abort(void) __attribute__ ((__nothrow__)) { |
---|
813 | // abort cannot be recursively entered by the same or different processors because all signal handlers return when |
---|
814 | // the globalAbort flag is true. |
---|
815 | lock( kernel_abort_lock __cfaabi_dbg_ctx2 ); |
---|
816 | |
---|
817 | // first task to abort ? |
---|
818 | if ( kernel_abort_called ) { // not first task to abort ? |
---|
819 | unlock( kernel_abort_lock ); |
---|
820 | |
---|
821 | sigset_t mask; |
---|
822 | sigemptyset( &mask ); |
---|
823 | sigaddset( &mask, SIGALRM ); // block SIGALRM signals |
---|
824 | sigaddset( &mask, SIGUSR1 ); // block SIGALRM signals |
---|
825 | sigsuspend( &mask ); // block the processor to prevent further damage during abort |
---|
826 | _exit( EXIT_FAILURE ); // if processor unblocks before it is killed, terminate it |
---|
827 | } |
---|
828 | else { |
---|
829 | kernel_abort_called = true; |
---|
830 | unlock( kernel_abort_lock ); |
---|
831 | } |
---|
832 | |
---|
833 | return kernelTLS.this_thread; |
---|
834 | } |
---|
835 | |
---|
836 | void kernel_abort_msg( void * kernel_data, char * abort_text, int abort_text_size ) { |
---|
837 | $thread * thrd = kernel_data; |
---|
838 | |
---|
839 | if(thrd) { |
---|
840 | int len = snprintf( abort_text, abort_text_size, "Error occurred while executing thread %.256s (%p)", thrd->self_cor.name, thrd ); |
---|
841 | __cfaabi_bits_write( STDERR_FILENO, abort_text, len ); |
---|
842 | |
---|
843 | if ( &thrd->self_cor != thrd->curr_cor ) { |
---|
844 | len = snprintf( abort_text, abort_text_size, " in coroutine %.256s (%p).\n", thrd->curr_cor->name, thrd->curr_cor ); |
---|
845 | __cfaabi_bits_write( STDERR_FILENO, abort_text, len ); |
---|
846 | } |
---|
847 | else { |
---|
848 | __cfaabi_bits_write( STDERR_FILENO, ".\n", 2 ); |
---|
849 | } |
---|
850 | } |
---|
851 | else { |
---|
852 | int len = snprintf( abort_text, abort_text_size, "Error occurred outside of any thread.\n" ); |
---|
853 | __cfaabi_bits_write( STDERR_FILENO, abort_text, len ); |
---|
854 | } |
---|
855 | } |
---|
856 | |
---|
857 | int kernel_abort_lastframe( void ) __attribute__ ((__nothrow__)) { |
---|
858 | return get_coroutine(kernelTLS.this_thread) == get_coroutine(mainThread) ? 4 : 2; |
---|
859 | } |
---|
860 | |
---|
861 | static __spinlock_t kernel_debug_lock; |
---|
862 | |
---|
863 | extern "C" { |
---|
864 | void __cfaabi_bits_acquire() { |
---|
865 | lock( kernel_debug_lock __cfaabi_dbg_ctx2 ); |
---|
866 | } |
---|
867 | |
---|
868 | void __cfaabi_bits_release() { |
---|
869 | unlock( kernel_debug_lock ); |
---|
870 | } |
---|
871 | } |
---|
872 | |
---|
873 | //============================================================================================= |
---|
874 | // Kernel Utilities |
---|
875 | //============================================================================================= |
---|
876 | //----------------------------------------------------------------------------- |
---|
877 | // Locks |
---|
878 | void ?{}( semaphore & this, int count = 1 ) { |
---|
879 | (this.lock){}; |
---|
880 | this.count = count; |
---|
881 | (this.waiting){}; |
---|
882 | } |
---|
883 | void ^?{}(semaphore & this) {} |
---|
884 | |
---|
885 | void P(semaphore & this) with( this ){ |
---|
886 | lock( lock __cfaabi_dbg_ctx2 ); |
---|
887 | count -= 1; |
---|
888 | if ( count < 0 ) { |
---|
889 | // queue current task |
---|
890 | append( waiting, kernelTLS.this_thread ); |
---|
891 | |
---|
892 | // atomically release spin lock and block |
---|
893 | unlock( lock ); |
---|
894 | park(); |
---|
895 | } |
---|
896 | else { |
---|
897 | unlock( lock ); |
---|
898 | } |
---|
899 | } |
---|
900 | |
---|
901 | void V(semaphore & this) with( this ) { |
---|
902 | $thread * thrd = 0p; |
---|
903 | lock( lock __cfaabi_dbg_ctx2 ); |
---|
904 | count += 1; |
---|
905 | if ( count <= 0 ) { |
---|
906 | // remove task at head of waiting list |
---|
907 | thrd = pop_head( waiting ); |
---|
908 | } |
---|
909 | |
---|
910 | unlock( lock ); |
---|
911 | |
---|
912 | // make new owner |
---|
913 | unpark( thrd ); |
---|
914 | } |
---|
915 | |
---|
916 | //----------------------------------------------------------------------------- |
---|
917 | // Global Queues |
---|
918 | void doregister( cluster & cltr ) { |
---|
919 | lock ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2); |
---|
920 | push_front( __cfa_dbg_global_clusters.list, cltr ); |
---|
921 | unlock ( __cfa_dbg_global_clusters.lock ); |
---|
922 | } |
---|
923 | |
---|
924 | void unregister( cluster & cltr ) { |
---|
925 | lock ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2); |
---|
926 | remove( __cfa_dbg_global_clusters.list, cltr ); |
---|
927 | unlock( __cfa_dbg_global_clusters.lock ); |
---|
928 | } |
---|
929 | |
---|
930 | void doregister( cluster * cltr, $thread & thrd ) { |
---|
931 | lock (cltr->thread_list_lock __cfaabi_dbg_ctx2); |
---|
932 | cltr->nthreads += 1; |
---|
933 | push_front(cltr->threads, thrd); |
---|
934 | unlock (cltr->thread_list_lock); |
---|
935 | } |
---|
936 | |
---|
937 | void unregister( cluster * cltr, $thread & thrd ) { |
---|
938 | lock (cltr->thread_list_lock __cfaabi_dbg_ctx2); |
---|
939 | remove(cltr->threads, thrd ); |
---|
940 | cltr->nthreads -= 1; |
---|
941 | unlock(cltr->thread_list_lock); |
---|
942 | } |
---|
943 | |
---|
944 | void doregister( cluster * cltr, processor * proc ) { |
---|
945 | lock (cltr->proc_list_lock __cfaabi_dbg_ctx2); |
---|
946 | cltr->nprocessors += 1; |
---|
947 | push_front(cltr->procs, *proc); |
---|
948 | unlock (cltr->proc_list_lock); |
---|
949 | } |
---|
950 | |
---|
951 | void unregister( cluster * cltr, processor * proc ) { |
---|
952 | lock (cltr->proc_list_lock __cfaabi_dbg_ctx2); |
---|
953 | remove(cltr->procs, *proc ); |
---|
954 | cltr->nprocessors -= 1; |
---|
955 | unlock(cltr->proc_list_lock); |
---|
956 | } |
---|
957 | |
---|
958 | //----------------------------------------------------------------------------- |
---|
959 | // Debug |
---|
960 | __cfaabi_dbg_debug_do( |
---|
961 | extern "C" { |
---|
962 | void __cfaabi_dbg_record(__spinlock_t & this, const char prev_name[]) { |
---|
963 | this.prev_name = prev_name; |
---|
964 | this.prev_thrd = kernelTLS.this_thread; |
---|
965 | } |
---|
966 | } |
---|
967 | ) |
---|
968 | |
---|
969 | //----------------------------------------------------------------------------- |
---|
970 | // Debug |
---|
971 | bool threading_enabled(void) __attribute__((const)) { |
---|
972 | return true; |
---|
973 | } |
---|
974 | // Local Variables: // |
---|
975 | // mode: c // |
---|
976 | // tab-width: 4 // |
---|
977 | // End: // |
---|