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

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

Fix error in benchmark where the wrong fd was used.
Changed behcnmark to use seperate cluster for I/O.
Changed some debug prints to use new versions with groups.
Fixed halting race condition leading to deadlock.

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