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

arm-ehenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since b0c7419 was b0c7419, checked in by Thierry Delisle <tdelisle@…>, 3 years ago

Yield now uses force_yield instead of park/unpark.
Final ctxswitch of a thread now uses ad-hoc mechanism instead of park/unpark.

  • Property mode set to 100644
File size: 29.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 : Thu Jan 30 22:55:50 2020
13// Update Count     : 56
14//
15
16#define __cforall_thread__
17
18//C Includes
19#include <stddef.h>
20#include <errno.h>
21#include <string.h>
22extern "C" {
23#include <stdio.h>
24#include <fenv.h>
25#include <sys/resource.h>
26#include <signal.h>
27#include <unistd.h>
28#include <limits.h>                                                                             // PTHREAD_STACK_MIN
29#include <sys/mman.h>                                                                   // mprotect
30}
31
32//CFA Includes
33#include "time.hfa"
34#include "kernel_private.hfa"
35#include "preemption.hfa"
36#include "startup.hfa"
37
38//Private includes
39#define __CFA_INVOKE_PRIVATE__
40#include "invoke.h"
41
42//-----------------------------------------------------------------------------
43// Some assembly required
44#if defined( __i386 )
45        #define CtxGet( ctx )        \
46                __asm__ volatile (     \
47                        "movl %%esp,%0\n"\
48                        "movl %%ebp,%1\n"\
49                        : "=rm" (ctx.SP),\
50                                "=rm" (ctx.FP) \
51                )
52
53        // mxcr : SSE Status and Control bits (control bits are preserved across function calls)
54        // fcw  : X87 FPU control word (preserved across function calls)
55        #define __x87_store         \
56                uint32_t __mxcr;      \
57                uint16_t __fcw;       \
58                __asm__ volatile (    \
59                        "stmxcsr %0\n"  \
60                        "fnstcw  %1\n"  \
61                        : "=m" (__mxcr),\
62                                "=m" (__fcw)  \
63                )
64
65        #define __x87_load         \
66                __asm__ volatile (   \
67                        "fldcw  %1\n"  \
68                        "ldmxcsr %0\n" \
69                        ::"m" (__mxcr),\
70                                "m" (__fcw)  \
71                )
72
73#elif defined( __x86_64 )
74        #define CtxGet( ctx )        \
75                __asm__ volatile (     \
76                        "movq %%rsp,%0\n"\
77                        "movq %%rbp,%1\n"\
78                        : "=rm" (ctx.SP),\
79                                "=rm" (ctx.FP) \
80                )
81
82        #define __x87_store         \
83                uint32_t __mxcr;      \
84                uint16_t __fcw;       \
85                __asm__ volatile (    \
86                        "stmxcsr %0\n"  \
87                        "fnstcw  %1\n"  \
88                        : "=m" (__mxcr),\
89                                "=m" (__fcw)  \
90                )
91
92        #define __x87_load          \
93                __asm__ volatile (    \
94                        "fldcw  %1\n"   \
95                        "ldmxcsr %0\n"  \
96                        :: "m" (__mxcr),\
97                                "m" (__fcw)  \
98                )
99
100
101#elif defined( __ARM_ARCH )
102#define CtxGet( ctx ) __asm__ ( \
103                "mov %0,%%sp\n"   \
104                "mov %1,%%r11\n"   \
105        : "=rm" (ctx.SP), "=rm" (ctx.FP) )
106#else
107        #error unknown hardware architecture
108#endif
109
110//-----------------------------------------------------------------------------
111//Start and stop routine for the kernel, declared first to make sure they run first
112static void kernel_startup(void)  __attribute__(( constructor( STARTUP_PRIORITY_KERNEL ) ));
113static void kernel_shutdown(void) __attribute__(( destructor ( STARTUP_PRIORITY_KERNEL ) ));
114
115//-----------------------------------------------------------------------------
116// Kernel storage
117KERNEL_STORAGE(cluster,         mainCluster);
118KERNEL_STORAGE(processor,       mainProcessor);
119KERNEL_STORAGE(thread_desc,     mainThread);
120KERNEL_STORAGE(__stack_t,       mainThreadCtx);
121
122cluster     * mainCluster;
123processor   * mainProcessor;
124thread_desc * mainThread;
125
126extern "C" {
127        struct { __dllist_t(cluster) list; __spinlock_t lock; } __cfa_dbg_global_clusters;
128}
129
130size_t __page_size = 0;
131
132//-----------------------------------------------------------------------------
133// Global state
134thread_local struct KernelThreadData kernelTLS __attribute__ ((tls_model ( "initial-exec" ))) = {
135        NULL,                                                                                           // cannot use 0p
136        NULL,
137        { 1, false, false },
138        6u //this should be seeded better but due to a bug calling rdtsc doesn't work
139};
140
141//-----------------------------------------------------------------------------
142// Struct to steal stack
143struct current_stack_info_t {
144        __stack_t * storage;                                                            // pointer to stack object
145        void * base;                                                                            // base of stack
146        void * limit;                                                                           // stack grows towards stack limit
147        void * context;                                                                         // address of cfa_context_t
148};
149
150void ?{}( current_stack_info_t & this ) {
151        __stack_context_t ctx;
152        CtxGet( ctx );
153        this.base = ctx.FP;
154
155        rlimit r;
156        getrlimit( RLIMIT_STACK, &r);
157        size_t size = r.rlim_cur;
158
159        this.limit = (void *)(((intptr_t)this.base) - size);
160        this.context = &storage_mainThreadCtx;
161}
162
163//-----------------------------------------------------------------------------
164// Main thread construction
165
166void ?{}( coroutine_desc & this, current_stack_info_t * info) with( this ) {
167        stack.storage = info->storage;
168        with(*stack.storage) {
169                limit     = info->limit;
170                base      = info->base;
171        }
172        __attribute__((may_alias)) intptr_t * istorage = (intptr_t*) &stack.storage;
173        *istorage |= 0x1;
174        name = "Main Thread";
175        state = Start;
176        starter = 0p;
177        last = 0p;
178        cancellation = 0p;
179}
180
181void ?{}( thread_desc & this, current_stack_info_t * info) with( this ) {
182        state = Start;
183        self_cor{ info };
184        curr_cor = &self_cor;
185        curr_cluster = mainCluster;
186        self_mon.owner = &this;
187        self_mon.recursion = 1;
188        self_mon_p = &self_mon;
189        next = 0p;
190
191        node.next = 0p;
192        node.prev = 0p;
193        doregister(curr_cluster, this);
194
195        monitors{ &self_mon_p, 1, (fptr_t)0 };
196}
197
198//-----------------------------------------------------------------------------
199// Processor coroutine
200void ?{}(processorCtx_t & this) {
201
202}
203
204// Construct the processor context of non-main processors
205static void ?{}(processorCtx_t & this, processor * proc, current_stack_info_t * info) {
206        (this.__cor){ info };
207        this.proc = proc;
208}
209
210static void start(processor * this);
211void ?{}(processor & this, const char * name, cluster & cltr) with( this ) {
212        this.name = name;
213        this.cltr = &cltr;
214        terminated{ 0 };
215        destroyer = 0p;
216        do_terminate = false;
217        preemption_alarm = 0p;
218        pending_preemption = false;
219        runner.proc = &this;
220
221        idleLock{};
222
223        start( &this );
224}
225
226void ^?{}(processor & this) with( this ){
227        if( ! __atomic_load_n(&do_terminate, __ATOMIC_ACQUIRE) ) {
228                __cfaabi_dbg_print_safe("Kernel : core %p signaling termination\n", &this);
229
230                __atomic_store_n(&do_terminate, true, __ATOMIC_RELAXED);
231                wake( &this );
232
233                P( terminated );
234                verify( kernelTLS.this_processor != &this);
235        }
236
237        pthread_join( kernel_thread, 0p );
238        free( this.stack );
239}
240
241void ?{}(cluster & this, const char * name, Duration preemption_rate) with( this ) {
242        this.name = name;
243        this.preemption_rate = preemption_rate;
244        ready_queue{};
245        ready_queue_lock{};
246
247        procs{ __get };
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 thread_desc * nextThread(cluster * this);
262static void runThread(processor * this, thread_desc * dst);
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        doregister(this->cltr, this);
277
278        {
279                // Setup preemption data
280                preemption_scope scope = { this };
281
282                __cfaabi_dbg_print_safe("Kernel : core %p started\n", this);
283
284                thread_desc * readyThread = 0p;
285                for( unsigned int spin_count = 0; ! __atomic_load_n(&this->do_terminate, __ATOMIC_SEQ_CST); spin_count++ ) {
286                        readyThread = nextThread( this->cltr );
287
288                        if(readyThread) {
289                                /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
290                                /* paranoid */ verifyf( readyThread->state == Inactive || readyThread->state == Start || readyThread->preempted != __NO_PREEMPTION, "state : %d, preempted %d\n", readyThread->state, readyThread->preempted);
291                                /* paranoid */ verifyf( readyThread->next == 0p, "Expected null got %p", readyThread->next );
292
293                                runThread(this, readyThread);
294
295                                /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
296
297                                spin_count = 0;
298                        } else {
299                                // spin(this, &spin_count);
300                                // halt(this);
301                        }
302                }
303
304                __cfaabi_dbg_print_safe("Kernel : core %p stopping\n", this);
305        }
306
307        unregister(this->cltr, this);
308
309        V( this->terminated );
310
311        __cfaabi_dbg_print_safe("Kernel : core %p terminated\n", this);
312}
313
314static int * __volatile_errno() __attribute__((noinline));
315static int * __volatile_errno() { asm(""); return &errno; }
316
317// KERNEL ONLY
318// runThread runs a thread by context switching
319// from the processor coroutine to the target thread
320static void runThread(processor * this, thread_desc * thrd_dst) {
321        coroutine_desc * proc_cor = get_coroutine(this->runner);
322
323        // Update global state
324        kernelTLS.this_thread = thrd_dst;
325
326        // set state of processor coroutine to inactive
327        verify(proc_cor->state == Active);
328        proc_cor->state = Inactive;
329
330        // Actually run the thread
331        RUNNING:  while(true) {
332                if(unlikely(thrd_dst->preempted)) {
333                        thrd_dst->preempted = __NO_PREEMPTION;
334                        verify(thrd_dst->state == Active || thrd_dst->state == Rerun);
335                } else {
336                        verify(thrd_dst->state == Start || thrd_dst->state == Primed || thrd_dst->state == Inactive);
337                        thrd_dst->state = Active;
338                }
339
340                /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
341
342                // set context switch to the thread that the processor is executing
343                verify( thrd_dst->context.SP );
344                CtxSwitch( &proc_cor->context, &thrd_dst->context );
345                // when CtxSwitch returns we are back in the processor coroutine
346
347                /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
348
349
350                // We just finished running a thread, there are a few things that could have happened.
351                // 1 - Regular case : the thread has blocked and now one has scheduled it yet.
352                // 2 - Racy case    : the thread has blocked but someone has already tried to schedule it.
353                // 3 - Polite Racy case : the thread has blocked, someone has already tried to schedule it, but the thread is nice and wants to go through the ready-queue any way
354                // 4 - Preempted
355                // In case 1, we may have won a race so we can't write to the state again.
356                // In case 2, we lost the race so we now own the thread.
357                // In case 3, we lost the race but can just reschedule the thread.
358
359                if(unlikely(thrd_dst->preempted != __NO_PREEMPTION)) {
360                        // The thread was preempted, reschedule it and reset the flag
361                        ScheduleThread( thrd_dst );
362                        break RUNNING;
363                }
364
365                // set state of processor coroutine to active and the thread to inactive
366                static_assert(sizeof(thrd_dst->state) == sizeof(int));
367                enum coroutine_state old_state = __atomic_exchange_n(&thrd_dst->state, Inactive, __ATOMIC_SEQ_CST);
368                switch(old_state) {
369                        case Halted:
370                                // The thread has halted, it should never be scheduled/run again, leave it back to Halted and move on
371                                thrd_dst->state = Halted;
372
373                                // We may need to wake someone up here since
374                                unpark( this->destroyer );
375                                this->destroyer = 0p;
376                                break RUNNING;
377                        case Active:
378                                // This is case 1, the regular case, nothing more is needed
379                                break RUNNING;
380                        case Rerun:
381                                // This is case 2, the racy case, someone tried to run this thread before it finished blocking
382                                // In this case, just run it again.
383                                continue RUNNING;
384                        default:
385                                // This makes no sense, something is wrong abort
386                                abort("Finished running a thread that was Inactive/Start/Primed %d\n", old_state);
387                }
388        }
389
390        // Just before returning to the processor, set the processor coroutine to active
391        proc_cor->state = Active;
392}
393
394// KERNEL_ONLY
395void returnToKernel() {
396        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
397        coroutine_desc * proc_cor = get_coroutine(kernelTLS.this_processor->runner);
398        thread_desc * thrd_src = kernelTLS.this_thread;
399
400        // Run the thread on this processor
401        {
402                int local_errno = *__volatile_errno();
403                #if defined( __i386 ) || defined( __x86_64 )
404                        __x87_store;
405                #endif
406                verify( proc_cor->context.SP );
407                CtxSwitch( &thrd_src->context, &proc_cor->context );
408                #if defined( __i386 ) || defined( __x86_64 )
409                        __x87_load;
410                #endif
411                *__volatile_errno() = local_errno;
412        }
413
414        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
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// KERNEL ONLY
546void ScheduleThread( thread_desc * thrd ) with( *thrd->curr_cluster ) {
547        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
548        /* paranoid */ #if defined( __CFA_WITH_VERIFY__ )
549        /* paranoid */ if( thrd->state == Inactive || thrd->state == Start ) assertf( thrd->preempted == __NO_PREEMPTION,
550                          "Error inactive thread marked as preempted, state %d, preemption %d\n", thrd->state, thrd->preempted );
551        /* paranoid */ if( thrd->preempted != __NO_PREEMPTION ) assertf(thrd->state == Active || thrd->state == Rerun,
552                          "Error preempted thread marked as not currently running, state %d, preemption %d\n", thrd->state, thrd->preempted );
553        /* paranoid */ #endif
554        /* paranoid */ verifyf( thrd->next == 0p, "Expected null got %p", thrd->next );
555
556        lock  ( ready_queue_lock __cfaabi_dbg_ctx2 );
557        bool was_empty = !(ready_queue != 0);
558        append( ready_queue, thrd );
559        unlock( ready_queue_lock );
560
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        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
573}
574
575// KERNEL ONLY
576static thread_desc * nextThread(cluster * this) with( *this ) {
577        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
578
579        lock( ready_queue_lock __cfaabi_dbg_ctx2 );
580        thread_desc * head = pop_head( ready_queue );
581        unlock( ready_queue_lock );
582
583        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
584        return head;
585}
586
587void unpark( thread_desc * thrd ) {
588        if( !thrd ) return;
589
590        disable_interrupts();
591        static_assert(sizeof(thrd->state) == sizeof(int));
592        enum coroutine_state old_state = __atomic_exchange_n(&thrd->state, Rerun, __ATOMIC_SEQ_CST);
593        switch(old_state) {
594                case Active:
595                        // Wake won the race, the thread will reschedule/rerun itself
596                        break;
597                case Inactive:
598                        /* paranoid */ verify( ! thrd->preempted != __NO_PREEMPTION );
599
600                        // Wake lost the race,
601                        thrd->state = Inactive;
602                        ScheduleThread( thrd );
603                        break;
604                case Rerun:
605                        abort("More than one thread attempted to schedule thread %p\n", thrd);
606                        break;
607                case Halted:
608                case Start:
609                case Primed:
610                default:
611                        // This makes no sense, something is wrong abort
612                        abort();
613        }
614        enable_interrupts( __cfaabi_dbg_ctx );
615}
616
617void park( void ) {
618        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
619        disable_interrupts();
620        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
621        /* paranoid */ verify( kernelTLS.this_thread->preempted == __NO_PREEMPTION );
622
623        returnToKernel();
624
625        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
626        enable_interrupts( __cfaabi_dbg_ctx );
627        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
628
629}
630
631// KERNEL ONLY
632void __leave_thread() {
633        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
634        returnToKernel();
635        abort();
636}
637
638// KERNEL ONLY
639bool force_yield( __Preemption_Reason reason ) {
640        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
641        disable_interrupts();
642        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
643
644        thread_desc * thrd = kernelTLS.this_thread;
645        /* paranoid */ verify(thrd->state == Active || thrd->state == Rerun);
646
647        // SKULLDUGGERY: It is possible that we are preempting this thread just before
648        // it was going to park itself. If that is the case and it is already using the
649        // intrusive fields then we can't use them to preempt the thread
650        // If that is the case, abandon the preemption.
651        bool preempted = false;
652        if(thrd->next == 0p) {
653                preempted = true;
654                thrd->preempted = reason;
655                returnToKernel();
656        }
657
658        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
659        enable_interrupts_noPoll();
660        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
661
662        return preempted;
663}
664
665//=============================================================================================
666// Kernel Setup logic
667//=============================================================================================
668//-----------------------------------------------------------------------------
669// Kernel boot procedures
670static void kernel_startup(void) {
671        verify( ! kernelTLS.preemption_state.enabled );
672        __cfaabi_dbg_print_safe("Kernel : Starting\n");
673
674        __page_size = sysconf( _SC_PAGESIZE );
675
676        __cfa_dbg_global_clusters.list{ __get };
677        __cfa_dbg_global_clusters.lock{};
678
679        // Initialize the main cluster
680        mainCluster = (cluster *)&storage_mainCluster;
681        (*mainCluster){"Main Cluster"};
682
683        __cfaabi_dbg_print_safe("Kernel : Main cluster ready\n");
684
685        // Start by initializing the main thread
686        // SKULLDUGGERY: the mainThread steals the process main thread
687        // which will then be scheduled by the mainProcessor normally
688        mainThread = (thread_desc *)&storage_mainThread;
689        current_stack_info_t info;
690        info.storage = (__stack_t*)&storage_mainThreadCtx;
691        (*mainThread){ &info };
692
693        __cfaabi_dbg_print_safe("Kernel : Main thread ready\n");
694
695
696
697        // Construct the processor context of the main processor
698        void ?{}(processorCtx_t & this, processor * proc) {
699                (this.__cor){ "Processor" };
700                this.__cor.starter = 0p;
701                this.proc = proc;
702        }
703
704        void ?{}(processor & this) with( this ) {
705                name = "Main Processor";
706                cltr = mainCluster;
707                terminated{ 0 };
708                do_terminate = false;
709                preemption_alarm = 0p;
710                pending_preemption = false;
711                kernel_thread = pthread_self();
712
713                runner{ &this };
714                __cfaabi_dbg_print_safe("Kernel : constructed main processor context %p\n", &runner);
715        }
716
717        // Initialize the main processor and the main processor ctx
718        // (the coroutine that contains the processing control flow)
719        mainProcessor = (processor *)&storage_mainProcessor;
720        (*mainProcessor){};
721
722        //initialize the global state variables
723        kernelTLS.this_processor = mainProcessor;
724        kernelTLS.this_thread    = mainThread;
725
726        // Enable preemption
727        kernel_start_preemption();
728
729        // Add the main thread to the ready queue
730        // once resume is called on mainProcessor->runner the mainThread needs to be scheduled like any normal thread
731        ScheduleThread(mainThread);
732
733        // SKULLDUGGERY: Force a context switch to the main processor to set the main thread's context to the current UNIX
734        // context. Hence, the main thread does not begin through CtxInvokeThread, like all other threads. The trick here is that
735        // mainThread is on the ready queue when this call is made.
736        kernel_first_resume( kernelTLS.this_processor );
737
738
739
740        // THE SYSTEM IS NOW COMPLETELY RUNNING
741        __cfaabi_dbg_print_safe("Kernel : Started\n--------------------------------------------------\n\n");
742
743        verify( ! kernelTLS.preemption_state.enabled );
744        enable_interrupts( __cfaabi_dbg_ctx );
745        verify( TL_GET( preemption_state.enabled ) );
746}
747
748static void kernel_shutdown(void) {
749        __cfaabi_dbg_print_safe("\n--------------------------------------------------\nKernel : Shutting down\n");
750
751        verify( TL_GET( preemption_state.enabled ) );
752        disable_interrupts();
753        verify( ! kernelTLS.preemption_state.enabled );
754
755        // SKULLDUGGERY: Notify the mainProcessor it needs to terminates.
756        // When its coroutine terminates, it return control to the mainThread
757        // which is currently here
758        __atomic_store_n(&mainProcessor->do_terminate, true, __ATOMIC_RELEASE);
759        kernel_last_resume( kernelTLS.this_processor );
760        mainThread->self_cor.state = Halted;
761
762        // THE SYSTEM IS NOW COMPLETELY STOPPED
763
764        // Disable preemption
765        kernel_stop_preemption();
766
767        // Destroy the main processor and its context in reverse order of construction
768        // These were manually constructed so we need manually destroy them
769        ^(mainProcessor->runner){};
770        ^(mainProcessor){};
771
772        // Final step, destroy the main thread since it is no longer needed
773        // Since we provided a stack to this taxk it will not destroy anything
774        ^(mainThread){};
775
776        ^(__cfa_dbg_global_clusters.list){};
777        ^(__cfa_dbg_global_clusters.lock){};
778
779        __cfaabi_dbg_print_safe("Kernel : Shutdown complete\n");
780}
781
782//=============================================================================================
783// Kernel Quiescing
784//=============================================================================================
785static void halt(processor * this) with( *this ) {
786        // verify( ! __atomic_load_n(&do_terminate, __ATOMIC_SEQ_CST) );
787
788        with( *cltr ) {
789                lock      (proc_list_lock __cfaabi_dbg_ctx2);
790                remove    (procs, *this);
791                push_front(idles, *this);
792                unlock    (proc_list_lock);
793        }
794
795        __cfaabi_dbg_print_safe("Kernel : Processor %p ready to sleep\n", this);
796
797        wait( idleLock );
798
799        __cfaabi_dbg_print_safe("Kernel : Processor %p woke up and ready to run\n", this);
800
801        with( *cltr ) {
802                lock      (proc_list_lock __cfaabi_dbg_ctx2);
803                remove    (idles, *this);
804                push_front(procs, *this);
805                unlock    (proc_list_lock);
806        }
807}
808
809//=============================================================================================
810// Unexpected Terminating logic
811//=============================================================================================
812static __spinlock_t kernel_abort_lock;
813static bool kernel_abort_called = false;
814
815void * kernel_abort(void) __attribute__ ((__nothrow__)) {
816        // abort cannot be recursively entered by the same or different processors because all signal handlers return when
817        // the globalAbort flag is true.
818        lock( kernel_abort_lock __cfaabi_dbg_ctx2 );
819
820        // first task to abort ?
821        if ( kernel_abort_called ) {                    // not first task to abort ?
822                unlock( kernel_abort_lock );
823
824                sigset_t mask;
825                sigemptyset( &mask );
826                sigaddset( &mask, SIGALRM );            // block SIGALRM signals
827                sigaddset( &mask, SIGUSR1 );            // block SIGALRM signals
828                sigsuspend( &mask );                            // block the processor to prevent further damage during abort
829                _exit( EXIT_FAILURE );                          // if processor unblocks before it is killed, terminate it
830        }
831        else {
832                kernel_abort_called = true;
833                unlock( kernel_abort_lock );
834        }
835
836        return kernelTLS.this_thread;
837}
838
839void kernel_abort_msg( void * kernel_data, char * abort_text, int abort_text_size ) {
840        thread_desc * thrd = kernel_data;
841
842        if(thrd) {
843                int len = snprintf( abort_text, abort_text_size, "Error occurred while executing thread %.256s (%p)", thrd->self_cor.name, thrd );
844                __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
845
846                if ( &thrd->self_cor != thrd->curr_cor ) {
847                        len = snprintf( abort_text, abort_text_size, " in coroutine %.256s (%p).\n", thrd->curr_cor->name, thrd->curr_cor );
848                        __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
849                }
850                else {
851                        __cfaabi_bits_write( STDERR_FILENO, ".\n", 2 );
852                }
853        }
854        else {
855                int len = snprintf( abort_text, abort_text_size, "Error occurred outside of any thread.\n" );
856                __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
857        }
858}
859
860int kernel_abort_lastframe( void ) __attribute__ ((__nothrow__)) {
861        return get_coroutine(kernelTLS.this_thread) == get_coroutine(mainThread) ? 4 : 2;
862}
863
864static __spinlock_t kernel_debug_lock;
865
866extern "C" {
867        void __cfaabi_bits_acquire() {
868                lock( kernel_debug_lock __cfaabi_dbg_ctx2 );
869        }
870
871        void __cfaabi_bits_release() {
872                unlock( kernel_debug_lock );
873        }
874}
875
876//=============================================================================================
877// Kernel Utilities
878//=============================================================================================
879//-----------------------------------------------------------------------------
880// Locks
881void  ?{}( semaphore & this, int count = 1 ) {
882        (this.lock){};
883        this.count = count;
884        (this.waiting){};
885}
886void ^?{}(semaphore & this) {}
887
888void P(semaphore & this) with( this ){
889        lock( lock __cfaabi_dbg_ctx2 );
890        count -= 1;
891        if ( count < 0 ) {
892                // queue current task
893                append( waiting, kernelTLS.this_thread );
894
895                // atomically release spin lock and block
896                unlock( lock );
897                park();
898        }
899        else {
900            unlock( lock );
901        }
902}
903
904void V(semaphore & this) with( this ) {
905        thread_desc * thrd = 0p;
906        lock( lock __cfaabi_dbg_ctx2 );
907        count += 1;
908        if ( count <= 0 ) {
909                // remove task at head of waiting list
910                thrd = pop_head( waiting );
911        }
912
913        unlock( lock );
914
915        // make new owner
916        unpark( thrd );
917}
918
919//-----------------------------------------------------------------------------
920// Global Queues
921void doregister( cluster     & cltr ) {
922        lock      ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2);
923        push_front( __cfa_dbg_global_clusters.list, cltr );
924        unlock    ( __cfa_dbg_global_clusters.lock );
925}
926
927void unregister( cluster     & cltr ) {
928        lock  ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2);
929        remove( __cfa_dbg_global_clusters.list, cltr );
930        unlock( __cfa_dbg_global_clusters.lock );
931}
932
933void doregister( cluster * cltr, thread_desc & thrd ) {
934        lock      (cltr->thread_list_lock __cfaabi_dbg_ctx2);
935        cltr->nthreads += 1;
936        push_front(cltr->threads, thrd);
937        unlock    (cltr->thread_list_lock);
938}
939
940void unregister( cluster * cltr, thread_desc & thrd ) {
941        lock  (cltr->thread_list_lock __cfaabi_dbg_ctx2);
942        remove(cltr->threads, thrd );
943        cltr->nthreads -= 1;
944        unlock(cltr->thread_list_lock);
945}
946
947void doregister( cluster * cltr, processor * proc ) {
948        lock      (cltr->proc_list_lock __cfaabi_dbg_ctx2);
949        cltr->nprocessors += 1;
950        push_front(cltr->procs, *proc);
951        unlock    (cltr->proc_list_lock);
952}
953
954void unregister( cluster * cltr, processor * proc ) {
955        lock  (cltr->proc_list_lock __cfaabi_dbg_ctx2);
956        remove(cltr->procs, *proc );
957        cltr->nprocessors -= 1;
958        unlock(cltr->proc_list_lock);
959}
960
961//-----------------------------------------------------------------------------
962// Debug
963__cfaabi_dbg_debug_do(
964        extern "C" {
965                void __cfaabi_dbg_record(__spinlock_t & this, const char * prev_name) {
966                        this.prev_name = prev_name;
967                        this.prev_thrd = kernelTLS.this_thread;
968                }
969        }
970)
971
972//-----------------------------------------------------------------------------
973// Debug
974bool threading_enabled(void) {
975        return true;
976}
977// Local Variables: //
978// mode: c //
979// tab-width: 4 //
980// End: //
Note: See TracBrowser for help on using the repository browser.