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

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

Seperated semphore and scheduling logic in unpark

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