source: libcfa/src/concurrency/coroutine.cfa @ ccb8c8a

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since ccb8c8a was 97229d6, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Changed stack creation to toggle between mmap and malloc based on the defines CFA_COROUTINE_USE_MMAP and CFA_PROCESSOR_USE_MMAP

  • Property mode set to 100644
File size: 9.3 KB
RevLine 
[6a3d2e7]1//
2// Cforall Version 1.0.0 Copyright (C) 2016 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
[75a17f1]7// coroutine.c --
[6a3d2e7]8//
9// Author           : Thierry Delisle
10// Created On       : Mon Nov 28 12:27:26 2016
[6b0b624]11// Last Modified By : Peter A. Buhr
[9b0c3ec5]12// Last Modified On : Fri Oct 23 23:05:24 2020
13// Update Count     : 22
[6a3d2e7]14//
15
[2026bb6]16#define __cforall_thread__
17
[58b6d1b]18#include "coroutine.hfa"
[bd98b58]19
[6a3d2e7]20#include <stddef.h>
21#include <malloc.h>
22#include <errno.h>
23#include <string.h>
24#include <unistd.h>
[ada0246d]25#include <sys/mman.h>                                                                   // mprotect
[76e069f]26#include <unwind.h>
[6a3d2e7]27
[73abe95]28#include "kernel_private.hfa"
[c960331]29#include "exception.hfa"
[bfcf6b9]30#include "math.hfa"
[6a3d2e7]31
[97229d6]32#define CFA_COROUTINE_USE_MMAP 0
33
[6a3d2e7]34#define __CFA_INVOKE_PRIVATE__
35#include "invoke.h"
36
[76e069f]37extern "C" {
[ac2b598]38        void _CtxCoroutine_Unwind(struct _Unwind_Exception * storage, struct $coroutine *) __attribute__ ((__noreturn__));
[b2f6113]39        static void _CtxCoroutine_UnwindCleanup(_Unwind_Reason_Code, struct _Unwind_Exception *) __attribute__ ((__noreturn__));
40        static void _CtxCoroutine_UnwindCleanup(_Unwind_Reason_Code, struct _Unwind_Exception *) {
41                abort();
42        }
[f019069]43
44        extern void CtxRet( struct __stack_context_t * to ) asm ("CtxRet") __attribute__ ((__noreturn__));
[76e069f]45}
46
[1c01c58]47//-----------------------------------------------------------------------------
[69c5c00]48FORALL_DATA_INSTANCE(CoroutineCancelled, (dtype coroutine_t), (coroutine_t))
[1c01c58]49
50forall(dtype T)
51void mark_exception(CoroutineCancelled(T) *) {}
52
[69c5c00]53forall(dtype T)
[1c01c58]54void copy(CoroutineCancelled(T) * dst, CoroutineCancelled(T) * src) {
[342be43]55        dst->virtual_table = src->virtual_table;
[1c01c58]56        dst->the_coroutine = src->the_coroutine;
57        dst->the_exception = src->the_exception;
58}
59
60forall(dtype T)
61const char * msg(CoroutineCancelled(T) *) {
62        return "CoroutineCancelled(...)";
63}
64
65// This code should not be inlined. It is the error path on resume.
66forall(dtype T | is_coroutine(T))
67void __cfaehm_cancelled_coroutine( T & cor, $coroutine * desc ) {
68        verify( desc->cancellation );
69        desc->state = Cancelled;
[342be43]70        exception_t * except = __cfaehm_cancellation_exception( desc->cancellation );
[1c01c58]71
[69c5c00]72        // TODO: Remove explitate vtable set once trac#186 is fixed.
[1c01c58]73        CoroutineCancelled(T) except;
[69c5c00]74        except.virtual_table = &get_exception_vtable(&except);
[1c01c58]75        except.the_coroutine = &cor;
76        except.the_exception = except;
77        throwResume except;
78
79        except->virtual_table->free( except );
80        free( desc->cancellation );
81        desc->cancellation = 0p;
82}
83
[6a3d2e7]84//-----------------------------------------------------------------------------
85// Global state variables
86
87// minimum feasible stack size in bytes
[290553a]88static const size_t MinStackSize = 1000;
[b2f6113]89extern size_t __page_size;                              // architecture pagesize HACK, should go in proper runtime singleton
90
91void __stack_prepare( __stack_info_t * this, size_t create_size );
[bfcf6b9]92void __stack_clean  ( __stack_info_t * this );
[6a3d2e7]93
94//-----------------------------------------------------------------------------
95// Coroutine ctors and dtors
[b2f6113]96void ?{}( __stack_info_t & this, void * storage, size_t storageSize ) {
97        this.storage   = (__stack_t *)storage;
98
99        // Did we get a piece of storage ?
100        if (this.storage || storageSize != 0) {
101                // We either got a piece of storage or the user asked for a specific size
102                // Immediately create the stack
103                // (This is slightly unintuitive that non-default sized coroutines create are eagerly created
104                // but it avoids that all coroutines carry an unnecessary size)
105                verify( storageSize != 0 );
106                __stack_prepare( &this, storageSize );
107        }
[6a3d2e7]108}
109
[b2f6113]110void ^?{}(__stack_info_t & this) {
[8c01e1b]111        bool userStack = ((intptr_t)this.storage & 0x1) != 0;
112        if ( ! userStack && this.storage ) {
[bfcf6b9]113                __stack_clean( &this );
[b2f6113]114        }
[6a3d2e7]115}
116
[ac2b598]117void ?{}( $coroutine & this, const char name[], void * storage, size_t storageSize ) with( this ) {
[524627e]118        (this.context){0p, 0p};
[b2f6113]119        (this.stack){storage, storageSize};
120        this.name = name;
121        state = Start;
[524627e]122        starter = 0p;
123        last = 0p;
124        cancellation = 0p;
[6a3d2e7]125}
126
[ac2b598]127void ^?{}($coroutine& this) {
[3623f9d]128        if(this.state != Halted && this.state != Start && this.state != Primed) {
[be73f30]129                $coroutine * src = active_coroutine();
[ac2b598]130                $coroutine * dst = &this;
[b2f6113]131
132                struct _Unwind_Exception storage;
133                storage.exception_class = -1;
134                storage.exception_cleanup = _CtxCoroutine_UnwindCleanup;
135                this.cancellation = &storage;
136                this.last = src;
137
138                // not resuming self ?
139                if ( src == dst ) {
140                        abort( "Attempt by coroutine %.256s (%p) to terminate itself.\n", src->name, src );
141                }
142
[ac2b598]143                $ctx_switch( src, dst );
[b2f6113]144        }
[76e069f]145}
[6a3d2e7]146
147// Part of the Public API
148// Not inline since only ever called once per coroutine
149forall(dtype T | is_coroutine(T))
[83a071f9]150void prime(T& cor) {
[ac2b598]151        $coroutine* this = get_coroutine(cor);
[b2f6113]152        assert(this->state == Start);
[6a3d2e7]153
[b2f6113]154        this->state = Primed;
155        resume(cor);
[6a3d2e7]156}
157
[b2f6113]158[void *, size_t] __stack_alloc( size_t storageSize ) {
[0030ada3]159        const size_t stack_data_size = libCeiling( sizeof(__stack_t), 16 ); // minimum alignment
[b2f6113]160        assert(__page_size != 0l);
161        size_t size = libCeiling( storageSize, 16 ) + stack_data_size;
[bfcf6b9]162        size = ceiling(size, __page_size);
[b2f6113]163
164        // If we are running debug, we also need to allocate a guardpage to catch stack overflows.
165        void * storage;
[97229d6]166        #if CFA_COROUTINE_USE_MMAP
167                storage = mmap(0p, size + __page_size, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
168                if(storage == ((void*)-1)) {
169                        abort( "coroutine stack creation : internal error, mmap failure, error(%d) %s.", errno, strerror( errno ) );
170                }
171                if ( mprotect( storage, __page_size, PROT_NONE ) == -1 ) {
172                        abort( "coroutine stack creation : internal error, mprotect failure, error(%d) %s.", errno, strerror( errno ) );
173                } // if
174                storage = (void *)(((intptr_t)storage) + __page_size);
175        #else
176                __cfaabi_dbg_debug_do(
177                        storage = memalign( __page_size, size + __page_size );
178                );
179                __cfaabi_dbg_no_debug_do(
180                        storage = (void*)malloc(size);
181                );
182
183                __cfaabi_dbg_debug_do(
184                        if ( mprotect( storage, __page_size, PROT_NONE ) == -1 ) {
185                                abort( "__stack_alloc : internal error, mprotect failure, error(%d) %s.", (int)errno, strerror( (int)errno ) );
186                        }
187                        storage = (void *)(((intptr_t)storage) + __page_size);
188                );
189        #endif
190        __cfaabi_dbg_print_safe("Kernel : Created stack %p of size %zu\n", storage, size);
[b2f6113]191
192        verify( ((intptr_t)storage & (libAlign() - 1)) == 0ul );
193        return [storage, size];
194}
[6a3d2e7]195
[bfcf6b9]196void __stack_clean  ( __stack_info_t * this ) {
197        size_t size = ((intptr_t)this->storage->base) - ((intptr_t)this->storage->limit) + sizeof(__stack_t);
198        void * storage = this->storage->limit;
199
[97229d6]200        #if CFA_COROUTINE_USE_MMAP
201                storage = (void *)(((intptr_t)storage) - __page_size);
202                if(munmap(storage, size + __page_size) == -1) {
203                        abort( "coroutine stack destruction : internal error, munmap failure, error(%d) %s.", errno, strerror( errno ) );
204                }
205        #else
206                __cfaabi_dbg_debug_do(
207                        storage = (char*)(storage) - __page_size;
208                        if ( mprotect( storage, __page_size, PROT_READ | PROT_WRITE ) == -1 ) {
209                                abort( "(coStack_t *)%p.^?{}() : internal error, mprotect failure, error(%d) %s.", &this, errno, strerror( errno ) );
210                        }
211                );
212
213                free( storage );
214        #endif
215        __cfaabi_dbg_print_safe("Kernel : Deleting stack %p\n", storage);
[bfcf6b9]216}
217
[b2f6113]218void __stack_prepare( __stack_info_t * this, size_t create_size ) {
[0030ada3]219        const size_t stack_data_size = libCeiling( sizeof(__stack_t), 16 ); // minimum alignment
[b2f6113]220        bool userStack;
221        void * storage;
222        size_t size;
223        if ( !this->storage ) {
224                userStack = false;
225                [storage, size] = __stack_alloc( create_size );
226        } else {
227                userStack = true;
[69a61d2]228                __cfaabi_dbg_print_safe("Kernel : stack obj %p using user stack %p(%zd bytes)\n", this, this->storage, (intptr_t)this->storage->limit - (intptr_t)this->storage->base);
[b2f6113]229
230                // The stack must be aligned, advance the pointer to the next align data
231                storage = (void*)libCeiling( (intptr_t)this->storage, libAlign());
232
233                // The size needs to be shrinked to fit all the extra data structure and be aligned
234                ptrdiff_t diff = (intptr_t)storage - (intptr_t)this->storage;
235                size = libFloor(create_size - stack_data_size - diff, libAlign());
236        } // if
[9b0c3ec5]237        assertf( size >= MinStackSize, "Stack size %zd provides less than minimum of %zd bytes for a stack.", size, MinStackSize );
[b2f6113]238
[bfcf6b9]239        this->storage = (__stack_t *)((intptr_t)storage + size - sizeof(__stack_t));
[b2f6113]240        this->storage->limit = storage;
[bfcf6b9]241        this->storage->base  = (void*)((intptr_t)storage + size - sizeof(__stack_t));
[1c01c58]242        this->storage->exception_context.top_resume = 0p;
243        this->storage->exception_context.current_exception = 0p;
[ffe2fad]244        __attribute__((may_alias)) intptr_t * istorage = (intptr_t*)&this->storage;
245        *istorage |= userStack ? 0x1 : 0x0;
[6a3d2e7]246}
247
[0c92c9f]248// We need to call suspend from invoke.c, so we expose this wrapper that
249// is not inline (We can't inline Cforall in C)
250extern "C" {
[ac2b598]251        void __cfactx_cor_leave( struct $coroutine * src ) {
252                $coroutine * starter = src->cancellation != 0 ? src->last : src->starter;
[b2f6113]253
254                src->state = Halted;
255
256                assertf( starter != 0,
257                        "Attempt to suspend/leave coroutine \"%.256s\" (%p) that has never been resumed.\n"
258                        "Possible cause is a suspend executed in a member called by a coroutine user rather than by the coroutine main.",
259                        src->name, src );
260                assertf( starter->state != Halted,
261                        "Attempt by coroutine \"%.256s\" (%p) to suspend/leave back to terminated coroutine \"%.256s\" (%p).\n"
262                        "Possible cause is terminated coroutine's main routine has already returned.",
263                        src->name, src, starter->name, starter );
264
[ac2b598]265                $ctx_switch( src, starter );
[b2f6113]266        }
[09f357ec]267
[ac2b598]268        struct $coroutine * __cfactx_cor_finish(void) {
[be73f30]269                struct $coroutine * cor = active_coroutine();
[09f357ec]270
271                if(cor->state == Primed) {
[427854b]272                        __cfactx_suspend();
[09f357ec]273                }
274
275                cor->state = Active;
276
277                return cor;
278        }
[0c92c9f]279}
280
[6a3d2e7]281// Local Variables: //
282// mode: c //
283// tab-width: 4 //
[4aa2fb2]284// End: //
Note: See TracBrowser for help on using the repository browser.