source: libcfa/src/concurrency/kernel.cfa @ deca0f5

arm-ehcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since deca0f5 was deca0f5, checked in by tdelisle <tdelisle@…>, 4 years ago

x87 and SSE flags are now only saved by threads

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