1 contributor
1104 lines29.4 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 "cor_platform.h"
8
9// see CPython again, this time from ctypes.h
10#if (defined (__SVR4) && defined (__sun)) || defined(COROUTINE_HAVE_ALLOCA_H)
11# include <alloca.h>
12#elif defined(MS_WIN32)
13# include <malloc.h>
14#endif
15
16/* If the system does not define alloca(), we have to hope for a compiler builtin. */
17#ifndef alloca
18# if defined __GNUC__ || (__clang_major__ >= 4)
19# define alloca __builtin_alloca
20# else
21# error "Could not define alloca() on your platform."
22# endif
23#endif
24
25static void Coroutine_RunNext(void);
26static void _Coroutine_Continue(Coroutine *cor, void *value, bool early);
27static unsigned char *StackTopNow(void);
28
29///////////////////////////////////////////////////////////////////////////////
30// 2-way linked lists...
31//
32// Brought inline here to avoid namespace polution
33///////////////////////////////////////////////////////////////////////////////
34
35typedef struct List_Link List_Link;
36struct List_Link {
37 List_Link *next;
38 List_Link *prev;
39};
40
41typedef struct List_Head List_Head;
42struct List_Head {
43 union {
44 struct {
45 List_Link link;
46 List_Link *filler;
47 } fwd;
48 struct {
49 List_Link *filler;
50 List_Link link;
51 } back;
52 };
53};
54
55
56static inline bool List_IsEmpty(
57 const List_Head *list
58){
59 return list->fwd.link.next == &list->back.link;
60}
61
62
63static inline List_Link *List_GetHead(
64 const List_Head *list
65){
66 return List_IsEmpty(list) ? NULL : list->fwd.link.next;
67}
68
69
70static inline List_Link *List_Begin(
71 const List_Head *list
72){
73 return list->fwd.link.next;
74}
75
76
77static inline bool Link_NextIsLink(
78 const List_Link *link
79){
80 return link->next != NULL;
81}
82
83
84static inline List_Link *Link_Next(
85 List_Link *link
86){
87 return link->next;
88}
89
90
91static inline bool Link_PrevIsLink(
92 const List_Link *link
93){
94 return link->prev != NULL;
95}
96
97
98static inline List_Link *Link_Prev(
99 List_Link *link
100){
101 return link->prev;
102}
103
104static inline List_Link *List_GetTail(
105 const List_Head *list
106){
107 return List_IsEmpty(list) ? NULL : list->back.link.prev;
108}
109
110
111#define OFFSETOF(Container, Field) ((char *)&((Container *)4)->Field - (char *)(Container *)4)
112#define List_Link_Container(Container, Link, link) ((Container *)((char *)(link) - OFFSETOF(Container, Link)))
113
114
115static inline void List_Init(
116 List_Head *list
117){
118 list->fwd.link.next = &list->back.link;
119 list->fwd.link.prev = NULL;
120 list->back.link.prev = &list->fwd.link;
121}
122
123
124static inline void Link_AddAfter(
125 List_Link *link,
126 List_Link *after
127){
128 link->next = after->next;
129 link->prev = after;
130 after->next->prev = link;
131 after->next = link;
132}
133
134
135static inline void List_AddHead(
136 List_Head *list,
137 List_Link *link
138){
139 Link_AddAfter(link, &list->fwd.link);
140}
141
142
143static inline void Link_AddBefore(
144 List_Link *link,
145 List_Link *before
146){
147 link->prev = before->prev;
148 link->next = before;
149 before->prev->next = link;
150 before->prev = link;
151}
152
153
154static inline void List_AddTail(
155 List_Head *list,
156 List_Link *link
157){
158 Link_AddBefore(link, &list->back.link);
159}
160
161
162static inline void Link_Remove(
163 List_Link *link
164){
165 link->prev->next = link->next;
166 link->next->prev = link->prev;
167}
168
169///////////////////////////////////////////////////////////////////////////////
170// ...2-way linked lists
171///////////////////////////////////////////////////////////////////////////////
172
173typedef struct Coroutines Coroutines;
174
175enum {
176 Coroutines_Starting,
177 Coroutines_Started,
178 Coroutines_Active,
179 Coroutines_Stopping
180};
181
182enum {
183 Chunk_Initial,
184 Chunk_Create,
185 Chunk_Split,
186 Chunk_Enter
187};
188
189typedef enum Coroutine_State {
190 Coroutine_Free,
191 Coroutine_Idle,
192 Coroutine_Running,
193 Coroutine_Waiting,
194 Coroutine_Complete
195} Coroutine_State;
196
197enum {
198 Coroutines_Init,
199 Coroutines_AllocatedChunk,
200 Coroutines_CoroutineComplete,
201};
202
203struct Coroutine {
204 Coroutines *coroutines; // so can work with it off-thread
205 List_Link link; // for whichever list it's on
206 List_Link all_link; // list of all Coroutines
207 jmp_buf buf; // how to get back to it
208 unsigned char *prev_limit; // the previous Coroutine's stack limit
209 unsigned char *base; // where the base (high address) of this Coroutine's stack is
210 unsigned char *limit; // where the limit (low address) of this Coroutine's stack is
211 unsigned char *guard; // where the stack overrun guard is
212 size_t size;
213 Coroutine_Start start; // entry point
214 void *entry_param; // to pass to start
215 void *value; // yielded/returned
216 unsigned char *stack_top; // recorded at yield
217 Coroutine_State state;
218};
219
220struct Coroutines {
221 _Cor_Mutex mutex;
222 jmp_buf controller; // to return from Coroutine_Run
223 jmp_buf chunk_allocated;// for chunk allocation
224 unsigned char *guard; // the stack guard for the startup sequence
225 size_t gap_before; // bytes between previous's stack_top and next's Coroutine
226 size_t gap_after; // bytes between Coroutine and stack_base
227
228 // singletons
229 Coroutine *tip; // top of stack chunk
230 Coroutine *active; // currently running coroutine
231 Coroutine *primary; // Coroutine_Run coroutine
232 unsigned char *stack_limit; // when not NULL, where the stack finishes
233
234 // lists
235 List_Head all; // all Coroutines (in address order)
236 List_Head free; // free Coroutines
237 List_Head inactive; // idle or complete
238 List_Head runable; // running or waiting to run
239 List_Head waiting; // yielded / waiting to run
240 _Cor_Mutex waiting_mutex;
241
242 // Summary of the system
243 Coroutine_Report report;
244
245 // state
246 char state;
247};
248
249_Cor_thread_local Coroutines *g_c;
250
251static void ReserveStackSpace(Coroutines *cors, Coroutine *parent, size_t chunk_size, unsigned char *childs_limit);
252static void stack_chunk_base(Coroutines *cors, Coroutine *parent, unsigned char *prev_limit, unsigned char *limit);
253
254
255#define GUARD_PATTERN_SIZE (4)
256// Check whether the guard is intact
257static inline bool Check_Guard(
258 unsigned char *guard
259){
260 return !guard ||
261 (guard[0] == 0xde &&
262 guard[1] == 0xad &&
263 guard[2] == 0xbe &&
264 guard[3] == 0xef);
265}
266
267
268static inline void Apply_Guard(unsigned char *guard){
269 guard[0] = 0xde;
270 guard[1] = 0xad;
271 guard[2] = 0xbe;
272 guard[3] = 0xef;
273}
274
275
276static bool Coroutine_StackHasOverrun(void){
277 unsigned char *stack_top = StackTopNow();
278 unsigned char *stack_limit = g_c ? g_c->stack_limit : NULL;
279 if (stack_limit && stack_top < stack_limit){
280 // current stack top is beyond limit - we are overrunning NOW
281 return true;
282 }
283 Coroutine *me = g_c ? g_c->active : NULL;
284 if (!me){
285 return false;
286 }
287 if (me->guard){
288 return !Check_Guard(me->guard);
289 }
290 return stack_top < me->limit;
291}
292
293
294static void ReserveStackSpace(
295 Coroutines *cors,
296 Coroutine *parent,
297 size_t chunk_size,
298 unsigned char *childs_limit
299){
300 unsigned char *chunk_of_stack = alloca(chunk_size);
301#if COROUTINE_RECORD_LOWEST_HEADROOM
302 for (size_t i = 0; i <= chunk_size-GUARD_PATTERN_SIZE; i += GUARD_PATTERN_SIZE){
303 Apply_Guard(&chunk_of_stack[i]);
304 }
305#else
306 Apply_Guard(chunk_of_stack);
307#endif
308 if (parent){
309 parent->guard = chunk_of_stack;
310 parent->limit = chunk_of_stack;
311 parent->base = chunk_of_stack + chunk_size;
312 }
313 stack_chunk_base(cors, parent, chunk_of_stack, childs_limit);
314}
315
316
317static void stack_chunk_base(
318 Coroutines *cors,
319 Coroutine *parent,
320 unsigned char *prev_limit,
321 unsigned char *limit
322){
323 Coroutine here;
324 here.coroutines = cors;
325 here.state = Coroutine_Free;
326 here.prev_limit = prev_limit;
327 here.size = 0;
328 here.base = NULL;
329 here.guard = limit;
330 here.limit = limit;
331 if (limit){
332 here.base = (unsigned char *)&here - cors->gap_after;
333 here.size = here.base - here.limit;
334 Apply_Guard(limit);
335 }
336
337 // insert into all list
338 if (parent){
339 Link_AddAfter(&here.all_link, &parent->all_link);
340 } else {
341 List_AddHead(&cors->all, &here.all_link);
342 }
343 // add to free list
344 List_AddTail(&cors->free, &here.link);
345
346 cors->report.coroutines_pool_size += 1;
347
348 if (!cors->tip || &here < cors->tip){
349 cors->tip = &here;
350 }
351
352 for(;;){
353 switch (setjmp(here.buf)) {
354 case Chunk_Initial:
355 if (here.state == Coroutine_Free){
356 // return to the coroutine allocator
357 longjmp(cors->chunk_allocated, 1);
358 } else {
359 assert(here.state == Coroutine_Complete);
360 // we finish here to ensure the setjmp is redone
361 if (cors->primary == &here) {
362 // if primary coroutine - return to Coroutine_Run
363 longjmp(cors->controller, Coroutines_CoroutineComplete);
364 }
365 _Cor_Mutex_Unlock(&cors->mutex);
366 Coroutine_RunNext();
367 assert(false);
368 }
369 case Chunk_Create:
370 // Request to create a new chunk on the stack
371 // We're here if the coroutine is:
372 // Allocated, but not 'run' (Coroutine_Idle)
373 // Run, but not not entered yet (Coroutine_Running)
374 // Completed (Coroutine_Complete)
375 // Free, and the coroutines system is starting - we're characterising the system
376 assert(here.state == Coroutine_Idle ||
377 here.state == Coroutine_Running ||
378 here.state == Coroutine_Complete ||
379 (here.state == Coroutine_Free && cors->state == Coroutines_Starting));
380 ReserveStackSpace(here.coroutines, &here, here.size, NULL);
381 assert(false);
382 case Chunk_Split:
383 // Request to split this free block into two
384 // here.size will be set to our shorter size
385 ReserveStackSpace(here.coroutines, &here, here.size, here.limit);
386 assert(false);
387 case Chunk_Enter:
388 // request to start a coroutine (ie use the chunk for a coroutine)
389 // arrive here with mutex locked
390 assert(here.state == Coroutine_Running);
391 here.coroutines->active = &here;
392 _Cor_Mutex_Unlock(&cors->mutex);
393 here.value = here.start(here.entry_param);
394
395 // check the guard
396 assert(Check_Guard(here.guard));
397
398 _Cor_Mutex_Lock(&here.coroutines->mutex);
399 here.coroutines->active = NULL;
400 assert(here.state == Coroutine_Running);
401 Link_Remove(&here.link);
402 here.state = Coroutine_Complete;
403 List_AddTail(&here.coroutines->inactive, &here.link);
404 // Coroutine has completed
405 // Loop round to redo the setjmp() - if this coroutine yielded, then the setjmp will
406 // need reseting
407 }
408 }
409}
410
411
412static void Coroutine_RunNext(void)
413{
414 // arrive here with mutex unlocked
415 _Cor_Mutex_Lock(&g_c->waiting_mutex);
416 _Cor_Mutex_Lock(&g_c->mutex);
417 Coroutine *next = List_Link_Container(Coroutine, link, List_GetHead(&g_c->runable));
418 assert(next->state == Coroutine_Running);
419 longjmp(next->buf, Chunk_Enter);
420 assert(false);
421}
422
423
424void Coroutine_StartSystem(void)
425{
426 assert(!g_c);
427
428 Coroutines *cors = _Cor_Malloc(sizeof(*g_c));
429 assert(cors);
430
431 cors->state = Coroutines_Starting;
432 _Cor_Mutex_ctor(&cors->mutex);
433
434 cors->tip = NULL;
435 cors->active = NULL;
436
437 List_Init(&cors->all);
438 List_Init(&cors->free);
439 List_Init(&cors->inactive);
440 List_Init(&cors->runable);
441 List_Init(&cors->waiting);
442 _Cor_Mutex_ctor(&cors->waiting_mutex);
443 _Cor_Mutex_Lock(&cors->waiting_mutex);
444
445 cors->report.coroutines_created = 0;
446 cors->report.coroutines_pool_size = 0;
447 cors->report.largest_stack = 0;
448
449 // Charactersize the system...
450 if (!setjmp(cors->chunk_allocated)){
451 ReserveStackSpace(cors, NULL, COROUTINE_STARTUP_STACK_SIZE, NULL);
452 }
453 Coroutine *cor = List_Link_Container(Coroutine, link, List_GetHead(&cors->free));
454 cor->size = COROUTINE_STARTUP_STACK_SIZE;
455 if (!setjmp(cors->chunk_allocated)){
456 longjmp(cor->buf, Chunk_Create);
457 }
458 cors->gap_before = cor->prev_limit - (unsigned char *)cor;
459 cors->gap_after = (unsigned char *)cor - cor->base;
460 // ...charactersize the system
461
462 // discard what we've just created
463 List_Init(&cors->free);
464 cors->tip = NULL;
465
466 cors->state = Coroutines_Started;
467
468 g_c = cors;
469}
470
471
472void Coroutine_SetStackLimit(void *limit){
473 assert(g_c);
474 assert(!limit || !(g_c->state == Coroutines_Started || g_c->state == Coroutines_Active) || (unsigned char *)limit < (unsigned char *)g_c->tip);
475 g_c->stack_limit = limit;
476}
477
478
479Coroutine_Report Coroutine_StopSystem(void)
480{
481 assert(g_c);
482 assert(g_c->state == Coroutines_Started);
483 _Cor_Mutex_Lock(&g_c->mutex);
484 g_c->state = Coroutines_Stopping;
485
486 uintptr_t stackminheadroom;
487#if COROUTINE_RECORD_LOWEST_HEADROOM
488 stackminheadroom = g_c->report.largest_stack;
489 for (List_Link *link = g_c->free.fwd.link.next; Link_NextIsLink(link); link = Link_Next(link)){
490 Coroutine *cor = List_Link_Container(Coroutine, link, link);
491 if (cor->guard){
492 for (uintptr_t i = 4; i < cor->size-3; i += 4){
493 if (!Check_Guard(&cor->guard[i])){
494 stackminheadroom = i < stackminheadroom ? i : stackminheadroom;
495 break;
496 }
497 }
498 }
499 }
500#else
501 stackminheadroom = 0;
502#endif
503 g_c->report.lowest_headroom = stackminheadroom;
504
505 assert(List_IsEmpty(&g_c->inactive));
506 _Cor_Mutex_Unlock(&g_c->waiting_mutex);
507 _Cor_Mutex_dtor(&g_c->waiting_mutex);
508
509 assert(g_c->state == Coroutines_Stopping);
510 _Cor_Mutex_Unlock(&g_c->mutex);
511 _Cor_Mutex_dtor(&g_c->mutex);
512
513 Coroutine_Report ret = g_c->report;
514
515 _Cor_Free(g_c);
516 g_c = NULL;
517
518 return ret;
519}
520
521
522void Coroutine_Run_Coroutine(
523 Coroutine *cor,
524 void *value
525){
526 Coroutines *cors = cor->coroutines;
527
528 // Can't Coroutine_Run_Coroutine() off-thread
529 assert(g_c == cors);
530
531 _Cor_Mutex_Lock(&cors->mutex);
532 assert(cors->state == Coroutines_Started);
533 cors->state = Coroutines_Active;
534 cors->primary = cor;
535
536 _Coroutine_Continue(cor, value, true);
537
538 if (!setjmp(cors->controller)){
539 _Cor_Mutex_Unlock(&cors->mutex);
540
541 // check the guard
542 assert(Check_Guard(cors->guard));
543
544 // start the first coroutine
545 Coroutine_RunNext();
546 }
547 // arrive here with mutex locked
548 assert(List_IsEmpty(&cors->runable));
549 assert(List_IsEmpty(&cors->waiting));
550 assert(cors->state == Coroutines_Active);
551 cors->state = Coroutines_Started;
552 _Cor_Mutex_Unlock(&cors->mutex);
553}
554
555
556bool Coroutine_Run(
557 size_t stack,
558 Coroutine_Start start,
559 void *value,
560 void **result
561){
562 if (g_c && g_c->active){
563 void *res = start(value);
564 if (result){
565 *result = res;
566 }
567 // no failures, so...
568 return false;
569 }
570 assert(!g_c || g_c->state == Coroutines_Started);
571 bool need_start = !g_c;
572 if (need_start){
573 Coroutine_StartSystem();
574 }
575 Coroutine *cor = Coroutine_New(stack, start);
576 if (!cor){
577 // that didn't work
578 return true;
579 }
580 Coroutine_Run_Coroutine(cor, value);
581 if (result){
582 *result = Coroutine_GetValue(cor);
583 }
584 Coroutine_Delete(cor);
585 if (need_start){
586 Coroutine_StopSystem();
587 }
588 // no failures, so...
589 return false;
590}
591
592
593static void Coroutine_FreeToIdle(
594 Coroutine *cor,
595 Coroutine_Start start
596){
597 assert(cor->state == Coroutine_Free);
598 cor->state = Coroutine_Idle;
599 cor->start = start;
600 cor->value = NULL;
601 Link_Remove(&cor->link);
602 List_AddHead(&g_c->inactive, &cor->link);
603
604 g_c->report.coroutines_created += 1;
605}
606
607
608static void Coroutine_FreeToIdleSize(
609 Coroutine *cor,
610 Coroutine_Start start,
611 size_t size
612){
613 assert(!cor->guard);
614 cor->size = size;
615 cor->base = (unsigned char *)cor - g_c->gap_after;
616 cor->limit = cor->base - cor->size;
617 Coroutine_FreeToIdle(cor, start);
618}
619
620
621static Coroutine *Coroutine_New_Lock_Assumed(
622 size_t size,
623 Coroutine_Start start
624){
625 List_Link *link;
626
627 if (!g_c->tip){
628 // no tip - time to create one
629
630 // we're the non-Coroutine which starts the Coroutine system.
631 // Add a single free block
632 if (!setjmp(g_c->chunk_allocated)){
633 ReserveStackSpace(g_c, NULL, COROUTINE_STARTUP_STACK_SIZE, NULL);
634 }
635 }
636
637 Coroutine *cor = NULL;
638 for (link = List_Begin(&g_c->free); Link_NextIsLink(link); link = Link_Next(link)){
639 Coroutine *candidate = List_Link_Container(Coroutine, link, link);
640 if (!candidate->guard) {
641 // this must be the tip
642 assert(candidate == g_c->tip);
643
644 // If this is the only Coroutine in the system, go ahead and use it regardless of size.
645 // Note: there can only be one free block if there's no other sort of blocks as we merge on free
646 if (List_IsEmpty(&g_c->inactive) &&
647 List_IsEmpty(&g_c->runable) &&
648 List_IsEmpty(&g_c->waiting) ){
649 if (g_c->stack_limit){
650 size_t available = (unsigned char *)candidate - g_c->stack_limit - g_c->gap_after;
651 size = available < size ? available : size;
652 }
653 Coroutine_FreeToIdleSize(candidate, start, size);
654 return candidate;
655 }
656
657 // Not the only coroutine in the system - check size
658 if (g_c->stack_limit){
659 // there's a limit - see what that space allows....
660 size_t available = (unsigned char *)candidate - g_c->stack_limit - g_c->gap_after;
661
662 if (available < size){
663 // not enough space for this coroutine
664 return NULL;
665 }
666
667 if (available >= size + g_c->gap_before + g_c->gap_after + COROUTINE_MINIMUM_STACK_SIZE) {
668 // not enough space for another coroutine - use all the space for this one
669 size = available;
670 }
671 }
672 Coroutine_FreeToIdleSize(candidate, start, size);
673 return candidate;
674 }
675 if (candidate->size >= size && candidate > cor){
676 // chunk big enough, and a better choice than cor
677 cor = candidate;
678 }
679 }
680
681 if (cor){
682 // - work out whether we're splitting or using the whole chunk
683 if (cor->size >= size + g_c->gap_before + g_c->gap_after + COROUTINE_MINIMUM_STACK_SIZE){
684 // enough space for a second coroutine so split this free block
685 cor->size = size;
686 if (!setjmp(g_c->chunk_allocated)){
687 longjmp(cor->buf, Chunk_Split);
688 }
689 }
690 // cor now ready to use
691 Coroutine_FreeToIdle(cor, start);
692 return cor;
693 }
694
695 // No big-enough free blocks - check if there's space beyond the tip block
696
697 if (g_c->stack_limit && g_c->stack_limit > (unsigned char *)g_c->tip->limit - sizeof(Coroutine) - size){
698 // no space for a new stack block
699 return NULL;
700 }
701 Coroutine *tip = g_c->tip;
702 Coroutine *me = g_c->active;
703 if (tip == me) {
704 if (!setjmp(g_c->chunk_allocated)){
705 ReserveStackSpace(g_c, me, StackTopNow() - me->limit, NULL);
706 }
707 } else {
708 if (!setjmp(g_c->chunk_allocated)){
709 longjmp(tip->buf, Chunk_Create);
710 }
711 }
712
713 cor = List_Link_Container(Coroutine, link, List_GetTail(&g_c->free));
714 assert(cor->state == Coroutine_Free);
715 cor->size = size;
716 cor->limit = (unsigned char *)cor - g_c->gap_after - size;
717 cor->state = Coroutine_Idle;
718 cor->start = start;
719 cor->value = NULL;
720 Link_Remove(&cor->link);
721 List_AddHead(&g_c->inactive, &cor->link);
722
723 g_c->report.coroutines_created += 1;
724 return cor;
725}
726
727
728Coroutine *Coroutine_New(
729 size_t stack,
730 Coroutine_Start start
731){
732 assert(g_c);
733 assert((g_c->state == Coroutines_Started && List_IsEmpty(&g_c->inactive)) || g_c->state == Coroutines_Active);
734 assert(!Coroutine_StackHasOverrun());
735
736 _Cor_Mutex_Lock(&g_c->mutex);
737
738 Coroutine *cor = Coroutine_New_Lock_Assumed(stack, start);
739
740 if (cor && cor->size > g_c->report.largest_stack){
741 g_c->report.largest_stack = cor->size;
742 }
743
744 _Cor_Mutex_Unlock(&g_c->mutex);
745
746 return cor;
747}
748
749
750void Coroutine_Delete(
751 Coroutine *cor
752){
753 assert(!Coroutine_StackHasOverrun());
754 if (cor){
755 Coroutines *cors = cor->coroutines;
756 _Cor_Mutex_Lock(&cors->mutex);
757 assert(cor->state == Coroutine_Idle || cor->state == Coroutine_Complete);
758 cor->state = Coroutine_Free;
759 Link_Remove(&cor->link);
760
761 // insert into free list
762 List_AddHead(&cors->free, &cor->link);
763
764 // Check for merge with following Coroutine
765 List_Link *link = Link_Next(&cor->all_link);
766 if (Link_NextIsLink(link)){
767 Coroutine *listcor = List_Link_Container(Coroutine, all_link, link);
768 if (listcor->state == Coroutine_Free){
769 // merge
770 cor->size += cor->limit - listcor->limit;
771 cor->limit = listcor->limit;
772 cor->guard = listcor->guard;
773 Link_Remove(&listcor->all_link);
774 Link_Remove(&listcor->link);
775 if (g_c->tip == listcor){
776 g_c->tip = cor;
777 }
778 }
779 }
780
781 // check for merge with prev coroutine
782 link = Link_Prev(&cor->all_link);
783 if (Link_PrevIsLink(link)){
784 Coroutine *listcor = List_Link_Container(Coroutine, all_link, link);
785 if (listcor->state == Coroutine_Free){
786 // merge
787 listcor->size += listcor->limit - cor->limit;
788 listcor->limit = cor->limit;
789 listcor->guard = cor->guard;
790 Link_Remove(&cor->all_link);
791 Link_Remove(&cor->link);
792 if (g_c->tip == cor){
793 g_c->tip = listcor;
794 }
795 }
796 }
797
798 _Cor_Mutex_Unlock(&cors->mutex);
799 }
800}
801
802
803// Coroutine_Continue, assuming the mutex is claimed
804static void _Coroutine_Continue(
805 Coroutine *cor,
806 void *value,
807 bool early
808){
809 Coroutines *cors = cor->coroutines;
810 assert(cor->state == Coroutine_Idle || cor->state == Coroutine_Waiting);
811 cor->entry_param = value;
812 cor->state = Coroutine_Running;
813 Link_Remove(&cor->link);
814 if ( early ) {
815 List_AddHead(&cors->runable, &cor->link);
816 } else {
817 List_AddTail(&cors->runable, &cor->link);
818 }
819 _Cor_Mutex_Unlock(&cors->waiting_mutex);
820}
821
822
823void Coroutine_Continue(
824 Coroutine *cor,
825 void *value,
826 bool early
827){
828 assert(!Coroutine_StackHasOverrun());
829 Coroutines *cors = cor->coroutines;
830 _Cor_Mutex_Lock(&cors->mutex);
831 _Coroutine_Continue(cor, value, early);
832 _Cor_Mutex_Unlock(&cors->mutex);
833}
834
835
836void *Coroutine_Yield(
837 void *value,
838 Coroutine_YieldCallback on_yield,
839 void *yield_me
840){
841 assert(g_c);
842 Coroutine *me = g_c->active;
843 assert(me);
844 assert(!Coroutine_StackHasOverrun());
845
846 _Cor_Mutex_Lock(&g_c->mutex);
847 Coroutines *cors = me->coroutines;
848 assert(me && me->state == Coroutine_Running && cors == g_c);
849 me->stack_top = StackTopNow();
850 me->value = value;
851 me->state = Coroutine_Waiting;
852
853 Link_Remove(&me->link);
854 if (!List_IsEmpty(&cors->runable)){
855 _Cor_Mutex_Unlock(&cors->waiting_mutex);
856 }
857 List_AddTail(&cors->waiting, &me->link);
858
859 switch (setjmp(me->buf)){
860 case Chunk_Initial:
861 _Cor_Mutex_Unlock(&cors->mutex);
862 on_yield(yield_me);
863 Coroutine_RunNext();
864 assert(false);
865 case Chunk_Create:
866 assert(me == g_c->tip);
867 ReserveStackSpace(me->coroutines, me, me->stack_top - me->limit, NULL);
868 assert(false);
869 case Chunk_Enter:
870 // arrive here with mutex locked
871 cors->active = me;
872 assert(!Coroutine_StackHasOverrun());
873 // when we return here - we are running again
874 assert(me->state == Coroutine_Running);
875 void *res = me->entry_param;
876 _Cor_Mutex_Unlock(&cors->mutex);
877 return res;
878 }
879 return NULL;
880}
881
882
883void *Coroutine_GetValue(
884 Coroutine *cor
885){
886 return cor->value;
887}
888
889
890Coroutine *Coroutine_GetActive(void)
891{
892 return g_c ? g_c->active : NULL;
893}
894
895
896intptr_t Coroutine_GetStackHeadroom(void){
897 assert(g_c);
898 assert(!Coroutine_StackHasOverrun());
899 Coroutine *me = g_c->active;
900 if (!me){
901 // no active coroutine
902 unsigned char *stack_limit = g_c->stack_limit;
903 if (stack_limit){
904 // no stack limit - assume we'll use COROUTINE_STACK_SIZE
905 return StackTopNow() - stack_limit;
906 } else {
907 // no information where the stack ends - return something
908 return COROUTINE_MINIMUM_STACK_SIZE;
909 }
910 }
911 return StackTopNow() - me->limit;
912}
913
914
915// This is used to avoid compiler warnings about returning the address of a local
916static inline void *StopAddressWarnings(void *p)
917{
918 return p;
919}
920
921
922void *Coroutine_GetStackHWM(void){
923 assert(g_c);
924 assert(g_c->state == Coroutines_Active);
925 assert(!Coroutine_StackHasOverrun());
926 // Find where the guards end
927 unsigned char *guard;
928 for (guard = g_c->active->guard; Check_Guard(guard); guard += 4){
929 // do nothing
930 }
931 return guard;
932}
933
934
935void Coroutine_ClearStackForHWM(void){
936 assert(g_c);
937 assert(g_c->state == Coroutines_Active);
938 assert(!Coroutine_StackHasOverrun());
939 unsigned char *end = StackTopNow() - GUARD_PATTERN_SIZE;
940 for (unsigned char *guard = g_c->active->guard+GUARD_PATTERN_SIZE; guard <= end; guard += GUARD_PATTERN_SIZE){
941 Apply_Guard(guard);
942 }
943}
944
945
946static bool Coroutine_CanStartCoroutine_Lock_Assumed(
947 size_t size
948){
949 assert(g_c);
950 assert(g_c->state == Coroutines_Started || g_c->state == Coroutines_Active);
951 assert(!Coroutine_StackHasOverrun());
952
953 if (!g_c->stack_limit){
954 return true;
955 }
956
957 if (!g_c->tip){
958 return true;
959 }
960
961 if (g_c->tip->state == Coroutine_Free){
962 // last block is free
963 if ((unsigned char *)g_c->tip - g_c->stack_limit >= (ptrdiff_t)(g_c->gap_after + size)){
964 // enough room in free block, which is the last block
965 return true;
966 }
967 } else {
968 // last block is allocated
969 if (g_c->tip->limit - g_c->stack_limit >= (ptrdiff_t)(g_c->gap_before + g_c->gap_after + size)){
970 // enough room after the last block, which is allocated
971 return true;
972 }
973 }
974
975 // not enough room between allocated blocks and stack limit, so check free list
976 List_Link *link;
977 for (link = List_Begin(&g_c->free); Link_NextIsLink(link); link = Link_Next(link)){
978 Coroutine *cor = List_Link_Container(Coroutine, link, link);
979 if (cor->size >= size){
980 return true;
981 }
982 }
983
984 return false;
985}
986
987
988bool Coroutine_CanStartCoroutine(
989 size_t size
990){
991 _Cor_Mutex_Lock(&g_c->mutex);
992
993 bool result = Coroutine_CanStartCoroutine_Lock_Assumed(size);
994
995 _Cor_Mutex_Unlock(&g_c->mutex);
996
997 return result;
998}
999
1000void *Coroutine_GetCStackTop(void){
1001 assert(!Coroutine_StackHasOverrun());
1002 if ((g_c->state == Coroutines_Started || g_c->state == Coroutines_Active) && g_c->tip != g_c->active) {
1003 return g_c->tip->stack_top;
1004 } else {
1005 return StackTopNow();
1006 }
1007}
1008
1009
1010static unsigned char *StackTopNow(void){
1011 unsigned char here[4];
1012 return StopAddressWarnings(here);
1013}
1014
1015
1016struct Coroutine_ChainParam {
1017 Coroutine_Start start;
1018 void *value;
1019 Coroutine *ret;
1020};
1021
1022
1023static void *Coroutine_ChainFn(
1024 void *param
1025){
1026 struct Coroutine_ChainParam *params = (struct Coroutine_ChainParam *)param;
1027 Coroutine_Continue(params->ret, params->start(params->value), true);
1028 return NULL;
1029}
1030
1031
1032static void Coroutine_ChainYield(
1033 void *unused
1034){
1035 (void)unused;
1036}
1037
1038
1039bool Coroutine_Chain(
1040 size_t size,
1041 Coroutine_Start start,
1042 void *value,
1043 void **result
1044){
1045 assert(Check_Guard(Coroutine_GetActive()->guard));
1046 Coroutine *cor = Coroutine_New(size, Coroutine_ChainFn);
1047 if (!cor){
1048 // failed
1049 return true;
1050 }
1051 struct Coroutine_ChainParam params = {
1052 start,
1053 value,
1054 Coroutine_GetActive()
1055 };
1056 Coroutine_Continue(cor, &params, true);
1057 void *res = Coroutine_Yield(NULL, Coroutine_ChainYield, NULL);
1058 Coroutine_Delete(cor);
1059 if (result){
1060 *result = res;
1061 }
1062 // success!
1063 return false;
1064}
1065
1066
1067bool Coroutine_IsRunning(
1068 Coroutine *cor
1069)
1070{
1071 int state = cor->state;
1072 return state == Coroutine_Running || state == Coroutine_Waiting;
1073}
1074
1075
1076bool Coroutine_IsComplete(
1077 Coroutine *cor
1078)
1079{
1080 int state = cor->state;
1081 return state == Coroutine_Complete;
1082}
1083
1084
1085bool Coroutine_IsStarted(void){
1086 return g_c && (g_c->state == Coroutines_Active || g_c->state == Coroutines_Started);
1087}
1088
1089void _Coroutine_Dump(void){
1090 char *state_to_text[] = {
1091 "Free",
1092 "Idle",
1093 "Running",
1094 "Waiting",
1095 "Complete"
1096 };
1097 unsigned idx = 0;
1098 List_Link *link;
1099 for (link = List_Begin(&g_c->all); Link_NextIsLink(link); link = Link_Next(link)){
1100 Coroutine *cor = List_Link_Container(Coroutine, all_link, link);
1101 printf("%d) %p (%s) %ld%s\n", idx++, cor, state_to_text[cor->state], cor->size, cor == g_c->tip ? " (TIP)" : "");
1102 }
1103}
1104