source: libcfa/src/concurrency/kernel.cfa@ 924c5ce

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 924c5ce was 1805b1b, checked in by Peter A. Buhr <pabuhr@…>, 6 years ago

refactor pthread_create into create_pthread, change NULL to 0p

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