source: libcfa/src/concurrency/kernel.cfa@ 040334e

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

Removed so-called 'new proc main' which wasn't useful.

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