github.com/dannin/go@v0.0.0-20161031215817-d35dfd405eaa/src/runtime/chan.go (about) 1 // Copyright 2014 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 package runtime 6 7 // This file contains the implementation of Go channels. 8 9 // Invariants: 10 // At least one of c.sendq and c.recvq is empty, 11 // except for the case of an unbuffered channel with a single goroutine 12 // blocked on it for both sending and receiving using a select statement, 13 // in which case the length of c.sendq and c.recvq is limited only by the 14 // size of the select statement. 15 // 16 // For buffered channels, also: 17 // c.qcount > 0 implies that c.recvq is empty. 18 // c.qcount < c.dataqsiz implies that c.sendq is empty. 19 20 import ( 21 "runtime/internal/atomic" 22 "unsafe" 23 ) 24 25 const ( 26 maxAlign = 8 27 hchanSize = unsafe.Sizeof(hchan{}) + uintptr(-int(unsafe.Sizeof(hchan{}))&(maxAlign-1)) 28 debugChan = false 29 ) 30 31 type hchan struct { 32 qcount uint // total data in the queue 33 dataqsiz uint // size of the circular queue 34 buf unsafe.Pointer // points to an array of dataqsiz elements 35 elemsize uint16 36 closed uint32 37 elemtype *_type // element type 38 sendx uint // send index 39 recvx uint // receive index 40 recvq waitq // list of recv waiters 41 sendq waitq // list of send waiters 42 43 // lock protects all fields in hchan, as well as several 44 // fields in sudogs blocked on this channel. 45 // 46 // Do not change another G's status while holding this lock 47 // (in particular, do not ready a G), as this can deadlock 48 // with stack shrinking. 49 lock mutex 50 } 51 52 type waitq struct { 53 first *sudog 54 last *sudog 55 } 56 57 //go:linkname reflect_makechan reflect.makechan 58 func reflect_makechan(t *chantype, size int64) *hchan { 59 return makechan(t, size) 60 } 61 62 func makechan(t *chantype, size int64) *hchan { 63 elem := t.elem 64 65 // compiler checks this but be safe. 66 if elem.size >= 1<<16 { 67 throw("makechan: invalid channel element type") 68 } 69 if hchanSize%maxAlign != 0 || elem.align > maxAlign { 70 throw("makechan: bad alignment") 71 } 72 if size < 0 || int64(uintptr(size)) != size || (elem.size > 0 && uintptr(size) > (_MaxMem-hchanSize)/elem.size) { 73 panic(plainError("makechan: size out of range")) 74 } 75 76 var c *hchan 77 if elem.kind&kindNoPointers != 0 || size == 0 { 78 // Allocate memory in one call. 79 // Hchan does not contain pointers interesting for GC in this case: 80 // buf points into the same allocation, elemtype is persistent. 81 // SudoG's are referenced from their owning thread so they can't be collected. 82 // TODO(dvyukov,rlh): Rethink when collector can move allocated objects. 83 c = (*hchan)(mallocgc(hchanSize+uintptr(size)*elem.size, nil, true)) 84 if size > 0 && elem.size != 0 { 85 c.buf = add(unsafe.Pointer(c), hchanSize) 86 } else { 87 // race detector uses this location for synchronization 88 // Also prevents us from pointing beyond the allocation (see issue 9401). 89 c.buf = unsafe.Pointer(c) 90 } 91 } else { 92 c = new(hchan) 93 c.buf = newarray(elem, int(size)) 94 } 95 c.elemsize = uint16(elem.size) 96 c.elemtype = elem 97 c.dataqsiz = uint(size) 98 99 if debugChan { 100 print("makechan: chan=", c, "; elemsize=", elem.size, "; elemalg=", elem.alg, "; dataqsiz=", size, "\n") 101 } 102 return c 103 } 104 105 // chanbuf(c, i) is pointer to the i'th slot in the buffer. 106 func chanbuf(c *hchan, i uint) unsafe.Pointer { 107 return add(c.buf, uintptr(i)*uintptr(c.elemsize)) 108 } 109 110 // entry point for c <- x from compiled code 111 //go:nosplit 112 func chansend1(t *chantype, c *hchan, elem unsafe.Pointer) { 113 chansend(t, c, elem, true, getcallerpc(unsafe.Pointer(&t))) 114 } 115 116 /* 117 * generic single channel send/recv 118 * If block is not nil, 119 * then the protocol will not 120 * sleep but return if it could 121 * not complete. 122 * 123 * sleep can wake up with g.param == nil 124 * when a channel involved in the sleep has 125 * been closed. it is easiest to loop and re-run 126 * the operation; we'll see that it's now closed. 127 */ 128 func chansend(t *chantype, c *hchan, ep unsafe.Pointer, block bool, callerpc uintptr) bool { 129 if raceenabled { 130 raceReadObjectPC(t.elem, ep, callerpc, funcPC(chansend)) 131 } 132 if msanenabled { 133 msanread(ep, t.elem.size) 134 } 135 136 if c == nil { 137 if !block { 138 return false 139 } 140 gopark(nil, nil, "chan send (nil chan)", traceEvGoStop, 2) 141 throw("unreachable") 142 } 143 144 if debugChan { 145 print("chansend: chan=", c, "\n") 146 } 147 148 if raceenabled { 149 racereadpc(unsafe.Pointer(c), callerpc, funcPC(chansend)) 150 } 151 152 // Fast path: check for failed non-blocking operation without acquiring the lock. 153 // 154 // After observing that the channel is not closed, we observe that the channel is 155 // not ready for sending. Each of these observations is a single word-sized read 156 // (first c.closed and second c.recvq.first or c.qcount depending on kind of channel). 157 // Because a closed channel cannot transition from 'ready for sending' to 158 // 'not ready for sending', even if the channel is closed between the two observations, 159 // they imply a moment between the two when the channel was both not yet closed 160 // and not ready for sending. We behave as if we observed the channel at that moment, 161 // and report that the send cannot proceed. 162 // 163 // It is okay if the reads are reordered here: if we observe that the channel is not 164 // ready for sending and then observe that it is not closed, that implies that the 165 // channel wasn't closed during the first observation. 166 if !block && c.closed == 0 && ((c.dataqsiz == 0 && c.recvq.first == nil) || 167 (c.dataqsiz > 0 && c.qcount == c.dataqsiz)) { 168 return false 169 } 170 171 var t0 int64 172 if blockprofilerate > 0 { 173 t0 = cputicks() 174 } 175 176 lock(&c.lock) 177 178 if c.closed != 0 { 179 unlock(&c.lock) 180 panic(plainError("send on closed channel")) 181 } 182 183 if sg := c.recvq.dequeue(); sg != nil { 184 // Found a waiting receiver. We pass the value we want to send 185 // directly to the receiver, bypassing the channel buffer (if any). 186 send(c, sg, ep, func() { unlock(&c.lock) }) 187 return true 188 } 189 190 if c.qcount < c.dataqsiz { 191 // Space is available in the channel buffer. Enqueue the element to send. 192 qp := chanbuf(c, c.sendx) 193 if raceenabled { 194 raceacquire(qp) 195 racerelease(qp) 196 } 197 typedmemmove(c.elemtype, qp, ep) 198 c.sendx++ 199 if c.sendx == c.dataqsiz { 200 c.sendx = 0 201 } 202 c.qcount++ 203 unlock(&c.lock) 204 return true 205 } 206 207 if !block { 208 unlock(&c.lock) 209 return false 210 } 211 212 // Block on the channel. Some receiver will complete our operation for us. 213 gp := getg() 214 mysg := acquireSudog() 215 mysg.releasetime = 0 216 if t0 != 0 { 217 mysg.releasetime = -1 218 } 219 // No stack splits between assigning elem and enqueuing mysg 220 // on gp.waiting where copystack can find it. 221 mysg.elem = ep 222 mysg.waitlink = nil 223 mysg.g = gp 224 mysg.selectdone = nil 225 mysg.c = c 226 gp.waiting = mysg 227 gp.param = nil 228 c.sendq.enqueue(mysg) 229 goparkunlock(&c.lock, "chan send", traceEvGoBlockSend, 3) 230 231 // someone woke us up. 232 if mysg != gp.waiting { 233 throw("G waiting list is corrupted") 234 } 235 gp.waiting = nil 236 if gp.param == nil { 237 if c.closed == 0 { 238 throw("chansend: spurious wakeup") 239 } 240 panic(plainError("send on closed channel")) 241 } 242 gp.param = nil 243 if mysg.releasetime > 0 { 244 blockevent(mysg.releasetime-t0, 2) 245 } 246 mysg.c = nil 247 releaseSudog(mysg) 248 return true 249 } 250 251 // send processes a send operation on an empty channel c. 252 // The value ep sent by the sender is copied to the receiver sg. 253 // The receiver is then woken up to go on its merry way. 254 // Channel c must be empty and locked. send unlocks c with unlockf. 255 // sg must already be dequeued from c. 256 // ep must be non-nil and point to the heap or the caller's stack. 257 func send(c *hchan, sg *sudog, ep unsafe.Pointer, unlockf func()) { 258 if raceenabled { 259 if c.dataqsiz == 0 { 260 racesync(c, sg) 261 } else { 262 // Pretend we go through the buffer, even though 263 // we copy directly. Note that we need to increment 264 // the head/tail locations only when raceenabled. 265 qp := chanbuf(c, c.recvx) 266 raceacquire(qp) 267 racerelease(qp) 268 raceacquireg(sg.g, qp) 269 racereleaseg(sg.g, qp) 270 c.recvx++ 271 if c.recvx == c.dataqsiz { 272 c.recvx = 0 273 } 274 c.sendx = c.recvx // c.sendx = (c.sendx+1) % c.dataqsiz 275 } 276 } 277 if sg.elem != nil { 278 sendDirect(c.elemtype, sg, ep) 279 sg.elem = nil 280 } 281 gp := sg.g 282 unlockf() 283 gp.param = unsafe.Pointer(sg) 284 if sg.releasetime != 0 { 285 sg.releasetime = cputicks() 286 } 287 goready(gp, 4) 288 } 289 290 func sendDirect(t *_type, sg *sudog, src unsafe.Pointer) { 291 // Send on an unbuffered or empty-buffered channel is the only operation 292 // in the entire runtime where one goroutine 293 // writes to the stack of another goroutine. The GC assumes that 294 // stack writes only happen when the goroutine is running and are 295 // only done by that goroutine. Using a write barrier is sufficient to 296 // make up for violating that assumption, but the write barrier has to work. 297 // typedmemmove will call bulkBarrierPreWrite, but the target bytes 298 // are not in the heap, so that will not help. We arrange to call 299 // memmove and typeBitsBulkBarrier instead. 300 301 // Once we read sg.elem out of sg, it will no longer 302 // be updated if the destination's stack gets copied (shrunk). 303 // So make sure that no preemption points can happen between read & use. 304 dst := sg.elem 305 typeBitsBulkBarrier(t, uintptr(dst), uintptr(src), t.size) 306 memmove(dst, src, t.size) 307 } 308 309 func closechan(c *hchan) { 310 if c == nil { 311 panic(plainError("close of nil channel")) 312 } 313 314 lock(&c.lock) 315 if c.closed != 0 { 316 unlock(&c.lock) 317 panic(plainError("close of closed channel")) 318 } 319 320 if raceenabled { 321 callerpc := getcallerpc(unsafe.Pointer(&c)) 322 racewritepc(unsafe.Pointer(c), callerpc, funcPC(closechan)) 323 racerelease(unsafe.Pointer(c)) 324 } 325 326 c.closed = 1 327 328 var glist *g 329 330 // release all readers 331 for { 332 sg := c.recvq.dequeue() 333 if sg == nil { 334 break 335 } 336 if sg.elem != nil { 337 typedmemclr(c.elemtype, sg.elem) 338 sg.elem = nil 339 } 340 if sg.releasetime != 0 { 341 sg.releasetime = cputicks() 342 } 343 gp := sg.g 344 gp.param = nil 345 if raceenabled { 346 raceacquireg(gp, unsafe.Pointer(c)) 347 } 348 gp.schedlink.set(glist) 349 glist = gp 350 } 351 352 // release all writers (they will panic) 353 for { 354 sg := c.sendq.dequeue() 355 if sg == nil { 356 break 357 } 358 sg.elem = nil 359 if sg.releasetime != 0 { 360 sg.releasetime = cputicks() 361 } 362 gp := sg.g 363 gp.param = nil 364 if raceenabled { 365 raceacquireg(gp, unsafe.Pointer(c)) 366 } 367 gp.schedlink.set(glist) 368 glist = gp 369 } 370 unlock(&c.lock) 371 372 // Ready all Gs now that we've dropped the channel lock. 373 for glist != nil { 374 gp := glist 375 glist = glist.schedlink.ptr() 376 gp.schedlink = 0 377 goready(gp, 3) 378 } 379 } 380 381 // entry points for <- c from compiled code 382 //go:nosplit 383 func chanrecv1(t *chantype, c *hchan, elem unsafe.Pointer) { 384 chanrecv(t, c, elem, true) 385 } 386 387 //go:nosplit 388 func chanrecv2(t *chantype, c *hchan, elem unsafe.Pointer) (received bool) { 389 _, received = chanrecv(t, c, elem, true) 390 return 391 } 392 393 // chanrecv receives on channel c and writes the received data to ep. 394 // ep may be nil, in which case received data is ignored. 395 // If block == false and no elements are available, returns (false, false). 396 // Otherwise, if c is closed, zeros *ep and returns (true, false). 397 // Otherwise, fills in *ep with an element and returns (true, true). 398 // A non-nil ep must point to the heap or the caller's stack. 399 func chanrecv(t *chantype, c *hchan, ep unsafe.Pointer, block bool) (selected, received bool) { 400 // raceenabled: don't need to check ep, as it is always on the stack 401 // or is new memory allocated by reflect. 402 403 if debugChan { 404 print("chanrecv: chan=", c, "\n") 405 } 406 407 if c == nil { 408 if !block { 409 return 410 } 411 gopark(nil, nil, "chan receive (nil chan)", traceEvGoStop, 2) 412 throw("unreachable") 413 } 414 415 // Fast path: check for failed non-blocking operation without acquiring the lock. 416 // 417 // After observing that the channel is not ready for receiving, we observe that the 418 // channel is not closed. Each of these observations is a single word-sized read 419 // (first c.sendq.first or c.qcount, and second c.closed). 420 // Because a channel cannot be reopened, the later observation of the channel 421 // being not closed implies that it was also not closed at the moment of the 422 // first observation. We behave as if we observed the channel at that moment 423 // and report that the receive cannot proceed. 424 // 425 // The order of operations is important here: reversing the operations can lead to 426 // incorrect behavior when racing with a close. 427 if !block && (c.dataqsiz == 0 && c.sendq.first == nil || 428 c.dataqsiz > 0 && atomic.Loaduint(&c.qcount) == 0) && 429 atomic.Load(&c.closed) == 0 { 430 return 431 } 432 433 var t0 int64 434 if blockprofilerate > 0 { 435 t0 = cputicks() 436 } 437 438 lock(&c.lock) 439 440 if c.closed != 0 && c.qcount == 0 { 441 if raceenabled { 442 raceacquire(unsafe.Pointer(c)) 443 } 444 unlock(&c.lock) 445 if ep != nil { 446 typedmemclr(c.elemtype, ep) 447 } 448 return true, false 449 } 450 451 if sg := c.sendq.dequeue(); sg != nil { 452 // Found a waiting sender. If buffer is size 0, receive value 453 // directly from sender. Otherwise, receive from head of queue 454 // and add sender's value to the tail of the queue (both map to 455 // the same buffer slot because the queue is full). 456 recv(c, sg, ep, func() { unlock(&c.lock) }) 457 return true, true 458 } 459 460 if c.qcount > 0 { 461 // Receive directly from queue 462 qp := chanbuf(c, c.recvx) 463 if raceenabled { 464 raceacquire(qp) 465 racerelease(qp) 466 } 467 if ep != nil { 468 typedmemmove(c.elemtype, ep, qp) 469 } 470 typedmemclr(c.elemtype, qp) 471 c.recvx++ 472 if c.recvx == c.dataqsiz { 473 c.recvx = 0 474 } 475 c.qcount-- 476 unlock(&c.lock) 477 return true, true 478 } 479 480 if !block { 481 unlock(&c.lock) 482 return false, false 483 } 484 485 // no sender available: block on this channel. 486 gp := getg() 487 mysg := acquireSudog() 488 mysg.releasetime = 0 489 if t0 != 0 { 490 mysg.releasetime = -1 491 } 492 // No stack splits between assigning elem and enqueuing mysg 493 // on gp.waiting where copystack can find it. 494 mysg.elem = ep 495 mysg.waitlink = nil 496 gp.waiting = mysg 497 mysg.g = gp 498 mysg.selectdone = nil 499 mysg.c = c 500 gp.param = nil 501 c.recvq.enqueue(mysg) 502 goparkunlock(&c.lock, "chan receive", traceEvGoBlockRecv, 3) 503 504 // someone woke us up 505 if mysg != gp.waiting { 506 throw("G waiting list is corrupted") 507 } 508 gp.waiting = nil 509 if mysg.releasetime > 0 { 510 blockevent(mysg.releasetime-t0, 2) 511 } 512 closed := gp.param == nil 513 gp.param = nil 514 mysg.c = nil 515 releaseSudog(mysg) 516 return true, !closed 517 } 518 519 // recv processes a receive operation on a full channel c. 520 // There are 2 parts: 521 // 1) The value sent by the sender sg is put into the channel 522 // and the sender is woken up to go on its merry way. 523 // 2) The value received by the receiver (the current G) is 524 // written to ep. 525 // For synchronous channels, both values are the same. 526 // For asynchronous channels, the receiver gets its data from 527 // the channel buffer and the sender's data is put in the 528 // channel buffer. 529 // Channel c must be full and locked. recv unlocks c with unlockf. 530 // sg must already be dequeued from c. 531 // A non-nil ep must point to the heap or the caller's stack. 532 func recv(c *hchan, sg *sudog, ep unsafe.Pointer, unlockf func()) { 533 if c.dataqsiz == 0 { 534 if raceenabled { 535 racesync(c, sg) 536 } 537 if ep != nil { 538 // copy data from sender 539 // ep points to our own stack or heap, so nothing 540 // special (ala sendDirect) needed here. 541 typedmemmove(c.elemtype, ep, sg.elem) 542 } 543 } else { 544 // Queue is full. Take the item at the 545 // head of the queue. Make the sender enqueue 546 // its item at the tail of the queue. Since the 547 // queue is full, those are both the same slot. 548 qp := chanbuf(c, c.recvx) 549 if raceenabled { 550 raceacquire(qp) 551 racerelease(qp) 552 raceacquireg(sg.g, qp) 553 racereleaseg(sg.g, qp) 554 } 555 // copy data from queue to receiver 556 if ep != nil { 557 typedmemmove(c.elemtype, ep, qp) 558 } 559 // copy data from sender to queue 560 typedmemmove(c.elemtype, qp, sg.elem) 561 c.recvx++ 562 if c.recvx == c.dataqsiz { 563 c.recvx = 0 564 } 565 c.sendx = c.recvx // c.sendx = (c.sendx+1) % c.dataqsiz 566 } 567 sg.elem = nil 568 gp := sg.g 569 unlockf() 570 gp.param = unsafe.Pointer(sg) 571 if sg.releasetime != 0 { 572 sg.releasetime = cputicks() 573 } 574 goready(gp, 4) 575 } 576 577 // compiler implements 578 // 579 // select { 580 // case c <- v: 581 // ... foo 582 // default: 583 // ... bar 584 // } 585 // 586 // as 587 // 588 // if selectnbsend(c, v) { 589 // ... foo 590 // } else { 591 // ... bar 592 // } 593 // 594 func selectnbsend(t *chantype, c *hchan, elem unsafe.Pointer) (selected bool) { 595 return chansend(t, c, elem, false, getcallerpc(unsafe.Pointer(&t))) 596 } 597 598 // compiler implements 599 // 600 // select { 601 // case v = <-c: 602 // ... foo 603 // default: 604 // ... bar 605 // } 606 // 607 // as 608 // 609 // if selectnbrecv(&v, c) { 610 // ... foo 611 // } else { 612 // ... bar 613 // } 614 // 615 func selectnbrecv(t *chantype, elem unsafe.Pointer, c *hchan) (selected bool) { 616 selected, _ = chanrecv(t, c, elem, false) 617 return 618 } 619 620 // compiler implements 621 // 622 // select { 623 // case v, ok = <-c: 624 // ... foo 625 // default: 626 // ... bar 627 // } 628 // 629 // as 630 // 631 // if c != nil && selectnbrecv2(&v, &ok, c) { 632 // ... foo 633 // } else { 634 // ... bar 635 // } 636 // 637 func selectnbrecv2(t *chantype, elem unsafe.Pointer, received *bool, c *hchan) (selected bool) { 638 // TODO(khr): just return 2 values from this function, now that it is in Go. 639 selected, *received = chanrecv(t, c, elem, false) 640 return 641 } 642 643 //go:linkname reflect_chansend reflect.chansend 644 func reflect_chansend(t *chantype, c *hchan, elem unsafe.Pointer, nb bool) (selected bool) { 645 return chansend(t, c, elem, !nb, getcallerpc(unsafe.Pointer(&t))) 646 } 647 648 //go:linkname reflect_chanrecv reflect.chanrecv 649 func reflect_chanrecv(t *chantype, c *hchan, nb bool, elem unsafe.Pointer) (selected bool, received bool) { 650 return chanrecv(t, c, elem, !nb) 651 } 652 653 //go:linkname reflect_chanlen reflect.chanlen 654 func reflect_chanlen(c *hchan) int { 655 if c == nil { 656 return 0 657 } 658 return int(c.qcount) 659 } 660 661 //go:linkname reflect_chancap reflect.chancap 662 func reflect_chancap(c *hchan) int { 663 if c == nil { 664 return 0 665 } 666 return int(c.dataqsiz) 667 } 668 669 //go:linkname reflect_chanclose reflect.chanclose 670 func reflect_chanclose(c *hchan) { 671 closechan(c) 672 } 673 674 func (q *waitq) enqueue(sgp *sudog) { 675 sgp.next = nil 676 x := q.last 677 if x == nil { 678 sgp.prev = nil 679 q.first = sgp 680 q.last = sgp 681 return 682 } 683 sgp.prev = x 684 x.next = sgp 685 q.last = sgp 686 } 687 688 func (q *waitq) dequeue() *sudog { 689 for { 690 sgp := q.first 691 if sgp == nil { 692 return nil 693 } 694 y := sgp.next 695 if y == nil { 696 q.first = nil 697 q.last = nil 698 } else { 699 y.prev = nil 700 q.first = y 701 sgp.next = nil // mark as removed (see dequeueSudog) 702 } 703 704 // if sgp participates in a select and is already signaled, ignore it 705 if sgp.selectdone != nil { 706 // claim the right to signal 707 if *sgp.selectdone != 0 || !atomic.Cas(sgp.selectdone, 0, 1) { 708 continue 709 } 710 } 711 712 return sgp 713 } 714 } 715 716 func racesync(c *hchan, sg *sudog) { 717 racerelease(chanbuf(c, 0)) 718 raceacquireg(sg.g, chanbuf(c, 0)) 719 racereleaseg(sg.g, chanbuf(c, 0)) 720 raceacquire(chanbuf(c, 0)) 721 }