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 Dec 3 21:46:54 2019
|
---|
13 | // Update Count : 49
|
---|
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_desc, mainThread);
|
---|
120 | KERNEL_STORAGE(__stack_t, mainThreadCtx);
|
---|
121 |
|
---|
122 | cluster * mainCluster;
|
---|
123 | processor * mainProcessor;
|
---|
124 | thread_desc * 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 | { NULL, 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_desc & 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_desc & 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 start(processor * this);
|
---|
211 | void ?{}(processor & this, const char * name, cluster & cltr) with( this ) {
|
---|
212 | this.name = name;
|
---|
213 | this.cltr = &cltr;
|
---|
214 | terminated{ 0 };
|
---|
215 | do_terminate = false;
|
---|
216 | preemption_alarm = 0p;
|
---|
217 | pending_preemption = false;
|
---|
218 | runner.proc = &this;
|
---|
219 |
|
---|
220 | idleLock{};
|
---|
221 |
|
---|
222 | start( &this );
|
---|
223 | }
|
---|
224 |
|
---|
225 | void ^?{}(processor & this) with( this ){
|
---|
226 | if( ! __atomic_load_n(&do_terminate, __ATOMIC_ACQUIRE) ) {
|
---|
227 | __cfaabi_dbg_print_safe("Kernel : core %p signaling termination\n", &this);
|
---|
228 |
|
---|
229 | __atomic_store_n(&do_terminate, true, __ATOMIC_RELAXED);
|
---|
230 | wake( &this );
|
---|
231 |
|
---|
232 | P( terminated );
|
---|
233 | verify( kernelTLS.this_processor != &this);
|
---|
234 | }
|
---|
235 |
|
---|
236 | pthread_join( kernel_thread, 0p );
|
---|
237 | free( this.stack );
|
---|
238 | }
|
---|
239 |
|
---|
240 | void ?{}(cluster & this, const char * name, Duration preemption_rate) with( this ) {
|
---|
241 | this.name = name;
|
---|
242 | this.preemption_rate = preemption_rate;
|
---|
243 | ready_queue{};
|
---|
244 | ready_queue_lock{};
|
---|
245 |
|
---|
246 | procs{ __get };
|
---|
247 | idles{ __get };
|
---|
248 | threads{ __get };
|
---|
249 |
|
---|
250 | doregister(this);
|
---|
251 | }
|
---|
252 |
|
---|
253 | void ^?{}(cluster & this) {
|
---|
254 | unregister(this);
|
---|
255 | }
|
---|
256 |
|
---|
257 | //=============================================================================================
|
---|
258 | // Kernel Scheduling logic
|
---|
259 | //=============================================================================================
|
---|
260 | static void runThread(processor * this, thread_desc * dst);
|
---|
261 | static void finishRunning(processor * this);
|
---|
262 | static void halt(processor * this);
|
---|
263 |
|
---|
264 | //Main of the processor contexts
|
---|
265 | void main(processorCtx_t & runner) {
|
---|
266 | // Because of a bug, we couldn't initialized the seed on construction
|
---|
267 | // Do it here
|
---|
268 | kernelTLS.rand_seed ^= rdtscl();
|
---|
269 |
|
---|
270 | processor * this = runner.proc;
|
---|
271 | verify(this);
|
---|
272 |
|
---|
273 | __cfaabi_dbg_print_safe("Kernel : core %p starting\n", this);
|
---|
274 |
|
---|
275 | doregister(this->cltr, this);
|
---|
276 |
|
---|
277 | {
|
---|
278 | // Setup preemption data
|
---|
279 | preemption_scope scope = { this };
|
---|
280 |
|
---|
281 | __cfaabi_dbg_print_safe("Kernel : core %p started\n", this);
|
---|
282 |
|
---|
283 | thread_desc * readyThread = 0p;
|
---|
284 | for( unsigned int spin_count = 0; ! __atomic_load_n(&this->do_terminate, __ATOMIC_SEQ_CST); spin_count++ ) {
|
---|
285 | readyThread = nextThread( this->cltr );
|
---|
286 |
|
---|
287 | if(readyThread) {
|
---|
288 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
289 |
|
---|
290 | runThread(this, readyThread);
|
---|
291 |
|
---|
292 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
293 |
|
---|
294 | //Some actions need to be taken from the kernel
|
---|
295 | finishRunning(this);
|
---|
296 |
|
---|
297 | spin_count = 0;
|
---|
298 | } else {
|
---|
299 | // spin(this, &spin_count);
|
---|
300 | halt(this);
|
---|
301 | }
|
---|
302 | }
|
---|
303 |
|
---|
304 | __cfaabi_dbg_print_safe("Kernel : core %p stopping\n", this);
|
---|
305 | }
|
---|
306 |
|
---|
307 | unregister(this->cltr, this);
|
---|
308 |
|
---|
309 | V( this->terminated );
|
---|
310 |
|
---|
311 | __cfaabi_dbg_print_safe("Kernel : core %p terminated\n", this);
|
---|
312 | }
|
---|
313 |
|
---|
314 | static int * __volatile_errno() __attribute__((noinline));
|
---|
315 | static int * __volatile_errno() { asm(""); return &errno; }
|
---|
316 |
|
---|
317 | // KERNEL ONLY
|
---|
318 | // runThread runs a thread by context switching
|
---|
319 | // from the processor coroutine to the target thread
|
---|
320 | static void runThread(processor * this, thread_desc * thrd_dst) {
|
---|
321 | coroutine_desc * proc_cor = get_coroutine(this->runner);
|
---|
322 |
|
---|
323 | // Reset the terminating actions here
|
---|
324 | this->finish.action_code = No_Action;
|
---|
325 |
|
---|
326 | // Update global state
|
---|
327 | kernelTLS.this_thread = thrd_dst;
|
---|
328 |
|
---|
329 | // set state of processor coroutine to inactive and the thread to active
|
---|
330 | proc_cor->state = proc_cor->state == Halted ? Halted : Inactive;
|
---|
331 | thrd_dst->state = Active;
|
---|
332 |
|
---|
333 | // set context switch to the thread that the processor is executing
|
---|
334 | verify( thrd_dst->context.SP );
|
---|
335 | CtxSwitch( &proc_cor->context, &thrd_dst->context );
|
---|
336 | // when CtxSwitch returns we are back in the processor coroutine
|
---|
337 |
|
---|
338 | // set state of processor coroutine to active and the thread to inactive
|
---|
339 | thrd_dst->state = thrd_dst->state == Halted ? Halted : Inactive;
|
---|
340 | proc_cor->state = Active;
|
---|
341 | }
|
---|
342 |
|
---|
343 | // KERNEL_ONLY
|
---|
344 | static void returnToKernel() {
|
---|
345 | coroutine_desc * proc_cor = get_coroutine(kernelTLS.this_processor->runner);
|
---|
346 | thread_desc * thrd_src = kernelTLS.this_thread;
|
---|
347 |
|
---|
348 | // set state of current coroutine to inactive
|
---|
349 | thrd_src->state = thrd_src->state == Halted ? Halted : Inactive;
|
---|
350 | proc_cor->state = Active;
|
---|
351 | int local_errno = *__volatile_errno();
|
---|
352 | #if defined( __i386 ) || defined( __x86_64 )
|
---|
353 | __x87_store;
|
---|
354 | #endif
|
---|
355 |
|
---|
356 | // set new coroutine that the processor is executing
|
---|
357 | // and context switch to it
|
---|
358 | verify( proc_cor->context.SP );
|
---|
359 | CtxSwitch( &thrd_src->context, &proc_cor->context );
|
---|
360 |
|
---|
361 | // set state of new coroutine to active
|
---|
362 | proc_cor->state = proc_cor->state == Halted ? Halted : Inactive;
|
---|
363 | thrd_src->state = Active;
|
---|
364 |
|
---|
365 | #if defined( __i386 ) || defined( __x86_64 )
|
---|
366 | __x87_load;
|
---|
367 | #endif
|
---|
368 | *__volatile_errno() = local_errno;
|
---|
369 | }
|
---|
370 |
|
---|
371 | // KERNEL_ONLY
|
---|
372 | // Once a thread has finished running, some of
|
---|
373 | // its final actions must be executed from the kernel
|
---|
374 | static void finishRunning(processor * this) with( this->finish ) {
|
---|
375 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
376 | choose( action_code ) {
|
---|
377 | case No_Action:
|
---|
378 | break;
|
---|
379 | case Release:
|
---|
380 | unlock( *lock );
|
---|
381 | case Schedule:
|
---|
382 | ScheduleThread( thrd );
|
---|
383 | case Release_Schedule:
|
---|
384 | unlock( *lock );
|
---|
385 | ScheduleThread( thrd );
|
---|
386 | case Release_Multi:
|
---|
387 | for(int i = 0; i < lock_count; i++) {
|
---|
388 | unlock( *locks[i] );
|
---|
389 | }
|
---|
390 | case Release_Multi_Schedule:
|
---|
391 | for(int i = 0; i < lock_count; i++) {
|
---|
392 | unlock( *locks[i] );
|
---|
393 | }
|
---|
394 | for(int i = 0; i < thrd_count; i++) {
|
---|
395 | ScheduleThread( thrds[i] );
|
---|
396 | }
|
---|
397 | case Callback:
|
---|
398 | callback();
|
---|
399 | default:
|
---|
400 | abort("KERNEL ERROR: Unexpected action to run after thread");
|
---|
401 | }
|
---|
402 | }
|
---|
403 |
|
---|
404 | // KERNEL_ONLY
|
---|
405 | // Context invoker for processors
|
---|
406 | // This is the entry point for processors (kernel threads)
|
---|
407 | // It effectively constructs a coroutine by stealing the pthread stack
|
---|
408 | static void * CtxInvokeProcessor(void * arg) {
|
---|
409 | processor * proc = (processor *) arg;
|
---|
410 | kernelTLS.this_processor = proc;
|
---|
411 | kernelTLS.this_thread = 0p;
|
---|
412 | kernelTLS.preemption_state.[enabled, disable_count] = [false, 1];
|
---|
413 | // SKULLDUGGERY: We want to create a context for the processor coroutine
|
---|
414 | // which is needed for the 2-step context switch. However, there is no reason
|
---|
415 | // to waste the perfectly valid stack create by pthread.
|
---|
416 | current_stack_info_t info;
|
---|
417 | __stack_t ctx;
|
---|
418 | info.storage = &ctx;
|
---|
419 | (proc->runner){ proc, &info };
|
---|
420 |
|
---|
421 | __cfaabi_dbg_print_safe("Coroutine : created stack %p\n", get_coroutine(proc->runner)->stack.storage);
|
---|
422 |
|
---|
423 | //Set global state
|
---|
424 | kernelTLS.this_thread = 0p;
|
---|
425 |
|
---|
426 | //We now have a proper context from which to schedule threads
|
---|
427 | __cfaabi_dbg_print_safe("Kernel : core %p created (%p, %p)\n", proc, &proc->runner, &ctx);
|
---|
428 |
|
---|
429 | // SKULLDUGGERY: Since the coroutine doesn't have its own stack, we can't
|
---|
430 | // resume it to start it like it normally would, it will just context switch
|
---|
431 | // back to here. Instead directly call the main since we already are on the
|
---|
432 | // appropriate stack.
|
---|
433 | get_coroutine(proc->runner)->state = Active;
|
---|
434 | main( proc->runner );
|
---|
435 | get_coroutine(proc->runner)->state = Halted;
|
---|
436 |
|
---|
437 | // Main routine of the core returned, the core is now fully terminated
|
---|
438 | __cfaabi_dbg_print_safe("Kernel : core %p main ended (%p)\n", proc, &proc->runner);
|
---|
439 |
|
---|
440 | return 0p;
|
---|
441 | }
|
---|
442 |
|
---|
443 | static void Abort( int ret, const char * func ) {
|
---|
444 | if ( ret ) { // pthread routines return errno values
|
---|
445 | abort( "%s : internal error, error(%d) %s.", func, ret, strerror( ret ) );
|
---|
446 | } // if
|
---|
447 | } // Abort
|
---|
448 |
|
---|
449 | void * create_pthread( pthread_t * pthread, void * (*start)(void *), void * arg ) {
|
---|
450 | pthread_attr_t attr;
|
---|
451 |
|
---|
452 | Abort( pthread_attr_init( &attr ), "pthread_attr_init" ); // initialize attribute
|
---|
453 |
|
---|
454 | size_t stacksize;
|
---|
455 | // default stack size, normally defined by shell limit
|
---|
456 | Abort( pthread_attr_getstacksize( &attr, &stacksize ), "pthread_attr_getstacksize" );
|
---|
457 | assert( stacksize >= PTHREAD_STACK_MIN );
|
---|
458 |
|
---|
459 | #ifdef __CFA_DEBUG__
|
---|
460 | void * stack = memalign( __page_size, stacksize + __page_size );
|
---|
461 | // pthread has no mechanism to create the guard page in user supplied stack.
|
---|
462 | if ( mprotect( stack, __page_size, PROT_NONE ) == -1 ) {
|
---|
463 | abort( "mprotect : internal error, mprotect failure, error(%d) %s.", errno, strerror( errno ) );
|
---|
464 | } // if
|
---|
465 | #else
|
---|
466 | void * stack = malloc( stacksize );
|
---|
467 | #endif
|
---|
468 |
|
---|
469 | Abort( pthread_attr_setstack( &attr, stack, stacksize ), "pthread_attr_setstack" );
|
---|
470 |
|
---|
471 | Abort( pthread_create( pthread, &attr, start, arg ), "pthread_create" );
|
---|
472 | return stack;
|
---|
473 | }
|
---|
474 |
|
---|
475 | static void start(processor * this) {
|
---|
476 | __cfaabi_dbg_print_safe("Kernel : Starting core %p\n", this);
|
---|
477 |
|
---|
478 | this->stack = create_pthread( &this->kernel_thread, CtxInvokeProcessor, (void *)this );
|
---|
479 |
|
---|
480 | __cfaabi_dbg_print_safe("Kernel : core %p started\n", this);
|
---|
481 | }
|
---|
482 |
|
---|
483 | // KERNEL_ONLY
|
---|
484 | void kernel_first_resume( processor * this ) {
|
---|
485 | thread_desc * src = mainThread;
|
---|
486 | coroutine_desc * dst = get_coroutine(this->runner);
|
---|
487 |
|
---|
488 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
489 |
|
---|
490 | __stack_prepare( &dst->stack, 65000 );
|
---|
491 | CtxStart(&this->runner, CtxInvokeCoroutine);
|
---|
492 |
|
---|
493 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
494 |
|
---|
495 | dst->last = &src->self_cor;
|
---|
496 | dst->starter = dst->starter ? dst->starter : &src->self_cor;
|
---|
497 |
|
---|
498 | // set state of current coroutine to inactive
|
---|
499 | src->state = src->state == Halted ? Halted : Inactive;
|
---|
500 |
|
---|
501 | // context switch to specified coroutine
|
---|
502 | verify( dst->context.SP );
|
---|
503 | CtxSwitch( &src->context, &dst->context );
|
---|
504 | // when CtxSwitch returns we are back in the src coroutine
|
---|
505 |
|
---|
506 | // set state of new coroutine to active
|
---|
507 | src->state = Active;
|
---|
508 |
|
---|
509 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
510 | }
|
---|
511 |
|
---|
512 | // KERNEL_ONLY
|
---|
513 | void kernel_last_resume( processor * this ) {
|
---|
514 | coroutine_desc * src = &mainThread->self_cor;
|
---|
515 | coroutine_desc * dst = get_coroutine(this->runner);
|
---|
516 |
|
---|
517 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
518 | verify( dst->starter == src );
|
---|
519 | verify( dst->context.SP );
|
---|
520 |
|
---|
521 | // context switch to the processor
|
---|
522 | CtxSwitch( &src->context, &dst->context );
|
---|
523 | }
|
---|
524 |
|
---|
525 | //-----------------------------------------------------------------------------
|
---|
526 | // Scheduler routines
|
---|
527 |
|
---|
528 | // KERNEL ONLY
|
---|
529 | void ScheduleThread( thread_desc * thrd ) {
|
---|
530 | verify( thrd );
|
---|
531 | verify( thrd->state != Halted );
|
---|
532 |
|
---|
533 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
534 |
|
---|
535 | verifyf( thrd->next == 0p, "Expected null got %p", thrd->next );
|
---|
536 |
|
---|
537 | with( *thrd->curr_cluster ) {
|
---|
538 | lock ( ready_queue_lock __cfaabi_dbg_ctx2 );
|
---|
539 | bool was_empty = !(ready_queue != 0);
|
---|
540 | append( ready_queue, thrd );
|
---|
541 | unlock( ready_queue_lock );
|
---|
542 |
|
---|
543 | if(was_empty) {
|
---|
544 | lock (proc_list_lock __cfaabi_dbg_ctx2);
|
---|
545 | if(idles) {
|
---|
546 | wake_fast(idles.head);
|
---|
547 | }
|
---|
548 | unlock (proc_list_lock);
|
---|
549 | }
|
---|
550 | else if( struct processor * idle = idles.head ) {
|
---|
551 | wake_fast(idle);
|
---|
552 | }
|
---|
553 |
|
---|
554 | }
|
---|
555 |
|
---|
556 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
557 | }
|
---|
558 |
|
---|
559 | // KERNEL ONLY
|
---|
560 | thread_desc * nextThread(cluster * this) with( *this ) {
|
---|
561 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
562 | lock( ready_queue_lock __cfaabi_dbg_ctx2 );
|
---|
563 | thread_desc * head = pop_head( ready_queue );
|
---|
564 | unlock( ready_queue_lock );
|
---|
565 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
566 | return head;
|
---|
567 | }
|
---|
568 |
|
---|
569 | void BlockInternal() {
|
---|
570 | disable_interrupts();
|
---|
571 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
572 | returnToKernel();
|
---|
573 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
574 | enable_interrupts( __cfaabi_dbg_ctx );
|
---|
575 | }
|
---|
576 |
|
---|
577 | void BlockInternal( __spinlock_t * lock ) {
|
---|
578 | disable_interrupts();
|
---|
579 | with( *kernelTLS.this_processor ) {
|
---|
580 | finish.action_code = Release;
|
---|
581 | finish.lock = lock;
|
---|
582 | }
|
---|
583 |
|
---|
584 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
585 | returnToKernel();
|
---|
586 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
587 |
|
---|
588 | enable_interrupts( __cfaabi_dbg_ctx );
|
---|
589 | }
|
---|
590 |
|
---|
591 | void BlockInternal( thread_desc * thrd ) {
|
---|
592 | disable_interrupts();
|
---|
593 | with( * kernelTLS.this_processor ) {
|
---|
594 | finish.action_code = Schedule;
|
---|
595 | finish.thrd = thrd;
|
---|
596 | }
|
---|
597 |
|
---|
598 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
599 | returnToKernel();
|
---|
600 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
601 |
|
---|
602 | enable_interrupts( __cfaabi_dbg_ctx );
|
---|
603 | }
|
---|
604 |
|
---|
605 | void BlockInternal( __spinlock_t * lock, thread_desc * thrd ) {
|
---|
606 | assert(thrd);
|
---|
607 | disable_interrupts();
|
---|
608 | with( * kernelTLS.this_processor ) {
|
---|
609 | finish.action_code = Release_Schedule;
|
---|
610 | finish.lock = lock;
|
---|
611 | finish.thrd = thrd;
|
---|
612 | }
|
---|
613 |
|
---|
614 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
615 | returnToKernel();
|
---|
616 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
617 |
|
---|
618 | enable_interrupts( __cfaabi_dbg_ctx );
|
---|
619 | }
|
---|
620 |
|
---|
621 | void BlockInternal(__spinlock_t * locks [], unsigned short count) {
|
---|
622 | disable_interrupts();
|
---|
623 | with( * kernelTLS.this_processor ) {
|
---|
624 | finish.action_code = Release_Multi;
|
---|
625 | finish.locks = locks;
|
---|
626 | finish.lock_count = count;
|
---|
627 | }
|
---|
628 |
|
---|
629 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
630 | returnToKernel();
|
---|
631 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
632 |
|
---|
633 | enable_interrupts( __cfaabi_dbg_ctx );
|
---|
634 | }
|
---|
635 |
|
---|
636 | void BlockInternal(__spinlock_t * locks [], unsigned short lock_count, thread_desc * thrds [], unsigned short thrd_count) {
|
---|
637 | disable_interrupts();
|
---|
638 | with( *kernelTLS.this_processor ) {
|
---|
639 | finish.action_code = Release_Multi_Schedule;
|
---|
640 | finish.locks = locks;
|
---|
641 | finish.lock_count = lock_count;
|
---|
642 | finish.thrds = thrds;
|
---|
643 | finish.thrd_count = thrd_count;
|
---|
644 | }
|
---|
645 |
|
---|
646 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
647 | returnToKernel();
|
---|
648 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
649 |
|
---|
650 | enable_interrupts( __cfaabi_dbg_ctx );
|
---|
651 | }
|
---|
652 |
|
---|
653 | void BlockInternal(__finish_callback_fptr_t callback) {
|
---|
654 | disable_interrupts();
|
---|
655 | with( *kernelTLS.this_processor ) {
|
---|
656 | finish.action_code = Callback;
|
---|
657 | finish.callback = callback;
|
---|
658 | }
|
---|
659 |
|
---|
660 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
661 | returnToKernel();
|
---|
662 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
663 |
|
---|
664 | enable_interrupts( __cfaabi_dbg_ctx );
|
---|
665 | }
|
---|
666 |
|
---|
667 | // KERNEL ONLY
|
---|
668 | void LeaveThread(__spinlock_t * lock, thread_desc * thrd) {
|
---|
669 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
670 | with( * kernelTLS.this_processor ) {
|
---|
671 | finish.action_code = thrd ? Release_Schedule : Release;
|
---|
672 | finish.lock = lock;
|
---|
673 | finish.thrd = thrd;
|
---|
674 | }
|
---|
675 |
|
---|
676 | returnToKernel();
|
---|
677 | }
|
---|
678 |
|
---|
679 | //=============================================================================================
|
---|
680 | // Kernel Setup logic
|
---|
681 | //=============================================================================================
|
---|
682 | //-----------------------------------------------------------------------------
|
---|
683 | // Kernel boot procedures
|
---|
684 | static void kernel_startup(void) {
|
---|
685 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
686 | __cfaabi_dbg_print_safe("Kernel : Starting\n");
|
---|
687 |
|
---|
688 | __page_size = sysconf( _SC_PAGESIZE );
|
---|
689 |
|
---|
690 | __cfa_dbg_global_clusters.list{ __get };
|
---|
691 | __cfa_dbg_global_clusters.lock{};
|
---|
692 |
|
---|
693 | // Initialize the main cluster
|
---|
694 | mainCluster = (cluster *)&storage_mainCluster;
|
---|
695 | (*mainCluster){"Main Cluster"};
|
---|
696 |
|
---|
697 | __cfaabi_dbg_print_safe("Kernel : Main cluster ready\n");
|
---|
698 |
|
---|
699 | // Start by initializing the main thread
|
---|
700 | // SKULLDUGGERY: the mainThread steals the process main thread
|
---|
701 | // which will then be scheduled by the mainProcessor normally
|
---|
702 | mainThread = (thread_desc *)&storage_mainThread;
|
---|
703 | current_stack_info_t info;
|
---|
704 | info.storage = (__stack_t*)&storage_mainThreadCtx;
|
---|
705 | (*mainThread){ &info };
|
---|
706 |
|
---|
707 | __cfaabi_dbg_print_safe("Kernel : Main thread ready\n");
|
---|
708 |
|
---|
709 |
|
---|
710 |
|
---|
711 | // Construct the processor context of the main processor
|
---|
712 | void ?{}(processorCtx_t & this, processor * proc) {
|
---|
713 | (this.__cor){ "Processor" };
|
---|
714 | this.__cor.starter = 0p;
|
---|
715 | this.proc = proc;
|
---|
716 | }
|
---|
717 |
|
---|
718 | void ?{}(processor & this) with( this ) {
|
---|
719 | name = "Main Processor";
|
---|
720 | cltr = mainCluster;
|
---|
721 | terminated{ 0 };
|
---|
722 | do_terminate = false;
|
---|
723 | preemption_alarm = 0p;
|
---|
724 | pending_preemption = false;
|
---|
725 | kernel_thread = pthread_self();
|
---|
726 |
|
---|
727 | runner{ &this };
|
---|
728 | __cfaabi_dbg_print_safe("Kernel : constructed main processor context %p\n", &runner);
|
---|
729 | }
|
---|
730 |
|
---|
731 | // Initialize the main processor and the main processor ctx
|
---|
732 | // (the coroutine that contains the processing control flow)
|
---|
733 | mainProcessor = (processor *)&storage_mainProcessor;
|
---|
734 | (*mainProcessor){};
|
---|
735 |
|
---|
736 | //initialize the global state variables
|
---|
737 | kernelTLS.this_processor = mainProcessor;
|
---|
738 | kernelTLS.this_thread = mainThread;
|
---|
739 |
|
---|
740 | // Enable preemption
|
---|
741 | kernel_start_preemption();
|
---|
742 |
|
---|
743 | // Add the main thread to the ready queue
|
---|
744 | // once resume is called on mainProcessor->runner the mainThread needs to be scheduled like any normal thread
|
---|
745 | ScheduleThread(mainThread);
|
---|
746 |
|
---|
747 | // SKULLDUGGERY: Force a context switch to the main processor to set the main thread's context to the current UNIX
|
---|
748 | // context. Hence, the main thread does not begin through CtxInvokeThread, like all other threads. The trick here is that
|
---|
749 | // mainThread is on the ready queue when this call is made.
|
---|
750 | kernel_first_resume( kernelTLS.this_processor );
|
---|
751 |
|
---|
752 |
|
---|
753 |
|
---|
754 | // THE SYSTEM IS NOW COMPLETELY RUNNING
|
---|
755 | __cfaabi_dbg_print_safe("Kernel : Started\n--------------------------------------------------\n\n");
|
---|
756 |
|
---|
757 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
758 | enable_interrupts( __cfaabi_dbg_ctx );
|
---|
759 | verify( TL_GET( preemption_state.enabled ) );
|
---|
760 | }
|
---|
761 |
|
---|
762 | static void kernel_shutdown(void) {
|
---|
763 | __cfaabi_dbg_print_safe("\n--------------------------------------------------\nKernel : Shutting down\n");
|
---|
764 |
|
---|
765 | verify( TL_GET( preemption_state.enabled ) );
|
---|
766 | disable_interrupts();
|
---|
767 | verify( ! kernelTLS.preemption_state.enabled );
|
---|
768 |
|
---|
769 | // SKULLDUGGERY: Notify the mainProcessor it needs to terminates.
|
---|
770 | // When its coroutine terminates, it return control to the mainThread
|
---|
771 | // which is currently here
|
---|
772 | __atomic_store_n(&mainProcessor->do_terminate, true, __ATOMIC_RELEASE);
|
---|
773 | kernel_last_resume( kernelTLS.this_processor );
|
---|
774 | mainThread->self_cor.state = Halted;
|
---|
775 |
|
---|
776 | // THE SYSTEM IS NOW COMPLETELY STOPPED
|
---|
777 |
|
---|
778 | // Disable preemption
|
---|
779 | kernel_stop_preemption();
|
---|
780 |
|
---|
781 | // Destroy the main processor and its context in reverse order of construction
|
---|
782 | // These were manually constructed so we need manually destroy them
|
---|
783 | ^(mainProcessor->runner){};
|
---|
784 | ^(mainProcessor){};
|
---|
785 |
|
---|
786 | // Final step, destroy the main thread since it is no longer needed
|
---|
787 | // Since we provided a stack to this taxk it will not destroy anything
|
---|
788 | ^(mainThread){};
|
---|
789 |
|
---|
790 | ^(__cfa_dbg_global_clusters.list){};
|
---|
791 | ^(__cfa_dbg_global_clusters.lock){};
|
---|
792 |
|
---|
793 | __cfaabi_dbg_print_safe("Kernel : Shutdown complete\n");
|
---|
794 | }
|
---|
795 |
|
---|
796 | //=============================================================================================
|
---|
797 | // Kernel Quiescing
|
---|
798 | //=============================================================================================
|
---|
799 | static void halt(processor * this) with( *this ) {
|
---|
800 | // verify( ! __atomic_load_n(&do_terminate, __ATOMIC_SEQ_CST) );
|
---|
801 |
|
---|
802 | with( *cltr ) {
|
---|
803 | lock (proc_list_lock __cfaabi_dbg_ctx2);
|
---|
804 | remove (procs, *this);
|
---|
805 | push_front(idles, *this);
|
---|
806 | unlock (proc_list_lock);
|
---|
807 | }
|
---|
808 |
|
---|
809 | __cfaabi_dbg_print_safe("Kernel : Processor %p ready to sleep\n", this);
|
---|
810 |
|
---|
811 | wait( idleLock );
|
---|
812 |
|
---|
813 | __cfaabi_dbg_print_safe("Kernel : Processor %p woke up and ready to run\n", this);
|
---|
814 |
|
---|
815 | with( *cltr ) {
|
---|
816 | lock (proc_list_lock __cfaabi_dbg_ctx2);
|
---|
817 | remove (idles, *this);
|
---|
818 | push_front(procs, *this);
|
---|
819 | unlock (proc_list_lock);
|
---|
820 | }
|
---|
821 | }
|
---|
822 |
|
---|
823 | //=============================================================================================
|
---|
824 | // Unexpected Terminating logic
|
---|
825 | //=============================================================================================
|
---|
826 | static __spinlock_t kernel_abort_lock;
|
---|
827 | static bool kernel_abort_called = false;
|
---|
828 |
|
---|
829 | void * kernel_abort(void) __attribute__ ((__nothrow__)) {
|
---|
830 | // abort cannot be recursively entered by the same or different processors because all signal handlers return when
|
---|
831 | // the globalAbort flag is true.
|
---|
832 | lock( kernel_abort_lock __cfaabi_dbg_ctx2 );
|
---|
833 |
|
---|
834 | // first task to abort ?
|
---|
835 | if ( kernel_abort_called ) { // not first task to abort ?
|
---|
836 | unlock( kernel_abort_lock );
|
---|
837 |
|
---|
838 | sigset_t mask;
|
---|
839 | sigemptyset( &mask );
|
---|
840 | sigaddset( &mask, SIGALRM ); // block SIGALRM signals
|
---|
841 | sigsuspend( &mask ); // block the processor to prevent further damage during abort
|
---|
842 | _exit( EXIT_FAILURE ); // if processor unblocks before it is killed, terminate it
|
---|
843 | }
|
---|
844 | else {
|
---|
845 | kernel_abort_called = true;
|
---|
846 | unlock( kernel_abort_lock );
|
---|
847 | }
|
---|
848 |
|
---|
849 | return kernelTLS.this_thread;
|
---|
850 | }
|
---|
851 |
|
---|
852 | void kernel_abort_msg( void * kernel_data, char * abort_text, int abort_text_size ) {
|
---|
853 | thread_desc * thrd = kernel_data;
|
---|
854 |
|
---|
855 | if(thrd) {
|
---|
856 | int len = snprintf( abort_text, abort_text_size, "Error occurred while executing thread %.256s (%p)", thrd->self_cor.name, thrd );
|
---|
857 | __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
|
---|
858 |
|
---|
859 | if ( &thrd->self_cor != thrd->curr_cor ) {
|
---|
860 | len = snprintf( abort_text, abort_text_size, " in coroutine %.256s (%p).\n", thrd->curr_cor->name, thrd->curr_cor );
|
---|
861 | __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
|
---|
862 | }
|
---|
863 | else {
|
---|
864 | __cfaabi_bits_write( STDERR_FILENO, ".\n", 2 );
|
---|
865 | }
|
---|
866 | }
|
---|
867 | else {
|
---|
868 | int len = snprintf( abort_text, abort_text_size, "Error occurred outside of any thread.\n" );
|
---|
869 | __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
|
---|
870 | }
|
---|
871 | }
|
---|
872 |
|
---|
873 | int kernel_abort_lastframe( void ) __attribute__ ((__nothrow__)) {
|
---|
874 | return get_coroutine(kernelTLS.this_thread) == get_coroutine(mainThread) ? 4 : 2;
|
---|
875 | }
|
---|
876 |
|
---|
877 | static __spinlock_t kernel_debug_lock;
|
---|
878 |
|
---|
879 | extern "C" {
|
---|
880 | void __cfaabi_bits_acquire() {
|
---|
881 | lock( kernel_debug_lock __cfaabi_dbg_ctx2 );
|
---|
882 | }
|
---|
883 |
|
---|
884 | void __cfaabi_bits_release() {
|
---|
885 | unlock( kernel_debug_lock );
|
---|
886 | }
|
---|
887 | }
|
---|
888 |
|
---|
889 | //=============================================================================================
|
---|
890 | // Kernel Utilities
|
---|
891 | //=============================================================================================
|
---|
892 | //-----------------------------------------------------------------------------
|
---|
893 | // Locks
|
---|
894 | void ?{}( semaphore & this, int count = 1 ) {
|
---|
895 | (this.lock){};
|
---|
896 | this.count = count;
|
---|
897 | (this.waiting){};
|
---|
898 | }
|
---|
899 | void ^?{}(semaphore & this) {}
|
---|
900 |
|
---|
901 | void P(semaphore & this) with( this ){
|
---|
902 | lock( lock __cfaabi_dbg_ctx2 );
|
---|
903 | count -= 1;
|
---|
904 | if ( count < 0 ) {
|
---|
905 | // queue current task
|
---|
906 | append( waiting, kernelTLS.this_thread );
|
---|
907 |
|
---|
908 | // atomically release spin lock and block
|
---|
909 | BlockInternal( &lock );
|
---|
910 | }
|
---|
911 | else {
|
---|
912 | unlock( lock );
|
---|
913 | }
|
---|
914 | }
|
---|
915 |
|
---|
916 | void V(semaphore & this) with( this ) {
|
---|
917 | thread_desc * thrd = 0p;
|
---|
918 | lock( lock __cfaabi_dbg_ctx2 );
|
---|
919 | count += 1;
|
---|
920 | if ( count <= 0 ) {
|
---|
921 | // remove task at head of waiting list
|
---|
922 | thrd = pop_head( waiting );
|
---|
923 | }
|
---|
924 |
|
---|
925 | unlock( lock );
|
---|
926 |
|
---|
927 | // make new owner
|
---|
928 | WakeThread( thrd );
|
---|
929 | }
|
---|
930 |
|
---|
931 | //-----------------------------------------------------------------------------
|
---|
932 | // Global Queues
|
---|
933 | void doregister( cluster & cltr ) {
|
---|
934 | lock ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2);
|
---|
935 | push_front( __cfa_dbg_global_clusters.list, cltr );
|
---|
936 | unlock ( __cfa_dbg_global_clusters.lock );
|
---|
937 | }
|
---|
938 |
|
---|
939 | void unregister( cluster & cltr ) {
|
---|
940 | lock ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2);
|
---|
941 | remove( __cfa_dbg_global_clusters.list, cltr );
|
---|
942 | unlock( __cfa_dbg_global_clusters.lock );
|
---|
943 | }
|
---|
944 |
|
---|
945 | void doregister( cluster * cltr, thread_desc & thrd ) {
|
---|
946 | lock (cltr->thread_list_lock __cfaabi_dbg_ctx2);
|
---|
947 | cltr->nthreads += 1;
|
---|
948 | push_front(cltr->threads, thrd);
|
---|
949 | unlock (cltr->thread_list_lock);
|
---|
950 | }
|
---|
951 |
|
---|
952 | void unregister( cluster * cltr, thread_desc & thrd ) {
|
---|
953 | lock (cltr->thread_list_lock __cfaabi_dbg_ctx2);
|
---|
954 | remove(cltr->threads, thrd );
|
---|
955 | cltr->nthreads -= 1;
|
---|
956 | unlock(cltr->thread_list_lock);
|
---|
957 | }
|
---|
958 |
|
---|
959 | void doregister( cluster * cltr, processor * proc ) {
|
---|
960 | lock (cltr->proc_list_lock __cfaabi_dbg_ctx2);
|
---|
961 | cltr->nprocessors += 1;
|
---|
962 | push_front(cltr->procs, *proc);
|
---|
963 | unlock (cltr->proc_list_lock);
|
---|
964 | }
|
---|
965 |
|
---|
966 | void unregister( cluster * cltr, processor * proc ) {
|
---|
967 | lock (cltr->proc_list_lock __cfaabi_dbg_ctx2);
|
---|
968 | remove(cltr->procs, *proc );
|
---|
969 | cltr->nprocessors -= 1;
|
---|
970 | unlock(cltr->proc_list_lock);
|
---|
971 | }
|
---|
972 |
|
---|
973 | //-----------------------------------------------------------------------------
|
---|
974 | // Debug
|
---|
975 | __cfaabi_dbg_debug_do(
|
---|
976 | extern "C" {
|
---|
977 | void __cfaabi_dbg_record(__spinlock_t & this, const char * prev_name) {
|
---|
978 | this.prev_name = prev_name;
|
---|
979 | this.prev_thrd = kernelTLS.this_thread;
|
---|
980 | }
|
---|
981 | }
|
---|
982 | )
|
---|
983 |
|
---|
984 | //-----------------------------------------------------------------------------
|
---|
985 | // Debug
|
---|
986 | bool threading_enabled(void) {
|
---|
987 | return true;
|
---|
988 | }
|
---|
989 | // Local Variables: //
|
---|
990 | // mode: c //
|
---|
991 | // tab-width: 4 //
|
---|
992 | // End: //
|
---|