OSDN Git Service

compiler, runtime: Check make int64 args for overflow.
[pf3gnuchains/gcc-fork.git] / libgo / runtime / chan.c
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 #include "runtime.h"
6 #include "go-type.h"
7
8 #define NOSELGEN        1
9
10 static  int32   debug   = 0;
11
12 typedef struct  WaitQ   WaitQ;
13 typedef struct  SudoG   SudoG;
14 typedef struct  Select  Select;
15 typedef struct  Scase   Scase;
16
17 typedef struct  __go_type_descriptor    Type;
18 typedef struct  __go_channel_type       ChanType;
19
20 struct  SudoG
21 {
22         G*      g;              // g and selgen constitute
23         uint32  selgen;         // a weak pointer to g
24         SudoG*  link;
25         byte*   elem;           // data element
26 };
27
28 struct  WaitQ
29 {
30         SudoG*  first;
31         SudoG*  last;
32 };
33
34 struct  Hchan
35 {
36         uint32  qcount;                 // total data in the q
37         uint32  dataqsiz;               // size of the circular q
38         uint16  elemsize;
39         bool    closed;
40         uint8   elemalign;
41         uint32  sendx;                  // send index
42         uint32  recvx;                  // receive index
43         WaitQ   recvq;                  // list of recv waiters
44         WaitQ   sendq;                  // list of send waiters
45         Lock;
46 };
47
48 // Buffer follows Hchan immediately in memory.
49 // chanbuf(c, i) is pointer to the i'th slot in the buffer.
50 #define chanbuf(c, i) ((byte*)((c)+1)+(uintptr)(c)->elemsize*(i))
51
52 enum
53 {
54         // Scase.kind
55         CaseRecv,
56         CaseSend,
57         CaseDefault,
58 };
59
60 struct  Scase
61 {
62         SudoG   sg;                     // must be first member (cast to Scase)
63         Hchan*  chan;                   // chan
64         uint16  kind;
65         uint16  index;                  // index to return
66         bool*   receivedp;              // pointer to received bool (recv2)
67 };
68
69 struct  Select
70 {
71         uint16  tcase;                  // total count of scase[]
72         uint16  ncase;                  // currently filled scase[]
73         uint16* pollorder;              // case poll order
74         Hchan** lockorder;              // channel lock order
75         Scase   scase[1];               // one per case (in order of appearance)
76 };
77
78 static  void    dequeueg(WaitQ*);
79 static  SudoG*  dequeue(WaitQ*);
80 static  void    enqueue(WaitQ*, SudoG*);
81
82 Hchan*
83 runtime_makechan_c(ChanType *t, int64 hint)
84 {
85         Hchan *c;
86         int32 n;
87         const Type *elem;
88         
89         elem = t->__element_type;
90
91         if(hint < 0 || (int32)hint != hint || (elem->__size > 0 && (uintptr)hint > ((uintptr)-1) / elem->__size))
92                 runtime_panicstring("makechan: size out of range");
93
94         n = sizeof(*c);
95
96         // allocate memory in one call
97         c = (Hchan*)runtime_mal(n + hint*elem->__size);
98         c->elemsize = elem->__size;
99         c->elemalign = elem->__align;
100         c->dataqsiz = hint;
101
102         if(debug)
103                 runtime_printf("makechan: chan=%p; elemsize=%lld; elemalign=%d; dataqsiz=%d\n",
104                         c, (long long)elem->__size, elem->__align, c->dataqsiz);
105
106         return c;
107 }
108
109 // For reflect
110 //      func makechan(typ *ChanType, size uint32) (chan)
111 uintptr reflect_makechan(ChanType *, uint32)
112   asm ("libgo_reflect.reflect.makechan");
113
114 uintptr
115 reflect_makechan(ChanType *t, uint32 size)
116 {
117         void *ret;
118         Hchan *c;
119
120         c = runtime_makechan_c(t, size);
121         ret = runtime_mal(sizeof(void*));
122         __builtin_memcpy(ret, &c, sizeof(void*));
123         return (uintptr)ret;
124 }
125
126 // makechan(t *ChanType, hint int64) (hchan *chan any);
127 Hchan*
128 __go_new_channel(ChanType *t, uintptr hint)
129 {
130         return runtime_makechan_c(t, hint);
131 }
132
133 Hchan*
134 __go_new_channel_big(ChanType *t, uint64 hint)
135 {
136         return runtime_makechan_c(t, hint);
137 }
138
139 /*
140  * generic single channel send/recv
141  * if the bool pointer is nil,
142  * then the full exchange will
143  * occur. if pres is not nil,
144  * then the protocol will not
145  * sleep but return if it could
146  * not complete.
147  *
148  * sleep can wake up with g->param == nil
149  * when a channel involved in the sleep has
150  * been closed.  it is easiest to loop and re-run
151  * the operation; we'll see that it's now closed.
152  */
153 void
154 runtime_chansend(ChanType *t, Hchan *c, byte *ep, bool *pres)
155 {
156         SudoG *sg;
157         SudoG mysg;
158         G* gp;
159         G* g;
160
161         g = runtime_g();
162
163         if(c == nil) {
164                 USED(t);
165                 if(pres != nil) {
166                         *pres = false;
167                         return;
168                 }
169                 g->status = Gwaiting;
170                 g->waitreason = "chan send (nil chan)";
171                 runtime_gosched();
172                 return;  // not reached
173         }
174
175         if(runtime_gcwaiting)
176                 runtime_gosched();
177
178         if(debug) {
179                 runtime_printf("chansend: chan=%p\n", c);
180         }
181
182         runtime_lock(c);
183         if(c->closed)
184                 goto closed;
185
186         if(c->dataqsiz > 0)
187                 goto asynch;
188
189         sg = dequeue(&c->recvq);
190         if(sg != nil) {
191                 runtime_unlock(c);
192                 
193                 gp = sg->g;
194                 gp->param = sg;
195                 if(sg->elem != nil)
196                         runtime_memmove(sg->elem, ep, c->elemsize);
197                 runtime_ready(gp);
198
199                 if(pres != nil)
200                         *pres = true;
201                 return;
202         }
203
204         if(pres != nil) {
205                 runtime_unlock(c);
206                 *pres = false;
207                 return;
208         }
209
210         mysg.elem = ep;
211         mysg.g = g;
212         mysg.selgen = NOSELGEN;
213         g->param = nil;
214         g->status = Gwaiting;
215         g->waitreason = "chan send";
216         enqueue(&c->sendq, &mysg);
217         runtime_unlock(c);
218         runtime_gosched();
219
220         if(g->param == nil) {
221                 runtime_lock(c);
222                 if(!c->closed)
223                         runtime_throw("chansend: spurious wakeup");
224                 goto closed;
225         }
226
227         return;
228
229 asynch:
230         if(c->closed)
231                 goto closed;
232
233         if(c->qcount >= c->dataqsiz) {
234                 if(pres != nil) {
235                         runtime_unlock(c);
236                         *pres = false;
237                         return;
238                 }
239                 mysg.g = g;
240                 mysg.elem = nil;
241                 mysg.selgen = NOSELGEN;
242                 g->status = Gwaiting;
243                 g->waitreason = "chan send";
244                 enqueue(&c->sendq, &mysg);
245                 runtime_unlock(c);
246                 runtime_gosched();
247
248                 runtime_lock(c);
249                 goto asynch;
250         }
251         runtime_memmove(chanbuf(c, c->sendx), ep, c->elemsize);
252         if(++c->sendx == c->dataqsiz)
253                 c->sendx = 0;
254         c->qcount++;
255
256         sg = dequeue(&c->recvq);
257         if(sg != nil) {
258                 gp = sg->g;
259                 runtime_unlock(c);
260                 runtime_ready(gp);
261         } else
262                 runtime_unlock(c);
263         if(pres != nil)
264                 *pres = true;
265         return;
266
267 closed:
268         runtime_unlock(c);
269         runtime_panicstring("send on closed channel");
270 }
271
272
273 void
274 runtime_chanrecv(ChanType *t, Hchan* c, byte *ep, bool *selected, bool *received)
275 {
276         SudoG *sg;
277         SudoG mysg;
278         G *gp;
279         G *g;
280
281         if(runtime_gcwaiting)
282                 runtime_gosched();
283
284         if(debug)
285                 runtime_printf("chanrecv: chan=%p\n", c);
286
287         g = runtime_g();
288
289         if(c == nil) {
290                 USED(t);
291                 if(selected != nil) {
292                         *selected = false;
293                         return;
294                 }
295                 g->status = Gwaiting;
296                 g->waitreason = "chan receive (nil chan)";
297                 runtime_gosched();
298                 return;  // not reached
299         }
300
301         runtime_lock(c);
302         if(c->dataqsiz > 0)
303                 goto asynch;
304
305         if(c->closed)
306                 goto closed;
307
308         sg = dequeue(&c->sendq);
309         if(sg != nil) {
310                 runtime_unlock(c);
311
312                 if(ep != nil)
313                         runtime_memmove(ep, sg->elem, c->elemsize);
314                 gp = sg->g;
315                 gp->param = sg;
316                 runtime_ready(gp);
317
318                 if(selected != nil)
319                         *selected = true;
320                 if(received != nil)
321                         *received = true;
322                 return;
323         }
324
325         if(selected != nil) {
326                 runtime_unlock(c);
327                 *selected = false;
328                 return;
329         }
330
331         mysg.elem = ep;
332         mysg.g = g;
333         mysg.selgen = NOSELGEN;
334         g->param = nil;
335         g->status = Gwaiting;
336         g->waitreason = "chan receive";
337         enqueue(&c->recvq, &mysg);
338         runtime_unlock(c);
339         runtime_gosched();
340
341         if(g->param == nil) {
342                 runtime_lock(c);
343                 if(!c->closed)
344                         runtime_throw("chanrecv: spurious wakeup");
345                 goto closed;
346         }
347
348         if(received != nil)
349                 *received = true;
350         return;
351
352 asynch:
353         if(c->qcount <= 0) {
354                 if(c->closed)
355                         goto closed;
356
357                 if(selected != nil) {
358                         runtime_unlock(c);
359                         *selected = false;
360                         if(received != nil)
361                                 *received = false;
362                         return;
363                 }
364                 mysg.g = g;
365                 mysg.elem = nil;
366                 mysg.selgen = NOSELGEN;
367                 g->status = Gwaiting;
368                 g->waitreason = "chan receive";
369                 enqueue(&c->recvq, &mysg);
370                 runtime_unlock(c);
371                 runtime_gosched();
372
373                 runtime_lock(c);
374                 goto asynch;
375         }
376         if(ep != nil)
377                 runtime_memmove(ep, chanbuf(c, c->recvx), c->elemsize);
378         runtime_memclr(chanbuf(c, c->recvx), c->elemsize);
379         if(++c->recvx == c->dataqsiz)
380                 c->recvx = 0;
381         c->qcount--;
382
383         sg = dequeue(&c->sendq);
384         if(sg != nil) {
385                 gp = sg->g;
386                 runtime_unlock(c);
387                 runtime_ready(gp);
388         } else
389                 runtime_unlock(c);
390
391         if(selected != nil)
392                 *selected = true;
393         if(received != nil)
394                 *received = true;
395         return;
396
397 closed:
398         if(ep != nil)
399                 runtime_memclr(ep, c->elemsize);
400         if(selected != nil)
401                 *selected = true;
402         if(received != nil)
403                 *received = false;
404         runtime_unlock(c);
405 }
406
407 // The compiler generates a call to __go_send_small to send a value 8
408 // bytes or smaller.
409 void
410 __go_send_small(ChanType *t, Hchan* c, uint64 val)
411 {
412         byte b[sizeof(uint64)];
413
414         runtime_memclr(b, sizeof(uint64));
415         __builtin_memcpy(b, &val, t->__element_type->__size);
416         runtime_chansend(t, c, b, nil);
417 }
418
419 // The compiler generates a call to __go_send_big to send a value
420 // larger than 8 bytes or smaller.
421 void
422 __go_send_big(ChanType *t, Hchan* c, byte* p)
423 {
424         runtime_chansend(t, c, p, nil);
425 }
426
427 // The compiler generates a call to __go_receive_small to receive a
428 // value 8 bytes or smaller.
429 uint64
430 __go_receive_small(ChanType *t, Hchan* c)
431 {
432         union {
433                 byte b[sizeof(uint64)];
434                 uint64 v;
435         } u;
436
437         u.v = 0;
438         runtime_chanrecv(t, c, u.b, nil, nil);
439         return u.v;
440 }
441
442 // The compiler generates a call to __go_receive_big to receive a
443 // value larger than 8 bytes.
444 void
445 __go_receive_big(ChanType *t, Hchan* c, byte* p)
446 {
447         runtime_chanrecv(t, c, p, nil, nil);
448 }
449
450 _Bool runtime_chanrecv2(ChanType *t, Hchan* c, byte* p)
451   __asm__("runtime.chanrecv2");
452
453 _Bool
454 runtime_chanrecv2(ChanType *t, Hchan* c, byte* p)
455 {
456         bool received;
457
458         runtime_chanrecv(t, c, p, nil, &received);
459         return received;
460 }
461
462 // func selectnbsend(c chan any, elem any) bool
463 //
464 // compiler implements
465 //
466 //      select {
467 //      case c <- v:
468 //              ... foo
469 //      default:
470 //              ... bar
471 //      }
472 //
473 // as
474 //
475 //      if selectnbsend(c, v) {
476 //              ... foo
477 //      } else {
478 //              ... bar
479 //      }
480 //
481 _Bool
482 runtime_selectnbsend(ChanType *t, Hchan *c, byte *p)
483 {
484         bool res;
485
486         runtime_chansend(t, c, p, &res);
487         return res;
488 }
489
490 // func selectnbrecv(elem *any, c chan any) bool
491 //
492 // compiler implements
493 //
494 //      select {
495 //      case v = <-c:
496 //              ... foo
497 //      default:
498 //              ... bar
499 //      }
500 //
501 // as
502 //
503 //      if selectnbrecv(&v, c) {
504 //              ... foo
505 //      } else {
506 //              ... bar
507 //      }
508 //
509 _Bool
510 runtime_selectnbrecv(ChanType *t, byte *v, Hchan *c)
511 {
512         bool selected;
513
514         runtime_chanrecv(t, c, v, &selected, nil);
515         return selected;
516 }       
517
518 // func selectnbrecv2(elem *any, ok *bool, c chan any) bool
519 //
520 // compiler implements
521 //
522 //      select {
523 //      case v, ok = <-c:
524 //              ... foo
525 //      default:
526 //              ... bar
527 //      }
528 //
529 // as
530 //
531 //      if c != nil && selectnbrecv2(&v, &ok, c) {
532 //              ... foo
533 //      } else {
534 //              ... bar
535 //      }
536 //
537 _Bool
538 runtime_selectnbrecv2(ChanType *t, byte *v, _Bool *received, Hchan *c)
539 {
540         bool selected;
541         bool r;
542
543         r = false;
544         runtime_chanrecv(t, c, v, &selected, received == nil ? nil : &r);
545         if(received != nil)
546                 *received = r;
547         return selected;
548 }       
549
550 // For reflect:
551 //      func chansend(c chan, val iword, nb bool) (selected bool)
552 // where an iword is the same word an interface value would use:
553 // the actual data if it fits, or else a pointer to the data.
554
555 _Bool reflect_chansend(ChanType *, Hchan *, uintptr, _Bool)
556   __asm__("libgo_reflect.reflect.chansend");
557
558 _Bool
559 reflect_chansend(ChanType *t, Hchan *c, uintptr val, _Bool nb)
560 {
561         bool selected;
562         bool *sp;
563         byte *vp;
564         
565         if(nb) {
566                 selected = false;
567                 sp = (bool*)&selected;
568         } else {
569                 selected = true;
570                 sp = nil;
571         }
572         if(__go_is_pointer_type(t->__element_type))
573                 vp = (byte*)&val;
574         else
575                 vp = (byte*)val;
576         runtime_chansend(t, c, vp, sp);
577         return selected;
578 }
579
580 // For reflect:
581 //      func chanrecv(c chan, nb bool) (val iword, selected, received bool)
582 // where an iword is the same word an interface value would use:
583 // the actual data if it fits, or else a pointer to the data.
584
585 struct chanrecv_ret
586 {
587         uintptr val;
588         _Bool selected;
589         _Bool received;
590 };
591
592 struct chanrecv_ret reflect_chanrecv(ChanType *, Hchan *, _Bool)
593   __asm__("libgo_reflect.reflect.chanrecv");
594
595 struct chanrecv_ret
596 reflect_chanrecv(ChanType *t, Hchan *c, _Bool nb)
597 {
598         struct chanrecv_ret ret;
599         byte *vp;
600         bool *sp;
601         bool selected;
602         bool received;
603
604         if(nb) {
605                 selected = false;
606                 sp = &selected;
607         } else {
608                 ret.selected = true;
609                 sp = nil;
610         }
611         received = false;
612         if(__go_is_pointer_type(t->__element_type)) {
613                 vp = (byte*)&ret.val;
614         } else {
615                 vp = runtime_mal(t->__element_type->__size);
616                 ret.val = (uintptr)vp;
617         }
618         runtime_chanrecv(t, c, vp, sp, &received);
619         if(nb)
620                 ret.selected = selected;
621         ret.received = received;
622         return ret;
623 }
624
625 static void newselect(int32, Select**);
626
627 // newselect(size uint32) (sel *byte);
628
629 void* runtime_newselect(int) __asm__("runtime.newselect");
630
631 void*
632 runtime_newselect(int size)
633 {
634         Select *sel;
635
636         newselect(size, &sel);
637         return (void*)sel;
638 }
639
640 static void
641 newselect(int32 size, Select **selp)
642 {
643         int32 n;
644         Select *sel;
645
646         n = 0;
647         if(size > 1)
648                 n = size-1;
649
650         sel = runtime_mal(sizeof(*sel) +
651                 n*sizeof(sel->scase[0]) +
652                 size*sizeof(sel->lockorder[0]) +
653                 size*sizeof(sel->pollorder[0]));
654
655         sel->tcase = size;
656         sel->ncase = 0;
657         sel->pollorder = (void*)(sel->scase + size);
658         sel->lockorder = (void*)(sel->pollorder + size);
659         *selp = sel;
660
661         if(debug)
662                 runtime_printf("newselect s=%p size=%d\n", sel, size);
663 }
664
665 // cut in half to give stack a chance to split
666 static void selectsend(Select *sel, Hchan *c, int index, void *elem);
667
668 // selectsend(sel *byte, hchan *chan any, elem *any) (selected bool);
669
670 void runtime_selectsend(Select *, Hchan *, void *, int)
671   __asm__("runtime.selectsend");
672
673 void
674 runtime_selectsend(Select *sel, Hchan *c, void *elem, int index)
675 {
676         // nil cases do not compete
677         if(c == nil)
678                 return;
679         
680         selectsend(sel, c, index, elem);
681 }
682
683 static void
684 selectsend(Select *sel, Hchan *c, int index, void *elem)
685 {
686         int32 i;
687         Scase *cas;
688         
689         i = sel->ncase;
690         if(i >= sel->tcase)
691                 runtime_throw("selectsend: too many cases");
692         sel->ncase = i+1;
693         cas = &sel->scase[i];
694
695         cas->index = index;
696         cas->chan = c;
697         cas->kind = CaseSend;
698         cas->sg.elem = elem;
699
700         if(debug)
701                 runtime_printf("selectsend s=%p index=%d chan=%p\n",
702                         sel, cas->index, cas->chan);
703 }
704
705 // cut in half to give stack a chance to split
706 static void selectrecv(Select *sel, Hchan *c, int index, void *elem, bool*);
707
708 // selectrecv(sel *byte, hchan *chan any, elem *any) (selected bool);
709
710 void runtime_selectrecv(Select *, Hchan *, void *, int)
711   __asm__("runtime.selectrecv");
712
713 void
714 runtime_selectrecv(Select *sel, Hchan *c, void *elem, int index)
715 {
716         // nil cases do not compete
717         if(c == nil)
718                 return;
719
720         selectrecv(sel, c, index, elem, nil);
721 }
722
723 // selectrecv2(sel *byte, hchan *chan any, elem *any, received *bool) (selected bool);
724
725 void runtime_selectrecv2(Select *, Hchan *, void *, bool *, int)
726   __asm__("runtime.selectrecv2");
727
728 void
729 runtime_selectrecv2(Select *sel, Hchan *c, void *elem, bool *received, int index)
730 {
731         // nil cases do not compete
732         if(c == nil)
733                 return;
734
735         selectrecv(sel, c, index, elem, received);
736 }
737
738 static void
739 selectrecv(Select *sel, Hchan *c, int index, void *elem, bool *received)
740 {
741         int32 i;
742         Scase *cas;
743
744         i = sel->ncase;
745         if(i >= sel->tcase)
746                 runtime_throw("selectrecv: too many cases");
747         sel->ncase = i+1;
748         cas = &sel->scase[i];
749         cas->index = index;
750         cas->chan = c;
751
752         cas->kind = CaseRecv;
753         cas->sg.elem = elem;
754         cas->receivedp = received;
755
756         if(debug)
757                 runtime_printf("selectrecv s=%p index=%d chan=%p\n",
758                         sel, cas->index, cas->chan);
759 }
760
761 // cut in half to give stack a chance to split
762 static void selectdefault(Select*, int);
763
764 // selectdefault(sel *byte) (selected bool);
765
766 void runtime_selectdefault(Select *, int) __asm__("runtime.selectdefault");
767
768 void
769 runtime_selectdefault(Select *sel, int index)
770 {
771         selectdefault(sel, index);
772 }
773
774 static void
775 selectdefault(Select *sel, int index)
776 {
777         int32 i;
778         Scase *cas;
779
780         i = sel->ncase;
781         if(i >= sel->tcase)
782                 runtime_throw("selectdefault: too many cases");
783         sel->ncase = i+1;
784         cas = &sel->scase[i];
785         cas->index = index;
786         cas->chan = nil;
787
788         cas->kind = CaseDefault;
789
790         if(debug)
791                 runtime_printf("selectdefault s=%p index=%d\n",
792                         sel, cas->index);
793 }
794
795 static void
796 sellock(Select *sel)
797 {
798         uint32 i;
799         Hchan *c, *c0;
800
801         c = nil;
802         for(i=0; i<sel->ncase; i++) {
803                 c0 = sel->lockorder[i];
804                 if(c0 && c0 != c) {
805                         c = sel->lockorder[i];
806                         runtime_lock(c);
807                 }
808         }
809 }
810
811 static void
812 selunlock(Select *sel)
813 {
814         uint32 i;
815         Hchan *c, *c0;
816
817         c = nil;
818         for(i=sel->ncase; i-->0;) {
819                 c0 = sel->lockorder[i];
820                 if(c0 && c0 != c) {
821                         c = c0;
822                         runtime_unlock(c);
823                 }
824         }
825 }
826
827 void
828 runtime_block(void)
829 {
830         G *g;
831
832         g = runtime_g();
833         g->status = Gwaiting;   // forever
834         g->waitreason = "select (no cases)";
835         runtime_gosched();
836 }
837
838 static int selectgo(Select**);
839
840 // selectgo(sel *byte);
841
842 int runtime_selectgo(Select *) __asm__("runtime.selectgo");
843
844 int
845 runtime_selectgo(Select *sel)
846 {
847         return selectgo(&sel);
848 }
849
850 static int
851 selectgo(Select **selp)
852 {
853         Select *sel;
854         uint32 o, i, j;
855         Scase *cas, *dfl;
856         Hchan *c;
857         SudoG *sg;
858         G *gp;
859         int index;
860         G *g;
861
862         sel = *selp;
863         if(runtime_gcwaiting)
864                 runtime_gosched();
865
866         if(debug)
867                 runtime_printf("select: sel=%p\n", sel);
868
869         g = runtime_g();
870
871         // The compiler rewrites selects that statically have
872         // only 0 or 1 cases plus default into simpler constructs.
873         // The only way we can end up with such small sel->ncase
874         // values here is for a larger select in which most channels
875         // have been nilled out.  The general code handles those
876         // cases correctly, and they are rare enough not to bother
877         // optimizing (and needing to test).
878
879         // generate permuted order
880         for(i=0; i<sel->ncase; i++)
881                 sel->pollorder[i] = i;
882         for(i=1; i<sel->ncase; i++) {
883                 o = sel->pollorder[i];
884                 j = runtime_fastrand1()%(i+1);
885                 sel->pollorder[i] = sel->pollorder[j];
886                 sel->pollorder[j] = o;
887         }
888
889         // sort the cases by Hchan address to get the locking order.
890         for(i=0; i<sel->ncase; i++) {
891                 c = sel->scase[i].chan;
892                 for(j=i; j>0 && sel->lockorder[j-1] >= c; j--)
893                         sel->lockorder[j] = sel->lockorder[j-1];
894                 sel->lockorder[j] = c;
895         }
896         sellock(sel);
897
898 loop:
899         // pass 1 - look for something already waiting
900         dfl = nil;
901         for(i=0; i<sel->ncase; i++) {
902                 o = sel->pollorder[i];
903                 cas = &sel->scase[o];
904                 c = cas->chan;
905
906                 switch(cas->kind) {
907                 case CaseRecv:
908                         if(c->dataqsiz > 0) {
909                                 if(c->qcount > 0)
910                                         goto asyncrecv;
911                         } else {
912                                 sg = dequeue(&c->sendq);
913                                 if(sg != nil)
914                                         goto syncrecv;
915                         }
916                         if(c->closed)
917                                 goto rclose;
918                         break;
919
920                 case CaseSend:
921                         if(c->closed)
922                                 goto sclose;
923                         if(c->dataqsiz > 0) {
924                                 if(c->qcount < c->dataqsiz)
925                                         goto asyncsend;
926                         } else {
927                                 sg = dequeue(&c->recvq);
928                                 if(sg != nil)
929                                         goto syncsend;
930                         }
931                         break;
932
933                 case CaseDefault:
934                         dfl = cas;
935                         break;
936                 }
937         }
938
939         if(dfl != nil) {
940                 selunlock(sel);
941                 cas = dfl;
942                 goto retc;
943         }
944
945
946         // pass 2 - enqueue on all chans
947         for(i=0; i<sel->ncase; i++) {
948                 o = sel->pollorder[i];
949                 cas = &sel->scase[o];
950                 c = cas->chan;
951                 sg = &cas->sg;
952                 sg->g = g;
953                 sg->selgen = g->selgen;
954
955                 switch(cas->kind) {
956                 case CaseRecv:
957                         enqueue(&c->recvq, sg);
958                         break;
959                 
960                 case CaseSend:
961                         enqueue(&c->sendq, sg);
962                         break;
963                 }
964         }
965
966         g->param = nil;
967         g->status = Gwaiting;
968         g->waitreason = "select";
969         selunlock(sel);
970         runtime_gosched();
971
972         sellock(sel);
973         sg = g->param;
974
975         // pass 3 - dequeue from unsuccessful chans
976         // otherwise they stack up on quiet channels
977         for(i=0; i<sel->ncase; i++) {
978                 cas = &sel->scase[i];
979                 if(cas != (Scase*)sg) {
980                         c = cas->chan;
981                         if(cas->kind == CaseSend)
982                                 dequeueg(&c->sendq);
983                         else
984                                 dequeueg(&c->recvq);
985                 }
986         }
987
988         if(sg == nil)
989                 goto loop;
990
991         cas = (Scase*)sg;
992         c = cas->chan;
993
994         if(c->dataqsiz > 0)
995                 runtime_throw("selectgo: shouldnt happen");
996
997         if(debug)
998                 runtime_printf("wait-return: sel=%p c=%p cas=%p kind=%d\n",
999                         sel, c, cas, cas->kind);
1000
1001         if(cas->kind == CaseRecv) {
1002                 if(cas->receivedp != nil)
1003                         *cas->receivedp = true;
1004         }
1005
1006         selunlock(sel);
1007         goto retc;
1008
1009 asyncrecv:
1010         // can receive from buffer
1011         if(cas->receivedp != nil)
1012                 *cas->receivedp = true;
1013         if(cas->sg.elem != nil)
1014                 runtime_memmove(cas->sg.elem, chanbuf(c, c->recvx), c->elemsize);
1015         runtime_memclr(chanbuf(c, c->recvx), c->elemsize);
1016         if(++c->recvx == c->dataqsiz)
1017                 c->recvx = 0;
1018         c->qcount--;
1019         sg = dequeue(&c->sendq);
1020         if(sg != nil) {
1021                 gp = sg->g;
1022                 selunlock(sel);
1023                 runtime_ready(gp);
1024         } else {
1025                 selunlock(sel);
1026         }
1027         goto retc;
1028
1029 asyncsend:
1030         // can send to buffer
1031         runtime_memmove(chanbuf(c, c->sendx), cas->sg.elem, c->elemsize);
1032         if(++c->sendx == c->dataqsiz)
1033                 c->sendx = 0;
1034         c->qcount++;
1035         sg = dequeue(&c->recvq);
1036         if(sg != nil) {
1037                 gp = sg->g;
1038                 selunlock(sel);
1039                 runtime_ready(gp);
1040         } else {
1041                 selunlock(sel);
1042         }
1043         goto retc;
1044
1045 syncrecv:
1046         // can receive from sleeping sender (sg)
1047         selunlock(sel);
1048         if(debug)
1049                 runtime_printf("syncrecv: sel=%p c=%p o=%d\n", sel, c, o);
1050         if(cas->receivedp != nil)
1051                 *cas->receivedp = true;
1052         if(cas->sg.elem != nil)
1053                 runtime_memmove(cas->sg.elem, sg->elem, c->elemsize);
1054         gp = sg->g;
1055         gp->param = sg;
1056         runtime_ready(gp);
1057         goto retc;
1058
1059 rclose:
1060         // read at end of closed channel
1061         selunlock(sel);
1062         if(cas->receivedp != nil)
1063                 *cas->receivedp = false;
1064         if(cas->sg.elem != nil)
1065                 runtime_memclr(cas->sg.elem, c->elemsize);
1066         goto retc;
1067
1068 syncsend:
1069         // can send to sleeping receiver (sg)
1070         selunlock(sel);
1071         if(debug)
1072                 runtime_printf("syncsend: sel=%p c=%p o=%d\n", sel, c, o);
1073         if(sg->elem != nil)
1074                 runtime_memmove(sg->elem, cas->sg.elem, c->elemsize);
1075         gp = sg->g;
1076         gp->param = sg;
1077         runtime_ready(gp);
1078
1079 retc:
1080         // return index corresponding to chosen case
1081         index = cas->index;
1082         runtime_free(sel);
1083         return index;
1084
1085 sclose:
1086         // send on closed channel
1087         selunlock(sel);
1088         runtime_panicstring("send on closed channel");
1089         return 0;  // not reached
1090 }
1091
1092 // closechan(sel *byte);
1093 void
1094 runtime_closechan(Hchan *c)
1095 {
1096         SudoG *sg;
1097         G* gp;
1098
1099         if(c == nil)
1100                 runtime_panicstring("close of nil channel");
1101
1102         if(runtime_gcwaiting)
1103                 runtime_gosched();
1104
1105         runtime_lock(c);
1106         if(c->closed) {
1107                 runtime_unlock(c);
1108                 runtime_panicstring("close of closed channel");
1109         }
1110
1111         c->closed = true;
1112
1113         // release all readers
1114         for(;;) {
1115                 sg = dequeue(&c->recvq);
1116                 if(sg == nil)
1117                         break;
1118                 gp = sg->g;
1119                 gp->param = nil;
1120                 runtime_ready(gp);
1121         }
1122
1123         // release all writers
1124         for(;;) {
1125                 sg = dequeue(&c->sendq);
1126                 if(sg == nil)
1127                         break;
1128                 gp = sg->g;
1129                 gp->param = nil;
1130                 runtime_ready(gp);
1131         }
1132
1133         runtime_unlock(c);
1134 }
1135
1136 void
1137 __go_builtin_close(Hchan *c)
1138 {
1139         runtime_closechan(c);
1140 }
1141
1142 // For reflect
1143 //      func chanclose(c chan)
1144
1145 void reflect_chanclose(uintptr) __asm__("libgo_reflect.reflect.chanclose");
1146
1147 void
1148 reflect_chanclose(uintptr c)
1149 {
1150         runtime_closechan((Hchan*)c);
1151 }
1152
1153 // For reflect
1154 //      func chanlen(c chan) (len int32)
1155
1156 int32 reflect_chanlen(uintptr) __asm__("libgo_reflect.reflect.chanlen");
1157
1158 int32
1159 reflect_chanlen(uintptr ca)
1160 {
1161         Hchan *c;
1162         int32 len;
1163
1164         c = (Hchan*)ca;
1165         if(c == nil)
1166                 len = 0;
1167         else
1168                 len = c->qcount;
1169         return len;
1170 }
1171
1172 int
1173 __go_chan_len(Hchan *c)
1174 {
1175         return reflect_chanlen((uintptr)c);
1176 }
1177
1178 // For reflect
1179 //      func chancap(c chan) (cap int32)
1180
1181 int32 reflect_chancap(uintptr) __asm__("libgo_reflect.reflect.chancap");
1182
1183 int32
1184 reflect_chancap(uintptr ca)
1185 {
1186         Hchan *c;
1187         int32 cap;
1188
1189         c = (Hchan*)ca;
1190         if(c == nil)
1191                 cap = 0;
1192         else
1193                 cap = c->dataqsiz;
1194         return cap;
1195 }
1196
1197 int
1198 __go_chan_cap(Hchan *c)
1199 {
1200         return reflect_chancap((uintptr)c);
1201 }
1202
1203 static SudoG*
1204 dequeue(WaitQ *q)
1205 {
1206         SudoG *sgp;
1207
1208 loop:
1209         sgp = q->first;
1210         if(sgp == nil)
1211                 return nil;
1212         q->first = sgp->link;
1213
1214         // if sgp is stale, ignore it
1215         if(sgp->selgen != NOSELGEN &&
1216                 (sgp->selgen != sgp->g->selgen ||
1217                 !runtime_cas(&sgp->g->selgen, sgp->selgen, sgp->selgen + 2))) {
1218                 //prints("INVALID PSEUDOG POINTER\n");
1219                 goto loop;
1220         }
1221
1222         return sgp;
1223 }
1224
1225 static void
1226 dequeueg(WaitQ *q)
1227 {
1228         SudoG **l, *sgp, *prevsgp;
1229         G *g;
1230
1231         g = runtime_g();
1232         prevsgp = nil;
1233         for(l=&q->first; (sgp=*l) != nil; l=&sgp->link, prevsgp=sgp) {
1234                 if(sgp->g == g) {
1235                         *l = sgp->link;
1236                         if(q->last == sgp)
1237                                 q->last = prevsgp;
1238                         break;
1239                 }
1240         }
1241 }
1242
1243 static void
1244 enqueue(WaitQ *q, SudoG *sgp)
1245 {
1246         sgp->link = nil;
1247         if(q->first == nil) {
1248                 q->first = sgp;
1249                 q->last = sgp;
1250                 return;
1251         }
1252         q->last->link = sgp;
1253         q->last = sgp;
1254 }