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