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

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 b158d8f was b158d8f, checked in by Alan Kennedy <afakenne@…>, 8 years ago

add context switch for ARM

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