...

Source file src/runtime/sema.go

Documentation: runtime

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

View as plain text