source: src/libcfa/concurrency/preemption.c@ 5f95b5f

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 5f95b5f was d0a045c7, checked in by Thierry Delisle <tdelisle@…>, 8 years ago

Faster (but maybe unsafe) interupt management

  • Property mode set to 100644
File size: 12.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 : 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 <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_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(__x86_64__)
51#define CFA_REG_IP gregs[REG_RIP]
52#elif defined(__i386__)
53#define CFA_REG_IP gregs[REG_EIP]
54#elif defined(__ARM_ARCH__)
55#define CFA_REG_IP arm_pc
56#endif
57
58KERNEL_STORAGE(event_kernel_t, event_kernel); // private storage for event kernel
59event_kernel_t * event_kernel; // kernel public handle to even kernel
60static pthread_t alarm_thread; // pthread handle to alarm thread
61
62void ?{}(event_kernel_t & this) with( this ) {
63 alarms{};
64 lock{};
65}
66
67//=============================================================================================
68// Kernel Preemption logic
69//=============================================================================================
70
71// Get next expired node
72static inline alarm_node_t * get_expired( alarm_list_t * alarms, __cfa_time_t currtime ) {
73 if( !alarms->head ) return NULL; // If no alarms return null
74 if( alarms->head->alarm >= currtime ) return NULL; // If alarms head not expired return null
75 return pop(alarms); // Otherwise just pop head
76}
77
78// Tick one frame of the Discrete Event Simulation for alarms
79void tick_preemption() {
80 alarm_node_t * node = NULL; // Used in the while loop but cannot be declared in the while condition
81 alarm_list_t * alarms = &event_kernel->alarms; // Local copy for ease of reading
82 __cfa_time_t currtime = __kernel_get_time(); // Check current time once so we everything "happens at once"
83
84 //Loop throught every thing expired
85 while( node = get_expired( alarms, currtime ) ) {
86
87 // Check if this is a kernel
88 if( node->kernel_alarm ) {
89 preempt( node->proc );
90 }
91 else {
92 timeout( node->thrd );
93 }
94
95 // Check if this is a periodic alarm
96 __cfa_time_t period = node->period;
97 if( period > 0 ) {
98 node->alarm = currtime + period; // Alarm is periodic, add currtime to it (used cached current time)
99 insert( alarms, node ); // Reinsert the node for the next time it triggers
100 }
101 else {
102 node->set = false; // Node is one-shot, just mark it as not pending
103 }
104 }
105
106 // If there are still alarms pending, reset the timer
107 if( alarms->head ) { __kernel_set_timer( alarms->head->alarm - currtime ); }
108}
109
110// Update the preemption of a processor and notify interested parties
111void update_preemption( processor * this, __cfa_time_t duration ) {
112 alarm_node_t * alarm = this->preemption_alarm;
113
114 // Alarms need to be enabled
115 if ( duration > 0 && !alarm->set ) {
116 alarm->alarm = __kernel_get_time() + duration;
117 alarm->period = duration;
118 register_self( alarm );
119 }
120 // Zero duraction but alarm is set
121 else if ( duration == 0 && alarm->set ) {
122 unregister_self( alarm );
123 alarm->alarm = 0;
124 alarm->period = 0;
125 }
126 // If alarm is different from previous, change it
127 else if ( duration > 0 && alarm->period != duration ) {
128 unregister_self( alarm );
129 alarm->alarm = __kernel_get_time() + duration;
130 alarm->period = duration;
131 register_self( alarm );
132 }
133}
134
135//=============================================================================================
136// Kernel Signal Tools
137//=============================================================================================
138
139__cfaabi_dbg_debug_do( static thread_local void * last_interrupt = 0; )
140
141extern "C" {
142 // Disable interrupts by incrementing the counter
143 void disable_interrupts() {
144 preemption_enabled = false;
145 __attribute__((unused)) unsigned short new_val = disable_preempt_count + 1;
146 disable_preempt_count = new_val;
147 verify( new_val < 65_000u ); // If this triggers someone is disabling interrupts without enabling them
148 }
149
150 // Enable interrupts by decrementing the counter
151 // If counter reaches 0, execute any pending CtxSwitch
152 void enable_interrupts( __cfaabi_dbg_ctx_param ) {
153 processor * proc = this_processor; // Cache the processor now since interrupts can start happening after the atomic add
154 thread_desc * thrd = this_thread; // Cache the thread now since interrupts can start happening after the atomic add
155
156 unsigned short prev = disable_preempt_count;
157 disable_preempt_count -= 1;
158 verify( prev != 0u ); // If this triggers someone is enabled already enabled interruptsverify( prev != 0u );
159
160 // Check if we need to prempt the thread because an interrupt was missed
161 if( prev == 1 ) {
162 preemption_enabled = true;
163 if( proc->pending_preemption ) {
164 proc->pending_preemption = false;
165 BlockInternal( thrd );
166 }
167 }
168
169 // For debugging purposes : keep track of the last person to enable the interrupts
170 __cfaabi_dbg_debug_do( proc->last_enable = caller; )
171 }
172
173 // Disable interrupts by incrementint the counter
174 // Don't execute any pending CtxSwitch even if counter reaches 0
175 void enable_interrupts_noPoll() {
176 unsigned short prev = disable_preempt_count;
177 disable_preempt_count -= 1;
178 verifyf( prev != 0u, "Incremented from %u\n", prev ); // If this triggers someone is enabled already enabled interrupts
179 if( prev == 1 ) {
180 preemption_enabled = true;
181 }
182 }
183}
184
185// sigprocmask wrapper : unblock a single signal
186static inline void signal_unblock( int sig ) {
187 sigset_t mask;
188 sigemptyset( &mask );
189 sigaddset( &mask, sig );
190
191 if ( pthread_sigmask( SIG_UNBLOCK, &mask, NULL ) == -1 ) {
192 abortf( "internal error, pthread_sigmask" );
193 }
194}
195
196// sigprocmask wrapper : block a single signal
197static inline void signal_block( int sig ) {
198 sigset_t mask;
199 sigemptyset( &mask );
200 sigaddset( &mask, sig );
201
202 if ( pthread_sigmask( SIG_BLOCK, &mask, NULL ) == -1 ) {
203 abortf( "internal error, pthread_sigmask" );
204 }
205}
206
207// kill wrapper : signal a processor
208static void preempt( processor * this ) {
209 pthread_kill( this->kernel_thread, SIGUSR1 );
210}
211
212// reserved for future use
213static void timeout( thread_desc * this ) {
214 //TODO : implement waking threads
215}
216
217
218// Check if a CtxSwitch signal handler shoud defer
219// If true : preemption is safe
220// If false : preemption is unsafe and marked as pending
221static inline bool preemption_ready() {
222 bool ready = preemption_enabled && !preemption_in_progress; // Check if preemption is safe
223 this_processor->pending_preemption = !ready; // Adjust the pending flag accordingly
224 return ready;
225}
226
227//=============================================================================================
228// Kernel Signal Startup/Shutdown logic
229//=============================================================================================
230
231// Startup routine to activate preemption
232// Called from kernel_startup
233void kernel_start_preemption() {
234 __cfaabi_dbg_print_safe("Kernel : Starting preemption\n");
235
236 // Start with preemption disabled until ready
237 preemption_enabled = false;
238 disable_preempt_count = 1;
239
240 // Initialize the event kernel
241 event_kernel = (event_kernel_t *)&storage_event_kernel;
242 (*event_kernel){};
243
244 // Setup proper signal handlers
245 __kernel_sigaction( SIGUSR1, sigHandler_ctxSwitch, SA_SIGINFO | SA_RESTART ); // CtxSwitch handler
246
247 signal_block( SIGALRM );
248
249 pthread_create( &alarm_thread, NULL, alarm_loop, NULL );
250}
251
252// Shutdown routine to deactivate preemption
253// Called from kernel_shutdown
254void kernel_stop_preemption() {
255 __cfaabi_dbg_print_safe("Kernel : Preemption stopping\n");
256
257 // Block all signals since we are already shutting down
258 sigset_t mask;
259 sigfillset( &mask );
260 sigprocmask( SIG_BLOCK, &mask, NULL );
261
262 // Notify the alarm thread of the shutdown
263 sigval val = { 1 };
264 pthread_sigqueue( alarm_thread, SIGALRM, val );
265
266 // Wait for the preemption thread to finish
267 pthread_join( alarm_thread, NULL );
268
269 // Preemption is now fully stopped
270
271 __cfaabi_dbg_print_safe("Kernel : Preemption stopped\n");
272}
273
274// Raii ctor/dtor for the preemption_scope
275// Used by thread to control when they want to receive preemption signals
276void ?{}( preemption_scope & this, processor * proc ) {
277 (this.alarm){ proc, zero_time, zero_time };
278 this.proc = proc;
279 this.proc->preemption_alarm = &this.alarm;
280
281 update_preemption( this.proc, from_us(this.proc->cltr->preemption) );
282}
283
284void ^?{}( preemption_scope & this ) {
285 disable_interrupts();
286
287 update_preemption( this.proc, zero_time );
288}
289
290//=============================================================================================
291// Kernel Signal Handlers
292//=============================================================================================
293
294// Context switch signal handler
295// Receives SIGUSR1 signal and causes the current thread to yield
296void sigHandler_ctxSwitch( __CFA_SIGPARMS__ ) {
297 __cfaabi_dbg_debug_do( last_interrupt = (void *)(cxt->uc_mcontext.CFA_REG_IP); )
298
299 // Check if it is safe to preempt here
300 if( !preemption_ready() ) { return; }
301
302 __cfaabi_dbg_print_buffer_decl(" KERNEL: preempting core %p (%p).\n", this_processor, this_thread);
303
304 preemption_in_progress = true; // Sync flag : prevent recursive calls to the signal handler
305 signal_unblock( SIGUSR1 ); // We are about to CtxSwitch out of the signal handler, let other handlers in
306 preemption_in_progress = false; // Clear the in progress flag
307
308 // Preemption can occur here
309
310 BlockInternal( (thread_desc*)this_thread ); // Do the actual CtxSwitch
311}
312
313// Main of the alarm thread
314// Waits on SIGALRM and send SIGUSR1 to whom ever needs it
315void * alarm_loop( __attribute__((unused)) void * args ) {
316 // Block sigalrms to control when they arrive
317 sigset_t mask;
318 sigemptyset( &mask );
319 sigaddset( &mask, SIGALRM );
320
321 if ( pthread_sigmask( SIG_BLOCK, &mask, NULL ) == -1 ) {
322 abortf( "internal error, pthread_sigmask" );
323 }
324
325 // Main loop
326 while( true ) {
327 // Wait for a sigalrm
328 siginfo_t info;
329 int sig = sigwaitinfo( &mask, &info );
330
331 if( sig < 0 ) {
332 //Error!
333 int err = errno;
334 switch( err ) {
335 case EAGAIN :
336 case EINTR :
337 continue;
338 case EINVAL :
339 abortf("Timeout was invalid.");
340 default:
341 abortf("Unhandled error %d", err);
342 }
343 }
344
345 // If another signal arrived something went wrong
346 assertf(sig == SIGALRM, "Kernel Internal Error, sigwait: Unexpected signal %d (%d : %d)\n", sig, info.si_code, info.si_value.sival_int);
347
348 // __cfaabi_dbg_print_safe("Kernel : Caught alarm from %d with %d\n", info.si_code, info.si_value.sival_int );
349 // Switch on the code (a.k.a. the sender) to
350 switch( info.si_code )
351 {
352 // Timers can apparently be marked as sent for the kernel
353 // In either case, tick preemption
354 case SI_TIMER:
355 case SI_KERNEL:
356 // __cfaabi_dbg_print_safe("Kernel : Preemption thread tick\n");
357 lock( event_kernel->lock __cfaabi_dbg_ctx2 );
358 tick_preemption();
359 unlock( event_kernel->lock );
360 break;
361 // Signal was not sent by the kernel but by an other thread
362 case SI_QUEUE:
363 // For now, other thread only signal the alarm thread to shut it down
364 // If this needs to change use info.si_value and handle the case here
365 goto EXIT;
366 }
367 }
368
369EXIT:
370 __cfaabi_dbg_print_safe("Kernel : Preemption thread stopping\n");
371 return NULL;
372}
373
374// Local Variables: //
375// mode: c //
376// tab-width: 4 //
377// End: //
Note: See TracBrowser for help on using the repository browser.