--- Coro/Coro/State.xs 2001/07/26 03:46:15 1.18 +++ Coro/Coro/State.xs 2006/11/27 01:28:03 1.102 @@ -1,65 +1,125 @@ +#include "libcoro/coro.c" + #include "EXTERN.h" #include "perl.h" #include "XSUB.h" -#include "libcoro/coro.c" +#include "patchlevel.h" + +#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 + +#include +#include + +#if !__i386 && !__x86_64 && !__powerpc && !__m68k && !__alpha && !__mips && !__sparc64 +# undef STACKGUARD +#endif + +#ifndef STACKGUARD +# define STACKGUARD 0 +#endif #ifdef HAVE_MMAP # include # include -# ifndef MAP_ANON -# ifdef MAP_ANONYMOUS -# define MAP_ANON MAP_ANONYMOUS +# ifndef MAP_ANONYMOUS +# ifdef MAP_ANON +# define MAP_ANONYMOUS MAP_ANON # else # undef HAVE_MMAP # endif # endif +# include +# ifndef PAGESIZE +# define PAGESIZE pagesize +# define BOOT_PAGESIZE pagesize = sysconf (_SC_PAGESIZE) +static long pagesize; +# else +# define BOOT_PAGESIZE +# endif #endif -#define MAY_FLUSH /* increases codesize */ +/* The next macro should declare a variable stacklevel that contains and approximation + * to the current C stack pointer. Its property is that it changes with each call + * and should be unique. */ +#define dSTACKLEVEL int stacklevel +#define STACKLEVEL ((void *)&stacklevel) -/* perl-related */ -#define TRANSFER_SAVE_DEFAV 0x00000001 -#define TRANSFER_SAVE_DEFSV 0x00000002 -#define TRANSFER_SAVE_ERRSV 0x00000004 -/* c-related */ -#define TRANSFER_SAVE_CCTXT 0x00000008 -#ifdef CORO_LAZY_STACK -# define TRANSFER_LAZY_STACK 0x00000010 +#define IN_DESTRUCT (PL_main_cv == Nullcv) + +#if __GNUC__ >= 3 +# define attribute(x) __attribute__(x) #else -# define TRANSFER_LAZY_STACK 0x00000000 +# define attribute(x) #endif -#define TRANSFER_SAVE_ALL (TRANSFER_SAVE_DEFAV|TRANSFER_SAVE_DEFSV \ - |TRANSFER_SAVE_ERRSV|TRANSFER_SAVE_CCTXT) +#define NOINLINE attribute ((noinline)) -#define SUB_INIT "Coro::State::initialize" -#define UCORO_STATE "_coro_state" +#include "CoroAPI.h" -/* The next macro should delcare a variable stacklevel that contains and approximation - * to the current C stack pointer. It's property is that it changes with each call - * and should be unique. */ -#define dSTACKLEVEL void *stacklevel = &stacklevel +#define TRANSFER_SET_STACKLEVEL 0x8bfbfbfb /* magic cookie */ -#define labs(l) ((l) >= 0 ? (l) : -(l)) +#ifdef USE_ITHREADS +static perl_mutex coro_mutex; +# define LOCK do { MUTEX_LOCK (&coro_mutex); } while (0) +# define UNLOCK do { MUTEX_UNLOCK (&coro_mutex); } while (0) +#else +# define LOCK (void)0 +# define UNLOCK (void)0 +#endif -/* this is actually not only the c stack but also c registers etc... */ -typedef struct { - int refcnt; /* pointer reference counter */ - int usecnt; /* shared by how many coroutines */ - int gencnt; /* generation counter */ +static struct CoroAPI coroapi; +static AV *main_mainstack; /* used to differentiate between $main and others */ +static HV *coro_state_stash, *coro_stash; +static SV *coro_mortal; /* will be freed after next transfer */ - coro_context cctx; +/* this is a structure representing a c-level coroutine */ +typedef struct coro_stack { + struct coro_stack *next; + /* the stack */ void *sptr; long ssize; /* positive == mmap, otherwise malloc */ + + /* cpu state */ + void *idle_sp; /* sp of top-level transfer/schedule/cede call */ + JMPENV *top_env; + coro_context cctx; } coro_stack; +/* this is a structure representing a perl-level coroutine */ struct coro { - /* the optional C context */ + /* the c coroutine allocated to this perl coroutine, if any */ coro_stack *stack; - void *cursp; - int gencnt; + + /* data associated with this coroutine (initial args) */ + AV *args; + int refcnt; /* optionally saved, might be zero */ AV *defav; @@ -68,6 +128,7 @@ /* saved global state not related to stacks */ U8 dowarn; + I32 in_eval; /* the stacks and related info (callchain etc..) */ PERL_SI *curstackinfo; @@ -76,6 +137,8 @@ SV **stack_sp; OP *op; SV **curpad; + AV *comppad; + CV *compcv; SV **stack_base; SV **stack_max; SV **tmps_stack; @@ -94,202 +157,132 @@ OP **retstack; I32 retstack_ix; I32 retstack_max; + PMOP *curpm; COP *curcop; - JMPENV start_env; - JMPENV *top_env; - /* data associated with this coroutine (initial args) */ - AV *args; + /* coro process data */ + int prio; }; typedef struct coro *Coro__State; typedef struct coro *Coro__State_or_hashref; -static AV *main_mainstack; /* used to differentiate between $main and others */ -static HV *coro_state_stash; -static SV *ucoro_state_sv; -static U32 ucoro_state_hash; -static HV *padlist_cache; - -/* mostly copied from op.c:cv_clone2 */ -STATIC AV * -clone_padlist (AV *protopadlist) -{ - AV *av; - I32 ix; - AV *protopad_name = (AV *) * av_fetch (protopadlist, 0, FALSE); - AV *protopad = (AV *) * av_fetch (protopadlist, 1, FALSE); - SV **pname = AvARRAY (protopad_name); - SV **ppad = AvARRAY (protopad); - I32 fname = AvFILLp (protopad_name); - I32 fpad = AvFILLp (protopad); - AV *newpadlist, *newpad_name, *newpad; - SV **npad; - - newpad_name = newAV (); - for (ix = fname; ix >= 0; ix--) - av_store (newpad_name, ix, SvREFCNT_inc (pname[ix])); - - newpad = newAV (); - av_fill (newpad, AvFILLp (protopad)); - npad = AvARRAY (newpad); +static AV * +coro_clone_padlist (CV *cv) +{ + AV *padlist = CvPADLIST (cv); + AV *newpadlist, *newpad; newpadlist = newAV (); AvREAL_off (newpadlist); - av_store (newpadlist, 0, (SV *) newpad_name); - av_store (newpadlist, 1, (SV *) newpad); - - av = newAV (); /* will be @_ */ - av_extend (av, 0); - av_store (newpad, 0, (SV *) av); - AvFLAGS (av) = AVf_REIFY; - - for (ix = fpad; ix > 0; ix--) - { - SV *namesv = (ix <= fname) ? pname[ix] : Nullsv; - if (namesv && namesv != &PL_sv_undef) - { - char *name = SvPVX (namesv); /* XXX */ - if (SvFLAGS (namesv) & SVf_FAKE || *name == '&') - { /* lexical from outside? */ - npad[ix] = SvREFCNT_inc (ppad[ix]); - } - else - { /* our own lexical */ - SV *sv; - if (*name == '&') - sv = SvREFCNT_inc (ppad[ix]); - else if (*name == '@') - sv = (SV *) newAV (); - else if (*name == '%') - sv = (SV *) newHV (); - else - sv = NEWSV (0, 0); - if (!SvPADBUSY (sv)) - SvPADMY_on (sv); - npad[ix] = sv; - } - } - else if (IS_PADGV (ppad[ix]) || IS_PADCONST (ppad[ix])) - { - npad[ix] = SvREFCNT_inc (ppad[ix]); - } - else - { - SV *sv = NEWSV (0, 0); - SvPADTMP_on (sv); - npad[ix] = sv; - } - } - -#if 0 /* return -ENOTUNDERSTOOD */ - /* Now that vars are all in place, clone nested closures. */ - - for (ix = fpad; ix > 0; ix--) { - SV* namesv = (ix <= fname) ? pname[ix] : Nullsv; - if (namesv - && namesv != &PL_sv_undef - && !(SvFLAGS(namesv) & SVf_FAKE) - && *SvPVX(namesv) == '&' - && CvCLONE(ppad[ix])) - { - CV *kid = cv_clone((CV*)ppad[ix]); - SvREFCNT_dec(ppad[ix]); - CvCLONE_on(kid); - SvPADMY_on(kid); - npad[ix] = (SV*)kid; - } - } +#if PERL_VERSION_ATLEAST (5,9,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 (*av_fetch (padlist, 0, FALSE))); + av_store (newpadlist, 1, (SV *)newpad); return newpadlist; } -#ifdef MAY_FLUSH -STATIC AV * +static void free_padlist (AV *padlist) { /* may be during global destruction */ - if (SvREFCNT(padlist)) + if (SvREFCNT (padlist)) { - I32 i = AvFILLp(padlist); + I32 i = AvFILLp (padlist); while (i >= 0) { - SV **svp = av_fetch(padlist, i--, FALSE); - SV *sv = svp ? *svp : Nullsv; - if (sv) - SvREFCNT_dec(sv); + 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); - } + SvREFCNT_dec ((SV*)padlist); + } } -#endif -/* the next two functions merely cache the padlists */ -STATIC void -get_padlist (CV *cv) +static int +coro_cv_free (pTHX_ SV *sv, MAGIC *mg) { - SV **he = hv_fetch (padlist_cache, (void *)&cv, sizeof (CV *), 0); + AV *padlist; + AV *av = (AV *)mg->mg_obj; - if (he && AvFILLp ((AV *)*he) >= 0) - CvPADLIST (cv) = (AV *)av_pop ((AV *)*he); - else - CvPADLIST (cv) = clone_padlist (CvPADLIST (cv)); + /* casting is fun. */ + while (&PL_sv_undef != (SV *)(padlist = (AV *)av_pop (av))) + free_padlist (padlist); + + SvREFCNT_dec (av); + + return 0; } -STATIC void -put_padlist (CV *cv) -{ - SV **he = hv_fetch (padlist_cache, (void *)&cv, sizeof (CV *), 1); +#define PERL_MAGIC_coro PERL_MAGIC_ext - if (SvTYPE (*he) != SVt_PVAV) - { - SvREFCNT_dec (*he); - *he = (SV *)newAV (); - } +static MGVTBL vtbl_coro = {0, 0, 0, 0, coro_cv_free}; - av_push ((AV *)*he, (SV *)CvPADLIST (cv)); +/* the next two functions merely cache the padlists */ +static void +get_padlist (CV *cv) +{ + MAGIC *mg = mg_find ((SV *)cv, PERL_MAGIC_coro); + + if (mg && AvFILLp ((AV *)mg->mg_obj) >= 0) + CvPADLIST (cv) = (AV *)av_pop ((AV *)mg->mg_obj); + else + { +#if 0 + /* this is probably cleaner, but also slower? */ + CV *cp = Perl_cv_clone (cv); + CvPADLIST (cv) = CvPADLIST (cp); + CvPADLIST (cp) = 0; + SvREFCNT_dec (cp); +#else + CvPADLIST (cv) = coro_clone_padlist (cv); +#endif + } } -#ifdef MAY_FLUSH -STATIC void -flush_padlist_cache () +static void +put_padlist (CV *cv) { - HV *hv = padlist_cache; - padlist_cache = newHV (); + MAGIC *mg = mg_find ((SV *)cv, PERL_MAGIC_coro); - if (hv_iterinit (hv)) + if (!mg) { - HE *he; - AV *padlist; - - while (!!(he = hv_iternext (hv))) - { - AV *av = (AV *)HeVAL(he); - - /* casting is fun. */ - while (&PL_sv_undef != (SV *)(padlist = (AV *)av_pop (av))) - free_padlist (padlist); - } + sv_magic ((SV *)cv, 0, PERL_MAGIC_coro, 0, 0); + mg = mg_find ((SV *)cv, PERL_MAGIC_coro); + mg->mg_virtual = &vtbl_coro; + mg->mg_obj = (SV *)newAV (); } - SvREFCNT_dec (hv); + av_push ((AV *)mg->mg_obj, (SV *)CvPADLIST (cv)); } -#endif #define SB do { #define SE } while (0) -#define LOAD(state) SB load_state(aTHX_ (state)); SPAGAIN; SE -#define SAVE(state,flags) SB PUTBACK; save_state(aTHX_ (state),(flags)); SE +#define LOAD(state) load_state((state)); +#define SAVE(state,flags) save_state((state),(flags)); -#define REPLACE_SV(sv,val) SB SvREFCNT_dec(sv); (sv) = (val); SE +#define REPLACE_SV(sv,val) SB SvREFCNT_dec(sv); (sv) = (val); (val) = 0; SE static void -load_state(pTHX_ Coro__State c) +load_state(Coro__State c) { PL_dowarn = c->dowarn; + PL_in_eval = c->in_eval; PL_curstackinfo = c->curstackinfo; PL_curstack = c->curstack; @@ -297,6 +290,8 @@ PL_stack_sp = c->stack_sp; PL_op = c->op; PL_curpad = c->curpad; + PL_comppad = c->comppad; + PL_compcv = c->compcv; PL_stack_base = c->stack_base; PL_stack_max = c->stack_max; PL_tmps_stack = c->tmps_stack; @@ -312,12 +307,13 @@ PL_savestack = c->savestack; PL_savestack_ix = c->savestack_ix; PL_savestack_max = c->savestack_max; +#if !PERL_VERSION_ATLEAST (5,9,0) PL_retstack = c->retstack; PL_retstack_ix = c->retstack_ix; PL_retstack_max = c->retstack_max; +#endif + PL_curpm = c->curpm; PL_curcop = c->curcop; - PL_start_env = c->start_env; - PL_top_env = c->top_env; if (c->defav) REPLACE_SV (GvAV (PL_defgv), c->defav); if (c->defsv) REPLACE_SV (DEFSV , c->defsv); @@ -336,9 +332,6 @@ { put_padlist (cv); /* mark this padlist as available */ CvPADLIST(cv) = padlist; -#ifdef USE_THREADS - /*CvOWNER(cv) = (struct perl_thread *)POPs;*/ -#endif } ++CvDEPTH(cv); @@ -349,7 +342,7 @@ } static void -save_state(pTHX_ Coro__State c, int flags) +save_state(Coro__State c, int flags) { { dSP; @@ -366,7 +359,7 @@ /* this loop was inspired by pp_caller */ for (;;) { - do + while (cxix >= 0) { PERL_CONTEXT *cx = &ccstk[cxix--]; @@ -375,11 +368,6 @@ CV *cv = cx->blk_sub.cv; if (CvDEPTH(cv)) { -#ifdef USE_THREADS - /*XPUSHs ((SV *)CvOWNER(cv));*/ - /*CvOWNER(cv) = 0;*/ - /*error must unlock this cv etc.. etc...*/ -#endif EXTEND (SP, CvDEPTH(cv)*2); while (--CvDEPTH(cv)) @@ -392,17 +380,18 @@ PUSHs ((SV *)CvPADLIST(cv)); PUSHs ((SV *)cv); - get_padlist (cv); /* this is a monster */ + get_padlist (cv); } } +#ifdef CXt_FORMAT else if (CxTYPE(cx) == CXt_FORMAT) { /* I never used formats, so how should I know how these are implemented? */ /* my bold guess is as a simple, plain sub... */ croak ("CXt_FORMAT not yet handled. Don't switch coroutines from within formats"); } +#endif } - while (cxix >= 0); if (top_si->si_type == PERLSI_MAIN) break; @@ -419,12 +408,8 @@ c->defsv = flags & TRANSFER_SAVE_DEFSV ? SvREFCNT_inc (DEFSV) : 0; c->errsv = flags & TRANSFER_SAVE_ERRSV ? SvREFCNT_inc (ERRSV) : 0; - /* I have not the slightest idea of why av_reify is necessary */ - /* but if it's missing the defav contents magically get replaced sometimes */ - if (c->defav) - av_reify (c->defav); - c->dowarn = PL_dowarn; + c->in_eval = PL_in_eval; c->curstackinfo = PL_curstackinfo; c->curstack = PL_curstack; @@ -432,6 +417,8 @@ c->stack_sp = PL_stack_sp; c->op = PL_op; c->curpad = PL_curpad; + c->comppad = PL_comppad; + c->compcv = PL_compcv; c->stack_base = PL_stack_base; c->stack_max = PL_stack_max; c->tmps_stack = PL_tmps_stack; @@ -447,22 +434,23 @@ c->savestack = PL_savestack; c->savestack_ix = PL_savestack_ix; c->savestack_max = PL_savestack_max; +#if !PERL_VERSION_ATLEAST (5,9,0) c->retstack = PL_retstack; c->retstack_ix = PL_retstack_ix; c->retstack_max = PL_retstack_max; +#endif + c->curpm = PL_curpm; c->curcop = PL_curcop; - c->start_env = PL_start_env; - c->top_env = PL_top_env; } /* * allocate various perl stacks. This is an exact copy * of perl.c:init_stacks, except that it uses less memory - * on the assumption that coroutines do not usually need - * a lot of stackspace. + * on the (sometimes correct) assumption that coroutines do + * not usually need a lot of stackspace. */ -STATIC void -coro_init_stacks (pTHX) +static void +coro_init_stacks () { PL_curstackinfo = new_stackinfo(96, 1024/sizeof(PERL_CONTEXT) - 1); PL_curstackinfo->si_type = PERLSI_MAIN; @@ -482,7 +470,9 @@ PL_markstack_ptr = PL_markstack; PL_markstack_max = PL_markstack + 16; +#ifdef SET_MARK_OFFSET SET_MARK_OFFSET; +#endif New(54,PL_scopestack,16,I32); PL_scopestack_ix = 0; @@ -492,25 +482,29 @@ PL_savestack_ix = 0; PL_savestack_max = 96; +#if !PERL_VERSION_ATLEAST (5,9,0) New(54,PL_retstack,8,OP*); PL_retstack_ix = 0; PL_retstack_max = 8; +#endif } /* * destroy the stacks, the callchain etc... - * still there is a memleak of 128 bytes... */ -STATIC void -destroy_stacks(pTHX) +static void +coro_destroy_stacks() { - /* is this ugly, I ask? */ - while (PL_scopestack_ix) - LEAVE; - - /* sure it is, but more important: is it correct?? :/ */ - while (PL_tmps_ix > PL_tmps_floor) /* should only ever be one iteration */ - FREETMPS; + if (!IN_DESTRUCT) + { + /* is this ugly, I ask? */ + LEAVE_SCOPE (0); + + /* sure it is, but more important: is it correct?? :/ */ + FREETMPS; + + /*POPSTACK_TO (PL_mainstack);*//*D*//*use*/ + } while (PL_curstackinfo->si_next) PL_curstackinfo = PL_curstackinfo->si_next; @@ -519,337 +513,747 @@ { PERL_SI *p = PL_curstackinfo->si_prev; - { + { /*D*//*remove*/ dSP; SWITCHSTACK (PL_curstack, PL_curstackinfo->si_stack); PUTBACK; /* possibly superfluous */ } - dounwind(-1); + if (!IN_DESTRUCT) + { + dounwind (-1);/*D*//*remove*/ + SvREFCNT_dec (PL_curstackinfo->si_stack); + } - SvREFCNT_dec(PL_curstackinfo->si_stack); - Safefree(PL_curstackinfo->si_cxstack); - Safefree(PL_curstackinfo); + Safefree (PL_curstackinfo->si_cxstack); + Safefree (PL_curstackinfo); PL_curstackinfo = p; } - Safefree(PL_tmps_stack); - Safefree(PL_markstack); - Safefree(PL_scopestack); - Safefree(PL_savestack); - Safefree(PL_retstack); + Safefree (PL_tmps_stack); + Safefree (PL_markstack); + Safefree (PL_scopestack); + Safefree (PL_savestack); +#if !PERL_VERSION_ATLEAST (5,9,0) + Safefree (PL_retstack); +#endif +} + +static void +setup_coro (struct coro *coro) +{ + /* + * emulate part of the perl startup here. + */ + + coro_init_stacks (); + + { + dSP; + LOGOP myop; + + /*PL_curcop = 0;*/ + PL_in_eval = 0; + SvREFCNT_dec (GvAV (PL_defgv)); + GvAV (PL_defgv) = coro->args; coro->args = 0; + + SPAGAIN; + + Zero (&myop, 1, LOGOP); + myop.op_next = Nullop; + myop.op_flags = OPf_WANT_VOID; + + PL_op = (OP *)&myop; + + PUSHMARK (SP); + PUSHMARK (SP); + XPUSHs ((SV *)get_cv ("Coro::State::coro_init", FALSE)); + PUTBACK; + PL_op = PL_ppaddr[OP_ENTERSUB](aTHX); + SPAGAIN; + + ENTER; /* necessary e.g. for dounwind */ + } +} + +static void +free_coro_mortal () +{ + if (coro_mortal) + { + SvREFCNT_dec (coro_mortal); + coro_mortal = 0; + } +} + +static void NOINLINE +prepare_cctx (coro_stack *cctx) +{ + dSP; + LOGOP myop; + + Zero (&myop, 1, LOGOP); + myop.op_next = PL_op; + myop.op_flags = OPf_WANT_VOID; + + sv_setiv (get_sv ("Coro::State::cctx_stack", FALSE), PTR2IV (cctx)); + + PUSHMARK (SP); + XPUSHs ((SV *)get_cv ("Coro::State::cctx_init", FALSE)); + PUTBACK; + PL_restartop = PL_ppaddr[OP_ENTERSUB](aTHX); + SPAGAIN; } static void -allocate_stack (Coro__State ctx, int alloc) +coro_run (void *arg) +{ + /* coro_run is the alternative epilogue of transfer() */ + UNLOCK; + + /* + * this is a _very_ stripped down perl interpreter ;) + */ + PL_top_env = &PL_start_env; + /* inject call to cctx_init */ + prepare_cctx ((coro_stack *)arg); + + /* somebody will hit me for both perl_run and PL_restartop */ + perl_run (PL_curinterp); + + fputs ("FATAL: C coroutine fell over the edge of the world, aborting.\n", stderr); + abort (); +} + +static coro_stack * +stack_new () { coro_stack *stack; New (0, stack, 1, coro_stack); - stack->refcnt = 1; - stack->usecnt = 1; - stack->gencnt = ctx->gencnt = 0; - if (alloc) +#if HAVE_MMAP + + stack->ssize = ((STACKSIZE * sizeof (long) + PAGESIZE - 1) / PAGESIZE + STACKGUARD) * PAGESIZE; + /* mmap suppsedly does allocate-on-write for us */ + stack->sptr = mmap (0, stack->ssize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 0, 0); + + if (stack->sptr == (void *)-1) { -#ifdef HAVE_MMAP - stack->ssize = 128 * 1024 * sizeof (long); /* mmap should do allocate-on-write for us */ - stack->sptr = mmap (0, stack->ssize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, 0, 0); - if (stack->sptr == (void *)-1) + perror ("FATAL: unable to mmap stack for coroutine"); + _exit (EXIT_FAILURE); + } + +# if STACKGUARD + mprotect (stack->sptr, STACKGUARD * PAGESIZE, PROT_NONE); +# endif + +#else + + stack->ssize = STACKSIZE * (long)sizeof (long); + New (0, stack->sptr, STACKSIZE, long); + + if (!stack->sptr) + { + perror (stderr, "FATAL: unable to malloc stack for coroutine"); + _exit (EXIT_FAILURE); + } + #endif - { - /*FIXME*//*D*//* reasonable stack size! */ - stack->ssize = -4096 * sizeof (long); - New (0, stack->sptr, 4096, long); - } + + coro_create (&stack->cctx, coro_run, (void *)stack, stack->sptr, stack->ssize); + + return stack; +} + +static void +stack_free (coro_stack *stack) +{ + if (!stack) + return; + +#if HAVE_MMAP + munmap (stack->sptr, stack->ssize); +#else + Safefree (stack->sptr); +#endif + + Safefree (stack); +} + +static coro_stack *stack_first; +static int cctx_count, cctx_idle; + +static coro_stack * +stack_get () +{ + coro_stack *stack; + + if (stack_first) + { + --cctx_idle; + stack = stack_first; + stack_first = stack->next; } else - stack->sptr = 0; + { + ++cctx_count; + stack = stack_new (); + PL_op = PL_op->op_next; + } - ctx->stack = stack; + return stack; } static void -deallocate_stack (Coro__State ctx) +stack_put (coro_stack *stack) { - coro_stack *stack = ctx->stack; + ++cctx_idle; + stack->next = stack_first; + stack_first = stack; +} - ctx->stack = 0; +/* never call directly, always through the coro_state_transfer global variable */ +static void NOINLINE +transfer (struct coro *prev, struct coro *next, int flags) +{ + dSTACKLEVEL; - if (stack) + /* sometimes transfer is only called to set idle_sp */ + if (flags == TRANSFER_SET_STACKLEVEL) + ((coro_stack *)prev)->idle_sp = STACKLEVEL; + else if (prev != next) { - if (!--stack->refcnt) + coro_stack *prev__stack; + + LOCK; + + if (next->mainstack) { -#ifdef HAVE_MMAP - if (stack->ssize > 0 && stack->sptr) - munmap (stack->sptr, stack->ssize); - else -#else - Safefree (stack->sptr); -#endif - Safefree (stack); + /* coroutine already started */ + SAVE (prev, flags); + LOAD (next); + } + else + { + /* need to start coroutine */ + /* first get rid of the old state */ + SAVE (prev, -1); + /* setup coroutine call */ + setup_coro (next); + /* need a stack */ + next->stack = 0; } - else if (ctx->gencnt == stack->gencnt) - --stack->usecnt; + + if (!prev->stack) + /* create a new empty context */ + Newz (0, prev->stack, 1, coro_stack); + + prev__stack = prev->stack; + + /* possibly "free" the stack */ + if (prev__stack->idle_sp == STACKLEVEL) + { + stack_put (prev__stack); + prev->stack = 0; + } + + if (!next->stack) + next->stack = stack_get (); + + if (prev__stack != next->stack) + { + prev__stack->top_env = PL_top_env; + PL_top_env = next->stack->top_env; + coro_transfer (&prev__stack->cctx, &next->stack->cctx); + } + + free_coro_mortal (); + + UNLOCK; } } +struct transfer_args +{ + struct coro *prev, *next; + int flags; +}; + +#define TRANSFER(ta) transfer ((ta).prev, (ta).next, (ta).flags) + static void -setup_coro (void *arg) +coro_state_destroy (struct coro *coro) { - /* - * emulate part of the perl startup here. - */ - dSP; - Coro__State ctx = (Coro__State)arg; - SV *sub_init = (SV*)get_cv(SUB_INIT, FALSE); + if (coro->refcnt--) + return; - coro_init_stacks (aTHX); - JMPENV_BOOTSTRAP; - SPAGAIN; + if (coro->mainstack && coro->mainstack != main_mainstack) + { + struct coro temp; + + SAVE ((&temp), TRANSFER_SAVE_ALL); + LOAD (coro); + + coro_destroy_stacks (); - /*PL_curcop = 0;*/ - SvREFCNT_dec (GvAV (PL_defgv)); - GvAV (PL_defgv) = ctx->args; - - if (ctx->stack) - { - ctx->cursp = 0; - - PUSHMARK(SP); - PUTBACK; - (void) call_sv (sub_init, G_VOID|G_NOARGS); - croak ("FATAL: CCTXT coroutine returned!"); + LOAD ((&temp)); /* this will get rid of defsv etc.. */ + + coro->mainstack = 0; } - else - { - UNOP myop; - PL_op = (OP *)&myop; + stack_free (coro->stack); + SvREFCNT_dec (coro->args); + Safefree (coro); +} - Zero(&myop, 1, UNOP); - myop.op_next = Nullop; - myop.op_flags = OPf_WANT_VOID; +static int +coro_state_clear (pTHX_ SV *sv, MAGIC *mg) +{ + struct coro *coro = (struct coro *)mg->mg_ptr; + mg->mg_ptr = 0; - PUSHMARK(SP); - XPUSHs (sub_init); - /* - * the next line is slightly wrong, as PL_op->op_next - * is actually being executed so we skip the first op. - * that doesn't matter, though, since it is only - * pp_nextstate and we never return... - * ah yes, and I don't care anyways ;) - */ - PUTBACK; - PL_op = pp_entersub(); - SPAGAIN; + coro_state_destroy (coro); - ENTER; /* necessary e.g. for dounwind */ + return 0; +} + +static int +coro_state_dup (pTHX_ MAGIC *mg, CLONE_PARAMS *params) +{ + struct coro *coro = (struct coro *)mg->mg_ptr; + + ++coro->refcnt; + + return 0; +} + +static MGVTBL coro_state_vtbl = { + 0, 0, 0, 0, + coro_state_clear, + 0, +#ifdef MGf_DUP + coro_state_dup, +#else +# define MGf_DUP 0 +#endif +}; + +static struct coro * +SvSTATE (SV *coro) +{ + HV *stash; + MAGIC *mg; + + if (SvROK (coro)) + coro = SvRV (coro); + + stash = SvSTASH (coro); + if (stash != coro_stash && stash != coro_state_stash) + { + /* very slow, but rare, check */ + if (!sv_derived_from (sv_2mortal (newRV_inc (coro)), "Coro::State")) + croak ("Coro::State object required"); } + + mg = SvMAGIC (coro); + assert (mg->mg_type == PERL_MAGIC_ext); + return (struct coro *)mg->mg_ptr; } static void -continue_coro (void *arg) +prepare_transfer (struct transfer_args *ta, SV *prev, SV *next, int flags) { - /* - * this is a _very_ stripped down perl interpreter ;) - */ - Coro__State ctx = (Coro__State)arg; + ta->prev = SvSTATE (prev); + ta->next = SvSTATE (next); + ta->flags = flags; +} - ctx->cursp = 0; - PL_op = PL_op->op_next; - CALLRUNOPS(aTHX); - /*NORETURN*/ - abort (); +static void +api_transfer (SV *prev, SV *next, int flags) +{ + dTHX; + struct transfer_args ta; + + prepare_transfer (&ta, prev, next, flags); + TRANSFER (ta); } -STATIC void -transfer(pTHX_ struct coro *prev, struct coro *next, int flags) +/** 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 + +/* for Coro.pm */ +static GV *coro_current, *coro_idle; +static AV *coro_ready [PRIO_MAX-PRIO_MIN+1]; +static int coro_nready; + +static void +coro_enq (SV *sv) { - dSP; - dSTACKLEVEL; + int prio; - if (prev != next) - { - if (next->mainstack) - { - SAVE (prev, flags); - LOAD (next); + if (SvTYPE (sv) != SVt_PVHV) + croak ("Coro::ready tried to enqueue something that is not a coroutine"); - /* mark this state as in-use */ - next->mainstack = 0; - next->tmps_ix = -2; + prio = SvSTATE (sv)->prio; - /* stacklevel changed? if yes, grab the stack for us! */ - if (flags & TRANSFER_SAVE_CCTXT) - { - if (!prev->stack) - allocate_stack (prev, 0); - else if (prev->cursp != stacklevel - && prev->stack->usecnt > 1) - { - prev->gencnt = ++prev->stack->gencnt; - prev->stack->usecnt = 1; - } - - /* has our stack been invalidated? */ - if (next->stack && next->stack->gencnt != next->gencnt) - { - deallocate_stack (next); - allocate_stack (next, 1); - coro_create (&(next->stack->cctx), - continue_coro, (void *)next, - next->stack->sptr, labs (next->stack->ssize)); - } + av_push (coro_ready [prio - PRIO_MIN], sv); + coro_nready++; +} - coro_transfer (&(prev->stack->cctx), &(next->stack->cctx)); - } +static SV * +coro_deq (int min_prio) +{ + int prio = PRIO_MAX - PRIO_MIN; - } - else if (next->tmps_ix == -2) - croak ("tried to transfer to running coroutine"); - else - { - SAVE (prev, -1); /* first get rid of the old state */ + min_prio -= PRIO_MIN; + if (min_prio < 0) + min_prio = 0; - if (flags & TRANSFER_SAVE_CCTXT) - { - if (!prev->stack) - allocate_stack (prev, 0); + for (prio = PRIO_MAX - PRIO_MIN + 1; --prio >= min_prio; ) + if (AvFILLp (coro_ready [prio]) >= 0) + { + coro_nready--; + return av_shift (coro_ready [prio]); + } - if (prev->stack->sptr && flags & TRANSFER_LAZY_STACK) - { - setup_coro (next); - - prev->stack->refcnt++; - prev->stack->usecnt++; - next->stack = prev->stack; - next->gencnt = prev->gencnt; - } - else - { - allocate_stack (next, 1); - coro_create (&(next->stack->cctx), - setup_coro, (void *)next, - next->stack->sptr, labs (next->stack->ssize)); - coro_transfer (&(prev->stack->cctx), &(next->stack->cctx)); - } - } - else - setup_coro (next); - } + return 0; +} + +static void +api_ready (SV *coro) +{ + dTHX; + + if (SvROK (coro)) + coro = SvRV (coro); + + LOCK; + coro_enq (SvREFCNT_inc (coro)); + UNLOCK; +} + +static void +prepare_schedule (struct transfer_args *ta) +{ + SV *current, *prev, *next; + + current = GvSV (coro_current); + + for (;;) + { + LOCK; + next = coro_deq (PRIO_MIN); + UNLOCK; + + if (next) + break; + + { + dSP; + + ENTER; + SAVETMPS; + + PUSHMARK (SP); + PUTBACK; + call_sv (GvSV (coro_idle), G_DISCARD); + + FREETMPS; + LEAVE; + } } - next->cursp = stacklevel; + prev = SvRV (current); + SvRV (current) = next; + + /* free this only after the transfer */ + LOCK; + free_coro_mortal (); + UNLOCK; + coro_mortal = prev; + + ta->prev = SvSTATE (prev); + ta->next = SvSTATE (next); + ta->flags = TRANSFER_SAVE_ALL; +} + +static void +prepare_cede (struct transfer_args *ta) +{ + LOCK; + coro_enq (SvREFCNT_inc (SvRV (GvSV (coro_current)))); + UNLOCK; + + prepare_schedule (ta); +} + +static void +api_schedule (void) +{ + dTHX; + struct transfer_args ta; + + prepare_schedule (&ta); + TRANSFER (ta); +} + +static void +api_cede (void) +{ + dTHX; + struct transfer_args ta; + + prepare_cede (&ta); + TRANSFER (ta); } MODULE = Coro::State PACKAGE = Coro::State -PROTOTYPES: ENABLE +PROTOTYPES: DISABLE BOOT: -{ /* {} necessary for stoopid perl-5.6.x */ - ucoro_state_sv = newSVpv (UCORO_STATE, sizeof(UCORO_STATE) - 1); - PERL_HASH(ucoro_state_hash, UCORO_STATE, sizeof(UCORO_STATE) - 1); +{ +#ifdef USE_ITHREADS + MUTEX_INIT (&coro_mutex); +#endif + BOOT_PAGESIZE; + coro_state_stash = gv_stashpv ("Coro::State", TRUE); newCONSTSUB (coro_state_stash, "SAVE_DEFAV", newSViv (TRANSFER_SAVE_DEFAV)); newCONSTSUB (coro_state_stash, "SAVE_DEFSV", newSViv (TRANSFER_SAVE_DEFSV)); newCONSTSUB (coro_state_stash, "SAVE_ERRSV", newSViv (TRANSFER_SAVE_ERRSV)); - newCONSTSUB (coro_state_stash, "SAVE_CCTXT", newSViv (TRANSFER_SAVE_CCTXT)); - - if (!padlist_cache) - padlist_cache = newHV (); main_mainstack = PL_mainstack; + + coroapi.ver = CORO_API_VERSION; + coroapi.transfer = api_transfer; + + assert (("PRIO_NORMAL must be 0", !PRIO_NORMAL)); } -Coro::State -_newprocess(args) - SV * args - PROTOTYPE: $ +SV * +new (char *klass, ...) CODE: - Coro__State coro; +{ + struct coro *coro; + HV *hv; + int i; + + Newz (0, coro, 1, struct coro); + coro->args = newAV (); + + hv = newHV (); + sv_magicext ((SV *)hv, 0, PERL_MAGIC_ext, &coro_state_vtbl, (char *)coro, 0)->mg_flags |= MGf_DUP; + RETVAL = sv_bless (newRV_noinc ((SV *)hv), gv_stashpv (klass, 1)); - if (!SvROK (args) || SvTYPE (SvRV (args)) != SVt_PVAV) - croak ("Coro::State::_newprocess expects an arrayref"); - - New (0, coro, 1, struct coro); - - coro->args = (AV *)SvREFCNT_inc (SvRV (args)); - coro->mainstack = 0; /* actual work is done inside transfer */ - coro->stack = 0; + for (i = 1; i < items; i++) + av_push (coro->args, newSVsv (ST (i))); - RETVAL = coro; + /*coro->mainstack = 0; *//*actual work is done inside transfer */ + /*coro->stack = 0;*/ +} OUTPUT: RETVAL void -transfer(prev, next, flags = TRANSFER_SAVE_ALL | TRANSFER_LAZY_STACK) - Coro::State_or_hashref prev - Coro::State_or_hashref next - int flags - PROTOTYPE: @ - CODE: - transfer (aTHX_ prev, next, flags); - -void -DESTROY(coro) - Coro::State coro +_set_stacklevel (...) + ALIAS: + Coro::State::transfer = 1 + Coro::schedule = 2 + Coro::cede = 3 + Coro::Cont::yield = 4 CODE: +{ + struct transfer_args ta; - if (coro->mainstack && coro->mainstack != main_mainstack) + switch (ix) { - struct coro temp; + case 0: + ta.prev = (struct coro *)INT2PTR (coro_stack *, SvIV (ST (0))); + ta.next = 0; + ta.flags = TRANSFER_SET_STACKLEVEL; + break; + + case 1: + if (items != 3) + croak ("Coro::State::transfer(prev,next,flags) expects three arguments, not %d", items); + + prepare_transfer (&ta, ST (0), ST (1), SvIV (ST (2))); + break; + + case 2: + prepare_schedule (&ta); + break; + + case 3: + prepare_cede (&ta); + break; - SAVE(aTHX_ (&temp), TRANSFER_SAVE_ALL); - LOAD(aTHX_ coro); + case 4: + { + SV *yieldstack; + SV *sv; + AV *defav = GvAV (PL_defgv); + + yieldstack = *hv_fetch ( + (HV *)SvRV (GvSV (coro_current)), + "yieldstack", sizeof ("yieldstack") - 1, + 0 + ); + + /* set up @_ -- ugly */ + av_clear (defav); + av_fill (defav, items - 1); + while (items--) + av_store (defav, items, SvREFCNT_inc (ST(items))); + + sv = av_pop ((AV *)SvRV (yieldstack)); + ta.prev = SvSTATE (*av_fetch ((AV *)SvRV (sv), 0, 0)); + ta.next = SvSTATE (*av_fetch ((AV *)SvRV (sv), 1, 0)); + ta.flags = 0; + SvREFCNT_dec (sv); + } + break; - destroy_stacks (aTHX); + } - LOAD((&temp)); /* this will get rid of defsv etc.. */ + TRANSFER (ta); +} - coro->mainstack = 0; - } +void +_clone_state_from (SV *dst, SV *src) + CODE: +{ + struct coro *coro_src = SvSTATE (src); - deallocate_stack (coro); + sv_unmagic (SvRV (dst), PERL_MAGIC_ext); - Safefree (coro); + ++coro_src->refcnt; + sv_magicext (SvRV (dst), 0, PERL_MAGIC_ext, &coro_state_vtbl, (char *)coro_src, 0)->mg_flags |= MGf_DUP; +} void -flush() +_exit (code) + int code + PROTOTYPE: $ CODE: -#ifdef MAY_FLUSH - flush_padlist_cache (); -#endif + _exit (code); -MODULE = Coro::State PACKAGE = Coro::Cont +MODULE = Coro::State PACKAGE = Coro -# this is slightly dirty +BOOT: +{ + int i; + + coro_stash = gv_stashpv ("Coro", TRUE); + + 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)); + + coro_current = gv_fetchpv ("Coro::current", TRUE, SVt_PV); + coro_idle = gv_fetchpv ("Coro::idle" , TRUE, SVt_PV); + + for (i = PRIO_MAX - PRIO_MIN + 1; i--; ) + coro_ready[i] = newAV (); + + { + SV *sv = perl_get_sv("Coro::API", 1); + + coroapi.schedule = api_schedule; + coroapi.cede = api_cede; + coroapi.ready = api_ready; + coroapi.nready = &coro_nready; + coroapi.current = coro_current; + + GCoroAPI = &coroapi; + sv_setiv (sv, (IV)&coroapi); + SvREADONLY_on (sv); + } +} + +int +prio (Coro::State coro, int newprio = 0) + ALIAS: + nice = 1 + CODE: +{ + RETVAL = coro->prio; + + if (items > 1) + { + if (ix) + newprio += coro->prio; + + if (newprio < PRIO_MIN) newprio = PRIO_MIN; + if (newprio > PRIO_MAX) newprio = PRIO_MAX; + + coro->prio = newprio; + } +} void -yield(...) - PROTOTYPE: @ +ready (SV *self) + PROTOTYPE: $ + CODE: + api_ready (self); + +int +nready (...) + PROTOTYPE: CODE: - static SV *returnstk; - SV *sv; - AV *defav = GvAV (PL_defgv); - struct coro *prev, *next; - - if (!returnstk) - returnstk = SvRV (get_sv ("Coro::Cont::return", FALSE)); - - /* set up @_ -- ugly */ - av_clear (defav); - av_fill (defav, items - 1); - while (items--) - av_store (defav, items, SvREFCNT_inc (ST(items))); - - mg_get (returnstk); /* isn't documentation wrong for mg_get? */ - sv = av_pop ((AV *)SvRV (returnstk)); - prev = (struct coro *)SvIV ((SV*)SvRV (*av_fetch ((AV *)SvRV (sv), 0, 0))); - next = (struct coro *)SvIV ((SV*)SvRV (*av_fetch ((AV *)SvRV (sv), 1, 0))); - SvREFCNT_dec (sv); + RETVAL = coro_nready; + OUTPUT: + RETVAL + +MODULE = Coro::State PACKAGE = Coro::AIO - transfer(aTHX_ prev, next, 0); +SV * +_get_state () + CODE: +{ + struct { + int errorno; + int laststype; + int laststatval; + Stat_t statcache; + } data; + + data.errorno = errno; + data.laststype = PL_laststype; + data.laststatval = PL_laststatval; + data.statcache = PL_statcache; + RETVAL = newSVpvn ((char *)&data, sizeof data); +} + OUTPUT: + RETVAL + +void +_set_state (char *data_) + PROTOTYPE: $ + CODE: +{ + struct { + int errorno; + int laststype; + int laststatval; + Stat_t statcache; + } *data = (void *)data_; + + errno = data->errorno; + PL_laststype = data->laststype; + PL_laststatval = data->laststatval; + PL_statcache = data->statcache; +}