Source file src/runtime/sema.go

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

View as plain text