source: libcfa/src/concurrency/kernel.cfa @ 5c216b4

ADTast-experimentalenumpthread-emulationqualifiedEnum
Last change on this file since 5c216b4 was c9c1c1c, checked in by Thierry Delisle <tdelisle@…>, 3 years ago

Minor changes to kernel main loop and fixed stats.

  • Property mode set to 100644
File size: 28.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 _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_DEF( ...) __VA_ARGS__
45#else
46        #define __STATS_DEF( ...)
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 thread$ * __next_thread_search(cluster * this);
125static inline bool __must_unpark( thread$ * thrd ) __attribute((nonnull(1)));
126static void __run_thread(processor * this, thread$ * dst);
127static void __wake_one(cluster * cltr);
128
129static void idle_sleep(processor * proc, io_future_t & future, iovec & iov);
130static bool mark_idle (__cluster_proc_list & idles, processor & proc);
131static void mark_awake(__cluster_proc_list & idles, processor & proc);
132
133extern void __cfa_io_start( processor * );
134extern bool __cfa_io_drain( processor * );
135extern bool __cfa_io_flush( processor *, int min_comp );
136extern void __cfa_io_stop ( processor * );
137static inline bool __maybe_io_drain( processor * );
138
139#if defined(CFA_WITH_IO_URING_IDLE)
140        extern bool __kernel_read(processor * proc, io_future_t & future, iovec &, int fd);
141#endif
142
143extern void __disable_interrupts_hard();
144extern void __enable_interrupts_hard();
145
146
147//=============================================================================================
148// Kernel Scheduling logic
149//=============================================================================================
150//Main of the processor contexts
151void main(processorCtx_t & runner) {
152        // Because of a bug, we couldn't initialized the seed on construction
153        // Do it here
154        __cfaabi_tls.rand_seed ^= rdtscl();
155        __cfaabi_tls.ready_rng.fwd_seed = 25214903917_l64u * (rdtscl() ^ (uintptr_t)&runner);
156        __tls_rand_advance_bck();
157
158        processor * this = runner.proc;
159        verify(this);
160
161        io_future_t future; // used for idle sleep when io_uring is present
162        future.self.ptr = 1p;  // mark it as already fulfilled so we know if there is a pending request or not
163        eventfd_t idle_val;
164        iovec idle_iovec = { &idle_val, sizeof(idle_val) };
165
166        __cfa_io_start( this );
167
168        __cfadbg_print_safe(runtime_core, "Kernel : core %p starting\n", this);
169        #if !defined(__CFA_NO_STATISTICS__)
170                if( this->print_halts ) {
171                        __cfaabi_bits_print_safe( STDOUT_FILENO, "Processor : %d - %s (%p)\n", this->unique_id, this->name, (void*)this);
172                }
173        #endif
174
175        {
176                // Setup preemption data
177                preemption_scope scope = { this };
178
179                // if we need to run some special setup, now is the time to do it.
180                if(this->init.thrd) {
181                        this->init.thrd->curr_cluster = this->cltr;
182                        __run_thread(this, this->init.thrd);
183                }
184
185                __cfadbg_print_safe(runtime_core, "Kernel : core %p started\n", this);
186
187                thread$ * readyThread = 0p;
188                MAIN_LOOP:
189                for() {
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                                __IO_STATS__(true, io.flush.idle++; )
198                                __cfa_io_flush( this, 0 );
199
200                                readyThread = __next_thread( this->cltr );
201                        }
202
203                        if( !readyThread ) for(5) {
204                                __IO_STATS__(true, io.flush.idle++; )
205
206                                readyThread = __next_thread_slow( this->cltr );
207
208                                if( readyThread ) break;
209
210                                __cfa_io_flush( this, 0 );
211                        }
212
213                        HALT:
214                        if( !readyThread ) {
215                                // Don't block if we are done
216                                if( __atomic_load_n(&this->do_terminate, __ATOMIC_SEQ_CST) ) break MAIN_LOOP;
217
218                                // Push self to idle stack
219                                if(!mark_idle(this->cltr->procs, * this)) continue MAIN_LOOP;
220
221                                // Confirm the ready-queue is empty
222                                readyThread = __next_thread_search( this->cltr );
223                                if( readyThread ) {
224                                        // A thread was found, cancel the halt
225                                        mark_awake(this->cltr->procs, * this);
226
227                                        __STATS__(true, ready.sleep.cancels++; )
228
229                                        // continue the mai loop
230                                        break HALT;
231                                }
232
233                                idle_sleep( this, future, idle_iovec );
234
235                                // We were woken up, remove self from idle
236                                mark_awake(this->cltr->procs, * this);
237
238                                // DON'T just proceed, start looking again
239                                continue MAIN_LOOP;
240                        }
241
242                        /* paranoid */ verify( readyThread );
243
244                        // Reset io dirty bit
245                        this->io.dirty = false;
246
247                        // We found a thread run it
248                        __run_thread(this, readyThread);
249
250                        // Are we done?
251                        if( __atomic_load_n(&this->do_terminate, __ATOMIC_SEQ_CST) ) break MAIN_LOOP;
252
253                        if(this->io.pending && !this->io.dirty) {
254                                __IO_STATS__(true, io.flush.dirty++; )
255                                __cfa_io_flush( this, 0 );
256                        }
257                }
258
259                __cfadbg_print_safe(runtime_core, "Kernel : core %p stopping\n", this);
260        }
261
262        for(int i = 0; !available(future); i++) {
263                if(i > 1000) __cfaabi_dbg_write( "ERROR: kernel has bin spinning on a flush after exit loop.\n", 60);
264                __cfa_io_flush( this, 1 );
265        }
266
267        __cfa_io_stop( this );
268
269        post( this->terminated );
270
271        if(this == mainProcessor) {
272                // HACK : the coroutine context switch expects this_thread to be set
273                // and it make sense for it to be set in all other cases except here
274                // fake it
275                __cfaabi_tls.this_thread = mainThread;
276        }
277
278        __cfadbg_print_safe(runtime_core, "Kernel : core %p terminated\n", this);
279}
280
281static int * __volatile_errno() __attribute__((noinline));
282static int * __volatile_errno() { asm(""); return &errno; }
283
284// KERNEL ONLY
285// runThread runs a thread by context switching
286// from the processor coroutine to the target thread
287static void __run_thread(processor * this, thread$ * thrd_dst) {
288        /* paranoid */ verify( ! __preemption_enabled() );
289        /* paranoid */ verifyf( thrd_dst->state == Ready || thrd_dst->preempted != __NO_PREEMPTION, "state : %d, preempted %d\n", thrd_dst->state, thrd_dst->preempted);
290        /* paranoid */ verifyf( thrd_dst->link.next == 0p, "Expected null got %p", thrd_dst->link.next );
291        __builtin_prefetch( thrd_dst->context.SP );
292
293        __cfadbg_print_safe(runtime_core, "Kernel : core %p running thread %p (%s)\n", this, thrd_dst, thrd_dst->self_cor.name);
294
295        coroutine$ * proc_cor = get_coroutine(this->runner);
296
297        // set state of processor coroutine to inactive
298        verify(proc_cor->state == Active);
299        proc_cor->state = Blocked;
300
301        // Actually run the thread
302        RUNNING:  while(true) {
303                thrd_dst->preempted = __NO_PREEMPTION;
304                thrd_dst->state = Active;
305
306                // Update global state
307                kernelTLS().this_thread = thrd_dst;
308
309                /* paranoid */ verify( ! __preemption_enabled() );
310                /* paranoid */ verify( kernelTLS().this_thread == thrd_dst );
311                /* paranoid */ verify( thrd_dst->curr_cluster == this->cltr );
312                /* paranoid */ verify( thrd_dst->context.SP );
313                /* paranoid */ verify( thrd_dst->state != Halted );
314                /* 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
315                /* 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
316                /* paranoid */ verify( 0x0D15EA5E0D15EA5Ep == thrd_dst->canary );
317
318
319
320                // set context switch to the thread that the processor is executing
321                __cfactx_switch( &proc_cor->context, &thrd_dst->context );
322                // when __cfactx_switch returns we are back in the processor coroutine
323
324
325
326                /* paranoid */ verify( 0x0D15EA5E0D15EA5Ep == thrd_dst->canary );
327                /* 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 );
328                /* 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 );
329                /* paranoid */ verify( thrd_dst->context.SP );
330                /* paranoid */ verify( thrd_dst->curr_cluster == this->cltr );
331                /* paranoid */ verify( kernelTLS().this_thread == thrd_dst );
332                /* paranoid */ verify( ! __preemption_enabled() );
333
334                // Reset global state
335                kernelTLS().this_thread = 0p;
336
337                // We just finished running a thread, there are a few things that could have happened.
338                // 1 - Regular case : the thread has blocked and now one has scheduled it yet.
339                // 2 - Racy case    : the thread has blocked but someone has already tried to schedule it.
340                // 4 - Preempted
341                // In case 1, we may have won a race so we can't write to the state again.
342                // In case 2, we lost the race so we now own the thread.
343
344                if(unlikely(thrd_dst->preempted != __NO_PREEMPTION)) {
345                        // The thread was preempted, reschedule it and reset the flag
346                        schedule_thread$( thrd_dst, UNPARK_LOCAL );
347                        break RUNNING;
348                }
349
350                if(unlikely(thrd_dst->state == Halting)) {
351                        // The thread has halted, it should never be scheduled/run again
352                        // finish the thread
353                        __thread_finish( thrd_dst );
354                        break RUNNING;
355                }
356
357                /* paranoid */ verify( thrd_dst->state == Active );
358                thrd_dst->state = Blocked;
359
360                // set state of processor coroutine to active and the thread to inactive
361                int old_ticket = __atomic_fetch_sub(&thrd_dst->ticket, 1, __ATOMIC_SEQ_CST);
362                switch(old_ticket) {
363                        case TICKET_RUNNING:
364                                // This is case 1, the regular case, nothing more is needed
365                                break RUNNING;
366                        case TICKET_UNBLOCK:
367                                __STATS__(true, ready.threads.threads++; )
368                                // This is case 2, the racy case, someone tried to run this thread before it finished blocking
369                                // In this case, just run it again.
370                                continue RUNNING;
371                        default:
372                                // This makes no sense, something is wrong abort
373                                abort();
374                }
375        }
376
377        // Just before returning to the processor, set the processor coroutine to active
378        proc_cor->state = Active;
379
380        __cfadbg_print_safe(runtime_core, "Kernel : core %p finished running thread %p\n", this, thrd_dst);
381
382        __STATS__(true, ready.threads.threads--; )
383
384        /* paranoid */ verify( ! __preemption_enabled() );
385}
386
387// KERNEL_ONLY
388void returnToKernel() {
389        /* paranoid */ verify( ! __preemption_enabled() );
390        coroutine$ * proc_cor = get_coroutine(kernelTLS().this_processor->runner);
391        thread$ * thrd_src = kernelTLS().this_thread;
392
393        __STATS_DEF( thrd_src->last_proc = kernelTLS().this_processor; )
394
395        // Run the thread on this processor
396        {
397                int local_errno = *__volatile_errno();
398                #if defined( __i386 ) || defined( __x86_64 )
399                        __x87_store;
400                #endif
401                /* paranoid */ verify( proc_cor->context.SP );
402                /* paranoid */ verify( 0x0D15EA5E0D15EA5Ep == thrd_src->canary );
403                __cfactx_switch( &thrd_src->context, &proc_cor->context );
404                /* paranoid */ verify( 0x0D15EA5E0D15EA5Ep == thrd_src->canary );
405                #if defined( __i386 ) || defined( __x86_64 )
406                        __x87_load;
407                #endif
408                *__volatile_errno() = local_errno;
409        }
410
411        #if !defined(__CFA_NO_STATISTICS__)
412                /* paranoid */ verify( thrd_src->last_proc != 0p );
413                if(thrd_src->last_proc != kernelTLS().this_processor) {
414                        __tls_stats()->ready.threads.migration++;
415                }
416        #endif
417
418        /* paranoid */ verify( ! __preemption_enabled() );
419        /* paranoid */ verifyf( ((uintptr_t)thrd_src->context.SP) < ((uintptr_t)__get_stack(thrd_src->curr_cor)->base ) || thrd_src->corctx_flag, "ERROR : Returning thread$ %p has been corrupted.\n StackPointer too small.\n", thrd_src );
420        /* paranoid */ verifyf( ((uintptr_t)thrd_src->context.SP) > ((uintptr_t)__get_stack(thrd_src->curr_cor)->limit) || thrd_src->corctx_flag, "ERROR : Returning thread$ %p has been corrupted.\n StackPointer too large.\n", thrd_src );
421}
422
423//-----------------------------------------------------------------------------
424// Scheduler routines
425// KERNEL ONLY
426static void __schedule_thread( thread$ * thrd, unpark_hint hint ) {
427        /* paranoid */ verify( ! __preemption_enabled() );
428        /* paranoid */ verify( ready_schedule_islocked());
429        /* paranoid */ verify( thrd );
430        /* paranoid */ verify( thrd->state != Halted );
431        /* paranoid */ verify( thrd->curr_cluster );
432        /* paranoid */ #if defined( __CFA_WITH_VERIFY__ )
433        /* paranoid */  if( thrd->state == Blocked || thrd->state == Start ) assertf( thrd->preempted == __NO_PREEMPTION,
434                                        "Error inactive thread marked as preempted, state %d, preemption %d\n", thrd->state, thrd->preempted );
435        /* paranoid */  if( thrd->preempted != __NO_PREEMPTION ) assertf(thrd->state == Active,
436                                        "Error preempted thread marked as not currently running, state %d, preemption %d\n", thrd->state, thrd->preempted );
437        /* paranoid */ #endif
438        /* paranoid */ verifyf( thrd->link.next == 0p, "Expected null got %p", thrd->link.next );
439        /* paranoid */ verify( 0x0D15EA5E0D15EA5Ep == thrd->canary );
440
441        if (thrd->preempted == __NO_PREEMPTION) thrd->state = Ready;
442
443        // Dereference the thread now because once we push it, there is not guaranteed it's still valid.
444        struct cluster * cl = thrd->curr_cluster;
445        __STATS_DEF(bool outside = hint == UNPARK_LOCAL && thrd->last_proc && thrd->last_proc != kernelTLS().this_processor; )
446
447        // push the thread to the cluster ready-queue
448        push( cl, thrd, hint );
449
450        // variable thrd is no longer safe to use
451        thrd = 0xdeaddeaddeaddeadp;
452
453        // wake the cluster using the save variable.
454        __wake_one( cl );
455
456        #if !defined(__CFA_NO_STATISTICS__)
457                if( kernelTLS().this_stats ) {
458                        __tls_stats()->ready.threads.threads++;
459                        if(outside) {
460                                __tls_stats()->ready.threads.extunpark++;
461                        }
462                }
463                else {
464                        __atomic_fetch_add(&cl->stats->ready.threads.threads, 1, __ATOMIC_RELAXED);
465                        __atomic_fetch_add(&cl->stats->ready.threads.extunpark, 1, __ATOMIC_RELAXED);
466                }
467        #endif
468
469        /* paranoid */ verify( ready_schedule_islocked());
470        /* paranoid */ verify( ! __preemption_enabled() );
471}
472
473void schedule_thread$( thread$ * thrd, unpark_hint hint ) {
474        ready_schedule_lock();
475                __schedule_thread( thrd, hint );
476        ready_schedule_unlock();
477}
478
479// KERNEL ONLY
480static inline thread$ * __next_thread(cluster * this) with( *this ) {
481        /* paranoid */ verify( ! __preemption_enabled() );
482
483        ready_schedule_lock();
484                thread$ * thrd = pop_fast( this );
485        ready_schedule_unlock();
486
487        /* paranoid */ verify( ! __preemption_enabled() );
488        return thrd;
489}
490
491// KERNEL ONLY
492static inline thread$ * __next_thread_slow(cluster * this) with( *this ) {
493        /* paranoid */ verify( ! __preemption_enabled() );
494
495        ready_schedule_lock();
496                thread$ * thrd = pop_slow( this );
497        ready_schedule_unlock();
498
499        /* paranoid */ verify( ! __preemption_enabled() );
500        return thrd;
501}
502
503// KERNEL ONLY
504static inline thread$ * __next_thread_search(cluster * this) with( *this ) {
505        /* paranoid */ verify( ! __preemption_enabled() );
506
507        ready_schedule_lock();
508                thread$ * thrd = pop_search( this );
509        ready_schedule_unlock();
510
511        /* paranoid */ verify( ! __preemption_enabled() );
512        return thrd;
513}
514
515static inline bool __must_unpark( thread$ * thrd ) {
516        int old_ticket = __atomic_fetch_add(&thrd->ticket, 1, __ATOMIC_SEQ_CST);
517        switch(old_ticket) {
518                case TICKET_RUNNING:
519                        // Wake won the race, the thread will reschedule/rerun itself
520                        return false;
521                case TICKET_BLOCKED:
522                        /* paranoid */ verify( ! thrd->preempted != __NO_PREEMPTION );
523                        /* paranoid */ verify( thrd->state == Blocked );
524                        return true;
525                default:
526                        // This makes no sense, something is wrong abort
527                        abort("Thread %p (%s) has mismatch park/unpark\n", thrd, thrd->self_cor.name);
528        }
529}
530
531void __kernel_unpark( thread$ * thrd, unpark_hint hint ) {
532        /* paranoid */ verify( ! __preemption_enabled() );
533        /* paranoid */ verify( ready_schedule_islocked());
534
535        if( !thrd ) return;
536
537        if(__must_unpark(thrd)) {
538                // Wake lost the race,
539                __schedule_thread( thrd, hint );
540        }
541
542        /* paranoid */ verify( ready_schedule_islocked());
543        /* paranoid */ verify( ! __preemption_enabled() );
544}
545
546void unpark( thread$ * thrd, unpark_hint hint ) {
547        if( !thrd ) return;
548
549        if(__must_unpark(thrd)) {
550                disable_interrupts();
551                        // Wake lost the race,
552                        schedule_thread$( thrd, hint );
553                enable_interrupts(false);
554        }
555}
556
557void park( void ) {
558        __disable_interrupts_checked();
559                /* paranoid */ verify( kernelTLS().this_thread->preempted == __NO_PREEMPTION );
560                returnToKernel();
561        __enable_interrupts_checked();
562
563}
564
565extern "C" {
566        // Leave the thread monitor
567        // last routine called by a thread.
568        // Should never return
569        void __cfactx_thrd_leave() {
570                thread$ * thrd = active_thread();
571                monitor$ * this = &thrd->self_mon;
572
573                // Lock the monitor now
574                lock( this->lock __cfaabi_dbg_ctx2 );
575
576                disable_interrupts();
577
578                /* paranoid */ verify( ! __preemption_enabled() );
579                /* paranoid */ verify( thrd->state == Active );
580                /* paranoid */ verify( 0x0D15EA5E0D15EA5Ep == thrd->canary );
581                /* paranoid */ verify( kernelTLS().this_thread == thrd );
582                /* paranoid */ verify( thrd->context.SP );
583                /* 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 );
584                /* 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 );
585
586                thrd->state = Halting;
587                if( TICKET_RUNNING != thrd->ticket ) { abort( "Thread terminated with pending unpark" ); }
588                if( thrd != this->owner ) { abort( "Thread internal monitor has incorrect owner" ); }
589                if( this->recursion != 1) { abort( "Thread internal monitor has unbalanced recursion" ); }
590
591                // Leave the thread
592                returnToKernel();
593
594                // Control flow should never reach here!
595                abort();
596        }
597}
598
599// KERNEL ONLY
600bool force_yield( __Preemption_Reason reason ) {
601        __disable_interrupts_checked();
602                thread$ * thrd = kernelTLS().this_thread;
603                /* paranoid */ verify(thrd->state == Active);
604
605                // SKULLDUGGERY: It is possible that we are preempting this thread just before
606                // it was going to park itself. If that is the case and it is already using the
607                // intrusive fields then we can't use them to preempt the thread
608                // If that is the case, abandon the preemption.
609                bool preempted = false;
610                if(thrd->link.next == 0p) {
611                        preempted = true;
612                        thrd->preempted = reason;
613                        returnToKernel();
614                }
615        __enable_interrupts_checked( false );
616        return preempted;
617}
618
619//=============================================================================================
620// Kernel Idle Sleep
621//=============================================================================================
622// Wake a thread from the front if there are any
623static void __wake_one(cluster * this) {
624        eventfd_t val;
625
626        /* paranoid */ verify( ! __preemption_enabled() );
627        /* paranoid */ verify( ready_schedule_islocked() );
628
629        // Check if there is a sleeping processor
630        struct __fd_waitctx * fdp = __atomic_load_n(&this->procs.fdw, __ATOMIC_SEQ_CST);
631
632        // If no one is sleeping: we are done
633        if( fdp == 0p ) return;
634
635        int fd = 1;
636        if( __atomic_load_n(&fdp->fd, __ATOMIC_SEQ_CST) != 1 ) {
637                fd = __atomic_exchange_n(&fdp->fd, 1, __ATOMIC_RELAXED);
638        }
639
640        switch(fd) {
641        case 0:
642                // If the processor isn't ready to sleep then the exchange will already wake it up
643                #if !defined(__CFA_NO_STATISTICS__)
644                        if( kernelTLS().this_stats ) { __tls_stats()->ready.sleep.early++;
645                        } else { __atomic_fetch_add(&this->stats->ready.sleep.early, 1, __ATOMIC_RELAXED); }
646                #endif
647                break;
648        case 1:
649                // If someone else already said they will wake them: we are done
650                #if !defined(__CFA_NO_STATISTICS__)
651                        if( kernelTLS().this_stats ) { __tls_stats()->ready.sleep.seen++;
652                        } else { __atomic_fetch_add(&this->stats->ready.sleep.seen, 1, __ATOMIC_RELAXED); }
653                #endif
654                break;
655        default:
656                // If the processor was ready to sleep, we need to wake it up with an actual write
657                val = 1;
658                eventfd_write( fd, val );
659
660                #if !defined(__CFA_NO_STATISTICS__)
661                        if( kernelTLS().this_stats ) { __tls_stats()->ready.sleep.wakes++;
662                        } else { __atomic_fetch_add(&this->stats->ready.sleep.wakes, 1, __ATOMIC_RELAXED); }
663                #endif
664                break;
665        }
666
667        /* paranoid */ verify( ready_schedule_islocked() );
668        /* paranoid */ verify( ! __preemption_enabled() );
669
670        return;
671}
672
673// Unconditionnaly wake a thread
674void __wake_proc(processor * this) {
675        /* paranoid */ verify( ! __preemption_enabled() );
676
677        __cfadbg_print_safe(runtime_core, "Kernel : waking Processor %p\n", this);
678
679        this->idle_wctx.fd = 1;
680
681        eventfd_t val;
682        val = 1;
683        eventfd_write( this->idle_fd, val );
684
685        /* paranoid */ verify( ! __preemption_enabled() );
686}
687
688static void idle_sleep(processor * this, io_future_t & future, iovec & iov) {
689        // Tell everyone we are ready to go do sleep
690        for() {
691                int expected = this->idle_wctx.fd;
692
693                // Someone already told us to wake-up! No time for a nap.
694                if(expected == 1) { return; }
695
696                // Try to mark that we are going to sleep
697                if(__atomic_compare_exchange_n(&this->idle_wctx.fd, &expected, this->idle_fd, false,  __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) ) {
698                        // Every one agreed, taking a nap
699                        break;
700                }
701        }
702
703
704        #if !defined(CFA_WITH_IO_URING_IDLE)
705                #if !defined(__CFA_NO_STATISTICS__)
706                        if(this->print_halts) {
707                                __cfaabi_bits_print_safe( STDOUT_FILENO, "PH:%d - %lld 0\n", this->unique_id, rdtscl());
708                        }
709                #endif
710
711                __cfadbg_print_safe(runtime_core, "Kernel : core %p waiting on eventfd %d\n", this, this->idle_fd);
712
713                {
714                        eventfd_t val;
715                        ssize_t ret = read( this->idle_fd, &val, sizeof(val) );
716                        if(ret < 0) {
717                                switch((int)errno) {
718                                case EAGAIN:
719                                #if EAGAIN != EWOULDBLOCK
720                                        case EWOULDBLOCK:
721                                #endif
722                                case EINTR:
723                                        // No need to do anything special here, just assume it's a legitimate wake-up
724                                        break;
725                                default:
726                                        abort( "KERNEL : internal error, read failure on idle eventfd, error(%d) %s.", (int)errno, strerror( (int)errno ) );
727                                }
728                        }
729                }
730
731                #if !defined(__CFA_NO_STATISTICS__)
732                        if(this->print_halts) {
733                                __cfaabi_bits_print_safe( STDOUT_FILENO, "PH:%d - %lld 1\n", this->unique_id, rdtscl());
734                        }
735                #endif
736        #else
737                // Do we already have a pending read
738                if(available(future)) {
739                        // There is no pending read, we need to add one
740                        reset(future);
741
742                        __kernel_read(this, future, iov, this->idle_fd );
743                }
744
745                __cfa_io_flush( this, 1 );
746        #endif
747}
748
749static bool mark_idle(__cluster_proc_list & this, processor & proc) {
750        __STATS__(true, ready.sleep.halts++; )
751
752        proc.idle_wctx.fd = 0;
753
754        /* paranoid */ verify( ! __preemption_enabled() );
755        if(!try_lock( this )) return false;
756                this.idle++;
757                /* paranoid */ verify( this.idle <= this.total );
758                remove(proc);
759                insert_first(this.idles, proc);
760
761                __atomic_store_n(&this.fdw, &proc.idle_wctx, __ATOMIC_SEQ_CST);
762        unlock( this );
763        /* paranoid */ verify( ! __preemption_enabled() );
764
765        return true;
766}
767
768static void mark_awake(__cluster_proc_list & this, processor & proc) {
769        /* paranoid */ verify( ! __preemption_enabled() );
770        lock( this );
771                this.idle--;
772                /* paranoid */ verify( this.idle >= 0 );
773                remove(proc);
774                insert_last(this.actives, proc);
775
776                {
777                        struct __fd_waitctx * wctx = 0;
778                        if(!this.idles`isEmpty) wctx = &this.idles`first.idle_wctx;
779                        __atomic_store_n(&this.fdw, wctx, __ATOMIC_SEQ_CST);
780                }
781
782        unlock( this );
783        /* paranoid */ verify( ! __preemption_enabled() );
784}
785
786//=============================================================================================
787// Unexpected Terminating logic
788//=============================================================================================
789void __kernel_abort_msg( char * abort_text, int abort_text_size ) {
790        thread$ * thrd = __cfaabi_tls.this_thread;
791
792        if(thrd) {
793                int len = snprintf( abort_text, abort_text_size, "Error occurred while executing thread %.256s (%p)", thrd->self_cor.name, thrd );
794                __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
795
796                if ( &thrd->self_cor != thrd->curr_cor ) {
797                        len = snprintf( abort_text, abort_text_size, " in coroutine %.256s (%p).\n", thrd->curr_cor->name, thrd->curr_cor );
798                        __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
799                }
800                else {
801                        __cfaabi_bits_write( STDERR_FILENO, ".\n", 2 );
802                }
803        }
804        else {
805                int len = snprintf( abort_text, abort_text_size, "Error occurred outside of any thread.\n" );
806                __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
807        }
808}
809
810int __kernel_abort_lastframe( void ) __attribute__ ((__nothrow__)) {
811        return get_coroutine(__cfaabi_tls.this_thread) == get_coroutine(mainThread) ? 4 : 2;
812}
813
814static __spinlock_t kernel_debug_lock;
815
816extern "C" {
817        void __cfaabi_bits_acquire() {
818                lock( kernel_debug_lock __cfaabi_dbg_ctx2 );
819        }
820
821        void __cfaabi_bits_release() {
822                unlock( kernel_debug_lock );
823        }
824}
825
826//=============================================================================================
827// Kernel Utilities
828//=============================================================================================
829#if defined(CFA_HAVE_LINUX_IO_URING_H)
830#include "io/types.hfa"
831#endif
832
833static inline bool __maybe_io_drain( processor * proc ) {
834        bool ret = false;
835        #if defined(CFA_HAVE_LINUX_IO_URING_H)
836                __cfadbg_print_safe(runtime_core, "Kernel : core %p checking io for ring %d\n", proc, proc->io.ctx->fd);
837
838                // Check if we should drain the queue
839                $io_context * ctx = proc->io.ctx;
840                unsigned head = *ctx->cq.head;
841                unsigned tail = *ctx->cq.tail;
842                if(head == tail) return false;
843                ready_schedule_lock();
844                ret = __cfa_io_drain( proc );
845                ready_schedule_unlock();
846        #endif
847        return ret;
848}
849
850//-----------------------------------------------------------------------------
851// Debug
852__cfaabi_dbg_debug_do(
853        extern "C" {
854                void __cfaabi_dbg_record_lock(__spinlock_t & this, const char prev_name[]) {
855                        this.prev_name = prev_name;
856                        this.prev_thrd = kernelTLS().this_thread;
857                }
858        }
859)
860
861//-----------------------------------------------------------------------------
862// Debug
863bool threading_enabled(void) __attribute__((const)) {
864        return true;
865}
866
867//-----------------------------------------------------------------------------
868// Statistics
869#if !defined(__CFA_NO_STATISTICS__)
870        void print_halts( processor & this ) {
871                this.print_halts = true;
872        }
873
874        static void crawl_list( cluster * cltr, dlist(processor) & list, unsigned count ) {
875                /* paranoid */ verify( cltr->stats );
876
877                processor * it = &list`first;
878                for(unsigned i = 0; i < count; i++) {
879                        /* paranoid */ verifyf( it, "Unexpected null iterator, at index %u of %u\n", i, count);
880                        /* paranoid */ verify( it->local_data->this_stats );
881                        // __print_stats( it->local_data->this_stats, cltr->print_stats, "Processor", it->name, (void*)it );
882                        __tally_stats( cltr->stats, it->local_data->this_stats );
883                        it = &(*it)`next;
884                }
885        }
886
887        void crawl_cluster_stats( cluster & this ) {
888                // Stop the world, otherwise stats could get really messed-up
889                // this doesn't solve all problems but does solve many
890                // so it's probably good enough
891                disable_interrupts();
892                uint_fast32_t last_size = ready_mutate_lock();
893
894                        crawl_list(&this, this.procs.actives, this.procs.total - this.procs.idle);
895                        crawl_list(&this, this.procs.idles  , this.procs.idle );
896
897                // Unlock the RWlock
898                ready_mutate_unlock( last_size );
899                enable_interrupts();
900        }
901
902
903        void print_stats_now( cluster & this, int flags ) {
904                crawl_cluster_stats( this );
905                __print_stats( this.stats, this.print_stats, "Cluster", this.name, (void*)&this );
906        }
907#endif
908// Local Variables: //
909// mode: c //
910// tab-width: 4 //
911// End: //
Note: See TracBrowser for help on using the repository browser.