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

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since a76efc8 was 254ad1b, checked in by Thierry Delisle <tdelisle@…>, 3 years ago

Separate schedule_thread from the scheduler lock

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