Source file src/runtime/mprof.go

     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  // Malloc profiling.
     6  // Patterned after tcmalloc's algorithms; shorter code.
     7  
     8  package runtime
     9  
    10  import (
    11  	"internal/abi"
    12  	"internal/goarch"
    13  	"internal/profilerecord"
    14  	"internal/runtime/atomic"
    15  	"internal/runtime/sys"
    16  	"unsafe"
    17  )
    18  
    19  // NOTE(rsc): Everything here could use cas if contention became an issue.
    20  var (
    21  	// profInsertLock protects changes to the start of all *bucket linked lists
    22  	profInsertLock mutex
    23  	// profBlockLock protects the contents of every blockRecord struct
    24  	profBlockLock mutex
    25  	// profMemActiveLock protects the active field of every memRecord struct
    26  	profMemActiveLock mutex
    27  	// profMemFutureLock is a set of locks that protect the respective elements
    28  	// of the future array of every memRecord struct
    29  	profMemFutureLock [len(memRecord{}.future)]mutex
    30  )
    31  
    32  // All memory allocations are local and do not escape outside of the profiler.
    33  // The profiler is forbidden from referring to garbage-collected memory.
    34  
    35  const (
    36  	// profile types
    37  	memProfile bucketType = 1 + iota
    38  	blockProfile
    39  	mutexProfile
    40  
    41  	// size of bucket hash table
    42  	buckHashSize = 179999
    43  
    44  	// maxSkip is to account for deferred inline expansion
    45  	// when using frame pointer unwinding. We record the stack
    46  	// with "physical" frame pointers but handle skipping "logical"
    47  	// frames at some point after collecting the stack. So
    48  	// we need extra space in order to avoid getting fewer than the
    49  	// desired maximum number of frames after expansion.
    50  	// This should be at least as large as the largest skip value
    51  	// used for profiling; otherwise stacks may be truncated inconsistently
    52  	maxSkip = 6
    53  
    54  	// maxProfStackDepth is the highest valid value for debug.profstackdepth.
    55  	// It's used for the bucket.stk func.
    56  	// TODO(fg): can we get rid of this?
    57  	maxProfStackDepth = 1024
    58  )
    59  
    60  type bucketType int
    61  
    62  // A bucket holds per-call-stack profiling information.
    63  // The representation is a bit sleazy, inherited from C.
    64  // This struct defines the bucket header. It is followed in
    65  // memory by the stack words and then the actual record
    66  // data, either a memRecord or a blockRecord.
    67  //
    68  // Per-call-stack profiling information.
    69  // Lookup by hashing call stack into a linked-list hash table.
    70  //
    71  // None of the fields in this bucket header are modified after
    72  // creation, including its next and allnext links.
    73  //
    74  // No heap pointers.
    75  type bucket struct {
    76  	_       sys.NotInHeap
    77  	next    *bucket
    78  	allnext *bucket
    79  	typ     bucketType // memBucket or blockBucket (includes mutexProfile)
    80  	hash    uintptr
    81  	size    uintptr
    82  	nstk    uintptr
    83  }
    84  
    85  // A memRecord is the bucket data for a bucket of type memProfile,
    86  // part of the memory profile.
    87  type memRecord struct {
    88  	// The following complex 3-stage scheme of stats accumulation
    89  	// is required to obtain a consistent picture of mallocs and frees
    90  	// for some point in time.
    91  	// The problem is that mallocs come in real time, while frees
    92  	// come only after a GC during concurrent sweeping. So if we would
    93  	// naively count them, we would get a skew toward mallocs.
    94  	//
    95  	// Hence, we delay information to get consistent snapshots as
    96  	// of mark termination. Allocations count toward the next mark
    97  	// termination's snapshot, while sweep frees count toward the
    98  	// previous mark termination's snapshot:
    99  	//
   100  	//              MT          MT          MT          MT
   101  	//             .·|         .·|         .·|         .·|
   102  	//          .·˙  |      .·˙  |      .·˙  |      .·˙  |
   103  	//       .·˙     |   .·˙     |   .·˙     |   .·˙     |
   104  	//    .·˙        |.·˙        |.·˙        |.·˙        |
   105  	//
   106  	//       alloc → ▲ ← free
   107  	//               ┠┅┅┅┅┅┅┅┅┅┅┅P
   108  	//       C+2     →    C+1    →  C
   109  	//
   110  	//                   alloc → ▲ ← free
   111  	//                           ┠┅┅┅┅┅┅┅┅┅┅┅P
   112  	//                   C+2     →    C+1    →  C
   113  	//
   114  	// Since we can't publish a consistent snapshot until all of
   115  	// the sweep frees are accounted for, we wait until the next
   116  	// mark termination ("MT" above) to publish the previous mark
   117  	// termination's snapshot ("P" above). To do this, allocation
   118  	// and free events are accounted to *future* heap profile
   119  	// cycles ("C+n" above) and we only publish a cycle once all
   120  	// of the events from that cycle must be done. Specifically:
   121  	//
   122  	// Mallocs are accounted to cycle C+2.
   123  	// Explicit frees are accounted to cycle C+2.
   124  	// GC frees (done during sweeping) are accounted to cycle C+1.
   125  	//
   126  	// After mark termination, we increment the global heap
   127  	// profile cycle counter and accumulate the stats from cycle C
   128  	// into the active profile.
   129  
   130  	// active is the currently published profile. A profiling
   131  	// cycle can be accumulated into active once its complete.
   132  	active memRecordCycle
   133  
   134  	// future records the profile events we're counting for cycles
   135  	// that have not yet been published. This is ring buffer
   136  	// indexed by the global heap profile cycle C and stores
   137  	// cycles C, C+1, and C+2. Unlike active, these counts are
   138  	// only for a single cycle; they are not cumulative across
   139  	// cycles.
   140  	//
   141  	// We store cycle C here because there's a window between when
   142  	// C becomes the active cycle and when we've flushed it to
   143  	// active.
   144  	future [3]memRecordCycle
   145  }
   146  
   147  // memRecordCycle
   148  type memRecordCycle struct {
   149  	allocs, frees           uintptr
   150  	alloc_bytes, free_bytes uintptr
   151  }
   152  
   153  // add accumulates b into a. It does not zero b.
   154  func (a *memRecordCycle) add(b *memRecordCycle) {
   155  	a.allocs += b.allocs
   156  	a.frees += b.frees
   157  	a.alloc_bytes += b.alloc_bytes
   158  	a.free_bytes += b.free_bytes
   159  }
   160  
   161  // A blockRecord is the bucket data for a bucket of type blockProfile,
   162  // which is used in blocking and mutex profiles.
   163  type blockRecord struct {
   164  	count  float64
   165  	cycles int64
   166  }
   167  
   168  var (
   169  	mbuckets atomic.UnsafePointer // *bucket, memory profile buckets
   170  	bbuckets atomic.UnsafePointer // *bucket, blocking profile buckets
   171  	xbuckets atomic.UnsafePointer // *bucket, mutex profile buckets
   172  	buckhash atomic.UnsafePointer // *buckhashArray
   173  
   174  	mProfCycle mProfCycleHolder
   175  )
   176  
   177  type buckhashArray [buckHashSize]atomic.UnsafePointer // *bucket
   178  
   179  const mProfCycleWrap = uint32(len(memRecord{}.future)) * (2 << 24)
   180  
   181  // mProfCycleHolder holds the global heap profile cycle number (wrapped at
   182  // mProfCycleWrap, stored starting at bit 1), and a flag (stored at bit 0) to
   183  // indicate whether future[cycle] in all buckets has been queued to flush into
   184  // the active profile.
   185  type mProfCycleHolder struct {
   186  	value atomic.Uint32
   187  }
   188  
   189  // read returns the current cycle count.
   190  func (c *mProfCycleHolder) read() (cycle uint32) {
   191  	v := c.value.Load()
   192  	cycle = v >> 1
   193  	return cycle
   194  }
   195  
   196  // setFlushed sets the flushed flag. It returns the current cycle count and the
   197  // previous value of the flushed flag.
   198  func (c *mProfCycleHolder) setFlushed() (cycle uint32, alreadyFlushed bool) {
   199  	for {
   200  		prev := c.value.Load()
   201  		cycle = prev >> 1
   202  		alreadyFlushed = (prev & 0x1) != 0
   203  		next := prev | 0x1
   204  		if c.value.CompareAndSwap(prev, next) {
   205  			return cycle, alreadyFlushed
   206  		}
   207  	}
   208  }
   209  
   210  // increment increases the cycle count by one, wrapping the value at
   211  // mProfCycleWrap. It clears the flushed flag.
   212  func (c *mProfCycleHolder) increment() {
   213  	// We explicitly wrap mProfCycle rather than depending on
   214  	// uint wraparound because the memRecord.future ring does not
   215  	// itself wrap at a power of two.
   216  	for {
   217  		prev := c.value.Load()
   218  		cycle := prev >> 1
   219  		cycle = (cycle + 1) % mProfCycleWrap
   220  		next := cycle << 1
   221  		if c.value.CompareAndSwap(prev, next) {
   222  			break
   223  		}
   224  	}
   225  }
   226  
   227  // newBucket allocates a bucket with the given type and number of stack entries.
   228  func newBucket(typ bucketType, nstk int) *bucket {
   229  	size := unsafe.Sizeof(bucket{}) + uintptr(nstk)*unsafe.Sizeof(uintptr(0))
   230  	switch typ {
   231  	default:
   232  		throw("invalid profile bucket type")
   233  	case memProfile:
   234  		size += unsafe.Sizeof(memRecord{})
   235  	case blockProfile, mutexProfile:
   236  		size += unsafe.Sizeof(blockRecord{})
   237  	}
   238  
   239  	b := (*bucket)(persistentalloc(size, 0, &memstats.buckhash_sys))
   240  	b.typ = typ
   241  	b.nstk = uintptr(nstk)
   242  	return b
   243  }
   244  
   245  // stk returns the slice in b holding the stack. The caller can assume that the
   246  // backing array is immutable.
   247  func (b *bucket) stk() []uintptr {
   248  	stk := (*[maxProfStackDepth]uintptr)(add(unsafe.Pointer(b), unsafe.Sizeof(*b)))
   249  	if b.nstk > maxProfStackDepth {
   250  		// prove that slicing works; otherwise a failure requires a P
   251  		throw("bad profile stack count")
   252  	}
   253  	return stk[:b.nstk:b.nstk]
   254  }
   255  
   256  // mp returns the memRecord associated with the memProfile bucket b.
   257  func (b *bucket) mp() *memRecord {
   258  	if b.typ != memProfile {
   259  		throw("bad use of bucket.mp")
   260  	}
   261  	data := add(unsafe.Pointer(b), unsafe.Sizeof(*b)+b.nstk*unsafe.Sizeof(uintptr(0)))
   262  	return (*memRecord)(data)
   263  }
   264  
   265  // bp returns the blockRecord associated with the blockProfile bucket b.
   266  func (b *bucket) bp() *blockRecord {
   267  	if b.typ != blockProfile && b.typ != mutexProfile {
   268  		throw("bad use of bucket.bp")
   269  	}
   270  	data := add(unsafe.Pointer(b), unsafe.Sizeof(*b)+b.nstk*unsafe.Sizeof(uintptr(0)))
   271  	return (*blockRecord)(data)
   272  }
   273  
   274  // Return the bucket for stk[0:nstk], allocating new bucket if needed.
   275  func stkbucket(typ bucketType, size uintptr, stk []uintptr, alloc bool) *bucket {
   276  	bh := (*buckhashArray)(buckhash.Load())
   277  	if bh == nil {
   278  		lock(&profInsertLock)
   279  		// check again under the lock
   280  		bh = (*buckhashArray)(buckhash.Load())
   281  		if bh == nil {
   282  			bh = (*buckhashArray)(sysAlloc(unsafe.Sizeof(buckhashArray{}), &memstats.buckhash_sys, "profiler hash buckets"))
   283  			if bh == nil {
   284  				throw("runtime: cannot allocate memory")
   285  			}
   286  			buckhash.StoreNoWB(unsafe.Pointer(bh))
   287  		}
   288  		unlock(&profInsertLock)
   289  	}
   290  
   291  	// Hash stack.
   292  	var h uintptr
   293  	for _, pc := range stk {
   294  		h += pc
   295  		h += h << 10
   296  		h ^= h >> 6
   297  	}
   298  	// hash in size
   299  	h += size
   300  	h += h << 10
   301  	h ^= h >> 6
   302  	// finalize
   303  	h += h << 3
   304  	h ^= h >> 11
   305  
   306  	i := int(h % buckHashSize)
   307  	// first check optimistically, without the lock
   308  	for b := (*bucket)(bh[i].Load()); b != nil; b = b.next {
   309  		if b.typ == typ && b.hash == h && b.size == size && eqslice(b.stk(), stk) {
   310  			return b
   311  		}
   312  	}
   313  
   314  	if !alloc {
   315  		return nil
   316  	}
   317  
   318  	lock(&profInsertLock)
   319  	// check again under the insertion lock
   320  	for b := (*bucket)(bh[i].Load()); b != nil; b = b.next {
   321  		if b.typ == typ && b.hash == h && b.size == size && eqslice(b.stk(), stk) {
   322  			unlock(&profInsertLock)
   323  			return b
   324  		}
   325  	}
   326  
   327  	// Create new bucket.
   328  	b := newBucket(typ, len(stk))
   329  	copy(b.stk(), stk)
   330  	b.hash = h
   331  	b.size = size
   332  
   333  	var allnext *atomic.UnsafePointer
   334  	if typ == memProfile {
   335  		allnext = &mbuckets
   336  	} else if typ == mutexProfile {
   337  		allnext = &xbuckets
   338  	} else {
   339  		allnext = &bbuckets
   340  	}
   341  
   342  	b.next = (*bucket)(bh[i].Load())
   343  	b.allnext = (*bucket)(allnext.Load())
   344  
   345  	bh[i].StoreNoWB(unsafe.Pointer(b))
   346  	allnext.StoreNoWB(unsafe.Pointer(b))
   347  
   348  	unlock(&profInsertLock)
   349  	return b
   350  }
   351  
   352  func eqslice(x, y []uintptr) bool {
   353  	if len(x) != len(y) {
   354  		return false
   355  	}
   356  	for i, xi := range x {
   357  		if xi != y[i] {
   358  			return false
   359  		}
   360  	}
   361  	return true
   362  }
   363  
   364  // mProf_NextCycle publishes the next heap profile cycle and creates a
   365  // fresh heap profile cycle. This operation is fast and can be done
   366  // during STW. The caller must call mProf_Flush before calling
   367  // mProf_NextCycle again.
   368  //
   369  // This is called by mark termination during STW so allocations and
   370  // frees after the world is started again count towards a new heap
   371  // profiling cycle.
   372  func mProf_NextCycle() {
   373  	mProfCycle.increment()
   374  }
   375  
   376  // mProf_Flush flushes the events from the current heap profiling
   377  // cycle into the active profile. After this it is safe to start a new
   378  // heap profiling cycle with mProf_NextCycle.
   379  //
   380  // This is called by GC after mark termination starts the world. In
   381  // contrast with mProf_NextCycle, this is somewhat expensive, but safe
   382  // to do concurrently.
   383  func mProf_Flush() {
   384  	cycle, alreadyFlushed := mProfCycle.setFlushed()
   385  	if alreadyFlushed {
   386  		return
   387  	}
   388  
   389  	index := cycle % uint32(len(memRecord{}.future))
   390  	lock(&profMemActiveLock)
   391  	lock(&profMemFutureLock[index])
   392  	mProf_FlushLocked(index)
   393  	unlock(&profMemFutureLock[index])
   394  	unlock(&profMemActiveLock)
   395  }
   396  
   397  // mProf_FlushLocked flushes the events from the heap profiling cycle at index
   398  // into the active profile. The caller must hold the lock for the active profile
   399  // (profMemActiveLock) and for the profiling cycle at index
   400  // (profMemFutureLock[index]).
   401  func mProf_FlushLocked(index uint32) {
   402  	assertLockHeld(&profMemActiveLock)
   403  	assertLockHeld(&profMemFutureLock[index])
   404  	head := (*bucket)(mbuckets.Load())
   405  	for b := head; b != nil; b = b.allnext {
   406  		mp := b.mp()
   407  
   408  		// Flush cycle C into the published profile and clear
   409  		// it for reuse.
   410  		mpc := &mp.future[index]
   411  		mp.active.add(mpc)
   412  		*mpc = memRecordCycle{}
   413  	}
   414  }
   415  
   416  // mProf_PostSweep records that all sweep frees for this GC cycle have
   417  // completed. This has the effect of publishing the heap profile
   418  // snapshot as of the last mark termination without advancing the heap
   419  // profile cycle.
   420  func mProf_PostSweep() {
   421  	// Flush cycle C+1 to the active profile so everything as of
   422  	// the last mark termination becomes visible. *Don't* advance
   423  	// the cycle, since we're still accumulating allocs in cycle
   424  	// C+2, which have to become C+1 in the next mark termination
   425  	// and so on.
   426  	cycle := mProfCycle.read() + 1
   427  
   428  	index := cycle % uint32(len(memRecord{}.future))
   429  	lock(&profMemActiveLock)
   430  	lock(&profMemFutureLock[index])
   431  	mProf_FlushLocked(index)
   432  	unlock(&profMemFutureLock[index])
   433  	unlock(&profMemActiveLock)
   434  }
   435  
   436  // Called by malloc to record a profiled block.
   437  func mProf_Malloc(mp *m, p unsafe.Pointer, size uintptr) {
   438  	if mp.profStack == nil {
   439  		// mp.profStack is nil if we happen to sample an allocation during the
   440  		// initialization of mp. This case is rare, so we just ignore such
   441  		// allocations. Change MemProfileRate to 1 if you need to reproduce such
   442  		// cases for testing purposes.
   443  		return
   444  	}
   445  	// Only use the part of mp.profStack we need and ignore the extra space
   446  	// reserved for delayed inline expansion with frame pointer unwinding.
   447  	nstk := callers(5, mp.profStack[:debug.profstackdepth])
   448  	index := (mProfCycle.read() + 2) % uint32(len(memRecord{}.future))
   449  
   450  	b := stkbucket(memProfile, size, mp.profStack[:nstk], true)
   451  	mr := b.mp()
   452  	mpc := &mr.future[index]
   453  
   454  	lock(&profMemFutureLock[index])
   455  	mpc.allocs++
   456  	mpc.alloc_bytes += size
   457  	unlock(&profMemFutureLock[index])
   458  
   459  	// Setprofilebucket locks a bunch of other mutexes, so we call it outside of
   460  	// the profiler locks. This reduces potential contention and chances of
   461  	// deadlocks. Since the object must be alive during the call to
   462  	// mProf_Malloc, it's fine to do this non-atomically.
   463  	systemstack(func() {
   464  		setprofilebucket(p, b)
   465  	})
   466  }
   467  
   468  // Called when freeing a profiled block.
   469  func mProf_Free(b *bucket, size uintptr) {
   470  	index := (mProfCycle.read() + 1) % uint32(len(memRecord{}.future))
   471  
   472  	mp := b.mp()
   473  	mpc := &mp.future[index]
   474  
   475  	lock(&profMemFutureLock[index])
   476  	mpc.frees++
   477  	mpc.free_bytes += size
   478  	unlock(&profMemFutureLock[index])
   479  }
   480  
   481  var blockprofilerate uint64 // in CPU ticks
   482  
   483  // SetBlockProfileRate controls the fraction of goroutine blocking events
   484  // that are reported in the blocking profile. The profiler aims to sample
   485  // an average of one blocking event per rate nanoseconds spent blocked.
   486  //
   487  // To include every blocking event in the profile, pass rate = 1.
   488  // To turn off profiling entirely, pass rate <= 0.
   489  func SetBlockProfileRate(rate int) {
   490  	var r int64
   491  	if rate <= 0 {
   492  		r = 0 // disable profiling
   493  	} else if rate == 1 {
   494  		r = 1 // profile everything
   495  	} else {
   496  		// convert ns to cycles, use float64 to prevent overflow during multiplication
   497  		r = int64(float64(rate) * float64(ticksPerSecond()) / (1000 * 1000 * 1000))
   498  		if r == 0 {
   499  			r = 1
   500  		}
   501  	}
   502  
   503  	atomic.Store64(&blockprofilerate, uint64(r))
   504  }
   505  
   506  func blockevent(cycles int64, skip int) {
   507  	if cycles <= 0 {
   508  		cycles = 1
   509  	}
   510  
   511  	rate := int64(atomic.Load64(&blockprofilerate))
   512  	if blocksampled(cycles, rate) {
   513  		saveblockevent(cycles, rate, skip+1, blockProfile)
   514  	}
   515  }
   516  
   517  // blocksampled returns true for all events where cycles >= rate. Shorter
   518  // events have a cycles/rate random chance of returning true.
   519  func blocksampled(cycles, rate int64) bool {
   520  	if rate <= 0 || (rate > cycles && cheaprand64()%rate > cycles) {
   521  		return false
   522  	}
   523  	return true
   524  }
   525  
   526  // saveblockevent records a profile event of the type specified by which.
   527  // cycles is the quantity associated with this event and rate is the sampling rate,
   528  // used to adjust the cycles value in the manner determined by the profile type.
   529  // skip is the number of frames to omit from the traceback associated with the event.
   530  // The traceback will be recorded from the stack of the goroutine associated with the current m.
   531  // skip should be positive if this event is recorded from the current stack
   532  // (e.g. when this is not called from a system stack)
   533  func saveblockevent(cycles, rate int64, skip int, which bucketType) {
   534  	if debug.profstackdepth == 0 {
   535  		// profstackdepth is set to 0 by the user, so mp.profStack is nil and we
   536  		// can't record a stack trace.
   537  		return
   538  	}
   539  	if skip > maxSkip {
   540  		print("requested skip=", skip)
   541  		throw("invalid skip value")
   542  	}
   543  	gp := getg()
   544  	mp := acquirem() // we must not be preempted while accessing profstack
   545  
   546  	var nstk int
   547  	if tracefpunwindoff() || gp.m.hasCgoOnStack() {
   548  		if gp.m.curg == nil || gp.m.curg == gp {
   549  			nstk = callers(skip, mp.profStack)
   550  		} else {
   551  			nstk = gcallers(gp.m.curg, skip, mp.profStack)
   552  		}
   553  	} else {
   554  		if gp.m.curg == nil || gp.m.curg == gp {
   555  			if skip > 0 {
   556  				// We skip one fewer frame than the provided value for frame
   557  				// pointer unwinding because the skip value includes the current
   558  				// frame, whereas the saved frame pointer will give us the
   559  				// caller's return address first (so, not including
   560  				// saveblockevent)
   561  				skip -= 1
   562  			}
   563  			nstk = fpTracebackPartialExpand(skip, unsafe.Pointer(getfp()), mp.profStack)
   564  		} else {
   565  			mp.profStack[0] = gp.m.curg.sched.pc
   566  			nstk = 1 + fpTracebackPartialExpand(skip, unsafe.Pointer(gp.m.curg.sched.bp), mp.profStack[1:])
   567  		}
   568  	}
   569  
   570  	saveBlockEventStack(cycles, rate, mp.profStack[:nstk], which)
   571  	releasem(mp)
   572  }
   573  
   574  // fpTracebackPartialExpand records a call stack obtained starting from fp.
   575  // This function will skip the given number of frames, properly accounting for
   576  // inlining, and save remaining frames as "physical" return addresses. The
   577  // consumer should later use CallersFrames or similar to expand inline frames.
   578  func fpTracebackPartialExpand(skip int, fp unsafe.Pointer, pcBuf []uintptr) int {
   579  	var n int
   580  	lastFuncID := abi.FuncIDNormal
   581  	skipOrAdd := func(retPC uintptr) bool {
   582  		if skip > 0 {
   583  			skip--
   584  		} else if n < len(pcBuf) {
   585  			pcBuf[n] = retPC
   586  			n++
   587  		}
   588  		return n < len(pcBuf)
   589  	}
   590  	for n < len(pcBuf) && fp != nil {
   591  		// return addr sits one word above the frame pointer
   592  		pc := *(*uintptr)(unsafe.Pointer(uintptr(fp) + goarch.PtrSize))
   593  
   594  		if skip > 0 {
   595  			callPC := pc - 1
   596  			fi := findfunc(callPC)
   597  			u, uf := newInlineUnwinder(fi, callPC)
   598  			for ; uf.valid(); uf = u.next(uf) {
   599  				sf := u.srcFunc(uf)
   600  				if sf.funcID == abi.FuncIDWrapper && elideWrapperCalling(lastFuncID) {
   601  					// ignore wrappers
   602  				} else if more := skipOrAdd(uf.pc + 1); !more {
   603  					return n
   604  				}
   605  				lastFuncID = sf.funcID
   606  			}
   607  		} else {
   608  			// We've skipped the desired number of frames, so no need
   609  			// to perform further inline expansion now.
   610  			pcBuf[n] = pc
   611  			n++
   612  		}
   613  
   614  		// follow the frame pointer to the next one
   615  		fp = unsafe.Pointer(*(*uintptr)(fp))
   616  	}
   617  	return n
   618  }
   619  
   620  // mLockProfile holds information about the runtime-internal lock contention
   621  // experienced and caused by this M, to report in metrics and profiles.
   622  //
   623  // These measurements are subject to some notable constraints: First, the fast
   624  // path for lock and unlock must remain very fast, with a minimal critical
   625  // section. Second, the critical section during contention has to remain small
   626  // too, so low levels of contention are less likely to snowball into large ones.
   627  // The reporting code cannot acquire new locks until the M has released all
   628  // other locks, which means no memory allocations and encourages use of
   629  // (temporary) M-local storage.
   630  //
   631  // The M has space for storing one call stack that caused contention, and the
   632  // magnitude of that contention. It also has space to store the magnitude of
   633  // additional contention the M caused, since it might encounter several
   634  // contention events before it releases all of its locks and is thus able to
   635  // transfer the locally buffered call stack and magnitude into the profile.
   636  //
   637  // The M collects the call stack when it unlocks the contended lock. The
   638  // traceback takes place outside of the lock's critical section.
   639  //
   640  // The profile for contention on sync.Mutex blames the caller of Unlock for the
   641  // amount of contention experienced by the callers of Lock which had to wait.
   642  // When there are several critical sections, this allows identifying which of
   643  // them is responsible. We must match that reporting behavior for contention on
   644  // runtime-internal locks.
   645  //
   646  // When the M unlocks its last mutex, it transfers the locally buffered call
   647  // stack and magnitude into the profile. As part of that step, it also transfers
   648  // any "additional contention" time to the profile. Any lock contention that it
   649  // experiences while adding samples to the profile will be recorded later as
   650  // "additional contention" and not include a call stack, to avoid an echo.
   651  type mLockProfile struct {
   652  	waitTime   atomic.Int64 // (nanotime) total time this M has spent waiting in runtime.lockWithRank. Read by runtime/metrics.
   653  	stack      []uintptr    // call stack at the point of this M's unlock call, when other Ms had to wait
   654  	cycles     int64        // (cputicks) cycles attributable to "stack"
   655  	cyclesLost int64        // (cputicks) contention for which we weren't able to record a call stack
   656  	haveStack  bool         // stack and cycles are to be added to the mutex profile (even if cycles is 0)
   657  	disabled   bool         // attribute all time to "lost"
   658  }
   659  
   660  func (prof *mLockProfile) start() int64 {
   661  	if cheaprandn(gTrackingPeriod) == 0 {
   662  		return nanotime()
   663  	}
   664  	return 0
   665  }
   666  
   667  func (prof *mLockProfile) end(start int64) {
   668  	if start != 0 {
   669  		prof.waitTime.Add((nanotime() - start) * gTrackingPeriod)
   670  	}
   671  }
   672  
   673  // recordUnlock prepares data for later addition to the mutex contention
   674  // profile. The M may hold arbitrary locks during this call.
   675  //
   676  // From unlock2, we might not be holding a p in this code.
   677  //
   678  //go:nowritebarrierrec
   679  func (prof *mLockProfile) recordUnlock(cycles int64) {
   680  	if cycles < 0 {
   681  		cycles = 0
   682  	}
   683  
   684  	if prof.disabled {
   685  		// We're experiencing contention while attempting to report contention.
   686  		// Make a note of its magnitude, but don't allow it to be the sole cause
   687  		// of another contention report.
   688  		prof.cyclesLost += cycles
   689  		return
   690  	}
   691  
   692  	if prev := prof.cycles; prev > 0 {
   693  		// We can only store one call stack for runtime-internal lock contention
   694  		// on this M, and we've already got one. Decide which should stay, and
   695  		// add the other to the report for runtime._LostContendedRuntimeLock.
   696  		if cycles == 0 {
   697  			return
   698  		}
   699  		prevScore := uint64(cheaprand64()) % uint64(prev)
   700  		thisScore := uint64(cheaprand64()) % uint64(cycles)
   701  		if prevScore > thisScore {
   702  			prof.cyclesLost += cycles
   703  			return
   704  		} else {
   705  			prof.cyclesLost += prev
   706  		}
   707  	}
   708  	prof.captureStack()
   709  	prof.cycles = cycles
   710  }
   711  
   712  func (prof *mLockProfile) captureStack() {
   713  	if debug.profstackdepth == 0 {
   714  		// profstackdepth is set to 0 by the user, so mp.profStack is nil and we
   715  		// can't record a stack trace.
   716  		return
   717  	}
   718  
   719  	skip := 4 // runtime.(*mLockProfile).recordUnlock runtime.unlock2Wake runtime.unlock2 runtime.unlockWithRank
   720  	if staticLockRanking {
   721  		// When static lock ranking is enabled, we'll always be on the system
   722  		// stack at this point. There will be a runtime.unlockWithRank.func1
   723  		// frame, and if the call to runtime.unlock took place on a user stack
   724  		// then there'll also be a runtime.systemstack frame. To keep stack
   725  		// traces somewhat consistent whether or not static lock ranking is
   726  		// enabled, we'd like to skip those. But it's hard to tell how long
   727  		// we've been on the system stack so accept an extra frame in that case,
   728  		// with a leaf of "runtime.unlockWithRank runtime.unlock" instead of
   729  		// "runtime.unlock".
   730  		skip += 1 // runtime.unlockWithRank.func1
   731  	}
   732  	prof.haveStack = true
   733  
   734  	prof.stack[0] = logicalStackSentinel
   735  
   736  	var nstk int
   737  	gp := getg()
   738  	sp := sys.GetCallerSP()
   739  	pc := sys.GetCallerPC()
   740  	systemstack(func() {
   741  		var u unwinder
   742  		u.initAt(pc, sp, 0, gp, unwindSilentErrors|unwindJumpStack)
   743  		nstk = 1 + tracebackPCs(&u, skip, prof.stack[1:])
   744  	})
   745  	if nstk < len(prof.stack) {
   746  		prof.stack[nstk] = 0
   747  	}
   748  }
   749  
   750  // store adds the M's local record to the mutex contention profile.
   751  //
   752  // From unlock2, we might not be holding a p in this code.
   753  //
   754  //go:nowritebarrierrec
   755  func (prof *mLockProfile) store() {
   756  	if gp := getg(); gp.m.locks == 1 && gp.m.mLockProfile.haveStack {
   757  		prof.storeSlow()
   758  	}
   759  }
   760  
   761  func (prof *mLockProfile) storeSlow() {
   762  	// Report any contention we experience within this function as "lost"; it's
   763  	// important that the act of reporting a contention event not lead to a
   764  	// reportable contention event. This also means we can use prof.stack
   765  	// without copying, since it won't change during this function.
   766  	mp := acquirem()
   767  	prof.disabled = true
   768  
   769  	nstk := int(debug.profstackdepth)
   770  	for i := 0; i < nstk; i++ {
   771  		if pc := prof.stack[i]; pc == 0 {
   772  			nstk = i
   773  			break
   774  		}
   775  	}
   776  
   777  	cycles, lost := prof.cycles, prof.cyclesLost
   778  	prof.cycles, prof.cyclesLost = 0, 0
   779  	prof.haveStack = false
   780  
   781  	rate := int64(atomic.Load64(&mutexprofilerate))
   782  	saveBlockEventStack(cycles, rate, prof.stack[:nstk], mutexProfile)
   783  	if lost > 0 {
   784  		lostStk := [...]uintptr{
   785  			logicalStackSentinel,
   786  			abi.FuncPCABIInternal(_LostContendedRuntimeLock) + sys.PCQuantum,
   787  		}
   788  		saveBlockEventStack(lost, rate, lostStk[:], mutexProfile)
   789  	}
   790  
   791  	prof.disabled = false
   792  	releasem(mp)
   793  }
   794  
   795  func saveBlockEventStack(cycles, rate int64, stk []uintptr, which bucketType) {
   796  	b := stkbucket(which, 0, stk, true)
   797  	bp := b.bp()
   798  
   799  	lock(&profBlockLock)
   800  	// We want to up-scale the count and cycles according to the
   801  	// probability that the event was sampled. For block profile events,
   802  	// the sample probability is 1 if cycles >= rate, and cycles / rate
   803  	// otherwise. For mutex profile events, the sample probability is 1 / rate.
   804  	// We scale the events by 1 / (probability the event was sampled).
   805  	if which == blockProfile && cycles < rate {
   806  		// Remove sampling bias, see discussion on http://golang.org/cl/299991.
   807  		bp.count += float64(rate) / float64(cycles)
   808  		bp.cycles += rate
   809  	} else if which == mutexProfile {
   810  		bp.count += float64(rate)
   811  		bp.cycles += rate * cycles
   812  	} else {
   813  		bp.count++
   814  		bp.cycles += cycles
   815  	}
   816  	unlock(&profBlockLock)
   817  }
   818  
   819  var mutexprofilerate uint64 // fraction sampled
   820  
   821  // SetMutexProfileFraction controls the fraction of mutex contention events
   822  // that are reported in the mutex profile. On average 1/rate events are
   823  // reported. The previous rate is returned.
   824  //
   825  // To turn off profiling entirely, pass rate 0.
   826  // To just read the current rate, pass rate < 0.
   827  // (For n>1 the details of sampling may change.)
   828  func SetMutexProfileFraction(rate int) int {
   829  	if rate < 0 {
   830  		return int(mutexprofilerate)
   831  	}
   832  	old := mutexprofilerate
   833  	atomic.Store64(&mutexprofilerate, uint64(rate))
   834  	return int(old)
   835  }
   836  
   837  //go:linkname mutexevent sync.event
   838  func mutexevent(cycles int64, skip int) {
   839  	if cycles < 0 {
   840  		cycles = 0
   841  	}
   842  	rate := int64(atomic.Load64(&mutexprofilerate))
   843  	if rate > 0 && cheaprand64()%rate == 0 {
   844  		saveblockevent(cycles, rate, skip+1, mutexProfile)
   845  	}
   846  }
   847  
   848  // Go interface to profile data.
   849  
   850  // A StackRecord describes a single execution stack.
   851  type StackRecord struct {
   852  	Stack0 [32]uintptr // stack trace for this record; ends at first 0 entry
   853  }
   854  
   855  // Stack returns the stack trace associated with the record,
   856  // a prefix of r.Stack0.
   857  func (r *StackRecord) Stack() []uintptr {
   858  	for i, v := range r.Stack0 {
   859  		if v == 0 {
   860  			return r.Stack0[0:i]
   861  		}
   862  	}
   863  	return r.Stack0[0:]
   864  }
   865  
   866  // MemProfileRate controls the fraction of memory allocations
   867  // that are recorded and reported in the memory profile.
   868  // The profiler aims to sample an average of
   869  // one allocation per MemProfileRate bytes allocated.
   870  //
   871  // To include every allocated block in the profile, set MemProfileRate to 1.
   872  // To turn off profiling entirely, set MemProfileRate to 0.
   873  //
   874  // The tools that process the memory profiles assume that the
   875  // profile rate is constant across the lifetime of the program
   876  // and equal to the current value. Programs that change the
   877  // memory profiling rate should do so just once, as early as
   878  // possible in the execution of the program (for example,
   879  // at the beginning of main).
   880  var MemProfileRate int = 512 * 1024
   881  
   882  // disableMemoryProfiling is set by the linker if memory profiling
   883  // is not used and the link type guarantees nobody else could use it
   884  // elsewhere.
   885  // We check if the runtime.memProfileInternal symbol is present.
   886  var disableMemoryProfiling bool
   887  
   888  // A MemProfileRecord describes the live objects allocated
   889  // by a particular call sequence (stack trace).
   890  type MemProfileRecord struct {
   891  	AllocBytes, FreeBytes     int64       // number of bytes allocated, freed
   892  	AllocObjects, FreeObjects int64       // number of objects allocated, freed
   893  	Stack0                    [32]uintptr // stack trace for this record; ends at first 0 entry
   894  }
   895  
   896  // InUseBytes returns the number of bytes in use (AllocBytes - FreeBytes).
   897  func (r *MemProfileRecord) InUseBytes() int64 { return r.AllocBytes - r.FreeBytes }
   898  
   899  // InUseObjects returns the number of objects in use (AllocObjects - FreeObjects).
   900  func (r *MemProfileRecord) InUseObjects() int64 {
   901  	return r.AllocObjects - r.FreeObjects
   902  }
   903  
   904  // Stack returns the stack trace associated with the record,
   905  // a prefix of r.Stack0.
   906  func (r *MemProfileRecord) Stack() []uintptr {
   907  	for i, v := range r.Stack0 {
   908  		if v == 0 {
   909  			return r.Stack0[0:i]
   910  		}
   911  	}
   912  	return r.Stack0[0:]
   913  }
   914  
   915  // MemProfile returns a profile of memory allocated and freed per allocation
   916  // site.
   917  //
   918  // MemProfile returns n, the number of records in the current memory profile.
   919  // If len(p) >= n, MemProfile copies the profile into p and returns n, true.
   920  // If len(p) < n, MemProfile does not change p and returns n, false.
   921  //
   922  // If inuseZero is true, the profile includes allocation records
   923  // where r.AllocBytes > 0 but r.AllocBytes == r.FreeBytes.
   924  // These are sites where memory was allocated, but it has all
   925  // been released back to the runtime.
   926  //
   927  // The returned profile may be up to two garbage collection cycles old.
   928  // This is to avoid skewing the profile toward allocations; because
   929  // allocations happen in real time but frees are delayed until the garbage
   930  // collector performs sweeping, the profile only accounts for allocations
   931  // that have had a chance to be freed by the garbage collector.
   932  //
   933  // Most clients should use the runtime/pprof package or
   934  // the testing package's -test.memprofile flag instead
   935  // of calling MemProfile directly.
   936  func MemProfile(p []MemProfileRecord, inuseZero bool) (n int, ok bool) {
   937  	return memProfileInternal(len(p), inuseZero, func(r profilerecord.MemProfileRecord) {
   938  		copyMemProfileRecord(&p[0], r)
   939  		p = p[1:]
   940  	})
   941  }
   942  
   943  // memProfileInternal returns the number of records n in the profile. If there
   944  // are less than size records, copyFn is invoked for each record, and ok returns
   945  // true.
   946  //
   947  // The linker set disableMemoryProfiling to true to disable memory profiling
   948  // if this function is not reachable. Mark it noinline to ensure the symbol exists.
   949  // (This function is big and normally not inlined anyway.)
   950  // See also disableMemoryProfiling above and cmd/link/internal/ld/lib.go:linksetup.
   951  //
   952  //go:noinline
   953  func memProfileInternal(size int, inuseZero bool, copyFn func(profilerecord.MemProfileRecord)) (n int, ok bool) {
   954  	cycle := mProfCycle.read()
   955  	// If we're between mProf_NextCycle and mProf_Flush, take care
   956  	// of flushing to the active profile so we only have to look
   957  	// at the active profile below.
   958  	index := cycle % uint32(len(memRecord{}.future))
   959  	lock(&profMemActiveLock)
   960  	lock(&profMemFutureLock[index])
   961  	mProf_FlushLocked(index)
   962  	unlock(&profMemFutureLock[index])
   963  	clear := true
   964  	head := (*bucket)(mbuckets.Load())
   965  	for b := head; b != nil; b = b.allnext {
   966  		mp := b.mp()
   967  		if inuseZero || mp.active.alloc_bytes != mp.active.free_bytes {
   968  			n++
   969  		}
   970  		if mp.active.allocs != 0 || mp.active.frees != 0 {
   971  			clear = false
   972  		}
   973  	}
   974  	if clear {
   975  		// Absolutely no data, suggesting that a garbage collection
   976  		// has not yet happened. In order to allow profiling when
   977  		// garbage collection is disabled from the beginning of execution,
   978  		// accumulate all of the cycles, and recount buckets.
   979  		n = 0
   980  		for b := head; b != nil; b = b.allnext {
   981  			mp := b.mp()
   982  			for c := range mp.future {
   983  				lock(&profMemFutureLock[c])
   984  				mp.active.add(&mp.future[c])
   985  				mp.future[c] = memRecordCycle{}
   986  				unlock(&profMemFutureLock[c])
   987  			}
   988  			if inuseZero || mp.active.alloc_bytes != mp.active.free_bytes {
   989  				n++
   990  			}
   991  		}
   992  	}
   993  	if n <= size {
   994  		ok = true
   995  		for b := head; b != nil; b = b.allnext {
   996  			mp := b.mp()
   997  			if inuseZero || mp.active.alloc_bytes != mp.active.free_bytes {
   998  				r := profilerecord.MemProfileRecord{
   999  					AllocBytes:   int64(mp.active.alloc_bytes),
  1000  					FreeBytes:    int64(mp.active.free_bytes),
  1001  					AllocObjects: int64(mp.active.allocs),
  1002  					FreeObjects:  int64(mp.active.frees),
  1003  					Stack:        b.stk(),
  1004  				}
  1005  				copyFn(r)
  1006  			}
  1007  		}
  1008  	}
  1009  	unlock(&profMemActiveLock)
  1010  	return
  1011  }
  1012  
  1013  func copyMemProfileRecord(dst *MemProfileRecord, src profilerecord.MemProfileRecord) {
  1014  	dst.AllocBytes = src.AllocBytes
  1015  	dst.FreeBytes = src.FreeBytes
  1016  	dst.AllocObjects = src.AllocObjects
  1017  	dst.FreeObjects = src.FreeObjects
  1018  	if raceenabled {
  1019  		racewriterangepc(unsafe.Pointer(&dst.Stack0[0]), unsafe.Sizeof(dst.Stack0), sys.GetCallerPC(), abi.FuncPCABIInternal(MemProfile))
  1020  	}
  1021  	if msanenabled {
  1022  		msanwrite(unsafe.Pointer(&dst.Stack0[0]), unsafe.Sizeof(dst.Stack0))
  1023  	}
  1024  	if asanenabled {
  1025  		asanwrite(unsafe.Pointer(&dst.Stack0[0]), unsafe.Sizeof(dst.Stack0))
  1026  	}
  1027  	i := copy(dst.Stack0[:], src.Stack)
  1028  	clear(dst.Stack0[i:])
  1029  }
  1030  
  1031  //go:linkname pprof_memProfileInternal
  1032  func pprof_memProfileInternal(p []profilerecord.MemProfileRecord, inuseZero bool) (n int, ok bool) {
  1033  	return memProfileInternal(len(p), inuseZero, func(r profilerecord.MemProfileRecord) {
  1034  		p[0] = r
  1035  		p = p[1:]
  1036  	})
  1037  }
  1038  
  1039  func iterate_memprof(fn func(*bucket, uintptr, *uintptr, uintptr, uintptr, uintptr)) {
  1040  	lock(&profMemActiveLock)
  1041  	head := (*bucket)(mbuckets.Load())
  1042  	for b := head; b != nil; b = b.allnext {
  1043  		mp := b.mp()
  1044  		fn(b, b.nstk, &b.stk()[0], b.size, mp.active.allocs, mp.active.frees)
  1045  	}
  1046  	unlock(&profMemActiveLock)
  1047  }
  1048  
  1049  // BlockProfileRecord describes blocking events originated
  1050  // at a particular call sequence (stack trace).
  1051  type BlockProfileRecord struct {
  1052  	Count  int64
  1053  	Cycles int64
  1054  	StackRecord
  1055  }
  1056  
  1057  // BlockProfile returns n, the number of records in the current blocking profile.
  1058  // If len(p) >= n, BlockProfile copies the profile into p and returns n, true.
  1059  // If len(p) < n, BlockProfile does not change p and returns n, false.
  1060  //
  1061  // Most clients should use the [runtime/pprof] package or
  1062  // the [testing] package's -test.blockprofile flag instead
  1063  // of calling BlockProfile directly.
  1064  func BlockProfile(p []BlockProfileRecord) (n int, ok bool) {
  1065  	var m int
  1066  	n, ok = blockProfileInternal(len(p), func(r profilerecord.BlockProfileRecord) {
  1067  		copyBlockProfileRecord(&p[m], r)
  1068  		m++
  1069  	})
  1070  	if ok {
  1071  		expandFrames(p[:n])
  1072  	}
  1073  	return
  1074  }
  1075  
  1076  func expandFrames(p []BlockProfileRecord) {
  1077  	expandedStack := makeProfStack()
  1078  	for i := range p {
  1079  		cf := CallersFrames(p[i].Stack())
  1080  		j := 0
  1081  		for j < len(expandedStack) {
  1082  			f, more := cf.Next()
  1083  			// f.PC is a "call PC", but later consumers will expect
  1084  			// "return PCs"
  1085  			expandedStack[j] = f.PC + 1
  1086  			j++
  1087  			if !more {
  1088  				break
  1089  			}
  1090  		}
  1091  		k := copy(p[i].Stack0[:], expandedStack[:j])
  1092  		clear(p[i].Stack0[k:])
  1093  	}
  1094  }
  1095  
  1096  // blockProfileInternal returns the number of records n in the profile. If there
  1097  // are less than size records, copyFn is invoked for each record, and ok returns
  1098  // true.
  1099  func blockProfileInternal(size int, copyFn func(profilerecord.BlockProfileRecord)) (n int, ok bool) {
  1100  	lock(&profBlockLock)
  1101  	head := (*bucket)(bbuckets.Load())
  1102  	for b := head; b != nil; b = b.allnext {
  1103  		n++
  1104  	}
  1105  	if n <= size {
  1106  		ok = true
  1107  		for b := head; b != nil; b = b.allnext {
  1108  			bp := b.bp()
  1109  			r := profilerecord.BlockProfileRecord{
  1110  				Count:  int64(bp.count),
  1111  				Cycles: bp.cycles,
  1112  				Stack:  b.stk(),
  1113  			}
  1114  			// Prevent callers from having to worry about division by zero errors.
  1115  			// See discussion on http://golang.org/cl/299991.
  1116  			if r.Count == 0 {
  1117  				r.Count = 1
  1118  			}
  1119  			copyFn(r)
  1120  		}
  1121  	}
  1122  	unlock(&profBlockLock)
  1123  	return
  1124  }
  1125  
  1126  // copyBlockProfileRecord copies the sample values and call stack from src to dst.
  1127  // The call stack is copied as-is. The caller is responsible for handling inline
  1128  // expansion, needed when the call stack was collected with frame pointer unwinding.
  1129  func copyBlockProfileRecord(dst *BlockProfileRecord, src profilerecord.BlockProfileRecord) {
  1130  	dst.Count = src.Count
  1131  	dst.Cycles = src.Cycles
  1132  	if raceenabled {
  1133  		racewriterangepc(unsafe.Pointer(&dst.Stack0[0]), unsafe.Sizeof(dst.Stack0), sys.GetCallerPC(), abi.FuncPCABIInternal(BlockProfile))
  1134  	}
  1135  	if msanenabled {
  1136  		msanwrite(unsafe.Pointer(&dst.Stack0[0]), unsafe.Sizeof(dst.Stack0))
  1137  	}
  1138  	if asanenabled {
  1139  		asanwrite(unsafe.Pointer(&dst.Stack0[0]), unsafe.Sizeof(dst.Stack0))
  1140  	}
  1141  	// We just copy the stack here without inline expansion
  1142  	// (needed if frame pointer unwinding is used)
  1143  	// since this function is called under the profile lock,
  1144  	// and doing something that might allocate can violate lock ordering.
  1145  	i := copy(dst.Stack0[:], src.Stack)
  1146  	clear(dst.Stack0[i:])
  1147  }
  1148  
  1149  //go:linkname pprof_blockProfileInternal
  1150  func pprof_blockProfileInternal(p []profilerecord.BlockProfileRecord) (n int, ok bool) {
  1151  	return blockProfileInternal(len(p), func(r profilerecord.BlockProfileRecord) {
  1152  		p[0] = r
  1153  		p = p[1:]
  1154  	})
  1155  }
  1156  
  1157  // MutexProfile returns n, the number of records in the current mutex profile.
  1158  // If len(p) >= n, MutexProfile copies the profile into p and returns n, true.
  1159  // Otherwise, MutexProfile does not change p, and returns n, false.
  1160  //
  1161  // Most clients should use the [runtime/pprof] package
  1162  // instead of calling MutexProfile directly.
  1163  func MutexProfile(p []BlockProfileRecord) (n int, ok bool) {
  1164  	var m int
  1165  	n, ok = mutexProfileInternal(len(p), func(r profilerecord.BlockProfileRecord) {
  1166  		copyBlockProfileRecord(&p[m], r)
  1167  		m++
  1168  	})
  1169  	if ok {
  1170  		expandFrames(p[:n])
  1171  	}
  1172  	return
  1173  }
  1174  
  1175  // mutexProfileInternal returns the number of records n in the profile. If there
  1176  // are less than size records, copyFn is invoked for each record, and ok returns
  1177  // true.
  1178  func mutexProfileInternal(size int, copyFn func(profilerecord.BlockProfileRecord)) (n int, ok bool) {
  1179  	lock(&profBlockLock)
  1180  	head := (*bucket)(xbuckets.Load())
  1181  	for b := head; b != nil; b = b.allnext {
  1182  		n++
  1183  	}
  1184  	if n <= size {
  1185  		ok = true
  1186  		for b := head; b != nil; b = b.allnext {
  1187  			bp := b.bp()
  1188  			r := profilerecord.BlockProfileRecord{
  1189  				Count:  int64(bp.count),
  1190  				Cycles: bp.cycles,
  1191  				Stack:  b.stk(),
  1192  			}
  1193  			copyFn(r)
  1194  		}
  1195  	}
  1196  	unlock(&profBlockLock)
  1197  	return
  1198  }
  1199  
  1200  //go:linkname pprof_mutexProfileInternal
  1201  func pprof_mutexProfileInternal(p []profilerecord.BlockProfileRecord) (n int, ok bool) {
  1202  	return mutexProfileInternal(len(p), func(r profilerecord.BlockProfileRecord) {
  1203  		p[0] = r
  1204  		p = p[1:]
  1205  	})
  1206  }
  1207  
  1208  // ThreadCreateProfile returns n, the number of records in the thread creation profile.
  1209  // If len(p) >= n, ThreadCreateProfile copies the profile into p and returns n, true.
  1210  // If len(p) < n, ThreadCreateProfile does not change p and returns n, false.
  1211  //
  1212  // Most clients should use the runtime/pprof package instead
  1213  // of calling ThreadCreateProfile directly.
  1214  func ThreadCreateProfile(p []StackRecord) (n int, ok bool) {
  1215  	return threadCreateProfileInternal(len(p), func(r profilerecord.StackRecord) {
  1216  		i := copy(p[0].Stack0[:], r.Stack)
  1217  		clear(p[0].Stack0[i:])
  1218  		p = p[1:]
  1219  	})
  1220  }
  1221  
  1222  // threadCreateProfileInternal returns the number of records n in the profile.
  1223  // If there are less than size records, copyFn is invoked for each record, and
  1224  // ok returns true.
  1225  func threadCreateProfileInternal(size int, copyFn func(profilerecord.StackRecord)) (n int, ok bool) {
  1226  	first := (*m)(atomic.Loadp(unsafe.Pointer(&allm)))
  1227  	for mp := first; mp != nil; mp = mp.alllink {
  1228  		n++
  1229  	}
  1230  	if n <= size {
  1231  		ok = true
  1232  		for mp := first; mp != nil; mp = mp.alllink {
  1233  			r := profilerecord.StackRecord{Stack: mp.createstack[:]}
  1234  			copyFn(r)
  1235  		}
  1236  	}
  1237  	return
  1238  }
  1239  
  1240  //go:linkname pprof_threadCreateInternal
  1241  func pprof_threadCreateInternal(p []profilerecord.StackRecord) (n int, ok bool) {
  1242  	return threadCreateProfileInternal(len(p), func(r profilerecord.StackRecord) {
  1243  		p[0] = r
  1244  		p = p[1:]
  1245  	})
  1246  }
  1247  
  1248  //go:linkname pprof_goroutineProfileWithLabels
  1249  func pprof_goroutineProfileWithLabels(p []profilerecord.StackRecord, labels []unsafe.Pointer) (n int, ok bool) {
  1250  	return goroutineProfileWithLabels(p, labels)
  1251  }
  1252  
  1253  // labels may be nil. If labels is non-nil, it must have the same length as p.
  1254  func goroutineProfileWithLabels(p []profilerecord.StackRecord, labels []unsafe.Pointer) (n int, ok bool) {
  1255  	if labels != nil && len(labels) != len(p) {
  1256  		labels = nil
  1257  	}
  1258  
  1259  	return goroutineProfileWithLabelsConcurrent(p, labels)
  1260  }
  1261  
  1262  var goroutineProfile = struct {
  1263  	sema    uint32
  1264  	active  bool
  1265  	offset  atomic.Int64
  1266  	records []profilerecord.StackRecord
  1267  	labels  []unsafe.Pointer
  1268  }{
  1269  	sema: 1,
  1270  }
  1271  
  1272  // goroutineProfileState indicates the status of a goroutine's stack for the
  1273  // current in-progress goroutine profile. Goroutines' stacks are initially
  1274  // "Absent" from the profile, and end up "Satisfied" by the time the profile is
  1275  // complete. While a goroutine's stack is being captured, its
  1276  // goroutineProfileState will be "InProgress" and it will not be able to run
  1277  // until the capture completes and the state moves to "Satisfied".
  1278  //
  1279  // Some goroutines (the finalizer goroutine, which at various times can be
  1280  // either a "system" or a "user" goroutine, and the goroutine that is
  1281  // coordinating the profile, any goroutines created during the profile) move
  1282  // directly to the "Satisfied" state.
  1283  type goroutineProfileState uint32
  1284  
  1285  const (
  1286  	goroutineProfileAbsent goroutineProfileState = iota
  1287  	goroutineProfileInProgress
  1288  	goroutineProfileSatisfied
  1289  )
  1290  
  1291  type goroutineProfileStateHolder atomic.Uint32
  1292  
  1293  func (p *goroutineProfileStateHolder) Load() goroutineProfileState {
  1294  	return goroutineProfileState((*atomic.Uint32)(p).Load())
  1295  }
  1296  
  1297  func (p *goroutineProfileStateHolder) Store(value goroutineProfileState) {
  1298  	(*atomic.Uint32)(p).Store(uint32(value))
  1299  }
  1300  
  1301  func (p *goroutineProfileStateHolder) CompareAndSwap(old, new goroutineProfileState) bool {
  1302  	return (*atomic.Uint32)(p).CompareAndSwap(uint32(old), uint32(new))
  1303  }
  1304  
  1305  func goroutineProfileWithLabelsConcurrent(p []profilerecord.StackRecord, labels []unsafe.Pointer) (n int, ok bool) {
  1306  	if len(p) == 0 {
  1307  		// An empty slice is obviously too small. Return a rough
  1308  		// allocation estimate without bothering to STW. As long as
  1309  		// this is close, then we'll only need to STW once (on the next
  1310  		// call).
  1311  		return int(gcount()), false
  1312  	}
  1313  
  1314  	semacquire(&goroutineProfile.sema)
  1315  
  1316  	ourg := getg()
  1317  
  1318  	pcbuf := makeProfStack() // see saveg() for explanation
  1319  	stw := stopTheWorld(stwGoroutineProfile)
  1320  	// Using gcount while the world is stopped should give us a consistent view
  1321  	// of the number of live goroutines, minus the number of goroutines that are
  1322  	// alive and permanently marked as "system". But to make this count agree
  1323  	// with what we'd get from isSystemGoroutine, we need special handling for
  1324  	// goroutines that can vary between user and system to ensure that the count
  1325  	// doesn't change during the collection. So, check the finalizer goroutine
  1326  	// and cleanup goroutines in particular.
  1327  	n = int(gcount())
  1328  	if fingStatus.Load()&fingRunningFinalizer != 0 {
  1329  		n++
  1330  	}
  1331  	n += int(gcCleanups.running.Load())
  1332  
  1333  	if n > len(p) {
  1334  		// There's not enough space in p to store the whole profile, so (per the
  1335  		// contract of runtime.GoroutineProfile) we're not allowed to write to p
  1336  		// at all and must return n, false.
  1337  		startTheWorld(stw)
  1338  		semrelease(&goroutineProfile.sema)
  1339  		return n, false
  1340  	}
  1341  
  1342  	// Save current goroutine.
  1343  	sp := sys.GetCallerSP()
  1344  	pc := sys.GetCallerPC()
  1345  	systemstack(func() {
  1346  		saveg(pc, sp, ourg, &p[0], pcbuf)
  1347  	})
  1348  	if labels != nil {
  1349  		labels[0] = ourg.labels
  1350  	}
  1351  	ourg.goroutineProfiled.Store(goroutineProfileSatisfied)
  1352  	goroutineProfile.offset.Store(1)
  1353  
  1354  	// Prepare for all other goroutines to enter the profile. Aside from ourg,
  1355  	// every goroutine struct in the allgs list has its goroutineProfiled field
  1356  	// cleared. Any goroutine created from this point on (while
  1357  	// goroutineProfile.active is set) will start with its goroutineProfiled
  1358  	// field set to goroutineProfileSatisfied.
  1359  	goroutineProfile.active = true
  1360  	goroutineProfile.records = p
  1361  	goroutineProfile.labels = labels
  1362  	startTheWorld(stw)
  1363  
  1364  	// Visit each goroutine that existed as of the startTheWorld call above.
  1365  	//
  1366  	// New goroutines may not be in this list, but we didn't want to know about
  1367  	// them anyway. If they do appear in this list (via reusing a dead goroutine
  1368  	// struct, or racing to launch between the world restarting and us getting
  1369  	// the list), they will already have their goroutineProfiled field set to
  1370  	// goroutineProfileSatisfied before their state transitions out of _Gdead.
  1371  	//
  1372  	// Any goroutine that the scheduler tries to execute concurrently with this
  1373  	// call will start by adding itself to the profile (before the act of
  1374  	// executing can cause any changes in its stack).
  1375  	forEachGRace(func(gp1 *g) {
  1376  		tryRecordGoroutineProfile(gp1, pcbuf, Gosched)
  1377  	})
  1378  
  1379  	stw = stopTheWorld(stwGoroutineProfileCleanup)
  1380  	endOffset := goroutineProfile.offset.Swap(0)
  1381  	goroutineProfile.active = false
  1382  	goroutineProfile.records = nil
  1383  	goroutineProfile.labels = nil
  1384  	startTheWorld(stw)
  1385  
  1386  	// Restore the invariant that every goroutine struct in allgs has its
  1387  	// goroutineProfiled field cleared.
  1388  	forEachGRace(func(gp1 *g) {
  1389  		gp1.goroutineProfiled.Store(goroutineProfileAbsent)
  1390  	})
  1391  
  1392  	if raceenabled {
  1393  		raceacquire(unsafe.Pointer(&labelSync))
  1394  	}
  1395  
  1396  	if n != int(endOffset) {
  1397  		// It's a big surprise that the number of goroutines changed while we
  1398  		// were collecting the profile. But probably better to return a
  1399  		// truncated profile than to crash the whole process.
  1400  		//
  1401  		// For instance, needm moves a goroutine out of the _Gdead state and so
  1402  		// might be able to change the goroutine count without interacting with
  1403  		// the scheduler. For code like that, the race windows are small and the
  1404  		// combination of features is uncommon, so it's hard to be (and remain)
  1405  		// sure we've caught them all.
  1406  	}
  1407  
  1408  	semrelease(&goroutineProfile.sema)
  1409  	return n, true
  1410  }
  1411  
  1412  // tryRecordGoroutineProfileWB asserts that write barriers are allowed and calls
  1413  // tryRecordGoroutineProfile.
  1414  //
  1415  //go:yeswritebarrierrec
  1416  func tryRecordGoroutineProfileWB(gp1 *g) {
  1417  	if getg().m.p.ptr() == nil {
  1418  		throw("no P available, write barriers are forbidden")
  1419  	}
  1420  	tryRecordGoroutineProfile(gp1, nil, osyield)
  1421  }
  1422  
  1423  // tryRecordGoroutineProfile ensures that gp1 has the appropriate representation
  1424  // in the current goroutine profile: either that it should not be profiled, or
  1425  // that a snapshot of its call stack and labels are now in the profile.
  1426  func tryRecordGoroutineProfile(gp1 *g, pcbuf []uintptr, yield func()) {
  1427  	if readgstatus(gp1) == _Gdead {
  1428  		// Dead goroutines should not appear in the profile. Goroutines that
  1429  		// start while profile collection is active will get goroutineProfiled
  1430  		// set to goroutineProfileSatisfied before transitioning out of _Gdead,
  1431  		// so here we check _Gdead first.
  1432  		return
  1433  	}
  1434  
  1435  	for {
  1436  		prev := gp1.goroutineProfiled.Load()
  1437  		if prev == goroutineProfileSatisfied {
  1438  			// This goroutine is already in the profile (or is new since the
  1439  			// start of collection, so shouldn't appear in the profile).
  1440  			break
  1441  		}
  1442  		if prev == goroutineProfileInProgress {
  1443  			// Something else is adding gp1 to the goroutine profile right now.
  1444  			// Give that a moment to finish.
  1445  			yield()
  1446  			continue
  1447  		}
  1448  
  1449  		// While we have gp1.goroutineProfiled set to
  1450  		// goroutineProfileInProgress, gp1 may appear _Grunnable but will not
  1451  		// actually be able to run. Disable preemption for ourselves, to make
  1452  		// sure we finish profiling gp1 right away instead of leaving it stuck
  1453  		// in this limbo.
  1454  		mp := acquirem()
  1455  		if gp1.goroutineProfiled.CompareAndSwap(goroutineProfileAbsent, goroutineProfileInProgress) {
  1456  			doRecordGoroutineProfile(gp1, pcbuf)
  1457  			gp1.goroutineProfiled.Store(goroutineProfileSatisfied)
  1458  		}
  1459  		releasem(mp)
  1460  	}
  1461  }
  1462  
  1463  // doRecordGoroutineProfile writes gp1's call stack and labels to an in-progress
  1464  // goroutine profile. Preemption is disabled.
  1465  //
  1466  // This may be called via tryRecordGoroutineProfile in two ways: by the
  1467  // goroutine that is coordinating the goroutine profile (running on its own
  1468  // stack), or from the scheduler in preparation to execute gp1 (running on the
  1469  // system stack).
  1470  func doRecordGoroutineProfile(gp1 *g, pcbuf []uintptr) {
  1471  	if isSystemGoroutine(gp1, false) {
  1472  		// System goroutines should not appear in the profile.
  1473  		// Check this here and not in tryRecordGoroutineProfile because isSystemGoroutine
  1474  		// may change on a goroutine while it is executing, so while the scheduler might
  1475  		// see a system goroutine, goroutineProfileWithLabelsConcurrent might not, and
  1476  		// this inconsistency could cause invariants to be violated, such as trying to
  1477  		// record the stack of a running goroutine below. In short, we still want system
  1478  		// goroutines to participate in the same state machine on gp1.goroutineProfiled as
  1479  		// everything else, we just don't record the stack in the profile.
  1480  		return
  1481  	}
  1482  	if readgstatus(gp1) == _Grunning {
  1483  		print("doRecordGoroutineProfile gp1=", gp1.goid, "\n")
  1484  		throw("cannot read stack of running goroutine")
  1485  	}
  1486  
  1487  	offset := int(goroutineProfile.offset.Add(1)) - 1
  1488  
  1489  	if offset >= len(goroutineProfile.records) {
  1490  		// Should be impossible, but better to return a truncated profile than
  1491  		// to crash the entire process at this point. Instead, deal with it in
  1492  		// goroutineProfileWithLabelsConcurrent where we have more context.
  1493  		return
  1494  	}
  1495  
  1496  	// saveg calls gentraceback, which may call cgo traceback functions. When
  1497  	// called from the scheduler, this is on the system stack already so
  1498  	// traceback.go:cgoContextPCs will avoid calling back into the scheduler.
  1499  	//
  1500  	// When called from the goroutine coordinating the profile, we still have
  1501  	// set gp1.goroutineProfiled to goroutineProfileInProgress and so are still
  1502  	// preventing it from being truly _Grunnable. So we'll use the system stack
  1503  	// to avoid schedule delays.
  1504  	systemstack(func() { saveg(^uintptr(0), ^uintptr(0), gp1, &goroutineProfile.records[offset], pcbuf) })
  1505  
  1506  	if goroutineProfile.labels != nil {
  1507  		goroutineProfile.labels[offset] = gp1.labels
  1508  	}
  1509  }
  1510  
  1511  func goroutineProfileWithLabelsSync(p []profilerecord.StackRecord, labels []unsafe.Pointer) (n int, ok bool) {
  1512  	gp := getg()
  1513  
  1514  	isOK := func(gp1 *g) bool {
  1515  		// Checking isSystemGoroutine here makes GoroutineProfile
  1516  		// consistent with both NumGoroutine and Stack.
  1517  		return gp1 != gp && readgstatus(gp1) != _Gdead && !isSystemGoroutine(gp1, false)
  1518  	}
  1519  
  1520  	pcbuf := makeProfStack() // see saveg() for explanation
  1521  	stw := stopTheWorld(stwGoroutineProfile)
  1522  
  1523  	// World is stopped, no locking required.
  1524  	n = 1
  1525  	forEachGRace(func(gp1 *g) {
  1526  		if isOK(gp1) {
  1527  			n++
  1528  		}
  1529  	})
  1530  
  1531  	if n <= len(p) {
  1532  		ok = true
  1533  		r, lbl := p, labels
  1534  
  1535  		// Save current goroutine.
  1536  		sp := sys.GetCallerSP()
  1537  		pc := sys.GetCallerPC()
  1538  		systemstack(func() {
  1539  			saveg(pc, sp, gp, &r[0], pcbuf)
  1540  		})
  1541  		r = r[1:]
  1542  
  1543  		// If we have a place to put our goroutine labelmap, insert it there.
  1544  		if labels != nil {
  1545  			lbl[0] = gp.labels
  1546  			lbl = lbl[1:]
  1547  		}
  1548  
  1549  		// Save other goroutines.
  1550  		forEachGRace(func(gp1 *g) {
  1551  			if !isOK(gp1) {
  1552  				return
  1553  			}
  1554  
  1555  			if len(r) == 0 {
  1556  				// Should be impossible, but better to return a
  1557  				// truncated profile than to crash the entire process.
  1558  				return
  1559  			}
  1560  			// saveg calls gentraceback, which may call cgo traceback functions.
  1561  			// The world is stopped, so it cannot use cgocall (which will be
  1562  			// blocked at exitsyscall). Do it on the system stack so it won't
  1563  			// call into the schedular (see traceback.go:cgoContextPCs).
  1564  			systemstack(func() { saveg(^uintptr(0), ^uintptr(0), gp1, &r[0], pcbuf) })
  1565  			if labels != nil {
  1566  				lbl[0] = gp1.labels
  1567  				lbl = lbl[1:]
  1568  			}
  1569  			r = r[1:]
  1570  		})
  1571  	}
  1572  
  1573  	if raceenabled {
  1574  		raceacquire(unsafe.Pointer(&labelSync))
  1575  	}
  1576  
  1577  	startTheWorld(stw)
  1578  	return n, ok
  1579  }
  1580  
  1581  // GoroutineProfile returns n, the number of records in the active goroutine stack profile.
  1582  // If len(p) >= n, GoroutineProfile copies the profile into p and returns n, true.
  1583  // If len(p) < n, GoroutineProfile does not change p and returns n, false.
  1584  //
  1585  // Most clients should use the [runtime/pprof] package instead
  1586  // of calling GoroutineProfile directly.
  1587  func GoroutineProfile(p []StackRecord) (n int, ok bool) {
  1588  	records := make([]profilerecord.StackRecord, len(p))
  1589  	n, ok = goroutineProfileInternal(records)
  1590  	if !ok {
  1591  		return
  1592  	}
  1593  	for i, mr := range records[0:n] {
  1594  		l := copy(p[i].Stack0[:], mr.Stack)
  1595  		clear(p[i].Stack0[l:])
  1596  	}
  1597  	return
  1598  }
  1599  
  1600  func goroutineProfileInternal(p []profilerecord.StackRecord) (n int, ok bool) {
  1601  	return goroutineProfileWithLabels(p, nil)
  1602  }
  1603  
  1604  func saveg(pc, sp uintptr, gp *g, r *profilerecord.StackRecord, pcbuf []uintptr) {
  1605  	// To reduce memory usage, we want to allocate a r.Stack that is just big
  1606  	// enough to hold gp's stack trace. Naively we might achieve this by
  1607  	// recording our stack trace into mp.profStack, and then allocating a
  1608  	// r.Stack of the right size. However, mp.profStack is also used for
  1609  	// allocation profiling, so it could get overwritten if the slice allocation
  1610  	// gets profiled. So instead we record the stack trace into a temporary
  1611  	// pcbuf which is usually given to us by our caller. When it's not, we have
  1612  	// to allocate one here. This will only happen for goroutines that were in a
  1613  	// syscall when the goroutine profile started or for goroutines that manage
  1614  	// to execute before we finish iterating over all the goroutines.
  1615  	if pcbuf == nil {
  1616  		pcbuf = makeProfStack()
  1617  	}
  1618  
  1619  	var u unwinder
  1620  	u.initAt(pc, sp, 0, gp, unwindSilentErrors)
  1621  	n := tracebackPCs(&u, 0, pcbuf)
  1622  	r.Stack = make([]uintptr, n)
  1623  	copy(r.Stack, pcbuf)
  1624  }
  1625  
  1626  // Stack formats a stack trace of the calling goroutine into buf
  1627  // and returns the number of bytes written to buf.
  1628  // If all is true, Stack formats stack traces of all other goroutines
  1629  // into buf after the trace for the current goroutine.
  1630  func Stack(buf []byte, all bool) int {
  1631  	var stw worldStop
  1632  	if all {
  1633  		stw = stopTheWorld(stwAllGoroutinesStack)
  1634  	}
  1635  
  1636  	n := 0
  1637  	if len(buf) > 0 {
  1638  		gp := getg()
  1639  		sp := sys.GetCallerSP()
  1640  		pc := sys.GetCallerPC()
  1641  		systemstack(func() {
  1642  			g0 := getg()
  1643  			// Force traceback=1 to override GOTRACEBACK setting,
  1644  			// so that Stack's results are consistent.
  1645  			// GOTRACEBACK is only about crash dumps.
  1646  			g0.m.traceback = 1
  1647  			g0.writebuf = buf[0:0:len(buf)]
  1648  			goroutineheader(gp)
  1649  			traceback(pc, sp, 0, gp)
  1650  			if all {
  1651  				tracebackothers(gp)
  1652  			}
  1653  			g0.m.traceback = 0
  1654  			n = len(g0.writebuf)
  1655  			g0.writebuf = nil
  1656  		})
  1657  	}
  1658  
  1659  	if all {
  1660  		startTheWorld(stw)
  1661  	}
  1662  	return n
  1663  }
  1664  

View as plain text