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

View as plain text