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

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since fd54fef was fd54fef, checked in by Michael Brooks <mlbrooks@…>, 3 years ago

Converting the project to use the new syntax for otype, dtype and ttytpe.

Changed prelude (gen), libcfa and test suite to use it. Added a simple deprecation rule of the old syntax to the parser; we might wish to support both syntaxes "officially," like with an extra CLI switch, but this measure should serve as a simple reminder for our team to try the new syntax.

  • 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
[dd92fe9]12// Last Modified On : Tue Dec 15 12:06:04 2020
13// Update Count     : 23
[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//-----------------------------------------------------------------------------
[fd54fef]48FORALL_DATA_INSTANCE(CoroutineCancelled, (coroutine_t &), (coroutine_t))
[1c01c58]49
[fd54fef]50forall(T &)
[1c01c58]51void mark_exception(CoroutineCancelled(T) *) {}
52
[fd54fef]53forall(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
[fd54fef]60forall(T &)
[1c01c58]61const char * msg(CoroutineCancelled(T) *) {
62        return "CoroutineCancelled(...)";
63}
64
65// This code should not be inlined. It is the error path on resume.
[fd54fef]66forall(T & | is_coroutine(T))
[1c01c58]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
[dd92fe9]90extern int __map_prot;
[b2f6113]91
92void __stack_prepare( __stack_info_t * this, size_t create_size );
[bfcf6b9]93void __stack_clean  ( __stack_info_t * this );
[6a3d2e7]94
95//-----------------------------------------------------------------------------
96// Coroutine ctors and dtors
[b2f6113]97void ?{}( __stack_info_t & this, void * storage, size_t storageSize ) {
98        this.storage   = (__stack_t *)storage;
99
100        // Did we get a piece of storage ?
101        if (this.storage || storageSize != 0) {
102                // We either got a piece of storage or the user asked for a specific size
103                // Immediately create the stack
104                // (This is slightly unintuitive that non-default sized coroutines create are eagerly created
105                // but it avoids that all coroutines carry an unnecessary size)
106                verify( storageSize != 0 );
107                __stack_prepare( &this, storageSize );
108        }
[6a3d2e7]109}
110
[b2f6113]111void ^?{}(__stack_info_t & this) {
[8c01e1b]112        bool userStack = ((intptr_t)this.storage & 0x1) != 0;
113        if ( ! userStack && this.storage ) {
[bfcf6b9]114                __stack_clean( &this );
[b2f6113]115        }
[6a3d2e7]116}
117
[ac2b598]118void ?{}( $coroutine & this, const char name[], void * storage, size_t storageSize ) with( this ) {
[524627e]119        (this.context){0p, 0p};
[b2f6113]120        (this.stack){storage, storageSize};
121        this.name = name;
122        state = Start;
[524627e]123        starter = 0p;
124        last = 0p;
125        cancellation = 0p;
[6a3d2e7]126}
127
[ac2b598]128void ^?{}($coroutine& this) {
[3623f9d]129        if(this.state != Halted && this.state != Start && this.state != Primed) {
[be73f30]130                $coroutine * src = active_coroutine();
[ac2b598]131                $coroutine * dst = &this;
[b2f6113]132
133                struct _Unwind_Exception storage;
134                storage.exception_class = -1;
135                storage.exception_cleanup = _CtxCoroutine_UnwindCleanup;
136                this.cancellation = &storage;
137                this.last = src;
138
139                // not resuming self ?
140                if ( src == dst ) {
141                        abort( "Attempt by coroutine %.256s (%p) to terminate itself.\n", src->name, src );
142                }
143
[ac2b598]144                $ctx_switch( src, dst );
[b2f6113]145        }
[76e069f]146}
[6a3d2e7]147
148// Part of the Public API
149// Not inline since only ever called once per coroutine
[fd54fef]150forall(T & | is_coroutine(T))
[83a071f9]151void prime(T& cor) {
[ac2b598]152        $coroutine* this = get_coroutine(cor);
[b2f6113]153        assert(this->state == Start);
[6a3d2e7]154
[b2f6113]155        this->state = Primed;
156        resume(cor);
[6a3d2e7]157}
158
[b2f6113]159[void *, size_t] __stack_alloc( size_t storageSize ) {
[0030ada3]160        const size_t stack_data_size = libCeiling( sizeof(__stack_t), 16 ); // minimum alignment
[b2f6113]161        assert(__page_size != 0l);
162        size_t size = libCeiling( storageSize, 16 ) + stack_data_size;
[bfcf6b9]163        size = ceiling(size, __page_size);
[b2f6113]164
165        // If we are running debug, we also need to allocate a guardpage to catch stack overflows.
166        void * storage;
[97229d6]167        #if CFA_COROUTINE_USE_MMAP
168                storage = mmap(0p, size + __page_size, PROT_EXEC | PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
169                if(storage == ((void*)-1)) {
170                        abort( "coroutine stack creation : internal error, mmap failure, error(%d) %s.", errno, strerror( errno ) );
171                }
172                if ( mprotect( storage, __page_size, PROT_NONE ) == -1 ) {
173                        abort( "coroutine stack creation : internal error, mprotect failure, error(%d) %s.", errno, strerror( errno ) );
174                } // if
175                storage = (void *)(((intptr_t)storage) + __page_size);
176        #else
177                __cfaabi_dbg_debug_do(
178                        storage = memalign( __page_size, size + __page_size );
179                );
180                __cfaabi_dbg_no_debug_do(
181                        storage = (void*)malloc(size);
182                );
183
184                __cfaabi_dbg_debug_do(
185                        if ( mprotect( storage, __page_size, PROT_NONE ) == -1 ) {
186                                abort( "__stack_alloc : internal error, mprotect failure, error(%d) %s.", (int)errno, strerror( (int)errno ) );
187                        }
188                        storage = (void *)(((intptr_t)storage) + __page_size);
189                );
190        #endif
191        __cfaabi_dbg_print_safe("Kernel : Created stack %p of size %zu\n", storage, size);
[b2f6113]192
193        verify( ((intptr_t)storage & (libAlign() - 1)) == 0ul );
194        return [storage, size];
195}
[6a3d2e7]196
[bfcf6b9]197void __stack_clean  ( __stack_info_t * this ) {
198        size_t size = ((intptr_t)this->storage->base) - ((intptr_t)this->storage->limit) + sizeof(__stack_t);
199        void * storage = this->storage->limit;
200
[97229d6]201        #if CFA_COROUTINE_USE_MMAP
202                storage = (void *)(((intptr_t)storage) - __page_size);
203                if(munmap(storage, size + __page_size) == -1) {
204                        abort( "coroutine stack destruction : internal error, munmap failure, error(%d) %s.", errno, strerror( errno ) );
205                }
206        #else
207                __cfaabi_dbg_debug_do(
208                        storage = (char*)(storage) - __page_size;
[dd92fe9]209                        if ( mprotect( storage, __page_size, __map_prot ) == -1 ) {
[97229d6]210                                abort( "(coStack_t *)%p.^?{}() : internal error, mprotect failure, error(%d) %s.", &this, errno, strerror( errno ) );
211                        }
212                );
213
214                free( storage );
215        #endif
216        __cfaabi_dbg_print_safe("Kernel : Deleting stack %p\n", storage);
[bfcf6b9]217}
218
[b2f6113]219void __stack_prepare( __stack_info_t * this, size_t create_size ) {
[0030ada3]220        const size_t stack_data_size = libCeiling( sizeof(__stack_t), 16 ); // minimum alignment
[b2f6113]221        bool userStack;
222        void * storage;
223        size_t size;
224        if ( !this->storage ) {
225                userStack = false;
226                [storage, size] = __stack_alloc( create_size );
227        } else {
228                userStack = true;
[69a61d2]229                __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]230
231                // The stack must be aligned, advance the pointer to the next align data
232                storage = (void*)libCeiling( (intptr_t)this->storage, libAlign());
233
234                // The size needs to be shrinked to fit all the extra data structure and be aligned
235                ptrdiff_t diff = (intptr_t)storage - (intptr_t)this->storage;
236                size = libFloor(create_size - stack_data_size - diff, libAlign());
237        } // if
[9b0c3ec5]238        assertf( size >= MinStackSize, "Stack size %zd provides less than minimum of %zd bytes for a stack.", size, MinStackSize );
[b2f6113]239
[bfcf6b9]240        this->storage = (__stack_t *)((intptr_t)storage + size - sizeof(__stack_t));
[b2f6113]241        this->storage->limit = storage;
[bfcf6b9]242        this->storage->base  = (void*)((intptr_t)storage + size - sizeof(__stack_t));
[1c01c58]243        this->storage->exception_context.top_resume = 0p;
244        this->storage->exception_context.current_exception = 0p;
[ffe2fad]245        __attribute__((may_alias)) intptr_t * istorage = (intptr_t*)&this->storage;
246        *istorage |= userStack ? 0x1 : 0x0;
[6a3d2e7]247}
248
[0c92c9f]249// We need to call suspend from invoke.c, so we expose this wrapper that
250// is not inline (We can't inline Cforall in C)
251extern "C" {
[ac2b598]252        void __cfactx_cor_leave( struct $coroutine * src ) {
253                $coroutine * starter = src->cancellation != 0 ? src->last : src->starter;
[b2f6113]254
255                src->state = Halted;
256
257                assertf( starter != 0,
258                        "Attempt to suspend/leave coroutine \"%.256s\" (%p) that has never been resumed.\n"
259                        "Possible cause is a suspend executed in a member called by a coroutine user rather than by the coroutine main.",
260                        src->name, src );
261                assertf( starter->state != Halted,
262                        "Attempt by coroutine \"%.256s\" (%p) to suspend/leave back to terminated coroutine \"%.256s\" (%p).\n"
263                        "Possible cause is terminated coroutine's main routine has already returned.",
264                        src->name, src, starter->name, starter );
265
[ac2b598]266                $ctx_switch( src, starter );
[b2f6113]267        }
[09f357ec]268
[ac2b598]269        struct $coroutine * __cfactx_cor_finish(void) {
[be73f30]270                struct $coroutine * cor = active_coroutine();
[09f357ec]271
272                if(cor->state == Primed) {
[427854b]273                        __cfactx_suspend();
[09f357ec]274                }
275
276                cor->state = Active;
277
278                return cor;
279        }
[0c92c9f]280}
281
[6a3d2e7]282// Local Variables: //
283// mode: c //
284// tab-width: 4 //
[4aa2fb2]285// End: //
Note: See TracBrowser for help on using the repository browser.