source: libcfa/src/concurrency/kernel.cfa @ 42cd451e

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

Moved processor registration to constructor

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