hw/display/apple-gfx: New macOS PV Graphics device
v2 cover hw/display/apple-gfx: New macOS PV Graphics device
This sequence of patches integrates the paravirtualised graphics device implemented by macOS's ParavirtualizedGraphics.Framework into Qemu. Combined with the guest drivers which ship with macOS versions 11 and up, this allows the guest OS to use the host's GPU for hardware accelerated 3D graphics, GPGPU compute (both using the 'Metal' graphics API), and window compositing.
Some background:
----------------
The device exposed by the ParavirtualizedGraphics.Framework's (henceforth PVG) public API consists of a PCI device with a single memory-mapped BAR; the VMM is expected to pass reads and writes through to the framework, and to forward interrupts emenating from it to the guest VM.
The bulk of data exchange between host and guest occurs via shared memory, however. For this purpose, PVG makes callbacks to VMM code for allocating, mapping, unmapping, and deallocating "task" memory ranges. Each task represents a contiguous host virtual address range, and PVG expects the VMM to map specific guest system memory ranges to these host addresses via subsequent map callbacks. Multiple tasks can exist at a time, each with many mappings.
Data is exchanged via an undocumented, Apple-proprietary protocol. The PVG API only acts as a facilitator for establishing the communication mechanism. This is perhaps not ideal, and among other things means it only works on macOS hosts, but it's the only serious option we've got for good performance and quality graphics with macOS guests at this time.
The first iterations of this PVG integration into Qemu were developed by Alexander Graf as part of his "vmapple" machine patch series for supporting aarch64 macOS guests, and posted to qemu-devel in June and August 2023:
https://lore.kernel.org/all/[email protected]/T/
This integration mimics the "vmapple"/"apple-gfx" variant of the PVG device used by Apple's own VMM, Virtualization.framework. This variant does not use PCI but acts as a direct MMIO system device; there are two MMIO ranges, one behaving identically to the PCI BAR, while the other's functionality is exposed by private APIs in the PVG framework. It is only available on aarch64 macOS hosts.
I had prior to this simultaneously and independently developed my own PVG integration for Qemu using the public PCI device APIs, with x86-64 and corresponding macOS guests and hosts as the target. After some months of use in production, I was slowly reviewing the code and readying it for upstreaming around the time Alexander posted his vmapple patches.
I ended up reviewing the vmapple PVG code in detail; I identified a number of issues with it (mainly thanks to my prior trial-and-error working with the framework) but overall I thought it a better basis for refinement than my own version:
- It implemented the vmapple variant of the device. I thought it better to port the part I understood well (PCI variant) to this than trying to port the part I didn't understand well (MMIO vmapple variant) to my own code.
- The code was already tidier than my own.
It also became clear in out-of-band communication that Alexander would probably not end up having the time to see the patch through to inclusion, and was happy for me to start making changes and to integrate my PCI code.
It's taken a while, but I'm happy with the result and think it will be a welcome addition for anyone running macOS VMs.
What doesn't work:
------------------
* State (de-)serialisation and thus migration. There is no fundamental technical obstacle to this. PVG supports saving and loading device state. I have simply not had the resources to implement (and crucially, test it) it yet.
* Setting the list of display modes via a property is currently only implemented on the PCI version, which is the only one readily testable without the out-of-tree vmapple patches. (See review notes for patch 7)
* End-to-end GPU-only rendering. After the host GPU has rendered the guest's screen, the framebuffer is copied into a system memory buffer (surface). When using the Qemu Cocoa UI, this buffer is drawn by the CPU into a GPU texture used for hardware window compositing. It would be vastly more efficient to retain the Metal texture and pass it directly through to the Cocoa window. We currently have no mechanism for doing so; it would need to be similar to the end-to-end OpenGL rendering support, with the added complication that Metal textures are Objective-C types and would need to traverse the plain C code of the Qemu display subsystem.
* Dirty region detection. Similarly, the whole framebuffer is marked modified even if there has only been a small change. This hurts network data volume when using VNC.
* Multi-head support. PVG allows "connecting" more than one virtual display. This integration currently always uses exactly 1 display.
* The vmapple/aarch64 variant of the device is only testable with Alexander's vmapple machine type patch set. I've been maintaining this out-of-tree and have made a few improvements, but it doesn't yet run smoothly. (Graphics work fine with this code, issues are with other devices.) I can push my current draft to a git forge if anyone wants to test with them. I'm definitely hoping to eventually resolve the remaining problems and submit a revised version of that patch set as well.
I think we can live without these for the moment, and I'd prefer to work on them only if and when the baseline functionality has been merged.
Patch review notes:
-------------------
As requested, I have now squashed any fixes and refactorings into the orginal commit and changed that to be marked as co-authored.
Brief meta-discussion of specific patches and groups of patches:
01: Alexander Graf's original patch, rebased on latest upstream and
combined with a long list of improvements.
02: The PCI variant. This implements the PCI variant of the PVG device
in addition to the original vmapple/mmio one. The PCI variant is intended for x86-64 macOS guests.
03-06: Various improvements on top of the baseline functionality. I've left
these non-squashed as I think some of them might generate more feedback and iteration, and thus may distract from the main task of getting the core merged.
07: QOM property for specifying the display mode list (resolutions) the
device will report to the guest. I checked other display devices and found none supported this, though I personally find it very useful. I'm wondering whether this should be a more generic feature optionally usable by any display device in Qemu?
08: Adding myself as maintainer for the PVG code, and reviewer for HVF.
Changes since v1:
-----------------
* Squashed most of the commits into the first one, including the dpy_cursor_define_supported removal as that API has now disappeared from upstream.
* Added comments explaining the reasons for different MMIO write handling on aarch64 vs x86-64.
* Integrated cursor image RGBA<->BGRA conversion which I'd missed in the v1 patch set. (This fixes the colours on non-greyscale guest cursors.)
* Removed a stray macOS 12 availability check. (These are no longer needed as Qemu 9.1 removes support for macOS 11 and older hosts.)
Phil Dennis-Jordan (8):
hw/display/apple-gfx: Introduce ParavirtualizedGraphics.Framework
support
hw/display/apple-gfx: Adds PCI implementation
ui/cocoa: Adds non-app runloop on main thread mode hw/display/apple-gfx: Implements texture syncing for non-UMA GPUs hw/display/apple-gfx: Replaces magic number with queried MMIO length hw/display/apple-gfx: Host GPU picking improvements hw/display/apple-gfx: Adds configurable mode list
MAINTAINERS: Add myself as maintainer for apple-gfx, reviewer for HVF
MAINTAINERS | 7 + hw/display/Kconfig | 13 + hw/display/apple-gfx-pci.m | 162 ++++++++ hw/display/apple-gfx-vmapple.m | 194 ++++++++++ hw/display/apple-gfx.h | 72 ++++ hw/display/apple-gfx.m | 681 +++++++++++++++++++++++++++++++++ hw/display/meson.build | 3 + hw/display/trace-events | 26 ++ include/qemu-main.h | 2 + meson.build | 4 + ui/cocoa.m | 15 +- 11 files changed, 1177 insertions(+), 2 deletions(-) create mode 100644 hw/display/apple-gfx-pci.m create mode 100644 hw/display/apple-gfx-vmapple.m create mode 100644 hw/display/apple-gfx.h create mode 100644 hw/display/apple-gfx.m
Signature · 1 line
2.39.3 (Apple Git-146)
PATCH v2 1/8 hw/display/apple-gfx: Introduce ParavirtualizedGraphics.Framework support
MacOS provides a framework (library) that allows any vmm to implement a paravirtualized 3d graphics passthrough to the host metal stack called ParavirtualizedGraphics.Framework (PVG). The library abstracts away almost every aspect of the paravirtualized device model and only provides and receives callbacks on MMIO access as well as to share memory address space between the VM and PVG.
This patch implements a QEMU device that drives PVG for the VMApple variant of it.
Subsequent changes:
* Cherry-pick/rebase conflict fixes
* BQL function renaming
* Moved from hw/vmapple/ (useful outside that machine type)
* Code review comments: Switched to DEFINE_TYPES macro & little endian MMIO.
* Removed some dead/superfluous code
* Mad set_mode thread & memory safe
* Added migration blocker due to lack of (de-)serialisation.
* Fixes to ObjC refcounting and autorelease pool usage.
* Fixed ObjC new/init misuse
* Switched to ObjC category extension for private property.
* Simplified task memory mapping and made it thread safe.
* Refactoring to split generic and vmapple MMIO variant specific code.
* Switched to asynchronous MMIO writes on x86-64
* Rendering and graphics update are now done asynchronously
* Fixed cursor handling
* Coding convention fixes
* Removed software cursor compositing
--- hw/display/Kconfig | 8 + hw/display/apple-gfx-vmapple.m | 194 +++++++++++++ hw/display/apple-gfx.h | 56 ++++ hw/display/apple-gfx.m | 501 +++++++++++++++++++++++++++++++++ hw/display/meson.build | 2 + hw/display/trace-events | 25 ++ meson.build | 4 + 7 files changed, 790 insertions(+) create mode 100644 hw/display/apple-gfx-vmapple.m create mode 100644 hw/display/apple-gfx.h create mode 100644 hw/display/apple-gfx.m
hw/display/Kconfig +8 -0
@@ -143,3 +143,11 @@ config XLNX_DISPLAYPORT config DM163 bool + +config MAC_PVG + bool + default y + +config MAC_PVG_VMAPPLE + bool + depends on MAC_PVG
hw/display/apple-gfx-vmapple.m new file +194 -0
194 lines not on this page · raw message
hw/display/apple-gfx.h new file +56 -0
56 lines not on this page · raw message
hw/display/apple-gfx.m new file +501 -0
501 lines not on this page · raw message
hw/display/meson.build +2 -0
@@ -65,6 +65,8 @@ system_ss.add(when: 'CONFIG_ARTIST', if_true: files('artist.c')) system_ss.add(when: 'CONFIG_ATI_VGA', if_true: [files('ati.c', 'ati_2d.c', 'ati_dbg.c'), pixman]) +system_ss.add(when: 'CONFIG_MAC_PVG', if_true: [files('apple-gfx.m'), pvg, metal]) +system_ss.add(when: 'CONFIG_MAC_PVG_VMAPPLE', if_true: [files('apple-gfx-vmapple.m'), pvg, metal]) if config_all_devices.has_key('CONFIG_VIRTIO_GPU') virtio_gpu_ss = ss.source_set()
hw/display/trace-events +25 -0
@@ -191,3 +191,28 @@ dm163_bits_ppi(unsigned dest_width) "dest_width : %u" dm163_leds(int led, uint32_t value) "led %d: 0x%x" dm163_channels(int channel, uint8_t value) "channel %d: 0x%x" dm163_refresh_rate(uint32_t rr) "refresh rate %d" + +# apple-gfx.m +apple_gfx_read(uint64_t offset, uint64_t res) "offset=0x%"PRIx64" res=0x%"PRIx64 +apple_gfx_write(uint64_t offset, uint64_t val) "offset=0x%"PRIx64" val=0x%"PRIx64 +apple_gfx_create_task(uint32_t vm_size, void *va) "vm_size=0x%x base_addr=%p" +apple_gfx_destroy_task(void *task) "task=%p" +apple_gfx_map_memory(void *task, uint32_t range_count, uint64_t virtual_offset, uint32_t read_only) "task=%p range_count=0x%x virtual_offset=0x%"PRIx64" read_only=%d" +apple_gfx_map_memory_range(uint32_t i, uint64_t phys_addr, uint64_t phys_len) "[%d] phys_addr=0x%"PRIx64" phys_len=0x%"PRIx64 +apple_gfx_remap(uint64_t retval, uint64_t source, uint64_t target) "retval=%"PRId64" source=0x%"PRIx64" target=0x%"PRIx64 +apple_gfx_unmap_memory(void *task, uint64_t virtual_offset, uint64_t length) "task=%p virtual_offset=0x%"PRIx64" length=0x%"PRIx64 +apple_gfx_read_memory(uint64_t phys_address, uint64_t length, void *dst) "phys_addr=0x%"PRIx64" length=0x%"PRIx64" dest=%p" +apple_gfx_raise_irq(uint32_t vector) "vector=0x%x" +apple_gfx_new_frame(void) "" +apple_gfx_mode_change(uint64_t x, uint64_t y) "x=%"PRId64" y=%"PRId64 +apple_gfx_cursor_set(uint32_t bpp, uint64_t width, uint64_t height) "bpp=%d width=%"PRId64" height=0x%"PRId64 +apple_gfx_cursor_show(uint32_t show) "show=%d" +apple_gfx_cursor_move(void) "" + +# apple-gfx-vmapple.m +apple_iosfc_read(uint64_t offset, uint64_t res) "offset=0x%"PRIx64" res=0x%"PRIx64 +apple_iosfc_write(uint64_t offset, uint64_t val) "offset=0x%"PRIx64" val=0x%"PRIx64 +apple_iosfc_map_memory(uint64_t phys, uint64_t len, uint32_t ro, void *va, void *e, void *f) "phys=0x%"PRIx64" len=0x%"PRIx64" ro=%d va=%p e=%p f=%p" +apple_iosfc_unmap_memory(void *a, void *b, void *c, void *d, void *e, void *f) "a=%p b=%p c=%p d=%p e=%p f=%p" +apple_iosfc_raise_irq(uint32_t vector) "vector=0x%x" +
meson.build +4 -0
@@ -710,6 +710,8 @@ socket = [] version_res = [] coref = [] iokit = [] +pvg = [] +metal = [] emulator_link_args = [] midl = not_found widl = not_found
@@ -731,6 +733,8 @@ elif host_os == 'darwin' coref = dependency('appleframeworks', modules: 'CoreFoundation') iokit = dependency('appleframeworks', modules: 'IOKit', required: false) host_dsosuf = '.dylib' + pvg = dependency('appleframeworks', modules: 'ParavirtualizedGraphics') + metal = dependency('appleframeworks', modules: 'Metal') elif host_os == 'sunos' socket = [cc.find_library('socket'), cc.find_library('nsl'),
Signature · 1 line
2.39.3 (Apple Git-146)
PATCH v2 2/8 hw/display/apple-gfx: Adds PCI implementation
In reply to Phil Dennis-JordanThis change wires up the PCI variant of the paravirtualised graphics device, mainly useful for x86-64 macOS guests, implemented by macOS's ParavirtualizedGraphics.framework. It builds on code shared with the vmapple/mmio variant of the PVG device.
--- hw/display/Kconfig | 5 ++ hw/display/apple-gfx-pci.m | 121 +++++++++++++++++++++++++++++++++++++ hw/display/meson.build | 1 + 3 files changed, 127 insertions(+) create mode 100644 hw/display/apple-gfx-pci.m
hw/display/Kconfig +5 -0
@@ -151,3 +151,8 @@ config MAC_PVG config MAC_PVG_VMAPPLE bool depends on MAC_PVG + +config MAC_PVG_PCI + bool + depends on MAC_PVG && PCI + default y if PCI_DEVICES
hw/display/apple-gfx-pci.m new file +121 -0
121 lines not on this page · raw message
hw/display/meson.build +1 -0
@@ -67,6 +67,7 @@ system_ss.add(when: 'CONFIG_ATI_VGA', if_true: [files('ati.c', 'ati_2d.c', 'ati_ system_ss.add(when: 'CONFIG_MAC_PVG', if_true: [files('apple-gfx.m'), pvg, metal]) system_ss.add(when: 'CONFIG_MAC_PVG_VMAPPLE', if_true: [files('apple-gfx-vmapple.m'), pvg, metal]) +system_ss.add(when: 'CONFIG_MAC_PVG_PCI', if_true: [files('apple-gfx-pci.m'), pvg, metal]) if config_all_devices.has_key('CONFIG_VIRTIO_GPU') virtio_gpu_ss = ss.source_set()
Signature · 1 line
2.39.3 (Apple Git-146)
PATCH v2 3/8 ui/cocoa: Adds non-app runloop on main thread mode
In reply to Phil Dennis-JordanVarious system frameworks on macOS and other Apple platforms require a main runloop to be processing events on the process’s main thread. The Cocoa UI’s requirement to run the process as a Cocoa application automatically enables this runloop, but it can be useful to have the runloop handling events even without the Cocoa UI active.
This change adds a non-app runloop mode to the cocoa_main function. This can be requested by other code, while the Cocoa UI additionally enables app mode. This arrangement ensures there is only one qemu_main function switcheroo, and the Cocoa UI’s app mode requirement and other subsystems’ runloop requests don’t conflict with each other.
The main runloop is required for the AppleGFX PV graphics device, so the runloop request call has been added to its initialisation.
--- hw/display/apple-gfx.m | 3 +++ include/qemu-main.h | 2 ++ ui/cocoa.m | 15 +++++++++++++-- 3 files changed, 18 insertions(+), 2 deletions(-)
hw/display/apple-gfx.m +3 -0
@@ -14,6 +14,7 @@ #include "apple-gfx.h" #include "trace.h" +#include "qemu-main.h" #include "qemu/main-loop.h" #include "ui/console.h" #include "monitor/monitor.h"
@@ -290,6 +291,8 @@ void apple_gfx_common_init(Object *obj, AppleGFXState *s, const char* obj_name) error_report_err(local_err); } } + + cocoa_enable_runloop_on_main_thread(); } static void apple_gfx_register_task_mapping_handlers(AppleGFXState *s,
include/qemu-main.h +2 -0
@@ -8,4 +8,6 @@int qemu_default_main (void );extern int (*qemu_main)(void ); +void cocoa_enable_runloop_on_main_thread (void ); +#endif /* QEMU_MAIN_H */
ui/cocoa.m +13 -2
@@ -2028,6 +2028,7 @@ static void cocoa_clipboard_request(QemuClipboardInfo *info, exit(status); } +static bool run_as_cocoa_app = false; static int cocoa_main(void) { QemuThread thread;
@@ -2040,7 +2041,11 @@ static int cocoa_main(void) // Start the main event loop COCOA_DEBUG("Main thread: entering OSX run loop\n"); - [NSApp run]; + if (run_as_cocoa_app) { + [NSApp run]; + } else { + CFRunLoopRun(); + } COCOA_DEBUG("Main thread: left OSX run loop, which should never happen\n"); abort();
@@ -2114,13 +2119,19 @@ static void cocoa_cursor_define(DisplayChangeListener *dcl, QEMUCursor *cursor) }); } +void cocoa_enable_runloop_on_main_thread(void) +{ + qemu_main = cocoa_main; +} + static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n"); - qemu_main = cocoa_main; + run_as_cocoa_app = true; + cocoa_enable_runloop_on_main_thread(); // Pull this console process up to being a fully-fledged graphical // app with a menubar and Dock icon
Signature · 1 line
2.39.3 (Apple Git-146)
PATCH v2 4/8 hw/display/apple-gfx: Implements texture syncing for non-UMA GPUs
In reply to Phil Dennis-JordanRenderable Metal textures are handled differently depending on whether the GPU uses a unified memory architecture (no physical distinction between VRAM and system RAM, CPU and GPU share the memory bus) or not. (Traditional discrete GPU with its own VRAM)
In the discrete GPU case, textures must be explicitly synchronised to the CPU or the GPU before use after being modified by the other. In this case, we sync after the PV graphics framework has rendered the next frame into the texture using the GPU so that we can read out its contents using the CPU. This fixes the issue where the guest screen stayed black on AMD Radeon GPUs.
--- hw/display/apple-gfx.h | 1 + hw/display/apple-gfx.m | 10 +++++++++- 2 files changed, 10 insertions(+), 1 deletion(-)
hw/display/apple-gfx.h +1 -0
@@ -43,6 +43,7 @@ struct AppleGFXState {/* The following fields should only be accessed from render_queue: */ bool gfx_update_requested;bool new_frame_ready; +bool using_managed_texture_storage;int32_t pending_frames;void *vram;DisplaySurface *surface;
hw/display/apple-gfx.m +9 -1
@@ -129,7 +129,12 @@ static void apple_gfx_render_new_frame(AppleGFXState *s) return; } [texture retain]; - + if (s->using_managed_texture_storage) { + /* "Managed" textures exist in both VRAM and RAM and must be synced. */ + id<MTLBlitCommandEncoder> blit = [command_buffer blitCommandEncoder]; + [blit synchronizeResource:texture]; + [blit endEncoding]; + } [command_buffer retain]; [command_buffer addCompletedHandler: ^(id<MTLCommandBuffer> cb)
@@ -248,6 +253,9 @@ static void set_mode(AppleGFXState *s, uint32_t width, uint32_t height) texture = [s->mtl newTextureWithDescriptor:textureDescriptor]; } + s->using_managed_texture_storage = + (texture.storageMode == MTLStorageModeManaged); + dispatch_sync(s->render_queue, ^{ id<MTLTexture> old_texture = nil;
Signature · 1 line
2.39.3 (Apple Git-146)
PATCH v2 5/8 hw/display/apple-gfx: Replaces magic number with queried MMIO length
In reply to Phil Dennis-JordanRather than specifying the length of the device's MMIO range as an unnamed literal constant (which is at least documented as a comment in the framework headers), we query the PVG framework's API for the recommended value. This also avoids problems in future, in case the currently documented value for the default changes.
--- hw/display/apple-gfx.m | 16 +++++++++++++++- hw/display/trace-events | 1 + 2 files changed, 16 insertions(+), 1 deletion(-)
hw/display/apple-gfx.m +15 -1
@@ -283,12 +283,26 @@ static void create_fb(AppleGFXState *s) s->cursor_show = true; } +static size_t apple_gfx_get_default_mmio_range_size(void) +{ + size_t mmio_range_size; + @autoreleasepool { + PGDeviceDescriptor *desc = [PGDeviceDescriptor new]; + mmio_range_size = desc.mmioLength; + [desc release]; + } + return mmio_range_size; +} + void apple_gfx_common_init(Object *obj, AppleGFXState *s, const char* obj_name) { Error *local_err = NULL; int r; + size_t mmio_range_size = apple_gfx_get_default_mmio_range_size(); - memory_region_init_io(&s->iomem_gfx, obj, &apple_gfx_ops, s, obj_name, 0x4000); + trace_apple_gfx_common_init(obj_name, mmio_range_size); + memory_region_init_io(&s->iomem_gfx, obj, &apple_gfx_ops, s, obj_name, + mmio_range_size); /* TODO: PVG framework supports serialising device state: integrate it! */ if (apple_gfx_mig_blocker == NULL) {
hw/display/trace-events +1 -0
@@ -208,6 +208,7 @@ apple_gfx_mode_change(uint64_t x, uint64_t y) "x=%"PRId64" y=%"PRId64 apple_gfx_cursor_set(uint32_t bpp, uint64_t width, uint64_t height) "bpp=%d width=%"PRId64" height=0x%"PRId64 apple_gfx_cursor_show(uint32_t show) "show=%d" apple_gfx_cursor_move(void) "" +apple_gfx_common_init(const char *device_name, size_t mmio_size) "device: %s; MMIO size: %zu bytes" # apple-gfx-vmapple.m apple_iosfc_read(uint64_t offset, uint64_t res) "offset=0x%"PRIx64" res=0x%"PRIx64
Signature · 1 line
2.39.3 (Apple Git-146)
PATCH v2 6/8 hw/display/apple-gfx: Host GPU picking improvements
In reply to Phil Dennis-JordanDuring startup of the PV graphics device, we need to specify the host GPU to use for PV acceleration of the guest's graphics operations.
On a host system, this is trivial: pick the only one. The MTLCreateSystemDefaultDevice() function will do the right thing in this case.
It gets a little more complicated on systems with more than one GPU; first and foremost, this applies to x86-64 MacBook Pros with 15/16" displays. However, with eGPUs, in theory any x86-64 Mac can gain one or more additional GPUs. In these cases, the default is often not ideal - usually, discrete GPUs are selected. In my tests, performance tends to be best with iGPUs, however, and they are usually also best in terms of energy consumption.
Ideally, we will want to allow the user to manually select a GPU if they so choose. In this patch, I am interested in picking a sensible default. Instead of the built-in default logic, it is now:
1. Select a GPU with unified memory (iGPU)
2. If (1) fails, select a GPU that is built-in, not an eGPU.
3. If (2) fails, fall back to system default.
--- hw/display/apple-gfx.m | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-)
hw/display/apple-gfx.m +27 -1
@@ -500,6 +500,32 @@ static void apple_gfx_register_task_mapping_handlers(AppleGFXState *s, return mode_array; } +static id<MTLDevice> copy_suitable_metal_device(void) +{ + id<MTLDevice> dev = nil; + NSArray<id<MTLDevice>> *devs = MTLCopyAllDevices(); + + /* Prefer a unified memory GPU. Failing that, pick a non-removable GPU. */ + for (size_t i = 0; i < devs.count; ++i) { + if (devs[i].hasUnifiedMemory) { + dev = devs[i]; + break; + } + if (!devs[i].removable) { + dev = devs[i]; + } + } + + if (dev != nil) { + [dev retain]; + } else { + dev = MTLCreateSystemDefaultDevice(); + } + [devs release]; + + return dev; +} + void apple_gfx_common_realize(AppleGFXState *s, PGDeviceDescriptor *desc) { PGDisplayDescriptor *disp_desc = nil;
@@ -507,7 +533,7 @@ void apple_gfx_common_realize(AppleGFXState *s, PGDeviceDescriptor *desc) QTAILQ_INIT(&s->tasks); s->render_queue = dispatch_queue_create("apple-gfx.render", DISPATCH_QUEUE_SERIAL); - s->mtl = MTLCreateSystemDefaultDevice(); + s->mtl = copy_suitable_metal_device(); s->mtl_queue = [s->mtl newCommandQueue]; desc.device = s->mtl;
Signature · 1 line
2.39.3 (Apple Git-146)
PATCH v2 7/8 hw/display/apple-gfx: Adds configurable mode list
In reply to Phil Dennis-JordanThis change adds a property 'display_modes' on the graphics device which permits specifying a list of display modes. (screen resolution and refresh rate)
PCI variant of apple-gfx only for the moment.
--- hw/display/apple-gfx-pci.m | 43 ++++++++++- hw/display/apple-gfx.h | 17 ++++- hw/display/apple-gfx.m | 151 ++++++++++++++++++++++++++++++++++--- 3 files changed, 198 insertions(+), 13 deletions(-)
hw/display/apple-gfx-pci.m +42 -1
@@ -1,6 +1,7 @@ #include "apple-gfx.h" #include "hw/pci/pci_device.h" #include "hw/pci/msi.h" +#include "hw/qdev-properties.h" #include "qapi/error.h" #include "trace.h" #import <ParavirtualizedGraphics/ParavirtualizedGraphics.h>
@@ -86,6 +87,46 @@ static void apple_gfx_pci_reset(DeviceState *dev) [s->common.pgdev reset]; } +static void apple_gfx_pci_get_display_modes(Object *obj, Visitor *v, + const char *name, void *opaque, + Error **errp) +{ + Property *prop = opaque; + AppleGFXDisplayModeList *mode_list = object_field_prop_ptr(obj, prop); + + apple_gfx_get_display_modes(mode_list, v, name, errp); +} + +static void apple_gfx_pci_set_display_modes(Object *obj, Visitor *v, + const char *name, void *opaque, + Error **errp) +{ + Property *prop = opaque; + AppleGFXDisplayModeList *mode_list = object_field_prop_ptr(obj, prop); + + apple_gfx_set_display_modes(mode_list, v, name, errp); +} + +const PropertyInfo apple_gfx_pci_prop_display_modes = { + .name = "display_modes", + .description = + "Colon-separated list of display modes; " + "<width>x<height>@<refresh-rate>; the first mode is considered " + "'native'. Example: 3840x2160@60:2560x1440@60:1920x1080@60", + .get = apple_gfx_pci_get_display_modes, + .set = apple_gfx_pci_set_display_modes, +}; + +#define DEFINE_PROP_DISPLAY_MODES(_name, _state, _field) \ + DEFINE_PROP(_name, _state, _field, apple_gfx_pci_prop_display_modes, \ + AppleGFXDisplayModeList) + +static Property apple_gfx_pci_properties[] = { + DEFINE_PROP_DISPLAY_MODES("display-modes", AppleGFXPCIState, + common.display_modes), + DEFINE_PROP_END_OF_LIST(), +}; + static void apple_gfx_pci_class_init(ObjectClass *klass, void *data) { DeviceClass *dc = DEVICE_CLASS(klass);
@@ -101,7 +142,7 @@ static void apple_gfx_pci_class_init(ObjectClass *klass, void *data) pci->class_id = PCI_CLASS_DISPLAY_OTHER; pci->realize = apple_gfx_pci_realize; - // TODO: Property for setting mode list + device_class_set_props(dc, apple_gfx_pci_properties); } static TypeInfo apple_gfx_pci_types[] = {
hw/display/apple-gfx.h +16 -1
@@ -5,14 +5,28 @@#define TYPE_APPLE_GFX_PCI "apple-gfx-pci"#include "qemu/typedefs.h" +#include "qemu/osdep.h" typedef struct AppleGFXState AppleGFXState ; +typedef struct AppleGFXDisplayMode { +uint16_t width_px; +uint16_t height_px; +uint16_t refresh_rate_hz; +}AppleGFXDisplayMode ; + +typedef struct AppleGFXDisplayModeList { +GArray *modes; +}AppleGFXDisplayModeList ; +void apple_gfx_common_init (Object *obj,AppleGFXState *s,const char * obj_name); +void apple_gfx_get_display_modes (AppleGFXDisplayModeList *mode_list,Visitor *v, +const char *name,Error **errp); +void apple_gfx_set_display_modes (AppleGFXDisplayModeList *mode_list,Visitor *v, +const char *name,Error **errp);#ifdef __OBJC__ -#include "qemu/osdep.h" #include "exec/memory.h" #include "ui/surface.h" #include <dispatch/dispatch.h>
@@ -38,6 +52,7 @@ struct AppleGFXState {bool new_frame;bool cursor_show;QEMUCursor *cursor; +AppleGFXDisplayModeList display_modes;dispatch_queue_t render_queue;/* The following fields should only be accessed from render_queue: */
hw/display/apple-gfx.m +140 -11
195 lines not on this page · raw message
Signature · 1 line
2.39.3 (Apple Git-146)
PATCH v2 8/8 MAINTAINERS: Add myself as maintainer for apple-gfx, reviewer for HVF
In reply to Phil Dennis-JordanI'm happy to take responsibility for the macOS PV graphics code. As HVF patches don't seem to get much attention at the moment, I'm also adding myself as designated reviewer for HVF and x86 HVF to try and improve that.
I anticipate that the resulting workload should be covered by the funding I'm receiving for improving Qemu in combination with macOS. As of right now this runs out at the end of 2024; I expect the workload on apple-gfx should be relatively minor and manageable in my spare time beyond that. I may have to remove myself from more general HVF duties once the contract runs out if it's more than I can manage.
--- MAINTAINERS | 7 +++++++ 1 file changed, 7 insertions(+)
MAINTAINERS +7 -0
@@ -511,6 +511,7 @@ F: target/arm/hvf/ X86 HVF CPUs M: Cameron Esfahani <[email protected]> M: Roman Bolshakov <[email protected]> +R: Phil Dennis-Jordan <[email protected]> W: https://wiki.qemu.org/Features/HVF S: Maintained F: target/i386/hvf/
@@ -518,6 +519,7 @@ F: target/i386/hvf/ HVF M: Cameron Esfahani <[email protected]> M: Roman Bolshakov <[email protected]> +R: Phil Dennis-Jordan <[email protected]> W: https://wiki.qemu.org/Features/HVF S: Maintained F: accel/hvf/
@@ -2624,6 +2626,11 @@ F: hw/display/edid* F: include/hw/display/edid.h F: qemu-edid.c +macOS PV Graphics (apple-gfx) +M: Phil Dennis-Jordan <[email protected]> +S: Maintained +F: hw/display/apple-gfx* + PIIX4 South Bridge (i82371AB) M: Hervé Poussineau <[email protected]> M: Philippe Mathieu-Daudé <[email protected]>
Signature · 1 line
2.39.3 (Apple Git-146)
Quoted 54 lines · Phil Dennis-Jordan
This sequence of patches integrates the paravirtualised graphics device implemented by macOS's ParavirtualizedGraphics.Framework into Qemu. Combined with the guest drivers which ship with macOS versions 11 and up, this allows the guest OS to use the host's GPU for hardware accelerated 3D graphics, GPGPU compute (both using the 'Metal' graphics API), and window compositing.
Some background:
----------------The device exposed by the ParavirtualizedGraphics.Framework's (henceforth PVG) public API consists of a PCI device with a single memory-mapped BAR; the VMM is expected to pass reads and writes through to the framework, and to forward interrupts emenating from it to the guest VM.
The bulk of data exchange between host and guest occurs via shared memory, however. For this purpose, PVG makes callbacks to VMM code for allocating, mapping, unmapping, and deallocating "task" memory ranges. Each task represents a contiguous host virtual address range, and PVG expects the VMM to map specific guest system memory ranges to these host addresses via subsequent map callbacks. Multiple tasks can exist at a time, each with many mappings.
Data is exchanged via an undocumented, Apple-proprietary protocol. The PVG API only acts as a facilitator for establishing the communication mechanism. This is perhaps not ideal, and among other things means it only works on macOS hosts, but it's the only serious option we've got for good performance and quality graphics with macOS guests at this time.
The first iterations of this PVG integration into Qemu were developed by Alexander Graf as part of his "vmapple" machine patch series for supporting aarch64 macOS guests, and posted to qemu-devel in June and August 2023:
https://lore.kernel.org/all/[email protected]/T/
This integration mimics the "vmapple"/"apple-gfx" variant of the PVG device used by Apple's own VMM, Virtualization.framework. This variant does not use PCI but acts as a direct MMIO system device; there are two MMIO ranges, one behaving identically to the PCI BAR, while the other's functionality is exposed by private APIs in the PVG framework. It is only available on aarch64 macOS hosts.
I had prior to this simultaneously and independently developed my own PVG integration for Qemu using the public PCI device APIs, with x86-64 and corresponding macOS guests and hosts as the target. After some months of use in production, I was slowly reviewing the code and readying it for upstreaming around the time Alexander posted his vmapple patches.
I ended up reviewing the vmapple PVG code in detail; I identified a number of issues with it (mainly thanks to my prior trial-and-error working with the framework) but overall I thought it a better basis for refinement than my own version:
Quoted 8 lines
- It implemented the vmapple variant of the device. I thought it better to port the part I understood well (PCI variant) to this than trying to port the part I didn't understand well (MMIO vmapple variant) to my own code.
- The code was already tidier than my own.It also became clear in out-of-band communication that Alexander would probably not end up having the time to see the patch through to inclusion, and was happy for me to start making changes and to integrate my PCI code.
I think you also need to take over the base vmapple change because PVG cannot be tested without it; Only macOS can use PVG, and macOS requires vmapple in my understanding.
Regards,
Akihiko Odaki
Quoted 10 lines · Akihiko Odaki
Quoted 3 lines
It also became clear in out-of-band communication that Alexander would probably not end up having the time to see the patch through to
inclusion,
Quoted 1 line
and was happy for me to start making changes and to integrate my PCI
code.
I think you also need to take over the base vmapple change because PVG cannot be tested without it; Only macOS can use PVG, and macOS requires vmapple in my understanding.
The PCI device variant works fine with x86-64 macOS as the guest system. (Or technically any UEFI based guest as the bootrom comes with a UEFI frame buffer driver; it just won’t have any acceleration features unless you boot macOS.)
If preferable I can leave out the vmapple/MMIO device variant (the -vmapple.m file) until the rest of the vmapple machine type modifications are ready. There still appears to be some kind of interrupt delivery issue with some devices on vmapple, so USB HID events are very slow. Or I can submit it as is if that’s not a dealbreaker. (How do I handle Alex’ unmodified patches though, as git send-email tries to send them from the patch author’s email address, which means the email rapidly gets shot down by DKIM mismatch or whatever?)
Thanks,
Phil
Quoted 12 lines · Phil Dennis-Jordan
On Sat 20. Jul 2024 at 16:42, Akihiko Odaki <[email protected] <mailto:[email protected]>> wrote:
> It also became clear in out-of-band communication that Alexander
would
> probably not end up having the time to see the patch through to
inclusion,
> and was happy for me to start making changes and to integrate my
PCI code.
Quoted 6 lines
I think you also need to take over the base vmapple change because PVG cannot be tested without it; Only macOS can use PVG, and macOS requires vmapple in my understanding.
The PCI device variant works fine with x86-64 macOS as the guest system. (Or technically any UEFI based guest as the bootrom comes with a UEFI frame buffer driver; it just won’t have any acceleration features unless you boot macOS.)
I tried apple-gfx-pci with AArch64 and x86-64 EDK firmware on M2 MacBook Air, but it didn't work. I guess the bootrom does not work with Apple Silicon.
Quoted 4 lines
If preferable I can leave out the vmapple/MMIO device variant (the
-vmapple.m file) until the rest of the vmapple machine type
modifications are ready. There still appears to be some kind of interrupt delivery issue with some devices on vmapple, so USB HID events are very slow. Or I can submit it as is if that’s not a dealbreaker.
The vmapple variant should be omitted for now. It is fine for me to submit the vmapple variant with the other vmapple changes as long as that behavior is documented.
Quoted 1 line
(How do I handle Alex’ unmodified patches though, as git send-email tries to send them from the patch author’s email address, which means the email rapidly gets shot down by DKIM mismatch or whatever?)
I think you can set sendemail.from configuration or specify --from option.
Regards,
Akihiko Odaki