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

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

Fixed some warnings

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