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

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

Fixed stupid copy past mistake where I used eventfd_read (wait) instead of eventfd_write (signal).

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