source: libcfa/src/concurrency/kernel.cfa@ 2514f68b

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

No longer define kernel_read when not needed.

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