github.com/ltltlt/go-source-code@v0.0.0-20190830023027-95be009773aa/runtime/os_linux.go (about)

     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  	"runtime/internal/sys"
     9  	"unsafe"
    10  )
    11  
    12  type mOS struct{}
    13  
    14  //go:noescape
    15  func futex(addr unsafe.Pointer, op int32, val uint32, ts, addr2 unsafe.Pointer, val3 uint32) int32
    16  
    17  // Linux futex.
    18  //
    19  //	futexsleep(uint32 *addr, uint32 val)
    20  //	futexwakeup(uint32 *addr)
    21  //
    22  // Futexsleep atomically checks if *addr == val and if so, sleeps on addr.
    23  // Futexwakeup wakes up threads sleeping on addr.
    24  // Futexsleep is allowed to wake up spuriously.
    25  
    26  const (
    27  	_FUTEX_WAIT = 0
    28  	_FUTEX_WAKE = 1
    29  )
    30  
    31  // Atomically,
    32  //	if(*addr == val) sleep
    33  // Might be woken up spuriously; that's allowed.
    34  // Don't sleep longer than ns; ns < 0 means forever.
    35  //go:nosplit
    36  func futexsleep(addr *uint32, val uint32, ns int64) {
    37  	var ts timespec
    38  
    39  	// Some Linux kernels have a bug where futex of
    40  	// FUTEX_WAIT returns an internal error code
    41  	// as an errno. Libpthread ignores the return value
    42  	// here, and so can we: as it says a few lines up,
    43  	// spurious wakeups are allowed.
    44  	if ns < 0 {
    45  		futex(unsafe.Pointer(addr), _FUTEX_WAIT, val, nil, nil, 0)
    46  		return
    47  	}
    48  
    49  	// It's difficult to live within the no-split stack limits here.
    50  	// On ARM and 386, a 64-bit divide invokes a general software routine
    51  	// that needs more stack than we can afford. So we use timediv instead.
    52  	// But on real 64-bit systems, where words are larger but the stack limit
    53  	// is not, even timediv is too heavy, and we really need to use just an
    54  	// ordinary machine instruction.
    55  	if sys.PtrSize == 8 {
    56  		ts.set_sec(ns / 1000000000)
    57  		ts.set_nsec(int32(ns % 1000000000))
    58  	} else {
    59  		ts.tv_nsec = 0
    60  		ts.set_sec(int64(timediv(ns, 1000000000, (*int32)(unsafe.Pointer(&ts.tv_nsec)))))
    61  	}
    62  	futex(unsafe.Pointer(addr), _FUTEX_WAIT, val, unsafe.Pointer(&ts), nil, 0)
    63  }
    64  
    65  // If any procs are sleeping on addr, wake up at most cnt.
    66  //go:nosplit
    67  func futexwakeup(addr *uint32, cnt uint32) {
    68  	ret := futex(unsafe.Pointer(addr), _FUTEX_WAKE, cnt, nil, nil, 0)
    69  	if ret >= 0 {
    70  		return
    71  	}
    72  
    73  	// I don't know that futex wakeup can return
    74  	// EAGAIN or EINTR, but if it does, it would be
    75  	// safe to loop and call futex again.
    76  	systemstack(func() {
    77  		print("futexwakeup addr=", addr, " returned ", ret, "\n")
    78  	})
    79  
    80  	*(*int32)(unsafe.Pointer(uintptr(0x1006))) = 0x1006
    81  }
    82  
    83  func getproccount() int32 {
    84  	// This buffer is huge (8 kB) but we are on the system stack
    85  	// and there should be plenty of space (64 kB).
    86  	// Also this is a leaf, so we're not holding up the memory for long.
    87  	// See golang.org/issue/11823.
    88  	// The suggested behavior here is to keep trying with ever-larger
    89  	// buffers, but we don't have a dynamic memory allocator at the
    90  	// moment, so that's a bit tricky and seems like overkill.
    91  	const maxCPUs = 64 * 1024
    92  	var buf [maxCPUs / 8]byte
    93  	r := sched_getaffinity(0, unsafe.Sizeof(buf), &buf[0])
    94  	if r < 0 {
    95  		return 1
    96  	}
    97  	n := int32(0)
    98  	for _, v := range buf[:r] {
    99  		for v != 0 {
   100  			n += int32(v & 1)
   101  			v >>= 1
   102  		}
   103  	}
   104  	if n == 0 {
   105  		n = 1
   106  	}
   107  	return n
   108  }
   109  
   110  // Clone, the Linux rfork.
   111  const (
   112  	_CLONE_VM             = 0x100
   113  	_CLONE_FS             = 0x200
   114  	_CLONE_FILES          = 0x400
   115  	_CLONE_SIGHAND        = 0x800
   116  	_CLONE_PTRACE         = 0x2000
   117  	_CLONE_VFORK          = 0x4000
   118  	_CLONE_PARENT         = 0x8000
   119  	_CLONE_THREAD         = 0x10000
   120  	_CLONE_NEWNS          = 0x20000
   121  	_CLONE_SYSVSEM        = 0x40000
   122  	_CLONE_SETTLS         = 0x80000
   123  	_CLONE_PARENT_SETTID  = 0x100000
   124  	_CLONE_CHILD_CLEARTID = 0x200000
   125  	_CLONE_UNTRACED       = 0x800000
   126  	_CLONE_CHILD_SETTID   = 0x1000000
   127  	_CLONE_STOPPED        = 0x2000000
   128  	_CLONE_NEWUTS         = 0x4000000
   129  	_CLONE_NEWIPC         = 0x8000000
   130  
   131  	cloneFlags = _CLONE_VM | /* share memory */
   132  		_CLONE_FS | /* share cwd, etc */
   133  		_CLONE_FILES | /* share fd table */
   134  		_CLONE_SIGHAND | /* share sig handler table */
   135  		_CLONE_SYSVSEM | /* share SysV semaphore undo lists (see issue #20763) */
   136  		_CLONE_THREAD /* revisit - okay for now */
   137  )
   138  
   139  //go:noescape
   140  func clone(flags int32, stk, mp, gp, fn unsafe.Pointer) int32
   141  
   142  // May run with m.p==nil, so write barriers are not allowed.
   143  //go:nowritebarrier
   144  func newosproc(mp *m, stk unsafe.Pointer) {
   145  	/*
   146  	 * note: strace gets confused if we use CLONE_PTRACE here.
   147  	 */
   148  	if false {
   149  		print("newosproc stk=", stk, " m=", mp, " g=", mp.g0, " clone=", funcPC(clone), " id=", mp.id, " ostk=", &mp, "\n")
   150  	}
   151  
   152  	// Disable signals during clone, so that the new thread starts
   153  	// with signals disabled. It will enable them in minit.
   154  	var oset sigset
   155  	sigprocmask(_SIG_SETMASK, &sigset_all, &oset)
   156  	// linux system call
   157  	ret := clone(cloneFlags, stk, unsafe.Pointer(mp), unsafe.Pointer(mp.g0), unsafe.Pointer(funcPC(mstart)))
   158  	sigprocmask(_SIG_SETMASK, &oset, nil)
   159  
   160  	if ret < 0 {
   161  		print("runtime: failed to create new OS thread (have ", mcount(), " already; errno=", -ret, ")\n")
   162  		if ret == -_EAGAIN {
   163  			println("runtime: may need to increase max user processes (ulimit -u)")
   164  		}
   165  		throw("newosproc")
   166  	}
   167  }
   168  
   169  // Version of newosproc that doesn't require a valid G.
   170  //go:nosplit
   171  func newosproc0(stacksize uintptr, fn unsafe.Pointer) {
   172  	stack := sysAlloc(stacksize, &memstats.stacks_sys)
   173  	if stack == nil {
   174  		write(2, unsafe.Pointer(&failallocatestack[0]), int32(len(failallocatestack)))
   175  		exit(1)
   176  	}
   177  	ret := clone(cloneFlags, unsafe.Pointer(uintptr(stack)+stacksize), nil, nil, fn)
   178  	if ret < 0 {
   179  		write(2, unsafe.Pointer(&failthreadcreate[0]), int32(len(failthreadcreate)))
   180  		exit(1)
   181  	}
   182  }
   183  
   184  var failallocatestack = []byte("runtime: failed to allocate stack for the new OS thread\n")
   185  var failthreadcreate = []byte("runtime: failed to create new OS thread\n")
   186  
   187  const (
   188  	_AT_NULL   = 0  // End of vector
   189  	_AT_PAGESZ = 6  // System physical page size
   190  	_AT_HWCAP  = 16 // hardware capability bit vector
   191  	_AT_RANDOM = 25 // introduced in 2.6.29
   192  	_AT_HWCAP2 = 26 // hardware capability bit vector 2
   193  )
   194  
   195  var procAuxv = []byte("/proc/self/auxv\x00")
   196  
   197  func mincore(addr unsafe.Pointer, n uintptr, dst *byte) int32
   198  
   199  func sysargs(argc int32, argv **byte) {
   200  	n := argc + 1
   201  
   202  	// skip over argv, envp to get to auxv
   203  	for argv_index(argv, n) != nil {
   204  		n++
   205  	}
   206  
   207  	// skip NULL separator
   208  	n++
   209  
   210  	// now argv+n is auxv
   211  	auxv := (*[1 << 28]uintptr)(add(unsafe.Pointer(argv), uintptr(n)*sys.PtrSize))
   212  	if sysauxv(auxv[:]) != 0 {
   213  		return
   214  	}
   215  	// In some situations we don't get a loader-provided
   216  	// auxv, such as when loaded as a library on Android.
   217  	// Fall back to /proc/self/auxv.
   218  	fd := open(&procAuxv[0], 0 /* O_RDONLY */, 0)
   219  	if fd < 0 {
   220  		// On Android, /proc/self/auxv might be unreadable (issue 9229), so we fallback to
   221  		// try using mincore to detect the physical page size.
   222  		// mincore should return EINVAL when address is not a multiple of system page size.
   223  		const size = 256 << 10 // size of memory region to allocate
   224  		p, err := mmap(nil, size, _PROT_READ|_PROT_WRITE, _MAP_ANON|_MAP_PRIVATE, -1, 0)
   225  		if err != 0 {
   226  			return
   227  		}
   228  		var n uintptr
   229  		for n = 4 << 10; n < size; n <<= 1 {
   230  			err := mincore(unsafe.Pointer(uintptr(p)+n), 1, &addrspace_vec[0])
   231  			if err == 0 {
   232  				physPageSize = n
   233  				break
   234  			}
   235  		}
   236  		if physPageSize == 0 {
   237  			physPageSize = size
   238  		}
   239  		munmap(p, size)
   240  		return
   241  	}
   242  	var buf [128]uintptr
   243  	n = read(fd, noescape(unsafe.Pointer(&buf[0])), int32(unsafe.Sizeof(buf)))
   244  	closefd(fd)
   245  	if n < 0 {
   246  		return
   247  	}
   248  	// Make sure buf is terminated, even if we didn't read
   249  	// the whole file.
   250  	buf[len(buf)-2] = _AT_NULL
   251  	sysauxv(buf[:])
   252  }
   253  
   254  func sysauxv(auxv []uintptr) int {
   255  	var i int
   256  	for ; auxv[i] != _AT_NULL; i += 2 {
   257  		tag, val := auxv[i], auxv[i+1]
   258  		switch tag {
   259  		case _AT_RANDOM:
   260  			// The kernel provides a pointer to 16-bytes
   261  			// worth of random data.
   262  			startupRandomData = (*[16]byte)(unsafe.Pointer(val))[:]
   263  
   264  		case _AT_PAGESZ:
   265  			physPageSize = val
   266  		}
   267  
   268  		archauxv(tag, val)
   269  	}
   270  	return i / 2
   271  }
   272  
   273  func osinit() {
   274  	ncpu = getproccount()
   275  }
   276  
   277  var urandom_dev = []byte("/dev/urandom\x00")
   278  
   279  func getRandomData(r []byte) {
   280  	if startupRandomData != nil {
   281  		n := copy(r, startupRandomData)
   282  		extendRandom(r, n)
   283  		return
   284  	}
   285  	fd := open(&urandom_dev[0], 0 /* O_RDONLY */, 0)
   286  	n := read(fd, unsafe.Pointer(&r[0]), int32(len(r)))
   287  	closefd(fd)
   288  	extendRandom(r, int(n))
   289  }
   290  
   291  func goenvs() {
   292  	goenvs_unix()
   293  }
   294  
   295  // Called to do synchronous initialization of Go code built with
   296  // -buildmode=c-archive or -buildmode=c-shared.
   297  // None of the Go runtime is initialized.
   298  //go:nosplit
   299  //go:nowritebarrierrec
   300  func libpreinit() {
   301  	initsig(true)
   302  }
   303  
   304  // Called to initialize a new m (including the bootstrap m).
   305  // Called on the parent thread (main thread in case of bootstrap), can allocate memory.
   306  func mpreinit(mp *m) {
   307  	mp.gsignal = malg(32 * 1024) // Linux wants >= 2K
   308  	mp.gsignal.m = mp
   309  }
   310  
   311  func gettid() uint32
   312  
   313  // Called to initialize a new m (including the bootstrap m).
   314  // Called on the new thread, cannot allocate memory.
   315  func minit() {
   316  	minitSignals()
   317  
   318  	// for debuggers, in case cgo created the thread
   319  	getg().m.procid = uint64(gettid())
   320  }
   321  
   322  // Called from dropm to undo the effect of an minit.
   323  //go:nosplit
   324  func unminit() {
   325  	unminitSignals()
   326  }
   327  
   328  func memlimit() uintptr {
   329  	/*
   330  		TODO: Convert to Go when something actually uses the result.
   331  
   332  		Rlimit rl;
   333  		extern byte runtime·text[], runtime·end[];
   334  		uintptr used;
   335  
   336  		if(runtime·getrlimit(RLIMIT_AS, &rl) != 0)
   337  			return 0;
   338  		if(rl.rlim_cur >= 0x7fffffff)
   339  			return 0;
   340  
   341  		// Estimate our VM footprint excluding the heap.
   342  		// Not an exact science: use size of binary plus
   343  		// some room for thread stacks.
   344  		used = runtime·end - runtime·text + (64<<20);
   345  		if(used >= rl.rlim_cur)
   346  			return 0;
   347  
   348  		// If there's not at least 16 MB left, we're probably
   349  		// not going to be able to do much. Treat as no limit.
   350  		rl.rlim_cur -= used;
   351  		if(rl.rlim_cur < (16<<20))
   352  			return 0;
   353  
   354  		return rl.rlim_cur - used;
   355  	*/
   356  
   357  	return 0
   358  }
   359  
   360  //#ifdef GOARCH_386
   361  //#define sa_handler k_sa_handler
   362  //#endif
   363  
   364  func sigreturn()
   365  func sigtramp(sig uint32, info *siginfo, ctx unsafe.Pointer)
   366  func cgoSigtramp()
   367  
   368  //go:noescape
   369  func sigaltstack(new, old *stackt)
   370  
   371  //go:noescape
   372  func setitimer(mode int32, new, old *itimerval)
   373  
   374  //go:noescape
   375  func rtsigprocmask(how int32, new, old *sigset, size int32)
   376  
   377  //go:nosplit
   378  //go:nowritebarrierrec
   379  func sigprocmask(how int32, new, old *sigset) {
   380  	rtsigprocmask(how, new, old, int32(unsafe.Sizeof(*new)))
   381  }
   382  
   383  //go:noescape
   384  func getrlimit(kind int32, limit unsafe.Pointer) int32
   385  func raise(sig uint32)
   386  func raiseproc(sig uint32)
   387  
   388  //go:noescape
   389  func sched_getaffinity(pid, len uintptr, buf *byte) int32
   390  
   391  // 看了汇编代码, 调用syscall 0x18即sched_yield, 这个系统调用指示调用线程放弃cpu. 线程被放到优先队列尾部
   392  // see linux `man sched_yield`
   393  func osyield()
   394  
   395  //go:nosplit
   396  //go:nowritebarrierrec
   397  func setsig(i uint32, fn uintptr) {
   398  	var sa sigactiont
   399  	sa.sa_flags = _SA_SIGINFO | _SA_ONSTACK | _SA_RESTORER | _SA_RESTART
   400  	sigfillset(&sa.sa_mask)
   401  	// Although Linux manpage says "sa_restorer element is obsolete and
   402  	// should not be used". x86_64 kernel requires it. Only use it on
   403  	// x86.
   404  	if GOARCH == "386" || GOARCH == "amd64" {
   405  		sa.sa_restorer = funcPC(sigreturn)
   406  	}
   407  	if fn == funcPC(sighandler) {
   408  		if iscgo {
   409  			fn = funcPC(cgoSigtramp)
   410  		} else {
   411  			fn = funcPC(sigtramp)
   412  		}
   413  	}
   414  	sa.sa_handler = fn
   415  	rt_sigaction(uintptr(i), &sa, nil, unsafe.Sizeof(sa.sa_mask))
   416  }
   417  
   418  //go:nosplit
   419  //go:nowritebarrierrec
   420  func setsigstack(i uint32) {
   421  	var sa sigactiont
   422  	rt_sigaction(uintptr(i), nil, &sa, unsafe.Sizeof(sa.sa_mask))
   423  	if sa.sa_flags&_SA_ONSTACK != 0 {
   424  		return
   425  	}
   426  	sa.sa_flags |= _SA_ONSTACK
   427  	rt_sigaction(uintptr(i), &sa, nil, unsafe.Sizeof(sa.sa_mask))
   428  }
   429  
   430  //go:nosplit
   431  //go:nowritebarrierrec
   432  func getsig(i uint32) uintptr {
   433  	var sa sigactiont
   434  	if rt_sigaction(uintptr(i), nil, &sa, unsafe.Sizeof(sa.sa_mask)) != 0 {
   435  		throw("rt_sigaction read failure")
   436  	}
   437  	return sa.sa_handler
   438  }
   439  
   440  // setSignaltstackSP sets the ss_sp field of a stackt.
   441  //go:nosplit
   442  func setSignalstackSP(s *stackt, sp uintptr) {
   443  	*(*uintptr)(unsafe.Pointer(&s.ss_sp)) = sp
   444  }
   445  
   446  func (c *sigctxt) fixsigcode(sig uint32) {
   447  }