source: libcfa/src/concurrency/kernel.cfa@ 660665f

ADT ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 660665f was 12daa43, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Added a define switch for using cpu workstealing.
Not Fully implemented.

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