Commit Graph
55 Commits
Author SHA1 Message Date
Anees Iqbal 402b7463a9 🐎 Restore the write-combined spans: they take, and the encode was theirs
Reverts 0825b1ea2, restoring 0afc30f37, e8d04b187 and ea13ccbca. A write-combined
mapping of the region does take: the region's descriptor is physically
contiguous, and xnu's fault path maps such an object's pages in its own cache
mode (vm_fault's pmap_map_block_addr, read from the public xnu source), which
the earlier reading missed. The page-table probe that seemed to agree saw only
the processes on the CPUs at its instant, not the bench.

Measured on the Radeon 780M host, draws.10k's encode: 9.2-9.5 ms at the base,
7.7 ms with the slabs in the process's own pages alone (936e3968d's set), and
1.05-1.3 ms with the spans write-combined as well (0afc30f37's and ea13ccbca's
sets). The kext's comment and the design doc say why, and docs/lessons.md the
probe's trap.

For the guest, as 0afc30f37: a queue's submission ring starts 3840 bytes into
its block, the kext's Alloc takes a third input and its feature word holds
1 << 7.
2026-11-07 08:27:28 -08:00
Anees Iqbal c08c19f377 🔥 Drop the write-combined spans: no user mapping of the region can be
Reverts 0afc30f37, e8d04b187 and ea13ccbca. On x86-64 xnu every mapping of
the region in a guest process is uncached, whatever cache mode the kext asks:
vm_fault enters each page with no cache flags, and the pmap gives a page it
does not manage PCD alone, the guest PAT's UC- (read from the public xnu
source: pmap_get_cache_attributes and vm_fault's pmap_enter wrappers). Measured
on the Radeon 780M host with both the region's own descriptor and one of the
write-combined spans' own: every page of a process's over BAR 2 was PCD alone,
none PAT and PCD, and draws.10k encoded as fast as with the spans write-back.

For the guest, a queue's submission ring starts its block again, the kext's
Alloc takes two inputs and its feature word drops 1 << 7; the slabs in the
process's own pages (72c09eddc) carry the measured gains. The design doc says
why the region is uncached, as measured.
2026-11-07 08:27:28 -08:00
Anees Iqbal b396a9b33a ✅ Refill the write-combined test's memory before its second region
The test's first region zeroed its rings in the same memory, so the second region's
check that its ring block's head is untouched read those zeros.
2026-11-07 08:27:28 -08:00
Anees Iqbal fac9e06ca7 🐎 Map the bytes the guest only writes write-combined
The guest's kernel maps the device region uncached whatever the kext asks:
xnu's pmap sets PCD on every page it does not manage, and the region is no RAM
of the guest's. An AMD host applies the guest's memory type (Intel's EPT
ignores it), so on the Radeon 780M host the guest's stores there ran at
13 MB/s and draws.10k spent 9.1 ms encoding against 0.5 ms on the RTX 5080.

The kext's Alloc now takes a third input, the byte from which the process's
mapping of the block is write-combined (kIOMapWriteCombineCache, PAT index 6),
behind a kext feature bit. The bundle puts there what it only writes: a
submission ring's data, which now starts its block's second page with the
ring's header ending the first, write-back as before, since the host writes
it too and the writer reads it; command buffers' bodies; and a library's
staging chunks, past the page of acks it reads. The ring writer fences its
stores (sfence) before it publishes a message, so write-combined stores reach
the host before the producer index that names them, as a release store
orders write-back ones. ICB slots stay write-back: their setters read fields
back and OR bits in with locked operations, which write-combined memory does
not keep atomic.

For the guest, a queue's submission ring now starts 3840 bytes into its block
where the kext has the feature; the wire is unchanged.
2026-11-07 08:27:28 -08:00
Anees Iqbal 11672a2a5f 🐛 Carry only the options the host takes on heap and buffer creates
The GL renderer makes its no-copy buffers with resource option bit 20
(0x100000), a hint for the device's driver. The bundle passed every bit
to the host, and the host's runtime refuses a buffer with a bit Metal
gives no meaning, so each such buffer was refused (measured: macOS 26.6.1
on the RTX 5080 host).

Heap and buffer creates now carry only the CPU cache, storage and hazard
tracking modes, and Metal's private bit 24, which the host takes as Metal
does.

A buffer outside a heap now answers resourceOptions with its three modes
alone. On macOS 26.7.1 the AMD 5300M and the Intel 630 drop each of bits
10 to 31 from the answer, for length and no-copy buffers alike: they give
0x200, 0x210 and 0x220 for Shared, Managed and Private.
2026-11-07 06:57:51 -08:00
Anees Iqbal 77f12120d4 🐛 Answer nil for a texture with no GPU address left
A device-placed texture and a Managed texture's GPU copy take a GPU address
of the context's range, which runs out at address-space exhaustion. Their
creates took the address unchecked and posted 0, where a heap, a buffer and
every other create that picks an address answer no object.

What changes for the guest: at exhaustion such a texture is nil, as Metal
answers one it cannot place, and nothing is posted; its resource id goes back
for the next texture. A texture in a heap takes no address and is unchanged.

Test: test_creates_with_no_address_post_nothing fails at the base, where both
creates post with address 0.
2026-11-05 21:59:36 -08:00
Anees Iqbal 7defb7f533 🆕 Make mesh render pipelines and draw them, as an x86 Mac's Metal
For the guest: where the device takes MESH_PIPELINES, every
newRenderPipelineStateWithMeshDescriptor: form makes a mesh render pipeline. It
used to answer nil and an unsupported error. The render encoders send the object
and mesh stages' bindings and drawMeshThreadgroups:, drawMeshThreads: and the
indirect form, and the SPI's supportsMeshShaders answers YES. Without the
feature they answer as before. The state answers its object and mesh limits as
the host's platform answers them (maxTotalThreadgroupsPerMeshGrid NSUIntegerMax
past 32 bits) and the threadgroup sizes its descriptor required.

Measured with guest/bundle/tools/oracle/oracle_mesh, plain Metal, on the AMD
Radeon Pro 5300M and the Intel UHD Graphics 630 (macOS 26.7.1, 25G241) and the
M3 Max (macOS 27.0.1, 26A434), the creators now end the process where the x86
Macs' Metal does, with their words:
- supportIndirectCommandBuffers YES, on the 5300M and the 630 (the M3 Max makes
  it): "validateWithDevice:1884: failed assertion `Mesh Render Pipeline
  Descriptor Validation\nUse of mesh shader pipelines in indirect command
  buffers is not supported by this device.\n'"
- no mesh function, on all three: "...\nmeshFunction must not be nil.\n'"
- no fragment function while rasterizing, on all three: "...\nfragmentFunction
  must not be nil.\n'"
So no mesh pipeline supports indirect command buffers, and indirect commands
carry no mesh draw. This matches the families: supportsFamily: answers no for
Apple7 to Apple9 on the x86 Macs and on the device, and the SPI's
supportsMeshShadersInICB answers NO on the x86 Macs and the device (YES on the
M3 Max).

