source: libcfa/src/concurrency/kernel.cfa @ d60d30e

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since d60d30e was da3963a, checked in by Thierry Delisle <tdelisle@…>, 3 years ago

Moved bin_sem_t out of kernel.hfa since it's not needed.

  • Property mode set to 100644
File size: 23.1 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// kernel.c --
8//
9// Author           : Thierry Delisle
10// Created On       : Tue Jan 17 12:27:26 2017
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Mon Aug 31 07:08:20 2020
13// Update Count     : 71
14//
15
16#define __cforall_thread__
17// #define __CFA_DEBUG_PRINT_RUNTIME_CORE__
18
19//C Includes
20#include <errno.h>
21#include <stdio.h>
22#include <signal.h>
23#include <unistd.h>
24
25//CFA Includes
26#include "kernel_private.hfa"
27#include "preemption.hfa"
28
29//Private includes
30#define __CFA_INVOKE_PRIVATE__
31#include "invoke.h"
32
33
34//-----------------------------------------------------------------------------
35// Some assembly required
36#if defined( __i386 )
37        // mxcr : SSE Status and Control bits (control bits are preserved across function calls)
38        // fcw  : X87 FPU control word (preserved across function calls)
39        #define __x87_store         \
40                uint32_t __mxcr;      \
41                uint16_t __fcw;       \
42                __asm__ volatile (    \
43                        "stmxcsr %0\n"  \
44                        "fnstcw  %1\n"  \
45                        : "=m" (__mxcr),\
46                                "=m" (__fcw)  \
47                )
48
49        #define __x87_load         \
50                __asm__ volatile (   \
51                        "fldcw  %1\n"  \
52                        "ldmxcsr %0\n" \
53                        ::"m" (__mxcr),\
54                                "m" (__fcw)  \
55                )
56
57#elif defined( __x86_64 )
58        #define __x87_store         \
59                uint32_t __mxcr;      \
60                uint16_t __fcw;       \
61                __asm__ volatile (    \
62                        "stmxcsr %0\n"  \
63                        "fnstcw  %1\n"  \
64                        : "=m" (__mxcr),\
65                                "=m" (__fcw)  \
66                )
67
68        #define __x87_load          \
69                __asm__ volatile (    \
70                        "fldcw  %1\n"   \
71                        "ldmxcsr %0\n"  \
72                        :: "m" (__mxcr),\
73                                "m" (__fcw)  \
74                )
75
76#elif defined( __arm__ )
77        #define __x87_store
78        #define __x87_load
79
80#elif defined( __aarch64__ )
81        #define __x87_store              \
82                uint32_t __fpcntl[2];    \
83                __asm__ volatile (    \
84                        "mrs x9, FPCR\n" \
85                        "mrs x10, FPSR\n"  \
86                        "stp x9, x10, %0\n"  \
87                        : "=m" (__fpcntl) : : "x9", "x10" \
88                )
89
90        #define __x87_load         \
91                __asm__ volatile (    \
92                        "ldp x9, x10, %0\n"  \
93                        "msr FPSR, x10\n"  \
94                        "msr FPCR, x9\n" \
95                : "=m" (__fpcntl) : : "x9", "x10" \
96                )
97
98#else
99        #error unsupported hardware architecture
100#endif
101
102extern $thread * mainThread;
103extern processor * mainProcessor;
104
105//-----------------------------------------------------------------------------
106// Kernel Scheduling logic
107static $thread * __next_thread(cluster * this);
108static $thread * __next_thread_slow(cluster * this);
109static void __run_thread(processor * this, $thread * dst);
110static void __wake_one(cluster * cltr);
111static void wait(__bin_sem_t & this);
112
113static void push  (__cluster_idles & idles, processor & proc);
114static void remove(__cluster_idles & idles, processor & proc);
115static [unsigned idle, unsigned total, * processor] query( & __cluster_idles idles );
116
117
118//=============================================================================================
119// Kernel Scheduling logic
120//=============================================================================================
121//Main of the processor contexts
122void main(processorCtx_t & runner) {
123        // Because of a bug, we couldn't initialized the seed on construction
124        // Do it here
125        __cfaabi_tls.rand_seed ^= rdtscl();
126        __cfaabi_tls.ready_rng.fwd_seed = 25214903917_l64u * (rdtscl() ^ (uintptr_t)&runner);
127        __tls_rand_advance_bck();
128
129        processor * this = runner.proc;
130        verify(this);
131
132        __cfadbg_print_safe(runtime_core, "Kernel : core %p starting\n", this);
133        #if !defined(__CFA_NO_STATISTICS__)
134                if( this->print_halts ) {
135                        __cfaabi_bits_print_safe( STDOUT_FILENO, "Processor : %d - %s (%p)\n", this->id, this->name, (void*)this);
136                }
137        #endif
138
139        {
140                // Setup preemption data
141                preemption_scope scope = { this };
142
143                #if !defined(__CFA_NO_STATISTICS__)
144                        unsigned long long last_tally = rdtscl();
145                #endif
146
147
148                __cfadbg_print_safe(runtime_core, "Kernel : core %p started\n", this);
149
150                $thread * readyThread = 0p;
151                MAIN_LOOP:
152                for() {
153                        // Try to get the next thread
154                        readyThread = __next_thread( this->cltr );
155
156                        if( !readyThread ) {
157                                readyThread = __next_thread_slow( this->cltr );
158                        }
159
160                        HALT:
161                        if( !readyThread ) {
162                                // Don't block if we are done
163                                if( __atomic_load_n(&this->do_terminate, __ATOMIC_SEQ_CST) ) break MAIN_LOOP;
164
165                                #if !defined(__CFA_NO_STATISTICS__)
166                                        __tls_stats()->ready.sleep.halts++;
167                                #endif
168
169                                // Push self to idle stack
170                                push(this->cltr->idles, * this);
171
172                                // Confirm the ready-queue is empty
173                                readyThread = __next_thread_slow( this->cltr );
174                                if( readyThread ) {
175                                        // A thread was found, cancel the halt
176                                        remove(this->cltr->idles, * this);
177
178                                        #if !defined(__CFA_NO_STATISTICS__)
179                                                __tls_stats()->ready.sleep.cancels++;
180                                        #endif
181
182                                        // continue the mai loop
183                                        break HALT;
184                                }
185
186                                #if !defined(__CFA_NO_STATISTICS__)
187                                        if(this->print_halts) {
188                                                __cfaabi_bits_print_safe( STDOUT_FILENO, "PH:%d - %lld 0\n", this->id, rdtscl());
189                                        }
190                                #endif
191
192                                wait( this->idle );
193
194                                #if !defined(__CFA_NO_STATISTICS__)
195                                        if(this->print_halts) {
196                                                __cfaabi_bits_print_safe( STDOUT_FILENO, "PH:%d - %lld 1\n", this->id, rdtscl());
197                                        }
198                                #endif
199
200                                // We were woken up, remove self from idle
201                                remove(this->cltr->idles, * this);
202
203                                // DON'T just proceed, start looking again
204                                continue MAIN_LOOP;
205                        }
206
207                        /* paranoid */ verify( readyThread );
208
209                        // We found a thread run it
210                        __run_thread(this, readyThread);
211
212                        // Are we done?
213                        if( __atomic_load_n(&this->do_terminate, __ATOMIC_SEQ_CST) ) break MAIN_LOOP;
214
215                        #if !defined(__CFA_NO_STATISTICS__)
216                                unsigned long long curr = rdtscl();
217                                if(curr > (last_tally + 500000000)) {
218                                        __tally_stats(this->cltr->stats, __cfaabi_tls.this_stats);
219                                        last_tally = curr;
220                                }
221                        #endif
222                }
223
224                __cfadbg_print_safe(runtime_core, "Kernel : core %p stopping\n", this);
225        }
226
227        post( this->terminated );
228
229        if(this == mainProcessor) {
230                // HACK : the coroutine context switch expects this_thread to be set
231                // and it make sense for it to be set in all other cases except here
232                // fake it
233                __cfaabi_tls.this_thread = mainThread;
234        }
235
236        __cfadbg_print_safe(runtime_core, "Kernel : core %p terminated\n", this);
237}
238
239static int * __volatile_errno() __attribute__((noinline));
240static int * __volatile_errno() { asm(""); return &errno; }
241
242// KERNEL ONLY
243// runThread runs a thread by context switching
244// from the processor coroutine to the target thread
245static void __run_thread(processor * this, $thread * thrd_dst) {
246        /* paranoid */ verify( ! __preemption_enabled() );
247        /* paranoid */ verifyf( thrd_dst->state == Ready || thrd_dst->preempted != __NO_PREEMPTION, "state : %d, preempted %d\n", thrd_dst->state, thrd_dst->preempted);
248        /* paranoid */ verifyf( thrd_dst->link.next == 0p, "Expected null got %p", thrd_dst->link.next );
249        __builtin_prefetch( thrd_dst->context.SP );
250
251        $coroutine * proc_cor = get_coroutine(this->runner);
252
253        // set state of processor coroutine to inactive
254        verify(proc_cor->state == Active);
255        proc_cor->state = Blocked;
256
257        // Actually run the thread
258        RUNNING:  while(true) {
259                thrd_dst->preempted = __NO_PREEMPTION;
260                thrd_dst->state = Active;
261
262                // Update global state
263                kernelTLS().this_thread = thrd_dst;
264
265                /* paranoid */ verify( ! __preemption_enabled() );
266                /* paranoid */ verify( kernelTLS().this_thread == thrd_dst );
267                /* paranoid */ verify( thrd_dst->curr_cluster == this->cltr );
268                /* paranoid */ verify( thrd_dst->context.SP );
269                /* paranoid */ verify( thrd_dst->state != Halted );
270                /* paranoid */ verifyf( ((uintptr_t)thrd_dst->context.SP) < ((uintptr_t)__get_stack(thrd_dst->curr_cor)->base ) || thrd_dst->curr_cor == proc_cor, "ERROR : Destination $thread %p has been corrupted.\n StackPointer too small.\n", thrd_dst ); // add escape condition if we are setting up the processor
271                /* paranoid */ verifyf( ((uintptr_t)thrd_dst->context.SP) > ((uintptr_t)__get_stack(thrd_dst->curr_cor)->limit) || thrd_dst->curr_cor == proc_cor, "ERROR : Destination $thread %p has been corrupted.\n StackPointer too large.\n", thrd_dst ); // add escape condition if we are setting up the processor
272                /* paranoid */ verify( 0x0D15EA5E0D15EA5Ep == thrd_dst->canary );
273
274
275
276                // set context switch to the thread that the processor is executing
277                __cfactx_switch( &proc_cor->context, &thrd_dst->context );
278                // when __cfactx_switch returns we are back in the processor coroutine
279
280                /* paranoid */ verify( 0x0D15EA5E0D15EA5Ep == thrd_dst->canary );
281                /* paranoid */ verifyf( ((uintptr_t)thrd_dst->context.SP) > ((uintptr_t)__get_stack(thrd_dst->curr_cor)->limit), "ERROR : Destination $thread %p has been corrupted.\n StackPointer too large.\n", thrd_dst );
282                /* paranoid */ verifyf( ((uintptr_t)thrd_dst->context.SP) < ((uintptr_t)__get_stack(thrd_dst->curr_cor)->base ), "ERROR : Destination $thread %p has been corrupted.\n StackPointer too small.\n", thrd_dst );
283                /* paranoid */ verify( thrd_dst->context.SP );
284                /* paranoid */ verify( thrd_dst->curr_cluster == this->cltr );
285                /* paranoid */ verify( kernelTLS().this_thread == thrd_dst );
286                /* paranoid */ verify( ! __preemption_enabled() );
287
288                // Reset global state
289                kernelTLS().this_thread = 0p;
290
291                // We just finished running a thread, there are a few things that could have happened.
292                // 1 - Regular case : the thread has blocked and now one has scheduled it yet.
293                // 2 - Racy case    : the thread has blocked but someone has already tried to schedule it.
294                // 4 - Preempted
295                // In case 1, we may have won a race so we can't write to the state again.
296                // In case 2, we lost the race so we now own the thread.
297
298                if(unlikely(thrd_dst->preempted != __NO_PREEMPTION)) {
299                        // The thread was preempted, reschedule it and reset the flag
300                        __schedule_thread( thrd_dst );
301                        break RUNNING;
302                }
303
304                if(unlikely(thrd_dst->state == Halting)) {
305                        // The thread has halted, it should never be scheduled/run again
306                        // finish the thread
307                        __thread_finish( thrd_dst );
308                        break RUNNING;
309                }
310
311                /* paranoid */ verify( thrd_dst->state == Active );
312                thrd_dst->state = Blocked;
313
314                // set state of processor coroutine to active and the thread to inactive
315                int old_ticket = __atomic_fetch_sub(&thrd_dst->ticket, 1, __ATOMIC_SEQ_CST);
316                switch(old_ticket) {
317                        case TICKET_RUNNING:
318                                // This is case 1, the regular case, nothing more is needed
319                                break RUNNING;
320                        case TICKET_UNBLOCK:
321                                // This is case 2, the racy case, someone tried to run this thread before it finished blocking
322                                // In this case, just run it again.
323                                continue RUNNING;
324                        default:
325                                // This makes no sense, something is wrong abort
326                                abort();
327                }
328        }
329
330        // Just before returning to the processor, set the processor coroutine to active
331        proc_cor->state = Active;
332
333        /* paranoid */ verify( ! __preemption_enabled() );
334}
335
336// KERNEL_ONLY
337void returnToKernel() {
338        /* paranoid */ verify( ! __preemption_enabled() );
339        $coroutine * proc_cor = get_coroutine(kernelTLS().this_processor->runner);
340        $thread * thrd_src = kernelTLS().this_thread;
341
342        #if !defined(__CFA_NO_STATISTICS__)
343                struct processor * last_proc = kernelTLS().this_processor;
344        #endif
345
346        // Run the thread on this processor
347        {
348                int local_errno = *__volatile_errno();
349                #if defined( __i386 ) || defined( __x86_64 )
350                        __x87_store;
351                #endif
352                /* paranoid */ verify( proc_cor->context.SP );
353                /* paranoid */ verify( 0x0D15EA5E0D15EA5Ep == thrd_src->canary );
354                __cfactx_switch( &thrd_src->context, &proc_cor->context );
355                /* paranoid */ verify( 0x0D15EA5E0D15EA5Ep == thrd_src->canary );
356                #if defined( __i386 ) || defined( __x86_64 )
357                        __x87_load;
358                #endif
359                *__volatile_errno() = local_errno;
360        }
361
362        #if !defined(__CFA_NO_STATISTICS__)
363                if(last_proc != kernelTLS().this_processor) {
364                        __tls_stats()->ready.threads.migration++;
365                }
366        #endif
367
368        /* paranoid */ verify( ! __preemption_enabled() );
369        /* paranoid */ verifyf( ((uintptr_t)thrd_src->context.SP) < ((uintptr_t)__get_stack(thrd_src->curr_cor)->base ), "ERROR : Returning $thread %p has been corrupted.\n StackPointer too small.\n", thrd_src );
370        /* paranoid */ verifyf( ((uintptr_t)thrd_src->context.SP) > ((uintptr_t)__get_stack(thrd_src->curr_cor)->limit), "ERROR : Returning $thread %p has been corrupted.\n StackPointer too large.\n", thrd_src );
371}
372
373//-----------------------------------------------------------------------------
374// Scheduler routines
375// KERNEL ONLY
376void __schedule_thread( $thread * thrd ) {
377        /* paranoid */ verify( ! __preemption_enabled() );
378        /* paranoid */ verify( kernelTLS().this_proc_id );
379        /* paranoid */ verify( thrd );
380        /* paranoid */ verify( thrd->state != Halted );
381        /* paranoid */ verify( thrd->curr_cluster );
382        /* paranoid */ #if defined( __CFA_WITH_VERIFY__ )
383        /* paranoid */  if( thrd->state == Blocked || thrd->state == Start ) assertf( thrd->preempted == __NO_PREEMPTION,
384                                        "Error inactive thread marked as preempted, state %d, preemption %d\n", thrd->state, thrd->preempted );
385        /* paranoid */  if( thrd->preempted != __NO_PREEMPTION ) assertf(thrd->state == Active,
386                                        "Error preempted thread marked as not currently running, state %d, preemption %d\n", thrd->state, thrd->preempted );
387        /* paranoid */ #endif
388        /* paranoid */ verifyf( thrd->link.next == 0p, "Expected null got %p", thrd->link.next );
389        /* paranoid */ verify( 0x0D15EA5E0D15EA5Ep == thrd->canary );
390
391
392        if (thrd->preempted == __NO_PREEMPTION) thrd->state = Ready;
393
394        ready_schedule_lock();
395                // Dereference the thread now because once we push it, there is not guaranteed it's still valid.
396                struct cluster * cl = thrd->curr_cluster;
397
398                // push the thread to the cluster ready-queue
399                push( cl, thrd );
400
401                // variable thrd is no longer safe to use
402
403                // wake the cluster using the save variable.
404                __wake_one( cl );
405        ready_schedule_unlock();
406
407        /* paranoid */ verify( ! __preemption_enabled() );
408}
409
410// KERNEL ONLY
411static inline $thread * __next_thread(cluster * this) with( *this ) {
412        /* paranoid */ verify( ! __preemption_enabled() );
413        /* paranoid */ verify( kernelTLS().this_proc_id );
414
415        ready_schedule_lock();
416                $thread * thrd = pop( this );
417        ready_schedule_unlock();
418
419        /* paranoid */ verify( kernelTLS().this_proc_id );
420        /* paranoid */ verify( ! __preemption_enabled() );
421        return thrd;
422}
423
424// KERNEL ONLY
425static inline $thread * __next_thread_slow(cluster * this) with( *this ) {
426        /* paranoid */ verify( ! __preemption_enabled() );
427        /* paranoid */ verify( kernelTLS().this_proc_id );
428
429        ready_schedule_lock();
430                $thread * thrd = pop_slow( this );
431        ready_schedule_unlock();
432
433        /* paranoid */ verify( kernelTLS().this_proc_id );
434        /* paranoid */ verify( ! __preemption_enabled() );
435        return thrd;
436}
437
438void unpark( $thread * thrd ) {
439        if( !thrd ) return;
440
441        int old_ticket = __atomic_fetch_add(&thrd->ticket, 1, __ATOMIC_SEQ_CST);
442        switch(old_ticket) {
443                case TICKET_RUNNING:
444                        // Wake won the race, the thread will reschedule/rerun itself
445                        break;
446                case TICKET_BLOCKED:
447                        /* paranoid */ verify( ! thrd->preempted != __NO_PREEMPTION );
448                        /* paranoid */ verify( thrd->state == Blocked );
449
450                        {
451                                /* paranoid */ verify( publicTLS_get(this_proc_id) );
452                                bool full = publicTLS_get(this_proc_id)->full_proc;
453                                if(full) disable_interrupts();
454
455                                /* paranoid */ verify( ! __preemption_enabled() );
456
457                                // Wake lost the race,
458                                __schedule_thread( thrd );
459
460                                /* paranoid */ verify( ! __preemption_enabled() );
461
462                                if(full) enable_interrupts( __cfaabi_dbg_ctx );
463                                /* paranoid */ verify( publicTLS_get(this_proc_id) );
464                        }
465
466                        break;
467                default:
468                        // This makes no sense, something is wrong abort
469                        abort("Thread %p (%s) has mismatch park/unpark\n", thrd, thrd->self_cor.name);
470        }
471}
472
473void park( void ) {
474        /* paranoid */ verify( __preemption_enabled() );
475        disable_interrupts();
476        /* paranoid */ verify( ! __preemption_enabled() );
477        /* paranoid */ verify( kernelTLS().this_thread->preempted == __NO_PREEMPTION );
478
479        returnToKernel();
480
481        /* paranoid */ verify( ! __preemption_enabled() );
482        enable_interrupts( __cfaabi_dbg_ctx );
483        /* paranoid */ verify( __preemption_enabled() );
484
485}
486
487extern "C" {
488        // Leave the thread monitor
489        // last routine called by a thread.
490        // Should never return
491        void __cfactx_thrd_leave() {
492                $thread * thrd = active_thread();
493                $monitor * this = &thrd->self_mon;
494
495                // Lock the monitor now
496                lock( this->lock __cfaabi_dbg_ctx2 );
497
498                disable_interrupts();
499
500                /* paranoid */ verify( ! __preemption_enabled() );
501                /* paranoid */ verify( thrd->state == Active );
502                /* paranoid */ verify( 0x0D15EA5E0D15EA5Ep == thrd->canary );
503                /* paranoid */ verify( kernelTLS().this_thread == thrd );
504                /* paranoid */ verify( thrd->context.SP );
505                /* paranoid */ verifyf( ((uintptr_t)thrd->context.SP) > ((uintptr_t)__get_stack(thrd->curr_cor)->limit), "ERROR : $thread %p has been corrupted.\n StackPointer too large.\n", thrd );
506                /* paranoid */ verifyf( ((uintptr_t)thrd->context.SP) < ((uintptr_t)__get_stack(thrd->curr_cor)->base ), "ERROR : $thread %p has been corrupted.\n StackPointer too small.\n", thrd );
507
508                thrd->state = Halting;
509                if( TICKET_RUNNING != thrd->ticket ) { abort( "Thread terminated with pending unpark" ); }
510                if( thrd != this->owner ) { abort( "Thread internal monitor has incorrect owner" ); }
511                if( this->recursion != 1) { abort( "Thread internal monitor has unbalanced recursion" ); }
512
513                // Leave the thread
514                returnToKernel();
515
516                // Control flow should never reach here!
517                abort();
518        }
519}
520
521// KERNEL ONLY
522bool force_yield( __Preemption_Reason reason ) {
523        /* paranoid */ verify( __preemption_enabled() );
524        disable_interrupts();
525        /* paranoid */ verify( ! __preemption_enabled() );
526
527        $thread * thrd = kernelTLS().this_thread;
528        /* paranoid */ verify(thrd->state == Active);
529
530        // SKULLDUGGERY: It is possible that we are preempting this thread just before
531        // it was going to park itself. If that is the case and it is already using the
532        // intrusive fields then we can't use them to preempt the thread
533        // If that is the case, abandon the preemption.
534        bool preempted = false;
535        if(thrd->link.next == 0p) {
536                preempted = true;
537                thrd->preempted = reason;
538                returnToKernel();
539        }
540
541        /* paranoid */ verify( ! __preemption_enabled() );
542        enable_interrupts_noPoll();
543        /* paranoid */ verify( __preemption_enabled() );
544
545        return preempted;
546}
547
548//=============================================================================================
549// Kernel Idle Sleep
550//=============================================================================================
551extern "C" {
552        char * strerror(int);
553}
554#define CHECKED(x) { int err = x; if( err != 0 ) abort("KERNEL ERROR: Operation \"" #x "\" return error %d - %s\n", err, strerror(err)); }
555
556static void wait(__bin_sem_t & this) with( this ) {
557        verify(__cfaabi_dbg_in_kernel());
558        CHECKED( pthread_mutex_lock(&lock) );
559                while(val < 1) {
560                        pthread_cond_wait(&cond, &lock);
561                }
562                val -= 1;
563        CHECKED( pthread_mutex_unlock(&lock) );
564}
565
566static bool post(__bin_sem_t & this) with( this ) {
567        bool needs_signal = false;
568
569        CHECKED( pthread_mutex_lock(&lock) );
570                if(val < 1) {
571                        val += 1;
572                        pthread_cond_signal(&cond);
573                        needs_signal = true;
574                }
575        CHECKED( pthread_mutex_unlock(&lock) );
576
577        return needs_signal;
578}
579
580#undef CHECKED
581
582// Wake a thread from the front if there are any
583static void __wake_one(cluster * this) {
584        /* paranoid */ verify( ! __preemption_enabled() );
585        /* paranoid */ verify( ready_schedule_islocked() );
586
587        // Check if there is a sleeping processor
588        processor * p;
589        unsigned idle;
590        unsigned total;
591        [idle, total, p] = query(this->idles);
592
593        // If no one is sleeping, we are done
594        if( idle == 0 ) return;
595
596        // We found a processor, wake it up
597        post( p->idle );
598
599        #if !defined(__CFA_NO_STATISTICS__)
600                __tls_stats()->ready.sleep.wakes++;
601        #endif
602
603        /* paranoid */ verify( ready_schedule_islocked() );
604        /* paranoid */ verify( ! __preemption_enabled() );
605
606        return;
607}
608
609// Unconditionnaly wake a thread
610void __wake_proc(processor * this) {
611        __cfadbg_print_safe(runtime_core, "Kernel : waking Processor %p\n", this);
612
613        disable_interrupts();
614                /* paranoid */ verify( ! __preemption_enabled() );
615                post( this->idle );
616        enable_interrupts( __cfaabi_dbg_ctx );
617}
618
619static void push  (__cluster_idles & this, processor & proc) {
620        /* paranoid */ verify( ! __preemption_enabled() );
621        lock( this );
622                this.idle++;
623                /* paranoid */ verify( this.idle <= this.total );
624
625                insert_first(this.list, proc);
626        unlock( this );
627        /* paranoid */ verify( ! __preemption_enabled() );
628}
629
630static void remove(__cluster_idles & this, processor & proc) {
631        /* paranoid */ verify( ! __preemption_enabled() );
632        lock( this );
633                this.idle--;
634                /* paranoid */ verify( this.idle >= 0 );
635
636                remove(proc);
637        unlock( this );
638        /* paranoid */ verify( ! __preemption_enabled() );
639}
640
641static [unsigned idle, unsigned total, * processor] query( & __cluster_idles this ) {
642        for() {
643                uint64_t l = __atomic_load_n(&this.lock, __ATOMIC_SEQ_CST);
644                if( 1 == (l % 2) ) { Pause(); continue; }
645                unsigned idle    = this.idle;
646                unsigned total   = this.total;
647                processor * proc = &this.list`first;
648                // Compiler fence is unnecessary, but gcc-8 and older incorrectly reorder code without it
649                asm volatile("": : :"memory");
650                if(l != __atomic_load_n(&this.lock, __ATOMIC_SEQ_CST)) { Pause(); continue; }
651                return [idle, total, proc];
652        }
653}
654
655//=============================================================================================
656// Unexpected Terminating logic
657//=============================================================================================
658void __kernel_abort_msg( char * abort_text, int abort_text_size ) {
659        $thread * thrd = __cfaabi_tls.this_thread;
660
661        if(thrd) {
662                int len = snprintf( abort_text, abort_text_size, "Error occurred while executing thread %.256s (%p)", thrd->self_cor.name, thrd );
663                __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
664
665                if ( &thrd->self_cor != thrd->curr_cor ) {
666                        len = snprintf( abort_text, abort_text_size, " in coroutine %.256s (%p).\n", thrd->curr_cor->name, thrd->curr_cor );
667                        __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
668                }
669                else {
670                        __cfaabi_bits_write( STDERR_FILENO, ".\n", 2 );
671                }
672        }
673        else {
674                int len = snprintf( abort_text, abort_text_size, "Error occurred outside of any thread.\n" );
675                __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
676        }
677}
678
679int __kernel_abort_lastframe( void ) __attribute__ ((__nothrow__)) {
680        return get_coroutine(__cfaabi_tls.this_thread) == get_coroutine(mainThread) ? 4 : 2;
681}
682
683static __spinlock_t kernel_debug_lock;
684
685extern "C" {
686        void __cfaabi_bits_acquire() {
687                lock( kernel_debug_lock __cfaabi_dbg_ctx2 );
688        }
689
690        void __cfaabi_bits_release() {
691                unlock( kernel_debug_lock );
692        }
693}
694
695//=============================================================================================
696// Kernel Utilities
697//=============================================================================================
698//-----------------------------------------------------------------------------
699// Debug
700__cfaabi_dbg_debug_do(
701        extern "C" {
702                void __cfaabi_dbg_record_lock(__spinlock_t & this, const char prev_name[]) {
703                        this.prev_name = prev_name;
704                        this.prev_thrd = kernelTLS().this_thread;
705                }
706        }
707)
708
709//-----------------------------------------------------------------------------
710// Debug
711bool threading_enabled(void) __attribute__((const)) {
712        return true;
713}
714
715//-----------------------------------------------------------------------------
716// Statistics
717#if !defined(__CFA_NO_STATISTICS__)
718        void print_halts( processor & this ) {
719                this.print_halts = true;
720        }
721
722        void print_stats_now( cluster & this, int flags ) {
723                __print_stats( this.stats, this.print_stats, "Cluster", this.name, (void*)&this );
724        }
725
726        extern int __print_alarm_stats;
727        void print_alarm_stats() {
728                __print_alarm_stats = -1;
729        }
730#endif
731// Local Variables: //
732// mode: c //
733// tab-width: 4 //
734// End: //
Note: See TracBrowser for help on using the repository browser.