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
5package runtime
6
7// This file contains the implementation of Go select statements.
8
9import (
10	"unsafe"
11)
12
13// For gccgo, use go:linkname to rename compiler-called functions to
14// themselves, so that the compiler will export them.
15//
16//go:linkname selectgo runtime.selectgo
17
18const debugSelect = false
19
20// scase.kind values.
21// Known to compiler.
22// Changes here must also be made in src/cmd/compile/internal/gc/select.go's walkselect.
23const (
24	caseNil = iota
25	caseRecv
26	caseSend
27	caseDefault
28)
29
30// Select case descriptor.
31// Known to compiler.
32// Changes here must also be made in src/cmd/internal/gc/select.go's scasetype.
33type scase struct {
34	c           *hchan         // chan
35	elem        unsafe.Pointer // data element
36	kind        uint16
37	releasetime int64
38}
39
40func sellock(scases []scase, lockorder []uint16) {
41	var c *hchan
42	for _, o := range lockorder {
43		c0 := scases[o].c
44		if c0 != nil && c0 != c {
45			c = c0
46			lock(&c.lock)
47		}
48	}
49}
50
51func selunlock(scases []scase, lockorder []uint16) {
52	// We must be very careful here to not touch sel after we have unlocked
53	// the last lock, because sel can be freed right after the last unlock.
54	// Consider the following situation.
55	// First M calls runtime·park() in runtime·selectgo() passing the sel.
56	// Once runtime·park() has unlocked the last lock, another M makes
57	// the G that calls select runnable again and schedules it for execution.
58	// When the G runs on another M, it locks all the locks and frees sel.
59	// Now if the first M touches sel, it will access freed memory.
60	for i := len(scases) - 1; i >= 0; i-- {
61		c := scases[lockorder[i]].c
62		if c == nil {
63			break
64		}
65		if i > 0 && c == scases[lockorder[i-1]].c {
66			continue // will unlock it on the next iteration
67		}
68		unlock(&c.lock)
69	}
70}
71
72func selparkcommit(gp *g, _ unsafe.Pointer) bool {
73	// This must not access gp's stack (see gopark). In
74	// particular, it must not access the *hselect. That's okay,
75	// because by the time this is called, gp.waiting has all
76	// channels in lock order.
77	var lastc *hchan
78	for sg := gp.waiting; sg != nil; sg = sg.waitlink {
79		if sg.c != lastc && lastc != nil {
80			// As soon as we unlock the channel, fields in
81			// any sudog with that channel may change,
82			// including c and waitlink. Since multiple
83			// sudogs may have the same channel, we unlock
84			// only after we've passed the last instance
85			// of a channel.
86			unlock(&lastc.lock)
87		}
88		lastc = sg.c
89	}
90	if lastc != nil {
91		unlock(&lastc.lock)
92	}
93	return true
94}
95
96func block() {
97	gopark(nil, nil, waitReasonSelectNoCases, traceEvGoStop, 1) // forever
98}
99
100// selectgo implements the select statement.
101//
102// cas0 points to an array of type [ncases]scase, and order0 points to
103// an array of type [2*ncases]uint16. Both reside on the goroutine's
104// stack (regardless of any escaping in selectgo).
105//
106// selectgo returns the index of the chosen scase, which matches the
107// ordinal position of its respective select{recv,send,default} call.
108// Also, if the chosen scase was a receive operation, it reports whether
109// a value was received.
110func selectgo(cas0 *scase, order0 *uint16, ncases int) (int, bool) {
111	if debugSelect {
112		print("select: cas0=", cas0, "\n")
113	}
114
115	cas1 := (*[1 << 16]scase)(unsafe.Pointer(cas0))
116	order1 := (*[1 << 17]uint16)(unsafe.Pointer(order0))
117
118	scases := cas1[:ncases:ncases]
119	pollorder := order1[:ncases:ncases]
120	lockorder := order1[ncases:][:ncases:ncases]
121
122	// Replace send/receive cases involving nil channels with
123	// caseNil so logic below can assume non-nil channel.
124	for i := range scases {
125		cas := &scases[i]
126		if cas.c == nil && cas.kind != caseDefault {
127			*cas = scase{}
128		}
129	}
130
131	var t0 int64
132	if blockprofilerate > 0 {
133		t0 = cputicks()
134		for i := 0; i < ncases; i++ {
135			scases[i].releasetime = -1
136		}
137	}
138
139	// The compiler rewrites selects that statically have
140	// only 0 or 1 cases plus default into simpler constructs.
141	// The only way we can end up with such small sel.ncase
142	// values here is for a larger select in which most channels
143	// have been nilled out. The general code handles those
144	// cases correctly, and they are rare enough not to bother
145	// optimizing (and needing to test).
146
147	// needed for gccgo, which doesn't zero pollorder
148	if ncases > 0 {
149		pollorder[0] = 0
150	}
151
152	// generate permuted order
153	for i := 1; i < ncases; i++ {
154		j := fastrandn(uint32(i + 1))
155		pollorder[i] = pollorder[j]
156		pollorder[j] = uint16(i)
157	}
158
159	// sort the cases by Hchan address to get the locking order.
160	// simple heap sort, to guarantee n log n time and constant stack footprint.
161	for i := 0; i < ncases; i++ {
162		j := i
163		// Start with the pollorder to permute cases on the same channel.
164		c := scases[pollorder[i]].c
165		for j > 0 && scases[lockorder[(j-1)/2]].c.sortkey() < c.sortkey() {
166			k := (j - 1) / 2
167			lockorder[j] = lockorder[k]
168			j = k
169		}
170		lockorder[j] = pollorder[i]
171	}
172	for i := ncases - 1; i >= 0; i-- {
173		o := lockorder[i]
174		c := scases[o].c
175		lockorder[i] = lockorder[0]
176		j := 0
177		for {
178			k := j*2 + 1
179			if k >= i {
180				break
181			}
182			if k+1 < i && scases[lockorder[k]].c.sortkey() < scases[lockorder[k+1]].c.sortkey() {
183				k++
184			}
185			if c.sortkey() < scases[lockorder[k]].c.sortkey() {
186				lockorder[j] = lockorder[k]
187				j = k
188				continue
189			}
190			break
191		}
192		lockorder[j] = o
193	}
194
195	if debugSelect {
196		for i := 0; i+1 < ncases; i++ {
197			if scases[lockorder[i]].c.sortkey() > scases[lockorder[i+1]].c.sortkey() {
198				print("i=", i, " x=", lockorder[i], " y=", lockorder[i+1], "\n")
199				throw("select: broken sort")
200			}
201		}
202	}
203
204	// lock all the channels involved in the select
205	sellock(scases, lockorder)
206
207	var (
208		gp     *g
209		sg     *sudog
210		c      *hchan
211		k      *scase
212		sglist *sudog
213		sgnext *sudog
214		qp     unsafe.Pointer
215		nextp  **sudog
216	)
217
218loop:
219	// pass 1 - look for something already waiting
220	var dfli int
221	var dfl *scase
222	var casi int
223	var cas *scase
224	var recvOK bool
225	for i := 0; i < ncases; i++ {
226		casi = int(pollorder[i])
227		cas = &scases[casi]
228		c = cas.c
229
230		switch cas.kind {
231		case caseNil:
232			continue
233
234		case caseRecv:
235			sg = c.sendq.dequeue()
236			if sg != nil {
237				goto recv
238			}
239			if c.qcount > 0 {
240				goto bufrecv
241			}
242			if c.closed != 0 {
243				goto rclose
244			}
245
246		case caseSend:
247			if c.closed != 0 {
248				goto sclose
249			}
250			sg = c.recvq.dequeue()
251			if sg != nil {
252				goto send
253			}
254			if c.qcount < c.dataqsiz {
255				goto bufsend
256			}
257
258		case caseDefault:
259			dfli = casi
260			dfl = cas
261		}
262	}
263
264	if dfl != nil {
265		selunlock(scases, lockorder)
266		casi = dfli
267		cas = dfl
268		goto retc
269	}
270
271	// pass 2 - enqueue on all chans
272	gp = getg()
273	if gp.waiting != nil {
274		throw("gp.waiting != nil")
275	}
276	nextp = &gp.waiting
277	for _, casei := range lockorder {
278		casi = int(casei)
279		cas = &scases[casi]
280		if cas.kind == caseNil {
281			continue
282		}
283		c = cas.c
284		sg := acquireSudog()
285		sg.g = gp
286		sg.isSelect = true
287		// No stack splits between assigning elem and enqueuing
288		// sg on gp.waiting where copystack can find it.
289		sg.elem = cas.elem
290		sg.releasetime = 0
291		if t0 != 0 {
292			sg.releasetime = -1
293		}
294		sg.c = c
295		// Construct waiting list in lock order.
296		*nextp = sg
297		nextp = &sg.waitlink
298
299		switch cas.kind {
300		case caseRecv:
301			c.recvq.enqueue(sg)
302
303		case caseSend:
304			c.sendq.enqueue(sg)
305		}
306	}
307
308	// wait for someone to wake us up
309	gp.param = nil
310	gopark(selparkcommit, nil, waitReasonSelect, traceEvGoBlockSelect, 1)
311
312	sellock(scases, lockorder)
313
314	gp.selectDone = 0
315	sg = (*sudog)(gp.param)
316	gp.param = nil
317
318	// pass 3 - dequeue from unsuccessful chans
319	// otherwise they stack up on quiet channels
320	// record the successful case, if any.
321	// We singly-linked up the SudoGs in lock order.
322	casi = -1
323	cas = nil
324	sglist = gp.waiting
325	// Clear all elem before unlinking from gp.waiting.
326	for sg1 := gp.waiting; sg1 != nil; sg1 = sg1.waitlink {
327		sg1.isSelect = false
328		sg1.elem = nil
329		sg1.c = nil
330	}
331	gp.waiting = nil
332
333	for _, casei := range lockorder {
334		k = &scases[casei]
335		if k.kind == caseNil {
336			continue
337		}
338		if sglist.releasetime > 0 {
339			k.releasetime = sglist.releasetime
340		}
341		if sg == sglist {
342			// sg has already been dequeued by the G that woke us up.
343			casi = int(casei)
344			cas = k
345		} else {
346			c = k.c
347			if k.kind == caseSend {
348				c.sendq.dequeueSudoG(sglist)
349			} else {
350				c.recvq.dequeueSudoG(sglist)
351			}
352		}
353		sgnext = sglist.waitlink
354		sglist.waitlink = nil
355		releaseSudog(sglist)
356		sglist = sgnext
357	}
358
359	if cas == nil {
360		// We can wake up with gp.param == nil (so cas == nil)
361		// when a channel involved in the select has been closed.
362		// It is easiest to loop and re-run the operation;
363		// we'll see that it's now closed.
364		// Maybe some day we can signal the close explicitly,
365		// but we'd have to distinguish close-on-reader from close-on-writer.
366		// It's easiest not to duplicate the code and just recheck above.
367		// We know that something closed, and things never un-close,
368		// so we won't block again.
369		goto loop
370	}
371
372	c = cas.c
373
374	if debugSelect {
375		print("wait-return: cas0=", cas0, " c=", c, " cas=", cas, " kind=", cas.kind, "\n")
376	}
377
378	if cas.kind == caseRecv {
379		recvOK = true
380	}
381
382	selunlock(scases, lockorder)
383	goto retc
384
385bufrecv:
386	// can receive from buffer
387	recvOK = true
388	qp = chanbuf(c, c.recvx)
389	if cas.elem != nil {
390		typedmemmove(c.elemtype, cas.elem, qp)
391	}
392	typedmemclr(c.elemtype, qp)
393	c.recvx++
394	if c.recvx == c.dataqsiz {
395		c.recvx = 0
396	}
397	c.qcount--
398	selunlock(scases, lockorder)
399	goto retc
400
401bufsend:
402	// can send to buffer
403	typedmemmove(c.elemtype, chanbuf(c, c.sendx), cas.elem)
404	c.sendx++
405	if c.sendx == c.dataqsiz {
406		c.sendx = 0
407	}
408	c.qcount++
409	selunlock(scases, lockorder)
410	goto retc
411
412recv:
413	// can receive from sleeping sender (sg)
414	recv(c, sg, cas.elem, func() { selunlock(scases, lockorder) }, 2)
415	if debugSelect {
416		print("syncrecv: cas0=", cas0, " c=", c, "\n")
417	}
418	recvOK = true
419	goto retc
420
421rclose:
422	// read at end of closed channel
423	selunlock(scases, lockorder)
424	recvOK = false
425	if cas.elem != nil {
426		typedmemclr(c.elemtype, cas.elem)
427	}
428	if raceenabled {
429		raceacquire(c.raceaddr())
430	}
431	goto retc
432
433send:
434	// can send to a sleeping receiver (sg)
435	send(c, sg, cas.elem, func() { selunlock(scases, lockorder) }, 2)
436	if debugSelect {
437		print("syncsend: cas0=", cas0, " c=", c, "\n")
438	}
439	goto retc
440
441retc:
442	if cas.releasetime > 0 {
443		blockevent(cas.releasetime-t0, 1)
444	}
445
446	// Check preemption, since unlike gc we don't check on every call.
447	// A test case for this one is BenchmarkPingPongHog in proc_test.go.
448	if dfl != nil && getg().preempt {
449		checkPreempt()
450	}
451
452	return casi, recvOK
453
454sclose:
455	// send on closed channel
456	selunlock(scases, lockorder)
457	panic(plainError("send on closed channel"))
458}
459
460func (c *hchan) sortkey() uintptr {
461	// TODO(khr): if we have a moving garbage collector, we'll need to
462	// change this function.
463	return uintptr(unsafe.Pointer(c))
464}
465
466// A runtimeSelect is a single case passed to rselect.
467// This must match ../reflect/value.go:/runtimeSelect
468type runtimeSelect struct {
469	dir selectDir
470	typ unsafe.Pointer // channel type (not used here)
471	ch  *hchan         // channel
472	val unsafe.Pointer // ptr to data (SendDir) or ptr to receive buffer (RecvDir)
473}
474
475// These values must match ../reflect/value.go:/SelectDir.
476type selectDir int
477
478const (
479	_             selectDir = iota
480	selectSend              // case Chan <- Send
481	selectRecv              // case <-Chan:
482	selectDefault           // default
483)
484
485//go:linkname reflect_rselect reflect.rselect
486func reflect_rselect(cases []runtimeSelect) (int, bool) {
487	if len(cases) == 0 {
488		block()
489	}
490	sel := make([]scase, len(cases))
491	order := make([]uint16, 2*len(cases))
492	for i := range cases {
493		rc := &cases[i]
494		switch rc.dir {
495		case selectDefault:
496			sel[i] = scase{kind: caseDefault}
497		case selectSend:
498			sel[i] = scase{kind: caseSend, c: rc.ch, elem: rc.val}
499		case selectRecv:
500			sel[i] = scase{kind: caseRecv, c: rc.ch, elem: rc.val}
501		}
502	}
503
504	return selectgo(&sel[0], &order[0], len(cases))
505}
506
507func (q *waitq) dequeueSudoG(sgp *sudog) {
508	x := sgp.prev
509	y := sgp.next
510	if x != nil {
511		if y != nil {
512			// middle of queue
513			x.next = y
514			y.prev = x
515			sgp.next = nil
516			sgp.prev = nil
517			return
518		}
519		// end of queue
520		x.next = nil
521		q.last = x
522		sgp.prev = nil
523		return
524	}
525	if y != nil {
526		// start of queue
527		y.prev = nil
528		q.first = y
529		sgp.next = nil
530		return
531	}
532
533	// x==y==nil. Either sgp is the only element in the queue,
534	// or it has already been removed. Use q.first to disambiguate.
535	if q.first == sgp {
536		q.first = nil
537		q.last = nil
538	}
539}
540