source: libcfa/src/concurrency/kernel.cfa @ 03cdad6

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

Reworked io_uring idle sleep to work with either read or readv depending on what's available.

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