source: libcfa/src/concurrency/kernel.cfa @ 7df014f

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

Implemented basic io_uring setup and poller

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