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

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since b7d6a36 was b7d6a36, checked in by Thierry Delisle <tdelisle@…>, 5 years ago

Merge branch 'master' into relaxed_ready

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