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 // gcController.heapLive change [timestamp, heap_alloc]
57	traceEvHeapGoal          = 34 // gcController.heapGoal (formerly next_gc) change [timestamp, heap goal in bytes]
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	// World is stopped, no need to lock.
226	forEachGRace(func(gp *g) {
227		status := readgstatus(gp)
228		if status != _Gdead {
229			gp.traceseq = 0
230			gp.tracelastp = getg().m.p
231			// +PCQuantum because traceFrameForPC expects return PCs and subtracts PCQuantum.
232			id := trace.stackTab.put([]location{location{pc: gp.startpc + sys.PCQuantum}})
233			traceEvent(traceEvGoCreate, -1, uint64(gp.goid), uint64(id), stackID)
234		}
235		if status == _Gwaiting {
236			// traceEvGoWaiting is implied to have seq=1.
237			gp.traceseq++
238			traceEvent(traceEvGoWaiting, -1, uint64(gp.goid))
239		}
240		if status == _Gsyscall {
241			gp.traceseq++
242			traceEvent(traceEvGoInSyscall, -1, uint64(gp.goid))
243		} else {
244			gp.sysblocktraced = false
245		}
246	})
247	traceProcStart()
248	traceGoStart()
249	// Note: ticksStart needs to be set after we emit traceEvGoInSyscall events.
250	// If we do it the other way around, it is possible that exitsyscall will
251	// query sysexitticks after ticksStart but before traceEvGoInSyscall timestamp.
252	// It will lead to a false conclusion that cputicks is broken.
253	trace.ticksStart = cputicks()
254	trace.timeStart = nanotime()
255	trace.headerWritten = false
256	trace.footerWritten = false
257
258	// string to id mapping
259	//  0 : reserved for an empty string
260	//  remaining: other strings registered by traceString
261	trace.stringSeq = 0
262	trace.strings = make(map[string]uint64)
263
264	trace.seqGC = 0
265	_g_.m.startingtrace = false
266	trace.enabled = true
267
268	// Register runtime goroutine labels.
269	_, pid, bufp := traceAcquireBuffer()
270	for i, label := range gcMarkWorkerModeStrings[:] {
271		trace.markWorkerLabels[i], bufp = traceString(bufp, pid, label)
272	}
273	traceReleaseBuffer(pid)
274
275	unlock(&trace.bufLock)
276
277	unlock(&sched.sysmonlock)
278
279	startTheWorldGC()
280	return nil
281}
282
283// StopTrace stops tracing, if it was previously enabled.
284// StopTrace only returns after all the reads for the trace have completed.
285func StopTrace() {
286	// Stop the world so that we can collect the trace buffers from all p's below,
287	// and also to avoid races with traceEvent.
288	stopTheWorldGC("stop tracing")
289
290	// See the comment in StartTrace.
291	lock(&sched.sysmonlock)
292
293	// See the comment in StartTrace.
294	lock(&trace.bufLock)
295
296	if !trace.enabled {
297		unlock(&trace.bufLock)
298		unlock(&sched.sysmonlock)
299		startTheWorldGC()
300		return
301	}
302
303	traceGoSched()
304
305	// Loop over all allocated Ps because dead Ps may still have
306	// trace buffers.
307	for _, p := range allp[:cap(allp)] {
308		buf := p.tracebuf
309		if buf != 0 {
310			traceFullQueue(buf)
311			p.tracebuf = 0
312		}
313	}
314	if trace.buf != 0 {
315		buf := trace.buf
316		trace.buf = 0
317		if buf.ptr().pos != 0 {
318			traceFullQueue(buf)
319		}
320	}
321
322	for {
323		trace.ticksEnd = cputicks()
324		trace.timeEnd = nanotime()
325		// Windows time can tick only every 15ms, wait for at least one tick.
326		if trace.timeEnd != trace.timeStart {
327			break
328		}
329		osyield()
330	}
331
332	trace.enabled = false
333	trace.shutdown = true
334	unlock(&trace.bufLock)
335
336	unlock(&sched.sysmonlock)
337
338	startTheWorldGC()
339
340	// The world is started but we've set trace.shutdown, so new tracing can't start.
341	// Wait for the trace reader to flush pending buffers and stop.
342	semacquire(&trace.shutdownSema)
343	if raceenabled {
344		raceacquire(unsafe.Pointer(&trace.shutdownSema))
345	}
346
347	// The lock protects us from races with StartTrace/StopTrace because they do stop-the-world.
348	lock(&trace.lock)
349	for _, p := range allp[:cap(allp)] {
350		if p.tracebuf != 0 {
351			throw("trace: non-empty trace buffer in proc")
352		}
353	}
354	if trace.buf != 0 {
355		throw("trace: non-empty global trace buffer")
356	}
357	if trace.fullHead != 0 || trace.fullTail != 0 {
358		throw("trace: non-empty full trace buffer")
359	}
360	if trace.reading != 0 || trace.reader != 0 {
361		throw("trace: reading after shutdown")
362	}
363	for trace.empty != 0 {
364		buf := trace.empty
365		trace.empty = buf.ptr().link
366		sysFree(unsafe.Pointer(buf), unsafe.Sizeof(*buf.ptr()), &memstats.other_sys)
367	}
368	trace.strings = nil
369	trace.shutdown = false
370	unlock(&trace.lock)
371}
372
373// ReadTrace returns the next chunk of binary tracing data, blocking until data
374// is available. If tracing is turned off and all the data accumulated while it
375// was on has been returned, ReadTrace returns nil. The caller must copy the
376// returned data before calling ReadTrace again.
377// ReadTrace must be called from one goroutine at a time.
378func ReadTrace() []byte {
379	// This function may need to lock trace.lock recursively
380	// (goparkunlock -> traceGoPark -> traceEvent -> traceFlush).
381	// To allow this we use trace.lockOwner.
382	// Also this function must not allocate while holding trace.lock:
383	// allocation can call heap allocate, which will try to emit a trace
384	// event while holding heap lock.
385	lock(&trace.lock)
386	trace.lockOwner = getg()
387
388	if trace.reader != 0 {
389		// More than one goroutine reads trace. This is bad.
390		// But we rather do not crash the program because of tracing,
391		// because tracing can be enabled at runtime on prod servers.
392		trace.lockOwner = nil
393		unlock(&trace.lock)
394		println("runtime: ReadTrace called from multiple goroutines simultaneously")
395		return nil
396	}
397	// Recycle the old buffer.
398	if buf := trace.reading; buf != 0 {
399		buf.ptr().link = trace.empty
400		trace.empty = buf
401		trace.reading = 0
402	}
403	// Write trace header.
404	if !trace.headerWritten {
405		trace.headerWritten = true
406		trace.lockOwner = nil
407		unlock(&trace.lock)
408		return []byte("go 1.11 trace\x00\x00\x00")
409	}
410	// Wait for new data.
411	if trace.fullHead == 0 && !trace.shutdown {
412		trace.reader.set(getg())
413		goparkunlock(&trace.lock, waitReasonTraceReaderBlocked, traceEvGoBlock, 2)
414		lock(&trace.lock)
415	}
416	// Write a buffer.
417	if trace.fullHead != 0 {
418		buf := traceFullDequeue()
419		trace.reading = buf
420		trace.lockOwner = nil
421		unlock(&trace.lock)
422		return buf.ptr().arr[:buf.ptr().pos]
423	}
424	// Write footer with timer frequency.
425	if !trace.footerWritten {
426		trace.footerWritten = true
427		// Use float64 because (trace.ticksEnd - trace.ticksStart) * 1e9 can overflow int64.
428		freq := float64(trace.ticksEnd-trace.ticksStart) * 1e9 / float64(trace.timeEnd-trace.timeStart) / traceTickDiv
429		trace.lockOwner = nil
430		unlock(&trace.lock)
431		var data []byte
432		data = append(data, traceEvFrequency|0<<traceArgCountShift)
433		data = traceAppend(data, uint64(freq))
434		// This will emit a bunch of full buffers, we will pick them up
435		// on the next iteration.
436		trace.stackTab.dump()
437		return data
438	}
439	// Done.
440	if trace.shutdown {
441		trace.lockOwner = nil
442		unlock(&trace.lock)
443		if raceenabled {
444			// Model synchronization on trace.shutdownSema, which race
445			// detector does not see. This is required to avoid false
446			// race reports on writer passed to trace.Start.
447			racerelease(unsafe.Pointer(&trace.shutdownSema))
448		}
449		// trace.enabled is already reset, so can call traceable functions.
450		semrelease(&trace.shutdownSema)
451		return nil
452	}
453	// Also bad, but see the comment above.
454	trace.lockOwner = nil
455	unlock(&trace.lock)
456	println("runtime: spurious wakeup of trace reader")
457	return nil
458}
459
460// traceReader returns the trace reader that should be woken up, if any.
461func traceReader() *g {
462	if trace.reader == 0 || (trace.fullHead == 0 && !trace.shutdown) {
463		return nil
464	}
465	lock(&trace.lock)
466	if trace.reader == 0 || (trace.fullHead == 0 && !trace.shutdown) {
467		unlock(&trace.lock)
468		return nil
469	}
470	gp := trace.reader.ptr()
471	trace.reader.set(nil)
472	unlock(&trace.lock)
473	return gp
474}
475
476// traceProcFree frees trace buffer associated with pp.
477func traceProcFree(pp *p) {
478	buf := pp.tracebuf
479	pp.tracebuf = 0
480	if buf == 0 {
481		return
482	}
483	lock(&trace.lock)
484	traceFullQueue(buf)
485	unlock(&trace.lock)
486}
487
488// traceFullQueue queues buf into queue of full buffers.
489func traceFullQueue(buf traceBufPtr) {
490	buf.ptr().link = 0
491	if trace.fullHead == 0 {
492		trace.fullHead = buf
493	} else {
494		trace.fullTail.ptr().link = buf
495	}
496	trace.fullTail = buf
497}
498
499// traceFullDequeue dequeues from queue of full buffers.
500func traceFullDequeue() traceBufPtr {
501	buf := trace.fullHead
502	if buf == 0 {
503		return 0
504	}
505	trace.fullHead = buf.ptr().link
506	if trace.fullHead == 0 {
507		trace.fullTail = 0
508	}
509	buf.ptr().link = 0
510	return buf
511}
512
513// traceEvent writes a single event to trace buffer, flushing the buffer if necessary.
514// ev is event type.
515// If skip > 0, write current stack id as the last argument (skipping skip top frames).
516// If skip = 0, this event type should contain a stack, but we don't want
517// to collect and remember it for this particular call.
518func traceEvent(ev byte, skip int, args ...uint64) {
519	mp, pid, bufp := traceAcquireBuffer()
520	// Double-check trace.enabled now that we've done m.locks++ and acquired bufLock.
521	// This protects from races between traceEvent and StartTrace/StopTrace.
522
523	// The caller checked that trace.enabled == true, but trace.enabled might have been
524	// turned off between the check and now. Check again. traceLockBuffer did mp.locks++,
525	// StopTrace does stopTheWorld, and stopTheWorld waits for mp.locks to go back to zero,
526	// so if we see trace.enabled == true now, we know it's true for the rest of the function.
527	// Exitsyscall can run even during stopTheWorld. The race with StartTrace/StopTrace
528	// during tracing in exitsyscall is resolved by locking trace.bufLock in traceLockBuffer.
529	//
530	// Note trace_userTaskCreate runs the same check.
531	if !trace.enabled && !mp.startingtrace {
532		traceReleaseBuffer(pid)
533		return
534	}
535
536	if skip > 0 {
537		if getg() == mp.curg {
538			skip++ // +1 because stack is captured in traceEventLocked.
539		}
540	}
541	traceEventLocked(0, mp, pid, bufp, ev, skip, args...)
542	traceReleaseBuffer(pid)
543}
544
545func traceEventLocked(extraBytes int, mp *m, pid int32, bufp *traceBufPtr, ev byte, skip int, args ...uint64) {
546	buf := bufp.ptr()
547	// TODO: test on non-zero extraBytes param.
548	maxSize := 2 + 5*traceBytesPerNumber + extraBytes // event type, length, sequence, timestamp, stack id and two add params
549	if buf == nil || len(buf.arr)-buf.pos < maxSize {
550		buf = traceFlush(traceBufPtrOf(buf), pid).ptr()
551		bufp.set(buf)
552	}
553
554	ticks := uint64(cputicks()) / traceTickDiv
555	tickDiff := ticks - buf.lastTicks
556	buf.lastTicks = ticks
557	narg := byte(len(args))
558	if skip >= 0 {
559		narg++
560	}
561	// We have only 2 bits for number of arguments.
562	// If number is >= 3, then the event type is followed by event length in bytes.
563	if narg > 3 {
564		narg = 3
565	}
566	startPos := buf.pos
567	buf.byte(ev | narg<<traceArgCountShift)
568	var lenp *byte
569	if narg == 3 {
570		// Reserve the byte for length assuming that length < 128.
571		buf.varint(0)
572		lenp = &buf.arr[buf.pos-1]
573	}
574	buf.varint(tickDiff)
575	for _, a := range args {
576		buf.varint(a)
577	}
578	if skip == 0 {
579		buf.varint(0)
580	} else if skip > 0 {
581		buf.varint(traceStackID(mp, buf.stk[:], skip))
582	}
583	evSize := buf.pos - startPos
584	if evSize > maxSize {
585		throw("invalid length of trace event")
586	}
587	if lenp != nil {
588		// Fill in actual length.
589		*lenp = byte(evSize - 2)
590	}
591}
592
593func traceStackID(mp *m, buf []location, skip int) uint64 {
594	_g_ := getg()
595	gp := mp.curg
596	var nstk int
597	if gp == _g_ {
598		nstk = callers(skip+1, buf)
599	} else if gp != nil {
600		// FIXME: get stack trace of different goroutine.
601	}
602	if nstk > 0 {
603		nstk-- // skip runtime.goexit
604	}
605	if nstk > 0 && gp.goid == 1 {
606		nstk-- // skip runtime.main
607	}
608	id := trace.stackTab.put(buf[:nstk])
609	return uint64(id)
610}
611
612// traceAcquireBuffer returns trace buffer to use and, if necessary, locks it.
613func traceAcquireBuffer() (mp *m, pid int32, bufp *traceBufPtr) {
614	mp = acquirem()
615	if p := mp.p.ptr(); p != nil {
616		return mp, p.id, &p.tracebuf
617	}
618	lock(&trace.bufLock)
619	return mp, traceGlobProc, &trace.buf
620}
621
622// traceReleaseBuffer releases a buffer previously acquired with traceAcquireBuffer.
623func traceReleaseBuffer(pid int32) {
624	if pid == traceGlobProc {
625		unlock(&trace.bufLock)
626	}
627	releasem(getg().m)
628}
629
630// traceFlush puts buf onto stack of full buffers and returns an empty buffer.
631func traceFlush(buf traceBufPtr, pid int32) traceBufPtr {
632	owner := trace.lockOwner
633	dolock := owner == nil || owner != getg().m.curg
634	if dolock {
635		lock(&trace.lock)
636	}
637	if buf != 0 {
638		traceFullQueue(buf)
639	}
640	if trace.empty != 0 {
641		buf = trace.empty
642		trace.empty = buf.ptr().link
643	} else {
644		buf = traceBufPtr(sysAlloc(unsafe.Sizeof(traceBuf{}), &memstats.other_sys))
645		if buf == 0 {
646			throw("trace: out of memory")
647		}
648	}
649	bufp := buf.ptr()
650	bufp.link.set(nil)
651	bufp.pos = 0
652
653	// initialize the buffer for a new batch
654	ticks := uint64(cputicks()) / traceTickDiv
655	bufp.lastTicks = ticks
656	bufp.byte(traceEvBatch | 1<<traceArgCountShift)
657	bufp.varint(uint64(pid))
658	bufp.varint(ticks)
659
660	if dolock {
661		unlock(&trace.lock)
662	}
663	return buf
664}
665
666// traceString adds a string to the trace.strings and returns the id.
667func traceString(bufp *traceBufPtr, pid int32, s string) (uint64, *traceBufPtr) {
668	if s == "" {
669		return 0, bufp
670	}
671
672	lock(&trace.stringsLock)
673	if raceenabled {
674		// raceacquire is necessary because the map access
675		// below is race annotated.
676		raceacquire(unsafe.Pointer(&trace.stringsLock))
677	}
678
679	if id, ok := trace.strings[s]; ok {
680		if raceenabled {
681			racerelease(unsafe.Pointer(&trace.stringsLock))
682		}
683		unlock(&trace.stringsLock)
684
685		return id, bufp
686	}
687
688	trace.stringSeq++
689	id := trace.stringSeq
690	trace.strings[s] = id
691
692	if raceenabled {
693		racerelease(unsafe.Pointer(&trace.stringsLock))
694	}
695	unlock(&trace.stringsLock)
696
697	// memory allocation in above may trigger tracing and
698	// cause *bufp changes. Following code now works with *bufp,
699	// so there must be no memory allocation or any activities
700	// that causes tracing after this point.
701
702	buf := bufp.ptr()
703	size := 1 + 2*traceBytesPerNumber + len(s)
704	if buf == nil || len(buf.arr)-buf.pos < size {
705		buf = traceFlush(traceBufPtrOf(buf), pid).ptr()
706		bufp.set(buf)
707	}
708	buf.byte(traceEvString)
709	buf.varint(id)
710
711	// double-check the string and the length can fit.
712	// Otherwise, truncate the string.
713	slen := len(s)
714	if room := len(buf.arr) - buf.pos; room < slen+traceBytesPerNumber {
715		slen = room
716	}
717
718	buf.varint(uint64(slen))
719	buf.pos += copy(buf.arr[buf.pos:], s[:slen])
720
721	bufp.set(buf)
722	return id, bufp
723}
724
725// traceAppend appends v to buf in little-endian-base-128 encoding.
726func traceAppend(buf []byte, v uint64) []byte {
727	for ; v >= 0x80; v >>= 7 {
728		buf = append(buf, 0x80|byte(v))
729	}
730	buf = append(buf, byte(v))
731	return buf
732}
733
734// varint appends v to buf in little-endian-base-128 encoding.
735func (buf *traceBuf) varint(v uint64) {
736	pos := buf.pos
737	for ; v >= 0x80; v >>= 7 {
738		buf.arr[pos] = 0x80 | byte(v)
739		pos++
740	}
741	buf.arr[pos] = byte(v)
742	pos++
743	buf.pos = pos
744}
745
746// byte appends v to buf.
747func (buf *traceBuf) byte(v byte) {
748	buf.arr[buf.pos] = v
749	buf.pos++
750}
751
752// traceStackTable maps stack traces (arrays of PC's) to unique uint32 ids.
753// It is lock-free for reading.
754type traceStackTable struct {
755	lock mutex
756	seq  uint32
757	mem  traceAlloc
758	tab  [1 << 13]traceStackPtr
759}
760
761// traceStack is a single stack in traceStackTable.
762type traceStack struct {
763	link traceStackPtr
764	hash uintptr
765	id   uint32
766	n    int
767	stk  [0]location // real type [n]location
768}
769
770type traceStackPtr uintptr
771
772func (tp traceStackPtr) ptr() *traceStack { return (*traceStack)(unsafe.Pointer(tp)) }
773
774// stack returns slice of PCs.
775func (ts *traceStack) stack() []location {
776	return (*[traceStackSize]location)(unsafe.Pointer(&ts.stk))[:ts.n]
777}
778
779// put returns a unique id for the stack trace pcs and caches it in the table,
780// if it sees the trace for the first time.
781func (tab *traceStackTable) put(pcs []location) uint32 {
782	if len(pcs) == 0 {
783		return 0
784	}
785	var hash uintptr
786	for _, loc := range pcs {
787		hash += loc.pc
788		hash += hash << 10
789		hash ^= hash >> 6
790	}
791	// First, search the hashtable w/o the mutex.
792	if id := tab.find(pcs, hash); id != 0 {
793		return id
794	}
795	// Now, double check under the mutex.
796	lock(&tab.lock)
797	if id := tab.find(pcs, hash); id != 0 {
798		unlock(&tab.lock)
799		return id
800	}
801	// Create new record.
802	tab.seq++
803	stk := tab.newStack(len(pcs))
804	stk.hash = hash
805	stk.id = tab.seq
806	stk.n = len(pcs)
807	stkpc := stk.stack()
808	for i, pc := range pcs {
809		// Use memmove to avoid write barrier.
810		memmove(unsafe.Pointer(&stkpc[i]), unsafe.Pointer(&pc), unsafe.Sizeof(pc))
811	}
812	part := int(hash % uintptr(len(tab.tab)))
813	stk.link = tab.tab[part]
814	atomicstorep(unsafe.Pointer(&tab.tab[part]), unsafe.Pointer(stk))
815	unlock(&tab.lock)
816	return stk.id
817}
818
819// find checks if the stack trace pcs is already present in the table.
820func (tab *traceStackTable) find(pcs []location, hash uintptr) uint32 {
821	part := int(hash % uintptr(len(tab.tab)))
822Search:
823	for stk := tab.tab[part].ptr(); stk != nil; stk = stk.link.ptr() {
824		if stk.hash == hash && stk.n == len(pcs) {
825			for i, stkpc := range stk.stack() {
826				if stkpc != pcs[i] {
827					continue Search
828				}
829			}
830			return stk.id
831		}
832	}
833	return 0
834}
835
836// newStack allocates a new stack of size n.
837func (tab *traceStackTable) newStack(n int) *traceStack {
838	return (*traceStack)(tab.mem.alloc(unsafe.Sizeof(traceStack{}) + uintptr(n)*unsafe.Sizeof(location{})))
839}
840
841// dump writes all previously cached stacks to trace buffers,
842// releases all memory and resets state.
843func (tab *traceStackTable) dump() {
844	var tmp [(2 + 4*traceStackSize) * traceBytesPerNumber]byte
845	bufp := traceFlush(0, 0)
846	for _, stk := range tab.tab {
847		stk := stk.ptr()
848		for ; stk != nil; stk = stk.link.ptr() {
849			tmpbuf := tmp[:0]
850			tmpbuf = traceAppend(tmpbuf, uint64(stk.id))
851			frames := stk.stack()
852			tmpbuf = traceAppend(tmpbuf, uint64(len(frames)))
853			for _, f := range frames {
854				var frame traceFrame
855				frame, bufp = traceFrameForPC(bufp, 0, f)
856				tmpbuf = traceAppend(tmpbuf, uint64(f.pc))
857				tmpbuf = traceAppend(tmpbuf, uint64(frame.funcID))
858				tmpbuf = traceAppend(tmpbuf, uint64(frame.fileID))
859				tmpbuf = traceAppend(tmpbuf, uint64(frame.line))
860			}
861			// Now copy to the buffer.
862			size := 1 + traceBytesPerNumber + len(tmpbuf)
863			if buf := bufp.ptr(); len(buf.arr)-buf.pos < size {
864				bufp = traceFlush(bufp, 0)
865			}
866			buf := bufp.ptr()
867			buf.byte(traceEvStack | 3<<traceArgCountShift)
868			buf.varint(uint64(len(tmpbuf)))
869			buf.pos += copy(buf.arr[buf.pos:], tmpbuf)
870		}
871	}
872
873	lock(&trace.lock)
874	traceFullQueue(bufp)
875	unlock(&trace.lock)
876
877	tab.mem.drop()
878	*tab = traceStackTable{}
879	lockInit(&((*tab).lock), lockRankTraceStackTab)
880}
881
882type traceFrame struct {
883	funcID uint64
884	fileID uint64
885	line   uint64
886}
887
888// traceFrameForPC records the frame information.
889// It may allocate memory.
890func traceFrameForPC(buf traceBufPtr, pid int32, f location) (traceFrame, traceBufPtr) {
891	bufp := &buf
892	var frame traceFrame
893
894	fn := f.function
895	const maxLen = 1 << 10
896	if len(fn) > maxLen {
897		fn = fn[len(fn)-maxLen:]
898	}
899	frame.funcID, bufp = traceString(bufp, pid, fn)
900	frame.line = uint64(f.lineno)
901	file := f.filename
902	if len(file) > maxLen {
903		file = file[len(file)-maxLen:]
904	}
905	frame.fileID, bufp = traceString(bufp, pid, file)
906	return frame, (*bufp)
907}
908
909// traceAlloc is a non-thread-safe region allocator.
910// It holds a linked list of traceAllocBlock.
911type traceAlloc struct {
912	head traceAllocBlockPtr
913	off  uintptr
914}
915
916// traceAllocBlock is a block in traceAlloc.
917//
918// traceAllocBlock is allocated from non-GC'd memory, so it must not
919// contain heap pointers. Writes to pointers to traceAllocBlocks do
920// not need write barriers.
921//
922//go:notinheap
923type traceAllocBlock struct {
924	next traceAllocBlockPtr
925	data [64<<10 - sys.PtrSize]byte
926}
927
928// TODO: Since traceAllocBlock is now go:notinheap, this isn't necessary.
929type traceAllocBlockPtr uintptr
930
931func (p traceAllocBlockPtr) ptr() *traceAllocBlock   { return (*traceAllocBlock)(unsafe.Pointer(p)) }
932func (p *traceAllocBlockPtr) set(x *traceAllocBlock) { *p = traceAllocBlockPtr(unsafe.Pointer(x)) }
933
934// alloc allocates n-byte block.
935func (a *traceAlloc) alloc(n uintptr) unsafe.Pointer {
936	n = alignUp(n, sys.PtrSize)
937	if a.head == 0 || a.off+n > uintptr(len(a.head.ptr().data)) {
938		if n > uintptr(len(a.head.ptr().data)) {
939			throw("trace: alloc too large")
940		}
941		// This is only safe because the strings returned by callers
942		// are stored in a location that is not in the Go heap.
943		block := (*traceAllocBlock)(sysAlloc(unsafe.Sizeof(traceAllocBlock{}), &memstats.other_sys))
944		if block == nil {
945			throw("trace: out of memory")
946		}
947		block.next.set(a.head.ptr())
948		a.head.set(block)
949		a.off = 0
950	}
951	p := &a.head.ptr().data[a.off]
952	a.off += n
953	return unsafe.Pointer(p)
954}
955
956// drop frees all previously allocated memory and resets the allocator.
957func (a *traceAlloc) drop() {
958	for a.head != 0 {
959		block := a.head.ptr()
960		a.head.set(block.next.ptr())
961		sysFree(unsafe.Pointer(block), unsafe.Sizeof(traceAllocBlock{}), &memstats.other_sys)
962	}
963}
964
965// The following functions write specific events to trace.
966
967func traceGomaxprocs(procs int32) {
968	traceEvent(traceEvGomaxprocs, 1, uint64(procs))
969}
970
971func traceProcStart() {
972	traceEvent(traceEvProcStart, -1, uint64(getg().m.id))
973}
974
975func traceProcStop(pp *p) {
976	// Sysmon and stopTheWorld can stop Ps blocked in syscalls,
977	// to handle this we temporary employ the P.
978	mp := acquirem()
979	oldp := mp.p
980	mp.p.set(pp)
981	traceEvent(traceEvProcStop, -1)
982	mp.p = oldp
983	releasem(mp)
984}
985
986func traceGCStart() {
987	traceEvent(traceEvGCStart, 3, trace.seqGC)
988	trace.seqGC++
989}
990
991func traceGCDone() {
992	traceEvent(traceEvGCDone, -1)
993}
994
995func traceGCSTWStart(kind int) {
996	traceEvent(traceEvGCSTWStart, -1, uint64(kind))
997}
998
999func traceGCSTWDone() {
1000	traceEvent(traceEvGCSTWDone, -1)
1001}
1002
1003// traceGCSweepStart prepares to trace a sweep loop. This does not
1004// emit any events until traceGCSweepSpan is called.
1005//
1006// traceGCSweepStart must be paired with traceGCSweepDone and there
1007// must be no preemption points between these two calls.
1008func traceGCSweepStart() {
1009	// Delay the actual GCSweepStart event until the first span
1010	// sweep. If we don't sweep anything, don't emit any events.
1011	_p_ := getg().m.p.ptr()
1012	if _p_.traceSweep {
1013		throw("double traceGCSweepStart")
1014	}
1015	_p_.traceSweep, _p_.traceSwept, _p_.traceReclaimed = true, 0, 0
1016}
1017
1018// traceGCSweepSpan traces the sweep of a single page.
1019//
1020// This may be called outside a traceGCSweepStart/traceGCSweepDone
1021// pair; however, it will not emit any trace events in this case.
1022func traceGCSweepSpan(bytesSwept uintptr) {
1023	_p_ := getg().m.p.ptr()
1024	if _p_.traceSweep {
1025		if _p_.traceSwept == 0 {
1026			traceEvent(traceEvGCSweepStart, 1)
1027		}
1028		_p_.traceSwept += bytesSwept
1029	}
1030}
1031
1032func traceGCSweepDone() {
1033	_p_ := getg().m.p.ptr()
1034	if !_p_.traceSweep {
1035		throw("missing traceGCSweepStart")
1036	}
1037	if _p_.traceSwept != 0 {
1038		traceEvent(traceEvGCSweepDone, -1, uint64(_p_.traceSwept), uint64(_p_.traceReclaimed))
1039	}
1040	_p_.traceSweep = false
1041}
1042
1043func traceGCMarkAssistStart() {
1044	traceEvent(traceEvGCMarkAssistStart, 1)
1045}
1046
1047func traceGCMarkAssistDone() {
1048	traceEvent(traceEvGCMarkAssistDone, -1)
1049}
1050
1051func traceGoCreate(newg *g, pc uintptr) {
1052	newg.traceseq = 0
1053	newg.tracelastp = getg().m.p
1054	// +PCQuantum because traceFrameForPC expects return PCs and subtracts PCQuantum.
1055	id := trace.stackTab.put([]location{location{pc: pc + sys.PCQuantum}})
1056	traceEvent(traceEvGoCreate, 2, uint64(newg.goid), uint64(id))
1057}
1058
1059func traceGoStart() {
1060	_g_ := getg().m.curg
1061	_p_ := _g_.m.p
1062	_g_.traceseq++
1063	if _p_.ptr().gcMarkWorkerMode != gcMarkWorkerNotWorker {
1064		traceEvent(traceEvGoStartLabel, -1, uint64(_g_.goid), _g_.traceseq, trace.markWorkerLabels[_p_.ptr().gcMarkWorkerMode])
1065	} else if _g_.tracelastp == _p_ {
1066		traceEvent(traceEvGoStartLocal, -1, uint64(_g_.goid))
1067	} else {
1068		_g_.tracelastp = _p_
1069		traceEvent(traceEvGoStart, -1, uint64(_g_.goid), _g_.traceseq)
1070	}
1071}
1072
1073func traceGoEnd() {
1074	traceEvent(traceEvGoEnd, -1)
1075}
1076
1077func traceGoSched() {
1078	_g_ := getg()
1079	_g_.tracelastp = _g_.m.p
1080	traceEvent(traceEvGoSched, 1)
1081}
1082
1083func traceGoPreempt() {
1084	_g_ := getg()
1085	_g_.tracelastp = _g_.m.p
1086	traceEvent(traceEvGoPreempt, 1)
1087}
1088
1089func traceGoPark(traceEv byte, skip int) {
1090	if traceEv&traceFutileWakeup != 0 {
1091		traceEvent(traceEvFutileWakeup, -1)
1092	}
1093	traceEvent(traceEv & ^traceFutileWakeup, skip)
1094}
1095
1096func traceGoUnpark(gp *g, skip int) {
1097	_p_ := getg().m.p
1098	gp.traceseq++
1099	if gp.tracelastp == _p_ {
1100		traceEvent(traceEvGoUnblockLocal, skip, uint64(gp.goid))
1101	} else {
1102		gp.tracelastp = _p_
1103		traceEvent(traceEvGoUnblock, skip, uint64(gp.goid), gp.traceseq)
1104	}
1105}
1106
1107func traceGoSysCall() {
1108	traceEvent(traceEvGoSysCall, 1)
1109}
1110
1111func traceGoSysExit(ts int64) {
1112	if ts != 0 && ts < trace.ticksStart {
1113		// There is a race between the code that initializes sysexitticks
1114		// (in exitsyscall, which runs without a P, and therefore is not
1115		// stopped with the rest of the world) and the code that initializes
1116		// a new trace. The recorded sysexitticks must therefore be treated
1117		// as "best effort". If they are valid for this trace, then great,
1118		// use them for greater accuracy. But if they're not valid for this
1119		// trace, assume that the trace was started after the actual syscall
1120		// exit (but before we actually managed to start the goroutine,
1121		// aka right now), and assign a fresh time stamp to keep the log consistent.
1122		ts = 0
1123	}
1124	_g_ := getg().m.curg
1125	_g_.traceseq++
1126	_g_.tracelastp = _g_.m.p
1127	traceEvent(traceEvGoSysExit, -1, uint64(_g_.goid), _g_.traceseq, uint64(ts)/traceTickDiv)
1128}
1129
1130func traceGoSysBlock(pp *p) {
1131	// Sysmon and stopTheWorld can declare syscalls running on remote Ps as blocked,
1132	// to handle this we temporary employ the P.
1133	mp := acquirem()
1134	oldp := mp.p
1135	mp.p.set(pp)
1136	traceEvent(traceEvGoSysBlock, -1)
1137	mp.p = oldp
1138	releasem(mp)
1139}
1140
1141func traceHeapAlloc() {
1142	traceEvent(traceEvHeapAlloc, -1, gcController.heapLive)
1143}
1144
1145func traceHeapGoal() {
1146	if heapGoal := atomic.Load64(&gcController.heapGoal); heapGoal == ^uint64(0) {
1147		// Heap-based triggering is disabled.
1148		traceEvent(traceEvHeapGoal, -1, 0)
1149	} else {
1150		traceEvent(traceEvHeapGoal, -1, heapGoal)
1151	}
1152}
1153
1154// To access runtime functions from runtime/trace.
1155// See runtime/trace/annotation.go
1156
1157//go:linkname trace_userTaskCreate runtime_1trace.userTaskCreate
1158func trace_userTaskCreate(id, parentID uint64, taskType string) {
1159	if !trace.enabled {
1160		return
1161	}
1162
1163	// Same as in traceEvent.
1164	mp, pid, bufp := traceAcquireBuffer()
1165	if !trace.enabled && !mp.startingtrace {
1166		traceReleaseBuffer(pid)
1167		return
1168	}
1169
1170	typeStringID, bufp := traceString(bufp, pid, taskType)
1171	traceEventLocked(0, mp, pid, bufp, traceEvUserTaskCreate, 3, id, parentID, typeStringID)
1172	traceReleaseBuffer(pid)
1173}
1174
1175//go:linkname trace_userTaskEnd runtime_1trace.userTaskEnd
1176func trace_userTaskEnd(id uint64) {
1177	traceEvent(traceEvUserTaskEnd, 2, id)
1178}
1179
1180//go:linkname trace_userRegion runtime_1trace.userRegion
1181func trace_userRegion(id, mode uint64, name string) {
1182	if !trace.enabled {
1183		return
1184	}
1185
1186	mp, pid, bufp := traceAcquireBuffer()
1187	if !trace.enabled && !mp.startingtrace {
1188		traceReleaseBuffer(pid)
1189		return
1190	}
1191
1192	nameStringID, bufp := traceString(bufp, pid, name)
1193	traceEventLocked(0, mp, pid, bufp, traceEvUserRegion, 3, id, mode, nameStringID)
1194	traceReleaseBuffer(pid)
1195}
1196
1197//go:linkname trace_userLog runtime_1trace.userLog
1198func trace_userLog(id uint64, category, message string) {
1199	if !trace.enabled {
1200		return
1201	}
1202
1203	mp, pid, bufp := traceAcquireBuffer()
1204	if !trace.enabled && !mp.startingtrace {
1205		traceReleaseBuffer(pid)
1206		return
1207	}
1208
1209	categoryID, bufp := traceString(bufp, pid, category)
1210
1211	extraSpace := traceBytesPerNumber + len(message) // extraSpace for the value string
1212	traceEventLocked(extraSpace, mp, pid, bufp, traceEvUserLog, 3, id, categoryID)
1213	// traceEventLocked reserved extra space for val and len(val)
1214	// in buf, so buf now has room for the following.
1215	buf := bufp.ptr()
1216
1217	// double-check the message and its length can fit.
1218	// Otherwise, truncate the message.
1219	slen := len(message)
1220	if room := len(buf.arr) - buf.pos; room < slen+traceBytesPerNumber {
1221		slen = room
1222	}
1223	buf.varint(uint64(slen))
1224	buf.pos += copy(buf.arr[buf.pos:], message[:slen])
1225
1226	traceReleaseBuffer(pid)
1227}
1228