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

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

Some more work on TLS macros

  • Property mode set to 100644
File size: 13.9 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 : Mon Apr  9 13:52:39 2018
13// Update Count     : 36
14//
15
16#include "preemption.h"
17
18extern "C" {
19#include <errno.h>
20#include <stdio.h>
21#include <string.h>
22#include <unistd.h>
23}
24
25#include "bits/signal.h"
26
27#if !defined(__CFA_DEFAULT_PREEMPTION__)
28#define __CFA_DEFAULT_PREEMPTION__ 10`ms
29#endif
30
31Duration default_preemption() __attribute__((weak)) {
32        return __CFA_DEFAULT_PREEMPTION__;
33}
34
35// FwdDeclarations : timeout handlers
36static void preempt( processor   * this );
37static void timeout( thread_desc * this );
38
39// FwdDeclarations : Signal handlers
40void sigHandler_ctxSwitch( __CFA_SIGPARMS__ );
41void sigHandler_segv     ( __CFA_SIGPARMS__ );
42void sigHandler_ill      ( __CFA_SIGPARMS__ );
43void sigHandler_fpe      ( __CFA_SIGPARMS__ );
44void sigHandler_abort    ( __CFA_SIGPARMS__ );
45
46// FwdDeclarations : alarm thread main
47void * alarm_loop( __attribute__((unused)) void * args );
48
49// Machine specific register name
50#if   defined( __i386 )
51#define CFA_REG_IP gregs[REG_EIP]
52#elif defined( __x86_64 )
53#define CFA_REG_IP gregs[REG_RIP]
54#elif defined( __ARM_ARCH )
55#define CFA_REG_IP arm_pc
56#else
57#error unknown hardware architecture
58#endif
59
60KERNEL_STORAGE(event_kernel_t, event_kernel);         // private storage for event kernel
61event_kernel_t * event_kernel;                        // kernel public handle to even kernel
62static pthread_t alarm_thread;                        // pthread handle to alarm thread
63
64void ?{}(event_kernel_t & this) with( this ) {
65        alarms{};
66        lock{};
67}
68
69enum {
70        PREEMPT_NORMAL    = 0,
71        PREEMPT_TERMINATE = 1,
72};
73
74//=============================================================================================
75// Kernel Preemption logic
76//=============================================================================================
77
78// Get next expired node
79static inline alarm_node_t * get_expired( alarm_list_t * alarms, Time currtime ) {
80        if( !alarms->head ) return NULL;                          // If no alarms return null
81        if( alarms->head->alarm >= currtime ) return NULL;        // If alarms head not expired return null
82        return pop(alarms);                                       // Otherwise just pop head
83}
84
85// Tick one frame of the Discrete Event Simulation for alarms
86void tick_preemption() {
87        alarm_node_t * node = NULL;                     // Used in the while loop but cannot be declared in the while condition
88        alarm_list_t * alarms = &event_kernel->alarms;  // Local copy for ease of reading
89        Time currtime = __kernel_get_time();                    // Check current time once so we everything "happens at once"
90
91        //Loop throught every thing expired
92        while( node = get_expired( alarms, currtime ) ) {
93
94                // Check if this is a kernel
95                if( node->kernel_alarm ) {
96                        preempt( node->proc );
97                }
98                else {
99                        timeout( node->thrd );
100                }
101
102                // Check if this is a periodic alarm
103                Duration period = node->period;
104                if( period > 0 ) {
105                        node->alarm = currtime + period;    // Alarm is periodic, add currtime to it (used cached current time)
106                        insert( alarms, node );             // Reinsert the node for the next time it triggers
107                }
108                else {
109                        node->set = false;                  // Node is one-shot, just mark it as not pending
110                }
111        }
112
113        // If there are still alarms pending, reset the timer
114        if( alarms->head ) { __kernel_set_timer( alarms->head->alarm - currtime ); }
115}
116
117// Update the preemption of a processor and notify interested parties
118void update_preemption( processor * this, Duration duration ) {
119        alarm_node_t * alarm = this->preemption_alarm;
120
121        // Alarms need to be enabled
122        if ( duration > 0 && ! alarm->set ) {
123                alarm->alarm = __kernel_get_time() + duration;
124                alarm->period = duration;
125                register_self( alarm );
126        }
127        // Zero duration but alarm is set
128        else if ( duration == 0 && alarm->set ) {
129                unregister_self( alarm );
130                alarm->alarm = 0;
131                alarm->period = 0;
132        }
133        // If alarm is different from previous, change it
134        else if ( duration > 0 && alarm->period != duration ) {
135                unregister_self( alarm );
136                alarm->alarm = __kernel_get_time() + duration;
137                alarm->period = duration;
138                register_self( alarm );
139        }
140}
141
142//=============================================================================================
143// Kernel Signal Tools
144//=============================================================================================
145
146__cfaabi_dbg_debug_do( static thread_local void * last_interrupt = 0; )
147
148extern "C" {
149        // Disable interrupts by incrementing the counter
150        void disable_interrupts() {
151                with( kernelTLS.preemption_state ) {
152                        enabled = false;
153                        __attribute__((unused)) unsigned short new_val = disable_count + 1;
154                        disable_count = new_val;
155                        verify( new_val < 65_000u );              // If this triggers someone is disabling interrupts without enabling them
156                }
157        }
158
159        // Enable interrupts by decrementing the counter
160        // If counter reaches 0, execute any pending CtxSwitch
161        void enable_interrupts( __cfaabi_dbg_ctx_param ) {
162                processor   * proc = kernelTLS.this_processor; // Cache the processor now since interrupts can start happening after the atomic add
163                thread_desc * thrd = kernelTLS.this_thread;       // Cache the thread now since interrupts can start happening after the atomic add
164
165                with( kernelTLS.preemption_state ){
166                        unsigned short prev = disable_count;
167                        disable_count -= 1;
168                        verify( prev != 0u );                     // If this triggers someone is enabled already enabled interruptsverify( prev != 0u );
169
170                        // Check if we need to prempt the thread because an interrupt was missed
171                        if( prev == 1 ) {
172                                enabled = true;
173                                if( proc->pending_preemption ) {
174                                        proc->pending_preemption = false;
175                                        BlockInternal( thrd );
176                                }
177                        }
178                }
179
180                // For debugging purposes : keep track of the last person to enable the interrupts
181                __cfaabi_dbg_debug_do( proc->last_enable = caller; )
182        }
183
184        // Disable interrupts by incrementint the counter
185        // Don't execute any pending CtxSwitch even if counter reaches 0
186        void enable_interrupts_noPoll() {
187                unsigned short prev = kernelTLS.preemption_state.disable_count;
188                kernelTLS.preemption_state.disable_count -= 1;
189                verifyf( prev != 0u, "Incremented from %u\n", prev );                     // If this triggers someone is enabled already enabled interrupts
190                if( prev == 1 ) {
191                        kernelTLS.preemption_state.enabled = true;
192                }
193        }
194}
195
196// sigprocmask wrapper : unblock a single signal
197static inline void signal_unblock( int sig ) {
198        sigset_t mask;
199        sigemptyset( &mask );
200        sigaddset( &mask, sig );
201
202        if ( pthread_sigmask( SIG_UNBLOCK, &mask, NULL ) == -1 ) {
203            abort( "internal error, pthread_sigmask" );
204        }
205}
206
207// sigprocmask wrapper : block a single signal
208static inline void signal_block( int sig ) {
209        sigset_t mask;
210        sigemptyset( &mask );
211        sigaddset( &mask, sig );
212
213        if ( pthread_sigmask( SIG_BLOCK, &mask, NULL ) == -1 ) {
214            abort( "internal error, pthread_sigmask" );
215        }
216}
217
218// kill wrapper : signal a processor
219static void preempt( processor * this ) {
220        sigval_t value = { PREEMPT_NORMAL };
221        pthread_sigqueue( this->kernel_thread, SIGUSR1, value );
222}
223
224// kill wrapper : signal a processor
225void terminate(processor * this) {
226        this->do_terminate = true;
227        sigval_t value = { PREEMPT_TERMINATE };
228        pthread_sigqueue( this->kernel_thread, SIGUSR1, value );
229}
230
231// reserved for future use
232static void timeout( thread_desc * this ) {
233        //TODO : implement waking threads
234}
235
236// KERNEL ONLY
237// Check if a CtxSwitch signal handler shoud defer
238// If true  : preemption is safe
239// If false : preemption is unsafe and marked as pending
240static inline bool preemption_ready() {
241        // Check if preemption is safe
242        bool ready = kernelTLS.preemption_state.enabled && ! kernelTLS.preemption_state.in_progress;
243
244        // Adjust the pending flag accordingly
245        kernelTLS.this_processor->pending_preemption = !ready;
246        return ready;
247}
248
249//=============================================================================================
250// Kernel Signal Startup/Shutdown logic
251//=============================================================================================
252
253// Startup routine to activate preemption
254// Called from kernel_startup
255void kernel_start_preemption() {
256        __cfaabi_dbg_print_safe( "Kernel : Starting preemption\n" );
257
258        // Start with preemption disabled until ready
259        kernelTLS.preemption_state.enabled = false;
260        kernelTLS.preemption_state.disable_count = 1;
261
262        // Initialize the event kernel
263        event_kernel = (event_kernel_t *)&storage_event_kernel;
264        (*event_kernel){};
265
266        // Setup proper signal handlers
267        __cfaabi_sigaction( SIGUSR1, sigHandler_ctxSwitch, SA_SIGINFO | SA_RESTART );         // CtxSwitch handler
268
269        signal_block( SIGALRM );
270
271        pthread_create( &alarm_thread, NULL, alarm_loop, NULL );
272}
273
274// Shutdown routine to deactivate preemption
275// Called from kernel_shutdown
276void kernel_stop_preemption() {
277        __cfaabi_dbg_print_safe( "Kernel : Preemption stopping\n" );
278
279        // Block all signals since we are already shutting down
280        sigset_t mask;
281        sigfillset( &mask );
282        sigprocmask( SIG_BLOCK, &mask, NULL );
283
284        // Notify the alarm thread of the shutdown
285        sigval val = { 1 };
286        pthread_sigqueue( alarm_thread, SIGALRM, val );
287
288        // Wait for the preemption thread to finish
289        pthread_join( alarm_thread, NULL );
290
291        // Preemption is now fully stopped
292
293        __cfaabi_dbg_print_safe( "Kernel : Preemption stopped\n" );
294}
295
296// Raii ctor/dtor for the preemption_scope
297// Used by thread to control when they want to receive preemption signals
298void ?{}( preemption_scope & this, processor * proc ) {
299        (this.alarm){ proc, (Time){ 0 }, 0`s };
300        this.proc = proc;
301        this.proc->preemption_alarm = &this.alarm;
302
303        update_preemption( this.proc, this.proc->cltr->preemption_rate );
304}
305
306void ^?{}( preemption_scope & this ) {
307        disable_interrupts();
308
309        update_preemption( this.proc, 0`s );
310}
311
312//=============================================================================================
313// Kernel Signal Handlers
314//=============================================================================================
315
316// Context switch signal handler
317// Receives SIGUSR1 signal and causes the current thread to yield
318void sigHandler_ctxSwitch( __CFA_SIGPARMS__ ) {
319        __cfaabi_dbg_debug_do( last_interrupt = (void *)(cxt->uc_mcontext.CFA_REG_IP); )
320
321        // SKULLDUGGERY: if a thread creates a processor and the immediately deletes it,
322        // the interrupt that is supposed to force the kernel thread to preempt might arrive
323        // before the kernel thread has even started running. When that happens an iterrupt
324        // we a null 'this_processor' will be caught, just ignore it.
325        if(! kernelTLS.this_processor ) return;
326
327        choose(sfp->si_value.sival_int) {
328                case PREEMPT_NORMAL   : ;// Normal case, nothing to do here
329                case PREEMPT_TERMINATE: verify( kernelTLS.this_processor->do_terminate);
330                default:
331                        abort( "internal error, signal value is %d", sfp->si_value.sival_int );
332        }
333
334        // Check if it is safe to preempt here
335        if( !preemption_ready() ) { return; }
336
337        __cfaabi_dbg_print_buffer_decl( " KERNEL: preempting core %p (%p).\n", kernelTLS.this_processor, kernelTLS.this_thread );
338
339        // Sync flag : prevent recursive calls to the signal handler
340        kernelTLS.preemption_state.in_progress = true;
341
342        // We are about to CtxSwitch out of the signal handler, let other handlers in
343        signal_unblock( SIGUSR1 );
344
345        // TODO: this should go in finish action
346        // Clear the in progress flag
347        kernelTLS.preemption_state.in_progress = false;
348
349        // Preemption can occur here
350
351        BlockInternal( kernelTLS.this_thread ); // Do the actual CtxSwitch
352}
353
354// Main of the alarm thread
355// Waits on SIGALRM and send SIGUSR1 to whom ever needs it
356void * alarm_loop( __attribute__((unused)) void * args ) {
357        // Block sigalrms to control when they arrive
358        sigset_t mask;
359        sigemptyset( &mask );
360        sigaddset( &mask, SIGALRM );
361
362        if ( pthread_sigmask( SIG_BLOCK, &mask, NULL ) == -1 ) {
363            abort( "internal error, pthread_sigmask" );
364        }
365
366        // Main loop
367        while( true ) {
368                // Wait for a sigalrm
369                siginfo_t info;
370                int sig = sigwaitinfo( &mask, &info );
371
372                if( sig < 0 ) {
373                        //Error!
374                        int err = errno;
375                        switch( err ) {
376                                case EAGAIN :
377                                case EINTR :
378                                        continue;
379                        case EINVAL :
380                                        abort( "Timeout was invalid." );
381                                default:
382                                        abort( "Unhandled error %d", err);
383                        }
384                }
385
386                // If another signal arrived something went wrong
387                assertf(sig == SIGALRM, "Kernel Internal Error, sigwait: Unexpected signal %d (%d : %d)\n", sig, info.si_code, info.si_value.sival_int);
388
389                // __cfaabi_dbg_print_safe( "Kernel : Caught alarm from %d with %d\n", info.si_code, info.si_value.sival_int );
390                // Switch on the code (a.k.a. the sender) to
391                switch( info.si_code )
392                {
393                // Timers can apparently be marked as sent for the kernel
394                // In either case, tick preemption
395                case SI_TIMER:
396                case SI_KERNEL:
397                        // __cfaabi_dbg_print_safe( "Kernel : Preemption thread tick\n" );
398                        lock( event_kernel->lock __cfaabi_dbg_ctx2 );
399                        tick_preemption();
400                        unlock( event_kernel->lock );
401                        break;
402                // Signal was not sent by the kernel but by an other thread
403                case SI_QUEUE:
404                        // For now, other thread only signal the alarm thread to shut it down
405                        // If this needs to change use info.si_value and handle the case here
406                        goto EXIT;
407                }
408        }
409
410EXIT:
411        __cfaabi_dbg_print_safe( "Kernel : Preemption thread stopping\n" );
412        return NULL;
413}
414
415//=============================================================================================
416// Kernel Signal Debug
417//=============================================================================================
418
419void __cfaabi_check_preemption() {
420        bool ready = kernelTLS.preemption_state.enabled;
421        if(!ready) { abort("Preemption should be ready"); }
422
423        sigset_t oldset;
424        int ret;
425        ret = sigprocmask(0, NULL, &oldset);
426        if(ret != 0) { abort("ERROR sigprocmask returned %d", ret); }
427
428        ret = sigismember(&oldset, SIGUSR1);
429        if(ret <  0) { abort("ERROR sigismember returned %d", ret); }
430
431        if(ret == 1) { abort("ERROR SIGUSR1 is disabled"); }
432}
433
434// Local Variables: //
435// mode: c //
436// tab-width: 4 //
437// End: //
Note: See TracBrowser for help on using the repository browser.