Debian Codegraph @

libgo/go/runtime/netpoll.go

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