source: libcfa/src/concurrency/kernel.cfa@ 564148f

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 564148f was 29cb302, checked in by Thierry Delisle <tdelisle@…>, 5 years ago

cfa stats now count number of migrations

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