source: libcfa/src/concurrency/kernel.cfa @ 0f89d4f

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

Added Idle Sleep stats and removed extra call to unsafe_remove

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