source: libcfa/src/concurrency/kernel.cfa@ 040334e

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

Removed so-called 'new proc main' which wasn't useful.

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