Documentation
¶
Overview ¶
Package metalheap provides a zero-cgo wrapper around Metal metal.MTLHeap sub-allocation, resource aliasing, purgeability control, and metal.MTLResidencySet bulk residency management.
A Heap wraps either a placement heap (metal.MTLHeapTypePlacement, the default) with an internal alignment-aware free-list allocator, or an automatic heap (metal.MTLHeapTypeAutomatic) delegated to Metal's own sub-allocator.
Basic usage:
dev := metal.MTLCreateSystemDefaultDevice()
h, err := metalheap.NewHeap(dev, metalheap.Config{
Size: 16 << 20, // 16 MiB
Type: metal.MTLHeapTypePlacement,
StorageMode: metal.MTLStorageModeShared,
})
if err != nil {
return err
}
defer h.Close()
buf, err := h.AllocBuffer(4096)
if err != nil {
return err
}
defer h.Free(buf)
Use NewResidency to stage heaps or buffers into a metal.MTLResidencySet and commit them in bulk before GPU submission.
The zero values of Heap, Buffer, and Residency are not usable; construct them with NewHeap, Heap.AllocBuffer/Heap.AllocAt, and NewResidency respectively.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/metal"
"github.com/tmc/apple/x/metalheap"
)
func main() {
dev := metal.MTLCreateSystemDefaultDevice()
if dev.GetID() == 0 {
fmt.Println("unsupported")
return
}
h, err := metalheap.NewHeap(dev, metalheap.Config{
Size: 1 << 20, // 1 MiB
Type: metal.MTLHeapTypePlacement,
StorageMode: metal.MTLStorageModeShared,
Label: "example-heap",
})
if err != nil {
fmt.Println("error:", err)
return
}
defer h.Close()
buf, err := h.AllocBuffer(4096)
if err != nil {
fmt.Println("error:", err)
return
}
defer h.Free(buf)
fmt.Printf("offset=%d length=%d\n", buf.Offset(), buf.Length())
}
Output: offset=0 length=4096
Index ¶
- Variables
- type Buffer
- func (b *Buffer) Alignment() uint
- func (b *Buffer) AllocatedSize() uint
- func (b *Buffer) Bytes() []byte
- func (b *Buffer) Contents() unsafe.Pointer
- func (b *Buffer) Free() error
- func (b *Buffer) IsAliasable() bool
- func (b *Buffer) Length() uint
- func (b *Buffer) MTLBuffer() metal.MTLBuffer
- func (b *Buffer) MakeAliasable() error
- func (b *Buffer) Offset() uint
- type Config
- type Heap
- func (h *Heap) AllocAt(length, offset uint) (*Buffer, error)
- func (h *Heap) AllocBuffer(length uint) (*Buffer, error)
- func (h *Heap) Close() error
- func (h *Heap) Free(b *Buffer) error
- func (h *Heap) MTLHeap() metal.MTLHeap
- func (h *Heap) MakeAliasable(b *Buffer) error
- func (h *Heap) PurgeableState() (metal.MTLPurgeableState, error)
- func (h *Heap) SetPurgeable(state metal.MTLPurgeableState) (metal.MTLPurgeableState, error)
- func (h *Heap) Size() uint
- func (h *Heap) SizeAndAlign(length uint) metal.MTLSizeAndAlign
- func (h *Heap) Stats() Stats
- func (h *Heap) Type() metal.MTLHeapType
- type Residency
- func (r *Residency) Add(allocs ...metal.MTLAllocation) error
- func (r *Residency) AddBuffer(b *Buffer) error
- func (r *Residency) AddHeap(h *Heap) error
- func (r *Residency) AllocatedSize() uint64
- func (r *Residency) AllocationCount() uint
- func (r *Residency) Close() error
- func (r *Residency) Commit() error
- func (r *Residency) Contains(alloc metal.MTLAllocation) bool
- func (r *Residency) EndResidency() error
- func (r *Residency) MTLResidencySet() metal.MTLResidencySet
- func (r *Residency) Remove(allocs ...metal.MTLAllocation) error
- func (r *Residency) RemoveAll() error
- func (r *Residency) RequestResidency() error
- type ResidencyConfig
- type Stats
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrUnsupported is returned when the Metal device is nil or cannot create // the requested heap or residency set. ErrUnsupported = errors.New("metalheap: unsupported metal device") // ErrClosed is returned when a method is called on a nil or closed Heap or // Residency. ErrClosed = errors.New("metalheap: closed") // ErrInvalidConfig is returned when Config contains invalid parameters. ErrInvalidConfig = errors.New("metalheap: invalid config") // ErrOutOfMemory is returned when a heap cannot satisfy an allocation. ErrOutOfMemory = errors.New("metalheap: out of heap memory") // ErrInvalidOffset is returned when AllocAt receives an unaligned or // out-of-bounds offset. ErrInvalidOffset = errors.New("metalheap: invalid offset") // ErrInvalidBuffer is returned when a Buffer is nil, already freed, or // belongs to a different Heap. ErrInvalidBuffer = errors.New("metalheap: invalid buffer") // ErrWrongHeapType is returned when an operation requires a different // MTLHeapType (for example, AllocAt on an automatic heap). ErrWrongHeapType = errors.New("metalheap: incompatible heap type") )
Functions ¶
This section is empty.
Types ¶
type Buffer ¶
type Buffer struct {
// contains filtered or unexported fields
}
Buffer is a sub-allocated metal.MTLBuffer backed by a Heap.
func (*Buffer) AllocatedSize ¶
AllocatedSize returns the aligned span size reserved in the heap in bytes.
func (*Buffer) Bytes ¶
Bytes returns a byte slice backed by the buffer's CPU-accessible memory, or nil if b is nil, freed, empty, or backed by private storage.
func (*Buffer) Contents ¶
Contents returns the CPU pointer to the buffer's storage, or nil if b is nil, freed, or backed by private storage.
func (*Buffer) IsAliasable ¶
IsAliasable reports whether Heap.MakeAliasable has been called on b.
func (*Buffer) MTLBuffer ¶
MTLBuffer returns the underlying metal.MTLBuffer, or nil if b is nil or freed.
func (*Buffer) MakeAliasable ¶
MakeAliasable marks b's backing heap memory as reusable by future heap allocations.
type Config ¶
type Config struct {
// Size is the total backing capacity of the heap in bytes. Must be > 0.
Size uint
// Type selects the heap placement strategy. Supported values are
// metal.MTLHeapTypePlacement and metal.MTLHeapTypeAutomatic.
// The zero value (MTLHeapTypeAutomatic) creates an automatic heap; set
// MTLHeapTypePlacement explicitly for placement sub-allocation.
Type metal.MTLHeapType
// StorageMode sets the heap storage mode (default: MTLStorageModeShared).
StorageMode metal.MTLStorageMode
// CPUCacheMode sets the CPU cache mode (default: MTLCPUCacheModeDefaultCache).
CPUCacheMode metal.MTLCPUCacheMode
// HazardTrackingMode sets the hazard tracking mode
// (default: MTLHazardTrackingModeDefault).
HazardTrackingMode metal.MTLHazardTrackingMode
// Label is an optional debug label attached to the underlying MTLHeap.
Label string
}
Config configures a Heap backed by a metal.MTLHeap.
type Heap ¶
type Heap struct {
// contains filtered or unexported fields
}
Heap wraps a metal.MTLHeap and provides alignment-aware buffer sub-allocation, free-list reuse, aliasing, and purgeability control.
func (*Heap) AllocAt ¶
AllocAt creates a buffer of length bytes at an exact byte offset on a placement heap.
Offset must be a multiple of the alignment returned by HeapBufferSizeAndAlignWithLengthOptions and fit within the heap's size. If the span is currently free in the free list it is reserved; if it overlaps an existing or aliased span, AllocAt still succeeds so callers can perform explicit offset aliasing.
func (*Heap) AllocBuffer ¶
AllocBuffer sub-allocates a buffer of at least length bytes from h.
On a placement heap, AllocBuffer queries HeapBufferSizeAndAlignWithLengthOptions to satisfy alignment and reserves a span from the internal free list. On an automatic heap, it delegates placement to Metal.
func (*Heap) Close ¶
Close releases the underlying metal.MTLHeap. Close is idempotent.
func (*Heap) Free ¶
Free releases b's Metal buffer handle and, for placement heaps, returns its aligned span to the free list and coalesces adjacent free spans.
func (*Heap) MTLHeap ¶
MTLHeap returns the underlying metal.MTLHeap, or nil if h is nil or closed.
func (*Heap) MakeAliasable ¶
MakeAliasable marks b's backing memory as aliasable via metal.MTLResource.MakeAliasable.
func (*Heap) PurgeableState ¶
func (h *Heap) PurgeableState() (metal.MTLPurgeableState, error)
PurgeableState queries the heap's current purgeable state without modifying it.
func (*Heap) SetPurgeable ¶
func (h *Heap) SetPurgeable(state metal.MTLPurgeableState) (metal.MTLPurgeableState, error)
SetPurgeable transitions the heap's purgeable state and returns the previous state.
Valid states include metal.MTLPurgeableStateNonVolatile, metal.MTLPurgeableStateVolatile, metal.MTLPurgeableStateEmpty, and metal.MTLPurgeableStateKeepCurrent.
func (*Heap) SizeAndAlign ¶
func (h *Heap) SizeAndAlign(length uint) metal.MTLSizeAndAlign
SizeAndAlign returns the Metal driver's required heap size and alignment for a buffer of length bytes with the heap's resource options.
func (*Heap) Type ¶
func (h *Heap) Type() metal.MTLHeapType
Type returns the heap's metal.MTLHeapType.
type Residency ¶
type Residency struct {
// contains filtered or unexported fields
}
Residency manages bulk metal.MTLResidencySet staging and commits for heaps and buffers.
func NewResidency ¶
func NewResidency(dev metal.MTLDevice, cfg ResidencyConfig) (*Residency, error)
NewResidency creates a new metal.MTLResidencySet on dev.
Example ¶
package main
import (
"fmt"
"github.com/tmc/apple/metal"
"github.com/tmc/apple/x/metalheap"
)
func main() {
dev := metal.MTLCreateSystemDefaultDevice()
if dev.GetID() == 0 {
fmt.Println("unsupported")
return
}
h, err := metalheap.NewHeap(dev, metalheap.Config{
Size: 1 << 20,
Type: metal.MTLHeapTypePlacement,
StorageMode: metal.MTLStorageModeShared,
})
if err != nil {
fmt.Println("error:", err)
return
}
defer h.Close()
rs, err := metalheap.NewResidency(dev, metalheap.ResidencyConfig{
Label: "example-residency",
InitialCapacity: 4,
})
if err != nil {
fmt.Println("error:", err)
return
}
defer rs.Close()
if err := rs.AddHeap(h); err != nil {
fmt.Println("error:", err)
return
}
if err := rs.Commit(); err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("count=%d resident=%v\n", rs.AllocationCount(), rs.AllocatedSize() >= uint64(h.Size()))
}
Output: count=1 resident=true
func (*Residency) Add ¶
func (r *Residency) Add(allocs ...metal.MTLAllocation) error
Add stages one or more Metal allocations (heaps, buffers, or textures) to join the residency set. Call Residency.Commit to apply staged changes.
func (*Residency) AddBuffer ¶
AddBuffer stages b's underlying metal.MTLBuffer to join the residency set. Call Residency.Commit to apply staged changes.
func (*Residency) AddHeap ¶
AddHeap stages h's underlying metal.MTLHeap to join the residency set. Call Residency.Commit to apply staged changes.
func (*Residency) AllocatedSize ¶
AllocatedSize returns the total resident memory in bytes reported by Metal for the committed residency set.
func (*Residency) AllocationCount ¶
AllocationCount returns the number of committed allocations in the set.
func (*Residency) Close ¶
Close ends residency if active and releases the underlying metal.MTLResidencySet. Close is idempotent.
func (*Residency) Contains ¶
func (r *Residency) Contains(alloc metal.MTLAllocation) bool
Contains reports whether alloc is currently in the committed residency set.
func (*Residency) EndResidency ¶
EndResidency informs Metal that the residency set's allocations no longer need to remain resident.
func (*Residency) MTLResidencySet ¶
func (r *Residency) MTLResidencySet() metal.MTLResidencySet
MTLResidencySet returns the underlying metal.MTLResidencySet, or nil if r is nil or closed.
func (*Residency) Remove ¶
func (r *Residency) Remove(allocs ...metal.MTLAllocation) error
Remove stages one or more allocations to leave the residency set. Call Residency.Commit to apply staged changes.
func (*Residency) RemoveAll ¶
RemoveAll stages all allocations for removal from the residency set. Call Residency.Commit to apply staged changes.
func (*Residency) RequestResidency ¶
RequestResidency asks Metal to make the committed allocations resident.
type ResidencyConfig ¶
type ResidencyConfig struct {
// Label is an optional debug label attached to the residency set.
Label string
// InitialCapacity hints the initial allocation capacity so Metal avoids
// resizing the internal table when staging allocations. Zero uses Metal's
// default starting capacity.
InitialCapacity uint
}
ResidencyConfig configures a Residency set backed by a metal.MTLResidencySet.
type Stats ¶
type Stats struct {
// Size is the configured heap size in bytes.
Size uint
// AllocatedSize is the Metal driver's current allocated size in bytes.
AllocatedSize uint
// UsedBytes is the sum of aligned byte spans currently allocated on a
// placement heap, or MTLHeap.UsedSize on an automatic heap.
UsedBytes uint
// FreeBytes is the remaining free capacity in bytes.
FreeBytes uint
// ActiveBuffers is the number of live sub-allocated buffers not yet freed.
ActiveBuffers int
// FreeBlocks is the number of coalesced free spans in the placement
// free list (0 for automatic heaps).
FreeBlocks int
// TotalAllocs is the cumulative number of successful allocations.
TotalAllocs uint64
// TotalFrees is the cumulative number of successful Free calls.
TotalFrees uint64
// ReusedAllocs is the number of placement allocations satisfied from a
// previously freed span.
ReusedAllocs uint64
}
Stats reports point-in-time accounting for a Heap.