An x86-64 guest's hardware HEVC encoding never reached our GPU: macOS's HEVC encoder plug-in drives only an Intel GPU's driver, found by name, so an app that required hardware failed at its create (-12908) and others encoded in software (m3-max-77632, development's set on this host). What the guest sees now, where the host's video arm lists an HEVC encoder of Main and Main 10 with a constant QP that codes a frame in place of the last (Linux hosts' VA-API, and NVENC where its driver codes a frame without advancing its state): - the accelerator publishes an IntelAccelerator child of its own with IOGVAHEVCEncode and IOGVAHEVCEncodeCapabilities (Main and Main 10, up to the encoder's level), so VideoToolbox lists a hardware HEVC encoder (hevc.gva); - RgfxGate keeps the Intel driver path the plug-in loads from /Library/GPUBundles a hard link to the bundle's executable, at every boot; - the bundle's video driver takes the plug-in's encode commands (function 0x20, sub-ID 0x1000), codes each frame on the host (ENCODE_H265) at the QP the plug-in's rate control chose, an IRAP picture as a keyframe, Main from an 8-bit source and Main 10 from a 10-bit one, and hands back the access unit with 4-byte start codes, whose VPS, SPS and PPS make the session's format description; - a frame the plug-in codes again over its data rate limit, at a higher QP, is sent in place of the last one (RGFX_VIDEO_ENCODE_IN_PLACE): a P picture of the last frame's order count and source surface; a keyframe coded again is sent as a new IDR picture; - a session of a size the host does not encode is refused at its create, so an app that allows software encodes in software as before. A host whose encoder has Main alone gets no nub: VideoToolbox hands the plug-in a Main 10 session whatever profiles the nub lists, and the driver learns a session's profile only from its first frame. Nor does one that codes no frame in place, where a retry would predict from the frame it replaces. H.264 encode and both decodes are as before on either. The plug-in's per-CTU QP map (its pool 27) is not applied, and its frame statistics record is not supplied. The route is macOS 26.7.1's plug-in's, booted on 26.7.2. Windows hosts list no encoder, so encode in software as before. Rows (macOS 26.7.2 guest, 1080p, 300 frames at 8 Mbit/s, decoded back by VideoToolbox; the rate band is vboot's RATE_BAND_PCT, 6%, both codecs), the same with the frames in place (m3-max-77615, m3-max-77613, m3-max-77614), byte for byte but for 205 bytes of the Iris Xe's Main stream: - RX 7900 XTX (m3-max-77475): Main 105.1%, 45.02 dB; Main 10 104.8%, 45.17 dB - Iris Xe (m3-max-77476): Main 103.5%, 48.04 dB; Main 10 98.1%, 48.86 dB - RTX 3090 (m3-max-77477): Main 100.7%, 44.81 dB; Main 10 106.1%, 45.06 dB, where NVENC's own lands 104.6%: known-issues and video/bugs.md B97 At a data rate limit of 1 Mbyte a second, the plug-in coded 2 to 30 frames of a session again, each sent in place: no gap in the order counts, all 300 frames decoded back, and the most bytes in a second 1.7% to 3.0% over the limit (RX 7900 XTX m3-max-77611, RTX 3090 m3-max-77609, Iris Xe m3-max-77627; video/bugs.md B100, to be read on a user's report). With a keyframe every frame the stream comes to 4.1 to 5.0 times the asked rate, as a real Intel Mac's comes to 5.7 times with the same QPs frame for frame (m3-max-77635; design.md, known-issues); every frame decodes back. Main 10 from a retained pool and from the app's own 8-bit buffers decodes as from the pool taken per frame on all three. A real Intel Mac's hevc.gva (macOS 26.7.1, m3-max-77481) replaces the session's pool at the third Main 10 frame, as ours does. Speed (Iris Xe, m3-max-77497): 94 to 118 fps at 1080p against software's 3.3; 10.3 to 10.8 at 8K against 0.5 (B98, B99). Tests: the kext's publish condition and its pairing with a host that codes no frame in place (video_codecs_test: the caps of both decoders and encoders without the flag publish no HEVC encode and the rest as before), the link's update on real files (rgfxgate alias_test), and the driver's listing, create refusals, settings, keyframes, write-back, failures, refused sources and the frames it sends in place, and those it does not: never a keyframe, so a session of keyframes from one reused surface sends none (video_driver_tests; m3-max-77590). Development's set on this host (m3-max-77632) encodes H.264 to the same bytes as this one and decodes as before. Docs: design.md and devices.md, video/bugs.md B97 to B100, and known-issues.md's HEVC encoding line, which now says which GPUs encode HEVC for an Intel Mac guest, and its section on HEVC over the bitrate asked.
1171 lines
46 KiB
C++
1171 lines
46 KiB
C++
/*
|
|
* RgfxAccelerator: see RgfxAccelerator.hpp for the service's role, the Metal
|
|
* discovery keys it carries, and the boot-gated base-class decision.
|
|
*/
|
|
|
|
#include "RgfxAccelerator.hpp"
|
|
|
|
#include "ReimsGraphics.hpp"
|
|
#include "RgfxAcceleratorUserClient.hpp"
|
|
#include "RgfxDisplayPipeUserClient.hpp"
|
|
#include "RgfxGLUserClients.hpp"
|
|
#include "RgfxSurfaceUserClient.hpp"
|
|
|
|
#include <IOKit/IOLib.h>
|
|
#include <IOKit/graphics/IOGraphicsInterfaceTypes.h>
|
|
#include <kern/clock.h>
|
|
#include <kern/thread_call.h>
|
|
#include <sys/mount.h>
|
|
#include <sys/proc.h>
|
|
#include <sys/vnode.h>
|
|
|
|
#include "RgfxAccelTypes.hpp"
|
|
#include "RgfxBundlePaths.hpp"
|
|
#include "RgfxFeatures.hpp"
|
|
#include "RgfxIOSurfaceKPI.hpp"
|
|
#include "RgfxKeptService.hpp"
|
|
#include "RgfxPciClass.hpp"
|
|
#include "RgfxRegionMapping.hpp"
|
|
#include "RgfxSurfaceLimits.hpp"
|
|
#include "RgfxSurfaceRows.hpp"
|
|
#include "RgfxTrace.hpp"
|
|
#include "RgfxVideoCodecs.hpp"
|
|
|
|
#define super IOAccelerator
|
|
OSDefineMetaClassAndStructors(RgfxAccelerator, IOAccelerator);
|
|
|
|
namespace {
|
|
// The started framebuffer copyFramebuffer found, retained, under keptLock (made at the
|
|
// accelerator's start), handed out while it is live (RgfxKeptService.hpp): one accelerator per
|
|
// device, one device per guest, as the contexts' state (RgfxAcceleratorContexts.cpp), and kept out
|
|
// of the class, whose layout stays as the loader's sites were taken from (RgfxAccelerator.hpp).
|
|
IOLock *keptLock = nullptr;
|
|
ReimsGraphics *keptFramebuffer = nullptr;
|
|
|
|
// A framebuffer is live while it has started and its termination has not begun.
|
|
struct KeptOps {
|
|
bool live(ReimsGraphics *fb) { return fb->hasStarted() && !fb->isInactive(); }
|
|
void retain(ReimsGraphics *fb) { fb->retain(); }
|
|
};
|
|
} // namespace
|
|
|
|
// MARK: - The bundle
|
|
//
|
|
// Metal finds a GPU by its registered IOAccelerator, and loads the bundle the accelerator's
|
|
// MetalPluginName names. Where the accelerator is registered and its bundle is not on disk (an
|
|
// install boot before the bundle is installed, Recovery, the installer), every WindowServer
|
|
// aborts in CoreDisplay as it brings the display up, and launchd starts another until it gives
|
|
// up: the screen stays black. Where no accelerator is registered, WindowServer composites in
|
|
// software on the framebuffer (measured on msi: an accelerator that does not start leaves
|
|
// WindowServer up with a console session and the desktop drawn, the framebuffer still naming it
|
|
// in IOAccelTypes; a registered accelerator, the framebuffer not naming it, still aborts).
|
|
//
|
|
// So the accelerator registers only once the bundle is on disk. It starts as before, but a
|
|
// check repeats from its start: none before the root file system is mounted, then a lookup of
|
|
// the bundle's executable every kBundleCheckMs. /Library/GPUBundles is on the data volume,
|
|
// which launchd mounts early in boot, well before it starts WindowServer, so on a guest with the
|
|
// bundle the accelerator is registered before WindowServer looks for a GPU. WindowServer's
|
|
// first server connection to the framebuffer settles it (settleBundle, from
|
|
// ReimsGraphics::newUserClient, before IOFramebuffer makes the connection, which WindowServer
|
|
// opens before any of the accelerator's user clients): one last check there, and none after.
|
|
// Without the bundle by then, the accelerator stays unregistered for the rest of the boot, so
|
|
// WindowServer never sees a GPU appear under it; a bundle installed later is used from the next
|
|
// boot. Neither the check nor its wait runs on the kext's start or the framebuffer's console.
|
|
//
|
|
// The bundle must also be of the kext's wire version (design.md, "The wire's version"): it maps
|
|
// the region and speaks the messages. Its package carries an empty marker named for the version
|
|
// it was built with (RgfxBundlePaths.hpp), and only the executable with the marker of this
|
|
// kext's RGFX_VERSION counts as the bundle on disk. A bundle of another version is left as if
|
|
// there were none, so WindowServer composites in software: a bundle that refused to make a
|
|
// device under a registered accelerator would leave WindowServer aborting, as with no bundle.
|
|
//
|
|
// The accelerator registers only once the framebuffer has started too (ReimsGraphics::hasStarted):
|
|
// a process's context reaches the device only through the framebuffer's rings, so with no
|
|
// framebuffer (one whose start failed, as arm64 27.0.1's once did) every context Metal opened
|
|
// would have its messages and its close refused. The check repeats until both hold; with the
|
|
// bundle found and no framebuffer started it says so once.
|
|
//
|
|
// Where RgfxGate installs the bundle, nothing on disk counts while its install pass is under way
|
|
// (rgfxBundleRegisters): an update that keeps the wire version finds the old bundle and its
|
|
// marker before the pass drops the marker and rewrites the files. The pass publishes itself on
|
|
// IOResources (kRgfxGateInstallDoneKey), and the check looks again until it has ended. The
|
|
// settling connection waits up to kGatePassWaitMs for a pass under way; one still under way then
|
|
// leaves the accelerator unregistered for the boot. Without RgfxGate there is no property, and
|
|
// the check registers for what it finds.
|
|
//
|
|
// On arm64 every boot starts in the paired recoveryOS's BaseSystem, and one that stays there
|
|
// (FileVault's unlock, Recovery) registers the accelerator for the bundle RgfxGate's pass puts
|
|
// into the BaseSystem's temporary Data volume. Leaving for the full system keeps the kernel and
|
|
// the registration, so there a process's read of MetalPluginName waits for RgfxGate's pass of the
|
|
// full system's Data volume instead (holdMetalName).
|
|
namespace {
|
|
// How often the check repeats until the bundle is found or WindowServer settles it.
|
|
constexpr UInt32 kBundleCheckMs = 100;
|
|
// How long the settling connection waits for a registration in flight to finish.
|
|
constexpr UInt32 kBundleRegisterWaitMs = 5000;
|
|
// How long the settling connection waits for RgfxGate's install pass to end, and how often it
|
|
// looks.
|
|
constexpr UInt32 kGatePassWaitMs = 5000;
|
|
constexpr UInt32 kGatePassLookMs = 10;
|
|
// How long the start waits for IOSurfaceRoot to align the rows it lays out.
|
|
constexpr uint64_t kSurfaceRootWaitNs = 10ull * 1000 * 1000 * 1000;
|
|
|
|
enum : UInt32 {
|
|
// The check repeats.
|
|
kBundleWatching,
|
|
// The bundle was found; registerService is under way (the service may be published already).
|
|
kBundleRegistering,
|
|
// registerService has returned: the accelerator is registered.
|
|
kBundleRegistered,
|
|
// WindowServer opened the display without the bundle: the accelerator stays unregistered.
|
|
kBundleSettled,
|
|
};
|
|
|
|
// One accelerator per device, one device per guest. The state stays out of the class, as the
|
|
// contexts' does (RgfxAcceleratorContexts.cpp).
|
|
struct BundleWatch {
|
|
// Under lock: where the accelerator stands (above).
|
|
IOLock *lock;
|
|
UInt32 state;
|
|
// The repeating check, and under lock whether it is running (stop waits for it to end).
|
|
thread_call_t call;
|
|
bool running;
|
|
// The bundle's executable and its marker for this kext's wire version, NAME the
|
|
// accelerator's MetalPluginName (the bundle's Makefile names its executable so).
|
|
RgfxBundlePaths paths;
|
|
// The check's own: whether it has said the bundle waits for the framebuffer.
|
|
bool toldFramebuffer;
|
|
};
|
|
BundleWatch bundle = {nullptr, kBundleWatching, nullptr, false, {}, false};
|
|
|
|
// What the lookups find.
|
|
enum BundleFound : UInt32 {
|
|
// No executable, or no root file system yet.
|
|
kBundleAbsent,
|
|
// The executable, without the marker of this kext's wire version.
|
|
kBundleOtherVersion,
|
|
// The executable and the marker: the bundle to register for.
|
|
kBundleOurs,
|
|
};
|
|
|
|
UInt32 bundleState()
|
|
{
|
|
if (!bundle.lock)
|
|
return kBundleSettled;
|
|
IOLockLock(bundle.lock);
|
|
UInt32 state = bundle.state;
|
|
IOLockUnlock(bundle.lock);
|
|
return state;
|
|
}
|
|
|
|
// Moves the watch from Watching to `to`, and ends the repeating check where `to` is not Watching;
|
|
// false where it was no longer Watching.
|
|
bool leaveWatching(UInt32 to)
|
|
{
|
|
IOLockLock(bundle.lock);
|
|
bool moved = bundle.state == kBundleWatching;
|
|
if (moved)
|
|
bundle.state = to;
|
|
IOLockUnlock(bundle.lock);
|
|
if (moved)
|
|
thread_call_cancel(bundle.call);
|
|
return moved;
|
|
}
|
|
|
|
// Whether `path` is there.
|
|
bool onDisk(const char *path, vfs_context_t context)
|
|
{
|
|
vnode_t found = nullptr;
|
|
errno_t error = vnode_lookup(path, 0, &found, context);
|
|
if (!error)
|
|
vnode_put(found);
|
|
return !error;
|
|
}
|
|
|
|
// RgfxGate's install pass, from its property on IOResources (above).
|
|
RgfxGatePass gatePass()
|
|
{
|
|
IOService *resources = IOService::getResourceService();
|
|
OSObject *value = resources ? resources->copyProperty(kRgfxGateInstallDoneKey) : nullptr;
|
|
OSBoolean *done = OSDynamicCast(OSBoolean, value);
|
|
RgfxGatePass pass = !done ? kRgfxGateAbsent
|
|
: done->isTrue() ? kRgfxGateDone : kRgfxGateInstalling;
|
|
if (value)
|
|
value->release();
|
|
return pass;
|
|
}
|
|
|
|
// Which bundle is on disk (above); none before the root file system is mounted.
|
|
BundleFound bundleOnDisk()
|
|
{
|
|
vnode_t root = vfs_rootvnode();
|
|
if (!root)
|
|
return kBundleAbsent;
|
|
vnode_put(root);
|
|
vfs_context_t context = vfs_context_create(nullptr);
|
|
if (!context)
|
|
return kBundleAbsent;
|
|
BundleFound found = kBundleAbsent;
|
|
if (onDisk(bundle.paths.executable, context))
|
|
found = onDisk(bundle.paths.marker, context) ? kBundleOurs : kBundleOtherVersion;
|
|
vfs_context_rele(context);
|
|
return found;
|
|
}
|
|
|
|
void armBundleCheck()
|
|
{
|
|
uint64_t deadline = 0;
|
|
clock_interval_to_deadline(kBundleCheckMs, kMillisecondScale, &deadline);
|
|
thread_call_enter_delayed(bundle.call, deadline);
|
|
}
|
|
|
|
// Registers the accelerator, which the caller moved to Registering, and marks it Registered once
|
|
// registerService returns: synchronously, so the matching (and Metal's notification) is done.
|
|
void registerAccelerator(RgfxAccelerator *accelerator, const char *when)
|
|
{
|
|
IOLog("RgfxAccelerator: the bundle is at %s%s: registered\n", bundle.paths.executable, when);
|
|
accelerator->registerService(kIOServiceSynchronous);
|
|
accelerator->publishHevcEncoder();
|
|
IOLockLock(bundle.lock);
|
|
bundle.state = kBundleRegistered;
|
|
IOLockUnlock(bundle.lock);
|
|
}
|
|
|
|
// The repeating check, on a thread call: registers the accelerator once the bundle is there and
|
|
// the framebuffer has started.
|
|
void checkBundle(thread_call_param_t accelerator, thread_call_param_t)
|
|
{
|
|
IOLockLock(bundle.lock);
|
|
bundle.running = true;
|
|
IOLockUnlock(bundle.lock);
|
|
// The pass first: once it has ended, the disk holds what it left.
|
|
const RgfxGatePass gate = gatePass();
|
|
const bool ours = gate != kRgfxGateInstalling && bundleOnDisk() == kBundleOurs;
|
|
const bool framebuffer = static_cast<RgfxAccelerator *>(accelerator)->framebufferStarted();
|
|
bool found = rgfxBundleRegisters(gate, ours, framebuffer);
|
|
if (ours && !framebuffer && !bundle.toldFramebuffer) {
|
|
bundle.toldFramebuffer = true;
|
|
IOLog("RgfxAccelerator: the bundle is at %s, and the framebuffer has not started: not "
|
|
"registered until it has\n",
|
|
bundle.paths.executable);
|
|
}
|
|
IOLockLock(bundle.lock);
|
|
bool watching = bundle.state == kBundleWatching;
|
|
if (watching && found)
|
|
bundle.state = kBundleRegistering;
|
|
else if (watching)
|
|
armBundleCheck();
|
|
IOLockUnlock(bundle.lock);
|
|
if (watching && found)
|
|
registerAccelerator(static_cast<RgfxAccelerator *>(accelerator), "");
|
|
IOLockLock(bundle.lock);
|
|
bundle.running = false;
|
|
IOLockWakeup(bundle.lock, &bundle.running, false);
|
|
IOLockUnlock(bundle.lock);
|
|
}
|
|
} // namespace
|
|
|
|
bool RgfxAccelerator::watchBundle()
|
|
{
|
|
OSString *name = OSDynamicCast(OSString, getProperty("MetalPluginName"));
|
|
if (!name) {
|
|
IOLog("RgfxAccelerator: no MetalPluginName: not registered\n");
|
|
return false;
|
|
}
|
|
const char *n = name->getCStringNoCopy();
|
|
if (!rgfxBundlePaths(n, RGFX_VERSION, &bundle.paths)) {
|
|
IOLog("RgfxAccelerator: MetalPluginName %s is too long: not registered\n", n);
|
|
return false;
|
|
}
|
|
IOLock *lock = IOLockAlloc();
|
|
thread_call_t call = thread_call_allocate(checkBundle, this);
|
|
if (!lock || !call) {
|
|
IOLog("RgfxAccelerator: no memory for the bundle's check: not registered\n");
|
|
if (lock)
|
|
IOLockFree(lock);
|
|
if (call)
|
|
thread_call_free(call);
|
|
return false;
|
|
}
|
|
bundle.call = call;
|
|
bundle.lock = lock;
|
|
IOLockLock(bundle.lock);
|
|
armBundleCheck();
|
|
IOLockUnlock(bundle.lock);
|
|
return true;
|
|
}
|
|
|
|
void RgfxAccelerator::settleBundle()
|
|
{
|
|
if (bundleState() == kBundleWatching) {
|
|
RgfxGatePass gate = gatePass();
|
|
for (UInt32 waited = 0; gate == kRgfxGateInstalling && waited < kGatePassWaitMs;
|
|
waited += kGatePassLookMs) {
|
|
IOSleep(kGatePassLookMs);
|
|
gate = gatePass();
|
|
}
|
|
BundleFound found = gate == kRgfxGateInstalling ? kBundleAbsent : bundleOnDisk();
|
|
// The framebuffer that calls this is registered, its start under way or done: its
|
|
// connection is the server's first.
|
|
if (rgfxBundleRegisters(gate, found == kBundleOurs, true)) {
|
|
if (leaveWatching(kBundleRegistering))
|
|
registerAccelerator(this, " as WindowServer opens the display");
|
|
} else if (leaveWatching(kBundleSettled)) {
|
|
if (gate == kRgfxGateInstalling)
|
|
IOLog("RgfxAccelerator: RgfxGate's install pass has not ended as WindowServer "
|
|
"opens the display: not registered this boot\n");
|
|
else if (found == kBundleOtherVersion)
|
|
IOLog("RgfxAccelerator: the bundle at %s is not of wire version %u (no %s) as "
|
|
"WindowServer opens the display: not registered this boot. The bundle, the "
|
|
"kext and the host must come from one build.\n",
|
|
bundle.paths.executable, RGFX_VERSION, bundle.paths.marker);
|
|
else
|
|
IOLog("RgfxAccelerator: no bundle at %s as WindowServer opens the display: not "
|
|
"registered this boot\n",
|
|
bundle.paths.executable);
|
|
}
|
|
}
|
|
// A registration the repeating check began finishes before the connection is made.
|
|
for (UInt32 waited = 0; bundleState() == kBundleRegistering && waited < kBundleRegisterWaitMs;
|
|
waited++)
|
|
IOSleep(1);
|
|
}
|
|
|
|
#if defined(__arm64e__)
|
|
namespace {
|
|
// How long a process's read of MetalPluginName waits for RgfxGate's pass of its root, and how
|
|
// often it looks.
|
|
constexpr UInt32 kMetalNameHoldMs = 10000;
|
|
constexpr UInt32 kMetalNameLookMs = 10;
|
|
|
|
// The root file system's id (RgfxGate's rootId, RgfxGateInstall.cpp, kept in step by hand); false
|
|
// before there is a root.
|
|
bool rootId(unsigned long long *id)
|
|
{
|
|
vnode_t root = vfs_rootvnode();
|
|
if (!root)
|
|
return false;
|
|
mount_t mp = vnode_mount(root);
|
|
struct vfsstatfs *st = mp ? vfs_statfs(mp) : nullptr;
|
|
if (st)
|
|
*id = (static_cast<unsigned long long>(static_cast<uint32_t>(st->f_fsid.val[0])) << 32) |
|
|
static_cast<uint32_t>(st->f_fsid.val[1]);
|
|
vnode_put(root);
|
|
return st != nullptr;
|
|
}
|
|
|
|
// Whether a read of MetalPluginName on the current root waits (rgfxMetalNameWaits), from
|
|
// RgfxGate's property on IOResources and the root.
|
|
bool metalNameWaits()
|
|
{
|
|
IOService *resources = IOService::getResourceService();
|
|
OSObject *value = resources ? resources->copyProperty(kRgfxGatePassRootKey) : nullptr;
|
|
OSNumber *number = OSDynamicCast(OSNumber, value);
|
|
const bool watching = number != nullptr;
|
|
const unsigned long long passRoot = number ? number->unsigned64BitValue() : 0;
|
|
if (value)
|
|
value->release();
|
|
unsigned long long root = 0;
|
|
const bool haveRoot = watching && rootId(&root);
|
|
return rgfxMetalNameWaits(watching, passRoot, haveRoot, root);
|
|
}
|
|
|
|
bool isMetalName(const char *key)
|
|
{
|
|
return key && !strcmp(key, "MetalPluginName");
|
|
}
|
|
|
|
// A boot that starts in arm64's BaseSystem (FileVault's unlock, Recovery) registers the
|
|
// accelerator there, once RgfxGate's pass has put the bundle into the BaseSystem's temporary Data
|
|
// volume. The unlock then leaves for the full system by a userspace reboot that keeps the kernel,
|
|
// and the accelerator stays registered: the full system's WindowServer finds it at once, while
|
|
// RgfxGate's pass of the full system's Data volume, whose bundle may be another build's, has not
|
|
// run yet. Metal reads MetalPluginName before it loads the bundle the name names, so a process's
|
|
// read waits here, with no lock held, until the pass of its root has ended (RgfxGate publishes the
|
|
// root each pass ends under), up to kMetalNameHoldMs. A read in the kernel, and every read on a
|
|
// boot that starts in its full system, where RgfxGate publishes no root, goes on at once.
|
|
void holdMetalName(const char *what)
|
|
{
|
|
if (proc_selfpid() == 0 || !metalNameWaits())
|
|
return;
|
|
UInt32 waited = 0;
|
|
bool waits = true;
|
|
while (waits && waited < kMetalNameHoldMs) {
|
|
IOSleep(kMetalNameLookMs);
|
|
waited += kMetalNameLookMs;
|
|
waits = metalNameWaits();
|
|
}
|
|
char name[64] = {};
|
|
proc_selfname(name, sizeof(name));
|
|
if (waits)
|
|
IOLog("RgfxAccelerator: %s (pid %d) read %s on a root RgfxGate's pass has not reached in "
|
|
"%u ms: answered without it\n",
|
|
name, proc_selfpid(), what, waited);
|
|
else
|
|
IOLog("RgfxAccelerator: %s (pid %d) read %s on a root RgfxGate's pass had not reached: "
|
|
"held %u ms, until the pass ended\n",
|
|
name, proc_selfpid(), what, waited);
|
|
}
|
|
} // namespace
|
|
#endif
|
|
|
|
// MARK: - Registers
|
|
|
|
UInt32 RgfxAccelerator::readRegister(UInt32 offset) const
|
|
{
|
|
return rgfxRegisterRead32(registers + offset);
|
|
}
|
|
|
|
void RgfxAccelerator::writeRegister(UInt32 offset, UInt32 value)
|
|
{
|
|
rgfxRegisterWriteBarrier();
|
|
rgfxRegisterWrite32(registers + offset, value);
|
|
}
|
|
|
|
uint64_t RgfxAccelerator::featureWord() const
|
|
{
|
|
const uint64_t offered = (static_cast<uint64_t>(readRegister(RGFX_REG_FEATURES_HI)) << 32) |
|
|
readRegister(RGFX_REG_FEATURES_LO);
|
|
const uint64_t taken = (static_cast<uint64_t>(readRegister(RGFX_REG_DRIVER_FEATURES_HI)) << 32) |
|
|
readRegister(RGFX_REG_DRIVER_FEATURES_LO);
|
|
return rgfxFeatureWord(offered, taken);
|
|
}
|
|
|
|
// MARK: - IOService
|
|
|
|
namespace {
|
|
// The size, in bits, of the driver keys' numbers: 64, as the kernel makes a plist's <integer>, so
|
|
// a process reads each as a 64-bit CFNumber (kCFNumberSInt64Type).
|
|
constexpr unsigned kDriverKeyNumberBits = 64;
|
|
|
|
// The renderer ID the video driver's IOVARendererID carries: the AMD Navi family's, as an
|
|
// iMac20,1's Radeon Pro answers (the bundle's RgfxVideoDriver.cpp answers the same).
|
|
constexpr unsigned long long kVideoRendererID = 0x1020004ull;
|
|
|
|
// The accelerator's driver keys, on its registry entry, where the guest's frameworks read them:
|
|
// Metal the bundle and the class it makes the device of (MetalPluginName, MetalPluginClassName),
|
|
// OpenGL its renderer (IOGLBundleName), the display pipe's capabilities (AcceleratorProperties),
|
|
// and the display count (DisplayPortCount); the same on x86-64 and arm64. AppleGVA's video driver
|
|
// is named where the host decodes video, on x86-64 (publishVideoCodecs). The personality holds
|
|
// only what matches the provider and names the driver: Graft records the rest of a personality as
|
|
// the provider's matching. Set at the start of start, before registerService lets any process
|
|
// find the accelerator and before the bundle's check reads MetalPluginName.
|
|
bool setDriverKeys(IOService *service)
|
|
{
|
|
OSDictionary *pipe = OSDictionary::withCapacity(2);
|
|
OSDictionary *accel = OSDictionary::withCapacity(2);
|
|
OSString *category = OSString::withCString("IOAccelerator");
|
|
OSNumber *ports = OSNumber::withNumber(1ull, kDriverKeyNumberBits);
|
|
bool set = pipe && accel && category && ports &&
|
|
pipe->setObject("DisplayPipeSupported", kOSBooleanTrue) &&
|
|
pipe->setObject("TransactionsSupported", kOSBooleanTrue) &&
|
|
accel->setObject("IOAccelDisplayPipeCapabilities", pipe) &&
|
|
accel->setObject("IOMatchCategory", category) &&
|
|
service->setProperty("AcceleratorProperties", accel) &&
|
|
service->setProperty("DisplayPortCount", ports) &&
|
|
service->setProperty("IOGLBundleName", "AppleMetalOpenGLRenderer") &&
|
|
service->setProperty("MetalPluginClassName", "RgfxMetalDevice") &&
|
|
service->setProperty("MetalPluginName", "reims-graphics");
|
|
OSSafeReleaseNULL(ports);
|
|
OSSafeReleaseNULL(category);
|
|
OSSafeReleaseNULL(accel);
|
|
OSSafeReleaseNULL(pipe);
|
|
return set;
|
|
}
|
|
} // namespace
|
|
|
|
bool RgfxAccelerator::start(IOService *provider)
|
|
{
|
|
ReimsGraphics *fb = nullptr;
|
|
if (!setDriverKeys(this)) {
|
|
IOLog("RgfxAccelerator: no memory for its driver keys: not starting\n");
|
|
return false;
|
|
}
|
|
pci = OSDynamicCast(IOPCIDevice, provider);
|
|
if (!pci)
|
|
return false;
|
|
// The framebuffer enables these too; doing so again is harmless. The
|
|
// accelerator needs BAR 0 for the doorbell and BAR 2 to hand to the bundle.
|
|
pci->setMemoryEnable(true);
|
|
// setBusMasterEnable rather than setBusLeadEnable, which macOS 11 does not export: a call
|
|
// through IOPCIDevice's vtable, the same slot on macOS 11 to 26 (ReimsGraphics::start).
|
|
#pragma clang diagnostic push
|
|
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
|
pci->setBusMasterEnable(true);
|
|
#pragma clang diagnostic pop
|
|
|
|
registerMap = pci->mapDeviceMemoryWithRegister(kIOPCIConfigBaseAddress0);
|
|
if (!registerMap) {
|
|
IOLog("RgfxAccelerator: BAR0 not mapped\n");
|
|
goto fail;
|
|
}
|
|
registers = reinterpret_cast<volatile UInt8 *>(registerMap->getVirtualAddress());
|
|
if (readRegister(RGFX_REG_MAGIC) != RGFX_MAGIC) {
|
|
IOLog("RgfxAccelerator: not the device: magic 0x%x\n", readRegister(RGFX_REG_MAGIC));
|
|
goto fail;
|
|
}
|
|
// The wire's version names the region's layout and the messages (design.md, "The wire's
|
|
// version"): a kext of another version misreads them, so it leaves the device.
|
|
if (readRegister(RGFX_REG_VERSION) != RGFX_VERSION) {
|
|
IOLog("RgfxAccelerator: the device speaks wire version %u, this kext version %u: not starting. "
|
|
"The kext and the host must come from one build.\n",
|
|
readRegister(RGFX_REG_VERSION), RGFX_VERSION);
|
|
goto fail;
|
|
}
|
|
|
|
region = pci->getDeviceMemoryWithRegister(kIOPCIConfigBaseAddress2);
|
|
if (!region) {
|
|
IOLog("RgfxAccelerator: no BAR2\n");
|
|
goto fail;
|
|
}
|
|
region->retain();
|
|
regionSize = (static_cast<UInt64>(readRegister(RGFX_REG_REGION_SIZE_HI)) << 32) |
|
|
readRegister(RGFX_REG_REGION_SIZE_LO);
|
|
if (regionSize > region->getLength())
|
|
regionSize = region->getLength();
|
|
if (regionSize <= RGFX_ALLOCATIONS_OFFSET) {
|
|
IOLog("RgfxAccelerator: the region is too small: 0x%llx bytes\n", regionSize);
|
|
goto fail;
|
|
}
|
|
|
|
// The Metal discovery keys (MetalPluginName / MetalPluginClassName) that make Metal
|
|
// load the bundle are on this service already (setDriverKeys, above); so is
|
|
// IOGLBundleName, the GL renderer OpenGL loads for it (AppleMetalOpenGLRenderer,
|
|
// which runs on the bundle's Metal device). The
|
|
// accelerator does not touch pixels or the control ring (the framebuffer owns
|
|
// those); it only publishes those keys and vends the region-map + doorbell user
|
|
// client. registerService lets Metal's IOServiceMatching("IOAccelerator")
|
|
// notification see it, once the bundle is on disk ("The bundle", above).
|
|
if (!super::start(provider))
|
|
goto fail;
|
|
// The accelerator's index, the one the framebuffer names it by (ReimsGraphics' IOAccelIndex):
|
|
// IOPresentment reads it here, before registerService, to match the display to this GPU.
|
|
setProperty(kIOAccelIndexKey, 0ull, 32);
|
|
// The GPU's memory, as a Mac's GPU states it (RgfxMemorySize.hpp): VRAM,totalMB on the PCI
|
|
// device, where system_profiler reads a discrete GPU's, and on the accelerator, where an
|
|
// Intel GPU states it. A host that gave no working set has none stated.
|
|
{
|
|
RgfxMemorySize memory;
|
|
if (readMemorySize(&memory) && memory.vramMB) {
|
|
pci->setProperty("VRAM,totalMB", memory.vramMB, 32);
|
|
setProperty("VRAM,totalMB", memory.vramMB, 32);
|
|
}
|
|
}
|
|
// The GPU's name, as a Mac's GPU states it (RgfxDeviceName.hpp): `model` on the PCI device,
|
|
// which System Information shows as its Chipset Model. On an arm64 guest a host that gave no
|
|
// name has none stated.
|
|
{
|
|
uint8_t model[kRgfxDeviceModelMax];
|
|
const size_t length = readDeviceModel(model);
|
|
if (OSData *data = length ? OSData::withBytes(model, static_cast<unsigned>(length)) : nullptr) {
|
|
pci->setProperty("model", data);
|
|
data->release();
|
|
}
|
|
}
|
|
// The GPU's class, as a Mac's GPU states it (RgfxPciClass.hpp): `class-code` on the PCI
|
|
// device, where software in the guest lists the Mac's GPUs.
|
|
if (OSData *data = OSData::withBytes(kRgfxMacGpuClassCode, sizeof(kRgfxMacGpuClassCode))) {
|
|
pci->setProperty("class-code", data);
|
|
data->release();
|
|
}
|
|
nameProviderForVideo();
|
|
// AppleGVA reads the video codecs off this service once Metal's matching sees it, after
|
|
// registerService.
|
|
publishVideoCodecs();
|
|
// Before any process that lays out a surface: WindowServer starts after the kernel's boot.
|
|
setSurfaceLimits();
|
|
// Name this accelerator on the framebuffer, if it has started already (else the display
|
|
// pipe's first association does).
|
|
if (!keptLock)
|
|
keptLock = IOLockAlloc();
|
|
OSSafeReleaseNULL(fb);
|
|
fb = copyFramebuffer();
|
|
// The display count, where the framebuffer drives more than one (ReimsGraphics' start sets it
|
|
// too, where it starts after).
|
|
if (fb && fb->drivenDisplays() > 1)
|
|
setProperty("DisplayPortCount", static_cast<unsigned long long>(fb->drivenDisplays()), 64);
|
|
// Without the check (no bundle named, no memory for it) the accelerator stays unregistered,
|
|
// as without the bundle.
|
|
if (watchBundle())
|
|
IOLog("RgfxAccelerator: ready, region 0x%llx bytes, framebuffer %s; registers once %s "
|
|
"and %s are on disk\n",
|
|
regionSize, fb ? "named" : "not yet started", bundle.paths.executable,
|
|
bundle.paths.marker);
|
|
OSSafeReleaseNULL(fb);
|
|
return true;
|
|
fail:
|
|
teardown();
|
|
return false;
|
|
}
|
|
|
|
void RgfxAccelerator::stop(IOService *provider)
|
|
{
|
|
// The check ends: a pending one is cancelled, a running one (registerService included)
|
|
// finishes first, and one that starts after finds the watch settled and does nothing.
|
|
if (bundle.lock) {
|
|
leaveWatching(kBundleSettled);
|
|
IOLockLock(bundle.lock);
|
|
while (bundle.running)
|
|
IOLockSleep(bundle.lock, &bundle.running, THREAD_UNINT);
|
|
IOLockUnlock(bundle.lock);
|
|
thread_call_free(bundle.call);
|
|
}
|
|
// The framebuffer stops calling queueFilter, queueInterrupt and the release hook (and lets
|
|
// this accelerator go).
|
|
if (ReimsGraphics *fb = copyFramebuffer()) {
|
|
fb->setQueueInterrupt(nullptr, nullptr, nullptr);
|
|
fb->setReleaseAnswer(nullptr, nullptr);
|
|
fb->release();
|
|
}
|
|
if (keptLock) {
|
|
IOLockLock(keptLock);
|
|
ReimsGraphics *kept = keptFramebuffer;
|
|
keptFramebuffer = nullptr;
|
|
IOLockUnlock(keptLock);
|
|
OSSafeReleaseNULL(kept);
|
|
}
|
|
super::stop(provider);
|
|
teardown();
|
|
}
|
|
|
|
void RgfxAccelerator::teardown()
|
|
{
|
|
OSSafeReleaseNULL(region);
|
|
OSSafeReleaseNULL(registerMap);
|
|
registers = nullptr;
|
|
}
|
|
|
|
|
|
// MARK: - The user client
|
|
|
|
IOReturn RgfxAccelerator::newUserClient(task_t owningTask, void *securityID, UInt32 type,
|
|
OSDictionary *properties, IOUserClient **handler)
|
|
{
|
|
// The types served: the display pipe (4), the one the IOGPUMetalDevice base builds its
|
|
// device over (5), ours, a shared event's port (RgfxSharedEventUserClient), and a GL
|
|
// window's drawable (7) and surface (0x20) (RgfxGLUserClients.hpp). Any other is refused,
|
|
// logged once per type. IOAccel surfaces (0) are among them: CoreDisplay opens them at
|
|
// display start for its display surface, and maps the framebuffer's memory for it when
|
|
// they are refused.
|
|
RgfxCaller caller;
|
|
IOLog("RGFX: newUserClient type=%u from %s[%d]\n", type, caller.name, caller.pid);
|
|
// Unregistered, without its bundle, the accelerator is no GPU ("The bundle"): a task that
|
|
// reaches it by path (the framebuffer's IOAccelTypes) is refused, logged once per type.
|
|
UInt32 standing = bundleState();
|
|
if (standing != kBundleRegistering && standing != kBundleRegistered) {
|
|
static char site;
|
|
if (rgfxFirstCalls(&site, type, 1))
|
|
IOLog("RGFX: user client type %u from %s[%d] refused: the accelerator is not "
|
|
"registered\n",
|
|
type, caller.name, caller.pid);
|
|
return kIOReturnNotReady;
|
|
}
|
|
if (type == kRgfxDisplayPipeUserClientType)
|
|
return newDisplayPipe(owningTask, securityID, type, properties, handler);
|
|
if (type == kRgfxSharedEventUserClientType)
|
|
return newSharedEventPort(owningTask, securityID, type, properties, handler);
|
|
if (type == kRgfxGLDrawableUserClientType || type == kRgfxGLSurfaceUserClientType)
|
|
return newGLClient(owningTask, securityID, type, properties, handler);
|
|
if (type != kRgfxAccelUserClientType && type != kRgfxIOGPUDeviceUserClientType) {
|
|
static char site;
|
|
if (rgfxFirstCalls(&site, type, 1))
|
|
IOLog("RGFX: user client type %u from %s[%d] is not supported\n", type, caller.name,
|
|
caller.pid);
|
|
return kIOReturnUnsupported;
|
|
}
|
|
|
|
RgfxAcceleratorUserClient *client = OSTypeAlloc(RgfxAcceleratorUserClient);
|
|
if (!client)
|
|
return kIOReturnNoMemory;
|
|
if (!client->initWithTask(owningTask, securityID, type, properties)) {
|
|
client->release();
|
|
return kIOReturnBadArgument;
|
|
}
|
|
if (!client->attach(this)) {
|
|
client->release();
|
|
return kIOReturnInternalError;
|
|
}
|
|
if (!client->start(this)) {
|
|
client->detach(this);
|
|
client->release();
|
|
return kIOReturnInternalError;
|
|
}
|
|
*handler = client;
|
|
return kIOReturnSuccess;
|
|
}
|
|
|
|
// The display pipe WindowServer presents through (RgfxDisplayPipeUserClient).
|
|
IOReturn RgfxAccelerator::newDisplayPipe(task_t owningTask, void *securityID, UInt32 type,
|
|
OSDictionary *properties, IOUserClient **handler)
|
|
{
|
|
RgfxDisplayPipeUserClient *client = OSTypeAlloc(RgfxDisplayPipeUserClient);
|
|
if (!client)
|
|
return kIOReturnNoMemory;
|
|
if (!client->initWithTask(owningTask, securityID, type, properties)) {
|
|
client->release();
|
|
return kIOReturnBadArgument;
|
|
}
|
|
if (!client->attach(this)) {
|
|
client->release();
|
|
return kIOReturnInternalError;
|
|
}
|
|
if (!client->start(this)) {
|
|
client->detach(this);
|
|
client->release();
|
|
return kIOReturnInternalError;
|
|
}
|
|
*handler = client;
|
|
return kIOReturnSuccess;
|
|
}
|
|
|
|
// A GL window's drawable or surface (RgfxGLUserClients.hpp).
|
|
IOReturn RgfxAccelerator::newGLClient(task_t owningTask, void *securityID, UInt32 type,
|
|
OSDictionary *properties, IOUserClient **handler)
|
|
{
|
|
IOUserClient *client = nullptr;
|
|
if (type == kRgfxGLDrawableUserClientType)
|
|
client = OSTypeAlloc(RgfxGLDrawableUserClient);
|
|
else
|
|
client = OSTypeAlloc(RgfxGLSurfaceUserClient);
|
|
if (!client)
|
|
return kIOReturnNoMemory;
|
|
if (!client->initWithTask(owningTask, securityID, type, properties)) {
|
|
client->release();
|
|
return kIOReturnNoResources;
|
|
}
|
|
if (!client->attach(this)) {
|
|
client->release();
|
|
return kIOReturnInternalError;
|
|
}
|
|
if (!client->start(this)) {
|
|
client->detach(this);
|
|
client->release();
|
|
return kIOReturnInternalError;
|
|
}
|
|
*handler = client;
|
|
return kIOReturnSuccess;
|
|
}
|
|
|
|
// An IOAccel surface (RgfxSurfaceUserClient).
|
|
IOReturn RgfxAccelerator::newSurface(task_t owningTask, void *securityID, UInt32 type,
|
|
OSDictionary *properties, IOUserClient **handler)
|
|
{
|
|
RgfxSurfaceUserClient *client = OSTypeAlloc(RgfxSurfaceUserClient);
|
|
if (!client)
|
|
return kIOReturnNoMemory;
|
|
if (!client->initWithTask(owningTask, securityID, type, properties)) {
|
|
client->release();
|
|
return kIOReturnBadArgument;
|
|
}
|
|
if (!client->attach(this)) {
|
|
client->release();
|
|
return kIOReturnInternalError;
|
|
}
|
|
if (!client->start(this)) {
|
|
client->detach(this);
|
|
client->release();
|
|
return kIOReturnInternalError;
|
|
}
|
|
*handler = client;
|
|
return kIOReturnSuccess;
|
|
}
|
|
|
|
// MARK: - Reached from the user client
|
|
|
|
ReimsGraphics *RgfxAccelerator::copyFramebuffer()
|
|
{
|
|
// The one kept, while it is live: a lookup walks the PCI device's clients and builds this
|
|
// accelerator's path under the registry's lock, which every message the kext posts paid for.
|
|
// One that stopped or was terminated is let go, and the lookup made again (RgfxKeptService.hpp).
|
|
KeptOps ops;
|
|
if (keptLock) {
|
|
ReimsGraphics *dropped = nullptr;
|
|
IOLockLock(keptLock);
|
|
ReimsGraphics *kept = rgfxKeptTake(keptFramebuffer, ops, &dropped);
|
|
IOLockUnlock(keptLock);
|
|
OSSafeReleaseNULL(dropped);
|
|
if (kept)
|
|
return kept;
|
|
}
|
|
if (!pci)
|
|
return nullptr;
|
|
ReimsGraphics *found = nullptr;
|
|
OSIterator *clients = pci->getClientIterator();
|
|
if (clients) {
|
|
// Display 0's, which owns the device: the other displays' framebuffers (heads) are the
|
|
// PCI device's clients too.
|
|
while (OSObject *o = clients->getNextObject()) {
|
|
found = OSDynamicCast(ReimsGraphics, o);
|
|
if (found && !found->isHead()) {
|
|
found->retain();
|
|
break;
|
|
}
|
|
found = nullptr;
|
|
}
|
|
clients->release();
|
|
}
|
|
// Named by this accelerator's path as it stands (RgfxAccelTypes.hpp), on every display's
|
|
// framebuffer: the framebuffer, started first, named it through the PCI device's name before
|
|
// nameProviderForVideo renamed the device GFX0, a path that no longer leads anywhere.
|
|
if (found) {
|
|
char path[512];
|
|
int length = sizeof(path);
|
|
if (getPath(path, &length, gIOServicePlane))
|
|
found->nameAccelerator(path);
|
|
}
|
|
// Kept once it is live, as named: the rename is this accelerator's own, at its start, before
|
|
// any lookup (nameProviderForVideo), so the path stays as it stands now.
|
|
if (found && keptLock) {
|
|
IOLockLock(keptLock);
|
|
rgfxKeptOffer(keptFramebuffer, ops, found);
|
|
IOLockUnlock(keptLock);
|
|
}
|
|
return found;
|
|
}
|
|
|
|
ReimsGraphics *RgfxAccelerator::copyDisplay(UInt32 display)
|
|
{
|
|
ReimsGraphics *fb = copyFramebuffer();
|
|
if (!fb)
|
|
return nullptr;
|
|
ReimsGraphics *driver = fb->copyDisplay(display);
|
|
fb->release();
|
|
return driver;
|
|
}
|
|
|
|
bool RgfxAccelerator::framebufferStarted()
|
|
{
|
|
ReimsGraphics *fb = copyFramebuffer();
|
|
const bool started = fb && fb->hasStarted();
|
|
OSSafeReleaseNULL(fb);
|
|
return started;
|
|
}
|
|
|
|
IODeviceMemory *RgfxAccelerator::copyRegion() const
|
|
{
|
|
if (region)
|
|
region->retain();
|
|
return region;
|
|
}
|
|
|
|
bool RgfxAccelerator::readMemorySize(RgfxMemorySize *out) const
|
|
{
|
|
if (!region)
|
|
return false;
|
|
// The device info's pages that hold the two answers, mapped into the kernel write-back as
|
|
// the user client's device info is: the region is BAR memory, which a physical copy does not
|
|
// read.
|
|
const UInt64 first = RGFX_DEVICE_INFO_OFFSET + kRgfxMemorySizeFirst;
|
|
const UInt64 page = first & ~0xfffull;
|
|
const UInt64 length =
|
|
((RGFX_DEVICE_INFO_OFFSET + kRgfxMemorySizeEnd + 0xfffull) & ~0xfffull) - page;
|
|
IOMemoryMap *map = region->createMappingInTask(
|
|
kernel_task, 0, kIOMapAnywhere | kIOMapCopybackCache | kIOMapReadOnly, page, length);
|
|
if (!map)
|
|
return false;
|
|
*out = rgfxMemorySizeFrom(reinterpret_cast<const uint8_t *>(map->getVirtualAddress()) +
|
|
(first - page));
|
|
map->release();
|
|
return true;
|
|
}
|
|
|
|
size_t RgfxAccelerator::readDeviceModel(uint8_t (&out)[kRgfxDeviceModelMax]) const
|
|
{
|
|
const void *info = nullptr;
|
|
IOMemoryMap *map = mapDeviceInfo(kRgfxDeviceNameEnd, &info);
|
|
if (!map)
|
|
return 0;
|
|
const size_t length =
|
|
rgfxDeviceModelFrom(static_cast<const uint8_t *>(info) + kRgfxDeviceNameFirst, out);
|
|
map->release();
|
|
return length;
|
|
}
|
|
|
|
IOMemoryMap *RgfxAccelerator::mapDeviceInfo(UInt64 size, const void **info) const
|
|
{
|
|
if (!region)
|
|
return nullptr;
|
|
// Its pages, mapped into the kernel write-back as the framebuffer maps the rings: the
|
|
// region is BAR memory, which a physical copy does not read.
|
|
const UInt64 page = RGFX_DEVICE_INFO_OFFSET & ~0xfffull;
|
|
const UInt64 length = ((RGFX_DEVICE_INFO_OFFSET + size + 0xfffull) & ~0xfffull) - page;
|
|
IOMemoryMap *map = region->createMappingInTask(
|
|
kernel_task, 0, kIOMapAnywhere | kIOMapCopybackCache | kIOMapReadOnly, page, length);
|
|
if (map)
|
|
*info = reinterpret_cast<const UInt8 *>(map->getVirtualAddress()) +
|
|
(RGFX_DEVICE_INFO_OFFSET - page);
|
|
return map;
|
|
}
|
|
|
|
void RgfxAccelerator::nameProviderForVideo()
|
|
{
|
|
// AppleGVA's hardware video routes to its vendor driver through the GPU it finds by the
|
|
// name real AMD Macs give the GPU's PCI device, GFX0 (on an iMac20,1 with
|
|
// forceOfflineRenderer it looks for GFX0/IGPU). HEVC decode needs it: without it
|
|
// VTDecompressionSessionCreate refuses every HEVC stream with -12913 and our driver is
|
|
// never called, while H.264 decodes all the same and the IOGVACodec name makes no
|
|
// difference (measured on the msi 5080, 2026-11-03: three boots with the provider's
|
|
// default name refused HEVC, a fourth that only named it GFX0 decoded every frame). So
|
|
// the provider is named GFX0, as the hardware does, before registerService lets any
|
|
// AppleGVA lookup see it. Where another device already carries the name (a renamer like
|
|
// WhateverGreen, or a second GPU), the name is left as it was, so two GFX0s are never
|
|
// published.
|
|
if (OSDictionary *match = IOService::nameMatching("GFX0")) {
|
|
IOService *existing = IOService::copyMatchingService(match);
|
|
match->release();
|
|
if (existing) {
|
|
IOLog("RgfxAccelerator: a device is already named GFX0; leaving the provider named %s\n",
|
|
pci->getName());
|
|
existing->release();
|
|
return;
|
|
}
|
|
}
|
|
pci->setName("GFX0");
|
|
}
|
|
|
|
static_assert(kRgfxIOSurfaceNoLimit == kRgfxSurfaceNoLimit, "IOSurfaceRoot's own limit");
|
|
|
|
void RgfxAccelerator::setSurfaceLimits()
|
|
{
|
|
const void *info = nullptr;
|
|
const uint64_t end = kRgfxSurfaceRowsEnd > kRgfxSurfaceLimitsEnd ? kRgfxSurfaceRowsEnd
|
|
: kRgfxSurfaceLimitsEnd;
|
|
IOMemoryMap *map = mapDeviceInfo(end, &info);
|
|
if (!map)
|
|
return;
|
|
const uint8_t *bytes = static_cast<const uint8_t *>(info);
|
|
const uint32_t align = rgfxSurfaceRowAlignmentFrom(bytes + kRgfxSurfaceRowsFirst);
|
|
const RgfxSurfaceLimits limits = rgfxSurfaceLimitsFrom(bytes + kRgfxSurfaceLimitsFirst);
|
|
map->release();
|
|
// IOSurfaceRoot starts with IOSurface.kext, which a GPU's accelerator waits for as well.
|
|
OSDictionary *matching = IOService::serviceMatching("IOSurfaceRoot");
|
|
IOService *root =
|
|
matching ? IOService::waitForMatchingService(matching, kSurfaceRootWaitNs) : nullptr;
|
|
OSSafeReleaseNULL(matching);
|
|
if (!root) {
|
|
IOLog("RgfxAccelerator: no IOSurfaceRoot: surfaces' rows stay at IOSurface's alignment, "
|
|
"not the host GPU's %u bytes, and IOSurface's limits stay its own\n",
|
|
align);
|
|
return;
|
|
}
|
|
// The plane offsets IOSurface works out take the host's alignment as the rows do, as the
|
|
// GPU's linear images start there; a mask of 0 ORs nothing in: IOSurface's own alignment
|
|
// where the host asks no more.
|
|
const uint32_t mask = align > kRgfxSurfaceRowsLeast ? align - 1 : 0;
|
|
rgfxIOSurfaceRootUpdateLimits(root, mask, mask, limits.bytesPerRow, limits.width,
|
|
limits.height);
|
|
root->release();
|
|
if (align > kRgfxSurfaceRowsLeast)
|
|
IOLog("RgfxAccelerator: IOSurface aligns the bytes per row and plane offsets it works out "
|
|
"to %u, as the host's GPU takes linear images in place\n",
|
|
align);
|
|
IOLog("RgfxAccelerator: IOSurface answers surfaces of at most %u x %u and %u bytes a row, as "
|
|
"the device's textures take them\n",
|
|
limits.width, limits.height, limits.bytesPerRow);
|
|
}
|
|
|
|
void RgfxAccelerator::publishVideoCodecs()
|
|
{
|
|
static_assert(RGFX_VIDEO_CAPS_OFFSET == RGFX_DEVICE_INFO_OFFSET + sizeof(RgfxDeviceInfo),
|
|
"the video caps follow the device info");
|
|
// An arm64 guest's AppleGVA takes no session to our video driver: named, VideoToolbox would
|
|
// answer hardware HEVC decode that no session can have (RgfxVideoCodecs.hpp).
|
|
if (!kRgfxGuestVideoDriver) {
|
|
IOLog("RgfxAccelerator: an arm64 guest takes no GPU video driver: no video driver for "
|
|
"AppleGVA\n");
|
|
return;
|
|
}
|
|
const void *info = nullptr;
|
|
IOMemoryMap *map = mapDeviceInfo(sizeof(RgfxDeviceInfo) + sizeof(RgfxVideoCaps), &info);
|
|
if (!map)
|
|
return;
|
|
RgfxVideoCaps caps;
|
|
memcpy(&caps, reinterpret_cast<const UInt8 *>(info) + sizeof(RgfxDeviceInfo), sizeof(caps));
|
|
map->release();
|
|
// AppleGVA's video driver, the bundle (IODVDBundleName), where the host decodes video:
|
|
// named on a host with no decoder, VideoToolbox would answer a hardware H.264 decoder and
|
|
// list a hardware H.264 encoder that no session can have (RgfxVideoCodecs.hpp).
|
|
if (!rgfxDecodesVideo(caps)) {
|
|
IOLog("RgfxAccelerator: the host decodes no video: no video driver for AppleGVA\n");
|
|
return;
|
|
}
|
|
if (OSNumber *renderer = OSNumber::withNumber(kVideoRendererID, kDriverKeyNumberBits)) {
|
|
setProperty("IODVDBundleName", "reims-graphics");
|
|
setProperty("IOGVACodec", "RgfxVideo");
|
|
setProperty("IOVARendererID", renderer);
|
|
renderer->release();
|
|
}
|
|
if (rgfxH264Encode(caps)) {
|
|
OSDictionary *h264 = OSDictionary::withCapacity(2);
|
|
OSNumber *rating = OSNumber::withNumber(kRgfxH264EncodeRating, 32);
|
|
OSNumber *quality = OSNumber::withNumber(kRgfxH264EncodeQualityRating, 32);
|
|
if (h264 && rating && quality && h264->setObject("VTRating", rating) &&
|
|
h264->setObject("VTQualityRating", quality)) {
|
|
setProperty("IOGVAH264EncodeCapabilities", h264);
|
|
IOLog("RgfxAccelerator: H.264 encode\n");
|
|
}
|
|
OSSafeReleaseNULL(quality);
|
|
OSSafeReleaseNULL(rating);
|
|
OSSafeReleaseNULL(h264);
|
|
}
|
|
RgfxHevcEncode hevcEncode;
|
|
if (rgfxHevcEncode(caps, &hevcEncode))
|
|
hevcEncodeLevel = hevcEncode.maxLevel;
|
|
RgfxHevcDecode hevc;
|
|
if (!rgfxHevcDecode(caps, &hevc))
|
|
return;
|
|
OSArray *profiles = OSArray::withCapacity(hevc.count);
|
|
OSDictionary *details = OSDictionary::withCapacity(hevc.count);
|
|
OSDictionary *capabilities = OSDictionary::withCapacity(2);
|
|
OSNumber *level = OSNumber::withNumber(hevc.maxLevel, 32);
|
|
OSDictionary *profileDetail = OSDictionary::withCapacity(1);
|
|
bool made = profiles && details && capabilities && level && profileDetail &&
|
|
profileDetail->setObject("VTMaxDecodeLevel", level);
|
|
for (uint32_t i = 0; made && i < hevc.count; i++) {
|
|
char key[4];
|
|
snprintf(key, sizeof key, "%u", hevc.profiles[i]);
|
|
OSNumber *profile = OSNumber::withNumber(hevc.profiles[i], 32);
|
|
made = profile && profiles->setObject(profile) && details->setObject(key, profileDetail);
|
|
OSSafeReleaseNULL(profile);
|
|
}
|
|
if (made && capabilities->setObject("VTSupportedProfileArray", profiles) &&
|
|
capabilities->setObject("VTPerProfileDetails", details)) {
|
|
setProperty("IOGVAHEVCDecode", "1");
|
|
setProperty("IOGVAHEVCDecodeCapabilities", capabilities);
|
|
IOLog("RgfxAccelerator: HEVC decode, %u profiles, level %u\n", hevc.count, hevc.maxLevel);
|
|
}
|
|
OSSafeReleaseNULL(profileDetail);
|
|
OSSafeReleaseNULL(level);
|
|
OSSafeReleaseNULL(capabilities);
|
|
OSSafeReleaseNULL(details);
|
|
OSSafeReleaseNULL(profiles);
|
|
}
|
|
|
|
// The guest's HEVC encoder plug-in (AppleGVAHEVCEncoder) finds a GPU encoder on an x86-64 Mac by
|
|
// name alone: the last service named IntelAccelerator whose IOGVACodec names an Intel generation
|
|
// ("Gen9" picks the driver at AppleIntelSKLGraphicsVADriver.bundle, which RgfxGate links to the
|
|
// bundle), with IOGVAHEVCEncode and IOVARendererID on it, and VideoToolbox lists that encoder
|
|
// with the capabilities IOGVAHEVCEncodeCapabilities carries. The nub is a plain IOService, a
|
|
// child of the accelerator, with no IODVDBundleName, which AppleGVA's own loader skips: no Metal
|
|
// device, no framebuffer, and none of AppleGVA's other routes moves to it (their Intel route
|
|
// looks only under IGPU@2 or GFX0@2). Main and Main 10, up to the host encoder's level: the two
|
|
// profiles the plug-in names, both of which the host encodes where the nub is published
|
|
// (rgfxHevcEncode).
|
|
void RgfxAccelerator::publishHevcEncoder()
|
|
{
|
|
const uint32_t level = hevcEncodeLevel;
|
|
if (level == 0)
|
|
return;
|
|
IOService *nub = OSTypeAlloc(IOService);
|
|
if (!nub || !nub->init()) {
|
|
OSSafeReleaseNULL(nub);
|
|
IOLog("RgfxAccelerator: no HEVC encoder: no memory\n");
|
|
return;
|
|
}
|
|
nub->setName("IntelAccelerator");
|
|
nub->setProperty("IOGVACodec", "Gen9");
|
|
nub->setProperty("IOGVAHEVCEncode", "2");
|
|
nub->setProperty("IOVARendererID", kVideoRendererID, kDriverKeyNumberBits);
|
|
OSArray *profiles = OSArray::withCapacity(2);
|
|
OSDictionary *details = OSDictionary::withCapacity(2);
|
|
OSDictionary *capabilities = OSDictionary::withCapacity(4);
|
|
OSNumber *maxLevel = OSNumber::withNumber(level, 32);
|
|
OSNumber *rating = OSNumber::withNumber(kRgfxHevcEncodeRating, 32);
|
|
OSNumber *quality = OSNumber::withNumber(kRgfxHevcEncodeQualityRating, 32);
|
|
OSNumber *mainProfile = OSNumber::withNumber(1, 32);
|
|
OSNumber *main10Profile = OSNumber::withNumber(2, 32);
|
|
OSDictionary *profileDetail = OSDictionary::withCapacity(1);
|
|
const bool made = profiles && details && capabilities && maxLevel && rating && quality &&
|
|
mainProfile && main10Profile && profileDetail &&
|
|
profileDetail->setObject("VTMaxEncodeLevel", maxLevel) &&
|
|
profiles->setObject(mainProfile) && profiles->setObject(main10Profile) &&
|
|
details->setObject("1", profileDetail) &&
|
|
details->setObject("2", profileDetail) &&
|
|
capabilities->setObject("VTSupportedProfileArray", profiles) &&
|
|
capabilities->setObject("VTPerProfileDetails", details) &&
|
|
capabilities->setObject("VTRating", rating) &&
|
|
capabilities->setObject("VTQualityRating", quality) &&
|
|
nub->setProperty("IOGVAHEVCEncodeCapabilities", capabilities);
|
|
OSSafeReleaseNULL(profileDetail);
|
|
OSSafeReleaseNULL(main10Profile);
|
|
OSSafeReleaseNULL(mainProfile);
|
|
OSSafeReleaseNULL(quality);
|
|
OSSafeReleaseNULL(rating);
|
|
OSSafeReleaseNULL(maxLevel);
|
|
OSSafeReleaseNULL(capabilities);
|
|
OSSafeReleaseNULL(details);
|
|
OSSafeReleaseNULL(profiles);
|
|
if (made && nub->attach(this)) {
|
|
nub->registerService();
|
|
IOLog("RgfxAccelerator: HEVC encode, Main and Main 10, level %u\n", level);
|
|
} else {
|
|
IOLog("RgfxAccelerator: no HEVC encoder: its nub not made\n");
|
|
}
|
|
nub->release();
|
|
}
|
|
|
|
// A queue's doorbell exits to the host, which may offer the ring's next command buffer to its
|
|
// decoder before the write returns: the write holds no lock and leaves interrupts as they are, so
|
|
// the CPU takes its IPIs (a TLB shootdown's among them) however long the host takes, and the
|
|
// other CPUs' rings go to the host meanwhile. A ring id is one 32-bit write, which needs no lock.
|
|
void RgfxAccelerator::ringDoorbell(UInt32 ringId)
|
|
{
|
|
if (!registers)
|
|
return;
|
|
writeRegister(RGFX_REG_DOORBELL, ringId);
|
|
}
|
|
|
|
#if RGFX_FB_TRACE || defined(__arm64e__)
|
|
// MARK: - The properties processes read
|
|
//
|
|
// A trace build logs them. On arm64 a read of MetalPluginName waits for RgfxGate's pass of the
|
|
// reader's root first (holdMetalName, "the bundle").
|
|
|
|
OSObject *RgfxAccelerator::copyProperty(const OSSymbol *aKey) const
|
|
{
|
|
#if defined(__arm64e__)
|
|
if (aKey && isMetalName(aKey->getCStringNoCopy()))
|
|
holdMetalName("MetalPluginName");
|
|
#endif
|
|
OSObject *o = super::copyProperty(aKey);
|
|
#if RGFX_FB_TRACE
|
|
rgfxTracePropertyRead("accel", aKey ? aKey->getCStringNoCopy() : nullptr, o != nullptr);
|
|
#endif
|
|
return o;
|
|
}
|
|
|
|
OSObject *RgfxAccelerator::copyProperty(const OSString *aKey) const
|
|
{
|
|
#if defined(__arm64e__)
|
|
if (aKey && isMetalName(aKey->getCStringNoCopy()))
|
|
holdMetalName("MetalPluginName");
|
|
#endif
|
|
OSObject *o = super::copyProperty(aKey);
|
|
#if RGFX_FB_TRACE
|
|
rgfxTracePropertyRead("accel", aKey ? aKey->getCStringNoCopy() : nullptr, o != nullptr);
|
|
#endif
|
|
return o;
|
|
}
|
|
|
|
OSObject *RgfxAccelerator::copyProperty(const char *aKey) const
|
|
{
|
|
#if defined(__arm64e__)
|
|
if (isMetalName(aKey))
|
|
holdMetalName("MetalPluginName");
|
|
#endif
|
|
OSObject *o = super::copyProperty(aKey);
|
|
#if RGFX_FB_TRACE
|
|
rgfxTracePropertyRead("accel", aKey, o != nullptr);
|
|
#endif
|
|
return o;
|
|
}
|
|
#endif
|
|
|
|
#if defined(__arm64e__)
|
|
bool RgfxAccelerator::serializeProperties(OSSerialize *s) const
|
|
{
|
|
holdMetalName("its properties");
|
|
return super::serializeProperties(s);
|
|
}
|
|
#endif
|