source: libcfa/src/concurrency/kernel.cfa @ 16a6a617

arm-ehcleanup-dtorsjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-expr
Last change on this file since 16a6a617 was 212c2187, checked in by tdelisle <tdelisle@…>, 3 years ago

Removed kernelTLS.this_coroutine which was redundant and some preleminary work for breaking into 2 step the context-switch

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