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

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since ff79d5e was ff79d5e, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Fixed park unpark to support park as first step of main()
Fixes #170?

  • Property mode set to 100644
File size: 35.8 KB
RevLine 
[8118303]1//
2// Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// kernel.c --
8//
9// Author           : Thierry Delisle
[75f3522]10// Created On       : Tue Jan 17 12:27:26 2017
[6b0b624]11// Last Modified By : Peter A. Buhr
[ada0246d]12// Last Modified On : Tue May 26 22:05:19 2020
13// Update Count     : 59
[8118303]14//
15
[2026bb6]16#define __cforall_thread__
[4069faad]17// #define __CFA_DEBUG_PRINT_RUNTIME_CORE__
[2026bb6]18
[8118303]19//C Includes
[c84e80a]20#include <stddef.h>
[214e8da]21#include <errno.h>
[ea8b2f7]22#include <string.h>
[9d944b2]23#include <stdio.h>
[8fcbb4c]24#include <fenv.h>
[58b6d1b]25#include <signal.h>
[9d944b2]26#include <unistd.h>
[27f5f71]27#include <limits.h>                                                                             // PTHREAD_STACK_MIN
[1a3040c]28#include <sys/mman.h>                                                                   // mprotect
[ada0246d]29extern "C" {
30#include <sys/resource.h>
[eb2e723]31}
[8118303]32
33//CFA Includes
[58b6d1b]34#include "time.hfa"
[73abe95]35#include "kernel_private.hfa"
36#include "preemption.hfa"
37#include "startup.hfa"
[8118303]38
39//Private includes
40#define __CFA_INVOKE_PRIVATE__
41#include "invoke.h"
42
[4069faad]43
[deca0f5]44//-----------------------------------------------------------------------------
45// Some assembly required
[1805b1b]46#if defined( __i386 )
[deca0f5]47        #define CtxGet( ctx )        \
48                __asm__ volatile (     \
49                        "movl %%esp,%0\n"\
50                        "movl %%ebp,%1\n"\
51                        : "=rm" (ctx.SP),\
52                                "=rm" (ctx.FP) \
53                )
54
55        // mxcr : SSE Status and Control bits (control bits are preserved across function calls)
56        // fcw  : X87 FPU control word (preserved across function calls)
57        #define __x87_store         \
58                uint32_t __mxcr;      \
59                uint16_t __fcw;       \
60                __asm__ volatile (    \
61                        "stmxcsr %0\n"  \
62                        "fnstcw  %1\n"  \
63                        : "=m" (__mxcr),\
64                                "=m" (__fcw)  \
65                )
66
67        #define __x87_load         \
68                __asm__ volatile (   \
69                        "fldcw  %1\n"  \
70                        "ldmxcsr %0\n" \
71                        ::"m" (__mxcr),\
72                                "m" (__fcw)  \
73                )
74
75#elif defined( __x86_64 )
76        #define CtxGet( ctx )        \
77                __asm__ volatile (     \
78                        "movq %%rsp,%0\n"\
79                        "movq %%rbp,%1\n"\
80                        : "=rm" (ctx.SP),\
81                                "=rm" (ctx.FP) \
82                )
83
84        #define __x87_store         \
85                uint32_t __mxcr;      \
86                uint16_t __fcw;       \
87                __asm__ volatile (    \
88                        "stmxcsr %0\n"  \
89                        "fnstcw  %1\n"  \
90                        : "=m" (__mxcr),\
91                                "=m" (__fcw)  \
92                )
93
94        #define __x87_load          \
95                __asm__ volatile (    \
96                        "fldcw  %1\n"   \
97                        "ldmxcsr %0\n"  \
98                        :: "m" (__mxcr),\
99                                "m" (__fcw)  \
100                )
101
102
103#elif defined( __ARM_ARCH )
104#define CtxGet( ctx ) __asm__ ( \
105                "mov %0,%%sp\n"   \
106                "mov %1,%%r11\n"   \
107        : "=rm" (ctx.SP), "=rm" (ctx.FP) )
108#else
109        #error unknown hardware architecture
110#endif
111
112//-----------------------------------------------------------------------------
[2ac095d]113//Start and stop routine for the kernel, declared first to make sure they run first
[8c50aed]114static void __kernel_startup (void) __attribute__(( constructor( STARTUP_PRIORITY_KERNEL ) ));
115static void __kernel_shutdown(void) __attribute__(( destructor ( STARTUP_PRIORITY_KERNEL ) ));
[2ac095d]116
[92e7631]117//-----------------------------------------------------------------------------
118// Kernel Scheduling logic
119static $thread * __next_thread(cluster * this);
120static void __run_thread(processor * this, $thread * dst);
121static $thread * __halt(processor * this);
[504a7dc]122static bool __wake_one(cluster * cltr);
[92e7631]123static bool __wake_proc(processor *);
[2ac095d]124
[8def349]125//-----------------------------------------------------------------------------
126// Kernel storage
[b388ee81]127KERNEL_STORAGE(cluster,              mainCluster);
128KERNEL_STORAGE(processor,            mainProcessor);
129KERNEL_STORAGE($thread,              mainThread);
130KERNEL_STORAGE(__stack_t,            mainThreadCtx);
131KERNEL_STORAGE(__scheduler_RWLock_t, __scheduler_lock);
[8def349]132
[b388ee81]133cluster              * mainCluster;
134processor            * mainProcessor;
135$thread              * mainThread;
136__scheduler_RWLock_t * __scheduler_lock;
[eb2e723]137
[ea8b2f7]138extern "C" {
[1805b1b]139        struct { __dllist_t(cluster) list; __spinlock_t lock; } __cfa_dbg_global_clusters;
[ea8b2f7]140}
[de94a60]141
[b2f6113]142size_t __page_size = 0;
143
[bd98b58]144//-----------------------------------------------------------------------------
145// Global state
[afc2427]146thread_local struct KernelThreadData kernelTLS __attribute__ ((tls_model ( "initial-exec" ))) = {
[1805b1b]147        NULL,                                                                                           // cannot use 0p
[b10affd]148        NULL,
[21184e3]149        { 1, false, false },
150        6u //this should be seeded better but due to a bug calling rdtsc doesn't work
[b10affd]151};
[c84e80a]152
153//-----------------------------------------------------------------------------
[de6319f]154// Struct to steal stack
[8def349]155struct current_stack_info_t {
[1805b1b]156        __stack_t * storage;                                                            // pointer to stack object
157        void * base;                                                                            // base of stack
158        void * limit;                                                                           // stack grows towards stack limit
159        void * context;                                                                         // address of cfa_context_t
[c84e80a]160};
161
[242a902]162void ?{}( current_stack_info_t & this ) {
[b2f6113]163        __stack_context_t ctx;
164        CtxGet( ctx );
165        this.base = ctx.FP;
[8def349]166
167        rlimit r;
[132fad4]168        getrlimit( RLIMIT_STACK, &r);
[69a61d2]169        size_t size = r.rlim_cur;
[8def349]170
[69a61d2]171        this.limit = (void *)(((intptr_t)this.base) - size);
[9236060]172        this.context = &storage_mainThreadCtx;
[8def349]173}
174
[de6319f]175//-----------------------------------------------------------------------------
176// Main thread construction
[8def349]177
[ac2b598]178void ?{}( $coroutine & this, current_stack_info_t * info) with( this ) {
[b2f6113]179        stack.storage = info->storage;
180        with(*stack.storage) {
181                limit     = info->limit;
182                base      = info->base;
183        }
[ffe2fad]184        __attribute__((may_alias)) intptr_t * istorage = (intptr_t*) &stack.storage;
185        *istorage |= 0x1;
[65deb18]186        name = "Main Thread";
187        state = Start;
[1805b1b]188        starter = 0p;
189        last = 0p;
190        cancellation = 0p;
[8def349]191}
192
[ac2b598]193void ?{}( $thread & this, current_stack_info_t * info) with( this ) {
[ff79d5e]194        ticket = 1;
[e8e457e]195        state = Start;
[65deb18]196        self_cor{ info };
[82c948c]197        curr_cor = &self_cor;
[de6319f]198        curr_cluster = mainCluster;
[82c948c]199        self_mon.owner = &this;
200        self_mon.recursion = 1;
201        self_mon_p = &self_mon;
[b798713]202        link.next = 0p;
203        link.prev = 0p;
[de94a60]204
[1805b1b]205        node.next = 0p;
206        node.prev = 0p;
[a1a17a74]207        doregister(curr_cluster, this);
[82c948c]208
209        monitors{ &self_mon_p, 1, (fptr_t)0 };
[8def349]210}
[c84e80a]211
[8def349]212//-----------------------------------------------------------------------------
213// Processor coroutine
[de6319f]214void ?{}(processorCtx_t & this) {
[39fea2f]215
[8def349]216}
217
[39fea2f]218// Construct the processor context of non-main processors
[c29c342]219static void ?{}(processorCtx_t & this, processor * proc, current_stack_info_t * info) {
[242a902]220        (this.__cor){ info };
221        this.proc = proc;
[8def349]222}
223
[c7a900a]224static void * __invoke_processor(void * arg);
[8c50aed]225
[e3fea42]226void ?{}(processor & this, const char name[], cluster & cltr) with( this ) {
[de6319f]227        this.name = name;
228        this.cltr = &cltr;
[7768b8d]229        id = -1u;
[c40e7c5]230        terminated{ 0 };
[b0c7419]231        destroyer = 0p;
[c40e7c5]232        do_terminate = false;
[1805b1b]233        preemption_alarm = 0p;
[c40e7c5]234        pending_preemption = false;
[094476d]235        runner.proc = &this;
[8def349]236
[92e7631]237        idle{};
[6b4cdd3]238
[4069faad]239        __cfadbg_print_safe(runtime_core, "Kernel : Starting core %p\n", &this);
[8c50aed]240
[c7a900a]241        this.stack = __create_pthread( &this.kernel_thread, __invoke_processor, (void *)&this );
[8c50aed]242
[4069faad]243        __cfadbg_print_safe(runtime_core, "Kernel : core %p created\n", &this);
[c84e80a]244}
245
[65deb18]246void ^?{}(processor & this) with( this ){
[ea8b2f7]247        if( ! __atomic_load_n(&do_terminate, __ATOMIC_ACQUIRE) ) {
[4069faad]248                __cfadbg_print_safe(runtime_core, "Kernel : core %p signaling termination\n", &this);
[85b1deb]249
250                __atomic_store_n(&do_terminate, true, __ATOMIC_RELAXED);
[92e7631]251                __wake_proc( &this );
[85b1deb]252
[65deb18]253                P( terminated );
[14a61b5]254                verify( kernelTLS.this_processor != &this);
[8def349]255        }
[6b4cdd3]256
[c66f6cb]257        int err = pthread_join( kernel_thread, 0p );
258        if( err != 0 ) abort("KERNEL ERROR: joining processor %p caused error %s\n", &this, strerror(err));
259
[27f5f71]260        free( this.stack );
[8def349]261}
262
[dd4e2d7]263void ?{}(cluster & this, const char name[], Duration preemption_rate, unsigned io_flags) with( this ) {
[de6319f]264        this.name = name;
265        this.preemption_rate = preemption_rate;
[65deb18]266        ready_queue{};
[de94a60]267
[038be32]268        #if !defined(__CFA_NO_STATISTICS__)
269                print_stats = false;
270        #endif
271
[de94a60]272        procs{ __get };
273        idles{ __get };
[a1a17a74]274        threads{ __get };
[de94a60]275
[b6f2b21]276        __kernel_io_startup( this, io_flags, &this == mainCluster );
[92976d9]277
[de94a60]278        doregister(this);
[8def349]279}
280
[242a902]281void ^?{}(cluster & this) {
[f6660520]282        __kernel_io_shutdown( this, &this == mainCluster );
[92976d9]283
[de94a60]284        unregister(this);
[c84e80a]285}
286
[75f3522]287//=============================================================================================
288// Kernel Scheduling logic
289//=============================================================================================
[8fcbb4c]290//Main of the processor contexts
[83a071f9]291void main(processorCtx_t & runner) {
[21184e3]292        // Because of a bug, we couldn't initialized the seed on construction
293        // Do it here
[7768b8d]294        kernelTLS.rand_seed ^= rdtscl();
[21184e3]295
[83a071f9]296        processor * this = runner.proc;
[094476d]297        verify(this);
[c81ebf9]298
[4069faad]299        __cfadbg_print_safe(runtime_core, "Kernel : core %p starting\n", this);
[8118303]300
[7768b8d]301        // register the processor unless it's the main thread which is handled in the boot sequence
[b798713]302        if(this != mainProcessor) {
[9b1dcc2]303                this->id = doregister((__processor_id_t*)this);
[b798713]304                ready_queue_grow( this->cltr );
305        }
306
[504a7dc]307        doregister(this->cltr, this);
[de94a60]308
[75f3522]309        {
[c81ebf9]310                // Setup preemption data
311                preemption_scope scope = { this };
312
[4069faad]313                __cfadbg_print_safe(runtime_core, "Kernel : core %p started\n", this);
[8118303]314
[ac2b598]315                $thread * readyThread = 0p;
[1a3040c]316                for( unsigned int spin_count = 0; ! __atomic_load_n(&this->do_terminate, __ATOMIC_SEQ_CST); spin_count++ ) {
[92e7631]317                        // Try to get the next thread
[8c50aed]318                        readyThread = __next_thread( this->cltr );
[75f3522]319
[92e7631]320                        // If no ready thread
321                        if( readyThread == 0p ) {
322                                // Block until a thread is ready
323                                readyThread = __halt(this);
324                        }
[75f3522]325
[92e7631]326                        // Check if we actually found a thread
327                        if( readyThread ) {
[3381ed7]328                                /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[92e7631]329                                /* paranoid */ verifyf( readyThread->state == Ready || readyThread->preempted != __NO_PREEMPTION, "state : %d, preempted %d\n", readyThread->state, readyThread->preempted);
[504a7dc]330                                /* paranoid */ verifyf( readyThread->link.next == 0p, "Expected null got %p", readyThread->link.next );
[4e6fb8e]331
[92e7631]332                                // We found a thread run it
[8c50aed]333                                __run_thread(this, readyThread);
[c81ebf9]334
[3381ed7]335                                /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[c81ebf9]336                        }
337                }
338
[4069faad]339                __cfadbg_print_safe(runtime_core, "Kernel : core %p stopping\n", this);
[c84e80a]340        }
[8118303]341
[504a7dc]342        unregister(this->cltr, this);
343
[4cedd9f]344        V( this->terminated );
[bdeba0b]345
[7768b8d]346        // unregister the processor unless it's the main thread which is handled in the boot sequence
[b798713]347        if(this != mainProcessor) {
348                ready_queue_shrink( this->cltr );
[9b1dcc2]349                unregister((__processor_id_t*)this);
[b798713]350        }
[6a490b2]351        else {
352                // HACK : the coroutine context switch expects this_thread to be set
353                // and it make sense for it to be set in all other cases except here
354                // fake it
355                kernelTLS.this_thread = mainThread;
356        }
[7768b8d]357
[4069faad]358        __cfadbg_print_safe(runtime_core, "Kernel : core %p terminated\n", this);
[b798713]359
360        stats_tls_tally(this->cltr);
[c84e80a]361}
362
[5c1a531]363static int * __volatile_errno() __attribute__((noinline));
364static int * __volatile_errno() { asm(""); return &errno; }
365
[14a61b5]366// KERNEL ONLY
[1c273d0]367// runThread runs a thread by context switching
368// from the processor coroutine to the target thread
[ac2b598]369static void __run_thread(processor * this, $thread * thrd_dst) {
370        $coroutine * proc_cor = get_coroutine(this->runner);
[8fcbb4c]371
[14a61b5]372        // Update global state
[e8e457e]373        kernelTLS.this_thread = thrd_dst;
374
[9f575ea]375        // set state of processor coroutine to inactive
376        verify(proc_cor->state == Active);
[ae7be7a]377        proc_cor->state = Blocked;
[e8e457e]378
[9f575ea]379        // Actually run the thread
[3381ed7]380        RUNNING:  while(true) {
[ff79d5e]381                thrd_dst->preempted = __NO_PREEMPTION;
382                thrd_dst->state = Active;
[e8e457e]383
[ae66348]384                __cfaabi_dbg_debug_do(
[276ae57e]385                        thrd_dst->park_stale   = true;
386                        thrd_dst->unpark_stale = true;
[ae66348]387                )
[75f3522]388
[3381ed7]389                /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[a7b486b]390                /* paranoid */ verify( kernelTLS.this_thread == thrd_dst );
[210b8b3]391                /* paranoid */ verifyf( ((uintptr_t)thrd_dst->context.SP) < ((uintptr_t)__get_stack(thrd_dst->curr_cor)->base ) || thrd_dst->curr_cor == proc_cor, "ERROR : Destination $thread %p has been corrupted.\n StackPointer too small.\n", thrd_dst ); // add escape condition if we are setting up the processor
392                /* paranoid */ verifyf( ((uintptr_t)thrd_dst->context.SP) > ((uintptr_t)__get_stack(thrd_dst->curr_cor)->limit) || thrd_dst->curr_cor == proc_cor, "ERROR : Destination $thread %p has been corrupted.\n StackPointer too large.\n", thrd_dst ); // add escape condition if we are setting up the processor
[3381ed7]393
[9f575ea]394                // set context switch to the thread that the processor is executing
395                verify( thrd_dst->context.SP );
[c7a900a]396                __cfactx_switch( &proc_cor->context, &thrd_dst->context );
397                // when __cfactx_switch returns we are back in the processor coroutine
[9f575ea]398
[210b8b3]399                /* paranoid */ verifyf( ((uintptr_t)thrd_dst->context.SP) > ((uintptr_t)__get_stack(thrd_dst->curr_cor)->limit), "ERROR : Destination $thread %p has been corrupted.\n StackPointer too large.\n", thrd_dst );
400                /* paranoid */ verifyf( ((uintptr_t)thrd_dst->context.SP) < ((uintptr_t)__get_stack(thrd_dst->curr_cor)->base ), "ERROR : Destination $thread %p has been corrupted.\n StackPointer too small.\n", thrd_dst );
[a7b486b]401                /* paranoid */ verify( kernelTLS.this_thread == thrd_dst );
[3381ed7]402                /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[75f3522]403
[3381ed7]404
405                // We just finished running a thread, there are a few things that could have happened.
406                // 1 - Regular case : the thread has blocked and now one has scheduled it yet.
407                // 2 - Racy case    : the thread has blocked but someone has already tried to schedule it.
408                // 4 - Preempted
409                // In case 1, we may have won a race so we can't write to the state again.
410                // In case 2, we lost the race so we now own the thread.
411
412                if(unlikely(thrd_dst->preempted != __NO_PREEMPTION)) {
413                        // The thread was preempted, reschedule it and reset the flag
[9b1dcc2]414                        __schedule_thread( (__processor_id_t*)this, thrd_dst );
[3381ed7]415                        break RUNNING;
416                }
[75f3522]417
[ff79d5e]418                if(unlikely(thrd_dst->state == Halted)) {
419                        // The thread has halted, it should never be scheduled/run again
420                        // We may need to wake someone up here since
421                        unpark( this->destroyer __cfaabi_dbg_ctx2 );
422                        this->destroyer = 0p;
423                        break RUNNING;
424                }
425
426                /* paranoid */ verify( thrd_dst->state == Active );
427                thrd_dst->state = Blocked;
428
[3381ed7]429                // set state of processor coroutine to active and the thread to inactive
[ff79d5e]430                int old_ticket = __atomic_fetch_sub(&thrd_dst->ticket, 1, __ATOMIC_SEQ_CST);
431                __cfaabi_dbg_debug_do( thrd_dst->park_result = old_ticket; )
432                switch(old_ticket) {
433                        case 1:
[3381ed7]434                                // This is case 1, the regular case, nothing more is needed
435                                break RUNNING;
[ff79d5e]436                        case 2:
[3381ed7]437                                // This is case 2, the racy case, someone tried to run this thread before it finished blocking
438                                // In this case, just run it again.
439                                continue RUNNING;
440                        default:
441                                // This makes no sense, something is wrong abort
[ff79d5e]442                                abort();
[3381ed7]443                }
[9f575ea]444        }
[e8e457e]445
[9f575ea]446        // Just before returning to the processor, set the processor coroutine to active
[e8e457e]447        proc_cor->state = Active;
[ae7be7a]448        kernelTLS.this_thread = 0p;
[82c948c]449}
450
[14a61b5]451// KERNEL_ONLY
[b0c7419]452void returnToKernel() {
[3381ed7]453        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[ac2b598]454        $coroutine * proc_cor = get_coroutine(kernelTLS.this_processor->runner);
455        $thread * thrd_src = kernelTLS.this_thread;
[e8e457e]456
[9f575ea]457        // Run the thread on this processor
458        {
459                int local_errno = *__volatile_errno();
460                #if defined( __i386 ) || defined( __x86_64 )
461                        __x87_store;
462                #endif
463                verify( proc_cor->context.SP );
[c7a900a]464                __cfactx_switch( &thrd_src->context, &proc_cor->context );
[9f575ea]465                #if defined( __i386 ) || defined( __x86_64 )
466                        __x87_load;
467                #endif
468                *__volatile_errno() = local_errno;
[8fcbb4c]469        }
[deca0f5]470
[3381ed7]471        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[210b8b3]472        /* paranoid */ verifyf( ((uintptr_t)thrd_src->context.SP) < ((uintptr_t)__get_stack(thrd_src->curr_cor)->base ), "ERROR : Returning $thread %p has been corrupted.\n StackPointer too small.\n", thrd_src );
473        /* paranoid */ verifyf( ((uintptr_t)thrd_src->context.SP) > ((uintptr_t)__get_stack(thrd_src->curr_cor)->limit), "ERROR : Returning $thread %p has been corrupted.\n StackPointer too large.\n", thrd_src );
[c84e80a]474}
475
[14a61b5]476// KERNEL_ONLY
[0c92c9f]477// Context invoker for processors
478// This is the entry point for processors (kernel threads)
479// It effectively constructs a coroutine by stealing the pthread stack
[c7a900a]480static void * __invoke_processor(void * arg) {
[8def349]481        processor * proc = (processor *) arg;
[14a61b5]482        kernelTLS.this_processor = proc;
[1805b1b]483        kernelTLS.this_thread    = 0p;
[14a61b5]484        kernelTLS.preemption_state.[enabled, disable_count] = [false, 1];
[8def349]485        // SKULLDUGGERY: We want to create a context for the processor coroutine
486        // which is needed for the 2-step context switch. However, there is no reason
[1c273d0]487        // to waste the perfectly valid stack create by pthread.
[8def349]488        current_stack_info_t info;
[b2f6113]489        __stack_t ctx;
490        info.storage = &ctx;
[094476d]491        (proc->runner){ proc, &info };
[8def349]492
[b2f6113]493        __cfaabi_dbg_print_safe("Coroutine : created stack %p\n", get_coroutine(proc->runner)->stack.storage);
[8fcbb4c]494
[0c92c9f]495        //Set global state
[1805b1b]496        kernelTLS.this_thread = 0p;
[8def349]497
498        //We now have a proper context from which to schedule threads
[4069faad]499        __cfadbg_print_safe(runtime_core, "Kernel : core %p created (%p, %p)\n", proc, &proc->runner, &ctx);
[8def349]500
[1c273d0]501        // SKULLDUGGERY: Since the coroutine doesn't have its own stack, we can't
502        // resume it to start it like it normally would, it will just context switch
503        // back to here. Instead directly call the main since we already are on the
[8def349]504        // appropriate stack.
[094476d]505        get_coroutine(proc->runner)->state = Active;
506        main( proc->runner );
507        get_coroutine(proc->runner)->state = Halted;
[8def349]508
[0c92c9f]509        // Main routine of the core returned, the core is now fully terminated
[4069faad]510        __cfadbg_print_safe(runtime_core, "Kernel : core %p main ended (%p)\n", proc, &proc->runner);
[8def349]511
[1805b1b]512        return 0p;
[c84e80a]513}
514
[e3fea42]515static void Abort( int ret, const char func[] ) {
[1a3040c]516        if ( ret ) {                                                                            // pthread routines return errno values
[1805b1b]517                abort( "%s : internal error, error(%d) %s.", func, ret, strerror( ret ) );
[27f5f71]518        } // if
[1805b1b]519} // Abort
520
[8c50aed]521void * __create_pthread( pthread_t * pthread, void * (*start)(void *), void * arg ) {
[1805b1b]522        pthread_attr_t attr;
523
524        Abort( pthread_attr_init( &attr ), "pthread_attr_init" ); // initialize attribute
525
[27f5f71]526        size_t stacksize;
[09d4b22]527        // default stack size, normally defined by shell limit
[1a3040c]528        Abort( pthread_attr_getstacksize( &attr, &stacksize ), "pthread_attr_getstacksize" );
[27f5f71]529        assert( stacksize >= PTHREAD_STACK_MIN );
[1a3040c]530
[09d4b22]531        void * stack;
532        __cfaabi_dbg_debug_do(
533                stack = memalign( __page_size, stacksize + __page_size );
534                // pthread has no mechanism to create the guard page in user supplied stack.
535                if ( mprotect( stack, __page_size, PROT_NONE ) == -1 ) {
536                        abort( "mprotect : internal error, mprotect failure, error(%d) %s.", errno, strerror( errno ) );
537                } // if
538        );
539        __cfaabi_dbg_no_debug_do(
540                stack = malloc( stacksize );
541        );
[1a3040c]542
[f80f840]543        Abort( pthread_attr_setstack( &attr, stack, stacksize ), "pthread_attr_setstack" );
[27f5f71]544
[1805b1b]545        Abort( pthread_create( pthread, &attr, start, arg ), "pthread_create" );
546        return stack;
[c84e80a]547}
548
[14a61b5]549// KERNEL_ONLY
[8c50aed]550static void __kernel_first_resume( processor * this ) {
[ac2b598]551        $thread * src = mainThread;
552        $coroutine * dst = get_coroutine(this->runner);
[b69ea6b]553
[14a61b5]554        verify( ! kernelTLS.preemption_state.enabled );
[b69ea6b]555
[09f357ec]556        kernelTLS.this_thread->curr_cor = dst;
[b2f6113]557        __stack_prepare( &dst->stack, 65000 );
[c7a900a]558        __cfactx_start(main, dst, this->runner, __cfactx_invoke_coroutine);
[b69ea6b]559
[14a61b5]560        verify( ! kernelTLS.preemption_state.enabled );
[b69ea6b]561
[e8e457e]562        dst->last = &src->self_cor;
563        dst->starter = dst->starter ? dst->starter : &src->self_cor;
[b69ea6b]564
[92e7631]565        // make sure the current state is still correct
566        /* paranoid */ verify(src->state == Ready);
[b69ea6b]567
568        // context switch to specified coroutine
[69a61d2]569        verify( dst->context.SP );
[c7a900a]570        __cfactx_switch( &src->context, &dst->context );
571        // when __cfactx_switch returns we are back in the src coroutine
[b69ea6b]572
[09f357ec]573        mainThread->curr_cor = &mainThread->self_cor;
574
[92e7631]575        // make sure the current state has been update
576        /* paranoid */ verify(src->state == Active);
[b69ea6b]577
[14a61b5]578        verify( ! kernelTLS.preemption_state.enabled );
[b69ea6b]579}
580
[e8e457e]581// KERNEL_ONLY
[8c50aed]582static void __kernel_last_resume( processor * this ) {
[ac2b598]583        $coroutine * src = &mainThread->self_cor;
584        $coroutine * dst = get_coroutine(this->runner);
[e8e457e]585
586        verify( ! kernelTLS.preemption_state.enabled );
587        verify( dst->starter == src );
588        verify( dst->context.SP );
589
[f586539]590        // SKULLDUGGERY in debug the processors check that the
591        // stack is still within the limit of the stack limits after running a thread.
592        // that check doesn't make sense if we context switch to the processor using the
593        // coroutine semantics. Since this is a special case, use the current context
594        // info to populate these fields.
595        __cfaabi_dbg_debug_do(
596                __stack_context_t ctx;
597                CtxGet( ctx );
598                mainThread->context.SP = ctx.SP;
599                mainThread->context.FP = ctx.FP;
600        )
601
[e8e457e]602        // context switch to the processor
[c7a900a]603        __cfactx_switch( &src->context, &dst->context );
[e8e457e]604}
605
[8def349]606//-----------------------------------------------------------------------------
607// Scheduler routines
[14a61b5]608// KERNEL ONLY
[9b1dcc2]609void __schedule_thread( struct __processor_id_t * id, $thread * thrd ) {
[6a490b2]610        /* paranoid */ verify( thrd );
611        /* paranoid */ verify( thrd->state != Halted );
[9f575ea]612        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[3381ed7]613        /* paranoid */ #if defined( __CFA_WITH_VERIFY__ )
[504a7dc]614        /* paranoid */  if( thrd->state == Blocked || thrd->state == Start ) assertf( thrd->preempted == __NO_PREEMPTION,
615                                        "Error inactive thread marked as preempted, state %d, preemption %d\n", thrd->state, thrd->preempted );
[ff79d5e]616        /* paranoid */  if( thrd->preempted != __NO_PREEMPTION ) assertf(thrd->state == Active,
[504a7dc]617                                        "Error preempted thread marked as not currently running, state %d, preemption %d\n", thrd->state, thrd->preempted );
[3381ed7]618        /* paranoid */ #endif
[6a490b2]619        /* paranoid */ verifyf( thrd->link.next == 0p, "Expected null got %p", thrd->link.next );
[9f575ea]620
[ae7be7a]621        if (thrd->preempted == __NO_PREEMPTION) thrd->state = Ready;
[6b4cdd3]622
[9b1dcc2]623        ready_schedule_lock  ( id );
[504a7dc]624                push( thrd->curr_cluster, thrd );
[b798713]625
[504a7dc]626                __wake_one(thrd->curr_cluster);
[9b1dcc2]627        ready_schedule_unlock( id );
[1c273d0]628
[9f575ea]629        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[db6f06a]630}
631
[14a61b5]632// KERNEL ONLY
[ac2b598]633static $thread * __next_thread(cluster * this) with( *this ) {
[3381ed7]634        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[7768b8d]635
[9b1dcc2]636        ready_schedule_lock  ( (__processor_id_t*)kernelTLS.this_processor );
[6a490b2]637                $thread * head = pop( this );
[9b1dcc2]638        ready_schedule_unlock( (__processor_id_t*)kernelTLS.this_processor );
[7768b8d]639
[3381ed7]640        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[db6f06a]641        return head;
[eb2e723]642}
643
[2d8f7b0]644// KERNEL ONLY unpark with out disabling interrupts
[9b1dcc2]645void __unpark(  struct __processor_id_t * id, $thread * thrd __cfaabi_dbg_ctx_param2 ) {
[ae66348]646        // record activity
[d47349b]647        __cfaabi_dbg_debug_do( char * old_caller = thrd->unpark_caller; )
[ae66348]648        __cfaabi_dbg_record_thrd( *thrd, false, caller );
649
[ff79d5e]650        int old_ticket = __atomic_fetch_add(&thrd->ticket, 1, __ATOMIC_SEQ_CST);
651        __cfaabi_dbg_debug_do( thrd->unpark_result = old_ticket; thrd->unpark_state = thrd->state; )
652        switch(old_ticket) {
653                case 1:
[3381ed7]654                        // Wake won the race, the thread will reschedule/rerun itself
655                        break;
[ff79d5e]656                case 0:
[3381ed7]657                        /* paranoid */ verify( ! thrd->preempted != __NO_PREEMPTION );
[ff79d5e]658                        /* paranoid */ verify( thrd->state == Blocked );
[0b33412]659
[3381ed7]660                        // Wake lost the race,
[9b1dcc2]661                        __schedule_thread( id, thrd );
[3381ed7]662                        break;
663                default:
664                        // This makes no sense, something is wrong abort
665                        abort();
[de6319f]666        }
[db6f06a]667}
668
[2d8f7b0]669void unpark( $thread * thrd __cfaabi_dbg_ctx_param2 ) {
670        if( !thrd ) return;
[db6f06a]671
[82ff5845]672        disable_interrupts();
[9b1dcc2]673        __unpark( (__processor_id_t*)kernelTLS.this_processor, thrd __cfaabi_dbg_ctx_fwd2 );
[36982fc]674        enable_interrupts( __cfaabi_dbg_ctx );
[eb2e723]675}
676
[ae66348]677void park( __cfaabi_dbg_ctx_param ) {
[3381ed7]678        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
[82ff5845]679        disable_interrupts();
[3381ed7]680        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
681        /* paranoid */ verify( kernelTLS.this_thread->preempted == __NO_PREEMPTION );
[0b33412]682
[ae66348]683        // record activity
684        __cfaabi_dbg_record_thrd( *kernelTLS.this_thread, true, caller );
[0b33412]685
[82c948c]686        returnToKernel();
[0b33412]687
[3381ed7]688        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[36982fc]689        enable_interrupts( __cfaabi_dbg_ctx );
[3381ed7]690        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
[0c78741]691
692}
[09800e9]693
[3381ed7]694// KERNEL ONLY
[b0c7419]695void __leave_thread() {
[3381ed7]696        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[09800e9]697        returnToKernel();
[b0c7419]698        abort();
[09800e9]699}
700
[14a61b5]701// KERNEL ONLY
[3381ed7]702bool force_yield( __Preemption_Reason reason ) {
703        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
[09800e9]704        disable_interrupts();
[3381ed7]705        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[09800e9]706
[ac2b598]707        $thread * thrd = kernelTLS.this_thread;
[ff79d5e]708        /* paranoid */ verify(thrd->state == Active);
[3381ed7]709
710        // SKULLDUGGERY: It is possible that we are preempting this thread just before
711        // it was going to park itself. If that is the case and it is already using the
712        // intrusive fields then we can't use them to preempt the thread
713        // If that is the case, abandon the preemption.
714        bool preempted = false;
[504a7dc]715        if(thrd->link.next == 0p) {
[3381ed7]716                preempted = true;
717                thrd->preempted = reason;
718                returnToKernel();
[de6319f]719        }
[f2b12406]720
[3381ed7]721        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
722        enable_interrupts_noPoll();
723        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
[f2b12406]724
[3381ed7]725        return preempted;
[f2b12406]726}
727
[fa21ac9]728//=============================================================================================
729// Kernel Setup logic
730//=============================================================================================
[eb2e723]731//-----------------------------------------------------------------------------
732// Kernel boot procedures
[8c50aed]733static void __kernel_startup(void) {
[14a61b5]734        verify( ! kernelTLS.preemption_state.enabled );
[4069faad]735        __cfadbg_print_safe(runtime_core, "Kernel : Starting\n");
[eb2e723]736
[b2f6113]737        __page_size = sysconf( _SC_PAGESIZE );
738
[ea8b2f7]739        __cfa_dbg_global_clusters.list{ __get };
740        __cfa_dbg_global_clusters.lock{};
[de94a60]741
[b388ee81]742        // Initialize the global scheduler lock
743        __scheduler_lock = (__scheduler_RWLock_t*)&storage___scheduler_lock;
744        (*__scheduler_lock){};
745
[de6319f]746        // Initialize the main cluster
747        mainCluster = (cluster *)&storage_mainCluster;
748        (*mainCluster){"Main Cluster"};
749
[4069faad]750        __cfadbg_print_safe(runtime_core, "Kernel : Main cluster ready\n");
[de6319f]751
[eb2e723]752        // Start by initializing the main thread
[1c273d0]753        // SKULLDUGGERY: the mainThread steals the process main thread
[969b3fe]754        // which will then be scheduled by the mainProcessor normally
[ac2b598]755        mainThread = ($thread *)&storage_mainThread;
[8fcbb4c]756        current_stack_info_t info;
[b2f6113]757        info.storage = (__stack_t*)&storage_mainThreadCtx;
[83a071f9]758        (*mainThread){ &info };
[eb2e723]759
[4069faad]760        __cfadbg_print_safe(runtime_core, "Kernel : Main thread ready\n");
[fa21ac9]761
[bd98b58]762
[de6319f]763
764        // Construct the processor context of the main processor
765        void ?{}(processorCtx_t & this, processor * proc) {
766                (this.__cor){ "Processor" };
[1805b1b]767                this.__cor.starter = 0p;
[de6319f]768                this.proc = proc;
769        }
770
771        void ?{}(processor & this) with( this ) {
772                name = "Main Processor";
773                cltr = mainCluster;
774                terminated{ 0 };
775                do_terminate = false;
[1805b1b]776                preemption_alarm = 0p;
[de6319f]777                pending_preemption = false;
778                kernel_thread = pthread_self();
[7768b8d]779                id = -1u;
[de6319f]780
781                runner{ &this };
[4069faad]782                __cfadbg_print_safe(runtime_core, "Kernel : constructed main processor context %p\n", &runner);
[de6319f]783        }
[fa21ac9]784
[969b3fe]785        // Initialize the main processor and the main processor ctx
[eb2e723]786        // (the coroutine that contains the processing control flow)
[969b3fe]787        mainProcessor = (processor *)&storage_mainProcessor;
[de6319f]788        (*mainProcessor){};
[eb2e723]789
[9b1dcc2]790        mainProcessor->id = doregister( (__processor_id_t*)mainProcessor);
[7768b8d]791
[dcb42b8]792        //initialize the global state variables
[14a61b5]793        kernelTLS.this_processor = mainProcessor;
794        kernelTLS.this_thread    = mainThread;
[eb2e723]795
[82ff5845]796        // Enable preemption
797        kernel_start_preemption();
798
[969b3fe]799        // Add the main thread to the ready queue
800        // once resume is called on mainProcessor->runner the mainThread needs to be scheduled like any normal thread
[9b1dcc2]801        __schedule_thread((__processor_id_t *)mainProcessor, mainThread);
[969b3fe]802
803        // SKULLDUGGERY: Force a context switch to the main processor to set the main thread's context to the current UNIX
[c7a900a]804        // context. Hence, the main thread does not begin through __cfactx_invoke_thread, like all other threads. The trick here is that
[1c273d0]805        // mainThread is on the ready queue when this call is made.
[8c50aed]806        __kernel_first_resume( kernelTLS.this_processor );
[dcb42b8]807
808
809        // THE SYSTEM IS NOW COMPLETELY RUNNING
[f6660520]810
811
812        // Now that the system is up, finish creating systems that need threading
813        __kernel_io_finish_start( *mainCluster );
814
815
816        __cfadbg_print_safe(runtime_core, "Kernel : Started\n--------------------------------------------------\n\n");
[82ff5845]817
[14a61b5]818        verify( ! kernelTLS.preemption_state.enabled );
[36982fc]819        enable_interrupts( __cfaabi_dbg_ctx );
[afd550c]820        verify( TL_GET( preemption_state.enabled ) );
[eb2e723]821}
822
[8c50aed]823static void __kernel_shutdown(void) {
[f6660520]824        //Before we start shutting things down, wait for systems that need threading to shutdown
825        __kernel_io_prepare_stop( *mainCluster );
[eb2e723]826
[92e7631]827        /* paranoid */ verify( TL_GET( preemption_state.enabled ) );
[4e6fb8e]828        disable_interrupts();
[92e7631]829        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[4e6fb8e]830
[f6660520]831        __cfadbg_print_safe(runtime_core, "\n--------------------------------------------------\nKernel : Shutting down\n");
[4e6fb8e]832
[969b3fe]833        // SKULLDUGGERY: Notify the mainProcessor it needs to terminates.
[dcb42b8]834        // When its coroutine terminates, it return control to the mainThread
835        // which is currently here
[ea8b2f7]836        __atomic_store_n(&mainProcessor->do_terminate, true, __ATOMIC_RELEASE);
[8c50aed]837        __kernel_last_resume( kernelTLS.this_processor );
[ea8b2f7]838        mainThread->self_cor.state = Halted;
[eb2e723]839
[dcb42b8]840        // THE SYSTEM IS NOW COMPLETELY STOPPED
[eb2e723]841
[82ff5845]842        // Disable preemption
843        kernel_stop_preemption();
844
[9b1dcc2]845        unregister((__processor_id_t*)mainProcessor);
[7768b8d]846
[969b3fe]847        // Destroy the main processor and its context in reverse order of construction
[dcb42b8]848        // These were manually constructed so we need manually destroy them
[c66f6cb]849        void ^?{}(processor & this) with( this ){
850                /* paranoid */ verify( this.do_terminate == true );
[b798713]851                __cfaabi_dbg_print_safe("Kernel : destroyed main processor context %p\n", &runner);
852        }
853
[7768b8d]854        ^(*mainProcessor){};
[eb2e723]855
[dcb42b8]856        // Final step, destroy the main thread since it is no longer needed
[6a490b2]857
[dcb42b8]858        // Since we provided a stack to this taxk it will not destroy anything
[210b8b3]859        /* paranoid */ verify(mainThread->self_cor.stack.storage == (__stack_t*)(((uintptr_t)&storage_mainThreadCtx)| 0x1));
[7768b8d]860        ^(*mainThread){};
861
862        ^(*mainCluster){};
[eb2e723]863
[b388ee81]864        ^(*__scheduler_lock){};
865
[ea8b2f7]866        ^(__cfa_dbg_global_clusters.list){};
867        ^(__cfa_dbg_global_clusters.lock){};
[a1a17a74]868
[4069faad]869        __cfadbg_print_safe(runtime_core, "Kernel : Shutdown complete\n");
[9d944b2]870}
871
[14a61b5]872//=============================================================================================
[92e7631]873// Kernel Idle Sleep
[14a61b5]874//=============================================================================================
[92e7631]875static $thread * __halt(processor * this) with( *this ) {
876        if( do_terminate ) return 0p;
[ea8b2f7]877
[92e7631]878        // First, lock the cluster idle
879        lock( cltr->idle_lock __cfaabi_dbg_ctx2 );
[14a61b5]880
[92e7631]881        // Check if we can find a thread
882        if( $thread * found = __next_thread( cltr ) ) {
883                unlock( cltr->idle_lock );
884                return found;
[6b4cdd3]885        }
[14a61b5]886
[92e7631]887        // Move this processor from the active list to the idle list
888        move_to_front(cltr->procs, cltr->idles, *this);
[14a61b5]889
[92e7631]890        // Unlock the idle lock so we don't go to sleep with a lock
891        unlock    (cltr->idle_lock);
[14a61b5]892
[92e7631]893        // We are ready to sleep
[4069faad]894        __cfadbg_print_safe(runtime_core, "Kernel : Processor %p ready to sleep\n", this);
[92e7631]895        wait( idle );
[14a61b5]896
[92e7631]897        // We have woken up
[4069faad]898        __cfadbg_print_safe(runtime_core, "Kernel : Processor %p woke up and ready to run\n", this);
[14a61b5]899
[92e7631]900        // Get ourself off the idle list
[6b4cdd3]901        with( *cltr ) {
[92e7631]902                lock  (idle_lock __cfaabi_dbg_ctx2);
903                move_to_front(idles, procs, *this);
904                unlock(idle_lock);
[6b4cdd3]905        }
[14a61b5]906
[92e7631]907        // Don't check the ready queue again, we may not be in a position to run a thread
908        return 0p;
909}
910
911// Wake a thread from the front if there are any
[504a7dc]912static bool __wake_one(cluster * this) {
[92e7631]913        // First, lock the cluster idle
914        lock( this->idle_lock __cfaabi_dbg_ctx2 );
915
916        // Check if there is someone to wake up
917        if( !this->idles.head ) {
918                // Nope unlock and return false
919                unlock( this->idle_lock );
920                return false;
921        }
922
923        // Wake them up
[4069faad]924        __cfadbg_print_safe(runtime_core, "Kernel : waking Processor %p\n", this->idles.head);
[8e16177]925        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[92e7631]926        post( this->idles.head->idle );
927
928        // Unlock and return true
929        unlock( this->idle_lock );
930        return true;
931}
932
933// Unconditionnaly wake a thread
934static bool __wake_proc(processor * this) {
[4069faad]935        __cfadbg_print_safe(runtime_core, "Kernel : waking Processor %p\n", this);
[8e16177]936
937        disable_interrupts();
938                /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
939                bool ret = post( this->idle );
940        enable_interrupts( __cfaabi_dbg_ctx );
941
942        return ret;
[6b4cdd3]943}
944
[dbe9b08]945//=============================================================================================
946// Unexpected Terminating logic
947//=============================================================================================
[ea7d2b0]948static __spinlock_t kernel_abort_lock;
[9d944b2]949static bool kernel_abort_called = false;
950
[afd550c]951void * kernel_abort(void) __attribute__ ((__nothrow__)) {
[9d944b2]952        // abort cannot be recursively entered by the same or different processors because all signal handlers return when
953        // the globalAbort flag is true.
[36982fc]954        lock( kernel_abort_lock __cfaabi_dbg_ctx2 );
[9d944b2]955
956        // first task to abort ?
[de94a60]957        if ( kernel_abort_called ) {                    // not first task to abort ?
[ea7d2b0]958                unlock( kernel_abort_lock );
[1c273d0]959
[9d944b2]960                sigset_t mask;
961                sigemptyset( &mask );
[de94a60]962                sigaddset( &mask, SIGALRM );            // block SIGALRM signals
[8a13c47]963                sigaddset( &mask, SIGUSR1 );            // block SIGALRM signals
964                sigsuspend( &mask );                            // block the processor to prevent further damage during abort
965                _exit( EXIT_FAILURE );                          // if processor unblocks before it is killed, terminate it
[de94a60]966        }
967        else {
968                kernel_abort_called = true;
969                unlock( kernel_abort_lock );
[9d944b2]970        }
971
[14a61b5]972        return kernelTLS.this_thread;
[9d944b2]973}
974
975void kernel_abort_msg( void * kernel_data, char * abort_text, int abort_text_size ) {
[ac2b598]976        $thread * thrd = kernel_data;
[9d944b2]977
[de94a60]978        if(thrd) {
979                int len = snprintf( abort_text, abort_text_size, "Error occurred while executing thread %.256s (%p)", thrd->self_cor.name, thrd );
[1c40091]980                __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
[de94a60]981
[212c2187]982                if ( &thrd->self_cor != thrd->curr_cor ) {
983                        len = snprintf( abort_text, abort_text_size, " in coroutine %.256s (%p).\n", thrd->curr_cor->name, thrd->curr_cor );
[1c40091]984                        __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
[de94a60]985                }
986                else {
[1c40091]987                        __cfaabi_bits_write( STDERR_FILENO, ".\n", 2 );
[de94a60]988                }
[1c273d0]989        }
[9d944b2]990        else {
[de94a60]991                int len = snprintf( abort_text, abort_text_size, "Error occurred outside of any thread.\n" );
[1c40091]992                __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
[9d944b2]993        }
994}
995
[2b8bc41]996int kernel_abort_lastframe( void ) __attribute__ ((__nothrow__)) {
[14a61b5]997        return get_coroutine(kernelTLS.this_thread) == get_coroutine(mainThread) ? 4 : 2;
[2b8bc41]998}
999
[de94a60]1000static __spinlock_t kernel_debug_lock;
1001
[9d944b2]1002extern "C" {
[1c40091]1003        void __cfaabi_bits_acquire() {
[36982fc]1004                lock( kernel_debug_lock __cfaabi_dbg_ctx2 );
[9d944b2]1005        }
1006
[1c40091]1007        void __cfaabi_bits_release() {
[ea7d2b0]1008                unlock( kernel_debug_lock );
[9d944b2]1009        }
[8118303]1010}
1011
[fa21ac9]1012//=============================================================================================
1013// Kernel Utilities
1014//=============================================================================================
[bd98b58]1015//-----------------------------------------------------------------------------
1016// Locks
[242a902]1017void  ?{}( semaphore & this, int count = 1 ) {
1018        (this.lock){};
1019        this.count = count;
1020        (this.waiting){};
[db6f06a]1021}
[242a902]1022void ^?{}(semaphore & this) {}
[db6f06a]1023
[71c8b7e]1024bool P(semaphore & this) with( this ){
[65deb18]1025        lock( lock __cfaabi_dbg_ctx2 );
1026        count -= 1;
1027        if ( count < 0 ) {
[bdeba0b]1028                // queue current task
[14a61b5]1029                append( waiting, kernelTLS.this_thread );
[bdeba0b]1030
1031                // atomically release spin lock and block
[3381ed7]1032                unlock( lock );
[ae66348]1033                park( __cfaabi_dbg_ctx );
[71c8b7e]1034                return true;
[8def349]1035        }
[4e6fb8e]1036        else {
[65deb18]1037            unlock( lock );
[71c8b7e]1038            return false;
[4e6fb8e]1039        }
[bd98b58]1040}
1041
[f0ce5f4]1042bool V(semaphore & this) with( this ) {
[ac2b598]1043        $thread * thrd = 0p;
[65deb18]1044        lock( lock __cfaabi_dbg_ctx2 );
1045        count += 1;
1046        if ( count <= 0 ) {
[bdeba0b]1047                // remove task at head of waiting list
[65deb18]1048                thrd = pop_head( waiting );
[bd98b58]1049        }
[bdeba0b]1050
[65deb18]1051        unlock( lock );
[bdeba0b]1052
1053        // make new owner
[ae66348]1054        unpark( thrd __cfaabi_dbg_ctx2 );
[f0ce5f4]1055
[d384787]1056        return thrd != 0p;
1057}
1058
1059bool V(semaphore & this, unsigned diff) with( this ) {
1060        $thread * thrd = 0p;
1061        lock( lock __cfaabi_dbg_ctx2 );
1062        int release = max(-count, (int)diff);
1063        count += diff;
1064        for(release) {
1065                unpark( pop_head( waiting ) __cfaabi_dbg_ctx2 );
1066        }
1067
1068        unlock( lock );
1069
[f0ce5f4]1070        return thrd != 0p;
[bd98b58]1071}
1072
[f7d6bb0]1073//-----------------------------------------------------------------------------
[de94a60]1074// Global Queues
1075void doregister( cluster     & cltr ) {
[ea8b2f7]1076        lock      ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2);
1077        push_front( __cfa_dbg_global_clusters.list, cltr );
1078        unlock    ( __cfa_dbg_global_clusters.lock );
[de94a60]1079}
[f7d6bb0]1080
[de94a60]1081void unregister( cluster     & cltr ) {
[ea8b2f7]1082        lock  ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2);
1083        remove( __cfa_dbg_global_clusters.list, cltr );
1084        unlock( __cfa_dbg_global_clusters.lock );
[de94a60]1085}
[f7d6bb0]1086
[ac2b598]1087void doregister( cluster * cltr, $thread & thrd ) {
[a1a17a74]1088        lock      (cltr->thread_list_lock __cfaabi_dbg_ctx2);
[d4e68a6]1089        cltr->nthreads += 1;
[a1a17a74]1090        push_front(cltr->threads, thrd);
1091        unlock    (cltr->thread_list_lock);
1092}
1093
[ac2b598]1094void unregister( cluster * cltr, $thread & thrd ) {
[a1a17a74]1095        lock  (cltr->thread_list_lock __cfaabi_dbg_ctx2);
1096        remove(cltr->threads, thrd );
[d4e68a6]1097        cltr->nthreads -= 1;
[a1a17a74]1098        unlock(cltr->thread_list_lock);
1099}
[9181f1d]1100
[504a7dc]1101void doregister( cluster * cltr, processor * proc ) {
1102        lock      (cltr->idle_lock __cfaabi_dbg_ctx2);
1103        cltr->nprocessors += 1;
1104        push_front(cltr->procs, *proc);
1105        unlock    (cltr->idle_lock);
1106}
1107
1108void unregister( cluster * cltr, processor * proc ) {
1109        lock  (cltr->idle_lock __cfaabi_dbg_ctx2);
1110        remove(cltr->procs, *proc );
1111        cltr->nprocessors -= 1;
1112        unlock(cltr->idle_lock);
1113}
1114
[de94a60]1115//-----------------------------------------------------------------------------
1116// Debug
1117__cfaabi_dbg_debug_do(
[1997b4e]1118        extern "C" {
[ae66348]1119                void __cfaabi_dbg_record_lock(__spinlock_t & this, const char prev_name[]) {
[1997b4e]1120                        this.prev_name = prev_name;
1121                        this.prev_thrd = kernelTLS.this_thread;
1122                }
[ae66348]1123
1124                void __cfaabi_dbg_record_thrd($thread & this, bool park, const char prev_name[]) {
1125                        if(park) {
[f0ce5f4]1126                                this.park_caller   = prev_name;
1127                                this.park_stale    = false;
[ae66348]1128                        }
1129                        else {
[f0ce5f4]1130                                this.unpark_caller = prev_name;
1131                                this.unpark_stale  = false;
[ae66348]1132                        }
1133                }
[9181f1d]1134        }
[f7d6bb0]1135)
[2026bb6]1136
1137//-----------------------------------------------------------------------------
1138// Debug
[8c50aed]1139bool threading_enabled(void) __attribute__((const)) {
[2026bb6]1140        return true;
1141}
[8118303]1142// Local Variables: //
1143// mode: c //
1144// tab-width: 4 //
1145// End: //
Note: See TracBrowser for help on using the repository browser.