source: src/libcfa/concurrency/kernel.c @ 639991a

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 639991a was 639991a, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

removed workaround for tuple references

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