source: libcfa/src/concurrency/kernel.cfa@ 3bb4f85

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

Kernel now waits for eventfd read to flush before terminating.

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