source: libcfa/src/concurrency/kernel/startup.cfa @ 95dab9e

ADTast-experimentalpthread-emulation
Last change on this file since 95dab9e was 95dab9e, checked in by Thierry Delisle <tdelisle@…>, 19 months ago

Changed real_pthread symbols (now cfaabi_pthread) to be protected in libcfathread

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