Documentation
¶
Overview ¶
Package bpf provides host eBPF policy budgets, device-side BPF launch records, and host-GPU trace collection.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
p := bpf.Program{Version: 1, Registers: 2, Slots: 1, Code: []bpf.Instruction{
{Op: bpf.Const, Dst: 1, Imm: 1},
{Op: bpf.MapAdd, B: 1},
{Op: bpf.Exit},
}}
b := bpf.DevBudget{MaxInstructions: 10, MaxSteps: 10, MaxRegisters: 4, MaxSlots: 1}
r, err := bpf.Evaluate(context.Background(), p, b, 0xff)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(r.Map, r.Steps)
}
Output: [1] 3
Index ¶
- Constants
- Variables
- func Arguments(symbol string) (slots int, layer string, ok bool)
- func Assemble(t Translation) (*nvjitlink.Result, error)
- func CheckBudget(threads, symbols int) error
- func CheckGoLayouts() error
- func CheckLayouts(p0 re_obsbpfpolicy.BTF) ([]string, error)
- func CompareOutputs(graph *cudair.Graph, inputs, original, instrumented map[string][]float32, ...) error
- func DefaultLimits() re_obsbpfpolicy.Limits
- func DefaultSymbols(layer string) []string
- func Discover(p0 context.Context, p1 re_obsbpfpolicy.Loader) (*re_obsbpfpolicy.Report, error)
- func GoLayouts() []re_obsbpfpolicy.TypeLayout
- func InventoryLayouts() []re_obsbpfpolicy.TypeLayout
- func MemOpsMembers() []string
- func NewBridge(p0 re_obsbpfpolicy.Loader, p1 re_obsbpfpolicy.Kfuncs, ...) *re_obsbpfpolicy.Bridge
- func NewBudget(p0 int) *re_obsbpfpolicy.PolicyBudget
- func NewPrefetchWorker(p0 re_obsbpfpolicy.Kfuncs, p1 int, p2 func() time.Time) *re_obsbpfpolicy.PrefetchWorker
- func SchedOpsMembers() []string
- func SymbolBudget(threads int) int
- func SymbolSet(layer, name string) []string
- func ThreadBudget(symbols int) int
- func UnmeasuredTimings() re_obsbpfpolicy.Timings
- type Analysis
- type ArtifactSource
- type BTF
- type BindContext
- type BindDecision
- type BlockState
- type Bridge
- type BudgetError
- type CallInterval
- type Capabilities
- type Collector
- type Correlator
- type Counters
- type Destination
- type DevBudget
- type DevResult
- type Execution
- type FieldLayout
- type Geometry
- type HolderPolicy
- type HookStatus
- type Injection
- type InjectionPolicy
- type Instruction
- type InterleaveLevel
- type InterpositionDeclaration
- type InvocationObservation
- type InvocationReader
- type KernelIdentity
- type KfuncAbsentError
- type KfuncSignature
- type KfuncStatus
- type Kfuncs
- type Launch
- type LaunchSource
- type LayoutMismatch
- type Limits
- type Link
- type LoadedInjection
- func (l *LoadedInjection) Close() error
- func (l *LoadedInjection) Launch(ctx context.Context, args ...any) error
- func (l *LoadedInjection) ObservationReader() InvocationReader
- func (l *LoadedInjection) Record() (iket.Record, error)
- func (l *LoadedInjection) Selection() (Selection, error)
- func (l *LoadedInjection) Snapshot() (MapSnapshot, bool)
- type Loader
- type Manifest
- type MapSnapshot
- type MemoryPolicy
- type NumericalPolicy
- type Object
- type ObjectSpec
- type Observation
- type Observer
- type Op
- type Outcome
- type PMMDecision
- type PMMRequest
- type PMMSnapshot
- type PolicyBudget
- type PolicyConfig
- type Position
- type PrefetchDecision
- type PrefetchRequest
- type PrefetchResult
- type PrefetchWorker
- type Program
- type ProgramSpec
- type RecordSink
- type Region
- type Reorder
- type Report
- type SchedAttributes
- type SchedPolicy
- type SchedulerEvent
- type Selection
- type SinkObserver
- type Snapshot
- type SnapshotCoverage
- type StopStats
- type StructOpsSpec
- type Target
- type TaskDestroyContext
- type TaskInitContext
- type ThreadRescan
- type ThreadSnapshot
- type TimesliceControlContext
- type Timings
- type TraceHostConfig
- type TraceHostResult
- type Translation
- type TypeAbsentError
- type TypeLayout
- type TypeStatus
- type VerifyError
Examples ¶
- Package
- ArtifactSource.DescribeLaunch
- ArtifactSource.Load
- Assemble
- CheckBudget
- CompareOutputs
- DefaultSymbols
- Execute
- Execution.Close
- Execution.Record
- Execution.Snapshot
- Injection.Load
- InterpositionDeclaration
- InvocationObservation.SameInvocation
- InvocationReader.ReadObservation
- LoadedInjection.Close
- LoadedInjection.Launch
- LoadedInjection.ObservationReader
- LoadedInjection.Record
- LoadedInjection.Selection
- LoadedInjection.Snapshot
- NewArtifactSource
- Parse
- ParseScheduler
- PrepareInjection
- PrepareInjection (Stub)
- SnapshotCoverage
- SymbolSet
- ThreadRescan
- ThreadSnapshot
- TraceHostConfig (ThreadRescan)
- Translate
- Verify
Constants ¶
const ( SelectAll = "all" // every thread in the snapshot SelectExplicit = "explicit" // threads listed by Config.Threads SelectObserved = "observed_calls" // threads seen calling a probed symbol )
Thread selection values recorded in SnapshotCoverage.Selection.
const BindRejection = re_obsbpfpolicy.BindRejection
const DestinationUnset = re_obsbpfpolicy.DestinationUnset
const DestinationUnused = re_obsbpfpolicy.DestinationUnused
const DestinationUsed = re_obsbpfpolicy.DestinationUsed
const EngineCopy = re_obsbpfpolicy.EngineCopy
const EngineGraphics = re_obsbpfpolicy.EngineGraphics
const EngineNVDEC = re_obsbpfpolicy.EngineNVDEC
const EngineNVENC = re_obsbpfpolicy.EngineNVENC
const EngineNVJPEG = re_obsbpfpolicy.EngineNVJPEG
const InterleaveHigh = re_obsbpfpolicy.InterleaveHigh
const InterleaveLow = re_obsbpfpolicy.InterleaveLow
const InterleaveMedium = re_obsbpfpolicy.InterleaveMedium
const MemOpsTable = re_obsbpfpolicy.MemOpsTable
const PositionHead = re_obsbpfpolicy.PositionHead
const PositionTail = re_obsbpfpolicy.PositionTail
const PositionUnset = re_obsbpfpolicy.PositionUnset
const SchedOpsTable = re_obsbpfpolicy.SchedOpsTable
const Unmeasured = re_obsbpfpolicy.Unmeasured
Variables ¶
var ErrBudgetExceeded = re_obsbpfpolicy.ErrBudgetExceeded
var ErrDisabled = re_obsbpfpolicy.ErrDisabled
var ErrNoBTF = re_obsbpfpolicy.ErrNoBTF
var ErrNotAttached = re_obsbpfpolicy.ErrNotAttached
var ErrOutOfRange = re_obsbpfpolicy.ErrOutOfRange
Functions ¶
func Arguments ¶
Arguments reports the number of ABI argument slots collected for symbol and its API layer, "driver" or "runtime". It reports ok false for a symbol the collector does not support.
func Assemble ¶
func Assemble(t Translation) (*nvjitlink.Result, error)
Assemble links translated PTX to CUBIN using nvJitLink, never NVRTC. It does not load or launch the output. A result accompanying an error may own native cleanup and must be closed according to nvjitlinkx.Result's contract.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
// An unverified or missing translation must never reach the native linker.
_, err := bpf.Assemble(bpf.Translation{})
fmt.Println(err != nil)
}
Output: true
func CheckBudget ¶
CheckBudget reports a *BudgetError when probing symbols symbols on threads threads exceeds the BPF attachment bound.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
// A Go server with 40 threads cannot take the 8-symbol default set.
fmt.Println(bpf.CheckBudget(40, 8))
fmt.Println(bpf.CheckBudget(40, bpf.SymbolBudget(40)))
}
Output: cudatracehost: 40 threads x 8 symbols x 2 probes = 640 attachments exceeds 256; 16 threads fit 8 symbols, 3 symbols fit 40 threads; select threads or probe fewer symbols <nil>
func CheckGoLayouts ¶
func CheckGoLayouts() error
func CheckLayouts ¶
func CheckLayouts(p0 re_obsbpfpolicy.BTF) ([]string, error)
func CompareOutputs ¶
func CompareOutputs(graph *cudair.Graph, inputs, original, instrumented map[string][]float32, policy NumericalPolicy) error
CompareOutputs evaluates graph with cudaref and compares both original and instrumented outputs to that independent reference, then to each other. Output names and lengths must match exactly. Only float32 graphs are accepted. The first mismatch is returned in sorted output-name order, with its pair and element index. Graph and buffers must not be mutated concurrently.
The caller must supply completed readbacks for the same inputs and identify the original and instrumented artifacts in its qualification receipt. This function establishes numerical agreement of supplied buffers, not that either kernel ran, that injection occurred, or that instrumentation overhead is small.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/graph"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
g := graph.NewGraph()
x := g.AddInput("x", []int{2}, graph.Float32)
y := g.AddUnary("neg", x)
if err := g.SetOutputs(y); err != nil {
fmt.Println(err)
return
}
inputs := map[string][]float32{"x": {1, -2}}
// Synthetic buffers illustrate comparison, not native qualification.
original := map[string][]float32{y.Name: {-1, 2}}
instrumented := map[string][]float32{y.Name: {-1, 2}}
err := bpf.CompareOutputs(g, inputs, original, instrumented, bpf.NumericalPolicy{Mode: "exact"})
fmt.Println(err)
}
Output: <nil>
func DefaultLimits ¶
func DefaultLimits() re_obsbpfpolicy.Limits
func DefaultSymbols ¶
DefaultSymbols returns the default probe symbols for layer, "driver" or "runtime", or nil for another layer. Both sets include graph launch, so a step replayed from a CUDA graph shows its submission.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
syms := bpf.DefaultSymbols("driver")
fmt.Println(syms)
fmt.Println(bpf.ThreadBudget(len(syms)), "threads")
}
Output: [cuLaunchKernel cuLaunchKernelEx cuGraphLaunch cuMemcpyHtoDAsync_v2 cuMemcpyDtoHAsync_v2 cuStreamSynchronize cuCtxSynchronize cuEventRecord] 16 threads
func Discover ¶
func Discover(p0 context.Context, p1 re_obsbpfpolicy.Loader) (*re_obsbpfpolicy.Report, error)
func GoLayouts ¶
func GoLayouts() []re_obsbpfpolicy.TypeLayout
func InventoryLayouts ¶
func InventoryLayouts() []re_obsbpfpolicy.TypeLayout
func MemOpsMembers ¶
func MemOpsMembers() []string
func NewBridge ¶
func NewBridge(p0 re_obsbpfpolicy.Loader, p1 re_obsbpfpolicy.Kfuncs, p2 re_obsbpfpolicy.PolicyConfig) *re_obsbpfpolicy.Bridge
func NewBudget ¶
func NewBudget(p0 int) *re_obsbpfpolicy.PolicyBudget
func NewPrefetchWorker ¶
func NewPrefetchWorker(p0 re_obsbpfpolicy.Kfuncs, p1 int, p2 func() time.Time) *re_obsbpfpolicy.PrefetchWorker
func SchedOpsMembers ¶
func SchedOpsMembers() []string
func SymbolBudget ¶
SymbolBudget returns the largest number of symbols the BPF backend can probe on threads threads. It is the inverse of ThreadBudget.
func SymbolSet ¶
SymbolSet returns the named probe set for layer, or nil if there is none. The sets are "serving" (the default), "launch-sync" (kernel and graph launch with synchronization) and "graph-sync" (graph launch and synchronization only). A smaller set fits more threads; see ThreadBudget.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
syms := bpf.SymbolSet("driver", "graph-sync")
fmt.Println(syms, bpf.ThreadBudget(len(syms)), "threads")
}
Output: [cuGraphLaunch cuStreamSynchronize cuCtxSynchronize] 42 threads
func ThreadBudget ¶
ThreadBudget returns the largest thread snapshot the BPF backend can attach when probing symbols functions. Each function needs an entry and a return probe on every thread, and a group holds at most 256 attachments. Open refuses a larger snapshot before attaching; select threads with Config.Threads or Config.SelectWindow, or probe a smaller SymbolSet.
func UnmeasuredTimings ¶
func UnmeasuredTimings() re_obsbpfpolicy.Timings
Types ¶
type Analysis ¶
Analysis reports the conservative instruction and register bounds. Registers includes declared virtual registers and one loop counter per Repeat. It is not a native compiler's register count or an occupancy estimate.
func Verify ¶
Verify checks the instruction contract, single-entry loop structure, resource bounds and warp uniformity at a control-flow fixed point. It rejects unreachable instructions and reports the instruction that violates a rule.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
p := bpf.Program{Version: 1, Registers: 1, Slots: 1, Code: []bpf.Instruction{{Op: bpf.Exit}}}
a, err := bpf.Verify(p, bpf.DevBudget{MaxInstructions: 1, MaxSteps: 1, MaxRegisters: 1, MaxSlots: 1})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(a.MaxSteps, a.Registers)
}
Output: 1 1
type ArtifactSource ¶
type ArtifactSource struct {
// contains filtered or unexported fields
}
ArtifactSource supplies a directly loaded cudakernel artifact, without an interposition shim. Its zero value is invalid. Construct it with NewArtifactSource; descriptions do not share mutable storage with the source.
func NewArtifactSource ¶
func NewArtifactSource(artifact *kernel.Artifact, geometry Geometry) (*ArtifactSource, error)
NewArtifactSource copies and validates artifact and geometry. This is a host check, not proof that the driver accepts the image or launch configuration. Only PTX and CUBIN can be loaded through this source; LTOIR must first be linked.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
ptx := []byte(".version 9.0\n.target sm_121a\n.address_size 64\n.visible .entry noop() { ret; }\n")
a, err := kernel.NewArtifact(kernel.KindPTX, ptx, "noop", kernel.Schema{}, "sm_121a")
if err != nil {
fmt.Println(err)
return
}
s, err := bpf.NewArtifactSource(a, bpf.Geometry{
Grid: [3]uint32{1, 1, 1}, Block: [3]uint32{32, 1, 1},
})
if err != nil {
fmt.Println(err)
return
}
launch, err := s.DescribeLaunch()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(launch.Artifact.EntryPoint(), launch.Geometry.Block)
}
Output: noop [32 1 1]
func (*ArtifactSource) DescribeLaunch ¶
func (s *ArtifactSource) DescribeLaunch() (Launch, error)
DescribeLaunch returns a detached copy of the original launch description.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
var source bpf.ArtifactSource
_, err := source.DescribeLaunch()
fmt.Println(err)
}
Output: cudabpfdev: uninitialized artifact source
func (*ArtifactSource) Load ¶
Load loads the original image unchanged, apart from the PTX NUL terminator required by the driver. It performs no instrumentation or launch. The driver checks device compatibility. Keep dev open throughout this call and until the module is unloaded or successfully transferred to cuda.OwnModule.
A nonzero module belongs to the caller even when an error is returned, for example when restoring the previous context fails after a successful load. Unload it with dev's context current. Never discard a nonzero error result.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
// A device must be explicitly supplied; Load does not select a GPU.
var source bpf.ArtifactSource
_, err := source.Load(nil)
fmt.Println(err)
}
Output: cudabpfdev: nil device
type BTF ¶
type BTF = re_obsbpfpolicy.BTF
type BindContext ¶
type BindContext = re_obsbpfpolicy.BindContext
type BindDecision ¶
type BindDecision = re_obsbpfpolicy.BindDecision
type BlockState ¶
type BlockState = re_obsbpfpolicy.BlockState
type Bridge ¶
type Bridge = re_obsbpfpolicy.Bridge
type BudgetError ¶
type BudgetError struct {
Threads, Symbols int
}
A BudgetError reports a BPF probe set that does not fit the group's attachment bound. Each symbol needs an entry and a return probe on every probed thread. It is returned before any probe is attached.
func (*BudgetError) Attachments ¶
func (e *BudgetError) Attachments() int
Attachments returns the attachment count the probe set needs.
func (*BudgetError) Error ¶
func (e *BudgetError) Error() string
type CallInterval ¶
type CallInterval struct {
ExecID uint64
ThreadGenerationKnown bool
ThreadGeneration uint64
PairingStatus string
TID uint32
EntryTimestamp, ReturnTimestamp uint64
Clock, Epoch string
Process obsprobe.Process
}
CallInterval is observed host API entry-to-return timing. It is not device execution time and does not imply application request identity.
type Capabilities ¶
type Capabilities = re_obsbpfpolicy.Capabilities
type Collector ¶
type Collector struct {
// contains filtered or unexported fields
}
Collector owns probe lifetime and bounded host-call correlation. It exposes raw scheduler events without claiming an exact request/goroutine join.
func Open ¶
func Open(cfg TraceHostConfig) (*Collector, error)
Open resolves and attaches entry/return probes. Permission, missing symbols, unsupported signatures and tracefs failures return errors without fallback.
func (*Collector) Close ¶
Close detaches owned probes. Missing return and pre-attachment history remain incomplete; Close never converts cancellation into successful completion.
func (*Collector) Next ¶
func (c *Collector) Next(ctx context.Context) (result TraceHostResult, err error)
Next returns the next raw event and optional completed call. Unknown transport or return pairing marks the capture incomplete and returns the original line.
func (*Collector) StopAndStats ¶
type Correlator ¶
type Correlator struct {
Incomplete bool
// contains filtered or unexported fields
}
Correlator pairs entry/return events by observed TID and nested call order. It bounds outstanding calls and never pairs a return across an observation gap. AddressSpace remains zero unless independently supplied by the caller.
func NewCorrelator ¶
func NewCorrelator(targets []Target, maxPending int) (*Correlator, error)
func (*Correlator) Gap ¶
func (c *Correlator) Gap()
Gap invalidates outstanding entry evidence. Lost observations cannot bridge an exact host call. Sequence advances so downstream trackers observe a gap.
func (*Correlator) Observe ¶
func (c *Correlator) Observe(o Observation) (*obsprobe.ProbeCapture, error)
Observe returns a completed capture when a matching return arrives. Raw entry and return lines should also be retained by the consumer independently.
type Counters ¶
type Counters = re_obsbpfpolicy.Counters
type Destination ¶
type Destination = re_obsbpfpolicy.Destination
type DevBudget ¶
Budget bounds verifier work and the declared instrumentation resources. MaxSteps bounds dynamic bytecode steps per warp, including loop repetition. Registers and shared bytes here are explicit caller allowances, not hardware facts or compiler allocation measurements. Injection must additionally check the target's measured limits and the compiler's final resource report.
type DevResult ¶
Result is the host interpreter's snapshot at program exit. Values holds each active lane's returned value. Map holds this invocation's counters, updated once per active warp. Misses counts out-of-range map keys without writing. Steps counts warp instruction steps, not GPU cycles or lane instructions.
func Evaluate ¶
Evaluate interprets a verified program for one active warp as a host oracle. Registers and map counters are private to each call. The result is published only at exit; cancellation or verification failure returns no snapshot. An empty active mask performs no instructions or side effects. This is not a GPU execution path and supplies no performance or injection qualification.
type Execution ¶
type Execution struct {
// contains filtered or unexported fields
}
Execution owns one invocation's module, stream and buffers. It must not be copied. Close every non-nil Execution returned by Execute, including on error, before closing its device. Failed cleanup retains resources for retry.
func Execute ¶
func Execute(ctx context.Context, dev *cuda.Device, t Translation, active uint32) (*Execution, error)
Execute assembles a translation with nvJitLink and runs its one-warp oracle kernel on dev. It allocates and zeroes private map, result and miss buffers, launches on a private nonblocking stream, waits for that stream, then copies the result. It does not inject into another kernel. The driver checks native target compatibility. This runner limits maps to 1048576 slots. Before allocating invocation buffers, it queries compiled function resources and rejects register/shared-memory budget overruns, any local memory (including spills), or a thread limit below 32. Declaration counts are not substituted for these loaded-function attributes.
Cancellation is checked between native calls; it cannot interrupt compilation or a running kernel. Cancellation never permits freeing in-flight storage. A snapshot is unavailable after any execution error, including readback or context restoration failure. A non-nil result must always be closed.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
// Native execution requires an explicit device; this host-only example
// exercises refusal before any linker or CUDA call.
_, err := bpf.Execute(context.Background(), nil, bpf.Translation{}, 0xff)
fmt.Println(err)
}
Output: cudabpfdev: nil device
func (*Execution) Close ¶
Close waits for any possibly submitted work before releasing device memory. It is repeatable and safe concurrently with Snapshot and other Close calls. A failed wait releases nothing; successful frees are recorded immediately, even if restoring the previous context subsequently fails.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
// Every non-nil Execute result must be closed, including error results.
var execution *bpf.Execution
fmt.Println(execution.Close())
}
Output: <nil>
func (*Execution) Record ¶
Record describes successful snapshot publication for the flight recorder. Call Recorder.Push with its result after Execute returns. Failed execution has no completed snapshot record, even if subsequent cleanup succeeds.
TimestampNs is the host's snapshot-publication time, after synchronization, readback and context restoration. GPU duration and CUPTI correlation are unavailable. Labels identify the loaded image and summarize the snapshot; the full values remain available from Snapshot. Each call returns new labels.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
var execution bpf.Execution
_, err := execution.Record()
fmt.Println(err)
}
Output: cudabpfdev: no completed snapshot
func (*Execution) Snapshot ¶
Snapshot returns a detached host view and whether execution completed successfully. It remains available after Close. An error or zero Execution has no snapshot; retrying cleanup does not turn failed execution into success.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
var execution bpf.Execution
_, ready := execution.Snapshot()
fmt.Println(ready)
}
Output: false
type FieldLayout ¶
type FieldLayout = re_obsbpfpolicy.FieldLayout
type Geometry ¶
type Geometry struct {
Grid, Block [3]uint32
}
Geometry describes an ordinary kernel launch. Cluster launches and other extended launch attributes are outside this source contract.
type HolderPolicy ¶
type HolderPolicy = re_obsbpfpolicy.HolderPolicy
type HookStatus ¶
type HookStatus = re_obsbpfpolicy.HookStatus
type Injection ¶
type Injection struct {
// contains filtered or unexported fields
}
Injection is a prepared PTX candidate and its original launch source. It is not proof of assembly, native equivalence or safe compiled resource cost. Loading a candidate requires linking, original/candidate resource comparison, and private module ownership per invocation so map state cannot be shared.
func PrepareInjection ¶
func PrepareInjection(source LaunchSource, p Program, b DevBudget, policy InjectionPolicy) (*Injection, error)
PrepareInjection preserves the original and prepares an opt-in PTX candidate. The current admission path supports one straight-line entry with scalar ABI, register declarations and one instruction per line, ending in an unconditional ret. Branches, predicates, calls, barriers, asynchronous operations, globals, nested scopes and ambiguous formatting preserve the original with a reason. Expanded admission paths require their own safety proof.
Each site executes the verified program with an explicitly synchronized warp membership mask and unique registers/labels. Original instructions and parameter declarations are retained verbatim. Program return values are ignored; only bounded map updates are observed. Declaration budgets include the original registers and all inserted scopes; final compiled resource checks remain required.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
a, err := kernel.NewArtifact(kernel.KindPTX, []byte(".version 9.0\n.target sm_121a\n.address_size 64\n.visible .entry noop() { ret; }\n"), "noop", kernel.Schema{}, "sm_121a")
if err != nil {
fmt.Println(err)
return
}
s, err := bpf.NewArtifactSource(a, bpf.Geometry{Grid: [3]uint32{1, 1, 1}, Block: [3]uint32{32, 1, 1}})
if err != nil {
fmt.Println(err)
return
}
// Instrumentation is disabled unless explicitly enabled and allowlisted.
i, err := bpf.PrepareInjection(s, bpf.Program{}, bpf.DevBudget{}, bpf.InjectionPolicy{})
if err != nil {
fmt.Println(err)
return
}
candidate, reason := i.Candidate()
original, err := i.Original()
fmt.Println(candidate == nil, reason, original != nil, err)
}
Output: true injection disabled true <nil>
Example (Stub) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/kernel"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
ptx := []byte(`.version 9.0
.target sm_121a
.address_size 64
.func trace_stub
{
ret;
}
.visible .entry kernel()
{
call.uni trace_stub;
ret;
}
`)
a, err := kernel.NewArtifact(kernel.KindPTX, ptx, "kernel", kernel.Schema{}, "sm_121a")
if err != nil {
fmt.Println(err)
return
}
s, err := bpf.NewArtifactSource(a, bpf.Geometry{Grid: [3]uint32{1, 1, 1}, Block: [3]uint32{32, 1, 1}})
if err != nil {
fmt.Println(err)
return
}
p := bpf.Program{Version: 1, Registers: 1, Slots: 1, Code: []bpf.Instruction{
{Op: bpf.Const, Dst: 0, Imm: 1},
{Op: bpf.MapAdd, B: 0},
{Op: bpf.Exit},
}}
b := bpf.DevBudget{MaxInstructions: 3, MaxSteps: 3, MaxRegisters: 128, MaxSlots: 1}
policy := bpf.InjectionPolicy{
Enabled: true, Allowlist: []bpf.KernelIdentity{{Digest: a.Digest(), EntryPoint: a.EntryPoint(), Target: a.Target()}},
StubFunctions: []string{"trace_stub"},
}
i, err := bpf.PrepareInjection(s, p, b, policy)
if err != nil {
fmt.Println(err)
return
}
candidate, reason := i.Candidate()
fmt.Println(candidate != nil, reason)
}
Output: true
func (*Injection) Candidate ¶
Candidate returns a detached candidate for review and assembly, or a reason for leaving the original unchanged. A non-nil candidate has not been loaded. Its ABI and launch geometry are those of Original. Instrumentation counters live in module globals __cudabpfdev_map and __cudabpfdev_misses; a runtime must initialize and read them at invocation boundaries, using a private module.
func (*Injection) Load ¶
func (i *Injection) Load(dev *cuda.Device) (*LoadedInjection, error)
Load first loads the original, then links the candidate through nvJitLink and checks its loaded resources and map symbols. A candidate failure selects the original with a reason. An original-load failure or context-restoration failure returns an error and no usable selection. No kernel is launched by Load.
Compiled total registers/shared bytes must fit the preparation budget; the added register cost must fit the declared instrumentation allowance. Candidate local memory is rejected. The supplied block size must fit the loaded function. Map sizes and alignment are checked before candidate selection; initialization and completion-boundary readback belong to the invocation path.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
// Loading always requires an explicit device, even on the original path.
var injection bpf.Injection
_, err := injection.Load(nil)
fmt.Println(err)
}
Output: cudabpfdev: nil device
func (*Injection) Original ¶
func (i *Injection) Original() (*ArtifactSource, error)
Original returns an independent original launch source, including on fallback.
type InjectionPolicy ¶
type InjectionPolicy struct {
Enabled bool
Allowlist []KernelIdentity
Entry, Exit bool
MemoryInstructions []int
// StubFunctions opts into defined device functions with no parameters or
// returns and an empty body. Bodiless declarations are rejected. A listed
// name that is absent and never called is ignored.
StubFunctions []string
}
InjectionPolicy selects insertion sites in an explicitly allowed kernel. MemoryInstructions are zero-based indices in the original parsed instruction sequence, and must name unpredicated global loads or stores. Instrumentation executes before these instructions. Entry and Exit select the first original instruction and final ret. Duplicate sites are coalesced.
type Instruction ¶
Instruction encodes one operation. Registers are indexed by Dst, A and B; unused fields must be zero. Target is an absolute instruction index. Imm is an unsigned constant or a bounded loop count. Unknown opcodes are rejected.
type InterleaveLevel ¶
type InterleaveLevel = re_obsbpfpolicy.InterleaveLevel
type InterpositionDeclaration ¶
type InterpositionDeclaration struct {
Symbol string
Interposition obsprobe.Interposition
}
InterpositionDeclaration reports the caller's interposition status for Symbol. Symbol must be one of Config.Symbols. Evidence is bounded by Interposition.Validate.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
"github.com/tmc/lib/nvidia/x/obs/internal/obsprobe"
)
func main() {
cfg := bpf.TraceHostConfig{Symbols: []string{"cuLaunchKernel"}, Interposition: []bpf.InterpositionDeclaration{{Symbol: "cuLaunchKernel", Interposition: obsprobe.Interposition{Status: "declared_active", Evidence: "operator run manifest"}}}}
fmt.Println(cfg.Interposition[0].Symbol, cfg.Interposition[0].Interposition.Status)
}
Output: cuLaunchKernel declared_active
type InvocationObservation ¶
type InvocationObservation struct {
Original KernelIdentity
Selection Selection
Geometry Geometry
Schema kernel.Schema
Ready, Used, Pending, Closed, Complete bool
TimestampNano int64
// contains filtered or unexported fields
}
InvocationObservation is a detached host receipt from one loaded owner. TimestampNano is completion publication time, available only when Complete. It contains no device identity, native function offset or device duration.
func (InvocationObservation) SameInvocation ¶
func (o InvocationObservation) SameInvocation(other InvocationObservation) bool
SameInvocation reports whether two receipts came from the same in-process owner. It is not an authenticated claim about serialized or caller data.
Example ¶
var observation InvocationObservation fmt.Println(observation.SameInvocation(observation))
Output: false
type InvocationReader ¶
type InvocationReader struct {
// contains filtered or unexported fields
}
InvocationReader is a read-only capability for one LoadedInjection. Its zero value is unavailable. It exposes no driver handles or actuators.
func (InvocationReader) ReadObservation ¶
func (r InvocationReader) ReadObservation() (InvocationObservation, error)
ReadObservation copies retained host state under the owner's mutex without calling native operations. Selection alone does not imply execution.
Example ¶
var reader InvocationReader _, err := reader.ReadObservation() fmt.Println(err != nil)
Output: true
type KernelIdentity ¶
type KernelIdentity struct{ Digest, EntryPoint, Target string }
KernelIdentity is an exact image, entry point and target allowlist key.
type KfuncAbsentError ¶
type KfuncAbsentError = re_obsbpfpolicy.KfuncAbsentError
type KfuncSignature ¶
type KfuncSignature = re_obsbpfpolicy.KfuncSignature
type KfuncStatus ¶
type KfuncStatus = re_obsbpfpolicy.KfuncStatus
type Kfuncs ¶
type Kfuncs = re_obsbpfpolicy.Kfuncs
type Launch ¶
Launch describes one kernel before instrumentation. Artifact contains its bytes, parameter ABI, target and digest; the digest and entry point together identify the kernel. Arguments and stream ownership remain with the caller.
type LaunchSource ¶
LaunchSource supplies a caller-owned snapshot of a kernel and its geometry. Implementations must not infer artifact identity from a symbol name alone. A source does not authorize instrumentation: injection requires a separate opt-in policy and an exact kernel allowlist.
type LayoutMismatch ¶
type LayoutMismatch = re_obsbpfpolicy.LayoutMismatch
type Limits ¶
type Limits = re_obsbpfpolicy.Limits
type Link ¶
type Link = re_obsbpfpolicy.Link
type LoadedInjection ¶
type LoadedInjection struct {
// contains filtered or unexported fields
}
LoadedInjection owns private original/candidate modules and linker resources. It must not be copied. Close every non-nil result of Injection.Load, including error results, before closing its device. Each Load creates separate modules; no instrumentation map is shared with another LoadedInjection.
func (*LoadedInjection) Close ¶
func (l *LoadedInjection) Close() error
Close waits for possibly submitted work, then destroys the stream and unloads retained modules. It retries failed cleanup. Successes are recorded before context restoration so retry cannot release the same handle twice. A failed wait releases nothing. After any Close call, further launches are forbidden.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
var loaded *bpf.LoadedInjection
fmt.Println(loaded.Close())
}
Output: <nil>
func (*LoadedInjection) Launch ¶
func (l *LoadedInjection) Launch(ctx context.Context, args ...any) error
Launch runs the selected image once using the original parameter ABI and geometry on a private nonblocking stream. Inputs must already be ready in the device's context; this call does not inherit dependencies from another stream. Device arguments remain caller-owned and must stay live until Launch succeeds or Close succeeds after an error. Host argument values are copied before launch.
Candidate globals are zeroed on the same stream, then the selected kernel is launched and synchronized. Only then is the instrumentation map read back. Original fallback launches publish no instrumentation snapshot. Execution errors are returned; Launch never reruns the original after possible submission. Cancellation is checked between calls and cannot interrupt native work.
A loaded owner admits one invocation; use another Load for another launch. Invalid arguments or a cancelled context at entry leave it unused. Once context entry is attempted, even a failed invocation consumes the owner. Close is always required. Concurrent calls serialize, with at most one invocation.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
var loaded bpf.LoadedInjection
fmt.Println(loaded.Launch(context.Background()))
}
Output: cudabpfdev: no open loaded selection
func (*LoadedInjection) ObservationReader ¶
func (l *LoadedInjection) ObservationReader() InvocationReader
ObservationReader returns a read-only view that remains readable after Close.
Example ¶
var owner *LoadedInjection _, err := owner.ObservationReader().ReadObservation() fmt.Println(err != nil)
Output: true
func (*LoadedInjection) Record ¶
func (l *LoadedInjection) Record() (iket.Record, error)
Record returns a successful invocation boundary for Recorder.Push, including the original fallback decision. Failed invocations produce no success record. The timestamp is host completion/readback publication; GPU duration and CUPTI correlation are unavailable. Full counter values are available from Snapshot.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
var loaded bpf.LoadedInjection
_, err := loaded.Record()
fmt.Println(err)
}
Output: cudabpfdev: no completed invocation
func (*LoadedInjection) Selection ¶
func (l *LoadedInjection) Selection() (Selection, error)
Selection returns the image decision after a successful Load. It remains available after Close as a receipt; it does not authorize further use then.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
var loaded bpf.LoadedInjection
_, err := loaded.Selection()
fmt.Println(err)
}
Output: cudabpfdev: no loaded selection
func (*LoadedInjection) Snapshot ¶
func (l *LoadedInjection) Snapshot() (MapSnapshot, bool)
Snapshot returns a detached instrumentation map after a successful candidate launch. It is unavailable for fallback or failed invocations and survives Close.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
var loaded bpf.LoadedInjection
_, available := loaded.Snapshot()
fmt.Println(available)
}
Output: false
type Loader ¶
type Loader = re_obsbpfpolicy.Loader
type Manifest ¶
type Manifest struct {
// Interposition binds caller declarations to actual attachment target identities.
Interposition []obsprobe.ProbeIdentity
ThreadCoverage SnapshotCoverage
ThreadRescans []ThreadRescan
ThreadRescanInterval time.Duration
MaxThreadRescans int
TaskExecOffset, TaskExecSize uint32
KernelBTFHash string
TaskStartOffset uint32
Backend, Clock, Epoch string
Process obsprobe.Process
Images []ebpfhost.Image
Complete bool
LossStatus, ThreadScope, LibraryVersionStatus string
}
Manifest records attachment provenance and explicit coverage limits. Epoch is the kernel boot ID for the monotonic clock, not a sensor clock mapping.
type MapSnapshot ¶
type MemoryPolicy ¶
type MemoryPolicy = re_obsbpfpolicy.MemoryPolicy
type NumericalPolicy ¶
type NumericalPolicy struct {
Mode string
AbsoluteTolerance, RelativeTolerance float64
EqualNaNs, IgnoreZeroSign bool
}
NumericalPolicy declares float32 output comparison semantics. Mode must be "exact" (identical bits) or "tolerance". Tolerance mode accepts finite values when abs(got-want) <= AbsoluteTolerance + RelativeTolerance*abs(want). Tolerances must be finite and nonnegative; exact mode requires both to be zero. Infinities must match in sign. NaNs match only when EqualNaNs is true, regardless of payload. Signed zeros must match unless IgnoreZeroSign is explicitly set in tolerance mode. The zero policy is invalid, requiring an explicit choice.
type Object ¶
type Object = re_obsbpfpolicy.Object
type ObjectSpec ¶
type ObjectSpec = re_obsbpfpolicy.ObjectSpec
type Observation ¶
type Observation struct {
ThreadGenerationKnown bool
ExecID uint64
ThreadGeneration uint64
Raw string
TID uint32
Timestamp uint64
Name string
Args [11]uint64
ArgsKnown [11]bool
Return int32
ReturnKnown bool
}
Observation preserves the original kernel line and parsed clock/TID. Args use entry ABI slots; Return is only known on an observed return event.
func Parse ¶
func Parse(line string) (Observation, error)
Parse parses the bounded text tracefs transport. It rejects truncated clocks, malformed numbers and unknown fields rather than inventing zero values.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
o, err := bpf.Parse(" app-42 [000] .... 1.000001: cuda0_in: a0=0x123")
fmt.Println(o.TID, o.Timestamp, o.Args[0], err)
}
Output: 42 1000001000 291 <nil>
type Observer ¶
type Observer = re_obsbpfpolicy.Observer
type Op ¶
type Op uint8
Op identifies a version-1 device instruction.
const ( Const Op = iota + 1 // Dst = Imm. Move // Dst = A. Add // Dst = A + B modulo 2^32. And // Dst = A & B. Lane // Dst = hardware lane ID, a varying value. Ballot // Dst = active mask of lanes whose A is nonzero. Leader // Dst = A from the lowest active lane, broadcast. JumpNonzero // Branch to Target if A != 0, otherwise fall through. Repeat // Repeat [Target, PC] Imm times in total. MapAdd // Add B to map slot A once per active warp. Exit // Return A; no side effect. )
type Outcome ¶
type Outcome = re_obsbpfpolicy.Outcome
type PMMDecision ¶
type PMMDecision = re_obsbpfpolicy.PMMDecision
type PMMRequest ¶
type PMMRequest = re_obsbpfpolicy.PMMRequest
type PMMSnapshot ¶
type PMMSnapshot = re_obsbpfpolicy.PMMSnapshot
type PolicyBudget ¶
type PolicyBudget = re_obsbpfpolicy.PolicyBudget
type PolicyConfig ¶
type PolicyConfig = re_obsbpfpolicy.PolicyConfig
type Position ¶
type Position = re_obsbpfpolicy.Position
type PrefetchDecision ¶
type PrefetchDecision = re_obsbpfpolicy.PrefetchDecision
type PrefetchRequest ¶
type PrefetchRequest = re_obsbpfpolicy.PrefetchRequest
type PrefetchResult ¶
type PrefetchResult = re_obsbpfpolicy.PrefetchResult
type PrefetchWorker ¶
type PrefetchWorker = re_obsbpfpolicy.PrefetchWorker
type Program ¶
type Program struct {
Version uint16
Registers uint8
Slots uint32
StagingBytes uint32
Code []Instruction
}
Program is the versioned device contract. Registers is in [1,32]. Slots is the fixed map capacity; a runtime key outside it must not write memory. StagingBytes is requested shared storage, not an inferred hardware limit. Code must not be mutated concurrently with verification or evaluation.
type ProgramSpec ¶
type ProgramSpec = re_obsbpfpolicy.ProgramSpec
type RecordSink ¶
type RecordSink = re_obsbpfpolicy.RecordSink
type Region ¶
type Region = re_obsbpfpolicy.Region
type Reorder ¶
type Reorder = re_obsbpfpolicy.Reorder
type Report ¶
type Report = re_obsbpfpolicy.Report
type SchedAttributes ¶
type SchedAttributes = re_obsbpfpolicy.SchedAttributes
type SchedPolicy ¶
type SchedPolicy = re_obsbpfpolicy.SchedPolicy
type SchedulerEvent ¶
type SchedulerEvent struct {
Clock string
Raw, Kind, PrevState string
Timestamp uint64
CPU uint32
PreviousTID, NextTID, WakeTID uint32
}
SchedulerEvent preserves kernel scheduling evidence. PrevState is the raw tracepoint state, not an inferred cause of blocking. Timestamps use tracefs mono clock. No application or GPU association is inferred.
func ParseScheduler ¶
func ParseScheduler(line string) (SchedulerEvent, error)
ParseScheduler decodes sched_switch and sched_wakeup lines. Event PID fields refer to Linux TIDs. Process membership must be checked independently.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
e, err := bpf.ParseScheduler(" app-42 [003] .... 1.25: sched_wakeup: comm=app pid=42 prio=120 target_cpu=003")
fmt.Println(e.Kind, e.WakeTID, e.CPU, e.Clock, err)
}
Output: sched_wakeup 42 3 linux_monotonic <nil>
type Selection ¶
type Selection struct {
Kernel KernelIdentity
Candidate bool
Reason string
}
Selection identifies the image selected after loading and resource checks. Candidate reports selection of instrumentation, not execution or equivalence. Reason explains why the original was selected; it is empty for a candidate.
type SinkObserver ¶
type SinkObserver = re_obsbpfpolicy.SinkObserver
type Snapshot ¶
Snapshot is a device invocation's host view after successful kernel completion and readback. Inactive Values are zero. The fixed-capacity Map is private to this invocation; Misses counts out-of-range keys. This is snapshot-at-boundary consistency, not a coherent live view of device memory. No timing is implied.
type SnapshotCoverage ¶
type SnapshotCoverage struct {
Status string
Clock string
DiscoveryEndNanos, AttachmentStartNanos, AttachmentEndNanos, VerificationEndNanos int64
Threads []ThreadSnapshot
FutureThreads string
BlindInterval string
// ProcessThreads counts the target's threads at discovery. Selection says
// how Threads were chosen from them: [SelectAll], [SelectExplicit] or
// [SelectObserved]. Excluded lists the unprobed rest; their calls are
// unobserved. Empty Selection (legacy manifests) means unknown.
ProcessThreads int
Selection string
Excluded []ThreadSnapshot
// SelectionWindow and SelectionSymbols describe a SelectObserved pass:
// how long each snapshot thread was watched and which entries were probed.
// A thread that called none of them during the window is excluded even
// if it calls CUDA later, as a Go thread can once it runs another goroutine.
SelectionWindow time.Duration
SelectionSymbols []string
}
SnapshotCoverage records the BPF attachment snapshot. Offset fields are elapsed monotonic nanoseconds from discovery start, not event timestamps. Successful verification establishes matching task generations before and after attachment, not continuous coverage or an atomic process snapshot. Future threads and calls during discovery/attachment remain unobserved. Tracefs coverage is unavailable here: that backend enumerates separately. The zero value (including legacy manifests omitting this field) means unknown.
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
// This is a serialized attachment manifest, not a native collection receipt.
data := []byte(`{"ThreadCoverage":{"Status":"generation_verified_attachment_snapshot","Clock":"elapsed_since_discovery","Threads":[{"TID":7,"Generation":107}],"FutureThreads":"unobserved","BlindInterval":"discovery_through_attachment"},"Complete":false}`)
var manifest bpf.Manifest
if err := json.Unmarshal(data, &manifest); err != nil {
fmt.Println(err)
return
}
coverage := manifest.ThreadCoverage
fmt.Println(coverage.Threads[0].TID, coverage.FutureThreads, manifest.Complete)
}
Output: 7 unobserved false
type StopStats ¶
type StopStats struct {
Submitted, Dropped, Delivered, Undelivered uint64
RingStatus string
Output bpfprobe.OutputFailures
}
StopStats reports known BPF ring counts after disabling attachments. The capture remains incomplete: pre-attachment history and tracefs loss are unknown. Delivered counts include records returned before caller writes.
type StructOpsSpec ¶
type StructOpsSpec = re_obsbpfpolicy.StructOpsSpec
type TaskDestroyContext ¶
type TaskDestroyContext = re_obsbpfpolicy.TaskDestroyContext
type TaskInitContext ¶
type TaskInitContext = re_obsbpfpolicy.TaskInitContext
type ThreadRescan ¶
type ThreadRescan struct {
Sequence int
Status, Clock, BlindInterval, MissedCalls string
StartNanos, EndNanos int64
Threads []ThreadSnapshot
AttachmentAttempted bool
Reason string
}
ThreadRescan records bounded attachment attempts. Times use elapsed monotonic nanoseconds from initial discovery, not the BPF event clock. Missed calls and threads born and gone between scans are unknown, even after a verified scan.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
r := bpf.ThreadRescan{Status: "generation_verified_attachment", MissedCalls: "unknown", BlindInterval: "between_scans_unknown"}
fmt.Println(r.Status, r.MissedCalls)
}
Output: generation_verified_attachment unknown
type ThreadSnapshot ¶
ThreadSnapshot identifies a discovered task by its Linux starttime ticks. Generation is the /proc stat token, not the kernel BPF event's nanosecond birth field. The two values must not be compared directly.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
task := bpf.ThreadSnapshot{TID: 7, Generation: 107}
fmt.Println(task.TID, task.Generation)
}
Output: 7 107
type TimesliceControlContext ¶
type TimesliceControlContext = re_obsbpfpolicy.TimesliceControlContext
type Timings ¶
type Timings = re_obsbpfpolicy.Timings
type TraceHostConfig ¶
type TraceHostConfig struct {
// Interposition declares exact selected symbols; omitted symbols remain unknown.
// Declarations are caller-reported and do not establish verified coactivity.
Interposition []InterpositionDeclaration
Backend string
PID int
Library, Version, Layer, TraceRoot string
Symbols []string
Scheduler bool
UserStack bool
MaxPending int
ThreadRescanInterval time.Duration
MaxThreadRescans int
// Threads restricts BPF probes to these threads of PID. SelectWindow
// instead probes only the threads seen entering a selected symbol during
// a discovery pass of that length. Each symbol costs two attachments per
// probed thread against a bound of 256; see [CheckBudget]. Selection is
// BPF-only, takes one of the two, and excludes thread rescans.
Threads []int
SelectWindow time.Duration
}
Example (ThreadRescan) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
"time"
)
func main() {
cfg := bpf.TraceHostConfig{Backend: "bpf", ThreadRescanInterval: time.Second, MaxThreadRescans: 32}
fmt.Println(cfg.ThreadRescanInterval, cfg.MaxThreadRescans)
}
Output: 1s 32
type TraceHostResult ¶
type TraceHostResult struct {
Call *CallInterval
Native *bpfprobe.Event
Raw string
Capture *obsprobe.ProbeCapture
Scheduler bool
ThreadRescan *ThreadRescan
PairingStatus string
}
Result preserves raw transport even when a line cannot be decoded. Scheduler is an observed host scheduling line, not GPU evidence.
type Translation ¶
type Translation struct {
Artifact *kernel.Artifact
Analysis Analysis
DeclaredRegisters uint32
// contains filtered or unexported fields
}
Translation contains verified PTX and its kernel ABI. DeclaredRegisters is the conservative 32-bit register footprint of the emitted declarations, including scratch registers and predicates. It is not the compiler's final register allocation. Injection still requires the compiled resource report.
func Translate ¶
func Translate(p Program, b DevBudget, target string) (Translation, error)
Translate emits a standalone one-warp oracle kernel for a verified program. It is the device bytecode execution path, not a trampoline injector. Launch exactly one block of 32 threads. Arguments are a zeroed Slots*4-byte map, a 128-byte per-lane return array, a zeroed 8-byte miss counter and an active lane mask. All storage must be disjoint and private to the invocation, and remain live until kernel completion. Inactive result slots are not written.
PTX ISA 9.0 is required. Shared staging is not emitted yet; a nonzero request is rejected. Unknown target limits are rejected, never filled with defaults.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/bpf"
)
func main() {
p := bpf.Program{Version: 1, Registers: 1, Slots: 1, Code: []bpf.Instruction{{Op: bpf.Exit}}}
b := bpf.DevBudget{MaxInstructions: 1, MaxSteps: 1, MaxRegisters: 32, MaxSlots: 1}
x, err := bpf.Translate(p, b, "sm_121a")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(x.Artifact.Target(), x.Artifact.EntryPoint(), x.Artifact.Schema().TotalParamBytes)
}
Output: sm_121a cudabpfdev_main 32
type TypeAbsentError ¶
type TypeAbsentError = re_obsbpfpolicy.TypeAbsentError
type TypeLayout ¶
type TypeLayout = re_obsbpfpolicy.TypeLayout
type TypeStatus ¶
type TypeStatus = re_obsbpfpolicy.TypeStatus
type VerifyError ¶
VerifyError locates a rejected instruction; PC -1 denotes a program header.
func (*VerifyError) Error ¶
func (e *VerifyError) Error() string
Source Files
¶
- dev_compare.go
- dev_eval.go
- dev_inject.go
- dev_launch.go
- dev_load.go
- dev_observation.go
- dev_program.go
- dev_ptx.go
- dev_record.go
- dev_resources.go
- dev_run.go
- dev_source.go
- dev_verify.go
- doc.go
- reexport.go
- tracehost_budget.go
- tracehost_collector.go
- tracehost_correlate.go
- tracehost_coverage.go
- tracehost_parse.go
- tracehost_rescan.go
- tracehost_scheduler.go
- tracehost_stat_linux.go
- tracehost_symbols.go