Source file src/runtime/traceruntime.go

     1  // Copyright 2023 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  // Runtime -> tracer API.
     6  
     7  package runtime
     8  
     9  import (
    10  	"internal/runtime/atomic"
    11  	_ "unsafe" // for go:linkname
    12  )
    13  
    14  // gTraceState is per-G state for the tracer.
    15  type gTraceState struct {
    16  	traceSchedResourceState
    17  }
    18  
    19  // reset resets the gTraceState for a new goroutine.
    20  func (s *gTraceState) reset() {
    21  	s.seq = [2]uint64{}
    22  	// N.B. s.statusTraced is managed and cleared separately.
    23  }
    24  
    25  // mTraceState is per-M state for the tracer.
    26  type mTraceState struct {
    27  	seqlock atomic.Uintptr // seqlock indicating that this M is writing to a trace buffer.
    28  	buf     [2]*traceBuf   // Per-M traceBuf for writing. Indexed by trace.gen%2.
    29  	link    *m             // Snapshot of alllink or freelink.
    30  }
    31  
    32  // pTraceState is per-P state for the tracer.
    33  type pTraceState struct {
    34  	traceSchedResourceState
    35  
    36  	// mSyscallID is the ID of the M this was bound to before entering a syscall.
    37  	mSyscallID int64
    38  
    39  	// maySweep indicates the sweep events should be traced.
    40  	// This is used to defer the sweep start event until a span
    41  	// has actually been swept.
    42  	maySweep bool
    43  
    44  	// inSweep indicates that at least one sweep event has been traced.
    45  	inSweep bool
    46  
    47  	// swept and reclaimed track the number of bytes swept and reclaimed
    48  	// by sweeping in the current sweep loop (while maySweep was true).
    49  	swept, reclaimed uintptr
    50  }
    51  
    52  // traceLockInit initializes global trace locks.
    53  func traceLockInit() {
    54  	// Sharing a lock rank here is fine because they should never be accessed
    55  	// together. If they are, we want to find out immediately.
    56  	lockInit(&trace.stringTab[0].lock, lockRankTraceStrings)
    57  	lockInit(&trace.stringTab[0].tab.mem.lock, lockRankTraceStrings)
    58  	lockInit(&trace.stringTab[1].lock, lockRankTraceStrings)
    59  	lockInit(&trace.stringTab[1].tab.mem.lock, lockRankTraceStrings)
    60  	lockInit(&trace.stackTab[0].tab.mem.lock, lockRankTraceStackTab)
    61  	lockInit(&trace.stackTab[1].tab.mem.lock, lockRankTraceStackTab)
    62  	lockInit(&trace.typeTab[0].tab.mem.lock, lockRankTraceTypeTab)
    63  	lockInit(&trace.typeTab[1].tab.mem.lock, lockRankTraceTypeTab)
    64  	lockInit(&trace.lock, lockRankTrace)
    65  }
    66  
    67  // lockRankMayTraceFlush records the lock ranking effects of a
    68  // potential call to traceFlush.
    69  //
    70  // nosplit because traceAcquire is nosplit.
    71  //
    72  //go:nosplit
    73  func lockRankMayTraceFlush() {
    74  	lockWithRankMayAcquire(&trace.lock, getLockRank(&trace.lock))
    75  }
    76  
    77  // traceBlockReason is an enumeration of reasons a goroutine might block.
    78  // This is the interface the rest of the runtime uses to tell the
    79  // tracer why a goroutine blocked. The tracer then propagates this information
    80  // into the trace however it sees fit.
    81  //
    82  // Note that traceBlockReasons should not be compared, since reasons that are
    83  // distinct by name may *not* be distinct by value.
    84  type traceBlockReason uint8
    85  
    86  const (
    87  	traceBlockGeneric traceBlockReason = iota
    88  	traceBlockForever
    89  	traceBlockNet
    90  	traceBlockSelect
    91  	traceBlockCondWait
    92  	traceBlockSync
    93  	traceBlockChanSend
    94  	traceBlockChanRecv
    95  	traceBlockGCMarkAssist
    96  	traceBlockGCSweep
    97  	traceBlockSystemGoroutine
    98  	traceBlockPreempted
    99  	traceBlockDebugCall
   100  	traceBlockUntilGCEnds
   101  	traceBlockSleep
   102  )
   103  
   104  var traceBlockReasonStrings = [...]string{
   105  	traceBlockGeneric:         "unspecified",
   106  	traceBlockForever:         "forever",
   107  	traceBlockNet:             "network",
   108  	traceBlockSelect:          "select",
   109  	traceBlockCondWait:        "sync.(*Cond).Wait",
   110  	traceBlockSync:            "sync",
   111  	traceBlockChanSend:        "chan send",
   112  	traceBlockChanRecv:        "chan receive",
   113  	traceBlockGCMarkAssist:    "GC mark assist wait for work",
   114  	traceBlockGCSweep:         "GC background sweeper wait",
   115  	traceBlockSystemGoroutine: "system goroutine wait",
   116  	traceBlockPreempted:       "preempted",
   117  	traceBlockDebugCall:       "wait for debug call",
   118  	traceBlockUntilGCEnds:     "wait until GC ends",
   119  	traceBlockSleep:           "sleep",
   120  }
   121  
   122  // traceGoStopReason is an enumeration of reasons a goroutine might yield.
   123  //
   124  // Note that traceGoStopReasons should not be compared, since reasons that are
   125  // distinct by name may *not* be distinct by value.
   126  type traceGoStopReason uint8
   127  
   128  const (
   129  	traceGoStopGeneric traceGoStopReason = iota
   130  	traceGoStopGoSched
   131  	traceGoStopPreempted
   132  )
   133  
   134  var traceGoStopReasonStrings = [...]string{
   135  	traceGoStopGeneric:   "unspecified",
   136  	traceGoStopGoSched:   "runtime.Gosched",
   137  	traceGoStopPreempted: "preempted",
   138  }
   139  
   140  // traceEnabled returns true if the trace is currently enabled.
   141  //
   142  //go:nosplit
   143  func traceEnabled() bool {
   144  	return trace.enabled
   145  }
   146  
   147  // traceAllocFreeEnabled returns true if the trace is currently enabled
   148  // and alloc/free events are also enabled.
   149  //
   150  //go:nosplit
   151  func traceAllocFreeEnabled() bool {
   152  	return trace.enabledWithAllocFree
   153  }
   154  
   155  // traceShuttingDown returns true if the trace is currently shutting down.
   156  func traceShuttingDown() bool {
   157  	return trace.shutdown.Load()
   158  }
   159  
   160  // traceLocker represents an M writing trace events. While a traceLocker value
   161  // is valid, the tracer observes all operations on the G/M/P or trace events being
   162  // written as happening atomically.
   163  type traceLocker struct {
   164  	mp  *m
   165  	gen uintptr
   166  }
   167  
   168  // debugTraceReentrancy checks if the trace is reentrant.
   169  //
   170  // This is optional because throwing in a function makes it instantly
   171  // not inlineable, and we want traceAcquire to be inlineable for
   172  // low overhead when the trace is disabled.
   173  const debugTraceReentrancy = false
   174  
   175  // traceAcquire prepares this M for writing one or more trace events.
   176  //
   177  // nosplit because it's called on the syscall path when stack movement is forbidden.
   178  //
   179  //go:nosplit
   180  func traceAcquire() traceLocker {
   181  	if !traceEnabled() {
   182  		return traceLocker{}
   183  	}
   184  	return traceAcquireEnabled()
   185  }
   186  
   187  // traceAcquireEnabled is the traceEnabled path for traceAcquire. It's explicitly
   188  // broken out to make traceAcquire inlineable to keep the overhead of the tracer
   189  // when it's disabled low.
   190  //
   191  // nosplit because it's called by traceAcquire, which is nosplit.
   192  //
   193  //go:nosplit
   194  func traceAcquireEnabled() traceLocker {
   195  	// Any time we acquire a traceLocker, we may flush a trace buffer. But
   196  	// buffer flushes are rare. Record the lock edge even if it doesn't happen
   197  	// this time.
   198  	lockRankMayTraceFlush()
   199  
   200  	// Prevent preemption.
   201  	mp := acquirem()
   202  
   203  	// Acquire the trace seqlock. This prevents traceAdvance from moving forward
   204  	// until all Ms are observed to be outside of their seqlock critical section.
   205  	//
   206  	// Note: The seqlock is mutated here and also in traceCPUSample. If you update
   207  	// usage of the seqlock here, make sure to also look at what traceCPUSample is
   208  	// doing.
   209  	seq := mp.trace.seqlock.Add(1)
   210  	if debugTraceReentrancy && seq%2 != 1 {
   211  		throw("bad use of trace.seqlock or tracer is reentrant")
   212  	}
   213  
   214  	// N.B. This load of gen appears redundant with the one in traceEnabled.
   215  	// However, it's very important that the gen we use for writing to the trace
   216  	// is acquired under a traceLocker so traceAdvance can make sure no stale
   217  	// gen values are being used.
   218  	//
   219  	// Because we're doing this load again, it also means that the trace
   220  	// might end up being disabled when we load it. In that case we need to undo
   221  	// what we did and bail.
   222  	gen := trace.gen.Load()
   223  	if gen == 0 {
   224  		mp.trace.seqlock.Add(1)
   225  		releasem(mp)
   226  		return traceLocker{}
   227  	}
   228  	return traceLocker{mp, gen}
   229  }
   230  
   231  // ok returns true if the traceLocker is valid (i.e. tracing is enabled).
   232  //
   233  // nosplit because it's called on the syscall path when stack movement is forbidden.
   234  //
   235  //go:nosplit
   236  func (tl traceLocker) ok() bool {
   237  	return tl.gen != 0
   238  }
   239  
   240  // traceRelease indicates that this M is done writing trace events.
   241  //
   242  // nosplit because it's called on the syscall path when stack movement is forbidden.
   243  //
   244  //go:nosplit
   245  func traceRelease(tl traceLocker) {
   246  	seq := tl.mp.trace.seqlock.Add(1)
   247  	if debugTraceReentrancy && seq%2 != 0 {
   248  		print("runtime: seq=", seq, "\n")
   249  		throw("bad use of trace.seqlock")
   250  	}
   251  	releasem(tl.mp)
   252  }
   253  
   254  // traceExitingSyscall marks a goroutine as exiting the syscall slow path.
   255  //
   256  // Must be paired with a traceExitedSyscall call.
   257  func traceExitingSyscall() {
   258  	trace.exitingSyscall.Add(1)
   259  }
   260  
   261  // traceExitedSyscall marks a goroutine as having exited the syscall slow path.
   262  func traceExitedSyscall() {
   263  	trace.exitingSyscall.Add(-1)
   264  }
   265  
   266  // Gomaxprocs emits a ProcsChange event.
   267  func (tl traceLocker) Gomaxprocs(procs int32) {
   268  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvProcsChange, traceArg(procs), tl.stack(1))
   269  }
   270  
   271  // ProcStart traces a ProcStart event.
   272  //
   273  // Must be called with a valid P.
   274  func (tl traceLocker) ProcStart() {
   275  	pp := tl.mp.p.ptr()
   276  	// Procs are typically started within the scheduler when there is no user goroutine. If there is a user goroutine,
   277  	// it must be in _Gsyscall because the only time a goroutine is allowed to have its Proc moved around from under it
   278  	// is during a syscall.
   279  	tl.eventWriter(traceGoSyscall, traceProcIdle).commit(traceEvProcStart, traceArg(pp.id), pp.trace.nextSeq(tl.gen))
   280  }
   281  
   282  // ProcStop traces a ProcStop event.
   283  func (tl traceLocker) ProcStop(pp *p) {
   284  	// The only time a goroutine is allowed to have its Proc moved around
   285  	// from under it is during a syscall.
   286  	tl.eventWriter(traceGoSyscall, traceProcRunning).commit(traceEvProcStop)
   287  }
   288  
   289  // GCActive traces a GCActive event.
   290  //
   291  // Must be emitted by an actively running goroutine on an active P. This restriction can be changed
   292  // easily and only depends on where it's currently called.
   293  func (tl traceLocker) GCActive() {
   294  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvGCActive, traceArg(trace.seqGC))
   295  	// N.B. Only one GC can be running at a time, so this is naturally
   296  	// serialized by the caller.
   297  	trace.seqGC++
   298  }
   299  
   300  // GCStart traces a GCBegin event.
   301  //
   302  // Must be emitted by an actively running goroutine on an active P. This restriction can be changed
   303  // easily and only depends on where it's currently called.
   304  func (tl traceLocker) GCStart() {
   305  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvGCBegin, traceArg(trace.seqGC), tl.stack(3))
   306  	// N.B. Only one GC can be running at a time, so this is naturally
   307  	// serialized by the caller.
   308  	trace.seqGC++
   309  }
   310  
   311  // GCDone traces a GCEnd event.
   312  //
   313  // Must be emitted by an actively running goroutine on an active P. This restriction can be changed
   314  // easily and only depends on where it's currently called.
   315  func (tl traceLocker) GCDone() {
   316  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvGCEnd, traceArg(trace.seqGC))
   317  	// N.B. Only one GC can be running at a time, so this is naturally
   318  	// serialized by the caller.
   319  	trace.seqGC++
   320  }
   321  
   322  // STWStart traces a STWBegin event.
   323  func (tl traceLocker) STWStart(reason stwReason) {
   324  	// Although the current P may be in _Pgcstop here, we model the P as running during the STW. This deviates from the
   325  	// runtime's state tracking, but it's more accurate and doesn't result in any loss of information.
   326  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvSTWBegin, tl.string(reason.String()), tl.stack(2))
   327  }
   328  
   329  // STWDone traces a STWEnd event.
   330  func (tl traceLocker) STWDone() {
   331  	// Although the current P may be in _Pgcstop here, we model the P as running during the STW. This deviates from the
   332  	// runtime's state tracking, but it's more accurate and doesn't result in any loss of information.
   333  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvSTWEnd)
   334  }
   335  
   336  // GCSweepStart prepares to trace a sweep loop. This does not
   337  // emit any events until traceGCSweepSpan is called.
   338  //
   339  // GCSweepStart must be paired with traceGCSweepDone and there
   340  // must be no preemption points between these two calls.
   341  //
   342  // Must be called with a valid P.
   343  func (tl traceLocker) GCSweepStart() {
   344  	// Delay the actual GCSweepBegin event until the first span
   345  	// sweep. If we don't sweep anything, don't emit any events.
   346  	pp := tl.mp.p.ptr()
   347  	if pp.trace.maySweep {
   348  		throw("double traceGCSweepStart")
   349  	}
   350  	pp.trace.maySweep, pp.trace.swept, pp.trace.reclaimed = true, 0, 0
   351  }
   352  
   353  // GCSweepSpan traces the sweep of a single span. If this is
   354  // the first span swept since traceGCSweepStart was called, this
   355  // will emit a GCSweepBegin event.
   356  //
   357  // This may be called outside a traceGCSweepStart/traceGCSweepDone
   358  // pair; however, it will not emit any trace events in this case.
   359  //
   360  // Must be called with a valid P.
   361  func (tl traceLocker) GCSweepSpan(bytesSwept uintptr) {
   362  	pp := tl.mp.p.ptr()
   363  	if pp.trace.maySweep {
   364  		if pp.trace.swept == 0 {
   365  			tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvGCSweepBegin, tl.stack(1))
   366  			pp.trace.inSweep = true
   367  		}
   368  		pp.trace.swept += bytesSwept
   369  	}
   370  }
   371  
   372  // GCSweepDone finishes tracing a sweep loop. If any memory was
   373  // swept (i.e. traceGCSweepSpan emitted an event) then this will emit
   374  // a GCSweepEnd event.
   375  //
   376  // Must be called with a valid P.
   377  func (tl traceLocker) GCSweepDone() {
   378  	pp := tl.mp.p.ptr()
   379  	if !pp.trace.maySweep {
   380  		throw("missing traceGCSweepStart")
   381  	}
   382  	if pp.trace.inSweep {
   383  		tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvGCSweepEnd, traceArg(pp.trace.swept), traceArg(pp.trace.reclaimed))
   384  		pp.trace.inSweep = false
   385  	}
   386  	pp.trace.maySweep = false
   387  }
   388  
   389  // GCMarkAssistStart emits a MarkAssistBegin event.
   390  func (tl traceLocker) GCMarkAssistStart() {
   391  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvGCMarkAssistBegin, tl.stack(1))
   392  }
   393  
   394  // GCMarkAssistDone emits a MarkAssistEnd event.
   395  func (tl traceLocker) GCMarkAssistDone() {
   396  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvGCMarkAssistEnd)
   397  }
   398  
   399  // GoCreate emits a GoCreate event.
   400  func (tl traceLocker) GoCreate(newg *g, pc uintptr, blocked bool) {
   401  	newg.trace.setStatusTraced(tl.gen)
   402  	ev := traceEvGoCreate
   403  	if blocked {
   404  		ev = traceEvGoCreateBlocked
   405  	}
   406  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(ev, traceArg(newg.goid), tl.startPC(pc), tl.stack(2))
   407  }
   408  
   409  // GoStart emits a GoStart event.
   410  //
   411  // Must be called with a valid P.
   412  func (tl traceLocker) GoStart() {
   413  	gp := getg().m.curg
   414  	pp := gp.m.p
   415  	w := tl.eventWriter(traceGoRunnable, traceProcRunning)
   416  	w = w.write(traceEvGoStart, traceArg(gp.goid), gp.trace.nextSeq(tl.gen))
   417  	if pp.ptr().gcMarkWorkerMode != gcMarkWorkerNotWorker {
   418  		w = w.write(traceEvGoLabel, trace.markWorkerLabels[tl.gen%2][pp.ptr().gcMarkWorkerMode])
   419  	}
   420  	w.end()
   421  }
   422  
   423  // GoEnd emits a GoDestroy event.
   424  //
   425  // TODO(mknyszek): Rename this to GoDestroy.
   426  func (tl traceLocker) GoEnd() {
   427  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvGoDestroy)
   428  }
   429  
   430  // GoSched emits a GoStop event with a GoSched reason.
   431  func (tl traceLocker) GoSched() {
   432  	tl.GoStop(traceGoStopGoSched)
   433  }
   434  
   435  // GoPreempt emits a GoStop event with a GoPreempted reason.
   436  func (tl traceLocker) GoPreempt() {
   437  	tl.GoStop(traceGoStopPreempted)
   438  }
   439  
   440  // GoStop emits a GoStop event with the provided reason.
   441  func (tl traceLocker) GoStop(reason traceGoStopReason) {
   442  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvGoStop, traceArg(trace.goStopReasons[tl.gen%2][reason]), tl.stack(1))
   443  }
   444  
   445  // GoPark emits a GoBlock event with the provided reason.
   446  //
   447  // TODO(mknyszek): Replace traceBlockReason with waitReason. It's silly
   448  // that we have both, and waitReason is way more descriptive.
   449  func (tl traceLocker) GoPark(reason traceBlockReason, skip int) {
   450  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvGoBlock, traceArg(trace.goBlockReasons[tl.gen%2][reason]), tl.stack(skip))
   451  }
   452  
   453  // GoUnpark emits a GoUnblock event.
   454  func (tl traceLocker) GoUnpark(gp *g, skip int) {
   455  	// Emit a GoWaiting status if necessary for the unblocked goroutine.
   456  	w := tl.eventWriter(traceGoRunning, traceProcRunning)
   457  	// Careful: don't use the event writer. We never want status or in-progress events
   458  	// to trigger more in-progress events.
   459  	w.w = emitUnblockStatus(w.w, gp, tl.gen)
   460  	w.commit(traceEvGoUnblock, traceArg(gp.goid), gp.trace.nextSeq(tl.gen), tl.stack(skip))
   461  }
   462  
   463  // GoCoroswitch emits a GoSwitch event. If destroy is true, the calling goroutine
   464  // is simultaneously being destroyed.
   465  func (tl traceLocker) GoSwitch(nextg *g, destroy bool) {
   466  	// Emit a GoWaiting status if necessary for the unblocked goroutine.
   467  	w := tl.eventWriter(traceGoRunning, traceProcRunning)
   468  	// Careful: don't use the event writer. We never want status or in-progress events
   469  	// to trigger more in-progress events.
   470  	w.w = emitUnblockStatus(w.w, nextg, tl.gen)
   471  	ev := traceEvGoSwitch
   472  	if destroy {
   473  		ev = traceEvGoSwitchDestroy
   474  	}
   475  	w.commit(ev, traceArg(nextg.goid), nextg.trace.nextSeq(tl.gen))
   476  }
   477  
   478  // emitUnblockStatus emits a GoStatus GoWaiting event for a goroutine about to be
   479  // unblocked to the trace writer.
   480  func emitUnblockStatus(w traceWriter, gp *g, gen uintptr) traceWriter {
   481  	if !gp.trace.statusWasTraced(gen) && gp.trace.acquireStatus(gen) {
   482  		// TODO(go.dev/issue/65634): Although it would be nice to add a stack trace here of gp,
   483  		// we cannot safely do so. gp is in _Gwaiting and so we don't have ownership of its stack.
   484  		// We can fix this by acquiring the goroutine's scan bit.
   485  		w = w.writeGoStatus(gp.goid, -1, traceGoWaiting, gp.inMarkAssist, 0)
   486  	}
   487  	return w
   488  }
   489  
   490  // GoSysCall emits a GoSyscallBegin event.
   491  //
   492  // Must be called with a valid P.
   493  func (tl traceLocker) GoSysCall() {
   494  	// Scribble down the M that the P is currently attached to.
   495  	pp := tl.mp.p.ptr()
   496  	pp.trace.mSyscallID = int64(tl.mp.procid)
   497  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvGoSyscallBegin, pp.trace.nextSeq(tl.gen), tl.stack(1))
   498  }
   499  
   500  // GoSysExit emits a GoSyscallEnd event, possibly along with a GoSyscallBlocked event
   501  // if lostP is true.
   502  //
   503  // lostP must be true in all cases that a goroutine loses its P during a syscall.
   504  // This means it's not sufficient to check if it has no P. In particular, it needs to be
   505  // true in the following cases:
   506  // - The goroutine lost its P, it ran some other code, and then got it back. It's now running with that P.
   507  // - The goroutine lost its P and was unable to reacquire it, and is now running without a P.
   508  // - The goroutine lost its P and acquired a different one, and is now running with that P.
   509  func (tl traceLocker) GoSysExit(lostP bool) {
   510  	ev := traceEvGoSyscallEnd
   511  	procStatus := traceProcSyscall // Procs implicitly enter traceProcSyscall on GoSyscallBegin.
   512  	if lostP {
   513  		ev = traceEvGoSyscallEndBlocked
   514  		procStatus = traceProcRunning // If a G has a P when emitting this event, it reacquired a P and is indeed running.
   515  	} else {
   516  		tl.mp.p.ptr().trace.mSyscallID = -1
   517  	}
   518  	tl.eventWriter(traceGoSyscall, procStatus).commit(ev)
   519  }
   520  
   521  // ProcSteal indicates that our current M stole a P from another M.
   522  //
   523  // inSyscall indicates that we're stealing the P from a syscall context.
   524  //
   525  // The caller must have ownership of pp.
   526  func (tl traceLocker) ProcSteal(pp *p, inSyscall bool) {
   527  	// Grab the M ID we stole from.
   528  	mStolenFrom := pp.trace.mSyscallID
   529  	pp.trace.mSyscallID = -1
   530  
   531  	// The status of the proc and goroutine, if we need to emit one here, is not evident from the
   532  	// context of just emitting this event alone. There are two cases. Either we're trying to steal
   533  	// the P just to get its attention (e.g. STW or sysmon retake) or we're trying to steal a P for
   534  	// ourselves specifically to keep running. The two contexts look different, but can be summarized
   535  	// fairly succinctly. In the former, we're a regular running goroutine and proc, if we have either.
   536  	// In the latter, we're a goroutine in a syscall.
   537  	goStatus := traceGoRunning
   538  	procStatus := traceProcRunning
   539  	if inSyscall {
   540  		goStatus = traceGoSyscall
   541  		procStatus = traceProcSyscallAbandoned
   542  	}
   543  	w := tl.eventWriter(goStatus, procStatus)
   544  
   545  	// Emit the status of the P we're stealing. We may have *just* done this when creating the event
   546  	// writer but it's not guaranteed, even if inSyscall is true. Although it might seem like from a
   547  	// syscall context we're always stealing a P for ourselves, we may have not wired it up yet (so
   548  	// it wouldn't be visible to eventWriter) or we may not even intend to wire it up to ourselves
   549  	// at all (e.g. entersyscall_gcwait).
   550  	if !pp.trace.statusWasTraced(tl.gen) && pp.trace.acquireStatus(tl.gen) {
   551  		// Careful: don't use the event writer. We never want status or in-progress events
   552  		// to trigger more in-progress events.
   553  		w.w = w.w.writeProcStatus(uint64(pp.id), traceProcSyscallAbandoned, pp.trace.inSweep)
   554  	}
   555  	w.commit(traceEvProcSteal, traceArg(pp.id), pp.trace.nextSeq(tl.gen), traceArg(mStolenFrom))
   556  }
   557  
   558  // HeapAlloc emits a HeapAlloc event.
   559  func (tl traceLocker) HeapAlloc(live uint64) {
   560  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvHeapAlloc, traceArg(live))
   561  }
   562  
   563  // HeapGoal reads the current heap goal and emits a HeapGoal event.
   564  func (tl traceLocker) HeapGoal() {
   565  	heapGoal := gcController.heapGoal()
   566  	if heapGoal == ^uint64(0) {
   567  		// Heap-based triggering is disabled.
   568  		heapGoal = 0
   569  	}
   570  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvHeapGoal, traceArg(heapGoal))
   571  }
   572  
   573  // GoCreateSyscall indicates that a goroutine has transitioned from dead to GoSyscall.
   574  //
   575  // Unlike GoCreate, the caller must be running on gp.
   576  //
   577  // This occurs when C code calls into Go. On pthread platforms it occurs only when
   578  // a C thread calls into Go code for the first time.
   579  func (tl traceLocker) GoCreateSyscall(gp *g) {
   580  	// N.B. We should never trace a status for this goroutine (which we're currently running on),
   581  	// since we want this to appear like goroutine creation.
   582  	gp.trace.setStatusTraced(tl.gen)
   583  	tl.eventWriter(traceGoBad, traceProcBad).commit(traceEvGoCreateSyscall, traceArg(gp.goid))
   584  }
   585  
   586  // GoDestroySyscall indicates that a goroutine has transitioned from GoSyscall to dead.
   587  //
   588  // Must not have a P.
   589  //
   590  // This occurs when Go code returns back to C. On pthread platforms it occurs only when
   591  // the C thread is destroyed.
   592  func (tl traceLocker) GoDestroySyscall() {
   593  	// N.B. If we trace a status here, we must never have a P, and we must be on a goroutine
   594  	// that is in the syscall state.
   595  	tl.eventWriter(traceGoSyscall, traceProcBad).commit(traceEvGoDestroySyscall)
   596  }
   597  
   598  // To access runtime functions from runtime/trace.
   599  // See runtime/trace/annotation.go
   600  
   601  // trace_userTaskCreate emits a UserTaskCreate event.
   602  //
   603  //go:linkname trace_userTaskCreate runtime/trace.userTaskCreate
   604  func trace_userTaskCreate(id, parentID uint64, taskType string) {
   605  	tl := traceAcquire()
   606  	if !tl.ok() {
   607  		// Need to do this check because the caller won't have it.
   608  		return
   609  	}
   610  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvUserTaskBegin, traceArg(id), traceArg(parentID), tl.string(taskType), tl.stack(3))
   611  	traceRelease(tl)
   612  }
   613  
   614  // trace_userTaskEnd emits a UserTaskEnd event.
   615  //
   616  //go:linkname trace_userTaskEnd runtime/trace.userTaskEnd
   617  func trace_userTaskEnd(id uint64) {
   618  	tl := traceAcquire()
   619  	if !tl.ok() {
   620  		// Need to do this check because the caller won't have it.
   621  		return
   622  	}
   623  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvUserTaskEnd, traceArg(id), tl.stack(2))
   624  	traceRelease(tl)
   625  }
   626  
   627  // trace_userTaskEnd emits a UserRegionBegin or UserRegionEnd event,
   628  // depending on mode (0 == Begin, 1 == End).
   629  //
   630  // TODO(mknyszek): Just make this two functions.
   631  //
   632  //go:linkname trace_userRegion runtime/trace.userRegion
   633  func trace_userRegion(id, mode uint64, name string) {
   634  	tl := traceAcquire()
   635  	if !tl.ok() {
   636  		// Need to do this check because the caller won't have it.
   637  		return
   638  	}
   639  	var ev traceEv
   640  	switch mode {
   641  	case 0:
   642  		ev = traceEvUserRegionBegin
   643  	case 1:
   644  		ev = traceEvUserRegionEnd
   645  	default:
   646  		return
   647  	}
   648  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(ev, traceArg(id), tl.string(name), tl.stack(3))
   649  	traceRelease(tl)
   650  }
   651  
   652  // trace_userTaskEnd emits a UserRegionBegin or UserRegionEnd event.
   653  //
   654  //go:linkname trace_userLog runtime/trace.userLog
   655  func trace_userLog(id uint64, category, message string) {
   656  	tl := traceAcquire()
   657  	if !tl.ok() {
   658  		// Need to do this check because the caller won't have it.
   659  		return
   660  	}
   661  	tl.eventWriter(traceGoRunning, traceProcRunning).commit(traceEvUserLog, traceArg(id), tl.string(category), tl.uniqueString(message), tl.stack(3))
   662  	traceRelease(tl)
   663  }
   664  
   665  // traceThreadDestroy is called when a thread is removed from
   666  // sched.freem.
   667  //
   668  // mp must not be able to emit trace events anymore.
   669  //
   670  // sched.lock must be held to synchronize with traceAdvance.
   671  func traceThreadDestroy(mp *m) {
   672  	assertLockHeld(&sched.lock)
   673  
   674  	// Flush all outstanding buffers to maintain the invariant
   675  	// that an M only has active buffers while on sched.freem
   676  	// or allm.
   677  	//
   678  	// Perform a traceAcquire/traceRelease on behalf of mp to
   679  	// synchronize with the tracer trying to flush our buffer
   680  	// as well.
   681  	seq := mp.trace.seqlock.Add(1)
   682  	if debugTraceReentrancy && seq%2 != 1 {
   683  		throw("bad use of trace.seqlock or tracer is reentrant")
   684  	}
   685  	systemstack(func() {
   686  		lock(&trace.lock)
   687  		for i := range mp.trace.buf {
   688  			if mp.trace.buf[i] != nil {
   689  				// N.B. traceBufFlush accepts a generation, but it
   690  				// really just cares about gen%2.
   691  				traceBufFlush(mp.trace.buf[i], uintptr(i))
   692  				mp.trace.buf[i] = nil
   693  			}
   694  		}
   695  		unlock(&trace.lock)
   696  	})
   697  	seq1 := mp.trace.seqlock.Add(1)
   698  	if seq1 != seq+1 {
   699  		print("runtime: seq1=", seq1, "\n")
   700  		throw("bad use of trace.seqlock")
   701  	}
   702  }
   703  

View as plain text