Debian Codegraph @

src/runtime/sema.go

raw
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 // Semaphore implementation exposed to Go.
6 // Intended use is provide a sleep and wakeup
7 // primitive that can be used in the contended case
8 // of other synchronization primitives.
9 // Thus it targets the same goal as Linux's futex,
10 // but it has much simpler semantics.
11 //
12 // That is, don't think of these as semaphores.
13 // Think of them as a way to implement sleep and wakeup
14 // such that every sleep is paired with a single wakeup,
15 // even if, due to races, the wakeup happens before the sleep.
16 //
17 // See Mullender and Cox, ``Semaphores in Plan 9,''
18 // https://swtch.com/semaphore.pdf
19
20 package runtime
21
22 import (
23 "internal/cpu"
24 "internal/runtime/atomic"
25 "unsafe"
26 )
27
28 // Asynchronous semaphore for sync.Mutex.
29
30 // A semaRoot holds a balanced tree of sudog with distinct addresses (s.elem).
31 // Each of those sudog may in turn point (through s.waitlink) to a list
32 // of other sudogs waiting on the same address.
33 // The operations on the inner lists of sudogs with the same address
34 // are all O(1). The scanning of the top-level semaRoot list is O(log n),
35 // where n is the number of distinct addresses with goroutines blocked
36 // on them that hash to the given semaRoot.
37 // See golang.org/issue/17953 for a program that worked badly
38 // before we introduced the second level of list, and
39 // BenchmarkSemTable/OneAddrCollision/* for a benchmark that exercises this.
40 type semaRoot struct {
41 lock mutex
42 treap *sudog // root of balanced tree of unique waiters.
43 nwait atomic.Uint32 // Number of waiters. Read w/o the lock.
44 }
45
46 var semtable semTable
47
48 // Prime to not correlate with any user patterns.
49 const semTabSize = 251
50
51 type semTable [semTabSize]struct {
52 root semaRoot
53 pad [cpu.CacheLinePadSize - unsafe.Sizeof(semaRoot{})]byte
54 }
55
56 func (t *semTable) rootFor(addr *uint32) *semaRoot {
57 return &t[(uintptr(unsafe.Pointer(addr))>>3)%semTabSize].root
58 }
59
60 // sync_runtime_Semacquire should be an internal detail,
61 // but widely used packages access it using linkname.
62 // Notable members of the hall of shame include:
63 // - gvisor.dev/gvisor
64 // - github.com/sagernet/gvisor
65 //
66 // Do not remove or change the type signature.
67 // See go.dev/issue/67401.
68 //
69 //go:linkname sync_runtime_Semacquire sync.runtime_Semacquire
70 func sync_runtime_Semacquire(addr *uint32) {
71 semacquire1(addr, false, semaBlockProfile, 0, waitReasonSemacquire)
72 }
73
74 //go:linkname poll_runtime_Semacquire internal/poll.runtime_Semacquire
75 func poll_runtime_Semacquire(addr *uint32) {
76 semacquire1(addr, false, semaBlockProfile, 0, waitReasonSemacquire)
77 }
78
79 // sync_runtime_Semrelease should be an internal detail,
80 // but widely used packages access it using linkname.
81 // Notable members of the hall of shame include:
82 // - gvisor.dev/gvisor
83 // - github.com/sagernet/gvisor
84 //
85 // Do not remove or change the type signature.
86 // See go.dev/issue/67401.
87 //
88 //go:linkname sync_runtime_Semrelease sync.runtime_Semrelease
89 func sync_runtime_Semrelease(addr *uint32, handoff bool, skipframes int) {
90 semrelease1(addr, handoff, skipframes)
91 }
92
93 //go:linkname internal_sync_runtime_SemacquireMutex internal/sync.runtime_SemacquireMutex
94 func internal_sync_runtime_SemacquireMutex(addr *uint32, lifo bool, skipframes int) {
95 semacquire1(addr, lifo, semaBlockProfile|semaMutexProfile, skipframes, waitReasonSyncMutexLock)
96 }
97
98 //go:linkname sync_runtime_SemacquireRWMutexR sync.runtime_SemacquireRWMutexR
99 func sync_runtime_SemacquireRWMutexR(addr *uint32, lifo bool, skipframes int) {
100 semacquire1(addr, lifo, semaBlockProfile|semaMutexProfile, skipframes, waitReasonSyncRWMutexRLock)
101 }
102
103 //go:linkname sync_runtime_SemacquireRWMutex sync.runtime_SemacquireRWMutex
104 func sync_runtime_SemacquireRWMutex(addr *uint32, lifo bool, skipframes int) {
105 semacquire1(addr, lifo, semaBlockProfile|semaMutexProfile, skipframes, waitReasonSyncRWMutexLock)
106 }
107
108 //go:linkname sync_runtime_SemacquireWaitGroup sync.runtime_SemacquireWaitGroup
109 func sync_runtime_SemacquireWaitGroup(addr *uint32, synctestDurable bool) {
110 reason := waitReasonSyncWaitGroupWait
111 if synctestDurable {
112 reason = waitReasonSynctestWaitGroupWait
113 }
114 semacquire1(addr, false, semaBlockProfile, 0, reason)
115 }
116
117 //go:linkname poll_runtime_Semrelease internal/poll.runtime_Semrelease
118 func poll_runtime_Semrelease(addr *uint32) {
119 semrelease(addr)
120 }
121
122 //go:linkname internal_sync_runtime_Semrelease internal/sync.runtime_Semrelease
123 func internal_sync_runtime_Semrelease(addr *uint32, handoff bool, skipframes int) {
124 semrelease1(addr, handoff, skipframes)
125 }
126
127 func readyWithTime(s *sudog, traceskip int) {
128 if s.releasetime != 0 {
129 s.releasetime = cputicks()
130 }
131 goready(s.g, traceskip)
132 }
133
134 type semaProfileFlags int
135
136 const (
137 semaBlockProfile semaProfileFlags = 1 << iota
138 semaMutexProfile
139 )
140
141 // Called from runtime.
142 func semacquire(addr *uint32) {
143 semacquire1(addr, false, 0, 0, waitReasonSemacquire)
144 }
145
146 func semacquire1(addr *uint32, lifo bool, profile semaProfileFlags, skipframes int, reason waitReason) {
147 gp := getg()
148 if gp != gp.m.curg {
149 throw("semacquire not on the G stack")
150 }
151
152 // Easy case.
153 if cansemacquire(addr) {
154 return
155 }
156
157 // Harder case:
158 // increment waiter count
159 // try cansemacquire one more time, return if succeeded
160 // enqueue itself as a waiter
161 // sleep
162 // (waiter descriptor is dequeued by signaler)
163 s := acquireSudog()
164 root := semtable.rootFor(addr)
165 t0 := int64(0)
166 s.releasetime = 0
167 s.acquiretime = 0
168 s.ticket = 0
169 if profile&semaBlockProfile != 0 && blockprofilerate > 0 {
170 t0 = cputicks()
171 s.releasetime = -1
172 }
173 if profile&semaMutexProfile != 0 && mutexprofilerate > 0 {
174 if t0 == 0 {
175 t0 = cputicks()
176 }
177 s.acquiretime = t0
178 }
179 for {
180 lockWithRank(&root.lock, lockRankRoot)
181 // Add ourselves to nwait to disable "easy case" in semrelease.
182 root.nwait.Add(1)
183 // Check cansemacquire to avoid missed wakeup.
184 if cansemacquire(addr) {
185 root.nwait.Add(-1)
186 unlock(&root.lock)
187 break
188 }
189 // Any semrelease after the cansemacquire knows we're waiting
190 // (we set nwait above), so go to sleep.
191 root.queue(addr, s, lifo)
192 goparkunlock(&root.lock, reason, traceBlockSync, 4+skipframes)
193 if s.ticket != 0 || cansemacquire(addr) {
194 break
195 }
196 }
197 if s.releasetime > 0 {
198 blockevent(s.releasetime-t0, 3+skipframes)
199 }
200 releaseSudog(s)
201 }
202
203 func semrelease(addr *uint32) {
204 semrelease1(addr, false, 0)
205 }
206
207 func semrelease1(addr *uint32, handoff bool, skipframes int) {
208 root := semtable.rootFor(addr)
209 atomic.Xadd(addr, 1)
210
211 // Easy case: no waiters?
212 // This check must happen after the xadd, to avoid a missed wakeup
213 // (see loop in semacquire).
214 if root.nwait.Load() == 0 {
215 return
216 }
217
218 // Harder case: search for a waiter and wake it.
219 lockWithRank(&root.lock, lockRankRoot)
220 if root.nwait.Load() == 0 {
221 // The count is already consumed by another goroutine,
222 // so no need to wake up another goroutine.
223 unlock(&root.lock)
224 return
225 }
226 s, t0, tailtime := root.dequeue(addr)
227 if s != nil {
228 root.nwait.Add(-1)
229 }
230 unlock(&root.lock)
231 if s != nil { // May be slow or even yield, so unlock first
232 acquiretime := s.acquiretime
233 if acquiretime != 0 {
234 // Charge contention that this (delayed) unlock caused.
235 // If there are N more goroutines waiting beyond the
236 // one that's waking up, charge their delay as well, so that
237 // contention holding up many goroutines shows up as
238 // more costly than contention holding up a single goroutine.
239 // It would take O(N) time to calculate how long each goroutine
240 // has been waiting, so instead we charge avg(head-wait, tail-wait)*N.
241 // head-wait is the longest wait and tail-wait is the shortest.
242 // (When we do a lifo insertion, we preserve this property by
243 // copying the old head's acquiretime into the inserted new head.
244 // In that case the overall average may be slightly high, but that's fine:
245 // the average of the ends is only an approximation to the actual
246 // average anyway.)
247 // The root.dequeue above changed the head and tail acquiretime
248 // to the current time, so the next unlock will not re-count this contention.
249 dt0 := t0 - acquiretime
250 dt := dt0
251 if s.waiters != 0 {
252 dtail := t0 - tailtime
253 dt += (dtail + dt0) / 2 * int64(s.waiters)
254 }
255 mutexevent(dt, 3+skipframes)
256 }
257 if s.ticket != 0 {
258 throw("corrupted semaphore ticket")
259 }
260 if handoff && cansemacquire(addr) {
261 s.ticket = 1
262 }
263 readyWithTime(s, 5+skipframes)
264 if s.ticket == 1 && getg().m.locks == 0 && getg() != getg().m.g0 {
265 // Direct G handoff
266 //
267 // readyWithTime has added the waiter G as runnext in the
268 // current P; we now call the scheduler so that we start running
269 // the waiter G immediately.
270 //
271 // Note that waiter inherits our time slice: this is desirable
272 // to avoid having a highly contended semaphore hog the P
273 // indefinitely. goyield is like Gosched, but it emits a
274 // "preempted" trace event instead and, more importantly, puts
275 // the current G on the local runq instead of the global one.
276 // We only do this in the starving regime (handoff=true), as in
277 // the non-starving case it is possible for a different waiter
278 // to acquire the semaphore while we are yielding/scheduling,
279 // and this would be wasteful. We wait instead to enter starving
280 // regime, and then we start to do direct handoffs of ticket and P.
281 //
282 // See issue 33747 for discussion.
283 //
284 // We don't handoff directly if we're holding locks or on the
285 // system stack, since it's not safe to enter the scheduler.
286 goyield()
287 }
288 }
289 }
290
291 func cansemacquire(addr *uint32) bool {
292 for {
293 v := atomic.Load(addr)
294 if v == 0 {
295 return false
296 }
297 if atomic.Cas(addr, v, v-1) {
298 return true
299 }
300 }
301 }
302
303 // queue adds s to the blocked goroutines in semaRoot.
304 func (root *semaRoot) queue(addr *uint32, s *sudog, lifo bool) {
305 s.g = getg()
306 s.elem = unsafe.Pointer(addr)
307 s.next = nil
308 s.prev = nil
309 s.waiters = 0
310
311 var last *sudog
312 pt := &root.treap
313 for t := *pt; t != nil; t = *pt {
314 if t.elem == unsafe.Pointer(addr) {
315 // Already have addr in list.
316 if lifo {
317 // Substitute s in t's place in treap.
318 *pt = s
319 s.ticket = t.ticket
320 s.acquiretime = t.acquiretime // preserve head acquiretime as oldest time
321 s.parent = t.parent
322 s.prev = t.prev
323 s.next = t.next
324 if s.prev != nil {
325 s.prev.parent = s
326 }
327 if s.next != nil {
328 s.next.parent = s
329 }
330 // Add t first in s's wait list.
331 s.waitlink = t
332 s.waittail = t.waittail
333 if s.waittail == nil {
334 s.waittail = t
335 }
336 s.waiters = t.waiters
337 if s.waiters+1 != 0 {
338 s.waiters++
339 }
340 t.parent = nil
341 t.prev = nil
342 t.next = nil
343 t.waittail = nil
344 } else {
345 // Add s to end of t's wait list.
346 if t.waittail == nil {
347 t.waitlink = s
348 } else {
349 t.waittail.waitlink = s
350 }
351 t.waittail = s
352 s.waitlink = nil
353 if t.waiters+1 != 0 {
354 t.waiters++
355 }
356 }
357 return
358 }
359 last = t
360 if uintptr(unsafe.Pointer(addr)) < uintptr(t.elem) {
361 pt = &t.prev
362 } else {
363 pt = &t.next
364 }
365 }
366
367 // Add s as new leaf in tree of unique addrs.
368 // The balanced tree is a treap using ticket as the random heap priority.
369 // That is, it is a binary tree ordered according to the elem addresses,
370 // but then among the space of possible binary trees respecting those
371 // addresses, it is kept balanced on average by maintaining a heap ordering
372 // on the ticket: s.ticket <= both s.prev.ticket and s.next.ticket.
373 // https://en.wikipedia.org/wiki/Treap
374 // https://faculty.washington.edu/aragon/pubs/rst89.pdf
375 //
376 // s.ticket compared with zero in couple of places, therefore set lowest bit.
377 // It will not affect treap's quality noticeably.
378 s.ticket = cheaprand() | 1
379 s.parent = last
380 *pt = s
381
382 // Rotate up into tree according to ticket (priority).
383 for s.parent != nil && s.parent.ticket > s.ticket {
384 if s.parent.prev == s {
385 root.rotateRight(s.parent)
386 } else {
387 if s.parent.next != s {
388 panic("semaRoot queue")
389 }
390 root.rotateLeft(s.parent)
391 }
392 }
393 }
394
395 // dequeue searches for and finds the first goroutine
396 // in semaRoot blocked on addr.
397 // If the sudog was being profiled, dequeue returns the time
398 // at which it was woken up as now. Otherwise now is 0.
399 // If there are additional entries in the wait list, dequeue
400 // returns tailtime set to the last entry's acquiretime.
401 // Otherwise tailtime is found.acquiretime.
402 func (root *semaRoot) dequeue(addr *uint32) (found *sudog, now, tailtime int64) {
403 ps := &root.treap
404 s := *ps
405 for ; s != nil; s = *ps {
406 if s.elem == unsafe.Pointer(addr) {
407 goto Found
408 }
409 if uintptr(unsafe.Pointer(addr)) < uintptr(s.elem) {
410 ps = &s.prev
411 } else {
412 ps = &s.next
413 }
414 }
415 return nil, 0, 0
416
417 Found:
418 now = int64(0)
419 if s.acquiretime != 0 {
420 now = cputicks()
421 }
422 if t := s.waitlink; t != nil {
423 // Substitute t, also waiting on addr, for s in root tree of unique addrs.
424 *ps = t
425 t.ticket = s.ticket
426 t.parent = s.parent
427 t.prev = s.prev
428 if t.prev != nil {
429 t.prev.parent = t
430 }
431 t.next = s.next
432 if t.next != nil {
433 t.next.parent = t
434 }
435 if t.waitlink != nil {
436 t.waittail = s.waittail
437 } else {
438 t.waittail = nil
439 }
440 t.waiters = s.waiters
441 if t.waiters > 1 {
442 t.waiters--
443 }
444 // Set head and tail acquire time to 'now',
445 // because the caller will take care of charging
446 // the delays before now for all entries in the list.
447 t.acquiretime = now
448 tailtime = s.waittail.acquiretime
449 s.waittail.acquiretime = now
450 s.waitlink = nil
451 s.waittail = nil
452 } else {
453 // Rotate s down to be leaf of tree for removal, respecting priorities.
454 for s.next != nil || s.prev != nil {
455 if s.next == nil || s.prev != nil && s.prev.ticket < s.next.ticket {
456 root.rotateRight(s)
457 } else {
458 root.rotateLeft(s)
459 }
460 }
461 // Remove s, now a leaf.
462 if s.parent != nil {
463 if s.parent.prev == s {
464 s.parent.prev = nil
465 } else {
466 s.parent.next = nil
467 }
468 } else {
469 root.treap = nil
470 }
471 tailtime = s.acquiretime
472 }
473 s.parent = nil
474 s.elem = nil
475 s.next = nil
476 s.prev = nil
477 s.ticket = 0
478 return s, now, tailtime
479 }
480
481 // rotateLeft rotates the tree rooted at node x.
482 // turning (x a (y b c)) into (y (x a b) c).
483 func (root *semaRoot) rotateLeft(x *sudog) {
484 // p -> (x a (y b c))
485 p := x.parent
486 y := x.next
487 b := y.prev
488
489 y.prev = x
490 x.parent = y
491 x.next = b
492 if b != nil {
493 b.parent = x
494 }
495
496 y.parent = p
497 if p == nil {
498 root.treap = y
499 } else if p.prev == x {
500 p.prev = y
501 } else {
502 if p.next != x {
503 throw("semaRoot rotateLeft")
504 }
505 p.next = y
506 }
507 }
508
509 // rotateRight rotates the tree rooted at node y.
510 // turning (y (x a b) c) into (x a (y b c)).
511 func (root *semaRoot) rotateRight(y *sudog) {
512 // p -> (y (x a b) c)
513 p := y.parent
514 x := y.prev
515 b := x.next
516
517 x.next = y
518 y.parent = x
519 y.prev = b
520 if b != nil {
521 b.parent = y
522 }
523
524 x.parent = p
525 if p == nil {
526 root.treap = x
527 } else if p.prev == y {
528 p.prev = x
529 } else {
530 if p.next != y {
531 throw("semaRoot rotateRight")
532 }
533 p.next = x
534 }
535 }
536
537 // notifyList is a ticket-based notification list used to implement sync.Cond.
538 //
539 // It must be kept in sync with the sync package.
540 type notifyList struct {
541 // wait is the ticket number of the next waiter. It is atomically
542 // incremented outside the lock.
543 wait atomic.Uint32
544
545 // notify is the ticket number of the next waiter to be notified. It can
546 // be read outside the lock, but is only written to with lock held.
547 //
548 // Both wait & notify can wrap around, and such cases will be correctly
549 // handled as long as their "unwrapped" difference is bounded by 2^31.
550 // For this not to be the case, we'd need to have 2^31+ goroutines
551 // blocked on the same condvar, which is currently not possible.
552 notify uint32
553
554 // List of parked waiters.
555 lock mutex
556 head *sudog
557 tail *sudog
558 }
559
560 // less checks if a < b, considering a & b running counts that may overflow the
561 // 32-bit range, and that their "unwrapped" difference is always less than 2^31.
562 func less(a, b uint32) bool {
563 return int32(a-b) < 0
564 }
565
566 // notifyListAdd adds the caller to a notify list such that it can receive
567 // notifications. The caller must eventually call notifyListWait to wait for
568 // such a notification, passing the returned ticket number.
569 //
570 //go:linkname notifyListAdd sync.runtime_notifyListAdd
571 func notifyListAdd(l *notifyList) uint32 {
572 // This may be called concurrently, for example, when called from
573 // sync.Cond.Wait while holding a RWMutex in read mode.
574 return l.wait.Add(1) - 1
575 }
576
577 // notifyListWait waits for a notification. If one has been sent since
578 // notifyListAdd was called, it returns immediately. Otherwise, it blocks.
579 //
580 //go:linkname notifyListWait sync.runtime_notifyListWait
581 func notifyListWait(l *notifyList, t uint32) {
582 lockWithRank(&l.lock, lockRankNotifyList)
583
584 // Return right away if this ticket has already been notified.
585 if less(t, l.notify) {
586 unlock(&l.lock)
587 return
588 }
589
590 // Enqueue itself.
591 s := acquireSudog()
592 s.g = getg()
593 s.ticket = t
594 s.releasetime = 0
595 t0 := int64(0)
596 if blockprofilerate > 0 {
597 t0 = cputicks()
598 s.releasetime = -1
599 }
600 if l.tail == nil {
601 l.head = s
602 } else {
603 l.tail.next = s
604 }
605 l.tail = s
606 goparkunlock(&l.lock, waitReasonSyncCondWait, traceBlockCondWait, 3)
607 if t0 != 0 {
608 blockevent(s.releasetime-t0, 2)
609 }
610 releaseSudog(s)
611 }
612
613 // notifyListNotifyAll notifies all entries in the list.
614 //
615 //go:linkname notifyListNotifyAll sync.runtime_notifyListNotifyAll
616 func notifyListNotifyAll(l *notifyList) {
617 // Fast-path: if there are no new waiters since the last notification
618 // we don't need to acquire the lock.
619 if l.wait.Load() == atomic.Load(&l.notify) {
620 return
621 }
622
623 // Pull the list out into a local variable, waiters will be readied
624 // outside the lock.
625 lockWithRank(&l.lock, lockRankNotifyList)
626 s := l.head
627 l.head = nil
628 l.tail = nil
629
630 // Update the next ticket to be notified. We can set it to the current
631 // value of wait because any previous waiters are already in the list
632 // or will notice that they have already been notified when trying to
633 // add themselves to the list.
634 atomic.Store(&l.notify, l.wait.Load())
635 unlock(&l.lock)
636
637 // Go through the local list and ready all waiters.
638 for s != nil {
639 next := s.next
640 s.next = nil
641 if s.g.bubble != nil && getg().bubble != s.g.bubble {
642 println("semaphore wake of synctest goroutine", s.g.goid, "from outside bubble")
643 fatal("semaphore wake of synctest goroutine from outside bubble")
644 }
645 readyWithTime(s, 4)
646 s = next
647 }
648 }
649
650 // notifyListNotifyOne notifies one entry in the list.
651 //
652 //go:linkname notifyListNotifyOne sync.runtime_notifyListNotifyOne
653 func notifyListNotifyOne(l *notifyList) {
654 // Fast-path: if there are no new waiters since the last notification
655 // we don't need to acquire the lock at all.
656 if l.wait.Load() == atomic.Load(&l.notify) {
657 return
658 }
659
660 lockWithRank(&l.lock, lockRankNotifyList)
661
662 // Re-check under the lock if we need to do anything.
663 t := l.notify
664 if t == l.wait.Load() {
665 unlock(&l.lock)
666 return
667 }
668
669 // Update the next notify ticket number.
670 atomic.Store(&l.notify, t+1)
671
672 // Try to find the g that needs to be notified.
673 // If it hasn't made it to the list yet we won't find it,
674 // but it won't park itself once it sees the new notify number.
675 //
676 // This scan looks linear but essentially always stops quickly.
677 // Because g's queue separately from taking numbers,
678 // there may be minor reorderings in the list, but we
679 // expect the g we're looking for to be near the front.
680 // The g has others in front of it on the list only to the
681 // extent that it lost the race, so the iteration will not
682 // be too long. This applies even when the g is missing:
683 // it hasn't yet gotten to sleep and has lost the race to
684 // the (few) other g's that we find on the list.
685 for p, s := (*sudog)(nil), l.head; s != nil; p, s = s, s.next {
686 if s.ticket == t {
687 n := s.next
688 if p != nil {
689 p.next = n
690 } else {
691 l.head = n
692 }
693 if n == nil {
694 l.tail = p
695 }
696 unlock(&l.lock)
697 s.next = nil
698 if s.g.bubble != nil && getg().bubble != s.g.bubble {
699 println("semaphore wake of synctest goroutine", s.g.goid, "from outside bubble")
700 fatal("semaphore wake of synctest goroutine from outside bubble")
701 }
702 readyWithTime(s, 4)
703 return
704 }
705 }
706 unlock(&l.lock)
707 }
708
709 //go:linkname notifyListCheck sync.runtime_notifyListCheck
710 func notifyListCheck(sz uintptr) {
711 if sz != unsafe.Sizeof(notifyList{}) {
712 print("runtime: bad notifyList size - sync=", sz, " runtime=", unsafe.Sizeof(notifyList{}), "\n")
713 throw("bad notifyList size")
714 }
715 }
716
717 //go:linkname internal_sync_nanotime internal/sync.runtime_nanotime
718 func internal_sync_nanotime() int64 {
719 return nanotime()
720 }