source: libcfa/src/concurrency/kernel.cfa @ 30763fd

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

Merge branch 'master' into relaxed_ready

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