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

ADT ast-experimental enum pthread-emulation qualifiedEnum
Last change on this file since f5a51db was c9c1c1cb, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Minor changes to kernel main loop and fixed stats.

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