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