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

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 c659968 was 2b8bc41, checked in by Peter A. Buhr <pabuhr@…>, 8 years ago

print backtrace on termination

  • Property mode set to 100644
File size: 12.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 Feb 6 15:00:36 2018
13// Update Count : 10
14//
15
16#include "preemption.h"
17
18#define ftype `ftype`
19extern "C" {
20#include <errno.h>
21#include <stdio.h>
22#include <string.h>
23#include <unistd.h>
24}
25#undef ftype
26
27#include "bits/signal.h"
28
29//TODO move to defaults
30#define __CFA_DEFAULT_PREEMPTION__ 10000
31
32//TODO move to defaults
33__attribute__((weak)) unsigned int default_preemption() {
34 return __CFA_DEFAULT_PREEMPTION__;
35}
36
37// FwdDeclarations : timeout handlers
38static void preempt( processor * this );
39static void timeout( thread_desc * this );
40
41// FwdDeclarations : Signal handlers
42void sigHandler_ctxSwitch( __CFA_SIGPARMS__ );
43void sigHandler_segv ( __CFA_SIGPARMS__ );
44void sigHandler_ill ( __CFA_SIGPARMS__ );
45void sigHandler_fpe ( __CFA_SIGPARMS__ );
46void sigHandler_abort ( __CFA_SIGPARMS__ );
47
48// FwdDeclarations : alarm thread main
49void * alarm_loop( __attribute__((unused)) void * args );
50
51// Machine specific register name
52#if defined(__x86_64__)
53#define CFA_REG_IP gregs[REG_RIP]
54#elif defined(__i386__)
55#define CFA_REG_IP gregs[REG_EIP]
56#elif defined(__ARM_ARCH__)
57#define CFA_REG_IP arm_pc
58#endif
59
60KERNEL_STORAGE(event_kernel_t, event_kernel); // private storage for event kernel
61event_kernel_t * event_kernel; // kernel public handle to even kernel
62static pthread_t alarm_thread; // pthread handle to alarm thread
63
64void ?{}(event_kernel_t & this) with( this ) {
65 alarms{};
66 lock{};
67}
68
69//=============================================================================================
70// Kernel Preemption logic
71//=============================================================================================
72
73// Get next expired node
74static inline alarm_node_t * get_expired( alarm_list_t * alarms, __cfa_time_t currtime ) {
75 if( !alarms->head ) return NULL; // If no alarms return null
76 if( alarms->head->alarm >= currtime ) return NULL; // If alarms head not expired return null
77 return pop(alarms); // Otherwise just pop head
78}
79
80// Tick one frame of the Discrete Event Simulation for alarms
81void tick_preemption() {
82 alarm_node_t * node = NULL; // Used in the while loop but cannot be declared in the while condition
83 alarm_list_t * alarms = &event_kernel->alarms; // Local copy for ease of reading
84 __cfa_time_t currtime = __kernel_get_time(); // Check current time once so we everything "happens at once"
85
86 //Loop throught every thing expired
87 while( node = get_expired( alarms, currtime ) ) {
88
89 // Check if this is a kernel
90 if( node->kernel_alarm ) {
91 preempt( node->proc );
92 }
93 else {
94 timeout( node->thrd );
95 }
96
97 // Check if this is a periodic alarm
98 __cfa_time_t period = node->period;
99 if( period > 0 ) {
100 node->alarm = currtime + period; // Alarm is periodic, add currtime to it (used cached current time)
101 insert( alarms, node ); // Reinsert the node for the next time it triggers
102 }
103 else {
104 node->set = false; // Node is one-shot, just mark it as not pending
105 }
106 }
107
108 // If there are still alarms pending, reset the timer
109 if( alarms->head ) { __kernel_set_timer( alarms->head->alarm - currtime ); }
110}
111
112// Update the preemption of a processor and notify interested parties
113void update_preemption( processor * this, __cfa_time_t duration ) {
114 alarm_node_t * alarm = this->preemption_alarm;
115
116 // Alarms need to be enabled
117 if ( duration > 0 && !alarm->set ) {
118 alarm->alarm = __kernel_get_time() + duration;
119 alarm->period = duration;
120 register_self( alarm );
121 }
122 // Zero duraction but alarm is set
123 else if ( duration == 0 && alarm->set ) {
124 unregister_self( alarm );
125 alarm->alarm = 0;
126 alarm->period = 0;
127 }
128 // If alarm is different from previous, change it
129 else if ( duration > 0 && alarm->period != duration ) {
130 unregister_self( alarm );
131 alarm->alarm = __kernel_get_time() + duration;
132 alarm->period = duration;
133 register_self( alarm );
134 }
135}
136
137//=============================================================================================
138// Kernel Signal Tools
139//=============================================================================================
140
141__cfaabi_dbg_debug_do( static thread_local void * last_interrupt = 0; )
142
143extern "C" {
144 // Disable interrupts by incrementing the counter
145 void disable_interrupts() {
146 preemption_enabled = false;
147 __attribute__((unused)) unsigned short new_val = disable_preempt_count + 1;
148 disable_preempt_count = new_val;
149 verify( new_val < 65_000u ); // If this triggers someone is disabling interrupts without enabling them
150 }
151
152 // Enable interrupts by decrementing the counter
153 // If counter reaches 0, execute any pending CtxSwitch
154 void enable_interrupts( __cfaabi_dbg_ctx_param ) {
155 processor * proc = this_processor; // Cache the processor now since interrupts can start happening after the atomic add
156 thread_desc * thrd = this_thread; // Cache the thread now since interrupts can start happening after the atomic add
157
158 unsigned short prev = disable_preempt_count;
159 disable_preempt_count -= 1;
160 verify( prev != 0u ); // If this triggers someone is enabled already enabled interruptsverify( prev != 0u );
161
162 // Check if we need to prempt the thread because an interrupt was missed
163 if( prev == 1 ) {
164 preemption_enabled = true;
165 if( proc->pending_preemption ) {
166 proc->pending_preemption = false;
167 BlockInternal( thrd );
168 }
169 }
170
171 // For debugging purposes : keep track of the last person to enable the interrupts
172 __cfaabi_dbg_debug_do( proc->last_enable = caller; )
173 }
174
175 // Disable interrupts by incrementint the counter
176 // Don't execute any pending CtxSwitch even if counter reaches 0
177 void enable_interrupts_noPoll() {
178 unsigned short prev = disable_preempt_count;
179 disable_preempt_count -= 1;
180 verifyf( prev != 0u, "Incremented from %u\n", prev ); // If this triggers someone is enabled already enabled interrupts
181 if( prev == 1 ) {
182 preemption_enabled = true;
183 }
184 }
185}
186
187// sigprocmask wrapper : unblock a single signal
188static inline void signal_unblock( int sig ) {
189 sigset_t mask;
190 sigemptyset( &mask );
191 sigaddset( &mask, sig );
192
193 if ( pthread_sigmask( SIG_UNBLOCK, &mask, NULL ) == -1 ) {
194 abortf( "internal error, pthread_sigmask" );
195 }
196}
197
198// sigprocmask wrapper : block a single signal
199static inline void signal_block( int sig ) {
200 sigset_t mask;
201 sigemptyset( &mask );
202 sigaddset( &mask, sig );
203
204 if ( pthread_sigmask( SIG_BLOCK, &mask, NULL ) == -1 ) {
205 abortf( "internal error, pthread_sigmask" );
206 }
207}
208
209// kill wrapper : signal a processor
210static void preempt( processor * this ) {
211 pthread_kill( this->kernel_thread, SIGUSR1 );
212}
213
214// reserved for future use
215static void timeout( thread_desc * this ) {
216 //TODO : implement waking threads
217}
218
219
220// Check if a CtxSwitch signal handler shoud defer
221// If true : preemption is safe
222// If false : preemption is unsafe and marked as pending
223static inline bool preemption_ready() {
224 bool ready = preemption_enabled && !preemption_in_progress; // Check if preemption is safe
225 this_processor->pending_preemption = !ready; // Adjust the pending flag accordingly
226 return ready;
227}
228
229//=============================================================================================
230// Kernel Signal Startup/Shutdown logic
231//=============================================================================================
232
233// Startup routine to activate preemption
234// Called from kernel_startup
235void kernel_start_preemption() {
236 __cfaabi_dbg_print_safe("Kernel : Starting preemption\n");
237
238 // Start with preemption disabled until ready
239 preemption_enabled = false;
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 __cfaabi_sigaction( SIGUSR1, sigHandler_ctxSwitch, SA_SIGINFO | SA_RESTART ); // CtxSwitch handler
248
249 signal_block( SIGALRM );
250
251 pthread_create( &alarm_thread, NULL, alarm_loop, NULL );
252}
253
254// Shutdown routine to deactivate preemption
255// Called from kernel_shutdown
256void kernel_stop_preemption() {
257 __cfaabi_dbg_print_safe("Kernel : Preemption stopping\n");
258
259 // Block all signals since we are already shutting down
260 sigset_t mask;
261 sigfillset( &mask );
262 sigprocmask( SIG_BLOCK, &mask, NULL );
263
264 // Notify the alarm thread of the shutdown
265 sigval val = { 1 };
266 pthread_sigqueue( alarm_thread, SIGALRM, val );
267
268 // Wait for the preemption thread to finish
269 pthread_join( alarm_thread, NULL );
270
271 // Preemption is now fully stopped
272
273 __cfaabi_dbg_print_safe("Kernel : Preemption stopped\n");
274}
275
276// Raii ctor/dtor for the preemption_scope
277// Used by thread to control when they want to receive preemption signals
278void ?{}( preemption_scope & this, processor * proc ) {
279 (this.alarm){ proc, zero_time, zero_time };
280 this.proc = proc;
281 this.proc->preemption_alarm = &this.alarm;
282
283 update_preemption( this.proc, from_us(this.proc->cltr->preemption) );
284}
285
286void ^?{}( preemption_scope & this ) {
287 disable_interrupts();
288
289 update_preemption( this.proc, zero_time );
290}
291
292//=============================================================================================
293// Kernel Signal Handlers
294//=============================================================================================
295
296// Context switch signal handler
297// Receives SIGUSR1 signal and causes the current thread to yield
298void sigHandler_ctxSwitch( __CFA_SIGPARMS__ ) {
299 __cfaabi_dbg_debug_do( last_interrupt = (void *)(cxt->uc_mcontext.CFA_REG_IP); )
300
301 // Check if it is safe to preempt here
302 if( !preemption_ready() ) { return; }
303
304 __cfaabi_dbg_print_buffer_decl(" KERNEL: preempting core %p (%p).\n", this_processor, this_thread);
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// Local Variables: //
377// mode: c //
378// tab-width: 4 //
379// End: //
Note: See TracBrowser for help on using the repository browser.