source: libcfa/src/concurrency/kernel.cfa @ 69fbc61

arm-ehenumforall-pointer-decayjacob/cs343-translationnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 69fbc61 was 69fbc61, checked in by Thierry Delisle <tdelisle@…>, 3 years ago

Clusters/Processors? can now select which stats to print.
Instead of all or nothing.

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