89
95
#define IN_DESTRUCT PL_dirty
92
# define attribute(x) __attribute__(x)
93
# define expect(expr,value) __builtin_expect ((expr), (value))
94
# define INLINE static inline
97
# define expect(expr,value) (expr)
98
# define INLINE static
101
#define expect_false(expr) expect ((expr) != 0, 0)
102
#define expect_true(expr) expect ((expr) != 0, 1)
104
#define NOINLINE attribute ((noinline))
106
97
#include "CoroAPI.h"
107
98
#define GCoroAPI (&coroapi) /* very sneaky */
198
194
unsigned char flags;
201
coro_cctx *cctx_current; /* the currently running cctx */
197
static coro_cctx *cctx_current; /* the currently running cctx */
203
199
/*****************************************************************************/
201
static MGVTBL coro_state_vtbl;
206
205
CF_RUNNING = 0x0001, /* coroutine is running */
207
206
CF_READY = 0x0002, /* coroutine is ready */
208
207
CF_NEW = 0x0004, /* has never been switched to */
209
CF_DESTROYED = 0x0008, /* coroutine data has been freed */
208
CF_ZOMBIE = 0x0008, /* coroutine data has been freed */
210
209
CF_SUSPENDED = 0x0010, /* coroutine can't be scheduled */
210
CF_NOCANCEL = 0x0020, /* cannot cancel, set slf_frame.data to 1 (hackish) */
213
213
/* the structure where most of the perl state is stored, overlaid on the cxstack */
221
#define VAR(name,type) type name;
216
#define VARx(name,expr,type) type name;
222
217
# include "state.h"
221
/* how many context stack entries do we need for perl_slots */
226
222
#define SLOT_COUNT ((sizeof (perl_slots) + sizeof (PERL_CONTEXT) - 1) / sizeof (PERL_CONTEXT))
228
224
/* this is a structure representing a perl-level coroutine */
230
227
/* the C coroutine allocated to this perl coroutine, if any */
239
236
perl_slots *slot; /* basically the saved sp */
241
CV *startcv; /* the CV to execute */
242
AV *args; /* data associated with this coroutine (initial args) */
243
int refcnt; /* coroutines are refcounted, yes */
244
int flags; /* CF_ flags */
245
HV *hv; /* the perl hash associated with this coro, if any */
246
void (*on_destroy)(pTHX_ struct coro *coro); /* for temporary use by xs in critical sections */
238
CV *startcv; /* the CV to execute */
239
AV *args; /* data associated with this coroutine (initial args) */
240
int flags; /* CF_ flags */
241
HV *hv; /* the perl hash associated with this coro, if any */
249
244
int usecount; /* number of transfers to this coro */
251
246
/* coro process data */
253
SV *except; /* exception to be thrown */
248
SV *except; /* exception to be thrown */
249
SV *rouse_cb; /* last rouse callback */
250
AV *on_destroy; /* callbacks or coros to notify on destroy */
251
AV *status; /* the exit status list */
293
290
static SV *coro_current;
294
291
static SV *coro_readyhook;
295
292
static struct coro *coro_ready [CORO_PRIO_MAX - CORO_PRIO_MIN + 1][2]; /* head|tail */
296
static CV *cv_coro_run, *cv_coro_terminate;
293
static CV *cv_coro_run;
297
294
static struct coro *coro_first;
298
295
#define coro_nready coroapi.nready
297
/** JIT *********************************************************************/
300
/* APPLE doesn't have HAVE_MMAP though */
301
#define CORO_JIT_UNIXY (__linux || __FreeBSD__ || __OpenBSD__ || __NetBSD__ || __solaris || __APPLE__)
302
#ifndef CORO_JIT_TYPE
303
#if __x86_64 && CORO_JIT_UNIXY
304
#define CORO_JIT_TYPE "amd64-unix"
305
#elif __i386 && CORO_JIT_UNIXY
306
#define CORO_JIT_TYPE "x86-unix"
311
#if !defined(CORO_JIT_TYPE) || !HAVE_MMAP
316
typedef void (*load_save_perl_slots_type)(perl_slots *);
317
static load_save_perl_slots_type load_perl_slots, save_perl_slots;
300
320
/** Coro::Select ************************************************************/
302
322
static OP *(*coro_old_pp_sselect) (pTHX);
454
474
#define CORO_MAGIC_type_cv 26
455
475
#define CORO_MAGIC_type_state PERL_MAGIC_ext
457
#define CORO_MAGIC_NN(sv, type) \
458
(expect_true (SvMAGIC (sv)->mg_type == type) \
477
#define CORO_MAGIC_NN(sv, type) \
478
(ecb_expect_true (SvMAGIC (sv)->mg_type == type) \
460
480
: mg_find (sv, type))
462
#define CORO_MAGIC(sv, type) \
463
(expect_true (SvMAGIC (sv)) \
464
? CORO_MAGIC_NN (sv, type) \
482
#define CORO_MAGIC(sv, type) \
483
(ecb_expect_true (SvMAGIC (sv)) \
484
? CORO_MAGIC_NN (sv, type) \
467
487
#define CORO_MAGIC_cv(cv) CORO_MAGIC (((SV *)(cv)), CORO_MAGIC_type_cv)
468
488
#define CORO_MAGIC_state(sv) CORO_MAGIC_NN (((SV *)(sv)), CORO_MAGIC_type_state)
491
SvSTATEhv_p (pTHX_ SV *coro)
495
if (ecb_expect_true (
496
SvTYPE (coro) == SVt_PVHV
497
&& (mg = CORO_MAGIC_state (coro))
498
&& mg->mg_virtual == &coro_state_vtbl
505
ecb_inline struct coro *
471
506
SvSTATE_ (pTHX_ SV *coro)
476
510
if (SvROK (coro))
477
511
coro = SvRV (coro);
479
if (expect_false (SvTYPE (coro) != SVt_PVHV))
513
mg = SvSTATEhv_p (aTHX_ coro);
480
515
croak ("Coro::State object required");
482
stash = SvSTASH (coro);
483
if (expect_false (stash != coro_stash && stash != coro_state_stash))
485
/* very slow, but rare, check */
486
if (!sv_derived_from (sv_2mortal (newRV_inc (coro)), "Coro::State"))
487
croak ("Coro::State object required");
490
mg = CORO_MAGIC_state (coro);
491
517
return (struct coro *)mg->mg_ptr;
801
825
/* allocate some space on the context stack for our purposes */
802
/* we manually unroll here, as usually 2 slots is enough */
803
if (SLOT_COUNT >= 1) CXINC;
804
if (SLOT_COUNT >= 2) CXINC;
805
if (SLOT_COUNT >= 3) CXINC;
808
for (i = 3; i < SLOT_COUNT; ++i)
811
cxstack_ix -= SLOT_COUNT; /* undo allocation */
826
if (ecb_expect_false (cxstack_ix + (int)SLOT_COUNT >= cxstack_max))
830
for (i = 0; i < SLOT_COUNT; ++i)
833
cxstack_ix -= SLOT_COUNT; /* undo allocation */
813
836
c->mainstack = PL_mainstack;
816
839
perl_slots *slot = c->slot = (perl_slots *)(cxstack + cxstack_ix + 1);
818
slot->defav = GvAV (PL_defgv);
821
slot->irsgv = GvSV (irsgv);
822
slot->hinthv = GvHV (PL_hintgv);
824
#define VAR(name,type) slot->name = PL_ ## name;
842
save_perl_slots (slot);
844
#define VARx(name,expr,type) slot->name = expr;
825
845
# include "state.h"
1158
struct coro *current = SvSTATE_current;
1186
SV *old_current = SvRV (coro_current);
1187
struct coro *current = SvSTATE (old_current);
1160
1189
assert (("FATAL: tried to destroy currently running coroutine", coro->mainstack != PL_mainstack));
1162
1191
save_perl (aTHX_ current);
1193
/* this will cause transfer_check to croak on block*/
1194
SvRV_set (coro_current, (SV *)coro->hv);
1163
1196
load_perl (aTHX_ coro);
1165
1198
coro_unwind_stacks (aTHX);
1166
coro_destruct_stacks (aTHX);
1168
1200
/* restore swapped sv's */
1169
1201
SWAP_SVS (coro);
1171
// now save some sv's to be free'd later
1203
coro_destruct_stacks (aTHX);
1205
/* now save some sv's to be free'd later */
1172
1206
svf [0] = GvSV (PL_defgv);
1173
1207
svf [1] = (SV *)GvAV (PL_defgv);
1174
1208
svf [2] = GvSV (PL_errgv);
1570
1606
/* TODO: throwing up here is considered harmful */
1572
if (expect_true (prev != next))
1608
if (ecb_expect_true (prev != next))
1574
if (expect_false (!(prev->flags & (CF_RUNNING | CF_NEW))))
1610
if (ecb_expect_false (!(prev->flags & (CF_RUNNING | CF_NEW))))
1575
1611
croak ("Coro::State::transfer called with a blocked prev Coro::State, but can only transfer from running or new states,");
1577
if (expect_false (next->flags & (CF_RUNNING | CF_DESTROYED | CF_SUSPENDED)))
1613
if (ecb_expect_false (next->flags & (CF_RUNNING | CF_ZOMBIE | CF_SUSPENDED)))
1578
1614
croak ("Coro::State::transfer called with running, destroyed or suspended next Coro::State, but can only transfer to inactive states,");
1580
1616
#if !PERL_VERSION_ATLEAST (5,10,0)
1581
if (expect_false (PL_lex_state != LEX_NOTPARSING))
1617
if (ecb_expect_false (PL_lex_state != LEX_NOTPARSING))
1582
1618
croak ("Coro::State::transfer called while parsing, but this is not supported in your perl version,");
1587
1623
/* always use the TRANSFER macro */
1588
static void NOINLINE /* noinline so we have a fixed stackframe */
1624
static void ecb_noinline /* noinline so we have a fixed stackframe */
1589
1625
transfer (pTHX_ struct coro *prev, struct coro *next, int force_cctx)
1593
1629
/* sometimes transfer is only called to set idle_sp */
1594
if (expect_false (!prev))
1630
if (ecb_expect_false (!prev))
1596
1632
cctx_current->idle_sp = STACKLEVEL;
1597
1633
assert (cctx_current->idle_te = PL_top_env); /* just for the side-effect when asserts are enabled */
1599
else if (expect_true (prev != next))
1635
else if (ecb_expect_true (prev != next))
1601
1637
coro_cctx *cctx_prev;
1603
if (expect_false (prev->flags & CF_NEW))
1639
if (ecb_expect_false (prev->flags & CF_NEW))
1605
1641
/* create a new empty/source context */
1606
1642
prev->flags &= ~CF_NEW;
1668
1704
/** high level stuff ********************************************************/
1706
/* this function is actually Coro, not Coro::State, but we call it from here */
1707
/* because it is convenient - but it hasn't been declared yet for that reason */
1709
coro_call_on_destroy (pTHX_ struct coro *coro);
1671
1712
coro_state_destroy (pTHX_ struct coro *coro)
1673
if (coro->flags & CF_DESTROYED)
1676
if (coro->on_destroy && !PL_dirty)
1677
coro->on_destroy (aTHX_ coro);
1679
coro->flags |= CF_DESTROYED;
1714
if (coro->flags & CF_ZOMBIE)
1717
slf_destroy (aTHX_ coro);
1719
coro->flags |= CF_ZOMBIE;
1681
1721
if (coro->flags & CF_READY)
1688
1728
coro->flags |= CF_READY; /* make sure it is NOT put into the readyqueue */
1730
if (coro->next) coro->next->prev = coro->prev;
1731
if (coro->prev) coro->prev->next = coro->next;
1732
if (coro == coro_first) coro_first = coro->next;
1690
1734
if (coro->mainstack
1691
1735
&& coro->mainstack != main_mainstack
1694
1738
destroy_perl (aTHX_ coro);
1696
if (coro->next) coro->next->prev = coro->prev;
1697
if (coro->prev) coro->prev->next = coro->next;
1698
if (coro == coro_first) coro_first = coro->next;
1700
1740
cctx_destroy (coro->cctx);
1701
1741
SvREFCNT_dec (coro->startcv);
1702
1742
SvREFCNT_dec (coro->args);
1703
1743
SvREFCNT_dec (coro->swap_sv);
1704
1744
SvREFCNT_dec (CORO_THROW);
1746
coro_call_on_destroy (aTHX_ coro);
1748
/* more destruction mayhem in coro_state_free */
2051
coro_push_av (pTHX_ AV *av, I32 gimme_v)
2053
if (AvFILLp (av) >= 0 && gimme_v != G_VOID)
2057
if (gimme_v == G_SCALAR)
2058
XPUSHs (AvARRAY (av)[AvFILLp (av)]);
2062
EXTEND (SP, AvFILLp (av) + 1);
2064
for (i = 0; i <= AvFILLp (av); ++i)
2065
PUSHs (AvARRAY (av)[i]);
2073
coro_push_on_destroy (pTHX_ struct coro *coro, SV *cb)
2075
if (!coro->on_destroy)
2076
coro->on_destroy = newAV ();
2078
av_push (coro->on_destroy, cb);
2082
slf_destroy_join (pTHX_ struct CoroSLF *frame)
2084
SvREFCNT_dec ((SV *)((struct coro *)frame->data)->hv);
2088
slf_check_join (pTHX_ struct CoroSLF *frame)
2090
struct coro *coro = (struct coro *)frame->data;
2097
coro_push_av (aTHX_ coro->status, GIMME_V);
2099
SvREFCNT_dec ((SV *)coro->hv);
2105
slf_init_join (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2107
struct coro *coro = SvSTATE (items > 0 ? arg [0] : &PL_sv_undef);
2110
croak ("join called with too many arguments");
2113
frame->prepare = prepare_nop;
2116
coro_push_on_destroy (aTHX_ coro, SvREFCNT_inc_NN (SvRV (coro_current)));
2117
frame->prepare = prepare_schedule;
2120
frame->check = slf_check_join;
2121
frame->destroy = slf_destroy_join;
2122
frame->data = (void *)coro;
2123
SvREFCNT_inc (coro->hv);
2010
2127
coro_call_on_destroy (pTHX_ struct coro *coro)
2012
SV **on_destroyp = hv_fetch (coro->hv, "_on_destroy", sizeof ("_on_destroy") - 1, 0);
2013
SV **statusp = hv_fetch (coro->hv, "_status", sizeof ("_status") - 1, 0);
2129
AV *od = coro->on_destroy;
2134
while (AvFILLp (od) >= 0)
2017
AV *on_destroy = (AV *)SvRV (*on_destroyp);
2136
SV *cb = sv_2mortal (av_pop (od));
2019
while (AvFILLp (on_destroy) >= 0)
2138
/* coro hv's (and only hv's at the moment) are supported as well */
2139
if (SvSTATEhv_p (aTHX_ cb))
2140
api_ready (aTHX_ cb);
2021
2143
dSP; /* don't disturb outer sp */
2022
SV *cb = av_pop (on_destroy);
2029
AV *status = (AV *)SvRV (*statusp);
2030
EXTEND (SP, AvFILLp (status) + 1);
2032
for (i = 0; i <= AvFILLp (status); ++i)
2033
PUSHs (AvARRAY (status)[i]);
2149
coro_push_av (aTHX_ coro->status, G_ARRAY);
2037
call_sv (sv_2mortal (cb), G_VOID | G_DISCARD);
2154
call_sv (cb, G_VOID | G_DISCARD);
2043
slf_init_terminate (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2160
coro_set_status (pTHX_ struct coro *coro, SV **arg, int items)
2046
HV *hv = (HV *)SvRV (coro_current);
2170
av = coro->status = newAV ();
2049
2172
/* items are actually not so common, so optimise for this case */
2052
2177
av_extend (av, items - 1);
2054
2179
for (i = 0; i < items; ++i)
2055
2180
av_push (av, SvREFCNT_inc_NN (arg [i]));
2058
hv_store (hv, "_status", sizeof ("_status") - 1, newRV_noinc ((SV *)av), 0);
2060
av_push (av_destroy, (SV *)newRV_inc ((SV *)hv)); /* RVinc for perl */
2185
slf_init_terminate_cancel_common (pTHX_ struct CoroSLF *frame, HV *coro_hv)
2187
av_push (av_destroy, (SV *)newRV_inc ((SV *)coro_hv)); /* RVinc for perl */
2061
2188
api_ready (aTHX_ sv_manager);
2063
2190
frame->prepare = prepare_schedule;
2068
2195
/*coro_unwind_stacks (aTHX);*/
2199
slf_init_terminate (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2201
HV *coro_hv = (HV *)SvRV (coro_current);
2203
coro_set_status (aTHX_ SvSTATE ((SV *)coro_hv), arg, items);
2204
slf_init_terminate_cancel_common (aTHX_ frame, coro_hv);
2208
slf_init_cancel (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2214
croak ("Coro::cancel called without coro object,");
2216
coro = SvSTATE (arg [0]);
2219
coro_set_status (aTHX_ coro, arg + 1, items - 1);
2221
if (ecb_expect_false (coro->flags & CF_NOCANCEL))
2223
/* coro currently busy cancelling something, so just notify it */
2224
coro->slf_frame.data = (void *)coro;
2226
frame->prepare = prepare_nop;
2227
frame->check = slf_check_nop;
2229
else if (coro_hv == (HV *)SvRV (coro_current))
2231
/* cancelling the current coro is allowed, and equals terminate */
2232
slf_init_terminate_cancel_common (aTHX_ frame, coro_hv);
2236
struct coro *self = SvSTATE_current;
2238
/* otherwise we cancel directly, purely for speed reasons
2239
* unfortunately, this requires some magic trickery, as
2240
* somebody else could cancel us, so we have to fight the cancellation.
2241
* this is ugly, and hopefully fully worth the extra speed.
2242
* besides, I can't get the slow-but-safe version working...
2245
self->flags |= CF_NOCANCEL;
2246
coro_state_destroy (aTHX_ coro);
2247
self->flags &= ~CF_NOCANCEL;
2251
/* while we were busy we have been cancelled, so terminate */
2252
slf_init_terminate_cancel_common (aTHX_ frame, self->hv);
2256
frame->prepare = prepare_nop;
2257
frame->check = slf_check_nop;
2263
slf_check_safe_cancel (pTHX_ struct CoroSLF *frame)
2266
coro_unwind_stacks (aTHX);
2268
slf_init_terminate_cancel_common (aTHX_ frame, (HV *)SvRV (coro_current));
2274
safe_cancel (pTHX_ struct coro *coro, SV **arg, int items)
2277
croak ("coro inside C callback, unable to cancel at this time, caught");
2279
if (coro->flags & CF_NEW)
2281
coro_set_status (aTHX_ coro, arg, items);
2282
coro_state_destroy (aTHX_ coro);
2286
if (!coro->slf_frame.prepare)
2287
croak ("coro outside an SLF function, unable to cancel at this time, caught");
2289
slf_destroy (aTHX_ coro);
2291
coro_set_status (aTHX_ coro, arg, items);
2292
coro->slf_frame.prepare = prepare_nop;
2293
coro->slf_frame.check = slf_check_safe_cancel;
2295
api_ready (aTHX_ (SV *)coro->hv);
2071
2301
/*****************************************************************************/
2072
2302
/* async pool handler */
2353
2581
frame->check = slf_check_nop;
2584
/* "undo"/cancel a running slf call - used when cancelling a coro, mainly */
2586
slf_destroy (pTHX_ struct coro *coro)
2588
/* this callback is reserved for slf functions needing to do cleanup */
2589
if (coro->slf_frame.destroy && coro->slf_frame.prepare && !PL_dirty)
2590
coro->slf_frame.destroy (aTHX_ &coro->slf_frame);
2593
* The on_destroy above most likely is from an SLF call.
2594
* Since by definition the SLF call will not finish when we destroy
2595
* the coro, we will have to force-finish it here, otherwise
2596
* cleanup functions cannot call SLF functions.
2598
coro->slf_frame.prepare = 0;
2357
2602
* these not obviously related functions are all rolled into one
2358
2603
* function to increase chances that they all will call transfer with the same
3103
3348
return coro_sv;
3352
ecb_cold XS(boot_Coro__State);
3357
static void ecb_noinline ecb_cold
3358
pushav_4uv (pTHX_ UV a, UV b, UV c, UV d)
3363
av_store (av, 3, newSVuv (d));
3364
av_store (av, 2, newSVuv (c));
3365
av_store (av, 1, newSVuv (b));
3366
av_store (av, 0, newSVuv (a));
3368
XPUSHs (sv_2mortal (newRV_noinc ((SV *)av)));
3373
static void ecb_noinline ecb_cold
3379
char *load_ptr, *save_ptr;
3380
STRLEN load_len, save_len, map_len;
3383
eval_pv ("require 'Coro/jit-" CORO_JIT_TYPE ".pl'", 1);
3386
#define VARx(name,expr,type) pushav_4uv (aTHX_ (UV)&(expr), sizeof (expr), offsetof (perl_slots, name), sizeof (type));
3389
count = call_pv ("Coro::State::_jit", G_ARRAY);
3392
save = POPs; save_ptr = SvPVbyte (save, save_len);
3393
load = POPs; load_ptr = SvPVbyte (load, load_len);
3395
map_len = load_len + save_len + 16;
3397
map_base = mmap (0, map_len, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
3399
assert (("Coro: unable to mmap jit code page, cannot continue.", map_base != (char *)MAP_FAILED));
3401
load_perl_slots = (load_save_perl_slots_type)map_base;
3402
memcpy (map_base, load_ptr, load_len);
3404
map_base += (load_len + 15) & ~15;
3406
save_perl_slots = (load_save_perl_slots_type)map_base;
3407
memcpy (map_base, save_ptr, save_len);
3409
/* we are good citizens and try to make the page read-only, so the evil evil */
3410
/* hackers might have it a bit more difficult */
3411
mprotect (map_base, map_len, PROT_READ | PROT_EXEC);
3414
eval_pv ("undef &Coro::State::_jit", 1);
3106
3419
MODULE = Coro::State PACKAGE = Coro::State PREFIX = api_
3108
3421
PROTOTYPES: DISABLE
3841
_destroy (Coro::State coro)
3843
/* used by the manager thread */
3844
coro_state_destroy (aTHX_ coro);
3847
on_destroy (Coro::State coro, SV *cb)
3849
coro_push_on_destroy (aTHX_ coro, newSVsv (cb));
3854
CORO_EXECUTE_SLF_XS (slf_init_join);
3514
3857
terminate (...)
3516
3859
CORO_EXECUTE_SLF_XS (slf_init_terminate);
3864
CORO_EXECUTE_SLF_XS (slf_init_cancel);
3867
safe_cancel (Coro::State self, ...)
3868
C_ARGS: aTHX_ self, &ST (1), items - 1
3521
3873
CORO_EXECUTE_SLF_XS (slf_init_schedule);