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  //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  	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 mexit, but not from dropm, to undo the effect of thread-owned
   416  // resources in minit, semacreate, or elsewhere. Do not take locks after calling this.
   417  //
   418  // This always runs without a P, so //go:nowritebarrierrec is required.
   419  //
   420  //go:nowritebarrierrec
   421  func mdestroy(mp *m) {
   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 := linux.Syscall6(linux.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. Note that on 386 this is cleared when using the C sigaction
   490  	// function via cgo; see fixSigactionForCgo.
   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  // fixSigactionForCgo is called when we are using cgo to call the
   567  // C sigaction function. On 386 the C function does not expect the
   568  // SA_RESTORER flag to be set, and in some cases will fail if it is set:
   569  // it will pass the SA_RESTORER flag to the kernel without passing
   570  // the sa_restorer field. Since the C function will handle SA_RESTORER
   571  // for us, we need not pass it. See issue #75253.
   572  //
   573  //go:nosplit
   574  func fixSigactionForCgo(new *sigactiont) {
   575  	if GOARCH == "386" && new != nil {
   576  		new.sa_flags &^= _SA_RESTORER
   577  		new.sa_restorer = 0
   578  	}
   579  }
   580  
   581  func getpid() int
   582  func tgkill(tgid, tid, sig int)
   583  
   584  // signalM sends a signal to mp.
   585  func signalM(mp *m, sig int) {
   586  	tgkill(getpid(), int(mp.procid), sig)
   587  }
   588  
   589  // validSIGPROF compares this signal delivery's code against the signal sources
   590  // that the profiler uses, returning whether the delivery should be processed.
   591  // To be processed, a signal delivery from a known profiling mechanism should
   592  // correspond to the best profiling mechanism available to this thread. Signals
   593  // from other sources are always considered valid.
   594  //
   595  //go:nosplit
   596  func validSIGPROF(mp *m, c *sigctxt) bool {
   597  	code := int32(c.sigcode())
   598  	setitimer := code == _SI_KERNEL
   599  	timer_create := code == _SI_TIMER
   600  
   601  	if !(setitimer || timer_create) {
   602  		// The signal doesn't correspond to a profiling mechanism that the
   603  		// runtime enables itself. There's no reason to process it, but there's
   604  		// no reason to ignore it either.
   605  		return true
   606  	}
   607  
   608  	if mp == nil {
   609  		// Since we don't have an M, we can't check if there's an active
   610  		// per-thread timer for this thread. We don't know how long this thread
   611  		// has been around, and if it happened to interact with the Go scheduler
   612  		// at a time when profiling was active (causing it to have a per-thread
   613  		// timer). But it may have never interacted with the Go scheduler, or
   614  		// never while profiling was active. To avoid double-counting, process
   615  		// only signals from setitimer.
   616  		//
   617  		// When a custom cgo traceback function has been registered (on
   618  		// platforms that support runtime.SetCgoTraceback), SIGPROF signals
   619  		// delivered to a thread that cannot find a matching M do this check in
   620  		// the assembly implementations of runtime.cgoSigtramp.
   621  		return setitimer
   622  	}
   623  
   624  	// Having an M means the thread interacts with the Go scheduler, and we can
   625  	// check whether there's an active per-thread timer for this thread.
   626  	if mp.profileTimerValid.Load() {
   627  		// If this M has its own per-thread CPU profiling interval timer, we
   628  		// should track the SIGPROF signals that come from that timer (for
   629  		// accurate reporting of its CPU usage; see issue 35057) and ignore any
   630  		// that it gets from the process-wide setitimer (to not over-count its
   631  		// CPU consumption).
   632  		return timer_create
   633  	}
   634  
   635  	// No active per-thread timer means the only valid profiler is setitimer.
   636  	return setitimer
   637  }
   638  
   639  func setProcessCPUProfiler(hz int32) {
   640  	setProcessCPUProfilerTimer(hz)
   641  }
   642  
   643  func setThreadCPUProfiler(hz int32) {
   644  	mp := getg().m
   645  	mp.profilehz = hz
   646  
   647  	// destroy any active timer
   648  	if mp.profileTimerValid.Load() {
   649  		timerid := mp.profileTimer
   650  		mp.profileTimerValid.Store(false)
   651  		mp.profileTimer = 0
   652  
   653  		ret := timer_delete(timerid)
   654  		if ret != 0 {
   655  			print("runtime: failed to disable profiling timer; timer_delete(", timerid, ") errno=", -ret, "\n")
   656  			throw("timer_delete")
   657  		}
   658  	}
   659  
   660  	if hz == 0 {
   661  		// If the goal was to disable profiling for this thread, then the job's done.
   662  		return
   663  	}
   664  
   665  	// The period of the timer should be 1/Hz. For every "1/Hz" of additional
   666  	// work, the user should expect one additional sample in the profile.
   667  	//
   668  	// But to scale down to very small amounts of application work, to observe
   669  	// even CPU usage of "one tenth" of the requested period, set the initial
   670  	// timing delay in a different way: So that "one tenth" of a period of CPU
   671  	// spend shows up as a 10% chance of one sample (for an expected value of
   672  	// 0.1 samples), and so that "two and six tenths" periods of CPU spend show
   673  	// up as a 60% chance of 3 samples and a 40% chance of 2 samples (for an
   674  	// expected value of 2.6). Set the initial delay to a value in the uniform
   675  	// random distribution between 0 and the desired period. And because "0"
   676  	// means "disable timer", add 1 so the half-open interval [0,period) turns
   677  	// into (0,period].
   678  	//
   679  	// Otherwise, this would show up as a bias away from short-lived threads and
   680  	// from threads that are only occasionally active: for example, when the
   681  	// garbage collector runs on a mostly-idle system, the additional threads it
   682  	// activates may do a couple milliseconds of GC-related work and nothing
   683  	// else in the few seconds that the profiler observes.
   684  	spec := new(itimerspec)
   685  	spec.it_value.setNsec(1 + int64(cheaprandn(uint32(1e9/hz))))
   686  	spec.it_interval.setNsec(1e9 / int64(hz))
   687  
   688  	var timerid int32
   689  	var sevp sigevent
   690  	sevp.notify = _SIGEV_THREAD_ID
   691  	sevp.signo = _SIGPROF
   692  	sevp.sigev_notify_thread_id = int32(mp.procid)
   693  	ret := timer_create(_CLOCK_THREAD_CPUTIME_ID, &sevp, &timerid)
   694  	if ret != 0 {
   695  		// If we cannot create a timer for this M, leave profileTimerValid false
   696  		// to fall back to the process-wide setitimer profiler.
   697  		return
   698  	}
   699  
   700  	ret = timer_settime(timerid, 0, spec, nil)
   701  	if ret != 0 {
   702  		print("runtime: failed to configure profiling timer; timer_settime(", timerid,
   703  			", 0, {interval: {",
   704  			spec.it_interval.tv_sec, "s + ", spec.it_interval.tv_nsec, "ns} value: {",
   705  			spec.it_value.tv_sec, "s + ", spec.it_value.tv_nsec, "ns}}, nil) errno=", -ret, "\n")
   706  		throw("timer_settime")
   707  	}
   708  
   709  	mp.profileTimer = timerid
   710  	mp.profileTimerValid.Store(true)
   711  }
   712  
   713  // perThreadSyscallArgs contains the system call number, arguments, and
   714  // expected return values for a system call to be executed on all threads.
   715  type perThreadSyscallArgs struct {
   716  	trap uintptr
   717  	a1   uintptr
   718  	a2   uintptr
   719  	a3   uintptr
   720  	a4   uintptr
   721  	a5   uintptr
   722  	a6   uintptr
   723  	r1   uintptr
   724  	r2   uintptr
   725  }
   726  
   727  // perThreadSyscall is the system call to execute for the ongoing
   728  // doAllThreadsSyscall.
   729  //
   730  // perThreadSyscall may only be written while mp.needPerThreadSyscall == 0 on
   731  // all Ms.
   732  var perThreadSyscall perThreadSyscallArgs
   733  
   734  // syscall_runtime_doAllThreadsSyscall and executes a specified system call on
   735  // all Ms.
   736  //
   737  // The system call is expected to succeed and return the same value on every
   738  // thread. If any threads do not match, the runtime throws.
   739  //
   740  //go:linkname syscall_runtime_doAllThreadsSyscall syscall.runtime_doAllThreadsSyscall
   741  //go:uintptrescapes
   742  func syscall_runtime_doAllThreadsSyscall(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr) {
   743  	if iscgo {
   744  		// In cgo, we are not aware of threads created in C, so this approach will not work.
   745  		panic("doAllThreadsSyscall not supported with cgo enabled")
   746  	}
   747  
   748  	// STW to guarantee that user goroutines see an atomic change to thread
   749  	// state. Without STW, goroutines could migrate Ms while change is in
   750  	// progress and e.g., see state old -> new -> old -> new.
   751  	//
   752  	// N.B. Internally, this function does not depend on STW to
   753  	// successfully change every thread. It is only needed for user
   754  	// expectations, per above.
   755  	stw := stopTheWorld(stwAllThreadsSyscall)
   756  
   757  	// This function depends on several properties:
   758  	//
   759  	// 1. All OS threads that already exist are associated with an M in
   760  	//    allm. i.e., we won't miss any pre-existing threads.
   761  	// 2. All Ms listed in allm will eventually have an OS thread exist.
   762  	//    i.e., they will set procid and be able to receive signals.
   763  	// 3. OS threads created after we read allm will clone from a thread
   764  	//    that has executed the system call. i.e., they inherit the
   765  	//    modified state.
   766  	//
   767  	// We achieve these through different mechanisms:
   768  	//
   769  	// 1. Addition of new Ms to allm in allocm happens before clone of its
   770  	//    OS thread later in newm.
   771  	// 2. newm does acquirem to avoid being preempted, ensuring that new Ms
   772  	//    created in allocm will eventually reach OS thread clone later in
   773  	//    newm.
   774  	// 3. We take allocmLock for write here to prevent allocation of new Ms
   775  	//    while this function runs. Per (1), this prevents clone of OS
   776  	//    threads that are not yet in allm.
   777  	allocmLock.lock()
   778  
   779  	// Disable preemption, preventing us from changing Ms, as we handle
   780  	// this M specially.
   781  	//
   782  	// N.B. STW and lock() above do this as well, this is added for extra
   783  	// clarity.
   784  	acquirem()
   785  
   786  	// N.B. allocmLock also prevents concurrent execution of this function,
   787  	// serializing use of perThreadSyscall, mp.needPerThreadSyscall, and
   788  	// ensuring all threads execute system calls from multiple calls in the
   789  	// same order.
   790  
   791  	r1, r2, errno := linux.Syscall6(trap, a1, a2, a3, a4, a5, a6)
   792  	if GOARCH == "ppc64" || GOARCH == "ppc64le" {
   793  		// TODO(https://go.dev/issue/51192 ): ppc64 doesn't use r2.
   794  		r2 = 0
   795  	}
   796  	if errno != 0 {
   797  		releasem(getg().m)
   798  		allocmLock.unlock()
   799  		startTheWorld(stw)
   800  		return r1, r2, errno
   801  	}
   802  
   803  	perThreadSyscall = perThreadSyscallArgs{
   804  		trap: trap,
   805  		a1:   a1,
   806  		a2:   a2,
   807  		a3:   a3,
   808  		a4:   a4,
   809  		a5:   a5,
   810  		a6:   a6,
   811  		r1:   r1,
   812  		r2:   r2,
   813  	}
   814  
   815  	// Wait for all threads to start.
   816  	//
   817  	// As described above, some Ms have been added to allm prior to
   818  	// allocmLock, but not yet completed OS clone and set procid.
   819  	//
   820  	// At minimum we must wait for a thread to set procid before we can
   821  	// send it a signal.
   822  	//
   823  	// We take this one step further and wait for all threads to start
   824  	// before sending any signals. This prevents system calls from getting
   825  	// applied twice: once in the parent and once in the child, like so:
   826  	//
   827  	//          A                     B                  C
   828  	//                         add C to allm
   829  	// doAllThreadsSyscall
   830  	//   allocmLock.lock()
   831  	//   signal B
   832  	//                         <receive signal>
   833  	//                         execute syscall
   834  	//                         <signal return>
   835  	//                         clone C
   836  	//                                             <thread start>
   837  	//                                             set procid
   838  	//   signal C
   839  	//                                             <receive signal>
   840  	//                                             execute syscall
   841  	//                                             <signal return>
   842  	//
   843  	// In this case, thread C inherited the syscall-modified state from
   844  	// thread B and did not need to execute the syscall, but did anyway
   845  	// because doAllThreadsSyscall could not be sure whether it was
   846  	// required.
   847  	//
   848  	// Some system calls may not be idempotent, so we ensure each thread
   849  	// executes the system call exactly once.
   850  	for mp := allm; mp != nil; mp = mp.alllink {
   851  		for atomic.Load64(&mp.procid) == 0 {
   852  			// Thread is starting.
   853  			osyield()
   854  		}
   855  	}
   856  
   857  	// Signal every other thread, where they will execute perThreadSyscall
   858  	// from the signal handler.
   859  	gp := getg()
   860  	tid := gp.m.procid
   861  	for mp := allm; mp != nil; mp = mp.alllink {
   862  		if atomic.Load64(&mp.procid) == tid {
   863  			// Our thread already performed the syscall.
   864  			continue
   865  		}
   866  		mp.needPerThreadSyscall.Store(1)
   867  		signalM(mp, sigPerThreadSyscall)
   868  	}
   869  
   870  	// Wait for all threads to complete.
   871  	for mp := allm; mp != nil; mp = mp.alllink {
   872  		if mp.procid == tid {
   873  			continue
   874  		}
   875  		for mp.needPerThreadSyscall.Load() != 0 {
   876  			osyield()
   877  		}
   878  	}
   879  
   880  	perThreadSyscall = perThreadSyscallArgs{}
   881  
   882  	releasem(getg().m)
   883  	allocmLock.unlock()
   884  	startTheWorld(stw)
   885  
   886  	return r1, r2, errno
   887  }
   888  
   889  // runPerThreadSyscall runs perThreadSyscall for this M if required.
   890  //
   891  // This function throws if the system call returns with anything other than the
   892  // expected values.
   893  //
   894  //go:nosplit
   895  func runPerThreadSyscall() {
   896  	gp := getg()
   897  	if gp.m.needPerThreadSyscall.Load() == 0 {
   898  		return
   899  	}
   900  
   901  	args := perThreadSyscall
   902  	r1, r2, errno := linux.Syscall6(args.trap, args.a1, args.a2, args.a3, args.a4, args.a5, args.a6)
   903  	if GOARCH == "ppc64" || GOARCH == "ppc64le" {
   904  		// TODO(https://go.dev/issue/51192 ): ppc64 doesn't use r2.
   905  		r2 = 0
   906  	}
   907  	if errno != 0 || r1 != args.r1 || r2 != args.r2 {
   908  		print("trap:", args.trap, ", a123456=[", args.a1, ",", args.a2, ",", args.a3, ",", args.a4, ",", args.a5, ",", args.a6, "]\n")
   909  		print("results: got {r1=", r1, ",r2=", r2, ",errno=", errno, "}, want {r1=", args.r1, ",r2=", args.r2, ",errno=0}\n")
   910  		fatal("AllThreadsSyscall6 results differ between threads; runtime corrupted")
   911  	}
   912  
   913  	gp.m.needPerThreadSyscall.Store(0)
   914  }
   915  
   916  const (
   917  	_SI_USER     = 0
   918  	_SI_TKILL    = -6
   919  	_SYS_SECCOMP = 1
   920  )
   921  
   922  // sigFromUser reports whether the signal was sent because of a call
   923  // to kill or tgkill.
   924  //
   925  //go:nosplit
   926  func (c *sigctxt) sigFromUser() bool {
   927  	code := int32(c.sigcode())
   928  	return code == _SI_USER || code == _SI_TKILL
   929  }
   930  
   931  // sigFromSeccomp reports whether the signal was sent from seccomp.
   932  //
   933  //go:nosplit
   934  func (c *sigctxt) sigFromSeccomp() bool {
   935  	code := int32(c.sigcode())
   936  	return code == _SYS_SECCOMP
   937  }
   938  
   939  //go:nosplit
   940  func mprotect(addr unsafe.Pointer, n uintptr, prot int32) (ret int32, errno int32) {
   941  	r, _, err := linux.Syscall6(linux.SYS_MPROTECT, uintptr(addr), n, uintptr(prot), 0, 0, 0)
   942  	return int32(r), int32(err)
   943  }
   944  

View as plain text