source: src/libcfa/concurrency/kernel.c @ ade5272

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumwith_gc
Last change on this file since ade5272 was de94a60, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

some more work on kernel doubly linked lists and fixed segfault in abort message

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