source: libcfa/src/concurrency/kernel.cfa @ 70b4aeb9

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

Commit last changes before moving off plg7a

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