source: src/libcfa/concurrency/kernel.c @ 0b33412

aaron-thesisarm-ehcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 0b33412 was 0b33412, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

Updated tests to use verify instead of assert

  • Property mode set to 100644
File size: 19.5 KB
Line 
1//                              -*- Mode: CFA -*-
2//
3// Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo
4//
5// The contents of this file are covered under the licence agreement in the
6// file "LICENCE" distributed with Cforall.
7//
8// kernel.c --
9//
10// Author           : Thierry Delisle
11// Created On       : Tue Jan 17 12:27:26 2017
12// Last Modified By : Thierry Delisle
13// Last Modified On : --
14// Update Count     : 0
15//
16
17#include "startup.h"
18
19//Start and stop routine for the kernel, declared first to make sure they run first
20void kernel_startup(void)  __attribute__(( constructor( STARTUP_PRIORITY_KERNEL ) ));
21void kernel_shutdown(void) __attribute__(( destructor ( STARTUP_PRIORITY_KERNEL ) ));
22
23//Header
24#include "kernel_private.h"
25
26//C Includes
27#include <stddef.h>
28extern "C" {
29#include <stdio.h>
30#include <fenv.h>
31#include <sys/resource.h>
32#include <signal.h>
33#include <unistd.h>
34}
35
36//CFA Includes
37#include "libhdr.h"
38#include "preemption.h"
39
40//Private includes
41#define __CFA_INVOKE_PRIVATE__
42#include "invoke.h"
43
44//-----------------------------------------------------------------------------
45// Kernel storage
46#define KERNEL_STORAGE(T,X) static char X##_storage[sizeof(T)]
47
48KERNEL_STORAGE(processorCtx_t, systemProcessorCtx);
49KERNEL_STORAGE(cluster, systemCluster);
50KERNEL_STORAGE(system_proc_t, systemProcessor);
51KERNEL_STORAGE(thread_desc, mainThread);
52KERNEL_STORAGE(machine_context_t, mainThread_context);
53
54cluster * systemCluster;
55system_proc_t * systemProcessor;
56thread_desc * mainThread;
57
58//-----------------------------------------------------------------------------
59// Global state
60
61volatile thread_local processor * this_processor;
62volatile thread_local unsigned short disable_preempt_count;
63
64coroutine_desc * this_coroutine(void) {
65        return this_processor->current_coroutine;
66}
67
68thread_desc * this_thread(void) {
69        return this_processor->current_thread;
70}
71
72//-----------------------------------------------------------------------------
73// Main thread construction
74struct current_stack_info_t {
75        machine_context_t ctx; 
76        unsigned int size;              // size of stack
77        void *base;                             // base of stack
78        void *storage;                  // pointer to stack
79        void *limit;                    // stack grows towards stack limit
80        void *context;                  // address of cfa_context_t
81        void *top;                              // address of top of storage
82};
83
84void ?{}( current_stack_info_t * this ) {
85        CtxGet( &this->ctx );
86        this->base = this->ctx.FP;
87        this->storage = this->ctx.SP;
88
89        rlimit r;
90        getrlimit( RLIMIT_STACK, &r);
91        this->size = r.rlim_cur;
92
93        this->limit = (void *)(((intptr_t)this->base) - this->size);
94        this->context = &mainThread_context_storage;
95        this->top = this->base;
96}
97
98void ?{}( coStack_t * this, current_stack_info_t * info) {
99        this->size = info->size;
100        this->storage = info->storage;
101        this->limit = info->limit;
102        this->base = info->base;
103        this->context = info->context;
104        this->top = info->top;
105        this->userStack = true;
106}
107
108void ?{}( coroutine_desc * this, current_stack_info_t * info) {
109        (&this->stack){ info }; 
110        this->name = "Main Thread";
111        this->errno_ = 0;
112        this->state = Start;
113}
114
115void ?{}( thread_desc * this, current_stack_info_t * info) {
116        (&this->cor){ info };
117}
118
119//-----------------------------------------------------------------------------
120// Processor coroutine
121void ?{}(processorCtx_t * this, processor * proc) {
122        (&this->__cor){ "Processor" };
123        this->proc = proc;
124        proc->runner = this;
125}
126
127void ?{}(processorCtx_t * this, processor * proc, current_stack_info_t * info) {
128        (&this->__cor){ info };
129        this->proc = proc;
130        proc->runner = this;
131}
132
133void ?{}(processor * this) {
134        this{ systemCluster };
135}
136
137void ?{}(processor * this, cluster * cltr) {
138        this->cltr = cltr;
139        this->current_coroutine = NULL;
140        this->current_thread = NULL;
141        (&this->terminated){};
142        this->is_terminated = false;
143        this->preemption_alarm = NULL;
144        this->preemption = default_preemption();
145        this->pending_preemption = false;
146
147        start( this );
148}
149
150void ?{}(processor * this, cluster * cltr, processorCtx_t * runner) {
151        this->cltr = cltr;
152        this->current_coroutine = NULL;
153        this->current_thread = NULL;
154        (&this->terminated){};
155        this->is_terminated = false;
156        this->preemption_alarm = NULL;
157        this->preemption = default_preemption();
158        this->pending_preemption = false;
159        this->kernel_thread = pthread_self();
160
161        this->runner = runner;
162        LIB_DEBUG_PRINT_SAFE("Kernel : constructing system processor context %p\n", runner);
163        runner{ this };
164}
165
166LIB_DEBUG_DO( bool validate( alarm_list_t * this ); )
167
168void ?{}(system_proc_t * this, cluster * cltr, processorCtx_t * runner) {
169        (&this->alarms){};
170        (&this->alarm_lock){};
171        this->pending_alarm = false;
172
173        (&this->proc){ cltr, runner };
174
175        verify( validate( &this->alarms ) );
176}
177
178void ^?{}(processor * this) {
179        if( ! this->is_terminated ) {
180                LIB_DEBUG_PRINT_SAFE("Kernel : core %p signaling termination\n", this);
181                this->is_terminated = true;
182                wait( &this->terminated );
183        }
184}
185
186void ?{}(cluster * this) {
187        ( &this->ready_queue ){};
188        ( &this->lock ){};
189}
190
191void ^?{}(cluster * this) {
192       
193}
194
195//=============================================================================================
196// Kernel Scheduling logic
197//=============================================================================================
198//Main of the processor contexts
199void main(processorCtx_t * runner) {
200        processor * this = runner->proc;
201
202        LIB_DEBUG_PRINT_SAFE("Kernel : core %p starting\n", this);
203
204        {
205                // Setup preemption data
206                preemption_scope scope = { this };
207
208                LIB_DEBUG_PRINT_SAFE("Kernel : core %p started\n", this);
209
210                thread_desc * readyThread = NULL;
211                for( unsigned int spin_count = 0; ! this->is_terminated; spin_count++ ) 
212                {
213                        readyThread = nextThread( this->cltr );
214
215                        if(readyThread)
216                        {
217                                verify( disable_preempt_count > 0 );
218
219                                runThread(this, readyThread);
220
221                                verify( disable_preempt_count > 0 );
222
223                                //Some actions need to be taken from the kernel
224                                finishRunning(this);
225
226                                spin_count = 0;
227                        }
228                        else
229                        {
230                                spin(this, &spin_count);
231                        }
232                }
233
234                LIB_DEBUG_PRINT_SAFE("Kernel : core %p stopping\n", this);
235        }
236
237        signal( &this->terminated );
238        LIB_DEBUG_PRINT_SAFE("Kernel : core %p terminated\n", this);
239}
240
241// runThread runs a thread by context switching
242// from the processor coroutine to the target thread
243void runThread(processor * this, thread_desc * dst) {
244        coroutine_desc * proc_cor = get_coroutine(this->runner);
245        coroutine_desc * thrd_cor = get_coroutine(dst);
246       
247        //Reset the terminating actions here
248        this->finish.action_code = No_Action;
249
250        //Update global state
251        this->current_thread = dst;
252
253        // Context Switch to the thread
254        ThreadCtxSwitch(proc_cor, thrd_cor);
255        // when ThreadCtxSwitch returns we are back in the processor coroutine
256}
257
258// Once a thread has finished running, some of
259// its final actions must be executed from the kernel
260void finishRunning(processor * this) {
261        if( this->finish.action_code == Release ) {
262                unlock( this->finish.lock );
263        }
264        else if( this->finish.action_code == Schedule ) {
265                ScheduleThread( this->finish.thrd );
266        }
267        else if( this->finish.action_code == Release_Schedule ) {
268                unlock( this->finish.lock );           
269                ScheduleThread( this->finish.thrd );
270        }
271        else if( this->finish.action_code == Release_Multi ) {
272                for(int i = 0; i < this->finish.lock_count; i++) {
273                        unlock( this->finish.locks[i] );
274                }
275        }
276        else if( this->finish.action_code == Release_Multi_Schedule ) {
277                for(int i = 0; i < this->finish.lock_count; i++) {
278                        unlock( this->finish.locks[i] );
279                }
280                for(int i = 0; i < this->finish.thrd_count; i++) {
281                        ScheduleThread( this->finish.thrds[i] );
282                }
283        }
284        else {
285                assert(this->finish.action_code == No_Action);
286        }
287}
288
289// Handles spinning logic
290// TODO : find some strategy to put cores to sleep after some time
291void spin(processor * this, unsigned int * spin_count) {
292        (*spin_count)++;
293}
294
295// Context invoker for processors
296// This is the entry point for processors (kernel threads)
297// It effectively constructs a coroutine by stealing the pthread stack
298void * CtxInvokeProcessor(void * arg) {
299        processor * proc = (processor *) arg;
300        this_processor = proc;
301        disable_preempt_count = 1;
302        // SKULLDUGGERY: We want to create a context for the processor coroutine
303        // which is needed for the 2-step context switch. However, there is no reason
304        // to waste the perfectly valid stack create by pthread.
305        current_stack_info_t info;
306        machine_context_t ctx;
307        info.context = &ctx;
308        processorCtx_t proc_cor_storage = { proc, &info };
309
310        LIB_DEBUG_PRINT_SAFE("Coroutine : created stack %p\n", proc_cor_storage.__cor.stack.base);
311
312        //Set global state
313        proc->current_coroutine = &proc->runner->__cor;
314        proc->current_thread = NULL;
315
316        //We now have a proper context from which to schedule threads
317        LIB_DEBUG_PRINT_SAFE("Kernel : core %p created (%p, %p)\n", proc, proc->runner, &ctx);
318
319        // SKULLDUGGERY: Since the coroutine doesn't have its own stack, we can't
320        // resume it to start it like it normally would, it will just context switch
321        // back to here. Instead directly call the main since we already are on the
322        // appropriate stack.
323        proc_cor_storage.__cor.state = Active;
324        main( &proc_cor_storage );
325        proc_cor_storage.__cor.state = Halted;
326
327        // Main routine of the core returned, the core is now fully terminated
328        LIB_DEBUG_PRINT_SAFE("Kernel : core %p main ended (%p)\n", proc, proc->runner); 
329
330        return NULL;
331}
332
333void start(processor * this) {
334        LIB_DEBUG_PRINT_SAFE("Kernel : Starting core %p\n", this);
335
336        // SIGALRM must only be caught by the system processor
337        sigset_t old_mask;
338        bool is_system_proc = this_processor == &systemProcessor->proc;
339        if ( is_system_proc ) {
340                // Child kernel-thread inherits the signal mask from the parent kernel-thread. So one special case for the
341                // system processor creating the user processor => toggle the blocking SIGALRM on system processor, create user
342                // processor, and toggle back (below) previous signal mask of the system processor.
343
344                sigset_t new_mask;
345                sigemptyset( &new_mask );
346                sigemptyset( &old_mask );
347                sigaddset( &new_mask, SIGALRM );
348
349                if ( sigprocmask( SIG_BLOCK, &new_mask, &old_mask ) == -1 ) {
350                        abortf( "internal error, sigprocmask" );
351                }
352
353                assert( ! sigismember( &old_mask, SIGALRM ) );
354        }
355
356        pthread_create( &this->kernel_thread, NULL, CtxInvokeProcessor, (void*)this );
357
358        // Toggle back previous signal mask of system processor.
359        if ( is_system_proc ) {
360                if ( sigprocmask( SIG_SETMASK, &old_mask, NULL ) == -1 ) {
361                        abortf( "internal error, sigprocmask" );
362                } // if
363        } // if
364
365        LIB_DEBUG_PRINT_SAFE("Kernel : core %p started\n", this);       
366}
367
368//-----------------------------------------------------------------------------
369// Scheduler routines
370void ScheduleThread( thread_desc * thrd ) {
371        if( !thrd ) return;
372
373        verifyf( thrd->next == NULL, "Expected null got %p", thrd->next );
374       
375        lock( &systemProcessor->proc.cltr->lock );
376        append( &systemProcessor->proc.cltr->ready_queue, thrd );
377        unlock( &systemProcessor->proc.cltr->lock );
378}
379
380thread_desc * nextThread(cluster * this) {
381        lock( &this->lock );
382        thread_desc * head = pop_head( &this->ready_queue );
383        unlock( &this->lock );
384        return head;
385}
386
387void BlockInternal() {
388        disable_interrupts();
389        verify( disable_preempt_count > 0 );
390        suspend();
391        verify( disable_preempt_count > 0 );
392        enable_interrupts( __PRETTY_FUNCTION__ );
393}
394
395void BlockInternal( spinlock * lock ) {
396        disable_interrupts();
397        this_processor->finish.action_code = Release;
398        this_processor->finish.lock = lock;
399
400        verify( disable_preempt_count > 0 );
401        suspend();
402        verify( disable_preempt_count > 0 );
403
404        enable_interrupts( __PRETTY_FUNCTION__ );
405}
406
407void BlockInternal( thread_desc * thrd ) {
408        disable_interrupts();
409        this_processor->finish.action_code = Schedule;
410        this_processor->finish.thrd = thrd;
411
412        verify( disable_preempt_count > 0 );
413        suspend();
414        verify( disable_preempt_count > 0 );
415
416        enable_interrupts( __PRETTY_FUNCTION__ );
417}
418
419void BlockInternal( spinlock * lock, thread_desc * thrd ) {
420        disable_interrupts();
421        this_processor->finish.action_code = Release_Schedule;
422        this_processor->finish.lock = lock;
423        this_processor->finish.thrd = thrd;
424
425        verify( disable_preempt_count > 0 );
426        suspend();
427        verify( disable_preempt_count > 0 );
428
429        enable_interrupts( __PRETTY_FUNCTION__ );
430}
431
432void BlockInternal(spinlock ** locks, unsigned short count) {
433        disable_interrupts();
434        this_processor->finish.action_code = Release_Multi;
435        this_processor->finish.locks = locks;
436        this_processor->finish.lock_count = count;
437
438        verify( disable_preempt_count > 0 );
439        suspend();
440        verify( disable_preempt_count > 0 );
441
442        enable_interrupts( __PRETTY_FUNCTION__ );
443}
444
445void BlockInternal(spinlock ** locks, unsigned short lock_count, thread_desc ** thrds, unsigned short thrd_count) {
446        disable_interrupts();
447        this_processor->finish.action_code = Release_Multi_Schedule;
448        this_processor->finish.locks = locks;
449        this_processor->finish.lock_count = lock_count;
450        this_processor->finish.thrds = thrds;
451        this_processor->finish.thrd_count = thrd_count;
452
453        verify( disable_preempt_count > 0 );
454        suspend();
455        verify( disable_preempt_count > 0 );
456
457        enable_interrupts( __PRETTY_FUNCTION__ );
458}
459
460//=============================================================================================
461// Kernel Setup logic
462//=============================================================================================
463//-----------------------------------------------------------------------------
464// Kernel boot procedures
465void kernel_startup(void) {
466        LIB_DEBUG_PRINT_SAFE("Kernel : Starting\n");   
467
468        // Start by initializing the main thread
469        // SKULLDUGGERY: the mainThread steals the process main thread
470        // which will then be scheduled by the systemProcessor normally
471        mainThread = (thread_desc *)&mainThread_storage;
472        current_stack_info_t info;
473        mainThread{ &info };
474
475        LIB_DEBUG_PRINT_SAFE("Kernel : Main thread ready\n");
476
477        // Initialize the system cluster
478        systemCluster = (cluster *)&systemCluster_storage;
479        systemCluster{};
480
481        LIB_DEBUG_PRINT_SAFE("Kernel : System cluster ready\n");
482
483        // Initialize the system processor and the system processor ctx
484        // (the coroutine that contains the processing control flow)
485        systemProcessor = (system_proc_t *)&systemProcessor_storage;
486        systemProcessor{ systemCluster, (processorCtx_t *)&systemProcessorCtx_storage };
487
488        // Add the main thread to the ready queue
489        // once resume is called on systemProcessor->runner the mainThread needs to be scheduled like any normal thread
490        ScheduleThread(mainThread);
491
492        //initialize the global state variables
493        this_processor = &systemProcessor->proc;
494        this_processor->current_thread = mainThread;
495        this_processor->current_coroutine = &mainThread->cor;
496        disable_preempt_count = 1;
497
498        // Enable preemption
499        kernel_start_preemption();
500
501        // SKULLDUGGERY: Force a context switch to the system processor to set the main thread's context to the current UNIX
502        // context. Hence, the main thread does not begin through CtxInvokeThread, like all other threads. The trick here is that
503        // mainThread is on the ready queue when this call is made.
504        resume( systemProcessor->proc.runner );
505
506
507
508        // THE SYSTEM IS NOW COMPLETELY RUNNING
509        LIB_DEBUG_PRINT_SAFE("Kernel : Started\n--------------------------------------------------\n\n");
510
511        enable_interrupts( __PRETTY_FUNCTION__ );
512}
513
514void kernel_shutdown(void) {
515        LIB_DEBUG_PRINT_SAFE("\n--------------------------------------------------\nKernel : Shutting down\n");
516
517        disable_interrupts();
518
519        // SKULLDUGGERY: Notify the systemProcessor it needs to terminates.
520        // When its coroutine terminates, it return control to the mainThread
521        // which is currently here
522        systemProcessor->proc.is_terminated = true;
523        suspend();
524
525        // THE SYSTEM IS NOW COMPLETELY STOPPED
526
527        // Disable preemption
528        kernel_stop_preemption();
529
530        // Destroy the system processor and its context in reverse order of construction
531        // These were manually constructed so we need manually destroy them
532        ^(systemProcessor->proc.runner){};
533        ^(systemProcessor){};
534
535        // Final step, destroy the main thread since it is no longer needed
536        // Since we provided a stack to this taxk it will not destroy anything
537        ^(mainThread){};
538
539        LIB_DEBUG_PRINT_SAFE("Kernel : Shutdown complete\n");   
540}
541
542static spinlock kernel_abort_lock;
543static spinlock kernel_debug_lock;
544static bool kernel_abort_called = false;
545
546void * kernel_abort    (void) __attribute__ ((__nothrow__)) {
547        // abort cannot be recursively entered by the same or different processors because all signal handlers return when
548        // the globalAbort flag is true.
549        lock( &kernel_abort_lock );
550
551        // first task to abort ?
552        if ( !kernel_abort_called ) {                   // not first task to abort ?
553                kernel_abort_called = true;
554                unlock( &kernel_abort_lock );
555        } 
556        else {
557                unlock( &kernel_abort_lock );
558               
559                sigset_t mask;
560                sigemptyset( &mask );
561                sigaddset( &mask, SIGALRM );                    // block SIGALRM signals
562                sigaddset( &mask, SIGUSR1 );                    // block SIGUSR1 signals
563                sigsuspend( &mask );                            // block the processor to prevent further damage during abort
564                _exit( EXIT_FAILURE );                          // if processor unblocks before it is killed, terminate it             
565        }
566
567        return this_thread();
568}
569
570void kernel_abort_msg( void * kernel_data, char * abort_text, int abort_text_size ) {
571        thread_desc * thrd = kernel_data;
572
573        int len = snprintf( abort_text, abort_text_size, "Error occurred while executing task %.256s (%p)", thrd->cor.name, thrd );
574        __lib_debug_write( STDERR_FILENO, abort_text, len );
575
576        if ( thrd != this_coroutine() ) {
577                len = snprintf( abort_text, abort_text_size, " in coroutine %.256s (%p).\n", this_coroutine()->name, this_coroutine() );
578                __lib_debug_write( STDERR_FILENO, abort_text, len );
579        } 
580        else {
581                __lib_debug_write( STDERR_FILENO, ".\n", 2 );
582        }
583}
584
585extern "C" {
586        void __lib_debug_acquire() {
587                lock(&kernel_debug_lock);
588        }
589
590        void __lib_debug_release() {
591                unlock(&kernel_debug_lock);
592        }
593}
594
595//=============================================================================================
596// Kernel Utilities
597//=============================================================================================
598//-----------------------------------------------------------------------------
599// Locks
600void ?{}( spinlock * this ) {
601        this->lock = 0;
602}
603void ^?{}( spinlock * this ) {
604
605}
606
607bool try_lock( spinlock * this ) {
608        return this->lock == 0 && __sync_lock_test_and_set_4( &this->lock, 1 ) == 0;
609}
610
611void lock( spinlock * this ) {
612        for ( unsigned int i = 1;; i += 1 ) {
613                if ( this->lock == 0 && __sync_lock_test_and_set_4( &this->lock, 1 ) == 0 ) break;
614        }
615}
616
617void unlock( spinlock * this ) {
618        __sync_lock_release_4( &this->lock );
619}
620
621void ?{}( signal_once * this ) {
622        this->cond = false;
623}
624void ^?{}( signal_once * this ) {
625
626}
627
628void wait( signal_once * this ) {
629        lock( &this->lock );
630        if( !this->cond ) {
631                append( &this->blocked, this_thread() );
632                BlockInternal( &this->lock );
633        }
634        else {
635                unlock( &this->lock );
636        }
637}
638
639void signal( signal_once * this ) {
640        lock( &this->lock );
641        {
642                this->cond = true;
643
644                disable_interrupts();
645                thread_desc * it;
646                while( it = pop_head( &this->blocked) ) {
647                        ScheduleThread( it );
648                }
649                enable_interrupts( __PRETTY_FUNCTION__ );
650        }
651        unlock( &this->lock );
652}
653
654//-----------------------------------------------------------------------------
655// Queues
656void ?{}( __thread_queue_t * this ) {
657        this->head = NULL;
658        this->tail = &this->head;
659}
660
661void append( __thread_queue_t * this, thread_desc * t ) {
662        verify(this->tail != NULL);
663        *this->tail = t;
664        this->tail = &t->next;
665}
666
667thread_desc * pop_head( __thread_queue_t * this ) {
668        thread_desc * head = this->head;
669        if( head ) {
670                this->head = head->next;
671                if( !head->next ) {
672                        this->tail = &this->head;
673                }
674                head->next = NULL;
675        }       
676        return head;
677}
678
679void ?{}( __condition_stack_t * this ) {
680        this->top = NULL;
681}
682
683void push( __condition_stack_t * this, __condition_criterion_t * t ) {
684        verify( !t->next );
685        t->next = this->top;
686        this->top = t;
687}
688
689__condition_criterion_t * pop( __condition_stack_t * this ) {
690        __condition_criterion_t * top = this->top;
691        if( top ) {
692                this->top = top->next;
693                top->next = NULL;
694        }       
695        return top;
696}
697// Local Variables: //
698// mode: c //
699// tab-width: 4 //
700// End: //
Note: See TracBrowser for help on using the repository browser.