source: src/libcfa/concurrency/preemption.c@ f4a6101

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 f4a6101 was 258e6ad5, checked in by Peter A. Buhr <pabuhr@…>, 8 years ago

fix ARM context-switch build

  • Property mode set to 100644
File size: 16.2 KB
RevLine 
[c81ebf9]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// signal.c --
8//
9// Author : Thierry Delisle
10// Created On : Mon Jun 5 14:20:42 2017
[6b0b624]11// Last Modified By : Peter A. Buhr
[258e6ad5]12// Last Modified On : Tue Jan 23 17:59:30 2018
13// Update Count : 7
[c81ebf9]14//
15
16#include "preemption.h"
17
[b158d8f]18#define ftype `ftype`
[c81ebf9]19extern "C" {
[82ff5845]20#include <errno.h>
[1c273d0]21#include <execinfo.h>
[4e6fb8e]22#define __USE_GNU
[c81ebf9]23#include <signal.h>
[4e6fb8e]24#undef __USE_GNU
[82ff5845]25#include <stdio.h>
26#include <string.h>
27#include <unistd.h>
[c81ebf9]28}
[b158d8f]29#undef ftype
[1c273d0]30
31#ifdef __USE_STREAM__
32#include "fstream"
33#endif
[82ff5845]34
[969b3fe]35//TODO move to defaults
[82ff5845]36#define __CFA_DEFAULT_PREEMPTION__ 10000
[c81ebf9]37
[969b3fe]38//TODO move to defaults
[c81ebf9]39__attribute__((weak)) unsigned int default_preemption() {
40 return __CFA_DEFAULT_PREEMPTION__;
41}
42
[969b3fe]43// Short hands for signal context information
[82ff5845]44#define __CFA_SIGCXT__ ucontext_t *
45#define __CFA_SIGPARMS__ __attribute__((unused)) int sig, __attribute__((unused)) siginfo_t *sfp, __attribute__((unused)) __CFA_SIGCXT__ cxt
46
[969b3fe]47// FwdDeclarations : timeout handlers
[c81ebf9]48static void preempt( processor * this );
49static void timeout( thread_desc * this );
50
[969b3fe]51// FwdDeclarations : Signal handlers
[82ff5845]52void sigHandler_ctxSwitch( __CFA_SIGPARMS__ );
[1c273d0]53void sigHandler_segv ( __CFA_SIGPARMS__ );
54void sigHandler_abort ( __CFA_SIGPARMS__ );
[82ff5845]55
[969b3fe]56// FwdDeclarations : sigaction wrapper
[82ff5845]57static void __kernel_sigaction( int sig, void (*handler)(__CFA_SIGPARMS__), int flags );
[cd17862]58
[969b3fe]59// FwdDeclarations : alarm thread main
60void * alarm_loop( __attribute__((unused)) void * args );
61
62// Machine specific register name
[b158d8f]63#if defined(__x86_64__)
[cd17862]64#define CFA_REG_IP REG_RIP
[b158d8f]65#elif defined(__i386__)
[cd17862]66#define CFA_REG_IP REG_EIP
[b158d8f]67#elif defined(__ARM_ARCH__)
68#define CFA_REG_IP REG_R15
[cd17862]69#endif
70
[969b3fe]71KERNEL_STORAGE(event_kernel_t, event_kernel); // private storage for event kernel
72event_kernel_t * event_kernel; // kernel public handle to even kernel
73static pthread_t alarm_thread; // pthread handle to alarm thread
74
[9236060]75void ?{}(event_kernel_t & this) {
76 (this.alarms){};
77 (this.lock){};
[969b3fe]78}
[82ff5845]79
[c81ebf9]80//=============================================================================================
81// Kernel Preemption logic
82//=============================================================================================
83
[969b3fe]84// Get next expired node
85static inline alarm_node_t * get_expired( alarm_list_t * alarms, __cfa_time_t currtime ) {
86 if( !alarms->head ) return NULL; // If no alarms return null
87 if( alarms->head->alarm >= currtime ) return NULL; // If alarms head not expired return null
88 return pop(alarms); // Otherwise just pop head
89}
90
91// Tick one frame of the Discrete Event Simulation for alarms
[c81ebf9]92void tick_preemption() {
[969b3fe]93 alarm_node_t * node = NULL; // Used in the while loop but cannot be declared in the while condition
94 alarm_list_t * alarms = &event_kernel->alarms; // Local copy for ease of reading
95 __cfa_time_t currtime = __kernel_get_time(); // Check current time once so we everything "happens at once"
[8cb529e]96
[969b3fe]97 //Loop throught every thing expired
98 while( node = get_expired( alarms, currtime ) ) {
[1c273d0]99
[969b3fe]100 // Check if this is a kernel
[c81ebf9]101 if( node->kernel_alarm ) {
102 preempt( node->proc );
103 }
104 else {
105 timeout( node->thrd );
106 }
107
[969b3fe]108 // Check if this is a periodic alarm
[8cb529e]109 __cfa_time_t period = node->period;
110 if( period > 0 ) {
[969b3fe]111 node->alarm = currtime + period; // Alarm is periodic, add currtime to it (used cached current time)
112 insert( alarms, node ); // Reinsert the node for the next time it triggers
[c81ebf9]113 }
114 else {
[969b3fe]115 node->set = false; // Node is one-shot, just mark it as not pending
[c81ebf9]116 }
117 }
118
[969b3fe]119 // If there are still alarms pending, reset the timer
120 if( alarms->head ) { __kernel_set_timer( alarms->head->alarm - currtime ); }
[c81ebf9]121}
122
[969b3fe]123// Update the preemption of a processor and notify interested parties
[c81ebf9]124void update_preemption( processor * this, __cfa_time_t duration ) {
125 alarm_node_t * alarm = this->preemption_alarm;
126
127 // Alarms need to be enabled
128 if ( duration > 0 && !alarm->set ) {
129 alarm->alarm = __kernel_get_time() + duration;
130 alarm->period = duration;
131 register_self( alarm );
132 }
133 // Zero duraction but alarm is set
134 else if ( duration == 0 && alarm->set ) {
135 unregister_self( alarm );
136 alarm->alarm = 0;
137 alarm->period = 0;
138 }
139 // If alarm is different from previous, change it
140 else if ( duration > 0 && alarm->period != duration ) {
141 unregister_self( alarm );
142 alarm->alarm = __kernel_get_time() + duration;
143 alarm->period = duration;
144 register_self( alarm );
145 }
146}
147
148//=============================================================================================
[cd17862]149// Kernel Signal Tools
[c81ebf9]150//=============================================================================================
151
[36982fc]152__cfaabi_dbg_debug_do( static thread_local void * last_interrupt = 0; )
[b227f68]153
[82ff5845]154extern "C" {
[969b3fe]155 // Disable interrupts by incrementing the counter
[82ff5845]156 void disable_interrupts() {
[4e6fb8e]157 __attribute__((unused)) unsigned short new_val = __atomic_add_fetch_2( &disable_preempt_count, 1, __ATOMIC_SEQ_CST );
[969b3fe]158 verify( new_val < 65_000u ); // If this triggers someone is disabling interrupts without enabling them
[82ff5845]159 }
160
[969b3fe]161 // Enable interrupts by decrementing the counter
162 // If counter reaches 0, execute any pending CtxSwitch
[36982fc]163 void enable_interrupts( __cfaabi_dbg_ctx_param ) {
[969b3fe]164 processor * proc = this_processor; // Cache the processor now since interrupts can start happening after the atomic add
165 thread_desc * thrd = this_thread; // Cache the thread now since interrupts can start happening after the atomic add
166
[4e6fb8e]167 unsigned short prev = __atomic_fetch_add_2( &disable_preempt_count, -1, __ATOMIC_SEQ_CST );
[969b3fe]168 verify( prev != 0u ); // If this triggers someone is enabled already enabled interruptsverify( prev != 0u );
169
170 // Check if we need to prempt the thread because an interrupt was missed
[1c273d0]171 if( prev == 1 && proc->pending_preemption ) {
172 proc->pending_preemption = false;
173 BlockInternal( thrd );
[82ff5845]174 }
[4e6fb8e]175
[969b3fe]176 // For debugging purposes : keep track of the last person to enable the interrupts
[36982fc]177 __cfaabi_dbg_debug_do( proc->last_enable = caller; )
[82ff5845]178 }
[969b3fe]179
180 // Disable interrupts by incrementint the counter
181 // Don't execute any pending CtxSwitch even if counter reaches 0
182 void enable_interrupts_noPoll() {
183 __attribute__((unused)) unsigned short prev = __atomic_fetch_add_2( &disable_preempt_count, -1, __ATOMIC_SEQ_CST );
184 verify( prev != 0u ); // If this triggers someone is enabled already enabled interrupts
185 }
[82ff5845]186}
187
[969b3fe]188// sigprocmask wrapper : unblock a single signal
[1c273d0]189static inline void signal_unblock( int sig ) {
[82ff5845]190 sigset_t mask;
191 sigemptyset( &mask );
[1c273d0]192 sigaddset( &mask, sig );
[82ff5845]193
[47ecf2b]194 if ( pthread_sigmask( SIG_UNBLOCK, &mask, NULL ) == -1 ) {
195 abortf( "internal error, pthread_sigmask" );
[cd17862]196 }
[82ff5845]197}
198
[969b3fe]199// sigprocmask wrapper : block a single signal
[cd17862]200static inline void signal_block( int sig ) {
201 sigset_t mask;
202 sigemptyset( &mask );
203 sigaddset( &mask, sig );
[47ecf2b]204
[cd17862]205 if ( pthread_sigmask( SIG_BLOCK, &mask, NULL ) == -1 ) {
206 abortf( "internal error, pthread_sigmask" );
207 }
208}
[47ecf2b]209
[969b3fe]210// kill wrapper : signal a processor
[cd17862]211static void preempt( processor * this ) {
212 pthread_kill( this->kernel_thread, SIGUSR1 );
[1c273d0]213}
[82ff5845]214
[969b3fe]215// reserved for future use
[cd17862]216static void timeout( thread_desc * this ) {
217 //TODO : implement waking threads
218}
219
[969b3fe]220
221// Check if a CtxSwitch signal handler shoud defer
222// If true : preemption is safe
223// If false : preemption is unsafe and marked as pending
224static inline bool preemption_ready() {
225 bool ready = disable_preempt_count == 0 && !preemption_in_progress; // Check if preemption is safe
226 this_processor->pending_preemption = !ready; // Adjust the pending flag accordingly
227 return ready;
228}
229
[cd17862]230//=============================================================================================
231// Kernel Signal Startup/Shutdown logic
232//=============================================================================================
233
[969b3fe]234// Startup routine to activate preemption
235// Called from kernel_startup
[cd17862]236void kernel_start_preemption() {
[36982fc]237 __cfaabi_dbg_print_safe("Kernel : Starting preemption\n");
[969b3fe]238
239 // Start with preemption disabled until ready
240 disable_preempt_count = 1;
241
242 // Initialize the event kernel
243 event_kernel = (event_kernel_t *)&storage_event_kernel;
[9236060]244 (*event_kernel){};
[969b3fe]245
246 // Setup proper signal handlers
[ed235b6]247 __kernel_sigaction( SIGUSR1, sigHandler_ctxSwitch, SA_SIGINFO | SA_RESTART ); // CtxSwitch handler
[969b3fe]248 // __kernel_sigaction( SIGSEGV, sigHandler_segv , SA_SIGINFO ); // Failure handler
249 // __kernel_sigaction( SIGBUS , sigHandler_segv , SA_SIGINFO ); // Failure handler
[cd17862]250
251 signal_block( SIGALRM );
252
253 pthread_create( &alarm_thread, NULL, alarm_loop, NULL );
254}
255
[969b3fe]256// Shutdown routine to deactivate preemption
257// Called from kernel_shutdown
[cd17862]258void kernel_stop_preemption() {
[36982fc]259 __cfaabi_dbg_print_safe("Kernel : Preemption stopping\n");
[d6ff3ff]260
[969b3fe]261 // Block all signals since we are already shutting down
[cd17862]262 sigset_t mask;
263 sigfillset( &mask );
264 sigprocmask( SIG_BLOCK, &mask, NULL );
265
[969b3fe]266 // Notify the alarm thread of the shutdown
[a0b3e32]267 sigval val = { 1 };
268 pthread_sigqueue( alarm_thread, SIGALRM, val );
[969b3fe]269
270 // Wait for the preemption thread to finish
[cd17862]271 pthread_join( alarm_thread, NULL );
[969b3fe]272
273 // Preemption is now fully stopped
274
[36982fc]275 __cfaabi_dbg_print_safe("Kernel : Preemption stopped\n");
[cd17862]276}
277
[969b3fe]278// Raii ctor/dtor for the preemption_scope
279// Used by thread to control when they want to receive preemption signals
[242a902]280void ?{}( preemption_scope & this, processor * proc ) {
[9236060]281 (this.alarm){ proc, zero_time, zero_time };
[242a902]282 this.proc = proc;
283 this.proc->preemption_alarm = &this.alarm;
[969b3fe]284
[9236060]285 update_preemption( this.proc, from_us(this.proc->cltr->preemption) );
[cd17862]286}
287
[242a902]288void ^?{}( preemption_scope & this ) {
[cd17862]289 disable_interrupts();
290
[9236060]291 update_preemption( this.proc, zero_time );
[cd17862]292}
293
294//=============================================================================================
295// Kernel Signal Handlers
296//=============================================================================================
[47ecf2b]297
[969b3fe]298// Context switch signal handler
299// Receives SIGUSR1 signal and causes the current thread to yield
[1c273d0]300void sigHandler_ctxSwitch( __CFA_SIGPARMS__ ) {
[258e6ad5]301#if defined( __ARM_ARCH )
[b158d8f]302 __cfaabi_dbg_debug_do( last_interrupt = (void *)(cxt->uc_mcontext.arm_pc); )
[258e6ad5]303#else
304 __cfaabi_dbg_debug_do( last_interrupt = (void *)(cxt->uc_mcontext.gregs[CFA_REG_IP]); )
305#endif
[969b3fe]306
[258e6ad5]307 // Check if it is safe to preempt here
[969b3fe]308 if( !preemption_ready() ) { return; }
309
[05615ba]310 // __cfaabi_dbg_print_buffer_decl(" KERNEL: preempting core %p (%p).\n", this_processor, this_thread);
311
[969b3fe]312 preemption_in_progress = true; // Sync flag : prevent recursive calls to the signal handler
313 signal_unblock( SIGUSR1 ); // We are about to CtxSwitch out of the signal handler, let other handlers in
314 preemption_in_progress = false; // Clear the in progress flag
315
316 // Preemption can occur here
317
318 BlockInternal( (thread_desc*)this_thread ); // Do the actual CtxSwitch
[c81ebf9]319}
320
[969b3fe]321// Main of the alarm thread
322// Waits on SIGALRM and send SIGUSR1 to whom ever needs it
[cd17862]323void * alarm_loop( __attribute__((unused)) void * args ) {
[969b3fe]324 // Block sigalrms to control when they arrive
[cd17862]325 sigset_t mask;
326 sigemptyset( &mask );
327 sigaddset( &mask, SIGALRM );
328
329 if ( pthread_sigmask( SIG_BLOCK, &mask, NULL ) == -1 ) {
330 abortf( "internal error, pthread_sigmask" );
[82ff5845]331 }
[c81ebf9]332
[969b3fe]333 // Main loop
[cd17862]334 while( true ) {
[969b3fe]335 // Wait for a sigalrm
[a0b3e32]336 siginfo_t info;
337 int sig = sigwaitinfo( &mask, &info );
[969b3fe]338
[e2f7bc3]339 if( sig < 0 ) {
340 //Error!
341 int err = errno;
342 switch( err ) {
343 case EAGAIN :
344 case EINTR :
345 continue;
346 case EINVAL :
347 abortf("Timeout was invalid.");
348 default:
349 abortf("Unhandled error %d", err);
350 }
351 }
352
[969b3fe]353 // If another signal arrived something went wrong
[8cb529e]354 assertf(sig == SIGALRM, "Kernel Internal Error, sigwait: Unexpected signal %d (%d : %d)\n", sig, info.si_code, info.si_value.sival_int);
355
[36982fc]356 // __cfaabi_dbg_print_safe("Kernel : Caught alarm from %d with %d\n", info.si_code, info.si_value.sival_int );
[969b3fe]357 // Switch on the code (a.k.a. the sender) to
[8cb529e]358 switch( info.si_code )
[a0b3e32]359 {
[969b3fe]360 // Timers can apparently be marked as sent for the kernel
361 // In either case, tick preemption
[8cb529e]362 case SI_TIMER:
363 case SI_KERNEL:
[36982fc]364 // __cfaabi_dbg_print_safe("Kernel : Preemption thread tick\n");
365 lock( event_kernel->lock __cfaabi_dbg_ctx2 );
[8cb529e]366 tick_preemption();
[ea7d2b0]367 unlock( event_kernel->lock );
[8cb529e]368 break;
[969b3fe]369 // Signal was not sent by the kernel but by an other thread
[8cb529e]370 case SI_QUEUE:
[969b3fe]371 // For now, other thread only signal the alarm thread to shut it down
372 // If this needs to change use info.si_value and handle the case here
[8cb529e]373 goto EXIT;
[cd17862]374 }
375 }
[a0b3e32]376
[8cb529e]377EXIT:
[36982fc]378 __cfaabi_dbg_print_safe("Kernel : Preemption thread stopping\n");
[a0b3e32]379 return NULL;
[82ff5845]380}
381
[969b3fe]382// Sigaction wrapper : register an signal handler
[82ff5845]383static void __kernel_sigaction( int sig, void (*handler)(__CFA_SIGPARMS__), int flags ) {
384 struct sigaction act;
385
386 act.sa_sigaction = (void (*)(int, siginfo_t *, void *))handler;
[1c273d0]387 act.sa_flags = flags;
388
389 if ( sigaction( sig, &act, NULL ) == -1 ) {
[36982fc]390 __cfaabi_dbg_print_buffer_decl(
[1c273d0]391 " __kernel_sigaction( sig:%d, handler:%p, flags:%d ), problem installing signal handler, error(%d) %s.\n",
392 sig, handler, flags, errno, strerror( errno )
393 );
394 _exit( EXIT_FAILURE );
395 }
396}
397
[969b3fe]398// Sigaction wrapper : restore default handler
[1c273d0]399static void __kernel_sigdefault( int sig ) {
400 struct sigaction act;
401
[969b3fe]402 act.sa_handler = SIG_DFL;
[1c273d0]403 act.sa_flags = 0;
404 sigemptyset( &act.sa_mask );
[82ff5845]405
406 if ( sigaction( sig, &act, NULL ) == -1 ) {
[36982fc]407 __cfaabi_dbg_print_buffer_decl(
[1c273d0]408 " __kernel_sigdefault( sig:%d ), problem reseting signal handler, error(%d) %s.\n",
409 sig, errno, strerror( errno )
410 );
[82ff5845]411 _exit( EXIT_FAILURE );
[1c273d0]412 }
413}
414
415//=============================================================================================
416// Terminating Signals logic
417//=============================================================================================
418
[36982fc]419__cfaabi_dbg_debug_do(
[1c273d0]420 static void __kernel_backtrace( int start ) {
421 // skip first N stack frames
422
423 enum { Frames = 50 };
424 void * array[Frames];
425 int size = backtrace( array, Frames );
426 char ** messages = backtrace_symbols( array, size );
427
428 // find executable name
429 *index( messages[0], '(' ) = '\0';
430 #ifdef __USE_STREAM__
431 serr | "Stack back trace for:" | messages[0] | endl;
432 #else
433 fprintf( stderr, "Stack back trace for: %s\n", messages[0]);
434 #endif
435
436 // skip last 2 stack frames after main
437 for ( int i = start; i < size && messages != NULL; i += 1 ) {
438 char * name = NULL;
439 char * offset_begin = NULL;
440 char * offset_end = NULL;
441
442 for ( char *p = messages[i]; *p; ++p ) {
443 // find parantheses and +offset
444 if ( *p == '(' ) {
445 name = p;
446 }
447 else if ( *p == '+' ) {
448 offset_begin = p;
449 }
450 else if ( *p == ')' ) {
451 offset_end = p;
452 break;
453 }
454 }
455
456 // if line contains symbol print it
457 int frameNo = i - start;
458 if ( name && offset_begin && offset_end && name < offset_begin ) {
459 // delimit strings
460 *name++ = '\0';
461 *offset_begin++ = '\0';
462 *offset_end++ = '\0';
463
464 #ifdef __USE_STREAM__
465 serr | "(" | frameNo | ")" | messages[i] | ":"
466 | name | "+" | offset_begin | offset_end | endl;
467 #else
468 fprintf( stderr, "(%i) %s : %s + %s %s\n", frameNo, messages[i], name, offset_begin, offset_end);
469 #endif
470 }
471 // otherwise, print the whole line
472 else {
473 #ifdef __USE_STREAM__
474 serr | "(" | frameNo | ")" | messages[i] | endl;
475 #else
476 fprintf( stderr, "(%i) %s\n", frameNo, messages[i] );
477 #endif
478 }
479 }
480
481 free( messages );
482 }
483)
484
[f2b12406]485// void sigHandler_segv( __CFA_SIGPARMS__ ) {
[36982fc]486// __cfaabi_dbg_debug_do(
[f2b12406]487// #ifdef __USE_STREAM__
488// serr | "*CFA runtime error* program cfa-cpp terminated with"
489// | (sig == SIGSEGV ? "segment fault." : "bus error.")
490// | endl;
491// #else
492// fprintf( stderr, "*CFA runtime error* program cfa-cpp terminated with %s\n", sig == SIGSEGV ? "segment fault." : "bus error." );
493// #endif
494
495// // skip first 2 stack frames
496// __kernel_backtrace( 1 );
497// )
498// exit( EXIT_FAILURE );
499// }
[1c273d0]500
501// void sigHandler_abort( __CFA_SIGPARMS__ ) {
502// // skip first 6 stack frames
[36982fc]503// __cfaabi_dbg_debug_do( __kernel_backtrace( 6 ); )
[1c273d0]504
505// // reset default signal handler
506// __kernel_sigdefault( SIGABRT );
507
508// raise( SIGABRT );
[6b0b624]509// }
510
511// Local Variables: //
512// mode: c //
513// tab-width: 4 //
514// End: //
Note: See TracBrowser for help on using the repository browser.