Source file src/runtime/netpoll.go

     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  //go:build unix || (js && wasm) || wasip1 || windows
     6  
     7  package runtime
     8  
     9  import (
    10  	"runtime/internal/atomic"
    11  	"runtime/internal/sys"
    12  	"unsafe"
    13  )
    14  
    15  // Integrated network poller (platform-independent part).
    16  // A particular implementation (epoll/kqueue/port/AIX/Windows)
    17  // must define the following functions:
    18  //
    19  // func netpollinit()
    20  //     Initialize the poller. Only called once.
    21  //
    22  // func netpollopen(fd uintptr, pd *pollDesc) int32
    23  //     Arm edge-triggered notifications for fd. The pd argument is to pass
    24  //     back to netpollready when fd is ready. Return an errno value.
    25  //
    26  // func netpollclose(fd uintptr) int32
    27  //     Disable notifications for fd. Return an errno value.
    28  //
    29  // func netpoll(delta int64) (gList, int32)
    30  //     Poll the network. If delta < 0, block indefinitely. If delta == 0,
    31  //     poll without blocking. If delta > 0, block for up to delta nanoseconds.
    32  //     Return a list of goroutines built by calling netpollready,
    33  //     and a delta to add to netpollWaiters when all goroutines are ready.
    34  //     This will never return an empty list with a non-zero delta.
    35  //
    36  // func netpollBreak()
    37  //     Wake up the network poller, assumed to be blocked in netpoll.
    38  //
    39  // func netpollIsPollDescriptor(fd uintptr) bool
    40  //     Reports whether fd is a file descriptor used by the poller.
    41  
    42  // Error codes returned by runtime_pollReset and runtime_pollWait.
    43  // These must match the values in internal/poll/fd_poll_runtime.go.
    44  const (
    45  	pollNoError        = 0 // no error
    46  	pollErrClosing     = 1 // descriptor is closed
    47  	pollErrTimeout     = 2 // I/O timeout
    48  	pollErrNotPollable = 3 // general error polling descriptor
    49  )
    50  
    51  // pollDesc contains 2 binary semaphores, rg and wg, to park reader and writer
    52  // goroutines respectively. The semaphore can be in the following states:
    53  //
    54  //	pdReady - io readiness notification is pending;
    55  //	          a goroutine consumes the notification by changing the state to pdNil.
    56  //	pdWait - a goroutine prepares to park on the semaphore, but not yet parked;
    57  //	         the goroutine commits to park by changing the state to G pointer,
    58  //	         or, alternatively, concurrent io notification changes the state to pdReady,
    59  //	         or, alternatively, concurrent timeout/close changes the state to pdNil.
    60  //	G pointer - the goroutine is blocked on the semaphore;
    61  //	            io notification or timeout/close changes the state to pdReady or pdNil respectively
    62  //	            and unparks the goroutine.
    63  //	pdNil - none of the above.
    64  const (
    65  	pdNil   uintptr = 0
    66  	pdReady uintptr = 1
    67  	pdWait  uintptr = 2
    68  )
    69  
    70  const pollBlockSize = 4 * 1024
    71  
    72  // Network poller descriptor.
    73  //
    74  // No heap pointers.
    75  type pollDesc struct {
    76  	_     sys.NotInHeap
    77  	link  *pollDesc      // in pollcache, protected by pollcache.lock
    78  	fd    uintptr        // constant for pollDesc usage lifetime
    79  	fdseq atomic.Uintptr // protects against stale pollDesc
    80  
    81  	// atomicInfo holds bits from closing, rd, and wd,
    82  	// which are only ever written while holding the lock,
    83  	// summarized for use by netpollcheckerr,
    84  	// which cannot acquire the lock.
    85  	// After writing these fields under lock in a way that
    86  	// might change the summary, code must call publishInfo
    87  	// before releasing the lock.
    88  	// Code that changes fields and then calls netpollunblock
    89  	// (while still holding the lock) must call publishInfo
    90  	// before calling netpollunblock, because publishInfo is what
    91  	// stops netpollblock from blocking anew
    92  	// (by changing the result of netpollcheckerr).
    93  	// atomicInfo also holds the eventErr bit,
    94  	// recording whether a poll event on the fd got an error;
    95  	// atomicInfo is the only source of truth for that bit.
    96  	atomicInfo atomic.Uint32 // atomic pollInfo
    97  
    98  	// rg, wg are accessed atomically and hold g pointers.
    99  	// (Using atomic.Uintptr here is similar to using guintptr elsewhere.)
   100  	rg atomic.Uintptr // pdReady, pdWait, G waiting for read or pdNil
   101  	wg atomic.Uintptr // pdReady, pdWait, G waiting for write or pdNil
   102  
   103  	lock    mutex // protects the following fields
   104  	closing bool
   105  	user    uint32    // user settable cookie
   106  	rseq    uintptr   // protects from stale read timers
   107  	rt      timer     // read deadline timer (set if rt.f != nil)
   108  	rd      int64     // read deadline (a nanotime in the future, -1 when expired)
   109  	wseq    uintptr   // protects from stale write timers
   110  	wt      timer     // write deadline timer
   111  	wd      int64     // write deadline (a nanotime in the future, -1 when expired)
   112  	self    *pollDesc // storage for indirect interface. See (*pollDesc).makeArg.
   113  }
   114  
   115  // pollInfo is the bits needed by netpollcheckerr, stored atomically,
   116  // mostly duplicating state that is manipulated under lock in pollDesc.
   117  // The one exception is the pollEventErr bit, which is maintained only
   118  // in the pollInfo.
   119  type pollInfo uint32
   120  
   121  const (
   122  	pollClosing = 1 << iota
   123  	pollEventErr
   124  	pollExpiredReadDeadline
   125  	pollExpiredWriteDeadline
   126  	pollFDSeq // 20 bit field, low 20 bits of fdseq field
   127  )
   128  
   129  const (
   130  	pollFDSeqBits = 20                   // number of bits in pollFDSeq
   131  	pollFDSeqMask = 1<<pollFDSeqBits - 1 // mask for pollFDSeq
   132  )
   133  
   134  func (i pollInfo) closing() bool              { return i&pollClosing != 0 }
   135  func (i pollInfo) eventErr() bool             { return i&pollEventErr != 0 }
   136  func (i pollInfo) expiredReadDeadline() bool  { return i&pollExpiredReadDeadline != 0 }
   137  func (i pollInfo) expiredWriteDeadline() bool { return i&pollExpiredWriteDeadline != 0 }
   138  
   139  // info returns the pollInfo corresponding to pd.
   140  func (pd *pollDesc) info() pollInfo {
   141  	return pollInfo(pd.atomicInfo.Load())
   142  }
   143  
   144  // publishInfo updates pd.atomicInfo (returned by pd.info)
   145  // using the other values in pd.
   146  // It must be called while holding pd.lock,
   147  // and it must be called after changing anything
   148  // that might affect the info bits.
   149  // In practice this means after changing closing
   150  // or changing rd or wd from < 0 to >= 0.
   151  func (pd *pollDesc) publishInfo() {
   152  	var info uint32
   153  	if pd.closing {
   154  		info |= pollClosing
   155  	}
   156  	if pd.rd < 0 {
   157  		info |= pollExpiredReadDeadline
   158  	}
   159  	if pd.wd < 0 {
   160  		info |= pollExpiredWriteDeadline
   161  	}
   162  	info |= uint32(pd.fdseq.Load()&pollFDSeqMask) << pollFDSeq
   163  
   164  	// Set all of x except the pollEventErr bit.
   165  	x := pd.atomicInfo.Load()
   166  	for !pd.atomicInfo.CompareAndSwap(x, (x&pollEventErr)|info) {
   167  		x = pd.atomicInfo.Load()
   168  	}
   169  }
   170  
   171  // setEventErr sets the result of pd.info().eventErr() to b.
   172  // We only change the error bit if seq == 0 or if seq matches pollFDSeq
   173  // (issue #59545).
   174  func (pd *pollDesc) setEventErr(b bool, seq uintptr) {
   175  	mSeq := uint32(seq & pollFDSeqMask)
   176  	x := pd.atomicInfo.Load()
   177  	xSeq := (x >> pollFDSeq) & pollFDSeqMask
   178  	if seq != 0 && xSeq != mSeq {
   179  		return
   180  	}
   181  	for (x&pollEventErr != 0) != b && !pd.atomicInfo.CompareAndSwap(x, x^pollEventErr) {
   182  		x = pd.atomicInfo.Load()
   183  		xSeq := (x >> pollFDSeq) & pollFDSeqMask
   184  		if seq != 0 && xSeq != mSeq {
   185  			return
   186  		}
   187  	}
   188  }
   189  
   190  type pollCache struct {
   191  	lock  mutex
   192  	first *pollDesc
   193  	// PollDesc objects must be type-stable,
   194  	// because we can get ready notification from epoll/kqueue
   195  	// after the descriptor is closed/reused.
   196  	// Stale notifications are detected using seq variable,
   197  	// seq is incremented when deadlines are changed or descriptor is reused.
   198  }
   199  
   200  var (
   201  	netpollInitLock mutex
   202  	netpollInited   atomic.Uint32
   203  
   204  	pollcache      pollCache
   205  	netpollWaiters atomic.Uint32
   206  )
   207  
   208  //go:linkname poll_runtime_pollServerInit internal/poll.runtime_pollServerInit
   209  func poll_runtime_pollServerInit() {
   210  	netpollGenericInit()
   211  }
   212  
   213  func netpollGenericInit() {
   214  	if netpollInited.Load() == 0 {
   215  		lockInit(&netpollInitLock, lockRankNetpollInit)
   216  		lock(&netpollInitLock)
   217  		if netpollInited.Load() == 0 {
   218  			netpollinit()
   219  			netpollInited.Store(1)
   220  		}
   221  		unlock(&netpollInitLock)
   222  	}
   223  }
   224  
   225  func netpollinited() bool {
   226  	return netpollInited.Load() != 0
   227  }
   228  
   229  //go:linkname poll_runtime_isPollServerDescriptor internal/poll.runtime_isPollServerDescriptor
   230  
   231  // poll_runtime_isPollServerDescriptor reports whether fd is a
   232  // descriptor being used by netpoll.
   233  func poll_runtime_isPollServerDescriptor(fd uintptr) bool {
   234  	return netpollIsPollDescriptor(fd)
   235  }
   236  
   237  //go:linkname poll_runtime_pollOpen internal/poll.runtime_pollOpen
   238  func poll_runtime_pollOpen(fd uintptr) (*pollDesc, int) {
   239  	pd := pollcache.alloc()
   240  	lock(&pd.lock)
   241  	wg := pd.wg.Load()
   242  	if wg != pdNil && wg != pdReady {
   243  		throw("runtime: blocked write on free polldesc")
   244  	}
   245  	rg := pd.rg.Load()
   246  	if rg != pdNil && rg != pdReady {
   247  		throw("runtime: blocked read on free polldesc")
   248  	}
   249  	pd.fd = fd
   250  	if pd.fdseq.Load() == 0 {
   251  		// The value 0 is special in setEventErr, so don't use it.
   252  		pd.fdseq.Store(1)
   253  	}
   254  	pd.closing = false
   255  	pd.setEventErr(false, 0)
   256  	pd.rseq++
   257  	pd.rg.Store(pdNil)
   258  	pd.rd = 0
   259  	pd.wseq++
   260  	pd.wg.Store(pdNil)
   261  	pd.wd = 0
   262  	pd.self = pd
   263  	pd.publishInfo()
   264  	unlock(&pd.lock)
   265  
   266  	errno := netpollopen(fd, pd)
   267  	if errno != 0 {
   268  		pollcache.free(pd)
   269  		return nil, int(errno)
   270  	}
   271  	return pd, 0
   272  }
   273  
   274  //go:linkname poll_runtime_pollClose internal/poll.runtime_pollClose
   275  func poll_runtime_pollClose(pd *pollDesc) {
   276  	if !pd.closing {
   277  		throw("runtime: close polldesc w/o unblock")
   278  	}
   279  	wg := pd.wg.Load()
   280  	if wg != pdNil && wg != pdReady {
   281  		throw("runtime: blocked write on closing polldesc")
   282  	}
   283  	rg := pd.rg.Load()
   284  	if rg != pdNil && rg != pdReady {
   285  		throw("runtime: blocked read on closing polldesc")
   286  	}
   287  	netpollclose(pd.fd)
   288  	pollcache.free(pd)
   289  }
   290  
   291  func (c *pollCache) free(pd *pollDesc) {
   292  	// pd can't be shared here, but lock anyhow because
   293  	// that's what publishInfo documents.
   294  	lock(&pd.lock)
   295  
   296  	// Increment the fdseq field, so that any currently
   297  	// running netpoll calls will not mark pd as ready.
   298  	fdseq := pd.fdseq.Load()
   299  	fdseq = (fdseq + 1) & (1<<taggedPointerBits - 1)
   300  	pd.fdseq.Store(fdseq)
   301  
   302  	pd.publishInfo()
   303  
   304  	unlock(&pd.lock)
   305  
   306  	lock(&c.lock)
   307  	pd.link = c.first
   308  	c.first = pd
   309  	unlock(&c.lock)
   310  }
   311  
   312  // poll_runtime_pollReset, which is internal/poll.runtime_pollReset,
   313  // prepares a descriptor for polling in mode, which is 'r' or 'w'.
   314  // This returns an error code; the codes are defined above.
   315  //
   316  //go:linkname poll_runtime_pollReset internal/poll.runtime_pollReset
   317  func poll_runtime_pollReset(pd *pollDesc, mode int) int {
   318  	errcode := netpollcheckerr(pd, int32(mode))
   319  	if errcode != pollNoError {
   320  		return errcode
   321  	}
   322  	if mode == 'r' {
   323  		pd.rg.Store(pdNil)
   324  	} else if mode == 'w' {
   325  		pd.wg.Store(pdNil)
   326  	}
   327  	return pollNoError
   328  }
   329  
   330  // poll_runtime_pollWait, which is internal/poll.runtime_pollWait,
   331  // waits for a descriptor to be ready for reading or writing,
   332  // according to mode, which is 'r' or 'w'.
   333  // This returns an error code; the codes are defined above.
   334  //
   335  //go:linkname poll_runtime_pollWait internal/poll.runtime_pollWait
   336  func poll_runtime_pollWait(pd *pollDesc, mode int) int {
   337  	errcode := netpollcheckerr(pd, int32(mode))
   338  	if errcode != pollNoError {
   339  		return errcode
   340  	}
   341  	// As for now only Solaris, illumos, AIX and wasip1 use level-triggered IO.
   342  	if GOOS == "solaris" || GOOS == "illumos" || GOOS == "aix" || GOOS == "wasip1" {
   343  		netpollarm(pd, mode)
   344  	}
   345  	for !netpollblock(pd, int32(mode), false) {
   346  		errcode = netpollcheckerr(pd, int32(mode))
   347  		if errcode != pollNoError {
   348  			return errcode
   349  		}
   350  		// Can happen if timeout has fired and unblocked us,
   351  		// but before we had a chance to run, timeout has been reset.
   352  		// Pretend it has not happened and retry.
   353  	}
   354  	return pollNoError
   355  }
   356  
   357  //go:linkname poll_runtime_pollWaitCanceled internal/poll.runtime_pollWaitCanceled
   358  func poll_runtime_pollWaitCanceled(pd *pollDesc, mode int) {
   359  	// This function is used only on windows after a failed attempt to cancel
   360  	// a pending async IO operation. Wait for ioready, ignore closing or timeouts.
   361  	for !netpollblock(pd, int32(mode), true) {
   362  	}
   363  }
   364  
   365  //go:linkname poll_runtime_pollSetDeadline internal/poll.runtime_pollSetDeadline
   366  func poll_runtime_pollSetDeadline(pd *pollDesc, d int64, mode int) {
   367  	lock(&pd.lock)
   368  	if pd.closing {
   369  		unlock(&pd.lock)
   370  		return
   371  	}
   372  	rd0, wd0 := pd.rd, pd.wd
   373  	combo0 := rd0 > 0 && rd0 == wd0
   374  	if d > 0 {
   375  		d += nanotime()
   376  		if d <= 0 {
   377  			// If the user has a deadline in the future, but the delay calculation
   378  			// overflows, then set the deadline to the maximum possible value.
   379  			d = 1<<63 - 1
   380  		}
   381  	}
   382  	if mode == 'r' || mode == 'r'+'w' {
   383  		pd.rd = d
   384  	}
   385  	if mode == 'w' || mode == 'r'+'w' {
   386  		pd.wd = d
   387  	}
   388  	pd.publishInfo()
   389  	combo := pd.rd > 0 && pd.rd == pd.wd
   390  	rtf := netpollReadDeadline
   391  	if combo {
   392  		rtf = netpollDeadline
   393  	}
   394  	if pd.rt.f == nil {
   395  		if pd.rd > 0 {
   396  			pd.rt.f = rtf
   397  			// Copy current seq into the timer arg.
   398  			// Timer func will check the seq against current descriptor seq,
   399  			// if they differ the descriptor was reused or timers were reset.
   400  			pd.rt.arg = pd.makeArg()
   401  			pd.rt.seq = pd.rseq
   402  			resettimer(&pd.rt, pd.rd)
   403  		}
   404  	} else if pd.rd != rd0 || combo != combo0 {
   405  		pd.rseq++ // invalidate current timers
   406  		if pd.rd > 0 {
   407  			modtimer(&pd.rt, pd.rd, 0, rtf, pd.makeArg(), pd.rseq)
   408  		} else {
   409  			deltimer(&pd.rt)
   410  			pd.rt.f = nil
   411  		}
   412  	}
   413  	if pd.wt.f == nil {
   414  		if pd.wd > 0 && !combo {
   415  			pd.wt.f = netpollWriteDeadline
   416  			pd.wt.arg = pd.makeArg()
   417  			pd.wt.seq = pd.wseq
   418  			resettimer(&pd.wt, pd.wd)
   419  		}
   420  	} else if pd.wd != wd0 || combo != combo0 {
   421  		pd.wseq++ // invalidate current timers
   422  		if pd.wd > 0 && !combo {
   423  			modtimer(&pd.wt, pd.wd, 0, netpollWriteDeadline, pd.makeArg(), pd.wseq)
   424  		} else {
   425  			deltimer(&pd.wt)
   426  			pd.wt.f = nil
   427  		}
   428  	}
   429  	// If we set the new deadline in the past, unblock currently pending IO if any.
   430  	// Note that pd.publishInfo has already been called, above, immediately after modifying rd and wd.
   431  	delta := int32(0)
   432  	var rg, wg *g
   433  	if pd.rd < 0 {
   434  		rg = netpollunblock(pd, 'r', false, &delta)
   435  	}
   436  	if pd.wd < 0 {
   437  		wg = netpollunblock(pd, 'w', false, &delta)
   438  	}
   439  	unlock(&pd.lock)
   440  	if rg != nil {
   441  		netpollgoready(rg, 3)
   442  	}
   443  	if wg != nil {
   444  		netpollgoready(wg, 3)
   445  	}
   446  	netpollAdjustWaiters(delta)
   447  }
   448  
   449  //go:linkname poll_runtime_pollUnblock internal/poll.runtime_pollUnblock
   450  func poll_runtime_pollUnblock(pd *pollDesc) {
   451  	lock(&pd.lock)
   452  	if pd.closing {
   453  		throw("runtime: unblock on closing polldesc")
   454  	}
   455  	pd.closing = true
   456  	pd.rseq++
   457  	pd.wseq++
   458  	var rg, wg *g
   459  	pd.publishInfo()
   460  	delta := int32(0)
   461  	rg = netpollunblock(pd, 'r', false, &delta)
   462  	wg = netpollunblock(pd, 'w', false, &delta)
   463  	if pd.rt.f != nil {
   464  		deltimer(&pd.rt)
   465  		pd.rt.f = nil
   466  	}
   467  	if pd.wt.f != nil {
   468  		deltimer(&pd.wt)
   469  		pd.wt.f = nil
   470  	}
   471  	unlock(&pd.lock)
   472  	if rg != nil {
   473  		netpollgoready(rg, 3)
   474  	}
   475  	if wg != nil {
   476  		netpollgoready(wg, 3)
   477  	}
   478  	netpollAdjustWaiters(delta)
   479  }
   480  
   481  // netpollready is called by the platform-specific netpoll function.
   482  // It declares that the fd associated with pd is ready for I/O.
   483  // The toRun argument is used to build a list of goroutines to return
   484  // from netpoll. The mode argument is 'r', 'w', or 'r'+'w' to indicate
   485  // whether the fd is ready for reading or writing or both.
   486  //
   487  // This returns a delta to apply to netpollWaiters.
   488  //
   489  // This may run while the world is stopped, so write barriers are not allowed.
   490  //
   491  //go:nowritebarrier
   492  func netpollready(toRun *gList, pd *pollDesc, mode int32) int32 {
   493  	delta := int32(0)
   494  	var rg, wg *g
   495  	if mode == 'r' || mode == 'r'+'w' {
   496  		rg = netpollunblock(pd, 'r', true, &delta)
   497  	}
   498  	if mode == 'w' || mode == 'r'+'w' {
   499  		wg = netpollunblock(pd, 'w', true, &delta)
   500  	}
   501  	if rg != nil {
   502  		toRun.push(rg)
   503  	}
   504  	if wg != nil {
   505  		toRun.push(wg)
   506  	}
   507  	return delta
   508  }
   509  
   510  func netpollcheckerr(pd *pollDesc, mode int32) int {
   511  	info := pd.info()
   512  	if info.closing() {
   513  		return pollErrClosing
   514  	}
   515  	if (mode == 'r' && info.expiredReadDeadline()) || (mode == 'w' && info.expiredWriteDeadline()) {
   516  		return pollErrTimeout
   517  	}
   518  	// Report an event scanning error only on a read event.
   519  	// An error on a write event will be captured in a subsequent
   520  	// write call that is able to report a more specific error.
   521  	if mode == 'r' && info.eventErr() {
   522  		return pollErrNotPollable
   523  	}
   524  	return pollNoError
   525  }
   526  
   527  func netpollblockcommit(gp *g, gpp unsafe.Pointer) bool {
   528  	r := atomic.Casuintptr((*uintptr)(gpp), pdWait, uintptr(unsafe.Pointer(gp)))
   529  	if r {
   530  		// Bump the count of goroutines waiting for the poller.
   531  		// The scheduler uses this to decide whether to block
   532  		// waiting for the poller if there is nothing else to do.
   533  		netpollAdjustWaiters(1)
   534  	}
   535  	return r
   536  }
   537  
   538  func netpollgoready(gp *g, traceskip int) {
   539  	goready(gp, traceskip+1)
   540  }
   541  
   542  // returns true if IO is ready, or false if timed out or closed
   543  // waitio - wait only for completed IO, ignore errors
   544  // Concurrent calls to netpollblock in the same mode are forbidden, as pollDesc
   545  // can hold only a single waiting goroutine for each mode.
   546  func netpollblock(pd *pollDesc, mode int32, waitio bool) bool {
   547  	gpp := &pd.rg
   548  	if mode == 'w' {
   549  		gpp = &pd.wg
   550  	}
   551  
   552  	// set the gpp semaphore to pdWait
   553  	for {
   554  		// Consume notification if already ready.
   555  		if gpp.CompareAndSwap(pdReady, pdNil) {
   556  			return true
   557  		}
   558  		if gpp.CompareAndSwap(pdNil, pdWait) {
   559  			break
   560  		}
   561  
   562  		// Double check that this isn't corrupt; otherwise we'd loop
   563  		// forever.
   564  		if v := gpp.Load(); v != pdReady && v != pdNil {
   565  			throw("runtime: double wait")
   566  		}
   567  	}
   568  
   569  	// need to recheck error states after setting gpp to pdWait
   570  	// this is necessary because runtime_pollUnblock/runtime_pollSetDeadline/deadlineimpl
   571  	// do the opposite: store to closing/rd/wd, publishInfo, load of rg/wg
   572  	if waitio || netpollcheckerr(pd, mode) == pollNoError {
   573  		gopark(netpollblockcommit, unsafe.Pointer(gpp), waitReasonIOWait, traceBlockNet, 5)
   574  	}
   575  	// be careful to not lose concurrent pdReady notification
   576  	old := gpp.Swap(pdNil)
   577  	if old > pdWait {
   578  		throw("runtime: corrupted polldesc")
   579  	}
   580  	return old == pdReady
   581  }
   582  
   583  // netpollunblock moves either pd.rg (if mode == 'r') or
   584  // pd.wg (if mode == 'w') into the pdReady state.
   585  // This returns any goroutine blocked on pd.{rg,wg}.
   586  // It adds any adjustment to netpollWaiters to *delta;
   587  // this adjustment should be applied after the goroutine has
   588  // been marked ready.
   589  func netpollunblock(pd *pollDesc, mode int32, ioready bool, delta *int32) *g {
   590  	gpp := &pd.rg
   591  	if mode == 'w' {
   592  		gpp = &pd.wg
   593  	}
   594  
   595  	for {
   596  		old := gpp.Load()
   597  		if old == pdReady {
   598  			return nil
   599  		}
   600  		if old == pdNil && !ioready {
   601  			// Only set pdReady for ioready. runtime_pollWait
   602  			// will check for timeout/cancel before waiting.
   603  			return nil
   604  		}
   605  		new := pdNil
   606  		if ioready {
   607  			new = pdReady
   608  		}
   609  		if gpp.CompareAndSwap(old, new) {
   610  			if old == pdWait {
   611  				old = pdNil
   612  			} else if old != pdNil {
   613  				*delta -= 1
   614  			}
   615  			return (*g)(unsafe.Pointer(old))
   616  		}
   617  	}
   618  }
   619  
   620  func netpolldeadlineimpl(pd *pollDesc, seq uintptr, read, write bool) {
   621  	lock(&pd.lock)
   622  	// Seq arg is seq when the timer was set.
   623  	// If it's stale, ignore the timer event.
   624  	currentSeq := pd.rseq
   625  	if !read {
   626  		currentSeq = pd.wseq
   627  	}
   628  	if seq != currentSeq {
   629  		// The descriptor was reused or timers were reset.
   630  		unlock(&pd.lock)
   631  		return
   632  	}
   633  	delta := int32(0)
   634  	var rg *g
   635  	if read {
   636  		if pd.rd <= 0 || pd.rt.f == nil {
   637  			throw("runtime: inconsistent read deadline")
   638  		}
   639  		pd.rd = -1
   640  		pd.publishInfo()
   641  		rg = netpollunblock(pd, 'r', false, &delta)
   642  	}
   643  	var wg *g
   644  	if write {
   645  		if pd.wd <= 0 || pd.wt.f == nil && !read {
   646  			throw("runtime: inconsistent write deadline")
   647  		}
   648  		pd.wd = -1
   649  		pd.publishInfo()
   650  		wg = netpollunblock(pd, 'w', false, &delta)
   651  	}
   652  	unlock(&pd.lock)
   653  	if rg != nil {
   654  		netpollgoready(rg, 0)
   655  	}
   656  	if wg != nil {
   657  		netpollgoready(wg, 0)
   658  	}
   659  	netpollAdjustWaiters(delta)
   660  }
   661  
   662  func netpollDeadline(arg any, seq uintptr) {
   663  	netpolldeadlineimpl(arg.(*pollDesc), seq, true, true)
   664  }
   665  
   666  func netpollReadDeadline(arg any, seq uintptr) {
   667  	netpolldeadlineimpl(arg.(*pollDesc), seq, true, false)
   668  }
   669  
   670  func netpollWriteDeadline(arg any, seq uintptr) {
   671  	netpolldeadlineimpl(arg.(*pollDesc), seq, false, true)
   672  }
   673  
   674  // netpollAnyWaiters reports whether any goroutines are waiting for I/O.
   675  func netpollAnyWaiters() bool {
   676  	return netpollWaiters.Load() > 0
   677  }
   678  
   679  // netpollAdjustWaiters adds delta to netpollWaiters.
   680  func netpollAdjustWaiters(delta int32) {
   681  	if delta != 0 {
   682  		netpollWaiters.Add(delta)
   683  	}
   684  }
   685  
   686  func (c *pollCache) alloc() *pollDesc {
   687  	lock(&c.lock)
   688  	if c.first == nil {
   689  		const pdSize = unsafe.Sizeof(pollDesc{})
   690  		n := pollBlockSize / pdSize
   691  		if n == 0 {
   692  			n = 1
   693  		}
   694  		// Must be in non-GC memory because can be referenced
   695  		// only from epoll/kqueue internals.
   696  		mem := persistentalloc(n*pdSize, 0, &memstats.other_sys)
   697  		for i := uintptr(0); i < n; i++ {
   698  			pd := (*pollDesc)(add(mem, i*pdSize))
   699  			pd.link = c.first
   700  			c.first = pd
   701  		}
   702  	}
   703  	pd := c.first
   704  	c.first = pd.link
   705  	lockInit(&pd.lock, lockRankPollDesc)
   706  	unlock(&c.lock)
   707  	return pd
   708  }
   709  
   710  // makeArg converts pd to an interface{}.
   711  // makeArg does not do any allocation. Normally, such
   712  // a conversion requires an allocation because pointers to
   713  // types which embed runtime/internal/sys.NotInHeap (which pollDesc is)
   714  // must be stored in interfaces indirectly. See issue 42076.
   715  func (pd *pollDesc) makeArg() (i any) {
   716  	x := (*eface)(unsafe.Pointer(&i))
   717  	x._type = pdType
   718  	x.data = unsafe.Pointer(&pd.self)
   719  	return
   720  }
   721  
   722  var (
   723  	pdEface any    = (*pollDesc)(nil)
   724  	pdType  *_type = efaceOf(&pdEface)._type
   725  )
   726  

View as plain text