source: src/libcfa/concurrency/preemption.c @ 35b06a8

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 35b06a8 was a0b3e32, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Alarmloop no longer uses signals other than SIGALRM

  • Property mode set to 100644
File size: 12.0 KB
RevLine 
[c81ebf9]1//                              -*- Mode: CFA -*-
2//
3// Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo
4//
5// The contents of this file are covered under the licence agreement in the
6// file "LICENCE" distributed with Cforall.
7//
8// signal.c --
9//
10// Author           : Thierry Delisle
11// Created On       : Mon Jun 5 14:20:42 2017
12// Last Modified By : Thierry Delisle
13// Last Modified On : --
14// Update Count     : 0
15//
16
[2ac095d]17#include "libhdr.h"
[c81ebf9]18#include "preemption.h"
19
20extern "C" {
[82ff5845]21#include <errno.h>
[1c273d0]22#include <execinfo.h>
[4e6fb8e]23#define __USE_GNU
[c81ebf9]24#include <signal.h>
[4e6fb8e]25#undef __USE_GNU
[82ff5845]26#include <stdio.h>
27#include <string.h>
28#include <unistd.h>
[c81ebf9]29}
30
[1c273d0]31
32#ifdef __USE_STREAM__
33#include "fstream"
34#endif
[82ff5845]35
36#define __CFA_DEFAULT_PREEMPTION__ 10000
[c81ebf9]37
38__attribute__((weak)) unsigned int default_preemption() {
39        return __CFA_DEFAULT_PREEMPTION__;
40}
41
[82ff5845]42#define __CFA_SIGCXT__ ucontext_t *
43#define __CFA_SIGPARMS__ __attribute__((unused)) int sig, __attribute__((unused)) siginfo_t *sfp, __attribute__((unused)) __CFA_SIGCXT__ cxt
44
[c81ebf9]45static void preempt( processor   * this );
46static void timeout( thread_desc * this );
47
[82ff5845]48void sigHandler_ctxSwitch( __CFA_SIGPARMS__ );
49void sigHandler_alarm    ( __CFA_SIGPARMS__ );
[1c273d0]50void sigHandler_segv     ( __CFA_SIGPARMS__ );
51void sigHandler_abort    ( __CFA_SIGPARMS__ );
[82ff5845]52
53static void __kernel_sigaction( int sig, void (*handler)(__CFA_SIGPARMS__), int flags );
[cd17862]54LIB_DEBUG_DO( bool validate( alarm_list_t * this ); )
55
56#ifdef __x86_64__
57#define CFA_REG_IP REG_RIP
58#else
59#define CFA_REG_IP REG_EIP
60#endif
61
[82ff5845]62
[c81ebf9]63//=============================================================================================
64// Kernel Preemption logic
65//=============================================================================================
66
67void tick_preemption() {
[1c273d0]68        // LIB_DEBUG_PRINT_BUFFER_DECL( STDERR_FILENO, "Ticking preemption\n" );
[82ff5845]69
[c81ebf9]70        alarm_list_t * alarms = &systemProcessor->alarms;
71        __cfa_time_t currtime = __kernel_get_time();
72        while( alarms->head && alarms->head->alarm < currtime ) {
73                alarm_node_t * node = pop(alarms);
[1c273d0]74                // LIB_DEBUG_PRINT_BUFFER_LOCAL( STDERR_FILENO, "Ticking %p\n", node );
75
[c81ebf9]76                if( node->kernel_alarm ) {
77                        preempt( node->proc );
78                }
79                else {
80                        timeout( node->thrd );
81                }
82
[1c273d0]83                verify( validate( alarms ) );
[4e6fb8e]84
[c81ebf9]85                if( node->period > 0 ) {
[82ff5845]86                        node->alarm = currtime + node->period;
[c81ebf9]87                        insert( alarms, node );
88                }
89                else {
90                        node->set = false;
91                }
92        }
93
94        if( alarms->head ) {
95                __kernel_set_timer( alarms->head->alarm - currtime );
96        }
[82ff5845]97
[0b33412]98        verify( validate( alarms ) );
[1c273d0]99        // LIB_DEBUG_PRINT_BUFFER_LOCAL( STDERR_FILENO, "Ticking preemption done\n" );
[c81ebf9]100}
101
102void update_preemption( processor * this, __cfa_time_t duration ) {
[1c273d0]103        LIB_DEBUG_PRINT_BUFFER_DECL( STDERR_FILENO, "Processor : %p updating preemption to %lu\n", this, duration );
[82ff5845]104
[c81ebf9]105        alarm_node_t * alarm = this->preemption_alarm;
[82ff5845]106        duration *= 1000;
[c81ebf9]107
108        // Alarms need to be enabled
109        if ( duration > 0 && !alarm->set ) {
110                alarm->alarm = __kernel_get_time() + duration;
111                alarm->period = duration;
112                register_self( alarm );
113        }
114        // Zero duraction but alarm is set
115        else if ( duration == 0 && alarm->set ) {
116                unregister_self( alarm );
117                alarm->alarm = 0;
118                alarm->period = 0;
119        }
120        // If alarm is different from previous, change it
121        else if ( duration > 0 && alarm->period != duration ) {
122                unregister_self( alarm );
123                alarm->alarm = __kernel_get_time() + duration;
124                alarm->period = duration;
125                register_self( alarm );
126        }
127}
128
129//=============================================================================================
[cd17862]130// Kernel Signal Tools
[c81ebf9]131//=============================================================================================
132
[b227f68]133LIB_DEBUG_DO( static thread_local void * last_interrupt = 0; )
134
[82ff5845]135extern "C" {
136        void disable_interrupts() {
[4e6fb8e]137                __attribute__((unused)) unsigned short new_val = __atomic_add_fetch_2( &disable_preempt_count, 1, __ATOMIC_SEQ_CST );
[0b33412]138                verify( new_val < (unsigned short)65_000 );
139                verify( new_val != (unsigned short) 0 );
[82ff5845]140        }
141
142        void enable_interrupts_noRF() {
[2ac095d]143                __attribute__((unused)) unsigned short prev = __atomic_fetch_add_2( &disable_preempt_count, -1, __ATOMIC_SEQ_CST );
[0b33412]144                verify( prev != (unsigned short) 0 );
[82ff5845]145        }
146
[2ac095d]147        void enable_interrupts( DEBUG_CTX_PARAM ) {
[1c273d0]148                processor * proc   = this_processor;
149                thread_desc * thrd = this_thread;
[4e6fb8e]150                unsigned short prev = __atomic_fetch_add_2( &disable_preempt_count, -1, __ATOMIC_SEQ_CST );
[0b33412]151                verify( prev != (unsigned short) 0 );
[1c273d0]152                if( prev == 1 && proc->pending_preemption ) {
153                        proc->pending_preemption = false;
154                        BlockInternal( thrd );
[82ff5845]155                }
[4e6fb8e]156
[2ac095d]157                LIB_DEBUG_DO( proc->last_enable = caller; )
[82ff5845]158        }
159}
160
[1c273d0]161static inline void signal_unblock( int sig ) {
[82ff5845]162        sigset_t mask;
163        sigemptyset( &mask );
[1c273d0]164        sigaddset( &mask, sig );
[82ff5845]165
[47ecf2b]166        if ( pthread_sigmask( SIG_UNBLOCK, &mask, NULL ) == -1 ) {
167            abortf( "internal error, pthread_sigmask" );
[cd17862]168        }
[82ff5845]169}
170
[cd17862]171static inline void signal_block( int sig ) {
172        sigset_t mask;
173        sigemptyset( &mask );
174        sigaddset( &mask, sig );
[47ecf2b]175
[cd17862]176        if ( pthread_sigmask( SIG_BLOCK, &mask, NULL ) == -1 ) {
177            abortf( "internal error, pthread_sigmask" );
178        }
179}
[47ecf2b]180
[c81ebf9]181static inline bool preemption_ready() {
[4e6fb8e]182        return disable_preempt_count == 0;
[c81ebf9]183}
184
185static inline void defer_ctxSwitch() {
186        this_processor->pending_preemption = true;
187}
188
189static inline void defer_alarm() {
190        systemProcessor->pending_alarm = true;
191}
192
[cd17862]193static void preempt( processor * this ) {
194        pthread_kill( this->kernel_thread, SIGUSR1 );
[1c273d0]195}
[82ff5845]196
[cd17862]197static void timeout( thread_desc * this ) {
198        //TODO : implement waking threads
199}
200
201//=============================================================================================
202// Kernel Signal Startup/Shutdown logic
203//=============================================================================================
204
205static pthread_t alarm_thread;
206void * alarm_loop( __attribute__((unused)) void * args );
207
208void kernel_start_preemption() {
209        LIB_DEBUG_PRINT_SAFE("Kernel : Starting preemption\n");
210        __kernel_sigaction( SIGUSR1, sigHandler_ctxSwitch, SA_SIGINFO );
[f2b12406]211        // __kernel_sigaction( SIGSEGV, sigHandler_segv     , SA_SIGINFO );
212        // __kernel_sigaction( SIGBUS , sigHandler_segv     , SA_SIGINFO );
[cd17862]213
214        signal_block( SIGALRM );
215
216        pthread_create( &alarm_thread, NULL, alarm_loop, NULL );
217}
218
219void kernel_stop_preemption() {
220        sigset_t mask;
221        sigfillset( &mask );
222        sigprocmask( SIG_BLOCK, &mask, NULL );
223
[a0b3e32]224        sigval val = { 1 };
225        pthread_sigqueue( alarm_thread, SIGALRM, val );
[cd17862]226        pthread_join( alarm_thread, NULL );
227        LIB_DEBUG_PRINT_SAFE("Kernel : Preemption stopped\n");
228}
229
230void ?{}( preemption_scope * this, processor * proc ) {
231        (&this->alarm){ proc };
232        this->proc = proc;
233        this->proc->preemption_alarm = &this->alarm;
234        update_preemption( this->proc, this->proc->preemption );
235}
236
237void ^?{}( preemption_scope * this ) {
238        disable_interrupts();
239
240        update_preemption( this->proc, 0 );
241}
242
243//=============================================================================================
244// Kernel Signal Handlers
245//=============================================================================================
[47ecf2b]246
[1c273d0]247void sigHandler_ctxSwitch( __CFA_SIGPARMS__ ) {
[47ecf2b]248        LIB_DEBUG_DO( last_interrupt = (void *)(cxt->uc_mcontext.gregs[CFA_REG_IP]); )
[c81ebf9]249        if( preemption_ready() ) {
[1c273d0]250                signal_unblock( SIGUSR1 );
251                BlockInternal( (thread_desc*)this_thread );
[c81ebf9]252        }
253        else {
254                defer_ctxSwitch();
255        }
256}
257
[cd17862]258// void sigHandler_alarm( __CFA_SIGPARMS__ ) {
259//      LIB_DEBUG_DO( last_interrupt = (void *)(cxt->uc_mcontext.gregs[CFA_REG_IP]); )
260//      verify( this_processor == systemProcessor );
[82ff5845]261
[cd17862]262//      if( try_lock( &systemProcessor->alarm_lock DEBUG_CTX2 ) ) {
263//              tick_preemption();
264//              systemProcessor->pending_alarm = false;
265//              unlock( &systemProcessor->alarm_lock );
266//      }
267//      else {
268//              defer_alarm();
269//      }
[82ff5845]270
[cd17862]271//      signal_unblock( SIGALRM );
[1c273d0]272
[cd17862]273//      if( preemption_ready() && this_processor->pending_preemption ) {
[47ecf2b]274
[cd17862]275//              this_processor->pending_preemption = false;
276//              BlockInternal( (thread_desc*)this_thread );
277//      }
278// }
[c81ebf9]279
[cd17862]280void * alarm_loop( __attribute__((unused)) void * args ) {
281        sigset_t mask;
282        sigemptyset( &mask );
283        sigaddset( &mask, SIGALRM );
284
285        if ( pthread_sigmask( SIG_BLOCK, &mask, NULL ) == -1 ) {
286            abortf( "internal error, pthread_sigmask" );
[82ff5845]287        }
[c81ebf9]288
[cd17862]289        while( true ) {
[a0b3e32]290                siginfo_t info;
291                int sig = sigwaitinfo( &mask, &info );
292                if( sig < 0 ) {
[cd17862]293                        abortf( "internal error, sigwait" );
294                }
[a0b3e32]295                else if( sig == SIGALRM )
296                {
297                        LIB_DEBUG_PRINT_SAFE("Kernel : Caught signal %d (%d)\n", sig, info.si_value.sival_int );
298                        if( info.si_value.sival_int == 0 )
299                        {
[cd17862]300                                LIB_DEBUG_PRINT_SAFE("Kernel : Preemption thread tick\n");
301                                lock( &systemProcessor->alarm_lock DEBUG_CTX2 );
302                                tick_preemption();
303                                unlock( &systemProcessor->alarm_lock );
[a0b3e32]304                        }
305                        else if( info.si_value.sival_int == 1 )
306                        {
[cd17862]307                                break;
[a0b3e32]308                        }
309                }
310                else
311                {
312                        LIB_DEBUG_PRINT_SAFE("Kernel : Unexpected signal %d (%d)\n", sig, info.si_value.sival_int);
[cd17862]313                }
314        }
[a0b3e32]315
316        LIB_DEBUG_PRINT_SAFE("Kernel : Preemption thread stopping\n");
317        return NULL;
[82ff5845]318}
319
320static void __kernel_sigaction( int sig, void (*handler)(__CFA_SIGPARMS__), int flags ) {
321        struct sigaction act;
322
323        act.sa_sigaction = (void (*)(int, siginfo_t *, void *))handler;
[1c273d0]324        act.sa_flags = flags;
325
326        if ( sigaction( sig, &act, NULL ) == -1 ) {
327                LIB_DEBUG_PRINT_BUFFER_DECL( STDERR_FILENO,
328                        " __kernel_sigaction( sig:%d, handler:%p, flags:%d ), problem installing signal handler, error(%d) %s.\n",
329                        sig, handler, flags, errno, strerror( errno )
330                );
331                _exit( EXIT_FAILURE );
332        }
333}
334
335typedef void (*sa_handler_t)(int);
336
337static void __kernel_sigdefault( int sig ) {
338        struct sigaction act;
339
340        // act.sa_handler = SIG_DFL;
341        act.sa_flags = 0;
342        sigemptyset( &act.sa_mask );
[82ff5845]343
344        if ( sigaction( sig, &act, NULL ) == -1 ) {
[1c273d0]345                LIB_DEBUG_PRINT_BUFFER_DECL( STDERR_FILENO,
346                        " __kernel_sigdefault( sig:%d ), problem reseting signal handler, error(%d) %s.\n",
347                        sig, errno, strerror( errno )
348                );
[82ff5845]349                _exit( EXIT_FAILURE );
[1c273d0]350        }
351}
352
353//=============================================================================================
354// Terminating Signals logic
355//=============================================================================================
356
357LIB_DEBUG_DO(
358        static void __kernel_backtrace( int start ) {
359                // skip first N stack frames
360
361                enum { Frames = 50 };
362                void * array[Frames];
363                int size = backtrace( array, Frames );
364                char ** messages = backtrace_symbols( array, size );
365
366                // find executable name
367                *index( messages[0], '(' ) = '\0';
368                #ifdef __USE_STREAM__
369                serr | "Stack back trace for:" | messages[0] | endl;
370                #else
371                fprintf( stderr, "Stack back trace for: %s\n", messages[0]);
372                #endif
373
374                // skip last 2 stack frames after main
375                for ( int i = start; i < size && messages != NULL; i += 1 ) {
376                        char * name = NULL;
377                        char * offset_begin = NULL;
378                        char * offset_end = NULL;
379
380                        for ( char *p = messages[i]; *p; ++p ) {
381                                // find parantheses and +offset
382                                if ( *p == '(' ) {
383                                        name = p;
384                                }
385                                else if ( *p == '+' ) {
386                                        offset_begin = p;
387                                }
388                                else if ( *p == ')' ) {
389                                        offset_end = p;
390                                        break;
391                                }
392                        }
393
394                        // if line contains symbol print it
395                        int frameNo = i - start;
396                        if ( name && offset_begin && offset_end && name < offset_begin ) {
397                                // delimit strings
398                                *name++ = '\0';
399                                *offset_begin++ = '\0';
400                                *offset_end++ = '\0';
401
402                                #ifdef __USE_STREAM__
403                                serr    | "("  | frameNo | ")" | messages[i] | ":"
404                                        | name | "+" | offset_begin | offset_end | endl;
405                                #else
406                                fprintf( stderr, "(%i) %s : %s + %s %s\n", frameNo, messages[i], name, offset_begin, offset_end);
407                                #endif
408                        }
409                        // otherwise, print the whole line
410                        else {
411                                #ifdef __USE_STREAM__
412                                serr | "(" | frameNo | ")" | messages[i] | endl;
413                                #else
414                                fprintf( stderr, "(%i) %s\n", frameNo, messages[i] );
415                                #endif
416                        }
417                }
418
419                free( messages );
420        }
421)
422
[f2b12406]423// void sigHandler_segv( __CFA_SIGPARMS__ ) {
424//      LIB_DEBUG_DO(
425//              #ifdef __USE_STREAM__
426//              serr    | "*CFA runtime error* program cfa-cpp terminated with"
427//                      | (sig == SIGSEGV ? "segment fault." : "bus error.")
428//                      | endl;
429//              #else
430//              fprintf( stderr, "*CFA runtime error* program cfa-cpp terminated with %s\n", sig == SIGSEGV ? "segment fault." : "bus error." );
431//              #endif
432
433//              // skip first 2 stack frames
434//              __kernel_backtrace( 1 );
435//      )
436//      exit( EXIT_FAILURE );
437// }
[1c273d0]438
439// void sigHandler_abort( __CFA_SIGPARMS__ ) {
440//      // skip first 6 stack frames
441//      LIB_DEBUG_DO( __kernel_backtrace( 6 ); )
442
443//      // reset default signal handler
444//      __kernel_sigdefault( SIGABRT );
445
446//      raise( SIGABRT );
447// }
Note: See TracBrowser for help on using the repository browser.