source: libcfa/src/concurrency/kernel.cfa @ 45fde9f

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

Added missing corctx_flag in assertion

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