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

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

Moved statistics to stats.cfa to combine ready Q stats and IO stats

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