source: libcfa/src/concurrency/kernel.cfa@ 9f575ea

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

First attempt at park/unpark

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