Black Lives Matter. Support the Equal Justice Initiative.

Source file src/runtime/runtime2.go

Documentation: runtime

     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/cpu"
     9  	"runtime/internal/atomic"
    10  	"runtime/internal/sys"
    11  	"unsafe"
    12  )
    13  
    14  // defined constants
    15  const (
    16  	// G status
    17  	//
    18  	// Beyond indicating the general state of a G, the G status
    19  	// acts like a lock on the goroutine's stack (and hence its
    20  	// ability to execute user code).
    21  	//
    22  	// If you add to this list, add to the list
    23  	// of "okay during garbage collection" status
    24  	// in mgcmark.go too.
    25  	//
    26  	// TODO(austin): The _Gscan bit could be much lighter-weight.
    27  	// For example, we could choose not to run _Gscanrunnable
    28  	// goroutines found in the run queue, rather than CAS-looping
    29  	// until they become _Grunnable. And transitions like
    30  	// _Gscanwaiting -> _Gscanrunnable are actually okay because
    31  	// they don't affect stack ownership.
    32  
    33  	// _Gidle means this goroutine was just allocated and has not
    34  	// yet been initialized.
    35  	_Gidle = iota // 0
    36  
    37  	// _Grunnable means this goroutine is on a run queue. It is
    38  	// not currently executing user code. The stack is not owned.
    39  	_Grunnable // 1
    40  
    41  	// _Grunning means this goroutine may execute user code. The
    42  	// stack is owned by this goroutine. It is not on a run queue.
    43  	// It is assigned an M and a P (g.m and g.m.p are valid).
    44  	_Grunning // 2
    45  
    46  	// _Gsyscall means this goroutine is executing a system call.
    47  	// It is not executing user code. The stack is owned by this
    48  	// goroutine. It is not on a run queue. It is assigned an M.
    49  	_Gsyscall // 3
    50  
    51  	// _Gwaiting means this goroutine is blocked in the runtime.
    52  	// It is not executing user code. It is not on a run queue,
    53  	// but should be recorded somewhere (e.g., a channel wait
    54  	// queue) so it can be ready()d when necessary. The stack is
    55  	// not owned *except* that a channel operation may read or
    56  	// write parts of the stack under the appropriate channel
    57  	// lock. Otherwise, it is not safe to access the stack after a
    58  	// goroutine enters _Gwaiting (e.g., it may get moved).
    59  	_Gwaiting // 4
    60  
    61  	// _Gmoribund_unused is currently unused, but hardcoded in gdb
    62  	// scripts.
    63  	_Gmoribund_unused // 5
    64  
    65  	// _Gdead means this goroutine is currently unused. It may be
    66  	// just exited, on a free list, or just being initialized. It
    67  	// is not executing user code. It may or may not have a stack
    68  	// allocated. The G and its stack (if any) are owned by the M
    69  	// that is exiting the G or that obtained the G from the free
    70  	// list.
    71  	_Gdead // 6
    72  
    73  	// _Genqueue_unused is currently unused.
    74  	_Genqueue_unused // 7
    75  
    76  	// _Gcopystack means this goroutine's stack is being moved. It
    77  	// is not executing user code and is not on a run queue. The
    78  	// stack is owned by the goroutine that put it in _Gcopystack.
    79  	_Gcopystack // 8
    80  
    81  	// _Gpreempted means this goroutine stopped itself for a
    82  	// suspendG preemption. It is like _Gwaiting, but nothing is
    83  	// yet responsible for ready()ing it. Some suspendG must CAS
    84  	// the status to _Gwaiting to take responsibility for
    85  	// ready()ing this G.
    86  	_Gpreempted // 9
    87  
    88  	// _Gscan combined with one of the above states other than
    89  	// _Grunning indicates that GC is scanning the stack. The
    90  	// goroutine is not executing user code and the stack is owned
    91  	// by the goroutine that set the _Gscan bit.
    92  	//
    93  	// _Gscanrunning is different: it is used to briefly block
    94  	// state transitions while GC signals the G to scan its own
    95  	// stack. This is otherwise like _Grunning.
    96  	//
    97  	// atomicstatus&~Gscan gives the state the goroutine will
    98  	// return to when the scan completes.
    99  	_Gscan          = 0x1000
   100  	_Gscanrunnable  = _Gscan + _Grunnable  // 0x1001
   101  	_Gscanrunning   = _Gscan + _Grunning   // 0x1002
   102  	_Gscansyscall   = _Gscan + _Gsyscall   // 0x1003
   103  	_Gscanwaiting   = _Gscan + _Gwaiting   // 0x1004
   104  	_Gscanpreempted = _Gscan + _Gpreempted // 0x1009
   105  )
   106  
   107  const (
   108  	// P status
   109  
   110  	// _Pidle means a P is not being used to run user code or the
   111  	// scheduler. Typically, it's on the idle P list and available
   112  	// to the scheduler, but it may just be transitioning between
   113  	// other states.
   114  	//
   115  	// The P is owned by the idle list or by whatever is
   116  	// transitioning its state. Its run queue is empty.
   117  	_Pidle = iota
   118  
   119  	// _Prunning means a P is owned by an M and is being used to
   120  	// run user code or the scheduler. Only the M that owns this P
   121  	// is allowed to change the P's status from _Prunning. The M
   122  	// may transition the P to _Pidle (if it has no more work to
   123  	// do), _Psyscall (when entering a syscall), or _Pgcstop (to
   124  	// halt for the GC). The M may also hand ownership of the P
   125  	// off directly to another M (e.g., to schedule a locked G).
   126  	_Prunning
   127  
   128  	// _Psyscall means a P is not running user code. It has
   129  	// affinity to an M in a syscall but is not owned by it and
   130  	// may be stolen by another M. This is similar to _Pidle but
   131  	// uses lightweight transitions and maintains M affinity.
   132  	//
   133  	// Leaving _Psyscall must be done with a CAS, either to steal
   134  	// or retake the P. Note that there's an ABA hazard: even if
   135  	// an M successfully CASes its original P back to _Prunning
   136  	// after a syscall, it must understand the P may have been
   137  	// used by another M in the interim.
   138  	_Psyscall
   139  
   140  	// _Pgcstop means a P is halted for STW and owned by the M
   141  	// that stopped the world. The M that stopped the world
   142  	// continues to use its P, even in _Pgcstop. Transitioning
   143  	// from _Prunning to _Pgcstop causes an M to release its P and
   144  	// park.
   145  	//
   146  	// The P retains its run queue and startTheWorld will restart
   147  	// the scheduler on Ps with non-empty run queues.
   148  	_Pgcstop
   149  
   150  	// _Pdead means a P is no longer used (GOMAXPROCS shrank). We
   151  	// reuse Ps if GOMAXPROCS increases. A dead P is mostly
   152  	// stripped of its resources, though a few things remain
   153  	// (e.g., trace buffers).
   154  	_Pdead
   155  )
   156  
   157  // Mutual exclusion locks.  In the uncontended case,
   158  // as fast as spin locks (just a few user-level instructions),
   159  // but on the contention path they sleep in the kernel.
   160  // A zeroed Mutex is unlocked (no need to initialize each lock).
   161  // Initialization is helpful for static lock ranking, but not required.
   162  type mutex struct {
   163  	// Empty struct if lock ranking is disabled, otherwise includes the lock rank
   164  	lockRankStruct
   165  	// Futex-based impl treats it as uint32 key,
   166  	// while sema-based impl as M* waitm.
   167  	// Used to be a union, but unions break precise GC.
   168  	key uintptr
   169  }
   170  
   171  // sleep and wakeup on one-time events.
   172  // before any calls to notesleep or notewakeup,
   173  // must call noteclear to initialize the Note.
   174  // then, exactly one thread can call notesleep
   175  // and exactly one thread can call notewakeup (once).
   176  // once notewakeup has been called, the notesleep
   177  // will return.  future notesleep will return immediately.
   178  // subsequent noteclear must be called only after
   179  // previous notesleep has returned, e.g. it's disallowed
   180  // to call noteclear straight after notewakeup.
   181  //
   182  // notetsleep is like notesleep but wakes up after
   183  // a given number of nanoseconds even if the event
   184  // has not yet happened.  if a goroutine uses notetsleep to
   185  // wake up early, it must wait to call noteclear until it
   186  // can be sure that no other goroutine is calling
   187  // notewakeup.
   188  //
   189  // notesleep/notetsleep are generally called on g0,
   190  // notetsleepg is similar to notetsleep but is called on user g.
   191  type note struct {
   192  	// Futex-based impl treats it as uint32 key,
   193  	// while sema-based impl as M* waitm.
   194  	// Used to be a union, but unions break precise GC.
   195  	key uintptr
   196  }
   197  
   198  type funcval struct {
   199  	fn uintptr
   200  	// variable-size, fn-specific data here
   201  }
   202  
   203  type iface struct {
   204  	tab  *itab
   205  	data unsafe.Pointer
   206  }
   207  
   208  type eface struct {
   209  	_type *_type
   210  	data  unsafe.Pointer
   211  }
   212  
   213  func efaceOf(ep *interface{}) *eface {
   214  	return (*eface)(unsafe.Pointer(ep))
   215  }
   216  
   217  // The guintptr, muintptr, and puintptr are all used to bypass write barriers.
   218  // It is particularly important to avoid write barriers when the current P has
   219  // been released, because the GC thinks the world is stopped, and an
   220  // unexpected write barrier would not be synchronized with the GC,
   221  // which can lead to a half-executed write barrier that has marked the object
   222  // but not queued it. If the GC skips the object and completes before the
   223  // queuing can occur, it will incorrectly free the object.
   224  //
   225  // We tried using special assignment functions invoked only when not
   226  // holding a running P, but then some updates to a particular memory
   227  // word went through write barriers and some did not. This breaks the
   228  // write barrier shadow checking mode, and it is also scary: better to have
   229  // a word that is completely ignored by the GC than to have one for which
   230  // only a few updates are ignored.
   231  //
   232  // Gs and Ps are always reachable via true pointers in the
   233  // allgs and allp lists or (during allocation before they reach those lists)
   234  // from stack variables.
   235  //
   236  // Ms are always reachable via true pointers either from allm or
   237  // freem. Unlike Gs and Ps we do free Ms, so it's important that
   238  // nothing ever hold an muintptr across a safe point.
   239  
   240  // A guintptr holds a goroutine pointer, but typed as a uintptr
   241  // to bypass write barriers. It is used in the Gobuf goroutine state
   242  // and in scheduling lists that are manipulated without a P.
   243  //
   244  // The Gobuf.g goroutine pointer is almost always updated by assembly code.
   245  // In one of the few places it is updated by Go code - func save - it must be
   246  // treated as a uintptr to avoid a write barrier being emitted at a bad time.
   247  // Instead of figuring out how to emit the write barriers missing in the
   248  // assembly manipulation, we change the type of the field to uintptr,
   249  // so that it does not require write barriers at all.
   250  //
   251  // Goroutine structs are published in the allg list and never freed.
   252  // That will keep the goroutine structs from being collected.
   253  // There is never a time that Gobuf.g's contain the only references
   254  // to a goroutine: the publishing of the goroutine in allg comes first.
   255  // Goroutine pointers are also kept in non-GC-visible places like TLS,
   256  // so I can't see them ever moving. If we did want to start moving data
   257  // in the GC, we'd need to allocate the goroutine structs from an
   258  // alternate arena. Using guintptr doesn't make that problem any worse.
   259  type guintptr uintptr
   260  
   261  //go:nosplit
   262  func (gp guintptr) ptr() *g { return (*g)(unsafe.Pointer(gp)) }
   263  
   264  //go:nosplit
   265  func (gp *guintptr) set(g *g) { *gp = guintptr(unsafe.Pointer(g)) }
   266  
   267  //go:nosplit
   268  func (gp *guintptr) cas(old, new guintptr) bool {
   269  	return atomic.Casuintptr((*uintptr)(unsafe.Pointer(gp)), uintptr(old), uintptr(new))
   270  }
   271  
   272  // setGNoWB performs *gp = new without a write barrier.
   273  // For times when it's impractical to use a guintptr.
   274  //go:nosplit
   275  //go:nowritebarrier
   276  func setGNoWB(gp **g, new *g) {
   277  	(*guintptr)(unsafe.Pointer(gp)).set(new)
   278  }
   279  
   280  type puintptr uintptr
   281  
   282  //go:nosplit
   283  func (pp puintptr) ptr() *p { return (*p)(unsafe.Pointer(pp)) }
   284  
   285  //go:nosplit
   286  func (pp *puintptr) set(p *p) { *pp = puintptr(unsafe.Pointer(p)) }
   287  
   288  // muintptr is a *m that is not tracked by the garbage collector.
   289  //
   290  // Because we do free Ms, there are some additional constrains on
   291  // muintptrs:
   292  //
   293  // 1. Never hold an muintptr locally across a safe point.
   294  //
   295  // 2. Any muintptr in the heap must be owned by the M itself so it can
   296  //    ensure it is not in use when the last true *m is released.
   297  type muintptr uintptr
   298  
   299  //go:nosplit
   300  func (mp muintptr) ptr() *m { return (*m)(unsafe.Pointer(mp)) }
   301  
   302  //go:nosplit
   303  func (mp *muintptr) set(m *m) { *mp = muintptr(unsafe.Pointer(m)) }
   304  
   305  // setMNoWB performs *mp = new without a write barrier.
   306  // For times when it's impractical to use an muintptr.
   307  //go:nosplit
   308  //go:nowritebarrier
   309  func setMNoWB(mp **m, new *m) {
   310  	(*muintptr)(unsafe.Pointer(mp)).set(new)
   311  }
   312  
   313  type gobuf struct {
   314  	// The offsets of sp, pc, and g are known to (hard-coded in) libmach.
   315  	//
   316  	// ctxt is unusual with respect to GC: it may be a
   317  	// heap-allocated funcval, so GC needs to track it, but it
   318  	// needs to be set and cleared from assembly, where it's
   319  	// difficult to have write barriers. However, ctxt is really a
   320  	// saved, live register, and we only ever exchange it between
   321  	// the real register and the gobuf. Hence, we treat it as a
   322  	// root during stack scanning, which means assembly that saves
   323  	// and restores it doesn't need write barriers. It's still
   324  	// typed as a pointer so that any other writes from Go get
   325  	// write barriers.
   326  	sp   uintptr
   327  	pc   uintptr
   328  	g    guintptr
   329  	ctxt unsafe.Pointer
   330  	ret  sys.Uintreg
   331  	lr   uintptr
   332  	bp   uintptr // for GOEXPERIMENT=framepointer
   333  }
   334  
   335  // sudog represents a g in a wait list, such as for sending/receiving
   336  // on a channel.
   337  //
   338  // sudog is necessary because the g ↔ synchronization object relation
   339  // is many-to-many. A g can be on many wait lists, so there may be
   340  // many sudogs for one g; and many gs may be waiting on the same
   341  // synchronization object, so there may be many sudogs for one object.
   342  //
   343  // sudogs are allocated from a special pool. Use acquireSudog and
   344  // releaseSudog to allocate and free them.
   345  type sudog struct {
   346  	// The following fields are protected by the hchan.lock of the
   347  	// channel this sudog is blocking on. shrinkstack depends on
   348  	// this for sudogs involved in channel ops.
   349  
   350  	g *g
   351  
   352  	next *sudog
   353  	prev *sudog
   354  	elem unsafe.Pointer // data element (may point to stack)
   355  
   356  	// The following fields are never accessed concurrently.
   357  	// For channels, waitlink is only accessed by g.
   358  	// For semaphores, all fields (including the ones above)
   359  	// are only accessed when holding a semaRoot lock.
   360  
   361  	acquiretime int64
   362  	releasetime int64
   363  	ticket      uint32
   364  
   365  	// isSelect indicates g is participating in a select, so
   366  	// g.selectDone must be CAS'd to win the wake-up race.
   367  	isSelect bool
   368  
   369  	parent   *sudog // semaRoot binary tree
   370  	waitlink *sudog // g.waiting list or semaRoot
   371  	waittail *sudog // semaRoot
   372  	c        *hchan // channel
   373  }
   374  
   375  type libcall struct {
   376  	fn   uintptr
   377  	n    uintptr // number of parameters
   378  	args uintptr // parameters
   379  	r1   uintptr // return values
   380  	r2   uintptr
   381  	err  uintptr // error number
   382  }
   383  
   384  // describes how to handle callback
   385  type wincallbackcontext struct {
   386  	gobody       unsafe.Pointer // go function to call
   387  	argsize      uintptr        // callback arguments size (in bytes)
   388  	restorestack uintptr        // adjust stack on return by (in bytes) (386 only)
   389  	cleanstack   bool
   390  }
   391  
   392  // Stack describes a Go execution stack.
   393  // The bounds of the stack are exactly [lo, hi),
   394  // with no implicit data structures on either side.
   395  type stack struct {
   396  	lo uintptr
   397  	hi uintptr
   398  }
   399  
   400  // heldLockInfo gives info on a held lock and the rank of that lock
   401  type heldLockInfo struct {
   402  	lockAddr uintptr
   403  	rank     lockRank
   404  }
   405  
   406  type g struct {
   407  	// Stack parameters.
   408  	// stack describes the actual stack memory: [stack.lo, stack.hi).
   409  	// stackguard0 is the stack pointer compared in the Go stack growth prologue.
   410  	// It is stack.lo+StackGuard normally, but can be StackPreempt to trigger a preemption.
   411  	// stackguard1 is the stack pointer compared in the C stack growth prologue.
   412  	// It is stack.lo+StackGuard on g0 and gsignal stacks.
   413  	// It is ~0 on other goroutine stacks, to trigger a call to morestackc (and crash).
   414  	stack       stack   // offset known to runtime/cgo
   415  	stackguard0 uintptr // offset known to liblink
   416  	stackguard1 uintptr // offset known to liblink
   417  
   418  	_panic       *_panic // innermost panic - offset known to liblink
   419  	_defer       *_defer // innermost defer
   420  	m            *m      // current m; offset known to arm liblink
   421  	sched        gobuf
   422  	syscallsp    uintptr        // if status==Gsyscall, syscallsp = sched.sp to use during gc
   423  	syscallpc    uintptr        // if status==Gsyscall, syscallpc = sched.pc to use during gc
   424  	stktopsp     uintptr        // expected sp at top of stack, to check in traceback
   425  	param        unsafe.Pointer // passed parameter on wakeup
   426  	atomicstatus uint32
   427  	stackLock    uint32 // sigprof/scang lock; TODO: fold in to atomicstatus
   428  	goid         int64
   429  	schedlink    guintptr
   430  	waitsince    int64      // approx time when the g become blocked
   431  	waitreason   waitReason // if status==Gwaiting
   432  
   433  	preempt       bool // preemption signal, duplicates stackguard0 = stackpreempt
   434  	preemptStop   bool // transition to _Gpreempted on preemption; otherwise, just deschedule
   435  	preemptShrink bool // shrink stack at synchronous safe point
   436  
   437  	// asyncSafePoint is set if g is stopped at an asynchronous
   438  	// safe point. This means there are frames on the stack
   439  	// without precise pointer information.
   440  	asyncSafePoint bool
   441  
   442  	paniconfault bool // panic (instead of crash) on unexpected fault address
   443  	gcscandone   bool // g has scanned stack; protected by _Gscan bit in status
   444  	throwsplit   bool // must not split stack
   445  	// activeStackChans indicates that there are unlocked channels
   446  	// pointing into this goroutine's stack. If true, stack
   447  	// copying needs to acquire channel locks to protect these
   448  	// areas of the stack.
   449  	activeStackChans bool
   450  	// parkingOnChan indicates that the goroutine is about to
   451  	// park on a chansend or chanrecv. Used to signal an unsafe point
   452  	// for stack shrinking. It's a boolean value, but is updated atomically.
   453  	parkingOnChan uint8
   454  
   455  	raceignore     int8     // ignore race detection events
   456  	sysblocktraced bool     // StartTrace has emitted EvGoInSyscall about this goroutine
   457  	sysexitticks   int64    // cputicks when syscall has returned (for tracing)
   458  	traceseq       uint64   // trace event sequencer
   459  	tracelastp     puintptr // last P emitted an event for this goroutine
   460  	lockedm        muintptr
   461  	sig            uint32
   462  	writebuf       []byte
   463  	sigcode0       uintptr
   464  	sigcode1       uintptr
   465  	sigpc          uintptr
   466  	gopc           uintptr         // pc of go statement that created this goroutine
   467  	ancestors      *[]ancestorInfo // ancestor information goroutine(s) that created this goroutine (only used if debug.tracebackancestors)
   468  	startpc        uintptr         // pc of goroutine function
   469  	racectx        uintptr
   470  	waiting        *sudog         // sudog structures this g is waiting on (that have a valid elem ptr); in lock order
   471  	cgoCtxt        []uintptr      // cgo traceback context
   472  	labels         unsafe.Pointer // profiler labels
   473  	timer          *timer         // cached timer for time.Sleep
   474  	selectDone     uint32         // are we participating in a select and did someone win the race?
   475  
   476  	// Per-G GC state
   477  
   478  	// gcAssistBytes is this G's GC assist credit in terms of
   479  	// bytes allocated. If this is positive, then the G has credit
   480  	// to allocate gcAssistBytes bytes without assisting. If this
   481  	// is negative, then the G must correct this by performing
   482  	// scan work. We track this in bytes to make it fast to update
   483  	// and check for debt in the malloc hot path. The assist ratio
   484  	// determines how this corresponds to scan work debt.
   485  	gcAssistBytes int64
   486  }
   487  
   488  type m struct {
   489  	g0      *g     // goroutine with scheduling stack
   490  	morebuf gobuf  // gobuf arg to morestack
   491  	divmod  uint32 // div/mod denominator for arm - known to liblink
   492  
   493  	// Fields not known to debuggers.
   494  	procid        uint64       // for debuggers, but offset not hard-coded
   495  	gsignal       *g           // signal-handling g
   496  	goSigStack    gsignalStack // Go-allocated signal handling stack
   497  	sigmask       sigset       // storage for saved signal mask
   498  	tls           [6]uintptr   // thread-local storage (for x86 extern register)
   499  	mstartfn      func()
   500  	curg          *g       // current running goroutine
   501  	caughtsig     guintptr // goroutine running during fatal signal
   502  	p             puintptr // attached p for executing go code (nil if not executing go code)
   503  	nextp         puintptr
   504  	oldp          puintptr // the p that was attached before executing a syscall
   505  	id            int64
   506  	mallocing     int32
   507  	throwing      int32
   508  	preemptoff    string // if != "", keep curg running on this m
   509  	locks         int32
   510  	dying         int32
   511  	profilehz     int32
   512  	spinning      bool // m is out of work and is actively looking for work
   513  	blocked       bool // m is blocked on a note
   514  	newSigstack   bool // minit on C thread called sigaltstack
   515  	printlock     int8
   516  	incgo         bool   // m is executing a cgo call
   517  	freeWait      uint32 // if == 0, safe to free g0 and delete m (atomic)
   518  	fastrand      [2]uint32
   519  	needextram    bool
   520  	traceback     uint8
   521  	ncgocall      uint64      // number of cgo calls in total
   522  	ncgo          int32       // number of cgo calls currently in progress
   523  	cgoCallersUse uint32      // if non-zero, cgoCallers in use temporarily
   524  	cgoCallers    *cgoCallers // cgo traceback if crashing in cgo call
   525  	park          note
   526  	alllink       *m // on allm
   527  	schedlink     muintptr
   528  	lockedg       guintptr
   529  	createstack   [32]uintptr // stack that created this thread.
   530  	lockedExt     uint32      // tracking for external LockOSThread
   531  	lockedInt     uint32      // tracking for internal lockOSThread
   532  	nextwaitm     muintptr    // next m waiting for lock
   533  	waitunlockf   func(*g, unsafe.Pointer) bool
   534  	waitlock      unsafe.Pointer
   535  	waittraceev   byte
   536  	waittraceskip int
   537  	startingtrace bool
   538  	syscalltick   uint32
   539  	freelink      *m // on sched.freem
   540  
   541  	// these are here because they are too large to be on the stack
   542  	// of low-level NOSPLIT functions.
   543  	libcall   libcall
   544  	libcallpc uintptr // for cpu profiler
   545  	libcallsp uintptr
   546  	libcallg  guintptr
   547  	syscall   libcall // stores syscall parameters on windows
   548  
   549  	vdsoSP uintptr // SP for traceback while in VDSO call (0 if not in call)
   550  	vdsoPC uintptr // PC for traceback while in VDSO call
   551  
   552  	// preemptGen counts the number of completed preemption
   553  	// signals. This is used to detect when a preemption is
   554  	// requested, but fails. Accessed atomically.
   555  	preemptGen uint32
   556  
   557  	// Whether this is a pending preemption signal on this M.
   558  	// Accessed atomically.
   559  	signalPending uint32
   560  
   561  	dlogPerM
   562  
   563  	mOS
   564  
   565  	// Up to 10 locks held by this m, maintained by the lock ranking code.
   566  	locksHeldLen int
   567  	locksHeld    [10]heldLockInfo
   568  }
   569  
   570  type p struct {
   571  	id          int32
   572  	status      uint32 // one of pidle/prunning/...
   573  	link        puintptr
   574  	schedtick   uint32     // incremented on every scheduler call
   575  	syscalltick uint32     // incremented on every system call
   576  	sysmontick  sysmontick // last tick observed by sysmon
   577  	m           muintptr   // back-link to associated m (nil if idle)
   578  	mcache      *mcache
   579  	pcache      pageCache
   580  	raceprocctx uintptr
   581  
   582  	deferpool    [5][]*_defer // pool of available defer structs of different sizes (see panic.go)
   583  	deferpoolbuf [5][32]*_defer
   584  
   585  	// Cache of goroutine ids, amortizes accesses to runtime·sched.goidgen.
   586  	goidcache    uint64
   587  	goidcacheend uint64
   588  
   589  	// Queue of runnable goroutines. Accessed without lock.
   590  	runqhead uint32
   591  	runqtail uint32
   592  	runq     [256]guintptr
   593  	// runnext, if non-nil, is a runnable G that was ready'd by
   594  	// the current G and should be run next instead of what's in
   595  	// runq if there's time remaining in the running G's time
   596  	// slice. It will inherit the time left in the current time
   597  	// slice. If a set of goroutines is locked in a
   598  	// communicate-and-wait pattern, this schedules that set as a
   599  	// unit and eliminates the (potentially large) scheduling
   600  	// latency that otherwise arises from adding the ready'd
   601  	// goroutines to the end of the run queue.
   602  	runnext guintptr
   603  
   604  	// Available G's (status == Gdead)
   605  	gFree struct {
   606  		gList
   607  		n int32
   608  	}
   609  
   610  	sudogcache []*sudog
   611  	sudogbuf   [128]*sudog
   612  
   613  	// Cache of mspan objects from the heap.
   614  	mspancache struct {
   615  		// We need an explicit length here because this field is used
   616  		// in allocation codepaths where write barriers are not allowed,
   617  		// and eliminating the write barrier/keeping it eliminated from
   618  		// slice updates is tricky, moreso than just managing the length
   619  		// ourselves.
   620  		len int
   621  		buf [128]*mspan
   622  	}
   623  
   624  	tracebuf traceBufPtr
   625  
   626  	// traceSweep indicates the sweep events should be traced.
   627  	// This is used to defer the sweep start event until a span
   628  	// has actually been swept.
   629  	traceSweep bool
   630  	// traceSwept and traceReclaimed track the number of bytes
   631  	// swept and reclaimed by sweeping in the current sweep loop.
   632  	traceSwept, traceReclaimed uintptr
   633  
   634  	palloc persistentAlloc // per-P to avoid mutex
   635  
   636  	_ uint32 // Alignment for atomic fields below
   637  
   638  	// The when field of the first entry on the timer heap.
   639  	// This is updated using atomic functions.
   640  	// This is 0 if the timer heap is empty.
   641  	timer0When uint64
   642  
   643  	// Per-P GC state
   644  	gcAssistTime         int64    // Nanoseconds in assistAlloc
   645  	gcFractionalMarkTime int64    // Nanoseconds in fractional mark worker (atomic)
   646  	gcBgMarkWorker       guintptr // (atomic)
   647  	gcMarkWorkerMode     gcMarkWorkerMode
   648  
   649  	// gcMarkWorkerStartTime is the nanotime() at which this mark
   650  	// worker started.
   651  	gcMarkWorkerStartTime int64
   652  
   653  	// gcw is this P's GC work buffer cache. The work buffer is
   654  	// filled by write barriers, drained by mutator assists, and
   655  	// disposed on certain GC state transitions.
   656  	gcw gcWork
   657  
   658  	// wbBuf is this P's GC write barrier buffer.
   659  	//
   660  	// TODO: Consider caching this in the running G.
   661  	wbBuf wbBuf
   662  
   663  	runSafePointFn uint32 // if 1, run sched.safePointFn at next safe point
   664  
   665  	// Lock for timers. We normally access the timers while running
   666  	// on this P, but the scheduler can also do it from a different P.
   667  	timersLock mutex
   668  
   669  	// Actions to take at some time. This is used to implement the
   670  	// standard library's time package.
   671  	// Must hold timersLock to access.
   672  	timers []*timer
   673  
   674  	// Number of timers in P's heap.
   675  	// Modified using atomic instructions.
   676  	numTimers uint32
   677  
   678  	// Number of timerModifiedEarlier timers on P's heap.
   679  	// This should only be modified while holding timersLock,
   680  	// or while the timer status is in a transient state
   681  	// such as timerModifying.
   682  	adjustTimers uint32
   683  
   684  	// Number of timerDeleted timers in P's heap.
   685  	// Modified using atomic instructions.
   686  	deletedTimers uint32
   687  
   688  	// Race context used while executing timer functions.
   689  	timerRaceCtx uintptr
   690  
   691  	// preempt is set to indicate that this P should be enter the
   692  	// scheduler ASAP (regardless of what G is running on it).
   693  	preempt bool
   694  
   695  	pad cpu.CacheLinePad
   696  }
   697  
   698  type schedt struct {
   699  	// accessed atomically. keep at top to ensure alignment on 32-bit systems.
   700  	goidgen   uint64
   701  	lastpoll  uint64 // time of last network poll, 0 if currently polling
   702  	pollUntil uint64 // time to which current poll is sleeping
   703  
   704  	lock mutex
   705  
   706  	// When increasing nmidle, nmidlelocked, nmsys, or nmfreed, be
   707  	// sure to call checkdead().
   708  
   709  	midle        muintptr // idle m's waiting for work
   710  	nmidle       int32    // number of idle m's waiting for work
   711  	nmidlelocked int32    // number of locked m's waiting for work
   712  	mnext        int64    // number of m's that have been created and next M ID
   713  	maxmcount    int32    // maximum number of m's allowed (or die)
   714  	nmsys        int32    // number of system m's not counted for deadlock
   715  	nmfreed      int64    // cumulative number of freed m's
   716  
   717  	ngsys uint32 // number of system goroutines; updated atomically
   718  
   719  	pidle      puintptr // idle p's
   720  	npidle     uint32
   721  	nmspinning uint32 // See "Worker thread parking/unparking" comment in proc.go.
   722  
   723  	// Global runnable queue.
   724  	runq     gQueue
   725  	runqsize int32
   726  
   727  	// disable controls selective disabling of the scheduler.
   728  	//
   729  	// Use schedEnableUser to control this.
   730  	//
   731  	// disable is protected by sched.lock.
   732  	disable struct {
   733  		// user disables scheduling of user goroutines.
   734  		user     bool
   735  		runnable gQueue // pending runnable Gs
   736  		n        int32  // length of runnable
   737  	}
   738  
   739  	// Global cache of dead G's.
   740  	gFree struct {
   741  		lock    mutex
   742  		stack   gList // Gs with stacks
   743  		noStack gList // Gs without stacks
   744  		n       int32
   745  	}
   746  
   747  	// Central cache of sudog structs.
   748  	sudoglock  mutex
   749  	sudogcache *sudog
   750  
   751  	// Central pool of available defer structs of different sizes.
   752  	deferlock mutex
   753  	deferpool [5]*_defer
   754  
   755  	// freem is the list of m's waiting to be freed when their
   756  	// m.exited is set. Linked through m.freelink.
   757  	freem *m
   758  
   759  	gcwaiting  uint32 // gc is waiting to run
   760  	stopwait   int32
   761  	stopnote   note
   762  	sysmonwait uint32
   763  	sysmonnote note
   764  
   765  	// safepointFn should be called on each P at the next GC
   766  	// safepoint if p.runSafePointFn is set.
   767  	safePointFn   func(*p)
   768  	safePointWait int32
   769  	safePointNote note
   770  
   771  	profilehz int32 // cpu profiling rate
   772  
   773  	procresizetime int64 // nanotime() of last change to gomaxprocs
   774  	totaltime      int64 // ∫gomaxprocs dt up to procresizetime
   775  
   776  	// sysmonlock protects sysmon's actions on the runtime.
   777  	//
   778  	// Acquire and hold this mutex to block sysmon from interacting
   779  	// with the rest of the runtime.
   780  	sysmonlock mutex
   781  }
   782  
   783  // Values for the flags field of a sigTabT.
   784  const (
   785  	_SigNotify   = 1 << iota // let signal.Notify have signal, even if from kernel
   786  	_SigKill                 // if signal.Notify doesn't take it, exit quietly
   787  	_SigThrow                // if signal.Notify doesn't take it, exit loudly
   788  	_SigPanic                // if the signal is from the kernel, panic
   789  	_SigDefault              // if the signal isn't explicitly requested, don't monitor it
   790  	_SigGoExit               // cause all runtime procs to exit (only used on Plan 9).
   791  	_SigSetStack             // add SA_ONSTACK to libc handler
   792  	_SigUnblock              // always unblock; see blockableSig
   793  	_SigIgn                  // _SIG_DFL action is to ignore the signal
   794  )
   795  
   796  // Layout of in-memory per-function information prepared by linker
   797  // See https://golang.org/s/go12symtab.
   798  // Keep in sync with linker (../cmd/link/internal/ld/pcln.go:/pclntab)
   799  // and with package debug/gosym and with symtab.go in package runtime.
   800  type _func struct {
   801  	entry   uintptr // start pc
   802  	nameoff int32   // function name
   803  
   804  	args        int32  // in/out args size
   805  	deferreturn uint32 // offset of start of a deferreturn call instruction from entry, if any.
   806  
   807  	pcsp      int32
   808  	pcfile    int32
   809  	pcln      int32
   810  	npcdata   int32
   811  	funcID    funcID  // set for certain special runtime functions
   812  	_         [2]int8 // unused
   813  	nfuncdata uint8   // must be last
   814  }
   815  
   816  // Pseudo-Func that is returned for PCs that occur in inlined code.
   817  // A *Func can be either a *_func or a *funcinl, and they are distinguished
   818  // by the first uintptr.
   819  type funcinl struct {
   820  	zero  uintptr // set to 0 to distinguish from _func
   821  	entry uintptr // entry of the real (the "outermost") frame.
   822  	name  string
   823  	file  string
   824  	line  int
   825  }
   826  
   827  // layout of Itab known to compilers
   828  // allocated in non-garbage-collected memory
   829  // Needs to be in sync with
   830  // ../cmd/compile/internal/gc/reflect.go:/^func.dumptabs.
   831  type itab struct {
   832  	inter *interfacetype
   833  	_type *_type
   834  	hash  uint32 // copy of _type.hash. Used for type switches.
   835  	_     [4]byte
   836  	fun   [1]uintptr // variable sized. fun[0]==0 means _type does not implement inter.
   837  }
   838  
   839  // Lock-free stack node.
   840  // Also known to export_test.go.
   841  type lfnode struct {
   842  	next    uint64
   843  	pushcnt uintptr
   844  }
   845  
   846  type forcegcstate struct {
   847  	lock mutex
   848  	g    *g
   849  	idle uint32
   850  }
   851  
   852  // startup_random_data holds random bytes initialized at startup. These come from
   853  // the ELF AT_RANDOM auxiliary vector (vdso_linux_amd64.go or os_linux_386.go).
   854  var startupRandomData []byte
   855  
   856  // extendRandom extends the random numbers in r[:n] to the whole slice r.
   857  // Treats n<0 as n==0.
   858  func extendRandom(r []byte, n int) {
   859  	if n < 0 {
   860  		n = 0
   861  	}
   862  	for n < len(r) {
   863  		// Extend random bits using hash function & time seed
   864  		w := n
   865  		if w > 16 {
   866  			w = 16
   867  		}
   868  		h := memhash(unsafe.Pointer(&r[n-w]), uintptr(nanotime()), uintptr(w))
   869  		for i := 0; i < sys.PtrSize && n < len(r); i++ {
   870  			r[n] = byte(h)
   871  			n++
   872  			h >>= 8
   873  		}
   874  	}
   875  }
   876  
   877  // A _defer holds an entry on the list of deferred calls.
   878  // If you add a field here, add code to clear it in freedefer and deferProcStack
   879  // This struct must match the code in cmd/compile/internal/gc/reflect.go:deferstruct
   880  // and cmd/compile/internal/gc/ssa.go:(*state).call.
   881  // Some defers will be allocated on the stack and some on the heap.
   882  // All defers are logically part of the stack, so write barriers to
   883  // initialize them are not required. All defers must be manually scanned,
   884  // and for heap defers, marked.
   885  type _defer struct {
   886  	siz     int32 // includes both arguments and results
   887  	started bool
   888  	heap    bool
   889  	// openDefer indicates that this _defer is for a frame with open-coded
   890  	// defers. We have only one defer record for the entire frame (which may
   891  	// currently have 0, 1, or more defers active).
   892  	openDefer bool
   893  	sp        uintptr  // sp at time of defer
   894  	pc        uintptr  // pc at time of defer
   895  	fn        *funcval // can be nil for open-coded defers
   896  	_panic    *_panic  // panic that is running defer
   897  	link      *_defer
   898  
   899  	// If openDefer is true, the fields below record values about the stack
   900  	// frame and associated function that has the open-coded defer(s). sp
   901  	// above will be the sp for the frame, and pc will be address of the
   902  	// deferreturn call in the function.
   903  	fd   unsafe.Pointer // funcdata for the function associated with the frame
   904  	varp uintptr        // value of varp for the stack frame
   905  	// framepc is the current pc associated with the stack frame. Together,
   906  	// with sp above (which is the sp associated with the stack frame),
   907  	// framepc/sp can be used as pc/sp pair to continue a stack trace via
   908  	// gentraceback().
   909  	framepc uintptr
   910  }
   911  
   912  // A _panic holds information about an active panic.
   913  //
   914  // This is marked go:notinheap because _panic values must only ever
   915  // live on the stack.
   916  //
   917  // The argp and link fields are stack pointers, but don't need special
   918  // handling during stack growth: because they are pointer-typed and
   919  // _panic values only live on the stack, regular stack pointer
   920  // adjustment takes care of them.
   921  type _panic struct {
   922  	argp      unsafe.Pointer // pointer to arguments of deferred call run during panic; cannot move - known to liblink
   923  	arg       interface{}    // argument to panic
   924  	link      *_panic        // link to earlier panic
   925  	pc        uintptr        // where to return to in runtime if this panic is bypassed
   926  	sp        unsafe.Pointer // where to return to in runtime if this panic is bypassed
   927  	recovered bool           // whether this panic is over
   928  	aborted   bool           // the panic was aborted
   929  	goexit    bool
   930  }
   931  
   932  // stack traces
   933  type stkframe struct {
   934  	fn       funcInfo   // function being run
   935  	pc       uintptr    // program counter within fn
   936  	continpc uintptr    // program counter where execution can continue, or 0 if not
   937  	lr       uintptr    // program counter at caller aka link register
   938  	sp       uintptr    // stack pointer at pc
   939  	fp       uintptr    // stack pointer at caller aka frame pointer
   940  	varp     uintptr    // top of local variables
   941  	argp     uintptr    // pointer to function arguments
   942  	arglen   uintptr    // number of bytes at argp
   943  	argmap   *bitvector // force use of this argmap
   944  }
   945  
   946  // ancestorInfo records details of where a goroutine was started.
   947  type ancestorInfo struct {
   948  	pcs  []uintptr // pcs from the stack of this goroutine
   949  	goid int64     // goroutine id of this goroutine; original goroutine possibly dead
   950  	gopc uintptr   // pc of go statement that created this goroutine
   951  }
   952  
   953  const (
   954  	_TraceRuntimeFrames = 1 << iota // include frames for internal runtime functions.
   955  	_TraceTrap                      // the initial PC, SP are from a trap, not a return PC from a call
   956  	_TraceJumpStack                 // if traceback is on a systemstack, resume trace at g that called into it
   957  )
   958  
   959  // The maximum number of frames we print for a traceback
   960  const _TracebackMaxFrames = 100
   961  
   962  // A waitReason explains why a goroutine has been stopped.
   963  // See gopark. Do not re-use waitReasons, add new ones.
   964  type waitReason uint8
   965  
   966  const (
   967  	waitReasonZero                  waitReason = iota // ""
   968  	waitReasonGCAssistMarking                         // "GC assist marking"
   969  	waitReasonIOWait                                  // "IO wait"
   970  	waitReasonChanReceiveNilChan                      // "chan receive (nil chan)"
   971  	waitReasonChanSendNilChan                         // "chan send (nil chan)"
   972  	waitReasonDumpingHeap                             // "dumping heap"
   973  	waitReasonGarbageCollection                       // "garbage collection"
   974  	waitReasonGarbageCollectionScan                   // "garbage collection scan"
   975  	waitReasonPanicWait                               // "panicwait"
   976  	waitReasonSelect                                  // "select"
   977  	waitReasonSelectNoCases                           // "select (no cases)"
   978  	waitReasonGCAssistWait                            // "GC assist wait"
   979  	waitReasonGCSweepWait                             // "GC sweep wait"
   980  	waitReasonGCScavengeWait                          // "GC scavenge wait"
   981  	waitReasonChanReceive                             // "chan receive"
   982  	waitReasonChanSend                                // "chan send"
   983  	waitReasonFinalizerWait                           // "finalizer wait"
   984  	waitReasonForceGCIdle                             // "force gc (idle)"
   985  	waitReasonSemacquire                              // "semacquire"
   986  	waitReasonSleep                                   // "sleep"
   987  	waitReasonSyncCondWait                            // "sync.Cond.Wait"
   988  	waitReasonTimerGoroutineIdle                      // "timer goroutine (idle)"
   989  	waitReasonTraceReaderBlocked                      // "trace reader (blocked)"
   990  	waitReasonWaitForGCCycle                          // "wait for GC cycle"
   991  	waitReasonGCWorkerIdle                            // "GC worker (idle)"
   992  	waitReasonPreempted                               // "preempted"
   993  	waitReasonDebugCall                               // "debug call"
   994  )
   995  
   996  var waitReasonStrings = [...]string{
   997  	waitReasonZero:                  "",
   998  	waitReasonGCAssistMarking:       "GC assist marking",
   999  	waitReasonIOWait:                "IO wait",
  1000  	waitReasonChanReceiveNilChan:    "chan receive (nil chan)",
  1001  	waitReasonChanSendNilChan:       "chan send (nil chan)",
  1002  	waitReasonDumpingHeap:           "dumping heap",
  1003  	waitReasonGarbageCollection:     "garbage collection",
  1004  	waitReasonGarbageCollectionScan: "garbage collection scan",
  1005  	waitReasonPanicWait:             "panicwait",
  1006  	waitReasonSelect:                "select",
  1007  	waitReasonSelectNoCases:         "select (no cases)",
  1008  	waitReasonGCAssistWait:          "GC assist wait",
  1009  	waitReasonGCSweepWait:           "GC sweep wait",
  1010  	waitReasonGCScavengeWait:        "GC scavenge wait",
  1011  	waitReasonChanReceive:           "chan receive",
  1012  	waitReasonChanSend:              "chan send",
  1013  	waitReasonFinalizerWait:         "finalizer wait",
  1014  	waitReasonForceGCIdle:           "force gc (idle)",
  1015  	waitReasonSemacquire:            "semacquire",
  1016  	waitReasonSleep:                 "sleep",
  1017  	waitReasonSyncCondWait:          "sync.Cond.Wait",
  1018  	waitReasonTimerGoroutineIdle:    "timer goroutine (idle)",
  1019  	waitReasonTraceReaderBlocked:    "trace reader (blocked)",
  1020  	waitReasonWaitForGCCycle:        "wait for GC cycle",
  1021  	waitReasonGCWorkerIdle:          "GC worker (idle)",
  1022  	waitReasonPreempted:             "preempted",
  1023  	waitReasonDebugCall:             "debug call",
  1024  }
  1025  
  1026  func (w waitReason) String() string {
  1027  	if w < 0 || w >= waitReason(len(waitReasonStrings)) {
  1028  		return "unknown wait reason"
  1029  	}
  1030  	return waitReasonStrings[w]
  1031  }
  1032  
  1033  var (
  1034  	allglen    uintptr
  1035  	allm       *m
  1036  	allp       []*p  // len(allp) == gomaxprocs; may change at safe points, otherwise immutable
  1037  	allpLock   mutex // Protects P-less reads of allp and all writes
  1038  	gomaxprocs int32
  1039  	ncpu       int32
  1040  	forcegc    forcegcstate
  1041  	sched      schedt
  1042  	newprocs   int32
  1043  
  1044  	// Information about what cpu features are available.
  1045  	// Packages outside the runtime should not use these
  1046  	// as they are not an external api.
  1047  	// Set on startup in asm_{386,amd64}.s
  1048  	processorVersionInfo uint32
  1049  	isIntel              bool
  1050  	lfenceBeforeRdtsc    bool
  1051  
  1052  	goarm                uint8 // set by cmd/link on arm systems
  1053  	framepointer_enabled bool  // set by cmd/link
  1054  )
  1055  
  1056  // Set by the linker so the runtime can determine the buildmode.
  1057  var (
  1058  	islibrary bool // -buildmode=c-shared
  1059  	isarchive bool // -buildmode=c-archive
  1060  )
  1061  

View as plain text