source: src/libcfa/concurrency/preemption.c @ 47ecf2b

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

Some cleanup before refactoring alarms

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