Debian Codegraph @

src/runtime/os_linux.go

raw
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/abi"
9 "internal/goarch"
10 "internal/runtime/atomic"
11 "internal/runtime/strconv"
12 "internal/runtime/syscall"
13 "unsafe"
14 )
15
16 // sigPerThreadSyscall is the same signal (SIGSETXID) used by glibc for
17 // per-thread syscalls on Linux. We use it for the same purpose in non-cgo
18 // binaries.
19 const sigPerThreadSyscall = _SIGRTMIN + 1
20
21 type mOS struct {
22 // profileTimer holds the ID of the POSIX interval timer for profiling CPU
23 // usage on this thread.
24 //
25 // It is valid when the profileTimerValid field is true. A thread
26 // creates and manages its own timer, and these fields are read and written
27 // only by this thread. But because some of the reads on profileTimerValid
28 // are in signal handling code, this field should be atomic type.
29 profileTimer int32
30 profileTimerValid atomic.Bool
31
32 // needPerThreadSyscall indicates that a per-thread syscall is required
33 // for doAllThreadsSyscall.
34 needPerThreadSyscall atomic.Uint8
35
36 // This is a pointer to a chunk of memory allocated with a special
37 // mmap invocation in vgetrandomGetState().
38 vgetrandomState uintptr
39
40 waitsema uint32 // semaphore for parking on locks
41 }
42
43 //go:noescape
44 func futex(addr unsafe.Pointer, op int32, val uint32, ts, addr2 unsafe.Pointer, val3 uint32) int32
45
46 // Linux futex.
47 //
48 // futexsleep(uint32 *addr, uint32 val)
49 // futexwakeup(uint32 *addr)
50 //
51 // Futexsleep atomically checks if *addr == val and if so, sleeps on addr.
52 // Futexwakeup wakes up threads sleeping on addr.
53 // Futexsleep is allowed to wake up spuriously.
54
55 const (
56 _FUTEX_PRIVATE_FLAG = 128
57 _FUTEX_WAIT_PRIVATE = 0 | _FUTEX_PRIVATE_FLAG
58 _FUTEX_WAKE_PRIVATE = 1 | _FUTEX_PRIVATE_FLAG
59 )
60
61 // Atomically,
62 //
63 // if(*addr == val) sleep
64 //
65 // Might be woken up spuriously; that's allowed.
66 // Don't sleep longer than ns; ns < 0 means forever.
67 //
68 //go:nosplit
69 func futexsleep(addr *uint32, val uint32, ns int64) {
70 // Some Linux kernels have a bug where futex of
71 // FUTEX_WAIT returns an internal error code
72 // as an errno. Libpthread ignores the return value
73 // here, and so can we: as it says a few lines up,
74 // spurious wakeups are allowed.
75 if ns < 0 {
76 futex(unsafe.Pointer(addr), _FUTEX_WAIT_PRIVATE, val, nil, nil, 0)
77 return
78 }
79
80 var ts timespec
81 ts.setNsec(ns)
82 futex(unsafe.Pointer(addr), _FUTEX_WAIT_PRIVATE, val, unsafe.Pointer(&ts), nil, 0)
83 }
84
85 // If any procs are sleeping on addr, wake up at most cnt.
86 //
87 //go:nosplit
88 func futexwakeup(addr *uint32, cnt uint32) {
89 ret := futex(unsafe.Pointer(addr), _FUTEX_WAKE_PRIVATE, cnt, nil, nil, 0)
90 if ret >= 0 {
91 return
92 }
93
94 // I don't know that futex wakeup can return
95 // EAGAIN or EINTR, but if it does, it would be
96 // safe to loop and call futex again.
97 systemstack(func() {
98 print("futexwakeup addr=", addr, " returned ", ret, "\n")
99 })
100
101 *(*int32)(unsafe.Pointer(uintptr(0x1006))) = 0x1006
102 }
103
104 func getCPUCount() int32 {
105 // This buffer is huge (8 kB) but we are on the system stack
106 // and there should be plenty of space (64 kB).
107 // Also this is a leaf, so we're not holding up the memory for long.
108 // See golang.org/issue/11823.
109 // The suggested behavior here is to keep trying with ever-larger
110 // buffers, but we don't have a dynamic memory allocator at the
111 // moment, so that's a bit tricky and seems like overkill.
112 const maxCPUs = 64 * 1024
113 var buf [maxCPUs / 8]byte
114 r := sched_getaffinity(0, unsafe.Sizeof(buf), &buf[0])
115 if r < 0 {
116 return 1
117 }
118 n := int32(0)
119 for _, v := range buf[:r] {
120 for v != 0 {
121 n += int32(v & 1)
122 v >>= 1
123 }
124 }
125 if n == 0 {
126 n = 1
127 }
128 return n
129 }
130
131 // Clone, the Linux rfork.
132 const (
133 _CLONE_VM = 0x100
134 _CLONE_FS = 0x200
135 _CLONE_FILES = 0x400
136 _CLONE_SIGHAND = 0x800
137 _CLONE_PTRACE = 0x2000
138 _CLONE_VFORK = 0x4000
139 _CLONE_PARENT = 0x8000
140 _CLONE_THREAD = 0x10000
141 _CLONE_NEWNS = 0x20000
142 _CLONE_SYSVSEM = 0x40000
143 _CLONE_SETTLS = 0x80000
144 _CLONE_PARENT_SETTID = 0x100000
145 _CLONE_CHILD_CLEARTID = 0x200000
146 _CLONE_UNTRACED = 0x800000
147 _CLONE_CHILD_SETTID = 0x1000000
148 _CLONE_STOPPED = 0x2000000
149 _CLONE_NEWUTS = 0x4000000
150 _CLONE_NEWIPC = 0x8000000
151
152 // As of QEMU 2.8.0 (5ea2fc84d), user emulation requires all six of these
153 // flags to be set when creating a thread; attempts to share the other
154 // five but leave SYSVSEM unshared will fail with -EINVAL.
155 //
156 // In non-QEMU environments CLONE_SYSVSEM is inconsequential as we do not
157 // use System V semaphores.
158
159 cloneFlags = _CLONE_VM | /* share memory */
160 _CLONE_FS | /* share cwd, etc */
161 _CLONE_FILES | /* share fd table */
162 _CLONE_SIGHAND | /* share sig handler table */
163 _CLONE_SYSVSEM | /* share SysV semaphore undo lists (see issue #20763) */
164 _CLONE_THREAD /* revisit - okay for now */
165 )
166
167 //go:noescape
168 func clone(flags int32, stk, mp, gp, fn unsafe.Pointer) int32
169
170 // May run with m.p==nil, so write barriers are not allowed.
171 //
172 //go:nowritebarrier
173 func newosproc(mp *m) {
174 stk := unsafe.Pointer(mp.g0.stack.hi)
175 /*
176 * note: strace gets confused if we use CLONE_PTRACE here.
177 */
178 if false {
179 print("newosproc stk=", stk, " m=", mp, " g=", mp.g0, " clone=", abi.FuncPCABI0(clone), " id=", mp.id, " ostk=", &mp, "\n")
180 }
181
182 // Disable signals during clone, so that the new thread starts
183 // with signals disabled. It will enable them in minit.
184 var oset sigset
185 sigprocmask(_SIG_SETMASK, &sigset_all, &oset)
186 ret := retryOnEAGAIN(func() int32 {
187 r := clone(cloneFlags, stk, unsafe.Pointer(mp), unsafe.Pointer(mp.g0), unsafe.Pointer(abi.FuncPCABI0(mstart)))
188 // clone returns positive TID, negative errno.
189 // We don't care about the TID.
190 if r >= 0 {
191 return 0
192 }
193 return -r
194 })
195 sigprocmask(_SIG_SETMASK, &oset, nil)
196
197 if ret != 0 {
198 print("runtime: failed to create new OS thread (have ", mcount(), " already; errno=", ret, ")\n")
199 if ret == _EAGAIN {
200 println("runtime: may need to increase max user processes (ulimit -u)")
201 }
202 throw("newosproc")
203 }
204 }
205
206 // Version of newosproc that doesn't require a valid G.
207 //
208 //go:nosplit
209 func newosproc0(stacksize uintptr, fn unsafe.Pointer) {
210 stack := sysAlloc(stacksize, &memstats.stacks_sys, "OS thread stack")
211 if stack == nil {
212 writeErrStr(failallocatestack)
213 exit(1)
214 }
215 ret := clone(cloneFlags, unsafe.Pointer(uintptr(stack)+stacksize), nil, nil, fn)
216 if ret < 0 {
217 writeErrStr(failthreadcreate)
218 exit(1)
219 }
220 }
221
222 const (
223 _AT_NULL = 0 // End of vector
224 _AT_PAGESZ = 6 // System physical page size
225 _AT_PLATFORM = 15 // string identifying platform
226 _AT_HWCAP = 16 // hardware capability bit vector
227 _AT_SECURE = 23 // secure mode boolean
228 _AT_RANDOM = 25 // introduced in 2.6.29
229 _AT_HWCAP2 = 26 // hardware capability bit vector 2
230 )
231
232 var procAuxv = []byte("/proc/self/auxv\x00")
233
234 var addrspace_vec [1]byte
235
236 func mincore(addr unsafe.Pointer, n uintptr, dst *byte) int32
237
238 var auxvreadbuf [128]uintptr
239
240 func sysargs(argc int32, argv **byte) {
241 n := argc + 1
242
243 // skip over argv, envp to get to auxv
244 for argv_index(argv, n) != nil {
245 n++
246 }
247
248 // skip NULL separator
249 n++
250
251 // now argv+n is auxv
252 auxvp := (*[1 << 28]uintptr)(add(unsafe.Pointer(argv), uintptr(n)*goarch.PtrSize))
253
254 if pairs := sysauxv(auxvp[:]); pairs != 0 {
255 auxv = auxvp[: pairs*2 : pairs*2]
256 return
257 }
258 // In some situations we don't get a loader-provided
259 // auxv, such as when loaded as a library on Android.
260 // Fall back to /proc/self/auxv.
261 fd := open(&procAuxv[0], 0 /* O_RDONLY */, 0)
262 if fd < 0 {
263 // On Android, /proc/self/auxv might be unreadable (issue 9229), so we fallback to
264 // try using mincore to detect the physical page size.
265 // mincore should return EINVAL when address is not a multiple of system page size.
266 const size = 256 << 10 // size of memory region to allocate
267 p, err := mmap(nil, size, _PROT_READ|_PROT_WRITE, _MAP_ANON|_MAP_PRIVATE, -1, 0)
268 if err != 0 {
269 return
270 }
271 var n uintptr
272 for n = 4 << 10; n < size; n <<= 1 {
273 err := mincore(unsafe.Pointer(uintptr(p)+n), 1, &addrspace_vec[0])
274 if err == 0 {
275 physPageSize = n
276 break
277 }
278 }
279 if physPageSize == 0 {
280 physPageSize = size
281 }
282 munmap(p, size)
283 return
284 }
285
286 n = read(fd, noescape(unsafe.Pointer(&auxvreadbuf[0])), int32(unsafe.Sizeof(auxvreadbuf)))
287 closefd(fd)
288 if n < 0 {
289 return
290 }
291 // Make sure buf is terminated, even if we didn't read
292 // the whole file.
293 auxvreadbuf[len(auxvreadbuf)-2] = _AT_NULL
294 pairs := sysauxv(auxvreadbuf[:])
295 auxv = auxvreadbuf[: pairs*2 : pairs*2]
296 }
297
298 // secureMode holds the value of AT_SECURE passed in the auxiliary vector.
299 var secureMode bool
300
301 func sysauxv(auxv []uintptr) (pairs int) {
302 // Process the auxiliary vector entries provided by the kernel when the
303 // program is executed. See getauxval(3).
304 var i int
305 for ; auxv[i] != _AT_NULL; i += 2 {
306 tag, val := auxv[i], auxv[i+1]
307 switch tag {
308 case _AT_RANDOM:
309 // The kernel provides a pointer to 16 bytes of cryptographically
310 // random data. Note that in cgo programs this value may have
311 // already been used by libc at this point, and in particular glibc
312 // and musl use the value as-is for stack and pointer protector
313 // cookies from libc_start_main and/or dl_start. Also, cgo programs
314 // may use the value after we do.
315 startupRand = (*[16]byte)(unsafe.Pointer(val))[:]
316
317 case _AT_PAGESZ:
318 physPageSize = val
319
320 case _AT_SECURE:
321 secureMode = val == 1
322 }
323
324 archauxv(tag, val)
325 vdsoauxv(tag, val)
326 }
327 return i / 2
328 }
329
330 var sysTHPSizePath = []byte("/sys/kernel/mm/transparent_hugepage/hpage_pmd_size\x00")
331
332 func getHugePageSize() uintptr {
333 var numbuf [20]byte
334 fd := open(&sysTHPSizePath[0], 0 /* O_RDONLY */, 0)
335 if fd < 0 {
336 return 0
337 }
338 ptr := noescape(unsafe.Pointer(&numbuf[0]))
339 n := read(fd, ptr, int32(len(numbuf)))
340 closefd(fd)
341 if n <= 0 {
342 return 0
343 }
344 n-- // remove trailing newline
345 v, ok := strconv.Atoi(slicebytetostringtmp((*byte)(ptr), int(n)))
346 if !ok || v < 0 {
347 v = 0
348 }
349 if v&(v-1) != 0 {
350 // v is not a power of 2
351 return 0
352 }
353 return uintptr(v)
354 }
355
356 func osinit() {
357 numCPUStartup = getCPUCount()
358 physHugePageSize = getHugePageSize()
359 osArchInit()
360 vgetrandomInit()
361 }
362
363 var urandom_dev = []byte("/dev/urandom\x00")
364
365 func readRandom(r []byte) int {
366 // Note that all supported Linux kernels should provide AT_RANDOM which
367 // populates startupRand, so this fallback should be unreachable.
368 fd := open(&urandom_dev[0], 0 /* O_RDONLY */, 0)
369 n := read(fd, unsafe.Pointer(&r[0]), int32(len(r)))
370 closefd(fd)
371 return int(n)
372 }
373
374 func goenvs() {
375 goenvs_unix()
376 }
377
378 // Called to do synchronous initialization of Go code built with
379 // -buildmode=c-archive or -buildmode=c-shared.
380 // None of the Go runtime is initialized.
381 //
382 //go:nosplit
383 //go:nowritebarrierrec
384 func libpreinit() {
385 initsig(true)
386 }
387
388 // Called to initialize a new m (including the bootstrap m).
389 // Called on the parent thread (main thread in case of bootstrap), can allocate memory.
390 func mpreinit(mp *m) {
391 mp.gsignal = malg(32 * 1024) // Linux wants >= 2K
392 mp.gsignal.m = mp
393 }
394
395 func gettid() uint32
396
397 // Called to initialize a new m (including the bootstrap m).
398 // Called on the new thread, cannot allocate memory.
399 func minit() {
400 minitSignals()
401
402 // Cgo-created threads and the bootstrap m are missing a
403 // procid. We need this for asynchronous preemption and it's
404 // useful in debuggers.
405 getg().m.procid = uint64(gettid())
406 }
407
408 // Called from dropm to undo the effect of an minit.
409 //
410 //go:nosplit
411 func unminit() {
412 unminitSignals()
413 getg().m.procid = 0
414 }
415
416 // Called from mexit, but not from dropm, to undo the effect of thread-owned
417 // resources in minit, semacreate, or elsewhere. Do not take locks after calling this.
418 //
419 // This always runs without a P, so //go:nowritebarrierrec is required.
420 //
421 //go:nowritebarrierrec
422 func mdestroy(mp *m) {
423 }
424
425 // #ifdef GOARCH_386
426 // #define sa_handler k_sa_handler
427 // #endif
428
429 func sigreturn__sigaction()
430 func sigtramp() // Called via C ABI
431 func cgoSigtramp()
432
433 //go:noescape
434 func sigaltstack(new, old *stackt)
435
436 //go:noescape
437 func setitimer(mode int32, new, old *itimerval)
438
439 //go:noescape
440 func timer_create(clockid int32, sevp *sigevent, timerid *int32) int32
441
442 //go:noescape
443 func timer_settime(timerid int32, flags int32, new, old *itimerspec) int32
444
445 //go:noescape
446 func timer_delete(timerid int32) int32
447
448 //go:noescape
449 func rtsigprocmask(how int32, new, old *sigset, size int32)
450
451 //go:nosplit
452 //go:nowritebarrierrec
453 func sigprocmask(how int32, new, old *sigset) {
454 rtsigprocmask(how, new, old, int32(unsafe.Sizeof(*new)))
455 }
456
457 func raise(sig uint32)
458 func raiseproc(sig uint32)
459
460 //go:noescape
461 func sched_getaffinity(pid, len uintptr, buf *byte) int32
462 func osyield()
463
464 //go:nosplit
465 func osyield_no_g() {
466 osyield()
467 }
468
469 func pipe2(flags int32) (r, w int32, errno int32)
470
471 //go:nosplit
472 func fcntl(fd, cmd, arg int32) (ret int32, errno int32) {
473 r, _, err := syscall.Syscall6(syscall.SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg), 0, 0, 0)
474 return int32(r), int32(err)
475 }
476
477 const (
478 _si_max_size = 128
479 _sigev_max_size = 64
480 )
481
482 //go:nosplit
483 //go:nowritebarrierrec
484 func setsig(i uint32, fn uintptr) {
485 var sa sigactiont
486 sa.sa_flags = _SA_SIGINFO | _SA_ONSTACK | _SA_RESTORER | _SA_RESTART
487 sigfillset(&sa.sa_mask)
488 // Although Linux manpage says "sa_restorer element is obsolete and
489 // should not be used". x86_64 kernel requires it. Only use it on
490 // x86.
491 if GOARCH == "386" || GOARCH == "amd64" {
492 sa.sa_restorer = abi.FuncPCABI0(sigreturn__sigaction)
493 }
494 if fn == abi.FuncPCABIInternal(sighandler) { // abi.FuncPCABIInternal(sighandler) matches the callers in signal_unix.go
495 if iscgo {
496 fn = abi.FuncPCABI0(cgoSigtramp)
497 } else {
498 fn = abi.FuncPCABI0(sigtramp)
499 }
500 }
501 sa.sa_handler = fn
502 sigaction(i, &sa, nil)
503 }
504
505 //go:nosplit
506 //go:nowritebarrierrec
507 func setsigstack(i uint32) {
508 var sa sigactiont
509 sigaction(i, nil, &sa)
510 if sa.sa_flags&_SA_ONSTACK != 0 {
511 return
512 }
513 sa.sa_flags |= _SA_ONSTACK
514 sigaction(i, &sa, nil)
515 }
516
517 //go:nosplit
518 //go:nowritebarrierrec
519 func getsig(i uint32) uintptr {
520 var sa sigactiont
521 sigaction(i, nil, &sa)
522 return sa.sa_handler
523 }
524
525 // setSignalstackSP sets the ss_sp field of a stackt.
526 //
527 //go:nosplit
528 func setSignalstackSP(s *stackt, sp uintptr) {
529 *(*uintptr)(unsafe.Pointer(&s.ss_sp)) = sp
530 }
531
532 //go:nosplit
533 func (c *sigctxt) fixsigcode(sig uint32) {
534 }
535
536 // sysSigaction calls the rt_sigaction system call.
537 //
538 //go:nosplit
539 func sysSigaction(sig uint32, new, old *sigactiont) {
540 if rt_sigaction(uintptr(sig), new, old, unsafe.Sizeof(sigactiont{}.sa_mask)) != 0 {
541 // Workaround for bugs in QEMU user mode emulation.
542 //
543 // QEMU turns calls to the sigaction system call into
544 // calls to the C library sigaction call; the C
545 // library call rejects attempts to call sigaction for
546 // SIGCANCEL (32) or SIGSETXID (33).
547 //
548 // QEMU rejects calling sigaction on SIGRTMAX (64).
549 //
550 // Just ignore the error in these case. There isn't
551 // anything we can do about it anyhow.
552 if sig != 32 && sig != 33 && sig != 64 {
553 // Use system stack to avoid split stack overflow on ppc64/ppc64le.
554 systemstack(func() {
555 throw("sigaction failed")
556 })
557 }
558 }
559 }
560
561 // rt_sigaction is implemented in assembly.
562 //
563 //go:noescape
564 func rt_sigaction(sig uintptr, new, old *sigactiont, size uintptr) int32
565
566 func getpid() int
567 func tgkill(tgid, tid, sig int)
568
569 // signalM sends a signal to mp.
570 func signalM(mp *m, sig int) {
571 tgkill(getpid(), int(mp.procid), sig)
572 }
573
574 // validSIGPROF compares this signal delivery's code against the signal sources
575 // that the profiler uses, returning whether the delivery should be processed.
576 // To be processed, a signal delivery from a known profiling mechanism should
577 // correspond to the best profiling mechanism available to this thread. Signals
578 // from other sources are always considered valid.
579 //
580 //go:nosplit
581 func validSIGPROF(mp *m, c *sigctxt) bool {
582 code := int32(c.sigcode())
583 setitimer := code == _SI_KERNEL
584 timer_create := code == _SI_TIMER
585
586 if !(setitimer || timer_create) {
587 // The signal doesn't correspond to a profiling mechanism that the
588 // runtime enables itself. There's no reason to process it, but there's
589 // no reason to ignore it either.
590 return true
591 }
592
593 if mp == nil {
594 // Since we don't have an M, we can't check if there's an active
595 // per-thread timer for this thread. We don't know how long this thread
596 // has been around, and if it happened to interact with the Go scheduler
597 // at a time when profiling was active (causing it to have a per-thread
598 // timer). But it may have never interacted with the Go scheduler, or
599 // never while profiling was active. To avoid double-counting, process
600 // only signals from setitimer.
601 //
602 // When a custom cgo traceback function has been registered (on
603 // platforms that support runtime.SetCgoTraceback), SIGPROF signals
604 // delivered to a thread that cannot find a matching M do this check in
605 // the assembly implementations of runtime.cgoSigtramp.
606 return setitimer
607 }
608
609 // Having an M means the thread interacts with the Go scheduler, and we can
610 // check whether there's an active per-thread timer for this thread.
611 if mp.profileTimerValid.Load() {
612 // If this M has its own per-thread CPU profiling interval timer, we
613 // should track the SIGPROF signals that come from that timer (for
614 // accurate reporting of its CPU usage; see issue 35057) and ignore any
615 // that it gets from the process-wide setitimer (to not over-count its
616 // CPU consumption).
617 return timer_create
618 }
619
620 // No active per-thread timer means the only valid profiler is setitimer.
621 return setitimer
622 }
623
624 func setProcessCPUProfiler(hz int32) {
625 setProcessCPUProfilerTimer(hz)
626 }
627
628 func setThreadCPUProfiler(hz int32) {
629 mp := getg().m
630 mp.profilehz = hz
631
632 // destroy any active timer
633 if mp.profileTimerValid.Load() {
634 timerid := mp.profileTimer
635 mp.profileTimerValid.Store(false)
636 mp.profileTimer = 0
637
638 ret := timer_delete(timerid)
639 if ret != 0 {
640 print("runtime: failed to disable profiling timer; timer_delete(", timerid, ") errno=", -ret, "\n")
641 throw("timer_delete")
642 }
643 }
644
645 if hz == 0 {
646 // If the goal was to disable profiling for this thread, then the job's done.
647 return
648 }
649
650 // The period of the timer should be 1/Hz. For every "1/Hz" of additional
651 // work, the user should expect one additional sample in the profile.
652 //
653 // But to scale down to very small amounts of application work, to observe
654 // even CPU usage of "one tenth" of the requested period, set the initial
655 // timing delay in a different way: So that "one tenth" of a period of CPU
656 // spend shows up as a 10% chance of one sample (for an expected value of
657 // 0.1 samples), and so that "two and six tenths" periods of CPU spend show
658 // up as a 60% chance of 3 samples and a 40% chance of 2 samples (for an
659 // expected value of 2.6). Set the initial delay to a value in the uniform
660 // random distribution between 0 and the desired period. And because "0"
661 // means "disable timer", add 1 so the half-open interval [0,period) turns
662 // into (0,period].
663 //
664 // Otherwise, this would show up as a bias away from short-lived threads and
665 // from threads that are only occasionally active: for example, when the
666 // garbage collector runs on a mostly-idle system, the additional threads it
667 // activates may do a couple milliseconds of GC-related work and nothing
668 // else in the few seconds that the profiler observes.
669 spec := new(itimerspec)
670 spec.it_value.setNsec(1 + int64(cheaprandn(uint32(1e9/hz))))
671 spec.it_interval.setNsec(1e9 / int64(hz))
672
673 var timerid int32
674 var sevp sigevent
675 sevp.notify = _SIGEV_THREAD_ID
676 sevp.signo = _SIGPROF
677 sevp.sigev_notify_thread_id = int32(mp.procid)
678 ret := timer_create(_CLOCK_THREAD_CPUTIME_ID, &sevp, &timerid)
679 if ret != 0 {
680 // If we cannot create a timer for this M, leave profileTimerValid false
681 // to fall back to the process-wide setitimer profiler.
682 return
683 }
684
685 ret = timer_settime(timerid, 0, spec, nil)
686 if ret != 0 {
687 print("runtime: failed to configure profiling timer; timer_settime(", timerid,
688 ", 0, {interval: {",
689 spec.it_interval.tv_sec, "s + ", spec.it_interval.tv_nsec, "ns} value: {",
690 spec.it_value.tv_sec, "s + ", spec.it_value.tv_nsec, "ns}}, nil) errno=", -ret, "\n")
691 throw("timer_settime")
692 }
693
694 mp.profileTimer = timerid
695 mp.profileTimerValid.Store(true)
696 }
697
698 // perThreadSyscallArgs contains the system call number, arguments, and
699 // expected return values for a system call to be executed on all threads.
700 type perThreadSyscallArgs struct {
701 trap uintptr
702 a1 uintptr
703 a2 uintptr
704 a3 uintptr
705 a4 uintptr
706 a5 uintptr
707 a6 uintptr
708 r1 uintptr
709 r2 uintptr
710 }
711
712 // perThreadSyscall is the system call to execute for the ongoing
713 // doAllThreadsSyscall.
714 //
715 // perThreadSyscall may only be written while mp.needPerThreadSyscall == 0 on
716 // all Ms.
717 var perThreadSyscall perThreadSyscallArgs
718
719 // syscall_runtime_doAllThreadsSyscall and executes a specified system call on
720 // all Ms.
721 //
722 // The system call is expected to succeed and return the same value on every
723 // thread. If any threads do not match, the runtime throws.
724 //
725 //go:linkname syscall_runtime_doAllThreadsSyscall syscall.runtime_doAllThreadsSyscall
726 //go:uintptrescapes
727 func syscall_runtime_doAllThreadsSyscall(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr) {
728 if iscgo {
729 // In cgo, we are not aware of threads created in C, so this approach will not work.
730 panic("doAllThreadsSyscall not supported with cgo enabled")
731 }
732
733 // STW to guarantee that user goroutines see an atomic change to thread
734 // state. Without STW, goroutines could migrate Ms while change is in
735 // progress and e.g., see state old -> new -> old -> new.
736 //
737 // N.B. Internally, this function does not depend on STW to
738 // successfully change every thread. It is only needed for user
739 // expectations, per above.
740 stw := stopTheWorld(stwAllThreadsSyscall)
741
742 // This function depends on several properties:
743 //
744 // 1. All OS threads that already exist are associated with an M in
745 // allm. i.e., we won't miss any pre-existing threads.
746 // 2. All Ms listed in allm will eventually have an OS thread exist.
747 // i.e., they will set procid and be able to receive signals.
748 // 3. OS threads created after we read allm will clone from a thread
749 // that has executed the system call. i.e., they inherit the
750 // modified state.
751 //
752 // We achieve these through different mechanisms:
753 //
754 // 1. Addition of new Ms to allm in allocm happens before clone of its
755 // OS thread later in newm.
756 // 2. newm does acquirem to avoid being preempted, ensuring that new Ms
757 // created in allocm will eventually reach OS thread clone later in
758 // newm.
759 // 3. We take allocmLock for write here to prevent allocation of new Ms
760 // while this function runs. Per (1), this prevents clone of OS
761 // threads that are not yet in allm.
762 allocmLock.lock()
763
764 // Disable preemption, preventing us from changing Ms, as we handle
765 // this M specially.
766 //
767 // N.B. STW and lock() above do this as well, this is added for extra
768 // clarity.
769 acquirem()
770
771 // N.B. allocmLock also prevents concurrent execution of this function,
772 // serializing use of perThreadSyscall, mp.needPerThreadSyscall, and
773 // ensuring all threads execute system calls from multiple calls in the
774 // same order.
775
776 r1, r2, errno := syscall.Syscall6(trap, a1, a2, a3, a4, a5, a6)
777 if GOARCH == "ppc64" || GOARCH == "ppc64le" {
778 // TODO(https://go.dev/issue/51192 ): ppc64 doesn't use r2.
779 r2 = 0
780 }
781 if errno != 0 {
782 releasem(getg().m)
783 allocmLock.unlock()
784 startTheWorld(stw)
785 return r1, r2, errno
786 }
787
788 perThreadSyscall = perThreadSyscallArgs{
789 trap: trap,
790 a1: a1,
791 a2: a2,
792 a3: a3,
793 a4: a4,
794 a5: a5,
795 a6: a6,
796 r1: r1,
797 r2: r2,
798 }
799
800 // Wait for all threads to start.
801 //
802 // As described above, some Ms have been added to allm prior to
803 // allocmLock, but not yet completed OS clone and set procid.
804 //
805 // At minimum we must wait for a thread to set procid before we can
806 // send it a signal.
807 //
808 // We take this one step further and wait for all threads to start
809 // before sending any signals. This prevents system calls from getting
810 // applied twice: once in the parent and once in the child, like so:
811 //
812 // A B C
813 // add C to allm
814 // doAllThreadsSyscall
815 // allocmLock.lock()
816 // signal B
817 // <receive signal>
818 // execute syscall
819 // <signal return>
820 // clone C
821 // <thread start>
822 // set procid
823 // signal C
824 // <receive signal>
825 // execute syscall
826 // <signal return>
827 //
828 // In this case, thread C inherited the syscall-modified state from
829 // thread B and did not need to execute the syscall, but did anyway
830 // because doAllThreadsSyscall could not be sure whether it was
831 // required.
832 //
833 // Some system calls may not be idempotent, so we ensure each thread
834 // executes the system call exactly once.
835 for mp := allm; mp != nil; mp = mp.alllink {
836 for atomic.Load64(&mp.procid) == 0 {
837 // Thread is starting.
838 osyield()
839 }
840 }
841
842 // Signal every other thread, where they will execute perThreadSyscall
843 // from the signal handler.
844 gp := getg()
845 tid := gp.m.procid
846 for mp := allm; mp != nil; mp = mp.alllink {
847 if atomic.Load64(&mp.procid) == tid {
848 // Our thread already performed the syscall.
849 continue
850 }
851 mp.needPerThreadSyscall.Store(1)
852 signalM(mp, sigPerThreadSyscall)
853 }
854
855 // Wait for all threads to complete.
856 for mp := allm; mp != nil; mp = mp.alllink {
857 if mp.procid == tid {
858 continue
859 }
860 for mp.needPerThreadSyscall.Load() != 0 {
861 osyield()
862 }
863 }
864
865 perThreadSyscall = perThreadSyscallArgs{}
866
867 releasem(getg().m)
868 allocmLock.unlock()
869 startTheWorld(stw)
870
871 return r1, r2, errno
872 }
873
874 // runPerThreadSyscall runs perThreadSyscall for this M if required.
875 //
876 // This function throws if the system call returns with anything other than the
877 // expected values.
878 //
879 //go:nosplit
880 func runPerThreadSyscall() {
881 gp := getg()
882 if gp.m.needPerThreadSyscall.Load() == 0 {
883 return
884 }
885
886 args := perThreadSyscall
887 r1, r2, errno := syscall.Syscall6(args.trap, args.a1, args.a2, args.a3, args.a4, args.a5, args.a6)
888 if GOARCH == "ppc64" || GOARCH == "ppc64le" {
889 // TODO(https://go.dev/issue/51192 ): ppc64 doesn't use r2.
890 r2 = 0
891 }
892 if errno != 0 || r1 != args.r1 || r2 != args.r2 {
893 print("trap:", args.trap, ", a123456=[", args.a1, ",", args.a2, ",", args.a3, ",", args.a4, ",", args.a5, ",", args.a6, "]\n")
894 print("results: got {r1=", r1, ",r2=", r2, ",errno=", errno, "}, want {r1=", args.r1, ",r2=", args.r2, ",errno=0}\n")
895 fatal("AllThreadsSyscall6 results differ between threads; runtime corrupted")
896 }
897
898 gp.m.needPerThreadSyscall.Store(0)
899 }
900
901 const (
902 _SI_USER = 0
903 _SI_TKILL = -6
904 _SYS_SECCOMP = 1
905 )
906
907 // sigFromUser reports whether the signal was sent because of a call
908 // to kill or tgkill.
909 //
910 //go:nosplit
911 func (c *sigctxt) sigFromUser() bool {
912 code := int32(c.sigcode())
913 return code == _SI_USER || code == _SI_TKILL
914 }
915
916 // sigFromSeccomp reports whether the signal was sent from seccomp.
917 //
918 //go:nosplit
919 func (c *sigctxt) sigFromSeccomp() bool {
920 code := int32(c.sigcode())
921 return code == _SYS_SECCOMP
922 }
923
924 //go:nosplit
925 func mprotect(addr unsafe.Pointer, n uintptr, prot int32) (ret int32, errno int32) {
926 r, _, err := syscall.Syscall6(syscall.SYS_MPROTECT, uintptr(addr), n, uintptr(prot), 0, 0, 0)
927 return int32(r), int32(err)
928 }