ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/Coro/State.xs
Revision: 1.254
Committed: Fri Nov 7 20:27:47 2008 UTC (15 years, 6 months ago) by root
Branch: MAIN
Changes since 1.253: +25 -9 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.63 #include "libcoro/coro.c"
2    
3 root 1.146 #define PERL_NO_GET_CONTEXT
4 root 1.198 #define PERL_EXT
5 root 1.146
6 root 1.1 #include "EXTERN.h"
7     #include "perl.h"
8     #include "XSUB.h"
9 root 1.246 #include "perliol.h"
10 root 1.1
11 pcg 1.46 #include "patchlevel.h"
12    
13 root 1.127 #include <stdio.h>
14     #include <errno.h>
15     #include <assert.h>
16 root 1.231
17     #ifdef WIN32
18     # undef setjmp
19     # undef longjmp
20     # undef _exit
21 root 1.232 # define setjmp _setjmp // deep magic, don't ask
22 root 1.231 #else
23     # include <inttypes.h> /* most portable stdint.h */
24     #endif
25 root 1.127
26     #ifdef HAVE_MMAP
27     # include <unistd.h>
28     # include <sys/mman.h>
29     # ifndef MAP_ANONYMOUS
30     # ifdef MAP_ANON
31     # define MAP_ANONYMOUS MAP_ANON
32     # else
33     # undef HAVE_MMAP
34     # endif
35     # endif
36     # include <limits.h>
37     # ifndef PAGESIZE
38     # define PAGESIZE pagesize
39     # define BOOT_PAGESIZE pagesize = sysconf (_SC_PAGESIZE)
40     static long pagesize;
41     # else
42     # define BOOT_PAGESIZE (void)0
43     # endif
44     #else
45     # define PAGESIZE 0
46     # define BOOT_PAGESIZE (void)0
47     #endif
48    
49 root 1.143 #if CORO_USE_VALGRIND
50 root 1.104 # include <valgrind/valgrind.h>
51 root 1.141 # define REGISTER_STACK(cctx,start,end) (cctx)->valgrind_id = VALGRIND_STACK_REGISTER ((start), (end))
52     #else
53     # define REGISTER_STACK(cctx,start,end)
54 root 1.104 #endif
55    
56 root 1.115 /* the maximum number of idle cctx that will be pooled */
57 root 1.254 static int cctx_max_idle = 4;
58 root 1.115
59 root 1.100 #define PERL_VERSION_ATLEAST(a,b,c) \
60     (PERL_REVISION > (a) \
61     || (PERL_REVISION == (a) \
62     && (PERL_VERSION > (b) \
63     || (PERL_VERSION == (b) && PERLSUBVERSION >= (c)))))
64    
65 root 1.102 #if !PERL_VERSION_ATLEAST (5,6,0)
66 pcg 1.46 # ifndef PL_ppaddr
67     # define PL_ppaddr ppaddr
68     # endif
69     # ifndef call_sv
70     # define call_sv perl_call_sv
71     # endif
72     # ifndef get_sv
73     # define get_sv perl_get_sv
74     # endif
75     # ifndef get_cv
76     # define get_cv perl_get_cv
77     # endif
78     # ifndef IS_PADGV
79     # define IS_PADGV(v) 0
80     # endif
81     # ifndef IS_PADCONST
82     # define IS_PADCONST(v) 0
83     # endif
84     #endif
85    
86 root 1.251 /* 5.11 */
87     #ifndef CxHASARGS
88     # define CxHASARGS(cx) (cx)->blk_sub.hasargs
89     #endif
90    
91     /* 5.10.0 */
92     #ifndef SvREFCNT_inc_NN
93     # define SvREFCNT_inc_NN(sv) SvREFCNT_inc (sv)
94     #endif
95    
96 root 1.190 /* 5.8.8 */
97     #ifndef GV_NOTQUAL
98     # define GV_NOTQUAL 0
99     #endif
100 root 1.191 #ifndef newSV
101     # define newSV(l) NEWSV(0,l)
102     #endif
103 root 1.223
104     /* 5.8.7 */
105     #ifndef SvRV_set
106     # define SvRV_set(s,v) SvRV(s) = (v)
107     #endif
108    
109 root 1.78 #if !__i386 && !__x86_64 && !__powerpc && !__m68k && !__alpha && !__mips && !__sparc64
110 root 1.143 # undef CORO_STACKGUARD
111 root 1.78 #endif
112    
113 root 1.143 #ifndef CORO_STACKGUARD
114     # define CORO_STACKGUARD 0
115 root 1.78 #endif
116    
117 root 1.127 /* prefer perl internal functions over our own? */
118 root 1.143 #ifndef CORO_PREFER_PERL_FUNCTIONS
119     # define CORO_PREFER_PERL_FUNCTIONS 0
120 root 1.3 #endif
121    
122 root 1.158 /* The next macros try to return the current stack pointer, in an as
123     * portable way as possible. */
124     #define dSTACKLEVEL volatile char stacklevel
125 root 1.92 #define STACKLEVEL ((void *)&stacklevel)
126 root 1.15
127 root 1.34 #define IN_DESTRUCT (PL_main_cv == Nullcv)
128    
129 root 1.100 #if __GNUC__ >= 3
130     # define attribute(x) __attribute__(x)
131 root 1.131 # define BARRIER __asm__ __volatile__ ("" : : : "memory")
132 root 1.194 # define expect(expr,value) __builtin_expect ((expr),(value))
133 root 1.100 #else
134     # define attribute(x)
135 root 1.131 # define BARRIER
136 root 1.194 # define expect(expr,value) (expr)
137 root 1.100 #endif
138    
139 root 1.194 #define expect_false(expr) expect ((expr) != 0, 0)
140     #define expect_true(expr) expect ((expr) != 0, 1)
141    
142 root 1.100 #define NOINLINE attribute ((noinline))
143    
144 root 1.23 #include "CoroAPI.h"
145    
146 pcg 1.55 #ifdef USE_ITHREADS
147 root 1.253 static perl_mutex coro_lock;
148     # define LOCK do { MUTEX_LOCK (&coro_lock); } while (0)
149     # define UNLOCK do { MUTEX_UNLOCK (&coro_lock); } while (0)
150 pcg 1.55 #else
151 root 1.69 # define LOCK (void)0
152     # define UNLOCK (void)0
153 pcg 1.55 #endif
154    
155 root 1.136 /* helper storage struct for Coro::AIO */
156 root 1.120 struct io_state
157     {
158 root 1.249 AV *res;
159 root 1.120 int errorno;
160     I32 laststype;
161     int laststatval;
162     Stat_t statcache;
163     };
164    
165 root 1.246 static double (*nvtime)(); /* so why doesn't it take void? */
166    
167 root 1.254 static U32 cctx_gen;
168     static size_t cctx_stacksize = CORO_STACKSIZE;
169 root 1.23 static struct CoroAPI coroapi;
170 pcg 1.56 static AV *main_mainstack; /* used to differentiate between $main and others */
171 root 1.148 static JMPENV *main_top_env;
172 root 1.88 static HV *coro_state_stash, *coro_stash;
173 root 1.252 static volatile SV *coro_mortal; /* will be freed/thrown after next transfer */
174 root 1.23
175 root 1.189 static GV *irsgv; /* $/ */
176     static GV *stdoutgv; /* *STDOUT */
177 root 1.214 static SV *rv_diehook;
178     static SV *rv_warnhook;
179 root 1.200 static HV *hv_sig; /* %SIG */
180 root 1.178
181 root 1.159 /* async_pool helper stuff */
182     static SV *sv_pool_rss;
183     static SV *sv_pool_size;
184     static AV *av_async_pool;
185    
186 root 1.233 /* Coro::AnyEvent */
187     static SV *sv_activity;
188    
189 root 1.211 static struct coro_cctx *cctx_first;
190     static int cctx_count, cctx_idle;
191 root 1.107
192 root 1.165 enum {
193 root 1.167 CC_MAPPED = 0x01,
194     CC_NOREUSE = 0x02, /* throw this away after tracing */
195     CC_TRACE = 0x04,
196     CC_TRACE_SUB = 0x08, /* trace sub calls */
197     CC_TRACE_LINE = 0x10, /* trace each statement */
198     CC_TRACE_ALL = CC_TRACE_SUB | CC_TRACE_LINE,
199 root 1.165 };
200    
201 root 1.92 /* this is a structure representing a c-level coroutine */
202 root 1.106 typedef struct coro_cctx {
203     struct coro_cctx *next;
204 root 1.15
205 root 1.93 /* the stack */
206 root 1.15 void *sptr;
207 root 1.145 size_t ssize;
208 root 1.89
209     /* cpu state */
210 root 1.132 void *idle_sp; /* sp of top-level transfer/schedule/cede call */
211     JMPENV *idle_te; /* same as idle_sp, but for top_env, TODO: remove once stable */
212 root 1.93 JMPENV *top_env;
213 root 1.89 coro_context cctx;
214 root 1.104
215 root 1.254 U32 gen;
216 root 1.143 #if CORO_USE_VALGRIND
217 root 1.104 int valgrind_id;
218     #endif
219 root 1.165 unsigned char flags;
220 root 1.106 } coro_cctx;
221 root 1.15
222 root 1.111 enum {
223 root 1.133 CF_RUNNING = 0x0001, /* coroutine is running */
224     CF_READY = 0x0002, /* coroutine is ready */
225     CF_NEW = 0x0004, /* has never been switched to */
226     CF_DESTROYED = 0x0008, /* coroutine data has been freed */
227 root 1.111 };
228    
229 root 1.198 /* the structure where most of the perl state is stored, overlaid on the cxstack */
230     typedef struct {
231     SV *defsv;
232     AV *defav;
233     SV *errsv;
234     SV *irsgv;
235     #define VAR(name,type) type name;
236     # include "state.h"
237     #undef VAR
238     } perl_slots;
239    
240     #define SLOT_COUNT ((sizeof (perl_slots) + sizeof (PERL_CONTEXT) - 1) / sizeof (PERL_CONTEXT))
241    
242 root 1.92 /* this is a structure representing a perl-level coroutine */
243 root 1.1 struct coro {
244 root 1.92 /* the c coroutine allocated to this perl coroutine, if any */
245 root 1.106 coro_cctx *cctx;
246 root 1.92
247 root 1.198 /* process data */
248     AV *mainstack;
249     perl_slots *slot; /* basically the saved sp */
250    
251 root 1.203 AV *args; /* data associated with this coroutine (initial args) */
252     int refcnt; /* coroutines are refcounted, yes */
253     int flags; /* CF_ flags */
254     HV *hv; /* the perl hash associated with this coro, if any */
255 root 1.92
256 root 1.172 /* statistics */
257 root 1.181 int usecount; /* number of transfers to this coro */
258 root 1.172
259 root 1.87 /* coro process data */
260     int prio;
261 root 1.203 SV *throw; /* exception to be thrown */
262 root 1.181
263     /* async_pool */
264 root 1.184 SV *saved_deffh;
265 root 1.151
266     /* linked list */
267     struct coro *next, *prev;
268 root 1.1 };
269    
270     typedef struct coro *Coro__State;
271     typedef struct coro *Coro__State_or_hashref;
272    
273 root 1.137 /** Coro ********************************************************************/
274    
275     #define PRIO_MAX 3
276     #define PRIO_HIGH 1
277     #define PRIO_NORMAL 0
278     #define PRIO_LOW -1
279     #define PRIO_IDLE -3
280     #define PRIO_MIN -4
281    
282     /* for Coro.pm */
283     static SV *coro_current;
284 root 1.233 static SV *coro_readyhook;
285 root 1.137 static AV *coro_ready [PRIO_MAX-PRIO_MIN+1];
286     static int coro_nready;
287 root 1.153 static struct coro *coro_first;
288 root 1.137
289     /** lowlevel stuff **********************************************************/
290    
291 root 1.199 static SV *
292 root 1.213 coro_get_sv (pTHX_ const char *name, int create)
293 root 1.199 {
294 root 1.228 #if PERL_VERSION_ATLEAST (5,10,0)
295 root 1.199 /* silence stupid and wrong 5.10 warning that I am unable to switch off */
296     get_sv (name, create);
297     #endif
298     return get_sv (name, create);
299     }
300    
301 root 1.200 static AV *
302 root 1.213 coro_get_av (pTHX_ const char *name, int create)
303 root 1.199 {
304 root 1.228 #if PERL_VERSION_ATLEAST (5,10,0)
305 root 1.199 /* silence stupid and wrong 5.10 warning that I am unable to switch off */
306     get_av (name, create);
307     #endif
308     return get_av (name, create);
309     }
310    
311 root 1.200 static HV *
312 root 1.213 coro_get_hv (pTHX_ const char *name, int create)
313 root 1.200 {
314 root 1.228 #if PERL_VERSION_ATLEAST (5,10,0)
315 root 1.200 /* silence stupid and wrong 5.10 warning that I am unable to switch off */
316     get_hv (name, create);
317     #endif
318     return get_hv (name, create);
319     }
320    
321 root 1.77 static AV *
322 root 1.146 coro_clone_padlist (pTHX_ CV *cv)
323 root 1.77 {
324     AV *padlist = CvPADLIST (cv);
325     AV *newpadlist, *newpad;
326 root 1.3
327     newpadlist = newAV ();
328     AvREAL_off (newpadlist);
329 root 1.228 #if PERL_VERSION_ATLEAST (5,10,0)
330 root 1.100 Perl_pad_push (aTHX_ padlist, AvFILLp (padlist) + 1);
331     #else
332 root 1.77 Perl_pad_push (aTHX_ padlist, AvFILLp (padlist) + 1, 1);
333 root 1.79 #endif
334 root 1.77 newpad = (AV *)AvARRAY (padlist)[AvFILLp (padlist)];
335     --AvFILLp (padlist);
336 root 1.3
337 root 1.249 av_store (newpadlist, 0, SvREFCNT_inc_NN (*av_fetch (padlist, 0, FALSE)));
338 root 1.77 av_store (newpadlist, 1, (SV *)newpad);
339 root 1.3
340     return newpadlist;
341     }
342    
343 root 1.77 static void
344 root 1.146 free_padlist (pTHX_ AV *padlist)
345 root 1.3 {
346     /* may be during global destruction */
347 pcg 1.50 if (SvREFCNT (padlist))
348 root 1.3 {
349 pcg 1.50 I32 i = AvFILLp (padlist);
350 root 1.3 while (i >= 0)
351     {
352 pcg 1.50 SV **svp = av_fetch (padlist, i--, FALSE);
353     if (svp)
354     {
355     SV *sv;
356     while (&PL_sv_undef != (sv = av_pop ((AV *)*svp)))
357     SvREFCNT_dec (sv);
358    
359     SvREFCNT_dec (*svp);
360     }
361 root 1.3 }
362    
363 pcg 1.50 SvREFCNT_dec ((SV*)padlist);
364     }
365     }
366    
367 root 1.77 static int
368 pcg 1.54 coro_cv_free (pTHX_ SV *sv, MAGIC *mg)
369 pcg 1.50 {
370     AV *padlist;
371     AV *av = (AV *)mg->mg_obj;
372    
373     /* casting is fun. */
374     while (&PL_sv_undef != (SV *)(padlist = (AV *)av_pop (av)))
375 root 1.146 free_padlist (aTHX_ padlist);
376 root 1.61
377 root 1.245 SvREFCNT_dec (av); /* sv_magicext increased the refcount */
378 root 1.244
379 root 1.76 return 0;
380 root 1.3 }
381 pcg 1.50
382 root 1.214 #define CORO_MAGIC_type_cv PERL_MAGIC_ext
383     #define CORO_MAGIC_type_state PERL_MAGIC_ext
384 pcg 1.50
385 root 1.214 static MGVTBL coro_cv_vtbl = {
386     0, 0, 0, 0,
387     coro_cv_free
388     };
389 root 1.3
390 root 1.253 #define CORO_MAGIC(sv, type) \
391     SvMAGIC (sv) \
392     ? SvMAGIC (sv)->mg_type == type \
393     ? SvMAGIC (sv) \
394     : mg_find (sv, type) \
395     : 0
396 root 1.109
397 root 1.214 #define CORO_MAGIC_cv(cv) CORO_MAGIC (((SV *)(cv)), CORO_MAGIC_type_cv)
398     #define CORO_MAGIC_state(sv) CORO_MAGIC (((SV *)(sv)), CORO_MAGIC_type_state)
399    
400 root 1.169 static struct coro *
401     SvSTATE_ (pTHX_ SV *coro)
402     {
403     HV *stash;
404     MAGIC *mg;
405    
406     if (SvROK (coro))
407     coro = SvRV (coro);
408    
409 root 1.194 if (expect_false (SvTYPE (coro) != SVt_PVHV))
410 root 1.172 croak ("Coro::State object required");
411    
412 root 1.169 stash = SvSTASH (coro);
413 root 1.194 if (expect_false (stash != coro_stash && stash != coro_state_stash))
414 root 1.169 {
415     /* very slow, but rare, check */
416     if (!sv_derived_from (sv_2mortal (newRV_inc (coro)), "Coro::State"))
417     croak ("Coro::State object required");
418     }
419    
420 root 1.214 mg = CORO_MAGIC_state (coro);
421 root 1.169 return (struct coro *)mg->mg_ptr;
422     }
423    
424     #define SvSTATE(sv) SvSTATE_ (aTHX_ (sv))
425    
426 root 1.7 /* the next two functions merely cache the padlists */
427 root 1.77 static void
428 root 1.146 get_padlist (pTHX_ CV *cv)
429 root 1.3 {
430 root 1.214 MAGIC *mg = CORO_MAGIC_cv (cv);
431 root 1.109 AV *av;
432 root 1.4
433 root 1.194 if (expect_true (mg && AvFILLp ((av = (AV *)mg->mg_obj)) >= 0))
434 root 1.109 CvPADLIST (cv) = (AV *)AvARRAY (av)[AvFILLp (av)--];
435 root 1.4 else
436 root 1.77 {
437 root 1.143 #if CORO_PREFER_PERL_FUNCTIONS
438 root 1.244 /* this is probably cleaner? but also slower! */
439     /* in practise, it seems to be less stable */
440 root 1.98 CV *cp = Perl_cv_clone (cv);
441 root 1.77 CvPADLIST (cv) = CvPADLIST (cp);
442     CvPADLIST (cp) = 0;
443     SvREFCNT_dec (cp);
444     #else
445 root 1.146 CvPADLIST (cv) = coro_clone_padlist (aTHX_ cv);
446 root 1.77 #endif
447     }
448 root 1.4 }
449    
450 root 1.77 static void
451 root 1.146 put_padlist (pTHX_ CV *cv)
452 root 1.4 {
453 root 1.214 MAGIC *mg = CORO_MAGIC_cv (cv);
454 root 1.109 AV *av;
455 root 1.7
456 root 1.194 if (expect_false (!mg))
457 root 1.214 mg = sv_magicext ((SV *)cv, (SV *)newAV (), CORO_MAGIC_type_cv, &coro_cv_vtbl, 0, 0);
458 root 1.7
459 root 1.109 av = (AV *)mg->mg_obj;
460    
461 root 1.194 if (expect_false (AvFILLp (av) >= AvMAX (av)))
462 root 1.109 av_extend (av, AvMAX (av) + 1);
463    
464     AvARRAY (av)[++AvFILLp (av)] = (SV *)CvPADLIST (cv);
465 root 1.7 }
466    
467 root 1.137 /** load & save, init *******************************************************/
468    
469 root 1.7 static void
470 root 1.146 load_perl (pTHX_ Coro__State c)
471 root 1.7 {
472 root 1.198 perl_slots *slot = c->slot;
473     c->slot = 0;
474    
475     PL_mainstack = c->mainstack;
476 root 1.7
477 root 1.198 GvSV (PL_defgv) = slot->defsv;
478     GvAV (PL_defgv) = slot->defav;
479     GvSV (PL_errgv) = slot->errsv;
480     GvSV (irsgv) = slot->irsgv;
481    
482     #define VAR(name,type) PL_ ## name = slot->name;
483     # include "state.h"
484     #undef VAR
485 root 1.7
486     {
487     dSP;
488 root 1.198
489 root 1.7 CV *cv;
490    
491     /* now do the ugly restore mess */
492 root 1.194 while (expect_true (cv = (CV *)POPs))
493 root 1.7 {
494 root 1.146 put_padlist (aTHX_ cv); /* mark this padlist as available */
495 root 1.109 CvDEPTH (cv) = PTR2IV (POPs);
496     CvPADLIST (cv) = (AV *)POPs;
497 root 1.7 }
498    
499     PUTBACK;
500     }
501     }
502    
503 root 1.3 static void
504 root 1.146 save_perl (pTHX_ Coro__State c)
505 root 1.3 {
506     {
507     dSP;
508     I32 cxix = cxstack_ix;
509 root 1.11 PERL_CONTEXT *ccstk = cxstack;
510 root 1.3 PERL_SI *top_si = PL_curstackinfo;
511    
512     /*
513     * the worst thing you can imagine happens first - we have to save
514     * (and reinitialize) all cv's in the whole callchain :(
515     */
516    
517 root 1.157 XPUSHs (Nullsv);
518 root 1.3 /* this loop was inspired by pp_caller */
519     for (;;)
520     {
521 root 1.194 while (expect_true (cxix >= 0))
522 root 1.3 {
523 root 1.4 PERL_CONTEXT *cx = &ccstk[cxix--];
524 root 1.3
525 root 1.194 if (expect_true (CxTYPE (cx) == CXt_SUB || CxTYPE (cx) == CXt_FORMAT))
526 root 1.3 {
527     CV *cv = cx->blk_sub.cv;
528 root 1.109
529 root 1.194 if (expect_true (CvDEPTH (cv)))
530 root 1.3 {
531 root 1.109 EXTEND (SP, 3);
532 root 1.117 PUSHs ((SV *)CvPADLIST (cv));
533 root 1.233 PUSHs (INT2PTR (SV *, (IV)CvDEPTH (cv)));
534 root 1.3 PUSHs ((SV *)cv);
535    
536 root 1.109 CvDEPTH (cv) = 0;
537 root 1.146 get_padlist (aTHX_ cv);
538 root 1.3 }
539     }
540     }
541    
542 root 1.194 if (expect_true (top_si->si_type == PERLSI_MAIN))
543 root 1.3 break;
544    
545     top_si = top_si->si_prev;
546 root 1.158 ccstk = top_si->si_cxstack;
547     cxix = top_si->si_cxix;
548 root 1.3 }
549    
550     PUTBACK;
551     }
552    
553 root 1.198 /* allocate some space on the context stack for our purposes */
554 root 1.202 /* we manually unroll here, as usually 2 slots is enough */
555     if (SLOT_COUNT >= 1) CXINC;
556     if (SLOT_COUNT >= 2) CXINC;
557     if (SLOT_COUNT >= 3) CXINC;
558 root 1.198 {
559     int i;
560     for (i = 3; i < SLOT_COUNT; ++i)
561     CXINC;
562     }
563 root 1.202 cxstack_ix -= SLOT_COUNT; /* undo allocation */
564 root 1.198
565     c->mainstack = PL_mainstack;
566    
567     {
568     perl_slots *slot = c->slot = (perl_slots *)(cxstack + cxstack_ix + 1);
569    
570     slot->defav = GvAV (PL_defgv);
571     slot->defsv = DEFSV;
572     slot->errsv = ERRSV;
573     slot->irsgv = GvSV (irsgv);
574    
575     #define VAR(name,type) slot->name = PL_ ## name;
576     # include "state.h"
577     #undef VAR
578     }
579 root 1.13 }
580    
581     /*
582     * allocate various perl stacks. This is an exact copy
583     * of perl.c:init_stacks, except that it uses less memory
584 pcg 1.52 * on the (sometimes correct) assumption that coroutines do
585     * not usually need a lot of stackspace.
586 root 1.13 */
587 root 1.204 #if CORO_PREFER_PERL_FUNCTIONS
588 root 1.126 # define coro_init_stacks init_stacks
589     #else
590 root 1.77 static void
591 root 1.146 coro_init_stacks (pTHX)
592 root 1.13 {
593 root 1.198 PL_curstackinfo = new_stackinfo(32, 8);
594 root 1.13 PL_curstackinfo->si_type = PERLSI_MAIN;
595     PL_curstack = PL_curstackinfo->si_stack;
596     PL_mainstack = PL_curstack; /* remember in case we switch stacks */
597    
598     PL_stack_base = AvARRAY(PL_curstack);
599     PL_stack_sp = PL_stack_base;
600     PL_stack_max = PL_stack_base + AvMAX(PL_curstack);
601    
602 root 1.198 New(50,PL_tmps_stack,32,SV*);
603 root 1.13 PL_tmps_floor = -1;
604     PL_tmps_ix = -1;
605 root 1.198 PL_tmps_max = 32;
606 root 1.13
607 root 1.154 New(54,PL_markstack,16,I32);
608 root 1.13 PL_markstack_ptr = PL_markstack;
609 root 1.154 PL_markstack_max = PL_markstack + 16;
610 root 1.13
611 pcg 1.46 #ifdef SET_MARK_OFFSET
612 root 1.13 SET_MARK_OFFSET;
613 pcg 1.46 #endif
614 root 1.13
615 root 1.198 New(54,PL_scopestack,8,I32);
616 root 1.13 PL_scopestack_ix = 0;
617 root 1.198 PL_scopestack_max = 8;
618 root 1.13
619 root 1.198 New(54,PL_savestack,24,ANY);
620 root 1.13 PL_savestack_ix = 0;
621 root 1.198 PL_savestack_max = 24;
622 root 1.13
623 root 1.228 #if !PERL_VERSION_ATLEAST (5,10,0)
624 root 1.156 New(54,PL_retstack,4,OP*);
625 root 1.13 PL_retstack_ix = 0;
626 root 1.156 PL_retstack_max = 4;
627 root 1.71 #endif
628 root 1.3 }
629 root 1.127 #endif
630 root 1.1
631 root 1.7 /*
632     * destroy the stacks, the callchain etc...
633     */
634 root 1.77 static void
635 root 1.253 coro_destruct_stacks (pTHX)
636 root 1.1 {
637 root 1.4 while (PL_curstackinfo->si_next)
638     PL_curstackinfo = PL_curstackinfo->si_next;
639    
640     while (PL_curstackinfo)
641     {
642     PERL_SI *p = PL_curstackinfo->si_prev;
643    
644 root 1.34 if (!IN_DESTRUCT)
645 root 1.126 SvREFCNT_dec (PL_curstackinfo->si_stack);
646 root 1.7
647 pcg 1.57 Safefree (PL_curstackinfo->si_cxstack);
648     Safefree (PL_curstackinfo);
649 root 1.4 PL_curstackinfo = p;
650     }
651    
652 pcg 1.57 Safefree (PL_tmps_stack);
653     Safefree (PL_markstack);
654     Safefree (PL_scopestack);
655     Safefree (PL_savestack);
656 root 1.228 #if !PERL_VERSION_ATLEAST (5,10,0)
657 pcg 1.57 Safefree (PL_retstack);
658 root 1.71 #endif
659 root 1.1 }
660    
661 root 1.152 static size_t
662 root 1.171 coro_rss (pTHX_ struct coro *coro)
663 root 1.152 {
664 root 1.183 size_t rss = sizeof (*coro);
665 root 1.152
666     if (coro->mainstack)
667     {
668 root 1.198 perl_slots tmp_slot;
669     perl_slots *slot;
670    
671 root 1.153 if (coro->flags & CF_RUNNING)
672     {
673 root 1.198 slot = &tmp_slot;
674    
675     #define VAR(name,type) slot->name = PL_ ## name;
676 root 1.153 # include "state.h"
677     #undef VAR
678     }
679 root 1.198 else
680     slot = coro->slot;
681 root 1.153
682 root 1.245 if (slot)
683     {
684     rss += sizeof (slot->curstackinfo);
685     rss += (slot->curstackinfo->si_cxmax + 1) * sizeof (PERL_CONTEXT);
686     rss += sizeof (SV) + sizeof (struct xpvav) + (1 + AvMAX (slot->curstack)) * sizeof (SV *);
687     rss += slot->tmps_max * sizeof (SV *);
688     rss += (slot->markstack_max - slot->markstack_ptr) * sizeof (I32);
689     rss += slot->scopestack_max * sizeof (I32);
690     rss += slot->savestack_max * sizeof (ANY);
691 root 1.152
692 root 1.228 #if !PERL_VERSION_ATLEAST (5,10,0)
693 root 1.245 rss += slot->retstack_max * sizeof (OP *);
694 root 1.152 #endif
695 root 1.245 }
696 root 1.152 }
697    
698     return rss;
699     }
700    
701 root 1.137 /** coroutine stack handling ************************************************/
702    
703 root 1.214 static int (*orig_sigelem_get) (pTHX_ SV *sv, MAGIC *mg);
704 root 1.220 static int (*orig_sigelem_set) (pTHX_ SV *sv, MAGIC *mg);
705 root 1.239 static int (*orig_sigelem_clr) (pTHX_ SV *sv, MAGIC *mg);
706 root 1.214
707 root 1.238 /* apparently < 5.8.8 */
708     #ifndef MgPV_nolen_const
709     #define MgPV_nolen_const(mg) (((((int)(mg)->mg_len)) == HEf_SVKEY) ? \
710 root 1.241 SvPV_nolen((SV*)((mg)->mg_ptr)) : \
711 root 1.238 (const char*)(mg)->mg_ptr)
712     #endif
713    
714 root 1.214 /*
715     * This overrides the default magic get method of %SIG elements.
716     * The original one doesn't provide for reading back of PL_diehook/PL_warnhook
717     * and instead of tryign to save and restore the hash elements, we just provide
718     * readback here.
719     * We only do this when the hook is != 0, as they are often set to 0 temporarily,
720     * not expecting this to actually change the hook. This is a potential problem
721     * when a schedule happens then, but we ignore this.
722     */
723     static int
724     coro_sigelem_get (pTHX_ SV *sv, MAGIC *mg)
725     {
726     const char *s = MgPV_nolen_const (mg);
727    
728     if (*s == '_')
729     {
730 root 1.239 SV **svp = 0;
731    
732     if (strEQ (s, "__DIE__" )) svp = &PL_diehook;
733     if (strEQ (s, "__WARN__")) svp = &PL_warnhook;
734    
735     if (svp)
736     {
737     sv_setsv (sv, *svp ? *svp : &PL_sv_undef);
738     return 0;
739     }
740 root 1.214 }
741    
742 root 1.220 return orig_sigelem_get ? orig_sigelem_get (aTHX_ sv, mg) : 0;
743     }
744    
745     static int
746 root 1.239 coro_sigelem_clr (pTHX_ SV *sv, MAGIC *mg)
747     {
748     const char *s = MgPV_nolen_const (mg);
749    
750     if (*s == '_')
751     {
752     SV **svp = 0;
753    
754     if (strEQ (s, "__DIE__" )) svp = &PL_diehook;
755     if (strEQ (s, "__WARN__")) svp = &PL_warnhook;
756    
757     if (svp)
758     {
759     SV *old = *svp;
760     *svp = 0;
761     SvREFCNT_dec (old);
762     return 0;
763     }
764     }
765    
766     return orig_sigelem_clr ? orig_sigelem_clr (aTHX_ sv, mg) : 0;
767     }
768    
769     static int
770 root 1.220 coro_sigelem_set (pTHX_ SV *sv, MAGIC *mg)
771     {
772     const char *s = MgPV_nolen_const (mg);
773    
774     if (*s == '_')
775     {
776     SV **svp = 0;
777    
778     if (strEQ (s, "__DIE__" )) svp = &PL_diehook;
779     if (strEQ (s, "__WARN__")) svp = &PL_warnhook;
780    
781     if (svp)
782     {
783     SV *old = *svp;
784     *svp = newSVsv (sv);
785     SvREFCNT_dec (old);
786 root 1.231 return 0;
787 root 1.220 }
788     }
789    
790     return orig_sigelem_set ? orig_sigelem_set (aTHX_ sv, mg) : 0;
791 root 1.214 }
792    
793 root 1.13 static void
794 root 1.179 coro_setup (pTHX_ struct coro *coro)
795 root 1.13 {
796 root 1.89 /*
797     * emulate part of the perl startup here.
798     */
799 root 1.146 coro_init_stacks (aTHX);
800 root 1.15
801 root 1.169 PL_runops = RUNOPS_DEFAULT;
802 root 1.117 PL_curcop = &PL_compiling;
803     PL_in_eval = EVAL_NULL;
804 root 1.142 PL_comppad = 0;
805 root 1.117 PL_curpm = 0;
806 root 1.196 PL_curpad = 0;
807 root 1.117 PL_localizing = 0;
808     PL_dirty = 0;
809     PL_restartop = 0;
810 root 1.229 #if PERL_VERSION_ATLEAST (5,10,0)
811 root 1.228 PL_parser = 0;
812     #endif
813 root 1.214
814     /* recreate the die/warn hooks */
815 root 1.220 PL_diehook = 0; SvSetMagicSV (*hv_fetch (hv_sig, "__DIE__" , sizeof ("__DIE__" ) - 1, 1), rv_diehook );
816     PL_warnhook = 0; SvSetMagicSV (*hv_fetch (hv_sig, "__WARN__", sizeof ("__WARN__") - 1, 1), rv_warnhook);
817 root 1.178
818 root 1.191 GvSV (PL_defgv) = newSV (0);
819 root 1.178 GvAV (PL_defgv) = coro->args; coro->args = 0;
820 root 1.191 GvSV (PL_errgv) = newSV (0);
821 root 1.180 GvSV (irsgv) = newSVpvn ("\n", 1); sv_magic (GvSV (irsgv), (SV *)irsgv, PERL_MAGIC_sv, "/", 0);
822 root 1.179 PL_rs = newSVsv (GvSV (irsgv));
823 root 1.249 PL_defoutgv = (GV *)SvREFCNT_inc_NN (stdoutgv);
824 root 1.103
825 root 1.102 {
826     dSP;
827     LOGOP myop;
828    
829     Zero (&myop, 1, LOGOP);
830     myop.op_next = Nullop;
831     myop.op_flags = OPf_WANT_VOID;
832 root 1.89
833 root 1.102 PUSHMARK (SP);
834 root 1.192 XPUSHs (sv_2mortal (av_shift (GvAV (PL_defgv))));
835 root 1.102 PUTBACK;
836 root 1.120 PL_op = (OP *)&myop;
837 root 1.102 PL_op = PL_ppaddr[OP_ENTERSUB](aTHX);
838     SPAGAIN;
839 root 1.117 }
840 root 1.210
841     /* this newly created coroutine might be run on an existing cctx which most
842     * likely was suspended in set_stacklevel, called from entersub.
843     * set_stacklevl doesn't do anything on return, but entersub does LEAVE,
844     * so we ENTER here for symmetry
845     */
846     ENTER;
847 root 1.13 }
848    
849     static void
850 root 1.253 coro_destruct (pTHX_ struct coro *coro)
851 root 1.178 {
852     if (!IN_DESTRUCT)
853     {
854     /* restore all saved variables and stuff */
855     LEAVE_SCOPE (0);
856     assert (PL_tmps_floor == -1);
857    
858     /* free all temporaries */
859     FREETMPS;
860     assert (PL_tmps_ix == -1);
861    
862     /* unwind all extra stacks */
863     POPSTACK_TO (PL_mainstack);
864    
865     /* unwind main stack */
866     dounwind (-1);
867     }
868    
869     SvREFCNT_dec (GvSV (PL_defgv));
870     SvREFCNT_dec (GvAV (PL_defgv));
871     SvREFCNT_dec (GvSV (PL_errgv));
872 root 1.180 SvREFCNT_dec (PL_defoutgv);
873 root 1.178 SvREFCNT_dec (PL_rs);
874     SvREFCNT_dec (GvSV (irsgv));
875    
876 root 1.198 SvREFCNT_dec (PL_diehook);
877     SvREFCNT_dec (PL_warnhook);
878    
879 root 1.184 SvREFCNT_dec (coro->saved_deffh);
880 root 1.196 SvREFCNT_dec (coro->throw);
881 root 1.181
882 root 1.253 coro_destruct_stacks (aTHX);
883 root 1.178 }
884    
885     static void
886 root 1.146 free_coro_mortal (pTHX)
887 root 1.13 {
888 root 1.194 if (expect_true (coro_mortal))
889 root 1.15 {
890 root 1.89 SvREFCNT_dec (coro_mortal);
891     coro_mortal = 0;
892     }
893 root 1.13 }
894    
895 root 1.165 static int
896 root 1.169 runops_trace (pTHX)
897 root 1.165 {
898     COP *oldcop = 0;
899 root 1.167 int oldcxix = -2;
900 root 1.169 struct coro *coro = SvSTATE (coro_current); /* trace cctx is tied to specific coro */
901     coro_cctx *cctx = coro->cctx;
902 root 1.165
903     while ((PL_op = CALL_FPTR (PL_op->op_ppaddr) (aTHX)))
904     {
905     PERL_ASYNC_CHECK ();
906    
907 root 1.173 if (cctx->flags & CC_TRACE_ALL)
908 root 1.167 {
909 root 1.173 if (PL_op->op_type == OP_LEAVESUB && cctx->flags & CC_TRACE_SUB)
910     {
911     PERL_CONTEXT *cx = &cxstack[cxstack_ix];
912     SV **bot, **top;
913     AV *av = newAV (); /* return values */
914     SV **cb;
915     dSP;
916 root 1.167
917 root 1.173 GV *gv = CvGV (cx->blk_sub.cv);
918     SV *fullname = sv_2mortal (newSV (0));
919     if (isGV (gv))
920     gv_efullname3 (fullname, gv, 0);
921    
922     bot = PL_stack_base + cx->blk_oldsp + 1;
923     top = cx->blk_gimme == G_ARRAY ? SP + 1
924     : cx->blk_gimme == G_SCALAR ? bot + 1
925     : bot;
926 root 1.167
927 root 1.193 av_extend (av, top - bot);
928 root 1.173 while (bot < top)
929 root 1.249 av_push (av, SvREFCNT_inc_NN (*bot++));
930 root 1.167
931 root 1.173 PL_runops = RUNOPS_DEFAULT;
932 root 1.167 ENTER;
933     SAVETMPS;
934     EXTEND (SP, 3);
935 root 1.173 PUSHMARK (SP);
936     PUSHs (&PL_sv_no);
937     PUSHs (fullname);
938     PUSHs (sv_2mortal (newRV_noinc ((SV *)av)));
939     PUTBACK;
940 root 1.212 cb = hv_fetch ((HV *)SvRV (coro_current), "_trace_sub_cb", sizeof ("_trace_sub_cb") - 1, 0);
941 root 1.173 if (cb) call_sv (*cb, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD);
942     SPAGAIN;
943     FREETMPS;
944     LEAVE;
945     PL_runops = runops_trace;
946     }
947    
948     if (oldcop != PL_curcop)
949     {
950     oldcop = PL_curcop;
951 root 1.167
952 root 1.173 if (PL_curcop != &PL_compiling)
953 root 1.167 {
954 root 1.173 SV **cb;
955    
956     if (oldcxix != cxstack_ix && cctx->flags & CC_TRACE_SUB)
957     {
958     PERL_CONTEXT *cx = &cxstack[cxstack_ix];
959    
960     if (CxTYPE (cx) == CXt_SUB && oldcxix < cxstack_ix)
961     {
962     runops_proc_t old_runops = PL_runops;
963     dSP;
964     GV *gv = CvGV (cx->blk_sub.cv);
965     SV *fullname = sv_2mortal (newSV (0));
966    
967     if (isGV (gv))
968     gv_efullname3 (fullname, gv, 0);
969    
970     PL_runops = RUNOPS_DEFAULT;
971     ENTER;
972     SAVETMPS;
973     EXTEND (SP, 3);
974     PUSHMARK (SP);
975     PUSHs (&PL_sv_yes);
976     PUSHs (fullname);
977 root 1.223 PUSHs (CxHASARGS (cx) ? sv_2mortal (newRV_inc ((SV *)cx->blk_sub.argarray)) : &PL_sv_undef);
978 root 1.173 PUTBACK;
979 root 1.212 cb = hv_fetch ((HV *)SvRV (coro_current), "_trace_sub_cb", sizeof ("_trace_sub_cb") - 1, 0);
980 root 1.173 if (cb) call_sv (*cb, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD);
981     SPAGAIN;
982     FREETMPS;
983     LEAVE;
984     PL_runops = runops_trace;
985     }
986    
987     oldcxix = cxstack_ix;
988     }
989 root 1.167
990 root 1.173 if (cctx->flags & CC_TRACE_LINE)
991 root 1.167 {
992 root 1.173 dSP;
993 root 1.167
994 root 1.173 PL_runops = RUNOPS_DEFAULT;
995     ENTER;
996     SAVETMPS;
997     EXTEND (SP, 3);
998     PL_runops = RUNOPS_DEFAULT;
999 root 1.167 PUSHMARK (SP);
1000 root 1.173 PUSHs (sv_2mortal (newSVpv (OutCopFILE (oldcop), 0)));
1001     PUSHs (sv_2mortal (newSViv (CopLINE (oldcop))));
1002 root 1.167 PUTBACK;
1003 root 1.212 cb = hv_fetch ((HV *)SvRV (coro_current), "_trace_line_cb", sizeof ("_trace_line_cb") - 1, 0);
1004 root 1.169 if (cb) call_sv (*cb, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD);
1005 root 1.167 SPAGAIN;
1006 root 1.173 FREETMPS;
1007     LEAVE;
1008     PL_runops = runops_trace;
1009 root 1.167 }
1010 root 1.169 }
1011 root 1.167 }
1012 root 1.165 }
1013     }
1014    
1015     TAINT_NOT;
1016     return 0;
1017     }
1018    
1019 root 1.120 /* inject a fake call to Coro::State::_cctx_init into the execution */
1020 root 1.150 /* _cctx_init should be careful, as it could be called at almost any time */
1021     /* during execution of a perl program */
1022 root 1.100 static void NOINLINE
1023 root 1.201 cctx_prepare (pTHX_ coro_cctx *cctx)
1024 root 1.99 {
1025     dSP;
1026 root 1.102 LOGOP myop;
1027 root 1.99
1028 root 1.165 PL_top_env = &PL_start_env;
1029    
1030     if (cctx->flags & CC_TRACE)
1031 root 1.169 PL_runops = runops_trace;
1032 root 1.165
1033 root 1.102 Zero (&myop, 1, LOGOP);
1034 root 1.99 myop.op_next = PL_op;
1035 root 1.120 myop.op_flags = OPf_WANT_VOID | OPf_STACKED;
1036 root 1.102
1037     PUSHMARK (SP);
1038 root 1.120 EXTEND (SP, 2);
1039     PUSHs (sv_2mortal (newSViv (PTR2IV (cctx))));
1040     PUSHs ((SV *)get_cv ("Coro::State::_cctx_init", FALSE));
1041 root 1.99 PUTBACK;
1042 root 1.120 PL_op = (OP *)&myop;
1043     PL_op = PL_ppaddr[OP_ENTERSUB](aTHX);
1044 root 1.99 SPAGAIN;
1045     }
1046    
1047 root 1.148 /*
1048     * this is a _very_ stripped down perl interpreter ;)
1049     */
1050 root 1.99 static void
1051 root 1.201 cctx_run (void *arg)
1052 root 1.13 {
1053 root 1.146 dTHX;
1054    
1055 root 1.201 /* cctx_run is the alternative tail of transfer(), so unlock here. */
1056 root 1.102 UNLOCK;
1057    
1058 root 1.165 /* we now skip the entersub that lead to transfer() */
1059     PL_op = PL_op->op_next;
1060 root 1.107
1061 root 1.148 /* inject a fake subroutine call to cctx_init */
1062 root 1.201 cctx_prepare (aTHX_ (coro_cctx *)arg);
1063 root 1.89
1064 root 1.148 /* somebody or something will hit me for both perl_run and PL_restartop */
1065 root 1.120 PL_restartop = PL_op;
1066 root 1.102 perl_run (PL_curinterp);
1067 root 1.89
1068 root 1.149 /*
1069     * If perl-run returns we assume exit() was being called or the coro
1070     * fell off the end, which seems to be the only valid (non-bug)
1071     * reason for perl_run to return. We try to exit by jumping to the
1072     * bootstrap-time "top" top_env, as we cannot restore the "main"
1073     * coroutine as Coro has no such concept
1074     */
1075 root 1.148 PL_top_env = main_top_env;
1076     JMPENV_JUMP (2); /* I do not feel well about the hardcoded 2 at all */
1077 root 1.89 }
1078    
1079 root 1.106 static coro_cctx *
1080     cctx_new ()
1081 root 1.89 {
1082 root 1.106 coro_cctx *cctx;
1083 root 1.145 void *stack_start;
1084     size_t stack_size;
1085 root 1.89
1086 root 1.107 ++cctx_count;
1087 root 1.124 Newz (0, cctx, 1, coro_cctx);
1088 root 1.89
1089 root 1.254 cctx->gen = cctx_gen;
1090    
1091 root 1.89 #if HAVE_MMAP
1092 root 1.254 cctx->ssize = ((cctx_stacksize * sizeof (long) + PAGESIZE - 1) / PAGESIZE + CORO_STACKGUARD) * PAGESIZE;
1093 root 1.120 /* mmap supposedly does allocate-on-write for us */
1094 root 1.106 cctx->sptr = mmap (0, cctx->ssize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);
1095 root 1.19
1096 root 1.141 if (cctx->sptr != (void *)-1)
1097 root 1.13 {
1098 root 1.143 # if CORO_STACKGUARD
1099     mprotect (cctx->sptr, CORO_STACKGUARD * PAGESIZE, PROT_NONE);
1100 root 1.94 # endif
1101 root 1.145 stack_start = CORO_STACKGUARD * PAGESIZE + (char *)cctx->sptr;
1102     stack_size = cctx->ssize - CORO_STACKGUARD * PAGESIZE;
1103 root 1.165 cctx->flags |= CC_MAPPED;
1104 root 1.141 }
1105     else
1106     #endif
1107 root 1.89 {
1108 root 1.254 cctx->ssize = cctx_stacksize * (long)sizeof (long);
1109     New (0, cctx->sptr, cctx_stacksize, long);
1110 root 1.13
1111 root 1.141 if (!cctx->sptr)
1112     {
1113     perror ("FATAL: unable to allocate stack for coroutine");
1114     _exit (EXIT_FAILURE);
1115     }
1116 root 1.89
1117 root 1.145 stack_start = cctx->sptr;
1118     stack_size = cctx->ssize;
1119     }
1120 root 1.104
1121 root 1.145 REGISTER_STACK (cctx, (char *)stack_start, (char *)stack_start + stack_size);
1122 root 1.201 coro_create (&cctx->cctx, cctx_run, (void *)cctx, stack_start, stack_size);
1123 root 1.13
1124 root 1.106 return cctx;
1125 root 1.13 }
1126    
1127 root 1.15 static void
1128 root 1.115 cctx_destroy (coro_cctx *cctx)
1129 root 1.15 {
1130 root 1.106 if (!cctx)
1131 root 1.89 return;
1132    
1133 root 1.107 --cctx_count;
1134 root 1.253 coro_destroy (&cctx->cctx);
1135 root 1.107
1136 root 1.253 /* coro_transfer creates new, empty cctx's */
1137     if (cctx->sptr)
1138     {
1139 root 1.143 #if CORO_USE_VALGRIND
1140 root 1.253 VALGRIND_STACK_DEREGISTER (cctx->valgrind_id);
1141 root 1.104 #endif
1142    
1143 root 1.89 #if HAVE_MMAP
1144 root 1.253 if (cctx->flags & CC_MAPPED)
1145     munmap (cctx->sptr, cctx->ssize);
1146     else
1147 root 1.89 #endif
1148 root 1.253 Safefree (cctx->sptr);
1149     }
1150 root 1.89
1151 root 1.106 Safefree (cctx);
1152 root 1.89 }
1153 root 1.32
1154 root 1.193 /* wether this cctx should be destructed */
1155 root 1.254 #define CCTX_EXPIRED(cctx) ((cctx)->gen != cctx_gen || ((cctx)->flags & CC_NOREUSE))
1156 root 1.193
1157 root 1.106 static coro_cctx *
1158 root 1.211 cctx_get (pTHX)
1159 root 1.89 {
1160 root 1.211 while (expect_true (cctx_first))
1161 root 1.89 {
1162 root 1.211 coro_cctx *cctx = cctx_first;
1163     cctx_first = cctx->next;
1164     --cctx_idle;
1165 root 1.145
1166 root 1.194 if (expect_true (!CCTX_EXPIRED (cctx)))
1167 root 1.145 return cctx;
1168    
1169     cctx_destroy (cctx);
1170 root 1.89 }
1171 root 1.91
1172 root 1.145 return cctx_new ();
1173 root 1.89 }
1174 root 1.19
1175 root 1.89 static void
1176 root 1.211 cctx_put (coro_cctx *cctx)
1177 root 1.89 {
1178 root 1.253 assert (("cctx_put called on non-initialised cctx", cctx->sptr));
1179    
1180 root 1.115 /* free another cctx if overlimit */
1181 root 1.254 if (expect_false (cctx_idle >= cctx_max_idle))
1182 root 1.115 {
1183 root 1.211 coro_cctx *first = cctx_first;
1184     cctx_first = first->next;
1185     --cctx_idle;
1186 root 1.115
1187     cctx_destroy (first);
1188     }
1189    
1190 root 1.211 ++cctx_idle;
1191     cctx->next = cctx_first;
1192     cctx_first = cctx;
1193 root 1.15 }
1194    
1195 root 1.137 /** coroutine switching *****************************************************/
1196    
1197 root 1.194 static void
1198 root 1.170 transfer_check (pTHX_ struct coro *prev, struct coro *next)
1199     {
1200 root 1.194 if (expect_true (prev != next))
1201 root 1.170 {
1202 root 1.194 if (expect_false (!(prev->flags & (CF_RUNNING | CF_NEW))))
1203 root 1.170 croak ("Coro::State::transfer called with non-running/new prev Coro::State, but can only transfer from running or new states");
1204    
1205 root 1.194 if (expect_false (next->flags & CF_RUNNING))
1206 root 1.170 croak ("Coro::State::transfer called with running next Coro::State, but can only transfer to inactive states");
1207    
1208 root 1.194 if (expect_false (next->flags & CF_DESTROYED))
1209 root 1.170 croak ("Coro::State::transfer called with destroyed next Coro::State, but can only transfer to inactive states");
1210    
1211 root 1.228 #if !PERL_VERSION_ATLEAST (5,10,0)
1212 root 1.230 if (expect_false (PL_lex_state != LEX_NOTPARSING))
1213 root 1.229 croak ("Coro::State::transfer called while parsing, but this is not supported in your perl version");
1214 root 1.198 #endif
1215 root 1.170 }
1216     }
1217    
1218     /* always use the TRANSFER macro */
1219 root 1.100 static void NOINLINE
1220 root 1.227 transfer (pTHX_ struct coro *prev, struct coro *next, int force_cctx)
1221 root 1.8 {
1222 root 1.15 dSTACKLEVEL;
1223 root 1.8
1224 root 1.89 /* sometimes transfer is only called to set idle_sp */
1225 root 1.194 if (expect_false (!next))
1226 root 1.124 {
1227     ((coro_cctx *)prev)->idle_sp = STACKLEVEL;
1228 root 1.132 assert (((coro_cctx *)prev)->idle_te = PL_top_env); /* just for the side-effect when asserts are enabled */
1229 root 1.124 }
1230 root 1.194 else if (expect_true (prev != next))
1231 root 1.8 {
1232 root 1.252 static volatile int has_throw;
1233 root 1.106 coro_cctx *prev__cctx;
1234 root 1.89
1235 root 1.194 if (expect_false (prev->flags & CF_NEW))
1236 root 1.111 {
1237 root 1.253 /* create a new empty/source context */
1238     ++cctx_count;
1239     New (0, prev->cctx, 1, coro_cctx);
1240     prev->cctx->sptr = 0;
1241     coro_create (&prev->cctx->cctx, 0, 0, 0, 0);
1242    
1243 root 1.117 prev->flags &= ~CF_NEW;
1244     prev->flags |= CF_RUNNING;
1245 root 1.111 }
1246    
1247     prev->flags &= ~CF_RUNNING;
1248     next->flags |= CF_RUNNING;
1249    
1250 root 1.92 LOCK;
1251 root 1.13
1252 root 1.214 /* first get rid of the old state */
1253     save_perl (aTHX_ prev);
1254    
1255 root 1.194 if (expect_false (next->flags & CF_NEW))
1256 root 1.90 {
1257     /* need to start coroutine */
1258 root 1.117 next->flags &= ~CF_NEW;
1259 root 1.89 /* setup coroutine call */
1260 root 1.179 coro_setup (aTHX_ next);
1261 root 1.8 }
1262 root 1.118 else
1263 root 1.214 load_perl (aTHX_ next);
1264 root 1.15
1265 root 1.106 prev__cctx = prev->cctx;
1266 root 1.92
1267 root 1.106 /* possibly "free" the cctx */
1268 root 1.227 if (expect_true (
1269     prev__cctx->idle_sp == STACKLEVEL
1270     && !(prev__cctx->flags & CC_TRACE)
1271     && !force_cctx
1272     ))
1273 root 1.92 {
1274 root 1.114 /* I assume that STACKLEVEL is a stronger indicator than PL_top_env changes */
1275 root 1.132 assert (("ERROR: current top_env must equal previous top_env", PL_top_env == prev__cctx->idle_te));
1276 root 1.112
1277 root 1.117 prev->cctx = 0;
1278    
1279 root 1.193 /* if the cctx is about to be destroyed we need to make sure we won't see it in cctx_get */
1280 root 1.194 /* without this the next cctx_get might destroy the prev__cctx while still in use */
1281     if (expect_false (CCTX_EXPIRED (prev__cctx)))
1282 root 1.201 if (!next->cctx)
1283 root 1.211 next->cctx = cctx_get (aTHX);
1284 root 1.193
1285 root 1.211 cctx_put (prev__cctx);
1286 root 1.92 }
1287    
1288 root 1.172 ++next->usecount;
1289    
1290 root 1.194 if (expect_true (!next->cctx))
1291 root 1.211 next->cctx = cctx_get (aTHX);
1292 root 1.111
1293 root 1.216 has_throw = !!next->throw;
1294    
1295 root 1.194 if (expect_false (prev__cctx != next->cctx))
1296 root 1.117 {
1297 root 1.106 prev__cctx->top_env = PL_top_env;
1298     PL_top_env = next->cctx->top_env;
1299     coro_transfer (&prev__cctx->cctx, &next->cctx->cctx);
1300 root 1.92 }
1301    
1302 root 1.146 free_coro_mortal (aTHX);
1303 root 1.92 UNLOCK;
1304 root 1.196
1305 root 1.216 if (expect_false (has_throw))
1306 root 1.196 {
1307     struct coro *coro = SvSTATE (coro_current);
1308    
1309     if (coro->throw)
1310     {
1311     SV *exception = coro->throw;
1312     coro->throw = 0;
1313     sv_setsv (ERRSV, exception);
1314     croak (0);
1315     }
1316     }
1317 root 1.8 }
1318 root 1.39 }
1319 root 1.23
1320 root 1.92 struct transfer_args
1321     {
1322     struct coro *prev, *next;
1323     };
1324    
1325 root 1.227 #define TRANSFER(ta, force_cctx) transfer (aTHX_ (ta).prev, (ta).next, (force_cctx))
1326 root 1.170 #define TRANSFER_CHECK(ta) transfer_check (aTHX_ (ta).prev, (ta).next)
1327 root 1.92
1328 root 1.137 /** high level stuff ********************************************************/
1329    
1330 root 1.133 static int
1331 root 1.146 coro_state_destroy (pTHX_ struct coro *coro)
1332 root 1.87 {
1333 root 1.133 if (coro->flags & CF_DESTROYED)
1334     return 0;
1335    
1336     coro->flags |= CF_DESTROYED;
1337 root 1.137
1338     if (coro->flags & CF_READY)
1339     {
1340     /* reduce nready, as destroying a ready coro effectively unreadies it */
1341 root 1.139 /* alternative: look through all ready queues and remove the coro */
1342 root 1.137 LOCK;
1343     --coro_nready;
1344     UNLOCK;
1345     }
1346     else
1347     coro->flags |= CF_READY; /* make sure it is NOT put into the readyqueue */
1348 root 1.87
1349     if (coro->mainstack && coro->mainstack != main_mainstack)
1350     {
1351 root 1.140 struct coro temp;
1352    
1353 root 1.177 if (coro->flags & CF_RUNNING)
1354     croak ("FATAL: tried to destroy currently running coroutine");
1355 root 1.133
1356 root 1.146 save_perl (aTHX_ &temp);
1357     load_perl (aTHX_ coro);
1358 root 1.87
1359 root 1.253 coro_destruct (aTHX_ coro);
1360 root 1.87
1361 root 1.198 load_perl (aTHX_ &temp);
1362 root 1.87
1363 root 1.198 coro->slot = 0;
1364 root 1.87 }
1365    
1366 root 1.115 cctx_destroy (coro->cctx);
1367 root 1.87 SvREFCNT_dec (coro->args);
1368 root 1.133
1369 root 1.151 if (coro->next) coro->next->prev = coro->prev;
1370     if (coro->prev) coro->prev->next = coro->next;
1371 root 1.153 if (coro == coro_first) coro_first = coro->next;
1372 root 1.151
1373 root 1.133 return 1;
1374 root 1.87 }
1375    
1376     static int
1377 root 1.134 coro_state_free (pTHX_ SV *sv, MAGIC *mg)
1378 root 1.87 {
1379     struct coro *coro = (struct coro *)mg->mg_ptr;
1380     mg->mg_ptr = 0;
1381    
1382 root 1.151 coro->hv = 0;
1383    
1384 root 1.134 if (--coro->refcnt < 0)
1385     {
1386 root 1.146 coro_state_destroy (aTHX_ coro);
1387 root 1.134 Safefree (coro);
1388     }
1389 root 1.133
1390 root 1.87 return 0;
1391     }
1392    
1393     static int
1394 root 1.98 coro_state_dup (pTHX_ MAGIC *mg, CLONE_PARAMS *params)
1395 root 1.87 {
1396     struct coro *coro = (struct coro *)mg->mg_ptr;
1397    
1398     ++coro->refcnt;
1399    
1400     return 0;
1401     }
1402    
1403 root 1.100 static MGVTBL coro_state_vtbl = {
1404     0, 0, 0, 0,
1405 root 1.134 coro_state_free,
1406 root 1.100 0,
1407     #ifdef MGf_DUP
1408     coro_state_dup,
1409 root 1.102 #else
1410     # define MGf_DUP 0
1411 root 1.100 #endif
1412     };
1413 root 1.87
1414 root 1.23 static void
1415 root 1.146 prepare_transfer (pTHX_ struct transfer_args *ta, SV *prev_sv, SV *next_sv)
1416 root 1.23 {
1417 root 1.122 ta->prev = SvSTATE (prev_sv);
1418     ta->next = SvSTATE (next_sv);
1419 root 1.170 TRANSFER_CHECK (*ta);
1420 root 1.92 }
1421    
1422     static void
1423 root 1.122 api_transfer (SV *prev_sv, SV *next_sv)
1424 root 1.92 {
1425 root 1.146 dTHX;
1426 root 1.92 struct transfer_args ta;
1427    
1428 root 1.146 prepare_transfer (aTHX_ &ta, prev_sv, next_sv);
1429 root 1.227 TRANSFER (ta, 1);
1430 root 1.21 }
1431    
1432 root 1.22 /** Coro ********************************************************************/
1433    
1434     static void
1435 root 1.146 coro_enq (pTHX_ SV *coro_sv)
1436 root 1.22 {
1437 root 1.112 av_push (coro_ready [SvSTATE (coro_sv)->prio - PRIO_MIN], coro_sv);
1438 root 1.22 }
1439    
1440     static SV *
1441 root 1.218 coro_deq (pTHX)
1442 root 1.22 {
1443 root 1.218 int prio;
1444 root 1.22
1445 root 1.218 for (prio = PRIO_MAX - PRIO_MIN + 1; --prio >= 0; )
1446 root 1.83 if (AvFILLp (coro_ready [prio]) >= 0)
1447 root 1.137 return av_shift (coro_ready [prio]);
1448 root 1.22
1449     return 0;
1450     }
1451    
1452 root 1.111 static int
1453     api_ready (SV *coro_sv)
1454 root 1.23 {
1455 root 1.146 dTHX;
1456 root 1.111 struct coro *coro;
1457 root 1.237 SV *sv_hook;
1458     void (*xs_hook)(void);
1459 root 1.111
1460     if (SvROK (coro_sv))
1461     coro_sv = SvRV (coro_sv);
1462    
1463     coro = SvSTATE (coro_sv);
1464 root 1.112
1465 root 1.111 if (coro->flags & CF_READY)
1466     return 0;
1467 pcg 1.56
1468 root 1.111 coro->flags |= CF_READY;
1469 root 1.39
1470 pcg 1.55 LOCK;
1471 root 1.233
1472 root 1.237 sv_hook = coro_nready ? 0 : coro_readyhook;
1473     xs_hook = coro_nready ? 0 : coroapi.readyhook;
1474 root 1.233
1475 root 1.249 coro_enq (aTHX_ SvREFCNT_inc_NN (coro_sv));
1476 root 1.137 ++coro_nready;
1477 root 1.233
1478 pcg 1.55 UNLOCK;
1479 root 1.233
1480 root 1.237 if (sv_hook)
1481 root 1.233 {
1482     dSP;
1483    
1484     ENTER;
1485     SAVETMPS;
1486    
1487     PUSHMARK (SP);
1488     PUTBACK;
1489 root 1.237 call_sv (sv_hook, G_DISCARD);
1490 root 1.233 SPAGAIN;
1491    
1492     FREETMPS;
1493     LEAVE;
1494     }
1495 root 1.111
1496 root 1.237 if (xs_hook)
1497     xs_hook ();
1498    
1499 root 1.111 return 1;
1500     }
1501    
1502     static int
1503     api_is_ready (SV *coro_sv)
1504     {
1505 root 1.146 dTHX;
1506 root 1.130 return !!(SvSTATE (coro_sv)->flags & CF_READY);
1507 root 1.23 }
1508    
1509     static void
1510 root 1.146 prepare_schedule (pTHX_ struct transfer_args *ta)
1511 root 1.23 {
1512 root 1.133 SV *prev_sv, *next_sv;
1513 root 1.88
1514     for (;;)
1515     {
1516     LOCK;
1517 root 1.218 next_sv = coro_deq (aTHX);
1518 root 1.88
1519 root 1.133 /* nothing to schedule: call the idle handler */
1520 root 1.194 if (expect_false (!next_sv))
1521 root 1.133 {
1522 root 1.140 dSP;
1523 root 1.138 UNLOCK;
1524 root 1.133
1525     ENTER;
1526     SAVETMPS;
1527 root 1.23
1528 root 1.133 PUSHMARK (SP);
1529     PUTBACK;
1530     call_sv (get_sv ("Coro::idle", FALSE), G_DISCARD);
1531 root 1.219 SPAGAIN;
1532 root 1.133
1533     FREETMPS;
1534     LEAVE;
1535     continue;
1536     }
1537 root 1.88
1538 root 1.133 ta->next = SvSTATE (next_sv);
1539 pcg 1.55
1540 root 1.133 /* cannot transfer to destroyed coros, skip and look for next */
1541 root 1.194 if (expect_false (ta->next->flags & CF_DESTROYED))
1542 root 1.133 {
1543 root 1.138 UNLOCK;
1544 root 1.133 SvREFCNT_dec (next_sv);
1545 root 1.137 /* coro_nready is already taken care of by destroy */
1546 root 1.133 continue;
1547     }
1548 root 1.23
1549 root 1.137 --coro_nready;
1550     UNLOCK;
1551 root 1.133 break;
1552 root 1.88 }
1553    
1554 root 1.133 /* free this only after the transfer */
1555     prev_sv = SvRV (coro_current);
1556     ta->prev = SvSTATE (prev_sv);
1557 root 1.170 TRANSFER_CHECK (*ta);
1558 root 1.133 assert (ta->next->flags & CF_READY);
1559     ta->next->flags &= ~CF_READY;
1560 root 1.170 SvRV_set (coro_current, next_sv);
1561 root 1.23
1562 root 1.99 LOCK;
1563 root 1.146 free_coro_mortal (aTHX);
1564 root 1.133 coro_mortal = prev_sv;
1565 root 1.99 UNLOCK;
1566 root 1.92 }
1567    
1568     static void
1569 root 1.146 prepare_cede (pTHX_ struct transfer_args *ta)
1570 root 1.92 {
1571 root 1.117 api_ready (coro_current);
1572 root 1.146 prepare_schedule (aTHX_ ta);
1573 root 1.131 }
1574 pcg 1.55
1575 root 1.131 static int
1576 root 1.146 prepare_cede_notself (pTHX_ struct transfer_args *ta)
1577 root 1.131 {
1578     if (coro_nready)
1579     {
1580     SV *prev = SvRV (coro_current);
1581 root 1.146 prepare_schedule (aTHX_ ta);
1582 root 1.131 api_ready (prev);
1583     return 1;
1584     }
1585     else
1586     return 0;
1587 root 1.39 }
1588    
1589 root 1.92 static void
1590     api_schedule (void)
1591     {
1592 root 1.146 dTHX;
1593 root 1.92 struct transfer_args ta;
1594    
1595 root 1.146 prepare_schedule (aTHX_ &ta);
1596 root 1.227 TRANSFER (ta, 1);
1597 root 1.92 }
1598 root 1.89
1599 root 1.131 static int
1600 root 1.39 api_cede (void)
1601     {
1602 root 1.146 dTHX;
1603 root 1.92 struct transfer_args ta;
1604 root 1.89
1605 root 1.146 prepare_cede (aTHX_ &ta);
1606 root 1.131
1607 root 1.194 if (expect_true (ta.prev != ta.next))
1608 root 1.131 {
1609 root 1.227 TRANSFER (ta, 1);
1610 root 1.131 return 1;
1611     }
1612     else
1613     return 0;
1614     }
1615    
1616     static int
1617     api_cede_notself (void)
1618     {
1619 root 1.146 dTHX;
1620 root 1.131 struct transfer_args ta;
1621    
1622 root 1.146 if (prepare_cede_notself (aTHX_ &ta))
1623 root 1.131 {
1624 root 1.227 TRANSFER (ta, 1);
1625 root 1.131 return 1;
1626     }
1627     else
1628     return 0;
1629 root 1.23 }
1630    
1631 root 1.173 static void
1632 root 1.174 api_trace (SV *coro_sv, int flags)
1633 root 1.173 {
1634     dTHX;
1635 root 1.174 struct coro *coro = SvSTATE (coro_sv);
1636 root 1.173
1637     if (flags & CC_TRACE)
1638     {
1639     if (!coro->cctx)
1640     coro->cctx = cctx_new ();
1641     else if (!(coro->cctx->flags & CC_TRACE))
1642     croak ("cannot enable tracing on coroutine with custom stack");
1643    
1644     coro->cctx->flags |= CC_NOREUSE | (flags & (CC_TRACE | CC_TRACE_ALL));
1645     }
1646     else if (coro->cctx && coro->cctx->flags & CC_TRACE)
1647     {
1648     coro->cctx->flags &= ~(CC_TRACE | CC_TRACE_ALL);
1649    
1650     if (coro->flags & CF_RUNNING)
1651     PL_runops = RUNOPS_DEFAULT;
1652     else
1653 root 1.198 coro->slot->runops = RUNOPS_DEFAULT;
1654 root 1.173 }
1655     }
1656    
1657 root 1.243 static int
1658     coro_gensub_free (pTHX_ SV *sv, MAGIC *mg)
1659     {
1660     AV *padlist;
1661     AV *av = (AV *)mg->mg_obj;
1662    
1663     abort ();
1664    
1665     return 0;
1666     }
1667    
1668     static MGVTBL coro_gensub_vtbl = {
1669     0, 0, 0, 0,
1670     coro_gensub_free
1671     };
1672    
1673 root 1.246 /*****************************************************************************/
1674     /* PerlIO::cede */
1675    
1676     typedef struct
1677     {
1678     PerlIOBuf base;
1679     NV next, every;
1680     } PerlIOCede;
1681    
1682     static IV
1683     PerlIOCede_pushed (pTHX_ PerlIO *f, const char *mode, SV *arg, PerlIO_funcs *tab)
1684     {
1685     PerlIOCede *self = PerlIOSelf (f, PerlIOCede);
1686    
1687 root 1.247 self->every = SvCUR (arg) ? SvNV (arg) : 0.01;
1688 root 1.246 self->next = nvtime () + self->every;
1689    
1690     return PerlIOBuf_pushed (aTHX_ f, mode, Nullsv, tab);
1691     }
1692    
1693     static SV *
1694     PerlIOCede_getarg (pTHX_ PerlIO *f, CLONE_PARAMS *param, int flags)
1695     {
1696     PerlIOCede *self = PerlIOSelf (f, PerlIOCede);
1697    
1698     return newSVnv (self->every);
1699     }
1700    
1701     static IV
1702     PerlIOCede_flush (pTHX_ PerlIO *f)
1703     {
1704     PerlIOCede *self = PerlIOSelf (f, PerlIOCede);
1705     double now = nvtime ();
1706    
1707     if (now >= self->next)
1708     {
1709     api_cede ();
1710     self->next = now + self->every;
1711     }
1712    
1713 root 1.248 return PerlIOBuf_flush (aTHX_ f);
1714 root 1.246 }
1715    
1716     static PerlIO_funcs PerlIO_cede =
1717     {
1718     sizeof(PerlIO_funcs),
1719     "cede",
1720     sizeof(PerlIOCede),
1721     PERLIO_K_DESTRUCT | PERLIO_K_RAW,
1722     PerlIOCede_pushed,
1723     PerlIOBuf_popped,
1724     PerlIOBuf_open,
1725     PerlIOBase_binmode,
1726     PerlIOCede_getarg,
1727     PerlIOBase_fileno,
1728     PerlIOBuf_dup,
1729     PerlIOBuf_read,
1730     PerlIOBuf_unread,
1731     PerlIOBuf_write,
1732     PerlIOBuf_seek,
1733     PerlIOBuf_tell,
1734     PerlIOBuf_close,
1735     PerlIOCede_flush,
1736     PerlIOBuf_fill,
1737     PerlIOBase_eof,
1738     PerlIOBase_error,
1739     PerlIOBase_clearerr,
1740     PerlIOBase_setlinebuf,
1741     PerlIOBuf_get_base,
1742     PerlIOBuf_bufsiz,
1743     PerlIOBuf_get_ptr,
1744     PerlIOBuf_get_cnt,
1745     PerlIOBuf_set_ptrcnt,
1746     };
1747    
1748    
1749 root 1.173 MODULE = Coro::State PACKAGE = Coro::State PREFIX = api_
1750 root 1.1
1751 root 1.87 PROTOTYPES: DISABLE
1752 root 1.1
1753 root 1.3 BOOT:
1754 root 1.88 {
1755 pcg 1.55 #ifdef USE_ITHREADS
1756 root 1.253 MUTEX_INIT (&coro_lock);
1757 pcg 1.55 #endif
1758 root 1.78 BOOT_PAGESIZE;
1759 pcg 1.55
1760 root 1.190 irsgv = gv_fetchpv ("/" , GV_ADD|GV_NOTQUAL, SVt_PV);
1761     stdoutgv = gv_fetchpv ("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVIO);
1762 root 1.220
1763 root 1.239 orig_sigelem_get = PL_vtbl_sigelem.svt_get; PL_vtbl_sigelem.svt_get = coro_sigelem_get;
1764     orig_sigelem_set = PL_vtbl_sigelem.svt_set; PL_vtbl_sigelem.svt_set = coro_sigelem_set;
1765     orig_sigelem_clr = PL_vtbl_sigelem.svt_clear; PL_vtbl_sigelem.svt_clear = coro_sigelem_clr;
1766 root 1.220
1767 root 1.213 hv_sig = coro_get_hv (aTHX_ "SIG", TRUE);
1768 root 1.220 rv_diehook = newRV_inc ((SV *)gv_fetchpv ("Coro::State::diehook" , 0, SVt_PVCV));
1769     rv_warnhook = newRV_inc ((SV *)gv_fetchpv ("Coro::State::warnhook", 0, SVt_PVCV));
1770 root 1.199
1771 root 1.14 coro_state_stash = gv_stashpv ("Coro::State", TRUE);
1772 root 1.7
1773 root 1.167 newCONSTSUB (coro_state_stash, "CC_TRACE" , newSViv (CC_TRACE));
1774     newCONSTSUB (coro_state_stash, "CC_TRACE_SUB" , newSViv (CC_TRACE_SUB));
1775     newCONSTSUB (coro_state_stash, "CC_TRACE_LINE", newSViv (CC_TRACE_LINE));
1776     newCONSTSUB (coro_state_stash, "CC_TRACE_ALL" , newSViv (CC_TRACE_ALL));
1777    
1778 root 1.12 main_mainstack = PL_mainstack;
1779 root 1.148 main_top_env = PL_top_env;
1780    
1781     while (main_top_env->je_prev)
1782     main_top_env = main_top_env->je_prev;
1783 root 1.23
1784 root 1.237 coroapi.ver = CORO_API_VERSION;
1785     coroapi.rev = CORO_API_REVISION;
1786     coroapi.transfer = api_transfer;
1787 root 1.87
1788 root 1.246 {
1789     SV **svp = hv_fetch (PL_modglobal, "Time::NVtime", 12, 0);
1790    
1791     if (!svp) croak ("Time::HiRes is required");
1792     if (!SvIOK (*svp)) croak ("Time::NVtime isn't a function pointer");
1793    
1794     nvtime = INT2PTR (double (*)(), SvIV (*svp));
1795     }
1796    
1797 root 1.87 assert (("PRIO_NORMAL must be 0", !PRIO_NORMAL));
1798 root 1.9 }
1799 root 1.3
1800 root 1.87 SV *
1801 root 1.86 new (char *klass, ...)
1802 root 1.1 CODE:
1803 root 1.86 {
1804 root 1.87 struct coro *coro;
1805 root 1.214 MAGIC *mg;
1806 root 1.87 HV *hv;
1807 root 1.86 int i;
1808    
1809 pcg 1.47 Newz (0, coro, 1, struct coro);
1810 root 1.178 coro->args = newAV ();
1811 root 1.117 coro->flags = CF_NEW;
1812 root 1.86
1813 root 1.153 if (coro_first) coro_first->prev = coro;
1814     coro->next = coro_first;
1815     coro_first = coro;
1816 root 1.151
1817     coro->hv = hv = newHV ();
1818 root 1.214 mg = sv_magicext ((SV *)hv, 0, CORO_MAGIC_type_state, &coro_state_vtbl, (char *)coro, 0);
1819     mg->mg_flags |= MGf_DUP;
1820 root 1.89 RETVAL = sv_bless (newRV_noinc ((SV *)hv), gv_stashpv (klass, 1));
1821    
1822 root 1.192 av_extend (coro->args, items - 1);
1823 root 1.86 for (i = 1; i < items; i++)
1824     av_push (coro->args, newSVsv (ST (i)));
1825     }
1826 root 1.1 OUTPUT:
1827     RETVAL
1828    
1829 root 1.176 # these not obviously related functions are all rolled into the same xs
1830     # function to increase chances that they all will call transfer with the same
1831     # stack offset
1832 root 1.1 void
1833 root 1.94 _set_stacklevel (...)
1834 root 1.92 ALIAS:
1835 root 1.210 Coro::State::transfer = 1
1836     Coro::schedule = 2
1837     Coro::cede = 3
1838     Coro::cede_notself = 4
1839     CODE:
1840 root 1.87 {
1841 root 1.92 struct transfer_args ta;
1842 root 1.1
1843 root 1.219 PUTBACK;
1844 root 1.210 switch (ix)
1845 root 1.1 {
1846 root 1.210 case 0:
1847     ta.prev = (struct coro *)INT2PTR (coro_cctx *, SvIV (ST (0)));
1848     ta.next = 0;
1849     break;
1850    
1851     case 1:
1852     if (items != 2)
1853 root 1.252 croak ("Coro::State::transfer (prev, next) expects two arguments, not %d", items);
1854 root 1.210
1855     prepare_transfer (aTHX_ &ta, ST (0), ST (1));
1856     break;
1857    
1858     case 2:
1859     prepare_schedule (aTHX_ &ta);
1860     break;
1861    
1862     case 3:
1863     prepare_cede (aTHX_ &ta);
1864     break;
1865    
1866     case 4:
1867     if (!prepare_cede_notself (aTHX_ &ta))
1868     XSRETURN_EMPTY;
1869 root 1.131
1870 root 1.210 break;
1871 root 1.92 }
1872 root 1.219 SPAGAIN;
1873 root 1.135
1874 root 1.210 BARRIER;
1875     PUTBACK;
1876 root 1.227 TRANSFER (ta, 0);
1877 root 1.210 SPAGAIN; /* might be the sp of a different coroutine now */
1878     /* be extra careful not to ever do anything after TRANSFER */
1879 root 1.209 }
1880 root 1.1
1881 root 1.133 bool
1882     _destroy (SV *coro_sv)
1883 root 1.87 CODE:
1884 root 1.146 RETVAL = coro_state_destroy (aTHX_ SvSTATE (coro_sv));
1885 root 1.133 OUTPUT:
1886     RETVAL
1887 root 1.12
1888 root 1.7 void
1889 root 1.233 _exit (int code)
1890 root 1.20 PROTOTYPE: $
1891     CODE:
1892     _exit (code);
1893 root 1.1
1894 root 1.106 int
1895 root 1.145 cctx_stacksize (int new_stacksize = 0)
1896     CODE:
1897 root 1.254 RETVAL = cctx_stacksize;
1898 root 1.145 if (new_stacksize)
1899 root 1.254 {
1900     cctx_stacksize = new_stacksize;
1901     ++cctx_gen;
1902     }
1903     OUTPUT:
1904     RETVAL
1905    
1906     int
1907     cctx_max_idle (int max_idle = 0)
1908     CODE:
1909     RETVAL = cctx_max_idle;
1910     if (max_idle > 1)
1911     cctx_max_idle = max_idle;
1912 root 1.145 OUTPUT:
1913     RETVAL
1914    
1915     int
1916 root 1.106 cctx_count ()
1917     CODE:
1918     RETVAL = cctx_count;
1919     OUTPUT:
1920     RETVAL
1921    
1922     int
1923     cctx_idle ()
1924     CODE:
1925 root 1.211 RETVAL = cctx_idle;
1926 root 1.106 OUTPUT:
1927     RETVAL
1928    
1929 root 1.151 void
1930     list ()
1931     PPCODE:
1932     {
1933     struct coro *coro;
1934 root 1.153 for (coro = coro_first; coro; coro = coro->next)
1935 root 1.151 if (coro->hv)
1936     XPUSHs (sv_2mortal (newRV_inc ((SV *)coro->hv)));
1937     }
1938    
1939     void
1940 root 1.164 call (Coro::State coro, SV *coderef)
1941     ALIAS:
1942     eval = 1
1943 root 1.151 CODE:
1944     {
1945 root 1.245 if (coro->mainstack && ((coro->flags & CF_RUNNING) || coro->slot))
1946 root 1.151 {
1947     struct coro temp;
1948    
1949     if (!(coro->flags & CF_RUNNING))
1950     {
1951 root 1.219 PUTBACK;
1952 root 1.151 save_perl (aTHX_ &temp);
1953     load_perl (aTHX_ coro);
1954     }
1955    
1956     {
1957     dSP;
1958     ENTER;
1959     SAVETMPS;
1960 root 1.208 PUTBACK;
1961     PUSHSTACK;
1962 root 1.151 PUSHMARK (SP);
1963 root 1.198
1964 root 1.164 if (ix)
1965     eval_sv (coderef, 0);
1966     else
1967     call_sv (coderef, G_KEEPERR | G_EVAL | G_VOID | G_DISCARD);
1968 root 1.198
1969 root 1.208 POPSTACK;
1970 root 1.211 SPAGAIN;
1971 root 1.151 FREETMPS;
1972     LEAVE;
1973 root 1.210 PUTBACK;
1974 root 1.151 }
1975    
1976     if (!(coro->flags & CF_RUNNING))
1977     {
1978     save_perl (aTHX_ coro);
1979     load_perl (aTHX_ &temp);
1980 root 1.219 SPAGAIN;
1981 root 1.151 }
1982     }
1983     }
1984 root 1.172
1985 root 1.151 SV *
1986 root 1.152 is_ready (Coro::State coro)
1987 root 1.151 PROTOTYPE: $
1988     ALIAS:
1989     is_ready = CF_READY
1990     is_running = CF_RUNNING
1991     is_new = CF_NEW
1992     is_destroyed = CF_DESTROYED
1993     CODE:
1994     RETVAL = boolSV (coro->flags & ix);
1995     OUTPUT:
1996     RETVAL
1997    
1998 root 1.165 void
1999 root 1.174 api_trace (SV *coro, int flags = CC_TRACE | CC_TRACE_SUB)
2000 root 1.165
2001 root 1.162 SV *
2002 root 1.234 has_cctx (Coro::State coro)
2003 root 1.162 PROTOTYPE: $
2004     CODE:
2005     RETVAL = boolSV (!!coro->cctx);
2006     OUTPUT:
2007     RETVAL
2008    
2009 root 1.167 int
2010     is_traced (Coro::State coro)
2011     PROTOTYPE: $
2012     CODE:
2013     RETVAL = (coro->cctx ? coro->cctx->flags : 0) & CC_TRACE_ALL;
2014     OUTPUT:
2015     RETVAL
2016    
2017 root 1.152 IV
2018     rss (Coro::State coro)
2019     PROTOTYPE: $
2020 root 1.172 ALIAS:
2021     usecount = 1
2022 root 1.152 CODE:
2023 root 1.172 switch (ix)
2024     {
2025     case 0: RETVAL = coro_rss (aTHX_ coro); break;
2026     case 1: RETVAL = coro->usecount; break;
2027     }
2028 root 1.152 OUTPUT:
2029     RETVAL
2030    
2031 root 1.226 void
2032     force_cctx ()
2033     CODE:
2034     struct coro *coro = SvSTATE (coro_current);
2035     coro->cctx->idle_sp = 0;
2036 root 1.151
2037 root 1.242 void
2038     swap_defsv (Coro::State self)
2039     PROTOTYPE: $
2040     ALIAS:
2041     swap_defav = 1
2042     CODE:
2043     if (!self->slot)
2044     croak ("cannot swap state with coroutine that has no saved state");
2045     else
2046     {
2047     SV **src = ix ? (SV **)&GvAV (PL_defgv) : &GvSV (PL_defgv);
2048     SV **dst = ix ? (SV **)&self->slot->defav : (SV **)&self->slot->defsv;
2049    
2050     SV *tmp = *src; *src = *dst; *dst = tmp;
2051     }
2052    
2053 root 1.21 MODULE = Coro::State PACKAGE = Coro
2054    
2055     BOOT:
2056     {
2057 root 1.22 int i;
2058    
2059 root 1.233 av_async_pool = coro_get_av (aTHX_ "Coro::async_pool", TRUE);
2060 root 1.213 sv_pool_rss = coro_get_sv (aTHX_ "Coro::POOL_RSS" , TRUE);
2061     sv_pool_size = coro_get_sv (aTHX_ "Coro::POOL_SIZE" , TRUE);
2062 root 1.159
2063 root 1.213 coro_current = coro_get_sv (aTHX_ "Coro::current", FALSE);
2064 root 1.159 SvREADONLY_on (coro_current);
2065    
2066 root 1.198 coro_stash = gv_stashpv ("Coro", TRUE);
2067 root 1.88
2068     newCONSTSUB (coro_stash, "PRIO_MAX", newSViv (PRIO_MAX));
2069     newCONSTSUB (coro_stash, "PRIO_HIGH", newSViv (PRIO_HIGH));
2070     newCONSTSUB (coro_stash, "PRIO_NORMAL", newSViv (PRIO_NORMAL));
2071     newCONSTSUB (coro_stash, "PRIO_LOW", newSViv (PRIO_LOW));
2072     newCONSTSUB (coro_stash, "PRIO_IDLE", newSViv (PRIO_IDLE));
2073     newCONSTSUB (coro_stash, "PRIO_MIN", newSViv (PRIO_MIN));
2074 root 1.22
2075     for (i = PRIO_MAX - PRIO_MIN + 1; i--; )
2076     coro_ready[i] = newAV ();
2077 root 1.26
2078     {
2079 root 1.198 SV *sv = perl_get_sv ("Coro::API", TRUE);
2080     perl_get_sv ("Coro::API", TRUE); /* silence 5.10 warning */
2081 root 1.26
2082 root 1.131 coroapi.schedule = api_schedule;
2083     coroapi.cede = api_cede;
2084     coroapi.cede_notself = api_cede_notself;
2085     coroapi.ready = api_ready;
2086     coroapi.is_ready = api_is_ready;
2087     coroapi.nready = &coro_nready;
2088     coroapi.current = coro_current;
2089 root 1.26
2090     GCoroAPI = &coroapi;
2091 root 1.81 sv_setiv (sv, (IV)&coroapi);
2092     SvREADONLY_on (sv);
2093 root 1.26 }
2094 root 1.21 }
2095    
2096 root 1.122 void
2097     _set_current (SV *current)
2098     PROTOTYPE: $
2099     CODE:
2100     SvREFCNT_dec (SvRV (coro_current));
2101 root 1.249 SvRV_set (coro_current, SvREFCNT_inc_NN (SvRV (current)));
2102 root 1.122
2103 root 1.233 void
2104     _set_readyhook (SV *hook)
2105     PROTOTYPE: $
2106     CODE:
2107     LOCK;
2108 root 1.236 SvREFCNT_dec (coro_readyhook);
2109 root 1.233 coro_readyhook = SvOK (hook) ? newSVsv (hook) : 0;
2110     UNLOCK;
2111    
2112 root 1.92 int
2113     prio (Coro::State coro, int newprio = 0)
2114     ALIAS:
2115     nice = 1
2116     CODE:
2117     {
2118     RETVAL = coro->prio;
2119    
2120     if (items > 1)
2121     {
2122     if (ix)
2123 root 1.129 newprio = coro->prio - newprio;
2124 root 1.92
2125     if (newprio < PRIO_MIN) newprio = PRIO_MIN;
2126     if (newprio > PRIO_MAX) newprio = PRIO_MAX;
2127    
2128     coro->prio = newprio;
2129     }
2130     }
2131 root 1.130 OUTPUT:
2132     RETVAL
2133 root 1.92
2134 root 1.111 SV *
2135 root 1.89 ready (SV *self)
2136 root 1.35 PROTOTYPE: $
2137 root 1.21 CODE:
2138 root 1.111 RETVAL = boolSV (api_ready (self));
2139     OUTPUT:
2140     RETVAL
2141    
2142 root 1.25 int
2143 root 1.87 nready (...)
2144 root 1.25 PROTOTYPE:
2145     CODE:
2146     RETVAL = coro_nready;
2147     OUTPUT:
2148     RETVAL
2149    
2150 root 1.252 void
2151     throw (Coro::State self, SV *throw = &PL_sv_undef)
2152     PROTOTYPE: $;$
2153     CODE:
2154     SvREFCNT_dec (self->throw);
2155     self->throw = SvOK (throw) ? newSVsv (throw) : 0;
2156    
2157 root 1.159 # for async_pool speedup
2158 root 1.161 void
2159     _pool_1 (SV *cb)
2160 root 1.159 CODE:
2161     {
2162 root 1.181 struct coro *coro = SvSTATE (coro_current);
2163 root 1.159 HV *hv = (HV *)SvRV (coro_current);
2164     AV *defav = GvAV (PL_defgv);
2165 root 1.212 SV *invoke = hv_delete (hv, "_invoke", sizeof ("_invoke") - 1, 0);
2166 root 1.159 AV *invoke_av;
2167 root 1.181 int i, len;
2168    
2169 root 1.159 if (!invoke)
2170 root 1.221 {
2171 root 1.240 SV *old = PL_diehook;
2172     PL_diehook = 0;
2173     SvREFCNT_dec (old);
2174 root 1.221 croak ("\3async_pool terminate\2\n");
2175     }
2176 root 1.159
2177 root 1.184 SvREFCNT_dec (coro->saved_deffh);
2178 root 1.249 coro->saved_deffh = SvREFCNT_inc_NN ((SV *)PL_defoutgv);
2179 root 1.182
2180 root 1.159 hv_store (hv, "desc", sizeof ("desc") - 1,
2181 root 1.212 newSVpvn ("[async_pool]", sizeof ("[async_pool]") - 1), 0);
2182 root 1.159
2183     invoke_av = (AV *)SvRV (invoke);
2184     len = av_len (invoke_av);
2185    
2186 root 1.161 sv_setsv (cb, AvARRAY (invoke_av)[0]);
2187 root 1.159
2188     if (len > 0)
2189     {
2190 root 1.161 av_fill (defav, len - 1);
2191 root 1.159 for (i = 0; i < len; ++i)
2192 root 1.249 av_store (defav, i, SvREFCNT_inc_NN (AvARRAY (invoke_av)[i + 1]));
2193 root 1.159 }
2194    
2195     SvREFCNT_dec (invoke);
2196     }
2197    
2198     void
2199 root 1.161 _pool_2 (SV *cb)
2200 root 1.159 CODE:
2201     {
2202     struct coro *coro = SvSTATE (coro_current);
2203    
2204 root 1.161 sv_setsv (cb, &PL_sv_undef);
2205    
2206 root 1.184 SvREFCNT_dec ((SV *)PL_defoutgv); PL_defoutgv = (GV *)coro->saved_deffh;
2207     coro->saved_deffh = 0;
2208 root 1.181
2209 root 1.171 if (coro_rss (aTHX_ coro) > SvIV (sv_pool_rss)
2210 root 1.159 || av_len (av_async_pool) + 1 >= SvIV (sv_pool_size))
2211 root 1.221 {
2212 root 1.240 SV *old = PL_diehook;
2213     PL_diehook = 0;
2214     SvREFCNT_dec (old);
2215 root 1.221 croak ("\3async_pool terminate\2\n");
2216     }
2217 root 1.159
2218     av_clear (GvAV (PL_defgv));
2219 root 1.212 hv_store ((HV *)SvRV (coro_current), "desc", sizeof ("desc") - 1,
2220     newSVpvn ("[async_pool idle]", sizeof ("[async_pool idle]") - 1), 0);
2221 root 1.175
2222 root 1.159 coro->prio = 0;
2223 root 1.173
2224     if (coro->cctx && (coro->cctx->flags & CC_TRACE))
2225 root 1.174 api_trace (coro_current, 0);
2226 root 1.173
2227 root 1.159 av_push (av_async_pool, newSVsv (coro_current));
2228     }
2229    
2230 root 1.243 #if 0
2231    
2232     void
2233     _generator_call (...)
2234     PROTOTYPE: @
2235     PPCODE:
2236     fprintf (stderr, "call %p\n", CvXSUBANY(cv).any_ptr);
2237     xxxx
2238     abort ();
2239    
2240     SV *
2241     gensub (SV *sub, ...)
2242     PROTOTYPE: &;@
2243     CODE:
2244     {
2245     struct coro *coro;
2246     MAGIC *mg;
2247     CV *xcv;
2248     CV *ncv = (CV *)newSV_type (SVt_PVCV);
2249     int i;
2250    
2251     CvGV (ncv) = CvGV (cv);
2252     CvFILE (ncv) = CvFILE (cv);
2253    
2254     Newz (0, coro, 1, struct coro);
2255     coro->args = newAV ();
2256     coro->flags = CF_NEW;
2257    
2258     av_extend (coro->args, items - 1);
2259     for (i = 1; i < items; i++)
2260     av_push (coro->args, newSVsv (ST (i)));
2261    
2262     CvISXSUB_on (ncv);
2263     CvXSUBANY (ncv).any_ptr = (void *)coro;
2264    
2265     xcv = GvCV (gv_fetchpv ("Coro::_generator_call", 0, SVt_PVCV));
2266    
2267     CvXSUB (ncv) = CvXSUB (xcv);
2268     CvANON_on (ncv);
2269    
2270     mg = sv_magicext ((SV *)ncv, 0, CORO_MAGIC_type_state, &coro_gensub_vtbl, (char *)coro, 0);
2271     RETVAL = newRV_noinc ((SV *)ncv);
2272     }
2273     OUTPUT:
2274     RETVAL
2275    
2276     #endif
2277    
2278 root 1.159
2279 root 1.89 MODULE = Coro::State PACKAGE = Coro::AIO
2280    
2281 root 1.249 void
2282     _get_state (SV *self)
2283     PPCODE:
2284 root 1.70 {
2285 root 1.249 AV *defav = GvAV (PL_defgv);
2286     AV *av = newAV ();
2287     int i;
2288     SV *data_sv = newSV (sizeof (struct io_state));
2289     struct io_state *data = (struct io_state *)SvPVX (data_sv);
2290     SvCUR_set (data_sv, sizeof (struct io_state));
2291     SvPOK_only (data_sv);
2292 root 1.120
2293     data->errorno = errno;
2294     data->laststype = PL_laststype;
2295     data->laststatval = PL_laststatval;
2296     data->statcache = PL_statcache;
2297 root 1.249
2298     av_extend (av, AvFILLp (defav) + 1 + 1);
2299    
2300     for (i = 0; i <= AvFILLp (defav); ++i)
2301     av_push (av, SvREFCNT_inc_NN (AvARRAY (defav)[i]));
2302    
2303     av_push (av, data_sv);
2304    
2305     XPUSHs (sv_2mortal (newRV_noinc ((SV *)av)));
2306    
2307     api_ready (self);
2308 root 1.70 }
2309    
2310     void
2311 root 1.249 _set_state (SV *state)
2312 root 1.70 PROTOTYPE: $
2313 root 1.249 PPCODE:
2314 root 1.70 {
2315 root 1.249 AV *av = (AV *)SvRV (state);
2316     struct io_state *data = (struct io_state *)SvPVX (AvARRAY (av)[AvFILLp (av)]);
2317     int i;
2318 root 1.70
2319 root 1.120 errno = data->errorno;
2320     PL_laststype = data->laststype;
2321 root 1.70 PL_laststatval = data->laststatval;
2322 root 1.120 PL_statcache = data->statcache;
2323 root 1.249
2324     EXTEND (SP, AvFILLp (av));
2325     for (i = 0; i < AvFILLp (av); ++i)
2326     PUSHs (sv_2mortal (SvREFCNT_inc_NN (AvARRAY (av)[i])));
2327 root 1.70 }
2328 root 1.120
2329 root 1.233
2330     MODULE = Coro::State PACKAGE = Coro::AnyEvent
2331    
2332     BOOT:
2333     sv_activity = coro_get_sv (aTHX_ "Coro::AnyEvent::ACTIVITY", TRUE);
2334    
2335     SV *
2336 root 1.237 _schedule (...)
2337 root 1.233 PROTOTYPE: @
2338     CODE:
2339     {
2340     static int incede;
2341    
2342     api_cede_notself ();
2343    
2344     ++incede;
2345     while (coro_nready >= incede && api_cede ())
2346     ;
2347    
2348     sv_setsv (sv_activity, &PL_sv_undef);
2349     if (coro_nready >= incede)
2350     {
2351     PUSHMARK (SP);
2352     PUTBACK;
2353     call_pv ("Coro::AnyEvent::_activity", G_DISCARD | G_EVAL);
2354     SPAGAIN;
2355     }
2356    
2357     --incede;
2358     }
2359    
2360 root 1.246
2361     MODULE = Coro::State PACKAGE = PerlIO::cede
2362    
2363     BOOT:
2364     PerlIO_define_layer (aTHX_ &PerlIO_cede);