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

View as plain text