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

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

Improved assertions on halting/waking processors

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