source: libcfa/src/concurrency/kernel.cfa @ 398e8e9

arm-ehjacob/cs343-translationnew-astnew-ast-unique-expr
Last change on this file since 398e8e9 was 398e8e9, checked in by Thierry Delisle <tdelisle@…>, 16 months ago

Tentative deadlock fix

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