source: libcfa/src/concurrency/kernel.cfa @ 04b4a71

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 04b4a71 was ada0246d, checked in by Peter A. Buhr <pabuhr@…>, 4 years ago

create heap.hfa, use it in malloc.h, and cleanup includes with respect to extern "C"

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