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

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

Removed last parker/unparker information is it was not particularly useful

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