Black Lives Matter. Support the Equal Justice Initiative.

Source file src/runtime/netpoll.go

Documentation: runtime

     1  // Copyright 2013 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  // +build aix darwin dragonfly freebsd js,wasm linux netbsd openbsd solaris windows
     6  
     7  package runtime
     8  
     9  import (
    10  	"runtime/internal/atomic"
    11  	"unsafe"
    12  )
    13  
    14  // Integrated network poller (platform-independent part).
    15  // A particular implementation (epoll/kqueue/port/AIX/Windows)
    16  // must define the following functions:
    17  //
    18  // func netpollinit()
    19  //     Initialize the poller. Only called once.
    20  //
    21  // func netpollopen(fd uintptr, pd *pollDesc) int32
    22  //     Arm edge-triggered notifications for fd. The pd argument is to pass
    23  //     back to netpollready when fd is ready. Return an errno value.
    24  //
    25  // func netpoll(delta int64) gList
    26  //     Poll the network. If delta < 0, block indefinitely. If delta == 0,
    27  //     poll without blocking. If delta > 0, block for up to delta nanoseconds.
    28  //     Return a list of goroutines built by calling netpollready.
    29  //
    30  // func netpollBreak()
    31  //     Wake up the network poller, assumed to be blocked in netpoll.
    32  //
    33  // func netpollIsPollDescriptor(fd uintptr) bool
    34  //     Reports whether fd is a file descriptor used by the poller.
    35  
    36  // Error codes returned by runtime_pollReset and runtime_pollWait.
    37  // These must match the values in internal/poll/fd_poll_runtime.go.
    38  const (
    39  	pollNoError        = 0 // no error
    40  	pollErrClosing     = 1 // descriptor is closed
    41  	pollErrTimeout     = 2 // I/O timeout
    42  	pollErrNotPollable = 3 // general error polling descriptor
    43  )
    44  
    45  // pollDesc contains 2 binary semaphores, rg and wg, to park reader and writer
    46  // goroutines respectively. The semaphore can be in the following states:
    47  // pdReady - io readiness notification is pending;
    48  //           a goroutine consumes the notification by changing the state to nil.
    49  // pdWait - a goroutine prepares to park on the semaphore, but not yet parked;
    50  //          the goroutine commits to park by changing the state to G pointer,
    51  //          or, alternatively, concurrent io notification changes the state to pdReady,
    52  //          or, alternatively, concurrent timeout/close changes the state to nil.
    53  // G pointer - the goroutine is blocked on the semaphore;
    54  //             io notification or timeout/close changes the state to pdReady or nil respectively
    55  //             and unparks the goroutine.
    56  // nil - none of the above.
    57  const (
    58  	pdReady uintptr = 1
    59  	pdWait  uintptr = 2
    60  )
    61  
    62  const pollBlockSize = 4 * 1024
    63  
    64  // Network poller descriptor.
    65  //
    66  // No heap pointers.
    67  //
    68  //go:notinheap
    69  type pollDesc struct {
    70  	link *pollDesc // in pollcache, protected by pollcache.lock
    71  
    72  	// The lock protects pollOpen, pollSetDeadline, pollUnblock and deadlineimpl operations.
    73  	// This fully covers seq, rt and wt variables. fd is constant throughout the PollDesc lifetime.
    74  	// pollReset, pollWait, pollWaitCanceled and runtime¬∑netpollready (IO readiness notification)
    75  	// proceed w/o taking the lock. So closing, everr, rg, rd, wg and wd are manipulated
    76  	// in a lock-free way by all operations.
    77  	// NOTE(dvyukov): the following code uses uintptr to store *g (rg/wg),
    78  	// that will blow up when GC starts moving objects.
    79  	lock    mutex // protects the following fields
    80  	fd      uintptr
    81  	closing bool
    82  	everr   bool    // marks event scanning error happened
    83  	user    uint32  // user settable cookie
    84  	rseq    uintptr // protects from stale read timers
    85  	rg      uintptr // pdReady, pdWait, G waiting for read or nil
    86  	rt      timer   // read deadline timer (set if rt.f != nil)
    87  	rd      int64   // read deadline
    88  	wseq    uintptr // protects from stale write timers
    89  	wg      uintptr // pdReady, pdWait, G waiting for write or nil
    90  	wt      timer   // write deadline timer
    91  	wd      int64   // write deadline
    92  }
    93  
    94  type pollCache struct {
    95  	lock  mutex
    96  	first *pollDesc
    97  	// PollDesc objects must be type-stable,
    98  	// because we can get ready notification from epoll/kqueue
    99  	// after the descriptor is closed/reused.
   100  	// Stale notifications are detected using seq variable,
   101  	// seq is incremented when deadlines are changed or descriptor is reused.
   102  }
   103  
   104  var (
   105  	netpollInitLock mutex
   106  	netpollInited   uint32
   107  
   108  	pollcache      pollCache
   109  	netpollWaiters uint32
   110  )
   111  
   112  //go:linkname poll_runtime_pollServerInit internal/poll.runtime_pollServerInit
   113  func poll_runtime_pollServerInit() {
   114  	netpollGenericInit()
   115  }
   116  
   117  func netpollGenericInit() {
   118  	if atomic.Load(&netpollInited) == 0 {
   119  		lockInit(&netpollInitLock, lockRankNetpollInit)
   120  		lock(&netpollInitLock)
   121  		if netpollInited == 0 {
   122  			netpollinit()
   123  			atomic.Store(&netpollInited, 1)
   124  		}
   125  		unlock(&netpollInitLock)
   126  	}
   127  }
   128  
   129  func netpollinited() bool {
   130  	return atomic.Load(&netpollInited) != 0
   131  }
   132  
   133  //go:linkname poll_runtime_isPollServerDescriptor internal/poll.runtime_isPollServerDescriptor
   134  
   135  // poll_runtime_isPollServerDescriptor reports whether fd is a
   136  // descriptor being used by netpoll.
   137  func poll_runtime_isPollServerDescriptor(fd uintptr) bool {
   138  	return netpollIsPollDescriptor(fd)
   139  }
   140  
   141  //go:linkname poll_runtime_pollOpen internal/poll.runtime_pollOpen
   142  func poll_runtime_pollOpen(fd uintptr) (*pollDesc, int) {
   143  	pd := pollcache.alloc()
   144  	lock(&pd.lock)
   145  	if pd.wg != 0 && pd.wg != pdReady {
   146  		throw("runtime: blocked write on free polldesc")
   147  	}
   148  	if pd.rg != 0 && pd.rg != pdReady {
   149  		throw("runtime: blocked read on free polldesc")
   150  	}
   151  	pd.fd = fd
   152  	pd.closing = false
   153  	pd.everr = false
   154  	pd.rseq++
   155  	pd.rg = 0
   156  	pd.rd = 0
   157  	pd.wseq++
   158  	pd.wg = 0
   159  	pd.wd = 0
   160  	unlock(&pd.lock)
   161  
   162  	var errno int32
   163  	errno = netpollopen(fd, pd)
   164  	return pd, int(errno)
   165  }
   166  
   167  //go:linkname poll_runtime_pollClose internal/poll.runtime_pollClose
   168  func poll_runtime_pollClose(pd *pollDesc) {
   169  	if !pd.closing {
   170  		throw("runtime: close polldesc w/o unblock")
   171  	}
   172  	if pd.wg != 0 && pd.wg != pdReady {
   173  		throw("runtime: blocked write on closing polldesc")
   174  	}
   175  	if pd.rg != 0 && pd.rg != pdReady {
   176  		throw("runtime: blocked read on closing polldesc")
   177  	}
   178  	netpollclose(pd.fd)
   179  	pollcache.free(pd)
   180  }
   181  
   182  func (c *pollCache) free(pd *pollDesc) {
   183  	lock(&c.lock)
   184  	pd.link = c.first
   185  	c.first = pd
   186  	unlock(&c.lock)
   187  }
   188  
   189  // poll_runtime_pollReset, which is internal/poll.runtime_pollReset,
   190  // prepares a descriptor for polling in mode, which is 'r' or 'w'.
   191  // This returns an error code; the codes are defined above.
   192  //go:linkname poll_runtime_pollReset internal/poll.runtime_pollReset
   193  func poll_runtime_pollReset(pd *pollDesc, mode int) int {
   194  	errcode := netpollcheckerr(pd, int32(mode))
   195  	if errcode != pollNoError {
   196  		return errcode
   197  	}
   198  	if mode == 'r' {
   199  		pd.rg = 0
   200  	} else if mode == 'w' {
   201  		pd.wg = 0
   202  	}
   203  	return pollNoError
   204  }
   205  
   206  // poll_runtime_pollWait, which is internal/poll.runtime_pollWait,
   207  // waits for a descriptor to be ready for reading or writing,
   208  // according to mode, which is 'r' or 'w'.
   209  // This returns an error code; the codes are defined above.
   210  //go:linkname poll_runtime_pollWait internal/poll.runtime_pollWait
   211  func poll_runtime_pollWait(pd *pollDesc, mode int) int {
   212  	errcode := netpollcheckerr(pd, int32(mode))
   213  	if errcode != pollNoError {
   214  		return errcode
   215  	}
   216  	// As for now only Solaris, illumos, and AIX use level-triggered IO.
   217  	if GOOS == "solaris" || GOOS == "illumos" || GOOS == "aix" {
   218  		netpollarm(pd, mode)
   219  	}
   220  	for !netpollblock(pd, int32(mode), false) {
   221  		errcode = netpollcheckerr(pd, int32(mode))
   222  		if errcode != pollNoError {
   223  			return errcode
   224  		}
   225  		// Can happen if timeout has fired and unblocked us,
   226  		// but before we had a chance to run, timeout has been reset.
   227  		// Pretend it has not happened and retry.
   228  	}
   229  	return pollNoError
   230  }
   231  
   232  //go:linkname poll_runtime_pollWaitCanceled internal/poll.runtime_pollWaitCanceled
   233  func poll_runtime_pollWaitCanceled(pd *pollDesc, mode int) {
   234  	// This function is used only on windows after a failed attempt to cancel
   235  	// a pending async IO operation. Wait for ioready, ignore closing or timeouts.
   236  	for !netpollblock(pd, int32(mode), true) {
   237  	}
   238  }
   239  
   240  //go:linkname poll_runtime_pollSetDeadline internal/poll.runtime_pollSetDeadline
   241  func poll_runtime_pollSetDeadline(pd *pollDesc, d int64, mode int) {
   242  	lock(&pd.lock)
   243  	if pd.closing {
   244  		unlock(&pd.lock)
   245  		return
   246  	}
   247  	rd0, wd0 := pd.rd, pd.wd
   248  	combo0 := rd0 > 0 && rd0 == wd0
   249  	if d > 0 {
   250  		d += nanotime()
   251  		if d <= 0 {
   252  			// If the user has a deadline in the future, but the delay calculation
   253  			// overflows, then set the deadline to the maximum possible value.
   254  			d = 1<<63 - 1
   255  		}
   256  	}
   257  	if mode == 'r' || mode == 'r'+'w' {
   258  		pd.rd = d
   259  	}
   260  	if mode == 'w' || mode == 'r'+'w' {
   261  		pd.wd = d
   262  	}
   263  	combo := pd.rd > 0 && pd.rd == pd.wd
   264  	rtf := netpollReadDeadline
   265  	if combo {
   266  		rtf = netpollDeadline
   267  	}
   268  	if pd.rt.f == nil {
   269  		if pd.rd > 0 {
   270  			pd.rt.f = rtf
   271  			// Copy current seq into the timer arg.
   272  			// Timer func will check the seq against current descriptor seq,
   273  			// if they differ the descriptor was reused or timers were reset.
   274  			pd.rt.arg = pd
   275  			pd.rt.seq = pd.rseq
   276  			resettimer(&pd.rt, pd.rd)
   277  		}
   278  	} else if pd.rd != rd0 || combo != combo0 {
   279  		pd.rseq++ // invalidate current timers
   280  		if pd.rd > 0 {
   281  			modtimer(&pd.rt, pd.rd, 0, rtf, pd, pd.rseq)
   282  		} else {
   283  			deltimer(&pd.rt)
   284  			pd.rt.f = nil
   285  		}
   286  	}
   287  	if pd.wt.f == nil {
   288  		if pd.wd > 0 && !combo {
   289  			pd.wt.f = netpollWriteDeadline
   290  			pd.wt.arg = pd
   291  			pd.wt.seq = pd.wseq
   292  			resettimer(&pd.wt, pd.wd)
   293  		}
   294  	} else if pd.wd != wd0 || combo != combo0 {
   295  		pd.wseq++ // invalidate current timers
   296  		if pd.wd > 0 && !combo {
   297  			modtimer(&pd.wt, pd.wd, 0, netpollWriteDeadline, pd, pd.wseq)
   298  		} else {
   299  			deltimer(&pd.wt)
   300  			pd.wt.f = nil
   301  		}
   302  	}
   303  	// If we set the new deadline in the past, unblock currently pending IO if any.
   304  	var rg, wg *g
   305  	if pd.rd < 0 || pd.wd < 0 {
   306  		atomic.StorepNoWB(noescape(unsafe.Pointer(&wg)), nil) // full memory barrier between stores to rd/wd and load of rg/wg in netpollunblock
   307  		if pd.rd < 0 {
   308  			rg = netpollunblock(pd, 'r', false)
   309  		}
   310  		if pd.wd < 0 {
   311  			wg = netpollunblock(pd, 'w', false)
   312  		}
   313  	}
   314  	unlock(&pd.lock)
   315  	if rg != nil {
   316  		netpollgoready(rg, 3)
   317  	}
   318  	if wg != nil {
   319  		netpollgoready(wg, 3)
   320  	}
   321  }
   322  
   323  //go:linkname poll_runtime_pollUnblock internal/poll.runtime_pollUnblock
   324  func poll_runtime_pollUnblock(pd *pollDesc) {
   325  	lock(&pd.lock)
   326  	if pd.closing {
   327  		throw("runtime: unblock on closing polldesc")
   328  	}
   329  	pd.closing = true
   330  	pd.rseq++
   331  	pd.wseq++
   332  	var rg, wg *g
   333  	atomic.StorepNoWB(noescape(unsafe.Pointer(&rg)), nil) // full memory barrier between store to closing and read of rg/wg in netpollunblock
   334  	rg = netpollunblock(pd, 'r', false)
   335  	wg = netpollunblock(pd, 'w', false)
   336  	if pd.rt.f != nil {
   337  		deltimer(&pd.rt)
   338  		pd.rt.f = nil
   339  	}
   340  	if pd.wt.f != nil {
   341  		deltimer(&pd.wt)
   342  		pd.wt.f = nil
   343  	}
   344  	unlock(&pd.lock)
   345  	if rg != nil {
   346  		netpollgoready(rg, 3)
   347  	}
   348  	if wg != nil {
   349  		netpollgoready(wg, 3)
   350  	}
   351  }
   352  
   353  // netpollready is called by the platform-specific netpoll function.
   354  // It declares that the fd associated with pd is ready for I/O.
   355  // The toRun argument is used to build a list of goroutines to return
   356  // from netpoll. The mode argument is 'r', 'w', or 'r'+'w' to indicate
   357  // whether the fd is ready for reading or writing or both.
   358  //
   359  // This may run while the world is stopped, so write barriers are not allowed.
   360  //go:nowritebarrier
   361  func netpollready(toRun *gList, pd *pollDesc, mode int32) {
   362  	var rg, wg *g
   363  	if mode == 'r' || mode == 'r'+'w' {
   364  		rg = netpollunblock(pd, 'r', true)
   365  	}
   366  	if mode == 'w' || mode == 'r'+'w' {
   367  		wg = netpollunblock(pd, 'w', true)
   368  	}
   369  	if rg != nil {
   370  		toRun.push(rg)
   371  	}
   372  	if wg != nil {
   373  		toRun.push(wg)
   374  	}
   375  }
   376  
   377  func netpollcheckerr(pd *pollDesc, mode int32) int {
   378  	if pd.closing {
   379  		return pollErrClosing
   380  	}
   381  	if (mode == 'r' && pd.rd < 0) || (mode == 'w' && pd.wd < 0) {
   382  		return pollErrTimeout
   383  	}
   384  	// Report an event scanning error only on a read event.
   385  	// An error on a write event will be captured in a subsequent
   386  	// write call that is able to report a more specific error.
   387  	if mode == 'r' && pd.everr {
   388  		return pollErrNotPollable
   389  	}
   390  	return pollNoError
   391  }
   392  
   393  func netpollblockcommit(gp *g, gpp unsafe.Pointer) bool {
   394  	r := atomic.Casuintptr((*uintptr)(gpp), pdWait, uintptr(unsafe.Pointer(gp)))
   395  	if r {
   396  		// Bump the count of goroutines waiting for the poller.
   397  		// The scheduler uses this to decide whether to block
   398  		// waiting for the poller if there is nothing else to do.
   399  		atomic.Xadd(&netpollWaiters, 1)
   400  	}
   401  	return r
   402  }
   403  
   404  func netpollgoready(gp *g, traceskip int) {
   405  	atomic.Xadd(&netpollWaiters, -1)
   406  	goready(gp, traceskip+1)
   407  }
   408  
   409  // returns true if IO is ready, or false if timedout or closed
   410  // waitio - wait only for completed IO, ignore errors
   411  func netpollblock(pd *pollDesc, mode int32, waitio bool) bool {
   412  	gpp := &pd.rg
   413  	if mode == 'w' {
   414  		gpp = &pd.wg
   415  	}
   416  
   417  	// set the gpp semaphore to pdWait
   418  	for {
   419  		old := *gpp
   420  		if old == pdReady {
   421  			*gpp = 0
   422  			return true
   423  		}
   424  		if old != 0 {
   425  			throw("runtime: double wait")
   426  		}
   427  		if atomic.Casuintptr(gpp, 0, pdWait) {
   428  			break
   429  		}
   430  	}
   431  
   432  	// need to recheck error states after setting gpp to pdWait
   433  	// this is necessary because runtime_pollUnblock/runtime_pollSetDeadline/deadlineimpl
   434  	// do the opposite: store to closing/rd/wd, membarrier, load of rg/wg
   435  	if waitio || netpollcheckerr(pd, mode) == 0 {
   436  		gopark(netpollblockcommit, unsafe.Pointer(gpp), waitReasonIOWait, traceEvGoBlockNet, 5)
   437  	}
   438  	// be careful to not lose concurrent pdReady notification
   439  	old := atomic.Xchguintptr(gpp, 0)
   440  	if old > pdWait {
   441  		throw("runtime: corrupted polldesc")
   442  	}
   443  	return old == pdReady
   444  }
   445  
   446  func netpollunblock(pd *pollDesc, mode int32, ioready bool) *g {
   447  	gpp := &pd.rg
   448  	if mode == 'w' {
   449  		gpp = &pd.wg
   450  	}
   451  
   452  	for {
   453  		old := *gpp
   454  		if old == pdReady {
   455  			return nil
   456  		}
   457  		if old == 0 && !ioready {
   458  			// Only set pdReady for ioready. runtime_pollWait
   459  			// will check for timeout/cancel before waiting.
   460  			return nil
   461  		}
   462  		var new uintptr
   463  		if ioready {
   464  			new = pdReady
   465  		}
   466  		if atomic.Casuintptr(gpp, old, new) {
   467  			if old == pdWait {
   468  				old = 0
   469  			}
   470  			return (*g)(unsafe.Pointer(old))
   471  		}
   472  	}
   473  }
   474  
   475  func netpolldeadlineimpl(pd *pollDesc, seq uintptr, read, write bool) {
   476  	lock(&pd.lock)
   477  	// Seq arg is seq when the timer was set.
   478  	// If it's stale, ignore the timer event.
   479  	currentSeq := pd.rseq
   480  	if !read {
   481  		currentSeq = pd.wseq
   482  	}
   483  	if seq != currentSeq {
   484  		// The descriptor was reused or timers were reset.
   485  		unlock(&pd.lock)
   486  		return
   487  	}
   488  	var rg *g
   489  	if read {
   490  		if pd.rd <= 0 || pd.rt.f == nil {
   491  			throw("runtime: inconsistent read deadline")
   492  		}
   493  		pd.rd = -1
   494  		atomic.StorepNoWB(unsafe.Pointer(&pd.rt.f), nil) // full memory barrier between store to rd and load of rg in netpollunblock
   495  		rg = netpollunblock(pd, 'r', false)
   496  	}
   497  	var wg *g
   498  	if write {
   499  		if pd.wd <= 0 || pd.wt.f == nil && !read {
   500  			throw("runtime: inconsistent write deadline")
   501  		}
   502  		pd.wd = -1
   503  		atomic.StorepNoWB(unsafe.Pointer(&pd.wt.f), nil) // full memory barrier between store to wd and load of wg in netpollunblock
   504  		wg = netpollunblock(pd, 'w', false)
   505  	}
   506  	unlock(&pd.lock)
   507  	if rg != nil {
   508  		netpollgoready(rg, 0)
   509  	}
   510  	if wg != nil {
   511  		netpollgoready(wg, 0)
   512  	}
   513  }
   514  
   515  func netpollDeadline(arg interface{}, seq uintptr) {
   516  	netpolldeadlineimpl(arg.(*pollDesc), seq, true, true)
   517  }
   518  
   519  func netpollReadDeadline(arg interface{}, seq uintptr) {
   520  	netpolldeadlineimpl(arg.(*pollDesc), seq, true, false)
   521  }
   522  
   523  func netpollWriteDeadline(arg interface{}, seq uintptr) {
   524  	netpolldeadlineimpl(arg.(*pollDesc), seq, false, true)
   525  }
   526  
   527  func (c *pollCache) alloc() *pollDesc {
   528  	lock(&c.lock)
   529  	if c.first == nil {
   530  		const pdSize = unsafe.Sizeof(pollDesc{})
   531  		n := pollBlockSize / pdSize
   532  		if n == 0 {
   533  			n = 1
   534  		}
   535  		// Must be in non-GC memory because can be referenced
   536  		// only from epoll/kqueue internals.
   537  		mem := persistentalloc(n*pdSize, 0, &memstats.other_sys)
   538  		for i := uintptr(0); i < n; i++ {
   539  			pd := (*pollDesc)(add(mem, i*pdSize))
   540  			pd.link = c.first
   541  			c.first = pd
   542  		}
   543  	}
   544  	pd := c.first
   545  	c.first = pd.link
   546  	lockInit(&pd.lock, lockRankPollDesc)
   547  	unlock(&c.lock)
   548  	return pd
   549  }
   550  

View as plain text