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

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

Changed ready RW-Lock to be a single global lock instead of per cluster.
This was needed because otherwise, processors outside the cluster could not schedule threads.

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