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

View as plain text