source: libcfa/src/concurrency/kernel.cfa @ 320ec6fc

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

Changed ready_queue_(grow/shrink) to take a target instead of going incrementing

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