// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Trace event writing API for trace2runtime.go.

package runtime

import (
	
	
)

// Event types in the trace, args are given in square brackets.
//
// Naming scheme:
//   - Time range event pairs have suffixes "Begin" and "End".
//   - "Start", "Stop", "Create", "Destroy", "Block", "Unblock"
//     are suffixes reserved for scheduling resources.
//
// NOTE: If you add an event type, make sure you also update all
// tables in this file!
type traceEv uint8

const (
	traceEvNone traceEv = iota // unused

	// Structural events.
	traceEvEventBatch // start of per-M batch of events [generation, M ID, timestamp, batch length]
	traceEvStacks     // start of a section of the stack table [...traceEvStack]
	traceEvStack      // stack table entry [ID, ...{PC, func string ID, file string ID, line #}]
	traceEvStrings    // start of a section of the string dictionary [...traceEvString]
	traceEvString     // string dictionary entry [ID, length, string]
	traceEvCPUSamples // start of a section of CPU samples [...traceEvCPUSample]
	traceEvCPUSample  // CPU profiling sample [timestamp, M ID, P ID, goroutine ID, stack ID]
	traceEvFrequency  // timestamp units per sec [freq]

	// Procs.
	traceEvProcsChange // current value of GOMAXPROCS [timestamp, GOMAXPROCS, stack ID]
	traceEvProcStart   // start of P [timestamp, P ID, P seq]
	traceEvProcStop    // stop of P [timestamp]
	traceEvProcSteal   // P was stolen [timestamp, P ID, P seq, M ID]
	traceEvProcStatus  // P status at the start of a generation [timestamp, P ID, status]

	// Goroutines.
	traceEvGoCreate            // goroutine creation [timestamp, new goroutine ID, new stack ID, stack ID]
	traceEvGoCreateSyscall     // goroutine appears in syscall (cgo callback) [timestamp, new goroutine ID]
	traceEvGoStart             // goroutine starts running [timestamp, goroutine ID, goroutine seq]
	traceEvGoDestroy           // goroutine ends [timestamp]
	traceEvGoDestroySyscall    // goroutine ends in syscall (cgo callback) [timestamp]
	traceEvGoStop              // goroutine yields its time, but is runnable [timestamp, reason, stack ID]
	traceEvGoBlock             // goroutine blocks [timestamp, reason, stack ID]
	traceEvGoUnblock           // goroutine is unblocked [timestamp, goroutine ID, goroutine seq, stack ID]
	traceEvGoSyscallBegin      // syscall enter [timestamp, P seq, stack ID]
	traceEvGoSyscallEnd        // syscall exit [timestamp]
	traceEvGoSyscallEndBlocked // syscall exit and it blocked at some point [timestamp]
	traceEvGoStatus            // goroutine status at the start of a generation [timestamp, goroutine ID, M ID, status]

	// STW.
	traceEvSTWBegin // STW start [timestamp, kind]
	traceEvSTWEnd   // STW done [timestamp]

	// GC events.
	traceEvGCActive           // GC active [timestamp, seq]
	traceEvGCBegin            // GC start [timestamp, seq, stack ID]
	traceEvGCEnd              // GC done [timestamp, seq]
	traceEvGCSweepActive      // GC sweep active [timestamp, P ID]
	traceEvGCSweepBegin       // GC sweep start [timestamp, stack ID]
	traceEvGCSweepEnd         // GC sweep done [timestamp, swept bytes, reclaimed bytes]
	traceEvGCMarkAssistActive // GC mark assist active [timestamp, goroutine ID]
	traceEvGCMarkAssistBegin  // GC mark assist start [timestamp, stack ID]
	traceEvGCMarkAssistEnd    // GC mark assist done [timestamp]
	traceEvHeapAlloc          // gcController.heapLive change [timestamp, heap alloc in bytes]
	traceEvHeapGoal           // gcController.heapGoal() change [timestamp, heap goal in bytes]

	// Annotations.
	traceEvGoLabel         // apply string label to current running goroutine [timestamp, label string ID]
	traceEvUserTaskBegin   // trace.NewTask [timestamp, internal task ID, internal parent task ID, name string ID, stack ID]
	traceEvUserTaskEnd     // end of a task [timestamp, internal task ID, stack ID]
	traceEvUserRegionBegin // trace.{Start,With}Region [timestamp, internal task ID, name string ID, stack ID]
	traceEvUserRegionEnd   // trace.{End,With}Region [timestamp, internal task ID, name string ID, stack ID]
	traceEvUserLog         // trace.Log [timestamp, internal task ID, key string ID, stack, value string ID]

	// Coroutines.
	traceEvGoSwitch        // goroutine switch (coroswitch) [timestamp, goroutine ID, goroutine seq]
	traceEvGoSwitchDestroy // goroutine switch and destroy [timestamp, goroutine ID, goroutine seq]
	traceEvGoCreateBlocked // goroutine creation (starts blocked) [timestamp, new goroutine ID, new stack ID, stack ID]

	// GoStatus with stack.
	traceEvGoStatusStack // goroutine status at the start of a generation, with a stack [timestamp, goroutine ID, M ID, status, stack ID]

	// Batch event for an experimental batch with a custom format.
	traceEvExperimentalBatch // start of extra data [experiment ID, generation, M ID, timestamp, batch length, batch data...]
)

