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

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

Refactoring idle sleep to try and help the change from idle on read to idle on io_uring_enter.

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