Documentation
¶
Overview ¶
Package obsbpfpolicy holds pure-Go eBPF policy and budget definitions re-exported by x/obs/bpf.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsbpfpolicy"
)
func main() {
r := obsbpfpolicy.Reorder{Destination: obsbpfpolicy.DestinationUnused, Position: obsbpfpolicy.PositionTail}
fmt.Println(r.Valid())
fmt.Println(r)
}
Output: <nil> unused/tail
Index ¶
- Constants
- Variables
- func CheckGoLayouts() error
- func CheckLayouts(b BTF) (absent []string, err error)
- func MemOpsMembers() []string
- func SchedOpsMembers() []string
- type BTF
- type BindContext
- type BindDecision
- type BlockState
- type Bridge
- func (br *Bridge) Attach(ctx context.Context, obj ObjectSpec, spec StructOpsSpec) (Link, error)
- func (br *Bridge) Close() error
- func (br *Bridge) Detach(table string) error
- func (br *Bridge) Disable()
- func (br *Bridge) DisableHook(member, reason string)
- func (br *Bridge) Discover(ctx context.Context) (*Report, error)
- func (br *Bridge) Enable()
- func (br *Bridge) EnableHook(member string)
- func (br *Bridge) HookDisabled(member string) (string, bool)
- func (br *Bridge) OnBind(c *BindContext) (BindDecision, Outcome)
- func (br *Bridge) OnBlockAccess(d *PMMDecision) Outcome
- func (br *Bridge) OnBlockActivate(d *PMMDecision) Outcome
- func (br *Bridge) OnTaskInit(c *TaskInitContext) (SchedAttributes, Outcome)
- func (br *Bridge) Outcomes() []Outcome
- func (br *Bridge) Reattach(ctx context.Context, obj ObjectSpec, spec StructOpsSpec, generation uint64) (Link, error)
- func (br *Bridge) Report() *Report
- func (br *Bridge) SetMemoryPolicy(p MemoryPolicy)
- func (br *Bridge) SetSchedPolicy(p SchedPolicy)
- type Capabilities
- type Counters
- type Destination
- type FieldLayout
- type HolderPolicy
- func (p *HolderPolicy) BlockAccess(d *PMMDecision, b *PolicyBudget) (Reorder, bool, error)
- func (p *HolderPolicy) BlockActivate(d *PMMDecision, b *PolicyBudget) (Reorder, bool, error)
- func (p *HolderPolicy) Decide(s PMMSnapshot, b *PolicyBudget) (Reorder, bool, error)
- func (p *HolderPolicy) Prefetch(*PrefetchDecision, *PolicyBudget) (Region, bool, error)
- type HookStatus
- type InterleaveLevel
- type KfuncAbsentError
- type KfuncSignature
- type KfuncStatus
- type Kfuncs
- type LayoutMismatch
- type Limits
- type Link
- type Loader
- type MemoryPolicy
- type Object
- type ObjectSpec
- type Observer
- type Outcome
- type PMMDecision
- type PMMRequest
- type PMMSnapshot
- type PolicyBudget
- type PolicyConfig
- type Position
- type PrefetchDecision
- type PrefetchRequest
- type PrefetchResult
- type PrefetchWorker
- type ProgramSpec
- type RecordSink
- type Region
- type Reorder
- type Report
- type SchedAttributes
- type SchedPolicy
- type SinkObserver
- type StructOpsSpec
- type TaskDestroyContext
- type TaskInitContext
- type TimesliceControlContext
- type Timings
- type TypeAbsentError
- type TypeLayout
- type TypeStatus
Examples ¶
Constants ¶
const ( DestinationUnset Destination = 0 DestinationUsed Destination = 1 DestinationUnused Destination = 2 PositionUnset Position = 0 PositionHead Position = 1 PositionTail Position = 2 )
Destination and Position values, as enum nv_gpu_pmm_destination and enum nv_gpu_pmm_position. Zero is not a valid value of either, which is what makes an unset request distinguishable from a request for the head.
const ( EngineGraphics uint32 = 0 EngineCopy uint32 = 1 EngineNVDEC uint32 = 2 EngineNVENC uint32 = 3 EngineNVJPEG uint32 = 4 )
Engine types, as NV_ENGINE_TYPE_*.
const ( MemOpsTable = "gpu_mem_ops" SchedOpsTable = "nv_gpu_sched_ops" )
The two tables this package knows how to drive, and their members in declaration order. Member order is the slot order the kernel assigns, so it is part of the contract and not a presentation choice.
const BindRejection = "bpf_nv_gpu_reject_bind"
BindRejection names the mechanism by which a rejection reaches the driver.
Two forms exist in the interface: the kfunc bpf_nv_gpu_reject_bind, and the allow member of nv_gpu_bind_ctx. They are not alternatives. The kfunc is non-sleepable and its entire effect is to write the ctx field, so the field is what the driver reads and the call is how a verified BPF program is permitted to write it. A program that assigns ctx->allow directly is writing a struct_ops context member without the kfunc the verifier sanctions for it.
This package therefore implements the call form and never writes Allow. The determination is drawn from the interface sources, not from a live driver: no target available to this lane registers nv_gpu_sched_ops, so it has not been observed. See the handoff.
const Unmeasured time.Duration = -1
Unmeasured marks a duration that was not measured. A zero duration means a measurement was taken and came out at zero, which is a different claim.
Variables ¶
var ErrBudgetExceeded = errors.New("cudabpf: handler budget exceeded")
ErrBudgetExceeded is returned by [Budget.Step] when a handler has done more work than a fault path permits.
var ErrDisabled = errors.New("cudabpf: hook disabled")
ErrDisabled is returned when a hook or the whole bridge is switched off. Attachment is opt-in per process and reversible, so being off is a normal state and not a failure.
var ErrNoBTF = errors.New("cudabpf: target has no BTF")
ErrNoBTF is returned by a loader on a target with no type information. Without BTF nothing here can be attached, because every identifier would be an unverified guess.
var ErrNotAttached = errors.New("cudabpf: not attached")
ErrNotAttached is returned when an operation needs a live attachment.
var ErrOutOfRange = errors.New("cudabpf: scheduling attribute out of range")
ErrOutOfRange is returned by SchedAttributes.Validate.
Functions ¶
func CheckGoLayouts ¶
func CheckGoLayouts() error
CheckGoLayouts reports the first disagreement between the Go declarations in this package and InventoryLayouts. It exists so a struct edit that silently changes an offset is caught on a host with no BTF at all, and so a consumer can assert the same thing without a target.
func CheckLayouts ¶
CheckLayouts compares every inventory layout against the target's BTF.
A type BTF does not know is reported through TypeAbsentError, which is a capability result rather than a mismatch: on an unpatched kernel every one of these types is absent and that is the expected answer. A type BTF does know but lays out differently is a LayoutMismatch, and the caller must not attach.
func MemOpsMembers ¶
func MemOpsMembers() []string
MemOpsMembers are the six members of struct gpu_mem_ops.
func SchedOpsMembers ¶
func SchedOpsMembers() []string
SchedOpsMembers are the four members of struct nv_gpu_sched_ops.
Types ¶
type BTF ¶
type BTF interface {
// TypeLayout returns the size and member offsets of a named type.
// A type the target does not define is reported with a
// [TypeAbsentError], not a zero layout.
TypeLayout(name string) (TypeLayout, error)
// KfuncSignature returns the signature of a named BPF kfunc. A kfunc
// the target does not define is reported with a [KfuncAbsentError].
KfuncSignature(name string) (KfuncSignature, error)
// StructOpsTables lists the struct_ops table types the kernel has
// registered. On a target with no GPU policy module this contains the
// ordinary kernel tables and neither of the two this package wants.
StructOpsTables() ([]string, error)
// ValidateStructOpsMember checks that the registered table contains the
// requested callback and its prototype matches the driver ABI. A BTF
// struct name alone does not establish registration or verifier support.
ValidateStructOpsMember(table, member string) error
}
A BTF is a target's type information. It answers questions about the types and kfuncs a driver actually exports, and it is the only authority: an identifier from a header, a proposal or InventoryLayouts is a hypothesis until BTF confirms it.
type BindContext ¶
type BindContext struct {
TSGID uint64
RunlistID uint32
ChannelCount uint32
TimesliceUS uint64
InterleaveLevel uint32
Allow uint32
}
BindContext is struct nv_gpu_bind_ctx. Allow is written by the driver in response to bpf_nv_gpu_reject_bind; see BindRejection.
type BindDecision ¶
A BindDecision is the answer to an admission-control hook.
type BlockState ¶
type BlockState interface {
// Holders returns how many sequences reference a block. An unknown
// block is an error, not zero holders -- zero holders means the block
// is free, which is the opposite claim.
Holders(block int) (int, error)
}
A BlockState is the KV cache's own view of whether a block is still referenced. The signature is cudakv's: block ownership, allocation and refcounting stay there, and this package supplies events and decisions rather than holding any of it. It is an interface so that nothing here imports the KV cache, and so a parity test can drive both sides from the same allocator.
type Bridge ¶
type Bridge struct {
// contains filtered or unexported fields
}
A Bridge owns compiled-object attachments and evaluates host policy models. SetMemoryPolicy and SetSchedPolicy do not compile Go callbacks into BPF or alter the supplied object. On* methods are explicit host-model invocations; kernel hooks run the compiled object programs, not these Go methods.
The bridge never takes eviction authority from the driver. Every path through it ends either in a submitted request the driver may ignore, or in the driver's own behavior with a recorded reason. There is no path that leaves a placement undefined.
func NewBridge ¶
func NewBridge(l Loader, k Kfuncs, cfg PolicyConfig) *Bridge
NewBridge returns an attachment owner and host-model evaluator. Policies are used only by the On* methods. Attach loads the supplied compiled object regardless of which host policies are installed.
func (*Bridge) Attach ¶
func (br *Bridge) Attach(ctx context.Context, obj ObjectSpec, spec StructOpsSpec) (Link, error)
Attach loads an object and registers one struct_ops map.
Attaching a table that is already attached is not an error and does not register a second map: the existing link is returned. Two processes racing to attach is a different case, and one the kernel arbitrates -- the second registration fails at the loader and the error is returned unwrapped.
func (*Bridge) Close ¶
Close disables the bridge and detaches all owned links. Failed detach or close operations retain ownership so a later Close can retry cleanup.
func (*Bridge) Detach ¶
Detach removes one table's attachment. Detaching what is not attached succeeds: a disable switch must work whatever state it finds.
func (*Bridge) Disable ¶
func (br *Bridge) Disable()
Disable switches host-model evaluation and new attachment requests off. Existing kernel links remain attached until Detach or Close.
func (*Bridge) DisableHook ¶
DisableHook switches one hook off with a recorded reason. The driver's default behavior takes over immediately; the attachment is left in place so the hook can be re-enabled without a reload.
func (*Bridge) EnableHook ¶
EnableHook clears a disable.
func (*Bridge) HookDisabled ¶
HookDisabled reports whether a hook is off, and why.
func (*Bridge) OnBind ¶
func (br *Bridge) OnBind(c *BindContext) (BindDecision, Outcome)
OnBind routes an on_bind invocation.
func (*Bridge) OnBlockAccess ¶
func (br *Bridge) OnBlockAccess(d *PMMDecision) Outcome
OnBlockAccess routes a gpu_block_access invocation.
func (*Bridge) OnBlockActivate ¶
func (br *Bridge) OnBlockActivate(d *PMMDecision) Outcome
OnBlockActivate routes a gpu_block_activate invocation.
func (*Bridge) OnTaskInit ¶
func (br *Bridge) OnTaskInit(c *TaskInitContext) (SchedAttributes, Outcome)
OnTaskInit routes an on_task_init invocation.
func (*Bridge) Reattach ¶
func (br *Bridge) Reattach(ctx context.Context, obj ObjectSpec, spec StructOpsSpec, generation uint64) (Link, error)
Reattach re-registers a table whose link is stale because the driver re-registered its tables. A generation change invalidates the link but not the policy, so the old link is detached and a new one taken.
func (*Bridge) SetMemoryPolicy ¶
func (br *Bridge) SetMemoryPolicy(p MemoryPolicy)
SetMemoryPolicy installs the placement policy.
func (*Bridge) SetSchedPolicy ¶
func (br *Bridge) SetSchedPolicy(p SchedPolicy)
SetSchedPolicy installs the scheduling policy.
type Capabilities ¶
type Capabilities struct {
Kernel string // uname -r
KernelConfig map[string]string
Driver string // e.g. "NVIDIA UNIX Open Kernel Module 580.173.02"
GPU string // e.g. "NVIDIA GB10"
ComputeCap string // e.g. "12.1"
CUDA string
BTFAvailable bool
// UnprivilegedBPFKnown distinguishes "permitted" from "not
// determined". Without it, false would mean both.
UnprivilegedBPFKnown bool
UnprivilegedBPFAllowed bool
StructOpsTables []string
}
Capabilities is the P0 identity of a target: enough to decide what can be attached, and enough that a later claim about kernel behavior can name the machine it was made on.
The string fields are recorded verbatim from the target. An unknown one is empty, and empty means unknown -- it is never filled with a plausible value.
func (Capabilities) String ¶
func (c Capabilities) String() string
type Counters ¶
type Counters struct {
Consulted uint64
Opinions uint64
Submitted uint64
Fallbacks uint64
Conflicts uint64
Attempted uint64
}
A Counters is the fixed-size observation a fault path can afford. It allocates nothing and its size does not depend on how many hooks fire.
type Destination ¶
type Destination uint64
Destination selects which of the driver's two chunk lists the request names.
func (Destination) String ¶
func (d Destination) String() string
func (Destination) Valid ¶
func (d Destination) Valid() bool
Valid reports whether d names one of the driver's lists.
type FieldLayout ¶
FieldLayout is the offset of one named member within a type.
type HolderPolicy ¶
type HolderPolicy struct {
State BlockState
// Block maps the driver's view of a root chunk to a KV block. It
// reports false for a chunk that is not KV cache at all, and such a
// chunk gets no opinion rather than a guessed one.
Block func(PMMSnapshot) (int, bool)
// StepCost is charged per invocation against the fault budget.
StepCost int
}
A HolderPolicy places a root chunk according to whether the KV block behind it is still referenced. It is the reference placement policy: unreferenced blocks are moved toward the unused list so the driver reaches them first, referenced ones toward the used list so it reaches them last.
It expresses a preference and nothing more. The driver keeps final authority, the request may be refused or collide, and a block the policy wanted kept can still be evicted.
func (*HolderPolicy) BlockAccess ¶
func (p *HolderPolicy) BlockAccess(d *PMMDecision, b *PolicyBudget) (Reorder, bool, error)
BlockAccess implements MemoryPolicy.
func (*HolderPolicy) BlockActivate ¶
func (p *HolderPolicy) BlockActivate(d *PMMDecision, b *PolicyBudget) (Reorder, bool, error)
BlockActivate implements MemoryPolicy. Activation and access take the same decision: both ask where a chunk belongs given who still holds it.
func (*HolderPolicy) Decide ¶
func (p *HolderPolicy) Decide(s PMMSnapshot, b *PolicyBudget) (Reorder, bool, error)
Decide returns the placement for one observed chunk.
func (*HolderPolicy) Prefetch ¶
func (p *HolderPolicy) Prefetch(*PrefetchDecision, *PolicyBudget) (Region, bool, error)
Prefetch implements MemoryPolicy. A holder policy has no view on prefetching, and says so rather than inventing a region.
type HookStatus ¶
A HookStatus is one hook's availability on a target. Available false with a Reason is the normal result: these tables are not mainline, so on an ordinary kernel every hook is absent.
func (HookStatus) String ¶
func (h HookStatus) String() string
type InterleaveLevel ¶
type InterleaveLevel uint32
InterleaveLevel is a runlist interleave level, as NV_INTERLEAVE_LEVEL_*.
const ( InterleaveLow InterleaveLevel = 0 InterleaveMedium InterleaveLevel = 1 InterleaveHigh InterleaveLevel = 2 )
The interleave levels the driver defines. There are exactly three; a value outside them is rejected by SchedAttributes.Validate rather than clamped.
func (InterleaveLevel) String ¶
func (l InterleaveLevel) String() string
func (InterleaveLevel) Valid ¶
func (l InterleaveLevel) Valid() bool
Valid reports whether l is one of the three defined levels.
type KfuncAbsentError ¶
type KfuncAbsentError struct{ Name string }
A KfuncAbsentError reports that BTF does not define a kfunc.
func (*KfuncAbsentError) Error ¶
func (e *KfuncAbsentError) Error() string
type KfuncSignature ¶
type KfuncSignature struct {
Name string
Params []string
Returns string
Annotated bool // BTF_ID_FLAGS present, i.e. callable from a BPF program
}
A KfuncSignature is a kfunc's name and parameter types as BTF reports them. Params holds BTF type names in declaration order; a pointer parameter is spelled with a trailing "*", matching how the driver's headers declare it.
func (KfuncSignature) String ¶
func (s KfuncSignature) String() string
type KfuncStatus ¶
type KfuncStatus struct {
Name string
Available bool
Reason string
Signature KfuncSignature
}
A KfuncStatus is one kfunc's availability and, when present, the signature BTF reports for it. A kfunc present but unannotated cannot be called from a BPF program, so it is recorded as unavailable with that as the reason.
type Kfuncs ¶
type Kfuncs interface {
// RequestReorder is bpf_gpu_request_reorder. It submits destination
// and position; it does not report whether the driver obeyed them.
// The answer, such as it is, arrives in ctx.Request.Attempted and
// ctx.Request.Conflict, which the driver writes.
RequestReorder(ctx *PMMDecision, dst Destination, pos Position) error
// SetPrefetchRegion is bpf_gpu_set_prefetch_region.
SetPrefetchRegion(d *PrefetchDecision, first, outer uint64) error
// MigrateRange is bpf_gpu_migrate_range.
MigrateRange(vaSpace, addr, length uint64) error
// SetTimeslice is bpf_nv_gpu_set_timeslice.
SetTimeslice(ctx *TaskInitContext, us uint64) error
// SetInterleave is bpf_nv_gpu_set_interleave.
SetInterleave(ctx *TaskInitContext, level InterleaveLevel) error
// RejectBind is bpf_nv_gpu_reject_bind. It is non-sleepable and its
// whole effect is to clear ctx.Allow; see [BindRejection] for why the
// call form and not the field write is the supported path.
RejectBind(ctx *BindContext) error
}
A Kfuncs actuates a policy decision. On a real target these are BPF kfunc calls made from inside a handler; the interface exists so the decision logic can be exercised with no kernel, and so an unannotated or absent kfunc is a refusal at one place rather than a silent no-op at many.
type LayoutMismatch ¶
type LayoutMismatch struct {
Type string
Member string // empty when the size itself disagrees
Want uintptr
Got uintptr
Source string // where Got came from, e.g. "BTF"
}
A LayoutMismatch is a disagreement between a layout this package requires and one a target reports. It is an error, never a warning: a context struct read at the wrong offset yields a plausible number from the wrong field, and nothing downstream can tell that it did.
func (*LayoutMismatch) Error ¶
func (e *LayoutMismatch) Error() string
type Limits ¶
type Limits struct {
MinTimesliceUS uint64
MaxTimesliceUS uint64
// MaxInterleave is the highest level the driver defines. There are
// three, so a request above it is a request for a level that does not
// exist rather than for more of something.
MaxInterleave InterleaveLevel
}
Limits are the ranges the driver accepts. They are a property of the target. The defaults below are host-model policy limits, not a discovery receipt. A consumer must supply driver and tenant limits validated on the target rather than treating this example window as an admission result.
func DefaultLimits ¶
func DefaultLimits() Limits
DefaultLimits returns a host-model policy window. It is not a verified driver range: no target with the scheduler table has been qualified.
type Link ¶
type Link interface {
// Generation is the driver generation the link was made against. A
// change means the tables were re-registered and the link is stale.
Generation() uint64
// Detach removes the attachment. Detach is idempotent.
Detach() error
}
A Link is one live attachment. Detaching is the only way to stop a policy from running, and it must always be available: a bridge that cannot detach cannot honor its disable switch.
type Loader ¶
type Loader interface {
// Capabilities reports what the target provides: kernel, driver and
// GPU identity, BTF presence, registered struct_ops tables, and
// whether unprivileged BPF is permitted.
Capabilities(ctx context.Context) (Capabilities, error)
// BTF returns the target's type information, or an error if the
// target has none.
BTF(ctx context.Context) (BTF, error)
// Load loads the programs and maps of one object without attaching
// anything.
Load(ctx context.Context, spec ObjectSpec) (Object, error)
}
A Loader loads and attaches BPF programs. It is satisfied by a consumer in a module that may depend on libbpf or cilium/ebpf; nothing here does.
type MemoryPolicy ¶
type MemoryPolicy interface {
// BlockAccess runs on gpu_block_access.
BlockAccess(d *PMMDecision, b *PolicyBudget) (r Reorder, ok bool, err error)
// BlockActivate runs on gpu_block_activate.
BlockActivate(d *PMMDecision, b *PolicyBudget) (r Reorder, ok bool, err error)
// Prefetch runs on gpu_page_prefetch and gpu_page_prefetch_iter.
Prefetch(d *PrefetchDecision, b *PolicyBudget) (r Region, ok bool, err error)
}
A MemoryPolicy decides placement. Every method is called on a fault path, must charge its work against the budget, and must not block or allocate.
Returning ok false is a first-class answer meaning "no opinion": the driver's own behavior stands, and nothing is recorded as a fallback, because nothing failed.
type Object ¶
type Object interface {
// AttachStructOps registers a struct_ops map against a table and
// returns a link whose lifetime owns the attachment.
AttachStructOps(ctx context.Context, spec StructOpsSpec) (Link, error)
// Close releases the programs and maps. Closing an object does not
// detach links taken from it; a link outlives its object.
Close() error
}
An Object is a loaded but unattached set of programs and maps.
type ObjectSpec ¶
type ObjectSpec struct {
Name string
Programs []ProgramSpec
// Bytes is the compiled object. It is opaque here: authoring and
// compiling programs is this lane's work, but the encoding of an ELF
// is the loader's.
Bytes []byte
}
An ObjectSpec is a request to load one object.
type Observer ¶
type Observer interface {
Observe(Outcome)
}
An Observer receives one bounded record per hook invocation. It is called after the handler has returned, never from inside one: a fault handler does no logging beyond a fixed-size counter or ring slot, and formatting a string is not that.
type Outcome ¶
type Outcome struct {
// PartiallySubmitted means an earlier scheduling actuator succeeded before
// a later call failed. No driver rollback is claimed.
PartiallySubmitted bool
Policy string
Hook string
Consulted bool // the policy was asked
HadOpinion bool // the policy returned one
Submitted bool // the kfunc call was made and returned no error
DriverAttempted bool
DriverConflict bool
// Fallback is set when the driver's default behavior stands because
// something went wrong rather than because the policy declined.
Fallback bool
Reason string
Reorder Reorder
Region Region
// HandlerTime is the time spent inside the handler. Timings are
// reported in separate non-additive fields and an unmeasured one is
// [Unmeasured], never zero: zero is a real and different answer.
HandlerTime time.Duration
}
An Outcome is what happened to one hook invocation. It separates four things a single boolean would conflate: whether the policy had an opinion, whether that opinion was submitted to the driver, whether the driver recorded having taken it, and whether the driver recorded a collision.
DriverAttempted and DriverConflict are read back out of the context after the kfunc call. They are the driver's own record, not a Go-side flag, and they are the only evidence available that a decision reached the driver at all. Neither of them says the driver obeyed it.
type PMMDecision ¶
type PMMDecision struct {
PMM uint64
RootChunk uint64
Observed PMMSnapshot
Request PMMRequest
}
PMMDecision is uvm_bpf_pmm_decision_ctx_t, the context passed to gpu_block_access and gpu_block_activate.
type PMMRequest ¶
PMMRequest is nv_gpu_pmm_request_t. Destination and Position carry the policy's request; Attempted and Conflict are the driver's answer to it.
type PMMSnapshot ¶
PMMSnapshot is nv_gpu_pmm_snapshot_t, the driver's view of a root chunk at the moment the hook fired.
type PolicyBudget ¶
type PolicyBudget struct {
MaxSteps int
// contains filtered or unexported fields
}
A Budget bounds the work a fault-path handler may do. Fault-path handlers are bounded work by contract: fixed instruction budget, no unbounded loops, no blocking, no allocation. The Budget is the host-testable half of that -- the BPF verifier enforces the rest inside the kernel -- and a handler that exhausts it has its hook disabled rather than being allowed to run long.
The zero Budget permits nothing, so a handler reached without one stops at its first step instead of running unbounded.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/obs/internal/obsbpfpolicy"
)
func main() {
b := obsbpfpolicy.NewBudget(2)
fmt.Println(b.Step(2))
fmt.Println(b.Used())
}
Output: <nil> 2
func (*PolicyBudget) Reset ¶
func (b *PolicyBudget) Reset()
Reset returns the budget to full, for the next hook invocation.
func (*PolicyBudget) Step ¶
func (b *PolicyBudget) Step(n int) error
Step charges n units of work and reports ErrBudgetExceeded once the total passes the maximum. Once exceeded, every later Step also fails: a budget does not refill mid-handler.
type PolicyConfig ¶
type PolicyConfig struct {
// Limits are the driver's accepted attribute ranges.
Limits Limits
// Budget is the per-invocation step budget for a fault-path handler.
// A handler that exceeds it has its hook disabled.
Budget int
// Observer receives bounded records. It may be nil.
Observer Observer
// MaxOutcomes bounds retained host observations; zero uses 256.
MaxOutcomes int
// Clock measures handler time. Nil means handler time is
// [Unmeasured] rather than zero.
Clock func() time.Time
}
Config configures a Bridge.
type Position ¶
type Position uint64
Position selects an end of that list. Only the two ends are addressable; an arbitrary rank is not.
type PrefetchDecision ¶
PrefetchDecision is uvm_bpf_prefetch_decision_t. Attempted and Conflict are the driver's own record of whether a decision was submitted and whether it collided with another; a handler reads them and must not write them.
type PrefetchRequest ¶
type PrefetchRequest struct {
ID uint64
VASpace uint64
Region Region
// Decision is a host-model context. It must remain valid through
// completion. Never retain a live kernel fault-context pointer here:
// kernel prefetch requires its own verified asynchronous interface.
Decision *PrefetchDecision
}
A PrefetchRequest is one queued region to prefetch. ID identifies it for cancellation; a request already taken by the worker cannot be cancelled, which PrefetchWorker.Cancel reports rather than pretending otherwise.
type PrefetchResult ¶
type PrefetchResult struct {
ID uint64
Issued bool
Cancelled bool
Err error
// Latency is the time from submission to issue. It is [Unmeasured]
// unless the worker was given a clock.
Latency time.Duration
}
A PrefetchResult is what became of one request.
type PrefetchWorker ¶
type PrefetchWorker struct {
// contains filtered or unexported fields
}
A PrefetchWorker issues prefetch regions off the fault path.
Issuance is non-blocking by construction: PrefetchWorker.Submit never waits, and a full queue is reported to the caller rather than absorbed. Anything expensive belongs here and not in a handler, and the time it takes is reported separately from fault-handling time because the two overlap and must never be summed.
func NewPrefetchWorker ¶
func NewPrefetchWorker(k Kfuncs, depth int, clock func() time.Time) *PrefetchWorker
NewPrefetchWorker returns a worker with a bounded queue. The bound is the whole point: an unbounded queue turns a burst of faults into unbounded memory, and the fault path has nowhere to report that.
func (*PrefetchWorker) Cancel ¶
func (w *PrefetchWorker) Cancel(id uint64) bool
Cancel marks a request cancelled. It reports whether the cancellation arrived in time: a request the worker has already issued cannot be recalled, and saying otherwise would make a cancelled prefetch indistinguishable from one that never ran.
func (*PrefetchWorker) Close ¶
func (w *PrefetchWorker) Close()
Close stops the worker and waits for in-flight issuance to finish.
func (*PrefetchWorker) Results ¶
func (w *PrefetchWorker) Results() []PrefetchResult
Results returns the most recent completed requests, bounded by queue depth.
func (*PrefetchWorker) Start ¶
func (w *PrefetchWorker) Start()
Start begins issuing. A worker that is not started still accepts submissions up to its queue depth, so a handler never blocks on startup order.
func (*PrefetchWorker) Submit ¶
func (w *PrefetchWorker) Submit(req PrefetchRequest) bool
Submit queues a request. It never blocks. It reports false when the queue is full, when the worker is closed, or when the region is not a valid range; in every one of those cases nothing was queued and the caller knows it.
type ProgramSpec ¶
type ProgramSpec struct {
Name string // symbol name of the program
Section string // SEC() string, informational
Member string // struct_ops member this program binds to
}
A ProgramSpec is one BPF program within an object.
Section and Member are separate fields and are never derived from one another. In a struct_ops object the member a program binds to comes from the .struct_ops map initializer, not from the text after "struct_ops/" in the section name. The two agree for the memory table and disagree for at least one real scheduler object, where programs named gp_task_init, gp_bind, gp_destroy and gp_timeslice_control carry sections of those names while binding to members on_task_init, on_bind, on_task_destroy and on_timeslice_control. A loader that derives the member from the section attaches the wrong slot or none at all.
type RecordSink ¶
type RecordSink interface {
PushPolicyRecord(timestampNs int64, hook string, labels map[string]string)
}
A RecordSink receives a flight-recorder-shaped record. It is an interface rather than a direct dependency so the policy layer stays importable by anything, and so a record's shape is fixed here rather than by whoever happens to consume it.
type Region ¶
A Region is a half-open range of pages to prefetch, matching the first and outer members of uvm_bpf_prefetch_decision_t.
type Reorder ¶
type Reorder struct {
Destination Destination
Position Position
}
A Reorder is a request to move a root chunk to one end of one of the driver's two lists. It is the whole of what this interface can express: head and tail are values written into the request, there is no insert-after kfunc, and so strict eviction-list ordering is not expressible here at all. Rank-and-position reordering is.
type Report ¶
type Report struct {
Capabilities Capabilities
Hooks []HookStatus
Kfuncs []KfuncStatus
Types []TypeStatus
// LayoutError is set when a type BTF defines disagrees with the
// layout this package requires. It is fatal for attach even when
// every hook is present.
LayoutError error
}
A Report is the outcome of Discover: the capability matrix a handoff quotes and an attach path consults.
func Discover ¶
Discover records what a target actually provides. It never reports a hook as available on the strength of an identifier appearing in a header: a hook is available only when BTF defines its table, its context types match the required layout, and the kfuncs it actuates through are present and annotated.
Discovery is not an error when nothing is available. A target with no policy module returns a report in which every hook is absent, which is the expected result and the one an unpatched kernel must produce.
func (*Report) AnyHookAvailable ¶
AnyHookAvailable reports whether any hook can be attached at all.
func (*Report) Kfunc ¶
func (r *Report) Kfunc(name string) (KfuncStatus, bool)
Kfunc returns the status recorded for a named kfunc.
func (*Report) TableAvailable ¶
TableAvailable reports whether every member of a table is attachable.
type SchedAttributes ¶
type SchedAttributes struct {
TimesliceUS uint64
SetTimeslice bool
Interleave InterleaveLevel
SetInterleave bool
}
SchedAttributes are the time-slice-group attributes a policy may set on task init. Each has a companion Set flag rather than a sentinel value, because every numeric value in range is a legitimate request and there is no number left over to mean "unset".
func (SchedAttributes) String ¶
func (a SchedAttributes) String() string
func (SchedAttributes) Validate ¶
func (a SchedAttributes) Validate(l Limits) error
Validate checks every set attribute against the driver's accepted range before any kfunc call is made. Validation is not clamping: a request above the maximum is refused, and in particular a tenant asking for a longer timeslice than it is allowed does not silently receive the maximum.
type SchedPolicy ¶
type SchedPolicy interface {
// TaskInit returns the attributes to set for a newly initialized TSG.
// The returned attributes are validated before any of them is applied,
// and a validation failure applies none of them.
TaskInit(c *TaskInitContext, b *PolicyBudget) (SchedAttributes, error)
// Bind decides whether a channel bind is admitted.
Bind(c *BindContext, b *PolicyBudget) (BindDecision, error)
}
A SchedPolicy decides scheduling attributes. TaskInit is called on on_task_init and Bind on on_bind; both run on a driver path and are bounded work under the same rules as a memory hook.
type SinkObserver ¶
type SinkObserver struct {
Sink RecordSink
Clock func() int64
}
A SinkObserver forwards outcomes to a RecordSink as labelled records. Labels carry the four things worth separating after the fact: whether the policy had an opinion, whether it was submitted, whether the driver recorded taking it, and why the driver default stands if it does.
func (SinkObserver) Observe ¶
func (s SinkObserver) Observe(o Outcome)
Observe forwards one outcome.
type StructOpsSpec ¶
type StructOpsSpec struct {
Table string // BTF name of the table type, e.g. "gpu_mem_ops"
MapName string
Programs map[string]string // member -> program name
}
A StructOpsSpec is a request to register one struct_ops map against one table. Programs maps member name to program name, reproducing the .struct_ops initializer.
func (StructOpsSpec) RequiredKfuncs ¶
func (s StructOpsSpec) RequiredKfuncs() []string
RequiredKfuncs returns the kfuncs a struct_ops request will actuate through, so they can be checked against BTF before the object is loaded rather than discovered missing inside a fault handler.
func (StructOpsSpec) Validate ¶
func (s StructOpsSpec) Validate(obj ObjectSpec) error
Validate checks a struct_ops request against the table it names before any of it reaches the kernel: the table must be one this package knows, every member must exist on it, and every named program must exist in the object.
It deliberately does not check that Section agrees with Member. They are allowed to disagree, and a validator that required agreement would reject a correct scheduler object.
type TaskDestroyContext ¶
TaskDestroyContext is struct nv_gpu_task_destroy_ctx.
type TaskInitContext ¶
type TaskInitContext struct {
TSGID uint64
EngineType uint32
DefaultTimeslice uint64
DefaultInterleave uint32
RunlistID uint32
}
TaskInitContext is struct nv_gpu_task_init_ctx.
type TimesliceControlContext ¶
type TimesliceControlContext struct {
TSGID uint64
RequestedTimesliceUS uint64
EngineType uint32
RunlistID uint32
HClient uint32
HTSG uint32
GPUInstance uint32
Phase uint32
}
TimesliceControlContext is struct nv_gpu_timeslice_control_ctx.
type Timings ¶
type Timings struct {
FaultHandling time.Duration
PrefetchWorker time.Duration
Transfer time.Duration
GPUCompute time.Duration
}
Timings separates the four costs a policy path can incur. They are not additive -- prefetch worker time overlaps fault handling, transfer overlaps compute -- so they are never summed into a single number.
func UnmeasuredTimings ¶
func UnmeasuredTimings() Timings
UnmeasuredTimings returns a Timings in which nothing has been measured.
type TypeAbsentError ¶
type TypeAbsentError struct{ Name string }
A TypeAbsentError reports that BTF does not define a type. It is the expected answer on every target without the out-of-tree policy module, so it is a distinct error rather than a generic failure: callers branch on it.
func (*TypeAbsentError) Error ¶
func (e *TypeAbsentError) Error() string
type TypeLayout ¶
type TypeLayout struct {
Name string
Size uintptr
Fields []FieldLayout
}
TypeLayout is the size of a context type and the offsets of the members whose placement is load-bearing. It is deliberately not a full description: only members the driver and the policy layer both address are listed, since those are the ones a drift would break.
func GoLayouts ¶
func GoLayouts() []TypeLayout
GoLayouts returns the layout the Go declarations in this package actually have, as the compiler arranged them. Compare it with InventoryLayouts to find a Go struct that has drifted from the C one, and with a target's BTF to find a driver that has drifted from both.
func InventoryLayouts ¶
func InventoryLayouts() []TypeLayout
InventoryLayouts returns the layout every context type is required to have, transcribed from the _Static_assert declarations in the driver's own headers. These are constants in the source sense -- they are what the C side enforces at compile time -- and they are held separately from GoLayouts on purpose: a Go struct edited until the two agree has been edited until the test passes, so the numbers a test compares against must not be derived from the structs under test.
func (TypeLayout) String ¶
func (t TypeLayout) String() string
type TypeStatus ¶
A TypeStatus is one context type's availability and whether its layout matched. Layout mismatch is not absence: the type exists and disagrees, which is a harder failure than not being there.