// traceArg is a simple wrapper type to help ensure that arguments passed
// to traces are well-formed.
type traceArg uint64

// traceEventWriter is the high-level API for writing trace events.
//
// See the comment on traceWriter about style for more details as to why
// this type and its methods are structured the way they are.
type traceEventWriter struct {
	w traceWriter
}

// eventWriter creates a new traceEventWriter. It is the main entrypoint for writing trace events.
//
// Before creating the event writer, this method will emit a status for the current goroutine
// or proc if it exists, and if it hasn't had its status emitted yet. goStatus and procStatus indicate
// what the status of goroutine or P should be immediately *before* the events that are about to
// be written using the eventWriter (if they exist). No status will be written if there's no active
// goroutine or P.
//
// Callers can elect to pass a constant value here if the status is clear (e.g. a goroutine must have
// been Runnable before a GoStart). Otherwise, callers can query the status of either the goroutine
// or P and pass the appropriate status.
//
// In this case, the default status should be traceGoBad or traceProcBad to help identify bugs sooner.
func ( traceLocker) ( traceGoStatus,  traceProcStatus) traceEventWriter {
	 := .writer()
	if  := .mp.p.ptr();  != nil && !.trace.statusWasTraced(.gen) && .trace.acquireStatus(.gen) {
		 = .writeProcStatus(uint64(.id), , .trace.inSweep)
	}
	if  := .mp.curg;  != nil && !.trace.statusWasTraced(.gen) && .trace.acquireStatus(.gen) {
		 = .writeGoStatus(uint64(.goid), int64(.mp.procid), , .inMarkAssist, 0 /* no stack */)
	}
	return traceEventWriter{}
}

// commit writes out a trace event and calls end. It's a helper to make the
// common case of writing out a single event less error-prone.
func ( traceEventWriter) ( traceEv,  ...traceArg) {
	 = .write(, ...)
	.end()
}

// write writes an event into the trace.
func ( traceEventWriter) ( traceEv,  ...traceArg) traceEventWriter {
	.w = .w.event(, ...)
	return 
}

// end finishes writing to the trace. The traceEventWriter must not be used after this call.
func ( traceEventWriter) () {
	.w.end()
}

// traceEventWrite is the part of traceEvent that actually writes the event.
func ( traceWriter) ( traceEv,  ...traceArg) traceWriter {
	// Make sure we have room.
	, _ = .ensure(1 + (len()+1)*traceBytesPerNumber)

	// Compute the timestamp diff that we'll put in the trace.
	 := traceClockNow()
	if  <= .traceBuf.lastTime {
		 = .traceBuf.lastTime + 1
	}
	 := uint64( - .traceBuf.lastTime)
	.traceBuf.lastTime = 

	// Write out event.
	.byte(byte())
	.varint()
	for ,  := range  {
		.varint(uint64())
	}
	return 
}

// stack takes a stack trace skipping the provided number of frames.
// It then returns a traceArg representing that stack which may be
// passed to write.
func ( traceLocker) ( int) traceArg {
	return traceArg(traceStack(, nil, .gen))
}

// startPC takes a start PC for a goroutine and produces a unique
// stack ID for it.
//
// It then returns a traceArg representing that stack which may be
// passed to write.
func ( traceLocker) ( uintptr) traceArg {
	// +PCQuantum because makeTraceFrame expects return PCs and subtracts PCQuantum.
	return traceArg(trace.stackTab[.gen%2].put([]uintptr{
		logicalStackSentinel,
		startPCForTrace() + sys.PCQuantum,
	}))
}

// string returns a traceArg representing s which may be passed to write.
// The string is assumed to be relatively short and popular, so it may be
// stored for a while in the string dictionary.
func ( traceLocker) ( string) traceArg {
	return traceArg(trace.stringTab[.gen%2].put(.gen, ))
}

// uniqueString returns a traceArg representing s which may be passed to write.
// The string is assumed to be unique or long, so it will be written out to
// the trace eagerly.
func ( traceLocker) ( string) traceArg {
	return traceArg(trace.stringTab[.gen%2].emit(.gen, ))
}

// rtype returns a traceArg representing typ which may be passed to write.
func ( traceLocker) ( *abi.Type) traceArg {
	return traceArg(trace.typeTab[.gen%2].put())
}