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

arm-ehjacob/cs343-translationnew-ast-unique-expr
Last change on this file since ec43cf9 was ec43cf9, checked in by Thierry Delisle <tdelisle@…>, 7 months ago

Kernel now keeps track of the how many threads each processor has contributed.
This isn't useful if it is not sampled regularly but it's a first step.

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