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.108 by root, Mon Nov 27 18:15:47 2006 UTC vs.
Revision 1.146 by root, Sat Mar 17 19:51:57 2007 UTC

1#include "libcoro/coro.c" 1#include "libcoro/coro.c"
2
3#define PERL_NO_GET_CONTEXT
2 4
3#include "EXTERN.h" 5#include "EXTERN.h"
4#include "perl.h" 6#include "perl.h"
5#include "XSUB.h" 7#include "XSUB.h"
6 8
7#include "patchlevel.h" 9#include "patchlevel.h"
8 10
9#if USE_VALGRIND
10# include <valgrind/valgrind.h>
11#endif
12
13#define PERL_VERSION_ATLEAST(a,b,c) \
14 (PERL_REVISION > (a) \
15 || (PERL_REVISION == (a) \
16 && (PERL_VERSION > (b) \
17 || (PERL_VERSION == (b) && PERLSUBVERSION >= (c)))))
18
19#if !PERL_VERSION_ATLEAST (5,6,0)
20# ifndef PL_ppaddr
21# define PL_ppaddr ppaddr
22# endif
23# ifndef call_sv
24# define call_sv perl_call_sv
25# endif
26# ifndef get_sv
27# define get_sv perl_get_sv
28# endif
29# ifndef get_cv
30# define get_cv perl_get_cv
31# endif
32# ifndef IS_PADGV
33# define IS_PADGV(v) 0
34# endif
35# ifndef IS_PADCONST
36# define IS_PADCONST(v) 0
37# endif
38#endif
39
40#include <stdio.h> 11#include <stdio.h>
41#include <errno.h> 12#include <errno.h>
42 13#include <assert.h>
43#if !__i386 && !__x86_64 && !__powerpc && !__m68k && !__alpha && !__mips && !__sparc64
44# undef STACKGUARD
45#endif
46
47#ifndef STACKGUARD
48# define STACKGUARD 0
49#endif
50 14
51#ifdef HAVE_MMAP 15#ifdef HAVE_MMAP
52# include <unistd.h> 16# include <unistd.h>
53# include <sys/mman.h> 17# include <sys/mman.h>
54# ifndef MAP_ANONYMOUS 18# ifndef MAP_ANONYMOUS
69#else 33#else
70# define PAGESIZE 0 34# define PAGESIZE 0
71# define BOOT_PAGESIZE (void)0 35# define BOOT_PAGESIZE (void)0
72#endif 36#endif
73 37
38#if CORO_USE_VALGRIND
39# include <valgrind/valgrind.h>
40# define REGISTER_STACK(cctx,start,end) (cctx)->valgrind_id = VALGRIND_STACK_REGISTER ((start), (end))
41#else
42# define REGISTER_STACK(cctx,start,end)
43#endif
44
45/* the maximum number of idle cctx that will be pooled */
46#define MAX_IDLE_CCTX 8
47
48#define PERL_VERSION_ATLEAST(a,b,c) \
49 (PERL_REVISION > (a) \
50 || (PERL_REVISION == (a) \
51 && (PERL_VERSION > (b) \
52 || (PERL_VERSION == (b) && PERLSUBVERSION >= (c)))))
53
54#if !PERL_VERSION_ATLEAST (5,6,0)
55# ifndef PL_ppaddr
56# define PL_ppaddr ppaddr
57# endif
58# ifndef call_sv
59# define call_sv perl_call_sv
60# endif
61# ifndef get_sv
62# define get_sv perl_get_sv
63# endif
64# ifndef get_cv
65# define get_cv perl_get_cv
66# endif
67# ifndef IS_PADGV
68# define IS_PADGV(v) 0
69# endif
70# ifndef IS_PADCONST
71# define IS_PADCONST(v) 0
72# endif
73#endif
74
75/* 5.8.7 */
76#ifndef SvRV_set
77# define SvRV_set(s,v) SvRV(s) = (v)
78#endif
79
80#if !__i386 && !__x86_64 && !__powerpc && !__m68k && !__alpha && !__mips && !__sparc64
81# undef CORO_STACKGUARD
82#endif
83
84#ifndef CORO_STACKGUARD
85# define CORO_STACKGUARD 0
86#endif
87
88/* prefer perl internal functions over our own? */
89#ifndef CORO_PREFER_PERL_FUNCTIONS
90# define CORO_PREFER_PERL_FUNCTIONS 0
91#endif
92
74/* The next macro should declare a variable stacklevel that contains and approximation 93/* The next macro should declare a variable stacklevel that contains and approximation
75 * to the current C stack pointer. Its property is that it changes with each call 94 * to the current C stack pointer. Its property is that it changes with each call
76 * and should be unique. */ 95 * and should be unique. */
77#define dSTACKLEVEL int stacklevel 96#define dSTACKLEVEL int stacklevel
78#define STACKLEVEL ((void *)&stacklevel) 97#define STACKLEVEL ((void *)&stacklevel)
79 98
80#define IN_DESTRUCT (PL_main_cv == Nullcv) 99#define IN_DESTRUCT (PL_main_cv == Nullcv)
81 100
82#if __GNUC__ >= 3 101#if __GNUC__ >= 3
83# define attribute(x) __attribute__(x) 102# define attribute(x) __attribute__(x)
103# define BARRIER __asm__ __volatile__ ("" : : : "memory")
84#else 104#else
85# define attribute(x) 105# define attribute(x)
106# define BARRIER
86#endif 107#endif
87 108
88#define NOINLINE attribute ((noinline)) 109#define NOINLINE attribute ((noinline))
89 110
90#include "CoroAPI.h" 111#include "CoroAPI.h"
91
92#define TRANSFER_SET_STACKLEVEL 0x8bfbfbfb /* magic cookie */
93 112
94#ifdef USE_ITHREADS 113#ifdef USE_ITHREADS
95static perl_mutex coro_mutex; 114static perl_mutex coro_mutex;
96# define LOCK do { MUTEX_LOCK (&coro_mutex); } while (0) 115# define LOCK do { MUTEX_LOCK (&coro_mutex); } while (0)
97# define UNLOCK do { MUTEX_UNLOCK (&coro_mutex); } while (0) 116# define UNLOCK do { MUTEX_UNLOCK (&coro_mutex); } while (0)
98#else 117#else
99# define LOCK (void)0 118# define LOCK (void)0
100# define UNLOCK (void)0 119# define UNLOCK (void)0
101#endif 120#endif
102 121
122/* helper storage struct for Coro::AIO */
123struct io_state
124{
125 int errorno;
126 I32 laststype;
127 int laststatval;
128 Stat_t statcache;
129};
130
131static size_t coro_stacksize = CORO_STACKSIZE;
103static struct CoroAPI coroapi; 132static struct CoroAPI coroapi;
104static AV *main_mainstack; /* used to differentiate between $main and others */ 133static AV *main_mainstack; /* used to differentiate between $main and others */
105static HV *coro_state_stash, *coro_stash; 134static HV *coro_state_stash, *coro_stash;
106static SV *coro_mortal; /* will be freed after next transfer */ 135static SV *coro_mortal; /* will be freed after next transfer */
107 136
112typedef struct coro_cctx { 141typedef struct coro_cctx {
113 struct coro_cctx *next; 142 struct coro_cctx *next;
114 143
115 /* the stack */ 144 /* the stack */
116 void *sptr; 145 void *sptr;
117 long ssize; /* positive == mmap, otherwise malloc */ 146 size_t ssize;
118 147
119 /* cpu state */ 148 /* cpu state */
120 void *idle_sp; /* sp of top-level transfer/schedule/cede call */ 149 void *idle_sp; /* sp of top-level transfer/schedule/cede call */
150 JMPENV *idle_te; /* same as idle_sp, but for top_env, TODO: remove once stable */
121 JMPENV *top_env; 151 JMPENV *top_env;
122 coro_context cctx; 152 coro_context cctx;
123 153
124#if USE_VALGRIND 154#if CORO_USE_VALGRIND
125 int valgrind_id; 155 int valgrind_id;
126#endif 156#endif
157 char inuse, mapped;
127} coro_cctx; 158} coro_cctx;
159
160enum {
161 CF_RUNNING = 0x0001, /* coroutine is running */
162 CF_READY = 0x0002, /* coroutine is ready */
163 CF_NEW = 0x0004, /* has never been switched to */
164 CF_DESTROYED = 0x0008, /* coroutine data has been freed */
165};
128 166
129/* this is a structure representing a perl-level coroutine */ 167/* this is a structure representing a perl-level coroutine */
130struct coro { 168struct coro {
131 /* the c coroutine allocated to this perl coroutine, if any */ 169 /* the c coroutine allocated to this perl coroutine, if any */
132 coro_cctx *cctx; 170 coro_cctx *cctx;
133 171
134 /* data associated with this coroutine (initial args) */ 172 /* data associated with this coroutine (initial args) */
135 AV *args; 173 AV *args;
136 int refcnt; 174 int refcnt;
175 int save; /* CORO_SAVE flags */
176 int flags; /* CF_ flags */
137 177
138 /* optionally saved, might be zero */ 178 /* optionally saved, might be zero */
139 AV *defav; 179 AV *defav; /* @_ */
140 SV *defsv; 180 SV *defsv; /* $_ */
141 SV *errsv; 181 SV *errsv; /* $@ */
182 SV *irssv; /* $/ */
183 SV *irssv_sv; /* real $/ cache */
142 184
143#define VAR(name,type) type name; 185#define VAR(name,type) type name;
144# include "state.h" 186# include "state.h"
145#undef VAR 187#undef VAR
146 188
149}; 191};
150 192
151typedef struct coro *Coro__State; 193typedef struct coro *Coro__State;
152typedef struct coro *Coro__State_or_hashref; 194typedef struct coro *Coro__State_or_hashref;
153 195
196/** Coro ********************************************************************/
197
198#define PRIO_MAX 3
199#define PRIO_HIGH 1
200#define PRIO_NORMAL 0
201#define PRIO_LOW -1
202#define PRIO_IDLE -3
203#define PRIO_MIN -4
204
205/* for Coro.pm */
206static SV *coro_current;
207static AV *coro_ready [PRIO_MAX-PRIO_MIN+1];
208static int coro_nready;
209
210/** lowlevel stuff **********************************************************/
211
154static AV * 212static AV *
155coro_clone_padlist (CV *cv) 213coro_clone_padlist (pTHX_ CV *cv)
156{ 214{
157 AV *padlist = CvPADLIST (cv); 215 AV *padlist = CvPADLIST (cv);
158 AV *newpadlist, *newpad; 216 AV *newpadlist, *newpad;
159 217
160 newpadlist = newAV (); 218 newpadlist = newAV ();
172 230
173 return newpadlist; 231 return newpadlist;
174} 232}
175 233
176static void 234static void
177free_padlist (AV *padlist) 235free_padlist (pTHX_ AV *padlist)
178{ 236{
179 /* may be during global destruction */ 237 /* may be during global destruction */
180 if (SvREFCNT (padlist)) 238 if (SvREFCNT (padlist))
181 { 239 {
182 I32 i = AvFILLp (padlist); 240 I32 i = AvFILLp (padlist);
203 AV *padlist; 261 AV *padlist;
204 AV *av = (AV *)mg->mg_obj; 262 AV *av = (AV *)mg->mg_obj;
205 263
206 /* casting is fun. */ 264 /* casting is fun. */
207 while (&PL_sv_undef != (SV *)(padlist = (AV *)av_pop (av))) 265 while (&PL_sv_undef != (SV *)(padlist = (AV *)av_pop (av)))
208 free_padlist (padlist); 266 free_padlist (aTHX_ padlist);
209 267
210 SvREFCNT_dec (av); 268 SvREFCNT_dec (av);
211 269
212 return 0; 270 return 0;
213} 271}
214 272
215#define PERL_MAGIC_coro PERL_MAGIC_ext 273#define PERL_MAGIC_coro PERL_MAGIC_ext
216 274
217static MGVTBL vtbl_coro = {0, 0, 0, 0, coro_cv_free}; 275static MGVTBL vtbl_coro = {0, 0, 0, 0, coro_cv_free};
218 276
277#define CORO_MAGIC(cv) \
278 SvMAGIC (cv) \
279 ? SvMAGIC (cv)->mg_type == PERL_MAGIC_coro \
280 ? SvMAGIC (cv) \
281 : mg_find ((SV *)cv, PERL_MAGIC_coro) \
282 : 0
283
219/* the next two functions merely cache the padlists */ 284/* the next two functions merely cache the padlists */
220static void 285static void
221get_padlist (CV *cv) 286get_padlist (pTHX_ CV *cv)
222{ 287{
223 MAGIC *mg = mg_find ((SV *)cv, PERL_MAGIC_coro); 288 MAGIC *mg = CORO_MAGIC (cv);
289 AV *av;
224 290
225 if (mg && AvFILLp ((AV *)mg->mg_obj) >= 0) 291 if (mg && AvFILLp ((av = (AV *)mg->mg_obj)) >= 0)
226 CvPADLIST (cv) = (AV *)av_pop ((AV *)mg->mg_obj); 292 CvPADLIST (cv) = (AV *)AvARRAY (av)[AvFILLp (av)--];
227 else 293 else
228 { 294 {
229#if 0 295#if CORO_PREFER_PERL_FUNCTIONS
230 /* this is probably cleaner, but also slower? */ 296 /* this is probably cleaner, but also slower? */
231 CV *cp = Perl_cv_clone (cv); 297 CV *cp = Perl_cv_clone (cv);
232 CvPADLIST (cv) = CvPADLIST (cp); 298 CvPADLIST (cv) = CvPADLIST (cp);
233 CvPADLIST (cp) = 0; 299 CvPADLIST (cp) = 0;
234 SvREFCNT_dec (cp); 300 SvREFCNT_dec (cp);
235#else 301#else
236 CvPADLIST (cv) = coro_clone_padlist (cv); 302 CvPADLIST (cv) = coro_clone_padlist (aTHX_ cv);
237#endif 303#endif
238 } 304 }
239} 305}
240 306
241static void 307static void
242put_padlist (CV *cv) 308put_padlist (pTHX_ CV *cv)
243{ 309{
244 MAGIC *mg = mg_find ((SV *)cv, PERL_MAGIC_coro); 310 MAGIC *mg = CORO_MAGIC (cv);
311 AV *av;
245 312
246 if (!mg) 313 if (!mg)
247 { 314 {
248 sv_magic ((SV *)cv, 0, PERL_MAGIC_coro, 0, 0); 315 sv_magic ((SV *)cv, 0, PERL_MAGIC_coro, 0, 0);
249 mg = mg_find ((SV *)cv, PERL_MAGIC_coro); 316 mg = mg_find ((SV *)cv, PERL_MAGIC_coro);
250 mg->mg_virtual = &vtbl_coro; 317 mg->mg_virtual = &vtbl_coro;
251 mg->mg_obj = (SV *)newAV (); 318 mg->mg_obj = (SV *)newAV ();
252 } 319 }
253 320
254 av_push ((AV *)mg->mg_obj, (SV *)CvPADLIST (cv)); 321 av = (AV *)mg->mg_obj;
322
323 if (AvFILLp (av) >= AvMAX (av))
324 av_extend (av, AvMAX (av) + 1);
325
326 AvARRAY (av)[++AvFILLp (av)] = (SV *)CvPADLIST (cv);
255} 327}
328
329/** load & save, init *******************************************************/
256 330
257#define SB do { 331#define SB do {
258#define SE } while (0) 332#define SE } while (0)
259 333
260#define LOAD(state) load_state((state));
261#define SAVE(state,flags) save_state((state),(flags));
262
263#define REPLACE_SV(sv,val) SB SvREFCNT_dec(sv); (sv) = (val); (val) = 0; SE 334#define REPLACE_SV(sv,val) SB SvREFCNT_dec (sv); (sv) = (val); (val) = 0; SE
264 335
265static void 336static void
266load_state(Coro__State c) 337load_perl (pTHX_ Coro__State c)
267{ 338{
268#define VAR(name,type) PL_ ## name = c->name; 339#define VAR(name,type) PL_ ## name = c->name;
269# include "state.h" 340# include "state.h"
270#undef VAR 341#undef VAR
271 342
272 if (c->defav) REPLACE_SV (GvAV (PL_defgv), c->defav); 343 if (c->defav) REPLACE_SV (GvAV (PL_defgv), c->defav);
273 if (c->defsv) REPLACE_SV (DEFSV , c->defsv); 344 if (c->defsv) REPLACE_SV (DEFSV , c->defsv);
274 if (c->errsv) REPLACE_SV (ERRSV , c->errsv); 345 if (c->errsv) REPLACE_SV (ERRSV , c->errsv);
346 if (c->irssv)
347 {
348 if (c->irssv == PL_rs || sv_eq (PL_rs, c->irssv))
349 SvREFCNT_dec (c->irssv);
350 else
351 {
352 REPLACE_SV (PL_rs, c->irssv);
353 if (!c->irssv_sv) c->irssv_sv = get_sv ("/", 0);
354 sv_setsv (c->irssv_sv, PL_rs);
355 }
356 }
275 357
276 { 358 {
277 dSP; 359 dSP;
278 CV *cv; 360 CV *cv;
279 361
280 /* now do the ugly restore mess */ 362 /* now do the ugly restore mess */
281 while ((cv = (CV *)POPs)) 363 while ((cv = (CV *)POPs))
282 { 364 {
283 AV *padlist = (AV *)POPs;
284
285 if (padlist)
286 {
287 put_padlist (cv); /* mark this padlist as available */ 365 put_padlist (aTHX_ cv); /* mark this padlist as available */
288 CvPADLIST(cv) = padlist; 366 CvDEPTH (cv) = PTR2IV (POPs);
289 } 367 CvPADLIST (cv) = (AV *)POPs;
290
291 ++CvDEPTH(cv);
292 } 368 }
293 369
294 PUTBACK; 370 PUTBACK;
295 } 371 }
372 assert (!PL_comppad || AvARRAY (PL_comppad));//D
296} 373}
297 374
298static void 375static void
299save_state(Coro__State c, int flags) 376save_perl (pTHX_ Coro__State c)
300{ 377{
378 assert (!PL_comppad || AvARRAY (PL_comppad));//D
301 { 379 {
302 dSP; 380 dSP;
303 I32 cxix = cxstack_ix; 381 I32 cxix = cxstack_ix;
304 PERL_CONTEXT *ccstk = cxstack; 382 PERL_CONTEXT *ccstk = cxstack;
305 PERL_SI *top_si = PL_curstackinfo; 383 PERL_SI *top_si = PL_curstackinfo;
307 /* 385 /*
308 * the worst thing you can imagine happens first - we have to save 386 * the worst thing you can imagine happens first - we have to save
309 * (and reinitialize) all cv's in the whole callchain :( 387 * (and reinitialize) all cv's in the whole callchain :(
310 */ 388 */
311 389
390 EXTEND (SP, 3 + 1);
312 PUSHs (Nullsv); 391 PUSHs (Nullsv);
313 /* this loop was inspired by pp_caller */ 392 /* this loop was inspired by pp_caller */
314 for (;;) 393 for (;;)
315 { 394 {
316 while (cxix >= 0) 395 while (cxix >= 0)
317 { 396 {
318 PERL_CONTEXT *cx = &ccstk[cxix--]; 397 PERL_CONTEXT *cx = &ccstk[cxix--];
319 398
320 if (CxTYPE(cx) == CXt_SUB) 399 if (CxTYPE (cx) == CXt_SUB)
321 { 400 {
322 CV *cv = cx->blk_sub.cv; 401 CV *cv = cx->blk_sub.cv;
402
323 if (CvDEPTH(cv)) 403 if (CvDEPTH (cv))
324 { 404 {
325 EXTEND (SP, CvDEPTH(cv)*2); 405 EXTEND (SP, 3);
326
327 while (--CvDEPTH(cv))
328 {
329 /* this tells the restore code to increment CvDEPTH */
330 PUSHs (Nullsv);
331 PUSHs ((SV *)cv);
332 }
333
334 PUSHs ((SV *)CvPADLIST(cv)); 406 PUSHs ((SV *)CvPADLIST (cv));
407 PUSHs (INT2PTR (SV *, CvDEPTH (cv)));
335 PUSHs ((SV *)cv); 408 PUSHs ((SV *)cv);
336 409
410 CvDEPTH (cv) = 0;
337 get_padlist (cv); 411 get_padlist (aTHX_ cv);
338 } 412 }
339 } 413 }
340#ifdef CXt_FORMAT
341 else if (CxTYPE(cx) == CXt_FORMAT)
342 {
343 /* I never used formats, so how should I know how these are implemented? */
344 /* my bold guess is as a simple, plain sub... */
345 croak ("CXt_FORMAT not yet handled. Don't switch coroutines from within formats");
346 }
347#endif
348 } 414 }
349 415
350 if (top_si->si_type == PERLSI_MAIN) 416 if (top_si->si_type == PERLSI_MAIN)
351 break; 417 break;
352 418
356 } 422 }
357 423
358 PUTBACK; 424 PUTBACK;
359 } 425 }
360 426
361 c->defav = flags & TRANSFER_SAVE_DEFAV ? (AV *)SvREFCNT_inc (GvAV (PL_defgv)) : 0; 427 c->defav = c->save & CORO_SAVE_DEFAV ? (AV *)SvREFCNT_inc (GvAV (PL_defgv)) : 0;
362 c->defsv = flags & TRANSFER_SAVE_DEFSV ? SvREFCNT_inc (DEFSV) : 0; 428 c->defsv = c->save & CORO_SAVE_DEFSV ? SvREFCNT_inc (DEFSV) : 0;
363 c->errsv = flags & TRANSFER_SAVE_ERRSV ? SvREFCNT_inc (ERRSV) : 0; 429 c->errsv = c->save & CORO_SAVE_ERRSV ? SvREFCNT_inc (ERRSV) : 0;
430 c->irssv = c->save & CORO_SAVE_IRSSV ? SvREFCNT_inc (PL_rs) : 0;
364 431
365#define VAR(name,type)c->name = PL_ ## name; 432#define VAR(name,type)c->name = PL_ ## name;
366# include "state.h" 433# include "state.h"
367#undef VAR 434#undef VAR
368} 435}
371 * allocate various perl stacks. This is an exact copy 438 * allocate various perl stacks. This is an exact copy
372 * of perl.c:init_stacks, except that it uses less memory 439 * of perl.c:init_stacks, except that it uses less memory
373 * on the (sometimes correct) assumption that coroutines do 440 * on the (sometimes correct) assumption that coroutines do
374 * not usually need a lot of stackspace. 441 * not usually need a lot of stackspace.
375 */ 442 */
443#if CORO_PREFER_PERL_FUNCTIONS
444# define coro_init_stacks init_stacks
445#else
376static void 446static void
377coro_init_stacks () 447coro_init_stacks (pTHX)
378{ 448{
379 PL_curstackinfo = new_stackinfo(96, 1024/sizeof(PERL_CONTEXT) - 1); 449 PL_curstackinfo = new_stackinfo(128, 1024/sizeof(PERL_CONTEXT));
380 PL_curstackinfo->si_type = PERLSI_MAIN; 450 PL_curstackinfo->si_type = PERLSI_MAIN;
381 PL_curstack = PL_curstackinfo->si_stack; 451 PL_curstack = PL_curstackinfo->si_stack;
382 PL_mainstack = PL_curstack; /* remember in case we switch stacks */ 452 PL_mainstack = PL_curstack; /* remember in case we switch stacks */
383 453
384 PL_stack_base = AvARRAY(PL_curstack); 454 PL_stack_base = AvARRAY(PL_curstack);
385 PL_stack_sp = PL_stack_base; 455 PL_stack_sp = PL_stack_base;
386 PL_stack_max = PL_stack_base + AvMAX(PL_curstack); 456 PL_stack_max = PL_stack_base + AvMAX(PL_curstack);
387 457
388 New(50,PL_tmps_stack,96,SV*); 458 New(50,PL_tmps_stack,128,SV*);
389 PL_tmps_floor = -1; 459 PL_tmps_floor = -1;
390 PL_tmps_ix = -1; 460 PL_tmps_ix = -1;
391 PL_tmps_max = 96; 461 PL_tmps_max = 128;
392 462
393 New(54,PL_markstack,16,I32); 463 New(54,PL_markstack,32,I32);
394 PL_markstack_ptr = PL_markstack; 464 PL_markstack_ptr = PL_markstack;
395 PL_markstack_max = PL_markstack + 16; 465 PL_markstack_max = PL_markstack + 32;
396 466
397#ifdef SET_MARK_OFFSET 467#ifdef SET_MARK_OFFSET
398 SET_MARK_OFFSET; 468 SET_MARK_OFFSET;
399#endif 469#endif
400 470
401 New(54,PL_scopestack,16,I32); 471 New(54,PL_scopestack,32,I32);
402 PL_scopestack_ix = 0; 472 PL_scopestack_ix = 0;
403 PL_scopestack_max = 16; 473 PL_scopestack_max = 32;
404 474
405 New(54,PL_savestack,96,ANY); 475 New(54,PL_savestack,64,ANY);
406 PL_savestack_ix = 0; 476 PL_savestack_ix = 0;
407 PL_savestack_max = 96; 477 PL_savestack_max = 64;
408 478
409#if !PERL_VERSION_ATLEAST (5,9,0) 479#if !PERL_VERSION_ATLEAST (5,9,0)
410 New(54,PL_retstack,8,OP*); 480 New(54,PL_retstack,16,OP*);
411 PL_retstack_ix = 0; 481 PL_retstack_ix = 0;
412 PL_retstack_max = 8; 482 PL_retstack_max = 16;
413#endif 483#endif
414} 484}
485#endif
415 486
416/* 487/*
417 * destroy the stacks, the callchain etc... 488 * destroy the stacks, the callchain etc...
418 */ 489 */
419static void 490static void
420coro_destroy_stacks () 491coro_destroy_stacks (pTHX)
421{ 492{
422 if (!IN_DESTRUCT) 493 if (!IN_DESTRUCT)
423 { 494 {
424 /* is this ugly, I ask? */ 495 /* restore all saved variables and stuff */
425 LEAVE_SCOPE (0); 496 LEAVE_SCOPE (0);
497 assert (PL_tmps_floor == -1);
426 498
427 /* sure it is, but more important: is it correct?? :/ */ 499 /* free all temporaries */
428 FREETMPS; 500 FREETMPS;
501 assert (PL_tmps_ix == -1);
429 502
503 /* unwind all extra stacks */
430 /*POPSTACK_TO (PL_mainstack);*//*D*//*use*/ 504 POPSTACK_TO (PL_mainstack);
505
506 /* unwind main stack */
507 dounwind (-1);
431 } 508 }
432 509
433 while (PL_curstackinfo->si_next) 510 while (PL_curstackinfo->si_next)
434 PL_curstackinfo = PL_curstackinfo->si_next; 511 PL_curstackinfo = PL_curstackinfo->si_next;
435 512
436 while (PL_curstackinfo) 513 while (PL_curstackinfo)
437 { 514 {
438 PERL_SI *p = PL_curstackinfo->si_prev; 515 PERL_SI *p = PL_curstackinfo->si_prev;
439 516
440 { /*D*//*remove*/
441 dSP;
442 SWITCHSTACK (PL_curstack, PL_curstackinfo->si_stack);
443 PUTBACK; /* possibly superfluous */
444 }
445
446 if (!IN_DESTRUCT) 517 if (!IN_DESTRUCT)
447 {
448 dounwind (-1);/*D*//*remove*/
449 SvREFCNT_dec (PL_curstackinfo->si_stack); 518 SvREFCNT_dec (PL_curstackinfo->si_stack);
450 }
451 519
452 Safefree (PL_curstackinfo->si_cxstack); 520 Safefree (PL_curstackinfo->si_cxstack);
453 Safefree (PL_curstackinfo); 521 Safefree (PL_curstackinfo);
454 PL_curstackinfo = p; 522 PL_curstackinfo = p;
455 } 523 }
461#if !PERL_VERSION_ATLEAST (5,9,0) 529#if !PERL_VERSION_ATLEAST (5,9,0)
462 Safefree (PL_retstack); 530 Safefree (PL_retstack);
463#endif 531#endif
464} 532}
465 533
534/** coroutine stack handling ************************************************/
535
466static void 536static void
467setup_coro (struct coro *coro) 537setup_coro (pTHX_ struct coro *coro)
468{ 538{
469 /* 539 /*
470 * emulate part of the perl startup here. 540 * emulate part of the perl startup here.
471 */ 541 */
472
473 coro_init_stacks (); 542 coro_init_stacks (aTHX);
474 543
544 PL_curcop = &PL_compiling;
545 PL_in_eval = EVAL_NULL;
475 PL_curcop = 0; 546 PL_comppad = 0;
476 PL_in_eval = 0;
477 PL_curpm = 0; 547 PL_curpm = 0;
548 PL_localizing = 0;
549 PL_dirty = 0;
550 PL_restartop = 0;
478 551
479 { 552 {
480 dSP; 553 dSP;
481 LOGOP myop; 554 LOGOP myop;
482 555
483 /* I have no idea why this is needed, but it is */
484 PUSHMARK (SP);
485
486 SvREFCNT_dec (GvAV (PL_defgv)); 556 SvREFCNT_dec (GvAV (PL_defgv));
487 GvAV (PL_defgv) = coro->args; coro->args = 0; 557 GvAV (PL_defgv) = coro->args; coro->args = 0;
488 558
489 Zero (&myop, 1, LOGOP); 559 Zero (&myop, 1, LOGOP);
490 myop.op_next = Nullop; 560 myop.op_next = Nullop;
491 myop.op_flags = OPf_WANT_VOID; 561 myop.op_flags = OPf_WANT_VOID;
492 562
493 PL_op = (OP *)&myop;
494
495 PUSHMARK (SP); 563 PUSHMARK (SP);
496 XPUSHs ((SV *)get_cv ("Coro::State::_coro_init", FALSE)); 564 XPUSHs ((SV *)get_cv ("Coro::State::_coro_init", FALSE));
497 PUTBACK; 565 PUTBACK;
566 PL_op = (OP *)&myop;
498 PL_op = PL_ppaddr[OP_ENTERSUB](aTHX); 567 PL_op = PL_ppaddr[OP_ENTERSUB](aTHX);
499 SPAGAIN; 568 SPAGAIN;
500
501 ENTER; /* necessary e.g. for dounwind */
502 } 569 }
503}
504 570
571 ENTER; /* necessary e.g. for dounwind */
572}
573
505static void 574static void
506free_coro_mortal () 575free_coro_mortal (pTHX)
507{ 576{
508 if (coro_mortal) 577 if (coro_mortal)
509 { 578 {
510 SvREFCNT_dec (coro_mortal); 579 SvREFCNT_dec (coro_mortal);
511 coro_mortal = 0; 580 coro_mortal = 0;
512 } 581 }
513} 582}
514 583
584/* inject a fake call to Coro::State::_cctx_init into the execution */
515static void NOINLINE 585static void NOINLINE
516prepare_cctx (coro_cctx *cctx) 586prepare_cctx (pTHX_ coro_cctx *cctx)
517{ 587{
518 dSP; 588 dSP;
519 LOGOP myop; 589 LOGOP myop;
520 590
521 Zero (&myop, 1, LOGOP); 591 Zero (&myop, 1, LOGOP);
522 myop.op_next = PL_op; 592 myop.op_next = PL_op;
523 myop.op_flags = OPf_WANT_VOID; 593 myop.op_flags = OPf_WANT_VOID | OPf_STACKED;
524
525 sv_setiv (get_sv ("Coro::State::_cctx", FALSE), PTR2IV (cctx));
526 594
527 PUSHMARK (SP); 595 PUSHMARK (SP);
596 EXTEND (SP, 2);
597 PUSHs (sv_2mortal (newSViv (PTR2IV (cctx))));
528 XPUSHs ((SV *)get_cv ("Coro::State::_cctx_init", FALSE)); 598 PUSHs ((SV *)get_cv ("Coro::State::_cctx_init", FALSE));
529 PUTBACK; 599 PUTBACK;
600 PL_op = (OP *)&myop;
530 PL_restartop = PL_ppaddr[OP_ENTERSUB](aTHX); 601 PL_op = PL_ppaddr[OP_ENTERSUB](aTHX);
531 SPAGAIN; 602 SPAGAIN;
532} 603}
533 604
534static void 605static void
535coro_run (void *arg) 606coro_run (void *arg)
536{ 607{
608 dTHX;
609
537 /* coro_run is the alternative epilogue of transfer() */ 610 /* coro_run is the alternative tail of transfer(), so unlock here. */
538 UNLOCK; 611 UNLOCK;
539 612
540 /* 613 /*
541 * this is a _very_ stripped down perl interpreter ;) 614 * this is a _very_ stripped down perl interpreter ;)
542 */ 615 */
543 PL_top_env = &PL_start_env; 616 PL_top_env = &PL_start_env;
544 617
545 /* inject call to cctx_init */ 618 /* inject call to cctx_init */
546 prepare_cctx ((coro_cctx *)arg); 619 prepare_cctx (aTHX_ (coro_cctx *)arg);
547 620
548 /* somebody will hit me for both perl_run and PL_restartop */ 621 /* somebody will hit me for both perl_run and PL_restartop */
622 PL_restartop = PL_op;
549 perl_run (PL_curinterp); 623 perl_run (PL_curinterp);
550 624
551 fputs ("FATAL: C coroutine fell over the edge of the world, aborting. Did you call exit in a coroutine?\n", stderr); 625 fputs ("FATAL: C coroutine fell over the edge of the world, aborting. Did you call exit in a coroutine?\n", stderr);
552 abort (); 626 abort ();
553} 627}
554 628
555static coro_cctx * 629static coro_cctx *
556cctx_new () 630cctx_new ()
557{ 631{
558 coro_cctx *cctx; 632 coro_cctx *cctx;
633 void *stack_start;
634 size_t stack_size;
559 635
560 ++cctx_count; 636 ++cctx_count;
561 637
562 New (0, cctx, 1, coro_cctx); 638 Newz (0, cctx, 1, coro_cctx);
563 639
564#if HAVE_MMAP 640#if HAVE_MMAP
565 641
566 cctx->ssize = ((STACKSIZE * sizeof (long) + PAGESIZE - 1) / PAGESIZE + STACKGUARD) * PAGESIZE; 642 cctx->ssize = ((coro_stacksize * sizeof (long) + PAGESIZE - 1) / PAGESIZE + CORO_STACKGUARD) * PAGESIZE;
567 /* mmap suppsedly does allocate-on-write for us */ 643 /* mmap supposedly does allocate-on-write for us */
568 cctx->sptr = mmap (0, cctx->ssize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 0, 0); 644 cctx->sptr = mmap (0, cctx->ssize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);
569 645
570 if (cctx->sptr == (void *)-1) 646 if (cctx->sptr != (void *)-1)
571 {
572 perror ("FATAL: unable to mmap stack for coroutine");
573 _exit (EXIT_FAILURE);
574 } 647 {
575
576# if STACKGUARD 648# if CORO_STACKGUARD
577 mprotect (cctx->sptr, STACKGUARD * PAGESIZE, PROT_NONE); 649 mprotect (cctx->sptr, CORO_STACKGUARD * PAGESIZE, PROT_NONE);
578# endif 650# endif
651 stack_start = CORO_STACKGUARD * PAGESIZE + (char *)cctx->sptr;
652 stack_size = cctx->ssize - CORO_STACKGUARD * PAGESIZE;
653 cctx->mapped = 1;
654 }
655 else
656#endif
657 {
658 cctx->ssize = coro_stacksize * (long)sizeof (long);
659 New (0, cctx->sptr, coro_stacksize, long);
579 660
580#else
581
582 cctx->ssize = STACKSIZE * (long)sizeof (long);
583 New (0, cctx->sptr, STACKSIZE, long);
584
585 if (!cctx->sptr) 661 if (!cctx->sptr)
586 { 662 {
587 perror ("FATAL: unable to malloc stack for coroutine"); 663 perror ("FATAL: unable to allocate stack for coroutine");
588 _exit (EXIT_FAILURE); 664 _exit (EXIT_FAILURE);
589 } 665 }
590 666
591#endif 667 stack_start = cctx->sptr;
668 stack_size = cctx->ssize;
669 }
592 670
593#if USE_VALGRIND 671 REGISTER_STACK (cctx, (char *)stack_start, (char *)stack_start + stack_size);
594 cctx->valgrind_id = VALGRIND_STACK_REGISTER (
595 STACKGUARD * PAGESIZE + (char *)cctx->sptr,
596 cctx->ssize + (char *)cctx->sptr
597 );
598#endif
599
600 coro_create (&cctx->cctx, coro_run, (void *)cctx, cctx->sptr, cctx->ssize); 672 coro_create (&cctx->cctx, coro_run, (void *)cctx, stack_start, stack_size);
601 673
602 return cctx; 674 return cctx;
603} 675}
604 676
605static void 677static void
606cctx_free (coro_cctx *cctx) 678cctx_destroy (coro_cctx *cctx)
607{ 679{
608 if (!cctx) 680 if (!cctx)
609 return; 681 return;
610 682
611 --cctx_count; 683 --cctx_count;
612 684
613#if USE_VALGRIND 685#if CORO_USE_VALGRIND
614 VALGRIND_STACK_DEREGISTER (cctx->valgrind_id); 686 VALGRIND_STACK_DEREGISTER (cctx->valgrind_id);
615#endif 687#endif
616 688
617#if HAVE_MMAP 689#if HAVE_MMAP
690 if (cctx->mapped)
618 munmap (cctx->sptr, cctx->ssize); 691 munmap (cctx->sptr, cctx->ssize);
619#else 692 else
693#endif
620 Safefree (cctx->sptr); 694 Safefree (cctx->sptr);
621#endif
622 695
623 Safefree (cctx); 696 Safefree (cctx);
624} 697}
625 698
626static coro_cctx * 699static coro_cctx *
627cctx_get () 700cctx_get (pTHX)
628{ 701{
629 coro_cctx *cctx;
630
631 if (cctx_first) 702 while (cctx_first)
632 { 703 {
704 coro_cctx *cctx = cctx_first;
705 cctx_first = cctx->next;
633 --cctx_idle; 706 --cctx_idle;
634 cctx = cctx_first; 707
635 cctx_first = cctx->next; 708 if (cctx->ssize >= coro_stacksize)
709 return cctx;
710
711 cctx_destroy (cctx);
636 } 712 }
637 else 713
638 {
639 cctx = cctx_new ();
640 PL_op = PL_op->op_next; 714 PL_op = PL_op->op_next;
641 }
642
643 return cctx; 715 return cctx_new ();
644} 716}
645 717
646static void 718static void
647cctx_put (coro_cctx *cctx) 719cctx_put (coro_cctx *cctx)
648{ 720{
721 /* free another cctx if overlimit */
722 if (cctx_idle >= MAX_IDLE_CCTX)
723 {
724 coro_cctx *first = cctx_first;
725 cctx_first = first->next;
726 --cctx_idle;
727
728 assert (!first->inuse);
729 cctx_destroy (first);
730 }
731
649 ++cctx_idle; 732 ++cctx_idle;
650 cctx->next = cctx_first; 733 cctx->next = cctx_first;
651 cctx_first = cctx; 734 cctx_first = cctx;
652} 735}
653 736
737/** coroutine switching *****************************************************/
738
654/* never call directly, always through the coro_state_transfer global variable */ 739/* never call directly, always through the coro_state_transfer global variable */
655static void NOINLINE 740static void NOINLINE
656transfer (struct coro *prev, struct coro *next, int flags) 741transfer (pTHX_ struct coro *prev, struct coro *next)
657{ 742{
658 dSTACKLEVEL; 743 dSTACKLEVEL;
659 744
660 /* sometimes transfer is only called to set idle_sp */ 745 /* sometimes transfer is only called to set idle_sp */
661 if (flags == TRANSFER_SET_STACKLEVEL) 746 if (!next)
747 {
662 ((coro_cctx *)prev)->idle_sp = STACKLEVEL; 748 ((coro_cctx *)prev)->idle_sp = STACKLEVEL;
749 assert (((coro_cctx *)prev)->idle_te = PL_top_env); /* just for the side-effect when asserts are enabled */
750 }
663 else if (prev != next) 751 else if (prev != next)
664 { 752 {
665 coro_cctx *prev__cctx; 753 coro_cctx *prev__cctx;
666 754
755 if (prev->flags & CF_NEW)
756 {
757 /* create a new empty context */
758 Newz (0, prev->cctx, 1, coro_cctx);
759 prev->cctx->inuse = 1;
760 prev->flags &= ~CF_NEW;
761 prev->flags |= CF_RUNNING;
762 }
763
764 /*TODO: must not croak here */
765 if (!prev->flags & CF_RUNNING)
766 croak ("Coro::State::transfer called with non-running prev Coro::State, but can only transfer from running states");
767
768 if (next->flags & CF_RUNNING)
769 croak ("Coro::State::transfer called with running next Coro::State, but can only transfer to inactive states");
770
771 if (next->flags & CF_DESTROYED)
772 croak ("Coro::State::transfer called with destroyed next Coro::State, but can only transfer to inactive states");
773
774 prev->flags &= ~CF_RUNNING;
775 next->flags |= CF_RUNNING;
776
667 LOCK; 777 LOCK;
668 778
669 if (next->mainstack) 779 if (next->flags & CF_NEW)
670 { 780 {
671 /* coroutine already started */ 781 /* need to start coroutine */
672 SAVE (prev, flags); 782 next->flags &= ~CF_NEW;
673 LOAD (next); 783 /* first get rid of the old state */
784 save_perl (aTHX_ prev);
785 /* setup coroutine call */
786 setup_coro (aTHX_ next);
787 /* need a new stack */
788 assert (!next->cctx);
674 } 789 }
675 else 790 else
676 { 791 {
677 /* need to start coroutine */ 792 /* coroutine already started */
678 /* first get rid of the old state */ 793 save_perl (aTHX_ prev);
679 SAVE (prev, -1); 794 load_perl (aTHX_ next);
680 /* setup coroutine call */
681 setup_coro (next);
682 /* need a stack */
683 next->cctx = 0;
684 } 795 }
685
686 if (!prev->cctx)
687 /* create a new empty context */
688 Newz (0, prev->cctx, 1, coro_cctx);
689 796
690 prev__cctx = prev->cctx; 797 prev__cctx = prev->cctx;
691 798
692 /* possibly "free" the cctx */ 799 /* possibly "free" the cctx */
693 if (prev__cctx->idle_sp == STACKLEVEL) 800 if (prev__cctx->idle_sp == STACKLEVEL)
694 { 801 {
802 /* I assume that STACKLEVEL is a stronger indicator than PL_top_env changes */
803 assert (("ERROR: current top_env must equal previous top_env", PL_top_env == prev__cctx->idle_te));
804
805 prev->cctx = 0;
806
695 cctx_put (prev__cctx); 807 cctx_put (prev__cctx);
696 prev->cctx = 0; 808 prev__cctx->inuse = 0;
697 } 809 }
698 810
699 if (!next->cctx) 811 if (!next->cctx)
812 {
700 next->cctx = cctx_get (); 813 next->cctx = cctx_get (aTHX);
814 assert (!next->cctx->inuse);
815 next->cctx->inuse = 1;
816 }
701 817
702 if (prev__cctx != next->cctx) 818 if (prev__cctx != next->cctx)
703 { 819 {
704 prev__cctx->top_env = PL_top_env; 820 prev__cctx->top_env = PL_top_env;
705 PL_top_env = next->cctx->top_env; 821 PL_top_env = next->cctx->top_env;
706 coro_transfer (&prev__cctx->cctx, &next->cctx->cctx); 822 coro_transfer (&prev__cctx->cctx, &next->cctx->cctx);
707 } 823 }
708 824
709 free_coro_mortal (); 825 free_coro_mortal (aTHX);
710
711 UNLOCK; 826 UNLOCK;
712 } 827 }
713} 828}
714 829
715struct transfer_args 830struct transfer_args
716{ 831{
717 struct coro *prev, *next; 832 struct coro *prev, *next;
718 int flags;
719}; 833};
720 834
721#define TRANSFER(ta) transfer ((ta).prev, (ta).next, (ta).flags) 835#define TRANSFER(ta) transfer (aTHX_ (ta).prev, (ta).next)
722 836
837/** high level stuff ********************************************************/
838
723static void 839static int
724coro_state_destroy (struct coro *coro) 840coro_state_destroy (pTHX_ struct coro *coro)
725{ 841{
726 if (coro->refcnt--) 842 if (coro->flags & CF_DESTROYED)
727 return; 843 return 0;
844
845 coro->flags |= CF_DESTROYED;
846
847 if (coro->flags & CF_READY)
848 {
849 /* reduce nready, as destroying a ready coro effectively unreadies it */
850 /* alternative: look through all ready queues and remove the coro */
851 LOCK;
852 --coro_nready;
853 UNLOCK;
854 }
855 else
856 coro->flags |= CF_READY; /* make sure it is NOT put into the readyqueue */
728 857
729 if (coro->mainstack && coro->mainstack != main_mainstack) 858 if (coro->mainstack && coro->mainstack != main_mainstack)
730 { 859 {
731 struct coro temp; 860 struct coro temp;
732 861
733 SAVE ((&temp), TRANSFER_SAVE_ALL); 862 assert (!(coro->flags & CF_RUNNING));
734 LOAD (coro);
735 863
864 Zero (&temp, 1, struct coro);
865 temp.save = CORO_SAVE_ALL;
866
867 if (coro->flags & CF_RUNNING)
868 croak ("FATAL: tried to destroy currently running coroutine");
869
870 save_perl (aTHX_ &temp);
871 load_perl (aTHX_ coro);
872
736 coro_destroy_stacks (); 873 coro_destroy_stacks (aTHX);
737 874
738 LOAD ((&temp)); /* this will get rid of defsv etc.. */ 875 load_perl (aTHX_ &temp); /* this will get rid of defsv etc.. */
739 876
740 coro->mainstack = 0; 877 coro->mainstack = 0;
741 } 878 }
742 879
743 cctx_free (coro->cctx); 880 cctx_destroy (coro->cctx);
744 SvREFCNT_dec (coro->args); 881 SvREFCNT_dec (coro->args);
745 Safefree (coro); 882
883 return 1;
746} 884}
747 885
748static int 886static int
749coro_state_clear (pTHX_ SV *sv, MAGIC *mg) 887coro_state_free (pTHX_ SV *sv, MAGIC *mg)
750{ 888{
751 struct coro *coro = (struct coro *)mg->mg_ptr; 889 struct coro *coro = (struct coro *)mg->mg_ptr;
752 mg->mg_ptr = 0; 890 mg->mg_ptr = 0;
753 891
892 if (--coro->refcnt < 0)
893 {
754 coro_state_destroy (coro); 894 coro_state_destroy (aTHX_ coro);
895 Safefree (coro);
896 }
755 897
756 return 0; 898 return 0;
757} 899}
758 900
759static int 901static int
766 return 0; 908 return 0;
767} 909}
768 910
769static MGVTBL coro_state_vtbl = { 911static MGVTBL coro_state_vtbl = {
770 0, 0, 0, 0, 912 0, 0, 0, 0,
771 coro_state_clear, 913 coro_state_free,
772 0, 914 0,
773#ifdef MGf_DUP 915#ifdef MGf_DUP
774 coro_state_dup, 916 coro_state_dup,
775#else 917#else
776# define MGf_DUP 0 918# define MGf_DUP 0
777#endif 919#endif
778}; 920};
779 921
780static struct coro * 922static struct coro *
781SvSTATE (SV *coro) 923SvSTATE_ (pTHX_ SV *coro)
782{ 924{
783 HV *stash; 925 HV *stash;
784 MAGIC *mg; 926 MAGIC *mg;
785 927
786 if (SvROK (coro)) 928 if (SvROK (coro))
792 /* very slow, but rare, check */ 934 /* very slow, but rare, check */
793 if (!sv_derived_from (sv_2mortal (newRV_inc (coro)), "Coro::State")) 935 if (!sv_derived_from (sv_2mortal (newRV_inc (coro)), "Coro::State"))
794 croak ("Coro::State object required"); 936 croak ("Coro::State object required");
795 } 937 }
796 938
797 mg = SvMAGIC (coro); 939 mg = CORO_MAGIC (coro);
798 assert (mg->mg_type == PERL_MAGIC_ext);
799 return (struct coro *)mg->mg_ptr; 940 return (struct coro *)mg->mg_ptr;
800} 941}
801 942
943#define SvSTATE(sv) SvSTATE_ (aTHX_ (sv))
944
802static void 945static void
803prepare_transfer (struct transfer_args *ta, SV *prev, SV *next, int flags) 946prepare_transfer (pTHX_ struct transfer_args *ta, SV *prev_sv, SV *next_sv)
804{ 947{
805 ta->prev = SvSTATE (prev); 948 ta->prev = SvSTATE (prev_sv);
806 ta->next = SvSTATE (next); 949 ta->next = SvSTATE (next_sv);
807 ta->flags = flags;
808} 950}
809 951
810static void 952static void
811api_transfer (SV *prev, SV *next, int flags) 953api_transfer (SV *prev_sv, SV *next_sv)
812{ 954{
813 dTHX; 955 dTHX;
814 struct transfer_args ta; 956 struct transfer_args ta;
815 957
816 prepare_transfer (&ta, prev, next, flags); 958 prepare_transfer (aTHX_ &ta, prev_sv, next_sv);
817 TRANSFER (ta); 959 TRANSFER (ta);
818} 960}
819 961
962static int
963api_save (SV *coro_sv, int new_save)
964{
965 dTHX;
966 struct coro *coro = SvSTATE (coro_sv);
967 int old_save = coro->save;
968
969 if (new_save >= 0)
970 coro->save = new_save;
971
972 return old_save;
973}
974
820/** Coro ********************************************************************/ 975/** Coro ********************************************************************/
821 976
822#define PRIO_MAX 3
823#define PRIO_HIGH 1
824#define PRIO_NORMAL 0
825#define PRIO_LOW -1
826#define PRIO_IDLE -3
827#define PRIO_MIN -4
828
829/* for Coro.pm */
830static GV *coro_current, *coro_idle;
831static AV *coro_ready [PRIO_MAX-PRIO_MIN+1];
832static int coro_nready;
833
834static void 977static void
835coro_enq (SV *sv) 978coro_enq (pTHX_ SV *coro_sv)
836{ 979{
837 int prio;
838
839 if (SvTYPE (sv) != SVt_PVHV)
840 croak ("Coro::ready tried to enqueue something that is not a coroutine");
841
842 prio = SvSTATE (sv)->prio;
843
844 av_push (coro_ready [prio - PRIO_MIN], sv); 980 av_push (coro_ready [SvSTATE (coro_sv)->prio - PRIO_MIN], coro_sv);
845 coro_nready++;
846} 981}
847 982
848static SV * 983static SV *
849coro_deq (int min_prio) 984coro_deq (pTHX_ int min_prio)
850{ 985{
851 int prio = PRIO_MAX - PRIO_MIN; 986 int prio = PRIO_MAX - PRIO_MIN;
852 987
853 min_prio -= PRIO_MIN; 988 min_prio -= PRIO_MIN;
854 if (min_prio < 0) 989 if (min_prio < 0)
855 min_prio = 0; 990 min_prio = 0;
856 991
857 for (prio = PRIO_MAX - PRIO_MIN + 1; --prio >= min_prio; ) 992 for (prio = PRIO_MAX - PRIO_MIN + 1; --prio >= min_prio; )
858 if (AvFILLp (coro_ready [prio]) >= 0) 993 if (AvFILLp (coro_ready [prio]) >= 0)
859 {
860 coro_nready--;
861 return av_shift (coro_ready [prio]); 994 return av_shift (coro_ready [prio]);
862 }
863 995
864 return 0; 996 return 0;
865} 997}
866 998
867static void 999static int
868api_ready (SV *coro) 1000api_ready (SV *coro_sv)
869{ 1001{
870 dTHX; 1002 dTHX;
1003 struct coro *coro;
871 1004
872 if (SvROK (coro)) 1005 if (SvROK (coro_sv))
873 coro = SvRV (coro); 1006 coro_sv = SvRV (coro_sv);
1007
1008 coro = SvSTATE (coro_sv);
1009
1010 if (coro->flags & CF_READY)
1011 return 0;
1012
1013 coro->flags |= CF_READY;
874 1014
875 LOCK; 1015 LOCK;
876 coro_enq (SvREFCNT_inc (coro)); 1016 coro_enq (aTHX_ SvREFCNT_inc (coro_sv));
1017 ++coro_nready;
877 UNLOCK; 1018 UNLOCK;
878}
879 1019
1020 return 1;
1021}
1022
880static void 1023static int
1024api_is_ready (SV *coro_sv)
1025{
1026 dTHX;
1027 return !!(SvSTATE (coro_sv)->flags & CF_READY);
1028}
1029
1030static void
881prepare_schedule (struct transfer_args *ta) 1031prepare_schedule (pTHX_ struct transfer_args *ta)
882{ 1032{
883 SV *current, *prev, *next; 1033 SV *prev_sv, *next_sv;
884
885 current = GvSV (coro_current);
886 1034
887 for (;;) 1035 for (;;)
888 { 1036 {
889 LOCK; 1037 LOCK;
890 next = coro_deq (PRIO_MIN); 1038 next_sv = coro_deq (aTHX_ PRIO_MIN);
1039
1040 /* nothing to schedule: call the idle handler */
1041 if (!next_sv)
1042 {
1043 dSP;
1044 UNLOCK;
1045
1046 ENTER;
1047 SAVETMPS;
1048
1049 PUSHMARK (SP);
1050 PUTBACK;
1051 call_sv (get_sv ("Coro::idle", FALSE), G_DISCARD);
1052
1053 FREETMPS;
1054 LEAVE;
1055 continue;
1056 }
1057
1058 ta->next = SvSTATE (next_sv);
1059
1060 /* cannot transfer to destroyed coros, skip and look for next */
1061 if (ta->next->flags & CF_DESTROYED)
1062 {
1063 UNLOCK;
1064 SvREFCNT_dec (next_sv);
1065 /* coro_nready is already taken care of by destroy */
1066 continue;
1067 }
1068
1069 --coro_nready;
891 UNLOCK; 1070 UNLOCK;
892
893 if (next)
894 break; 1071 break;
895
896 {
897 dSP;
898
899 ENTER;
900 SAVETMPS;
901
902 PUSHMARK (SP);
903 PUTBACK;
904 call_sv (GvSV (coro_idle), G_DISCARD);
905
906 FREETMPS;
907 LEAVE;
908 } 1072 }
909 }
910
911 prev = SvRV (current);
912 SvRV (current) = next;
913 1073
914 /* free this only after the transfer */ 1074 /* free this only after the transfer */
1075 prev_sv = SvRV (coro_current);
1076 SvRV_set (coro_current, next_sv);
1077 ta->prev = SvSTATE (prev_sv);
1078
1079 assert (ta->next->flags & CF_READY);
1080 ta->next->flags &= ~CF_READY;
1081
915 LOCK; 1082 LOCK;
916 free_coro_mortal (); 1083 free_coro_mortal (aTHX);
1084 coro_mortal = prev_sv;
917 UNLOCK; 1085 UNLOCK;
918 coro_mortal = prev;
919
920 ta->prev = SvSTATE (prev);
921 ta->next = SvSTATE (next);
922 ta->flags = TRANSFER_SAVE_ALL;
923} 1086}
924 1087
925static void 1088static void
926prepare_cede (struct transfer_args *ta) 1089prepare_cede (pTHX_ struct transfer_args *ta)
927{ 1090{
928 LOCK; 1091 api_ready (coro_current);
929 coro_enq (SvREFCNT_inc (SvRV (GvSV (coro_current))));
930 UNLOCK;
931
932 prepare_schedule (ta); 1092 prepare_schedule (aTHX_ ta);
1093}
1094
1095static int
1096prepare_cede_notself (pTHX_ struct transfer_args *ta)
1097{
1098 if (coro_nready)
1099 {
1100 SV *prev = SvRV (coro_current);
1101 prepare_schedule (aTHX_ ta);
1102 api_ready (prev);
1103 return 1;
1104 }
1105 else
1106 return 0;
933} 1107}
934 1108
935static void 1109static void
936api_schedule (void) 1110api_schedule (void)
937{ 1111{
938 dTHX; 1112 dTHX;
939 struct transfer_args ta; 1113 struct transfer_args ta;
940 1114
941 prepare_schedule (&ta); 1115 prepare_schedule (aTHX_ &ta);
942 TRANSFER (ta); 1116 TRANSFER (ta);
943} 1117}
944 1118
945static void 1119static int
946api_cede (void) 1120api_cede (void)
947{ 1121{
948 dTHX; 1122 dTHX;
949 struct transfer_args ta; 1123 struct transfer_args ta;
950 1124
951 prepare_cede (&ta); 1125 prepare_cede (aTHX_ &ta);
1126
1127 if (ta.prev != ta.next)
1128 {
952 TRANSFER (ta); 1129 TRANSFER (ta);
1130 return 1;
1131 }
1132 else
1133 return 0;
1134}
1135
1136static int
1137api_cede_notself (void)
1138{
1139 dTHX;
1140 struct transfer_args ta;
1141
1142 if (prepare_cede_notself (aTHX_ &ta))
1143 {
1144 TRANSFER (ta);
1145 return 1;
1146 }
1147 else
1148 return 0;
953} 1149}
954 1150
955MODULE = Coro::State PACKAGE = Coro::State 1151MODULE = Coro::State PACKAGE = Coro::State
956 1152
957PROTOTYPES: DISABLE 1153PROTOTYPES: DISABLE
963#endif 1159#endif
964 BOOT_PAGESIZE; 1160 BOOT_PAGESIZE;
965 1161
966 coro_state_stash = gv_stashpv ("Coro::State", TRUE); 1162 coro_state_stash = gv_stashpv ("Coro::State", TRUE);
967 1163
968 newCONSTSUB (coro_state_stash, "SAVE_DEFAV", newSViv (TRANSFER_SAVE_DEFAV)); 1164 newCONSTSUB (coro_state_stash, "SAVE_DEFAV", newSViv (CORO_SAVE_DEFAV));
969 newCONSTSUB (coro_state_stash, "SAVE_DEFSV", newSViv (TRANSFER_SAVE_DEFSV)); 1165 newCONSTSUB (coro_state_stash, "SAVE_DEFSV", newSViv (CORO_SAVE_DEFSV));
970 newCONSTSUB (coro_state_stash, "SAVE_ERRSV", newSViv (TRANSFER_SAVE_ERRSV)); 1166 newCONSTSUB (coro_state_stash, "SAVE_ERRSV", newSViv (CORO_SAVE_ERRSV));
1167 newCONSTSUB (coro_state_stash, "SAVE_IRSSV", newSViv (CORO_SAVE_IRSSV));
1168 newCONSTSUB (coro_state_stash, "SAVE_ALL", newSViv (CORO_SAVE_ALL));
971 1169
972 main_mainstack = PL_mainstack; 1170 main_mainstack = PL_mainstack;
973 1171
974 coroapi.ver = CORO_API_VERSION; 1172 coroapi.ver = CORO_API_VERSION;
975 coroapi.transfer = api_transfer; 1173 coroapi.transfer = api_transfer;
985 HV *hv; 1183 HV *hv;
986 int i; 1184 int i;
987 1185
988 Newz (0, coro, 1, struct coro); 1186 Newz (0, coro, 1, struct coro);
989 coro->args = newAV (); 1187 coro->args = newAV ();
1188 coro->save = CORO_SAVE_ALL;
1189 coro->flags = CF_NEW;
990 1190
991 hv = newHV (); 1191 hv = newHV ();
992 sv_magicext ((SV *)hv, 0, PERL_MAGIC_ext, &coro_state_vtbl, (char *)coro, 0)->mg_flags |= MGf_DUP; 1192 sv_magicext ((SV *)hv, 0, PERL_MAGIC_ext, &coro_state_vtbl, (char *)coro, 0)->mg_flags |= MGf_DUP;
993 RETVAL = sv_bless (newRV_noinc ((SV *)hv), gv_stashpv (klass, 1)); 1193 RETVAL = sv_bless (newRV_noinc ((SV *)hv), gv_stashpv (klass, 1));
994 1194
995 for (i = 1; i < items; i++) 1195 for (i = 1; i < items; i++)
996 av_push (coro->args, newSVsv (ST (i))); 1196 av_push (coro->args, newSVsv (ST (i)));
997} 1197}
998 OUTPUT: 1198 OUTPUT:
1199 RETVAL
1200
1201int
1202save (SV *coro, int new_save = -1)
1203 CODE:
1204 RETVAL = api_save (coro, new_save);
1205 OUTPUT:
999 RETVAL 1206 RETVAL
1000 1207
1001void 1208void
1002_set_stacklevel (...) 1209_set_stacklevel (...)
1003 ALIAS: 1210 ALIAS:
1004 Coro::State::transfer = 1 1211 Coro::State::transfer = 1
1005 Coro::schedule = 2 1212 Coro::schedule = 2
1006 Coro::cede = 3 1213 Coro::cede = 3
1007 Coro::Cont::yield = 4 1214 Coro::cede_notself = 4
1008 CODE: 1215 CODE:
1009{ 1216{
1010 struct transfer_args ta; 1217 struct transfer_args ta;
1011 1218
1012 switch (ix) 1219 switch (ix)
1013 { 1220 {
1014 case 0: 1221 case 0:
1015 ta.prev = (struct coro *)INT2PTR (coro_cctx *, SvIV (ST (0))); 1222 ta.prev = (struct coro *)INT2PTR (coro_cctx *, SvIV (ST (0)));
1016 ta.next = 0; 1223 ta.next = 0;
1017 ta.flags = TRANSFER_SET_STACKLEVEL;
1018 break; 1224 break;
1019 1225
1020 case 1: 1226 case 1:
1021 if (items != 3) 1227 if (items != 2)
1022 croak ("Coro::State::transfer(prev,next,flags) expects three arguments, not %d", items); 1228 croak ("Coro::State::transfer (prev,next) expects two arguments, not %d", items);
1023 1229
1024 prepare_transfer (&ta, ST (0), ST (1), SvIV (ST (2))); 1230 prepare_transfer (aTHX_ &ta, ST (0), ST (1));
1025 break; 1231 break;
1026 1232
1027 case 2: 1233 case 2:
1028 prepare_schedule (&ta); 1234 prepare_schedule (aTHX_ &ta);
1029 break; 1235 break;
1030 1236
1031 case 3: 1237 case 3:
1032 prepare_cede (&ta); 1238 prepare_cede (aTHX_ &ta);
1033 break; 1239 break;
1034 1240
1035 case 4: 1241 case 4:
1036 { 1242 if (!prepare_cede_notself (aTHX_ &ta))
1037 SV *yieldstack; 1243 XSRETURN_EMPTY;
1038 SV *sv;
1039 AV *defav = GvAV (PL_defgv);
1040 1244
1041 yieldstack = *hv_fetch (
1042 (HV *)SvRV (GvSV (coro_current)),
1043 "yieldstack", sizeof ("yieldstack") - 1,
1044 0
1045 );
1046
1047 /* set up @_ -- ugly */
1048 av_clear (defav);
1049 av_fill (defav, items - 1);
1050 while (items--)
1051 av_store (defav, items, SvREFCNT_inc (ST(items)));
1052
1053 sv = av_pop ((AV *)SvRV (yieldstack));
1054 ta.prev = SvSTATE (*av_fetch ((AV *)SvRV (sv), 0, 0));
1055 ta.next = SvSTATE (*av_fetch ((AV *)SvRV (sv), 1, 0));
1056 ta.flags = 0;
1057 SvREFCNT_dec (sv);
1058 }
1059 break; 1245 break;
1060
1061 } 1246 }
1062 1247
1248 BARRIER;
1063 TRANSFER (ta); 1249 TRANSFER (ta);
1064}
1065 1250
1066void 1251 if (GIMME_V != G_VOID && ta.next != ta.prev)
1067_clone_state_from (SV *dst, SV *src) 1252 XSRETURN_YES;
1253}
1254
1255bool
1256_destroy (SV *coro_sv)
1068 CODE: 1257 CODE:
1069{ 1258 RETVAL = coro_state_destroy (aTHX_ SvSTATE (coro_sv));
1070 struct coro *coro_src = SvSTATE (src); 1259 OUTPUT:
1071 1260 RETVAL
1072 sv_unmagic (SvRV (dst), PERL_MAGIC_ext);
1073
1074 ++coro_src->refcnt;
1075 sv_magicext (SvRV (dst), 0, PERL_MAGIC_ext, &coro_state_vtbl, (char *)coro_src, 0)->mg_flags |= MGf_DUP;
1076}
1077 1261
1078void 1262void
1079_exit (code) 1263_exit (code)
1080 int code 1264 int code
1081 PROTOTYPE: $ 1265 PROTOTYPE: $
1082 CODE: 1266 CODE:
1083 _exit (code); 1267 _exit (code);
1084 1268
1085int 1269int
1270cctx_stacksize (int new_stacksize = 0)
1271 CODE:
1272 RETVAL = coro_stacksize;
1273 if (new_stacksize)
1274 coro_stacksize = new_stacksize;
1275 OUTPUT:
1276 RETVAL
1277
1278int
1086cctx_count () 1279cctx_count ()
1087 CODE: 1280 CODE:
1088 RETVAL = cctx_count; 1281 RETVAL = cctx_count;
1089 OUTPUT: 1282 OUTPUT:
1090 RETVAL 1283 RETVAL
1109 newCONSTSUB (coro_stash, "PRIO_NORMAL", newSViv (PRIO_NORMAL)); 1302 newCONSTSUB (coro_stash, "PRIO_NORMAL", newSViv (PRIO_NORMAL));
1110 newCONSTSUB (coro_stash, "PRIO_LOW", newSViv (PRIO_LOW)); 1303 newCONSTSUB (coro_stash, "PRIO_LOW", newSViv (PRIO_LOW));
1111 newCONSTSUB (coro_stash, "PRIO_IDLE", newSViv (PRIO_IDLE)); 1304 newCONSTSUB (coro_stash, "PRIO_IDLE", newSViv (PRIO_IDLE));
1112 newCONSTSUB (coro_stash, "PRIO_MIN", newSViv (PRIO_MIN)); 1305 newCONSTSUB (coro_stash, "PRIO_MIN", newSViv (PRIO_MIN));
1113 1306
1114 coro_current = gv_fetchpv ("Coro::current", TRUE, SVt_PV); 1307 coro_current = get_sv ("Coro::current", FALSE);
1115 coro_idle = gv_fetchpv ("Coro::idle" , TRUE, SVt_PV); 1308 SvREADONLY_on (coro_current);
1116 1309
1117 for (i = PRIO_MAX - PRIO_MIN + 1; i--; ) 1310 for (i = PRIO_MAX - PRIO_MIN + 1; i--; )
1118 coro_ready[i] = newAV (); 1311 coro_ready[i] = newAV ();
1119 1312
1120 { 1313 {
1121 SV *sv = perl_get_sv("Coro::API", 1); 1314 SV *sv = perl_get_sv("Coro::API", 1);
1122 1315
1123 coroapi.schedule = api_schedule; 1316 coroapi.schedule = api_schedule;
1317 coroapi.save = api_save;
1124 coroapi.cede = api_cede; 1318 coroapi.cede = api_cede;
1319 coroapi.cede_notself = api_cede_notself;
1125 coroapi.ready = api_ready; 1320 coroapi.ready = api_ready;
1321 coroapi.is_ready = api_is_ready;
1126 coroapi.nready = &coro_nready; 1322 coroapi.nready = &coro_nready;
1127 coroapi.current = coro_current; 1323 coroapi.current = coro_current;
1128 1324
1129 GCoroAPI = &coroapi; 1325 GCoroAPI = &coroapi;
1130 sv_setiv (sv, (IV)&coroapi); 1326 sv_setiv (sv, (IV)&coroapi);
1131 SvREADONLY_on (sv); 1327 SvREADONLY_on (sv);
1132 } 1328 }
1133} 1329}
1330
1331void
1332_set_current (SV *current)
1333 PROTOTYPE: $
1334 CODE:
1335 SvREFCNT_dec (SvRV (coro_current));
1336 SvRV_set (coro_current, SvREFCNT_inc (SvRV (current)));
1134 1337
1135int 1338int
1136prio (Coro::State coro, int newprio = 0) 1339prio (Coro::State coro, int newprio = 0)
1137 ALIAS: 1340 ALIAS:
1138 nice = 1 1341 nice = 1
1141 RETVAL = coro->prio; 1344 RETVAL = coro->prio;
1142 1345
1143 if (items > 1) 1346 if (items > 1)
1144 { 1347 {
1145 if (ix) 1348 if (ix)
1146 newprio += coro->prio; 1349 newprio = coro->prio - newprio;
1147 1350
1148 if (newprio < PRIO_MIN) newprio = PRIO_MIN; 1351 if (newprio < PRIO_MIN) newprio = PRIO_MIN;
1149 if (newprio > PRIO_MAX) newprio = PRIO_MAX; 1352 if (newprio > PRIO_MAX) newprio = PRIO_MAX;
1150 1353
1151 coro->prio = newprio; 1354 coro->prio = newprio;
1152 } 1355 }
1153} 1356}
1357 OUTPUT:
1358 RETVAL
1154 1359
1155void 1360SV *
1156ready (SV *self) 1361ready (SV *self)
1157 PROTOTYPE: $ 1362 PROTOTYPE: $
1158 CODE: 1363 CODE:
1159 api_ready (self); 1364 RETVAL = boolSV (api_ready (self));
1365 OUTPUT:
1366 RETVAL
1367
1368SV *
1369is_ready (SV *self)
1370 PROTOTYPE: $
1371 CODE:
1372 RETVAL = boolSV (api_is_ready (self));
1373 OUTPUT:
1374 RETVAL
1160 1375
1161int 1376int
1162nready (...) 1377nready (...)
1163 PROTOTYPE: 1378 PROTOTYPE:
1164 CODE: 1379 CODE:
1170 1385
1171SV * 1386SV *
1172_get_state () 1387_get_state ()
1173 CODE: 1388 CODE:
1174{ 1389{
1175 struct { 1390 struct io_state *data;
1176 int errorno;
1177 int laststype;
1178 int laststatval;
1179 Stat_t statcache;
1180 } data;
1181 1391
1392 RETVAL = newSV (sizeof (struct io_state));
1393 data = (struct io_state *)SvPVX (RETVAL);
1394 SvCUR_set (RETVAL, sizeof (struct io_state));
1395 SvPOK_only (RETVAL);
1396
1182 data.errorno = errno; 1397 data->errorno = errno;
1183 data.laststype = PL_laststype; 1398 data->laststype = PL_laststype;
1184 data.laststatval = PL_laststatval; 1399 data->laststatval = PL_laststatval;
1185 data.statcache = PL_statcache; 1400 data->statcache = PL_statcache;
1186
1187 RETVAL = newSVpvn ((char *)&data, sizeof data);
1188} 1401}
1189 OUTPUT: 1402 OUTPUT:
1190 RETVAL 1403 RETVAL
1191 1404
1192void 1405void
1193_set_state (char *data_) 1406_set_state (char *data_)
1194 PROTOTYPE: $ 1407 PROTOTYPE: $
1195 CODE: 1408 CODE:
1196{ 1409{
1197 struct { 1410 struct io_state *data = (void *)data_;
1198 int errorno;
1199 int laststype;
1200 int laststatval;
1201 Stat_t statcache;
1202 } *data = (void *)data_;
1203 1411
1204 errno = data->errorno; 1412 errno = data->errorno;
1205 PL_laststype = data->laststype; 1413 PL_laststype = data->laststype;
1206 PL_laststatval = data->laststatval; 1414 PL_laststatval = data->laststatval;
1207 PL_statcache = data->statcache; 1415 PL_statcache = data->statcache;
1208} 1416}
1417

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines