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

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 b0c32da was 2e9aed4, checked in by Thierry Delisle <tdelisle@…>, 8 years ago

Fixed non-preemptive locks

  • Property mode set to 100644
File size: 12.1 KB
RevLine 
[c81ebf9]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
[6b0b624]11// Last Modified By : Peter A. Buhr
[258e6ad5]12// Last Modified On : Tue Jan 23 17:59:30 2018
13// Update Count : 7
[c81ebf9]14//
15
16#include "preemption.h"
17
[b158d8f]18#define ftype `ftype`
[c81ebf9]19extern "C" {
[82ff5845]20#include <errno.h>
21#include <stdio.h>
22#include <string.h>
23#include <unistd.h>
[c81ebf9]24}
[b158d8f]25#undef ftype
[1c273d0]26
[dbe9b08]27#include "bits/signal.h"
[82ff5845]28
[969b3fe]29//TODO move to defaults
[82ff5845]30#define __CFA_DEFAULT_PREEMPTION__ 10000
[c81ebf9]31
[969b3fe]32//TODO move to defaults
[c81ebf9]33__attribute__((weak)) unsigned int default_preemption() {
34 return __CFA_DEFAULT_PREEMPTION__;
35}
36
[969b3fe]37// FwdDeclarations : timeout handlers
[c81ebf9]38static void preempt( processor * this );
39static void timeout( thread_desc * this );
40
[969b3fe]41// FwdDeclarations : Signal handlers
[82ff5845]42void sigHandler_ctxSwitch( __CFA_SIGPARMS__ );
[1c273d0]43void sigHandler_segv ( __CFA_SIGPARMS__ );
44void sigHandler_abort ( __CFA_SIGPARMS__ );
[82ff5845]45
[969b3fe]46// FwdDeclarations : alarm thread main
47void * alarm_loop( __attribute__((unused)) void * args );
48
49// Machine specific register name
[b158d8f]50#if defined(__x86_64__)
[cd17862]51#define CFA_REG_IP REG_RIP
[b158d8f]52#elif defined(__i386__)
[cd17862]53#define CFA_REG_IP REG_EIP
[b158d8f]54#elif defined(__ARM_ARCH__)
55#define CFA_REG_IP REG_R15
[cd17862]56#endif
57
[969b3fe]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
[9236060]62void ?{}(event_kernel_t & this) {
63 (this.alarms){};
64 (this.lock){};
[969b3fe]65}
[82ff5845]66
[c81ebf9]67//=============================================================================================
68// Kernel Preemption logic
69//=============================================================================================
70
[969b3fe]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
[c81ebf9]79void tick_preemption() {
[969b3fe]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"
[8cb529e]83
[969b3fe]84 //Loop throught every thing expired
85 while( node = get_expired( alarms, currtime ) ) {
[1c273d0]86
[969b3fe]87 // Check if this is a kernel
[c81ebf9]88 if( node->kernel_alarm ) {
89 preempt( node->proc );
90 }
91 else {
92 timeout( node->thrd );
93 }
94
[969b3fe]95 // Check if this is a periodic alarm
[8cb529e]96 __cfa_time_t period = node->period;
97 if( period > 0 ) {
[969b3fe]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
[c81ebf9]100 }
101 else {
[969b3fe]102 node->set = false; // Node is one-shot, just mark it as not pending
[c81ebf9]103 }
104 }
105
[969b3fe]106 // If there are still alarms pending, reset the timer
107 if( alarms->head ) { __kernel_set_timer( alarms->head->alarm - currtime ); }
[c81ebf9]108}
109
[969b3fe]110// Update the preemption of a processor and notify interested parties
[c81ebf9]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//=============================================================================================
[cd17862]136// Kernel Signal Tools
[c81ebf9]137//=============================================================================================
138
[36982fc]139__cfaabi_dbg_debug_do( static thread_local void * last_interrupt = 0; )
[b227f68]140
[82ff5845]141extern "C" {
[969b3fe]142 // Disable interrupts by incrementing the counter
[82ff5845]143 void disable_interrupts() {
[4e6fb8e]144 __attribute__((unused)) unsigned short new_val = __atomic_add_fetch_2( &disable_preempt_count, 1, __ATOMIC_SEQ_CST );
[969b3fe]145 verify( new_val < 65_000u ); // If this triggers someone is disabling interrupts without enabling them
[82ff5845]146 }
147
[969b3fe]148 // Enable interrupts by decrementing the counter
149 // If counter reaches 0, execute any pending CtxSwitch
[36982fc]150 void enable_interrupts( __cfaabi_dbg_ctx_param ) {
[969b3fe]151 processor * proc = this_processor; // Cache the processor now since interrupts can start happening after the atomic add
152 thread_desc * thrd = this_thread; // Cache the thread now since interrupts can start happening after the atomic add
153
[4e6fb8e]154 unsigned short prev = __atomic_fetch_add_2( &disable_preempt_count, -1, __ATOMIC_SEQ_CST );
[969b3fe]155 verify( prev != 0u ); // If this triggers someone is enabled already enabled interruptsverify( prev != 0u );
156
157 // Check if we need to prempt the thread because an interrupt was missed
[1c273d0]158 if( prev == 1 && proc->pending_preemption ) {
159 proc->pending_preemption = false;
160 BlockInternal( thrd );
[82ff5845]161 }
[4e6fb8e]162
[969b3fe]163 // For debugging purposes : keep track of the last person to enable the interrupts
[36982fc]164 __cfaabi_dbg_debug_do( proc->last_enable = caller; )
[82ff5845]165 }
[969b3fe]166
167 // Disable interrupts by incrementint the counter
168 // Don't execute any pending CtxSwitch even if counter reaches 0
169 void enable_interrupts_noPoll() {
170 __attribute__((unused)) unsigned short prev = __atomic_fetch_add_2( &disable_preempt_count, -1, __ATOMIC_SEQ_CST );
[2e9aed4]171 verifyf( prev != 0u, "Incremented from %u\n", prev ); // If this triggers someone is enabled already enabled interrupts
[969b3fe]172 }
[82ff5845]173}
174
[969b3fe]175// sigprocmask wrapper : unblock a single signal
[1c273d0]176static inline void signal_unblock( int sig ) {
[82ff5845]177 sigset_t mask;
178 sigemptyset( &mask );
[1c273d0]179 sigaddset( &mask, sig );
[82ff5845]180
[47ecf2b]181 if ( pthread_sigmask( SIG_UNBLOCK, &mask, NULL ) == -1 ) {
182 abortf( "internal error, pthread_sigmask" );
[cd17862]183 }
[82ff5845]184}
185
[969b3fe]186// sigprocmask wrapper : block a single signal
[cd17862]187static inline void signal_block( int sig ) {
188 sigset_t mask;
189 sigemptyset( &mask );
190 sigaddset( &mask, sig );
[47ecf2b]191
[cd17862]192 if ( pthread_sigmask( SIG_BLOCK, &mask, NULL ) == -1 ) {
193 abortf( "internal error, pthread_sigmask" );
194 }
195}
[47ecf2b]196
[969b3fe]197// kill wrapper : signal a processor
[cd17862]198static void preempt( processor * this ) {
199 pthread_kill( this->kernel_thread, SIGUSR1 );
[1c273d0]200}
[82ff5845]201
[969b3fe]202// reserved for future use
[cd17862]203static void timeout( thread_desc * this ) {
204 //TODO : implement waking threads
205}
206
[969b3fe]207
208// Check if a CtxSwitch signal handler shoud defer
209// If true : preemption is safe
210// If false : preemption is unsafe and marked as pending
211static inline bool preemption_ready() {
212 bool ready = disable_preempt_count == 0 && !preemption_in_progress; // Check if preemption is safe
213 this_processor->pending_preemption = !ready; // Adjust the pending flag accordingly
214 return ready;
215}
216
[cd17862]217//=============================================================================================
218// Kernel Signal Startup/Shutdown logic
219//=============================================================================================
220
[969b3fe]221// Startup routine to activate preemption
222// Called from kernel_startup
[cd17862]223void kernel_start_preemption() {
[36982fc]224 __cfaabi_dbg_print_safe("Kernel : Starting preemption\n");
[969b3fe]225
226 // Start with preemption disabled until ready
227 disable_preempt_count = 1;
228
229 // Initialize the event kernel
230 event_kernel = (event_kernel_t *)&storage_event_kernel;
[9236060]231 (*event_kernel){};
[969b3fe]232
233 // Setup proper signal handlers
[ed235b6]234 __kernel_sigaction( SIGUSR1, sigHandler_ctxSwitch, SA_SIGINFO | SA_RESTART ); // CtxSwitch handler
[cd17862]235
236 signal_block( SIGALRM );
237
238 pthread_create( &alarm_thread, NULL, alarm_loop, NULL );
239}
240
[969b3fe]241// Shutdown routine to deactivate preemption
242// Called from kernel_shutdown
[cd17862]243void kernel_stop_preemption() {
[36982fc]244 __cfaabi_dbg_print_safe("Kernel : Preemption stopping\n");
[d6ff3ff]245
[969b3fe]246 // Block all signals since we are already shutting down
[cd17862]247 sigset_t mask;
248 sigfillset( &mask );
249 sigprocmask( SIG_BLOCK, &mask, NULL );
250
[969b3fe]251 // Notify the alarm thread of the shutdown
[a0b3e32]252 sigval val = { 1 };
253 pthread_sigqueue( alarm_thread, SIGALRM, val );
[969b3fe]254
255 // Wait for the preemption thread to finish
[cd17862]256 pthread_join( alarm_thread, NULL );
[969b3fe]257
258 // Preemption is now fully stopped
259
[36982fc]260 __cfaabi_dbg_print_safe("Kernel : Preemption stopped\n");
[cd17862]261}
262
[969b3fe]263// Raii ctor/dtor for the preemption_scope
264// Used by thread to control when they want to receive preemption signals
[242a902]265void ?{}( preemption_scope & this, processor * proc ) {
[9236060]266 (this.alarm){ proc, zero_time, zero_time };
[242a902]267 this.proc = proc;
268 this.proc->preemption_alarm = &this.alarm;
[969b3fe]269
[9236060]270 update_preemption( this.proc, from_us(this.proc->cltr->preemption) );
[cd17862]271}
272
[242a902]273void ^?{}( preemption_scope & this ) {
[cd17862]274 disable_interrupts();
275
[9236060]276 update_preemption( this.proc, zero_time );
[cd17862]277}
278
279//=============================================================================================
280// Kernel Signal Handlers
281//=============================================================================================
[47ecf2b]282
[969b3fe]283// Context switch signal handler
284// Receives SIGUSR1 signal and causes the current thread to yield
[1c273d0]285void sigHandler_ctxSwitch( __CFA_SIGPARMS__ ) {
[258e6ad5]286#if defined( __ARM_ARCH )
[b158d8f]287 __cfaabi_dbg_debug_do( last_interrupt = (void *)(cxt->uc_mcontext.arm_pc); )
[258e6ad5]288#else
289 __cfaabi_dbg_debug_do( last_interrupt = (void *)(cxt->uc_mcontext.gregs[CFA_REG_IP]); )
290#endif
[969b3fe]291
[258e6ad5]292 // Check if it is safe to preempt here
[969b3fe]293 if( !preemption_ready() ) { return; }
294
[2e9aed4]295 __cfaabi_dbg_print_buffer_decl(" KERNEL: preempting core %p (%p).\n", this_processor, this_thread);
[05615ba]296
[969b3fe]297 preemption_in_progress = true; // Sync flag : prevent recursive calls to the signal handler
298 signal_unblock( SIGUSR1 ); // We are about to CtxSwitch out of the signal handler, let other handlers in
299 preemption_in_progress = false; // Clear the in progress flag
300
301 // Preemption can occur here
302
303 BlockInternal( (thread_desc*)this_thread ); // Do the actual CtxSwitch
[c81ebf9]304}
305
[969b3fe]306// Main of the alarm thread
307// Waits on SIGALRM and send SIGUSR1 to whom ever needs it
[cd17862]308void * alarm_loop( __attribute__((unused)) void * args ) {
[969b3fe]309 // Block sigalrms to control when they arrive
[cd17862]310 sigset_t mask;
311 sigemptyset( &mask );
312 sigaddset( &mask, SIGALRM );
313
314 if ( pthread_sigmask( SIG_BLOCK, &mask, NULL ) == -1 ) {
315 abortf( "internal error, pthread_sigmask" );
[82ff5845]316 }
[c81ebf9]317
[969b3fe]318 // Main loop
[cd17862]319 while( true ) {
[969b3fe]320 // Wait for a sigalrm
[a0b3e32]321 siginfo_t info;
322 int sig = sigwaitinfo( &mask, &info );
[969b3fe]323
[e2f7bc3]324 if( sig < 0 ) {
325 //Error!
326 int err = errno;
327 switch( err ) {
328 case EAGAIN :
329 case EINTR :
330 continue;
331 case EINVAL :
332 abortf("Timeout was invalid.");
333 default:
334 abortf("Unhandled error %d", err);
335 }
336 }
337
[969b3fe]338 // If another signal arrived something went wrong
[8cb529e]339 assertf(sig == SIGALRM, "Kernel Internal Error, sigwait: Unexpected signal %d (%d : %d)\n", sig, info.si_code, info.si_value.sival_int);
340
[36982fc]341 // __cfaabi_dbg_print_safe("Kernel : Caught alarm from %d with %d\n", info.si_code, info.si_value.sival_int );
[969b3fe]342 // Switch on the code (a.k.a. the sender) to
[8cb529e]343 switch( info.si_code )
[a0b3e32]344 {
[969b3fe]345 // Timers can apparently be marked as sent for the kernel
346 // In either case, tick preemption
[8cb529e]347 case SI_TIMER:
348 case SI_KERNEL:
[36982fc]349 // __cfaabi_dbg_print_safe("Kernel : Preemption thread tick\n");
350 lock( event_kernel->lock __cfaabi_dbg_ctx2 );
[8cb529e]351 tick_preemption();
[ea7d2b0]352 unlock( event_kernel->lock );
[8cb529e]353 break;
[969b3fe]354 // Signal was not sent by the kernel but by an other thread
[8cb529e]355 case SI_QUEUE:
[969b3fe]356 // For now, other thread only signal the alarm thread to shut it down
357 // If this needs to change use info.si_value and handle the case here
[8cb529e]358 goto EXIT;
[cd17862]359 }
360 }
[a0b3e32]361
[8cb529e]362EXIT:
[36982fc]363 __cfaabi_dbg_print_safe("Kernel : Preemption thread stopping\n");
[a0b3e32]364 return NULL;
[82ff5845]365}
366
[6b0b624]367// Local Variables: //
368// mode: c //
369// tab-width: 4 //
370// End: //
Note: See TracBrowser for help on using the repository browser.