source: libcfa/src/concurrency/kernel.cfa @ 69a61d2

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

coroutine and thread no longer store stack size

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