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

aaron-thesisarm-ehcleanup-dtorsdeferred_resndemanglerjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerwith_gc
Last change on this file since b1a4300 was b1a4300, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Added assert for set_timer for duration < 1us && != 0.
Preemption now always calls timer with at least 50us durations.
Fixed verifies in nodebug.

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