metalheap

package
v0.6.21 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: MIT Imports: 6 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Rendered for darwin/amd64

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

Examples

Constants

This section is empty.

Variables

View Source
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) Alignment

func (b *Buffer) Alignment() uint

Alignment returns the required heap alignment for this buffer in bytes.

func (*Buffer) AllocatedSize

func (b *Buffer) AllocatedSize() uint

AllocatedSize returns the aligned span size reserved in the heap in bytes.

func (*Buffer) Bytes

func (b *Buffer) Bytes() []byte

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

func (b *Buffer) Contents() unsafe.Pointer

Contents returns the CPU pointer to the buffer's storage, or nil if b is nil, freed, or backed by private storage.

func (*Buffer) Free

func (b *Buffer) Free() error

Free releases b and returns its placement span (if any) to the backing heap.

func (*Buffer) IsAliasable

func (b *Buffer) IsAliasable() bool

IsAliasable reports whether Heap.MakeAliasable has been called on b.

func (*Buffer) Length

func (b *Buffer) Length() uint

Length returns the logical length of the buffer in bytes.

func (*Buffer) MTLBuffer

func (b *Buffer) MTLBuffer() metal.MTLBuffer

MTLBuffer returns the underlying metal.MTLBuffer, or nil if b is nil or freed.

func (*Buffer) MakeAliasable

func (b *Buffer) MakeAliasable() error

MakeAliasable marks b's backing heap memory as reusable by future heap allocations.

func (*Buffer) Offset

func (b *Buffer) Offset() uint

Offset returns the byte offset of the buffer within its backing heap.

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 NewHeap

func NewHeap(dev metal.MTLDevice, cfg Config) (*Heap, error)

NewHeap allocates a Metal heap configured by cfg on dev.

func (*Heap) AllocAt

func (h *Heap) AllocAt(length, offset uint) (*Buffer, error)

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

func (h *Heap) AllocBuffer(length uint) (*Buffer, error)

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

func (h *Heap) Close() error

Close releases the underlying metal.MTLHeap. Close is idempotent.

func (*Heap) Free

func (h *Heap) Free(b *Buffer) error

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

func (h *Heap) MTLHeap() metal.MTLHeap

MTLHeap returns the underlying metal.MTLHeap, or nil if h is nil or closed.

func (*Heap) MakeAliasable

func (h *Heap) MakeAliasable(b *Buffer) error

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) Size

func (h *Heap) Size() uint

Size returns the heap's total capacity in bytes.

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) Stats

func (h *Heap) Stats() Stats

Stats returns a snapshot of the heap's memory and allocator statistics.

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

func (r *Residency) AddBuffer(b *Buffer) error

AddBuffer stages b's underlying metal.MTLBuffer to join the residency set. Call Residency.Commit to apply staged changes.

func (*Residency) AddHeap

func (r *Residency) AddHeap(h *Heap) error

AddHeap stages h's underlying metal.MTLHeap to join the residency set. Call Residency.Commit to apply staged changes.

func (*Residency) AllocatedSize

func (r *Residency) AllocatedSize() uint64

AllocatedSize returns the total resident memory in bytes reported by Metal for the committed residency set.

func (*Residency) AllocationCount

func (r *Residency) AllocationCount() uint

AllocationCount returns the number of committed allocations in the set.

func (*Residency) Close

func (r *Residency) Close() error

Close ends residency if active and releases the underlying metal.MTLResidencySet. Close is idempotent.

func (*Residency) Commit

func (r *Residency) Commit() error

Commit applies all staged additions and removals to the residency set.

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

func (r *Residency) EndResidency() error

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

func (r *Residency) RemoveAll() error

RemoveAll stages all allocations for removal from the residency set. Call Residency.Commit to apply staged changes.

func (*Residency) RequestResidency

func (r *Residency) RequestResidency() error

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL