Source file src/runtime/os_linux.go

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

View as plain text