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

View as plain text