source: libcfa/src/concurrency/kernel/startup.cfa @ 78da4ab

arm-ehjacob/cs343-translationnew-ast-unique-expr
Last change on this file since 78da4ab was 78da4ab, checked in by Thierry Delisle <tdelisle@…>, 8 months ago

New implementation of io based on instance burrowing.
Trying to avoid the unbounded growth of the previous flat combining approach.

  • Property mode set to 100644
File size: 24.0 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
18// C Includes
19#include <errno.h>              // errno
20#include <string.h>             // strerror
21#include <unistd.h>             // sysconf
22extern "C" {
23      #include <limits.h>       // PTHREAD_STACK_MIN
24      #include <sys/mman.h>     // mprotect
25      #include <sys/resource.h> // getrlimit
26}
27
28// CFA Includes
29#include "kernel_private.hfa"
30#include "startup.hfa"          // STARTUP_PRIORITY_XXX
31#include "math.hfa"
32
33#define CFA_PROCESSOR_USE_MMAP 0
34
35//-----------------------------------------------------------------------------
36// Some assembly required
37#if defined( __i386 )
38        #define CtxGet( ctx ) __asm__ volatile ( \
39                "movl %%esp,%0\n" \
40                "movl %%ebp,%1\n" \
41                : "=rm" (ctx.SP), \
42                  "=rm" (ctx.FP) \
43        )
44#elif defined( __x86_64 )
45        #define CtxGet( ctx ) __asm__ volatile ( \
46                "movq %%rsp,%0\n" \
47                "movq %%rbp,%1\n" \
48                : "=rm" (ctx.SP), \
49                  "=rm" (ctx.FP) \
50        )
51#elif defined( __aarch64__ )
52        #define CtxGet( ctx ) __asm__ volatile ( \
53                "mov %0, sp\n" \
54                "mov %1, fp\n" \
55                : "=rm" (ctx.SP), \
56                  "=rm" (ctx.FP) \
57        )
58#else
59        #error unknown hardware architecture
60#endif
61
62//-----------------------------------------------------------------------------
63// Start and stop routine for the kernel, declared first to make sure they run first
64static void __kernel_startup (void) __attribute__(( constructor( STARTUP_PRIORITY_KERNEL ) ));
65static void __kernel_shutdown(void) __attribute__(( destructor ( STARTUP_PRIORITY_KERNEL ) ));
66
67//-----------------------------------------------------------------------------
68// Static Forward Declarations
69struct current_stack_info_t;
70
71static void * __invoke_processor(void * arg);
72static void __kernel_first_resume( processor * this );
73static void __kernel_last_resume ( processor * this );
74static void init(processor & this, const char name[], cluster & _cltr);
75static void deinit(processor & this);
76static void doregister( struct cluster & cltr );
77static void unregister( struct cluster & cltr );
78static void ?{}( $coroutine & this, current_stack_info_t * info);
79static void ?{}( $thread & this, current_stack_info_t * info);
80static void ?{}(processorCtx_t & this) {}
81static void ?{}(processorCtx_t & this, processor * proc, current_stack_info_t * info);
82static void ?{}(__bin_sem_t & this);
83static void ^?{}(__bin_sem_t & this);
84
85#if defined(__CFA_WITH_VERIFY__)
86        static bool verify_fwd_bck_rng(void);
87#endif
88
89//-----------------------------------------------------------------------------
90// Forward Declarations for other modules
91extern void __kernel_alarm_startup(void);
92extern void __kernel_alarm_shutdown(void);
93extern void __kernel_io_startup (void);
94extern void __kernel_io_shutdown(void);
95
96//-----------------------------------------------------------------------------
97// Other Forward Declarations
98extern void __wake_proc(processor *);
99
100//-----------------------------------------------------------------------------
101// Kernel storage
102KERNEL_STORAGE(cluster,              mainCluster);
103KERNEL_STORAGE(processor,            mainProcessor);
104KERNEL_STORAGE($thread,              mainThread);
105KERNEL_STORAGE(__stack_t,            mainThreadCtx);
106KERNEL_STORAGE(io_context,           mainIoContext);
107KERNEL_STORAGE(__scheduler_RWLock_t, __scheduler_lock);
108#if !defined(__CFA_NO_STATISTICS__)
109KERNEL_STORAGE(__stats_t, mainProcStats);
110#endif
111
112cluster              * mainCluster;
113processor            * mainProcessor;
114$thread              * mainThread;
115__scheduler_RWLock_t * __scheduler_lock;
116
117extern "C" {
118        struct { __dllist_t(cluster) list; __spinlock_t lock; } __cfa_dbg_global_clusters;
119}
120
121extern size_t __page_size;
122extern int __map_prot;
123
124//-----------------------------------------------------------------------------
125// Global state
126thread_local struct KernelThreadData __cfaabi_tls __attribute__ ((tls_model ( "initial-exec" ))) @= {
127        NULL,                                                                                           // cannot use 0p
128        NULL,
129        NULL,
130        NULL,
131        { 1, false, false },
132};
133
134//-----------------------------------------------------------------------------
135// Struct to steal stack
136struct current_stack_info_t {
137        __stack_t * storage;  // pointer to stack object
138        void * base;          // base of stack
139        void * limit;         // stack grows towards stack limit
140        void * context;       // address of cfa_context_t
141};
142
143void ?{}( current_stack_info_t & this ) {
144        __stack_context_t ctx;
145        CtxGet( ctx );
146        this.base = ctx.FP;
147
148        rlimit r;
149        getrlimit( RLIMIT_STACK, &r);
150        size_t size = r.rlim_cur;
151
152        this.limit = (void *)(((intptr_t)this.base) - size);
153        this.context = &storage_mainThreadCtx;
154}
155
156
157
158//=============================================================================================
159// Kernel Setup logic
160//=============================================================================================
161//-----------------------------------------------------------------------------
162// Kernel boot procedures
163static void __kernel_startup(void) {
164        /* paranoid */ verify( ! __preemption_enabled() );
165        __cfadbg_print_safe(runtime_core, "Kernel : Starting\n");
166
167        __cfa_dbg_global_clusters.list{ __get };
168        __cfa_dbg_global_clusters.lock{};
169
170        /* paranoid */ verify( verify_fwd_bck_rng() );
171
172        // Initialize the global scheduler lock
173        __scheduler_lock = (__scheduler_RWLock_t*)&storage___scheduler_lock;
174        (*__scheduler_lock){};
175
176        // Initialize the main cluster
177        mainCluster = (cluster *)&storage_mainCluster;
178        (*mainCluster){"Main Cluster", 0};
179
180        __cfadbg_print_safe(runtime_core, "Kernel : Main cluster ready\n");
181
182        // Start by initializing the main thread
183        // SKULLDUGGERY: the mainThread steals the process main thread
184        // which will then be scheduled by the mainProcessor normally
185        mainThread = ($thread *)&storage_mainThread;
186        current_stack_info_t info;
187        info.storage = (__stack_t*)&storage_mainThreadCtx;
188        (*mainThread){ &info };
189
190        __cfadbg_print_safe(runtime_core, "Kernel : Main thread ready\n");
191
192
193
194        // Construct the processor context of the main processor
195        void ?{}(processorCtx_t & this, processor * proc) {
196                (this.__cor){ "Processor" };
197                this.__cor.starter = 0p;
198                this.proc = proc;
199        }
200
201        void ?{}(processor & this) with( this ) {
202                ( this.idle ){};
203                ( this.terminated ){};
204                ( this.runner ){};
205                init( this, "Main Processor", *mainCluster );
206                kernel_thread = pthread_self();
207
208                runner{ &this };
209                __cfadbg_print_safe(runtime_core, "Kernel : constructed main processor context %p\n", &runner);
210        }
211
212        // Initialize the main processor and the main processor ctx
213        // (the coroutine that contains the processing control flow)
214        mainProcessor = (processor *)&storage_mainProcessor;
215        (*mainProcessor){};
216
217        //initialize the global state variables
218        __cfaabi_tls.this_processor = mainProcessor;
219        __cfaabi_tls.this_proc_id   = (__processor_id_t*)mainProcessor;
220        __cfaabi_tls.this_thread    = mainThread;
221
222        #if !defined( __CFA_NO_STATISTICS__ )
223                __cfaabi_tls.this_stats = (__stats_t *)& storage_mainProcStats;
224                __init_stats( __cfaabi_tls.this_stats );
225        #endif
226
227        // Enable preemption
228        __kernel_alarm_startup();
229
230        // Start IO
231        __kernel_io_startup();
232
233        io_context * mainio = (io_context *)&storage_mainIoContext;
234        (*mainio){ *mainCluster };
235
236        // Add the main thread to the ready queue
237        // once resume is called on mainProcessor->runner the mainThread needs to be scheduled like any normal thread
238        __schedule_thread(mainThread);
239
240        // SKULLDUGGERY: Force a context switch to the main processor to set the main thread's context to the current UNIX
241        // context. Hence, the main thread does not begin through __cfactx_invoke_thread, like all other threads. The trick here is that
242        // mainThread is on the ready queue when this call is made.
243        __kernel_first_resume( __cfaabi_tls.this_processor );
244
245
246        // THE SYSTEM IS NOW COMPLETELY RUNNING
247
248        __cfadbg_print_safe(runtime_core, "Kernel : Started\n--------------------------------------------------\n\n");
249
250        /* paranoid */ verify( ! __preemption_enabled() );
251        enable_interrupts( __cfaabi_dbg_ctx );
252        /* paranoid */ verify( __preemption_enabled() );
253
254}
255
256static void __kernel_shutdown(void) {
257        //Before we start shutting things down, wait for systems that need threading to shutdown
258        io_context * mainio = (io_context *)&storage_mainIoContext;
259        ^(*mainio){};
260
261        /* paranoid */ verify( __preemption_enabled() );
262        disable_interrupts();
263        /* paranoid */ verify( ! __preemption_enabled() );
264
265        __cfadbg_print_safe(runtime_core, "\n--------------------------------------------------\nKernel : Shutting down\n");
266
267        // SKULLDUGGERY: Notify the mainProcessor it needs to terminates.
268        // When its coroutine terminates, it return control to the mainThread
269        // which is currently here
270        __atomic_store_n(&mainProcessor->do_terminate, true, __ATOMIC_RELEASE);
271        __kernel_last_resume( __cfaabi_tls.this_processor );
272        mainThread->self_cor.state = Halted;
273
274        // THE SYSTEM IS NOW COMPLETELY STOPPED
275
276        // Disable preemption
277        __kernel_alarm_shutdown();
278
279        // Stop IO
280        __kernel_io_shutdown();
281
282        // Destroy the main processor and its context in reverse order of construction
283        // These were manually constructed so we need manually destroy them
284        void ^?{}(processor & this) with( this ){
285                deinit( this );
286
287                /* paranoid */ verify( this.do_terminate == true );
288                __cfaabi_dbg_print_safe("Kernel : destroyed main processor context %p\n", &runner);
289        }
290
291        ^(*mainProcessor){};
292
293        // Final step, destroy the main thread since it is no longer needed
294
295        // Since we provided a stack to this taxk it will not destroy anything
296        /* paranoid */ verify(mainThread->self_cor.stack.storage == (__stack_t*)(((uintptr_t)&storage_mainThreadCtx)| 0x1));
297        ^(*mainThread){};
298
299        ^(*mainCluster){};
300
301        ^(*__scheduler_lock){};
302
303        ^(__cfa_dbg_global_clusters.list){};
304        ^(__cfa_dbg_global_clusters.lock){};
305
306        __cfadbg_print_safe(runtime_core, "Kernel : Shutdown complete\n");
307}
308
309//=============================================================================================
310// Kernel Initial Scheduling logic
311//=============================================================================================
312
313// Context invoker for processors
314// This is the entry point for processors (kernel threads) *except* for the main processor
315// It effectively constructs a coroutine by stealing the pthread stack
316static void * __invoke_processor(void * arg) {
317        #if !defined( __CFA_NO_STATISTICS__ )
318                __stats_t local_stats;
319                __init_stats( &local_stats );
320                __cfaabi_tls.this_stats = &local_stats;
321        #endif
322
323        processor * proc = (processor *) arg;
324        __cfaabi_tls.this_processor = proc;
325        __cfaabi_tls.this_proc_id   = (__processor_id_t*)proc;
326        __cfaabi_tls.this_thread    = 0p;
327        __cfaabi_tls.preemption_state.[enabled, disable_count] = [false, 1];
328        // SKULLDUGGERY: We want to create a context for the processor coroutine
329        // which is needed for the 2-step context switch. However, there is no reason
330        // to waste the perfectly valid stack create by pthread.
331        current_stack_info_t info;
332        __stack_t ctx;
333        info.storage = &ctx;
334        (proc->runner){ proc, &info };
335
336        __cfaabi_dbg_print_safe("Coroutine : created stack %p\n", get_coroutine(proc->runner)->stack.storage);
337
338        //Set global state
339        __cfaabi_tls.this_thread = 0p;
340
341        //We now have a proper context from which to schedule threads
342        __cfadbg_print_safe(runtime_core, "Kernel : core %p created (%p, %p)\n", proc, &proc->runner, &ctx);
343
344        // SKULLDUGGERY: Since the coroutine doesn't have its own stack, we can't
345        // resume it to start it like it normally would, it will just context switch
346        // back to here. Instead directly call the main since we already are on the
347        // appropriate stack.
348        get_coroutine(proc->runner)->state = Active;
349        main( proc->runner );
350        get_coroutine(proc->runner)->state = Halted;
351
352        // Main routine of the core returned, the core is now fully terminated
353        __cfadbg_print_safe(runtime_core, "Kernel : core %p main ended (%p)\n", proc, &proc->runner);
354
355        #if !defined(__CFA_NO_STATISTICS__)
356                __tally_stats(proc->cltr->stats, &local_stats);
357                if( 0 != proc->print_stats ) {
358                        __print_stats( &local_stats, proc->print_stats, "Processor ", proc->name, (void*)proc );
359                }
360        #endif
361
362        return 0p;
363}
364
365static void __kernel_first_resume( processor * this ) {
366        $thread * src = mainThread;
367        $coroutine * dst = get_coroutine(this->runner);
368
369        /* paranoid */ verify( ! __preemption_enabled() );
370
371        __cfaabi_tls.this_thread->curr_cor = dst;
372        __stack_prepare( &dst->stack, 65000 );
373        __cfactx_start(main, dst, this->runner, __cfactx_invoke_coroutine);
374
375        /* paranoid */ verify( ! __preemption_enabled() );
376
377        dst->last = &src->self_cor;
378        dst->starter = dst->starter ? dst->starter : &src->self_cor;
379
380        // make sure the current state is still correct
381        /* paranoid */ verify(src->state == Ready);
382
383        // context switch to specified coroutine
384        verify( dst->context.SP );
385        __cfactx_switch( &src->context, &dst->context );
386        // when __cfactx_switch returns we are back in the src coroutine
387
388        mainThread->curr_cor = &mainThread->self_cor;
389
390        // make sure the current state has been update
391        /* paranoid */ verify(src->state == Active);
392
393        /* paranoid */ verify( ! __preemption_enabled() );
394}
395
396// KERNEL_ONLY
397static void __kernel_last_resume( processor * this ) {
398        $coroutine * src = &mainThread->self_cor;
399        $coroutine * dst = get_coroutine(this->runner);
400
401        /* paranoid */ verify( ! __preemption_enabled() );
402        /* paranoid */ verify( dst->starter == src );
403        /* paranoid */ verify( dst->context.SP );
404
405        // SKULLDUGGERY in debug the processors check that the
406        // stack is still within the limit of the stack limits after running a thread.
407        // that check doesn't make sense if we context switch to the processor using the
408        // coroutine semantics. Since this is a special case, use the current context
409        // info to populate these fields.
410        __cfaabi_dbg_debug_do(
411                __stack_context_t ctx;
412                CtxGet( ctx );
413                mainThread->context.SP = ctx.SP;
414                mainThread->context.FP = ctx.FP;
415        )
416
417        // context switch to the processor
418        __cfactx_switch( &src->context, &dst->context );
419}
420
421
422//=============================================================================================
423// Kernel Object Constructors logic
424//=============================================================================================
425//-----------------------------------------------------------------------------
426// Main thread construction
427static void ?{}( $coroutine & this, current_stack_info_t * info) with( this ) {
428        stack.storage = info->storage;
429        with(*stack.storage) {
430                limit     = info->limit;
431                base      = info->base;
432        }
433        __attribute__((may_alias)) intptr_t * istorage = (intptr_t*) &stack.storage;
434        *istorage |= 0x1;
435        name = "Main Thread";
436        state = Start;
437        starter = 0p;
438        last = 0p;
439        cancellation = 0p;
440}
441
442static void ?{}( $thread & this, current_stack_info_t * info) with( this ) {
443        ticket = TICKET_RUNNING;
444        state = Start;
445        self_cor{ info };
446        curr_cor = &self_cor;
447        curr_cluster = mainCluster;
448        self_mon.owner = &this;
449        self_mon.recursion = 1;
450        self_mon_p = &self_mon;
451        link.next = 0p;
452        link.prev = 0p;
453        #if defined( __CFA_WITH_VERIFY__ )
454                canary = 0x0D15EA5E0D15EA5Ep;
455        #endif
456
457        node.next = 0p;
458        node.prev = 0p;
459        doregister(curr_cluster, this);
460
461        monitors{ &self_mon_p, 1, (fptr_t)0 };
462}
463
464//-----------------------------------------------------------------------------
465// Processor
466// Construct the processor context of non-main processors
467static void ?{}(processorCtx_t & this, processor * proc, current_stack_info_t * info) {
468        (this.__cor){ info };
469        this.proc = proc;
470}
471
472static void init(processor & this, const char name[], cluster & _cltr) with( this ) {
473        this.name = name;
474        this.cltr = &_cltr;
475        full_proc = true;
476        do_terminate = false;
477        preemption_alarm = 0p;
478        pending_preemption = false;
479
480        this.io.ctx = 0p;
481        this.io.lock = false;
482
483        #if !defined(__CFA_NO_STATISTICS__)
484                print_stats = 0;
485                print_halts = false;
486        #endif
487
488        lock( this.cltr->idles );
489                int target = this.cltr->idles.total += 1u;
490        unlock( this.cltr->idles );
491
492        id = doregister((__processor_id_t*)&this);
493
494        // Lock the RWlock so no-one pushes/pops while we are changing the queue
495        uint_fast32_t last_size = ready_mutate_lock();
496
497                // Adjust the ready queue size
498                ready_queue_grow( cltr, target );
499
500        // Unlock the RWlock
501        ready_mutate_unlock( last_size );
502
503        __cfadbg_print_safe(runtime_core, "Kernel : core %p created\n", &this);
504}
505
506// Not a ctor, it just preps the destruction but should not destroy members
507static void deinit(processor & this) {
508        lock( this.cltr->idles );
509                int target = this.cltr->idles.total -= 1u;
510        unlock( this.cltr->idles );
511
512        // Lock the RWlock so no-one pushes/pops while we are changing the queue
513        uint_fast32_t last_size = ready_mutate_lock();
514
515                // Adjust the ready queue size
516                ready_queue_shrink( this.cltr, target );
517
518        // Unlock the RWlock
519        ready_mutate_unlock( last_size );
520
521        // Finally we don't need the read_lock any more
522        unregister((__processor_id_t*)&this);
523}
524
525void ?{}(processor & this, const char name[], cluster & _cltr) {
526        ( this.idle ){};
527        ( this.terminated ){};
528        ( this.runner ){};
529
530        disable_interrupts();
531                init( this, name, _cltr );
532        enable_interrupts( __cfaabi_dbg_ctx );
533
534        __cfadbg_print_safe(runtime_core, "Kernel : Starting core %p\n", &this);
535
536        this.stack = __create_pthread( &this.kernel_thread, __invoke_processor, (void *)&this );
537
538}
539
540extern size_t __page_size;
541void ^?{}(processor & this) with( this ){
542        if( ! __atomic_load_n(&do_terminate, __ATOMIC_ACQUIRE) ) {
543                __cfadbg_print_safe(runtime_core, "Kernel : core %p signaling termination\n", &this);
544
545                __atomic_store_n(&do_terminate, true, __ATOMIC_RELAXED);
546                __wake_proc( &this );
547
548                wait( terminated );
549                /* paranoid */ verify( active_processor() != &this);
550        }
551
552        __destroy_pthread( kernel_thread, this.stack, 0p );
553
554        disable_interrupts();
555                deinit( this );
556        enable_interrupts( __cfaabi_dbg_ctx );
557}
558
559//-----------------------------------------------------------------------------
560// Cluster
561static void ?{}(__cluster_idles & this) {
562        this.lock  = 0;
563        this.idle  = 0;
564        this.total = 0;
565        (this.list){};
566}
567
568void ?{}(cluster & this, const char name[], Duration preemption_rate, unsigned num_io, const io_context_params & io_params) with( this ) {
569        this.name = name;
570        this.preemption_rate = preemption_rate;
571        ready_queue{};
572
573        #if !defined(__CFA_NO_STATISTICS__)
574                print_stats = 0;
575                stats = alloc();
576                __init_stats( stats );
577        #endif
578
579        threads{ __get };
580
581        io.arbiter = create();
582        io.params = io_params;
583
584        doregister(this);
585
586        // Lock the RWlock so no-one pushes/pops while we are changing the queue
587        disable_interrupts();
588        uint_fast32_t last_size = ready_mutate_lock();
589
590                // Adjust the ready queue size
591                ready_queue_grow( &this, 0 );
592
593        // Unlock the RWlock
594        ready_mutate_unlock( last_size );
595        enable_interrupts_noPoll(); // Don't poll, could be in main cluster
596}
597
598void ^?{}(cluster & this) {
599        destroy(this.io.arbiter);
600
601        // Lock the RWlock so no-one pushes/pops while we are changing the queue
602        disable_interrupts();
603        uint_fast32_t last_size = ready_mutate_lock();
604
605                // Adjust the ready queue size
606                ready_queue_shrink( &this, 0 );
607
608        // Unlock the RWlock
609        ready_mutate_unlock( last_size );
610        enable_interrupts_noPoll(); // Don't poll, could be in main cluster
611
612        #if !defined(__CFA_NO_STATISTICS__)
613                if( 0 != this.print_stats ) {
614                        __print_stats( this.stats, this.print_stats, "Cluster", this.name, (void*)&this );
615                }
616                free( this.stats );
617        #endif
618
619        unregister(this);
620}
621
622//=============================================================================================
623// Miscellaneous Initialization
624//=============================================================================================
625//-----------------------------------------------------------------------------
626// Global Queues
627static void doregister( cluster     & cltr ) {
628        lock      ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2);
629        push_front( __cfa_dbg_global_clusters.list, cltr );
630        unlock    ( __cfa_dbg_global_clusters.lock );
631}
632
633static void unregister( cluster     & cltr ) {
634        lock  ( __cfa_dbg_global_clusters.lock __cfaabi_dbg_ctx2);
635        remove( __cfa_dbg_global_clusters.list, cltr );
636        unlock( __cfa_dbg_global_clusters.lock );
637}
638
639void doregister( cluster * cltr, $thread & thrd ) {
640        lock      (cltr->thread_list_lock __cfaabi_dbg_ctx2);
641        cltr->nthreads += 1;
642        push_front(cltr->threads, thrd);
643        unlock    (cltr->thread_list_lock);
644}
645
646void unregister( cluster * cltr, $thread & thrd ) {
647        lock  (cltr->thread_list_lock __cfaabi_dbg_ctx2);
648        remove(cltr->threads, thrd );
649        cltr->nthreads -= 1;
650        unlock(cltr->thread_list_lock);
651}
652
653static void check( int ret, const char func[] ) {
654        if ( ret ) {                                                                            // pthread routines return errno values
655                abort( "%s : internal error, error(%d) %s.", func, ret, strerror( ret ) );
656        } // if
657} // Abort
658
659void * __create_pthread( pthread_t * pthread, void * (*start)(void *), void * arg ) {
660        pthread_attr_t attr;
661
662        check( pthread_attr_init( &attr ), "pthread_attr_init" ); // initialize attribute
663
664        size_t stacksize;
665        // default stack size, normally defined by shell limit
666        check( pthread_attr_getstacksize( &attr, &stacksize ), "pthread_attr_getstacksize" );
667        assert( stacksize >= PTHREAD_STACK_MIN );
668
669        void * stack;
670        #if CFA_PROCESSOR_USE_MMAP
671                stacksize = ceiling( stacksize, __page_size ) + __page_size;
672                stack = mmap(0p, stacksize, __map_prot, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
673                if(stack == ((void*)-1)) {
674                        abort( "pthread stack creation : internal error, mmap failure, error(%d) %s.", errno, strerror( errno ) );
675                }
676                if ( mprotect( stack, __page_size, PROT_NONE ) == -1 ) {
677                        abort( "pthread stack creation : internal error, mprotect failure, error(%d) %s.", errno, strerror( errno ) );
678                } // if
679        #else
680                __cfaabi_dbg_debug_do(
681                        stack = memalign( __page_size, stacksize + __page_size );
682                        // pthread has no mechanism to create the guard page in user supplied stack.
683                        if ( mprotect( stack, __page_size, PROT_NONE ) == -1 ) {
684                                abort( "mprotect : internal error, mprotect failure, error(%d) %s.", errno, strerror( errno ) );
685                        } // if
686                );
687                __cfaabi_dbg_no_debug_do(
688                        stack = malloc( stacksize );
689                );
690        #endif
691
692
693        check( pthread_attr_setstack( &attr, stack, stacksize ), "pthread_attr_setstack" );
694
695        check( pthread_create( pthread, &attr, start, arg ), "pthread_create" );
696        return stack;
697}
698
699void __destroy_pthread( pthread_t pthread, void * stack, void ** retval ) {
700        int err = pthread_join( pthread, retval );
701        if( err != 0 ) abort("KERNEL ERROR: joining pthread %p caused error %s\n", (void*)pthread, strerror(err));
702
703        #if CFA_PROCESSOR_USE_MMAP
704                pthread_attr_t attr;
705
706                check( pthread_attr_init( &attr ), "pthread_attr_init" ); // initialize attribute
707
708                size_t stacksize;
709                // default stack size, normally defined by shell limit
710                check( pthread_attr_getstacksize( &attr, &stacksize ), "pthread_attr_getstacksize" );
711                assert( stacksize >= PTHREAD_STACK_MIN );
712                stacksize += __page_size;
713
714                if(munmap(stack, stacksize) == -1) {
715                        abort( "pthread stack destruction : internal error, munmap failure, error(%d) %s.", errno, strerror( errno ) );
716                }
717        #else
718                __cfaabi_dbg_debug_do(
719                        // pthread has no mechanism to create the guard page in user supplied stack.
720                        if ( mprotect( stack, __page_size, __map_prot ) == -1 ) {
721                                abort( "mprotect : internal error, mprotect failure, error(%d) %s.", errno, strerror( errno ) );
722                        } // if
723                );
724                free( stack );
725        #endif
726}
727
728extern "C" {
729        char * strerror(int);
730}
731#define CHECKED(x) { int err = x; if( err != 0 ) abort("KERNEL ERROR: Operation \"" #x "\" return error %d - %s\n", err, strerror(err)); }
732
733static void ?{}(__bin_sem_t & this) with( this ) {
734        // Create the mutex with error checking
735        pthread_mutexattr_t mattr;
736        pthread_mutexattr_init( &mattr );
737        pthread_mutexattr_settype( &mattr, PTHREAD_MUTEX_ERRORCHECK_NP);
738        pthread_mutex_init(&lock, &mattr);
739
740        pthread_cond_init (&cond, (const pthread_condattr_t *)0p);  // workaround trac#208: cast should not be required
741        val = 0;
742}
743
744static void ^?{}(__bin_sem_t & this) with( this ) {
745        CHECKED( pthread_mutex_destroy(&lock) );
746        CHECKED( pthread_cond_destroy (&cond) );
747}
748
749#undef CHECKED
750
751#if defined(__CFA_WITH_VERIFY__)
752static bool verify_fwd_bck_rng(void) {
753        __cfaabi_tls.ready_rng.fwd_seed = 25214903917_l64u * (rdtscl() ^ (uintptr_t)&verify_fwd_bck_rng);
754
755        unsigned values[10];
756        for(i; 10) {
757                values[i] = __tls_rand_fwd();
758        }
759
760        __tls_rand_advance_bck();
761
762        for ( i; 9 -~= 0 ) {
763                if(values[i] != __tls_rand_bck()) {
764                        return false;
765                }
766        }
767
768        return true;
769}
770#endif
Note: See TracBrowser for help on using the repository browser.