source: libcfa/src/concurrency/kernel.cfa@ c84b4be

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since c84b4be was c84b4be, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

new ready queue seems to work but halting does not, had to be disabled

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