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

View as plain text