They refuse before the host is asked, in the x86 Macs' compiler's domain
(CompilerError):
- a payload past 16384 bytes, code 2, "payloadMemoryLength property of
  MTLMeshRenderPipelineDescriptor (16385 bytes) exceeds maximum supported by
  this device (16384 bytes)";
- a stage maximum past the device's 1024 threads, code 2, the 5300M's
  "maxThreadsPerThreadgroup pipeline descriptor value (2048) exceeds maximum
  supported (1024)\n" (the 630 makes it, the M3 Max refuses it);
- a vertex function as the mesh function, code 2, "RasterizationEnabled is
  false but the vertex shader's return type is not void";
- any other function of another stage, code 1. The x86 Macs answer the
  crashed compiler's XPC words; ours are the validation layer's;
- a mesh function as the object function, code 1, which the x86 Macs make
  and the M3 Max refuses;
- an archive miss under MTLPipelineOptionFailOnBinaryArchiveMiss, code 2,
  "Unable to find function \"f_col\" in binary archives. \n ". It names the
  fragment function, else the mesh function. An x86 archive holds no mesh
  pipeline, so every create naming an archive misses.

The creators with a reflection answer RgfxMeshPipelineReflectionOf's, the
reflection of the pipeline's functions, as the render pipeline creators answer
theirs.
2026-11-05 21:59:35 -08:00
Anees Iqbal b08d7badba ✅ Pin x86 Metal's rule for which archive slices it reads
Both x86 Macs read a binary archive's slice bytes only where the file holds the
device's own slice (its CPU type and subtype): then that slice and the AIR
slice are read, and either one junked is "an invalid format"; a file whose
slices are none of the device's is an archive of no keys, junk or not (AMD
5300M and Intel 630, macOS 26.7.1: oracle_bundle archive.slices, 21 files of
recombined and junked slices). No Metal slice is the device's, whose archives
are its own format, so the bundle, which never reads a Metal archive's slices,
already answers so; a junk AIR slice beside another GPU's slice now has a test.
2026-11-05 21:59:34 -08:00
Anees Iqbal a10e86b369 🆕 Take resource ids from chunks of 16 in the bundle
The kext hands out chunks of 16 texture resource ids where it takes
SMALL_ID_CHUNKS (bit 23). The bundle now keeps its ids by small chunk, each
small chunk's free ids in a 16-bit mask, and takes each chunk from the kext
as the size its feature word says: 16 ids with bit 23, else 64, a chunk of 64
being four small chunks. A chunk not aligned to its size, past the pool, or
over a small chunk the process holds is no chunk.

Until the kext takes bit 23 its chunks are 64 ids, and the bundle takes and
hands out ids as before.
2026-11-05 21:59:33 -08:00
Anees Iqbal 0b8051bc9d 🐛 Make a binary archive of a whole metallib as x86 Metal does
A guest app that makes a binary archive from a .metallib's URL now gets an
archive, holding none of the device's compiles, where the bundle answered nil
and "has an invalid format". Both x86 Macs' Metal makes one (AMD 5300M and
Intel 630, macOS 26.7.1; oracle_bundle archive.metallib). Bytes of the magic
MTLB whose header states another file size stay no archive, as the bundle reads
a fat file cut short.
2026-11-05 21:59:33 -08:00
Anees Iqbal 71a895ec3a 🐛 Read fat 0xcafebabe files as Metal's binary archives
The guest's IconRendering opens its binary.metallib, a fat file of magic
0xcafebabe and 18 slices of other GPUs, as a binary archive. The bundle read
only its own format and Metal's 0xcbfebabe, so it answered nil and "has an
invalid format". Metal reads the fat files of 0xcafebabe alike: on the AMD
5300M and Intel 630 under macOS 26.7.1 (oracle_bundle archive.*), that file
and an archive the device wrote with its magic changed each make an archive of
no keys with no error, and a file of no slices is an invalid format.

What the guest sees now: such a file makes an archive with no keys, which
misses every lookup, as another GPU's archive does.
2026-11-05 21:59:32 -08:00
Anees Iqbal 8d53659fbd 🐛 Name every MTLDataType in a constant's type error as Metal does
A function made with a constant value of another type fails with Metal's
words, which name both types. The bundle named only the constant types (the
scalars and vectors) and printed any other value, a matrix, a texture or a
pipeline among them, as MTLDataType(N). Metal names every value of the enum
"MTLDataType" and its name in MTLDataType.h (measured with oracle_names on the
AMD Radeon Pro 5300M and the Intel UHD Graphics 630, macOS 26.7.1, each of the
95 values set for an int constant).

What the guest sees: the error's description names a value of a type no
function constant takes as Metal does ("... has type MTLDataTypeFloat4x4").
A value outside the enum still prints as MTLDataType(N).
2026-11-05 21:59:31 -08:00
Anees Iqbal f2f96a2479 🆕 Lay heaped slabs in the process's own superpages
The region gives an app about 440 MiB of slabs, past which its buffers'
creates fail. Where the host makes heaps over pages blocks (HEAP_OVER_PAGES)
and the kext wires them (PagesBlock), a heaped class's 2 MiB slab is now a
superpage of the process's own, one run of guest RAM, wired into a pages
block and made one HEAP_OVER_PAGES, its buffers placed in it as in a region
slab's heap: BUFFER_AT_OFFSET, and BUFFER_MANAGED_AT_OFFSET where the device
took MANAGED_AT_OFFSET. On the RTX 5080 such a heap takes 13.4 us and a
placed 4 KiB buffer 1.93 us, where a no-copy buffer over the block's view
took 65-75 us. A larger dedicated slab, which would be more than one run,
and a slab where the kernel has no superpage to give or the kext no pages
block, stay the region's. RgfxSlabs asks the first source before the
region's for each new slab, and a slab keeps the source it came from.
2026-11-05 21:59:27 -08:00
Anees Iqbal 2b1b29a759 🐛 Stream each library through a window made for it
A process's first library over 8 KiB took a staging window of 64 MiB and kept
it for the process's life. On a busy desktop on the RTX 5080 host, nine
processes held 576 of the 731 MiB of the region outside WindowServer's
reserve that way (mediaanalysisd held nothing else), so the region ran out at
41 processes. From there, libraries, buffers and queue rings came back nil,
and Games, Photos, Photo Booth, Maps, the Dock's extras, NotificationCenter
and WebKit's GPU process crashed.

The window is now made for one stream and sized to its library: as few
chunks of at most 32 MiB as hold it, split evenly in whole pages, and a
second block only where there are two or more chunks. It goes back to the
region once the host has acked every chunk. Where the region refuses it,
smaller chunks are asked for, down to a page, so a library is made while any
room for three pages is left. A window whose chunk the host never acks is
kept, so nothing the host may still read is given out again.

