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

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

Added forward/reverse rng for later use in the ready queue

  • Property mode set to 100644
File size: 22.2 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 : Thu Jul  9 06:22:54 2020
13// Update Count     : 66
14//
15
16#define __cforall_thread__
17// #define __CFA_DEBUG_PRINT_RUNTIME_CORE__
18
19//C Includes
20#include <errno.h>
21#include <stdio.h>
22#include <signal.h>
23#include <unistd.h>
24
25//CFA Includes
26#include "kernel_private.hfa"
27#include "preemption.hfa"
28
29//Private includes
30#define __CFA_INVOKE_PRIVATE__
31#include "invoke.h"
32
33
34//-----------------------------------------------------------------------------
35// Some assembly required
36#if defined( __i386 )
37        // mxcr : SSE Status and Control bits (control bits are preserved across function calls)
38        // fcw  : X87 FPU control word (preserved across function calls)
39        #define __x87_store         \
40                uint32_t __mxcr;      \
41                uint16_t __fcw;       \
42                __asm__ volatile (    \
43                        "stmxcsr %0\n"  \
44                        "fnstcw  %1\n"  \
45                        : "=m" (__mxcr),\
46                                "=m" (__fcw)  \
47                )
48
49        #define __x87_load         \
50                __asm__ volatile (   \
51                        "fldcw  %1\n"  \
52                        "ldmxcsr %0\n" \
53                        ::"m" (__mxcr),\
54                                "m" (__fcw)  \
55                )
56
57#elif defined( __x86_64 )
58        #define __x87_store         \
59                uint32_t __mxcr;      \
60                uint16_t __fcw;       \
61                __asm__ volatile (    \
62                        "stmxcsr %0\n"  \
63                        "fnstcw  %1\n"  \
64                        : "=m" (__mxcr),\
65                                "=m" (__fcw)  \
66                )
67
68        #define __x87_load          \
69                __asm__ volatile (    \
70                        "fldcw  %1\n"   \
71                        "ldmxcsr %0\n"  \
72                        :: "m" (__mxcr),\
73                                "m" (__fcw)  \
74                )
75
76
77#elif defined( __ARM_ARCH )
78#else
79        #error unknown hardware architecture
80#endif
81
82extern $thread * mainThread;
83extern processor * mainProcessor;
84
85//-----------------------------------------------------------------------------
86// Kernel Scheduling logic
87static $thread * __next_thread(cluster * this);
88static $thread * __next_thread_slow(cluster * this);
89static void __run_thread(processor * this, $thread * dst);
90static void __wake_one(struct __processor_id_t * id, cluster * cltr);
91
92static void push  (__cluster_idles & idles, processor & proc);
93static void remove(__cluster_idles & idles, processor & proc);
94static [unsigned idle, unsigned total, * processor] query( & __cluster_idles idles );
95
96
97//=============================================================================================
98// Kernel Scheduling logic
99//=============================================================================================
100//Main of the processor contexts
101void main(processorCtx_t & runner) {
102        // Because of a bug, we couldn't initialized the seed on construction
103        // Do it here
104        kernelTLS.rand_seed ^= rdtscl();
105        kernelTLS.ready_rng.fwd_seed = 25214903917_l64u * (rdtscl() ^ (uintptr_t)&runner);
106        __tls_rand_advance_bck();
107
108        processor * this = runner.proc;
109        verify(this);
110
111        __cfadbg_print_safe(runtime_core, "Kernel : core %p starting\n", this);
112        #if !defined(__CFA_NO_STATISTICS__)
113                if( this->print_halts ) {
114                        __cfaabi_bits_print_safe( STDOUT_FILENO, "Processor : %d - %s (%p)\n", this->id, this->name, (void*)this);
115                }
116        #endif
117
118        {
119                // Setup preemption data
120                preemption_scope scope = { this };
121
122                __cfadbg_print_safe(runtime_core, "Kernel : core %p started\n", this);
123
124                $thread * readyThread = 0p;
125                MAIN_LOOP:
126                for() {
127                        // Try to get the next thread
128                        readyThread = __next_thread( this->cltr );
129
130                        if( !readyThread ) {
131                                readyThread = __next_thread_slow( this->cltr );
132                        }
133
134                        HALT:
135                        if( !readyThread ) {
136                                // Don't block if we are done
137                                if( __atomic_load_n(&this->do_terminate, __ATOMIC_SEQ_CST) ) break MAIN_LOOP;
138
139                                #if !defined(__CFA_NO_STATISTICS__)
140                                        __tls_stats()->ready.sleep.halts++;
141                                #endif
142
143                                // Push self to idle stack
144                                push(this->cltr->idles, * this);
145
146                                // Confirm the ready-queue is empty
147                                readyThread = __next_thread_slow( this->cltr );
148                                if( readyThread ) {
149                                        // A thread was found, cancel the halt
150                                        remove(this->cltr->idles, * this);
151
152                                        #if !defined(__CFA_NO_STATISTICS__)
153                                                __tls_stats()->ready.sleep.cancels++;
154                                        #endif
155
156                                        // continue the mai loop
157                                        break HALT;
158                                }
159
160                                #if !defined(__CFA_NO_STATISTICS__)
161                                        if(this->print_halts) {
162                                                __cfaabi_bits_print_safe( STDOUT_FILENO, "PH:%d - %lld 0\n", this->id, rdtscl());
163                                        }
164                                #endif
165
166                                wait( this->idle );
167
168                                #if !defined(__CFA_NO_STATISTICS__)
169                                        if(this->print_halts) {
170                                                __cfaabi_bits_print_safe( STDOUT_FILENO, "PH:%d - %lld 1\n", this->id, rdtscl());
171                                        }
172                                #endif
173
174                                // We were woken up, remove self from idle
175                                remove(this->cltr->idles, * this);
176
177                                // DON'T just proceed, start looking again
178                                continue MAIN_LOOP;
179                        }
180
181                        /* paranoid */ verify( readyThread );
182
183                        // We found a thread run it
184                        __run_thread(this, readyThread);
185
186                        // Are we done?
187                        if( __atomic_load_n(&this->do_terminate, __ATOMIC_SEQ_CST) ) break MAIN_LOOP;
188                }
189
190                __cfadbg_print_safe(runtime_core, "Kernel : core %p stopping\n", this);
191        }
192
193        V( this->terminated );
194
195        if(this == mainProcessor) {
196                // HACK : the coroutine context switch expects this_thread to be set
197                // and it make sense for it to be set in all other cases except here
198                // fake it
199                kernelTLS.this_thread = mainThread;
200        }
201
202        __cfadbg_print_safe(runtime_core, "Kernel : core %p terminated\n", this);
203}
204
205static int * __volatile_errno() __attribute__((noinline));
206static int * __volatile_errno() { asm(""); return &errno; }
207
208// KERNEL ONLY
209// runThread runs a thread by context switching
210// from the processor coroutine to the target thread
211static void __run_thread(processor * this, $thread * thrd_dst) {
212        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
213        /* paranoid */ verifyf( thrd_dst->state == Ready || thrd_dst->preempted != __NO_PREEMPTION, "state : %d, preempted %d\n", thrd_dst->state, thrd_dst->preempted);
214        /* paranoid */ verifyf( thrd_dst->link.next == 0p, "Expected null got %p", thrd_dst->link.next );
215        __builtin_prefetch( thrd_dst->context.SP );
216
217        $coroutine * proc_cor = get_coroutine(this->runner);
218
219        // Update global state
220        kernelTLS.this_thread = thrd_dst;
221
222        // set state of processor coroutine to inactive
223        verify(proc_cor->state == Active);
224        proc_cor->state = Blocked;
225
226        // Actually run the thread
227        RUNNING:  while(true) {
228                thrd_dst->preempted = __NO_PREEMPTION;
229                thrd_dst->state = Active;
230
231                __cfaabi_dbg_debug_do(
232                        thrd_dst->park_stale   = true;
233                        thrd_dst->unpark_stale = true;
234                )
235
236                /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
237                /* paranoid */ verify( kernelTLS.this_thread == thrd_dst );
238                /* paranoid */ verifyf( ((uintptr_t)thrd_dst->context.SP) < ((uintptr_t)__get_stack(thrd_dst->curr_cor)->base ) || thrd_dst->curr_cor == proc_cor, "ERROR : Destination $thread %p has been corrupted.\n StackPointer too small.\n", thrd_dst ); // add escape condition if we are setting up the processor
239                /* paranoid */ verifyf( ((uintptr_t)thrd_dst->context.SP) > ((uintptr_t)__get_stack(thrd_dst->curr_cor)->limit) || thrd_dst->curr_cor == proc_cor, "ERROR : Destination $thread %p has been corrupted.\n StackPointer too large.\n", thrd_dst ); // add escape condition if we are setting up the processor
240
241                // set context switch to the thread that the processor is executing
242                verify( thrd_dst->context.SP );
243                __cfactx_switch( &proc_cor->context, &thrd_dst->context );
244                // when __cfactx_switch returns we are back in the processor coroutine
245
246                /* paranoid */ verifyf( ((uintptr_t)thrd_dst->context.SP) > ((uintptr_t)__get_stack(thrd_dst->curr_cor)->limit), "ERROR : Destination $thread %p has been corrupted.\n StackPointer too large.\n", thrd_dst );
247                /* paranoid */ verifyf( ((uintptr_t)thrd_dst->context.SP) < ((uintptr_t)__get_stack(thrd_dst->curr_cor)->base ), "ERROR : Destination $thread %p has been corrupted.\n StackPointer too small.\n", thrd_dst );
248                /* paranoid */ verify( kernelTLS.this_thread == thrd_dst );
249                /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
250
251
252                // We just finished running a thread, there are a few things that could have happened.
253                // 1 - Regular case : the thread has blocked and now one has scheduled it yet.
254                // 2 - Racy case    : the thread has blocked but someone has already tried to schedule it.
255                // 4 - Preempted
256                // In case 1, we may have won a race so we can't write to the state again.
257                // In case 2, we lost the race so we now own the thread.
258
259                if(unlikely(thrd_dst->preempted != __NO_PREEMPTION)) {
260                        // The thread was preempted, reschedule it and reset the flag
261                        __schedule_thread( (__processor_id_t*)this, thrd_dst );
262                        break RUNNING;
263                }
264
265                if(unlikely(thrd_dst->state == Halted)) {
266                        // The thread has halted, it should never be scheduled/run again
267                        // We may need to wake someone up here since
268                        unpark( this->destroyer __cfaabi_dbg_ctx2 );
269                        this->destroyer = 0p;
270                        break RUNNING;
271                }
272
273                /* paranoid */ verify( thrd_dst->state == Active );
274                thrd_dst->state = Blocked;
275
276                // set state of processor coroutine to active and the thread to inactive
277                int old_ticket = __atomic_fetch_sub(&thrd_dst->ticket, 1, __ATOMIC_SEQ_CST);
278                __cfaabi_dbg_debug_do( thrd_dst->park_result = old_ticket; )
279                switch(old_ticket) {
280                        case 1:
281                                // This is case 1, the regular case, nothing more is needed
282                                break RUNNING;
283                        case 2:
284                                // This is case 2, the racy case, someone tried to run this thread before it finished blocking
285                                // In this case, just run it again.
286                                continue RUNNING;
287                        default:
288                                // This makes no sense, something is wrong abort
289                                abort();
290                }
291        }
292
293        // Just before returning to the processor, set the processor coroutine to active
294        proc_cor->state = Active;
295        kernelTLS.this_thread = 0p;
296
297        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
298}
299
300// KERNEL_ONLY
301void returnToKernel() {
302        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
303        $coroutine * proc_cor = get_coroutine(kernelTLS.this_processor->runner);
304        $thread * thrd_src = kernelTLS.this_thread;
305
306        #if !defined(__CFA_NO_STATISTICS__)
307                struct processor * last_proc = kernelTLS.this_processor;
308        #endif
309
310        // Run the thread on this processor
311        {
312                int local_errno = *__volatile_errno();
313                #if defined( __i386 ) || defined( __x86_64 )
314                        __x87_store;
315                #endif
316                verify( proc_cor->context.SP );
317                __cfactx_switch( &thrd_src->context, &proc_cor->context );
318                #if defined( __i386 ) || defined( __x86_64 )
319                        __x87_load;
320                #endif
321                *__volatile_errno() = local_errno;
322        }
323
324        #if !defined(__CFA_NO_STATISTICS__)
325                if(last_proc != kernelTLS.this_processor) {
326                        __tls_stats()->ready.threads.migration++;
327                }
328        #endif
329
330        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
331        /* paranoid */ verifyf( ((uintptr_t)thrd_src->context.SP) < ((uintptr_t)__get_stack(thrd_src->curr_cor)->base ), "ERROR : Returning $thread %p has been corrupted.\n StackPointer too small.\n", thrd_src );
332        /* paranoid */ verifyf( ((uintptr_t)thrd_src->context.SP) > ((uintptr_t)__get_stack(thrd_src->curr_cor)->limit), "ERROR : Returning $thread %p has been corrupted.\n StackPointer too large.\n", thrd_src );
333}
334
335//-----------------------------------------------------------------------------
336// Scheduler routines
337// KERNEL ONLY
338void __schedule_thread( struct __processor_id_t * id, $thread * thrd ) {
339        /* paranoid */ verify( thrd );
340        /* paranoid */ verify( thrd->state != Halted );
341        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
342        /* paranoid */ #if defined( __CFA_WITH_VERIFY__ )
343        /* paranoid */  if( thrd->state == Blocked || thrd->state == Start ) assertf( thrd->preempted == __NO_PREEMPTION,
344                                        "Error inactive thread marked as preempted, state %d, preemption %d\n", thrd->state, thrd->preempted );
345        /* paranoid */  if( thrd->preempted != __NO_PREEMPTION ) assertf(thrd->state == Active,
346                                        "Error preempted thread marked as not currently running, state %d, preemption %d\n", thrd->state, thrd->preempted );
347        /* paranoid */ #endif
348        /* paranoid */ verifyf( thrd->link.next == 0p, "Expected null got %p", thrd->link.next );
349
350        if (thrd->preempted == __NO_PREEMPTION) thrd->state = Ready;
351
352        ready_schedule_lock  ( id );
353                push( thrd->curr_cluster, thrd );
354                __wake_one(id, thrd->curr_cluster);
355        ready_schedule_unlock( id );
356
357        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
358}
359
360// KERNEL ONLY
361static inline $thread * __next_thread(cluster * this) with( *this ) {
362        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
363
364        ready_schedule_lock  ( (__processor_id_t*)kernelTLS.this_processor );
365                $thread * thrd = pop( this );
366        ready_schedule_unlock( (__processor_id_t*)kernelTLS.this_processor );
367
368        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
369        return thrd;
370}
371
372// KERNEL ONLY
373static inline $thread * __next_thread_slow(cluster * this) with( *this ) {
374        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
375
376        ready_schedule_lock  ( (__processor_id_t*)kernelTLS.this_processor );
377                $thread * thrd = pop_slow( this );
378        ready_schedule_unlock( (__processor_id_t*)kernelTLS.this_processor );
379
380        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
381        return thrd;
382}
383
384// KERNEL ONLY unpark with out disabling interrupts
385void __unpark(  struct __processor_id_t * id, $thread * thrd __cfaabi_dbg_ctx_param2 ) {
386        // record activity
387        __cfaabi_dbg_record_thrd( *thrd, false, caller );
388
389        int old_ticket = __atomic_fetch_add(&thrd->ticket, 1, __ATOMIC_SEQ_CST);
390        __cfaabi_dbg_debug_do( thrd->unpark_result = old_ticket; thrd->unpark_state = thrd->state; )
391        switch(old_ticket) {
392                case 1:
393                        // Wake won the race, the thread will reschedule/rerun itself
394                        break;
395                case 0:
396                        /* paranoid */ verify( ! thrd->preempted != __NO_PREEMPTION );
397                        /* paranoid */ verify( thrd->state == Blocked );
398
399                        // Wake lost the race,
400                        __schedule_thread( id, thrd );
401                        break;
402                default:
403                        // This makes no sense, something is wrong abort
404                        abort();
405        }
406}
407
408void unpark( $thread * thrd __cfaabi_dbg_ctx_param2 ) {
409        if( !thrd ) return;
410
411        disable_interrupts();
412        __unpark( (__processor_id_t*)kernelTLS.this_processor, thrd __cfaabi_dbg_ctx_fwd2 );
413        enable_interrupts( __cfaabi_dbg_ctx );
414}
415
416void park( __cfaabi_dbg_ctx_param ) {
417        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
418        disable_interrupts();
419        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
420        /* paranoid */ verify( kernelTLS.this_thread->preempted == __NO_PREEMPTION );
421
422        // record activity
423        __cfaabi_dbg_record_thrd( *kernelTLS.this_thread, true, caller );
424
425        returnToKernel();
426
427        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
428        enable_interrupts( __cfaabi_dbg_ctx );
429        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
430
431}
432
433// KERNEL ONLY
434void __leave_thread() {
435        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
436        returnToKernel();
437        abort();
438}
439
440// KERNEL ONLY
441bool force_yield( __Preemption_Reason reason ) {
442        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
443        disable_interrupts();
444        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
445
446        $thread * thrd = kernelTLS.this_thread;
447        /* paranoid */ verify(thrd->state == Active);
448
449        // SKULLDUGGERY: It is possible that we are preempting this thread just before
450        // it was going to park itself. If that is the case and it is already using the
451        // intrusive fields then we can't use them to preempt the thread
452        // If that is the case, abandon the preemption.
453        bool preempted = false;
454        if(thrd->link.next == 0p) {
455                preempted = true;
456                thrd->preempted = reason;
457                returnToKernel();
458        }
459
460        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
461        enable_interrupts_noPoll();
462        /* paranoid */ verify( kernelTLS.preemption_state.enabled );
463
464        return preempted;
465}
466
467//=============================================================================================
468// Kernel Idle Sleep
469//=============================================================================================
470// Wake a thread from the front if there are any
471static void __wake_one(struct __processor_id_t * id, cluster * this) {
472        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
473        /* paranoid */ verify( ready_schedule_islocked( id ) );
474
475        // Check if there is a sleeping processor
476        processor * p;
477        unsigned idle;
478        unsigned total;
479        [idle, total, p] = query(this->idles);
480
481        // If no one is sleeping, we are done
482        if( idle == 0 ) return;
483
484        // We found a processor, wake it up
485        post( p->idle );
486
487        #if !defined(__CFA_NO_STATISTICS__)
488                __tls_stats()->ready.sleep.wakes++;
489        #endif
490
491        /* paranoid */ verify( ready_schedule_islocked( id ) );
492        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
493
494        return;
495}
496
497// Unconditionnaly wake a thread
498void __wake_proc(processor * this) {
499        __cfadbg_print_safe(runtime_core, "Kernel : waking Processor %p\n", this);
500
501        disable_interrupts();
502                /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
503                bool ret = post( this->idle );
504        enable_interrupts( __cfaabi_dbg_ctx );
505}
506
507static void push  (__cluster_idles & this, processor & proc) {
508        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
509        lock( this );
510                this.idle++;
511                /* paranoid */ verify( this.idle <= this.total );
512
513                insert_first(this.list, proc);
514        unlock( this );
515        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
516}
517
518static void remove(__cluster_idles & this, processor & proc) {
519        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
520        lock( this );
521                this.idle--;
522                /* paranoid */ verify( this.idle >= 0 );
523
524                remove(proc);
525        unlock( this );
526        /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
527}
528
529static [unsigned idle, unsigned total, * processor] query( & __cluster_idles this ) {
530        for() {
531                uint64_t l = __atomic_load_n(&this.lock, __ATOMIC_SEQ_CST);
532                if( 1 == (l % 2) ) { Pause(); continue; }
533                unsigned idle    = this.idle;
534                unsigned total   = this.total;
535                processor * proc = &this.list`first;
536                // Compiler fence is unnecessary, but gcc-8 and older incorrectly reorder code without it
537                asm volatile("": : :"memory");
538                if(l != __atomic_load_n(&this.lock, __ATOMIC_SEQ_CST)) { Pause(); continue; }
539                return [idle, total, proc];
540        }
541}
542
543//=============================================================================================
544// Unexpected Terminating logic
545//=============================================================================================
546static __spinlock_t kernel_abort_lock;
547static bool kernel_abort_called = false;
548
549void * kernel_abort(void) __attribute__ ((__nothrow__)) {
550        // abort cannot be recursively entered by the same or different processors because all signal handlers return when
551        // the globalAbort flag is true.
552        lock( kernel_abort_lock __cfaabi_dbg_ctx2 );
553
554        // first task to abort ?
555        if ( kernel_abort_called ) {                    // not first task to abort ?
556                unlock( kernel_abort_lock );
557
558                sigset_t mask;
559                sigemptyset( &mask );
560                sigaddset( &mask, SIGALRM );            // block SIGALRM signals
561                sigaddset( &mask, SIGUSR1 );            // block SIGALRM signals
562                sigsuspend( &mask );                            // block the processor to prevent further damage during abort
563                _exit( EXIT_FAILURE );                          // if processor unblocks before it is killed, terminate it
564        }
565        else {
566                kernel_abort_called = true;
567                unlock( kernel_abort_lock );
568        }
569
570        return kernelTLS.this_thread;
571}
572
573void kernel_abort_msg( void * kernel_data, char * abort_text, int abort_text_size ) {
574        $thread * thrd = ( $thread * ) kernel_data;
575
576        if(thrd) {
577                int len = snprintf( abort_text, abort_text_size, "Error occurred while executing thread %.256s (%p)", thrd->self_cor.name, thrd );
578                __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
579
580                if ( &thrd->self_cor != thrd->curr_cor ) {
581                        len = snprintf( abort_text, abort_text_size, " in coroutine %.256s (%p).\n", thrd->curr_cor->name, thrd->curr_cor );
582                        __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
583                }
584                else {
585                        __cfaabi_bits_write( STDERR_FILENO, ".\n", 2 );
586                }
587        }
588        else {
589                int len = snprintf( abort_text, abort_text_size, "Error occurred outside of any thread.\n" );
590                __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
591        }
592}
593
594int kernel_abort_lastframe( void ) __attribute__ ((__nothrow__)) {
595        return get_coroutine(kernelTLS.this_thread) == get_coroutine(mainThread) ? 4 : 2;
596}
597
598static __spinlock_t kernel_debug_lock;
599
600extern "C" {
601        void __cfaabi_bits_acquire() {
602                lock( kernel_debug_lock __cfaabi_dbg_ctx2 );
603        }
604
605        void __cfaabi_bits_release() {
606                unlock( kernel_debug_lock );
607        }
608}
609
610//=============================================================================================
611// Kernel Utilities
612//=============================================================================================
613//-----------------------------------------------------------------------------
614// Locks
615void  ?{}( semaphore & this, int count = 1 ) {
616        (this.lock){};
617        this.count = count;
618        (this.waiting){};
619}
620void ^?{}(semaphore & this) {}
621
622bool P(semaphore & this) with( this ){
623        lock( lock __cfaabi_dbg_ctx2 );
624        count -= 1;
625        if ( count < 0 ) {
626                // queue current task
627                append( waiting, kernelTLS.this_thread );
628
629                // atomically release spin lock and block
630                unlock( lock );
631                park( __cfaabi_dbg_ctx );
632                return true;
633        }
634        else {
635            unlock( lock );
636            return false;
637        }
638}
639
640bool V(semaphore & this) with( this ) {
641        $thread * thrd = 0p;
642        lock( lock __cfaabi_dbg_ctx2 );
643        count += 1;
644        if ( count <= 0 ) {
645                // remove task at head of waiting list
646                thrd = pop_head( waiting );
647        }
648
649        unlock( lock );
650
651        // make new owner
652        unpark( thrd __cfaabi_dbg_ctx2 );
653
654        return thrd != 0p;
655}
656
657bool V(semaphore & this, unsigned diff) with( this ) {
658        $thread * thrd = 0p;
659        lock( lock __cfaabi_dbg_ctx2 );
660        int release = max(-count, (int)diff);
661        count += diff;
662        for(release) {
663                unpark( pop_head( waiting ) __cfaabi_dbg_ctx2 );
664        }
665
666        unlock( lock );
667
668        return thrd != 0p;
669}
670
671//-----------------------------------------------------------------------------
672// Debug
673__cfaabi_dbg_debug_do(
674        extern "C" {
675                void __cfaabi_dbg_record_lock(__spinlock_t & this, const char prev_name[]) {
676                        this.prev_name = prev_name;
677                        this.prev_thrd = kernelTLS.this_thread;
678                }
679
680                void __cfaabi_dbg_record_thrd($thread & this, bool park, const char prev_name[]) {
681                        if(park) {
682                                this.park_caller   = prev_name;
683                                this.park_stale    = false;
684                        }
685                        else {
686                                this.unpark_caller = prev_name;
687                                this.unpark_stale  = false;
688                        }
689                }
690        }
691)
692
693//-----------------------------------------------------------------------------
694// Debug
695bool threading_enabled(void) __attribute__((const)) {
696        return true;
697}
698
699//-----------------------------------------------------------------------------
700// Statistics
701#if !defined(__CFA_NO_STATISTICS__)
702        void print_halts( processor & this ) {
703                this.print_halts = true;
704        }
705#endif
706// Local Variables: //
707// mode: c //
708// tab-width: 4 //
709// End: //
Note: See TracBrowser for help on using the repository browser.