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

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

Commit last changes before moving off plg7a

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