source: libcfa/src/concurrency/kernel.cfa @ 43784ac

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

Changed libcfathread to consistently define _GNU_SOURCE

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