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

aaron-thesisarm-ehcleanup-dtorsdeferred_resndemanglerjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerwith_gc
Last change on this file since ea8b2f7 was ea8b2f7, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Immetidate fix for halting processors, drifting still an issue

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