Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

runtime: let sysmon sleep in netpoll if possible #51651

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
hzzb wants to merge 3 commits into golang:master
base: master
Choose a base branch
Loading
from hzzb:feature/sysmon-netpoll
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/runtime/export_test.go
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ var MemclrNoHeapPointers = memclrNoHeapPointers

var LockPartialOrder = lockPartialOrder

var Goyield = goyield

var NeedSysmonWorkaround = needSysmonWorkaround

type LockRank lockRank

func (l LockRank) String() string {
Expand Down
97 changes: 71 additions & 26 deletions src/runtime/proc.go
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,9 @@ func main() {
systemstack(func() {
newm(sysmon, nil, -1)
})
if netpollInited == 0 {
netpollGenericInit()
}
}

// Lock the main goroutine onto this, the main OS thread,
Expand Down Expand Up @@ -5050,20 +5053,23 @@ func sysmon() {
checkdead()
unlock(&sched.lock)

lasttrace := int64(0)
idle := 0 // how many cycles in succession we had not wokeup somebody
delay := uint32(0)
tracedelay := int64(debug.schedtrace) * 1000000
nexttrace := int64(maxWhen) // when should we output next schedtrace. much far future if disabled.
if tracedelay > 0 {
nexttrace = nanotime()
}
idle := 0 // how many cycles in succession we had not wokeup somebody
delay := int64(0) // ns

for {
if idle == 0 { // start with 20us sleep...
delay = 20
delay = 20 * 1000
} else if idle > 50 { // start doubling the sleep after 1ms...
delay *= 2
}
if delay > 10*1000 { // up to 10ms
delay = 10 * 1000
if delay > 10*1000*1000 { // up to 10ms
delay = 10 * 1000 * 1000
}
usleep(delay)

// sysmon should not enter deep sleep if schedtrace is enabled so that
// it can print that information at the right time.
Expand Down Expand Up @@ -5109,7 +5115,7 @@ func sysmon() {
}
if syscallWake {
idle = 0
delay = 20
delay = 20 * 1000
}
}
unlock(&sched.lock)
Expand All @@ -5124,23 +5130,62 @@ func sysmon() {
if *cgo_yield != nil {
asmcgocall(*cgo_yield, nil)
}
// poll network if not polled for more than 10ms
lastpoll := int64(atomic.Load64(&sched.lastpoll))
if netpollinited() && lastpoll != 0 && lastpoll+10*1000*1000 < now {
atomic.Cas64(&sched.lastpoll, uint64(lastpoll), uint64(now))
list := netpoll(0) // non-blocking - returns list of goroutines
if !list.empty() {
// Need to decrement number of idle locked M's
// (pretending that one more is running) before injectglist.
// Otherwise it can lead to the following situation:
// injectglist grabs all P's but before it starts M's to run the P's,
// another M returns from syscall, finishes running its G,
// observes that there is no work to do and no other running M's
// and reports deadlock.
incidlelocked(-1)
injectglist(&list)
incidlelocked(1)

if delay < 1000*1000 || (GOOS == "netbsd" && needSysmonWorkaround) {
// netpoll() will convert (0, 999us] to 1ms on some platforms.
// to let retake() happen as often as want, using usleep if delay is less than 1ms.
// issue 42515 reports netbsd may sometimes miss netpoll wake-ups, so skip it.
usleep(uint32(delay / 1000))

// non-blocking poll if no other M polling, not polled for more than 2ms and there is any waiter.
lastpoll := int64(atomic.Load64(&sched.lastpoll))
if lastpoll != 0 && lastpoll+2*1000*1000 < now && atomic.Load(&netpollWaiters) > 0 {
atomic.Cas64(&sched.lastpoll, uint64(lastpoll), uint64(now))
list := netpoll(0) // non-blocking - returns list of goroutines
if !list.empty() {
// Need to decrement number of idle locked M's
// (pretending that one more is running) before injectglist.
// Otherwise it can lead to the following situation:
// injectglist grabs all P's but before it starts M's to run the P's,
// another M returns from syscall, finishes running its G,
// observes that there is no work to do and no other running M's
// and reports deadlock.
incidlelocked(-1)
injectglist(&list)
incidlelocked(1)
}
}
} else {
// poll network until earliest timer, next retake or next schedtrace, may blocking.
sleep := delay
pollUntil, _ := timeSleepUntil()
if nexttrace < pollUntil {
pollUntil = nexttrace
}
if pollUntil-now < sleep {
sleep = pollUntil - now
}
if sleep < 0 || faketime != 0 {
sleep = 0
}
pollUntil = now + sleep

// sysmon pretends to be a normal M waiting for timer and IO ready.
// so need to decrement number of idle locked M's.
incidlelocked(-1)
if atomic.Xchg64(&sched.lastpoll, 0) != 0 {
atomic.Store64(&sched.pollUntil, uint64(pollUntil))
list := netpoll(sleep)
atomic.Store64(&sched.pollUntil, 0)
atomic.Store64(&sched.lastpoll, uint64(nanotime()))
if !list.empty() {
injectglist(&list)
} else {
// may wake up by timer.
wakep()
}
}
incidlelocked(1)
}
if GOOS == "netbsd" && needSysmonWorkaround {
// netpoll is responsible for waiting for timer
Expand Down Expand Up @@ -5182,8 +5227,8 @@ func sysmon() {
injectglist(&list)
unlock(&forcegc.lock)
}
if debug.schedtrace > 0 && lasttrace+int64(debug.schedtrace)*1000000 <= now {
lasttrace = now
if nexttrace <= now {
nexttrace += tracedelay
schedtrace(debug.scheddetail > 0)
}
unlock(&sched.sysmonlock)
Expand Down
156 changes: 156 additions & 0 deletions src/runtime/sysmon_test.go
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Test netpoll waiters G's will be unparked as soon as IO readied
// even though M's are busy with G's in local runq.

package runtime_test

import (
"net"
"runtime"
"testing"
"time"
)

type busysrv struct {
l net.Listener
bucket []int
bucketTotal int
exit chan struct{}
start, end time.Time
}

func (srv *busysrv) stop() {
close(srv.exit)
}

func (srv *busysrv) startListening() {
l, _ := net.Listen("tcp4", "localhost:0")
bucket := make([]int, 12)
exit := make(chan struct{})
srv.l = l
srv.bucket = bucket
srv.exit = exit
go func() {
for {
select {
case _, ok := <-exit:
if !ok {
l.Close()
return
}
default:
}

if con, _ := l.Accept(); con != nil {
con.Close()
}
}
}()
}

func (srv *busysrv) startDialing() {
srv.start = time.Now()
defer func() {
srv.end = time.Now()
}()
network, addr := srv.l.Addr().Network(), srv.l.Addr().String()
for {
select {
case _, ok := <-srv.exit:
if !ok {
return
}
default:
}

start := time.Now()
con, _ := net.Dial(network, addr)
ms := int(time.Since(start) / 1000000)
if ms >= len(srv.bucket) {
ms = len(srv.bucket) - 1
}
srv.bucket[ms]++
srv.bucketTotal++
if con != nil {
con.Close()
}
}
}

func (srv *busysrv) busy() {
for {
select {
case _, ok := <-srv.exit:
if !ok {
return
}
default:
}
runtime.Goyield() // simulate many runnable G's in local runq.
}
}

func (srv *busysrv) expect(bucket int, percent float64) bool {
count := 0
for i := 0; i < bucket && i < len(srv.bucket); i++ {
count += srv.bucket[i]
}
return float64(count)/float64(srv.bucketTotal)*100.0 > percent
}

func (srv *busysrv) printf(ffn func(format string, args ...interface{})) {
ffn("dialed %d times within %v", srv.bucketTotal, srv.end.Sub(srv.start))
ffn("timeBucket\tcount\tpercent")
for bucket, cnt := range srv.bucket {
percent := float64(cnt) / float64(srv.bucketTotal) * 100.0
if bucket == len(srv.bucket)-1 {
ffn("[%2d, ~)ms\t%d\t%.2f%%", bucket, cnt, percent)
} else {
ffn("[%2d,%2d)ms\t%d\t%.2f%%", bucket, bucket+1, cnt, percent)
}
}
}

func TestSysmonReadyNetpollWaitersASAP(t *testing.T) {
if runtime.GOOS == "netbsd" && runtime.NeedSysmonWorkaround {
t.Skip("netbsd 9.2 earlier")
}
if runtime.GOARCH == "wasm" {
t.Skip("no sysmon on wasm yet")
}
if runtime.GOOS == "openbsd" {
// usleep(20us) actually slept 20ms. see issue #17712.
t.Skip("sysmon may oversleep on openbsd.")
}

// sysmon may starve if host load is too high.
np := runtime.GOMAXPROCS(0)
if np >= runtime.NumCPU() {
t.Skip("host load may be too high to run sysmon.")
}

srv := &busysrv{}
srv.startListening()
for i := 0; i < np*5; i++ {
go srv.busy()
}
go srv.startDialing()

time.Sleep(time.Second)
srv.stop()
time.Sleep(time.Millisecond * 100)

// expect more than 80% dialings accomplished within 2ms in general.
// but android emulator may be slow, so more patience needed.
bucket, percent := 2, 80.0
if runtime.GOOS == "android" {
bucket = 9
}
if !srv.expect(bucket, percent) {
t.Fail()
}
srv.printf(t.Logf)
}

AltStyle によって変換されたページ (->オリジナル) /