From fb1d285d4184fd6f36c0d4cb5811367951c10149 Mon Sep 17 00:00:00 2001 From: Tao Qingyun Date: Mon, 21 Jun 2021 09:26:43 +0800 Subject: [PATCH] runtime: make ncgocall a global counter ncgocall was stored per M, runtime.NumCgoCall lost the counter when a M die. Fixes #46789 --- src/runtime/cgocall.go | 4 ++-- src/runtime/debug.go | 8 ++++++-- src/runtime/proc.go | 1 + src/runtime/runtime2.go | 1 + 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/runtime/cgocall.go b/src/runtime/cgocall.go index 1dc5b415fb..8ffb48a888 100644 --- a/src/runtime/cgocall.go +++ b/src/runtime/cgocall.go @@ -110,7 +110,7 @@ func syscall_cgocaller(fn unsafe.Pointer, args ...uintptr) uintptr { return as.retval } -var ncgocall uint64 // number of cgo calls in total +var ncgocall uint64 // number of cgo calls in total for dead m // Call from Go to C. // @@ -132,8 +132,8 @@ func cgocall(fn, arg unsafe.Pointer) int32 { racereleasemerge(unsafe.Pointer(&racecgosync)) } - atomic.Xadd64(&ncgocall, 1) mp := getg().m + mp.ncgocall++ mp.ncgo++ // Reset traceback. diff --git a/src/runtime/debug.go b/src/runtime/debug.go index 45cfa6ed08..fd6cbd484e 100644 --- a/src/runtime/debug.go +++ b/src/runtime/debug.go @@ -6,7 +6,7 @@ package runtime import ( "runtime/internal/atomic" - _ "unsafe" + "unsafe" ) // GOMAXPROCS sets the maximum number of CPUs that can be executing @@ -45,7 +45,11 @@ func NumCPU() int { // NumCgoCall returns the number of cgo calls made by the current process. func NumCgoCall() int64 { - return int64(atomic.Load64(&ncgocall)) + var n = int64(ncgocall) + for mp := (*m)(atomic.Loadp(unsafe.Pointer(&allm))); mp != nil; mp = mp.alllink { + n += int64(mp.ncgocall) + } + return n } // NumGoroutine returns the number of goroutines that currently exist. diff --git a/src/runtime/proc.go b/src/runtime/proc.go index 8f1a443945..c4dc8717b0 100644 --- a/src/runtime/proc.go +++ b/src/runtime/proc.go @@ -1507,6 +1507,7 @@ func mexit(osStack bool) { } throw("m not found in allm") found: + ncgocall += m.ncgocall if !osStack { // Delay reaping m until it's done with the stack. // diff --git a/src/runtime/runtime2.go b/src/runtime/runtime2.go index 541a55b35d..0e0eb0b728 100644 --- a/src/runtime/runtime2.go +++ b/src/runtime/runtime2.go @@ -541,6 +541,7 @@ type m struct { fastrand [2]uint32 needextram bool traceback uint8 + ncgocall uint64 // number of cgo calls in total ncgo int32 // number of cgo calls currently in progress cgoCallersUse uint32 // if non-zero, cgoCallers in use temporarily cgoCallers *cgoCallers // cgo traceback if crashing in cgo call