source: libcfa/src/concurrency/kernel.cfa@ 97fed44

ADT ast-experimental enum forall-pointer-decay pthread-emulation qualifiedEnum
Last change on this file since 97fed44 was 7cf3b1d, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Added level of indirection to idle sleeps which helps statistics.

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