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