source: libcfa/src/concurrency/coroutine.cfa@ 2dd0689

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 2dd0689 was 97229d6, checked in by Thierry Delisle <tdelisle@…>, 5 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
Line 
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//
7// coroutine.c --
8//
9// Author : Thierry Delisle
10// Created On : Mon Nov 28 12:27:26 2016
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Fri Oct 23 23:05:24 2020
13// Update Count : 22
14//
15
16#define __cforall_thread__
17
18#include "coroutine.hfa"
19
20#include <stddef.h>
21#include <malloc.h>
22#include <errno.h>
23#include <string.h>
24#include <unistd.h>
25#include <sys/mman.h> // mprotect
26#include <unwind.h>
27
28#include "kernel_private.hfa"
29#include "exception.hfa"
30#include "math.hfa"
31
32#define CFA_COROUTINE_USE_MMAP 0
33
34#define __CFA_INVOKE_PRIVATE__
35#include "invoke.h"
36
37extern "C" {
38 void _CtxCoroutine_Unwind(struct _Unwind_Exception * storage, struct $coroutine *) __attribute__ ((__noreturn__));
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 }
43
44 extern void CtxRet( struct __stack_context_t * to ) asm ("CtxRet") __attribute__ ((__noreturn__));
45}
46
47//-----------------------------------------------------------------------------
48FORALL_DATA_INSTANCE(CoroutineCancelled, (dtype coroutine_t), (coroutine_t))
49
50forall(dtype T)
51void mark_exception(CoroutineCancelled(T) *) {}
52
53forall(dtype T)
54void copy(CoroutineCancelled(T) * dst, CoroutineCancelled(T) * src) {
55 dst->virtual_table = src->virtual_table;
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;
70 exception_t * except = __cfaehm_cancellation_exception( desc->cancellation );
71
72 // TODO: Remove explitate vtable set once trac#186 is fixed.
73 CoroutineCancelled(T) except;
74 except.virtual_table = &get_exception_vtable(&except);
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
84//-----------------------------------------------------------------------------
85// Global state variables
86
87// minimum feasible stack size in bytes
88static const size_t MinStackSize = 1000;
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 );
92void __stack_clean ( __stack_info_t * this );
93
94//-----------------------------------------------------------------------------
95// Coroutine ctors and dtors
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 }
108}
109
110void ^?{}(__stack_info_t & this) {
111 bool userStack = ((intptr_t)this.storage & 0x1) != 0;
112 if ( ! userStack && this.storage ) {
113 __stack_clean( &this );
114 }
115}
116
117void ?{}( $coroutine & this, const char name[], void * storage, size_t storageSize ) with( this ) {
118 (this.context){0p, 0p};
119 (this.stack){storage, storageSize};
120 this.name = name;
121 state = Start;
122 starter = 0p;
123 last = 0p;
124 cancellation = 0p;
125}
126
127void ^?{}($coroutine& this) {
128 if(this.state != Halted && this.state != Start && this.state != Primed) {
129 $coroutine * src = active_coroutine();
130 $coroutine * dst = &this;
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
143 $ctx_switch( src, dst );
144 }
145}
146
147// Part of the Public API
148// Not inline since only ever called once per coroutine
149forall(dtype T | is_coroutine(T))
150void prime(T& cor) {
151 $coroutine* this = get_coroutine(cor);
152 assert(this->state == Start);
153
154 this->state = Primed;
155 resume(cor);
156}
157
158[void *, size_t] __stack_alloc( size_t storageSize ) {
159 const size_t stack_data_size = libCeiling( sizeof(__stack_t), 16 ); // minimum alignment
160 assert(__page_size != 0l);
161 size_t size = libCeiling( storageSize, 16 ) + stack_data_size;
162 size = ceiling(size, __page_size);
163
164 // If we are running debug, we also need to allocate a guardpage to catch stack overflows.
165 void * storage;
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);
191
192 verify( ((intptr_t)storage & (libAlign() - 1)) == 0ul );
193 return [storage, size];
194}
195
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
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);
216}
217
218void __stack_prepare( __stack_info_t * this, size_t create_size ) {
219 const size_t stack_data_size = libCeiling( sizeof(__stack_t), 16 ); // minimum alignment
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;
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);
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
237 assertf( size >= MinStackSize, "Stack size %zd provides less than minimum of %zd bytes for a stack.", size, MinStackSize );
238
239 this->storage = (__stack_t *)((intptr_t)storage + size - sizeof(__stack_t));
240 this->storage->limit = storage;
241 this->storage->base = (void*)((intptr_t)storage + size - sizeof(__stack_t));
242 this->storage->exception_context.top_resume = 0p;
243 this->storage->exception_context.current_exception = 0p;
244 __attribute__((may_alias)) intptr_t * istorage = (intptr_t*)&this->storage;
245 *istorage |= userStack ? 0x1 : 0x0;
246}
247
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" {
251 void __cfactx_cor_leave( struct $coroutine * src ) {
252 $coroutine * starter = src->cancellation != 0 ? src->last : src->starter;
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
265 $ctx_switch( src, starter );
266 }
267
268 struct $coroutine * __cfactx_cor_finish(void) {
269 struct $coroutine * cor = active_coroutine();
270
271 if(cor->state == Primed) {
272 __cfactx_suspend();
273 }
274
275 cor->state = Active;
276
277 return cor;
278 }
279}
280
281// Local Variables: //
282// mode: c //
283// tab-width: 4 //
284// End: //
Note: See TracBrowser for help on using the repository browser.