623 lines15.3 KB
1#include "coroutine.h"
2#include <assert.h>
3#include <setjmp.h>
4#include <stdbool.h>
5#include <stddef.h>
6#include <stdio.h>
7#include <stdlib.h>
8#include "cor_platform.h"
9
10
11static void *mustmalloc(size_t size){
12 void *p = malloc(size);
13 assert(p);
14 return p;
15}
16
17#define New(type, ...) (type##_ctor((type *)mustmalloc(sizeof(type), ## __VA_ARGS__)))
18#define Delete(ptr, type) ((ptr) ? (type##_dtor(ptr), free(ptr), (ptr) = NULL) : (void)0)
19static void Coroutine_RunNext();
20static void _Coroutine_Continue(Coroutine *cor, void *value, bool early);
21
22///////////////////////////////////////////////////////////////////////////////
23// 2-way linked lists...
24//
25// Brought inline here to avoid namespace polution
26///////////////////////////////////////////////////////////////////////////////
27
28typedef struct List_Link List_Link;
29struct List_Link {
30 List_Link *next;
31 List_Link *prev;
32};
33
34typedef struct List_Head List_Head;
35struct List_Head {
36 union {
37 struct {
38 List_Link link;
39 List_Link *filler;
40 } fwd;
41 struct {
42 List_Link *filler;
43 List_Link link;
44 } back;
45 };
46};
47
48
49static inline bool List_IsEmpty(
50 const List_Head *list
51){
52 return list->fwd.link.next == &list->back.link;
53}
54
55
56static inline List_Link *List_GetHead(
57 const List_Head *list
58){
59 return List_IsEmpty(list) ? NULL : list->fwd.link.next;
60}
61
62
63// static inline List_Link *List_GetTail(
64// const List_Head *list
65// ){
66// return List_IsEmpty(list) ? NULL : list->back.link.prev;
67// }
68
69
70#define OFFSETOF(Container, Field) ((char *)&((Container *)4)->Field - (char *)(Container *)4)
71#define List_Link_Container(Container, Link, link) ((Container *)((char *)(link) - OFFSETOF(Container, Link)))
72
73
74static inline void List_Init(
75 List_Head *list
76){
77 list->fwd.link.next = &list->back.link;
78 list->fwd.link.prev = NULL;
79 list->back.link.prev = &list->fwd.link;
80}
81
82
83static inline void List_AddHead(
84 List_Head *list,
85 List_Link *link
86){
87 List_Link *first = list->fwd.link.next;
88 link->next = first;
89 link->prev = &list->fwd.link;
90 first->prev = link;
91 list->fwd.link.next = link;
92}
93
94
95static inline void List_AddTail(
96 List_Head *list,
97 List_Link *link
98){
99 List_Link *last = list->back.link.prev;
100 link->prev = last;
101 link->next = &list->back.link;
102 last->next = link;
103 list->back.link.prev = link;
104}
105
106
107static inline void List_Remove(
108 List_Link *link
109){
110 link->prev->next = link->next;
111 link->next->prev = link->prev;
112}
113
114///////////////////////////////////////////////////////////////////////////////
115// ...2-way linked lists
116///////////////////////////////////////////////////////////////////////////////
117
118typedef struct Coroutines Coroutines;
119
120enum {
121 Coroutines_Idle,
122 Coroutines_Starting,
123 Coroutines_Started,
124 Coroutines_Active,
125 Coroutines_Stopping
126};
127
128enum {
129 Chunk_Initial,
130 Chunk_Create,
131 Chunk_Enter
132};
133
134typedef enum Coroutine_State {
135 Coroutine_Constructing,
136 Coroutine_Free,
137 Coroutine_Idle,
138 Coroutine_Running,
139 Coroutine_Waiting,
140 Coroutine_Complete
141} Coroutine_State;
142
143enum {
144 Coroutines_Init,
145 Coroutines_AllocatedChunk,
146 Coroutines_CoroutineComplete,
147};
148
149struct Coroutine {
150 Coroutines *coroutines; // so can work with it off-thread
151 List_Link link; // for whichever list it's on
152 jmp_buf buf; // how to get back to it
153 unsigned char *guard; // where the stack overrun guard is
154 Coroutine_Start start; // entry point
155 void *entry_param; // to pass to start
156 void *value; // yielded/returned
157 Coroutine_State state;
158};
159
160struct Coroutines {
161 _Cor_Mutex mutex;
162 jmp_buf controller; // to return from Coroutine_Run
163 jmp_buf chunk_allocated;// for chunk allocation
164 unsigned char *guard; // the stack guard for the startup sequence
165
166 // singletons
167 Coroutine *tip; // top of stack chunk
168 Coroutine *active; // currently running coroutine
169 Coroutine *primary; // Coroutine_Run coroutine
170
171 // lists
172 List_Head free;
173 List_Head inactive; // idle or complete
174 List_Head runable; // running or waiting to run
175 List_Head waiting; // yielded / waiting to run
176 _Cor_Mutex waiting_mutex;
177
178 // Summary of the system
179 Coroutine_Report report;
180
181 // state
182 char state;
183};
184
185_Cor_thread_local Coroutines *g_c;
186
187static void stack_chunk_chunk(Coroutine *parent);
188static void stack_chunk_base(Coroutine *parent, unsigned char *guard);
189
190
191// Check whether the guard is intact
192static inline bool Check_Guard(
193 unsigned char *guard
194){
195 return guard[0] == 0xde &&
196 guard[1] == 0xad &&
197 guard[2] == 0xbe &&
198 guard[3] == 0xef;
199}
200
201
202static void Coroutine_PrimeStackChunks()
203{
204 unsigned char chunk_of_stack[COROUTINE_STARTUP_STACK_SIZE];
205 for (int i = 0; i < COROUTINE_STARTUP_STACK_SIZE-3; i += 4){
206 chunk_of_stack[i+0] = 0xde;
207 chunk_of_stack[i+1] = 0xad;
208 chunk_of_stack[i+2] = 0xbe;
209 chunk_of_stack[i+3] = 0xef;
210 }
211 assert(Check_Guard(chunk_of_stack));
212
213 // Stacks grow down in memory (almost always), so if the caller of this function changes
214 // the guard before entering the coroutine system, it has overrun the startup stack
215 g_c->guard = chunk_of_stack;
216
217 stack_chunk_base(NULL, NULL);
218}
219
220
221static void stack_chunk_chunk(
222 Coroutine *parent
223){
224 unsigned char chunk_of_stack[COROUTINE_STACK_SIZE];
225 for (int i = 0; i < COROUTINE_STACK_SIZE-3; i += 4){
226 chunk_of_stack[i+0] = 0xde;
227 chunk_of_stack[i+1] = 0xad;
228 chunk_of_stack[i+2] = 0xbe;
229 chunk_of_stack[i+3] = 0xef;
230 }
231 stack_chunk_base(parent, chunk_of_stack);
232}
233
234
235static void stack_chunk_base(
236 Coroutine *parent,
237 unsigned char *guard
238){
239 Coroutine here;
240 here.state = Coroutine_Constructing;
241 switch (setjmp(here.buf)) {
242 case Chunk_Initial:
243 // got here for the first time
244 // parent now has a chunk_of_stack - add it to the free list
245 if (parent) {
246 assert(parent->state == Coroutine_Constructing);
247 assert(Check_Guard(guard));
248 parent->guard = guard;
249 parent->state = Coroutine_Free;
250 List_AddHead(&g_c->free, &parent->link);
251 g_c->report.coroutines_pool_size += 1;
252 }
253 // note that here is the tip of the chunk-claim stack
254 here.coroutines = g_c;
255 g_c->tip = &here;
256
257 // return to the coroutine allocator
258 longjmp(g_c->chunk_allocated, 1);
259 case Chunk_Create:
260 // request to create a new chunk on the stack
261 assert(here.state == Coroutine_Constructing);
262 stack_chunk_chunk(&here);
263 assert(false);
264 case Chunk_Enter:
265 // request to start a coroutine (ie use the chunk for a coroutine)
266 // arrive here with mutex locked
267 assert(here.state == Coroutine_Running);
268 g_c->active = &here;
269 _Cor_Mutex_Unlock(&g_c->mutex);
270 here.value = here.start(here.entry_param);
271
272 // check the guard
273 if (!Check_Guard(here.guard)){
274 printf("Coroutine has overrun its stack - checked after returning from coroutine function\n");
275 exit(EXIT_FAILURE);
276 }
277
278 _Cor_Mutex_Lock(&g_c->mutex);
279 g_c->active = NULL;
280 assert(here.state == Coroutine_Running);
281 List_Remove(&here.link);
282 here.state = Coroutine_Complete;
283 List_AddTail(&g_c->inactive, &here.link);
284 // coroutine has completed
285 if (g_c->primary == &here) {
286 // if primary coroutine - return to Coroutine_Run
287 longjmp(g_c->controller, Coroutines_CoroutineComplete);
288 }
289 _Cor_Mutex_Unlock(&g_c->mutex);
290 Coroutine_RunNext();
291 assert(false);
292 }
293}
294
295
296static void Coroutine_RunNext()
297{
298 // arrive here with mutex unlocked
299 _Cor_Mutex_Lock(&g_c->waiting_mutex);
300 _Cor_Mutex_Lock(&g_c->mutex);
301 Coroutine *next = List_Link_Container(Coroutine, link, List_GetHead(&g_c->runable));
302 assert(next->state == Coroutine_Running);
303 longjmp(next->buf, Chunk_Enter);
304 assert(false);
305}
306
307
308void Coroutine_StartSystem()
309{
310 assert(!g_c);
311 g_c = mustmalloc(sizeof(Coroutines));
312
313 g_c->state = Coroutines_Starting;
314
315 _Cor_Mutex_ctor(&g_c->mutex);
316
317 g_c->tip = NULL;
318 g_c->active = NULL;
319
320 List_Init(&g_c->free);
321 List_Init(&g_c->inactive);
322 List_Init(&g_c->runable);
323 List_Init(&g_c->waiting);
324 _Cor_Mutex_ctor(&g_c->waiting_mutex);
325 _Cor_Mutex_Lock(&g_c->waiting_mutex);
326
327 g_c->report.coroutines_created = 0;
328 g_c->report.coroutines_pool_size = 0;
329 g_c->report.lowest_headroom = COROUTINE_STACK_SIZE;
330
331 // prime the chunk system
332 if (!setjmp(g_c->chunk_allocated)){
333 Coroutine_PrimeStackChunks();
334 assert(false);
335 }
336
337 assert(g_c->state == Coroutines_Starting);
338 g_c->state = Coroutines_Started;
339}
340
341
342Coroutine_Report Coroutine_StopSystem()
343{
344 _Cor_Mutex_Lock(&g_c->mutex);
345 assert(g_c->state == Coroutines_Started);
346 g_c->state = Coroutines_Stopping;
347
348 int stackminheadroom = COROUTINE_STACK_SIZE;
349 for (List_Link *link = g_c->free.fwd.link.next; link->next; link = link->next){
350 Coroutine *cor = List_Link_Container(Coroutine, link, link);
351 for (int i = 4; i < COROUTINE_STACK_SIZE-3; i += 4){
352 if (!Check_Guard(&cor->guard[i])){
353 stackminheadroom = i < stackminheadroom ? i : stackminheadroom;
354 break;
355 }
356 }
357 }
358 g_c->report.lowest_headroom = stackminheadroom;
359
360 assert(List_IsEmpty(&g_c->inactive));
361 _Cor_Mutex_Unlock(&g_c->waiting_mutex);
362 _Cor_Mutex_dtor(&g_c->waiting_mutex);
363
364 assert(g_c->state == Coroutines_Stopping);
365 _Cor_Mutex_Unlock(&g_c->mutex);
366 g_c->state = Coroutines_Idle;
367 _Cor_Mutex_dtor(&g_c->mutex);
368
369 Coroutine_Report res = g_c->report;
370
371 free(g_c);
372 g_c = NULL;
373
374 return res;
375}
376
377
378void Coroutine_Run_Coroutine(
379 Coroutine *cor,
380 void *value
381){
382 Coroutines *cors = cor->coroutines;
383 assert(g_c == cors);
384 _Cor_Mutex_Lock(&cors->mutex);
385 assert(cors->state == Coroutines_Started);
386 cors->state = Coroutines_Active;
387 cors->primary = cor;
388
389 _Coroutine_Continue(cor, value, true);
390
391 if (!setjmp(cors->controller)){
392 _Cor_Mutex_Unlock(&cors->mutex);
393
394 // check the guard
395 if (!Check_Guard(g_c->guard)){
396 printf("Coroutine startup stack as has overrun - checked on entering the main coroutine\n");
397 exit(EXIT_FAILURE);
398 }
399
400 // start the first coroutine
401 Coroutine_RunNext();
402 }
403 // arrive here with mutex locked
404 assert(List_IsEmpty(&cors->runable));
405 assert(List_IsEmpty(&cors->waiting));
406 assert(cors->state == Coroutines_Active);
407 cors->state = Coroutines_Started;
408 _Cor_Mutex_Unlock(&cors->mutex);
409}
410
411
412void *Coroutine_Run(
413 Coroutine_Start start,
414 void *value
415){
416 Coroutine *cor = Coroutine_New(start);
417 Coroutine_Run_Coroutine(cor, value);
418 void *res = Coroutine_GetValue(cor);
419 Coroutine_Delete(cor);
420 return res;
421}
422
423
424Coroutine *Coroutine_New(
425 Coroutine_Start start
426){
427 assert((g_c->state == Coroutines_Started && List_IsEmpty(&g_c->inactive)) || g_c->state == Coroutines_Active);
428
429 // if none free - add one
430 if (List_IsEmpty(&g_c->free)){
431 if (!setjmp(g_c->chunk_allocated)){
432 longjmp(g_c->tip->buf, Chunk_Create);
433 }
434 }
435
436 Coroutine *cor = List_Link_Container(Coroutine, link, List_GetHead(&g_c->free));
437 assert(cor->state == Coroutine_Free);
438 cor->state = Coroutine_Idle;
439 cor->start = start;
440 cor->value = NULL;
441 List_Remove(&cor->link);
442 List_AddHead(&g_c->inactive, &cor->link);
443
444 g_c->report.coroutines_created += 1;
445
446 return cor;
447}
448
449
450void Coroutine_Delete(
451 Coroutine *cor
452){
453 Coroutines *cors = cor->coroutines;
454 _Cor_Mutex_Lock(&cors->mutex);
455 assert(cor->state == Coroutine_Idle || cor->state == Coroutine_Complete);
456 cor->state = Coroutine_Free;
457 List_Remove(&cor->link);
458 List_AddTail(&cors->free, &cor->link);
459 _Cor_Mutex_Unlock(&cors->mutex);
460}
461
462
463// Coroutine_Continue, assuming the mutex is claimed
464static void _Coroutine_Continue(
465 Coroutine *cor,
466 void *value,
467 bool early
468){
469 Coroutines *cors = cor->coroutines;
470 assert(cor->state == Coroutine_Idle || cor->state == Coroutine_Waiting);
471 cor->entry_param = value;
472 cor->state = Coroutine_Running;
473 List_Remove(&cor->link);
474 if ( early ) {
475 List_AddHead(&cors->runable, &cor->link);
476 } else {
477 List_AddTail(&cors->runable, &cor->link);
478 }
479 _Cor_Mutex_Unlock(&cors->waiting_mutex);
480}
481
482
483void Coroutine_Continue(
484 Coroutine *cor,
485 void *value,
486 bool early
487){
488 Coroutines *cors = cor->coroutines;
489 _Cor_Mutex_Lock(&cors->mutex);
490 _Coroutine_Continue(cor, value, early);
491 _Cor_Mutex_Unlock(&cors->mutex);
492}
493
494
495void *Coroutine_Yield(
496 void *value,
497 Coroutine_YieldCallback on_yield,
498 void *yield_me
499){
500 Coroutine *me = g_c->active;
501 if (!Check_Guard(me->guard)){
502 printf("Coroutine has overrun its stack - checked when yielding coroutine\n");
503 exit(EXIT_FAILURE);
504 }
505
506 _Cor_Mutex_Lock(&g_c->mutex);
507 Coroutines *cors = me->coroutines;
508 assert(me && me->state == Coroutine_Running && cors == g_c);
509 me->value = value;
510 me->state = Coroutine_Waiting;
511
512 List_Remove(&me->link);
513 if (!List_IsEmpty(&cors->runable)){
514 _Cor_Mutex_Unlock(&cors->waiting_mutex);
515 }
516 List_AddTail(&cors->waiting, &me->link);
517
518 switch (setjmp(me->buf)){
519 case Chunk_Initial:
520 _Cor_Mutex_Unlock(&cors->mutex);
521 on_yield(yield_me);
522 Coroutine_RunNext();
523 case Chunk_Create:
524 assert(false);
525 case Chunk_Enter:
526 // arrive here with mutex locked
527 cors->active = me;
528 // when we return here - we are running again
529 assert(me->state == Coroutine_Running);
530 void *res = me->entry_param;
531 _Cor_Mutex_Unlock(&cors->mutex);
532 return res;
533 }
534 return NULL;
535}
536
537
538void *Coroutine_GetValue(
539 Coroutine *cor
540){
541 return cor->value;
542}
543
544
545Coroutine *Coroutine_GetActive()
546{
547 return g_c->active;
548}
549
550
551int Coroutine_GetStackHeadroom(){
552 unsigned char tbuf[4];
553 return tbuf - g_c->active->guard - 4;
554}
555
556
557bool Coroutine_HasCoroutinesInFreePool(){
558 return !List_IsEmpty(&g_c->free);
559}
560
561
562void *Coroutine_GetCStackTop(){
563 return g_c->tip;
564}
565
566
567struct Coroutine_ChainParam {
568 Coroutine_Start start;
569 void *value;
570 Coroutine *ret;
571};
572
573
574static void *Coroutine_ChainFn(
575 void *param
576){
577 struct Coroutine_ChainParam *params = (struct Coroutine_ChainParam *)param;
578 Coroutine_Continue(params->ret, params->start(params->value), true);
579 return NULL;
580}
581
582
583static void Coroutine_ChainYield(
584 void *unused
585){
586 (void)unused;
587}
588
589
590void *Coroutine_Chain(
591 Coroutine_Start start,
592 void *value
593){
594 if (!Check_Guard(Coroutine_GetActive()->guard)){
595 printf("Coroutine has overrun its stack - checked when chaining\n");
596 exit(EXIT_FAILURE);
597 }
598 Coroutine *cor = Coroutine_New(Coroutine_ChainFn);
599 struct Coroutine_ChainParam params = {
600 start,
601 value,
602 Coroutine_GetActive()
603 };
604 Coroutine_Continue(cor, &params, true);
605 void *res = Coroutine_Yield(NULL, Coroutine_ChainYield, NULL);
606 Coroutine_Delete(cor);
607 return res;
608}
609
610
611bool Coroutine_IsRunning(
612 Coroutine *cor
613)
614{
615 int state = cor->state;
616 return state == Coroutine_Running || state == Coroutine_Waiting;
617}
618
619
620bool Coroutine_IsStarted(){
621 return g_c != NULL;
622}
623