source: libcfa/src/concurrency/kernel.cfa @ 813dfd86

ADTast-experimentalenumforall-pointer-decaypthread-emulationqualifiedEnum
Last change on this file since 813dfd86 was a633f6f, checked in by Thierry Delisle <tdelisle@…>, 2 years ago

Fix the new FD change.

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