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

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since ed235b6 was ed235b6, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Fixed interrupts and coroutine deletion

  • Property mode set to 100644
File size: 15.6 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 Jul 21 22:36:05 2017
13// Update Count     : 2
14//
15
16#include "libhdr.h"
17#include "preemption.h"
18
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
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#ifdef __x86_64__
64#define CFA_REG_IP REG_RIP
65#else
66#define CFA_REG_IP REG_EIP
67#endif
68
69KERNEL_STORAGE(event_kernel_t, event_kernel);         // private storage for event kernel
70event_kernel_t * event_kernel;                        // kernel public handle to even kernel
71static pthread_t alarm_thread;                        // pthread handle to alarm thread
72
73void ?{}(event_kernel_t & this) {
74        (this.alarms){};
75        (this.lock){};
76}
77
78//=============================================================================================
79// Kernel Preemption logic
80//=============================================================================================
81
82// Get next expired node
83static inline alarm_node_t * get_expired( alarm_list_t * alarms, __cfa_time_t currtime ) {
84        if( !alarms->head ) return NULL;                          // If no alarms return null
85        if( alarms->head->alarm >= currtime ) return NULL;        // If alarms head not expired return null
86        return pop(alarms);                                       // Otherwise just pop head
87}
88
89// Tick one frame of the Discrete Event Simulation for alarms
90void tick_preemption() {
91        alarm_node_t * node = NULL;                     // Used in the while loop but cannot be declared in the while condition
92        alarm_list_t * alarms = &event_kernel->alarms;  // Local copy for ease of reading
93        __cfa_time_t currtime = __kernel_get_time();    // Check current time once so we everything "happens at once"
94
95        //Loop throught every thing expired
96        while( node = get_expired( alarms, currtime ) ) {
97
98                // Check if this is a kernel
99                if( node->kernel_alarm ) {
100                        preempt( node->proc );
101                }
102                else {
103                        timeout( node->thrd );
104                }
105
106                // Check if this is a periodic alarm
107                __cfa_time_t period = node->period;
108                if( period > 0 ) {
109                        node->alarm = currtime + period;    // Alarm is periodic, add currtime to it (used cached current time)
110                        insert( alarms, node );             // Reinsert the node for the next time it triggers
111                }
112                else {
113                        node->set = false;                  // Node is one-shot, just mark it as not pending
114                }
115        }
116
117        // If there are still alarms pending, reset the timer
118        if( alarms->head ) { __kernel_set_timer( alarms->head->alarm - currtime ); }
119}
120
121// Update the preemption of a processor and notify interested parties
122void update_preemption( processor * this, __cfa_time_t duration ) {
123        alarm_node_t * alarm = this->preemption_alarm;
124
125        // Alarms need to be enabled
126        if ( duration > 0 && !alarm->set ) {
127                alarm->alarm = __kernel_get_time() + duration;
128                alarm->period = duration;
129                register_self( alarm );
130        }
131        // Zero duraction but alarm is set
132        else if ( duration == 0 && alarm->set ) {
133                unregister_self( alarm );
134                alarm->alarm = 0;
135                alarm->period = 0;
136        }
137        // If alarm is different from previous, change it
138        else if ( duration > 0 && alarm->period != duration ) {
139                unregister_self( alarm );
140                alarm->alarm = __kernel_get_time() + duration;
141                alarm->period = duration;
142                register_self( alarm );
143        }
144}
145
146//=============================================================================================
147// Kernel Signal Tools
148//=============================================================================================
149
150LIB_DEBUG_DO( static thread_local void * last_interrupt = 0; )
151
152extern "C" {
153        // Disable interrupts by incrementing the counter
154        void disable_interrupts() {
155                __attribute__((unused)) unsigned short new_val = __atomic_add_fetch_2( &disable_preempt_count, 1, __ATOMIC_SEQ_CST );
156                verify( new_val < 65_000u );              // If this triggers someone is disabling interrupts without enabling them
157        }
158
159        // Enable interrupts by decrementing the counter
160        // If counter reaches 0, execute any pending CtxSwitch
161        void enable_interrupts( DEBUG_CTX_PARAM ) {
162                processor * proc   = this_processor;      // Cache the processor now since interrupts can start happening after the atomic add
163                thread_desc * thrd = this_thread;         // Cache the thread now since interrupts can start happening after the atomic add
164
165                unsigned short prev = __atomic_fetch_add_2( &disable_preempt_count, -1, __ATOMIC_SEQ_CST );
166                verify( prev != 0u );                     // If this triggers someone is enabled already enabled interruptsverify( prev != 0u );
167
168                // Check if we need to prempt the thread because an interrupt was missed
169                if( prev == 1 && proc->pending_preemption ) {
170                        proc->pending_preemption = false;
171                        BlockInternal( thrd );
172                }
173
174                // For debugging purposes : keep track of the last person to enable the interrupts
175                LIB_DEBUG_DO( proc->last_enable = caller; )
176        }
177
178        // Disable interrupts by incrementint the counter
179        // Don't execute any pending CtxSwitch even if counter reaches 0
180        void enable_interrupts_noPoll() {
181                __attribute__((unused)) unsigned short prev = __atomic_fetch_add_2( &disable_preempt_count, -1, __ATOMIC_SEQ_CST );
182                verify( prev != 0u );                     // If this triggers someone is enabled already enabled interrupts
183        }
184}
185
186// sigprocmask wrapper : unblock a single signal
187static inline void signal_unblock( int sig ) {
188        sigset_t mask;
189        sigemptyset( &mask );
190        sigaddset( &mask, sig );
191
192        if ( pthread_sigmask( SIG_UNBLOCK, &mask, NULL ) == -1 ) {
193            abortf( "internal error, pthread_sigmask" );
194        }
195}
196
197// sigprocmask wrapper : block a single signal
198static inline void signal_block( int sig ) {
199        sigset_t mask;
200        sigemptyset( &mask );
201        sigaddset( &mask, sig );
202
203        if ( pthread_sigmask( SIG_BLOCK, &mask, NULL ) == -1 ) {
204            abortf( "internal error, pthread_sigmask" );
205        }
206}
207
208// kill wrapper : signal a processor
209static void preempt( processor * this ) {
210        pthread_kill( this->kernel_thread, SIGUSR1 );
211}
212
213// reserved for future use
214static void timeout( thread_desc * this ) {
215        //TODO : implement waking threads
216}
217
218
219// Check if a CtxSwitch signal handler shoud defer
220// If true  : preemption is safe
221// If false : preemption is unsafe and marked as pending
222static inline bool preemption_ready() {
223        bool ready = disable_preempt_count == 0 && !preemption_in_progress; // Check if preemption is safe
224        this_processor->pending_preemption = !ready;                        // Adjust the pending flag accordingly
225        return ready;
226}
227
228//=============================================================================================
229// Kernel Signal Startup/Shutdown logic
230//=============================================================================================
231
232// Startup routine to activate preemption
233// Called from kernel_startup
234void kernel_start_preemption() {
235        LIB_DEBUG_PRINT_SAFE("Kernel : Starting preemption\n");
236
237        // Start with preemption disabled until ready
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        // __kernel_sigaction( SIGSEGV, sigHandler_segv     , SA_SIGINFO );      // Failure handler
247        // __kernel_sigaction( SIGBUS , sigHandler_segv     , SA_SIGINFO );      // Failure 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        LIB_DEBUG_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        LIB_DEBUG_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        LIB_DEBUG_DO( last_interrupt = (void *)(cxt->uc_mcontext.gregs[CFA_REG_IP]); )
300
301        // Check if it is safe to preempt here
302        if( !preemption_ready() ) { return; }
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 another signal arrived something went wrong
332                assertf(sig == SIGALRM, "Kernel Internal Error, sigwait: Unexpected signal %d (%d : %d)\n", sig, info.si_code, info.si_value.sival_int);
333
334                // LIB_DEBUG_PRINT_SAFE("Kernel : Caught alarm from %d with %d\n", info.si_code, info.si_value.sival_int );
335                // Switch on the code (a.k.a. the sender) to
336                switch( info.si_code )
337                {
338                // Timers can apparently be marked as sent for the kernel
339                // In either case, tick preemption
340                case SI_TIMER:
341                case SI_KERNEL:
342                        // LIB_DEBUG_PRINT_SAFE("Kernel : Preemption thread tick\n");
343                        lock( &event_kernel->lock DEBUG_CTX2 );
344                        tick_preemption();
345                        unlock( &event_kernel->lock );
346                        break;
347                // Signal was not sent by the kernel but by an other thread
348                case SI_QUEUE:
349                        // For now, other thread only signal the alarm thread to shut it down
350                        // If this needs to change use info.si_value and handle the case here
351                        goto EXIT;
352                }
353        }
354
355EXIT:
356        LIB_DEBUG_PRINT_SAFE("Kernel : Preemption thread stopping\n");
357        return NULL;
358}
359
360// Sigaction wrapper : register an signal handler
361static void __kernel_sigaction( int sig, void (*handler)(__CFA_SIGPARMS__), int flags ) {
362        struct sigaction act;
363
364        act.sa_sigaction = (void (*)(int, siginfo_t *, void *))handler;
365        act.sa_flags = flags;
366
367        if ( sigaction( sig, &act, NULL ) == -1 ) {
368                LIB_DEBUG_PRINT_BUFFER_DECL( STDERR_FILENO,
369                        " __kernel_sigaction( sig:%d, handler:%p, flags:%d ), problem installing signal handler, error(%d) %s.\n",
370                        sig, handler, flags, errno, strerror( errno )
371                );
372                _exit( EXIT_FAILURE );
373        }
374}
375
376// Sigaction wrapper : restore default handler
377static void __kernel_sigdefault( int sig ) {
378        struct sigaction act;
379
380        act.sa_handler = SIG_DFL;
381        act.sa_flags = 0;
382        sigemptyset( &act.sa_mask );
383
384        if ( sigaction( sig, &act, NULL ) == -1 ) {
385                LIB_DEBUG_PRINT_BUFFER_DECL( STDERR_FILENO,
386                        " __kernel_sigdefault( sig:%d ), problem reseting signal handler, error(%d) %s.\n",
387                        sig, errno, strerror( errno )
388                );
389                _exit( EXIT_FAILURE );
390        }
391}
392
393//=============================================================================================
394// Terminating Signals logic
395//=============================================================================================
396
397LIB_DEBUG_DO(
398        static void __kernel_backtrace( int start ) {
399                // skip first N stack frames
400
401                enum { Frames = 50 };
402                void * array[Frames];
403                int size = backtrace( array, Frames );
404                char ** messages = backtrace_symbols( array, size );
405
406                // find executable name
407                *index( messages[0], '(' ) = '\0';
408                #ifdef __USE_STREAM__
409                serr | "Stack back trace for:" | messages[0] | endl;
410                #else
411                fprintf( stderr, "Stack back trace for: %s\n", messages[0]);
412                #endif
413
414                // skip last 2 stack frames after main
415                for ( int i = start; i < size && messages != NULL; i += 1 ) {
416                        char * name = NULL;
417                        char * offset_begin = NULL;
418                        char * offset_end = NULL;
419
420                        for ( char *p = messages[i]; *p; ++p ) {
421                                // find parantheses and +offset
422                                if ( *p == '(' ) {
423                                        name = p;
424                                }
425                                else if ( *p == '+' ) {
426                                        offset_begin = p;
427                                }
428                                else if ( *p == ')' ) {
429                                        offset_end = p;
430                                        break;
431                                }
432                        }
433
434                        // if line contains symbol print it
435                        int frameNo = i - start;
436                        if ( name && offset_begin && offset_end && name < offset_begin ) {
437                                // delimit strings
438                                *name++ = '\0';
439                                *offset_begin++ = '\0';
440                                *offset_end++ = '\0';
441
442                                #ifdef __USE_STREAM__
443                                serr    | "("  | frameNo | ")" | messages[i] | ":"
444                                        | name | "+" | offset_begin | offset_end | endl;
445                                #else
446                                fprintf( stderr, "(%i) %s : %s + %s %s\n", frameNo, messages[i], name, offset_begin, offset_end);
447                                #endif
448                        }
449                        // otherwise, print the whole line
450                        else {
451                                #ifdef __USE_STREAM__
452                                serr | "(" | frameNo | ")" | messages[i] | endl;
453                                #else
454                                fprintf( stderr, "(%i) %s\n", frameNo, messages[i] );
455                                #endif
456                        }
457                }
458
459                free( messages );
460        }
461)
462
463// void sigHandler_segv( __CFA_SIGPARMS__ ) {
464//      LIB_DEBUG_DO(
465//              #ifdef __USE_STREAM__
466//              serr    | "*CFA runtime error* program cfa-cpp terminated with"
467//                      | (sig == SIGSEGV ? "segment fault." : "bus error.")
468//                      | endl;
469//              #else
470//              fprintf( stderr, "*CFA runtime error* program cfa-cpp terminated with %s\n", sig == SIGSEGV ? "segment fault." : "bus error." );
471//              #endif
472
473//              // skip first 2 stack frames
474//              __kernel_backtrace( 1 );
475//      )
476//      exit( EXIT_FAILURE );
477// }
478
479// void sigHandler_abort( __CFA_SIGPARMS__ ) {
480//      // skip first 6 stack frames
481//      LIB_DEBUG_DO( __kernel_backtrace( 6 ); )
482
483//      // reset default signal handler
484//      __kernel_sigdefault( SIGABRT );
485
486//      raise( SIGABRT );
487// }
488
489// Local Variables: //
490// mode: c //
491// tab-width: 4 //
492// End: //
Note: See TracBrowser for help on using the repository browser.