source: libcfa/src/concurrency/kernel.cfa@ 04b5cef

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 04b5cef was 04b5cef, checked in by Thierry Delisle <tdelisle@…>, 5 years ago

Added BIAS option to ready_queue
Added yield test for LibFibre
Fixed some alignments and minor optimizations

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