The stream moves to RgfxLibraryStream.cpp, so the serialiser check covers it
against a host of its own: the shapes, the fallbacks and their bytes and
order, the window given back, and one kept when an ack never comes.
2026-11-05 21:59:27 -08:00
Anees Iqbal c5f49a295f 🆕 Send a render pass's visibility result buffer from the bundle
fillRenderPass carried no visibilityResultBuffer, so the host met each
setVisibilityResultMode:offset: of a mode in a pass with no buffer and failed
the command buffer. A render and a parallel render pass whose descriptor holds
one of our buffers now send it after their colour records and sample positions,
with the descriptor's visibilityResultType where its class answers it (macOS
26). The buffer is noted as the command buffer's write, as an attachment is,
so a copy of app memory or of an IOSurface under it takes the GPU's results
back and the buffer is kept to the completion.
2026-11-05 21:59:26 -08:00
Anees Iqbal d7adb17838 🆕 Ask the kext for pages blocks and post buffers over them
The bundle's half of PagesBlock's plumbing, which no-copy buffers and
fix-shared-mem's guest-RAM slabs both build on, as its own commit.

RgfxRegion gains a pages block source: acquirePages asks it for the block of
the runs of the pages under an address range, which the kext wires for the
block's life. The block's pointer is null, since the process never maps a
pages block, and a block the region does not hold goes back through the
block source's release, as a surface block does. The device sets the source
to the kext's PagesBlock call (0x10e) only where the kext's own word holds
PagesBlock and the device's word holds PAGES_BUFFERS.

RgfxSerializer::createBufferOverPages posts BUFFER_OVER_PAGES. It picks the
GPU address and owns it as createBufferOverHostMemory does; the pick holds
the span from the page the buffer starts in, and the buffer's address keeps
its pointer's offset in that page, as Metal's no-copy buffer keeps its
pointer's. The answer's gpu_address is the pick, which releaseAddress gives
back; with an offset of 0 it is the buffer's address too.
2026-11-05 21:59:26 -08:00
Anees Iqbal 265c74e3d9 🐛 Hand the contexts 1024 ranges of GPU addresses, not 32
The kext gave each process a context in one of 32 slots of 2 TiB, and refused
the 33rd: on the RTX 5080 host 17 processes held one on an idle desktop, and
opening the system's apps refused Freeform, the 13th, and every app after it
(57 processes, 25 refused). A refused process got a device whose every create
answered nil, and Maps and Journal aborted in VectorKit, Photos asserted and
Games faulted at their first objects. No Mac caps Metal processes like that.

The guest's [2^46, 2^47) is now 1024 units of 64 GiB, which the kext hands out
from a bitmap (RgfxContextSlots.hpp, with its native test) as aligned runs: one
unit a context, or the least power of two holding twice the device's
maxBufferLength where that is more than 32 GiB, so a buffer of maxBufferLength
always fits. Runs go round-robin, and the last 32 units free are WindowServer's
alone, as the blocks' and queues' reserves are.

OpenContext answers the span sixth under the kext feature bit ContextSpan
(1 << 5), and the bundle picks through it. A bundle that asks for five values
gets an aligned 2 TiB run, the span it picks through, so an old bundle keeps
working on a new kext, and a new bundle on an old kext takes its 2 TiB slot.
The host knows no slot: it pins each address as given, so it is unchanged, and
needs no device feature bit. Its test now pins at every unit's first address.

Past the last run the bundle answers no device in that process (init answers
nil), the answer every Metal client handles, in place of a device whose
creates answer nil.
2026-11-05 21:59:26 -08:00
Anees Iqbal 53d53e308a 🔊 Log a ring's room line once more as its writer goes
A queue's ring writer logs its sleeps for room at the first sleep and then at
most once a second, so a process that slept for room for under a second after
that first line showed only the first sleep: in a ring-filling boot each
ringfill run's line read "1 sleeps" while the host posted about 2200 room
records in the same run, and how many more posts slept went unseen.

