Black Lives Matter. Support the Equal Justice Initiative.

Source file src/runtime/trace.go

Documentation: runtime

     1  // Copyright 2014 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  // Go execution tracer.
     6  // The tracer captures a wide range of execution events like goroutine
     7  // creation/blocking/unblocking, syscall enter/exit/block, GC-related events,
     8  // changes of heap size, processor start/stop, etc and writes them to a buffer
     9  // in a compact form. A precise nanosecond-precision timestamp and a stack
    10  // trace is captured for most events.
    11  // See https://golang.org/s/go15trace for more info.
    12  
    13  package runtime
    14  
    15  import (
    16  	"runtime/internal/sys"
    17  	"unsafe"
    18  )
    19  
    20  // Event types in the trace, args are given in square brackets.
    21  const (
    22  	traceEvNone              = 0  // unused
    23  	traceEvBatch             = 1  // start of per-P batch of events [pid, timestamp]
    24  	traceEvFrequency         = 2  // contains tracer timer frequency [frequency (ticks per second)]
    25  	traceEvStack             = 3  // stack [stack id, number of PCs, array of {PC, func string ID, file string ID, line}]
    26  	traceEvGomaxprocs        = 4  // current value of GOMAXPROCS [timestamp, GOMAXPROCS, stack id]
    27  	traceEvProcStart         = 5  // start of P [timestamp, thread id]
    28  	traceEvProcStop          = 6  // stop of P [timestamp]
    29  	traceEvGCStart           = 7  // GC start [timestamp, seq, stack id]
    30  	traceEvGCDone            = 8  // GC done [timestamp]
    31  	traceEvGCSTWStart        = 9  // GC STW start [timestamp, kind]
    32  	traceEvGCSTWDone         = 10 // GC STW done [timestamp]
    33  	traceEvGCSweepStart      = 11 // GC sweep start [timestamp, stack id]
    34  	traceEvGCSweepDone       = 12 // GC sweep done [timestamp, swept, reclaimed]
    35  	traceEvGoCreate          = 13 // goroutine creation [timestamp, new goroutine id, new stack id, stack id]
    36  	traceEvGoStart           = 14 // goroutine starts running [timestamp, goroutine id, seq]
    37  	traceEvGoEnd             = 15 // goroutine ends [timestamp]
    38  	traceEvGoStop            = 16 // goroutine stops (like in select{}) [timestamp, stack]
    39  	traceEvGoSched           = 17 // goroutine calls Gosched [timestamp, stack]
    40  	traceEvGoPreempt         = 18 // goroutine is preempted [timestamp, stack]
    41  	traceEvGoSleep           = 19 // goroutine calls Sleep [timestamp, stack]
    42  	traceEvGoBlock           = 20 // goroutine blocks [timestamp, stack]
    43  	traceEvGoUnblock         = 21 // goroutine is unblocked [timestamp, goroutine id, seq, stack]
    44  	traceEvGoBlockSend       = 22 // goroutine blocks on chan send [timestamp, stack]
    45  	traceEvGoBlockRecv       = 23 // goroutine blocks on chan recv [timestamp, stack]
    46  	traceEvGoBlockSelect     = 24 // goroutine blocks on select [timestamp, stack]
    47  	traceEvGoBlockSync       = 25 // goroutine blocks on Mutex/RWMutex [timestamp, stack]
    48  	traceEvGoBlockCond       = 26 // goroutine blocks on Cond [timestamp, stack]
    49  	traceEvGoBlockNet        = 27 // goroutine blocks on network [timestamp, stack]
    50  	traceEvGoSysCall         = 28 // syscall enter [timestamp, stack]
    51  	traceEvGoSysExit         = 29 // syscall exit [timestamp, goroutine id, seq, real timestamp]
    52  	traceEvGoSysBlock        = 30 // syscall blocks [timestamp]
    53  	traceEvGoWaiting         = 31 // denotes that goroutine is blocked when tracing starts [timestamp, goroutine id]
    54  	traceEvGoInSyscall       = 32 // denotes that goroutine is in syscall when tracing starts [timestamp, goroutine id]
    55  	traceEvHeapAlloc         = 33 // memstats.heap_live change [timestamp, heap_alloc]
    56  	traceEvNextGC            = 34 // memstats.next_gc change [timestamp, next_gc]
    57  	traceEvTimerGoroutine    = 35 // not currently used; previously denoted timer goroutine [timer goroutine id]
    58  	traceEvFutileWakeup      = 36 // denotes that the previous wakeup of this goroutine was futile [timestamp]
    59  	traceEvString            = 37 // string dictionary entry [ID, length, string]
    60  	traceEvGoStartLocal      = 38 // goroutine starts running on the same P as the last event [timestamp, goroutine id]
    61  	traceEvGoUnblockLocal    = 39 // goroutine is unblocked on the same P as the last event [timestamp, goroutine id, stack]
    62  	traceEvGoSysExitLocal    = 40 // syscall exit on the same P as the last event [timestamp, goroutine id, real timestamp]
    63  	traceEvGoStartLabel      = 41 // goroutine starts running with label [timestamp, goroutine id, seq, label string id]
    64  	traceEvGoBlockGC         = 42 // goroutine blocks on GC assist [timestamp, stack]
    65  	traceEvGCMarkAssistStart = 43 // GC mark assist start [timestamp, stack]
    66  	traceEvGCMarkAssistDone  = 44 // GC mark assist done [timestamp]
    67  	traceEvUserTaskCreate    = 45 // trace.NewContext [timestamp, internal task id, internal parent task id, stack, name string]
    68  	traceEvUserTaskEnd       = 46 // end of a task [timestamp, internal task id, stack]
    69  	traceEvUserRegion        = 47 // trace.WithRegion [timestamp, internal task id, mode(0:start, 1:end), stack, name string]
    70  	traceEvUserLog           = 48 // trace.Log [timestamp, internal task id, key string id, stack, value string]
    71  	traceEvCount             = 49
    72  	// Byte is used but only 6 bits are available for event type.
    73  	// The remaining 2 bits are used to specify the number of arguments.
    74  	// That means, the max event type value is 63.
    75  )
    76  
    77  const (
    78  	// Timestamps in trace are cputicks/traceTickDiv.
    79  	// This makes absolute values of timestamp diffs smaller,
    80  	// and so they are encoded in less number of bytes.
    81  	// 64 on x86 is somewhat arbitrary (one tick is ~20ns on a 3GHz machine).
    82  	// The suggested increment frequency for PowerPC's time base register is
    83  	// 512 MHz according to Power ISA v2.07 section 6.2, so we use 16 on ppc64
    84  	// and ppc64le.
    85  	// Tracing won't work reliably for architectures where cputicks is emulated
    86  	// by nanotime, so the value doesn't matter for those architectures.
    87  	traceTickDiv = 16 + 48*(sys.Goarch386|sys.GoarchAmd64)
    88  	// Maximum number of PCs in a single stack trace.
    89  	// Since events contain only stack id rather than whole stack trace,
    90  	// we can allow quite large values here.
    91  	traceStackSize = 128
    92  	// Identifier of a fake P that is used when we trace without a real P.
    93  	traceGlobProc = -1
    94  	// Maximum number of bytes to encode uint64 in base-128.
    95  	traceBytesPerNumber = 10
    96  	// Shift of the number of arguments in the first event byte.
    97  	traceArgCountShift = 6
    98  	// Flag passed to traceGoPark to denote that the previous wakeup of this
    99  	// goroutine was futile. For example, a goroutine was unblocked on a mutex,
   100  	// but another goroutine got ahead and acquired the mutex before the first
   101  	// goroutine is scheduled, so the first goroutine has to block again.
   102  	// Such wakeups happen on buffered channels and sync.Mutex,
   103  	// but are generally not interesting for end user.
   104  	traceFutileWakeup byte = 128
   105  )
   106  
   107  // trace is global tracing context.
   108  var trace struct {
   109  	lock          mutex       // protects the following members
   110  	lockOwner     *g          // to avoid deadlocks during recursive lock locks
   111  	enabled       bool        // when set runtime traces events
   112  	shutdown      bool        // set when we are waiting for trace reader to finish after setting enabled to false
   113  	headerWritten bool        // whether ReadTrace has emitted trace header
   114  	footerWritten bool        // whether ReadTrace has emitted trace footer
   115  	shutdownSema  uint32      // used to wait for ReadTrace completion
   116  	seqStart      uint64      // sequence number when tracing was started
   117  	ticksStart    int64       // cputicks when tracing was started
   118  	ticksEnd      int64       // cputicks when tracing was stopped
   119  	timeStart     int64       // nanotime when tracing was started
   120  	timeEnd       int64       // nanotime when tracing was stopped
   121  	seqGC         uint64      // GC start/done sequencer
   122  	reading       traceBufPtr // buffer currently handed off to user
   123  	empty         traceBufPtr // stack of empty buffers
   124  	fullHead      traceBufPtr // queue of full buffers
   125  	fullTail      traceBufPtr
   126  	reader        guintptr        // goroutine that called ReadTrace, or nil
   127  	stackTab      traceStackTable // maps stack traces to unique ids
   128  
   129  	// Dictionary for traceEvString.
   130  	//
   131  	// TODO: central lock to access the map is not ideal.
   132  	//   option: pre-assign ids to all user annotation region names and tags
   133  	//   option: per-P cache
   134  	//   option: sync.Map like data structure
   135  	stringsLock mutex
   136  	strings     map[string]uint64
   137  	stringSeq   uint64
   138  
   139  	// markWorkerLabels maps gcMarkWorkerMode to string ID.
   140  	markWorkerLabels [len(gcMarkWorkerModeStrings)]uint64
   141  
   142  	bufLock mutex       // protects buf
   143  	buf     traceBufPtr // global trace buffer, used when running without a p
   144  }
   145  
   146  // traceBufHeader is per-P tracing buffer.
   147  type traceBufHeader struct {
   148  	link      traceBufPtr             // in trace.empty/full
   149  	lastTicks uint64                  // when we wrote the last event
   150  	pos       int                     // next write offset in arr
   151  	stk       [traceStackSize]uintptr // scratch buffer for traceback
   152  }
   153  
   154  // traceBuf is per-P tracing buffer.
   155  //
   156  //go:notinheap
   157  type traceBuf struct {
   158  	traceBufHeader
   159  	arr [64<<10 - unsafe.Sizeof(traceBufHeader{})]byte // underlying buffer for traceBufHeader.buf
   160  }
   161  
   162  // traceBufPtr is a *traceBuf that is not traced by the garbage
   163  // collector and doesn't have write barriers. traceBufs are not
   164  // allocated from the GC'd heap, so this is safe, and are often
   165  // manipulated in contexts where write barriers are not allowed, so
   166  // this is necessary.
   167  //
   168  // TODO: Since traceBuf is now go:notinheap, this isn't necessary.
   169  type traceBufPtr uintptr
   170  
   171  func (tp traceBufPtr) ptr() *traceBuf   { return (*traceBuf)(unsafe.Pointer(tp)) }
   172  func (tp *traceBufPtr) set(b *traceBuf) { *tp = traceBufPtr(unsafe.Pointer(b)) }
   173  func traceBufPtrOf(b *traceBuf) traceBufPtr {
   174  	return traceBufPtr(unsafe.Pointer(b))
   175  }
   176  
   177  // StartTrace enables tracing for the current process.
   178  // While tracing, the data will be buffered and available via ReadTrace.
   179  // StartTrace returns an error if tracing is already enabled.
   180  // Most clients should use the runtime/trace package or the testing package's
   181  // -test.trace flag instead of calling StartTrace directly.
   182  func StartTrace() error {
   183  	// Stop the world so that we can take a consistent snapshot
   184  	// of all goroutines at the beginning of the trace.
   185  	// Do not stop the world during GC so we ensure we always see
   186  	// a consistent view of GC-related events (e.g. a start is always
   187  	// paired with an end).
   188  	stopTheWorldGC("start tracing")
   189  
   190  	// Prevent sysmon from running any code that could generate events.
   191  	lock(&sched.sysmonlock)
   192  
   193  	// We are in stop-the-world, but syscalls can finish and write to trace concurrently.
   194  	// Exitsyscall could check trace.enabled long before and then suddenly wake up
   195  	// and decide to write to trace at a random point in time.
   196  	// However, such syscall will use the global trace.buf buffer, because we've
   197  	// acquired all p's by doing stop-the-world. So this protects us from such races.
   198  	lock(&trace.bufLock)
   199  
   200  	if trace.enabled || trace.shutdown {
   201  		unlock(&trace.bufLock)
   202  		unlock(&sched.sysmonlock)
   203  		startTheWorldGC()
   204  		return errorString("tracing is already enabled")
   205  	}
   206  
   207  	// Can't set trace.enabled yet. While the world is stopped, exitsyscall could
   208  	// already emit a delayed event (see exitTicks in exitsyscall) if we set trace.enabled here.
   209  	// That would lead to an inconsistent trace:
   210  	// - either GoSysExit appears before EvGoInSyscall,
   211  	// - or GoSysExit appears for a goroutine for which we don't emit EvGoInSyscall below.
   212  	// To instruct traceEvent that it must not ignore events below, we set startingtrace.
   213  	// trace.enabled is set afterwards once we have emitted all preliminary events.
   214  	_g_ := getg()
   215  	_g_.m.startingtrace = true
   216  
   217  	// Obtain current stack ID to use in all traceEvGoCreate events below.
   218  	mp := acquirem()
   219  	stkBuf := make([]uintptr, traceStackSize)
   220  	stackID := traceStackID(mp, stkBuf, 2)
   221  	releasem(mp)
   222  
   223  	for _, gp := range allgs {
   224  		status := readgstatus(gp)
   225  		if status != _Gdead {
   226  			gp.traceseq = 0
   227  			gp.tracelastp = getg().m.p
   228  			// +PCQuantum because traceFrameForPC expects return PCs and subtracts PCQuantum.
   229  			id := trace.stackTab.put([]uintptr{gp.startpc + sys.PCQuantum})
   230  			traceEvent(traceEvGoCreate, -1, uint64(gp.goid), uint64(id), stackID)
   231  		}
   232  		if status == _Gwaiting {
   233  			// traceEvGoWaiting is implied to have seq=1.
   234  			gp.traceseq++
   235  			traceEvent(traceEvGoWaiting, -1, uint64(gp.goid))
   236  		}
   237  		if status == _Gsyscall {
   238  			gp.traceseq++
   239  			traceEvent(traceEvGoInSyscall, -1, uint64(gp.goid))
   240  		} else {
   241  			gp.sysblocktraced = false
   242  		}
   243  	}
   244  	traceProcStart()
   245  	traceGoStart()
   246  	// Note: ticksStart needs to be set after we emit traceEvGoInSyscall events.
   247  	// If we do it the other way around, it is possible that exitsyscall will
   248  	// query sysexitticks after ticksStart but before traceEvGoInSyscall timestamp.
   249  	// It will lead to a false conclusion that cputicks is broken.
   250  	trace.ticksStart = cputicks()
   251  	trace.timeStart = nanotime()
   252  	trace.headerWritten = false
   253  	trace.footerWritten = false
   254  
   255  	// string to id mapping
   256  	//  0 : reserved for an empty string
   257  	//  remaining: other strings registered by traceString
   258  	trace.stringSeq = 0
   259  	trace.strings = make(map[string]uint64)
   260  
   261  	trace.seqGC = 0
   262  	_g_.m.startingtrace = false
   263  	trace.enabled = true
   264  
   265  	// Register runtime goroutine labels.
   266  	_, pid, bufp := traceAcquireBuffer()
   267  	for i, label := range gcMarkWorkerModeStrings[:] {
   268  		trace.markWorkerLabels[i], bufp = traceString(bufp, pid, label)
   269  	}
   270  	traceReleaseBuffer(pid)
   271  
   272  	unlock(&trace.bufLock)
   273  
   274  	unlock(&sched.sysmonlock)
   275  
   276  	startTheWorldGC()
   277  	return nil
   278  }
   279  
   280  // StopTrace stops tracing, if it was previously enabled.
   281  // StopTrace only returns after all the reads for the trace have completed.
   282  func StopTrace() {
   283  	// Stop the world so that we can collect the trace buffers from all p's below,
   284  	// and also to avoid races with traceEvent.
   285  	stopTheWorldGC("stop tracing")
   286  
   287  	// See the comment in StartTrace.
   288  	lock(&sched.sysmonlock)
   289  
   290  	// See the comment in StartTrace.
   291  	lock(&trace.bufLock)
   292  
   293  	if !trace.enabled {
   294  		unlock(&trace.bufLock)
   295  		unlock(&sched.sysmonlock)
   296  		startTheWorldGC()
   297  		return
   298  	}
   299  
   300  	traceGoSched()
   301  
   302  	// Loop over all allocated Ps because dead Ps may still have
   303  	// trace buffers.
   304  	for _, p := range allp[:cap(allp)] {
   305  		buf := p.tracebuf
   306  		if buf != 0 {
   307  			traceFullQueue(buf)
   308  			p.tracebuf = 0
   309  		}
   310  	}
   311  	if trace.buf != 0 {
   312  		buf := trace.buf
   313  		trace.buf = 0
   314  		if buf.ptr().pos != 0 {
   315  			traceFullQueue(buf)
   316  		}
   317  	}
   318  
   319  	for {
   320  		trace.ticksEnd = cputicks()
   321  		trace.timeEnd = nanotime()
   322  		// Windows time can tick only every 15ms, wait for at least one tick.
   323  		if trace.timeEnd != trace.timeStart {
   324  			break
   325  		}
   326  		osyield()
   327  	}
   328  
   329  	trace.enabled = false
   330  	trace.shutdown = true
   331  	unlock(&trace.bufLock)
   332  
   333  	unlock(&sched.sysmonlock)
   334  
   335  	startTheWorldGC()
   336  
   337  	// The world is started but we've set trace.shutdown, so new tracing can't start.
   338  	// Wait for the trace reader to flush pending buffers and stop.
   339  	semacquire(&trace.shutdownSema)
   340  	if raceenabled {
   341  		raceacquire(unsafe.Pointer(&trace.shutdownSema))
   342  	}
   343  
   344  	// The lock protects us from races with StartTrace/StopTrace because they do stop-the-world.
   345  	lock(&trace.lock)
   346  	for _, p := range allp[:cap(allp)] {
   347  		if p.tracebuf != 0 {
   348  			throw("trace: non-empty trace buffer in proc")
   349  		}
   350  	}
   351  	if trace.buf != 0 {
   352  		throw("trace: non-empty global trace buffer")
   353  	}
   354  	if trace.fullHead != 0 || trace.fullTail != 0 {
   355  		throw("trace: non-empty full trace buffer")
   356  	}
   357  	if trace.reading != 0 || trace.reader != 0 {
   358  		throw("trace: reading after shutdown")
   359  	}
   360  	for trace.empty != 0 {
   361  		buf := trace.empty
   362  		trace.empty = buf.ptr().link
   363  		sysFree(unsafe.Pointer(buf), unsafe.Sizeof(*buf.ptr()), &memstats.other_sys)
   364  	}
   365  	trace.strings = nil
   366  	trace.shutdown = false
   367  	unlock(&trace.lock)
   368  }
   369  
   370  // ReadTrace returns the next chunk of binary tracing data, blocking until data
   371  // is available. If tracing is turned off and all the data accumulated while it
   372  // was on has been returned, ReadTrace returns nil. The caller must copy the
   373  // returned data before calling ReadTrace again.
   374  // ReadTrace must be called from one goroutine at a time.
   375  func ReadTrace() []byte {
   376  	// This function may need to lock trace.lock recursively
   377  	// (goparkunlock -> traceGoPark -> traceEvent -> traceFlush).
   378  	// To allow this we use trace.lockOwner.
   379  	// Also this function must not allocate while holding trace.lock:
   380  	// allocation can call heap allocate, which will try to emit a trace
   381  	// event while holding heap lock.
   382  	lock(&trace.lock)
   383  	trace.lockOwner = getg()
   384  
   385  	if trace.reader != 0 {
   386  		// More than one goroutine reads trace. This is bad.
   387  		// But we rather do not crash the program because of tracing,
   388  		// because tracing can be enabled at runtime on prod servers.
   389  		trace.lockOwner = nil
   390  		unlock(&trace.lock)
   391  		println("runtime: ReadTrace called from multiple goroutines simultaneously")
   392  		return nil
   393  	}
   394  	// Recycle the old buffer.
   395  	if buf := trace.reading; buf != 0 {
   396  		buf.ptr().link = trace.empty
   397  		trace.empty = buf
   398  		trace.reading = 0
   399  	}
   400  	// Write trace header.
   401  	if !trace.headerWritten {
   402  		trace.headerWritten = true
   403  		trace.lockOwner = nil
   404  		unlock(&trace.lock)
   405  		return []byte("go 1.11 trace\x00\x00\x00")
   406  	}
   407  	// Wait for new data.
   408  	if trace.fullHead == 0 && !trace.shutdown {
   409  		trace.reader.set(getg())
   410  		goparkunlock(&trace.lock, waitReasonTraceReaderBlocked, traceEvGoBlock, 2)
   411  		lock(&trace.lock)
   412  	}
   413  	// Write a buffer.
   414  	if trace.fullHead != 0 {
   415  		buf := traceFullDequeue()
   416  		trace.reading = buf
   417  		trace.lockOwner = nil
   418  		unlock(&trace.lock)
   419  		return buf.ptr().arr[:buf.ptr().pos]
   420  	}
   421  	// Write footer with timer frequency.
   422  	if !trace.footerWritten {
   423  		trace.footerWritten = true
   424  		// Use float64 because (trace.ticksEnd - trace.ticksStart) * 1e9 can overflow int64.
   425  		freq := float64(trace.ticksEnd-trace.ticksStart) * 1e9 / float64(trace.timeEnd-trace.timeStart) / traceTickDiv
   426  		trace.lockOwner = nil
   427  		unlock(&trace.lock)
   428  		var data []byte
   429  		data = append(data, traceEvFrequency|0<<traceArgCountShift)
   430  		data = traceAppend(data, uint64(freq))
   431  		// This will emit a bunch of full buffers, we will pick them up
   432  		// on the next iteration.
   433  		trace.stackTab.dump()
   434  		return data
   435  	}
   436  	// Done.
   437  	if trace.shutdown {
   438  		trace.lockOwner = nil
   439  		unlock(&trace.lock)
   440  		if raceenabled {
   441  			// Model synchronization on trace.shutdownSema, which race
   442  			// detector does not see. This is required to avoid false
   443  			// race reports on writer passed to trace.Start.
   444  			racerelease(unsafe.Pointer(&trace.shutdownSema))
   445  		}
   446  		// trace.enabled is already reset, so can call traceable functions.
   447  		semrelease(&trace.shutdownSema)
   448  		return nil
   449  	}
   450  	// Also bad, but see the comment above.
   451  	trace.lockOwner = nil
   452  	unlock(&trace.lock)
   453  	println("runtime: spurious wakeup of trace reader")
   454  	return nil
   455  }
   456  
   457  // traceReader returns the trace reader that should be woken up, if any.
   458  func traceReader() *g {
   459  	if trace.reader == 0 || (trace.fullHead == 0 && !trace.shutdown) {
   460  		return nil
   461  	}
   462  	lock(&trace.lock)
   463  	if trace.reader == 0 || (trace.fullHead == 0 && !trace.shutdown) {
   464  		unlock(&trace.lock)
   465  		return nil
   466  	}
   467  	gp := trace.reader.ptr()
   468  	trace.reader.set(nil)
   469  	unlock(&trace.lock)
   470  	return gp
   471  }
   472  
   473  // traceProcFree frees trace buffer associated with pp.
   474  func traceProcFree(pp *p) {
   475  	buf := pp.tracebuf
   476  	pp.tracebuf = 0
   477  	if buf == 0 {
   478  		return
   479  	}
   480  	lock(&trace.lock)
   481  	traceFullQueue(buf)
   482  	unlock(&trace.lock)
   483  }
   484  
   485  // traceFullQueue queues buf into queue of full buffers.
   486  func traceFullQueue(buf traceBufPtr) {
   487  	buf.ptr().link = 0
   488  	if trace.fullHead == 0 {
   489  		trace.fullHead = buf
   490  	} else {
   491  		trace.fullTail.ptr().link = buf
   492  	}
   493  	trace.fullTail = buf
   494  }
   495  
   496  // traceFullDequeue dequeues from queue of full buffers.
   497  func traceFullDequeue() traceBufPtr {
   498  	buf := trace.fullHead
   499  	if buf == 0 {
   500  		return 0
   501  	}
   502  	trace.fullHead = buf.ptr().link
   503  	if trace.fullHead == 0 {
   504  		trace.fullTail = 0
   505  	}
   506  	buf.ptr().link = 0
   507  	return buf
   508  }
   509  
   510  // traceEvent writes a single event to trace buffer, flushing the buffer if necessary.
   511  // ev is event type.
   512  // If skip > 0, write current stack id as the last argument (skipping skip top frames).
   513  // If skip = 0, this event type should contain a stack, but we don't want
   514  // to collect and remember it for this particular call.
   515  func traceEvent(ev byte, skip int, args ...uint64) {
   516  	mp, pid, bufp := traceAcquireBuffer()
   517  	// Double-check trace.enabled now that we've done m.locks++ and acquired bufLock.
   518  	// This protects from races between traceEvent and StartTrace/StopTrace.
   519  
   520  	// The caller checked that trace.enabled == true, but trace.enabled might have been
   521  	// turned off between the check and now. Check again. traceLockBuffer did mp.locks++,
   522  	// StopTrace does stopTheWorld, and stopTheWorld waits for mp.locks to go back to zero,
   523  	// so if we see trace.enabled == true now, we know it's true for the rest of the function.
   524  	// Exitsyscall can run even during stopTheWorld. The race with StartTrace/StopTrace
   525  	// during tracing in exitsyscall is resolved by locking trace.bufLock in traceLockBuffer.
   526  	//
   527  	// Note trace_userTaskCreate runs the same check.
   528  	if !trace.enabled && !mp.startingtrace {
   529  		traceReleaseBuffer(pid)
   530  		return
   531  	}
   532  
   533  	if skip > 0 {
   534  		if getg() == mp.curg {
   535  			skip++ // +1 because stack is captured in traceEventLocked.
   536  		}
   537  	}
   538  	traceEventLocked(0, mp, pid, bufp, ev, skip, args...)
   539  	traceReleaseBuffer(pid)
   540  }
   541  
   542  func traceEventLocked(extraBytes int, mp *m, pid int32, bufp *traceBufPtr, ev byte, skip int, args ...uint64) {
   543  	buf := bufp.ptr()
   544  	// TODO: test on non-zero extraBytes param.
   545  	maxSize := 2 + 5*traceBytesPerNumber + extraBytes // event type, length, sequence, timestamp, stack id and two add params
   546  	if buf == nil || len(buf.arr)-buf.pos < maxSize {
   547  		buf = traceFlush(traceBufPtrOf(buf), pid).ptr()
   548  		bufp.set(buf)
   549  	}
   550  
   551  	ticks := uint64(cputicks()) / traceTickDiv
   552  	tickDiff := ticks - buf.lastTicks
   553  	buf.lastTicks = ticks
   554  	narg := byte(len(args))
   555  	if skip >= 0 {
   556  		narg++
   557  	}
   558  	// We have only 2 bits for number of arguments.
   559  	// If number is >= 3, then the event type is followed by event length in bytes.
   560  	if narg > 3 {
   561  		narg = 3
   562  	}
   563  	startPos := buf.pos
   564  	buf.byte(ev | narg<<traceArgCountShift)
   565  	var lenp *byte
   566  	if narg == 3 {
   567  		// Reserve the byte for length assuming that length < 128.
   568  		buf.varint(0)
   569  		lenp = &buf.arr[buf.pos-1]
   570  	}
   571  	buf.varint(tickDiff)
   572  	for _, a := range args {
   573  		buf.varint(a)
   574  	}
   575  	if skip == 0 {
   576  		buf.varint(0)
   577  	} else if skip > 0 {
   578  		buf.varint(traceStackID(mp, buf.stk[:], skip))
   579  	}
   580  	evSize := buf.pos - startPos
   581  	if evSize > maxSize {
   582  		throw("invalid length of trace event")
   583  	}
   584  	if lenp != nil {
   585  		// Fill in actual length.
   586  		*lenp = byte(evSize - 2)
   587  	}
   588  }
   589  
   590  func traceStackID(mp *m, buf []uintptr, skip int) uint64 {
   591  	_g_ := getg()
   592  	gp := mp.curg
   593  	var nstk int
   594  	if gp == _g_ {
   595  		nstk = callers(skip+1, buf)
   596  	} else if gp != nil {
   597  		gp = mp.curg
   598  		nstk = gcallers(gp, skip, buf)
   599  	}
   600  	if nstk > 0 {
   601  		nstk-- // skip runtime.goexit
   602  	}
   603  	if nstk > 0 && gp.goid == 1 {
   604  		nstk-- // skip runtime.main
   605  	}
   606  	id := trace.stackTab.put(buf[:nstk])
   607  	return uint64(id)
   608  }
   609  
   610  // traceAcquireBuffer returns trace buffer to use and, if necessary, locks it.
   611  func traceAcquireBuffer() (mp *m, pid int32, bufp *traceBufPtr) {
   612  	mp = acquirem()
   613  	if p := mp.p.ptr(); p != nil {
   614  		return mp, p.id, &p.tracebuf
   615  	}
   616  	lock(&trace.bufLock)
   617  	return mp, traceGlobProc, &trace.buf
   618  }
   619  
   620  // traceReleaseBuffer releases a buffer previously acquired with traceAcquireBuffer.
   621  func traceReleaseBuffer(pid int32) {
   622  	if pid == traceGlobProc {
   623  		unlock(&trace.bufLock)
   624  	}
   625  	releasem(getg().m)
   626  }
   627  
   628  // traceFlush puts buf onto stack of full buffers and returns an empty buffer.
   629  func traceFlush(buf traceBufPtr, pid int32) traceBufPtr {
   630  	owner := trace.lockOwner
   631  	dolock := owner == nil || owner != getg().m.curg
   632  	if dolock {
   633  		lock(&trace.lock)
   634  	}
   635  	if buf != 0 {
   636  		traceFullQueue(buf)
   637  	}
   638  	if trace.empty != 0 {
   639  		buf = trace.empty
   640  		trace.empty = buf.ptr().link
   641  	} else {
   642  		buf = traceBufPtr(sysAlloc(unsafe.Sizeof(traceBuf{}), &memstats.other_sys))
   643  		if buf == 0 {
   644  			throw("trace: out of memory")
   645  		}
   646  	}
   647  	bufp := buf.ptr()
   648  	bufp.link.set(nil)
   649  	bufp.pos = 0
   650  
   651  	// initialize the buffer for a new batch
   652  	ticks := uint64(cputicks()) / traceTickDiv
   653  	bufp.lastTicks = ticks
   654  	bufp.byte(traceEvBatch | 1<<traceArgCountShift)
   655  	bufp.varint(uint64(pid))
   656  	bufp.varint(ticks)
   657  
   658  	if dolock {
   659  		unlock(&trace.lock)
   660  	}
   661  	return buf
   662  }
   663  
   664  // traceString adds a string to the trace.strings and returns the id.
   665  func traceString(bufp *traceBufPtr, pid int32, s string) (uint64, *traceBufPtr) {
   666  	if s == "" {
   667  		return 0, bufp
   668  	}
   669  
   670  	lock(&trace.stringsLock)
   671  	if raceenabled {
   672  		// raceacquire is necessary because the map access
   673  		// below is race annotated.
   674  		raceacquire(unsafe.Pointer(&trace.stringsLock))
   675  	}
   676  
   677  	if id, ok := trace.strings[s]; ok {
   678  		if raceenabled {
   679  			racerelease(unsafe.Pointer(&trace.stringsLock))
   680  		}
   681  		unlock(&trace.stringsLock)
   682  
   683  		return id, bufp
   684  	}
   685  
   686  	trace.stringSeq++
   687  	id := trace.stringSeq
   688  	trace.strings[s] = id
   689  
   690  	if raceenabled {
   691  		racerelease(unsafe.Pointer(&trace.stringsLock))
   692  	}
   693  	unlock(&trace.stringsLock)
   694  
   695  	// memory allocation in above may trigger tracing and
   696  	// cause *bufp changes. Following code now works with *bufp,
   697  	// so there must be no memory allocation or any activities
   698  	// that causes tracing after this point.
   699  
   700  	buf := bufp.ptr()
   701  	size := 1 + 2*traceBytesPerNumber + len(s)
   702  	if buf == nil || len(buf.arr)-buf.pos < size {
   703  		buf = traceFlush(traceBufPtrOf(buf), pid).ptr()
   704  		bufp.set(buf)
   705  	}
   706  	buf.byte(traceEvString)
   707  	buf.varint(id)
   708  
   709  	// double-check the string and the length can fit.
   710  	// Otherwise, truncate the string.
   711  	slen := len(s)
   712  	if room := len(buf.arr) - buf.pos; room < slen+traceBytesPerNumber {
   713  		slen = room
   714  	}
   715  
   716  	buf.varint(uint64(slen))
   717  	buf.pos += copy(buf.arr[buf.pos:], s[:slen])
   718  
   719  	bufp.set(buf)
   720  	return id, bufp
   721  }
   722  
   723  // traceAppend appends v to buf in little-endian-base-128 encoding.
   724  func traceAppend(buf []byte, v uint64) []byte {
   725  	for ; v >= 0x80; v >>= 7 {
   726  		buf = append(buf, 0x80|byte(v))
   727  	}
   728  	buf = append(buf, byte(v))
   729  	return buf
   730  }
   731  
   732  // varint appends v to buf in little-endian-base-128 encoding.
   733  func (buf *traceBuf) varint(v uint64) {
   734  	pos := buf.pos
   735  	for ; v >= 0x80; v >>= 7 {
   736  		buf.arr[pos] = 0x80 | byte(v)
   737  		pos++
   738  	}
   739  	buf.arr[pos] = byte(v)
   740  	pos++
   741  	buf.pos = pos
   742  }
   743  
   744  // byte appends v to buf.
   745  func (buf *traceBuf) byte(v byte) {
   746  	buf.arr[buf.pos] = v
   747  	buf.pos++
   748  }
   749  
   750  // traceStackTable maps stack traces (arrays of PC's) to unique uint32 ids.
   751  // It is lock-free for reading.
   752  type traceStackTable struct {
   753  	lock mutex
   754  	seq  uint32
   755  	mem  traceAlloc
   756  	tab  [1 << 13]traceStackPtr
   757  }
   758  
   759  // traceStack is a single stack in traceStackTable.
   760  type traceStack struct {
   761  	link traceStackPtr
   762  	hash uintptr
   763  	id   uint32
   764  	n    int
   765  	stk  [0]uintptr // real type [n]uintptr
   766  }
   767  
   768  type traceStackPtr uintptr
   769  
   770  func (tp traceStackPtr) ptr() *traceStack { return (*traceStack)(unsafe.Pointer(tp)) }
   771  
   772  // stack returns slice of PCs.
   773  func (ts *traceStack) stack() []uintptr {
   774  	return (*[traceStackSize]uintptr)(unsafe.Pointer(&ts.stk))[:ts.n]
   775  }
   776  
   777  // put returns a unique id for the stack trace pcs and caches it in the table,
   778  // if it sees the trace for the first time.
   779  func (tab *traceStackTable) put(pcs []uintptr) uint32 {
   780  	if len(pcs) == 0 {
   781  		return 0
   782  	}
   783  	hash := memhash(unsafe.Pointer(&pcs[0]), 0, uintptr(len(pcs))*unsafe.Sizeof(pcs[0]))
   784  	// First, search the hashtable w/o the mutex.
   785  	if id := tab.find(pcs, hash); id != 0 {
   786  		return id
   787  	}
   788  	// Now, double check under the mutex.
   789  	lock(&tab.lock)
   790  	if id := tab.find(pcs, hash); id != 0 {
   791  		unlock(&tab.lock)
   792  		return id
   793  	}
   794  	// Create new record.
   795  	tab.seq++
   796  	stk := tab.newStack(len(pcs))
   797  	stk.hash = hash
   798  	stk.id = tab.seq
   799  	stk.n = len(pcs)
   800  	stkpc := stk.stack()
   801  	for i, pc := range pcs {
   802  		stkpc[i] = pc
   803  	}
   804  	part := int(hash % uintptr(len(tab.tab)))
   805  	stk.link = tab.tab[part]
   806  	atomicstorep(unsafe.Pointer(&tab.tab[part]), unsafe.Pointer(stk))
   807  	unlock(&tab.lock)
   808  	return stk.id
   809  }
   810  
   811  // find checks if the stack trace pcs is already present in the table.
   812  func (tab *traceStackTable) find(pcs []uintptr, hash uintptr) uint32 {
   813  	part := int(hash % uintptr(len(tab.tab)))
   814  Search:
   815  	for stk := tab.tab[part].ptr(); stk != nil; stk = stk.link.ptr() {
   816  		if stk.hash == hash && stk.n == len(pcs) {
   817  			for i, stkpc := range stk.stack() {
   818  				if stkpc != pcs[i] {
   819  					continue Search
   820  				}
   821  			}
   822  			return stk.id
   823  		}
   824  	}
   825  	return 0
   826  }
   827  
   828  // newStack allocates a new stack of size n.
   829  func (tab *traceStackTable) newStack(n int) *traceStack {
   830  	return (*traceStack)(tab.mem.alloc(unsafe.Sizeof(traceStack{}) + uintptr(n)*sys.PtrSize))
   831  }
   832  
   833  // allFrames returns all of the Frames corresponding to pcs.
   834  func allFrames(pcs []uintptr) []Frame {
   835  	frames := make([]Frame, 0, len(pcs))
   836  	ci := CallersFrames(pcs)
   837  	for {
   838  		f, more := ci.Next()
   839  		frames = append(frames, f)
   840  		if !more {
   841  			return frames
   842  		}
   843  	}
   844  }
   845  
   846  // dump writes all previously cached stacks to trace buffers,
   847  // releases all memory and resets state.
   848  func (tab *traceStackTable) dump() {
   849  	var tmp [(2 + 4*traceStackSize) * traceBytesPerNumber]byte
   850  	bufp := traceFlush(0, 0)
   851  	for _, stk := range tab.tab {
   852  		stk := stk.ptr()
   853  		for ; stk != nil; stk = stk.link.ptr() {
   854  			tmpbuf := tmp[:0]
   855  			tmpbuf = traceAppend(tmpbuf, uint64(stk.id))
   856  			frames := allFrames(stk.stack())
   857  			tmpbuf = traceAppend(tmpbuf, uint64(len(frames)))
   858  			for _, f := range frames {
   859  				var frame traceFrame
   860  				frame, bufp = traceFrameForPC(bufp, 0, f)
   861  				tmpbuf = traceAppend(tmpbuf, uint64(f.PC))
   862  				tmpbuf = traceAppend(tmpbuf, uint64(frame.funcID))
   863  				tmpbuf = traceAppend(tmpbuf, uint64(frame.fileID))
   864  				tmpbuf = traceAppend(tmpbuf, uint64(frame.line))
   865  			}
   866  			// Now copy to the buffer.
   867  			size := 1 + traceBytesPerNumber + len(tmpbuf)
   868  			if buf := bufp.ptr(); len(buf.arr)-buf.pos < size {
   869  				bufp = traceFlush(bufp, 0)
   870  			}
   871  			buf := bufp.ptr()
   872  			buf.byte(traceEvStack | 3<<traceArgCountShift)
   873  			buf.varint(uint64(len(tmpbuf)))
   874  			buf.pos += copy(buf.arr[buf.pos:], tmpbuf)
   875  		}
   876  	}
   877  
   878  	lock(&trace.lock)
   879  	traceFullQueue(bufp)
   880  	unlock(&trace.lock)
   881  
   882  	tab.mem.drop()
   883  	*tab = traceStackTable{}
   884  	lockInit(&((*tab).lock), lockRankTraceStackTab)
   885  }
   886  
   887  type traceFrame struct {
   888  	funcID uint64
   889  	fileID uint64
   890  	line   uint64
   891  }
   892  
   893  // traceFrameForPC records the frame information.
   894  // It may allocate memory.
   895  func traceFrameForPC(buf traceBufPtr, pid int32, f Frame) (traceFrame, traceBufPtr) {
   896  	bufp := &buf
   897  	var frame traceFrame
   898  
   899  	fn := f.Function
   900  	const maxLen = 1 << 10
   901  	if len(fn) > maxLen {
   902  		fn = fn[len(fn)-maxLen:]
   903  	}
   904  	frame.funcID, bufp = traceString(bufp, pid, fn)
   905  	frame.line = uint64(f.Line)
   906  	file := f.File
   907  	if len(file) > maxLen {
   908  		file = file[len(file)-maxLen:]
   909  	}
   910  	frame.fileID, bufp = traceString(bufp, pid, file)
   911  	return frame, (*bufp)
   912  }
   913  
   914  // traceAlloc is a non-thread-safe region allocator.
   915  // It holds a linked list of traceAllocBlock.
   916  type traceAlloc struct {
   917  	head traceAllocBlockPtr
   918  	off  uintptr
   919  }
   920  
   921  // traceAllocBlock is a block in traceAlloc.
   922  //
   923  // traceAllocBlock is allocated from non-GC'd memory, so it must not
   924  // contain heap pointers. Writes to pointers to traceAllocBlocks do
   925  // not need write barriers.
   926  //
   927  //go:notinheap
   928  type traceAllocBlock struct {
   929  	next traceAllocBlockPtr
   930  	data [64<<10 - sys.PtrSize]byte
   931  }
   932  
   933  // TODO: Since traceAllocBlock is now go:notinheap, this isn't necessary.
   934  type traceAllocBlockPtr uintptr
   935  
   936  func (p traceAllocBlockPtr) ptr() *traceAllocBlock   { return (*traceAllocBlock)(unsafe.Pointer(p)) }
   937  func (p *traceAllocBlockPtr) set(x *traceAllocBlock) { *p = traceAllocBlockPtr(unsafe.Pointer(x)) }
   938  
   939  // alloc allocates n-byte block.
   940  func (a *traceAlloc) alloc(n uintptr) unsafe.Pointer {
   941  	n = alignUp(n, sys.PtrSize)
   942  	if a.head == 0 || a.off+n > uintptr(len(a.head.ptr().data)) {
   943  		if n > uintptr(len(a.head.ptr().data)) {
   944  			throw("trace: alloc too large")
   945  		}
   946  		block := (*traceAllocBlock)(sysAlloc(unsafe.Sizeof(traceAllocBlock{}), &memstats.other_sys))
   947  		if block == nil {
   948  			throw("trace: out of memory")
   949  		}
   950  		block.next.set(a.head.ptr())
   951  		a.head.set(block)
   952  		a.off = 0
   953  	}
   954  	p := &a.head.ptr().data[a.off]
   955  	a.off += n
   956  	return unsafe.Pointer(p)
   957  }
   958  
   959  // drop frees all previously allocated memory and resets the allocator.
   960  func (a *traceAlloc) drop() {
   961  	for a.head != 0 {
   962  		block := a.head.ptr()
   963  		a.head.set(block.next.ptr())
   964  		sysFree(unsafe.Pointer(block), unsafe.Sizeof(traceAllocBlock{}), &memstats.other_sys)
   965  	}
   966  }
   967  
   968  // The following functions write specific events to trace.
   969  
   970  func traceGomaxprocs(procs int32) {
   971  	traceEvent(traceEvGomaxprocs, 1, uint64(procs))
   972  }
   973  
   974  func traceProcStart() {
   975  	traceEvent(traceEvProcStart, -1, uint64(getg().m.id))
   976  }
   977  
   978  func traceProcStop(pp *p) {
   979  	// Sysmon and stopTheWorld can stop Ps blocked in syscalls,
   980  	// to handle this we temporary employ the P.
   981  	mp := acquirem()
   982  	oldp := mp.p
   983  	mp.p.set(pp)
   984  	traceEvent(traceEvProcStop, -1)
   985  	mp.p = oldp
   986  	releasem(mp)
   987  }
   988  
   989  func traceGCStart() {
   990  	traceEvent(traceEvGCStart, 3, trace.seqGC)
   991  	trace.seqGC++
   992  }
   993  
   994  func traceGCDone() {
   995  	traceEvent(traceEvGCDone, -1)
   996  }
   997  
   998  func traceGCSTWStart(kind int) {
   999  	traceEvent(traceEvGCSTWStart, -1, uint64(kind))
  1000  }
  1001  
  1002  func traceGCSTWDone() {
  1003  	traceEvent(traceEvGCSTWDone, -1)
  1004  }
  1005  
  1006  // traceGCSweepStart prepares to trace a sweep loop. This does not
  1007  // emit any events until traceGCSweepSpan is called.
  1008  //
  1009  // traceGCSweepStart must be paired with traceGCSweepDone and there
  1010  // must be no preemption points between these two calls.
  1011  func traceGCSweepStart() {
  1012  	// Delay the actual GCSweepStart event until the first span
  1013  	// sweep. If we don't sweep anything, don't emit any events.
  1014  	_p_ := getg().m.p.ptr()
  1015  	if _p_.traceSweep {
  1016  		throw("double traceGCSweepStart")
  1017  	}
  1018  	_p_.traceSweep, _p_.traceSwept, _p_.traceReclaimed = true, 0, 0
  1019  }
  1020  
  1021  // traceGCSweepSpan traces the sweep of a single page.
  1022  //
  1023  // This may be called outside a traceGCSweepStart/traceGCSweepDone
  1024  // pair; however, it will not emit any trace events in this case.
  1025  func traceGCSweepSpan(bytesSwept uintptr) {
  1026  	_p_ := getg().m.p.ptr()
  1027  	if _p_.traceSweep {
  1028  		if _p_.traceSwept == 0 {
  1029  			traceEvent(traceEvGCSweepStart, 1)
  1030  		}
  1031  		_p_.traceSwept += bytesSwept
  1032  	}
  1033  }
  1034  
  1035  func traceGCSweepDone() {
  1036  	_p_ := getg().m.p.ptr()
  1037  	if !_p_.traceSweep {
  1038  		throw("missing traceGCSweepStart")
  1039  	}
  1040  	if _p_.traceSwept != 0 {
  1041  		traceEvent(traceEvGCSweepDone, -1, uint64(_p_.traceSwept), uint64(_p_.traceReclaimed))
  1042  	}
  1043  	_p_.traceSweep = false
  1044  }
  1045  
  1046  func traceGCMarkAssistStart() {
  1047  	traceEvent(traceEvGCMarkAssistStart, 1)
  1048  }
  1049  
  1050  func traceGCMarkAssistDone() {
  1051  	traceEvent(traceEvGCMarkAssistDone, -1)
  1052  }
  1053  
  1054  func traceGoCreate(newg *g, pc uintptr) {
  1055  	newg.traceseq = 0
  1056  	newg.tracelastp = getg().m.p
  1057  	// +PCQuantum because traceFrameForPC expects return PCs and subtracts PCQuantum.
  1058  	id := trace.stackTab.put([]uintptr{pc + sys.PCQuantum})
  1059  	traceEvent(traceEvGoCreate, 2, uint64(newg.goid), uint64(id))
  1060  }
  1061  
  1062  func traceGoStart() {
  1063  	_g_ := getg().m.curg
  1064  	_p_ := _g_.m.p
  1065  	_g_.traceseq++
  1066  	if _g_ == _p_.ptr().gcBgMarkWorker.ptr() {
  1067  		traceEvent(traceEvGoStartLabel, -1, uint64(_g_.goid), _g_.traceseq, trace.markWorkerLabels[_p_.ptr().gcMarkWorkerMode])
  1068  	} else if _g_.tracelastp == _p_ {
  1069  		traceEvent(traceEvGoStartLocal, -1, uint64(_g_.goid))
  1070  	} else {
  1071  		_g_.tracelastp = _p_
  1072  		traceEvent(traceEvGoStart, -1, uint64(_g_.goid), _g_.traceseq)
  1073  	}
  1074  }
  1075  
  1076  func traceGoEnd() {
  1077  	traceEvent(traceEvGoEnd, -1)
  1078  }
  1079  
  1080  func traceGoSched() {
  1081  	_g_ := getg()
  1082  	_g_.tracelastp = _g_.m.p
  1083  	traceEvent(traceEvGoSched, 1)
  1084  }
  1085  
  1086  func traceGoPreempt() {
  1087  	_g_ := getg()
  1088  	_g_.tracelastp = _g_.m.p
  1089  	traceEvent(traceEvGoPreempt, 1)
  1090  }
  1091  
  1092  func traceGoPark(traceEv byte, skip int) {
  1093  	if traceEv&traceFutileWakeup != 0 {
  1094  		traceEvent(traceEvFutileWakeup, -1)
  1095  	}
  1096  	traceEvent(traceEv & ^traceFutileWakeup, skip)
  1097  }
  1098  
  1099  func traceGoUnpark(gp *g, skip int) {
  1100  	_p_ := getg().m.p
  1101  	gp.traceseq++
  1102  	if gp.tracelastp == _p_ {
  1103  		traceEvent(traceEvGoUnblockLocal, skip, uint64(gp.goid))
  1104  	} else {
  1105  		gp.tracelastp = _p_
  1106  		traceEvent(traceEvGoUnblock, skip, uint64(gp.goid), gp.traceseq)
  1107  	}
  1108  }
  1109  
  1110  func traceGoSysCall() {
  1111  	traceEvent(traceEvGoSysCall, 1)
  1112  }
  1113  
  1114  func traceGoSysExit(ts int64) {
  1115  	if ts != 0 && ts < trace.ticksStart {
  1116  		// There is a race between the code that initializes sysexitticks
  1117  		// (in exitsyscall, which runs without a P, and therefore is not
  1118  		// stopped with the rest of the world) and the code that initializes
  1119  		// a new trace. The recorded sysexitticks must therefore be treated
  1120  		// as "best effort". If they are valid for this trace, then great,
  1121  		// use them for greater accuracy. But if they're not valid for this
  1122  		// trace, assume that the trace was started after the actual syscall
  1123  		// exit (but before we actually managed to start the goroutine,
  1124  		// aka right now), and assign a fresh time stamp to keep the log consistent.
  1125  		ts = 0
  1126  	}
  1127  	_g_ := getg().m.curg
  1128  	_g_.traceseq++
  1129  	_g_.tracelastp = _g_.m.p
  1130  	traceEvent(traceEvGoSysExit, -1, uint64(_g_.goid), _g_.traceseq, uint64(ts)/traceTickDiv)
  1131  }
  1132  
  1133  func traceGoSysBlock(pp *p) {
  1134  	// Sysmon and stopTheWorld can declare syscalls running on remote Ps as blocked,
  1135  	// to handle this we temporary employ the P.
  1136  	mp := acquirem()
  1137  	oldp := mp.p
  1138  	mp.p.set(pp)
  1139  	traceEvent(traceEvGoSysBlock, -1)
  1140  	mp.p = oldp
  1141  	releasem(mp)
  1142  }
  1143  
  1144  func traceHeapAlloc() {
  1145  	traceEvent(traceEvHeapAlloc, -1, memstats.heap_live)
  1146  }
  1147  
  1148  func traceNextGC() {
  1149  	if memstats.next_gc == ^uint64(0) {
  1150  		// Heap-based triggering is disabled.
  1151  		traceEvent(traceEvNextGC, -1, 0)
  1152  	} else {
  1153  		traceEvent(traceEvNextGC, -1, memstats.next_gc)
  1154  	}
  1155  }
  1156  
  1157  // To access runtime functions from runtime/trace.
  1158  // See runtime/trace/annotation.go
  1159  
  1160  //go:linkname trace_userTaskCreate runtime/trace.userTaskCreate
  1161  func trace_userTaskCreate(id, parentID uint64, taskType string) {
  1162  	if !trace.enabled {
  1163  		return
  1164  	}
  1165  
  1166  	// Same as in traceEvent.
  1167  	mp, pid, bufp := traceAcquireBuffer()
  1168  	if !trace.enabled && !mp.startingtrace {
  1169  		traceReleaseBuffer(pid)
  1170  		return
  1171  	}
  1172  
  1173  	typeStringID, bufp := traceString(bufp, pid, taskType)
  1174  	traceEventLocked(0, mp, pid, bufp, traceEvUserTaskCreate, 3, id, parentID, typeStringID)
  1175  	traceReleaseBuffer(pid)
  1176  }
  1177  
  1178  //go:linkname trace_userTaskEnd runtime/trace.userTaskEnd
  1179  func trace_userTaskEnd(id uint64) {
  1180  	traceEvent(traceEvUserTaskEnd, 2, id)
  1181  }
  1182  
  1183  //go:linkname trace_userRegion runtime/trace.userRegion
  1184  func trace_userRegion(id, mode uint64, name string) {
  1185  	if !trace.enabled {
  1186  		return
  1187  	}
  1188  
  1189  	mp, pid, bufp := traceAcquireBuffer()
  1190  	if !trace.enabled && !mp.startingtrace {
  1191  		traceReleaseBuffer(pid)
  1192  		return
  1193  	}
  1194  
  1195  	nameStringID, bufp := traceString(bufp, pid, name)
  1196  	traceEventLocked(0, mp, pid, bufp, traceEvUserRegion, 3, id, mode, nameStringID)
  1197  	traceReleaseBuffer(pid)
  1198  }
  1199  
  1200  //go:linkname trace_userLog runtime/trace.userLog
  1201  func trace_userLog(id uint64, category, message string) {
  1202  	if !trace.enabled {
  1203  		return
  1204  	}
  1205  
  1206  	mp, pid, bufp := traceAcquireBuffer()
  1207  	if !trace.enabled && !mp.startingtrace {
  1208  		traceReleaseBuffer(pid)
  1209  		return
  1210  	}
  1211  
  1212  	categoryID, bufp := traceString(bufp, pid, category)
  1213  
  1214  	extraSpace := traceBytesPerNumber + len(message) // extraSpace for the value string
  1215  	traceEventLocked(extraSpace, mp, pid, bufp, traceEvUserLog, 3, id, categoryID)
  1216  	// traceEventLocked reserved extra space for val and len(val)
  1217  	// in buf, so buf now has room for the following.
  1218  	buf := bufp.ptr()
  1219  
  1220  	// double-check the message and its length can fit.
  1221  	// Otherwise, truncate the message.
  1222  	slen := len(message)
  1223  	if room := len(buf.arr) - buf.pos; room < slen+traceBytesPerNumber {
  1224  		slen = room
  1225  	}
  1226  	buf.varint(uint64(slen))
  1227  	buf.pos += copy(buf.arr[buf.pos:], message[:slen])
  1228  
  1229  	traceReleaseBuffer(pid)
  1230  }
  1231  

View as plain text