Source file src/runtime/os_linux.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package runtime
     6  
     7  import (
     8  	"internal/abi"
     9  	"internal/goarch"
    10  	"internal/runtime/atomic"
    11  	"internal/runtime/syscall"
    12  	"unsafe"
    13  )
    14  
    15  // sigPerThreadSyscall is the same signal (SIGSETXID) used by glibc for
    16  // per-thread syscalls on Linux. We use it for the same purpose in non-cgo
    17  // binaries.
    18  const sigPerThreadSyscall = _SIGRTMIN + 1
    19  
    20  type mOS struct {
    21  	// profileTimer holds the ID of the POSIX interval timer for profiling CPU
    22  	// usage on this thread.
    23  	//
    24  	// It is valid when the profileTimerValid field is true. A thread
    25  	// creates and manages its own timer, and these fields are read and written
    26  	// only by this thread. But because some of the reads on profileTimerValid
    27  	// are in signal handling code, this field should be atomic type.
    28  	profileTimer      int32
    29  	profileTimerValid atomic.Bool
    30  
    31  	// needPerThreadSyscall indicates that a per-thread syscall is required
    32  	// for doAllThreadsSyscall.
    33  	needPerThreadSyscall atomic.Uint8
    34  
    35  	// This is a pointer to a chunk of memory allocated with a special
    36  	// mmap invocation in vgetrandomGetState().
    37  	vgetrandomState uintptr
    38  }
    39  
    40  //go:noescape
    41  func futex(addr unsafe.Pointer, op int32, val uint32, ts, addr2 unsafe.Pointer, val3 uint32) int32
    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, unsafe.Pointer(&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 getproccount() 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)
   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 := 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  	ncpu = getproccount()
   355  	physHugePageSize = getHugePageSize()
   356  	osArchInit()
   357  	vgetrandomInit()
   358  }
   359  
   360  var urandom_dev = []byte("/dev/urandom\x00")
   361  
   362  func readRandom(r []byte) int {
   363  	// Note that all supported Linux kernels should provide AT_RANDOM which
   364  	// populates startupRand, so this fallback should be unreachable.
   365  	fd := open(&urandom_dev[0], 0 /* O_RDONLY */, 0)
   366  	n := read(fd, unsafe.Pointer(&r[0]), int32(len(r)))
   367  	closefd(fd)
   368  	return int(n)
   369  }
   370  
   371  func goenvs() {
   372  	goenvs_unix()
   373  }
   374  
   375  // Called to do synchronous initialization of Go code built with
   376  // -buildmode=c-archive or -buildmode=c-shared.
   377  // None of the Go runtime is initialized.
   378  //
   379  //go:nosplit
   380  //go:nowritebarrierrec
   381  func libpreinit() {
   382  	initsig(true)
   383  }
   384  
   385  // Called to initialize a new m (including the bootstrap m).
   386  // Called on the parent thread (main thread in case of bootstrap), can allocate memory.
   387  func mpreinit(mp *m) {
   388  	mp.gsignal = malg(32 * 1024) // Linux wants >= 2K
   389  	mp.gsignal.m = mp
   390  }
   391  
   392  func gettid() uint32
   393  
   394  // Called to initialize a new m (including the bootstrap m).
   395  // Called on the new thread, cannot allocate memory.
   396  func minit() {
   397  	minitSignals()
   398  
   399  	// Cgo-created threads and the bootstrap m are missing a
   400  	// procid. We need this for asynchronous preemption and it's
   401  	// useful in debuggers.
   402  	getg().m.procid = uint64(gettid())
   403  }
   404  
   405  // Called from dropm to undo the effect of an minit.
   406  //
   407  //go:nosplit
   408  func unminit() {
   409  	unminitSignals()
   410  	getg().m.procid = 0
   411  }
   412  
   413  // Called from exitm, but not from drop, to undo the effect of thread-owned
   414  // resources in minit, semacreate, or elsewhere. Do not take locks after calling this.
   415  func mdestroy(mp *m) {
   416  	if mp.vgetrandomState != 0 {
   417  		vgetrandomPutState(mp.vgetrandomState)
   418  		mp.vgetrandomState = 0
   419  	}
   420  }
   421  
   422  // #ifdef GOARCH_386
   423  // #define sa_handler k_sa_handler
   424  // #endif
   425  
   426  func sigreturn__sigaction()
   427  func sigtramp() // Called via C ABI
   428  func cgoSigtramp()
   429  
   430  //go:noescape
   431  func sigaltstack(new, old *stackt)
   432  
   433  //go:noescape
   434  func setitimer(mode int32, new, old *itimerval)
   435  
   436  //go:noescape
   437  func timer_create(clockid int32, sevp *sigevent, timerid *int32) int32
   438  
   439  //go:noescape
   440  func timer_settime(timerid int32, flags int32, new, old *itimerspec) int32
   441  
   442  //go:noescape
   443  func timer_delete(timerid int32) int32
   444  
   445  //go:noescape
   446  func rtsigprocmask(how int32, new, old *sigset, size int32)
   447  
   448  //go:nosplit
   449  //go:nowritebarrierrec
   450  func sigprocmask(how int32, new, old *sigset) {
   451  	rtsigprocmask(how, new, old, int32(unsafe.Sizeof(*new)))
   452  }
   453  
   454  func raise(sig uint32)
   455  func raiseproc(sig uint32)
   456  
   457  //go:noescape
   458  func sched_getaffinity(pid, len uintptr, buf *byte) int32
   459  func osyield()
   460  
   461  //go:nosplit
   462  func osyield_no_g() {
   463  	osyield()
   464  }
   465  
   466  func pipe2(flags int32) (r, w int32, errno int32)
   467  
   468  //go:nosplit
   469  func fcntl(fd, cmd, arg int32) (ret int32, errno int32) {
   470  	r, _, err := syscall.Syscall6(syscall.SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg), 0, 0, 0)
   471  	return int32(r), int32(err)
   472  }
   473  
   474  const (
   475  	_si_max_size    = 128
   476  	_sigev_max_size = 64
   477  )
   478  
   479  //go:nosplit
   480  //go:nowritebarrierrec
   481  func setsig(i uint32, fn uintptr) {
   482  	var sa sigactiont
   483  	sa.sa_flags = _SA_SIGINFO | _SA_ONSTACK | _SA_RESTORER | _SA_RESTART
   484  	sigfillset(&sa.sa_mask)
   485  	// Although Linux manpage says "sa_restorer element is obsolete and
   486  	// should not be used". x86_64 kernel requires it. Only use it on
   487  	// x86.
   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  func getpid() int
   564  func tgkill(tgid, tid, sig int)
   565  
   566  // signalM sends a signal to mp.
   567  func signalM(mp *m, sig int) {
   568  	tgkill(getpid(), int(mp.procid), sig)
   569  }
   570  
   571  // validSIGPROF compares this signal delivery's code against the signal sources
   572  // that the profiler uses, returning whether the delivery should be processed.
   573  // To be processed, a signal delivery from a known profiling mechanism should
   574  // correspond to the best profiling mechanism available to this thread. Signals
   575  // from other sources are always considered valid.
   576  //
   577  //go:nosplit
   578  func validSIGPROF(mp *m, c *sigctxt) bool {
   579  	code := int32(c.sigcode())
   580  	setitimer := code == _SI_KERNEL
   581  	timer_create := code == _SI_TIMER
   582  
   583  	if !(setitimer || timer_create) {
   584  		// The signal doesn't correspond to a profiling mechanism that the
   585  		// runtime enables itself. There's no reason to process it, but there's
   586  		// no reason to ignore it either.
   587  		return true
   588  	}
   589  
   590  	if mp == nil {
   591  		// Since we don't have an M, we can't check if there's an active
   592  		// per-thread timer for this thread. We don't know how long this thread
   593  		// has been around, and if it happened to interact with the Go scheduler
   594  		// at a time when profiling was active (causing it to have a per-thread
   595  		// timer). But it may have never interacted with the Go scheduler, or
   596  		// never while profiling was active. To avoid double-counting, process
   597  		// only signals from setitimer.
   598  		//
   599  		// When a custom cgo traceback function has been registered (on
   600  		// platforms that support runtime.SetCgoTraceback), SIGPROF signals
   601  		// delivered to a thread that cannot find a matching M do this check in
   602  		// the assembly implementations of runtime.cgoSigtramp.
   603  		return setitimer
   604  	}
   605  
   606  	// Having an M means the thread interacts with the Go scheduler, and we can
   607  	// check whether there's an active per-thread timer for this thread.
   608  	if mp.profileTimerValid.Load() {
   609  		// If this M has its own per-thread CPU profiling interval timer, we
   610  		// should track the SIGPROF signals that come from that timer (for
   611  		// accurate reporting of its CPU usage; see issue 35057) and ignore any
   612  		// that it gets from the process-wide setitimer (to not over-count its
   613  		// CPU consumption).
   614  		return timer_create
   615  	}
   616  
   617  	// No active per-thread timer means the only valid profiler is setitimer.
   618  	return setitimer
   619  }
   620  
   621  func setProcessCPUProfiler(hz int32) {
   622  	setProcessCPUProfilerTimer(hz)
   623  }
   624  
   625  func setThreadCPUProfiler(hz int32) {
   626  	mp := getg().m
   627  	mp.profilehz = hz
   628  
   629  	// destroy any active timer
   630  	if mp.profileTimerValid.Load() {
   631  		timerid := mp.profileTimer
   632  		mp.profileTimerValid.Store(false)
   633  		mp.profileTimer = 0
   634  
   635  		ret := timer_delete(timerid)
   636  		if ret != 0 {
   637  			print("runtime: failed to disable profiling timer; timer_delete(", timerid, ") errno=", -ret, "\n")
   638  			throw("timer_delete")
   639  		}
   640  	}
   641  
   642  	if hz == 0 {
   643  		// If the goal was to disable profiling for this thread, then the job's done.
   644  		return
   645  	}
   646  
   647  	// The period of the timer should be 1/Hz. For every "1/Hz" of additional
   648  	// work, the user should expect one additional sample in the profile.
   649  	//
   650  	// But to scale down to very small amounts of application work, to observe
   651  	// even CPU usage of "one tenth" of the requested period, set the initial
   652  	// timing delay in a different way: So that "one tenth" of a period of CPU
   653  	// spend shows up as a 10% chance of one sample (for an expected value of
   654  	// 0.1 samples), and so that "two and six tenths" periods of CPU spend show
   655  	// up as a 60% chance of 3 samples and a 40% chance of 2 samples (for an
   656  	// expected value of 2.6). Set the initial delay to a value in the uniform
   657  	// random distribution between 0 and the desired period. And because "0"
   658  	// means "disable timer", add 1 so the half-open interval [0,period) turns
   659  	// into (0,period].
   660  	//
   661  	// Otherwise, this would show up as a bias away from short-lived threads and
   662  	// from threads that are only occasionally active: for example, when the
   663  	// garbage collector runs on a mostly-idle system, the additional threads it
   664  	// activates may do a couple milliseconds of GC-related work and nothing
   665  	// else in the few seconds that the profiler observes.
   666  	spec := new(itimerspec)
   667  	spec.it_value.setNsec(1 + int64(cheaprandn(uint32(1e9/hz))))
   668  	spec.it_interval.setNsec(1e9 / int64(hz))
   669  
   670  	var timerid int32
   671  	var sevp sigevent
   672  	sevp.notify = _SIGEV_THREAD_ID
   673  	sevp.signo = _SIGPROF
   674  	sevp.sigev_notify_thread_id = int32(mp.procid)
   675  	ret := timer_create(_CLOCK_THREAD_CPUTIME_ID, &sevp, &timerid)
   676  	if ret != 0 {
   677  		// If we cannot create a timer for this M, leave profileTimerValid false
   678  		// to fall back to the process-wide setitimer profiler.
   679  		return
   680  	}
   681  
   682  	ret = timer_settime(timerid, 0, spec, nil)
   683  	if ret != 0 {
   684  		print("runtime: failed to configure profiling timer; timer_settime(", timerid,
   685  			", 0, {interval: {",
   686  			spec.it_interval.tv_sec, "s + ", spec.it_interval.tv_nsec, "ns} value: {",
   687  			spec.it_value.tv_sec, "s + ", spec.it_value.tv_nsec, "ns}}, nil) errno=", -ret, "\n")
   688  		throw("timer_settime")
   689  	}
   690  
   691  	mp.profileTimer = timerid
   692  	mp.profileTimerValid.Store(true)
   693  }
   694  
   695  // perThreadSyscallArgs contains the system call number, arguments, and
   696  // expected return values for a system call to be executed on all threads.
   697  type perThreadSyscallArgs struct {
   698  	trap uintptr
   699  	a1   uintptr
   700  	a2   uintptr
   701  	a3   uintptr
   702  	a4   uintptr
   703  	a5   uintptr
   704  	a6   uintptr
   705  	r1   uintptr
   706  	r2   uintptr
   707  }
   708  
   709  // perThreadSyscall is the system call to execute for the ongoing
   710  // doAllThreadsSyscall.
   711  //
   712  // perThreadSyscall may only be written while mp.needPerThreadSyscall == 0 on
   713  // all Ms.
   714  var perThreadSyscall perThreadSyscallArgs
   715  
   716  // syscall_runtime_doAllThreadsSyscall and executes a specified system call on
   717  // all Ms.
   718  //
   719  // The system call is expected to succeed and return the same value on every
   720  // thread. If any threads do not match, the runtime throws.
   721  //
   722  //go:linkname syscall_runtime_doAllThreadsSyscall syscall.runtime_doAllThreadsSyscall
   723  //go:uintptrescapes
   724  func syscall_runtime_doAllThreadsSyscall(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr) {
   725  	if iscgo {
   726  		// In cgo, we are not aware of threads created in C, so this approach will not work.
   727  		panic("doAllThreadsSyscall not supported with cgo enabled")
   728  	}
   729  
   730  	// STW to guarantee that user goroutines see an atomic change to thread
   731  	// state. Without STW, goroutines could migrate Ms while change is in
   732  	// progress and e.g., see state old -> new -> old -> new.
   733  	//
   734  	// N.B. Internally, this function does not depend on STW to
   735  	// successfully change every thread. It is only needed for user
   736  	// expectations, per above.
   737  	stw := stopTheWorld(stwAllThreadsSyscall)
   738  
   739  	// This function depends on several properties:
   740  	//
   741  	// 1. All OS threads that already exist are associated with an M in
   742  	//    allm. i.e., we won't miss any pre-existing threads.
   743  	// 2. All Ms listed in allm will eventually have an OS thread exist.
   744  	//    i.e., they will set procid and be able to receive signals.
   745  	// 3. OS threads created after we read allm will clone from a thread
   746  	//    that has executed the system call. i.e., they inherit the
   747  	//    modified state.
   748  	//
   749  	// We achieve these through different mechanisms:
   750  	//
   751  	// 1. Addition of new Ms to allm in allocm happens before clone of its
   752  	//    OS thread later in newm.
   753  	// 2. newm does acquirem to avoid being preempted, ensuring that new Ms
   754  	//    created in allocm will eventually reach OS thread clone later in
   755  	//    newm.
   756  	// 3. We take allocmLock for write here to prevent allocation of new Ms
   757  	//    while this function runs. Per (1), this prevents clone of OS
   758  	//    threads that are not yet in allm.
   759  	allocmLock.lock()
   760  
   761  	// Disable preemption, preventing us from changing Ms, as we handle
   762  	// this M specially.
   763  	//
   764  	// N.B. STW and lock() above do this as well, this is added for extra
   765  	// clarity.
   766  	acquirem()
   767  
   768  	// N.B. allocmLock also prevents concurrent execution of this function,
   769  	// serializing use of perThreadSyscall, mp.needPerThreadSyscall, and
   770  	// ensuring all threads execute system calls from multiple calls in the
   771  	// same order.
   772  
   773  	r1, r2, errno := syscall.Syscall6(trap, a1, a2, a3, a4, a5, a6)
   774  	if GOARCH == "ppc64" || GOARCH == "ppc64le" {
   775  		// TODO(https://go.dev/issue/51192 ): ppc64 doesn't use r2.
   776  		r2 = 0
   777  	}
   778  	if errno != 0 {
   779  		releasem(getg().m)
   780  		allocmLock.unlock()
   781  		startTheWorld(stw)
   782  		return r1, r2, errno
   783  	}
   784  
   785  	perThreadSyscall = perThreadSyscallArgs{
   786  		trap: trap,
   787  		a1:   a1,
   788  		a2:   a2,
   789  		a3:   a3,
   790  		a4:   a4,
   791  		a5:   a5,
   792  		a6:   a6,
   793  		r1:   r1,
   794  		r2:   r2,
   795  	}
   796  
   797  	// Wait for all threads to start.
   798  	//
   799  	// As described above, some Ms have been added to allm prior to
   800  	// allocmLock, but not yet completed OS clone and set procid.
   801  	//
   802  	// At minimum we must wait for a thread to set procid before we can
   803  	// send it a signal.
   804  	//
   805  	// We take this one step further and wait for all threads to start
   806  	// before sending any signals. This prevents system calls from getting
   807  	// applied twice: once in the parent and once in the child, like so:
   808  	//
   809  	//          A                     B                  C
   810  	//                         add C to allm
   811  	// doAllThreadsSyscall
   812  	//   allocmLock.lock()
   813  	//   signal B
   814  	//                         <receive signal>
   815  	//                         execute syscall
   816  	//                         <signal return>
   817  	//                         clone C
   818  	//                                             <thread start>
   819  	//                                             set procid
   820  	//   signal C
   821  	//                                             <receive signal>
   822  	//                                             execute syscall
   823  	//                                             <signal return>
   824  	//
   825  	// In this case, thread C inherited the syscall-modified state from
   826  	// thread B and did not need to execute the syscall, but did anyway
   827  	// because doAllThreadsSyscall could not be sure whether it was
   828  	// required.
   829  	//
   830  	// Some system calls may not be idempotent, so we ensure each thread
   831  	// executes the system call exactly once.
   832  	for mp := allm; mp != nil; mp = mp.alllink {
   833  		for atomic.Load64(&mp.procid) == 0 {
   834  			// Thread is starting.
   835  			osyield()
   836  		}
   837  	}
   838  
   839  	// Signal every other thread, where they will execute perThreadSyscall
   840  	// from the signal handler.
   841  	gp := getg()
   842  	tid := gp.m.procid
   843  	for mp := allm; mp != nil; mp = mp.alllink {
   844  		if atomic.Load64(&mp.procid) == tid {
   845  			// Our thread already performed the syscall.
   846  			continue
   847  		}
   848  		mp.needPerThreadSyscall.Store(1)
   849  		signalM(mp, sigPerThreadSyscall)
   850  	}
   851  
   852  	// Wait for all threads to complete.
   853  	for mp := allm; mp != nil; mp = mp.alllink {
   854  		if mp.procid == tid {
   855  			continue
   856  		}
   857  		for mp.needPerThreadSyscall.Load() != 0 {
   858  			osyield()
   859  		}
   860  	}
   861  
   862  	perThreadSyscall = perThreadSyscallArgs{}
   863  
   864  	releasem(getg().m)
   865  	allocmLock.unlock()
   866  	startTheWorld(stw)
   867  
   868  	return r1, r2, errno
   869  }
   870  
   871  // runPerThreadSyscall runs perThreadSyscall for this M if required.
   872  //
   873  // This function throws if the system call returns with anything other than the
   874  // expected values.
   875  //
   876  //go:nosplit
   877  func runPerThreadSyscall() {
   878  	gp := getg()
   879  	if gp.m.needPerThreadSyscall.Load() == 0 {
   880  		return
   881  	}
   882  
   883  	args := perThreadSyscall
   884  	r1, r2, errno := syscall.Syscall6(args.trap, args.a1, args.a2, args.a3, args.a4, args.a5, args.a6)
   885  	if GOARCH == "ppc64" || GOARCH == "ppc64le" {
   886  		// TODO(https://go.dev/issue/51192 ): ppc64 doesn't use r2.
   887  		r2 = 0
   888  	}
   889  	if errno != 0 || r1 != args.r1 || r2 != args.r2 {
   890  		print("trap:", args.trap, ", a123456=[", args.a1, ",", args.a2, ",", args.a3, ",", args.a4, ",", args.a5, ",", args.a6, "]\n")
   891  		print("results: got {r1=", r1, ",r2=", r2, ",errno=", errno, "}, want {r1=", args.r1, ",r2=", args.r2, ",errno=0}\n")
   892  		fatal("AllThreadsSyscall6 results differ between threads; runtime corrupted")
   893  	}
   894  
   895  	gp.m.needPerThreadSyscall.Store(0)
   896  }
   897  
   898  const (
   899  	_SI_USER     = 0
   900  	_SI_TKILL    = -6
   901  	_SYS_SECCOMP = 1
   902  )
   903  
   904  // sigFromUser reports whether the signal was sent because of a call
   905  // to kill or tgkill.
   906  //
   907  //go:nosplit
   908  func (c *sigctxt) sigFromUser() bool {
   909  	code := int32(c.sigcode())
   910  	return code == _SI_USER || code == _SI_TKILL
   911  }
   912  
   913  // sigFromSeccomp reports whether the signal was sent from seccomp.
   914  //
   915  //go:nosplit
   916  func (c *sigctxt) sigFromSeccomp() bool {
   917  	code := int32(c.sigcode())
   918  	return code == _SYS_SECCOMP
   919  }
   920  
   921  //go:nosplit
   922  func mprotect(addr unsafe.Pointer, n uintptr, prot int32) (ret int32, errno int32) {
   923  	r, _, err := syscall.Syscall6(syscall.SYS_MPROTECT, uintptr(addr), n, uintptr(prot), 0, 0, 0)
   924  	return int32(r), int32(err)
   925  }
   926  

View as plain text