source: src/libcfa/concurrency/preemption.c@ 93401f8

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 93401f8 was b69ea6b, checked in by Thierry Delisle <tdelisle@…>, 8 years ago

Updated alarm to use bits/cfatime and fixed preemption for coroutines

  • Property mode set to 100644
File size: 13.1 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 : Fri Feb 9 16:38:13 2018
13// Update Count : 14
14//
15
16#include "preemption.h"
17
18extern "C" {
19#include <errno.h>
20#include <stdio.h>
21#include <string.h>
22#include <unistd.h>
23}
24
25#include "bits/signal.h"
26
27//TODO move to defaults
28#define __CFA_DEFAULT_PREEMPTION__ 10000
29
30//TODO move to defaults
31__attribute__((weak)) unsigned int default_preemption() {
32 return __CFA_DEFAULT_PREEMPTION__;
33}
34
35// FwdDeclarations : timeout handlers
36static void preempt( processor * this );
37static void timeout( thread_desc * this );
38
39// FwdDeclarations : Signal handlers
40void sigHandler_ctxSwitch( __CFA_SIGPARMS__ );
41void sigHandler_segv ( __CFA_SIGPARMS__ );
42void sigHandler_ill ( __CFA_SIGPARMS__ );
43void sigHandler_fpe ( __CFA_SIGPARMS__ );
44void sigHandler_abort ( __CFA_SIGPARMS__ );
45
46// FwdDeclarations : alarm thread main
47void * alarm_loop( __attribute__((unused)) void * args );
48
49// Machine specific register name
50#if defined( __i386 )
51#define CFA_REG_IP gregs[REG_EIP]
52#elif defined( __x86_64 )
53#define CFA_REG_IP gregs[REG_RIP]
54#elif defined( __ARM_ARCH )
55#define CFA_REG_IP arm_pc
56#else
57#error unknown hardware architecture
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
69enum {
70 PREEMPT_NORMAL = 0,
71 PREEMPT_TERMINATE = 1,
72};
73
74//=============================================================================================
75// Kernel Preemption logic
76//=============================================================================================
77
78// Get next expired node
79static inline alarm_node_t * get_expired( alarm_list_t * alarms, __cfa_time_t currtime ) {
80 if( !alarms->head ) return NULL; // If no alarms return null
81 if( alarms->head->alarm >= currtime ) return NULL; // If alarms head not expired return null
82 return pop(alarms); // Otherwise just pop head
83}
84
85// Tick one frame of the Discrete Event Simulation for alarms
86void tick_preemption() {
87 alarm_node_t * node = NULL; // Used in the while loop but cannot be declared in the while condition
88 alarm_list_t * alarms = &event_kernel->alarms; // Local copy for ease of reading
89 __cfa_time_t currtime = __kernel_get_time(); // Check current time once so we everything "happens at once"
90
91 //Loop throught every thing expired
92 while( node = get_expired( alarms, currtime ) ) {
93
94 // Check if this is a kernel
95 if( node->kernel_alarm ) {
96 preempt( node->proc );
97 }
98 else {
99 timeout( node->thrd );
100 }
101
102 // Check if this is a periodic alarm
103 __cfa_time_t period = node->period;
104 if( period > 0 ) {
105 node->alarm = currtime + period; // Alarm is periodic, add currtime to it (used cached current time)
106 insert( alarms, node ); // Reinsert the node for the next time it triggers
107 }
108 else {
109 node->set = false; // Node is one-shot, just mark it as not pending
110 }
111 }
112
113 // If there are still alarms pending, reset the timer
114 if( alarms->head ) { __kernel_set_timer( alarms->head->alarm - currtime ); }
115}
116
117// Update the preemption of a processor and notify interested parties
118void update_preemption( processor * this, __cfa_time_t duration ) {
119 alarm_node_t * alarm = this->preemption_alarm;
120
121 // Alarms need to be enabled
122 if ( duration > 0 && !alarm->set ) {
123 alarm->alarm = __kernel_get_time() + duration;
124 alarm->period = duration;
125 register_self( alarm );
126 }
127 // Zero duraction but alarm is set
128 else if ( duration == 0 && alarm->set ) {
129 unregister_self( alarm );
130 alarm->alarm = 0;
131 alarm->period = 0;
132 }
133 // If alarm is different from previous, change it
134 else if ( duration > 0 && alarm->period != duration ) {
135 unregister_self( alarm );
136 alarm->alarm = __kernel_get_time() + duration;
137 alarm->period = duration;
138 register_self( alarm );
139 }
140}
141
142//=============================================================================================
143// Kernel Signal Tools
144//=============================================================================================
145
146__cfaabi_dbg_debug_do( static thread_local void * last_interrupt = 0; )
147
148extern "C" {
149 // Disable interrupts by incrementing the counter
150 void disable_interrupts() {
151 preemption.enabled = false;
152 __attribute__((unused)) unsigned short new_val = preemption.disable_count + 1;
153 preemption.disable_count = new_val;
154 verify( new_val < 65_000u ); // If this triggers someone is disabling interrupts without enabling them
155 }
156
157 // Enable interrupts by decrementing the counter
158 // If counter reaches 0, execute any pending CtxSwitch
159 void enable_interrupts( __cfaabi_dbg_ctx_param ) {
160 processor * proc = this_processor; // Cache the processor now since interrupts can start happening after the atomic add
161 thread_desc * thrd = this_thread; // Cache the thread now since interrupts can start happening after the atomic add
162
163 unsigned short prev = preemption.disable_count;
164 preemption.disable_count -= 1;
165 verify( prev != 0u ); // If this triggers someone is enabled already enabled interruptsverify( prev != 0u );
166
167 // Check if we need to prempt the thread because an interrupt was missed
168 if( prev == 1 ) {
169 preemption.enabled = true;
170 if( proc->pending_preemption ) {
171 proc->pending_preemption = false;
172 BlockInternal( thrd );
173 }
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 unsigned short prev = preemption.disable_count;
184 preemption.disable_count -= 1;
185 verifyf( prev != 0u, "Incremented from %u\n", prev ); // If this triggers someone is enabled already enabled interrupts
186 if( prev == 1 ) {
187 preemption.enabled = true;
188 }
189 }
190}
191
192// sigprocmask wrapper : unblock a single signal
193static inline void signal_unblock( int sig ) {
194 sigset_t mask;
195 sigemptyset( &mask );
196 sigaddset( &mask, sig );
197
198 if ( pthread_sigmask( SIG_UNBLOCK, &mask, NULL ) == -1 ) {
199 abort( "internal error, pthread_sigmask" );
200 }
201}
202
203// sigprocmask wrapper : block a single signal
204static inline void signal_block( int sig ) {
205 sigset_t mask;
206 sigemptyset( &mask );
207 sigaddset( &mask, sig );
208
209 if ( pthread_sigmask( SIG_BLOCK, &mask, NULL ) == -1 ) {
210 abort( "internal error, pthread_sigmask" );
211 }
212}
213
214// kill wrapper : signal a processor
215static void preempt( processor * this ) {
216 sigval_t value = { PREEMPT_NORMAL };
217 pthread_sigqueue( this->kernel_thread, SIGUSR1, value );
218}
219
220// kill wrapper : signal a processor
221void terminate(processor * this) {
222 this->do_terminate = true;
223 sigval_t value = { PREEMPT_TERMINATE };
224 pthread_sigqueue( this->kernel_thread, SIGUSR1, value );
225}
226
227// reserved for future use
228static void timeout( thread_desc * this ) {
229 //TODO : implement waking threads
230}
231
232
233// Check if a CtxSwitch signal handler shoud defer
234// If true : preemption is safe
235// If false : preemption is unsafe and marked as pending
236static inline bool preemption_ready() {
237 bool ready = preemption.enabled && !preemption.in_progress; // Check if preemption is safe
238 this_processor->pending_preemption = !ready; // Adjust the pending flag accordingly
239 return ready;
240}
241
242//=============================================================================================
243// Kernel Signal Startup/Shutdown logic
244//=============================================================================================
245
246// Startup routine to activate preemption
247// Called from kernel_startup
248void kernel_start_preemption() {
249 __cfaabi_dbg_print_safe( "Kernel : Starting preemption\n" );
250
251 // Start with preemption disabled until ready
252 preemption.enabled = false;
253 preemption.disable_count = 1;
254
255 // Initialize the event kernel
256 event_kernel = (event_kernel_t *)&storage_event_kernel;
257 (*event_kernel){};
258
259 // Setup proper signal handlers
260 __cfaabi_sigaction( SIGUSR1, sigHandler_ctxSwitch, SA_SIGINFO | SA_RESTART ); // CtxSwitch handler
261
262 signal_block( SIGALRM );
263
264 pthread_create( &alarm_thread, NULL, alarm_loop, NULL );
265}
266
267// Shutdown routine to deactivate preemption
268// Called from kernel_shutdown
269void kernel_stop_preemption() {
270 __cfaabi_dbg_print_safe( "Kernel : Preemption stopping\n" );
271
272 // Block all signals since we are already shutting down
273 sigset_t mask;
274 sigfillset( &mask );
275 sigprocmask( SIG_BLOCK, &mask, NULL );
276
277 // Notify the alarm thread of the shutdown
278 sigval val = { 1 };
279 pthread_sigqueue( alarm_thread, SIGALRM, val );
280
281 // Wait for the preemption thread to finish
282 pthread_join( alarm_thread, NULL );
283
284 // Preemption is now fully stopped
285
286 __cfaabi_dbg_print_safe( "Kernel : Preemption stopped\n" );
287}
288
289// Raii ctor/dtor for the preemption_scope
290// Used by thread to control when they want to receive preemption signals
291void ?{}( preemption_scope & this, processor * proc ) {
292 (this.alarm){ proc, 0`cfa_s, 0`cfa_s };
293 this.proc = proc;
294 this.proc->preemption_alarm = &this.alarm;
295
296 update_preemption( this.proc, from_us(this.proc->cltr->preemption) );
297}
298
299void ^?{}( preemption_scope & this ) {
300 disable_interrupts();
301
302 update_preemption( this.proc, 0`cfa_s );
303}
304
305//=============================================================================================
306// Kernel Signal Handlers
307//=============================================================================================
308
309// Context switch signal handler
310// Receives SIGUSR1 signal and causes the current thread to yield
311void sigHandler_ctxSwitch( __CFA_SIGPARMS__ ) {
312 __cfaabi_dbg_debug_do( last_interrupt = (void *)(cxt->uc_mcontext.CFA_REG_IP); )
313
314 // SKULLDUGGERY: if a thread creates a processor and the immediately deletes it,
315 // the interrupt that is supposed to force the kernel thread to preempt might arrive
316 // before the kernel thread has even started running. When that happens an iterrupt
317 // we a null 'this_processor' will be caught, just ignore it.
318 if(!this_processor) return;
319
320 choose(sfp->si_value.sival_int) {
321 case PREEMPT_NORMAL : ;// Normal case, nothing to do here
322 case PREEMPT_TERMINATE: verify(this_processor->do_terminate);
323 default:
324 abort( "internal error, signal value is %d", sfp->si_value.sival_int );
325 }
326
327 // Check if it is safe to preempt here
328 if( !preemption_ready() ) { return; }
329
330 __cfaabi_dbg_print_buffer_decl( " KERNEL: preempting core %p (%p).\n", this_processor, this_thread);
331
332 preemption.in_progress = true; // Sync flag : prevent recursive calls to the signal handler
333 signal_unblock( SIGUSR1 ); // We are about to CtxSwitch out of the signal handler, let other handlers in
334 preemption.in_progress = false; // Clear the in progress flag
335
336 // Preemption can occur here
337
338 BlockInternal( (thread_desc*)this_thread ); // Do the actual CtxSwitch
339}
340
341// Main of the alarm thread
342// Waits on SIGALRM and send SIGUSR1 to whom ever needs it
343void * alarm_loop( __attribute__((unused)) void * args ) {
344 // Block sigalrms to control when they arrive
345 sigset_t mask;
346 sigemptyset( &mask );
347 sigaddset( &mask, SIGALRM );
348
349 if ( pthread_sigmask( SIG_BLOCK, &mask, NULL ) == -1 ) {
350 abort( "internal error, pthread_sigmask" );
351 }
352
353 // Main loop
354 while( true ) {
355 // Wait for a sigalrm
356 siginfo_t info;
357 int sig = sigwaitinfo( &mask, &info );
358
359 if( sig < 0 ) {
360 //Error!
361 int err = errno;
362 switch( err ) {
363 case EAGAIN :
364 case EINTR :
365 continue;
366 case EINVAL :
367 abort( "Timeout was invalid." );
368 default:
369 abort( "Unhandled error %d", err);
370 }
371 }
372
373 // If another signal arrived something went wrong
374 assertf(sig == SIGALRM, "Kernel Internal Error, sigwait: Unexpected signal %d (%d : %d)\n", sig, info.si_code, info.si_value.sival_int);
375
376 // __cfaabi_dbg_print_safe( "Kernel : Caught alarm from %d with %d\n", info.si_code, info.si_value.sival_int );
377 // Switch on the code (a.k.a. the sender) to
378 switch( info.si_code )
379 {
380 // Timers can apparently be marked as sent for the kernel
381 // In either case, tick preemption
382 case SI_TIMER:
383 case SI_KERNEL:
384 // __cfaabi_dbg_print_safe( "Kernel : Preemption thread tick\n" );
385 lock( event_kernel->lock __cfaabi_dbg_ctx2 );
386 tick_preemption();
387 unlock( event_kernel->lock );
388 break;
389 // Signal was not sent by the kernel but by an other thread
390 case SI_QUEUE:
391 // For now, other thread only signal the alarm thread to shut it down
392 // If this needs to change use info.si_value and handle the case here
393 goto EXIT;
394 }
395 }
396
397EXIT:
398 __cfaabi_dbg_print_safe( "Kernel : Preemption thread stopping\n" );
399 return NULL;
400}
401
402// Local Variables: //
403// mode: c //
404// tab-width: 4 //
405// End: //
Note: See TracBrowser for help on using the repository browser.