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
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 17:59:30 2018
13// Update Count : 7
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#if defined( __ARM_ARCH )
302 __cfaabi_dbg_debug_do( last_interrupt = (void *)(cxt->uc_mcontext.arm_pc); )
303#else
304 __cfaabi_dbg_debug_do( last_interrupt = (void *)(cxt->uc_mcontext.gregs[CFA_REG_IP]); )
305#endif
306
307 // Check if it is safe to preempt here
308 if( !preemption_ready() ) { return; }
309
310 // __cfaabi_dbg_print_buffer_decl(" KERNEL: preempting core %p (%p).\n", this_processor, this_thread);
311
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
319}
320
321// Main of the alarm thread
322// Waits on SIGALRM and send SIGUSR1 to whom ever needs it
323void * alarm_loop( __attribute__((unused)) void * args ) {
324 // Block sigalrms to control when they arrive
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" );
331 }
332
333 // Main loop
334 while( true ) {
335 // Wait for a sigalrm
336 siginfo_t info;
337 int sig = sigwaitinfo( &mask, &info );
338
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
353 // If another signal arrived something went wrong
354 assertf(sig == SIGALRM, "Kernel Internal Error, sigwait: Unexpected signal %d (%d : %d)\n", sig, info.si_code, info.si_value.sival_int);
355
356 // __cfaabi_dbg_print_safe("Kernel : Caught alarm from %d with %d\n", info.si_code, info.si_value.sival_int );
357 // Switch on the code (a.k.a. the sender) to
358 switch( info.si_code )
359 {
360 // Timers can apparently be marked as sent for the kernel
361 // In either case, tick preemption
362 case SI_TIMER:
363 case SI_KERNEL:
364 // __cfaabi_dbg_print_safe("Kernel : Preemption thread tick\n");
365 lock( event_kernel->lock __cfaabi_dbg_ctx2 );
366 tick_preemption();
367 unlock( event_kernel->lock );
368 break;
369 // Signal was not sent by the kernel but by an other thread
370 case SI_QUEUE:
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
373 goto EXIT;
374 }
375 }
376
377EXIT:
378 __cfaabi_dbg_print_safe("Kernel : Preemption thread stopping\n");
379 return NULL;
380}
381
382// Sigaction wrapper : register an signal handler
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;
387 act.sa_flags = flags;
388
389 if ( sigaction( sig, &act, NULL ) == -1 ) {
390 __cfaabi_dbg_print_buffer_decl(
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
398// Sigaction wrapper : restore default handler
399static void __kernel_sigdefault( int sig ) {
400 struct sigaction act;
401
402 act.sa_handler = SIG_DFL;
403 act.sa_flags = 0;
404 sigemptyset( &act.sa_mask );
405
406 if ( sigaction( sig, &act, NULL ) == -1 ) {
407 __cfaabi_dbg_print_buffer_decl(
408 " __kernel_sigdefault( sig:%d ), problem reseting signal handler, error(%d) %s.\n",
409 sig, errno, strerror( errno )
410 );
411 _exit( EXIT_FAILURE );
412 }
413}
414
415//=============================================================================================
416// Terminating Signals logic
417//=============================================================================================
418
419__cfaabi_dbg_debug_do(
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
485// void sigHandler_segv( __CFA_SIGPARMS__ ) {
486// __cfaabi_dbg_debug_do(
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// }
500
501// void sigHandler_abort( __CFA_SIGPARMS__ ) {
502// // skip first 6 stack frames
503// __cfaabi_dbg_debug_do( __kernel_backtrace( 6 ); )
504
505// // reset default signal handler
506// __kernel_sigdefault( SIGABRT );
507
508// raise( SIGABRT );
509// }
510
511// Local Variables: //
512// mode: c //
513// tab-width: 4 //
514// End: //
Note: See TracBrowser for help on using the repository browser.