The writer now logs the counts once more as it goes (its queue's release) where
its posts slept since the last line.
2026-11-05 21:59:26 -08:00
Anees Iqbal 274e691144 🔊 Log what a queue's posts slept for room on its ring
A boot can now show how the commits that found a queue's submission ring
full waited: a line for each ring at its first sleep for room and then at
most every second, with the sleeps, how many a SUBMIT_ROOM record ended,
and their time in all and at most. Without SUBMIT_ROOM every sleep is the
backoff's; with it, the records end them. RgfxRingRoomSleeps counts and
paces the line, and the serializer tests pin both.
2026-11-05 21:59:26 -08:00
Anees Iqbal 77eac2b6ae 🐎 Wait for the host's room record on a queue's full ring
A commit that finds its queue's submission ring full rang the doorbell and slept
20 us, doubling to 1 ms, between looks, so its post went on up to the last
step after the host took room, and a stream of commits through a full ring ran
at the sleep's cadence.

Where the device's word holds SUBMIT_ROOM, a new queue's ring writer and its
completion reader share a room signal (RgfxRingRoomEvents). A post that finds
no room stores 1 in the ring's producer_waiting, fences and looks once more,
then waits on the signal, which the reader raises as it reads the host's
RGFX_EVT_SUBMIT_ROOM, with a 20 ms backstop; where no completion thread drives
the reader, the wait keeps the sleep's step, as the waiter's own pump takes the
record. Without the bit nothing changes. The signal is shared, so a record read
as its queue goes finds it alive.

serializer_tests' test_ring_post_waits_for_the_room_record pins it: the full
ring's post sets the flag, room taken with no record leaves it waiting, the
record ends the wait, and a reader hands its ring's record to the signal.
2026-11-05 21:59:26 -08:00
Anees Iqbal f8f3e6817b ✅ Pin that a pending ICB's destroy names no later object
The kext destroys behind an ICB_CREATE it stopped waiting for, and the host
makes that ICB off the control thread. Were that destroy carried out out of
ring order, it could remove a later object under the same id.

The bundle gives each object id once in a context: ids only grow, a destroy
frees none, and only a new context's bases start them again. So within a
process no later object can take the id. A later context under a number given
again can, and the host test pins what then happens: the destroy waits for
the ICB's create, the ICB is made and destroyed, and the buffer created after
under the same id is made last and kept. Both tests fail with the destroy's
wait taken out.
2026-11-05 21:59:25 -08:00
Anees Iqbal 351724d07a 🐎 Lay Shared and Managed buffers in slabs of the region
Each Shared or Managed buffer took a kext block of its own: a blocking ALLOC
with a first-fit scan and an overwrite mapping, a BLOCK_GRANT, a memset of the
whole block, a host import per buffer, and a BLOCK_RELEASE round trip at its
free. In a 16 GiB guest on the 5080 that made 4 KiB creates 29 us (76 us late
in a hold, the scan), stopped them at the block table's 16,384 entries, and
made frees a round trip each, RES-01's trigger.

Buffers now take whole 4 KiB pages of slabs the bundle holds (RgfxSlabs):
- a Shared slab is one Placement HEAP_OVER_HOST_MEMORY of the class's
  options and each buffer a BUFFER_AT_OFFSET there; a Managed slab a plain
  block and each buffer a BUFFER_OVER_HOST_MEMORY over its own range;
- buffers up to 1 MiB share their class's slabs, which grow from 128 KiB to
  2 MiB; a larger one takes a slab of its own, cached once freed for reuse;
- a create zeroes only what of its range is dirty, and a background thread
  zeroes freed ranges and lets slabs go, so no free waits for the host;
- where the region has no block for a slab, the process's own empty and
  cached slabs go first, then smaller slabs down to the buffer's size: nil
  only where the region is full.

A create is a free-list take and one ring-0 post, with no kext call, and the
block table holds one entry per slab. Where slabs come from is their source's,
so guest-RAM slabs can take the region's place behind a feature bit.
2026-11-05 21:59:24 -08:00
Anees Iqbal ae30f6891a 🆕 Decode HEVC in the guest's video driver
The video driver now offers AppleGVA HEVC decode where the host's video
caps list it: Main into NV12 ('420v', '420f') and Main 10 into P010
('x420', 'xf20'), in the profiles the host lists. Each picture goes to the
host as H.264's do, its slice segments copied out of AppleGVA's bitstream
buffer and the SPS and PPS written from AppleGVA's parsed form where they
changed (RgfxVideoH265.cpp, sharing the bit writer with H.264).

An HEVC decode command carries no output surface and no transfer command,
unlike H.264's: AppleGVA names the output frame in its decoded-picture
record, whose frame holds the surface's global IOSurface id, and the driver
looks it up there. AppleGVA holds each short-term set of the SPS by its
pictures, a predicted set's already derived, and the writer writes every set
by them. Both measured on the guest with the RTX 5080; the sets' layout
against hevc-main-720p-sets-sps, whose 25 sets AppleGVA held as 7-61 and
7-62 derive them, and whose SPS written from AppleGVA's struct decodes as
the stream's own.
2026-11-05 21:59:24 -08:00
Anees Iqbal b8c902195b 🐎 Read a library's function table and file key once per process
A library loaded again re-read its whole function list each time, and one
from a URL re-hashed its bytes too: MPSImage's metallib (1,837 functions)
cost 4.4 to 5.1 ms on every newLibraryWithURL:, against 0.01 to 0.04 ms for
native Metal's repeat (scout-pipelines-05, measured on msi and the oracles).

Libraries of one content key now share one function table, read the first
time the process makes one. The key covers the function list, so bytes of
one key have one table. A URL load keys the file by its identity: device,
inode, size, and modification and status-change times to the nanosecond,
taken before and after the read. A load of an identity the process keyed
before takes that key without hashing. A rewritten file changes the identity
and is keyed again. The LIBRARY_LOOKUP round trip stays.
2026-11-05 21:59:24 -08:00
Anees Iqbal a71722deb1 🆕 Take the kext's own feature word in the bundle
The bundle asks Features for both words now and keeps the kext's in
RgfxCaps::kextFeatures, with a copy of the kRgfxKextFeature* bits beside the
selectors it mirrors. A kext older than the call, or any failure, leaves the
device info's bits 0-2 and no kext feature. The probe test covers both words,
and its comment sits with it again rather than above the layout asserts.
2026-11-05 21:59:24 -08:00
Anees Iqbal be2ed1c541 🆕 Work by the kext's feature word in the bundle
The device now asks the kext's Features selector for the word it works by
and keeps it in RgfxCaps. A kext older than the call answers
kIOReturnUnsupported; on that, or any failure, the word is the device info's
features_lo bits 0-2, which is what the bundle used before. The queue's
asksSubmitted reads the word.

serializer_tests checks the fallback and the word, and asserts the
negotiation's wire layout as the bundle compiles it.
2026-11-05 21:59:24 -08:00
Anees Iqbal 2d6015ddb5 🐎 Ask the host each heap texture shape's size once
Every heapTextureSizeAndAlignWithDescriptor: and every texture placed in a heap
waited for a HEAP_TEXTURE_SIZE_AND_ALIGN round trip: 12 us a query and 19.3 us
a placed 1024 texture on the msi 5080, where the M3, the AMD 5300M and the
Intel 630 answer in 0.5-0.9 us (scout-resources RES-06, measured).

The host's device answers a shape alike every time (it asks its own Metal or
metal2vulkan, which do; the oracle's AMD and Intel answer a repeat equally,
measured), so the serializer keeps each answered shape's size and alignment,
by the wire descriptor's bytes, and asks only a shape it has not seen. A refusal
or no answer is not kept, and is asked again. Up to 4096 shapes are kept.
2026-11-05 21:59:23 -08:00
Anees Iqbal f58636cda1 🐛 Answer the device's family name from its name, as Macs answer theirs
The IOGPU base answered the MTLDeviceSPI familyName "", which no Mac's
device answers. Each Mac answers its device name without the vendor and
the model number (measured: "M3 Max" for Apple M3 Max, "Radeon Pro" for
AMD Radeon Pro 5300M, "UHD Graphics" for Intel(R) UHD Graphics 630). The
Macs diverge, so the answer is the lane's choice inside what they give:
the same rule over the name the device already answers, "GeForce RTX" for
an RTX 5080. A serializer test runs the three Macs' names and the hosts'.

targetDeviceArchitecture stays the base's nil: each Mac answers its GPU
compiler's target, an instruction set the host cannot run, and nil names
none. The register records both as class 2 with the measured values.
2026-11-05 21:59:23 -08:00
Anees Iqbal 3acab669b8 🐛 Answer the SPI feature queries the lane carries out, as Metal does
The IOGPU base answers each supports* query of MTLDeviceSPI from the IOGPU
device info, which the kext gives all zero, so the device answered NO to
84 queries the M3 Max, the AMD 5300M and the Intel UHD 630 all answer YES
(measured with tools/base_answers_probe.m, aud-tests-04), contradicting
its own public answers: tessellation, argument buffers, heaps, binary
archives, 64-bit integers, SIMD-group functions and more. A framework that
asks the SPI before using a feature took the path for a device without it.

The device now answers 44 of them itself, each only where the lane
carries the feature out and from the host's answers: what the wire
carries, on a host of the Mac2 family; the Metal Shading Language's
features, on the same; four from the host's own flags; and read-write
texture arguments from its tier. RgfxCaps::spiFeature holds the decision
and a serializer test checks it against hosts with and without each
answer. The other 40 keep the base's NO: 18 name features the lane does
not carry (mesh shading, ray tracing, indirect command buffers, counters,
dynamic and pipeline libraries, shared textures), and 22 gate what is not
established; the register says which for each.
2026-11-05 21:59:23 -08:00
Anees Iqbal 34a4a18435 🐎 Build a large command buffer's message in its region block
aud-bundle-07. A command buffer too large for half its ring was built in a
std::vector that re-grew about five times for a 10k-draw buffer (625 KiB).
The queue's reserve was capped at the ring's size, so the next large buffer
started small again. At commit the whole message was copied into a region
block, and the SURFACE_USE ops were inserted at its front with a memmove.

