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

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

Kernel now waits for eventfd read to flush before terminating.

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