source: libcfa/src/concurrency/kernel.cfa @ 7458fea

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

Fixed ready_queue working with 0/1 processors on cluster

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