github.com/ltltlt/go-source-code@v0.0.0-20190830023027-95be009773aa/runtime/runtime2.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/atomic"
     9  	"runtime/internal/sys"
    10  	"unsafe"
    11  )
    12  
    13  // defined constants
    14  const (
    15  	// G status
    16  	//
    17  	// Beyond indicating the general state of a G, the G status
    18  	// acts like a lock on the goroutine's stack (and hence its
    19  	// ability to execute user code).
    20  	//
    21  	// If you add to this list, add to the list
    22  	// of "okay during garbage collection" status
    23  	// in mgcmark.go too.
    24  
    25  	// _Gidle means this goroutine was just allocated and has not
    26  	// yet been initialized.
    27  	_Gidle = iota // 0
    28  
    29  	// _Grunnable means this goroutine is on a run queue. It is
    30  	// not currently executing user code. The stack is not owned.
    31  	_Grunnable // 1
    32  
    33  	// _Grunning means this goroutine may execute user code. The
    34  	// stack is owned by this goroutine. It is not on a run queue.
    35  	// It is assigned an M and a P.
    36  	_Grunning // 2
    37  
    38  	// _Gsyscall means this goroutine is executing a system call.
    39  	// It is not executing user code. The stack is owned by this
    40  	// goroutine. It is not on a run queue. It is assigned an M.
    41  	_Gsyscall // 3
    42  
    43  	// _Gwaiting means this goroutine is blocked in the runtime.
    44  	// It is not executing user code. It is not on a run queue,
    45  	// but should be recorded somewhere (e.g., a channel wait
    46  	// queue) so it can be ready()d when necessary. The stack is
    47  	// not owned *except* that a channel operation may read or
    48  	// write parts of the stack under the appropriate channel
    49  	// lock. Otherwise, it is not safe to access the stack after a
    50  	// goroutine enters _Gwaiting (e.g., it may get moved).
    51  	_Gwaiting // 4
    52  
    53  	// _Gmoribund_unused is currently unused, but hardcoded in gdb
    54  	// scripts.
    55  	_Gmoribund_unused // 5
    56  
    57  	// _Gdead means this goroutine is currently unused. It may be
    58  	// just exited, on a free list, or just being initialized. It
    59  	// is not executing user code. It may or may not have a stack
    60  	// allocated. The G and its stack (if any) are owned by the M
    61  	// that is exiting the G or that obtained the G from the free
    62  	// list.
    63  	_Gdead // 6
    64  
    65  	// _Genqueue_unused is currently unused.
    66  	_Genqueue_unused // 7
    67  
    68  	// _Gcopystack means this goroutine's stack is being moved. It
    69  	// is not executing user code and is not on a run queue. The
    70  	// stack is owned by the goroutine that put it in _Gcopystack.
    71  	_Gcopystack // 8
    72  
    73  	// _Gscan combined with one of the above states other than
    74  	// _Grunning indicates that GC is scanning the stack. The
    75  	// goroutine is not executing user code and the stack is owned
    76  	// by the goroutine that set the _Gscan bit.
    77  	//
    78  	// _Gscanrunning is different: it is used to briefly block
    79  	// state transitions while GC signals the G to scan its own
    80  	// stack. This is otherwise like _Grunning.
    81  	//
    82  	// atomicstatus&~Gscan gives the state the goroutine will
    83  	// return to when the scan completes.
    84  	_Gscan         = 0x1000
    85  	_Gscanrunnable = _Gscan + _Grunnable // 0x1001
    86  	_Gscanrunning  = _Gscan + _Grunning  // 0x1002
    87  	_Gscansyscall  = _Gscan + _Gsyscall  // 0x1003
    88  	_Gscanwaiting  = _Gscan + _Gwaiting  // 0x1004
    89  )
    90  
    91  const (
    92  	// P status
    93  	_Pidle    = iota
    94  	_Prunning // Only this P is allowed to change from _Prunning.
    95  	_Psyscall
    96  	_Pgcstop
    97  	_Pdead
    98  )
    99  
   100  // Mutual exclusion locks.  In the uncontended case,
   101  // as fast as spin locks (just a few user-level instructions),
   102  // but on the contention path they sleep in the kernel.
   103  // A zeroed Mutex is unlocked (no need to initialize each lock).
   104  // 互相排斥的锁. 无竞争时, 就像自旋锁一样快(只是几条用户态指令)
   105  // 但有竞争时, 其在内核态睡眠. 一个0值mutex是未锁定的, 没必要初始化每个锁
   106  type mutex struct {
   107  	// Futex-based impl treats it as uint32 key,
   108  	// while sema-based impl as M* waitm.
   109  	// Used to be a union, but unions break precise GC.
   110  	key uintptr
   111  }
   112  
   113  // sleep and wakeup on one-time events.
   114  // before any calls to notesleep or notewakeup,
   115  // must call noteclear to initialize the Note.
   116  // then, exactly one thread can call notesleep
   117  // and exactly one thread can call notewakeup (once).
   118  // once notewakeup has been called, the notesleep
   119  // will return.  future notesleep will return immediately.
   120  // subsequent noteclear must be called only after
   121  // previous notesleep has returned, e.g. it's disallowed
   122  // to call noteclear straight after notewakeup.
   123  //
   124  // notetsleep is like notesleep but wakes up after
   125  // a given number of nanoseconds even if the event
   126  // has not yet happened.  if a goroutine uses notetsleep to
   127  // wake up early, it must wait to call noteclear until it
   128  // can be sure that no other goroutine is calling
   129  // notewakeup.
   130  //
   131  // notesleep/notetsleep are generally called on g0,
   132  // notetsleepg is similar to notetsleep but is called on user g.
   133  type note struct {
   134  	// Futex-based impl treats it as uint32 key,
   135  	// while sema-based impl as M* waitm.
   136  	// Used to be a union, but unions break precise GC.
   137  	key uintptr
   138  }
   139  
   140  type funcval struct {
   141  	fn uintptr
   142  	// variable-size, fn-specific data here
   143  	// 闭包能引用到的变量的地址就放这, 还有binded method引用到的receiver地址也放这
   144  }
   145  
   146  // non-empty interface
   147  // 此interface含method, 如var v Reader = whatever
   148  // tab 里包含一些实际类型和接口类型
   149  type iface struct {
   150  	tab  *itab // _type的基础上加上一些函数指针
   151  	data unsafe.Pointer
   152  }
   153  
   154  // empty interface
   155  // 此interface不含method, 如var v interface{} = whatever
   156  // 故只要存实际类型和指针即可
   157  type eface struct {
   158  	_type *_type
   159  	data  unsafe.Pointer
   160  }
   161  
   162  func efaceOf(ep *interface{}) *eface {
   163  	return (*eface)(unsafe.Pointer(ep))
   164  }
   165  
   166  // The guintptr, muintptr, and puintptr are all used to bypass write barriers.
   167  // It is particularly important to avoid write barriers when the current P has
   168  // been released, because the GC thinks the world is stopped, and an
   169  // unexpected write barrier would not be synchronized with the GC,
   170  // which can lead to a half-executed write barrier that has marked the object
   171  // but not queued it. If the GC skips the object and completes before the
   172  // queuing can occur, it will incorrectly free the object.
   173  //
   174  // We tried using special assignment functions invoked only when not
   175  // holding a running P, but then some updates to a particular memory
   176  // word went through write barriers and some did not. This breaks the
   177  // write barrier shadow checking mode, and it is also scary: better to have
   178  // a word that is completely ignored by the GC than to have one for which
   179  // only a few updates are ignored.
   180  //
   181  // Gs and Ps are always reachable via true pointers in the
   182  // allgs and allp lists or (during allocation before they reach those lists)
   183  // from stack variables.
   184  //
   185  // Ms are always reachable via true pointers either from allm or
   186  // freem. Unlike Gs and Ps we do free Ms, so it's important that
   187  // nothing ever hold an muintptr across a safe point.
   188  
   189  // A guintptr holds a goroutine pointer, but typed as a uintptr
   190  // to bypass write barriers. It is used in the Gobuf goroutine state
   191  // and in scheduling lists that are manipulated without a P.
   192  //
   193  // The Gobuf.g goroutine pointer is almost always updated by assembly code.
   194  // In one of the few places it is updated by Go code - func save - it must be
   195  // treated as a uintptr to avoid a write barrier being emitted at a bad time.
   196  // Instead of figuring out how to emit the write barriers missing in the
   197  // assembly manipulation, we change the type of the field to uintptr,
   198  // so that it does not require write barriers at all.
   199  //
   200  // Goroutine structs are published in the allg list and never freed.
   201  // That will keep the goroutine structs from being collected.
   202  // There is never a time that Gobuf.g's contain the only references
   203  // to a goroutine: the publishing of the goroutine in allg comes first.
   204  // Goroutine pointers are also kept in non-GC-visible places like TLS,
   205  // so I can't see them ever moving. If we did want to start moving data
   206  // in the GC, we'd need to allocate the goroutine structs from an
   207  // alternate arena. Using guintptr doesn't make that problem any worse.
   208  type guintptr uintptr
   209  
   210  //go:nosplit
   211  func (gp guintptr) ptr() *g { return (*g)(unsafe.Pointer(gp)) }
   212  
   213  //go:nosplit
   214  func (gp *guintptr) set(g *g) { *gp = guintptr(unsafe.Pointer(g)) }
   215  
   216  //go:nosplit
   217  func (gp *guintptr) cas(old, new guintptr) bool {
   218  	return atomic.Casuintptr((*uintptr)(unsafe.Pointer(gp)), uintptr(old), uintptr(new))
   219  }
   220  
   221  // setGNoWB performs *gp = new without a write barrier.
   222  // For times when it's impractical to use a guintptr.
   223  //go:nosplit
   224  //go:nowritebarrier
   225  func setGNoWB(gp **g, new *g) {
   226  	(*guintptr)(unsafe.Pointer(gp)).set(new)
   227  }
   228  
   229  type puintptr uintptr
   230  
   231  //go:nosplit
   232  func (pp puintptr) ptr() *p { return (*p)(unsafe.Pointer(pp)) }
   233  
   234  //go:nosplit
   235  func (pp *puintptr) set(p *p) { *pp = puintptr(unsafe.Pointer(p)) }
   236  
   237  // muintptr is a *m that is not tracked by the garbage collector.
   238  // 不被垃圾收集器跟踪
   239  //
   240  // Because we do free Ms, there are some additional constrains on
   241  // muintptrs:
   242  //
   243  // 1. Never hold an muintptr locally across a safe point.
   244  //
   245  // 2. Any muintptr in the heap must be owned by the M itself so it can
   246  //    ensure it is not in use when the last true *m is released.
   247  type muintptr uintptr
   248  
   249  //go:nosplit
   250  func (mp muintptr) ptr() *m { return (*m)(unsafe.Pointer(mp)) }
   251  
   252  //go:nosplit
   253  func (mp *muintptr) set(m *m) { *mp = muintptr(unsafe.Pointer(m)) }
   254  
   255  // setMNoWB performs *mp = new without a write barrier.
   256  // For times when it's impractical to use an muintptr.
   257  //go:nosplit
   258  //go:nowritebarrier
   259  func setMNoWB(mp **m, new *m) {
   260  	(*muintptr)(unsafe.Pointer(mp)).set(new)
   261  }
   262  
   263  type gobuf struct {
   264  	// The offsets of sp, pc, and g are known to (hard-coded in) libmach.
   265  	//
   266  	// ctxt is unusual with respect to GC: it may be a
   267  	// heap-allocated funcval, so GC needs to track it, but it
   268  	// needs to be set and cleared from assembly, where it's
   269  	// difficult to have write barriers. However, ctxt is really a
   270  	// saved, live register, and we only ever exchange it between
   271  	// the real register and the gobuf. Hence, we treat it as a
   272  	// root during stack scanning, which means assembly that saves
   273  	// and restores it doesn't need write barriers. It's still
   274  	// typed as a pointer so that any other writes from Go get
   275  	// write barriers.
   276  	sp   uintptr
   277  	pc   uintptr
   278  	g    guintptr
   279  	ctxt unsafe.Pointer
   280  	ret  sys.Uintreg
   281  	lr   uintptr
   282  	bp   uintptr // for GOEXPERIMENT=framepointer
   283  }
   284  
   285  // sudog represents a g in a wait list, such as for sending/receiving
   286  // on a channel.
   287  // 代表在等待list中的g
   288  //
   289  // sudog is necessary because the g ↔ synchronization object relation
   290  // is many-to-many. A g can be on many wait lists, so there may be
   291  // many sudogs for one g; and many gs may be waiting on the same
   292  // synchronization object, so there may be many sudogs for one object.
   293  //
   294  // sudogs are allocated from a special pool. Use acquireSudog and
   295  // releaseSudog to allocate and free them.
   296  type sudog struct {
   297  	// The following fields are protected by the hchan.lock of the
   298  	// channel this sudog is blocking on. shrinkstack depends on
   299  	// this for sudogs involved in channel ops.
   300  
   301  	g *g
   302  
   303  	// isSelect indicates g is participating in a select, so
   304  	// g.selectDone must be CAS'd to win the wake-up race.
   305  	isSelect bool
   306  	next     *sudog
   307  	prev     *sudog
   308  	elem     unsafe.Pointer // data element (may point to stack)
   309  
   310  	// The following fields are never accessed concurrently.
   311  	// For channels, waitlink is only accessed by g.
   312  	// For semaphores, all fields (including the ones above)
   313  	// are only accessed when holding a semaRoot lock.
   314  
   315  	acquiretime int64
   316  	releasetime int64
   317  	ticket      uint32 // treap中的优先级, 插入一个节点时随机生成
   318  	parent      *sudog // semaRoot binary tree
   319  	waitlink    *sudog // g.waiting list or semaRoot
   320  	waittail    *sudog // semaRoot
   321  	c           *hchan // channel
   322  }
   323  
   324  type libcall struct {
   325  	fn   uintptr
   326  	n    uintptr // number of parameters
   327  	args uintptr // parameters
   328  	r1   uintptr // return values
   329  	r2   uintptr
   330  	err  uintptr // error number
   331  }
   332  
   333  // describes how to handle callback
   334  type wincallbackcontext struct {
   335  	gobody       unsafe.Pointer // go function to call
   336  	argsize      uintptr        // callback arguments size (in bytes)
   337  	restorestack uintptr        // adjust stack on return by (in bytes) (386 only)
   338  	cleanstack   bool
   339  }
   340  
   341  // Stack describes a Go execution stack.
   342  // The bounds of the stack are exactly [lo, hi),
   343  // with no implicit data structures on either side.
   344  type stack struct {
   345  	lo uintptr
   346  	hi uintptr
   347  }
   348  
   349  // goroutine
   350  // 表示goroutine,存储了goroutine的执行stack信息、goroutine状态以及goroutine的任务函数等
   351  // 可重用
   352  type g struct {
   353  	// Stack parameters.
   354  	// stack describes the actual stack memory: [stack.lo, stack.hi).
   355  	// stackguard0 is the stack pointer compared in the Go stack growth prologue.
   356  	// It is stack.lo+StackGuard normally, but can be StackPreempt to trigger a preemption.
   357  	// stackguard1 is the stack pointer compared in the C stack growth prologue.
   358  	// It is stack.lo+StackGuard on g0 and gsignal stacks.
   359  	// It is ~0 on other goroutine stacks, to trigger a call to morestackc (and crash).
   360  	stack       stack   // offset known to runtime/cgo
   361  	stackguard0 uintptr // offset known to liblink, 检查栈空间是否足够的值, 低于这个值会扩张栈, 0是go代码使用的
   362  	stackguard1 uintptr // offset known to liblink, 1是给原生代码用的
   363  
   364  	_panic       *_panic // innermost panic - offset known to liblink
   365  	_defer       *_defer // innermost defer
   366  	m            *m      // current m; offset known to arm liblink
   367  	sched        gobuf
   368  	syscallsp    uintptr        // if status==Gsyscall, syscallsp = sched.sp to use during gc
   369  	syscallpc    uintptr        // if status==Gsyscall, syscallpc = sched.pc to use during gc
   370  	stktopsp     uintptr        // expected sp at top of stack, to check in traceback
   371  	param        unsafe.Pointer // passed parameter on wakeup
   372  	atomicstatus uint32
   373  	stackLock    uint32 // sigprof/scang lock; TODO: fold in to atomicstatus
   374  	goid         int64
   375  	waitsince    int64    // approx time when the g become blocked
   376  	waitreason   string   // if status==Gwaiting
   377  	schedlink    guintptr // schedule里用到, 指向下一个相同类型g的指针(比如runnable队列就是指向下一个runnable g)
   378  
   379  	// 抢占位, 如果被设置, 这个G的下一次函数调用, runtime就将其抢占, 放入P的local runq中,等待被下次调用
   380  	// retake -> preemptone中会设置
   381  	preempt        bool     // preemption signal, duplicates stackguard0 = stackpreempt
   382  	paniconfault   bool     // panic (instead of crash) on unexpected fault address
   383  	preemptscan    bool     // preempted g does scan for gc
   384  	gcscandone     bool     // g has scanned stack; protected by _Gscan bit in status
   385  	gcscanvalid    bool     // false at start of gc cycle, true if G has not run since last scan; TODO: remove?
   386  	throwsplit     bool     // must not split stack
   387  	raceignore     int8     // ignore race detection events
   388  	sysblocktraced bool     // StartTrace has emitted EvGoInSyscall about this goroutine
   389  	sysexitticks   int64    // cputicks when syscall has returned (for tracing)
   390  	traceseq       uint64   // trace event sequencer
   391  	tracelastp     puintptr // last P emitted an event for this goroutine
   392  	lockedm        muintptr
   393  	sig            uint32
   394  	writebuf       []byte
   395  	sigcode0       uintptr
   396  	sigcode1       uintptr
   397  	sigpc          uintptr
   398  	gopc           uintptr // pc of go statement that created this goroutine
   399  	startpc        uintptr // pc of goroutine function
   400  	racectx        uintptr
   401  	waiting        *sudog         // sudog structures this g is waiting on (that have a valid elem ptr); in lock order
   402  	cgoCtxt        []uintptr      // cgo traceback context
   403  	labels         unsafe.Pointer // profiler labels
   404  	timer          *timer         // cached timer for time.Sleep
   405  	selectDone     uint32         // are we participating in a select and did someone win the race?
   406  
   407  	// Per-G GC state
   408  
   409  	// gcAssistBytes is this G's GC assist credit in terms of
   410  	// bytes allocated. If this is positive, then the G has credit
   411  	// to allocate gcAssistBytes bytes without assisting. If this
   412  	// is negative, then the G must correct this by performing
   413  	// scan work. We track this in bytes to make it fast to update
   414  	// and check for debt in the malloc hot path. The assist ratio
   415  	// determines how this corresponds to scan work debt.
   416  	gcAssistBytes int64
   417  }
   418  
   419  // M代表着真正的执行计算资源(os thread)
   420  // 在绑定有效的p后,进入schedule循环
   421  // 而schedule循环的机制大致是从各种队列、p的本地队列中获取G,切换到G的执行栈上并执行G的函数,调用goexit做清理工作并回到m,如此反复
   422  // M并不保留G状态,这是G可以跨M调度的基础。
   423  type m struct {
   424  	// g0是负责调度这个m的g
   425  	// g0 的栈是带有调度栈的goroutine,其栈是M对应的系统线程的栈
   426  	// 所有调度相关的代码会先切换到此goroutine的栈中执行
   427  	g0      *g     // goroutine with scheduling stack
   428  	morebuf gobuf  // gobuf arg to morestack
   429  	divmod  uint32 // div/mod denominator for arm - known to liblink
   430  
   431  	// Fields not known to debuggers.
   432  	procid        uint64       // for debuggers, but offset not hard-coded
   433  	gsignal       *g           // signal-handling g
   434  	goSigStack    gsignalStack // Go-allocated signal handling stack
   435  	sigmask       sigset       // storage for saved signal mask
   436  	tls           [6]uintptr   // thread-local storage (for x86 extern register)
   437  	mstartfn      func()
   438  	curg          *g       // current running goroutine
   439  	caughtsig     guintptr // goroutine running during fatal signal
   440  	p             puintptr // attached p for executing go code (nil if not executing go code)
   441  	nextp         puintptr
   442  	id            int64
   443  	mallocing     int32
   444  	throwing      int32
   445  	preemptoff    string // if != "", keep curg running on this m
   446  	locks         int32
   447  	softfloat     int32
   448  	dying         int32
   449  	profilehz     int32
   450  	helpgc        int32
   451  	spinning      bool // m is out of work and is actively looking for work
   452  	blocked       bool // m is blocked on a note
   453  	inwb          bool // m is executing a write barrier
   454  	newSigstack   bool // minit on C thread called sigaltstack
   455  	printlock     int8
   456  	incgo         bool   // m is executing a cgo call
   457  	freeWait      uint32 // if == 0, safe to free g0 and delete m (atomic)
   458  	fastrand      [2]uint32
   459  	needextram    bool
   460  	traceback     uint8
   461  	ncgocall      uint64      // number of cgo calls in total
   462  	ncgo          int32       // number of cgo calls currently in progress
   463  	cgoCallersUse uint32      // if non-zero, cgoCallers in use temporarily
   464  	cgoCallers    *cgoCallers // cgo traceback if crashing in cgo call
   465  	park          note
   466  	alllink       *m // on allm
   467  	schedlink     muintptr
   468  	mcache        *mcache
   469  	lockedg       guintptr
   470  	createstack   [32]uintptr    // stack that created this thread.
   471  	freglo        [16]uint32     // d[i] lsb and f[i]
   472  	freghi        [16]uint32     // d[i] msb and f[i+16]
   473  	fflag         uint32         // floating point compare flags
   474  	lockedExt     uint32         // tracking for external LockOSThread
   475  	lockedInt     uint32         // tracking for internal lockOSThread
   476  	nextwaitm     muintptr       // next m waiting for lock
   477  	waitunlockf   unsafe.Pointer // todo go func(*g, unsafe.pointer) bool
   478  	waitlock      unsafe.Pointer
   479  	waittraceev   byte
   480  	waittraceskip int
   481  	startingtrace bool
   482  	syscalltick   uint32
   483  	thread        uintptr // thread handle
   484  	freelink      *m      // on sched.freem
   485  
   486  	// these are here because they are too large to be on the stack
   487  	// of low-level NOSPLIT functions.
   488  	libcall   libcall
   489  	libcallpc uintptr // for cpu profiler
   490  	libcallsp uintptr
   491  	libcallg  guintptr
   492  	syscall   libcall // stores syscall parameters on windows
   493  
   494  	mOS
   495  }
   496  
   497  // 处理器, 每个g都由p来调度在m上运行
   498  // 其个数是GOMAXPROCS
   499  // P的数量决定了系统内最大可并行的G的数量(前提:系统的物理cpu核数>=P的数量)
   500  // P的最大作用还是其拥有的各种G对象队列、链表、一些cache和状态
   501  type p struct {
   502  	lock mutex
   503  
   504  	id          int32
   505  	status      uint32 // one of pidle/prunning/...
   506  	link        puintptr
   507  	schedtick   uint32     // incremented on every scheduler call
   508  	syscalltick uint32     // incremented on every system call
   509  	sysmontick  sysmontick // last tick observed by sysmon
   510  	m           muintptr   // back-link to associated m (nil if idle)
   511  	mcache      *mcache    // memory span cache
   512  	racectx     uintptr
   513  
   514  	deferpool    [5][]*_defer // pool of available defer structs of different sizes (see panic.go)
   515  	deferpoolbuf [5][32]*_defer
   516  
   517  	// Cache of goroutine ids, amortizes accesses to runtime·sched.goidgen.
   518  	goidcache    uint64
   519  	goidcacheend uint64
   520  
   521  	// p独立的goroutine
   522  	// Queue of runnable goroutines. Accessed without lock.
   523  	runqhead uint32
   524  	runqtail uint32
   525  	runq     [256]guintptr // wait for run queue
   526  	// runnext, if non-nil, is a runnable G that was ready'd by
   527  	// the current G and should be run next instead of what's in
   528  	// runq if there's time remaining in the running G's time
   529  	// slice. It will inherit the time left in the current time
   530  	// slice. If a set of goroutines is locked in a
   531  	// communicate-and-wait pattern, this schedules that set as a
   532  	// unit and eliminates the (potentially large) scheduling
   533  	// latency that otherwise arises from adding the ready'd
   534  	// goroutines to the end of the run queue.
   535  	runnext guintptr
   536  
   537  	// Available G's (status == Gdead)
   538  	// G可被重用
   539  	gfree    *g
   540  	gfreecnt int32
   541  
   542  	// g 的等待列表
   543  	sudogcache []*sudog
   544  	sudogbuf   [128]*sudog
   545  
   546  	tracebuf traceBufPtr
   547  
   548  	// traceSweep indicates the sweep events should be traced.
   549  	// This is used to defer the sweep start event until a span
   550  	// has actually been swept.
   551  	traceSweep bool
   552  	// traceSwept and traceReclaimed track the number of bytes
   553  	// swept and reclaimed by sweeping in the current sweep loop.
   554  	traceSwept, traceReclaimed uintptr
   555  
   556  	palloc persistentAlloc // per-P to avoid mutex
   557  
   558  	// Per-P GC state
   559  	gcAssistTime         int64 // Nanoseconds in assistAlloc
   560  	gcFractionalMarkTime int64 // Nanoseconds in fractional mark worker
   561  	gcBgMarkWorker       guintptr
   562  	gcMarkWorkerMode     gcMarkWorkerMode
   563  
   564  	// gcMarkWorkerStartTime is the nanotime() at which this mark
   565  	// worker started.
   566  	gcMarkWorkerStartTime int64
   567  
   568  	// gcw is this P's GC work buffer cache. The work buffer is
   569  	// filled by write barriers, drained by mutator assists, and
   570  	// disposed on certain GC state transitions.
   571  	gcw gcWork
   572  
   573  	// wbBuf is this P's GC write barrier buffer.
   574  	//
   575  	// TODO: Consider caching this in the running G.
   576  	wbBuf wbBuf
   577  
   578  	runSafePointFn uint32 // if 1, run sched.safePointFn at next safe point
   579  
   580  	pad [sys.CacheLineSize]byte
   581  }
   582  
   583  // 全局调度者
   584  type schedt struct {
   585  	// accessed atomically. keep at top to ensure alignment on 32-bit systems.
   586  	goidgen  uint64
   587  	lastpoll uint64
   588  
   589  	lock mutex
   590  
   591  	// When increasing nmidle, nmidlelocked, nmsys, or nmfreed, be
   592  	// sure to call checkdead().
   593  
   594  	midle        muintptr // idle m's waiting for work
   595  	nmidle       int32    // number of idle m's waiting for work
   596  	nmidlelocked int32    // number of locked m's waiting for work
   597  	mnext        int64    // number of m's that have been created and next M ID
   598  	maxmcount    int32    // maximum number of m's allowed (or die)
   599  	nmsys        int32    // number of system m's not counted for deadlock
   600  	nmfreed      int64    // cumulative number of freed m's
   601  
   602  	ngsys uint32 // number of system goroutines; updated atomically
   603  
   604  	pidle      puintptr // idle p's
   605  	npidle     uint32
   606  	nmspinning uint32 // See "Worker thread parking/unparking" comment in proc.go.
   607  
   608  	// Global runnable queue.
   609  	runqhead guintptr
   610  	runqtail guintptr
   611  	runqsize int32
   612  
   613  	// Global cache of dead G's.
   614  	gflock       mutex
   615  	gfreeStack   *g
   616  	gfreeNoStack *g
   617  	ngfree       int32
   618  
   619  	// Central cache of sudog structs.
   620  	sudoglock  mutex
   621  	sudogcache *sudog
   622  
   623  	// Central pool of available defer structs of different sizes.
   624  	deferlock mutex
   625  	deferpool [5]*_defer
   626  
   627  	// freem is the list of m's waiting to be freed when their
   628  	// m.exited is set. Linked through m.freelink.
   629  	freem *m
   630  
   631  	gcwaiting  uint32 // gc is waiting to run
   632  	stopwait   int32
   633  	stopnote   note
   634  	sysmonwait uint32
   635  	sysmonnote note
   636  
   637  	// safepointFn should be called on each P at the next GC
   638  	// safepoint if p.runSafePointFn is set.
   639  	safePointFn   func(*p)
   640  	safePointWait int32
   641  	safePointNote note
   642  
   643  	profilehz int32 // cpu profiling rate
   644  
   645  	procresizetime int64 // nanotime() of last change to gomaxprocs
   646  	totaltime      int64 // ∫gomaxprocs dt up to procresizetime
   647  }
   648  
   649  // Values for the flags field of a sigTabT.
   650  const (
   651  	_SigNotify   = 1 << iota // let signal.Notify have signal, even if from kernel
   652  	_SigKill                 // if signal.Notify doesn't take it, exit quietly
   653  	_SigThrow                // if signal.Notify doesn't take it, exit loudly
   654  	_SigPanic                // if the signal is from the kernel, panic
   655  	_SigDefault              // if the signal isn't explicitly requested, don't monitor it
   656  	_SigGoExit               // cause all runtime procs to exit (only used on Plan 9).
   657  	_SigSetStack             // add SA_ONSTACK to libc handler
   658  	_SigUnblock              // always unblock; see blockableSig
   659  	_SigIgn                  // _SIG_DFL action is to ignore the signal
   660  )
   661  
   662  // Layout of in-memory per-function information prepared by linker
   663  // See https://golang.org/s/go12symtab.
   664  // Keep in sync with linker (../cmd/link/internal/ld/pcln.go:/pclntab)
   665  // and with package debug/gosym and with symtab.go in package runtime.
   666  type _func struct {
   667  	entry   uintptr // start pc
   668  	nameoff int32   // function name
   669  
   670  	args   int32  // in/out args size
   671  	funcID funcID // set for certain special runtime functions
   672  
   673  	pcsp      int32
   674  	pcfile    int32
   675  	pcln      int32
   676  	npcdata   int32
   677  	nfuncdata int32
   678  }
   679  
   680  // layout of Itab known to compilers
   681  // allocated in non-garbage-collected memory
   682  // Needs to be in sync with
   683  // ../cmd/compile/internal/gc/reflect.go:/^func.dumptypestructs.
   684  type itab struct {
   685  	inter *interfacetype
   686  	_type *_type
   687  	hash  uint32 // copy of _type.hash. Used for type switches.
   688  	_     [4]byte
   689  	fun   [1]uintptr // variable sized. fun[0]==0 means _type does not implement inter.
   690  }
   691  
   692  // Lock-free stack node.
   693  // // Also known to export_test.go.
   694  type lfnode struct {
   695  	next    uint64
   696  	pushcnt uintptr
   697  }
   698  
   699  type forcegcstate struct {
   700  	lock mutex
   701  	g    *g
   702  	idle uint32
   703  }
   704  
   705  // startup_random_data holds random bytes initialized at startup. These come from
   706  // the ELF AT_RANDOM auxiliary vector (vdso_linux_amd64.go or os_linux_386.go).
   707  var startupRandomData []byte
   708  
   709  // extendRandom extends the random numbers in r[:n] to the whole slice r.
   710  // Treats n<0 as n==0.
   711  func extendRandom(r []byte, n int) {
   712  	if n < 0 {
   713  		n = 0
   714  	}
   715  	for n < len(r) {
   716  		// Extend random bits using hash function & time seed
   717  		w := n
   718  		if w > 16 {
   719  			w = 16
   720  		}
   721  		h := memhash(unsafe.Pointer(&r[n-w]), uintptr(nanotime()), uintptr(w))
   722  		for i := 0; i < sys.PtrSize && n < len(r); i++ {
   723  			r[n] = byte(h)
   724  			n++
   725  			h >>= 8
   726  		}
   727  	}
   728  }
   729  
   730  // A _defer holds an entry on the list of deferred calls.
   731  // If you add a field here, add code to clear it in freedefer.
   732  type _defer struct {
   733  	siz     int32
   734  	started bool
   735  	sp      uintptr // sp at time of defer
   736  	pc      uintptr
   737  	fn      *funcval
   738  	_panic  *_panic // panic that is running defer
   739  	link    *_defer
   740  }
   741  
   742  // panics
   743  type _panic struct {
   744  	argp      unsafe.Pointer // pointer to arguments of deferred call run during panic; cannot move - known to liblink
   745  	arg       interface{}    // argument to panic
   746  	link      *_panic        // link to earlier panic
   747  	recovered bool           // whether this panic is over
   748  	aborted   bool           // the panic was aborted
   749  }
   750  
   751  // stack traces
   752  type stkframe struct {
   753  	fn       funcInfo   // function being run
   754  	pc       uintptr    // program counter within fn
   755  	continpc uintptr    // program counter where execution can continue, or 0 if not
   756  	lr       uintptr    // program counter at caller aka link register
   757  	sp       uintptr    // stack pointer at pc
   758  	fp       uintptr    // stack pointer at caller aka frame pointer
   759  	varp     uintptr    // top of local variables
   760  	argp     uintptr    // pointer to function arguments
   761  	arglen   uintptr    // number of bytes at argp
   762  	argmap   *bitvector // force use of this argmap
   763  }
   764  
   765  const (
   766  	_TraceRuntimeFrames = 1 << iota // include frames for internal runtime functions.
   767  	_TraceTrap                      // the initial PC, SP are from a trap, not a return PC from a call
   768  	_TraceJumpStack                 // if traceback is on a systemstack, resume trace at g that called into it
   769  )
   770  
   771  // The maximum number of frames we print for a traceback
   772  const _TracebackMaxFrames = 100
   773  
   774  var (
   775  	allglen    uintptr
   776  	allm       *m
   777  	allp       []*p  // len(allp) == gomaxprocs; may change at safe points, otherwise immutable
   778  	allpLock   mutex // Protects P-less reads of allp and all writes
   779  	gomaxprocs int32
   780  	ncpu       int32
   781  	forcegc    forcegcstate
   782  	sched      schedt
   783  	newprocs   int32
   784  
   785  	// Information about what cpu features are available.
   786  	// Set on startup in asm_{386,amd64,amd64p32}.s.
   787  	// Packages outside the runtime should not use these
   788  	// as they are not an external api.
   789  	processorVersionInfo uint32
   790  	isIntel              bool
   791  	lfenceBeforeRdtsc    bool
   792  	support_aes          bool
   793  	support_avx          bool
   794  	support_avx2         bool
   795  	support_bmi1         bool
   796  	support_bmi2         bool
   797  	support_erms         bool
   798  	support_osxsave      bool
   799  	support_popcnt       bool
   800  	support_sse2         bool
   801  	support_sse41        bool
   802  	support_sse42        bool
   803  	support_ssse3        bool
   804  
   805  	goarm                uint8 // set by cmd/link on arm systems
   806  	framepointer_enabled bool  // set by cmd/link
   807  )
   808  
   809  // Set by the linker so the runtime can determine the buildmode.
   810  var (
   811  	islibrary bool // -buildmode=c-shared
   812  	isarchive bool // -buildmode=c-archive
   813  )