github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/runtime/os_freebsd.go (about) 1 // Copyright 2011 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 "unsafe" 11 ) 12 13 type mOS struct{} 14 15 //go:noescape 16 func thr_new(param *thrparam, size int32) int32 17 18 //go:noescape 19 func sigaltstack(new, old *stackt) 20 21 //go:noescape 22 func sigprocmask(how int32, new, old *sigset) 23 24 //go:noescape 25 func setitimer(mode int32, new, old *itimerval) 26 27 //go:noescape 28 func sysctl(mib *uint32, miblen uint32, out *byte, size *uintptr, dst *byte, ndst uintptr) int32 29 30 func raiseproc(sig uint32) 31 32 func thr_self() thread 33 func thr_kill(tid thread, sig int) 34 35 //go:noescape 36 func sys_umtx_op(addr *uint32, mode int32, val uint32, uaddr1 uintptr, ut *umtx_time) int32 37 38 func osyield() 39 40 //go:nosplit 41 func osyield_no_g() { 42 osyield() 43 } 44 45 func kqueue() int32 46 47 //go:noescape 48 func kevent(kq int32, ch *keventt, nch int32, ev *keventt, nev int32, ts *timespec) int32 49 50 func pipe2(flags int32) (r, w int32, errno int32) 51 func closeonexec(fd int32) 52 53 // From FreeBSD's <sys/sysctl.h> 54 const ( 55 _CTL_HW = 6 56 _HW_PAGESIZE = 7 57 ) 58 59 var sigset_all = sigset{[4]uint32{^uint32(0), ^uint32(0), ^uint32(0), ^uint32(0)}} 60 61 // Undocumented numbers from FreeBSD's lib/libc/gen/sysctlnametomib.c. 62 const ( 63 _CTL_QUERY = 0 64 _CTL_QUERY_MIB = 3 65 ) 66 67 // sysctlnametomib fill mib with dynamically assigned sysctl entries of name, 68 // return count of effected mib slots, return 0 on error. 69 func sysctlnametomib(name []byte, mib *[_CTL_MAXNAME]uint32) uint32 { 70 oid := [2]uint32{_CTL_QUERY, _CTL_QUERY_MIB} 71 miblen := uintptr(_CTL_MAXNAME) 72 if sysctl(&oid[0], 2, (*byte)(unsafe.Pointer(mib)), &miblen, (*byte)(unsafe.Pointer(&name[0])), (uintptr)(len(name))) < 0 { 73 return 0 74 } 75 miblen /= unsafe.Sizeof(uint32(0)) 76 if miblen <= 0 { 77 return 0 78 } 79 return uint32(miblen) 80 } 81 82 const ( 83 _CPU_CURRENT_PID = -1 // Current process ID. 84 ) 85 86 //go:noescape 87 func cpuset_getaffinity(level int, which int, id int64, size int, mask *byte) int32 88 89 //go:systemstack 90 func getncpu() int32 { 91 // Use a large buffer for the CPU mask. We're on the system 92 // stack, so this is fine, and we can't allocate memory for a 93 // dynamically-sized buffer at this point. 94 const maxCPUs = 64 * 1024 95 var mask [maxCPUs / 8]byte 96 var mib [_CTL_MAXNAME]uint32 97 98 // According to FreeBSD's /usr/src/sys/kern/kern_cpuset.c, 99 // cpuset_getaffinity return ERANGE when provided buffer size exceed the limits in kernel. 100 // Querying kern.smp.maxcpus to calculate maximum buffer size. 101 // See https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=200802 102 103 // Variable kern.smp.maxcpus introduced at Dec 23 2003, revision 123766, 104 // with dynamically assigned sysctl entries. 105 miblen := sysctlnametomib([]byte("kern.smp.maxcpus"), &mib) 106 if miblen == 0 { 107 return 1 108 } 109 110 // Query kern.smp.maxcpus. 111 dstsize := uintptr(4) 112 maxcpus := uint32(0) 113 if sysctl(&mib[0], miblen, (*byte)(unsafe.Pointer(&maxcpus)), &dstsize, nil, 0) != 0 { 114 return 1 115 } 116 117 maskSize := int(maxcpus+7) / 8 118 if maskSize < goarch.PtrSize { 119 maskSize = goarch.PtrSize 120 } 121 if maskSize > len(mask) { 122 maskSize = len(mask) 123 } 124 125 if cpuset_getaffinity(_CPU_LEVEL_WHICH, _CPU_WHICH_PID, _CPU_CURRENT_PID, 126 maskSize, (*byte)(unsafe.Pointer(&mask[0]))) != 0 { 127 return 1 128 } 129 n := int32(0) 130 for _, v := range mask[:maskSize] { 131 for v != 0 { 132 n += int32(v & 1) 133 v >>= 1 134 } 135 } 136 if n == 0 { 137 return 1 138 } 139 return n 140 } 141 142 func getPageSize() uintptr { 143 mib := [2]uint32{_CTL_HW, _HW_PAGESIZE} 144 out := uint32(0) 145 nout := unsafe.Sizeof(out) 146 ret := sysctl(&mib[0], 2, (*byte)(unsafe.Pointer(&out)), &nout, nil, 0) 147 if ret >= 0 { 148 return uintptr(out) 149 } 150 return 0 151 } 152 153 // FreeBSD's umtx_op syscall is effectively the same as Linux's futex, and 154 // thus the code is largely similar. See Linux implementation 155 // and lock_futex.go for comments. 156 157 //go:nosplit 158 func futexsleep(addr *uint32, val uint32, ns int64) { 159 systemstack(func() { 160 futexsleep1(addr, val, ns) 161 }) 162 } 163 164 func futexsleep1(addr *uint32, val uint32, ns int64) { 165 var utp *umtx_time 166 if ns >= 0 { 167 var ut umtx_time 168 ut._clockid = _CLOCK_MONOTONIC 169 ut._timeout.setNsec(ns) 170 utp = &ut 171 } 172 ret := sys_umtx_op(addr, _UMTX_OP_WAIT_UINT_PRIVATE, val, unsafe.Sizeof(*utp), utp) 173 if ret >= 0 || ret == -_EINTR || ret == -_ETIMEDOUT { 174 return 175 } 176 print("umtx_wait addr=", addr, " val=", val, " ret=", ret, "\n") 177 *(*int32)(unsafe.Pointer(uintptr(0x1005))) = 0x1005 178 } 179 180 //go:nosplit 181 func futexwakeup(addr *uint32, cnt uint32) { 182 ret := sys_umtx_op(addr, _UMTX_OP_WAKE_PRIVATE, cnt, 0, nil) 183 if ret >= 0 { 184 return 185 } 186 187 systemstack(func() { 188 print("umtx_wake_addr=", addr, " ret=", ret, "\n") 189 }) 190 } 191 192 func thr_start() 193 194 // May run with m.p==nil, so write barriers are not allowed. 195 // 196 //go:nowritebarrier 197 func newosproc(mp *m) { 198 stk := unsafe.Pointer(mp.g0.stack.hi) 199 if false { 200 print("newosproc stk=", stk, " m=", mp, " g=", mp.g0, " thr_start=", abi.FuncPCABI0(thr_start), " id=", mp.id, " ostk=", &mp, "\n") 201 } 202 203 param := thrparam{ 204 start_func: abi.FuncPCABI0(thr_start), 205 arg: unsafe.Pointer(mp), 206 stack_base: mp.g0.stack.lo, 207 stack_size: uintptr(stk) - mp.g0.stack.lo, 208 child_tid: nil, // minit will record tid 209 parent_tid: nil, 210 tls_base: unsafe.Pointer(&mp.tls[0]), 211 tls_size: unsafe.Sizeof(mp.tls), 212 } 213 214 var oset sigset 215 sigprocmask(_SIG_SETMASK, &sigset_all, &oset) 216 ret := retryOnEAGAIN(func() int32 { 217 errno := thr_new(¶m, int32(unsafe.Sizeof(param))) 218 // thr_new returns negative errno 219 return -errno 220 }) 221 sigprocmask(_SIG_SETMASK, &oset, nil) 222 if ret != 0 { 223 print("runtime: failed to create new OS thread (have ", mcount(), " already; errno=", ret, ")\n") 224 throw("newosproc") 225 } 226 } 227 228 // Version of newosproc that doesn't require a valid G. 229 // 230 //go:nosplit 231 func newosproc0(stacksize uintptr, fn unsafe.Pointer) { 232 stack := sysAlloc(stacksize, &memstats.stacks_sys) 233 if stack == nil { 234 writeErrStr(failallocatestack) 235 exit(1) 236 } 237 // This code "knows" it's being called once from the library 238 // initialization code, and so it's using the static m0 for the 239 // tls and procid (thread) pointers. thr_new() requires the tls 240 // pointers, though the tid pointers can be nil. 241 // However, newosproc0 is currently unreachable because builds 242 // utilizing c-shared/c-archive force external linking. 243 param := thrparam{ 244 start_func: uintptr(fn), 245 arg: nil, 246 stack_base: uintptr(stack), //+stacksize? 247 stack_size: stacksize, 248 child_tid: nil, // minit will record tid 249 parent_tid: nil, 250 tls_base: unsafe.Pointer(&m0.tls[0]), 251 tls_size: unsafe.Sizeof(m0.tls), 252 } 253 254 var oset sigset 255 sigprocmask(_SIG_SETMASK, &sigset_all, &oset) 256 ret := thr_new(¶m, int32(unsafe.Sizeof(param))) 257 sigprocmask(_SIG_SETMASK, &oset, nil) 258 if ret < 0 { 259 writeErrStr(failthreadcreate) 260 exit(1) 261 } 262 } 263 264 // Called to do synchronous initialization of Go code built with 265 // -buildmode=c-archive or -buildmode=c-shared. 266 // None of the Go runtime is initialized. 267 // 268 //go:nosplit 269 //go:nowritebarrierrec 270 func libpreinit() { 271 initsig(true) 272 } 273 274 func osinit() { 275 ncpu = getncpu() 276 if physPageSize == 0 { 277 physPageSize = getPageSize() 278 } 279 } 280 281 var urandom_dev = []byte("/dev/urandom\x00") 282 283 //go:nosplit 284 func getRandomData(r []byte) { 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 initialize a new m (including the bootstrap m). 296 // Called on the parent thread (main thread in case of bootstrap), can allocate memory. 297 func mpreinit(mp *m) { 298 mp.gsignal = malg(32 * 1024) 299 mp.gsignal.m = mp 300 } 301 302 // Called to initialize a new m (including the bootstrap m). 303 // Called on the new thread, cannot allocate memory. 304 func minit() { 305 getg().m.procid = uint64(thr_self()) 306 307 // On FreeBSD before about April 2017 there was a bug such 308 // that calling execve from a thread other than the main 309 // thread did not reset the signal stack. That would confuse 310 // minitSignals, which calls minitSignalStack, which checks 311 // whether there is currently a signal stack and uses it if 312 // present. To avoid this confusion, explicitly disable the 313 // signal stack on the main thread when not running in a 314 // library. This can be removed when we are confident that all 315 // FreeBSD users are running a patched kernel. See issue #15658. 316 if gp := getg(); !isarchive && !islibrary && gp.m == &m0 && gp == gp.m.g0 { 317 st := stackt{ss_flags: _SS_DISABLE} 318 sigaltstack(&st, nil) 319 } 320 321 minitSignals() 322 } 323 324 // Called from dropm to undo the effect of an minit. 325 // 326 //go:nosplit 327 func unminit() { 328 unminitSignals() 329 } 330 331 // Called from exitm, but not from drop, to undo the effect of thread-owned 332 // resources in minit, semacreate, or elsewhere. Do not take locks after calling this. 333 func mdestroy(mp *m) { 334 } 335 336 func sigtramp() 337 338 type sigactiont struct { 339 sa_handler uintptr 340 sa_flags int32 341 sa_mask sigset 342 } 343 344 // See os_freebsd2.go, os_freebsd_amd64.go for setsig function 345 346 //go:nosplit 347 //go:nowritebarrierrec 348 func setsigstack(i uint32) { 349 var sa sigactiont 350 sigaction(i, nil, &sa) 351 if sa.sa_flags&_SA_ONSTACK != 0 { 352 return 353 } 354 sa.sa_flags |= _SA_ONSTACK 355 sigaction(i, &sa, nil) 356 } 357 358 //go:nosplit 359 //go:nowritebarrierrec 360 func getsig(i uint32) uintptr { 361 var sa sigactiont 362 sigaction(i, nil, &sa) 363 return sa.sa_handler 364 } 365 366 // setSignalstackSP sets the ss_sp field of a stackt. 367 // 368 //go:nosplit 369 func setSignalstackSP(s *stackt, sp uintptr) { 370 s.ss_sp = sp 371 } 372 373 //go:nosplit 374 //go:nowritebarrierrec 375 func sigaddset(mask *sigset, i int) { 376 mask.__bits[(i-1)/32] |= 1 << ((uint32(i) - 1) & 31) 377 } 378 379 func sigdelset(mask *sigset, i int) { 380 mask.__bits[(i-1)/32] &^= 1 << ((uint32(i) - 1) & 31) 381 } 382 383 //go:nosplit 384 func (c *sigctxt) fixsigcode(sig uint32) { 385 } 386 387 func setProcessCPUProfiler(hz int32) { 388 setProcessCPUProfilerTimer(hz) 389 } 390 391 func setThreadCPUProfiler(hz int32) { 392 setThreadCPUProfilerHz(hz) 393 } 394 395 //go:nosplit 396 func validSIGPROF(mp *m, c *sigctxt) bool { 397 return true 398 } 399 400 func sysargs(argc int32, argv **byte) { 401 n := argc + 1 402 403 // skip over argv, envp to get to auxv 404 for argv_index(argv, n) != nil { 405 n++ 406 } 407 408 // skip NULL separator 409 n++ 410 411 // now argv+n is auxv 412 auxvp := (*[1 << 28]uintptr)(add(unsafe.Pointer(argv), uintptr(n)*goarch.PtrSize)) 413 pairs := sysauxv(auxvp[:]) 414 auxv = auxvp[: pairs*2 : pairs*2] 415 } 416 417 const ( 418 _AT_NULL = 0 // Terminates the vector 419 _AT_PAGESZ = 6 // Page size in bytes 420 _AT_TIMEKEEP = 22 // Pointer to timehands. 421 _AT_HWCAP = 25 // CPU feature flags 422 _AT_HWCAP2 = 26 // CPU feature flags 2 423 ) 424 425 func sysauxv(auxv []uintptr) (pairs int) { 426 var i int 427 for i = 0; auxv[i] != _AT_NULL; i += 2 { 428 tag, val := auxv[i], auxv[i+1] 429 switch tag { 430 // _AT_NCPUS from auxv shouldn't be used due to golang.org/issue/15206 431 case _AT_PAGESZ: 432 physPageSize = val 433 case _AT_TIMEKEEP: 434 timekeepSharedPage = (*vdsoTimekeep)(unsafe.Pointer(val)) 435 } 436 437 archauxv(tag, val) 438 } 439 return i / 2 440 } 441 442 // sysSigaction calls the sigaction system call. 443 // 444 //go:nosplit 445 func sysSigaction(sig uint32, new, old *sigactiont) { 446 // Use system stack to avoid split stack overflow on amd64 447 if asmSigaction(uintptr(sig), new, old) != 0 { 448 systemstack(func() { 449 throw("sigaction failed") 450 }) 451 } 452 } 453 454 // asmSigaction is implemented in assembly. 455 // 456 //go:noescape 457 func asmSigaction(sig uintptr, new, old *sigactiont) int32 458 459 // raise sends a signal to the calling thread. 460 // 461 // It must be nosplit because it is used by the signal handler before 462 // it definitely has a Go stack. 463 // 464 //go:nosplit 465 func raise(sig uint32) { 466 thr_kill(thr_self(), int(sig)) 467 } 468 469 func signalM(mp *m, sig int) { 470 thr_kill(thread(mp.procid), sig) 471 } 472 473 // sigPerThreadSyscall is only used on linux, so we assign a bogus signal 474 // number. 475 const sigPerThreadSyscall = 1 << 31 476 477 //go:nosplit 478 func runPerThreadSyscall() { 479 throw("runPerThreadSyscall only valid on linux") 480 }