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

ADTarm-ehast-experimentalcleanup-dtorsenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since b2f6113 was b2f6113, checked in by tdelisle <tdelisle@…>, 5 years ago

Swapped memory storage for context and stack information inside the coroutine implementation

  • Property mode set to 100644
File size: 7.6 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
[b10affd]12// Last Modified On : Fri Mar 30 17:20:57 2018
13// Update Count     : 9
[6a3d2e7]14//
15
[58b6d1b]16#include "coroutine.hfa"
[bd98b58]17
[6a3d2e7]18extern "C" {
19#include <stddef.h>
20#include <malloc.h>
21#include <errno.h>
22#include <string.h>
23#include <unistd.h>
[76e069f]24// use this define to make unwind.h play nice, definetely a hack
25#define HIDE_EXPORTS
26#include <unwind.h>
27#undef HIDE_EXPORTS
[6a3d2e7]28#include <sys/mman.h>
29}
30
[73abe95]31#include "kernel_private.hfa"
[6a3d2e7]32
33#define __CFA_INVOKE_PRIVATE__
34#include "invoke.h"
35
[76e069f]36extern "C" {
[b2f6113]37        void _CtxCoroutine_Unwind(struct _Unwind_Exception * storage, struct coroutine_desc *) __attribute__ ((__noreturn__));
38        static void _CtxCoroutine_UnwindCleanup(_Unwind_Reason_Code, struct _Unwind_Exception *) __attribute__ ((__noreturn__));
39        static void _CtxCoroutine_UnwindCleanup(_Unwind_Reason_Code, struct _Unwind_Exception *) {
40                abort();
41        }
[76e069f]42}
43
[6a3d2e7]44//-----------------------------------------------------------------------------
45// Global state variables
46
47// minimum feasible stack size in bytes
48#define MinStackSize 1000
[b2f6113]49extern size_t __page_size;                              // architecture pagesize HACK, should go in proper runtime singleton
50
51void __stack_prepare( __stack_info_t * this, size_t create_size );
[6a3d2e7]52
53//-----------------------------------------------------------------------------
54// Coroutine ctors and dtors
[b2f6113]55void ?{}( __stack_info_t & this, void * storage, size_t storageSize ) {
56        this.storage   = (__stack_t *)storage;
57
58        // Did we get a piece of storage ?
59        if (this.storage || storageSize != 0) {
60                // We either got a piece of storage or the user asked for a specific size
61                // Immediately create the stack
62                // (This is slightly unintuitive that non-default sized coroutines create are eagerly created
63                // but it avoids that all coroutines carry an unnecessary size)
64                verify( storageSize != 0 );
65                __stack_prepare( &this, storageSize );
66        }
[6a3d2e7]67}
68
[b2f6113]69void ^?{}(__stack_info_t & this) {
70        if ( ! this.userStack && this.storage ) {
71                void * storage = (char*)(this.storage) - this.storage->size;
72                __cfaabi_dbg_debug_do(
73                        storage = (char*)(storage) - __page_size;
74                        if ( mprotect( storage, __page_size, PROT_READ | PROT_WRITE ) == -1 ) {
75                                abort( "(coStack_t *)%p.^?{}() : internal error, mprotect failure, error(%d) %s.", &this, errno, strerror( errno ) );
76                        }
77                );
78                __cfaabi_dbg_print_safe("Kernel : Deleting stack %p\n", storage);
79                free( storage );
80        }
[6a3d2e7]81}
82
[de6319f]83void ?{}( coroutine_desc & this, const char * name, void * storage, size_t storageSize ) with( this ) {
[b2f6113]84        (this.stack){storage, storageSize};
85        this.name = name;
86        state = Start;
87        starter = NULL;
88        last = NULL;
89        cancellation = NULL;
[6a3d2e7]90}
91
[76e069f]92void ^?{}(coroutine_desc& this) {
[b2f6113]93        if(this.state != Halted && this.state != Start) {
94                coroutine_desc * src = TL_GET( this_thread )->curr_cor;
95                coroutine_desc * dst = &this;
96
97                struct _Unwind_Exception storage;
98                storage.exception_class = -1;
99                storage.exception_cleanup = _CtxCoroutine_UnwindCleanup;
100                this.cancellation = &storage;
101                this.last = src;
102
103                // not resuming self ?
104                if ( src == dst ) {
105                        abort( "Attempt by coroutine %.256s (%p) to terminate itself.\n", src->name, src );
106                }
107
108                CoroutineCtxSwitch( src, dst );
109        }
[76e069f]110}
[6a3d2e7]111
112// Part of the Public API
113// Not inline since only ever called once per coroutine
114forall(dtype T | is_coroutine(T))
[83a071f9]115void prime(T& cor) {
[b2f6113]116        coroutine_desc* this = get_coroutine(cor);
117        assert(this->state == Start);
[6a3d2e7]118
[b2f6113]119        this->state = Primed;
120        resume(cor);
[6a3d2e7]121}
122
[0c92c9f]123// Wrapper for co
[c3acb841]124void CoroutineCtxSwitch(coroutine_desc* src, coroutine_desc* dst) {
[b2f6113]125        // Safety note : Preemption must be disabled since there is a race condition
126        // kernelTLS.this_thread->curr_cor and $rsp/$rbp must agree at all times
127        verify( TL_GET( preemption_state.enabled ) || TL_GET( this_processor )->do_terminate );
128        disable_interrupts();
[6a3d2e7]129
[b2f6113]130        // set state of current coroutine to inactive
131        src->state = src->state == Halted ? Halted : Inactive;
[de6319f]132
[b2f6113]133        // set new coroutine that task is executing
134        TL_GET( this_thread )->curr_cor = dst;
[de6319f]135
[b2f6113]136        // context switch to specified coroutine
137        CtxSwitch( &src->context, &dst->context );
138        // when CtxSwitch returns we are back in the src coroutine
[6a3d2e7]139
[b2f6113]140        // set state of new coroutine to active
141        src->state = Active;
[6a3d2e7]142
[b2f6113]143        enable_interrupts( __cfaabi_dbg_ctx );
144        verify( TL_GET( preemption_state.enabled ) || TL_GET( this_processor )->do_terminate );
[47ecf2b]145
[b2f6113]146        if( unlikely(src->cancellation != NULL) ) {
147                _CtxCoroutine_Unwind(src->cancellation, src);
148        }
149}
[6a3d2e7]150
[b2f6113]151[void *, size_t] __stack_alloc( size_t storageSize ) {
152        static const size_t stack_data_size = libCeiling( sizeof(__stack_t), 16 ); // minimum alignment
153        assert(__page_size != 0l);
154        size_t size = libCeiling( storageSize, 16 ) + stack_data_size;
155
156        // If we are running debug, we also need to allocate a guardpage to catch stack overflows.
157        void * storage;
158        __cfaabi_dbg_debug_do(
159                storage = memalign( __page_size, size + __page_size );
160        );
161        __cfaabi_dbg_no_debug_do(
162                storage = (void*)malloc(size);
163        );
164
165        __cfaabi_dbg_print_safe("Kernel : Created stack %p of size %zu\n", storage, size);
166        __cfaabi_dbg_debug_do(
167                if ( mprotect( storage, __page_size, PROT_NONE ) == -1 ) {
168                        abort( "__stack_alloc : internal error, mprotect failure, error(%d) %s.", (int)errno, strerror( (int)errno ) );
169                }
170                storage = (void *)(((intptr_t)storage) + __page_size);
171        );
172
173        verify( ((intptr_t)storage & (libAlign() - 1)) == 0ul );
174        return [storage, size];
175}
[6a3d2e7]176
[b2f6113]177void __stack_prepare( __stack_info_t * this, size_t create_size ) {
178        static const size_t stack_data_size = libCeiling( sizeof(__stack_t), 16 ); // minimum alignment
179        bool userStack;
180        void * storage;
181        size_t size;
182        if ( !this->storage ) {
183                userStack = false;
184                [storage, size] = __stack_alloc( create_size );
185        } else {
186                userStack = true;
187                __cfaabi_dbg_print_safe("Kernel : stack obj %p using user stack %p(%zu bytes)\n", this, this->storage, this->storage->size);
188
189                // The stack must be aligned, advance the pointer to the next align data
190                storage = (void*)libCeiling( (intptr_t)this->storage, libAlign());
191
192                // The size needs to be shrinked to fit all the extra data structure and be aligned
193                ptrdiff_t diff = (intptr_t)storage - (intptr_t)this->storage;
194                size = libFloor(create_size - stack_data_size - diff, libAlign());
195        } // if
196        assertf( size >= MinStackSize, "Stack size %zd provides less than minimum of %d bytes for a stack.", size, MinStackSize );
197
198        this->storage = (__stack_t *)((intptr_t)storage + size);
199        this->storage->size  = size;
200        this->storage->limit = storage;
201        this->storage->base  = (void*)((intptr_t)storage + size);
202        this->userStack = userStack;
[6a3d2e7]203}
204
[0c92c9f]205// We need to call suspend from invoke.c, so we expose this wrapper that
206// is not inline (We can't inline Cforall in C)
207extern "C" {
[b2f6113]208        void __suspend_internal(void) {
209                suspend();
210        }
211
212        void __leave_coroutine( coroutine_desc * src ) {
213                coroutine_desc * starter = src->cancellation != 0 ? src->last : src->starter;
214
215                src->state = Halted;
216
217                assertf( starter != 0,
218                        "Attempt to suspend/leave coroutine \"%.256s\" (%p) that has never been resumed.\n"
219                        "Possible cause is a suspend executed in a member called by a coroutine user rather than by the coroutine main.",
220                        src->name, src );
221                assertf( starter->state != Halted,
222                        "Attempt by coroutine \"%.256s\" (%p) to suspend/leave back to terminated coroutine \"%.256s\" (%p).\n"
223                        "Possible cause is terminated coroutine's main routine has already returned.",
224                        src->name, src, starter->name, starter );
225
226                CoroutineCtxSwitch( src, starter );
227        }
[0c92c9f]228}
229
[6a3d2e7]230// Local Variables: //
231// mode: c //
232// tab-width: 4 //
[4aa2fb2]233// End: //
Note: See TracBrowser for help on using the repository browser.