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

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

Updated alternate main for processors

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