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

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

Added verify and changed print_now to not ignore flags.

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