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

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

First version of tools to view halts

  • Property mode set to 100644
File size: 38.3 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// kernel.c --
8//
9// Author           : Thierry Delisle
10// Created On       : Tue Jan 17 12:27:26 2017
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Tue May 26 22:05:19 2020
13// Update Count     : 59
14//
15
16#define __cforall_thread__
17// #define __CFA_DEBUG_PRINT_RUNTIME_CORE__
18
19//C Includes
20#include <stddef.h>
21#include <errno.h>
22#include <string.h>
23#include <stdio.h>
24#include <fenv.h>
25#include <signal.h>
26#include <unistd.h>
27#include <limits.h>                                                                             // PTHREAD_STACK_MIN
28#include <sys/mman.h>                                                                   // mprotect
29extern "C" {
30#include <sys/resource.h>
31}
32
33//CFA Includes
34#include "time.hfa"
35#include "kernel_private.hfa"
36#include "preemption.hfa"
37#include "startup.hfa"
38
39//Private includes
40#define __CFA_INVOKE_PRIVATE__
41#include "invoke.h"
42
43
44//-----------------------------------------------------------------------------
45// Some assembly required
46#if defined( __i386 )
47        #define CtxGet( ctx )        \
48                __asm__ volatile (     \
49                        "movl %%esp,%0\n"\
50                        "movl %%ebp,%1\n"\
51                        : "=rm" (ctx.SP),\
52                                "=rm" (ctx.FP) \
53                )
54
55        // mxcr : SSE Status and Control bits (control bits are preserved across function calls)
56        // fcw  : X87 FPU control word (preserved across function calls)
57        #define __x87_store         \
58                uint32_t __mxcr;      \
59                uint16_t __fcw;       \
60                __asm__ volatile (    \
61                        "stmxcsr %0\n"  \
62                        "fnstcw  %1\n"  \
63                        : "=m" (__mxcr),\
64                                "=m" (__fcw)  \
65                )
66
67        #define __x87_load         \
68                __asm__ volatile (   \
69                        "fldcw  %1\n"  \
70                        "ldmxcsr %0\n" \
71                        ::"m" (__mxcr),\
72                                "m" (__fcw)  \
73                )
74
75#elif defined( __x86_64 )
76        #define CtxGet( ctx )        \
77                __asm__ volatile (     \
78                        "movq %%rsp,%0\n"\
79                        "movq %%rbp,%1\n"\
80                        : "=rm" (ctx.SP),\
81                                "=rm" (ctx.FP) \
82                )
83
84        #define __x87_store         \
85                uint32_t __mxcr;      \
86                uint16_t __fcw;       \
87                __asm__ volatile (    \
88                        "stmxcsr %0\n"  \
89                        "fnstcw  %1\n"  \
90                        : "=m" (__mxcr),\
91                                "=m" (__fcw)  \
92                )
93
94        #define __x87_load          \
95                __asm__ volatile (    \
96                        "fldcw  %1\n"   \
97                        "ldmxcsr %0\n"  \
98                        :: "m" (__mxcr),\
99                                "m" (__fcw)  \
100                )
101
102
103#elif defined( __ARM_ARCH )
104#define CtxGet( ctx ) __asm__ ( \
105                "mov %0,%%sp\n"   \
106                "mov %1,%%r11\n"   \
107        : "=rm" (ctx.SP), "=rm" (ctx.FP) )
108#else
109        #error unknown hardware architecture
110#endif
111
112//-----------------------------------------------------------------------------
113//Start and stop routine for the kernel, declared first to make sure they run first
114static void __kernel_startup (void) __attribute__(( constructor( STARTUP_PRIORITY_KERNEL ) ));
115static void __kernel_shutdown(void) __attribute__(( destructor ( STARTUP_PRIORITY_KERNEL ) ));
116
117//-----------------------------------------------------------------------------
118// Kernel Scheduling logic
119static $thread * __next_thread(cluster * this);
120static bool __has_next_thread(cluster * this);
121static void __run_thread(processor * this, $thread * dst);
122static bool __wake_proc(processor *);
123static bool __wake_one(struct __processor_id_t * id, cluster * cltr);
124static void __halt(processor * this);
125
126//-----------------------------------------------------------------------------
127// Kernel storage
128KERNEL_STORAGE(cluster,              mainCluster);
129KERNEL_STORAGE(processor,            mainProcessor);
130KERNEL_STORAGE($thread,              mainThread);
131KERNEL_STORAGE(__stack_t,            mainThreadCtx);
132KERNEL_STORAGE(__scheduler_RWLock_t, __scheduler_lock);
133#if !defined(__CFA_NO_STATISTICS__)
134KERNEL_STORAGE(__stats_t, mainProcStats);
135#endif
136
137cluster              * mainCluster;
138processor            * mainProcessor;
139$thread              * mainThread;
140__scheduler_RWLock_t * __scheduler_lock;
141
142extern "C" {
143        struct { __dllist_t(cluster) list; __spinlock_t lock; } __cfa_dbg_global_clusters;
144}
145
146size_t __page_size = 0;
147
148//-----------------------------------------------------------------------------
149// Global state
150thread_local struct KernelThreadData kernelTLS __attribute__ ((tls_model ( "initial-exec" ))) = {
151        NULL,                                                                                           // cannot use 0p
152        NULL,
153        NULL,
154        { 1, false, false },
155        6u //this should be seeded better but due to a bug calling rdtsc doesn't work
156};
157
158//-----------------------------------------------------------------------------
159// Struct to steal stack
160struct current_stack_info_t {
161        __stack_t * storage;                                                            // pointer to stack object
162        void * base;                                                                            // base of stack
163        void * limit;                                                                           // stack grows towards stack limit
164        void * context;                                                                         // address of cfa_context_t
165};
166
167void ?{}( current_stack_info_t & this ) {
168        __stack_context_t ctx;
169        CtxGet( ctx );
170        this.base = ctx.FP;
171
172        rlimit r;
173        getrlimit( RLIMIT_STACK, &r);
174        size_t size = r.rlim_cur;
175
176        this.limit = (void *)(((intptr_t)this.base) - size);
177        this.context = &storage_mainThreadCtx;
178}
179
180//-----------------------------------------------------------------------------
181// Main thread construction
182
183void ?{}( $coroutine & this, current_stack_info_t * info) with( this ) {
184        stack.storage = info->storage;
185        with(*stack.storage) {
186                limit     = info->limit;
187                base      = info->base;
188        }
189        __attribute__((may_alias)) intptr_t * istorage = (intptr_t*) &stack.storage;
190        *istorage |= 0x1;
191        name = "Main Thread";
192        state = Start;
193        starter = 0p;
194        last = 0p;
195        cancellation = 0p;
196}
197
198void ?{}( $thread & this, current_stack_info_t * info) with( this ) {
199        ticket = 1;
200        state = Start;
201        self_cor{ info };
202        curr_cor = &self_cor;
203        curr_cluster = mainCluster;
204        self_mon.owner = &this;
205        self_mon.recursion = 1;
206        self_mon_p = &self_mon;
207        link.next = 0p;
208        link.prev = 0p;
209
210        node.next = 0p;
211        node.prev = 0p;
212        doregister(curr_cluster, this);
213
214        monitors{ &self_mon_p, 1, (fptr_t)0 };
215}
216
217//-----------------------------------------------------------------------------
218// Processor coroutine
219void ?{}(processorCtx_t & this) {
220
221}
222
223// Construct the processor context of non-main processors
224static void ?{}(processorCtx_t & this, processor * proc, current_stack_info_t * info) {
225        (this.__cor){ info };
226        this.proc = proc;
227}
228
229static void * __invoke_processor(void * arg);
230
231void ?{}(processor & this, const char name[], cluster & _cltr) with( this ) {
232        this.name = name;
233        this.cltr = &_cltr;
234        id = -1u;
235        terminated{ 0 };
236        destroyer = 0p;
237        do_terminate = false;
238        preemption_alarm = 0p;
239        pending_preemption = false;
240        runner.proc = &this;
241
242        #if !defined(__CFA_NO_STATISTICS__)
243                print_stats = 0;
244                print_halts = false;
245        #endif
246
247        idle{};
248
249        __cfadbg_print_safe(runtime_core, "Kernel : Starting core %p\n", &this);
250
251        this.stack = __create_pthread( &this.kernel_thread, __invoke_processor, (void *)&this );
252        __atomic_fetch_add( &cltr->nprocessors, 1u, __ATOMIC_SEQ_CST );
253
254        __cfadbg_print_safe(runtime_core, "Kernel : core %p created\n", &this);
255}
256
257void ^?{}(processor & this) with( this ){
258        if( ! __atomic_load_n(&do_terminate, __ATOMIC_ACQUIRE) ) {
259                __cfadbg_print_safe(runtime_core, "Kernel : core %p signaling termination\n", &this);
260
261                __atomic_store_n(&do_terminate, true, __ATOMIC_RELAXED);
262                __wake_proc( &this );
263
264                P( terminated );
265                verify( kernelTLS.this_processor != &this);
266        }
267
268        int err = pthread_join( kernel_thread, 0p );
269        if( err != 0 ) abort("KERNEL ERROR: joining processor %p caused error %s\n", &this, strerror(err));
270
271        free( this.stack );
272
273        __atomic_fetch_sub( &cltr->nprocessors, 1u, __ATOMIC_SEQ_CST );
274}
275
276void ?{}(cluster & this, const char name[], Duration preemption_rate, unsigned io_flags) with( this ) {
277        this.name = name;
278        this.preemption_rate = preemption_rate;
279        this.nprocessors = 0;
280        ready_queue{};
281
282        #if !defined(__CFA_NO_STATISTICS__)
283                print_stats = 0;
284                stats = alloc();
285                __init_stats( stats );
286        #endif
287
288        threads{ __get };
289
290        __kernel_io_startup( this, io_flags, &this == mainCluster );
291
292        doregister(this);
293}
294
295void ^?{}(cluster & this) {
296        __kernel_io_shutdown( this, &this == mainCluster );
297
298        #if !defined(__CFA_NO_STATISTICS__)
299                if( 0 != this.print_stats ) {
300                        __print_stats( this.stats, this.print_stats, true, this.name, (void*)&this );
301                }
302                free( this.stats );
303        #endif
304
305        unregister(this);
306}
307
308//=============================================================================================
309// Kernel Scheduling logic
310//=============================================================================================
311//Main of the processor contexts
312void main(processorCtx_t & runner) {
313        // Because of a bug, we couldn't initialized the seed on construction
314        // Do it here
315        kernelTLS.rand_seed ^= rdtscl();
316
317        processor * this = runner.proc;
318        verify(this);
319
320        __cfadbg_print_safe(runtime_core, "Kernel : core %p starting\n", this);
321
322        // register the processor unless it's the main thread which is handled in the boot sequence
323        if(this != mainProcessor) {
324                this->id = doregister((__processor_id_t*)this);
325                #if !defined(__CFA_NO_STATISTICS__)
326                        if( this->print_halts ) {
327                                __cfaabi_bits_print_safe( STDOUT_FILENO, "Processor : %d - %s (%p)\n", this->id, this->name, (void*)this);
328                        }
329                #endif
330
331                // Lock the RWlock so no-one pushes/pops while we are changing the queue
332                uint_fast32_t last_size = ready_mutate_lock();
333
334                        // Adjust the ready queue size
335                        ready_queue_grow( this->cltr );
336
337                // Unlock the RWlock
338                ready_mutate_unlock( last_size );
339        }
340
341        {
342                // Setup preemption data
343                preemption_scope scope = { this };
344
345                __cfadbg_print_safe(runtime_core, "Kernel : core %p started\n", this);
346
347                $thread * readyThread = 0p;
348                for( unsigned int spin_count = 0; ! __atomic_load_n(&this->do_terminate, __ATOMIC_SEQ_CST); spin_count++ ) {
349                        // Try to get the next thread
350                        readyThread = __next_thread( this->cltr );
351
352                        // Check if we actually found a thread
353                        if( readyThread ) {
354                                /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
355                                /* paranoid */ verifyf( readyThread->state == Ready || readyThread->preempted != __NO_PREEMPTION, "state : %d, preempted %d\n", readyThread->state, readyThread->preempted);
356                                /* paranoid */ verifyf( readyThread->link.next == 0p, "Expected null got %p", readyThread->link.next );
357                                __builtin_prefetch( readyThread->context.SP );
358
359                                // We found a thread run it
360                                __run_thread(this, readyThread);
361
362                                /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
363                        }
364                        else {
365                                // Block until a thread is ready
366                                __halt(this);
367                        }
368                }
369
370                __cfadbg_print_safe(runtime_core, "Kernel : core %p stopping\n", this);
371        }
372
373        V( this->terminated );
374
375        // unregister the processor unless it's the main thread which is handled in the boot sequence
376        if(this != mainProcessor) {
377                // Lock the RWlock so no-one pushes/pops while we are changing the queue
378                uint_fast32_t last_size = ready_mutate_lock();
379
380                        // Adjust the ready queue size
381                        ready_queue_shrink( this->cltr );
382
383                        // Make sure we aren't on the idle queue
384                        #if !defined(__CFA_NO_STATISTICS__)
385                                bool removed =
386                        #endif
387                        unsafe_remove( this->cltr->idles, this );
388
389                        #if !defined(__CFA_NO_STATISTICS__)
390                                if(removed) __tls_stats()->ready.sleep.exits++;
391                        #endif
392
393                // Unlock the RWlock
394                ready_mutate_unlock( last_size );
395
396                // Finally we don't need the read_lock any more
397                unregister((__processor_id_t*)this);
398        }
399        else {
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_debug_do( char * old_caller = thrd->unpark_caller; )
736        __cfaabi_dbg_record_thrd( *thrd, false, caller );
737
738        int old_ticket = __atomic_fetch_add(&thrd->ticket, 1, __ATOMIC_SEQ_CST);
739        __cfaabi_dbg_debug_do( thrd->unpark_result = old_ticket; thrd->unpark_state = thrd->state; )
740        switch(old_ticket) {
741                case 1:
742                        // Wake won the race, the thread will reschedule/rerun itself
743                        break;
744                case 0:
745                        /* paranoid */ verify( ! thrd->preempted != __NO_PREEMPTION );
746                        /* paranoid */ verify( thrd->state == Blocked );
747
748                        // Wake lost the race,
749                        __schedule_thread( id, thrd );
750                        break;
751                default:
752                        // This makes no sense, something is wrong abort
753                        abort();
754        }
755}
756
757void unpark( $thread * thrd __cfaabi_dbg_ctx_param2 ) {
758        if( !thrd ) return;
759
760        disable_interrupts();
761        __unpark( (__processor_id_t*)kernelTLS.this_processor, thrd __cfaabi_dbg_ctx_fwd2 );
762        enable_interrupts( __cfaabi_dbg_ctx );
763}
764
765void park( __cfaabi_dbg_ctx_param ) {
766        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
767        disable_interrupts();
768        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
769        /* paranoid */ verify( kernelTLS.this_thread->preempted == __NO_PREEMPTION );
770
771        // record activity
772        __cfaabi_dbg_record_thrd( *kernelTLS.this_thread, true, caller );
773
774        returnToKernel();
775
776        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
777        enable_interrupts( __cfaabi_dbg_ctx );
778        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
779
780}
781
782// KERNEL ONLY
783void __leave_thread() {
784        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
785        returnToKernel();
786        abort();
787}
788
789// KERNEL ONLY
790bool force_yield( __Preemption_Reason reason ) {
791        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
792        disable_interrupts();
793        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
794
795        $thread * thrd = kernelTLS.this_thread;
796        /* paranoid */ verify(thrd->state == Active);
797
798        // SKULLDUGGERY: It is possible that we are preempting this thread just before
799        // it was going to park itself. If that is the case and it is already using the
800        // intrusive fields then we can't use them to preempt the thread
801        // If that is the case, abandon the preemption.
802        bool preempted = false;
803        if(thrd->link.next == 0p) {
804                preempted = true;
805                thrd->preempted = reason;
806                returnToKernel();
807        }
808
809        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
810        enable_interrupts_noPoll();
811        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
812
813        return preempted;
814}
815
816//=============================================================================================
817// Kernel Setup logic
818//=============================================================================================
819//-----------------------------------------------------------------------------
820// Kernel boot procedures
821static void __kernel_startup(void) {
822        verify( ! kernelTLS.preemption_state.enabled );
823        __cfadbg_print_safe(runtime_core, "Kernel : Starting\n");
824
825        __page_size = sysconf( _SC_PAGESIZE );
826
827        __cfa_dbg_global_clusters.list{ __get };
828        __cfa_dbg_global_clusters.lock{};
829
830        // Initialize the global scheduler lock
831        __scheduler_lock = (__scheduler_RWLock_t*)&storage___scheduler_lock;
832        (*__scheduler_lock){};
833
834        // Initialize the main cluster
835        mainCluster = (cluster *)&storage_mainCluster;
836        (*mainCluster){"Main Cluster"};
837
838        __cfadbg_print_safe(runtime_core, "Kernel : Main cluster ready\n");
839
840        // Start by initializing the main thread
841        // SKULLDUGGERY: the mainThread steals the process main thread
842        // which will then be scheduled by the mainProcessor normally
843        mainThread = ($thread *)&storage_mainThread;
844        current_stack_info_t info;
845        info.storage = (__stack_t*)&storage_mainThreadCtx;
846        (*mainThread){ &info };
847
848        __cfadbg_print_safe(runtime_core, "Kernel : Main thread ready\n");
849
850
851
852        // Construct the processor context of the main processor
853        void ?{}(processorCtx_t & this, processor * proc) {
854                (this.__cor){ "Processor" };
855                this.__cor.starter = 0p;
856                this.proc = proc;
857        }
858
859        void ?{}(processor & this) with( this ) {
860                name = "Main Processor";
861                cltr = mainCluster;
862                terminated{ 0 };
863                do_terminate = false;
864                preemption_alarm = 0p;
865                pending_preemption = false;
866                kernel_thread = pthread_self();
867                id = -1u;
868
869                #if !defined(__CFA_NO_STATISTICS__)
870                        print_stats = false;
871                        print_halts = false;
872                #endif
873
874                runner{ &this };
875                __cfadbg_print_safe(runtime_core, "Kernel : constructed main processor context %p\n", &runner);
876
877                __atomic_fetch_add( &cltr->nprocessors, 1u, __ATOMIC_SEQ_CST );
878        }
879
880        // Initialize the main processor and the main processor ctx
881        // (the coroutine that contains the processing control flow)
882        mainProcessor = (processor *)&storage_mainProcessor;
883        (*mainProcessor){};
884
885        mainProcessor->id = doregister( (__processor_id_t*)mainProcessor);
886
887        //initialize the global state variables
888        kernelTLS.this_processor = mainProcessor;
889        kernelTLS.this_thread    = mainThread;
890
891        #if !defined( __CFA_NO_STATISTICS__ )
892                kernelTLS.this_stats = (__stats_t *)& storage_mainProcStats;
893                __init_stats( kernelTLS.this_stats );
894        #endif
895
896        // Enable preemption
897        kernel_start_preemption();
898
899        // Add the main thread to the ready queue
900        // once resume is called on mainProcessor->runner the mainThread needs to be scheduled like any normal thread
901        __schedule_thread((__processor_id_t *)mainProcessor, mainThread);
902
903        // SKULLDUGGERY: Force a context switch to the main processor to set the main thread's context to the current UNIX
904        // context. Hence, the main thread does not begin through __cfactx_invoke_thread, like all other threads. The trick here is that
905        // mainThread is on the ready queue when this call is made.
906        __kernel_first_resume( kernelTLS.this_processor );
907
908
909        // THE SYSTEM IS NOW COMPLETELY RUNNING
910
911
912        // Now that the system is up, finish creating systems that need threading
913        __kernel_io_finish_start( *mainCluster );
914
915
916        __cfadbg_print_safe(runtime_core, "Kernel : Started\n--------------------------------------------------\n\n");
917
918        verify( ! kernelTLS.preemption_state.enabled );
919        enable_interrupts( __cfaabi_dbg_ctx );
920        verify( TL_GET( preemption_state.enabled ) );
921}
922
923static void __kernel_shutdown(void) {
924        //Before we start shutting things down, wait for systems that need threading to shutdown
925        __kernel_io_prepare_stop( *mainCluster );
926
927        /* paranoid */ verify( TL_GET( preemption_state.enabled ) );
928        disable_interrupts();
929        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
930
931        __cfadbg_print_safe(runtime_core, "\n--------------------------------------------------\nKernel : Shutting down\n");
932
933        // SKULLDUGGERY: Notify the mainProcessor it needs to terminates.
934        // When its coroutine terminates, it return control to the mainThread
935        // which is currently here
936        __atomic_store_n(&mainProcessor->do_terminate, true, __ATOMIC_RELEASE);
937        __kernel_last_resume( kernelTLS.this_processor );
938        mainThread->self_cor.state = Halted;
939
940        // THE SYSTEM IS NOW COMPLETELY STOPPED
941
942        // Disable preemption
943        kernel_stop_preemption();
944
945        unregister((__processor_id_t*)mainProcessor);
946
947        // Destroy the main processor and its context in reverse order of construction
948        // These were manually constructed so we need manually destroy them
949        void ^?{}(processor & this) with( this ){
950                /* paranoid */ verify( this.do_terminate == true );
951                __atomic_fetch_sub( &cltr->nprocessors, 1u, __ATOMIC_SEQ_CST );
952                __cfaabi_dbg_print_safe("Kernel : destroyed main processor context %p\n", &runner);
953        }
954
955        ^(*mainProcessor){};
956
957        // Final step, destroy the main thread since it is no longer needed
958
959        // Since we provided a stack to this taxk it will not destroy anything
960        /* paranoid */ verify(mainThread->self_cor.stack.storage == (__stack_t*)(((uintptr_t)&storage_mainThreadCtx)| 0x1));
961        ^(*mainThread){};
962
963        ^(*mainCluster){};
964
965        ^(*__scheduler_lock){};
966
967        ^(__cfa_dbg_global_clusters.list){};
968        ^(__cfa_dbg_global_clusters.lock){};
969
970        __cfadbg_print_safe(runtime_core, "Kernel : Shutdown complete\n");
971}
972
973//=============================================================================================
974// Kernel Idle Sleep
975//=============================================================================================
976// Wake a thread from the front if there are any
977static bool __wake_one(struct __processor_id_t * id, cluster * this) {
978        /* paranoid */ verify( ready_schedule_islocked( id ) );
979
980        // Check if there is a sleeping processor
981        processor * p = pop(this->idles);
982
983        // If no one is sleeping, we are done
984        if( 0p == p ) return false;
985
986        // We found a processor, wake it up
987        post( p->idle );
988
989        return true;
990}
991
992// Unconditionnaly wake a thread
993static bool __wake_proc(processor * this) {
994        __cfadbg_print_safe(runtime_core, "Kernel : waking Processor %p\n", this);
995
996        disable_interrupts();
997                /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
998                bool ret = post( this->idle );
999        enable_interrupts( __cfaabi_dbg_ctx );
1000
1001        return ret;
1002}
1003
1004static void __halt(processor * this) with( *this ) {
1005        if( do_terminate ) return;
1006
1007        #if !defined(__CFA_NO_STATISTICS__)
1008                __tls_stats()->ready.sleep.halts++;
1009        #endif
1010        // Push self to queue
1011        push(cltr->idles, *this);
1012
1013        // Makre sure we don't miss a thread
1014        if( __has_next_thread(cltr) ) {
1015                // A thread was posted, make sure a processor is woken up
1016                struct __processor_id_t *id = (struct __processor_id_t *) this;
1017                ready_schedule_lock  ( id );
1018                        __wake_one( id, cltr );
1019                ready_schedule_unlock( id );
1020                #if !defined(__CFA_NO_STATISTICS__)
1021                        __tls_stats()->ready.sleep.cancels++;
1022                #endif
1023        }
1024
1025        #if !defined(__CFA_NO_STATISTICS__)
1026                if(this->print_halts) {
1027                        __cfaabi_bits_print_safe( STDOUT_FILENO, "PH:%d - %lld 0\n", this->id, rdtscl());
1028                }
1029        #endif
1030
1031        wait( idle );
1032
1033        #if !defined(__CFA_NO_STATISTICS__)
1034                if(this->print_halts) {
1035                        __cfaabi_bits_print_safe( STDOUT_FILENO, "PH:%d - %lld 1\n", this->id, rdtscl());
1036                }
1037        #endif
1038}
1039
1040//=============================================================================================
1041// Unexpected Terminating logic
1042//=============================================================================================
1043static __spinlock_t kernel_abort_lock;
1044static bool kernel_abort_called = false;
1045
1046void * kernel_abort(void) __attribute__ ((__nothrow__)) {
1047        // abort cannot be recursively entered by the same or different processors because all signal handlers return when
1048        // the globalAbort flag is true.
1049        lock( kernel_abort_lock __cfaabi_dbg_ctx2 );
1050
1051        // first task to abort ?
1052        if ( kernel_abort_called ) {                    // not first task to abort ?
1053                unlock( kernel_abort_lock );
1054
1055                sigset_t mask;
1056                sigemptyset( &mask );
1057                sigaddset( &mask, SIGALRM );            // block SIGALRM signals
1058                sigaddset( &mask, SIGUSR1 );            // block SIGALRM signals
1059                sigsuspend( &mask );                            // block the processor to prevent further damage during abort
1060                _exit( EXIT_FAILURE );                          // if processor unblocks before it is killed, terminate it
1061        }
1062        else {
1063                kernel_abort_called = true;
1064                unlock( kernel_abort_lock );
1065        }
1066
1067        return kernelTLS.this_thread;
1068}
1069
1070void kernel_abort_msg( void * kernel_data, char * abort_text, int abort_text_size ) {
1071        $thread * thrd = kernel_data;
1072
1073        if(thrd) {
1074                int len = snprintf( abort_text, abort_text_size, "Error occurred while executing thread %.256s (%p)", thrd->self_cor.name, thrd );
1075                __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
1076
1077                if ( &thrd->self_cor != thrd->curr_cor ) {
1078                        len = snprintf( abort_text, abort_text_size, " in coroutine %.256s (%p).\n", thrd->curr_cor->name, thrd->curr_cor );
1079                        __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
1080                }
1081                else {
1082                        __cfaabi_bits_write( STDERR_FILENO, ".\n", 2 );
1083                }
1084        }
1085        else {
1086                int len = snprintf( abort_text, abort_text_size, "Error occurred outside of any thread.\n" );
1087                __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
1088        }
1089}
1090
1091int kernel_abort_lastframe( void ) __attribute__ ((__nothrow__)) {
1092        return get_coroutine(kernelTLS.this_thread) == get_coroutine(mainThread) ? 4 : 2;
1093}
1094
1095static __spinlock_t kernel_debug_lock;
1096
1097extern "C" {
1098        void __cfaabi_bits_acquire() {
1099                lock( kernel_debug_lock __cfaabi_dbg_ctx2 );
1100        }
1101
1102        void __cfaabi_bits_release() {
1103                unlock( kernel_debug_lock );
1104        }
1105}
1106
1107//=============================================================================================
1108// Kernel Utilities
1109//=============================================================================================
1110//-----------------------------------------------------------------------------
1111// Locks
1112void  ?{}( semaphore & this, int count = 1 ) {
1113        (this.lock){};
1114        this.count = count;
1115        (this.waiting){};
1116}
1117void ^?{}(semaphore & this) {}
1118
1119bool P(semaphore & this) with( this ){
1120        lock( lock __cfaabi_dbg_ctx2 );
1121        count -= 1;
1122        if ( count < 0 ) {
1123                // queue current task
1124                append( waiting, kernelTLS.this_thread );
1125
1126                // atomically release spin lock and block
1127                unlock( lock );
1128                park( __cfaabi_dbg_ctx );
1129                return true;
1130        }
1131        else {
1132            unlock( lock );
1133            return false;
1134        }
1135}
1136
1137bool V(semaphore & this) with( this ) {
1138        $thread * thrd = 0p;
1139        lock( lock __cfaabi_dbg_ctx2 );
1140        count += 1;
1141        if ( count <= 0 ) {
1142                // remove task at head of waiting list
1143                thrd = pop_head( waiting );
1144        }
1145
1146        unlock( lock );
1147
1148        // make new owner
1149        unpark( thrd __cfaabi_dbg_ctx2 );
1150
1151        return thrd != 0p;
1152}
1153
1154bool V(semaphore & this, unsigned diff) with( this ) {
1155        $thread * thrd = 0p;
1156        lock( lock __cfaabi_dbg_ctx2 );
1157        int release = max(-count, (int)diff);
1158        count += diff;
1159        for(release) {
1160                unpark( pop_head( waiting ) __cfaabi_dbg_ctx2 );
1161        }
1162
1163        unlock( lock );
1164
1165        return thrd != 0p;
1166}
1167
1168//-----------------------------------------------------------------------------
1169// Global Queues
1170void doregister( cluster     & cltr ) {
1171        lock      ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2);
1172        push_front( __cfa_dbg_global_clusters.list, cltr );
1173        unlock    ( __cfa_dbg_global_clusters.lock );
1174}
1175
1176void unregister( cluster     & cltr ) {
1177        lock  ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2);
1178        remove( __cfa_dbg_global_clusters.list, cltr );
1179        unlock( __cfa_dbg_global_clusters.lock );
1180}
1181
1182void doregister( cluster * cltr, $thread & thrd ) {
1183        lock      (cltr->thread_list_lock __cfaabi_dbg_ctx2);
1184        cltr->nthreads += 1;
1185        push_front(cltr->threads, thrd);
1186        unlock    (cltr->thread_list_lock);
1187}
1188
1189void unregister( cluster * cltr, $thread & thrd ) {
1190        lock  (cltr->thread_list_lock __cfaabi_dbg_ctx2);
1191        remove(cltr->threads, thrd );
1192        cltr->nthreads -= 1;
1193        unlock(cltr->thread_list_lock);
1194}
1195
1196//-----------------------------------------------------------------------------
1197// Debug
1198__cfaabi_dbg_debug_do(
1199        extern "C" {
1200                void __cfaabi_dbg_record_lock(__spinlock_t & this, const char prev_name[]) {
1201                        this.prev_name = prev_name;
1202                        this.prev_thrd = kernelTLS.this_thread;
1203                }
1204
1205                void __cfaabi_dbg_record_thrd($thread & this, bool park, const char prev_name[]) {
1206                        if(park) {
1207                                this.park_caller   = prev_name;
1208                                this.park_stale    = false;
1209                        }
1210                        else {
1211                                this.unpark_caller = prev_name;
1212                                this.unpark_stale  = false;
1213                        }
1214                }
1215        }
1216)
1217
1218//-----------------------------------------------------------------------------
1219// Debug
1220bool threading_enabled(void) __attribute__((const)) {
1221        return true;
1222}
1223
1224//-----------------------------------------------------------------------------
1225// Statistics
1226#if !defined(__CFA_NO_STATISTICS__)
1227        void print_halts( processor & this ) {
1228                this.print_halts = true;
1229        }
1230#endif
1231// Local Variables: //
1232// mode: c //
1233// tab-width: 4 //
1234// End: //
Note: See TracBrowser for help on using the repository browser.