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

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

Preemption now properly(?) use si_code in addition to si_value

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