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

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

Added level of indirection to idle sleeps which helps statistics.

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