The message is now written where it is posted from:
- on the builder's heap, at most half the ring, while it fits the ring;
- once it outgrows the ring, moved once (at most 16 KiB copied) into a block
  of the queue's body pool. The block is as large as the queue's recent
  largest message, which rgfxMessageReserve no longer caps at the ring, and
  it doubles from block to block after that.
The header and the commit's SURFACE_USE ops go into room kept before the
ops. finish() posts COMMAND_BUFFER_IN_REGION straight from the block and
hands the block to the command buffer before the post, since the completion may
come before finish() returns. The buffer gives the block back at completion,
or as it goes uncompleted, as before. RgfxBodyPool implements the encoder's
RgfxMessageBlocks, and its giveBack ignores an empty block: one a buffer
whose message found no block holds.

Design (Decided 3): encoders streaming as they end needs a command buffer in
several messages, which the wire does not have. That proposal went to
wire-v3 (~/.cache/rgk-audit/r1/fix-bundle-encode-streaming.md). design.md
now says what the bundle does today.

Wire bytes: COMMAND_BUFFER_IN_REGION's region_offset is now the block's
offset plus the room before the header, not the block's start. The format
is unchanged and still 8-aligned. The message's bytes are the same.

Measured natively on the M3 Max, headless (aud-bundle's audit bench), tree
before -> this, warm runs:
  commit of a 10k-draw buffer (setVertexBytes + draw)   9.1-12 -> 0.2 us
  the next large buffer's starting room               32 KiB -> 625 KiB
  setVertexBytes + draw                               ~15 ns, unchanged
  a command buffer's fixed cost                       1.25 us, unchanged
A queue's first large buffer has no guess yet, so it grows from block to
block where realloc might have grown in place. On a fresh queue's parallel
pass of 2 x 5,000 draws that costs 1-2 ns a draw (10.2 -> 12 ns).
test_command_buffer_storage checks the ring path and the block path: the
one move, doubling, blocks handed back, and a refused block posting
nothing.
2026-11-05 21:59:23 -08:00
Anees Iqbal a5a4b83534 🆕 Decode H.264 in the video driver through the host's sessions
The driver now answers AppleGVA's decode commands itself: a host session per
decode context, and each picture a command buffer of the session's queue
whose op carries the access unit, the SPS and PPS written back out of
AppleGVA's records where they changed, and textures over the output
surface's planes. A command's token is answered done once its command buffer
completes, which is once the picture is in the surface.

AppleGVA asks for one bitstream buffer and writes the next access unit into
it as soon as a picture is scheduled, without waiting for the decode that
reads it. So the channel copies each access unit, compressed data only, into
the next of eight Shared buffers of its session, from its first 3-byte start
code and padded to the host's alignment, and the host reads it there in
place; AppleGVA's own buffers are plain pages. The kext hands the bundle the
host's video caps with the device info. The call recorder used to learn the
interface is gone, and AppleGVA's records are read with plain loads.

Checked on the RTX 5080: the 672 frames of eight streams equal ffmpeg's
MD5s, and 1080p decodes at 1546 frames a second, 4K at 144.
2026-11-05 21:59:22 -08:00
Anees Iqbal a75a29a94b 🐛 Answer the linear texture alignment for every pixel format
6ae625668 answered minimumLinearTextureAlignmentForPixelFormat: 256 for the
56 formats the host backs with a buffer and 0 for the other 95. No Mac
answers 0. The oracle's q9 tables give one value on every format a Mac
makes linear textures of: 256 on 46 formats on the Radeon Pro 5300M and
the UHD 630 alike, and 16 on 56 on the M3 Max. On every other format,
Metal's own assertion ends the process (SIGABRT): compressed, depth and
stencil formats, Invalid, and formats the device lacks. The x86 Macs also
end it on the M3's ten extra formats (11, 31, 40-42, 263, 552-555).

So no working guest asks for one of those formats. One that did would get
a 0 to align up by, a divide or mask by zero. Every format now answers the
device's linear alignment, 256.
2026-11-05 21:59:19 -08:00
Anees Iqbal 7b2ecacab6 🎨 Answer the graphics lane's device limits as an AMD Mac does
The graphics lane's device answered what the host platform answers for
maxBufferLength and the linear texture alignment, and left the framebuffer
read, tile shader and imageblock answers to the base class. Each answer
steers the guest's frameworks, so each now picks, from the answers real
Macs give, the one the lane can keep cheapest (dgpu-oracle.md):

- maxBufferLength is the host's, but at most three quarters of
  recommendedMaxWorkingSetSize rounded down to 16 KiB. That is the rule the
  Radeon Pro 5300M and the M3 Max answer by. The Vulkan platform answers
  the driver's maxBufferSize, a terabyte on an RTX 5080 that no allocation
  reaches; the 5080 now answers 12821200896.
- minimumLinearTextureAlignmentForPixelFormat: and the SPI
  linearTextureAlignmentBytes and deviceLinearTextureAlignmentBytes answer
  256 (or the host's, where larger), as the 5300M and the UHD 630 answer.
  RADV takes a texture over dma-buf pages in place only at rows a multiple
  of 256 apart, and every 256-byte layout is one the host's 16 takes.
- isFramebufferReadSupported answers no, as the 5300M does. That keeps the
  guest's frameworks off attachment reads, which cost the Vulkan platform
  the most.
- supportsTileShaders, supportsNonSquareTileShaders and supportsImageBlocks
  answer no, as the 5300M and the UHD 630 do. The lane carries none of
  them.

The bundle answers all of these from the device-info blob, never through
the base class.
2026-11-05 21:59:19 -08:00
Anees Iqbal ebabaf40c1 🆕 Copy every plane of an IOSurface into one block, with its facts
WindowServer on the x86-64 guest samples the aerial wallpaper's 4K HDR video
frames through a YCBCR10_420_2P texture over plane 0 of each decoded surface,
which reads plane 1's chroma as Metal does. The bundle copied each plane into
a block of its own, so the host's texture over plane 0 had no chroma to read.

A surface's copy is now one block holding every plane, in plane order, each
from a 256-byte multiple with its rows 256 bytes apart, then the header and
the writers. A texture over any plane lies in the copy's one buffer at its
plane's offset, so every texture over the surface reads and writes the same
bytes, as Metal's over one surface do. The shared block is found by plane 0's
pages, which no other surface holds. Upload and write-back copy every plane.
A surface without planes is laid out as before.

Each TEXTURE_FROM_IOSURFACE now carries the surface's facts after its struct
(RgfxSurfaceFacts): IOSurfaceGetPixelFormat, the plane count, the size, plane
1's offset and pitch in the copy, and the YCbCr matrix. The matrix is the
surface's IOSurfaceYCbCrMatrix value, where CoreVideo leaves a propagated
kCVImageBufferYCbCrMatrixKey attachment (measured on the M3 Max under macOS
27.0.1 for all six of its constants). It is read from the surface, not
through CVPixelBufferCreateWithIOSurface, which holds the surface in use while
the pixel buffer lives.

The new shell test covers a 64 x 48 'x420' surface's one block, both planes'
textures, the facts, CPU access to plane 1, a missing plane, and a surface
without planes.
2026-11-05 21:59:19 -08:00
Anees Iqbal 75daf32d69 🆕 Carry a pass's programmable sample positions
Apple2's rows need programmable sample positions, and the bundle dropped them:
a pass's setSamplePositions:count: never left the guest, and
setDepthStoreActionOptions: was a logged no-op. The device answers
areProgrammableSamplePositionsSupported from the host, so apps that asked got
the default positions with no sign of it.

A pass's positions now travel after its colour records
(RGFX_PASS_FLAG_SAMPLE_POSITIONS, RgfxRenderPassSamplePositions), and the host
sets them on its pass; RENDER_SET_DEPTH_STORE_ACTION_OPTIONS (0x104f) carries
the encoder's options to Metal, and to the Vulkan platform as late options over
a store action left Unknown, as the stencil and colour ones go.

Metal ends the process at positions it does not take (measured on the M3 Max,
macOS 27): its descriptor's setter at a count other than 2, 4 or 8 or a
coordinate outside [0, 1), its pass validation at a count the device makes no
texture of (8 there), whatever the attachments' sample count. The guest's
descriptor stops the first; the bundle answers no encoder for the second; and
the host faults a pass that holds either, so no guest bytes reach the abort.

SamplePositions joins WIRED with its cap test: Apple2 now waits only on Metal
IO queues.
2026-11-05 21:58:32 -08:00
Anees Iqbal 0f3cf873be 🐛 Show a present only once the buffers drawing its surface finish
A compositor commits the command buffer that draws its frame into an
IOSurface and then submits the display pipe's transaction for it, without
waiting for the buffer. The buffer rides its queue's ring and the present
ring 0, which the host takes on separate threads, so the window could show
the surface before the buffer had run, or before the host had taken it.

Each guest process that commits a buffer writing a surface's copy now names
its queue and the buffer's seqno in the copy's RgfxSurfaceWriters, four
slots past the block's header, before the commit returns, and
TEXTURE_FROM_IOSURFACE carries where they lie. A PRESENT_SURFACE reads
them, and the host's PresentQueue shows it once each named buffer's
CB_COMPLETE is posted, in the order the presents came, with no wait on
anything else: buffers of other queues or surfaces hold nothing. A queue's
destroy, or its context's close, releases what waits on it.

A process writes only slots naming its own queues: it raises its queue's
seqno, takes back a slot of a queue of its own that is gone, or claims an
empty one, and it empties its slots when its copy goes. A slot given to
another queue has its seqno emptied first, so the host's queue, seqno,
queue read never pairs one queue with another's seqno.
2026-11-05 21:58:32 -08:00
Anees Iqbal 516a241e09 🆕 Write argument buffers by the host's layout in the guest's encoders
The bundle's argument encoders were stubs: newArgumentEncoderWithArguments:
and a function's newArgumentEncoderWithBufferIndex: answered nil, so no
app or framework could fill an argument buffer.

Each now asks the host for the layout (ARGUMENT_LAYOUT) through the
serializer's asker, the kext's submit that waits for the answer, into a
page of the region it gives back once the answer is read, and asks once
more into a block of the size the host needs where the layout outgrows the
first. The encoder parses the layout into a tree, checked whole, and writes
each argument's word where Metal's encoder writes it: in the last member
holding the index, at its element, through struct elements, and at the
arguments' offset 0 for an index no argument has. A buffer writes its GPU
address plus the offset, a texture or pipeline its resource id, nil 0. A
nested argument buffer's encoder takes its layout from the same answer.

What the wire does not carry logs its first use: a sampler's resource id
(its word is 0), a depth/stencil state's (the bytes stay), and the
argument's reflection. Indirect command buffers, acceleration structures
and function tables take only nil, which writes 0, since the device makes
none. A setter with no argument buffer set, where Metal's process ends,
writes nothing and logs it.
2026-11-05 21:58:32 -08:00
Anees Iqbal 3dae60cefb 🐛 Make no-copy buffers over the app's own memory
CA in WindowServer logged "nil buffer from memory": newBufferWithBytesNoCopy:
answered nil for every pointer outside the device region, which is all of an
app's own memory. Metal makes one over any range the process maps readable, at
any alignment and length (measured on an M3 Max at 16 KiB and, under Rosetta,
4 KiB pages: malloc'd, vm_allocate'd, read-only and file-mapped memory), and
answers nil only for a length of 0 or a range not wholly mapped.

Such a buffer now lies over a region block of its own, and its contents stay
the app's pointer. The block syncs with the memory as the IOSurface copies do:
the CPU's bytes go in at the commit of each command buffer that uses it, and the
GPU's come back when one that may write it completes, before its completion is
reported. Only the bytes each side moved since the two last agreed move, byte
by byte, so CPU and GPU writes beside each other both stand. The encoders note
each use as a read or a write, and they look up a buffer only while a shadow
lives. A null pointer gets zeroed contents of the buffer's own, and its
deallocator gets null, as Metal's does.
2026-11-05 21:58:32 -08:00
Anees Iqbal 5b45fdb5e8 🆕 Place an Automatic heap's resources as Metal does
An Automatic heap's newBufferWithLength:options: and
newTextureWithDescriptor: answered nil, and usedSize and
maxAvailableSizeWithAlignment: answered 0 and the heap's size. The heap now
places each resource itself, as Metal's Automatic heap does on an M3 Max
under macOS 27 (RgfxHeapRanges.hpp): at the lowest free offset at its
alignment, a buffer taking its length at the device's heap buffer
alignment and a texture the size heapTextureSizeAndAlignWithDescriptor:
answers, now the host device's (HEAP_TEXTURE_SIZE_AND_ALIGN) and the bound
only where none came back. Each goes to the host as a placement at that
offset in the Placement heap the host made; its heapOffset answers 0, as
Metal's does. Its bytes go back when it is made aliasable, at once, or else
once its destroy has gone, and usedSize and maxAvailableSizeWithAlignment:
answer from the placements, 0 for a Placement heap as Metal answers. A
heap's size is the descriptor's rounded up to the 16 KiB page, as Metal's
and the host's are, and a heap texture answers its placed size as its
allocatedSize.

The lane now carries Automatic heaps, so the piece joins WIRED.
2026-11-05 21:58:32 -08:00
Anees Iqbal 56e22234c5 🆕 Keep binary archives in the guest, as Metal answers them
newBinaryArchiveWithDescriptor: answered nil and an error, and Apple's own
archive, which the base class made before that, needs a target architecture
the device has none of. RgfxBinaryArchive is the device's own: no compiled
code crosses the wire, so it keeps the key Metal looks each function's compile
up by (its bitcode hash, name and constants, with the state Metal's misses show
it keys by), per architecture, and writes them as a file of its own format.

Every answer is Metal's on the M3 Max (archive_probe): an empty archive from
no URL, Invalid URL for no readable file, an invalid format for any other
file, Nothing to serialize for an empty one, and a Metal archive, another GPU's
to this device, loads and misses every lookup. A pipeline create with
MTLPipelineOptionFailOnBinaryArchiveMiss answers Metal's miss, naming the
fragment then the vertex function it lacks, and compiles as before when it
names no archive or lacks the option. Where Metal asserts (no compute, vertex
or tile function) the add answers NO with Metal's words.
2026-11-05 21:58:32 -08:00
Anees Iqbal cd126615e4 🆕 Answer the texture view selectors in the bundle
iconservicesagent and WindowServer's desktop capture call
newTextureViewWithPixelFormat:, which the bundle did not answer.

Every public form is made: a format alone; with type, levels and slices;
with a swizzle; and by a descriptor. Each posts TEXTURE_VIEW and makes a
texture of the view's own shape and resource id that keeps its texture. As
Metal's views do (measured on the M3 Max under macOS 27.0.1), it answers:
- its own format, type, levels and slices, and its texture's size at its
  first level;
- the swizzle it names, else its texture's; a swizzle other than the default
  keeps only ShaderRead and PixelFormatView of the usage, and 0x4000 and
  0x10000;
- its texture as parentTexture, and the level and slice it starts at;
- its texture's buffer, IOSurface, heap, offset, aliasing and size;
- NonVolatile to setPurgeableState:, and makeAliasable changes nothing.

A view's CPU copies are its texture's at the view's levels and slices, and a
write through a view of an IOSurface texture is noted as a write of that
surface.

Metal ends the process at a view it does not make, and answers nil for one in
no format. The bundle answers nil and posts nothing for each case it can tell:
- no format;
- blocks of other bytes or size, or compressed against uncompressed;
- levels or slices outside the texture;
- a type of another family;
- a slice count the type does not take.
The host refuses any other view its platform does not make.

The wire carries no minLOD, so a descriptor view with a nonzero one is
answered nil.
2026-11-05 21:58:31 -08:00
Anees Iqbal fc8efad649 🐛 Answer nil for a heap of no bytes or with no address left
newHeapWithDescriptor: made a heap of size 0, and a heap or buffer whose
GPU address found no room in the context's range, and posted its create
anyway: the first at a size the host refuses, the second at address 0,
which the host places unpinned. Metal answers nil for a heap of size 0
(measured on the Metal platform) and for a resource it cannot place, so the
app went on with a heap the host never made, and every placement in it was
a bad reference after that.

Both are now nil, and nothing is posted for them: a heap of size 0, and a
heap, a heap over host memory, a device buffer or a buffer over host memory
whose address the context's range has no room for. The block under a
Shared one goes back, as for any that could not be made.
2026-11-05 21:58:31 -08:00
Anees Iqbal 651fa6b653 🐛 Resolve function constants by name and range as Metal does
The bundle carried only the values a process set by index, so a function
specialised by name (WindowServer's and SecurityAgent's RenderBox pipelines)
reached the host unspecialised, and the Vulkan runtime refused its compile
(NeedsInput(FunctionConstant { index: 0 })).

The bundle now reads each function's constants from its library's bytes (the
CNST table of its public metadata) and resolves the values as Metal does,
measured on macOS 27.0.1: the value at a constant's index (set by index or by
range) wins over the one under its name, values for constants the function does
not declare are ignored, a value of another type fails the function with
Metal's MTLLibraryErrorCompileFailure and words, a required constant with no
value reads 0, and an optional one stays undefined. A missing function answers
Metal's MTLLibraryErrorFunctionNotFound. A function made with no values answers
its constants from functionConstantsDictionary, and the pipelines of it are
refused where Metal asserts.

A wire record now carries a value of up to 32 bytes (a long4), so float4 and
wider constants reach the host; core's FunctionConstant follows, which only
this lane's decoder uses.
2026-11-05 21:58:31 -08:00
Anees Iqbal 80094a9aa6 🐛 Pick GPU addresses as the host's pins need, and reuse them
The bundle picked each device buffer's and heap's GPU address 256-byte
aligned, right after the one before it. The host pins those addresses, and
a pin must start a 32 KiB granule and hold the pages its bytes touch plus a
guard page, rounded up to a granule, apart from every other live pin
(metal2vulkan's address.rs). Picks that broke the rule were refused, so
every other HEAP_CREATE of a churn failed. Nothing was ever given back
either, so a long-lived process would walk off its context's 64 GiB.

Each pick now starts a granule and holds that span. A pick's range goes
back once its object's destroy is retired, into a coalesced free map per
context. Picks go forward from the last one and wrap round to the ranges
given back behind them, so a freed range is picked again only after a lap
of the slot. Buffers that picked their address (device buffers and those
over host memory, not ones placed in a heap), heaps, and device-placed and
Managed textures give theirs back.
2026-11-05 21:58:31 -08:00
Anees Iqbal 0b560fe199 🆕 Answer texture-buffer alignment and sparse tiles per pixel format
The bundle answered neither minimumTextureBufferAlignmentForPixelFormat: nor
either sparseTileSizeWithTextureType: form, and IOGPUMetalDevice has none of
them. A call fell through to the zero catch-all, whose signature returns a
scalar where both tile queries return an MTLSize.

The blob now carries, for each pixel format of the SDK, its texture-buffer
alignment and its 2D sparse tile at 1, 2 and 4 samples on 16, 64 and 256 KiB
pages. The tile is one answer for every texture type, as Metal gives it on an
M3 Max. Metal asks the alignment only of the 56 formats it answers; on every
other one it fails an assertion, measured on the M3 Max. The Vulkan platform
answers with the runtime's linear alignment, which Metal answers alike for
every format, and with the runtime's tiles.
2026-11-05 21:58:30 -08:00
Anees Iqbal 92602e905e 🆕 Answer every family, feature set and identity getter from the host
The guest's MTLDevice answered supportsFamily: of Apple5 to Apple10 and -1009
alone, no to Common1-3, Mac1/Mac2, Metal3 and every feature set, a 32-byte
name that cut "NVIDIA GeForce RTX 5080 Laptop GPU" short, and placeholders for
its identity (1 GiB working set, unified memory, Tier2 argument buffers). Apps
that gate on Mac2, Metal3 or a macOS feature set refused to run.

- GpuDevice::identity_caps, which only the graphics lane asks, holds
  supportsFamily: of every family of the SDK, supportsFeatureSet: of every
  feature set, and the identity and capability getters. The paravirt lane's
  DeviceCaps are untouched. Metal answers every one with its own getter. The
  Vulkan platform answers each from the runtime where it can: its properties,
  supportsFamily:, and the audit of a feature row (BC formats, query LOD,
  barycentrics, dynamic libraries, ray tracing, function pointers). Apple5 to
  Apple10 keep the platform's DeviceCaps answers. Each claimed family claims
  what Metal documents it contains. Feature sets follow their families, as
  Metal on an M3 Max answers them: no to ReadWriteTextureTier2 and to tvOS.
  The working set is the sum of the device-local Vulkan heaps. The runtime
  has no answer of the rest, which is None.
- RgfxDeviceInfo v2 carries all of it: families and feature sets as (value,
  answer) lists that the bundle looks up by value, the integer and BOOL
  identity answers, the architecture name, and a name of 256 bytes. A gap
  reads 0, never yes.
- device_info.rs answers with the lane's own device where it can do less
  than the host GPU, in one table with a row per missing piece: Metal4,
  ray tracing, motion blur, function pointers, dynamic libraries, placement
  sparse, counter sampling and rate maps answer no. hasUnifiedMemory stays
  yes for now, because Managed buffers are guest memory alone in the bundle.
- The bundle answers every one of these getters from the blob, with no
  defaults of its own.
2026-11-05 21:58:30 -08:00
Anees Iqbal c7b4ff7f66 🐛 Never drop a command buffer its queue's ring has no room for
-commit posted with tryPost and ignored its answer, so a command buffer
committed while its queue's 32 KiB submission ring was full, or one larger
than the ring, was never posted and never completed: 400 small fills in a row
hung every time on msi. Metal never fails or drops a buffer for its size, and
throttles with maxCommandBufferCount.

- A buffer larger than half its ring goes out of line: the bundle writes its
  whole COMMAND_BUFFER message into a region block of the process's own and
  posts a new COMMAND_BUFFER_IN_REGION (0x301: offset, length). The queue's
  service thread copies the message out of the block once, with the
  reference's seqno, and refuses a span outside the processes' blocks or one
  holding no COMMAND_BUFFER of that length. The block goes back as the buffer
  completes. With no block to be had, the buffer fails with
  MTLCommandBufferErrorOutOfMemory, off the committing thread.
- A queue keeps maxCommandBufferCount slots (64 for 0, as Metal's default):
  -commandBuffer blocks while every one is held by a buffer alive and not
  completed, and a buffer gives its slot back before its handlers run, or at
  dealloc where it never completes.
- A commit that finds the ring full rings the doorbell and sleeps 20 us
  doubling to 1 ms between looks; on the delivering thread, or where no
  completion thread drives the ring, it takes the queue's completions
  meanwhile, as the host may be waiting for room there.

It also closes a race in the completion work: commit expected a buffer's
completion only after posting it, and set Committed after, so the completion
thread could take a fast completion with no handler yet (lost, the buffer
hung) or have its status overwritten. The completion is now expected under the
ring's lock before producer moves, and Committed is set before the post.
2026-11-05 21:58:30 -08:00
Anees Iqbal c166383741 🐛 Hand out texture resource ids in chunks from one guest-wide pool
Every guest Metal process's textures share the host's one device, whose
texture ids end below 16381: Metal ends the process for a texture placed at
16381 or more, and metal2vulkan imitates that. The ids were split by context
slot (1 + s * 2048), so slot 8 onward was past the limit, and a WindowServer
crash loop or a few app launches killed QEMU at the first texture create
("invalid use of new_texture: ResourceId { id: 16385, limit: 16381 }").

The kext now keeps one pool of 255 chunks of 64 ids, all below 16321, and
gives a process a chunk when it asks (user-client selector 0x106). It posts
the grant on ring 0 (RESOURCE_ID_CHUNK: context, chunk) before it returns, so
the host has it before any create naming its ids. A process keeps its chunks
until its close, and they are freed after its CONTEXT_CLOSE is answered, with
its blocks. OPEN_CONTEXT answers no resource-id base any more. A chunk is 64
ids so that the bundle keeps each chunk's free ids in one 64-bit mask.

The bundle takes the lowest free id of the first chunk it took that has one,
asks for a chunk only when all of its are in use, and gives an id back as its
texture goes. With every chunk held, newTexture answers nil, as Metal answers
a texture it cannot make.

The host refuses a texture create, from a device, a buffer or an IOSurface,
whose id lies in no chunk of its own context, 0 and the limit's included,
before any platform call, as a refused create is refused: unanswered, and a
command buffer naming the texture fails. So no guest id reaches the
platform's own limit, where the Vulkan platform ends the process.

Only textures are affected: sampler and pipeline states take no guest-picked
ids (the host numbers them), and the bundle makes no indirect command buffers.

tools/tex_probe copies a pattern through a Private texture and back, and holds
N textures at once, checking their ids are distinct and below the limit.
2026-11-05 21:58:30 -08:00
Anees Iqbal 1f57dd0cd0 🆕 Key libraries by content, and keep them on the host
Every process that loads QuartzCore's shaders sent the whole library over
the region, and the host built it again. Now the bundle takes the AIR slice's
content key (SHA-256 of the .metallib without its bitcode section, whose
functions the HASH tags name) and asks the host first with LIBRARY_LOOKUP.
On a hit the new id is bound to the library the device made for any process,
and no bytes cross. On a miss the slice goes as before, now with its key.

The host keeps a library under a key only where it computed that key from
the bytes itself, checked every HASH tag against its bitcode, and found the
functions cover the bitcode section. Every AIR metallib of macOS 27's system
covers it. A lookup can then only bind content with that key, on Metal as on
the Vulkan platform. A wrong key makes the library uncached. Libraries no id
names stay in a 64 MiB least-recently-released list, so a restarted
WindowServer still hits.

Library creates are now answered with COMPLETE, and the kext waits for the
answer (for a region-streamed library, its last chunk), so a refusal is nil
and an NSError at newLibrary*, as in Metal. They are made on the compile pool,
off the control thread. A pipeline create that names a library still being
made waits for it on its compile thread, and a destroy of such a library
keeps ring order.
2026-11-05 21:58:30 -08:00
Anees Iqbal ad831c411e 🐎 Post the Metal processes' object lifecycle on ring 0
Each process's creates and destroys now reach the host on the control ring,
which the accelerator kext posts for it under the framebuffer's ring lock, in
place of a device queue per process and the BAR 0 mailbox. Ring 0 keeps one
producer, the kexts, and one consumer, the host's control thread, so the
lifecycle of every process is in one order with the display commands.

The bundle hands each message to the kext by a user-client call (selector
0x105, struct in). The kext checks the object is in the caller's context,
stamps the seqno and posts it; for a pipeline create it waits for the
reflection, which the work loop routes by seqno, and hands it back as struct
out. QUEUE_CREATE (selector 0x103) is posted and answered with COMPLETE once
the host has the queue's rings. At a close the kext posts each queue's
OBJECT_DESTROY, then CONTEXT_CLOSE, which the host answers once the context's
objects are dropped, then frees the blocks.

The host carries out lifecycle messages on the control thread with no ring
held, and a command buffer waits until every ring-0 message published before
its queue's thread took it is carried out. The Host trait's queue_message
becomes stage3_message, and its poster (CompletionPoster) also targets the
control completion ring.
2026-11-05 21:58:30 -08:00