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

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

Basic monitor implementation

  • Property mode set to 100644
File size: 13.0 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//Start and stop routine for the kernel, declared first to make sure they run first
18void kernel_startup(void)  __attribute__((constructor(101)));
19void kernel_shutdown(void) __attribute__((destructor(101)));
20
21//Header
22#include "kernel_private.h"
23
24//C Includes
25#include <stddef.h>
26extern "C" {
27#include <fenv.h>
28#include <sys/resource.h>
29}
30
31//CFA Includes
32#include "libhdr.h"
33
34//Private includes
35#define __CFA_INVOKE_PRIVATE__
36#include "invoke.h"
37
38//-----------------------------------------------------------------------------
39// Kernel storage
40#define KERNEL_STORAGE(T,X) static char X##_storage[sizeof(T)]
41
42KERNEL_STORAGE(processorCtx_t, systemProcessorCtx);
43KERNEL_STORAGE(cluster, systemCluster);
44KERNEL_STORAGE(processor, systemProcessor);
45KERNEL_STORAGE(thread, mainThread);
46KERNEL_STORAGE(machine_context_t, mainThread_context);
47
48cluster * systemCluster;
49processor * systemProcessor;
50thread * mainThread;
51
52//-----------------------------------------------------------------------------
53// Global state
54
55thread_local processor * this_processor;
56
57processor * get_this_processor() {
58        return this_processor;
59}
60
61coroutine * this_coroutine(void) {
62        return this_processor->current_coroutine;
63}
64
65thread * this_thread(void) {
66        return this_processor->current_thread;
67}
68
69//-----------------------------------------------------------------------------
70// Main thread construction
71struct current_stack_info_t {
72        machine_context_t ctx; 
73        unsigned int size;              // size of stack
74        void *base;                             // base of stack
75        void *storage;                  // pointer to stack
76        void *limit;                    // stack grows towards stack limit
77        void *context;                  // address of cfa_context_t
78        void *top;                              // address of top of storage
79};
80
81void ?{}( current_stack_info_t * this ) {
82        CtxGet( &this->ctx );
83        this->base = this->ctx.FP;
84        this->storage = this->ctx.SP;
85
86        rlimit r;
87        getrlimit( RLIMIT_STACK, &r);
88        this->size = r.rlim_cur;
89
90        this->limit = (void *)(((intptr_t)this->base) - this->size);
91        this->context = &mainThread_context_storage;
92        this->top = this->base;
93}
94
95void ?{}( coStack_t * this, current_stack_info_t * info) {
96        this->size = info->size;
97        this->storage = info->storage;
98        this->limit = info->limit;
99        this->base = info->base;
100        this->context = info->context;
101        this->top = info->top;
102        this->userStack = true;
103}
104
105void ?{}( coroutine * this, current_stack_info_t * info) {
106        (&this->stack){ info }; 
107        this->name = "Main Thread";
108        this->errno_ = 0;
109        this->state = Start;
110}
111
112void ?{}( thread * this, current_stack_info_t * info) {
113        (&this->c){ info };
114}
115
116//-----------------------------------------------------------------------------
117// Processor coroutine
118void ?{}(processorCtx_t * this, processor * proc) {
119        (&this->c){};
120        this->proc = proc;
121        proc->runner = this;
122}
123
124void ?{}(processorCtx_t * this, processor * proc, current_stack_info_t * info) {
125        (&this->c){ info };
126        this->proc = proc;
127        proc->runner = this;
128}
129
130void ?{}(processor * this) {
131        this{ systemCluster };
132}
133
134void ?{}(processor * this, cluster * cltr) {
135        this->cltr = cltr;
136        this->current_coroutine = NULL;
137        this->current_thread = NULL;
138        (&this->terminated){};
139        this->is_terminated = false;
140
141        start( this );
142}
143
144void ?{}(processor * this, cluster * cltr, processorCtx_t * runner) {
145        this->cltr = cltr;
146        this->current_coroutine = NULL;
147        this->current_thread = NULL;
148        (&this->terminated){};
149        this->is_terminated = false;
150
151        this->runner = runner;
152        LIB_DEBUG_PRINTF("Kernel : constructing processor context %p\n", runner);
153        runner{ this };
154}
155
156void ^?{}(processor * this) {
157        if( ! this->is_terminated ) {
158                LIB_DEBUG_PRINTF("Kernel : core %p signaling termination\n", this);
159                this->is_terminated = true;
160                wait( &this->terminated );
161        }
162}
163
164void ?{}(cluster * this) {
165        ( &this->ready_queue ){};
166        ( &this->lock ){};
167}
168
169void ^?{}(cluster * this) {
170       
171}
172
173//=============================================================================================
174// Kernel Scheduling logic
175//=============================================================================================
176//Main of the processor contexts
177void main(processorCtx_t * runner) {
178        processor * this = runner->proc;
179        LIB_DEBUG_PRINTF("Kernel : core %p starting\n", this);
180
181        thread * readyThread = NULL;
182        for( unsigned int spin_count = 0; ! this->is_terminated; spin_count++ ) 
183        {
184                readyThread = nextThread( this->cltr );
185
186                if(readyThread) 
187                {
188                        runThread(this, readyThread);
189
190                        //Some actions need to be taken from the kernel
191                        finishRunning(this);
192
193                        spin_count = 0;
194                } 
195                else 
196                {
197                        spin(this, &spin_count);
198                }               
199        }
200
201        LIB_DEBUG_PRINTF("Kernel : core %p unlocking thread\n", this);
202        signal( &this->terminated );
203        LIB_DEBUG_PRINTF("Kernel : core %p terminated\n", this);
204}
205
206// runThread runs a thread by context switching
207// from the processor coroutine to the target thread
208void runThread(processor * this, thread * dst) {
209        coroutine * proc_cor = get_coroutine(this->runner);
210        coroutine * thrd_cor = get_coroutine(dst);
211       
212        //Reset the terminating actions here
213        this->finish.action_code = No_Action;
214
215        //Update global state
216        this->current_thread = dst;
217
218        // Context Switch to the thread
219        ThreadCtxSwitch(proc_cor, thrd_cor);
220        // when ThreadCtxSwitch returns we are back in the processor coroutine
221}
222
223// Once a thread has finished running, some of
224// its final actions must be executed from the kernel
225void finishRunning(processor * this) {
226        if( this->finish.action_code == Release ) {
227                unlock( this->finish.lock );
228        }
229        else if( this->finish.action_code == Schedule ) {
230                ScheduleThread( this->finish.thrd );
231        }
232        else if( this->finish.action_code == Release_Schedule ) {
233                unlock( this->finish.lock );           
234                ScheduleThread( this->finish.thrd );
235        }
236        else {
237                assert(this->finish.action_code == No_Action);
238        }
239}
240
241// Handles spinning logic
242// TODO : find some strategy to put cores to sleep after some time
243void spin(processor * this, unsigned int * spin_count) {
244        (*spin_count)++;
245}
246
247// Context invoker for processors
248// This is the entry point for processors (kernel threads)
249// It effectively constructs a coroutine by stealing the pthread stack
250void * CtxInvokeProcessor(void * arg) {
251        processor * proc = (processor *) arg;
252        this_processor = proc;
253        // SKULLDUGGERY: We want to create a context for the processor coroutine
254        // which is needed for the 2-step context switch. However, there is no reason
255        // to waste the perfectly valid stack create by pthread.
256        current_stack_info_t info;
257        machine_context_t ctx;
258        info.context = &ctx;
259        processorCtx_t proc_cor_storage = { proc, &info };
260
261        LIB_DEBUG_PRINTF("Coroutine : created stack %p\n", proc_cor_storage.c.stack.base);
262
263        //Set global state
264        proc->current_coroutine = &proc->runner->c;
265        proc->current_thread = NULL;
266
267        //We now have a proper context from which to schedule threads
268        LIB_DEBUG_PRINTF("Kernel : core %p created (%p, %p)\n", proc, proc->runner, &ctx);
269
270        // SKULLDUGGERY: Since the coroutine doesn't have its own stack, we can't
271        // resume it to start it like it normally would, it will just context switch
272        // back to here. Instead directly call the main since we already are on the
273        // appropriate stack.
274        proc_cor_storage.c.state = Active;
275      main( &proc_cor_storage );
276      proc_cor_storage.c.state = Halted;
277
278        // Main routine of the core returned, the core is now fully terminated
279        LIB_DEBUG_PRINTF("Kernel : core %p main ended (%p)\n", proc, proc->runner);     
280
281        return NULL;
282}
283
284void start(processor * this) {
285        LIB_DEBUG_PRINTF("Kernel : Starting core %p\n", this);
286       
287        // pthread_attr_t attributes;
288        // pthread_attr_init( &attributes );
289
290        pthread_create( &this->kernel_thread, NULL, CtxInvokeProcessor, (void*)this );
291
292        // pthread_attr_destroy( &attributes );
293
294        LIB_DEBUG_PRINTF("Kernel : core %p started\n", this);   
295}
296
297//-----------------------------------------------------------------------------
298// Scheduler routines
299void ScheduleThread( thread * thrd ) {
300        assertf( thrd->next == NULL, "Expected null got %p", thrd->next );
301       
302        lock( &systemProcessor->cltr->lock );
303        append( &systemProcessor->cltr->ready_queue, thrd );
304        unlock( &systemProcessor->cltr->lock );
305}
306
307thread * nextThread(cluster * this) {
308        lock( &this->lock );
309        thread * head = pop_head( &this->ready_queue );
310        unlock( &this->lock );
311        return head;
312}
313
314void ScheduleInternal() {
315        suspend();
316}
317
318void ScheduleInternal( spinlock * lock ) {
319        get_this_processor()->finish.action_code = Release;
320        get_this_processor()->finish.lock = lock;
321        suspend();
322}
323
324void ScheduleInternal( thread * thrd ) {
325        get_this_processor()->finish.action_code = Schedule;
326        get_this_processor()->finish.thrd = thrd;
327        suspend();
328}
329
330void ScheduleInternal( spinlock * lock, thread * thrd ) {
331        get_this_processor()->finish.action_code = Release_Schedule;
332        get_this_processor()->finish.lock = lock;
333        get_this_processor()->finish.thrd = thrd;
334        suspend();
335}
336
337//-----------------------------------------------------------------------------
338// Kernel boot procedures
339void kernel_startup(void) {
340        LIB_DEBUG_PRINTF("Kernel : Starting\n");       
341
342        // Start by initializing the main thread
343        // SKULLDUGGERY: the mainThread steals the process main thread
344        // which will then be scheduled by the systemProcessor normally
345        mainThread = (thread *)&mainThread_storage;
346        current_stack_info_t info;
347        mainThread{ &info };
348
349        // Initialize the system cluster
350        systemCluster = (cluster *)&systemCluster_storage;
351        systemCluster{};
352
353        // Initialize the system processor and the system processor ctx
354        // (the coroutine that contains the processing control flow)
355        systemProcessor = (processor *)&systemProcessor_storage;
356        systemProcessor{ systemCluster, (processorCtx_t *)&systemProcessorCtx_storage };
357
358        // Add the main thread to the ready queue
359        // once resume is called on systemProcessor->ctx the mainThread needs to be scheduled like any normal thread
360        ScheduleThread(mainThread);
361
362        //initialize the global state variables
363        this_processor = systemProcessor;
364        this_processor->current_thread = mainThread;
365        this_processor->current_coroutine = &mainThread->c;
366
367        // SKULLDUGGERY: Force a context switch to the system processor to set the main thread's context to the current UNIX
368        // context. Hence, the main thread does not begin through CtxInvokeThread, like all other threads. The trick here is that
369        // mainThread is on the ready queue when this call is made.
370        resume(systemProcessor->runner);
371
372
373
374        // THE SYSTEM IS NOW COMPLETELY RUNNING
375        LIB_DEBUG_PRINTF("Kernel : Started\n--------------------------------------------------\n\n");
376}
377
378void kernel_shutdown(void) {
379        LIB_DEBUG_PRINTF("\n--------------------------------------------------\nKernel : Shutting down\n");
380
381        // SKULLDUGGERY: Notify the systemProcessor it needs to terminates.
382        // When its coroutine terminates, it return control to the mainThread
383        // which is currently here
384        systemProcessor->is_terminated = true;
385        suspend();
386
387        // THE SYSTEM IS NOW COMPLETELY STOPPED
388
389        // Destroy the system processor and its context in reverse order of construction
390        // These were manually constructed so we need manually destroy them
391        ^(systemProcessor->runner){};
392        ^(systemProcessor){};
393
394        // Final step, destroy the main thread since it is no longer needed
395        // Since we provided a stack to this taxk it will not destroy anything
396        ^(mainThread){};
397
398        LIB_DEBUG_PRINTF("Kernel : Shutdown complete\n");       
399}
400
401//-----------------------------------------------------------------------------
402// Locks
403void ?{}( spinlock * this ) {
404        this->lock = 0;
405}
406void ^?{}( spinlock * this ) {
407
408}
409
410void lock( spinlock * this ) {
411        for ( unsigned int i = 1;; i += 1 ) {
412                if ( this->lock == 0 && __sync_lock_test_and_set_4( &this->lock, 1 ) == 0 ) break;
413        }
414}
415
416void unlock( spinlock * this ) {
417        __sync_lock_release_4( &this->lock );
418}
419
420void ?{}( signal_once * this ) {
421        this->condition = false;
422}
423void ^?{}( signal_once * this ) {
424
425}
426
427void wait( signal_once * this ) {
428        lock( &this->lock );
429        if( !this->condition ) {
430                append( &this->blocked, this_thread() );
431                ScheduleInternal( &this->lock );
432                lock( &this->lock );
433        }
434        unlock( &this->lock );
435}
436
437void signal( signal_once * this ) {
438        lock( &this->lock );
439        {
440                this->condition = true;
441
442                thread * it;
443                while( it = pop_head( &this->blocked) ) {
444                        ScheduleThread( it );
445                }
446        }
447        unlock( &this->lock );
448}
449
450//-----------------------------------------------------------------------------
451// Queues
452void ?{}( simple_thread_list * this ) {
453        this->head = NULL;
454        this->tail = &this->head;
455}
456
457void append( simple_thread_list * this, thread * t ) {
458        assert( t->next == NULL );
459        assert(this->tail != NULL);
460        *this->tail = t;
461        this->tail = &t->next;
462        assert(this->tail != NULL);
463}
464
465thread * pop_head( simple_thread_list * this ) {
466        assert(this->tail != NULL);
467        thread * head = this->head;
468        if( head ) {
469                this->head = head->next;
470                if( !head->next ) {
471                        this->tail = &this->head;
472                }
473                head->next = NULL;
474        }       
475        assert(this->tail != NULL);
476        return head;
477}
478// Local Variables: //
479// mode: c //
480// tab-width: 4 //
481// End: //
Note: See TracBrowser for help on using the repository browser.