| 1 |
// Copyright 2009 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 |
package runtime |
| 6 |
|
| 7 |
import ( |
| 8 |
"internal/goarch" |
| 9 |
"runtime/internal/atomic" |
| 10 |
"unsafe" |
| 11 |
) |
| 12 |
|
| 13 |
type mOS struct { |
| 14 |
// profileTimer holds the ID of the POSIX interval timer for profiling CPU |
| 15 |
// usage on this thread. |
| 16 |
// |
| 17 |
// It is valid when the profileTimerValid field is non-zero. A thread |
| 18 |
// creates and manages its own timer, and these fields are read and written |
| 19 |
// only by this thread. But because some of the reads on profileTimerValid |
| 20 |
// are in signal handling code, access to that field uses atomic operations. |
| 21 |
profileTimer int32 |
| 22 |
profileTimerValid uint32 |
| 23 |
} |
| 24 |
|
| 25 |
// setSigeventTID is written in C to set the sigev_notify_thread_id |
| 26 |
// field of a sigevent struct. |
| 27 |
// |
| 28 |
//go:noescape |
| 29 |
func setSigeventTID(*_sigevent, int32) |
| 30 |
|
| 31 |
func getProcID() uint64 { |
| 32 |
return uint64(gettid()) |
| 33 |
} |
| 34 |
|
| 35 |
func futex(addr unsafe.Pointer, op int32, val uint32, ts, addr2 unsafe.Pointer, val3 uint32) int32 { |
| 36 |
return int32(syscall(_SYS_futex, uintptr(addr), uintptr(op), uintptr(val), uintptr(ts), uintptr(addr2), uintptr(val3))) |
| 37 |
} |
| 38 |
|
| 39 |
// For sched_getaffinity use the system call rather than the libc call, |
| 40 |
// because the system call returns the number of entries set by the kernel. |
| 41 |
func sched_getaffinity(pid _pid_t, cpusetsize uintptr, mask *byte) int32 { |
| 42 |
return int32(syscall(_SYS_sched_getaffinity, uintptr(pid), cpusetsize, uintptr(unsafe.Pointer(mask)), 0, 0, 0)) |
| 43 |
} |
| 44 |
|
| 45 |
// Linux futex. |
| 46 |
// |
| 47 |
// futexsleep(uint32 *addr, uint32 val) |
| 48 |
// futexwakeup(uint32 *addr) |
| 49 |
// |
| 50 |
// Futexsleep atomically checks if *addr == val and if so, sleeps on addr. |
| 51 |
// Futexwakeup wakes up threads sleeping on addr. |
| 52 |
// Futexsleep is allowed to wake up spuriously. |
| 53 |
|
| 54 |
const ( |
| 55 |
_FUTEX_PRIVATE_FLAG = 128 |
| 56 |
_FUTEX_WAIT_PRIVATE = 0 | _FUTEX_PRIVATE_FLAG |
| 57 |
_FUTEX_WAKE_PRIVATE = 1 | _FUTEX_PRIVATE_FLAG |
| 58 |
) |
| 59 |
|
| 60 |
// Atomically, |
| 61 |
// |
| 62 |
// if(*addr == val) sleep |
| 63 |
// |
| 64 |
// Might be woken up spuriously; that's allowed. |
| 65 |
// Don't sleep longer than ns; ns < 0 means forever. |
| 66 |
// |
| 67 |
//go:nosplit |
| 68 |
func futexsleep(addr *uint32, val uint32, ns int64) { |
| 69 |
// Some Linux kernels have a bug where futex of |
| 70 |
// FUTEX_WAIT returns an internal error code |
| 71 |
// as an errno. Libpthread ignores the return value |
| 72 |
// here, and so can we: as it says a few lines up, |
| 73 |
// spurious wakeups are allowed. |
| 74 |
if ns < 0 { |
| 75 |
futex(unsafe.Pointer(addr), _FUTEX_WAIT_PRIVATE, val, nil, nil, 0) |
| 76 |
return |
| 77 |
} |
| 78 |
|
| 79 |
var ts timespec |
| 80 |
ts.setNsec(ns) |
| 81 |
futex(unsafe.Pointer(addr), _FUTEX_WAIT_PRIVATE, val, unsafe.Pointer(&ts), nil, 0) |
| 82 |
} |
| 83 |
|
| 84 |
// If any procs are sleeping on addr, wake up at most cnt. |
| 85 |
// |
| 86 |
//go:nosplit |
| 87 |
func futexwakeup(addr *uint32, cnt uint32) { |
| 88 |
ret := futex(unsafe.Pointer(addr), _FUTEX_WAKE_PRIVATE, cnt, nil, nil, 0) |
| 89 |
if ret >= 0 { |
| 90 |
return |
| 91 |
} |
| 92 |
|
| 93 |
// I don't know that futex wakeup can return |
| 94 |
// EAGAIN or EINTR, but if it does, it would be |
| 95 |
// safe to loop and call futex again. |
| 96 |
systemstack(func() { |
| 97 |
print("futexwakeup addr=", addr, " returned ", ret, "\n") |
| 98 |
}) |
| 99 |
|
| 100 |
*(*int32)(unsafe.Pointer(uintptr(0x1006))) = 0x1006 |
| 101 |
} |
| 102 |
|
| 103 |
func getproccount() int32 { |
| 104 |
// This buffer is huge (8 kB) but we are on the system stack |
| 105 |
// and there should be plenty of space (64 kB). |
| 106 |
// Also this is a leaf, so we're not holding up the memory for long. |
| 107 |
// See golang.org/issue/11823. |
| 108 |
// The suggested behavior here is to keep trying with ever-larger |
| 109 |
// buffers, but we don't have a dynamic memory allocator at the |
| 110 |
// moment, so that's a bit tricky and seems like overkill. |
| 111 |
const maxCPUs = 64 * 1024 |
| 112 |
var buf [maxCPUs / 8]byte |
| 113 |
r := sched_getaffinity(0, unsafe.Sizeof(buf), &buf[0]) |
| 114 |
if r < 0 { |
| 115 |
return 1 |
| 116 |
} |
| 117 |
n := int32(0) |
| 118 |
for _, v := range buf[:r] { |
| 119 |
for v != 0 { |
| 120 |
n += int32(v & 1) |
| 121 |
v >>= 1 |
| 122 |
} |
| 123 |
} |
| 124 |
if n == 0 { |
| 125 |
n = 1 |
| 126 |
} |
| 127 |
return n |
| 128 |
} |
| 129 |
|
| 130 |
const ( |
| 131 |
_AT_NULL = 0 // End of vector |
| 132 |
_AT_PAGESZ = 6 // System physical page size |
| 133 |
_AT_HWCAP = 16 // hardware capability bit vector |
| 134 |
_AT_RANDOM = 25 // introduced in 2.6.29 |
| 135 |
_AT_HWCAP2 = 26 // hardware capability bit vector 2 |
| 136 |
) |
| 137 |
|
| 138 |
var procAuxv = []byte("/proc/self/auxv\x00") |
| 139 |
|
| 140 |
var addrspace_vec [1]byte |
| 141 |
|
| 142 |
//extern-sysinfo mincore |
| 143 |
func mincore(addr unsafe.Pointer, n uintptr, dst *byte) int32 |
| 144 |
|
| 145 |
func sysargs(argc int32, argv **byte) { |
| 146 |
n := argc + 1 |
| 147 |
|
| 148 |
// skip over argv, envp to get to auxv |
| 149 |
for argv_index(argv, n) != nil { |
| 150 |
n++ |
| 151 |
} |
| 152 |
|
| 153 |
// skip NULL separator |
| 154 |
n++ |
| 155 |
|
| 156 |
// now argv+n is auxv |
| 157 |
auxv := (*[1 << 28]uintptr)(add(unsafe.Pointer(argv), uintptr(n)*goarch.PtrSize)) |
| 158 |
if sysauxv(auxv[:]) != 0 { |
| 159 |
return |
| 160 |
} |
| 161 |
// In some situations we don't get a loader-provided |
| 162 |
// auxv, such as when loaded as a library on Android. |
| 163 |
// Fall back to /proc/self/auxv. |
| 164 |
fd := open(&procAuxv[0], 0 /* O_RDONLY */, 0) |
| 165 |
if fd < 0 { |
| 166 |
// On Android, /proc/self/auxv might be unreadable (issue 9229), so we fallback to |
| 167 |
// try using mincore to detect the physical page size. |
| 168 |
// mincore should return EINVAL when address is not a multiple of system page size. |
| 169 |
const size = 256 << 10 // size of memory region to allocate |
| 170 |
p, err := mmap(nil, size, _PROT_READ|_PROT_WRITE, _MAP_ANON|_MAP_PRIVATE, -1, 0) |
| 171 |
if err != 0 { |
| 172 |
return |
| 173 |
} |
| 174 |
var n uintptr |
| 175 |
for n = 4 << 10; n < size; n <<= 1 { |
| 176 |
err := mincore(unsafe.Pointer(uintptr(p)+n), 1, &addrspace_vec[0]) |
| 177 |
if err == 0 { |
| 178 |
physPageSize = n |
| 179 |
break |
| 180 |
} |
| 181 |
} |
| 182 |
if physPageSize == 0 { |
| 183 |
physPageSize = size |
| 184 |
} |
| 185 |
munmap(p, size) |
| 186 |
return |
| 187 |
} |
| 188 |
var buf [128]uintptr |
| 189 |
n = read(fd, noescape(unsafe.Pointer(&buf[0])), int32(unsafe.Sizeof(buf))) |
| 190 |
closefd(fd) |
| 191 |
if n < 0 { |
| 192 |
return |
| 193 |
} |
| 194 |
// Make sure buf is terminated, even if we didn't read |
| 195 |
// the whole file. |
| 196 |
buf[len(buf)-2] = _AT_NULL |
| 197 |
sysauxv(buf[:]) |
| 198 |
} |
| 199 |
|
| 200 |
func sysauxv(auxv []uintptr) int { |
| 201 |
var i int |
| 202 |
for ; auxv[i] != _AT_NULL; i += 2 { |
| 203 |
tag, val := auxv[i], auxv[i+1] |
| 204 |
switch tag { |
| 205 |
case _AT_RANDOM: |
| 206 |
// The kernel provides a pointer to 16-bytes |
| 207 |
// worth of random data. |
| 208 |
startupRandomData = (*[16]byte)(unsafe.Pointer(val))[:] |
| 209 |
|
| 210 |
setRandomNumber(uint32(startupRandomData[4]) | uint32(startupRandomData[5])<<8 | |
| 211 |
uint32(startupRandomData[6])<<16 | uint32(startupRandomData[7])<<24) |
| 212 |
|
| 213 |
case _AT_PAGESZ: |
| 214 |
physPageSize = val |
| 215 |
} |
| 216 |
|
| 217 |
archauxv(tag, val) |
| 218 |
|
| 219 |
// Commented out for gccgo for now. |
| 220 |
// vdsoauxv(tag, val) |
| 221 |
} |
| 222 |
return i / 2 |
| 223 |
} |
| 224 |
|
| 225 |
var sysTHPSizePath = []byte("/sys/kernel/mm/transparent_hugepage/hpage_pmd_size\x00") |
| 226 |
|
| 227 |
func getHugePageSize() uintptr { |
| 228 |
var numbuf [20]byte |
| 229 |
fd := open(&sysTHPSizePath[0], 0 /* O_RDONLY */, 0) |
| 230 |
if fd < 0 { |
| 231 |
return 0 |
| 232 |
} |
| 233 |
ptr := noescape(unsafe.Pointer(&numbuf[0])) |
| 234 |
n := read(fd, ptr, int32(len(numbuf))) |
| 235 |
closefd(fd) |
| 236 |
if n <= 0 { |
| 237 |
return 0 |
| 238 |
} |
| 239 |
n-- // remove trailing newline |
| 240 |
v, ok := atoi(slicebytetostringtmp((*byte)(ptr), int(n))) |
| 241 |
if !ok || v < 0 { |
| 242 |
v = 0 |
| 243 |
} |
| 244 |
if v&(v-1) != 0 { |
| 245 |
// v is not a power of 2 |
| 246 |
return 0 |
| 247 |
} |
| 248 |
return uintptr(v) |
| 249 |
} |
| 250 |
|
| 251 |
func osinit() { |
| 252 |
ncpu = getproccount() |
| 253 |
physHugePageSize = getHugePageSize() |
| 254 |
} |
| 255 |
|
| 256 |
func timer_create(clockid int32, sevp *_sigevent, timerid *int32) int32 { |
| 257 |
return int32(syscall(_SYS_timer_create, uintptr(clockid), uintptr(unsafe.Pointer(sevp)), uintptr(unsafe.Pointer(timerid)), 0, 0, 0)) |
| 258 |
} |
| 259 |
|
| 260 |
func timer_settime(timerid int32, flags int32, new, old *_itimerspec) int32 { |
| 261 |
return int32(syscall(_SYS_timer_settime, uintptr(timerid), uintptr(flags), uintptr(unsafe.Pointer(new)), uintptr(unsafe.Pointer(old)), 0, 0)) |
| 262 |
} |
| 263 |
|
| 264 |
func timer_delete(timerid int32) int32 { |
| 265 |
return int32(syscall(_SYS_timer_delete, uintptr(timerid), 0, 0, 0, 0, 0)) |
| 266 |
} |
| 267 |
|
| 268 |
// go118UseTimerCreateProfiler enables the per-thread CPU profiler. |
| 269 |
const go118UseTimerCreateProfiler = true |
| 270 |
|
| 271 |
// validSIGPROF compares this signal delivery's code against the signal sources |
| 272 |
// that the profiler uses, returning whether the delivery should be processed. |
| 273 |
// To be processed, a signal delivery from a known profiling mechanism should |
| 274 |
// correspond to the best profiling mechanism available to this thread. Signals |
| 275 |
// from other sources are always considered valid. |
| 276 |
// |
| 277 |
//go:nosplit |
| 278 |
func validSIGPROF(mp *m, c *sigctxt) bool { |
| 279 |
code := int32(c.sigcode()) |
| 280 |
setitimer := code == _SI_KERNEL |
| 281 |
timer_create := code == _SI_TIMER |
| 282 |
|
| 283 |
if !(setitimer || timer_create) { |
| 284 |
// The signal doesn't correspond to a profiling mechanism that the |
| 285 |
// runtime enables itself. There's no reason to process it, but there's |
| 286 |
// no reason to ignore it either. |
| 287 |
return true |
| 288 |
} |
| 289 |
|
| 290 |
if mp == nil { |
| 291 |
// Since we don't have an M, we can't check if there's an active |
| 292 |
// per-thread timer for this thread. We don't know how long this thread |
| 293 |
// has been around, and if it happened to interact with the Go scheduler |
| 294 |
// at a time when profiling was active (causing it to have a per-thread |
| 295 |
// timer). But it may have never interacted with the Go scheduler, or |
| 296 |
// never while profiling was active. To avoid double-counting, process |
| 297 |
// only signals from setitimer. |
| 298 |
// |
| 299 |
// When a custom cgo traceback function has been registered (on |
| 300 |
// platforms that support runtime.SetCgoTraceback), SIGPROF signals |
| 301 |
// delivered to a thread that cannot find a matching M do this check in |
| 302 |
// the assembly implementations of runtime.cgoSigtramp. |
| 303 |
return setitimer |
| 304 |
} |
| 305 |
|
| 306 |
// Having an M means the thread interacts with the Go scheduler, and we can |
| 307 |
// check whether there's an active per-thread timer for this thread. |
| 308 |
if atomic.Load(&mp.profileTimerValid) != 0 { |
| 309 |
// If this M has its own per-thread CPU profiling interval timer, we |
| 310 |
// should track the SIGPROF signals that come from that timer (for |
| 311 |
// accurate reporting of its CPU usage; see issue 35057) and ignore any |
| 312 |
// that it gets from the process-wide setitimer (to not over-count its |
| 313 |
// CPU consumption). |
| 314 |
return timer_create |
| 315 |
} |
| 316 |
|
| 317 |
// No active per-thread timer means the only valid profiler is setitimer. |
| 318 |
return setitimer |
| 319 |
} |
| 320 |
|
| 321 |
func setProcessCPUProfiler(hz int32) { |
| 322 |
setProcessCPUProfilerTimer(hz) |
| 323 |
} |
| 324 |
|
| 325 |
func setThreadCPUProfiler(hz int32) { |
| 326 |
mp := getg().m |
| 327 |
mp.profilehz = hz |
| 328 |
|
| 329 |
if !go118UseTimerCreateProfiler { |
| 330 |
return |
| 331 |
} |
| 332 |
|
| 333 |
// destroy any active timer |
| 334 |
if atomic.Load(&mp.profileTimerValid) != 0 { |
| 335 |
timerid := mp.profileTimer |
| 336 |
atomic.Store(&mp.profileTimerValid, 0) |
| 337 |
mp.profileTimer = 0 |
| 338 |
|
| 339 |
ret := timer_delete(timerid) |
| 340 |
if ret != 0 { |
| 341 |
print("runtime: failed to disable profiling timer; timer_delete(", timerid, ") errno=", -ret, "\n") |
| 342 |
throw("timer_delete") |
| 343 |
} |
| 344 |
} |
| 345 |
|
| 346 |
if hz == 0 { |
| 347 |
// If the goal was to disable profiling for this thread, then the job's done. |
| 348 |
return |
| 349 |
} |
| 350 |
|
| 351 |
// The period of the timer should be 1/Hz. For every "1/Hz" of additional |
| 352 |
// work, the user should expect one additional sample in the profile. |
| 353 |
// |
| 354 |
// But to scale down to very small amounts of application work, to observe |
| 355 |
// even CPU usage of "one tenth" of the requested period, set the initial |
| 356 |
// timing delay in a different way: So that "one tenth" of a period of CPU |
| 357 |
// spend shows up as a 10% chance of one sample (for an expected value of |
| 358 |
// 0.1 samples), and so that "two and six tenths" periods of CPU spend show |
| 359 |
// up as a 60% chance of 3 samples and a 40% chance of 2 samples (for an |
| 360 |
// expected value of 2.6). Set the initial delay to a value in the unifom |
| 361 |
// random distribution between 0 and the desired period. And because "0" |
| 362 |
// means "disable timer", add 1 so the half-open interval [0,period) turns |
| 363 |
// into (0,period]. |
| 364 |
// |
| 365 |
// Otherwise, this would show up as a bias away from short-lived threads and |
| 366 |
// from threads that are only occasionally active: for example, when the |
| 367 |
// garbage collector runs on a mostly-idle system, the additional threads it |
| 368 |
// activates may do a couple milliseconds of GC-related work and nothing |
| 369 |
// else in the few seconds that the profiler observes. |
| 370 |
spec := new(_itimerspec) |
| 371 |
spec.it_value.setNsec(1 + int64(fastrandn(uint32(1e9/hz)))) |
| 372 |
spec.it_interval.setNsec(1e9 / int64(hz)) |
| 373 |
|
| 374 |
var timerid int32 |
| 375 |
var sevp _sigevent |
| 376 |
sevp.sigev_notify = _SIGEV_THREAD_ID |
| 377 |
sevp.sigev_signo = _SIGPROF |
| 378 |
setSigeventTID(&sevp, int32(mp.procid)) |
| 379 |
ret := timer_create(_CLOCK_THREAD_CPUTIME_ID, &sevp, &timerid) |
| 380 |
if ret != 0 { |
| 381 |
// If we cannot create a timer for this M, leave profileTimerValid false |
| 382 |
// to fall back to the process-wide setitimer profiler. |
| 383 |
return |
| 384 |
} |
| 385 |
|
| 386 |
ret = timer_settime(timerid, 0, spec, nil) |
| 387 |
if ret != 0 { |
| 388 |
print("runtime: failed to configure profiling timer; timer_settime(", timerid, |
| 389 |
", 0, {interval: {", |
| 390 |
spec.it_interval.tv_sec, "s + ", spec.it_interval.tv_nsec, "ns} value: {", |
| 391 |
spec.it_value.tv_sec, "s + ", spec.it_value.tv_nsec, "ns}}, nil) errno=", -ret, "\n") |
| 392 |
throw("timer_settime") |
| 393 |
} |
| 394 |
|
| 395 |
mp.profileTimer = timerid |
| 396 |
atomic.Store(&mp.profileTimerValid, 1) |
| 397 |
} |