source: libcfa/src/concurrency/kernel/startup.cfa@ 1afd9ccb

ADT ast-experimental
Last change on this file since 1afd9ccb was a0a949c, checked in by Peter A. Buhr <pabuhr@…>, 3 years ago

formatting, remove unnecessary #include files and code

  • Property mode set to 100644
File size: 27.3 KB
RevLine 
[e660761]1//
2// Cforall Version 1.0.0 Copyright (C) 2020 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/startup.cfa --
8//
9// Author : Thierry Delisle
10// Created On : Thu Jul 30 15:12:54 2020
11// Last Modified By :
12// Last Modified On :
13// Update Count :
14//
15
16#define __cforall_thread__
17
[8b74fa7]18// #define __CFA_DEBUG_PRINT_RUNTIME_CORE__
19
[e660761]20// C Includes
[56bb2e1]21#include <errno.h> // errno
[f558b5f]22#include <signal.h>
[56bb2e1]23#include <string.h> // strerror
24#include <unistd.h>
25#include <limits.h> // PTHREAD_STACK_MIN
[e660761]26extern "C" {
[56bb2e1]27 #include <sys/eventfd.h> // eventfd
28 #include <sys/mman.h> // mprotect
29 #include <sys/resource.h> // getrlimit
[e660761]30}
31
32// CFA Includes
[708ae38]33#include "kernel/private.hfa"
[22226e4]34#include "iofwd.hfa"
[a0a949c]35#include "startup.hfa" // STARTUP_PRIORITY_XXX
[145dcd5]36#include "limits.hfa"
[bfcf6b9]37#include "math.hfa"
[d2ad151]38#include "bits/random.hfa" // prng
[e660761]39
[97229d6]40#define CFA_PROCESSOR_USE_MMAP 0
41
[e660761]42//-----------------------------------------------------------------------------
43// Some assembly required
44#if defined( __i386 )
[88cafe7]45 #define CtxGet( ctx ) __asm__ volatile ( \
46 "movl %%esp,%0\n" \
47 "movl %%ebp,%1\n" \
48 : "=rm" (ctx.SP), \
49 "=rm" (ctx.FP) \
50 )
[e660761]51#elif defined( __x86_64 )
[88cafe7]52 #define CtxGet( ctx ) __asm__ volatile ( \
53 "movq %%rsp,%0\n" \
54 "movq %%rbp,%1\n" \
55 : "=rm" (ctx.SP), \
56 "=rm" (ctx.FP) \
57 )
58#elif defined( __aarch64__ )
59 #define CtxGet( ctx ) __asm__ volatile ( \
60 "mov %0, sp\n" \
61 "mov %1, fp\n" \
62 : "=rm" (ctx.SP), \
63 "=rm" (ctx.FP) \
64 )
[e660761]65#else
66 #error unknown hardware architecture
67#endif
68
69//-----------------------------------------------------------------------------
70// Start and stop routine for the kernel, declared first to make sure they run first
71static void __kernel_startup (void) __attribute__(( constructor( STARTUP_PRIORITY_KERNEL ) ));
72static void __kernel_shutdown(void) __attribute__(( destructor ( STARTUP_PRIORITY_KERNEL ) ));
73
74//-----------------------------------------------------------------------------
75// Static Forward Declarations
76struct current_stack_info_t;
77
78static void * __invoke_processor(void * arg);
79static void __kernel_first_resume( processor * this );
80static void __kernel_last_resume ( processor * this );
[e84ab3d]81static void init(processor & this, const char name[], cluster & _cltr, thread$ * initT);
[e660761]82static void deinit(processor & this);
83static void doregister( struct cluster & cltr );
84static void unregister( struct cluster & cltr );
[c993b15]85static void register_tls( processor * this );
86static void unregister_tls( processor * this );
[e84ab3d]87static void ?{}( coroutine$ & this, current_stack_info_t * info);
88static void ?{}( thread$ & this, current_stack_info_t * info);
[e660761]89static void ?{}(processorCtx_t & this) {}
90static void ?{}(processorCtx_t & this, processor * proc, current_stack_info_t * info);
91
[f2384c9a]92#if defined(__CFA_WITH_VERIFY__)
93 static bool verify_fwd_bck_rng(void);
94#endif
95
[e660761]96//-----------------------------------------------------------------------------
97// Forward Declarations for other modules
98extern void __kernel_alarm_startup(void);
99extern void __kernel_alarm_shutdown(void);
[22226e4]100extern void __cfa_io_start( processor * );
101extern void __cfa_io_stop ( processor * );
[e660761]102
103//-----------------------------------------------------------------------------
104// Other Forward Declarations
[1eb239e4]105extern void __wake_proc(processor *);
[7dd98b6]106extern int cfa_main_returned; // from interpose.cfa
[dd46fd3]107size_t __global_random_prime = 4_294_967_291u;
[d2ad151]108bool __global_random_mask = false;
[e660761]109
110//-----------------------------------------------------------------------------
111// Kernel storage
112KERNEL_STORAGE(cluster, mainCluster);
113KERNEL_STORAGE(processor, mainProcessor);
[e84ab3d]114KERNEL_STORAGE(thread$, mainThread);
[e660761]115KERNEL_STORAGE(__stack_t, mainThreadCtx);
116#if !defined(__CFA_NO_STATISTICS__)
117KERNEL_STORAGE(__stats_t, mainProcStats);
118#endif
119
[c18bf9e]120cluster * mainCluster libcfa_public;
[e660761]121processor * mainProcessor;
[e84ab3d]122thread$ * mainThread;
[e660761]123
124extern "C" {
125 struct { __dllist_t(cluster) list; __spinlock_t lock; } __cfa_dbg_global_clusters;
126}
127
[a182ad5]128extern size_t __page_size;
129extern int __map_prot;
130
[e660761]131//-----------------------------------------------------------------------------
132// Global state
[1bcbf02]133__thread struct KernelThreadData __cfaabi_tls __attribute__ ((tls_model ( "initial-exec" ))) @= {
[dd46fd3]134 .this_thread : NULL, // cannot use 0p
135 .this_processor : NULL,
136 .sched_lock : false,
137 .preemption_state : { .disable_count : 1, .enabled : false, .in_progress : false },
138 // random_state uninitialized
139 .ready_rng : { .fwd_seed : 0, .bck_seed : 0 },
140 .this_stats : NULL,
[c993b15]141 #ifdef __CFA_WITH_VERIFY__
[dd46fd3]142 .in_sched_lock : false,
143 .sched_id : 0,
[c993b15]144 #endif
[e660761]145};
146
[cd3fc46]147__scheduler_RWLock_t __scheduler_lock @= { 0 };
148
[e660761]149//-----------------------------------------------------------------------------
150// Struct to steal stack
151struct current_stack_info_t {
152 __stack_t * storage; // pointer to stack object
153 void * base; // base of stack
154 void * limit; // stack grows towards stack limit
155 void * context; // address of cfa_context_t
156};
157
[c18bf9e]158static void ?{}( current_stack_info_t & this ) {
[e660761]159 __stack_context_t ctx;
160 CtxGet( ctx );
161 this.base = ctx.FP;
162
163 rlimit r;
164 getrlimit( RLIMIT_STACK, &r);
165 size_t size = r.rlim_cur;
166
167 this.limit = (void *)(((intptr_t)this.base) - size);
168 this.context = &storage_mainThreadCtx;
169}
170
171
[116a2ea]172extern void heapManagerCtor();
173extern void heapManagerDtor();
174
[e660761]175//=============================================================================================
176// Kernel Setup logic
177//=============================================================================================
178//-----------------------------------------------------------------------------
179// Kernel boot procedures
180static void __kernel_startup(void) {
[8fc652e0]181 /* paranoid */ verify( ! __preemption_enabled() );
[e660761]182 __cfadbg_print_safe(runtime_core, "Kernel : Starting\n");
183
184 __cfa_dbg_global_clusters.list{ __get };
185 __cfa_dbg_global_clusters.lock{};
186
[f2384c9a]187 /* paranoid */ verify( verify_fwd_bck_rng() );
188
[e660761]189 // Initialize the global scheduler lock
[cd3fc46]190 // __scheduler_lock = (__scheduler_RWLock_t*)&storage___scheduler_lock;
191 (__scheduler_lock){};
[e660761]192
193 // Initialize the main cluster
194 mainCluster = (cluster *)&storage_mainCluster;
195 (*mainCluster){"Main Cluster", 0};
196
197 __cfadbg_print_safe(runtime_core, "Kernel : Main cluster ready\n");
198
199 // Construct the processor context of the main processor
200 void ?{}(processorCtx_t & this, processor * proc) {
[c18bf9e]201 (this.self){ "Processor" };
202 this.self.starter = 0p;
[e660761]203 this.proc = proc;
204 }
205
206 void ?{}(processor & this) with( this ) {
[454f478]207 ( this.terminated ){};
[e660761]208 ( this.runner ){};
[a5e7233]209 init( this, "Main Processor", *mainCluster, 0p );
[95dab9e]210 kernel_thread = __cfaabi_pthread_self();
[e660761]211
212 runner{ &this };
213 __cfadbg_print_safe(runtime_core, "Kernel : constructed main processor context %p\n", &runner);
214 }
215
216 // Initialize the main processor and the main processor ctx
217 // (the coroutine that contains the processing control flow)
218 mainProcessor = (processor *)&storage_mainProcessor;
219 (*mainProcessor){};
220
[22226e4]221 __cfa_io_start( mainProcessor );
[78a580d]222 register_tls( mainProcessor );
[c993b15]223
[24e321c]224 // Start by initializing the main thread
225 // SKULLDUGGERY: the mainThread steals the process main thread
226 // which will then be scheduled by the mainProcessor normally
227 mainThread = (thread$ *)&storage_mainThread;
228 current_stack_info_t info;
229 info.storage = (__stack_t*)&storage_mainThreadCtx;
230 (*mainThread){ &info };
231
232 __cfadbg_print_safe(runtime_core, "Kernel : Main thread ready\n");
233
[e660761]234 //initialize the global state variables
[8fc652e0]235 __cfaabi_tls.this_processor = mainProcessor;
236 __cfaabi_tls.this_thread = mainThread;
[e660761]237
238 #if !defined( __CFA_NO_STATISTICS__ )
[8fc652e0]239 __cfaabi_tls.this_stats = (__stats_t *)& storage_mainProcStats;
240 __init_stats( __cfaabi_tls.this_stats );
[e660761]241 #endif
[a67c5b6]242 mainProcessor->local_data = &__cfaabi_tls;
[e660761]243
244 // Enable preemption
245 __kernel_alarm_startup();
246
247 // Add the main thread to the ready queue
248 // once resume is called on mainProcessor->runner the mainThread needs to be scheduled like any normal thread
[24e321c]249 schedule_thread$(mainThread, UNPARK_LOCAL);
[e660761]250
251 // SKULLDUGGERY: Force a context switch to the main processor to set the main thread's context to the current UNIX
252 // context. Hence, the main thread does not begin through __cfactx_invoke_thread, like all other threads. The trick here is that
253 // mainThread is on the ready queue when this call is made.
[8fc652e0]254 __kernel_first_resume( __cfaabi_tls.this_processor );
[e660761]255
256
257 // THE SYSTEM IS NOW COMPLETELY RUNNING
258
259 __cfadbg_print_safe(runtime_core, "Kernel : Started\n--------------------------------------------------\n\n");
260
[8fc652e0]261 /* paranoid */ verify( ! __preemption_enabled() );
[a3821fa]262 enable_interrupts();
[8fc652e0]263 /* paranoid */ verify( __preemption_enabled() );
264
[e660761]265}
266
[20be782]267extern "C"{
268 void pthread_delete_kernel_threads_();
269}
270
271
[e660761]272static void __kernel_shutdown(void) {
[7dd98b6]273 if(!cfa_main_returned) return;
[20be782]274
275 //delete kernel threads for pthread_concurrency
276 pthread_delete_kernel_threads_();
277
[8fc652e0]278 /* paranoid */ verify( __preemption_enabled() );
[e660761]279 disable_interrupts();
[8fc652e0]280 /* paranoid */ verify( ! __preemption_enabled() );
[e660761]281
282 __cfadbg_print_safe(runtime_core, "\n--------------------------------------------------\nKernel : Shutting down\n");
283
284 // SKULLDUGGERY: Notify the mainProcessor it needs to terminates.
285 // When its coroutine terminates, it return control to the mainThread
286 // which is currently here
[7d0ebd0]287 /* paranoid */ verify( !__atomic_load_n(&mainProcessor->do_terminate, __ATOMIC_ACQUIRE) );
[e660761]288 __atomic_store_n(&mainProcessor->do_terminate, true, __ATOMIC_RELEASE);
[7d0ebd0]289 __wake_proc( mainProcessor );
[8fc652e0]290 __kernel_last_resume( __cfaabi_tls.this_processor );
[e660761]291 mainThread->self_cor.state = Halted;
292
293 // THE SYSTEM IS NOW COMPLETELY STOPPED
294
295 // Disable preemption
296 __kernel_alarm_shutdown();
297
[a5a01faa]298 #if !defined( __CFA_NO_STATISTICS__ )
299 __stats_t * st = (__stats_t *)& storage_mainProcStats;
300 __tally_stats(mainCluster->stats, st);
301 if( 0 != mainProcessor->print_stats ) {
302 __print_stats( st, mainProcessor->print_stats, "Processor ", mainProcessor->name, (void*)mainProcessor );
303 }
[73f4d08]304 #if defined(CFA_STATS_ARRAY)
305 __flush_stat( st, "Processor", mainProcessor );
306 #endif
[a5a01faa]307 #endif
308
[a67c5b6]309 mainProcessor->local_data = 0p;
310
[c993b15]311 unregister_tls( mainProcessor );
[78a580d]312 __cfa_io_stop( mainProcessor );
[c993b15]313
[e660761]314 // Destroy the main processor and its context in reverse order of construction
315 // These were manually constructed so we need manually destroy them
316 void ^?{}(processor & this) with( this ){
317 deinit( this );
318
319 /* paranoid */ verify( this.do_terminate == true );
[8b74fa7]320 __cfadbg_print_safe(runtime_core, "Kernel : destroyed main processor context %p\n", &runner);
[e660761]321 }
322
323 ^(*mainProcessor){};
324
325 // Final step, destroy the main thread since it is no longer needed
326
327 // Since we provided a stack to this taxk it will not destroy anything
328 /* paranoid */ verify(mainThread->self_cor.stack.storage == (__stack_t*)(((uintptr_t)&storage_mainThreadCtx)| 0x1));
329 ^(*mainThread){};
330
331 ^(*mainCluster){};
332
[cd3fc46]333 ^(__scheduler_lock){};
[e660761]334
335 ^(__cfa_dbg_global_clusters.list){};
336 ^(__cfa_dbg_global_clusters.lock){};
337
338 __cfadbg_print_safe(runtime_core, "Kernel : Shutdown complete\n");
339}
340
341//=============================================================================================
342// Kernel Initial Scheduling logic
343//=============================================================================================
344
345// Context invoker for processors
346// This is the entry point for processors (kernel threads) *except* for the main processor
347// It effectively constructs a coroutine by stealing the pthread stack
348static void * __invoke_processor(void * arg) {
349 #if !defined( __CFA_NO_STATISTICS__ )
350 __stats_t local_stats;
351 __init_stats( &local_stats );
[8fc652e0]352 __cfaabi_tls.this_stats = &local_stats;
[e660761]353 #endif
354
355 processor * proc = (processor *) arg;
[8fc652e0]356 __cfaabi_tls.this_processor = proc;
357 __cfaabi_tls.this_thread = 0p;
358 __cfaabi_tls.preemption_state.[enabled, disable_count] = [false, 1];
[a67c5b6]359 proc->local_data = &__cfaabi_tls;
[c993b15]360
[116a2ea]361 heapManagerCtor(); // initialize heap
362
[22226e4]363 __cfa_io_start( proc );
[78a580d]364 register_tls( proc );
[22226e4]365
[e660761]366 // SKULLDUGGERY: We want to create a context for the processor coroutine
367 // which is needed for the 2-step context switch. However, there is no reason
368 // to waste the perfectly valid stack create by pthread.
369 current_stack_info_t info;
370 __stack_t ctx;
371 info.storage = &ctx;
372 (proc->runner){ proc, &info };
373
[8b74fa7]374 __cfadbg_print_safe(runtime_core, "Coroutine : created stack %p\n", get_coroutine(proc->runner)->stack.storage);
[e660761]375
376 //Set global state
[8fc652e0]377 __cfaabi_tls.this_thread = 0p;
[e660761]378
379 //We now have a proper context from which to schedule threads
380 __cfadbg_print_safe(runtime_core, "Kernel : core %p created (%p, %p)\n", proc, &proc->runner, &ctx);
381
382 // SKULLDUGGERY: Since the coroutine doesn't have its own stack, we can't
383 // resume it to start it like it normally would, it will just context switch
384 // back to here. Instead directly call the main since we already are on the
385 // appropriate stack.
386 get_coroutine(proc->runner)->state = Active;
387 main( proc->runner );
388 get_coroutine(proc->runner)->state = Halted;
389
390 // Main routine of the core returned, the core is now fully terminated
391 __cfadbg_print_safe(runtime_core, "Kernel : core %p main ended (%p)\n", proc, &proc->runner);
392
393 #if !defined(__CFA_NO_STATISTICS__)
394 __tally_stats(proc->cltr->stats, &local_stats);
395 if( 0 != proc->print_stats ) {
[1b033b8]396 __print_stats( &local_stats, proc->print_stats, "Processor ", proc->name, (void*)proc );
[e660761]397 }
[73f4d08]398 #if defined(CFA_STATS_ARRAY)
399 __flush_stat( &local_stats, "Processor", proc );
400 #endif
[e660761]401 #endif
402
[a67c5b6]403 proc->local_data = 0p;
404
[c993b15]405 unregister_tls( proc );
[78a580d]406 __cfa_io_stop( proc );
[c993b15]407
[116a2ea]408 heapManagerDtor(); // de-initialize heap
409
[e660761]410 return 0p;
411}
412
413static void __kernel_first_resume( processor * this ) {
[e84ab3d]414 thread$ * src = mainThread;
415 coroutine$ * dst = get_coroutine(this->runner);
[e660761]416
[8fc652e0]417 /* paranoid */ verify( ! __preemption_enabled() );
[e660761]418
[8fc652e0]419 __cfaabi_tls.this_thread->curr_cor = dst;
[eaf269d]420 __stack_prepare( &dst->stack, DEFAULT_STACK_SIZE );
[e660761]421 __cfactx_start(main, dst, this->runner, __cfactx_invoke_coroutine);
422
[8fc652e0]423 /* paranoid */ verify( ! __preemption_enabled() );
[e660761]424
425 dst->last = &src->self_cor;
426 dst->starter = dst->starter ? dst->starter : &src->self_cor;
427
428 // make sure the current state is still correct
429 /* paranoid */ verify(src->state == Ready);
[ab5baab]430 src->corctx_flag = true;
[e660761]431
432 // context switch to specified coroutine
433 verify( dst->context.SP );
434 __cfactx_switch( &src->context, &dst->context );
435 // when __cfactx_switch returns we are back in the src coroutine
436
437 mainThread->curr_cor = &mainThread->self_cor;
438
439 // make sure the current state has been update
440 /* paranoid */ verify(src->state == Active);
441
[8fc652e0]442 /* paranoid */ verify( ! __preemption_enabled() );
[e660761]443}
444
445// KERNEL_ONLY
446static void __kernel_last_resume( processor * this ) {
[e84ab3d]447 coroutine$ * src = &mainThread->self_cor;
448 coroutine$ * dst = get_coroutine(this->runner);
[e660761]449
[8fc652e0]450 /* paranoid */ verify( ! __preemption_enabled() );
451 /* paranoid */ verify( dst->starter == src );
452 /* paranoid */ verify( dst->context.SP );
[e660761]453
454 // SKULLDUGGERY in debug the processors check that the
455 // stack is still within the limit of the stack limits after running a thread.
456 // that check doesn't make sense if we context switch to the processor using the
457 // coroutine semantics. Since this is a special case, use the current context
458 // info to populate these fields.
459 __cfaabi_dbg_debug_do(
460 __stack_context_t ctx;
461 CtxGet( ctx );
462 mainThread->context.SP = ctx.SP;
463 mainThread->context.FP = ctx.FP;
464 )
465
466 // context switch to the processor
467 __cfactx_switch( &src->context, &dst->context );
468}
469
470
471//=============================================================================================
472// Kernel Object Constructors logic
473//=============================================================================================
474//-----------------------------------------------------------------------------
475// Main thread construction
[e84ab3d]476static void ?{}( coroutine$ & this, current_stack_info_t * info) with( this ) {
[e660761]477 stack.storage = info->storage;
478 with(*stack.storage) {
479 limit = info->limit;
480 base = info->base;
481 }
482 __attribute__((may_alias)) intptr_t * istorage = (intptr_t*) &stack.storage;
483 *istorage |= 0x1;
484 name = "Main Thread";
485 state = Start;
486 starter = 0p;
487 last = 0p;
488 cancellation = 0p;
489}
490
[e84ab3d]491static void ?{}( thread$ & this, current_stack_info_t * info) with( this ) {
[6a77224]492 ticket = TICKET_RUNNING;
[e660761]493 state = Start;
494 self_cor{ info };
495 curr_cor = &self_cor;
496 curr_cluster = mainCluster;
497 self_mon.owner = &this;
498 self_mon.recursion = 1;
499 self_mon_p = &self_mon;
[15c93d8]500 rdy_link.next = 0p;
501 rdy_link.ts = MAX;
[1553a55]502 user_link.next = 0p;
503 user_link.prev = 0p;
504 cltr_link.next = 0p;
505 cltr_link.prev = 0p;
[24e321c]506 preferred = ready_queue_new_preferred();
[89eff25]507 last_proc = 0p;
[dd46fd3]508 PRNG_SET_SEED( random_state, __global_random_mask ? __global_random_prime : __global_random_prime ^ rdtscl() );
[b4b63e8]509 #if defined( __CFA_WITH_VERIFY__ )
[878cfcc]510 executing = 0p;
[ac12f1f]511 canary = 0x0D15EA5E0D15EA5Ep;
[b4b63e8]512 #endif
[e660761]513
514 doregister(curr_cluster, this);
515
516 monitors{ &self_mon_p, 1, (fptr_t)0 };
517}
518
519//-----------------------------------------------------------------------------
520// Processor
521// Construct the processor context of non-main processors
522static void ?{}(processorCtx_t & this, processor * proc, current_stack_info_t * info) {
[c18bf9e]523 (this.self){ info };
[e660761]524 this.proc = proc;
525}
526
[e84ab3d]527static void init(processor & this, const char name[], cluster & _cltr, thread$ * initT) with( this ) {
[e660761]528 this.name = name;
529 this.cltr = &_cltr;
[431cd4f]530 this.rdq.its = 0;
531 this.rdq.itr = 0;
[884f3f67]532 this.rdq.id = 0;
[145dcd5]533 this.rdq.target = MAX;
534 this.rdq.last = MAX;
535 this.rdq.cpu = 0;
536 // this.rdq.cutoff = 0ull;
[e660761]537 do_terminate = false;
538 preemption_alarm = 0p;
539 pending_preemption = false;
540
[78da4ab]541 this.io.ctx = 0p;
[dddb3dd0]542 this.io.pending = false;
543 this.io.dirty = false;
544
[a5e7233]545 this.init.thrd = initT;
[a1538cd]546
[a67c5b6]547 this.local_data = 0p;
548
[22226e4]549 idle_wctx.evfd = eventfd(0, 0);
550 if (idle_wctx.evfd < 0) {
[dddb3dd0]551 abort("KERNEL ERROR: PROCESSOR EVENTFD - %s\n", strerror(errno));
552 }
[78da4ab]553
[22226e4]554 idle_wctx.sem = 0;
[efa28d5]555 idle_wctx.wake__time = 0;
[7cf3b1d]556
557 // I'm assuming these two are reserved for standard input and output
558 // so I'm using them as sentinels with idle_wctx.
[22226e4]559 /* paranoid */ verify( idle_wctx.evfd != 0 );
560 /* paranoid */ verify( idle_wctx.evfd != 1 );
[7cf3b1d]561
[e660761]562 #if !defined(__CFA_NO_STATISTICS__)
563 print_stats = 0;
564 print_halts = false;
565 #endif
566
567 __cfadbg_print_safe(runtime_core, "Kernel : core %p created\n", &this);
568}
569
570// Not a ctor, it just preps the destruction but should not destroy members
571static void deinit(processor & this) {
[22226e4]572 close(this.idle_wctx.evfd);
[e660761]573}
574
[c18bf9e]575void ?{}(processor & this, const char name[], cluster & _cltr, thread$ * initT) libcfa_public {
[454f478]576 ( this.terminated ){};
[e660761]577 ( this.runner ){};
[62502cc4]578
579 disable_interrupts();
[a5e7233]580 init( this, name, _cltr, initT );
[a3821fa]581 enable_interrupts();
[e660761]582
583 __cfadbg_print_safe(runtime_core, "Kernel : Starting core %p\n", &this);
584
585 this.stack = __create_pthread( &this.kernel_thread, __invoke_processor, (void *)&this );
[a5e7233]586}
[e660761]587
[c18bf9e]588void ?{}(processor & this, const char name[], cluster & _cltr) libcfa_public {
[a5e7233]589 (this){name, _cltr, 0p};
[e660761]590}
591
[a182ad5]592extern size_t __page_size;
[c18bf9e]593void ^?{}(processor & this) libcfa_public with( this ) {
[7d0ebd0]594 /* paranoid */ verify( !__atomic_load_n(&do_terminate, __ATOMIC_ACQUIRE) );
595 __cfadbg_print_safe(runtime_core, "Kernel : core %p signaling termination\n", &this);
[e660761]596
[7d0ebd0]597 __atomic_store_n(&do_terminate, true, __ATOMIC_RELAXED);
598 __disable_interrupts_checked();
[e660761]599 __wake_proc( &this );
[7d0ebd0]600 __enable_interrupts_checked();
[e660761]601
[7d0ebd0]602 wait( terminated );
603 /* paranoid */ verify( active_processor() != &this);
[e660761]604
[bfcf6b9]605 __destroy_pthread( kernel_thread, this.stack, 0p );
[e660761]606
[62502cc4]607 disable_interrupts();
608 deinit( this );
[a3821fa]609 enable_interrupts();
[e660761]610}
611
612//-----------------------------------------------------------------------------
613// Cluster
[6a9b12b]614static void ?{}(__cluster_proc_list & this) {
[7cf3b1d]615 this.fdw = 0p;
[1eb239e4]616 this.idle = 0;
617 this.total = 0;
618}
619
[c18bf9e]620void ?{}(cluster & this, const char name[], Duration preemption_rate, unsigned num_io, const io_context_params & io_params) libcfa_public with( this ) {
[e660761]621 this.name = name;
622 this.preemption_rate = preemption_rate;
[884f3f67]623 this.sched.readyQ.data = 0p;
624 this.sched.readyQ.tscs = 0p;
625 this.sched.readyQ.count = 0;
626 this.sched.io.tscs = 0p;
[0c3aa67]627 this.sched.io.data = 0p;
[884f3f67]628 this.sched.caches = 0p;
[e660761]629
630 #if !defined(__CFA_NO_STATISTICS__)
631 print_stats = 0;
632 stats = alloc();
633 __init_stats( stats );
634 #endif
635
[cd5b58f]636 threads{};
[e660761]637
[78da4ab]638 io.arbiter = create();
639 io.params = io_params;
640
[8b74fa7]641 managed.procs = 0p;
642 managed.cnt = 0;
643
[e660761]644 doregister(this);
645
646 // Lock the RWlock so no-one pushes/pops while we are changing the queue
[772411a]647 disable_interrupts();
[e660761]648 uint_fast32_t last_size = ready_mutate_lock();
649
650 // Adjust the ready queue size
[a017ee7]651 ready_queue_grow( &this );
[e660761]652
653 // Unlock the RWlock
654 ready_mutate_unlock( last_size );
[a3821fa]655 enable_interrupts( false ); // Don't poll, could be in main cluster
[e660761]656}
657
[c18bf9e]658void ^?{}(cluster & this) libcfa_public {
[8b74fa7]659 set_concurrency( this, 0 );
660
[78da4ab]661 destroy(this.io.arbiter);
[e660761]662
663 // Lock the RWlock so no-one pushes/pops while we are changing the queue
[772411a]664 disable_interrupts();
[e660761]665 uint_fast32_t last_size = ready_mutate_lock();
666
667 // Adjust the ready queue size
[a017ee7]668 ready_queue_shrink( &this );
[e660761]669
670 // Unlock the RWlock
671 ready_mutate_unlock( last_size );
[884f3f67]672
673 ready_queue_close( &this );
674 /* paranoid */ verify( this.sched.readyQ.data == 0p );
675 /* paranoid */ verify( this.sched.readyQ.tscs == 0p );
676 /* paranoid */ verify( this.sched.readyQ.count == 0 );
677 /* paranoid */ verify( this.sched.io.tscs == 0p );
678 /* paranoid */ verify( this.sched.caches == 0p );
679
[a3821fa]680 enable_interrupts( false ); // Don't poll, could be in main cluster
[e660761]681
[884f3f67]682
[e660761]683 #if !defined(__CFA_NO_STATISTICS__)
684 if( 0 != this.print_stats ) {
[1b033b8]685 __print_stats( this.stats, this.print_stats, "Cluster", this.name, (void*)&this );
[e660761]686 }
[73f4d08]687 #if defined(CFA_STATS_ARRAY)
688 __flush_stat( this.stats, "Cluster", &this );
689 #endif
[e660761]690 free( this.stats );
691 #endif
692
693 unregister(this);
694}
695
696//=============================================================================================
697// Miscellaneous Initialization
698//=============================================================================================
699//-----------------------------------------------------------------------------
700// Global Queues
701static void doregister( cluster & cltr ) {
702 lock ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2);
703 push_front( __cfa_dbg_global_clusters.list, cltr );
704 unlock ( __cfa_dbg_global_clusters.lock );
705}
706
707static void unregister( cluster & cltr ) {
708 lock ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2);
709 remove( __cfa_dbg_global_clusters.list, cltr );
710 unlock( __cfa_dbg_global_clusters.lock );
711}
712
[e84ab3d]713void doregister( cluster * cltr, thread$ & thrd ) {
[e660761]714 lock (cltr->thread_list_lock __cfaabi_dbg_ctx2);
715 cltr->nthreads += 1;
[cd5b58f]716 insert_first(cltr->threads, thrd);
[e660761]717 unlock (cltr->thread_list_lock);
718}
719
[e84ab3d]720void unregister( cluster * cltr, thread$ & thrd ) {
[e660761]721 lock (cltr->thread_list_lock __cfaabi_dbg_ctx2);
[cd5b58f]722 {
723 tytagref( dlink(thread$), dlink(thread$) ) ?`inner( thread$ & this ) = void;
[639e4fc]724 with( DLINK_VIA( thread$, struct __thread_user_link ) )
[cd5b58f]725 remove( thrd );
726 cltr->nthreads -= 1;
727 }
[e660761]728 unlock(cltr->thread_list_lock);
729}
730
[c993b15]731static void register_tls( processor * this ) {
732 // Register and Lock the RWlock so no-one pushes/pops while we are changing the queue
733 uint_fast32_t last_size;
734 [this->unique_id, last_size] = ready_mutate_register();
735
[145dcd5]736 this->rdq.cpu = __kernel_getcpu();
737
[c993b15]738 this->cltr->procs.total += 1u;
739 insert_last(this->cltr->procs.actives, *this);
740
741 // Adjust the ready queue size
742 ready_queue_grow( this->cltr );
743
744 // Unlock the RWlock
745 ready_mutate_unlock( last_size );
746}
747
748
749static void unregister_tls( processor * this ) {
750 // Lock the RWlock so no-one pushes/pops while we are changing the queue
751 uint_fast32_t last_size = ready_mutate_lock();
752 this->cltr->procs.total -= 1u;
753 remove(*this);
754
755 // clear the cluster so nothing gets pushed to local queues
756 cluster * cltr = this->cltr;
757 this->cltr = 0p;
758
759 // Adjust the ready queue size
760 ready_queue_shrink( cltr );
761
762 // Unlock the RWlock and unregister: we don't need the read_lock any more
763 ready_mutate_unregister( this->unique_id, last_size );
764}
765
[e660761]766static void check( int ret, const char func[] ) {
767 if ( ret ) { // pthread routines return errno values
768 abort( "%s : internal error, error(%d) %s.", func, ret, strerror( ret ) );
769 } // if
770} // Abort
771
772void * __create_pthread( pthread_t * pthread, void * (*start)(void *), void * arg ) {
773 pthread_attr_t attr;
774
[95dab9e]775 check( __cfaabi_pthread_attr_init( &attr ), "pthread_attr_init" ); // initialize attribute
[e660761]776
[09ae8a6]777 size_t stacksize = max( PTHREAD_STACK_MIN, DEFAULT_STACK_SIZE );
[e660761]778
779 void * stack;
[97229d6]780 #if CFA_PROCESSOR_USE_MMAP
[a182ad5]781 stacksize = ceiling( stacksize, __page_size ) + __page_size;
[dd92fe9]782 stack = mmap(0p, stacksize, __map_prot, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
[97229d6]783 if(stack == ((void*)-1)) {
784 abort( "pthread stack creation : internal error, mmap failure, error(%d) %s.", errno, strerror( errno ) );
785 }
[a182ad5]786 if ( mprotect( stack, __page_size, PROT_NONE ) == -1 ) {
[97229d6]787 abort( "pthread stack creation : internal error, mprotect failure, error(%d) %s.", errno, strerror( errno ) );
788 } // if
789 #else
790 __cfaabi_dbg_debug_do(
[a182ad5]791 stack = memalign( __page_size, stacksize + __page_size );
[97229d6]792 // pthread has no mechanism to create the guard page in user supplied stack.
[a182ad5]793 if ( mprotect( stack, __page_size, PROT_NONE ) == -1 ) {
[97229d6]794 abort( "mprotect : internal error, mprotect failure, error(%d) %s.", errno, strerror( errno ) );
795 } // if
796 );
797 __cfaabi_dbg_no_debug_do(
798 stack = malloc( stacksize );
799 );
800 #endif
801
[95dab9e]802 check( __cfaabi_pthread_attr_setstack( &attr, stack, stacksize ), "pthread_attr_setstack" );
803 check( __cfaabi_pthread_create( pthread, &attr, start, arg ), "pthread_create" );
[e660761]804 return stack;
[88cafe7]805}
[f2384c9a]806
[bfcf6b9]807void __destroy_pthread( pthread_t pthread, void * stack, void ** retval ) {
[95dab9e]808 int err = __cfaabi_pthread_join( pthread, retval );
[bfcf6b9]809 if( err != 0 ) abort("KERNEL ERROR: joining pthread %p caused error %s\n", (void*)pthread, strerror(err));
810
[97229d6]811 #if CFA_PROCESSOR_USE_MMAP
812 pthread_attr_t attr;
[bfcf6b9]813
[95dab9e]814 check( __cfaabi_pthread_attr_init( &attr ), "pthread_attr_init" ); // initialize attribute
[bfcf6b9]815
[97229d6]816 size_t stacksize;
817 // default stack size, normally defined by shell limit
[95dab9e]818 check( __cfaabi_pthread_attr_getstacksize( &attr, &stacksize ), "pthread_attr_getstacksize" );
[97229d6]819 assert( stacksize >= PTHREAD_STACK_MIN );
[a182ad5]820 stacksize += __page_size;
[bfcf6b9]821
[97229d6]822 if(munmap(stack, stacksize) == -1) {
823 abort( "pthread stack destruction : internal error, munmap failure, error(%d) %s.", errno, strerror( errno ) );
824 }
825 #else
[72a3aff]826 __cfaabi_dbg_debug_do(
827 // pthread has no mechanism to create the guard page in user supplied stack.
[a182ad5]828 if ( mprotect( stack, __page_size, __map_prot ) == -1 ) {
[72a3aff]829 abort( "mprotect : internal error, mprotect failure, error(%d) %s.", errno, strerror( errno ) );
830 } // if
831 );
[97229d6]832 free( stack );
833 #endif
[bfcf6b9]834}
835
[8b74fa7]836unsigned set_concurrency( cluster & this, unsigned new ) libcfa_public {
837 unsigned old = this.managed.cnt;
838
839 __cfadbg_print_safe(runtime_core, "Kernel : resizing cluster from %u to %u\n", old, (unsigned)new);
840
841 // Delete all the old unneeded procs
842 if(old > new) for(i; (unsigned)new ~ old) {
843 __cfadbg_print_safe(runtime_core, "Kernel : destroying %u\n", i);
844 delete( this.managed.procs[i] );
845 }
846
847 // Allocate new array (uses realloc and memcpies the data)
848 this.managed.procs = alloc( new, this.managed.procs`realloc );
849 this.managed.cnt = new;
850
851 // Create the desired new procs
852 if(old < new) for(i; old ~ new) {
853 __cfadbg_print_safe(runtime_core, "Kernel : constructing %u\n", i);
854 (*(this.managed.procs[i] = alloc())){ this };
855 }
856
857 // return the old count
858 return old;
859}
860
[f2384c9a]861#if defined(__CFA_WITH_VERIFY__)
862static bool verify_fwd_bck_rng(void) {
[8fc652e0]863 __cfaabi_tls.ready_rng.fwd_seed = 25214903917_l64u * (rdtscl() ^ (uintptr_t)&verify_fwd_bck_rng);
[f2384c9a]864
865 unsigned values[10];
866 for(i; 10) {
867 values[i] = __tls_rand_fwd();
868 }
869
870 __tls_rand_advance_bck();
871
872 for ( i; 9 -~= 0 ) {
873 if(values[i] != __tls_rand_bck()) {
874 return false;
875 }
876 }
877
878 return true;
879}
[eaf269d]880#endif
Note: See TracBrowser for help on using the repository browser.