source: src/libcfa/concurrency/kernel.c @ fa21ac9

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since fa21ac9 was fa21ac9, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Added alarm list to the system processor in the kernel

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