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

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

Fixed park unpark to support park as first step of main()
Fixes #170?

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