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

arm-ehjacob/cs343-translationnew-astnew-ast-unique-expr
Last change on this file since bb83b47 was bb83b47, checked in by Peter A. Buhr <pabuhr@…>, 16 months ago

change initialization of kernelTLS to use @= and remove spurious initialization

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