github.com/q45/go@v0.0.0-20151101211701-a4fb8c13db3f/src/runtime/os1_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 "unsafe"
     8  
     9  var sigset_all sigset = sigset{^uint32(0), ^uint32(0)}
    10  
    11  // Linux futex.
    12  //
    13  //	futexsleep(uint32 *addr, uint32 val)
    14  //	futexwakeup(uint32 *addr)
    15  //
    16  // Futexsleep atomically checks if *addr == val and if so, sleeps on addr.
    17  // Futexwakeup wakes up threads sleeping on addr.
    18  // Futexsleep is allowed to wake up spuriously.
    19  
    20  const (
    21  	_FUTEX_WAIT = 0
    22  	_FUTEX_WAKE = 1
    23  )
    24  
    25  // Atomically,
    26  //	if(*addr == val) sleep
    27  // Might be woken up spuriously; that's allowed.
    28  // Don't sleep longer than ns; ns < 0 means forever.
    29  //go:nosplit
    30  func futexsleep(addr *uint32, val uint32, ns int64) {
    31  	var ts timespec
    32  
    33  	// Some Linux kernels have a bug where futex of
    34  	// FUTEX_WAIT returns an internal error code
    35  	// as an errno.  Libpthread ignores the return value
    36  	// here, and so can we: as it says a few lines up,
    37  	// spurious wakeups are allowed.
    38  	if ns < 0 {
    39  		futex(unsafe.Pointer(addr), _FUTEX_WAIT, val, nil, nil, 0)
    40  		return
    41  	}
    42  
    43  	// It's difficult to live within the no-split stack limits here.
    44  	// On ARM and 386, a 64-bit divide invokes a general software routine
    45  	// that needs more stack than we can afford. So we use timediv instead.
    46  	// But on real 64-bit systems, where words are larger but the stack limit
    47  	// is not, even timediv is too heavy, and we really need to use just an
    48  	// ordinary machine instruction.
    49  	if ptrSize == 8 {
    50  		ts.set_sec(ns / 1000000000)
    51  		ts.set_nsec(int32(ns % 1000000000))
    52  	} else {
    53  		ts.tv_nsec = 0
    54  		ts.set_sec(int64(timediv(ns, 1000000000, (*int32)(unsafe.Pointer(&ts.tv_nsec)))))
    55  	}
    56  	futex(unsafe.Pointer(addr), _FUTEX_WAIT, val, unsafe.Pointer(&ts), nil, 0)
    57  }
    58  
    59  // If any procs are sleeping on addr, wake up at most cnt.
    60  //go:nosplit
    61  func futexwakeup(addr *uint32, cnt uint32) {
    62  	ret := futex(unsafe.Pointer(addr), _FUTEX_WAKE, cnt, nil, nil, 0)
    63  	if ret >= 0 {
    64  		return
    65  	}
    66  
    67  	// I don't know that futex wakeup can return
    68  	// EAGAIN or EINTR, but if it does, it would be
    69  	// safe to loop and call futex again.
    70  	systemstack(func() {
    71  		print("futexwakeup addr=", addr, " returned ", ret, "\n")
    72  	})
    73  
    74  	*(*int32)(unsafe.Pointer(uintptr(0x1006))) = 0x1006
    75  }
    76  
    77  func getproccount() int32 {
    78  	// This buffer is huge (8 kB) but we are on the system stack
    79  	// and there should be plenty of space (64 kB).
    80  	// Also this is a leaf, so we're not holding up the memory for long.
    81  	// See golang.org/issue/11823.
    82  	// The suggested behavior here is to keep trying with ever-larger
    83  	// buffers, but we don't have a dynamic memory allocator at the
    84  	// moment, so that's a bit tricky and seems like overkill.
    85  	const maxCPUs = 64 * 1024
    86  	var buf [maxCPUs / (ptrSize * 8)]uintptr
    87  	r := sched_getaffinity(0, unsafe.Sizeof(buf), &buf[0])
    88  	n := int32(0)
    89  	for _, v := range buf[:r/ptrSize] {
    90  		for v != 0 {
    91  			n += int32(v & 1)
    92  			v >>= 1
    93  		}
    94  	}
    95  	if n == 0 {
    96  		n = 1
    97  	}
    98  	return n
    99  }
   100  
   101  // Clone, the Linux rfork.
   102  const (
   103  	_CLONE_VM             = 0x100
   104  	_CLONE_FS             = 0x200
   105  	_CLONE_FILES          = 0x400
   106  	_CLONE_SIGHAND        = 0x800
   107  	_CLONE_PTRACE         = 0x2000
   108  	_CLONE_VFORK          = 0x4000
   109  	_CLONE_PARENT         = 0x8000
   110  	_CLONE_THREAD         = 0x10000
   111  	_CLONE_NEWNS          = 0x20000
   112  	_CLONE_SYSVSEM        = 0x40000
   113  	_CLONE_SETTLS         = 0x80000
   114  	_CLONE_PARENT_SETTID  = 0x100000
   115  	_CLONE_CHILD_CLEARTID = 0x200000
   116  	_CLONE_UNTRACED       = 0x800000
   117  	_CLONE_CHILD_SETTID   = 0x1000000
   118  	_CLONE_STOPPED        = 0x2000000
   119  	_CLONE_NEWUTS         = 0x4000000
   120  	_CLONE_NEWIPC         = 0x8000000
   121  
   122  	cloneFlags = _CLONE_VM | /* share memory */
   123  		_CLONE_FS | /* share cwd, etc */
   124  		_CLONE_FILES | /* share fd table */
   125  		_CLONE_SIGHAND | /* share sig handler table */
   126  		_CLONE_THREAD /* revisit - okay for now */
   127  )
   128  
   129  // May run with m.p==nil, so write barriers are not allowed.
   130  //go:nowritebarrier
   131  func newosproc(mp *m, stk unsafe.Pointer) {
   132  	/*
   133  	 * note: strace gets confused if we use CLONE_PTRACE here.
   134  	 */
   135  	mp.tls[0] = uintptr(mp.id) // so 386 asm can find it
   136  	if false {
   137  		print("newosproc stk=", stk, " m=", mp, " g=", mp.g0, " clone=", funcPC(clone), " id=", mp.id, "/", mp.tls[0], " ostk=", &mp, "\n")
   138  	}
   139  
   140  	// Disable signals during clone, so that the new thread starts
   141  	// with signals disabled.  It will enable them in minit.
   142  	var oset sigset
   143  	rtsigprocmask(_SIG_SETMASK, &sigset_all, &oset, int32(unsafe.Sizeof(oset)))
   144  	ret := clone(cloneFlags, stk, unsafe.Pointer(mp), unsafe.Pointer(mp.g0), unsafe.Pointer(funcPC(mstart)))
   145  	rtsigprocmask(_SIG_SETMASK, &oset, nil, int32(unsafe.Sizeof(oset)))
   146  
   147  	if ret < 0 {
   148  		print("runtime: failed to create new OS thread (have ", mcount(), " already; errno=", -ret, ")\n")
   149  		throw("newosproc")
   150  	}
   151  }
   152  
   153  // Version of newosproc that doesn't require a valid G.
   154  //go:nosplit
   155  func newosproc0(stacksize uintptr, fn unsafe.Pointer) {
   156  	stack := sysAlloc(stacksize, &memstats.stacks_sys)
   157  	if stack == nil {
   158  		write(2, unsafe.Pointer(&failallocatestack[0]), int32(len(failallocatestack)))
   159  		exit(1)
   160  	}
   161  	ret := clone(cloneFlags, unsafe.Pointer(uintptr(stack)+stacksize), nil, nil, fn)
   162  	if ret < 0 {
   163  		write(2, unsafe.Pointer(&failthreadcreate[0]), int32(len(failthreadcreate)))
   164  		exit(1)
   165  	}
   166  }
   167  
   168  var failallocatestack = []byte("runtime: failed to allocate stack for the new OS thread\n")
   169  var failthreadcreate = []byte("runtime: failed to create new OS thread\n")
   170  
   171  func osinit() {
   172  	ncpu = getproccount()
   173  }
   174  
   175  var urandom_dev = []byte("/dev/urandom\x00")
   176  
   177  func getRandomData(r []byte) {
   178  	if startupRandomData != nil {
   179  		n := copy(r, startupRandomData)
   180  		extendRandom(r, n)
   181  		return
   182  	}
   183  	fd := open(&urandom_dev[0], 0 /* O_RDONLY */, 0)
   184  	n := read(fd, unsafe.Pointer(&r[0]), int32(len(r)))
   185  	closefd(fd)
   186  	extendRandom(r, int(n))
   187  }
   188  
   189  func goenvs() {
   190  	goenvs_unix()
   191  }
   192  
   193  // Called to initialize a new m (including the bootstrap m).
   194  // Called on the parent thread (main thread in case of bootstrap), can allocate memory.
   195  func mpreinit(mp *m) {
   196  	mp.gsignal = malg(32 * 1024) // Linux wants >= 2K
   197  	mp.gsignal.m = mp
   198  }
   199  
   200  func msigsave(mp *m) {
   201  	smask := (*sigset)(unsafe.Pointer(&mp.sigmask))
   202  	if unsafe.Sizeof(*smask) > unsafe.Sizeof(mp.sigmask) {
   203  		throw("insufficient storage for signal mask")
   204  	}
   205  	rtsigprocmask(_SIG_SETMASK, nil, smask, int32(unsafe.Sizeof(*smask)))
   206  }
   207  
   208  func gettid() uint32
   209  
   210  // Called to initialize a new m (including the bootstrap m).
   211  // Called on the new thread, can not allocate memory.
   212  func minit() {
   213  	// Initialize signal handling.
   214  	_g_ := getg()
   215  	signalstack(&_g_.m.gsignal.stack)
   216  
   217  	// for debuggers, in case cgo created the thread
   218  	_g_.m.procid = uint64(gettid())
   219  
   220  	// restore signal mask from m.sigmask and unblock essential signals
   221  	nmask := *(*sigset)(unsafe.Pointer(&_g_.m.sigmask))
   222  	for i := range sigtable {
   223  		if sigtable[i].flags&_SigUnblock != 0 {
   224  			nmask[(i-1)/32] &^= 1 << ((uint32(i) - 1) & 31)
   225  		}
   226  	}
   227  	rtsigprocmask(_SIG_SETMASK, &nmask, nil, int32(unsafe.Sizeof(nmask)))
   228  }
   229  
   230  // Called from dropm to undo the effect of an minit.
   231  func unminit() {
   232  	_g_ := getg()
   233  	smask := (*sigset)(unsafe.Pointer(&_g_.m.sigmask))
   234  	rtsigprocmask(_SIG_SETMASK, smask, nil, int32(unsafe.Sizeof(*smask)))
   235  	signalstack(nil)
   236  }
   237  
   238  func memlimit() uintptr {
   239  	/*
   240  		TODO: Convert to Go when something actually uses the result.
   241  
   242  		Rlimit rl;
   243  		extern byte runtime·text[], runtime·end[];
   244  		uintptr used;
   245  
   246  		if(runtime·getrlimit(RLIMIT_AS, &rl) != 0)
   247  			return 0;
   248  		if(rl.rlim_cur >= 0x7fffffff)
   249  			return 0;
   250  
   251  		// Estimate our VM footprint excluding the heap.
   252  		// Not an exact science: use size of binary plus
   253  		// some room for thread stacks.
   254  		used = runtime·end - runtime·text + (64<<20);
   255  		if(used >= rl.rlim_cur)
   256  			return 0;
   257  
   258  		// If there's not at least 16 MB left, we're probably
   259  		// not going to be able to do much.  Treat as no limit.
   260  		rl.rlim_cur -= used;
   261  		if(rl.rlim_cur < (16<<20))
   262  			return 0;
   263  
   264  		return rl.rlim_cur - used;
   265  	*/
   266  
   267  	return 0
   268  }
   269  
   270  //#ifdef GOARCH_386
   271  //#define sa_handler k_sa_handler
   272  //#endif
   273  
   274  func sigreturn()
   275  func sigtramp()
   276  
   277  func setsig(i int32, fn uintptr, restart bool) {
   278  	var sa sigactiont
   279  	memclr(unsafe.Pointer(&sa), unsafe.Sizeof(sa))
   280  	sa.sa_flags = _SA_SIGINFO | _SA_ONSTACK | _SA_RESTORER
   281  	if restart {
   282  		sa.sa_flags |= _SA_RESTART
   283  	}
   284  	sa.sa_mask = ^uint64(0)
   285  	// Although Linux manpage says "sa_restorer element is obsolete and
   286  	// should not be used". x86_64 kernel requires it. Only use it on
   287  	// x86.
   288  	if GOARCH == "386" || GOARCH == "amd64" {
   289  		sa.sa_restorer = funcPC(sigreturn)
   290  	}
   291  	if fn == funcPC(sighandler) {
   292  		fn = funcPC(sigtramp)
   293  	}
   294  	sa.sa_handler = fn
   295  	if rt_sigaction(uintptr(i), &sa, nil, unsafe.Sizeof(sa.sa_mask)) != 0 {
   296  		throw("rt_sigaction failure")
   297  	}
   298  }
   299  
   300  func setsigstack(i int32) {
   301  	var sa sigactiont
   302  	if rt_sigaction(uintptr(i), nil, &sa, unsafe.Sizeof(sa.sa_mask)) != 0 {
   303  		throw("rt_sigaction failure")
   304  	}
   305  	if sa.sa_handler == 0 || sa.sa_handler == _SIG_DFL || sa.sa_handler == _SIG_IGN || sa.sa_flags&_SA_ONSTACK != 0 {
   306  		return
   307  	}
   308  	sa.sa_flags |= _SA_ONSTACK
   309  	if rt_sigaction(uintptr(i), &sa, nil, unsafe.Sizeof(sa.sa_mask)) != 0 {
   310  		throw("rt_sigaction failure")
   311  	}
   312  }
   313  
   314  func getsig(i int32) uintptr {
   315  	var sa sigactiont
   316  
   317  	memclr(unsafe.Pointer(&sa), unsafe.Sizeof(sa))
   318  	if rt_sigaction(uintptr(i), nil, &sa, unsafe.Sizeof(sa.sa_mask)) != 0 {
   319  		throw("rt_sigaction read failure")
   320  	}
   321  	if sa.sa_handler == funcPC(sigtramp) {
   322  		return funcPC(sighandler)
   323  	}
   324  	return sa.sa_handler
   325  }
   326  
   327  func signalstack(s *stack) {
   328  	var st sigaltstackt
   329  	if s == nil {
   330  		st.ss_flags = _SS_DISABLE
   331  	} else {
   332  		st.ss_sp = (*byte)(unsafe.Pointer(s.lo))
   333  		st.ss_size = s.hi - s.lo
   334  		st.ss_flags = 0
   335  	}
   336  	sigaltstack(&st, nil)
   337  }
   338  
   339  func updatesigmask(m sigmask) {
   340  	var mask sigset
   341  	copy(mask[:], m[:])
   342  	rtsigprocmask(_SIG_SETMASK, &mask, nil, int32(unsafe.Sizeof(mask)))
   343  }
   344  
   345  func unblocksig(sig int32) {
   346  	var mask sigset
   347  	mask[(sig-1)/32] |= 1 << ((uint32(sig) - 1) & 31)
   348  	rtsigprocmask(_SIG_UNBLOCK, &mask, nil, int32(unsafe.Sizeof(mask)))
   349  }