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

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 ce7bdc4 was 27f5f71, checked in by Peter A. Buhr <pabuhr@…>, 6 years ago

explicitly create stack for pthread thread, 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 : Fri Nov 29 17:59:16 2019
13// Update Count : 35
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" {
126struct { __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,
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 = NULL;
176 last = NULL;
177 cancellation = NULL;
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 = NULL;
189
190 node.next = NULL;
191 node.prev = NULL;
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 = NULL;
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, NULL );
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 = NULL;
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 = NULL;
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 = NULL;
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 NULL;
444}
445
446static void start(processor * this) {
447 __cfaabi_dbg_print_safe("Kernel : Starting core %p\n", this);
448
449 pthread_attr_t attr;
450 int ret;
451 ret = pthread_attr_init( &attr ); // initialize attribute
452 if ( ret ) {
453 abort( "%s : internal error, pthread_attr_init failed, error(%d) %s.", __PRETTY_FUNCTION__, ret, strerror( ret ) );
454 } // if
455
456 size_t stacksize;
457 ret = pthread_attr_getstacksize( &attr, &stacksize ); // default stack size, normally defined by shell limit
458 if ( ret ) {
459 abort( "%s : internal error, pthread_attr_getstacksize failed, error(%d) %s.", __PRETTY_FUNCTION__, ret, strerror( ret ) );
460 } // if
461 assert( stacksize >= PTHREAD_STACK_MIN );
462
463 this->stack = malloc( stacksize );
464 ret = pthread_attr_setstack( &attr, this->stack, stacksize );
465 if ( ret ) {
466 abort( "%s : internal error, pthread_attr_setstack failed, error(%d) %s.", __PRETTY_FUNCTION__, ret, strerror( ret ) );
467 } // if
468
469 ret = pthread_create( &this->kernel_thread, &attr, CtxInvokeProcessor, (void *)this );
470 if ( ret ) {
471 abort( "%s : internal error, pthread_create failed, error(%d) %s.", __PRETTY_FUNCTION__, ret, strerror( ret ) );
472 } // if
473// pthread_create( &this->kernel_thread, NULL, CtxInvokeProcessor, (void*)this );
474
475 __cfaabi_dbg_print_safe("Kernel : core %p started\n", this);
476}
477
478// KERNEL_ONLY
479void kernel_first_resume( processor * this ) {
480 thread_desc * src = mainThread;
481 coroutine_desc * dst = get_coroutine(this->runner);
482
483 verify( ! kernelTLS.preemption_state.enabled );
484
485 __stack_prepare( &dst->stack, 65000 );
486 CtxStart(&this->runner, CtxInvokeCoroutine);
487
488 verify( ! kernelTLS.preemption_state.enabled );
489
490 dst->last = &src->self_cor;
491 dst->starter = dst->starter ? dst->starter : &src->self_cor;
492
493 // set state of current coroutine to inactive
494 src->state = src->state == Halted ? Halted : Inactive;
495
496 // context switch to specified coroutine
497 verify( dst->context.SP );
498 CtxSwitch( &src->context, &dst->context );
499 // when CtxSwitch returns we are back in the src coroutine
500
501 // set state of new coroutine to active
502 src->state = Active;
503
504 verify( ! kernelTLS.preemption_state.enabled );
505}
506
507// KERNEL_ONLY
508void kernel_last_resume( processor * this ) {
509 coroutine_desc * src = &mainThread->self_cor;
510 coroutine_desc * dst = get_coroutine(this->runner);
511
512 verify( ! kernelTLS.preemption_state.enabled );
513 verify( dst->starter == src );
514 verify( dst->context.SP );
515
516 // context switch to the processor
517 CtxSwitch( &src->context, &dst->context );
518}
519
520//-----------------------------------------------------------------------------
521// Scheduler routines
522
523// KERNEL ONLY
524void ScheduleThread( thread_desc * thrd ) {
525 verify( thrd );
526 verify( thrd->state != Halted );
527
528 verify( ! kernelTLS.preemption_state.enabled );
529
530 verifyf( thrd->next == NULL, "Expected null got %p", thrd->next );
531
532 with( *thrd->curr_cluster ) {
533 lock ( ready_queue_lock __cfaabi_dbg_ctx2 );
534 bool was_empty = !(ready_queue != 0);
535 append( ready_queue, thrd );
536 unlock( ready_queue_lock );
537
538 if(was_empty) {
539 lock (proc_list_lock __cfaabi_dbg_ctx2);
540 if(idles) {
541 wake_fast(idles.head);
542 }
543 unlock (proc_list_lock);
544 }
545 else if( struct processor * idle = idles.head ) {
546 wake_fast(idle);
547 }
548
549 }
550
551 verify( ! kernelTLS.preemption_state.enabled );
552}
553
554// KERNEL ONLY
555thread_desc * nextThread(cluster * this) with( *this ) {
556 verify( ! kernelTLS.preemption_state.enabled );
557 lock( ready_queue_lock __cfaabi_dbg_ctx2 );
558 thread_desc * head = pop_head( ready_queue );
559 unlock( ready_queue_lock );
560 verify( ! kernelTLS.preemption_state.enabled );
561 return head;
562}
563
564void BlockInternal() {
565 disable_interrupts();
566 verify( ! kernelTLS.preemption_state.enabled );
567 returnToKernel();
568 verify( ! kernelTLS.preemption_state.enabled );
569 enable_interrupts( __cfaabi_dbg_ctx );
570}
571
572void BlockInternal( __spinlock_t * lock ) {
573 disable_interrupts();
574 with( *kernelTLS.this_processor ) {
575 finish.action_code = Release;
576 finish.lock = lock;
577 }
578
579 verify( ! kernelTLS.preemption_state.enabled );
580 returnToKernel();
581 verify( ! kernelTLS.preemption_state.enabled );
582
583 enable_interrupts( __cfaabi_dbg_ctx );
584}
585
586void BlockInternal( thread_desc * thrd ) {
587 disable_interrupts();
588 with( * kernelTLS.this_processor ) {
589 finish.action_code = Schedule;
590 finish.thrd = thrd;
591 }
592
593 verify( ! kernelTLS.preemption_state.enabled );
594 returnToKernel();
595 verify( ! kernelTLS.preemption_state.enabled );
596
597 enable_interrupts( __cfaabi_dbg_ctx );
598}
599
600void BlockInternal( __spinlock_t * lock, thread_desc * thrd ) {
601 assert(thrd);
602 disable_interrupts();
603 with( * kernelTLS.this_processor ) {
604 finish.action_code = Release_Schedule;
605 finish.lock = lock;
606 finish.thrd = thrd;
607 }
608
609 verify( ! kernelTLS.preemption_state.enabled );
610 returnToKernel();
611 verify( ! kernelTLS.preemption_state.enabled );
612
613 enable_interrupts( __cfaabi_dbg_ctx );
614}
615
616void BlockInternal(__spinlock_t * locks [], unsigned short count) {
617 disable_interrupts();
618 with( * kernelTLS.this_processor ) {
619 finish.action_code = Release_Multi;
620 finish.locks = locks;
621 finish.lock_count = count;
622 }
623
624 verify( ! kernelTLS.preemption_state.enabled );
625 returnToKernel();
626 verify( ! kernelTLS.preemption_state.enabled );
627
628 enable_interrupts( __cfaabi_dbg_ctx );
629}
630
631void BlockInternal(__spinlock_t * locks [], unsigned short lock_count, thread_desc * thrds [], unsigned short thrd_count) {
632 disable_interrupts();
633 with( *kernelTLS.this_processor ) {
634 finish.action_code = Release_Multi_Schedule;
635 finish.locks = locks;
636 finish.lock_count = lock_count;
637 finish.thrds = thrds;
638 finish.thrd_count = thrd_count;
639 }
640
641 verify( ! kernelTLS.preemption_state.enabled );
642 returnToKernel();
643 verify( ! kernelTLS.preemption_state.enabled );
644
645 enable_interrupts( __cfaabi_dbg_ctx );
646}
647
648void BlockInternal(__finish_callback_fptr_t callback) {
649 disable_interrupts();
650 with( *kernelTLS.this_processor ) {
651 finish.action_code = Callback;
652 finish.callback = callback;
653 }
654
655 verify( ! kernelTLS.preemption_state.enabled );
656 returnToKernel();
657 verify( ! kernelTLS.preemption_state.enabled );
658
659 enable_interrupts( __cfaabi_dbg_ctx );
660}
661
662// KERNEL ONLY
663void LeaveThread(__spinlock_t * lock, thread_desc * thrd) {
664 verify( ! kernelTLS.preemption_state.enabled );
665 with( * kernelTLS.this_processor ) {
666 finish.action_code = thrd ? Release_Schedule : Release;
667 finish.lock = lock;
668 finish.thrd = thrd;
669 }
670
671 returnToKernel();
672}
673
674//=============================================================================================
675// Kernel Setup logic
676//=============================================================================================
677//-----------------------------------------------------------------------------
678// Kernel boot procedures
679static void kernel_startup(void) {
680 verify( ! kernelTLS.preemption_state.enabled );
681 __cfaabi_dbg_print_safe("Kernel : Starting\n");
682
683 __page_size = sysconf( _SC_PAGESIZE );
684
685 __cfa_dbg_global_clusters.list{ __get };
686 __cfa_dbg_global_clusters.lock{};
687
688 // Initialize the main cluster
689 mainCluster = (cluster *)&storage_mainCluster;
690 (*mainCluster){"Main Cluster"};
691
692 __cfaabi_dbg_print_safe("Kernel : Main cluster ready\n");
693
694 // Start by initializing the main thread
695 // SKULLDUGGERY: the mainThread steals the process main thread
696 // which will then be scheduled by the mainProcessor normally
697 mainThread = (thread_desc *)&storage_mainThread;
698 current_stack_info_t info;
699 info.storage = (__stack_t*)&storage_mainThreadCtx;
700 (*mainThread){ &info };
701
702 __cfaabi_dbg_print_safe("Kernel : Main thread ready\n");
703
704
705
706 // Construct the processor context of the main processor
707 void ?{}(processorCtx_t & this, processor * proc) {
708 (this.__cor){ "Processor" };
709 this.__cor.starter = NULL;
710 this.proc = proc;
711 }
712
713 void ?{}(processor & this) with( this ) {
714 name = "Main Processor";
715 cltr = mainCluster;
716 terminated{ 0 };
717 do_terminate = false;
718 preemption_alarm = NULL;
719 pending_preemption = false;
720 kernel_thread = pthread_self();
721
722 runner{ &this };
723 __cfaabi_dbg_print_safe("Kernel : constructed main processor context %p\n", &runner);
724 }
725
726 // Initialize the main processor and the main processor ctx
727 // (the coroutine that contains the processing control flow)
728 mainProcessor = (processor *)&storage_mainProcessor;
729 (*mainProcessor){};
730
731 //initialize the global state variables
732 kernelTLS.this_processor = mainProcessor;
733 kernelTLS.this_thread = mainThread;
734
735 // Enable preemption
736 kernel_start_preemption();
737
738 // Add the main thread to the ready queue
739 // once resume is called on mainProcessor->runner the mainThread needs to be scheduled like any normal thread
740 ScheduleThread(mainThread);
741
742 // SKULLDUGGERY: Force a context switch to the main processor to set the main thread's context to the current UNIX
743 // context. Hence, the main thread does not begin through CtxInvokeThread, like all other threads. The trick here is that
744 // mainThread is on the ready queue when this call is made.
745 kernel_first_resume( kernelTLS.this_processor );
746
747
748
749 // THE SYSTEM IS NOW COMPLETELY RUNNING
750 __cfaabi_dbg_print_safe("Kernel : Started\n--------------------------------------------------\n\n");
751
752 verify( ! kernelTLS.preemption_state.enabled );
753 enable_interrupts( __cfaabi_dbg_ctx );
754 verify( TL_GET( preemption_state.enabled ) );
755}
756
757static void kernel_shutdown(void) {
758 __cfaabi_dbg_print_safe("\n--------------------------------------------------\nKernel : Shutting down\n");
759
760 verify( TL_GET( preemption_state.enabled ) );
761 disable_interrupts();
762 verify( ! kernelTLS.preemption_state.enabled );
763
764 // SKULLDUGGERY: Notify the mainProcessor it needs to terminates.
765 // When its coroutine terminates, it return control to the mainThread
766 // which is currently here
767 __atomic_store_n(&mainProcessor->do_terminate, true, __ATOMIC_RELEASE);
768 kernel_last_resume( kernelTLS.this_processor );
769 mainThread->self_cor.state = Halted;
770
771 // THE SYSTEM IS NOW COMPLETELY STOPPED
772
773 // Disable preemption
774 kernel_stop_preemption();
775
776 // Destroy the main processor and its context in reverse order of construction
777 // These were manually constructed so we need manually destroy them
778 ^(mainProcessor->runner){};
779 ^(mainProcessor){};
780
781 // Final step, destroy the main thread since it is no longer needed
782 // Since we provided a stack to this taxk it will not destroy anything
783 ^(mainThread){};
784
785 ^(__cfa_dbg_global_clusters.list){};
786 ^(__cfa_dbg_global_clusters.lock){};
787
788 __cfaabi_dbg_print_safe("Kernel : Shutdown complete\n");
789}
790
791//=============================================================================================
792// Kernel Quiescing
793//=============================================================================================
794static void halt(processor * this) with( *this ) {
795 // verify( ! __atomic_load_n(&do_terminate, __ATOMIC_SEQ_CST) );
796
797 with( *cltr ) {
798 lock (proc_list_lock __cfaabi_dbg_ctx2);
799 remove (procs, *this);
800 push_front(idles, *this);
801 unlock (proc_list_lock);
802 }
803
804 __cfaabi_dbg_print_safe("Kernel : Processor %p ready to sleep\n", this);
805
806 wait( idleLock );
807
808 __cfaabi_dbg_print_safe("Kernel : Processor %p woke up and ready to run\n", this);
809
810 with( *cltr ) {
811 lock (proc_list_lock __cfaabi_dbg_ctx2);
812 remove (idles, *this);
813 push_front(procs, *this);
814 unlock (proc_list_lock);
815 }
816}
817
818//=============================================================================================
819// Unexpected Terminating logic
820//=============================================================================================
821static __spinlock_t kernel_abort_lock;
822static bool kernel_abort_called = false;
823
824void * kernel_abort(void) __attribute__ ((__nothrow__)) {
825 // abort cannot be recursively entered by the same or different processors because all signal handlers return when
826 // the globalAbort flag is true.
827 lock( kernel_abort_lock __cfaabi_dbg_ctx2 );
828
829 // first task to abort ?
830 if ( kernel_abort_called ) { // not first task to abort ?
831 unlock( kernel_abort_lock );
832
833 sigset_t mask;
834 sigemptyset( &mask );
835 sigaddset( &mask, SIGALRM ); // block SIGALRM signals
836 sigsuspend( &mask ); // block the processor to prevent further damage during abort
837 _exit( EXIT_FAILURE ); // if processor unblocks before it is killed, terminate it
838 }
839 else {
840 kernel_abort_called = true;
841 unlock( kernel_abort_lock );
842 }
843
844 return kernelTLS.this_thread;
845}
846
847void kernel_abort_msg( void * kernel_data, char * abort_text, int abort_text_size ) {
848 thread_desc * thrd = kernel_data;
849
850 if(thrd) {
851 int len = snprintf( abort_text, abort_text_size, "Error occurred while executing thread %.256s (%p)", thrd->self_cor.name, thrd );
852 __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
853
854 if ( &thrd->self_cor != thrd->curr_cor ) {
855 len = snprintf( abort_text, abort_text_size, " in coroutine %.256s (%p).\n", thrd->curr_cor->name, thrd->curr_cor );
856 __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
857 }
858 else {
859 __cfaabi_bits_write( STDERR_FILENO, ".\n", 2 );
860 }
861 }
862 else {
863 int len = snprintf( abort_text, abort_text_size, "Error occurred outside of any thread.\n" );
864 __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
865 }
866}
867
868int kernel_abort_lastframe( void ) __attribute__ ((__nothrow__)) {
869 return get_coroutine(kernelTLS.this_thread) == get_coroutine(mainThread) ? 4 : 2;
870}
871
872static __spinlock_t kernel_debug_lock;
873
874extern "C" {
875 void __cfaabi_bits_acquire() {
876 lock( kernel_debug_lock __cfaabi_dbg_ctx2 );
877 }
878
879 void __cfaabi_bits_release() {
880 unlock( kernel_debug_lock );
881 }
882}
883
884//=============================================================================================
885// Kernel Utilities
886//=============================================================================================
887//-----------------------------------------------------------------------------
888// Locks
889void ?{}( semaphore & this, int count = 1 ) {
890 (this.lock){};
891 this.count = count;
892 (this.waiting){};
893}
894void ^?{}(semaphore & this) {}
895
896void P(semaphore & this) with( this ){
897 lock( lock __cfaabi_dbg_ctx2 );
898 count -= 1;
899 if ( count < 0 ) {
900 // queue current task
901 append( waiting, kernelTLS.this_thread );
902
903 // atomically release spin lock and block
904 BlockInternal( &lock );
905 }
906 else {
907 unlock( lock );
908 }
909}
910
911void V(semaphore & this) with( this ) {
912 thread_desc * thrd = NULL;
913 lock( lock __cfaabi_dbg_ctx2 );
914 count += 1;
915 if ( count <= 0 ) {
916 // remove task at head of waiting list
917 thrd = pop_head( waiting );
918 }
919
920 unlock( lock );
921
922 // make new owner
923 WakeThread( thrd );
924}
925
926//-----------------------------------------------------------------------------
927// Global Queues
928void doregister( cluster & cltr ) {
929 lock ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2);
930 push_front( __cfa_dbg_global_clusters.list, cltr );
931 unlock ( __cfa_dbg_global_clusters.lock );
932}
933
934void unregister( cluster & cltr ) {
935 lock ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2);
936 remove( __cfa_dbg_global_clusters.list, cltr );
937 unlock( __cfa_dbg_global_clusters.lock );
938}
939
940void doregister( cluster * cltr, thread_desc & thrd ) {
941 lock (cltr->thread_list_lock __cfaabi_dbg_ctx2);
942 cltr->nthreads += 1;
943 push_front(cltr->threads, thrd);
944 unlock (cltr->thread_list_lock);
945}
946
947void unregister( cluster * cltr, thread_desc & thrd ) {
948 lock (cltr->thread_list_lock __cfaabi_dbg_ctx2);
949 remove(cltr->threads, thrd );
950 cltr->nthreads -= 1;
951 unlock(cltr->thread_list_lock);
952}
953
954void doregister( cluster * cltr, processor * proc ) {
955 lock (cltr->proc_list_lock __cfaabi_dbg_ctx2);
956 cltr->nprocessors += 1;
957 push_front(cltr->procs, *proc);
958 unlock (cltr->proc_list_lock);
959}
960
961void unregister( cluster * cltr, processor * proc ) {
962 lock (cltr->proc_list_lock __cfaabi_dbg_ctx2);
963 remove(cltr->procs, *proc );
964 cltr->nprocessors -= 1;
965 unlock(cltr->proc_list_lock);
966}
967
968//-----------------------------------------------------------------------------
969// Debug
970__cfaabi_dbg_debug_do(
971 extern "C" {
972 void __cfaabi_dbg_record(__spinlock_t & this, const char * prev_name) {
973 this.prev_name = prev_name;
974 this.prev_thrd = kernelTLS.this_thread;
975 }
976 }
977)
978
979//-----------------------------------------------------------------------------
980// Debug
981bool threading_enabled(void) {
982 return true;
983}
984// Local Variables: //
985// mode: c //
986// tab-width: 4 //
987// End: //
Note: See TracBrowser for help on using the repository browser.