source: libcfa/src/concurrency/kernel.cfa @ 734908c

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

Fudge variable in schedule_thread so it's not accidently used.

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