source: libcfa/src/concurrency/kernel.cfa @ 61d7bec

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

Merge branch 'master' into relaxed_ready

  • Property mode set to 100644
File size: 35.9 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 May 26 22:05:19 2020
13// Update Count     : 59
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>
23#include <stdio.h>
24#include <fenv.h>
25#include <signal.h>
26#include <unistd.h>
27#include <limits.h>                                                                             // PTHREAD_STACK_MIN
28#include <sys/mman.h>                                                                   // mprotect
29extern "C" {
30#include <sys/resource.h>
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_debug_do( char * old_caller = thrd->unpark_caller; )
651        __cfaabi_dbg_record_thrd( *thrd, false, caller );
652
653        enum coroutine_state old_state = __atomic_exchange_n(&thrd->state, Rerun, __ATOMIC_SEQ_CST);
654        __cfaabi_dbg_debug_do( thrd->unpark_result = old_state; )
655        switch(old_state) {
656                case Active:
657                        // Wake won the race, the thread will reschedule/rerun itself
658                        break;
659                case Blocked:
660                        /* paranoid */ verify( ! thrd->preempted != __NO_PREEMPTION );
661
662                        // Wake lost the race,
663                        thrd->state = Blocked;
664                        __schedule_thread( thrd );
665                        break;
666                case Rerun:
667                        abort("More than one thread attempted to schedule thread %p\n", thrd);
668                        break;
669                case Halted:
670                case Start:
671                case Primed:
672                default:
673                        // This makes no sense, something is wrong abort
674                        abort();
675        }
676}
677
678void unpark( $thread * thrd __cfaabi_dbg_ctx_param2 ) {
679        if( !thrd ) return;
680
681        disable_interrupts();
682        __unpark( thrd __cfaabi_dbg_ctx_fwd2 );
683        enable_interrupts( __cfaabi_dbg_ctx );
684}
685
686void park( __cfaabi_dbg_ctx_param ) {
687        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
688        disable_interrupts();
689        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
690        /* paranoid */ verify( kernelTLS.this_thread->preempted == __NO_PREEMPTION );
691
692        // record activity
693        __cfaabi_dbg_record_thrd( *kernelTLS.this_thread, true, caller );
694
695        returnToKernel();
696
697        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
698        enable_interrupts( __cfaabi_dbg_ctx );
699        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
700
701}
702
703// KERNEL ONLY
704void __leave_thread() {
705        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
706        returnToKernel();
707        abort();
708}
709
710// KERNEL ONLY
711bool force_yield( __Preemption_Reason reason ) {
712        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
713        disable_interrupts();
714        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
715
716        $thread * thrd = kernelTLS.this_thread;
717        /* paranoid */ verify(thrd->state == Active || thrd->state == Rerun);
718
719        // SKULLDUGGERY: It is possible that we are preempting this thread just before
720        // it was going to park itself. If that is the case and it is already using the
721        // intrusive fields then we can't use them to preempt the thread
722        // If that is the case, abandon the preemption.
723        bool preempted = false;
724        if(thrd->link.next == 0p) {
725                preempted = true;
726                thrd->preempted = reason;
727                returnToKernel();
728        }
729
730        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
731        enable_interrupts_noPoll();
732        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
733
734        return preempted;
735}
736
737//=============================================================================================
738// Kernel Setup logic
739//=============================================================================================
740//-----------------------------------------------------------------------------
741// Kernel boot procedures
742static void __kernel_startup(void) {
743        verify( ! kernelTLS.preemption_state.enabled );
744        __cfadbg_print_safe(runtime_core, "Kernel : Starting\n");
745
746        __page_size = sysconf( _SC_PAGESIZE );
747
748        __cfa_dbg_global_clusters.list{ __get };
749        __cfa_dbg_global_clusters.lock{};
750
751        // Initialize the main cluster
752        mainCluster = (cluster *)&storage_mainCluster;
753        (*mainCluster){"Main Cluster"};
754
755        __cfadbg_print_safe(runtime_core, "Kernel : Main cluster ready\n");
756
757        // Start by initializing the main thread
758        // SKULLDUGGERY: the mainThread steals the process main thread
759        // which will then be scheduled by the mainProcessor normally
760        mainThread = ($thread *)&storage_mainThread;
761        current_stack_info_t info;
762        info.storage = (__stack_t*)&storage_mainThreadCtx;
763        (*mainThread){ &info };
764
765        __cfadbg_print_safe(runtime_core, "Kernel : Main thread ready\n");
766
767
768
769        // Construct the processor context of the main processor
770        void ?{}(processorCtx_t & this, processor * proc) {
771                (this.__cor){ "Processor" };
772                this.__cor.starter = 0p;
773                this.proc = proc;
774        }
775
776        void ?{}(processor & this) with( this ) {
777                name = "Main Processor";
778                cltr = mainCluster;
779                terminated{ 0 };
780                do_terminate = false;
781                preemption_alarm = 0p;
782                pending_preemption = false;
783                kernel_thread = pthread_self();
784                id = -1u;
785
786                runner{ &this };
787                __cfadbg_print_safe(runtime_core, "Kernel : constructed main processor context %p\n", &runner);
788        }
789
790        // Initialize the main processor and the main processor ctx
791        // (the coroutine that contains the processing control flow)
792        mainProcessor = (processor *)&storage_mainProcessor;
793        (*mainProcessor){};
794
795        mainProcessor->id = doregister2(mainCluster, mainProcessor);
796
797        //initialize the global state variables
798        kernelTLS.this_processor = mainProcessor;
799        kernelTLS.this_thread    = mainThread;
800
801        // Enable preemption
802        kernel_start_preemption();
803
804        // Add the main thread to the ready queue
805        // once resume is called on mainProcessor->runner the mainThread needs to be scheduled like any normal thread
806        __schedule_thread(mainThread);
807
808        // SKULLDUGGERY: Force a context switch to the main processor to set the main thread's context to the current UNIX
809        // context. Hence, the main thread does not begin through __cfactx_invoke_thread, like all other threads. The trick here is that
810        // mainThread is on the ready queue when this call is made.
811        __kernel_first_resume( kernelTLS.this_processor );
812
813
814        // THE SYSTEM IS NOW COMPLETELY RUNNING
815
816
817        // Now that the system is up, finish creating systems that need threading
818        __kernel_io_finish_start( *mainCluster );
819
820
821        __cfadbg_print_safe(runtime_core, "Kernel : Started\n--------------------------------------------------\n\n");
822
823        verify( ! kernelTLS.preemption_state.enabled );
824        enable_interrupts( __cfaabi_dbg_ctx );
825        verify( TL_GET( preemption_state.enabled ) );
826}
827
828static void __kernel_shutdown(void) {
829        //Before we start shutting things down, wait for systems that need threading to shutdown
830        __kernel_io_prepare_stop( *mainCluster );
831
832        /* paranoid */ verify( TL_GET( preemption_state.enabled ) );
833        disable_interrupts();
834        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
835
836        __cfadbg_print_safe(runtime_core, "\n--------------------------------------------------\nKernel : Shutting down\n");
837
838        // SKULLDUGGERY: Notify the mainProcessor it needs to terminates.
839        // When its coroutine terminates, it return control to the mainThread
840        // which is currently here
841        __atomic_store_n(&mainProcessor->do_terminate, true, __ATOMIC_RELEASE);
842        __kernel_last_resume( kernelTLS.this_processor );
843        mainThread->self_cor.state = Halted;
844
845        // THE SYSTEM IS NOW COMPLETELY STOPPED
846
847        // Disable preemption
848        kernel_stop_preemption();
849
850        unregister2(mainCluster, mainProcessor);
851
852        // Destroy the main processor and its context in reverse order of construction
853        // These were manually constructed so we need manually destroy them
854        void ^?{}(processor & this) with( this ){
855                /* paranoid */ verify( this.do_terminate == true );
856                __cfaabi_dbg_print_safe("Kernel : destroyed main processor context %p\n", &runner);
857        }
858
859        ^(*mainProcessor){};
860
861        // Final step, destroy the main thread since it is no longer needed
862
863        // Since we provided a stack to this taxk it will not destroy anything
864        /* paranoid */ verify(mainThread->self_cor.stack.storage == (__stack_t*)(((uintptr_t)&storage_mainThreadCtx)| 0x1));
865        ^(*mainThread){};
866
867        ^(*mainCluster){};
868
869        ^(__cfa_dbg_global_clusters.list){};
870        ^(__cfa_dbg_global_clusters.lock){};
871
872        __cfadbg_print_safe(runtime_core, "Kernel : Shutdown complete\n");
873}
874
875//=============================================================================================
876// Kernel Idle Sleep
877//=============================================================================================
878static $thread * __halt(processor * this) with( *this ) {
879        if( do_terminate ) return 0p;
880
881        // First, lock the cluster idle
882        lock( cltr->idle_lock __cfaabi_dbg_ctx2 );
883
884        // Check if we can find a thread
885        if( $thread * found = __next_thread( cltr ) ) {
886                unlock( cltr->idle_lock );
887                return found;
888        }
889
890        // Move this processor from the active list to the idle list
891        move_to_front(cltr->procs, cltr->idles, *this);
892
893        // Unlock the idle lock so we don't go to sleep with a lock
894        unlock    (cltr->idle_lock);
895
896        // We are ready to sleep
897        __cfadbg_print_safe(runtime_core, "Kernel : Processor %p ready to sleep\n", this);
898        wait( idle );
899
900        // We have woken up
901        __cfadbg_print_safe(runtime_core, "Kernel : Processor %p woke up and ready to run\n", this);
902
903        // Get ourself off the idle list
904        with( *cltr ) {
905                lock  (idle_lock __cfaabi_dbg_ctx2);
906                move_to_front(idles, procs, *this);
907                unlock(idle_lock);
908        }
909
910        // Don't check the ready queue again, we may not be in a position to run a thread
911        return 0p;
912}
913
914// Wake a thread from the front if there are any
915static bool __wake_one(cluster * this) {
916        // First, lock the cluster idle
917        lock( this->idle_lock __cfaabi_dbg_ctx2 );
918
919        // Check if there is someone to wake up
920        if( !this->idles.head ) {
921                // Nope unlock and return false
922                unlock( this->idle_lock );
923                return false;
924        }
925
926        // Wake them up
927        __cfadbg_print_safe(runtime_core, "Kernel : waking Processor %p\n", this->idles.head);
928        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
929        post( this->idles.head->idle );
930
931        // Unlock and return true
932        unlock( this->idle_lock );
933        return true;
934}
935
936// Unconditionnaly wake a thread
937static bool __wake_proc(processor * this) {
938        __cfadbg_print_safe(runtime_core, "Kernel : waking Processor %p\n", this);
939
940        disable_interrupts();
941                /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
942                bool ret = post( this->idle );
943        enable_interrupts( __cfaabi_dbg_ctx );
944
945        return ret;
946}
947
948//=============================================================================================
949// Unexpected Terminating logic
950//=============================================================================================
951static __spinlock_t kernel_abort_lock;
952static bool kernel_abort_called = false;
953
954void * kernel_abort(void) __attribute__ ((__nothrow__)) {
955        // abort cannot be recursively entered by the same or different processors because all signal handlers return when
956        // the globalAbort flag is true.
957        lock( kernel_abort_lock __cfaabi_dbg_ctx2 );
958
959        // first task to abort ?
960        if ( kernel_abort_called ) {                    // not first task to abort ?
961                unlock( kernel_abort_lock );
962
963                sigset_t mask;
964                sigemptyset( &mask );
965                sigaddset( &mask, SIGALRM );            // block SIGALRM signals
966                sigaddset( &mask, SIGUSR1 );            // block SIGALRM signals
967                sigsuspend( &mask );                            // block the processor to prevent further damage during abort
968                _exit( EXIT_FAILURE );                          // if processor unblocks before it is killed, terminate it
969        }
970        else {
971                kernel_abort_called = true;
972                unlock( kernel_abort_lock );
973        }
974
975        return kernelTLS.this_thread;
976}
977
978void kernel_abort_msg( void * kernel_data, char * abort_text, int abort_text_size ) {
979        $thread * thrd = kernel_data;
980
981        if(thrd) {
982                int len = snprintf( abort_text, abort_text_size, "Error occurred while executing thread %.256s (%p)", thrd->self_cor.name, thrd );
983                __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
984
985                if ( &thrd->self_cor != thrd->curr_cor ) {
986                        len = snprintf( abort_text, abort_text_size, " in coroutine %.256s (%p).\n", thrd->curr_cor->name, thrd->curr_cor );
987                        __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
988                }
989                else {
990                        __cfaabi_bits_write( STDERR_FILENO, ".\n", 2 );
991                }
992        }
993        else {
994                int len = snprintf( abort_text, abort_text_size, "Error occurred outside of any thread.\n" );
995                __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
996        }
997}
998
999int kernel_abort_lastframe( void ) __attribute__ ((__nothrow__)) {
1000        return get_coroutine(kernelTLS.this_thread) == get_coroutine(mainThread) ? 4 : 2;
1001}
1002
1003static __spinlock_t kernel_debug_lock;
1004
1005extern "C" {
1006        void __cfaabi_bits_acquire() {
1007                lock( kernel_debug_lock __cfaabi_dbg_ctx2 );
1008        }
1009
1010        void __cfaabi_bits_release() {
1011                unlock( kernel_debug_lock );
1012        }
1013}
1014
1015//=============================================================================================
1016// Kernel Utilities
1017//=============================================================================================
1018//-----------------------------------------------------------------------------
1019// Locks
1020void  ?{}( semaphore & this, int count = 1 ) {
1021        (this.lock){};
1022        this.count = count;
1023        (this.waiting){};
1024}
1025void ^?{}(semaphore & this) {}
1026
1027bool P(semaphore & this) with( this ){
1028        lock( lock __cfaabi_dbg_ctx2 );
1029        count -= 1;
1030        if ( count < 0 ) {
1031                // queue current task
1032                append( waiting, kernelTLS.this_thread );
1033
1034                // atomically release spin lock and block
1035                unlock( lock );
1036                park( __cfaabi_dbg_ctx );
1037                return true;
1038        }
1039        else {
1040            unlock( lock );
1041            return false;
1042        }
1043}
1044
1045bool V(semaphore & this) with( this ) {
1046        $thread * thrd = 0p;
1047        lock( lock __cfaabi_dbg_ctx2 );
1048        count += 1;
1049        if ( count <= 0 ) {
1050                // remove task at head of waiting list
1051                thrd = pop_head( waiting );
1052        }
1053
1054        unlock( lock );
1055
1056        // make new owner
1057        unpark( thrd __cfaabi_dbg_ctx2 );
1058
1059        return thrd != 0p;
1060}
1061
1062bool V(semaphore & this, unsigned diff) with( this ) {
1063        $thread * thrd = 0p;
1064        lock( lock __cfaabi_dbg_ctx2 );
1065        int release = max(-count, (int)diff);
1066        count += diff;
1067        for(release) {
1068                unpark( pop_head( waiting ) __cfaabi_dbg_ctx2 );
1069        }
1070
1071        unlock( lock );
1072
1073        return thrd != 0p;
1074}
1075
1076//-----------------------------------------------------------------------------
1077// Global Queues
1078void doregister( cluster     & cltr ) {
1079        lock      ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2);
1080        push_front( __cfa_dbg_global_clusters.list, cltr );
1081        unlock    ( __cfa_dbg_global_clusters.lock );
1082}
1083
1084void unregister( cluster     & cltr ) {
1085        lock  ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2);
1086        remove( __cfa_dbg_global_clusters.list, cltr );
1087        unlock( __cfa_dbg_global_clusters.lock );
1088}
1089
1090void doregister( cluster * cltr, $thread & thrd ) {
1091        lock      (cltr->thread_list_lock __cfaabi_dbg_ctx2);
1092        cltr->nthreads += 1;
1093        push_front(cltr->threads, thrd);
1094        unlock    (cltr->thread_list_lock);
1095}
1096
1097void unregister( cluster * cltr, $thread & thrd ) {
1098        lock  (cltr->thread_list_lock __cfaabi_dbg_ctx2);
1099        remove(cltr->threads, thrd );
1100        cltr->nthreads -= 1;
1101        unlock(cltr->thread_list_lock);
1102}
1103
1104void doregister( cluster * cltr, processor * proc ) {
1105        lock      (cltr->idle_lock __cfaabi_dbg_ctx2);
1106        cltr->nprocessors += 1;
1107        push_front(cltr->procs, *proc);
1108        unlock    (cltr->idle_lock);
1109}
1110
1111void unregister( cluster * cltr, processor * proc ) {
1112        lock  (cltr->idle_lock __cfaabi_dbg_ctx2);
1113        remove(cltr->procs, *proc );
1114        cltr->nprocessors -= 1;
1115        unlock(cltr->idle_lock);
1116}
1117
1118//-----------------------------------------------------------------------------
1119// Debug
1120__cfaabi_dbg_debug_do(
1121        extern "C" {
1122                void __cfaabi_dbg_record_lock(__spinlock_t & this, const char prev_name[]) {
1123                        this.prev_name = prev_name;
1124                        this.prev_thrd = kernelTLS.this_thread;
1125                }
1126
1127                void __cfaabi_dbg_record_thrd($thread & this, bool park, const char prev_name[]) {
1128                        if(park) {
1129                                this.park_caller   = prev_name;
1130                                this.park_stale    = false;
1131                        }
1132                        else {
1133                                this.unpark_caller = prev_name;
1134                                this.unpark_stale  = false;
1135                        }
1136                }
1137        }
1138)
1139
1140//-----------------------------------------------------------------------------
1141// Debug
1142bool threading_enabled(void) __attribute__((const)) {
1143        return true;
1144}
1145// Local Variables: //
1146// mode: c //
1147// tab-width: 4 //
1148// End: //
Note: See TracBrowser for help on using the repository browser.