source: libcfa/src/concurrency/kernel.cfa @ 16a6a617

ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 16a6a617 was 212c2187, checked in by tdelisle <tdelisle@…>, 5 years ago

Removed kernelTLS.this_coroutine which was redundant and some preleminary work for breaking into 2 step the context-switch

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