--- Coro/Coro/State.xs 2008/11/19 02:07:48 1.300 +++ Coro/Coro/State.xs 2009/08/13 02:35:41 1.368 @@ -8,7 +8,7 @@ #include "XSUB.h" #include "perliol.h" -#include "patchlevel.h" +#include "schmorp.h" #include #include @@ -18,7 +18,7 @@ # undef setjmp # undef longjmp # undef _exit -# define setjmp _setjmp // deep magic, don't ask +# define setjmp _setjmp /* deep magic */ #else # include /* most portable stdint.h */ #endif @@ -53,59 +53,6 @@ /* the maximum number of idle cctx that will be pooled */ static int cctx_max_idle = 4; -#define PERL_VERSION_ATLEAST(a,b,c) \ - (PERL_REVISION > (a) \ - || (PERL_REVISION == (a) \ - && (PERL_VERSION > (b) \ - || (PERL_VERSION == (b) && PERLSUBVERSION >= (c))))) - -#if !PERL_VERSION_ATLEAST (5,6,0) -# ifndef PL_ppaddr -# define PL_ppaddr ppaddr -# endif -# ifndef call_sv -# define call_sv perl_call_sv -# endif -# ifndef get_sv -# define get_sv perl_get_sv -# endif -# ifndef get_cv -# define get_cv perl_get_cv -# endif -# ifndef IS_PADGV -# define IS_PADGV(v) 0 -# endif -# ifndef IS_PADCONST -# define IS_PADCONST(v) 0 -# endif -#endif - -/* 5.11 */ -#ifndef CxHASARGS -# define CxHASARGS(cx) (cx)->blk_sub.hasargs -#endif - -/* 5.10.0 */ -#ifndef SvREFCNT_inc_NN -# define SvREFCNT_inc_NN(sv) SvREFCNT_inc (sv) -#endif - -/* 5.8.8 */ -#ifndef GV_NOTQUAL -# define GV_NOTQUAL 0 -#endif -#ifndef newSV -# define newSV(l) NEWSV(0,l) -#endif -#ifndef CvISXSUB_on -# define CvISXSUB_on(cv) (void)cv -#endif - -/* 5.8.7 */ -#ifndef SvRV_set -# define SvRV_set(s,v) SvRV(s) = (v) -#endif - #if !__i386 && !__x86_64 && !__powerpc && !__m68k && !__alpha && !__mips && !__sparc64 # undef CORO_STACKGUARD #endif @@ -129,11 +76,11 @@ # define STACKLEVEL ((void *)&stacklevel) #endif -#define IN_DESTRUCT (PL_main_cv == Nullcv) +#define IN_DESTRUCT PL_dirty #if __GNUC__ >= 3 # define attribute(x) __attribute__(x) -# define expect(expr,value) __builtin_expect ((expr),(value)) +# define expect(expr,value) __builtin_expect ((expr), (value)) # define INLINE static inline #else # define attribute(x) @@ -155,7 +102,18 @@ # endif #endif +#ifdef __linux +# include /* for timespec */ +# include /* for SYS_* */ +# ifdef SYS_clock_gettime +# define coro_clock_gettime(id, ts) syscall (SYS_clock_gettime, (id), (ts)) +# define CORO_CLOCK_MONOTONIC 1 +# define CORO_CLOCK_THREAD_CPUTIME_ID 3 +# endif +#endif + static double (*nvtime)(); /* so why doesn't it take void? */ +static void (*u2time)(pTHX_ UV ret[2]); /* we hijack an hopefully unused CV flag for our purposes */ #define CVf_SLF 0x4000 @@ -169,6 +127,10 @@ static HV *coro_state_stash, *coro_stash; static volatile SV *coro_mortal; /* will be freed/thrown after next transfer */ +static AV *av_destroy; /* destruction queue */ +static SV *sv_manager; /* the manager coro */ +static SV *sv_idle; /* $Coro::idle */ + static GV *irsgv; /* $/ */ static GV *stdoutgv; /* *STDOUT */ static SV *rv_diehook; @@ -178,11 +140,21 @@ /* async_pool helper stuff */ static SV *sv_pool_rss; static SV *sv_pool_size; -static AV *av_async_pool; +static SV *sv_async_pool_idle; /* description string */ +static AV *av_async_pool; /* idle pool */ +static SV *sv_Coro; /* class string */ +static CV *cv_pool_handler; +static CV *cv_coro_state_new; /* Coro::AnyEvent */ static SV *sv_activity; +/* enable processtime/realtime profiling */ +static char enable_times; +typedef U32 coro_ts[2]; +static coro_ts time_real, time_cpu; +static char times_valid; + static struct coro_cctx *cctx_first; static int cctx_count, cctx_idle; @@ -217,11 +189,16 @@ unsigned char flags; } coro_cctx; +coro_cctx *cctx_current; /* the currently running cctx */ + +/*****************************************************************************/ + enum { CF_RUNNING = 0x0001, /* coroutine is running */ CF_READY = 0x0002, /* coroutine is ready */ CF_NEW = 0x0004, /* has never been switched to */ CF_DESTROYED = 0x0008, /* coroutine data has been freed */ + CF_SUSPENDED = 0x0010, /* coroutine can't be scheduled */ }; /* the structure where most of the perl state is stored, overlaid on the cxstack */ @@ -231,6 +208,7 @@ AV *defav; SV *errsv; SV *irsgv; + HV *hinthv; #define VAR(name,type) type name; # include "state.h" #undef VAR @@ -243,15 +221,19 @@ /* the C coroutine allocated to this perl coroutine, if any */ coro_cctx *cctx; + /* ready queue */ + struct coro *next_ready; + /* state data */ struct CoroSLF slf_frame; /* saved slf frame */ AV *mainstack; perl_slots *slot; /* basically the saved sp */ - AV *args; /* data associated with this coroutine (initial args) */ - int refcnt; /* coroutines are refcounted, yes */ - int flags; /* CF_ flags */ - HV *hv; /* the perl hash associated with this coro, if any */ + CV *startcv; /* the CV to execute */ + AV *args; /* data associated with this coroutine (initial args) */ + int refcnt; /* coroutines are refcounted, yes */ + int flags; /* CF_ flags */ + HV *hv; /* the perl hash associated with this coro, if any */ void (*on_destroy)(pTHX_ struct coro *coro); /* statistics */ @@ -260,9 +242,19 @@ /* coro process data */ int prio; SV *except; /* exception to be thrown */ + SV *rouse_cb; /* async_pool */ SV *saved_deffh; + SV *invoke_cb; + AV *invoke_av; + + /* on_enter/on_leave */ + AV *on_enter; + AV *on_leave; + + /* times */ + coro_ts t_cpu, t_real; /* linked list */ struct coro *next, *prev; @@ -278,20 +270,41 @@ /** Coro ********************************************************************/ -#define PRIO_MAX 3 -#define PRIO_HIGH 1 -#define PRIO_NORMAL 0 -#define PRIO_LOW -1 -#define PRIO_IDLE -3 -#define PRIO_MIN -4 +#define CORO_PRIO_MAX 3 +#define CORO_PRIO_HIGH 1 +#define CORO_PRIO_NORMAL 0 +#define CORO_PRIO_LOW -1 +#define CORO_PRIO_IDLE -3 +#define CORO_PRIO_MIN -4 /* for Coro.pm */ static SV *coro_current; static SV *coro_readyhook; -static AV *coro_ready [PRIO_MAX - PRIO_MIN + 1]; +static struct coro *coro_ready [CORO_PRIO_MAX - CORO_PRIO_MIN + 1][2]; /* head|tail */ +static CV *cv_coro_run, *cv_coro_terminate; static struct coro *coro_first; #define coro_nready coroapi.nready +/** Coro::Select ************************************************************/ + +static OP *(*coro_old_pp_sselect) (pTHX); +static SV *coro_select_select; + +/* horrible hack, but if it works... */ +static OP * +coro_pp_sselect (aTHX) +{ + dSP; + PUSHMARK (SP - 4); /* fake argument list */ + XPUSHs (coro_select_select); + PUTBACK; + + /* entersub is an UNOP, select a LISTOP... keep your fingers crossed */ + PL_op->op_flags |= OPf_STACKED; + PL_op->op_private = 0; + return PL_ppaddr [OP_ENTERSUB](aTHX); +} + /** lowlevel stuff **********************************************************/ static SV * @@ -324,75 +337,59 @@ return get_hv (name, create); } -static AV * -coro_clone_padlist (pTHX_ CV *cv) +INLINE void +coro_times_update () { - AV *padlist = CvPADLIST (cv); - AV *newpadlist, *newpad; +#ifdef coro_clock_gettime + struct timespec ts; - newpadlist = newAV (); - AvREAL_off (newpadlist); -#if PERL_VERSION_ATLEAST (5,10,0) - Perl_pad_push (aTHX_ padlist, AvFILLp (padlist) + 1); + ts.tv_sec = ts.tv_nsec = 0; + coro_clock_gettime (CORO_CLOCK_THREAD_CPUTIME_ID, &ts); + time_cpu [0] = ts.tv_sec; time_cpu [1] = ts.tv_nsec; + + ts.tv_sec = ts.tv_nsec = 0; + coro_clock_gettime (CORO_CLOCK_MONOTONIC, &ts); + time_real [0] = ts.tv_sec; time_real [1] = ts.tv_nsec; #else - Perl_pad_push (aTHX_ padlist, AvFILLp (padlist) + 1, 1); -#endif - newpad = (AV *)AvARRAY (padlist)[AvFILLp (padlist)]; - --AvFILLp (padlist); + dTHX; + UV tv[2]; - av_store (newpadlist, 0, SvREFCNT_inc_NN (*av_fetch (padlist, 0, FALSE))); - av_store (newpadlist, 1, (SV *)newpad); - - return newpadlist; + u2time (aTHX_ tv); + time_real [0] = tv [0]; + time_real [1] = tv [1] * 1000; +#endif } -static void -free_padlist (pTHX_ AV *padlist) +INLINE void +coro_times_add (struct coro *c) { - /* may be during global destruction */ - if (SvREFCNT (padlist)) - { - I32 i = AvFILLp (padlist); - while (i >= 0) - { - SV **svp = av_fetch (padlist, i--, FALSE); - if (svp) - { - SV *sv; - while (&PL_sv_undef != (sv = av_pop ((AV *)*svp))) - SvREFCNT_dec (sv); - - SvREFCNT_dec (*svp); - } - } - - SvREFCNT_dec ((SV*)padlist); - } + c->t_real [1] += time_real [1]; + if (c->t_real [1] > 1000000000) { c->t_real [1] -= 1000000000; ++c->t_real [0]; } + c->t_real [0] += time_real [0]; + + c->t_cpu [1] += time_cpu [1]; + if (c->t_cpu [1] > 1000000000) { c->t_cpu [1] -= 1000000000; ++c->t_cpu [0]; } + c->t_cpu [0] += time_cpu [0]; } -static int -coro_cv_free (pTHX_ SV *sv, MAGIC *mg) +INLINE void +coro_times_sub (struct coro *c) { - AV *padlist; - AV *av = (AV *)mg->mg_obj; - - /* casting is fun. */ - while (&PL_sv_undef != (SV *)(padlist = (AV *)av_pop (av))) - free_padlist (aTHX_ padlist); - - SvREFCNT_dec (av); /* sv_magicext increased the refcount */ - - return 0; + if (c->t_real [1] < time_real [1]) { c->t_real [1] += 1000000000; --c->t_real [0]; } + c->t_real [1] -= time_real [1]; + c->t_real [0] -= time_real [0]; + + if (c->t_cpu [1] < time_cpu [1]) { c->t_cpu [1] += 1000000000; --c->t_cpu [0]; } + c->t_cpu [1] -= time_cpu [1]; + c->t_cpu [0] -= time_cpu [0]; } +/*****************************************************************************/ +/* magic glue */ + #define CORO_MAGIC_type_cv 26 #define CORO_MAGIC_type_state PERL_MAGIC_ext -static MGVTBL coro_cv_vtbl = { - 0, 0, 0, 0, - coro_cv_free -}; - #define CORO_MAGIC_NN(sv, type) \ (expect_true (SvMAGIC (sv)->mg_type == type) \ ? SvMAGIC (sv) \ @@ -436,6 +433,83 @@ #define SvSTATE_hv(hv) ((struct coro *)CORO_MAGIC_NN ((SV *)hv, CORO_MAGIC_type_state)->mg_ptr) #define SvSTATE_current SvSTATE_hv (SvRV (coro_current)) +/*****************************************************************************/ +/* padlist management and caching */ + +static AV * +coro_derive_padlist (pTHX_ CV *cv) +{ + AV *padlist = CvPADLIST (cv); + AV *newpadlist, *newpad; + + newpadlist = newAV (); + AvREAL_off (newpadlist); +#if PERL_VERSION_ATLEAST (5,10,0) + Perl_pad_push (aTHX_ padlist, AvFILLp (padlist) + 1); +#else + Perl_pad_push (aTHX_ padlist, AvFILLp (padlist) + 1, 1); +#endif + newpad = (AV *)AvARRAY (padlist)[AvFILLp (padlist)]; + --AvFILLp (padlist); + + av_store (newpadlist, 0, SvREFCNT_inc_NN (AvARRAY (padlist)[0])); + av_store (newpadlist, 1, (SV *)newpad); + + return newpadlist; +} + +static void +free_padlist (pTHX_ AV *padlist) +{ + /* may be during global destruction */ + if (!IN_DESTRUCT) + { + I32 i = AvFILLp (padlist); + + while (i > 0) /* special-case index 0 */ + { + /* we try to be extra-careful here */ + AV *av = (AV *)AvARRAY (padlist)[i--]; + I32 j = AvFILLp (av); + + while (j >= 0) + SvREFCNT_dec (AvARRAY (av)[j--]); + + AvFILLp (av) = -1; + SvREFCNT_dec (av); + } + + SvREFCNT_dec (AvARRAY (padlist)[0]); + + AvFILLp (padlist) = -1; + SvREFCNT_dec ((SV*)padlist); + } +} + +static int +coro_cv_free (pTHX_ SV *sv, MAGIC *mg) +{ + AV *padlist; + AV *av = (AV *)mg->mg_obj; + + /* perl manages to free our internal AV and _then_ call us */ + if (IN_DESTRUCT) + return 0; + + /* casting is fun. */ + while (&PL_sv_undef != (SV *)(padlist = (AV *)av_pop (av))) + free_padlist (aTHX_ padlist); + + SvREFCNT_dec (av); /* sv_magicext increased the refcount */ + + return 0; +} + +static MGVTBL coro_cv_vtbl = { + 0, 0, 0, 0, + coro_cv_free +}; + /* the next two functions merely cache the padlists */ static void get_padlist (pTHX_ CV *cv) @@ -450,12 +524,12 @@ #if CORO_PREFER_PERL_FUNCTIONS /* this is probably cleaner? but also slower! */ /* in practise, it seems to be less stable */ - CV *cp = Perl_cv_clone (cv); + CV *cp = Perl_cv_clone (aTHX_ cv); CvPADLIST (cv) = CvPADLIST (cp); CvPADLIST (cp) = 0; SvREFCNT_dec (cp); #else - CvPADLIST (cv) = coro_clone_padlist (aTHX_ cv); + CvPADLIST (cv) = coro_derive_padlist (aTHX_ cv); #endif } } @@ -472,7 +546,7 @@ av = (AV *)mg->mg_obj; if (expect_false (AvFILLp (av) >= AvMAX (av))) - av_extend (av, AvMAX (av) + 1); + av_extend (av, AvFILLp (av) + 1); AvARRAY (av)[++AvFILLp (av)] = (SV *)CvPADLIST (cv); } @@ -480,6 +554,9 @@ /** load & save, init *******************************************************/ static void +on_enterleave_call (pTHX_ SV *cb); + +static void load_perl (pTHX_ Coro__State c) { perl_slots *slot = c->slot; @@ -487,10 +564,11 @@ PL_mainstack = c->mainstack; - GvSV (PL_defgv) = slot->defsv; - GvAV (PL_defgv) = slot->defav; - GvSV (PL_errgv) = slot->errsv; - GvSV (irsgv) = slot->irsgv; + GvSV (PL_defgv) = slot->defsv; + GvAV (PL_defgv) = slot->defav; + GvSV (PL_errgv) = slot->errsv; + GvSV (irsgv) = slot->irsgv; + GvHV (PL_hintgv) = slot->hinthv; #define VAR(name,type) PL_ ## name = slot->name; # include "state.h" @@ -514,11 +592,43 @@ slf_frame = c->slf_frame; CORO_THROW = c->except; + + if (expect_false (enable_times)) + { + if (expect_false (!times_valid)) + coro_times_update (); + + coro_times_sub (c); + } + + if (expect_false (c->on_enter)) + { + int i; + + for (i = 0; i <= AvFILLp (c->on_enter); ++i) + on_enterleave_call (aTHX_ AvARRAY (c->on_enter)[i]); + } } static void save_perl (pTHX_ Coro__State c) { + if (expect_false (c->on_leave)) + { + int i; + + for (i = AvFILLp (c->on_leave); i >= 0; --i) + on_enterleave_call (aTHX_ AvARRAY (c->on_leave)[i]); + } + + times_valid = 0; + + if (expect_false (enable_times)) + { + coro_times_update (); times_valid = 1; + coro_times_add (c); + } + c->except = CORO_THROW; c->slf_frame = slf_frame; @@ -541,7 +651,7 @@ { PERL_CONTEXT *cx = &ccstk[cxix--]; - if (expect_true (CxTYPE (cx) == CXt_SUB || CxTYPE (cx) == CXt_FORMAT)) + if (expect_true (CxTYPE (cx) == CXt_SUB) || expect_false (CxTYPE (cx) == CXt_FORMAT)) { CV *cv = cx->blk_sub.cv; @@ -575,7 +685,7 @@ if (SLOT_COUNT >= 2) CXINC; if (SLOT_COUNT >= 3) CXINC; { - int i; + unsigned int i; for (i = 3; i < SLOT_COUNT; ++i) CXINC; } @@ -586,10 +696,11 @@ { perl_slots *slot = c->slot = (perl_slots *)(cxstack + cxstack_ix + 1); - slot->defav = GvAV (PL_defgv); - slot->defsv = DEFSV; - slot->errsv = ERRSV; - slot->irsgv = GvSV (irsgv); + slot->defav = GvAV (PL_defgv); + slot->defsv = DEFSV; + slot->errsv = ERRSV; + slot->irsgv = GvSV (irsgv); + slot->hinthv = GvHV (PL_hintgv); #define VAR(name,type) slot->name = PL_ ## name; # include "state.h" @@ -604,7 +715,7 @@ * not usually need a lot of stackspace. */ #if CORO_PREFER_PERL_FUNCTIONS -# define coro_init_stacks init_stacks +# define coro_init_stacks(thx) init_stacks () #else static void coro_init_stacks (pTHX) @@ -677,6 +788,15 @@ #endif } +#define CORO_RSS \ + rss += sizeof (SYM (curstackinfo)); \ + rss += (SYM (curstackinfo->si_cxmax) + 1) * sizeof (PERL_CONTEXT); \ + rss += sizeof (SV) + sizeof (struct xpvav) + (1 + AvMAX (SYM (curstack))) * sizeof (SV *); \ + rss += SYM (tmps_max) * sizeof (SV *); \ + rss += (SYM (markstack_max) - SYM (markstack_ptr)) * sizeof (I32); \ + rss += SYM (scopestack_max) * sizeof (I32); \ + rss += SYM (savestack_max) * sizeof (ANY); + static size_t coro_rss (pTHX_ struct coro *coro) { @@ -684,33 +804,17 @@ if (coro->mainstack) { - perl_slots tmp_slot; - perl_slots *slot; - if (coro->flags & CF_RUNNING) { - slot = &tmp_slot; - - #define VAR(name,type) slot->name = PL_ ## name; - # include "state.h" - #undef VAR + #define SYM(sym) PL_ ## sym + CORO_RSS; + #undef SYM } else - slot = coro->slot; - - if (slot) { - rss += sizeof (slot->curstackinfo); - rss += (slot->curstackinfo->si_cxmax + 1) * sizeof (PERL_CONTEXT); - rss += sizeof (SV) + sizeof (struct xpvav) + (1 + AvMAX (slot->curstack)) * sizeof (SV *); - rss += slot->tmps_max * sizeof (SV *); - rss += (slot->markstack_max - slot->markstack_ptr) * sizeof (I32); - rss += slot->scopestack_max * sizeof (I32); - rss += slot->savestack_max * sizeof (ANY); - -#if !PERL_VERSION_ATLEAST (5,10,0) - rss += slot->retstack_max * sizeof (OP *); -#endif + #define SYM(sym) coro->slot->sym + CORO_RSS; + #undef SYM } } @@ -733,11 +837,8 @@ /* * This overrides the default magic get method of %SIG elements. * The original one doesn't provide for reading back of PL_diehook/PL_warnhook - * and instead of tryign to save and restore the hash elements, we just provide + * and instead of trying to save and restore the hash elements, we just provide * readback here. - * We only do this when the hook is != 0, as they are often set to 0 temporarily, - * not expecting this to actually change the hook. This is a potential problem - * when a schedule happens then, but we ignore this. */ static int coro_sigelem_get (pTHX_ SV *sv, MAGIC *mg) @@ -800,7 +901,7 @@ if (svp) { SV *old = *svp; - *svp = newSVsv (sv); + *svp = SvOK (sv) ? newSVsv (sv) : 0; SvREFCNT_dec (old); return 0; } @@ -822,6 +923,12 @@ return 0; } +static int +slf_check_repeat (pTHX_ struct CoroSLF *frame) +{ + return 1; +} + static UNOP coro_setup_op; static void NOINLINE /* noinline to keep it out of the transfer fast path */ @@ -836,6 +943,9 @@ PL_curcop = &PL_compiling; PL_in_eval = EVAL_NULL; PL_comppad = 0; + PL_comppad_name = 0; + PL_comppad_name_fill = 0; + PL_comppad_name_floor = 0; PL_curpm = 0; PL_curpad = 0; PL_localizing = 0; @@ -844,6 +954,7 @@ #if PERL_VERSION_ATLEAST (5,10,0) PL_parser = 0; #endif + PL_hints = 0; /* recreate the die/warn hooks */ PL_diehook = 0; SvSetMagicSV (*hv_fetch (hv_sig, "__DIE__" , sizeof ("__DIE__" ) - 1, 1), rv_diehook ); @@ -853,6 +964,7 @@ GvAV (PL_defgv) = coro->args; coro->args = 0; GvSV (PL_errgv) = newSV (0); GvSV (irsgv) = newSVpvn ("\n", 1); sv_magic (GvSV (irsgv), (SV *)irsgv, PERL_MAGIC_sv, "/", 0); + GvHV (PL_hintgv) = 0; PL_rs = newSVsv (GvSV (irsgv)); PL_defoutgv = (GV *)SvREFCNT_inc_NN (stdoutgv); @@ -862,14 +974,14 @@ Zero (&myop, 1, UNOP); myop.op_next = Nullop; + myop.op_type = OP_ENTERSUB; myop.op_flags = OPf_WANT_VOID; PUSHMARK (SP); - XPUSHs (sv_2mortal (av_shift (GvAV (PL_defgv)))); + PUSHs ((SV *)coro->startcv); PUTBACK; PL_op = (OP *)&myop; PL_op = PL_ppaddr[OP_ENTERSUB](aTHX); - SPAGAIN; } /* this newly created coroutine might be run on an existing cctx which most @@ -880,18 +992,24 @@ /* and we have to provide the pp_slf op in any case, so pp_slf can skip it */ coro_setup_op.op_next = PL_op; - coro_setup_op.op_type = OP_CUSTOM; + coro_setup_op.op_type = OP_ENTERSUB; coro_setup_op.op_ppaddr = pp_slf; - /* no flags required, as an init function won't be called */ + /* no flags etc. required, as an init function won't be called */ PL_op = (OP *)&coro_setup_op; /* copy throw, in case it was set before coro_setup */ CORO_THROW = coro->except; + + if (expect_false (enable_times)) + { + coro_times_update (); + coro_times_sub (coro); + } } static void -coro_destruct (pTHX_ struct coro *coro) +coro_unwind_stacks (pTHX) { if (!IN_DESTRUCT) { @@ -909,21 +1027,50 @@ /* unwind main stack */ dounwind (-1); } +} + +static void +coro_destruct_perl (pTHX_ struct coro *coro) +{ + SV *svf [9]; + + { + struct coro *current = SvSTATE_current; - SvREFCNT_dec (GvSV (PL_defgv)); - SvREFCNT_dec (GvAV (PL_defgv)); - SvREFCNT_dec (GvSV (PL_errgv)); - SvREFCNT_dec (PL_defoutgv); - SvREFCNT_dec (PL_rs); - SvREFCNT_dec (GvSV (irsgv)); + assert (("FATAL: tried to destroy currently running coroutine", coro->mainstack != PL_mainstack)); - SvREFCNT_dec (PL_diehook); - SvREFCNT_dec (PL_warnhook); - - SvREFCNT_dec (coro->saved_deffh); - SvREFCNT_dec (CORO_THROW); + save_perl (aTHX_ current); + load_perl (aTHX_ coro); + + coro_unwind_stacks (aTHX); + coro_destruct_stacks (aTHX); + + // now save some sv's to be free'd later + svf [0] = GvSV (PL_defgv); + svf [1] = (SV *)GvAV (PL_defgv); + svf [2] = GvSV (PL_errgv); + svf [3] = (SV *)PL_defoutgv; + svf [4] = PL_rs; + svf [5] = GvSV (irsgv); + svf [6] = (SV *)GvHV (PL_hintgv); + svf [7] = PL_diehook; + svf [8] = PL_warnhook; + assert (9 == sizeof (svf) / sizeof (*svf)); + + load_perl (aTHX_ current); + } + + { + unsigned int i; - coro_destruct_stacks (aTHX); + for (i = 0; i < sizeof (svf) / sizeof (*svf); ++i) + SvREFCNT_dec (svf [i]); + + SvREFCNT_dec (coro->saved_deffh); + SvREFCNT_dec (coro->rouse_cb); + SvREFCNT_dec (coro->invoke_cb); + SvREFCNT_dec (coro->invoke_av); + } } INLINE void @@ -941,16 +1088,14 @@ { COP *oldcop = 0; int oldcxix = -2; - struct coro *coro = SvSTATE_current; /* trace cctx is tied to specific coro */ - coro_cctx *cctx = coro->cctx; while ((PL_op = CALL_FPTR (PL_op->op_ppaddr) (aTHX))) { PERL_ASYNC_CHECK (); - if (cctx->flags & CC_TRACE_ALL) + if (cctx_current->flags & CC_TRACE_ALL) { - if (PL_op->op_type == OP_LEAVESUB && cctx->flags & CC_TRACE_SUB) + if (PL_op->op_type == OP_LEAVESUB && cctx_current->flags & CC_TRACE_SUB) { PERL_CONTEXT *cx = &cxstack[cxstack_ix]; SV **bot, **top; @@ -997,13 +1142,12 @@ { SV **cb; - if (oldcxix != cxstack_ix && cctx->flags & CC_TRACE_SUB) + if (oldcxix != cxstack_ix && cctx_current->flags & CC_TRACE_SUB) { PERL_CONTEXT *cx = &cxstack[cxstack_ix]; if (CxTYPE (cx) == CXt_SUB && oldcxix < cxstack_ix) { - runops_proc_t old_runops = PL_runops; dSP; GV *gv = CvGV (cx->blk_sub.cv); SV *fullname = sv_2mortal (newSV (0)); @@ -1018,7 +1162,7 @@ PUSHMARK (SP); PUSHs (&PL_sv_yes); PUSHs (fullname); - PUSHs (CxHASARGS (cx) ? sv_2mortal (newRV_inc ((SV *)cx->blk_sub.argarray)) : &PL_sv_undef); + PUSHs (CxHASARGS (cx) ? sv_2mortal (newRV_inc ((SV *)cx->blk_sub.argarray)) : &PL_sv_undef); PUTBACK; cb = hv_fetch ((HV *)SvRV (coro_current), "_trace_sub_cb", sizeof ("_trace_sub_cb") - 1, 0); if (cb) call_sv (*cb, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD); @@ -1031,7 +1175,7 @@ oldcxix = cxstack_ix; } - if (cctx->flags & CC_TRACE_LINE) + if (cctx_current->flags & CC_TRACE_LINE) { dSP; @@ -1060,14 +1204,12 @@ return 0; } -static struct coro_cctx *cctx_ssl_cctx; static struct CoroSLF cctx_ssl_frame; static void slf_prepare_set_stacklevel (pTHX_ struct coro_transfer_args *ta) { - ta->prev = (struct coro *)cctx_ssl_cctx; - ta->next = 0; + ta->prev = 0; } static int @@ -1080,11 +1222,11 @@ /* initialises PL_top_env and injects a pseudo-slf-call to set the stacklevel */ static void NOINLINE -cctx_prepare (pTHX_ coro_cctx *cctx) +cctx_prepare (pTHX) { PL_top_env = &PL_start_env; - if (cctx->flags & CC_TRACE) + if (cctx_current->flags & CC_TRACE) PL_runops = runops_trace; /* we already must be executing an SLF op, there is no other valid way @@ -1093,7 +1235,6 @@ slf_frame.prepare && PL_op->op_ppaddr == pp_slf)); /* we must emulate leaving pp_slf, which is done inside slf_check_set_stacklevel */ - cctx_ssl_cctx = cctx; cctx_ssl_frame = slf_frame; slf_frame.prepare = slf_prepare_set_stacklevel; @@ -1126,7 +1267,7 @@ /* PL_nop = PL_nop->op_next */ /* inject a fake subroutine call to cctx_init */ - cctx_prepare (aTHX_ (coro_cctx *)arg); + cctx_prepare (aTHX); /* cctx_run is the alternative tail of transfer() */ transfer_tail (aTHX); @@ -1134,13 +1275,20 @@ /* somebody or something will hit me for both perl_run and PL_restartop */ PL_restartop = PL_op; perl_run (PL_curinterp); + /* + * Unfortunately, there is no way to get at the return values of the + * coro body here, as perl_run destroys these. Likewise, we cannot catch + * runtime errors here, as this is just a random interpreter, not a thread. + */ /* * If perl-run returns we assume exit() was being called or the coro * fell off the end, which seems to be the only valid (non-bug) * reason for perl_run to return. We try to exit by jumping to the * bootstrap-time "top" top_env, as we cannot restore the "main" - * coroutine as Coro has no such concept + * coroutine as Coro has no such concept. + * This actually isn't valid with the pthread backend, but OSes requiring + * that backend are too broken to do it in a standards-compliant way. */ PL_top_env = main_top_env; JMPENV_JUMP (2); /* I do not feel well about the hardcoded 2 at all */ @@ -1227,6 +1375,8 @@ if (!cctx) return; + assert (("FATAL: tried to destroy current cctx", cctx != cctx_current));//D temporary? + --cctx_count; coro_destroy (&cctx->cctx); @@ -1299,13 +1449,10 @@ if (expect_true (prev != next)) { if (expect_false (!(prev->flags & (CF_RUNNING | CF_NEW)))) - croak ("Coro::State::transfer called with non-running/new prev Coro::State, but can only transfer from running or new states,"); - - if (expect_false (next->flags & CF_RUNNING)) - croak ("Coro::State::transfer called with running next Coro::State, but can only transfer to inactive states,"); + croak ("Coro::State::transfer called with a blocked prev Coro::State, but can only transfer from running or new states,"); - if (expect_false (next->flags & CF_DESTROYED)) - croak ("Coro::State::transfer called with destroyed next Coro::State, but can only transfer to inactive states,"); + if (expect_false (next->flags & (CF_RUNNING | CF_DESTROYED | CF_SUSPENDED))) + croak ("Coro::State::transfer called with running, destroyed or suspended next Coro::State, but can only transfer to inactive states,"); #if !PERL_VERSION_ATLEAST (5,10,0) if (expect_false (PL_lex_state != LEX_NOTPARSING)) @@ -1321,19 +1468,18 @@ dSTACKLEVEL; /* sometimes transfer is only called to set idle_sp */ - if (expect_false (!next)) + if (expect_false (!prev)) { - ((coro_cctx *)prev)->idle_sp = STACKLEVEL; - assert (((coro_cctx *)prev)->idle_te = PL_top_env); /* just for the side-effect when asserts are enabled */ + cctx_current->idle_sp = STACKLEVEL; + assert (cctx_current->idle_te = PL_top_env); /* just for the side-effect when asserts are enabled */ } else if (expect_true (prev != next)) { - coro_cctx *prev__cctx; + coro_cctx *cctx_prev; if (expect_false (prev->flags & CF_NEW)) { /* create a new empty/source context */ - prev->cctx = cctx_new_empty (); prev->flags &= ~CF_NEW; prev->flags |= CF_RUNNING; } @@ -1354,39 +1500,39 @@ else load_perl (aTHX_ next); - prev__cctx = prev->cctx; - /* possibly untie and reuse the cctx */ if (expect_true ( - prev__cctx->idle_sp == STACKLEVEL - && !(prev__cctx->flags & CC_TRACE) + cctx_current->idle_sp == STACKLEVEL + && !(cctx_current->flags & CC_TRACE) && !force_cctx )) { /* I assume that stacklevel is a stronger indicator than PL_top_env changes */ - assert (("FATAL: current top_env must equal previous top_env in Coro (please report)", PL_top_env == prev__cctx->idle_te)); - - prev->cctx = 0; + assert (("FATAL: current top_env must equal previous top_env in Coro (please report)", PL_top_env == cctx_current->idle_te)); - /* if the cctx is about to be destroyed we need to make sure we won't see it in cctx_get */ - /* without this the next cctx_get might destroy the prev__cctx while still in use */ - if (expect_false (CCTX_EXPIRED (prev__cctx))) - if (!next->cctx) + /* if the cctx is about to be destroyed we need to make sure we won't see it in cctx_get. */ + /* without this the next cctx_get might destroy the running cctx while still in use */ + if (expect_false (CCTX_EXPIRED (cctx_current))) + if (expect_true (!next->cctx)) next->cctx = cctx_get (aTHX); - cctx_put (prev__cctx); + cctx_put (cctx_current); } + else + prev->cctx = cctx_current; ++next->usecount; - if (expect_true (!next->cctx)) - next->cctx = cctx_get (aTHX); + cctx_prev = cctx_current; + cctx_current = expect_false (next->cctx) ? next->cctx : cctx_get (aTHX); - if (expect_false (prev__cctx != next->cctx)) + next->cctx = 0; + + if (expect_false (cctx_prev != cctx_current)) { - prev__cctx->top_env = PL_top_env; - PL_top_env = next->cctx->top_env; - coro_transfer (&prev__cctx->cctx, &next->cctx->cctx); + cctx_prev->top_env = PL_top_env; + PL_top_env = cctx_current->top_env; + coro_transfer (&cctx_prev->cctx, &cctx_current->cctx); } transfer_tail (aTHX); @@ -1404,7 +1550,7 @@ if (coro->flags & CF_DESTROYED) return 0; - if (coro->on_destroy) + if (coro->on_destroy && !PL_dirty) coro->on_destroy (aTHX_ coro); coro->flags |= CF_DESTROYED; @@ -1418,24 +1564,16 @@ else coro->flags |= CF_READY; /* make sure it is NOT put into the readyqueue */ - if (coro->mainstack && coro->mainstack != main_mainstack) - { - struct coro temp; - - assert (("FATAL: tried to destroy currently running coroutine (please report)", !(coro->flags & CF_RUNNING))); - - save_perl (aTHX_ &temp); - load_perl (aTHX_ coro); - - coro_destruct (aTHX_ coro); - - load_perl (aTHX_ &temp); - - coro->slot = 0; - } + if (coro->mainstack + && coro->mainstack != main_mainstack + && coro->slot + && !PL_dirty) + coro_destruct_perl (aTHX_ coro); cctx_destroy (coro->cctx); + SvREFCNT_dec (coro->startcv); SvREFCNT_dec (coro->args); + SvREFCNT_dec (CORO_THROW); if (coro->next) coro->next->prev = coro->prev; if (coro->prev) coro->prev->next = coro->next; @@ -1504,61 +1642,67 @@ INLINE void coro_enq (pTHX_ struct coro *coro) { - av_push (coro_ready [coro->prio - PRIO_MIN], SvREFCNT_inc_NN (coro->hv)); + struct coro **ready = coro_ready [coro->prio - CORO_PRIO_MIN]; + + SvREFCNT_inc_NN (coro->hv); + + coro->next_ready = 0; + *(ready [0] ? &ready [1]->next_ready : &ready [0]) = coro; + ready [1] = coro; } -INLINE SV * +INLINE struct coro * coro_deq (pTHX) { int prio; - for (prio = PRIO_MAX - PRIO_MIN + 1; --prio >= 0; ) - if (AvFILLp (coro_ready [prio]) >= 0) - return av_shift (coro_ready [prio]); + for (prio = CORO_PRIO_MAX - CORO_PRIO_MIN + 1; --prio >= 0; ) + { + struct coro **ready = coro_ready [prio]; + + if (ready [0]) + { + struct coro *coro = ready [0]; + ready [0] = coro->next_ready; + return coro; + } + } return 0; } -static int -api_ready (pTHX_ SV *coro_sv) +static void +invoke_sv_ready_hook_helper (void) { - struct coro *coro; - SV *sv_hook; - void (*xs_hook)(void); + dTHX; + dSP; + + ENTER; + SAVETMPS; + + PUSHMARK (SP); + PUTBACK; + call_sv (coro_readyhook, G_VOID | G_DISCARD); - if (SvROK (coro_sv)) - coro_sv = SvRV (coro_sv); + FREETMPS; + LEAVE; +} - coro = SvSTATE (coro_sv); +static int +api_ready (pTHX_ SV *coro_sv) +{ + struct coro *coro = SvSTATE (coro_sv); if (coro->flags & CF_READY) return 0; coro->flags |= CF_READY; - sv_hook = coro_nready ? 0 : coro_readyhook; - xs_hook = coro_nready ? 0 : coroapi.readyhook; - coro_enq (aTHX_ coro); - ++coro_nready; - if (sv_hook) - { - dSP; - - ENTER; - SAVETMPS; - - PUSHMARK (SP); - PUTBACK; - call_sv (sv_hook, G_VOID | G_DISCARD); - - FREETMPS; - LEAVE; - } - - if (xs_hook) - xs_hook (); + if (!coro_nready++) + if (coroapi.readyhook) + coroapi.readyhook (); return 1; } @@ -1569,56 +1713,70 @@ return !!(SvSTATE (coro_sv)->flags & CF_READY); } +/* expects to own a reference to next->hv */ INLINE void -prepare_schedule (pTHX_ struct coro_transfer_args *ta) +prepare_schedule_to (pTHX_ struct coro_transfer_args *ta, struct coro *next) { - SV *prev_sv, *next_sv; + SV *prev_sv = SvRV (coro_current); - for (;;) - { - next_sv = coro_deq (aTHX); - - /* nothing to schedule: call the idle handler */ - if (expect_false (!next_sv)) - { - dSP; + ta->prev = SvSTATE_hv (prev_sv); + ta->next = next; - ENTER; - SAVETMPS; + TRANSFER_CHECK (*ta); - PUSHMARK (SP); - PUTBACK; - call_sv (get_sv ("Coro::idle", FALSE), G_VOID | G_DISCARD); + SvRV_set (coro_current, (SV *)next->hv); - FREETMPS; - LEAVE; - continue; - } + free_coro_mortal (aTHX); + coro_mortal = prev_sv; +} - ta->next = SvSTATE_hv (next_sv); +static void +prepare_schedule (pTHX_ struct coro_transfer_args *ta) +{ + for (;;) + { + struct coro *next = coro_deq (aTHX); - /* cannot transfer to destroyed coros, skip and look for next */ - if (expect_false (ta->next->flags & CF_DESTROYED)) + if (expect_true (next)) { - SvREFCNT_dec (next_sv); - /* coro_nready has already been taken care of by destroy */ - continue; + /* cannot transfer to destroyed coros, skip and look for next */ + if (expect_false (next->flags & (CF_DESTROYED | CF_SUSPENDED))) + SvREFCNT_dec (next->hv); /* coro_nready has already been taken care of by destroy */ + else + { + next->flags &= ~CF_READY; + --coro_nready; + + prepare_schedule_to (aTHX_ ta, next); + break; + } } + else + { + /* nothing to schedule: call the idle handler */ + if (SvROK (sv_idle) + && SvOBJECT (SvRV (sv_idle))) + { + ++coro_nready; /* hack so that api_ready doesn't invoke ready hook */ + api_ready (aTHX_ SvRV (sv_idle)); + --coro_nready; + } + else + { + dSP; - --coro_nready; - break; - } + ENTER; + SAVETMPS; - /* free this only after the transfer */ - prev_sv = SvRV (coro_current); - ta->prev = SvSTATE_hv (prev_sv); - TRANSFER_CHECK (*ta); - assert (("FATAL: next coroutine isn't marked as ready in Coro (please report)", ta->next->flags & CF_READY)); - ta->next->flags &= ~CF_READY; - SvRV_set (coro_current, next_sv); + PUSHMARK (SP); + PUTBACK; + call_sv (sv_idle, G_VOID | G_DISCARD); - free_coro_mortal (aTHX); - coro_mortal = prev_sv; + FREETMPS; + LEAVE; + } + } + } } INLINE void @@ -1651,6 +1809,16 @@ TRANSFER (ta, 1); } +static void +api_schedule_to (pTHX_ SV *coro_sv) +{ + struct coro_transfer_args ta; + struct coro *next = SvSTATE (coro_sv); + + SvREFCNT_inc_NN (coro_sv); + prepare_schedule_to (aTHX_ &ta, next); +} + static int api_cede (pTHX) { @@ -1687,12 +1855,15 @@ { struct coro *coro = SvSTATE (coro_sv); + if (coro->flags & CF_RUNNING) + croak ("cannot enable tracing on a running coroutine, caught"); + if (flags & CC_TRACE) { if (!coro->cctx) coro->cctx = cctx_new_run (); else if (!(coro->cctx->flags & CC_TRACE)) - croak ("cannot enable tracing on coroutine with custom stack,"); + croak ("cannot enable tracing on coroutine with custom stack, caught"); coro->cctx->flags |= CC_NOREUSE | (flags & (CC_TRACE | CC_TRACE_ALL)); } @@ -1707,6 +1878,255 @@ } } +static void +coro_call_on_destroy (pTHX_ struct coro *coro) +{ + SV **on_destroyp = hv_fetch (coro->hv, "_on_destroy", sizeof ("_on_destroy") - 1, 0); + SV **statusp = hv_fetch (coro->hv, "_status", sizeof ("_status") - 1, 0); + + if (on_destroyp) + { + AV *on_destroy = (AV *)SvRV (*on_destroyp); + + while (AvFILLp (on_destroy) >= 0) + { + dSP; /* don't disturb outer sp */ + SV *cb = av_pop (on_destroy); + + PUSHMARK (SP); + + if (statusp) + { + int i; + AV *status = (AV *)SvRV (*statusp); + EXTEND (SP, AvFILLp (status) + 1); + + for (i = 0; i <= AvFILLp (status); ++i) + PUSHs (AvARRAY (status)[i]); + } + + PUTBACK; + call_sv (sv_2mortal (cb), G_VOID | G_DISCARD); + } + } +} + +static void +slf_init_terminate (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) +{ + int i; + HV *hv = (HV *)SvRV (coro_current); + AV *av = newAV (); + + /* items are actually not so common, so optimise for this case */ + if (items) + { + av_extend (av, items - 1); + + for (i = 0; i < items; ++i) + av_push (av, SvREFCNT_inc_NN (arg [i])); + } + + hv_store (hv, "_status", sizeof ("_status") - 1, newRV_noinc ((SV *)av), 0); + + av_push (av_destroy, (SV *)newRV_inc ((SV *)hv)); /* RVinc for perl */ + api_ready (aTHX_ sv_manager); + + frame->prepare = prepare_schedule; + frame->check = slf_check_repeat; + + /* as a minor optimisation, we could unwind all stacks here */ + /* but that puts extra pressure on pp_slf, and is not worth much */ + /*coro_unwind_stacks (aTHX);*/ +} + +/*****************************************************************************/ +/* async pool handler */ + +static int +slf_check_pool_handler (pTHX_ struct CoroSLF *frame) +{ + HV *hv = (HV *)SvRV (coro_current); + struct coro *coro = (struct coro *)frame->data; + + if (!coro->invoke_cb) + return 1; /* loop till we have invoke */ + else + { + hv_store (hv, "desc", sizeof ("desc") - 1, + newSVpvn ("[async_pool]", sizeof ("[async_pool]") - 1), 0); + + coro->saved_deffh = SvREFCNT_inc_NN ((SV *)PL_defoutgv); + + { + dSP; + XPUSHs (sv_2mortal (coro->invoke_cb)); coro->invoke_cb = 0; + PUTBACK; + } + + SvREFCNT_dec (GvAV (PL_defgv)); + GvAV (PL_defgv) = coro->invoke_av; + coro->invoke_av = 0; + + return 0; + } +} + +static void +slf_init_pool_handler (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) +{ + HV *hv = (HV *)SvRV (coro_current); + struct coro *coro = SvSTATE_hv ((SV *)hv); + + if (expect_true (coro->saved_deffh)) + { + /* subsequent iteration */ + SvREFCNT_dec ((SV *)PL_defoutgv); PL_defoutgv = (GV *)coro->saved_deffh; + coro->saved_deffh = 0; + + if (coro_rss (aTHX_ coro) > SvUV (sv_pool_rss) + || av_len (av_async_pool) + 1 >= SvIV (sv_pool_size)) + { + coro->invoke_cb = SvREFCNT_inc_NN ((SV *)cv_coro_terminate); + coro->invoke_av = newAV (); + + frame->prepare = prepare_nop; + } + else + { + av_clear (GvAV (PL_defgv)); + hv_store (hv, "desc", sizeof ("desc") - 1, SvREFCNT_inc_NN (sv_async_pool_idle), 0); + + coro->prio = 0; + + if (coro->cctx && (coro->cctx->flags & CC_TRACE)) + api_trace (aTHX_ coro_current, 0); + + frame->prepare = prepare_schedule; + av_push (av_async_pool, SvREFCNT_inc (hv)); + } + } + else + { + /* first iteration, simply fall through */ + frame->prepare = prepare_nop; + } + + frame->check = slf_check_pool_handler; + frame->data = (void *)coro; +} + +/*****************************************************************************/ +/* rouse callback */ + +#define CORO_MAGIC_type_rouse PERL_MAGIC_ext + +static void +coro_rouse_callback (pTHX_ CV *cv) +{ + dXSARGS; + SV *data = (SV *)S_GENSUB_ARG; + + if (SvTYPE (SvRV (data)) != SVt_PVAV) + { + /* first call, set args */ + SV *coro = SvRV (data); + AV *av = newAV (); + + SvRV_set (data, (SV *)av); + + /* better take a full copy of the arguments */ + while (items--) + av_store (av, items, newSVsv (ST (items))); + + api_ready (aTHX_ coro); + SvREFCNT_dec (coro); + } + + XSRETURN_EMPTY; +} + +static int +slf_check_rouse_wait (pTHX_ struct CoroSLF *frame) +{ + SV *data = (SV *)frame->data; + + if (CORO_THROW) + return 0; + + if (SvTYPE (SvRV (data)) != SVt_PVAV) + return 1; + + /* now push all results on the stack */ + { + dSP; + AV *av = (AV *)SvRV (data); + int i; + + EXTEND (SP, AvFILLp (av) + 1); + for (i = 0; i <= AvFILLp (av); ++i) + PUSHs (sv_2mortal (AvARRAY (av)[i])); + + /* we have stolen the elements, so set length to zero and free */ + AvFILLp (av) = -1; + av_undef (av); + + PUTBACK; + } + + return 0; +} + +static void +slf_init_rouse_wait (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) +{ + SV *cb; + + if (items) + cb = arg [0]; + else + { + struct coro *coro = SvSTATE_current; + + if (!coro->rouse_cb) + croak ("Coro::rouse_wait called without rouse callback, and no default rouse callback found either,"); + + cb = sv_2mortal (coro->rouse_cb); + coro->rouse_cb = 0; + } + + if (!SvROK (cb) + || SvTYPE (SvRV (cb)) != SVt_PVCV + || CvXSUB ((CV *)SvRV (cb)) != coro_rouse_callback) + croak ("Coro::rouse_wait called with illegal callback argument,"); + + { + CV *cv = (CV *)SvRV (cb); /* for S_GENSUB_ARG */ + SV *data = (SV *)S_GENSUB_ARG; + + frame->data = (void *)data; + frame->prepare = SvTYPE (SvRV (data)) == SVt_PVAV ? prepare_nop : prepare_schedule; + frame->check = slf_check_rouse_wait; + } +} + +static SV * +coro_new_rouse_cb (pTHX) +{ + HV *hv = (HV *)SvRV (coro_current); + struct coro *coro = SvSTATE_hv (hv); + SV *data = newRV_inc ((SV *)hv); + SV *cb = s_gensub (aTHX_ coro_rouse_callback, (void *)data); + + sv_magicext (SvRV (cb), data, CORO_MAGIC_type_rouse, 0, 0, 0); + SvREFCNT_dec (data); /* magicext increases the refcount */ + + SvREFCNT_dec (coro->rouse_cb); + coro->rouse_cb = SvREFCNT_inc_NN (cb); + + return cb; +} + /*****************************************************************************/ /* schedule-like-function opcode (SLF) */ @@ -1764,6 +2184,34 @@ } static void +slf_prepare_schedule_to (pTHX_ struct coro_transfer_args *ta) +{ + struct coro *next = (struct coro *)slf_frame.data; + + SvREFCNT_inc_NN (next->hv); + prepare_schedule_to (aTHX_ ta, next); +} + +static void +slf_init_schedule_to (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) +{ + if (!items) + croak ("Coro::schedule_to expects a coroutine argument, caught"); + + frame->data = (void *)SvSTATE (arg [0]); + frame->prepare = slf_prepare_schedule_to; + frame->check = slf_check_nop; +} + +static void +slf_init_cede_to (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) +{ + api_ready (aTHX_ SvRV (coro_current)); + + slf_init_schedule_to (aTHX_ frame, cv, arg, items); +} + +static void slf_init_cede (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) { frame->prepare = prepare_cede; @@ -1916,12 +2364,59 @@ slf_argc = 0; PL_op->op_ppaddr = pp_slf; - PL_op->op_type = OP_CUSTOM; /* maybe we should leave it at entersub? */ + /*PL_op->op_type = OP_CUSTOM; /* we do behave like entersub still */ PL_op = (OP *)&slf_restore; } /*****************************************************************************/ +/* dynamic wind */ + +static void +on_enterleave_call (pTHX_ SV *cb) +{ + dSP; + + PUSHSTACK; + + PUSHMARK (SP); + PUTBACK; + call_sv (cb, G_VOID | G_DISCARD); + SPAGAIN; + + POPSTACK; +} + +static SV * +coro_avp_pop_and_free (pTHX_ AV **avp) +{ + AV *av = *avp; + SV *res = av_pop (av); + + if (AvFILLp (av) < 0) + { + *avp = 0; + SvREFCNT_dec (av); + } + + return res; +} + +static void +coro_pop_on_enter (pTHX_ void *coro) +{ + SV *cb = coro_avp_pop_and_free (aTHX_ &((struct coro *)coro)->on_enter); + SvREFCNT_dec (cb); +} + +static void +coro_pop_on_leave (pTHX_ void *coro) +{ + SV *cb = coro_avp_pop_and_free (aTHX_ &((struct coro *)coro)->on_leave); + on_enterleave_call (aTHX_ sv_2mortal (cb)); +} + +/*****************************************************************************/ /* PerlIO::cede */ typedef struct @@ -2002,14 +2497,20 @@ static SV * coro_waitarray_new (pTHX_ int count) { - /* a semaphore contains a counter IV in $sem->[0] and any waiters after that */ + /* a waitarray=semaphore contains a counter IV in $sem->[0] and any waiters after that */ AV *av = newAV (); SV **ary; /* unfortunately, building manually saves memory */ Newx (ary, 2, SV *); AvALLOC (av) = ary; +#if PERL_VERSION_ATLEAST (5,10,0) AvARRAY (av) = ary; +#else + /* 5.8.8 needs this syntax instead of AvARRAY = ary, yet */ + /* -DDEBUGGING flags this as a bug, despite it perfectly working */ + SvPVX ((SV *)av) = (char *)ary; +#endif AvMAX (av) = 1; AvFILLp (av) = 0; ary [0] = newSViv (count); @@ -2039,13 +2540,20 @@ cb = av_shift (av); if (SvOBJECT (cb)) - api_ready (aTHX_ cb); - else - croak ("callbacks not yet supported"); + { + api_ready (aTHX_ cb); + --count; + } + else if (SvTYPE (cb) == SVt_PVCV) + { + dSP; + PUSHMARK (SP); + XPUSHs (sv_2mortal (newRV_inc ((SV *)av))); + PUTBACK; + call_sv (cb, G_VOID | G_DISCARD | G_EVAL | G_KEEPERR); + } SvREFCNT_dec (cb); - - --count; } } @@ -2137,8 +2645,25 @@ static void slf_init_semaphore_wait (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items) { - slf_init_semaphore_down_or_wait (aTHX_ frame, cv, arg, items); - frame->check = slf_check_semaphore_wait; + if (items >= 2) + { + /* callback form */ + AV *av = (AV *)SvRV (arg [0]); + SV *cb_cv = s_get_cv_croak (arg [1]); + + av_push (av, SvREFCNT_inc_NN (cb_cv)); + + if (SvIVX (AvARRAY (av)[0]) > 0) + coro_semaphore_adjust (aTHX_ av, 0); + + frame->prepare = prepare_nop; + frame->check = slf_check_nop; + } + else + { + slf_init_semaphore_down_or_wait (aTHX_ frame, cv, arg, items); + frame->check = slf_check_semaphore_wait; + } } /* signal */ @@ -2160,8 +2685,20 @@ cb = av_shift (av); - api_ready (cb); - sv_setiv (cb, 0); /* signal waiter */ + if (SvTYPE (cb) == SVt_PVCV) + { + dSP; + PUSHMARK (SP); + XPUSHs (sv_2mortal (newRV_inc ((SV *)av))); + PUTBACK; + call_sv (cb, G_VOID | G_DISCARD | G_EVAL | G_KEEPERR); + } + else + { + api_ready (aTHX_ cb); + sv_setiv (cb, 0); /* signal waiter */ + } + SvREFCNT_dec (cb); --count; @@ -2180,7 +2717,18 @@ { AV *av = (AV *)SvRV (arg [0]); - if (SvIVX (AvARRAY (av)[0])) + if (items >= 2) + { + SV *cb_cv = s_get_cv_croak (arg [1]); + av_push (av, SvREFCNT_inc_NN (cb_cv)); + + if (SvIVX (AvARRAY (av)[0])) + coro_signal_wake (aTHX_ av, 1); /* ust be the only waiter */ + + frame->prepare = prepare_nop; + frame->check = slf_check_nop; + } + else if (SvIVX (AvARRAY (av)[0])) { SvIVX (AvARRAY (av)[0]) = 0; frame->prepare = prepare_nop; @@ -2188,7 +2736,7 @@ } else { - SV *waiter = newRV_inc (SvRV (coro_current)); /* owned by signal av */ + SV *waiter = newSVsv (coro_current); /* owned by signal av */ av_push (av, waiter); @@ -2199,29 +2747,6 @@ } /*****************************************************************************/ -/* gensub: simple closure generation utility */ - -#define GENSUB_ARG CvXSUBANY (cv).any_ptr - -/* create a closure from XS, returns a code reference */ -/* the arg can be accessed via GENSUB_ARG from the callback */ -/* the callback must use dXSARGS/XSRETURN */ -static SV * -gensub (pTHX_ void (*xsub)(pTHX_ CV *), void *arg) -{ - CV *cv = (CV *)newSV (0); - - sv_upgrade ((SV *)cv, SVt_PVCV); - - CvANON_on (cv); - CvISXSUB_on (cv); - CvXSUB (cv) = xsub; - GENSUB_ARG = arg; - - return newRV_noinc ((SV *)cv); -} - -/*****************************************************************************/ /* Coro::AIO */ #define CORO_MAGIC_type_aio PERL_MAGIC_ext @@ -2239,11 +2764,11 @@ coro_aio_callback (pTHX_ CV *cv) { dXSARGS; - AV *state = (AV *)GENSUB_ARG; + AV *state = (AV *)S_GENSUB_ARG; SV *coro = av_pop (state); SV *data_sv = newSV (sizeof (struct io_state)); - av_extend (state, items); + av_extend (state, items - 1); sv_upgrade (data_sv, SVt_PV); SvCUR_set (data_sv, sizeof (struct io_state)); @@ -2363,7 +2888,7 @@ PUSHs (arg [i]); /* now push the callback closure */ - PUSHs (sv_2mortal (gensub (aTHX_ coro_aio_callback, (void *)SvREFCNT_inc_NN ((SV *)state)))); + PUSHs (sv_2mortal (s_gensub (aTHX_ coro_aio_callback, (void *)SvREFCNT_inc_NN ((SV *)state)))); /* now call the AIO function - we assume our request is uncancelable */ PUTBACK; @@ -2388,6 +2913,68 @@ /*****************************************************************************/ +#if CORO_CLONE +# include "clone.c" +#endif + +/*****************************************************************************/ + +static SV * +coro_new (HV *stash, SV **argv, int argc, int is_coro) +{ + SV *coro_sv; + struct coro *coro; + MAGIC *mg; + HV *hv; + SV *cb; + int i; + + if (argc > 0) + { + cb = s_get_cv_croak (argv [0]); + + if (!is_coro) + { + if (CvISXSUB (cb)) + croak ("Coro::State doesn't support XS functions as coroutine start, caught"); + + if (!CvROOT (cb)) + croak ("Coro::State doesn't support autoloaded or undefined functions as coroutine start, caught"); + } + } + + Newz (0, coro, 1, struct coro); + coro->args = newAV (); + coro->flags = CF_NEW; + + if (coro_first) coro_first->prev = coro; + coro->next = coro_first; + coro_first = coro; + + coro->hv = hv = newHV (); + mg = sv_magicext ((SV *)hv, 0, CORO_MAGIC_type_state, &coro_state_vtbl, (char *)coro, 0); + mg->mg_flags |= MGf_DUP; + coro_sv = sv_bless (newRV_noinc ((SV *)hv), stash); + + if (argc > 0) + { + av_extend (coro->args, argc + is_coro - 1); + + if (is_coro) + { + av_push (coro->args, SvREFCNT_inc_NN ((SV *)cb)); + cb = (SV *)cv_coro_run; + } + + coro->startcv = (CV *)SvREFCNT_inc_NN ((SV *)cb); + + for (i = 1; i < argc; i++) + av_push (coro->args, newSVsv (argv [i])); + } + + return coro_sv; +} + MODULE = Coro::State PACKAGE = Coro::State PREFIX = api_ PROTOTYPES: DISABLE @@ -2401,6 +2988,8 @@ #endif BOOT_PAGESIZE; + cctx_current = cctx_new_empty (); + irsgv = gv_fetchpv ("/" , GV_ADD|GV_NOTQUAL, SVt_PV); stdoutgv = gv_fetchpv ("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO); @@ -2429,12 +3018,10 @@ SV *slf = sv_2mortal (newSViv (PTR2IV (pp_slf))); if (!PL_custom_op_names) PL_custom_op_names = newHV (); - hv_store_ent (PL_custom_op_names, slf, - newSVpv ("coro_slf", 0), 0); + hv_store_ent (PL_custom_op_names, slf, newSVpv ("coro_slf", 0), 0); if (!PL_custom_op_descs) PL_custom_op_descs = newHV (); - hv_store_ent (PL_custom_op_descs, slf, - newSVpv ("coro schedule like function", 0), 0); + hv_store_ent (PL_custom_op_descs, slf, newSVpv ("coro schedule like function", 0), 0); } coroapi.ver = CORO_API_VERSION; @@ -2456,38 +3043,21 @@ if (!SvIOK (*svp)) croak ("Time::NVtime isn't a function pointer"); nvtime = INT2PTR (double (*)(), SvIV (*svp)); + + svp = hv_fetch (PL_modglobal, "Time::U2time", 12, 0); + u2time = INT2PTR (void (*)(pTHX_ UV ret[2]), SvIV (*svp)); } - assert (("PRIO_NORMAL must be 0", !PRIO_NORMAL)); + assert (("PRIO_NORMAL must be 0", !CORO_PRIO_NORMAL)); } SV * -new (char *klass, ...) +new (SV *klass, ...) + ALIAS: + Coro::new = 1 CODE: -{ - struct coro *coro; - MAGIC *mg; - HV *hv; - int i; - - Newz (0, coro, 1, struct coro); - coro->args = newAV (); - coro->flags = CF_NEW; - - if (coro_first) coro_first->prev = coro; - coro->next = coro_first; - coro_first = coro; - - coro->hv = hv = newHV (); - mg = sv_magicext ((SV *)hv, 0, CORO_MAGIC_type_state, &coro_state_vtbl, (char *)coro, 0); - mg->mg_flags |= MGf_DUP; - RETVAL = sv_bless (newRV_noinc ((SV *)hv), gv_stashpv (klass, 1)); - - av_extend (coro->args, items - 1); - for (i = 1; i < items; i++) - av_push (coro->args, newSVsv (ST (i))); -} - OUTPUT: + RETVAL = coro_new (ix ? coro_stash : coro_state_stash, &ST (1), items - 1, ix); + OUTPUT: RETVAL void @@ -2509,6 +3079,25 @@ CODE: _exit (code); +SV * +clone (Coro::State coro) + CODE: +{ +#if CORO_CLONE + struct coro *ncoro = coro_clone (aTHX_ coro); + MAGIC *mg; + /* TODO: too much duplication */ + ncoro->hv = newHV (); + mg = sv_magicext ((SV *)ncoro->hv, 0, CORO_MAGIC_type_state, &coro_state_vtbl, (char *)ncoro, 0); + mg->mg_flags |= MGf_DUP; + RETVAL = sv_bless (newRV_noinc ((SV *)ncoro->hv), SvSTASH (coro->hv)); +#else + croak ("Coro::State->clone has not been configured into this installation of Coro, realised"); +#endif +} + OUTPUT: + RETVAL + int cctx_stacksize (int new_stacksize = 0) PROTOTYPE: ;$ @@ -2567,39 +3156,34 @@ { if (coro->mainstack && ((coro->flags & CF_RUNNING) || coro->slot)) { - struct coro temp; + struct coro *current = SvSTATE_current; - if (!(coro->flags & CF_RUNNING)) + if (current != coro) { PUTBACK; - save_perl (aTHX_ &temp); + save_perl (aTHX_ current); load_perl (aTHX_ coro); + SPAGAIN; } - { - dSP; - ENTER; - SAVETMPS; - PUTBACK; - PUSHSTACK; - PUSHMARK (SP); + PUSHSTACK; - if (ix) - eval_sv (coderef, 0); - else - call_sv (coderef, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD); + PUSHMARK (SP); + PUTBACK; - POPSTACK; - SPAGAIN; - FREETMPS; - LEAVE; - PUTBACK; - } + if (ix) + eval_sv (coderef, 0); + else + call_sv (coderef, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD); - if (!(coro->flags & CF_RUNNING)) + POPSTACK; + SPAGAIN; + + if (current != coro) { + PUTBACK; save_perl (aTHX_ coro); - load_perl (aTHX_ &temp); + load_perl (aTHX_ current); SPAGAIN; } } @@ -2613,6 +3197,7 @@ is_running = CF_RUNNING is_new = CF_NEW is_destroyed = CF_DESTROYED + is_suspended = CF_SUSPENDED CODE: RETVAL = boolSV (coro->flags & ix); OUTPUT: @@ -2626,6 +3211,7 @@ struct coro *current = SvSTATE_current; SV **throwp = self == current ? &CORO_THROW : &self->except; SvREFCNT_dec (*throwp); + SvGETMAGIC (throw); *throwp = SvOK (throw) ? newSVsv (throw) : 0; } @@ -2638,7 +3224,8 @@ has_cctx (Coro::State coro) PROTOTYPE: $ CODE: - RETVAL = boolSV (!!coro->cctx); + /* maybe manage the running flag differently */ + RETVAL = boolSV (!!coro->cctx || (coro->flags & CF_RUNNING)); OUTPUT: RETVAL @@ -2668,7 +3255,7 @@ force_cctx () PROTOTYPE: CODE: - SvSTATE_current->cctx->idle_sp = 0; + cctx_current->idle_sp = 0; void swap_defsv (Coro::State self) @@ -2686,36 +3273,83 @@ SV *tmp = *src; *src = *dst; *dst = tmp; } +void +cancel (Coro::State self) + CODE: + coro_state_destroy (aTHX_ self); + coro_call_on_destroy (aTHX_ self); /* actually only for Coro objects */ -MODULE = Coro::State PACKAGE = Coro -BOOT: +SV * +enable_times (int enabled = enable_times) + CODE: { - int i; + RETVAL = boolSV (enable_times); - av_async_pool = coro_get_av (aTHX_ "Coro::async_pool", TRUE); - sv_pool_rss = coro_get_sv (aTHX_ "Coro::POOL_RSS" , TRUE); - sv_pool_size = coro_get_sv (aTHX_ "Coro::POOL_SIZE" , TRUE); + if (enabled != enable_times) + { + enable_times = enabled; - coro_current = coro_get_sv (aTHX_ "Coro::current", FALSE); - SvREADONLY_on (coro_current); + coro_times_update (); + (enabled ? coro_times_sub : coro_times_add)(SvSTATE (coro_current)); + } +} + OUTPUT: + RETVAL - coro_stash = gv_stashpv ("Coro", TRUE); +void +times (Coro::State self) + PPCODE: +{ + struct coro *current = SvSTATE (coro_current); + + if (expect_false (current == self)) + { + coro_times_update (); + coro_times_add (SvSTATE (coro_current)); + } - newCONSTSUB (coro_stash, "PRIO_MAX", newSViv (PRIO_MAX)); - newCONSTSUB (coro_stash, "PRIO_HIGH", newSViv (PRIO_HIGH)); - newCONSTSUB (coro_stash, "PRIO_NORMAL", newSViv (PRIO_NORMAL)); - newCONSTSUB (coro_stash, "PRIO_LOW", newSViv (PRIO_LOW)); - newCONSTSUB (coro_stash, "PRIO_IDLE", newSViv (PRIO_IDLE)); - newCONSTSUB (coro_stash, "PRIO_MIN", newSViv (PRIO_MIN)); + EXTEND (SP, 2); + PUSHs (sv_2mortal (newSVnv (self->t_real [0] + self->t_real [1] * 1e-9))); + PUSHs (sv_2mortal (newSVnv (self->t_cpu [0] + self->t_cpu [1] * 1e-9))); - for (i = PRIO_MAX - PRIO_MIN + 1; i--; ) - coro_ready[i] = newAV (); + if (expect_false (current == self)) + coro_times_sub (SvSTATE (coro_current)); +} + +MODULE = Coro::State PACKAGE = Coro + +BOOT: +{ + sv_pool_rss = coro_get_sv (aTHX_ "Coro::POOL_RSS" , TRUE); + sv_pool_size = coro_get_sv (aTHX_ "Coro::POOL_SIZE" , TRUE); + cv_coro_run = get_cv ( "Coro::_coro_run" , GV_ADD); + cv_coro_terminate = get_cv ( "Coro::terminate" , GV_ADD); + coro_current = coro_get_sv (aTHX_ "Coro::current" , FALSE); SvREADONLY_on (coro_current); + av_async_pool = coro_get_av (aTHX_ "Coro::async_pool", TRUE); + av_destroy = coro_get_av (aTHX_ "Coro::destroy" , TRUE); + sv_manager = coro_get_sv (aTHX_ "Coro::manager" , TRUE); + sv_idle = coro_get_sv (aTHX_ "Coro::idle" , TRUE); + + sv_async_pool_idle = newSVpv ("[async pool idle]", 0); SvREADONLY_on (sv_async_pool_idle); + sv_Coro = newSVpv ("Coro", 0); SvREADONLY_on (sv_Coro); + cv_pool_handler = get_cv ("Coro::pool_handler", GV_ADD); SvREADONLY_on (cv_pool_handler); + cv_coro_state_new = get_cv ("Coro::State::new", 0); SvREADONLY_on (cv_coro_state_new); + + coro_stash = gv_stashpv ("Coro", TRUE); + + newCONSTSUB (coro_stash, "PRIO_MAX", newSViv (CORO_PRIO_MAX)); + newCONSTSUB (coro_stash, "PRIO_HIGH", newSViv (CORO_PRIO_HIGH)); + newCONSTSUB (coro_stash, "PRIO_NORMAL", newSViv (CORO_PRIO_NORMAL)); + newCONSTSUB (coro_stash, "PRIO_LOW", newSViv (CORO_PRIO_LOW)); + newCONSTSUB (coro_stash, "PRIO_IDLE", newSViv (CORO_PRIO_IDLE)); + newCONSTSUB (coro_stash, "PRIO_MIN", newSViv (CORO_PRIO_MIN)); { SV *sv = coro_get_sv (aTHX_ "Coro::API", TRUE); coroapi.schedule = api_schedule; + coroapi.schedule_to = api_schedule_to; coroapi.cede = api_cede; coroapi.cede_notself = api_cede_notself; coroapi.ready = api_ready; @@ -2729,12 +3363,36 @@ } } +SV * +async (...) + PROTOTYPE: &@ + CODE: + RETVAL = coro_new (coro_stash, &ST (0), items, 1); + api_ready (RETVAL); + OUTPUT: + RETVAL + +void +terminate (...) + CODE: + CORO_EXECUTE_SLF_XS (slf_init_terminate); + void schedule (...) CODE: CORO_EXECUTE_SLF_XS (slf_init_schedule); void +schedule_to (...) + CODE: + CORO_EXECUTE_SLF_XS (slf_init_schedule_to); + +void +cede_to (...) + CODE: + CORO_EXECUTE_SLF_XS (slf_init_cede_to); + +void cede (...) CODE: CORO_EXECUTE_SLF_XS (slf_init_cede); @@ -2756,7 +3414,17 @@ PROTOTYPE: $ CODE: SvREFCNT_dec (coro_readyhook); - coro_readyhook = SvOK (hook) ? newSVsv (hook) : 0; + SvGETMAGIC (hook); + if (SvOK (hook)) + { + coro_readyhook = newSVsv (hook); + CORO_READYHOOK = invoke_sv_ready_hook_helper; + } + else + { + coro_readyhook = 0; + CORO_READYHOOK = 0; + } int prio (Coro::State coro, int newprio = 0) @@ -2772,8 +3440,8 @@ if (ix) newprio = coro->prio - newprio; - if (newprio < PRIO_MIN) newprio = PRIO_MIN; - if (newprio > PRIO_MAX) newprio = PRIO_MAX; + if (newprio < CORO_PRIO_MIN) newprio = CORO_PRIO_MIN; + if (newprio > CORO_PRIO_MAX) newprio = CORO_PRIO_MAX; coro->prio = newprio; } @@ -2797,76 +3465,104 @@ OUTPUT: RETVAL -# for async_pool speedup void -_pool_1 (SV *cb) +suspend (Coro::State self) + PROTOTYPE: $ CODE: + self->flags |= CF_SUSPENDED; + +void +resume (Coro::State self) + PROTOTYPE: $ + CODE: + self->flags &= ~CF_SUSPENDED; + +void +_pool_handler (...) + CODE: + CORO_EXECUTE_SLF_XS (slf_init_pool_handler); + +void +async_pool (SV *cv, ...) + PROTOTYPE: &@ + PPCODE: { - HV *hv = (HV *)SvRV (coro_current); - struct coro *coro = SvSTATE_hv ((SV *)hv); - AV *defav = GvAV (PL_defgv); - SV *invoke = hv_delete (hv, "_invoke", sizeof ("_invoke") - 1, 0); - AV *invoke_av; - int i, len; + HV *hv = (HV *)av_pop (av_async_pool); + AV *av = newAV (); + SV *cb = ST (0); + int i; - if (!invoke) + av_extend (av, items - 2); + for (i = 1; i < items; ++i) + av_push (av, SvREFCNT_inc_NN (ST (i))); + + if ((SV *)hv == &PL_sv_undef) { - SV *old = PL_diehook; - PL_diehook = 0; - SvREFCNT_dec (old); - croak ("\3async_pool terminate\2\n"); - } + PUSHMARK (SP); + EXTEND (SP, 2); + PUSHs (sv_Coro); + PUSHs ((SV *)cv_pool_handler); + PUTBACK; + call_sv ((SV *)cv_coro_state_new, G_SCALAR); + SPAGAIN; - SvREFCNT_dec (coro->saved_deffh); - coro->saved_deffh = SvREFCNT_inc_NN ((SV *)PL_defoutgv); + hv = (HV *)SvREFCNT_inc_NN (SvRV (POPs)); + } - hv_store (hv, "desc", sizeof ("desc") - 1, - newSVpvn ("[async_pool]", sizeof ("[async_pool]") - 1), 0); + { + struct coro *coro = SvSTATE_hv (hv); - invoke_av = (AV *)SvRV (invoke); - len = av_len (invoke_av); + assert (!coro->invoke_cb); + assert (!coro->invoke_av); + coro->invoke_cb = SvREFCNT_inc (cb); + coro->invoke_av = av; + } - sv_setsv (cb, AvARRAY (invoke_av)[0]); + api_ready (aTHX_ (SV *)hv); - if (len > 0) - { - av_fill (defav, len - 1); - for (i = 0; i < len; ++i) - av_store (defav, i, SvREFCNT_inc_NN (AvARRAY (invoke_av)[i + 1])); - } + if (GIMME_V != G_VOID) + XPUSHs (sv_2mortal (newRV_noinc ((SV *)hv))); + else + SvREFCNT_dec (hv); } -void -_pool_2 (SV *cb) +SV * +rouse_cb () + PROTOTYPE: CODE: -{ - HV *hv = (HV *)SvRV (coro_current); - struct coro *coro = SvSTATE_hv ((SV *)hv); + RETVAL = coro_new_rouse_cb (aTHX); + OUTPUT: + RETVAL - sv_setsv (cb, &PL_sv_undef); +void +rouse_wait (...) + PROTOTYPE: ;$ + PPCODE: + CORO_EXECUTE_SLF_XS (slf_init_rouse_wait); - SvREFCNT_dec ((SV *)PL_defoutgv); PL_defoutgv = (GV *)coro->saved_deffh; - coro->saved_deffh = 0; +void +on_enter (SV *block) + ALIAS: + on_leave = 1 + PROTOTYPE: & + CODE: +{ + struct coro *coro = SvSTATE_current; + AV **avp = ix ? &coro->on_leave : &coro->on_enter; - if (coro_rss (aTHX_ coro) > SvUV (sv_pool_rss) - || av_len (av_async_pool) + 1 >= SvIV (sv_pool_size)) - { - SV *old = PL_diehook; - PL_diehook = 0; - SvREFCNT_dec (old); - croak ("\3async_pool terminate\2\n"); - } + block = s_get_cv_croak (block); - av_clear (GvAV (PL_defgv)); - hv_store (hv, "desc", sizeof ("desc") - 1, - newSVpvn ("[async_pool idle]", sizeof ("[async_pool idle]") - 1), 0); + if (!*avp) + *avp = newAV (); - coro->prio = 0; + av_push (*avp, SvREFCNT_inc (block)); - if (coro->cctx && (coro->cctx->flags & CC_TRACE)) - api_trace (aTHX_ coro_current, 0); + if (!ix) + on_enterleave_call (aTHX_ block); - av_push (av_async_pool, newSVsv (coro_current)); + LEAVE; /* pp_entersub unfortunately forces an ENTER/LEAVE around XS calls */ + SAVEDESTRUCTOR_X (ix ? coro_pop_on_leave : coro_pop_on_enter, (void *)coro); + ENTER; /* pp_entersub unfortunately forces an ENTER/LEAVE around XS calls */ } @@ -2881,14 +3577,26 @@ SV * new (SV *klass, SV *count = 0) CODE: +{ + int semcnt = 1; + + if (count) + { + SvGETMAGIC (count); + + if (SvOK (count)) + semcnt = SvIV (count); + } + RETVAL = sv_bless ( - coro_waitarray_new (aTHX_ count && SvOK (count) ? SvIV (count) : 1), + coro_waitarray_new (aTHX_ semcnt), GvSTASH (CvGV (cv)) ); +} OUTPUT: RETVAL -# helper for Coro::Channel +# helper for Coro::Channel and others SV * _alloc (int count) CODE: @@ -2911,12 +3619,12 @@ coro_semaphore_adjust (aTHX_ (AV *)SvRV (self), ix ? adjust : 1); void -down (SV *self) +down (...) CODE: CORO_EXECUTE_SLF_XS (slf_init_semaphore_down); void -wait (SV *self) +wait (...) CODE: CORO_EXECUTE_SLF_XS (slf_init_semaphore_wait); @@ -2956,6 +3664,22 @@ } } +MODULE = Coro::State PACKAGE = Coro::SemaphoreSet + +void +_may_delete (SV *sem, int count, int extra_refs) + PPCODE: +{ + AV *av = (AV *)SvRV (sem); + + if (SvREFCNT ((SV *)av) == 1 + extra_refs + && AvFILLp (av) == 0 /* no waiters, just count */ + && SvIV (AvARRAY (av)[0]) == count) + XSRETURN_YES; + + XSRETURN_NO; +} + MODULE = Coro::State PACKAGE = Coro::Signal SV * @@ -2969,7 +3693,7 @@ RETVAL void -wait (SV *self) +wait (...) CODE: CORO_EXECUTE_SLF_XS (slf_init_signal_wait); @@ -2988,7 +3712,7 @@ AV *av = (AV *)SvRV (self); if (AvFILLp (av)) - coro_signal_wake (av, 1); + coro_signal_wake (aTHX_ av, 1); else SvIVX (AvARRAY (av)[0]) = 1; /* remember the signal */ } @@ -3036,12 +3760,32 @@ _register (char *target, char *proto, SV *req) CODE: { - HV *st; - GV *gvp; - CV *req_cv = sv_2cv (req, &st, &gvp, 0); + SV *req_cv = s_get_cv_croak (req); /* newXSproto doesn't return the CV on 5.8 */ CV *slf_cv = newXS (target, coro_aio_req_xs, __FILE__); sv_setpv ((SV *)slf_cv, proto); sv_magicext ((SV *)slf_cv, (SV *)req_cv, CORO_MAGIC_type_aio, 0, 0, 0); } +MODULE = Coro::State PACKAGE = Coro::Select + +void +patch_pp_sselect () + CODE: + if (!coro_old_pp_sselect) + { + coro_select_select = (SV *)get_cv ("Coro::Select::select", 0); + coro_old_pp_sselect = PL_ppaddr [OP_SSELECT]; + PL_ppaddr [OP_SSELECT] = coro_pp_sselect; + } + +void +unpatch_pp_sselect () + CODE: + if (coro_old_pp_sselect) + { + PL_ppaddr [OP_SSELECT] = coro_old_pp_sselect; + coro_old_pp_sselect = 0; + } + +