source: libcfa/src/concurrency/kernel.cfa@ 6dba8755

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 6dba8755 was b81fd95, checked in by Michael Brooks <mlbrooks@…>, 5 years ago

Fix bug where pointer and reference types allow unsound initialization and return. Fixes #189

There are two instances of the same basic change, which is using conversionCost instead of castCost for resolving...
A: an InitExpr, always; affects variable initializations
B: a CastExpr, for type-system-generated casts only; affects function returns

Changing the behaviour of the typechecker on initialization (do A) and cast (do B):
src/ResolvExpr/AlternativeFinder.cc
src/SynTree/Expression.h
testsinit1.*

Making type of string literal consistent with how C defines it (accommodate A):
src/Parser/ExpressionNode.cc

Making type system happy with incumbent use of void* (accommodate A):
libcfa/src/concurrency/kernel.cfa
libcfa/src/containers/list.hfa
tests/bugs/66.cfa
tests/avltree/avl1.cfa
tests/concurrent/signal/block.cfa
tests/searchsort.cfa

Making type system happy with incumbent plan-9 downcast (accommodate B):
libcfa/src/containers/list.hfa

Fixing previously incorrect constness of declarations (accommodate A):
tests/exceptions/defaults.cfa
libcfa/src/iostream.hfa

Fixing previously incorrect isGenerated classification of casts that desugaring introduces (accommodate B):
src/Concurrency/Keywords.cc
src/Concurrency/Waitfor.cc

Working around trac #207 (revealed by A):
tests/io2.cfa

Working around trac #208 (speculatively created by B):
libcfa/src/bits/locks.hfa
libcfa/src/concurrency/preemption.cfa

Misc:
tests/exceptions/conditional.cfa (accommodate A)

a _msg function for an exception was declared with wrong return type, so it was not compatible for assignment into the vtable instance

libcfa/src/stdlib.hfa

the compiler now prohibits a prior attempt to call a nonexistent realloc overload; calling alloc_align in its place

  • Property mode set to 100644
File size: 38.2 KB
RevLine 
[8118303]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
[75f3522]10// Created On : Tue Jan 17 12:27:26 2017
[6b0b624]11// Last Modified By : Peter A. Buhr
[bb83b47]12// Last Modified On : Thu Jul 9 06:22:54 2020
13// Update Count : 66
[8118303]14//
15
[2026bb6]16#define __cforall_thread__
[4069faad]17// #define __CFA_DEBUG_PRINT_RUNTIME_CORE__
[2026bb6]18
[8118303]19//C Includes
[c84e80a]20#include <stddef.h>
[214e8da]21#include <errno.h>
[ea8b2f7]22#include <string.h>
[9d944b2]23#include <stdio.h>
[8fcbb4c]24#include <fenv.h>
[58b6d1b]25#include <signal.h>
[9d944b2]26#include <unistd.h>
[27f5f71]27#include <limits.h> // PTHREAD_STACK_MIN
[1a3040c]28#include <sys/mman.h> // mprotect
[ada0246d]29extern "C" {
30#include <sys/resource.h>
[eb2e723]31}
[8118303]32
33//CFA Includes
[58b6d1b]34#include "time.hfa"
[73abe95]35#include "kernel_private.hfa"
36#include "preemption.hfa"
37#include "startup.hfa"
[8118303]38
39//Private includes
40#define __CFA_INVOKE_PRIVATE__
41#include "invoke.h"
42
[4069faad]43
[deca0f5]44//-----------------------------------------------------------------------------
45// Some assembly required
[1805b1b]46#if defined( __i386 )
[deca0f5]47 #define CtxGet( ctx ) \
48 __asm__ volatile ( \
49 "movl %%esp,%0\n"\
50 "movl %%ebp,%1\n"\
51 : "=rm" (ctx.SP),\
52 "=rm" (ctx.FP) \
53 )
54
55 // mxcr : SSE Status and Control bits (control bits are preserved across function calls)
56 // fcw : X87 FPU control word (preserved across function calls)
57 #define __x87_store \
58 uint32_t __mxcr; \
59 uint16_t __fcw; \
60 __asm__ volatile ( \
61 "stmxcsr %0\n" \
62 "fnstcw %1\n" \
63 : "=m" (__mxcr),\
64 "=m" (__fcw) \
65 )
66
67 #define __x87_load \
68 __asm__ volatile ( \
69 "fldcw %1\n" \
70 "ldmxcsr %0\n" \
71 ::"m" (__mxcr),\
72 "m" (__fcw) \
73 )
74
75#elif defined( __x86_64 )
76 #define CtxGet( ctx ) \
77 __asm__ volatile ( \
78 "movq %%rsp,%0\n"\
79 "movq %%rbp,%1\n"\
80 : "=rm" (ctx.SP),\
81 "=rm" (ctx.FP) \
82 )
83
84 #define __x87_store \
85 uint32_t __mxcr; \
86 uint16_t __fcw; \
87 __asm__ volatile ( \
88 "stmxcsr %0\n" \
89 "fnstcw %1\n" \
90 : "=m" (__mxcr),\
91 "=m" (__fcw) \
92 )
93
94 #define __x87_load \
95 __asm__ volatile ( \
96 "fldcw %1\n" \
97 "ldmxcsr %0\n" \
98 :: "m" (__mxcr),\
99 "m" (__fcw) \
100 )
101
102
103#elif defined( __ARM_ARCH )
104#define CtxGet( ctx ) __asm__ ( \
105 "mov %0,%%sp\n" \
106 "mov %1,%%r11\n" \
107 : "=rm" (ctx.SP), "=rm" (ctx.FP) )
108#else
109 #error unknown hardware architecture
110#endif
111
112//-----------------------------------------------------------------------------
[2ac095d]113//Start and stop routine for the kernel, declared first to make sure they run first
[8c50aed]114static void __kernel_startup (void) __attribute__(( constructor( STARTUP_PRIORITY_KERNEL ) ));
115static void __kernel_shutdown(void) __attribute__(( destructor ( STARTUP_PRIORITY_KERNEL ) ));
[2ac095d]116
[92e7631]117//-----------------------------------------------------------------------------
118// Kernel Scheduling logic
119static $thread * __next_thread(cluster * this);
[64a7146]120static bool __has_next_thread(cluster * this);
[92e7631]121static void __run_thread(processor * this, $thread * dst);
122static bool __wake_proc(processor *);
[64a7146]123static bool __wake_one(struct __processor_id_t * id, cluster * cltr);
124static void __halt(processor * this);
[2ac095d]125
[8def349]126//-----------------------------------------------------------------------------
127// Kernel storage
[b388ee81]128KERNEL_STORAGE(cluster, mainCluster);
129KERNEL_STORAGE(processor, mainProcessor);
130KERNEL_STORAGE($thread, mainThread);
131KERNEL_STORAGE(__stack_t, mainThreadCtx);
132KERNEL_STORAGE(__scheduler_RWLock_t, __scheduler_lock);
[8834751]133#if !defined(__CFA_NO_STATISTICS__)
134KERNEL_STORAGE(__stats_t, mainProcStats);
135#endif
[8def349]136
[b388ee81]137cluster * mainCluster;
138processor * mainProcessor;
139$thread * mainThread;
140__scheduler_RWLock_t * __scheduler_lock;
[eb2e723]141
[ea8b2f7]142extern "C" {
[1805b1b]143 struct { __dllist_t(cluster) list; __spinlock_t lock; } __cfa_dbg_global_clusters;
[ea8b2f7]144}
[de94a60]145
[b2f6113]146size_t __page_size = 0;
147
[bd98b58]148//-----------------------------------------------------------------------------
149// Global state
[bb83b47]150thread_local struct KernelThreadData kernelTLS __attribute__ ((tls_model ( "initial-exec" ))) @= {
[1805b1b]151 NULL, // cannot use 0p
[b10affd]152 NULL,
[8834751]153 NULL,
[21184e3]154 { 1, false, false },
[b10affd]155};
[c84e80a]156
157//-----------------------------------------------------------------------------
[de6319f]158// Struct to steal stack
[8def349]159struct current_stack_info_t {
[1805b1b]160 __stack_t * storage; // pointer to stack object
161 void * base; // base of stack
162 void * limit; // stack grows towards stack limit
163 void * context; // address of cfa_context_t
[c84e80a]164};
165
[242a902]166void ?{}( current_stack_info_t & this ) {
[b2f6113]167 __stack_context_t ctx;
168 CtxGet( ctx );
169 this.base = ctx.FP;
[8def349]170
171 rlimit r;
[132fad4]172 getrlimit( RLIMIT_STACK, &r);
[69a61d2]173 size_t size = r.rlim_cur;
[8def349]174
[69a61d2]175 this.limit = (void *)(((intptr_t)this.base) - size);
[9236060]176 this.context = &storage_mainThreadCtx;
[8def349]177}
178
[de6319f]179//-----------------------------------------------------------------------------
180// Main thread construction
[8def349]181
[ac2b598]182void ?{}( $coroutine & this, current_stack_info_t * info) with( this ) {
[b2f6113]183 stack.storage = info->storage;
184 with(*stack.storage) {
185 limit = info->limit;
186 base = info->base;
187 }
[ffe2fad]188 __attribute__((may_alias)) intptr_t * istorage = (intptr_t*) &stack.storage;
189 *istorage |= 0x1;
[65deb18]190 name = "Main Thread";
191 state = Start;
[1805b1b]192 starter = 0p;
193 last = 0p;
194 cancellation = 0p;
[8def349]195}
196
[ac2b598]197void ?{}( $thread & this, current_stack_info_t * info) with( this ) {
[ff79d5e]198 ticket = 1;
[e8e457e]199 state = Start;
[65deb18]200 self_cor{ info };
[82c948c]201 curr_cor = &self_cor;
[de6319f]202 curr_cluster = mainCluster;
[82c948c]203 self_mon.owner = &this;
204 self_mon.recursion = 1;
205 self_mon_p = &self_mon;
[b798713]206 link.next = 0p;
207 link.prev = 0p;
[de94a60]208
[1805b1b]209 node.next = 0p;
210 node.prev = 0p;
[a1a17a74]211 doregister(curr_cluster, this);
[82c948c]212
213 monitors{ &self_mon_p, 1, (fptr_t)0 };
[8def349]214}
[c84e80a]215
[8def349]216//-----------------------------------------------------------------------------
217// Processor coroutine
[de6319f]218void ?{}(processorCtx_t & this) {
[39fea2f]219
[8def349]220}
221
[39fea2f]222// Construct the processor context of non-main processors
[c29c342]223static void ?{}(processorCtx_t & this, processor * proc, current_stack_info_t * info) {
[242a902]224 (this.__cor){ info };
225 this.proc = proc;
[8def349]226}
227
[c7a900a]228static void * __invoke_processor(void * arg);
[8c50aed]229
[28d73c1]230static init(processor & this, const char name[], cluster & _cltr) with( this ) {
[de6319f]231 this.name = name;
[13c5e19]232 this.cltr = &_cltr;
[7768b8d]233 id = -1u;
[b0c7419]234 destroyer = 0p;
[c40e7c5]235 do_terminate = false;
[1805b1b]236 preemption_alarm = 0p;
[c40e7c5]237 pending_preemption = false;
[8def349]238
[c34ebf2]239 #if !defined(__CFA_NO_STATISTICS__)
[69fbc61]240 print_stats = 0;
[c34ebf2]241 print_halts = false;
242 #endif
243
[320ec6fc]244 int target = __atomic_add_fetch( &cltr->nprocessors, 1u, __ATOMIC_SEQ_CST );
[28d73c1]245
246 id = doregister((__processor_id_t*)&this);
247
248 // Lock the RWlock so no-one pushes/pops while we are changing the queue
249 uint_fast32_t last_size = ready_mutate_lock();
250
251 // Adjust the ready queue size
[320ec6fc]252 ready_queue_grow( cltr, target );
[28d73c1]253
254 // Unlock the RWlock
255 ready_mutate_unlock( last_size );
256
257 __cfadbg_print_safe(runtime_core, "Kernel : core %p created\n", &this);
258}
259
260// Not a ctor, it just preps the destruction but should not destroy members
261void deinit(processor & this) {
[320ec6fc]262
263 int target = __atomic_sub_fetch( &this.cltr->nprocessors, 1u, __ATOMIC_SEQ_CST );
264
[28d73c1]265 // Lock the RWlock so no-one pushes/pops while we are changing the queue
266 uint_fast32_t last_size = ready_mutate_lock();
267
268 // Adjust the ready queue size
[320ec6fc]269 ready_queue_shrink( this.cltr, target );
[28d73c1]270
271 // Make sure we aren't on the idle queue
272 unsafe_remove( this.cltr->idles, &this );
273
274 // Unlock the RWlock
275 ready_mutate_unlock( last_size );
276
277 // Finally we don't need the read_lock any more
278 unregister((__processor_id_t*)&this);
279}
280
281void ?{}(processor & this, const char name[], cluster & _cltr) {
282 ( this.idle ){};
283 ( this.terminated ){ 0 };
284 ( this.runner ){};
285 init( this, name, _cltr );
[6b4cdd3]286
[4069faad]287 __cfadbg_print_safe(runtime_core, "Kernel : Starting core %p\n", &this);
[8c50aed]288
[c7a900a]289 this.stack = __create_pthread( &this.kernel_thread, __invoke_processor, (void *)&this );
[8c50aed]290
[c84e80a]291}
292
[65deb18]293void ^?{}(processor & this) with( this ){
[ea8b2f7]294 if( ! __atomic_load_n(&do_terminate, __ATOMIC_ACQUIRE) ) {
[4069faad]295 __cfadbg_print_safe(runtime_core, "Kernel : core %p signaling termination\n", &this);
[85b1deb]296
297 __atomic_store_n(&do_terminate, true, __ATOMIC_RELAXED);
[92e7631]298 __wake_proc( &this );
[85b1deb]299
[65deb18]300 P( terminated );
[14a61b5]301 verify( kernelTLS.this_processor != &this);
[8def349]302 }
[6b4cdd3]303
[c66f6cb]304 int err = pthread_join( kernel_thread, 0p );
305 if( err != 0 ) abort("KERNEL ERROR: joining processor %p caused error %s\n", &this, strerror(err));
306
[27f5f71]307 free( this.stack );
[13c5e19]308
[28d73c1]309 deinit( this );
[8def349]310}
311
[dd4e2d7]312void ?{}(cluster & this, const char name[], Duration preemption_rate, unsigned io_flags) with( this ) {
[de6319f]313 this.name = name;
314 this.preemption_rate = preemption_rate;
[13c5e19]315 this.nprocessors = 0;
[65deb18]316 ready_queue{};
[de94a60]317
[038be32]318 #if !defined(__CFA_NO_STATISTICS__)
[69fbc61]319 print_stats = 0;
[8834751]320 stats = alloc();
321 __init_stats( stats );
[038be32]322 #endif
323
[a1a17a74]324 threads{ __get };
[de94a60]325
326 doregister(this);
[39fc03e]327
328 // Lock the RWlock so no-one pushes/pops while we are changing the queue
329 uint_fast32_t last_size = ready_mutate_lock();
330
331 // Adjust the ready queue size
332 ready_queue_grow( &this, 0 );
333
334 // Unlock the RWlock
335 ready_mutate_unlock( last_size );
336
337
338 __kernel_io_startup( this, io_flags, &this == mainCluster );
[8def349]339}
340
[242a902]341void ^?{}(cluster & this) {
[f6660520]342 __kernel_io_shutdown( this, &this == mainCluster );
[92976d9]343
[39fc03e]344 // Lock the RWlock so no-one pushes/pops while we are changing the queue
345 uint_fast32_t last_size = ready_mutate_lock();
346
347 // Adjust the ready queue size
348 ready_queue_shrink( &this, 0 );
349
350 // Unlock the RWlock
351 ready_mutate_unlock( last_size );
352
[8834751]353 #if !defined(__CFA_NO_STATISTICS__)
[69fbc61]354 if( 0 != this.print_stats ) {
355 __print_stats( this.stats, this.print_stats, true, this.name, (void*)&this );
[8834751]356 }
357 free( this.stats );
358 #endif
359
[de94a60]360 unregister(this);
[c84e80a]361}
362
[75f3522]363//=============================================================================================
364// Kernel Scheduling logic
365//=============================================================================================
[8fcbb4c]366//Main of the processor contexts
[83a071f9]367void main(processorCtx_t & runner) {
[21184e3]368 // Because of a bug, we couldn't initialized the seed on construction
369 // Do it here
[7768b8d]370 kernelTLS.rand_seed ^= rdtscl();
[21184e3]371
[83a071f9]372 processor * this = runner.proc;
[094476d]373 verify(this);
[c81ebf9]374
[4069faad]375 __cfadbg_print_safe(runtime_core, "Kernel : core %p starting\n", this);
[28d73c1]376 #if !defined(__CFA_NO_STATISTICS__)
377 if( this->print_halts ) {
378 __cfaabi_bits_print_safe( STDOUT_FILENO, "Processor : %d - %s (%p)\n", this->id, this->name, (void*)this);
379 }
380 #endif
[b798713]381
[75f3522]382 {
[c81ebf9]383 // Setup preemption data
384 preemption_scope scope = { this };
385
[4069faad]386 __cfadbg_print_safe(runtime_core, "Kernel : core %p started\n", this);
[8118303]387
[ac2b598]388 $thread * readyThread = 0p;
[398e8e9]389 for( unsigned int spin_count = 0;; spin_count++ ) {
[92e7631]390 // Try to get the next thread
[8c50aed]391 readyThread = __next_thread( this->cltr );
[75f3522]392
[92e7631]393 // Check if we actually found a thread
394 if( readyThread ) {
[3381ed7]395 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[92e7631]396 /* paranoid */ verifyf( readyThread->state == Ready || readyThread->preempted != __NO_PREEMPTION, "state : %d, preempted %d\n", readyThread->state, readyThread->preempted);
[504a7dc]397 /* paranoid */ verifyf( readyThread->link.next == 0p, "Expected null got %p", readyThread->link.next );
[04b5cef]398 __builtin_prefetch( readyThread->context.SP );
[4e6fb8e]399
[92e7631]400 // We found a thread run it
[8c50aed]401 __run_thread(this, readyThread);
[c81ebf9]402
[3381ed7]403 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[c81ebf9]404 }
[398e8e9]405
406 if(__atomic_load_n(&this->do_terminate, __ATOMIC_SEQ_CST)) break;
407
408 if( !readyThread ) {
[64a7146]409 // Block until a thread is ready
410 __halt(this);
411 }
[c81ebf9]412 }
413
[4069faad]414 __cfadbg_print_safe(runtime_core, "Kernel : core %p stopping\n", this);
[c84e80a]415 }
[8118303]416
[4cedd9f]417 V( this->terminated );
[bdeba0b]418
[28d73c1]419 if(this == mainProcessor) {
[6a490b2]420 // HACK : the coroutine context switch expects this_thread to be set
421 // and it make sense for it to be set in all other cases except here
422 // fake it
423 kernelTLS.this_thread = mainThread;
424 }
[7768b8d]425
[4069faad]426 __cfadbg_print_safe(runtime_core, "Kernel : core %p terminated\n", this);
[c84e80a]427}
428
[5c1a531]429static int * __volatile_errno() __attribute__((noinline));
430static int * __volatile_errno() { asm(""); return &errno; }
431
[14a61b5]432// KERNEL ONLY
[1c273d0]433// runThread runs a thread by context switching
434// from the processor coroutine to the target thread
[ac2b598]435static void __run_thread(processor * this, $thread * thrd_dst) {
436 $coroutine * proc_cor = get_coroutine(this->runner);
[8fcbb4c]437
[14a61b5]438 // Update global state
[e8e457e]439 kernelTLS.this_thread = thrd_dst;
440
[9f575ea]441 // set state of processor coroutine to inactive
442 verify(proc_cor->state == Active);
[ae7be7a]443 proc_cor->state = Blocked;
[e8e457e]444
[9f575ea]445 // Actually run the thread
[3381ed7]446 RUNNING: while(true) {
[ff79d5e]447 thrd_dst->preempted = __NO_PREEMPTION;
448 thrd_dst->state = Active;
[e8e457e]449
[ae66348]450 __cfaabi_dbg_debug_do(
[276ae57e]451 thrd_dst->park_stale = true;
452 thrd_dst->unpark_stale = true;
[ae66348]453 )
[75f3522]454
[3381ed7]455 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[a7b486b]456 /* paranoid */ verify( kernelTLS.this_thread == thrd_dst );
[210b8b3]457 /* 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
458 /* 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
[3381ed7]459
[9f575ea]460 // set context switch to the thread that the processor is executing
461 verify( thrd_dst->context.SP );
[c7a900a]462 __cfactx_switch( &proc_cor->context, &thrd_dst->context );
463 // when __cfactx_switch returns we are back in the processor coroutine
[9f575ea]464
[210b8b3]465 /* 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 );
466 /* 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 );
[a7b486b]467 /* paranoid */ verify( kernelTLS.this_thread == thrd_dst );
[3381ed7]468 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[75f3522]469
[3381ed7]470
471 // We just finished running a thread, there are a few things that could have happened.
472 // 1 - Regular case : the thread has blocked and now one has scheduled it yet.
473 // 2 - Racy case : the thread has blocked but someone has already tried to schedule it.
474 // 4 - Preempted
475 // In case 1, we may have won a race so we can't write to the state again.
476 // In case 2, we lost the race so we now own the thread.
477
478 if(unlikely(thrd_dst->preempted != __NO_PREEMPTION)) {
479 // The thread was preempted, reschedule it and reset the flag
[9b1dcc2]480 __schedule_thread( (__processor_id_t*)this, thrd_dst );
[3381ed7]481 break RUNNING;
482 }
[75f3522]483
[ff79d5e]484 if(unlikely(thrd_dst->state == Halted)) {
485 // The thread has halted, it should never be scheduled/run again
486 // We may need to wake someone up here since
487 unpark( this->destroyer __cfaabi_dbg_ctx2 );
488 this->destroyer = 0p;
489 break RUNNING;
490 }
491
492 /* paranoid */ verify( thrd_dst->state == Active );
493 thrd_dst->state = Blocked;
494
[3381ed7]495 // set state of processor coroutine to active and the thread to inactive
[ff79d5e]496 int old_ticket = __atomic_fetch_sub(&thrd_dst->ticket, 1, __ATOMIC_SEQ_CST);
497 __cfaabi_dbg_debug_do( thrd_dst->park_result = old_ticket; )
498 switch(old_ticket) {
499 case 1:
[3381ed7]500 // This is case 1, the regular case, nothing more is needed
501 break RUNNING;
[ff79d5e]502 case 2:
[3381ed7]503 // This is case 2, the racy case, someone tried to run this thread before it finished blocking
504 // In this case, just run it again.
505 continue RUNNING;
506 default:
507 // This makes no sense, something is wrong abort
[ff79d5e]508 abort();
[3381ed7]509 }
[9f575ea]510 }
[e8e457e]511
[9f575ea]512 // Just before returning to the processor, set the processor coroutine to active
[e8e457e]513 proc_cor->state = Active;
[ae7be7a]514 kernelTLS.this_thread = 0p;
[82c948c]515}
516
[14a61b5]517// KERNEL_ONLY
[b0c7419]518void returnToKernel() {
[3381ed7]519 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[ac2b598]520 $coroutine * proc_cor = get_coroutine(kernelTLS.this_processor->runner);
521 $thread * thrd_src = kernelTLS.this_thread;
[e8e457e]522
[29cb302]523 #if !defined(__CFA_NO_STATISTICS__)
524 struct processor * last_proc = kernelTLS.this_processor;
525 #endif
526
[9f575ea]527 // Run the thread on this processor
528 {
529 int local_errno = *__volatile_errno();
530 #if defined( __i386 ) || defined( __x86_64 )
531 __x87_store;
532 #endif
533 verify( proc_cor->context.SP );
[c7a900a]534 __cfactx_switch( &thrd_src->context, &proc_cor->context );
[9f575ea]535 #if defined( __i386 ) || defined( __x86_64 )
536 __x87_load;
537 #endif
538 *__volatile_errno() = local_errno;
[8fcbb4c]539 }
[deca0f5]540
[29cb302]541 #if !defined(__CFA_NO_STATISTICS__)
542 if(last_proc != kernelTLS.this_processor) {
543 __tls_stats()->ready.threads.migration++;
544 }
545 #endif
546
[3381ed7]547 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[210b8b3]548 /* 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 );
549 /* 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 );
[c84e80a]550}
551
[14a61b5]552// KERNEL_ONLY
[0c92c9f]553// Context invoker for processors
554// This is the entry point for processors (kernel threads)
555// It effectively constructs a coroutine by stealing the pthread stack
[c7a900a]556static void * __invoke_processor(void * arg) {
[8834751]557 #if !defined( __CFA_NO_STATISTICS__ )
558 __stats_t local_stats;
559 __init_stats( &local_stats );
560 kernelTLS.this_stats = &local_stats;
561 #endif
562
[8def349]563 processor * proc = (processor *) arg;
[14a61b5]564 kernelTLS.this_processor = proc;
[1805b1b]565 kernelTLS.this_thread = 0p;
[14a61b5]566 kernelTLS.preemption_state.[enabled, disable_count] = [false, 1];
[8def349]567 // SKULLDUGGERY: We want to create a context for the processor coroutine
568 // which is needed for the 2-step context switch. However, there is no reason
[1c273d0]569 // to waste the perfectly valid stack create by pthread.
[8def349]570 current_stack_info_t info;
[b2f6113]571 __stack_t ctx;
572 info.storage = &ctx;
[094476d]573 (proc->runner){ proc, &info };
[8def349]574
[b2f6113]575 __cfaabi_dbg_print_safe("Coroutine : created stack %p\n", get_coroutine(proc->runner)->stack.storage);
[8fcbb4c]576
[0c92c9f]577 //Set global state
[1805b1b]578 kernelTLS.this_thread = 0p;
[8def349]579
580 //We now have a proper context from which to schedule threads
[4069faad]581 __cfadbg_print_safe(runtime_core, "Kernel : core %p created (%p, %p)\n", proc, &proc->runner, &ctx);
[8def349]582
[1c273d0]583 // SKULLDUGGERY: Since the coroutine doesn't have its own stack, we can't
584 // resume it to start it like it normally would, it will just context switch
585 // back to here. Instead directly call the main since we already are on the
[8def349]586 // appropriate stack.
[094476d]587 get_coroutine(proc->runner)->state = Active;
588 main( proc->runner );
589 get_coroutine(proc->runner)->state = Halted;
[8def349]590
[0c92c9f]591 // Main routine of the core returned, the core is now fully terminated
[4069faad]592 __cfadbg_print_safe(runtime_core, "Kernel : core %p main ended (%p)\n", proc, &proc->runner);
[8def349]593
[8834751]594 #if !defined(__CFA_NO_STATISTICS__)
595 __tally_stats(proc->cltr->stats, &local_stats);
[69fbc61]596 if( 0 != proc->print_stats ) {
597 __print_stats( &local_stats, proc->print_stats, true, proc->name, (void*)proc );
[c34ebf2]598 }
[8834751]599 #endif
600
[1805b1b]601 return 0p;
[c84e80a]602}
603
[e3fea42]604static void Abort( int ret, const char func[] ) {
[1a3040c]605 if ( ret ) { // pthread routines return errno values
[1805b1b]606 abort( "%s : internal error, error(%d) %s.", func, ret, strerror( ret ) );
[27f5f71]607 } // if
[1805b1b]608} // Abort
609
[8c50aed]610void * __create_pthread( pthread_t * pthread, void * (*start)(void *), void * arg ) {
[1805b1b]611 pthread_attr_t attr;
612
613 Abort( pthread_attr_init( &attr ), "pthread_attr_init" ); // initialize attribute
614
[27f5f71]615 size_t stacksize;
[09d4b22]616 // default stack size, normally defined by shell limit
[1a3040c]617 Abort( pthread_attr_getstacksize( &attr, &stacksize ), "pthread_attr_getstacksize" );
[27f5f71]618 assert( stacksize >= PTHREAD_STACK_MIN );
[1a3040c]619
[09d4b22]620 void * stack;
621 __cfaabi_dbg_debug_do(
622 stack = memalign( __page_size, stacksize + __page_size );
623 // pthread has no mechanism to create the guard page in user supplied stack.
624 if ( mprotect( stack, __page_size, PROT_NONE ) == -1 ) {
625 abort( "mprotect : internal error, mprotect failure, error(%d) %s.", errno, strerror( errno ) );
626 } // if
627 );
628 __cfaabi_dbg_no_debug_do(
629 stack = malloc( stacksize );
630 );
[1a3040c]631
[f80f840]632 Abort( pthread_attr_setstack( &attr, stack, stacksize ), "pthread_attr_setstack" );
[27f5f71]633
[1805b1b]634 Abort( pthread_create( pthread, &attr, start, arg ), "pthread_create" );
635 return stack;
[c84e80a]636}
637
[14a61b5]638// KERNEL_ONLY
[8c50aed]639static void __kernel_first_resume( processor * this ) {
[ac2b598]640 $thread * src = mainThread;
641 $coroutine * dst = get_coroutine(this->runner);
[b69ea6b]642
[14a61b5]643 verify( ! kernelTLS.preemption_state.enabled );
[b69ea6b]644
[09f357ec]645 kernelTLS.this_thread->curr_cor = dst;
[b2f6113]646 __stack_prepare( &dst->stack, 65000 );
[c7a900a]647 __cfactx_start(main, dst, this->runner, __cfactx_invoke_coroutine);
[b69ea6b]648
[14a61b5]649 verify( ! kernelTLS.preemption_state.enabled );
[b69ea6b]650
[e8e457e]651 dst->last = &src->self_cor;
652 dst->starter = dst->starter ? dst->starter : &src->self_cor;
[b69ea6b]653
[92e7631]654 // make sure the current state is still correct
655 /* paranoid */ verify(src->state == Ready);
[b69ea6b]656
657 // context switch to specified coroutine
[69a61d2]658 verify( dst->context.SP );
[c7a900a]659 __cfactx_switch( &src->context, &dst->context );
660 // when __cfactx_switch returns we are back in the src coroutine
[b69ea6b]661
[09f357ec]662 mainThread->curr_cor = &mainThread->self_cor;
663
[92e7631]664 // make sure the current state has been update
665 /* paranoid */ verify(src->state == Active);
[b69ea6b]666
[14a61b5]667 verify( ! kernelTLS.preemption_state.enabled );
[b69ea6b]668}
669
[e8e457e]670// KERNEL_ONLY
[8c50aed]671static void __kernel_last_resume( processor * this ) {
[ac2b598]672 $coroutine * src = &mainThread->self_cor;
673 $coroutine * dst = get_coroutine(this->runner);
[e8e457e]674
675 verify( ! kernelTLS.preemption_state.enabled );
676 verify( dst->starter == src );
677 verify( dst->context.SP );
678
[f586539]679 // SKULLDUGGERY in debug the processors check that the
680 // stack is still within the limit of the stack limits after running a thread.
681 // that check doesn't make sense if we context switch to the processor using the
682 // coroutine semantics. Since this is a special case, use the current context
683 // info to populate these fields.
684 __cfaabi_dbg_debug_do(
685 __stack_context_t ctx;
686 CtxGet( ctx );
687 mainThread->context.SP = ctx.SP;
688 mainThread->context.FP = ctx.FP;
689 )
690
[e8e457e]691 // context switch to the processor
[c7a900a]692 __cfactx_switch( &src->context, &dst->context );
[e8e457e]693}
694
[8def349]695//-----------------------------------------------------------------------------
696// Scheduler routines
[14a61b5]697// KERNEL ONLY
[9b1dcc2]698void __schedule_thread( struct __processor_id_t * id, $thread * thrd ) {
[6a490b2]699 /* paranoid */ verify( thrd );
700 /* paranoid */ verify( thrd->state != Halted );
[9f575ea]701 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[3381ed7]702 /* paranoid */ #if defined( __CFA_WITH_VERIFY__ )
[504a7dc]703 /* paranoid */ if( thrd->state == Blocked || thrd->state == Start ) assertf( thrd->preempted == __NO_PREEMPTION,
704 "Error inactive thread marked as preempted, state %d, preemption %d\n", thrd->state, thrd->preempted );
[ff79d5e]705 /* paranoid */ if( thrd->preempted != __NO_PREEMPTION ) assertf(thrd->state == Active,
[504a7dc]706 "Error preempted thread marked as not currently running, state %d, preemption %d\n", thrd->state, thrd->preempted );
[3381ed7]707 /* paranoid */ #endif
[6a490b2]708 /* paranoid */ verifyf( thrd->link.next == 0p, "Expected null got %p", thrd->link.next );
[9f575ea]709
[ae7be7a]710 if (thrd->preempted == __NO_PREEMPTION) thrd->state = Ready;
[6b4cdd3]711
[9b1dcc2]712 ready_schedule_lock ( id );
[504a7dc]713 push( thrd->curr_cluster, thrd );
[b798713]714
[68f36f4]715 #if !defined(__CFA_NO_STATISTICS__)
716 bool woke =
717 #endif
718 __wake_one(id, thrd->curr_cluster);
719
720 #if !defined(__CFA_NO_STATISTICS__)
721 if(woke) __tls_stats()->ready.sleep.wakes++;
722 #endif
[9b1dcc2]723 ready_schedule_unlock( id );
[1c273d0]724
[9f575ea]725 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[db6f06a]726}
727
[14a61b5]728// KERNEL ONLY
[ac2b598]729static $thread * __next_thread(cluster * this) with( *this ) {
[3381ed7]730 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[7768b8d]731
[9b1dcc2]732 ready_schedule_lock ( (__processor_id_t*)kernelTLS.this_processor );
[6a490b2]733 $thread * head = pop( this );
[9b1dcc2]734 ready_schedule_unlock( (__processor_id_t*)kernelTLS.this_processor );
[7768b8d]735
[3381ed7]736 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[db6f06a]737 return head;
[eb2e723]738}
739
[64a7146]740// KERNEL ONLY
741static bool __has_next_thread(cluster * this) with( *this ) {
742 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
743
744 ready_schedule_lock ( (__processor_id_t*)kernelTLS.this_processor );
745 bool not_empty = query( this );
746 ready_schedule_unlock( (__processor_id_t*)kernelTLS.this_processor );
747
748 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
749 return not_empty;
750}
751
[2d8f7b0]752// KERNEL ONLY unpark with out disabling interrupts
[9b1dcc2]753void __unpark( struct __processor_id_t * id, $thread * thrd __cfaabi_dbg_ctx_param2 ) {
[ae66348]754 // record activity
755 __cfaabi_dbg_record_thrd( *thrd, false, caller );
756
[ff79d5e]757 int old_ticket = __atomic_fetch_add(&thrd->ticket, 1, __ATOMIC_SEQ_CST);
758 __cfaabi_dbg_debug_do( thrd->unpark_result = old_ticket; thrd->unpark_state = thrd->state; )
759 switch(old_ticket) {
760 case 1:
[3381ed7]761 // Wake won the race, the thread will reschedule/rerun itself
762 break;
[ff79d5e]763 case 0:
[3381ed7]764 /* paranoid */ verify( ! thrd->preempted != __NO_PREEMPTION );
[ff79d5e]765 /* paranoid */ verify( thrd->state == Blocked );
[0b33412]766
[3381ed7]767 // Wake lost the race,
[9b1dcc2]768 __schedule_thread( id, thrd );
[3381ed7]769 break;
770 default:
771 // This makes no sense, something is wrong abort
772 abort();
[de6319f]773 }
[db6f06a]774}
775
[2d8f7b0]776void unpark( $thread * thrd __cfaabi_dbg_ctx_param2 ) {
777 if( !thrd ) return;
[db6f06a]778
[82ff5845]779 disable_interrupts();
[9b1dcc2]780 __unpark( (__processor_id_t*)kernelTLS.this_processor, thrd __cfaabi_dbg_ctx_fwd2 );
[36982fc]781 enable_interrupts( __cfaabi_dbg_ctx );
[eb2e723]782}
783
[ae66348]784void park( __cfaabi_dbg_ctx_param ) {
[3381ed7]785 /* paranoid */ verify( kernelTLS.preemption_state.enabled );
[82ff5845]786 disable_interrupts();
[3381ed7]787 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
788 /* paranoid */ verify( kernelTLS.this_thread->preempted == __NO_PREEMPTION );
[0b33412]789
[ae66348]790 // record activity
791 __cfaabi_dbg_record_thrd( *kernelTLS.this_thread, true, caller );
[0b33412]792
[82c948c]793 returnToKernel();
[0b33412]794
[3381ed7]795 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[36982fc]796 enable_interrupts( __cfaabi_dbg_ctx );
[3381ed7]797 /* paranoid */ verify( kernelTLS.preemption_state.enabled );
[0c78741]798
799}
[09800e9]800
[3381ed7]801// KERNEL ONLY
[b0c7419]802void __leave_thread() {
[3381ed7]803 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[09800e9]804 returnToKernel();
[b0c7419]805 abort();
[09800e9]806}
807
[14a61b5]808// KERNEL ONLY
[3381ed7]809bool force_yield( __Preemption_Reason reason ) {
810 /* paranoid */ verify( kernelTLS.preemption_state.enabled );
[09800e9]811 disable_interrupts();
[3381ed7]812 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[09800e9]813
[ac2b598]814 $thread * thrd = kernelTLS.this_thread;
[ff79d5e]815 /* paranoid */ verify(thrd->state == Active);
[3381ed7]816
817 // SKULLDUGGERY: It is possible that we are preempting this thread just before
818 // it was going to park itself. If that is the case and it is already using the
819 // intrusive fields then we can't use them to preempt the thread
820 // If that is the case, abandon the preemption.
821 bool preempted = false;
[504a7dc]822 if(thrd->link.next == 0p) {
[3381ed7]823 preempted = true;
824 thrd->preempted = reason;
825 returnToKernel();
[de6319f]826 }
[f2b12406]827
[3381ed7]828 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
829 enable_interrupts_noPoll();
830 /* paranoid */ verify( kernelTLS.preemption_state.enabled );
[f2b12406]831
[3381ed7]832 return preempted;
[f2b12406]833}
834
[fa21ac9]835//=============================================================================================
836// Kernel Setup logic
837//=============================================================================================
[eb2e723]838//-----------------------------------------------------------------------------
839// Kernel boot procedures
[8c50aed]840static void __kernel_startup(void) {
[14a61b5]841 verify( ! kernelTLS.preemption_state.enabled );
[4069faad]842 __cfadbg_print_safe(runtime_core, "Kernel : Starting\n");
[eb2e723]843
[b2f6113]844 __page_size = sysconf( _SC_PAGESIZE );
845
[ea8b2f7]846 __cfa_dbg_global_clusters.list{ __get };
847 __cfa_dbg_global_clusters.lock{};
[de94a60]848
[b388ee81]849 // Initialize the global scheduler lock
850 __scheduler_lock = (__scheduler_RWLock_t*)&storage___scheduler_lock;
851 (*__scheduler_lock){};
852
[de6319f]853 // Initialize the main cluster
854 mainCluster = (cluster *)&storage_mainCluster;
855 (*mainCluster){"Main Cluster"};
856
[4069faad]857 __cfadbg_print_safe(runtime_core, "Kernel : Main cluster ready\n");
[de6319f]858
[eb2e723]859 // Start by initializing the main thread
[1c273d0]860 // SKULLDUGGERY: the mainThread steals the process main thread
[969b3fe]861 // which will then be scheduled by the mainProcessor normally
[ac2b598]862 mainThread = ($thread *)&storage_mainThread;
[8fcbb4c]863 current_stack_info_t info;
[b2f6113]864 info.storage = (__stack_t*)&storage_mainThreadCtx;
[83a071f9]865 (*mainThread){ &info };
[eb2e723]866
[4069faad]867 __cfadbg_print_safe(runtime_core, "Kernel : Main thread ready\n");
[fa21ac9]868
[bd98b58]869
[de6319f]870
871 // Construct the processor context of the main processor
872 void ?{}(processorCtx_t & this, processor * proc) {
873 (this.__cor){ "Processor" };
[1805b1b]874 this.__cor.starter = 0p;
[de6319f]875 this.proc = proc;
876 }
877
878 void ?{}(processor & this) with( this ) {
[28d73c1]879 ( this.idle ){};
880 ( this.terminated ){ 0 };
881 ( this.runner ){};
882 init( this, "Main Processor", *mainCluster );
[de6319f]883 kernel_thread = pthread_self();
[c34ebf2]884
[de6319f]885 runner{ &this };
[4069faad]886 __cfadbg_print_safe(runtime_core, "Kernel : constructed main processor context %p\n", &runner);
[de6319f]887 }
[fa21ac9]888
[969b3fe]889 // Initialize the main processor and the main processor ctx
[eb2e723]890 // (the coroutine that contains the processing control flow)
[969b3fe]891 mainProcessor = (processor *)&storage_mainProcessor;
[de6319f]892 (*mainProcessor){};
[eb2e723]893
[dcb42b8]894 //initialize the global state variables
[14a61b5]895 kernelTLS.this_processor = mainProcessor;
896 kernelTLS.this_thread = mainThread;
[eb2e723]897
[8834751]898 #if !defined( __CFA_NO_STATISTICS__ )
899 kernelTLS.this_stats = (__stats_t *)& storage_mainProcStats;
900 __init_stats( kernelTLS.this_stats );
901 #endif
902
[82ff5845]903 // Enable preemption
904 kernel_start_preemption();
905
[969b3fe]906 // Add the main thread to the ready queue
907 // once resume is called on mainProcessor->runner the mainThread needs to be scheduled like any normal thread
[9b1dcc2]908 __schedule_thread((__processor_id_t *)mainProcessor, mainThread);
[969b3fe]909
910 // SKULLDUGGERY: Force a context switch to the main processor to set the main thread's context to the current UNIX
[c7a900a]911 // context. Hence, the main thread does not begin through __cfactx_invoke_thread, like all other threads. The trick here is that
[1c273d0]912 // mainThread is on the ready queue when this call is made.
[8c50aed]913 __kernel_first_resume( kernelTLS.this_processor );
[dcb42b8]914
915
916 // THE SYSTEM IS NOW COMPLETELY RUNNING
[f6660520]917
918
919 // Now that the system is up, finish creating systems that need threading
920 __kernel_io_finish_start( *mainCluster );
921
922
923 __cfadbg_print_safe(runtime_core, "Kernel : Started\n--------------------------------------------------\n\n");
[82ff5845]924
[14a61b5]925 verify( ! kernelTLS.preemption_state.enabled );
[36982fc]926 enable_interrupts( __cfaabi_dbg_ctx );
[afd550c]927 verify( TL_GET( preemption_state.enabled ) );
[eb2e723]928}
929
[8c50aed]930static void __kernel_shutdown(void) {
[f6660520]931 //Before we start shutting things down, wait for systems that need threading to shutdown
932 __kernel_io_prepare_stop( *mainCluster );
[eb2e723]933
[92e7631]934 /* paranoid */ verify( TL_GET( preemption_state.enabled ) );
[4e6fb8e]935 disable_interrupts();
[92e7631]936 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
[4e6fb8e]937
[f6660520]938 __cfadbg_print_safe(runtime_core, "\n--------------------------------------------------\nKernel : Shutting down\n");
[4e6fb8e]939
[969b3fe]940 // SKULLDUGGERY: Notify the mainProcessor it needs to terminates.
[dcb42b8]941 // When its coroutine terminates, it return control to the mainThread
942 // which is currently here
[ea8b2f7]943 __atomic_store_n(&mainProcessor->do_terminate, true, __ATOMIC_RELEASE);
[8c50aed]944 __kernel_last_resume( kernelTLS.this_processor );
[ea8b2f7]945 mainThread->self_cor.state = Halted;
[eb2e723]946
[dcb42b8]947 // THE SYSTEM IS NOW COMPLETELY STOPPED
[eb2e723]948
[82ff5845]949 // Disable preemption
950 kernel_stop_preemption();
951
[969b3fe]952 // Destroy the main processor and its context in reverse order of construction
[dcb42b8]953 // These were manually constructed so we need manually destroy them
[c66f6cb]954 void ^?{}(processor & this) with( this ){
[28d73c1]955 deinit( this );
956
[c66f6cb]957 /* paranoid */ verify( this.do_terminate == true );
[b798713]958 __cfaabi_dbg_print_safe("Kernel : destroyed main processor context %p\n", &runner);
959 }
960
[7768b8d]961 ^(*mainProcessor){};
[eb2e723]962
[dcb42b8]963 // Final step, destroy the main thread since it is no longer needed
[6a490b2]964
[dcb42b8]965 // Since we provided a stack to this taxk it will not destroy anything
[210b8b3]966 /* paranoid */ verify(mainThread->self_cor.stack.storage == (__stack_t*)(((uintptr_t)&storage_mainThreadCtx)| 0x1));
[7768b8d]967 ^(*mainThread){};
968
969 ^(*mainCluster){};
[eb2e723]970
[b388ee81]971 ^(*__scheduler_lock){};
972
[ea8b2f7]973 ^(__cfa_dbg_global_clusters.list){};
974 ^(__cfa_dbg_global_clusters.lock){};
[a1a17a74]975
[4069faad]976 __cfadbg_print_safe(runtime_core, "Kernel : Shutdown complete\n");
[9d944b2]977}
978
[14a61b5]979//=============================================================================================
[92e7631]980// Kernel Idle Sleep
[14a61b5]981//=============================================================================================
[64a7146]982// Wake a thread from the front if there are any
983static bool __wake_one(struct __processor_id_t * id, cluster * this) {
984 /* paranoid */ verify( ready_schedule_islocked( id ) );
[14a61b5]985
[64a7146]986 // Check if there is a sleeping processor
987 processor * p = pop(this->idles);
[14a61b5]988
[64a7146]989 // If no one is sleeping, we are done
990 if( 0p == p ) return false;
[14a61b5]991
[64a7146]992 // We found a processor, wake it up
993 post( p->idle );
[14a61b5]994
[64a7146]995 return true;
996}
[14a61b5]997
[64a7146]998// Unconditionnaly wake a thread
999static bool __wake_proc(processor * this) {
1000 __cfadbg_print_safe(runtime_core, "Kernel : waking Processor %p\n", this);
[14a61b5]1001
[64a7146]1002 disable_interrupts();
1003 /* paranoid */ verify( ! kernelTLS.preemption_state.enabled );
1004 bool ret = post( this->idle );
1005 enable_interrupts( __cfaabi_dbg_ctx );
[92e7631]1006
[64a7146]1007 return ret;
[92e7631]1008}
1009
[64a7146]1010static void __halt(processor * this) with( *this ) {
1011 if( do_terminate ) return;
[8e16177]1012
[68f36f4]1013 #if !defined(__CFA_NO_STATISTICS__)
1014 __tls_stats()->ready.sleep.halts++;
1015 #endif
[64a7146]1016 // Push self to queue
1017 push(cltr->idles, *this);
[8834751]1018
[64a7146]1019 // Makre sure we don't miss a thread
1020 if( __has_next_thread(cltr) ) {
1021 // A thread was posted, make sure a processor is woken up
1022 struct __processor_id_t *id = (struct __processor_id_t *) this;
1023 ready_schedule_lock ( id );
1024 __wake_one( id, cltr );
1025 ready_schedule_unlock( id );
[68f36f4]1026 #if !defined(__CFA_NO_STATISTICS__)
1027 __tls_stats()->ready.sleep.cancels++;
1028 #endif
[64a7146]1029 }
[8e16177]1030
[c34ebf2]1031 #if !defined(__CFA_NO_STATISTICS__)
1032 if(this->print_halts) {
[f2b18d01]1033 __cfaabi_bits_print_safe( STDOUT_FILENO, "PH:%d - %lld 0\n", this->id, rdtscl());
[c34ebf2]1034 }
1035 #endif
1036
[64a7146]1037 wait( idle );
[c34ebf2]1038
1039 #if !defined(__CFA_NO_STATISTICS__)
1040 if(this->print_halts) {
[f2b18d01]1041 __cfaabi_bits_print_safe( STDOUT_FILENO, "PH:%d - %lld 1\n", this->id, rdtscl());
[c34ebf2]1042 }
1043 #endif
[6b4cdd3]1044}
1045
[dbe9b08]1046//=============================================================================================
1047// Unexpected Terminating logic
1048//=============================================================================================
[ea7d2b0]1049static __spinlock_t kernel_abort_lock;
[9d944b2]1050static bool kernel_abort_called = false;
1051
[afd550c]1052void * kernel_abort(void) __attribute__ ((__nothrow__)) {
[9d944b2]1053 // abort cannot be recursively entered by the same or different processors because all signal handlers return when
1054 // the globalAbort flag is true.
[36982fc]1055 lock( kernel_abort_lock __cfaabi_dbg_ctx2 );
[9d944b2]1056
1057 // first task to abort ?
[de94a60]1058 if ( kernel_abort_called ) { // not first task to abort ?
[ea7d2b0]1059 unlock( kernel_abort_lock );
[1c273d0]1060
[9d944b2]1061 sigset_t mask;
1062 sigemptyset( &mask );
[de94a60]1063 sigaddset( &mask, SIGALRM ); // block SIGALRM signals
[8a13c47]1064 sigaddset( &mask, SIGUSR1 ); // block SIGALRM signals
1065 sigsuspend( &mask ); // block the processor to prevent further damage during abort
1066 _exit( EXIT_FAILURE ); // if processor unblocks before it is killed, terminate it
[de94a60]1067 }
1068 else {
1069 kernel_abort_called = true;
1070 unlock( kernel_abort_lock );
[9d944b2]1071 }
1072
[14a61b5]1073 return kernelTLS.this_thread;
[9d944b2]1074}
1075
1076void kernel_abort_msg( void * kernel_data, char * abort_text, int abort_text_size ) {
[b81fd95]1077 $thread * thrd = ( $thread * ) kernel_data;
[9d944b2]1078
[de94a60]1079 if(thrd) {
1080 int len = snprintf( abort_text, abort_text_size, "Error occurred while executing thread %.256s (%p)", thrd->self_cor.name, thrd );
[1c40091]1081 __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
[de94a60]1082
[212c2187]1083 if ( &thrd->self_cor != thrd->curr_cor ) {
1084 len = snprintf( abort_text, abort_text_size, " in coroutine %.256s (%p).\n", thrd->curr_cor->name, thrd->curr_cor );
[1c40091]1085 __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
[de94a60]1086 }
1087 else {
[1c40091]1088 __cfaabi_bits_write( STDERR_FILENO, ".\n", 2 );
[de94a60]1089 }
[1c273d0]1090 }
[9d944b2]1091 else {
[de94a60]1092 int len = snprintf( abort_text, abort_text_size, "Error occurred outside of any thread.\n" );
[1c40091]1093 __cfaabi_bits_write( STDERR_FILENO, abort_text, len );
[9d944b2]1094 }
1095}
1096
[2b8bc41]1097int kernel_abort_lastframe( void ) __attribute__ ((__nothrow__)) {
[14a61b5]1098 return get_coroutine(kernelTLS.this_thread) == get_coroutine(mainThread) ? 4 : 2;
[2b8bc41]1099}
1100
[de94a60]1101static __spinlock_t kernel_debug_lock;
1102
[9d944b2]1103extern "C" {
[1c40091]1104 void __cfaabi_bits_acquire() {
[36982fc]1105 lock( kernel_debug_lock __cfaabi_dbg_ctx2 );
[9d944b2]1106 }
1107
[1c40091]1108 void __cfaabi_bits_release() {
[ea7d2b0]1109 unlock( kernel_debug_lock );
[9d944b2]1110 }
[8118303]1111}
1112
[fa21ac9]1113//=============================================================================================
1114// Kernel Utilities
1115//=============================================================================================
[bd98b58]1116//-----------------------------------------------------------------------------
1117// Locks
[242a902]1118void ?{}( semaphore & this, int count = 1 ) {
1119 (this.lock){};
1120 this.count = count;
1121 (this.waiting){};
[db6f06a]1122}
[242a902]1123void ^?{}(semaphore & this) {}
[db6f06a]1124
[71c8b7e]1125bool P(semaphore & this) with( this ){
[65deb18]1126 lock( lock __cfaabi_dbg_ctx2 );
1127 count -= 1;
1128 if ( count < 0 ) {
[bdeba0b]1129 // queue current task
[14a61b5]1130 append( waiting, kernelTLS.this_thread );
[bdeba0b]1131
1132 // atomically release spin lock and block
[3381ed7]1133 unlock( lock );
[ae66348]1134 park( __cfaabi_dbg_ctx );
[71c8b7e]1135 return true;
[8def349]1136 }
[4e6fb8e]1137 else {
[65deb18]1138 unlock( lock );
[71c8b7e]1139 return false;
[4e6fb8e]1140 }
[bd98b58]1141}
1142
[f0ce5f4]1143bool V(semaphore & this) with( this ) {
[ac2b598]1144 $thread * thrd = 0p;
[65deb18]1145 lock( lock __cfaabi_dbg_ctx2 );
1146 count += 1;
1147 if ( count <= 0 ) {
[bdeba0b]1148 // remove task at head of waiting list
[65deb18]1149 thrd = pop_head( waiting );
[bd98b58]1150 }
[bdeba0b]1151
[65deb18]1152 unlock( lock );
[bdeba0b]1153
1154 // make new owner
[ae66348]1155 unpark( thrd __cfaabi_dbg_ctx2 );
[f0ce5f4]1156
[d384787]1157 return thrd != 0p;
1158}
1159
1160bool V(semaphore & this, unsigned diff) with( this ) {
1161 $thread * thrd = 0p;
1162 lock( lock __cfaabi_dbg_ctx2 );
1163 int release = max(-count, (int)diff);
1164 count += diff;
1165 for(release) {
1166 unpark( pop_head( waiting ) __cfaabi_dbg_ctx2 );
1167 }
1168
1169 unlock( lock );
1170
[f0ce5f4]1171 return thrd != 0p;
[bd98b58]1172}
1173
[f7d6bb0]1174//-----------------------------------------------------------------------------
[de94a60]1175// Global Queues
1176void doregister( cluster & cltr ) {
[ea8b2f7]1177 lock ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2);
1178 push_front( __cfa_dbg_global_clusters.list, cltr );
1179 unlock ( __cfa_dbg_global_clusters.lock );
[de94a60]1180}
[f7d6bb0]1181
[de94a60]1182void unregister( cluster & cltr ) {
[ea8b2f7]1183 lock ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2);
1184 remove( __cfa_dbg_global_clusters.list, cltr );
1185 unlock( __cfa_dbg_global_clusters.lock );
[de94a60]1186}
[f7d6bb0]1187
[ac2b598]1188void doregister( cluster * cltr, $thread & thrd ) {
[a1a17a74]1189 lock (cltr->thread_list_lock __cfaabi_dbg_ctx2);
[d4e68a6]1190 cltr->nthreads += 1;
[a1a17a74]1191 push_front(cltr->threads, thrd);
1192 unlock (cltr->thread_list_lock);
1193}
1194
[ac2b598]1195void unregister( cluster * cltr, $thread & thrd ) {
[a1a17a74]1196 lock (cltr->thread_list_lock __cfaabi_dbg_ctx2);
1197 remove(cltr->threads, thrd );
[d4e68a6]1198 cltr->nthreads -= 1;
[a1a17a74]1199 unlock(cltr->thread_list_lock);
1200}
[9181f1d]1201
[de94a60]1202//-----------------------------------------------------------------------------
1203// Debug
1204__cfaabi_dbg_debug_do(
[1997b4e]1205 extern "C" {
[ae66348]1206 void __cfaabi_dbg_record_lock(__spinlock_t & this, const char prev_name[]) {
[1997b4e]1207 this.prev_name = prev_name;
1208 this.prev_thrd = kernelTLS.this_thread;
1209 }
[ae66348]1210
1211 void __cfaabi_dbg_record_thrd($thread & this, bool park, const char prev_name[]) {
1212 if(park) {
[f0ce5f4]1213 this.park_caller = prev_name;
1214 this.park_stale = false;
[ae66348]1215 }
1216 else {
[f0ce5f4]1217 this.unpark_caller = prev_name;
1218 this.unpark_stale = false;
[ae66348]1219 }
1220 }
[9181f1d]1221 }
[f7d6bb0]1222)
[2026bb6]1223
1224//-----------------------------------------------------------------------------
1225// Debug
[8c50aed]1226bool threading_enabled(void) __attribute__((const)) {
[2026bb6]1227 return true;
1228}
[c34ebf2]1229
1230//-----------------------------------------------------------------------------
1231// Statistics
1232#if !defined(__CFA_NO_STATISTICS__)
1233 void print_halts( processor & this ) {
1234 this.print_halts = true;
1235 }
1236#endif
[8118303]1237// Local Variables: //
1238// mode: c //
1239// tab-width: 4 //
1240// End: //
Note: See TracBrowser for help on using the repository browser.