Debian Codegraph @

trace/order.go

raw symbols SCIP
1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Code generated by "gen.bash" from internal/trace; DO NOT EDIT.
6
7 //go:build go1.23
8
9 package trace
10
11 import (
12 "fmt"
13 "slices"
14 "strings"
15
16 "golang.org/x/exp/trace/internal/tracev2"
17 "golang.org/x/exp/trace/internal/version"
18 )
19
20 // ordering emulates Go scheduler state for both validation and
21 // for putting events in the right order.
22 //
23 // The interface to ordering consists of two methods: Advance
24 // and Next. Advance is called to try and advance an event and
25 // add completed events to the ordering. Next is used to pick
26 // off events in the ordering.
27 type ordering struct {
28 traceVer version.Version
29 gStates map[GoID]*gState
30 pStates map[ProcID]*pState // TODO: The keys are dense, so this can be a slice.
31 mStates map[ThreadID]*mState
32 activeTasks map[TaskID]taskState
33 gcSeq uint64
34 gcState gcState
35 initialGen uint64
36 queue queue[Event]
37 }
38
39 // Advance checks if it's valid to proceed with ev which came from thread m.
40 //
41 // It assumes the gen value passed to it is monotonically increasing across calls.
42 //
43 // If any error is returned, then the trace is broken and trace parsing must cease.
44 // If it's not valid to advance with ev, but no error was encountered, the caller
45 // should attempt to advance with other candidate events from other threads. If the
46 // caller runs out of candidates, the trace is invalid.
47 //
48 // If this returns true, Next is guaranteed to return a complete event. However,
49 // multiple events may be added to the ordering, so the caller should (but is not
50 // required to) continue to call Next until it is exhausted.
51 func (o *ordering) Advance(ev *baseEvent, evt *evTable, m ThreadID, gen uint64) (bool, error) {
52 if o.initialGen == 0 {
53 // Set the initial gen if necessary.
54 o.initialGen = gen
55 }
56
57 var curCtx, newCtx schedCtx
58 curCtx.M = m
59 newCtx.M = m
60
61 var ms *mState
62 if m == NoThread {
63 curCtx.P = NoProc
64 curCtx.G = NoGoroutine
65 newCtx = curCtx
66 } else {
67 // Pull out or create the mState for this event.
68 var ok bool
69 ms, ok = o.mStates[m]
70 if !ok {
71 ms = &mState{
72 g: NoGoroutine,
73 p: NoProc,
74 }
75 o.mStates[m] = ms
76 }
77 curCtx.P = ms.p
78 curCtx.G = ms.g
79 newCtx = curCtx
80 }
81
82 f := orderingDispatch[ev.typ]
83 if f == nil {
84 return false, fmt.Errorf("bad event type found while ordering: %v", ev.typ)
85 }
86 newCtx, ok, err := f(o, ev, evt, m, gen, curCtx)
87 if err == nil && ok && ms != nil {
88 // Update the mState for this event.
89 ms.p = newCtx.P
90 ms.g = newCtx.G
91 }
92 return ok, err
93 }
94
95 func (o *ordering) evName(typ tracev2.EventType) string {
96 return o.traceVer.EventName(typ)
97 }
98
99 type orderingHandleFunc func(o *ordering, ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error)
100
101 var orderingDispatch = [256]orderingHandleFunc{
102 // Procs.
103 tracev2.EvProcsChange: (*ordering).advanceAnnotation,
104 tracev2.EvProcStart: (*ordering).advanceProcStart,
105 tracev2.EvProcStop: (*ordering).advanceProcStop,
106 tracev2.EvProcSteal: (*ordering).advanceProcSteal,
107 tracev2.EvProcStatus: (*ordering).advanceProcStatus,
108
109 // Goroutines.
110 tracev2.EvGoCreate: (*ordering).advanceGoCreate,
111 tracev2.EvGoCreateSyscall: (*ordering).advanceGoCreateSyscall,
112 tracev2.EvGoStart: (*ordering).advanceGoStart,
113 tracev2.EvGoDestroy: (*ordering).advanceGoStopExec,
114 tracev2.EvGoDestroySyscall: (*ordering).advanceGoDestroySyscall,
115 tracev2.EvGoStop: (*ordering).advanceGoStopExec,
116 tracev2.EvGoBlock: (*ordering).advanceGoStopExec,
117 tracev2.EvGoUnblock: (*ordering).advanceGoUnblock,
118 tracev2.EvGoSyscallBegin: (*ordering).advanceGoSyscallBegin,
119 tracev2.EvGoSyscallEnd: (*ordering).advanceGoSyscallEnd,
120 tracev2.EvGoSyscallEndBlocked: (*ordering).advanceGoSyscallEndBlocked,
121 tracev2.EvGoStatus: (*ordering).advanceGoStatus,
122
123 // STW.
124 tracev2.EvSTWBegin: (*ordering).advanceGoRangeBegin,
125 tracev2.EvSTWEnd: (*ordering).advanceGoRangeEnd,
126
127 // GC events.
128 tracev2.EvGCActive: (*ordering).advanceGCActive,
129 tracev2.EvGCBegin: (*ordering).advanceGCBegin,
130 tracev2.EvGCEnd: (*ordering).advanceGCEnd,
131 tracev2.EvGCSweepActive: (*ordering).advanceGCSweepActive,
132 tracev2.EvGCSweepBegin: (*ordering).advanceGCSweepBegin,
133 tracev2.EvGCSweepEnd: (*ordering).advanceGCSweepEnd,
134 tracev2.EvGCMarkAssistActive: (*ordering).advanceGoRangeActive,
135 tracev2.EvGCMarkAssistBegin: (*ordering).advanceGoRangeBegin,
136 tracev2.EvGCMarkAssistEnd: (*ordering).advanceGoRangeEnd,
137 tracev2.EvHeapAlloc: (*ordering).advanceHeapMetric,
138 tracev2.EvHeapGoal: (*ordering).advanceHeapMetric,
139
140 // Annotations.
141 tracev2.EvGoLabel: (*ordering).advanceAnnotation,
142 tracev2.EvUserTaskBegin: (*ordering).advanceUserTaskBegin,
143 tracev2.EvUserTaskEnd: (*ordering).advanceUserTaskEnd,
144 tracev2.EvUserRegionBegin: (*ordering).advanceUserRegionBegin,
145 tracev2.EvUserRegionEnd: (*ordering).advanceUserRegionEnd,
146 tracev2.EvUserLog: (*ordering).advanceAnnotation,
147
148 // Coroutines. Added in Go 1.23.
149 tracev2.EvGoSwitch: (*ordering).advanceGoSwitch,
150 tracev2.EvGoSwitchDestroy: (*ordering).advanceGoSwitch,
151 tracev2.EvGoCreateBlocked: (*ordering).advanceGoCreate,
152
153 // GoStatus event with a stack. Added in Go 1.23.
154 tracev2.EvGoStatusStack: (*ordering).advanceGoStatus,
155
156 // Experimental events.
157
158 // Experimental heap span events. Added in Go 1.23.
159 tracev2.EvSpan: (*ordering).advanceAllocFree,
160 tracev2.EvSpanAlloc: (*ordering).advanceAllocFree,
161 tracev2.EvSpanFree: (*ordering).advanceAllocFree,
162
163 // Experimental heap object events. Added in Go 1.23.
164 tracev2.EvHeapObject: (*ordering).advanceAllocFree,
165 tracev2.EvHeapObjectAlloc: (*ordering).advanceAllocFree,
166 tracev2.EvHeapObjectFree: (*ordering).advanceAllocFree,
167
168 // Experimental goroutine stack events. Added in Go 1.23.
169 tracev2.EvGoroutineStack: (*ordering).advanceAllocFree,
170 tracev2.EvGoroutineStackAlloc: (*ordering).advanceAllocFree,
171 tracev2.EvGoroutineStackFree: (*ordering).advanceAllocFree,
172 }
173
174 func (o *ordering) advanceProcStatus(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
175 pid := ProcID(ev.args[0])
176 status := tracev2.ProcStatus(ev.args[1])
177 if int(status) >= len(tracev2ProcStatus2ProcState) {
178 return curCtx, false, fmt.Errorf("invalid status for proc %d: %d", pid, status)
179 }
180 oldState := tracev2ProcStatus2ProcState[status]
181 if s, ok := o.pStates[pid]; ok {
182 if status == tracev2.ProcSyscallAbandoned && s.status == tracev2.ProcSyscall {
183 // ProcSyscallAbandoned is a special case of ProcSyscall. It indicates a
184 // potential loss of information, but if we're already in ProcSyscall,
185 // we haven't lost the relevant information. Promote the status and advance.
186 oldState = ProcRunning
187 ev.args[1] = uint64(tracev2.ProcSyscall)
188 } else if status == tracev2.ProcSyscallAbandoned && s.status == tracev2.ProcSyscallAbandoned {
189 // If we're passing through ProcSyscallAbandoned, then there's no promotion
190 // to do. We've lost the M that this P is associated with. However it got there,
191 // it's going to appear as idle in the API, so pass through as idle.
192 oldState = ProcIdle
193 ev.args[1] = uint64(tracev2.ProcSyscallAbandoned)
194 } else if s.status != status {
195 return curCtx, false, fmt.Errorf("inconsistent status for proc %d: old %v vs. new %v", pid, s.status, status)
196 }
197 s.seq = makeSeq(gen, 0) // Reset seq.
198 } else {
199 o.pStates[pid] = &pState{id: pid, status: status, seq: makeSeq(gen, 0)}
200 if gen == o.initialGen {
201 oldState = ProcUndetermined
202 } else {
203 oldState = ProcNotExist
204 }
205 }
206 ev.extra(version.Go122)[0] = uint64(oldState) // Smuggle in the old state for StateTransition.
207
208 // Bind the proc to the new context, if it's running.
209 newCtx := curCtx
210 if status == tracev2.ProcRunning || status == tracev2.ProcSyscall {
211 newCtx.P = pid
212 }
213 // If we're advancing through ProcSyscallAbandoned *but* oldState is running then we've
214 // promoted it to ProcSyscall. However, because it's ProcSyscallAbandoned, we know this
215 // P is about to get stolen and its status very likely isn't being emitted by the same
216 // thread it was bound to. Since this status is Running -> Running and Running is binding,
217 // we need to make sure we emit it in the right context: the context to which it is bound.
218 // Find it, and set our current context to it.
219 if status == tracev2.ProcSyscallAbandoned && oldState == ProcRunning {
220 // N.B. This is slow but it should be fairly rare.
221 found := false
222 for mid, ms := range o.mStates {
223 if ms.p == pid {
224 curCtx.M = mid
225 curCtx.P = pid
226 curCtx.G = ms.g
227 found = true
228 }
229 }
230 if !found {
231 return curCtx, false, fmt.Errorf("failed to find sched context for proc %d that's about to be stolen", pid)
232 }
233 }
234 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
235 return newCtx, true, nil
236 }
237
238 func (o *ordering) advanceProcStart(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
239 pid := ProcID(ev.args[0])
240 seq := makeSeq(gen, ev.args[1])
241
242 // Try to advance. We might fail here due to sequencing, because the P hasn't
243 // had a status emitted, or because we already have a P and we're in a syscall,
244 // and we haven't observed that it was stolen from us yet.
245 state, ok := o.pStates[pid]
246 if !ok || state.status != tracev2.ProcIdle || !seq.succeeds(state.seq) || curCtx.P != NoProc {
247 // We can't make an inference as to whether this is bad. We could just be seeing
248 // a ProcStart on a different M before the proc's state was emitted, or before we
249 // got to the right point in the trace.
250 //
251 // Note that we also don't advance here if we have a P and we're in a syscall.
252 return curCtx, false, nil
253 }
254 // We can advance this P. Check some invariants.
255 //
256 // We might have a goroutine if a goroutine is exiting a syscall.
257 reqs := schedReqs{M: mustHave, P: mustNotHave, G: mayHave}
258 if err := validateCtx(curCtx, reqs); err != nil {
259 return curCtx, false, err
260 }
261 state.status = tracev2.ProcRunning
262 state.seq = seq
263 newCtx := curCtx
264 newCtx.P = pid
265 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
266 return newCtx, true, nil
267 }
268
269 func (o *ordering) advanceProcStop(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
270 // We must be able to advance this P.
271 //
272 // There are 2 ways a P can stop: ProcStop and ProcSteal. ProcStop is used when the P
273 // is stopped by the same M that started it, while ProcSteal is used when another M
274 // steals the P by stopping it from a distance.
275 //
276 // Since a P is bound to an M, and we're stopping on the same M we started, it must
277 // always be possible to advance the current M's P from a ProcStop. This is also why
278 // ProcStop doesn't need a sequence number.
279 state, ok := o.pStates[curCtx.P]
280 if !ok {
281 return curCtx, false, fmt.Errorf("event %s for proc (%v) that doesn't exist", o.evName(ev.typ), curCtx.P)
282 }
283 if state.status != tracev2.ProcRunning && state.status != tracev2.ProcSyscall {
284 return curCtx, false, fmt.Errorf("%s event for proc that's not %s or %s", o.evName(ev.typ), tracev2.ProcRunning, tracev2.ProcSyscall)
285 }
286 reqs := schedReqs{M: mustHave, P: mustHave, G: mayHave}
287 if err := validateCtx(curCtx, reqs); err != nil {
288 return curCtx, false, err
289 }
290 state.status = tracev2.ProcIdle
291 newCtx := curCtx
292 newCtx.P = NoProc
293 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
294 return newCtx, true, nil
295 }
296
297 func (o *ordering) advanceProcSteal(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
298 pid := ProcID(ev.args[0])
299 seq := makeSeq(gen, ev.args[1])
300 state, ok := o.pStates[pid]
301 if !ok || (state.status != tracev2.ProcSyscall && state.status != tracev2.ProcSyscallAbandoned) || !seq.succeeds(state.seq) {
302 // We can't make an inference as to whether this is bad. We could just be seeing
303 // a ProcStart on a different M before the proc's state was emitted, or before we
304 // got to the right point in the trace.
305 return curCtx, false, nil
306 }
307 // We can advance this P. Check some invariants.
308 reqs := schedReqs{M: mustHave, P: mayHave, G: mayHave}
309 if err := validateCtx(curCtx, reqs); err != nil {
310 return curCtx, false, err
311 }
312 // Smuggle in the P state that let us advance so we can surface information to the event.
313 // Specifically, we need to make sure that the event is interpreted not as a transition of
314 // ProcRunning -> ProcIdle but ProcIdle -> ProcIdle instead.
315 //
316 // ProcRunning is binding, but we may be running with a P on the current M and we can't
317 // bind another P. This P is about to go ProcIdle anyway.
318 oldStatus := state.status
319 ev.extra(version.Go122)[0] = uint64(oldStatus)
320
321 // Update the P's status and sequence number.
322 state.status = tracev2.ProcIdle
323 state.seq = seq
324
325 // If we've lost information then don't try to do anything with the M.
326 // It may have moved on and we can't be sure.
327 if oldStatus == tracev2.ProcSyscallAbandoned {
328 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
329 return curCtx, true, nil
330 }
331
332 // Validate that the M we're stealing from is what we expect.
333 mid := ThreadID(ev.args[2]) // The M we're stealing from.
334
335 newCtx := curCtx
336 if mid == curCtx.M {
337 // We're stealing from ourselves. This behaves like a ProcStop.
338 if curCtx.P != pid {
339 return curCtx, false, fmt.Errorf("tried to self-steal proc %d (thread %d), but got proc %d instead", pid, mid, curCtx.P)
340 }
341 newCtx.P = NoProc
342 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
343 return newCtx, true, nil
344 }
345
346 // We're stealing from some other M.
347 mState, ok := o.mStates[mid]
348 if !ok {
349 return curCtx, false, fmt.Errorf("stole proc from non-existent thread %d", mid)
350 }
351
352 // Make sure we're actually stealing the right P.
353 if mState.p != pid {
354 return curCtx, false, fmt.Errorf("tried to steal proc %d from thread %d, but got proc %d instead", pid, mid, mState.p)
355 }
356
357 // Tell the M it has no P so it can proceed.
358 //
359 // This is safe because we know the P was in a syscall and
360 // the other M must be trying to get out of the syscall.
361 // GoSyscallEndBlocked cannot advance until the corresponding
362 // M loses its P.
363 mState.p = NoProc
364 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
365 return newCtx, true, nil
366 }
367
368 func (o *ordering) advanceGoStatus(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
369 gid := GoID(ev.args[0])
370 mid := ThreadID(ev.args[1])
371 status := tracev2.GoStatus(ev.args[2])
372
373 if int(status) >= len(tracev2GoStatus2GoState) {
374 return curCtx, false, fmt.Errorf("invalid status for goroutine %d: %d", gid, status)
375 }
376 oldState := tracev2GoStatus2GoState[status]
377 if s, ok := o.gStates[gid]; ok {
378 if s.status != status {
379 return curCtx, false, fmt.Errorf("inconsistent status for goroutine %d: old %v vs. new %v", gid, s.status, status)
380 }
381 s.seq = makeSeq(gen, 0) // Reset seq.
382 } else if gen == o.initialGen {
383 // Set the state.
384 o.gStates[gid] = &gState{id: gid, status: status, seq: makeSeq(gen, 0)}
385 oldState = GoUndetermined
386 } else {
387 return curCtx, false, fmt.Errorf("found goroutine status for new goroutine after the first generation: id=%v status=%v", gid, status)
388 }
389 ev.args[2] = uint64(oldState)<<32 | uint64(status) // Smuggle in the old state for StateTransition.
390
391 newCtx := curCtx
392 switch status {
393 case tracev2.GoRunning:
394 // Bind the goroutine to the new context, since it's running.
395 newCtx.G = gid
396 case tracev2.GoSyscall:
397 if mid == NoThread {
398 return curCtx, false, fmt.Errorf("found goroutine %d in syscall without a thread", gid)
399 }
400 // Is the syscall on this thread? If so, bind it to the context.
401 // Otherwise, we're talking about a G sitting in a syscall on an M.
402 // Validate the named M.
403 if mid == curCtx.M {
404 if gen != o.initialGen && curCtx.G != gid {
405 // If this isn't the first generation, we *must* have seen this
406 // binding occur already. Even if the G was blocked in a syscall
407 // for multiple generations since trace start, we would have seen
408 // a previous GoStatus event that bound the goroutine to an M.
409 return curCtx, false, fmt.Errorf("inconsistent thread for syscalling goroutine %d: thread has goroutine %d", gid, curCtx.G)
410 }
411 newCtx.G = gid
412 break
413 }
414 // Now we're talking about a thread and goroutine that have been
415 // blocked on a syscall for the entire generation. This case must
416 // not have a P; the runtime makes sure that all Ps are traced at
417 // the beginning of a generation, which involves taking a P back
418 // from every thread.
419 ms, ok := o.mStates[mid]
420 if ok {
421 // This M has been seen. That means we must have seen this
422 // goroutine go into a syscall on this thread at some point.
423 if ms.g != gid {
424 // But the G on the M doesn't match. Something's wrong.
425 return curCtx, false, fmt.Errorf("inconsistent thread for syscalling goroutine %d: thread has goroutine %d", gid, ms.g)
426 }
427 // This case is just a Syscall->Syscall event, which needs to
428 // appear as having the G currently bound to this M.
429 curCtx.G = ms.g
430 } else if !ok {
431 // The M hasn't been seen yet. That means this goroutine
432 // has just been sitting in a syscall on this M. Create
433 // a state for it.
434 o.mStates[mid] = &mState{g: gid, p: NoProc}
435 // Don't set curCtx.G in this case because this event is the
436 // binding event (and curCtx represents the "before" state).
437 }
438 // Update the current context to the M we're talking about.
439 curCtx.M = mid
440 }
441 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
442 return newCtx, true, nil
443 }
444
445 func (o *ordering) advanceGoCreate(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
446 // Goroutines must be created on a running P, but may or may not be created
447 // by a running goroutine.
448 reqs := schedReqs{M: mustHave, P: mustHave, G: mayHave}
449 if err := validateCtx(curCtx, reqs); err != nil {
450 return curCtx, false, err
451 }
452 // If we have a goroutine, it must be running.
453 if state, ok := o.gStates[curCtx.G]; ok && state.status != tracev2.GoRunning {
454 return curCtx, false, fmt.Errorf("%s event for goroutine that's not %s", o.evName(ev.typ), GoRunning)
455 }
456 // This goroutine created another. Add a state for it.
457 newgid := GoID(ev.args[0])
458 if _, ok := o.gStates[newgid]; ok {
459 return curCtx, false, fmt.Errorf("tried to create goroutine (%v) that already exists", newgid)
460 }
461 status := tracev2.GoRunnable
462 if ev.typ == tracev2.EvGoCreateBlocked {
463 status = tracev2.GoWaiting
464 }
465 o.gStates[newgid] = &gState{id: newgid, status: status, seq: makeSeq(gen, 0)}
466 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
467 return curCtx, true, nil
468 }
469
470 func (o *ordering) advanceGoStopExec(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
471 // These are goroutine events that all require an active running
472 // goroutine on some thread. They must *always* be advance-able,
473 // since running goroutines are bound to their M.
474 if err := validateCtx(curCtx, userGoReqs); err != nil {
475 return curCtx, false, err
476 }
477 state, ok := o.gStates[curCtx.G]
478 if !ok {
479 return curCtx, false, fmt.Errorf("event %s for goroutine (%v) that doesn't exist", o.evName(ev.typ), curCtx.G)
480 }
481 if state.status != tracev2.GoRunning {
482 return curCtx, false, fmt.Errorf("%s event for goroutine that's not %s", o.evName(ev.typ), GoRunning)
483 }
484 // Handle each case slightly differently; we just group them together
485 // because they have shared preconditions.
486 newCtx := curCtx
487 switch ev.typ {
488 case tracev2.EvGoDestroy:
489 // This goroutine is exiting itself.
490 delete(o.gStates, curCtx.G)
491 newCtx.G = NoGoroutine
492 case tracev2.EvGoStop:
493 // Goroutine stopped (yielded). It's runnable but not running on this M.
494 state.status = tracev2.GoRunnable
495 newCtx.G = NoGoroutine
496 case tracev2.EvGoBlock:
497 // Goroutine blocked. It's waiting now and not running on this M.
498 state.status = tracev2.GoWaiting
499 newCtx.G = NoGoroutine
500 }
501 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
502 return newCtx, true, nil
503 }
504
505 func (o *ordering) advanceGoStart(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
506 gid := GoID(ev.args[0])
507 seq := makeSeq(gen, ev.args[1])
508 state, ok := o.gStates[gid]
509 if !ok || state.status != tracev2.GoRunnable || !seq.succeeds(state.seq) {
510 // We can't make an inference as to whether this is bad. We could just be seeing
511 // a GoStart on a different M before the goroutine was created, before it had its
512 // state emitted, or before we got to the right point in the trace yet.
513 return curCtx, false, nil
514 }
515 // We can advance this goroutine. Check some invariants.
516 reqs := schedReqs{M: mustHave, P: mustHave, G: mustNotHave}
517 if err := validateCtx(curCtx, reqs); err != nil {
518 return curCtx, false, err
519 }
520 state.status = tracev2.GoRunning
521 state.seq = seq
522 newCtx := curCtx
523 newCtx.G = gid
524 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
525 return newCtx, true, nil
526 }
527
528 func (o *ordering) advanceGoUnblock(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
529 // N.B. These both reference the goroutine to unblock, not the current goroutine.
530 gid := GoID(ev.args[0])
531 seq := makeSeq(gen, ev.args[1])
532 state, ok := o.gStates[gid]
533 if !ok || state.status != tracev2.GoWaiting || !seq.succeeds(state.seq) {
534 // We can't make an inference as to whether this is bad. We could just be seeing
535 // a GoUnblock on a different M before the goroutine was created and blocked itself,
536 // before it had its state emitted, or before we got to the right point in the trace yet.
537 return curCtx, false, nil
538 }
539 state.status = tracev2.GoRunnable
540 state.seq = seq
541 // N.B. No context to validate. Basically anything can unblock
542 // a goroutine (e.g. sysmon).
543 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
544 return curCtx, true, nil
545 }
546
547 func (o *ordering) advanceGoSwitch(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
548 // GoSwitch and GoSwitchDestroy represent a trio of events:
549 // - Unblock of the goroutine to switch to.
550 // - Block or destroy of the current goroutine.
551 // - Start executing the next goroutine.
552 //
553 // Because it acts like a GoStart for the next goroutine, we can
554 // only advance it if the sequence numbers line up.
555 //
556 // The current goroutine on the thread must be actively running.
557 if err := validateCtx(curCtx, userGoReqs); err != nil {
558 return curCtx, false, err
559 }
560 curGState, ok := o.gStates[curCtx.G]
561 if !ok {
562 return curCtx, false, fmt.Errorf("event %s for goroutine (%v) that doesn't exist", o.evName(ev.typ), curCtx.G)
563 }
564 if curGState.status != tracev2.GoRunning {
565 return curCtx, false, fmt.Errorf("%s event for goroutine that's not %s", o.evName(ev.typ), GoRunning)
566 }
567 nextg := GoID(ev.args[0])
568 seq := makeSeq(gen, ev.args[1]) // seq is for nextg, not curCtx.G.
569 nextGState, ok := o.gStates[nextg]
570 if !ok || nextGState.status != tracev2.GoWaiting || !seq.succeeds(nextGState.seq) {
571 // We can't make an inference as to whether this is bad. We could just be seeing
572 // a GoSwitch on a different M before the goroutine was created, before it had its
573 // state emitted, or before we got to the right point in the trace yet.
574 return curCtx, false, nil
575 }
576 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
577
578 // Update the state of the executing goroutine and emit an event for it
579 // (GoSwitch and GoSwitchDestroy will be interpreted as GoUnblock events
580 // for nextg).
581 switch ev.typ {
582 case tracev2.EvGoSwitch:
583 // Goroutine blocked. It's waiting now and not running on this M.
584 curGState.status = tracev2.GoWaiting
585
586 // Emit a GoBlock event.
587 // TODO(mknyszek): Emit a reason.
588 o.queue.push(makeEvent(evt, curCtx, tracev2.EvGoBlock, ev.time, 0 /* no reason */, 0 /* no stack */))
589 case tracev2.EvGoSwitchDestroy:
590 // This goroutine is exiting itself.
591 delete(o.gStates, curCtx.G)
592
593 // Emit a GoDestroy event.
594 o.queue.push(makeEvent(evt, curCtx, tracev2.EvGoDestroy, ev.time))
595 }
596 // Update the state of the next goroutine.
597 nextGState.status = tracev2.GoRunning
598 nextGState.seq = seq
599 newCtx := curCtx
600 newCtx.G = nextg
601
602 // Queue an event for the next goroutine starting to run.
603 startCtx := curCtx
604 startCtx.G = NoGoroutine
605 o.queue.push(makeEvent(evt, startCtx, tracev2.EvGoStart, ev.time, uint64(nextg), ev.args[1]))
606 return newCtx, true, nil
607 }
608
609 func (o *ordering) advanceGoSyscallBegin(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
610 // Entering a syscall requires an active running goroutine with a
611 // proc on some thread. It is always advancable.
612 if err := validateCtx(curCtx, userGoReqs); err != nil {
613 return curCtx, false, err
614 }
615 state, ok := o.gStates[curCtx.G]
616 if !ok {
617 return curCtx, false, fmt.Errorf("event %s for goroutine (%v) that doesn't exist", o.evName(ev.typ), curCtx.G)
618 }
619 if state.status != tracev2.GoRunning {
620 return curCtx, false, fmt.Errorf("%s event for goroutine that's not %s", o.evName(ev.typ), GoRunning)
621 }
622 // Goroutine entered a syscall. It's still running on this P and M.
623 state.status = tracev2.GoSyscall
624 pState, ok := o.pStates[curCtx.P]
625 if !ok {
626 return curCtx, false, fmt.Errorf("uninitialized proc %d found during %s", curCtx.P, o.evName(ev.typ))
627 }
628 pState.status = tracev2.ProcSyscall
629 // Validate the P sequence number on the event and advance it.
630 //
631 // We have a P sequence number for what is supposed to be a goroutine event
632 // so that we can correctly model P stealing. Without this sequence number here,
633 // the syscall from which a ProcSteal event is stealing can be ambiguous in the
634 // face of broken timestamps. See the go122-syscall-steal-proc-ambiguous test for
635 // more details.
636 //
637 // Note that because this sequence number only exists as a tool for disambiguation,
638 // we can enforce that we have the right sequence number at this point; we don't need
639 // to back off and see if any other events will advance. This is a running P.
640 pSeq := makeSeq(gen, ev.args[0])
641 if !pSeq.succeeds(pState.seq) {
642 return curCtx, false, fmt.Errorf("failed to advance %s: can't make sequence: %s -> %s", o.evName(ev.typ), pState.seq, pSeq)
643 }
644 pState.seq = pSeq
645 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
646 return curCtx, true, nil
647 }
648
649 func (o *ordering) advanceGoSyscallEnd(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
650 // This event is always advance-able because it happens on the same
651 // thread that EvGoSyscallStart happened, and the goroutine can't leave
652 // that thread until its done.
653 if err := validateCtx(curCtx, userGoReqs); err != nil {
654 return curCtx, false, err
655 }
656 state, ok := o.gStates[curCtx.G]
657 if !ok {
658 return curCtx, false, fmt.Errorf("event %s for goroutine (%v) that doesn't exist", o.evName(ev.typ), curCtx.G)
659 }
660 if state.status != tracev2.GoSyscall {
661 return curCtx, false, fmt.Errorf("%s event for goroutine that's not %s", o.evName(ev.typ), GoRunning)
662 }
663 state.status = tracev2.GoRunning
664
665 // Transfer the P back to running from syscall.
666 pState, ok := o.pStates[curCtx.P]
667 if !ok {
668 return curCtx, false, fmt.Errorf("uninitialized proc %d found during %s", curCtx.P, o.evName(ev.typ))
669 }
670 if pState.status != tracev2.ProcSyscall {
671 return curCtx, false, fmt.Errorf("expected proc %d in state %v, but got %v instead", curCtx.P, tracev2.ProcSyscall, pState.status)
672 }
673 pState.status = tracev2.ProcRunning
674 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
675 return curCtx, true, nil
676 }
677
678 func (o *ordering) advanceGoSyscallEndBlocked(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
679 // This event becomes advanceable when its P is not in a syscall state
680 // (lack of a P altogether is also acceptable for advancing).
681 // The transfer out of ProcSyscall can happen either voluntarily via
682 // ProcStop or involuntarily via ProcSteal. We may also acquire a new P
683 // before we get here (after the transfer out) but that's OK: that new
684 // P won't be in the ProcSyscall state anymore.
685 //
686 // Basically: while we have a preemptible P, don't advance, because we
687 // *know* from the event that we're going to lose it at some point during
688 // the syscall. We shouldn't advance until that happens.
689 if curCtx.P != NoProc {
690 pState, ok := o.pStates[curCtx.P]
691 if !ok {
692 return curCtx, false, fmt.Errorf("uninitialized proc %d found during %s", curCtx.P, o.evName(ev.typ))
693 }
694 if pState.status == tracev2.ProcSyscall {
695 return curCtx, false, nil
696 }
697 }
698 // As mentioned above, we may have a P here if we ProcStart
699 // before this event.
700 if err := validateCtx(curCtx, schedReqs{M: mustHave, P: mayHave, G: mustHave}); err != nil {
701 return curCtx, false, err
702 }
703 state, ok := o.gStates[curCtx.G]
704 if !ok {
705 return curCtx, false, fmt.Errorf("event %s for goroutine (%v) that doesn't exist", o.evName(ev.typ), curCtx.G)
706 }
707 if state.status != tracev2.GoSyscall {
708 return curCtx, false, fmt.Errorf("%s event for goroutine that's not %s", o.evName(ev.typ), GoRunning)
709 }
710 newCtx := curCtx
711 newCtx.G = NoGoroutine
712 state.status = tracev2.GoRunnable
713 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
714 return newCtx, true, nil
715 }
716
717 func (o *ordering) advanceGoCreateSyscall(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
718 // This event indicates that a goroutine is effectively
719 // being created out of a cgo callback. Such a goroutine
720 // is 'created' in the syscall state.
721 if err := validateCtx(curCtx, schedReqs{M: mustHave, P: mayHave, G: mustNotHave}); err != nil {
722 return curCtx, false, err
723 }
724 // This goroutine is effectively being created. Add a state for it.
725 newgid := GoID(ev.args[0])
726 if _, ok := o.gStates[newgid]; ok {
727 return curCtx, false, fmt.Errorf("tried to create goroutine (%v) in syscall that already exists", newgid)
728 }
729 o.gStates[newgid] = &gState{id: newgid, status: tracev2.GoSyscall, seq: makeSeq(gen, 0)}
730 // Goroutine is executing. Bind it to the context.
731 newCtx := curCtx
732 newCtx.G = newgid
733 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
734 return newCtx, true, nil
735 }
736
737 func (o *ordering) advanceGoDestroySyscall(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
738 // This event indicates that a goroutine created for a
739 // cgo callback is disappearing, either because the callback
740 // ending or the C thread that called it is being destroyed.
741 //
742 // Also, treat this as if we lost our P too.
743 // The thread ID may be reused by the platform and we'll get
744 // really confused if we try to steal the P is this is running
745 // with later. The new M with the same ID could even try to
746 // steal back this P from itself!
747 //
748 // The runtime is careful to make sure that any GoCreateSyscall
749 // event will enter the runtime emitting events for reacquiring a P.
750 //
751 // Note: we might have a P here. The P might not be released
752 // eagerly by the runtime, and it might get stolen back later
753 // (or never again, if the program is going to exit).
754 if err := validateCtx(curCtx, schedReqs{M: mustHave, P: mayHave, G: mustHave}); err != nil {
755 return curCtx, false, err
756 }
757 // Check to make sure the goroutine exists in the right state.
758 state, ok := o.gStates[curCtx.G]
759 if !ok {
760 return curCtx, false, fmt.Errorf("event %s for goroutine (%v) that doesn't exist", o.evName(ev.typ), curCtx.G)
761 }
762 if state.status != tracev2.GoSyscall {
763 return curCtx, false, fmt.Errorf("%s event for goroutine that's not %v", o.evName(ev.typ), GoSyscall)
764 }
765 // This goroutine is exiting itself.
766 delete(o.gStates, curCtx.G)
767 newCtx := curCtx
768 newCtx.G = NoGoroutine
769
770 // If we have a proc, then we're dissociating from it now. See the comment at the top of the case.
771 if curCtx.P != NoProc {
772 pState, ok := o.pStates[curCtx.P]
773 if !ok {
774 return curCtx, false, fmt.Errorf("found invalid proc %d during %s", curCtx.P, o.evName(ev.typ))
775 }
776 if pState.status != tracev2.ProcSyscall {
777 return curCtx, false, fmt.Errorf("proc %d in unexpected state %s during %s", curCtx.P, pState.status, o.evName(ev.typ))
778 }
779 // See the go122-create-syscall-reuse-thread-id test case for more details.
780 pState.status = tracev2.ProcSyscallAbandoned
781 newCtx.P = NoProc
782
783 // Queue an extra self-ProcSteal event.
784 extra := makeEvent(evt, curCtx, tracev2.EvProcSteal, ev.time, uint64(curCtx.P))
785 extra.base.extra(version.Go122)[0] = uint64(tracev2.ProcSyscall)
786 o.queue.push(extra)
787 }
788 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
789 return newCtx, true, nil
790 }
791
792 func (o *ordering) advanceUserTaskBegin(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
793 // Handle tasks. Tasks are interesting because:
794 // - There's no Begin event required to reference a task.
795 // - End for a particular task ID can appear multiple times.
796 // As a result, there's very little to validate. The only
797 // thing we have to be sure of is that a task didn't begin
798 // after it had already begun. Task IDs are allowed to be
799 // reused, so we don't care about a Begin after an End.
800 id := TaskID(ev.args[0])
801 if _, ok := o.activeTasks[id]; ok {
802 return curCtx, false, fmt.Errorf("task ID conflict: %d", id)
803 }
804 // Get the parent ID, but don't validate it. There's no guarantee
805 // we actually have information on whether it's active.
806 parentID := TaskID(ev.args[1])
807 if parentID == BackgroundTask {
808 // Note: a value of 0 here actually means no parent, *not* the
809 // background task. Automatic background task attachment only
810 // applies to regions.
811 parentID = NoTask
812 ev.args[1] = uint64(NoTask)
813 }
814
815 // Validate the name and record it. We'll need to pass it through to
816 // EvUserTaskEnd.
817 nameID := stringID(ev.args[2])
818 name, ok := evt.strings.get(nameID)
819 if !ok {
820 return curCtx, false, fmt.Errorf("invalid string ID %v for %v event", nameID, ev.typ)
821 }
822 o.activeTasks[id] = taskState{name: name, parentID: parentID}
823 if err := validateCtx(curCtx, userGoReqs); err != nil {
824 return curCtx, false, err
825 }
826 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
827 return curCtx, true, nil
828 }
829
830 func (o *ordering) advanceUserTaskEnd(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
831 id := TaskID(ev.args[0])
832 if ts, ok := o.activeTasks[id]; ok {
833 // Smuggle the task info. This may happen in a different generation,
834 // which may not have the name in its string table. Add it to the extra
835 // strings table so we can look it up later.
836 ev.extra(version.Go122)[0] = uint64(ts.parentID)
837 ev.extra(version.Go122)[1] = uint64(evt.addExtraString(ts.name))
838 delete(o.activeTasks, id)
839 } else {
840 // Explicitly clear the task info.
841 ev.extra(version.Go122)[0] = uint64(NoTask)
842 ev.extra(version.Go122)[1] = uint64(evt.addExtraString(""))
843 }
844 if err := validateCtx(curCtx, userGoReqs); err != nil {
845 return curCtx, false, err
846 }
847 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
848 return curCtx, true, nil
849 }
850
851 func (o *ordering) advanceUserRegionBegin(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
852 if err := validateCtx(curCtx, userGoReqs); err != nil {
853 return curCtx, false, err
854 }
855 tid := TaskID(ev.args[0])
856 nameID := stringID(ev.args[1])
857 name, ok := evt.strings.get(nameID)
858 if !ok {
859 return curCtx, false, fmt.Errorf("invalid string ID %v for %v event", nameID, ev.typ)
860 }
861 gState, ok := o.gStates[curCtx.G]
862 if !ok {
863 return curCtx, false, fmt.Errorf("encountered EvUserRegionBegin without known state for current goroutine %d", curCtx.G)
864 }
865 if err := gState.beginRegion(userRegion{tid, name}); err != nil {
866 return curCtx, false, err
867 }
868 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
869 return curCtx, true, nil
870 }
871
872 func (o *ordering) advanceUserRegionEnd(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
873 if err := validateCtx(curCtx, userGoReqs); err != nil {
874 return curCtx, false, err
875 }
876 tid := TaskID(ev.args[0])
877 nameID := stringID(ev.args[1])
878 name, ok := evt.strings.get(nameID)
879 if !ok {
880 return curCtx, false, fmt.Errorf("invalid string ID %v for %v event", nameID, ev.typ)
881 }
882 gState, ok := o.gStates[curCtx.G]
883 if !ok {
884 return curCtx, false, fmt.Errorf("encountered EvUserRegionEnd without known state for current goroutine %d", curCtx.G)
885 }
886 if err := gState.endRegion(userRegion{tid, name}); err != nil {
887 return curCtx, false, err
888 }
889 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
890 return curCtx, true, nil
891 }
892
893 // Handle the GC mark phase.
894 //
895 // We have sequence numbers for both start and end because they
896 // can happen on completely different threads. We want an explicit
897 // partial order edge between start and end here, otherwise we're
898 // relying entirely on timestamps to make sure we don't advance a
899 // GCEnd for a _different_ GC cycle if timestamps are wildly broken.
900 func (o *ordering) advanceGCActive(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
901 seq := ev.args[0]
902 if gen == o.initialGen {
903 if o.gcState != gcUndetermined {
904 return curCtx, false, fmt.Errorf("GCActive in the first generation isn't first GC event")
905 }
906 o.gcSeq = seq
907 o.gcState = gcRunning
908 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
909 return curCtx, true, nil
910 }
911 if seq != o.gcSeq+1 {
912 // This is not the right GC cycle.
913 return curCtx, false, nil
914 }
915 if o.gcState != gcRunning {
916 return curCtx, false, fmt.Errorf("encountered GCActive while GC was not in progress")
917 }
918 o.gcSeq = seq
919 if err := validateCtx(curCtx, userGoReqs); err != nil {
920 return curCtx, false, err
921 }
922 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
923 return curCtx, true, nil
924 }
925
926 func (o *ordering) advanceGCBegin(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
927 seq := ev.args[0]
928 if o.gcState == gcUndetermined {
929 o.gcSeq = seq
930 o.gcState = gcRunning
931 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
932 return curCtx, true, nil
933 }
934 if seq != o.gcSeq+1 {
935 // This is not the right GC cycle.
936 return curCtx, false, nil
937 }
938 if o.gcState == gcRunning {
939 return curCtx, false, fmt.Errorf("encountered GCBegin while GC was already in progress")
940 }
941 o.gcSeq = seq
942 o.gcState = gcRunning
943 if err := validateCtx(curCtx, userGoReqs); err != nil {
944 return curCtx, false, err
945 }
946 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
947 return curCtx, true, nil
948 }
949
950 func (o *ordering) advanceGCEnd(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
951 seq := ev.args[0]
952 if seq != o.gcSeq+1 {
953 // This is not the right GC cycle.
954 return curCtx, false, nil
955 }
956 if o.gcState == gcNotRunning {
957 return curCtx, false, fmt.Errorf("encountered GCEnd when GC was not in progress")
958 }
959 if o.gcState == gcUndetermined {
960 return curCtx, false, fmt.Errorf("encountered GCEnd when GC was in an undetermined state")
961 }
962 o.gcSeq = seq
963 o.gcState = gcNotRunning
964 if err := validateCtx(curCtx, userGoReqs); err != nil {
965 return curCtx, false, err
966 }
967 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
968 return curCtx, true, nil
969 }
970
971 func (o *ordering) advanceAnnotation(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
972 // Handle simple instantaneous events that require a G.
973 if err := validateCtx(curCtx, userGoReqs); err != nil {
974 return curCtx, false, err
975 }
976 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
977 return curCtx, true, nil
978 }
979
980 func (o *ordering) advanceHeapMetric(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
981 // Handle allocation metrics, which don't require a G.
982 if err := validateCtx(curCtx, schedReqs{M: mustHave, P: mustHave, G: mayHave}); err != nil {
983 return curCtx, false, err
984 }
985 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
986 return curCtx, true, nil
987 }
988
989 func (o *ordering) advanceGCSweepBegin(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
990 // Handle sweep, which is bound to a P and doesn't require a G.
991 if err := validateCtx(curCtx, schedReqs{M: mustHave, P: mustHave, G: mayHave}); err != nil {
992 return curCtx, false, err
993 }
994 if err := o.pStates[curCtx.P].beginRange(makeRangeType(ev.typ, 0)); err != nil {
995 return curCtx, false, err
996 }
997 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
998 return curCtx, true, nil
999 }
1000
1001 func (o *ordering) advanceGCSweepActive(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
1002 pid := ProcID(ev.args[0])
1003 // N.B. In practice Ps can't block while they're sweeping, so this can only
1004 // ever reference curCtx.P. However, be lenient about this like we are with
1005 // GCMarkAssistActive; there's no reason the runtime couldn't change to block
1006 // in the middle of a sweep.
1007 pState, ok := o.pStates[pid]
1008 if !ok {
1009 return curCtx, false, fmt.Errorf("encountered GCSweepActive for unknown proc %d", pid)
1010 }
1011 if err := pState.activeRange(makeRangeType(ev.typ, 0), gen == o.initialGen); err != nil {
1012 return curCtx, false, err
1013 }
1014 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
1015 return curCtx, true, nil
1016 }
1017
1018 func (o *ordering) advanceGCSweepEnd(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
1019 if err := validateCtx(curCtx, schedReqs{M: mustHave, P: mustHave, G: mayHave}); err != nil {
1020 return curCtx, false, err
1021 }
1022 _, err := o.pStates[curCtx.P].endRange(ev.typ)
1023 if err != nil {
1024 return curCtx, false, err
1025 }
1026 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
1027 return curCtx, true, nil
1028 }
1029
1030 func (o *ordering) advanceGoRangeBegin(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
1031 // Handle special goroutine-bound event ranges.
1032 if err := validateCtx(curCtx, userGoReqs); err != nil {
1033 return curCtx, false, err
1034 }
1035 desc := stringID(0)
1036 if ev.typ == tracev2.EvSTWBegin {
1037 desc = stringID(ev.args[0])
1038 }
1039 gState, ok := o.gStates[curCtx.G]
1040 if !ok {
1041 return curCtx, false, fmt.Errorf("encountered event of type %d without known state for current goroutine %d", ev.typ, curCtx.G)
1042 }
1043 if err := gState.beginRange(makeRangeType(ev.typ, desc)); err != nil {
1044 return curCtx, false, err
1045 }
1046 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
1047 return curCtx, true, nil
1048 }
1049
1050 func (o *ordering) advanceGoRangeActive(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
1051 gid := GoID(ev.args[0])
1052 // N.B. Like GoStatus, this can happen at any time, because it can
1053 // reference a non-running goroutine. Don't check anything about the
1054 // current scheduler context.
1055 gState, ok := o.gStates[gid]
1056 if !ok {
1057 return curCtx, false, fmt.Errorf("uninitialized goroutine %d found during %s", gid, o.evName(ev.typ))
1058 }
1059 if err := gState.activeRange(makeRangeType(ev.typ, 0), gen == o.initialGen); err != nil {
1060 return curCtx, false, err
1061 }
1062 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
1063 return curCtx, true, nil
1064 }
1065
1066 func (o *ordering) advanceGoRangeEnd(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
1067 if err := validateCtx(curCtx, userGoReqs); err != nil {
1068 return curCtx, false, err
1069 }
1070 gState, ok := o.gStates[curCtx.G]
1071 if !ok {
1072 return curCtx, false, fmt.Errorf("encountered event of type %d without known state for current goroutine %d", ev.typ, curCtx.G)
1073 }
1074 desc, err := gState.endRange(ev.typ)
1075 if err != nil {
1076 return curCtx, false, err
1077 }
1078 if ev.typ == tracev2.EvSTWEnd {
1079 // Smuggle the kind into the event.
1080 // Don't use ev.extra here so we have symmetry with STWBegin.
1081 ev.args[0] = uint64(desc)
1082 }
1083 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
1084 return curCtx, true, nil
1085 }
1086
1087 func (o *ordering) advanceAllocFree(ev *baseEvent, evt *evTable, m ThreadID, gen uint64, curCtx schedCtx) (schedCtx, bool, error) {
1088 // Handle simple instantaneous events that may or may not have a P.
1089 if err := validateCtx(curCtx, schedReqs{M: mustHave, P: mayHave, G: mayHave}); err != nil {
1090 return curCtx, false, err
1091 }
1092 o.queue.push(Event{table: evt, ctx: curCtx, base: *ev})
1093 return curCtx, true, nil
1094 }
1095
1096 // Next returns the next event in the ordering.
1097 func (o *ordering) Next() (Event, bool) {
1098 return o.queue.pop()
1099 }
1100
1101 // schedCtx represents the scheduling resources associated with an event.
1102 type schedCtx struct {
1103 G GoID
1104 P ProcID
1105 M ThreadID
1106 }
1107
1108 // validateCtx ensures that ctx conforms to some reqs, returning an error if
1109 // it doesn't.
1110 func validateCtx(ctx schedCtx, reqs schedReqs) error {
1111 // Check thread requirements.
1112 if reqs.M == mustHave && ctx.M == NoThread {
1113 return fmt.Errorf("expected a thread but didn't have one")
1114 } else if reqs.M == mustNotHave && ctx.M != NoThread {
1115 return fmt.Errorf("expected no thread but had one")
1116 }
1117
1118 // Check proc requirements.
1119 if reqs.P == mustHave && ctx.P == NoProc {
1120 return fmt.Errorf("expected a proc but didn't have one")
1121 } else if reqs.P == mustNotHave && ctx.P != NoProc {
1122 return fmt.Errorf("expected no proc but had one")
1123 }
1124
1125 // Check goroutine requirements.
1126 if reqs.G == mustHave && ctx.G == NoGoroutine {
1127 return fmt.Errorf("expected a goroutine but didn't have one")
1128 } else if reqs.G == mustNotHave && ctx.G != NoGoroutine {
1129 return fmt.Errorf("expected no goroutine but had one")
1130 }
1131 return nil
1132 }
1133
1134 // gcState is a trinary variable for the current state of the GC.
1135 //
1136 // The third state besides "enabled" and "disabled" is "undetermined."
1137 type gcState uint8
1138
1139 const (
1140 gcUndetermined gcState = iota
1141 gcNotRunning
1142 gcRunning
1143 )
1144
1145 // String returns a human-readable string for the GC state.
1146 func (s gcState) String() string {
1147 switch s {
1148 case gcUndetermined:
1149 return "Undetermined"
1150 case gcNotRunning:
1151 return "NotRunning"
1152 case gcRunning:
1153 return "Running"
1154 }
1155 return "Bad"
1156 }
1157
1158 // userRegion represents a unique user region when attached to some gState.
1159 type userRegion struct {
1160 // name must be a resolved string because the string ID for the same
1161 // string may change across generations, but we care about checking
1162 // the value itself.
1163 taskID TaskID
1164 name string
1165 }
1166
1167 // rangeType is a way to classify special ranges of time.
1168 //
1169 // These typically correspond 1:1 with "Begin" events, but
1170 // they may have an optional subtype that describes the range
1171 // in more detail.
1172 type rangeType struct {
1173 typ tracev2.EventType // "Begin" event.
1174 desc stringID // Optional subtype.
1175 }
1176
1177 // makeRangeType constructs a new rangeType.
1178 func makeRangeType(typ tracev2.EventType, desc stringID) rangeType {
1179 if styp := tracev2.Specs()[typ].StartEv; styp != tracev2.EvNone {
1180 typ = styp
1181 }
1182 return rangeType{typ, desc}
1183 }
1184
1185 // gState is the state of a goroutine at a point in the trace.
1186 type gState struct {
1187 id GoID
1188 status tracev2.GoStatus
1189 seq seqCounter
1190
1191 // regions are the active user regions for this goroutine.
1192 regions []userRegion
1193
1194 // rangeState is the state of special time ranges bound to this goroutine.
1195 rangeState
1196 }
1197
1198 // beginRegion starts a user region on the goroutine.
1199 func (s *gState) beginRegion(r userRegion) error {
1200 s.regions = append(s.regions, r)
1201 return nil
1202 }
1203
1204 // endRegion ends a user region on the goroutine.
1205 func (s *gState) endRegion(r userRegion) error {
1206 if len(s.regions) == 0 {
1207 // We do not know about regions that began before tracing started.
1208 return nil
1209 }
1210 if next := s.regions[len(s.regions)-1]; next != r {
1211 return fmt.Errorf("misuse of region in goroutine %v: region end %v when the inner-most active region start event is %v", s.id, r, next)
1212 }
1213 s.regions = s.regions[:len(s.regions)-1]
1214 return nil
1215 }
1216
1217 // pState is the state of a proc at a point in the trace.
1218 type pState struct {
1219 id ProcID
1220 status tracev2.ProcStatus
1221 seq seqCounter
1222
1223 // rangeState is the state of special time ranges bound to this proc.
1224 rangeState
1225 }
1226
1227 // mState is the state of a thread at a point in the trace.
1228 type mState struct {
1229 g GoID // Goroutine bound to this M. (The goroutine's state is Executing.)
1230 p ProcID // Proc bound to this M. (The proc's state is Executing.)
1231 }
1232
1233 // rangeState represents the state of special time ranges.
1234 type rangeState struct {
1235 // inFlight contains the rangeTypes of any ranges bound to a resource.
1236 inFlight []rangeType
1237 }
1238
1239 // beginRange begins a special range in time on the goroutine.
1240 //
1241 // Returns an error if the range is already in progress.
1242 func (s *rangeState) beginRange(typ rangeType) error {
1243 if s.hasRange(typ) {
1244 return fmt.Errorf("discovered event already in-flight for when starting event %v", tracev2.Specs()[typ.typ].Name)
1245 }
1246 s.inFlight = append(s.inFlight, typ)
1247 return nil
1248 }
1249
1250 // activeRange marks special range in time on the goroutine as active in the
1251 // initial generation, or confirms that it is indeed active in later generations.
1252 func (s *rangeState) activeRange(typ rangeType, isInitialGen bool) error {
1253 if isInitialGen {
1254 if s.hasRange(typ) {
1255 return fmt.Errorf("found named active range already in first gen: %v", typ)
1256 }
1257 s.inFlight = append(s.inFlight, typ)
1258 } else if !s.hasRange(typ) {
1259 return fmt.Errorf("resource is missing active range: %v %v", tracev2.Specs()[typ.typ].Name, s.inFlight)
1260 }
1261 return nil
1262 }
1263
1264 // hasRange returns true if a special time range on the goroutine as in progress.
1265 func (s *rangeState) hasRange(typ rangeType) bool {
1266 return slices.Contains(s.inFlight, typ)
1267 }
1268
1269 // endRange ends a special range in time on the goroutine.
1270 //
1271 // This must line up with the start event type of the range the goroutine is currently in.
1272 func (s *rangeState) endRange(typ tracev2.EventType) (stringID, error) {
1273 st := tracev2.Specs()[typ].StartEv
1274 idx := -1
1275 for i, r := range s.inFlight {
1276 if r.typ == st {
1277 idx = i
1278 break
1279 }
1280 }
1281 if idx < 0 {
1282 return 0, fmt.Errorf("tried to end event %v, but not in-flight", tracev2.Specs()[st].Name)
1283 }
1284 // Swap remove.
1285 desc := s.inFlight[idx].desc
1286 s.inFlight[idx], s.inFlight[len(s.inFlight)-1] = s.inFlight[len(s.inFlight)-1], s.inFlight[idx]
1287 s.inFlight = s.inFlight[:len(s.inFlight)-1]
1288 return desc, nil
1289 }
1290
1291 // seqCounter represents a global sequence counter for a resource.
1292 type seqCounter struct {
1293 gen uint64 // The generation for the local sequence counter seq.
1294 seq uint64 // The sequence number local to the generation.
1295 }
1296
1297 // makeSeq creates a new seqCounter.
1298 func makeSeq(gen, seq uint64) seqCounter {
1299 return seqCounter{gen: gen, seq: seq}
1300 }
1301
1302 // succeeds returns true if a is the immediate successor of b.
1303 func (a seqCounter) succeeds(b seqCounter) bool {
1304 return a.gen == b.gen && a.seq == b.seq+1
1305 }
1306
1307 // String returns a debug string representation of the seqCounter.
1308 func (c seqCounter) String() string {
1309 return fmt.Sprintf("%d (gen=%d)", c.seq, c.gen)
1310 }
1311
1312 func dumpOrdering(order *ordering) string {
1313 var sb strings.Builder
1314 for id, state := range order.gStates {
1315 fmt.Fprintf(&sb, "G %d [status=%s seq=%s]\n", id, state.status, state.seq)
1316 }
1317 fmt.Fprintln(&sb)
1318 for id, state := range order.pStates {
1319 fmt.Fprintf(&sb, "P %d [status=%s seq=%s]\n", id, state.status, state.seq)
1320 }
1321 fmt.Fprintln(&sb)
1322 for id, state := range order.mStates {
1323 fmt.Fprintf(&sb, "M %d [g=%d p=%d]\n", id, state.g, state.p)
1324 }
1325 fmt.Fprintln(&sb)
1326 fmt.Fprintf(&sb, "GC %d %s\n", order.gcSeq, order.gcState)
1327 return sb.String()
1328 }
1329
1330 // taskState represents an active task.
1331 type taskState struct {
1332 // name is the type of the active task.
1333 name string
1334
1335 // parentID is the parent ID of the active task.
1336 parentID TaskID
1337 }
1338
1339 // queue implements a growable ring buffer with a queue API.
1340 type queue[T any] struct {
1341 start, end int
1342 buf []T
1343 }
1344
1345 // push adds a new event to the back of the queue.
1346 func (q *queue[T]) push(value T) {
1347 if q.end-q.start == len(q.buf) {
1348 q.grow()
1349 }
1350 q.buf[q.end%len(q.buf)] = value
1351 q.end++
1352 }
1353
1354 // grow increases the size of the queue.
1355 func (q *queue[T]) grow() {
1356 if len(q.buf) == 0 {
1357 q.buf = make([]T, 2)
1358 return
1359 }
1360
1361 // Create new buf and copy data over.
1362 newBuf := make([]T, len(q.buf)*2)
1363 pivot := q.start % len(q.buf)
1364 first, last := q.buf[pivot:], q.buf[:pivot]
1365 copy(newBuf[:len(first)], first)
1366 copy(newBuf[len(first):], last)
1367
1368 // Update the queue state.
1369 q.start = 0
1370 q.end = len(q.buf)
1371 q.buf = newBuf
1372 }
1373
1374 // pop removes an event from the front of the queue. If the
1375 // queue is empty, it returns an EventBad event.
1376 func (q *queue[T]) pop() (T, bool) {
1377 if q.end-q.start == 0 {
1378 return *new(T), false
1379 }
1380 elem := &q.buf[q.start%len(q.buf)]
1381 value := *elem
1382 *elem = *new(T) // Clear the entry before returning, so we don't hold onto old tables.
1383 q.start++
1384 return value, true
1385 }
1386
1387 // makeEvent creates an Event from the provided information.
1388 //
1389 // It's just a convenience function; it's always OK to construct
1390 // an Event manually if this isn't quite the right way to express
1391 // the contents of the event.
1392 func makeEvent(table *evTable, ctx schedCtx, typ tracev2.EventType, time Time, args ...uint64) Event {
1393 ev := Event{
1394 table: table,
1395 ctx: ctx,
1396 base: baseEvent{
1397 typ: typ,
1398 time: time,
1399 },
1400 }
1401 copy(ev.base.args[:], args)
1402 return ev
1403 }
1404
1405 // schedReqs is a set of constraints on what the scheduling
1406 // context must look like.
1407 type schedReqs struct {
1408 M constraint
1409 P constraint
1410 G constraint
1411 }
1412
1413 // constraint represents a various presence requirements.
1414 type constraint uint8
1415
1416 const (
1417 mustNotHave constraint = iota
1418 mayHave
1419 mustHave
1420 )
1421
1422 // userGoReqs is a common requirement among events that are running
1423 // or are close to running user code.
1424 var userGoReqs = schedReqs{M: mustHave, P: mustHave, G: mustHave}