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

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

Fix implementation of io_uring_enter instead of eventfds.

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