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

ADTast-experimentalenumforall-pointer-decaypthread-emulationqualifiedEnum
Last change on this file since a633f6f was a633f6f, checked in by Thierry Delisle <tdelisle@…>, 2 years ago

Fix the new FD change.

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