ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/Coro/State.xs
(Generate patch)

Comparing Coro/Coro/State.xs (file contents):
Revision 1.286 by root, Mon Nov 17 04:19:49 2008 UTC vs.
Revision 1.312 by root, Thu Nov 20 03:10:30 2008 UTC

16 16
17#ifdef WIN32 17#ifdef WIN32
18# undef setjmp 18# undef setjmp
19# undef longjmp 19# undef longjmp
20# undef _exit 20# undef _exit
21# define setjmp _setjmp // deep magic, don't ask 21# define setjmp _setjmp /* deep magic */
22#else 22#else
23# include <inttypes.h> /* most portable stdint.h */ 23# include <inttypes.h> /* most portable stdint.h */
24#endif 24#endif
25 25
26#ifdef HAVE_MMAP 26#ifdef HAVE_MMAP
55 55
56#define PERL_VERSION_ATLEAST(a,b,c) \ 56#define PERL_VERSION_ATLEAST(a,b,c) \
57 (PERL_REVISION > (a) \ 57 (PERL_REVISION > (a) \
58 || (PERL_REVISION == (a) \ 58 || (PERL_REVISION == (a) \
59 && (PERL_VERSION > (b) \ 59 && (PERL_VERSION > (b) \
60 || (PERL_VERSION == (b) && PERLSUBVERSION >= (c))))) 60 || (PERL_VERSION == (b) && PERL_SUBVERSION >= (c)))))
61 61
62#if !PERL_VERSION_ATLEAST (5,6,0) 62#if !PERL_VERSION_ATLEAST (5,6,0)
63# ifndef PL_ppaddr 63# ifndef PL_ppaddr
64# define PL_ppaddr ppaddr 64# define PL_ppaddr ppaddr
65# endif 65# endif
95# define GV_NOTQUAL 0 95# define GV_NOTQUAL 0
96#endif 96#endif
97#ifndef newSV 97#ifndef newSV
98# define newSV(l) NEWSV(0,l) 98# define newSV(l) NEWSV(0,l)
99#endif 99#endif
100#ifndef CvISXSUB_on
101# define CvISXSUB_on(cv) (void)cv
102#endif
100 103
101/* 5.8.7 */ 104/* 5.8.7 */
102#ifndef SvRV_set 105#ifndef SvRV_set
103# define SvRV_set(s,v) SvRV(s) = (v) 106# define SvRV_set(s,v) SvRV(s) = (v)
104#endif 107#endif
117#endif 120#endif
118 121
119/* The next macros try to return the current stack pointer, in an as 122/* The next macros try to return the current stack pointer, in an as
120 * portable way as possible. */ 123 * portable way as possible. */
121#if __GNUC__ >= 4 124#if __GNUC__ >= 4
125# define dSTACKLEVEL int stacklevel_dummy
122# define dSTACKLEVEL void *stacklevel = __builtin_frame_address (0) 126# define STACKLEVEL __builtin_frame_address (0)
123#else 127#else
124# define dSTACKLEVEL volatile void *stacklevel = (volatile void *)&stacklevel 128# define dSTACKLEVEL volatile void *stacklevel
129# define STACKLEVEL ((void *)&stacklevel)
125#endif 130#endif
126 131
127#define IN_DESTRUCT (PL_main_cv == Nullcv) 132#define IN_DESTRUCT (PL_main_cv == Nullcv)
128 133
129#if __GNUC__ >= 3 134#if __GNUC__ >= 3
140#define expect_true(expr) expect ((expr) != 0, 1) 145#define expect_true(expr) expect ((expr) != 0, 1)
141 146
142#define NOINLINE attribute ((noinline)) 147#define NOINLINE attribute ((noinline))
143 148
144#include "CoroAPI.h" 149#include "CoroAPI.h"
150#define GCoroAPI (&coroapi) /* very sneaky */
145 151
146#ifdef USE_ITHREADS 152#ifdef USE_ITHREADS
147# if CORO_PTHREAD 153# if CORO_PTHREAD
148static void *coro_thx; 154static void *coro_thx;
149# endif 155# endif
150#endif 156#endif
151 157
152/* helper storage struct for Coro::AIO */
153struct io_state
154{
155 AV *res;
156 int errorno;
157 I32 laststype; /* U16 in 5.10.0 */
158 int laststatval;
159 Stat_t statcache;
160};
161
162static double (*nvtime)(); /* so why doesn't it take void? */ 158static double (*nvtime)(); /* so why doesn't it take void? */
159
160/* we hijack an hopefully unused CV flag for our purposes */
161#define CVf_SLF 0x4000
162static OP *pp_slf (pTHX);
163 163
164static U32 cctx_gen; 164static U32 cctx_gen;
165static size_t cctx_stacksize = CORO_STACKSIZE; 165static size_t cctx_stacksize = CORO_STACKSIZE;
166static struct CoroAPI coroapi; 166static struct CoroAPI coroapi;
167static AV *main_mainstack; /* used to differentiate between $main and others */ 167static AV *main_mainstack; /* used to differentiate between $main and others */
176static HV *hv_sig; /* %SIG */ 176static HV *hv_sig; /* %SIG */
177 177
178/* async_pool helper stuff */ 178/* async_pool helper stuff */
179static SV *sv_pool_rss; 179static SV *sv_pool_rss;
180static SV *sv_pool_size; 180static SV *sv_pool_size;
181static SV *sv_async_pool_idle;
181static AV *av_async_pool; 182static AV *av_async_pool;
183static SV *sv_Coro;
184static CV *cv_pool_handler;
185static CV *cv_coro_new;
182 186
183/* Coro::AnyEvent */ 187/* Coro::AnyEvent */
184static SV *sv_activity; 188static SV *sv_activity;
185 189
186static struct coro_cctx *cctx_first; 190static struct coro_cctx *cctx_first;
246 /* state data */ 250 /* state data */
247 struct CoroSLF slf_frame; /* saved slf frame */ 251 struct CoroSLF slf_frame; /* saved slf frame */
248 AV *mainstack; 252 AV *mainstack;
249 perl_slots *slot; /* basically the saved sp */ 253 perl_slots *slot; /* basically the saved sp */
250 254
255 CV *startcv; /* the CV to execute */
251 AV *args; /* data associated with this coroutine (initial args) */ 256 AV *args; /* data associated with this coroutine (initial args) */
252 int refcnt; /* coroutines are refcounted, yes */ 257 int refcnt; /* coroutines are refcounted, yes */
253 int flags; /* CF_ flags */ 258 int flags; /* CF_ flags */
254 HV *hv; /* the perl hash associated with this coro, if any */ 259 HV *hv; /* the perl hash associated with this coro, if any */
255 void (*on_destroy)(pTHX_ struct coro *coro); 260 void (*on_destroy)(pTHX_ struct coro *coro);
256 261
257 /* statistics */ 262 /* statistics */
258 int usecount; /* number of transfers to this coro */ 263 int usecount; /* number of transfers to this coro */
259 264
260 /* coro process data */ 265 /* coro process data */
261 int prio; 266 int prio;
262 SV *throw; /* exception to be thrown */ 267 SV *except; /* exception to be thrown */
268 SV *rouse_cb;
263 269
264 /* async_pool */ 270 /* async_pool */
265 SV *saved_deffh; 271 SV *saved_deffh;
272 SV *invoke_cb;
273 AV *invoke_av;
266 274
267 /* linked list */ 275 /* linked list */
268 struct coro *next, *prev; 276 struct coro *next, *prev;
269}; 277};
270 278
273 281
274/* the following variables are effectively part of the perl context */ 282/* the following variables are effectively part of the perl context */
275/* and get copied between struct coro and these variables */ 283/* and get copied between struct coro and these variables */
276/* the mainr easonw e don't support windows process emulation */ 284/* the mainr easonw e don't support windows process emulation */
277static struct CoroSLF slf_frame; /* the current slf frame */ 285static struct CoroSLF slf_frame; /* the current slf frame */
278static SV *coro_throw;
279 286
280/** Coro ********************************************************************/ 287/** Coro ********************************************************************/
281 288
282#define PRIO_MAX 3 289#define PRIO_MAX 3
283#define PRIO_HIGH 1 290#define PRIO_HIGH 1
288 295
289/* for Coro.pm */ 296/* for Coro.pm */
290static SV *coro_current; 297static SV *coro_current;
291static SV *coro_readyhook; 298static SV *coro_readyhook;
292static AV *coro_ready [PRIO_MAX - PRIO_MIN + 1]; 299static AV *coro_ready [PRIO_MAX - PRIO_MIN + 1];
300static CV *cv_coro_run, *cv_coro_terminate;
293static struct coro *coro_first; 301static struct coro *coro_first;
294#define coro_nready coroapi.nready 302#define coro_nready coroapi.nready
295 303
296/** lowlevel stuff **********************************************************/ 304/** lowlevel stuff **********************************************************/
297 305
321#if PERL_VERSION_ATLEAST (5,10,0) 329#if PERL_VERSION_ATLEAST (5,10,0)
322 /* silence stupid and wrong 5.10 warning that I am unable to switch off */ 330 /* silence stupid and wrong 5.10 warning that I am unable to switch off */
323 get_hv (name, create); 331 get_hv (name, create);
324#endif 332#endif
325 return get_hv (name, create); 333 return get_hv (name, create);
334}
335
336/* may croak */
337INLINE CV *
338coro_sv_2cv (pTHX_ SV *sv)
339{
340 HV *st;
341 GV *gvp;
342 return sv_2cv (sv, &st, &gvp, 0);
326} 343}
327 344
328static AV * 345static AV *
329coro_clone_padlist (pTHX_ CV *cv) 346coro_clone_padlist (pTHX_ CV *cv)
330{ 347{
384 SvREFCNT_dec (av); /* sv_magicext increased the refcount */ 401 SvREFCNT_dec (av); /* sv_magicext increased the refcount */
385 402
386 return 0; 403 return 0;
387} 404}
388 405
389#define CORO_MAGIC_type_cv PERL_MAGIC_ext 406#define CORO_MAGIC_type_cv 26
390#define CORO_MAGIC_type_state PERL_MAGIC_ext 407#define CORO_MAGIC_type_state PERL_MAGIC_ext
391 408
392static MGVTBL coro_cv_vtbl = { 409static MGVTBL coro_cv_vtbl = {
393 0, 0, 0, 0, 410 0, 0, 0, 0,
394 coro_cv_free 411 coro_cv_free
395}; 412};
396 413
414#define CORO_MAGIC_NN(sv, type) \
415 (expect_true (SvMAGIC (sv)->mg_type == type) \
416 ? SvMAGIC (sv) \
417 : mg_find (sv, type))
418
397#define CORO_MAGIC(sv, type) \ 419#define CORO_MAGIC(sv, type) \
398 expect_true (SvMAGIC (sv)) \ 420 (expect_true (SvMAGIC (sv)) \
399 ? expect_true (SvMAGIC (sv)->mg_type == type) \ 421 ? CORO_MAGIC_NN (sv, type) \
400 ? SvMAGIC (sv) \
401 : mg_find (sv, type) \
402 : 0 422 : 0)
403 423
404#define CORO_MAGIC_cv(cv) CORO_MAGIC (((SV *)(cv)), CORO_MAGIC_type_cv) 424#define CORO_MAGIC_cv(cv) CORO_MAGIC (((SV *)(cv)), CORO_MAGIC_type_cv)
405#define CORO_MAGIC_state(sv) CORO_MAGIC (((SV *)(sv)), CORO_MAGIC_type_state) 425#define CORO_MAGIC_state(sv) CORO_MAGIC_NN (((SV *)(sv)), CORO_MAGIC_type_state)
406 426
407INLINE struct coro * 427INLINE struct coro *
408SvSTATE_ (pTHX_ SV *coro) 428SvSTATE_ (pTHX_ SV *coro)
409{ 429{
410 HV *stash; 430 HV *stash;
428 return (struct coro *)mg->mg_ptr; 448 return (struct coro *)mg->mg_ptr;
429} 449}
430 450
431#define SvSTATE(sv) SvSTATE_ (aTHX_ (sv)) 451#define SvSTATE(sv) SvSTATE_ (aTHX_ (sv))
432 452
433/* fastert than SvSTATE, but expects a coroutine hv */ 453/* faster than SvSTATE, but expects a coroutine hv */
434INLINE struct coro * 454#define SvSTATE_hv(hv) ((struct coro *)CORO_MAGIC_NN ((SV *)hv, CORO_MAGIC_type_state)->mg_ptr)
435SvSTATE_hv (SV *sv)
436{
437 MAGIC *mg = expect_true (SvMAGIC (sv)->mg_type == CORO_MAGIC_type_state)
438 ? SvMAGIC (sv)
439 : mg_find (sv, CORO_MAGIC_type_state);
440
441 return (struct coro *)mg->mg_ptr;
442}
443
444#define SvSTATE_current SvSTATE_hv (SvRV (coro_current)) 455#define SvSTATE_current SvSTATE_hv (SvRV (coro_current))
445 456
446/* the next two functions merely cache the padlists */ 457/* the next two functions merely cache the padlists */
447static void 458static void
448get_padlist (pTHX_ CV *cv) 459get_padlist (pTHX_ CV *cv)
455 else 466 else
456 { 467 {
457#if CORO_PREFER_PERL_FUNCTIONS 468#if CORO_PREFER_PERL_FUNCTIONS
458 /* this is probably cleaner? but also slower! */ 469 /* this is probably cleaner? but also slower! */
459 /* in practise, it seems to be less stable */ 470 /* in practise, it seems to be less stable */
460 CV *cp = Perl_cv_clone (cv); 471 CV *cp = Perl_cv_clone (aTHX_ cv);
461 CvPADLIST (cv) = CvPADLIST (cp); 472 CvPADLIST (cv) = CvPADLIST (cp);
462 CvPADLIST (cp) = 0; 473 CvPADLIST (cp) = 0;
463 SvREFCNT_dec (cp); 474 SvREFCNT_dec (cp);
464#else 475#else
465 CvPADLIST (cv) = coro_clone_padlist (aTHX_ cv); 476 CvPADLIST (cv) = coro_clone_padlist (aTHX_ cv);
518 529
519 PUTBACK; 530 PUTBACK;
520 } 531 }
521 532
522 slf_frame = c->slf_frame; 533 slf_frame = c->slf_frame;
523 coro_throw = c->throw; 534 CORO_THROW = c->except;
524} 535}
525 536
526static void 537static void
527save_perl (pTHX_ Coro__State c) 538save_perl (pTHX_ Coro__State c)
528{ 539{
529 c->throw = coro_throw; 540 c->except = CORO_THROW;
530 c->slf_frame = slf_frame; 541 c->slf_frame = slf_frame;
531 542
532 { 543 {
533 dSP; 544 dSP;
534 I32 cxix = cxstack_ix; 545 I32 cxix = cxstack_ix;
609 * of perl.c:init_stacks, except that it uses less memory 620 * of perl.c:init_stacks, except that it uses less memory
610 * on the (sometimes correct) assumption that coroutines do 621 * on the (sometimes correct) assumption that coroutines do
611 * not usually need a lot of stackspace. 622 * not usually need a lot of stackspace.
612 */ 623 */
613#if CORO_PREFER_PERL_FUNCTIONS 624#if CORO_PREFER_PERL_FUNCTIONS
614# define coro_init_stacks init_stacks 625# define coro_init_stacks(thx) init_stacks ()
615#else 626#else
616static void 627static void
617coro_init_stacks (pTHX) 628coro_init_stacks (pTHX)
618{ 629{
619 PL_curstackinfo = new_stackinfo(32, 8); 630 PL_curstackinfo = new_stackinfo(32, 8);
682#if !PERL_VERSION_ATLEAST (5,10,0) 693#if !PERL_VERSION_ATLEAST (5,10,0)
683 Safefree (PL_retstack); 694 Safefree (PL_retstack);
684#endif 695#endif
685} 696}
686 697
698#define CORO_RSS \
699 rss += sizeof (SYM (curstackinfo)); \
700 rss += (SYM (curstackinfo->si_cxmax) + 1) * sizeof (PERL_CONTEXT); \
701 rss += sizeof (SV) + sizeof (struct xpvav) + (1 + AvMAX (SYM (curstack))) * sizeof (SV *); \
702 rss += SYM (tmps_max) * sizeof (SV *); \
703 rss += (SYM (markstack_max) - SYM (markstack_ptr)) * sizeof (I32); \
704 rss += SYM (scopestack_max) * sizeof (I32); \
705 rss += SYM (savestack_max) * sizeof (ANY);
706
687static size_t 707static size_t
688coro_rss (pTHX_ struct coro *coro) 708coro_rss (pTHX_ struct coro *coro)
689{ 709{
690 size_t rss = sizeof (*coro); 710 size_t rss = sizeof (*coro);
691 711
692 if (coro->mainstack) 712 if (coro->mainstack)
693 { 713 {
694 perl_slots tmp_slot;
695 perl_slots *slot;
696
697 if (coro->flags & CF_RUNNING) 714 if (coro->flags & CF_RUNNING)
698 { 715 {
699 slot = &tmp_slot; 716 #define SYM(sym) PL_ ## sym
700 717 CORO_RSS;
701 #define VAR(name,type) slot->name = PL_ ## name;
702 # include "state.h"
703 #undef VAR 718 #undef SYM
704 } 719 }
705 else 720 else
706 slot = coro->slot;
707
708 if (slot)
709 { 721 {
710 rss += sizeof (slot->curstackinfo); 722 #define SYM(sym) coro->slot->sym
711 rss += (slot->curstackinfo->si_cxmax + 1) * sizeof (PERL_CONTEXT); 723 CORO_RSS;
712 rss += sizeof (SV) + sizeof (struct xpvav) + (1 + AvMAX (slot->curstack)) * sizeof (SV *); 724 #undef SYM
713 rss += slot->tmps_max * sizeof (SV *);
714 rss += (slot->markstack_max - slot->markstack_ptr) * sizeof (I32);
715 rss += slot->scopestack_max * sizeof (I32);
716 rss += slot->savestack_max * sizeof (ANY);
717
718#if !PERL_VERSION_ATLEAST (5,10,0)
719 rss += slot->retstack_max * sizeof (OP *);
720#endif
721 } 725 }
722 } 726 }
723 727
724 return rss; 728 return rss;
725} 729}
826static int 830static int
827slf_check_nop (pTHX_ struct CoroSLF *frame) 831slf_check_nop (pTHX_ struct CoroSLF *frame)
828{ 832{
829 return 0; 833 return 0;
830} 834}
835
836static UNOP coro_setup_op;
831 837
832static void NOINLINE /* noinline to keep it out of the transfer fast path */ 838static void NOINLINE /* noinline to keep it out of the transfer fast path */
833coro_setup (pTHX_ struct coro *coro) 839coro_setup (pTHX_ struct coro *coro)
834{ 840{
835 /* 841 /*
864 { 870 {
865 dSP; 871 dSP;
866 UNOP myop; 872 UNOP myop;
867 873
868 Zero (&myop, 1, UNOP); 874 Zero (&myop, 1, UNOP);
869 myop.op_next = Nullop; 875 myop.op_next = Nullop;
876 myop.op_type = OP_ENTERSUB;
870 myop.op_flags = OPf_WANT_VOID; 877 myop.op_flags = OPf_WANT_VOID;
871 878
872 PUSHMARK (SP); 879 PUSHMARK (SP);
873 XPUSHs (sv_2mortal (av_shift (GvAV (PL_defgv)))); 880 PUSHs ((SV *)coro->startcv);
874 PUTBACK; 881 PUTBACK;
875 PL_op = (OP *)&myop; 882 PL_op = (OP *)&myop;
876 PL_op = PL_ppaddr[OP_ENTERSUB](aTHX); 883 PL_op = PL_ppaddr[OP_ENTERSUB](aTHX);
877 SPAGAIN;
878 } 884 }
879 885
880 /* this newly created coroutine might be run on an existing cctx which most 886 /* this newly created coroutine might be run on an existing cctx which most
881 * likely was suspended in pp_slf, so we have to emulate entering pp_slf here. 887 * likely was suspended in pp_slf, so we have to emulate entering pp_slf here.
882 */ 888 */
883 slf_frame.prepare = prepare_nop; /* provide a nop function for an eventual pp_slf */ 889 slf_frame.prepare = prepare_nop; /* provide a nop function for an eventual pp_slf */
884 slf_frame.check = slf_check_nop; /* signal pp_slf to not repeat */ 890 slf_frame.check = slf_check_nop; /* signal pp_slf to not repeat */
885 891
886 coro_throw = coro->throw; 892 /* and we have to provide the pp_slf op in any case, so pp_slf can skip it */
893 coro_setup_op.op_next = PL_op;
894 coro_setup_op.op_type = OP_CUSTOM;
895 coro_setup_op.op_ppaddr = pp_slf;
896 /* no flags etc. required, as an init function won't be called */
897
898 PL_op = (OP *)&coro_setup_op;
899
900 /* copy throw, in case it was set before coro_setup */
901 CORO_THROW = coro->except;
887} 902}
888 903
889static void 904static void
890coro_destruct (pTHX_ struct coro *coro) 905coro_destruct (pTHX_ struct coro *coro)
891{ 906{
915 930
916 SvREFCNT_dec (PL_diehook); 931 SvREFCNT_dec (PL_diehook);
917 SvREFCNT_dec (PL_warnhook); 932 SvREFCNT_dec (PL_warnhook);
918 933
919 SvREFCNT_dec (coro->saved_deffh); 934 SvREFCNT_dec (coro->saved_deffh);
920 SvREFCNT_dec (coro_throw); 935 SvREFCNT_dec (coro->rouse_cb);
936 SvREFCNT_dec (coro->invoke_cb);
937 SvREFCNT_dec (coro->invoke_av);
921 938
922 coro_destruct_stacks (aTHX); 939 coro_destruct_stacks (aTHX);
923} 940}
924 941
925INLINE void 942INLINE void
1012 SAVETMPS; 1029 SAVETMPS;
1013 EXTEND (SP, 3); 1030 EXTEND (SP, 3);
1014 PUSHMARK (SP); 1031 PUSHMARK (SP);
1015 PUSHs (&PL_sv_yes); 1032 PUSHs (&PL_sv_yes);
1016 PUSHs (fullname); 1033 PUSHs (fullname);
1017 PUSHs (CxHASARGS (cx) ? sv_2mortal (newRV_inc ((SV *)cx->blk_sub.argarray)) : &PL_sv_undef); 1034 PUSHs (CxHASARGS (cx) ? sv_2mortal (newRV_inc ((SV *)cx->blk_sub.argarray)) : &PL_sv_undef);
1018 PUTBACK; 1035 PUTBACK;
1019 cb = hv_fetch ((HV *)SvRV (coro_current), "_trace_sub_cb", sizeof ("_trace_sub_cb") - 1, 0); 1036 cb = hv_fetch ((HV *)SvRV (coro_current), "_trace_sub_cb", sizeof ("_trace_sub_cb") - 1, 0);
1020 if (cb) call_sv (*cb, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD); 1037 if (cb) call_sv (*cb, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD);
1021 SPAGAIN; 1038 SPAGAIN;
1022 FREETMPS; 1039 FREETMPS;
1054 1071
1055 TAINT_NOT; 1072 TAINT_NOT;
1056 return 0; 1073 return 0;
1057} 1074}
1058 1075
1076static struct coro_cctx *cctx_ssl_cctx;
1077static struct CoroSLF cctx_ssl_frame;
1078
1059static void 1079static void
1060prepare_set_stacklevel (struct coro_transfer_args *ta, struct coro_cctx *cctx) 1080slf_prepare_set_stacklevel (pTHX_ struct coro_transfer_args *ta)
1061{ 1081{
1062 ta->prev = (struct coro *)cctx; 1082 ta->prev = (struct coro *)cctx_ssl_cctx;
1063 ta->next = 0; 1083 ta->next = 0;
1064} 1084}
1065 1085
1066/* inject a fake call to Coro::State::_cctx_init into the execution */ 1086static int
1067/* _cctx_init should be careful, as it could be called at almost any time */ 1087slf_check_set_stacklevel (pTHX_ struct CoroSLF *frame)
1068/* during execution of a perl program */ 1088{
1069/* also initialises PL_top_env */ 1089 *frame = cctx_ssl_frame;
1090
1091 return frame->check (aTHX_ frame); /* execute the restored frame - there must be one */
1092}
1093
1094/* initialises PL_top_env and injects a pseudo-slf-call to set the stacklevel */
1070static void NOINLINE 1095static void NOINLINE
1071cctx_prepare (pTHX_ coro_cctx *cctx) 1096cctx_prepare (pTHX_ coro_cctx *cctx)
1072{ 1097{
1073 dSP;
1074 UNOP myop;
1075
1076 PL_top_env = &PL_start_env; 1098 PL_top_env = &PL_start_env;
1077 1099
1078 if (cctx->flags & CC_TRACE) 1100 if (cctx->flags & CC_TRACE)
1079 PL_runops = runops_trace; 1101 PL_runops = runops_trace;
1080 1102
1081 Zero (&myop, 1, UNOP); 1103 /* we already must be executing an SLF op, there is no other valid way
1082 myop.op_next = PL_op; 1104 * that can lead to creation of a new cctx */
1083 myop.op_flags = OPf_WANT_VOID | OPf_STACKED; 1105 assert (("FATAL: can't prepare slf-less cctx in Coro module (please report)",
1106 slf_frame.prepare && PL_op->op_ppaddr == pp_slf));
1084 1107
1085 PUSHMARK (SP); 1108 /* we must emulate leaving pp_slf, which is done inside slf_check_set_stacklevel */
1086 EXTEND (SP, 2); 1109 cctx_ssl_cctx = cctx;
1087 PUSHs (sv_2mortal (newSViv ((IV)cctx))); 1110 cctx_ssl_frame = slf_frame;
1088 PUSHs ((SV *)get_cv ("Coro::State::_cctx_init", FALSE)); 1111
1089 PUTBACK; 1112 slf_frame.prepare = slf_prepare_set_stacklevel;
1090 PL_op = (OP *)&myop; 1113 slf_frame.check = slf_check_set_stacklevel;
1091 PL_op = PL_ppaddr[OP_ENTERSUB](aTHX);
1092 SPAGAIN;
1093} 1114}
1094 1115
1095/* the tail of transfer: execute stuff we can only do after a transfer */ 1116/* the tail of transfer: execute stuff we can only do after a transfer */
1096INLINE void 1117INLINE void
1097transfer_tail (pTHX) 1118transfer_tail (pTHX)
1124 transfer_tail (aTHX); 1145 transfer_tail (aTHX);
1125 1146
1126 /* somebody or something will hit me for both perl_run and PL_restartop */ 1147 /* somebody or something will hit me for both perl_run and PL_restartop */
1127 PL_restartop = PL_op; 1148 PL_restartop = PL_op;
1128 perl_run (PL_curinterp); 1149 perl_run (PL_curinterp);
1150 /*
1151 * Unfortunately, there is no way to get at the return values of the
1152 * coro body here, as perl_run destroys these
1153 */
1129 1154
1130 /* 1155 /*
1131 * If perl-run returns we assume exit() was being called or the coro 1156 * If perl-run returns we assume exit() was being called or the coro
1132 * fell off the end, which seems to be the only valid (non-bug) 1157 * fell off the end, which seems to be the only valid (non-bug)
1133 * reason for perl_run to return. We try to exit by jumping to the 1158 * reason for perl_run to return. We try to exit by jumping to the
1313 dSTACKLEVEL; 1338 dSTACKLEVEL;
1314 1339
1315 /* sometimes transfer is only called to set idle_sp */ 1340 /* sometimes transfer is only called to set idle_sp */
1316 if (expect_false (!next)) 1341 if (expect_false (!next))
1317 { 1342 {
1318 ((coro_cctx *)prev)->idle_sp = (void *)stacklevel; 1343 ((coro_cctx *)prev)->idle_sp = STACKLEVEL;
1319 assert (((coro_cctx *)prev)->idle_te = PL_top_env); /* just for the side-effect when asserts are enabled */ 1344 assert (((coro_cctx *)prev)->idle_te = PL_top_env); /* just for the side-effect when asserts are enabled */
1320 } 1345 }
1321 else if (expect_true (prev != next)) 1346 else if (expect_true (prev != next))
1322 { 1347 {
1323 coro_cctx *prev__cctx; 1348 coro_cctx *prev__cctx;
1348 1373
1349 prev__cctx = prev->cctx; 1374 prev__cctx = prev->cctx;
1350 1375
1351 /* possibly untie and reuse the cctx */ 1376 /* possibly untie and reuse the cctx */
1352 if (expect_true ( 1377 if (expect_true (
1353 prev__cctx->idle_sp == (void *)stacklevel 1378 prev__cctx->idle_sp == STACKLEVEL
1354 && !(prev__cctx->flags & CC_TRACE) 1379 && !(prev__cctx->flags & CC_TRACE)
1355 && !force_cctx 1380 && !force_cctx
1356 )) 1381 ))
1357 { 1382 {
1358 /* I assume that stacklevel is a stronger indicator than PL_top_env changes */ 1383 /* I assume that stacklevel is a stronger indicator than PL_top_env changes */
1425 1450
1426 coro->slot = 0; 1451 coro->slot = 0;
1427 } 1452 }
1428 1453
1429 cctx_destroy (coro->cctx); 1454 cctx_destroy (coro->cctx);
1455 SvREFCNT_dec (coro->startcv);
1430 SvREFCNT_dec (coro->args); 1456 SvREFCNT_dec (coro->args);
1457 SvREFCNT_dec (CORO_THROW);
1431 1458
1432 if (coro->next) coro->next->prev = coro->prev; 1459 if (coro->next) coro->next->prev = coro->prev;
1433 if (coro->prev) coro->prev->next = coro->next; 1460 if (coro->prev) coro->prev->next = coro->next;
1434 if (coro == coro_first) coro_first = coro->next; 1461 if (coro == coro_first) coro_first = coro->next;
1435 1462
1489 1516
1490 prepare_transfer (aTHX_ &ta, prev_sv, next_sv); 1517 prepare_transfer (aTHX_ &ta, prev_sv, next_sv);
1491 TRANSFER (ta, 1); 1518 TRANSFER (ta, 1);
1492} 1519}
1493 1520
1521/*****************************************************************************/
1522/* gensub: simple closure generation utility */
1523
1524#define GENSUB_ARG CvXSUBANY (cv).any_ptr
1525
1526/* create a closure from XS, returns a code reference */
1527/* the arg can be accessed via GENSUB_ARG from the callback */
1528/* the callback must use dXSARGS/XSRETURN */
1529static SV *
1530gensub (pTHX_ void (*xsub)(pTHX_ CV *), void *arg)
1531{
1532 CV *cv = (CV *)newSV (0);
1533
1534 sv_upgrade ((SV *)cv, SVt_PVCV);
1535
1536 CvANON_on (cv);
1537 CvISXSUB_on (cv);
1538 CvXSUB (cv) = xsub;
1539 GENSUB_ARG = arg;
1540
1541 return newRV_noinc ((SV *)cv);
1542}
1543
1494/** Coro ********************************************************************/ 1544/** Coro ********************************************************************/
1495 1545
1496INLINE void 1546INLINE void
1497coro_enq (pTHX_ struct coro *coro) 1547coro_enq (pTHX_ struct coro *coro)
1498{ 1548{
1541 ENTER; 1591 ENTER;
1542 SAVETMPS; 1592 SAVETMPS;
1543 1593
1544 PUSHMARK (SP); 1594 PUSHMARK (SP);
1545 PUTBACK; 1595 PUTBACK;
1546 call_sv (sv_hook, G_DISCARD); 1596 call_sv (sv_hook, G_VOID | G_DISCARD);
1547 SPAGAIN;
1548 1597
1549 FREETMPS; 1598 FREETMPS;
1550 LEAVE; 1599 LEAVE;
1551 } 1600 }
1552 1601
1579 ENTER; 1628 ENTER;
1580 SAVETMPS; 1629 SAVETMPS;
1581 1630
1582 PUSHMARK (SP); 1631 PUSHMARK (SP);
1583 PUTBACK; 1632 PUTBACK;
1584 call_sv (get_sv ("Coro::idle", FALSE), G_DISCARD); 1633 call_sv (get_sv ("Coro::idle", FALSE), G_VOID | G_DISCARD);
1585 SPAGAIN;
1586 1634
1587 FREETMPS; 1635 FREETMPS;
1588 LEAVE; 1636 LEAVE;
1589 continue; 1637 continue;
1590 } 1638 }
1697 if (coro->flags & CF_RUNNING) 1745 if (coro->flags & CF_RUNNING)
1698 PL_runops = RUNOPS_DEFAULT; 1746 PL_runops = RUNOPS_DEFAULT;
1699 else 1747 else
1700 coro->slot->runops = RUNOPS_DEFAULT; 1748 coro->slot->runops = RUNOPS_DEFAULT;
1701 } 1749 }
1750}
1751
1752/*****************************************************************************/
1753/* async pool handler */
1754
1755static int
1756slf_check_pool_handler (pTHX_ struct CoroSLF *frame)
1757{
1758 HV *hv = (HV *)SvRV (coro_current);
1759 struct coro *coro = (struct coro *)frame->data;
1760
1761 if (!coro->invoke_cb)
1762 return 1; /* loop till we have invoke */
1763 else
1764 {
1765 int i, len;
1766
1767 hv_store (hv, "desc", sizeof ("desc") - 1,
1768 newSVpvn ("[async_pool]", sizeof ("[async_pool]") - 1), 0);
1769
1770 coro->saved_deffh = SvREFCNT_inc_NN ((SV *)PL_defoutgv);
1771
1772 len = av_len (coro->invoke_av);
1773
1774 {
1775 dSP;
1776 XPUSHs (sv_2mortal (coro->invoke_cb)); coro->invoke_cb = 0;
1777 PUTBACK;
1778 }
1779
1780 SvREFCNT_dec (GvAV (PL_defgv));
1781 GvAV (PL_defgv) = coro->invoke_av;
1782 coro->invoke_av = 0;
1783
1784 return 0;
1785 }
1786}
1787
1788static void
1789slf_init_pool_handler (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
1790{
1791 HV *hv = (HV *)SvRV (coro_current);
1792 struct coro *coro = SvSTATE_hv ((SV *)hv);
1793
1794 if (expect_true (coro->saved_deffh))
1795 {
1796 /* subsequent iteration */
1797 SvREFCNT_dec ((SV *)PL_defoutgv); PL_defoutgv = (GV *)coro->saved_deffh;
1798 coro->saved_deffh = 0;
1799
1800 if (coro_rss (aTHX_ coro) > SvUV (sv_pool_rss)
1801 || av_len (av_async_pool) + 1 >= SvIV (sv_pool_size))
1802 {
1803 coro->invoke_cb = SvREFCNT_inc_NN ((SV *)cv_coro_terminate);
1804 coro->invoke_av = newAV ();
1805
1806 frame->prepare = prepare_nop;
1807 }
1808 else
1809 {
1810 av_clear (GvAV (PL_defgv));
1811 hv_store (hv, "desc", sizeof ("desc") - 1, SvREFCNT_inc_NN (sv_async_pool_idle), 0);
1812
1813 coro->prio = 0;
1814
1815 if (coro->cctx && (coro->cctx->flags & CC_TRACE))
1816 api_trace (aTHX_ coro_current, 0);
1817
1818 frame->prepare = prepare_schedule;
1819 av_push (av_async_pool, SvREFCNT_inc (hv));
1820 }
1821 }
1822 else
1823 {
1824 /* first iteration, simply fall through */
1825 frame->prepare = prepare_nop;
1826 }
1827
1828 frame->check = slf_check_pool_handler;
1829 frame->data = (void *)coro;
1830}
1831
1832/*****************************************************************************/
1833/* rouse callback */
1834
1835#define CORO_MAGIC_type_rouse PERL_MAGIC_ext
1836
1837static void
1838coro_rouse_callback (pTHX_ CV *cv)
1839{
1840 dXSARGS;
1841 SV *data = (SV *)GENSUB_ARG;
1842
1843 if (SvTYPE (SvRV (data)) != SVt_PVAV)
1844 {
1845 /* first call, set args */
1846 int i;
1847 AV *av = newAV ();
1848 SV *coro = SvRV (data);
1849
1850 SvRV_set (data, (SV *)av);
1851 api_ready (aTHX_ coro);
1852 SvREFCNT_dec (coro);
1853
1854 /* better take a full copy of the arguments */
1855 while (items--)
1856 av_store (av, items, newSVsv (ST (items)));
1857 }
1858
1859 XSRETURN_EMPTY;
1860}
1861
1862static int
1863slf_check_rouse_wait (pTHX_ struct CoroSLF *frame)
1864{
1865 SV *data = (SV *)frame->data;
1866
1867 if (CORO_THROW)
1868 return 0;
1869
1870 if (SvTYPE (SvRV (data)) != SVt_PVAV)
1871 return 1;
1872
1873 /* now push all results on the stack */
1874 {
1875 dSP;
1876 AV *av = (AV *)SvRV (data);
1877 int i;
1878
1879 EXTEND (SP, AvFILLp (av) + 1);
1880 for (i = 0; i <= AvFILLp (av); ++i)
1881 PUSHs (sv_2mortal (AvARRAY (av)[i]));
1882
1883 /* we have stolen the elements, so ste length to zero and free */
1884 AvFILLp (av) = -1;
1885 av_undef (av);
1886
1887 PUTBACK;
1888 }
1889
1890 return 0;
1891}
1892
1893static void
1894slf_init_rouse_wait (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
1895{
1896 SV *cb;
1897
1898 if (items)
1899 cb = arg [0];
1900 else
1901 {
1902 struct coro *coro = SvSTATE_current;
1903
1904 if (!coro->rouse_cb)
1905 croak ("Coro::rouse_wait called without rouse callback, and no default rouse callback found either,");
1906
1907 cb = sv_2mortal (coro->rouse_cb);
1908 coro->rouse_cb = 0;
1909 }
1910
1911 if (!SvROK (cb)
1912 || SvTYPE (SvRV (cb)) != SVt_PVCV
1913 || CvXSUB ((CV *)SvRV (cb)) != coro_rouse_callback)
1914 croak ("Coro::rouse_wait called with illegal callback argument,");
1915
1916 {
1917 CV *cv = (CV *)SvRV (cb); /* for GENSUB_ARG */
1918 SV *data = (SV *)GENSUB_ARG;
1919
1920 frame->data = (void *)data;
1921 frame->prepare = SvTYPE (SvRV (data)) == SVt_PVAV ? prepare_nop : prepare_schedule;
1922 frame->check = slf_check_rouse_wait;
1923 }
1924}
1925
1926static SV *
1927coro_new_rouse_cb (pTHX)
1928{
1929 HV *hv = (HV *)SvRV (coro_current);
1930 struct coro *coro = SvSTATE_hv (hv);
1931 SV *data = newRV_inc ((SV *)hv);
1932 SV *cb = gensub (aTHX_ coro_rouse_callback, (void *)data);
1933
1934 sv_magicext (SvRV (cb), data, CORO_MAGIC_type_rouse, 0, 0, 0);
1935 SvREFCNT_dec (data); /* magicext increases the refcount */
1936
1937 SvREFCNT_dec (coro->rouse_cb);
1938 coro->rouse_cb = SvREFCNT_inc_NN (cb);
1939
1940 return cb;
1941}
1942
1943/*****************************************************************************/
1944/* schedule-like-function opcode (SLF) */
1945
1946static UNOP slf_restore; /* restore stack as entersub did, for first-re-run */
1947static const CV *slf_cv;
1948static SV **slf_argv;
1949static int slf_argc, slf_arga; /* count, allocated */
1950static I32 slf_ax; /* top of stack, for restore */
1951
1952/* this restores the stack in the case we patched the entersub, to */
1953/* recreate the stack frame as perl will on following calls */
1954/* since entersub cleared the stack */
1955static OP *
1956pp_restore (pTHX)
1957{
1958 int i;
1959 SV **SP = PL_stack_base + slf_ax;
1960
1961 PUSHMARK (SP);
1962
1963 EXTEND (SP, slf_argc + 1);
1964
1965 for (i = 0; i < slf_argc; ++i)
1966 PUSHs (sv_2mortal (slf_argv [i]));
1967
1968 PUSHs ((SV *)CvGV (slf_cv));
1969
1970 RETURNOP (slf_restore.op_first);
1971}
1972
1973static void
1974slf_prepare_transfer (pTHX_ struct coro_transfer_args *ta)
1975{
1976 SV **arg = (SV **)slf_frame.data;
1977
1978 prepare_transfer (aTHX_ ta, arg [0], arg [1]);
1979}
1980
1981static void
1982slf_init_transfer (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
1983{
1984 if (items != 2)
1985 croak ("Coro::State::transfer (prev, next) expects two arguments, not %d,", items);
1986
1987 frame->prepare = slf_prepare_transfer;
1988 frame->check = slf_check_nop;
1989 frame->data = (void *)arg; /* let's hope it will stay valid */
1990}
1991
1992static void
1993slf_init_schedule (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
1994{
1995 frame->prepare = prepare_schedule;
1996 frame->check = slf_check_nop;
1997}
1998
1999static void
2000slf_init_cede (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2001{
2002 frame->prepare = prepare_cede;
2003 frame->check = slf_check_nop;
2004}
2005
2006static void
2007slf_init_cede_notself (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2008{
2009 frame->prepare = prepare_cede_notself;
2010 frame->check = slf_check_nop;
2011}
2012
2013/*
2014 * these not obviously related functions are all rolled into one
2015 * function to increase chances that they all will call transfer with the same
2016 * stack offset
2017 * SLF stands for "schedule-like-function".
2018 */
2019static OP *
2020pp_slf (pTHX)
2021{
2022 I32 checkmark; /* mark SP to see how many elements check has pushed */
2023
2024 /* set up the slf frame, unless it has already been set-up */
2025 /* the latter happens when a new coro has been started */
2026 /* or when a new cctx was attached to an existing coroutine */
2027 if (expect_true (!slf_frame.prepare))
2028 {
2029 /* first iteration */
2030 dSP;
2031 SV **arg = PL_stack_base + TOPMARK + 1;
2032 int items = SP - arg; /* args without function object */
2033 SV *gv = *sp;
2034
2035 /* do a quick consistency check on the "function" object, and if it isn't */
2036 /* for us, divert to the real entersub */
2037 if (SvTYPE (gv) != SVt_PVGV
2038 || !GvCV (gv)
2039 || !(CvFLAGS (GvCV (gv)) & CVf_SLF))
2040 return PL_ppaddr[OP_ENTERSUB](aTHX);
2041
2042 if (!(PL_op->op_flags & OPf_STACKED))
2043 {
2044 /* ampersand-form of call, use @_ instead of stack */
2045 AV *av = GvAV (PL_defgv);
2046 arg = AvARRAY (av);
2047 items = AvFILLp (av) + 1;
2048 }
2049
2050 /* now call the init function, which needs to set up slf_frame */
2051 ((coro_slf_cb)CvXSUBANY (GvCV (gv)).any_ptr)
2052 (aTHX_ &slf_frame, GvCV (gv), arg, items);
2053
2054 /* pop args */
2055 SP = PL_stack_base + POPMARK;
2056
2057 PUTBACK;
2058 }
2059
2060 /* now that we have a slf_frame, interpret it! */
2061 /* we use a callback system not to make the code needlessly */
2062 /* complicated, but so we can run multiple perl coros from one cctx */
2063
2064 do
2065 {
2066 struct coro_transfer_args ta;
2067
2068 slf_frame.prepare (aTHX_ &ta);
2069 TRANSFER (ta, 0);
2070
2071 checkmark = PL_stack_sp - PL_stack_base;
2072 }
2073 while (slf_frame.check (aTHX_ &slf_frame));
2074
2075 slf_frame.prepare = 0; /* invalidate the frame, we are done processing it */
2076
2077 /* exception handling */
2078 if (expect_false (CORO_THROW))
2079 {
2080 SV *exception = sv_2mortal (CORO_THROW);
2081
2082 CORO_THROW = 0;
2083 sv_setsv (ERRSV, exception);
2084 croak (0);
2085 }
2086
2087 /* return value handling - mostly like entersub */
2088 /* make sure we put something on the stack in scalar context */
2089 if (GIMME_V == G_SCALAR)
2090 {
2091 dSP;
2092 SV **bot = PL_stack_base + checkmark;
2093
2094 if (sp == bot) /* too few, push undef */
2095 bot [1] = &PL_sv_undef;
2096 else if (sp != bot + 1) /* too many, take last one */
2097 bot [1] = *sp;
2098
2099 SP = bot + 1;
2100
2101 PUTBACK;
2102 }
2103
2104 return NORMAL;
2105}
2106
2107static void
2108api_execute_slf (pTHX_ CV *cv, coro_slf_cb init_cb, I32 ax)
2109{
2110 int i;
2111 SV **arg = PL_stack_base + ax;
2112 int items = PL_stack_sp - arg + 1;
2113
2114 assert (("FATAL: SLF call with illegal CV value", !CvANON (cv)));
2115
2116 if (PL_op->op_ppaddr != PL_ppaddr [OP_ENTERSUB]
2117 && PL_op->op_ppaddr != pp_slf)
2118 croak ("FATAL: Coro SLF calls can only be made normally, not via goto or any other means, caught");
2119
2120 CvFLAGS (cv) |= CVf_SLF;
2121 CvXSUBANY (cv).any_ptr = (void *)init_cb;
2122 slf_cv = cv;
2123
2124 /* we patch the op, and then re-run the whole call */
2125 /* we have to put the same argument on the stack for this to work */
2126 /* and this will be done by pp_restore */
2127 slf_restore.op_next = (OP *)&slf_restore;
2128 slf_restore.op_type = OP_CUSTOM;
2129 slf_restore.op_ppaddr = pp_restore;
2130 slf_restore.op_first = PL_op;
2131
2132 slf_ax = ax - 1; /* undo the ax++ inside dAXMARK */
2133
2134 if (PL_op->op_flags & OPf_STACKED)
2135 {
2136 if (items > slf_arga)
2137 {
2138 slf_arga = items;
2139 free (slf_argv);
2140 slf_argv = malloc (slf_arga * sizeof (SV *));
2141 }
2142
2143 slf_argc = items;
2144
2145 for (i = 0; i < items; ++i)
2146 slf_argv [i] = SvREFCNT_inc (arg [i]);
2147 }
2148 else
2149 slf_argc = 0;
2150
2151 PL_op->op_ppaddr = pp_slf;
2152 PL_op->op_type = OP_CUSTOM; /* maybe we should leave it at entersub? */
2153
2154 PL_op = (OP *)&slf_restore;
1702} 2155}
1703 2156
1704/*****************************************************************************/ 2157/*****************************************************************************/
1705/* PerlIO::cede */ 2158/* PerlIO::cede */
1706 2159
1775 PerlIOBuf_get_cnt, 2228 PerlIOBuf_get_cnt,
1776 PerlIOBuf_set_ptrcnt, 2229 PerlIOBuf_set_ptrcnt,
1777}; 2230};
1778 2231
1779/*****************************************************************************/ 2232/*****************************************************************************/
2233/* Coro::Semaphore & Coro::Signal */
1780 2234
1781static UNOP slf_restore; /* restore stack as entersub did, for first-re-run */
1782static const CV *slf_cv;
1783static SV **slf_argv;
1784static int slf_argc, slf_arga; /* count, allocated */
1785static I32 slf_ax; /* top of stack, for restore */
1786
1787/* this restores the stack in the case we patched the entersub, to */
1788/* recreate the stack frame as perl will on following calls */
1789/* since entersub cleared the stack */
1790static OP * 2235static SV *
1791pp_restore (pTHX) 2236coro_waitarray_new (pTHX_ int count)
1792{ 2237{
1793 int i; 2238 /* a semaphore contains a counter IV in $sem->[0] and any waiters after that */
1794 SV **SP = PL_stack_base + slf_ax; 2239 AV *av = newAV ();
2240 SV **ary;
1795 2241
1796 PUSHMARK (SP); 2242 /* unfortunately, building manually saves memory */
2243 Newx (ary, 2, SV *);
2244 AvALLOC (av) = ary;
2245 /*AvARRAY (av) = ary;*/
2246 SvPVX ((SV *)av) = (char *)ary; /* 5.8.8 needs this syntax instead of AvARRAY = ary */
2247 AvMAX (av) = 1;
2248 AvFILLp (av) = 0;
2249 ary [0] = newSViv (count);
1797 2250
1798 EXTEND (SP, slf_argc + 1); 2251 return newRV_noinc ((SV *)av);
1799
1800 for (i = 0; i < slf_argc; ++i)
1801 PUSHs (sv_2mortal (slf_argv [i]));
1802
1803 PUSHs ((SV *)CvGV (slf_cv));
1804
1805 RETURNOP (slf_restore.op_first);
1806} 2252}
1807 2253
1808static void 2254/* semaphore */
1809slf_prepare_set_stacklevel (pTHX_ struct coro_transfer_args *ta)
1810{
1811 prepare_set_stacklevel (ta, (struct coro_cctx *)slf_frame.data);
1812}
1813
1814static void
1815slf_init_set_stacklevel (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
1816{
1817 assert (("FATAL: set_stacklevel needs the coro cctx as sole argument", items == 1));
1818
1819 frame->prepare = slf_prepare_set_stacklevel;
1820 frame->check = slf_check_nop;
1821 frame->data = (void *)SvIV (arg [0]);
1822}
1823
1824static void
1825slf_prepare_transfer (pTHX_ struct coro_transfer_args *ta)
1826{
1827 SV **arg = (SV **)slf_frame.data;
1828
1829 prepare_transfer (aTHX_ ta, arg [0], arg [1]);
1830}
1831
1832static void
1833slf_init_transfer (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
1834{
1835 if (items != 2)
1836 croak ("Coro::State::transfer (prev, next) expects two arguments, not %d,", items);
1837
1838 frame->prepare = slf_prepare_transfer;
1839 frame->check = slf_check_nop;
1840 frame->data = (void *)arg; /* let's hope it will stay valid */
1841}
1842
1843static void
1844slf_init_schedule (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
1845{
1846 frame->prepare = prepare_schedule;
1847 frame->check = slf_check_nop;
1848}
1849
1850static void
1851slf_init_cede (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
1852{
1853 frame->prepare = prepare_cede;
1854 frame->check = slf_check_nop;
1855}
1856
1857static void
1858slf_init_cede_notself (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
1859{
1860 frame->prepare = prepare_cede_notself;
1861 frame->check = slf_check_nop;
1862}
1863
1864/* we hijack an hopefully unused CV flag for our purposes */
1865#define CVf_SLF 0x4000
1866
1867/*
1868 * these not obviously related functions are all rolled into one
1869 * function to increase chances that they all will call transfer with the same
1870 * stack offset
1871 * SLF stands for "schedule-like-function".
1872 */
1873static OP *
1874pp_slf (pTHX)
1875{
1876 I32 checkmark; /* mark SP to see how many elements check has pushed */
1877
1878 /* set up the slf frame, unless it has already been set-up */
1879 /* the latter happens when a new coro has been started */
1880 /* or when a new cctx was attached to an existing coroutine */
1881 if (expect_true (!slf_frame.prepare))
1882 {
1883 /* first iteration */
1884 dSP;
1885 SV **arg = PL_stack_base + TOPMARK + 1;
1886 int items = SP - arg; /* args without function object */
1887 SV *gv = *sp;
1888
1889 /* do a quick consistency check on the "function" object, and if it isn't */
1890 /* for us, divert to the real entersub */
1891 if (SvTYPE (gv) != SVt_PVGV || !(CvFLAGS (GvCV (gv)) & CVf_SLF))
1892 return PL_ppaddr[OP_ENTERSUB](aTHX);
1893
1894 if (!(PL_op->op_flags & OPf_STACKED))
1895 {
1896 /* ampersand-form of call, use @_ instead of stack */
1897 AV *av = GvAV (PL_defgv);
1898 arg = AvARRAY (av);
1899 items = AvFILLp (av) + 1;
1900 }
1901
1902 /* now call the init function, which needs to set up slf_frame */
1903 ((coro_slf_cb)CvXSUBANY (GvCV (gv)).any_ptr)
1904 (aTHX_ &slf_frame, GvCV (gv), arg, items);
1905
1906 /* pop args */
1907 SP = PL_stack_base + POPMARK;
1908
1909 PUTBACK;
1910 }
1911
1912 /* now that we have a slf_frame, interpret it! */
1913 /* we use a callback system not to make the code needlessly */
1914 /* complicated, but so we can run multiple perl coros from one cctx */
1915
1916 do
1917 {
1918 struct coro_transfer_args ta;
1919
1920 slf_frame.prepare (aTHX_ &ta);
1921 TRANSFER (ta, 0);
1922
1923 checkmark = PL_stack_sp - PL_stack_base;
1924 }
1925 while (slf_frame.check (aTHX_ &slf_frame));
1926
1927 slf_frame.prepare = 0; /* invalidate the frame, we are done processing it */
1928
1929 /* return value handling - mostly like entersub */
1930 {
1931 dSP;
1932 SV **bot = PL_stack_base + checkmark;
1933 int gimme = GIMME_V;
1934
1935 /* make sure we put something on the stack in scalar context */
1936 if (gimme == G_SCALAR)
1937 {
1938 if (sp == bot)
1939 XPUSHs (&PL_sv_undef);
1940
1941 SP = bot + 1;
1942 }
1943
1944 PUTBACK;
1945 }
1946
1947 /* exception handling */
1948 if (expect_false (coro_throw))
1949 {
1950 SV *exception = sv_2mortal (coro_throw);
1951
1952 coro_throw = 0;
1953 sv_setsv (ERRSV, exception);
1954 croak (0);
1955 }
1956
1957 return NORMAL;
1958}
1959
1960static void
1961api_execute_slf (pTHX_ CV *cv, coro_slf_cb init_cb, I32 ax)
1962{
1963 int i;
1964 SV **arg = PL_stack_base + ax;
1965 int items = PL_stack_sp - arg + 1;
1966
1967 assert (("FATAL: SLF call with illegal CV value", !CvANON (cv)));
1968
1969 if (PL_op->op_ppaddr != PL_ppaddr [OP_ENTERSUB]
1970 && PL_op->op_ppaddr != pp_slf)
1971 croak ("FATAL: Coro SLF calls can only be made normally, not via goto or any other means, caught");
1972
1973 CvFLAGS (cv) |= CVf_SLF;
1974 CvXSUBANY (cv).any_ptr = (void *)init_cb;
1975 slf_cv = cv;
1976
1977 /* we patch the op, and then re-run the whole call */
1978 /* we have to put the same argument on the stack for this to work */
1979 /* and this will be done by pp_restore */
1980 slf_restore.op_next = (OP *)&slf_restore;
1981 slf_restore.op_type = OP_CUSTOM;
1982 slf_restore.op_ppaddr = pp_restore;
1983 slf_restore.op_first = PL_op;
1984
1985 slf_ax = ax - 1; /* undo the ax++ inside dAXMARK */
1986
1987 if (PL_op->op_flags & OPf_STACKED)
1988 {
1989 if (items > slf_arga)
1990 {
1991 slf_arga = items;
1992 free (slf_argv);
1993 slf_argv = malloc (slf_arga * sizeof (SV *));
1994 }
1995
1996 slf_argc = items;
1997
1998 for (i = 0; i < items; ++i)
1999 slf_argv [i] = SvREFCNT_inc (arg [i]);
2000 }
2001 else
2002 slf_argc = 0;
2003
2004 PL_op->op_ppaddr = pp_slf;
2005 PL_op->op_type = OP_CUSTOM; /* maybe we should leave it at entersub? */
2006
2007 PL_op = (OP *)&slf_restore;
2008}
2009
2010/*****************************************************************************/
2011 2255
2012static void 2256static void
2013coro_semaphore_adjust (pTHX_ AV *av, IV adjust) 2257coro_semaphore_adjust (pTHX_ AV *av, IV adjust)
2014{ 2258{
2015 SV *count_sv = AvARRAY (av)[0]; 2259 SV *count_sv = AvARRAY (av)[0];
2027 AvARRAY (av)[0] = AvARRAY (av)[1]; 2271 AvARRAY (av)[0] = AvARRAY (av)[1];
2028 AvARRAY (av)[1] = count_sv; 2272 AvARRAY (av)[1] = count_sv;
2029 cb = av_shift (av); 2273 cb = av_shift (av);
2030 2274
2031 if (SvOBJECT (cb)) 2275 if (SvOBJECT (cb))
2276 {
2032 api_ready (aTHX_ cb); 2277 api_ready (aTHX_ cb);
2033 else 2278 --count;
2034 croak ("callbacks not yet supported"); 2279 }
2280 else if (SvTYPE (cb) == SVt_PVCV)
2281 {
2282 dSP;
2283 PUSHMARK (SP);
2284 XPUSHs (sv_2mortal (newRV_inc ((SV *)av)));
2285 PUTBACK;
2286 call_sv (cb, G_VOID | G_DISCARD | G_EVAL | G_KEEPERR);
2287 }
2035 2288
2036 SvREFCNT_dec (cb); 2289 SvREFCNT_dec (cb);
2037
2038 --count;
2039 } 2290 }
2040} 2291}
2041 2292
2042static void 2293static void
2043coro_semaphore_on_destroy (pTHX_ struct coro *coro) 2294coro_semaphore_on_destroy (pTHX_ struct coro *coro)
2045 /* call $sem->adjust (0) to possibly wake up some other waiters */ 2296 /* call $sem->adjust (0) to possibly wake up some other waiters */
2046 coro_semaphore_adjust (aTHX_ (AV *)coro->slf_frame.data, 0); 2297 coro_semaphore_adjust (aTHX_ (AV *)coro->slf_frame.data, 0);
2047} 2298}
2048 2299
2049static int 2300static int
2050slf_check_semaphore_down (pTHX_ struct CoroSLF *frame) 2301slf_check_semaphore_down_or_wait (pTHX_ struct CoroSLF *frame, int acquire)
2051{ 2302{
2052 AV *av = (AV *)frame->data; 2303 AV *av = (AV *)frame->data;
2053 SV *count_sv = AvARRAY (av)[0]; 2304 SV *count_sv = AvARRAY (av)[0];
2054 2305
2306 /* if we are about to throw, don't actually acquire the lock, just throw */
2307 if (CORO_THROW)
2308 return 0;
2055 if (SvIVX (count_sv) > 0) 2309 else if (SvIVX (count_sv) > 0)
2056 { 2310 {
2057 SvSTATE_current->on_destroy = 0; 2311 SvSTATE_current->on_destroy = 0;
2312
2313 if (acquire)
2058 SvIVX (count_sv) = SvIVX (count_sv) - 1; 2314 SvIVX (count_sv) = SvIVX (count_sv) - 1;
2315 else
2316 coro_semaphore_adjust (aTHX_ av, 0);
2317
2059 return 0; 2318 return 0;
2060 } 2319 }
2061 else 2320 else
2062 { 2321 {
2063 int i; 2322 int i;
2072 av_push (av, SvREFCNT_inc (SvRV (coro_current))); 2331 av_push (av, SvREFCNT_inc (SvRV (coro_current)));
2073 return 1; 2332 return 1;
2074 } 2333 }
2075} 2334}
2076 2335
2077static void 2336static int
2337slf_check_semaphore_down (pTHX_ struct CoroSLF *frame)
2338{
2339 return slf_check_semaphore_down_or_wait (aTHX_ frame, 1);
2340}
2341
2342static int
2343slf_check_semaphore_wait (pTHX_ struct CoroSLF *frame)
2344{
2345 return slf_check_semaphore_down_or_wait (aTHX_ frame, 0);
2346}
2347
2348static void
2078slf_init_semaphore_down (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) 2349slf_init_semaphore_down_or_wait (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2079{ 2350{
2080 AV *av = (AV *)SvRV (arg [0]); 2351 AV *av = (AV *)SvRV (arg [0]);
2081 2352
2082 if (SvIVX (AvARRAY (av)[0]) > 0) 2353 if (SvIVX (AvARRAY (av)[0]) > 0)
2083 { 2354 {
2084 frame->data = (void *)av; 2355 frame->data = (void *)av;
2085 frame->prepare = prepare_nop; 2356 frame->prepare = prepare_nop;
2086 SvSTATE_current->on_destroy = coro_semaphore_on_destroy;
2087 } 2357 }
2088 else 2358 else
2089 { 2359 {
2090 av_push (av, SvREFCNT_inc (SvRV (coro_current))); 2360 av_push (av, SvREFCNT_inc (SvRV (coro_current)));
2091 2361
2092 frame->data = (void *)sv_2mortal (SvREFCNT_inc ((SV *)av)); 2362 frame->data = (void *)sv_2mortal (SvREFCNT_inc ((SV *)av));
2093 frame->prepare = prepare_schedule; 2363 frame->prepare = prepare_schedule;
2094 2364
2095 /* to avoid race conditions when a woken-up coro gets terminated */ 2365 /* to avoid race conditions when a woken-up coro gets terminated */
2096 /* we arrange for a temporary on_destroy that calls adjust (0) */ 2366 /* we arrange for a temporary on_destroy that calls adjust (0) */
2097 assert (!SvSTATE_current->on_destroy);//D
2098 SvSTATE_current->on_destroy = coro_semaphore_on_destroy; 2367 SvSTATE_current->on_destroy = coro_semaphore_on_destroy;
2099 } 2368 }
2369}
2100 2370
2371static void
2372slf_init_semaphore_down (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2373{
2374 slf_init_semaphore_down_or_wait (aTHX_ frame, cv, arg, items);
2101 frame->check = slf_check_semaphore_down; 2375 frame->check = slf_check_semaphore_down;
2376}
2102 2377
2378static void
2379slf_init_semaphore_wait (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2380{
2381 if (items >= 2)
2382 {
2383 /* callback form */
2384 AV *av = (AV *)SvRV (arg [0]);
2385 CV *cb_cv = coro_sv_2cv (aTHX_ arg [1]);
2386
2387 av_push (av, (SV *)SvREFCNT_inc_NN (cb_cv));
2388
2389 if (SvIVX (AvARRAY (av)[0]) > 0)
2390 coro_semaphore_adjust (aTHX_ av, 0);
2391
2392 frame->prepare = prepare_nop;
2393 frame->check = slf_check_nop;
2394 }
2395 else
2396 {
2397 slf_init_semaphore_down_or_wait (aTHX_ frame, cv, arg, items);
2398 frame->check = slf_check_semaphore_wait;
2399 }
2400}
2401
2402/* signal */
2403
2404static void
2405coro_signal_wake (pTHX_ AV *av, int count)
2406{
2407 SvIVX (AvARRAY (av)[0]) = 0;
2408
2409 /* now signal count waiters */
2410 while (count > 0 && AvFILLp (av) > 0)
2411 {
2412 SV *cb;
2413
2414 /* swap first two elements so we can shift a waiter */
2415 cb = AvARRAY (av)[0];
2416 AvARRAY (av)[0] = AvARRAY (av)[1];
2417 AvARRAY (av)[1] = cb;
2418
2419 cb = av_shift (av);
2420
2421 api_ready (aTHX_ cb);
2422 sv_setiv (cb, 0); /* signal waiter */
2423 SvREFCNT_dec (cb);
2424
2425 --count;
2426 }
2427}
2428
2429static int
2430slf_check_signal_wait (pTHX_ struct CoroSLF *frame)
2431{
2432 /* if we are about to throw, also stop waiting */
2433 return SvROK ((SV *)frame->data) && !CORO_THROW;
2434}
2435
2436static void
2437slf_init_signal_wait (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2438{
2439 AV *av = (AV *)SvRV (arg [0]);
2440
2441 if (SvIVX (AvARRAY (av)[0]))
2442 {
2443 SvIVX (AvARRAY (av)[0]) = 0;
2444 frame->prepare = prepare_nop;
2445 frame->check = slf_check_nop;
2446 }
2447 else
2448 {
2449 SV *waiter = newRV_inc (SvRV (coro_current)); /* owned by signal av */
2450
2451 av_push (av, waiter);
2452
2453 frame->data = (void *)sv_2mortal (SvREFCNT_inc_NN (waiter)); /* owned by process */
2454 frame->prepare = prepare_schedule;
2455 frame->check = slf_check_signal_wait;
2456 }
2103} 2457}
2104 2458
2105/*****************************************************************************/ 2459/*****************************************************************************/
2460/* Coro::AIO */
2106 2461
2107#define GENSUB_ARG CvXSUBANY (cv).any_ptr 2462#define CORO_MAGIC_type_aio PERL_MAGIC_ext
2108 2463
2109/* create a closure from XS, returns a code reference */ 2464/* helper storage struct */
2110/* the arg can be accessed via GENSUB_ARG from the callback */ 2465struct io_state
2111/* the callback must use dXSARGS/XSRETURN */
2112static SV *
2113gensub (pTHX_ void (*xsub)(pTHX_ CV *), void *arg)
2114{ 2466{
2115 CV *cv = (CV *)NEWSV (0, 0); 2467 int errorno;
2468 I32 laststype; /* U16 in 5.10.0 */
2469 int laststatval;
2470 Stat_t statcache;
2471};
2116 2472
2473static void
2474coro_aio_callback (pTHX_ CV *cv)
2475{
2476 dXSARGS;
2477 AV *state = (AV *)GENSUB_ARG;
2478 SV *coro = av_pop (state);
2479 SV *data_sv = newSV (sizeof (struct io_state));
2480
2481 av_extend (state, items - 1);
2482
2117 sv_upgrade ((SV *)cv, SVt_PVCV); 2483 sv_upgrade (data_sv, SVt_PV);
2484 SvCUR_set (data_sv, sizeof (struct io_state));
2485 SvPOK_only (data_sv);
2118 2486
2119 CvANON_on (cv); 2487 {
2120 CvISXSUB_on (cv); 2488 struct io_state *data = (struct io_state *)SvPVX (data_sv);
2121 CvXSUB (cv) = xsub;
2122 GENSUB_ARG = arg;
2123 2489
2124 return newRV_noinc ((SV *)cv); 2490 data->errorno = errno;
2491 data->laststype = PL_laststype;
2492 data->laststatval = PL_laststatval;
2493 data->statcache = PL_statcache;
2494 }
2495
2496 /* now build the result vector out of all the parameters and the data_sv */
2497 {
2498 int i;
2499
2500 for (i = 0; i < items; ++i)
2501 av_push (state, SvREFCNT_inc_NN (ST (i)));
2502 }
2503
2504 av_push (state, data_sv);
2505
2506 api_ready (aTHX_ coro);
2507 SvREFCNT_dec (coro);
2508 SvREFCNT_dec ((AV *)state);
2509}
2510
2511static int
2512slf_check_aio_req (pTHX_ struct CoroSLF *frame)
2513{
2514 AV *state = (AV *)frame->data;
2515
2516 /* if we are about to throw, return early */
2517 /* this does not cancel the aio request, but at least */
2518 /* it quickly returns */
2519 if (CORO_THROW)
2520 return 0;
2521
2522 /* one element that is an RV? repeat! */
2523 if (AvFILLp (state) == 0 && SvROK (AvARRAY (state)[0]))
2524 return 1;
2525
2526 /* restore status */
2527 {
2528 SV *data_sv = av_pop (state);
2529 struct io_state *data = (struct io_state *)SvPVX (data_sv);
2530
2531 errno = data->errorno;
2532 PL_laststype = data->laststype;
2533 PL_laststatval = data->laststatval;
2534 PL_statcache = data->statcache;
2535
2536 SvREFCNT_dec (data_sv);
2537 }
2538
2539 /* push result values */
2540 {
2541 dSP;
2542 int i;
2543
2544 EXTEND (SP, AvFILLp (state) + 1);
2545 for (i = 0; i <= AvFILLp (state); ++i)
2546 PUSHs (sv_2mortal (SvREFCNT_inc_NN (AvARRAY (state)[i])));
2547
2548 PUTBACK;
2549 }
2550
2551 return 0;
2552}
2553
2554static void
2555slf_init_aio_req (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2556{
2557 AV *state = (AV *)sv_2mortal ((SV *)newAV ());
2558 SV *coro_hv = SvRV (coro_current);
2559 struct coro *coro = SvSTATE_hv (coro_hv);
2560
2561 /* put our coroutine id on the state arg */
2562 av_push (state, SvREFCNT_inc_NN (coro_hv));
2563
2564 /* first see whether we have a non-zero priority and set it as AIO prio */
2565 if (coro->prio)
2566 {
2567 dSP;
2568
2569 static SV *prio_cv;
2570 static SV *prio_sv;
2571
2572 if (expect_false (!prio_cv))
2573 {
2574 prio_cv = (SV *)get_cv ("IO::AIO::aioreq_pri", 0);
2575 prio_sv = newSViv (0);
2576 }
2577
2578 PUSHMARK (SP);
2579 sv_setiv (prio_sv, coro->prio);
2580 XPUSHs (prio_sv);
2581
2582 PUTBACK;
2583 call_sv (prio_cv, G_VOID | G_DISCARD);
2584 }
2585
2586 /* now call the original request */
2587 {
2588 dSP;
2589 CV *req = (CV *)CORO_MAGIC_NN ((SV *)cv, CORO_MAGIC_type_aio)->mg_obj;
2590 int i;
2591
2592 PUSHMARK (SP);
2593
2594 /* first push all args to the stack */
2595 EXTEND (SP, items + 1);
2596
2597 for (i = 0; i < items; ++i)
2598 PUSHs (arg [i]);
2599
2600 /* now push the callback closure */
2601 PUSHs (sv_2mortal (gensub (aTHX_ coro_aio_callback, (void *)SvREFCNT_inc_NN ((SV *)state))));
2602
2603 /* now call the AIO function - we assume our request is uncancelable */
2604 PUTBACK;
2605 call_sv ((SV *)req, G_VOID | G_DISCARD);
2606 }
2607
2608 /* now that the requets is going, we loop toll we have a result */
2609 frame->data = (void *)state;
2610 frame->prepare = prepare_schedule;
2611 frame->check = slf_check_aio_req;
2612}
2613
2614static void
2615coro_aio_req_xs (pTHX_ CV *cv)
2616{
2617 dXSARGS;
2618
2619 CORO_EXECUTE_SLF_XS (slf_init_aio_req);
2620
2621 XSRETURN_EMPTY;
2125} 2622}
2126 2623
2127/*****************************************************************************/ 2624/*****************************************************************************/
2128 2625
2129MODULE = Coro::State PACKAGE = Coro::State PREFIX = api_ 2626MODULE = Coro::State PACKAGE = Coro::State PREFIX = api_
2199 assert (("PRIO_NORMAL must be 0", !PRIO_NORMAL)); 2696 assert (("PRIO_NORMAL must be 0", !PRIO_NORMAL));
2200} 2697}
2201 2698
2202SV * 2699SV *
2203new (char *klass, ...) 2700new (char *klass, ...)
2701 ALIAS:
2702 Coro::new = 1
2204 CODE: 2703 CODE:
2205{ 2704{
2206 struct coro *coro; 2705 struct coro *coro;
2207 MAGIC *mg; 2706 MAGIC *mg;
2208 HV *hv; 2707 HV *hv;
2708 CV *cb;
2209 int i; 2709 int i;
2710
2711 if (items > 1)
2712 {
2713 cb = coro_sv_2cv (aTHX_ ST (1));
2714
2715 if (!ix)
2716 {
2717 if (CvISXSUB (cb))
2718 croak ("Coro::State doesn't support XS functions as coroutine start, caught");
2719
2720 if (!CvROOT (cb))
2721 croak ("Coro::State doesn't support autoloaded or undefined functions as coroutine start, caught");
2722 }
2723 }
2210 2724
2211 Newz (0, coro, 1, struct coro); 2725 Newz (0, coro, 1, struct coro);
2212 coro->args = newAV (); 2726 coro->args = newAV ();
2213 coro->flags = CF_NEW; 2727 coro->flags = CF_NEW;
2214 2728
2219 coro->hv = hv = newHV (); 2733 coro->hv = hv = newHV ();
2220 mg = sv_magicext ((SV *)hv, 0, CORO_MAGIC_type_state, &coro_state_vtbl, (char *)coro, 0); 2734 mg = sv_magicext ((SV *)hv, 0, CORO_MAGIC_type_state, &coro_state_vtbl, (char *)coro, 0);
2221 mg->mg_flags |= MGf_DUP; 2735 mg->mg_flags |= MGf_DUP;
2222 RETVAL = sv_bless (newRV_noinc ((SV *)hv), gv_stashpv (klass, 1)); 2736 RETVAL = sv_bless (newRV_noinc ((SV *)hv), gv_stashpv (klass, 1));
2223 2737
2738 if (items > 1)
2739 {
2224 av_extend (coro->args, items - 1); 2740 av_extend (coro->args, items - 1 + ix - 1);
2741
2742 if (ix)
2743 {
2744 av_push (coro->args, SvREFCNT_inc_NN ((SV *)cb));
2745 cb = cv_coro_run;
2746 }
2747
2748 coro->startcv = (CV *)SvREFCNT_inc_NN ((SV *)cb);
2749
2225 for (i = 1; i < items; i++) 2750 for (i = 2; i < items; i++)
2226 av_push (coro->args, newSVsv (ST (i))); 2751 av_push (coro->args, newSVsv (ST (i)));
2752 }
2227} 2753}
2228 OUTPUT: 2754 OUTPUT:
2229 RETVAL 2755 RETVAL
2230
2231void
2232_set_stacklevel (...)
2233 CODE:
2234 CORO_EXECUTE_SLF_XS (slf_init_set_stacklevel);
2235 2756
2236void 2757void
2237transfer (...) 2758transfer (...)
2238 PROTOTYPE: $$ 2759 PROTOTYPE: $$
2239 CODE: 2760 CODE:
2365throw (Coro::State self, SV *throw = &PL_sv_undef) 2886throw (Coro::State self, SV *throw = &PL_sv_undef)
2366 PROTOTYPE: $;$ 2887 PROTOTYPE: $;$
2367 CODE: 2888 CODE:
2368{ 2889{
2369 struct coro *current = SvSTATE_current; 2890 struct coro *current = SvSTATE_current;
2370 SV **throwp = self == current ? &coro_throw : &self->throw; 2891 SV **throwp = self == current ? &CORO_THROW : &self->except;
2371 SvREFCNT_dec (*throwp); 2892 SvREFCNT_dec (*throwp);
2372 *throwp = SvOK (throw) ? newSVsv (throw) : 0; 2893 *throwp = SvOK (throw) ? newSVsv (throw) : 0;
2373} 2894}
2374 2895
2375void 2896void
2427 SV **dst = ix ? (SV **)&self->slot->defav : (SV **)&self->slot->defsv; 2948 SV **dst = ix ? (SV **)&self->slot->defav : (SV **)&self->slot->defsv;
2428 2949
2429 SV *tmp = *src; *src = *dst; *dst = tmp; 2950 SV *tmp = *src; *src = *dst; *dst = tmp;
2430 } 2951 }
2431 2952
2953
2432MODULE = Coro::State PACKAGE = Coro 2954MODULE = Coro::State PACKAGE = Coro
2433 2955
2434BOOT: 2956BOOT:
2435{ 2957{
2436 int i; 2958 int i;
2437 2959
2438 av_async_pool = coro_get_av (aTHX_ "Coro::async_pool", TRUE); 2960 av_async_pool = coro_get_av (aTHX_ "Coro::async_pool", TRUE);
2439 sv_pool_rss = coro_get_sv (aTHX_ "Coro::POOL_RSS" , TRUE); 2961 sv_pool_rss = coro_get_sv (aTHX_ "Coro::POOL_RSS" , TRUE);
2440 sv_pool_size = coro_get_sv (aTHX_ "Coro::POOL_SIZE" , TRUE); 2962 sv_pool_size = coro_get_sv (aTHX_ "Coro::POOL_SIZE" , TRUE);
2441 2963 cv_coro_run = get_cv ( "Coro::_terminate", GV_ADD);
2964 cv_coro_terminate = get_cv ( "Coro::terminate", GV_ADD);
2442 coro_current = coro_get_sv (aTHX_ "Coro::current", FALSE); 2965 coro_current = coro_get_sv (aTHX_ "Coro::current" , FALSE);
2443 SvREADONLY_on (coro_current); 2966 SvREADONLY_on (coro_current);
2967
2968 sv_async_pool_idle = newSVpv ("[async pool idle]", 0); SvREADONLY_on (sv_async_pool_idle);
2969 sv_Coro = newSVpv ("Coro", 0); SvREADONLY_on (sv_Coro);
2970 cv_pool_handler = get_cv ("Coro::_pool_handler", 0); SvREADONLY_on (cv_pool_handler);
2971 cv_coro_new = get_cv ("Coro::new", 0); SvREADONLY_on (cv_coro_new);
2444 2972
2445 coro_stash = gv_stashpv ("Coro", TRUE); 2973 coro_stash = gv_stashpv ("Coro", TRUE);
2446 2974
2447 newCONSTSUB (coro_stash, "PRIO_MAX", newSViv (PRIO_MAX)); 2975 newCONSTSUB (coro_stash, "PRIO_MAX", newSViv (PRIO_MAX));
2448 newCONSTSUB (coro_stash, "PRIO_HIGH", newSViv (PRIO_HIGH)); 2976 newCONSTSUB (coro_stash, "PRIO_HIGH", newSViv (PRIO_HIGH));
2463 coroapi.ready = api_ready; 2991 coroapi.ready = api_ready;
2464 coroapi.is_ready = api_is_ready; 2992 coroapi.is_ready = api_is_ready;
2465 coroapi.nready = coro_nready; 2993 coroapi.nready = coro_nready;
2466 coroapi.current = coro_current; 2994 coroapi.current = coro_current;
2467 2995
2468 GCoroAPI = &coroapi; 2996 /*GCoroAPI = &coroapi;*/
2469 sv_setiv (sv, (IV)&coroapi); 2997 sv_setiv (sv, (IV)&coroapi);
2470 SvREADONLY_on (sv); 2998 SvREADONLY_on (sv);
2471 } 2999 }
2472} 3000}
2473 3001
2537 CODE: 3065 CODE:
2538 RETVAL = coro_nready; 3066 RETVAL = coro_nready;
2539 OUTPUT: 3067 OUTPUT:
2540 RETVAL 3068 RETVAL
2541 3069
2542# for async_pool speedup
2543void 3070void
2544_pool_1 (SV *cb) 3071_pool_handler (...)
2545 CODE: 3072 CODE:
2546{ 3073 CORO_EXECUTE_SLF_XS (slf_init_pool_handler);
2547 HV *hv = (HV *)SvRV (coro_current);
2548 struct coro *coro = SvSTATE_hv ((SV *)hv);
2549 AV *defav = GvAV (PL_defgv);
2550 SV *invoke = hv_delete (hv, "_invoke", sizeof ("_invoke") - 1, 0);
2551 AV *invoke_av;
2552 int i, len;
2553
2554 if (!invoke)
2555 {
2556 SV *old = PL_diehook;
2557 PL_diehook = 0;
2558 SvREFCNT_dec (old);
2559 croak ("\3async_pool terminate\2\n");
2560 }
2561
2562 SvREFCNT_dec (coro->saved_deffh);
2563 coro->saved_deffh = SvREFCNT_inc_NN ((SV *)PL_defoutgv);
2564
2565 hv_store (hv, "desc", sizeof ("desc") - 1,
2566 newSVpvn ("[async_pool]", sizeof ("[async_pool]") - 1), 0);
2567
2568 invoke_av = (AV *)SvRV (invoke);
2569 len = av_len (invoke_av);
2570
2571 sv_setsv (cb, AvARRAY (invoke_av)[0]);
2572
2573 if (len > 0)
2574 {
2575 av_fill (defav, len - 1);
2576 for (i = 0; i < len; ++i)
2577 av_store (defav, i, SvREFCNT_inc_NN (AvARRAY (invoke_av)[i + 1]));
2578 }
2579}
2580 3074
2581void 3075void
2582_pool_2 (SV *cb) 3076async_pool (SV *cv, ...)
2583 CODE:
2584{
2585 HV *hv = (HV *)SvRV (coro_current);
2586 struct coro *coro = SvSTATE_hv ((SV *)hv);
2587
2588 sv_setsv (cb, &PL_sv_undef);
2589
2590 SvREFCNT_dec ((SV *)PL_defoutgv); PL_defoutgv = (GV *)coro->saved_deffh;
2591 coro->saved_deffh = 0;
2592
2593 if (coro_rss (aTHX_ coro) > SvUV (sv_pool_rss)
2594 || av_len (av_async_pool) + 1 >= SvIV (sv_pool_size))
2595 {
2596 SV *old = PL_diehook;
2597 PL_diehook = 0;
2598 SvREFCNT_dec (old);
2599 croak ("\3async_pool terminate\2\n");
2600 }
2601
2602 av_clear (GvAV (PL_defgv));
2603 hv_store (hv, "desc", sizeof ("desc") - 1,
2604 newSVpvn ("[async_pool idle]", sizeof ("[async_pool idle]") - 1), 0);
2605
2606 coro->prio = 0;
2607
2608 if (coro->cctx && (coro->cctx->flags & CC_TRACE))
2609 api_trace (aTHX_ coro_current, 0);
2610
2611 av_push (av_async_pool, newSVsv (coro_current));
2612}
2613
2614
2615MODULE = Coro::State PACKAGE = Coro::AIO
2616
2617void
2618_get_state (SV *self)
2619 PROTOTYPE: $ 3077 PROTOTYPE: &@
2620 PPCODE: 3078 PPCODE:
2621{ 3079{
2622 AV *defav = GvAV (PL_defgv); 3080 HV *hv = (HV *)av_pop (av_async_pool);
2623 AV *av = newAV (); 3081 AV *av = newAV ();
3082 SV *cb = ST (0);
2624 int i; 3083 int i;
2625 SV *data_sv = newSV (sizeof (struct io_state));
2626 struct io_state *data = (struct io_state *)SvPVX (data_sv);
2627 SvCUR_set (data_sv, sizeof (struct io_state));
2628 SvPOK_only (data_sv);
2629 3084
2630 data->errorno = errno; 3085 av_extend (av, items - 2);
2631 data->laststype = PL_laststype; 3086 for (i = 1; i < items; ++i)
2632 data->laststatval = PL_laststatval;
2633 data->statcache = PL_statcache;
2634
2635 av_extend (av, AvFILLp (defav) + 1 + 1);
2636
2637 for (i = 0; i <= AvFILLp (defav); ++i)
2638 av_push (av, SvREFCNT_inc_NN (AvARRAY (defav)[i])); 3087 av_push (av, SvREFCNT_inc_NN (ST (i)));
2639 3088
2640 av_push (av, data_sv); 3089 if ((SV *)hv == &PL_sv_undef)
2641
2642 XPUSHs (sv_2mortal (newRV_noinc ((SV *)av)));
2643
2644 api_ready (aTHX_ self);
2645}
2646
2647void
2648_set_state (SV *state)
2649 PROTOTYPE: $
2650 PPCODE:
2651{
2652 AV *av = (AV *)SvRV (state);
2653 struct io_state *data = (struct io_state *)SvPVX (AvARRAY (av)[AvFILLp (av)]);
2654 int i;
2655
2656 errno = data->errorno;
2657 PL_laststype = data->laststype;
2658 PL_laststatval = data->laststatval;
2659 PL_statcache = data->statcache;
2660
2661 EXTEND (SP, AvFILLp (av));
2662 for (i = 0; i < AvFILLp (av); ++i)
2663 PUSHs (sv_2mortal (SvREFCNT_inc_NN (AvARRAY (av)[i])));
2664}
2665
2666
2667MODULE = Coro::State PACKAGE = Coro::AnyEvent
2668
2669BOOT:
2670 sv_activity = coro_get_sv (aTHX_ "Coro::AnyEvent::ACTIVITY", TRUE);
2671
2672void
2673_schedule (...)
2674 CODE:
2675{
2676 static int incede;
2677
2678 api_cede_notself (aTHX);
2679
2680 ++incede;
2681 while (coro_nready >= incede && api_cede (aTHX))
2682 ;
2683
2684 sv_setsv (sv_activity, &PL_sv_undef);
2685 if (coro_nready >= incede)
2686 { 3090 {
2687 PUSHMARK (SP); 3091 PUSHMARK (SP);
3092 EXTEND (SP, 2);
3093 PUSHs (sv_Coro);
3094 PUSHs ((SV *)cv_pool_handler);
2688 PUTBACK; 3095 PUTBACK;
2689 call_pv ("Coro::AnyEvent::_activity", G_DISCARD | G_EVAL); 3096 call_sv (cv_coro_new, G_SCALAR);
2690 SPAGAIN; 3097 SPAGAIN;
3098
3099 hv = (HV *)SvREFCNT_inc_NN (SvRV (POPs));
2691 } 3100 }
2692 3101
2693 --incede; 3102 {
3103 struct coro *coro = SvSTATE_hv (hv);
3104
3105 assert (!coro->invoke_cb);
3106 assert (!coro->invoke_av);
3107 coro->invoke_cb = SvREFCNT_inc (cb);
3108 coro->invoke_av = av;
3109 }
3110
3111 api_ready ((SV *)hv);
3112
3113 if (GIMME_V != G_VOID)
3114 XPUSHs (sv_2mortal (newRV_noinc ((SV *)hv)));
3115 else
3116 SvREFCNT_dec (hv);
2694} 3117}
3118
3119SV *
3120rouse_cb ()
3121 PROTOTYPE:
3122 CODE:
3123 RETVAL = coro_new_rouse_cb (aTHX);
3124 OUTPUT:
3125 RETVAL
3126
3127void
3128rouse_wait (...)
3129 PROTOTYPE: ;$
3130 PPCODE:
3131 CORO_EXECUTE_SLF_XS (slf_init_rouse_wait);
2695 3132
2696 3133
2697MODULE = Coro::State PACKAGE = PerlIO::cede 3134MODULE = Coro::State PACKAGE = PerlIO::cede
2698 3135
2699BOOT: 3136BOOT:
2700 PerlIO_define_layer (aTHX_ &PerlIO_cede); 3137 PerlIO_define_layer (aTHX_ &PerlIO_cede);
2701 3138
3139
2702MODULE = Coro::State PACKAGE = Coro::Semaphore 3140MODULE = Coro::State PACKAGE = Coro::Semaphore
2703 3141
2704SV * 3142SV *
2705new (SV *klass, SV *count_ = 0) 3143new (SV *klass, SV *count = 0)
2706 CODE: 3144 CODE:
2707{ 3145 RETVAL = sv_bless (
2708 /* a semaphore contains a counter IV in $sem->[0] and any waiters after that */ 3146 coro_waitarray_new (aTHX_ count && SvOK (count) ? SvIV (count) : 1),
2709 AV *av = newAV (); 3147 GvSTASH (CvGV (cv))
2710 av_push (av, newSViv (count_ && SvOK (count_) ? SvIV (count_) : 1)); 3148 );
2711 RETVAL = sv_bless (newRV_noinc ((SV *)av), GvSTASH (CvGV (cv))); 3149 OUTPUT:
2712} 3150 RETVAL
3151
3152# helper for Coro::Channel
3153SV *
3154_alloc (int count)
3155 CODE:
3156 RETVAL = coro_waitarray_new (aTHX_ count);
2713 OUTPUT: 3157 OUTPUT:
2714 RETVAL 3158 RETVAL
2715 3159
2716SV * 3160SV *
2717count (SV *self) 3161count (SV *self)
2726 adjust = 1 3170 adjust = 1
2727 CODE: 3171 CODE:
2728 coro_semaphore_adjust (aTHX_ (AV *)SvRV (self), ix ? adjust : 1); 3172 coro_semaphore_adjust (aTHX_ (AV *)SvRV (self), ix ? adjust : 1);
2729 3173
2730void 3174void
2731down (SV *self) 3175down (...)
2732 CODE: 3176 CODE:
2733 CORO_EXECUTE_SLF_XS (slf_init_semaphore_down); 3177 CORO_EXECUTE_SLF_XS (slf_init_semaphore_down);
3178
3179void
3180wait (...)
3181 CODE:
3182 CORO_EXECUTE_SLF_XS (slf_init_semaphore_wait);
2734 3183
2735void 3184void
2736try (SV *self) 3185try (SV *self)
2737 PPCODE: 3186 PPCODE:
2738{ 3187{
2750 XSRETURN_NO; 3199 XSRETURN_NO;
2751} 3200}
2752 3201
2753void 3202void
2754waiters (SV *self) 3203waiters (SV *self)
2755 CODE: 3204 PPCODE:
2756{ 3205{
2757 AV *av = (AV *)SvRV (self); 3206 AV *av = (AV *)SvRV (self);
3207 int wcount = AvFILLp (av) + 1 - 1;
2758 3208
2759 if (GIMME_V == G_SCALAR) 3209 if (GIMME_V == G_SCALAR)
2760 XPUSHs (sv_2mortal (newSVsv (AvARRAY (av)[0]))); 3210 XPUSHs (sv_2mortal (newSViv (wcount)));
2761 else 3211 else
2762 { 3212 {
2763 int i; 3213 int i;
2764 EXTEND (SP, AvFILLp (av) + 1 - 1); 3214 EXTEND (SP, wcount);
2765 for (i = 1; i <= AvFILLp (av); ++i) 3215 for (i = 1; i <= wcount; ++i)
2766 PUSHs (newSVsv (AvARRAY (av)[i])); 3216 PUSHs (sv_2mortal (newRV_inc (AvARRAY (av)[i])));
2767 } 3217 }
2768} 3218}
2769 3219
3220MODULE = Coro::State PACKAGE = Coro::Signal
3221
3222SV *
3223new (SV *klass)
3224 CODE:
3225 RETVAL = sv_bless (
3226 coro_waitarray_new (aTHX_ 0),
3227 GvSTASH (CvGV (cv))
3228 );
3229 OUTPUT:
3230 RETVAL
3231
3232void
3233wait (...)
3234 CODE:
3235 CORO_EXECUTE_SLF_XS (slf_init_signal_wait);
3236
3237void
3238broadcast (SV *self)
3239 CODE:
3240{
3241 AV *av = (AV *)SvRV (self);
3242 coro_signal_wake (aTHX_ av, AvFILLp (av));
3243}
3244
3245void
3246send (SV *self)
3247 CODE:
3248{
3249 AV *av = (AV *)SvRV (self);
3250
3251 if (AvFILLp (av))
3252 coro_signal_wake (aTHX_ av, 1);
3253 else
3254 SvIVX (AvARRAY (av)[0]) = 1; /* remember the signal */
3255}
3256
3257IV
3258awaited (SV *self)
3259 CODE:
3260 RETVAL = AvFILLp ((AV *)SvRV (self)) + 1 - 1;
3261 OUTPUT:
3262 RETVAL
3263
3264
3265MODULE = Coro::State PACKAGE = Coro::AnyEvent
3266
3267BOOT:
3268 sv_activity = coro_get_sv (aTHX_ "Coro::AnyEvent::ACTIVITY", TRUE);
3269
3270void
3271_schedule (...)
3272 CODE:
3273{
3274 static int incede;
3275
3276 api_cede_notself (aTHX);
3277
3278 ++incede;
3279 while (coro_nready >= incede && api_cede (aTHX))
3280 ;
3281
3282 sv_setsv (sv_activity, &PL_sv_undef);
3283 if (coro_nready >= incede)
3284 {
3285 PUSHMARK (SP);
3286 PUTBACK;
3287 call_pv ("Coro::AnyEvent::_activity", G_KEEPERR | G_EVAL | G_VOID | G_DISCARD);
3288 }
3289
3290 --incede;
3291}
3292
3293
3294MODULE = Coro::State PACKAGE = Coro::AIO
3295
3296void
3297_register (char *target, char *proto, SV *req)
3298 CODE:
3299{
3300 CV *req_cv = coro_sv_2cv (aTHX_ req);
3301 /* newXSproto doesn't return the CV on 5.8 */
3302 CV *slf_cv = newXS (target, coro_aio_req_xs, __FILE__);
3303 sv_setpv ((SV *)slf_cv, proto);
3304 sv_magicext ((SV *)slf_cv, (SV *)req_cv, CORO_MAGIC_type_aio, 0, 0, 0);
3305}
3306

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines