source: src/libcfa/concurrency/kernel.c@ 9d85038

ADT aaron-thesis arm-eh ast-experimental cleanup-dtors deferred_resn demangler enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr new-env no_list persistent-indexer pthread-emulation qualifiedEnum resolv-new with_gc
Last change on this file since 9d85038 was 82ff5845, checked in by Thierry Delisle <tdelisle@…>, 8 years ago

First implementation of preemption, does not appear to work with scheduling

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