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

Comparing Coro/Coro/State.xs (file contents):
Revision 1.211 by root, Wed Oct 10 03:37:58 2007 UTC vs.
Revision 1.293 by root, Tue Nov 18 06:10:03 2008 UTC

4#define PERL_EXT 4#define PERL_EXT
5 5
6#include "EXTERN.h" 6#include "EXTERN.h"
7#include "perl.h" 7#include "perl.h"
8#include "XSUB.h" 8#include "XSUB.h"
9#include "perliol.h"
9 10
10#include "patchlevel.h" 11#include "patchlevel.h"
11 12
12#include <stdio.h> 13#include <stdio.h>
13#include <errno.h> 14#include <errno.h>
14#include <assert.h> 15#include <assert.h>
16
17#ifdef WIN32
18# undef setjmp
19# undef longjmp
20# undef _exit
21# define setjmp _setjmp // deep magic, don't ask
22#else
15#include <inttypes.h> /* portable stdint.h */ 23# include <inttypes.h> /* most portable stdint.h */
24#endif
16 25
17#ifdef HAVE_MMAP 26#ifdef HAVE_MMAP
18# include <unistd.h> 27# include <unistd.h>
19# include <sys/mman.h> 28# include <sys/mman.h>
20# ifndef MAP_ANONYMOUS 29# ifndef MAP_ANONYMOUS
37# define BOOT_PAGESIZE (void)0 46# define BOOT_PAGESIZE (void)0
38#endif 47#endif
39 48
40#if CORO_USE_VALGRIND 49#if CORO_USE_VALGRIND
41# include <valgrind/valgrind.h> 50# include <valgrind/valgrind.h>
42# define REGISTER_STACK(cctx,start,end) (cctx)->valgrind_id = VALGRIND_STACK_REGISTER ((start), (end))
43#else
44# define REGISTER_STACK(cctx,start,end)
45#endif 51#endif
46 52
47/* the maximum number of idle cctx that will be pooled */ 53/* the maximum number of idle cctx that will be pooled */
48#define MAX_IDLE_CCTX 8 54static int cctx_max_idle = 4;
49 55
50#define PERL_VERSION_ATLEAST(a,b,c) \ 56#define PERL_VERSION_ATLEAST(a,b,c) \
51 (PERL_REVISION > (a) \ 57 (PERL_REVISION > (a) \
52 || (PERL_REVISION == (a) \ 58 || (PERL_REVISION == (a) \
53 && (PERL_VERSION > (b) \ 59 && (PERL_VERSION > (b) \
72# ifndef IS_PADCONST 78# ifndef IS_PADCONST
73# define IS_PADCONST(v) 0 79# define IS_PADCONST(v) 0
74# endif 80# endif
75#endif 81#endif
76 82
83/* 5.11 */
84#ifndef CxHASARGS
85# define CxHASARGS(cx) (cx)->blk_sub.hasargs
86#endif
87
88/* 5.10.0 */
89#ifndef SvREFCNT_inc_NN
90# define SvREFCNT_inc_NN(sv) SvREFCNT_inc (sv)
91#endif
92
93/* 5.8.8 */
94#ifndef GV_NOTQUAL
95# define GV_NOTQUAL 0
96#endif
97#ifndef newSV
98# define newSV(l) NEWSV(0,l)
99#endif
100#ifndef CvISXSUB_on
101# define CvISXSUB_on(cv) (void)cv
102#endif
103
77/* 5.8.7 */ 104/* 5.8.7 */
78#ifndef SvRV_set 105#ifndef SvRV_set
79# define SvRV_set(s,v) SvRV(s) = (v) 106# define SvRV_set(s,v) SvRV(s) = (v)
80#endif 107#endif
81 108
82/* 5.8.8 */
83#ifndef GV_NOTQUAL
84# define GV_NOTQUAL 0
85#endif
86#ifndef newSV
87# define newSV(l) NEWSV(0,l)
88#endif
89
90#if !__i386 && !__x86_64 && !__powerpc && !__m68k && !__alpha && !__mips && !__sparc64 109#if !__i386 && !__x86_64 && !__powerpc && !__m68k && !__alpha && !__mips && !__sparc64
91# undef CORO_STACKGUARD 110# undef CORO_STACKGUARD
92#endif 111#endif
93 112
94#ifndef CORO_STACKGUARD 113#ifndef CORO_STACKGUARD
100# define CORO_PREFER_PERL_FUNCTIONS 0 119# define CORO_PREFER_PERL_FUNCTIONS 0
101#endif 120#endif
102 121
103/* The next macros try to return the current stack pointer, in an as 122/* The next macros try to return the current stack pointer, in an as
104 * portable way as possible. */ 123 * portable way as possible. */
105#define dSTACKLEVEL volatile char stacklevel 124#if __GNUC__ >= 4
106#define STACKLEVEL ((void *)&stacklevel) 125# define dSTACKLEVEL void *stacklevel = __builtin_frame_address (0)
126#else
127# define dSTACKLEVEL volatile void *stacklevel = (volatile void *)&stacklevel
128#endif
107 129
108#define IN_DESTRUCT (PL_main_cv == Nullcv) 130#define IN_DESTRUCT (PL_main_cv == Nullcv)
109 131
110#if __GNUC__ >= 3 132#if __GNUC__ >= 3
111# define attribute(x) __attribute__(x) 133# define attribute(x) __attribute__(x)
112# define BARRIER __asm__ __volatile__ ("" : : : "memory")
113# define expect(expr,value) __builtin_expect ((expr),(value)) 134# define expect(expr,value) __builtin_expect ((expr),(value))
135# define INLINE static inline
114#else 136#else
115# define attribute(x) 137# define attribute(x)
116# define BARRIER
117# define expect(expr,value) (expr) 138# define expect(expr,value) (expr)
139# define INLINE static
118#endif 140#endif
119 141
120#define expect_false(expr) expect ((expr) != 0, 0) 142#define expect_false(expr) expect ((expr) != 0, 0)
121#define expect_true(expr) expect ((expr) != 0, 1) 143#define expect_true(expr) expect ((expr) != 0, 1)
122 144
123#define NOINLINE attribute ((noinline)) 145#define NOINLINE attribute ((noinline))
124 146
125#include "CoroAPI.h" 147#include "CoroAPI.h"
126 148
127#ifdef USE_ITHREADS 149#ifdef USE_ITHREADS
128static perl_mutex coro_mutex; 150# if CORO_PTHREAD
129# define LOCK do { MUTEX_LOCK (&coro_mutex); } while (0) 151static void *coro_thx;
130# define UNLOCK do { MUTEX_UNLOCK (&coro_mutex); } while (0)
131#else
132# define LOCK (void)0
133# define UNLOCK (void)0
134#endif 152# endif
153#endif
135 154
136#define strpair(const) const, sizeof (const) - 1 155static double (*nvtime)(); /* so why doesn't it take void? */
137 156
138/* helper storage struct for Coro::AIO */ 157/* we hijack an hopefully unused CV flag for our purposes */
139struct io_state 158#define CVf_SLF 0x4000
140{ 159static OP *pp_slf (pTHX);
141 int errorno;
142 I32 laststype;
143 int laststatval;
144 Stat_t statcache;
145};
146 160
161static U32 cctx_gen;
147static size_t coro_stacksize = CORO_STACKSIZE; 162static size_t cctx_stacksize = CORO_STACKSIZE;
148static struct CoroAPI coroapi; 163static struct CoroAPI coroapi;
149static AV *main_mainstack; /* used to differentiate between $main and others */ 164static AV *main_mainstack; /* used to differentiate between $main and others */
150static JMPENV *main_top_env; 165static JMPENV *main_top_env;
151static HV *coro_state_stash, *coro_stash; 166static HV *coro_state_stash, *coro_stash;
152static SV *coro_mortal; /* will be freed after next transfer */ 167static volatile SV *coro_mortal; /* will be freed/thrown after next transfer */
153 168
154static GV *irsgv; /* $/ */ 169static GV *irsgv; /* $/ */
155static GV *stdoutgv; /* *STDOUT */ 170static GV *stdoutgv; /* *STDOUT */
156 171static SV *rv_diehook;
172static SV *rv_warnhook;
157static HV *hv_sig; /* %SIG */ 173static HV *hv_sig; /* %SIG */
158static SV *sv_diehook;
159static SV *sv_warnhook;
160 174
161/* async_pool helper stuff */ 175/* async_pool helper stuff */
162static SV *sv_pool_rss; 176static SV *sv_pool_rss;
163static SV *sv_pool_size; 177static SV *sv_pool_size;
164static AV *av_async_pool; 178static AV *av_async_pool;
179
180/* Coro::AnyEvent */
181static SV *sv_activity;
165 182
166static struct coro_cctx *cctx_first; 183static struct coro_cctx *cctx_first;
167static int cctx_count, cctx_idle; 184static int cctx_count, cctx_idle;
168 185
169enum { 186enum {
174 CC_TRACE_LINE = 0x10, /* trace each statement */ 191 CC_TRACE_LINE = 0x10, /* trace each statement */
175 CC_TRACE_ALL = CC_TRACE_SUB | CC_TRACE_LINE, 192 CC_TRACE_ALL = CC_TRACE_SUB | CC_TRACE_LINE,
176}; 193};
177 194
178/* this is a structure representing a c-level coroutine */ 195/* this is a structure representing a c-level coroutine */
179typedef struct coro_cctx { 196typedef struct coro_cctx
197{
180 struct coro_cctx *next; 198 struct coro_cctx *next;
181 199
182 /* the stack */ 200 /* the stack */
183 void *sptr; 201 void *sptr;
184 size_t ssize; 202 size_t ssize;
187 void *idle_sp; /* sp of top-level transfer/schedule/cede call */ 205 void *idle_sp; /* sp of top-level transfer/schedule/cede call */
188 JMPENV *idle_te; /* same as idle_sp, but for top_env, TODO: remove once stable */ 206 JMPENV *idle_te; /* same as idle_sp, but for top_env, TODO: remove once stable */
189 JMPENV *top_env; 207 JMPENV *top_env;
190 coro_context cctx; 208 coro_context cctx;
191 209
210 U32 gen;
192#if CORO_USE_VALGRIND 211#if CORO_USE_VALGRIND
193 int valgrind_id; 212 int valgrind_id;
194#endif 213#endif
195 unsigned char flags; 214 unsigned char flags;
196} coro_cctx; 215} coro_cctx;
201 CF_NEW = 0x0004, /* has never been switched to */ 220 CF_NEW = 0x0004, /* has never been switched to */
202 CF_DESTROYED = 0x0008, /* coroutine data has been freed */ 221 CF_DESTROYED = 0x0008, /* coroutine data has been freed */
203}; 222};
204 223
205/* the structure where most of the perl state is stored, overlaid on the cxstack */ 224/* the structure where most of the perl state is stored, overlaid on the cxstack */
206typedef struct { 225typedef struct
226{
207 SV *defsv; 227 SV *defsv;
208 AV *defav; 228 AV *defav;
209 SV *errsv; 229 SV *errsv;
210 SV *irsgv; 230 SV *irsgv;
211#define VAR(name,type) type name; 231#define VAR(name,type) type name;
215 235
216#define SLOT_COUNT ((sizeof (perl_slots) + sizeof (PERL_CONTEXT) - 1) / sizeof (PERL_CONTEXT)) 236#define SLOT_COUNT ((sizeof (perl_slots) + sizeof (PERL_CONTEXT) - 1) / sizeof (PERL_CONTEXT))
217 237
218/* this is a structure representing a perl-level coroutine */ 238/* this is a structure representing a perl-level coroutine */
219struct coro { 239struct coro {
220 /* the c coroutine allocated to this perl coroutine, if any */ 240 /* the C coroutine allocated to this perl coroutine, if any */
221 coro_cctx *cctx; 241 coro_cctx *cctx;
222 242
223 /* process data */ 243 /* state data */
244 struct CoroSLF slf_frame; /* saved slf frame */
224 AV *mainstack; 245 AV *mainstack;
225 perl_slots *slot; /* basically the saved sp */ 246 perl_slots *slot; /* basically the saved sp */
226 247
227 AV *args; /* data associated with this coroutine (initial args) */ 248 AV *args; /* data associated with this coroutine (initial args) */
228 int refcnt; /* coroutines are refcounted, yes */ 249 int refcnt; /* coroutines are refcounted, yes */
229 int flags; /* CF_ flags */ 250 int flags; /* CF_ flags */
230 HV *hv; /* the perl hash associated with this coro, if any */ 251 HV *hv; /* the perl hash associated with this coro, if any */
252 void (*on_destroy)(pTHX_ struct coro *coro);
231 253
232 /* statistics */ 254 /* statistics */
233 int usecount; /* number of transfers to this coro */ 255 int usecount; /* number of transfers to this coro */
234 256
235 /* coro process data */ 257 /* coro process data */
243 struct coro *next, *prev; 265 struct coro *next, *prev;
244}; 266};
245 267
246typedef struct coro *Coro__State; 268typedef struct coro *Coro__State;
247typedef struct coro *Coro__State_or_hashref; 269typedef struct coro *Coro__State_or_hashref;
270
271/* the following variables are effectively part of the perl context */
272/* and get copied between struct coro and these variables */
273/* the mainr easonw e don't support windows process emulation */
274static struct CoroSLF slf_frame; /* the current slf frame */
275static SV *coro_throw;
248 276
249/** Coro ********************************************************************/ 277/** Coro ********************************************************************/
250 278
251#define PRIO_MAX 3 279#define PRIO_MAX 3
252#define PRIO_HIGH 1 280#define PRIO_HIGH 1
255#define PRIO_IDLE -3 283#define PRIO_IDLE -3
256#define PRIO_MIN -4 284#define PRIO_MIN -4
257 285
258/* for Coro.pm */ 286/* for Coro.pm */
259static SV *coro_current; 287static SV *coro_current;
288static SV *coro_readyhook;
260static AV *coro_ready [PRIO_MAX-PRIO_MIN+1]; 289static AV *coro_ready [PRIO_MAX - PRIO_MIN + 1];
261static int coro_nready;
262static struct coro *coro_first; 290static struct coro *coro_first;
291#define coro_nready coroapi.nready
263 292
264/** lowlevel stuff **********************************************************/ 293/** lowlevel stuff **********************************************************/
265 294
266static SV * 295static SV *
267coro_get_sv (const char *name, int create) 296coro_get_sv (pTHX_ const char *name, int create)
268{ 297{
269#if PERL_VERSION_ATLEAST (5,9,0) 298#if PERL_VERSION_ATLEAST (5,10,0)
270 /* silence stupid and wrong 5.10 warning that I am unable to switch off */ 299 /* silence stupid and wrong 5.10 warning that I am unable to switch off */
271 get_sv (name, create); 300 get_sv (name, create);
272#endif 301#endif
273 return get_sv (name, create); 302 return get_sv (name, create);
274} 303}
275 304
276static AV * 305static AV *
277coro_get_av (const char *name, int create) 306coro_get_av (pTHX_ const char *name, int create)
278{ 307{
279#if PERL_VERSION_ATLEAST (5,9,0) 308#if PERL_VERSION_ATLEAST (5,10,0)
280 /* silence stupid and wrong 5.10 warning that I am unable to switch off */ 309 /* silence stupid and wrong 5.10 warning that I am unable to switch off */
281 get_av (name, create); 310 get_av (name, create);
282#endif 311#endif
283 return get_av (name, create); 312 return get_av (name, create);
284} 313}
285 314
286static HV * 315static HV *
287coro_get_hv (const char *name, int create) 316coro_get_hv (pTHX_ const char *name, int create)
288{ 317{
289#if PERL_VERSION_ATLEAST (5,9,0) 318#if PERL_VERSION_ATLEAST (5,10,0)
290 /* silence stupid and wrong 5.10 warning that I am unable to switch off */ 319 /* silence stupid and wrong 5.10 warning that I am unable to switch off */
291 get_hv (name, create); 320 get_hv (name, create);
292#endif 321#endif
293 return get_hv (name, create); 322 return get_hv (name, create);
294} 323}
299 AV *padlist = CvPADLIST (cv); 328 AV *padlist = CvPADLIST (cv);
300 AV *newpadlist, *newpad; 329 AV *newpadlist, *newpad;
301 330
302 newpadlist = newAV (); 331 newpadlist = newAV ();
303 AvREAL_off (newpadlist); 332 AvREAL_off (newpadlist);
304#if PERL_VERSION_ATLEAST (5,9,0) 333#if PERL_VERSION_ATLEAST (5,10,0)
305 Perl_pad_push (aTHX_ padlist, AvFILLp (padlist) + 1); 334 Perl_pad_push (aTHX_ padlist, AvFILLp (padlist) + 1);
306#else 335#else
307 Perl_pad_push (aTHX_ padlist, AvFILLp (padlist) + 1, 1); 336 Perl_pad_push (aTHX_ padlist, AvFILLp (padlist) + 1, 1);
308#endif 337#endif
309 newpad = (AV *)AvARRAY (padlist)[AvFILLp (padlist)]; 338 newpad = (AV *)AvARRAY (padlist)[AvFILLp (padlist)];
310 --AvFILLp (padlist); 339 --AvFILLp (padlist);
311 340
312 av_store (newpadlist, 0, SvREFCNT_inc (*av_fetch (padlist, 0, FALSE))); 341 av_store (newpadlist, 0, SvREFCNT_inc_NN (*av_fetch (padlist, 0, FALSE)));
313 av_store (newpadlist, 1, (SV *)newpad); 342 av_store (newpadlist, 1, (SV *)newpad);
314 343
315 return newpadlist; 344 return newpadlist;
316} 345}
317 346
347 376
348 /* casting is fun. */ 377 /* casting is fun. */
349 while (&PL_sv_undef != (SV *)(padlist = (AV *)av_pop (av))) 378 while (&PL_sv_undef != (SV *)(padlist = (AV *)av_pop (av)))
350 free_padlist (aTHX_ padlist); 379 free_padlist (aTHX_ padlist);
351 380
352 SvREFCNT_dec (av); 381 SvREFCNT_dec (av); /* sv_magicext increased the refcount */
353 382
354 return 0; 383 return 0;
355} 384}
356 385
386#define CORO_MAGIC_type_cv 26
357#define PERL_MAGIC_coro PERL_MAGIC_ext 387#define CORO_MAGIC_type_state PERL_MAGIC_ext
358 388
359static MGVTBL vtbl_coro = {0, 0, 0, 0, coro_cv_free}; 389static MGVTBL coro_cv_vtbl = {
390 0, 0, 0, 0,
391 coro_cv_free
392};
360 393
361#define CORO_MAGIC(cv) \ 394#define CORO_MAGIC_NN(sv, type) \
395 (expect_true (SvMAGIC (sv)->mg_type == type) \
362 SvMAGIC (cv) \ 396 ? SvMAGIC (sv) \
363 ? SvMAGIC (cv)->mg_type == PERL_MAGIC_coro \ 397 : mg_find (sv, type))
364 ? SvMAGIC (cv) \ 398
365 : mg_find ((SV *)cv, PERL_MAGIC_coro) \ 399#define CORO_MAGIC(sv, type) \
400 (expect_true (SvMAGIC (sv)) \
401 ? CORO_MAGIC_NN (sv, type) \
366 : 0 402 : 0)
367 403
368static struct coro * 404#define CORO_MAGIC_cv(cv) CORO_MAGIC (((SV *)(cv)), CORO_MAGIC_type_cv)
405#define CORO_MAGIC_state(sv) CORO_MAGIC_NN (((SV *)(sv)), CORO_MAGIC_type_state)
406
407INLINE struct coro *
369SvSTATE_ (pTHX_ SV *coro) 408SvSTATE_ (pTHX_ SV *coro)
370{ 409{
371 HV *stash; 410 HV *stash;
372 MAGIC *mg; 411 MAGIC *mg;
373 412
383 /* very slow, but rare, check */ 422 /* very slow, but rare, check */
384 if (!sv_derived_from (sv_2mortal (newRV_inc (coro)), "Coro::State")) 423 if (!sv_derived_from (sv_2mortal (newRV_inc (coro)), "Coro::State"))
385 croak ("Coro::State object required"); 424 croak ("Coro::State object required");
386 } 425 }
387 426
388 mg = CORO_MAGIC (coro); 427 mg = CORO_MAGIC_state (coro);
389 return (struct coro *)mg->mg_ptr; 428 return (struct coro *)mg->mg_ptr;
390} 429}
391 430
392#define SvSTATE(sv) SvSTATE_ (aTHX_ (sv)) 431#define SvSTATE(sv) SvSTATE_ (aTHX_ (sv))
393 432
433/* faster than SvSTATE, but expects a coroutine hv */
434#define SvSTATE_hv(hv) ((struct coro *)CORO_MAGIC_NN ((SV *)hv, CORO_MAGIC_type_state)->mg_ptr)
435#define SvSTATE_current SvSTATE_hv (SvRV (coro_current))
436
394/* the next two functions merely cache the padlists */ 437/* the next two functions merely cache the padlists */
395static void 438static void
396get_padlist (pTHX_ CV *cv) 439get_padlist (pTHX_ CV *cv)
397{ 440{
398 MAGIC *mg = CORO_MAGIC (cv); 441 MAGIC *mg = CORO_MAGIC_cv (cv);
399 AV *av; 442 AV *av;
400 443
401 if (expect_true (mg && AvFILLp ((av = (AV *)mg->mg_obj)) >= 0)) 444 if (expect_true (mg && AvFILLp ((av = (AV *)mg->mg_obj)) >= 0))
402 CvPADLIST (cv) = (AV *)AvARRAY (av)[AvFILLp (av)--]; 445 CvPADLIST (cv) = (AV *)AvARRAY (av)[AvFILLp (av)--];
403 else 446 else
404 { 447 {
405#if CORO_PREFER_PERL_FUNCTIONS 448#if CORO_PREFER_PERL_FUNCTIONS
406 /* this is probably cleaner, but also slower? */ 449 /* this is probably cleaner? but also slower! */
450 /* in practise, it seems to be less stable */
407 CV *cp = Perl_cv_clone (cv); 451 CV *cp = Perl_cv_clone (cv);
408 CvPADLIST (cv) = CvPADLIST (cp); 452 CvPADLIST (cv) = CvPADLIST (cp);
409 CvPADLIST (cp) = 0; 453 CvPADLIST (cp) = 0;
410 SvREFCNT_dec (cp); 454 SvREFCNT_dec (cp);
411#else 455#else
415} 459}
416 460
417static void 461static void
418put_padlist (pTHX_ CV *cv) 462put_padlist (pTHX_ CV *cv)
419{ 463{
420 MAGIC *mg = CORO_MAGIC (cv); 464 MAGIC *mg = CORO_MAGIC_cv (cv);
421 AV *av; 465 AV *av;
422 466
423 if (expect_false (!mg)) 467 if (expect_false (!mg))
424 { 468 mg = sv_magicext ((SV *)cv, (SV *)newAV (), CORO_MAGIC_type_cv, &coro_cv_vtbl, 0, 0);
425 sv_magic ((SV *)cv, 0, PERL_MAGIC_coro, 0, 0);
426 mg = mg_find ((SV *)cv, PERL_MAGIC_coro);
427 mg->mg_virtual = &vtbl_coro;
428 mg->mg_obj = (SV *)newAV ();
429 }
430 469
431 av = (AV *)mg->mg_obj; 470 av = (AV *)mg->mg_obj;
432 471
433 if (expect_false (AvFILLp (av) >= AvMAX (av))) 472 if (expect_false (AvFILLp (av) >= AvMAX (av)))
434 av_extend (av, AvMAX (av) + 1); 473 av_extend (av, AvMAX (av) + 1);
452 GvSV (irsgv) = slot->irsgv; 491 GvSV (irsgv) = slot->irsgv;
453 492
454 #define VAR(name,type) PL_ ## name = slot->name; 493 #define VAR(name,type) PL_ ## name = slot->name;
455 # include "state.h" 494 # include "state.h"
456 #undef VAR 495 #undef VAR
457
458 /*hv_store (hv_sig, strpair ("__DIE__" ), SvREFCNT_inc (sv_diehook ), 0);*/
459 /*hv_store (hv_sig, strpair ("__WARN__"), SvREFCNT_inc (sv_warnhook), 0);*/
460 496
461 { 497 {
462 dSP; 498 dSP;
463 499
464 CV *cv; 500 CV *cv;
471 CvPADLIST (cv) = (AV *)POPs; 507 CvPADLIST (cv) = (AV *)POPs;
472 } 508 }
473 509
474 PUTBACK; 510 PUTBACK;
475 } 511 }
512
513 slf_frame = c->slf_frame;
514 coro_throw = c->throw;
476} 515}
477 516
478static void 517static void
479save_perl (pTHX_ Coro__State c) 518save_perl (pTHX_ Coro__State c)
480{ 519{
520 c->throw = coro_throw;
521 c->slf_frame = slf_frame;
522
481 { 523 {
482 dSP; 524 dSP;
483 I32 cxix = cxstack_ix; 525 I32 cxix = cxstack_ix;
484 PERL_CONTEXT *ccstk = cxstack; 526 PERL_CONTEXT *ccstk = cxstack;
485 PERL_SI *top_si = PL_curstackinfo; 527 PERL_SI *top_si = PL_curstackinfo;
503 545
504 if (expect_true (CvDEPTH (cv))) 546 if (expect_true (CvDEPTH (cv)))
505 { 547 {
506 EXTEND (SP, 3); 548 EXTEND (SP, 3);
507 PUSHs ((SV *)CvPADLIST (cv)); 549 PUSHs ((SV *)CvPADLIST (cv));
508 PUSHs (INT2PTR (SV *, CvDEPTH (cv))); 550 PUSHs (INT2PTR (SV *, (IV)CvDEPTH (cv)));
509 PUSHs ((SV *)cv); 551 PUSHs ((SV *)cv);
510 552
511 CvDEPTH (cv) = 0; 553 CvDEPTH (cv) = 0;
512 get_padlist (aTHX_ cv); 554 get_padlist (aTHX_ cv);
513 } 555 }
552 #undef VAR 594 #undef VAR
553 } 595 }
554} 596}
555 597
556/* 598/*
557 * allocate various perl stacks. This is an exact copy 599 * allocate various perl stacks. This is almost an exact copy
558 * of perl.c:init_stacks, except that it uses less memory 600 * of perl.c:init_stacks, except that it uses less memory
559 * on the (sometimes correct) assumption that coroutines do 601 * on the (sometimes correct) assumption that coroutines do
560 * not usually need a lot of stackspace. 602 * not usually need a lot of stackspace.
561 */ 603 */
562#if CORO_PREFER_PERL_FUNCTIONS 604#if CORO_PREFER_PERL_FUNCTIONS
593 635
594 New(54,PL_savestack,24,ANY); 636 New(54,PL_savestack,24,ANY);
595 PL_savestack_ix = 0; 637 PL_savestack_ix = 0;
596 PL_savestack_max = 24; 638 PL_savestack_max = 24;
597 639
598#if !PERL_VERSION_ATLEAST (5,9,0) 640#if !PERL_VERSION_ATLEAST (5,10,0)
599 New(54,PL_retstack,4,OP*); 641 New(54,PL_retstack,4,OP*);
600 PL_retstack_ix = 0; 642 PL_retstack_ix = 0;
601 PL_retstack_max = 4; 643 PL_retstack_max = 4;
602#endif 644#endif
603} 645}
605 647
606/* 648/*
607 * destroy the stacks, the callchain etc... 649 * destroy the stacks, the callchain etc...
608 */ 650 */
609static void 651static void
610coro_destroy_stacks (pTHX) 652coro_destruct_stacks (pTHX)
611{ 653{
612 while (PL_curstackinfo->si_next) 654 while (PL_curstackinfo->si_next)
613 PL_curstackinfo = PL_curstackinfo->si_next; 655 PL_curstackinfo = PL_curstackinfo->si_next;
614 656
615 while (PL_curstackinfo) 657 while (PL_curstackinfo)
626 668
627 Safefree (PL_tmps_stack); 669 Safefree (PL_tmps_stack);
628 Safefree (PL_markstack); 670 Safefree (PL_markstack);
629 Safefree (PL_scopestack); 671 Safefree (PL_scopestack);
630 Safefree (PL_savestack); 672 Safefree (PL_savestack);
631#if !PERL_VERSION_ATLEAST (5,9,0) 673#if !PERL_VERSION_ATLEAST (5,10,0)
632 Safefree (PL_retstack); 674 Safefree (PL_retstack);
633#endif 675#endif
634} 676}
635 677
636static size_t 678static size_t
652 #undef VAR 694 #undef VAR
653 } 695 }
654 else 696 else
655 slot = coro->slot; 697 slot = coro->slot;
656 698
699 if (slot)
700 {
657 rss += sizeof (slot->curstackinfo); 701 rss += sizeof (slot->curstackinfo);
658 rss += (slot->curstackinfo->si_cxmax + 1) * sizeof (PERL_CONTEXT); 702 rss += (slot->curstackinfo->si_cxmax + 1) * sizeof (PERL_CONTEXT);
659 rss += sizeof (SV) + sizeof (struct xpvav) + (1 + AvMAX (slot->curstack)) * sizeof (SV *); 703 rss += sizeof (SV) + sizeof (struct xpvav) + (1 + AvMAX (slot->curstack)) * sizeof (SV *);
660 rss += slot->tmps_max * sizeof (SV *); 704 rss += slot->tmps_max * sizeof (SV *);
661 rss += (slot->markstack_max - slot->markstack_ptr) * sizeof (I32); 705 rss += (slot->markstack_max - slot->markstack_ptr) * sizeof (I32);
662 rss += slot->scopestack_max * sizeof (I32); 706 rss += slot->scopestack_max * sizeof (I32);
663 rss += slot->savestack_max * sizeof (ANY); 707 rss += slot->savestack_max * sizeof (ANY);
664 708
665#if !PERL_VERSION_ATLEAST (5,9,0) 709#if !PERL_VERSION_ATLEAST (5,10,0)
666 rss += slot->retstack_max * sizeof (OP *); 710 rss += slot->retstack_max * sizeof (OP *);
667#endif 711#endif
712 }
668 } 713 }
669 714
670 return rss; 715 return rss;
671} 716}
672 717
673/** coroutine stack handling ************************************************/ 718/** coroutine stack handling ************************************************/
674 719
720static int (*orig_sigelem_get) (pTHX_ SV *sv, MAGIC *mg);
721static int (*orig_sigelem_set) (pTHX_ SV *sv, MAGIC *mg);
722static int (*orig_sigelem_clr) (pTHX_ SV *sv, MAGIC *mg);
723
724/* apparently < 5.8.8 */
725#ifndef MgPV_nolen_const
726#define MgPV_nolen_const(mg) (((((int)(mg)->mg_len)) == HEf_SVKEY) ? \
727 SvPV_nolen((SV*)((mg)->mg_ptr)) : \
728 (const char*)(mg)->mg_ptr)
729#endif
730
731/*
732 * This overrides the default magic get method of %SIG elements.
733 * The original one doesn't provide for reading back of PL_diehook/PL_warnhook
734 * and instead of tryign to save and restore the hash elements, we just provide
735 * readback here.
736 * We only do this when the hook is != 0, as they are often set to 0 temporarily,
737 * not expecting this to actually change the hook. This is a potential problem
738 * when a schedule happens then, but we ignore this.
739 */
675static void 740static int
741coro_sigelem_get (pTHX_ SV *sv, MAGIC *mg)
742{
743 const char *s = MgPV_nolen_const (mg);
744
745 if (*s == '_')
746 {
747 SV **svp = 0;
748
749 if (strEQ (s, "__DIE__" )) svp = &PL_diehook;
750 if (strEQ (s, "__WARN__")) svp = &PL_warnhook;
751
752 if (svp)
753 {
754 sv_setsv (sv, *svp ? *svp : &PL_sv_undef);
755 return 0;
756 }
757 }
758
759 return orig_sigelem_get ? orig_sigelem_get (aTHX_ sv, mg) : 0;
760}
761
762static int
763coro_sigelem_clr (pTHX_ SV *sv, MAGIC *mg)
764{
765 const char *s = MgPV_nolen_const (mg);
766
767 if (*s == '_')
768 {
769 SV **svp = 0;
770
771 if (strEQ (s, "__DIE__" )) svp = &PL_diehook;
772 if (strEQ (s, "__WARN__")) svp = &PL_warnhook;
773
774 if (svp)
775 {
776 SV *old = *svp;
777 *svp = 0;
778 SvREFCNT_dec (old);
779 return 0;
780 }
781 }
782
783 return orig_sigelem_clr ? orig_sigelem_clr (aTHX_ sv, mg) : 0;
784}
785
786static int
787coro_sigelem_set (pTHX_ SV *sv, MAGIC *mg)
788{
789 const char *s = MgPV_nolen_const (mg);
790
791 if (*s == '_')
792 {
793 SV **svp = 0;
794
795 if (strEQ (s, "__DIE__" )) svp = &PL_diehook;
796 if (strEQ (s, "__WARN__")) svp = &PL_warnhook;
797
798 if (svp)
799 {
800 SV *old = *svp;
801 *svp = newSVsv (sv);
802 SvREFCNT_dec (old);
803 return 0;
804 }
805 }
806
807 return orig_sigelem_set ? orig_sigelem_set (aTHX_ sv, mg) : 0;
808}
809
810static void
811prepare_nop (pTHX_ struct coro_transfer_args *ta)
812{
813 /* kind of mega-hacky, but works */
814 ta->next = ta->prev = (struct coro *)ta;
815}
816
817static int
818slf_check_nop (pTHX_ struct CoroSLF *frame)
819{
820 return 0;
821}
822
823static UNOP coro_setup_op;
824
825static void NOINLINE /* noinline to keep it out of the transfer fast path */
676coro_setup (pTHX_ struct coro *coro) 826coro_setup (pTHX_ struct coro *coro)
677{ 827{
678 /* 828 /*
679 * emulate part of the perl startup here. 829 * emulate part of the perl startup here.
680 */ 830 */
687 PL_curpm = 0; 837 PL_curpm = 0;
688 PL_curpad = 0; 838 PL_curpad = 0;
689 PL_localizing = 0; 839 PL_localizing = 0;
690 PL_dirty = 0; 840 PL_dirty = 0;
691 PL_restartop = 0; 841 PL_restartop = 0;
692 PL_diehook = 0; hv_store (hv_sig, strpair ("__DIE__" ), SvREFCNT_inc (sv_diehook ), 0); 842#if PERL_VERSION_ATLEAST (5,10,0)
693 PL_warnhook = 0; hv_store (hv_sig, strpair ("__WARN__"), SvREFCNT_inc (sv_warnhook), 0); 843 PL_parser = 0;
844#endif
845
846 /* recreate the die/warn hooks */
847 PL_diehook = 0; SvSetMagicSV (*hv_fetch (hv_sig, "__DIE__" , sizeof ("__DIE__" ) - 1, 1), rv_diehook );
848 PL_warnhook = 0; SvSetMagicSV (*hv_fetch (hv_sig, "__WARN__", sizeof ("__WARN__") - 1, 1), rv_warnhook);
694 849
695 GvSV (PL_defgv) = newSV (0); 850 GvSV (PL_defgv) = newSV (0);
696 GvAV (PL_defgv) = coro->args; coro->args = 0; 851 GvAV (PL_defgv) = coro->args; coro->args = 0;
697 GvSV (PL_errgv) = newSV (0); 852 GvSV (PL_errgv) = newSV (0);
698 GvSV (irsgv) = newSVpvn ("\n", 1); sv_magic (GvSV (irsgv), (SV *)irsgv, PERL_MAGIC_sv, "/", 0); 853 GvSV (irsgv) = newSVpvn ("\n", 1); sv_magic (GvSV (irsgv), (SV *)irsgv, PERL_MAGIC_sv, "/", 0);
699 PL_rs = newSVsv (GvSV (irsgv)); 854 PL_rs = newSVsv (GvSV (irsgv));
700 PL_defoutgv = (GV *)SvREFCNT_inc (stdoutgv); 855 PL_defoutgv = (GV *)SvREFCNT_inc_NN (stdoutgv);
701 856
702 { 857 {
703 dSP; 858 dSP;
704 LOGOP myop; 859 UNOP myop;
705 860
706 Zero (&myop, 1, LOGOP); 861 Zero (&myop, 1, UNOP);
707 myop.op_next = Nullop; 862 myop.op_next = Nullop;
708 myop.op_flags = OPf_WANT_VOID; 863 myop.op_flags = OPf_WANT_VOID;
709 864
710 PUSHMARK (SP); 865 PUSHMARK (SP);
711 XPUSHs (sv_2mortal (av_shift (GvAV (PL_defgv)))); 866 XPUSHs (sv_2mortal (av_shift (GvAV (PL_defgv))));
714 PL_op = PL_ppaddr[OP_ENTERSUB](aTHX); 869 PL_op = PL_ppaddr[OP_ENTERSUB](aTHX);
715 SPAGAIN; 870 SPAGAIN;
716 } 871 }
717 872
718 /* this newly created coroutine might be run on an existing cctx which most 873 /* this newly created coroutine might be run on an existing cctx which most
719 * likely was suspended in set_stacklevel, called from entersub. 874 * likely was suspended in pp_slf, so we have to emulate entering pp_slf here.
720 * set_stacklevl doesn't do anything on return, but entersub does LEAVE,
721 * so we ENTER here for symmetry
722 */ 875 */
723 ENTER; 876 slf_frame.prepare = prepare_nop; /* provide a nop function for an eventual pp_slf */
724} 877 slf_frame.check = slf_check_nop; /* signal pp_slf to not repeat */
725 878
879 /* and we have to provide the pp_slf op in any case, so pp_slf can skip it */
880 coro_setup_op.op_type = OP_CUSTOM;
881 coro_setup_op.op_ppaddr = pp_slf;
882 coro_setup_op.op_next = PL_op;
883
884 PL_op = (OP *)&coro_setup_op;
885
886 /* copy throw, in case it was set before coro_setup */
887 coro_throw = coro->throw;
888}
889
726static void 890static void
727coro_destroy (pTHX_ struct coro *coro) 891coro_destruct (pTHX_ struct coro *coro)
728{ 892{
729 if (!IN_DESTRUCT) 893 if (!IN_DESTRUCT)
730 { 894 {
731 /* restore all saved variables and stuff */ 895 /* restore all saved variables and stuff */
732 LEAVE_SCOPE (0); 896 LEAVE_SCOPE (0);
752 916
753 SvREFCNT_dec (PL_diehook); 917 SvREFCNT_dec (PL_diehook);
754 SvREFCNT_dec (PL_warnhook); 918 SvREFCNT_dec (PL_warnhook);
755 919
756 SvREFCNT_dec (coro->saved_deffh); 920 SvREFCNT_dec (coro->saved_deffh);
757 SvREFCNT_dec (coro->throw); 921 SvREFCNT_dec (coro_throw);
758 922
759 coro_destroy_stacks (aTHX); 923 coro_destruct_stacks (aTHX);
760} 924}
761 925
762static void 926INLINE void
763free_coro_mortal (pTHX) 927free_coro_mortal (pTHX)
764{ 928{
765 if (expect_true (coro_mortal)) 929 if (expect_true (coro_mortal))
766 { 930 {
767 SvREFCNT_dec (coro_mortal); 931 SvREFCNT_dec (coro_mortal);
772static int 936static int
773runops_trace (pTHX) 937runops_trace (pTHX)
774{ 938{
775 COP *oldcop = 0; 939 COP *oldcop = 0;
776 int oldcxix = -2; 940 int oldcxix = -2;
777 struct coro *coro = SvSTATE (coro_current); /* trace cctx is tied to specific coro */ 941 struct coro *coro = SvSTATE_current; /* trace cctx is tied to specific coro */
778 coro_cctx *cctx = coro->cctx; 942 coro_cctx *cctx = coro->cctx;
779 943
780 while ((PL_op = CALL_FPTR (PL_op->op_ppaddr) (aTHX))) 944 while ((PL_op = CALL_FPTR (PL_op->op_ppaddr) (aTHX)))
781 { 945 {
782 PERL_ASYNC_CHECK (); 946 PERL_ASYNC_CHECK ();
801 : cx->blk_gimme == G_SCALAR ? bot + 1 965 : cx->blk_gimme == G_SCALAR ? bot + 1
802 : bot; 966 : bot;
803 967
804 av_extend (av, top - bot); 968 av_extend (av, top - bot);
805 while (bot < top) 969 while (bot < top)
806 av_push (av, SvREFCNT_inc (*bot++)); 970 av_push (av, SvREFCNT_inc_NN (*bot++));
807 971
808 PL_runops = RUNOPS_DEFAULT; 972 PL_runops = RUNOPS_DEFAULT;
809 ENTER; 973 ENTER;
810 SAVETMPS; 974 SAVETMPS;
811 EXTEND (SP, 3); 975 EXTEND (SP, 3);
812 PUSHMARK (SP); 976 PUSHMARK (SP);
813 PUSHs (&PL_sv_no); 977 PUSHs (&PL_sv_no);
814 PUSHs (fullname); 978 PUSHs (fullname);
815 PUSHs (sv_2mortal (newRV_noinc ((SV *)av))); 979 PUSHs (sv_2mortal (newRV_noinc ((SV *)av)));
816 PUTBACK; 980 PUTBACK;
817 cb = hv_fetch ((HV *)SvRV (coro_current), strpair ("_trace_sub_cb"), 0); 981 cb = hv_fetch ((HV *)SvRV (coro_current), "_trace_sub_cb", sizeof ("_trace_sub_cb") - 1, 0);
818 if (cb) call_sv (*cb, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD); 982 if (cb) call_sv (*cb, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD);
819 SPAGAIN; 983 SPAGAIN;
820 FREETMPS; 984 FREETMPS;
821 LEAVE; 985 LEAVE;
822 PL_runops = runops_trace; 986 PL_runops = runops_trace;
849 SAVETMPS; 1013 SAVETMPS;
850 EXTEND (SP, 3); 1014 EXTEND (SP, 3);
851 PUSHMARK (SP); 1015 PUSHMARK (SP);
852 PUSHs (&PL_sv_yes); 1016 PUSHs (&PL_sv_yes);
853 PUSHs (fullname); 1017 PUSHs (fullname);
854 PUSHs (cx->blk_sub.hasargs ? sv_2mortal (newRV_inc ((SV *)cx->blk_sub.argarray)) : &PL_sv_undef); 1018 PUSHs (CxHASARGS (cx) ? sv_2mortal (newRV_inc ((SV *)cx->blk_sub.argarray)) : &PL_sv_undef);
855 PUTBACK; 1019 PUTBACK;
856 cb = hv_fetch ((HV *)SvRV (coro_current), strpair ("_trace_sub_cb"), 0); 1020 cb = hv_fetch ((HV *)SvRV (coro_current), "_trace_sub_cb", sizeof ("_trace_sub_cb") - 1, 0);
857 if (cb) call_sv (*cb, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD); 1021 if (cb) call_sv (*cb, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD);
858 SPAGAIN; 1022 SPAGAIN;
859 FREETMPS; 1023 FREETMPS;
860 LEAVE; 1024 LEAVE;
861 PL_runops = runops_trace; 1025 PL_runops = runops_trace;
875 PL_runops = RUNOPS_DEFAULT; 1039 PL_runops = RUNOPS_DEFAULT;
876 PUSHMARK (SP); 1040 PUSHMARK (SP);
877 PUSHs (sv_2mortal (newSVpv (OutCopFILE (oldcop), 0))); 1041 PUSHs (sv_2mortal (newSVpv (OutCopFILE (oldcop), 0)));
878 PUSHs (sv_2mortal (newSViv (CopLINE (oldcop)))); 1042 PUSHs (sv_2mortal (newSViv (CopLINE (oldcop))));
879 PUTBACK; 1043 PUTBACK;
880 cb = hv_fetch ((HV *)SvRV (coro_current), strpair ("_trace_line_cb"), 0); 1044 cb = hv_fetch ((HV *)SvRV (coro_current), "_trace_line_cb", sizeof ("_trace_line_cb") - 1, 0);
881 if (cb) call_sv (*cb, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD); 1045 if (cb) call_sv (*cb, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD);
882 SPAGAIN; 1046 SPAGAIN;
883 FREETMPS; 1047 FREETMPS;
884 LEAVE; 1048 LEAVE;
885 PL_runops = runops_trace; 1049 PL_runops = runops_trace;
891 1055
892 TAINT_NOT; 1056 TAINT_NOT;
893 return 0; 1057 return 0;
894} 1058}
895 1059
896/* inject a fake call to Coro::State::_cctx_init into the execution */ 1060static struct coro_cctx *cctx_ssl_cctx;
897/* _cctx_init should be careful, as it could be called at almost any time */ 1061static struct CoroSLF cctx_ssl_frame;
898/* during execution of a perl program */ 1062
1063static void
1064slf_prepare_set_stacklevel (pTHX_ struct coro_transfer_args *ta)
1065{
1066 ta->prev = (struct coro *)cctx_ssl_cctx;
1067 ta->next = 0;
1068}
1069
1070static int
1071slf_check_set_stacklevel (pTHX_ struct CoroSLF *frame)
1072{
1073 *frame = cctx_ssl_frame;
1074
1075 return 1; /* execute the restored frame - there must be one */
1076}
1077
1078/* initialises PL_top_env and injects a pseudo-slf-call to sett he stacklevel */
899static void NOINLINE 1079static void NOINLINE
900cctx_prepare (pTHX_ coro_cctx *cctx) 1080cctx_prepare (pTHX_ coro_cctx *cctx)
901{ 1081{
902 dSP;
903 LOGOP myop;
904
905 PL_top_env = &PL_start_env; 1082 PL_top_env = &PL_start_env;
906 1083
907 if (cctx->flags & CC_TRACE) 1084 if (cctx->flags & CC_TRACE)
908 PL_runops = runops_trace; 1085 PL_runops = runops_trace;
909 1086
910 Zero (&myop, 1, LOGOP); 1087 /* we already must be executing an SLF op, there is no other valid way
911 myop.op_next = PL_op; 1088 * that can lead to creation of a new cctx */
912 myop.op_flags = OPf_WANT_VOID | OPf_STACKED; 1089 assert (("FATAL: can't prepare slf-less cctx in Coro module (please report)",
1090 slf_frame.prepare && PL_op->op_ppaddr == pp_slf));
913 1091
914 PUSHMARK (SP); 1092 cctx_ssl_cctx = cctx;
915 EXTEND (SP, 2); 1093 cctx_ssl_frame = slf_frame;
916 PUSHs (sv_2mortal (newSViv (PTR2IV (cctx)))); 1094
917 PUSHs ((SV *)get_cv ("Coro::State::_cctx_init", FALSE)); 1095 slf_frame.prepare = slf_prepare_set_stacklevel;
918 PUTBACK; 1096 slf_frame.check = slf_check_set_stacklevel;
919 PL_op = (OP *)&myop; 1097}
920 PL_op = PL_ppaddr[OP_ENTERSUB](aTHX); 1098
921 SPAGAIN; 1099/* the tail of transfer: execute stuff we can only do after a transfer */
1100INLINE void
1101transfer_tail (pTHX)
1102{
1103 free_coro_mortal (aTHX);
922} 1104}
923 1105
924/* 1106/*
925 * this is a _very_ stripped down perl interpreter ;) 1107 * this is a _very_ stripped down perl interpreter ;)
926 */ 1108 */
927static void 1109static void
928cctx_run (void *arg) 1110cctx_run (void *arg)
929{ 1111{
1112#ifdef USE_ITHREADS
1113# if CORO_PTHREAD
1114 PERL_SET_CONTEXT (coro_thx);
1115# endif
1116#endif
1117 {
930 dTHX; 1118 dTHX;
931 1119
932 /* cctx_run is the alternative tail of transfer(), so unlock here. */ 1120 /* normally we would need to skip the entersub here */
933 UNLOCK; 1121 /* not doing so will re-execute it, which is exactly what we want */
934
935 /* we now skip the entersub that lead to transfer() */
936 PL_op = PL_op->op_next; 1122 /* PL_nop = PL_nop->op_next */
937 1123
938 /* inject a fake subroutine call to cctx_init */ 1124 /* inject a fake subroutine call to cctx_init */
939 cctx_prepare (aTHX_ (coro_cctx *)arg); 1125 cctx_prepare (aTHX_ (coro_cctx *)arg);
940 1126
1127 /* cctx_run is the alternative tail of transfer() */
1128 transfer_tail (aTHX);
1129
941 /* somebody or something will hit me for both perl_run and PL_restartop */ 1130 /* somebody or something will hit me for both perl_run and PL_restartop */
942 PL_restartop = PL_op; 1131 PL_restartop = PL_op;
943 perl_run (PL_curinterp); 1132 perl_run (PL_curinterp);
944 1133
945 /* 1134 /*
946 * If perl-run returns we assume exit() was being called or the coro 1135 * If perl-run returns we assume exit() was being called or the coro
947 * fell off the end, which seems to be the only valid (non-bug) 1136 * fell off the end, which seems to be the only valid (non-bug)
948 * reason for perl_run to return. We try to exit by jumping to the 1137 * reason for perl_run to return. We try to exit by jumping to the
949 * bootstrap-time "top" top_env, as we cannot restore the "main" 1138 * bootstrap-time "top" top_env, as we cannot restore the "main"
950 * coroutine as Coro has no such concept 1139 * coroutine as Coro has no such concept
951 */ 1140 */
952 PL_top_env = main_top_env; 1141 PL_top_env = main_top_env;
953 JMPENV_JUMP (2); /* I do not feel well about the hardcoded 2 at all */ 1142 JMPENV_JUMP (2); /* I do not feel well about the hardcoded 2 at all */
1143 }
954} 1144}
955 1145
956static coro_cctx * 1146static coro_cctx *
957cctx_new () 1147cctx_new ()
958{ 1148{
959 coro_cctx *cctx; 1149 coro_cctx *cctx;
1150
1151 ++cctx_count;
1152 New (0, cctx, 1, coro_cctx);
1153
1154 cctx->gen = cctx_gen;
1155 cctx->flags = 0;
1156 cctx->idle_sp = 0; /* can be accessed by transfer between cctx_run and set_stacklevel, on throw */
1157
1158 return cctx;
1159}
1160
1161/* create a new cctx only suitable as source */
1162static coro_cctx *
1163cctx_new_empty ()
1164{
1165 coro_cctx *cctx = cctx_new ();
1166
1167 cctx->sptr = 0;
1168 coro_create (&cctx->cctx, 0, 0, 0, 0);
1169
1170 return cctx;
1171}
1172
1173/* create a new cctx suitable as destination/running a perl interpreter */
1174static coro_cctx *
1175cctx_new_run ()
1176{
1177 coro_cctx *cctx = cctx_new ();
960 void *stack_start; 1178 void *stack_start;
961 size_t stack_size; 1179 size_t stack_size;
962 1180
963 ++cctx_count;
964
965 Newz (0, cctx, 1, coro_cctx);
966
967#if HAVE_MMAP 1181#if HAVE_MMAP
968 cctx->ssize = ((coro_stacksize * sizeof (long) + PAGESIZE - 1) / PAGESIZE + CORO_STACKGUARD) * PAGESIZE; 1182 cctx->ssize = ((cctx_stacksize * sizeof (long) + PAGESIZE - 1) / PAGESIZE + CORO_STACKGUARD) * PAGESIZE;
969 /* mmap supposedly does allocate-on-write for us */ 1183 /* mmap supposedly does allocate-on-write for us */
970 cctx->sptr = mmap (0, cctx->ssize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 0, 0); 1184 cctx->sptr = mmap (0, cctx->ssize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);
971 1185
972 if (cctx->sptr != (void *)-1) 1186 if (cctx->sptr != (void *)-1)
973 { 1187 {
974# if CORO_STACKGUARD 1188 #if CORO_STACKGUARD
975 mprotect (cctx->sptr, CORO_STACKGUARD * PAGESIZE, PROT_NONE); 1189 mprotect (cctx->sptr, CORO_STACKGUARD * PAGESIZE, PROT_NONE);
976# endif 1190 #endif
977 stack_start = CORO_STACKGUARD * PAGESIZE + (char *)cctx->sptr; 1191 stack_start = (char *)cctx->sptr + CORO_STACKGUARD * PAGESIZE;
978 stack_size = cctx->ssize - CORO_STACKGUARD * PAGESIZE; 1192 stack_size = cctx->ssize - CORO_STACKGUARD * PAGESIZE;
979 cctx->flags |= CC_MAPPED; 1193 cctx->flags |= CC_MAPPED;
980 } 1194 }
981 else 1195 else
982#endif 1196#endif
983 { 1197 {
984 cctx->ssize = coro_stacksize * (long)sizeof (long); 1198 cctx->ssize = cctx_stacksize * (long)sizeof (long);
985 New (0, cctx->sptr, coro_stacksize, long); 1199 New (0, cctx->sptr, cctx_stacksize, long);
986 1200
987 if (!cctx->sptr) 1201 if (!cctx->sptr)
988 { 1202 {
989 perror ("FATAL: unable to allocate stack for coroutine"); 1203 perror ("FATAL: unable to allocate stack for coroutine, exiting.");
990 _exit (EXIT_FAILURE); 1204 _exit (EXIT_FAILURE);
991 } 1205 }
992 1206
993 stack_start = cctx->sptr; 1207 stack_start = cctx->sptr;
994 stack_size = cctx->ssize; 1208 stack_size = cctx->ssize;
995 } 1209 }
996 1210
997 REGISTER_STACK (cctx, (char *)stack_start, (char *)stack_start + stack_size); 1211 #if CORO_USE_VALGRIND
1212 cctx->valgrind_id = VALGRIND_STACK_REGISTER ((char *)stack_start, (char *)stack_start + stack_size);
1213 #endif
1214
998 coro_create (&cctx->cctx, cctx_run, (void *)cctx, stack_start, stack_size); 1215 coro_create (&cctx->cctx, cctx_run, (void *)cctx, stack_start, stack_size);
999 1216
1000 return cctx; 1217 return cctx;
1001} 1218}
1002 1219
1005{ 1222{
1006 if (!cctx) 1223 if (!cctx)
1007 return; 1224 return;
1008 1225
1009 --cctx_count; 1226 --cctx_count;
1227 coro_destroy (&cctx->cctx);
1010 1228
1229 /* coro_transfer creates new, empty cctx's */
1230 if (cctx->sptr)
1231 {
1011#if CORO_USE_VALGRIND 1232 #if CORO_USE_VALGRIND
1012 VALGRIND_STACK_DEREGISTER (cctx->valgrind_id); 1233 VALGRIND_STACK_DEREGISTER (cctx->valgrind_id);
1013#endif 1234 #endif
1014 1235
1015#if HAVE_MMAP 1236#if HAVE_MMAP
1016 if (cctx->flags & CC_MAPPED) 1237 if (cctx->flags & CC_MAPPED)
1017 munmap (cctx->sptr, cctx->ssize); 1238 munmap (cctx->sptr, cctx->ssize);
1018 else 1239 else
1019#endif 1240#endif
1020 Safefree (cctx->sptr); 1241 Safefree (cctx->sptr);
1242 }
1021 1243
1022 Safefree (cctx); 1244 Safefree (cctx);
1023} 1245}
1024 1246
1025/* wether this cctx should be destructed */ 1247/* wether this cctx should be destructed */
1026#define CCTX_EXPIRED(cctx) ((cctx)->ssize < coro_stacksize || ((cctx)->flags & CC_NOREUSE)) 1248#define CCTX_EXPIRED(cctx) ((cctx)->gen != cctx_gen || ((cctx)->flags & CC_NOREUSE))
1027 1249
1028static coro_cctx * 1250static coro_cctx *
1029cctx_get (pTHX) 1251cctx_get (pTHX)
1030{ 1252{
1031 while (expect_true (cctx_first)) 1253 while (expect_true (cctx_first))
1038 return cctx; 1260 return cctx;
1039 1261
1040 cctx_destroy (cctx); 1262 cctx_destroy (cctx);
1041 } 1263 }
1042 1264
1043 return cctx_new (); 1265 return cctx_new_run ();
1044} 1266}
1045 1267
1046static void 1268static void
1047cctx_put (coro_cctx *cctx) 1269cctx_put (coro_cctx *cctx)
1048{ 1270{
1271 assert (("FATAL: cctx_put called on non-initialised cctx in Coro (please report)", cctx->sptr));
1272
1049 /* free another cctx if overlimit */ 1273 /* free another cctx if overlimit */
1050 if (expect_false (cctx_idle >= MAX_IDLE_CCTX)) 1274 if (expect_false (cctx_idle >= cctx_max_idle))
1051 { 1275 {
1052 coro_cctx *first = cctx_first; 1276 coro_cctx *first = cctx_first;
1053 cctx_first = first->next; 1277 cctx_first = first->next;
1054 --cctx_idle; 1278 --cctx_idle;
1055 1279
1064/** coroutine switching *****************************************************/ 1288/** coroutine switching *****************************************************/
1065 1289
1066static void 1290static void
1067transfer_check (pTHX_ struct coro *prev, struct coro *next) 1291transfer_check (pTHX_ struct coro *prev, struct coro *next)
1068{ 1292{
1293 /* TODO: throwing up here is considered harmful */
1294
1069 if (expect_true (prev != next)) 1295 if (expect_true (prev != next))
1070 { 1296 {
1071 if (expect_false (!(prev->flags & (CF_RUNNING | CF_NEW)))) 1297 if (expect_false (!(prev->flags & (CF_RUNNING | CF_NEW))))
1072 croak ("Coro::State::transfer called with non-running/new prev Coro::State, but can only transfer from running or new states"); 1298 croak ("Coro::State::transfer called with non-running/new prev Coro::State, but can only transfer from running or new states,");
1073 1299
1074 if (expect_false (next->flags & CF_RUNNING)) 1300 if (expect_false (next->flags & CF_RUNNING))
1075 croak ("Coro::State::transfer called with running next Coro::State, but can only transfer to inactive states"); 1301 croak ("Coro::State::transfer called with running next Coro::State, but can only transfer to inactive states,");
1076 1302
1077 if (expect_false (next->flags & CF_DESTROYED)) 1303 if (expect_false (next->flags & CF_DESTROYED))
1078 croak ("Coro::State::transfer called with destroyed next Coro::State, but can only transfer to inactive states"); 1304 croak ("Coro::State::transfer called with destroyed next Coro::State, but can only transfer to inactive states,");
1079 1305
1080 if (
1081#if PERL_VERSION_ATLEAST (5,9,0) 1306#if !PERL_VERSION_ATLEAST (5,10,0)
1082 expect_false (PL_parser)
1083#else
1084 expect_false (PL_lex_state != LEX_NOTPARSING) 1307 if (expect_false (PL_lex_state != LEX_NOTPARSING))
1085#endif
1086 )
1087 croak ("Coro::State::transfer called while parsing, but this is not supported"); 1308 croak ("Coro::State::transfer called while parsing, but this is not supported in your perl version,");
1309#endif
1088 } 1310 }
1089} 1311}
1090 1312
1091/* always use the TRANSFER macro */ 1313/* always use the TRANSFER macro */
1092static void NOINLINE 1314static void NOINLINE /* noinline so we have a fixed stackframe */
1093transfer (pTHX_ struct coro *prev, struct coro *next) 1315transfer (pTHX_ struct coro *prev, struct coro *next, int force_cctx)
1094{ 1316{
1095 dSTACKLEVEL; 1317 dSTACKLEVEL;
1096 1318
1097 /* sometimes transfer is only called to set idle_sp */ 1319 /* sometimes transfer is only called to set idle_sp */
1098 if (expect_false (!next)) 1320 if (expect_false (!next))
1099 { 1321 {
1100 ((coro_cctx *)prev)->idle_sp = STACKLEVEL; 1322 ((coro_cctx *)prev)->idle_sp = (void *)stacklevel;
1101 assert (((coro_cctx *)prev)->idle_te = PL_top_env); /* just for the side-effect when asserts are enabled */ 1323 assert (((coro_cctx *)prev)->idle_te = PL_top_env); /* just for the side-effect when asserts are enabled */
1102 } 1324 }
1103 else if (expect_true (prev != next)) 1325 else if (expect_true (prev != next))
1104 { 1326 {
1105 coro_cctx *prev__cctx; 1327 coro_cctx *prev__cctx;
1106 1328
1107 if (expect_false (prev->flags & CF_NEW)) 1329 if (expect_false (prev->flags & CF_NEW))
1108 { 1330 {
1109 /* create a new empty context */ 1331 /* create a new empty/source context */
1110 Newz (0, prev->cctx, 1, coro_cctx); 1332 prev->cctx = cctx_new_empty ();
1111 prev->flags &= ~CF_NEW; 1333 prev->flags &= ~CF_NEW;
1112 prev->flags |= CF_RUNNING; 1334 prev->flags |= CF_RUNNING;
1113 } 1335 }
1114 1336
1115 prev->flags &= ~CF_RUNNING; 1337 prev->flags &= ~CF_RUNNING;
1116 next->flags |= CF_RUNNING; 1338 next->flags |= CF_RUNNING;
1117 1339
1118 LOCK; 1340 /* first get rid of the old state */
1341 save_perl (aTHX_ prev);
1119 1342
1120 if (expect_false (next->flags & CF_NEW)) 1343 if (expect_false (next->flags & CF_NEW))
1121 { 1344 {
1122 /* need to start coroutine */ 1345 /* need to start coroutine */
1123 next->flags &= ~CF_NEW; 1346 next->flags &= ~CF_NEW;
1124 /* first get rid of the old state */
1125 save_perl (aTHX_ prev);
1126 /* setup coroutine call */ 1347 /* setup coroutine call */
1127 coro_setup (aTHX_ next); 1348 coro_setup (aTHX_ next);
1128 } 1349 }
1129 else 1350 else
1351 load_perl (aTHX_ next);
1352
1353 prev__cctx = prev->cctx;
1354
1355 /* possibly untie and reuse the cctx */
1356 if (expect_true (
1357 prev__cctx->idle_sp == (void *)stacklevel
1358 && !(prev__cctx->flags & CC_TRACE)
1359 && !force_cctx
1360 ))
1130 { 1361 {
1131 /* coroutine already started */
1132 save_perl (aTHX_ prev);
1133 load_perl (aTHX_ next);
1134 }
1135
1136 prev__cctx = prev->cctx;
1137
1138 /* possibly "free" the cctx */
1139 if (expect_true (prev__cctx->idle_sp == STACKLEVEL && !(prev__cctx->flags & CC_TRACE)))
1140 {
1141 /* I assume that STACKLEVEL is a stronger indicator than PL_top_env changes */ 1362 /* I assume that stacklevel is a stronger indicator than PL_top_env changes */
1142 assert (("ERROR: current top_env must equal previous top_env", PL_top_env == prev__cctx->idle_te)); 1363 assert (("FATAL: current top_env must equal previous top_env in Coro (please report)", PL_top_env == prev__cctx->idle_te));
1143 1364
1144 prev->cctx = 0; 1365 prev->cctx = 0;
1145 1366
1146 /* if the cctx is about to be destroyed we need to make sure we won't see it in cctx_get */ 1367 /* if the cctx is about to be destroyed we need to make sure we won't see it in cctx_get */
1147 /* without this the next cctx_get might destroy the prev__cctx while still in use */ 1368 /* without this the next cctx_get might destroy the prev__cctx while still in use */
1162 prev__cctx->top_env = PL_top_env; 1383 prev__cctx->top_env = PL_top_env;
1163 PL_top_env = next->cctx->top_env; 1384 PL_top_env = next->cctx->top_env;
1164 coro_transfer (&prev__cctx->cctx, &next->cctx->cctx); 1385 coro_transfer (&prev__cctx->cctx, &next->cctx->cctx);
1165 } 1386 }
1166 1387
1167 free_coro_mortal (aTHX); 1388 transfer_tail (aTHX);
1168 UNLOCK;
1169
1170 if (expect_false (prev->throw || next->throw))
1171 {
1172 struct coro *coro = SvSTATE (coro_current);
1173
1174 if (coro->throw)
1175 {
1176 SV *exception = coro->throw;
1177 coro->throw = 0;
1178 sv_setsv (ERRSV, exception);
1179 croak (0);
1180 }
1181 }
1182 } 1389 }
1183} 1390}
1184 1391
1185struct transfer_args
1186{
1187 struct coro *prev, *next;
1188};
1189
1190#define TRANSFER(ta) transfer (aTHX_ (ta).prev, (ta).next) 1392#define TRANSFER(ta, force_cctx) transfer (aTHX_ (ta).prev, (ta).next, (force_cctx))
1191#define TRANSFER_CHECK(ta) transfer_check (aTHX_ (ta).prev, (ta).next) 1393#define TRANSFER_CHECK(ta) transfer_check (aTHX_ (ta).prev, (ta).next)
1192 1394
1193/** high level stuff ********************************************************/ 1395/** high level stuff ********************************************************/
1194 1396
1195static int 1397static int
1196coro_state_destroy (pTHX_ struct coro *coro) 1398coro_state_destroy (pTHX_ struct coro *coro)
1197{ 1399{
1198 if (coro->flags & CF_DESTROYED) 1400 if (coro->flags & CF_DESTROYED)
1199 return 0; 1401 return 0;
1402
1403 if (coro->on_destroy)
1404 coro->on_destroy (aTHX_ coro);
1200 1405
1201 coro->flags |= CF_DESTROYED; 1406 coro->flags |= CF_DESTROYED;
1202 1407
1203 if (coro->flags & CF_READY) 1408 if (coro->flags & CF_READY)
1204 { 1409 {
1205 /* reduce nready, as destroying a ready coro effectively unreadies it */ 1410 /* reduce nready, as destroying a ready coro effectively unreadies it */
1206 /* alternative: look through all ready queues and remove the coro */ 1411 /* alternative: look through all ready queues and remove the coro */
1207 LOCK;
1208 --coro_nready; 1412 --coro_nready;
1209 UNLOCK;
1210 } 1413 }
1211 else 1414 else
1212 coro->flags |= CF_READY; /* make sure it is NOT put into the readyqueue */ 1415 coro->flags |= CF_READY; /* make sure it is NOT put into the readyqueue */
1213 1416
1214 if (coro->mainstack && coro->mainstack != main_mainstack) 1417 if (coro->mainstack && coro->mainstack != main_mainstack)
1215 { 1418 {
1216 struct coro temp; 1419 struct coro temp;
1217 1420
1218 if (coro->flags & CF_RUNNING) 1421 assert (("FATAL: tried to destroy currently running coroutine (please report)", !(coro->flags & CF_RUNNING)));
1219 croak ("FATAL: tried to destroy currently running coroutine");
1220 1422
1221 save_perl (aTHX_ &temp); 1423 save_perl (aTHX_ &temp);
1222 load_perl (aTHX_ coro); 1424 load_perl (aTHX_ coro);
1223 1425
1224 coro_destroy (aTHX_ coro); 1426 coro_destruct (aTHX_ coro);
1225 1427
1226 load_perl (aTHX_ &temp); 1428 load_perl (aTHX_ &temp);
1227 1429
1228 coro->slot = 0; 1430 coro->slot = 0;
1229 } 1431 }
1275# define MGf_DUP 0 1477# define MGf_DUP 0
1276#endif 1478#endif
1277}; 1479};
1278 1480
1279static void 1481static void
1280prepare_transfer (pTHX_ struct transfer_args *ta, SV *prev_sv, SV *next_sv) 1482prepare_transfer (pTHX_ struct coro_transfer_args *ta, SV *prev_sv, SV *next_sv)
1281{ 1483{
1282 ta->prev = SvSTATE (prev_sv); 1484 ta->prev = SvSTATE (prev_sv);
1283 ta->next = SvSTATE (next_sv); 1485 ta->next = SvSTATE (next_sv);
1284 TRANSFER_CHECK (*ta); 1486 TRANSFER_CHECK (*ta);
1285} 1487}
1286 1488
1287static void 1489static void
1288api_transfer (SV *prev_sv, SV *next_sv) 1490api_transfer (pTHX_ SV *prev_sv, SV *next_sv)
1289{ 1491{
1290 dTHX;
1291 struct transfer_args ta; 1492 struct coro_transfer_args ta;
1292 1493
1293 prepare_transfer (aTHX_ &ta, prev_sv, next_sv); 1494 prepare_transfer (aTHX_ &ta, prev_sv, next_sv);
1294 TRANSFER (ta); 1495 TRANSFER (ta, 1);
1295} 1496}
1296 1497
1297/** Coro ********************************************************************/ 1498/** Coro ********************************************************************/
1298 1499
1299static void 1500INLINE void
1300coro_enq (pTHX_ SV *coro_sv) 1501coro_enq (pTHX_ struct coro *coro)
1301{ 1502{
1302 av_push (coro_ready [SvSTATE (coro_sv)->prio - PRIO_MIN], coro_sv); 1503 av_push (coro_ready [coro->prio - PRIO_MIN], SvREFCNT_inc_NN (coro->hv));
1303} 1504}
1304 1505
1305static SV * 1506INLINE SV *
1306coro_deq (pTHX_ int min_prio) 1507coro_deq (pTHX)
1307{ 1508{
1308 int prio = PRIO_MAX - PRIO_MIN; 1509 int prio;
1309 1510
1310 min_prio -= PRIO_MIN;
1311 if (min_prio < 0)
1312 min_prio = 0;
1313
1314 for (prio = PRIO_MAX - PRIO_MIN + 1; --prio >= min_prio; ) 1511 for (prio = PRIO_MAX - PRIO_MIN + 1; --prio >= 0; )
1315 if (AvFILLp (coro_ready [prio]) >= 0) 1512 if (AvFILLp (coro_ready [prio]) >= 0)
1316 return av_shift (coro_ready [prio]); 1513 return av_shift (coro_ready [prio]);
1317 1514
1318 return 0; 1515 return 0;
1319} 1516}
1320 1517
1321static int 1518static int
1322api_ready (SV *coro_sv) 1519api_ready (pTHX_ SV *coro_sv)
1323{ 1520{
1324 dTHX;
1325 struct coro *coro; 1521 struct coro *coro;
1522 SV *sv_hook;
1523 void (*xs_hook)(void);
1326 1524
1327 if (SvROK (coro_sv)) 1525 if (SvROK (coro_sv))
1328 coro_sv = SvRV (coro_sv); 1526 coro_sv = SvRV (coro_sv);
1329 1527
1330 coro = SvSTATE (coro_sv); 1528 coro = SvSTATE (coro_sv);
1332 if (coro->flags & CF_READY) 1530 if (coro->flags & CF_READY)
1333 return 0; 1531 return 0;
1334 1532
1335 coro->flags |= CF_READY; 1533 coro->flags |= CF_READY;
1336 1534
1337 LOCK; 1535 sv_hook = coro_nready ? 0 : coro_readyhook;
1338 coro_enq (aTHX_ SvREFCNT_inc (coro_sv)); 1536 xs_hook = coro_nready ? 0 : coroapi.readyhook;
1537
1538 coro_enq (aTHX_ coro);
1339 ++coro_nready; 1539 ++coro_nready;
1340 UNLOCK; 1540
1541 if (sv_hook)
1542 {
1543 dSP;
1544
1545 ENTER;
1546 SAVETMPS;
1547
1548 PUSHMARK (SP);
1549 PUTBACK;
1550 call_sv (sv_hook, G_VOID | G_DISCARD);
1551
1552 FREETMPS;
1553 LEAVE;
1554 }
1555
1556 if (xs_hook)
1557 xs_hook ();
1341 1558
1342 return 1; 1559 return 1;
1343} 1560}
1344 1561
1345static int 1562static int
1346api_is_ready (SV *coro_sv) 1563api_is_ready (pTHX_ SV *coro_sv)
1347{ 1564{
1348 dTHX;
1349 return !!(SvSTATE (coro_sv)->flags & CF_READY); 1565 return !!(SvSTATE (coro_sv)->flags & CF_READY);
1350} 1566}
1351 1567
1352static void 1568INLINE void
1353prepare_schedule (pTHX_ struct transfer_args *ta) 1569prepare_schedule (pTHX_ struct coro_transfer_args *ta)
1354{ 1570{
1355 SV *prev_sv, *next_sv; 1571 SV *prev_sv, *next_sv;
1356 1572
1357 for (;;) 1573 for (;;)
1358 { 1574 {
1359 LOCK;
1360 next_sv = coro_deq (aTHX_ PRIO_MIN); 1575 next_sv = coro_deq (aTHX);
1361 1576
1362 /* nothing to schedule: call the idle handler */ 1577 /* nothing to schedule: call the idle handler */
1363 if (expect_false (!next_sv)) 1578 if (expect_false (!next_sv))
1364 { 1579 {
1365 dSP; 1580 dSP;
1366 UNLOCK;
1367 1581
1368 ENTER; 1582 ENTER;
1369 SAVETMPS; 1583 SAVETMPS;
1370 1584
1371 PUSHMARK (SP); 1585 PUSHMARK (SP);
1372 PUTBACK; 1586 PUTBACK;
1373 call_sv (get_sv ("Coro::idle", FALSE), G_DISCARD); 1587 call_sv (get_sv ("Coro::idle", FALSE), G_VOID | G_DISCARD);
1374 1588
1375 FREETMPS; 1589 FREETMPS;
1376 LEAVE; 1590 LEAVE;
1377 continue; 1591 continue;
1378 } 1592 }
1379 1593
1380 ta->next = SvSTATE (next_sv); 1594 ta->next = SvSTATE_hv (next_sv);
1381 1595
1382 /* cannot transfer to destroyed coros, skip and look for next */ 1596 /* cannot transfer to destroyed coros, skip and look for next */
1383 if (expect_false (ta->next->flags & CF_DESTROYED)) 1597 if (expect_false (ta->next->flags & CF_DESTROYED))
1384 { 1598 {
1385 UNLOCK;
1386 SvREFCNT_dec (next_sv); 1599 SvREFCNT_dec (next_sv);
1387 /* coro_nready is already taken care of by destroy */ 1600 /* coro_nready has already been taken care of by destroy */
1388 continue; 1601 continue;
1389 } 1602 }
1390 1603
1391 --coro_nready; 1604 --coro_nready;
1392 UNLOCK;
1393 break; 1605 break;
1394 } 1606 }
1395 1607
1396 /* free this only after the transfer */ 1608 /* free this only after the transfer */
1397 prev_sv = SvRV (coro_current); 1609 prev_sv = SvRV (coro_current);
1398 ta->prev = SvSTATE (prev_sv); 1610 ta->prev = SvSTATE_hv (prev_sv);
1399 TRANSFER_CHECK (*ta); 1611 TRANSFER_CHECK (*ta);
1400 assert (ta->next->flags & CF_READY); 1612 assert (("FATAL: next coroutine isn't marked as ready in Coro (please report)", ta->next->flags & CF_READY));
1401 ta->next->flags &= ~CF_READY; 1613 ta->next->flags &= ~CF_READY;
1402 SvRV_set (coro_current, next_sv); 1614 SvRV_set (coro_current, next_sv);
1403 1615
1404 LOCK;
1405 free_coro_mortal (aTHX); 1616 free_coro_mortal (aTHX);
1406 coro_mortal = prev_sv; 1617 coro_mortal = prev_sv;
1407 UNLOCK;
1408} 1618}
1409 1619
1410static void 1620INLINE void
1411prepare_cede (pTHX_ struct transfer_args *ta) 1621prepare_cede (pTHX_ struct coro_transfer_args *ta)
1412{ 1622{
1413 api_ready (coro_current); 1623 api_ready (aTHX_ coro_current);
1414 prepare_schedule (aTHX_ ta); 1624 prepare_schedule (aTHX_ ta);
1415} 1625}
1416 1626
1627INLINE void
1628prepare_cede_notself (pTHX_ struct coro_transfer_args *ta)
1629{
1630 SV *prev = SvRV (coro_current);
1631
1632 if (coro_nready)
1633 {
1634 prepare_schedule (aTHX_ ta);
1635 api_ready (aTHX_ prev);
1636 }
1637 else
1638 prepare_nop (aTHX_ ta);
1639}
1640
1641static void
1642api_schedule (pTHX)
1643{
1644 struct coro_transfer_args ta;
1645
1646 prepare_schedule (aTHX_ &ta);
1647 TRANSFER (ta, 1);
1648}
1649
1417static int 1650static int
1418prepare_cede_notself (pTHX_ struct transfer_args *ta) 1651api_cede (pTHX)
1419{ 1652{
1420 if (coro_nready) 1653 struct coro_transfer_args ta;
1421 { 1654
1422 SV *prev = SvRV (coro_current);
1423 prepare_schedule (aTHX_ ta); 1655 prepare_cede (aTHX_ &ta);
1424 api_ready (prev); 1656
1657 if (expect_true (ta.prev != ta.next))
1658 {
1659 TRANSFER (ta, 1);
1425 return 1; 1660 return 1;
1426 } 1661 }
1427 else 1662 else
1428 return 0; 1663 return 0;
1429} 1664}
1430 1665
1431static void
1432api_schedule (void)
1433{
1434 dTHX;
1435 struct transfer_args ta;
1436
1437 prepare_schedule (aTHX_ &ta);
1438 TRANSFER (ta);
1439}
1440
1441static int 1666static int
1442api_cede (void) 1667api_cede_notself (pTHX)
1443{ 1668{
1444 dTHX; 1669 if (coro_nready)
1670 {
1445 struct transfer_args ta; 1671 struct coro_transfer_args ta;
1446 1672
1447 prepare_cede (aTHX_ &ta); 1673 prepare_cede_notself (aTHX_ &ta);
1448
1449 if (expect_true (ta.prev != ta.next))
1450 {
1451 TRANSFER (ta); 1674 TRANSFER (ta, 1);
1452 return 1; 1675 return 1;
1453 } 1676 }
1454 else 1677 else
1455 return 0; 1678 return 0;
1456} 1679}
1457 1680
1458static int 1681static void
1459api_cede_notself (void)
1460{
1461 dTHX;
1462 struct transfer_args ta;
1463
1464 if (prepare_cede_notself (aTHX_ &ta))
1465 {
1466 TRANSFER (ta);
1467 return 1;
1468 }
1469 else
1470 return 0;
1471}
1472
1473static void
1474api_trace (SV *coro_sv, int flags) 1682api_trace (pTHX_ SV *coro_sv, int flags)
1475{ 1683{
1476 dTHX;
1477 struct coro *coro = SvSTATE (coro_sv); 1684 struct coro *coro = SvSTATE (coro_sv);
1478 1685
1479 if (flags & CC_TRACE) 1686 if (flags & CC_TRACE)
1480 { 1687 {
1481 if (!coro->cctx) 1688 if (!coro->cctx)
1482 coro->cctx = cctx_new (); 1689 coro->cctx = cctx_new_run ();
1483 else if (!(coro->cctx->flags & CC_TRACE)) 1690 else if (!(coro->cctx->flags & CC_TRACE))
1484 croak ("cannot enable tracing on coroutine with custom stack"); 1691 croak ("cannot enable tracing on coroutine with custom stack,");
1485 1692
1486 coro->cctx->flags |= CC_NOREUSE | (flags & (CC_TRACE | CC_TRACE_ALL)); 1693 coro->cctx->flags |= CC_NOREUSE | (flags & (CC_TRACE | CC_TRACE_ALL));
1487 } 1694 }
1488 else if (coro->cctx && coro->cctx->flags & CC_TRACE) 1695 else if (coro->cctx && coro->cctx->flags & CC_TRACE)
1489 { 1696 {
1494 else 1701 else
1495 coro->slot->runops = RUNOPS_DEFAULT; 1702 coro->slot->runops = RUNOPS_DEFAULT;
1496 } 1703 }
1497} 1704}
1498 1705
1706/*****************************************************************************/
1707/* schedule-like-function opcode (SLF) */
1708
1709static UNOP slf_restore; /* restore stack as entersub did, for first-re-run */
1710static const CV *slf_cv;
1711static SV **slf_argv;
1712static int slf_argc, slf_arga; /* count, allocated */
1713static I32 slf_ax; /* top of stack, for restore */
1714
1715/* this restores the stack in the case we patched the entersub, to */
1716/* recreate the stack frame as perl will on following calls */
1717/* since entersub cleared the stack */
1718static OP *
1719pp_restore (pTHX)
1720{
1721 int i;
1722 SV **SP = PL_stack_base + slf_ax;
1723
1724 PUSHMARK (SP);
1725
1726 EXTEND (SP, slf_argc + 1);
1727
1728 for (i = 0; i < slf_argc; ++i)
1729 PUSHs (sv_2mortal (slf_argv [i]));
1730
1731 PUSHs ((SV *)CvGV (slf_cv));
1732
1733 RETURNOP (slf_restore.op_first);
1734}
1735
1736static void
1737slf_prepare_transfer (pTHX_ struct coro_transfer_args *ta)
1738{
1739 SV **arg = (SV **)slf_frame.data;
1740
1741 prepare_transfer (aTHX_ ta, arg [0], arg [1]);
1742}
1743
1744static void
1745slf_init_transfer (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
1746{
1747 if (items != 2)
1748 croak ("Coro::State::transfer (prev, next) expects two arguments, not %d,", items);
1749
1750 frame->prepare = slf_prepare_transfer;
1751 frame->check = slf_check_nop;
1752 frame->data = (void *)arg; /* let's hope it will stay valid */
1753}
1754
1755static void
1756slf_init_schedule (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
1757{
1758 frame->prepare = prepare_schedule;
1759 frame->check = slf_check_nop;
1760}
1761
1762static void
1763slf_init_cede (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
1764{
1765 frame->prepare = prepare_cede;
1766 frame->check = slf_check_nop;
1767}
1768
1769static void
1770slf_init_cede_notself (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
1771{
1772 frame->prepare = prepare_cede_notself;
1773 frame->check = slf_check_nop;
1774}
1775
1776/*
1777 * these not obviously related functions are all rolled into one
1778 * function to increase chances that they all will call transfer with the same
1779 * stack offset
1780 * SLF stands for "schedule-like-function".
1781 */
1782static OP *
1783pp_slf (pTHX)
1784{
1785 I32 checkmark; /* mark SP to see how many elements check has pushed */
1786
1787 /* set up the slf frame, unless it has already been set-up */
1788 /* the latter happens when a new coro has been started */
1789 /* or when a new cctx was attached to an existing coroutine */
1790 if (expect_true (!slf_frame.prepare))
1791 {
1792 /* first iteration */
1793 dSP;
1794 SV **arg = PL_stack_base + TOPMARK + 1;
1795 int items = SP - arg; /* args without function object */
1796 SV *gv = *sp;
1797
1798 /* do a quick consistency check on the "function" object, and if it isn't */
1799 /* for us, divert to the real entersub */
1800 if (SvTYPE (gv) != SVt_PVGV
1801 || !GvCV (gv)
1802 || !(CvFLAGS (GvCV (gv)) & CVf_SLF))
1803 return PL_ppaddr[OP_ENTERSUB](aTHX);
1804
1805 if (!(PL_op->op_flags & OPf_STACKED))
1806 {
1807 /* ampersand-form of call, use @_ instead of stack */
1808 AV *av = GvAV (PL_defgv);
1809 arg = AvARRAY (av);
1810 items = AvFILLp (av) + 1;
1811 }
1812
1813 /* now call the init function, which needs to set up slf_frame */
1814 ((coro_slf_cb)CvXSUBANY (GvCV (gv)).any_ptr)
1815 (aTHX_ &slf_frame, GvCV (gv), arg, items);
1816
1817 /* pop args */
1818 SP = PL_stack_base + POPMARK;
1819
1820 PUTBACK;
1821 }
1822
1823 /* now that we have a slf_frame, interpret it! */
1824 /* we use a callback system not to make the code needlessly */
1825 /* complicated, but so we can run multiple perl coros from one cctx */
1826
1827 do
1828 {
1829 struct coro_transfer_args ta;
1830
1831 slf_frame.prepare (aTHX_ &ta);
1832 TRANSFER (ta, 0);
1833
1834 checkmark = PL_stack_sp - PL_stack_base;
1835 }
1836 while (slf_frame.check (aTHX_ &slf_frame));
1837
1838 slf_frame.prepare = 0; /* invalidate the frame, we are done processing it */
1839
1840 /* return value handling - mostly like entersub */
1841 /* make sure we put something on the stack in scalar context */
1842 if (GIMME_V == G_SCALAR)
1843 {
1844 dSP;
1845 SV **bot = PL_stack_base + checkmark;
1846
1847 if (sp == bot) /* too few, push undef */
1848 bot [1] = &PL_sv_undef;
1849 else if (sp != bot + 1) /* too many, take last one */
1850 bot [1] = *sp;
1851
1852 SP = bot + 1;
1853
1854 PUTBACK;
1855 }
1856
1857 /* exception handling */
1858 if (expect_false (coro_throw))
1859 {
1860 SV *exception = sv_2mortal (coro_throw);
1861
1862 coro_throw = 0;
1863 sv_setsv (ERRSV, exception);
1864 croak (0);
1865 }
1866
1867 return NORMAL;
1868}
1869
1870static void
1871api_execute_slf (pTHX_ CV *cv, coro_slf_cb init_cb, I32 ax)
1872{
1873 int i;
1874 SV **arg = PL_stack_base + ax;
1875 int items = PL_stack_sp - arg + 1;
1876
1877 assert (("FATAL: SLF call with illegal CV value", !CvANON (cv)));
1878
1879 if (PL_op->op_ppaddr != PL_ppaddr [OP_ENTERSUB]
1880 && PL_op->op_ppaddr != pp_slf)
1881 croak ("FATAL: Coro SLF calls can only be made normally, not via goto or any other means, caught");
1882
1883 CvFLAGS (cv) |= CVf_SLF;
1884 CvXSUBANY (cv).any_ptr = (void *)init_cb;
1885 slf_cv = cv;
1886
1887 /* we patch the op, and then re-run the whole call */
1888 /* we have to put the same argument on the stack for this to work */
1889 /* and this will be done by pp_restore */
1890 slf_restore.op_next = (OP *)&slf_restore;
1891 slf_restore.op_type = OP_CUSTOM;
1892 slf_restore.op_ppaddr = pp_restore;
1893 slf_restore.op_first = PL_op;
1894
1895 slf_ax = ax - 1; /* undo the ax++ inside dAXMARK */
1896
1897 if (PL_op->op_flags & OPf_STACKED)
1898 {
1899 if (items > slf_arga)
1900 {
1901 slf_arga = items;
1902 free (slf_argv);
1903 slf_argv = malloc (slf_arga * sizeof (SV *));
1904 }
1905
1906 slf_argc = items;
1907
1908 for (i = 0; i < items; ++i)
1909 slf_argv [i] = SvREFCNT_inc (arg [i]);
1910 }
1911 else
1912 slf_argc = 0;
1913
1914 PL_op->op_ppaddr = pp_slf;
1915 PL_op->op_type = OP_CUSTOM; /* maybe we should leave it at entersub? */
1916
1917 PL_op = (OP *)&slf_restore;
1918}
1919
1920/*****************************************************************************/
1921/* PerlIO::cede */
1922
1923typedef struct
1924{
1925 PerlIOBuf base;
1926 NV next, every;
1927} PerlIOCede;
1928
1929static IV
1930PerlIOCede_pushed (pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1931{
1932 PerlIOCede *self = PerlIOSelf (f, PerlIOCede);
1933
1934 self->every = SvCUR (arg) ? SvNV (arg) : 0.01;
1935 self->next = nvtime () + self->every;
1936
1937 return PerlIOBuf_pushed (aTHX_ f, mode, Nullsv, tab);
1938}
1939
1940static SV *
1941PerlIOCede_getarg (pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
1942{
1943 PerlIOCede *self = PerlIOSelf (f, PerlIOCede);
1944
1945 return newSVnv (self->every);
1946}
1947
1948static IV
1949PerlIOCede_flush (pTHX_ PerlIO *f)
1950{
1951 PerlIOCede *self = PerlIOSelf (f, PerlIOCede);
1952 double now = nvtime ();
1953
1954 if (now >= self->next)
1955 {
1956 api_cede (aTHX);
1957 self->next = now + self->every;
1958 }
1959
1960 return PerlIOBuf_flush (aTHX_ f);
1961}
1962
1963static PerlIO_funcs PerlIO_cede =
1964{
1965 sizeof(PerlIO_funcs),
1966 "cede",
1967 sizeof(PerlIOCede),
1968 PERLIO_K_DESTRUCT | PERLIO_K_RAW,
1969 PerlIOCede_pushed,
1970 PerlIOBuf_popped,
1971 PerlIOBuf_open,
1972 PerlIOBase_binmode,
1973 PerlIOCede_getarg,
1974 PerlIOBase_fileno,
1975 PerlIOBuf_dup,
1976 PerlIOBuf_read,
1977 PerlIOBuf_unread,
1978 PerlIOBuf_write,
1979 PerlIOBuf_seek,
1980 PerlIOBuf_tell,
1981 PerlIOBuf_close,
1982 PerlIOCede_flush,
1983 PerlIOBuf_fill,
1984 PerlIOBase_eof,
1985 PerlIOBase_error,
1986 PerlIOBase_clearerr,
1987 PerlIOBase_setlinebuf,
1988 PerlIOBuf_get_base,
1989 PerlIOBuf_bufsiz,
1990 PerlIOBuf_get_ptr,
1991 PerlIOBuf_get_cnt,
1992 PerlIOBuf_set_ptrcnt,
1993};
1994
1995/*****************************************************************************/
1996/* Coro::Semaphore */
1997
1998static void
1999coro_semaphore_adjust (pTHX_ AV *av, IV adjust)
2000{
2001 SV *count_sv = AvARRAY (av)[0];
2002 IV count = SvIVX (count_sv);
2003
2004 count += adjust;
2005 SvIVX (count_sv) = count;
2006
2007 /* now wake up as many waiters as are expected to lock */
2008 while (count > 0 && AvFILLp (av) > 0)
2009 {
2010 SV *cb;
2011
2012 /* swap first two elements so we can shift a waiter */
2013 AvARRAY (av)[0] = AvARRAY (av)[1];
2014 AvARRAY (av)[1] = count_sv;
2015 cb = av_shift (av);
2016
2017 if (SvOBJECT (cb))
2018 api_ready (aTHX_ cb);
2019 else
2020 croak ("callbacks not yet supported");
2021
2022 SvREFCNT_dec (cb);
2023
2024 --count;
2025 }
2026}
2027
2028static void
2029coro_semaphore_on_destroy (pTHX_ struct coro *coro)
2030{
2031 /* call $sem->adjust (0) to possibly wake up some other waiters */
2032 coro_semaphore_adjust (aTHX_ (AV *)coro->slf_frame.data, 0);
2033}
2034
2035static int
2036slf_check_semaphore_down (pTHX_ struct CoroSLF *frame)
2037{
2038 AV *av = (AV *)frame->data;
2039 SV *count_sv = AvARRAY (av)[0];
2040
2041 if (SvIVX (count_sv) > 0)
2042 {
2043 SvSTATE_current->on_destroy = 0;
2044 SvIVX (count_sv) = SvIVX (count_sv) - 1;
2045 return 0;
2046 }
2047 else
2048 {
2049 int i;
2050 /* if we were woken up but can't down, we look through the whole */
2051 /* waiters list and only add us if we aren't in there already */
2052 /* this avoids some degenerate memory usage cases */
2053
2054 for (i = 1; i <= AvFILLp (av); ++i)
2055 if (AvARRAY (av)[i] == SvRV (coro_current))
2056 return 1;
2057
2058 av_push (av, SvREFCNT_inc (SvRV (coro_current)));
2059 return 1;
2060 }
2061}
2062
2063static void
2064slf_init_semaphore_down (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2065{
2066 AV *av = (AV *)SvRV (arg [0]);
2067
2068 if (SvIVX (AvARRAY (av)[0]) > 0)
2069 {
2070 frame->data = (void *)av;
2071 frame->prepare = prepare_nop;
2072 SvSTATE_current->on_destroy = coro_semaphore_on_destroy;
2073 }
2074 else
2075 {
2076 av_push (av, SvREFCNT_inc (SvRV (coro_current)));
2077
2078 frame->data = (void *)sv_2mortal (SvREFCNT_inc ((SV *)av));
2079 frame->prepare = prepare_schedule;
2080
2081 /* to avoid race conditions when a woken-up coro gets terminated */
2082 /* we arrange for a temporary on_destroy that calls adjust (0) */
2083 assert (!SvSTATE_current->on_destroy);//D
2084 SvSTATE_current->on_destroy = coro_semaphore_on_destroy;
2085 }
2086
2087 frame->check = slf_check_semaphore_down;
2088
2089}
2090
2091/*****************************************************************************/
2092/* gensub: simple closure generation utility */
2093
2094#define GENSUB_ARG CvXSUBANY (cv).any_ptr
2095
2096/* create a closure from XS, returns a code reference */
2097/* the arg can be accessed via GENSUB_ARG from the callback */
2098/* the callback must use dXSARGS/XSRETURN */
2099static SV *
2100gensub (pTHX_ void (*xsub)(pTHX_ CV *), void *arg)
2101{
2102 CV *cv = (CV *)newSV (0);
2103
2104 sv_upgrade ((SV *)cv, SVt_PVCV);
2105
2106 CvANON_on (cv);
2107 CvISXSUB_on (cv);
2108 CvXSUB (cv) = xsub;
2109 GENSUB_ARG = arg;
2110
2111 return newRV_noinc ((SV *)cv);
2112}
2113
2114/*****************************************************************************/
2115/* Coro::AIO */
2116
2117#define CORO_MAGIC_type_aio PERL_MAGIC_ext
2118
2119/* helper storage struct */
2120struct io_state
2121{
2122 int errorno;
2123 I32 laststype; /* U16 in 5.10.0 */
2124 int laststatval;
2125 Stat_t statcache;
2126};
2127
2128static void
2129coro_aio_callback (pTHX_ CV *cv)
2130{
2131 dXSARGS;
2132 AV *state = (AV *)GENSUB_ARG;
2133 SV *coro = av_pop (state);
2134 SV *data_sv = newSV (sizeof (struct io_state));
2135
2136 av_extend (state, items);
2137
2138 sv_upgrade (data_sv, SVt_PV);
2139 SvCUR_set (data_sv, sizeof (struct io_state));
2140 SvPOK_only (data_sv);
2141
2142 {
2143 struct io_state *data = (struct io_state *)SvPVX (data_sv);
2144
2145 data->errorno = errno;
2146 data->laststype = PL_laststype;
2147 data->laststatval = PL_laststatval;
2148 data->statcache = PL_statcache;
2149 }
2150
2151 /* now build the result vector out of all the parameters and the data_sv */
2152 {
2153 int i;
2154
2155 for (i = 0; i < items; ++i)
2156 av_push (state, SvREFCNT_inc_NN (ST (i)));
2157 }
2158
2159 av_push (state, data_sv);
2160
2161 api_ready (aTHX_ coro);
2162 SvREFCNT_dec (coro);
2163 SvREFCNT_dec ((AV *)state);
2164}
2165
2166static int
2167slf_check_aio_req (pTHX_ struct CoroSLF *frame)
2168{
2169 AV *state = (AV *)frame->data;
2170
2171 /* one element that is an RV? repeat! */
2172 if (AvFILLp (state) == 0 && SvROK (AvARRAY (state)[0]))
2173 return 1;
2174
2175 /* restore status */
2176 {
2177 SV *data_sv = av_pop (state);
2178 struct io_state *data = (struct io_state *)SvPVX (data_sv);
2179
2180 errno = data->errorno;
2181 PL_laststype = data->laststype;
2182 PL_laststatval = data->laststatval;
2183 PL_statcache = data->statcache;
2184
2185 SvREFCNT_dec (data_sv);
2186 }
2187
2188 /* push result values */
2189 {
2190 dSP;
2191 int i;
2192
2193 EXTEND (SP, AvFILLp (state) + 1);
2194 for (i = 0; i <= AvFILLp (state); ++i)
2195 PUSHs (sv_2mortal (SvREFCNT_inc_NN (AvARRAY (state)[i])));
2196
2197 PUTBACK;
2198 }
2199
2200 return 0;
2201}
2202
2203static void
2204slf_init_aio_req (pTHX_ struct CoroSLF *frame, CV *cv, SV **arg, int items)
2205{
2206 AV *state = (AV *)sv_2mortal ((SV *)newAV ());
2207 SV *coro_hv = SvRV (coro_current);
2208 struct coro *coro = SvSTATE_hv (coro_hv);
2209
2210 /* put our coroutine id on the state arg */
2211 av_push (state, SvREFCNT_inc_NN (coro_hv));
2212
2213 /* first see whether we have a non-zero priority and set it as AIO prio */
2214 if (coro->prio)
2215 {
2216 dSP;
2217
2218 static SV *prio_cv;
2219 static SV *prio_sv;
2220
2221 if (expect_false (!prio_cv))
2222 {
2223 prio_cv = (SV *)get_cv ("IO::AIO::aioreq_pri", 0);
2224 prio_sv = newSViv (0);
2225 }
2226
2227 PUSHMARK (SP);
2228 sv_setiv (prio_sv, coro->prio);
2229 XPUSHs (prio_sv);
2230
2231 PUTBACK;
2232 call_sv (prio_cv, G_VOID | G_DISCARD);
2233 }
2234
2235 /* now call the original request */
2236 {
2237 dSP;
2238 CV *req = (CV *)CORO_MAGIC_NN ((SV *)cv, CORO_MAGIC_type_aio)->mg_obj;
2239 int i;
2240
2241 PUSHMARK (SP);
2242
2243 /* first push all args to the stack */
2244 EXTEND (SP, items + 1);
2245
2246 for (i = 0; i < items; ++i)
2247 PUSHs (arg [i]);
2248
2249 /* now push the callback closure */
2250 PUSHs (sv_2mortal (gensub (aTHX_ coro_aio_callback, (void *)SvREFCNT_inc_NN ((SV *)state))));
2251
2252 /* now call the AIO function - we assume our request is uncancelable */
2253 PUTBACK;
2254 call_sv ((SV *)req, G_VOID | G_DISCARD);
2255 }
2256
2257 /* now that the requets is going, we loop toll we have a result */
2258 frame->data = (void *)state;
2259 frame->prepare = prepare_schedule;
2260 frame->check = slf_check_aio_req;
2261}
2262
2263static void
2264coro_aio_req_xs (pTHX_ CV *cv)
2265{
2266 dXSARGS;
2267
2268 CORO_EXECUTE_SLF_XS (slf_init_aio_req);
2269
2270 XSRETURN_EMPTY;
2271}
2272
2273/*****************************************************************************/
2274
1499MODULE = Coro::State PACKAGE = Coro::State PREFIX = api_ 2275MODULE = Coro::State PACKAGE = Coro::State PREFIX = api_
1500 2276
1501PROTOTYPES: DISABLE 2277PROTOTYPES: DISABLE
1502 2278
1503BOOT: 2279BOOT:
1504{ 2280{
1505#ifdef USE_ITHREADS 2281#ifdef USE_ITHREADS
1506 MUTEX_INIT (&coro_mutex); 2282# if CORO_PTHREAD
2283 coro_thx = PERL_GET_CONTEXT;
2284# endif
1507#endif 2285#endif
1508 BOOT_PAGESIZE; 2286 BOOT_PAGESIZE;
1509 2287
1510 irsgv = gv_fetchpv ("/" , GV_ADD|GV_NOTQUAL, SVt_PV); 2288 irsgv = gv_fetchpv ("/" , GV_ADD|GV_NOTQUAL, SVt_PV);
1511 stdoutgv = gv_fetchpv ("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO); 2289 stdoutgv = gv_fetchpv ("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO);
1512 2290
2291 orig_sigelem_get = PL_vtbl_sigelem.svt_get; PL_vtbl_sigelem.svt_get = coro_sigelem_get;
2292 orig_sigelem_set = PL_vtbl_sigelem.svt_set; PL_vtbl_sigelem.svt_set = coro_sigelem_set;
2293 orig_sigelem_clr = PL_vtbl_sigelem.svt_clear; PL_vtbl_sigelem.svt_clear = coro_sigelem_clr;
2294
1513 hv_sig = coro_get_hv ("SIG", TRUE); 2295 hv_sig = coro_get_hv (aTHX_ "SIG", TRUE);
1514 sv_diehook = coro_get_sv ("Coro::State::DIEHOOK" , TRUE); 2296 rv_diehook = newRV_inc ((SV *)gv_fetchpv ("Coro::State::diehook" , 0, SVt_PVCV));
1515 sv_warnhook = coro_get_sv ("Coro::State::WARNHOOK", TRUE); 2297 rv_warnhook = newRV_inc ((SV *)gv_fetchpv ("Coro::State::warnhook", 0, SVt_PVCV));
1516
1517 if (!PL_diehook ) hv_store (hv_sig, strpair ("__DIE__" ), SvREFCNT_inc (sv_diehook ), 0);
1518 if (!PL_warnhook) hv_store (hv_sig, strpair ("__WARN__"), SvREFCNT_inc (sv_warnhook), 0);
1519 2298
1520 coro_state_stash = gv_stashpv ("Coro::State", TRUE); 2299 coro_state_stash = gv_stashpv ("Coro::State", TRUE);
1521 2300
1522 newCONSTSUB (coro_state_stash, "CC_TRACE" , newSViv (CC_TRACE)); 2301 newCONSTSUB (coro_state_stash, "CC_TRACE" , newSViv (CC_TRACE));
1523 newCONSTSUB (coro_state_stash, "CC_TRACE_SUB" , newSViv (CC_TRACE_SUB)); 2302 newCONSTSUB (coro_state_stash, "CC_TRACE_SUB" , newSViv (CC_TRACE_SUB));
1528 main_top_env = PL_top_env; 2307 main_top_env = PL_top_env;
1529 2308
1530 while (main_top_env->je_prev) 2309 while (main_top_env->je_prev)
1531 main_top_env = main_top_env->je_prev; 2310 main_top_env = main_top_env->je_prev;
1532 2311
2312 {
2313 SV *slf = sv_2mortal (newSViv (PTR2IV (pp_slf)));
2314
2315 if (!PL_custom_op_names) PL_custom_op_names = newHV ();
2316 hv_store_ent (PL_custom_op_names, slf,
2317 newSVpv ("coro_slf", 0), 0);
2318
2319 if (!PL_custom_op_descs) PL_custom_op_descs = newHV ();
2320 hv_store_ent (PL_custom_op_descs, slf,
2321 newSVpv ("coro schedule like function", 0), 0);
2322 }
2323
1533 coroapi.ver = CORO_API_VERSION; 2324 coroapi.ver = CORO_API_VERSION;
1534 coroapi.rev = CORO_API_REVISION; 2325 coroapi.rev = CORO_API_REVISION;
2326
1535 coroapi.transfer = api_transfer; 2327 coroapi.transfer = api_transfer;
2328
2329 coroapi.sv_state = SvSTATE_;
2330 coroapi.execute_slf = api_execute_slf;
2331 coroapi.prepare_nop = prepare_nop;
2332 coroapi.prepare_schedule = prepare_schedule;
2333 coroapi.prepare_cede = prepare_cede;
2334 coroapi.prepare_cede_notself = prepare_cede_notself;
2335
2336 {
2337 SV **svp = hv_fetch (PL_modglobal, "Time::NVtime", 12, 0);
2338
2339 if (!svp) croak ("Time::HiRes is required");
2340 if (!SvIOK (*svp)) croak ("Time::NVtime isn't a function pointer");
2341
2342 nvtime = INT2PTR (double (*)(), SvIV (*svp));
2343 }
1536 2344
1537 assert (("PRIO_NORMAL must be 0", !PRIO_NORMAL)); 2345 assert (("PRIO_NORMAL must be 0", !PRIO_NORMAL));
1538} 2346}
1539 2347
1540SV * 2348SV *
1541new (char *klass, ...) 2349new (char *klass, ...)
1542 CODE: 2350 CODE:
1543{ 2351{
1544 struct coro *coro; 2352 struct coro *coro;
2353 MAGIC *mg;
1545 HV *hv; 2354 HV *hv;
1546 int i; 2355 int i;
1547 2356
1548 Newz (0, coro, 1, struct coro); 2357 Newz (0, coro, 1, struct coro);
1549 coro->args = newAV (); 2358 coro->args = newAV ();
1552 if (coro_first) coro_first->prev = coro; 2361 if (coro_first) coro_first->prev = coro;
1553 coro->next = coro_first; 2362 coro->next = coro_first;
1554 coro_first = coro; 2363 coro_first = coro;
1555 2364
1556 coro->hv = hv = newHV (); 2365 coro->hv = hv = newHV ();
1557 sv_magicext ((SV *)hv, 0, PERL_MAGIC_ext, &coro_state_vtbl, (char *)coro, 0)->mg_flags |= MGf_DUP; 2366 mg = sv_magicext ((SV *)hv, 0, CORO_MAGIC_type_state, &coro_state_vtbl, (char *)coro, 0);
2367 mg->mg_flags |= MGf_DUP;
1558 RETVAL = sv_bless (newRV_noinc ((SV *)hv), gv_stashpv (klass, 1)); 2368 RETVAL = sv_bless (newRV_noinc ((SV *)hv), gv_stashpv (klass, 1));
1559 2369
1560 av_extend (coro->args, items - 1); 2370 av_extend (coro->args, items - 1);
1561 for (i = 1; i < items; i++) 2371 for (i = 1; i < items; i++)
1562 av_push (coro->args, newSVsv (ST (i))); 2372 av_push (coro->args, newSVsv (ST (i)));
1563} 2373}
1564 OUTPUT: 2374 OUTPUT:
1565 RETVAL 2375 RETVAL
1566 2376
1567# these not obviously related functions are all rolled into the same xs
1568# function to increase chances that they all will call transfer with the same
1569# stack offset
1570void 2377void
1571_set_stacklevel (...) 2378transfer (...)
1572 ALIAS: 2379 PROTOTYPE: $$
1573 Coro::State::transfer = 1 2380 CODE:
1574 Coro::schedule = 2 2381 CORO_EXECUTE_SLF_XS (slf_init_transfer);
1575 Coro::cede = 3
1576 Coro::cede_notself = 4
1577 CODE:
1578{
1579 struct transfer_args ta;
1580
1581 switch (ix)
1582 {
1583 case 0:
1584 ta.prev = (struct coro *)INT2PTR (coro_cctx *, SvIV (ST (0)));
1585 ta.next = 0;
1586 break;
1587
1588 case 1:
1589 if (items != 2)
1590 croak ("Coro::State::transfer (prev,next) expects two arguments, not %d", items);
1591
1592 prepare_transfer (aTHX_ &ta, ST (0), ST (1));
1593 break;
1594
1595 case 2:
1596 prepare_schedule (aTHX_ &ta);
1597 break;
1598
1599 case 3:
1600 prepare_cede (aTHX_ &ta);
1601 break;
1602
1603 case 4:
1604 if (!prepare_cede_notself (aTHX_ &ta))
1605 XSRETURN_EMPTY;
1606
1607 break;
1608 }
1609
1610 BARRIER;
1611 PUTBACK;
1612 TRANSFER (ta);
1613 SPAGAIN; /* might be the sp of a different coroutine now */
1614 /* be extra careful not to ever do anything after TRANSFER */
1615}
1616 2382
1617bool 2383bool
1618_destroy (SV *coro_sv) 2384_destroy (SV *coro_sv)
1619 CODE: 2385 CODE:
1620 RETVAL = coro_state_destroy (aTHX_ SvSTATE (coro_sv)); 2386 RETVAL = coro_state_destroy (aTHX_ SvSTATE (coro_sv));
1621 OUTPUT: 2387 OUTPUT:
1622 RETVAL 2388 RETVAL
1623 2389
1624void 2390void
1625_exit (code) 2391_exit (int code)
1626 int code
1627 PROTOTYPE: $ 2392 PROTOTYPE: $
1628 CODE: 2393 CODE:
1629 _exit (code); 2394 _exit (code);
1630 2395
1631int 2396int
1632cctx_stacksize (int new_stacksize = 0) 2397cctx_stacksize (int new_stacksize = 0)
2398 PROTOTYPE: ;$
1633 CODE: 2399 CODE:
1634 RETVAL = coro_stacksize; 2400 RETVAL = cctx_stacksize;
1635 if (new_stacksize) 2401 if (new_stacksize)
2402 {
1636 coro_stacksize = new_stacksize; 2403 cctx_stacksize = new_stacksize;
2404 ++cctx_gen;
2405 }
1637 OUTPUT: 2406 OUTPUT:
1638 RETVAL 2407 RETVAL
1639 2408
1640int 2409int
2410cctx_max_idle (int max_idle = 0)
2411 PROTOTYPE: ;$
2412 CODE:
2413 RETVAL = cctx_max_idle;
2414 if (max_idle > 1)
2415 cctx_max_idle = max_idle;
2416 OUTPUT:
2417 RETVAL
2418
2419int
1641cctx_count () 2420cctx_count ()
2421 PROTOTYPE:
1642 CODE: 2422 CODE:
1643 RETVAL = cctx_count; 2423 RETVAL = cctx_count;
1644 OUTPUT: 2424 OUTPUT:
1645 RETVAL 2425 RETVAL
1646 2426
1647int 2427int
1648cctx_idle () 2428cctx_idle ()
2429 PROTOTYPE:
1649 CODE: 2430 CODE:
1650 RETVAL = cctx_idle; 2431 RETVAL = cctx_idle;
1651 OUTPUT: 2432 OUTPUT:
1652 RETVAL 2433 RETVAL
1653 2434
1654void 2435void
1655list () 2436list ()
2437 PROTOTYPE:
1656 PPCODE: 2438 PPCODE:
1657{ 2439{
1658 struct coro *coro; 2440 struct coro *coro;
1659 for (coro = coro_first; coro; coro = coro->next) 2441 for (coro = coro_first; coro; coro = coro->next)
1660 if (coro->hv) 2442 if (coro->hv)
1665call (Coro::State coro, SV *coderef) 2447call (Coro::State coro, SV *coderef)
1666 ALIAS: 2448 ALIAS:
1667 eval = 1 2449 eval = 1
1668 CODE: 2450 CODE:
1669{ 2451{
1670 if (coro->mainstack) 2452 if (coro->mainstack && ((coro->flags & CF_RUNNING) || coro->slot))
1671 { 2453 {
1672 struct coro temp; 2454 struct coro temp;
1673 2455
1674 if (!(coro->flags & CF_RUNNING)) 2456 if (!(coro->flags & CF_RUNNING))
1675 { 2457 {
2458 PUTBACK;
1676 save_perl (aTHX_ &temp); 2459 save_perl (aTHX_ &temp);
1677 load_perl (aTHX_ coro); 2460 load_perl (aTHX_ coro);
1678 } 2461 }
1679 2462
1680 { 2463 {
1699 2482
1700 if (!(coro->flags & CF_RUNNING)) 2483 if (!(coro->flags & CF_RUNNING))
1701 { 2484 {
1702 save_perl (aTHX_ coro); 2485 save_perl (aTHX_ coro);
1703 load_perl (aTHX_ &temp); 2486 load_perl (aTHX_ &temp);
2487 SPAGAIN;
1704 } 2488 }
1705 } 2489 }
1706} 2490}
1707 2491
1708SV * 2492SV *
1717 RETVAL = boolSV (coro->flags & ix); 2501 RETVAL = boolSV (coro->flags & ix);
1718 OUTPUT: 2502 OUTPUT:
1719 RETVAL 2503 RETVAL
1720 2504
1721void 2505void
2506throw (Coro::State self, SV *throw = &PL_sv_undef)
2507 PROTOTYPE: $;$
2508 CODE:
2509{
2510 struct coro *current = SvSTATE_current;
2511 SV **throwp = self == current ? &coro_throw : &self->throw;
2512 SvREFCNT_dec (*throwp);
2513 *throwp = SvOK (throw) ? newSVsv (throw) : 0;
2514}
2515
2516void
1722api_trace (SV *coro, int flags = CC_TRACE | CC_TRACE_SUB) 2517api_trace (SV *coro, int flags = CC_TRACE | CC_TRACE_SUB)
2518 PROTOTYPE: $;$
2519 C_ARGS: aTHX_ coro, flags
1723 2520
1724SV * 2521SV *
1725has_stack (Coro::State coro) 2522has_cctx (Coro::State coro)
1726 PROTOTYPE: $ 2523 PROTOTYPE: $
1727 CODE: 2524 CODE:
1728 RETVAL = boolSV (!!coro->cctx); 2525 RETVAL = boolSV (!!coro->cctx);
1729 OUTPUT: 2526 OUTPUT:
1730 RETVAL 2527 RETVAL
1735 CODE: 2532 CODE:
1736 RETVAL = (coro->cctx ? coro->cctx->flags : 0) & CC_TRACE_ALL; 2533 RETVAL = (coro->cctx ? coro->cctx->flags : 0) & CC_TRACE_ALL;
1737 OUTPUT: 2534 OUTPUT:
1738 RETVAL 2535 RETVAL
1739 2536
1740IV 2537UV
1741rss (Coro::State coro) 2538rss (Coro::State coro)
1742 PROTOTYPE: $ 2539 PROTOTYPE: $
1743 ALIAS: 2540 ALIAS:
1744 usecount = 1 2541 usecount = 1
1745 CODE: 2542 CODE:
1749 case 1: RETVAL = coro->usecount; break; 2546 case 1: RETVAL = coro->usecount; break;
1750 } 2547 }
1751 OUTPUT: 2548 OUTPUT:
1752 RETVAL 2549 RETVAL
1753 2550
2551void
2552force_cctx ()
2553 PROTOTYPE:
2554 CODE:
2555 SvSTATE_current->cctx->idle_sp = 0;
2556
2557void
2558swap_defsv (Coro::State self)
2559 PROTOTYPE: $
2560 ALIAS:
2561 swap_defav = 1
2562 CODE:
2563 if (!self->slot)
2564 croak ("cannot swap state with coroutine that has no saved state,");
2565 else
2566 {
2567 SV **src = ix ? (SV **)&GvAV (PL_defgv) : &GvSV (PL_defgv);
2568 SV **dst = ix ? (SV **)&self->slot->defav : (SV **)&self->slot->defsv;
2569
2570 SV *tmp = *src; *src = *dst; *dst = tmp;
2571 }
2572
1754 2573
1755MODULE = Coro::State PACKAGE = Coro 2574MODULE = Coro::State PACKAGE = Coro
1756 2575
1757BOOT: 2576BOOT:
1758{ 2577{
1759 int i; 2578 int i;
1760 2579
1761 sv_pool_rss = coro_get_sv ("Coro::POOL_RSS" , TRUE);
1762 sv_pool_size = coro_get_sv ("Coro::POOL_SIZE" , TRUE);
1763 av_async_pool = coro_get_av ("Coro::async_pool", TRUE); 2580 av_async_pool = coro_get_av (aTHX_ "Coro::async_pool", TRUE);
2581 sv_pool_rss = coro_get_sv (aTHX_ "Coro::POOL_RSS" , TRUE);
2582 sv_pool_size = coro_get_sv (aTHX_ "Coro::POOL_SIZE" , TRUE);
1764 2583
1765 coro_current = coro_get_sv ("Coro::current", FALSE); 2584 coro_current = coro_get_sv (aTHX_ "Coro::current", FALSE);
1766 SvREADONLY_on (coro_current); 2585 SvREADONLY_on (coro_current);
1767 2586
1768 coro_stash = gv_stashpv ("Coro", TRUE); 2587 coro_stash = gv_stashpv ("Coro", TRUE);
1769 2588
1770 newCONSTSUB (coro_stash, "PRIO_MAX", newSViv (PRIO_MAX)); 2589 newCONSTSUB (coro_stash, "PRIO_MAX", newSViv (PRIO_MAX));
1776 2595
1777 for (i = PRIO_MAX - PRIO_MIN + 1; i--; ) 2596 for (i = PRIO_MAX - PRIO_MIN + 1; i--; )
1778 coro_ready[i] = newAV (); 2597 coro_ready[i] = newAV ();
1779 2598
1780 { 2599 {
1781 SV *sv = perl_get_sv ("Coro::API", TRUE); 2600 SV *sv = coro_get_sv (aTHX_ "Coro::API", TRUE);
1782 perl_get_sv ("Coro::API", TRUE); /* silence 5.10 warning */
1783 2601
1784 coroapi.schedule = api_schedule; 2602 coroapi.schedule = api_schedule;
1785 coroapi.cede = api_cede; 2603 coroapi.cede = api_cede;
1786 coroapi.cede_notself = api_cede_notself; 2604 coroapi.cede_notself = api_cede_notself;
1787 coroapi.ready = api_ready; 2605 coroapi.ready = api_ready;
1788 coroapi.is_ready = api_is_ready; 2606 coroapi.is_ready = api_is_ready;
1789 coroapi.nready = &coro_nready; 2607 coroapi.nready = coro_nready;
1790 coroapi.current = coro_current; 2608 coroapi.current = coro_current;
1791 2609
1792 GCoroAPI = &coroapi; 2610 GCoroAPI = &coroapi;
1793 sv_setiv (sv, (IV)&coroapi); 2611 sv_setiv (sv, (IV)&coroapi);
1794 SvREADONLY_on (sv); 2612 SvREADONLY_on (sv);
1795 } 2613 }
1796} 2614}
2615
2616void
2617schedule (...)
2618 CODE:
2619 CORO_EXECUTE_SLF_XS (slf_init_schedule);
2620
2621void
2622cede (...)
2623 CODE:
2624 CORO_EXECUTE_SLF_XS (slf_init_cede);
2625
2626void
2627cede_notself (...)
2628 CODE:
2629 CORO_EXECUTE_SLF_XS (slf_init_cede_notself);
1797 2630
1798void 2631void
1799_set_current (SV *current) 2632_set_current (SV *current)
1800 PROTOTYPE: $ 2633 PROTOTYPE: $
1801 CODE: 2634 CODE:
1802 SvREFCNT_dec (SvRV (coro_current)); 2635 SvREFCNT_dec (SvRV (coro_current));
1803 SvRV_set (coro_current, SvREFCNT_inc (SvRV (current))); 2636 SvRV_set (coro_current, SvREFCNT_inc_NN (SvRV (current)));
2637
2638void
2639_set_readyhook (SV *hook)
2640 PROTOTYPE: $
2641 CODE:
2642 SvREFCNT_dec (coro_readyhook);
2643 coro_readyhook = SvOK (hook) ? newSVsv (hook) : 0;
1804 2644
1805int 2645int
1806prio (Coro::State coro, int newprio = 0) 2646prio (Coro::State coro, int newprio = 0)
2647 PROTOTYPE: $;$
1807 ALIAS: 2648 ALIAS:
1808 nice = 1 2649 nice = 1
1809 CODE: 2650 CODE:
1810{ 2651{
1811 RETVAL = coro->prio; 2652 RETVAL = coro->prio;
1826 2667
1827SV * 2668SV *
1828ready (SV *self) 2669ready (SV *self)
1829 PROTOTYPE: $ 2670 PROTOTYPE: $
1830 CODE: 2671 CODE:
1831 RETVAL = boolSV (api_ready (self)); 2672 RETVAL = boolSV (api_ready (aTHX_ self));
1832 OUTPUT: 2673 OUTPUT:
1833 RETVAL 2674 RETVAL
1834 2675
1835int 2676int
1836nready (...) 2677nready (...)
1838 CODE: 2679 CODE:
1839 RETVAL = coro_nready; 2680 RETVAL = coro_nready;
1840 OUTPUT: 2681 OUTPUT:
1841 RETVAL 2682 RETVAL
1842 2683
1843void
1844throw (Coro::State self, SV *throw = &PL_sv_undef)
1845 PROTOTYPE: $;$
1846 CODE:
1847 SvREFCNT_dec (self->throw);
1848 self->throw = SvOK (throw) ? newSVsv (throw) : 0;
1849
1850# for async_pool speedup 2684# for async_pool speedup
1851void 2685void
1852_pool_1 (SV *cb) 2686_pool_1 (SV *cb)
1853 CODE: 2687 CODE:
1854{ 2688{
1855 struct coro *coro = SvSTATE (coro_current);
1856 HV *hv = (HV *)SvRV (coro_current); 2689 HV *hv = (HV *)SvRV (coro_current);
2690 struct coro *coro = SvSTATE_hv ((SV *)hv);
1857 AV *defav = GvAV (PL_defgv); 2691 AV *defav = GvAV (PL_defgv);
1858 SV *invoke = hv_delete (hv, strpair ("_invoke"), 0); 2692 SV *invoke = hv_delete (hv, "_invoke", sizeof ("_invoke") - 1, 0);
1859 AV *invoke_av; 2693 AV *invoke_av;
1860 int i, len; 2694 int i, len;
1861 2695
1862 if (!invoke) 2696 if (!invoke)
2697 {
2698 SV *old = PL_diehook;
2699 PL_diehook = 0;
2700 SvREFCNT_dec (old);
1863 croak ("\3async_pool terminate\2\n"); 2701 croak ("\3async_pool terminate\2\n");
2702 }
1864 2703
1865 SvREFCNT_dec (coro->saved_deffh); 2704 SvREFCNT_dec (coro->saved_deffh);
1866 coro->saved_deffh = SvREFCNT_inc ((SV *)PL_defoutgv); 2705 coro->saved_deffh = SvREFCNT_inc_NN ((SV *)PL_defoutgv);
1867 2706
1868 hv_store (hv, "desc", sizeof ("desc") - 1, 2707 hv_store (hv, "desc", sizeof ("desc") - 1,
1869 newSVpvn (strpair ("[async_pool]")), 0); 2708 newSVpvn ("[async_pool]", sizeof ("[async_pool]") - 1), 0);
1870 2709
1871 invoke_av = (AV *)SvRV (invoke); 2710 invoke_av = (AV *)SvRV (invoke);
1872 len = av_len (invoke_av); 2711 len = av_len (invoke_av);
1873 2712
1874 sv_setsv (cb, AvARRAY (invoke_av)[0]); 2713 sv_setsv (cb, AvARRAY (invoke_av)[0]);
1875 2714
1876 if (len > 0) 2715 if (len > 0)
1877 { 2716 {
1878 av_fill (defav, len - 1); 2717 av_fill (defav, len - 1);
1879 for (i = 0; i < len; ++i) 2718 for (i = 0; i < len; ++i)
1880 av_store (defav, i, SvREFCNT_inc (AvARRAY (invoke_av)[i + 1])); 2719 av_store (defav, i, SvREFCNT_inc_NN (AvARRAY (invoke_av)[i + 1]));
1881 } 2720 }
1882
1883 SvREFCNT_dec (invoke);
1884} 2721}
1885 2722
1886void 2723void
1887_pool_2 (SV *cb) 2724_pool_2 (SV *cb)
1888 CODE: 2725 CODE:
1889{ 2726{
1890 struct coro *coro = SvSTATE (coro_current); 2727 HV *hv = (HV *)SvRV (coro_current);
2728 struct coro *coro = SvSTATE_hv ((SV *)hv);
1891 2729
1892 sv_setsv (cb, &PL_sv_undef); 2730 sv_setsv (cb, &PL_sv_undef);
1893 2731
1894 SvREFCNT_dec ((SV *)PL_defoutgv); PL_defoutgv = (GV *)coro->saved_deffh; 2732 SvREFCNT_dec ((SV *)PL_defoutgv); PL_defoutgv = (GV *)coro->saved_deffh;
1895 coro->saved_deffh = 0; 2733 coro->saved_deffh = 0;
1896 2734
1897 if (coro_rss (aTHX_ coro) > SvIV (sv_pool_rss) 2735 if (coro_rss (aTHX_ coro) > SvUV (sv_pool_rss)
1898 || av_len (av_async_pool) + 1 >= SvIV (sv_pool_size)) 2736 || av_len (av_async_pool) + 1 >= SvIV (sv_pool_size))
2737 {
2738 SV *old = PL_diehook;
2739 PL_diehook = 0;
2740 SvREFCNT_dec (old);
1899 croak ("\3async_pool terminate\2\n"); 2741 croak ("\3async_pool terminate\2\n");
2742 }
1900 2743
1901 av_clear (GvAV (PL_defgv)); 2744 av_clear (GvAV (PL_defgv));
1902 hv_store ((HV *)SvRV (coro_current), strpair ("desc"), 2745 hv_store (hv, "desc", sizeof ("desc") - 1,
1903 newSVpvn (strpair ("[async_pool idle]")), 0); 2746 newSVpvn ("[async_pool idle]", sizeof ("[async_pool idle]") - 1), 0);
1904 2747
1905 coro->prio = 0; 2748 coro->prio = 0;
1906 2749
1907 if (coro->cctx && (coro->cctx->flags & CC_TRACE)) 2750 if (coro->cctx && (coro->cctx->flags & CC_TRACE))
1908 api_trace (coro_current, 0); 2751 api_trace (aTHX_ coro_current, 0);
1909 2752
1910 av_push (av_async_pool, newSVsv (coro_current)); 2753 av_push (av_async_pool, newSVsv (coro_current));
1911} 2754}
1912 2755
1913 2756
2757MODULE = Coro::State PACKAGE = PerlIO::cede
2758
2759BOOT:
2760 PerlIO_define_layer (aTHX_ &PerlIO_cede);
2761
2762
1914MODULE = Coro::State PACKAGE = Coro::AIO 2763MODULE = Coro::State PACKAGE = Coro::Semaphore
1915 2764
1916SV * 2765SV *
1917_get_state () 2766new (SV *klass, SV *count_ = 0)
1918 CODE: 2767 CODE:
1919{ 2768{
1920 struct io_state *data; 2769 /* a semaphore contains a counter IV in $sem->[0] and any waiters after that */
2770 AV *av = newAV ();
2771 SV **ary;
1921 2772
1922 RETVAL = newSV (sizeof (struct io_state)); 2773 /* unfortunately, building manually saves memory */
1923 data = (struct io_state *)SvPVX (RETVAL); 2774 Newx (ary, 2, SV *);
1924 SvCUR_set (RETVAL, sizeof (struct io_state)); 2775 AvALLOC (av) = ary;
1925 SvPOK_only (RETVAL); 2776 AvARRAY (av) = ary;
2777 AvMAX (av) = 1;
2778 AvFILLp (av) = 0;
2779 ary [0] = newSViv (count_ && SvOK (count_) ? SvIV (count_) : 1);
1926 2780
1927 data->errorno = errno; 2781 RETVAL = sv_bless (newRV_noinc ((SV *)av), GvSTASH (CvGV (cv)));
1928 data->laststype = PL_laststype;
1929 data->laststatval = PL_laststatval;
1930 data->statcache = PL_statcache;
1931} 2782}
1932 OUTPUT: 2783 OUTPUT:
1933 RETVAL 2784 RETVAL
1934 2785
2786SV *
2787count (SV *self)
2788 CODE:
2789 RETVAL = newSVsv (AvARRAY ((AV *)SvRV (self))[0]);
2790 OUTPUT:
2791 RETVAL
2792
1935void 2793void
1936_set_state (char *data_) 2794up (SV *self, int adjust = 1)
1937 PROTOTYPE: $ 2795 ALIAS:
2796 adjust = 1
2797 CODE:
2798 coro_semaphore_adjust (aTHX_ (AV *)SvRV (self), ix ? adjust : 1);
2799
2800void
2801down (SV *self)
2802 CODE:
2803 CORO_EXECUTE_SLF_XS (slf_init_semaphore_down);
2804
2805void
2806try (SV *self)
2807 PPCODE:
2808{
2809 AV *av = (AV *)SvRV (self);
2810 SV *count_sv = AvARRAY (av)[0];
2811 IV count = SvIVX (count_sv);
2812
2813 if (count > 0)
2814 {
2815 --count;
2816 SvIVX (count_sv) = count;
2817 XSRETURN_YES;
2818 }
2819 else
2820 XSRETURN_NO;
2821}
2822
2823void
2824waiters (SV *self)
2825 CODE:
2826{
2827 AV *av = (AV *)SvRV (self);
2828
2829 if (GIMME_V == G_SCALAR)
2830 XPUSHs (sv_2mortal (newSVsv (AvARRAY (av)[0])));
2831 else
2832 {
2833 int i;
2834 EXTEND (SP, AvFILLp (av) + 1 - 1);
2835 for (i = 1; i <= AvFILLp (av); ++i)
2836 PUSHs (sv_2mortal (newRV_inc (AvARRAY (av)[i])));
2837 }
2838}
2839
2840
2841MODULE = Coro::State PACKAGE = Coro::AnyEvent
2842
2843BOOT:
2844 sv_activity = coro_get_sv (aTHX_ "Coro::AnyEvent::ACTIVITY", TRUE);
2845
2846void
2847_schedule (...)
1938 CODE: 2848 CODE:
1939{ 2849{
1940 struct io_state *data = (void *)data_; 2850 static int incede;
1941 2851
1942 errno = data->errorno; 2852 api_cede_notself (aTHX);
1943 PL_laststype = data->laststype;
1944 PL_laststatval = data->laststatval;
1945 PL_statcache = data->statcache;
1946}
1947 2853
2854 ++incede;
2855 while (coro_nready >= incede && api_cede (aTHX))
2856 ;
2857
2858 sv_setsv (sv_activity, &PL_sv_undef);
2859 if (coro_nready >= incede)
2860 {
2861 PUSHMARK (SP);
2862 PUTBACK;
2863 call_pv ("Coro::AnyEvent::_activity", G_KEEPERR | G_EVAL | G_VOID | G_DISCARD);
2864 }
2865
2866 --incede;
2867}
2868
2869
2870MODULE = Coro::State PACKAGE = Coro::AIO
2871
2872void
2873_register (char *target, char *proto, SV *req)
2874 CODE:
2875{
2876 HV *st;
2877 GV *gvp;
2878 CV *req_cv = sv_2cv (req, &st, &gvp, 0);
2879 /* newXSproto doesn't return the CV on 5.8 */
2880 CV *slf_cv = newXS (target, coro_aio_req_xs, __FILE__);
2881 sv_setpv ((SV *)slf_cv, proto);
2882 sv_magicext ((SV *)slf_cv, (SV *)req_cv, CORO_MAGIC_type_aio, 0, 0, 0);
2883}
2884

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines