source: libcfa/src/concurrency/kernel.cfa @ 2f1cb37

arm-ehenumforall-pointer-decayjacob/cs343-translationnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 2f1cb37 was 2f1cb37, checked in by Thierry Delisle <tdelisle@…>, 3 years ago

Merge branch 'master' into relaxed_ready

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