Skip to contentSkip to conversation

macOS PV Graphics and new vmapple machine type

PATCH Superseded Phil Dennis-Jordan 2 participants 27 messages Nov 27, 2024 – Nov 30, 2024

Subsystems (2)

v11 of 16 Superseded Latest is v16 →

lore
Share & tools
lore
#0 lore raw

v11 cover macOS PV Graphics and new vmapple machine type

This patch set introduces a new ARM and macOS HVF specific machine type called "vmapple", as well as a family of display devices based on the ParavirtualizedGraphics.framework in macOS. One of the display adapter variants, apple-gfx-mmio, is required for the new machine type, while apple-gfx-pci can be used to enable 3D graphics acceleration with x86-64 macOS guest OSes.

Previous versions of this patch set were submitted semi-separately:
the original vmapple patch set by Alexander Graf included a monolithic implementation of apple-gfx-mmio. I subsequently reviewed and reworked the latter to support the PCI variant of the device as well and submitted the result in isolation. As requested in subsequent review, I have now recombined this with the original vmapple patch set, which I have updated and improved in a few ways as well.

The vmapple machine type approximates the configuration in macOS's own Virtualization.framework when running arm64 macOS guests. In addition to generic components such as a GICv3 and an XHCI USB controller, it includes nonstandard extensions to the virtio block device, a special "hardware" aes engine, a configuration device, a pvpanic variant, a "backdoor" interface, and of course the apple-gfx paravirtualised display adapter.

There are currently a few limitations to this which aren't intrinsic, just imperfect emulation of the VZF, but it's good enough to be just about usable for some purposes:

* macOS 12 guests only. Versions 13+ currently fail during early boot.
* macOS 11+ arm64 hosts only, with hvf accel. (Perhaps some differences between Apple M series CPUs and TCG's aarch64 implementation? macOS hosts only because ParavirtualizedGraphics.framework is a black box implementing most of the logic behind the apple-gfx device.)
* PCI devices use legacy IRQs, not MSI/MSI-X. As far as I can tell, we'd need to include the GICv3 ITS, but it's unclear to me what exactly needs wiring up.
* Due to lack of MSI(-X), event delivery from USB devices to the guest macOS isn't working correctly. My current conclusion is that the OS's XHCI driver simply was never designed to work with legacy IRQs. The upshot is that keyboard and mouse/tablet input is very laggy. The solution would be to implement MSI(-X) support or figure out how to make hcd-xhci-sysbus work with the macOS guest, if at all possible. (EHCI and UHCI/OHCI controllers are not an option as the VMAPPLE guest kernel does not include drivers for these.)
* The guest OS must first be provisioned using Virtualization.framework; the disk images can subsequently be used in Qemu. (See docs.)

The apple-gfx device can be used independently from the vmapple machine type, at least in the PCI variant. It mainly targets x86-64 macOS guests from version 11 on, but also includes a UEFI bootrom for basic framebuffer mode. macOS 11 is also required on the host side, as well as a GPU that supports the Metal API. On the guest side, this provides 3D acceleration/GPGPU support with a baseline Metal feature set, irrespective of the host GPU's feature set. A few limitations in the current integration:

* Although it works fine with TCG, it does not work correctly
cross-architecture: x86-64 guests on arm64 hosts appear to make some boot progress, but rendering is corrupted. I suspect incompatible texture memory layouts; I have no idea if this is fixable.
* ParavirtualizedGraphics.framework and the guest driver support multi-headed configurations. The current Qemu integration always connects precisely 1 display.
* State serialisation and deserialisation is currently not implemented, though supported in principle by the framework. Both apple-gfx variants thus set up a migration blocker.
* Rendering efficiency could be better. The GPU-rendered guest framebuffer is copied to system memory and uses Qemu's usual CPU-based drawing. For maximum efficiency, the Metal texture containing the guest framebuffer could be drawn directly to a Metal view in the host window, staying on the GPU. (Similar to the OpenGL/virgl render path on other platforms.)

Some of my part of this work has been sponsored by Sauce Labs Inc.

---

v2 -> v3:

* Merged the apple-gfx and vmapple patchsets.
* Squashed a bunch of later apple-gfx patches into the main one. (dGPU support, queried MMIO area size, host GPU picking logic.)
* Rebased on latest upstream, fixing any breakages due to internal Qemu API changes.
* apple-gfx: Switched to re-entrant MMIO. This is supported by the underlying framework and simplifies the MMIO forwarding code which was previously different on x86-64 vs aarch64.
* vmapple: Fixes for minor bugs and comments from the last round of review.
* vmapple aes, conf, apple-gfx: Switched reset methods to implement the ResettableClass base's interface.
* vmapple: switched from virtio-hid to an XHCI USB controller and USB mouse and tablet devices. macOS does not provide drivers for virtio HID devices, at least not in version 12's vmapple kernel. So input now sort of works (interrupt issues) rather than not at all. Use network-based remote access to the guest OS as a work-around.

v3 -> v4:

* Complete rework of the mechanism for handling runloop/libdispatch events on the main thread. PV graphics now work with the SDL UI.
* Renamed 'apple-gfx-vmapple' device to 'apple-gfx-mmio'
* hw/display/apple-gfx: threading model overhaul to be more consistent, safer, and more QEMU-idiomatic.
* display-modes property on the apple-gfx devices now uses the native array property mechanism and works on both device variants.
* hw/vmapple/aes: Improvements to logging and error handling.
* hw/vmapple/cfg: Bug fixes around device property default values.
* hw/vmapple/{aes,cfg,virtio-blk/vmapple}: Most header code moved into .c files, only a single vmapple.h now contains the #defines for the vmapple machine model-specific device type names.
* hw/block/virtio-blk: New patch for replacing virtio_blk_free_request with g_free. (Optional)
* Various smaller changes following comments in v3 code review in apple-gfx, aes, cfg, bdif, virtio-blk-vmapple, and the vmapple machine type itself. See patch-specific v4 change notes for details.

v4 -> v5:

* Simplified the main thread runloop mechanism. Back to setting qemu_main directly, but narrowing the scope of what it needs to do, and it can now be NULL. (Meaning run the QEMU main event loop on the main thread as is traditional.)
* hw/display/apple-gfx: Further improvements to the BH based job code bridging the libdispatch & QEMU thread synchronisation impedance mismatch.
* hw/display/apple-gfx: Thread safety and object lifetime improvements.
* hw/display/apple-gfx-*: Better buffer and error handling in display mode property setters and getters.
* hw/vmapple/aes: More consistent and safer logging/tracing
* hw/vmapple/cfg: Better error reporting on overlong property strings.
* hw/vmapple/virtio-blk: Fixed theoretically-unaligned write to config buffer.
* vmapple machine type: Moved ecam region into machine state, improved device property setting error handling, improved ECID/UUID extraction script and docs.
* Various smaller fixes in apple-gfx/-mmio, apple-gfx-pci, vmapple/aes, vmapple/cfg, vmapple/virtio-blk, and vmapple machine type.
* Added SPDX license identifiers where they were missing.

v5 -> v6:

* 01/15 (main/Cocoa/runloop): Combined functions, fixed whitespace
* 02/15 (apple-gfx): Further refinement of PVG threading: reduced some callback tasks from BHs to merely acquiring RCU read lock; replaced some libdispatch tasks with BHs; last remaining synchronous BH now uses emphemeral QemuSemaphore.
* 02/15 (apple-gfx): Readability improvements and other smaller tweaks (see patch change notes for details)
* 04/15 (display modes): Replaced use of alloca() with NSMutableArray.

v6 -> v7:

* 02/15 (apple-gfx): Use g_ptr_array_find() helper function, coding style tweak
* 03/15 (apple-gfx-pci): Removed an unused function parameter
* 04/15 (apple-gfx display mode property): Simplified error handling in property parsing.
* 10/15 (vmapple/aes): Coding style tweaks.
* 12/15 (vmapple/cfg): Changed error messages for overrun of properties with fixed-length strings to be more useful to users than developers.
* 15/15 (vmapple machine type): Tiny error handling fix, un-inlined function

v7 -> v8:

* 02/15 (apple-gfx): Naming and type use improvements, fixes for a bug and a leak.
* 04/15 (apple-gfx display mode property): Type use improvement
* 10/15 (vmapple/aes): Guest error logging tweaks.
* 11/15 (vmapple/bdif): Replaced uses of cpu_physical_memory_read with dma_memory_read, and a g_free call with g_autofree.
* 12/15 (vmapple/cfg): Macro hygiene fix: consistently enclosing arguments in parens.
* 15/15 (vmapple machine type): Use less verbose pattern for defining uuid property.

v8 -> v9:

* 01/16 (ui & main loop): Set qemu_main to NULL for GTK UI as well.
* 02/16 (apple-gfx): Pass device pointer to graphic_console_init(), various non-functional changes.
* 03/16 (apple-gfx-pci): Fixup of changed common call, whitespace and comment formatting tweaks.
* 04/16 (apple-gfx display modes): Re-ordered type definitions so we can drop a 'struct' keyword.
* 10/16 (vmapple/aes): Replaced a use of cpu_physical_memory_write with dma_memory_write, minor style tweak.
* 11/16 (vmapple/bdif): Replaced uses of cpu_physical_memory_write with dma_memory_write.
* 13/16 (vmapple/virtio-blk): Correctly specify class_size for VMAppleVirtIOBlkClass.
* 15/16 (vmapple machine type): Documentation improvements, fixed variable name and struct field used during pvpanic device creation.
* 16/16 (NEW/RFC vmapple/virtio-blk): Proposed change to replace type hierarchy with a variant property. This seems cleaner and less confusing than the original approach to me, but I'm not sure if it warrants creation of a new QAPI enum and property type definition.

v9 -> v10:

* 01/15 (ui & main loop): Added comments to qemu_main declaration and GTK.
* 02/15 (apple-gfx): Reworked the way frame rendering code is threaded to use BHs for sections requiring BQL.
* 02/15 (apple-gfx): Fixed ./configure error on non-macOS platforms.
* 10/15 (vmapple/aes): Code style and comment improvements.
* 12/15 (vmapple/cfg): Slightly tidier error reporting for overlong property values.
* 13/15 (vmapple/virtio-blk): Folded v9 patch 16/16 into this one, changing the device type design to provide a single device type with a variant property instead of 2 different subtypes for aux and root volumes.
* 15/15 (vmapple machine type): Documentation fixup for changed virtio-blk device type; small improvements to shell commands in documentation; improved propagation of errors during cfg device instantiation.

v10 -> v11:

* 01/15 (ui & main loop): Simplified main.c, better comments & commit message
* 02/15 (apple-gfx): Give each PV display instance a unique serial number.
* 02 & 03/15 (apple-gfx, -pci): Formatting/style tweaks
* 15/15 (vmapple machine type): Improvements to shell code in docs

Alexander Graf (9):
hw: Add vmapple subdir
hw/misc/pvpanic: Add MMIO interface
hvf: arm: Ignore writes to CNTP_CTL_EL0
gpex: Allow more than 4 legacy IRQs hw/vmapple/aes: Introduce aes engine hw/vmapple/bdif: Introduce vmapple backdoor interface hw/vmapple/cfg: Introduce vmapple cfg region hw/vmapple/virtio-blk: Add support for apple virtio-blk hw/vmapple/vmapple: Add vmapple machine type

Phil Dennis-Jordan (6):
ui & main loop: Redesign of system-specific main thread event handling hw/display/apple-gfx: Introduce ParavirtualizedGraphics.Framework
support
hw/display/apple-gfx: Adds PCI implementation hw/display/apple-gfx: Adds configurable mode list
MAINTAINERS: Add myself as maintainer for apple-gfx, reviewer for HVF hw/block/virtio-blk: Replaces request free function with g_free

 MAINTAINERS                         |  15 +
 contrib/vmapple/uuid.sh             |   9 +
 docs/system/arm/vmapple.rst         |  63 ++
 docs/system/target-arm.rst          |   1 +
 hw/Kconfig                          |   1 +
 hw/arm/sbsa-ref.c                   |   2 +-
 hw/arm/virt.c                       |   2 +-
 hw/block/virtio-blk.c               |  58 +-
 hw/core/qdev-properties-system.c    |   8 +
 hw/display/Kconfig                  |  13 +
 hw/display/apple-gfx-mmio.m         | 289 +++++++++
 hw/display/apple-gfx-pci.m          | 157 +++++
 hw/display/apple-gfx.h              |  78 +++
 hw/display/apple-gfx.m              | 873 ++++++++++++++++++++++++++++
 hw/display/meson.build              |   7 +
 hw/display/trace-events             |  30 +
 hw/i386/microvm.c                   |   2 +-
 hw/loongarch/virt.c                 |   2 +-
 hw/meson.build                      |   1 +
 hw/mips/loongson3_virt.c            |   2 +-
 hw/misc/Kconfig                     |   4 +
 hw/misc/meson.build                 |   1 +
 hw/misc/pvpanic-mmio.c              |  61 ++
 hw/openrisc/virt.c                  |  12 +-
 hw/pci-host/gpex.c                  |  43 +-
 hw/riscv/virt.c                     |  12 +-
 hw/vmapple/Kconfig                  |  32 +
 hw/vmapple/aes.c                    | 581 ++++++++++++++++++
 hw/vmapple/bdif.c                   | 275 +++++++++
 hw/vmapple/cfg.c                    | 196 +++++++
 hw/vmapple/meson.build              |   5 +
 hw/vmapple/trace-events             |  21 +
 hw/vmapple/trace.h                  |   1 +
 hw/vmapple/virtio-blk.c             | 205 +++++++
 hw/vmapple/vmapple.c                | 646 ++++++++++++++++++++
 hw/xtensa/virt.c                    |   2 +-
 include/hw/misc/pvpanic.h           |   1 +
 include/hw/pci-host/gpex.h          |   7 +-
 include/hw/pci/pci_ids.h            |   1 +
 include/hw/qdev-properties-system.h |   5 +
 include/hw/virtio/virtio-blk.h      |  11 +-
 include/hw/vmapple/vmapple.h        |  23 +
 include/qemu-main.h                 |  14 +-
 include/qemu/cutils.h               |  15 +
 meson.build                         |   5 +
 qapi/virtio.json                    |  14 +
 system/main.c                       |  37 +-
 target/arm/hvf/hvf.c                |   9 +
 ui/cocoa.m                          |  54 +-
 ui/gtk.c                            |   8 +
 ui/sdl2.c                           |   4 +
 util/hexdump.c                      |  18 +
 52 files changed, 3832 insertions(+), 104 deletions(-)
 create mode 100755 contrib/vmapple/uuid.sh
 create mode 100644 docs/system/arm/vmapple.rst
 create mode 100644 hw/display/apple-gfx-mmio.m
 create mode 100644 hw/display/apple-gfx-pci.m
 create mode 100644 hw/display/apple-gfx.h
 create mode 100644 hw/display/apple-gfx.m
 create mode 100644 hw/misc/pvpanic-mmio.c
 create mode 100644 hw/vmapple/Kconfig
 create mode 100644 hw/vmapple/aes.c
 create mode 100644 hw/vmapple/bdif.c
 create mode 100644 hw/vmapple/cfg.c
 create mode 100644 hw/vmapple/meson.build
 create mode 100644 hw/vmapple/trace-events
 create mode 100644 hw/vmapple/trace.h
 create mode 100644 hw/vmapple/virtio-blk.c
 create mode 100644 hw/vmapple/vmapple.c
 create mode 100644 include/hw/vmapple/vmapple.h
Signature · 1 line
2.39.5 (Apple Git-154)
#1 lore raw

PATCH v11 1/15 ui & main loop: Redesign of system-specific main thread event handling

macOS's Cocoa event handling must be done on the initial (main) thread of the process. Furthermore, if library or application code uses libdispatch, the main dispatch queue must be handling events on the main thread as well.

So far, this has affected Qemu in both the Cocoa and SDL UIs, although in different ways: the Cocoa UI replaces the default qemu_main function with one that spins Qemu's internal main event loop off onto a background thread. SDL (which uses Cocoa internally) on the other hand uses a polling approach within Qemu's main event loop. Events are polled during the SDL UI's dpy_refresh callback, which happens to run on the main thread by default.

As UIs are mutually exclusive, this works OK as long as nothing else needs platform-native event handling. In the next patch, a new device is introduced based on the ParavirtualizedGraphics.framework in macOS. This uses libdispatch internally, and only works when events are being handled on the main runloop. With the current system, it works when using either the Cocoa or the SDL UI. However, it does not when running headless. Moreover, any attempt to install a similar scheme to the Cocoa UI's main thread replacement fails when combined with the SDL UI.

This change tidies up main thread management to be more flexible.

* The qemu_main global function pointer is a custom function for the main thread, and it may now be NULL. When it is, the main thread runs the main Qemu loop. This represents the traditional setup.
* When non-null, spawning the main Qemu event loop on a separate thread is now done centrally rather than inside the Cocoa UI code.
* For most platforms, qemu_main is indeed NULL by default, but on Darwin, it defaults to a function that runs the CFRunLoop.
* The Cocoa UI sets qemu_main to a function which runs the NSApplication event handling runloop, as is usual for a Cocoa app.
* The SDL UI overrides the qemu_main function to NULL, thus specifying that Qemu's main loop must run on the main thread.
* The GTK UI also overrides the qemu_main function to NULL.
* For other UIs, or in the absence of UIs, the platform's default behaviour is followed.

This means that on macOS, the platform's runloop events are always handled, regardless of chosen UI. The new PV graphics device will thus work in all configurations. There is no functional change on other operating systems.

Implementing this via a global function pointer variable is a bit ugly, but it's probably worth investigating the existing UI thread rule violations in the SDL (e.g. #2537) and GTK+ back-ends. Fixing those issues might precipitate requirements similar but not identical to those of the Cocoa UI; hopefully we'll see some kind of pattern emerge, which can then be used as a basis for an overhaul. (In fact, it may turn out to be simplest to split the UI/native platform event thread from the QEMU main event loop on all platforms, with any UI or even none at all.)

---

v5:

* Simplified the way of setting/clearing the main loop by going back to setting qemu_main directly, but narrowing the scope of what it needs to do, and it can now be NULL.

v6:

* Folded function qemu_run_default_main_on_new_thread's code into main()
* Removed whitespace changes left over on lines near code removed between v4 and v5

v9:

* Set qemu_main to NULL for GTK UI as well.

v10:

* Added comments clarifying the functionality and purpose of qemu_main.

v11:

* Removed the qemu_main_fn typedef again.
* Consolidation of main, qemu_default_main, and call_qemu_default_main so that the latter has been eliminated altogether.
* Reinstated the #include <SDL.h> directive, added comment saying why it's needed.
* Improved the comment on the qemu_main global variable.
* Expanded the commit message.

 include/qemu-main.h | 14 +++++++++++-
 system/main.c       | 37 +++++++++++++++++++++++++++----
 ui/cocoa.m          | 54 +++++++++++----------------------------------
 ui/gtk.c            |  8 +++++++
 ui/sdl2.c           |  4 ++++
 5 files changed, 71 insertions(+), 46 deletions(-)
include/qemu-main.h +13 -1
index 940960a7dbc..a926def7526 100644
@@ -5,7 +5,19 @@
 #ifndef QEMU_MAIN_H
 #define QEMU_MAIN_H
 
-int qemu_default_main(void);
+/*
+ * The function to run on the main (initial) thread of the process.
+ * NULL means QEMU's main event loop.
+ * When non-NULL, QEMU's main event loop will run on a purposely created
+ * thread, after which the provided function pointer will be invoked on
+ * the initial thread.
+ * This is useful on platforms which treat the main thread as special
+ * (macOS/Darwin) and/or require all UI API calls to occur from a
+ * specific thread. Those platforms can initialise it to a specific function,
+ * while UI implementations may reset it to NULL during their init if they
+ * will handle system and UI events on the main thread via QEMU's own main
+ * event loop.
+ */
 extern int (*qemu_main)(void);
 
 #endif /* QEMU_MAIN_H */
system/main.c +33 -4
index 9b91d21ea8c..668d0ecfe8c 100644
@@ -24,26 +24,55 @@
 
 #include "qemu/osdep.h"
 #include "qemu-main.h"
+#include "qemu/main-loop.h"
 #include "sysemu/sysemu.h"
 
 #ifdef CONFIG_SDL
+/*
+ * SDL insists on wrapping the main() function with its own implementation on
+ * some platforms; it does so via a macro that renames our main function, so
+ * <SDL.h> must be #included here even with no SDL code called from this file.
+ */
 #include <SDL.h>
 #endif
 
-int qemu_default_main(void)
+#ifdef CONFIG_DARWIN
+#include <CoreFoundation/CoreFoundation.h>
+#endif
+
+static void *qemu_default_main(void *opaque)
 {
     int status;
 
+    bql_lock();
     status = qemu_main_loop();
     qemu_cleanup(status);
+    bql_unlock();
 
-    return status;
+    exit(status);
 }
 
-int (*qemu_main)(void) = qemu_default_main;
+int (*qemu_main)(void);
+
+#ifdef CONFIG_DARWIN
+static int os_darwin_cfrunloop_main(void)
+{
+    CFRunLoopRun();
+    g_assert_not_reached();
+}
+int (*qemu_main)(void) = os_darwin_cfrunloop_main;
+#endif
 
 int main(int argc, char **argv)
 {
     qemu_init(argc, argv);
-    return qemu_main();
+    bql_unlock();
+    if (qemu_main) {
+        QemuThread main_loop_thread;
+        qemu_thread_create(&main_loop_thread, "qemu_main",
+                           qemu_default_main, NULL, QEMU_THREAD_DETACHED);
+        return qemu_main();
+    } else {
+        qemu_default_main(NULL);
+    }
 }
ui/cocoa.m +13 -41

98 lines not on this page · raw message

ui/gtk.c +8 -0
index bf9d3dd679a..5e6ee5c12a2 100644
@@ -38,6 +38,7 @@
 #include "qemu/cutils.h"
 #include "qemu/error-report.h"
 #include "qemu/main-loop.h"
+#include "qemu-main.h"
 
 #include "ui/console.h"
 #include "ui/gtk.h"
@@ -2485,6 +2486,13 @@ static void gtk_display_init(DisplayState *ds, DisplayOptions *opts)
 #ifdef CONFIG_GTK_CLIPBOARD
     gd_clipboard_init(s);
 #endif /* CONFIG_GTK_CLIPBOARD */
+
+    /*
+     * GTK+ calls must happen on the main thread at least on some platforms,
+     * and on macOS the main runloop is polled via GTK+'s event handling.
+     * Don't allow QEMU's event loop to be moved off the main thread.
+     */
+    qemu_main = NULL;
 }
 
 static void early_gtk_display_init(DisplayOptions *opts)
ui/sdl2.c +4 -0
index bd4f5a9da14..44ab2762262 100644
@@ -34,6 +34,7 @@
 #include "sysemu/sysemu.h"
 #include "ui/win32-kbd-hook.h"
 #include "qemu/log.h"
+#include "qemu-main.h"
 
 static int sdl2_num_outputs;
 static struct sdl2_console *sdl2_console;
@@ -965,6 +966,9 @@ static void sdl2_display_init(DisplayState *ds, DisplayOptions *o)
     }
 
     atexit(sdl_cleanup);
+
+    /* SDL's event polling (in dpy_refresh) must happen on the main thread. */
+    qemu_main = NULL;
 }
 
 static QemuDisplay qemu_display_sdl2 = {
Signature · 1 line
2.39.5 (Apple Git-154)
#2 lore raw

Re: [PATCH v11 01/15] ui & main loop: Redesign of system-specific main thread event handling

Quoted 104 lines · Phil Dennis-Jordan

macOS's Cocoa event handling must be done on the initial (main) thread of the process. Furthermore, if library or application code uses libdispatch, the main dispatch queue must be handling events on the main thread as well.

So far, this has affected Qemu in both the Cocoa and SDL UIs, although in different ways: the Cocoa UI replaces the default qemu_main function with one that spins Qemu's internal main event loop off onto a background thread. SDL (which uses Cocoa internally) on the other hand uses a polling approach within Qemu's main event loop. Events are polled during the SDL UI's dpy_refresh callback, which happens to run on the main thread by default.

As UIs are mutually exclusive, this works OK as long as nothing else needs platform-native event handling. In the next patch, a new device is introduced based on the ParavirtualizedGraphics.framework in macOS. This uses libdispatch internally, and only works when events are being handled on the main runloop. With the current system, it works when using either the Cocoa or the SDL UI. However, it does not when running headless. Moreover, any attempt to install a similar scheme to the Cocoa UI's main thread replacement fails when combined with the SDL UI.

This change tidies up main thread management to be more flexible.

* The qemu_main global function pointer is a custom function for the main thread, and it may now be NULL. When it is, the main thread runs the main Qemu loop. This represents the traditional setup.
* When non-null, spawning the main Qemu event loop on a separate thread is now done centrally rather than inside the Cocoa UI code.
* For most platforms, qemu_main is indeed NULL by default, but on Darwin, it defaults to a function that runs the CFRunLoop.
* The Cocoa UI sets qemu_main to a function which runs the NSApplication event handling runloop, as is usual for a Cocoa app.
* The SDL UI overrides the qemu_main function to NULL, thus specifying that Qemu's main loop must run on the main thread.
* The GTK UI also overrides the qemu_main function to NULL.
* For other UIs, or in the absence of UIs, the platform's default behaviour is followed.

This means that on macOS, the platform's runloop events are always handled, regardless of chosen UI. The new PV graphics device will thus work in all configurations. There is no functional change on other operating systems.

Implementing this via a global function pointer variable is a bit ugly, but it's probably worth investigating the existing UI thread rule violations in the SDL (e.g. #2537) and GTK+ back-ends. Fixing those issues might precipitate requirements similar but not identical to those of the Cocoa UI; hopefully we'll see some kind of pattern emerge, which can then be used as a basis for an overhaul. (In fact, it may turn out to be simplest to split the UI/native platform event thread from the QEMU main event loop on all platforms, with any UI or even none at all.)

---

v5:

* Simplified the way of setting/clearing the main loop by going back to setting qemu_main directly, but narrowing the scope of what it needs to do, and it can now be NULL.

v6:

* Folded function qemu_run_default_main_on_new_thread's code into

    main()

* Removed whitespace changes left over on lines near code removed between v4 and v5

v9:

* Set qemu_main to NULL for GTK UI as well.

v10:

* Added comments clarifying the functionality and purpose of qemu_main.

v11:

* Removed the qemu_main_fn typedef again.
* Consolidation of main, qemu_default_main, and call_qemu_default_main so that the latter has been eliminated altogether.
* Reinstated the #include <SDL.h> directive, added comment saying why it's needed.
* Improved the comment on the qemu_main global variable.
* Expanded the commit message.

  include/qemu-main.h | 14 +++++++++++-
  system/main.c       | 37 +++++++++++++++++++++++++++----
  ui/cocoa.m          | 54 +++++++++++----------------------------------
  ui/gtk.c            |  8 +++++++
  ui/sdl2.c           |  4 ++++
  5 files changed, 71 insertions(+), 46 deletions(-)
include/qemu-main.h +0 -0
index 940960a7dbc..a926def7526 100644
@@ -5,7 +5,19 @@
  #ifndef QEMU_MAIN_H
  #define QEMU_MAIN_H
 

include/qemu-main.h line 16

Quoted 10 lines
include/qemu-main.h +9 -1
-int qemu_default_main(void);
+/*
+ * The function to run on the main (initial) thread of the process.
+ * NULL means QEMU's main event loop.
+ * When non-NULL, QEMU's main event loop will run on a purposely created
+ * thread, after which the provided function pointer will be invoked on
+ * the initial thread.
+ * This is useful on platforms which treat the main thread as special
+ * (macOS/Darwin) and/or require all UI API calls to occur from a
+ * specific thread. Those platforms can initialise it to a specific function,

Although the change from v10 looks good, I have a few comments:

Here, it says "require all UI API calls to occur from a specific thread", but it is clearer to say "require all UI API calls to occur from *the main thread*". If we only need to ensure all UI API calls to occur from one thread, arranging all calls to happen in the thread running QEMU's main loop is sufficient. This variable is necessary only when the thread is the one that called main().

Quoted 218 lines
include/qemu-main.h +3 -0
+ * while UI implementations may reset it to NULL during their init if they
+ * will handle system and UI events on the main thread via QEMU's own main
+ * event loop.> + */
  extern int (*qemu_main)(void);
 
  #endif /* QEMU_MAIN_H */
system/main.c +33 -4
index 9b91d21ea8c..668d0ecfe8c 100644
@@ -24,26 +24,55 @@
 
  #include "qemu/osdep.h"
  #include "qemu-main.h"
+#include "qemu/main-loop.h"
  #include "sysemu/sysemu.h"
 
  #ifdef CONFIG_SDL
+/*
+ * SDL insists on wrapping the main() function with its own implementation on
+ * some platforms; it does so via a macro that renames our main function, so
+ * <SDL.h> must be #included here even with no SDL code called from this file.
+ */
  #include <SDL.h>
  #endif
 
-int qemu_default_main(void)
+#ifdef CONFIG_DARWIN
+#include <CoreFoundation/CoreFoundation.h>
+#endif
+
+static void *qemu_default_main(void *opaque)
  {
      int status;
 
+    bql_lock();
      status = qemu_main_loop();
      qemu_cleanup(status);
+    bql_unlock();
 
-    return status;
+    exit(status);
  }
 
-int (*qemu_main)(void) = qemu_default_main;
+int (*qemu_main)(void);
+
+#ifdef CONFIG_DARWIN
+static int os_darwin_cfrunloop_main(void)
+{
+    CFRunLoopRun();
+    g_assert_not_reached();
+}
+int (*qemu_main)(void) = os_darwin_cfrunloop_main;
+#endif
 
  int main(int argc, char **argv)
  {
      qemu_init(argc, argv);
-    return qemu_main();
+    bql_unlock();
+    if (qemu_main) {
+        QemuThread main_loop_thread;
+        qemu_thread_create(&main_loop_thread, "qemu_main",
+                           qemu_default_main, NULL, QEMU_THREAD_DETACHED);
+        return qemu_main();
+    } else {
+        qemu_default_main(NULL);
+    }
  }
ui/cocoa.m +13 -41
index 4c2dd335323..30b8920d929 100644
@@ -73,6 +73,8 @@
      int height;
  } QEMUScreen;
 
+@class QemuCocoaPasteboardTypeOwner;
+
  static void cocoa_update(DisplayChangeListener *dcl,
                           int x, int y, int w, int h);
 
@@ -107,6 +109,7 @@ static void cocoa_switch(DisplayChangeListener *dcl,
  static NSInteger cbchangecount = -1;
  static QemuClipboardInfo *cbinfo;
  static QemuEvent cbevent;
+static QemuCocoaPasteboardTypeOwner *cbowner;
 
  // Utility functions to run specified code block with the BQL held
  typedef void (^CodeBlock)(void);
@@ -1321,8 +1324,10 @@ - (void) dealloc
  {
      COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
 
-    if (cocoaView)
-        [cocoaView release];
+    [cocoaView release];
+    [cbowner release];
+    cbowner = nil;
+
      [super dealloc];
  }
 
@@ -1938,8 +1943,6 @@ - (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSPasteboardType)t
 
  @end
 
-static QemuCocoaPasteboardTypeOwner *cbowner;
-
  static void cocoa_clipboard_notify(Notifier *notifier, void *data);
  static void cocoa_clipboard_request(QemuClipboardInfo *info,
                                      QemuClipboardType type);
@@ -2002,43 +2005,8 @@ static void cocoa_clipboard_request(QemuClipboardInfo *info,
      }
  }
 
-/*
- * The startup process for the OSX/Cocoa UI is complicated, because
- * OSX insists that the UI runs on the initial main thread, and so we
- * need to start a second thread which runs the qemu_default_main():
- * in main():
- *  in cocoa_display_init():
- *   assign cocoa_main to qemu_main
- *   create application, menus, etc
- *  in cocoa_main():
- *   create qemu-main thread
- *   enter OSX run loop
- */
-
-static void *call_qemu_main(void *opaque)
-{
-    int status;
-
-    COCOA_DEBUG("Second thread: calling qemu_default_main()\n");
-    bql_lock();
-    status = qemu_default_main();
-    bql_unlock();
-    COCOA_DEBUG("Second thread: qemu_default_main() returned, exiting\n");
-    [cbowner release];
-    exit(status);
-}
-
  static int cocoa_main(void)
  {
-    QemuThread thread;
-
-    COCOA_DEBUG("Entered %s()\n", __func__);
-
-    bql_unlock();
-    qemu_thread_create(&thread, "qemu_main", call_qemu_main,
-                       NULL, QEMU_THREAD_DETACHED);
-
-    // Start the main event loop
      COCOA_DEBUG("Main thread: entering OSX run loop\n");
      [NSApp run];
      COCOA_DEBUG("Main thread: left OSX run loop, which should never happen\n");
@@ -2120,8 +2088,6 @@ static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
 
      COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
 
-    qemu_main = cocoa_main;
-
      // Pull this console process up to being a fully-fledged graphical
      // app with a menubar and Dock icon
      ProcessSerialNumber psn = { 0, kCurrentProcess };
@@ -2185,6 +2151,12 @@ static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
      qemu_clipboard_peer_register(&cbpeer);
 
      [pool release];
+
+    /*
+     * The Cocoa UI will run the NSApplication runloop on the main thread
+     * rather than the default Core Foundation one.
+     */
+    qemu_main = cocoa_main;
  }
 
  static QemuDisplay qemu_display_cocoa = {
ui/gtk.c +8 -0
index bf9d3dd679a..5e6ee5c12a2 100644
@@ -38,6 +38,7 @@
  #include "qemu/cutils.h"
  #include "qemu/error-report.h"
  #include "qemu/main-loop.h"
+#include "qemu-main.h"
 
  #include "ui/console.h"
  #include "ui/gtk.h"
@@ -2485,6 +2486,13 @@ static void gtk_display_init(DisplayState *ds, DisplayOptions *opts)
  #ifdef CONFIG_GTK_CLIPBOARD
      gd_clipboard_init(s);
  #endif /* CONFIG_GTK_CLIPBOARD */
+
+    /*
+     * GTK+ calls must happen on the main thread at least on some platforms,
+     * and on macOS the main runloop is polled via GTK+'s event handling.
+     * Don't allow QEMU's event loop to be moved off the main thread.
+     */
+    qemu_main = NULL;
  }
 
  static void early_gtk_display_init(DisplayOptions *opts)
ui/sdl2.c +1 -0
index bd4f5a9da14..44ab2762262 100644
@@ -34,6 +34,7 @@
  #include "sysemu/sysemu.h"
  #include "ui/win32-kbd-hook.h"
  #include "qemu/log.h"
+#include "qemu-main.h"
 
  static int sdl2_num_outputs;
  static struct sdl2_console *sdl2_console;

ui/sdl2.c static void sdl2_display_init(DisplayState *ds, DisplayOptions *o) · line 970

Quoted 5 lines
ui/sdl2.c +2 -0
@@ -965,6 +966,9 @@ static void sdl2_display_init(DisplayState *ds, DisplayOptions *o)
      }
 
      atexit(sdl_cleanup);
+
+    /* SDL's event polling (in dpy_refresh) must happen on the main thread. */

ui/gtk.c and ui/sdl2.c have the same background so the comments should also be identical except names.

Quoted 4 lines
ui/sdl2.c +1 -0
+    qemu_main = NULL;
  }
 
  static QemuDisplay qemu_display_sdl2 = {
#3 lore raw

Re: [PATCH v11 01/15] ui & main loop: Redesign of system-specific main thread event handling

Quoted 117 lines · Akihiko Odaki
Quoted 104 lines · Phil Dennis-Jordan

macOS's Cocoa event handling must be done on the initial (main) thread of the process. Furthermore, if library or application code uses libdispatch, the main dispatch queue must be handling events on the main thread as well.

So far, this has affected Qemu in both the Cocoa and SDL UIs, although in different ways: the Cocoa UI replaces the default qemu_main function with one that spins Qemu's internal main event loop off onto a background thread. SDL (which uses Cocoa internally) on the other hand uses a polling approach within Qemu's main event loop. Events are polled during the SDL UI's dpy_refresh callback, which happens to run on the main thread by default.

As UIs are mutually exclusive, this works OK as long as nothing else needs platform-native event handling. In the next patch, a new device is introduced based on the ParavirtualizedGraphics.framework in macOS. This uses libdispatch internally, and only works when events are being handled on the main runloop. With the current system, it works when using either the Cocoa or the SDL UI. However, it does not when running headless. Moreover, any attempt to install a similar scheme to the Cocoa UI's main thread replacement fails when combined with the SDL UI.

This change tidies up main thread management to be more flexible.

* The qemu_main global function pointer is a custom function for the main thread, and it may now be NULL. When it is, the main thread runs the main Qemu loop. This represents the traditional setup.
* When non-null, spawning the main Qemu event loop on a separate thread is now done centrally rather than inside the Cocoa UI code.
* For most platforms, qemu_main is indeed NULL by default, but on Darwin, it defaults to a function that runs the CFRunLoop.
* The Cocoa UI sets qemu_main to a function which runs the NSApplication event handling runloop, as is usual for a Cocoa app.
* The SDL UI overrides the qemu_main function to NULL, thus specifying that Qemu's main loop must run on the main thread.
* The GTK UI also overrides the qemu_main function to NULL.
* For other UIs, or in the absence of UIs, the platform's default behaviour is followed.

This means that on macOS, the platform's runloop events are always handled, regardless of chosen UI. The new PV graphics device will thus work in all configurations. There is no functional change on other operating systems.

Implementing this via a global function pointer variable is a bit ugly, but it's probably worth investigating the existing UI thread rule violations in the SDL (e.g. #2537) and GTK+ back-ends. Fixing those issues might precipitate requirements similar but not identical to those of the Cocoa UI; hopefully we'll see some kind of pattern emerge, which can then be used as a basis for an overhaul. (In fact, it may turn out to be simplest to split the UI/native platform event thread from the QEMU main event loop on all platforms, with any UI or even none at all.)

---

v5:

* Simplified the way of setting/clearing the main loop by going back to setting qemu_main directly, but narrowing the scope of what it needs to do, and it can now be NULL.

v6:

* Folded function qemu_run_default_main_on_new_thread's code into

    main()

* Removed whitespace changes left over on lines near code removed between v4 and v5

v9:

* Set qemu_main to NULL for GTK UI as well.

v10:

* Added comments clarifying the functionality and purpose of qemu_main.

v11:

* Removed the qemu_main_fn typedef again.
* Consolidation of main, qemu_default_main, and call_qemu_default_main so that the latter has been eliminated altogether.
* Reinstated the #include <SDL.h> directive, added comment saying why it's needed.
* Improved the comment on the qemu_main global variable.
* Expanded the commit message.

  include/qemu-main.h | 14 +++++++++++-
  system/main.c       | 37 +++++++++++++++++++++++++++----
  ui/cocoa.m          | 54 +++++++++++----------------------------------
  ui/gtk.c            |  8 +++++++
  ui/sdl2.c           |  4 ++++
  5 files changed, 71 insertions(+), 46 deletions(-)
include/qemu-main.h +0 -0
index 940960a7dbc..a926def7526 100644
@@ -5,7 +5,19 @@
  #ifndef QEMU_MAIN_H
  #define QEMU_MAIN_H
 

include/qemu-main.h line 16

Quoted 10 lines
include/qemu-main.h +9 -1
-int qemu_default_main(void);
+/*
+ * The function to run on the main (initial) thread of the process.
+ * NULL means QEMU's main event loop.
+ * When non-NULL, QEMU's main event loop will run on a purposely created
+ * thread, after which the provided function pointer will be invoked on
+ * the initial thread.
+ * This is useful on platforms which treat the main thread as special
+ * (macOS/Darwin) and/or require all UI API calls to occur from a
+ * specific thread. Those platforms can initialise it to a specific

function,

Quoted 9 lines

Although the change from v10 looks good, I have a few comments:

Here, it says "require all UI API calls to occur from a specific thread", but it is clearer to say "require all UI API calls to occur from *the main thread*". If we only need to ensure all UI API calls to occur from one thread, arranging all calls to happen in the thread running QEMU's main loop is sufficient. This variable is necessary only when the thread is the one that called main().

Is there a simple way to reliably run a block of code on the thread running QEMU's main loop? (*) BHs will run on any thread that's blocked in AIO_WAIT_WHILE(NULL, …) or similar, so those are not suitable. Apparently GTK+ on Win32 requires all API calls to originate from one thread, but it doesn't need to be the main thread, which is why I chose that phrasing. But I suppose if that's the only restriction, the UI can spawn its own thread and leave the main thread alone.

(*) This would be good to know for fixing this bug
https://gitlab.com/qemu-project/qemu/-/issues/2537 where the SDL UI code causes a hang by calling into SDL_SetWindowSize() from a CPU thread. My current thinking on that one is to use SDL_PushEvent() with a custom event type generated by SDL_RegisterEvents(), which then will be handled via the standard SDL event polling mechanism; but that seems awkward.

Quoted 237 lines

+ * while UI implementations may reset it to NULL during their init if they

include/qemu-main.h line 17

Quoted 1 line
include/qemu-main.h +1 -0
+ * will handle system and UI events on the main thread via QEMU's own

main

Quoted 9 lines
include/qemu-main.h +1 -0
+ * event loop.> + */
  extern int (*qemu_main)(void);
 
  #endif /* QEMU_MAIN_H */
system/main.c +0 -0
index 9b91d21ea8c..668d0ecfe8c 100644

system/main.c line 32

Quoted 9 lines
system/main.c +3 -0
@@ -24,26 +24,55 @@
 
  #include "qemu/osdep.h"
  #include "qemu-main.h"
+#include "qemu/main-loop.h"
  #include "sysemu/sysemu.h"
 
  #ifdef CONFIG_SDL
+/*
+ * SDL insists on wrapping the main() function with its own

implementation on

system/main.c line 33

Quoted 1 line
system/main.c +1 -0
+ * some platforms; it does so via a macro that renames our main

function, so

system/main.c line 34

Quoted 1 line
system/main.c +1 -0
+ * <SDL.h> must be #included here even with no SDL code called from

this file.

Quoted 33 lines
system/main.c +19 -3
+ */
  #include <SDL.h>
  #endif
 
-int qemu_default_main(void)
+#ifdef CONFIG_DARWIN
+#include <CoreFoundation/CoreFoundation.h>
+#endif
+
+static void *qemu_default_main(void *opaque)
  {
      int status;
 
+    bql_lock();
      status = qemu_main_loop();
      qemu_cleanup(status);
+    bql_unlock();
 
-    return status;
+    exit(status);
  }
 
-int (*qemu_main)(void) = qemu_default_main;
+int (*qemu_main)(void);
+
+#ifdef CONFIG_DARWIN
+static int os_darwin_cfrunloop_main(void)
+{
+    CFRunLoopRun();
+    g_assert_not_reached();
+}
+int (*qemu_main)(void) = os_darwin_cfrunloop_main;
+#endif

system/main.c

Quoted 10 lines
system/main.c +5 -1
 
  int main(int argc, char **argv)
  {
      qemu_init(argc, argv);
-    return qemu_main();
+    bql_unlock();
+    if (qemu_main) {
+        QemuThread main_loop_thread;
+        qemu_thread_create(&main_loop_thread, "qemu_main",
+                           qemu_default_main, NULL,

QEMU_THREAD_DETACHED);

ui/cocoa.m - (void)pasteboard:(NSPasteboard *)sender

Quoted 40 lines
system/main.c +4 -0
+        return qemu_main();
+    } else {
+        qemu_default_main(NULL);
+    }
  }
ui/cocoa.m +7 -2
index 4c2dd335323..30b8920d929 100644
@@ -73,6 +73,8 @@
      int height;
  } QEMUScreen;
 
+@class QemuCocoaPasteboardTypeOwner;
+
  static void cocoa_update(DisplayChangeListener *dcl,
                           int x, int y, int w, int h);
 
@@ -107,6 +109,7 @@ static void cocoa_switch(DisplayChangeListener *dcl,
  static NSInteger cbchangecount = -1;
  static QemuClipboardInfo *cbinfo;
  static QemuEvent cbevent;
+static QemuCocoaPasteboardTypeOwner *cbowner;
 
  // Utility functions to run specified code block with the BQL held
  typedef void (^CodeBlock)(void);
@@ -1321,8 +1324,10 @@ - (void) dealloc
  {
      COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
 
-    if (cocoaView)
-        [cocoaView release];
+    [cocoaView release];
+    [cbowner release];
+    cbowner = nil;
+
      [super dealloc];
  }
 
@@ -1938,8 +1943,6 @@ - (void)pasteboard:(NSPasteboard *)sender

provideDataForType:(NSPasteboardType)t

ui/cocoa.m static void

Quoted 9 lines
ui/cocoa.m +0 -2
  @end
 
-static QemuCocoaPasteboardTypeOwner *cbowner;
-
  static void cocoa_clipboard_notify(Notifier *notifier, void *data);
  static void cocoa_clipboard_request(QemuClipboardInfo *info,
                                      QemuClipboardType type);
@@ -2002,43 +2005,8 @@ static void

cocoa_clipboard_request(QemuClipboardInfo *info,

Quoted 15 lines
ui/cocoa.m +0 -12
      }
  }
 
-/*
- * The startup process for the OSX/Cocoa UI is complicated, because
- * OSX insists that the UI runs on the initial main thread, and so we
- * need to start a second thread which runs the qemu_default_main():
- * in main():
- *  in cocoa_display_init():
- *   assign cocoa_main to qemu_main
- *   create application, menus, etc
- *  in cocoa_main():
- *   create qemu-main thread
- *   enter OSX run loop
- */

ui/cocoa.m static void cocoa_clipboard_request(QemuClipboardInfo *info,

Quoted 10 lines
ui/cocoa.m +0 -10
-
-static void *call_qemu_main(void *opaque)
-{
-    int status;
-
-    COCOA_DEBUG("Second thread: calling qemu_default_main()\n");
-    bql_lock();
-    status = qemu_default_main();
-    bql_unlock();
-    COCOA_DEBUG("Second thread: qemu_default_main() returned,

exiting\n");

Quoted 8 lines
ui/cocoa.m +0 -6
-    [cbowner release];
-    exit(status);
-}
-
  static int cocoa_main(void)
  {
-    QemuThread thread;
-

ui/cocoa.m static void cocoa_clipboard_request(QemuClipboardInfo *info,

Quoted 10 lines
ui/cocoa.m +0 -7
-    COCOA_DEBUG("Entered %s()\n", __func__);
-
-    bql_unlock();
-    qemu_thread_create(&thread, "qemu_main", call_qemu_main,
-                       NULL, QEMU_THREAD_DETACHED);
-
-    // Start the main event loop
      COCOA_DEBUG("Main thread: entering OSX run loop\n");
      [NSApp run];
      COCOA_DEBUG("Main thread: left OSX run loop, which should never

happen\n");

ui/cocoa.m static void cocoa_display_init(DisplayState *ds,

Quoted 1 line
ui/cocoa.m +0 -0
@@ -2120,8 +2088,6 @@ static void cocoa_display_init(DisplayState *ds,

DisplayOptions *opts)

ui/cocoa.m static void cocoa_display_init(DisplayState *ds,

Quoted 9 lines
ui/cocoa.m +0 -2
      COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
 
-    qemu_main = cocoa_main;
-
      // Pull this console process up to being a fully-fledged graphical
      // app with a menubar and Dock icon
      ProcessSerialNumber psn = { 0, kCurrentProcess };
@@ -2185,6 +2151,12 @@ static void cocoa_display_init(DisplayState *ds,

DisplayOptions *opts)

ui/cocoa.m static void cocoa_display_init(DisplayState *ds, DisplayOptions *opts)

Quoted 6 lines
ui/cocoa.m +3 -0
      qemu_clipboard_peer_register(&cbpeer);
 
      [pool release];
+
+    /*
+     * The Cocoa UI will run the NSApplication runloop on the main

thread

ui/gtk.c static void gtk_display_init(DisplayState *ds,

Quoted 19 lines
ui/cocoa.m +3 -0
+     * rather than the default Core Foundation one.
+     */
+    qemu_main = cocoa_main;
  }
 
  static QemuDisplay qemu_display_cocoa = {
ui/gtk.c +1 -0
index bf9d3dd679a..5e6ee5c12a2 100644
@@ -38,6 +38,7 @@
  #include "qemu/cutils.h"
  #include "qemu/error-report.h"
  #include "qemu/main-loop.h"
+#include "qemu-main.h"
 
  #include "ui/console.h"
  #include "ui/gtk.h"
@@ -2485,6 +2486,13 @@ static void gtk_display_init(DisplayState *ds,

DisplayOptions *opts)

ui/gtk.c static void gtk_display_init(DisplayState *ds, DisplayOptions *opts)

Quoted 6 lines
ui/gtk.c +3 -0
  #ifdef CONFIG_GTK_CLIPBOARD
      gd_clipboard_init(s);
  #endif /* CONFIG_GTK_CLIPBOARD */
+
+    /*
+     * GTK+ calls must happen on the main thread at least on some

platforms,

ui/gtk.c static void gtk_display_init(DisplayState *ds, · line 2492

Quoted 1 line
ui/gtk.c +1 -0
+     * and on macOS the main runloop is polled via GTK+'s event

handling.

ui/sdl2.c static void sdl2_display_init(DisplayState *ds,

Quoted 19 lines
ui/gtk.c +3 -0
+     * Don't allow QEMU's event loop to be moved off the main thread.
+     */
+    qemu_main = NULL;
  }
 
  static void early_gtk_display_init(DisplayOptions *opts)
ui/sdl2.c +1 -0
index bd4f5a9da14..44ab2762262 100644
@@ -34,6 +34,7 @@
  #include "sysemu/sysemu.h"
  #include "ui/win32-kbd-hook.h"
  #include "qemu/log.h"
+#include "qemu-main.h"
 
  static int sdl2_num_outputs;
  static struct sdl2_console *sdl2_console;
@@ -965,6 +966,9 @@ static void sdl2_display_init(DisplayState *ds,

DisplayOptions *o)

Quoted 2 lines
ui/sdl2.c +0 -0
      }
 
Quoted 8 lines

ui/sdl2.c static void sdl2_display_init(DisplayState *ds, DisplayOptions *o)

Quoted 3 lines
ui/sdl2.c +2 -0
      atexit(sdl_cleanup);
+
+    /* SDL's event polling (in dpy_refresh) must happen on the main

thread. */

ui/gtk.c and ui/sdl2.c have the same background so the comments should also be identical except names.

Well, GTK doesn't currently do this, which is why it doesn't work on macOS, but hopefully this patch will be merged in some form, at which point it will:

https://patchew.org/QEMU/[email protected]/

But yeah, thanks to this patch we know that's a solution for GTK as well, and I can update the comment.

Quoted 6 lines
Quoted 4 lines
ui/sdl2.c +1 -0
+    qemu_main = NULL;
  }
 
  static QemuDisplay qemu_display_sdl2 = {
#4 lore raw

Re: [PATCH v11 01/15] ui & main loop: Redesign of system-specific main thread event handling

Quoted 156 lines · Phil Dennis-Jordan

On Thu, 28 Nov 2024 at 12:17, Akihiko Odaki <[email protected] <mailto:[email protected]>> wrote:

On 2024/11/28 0:02, Phil Dennis-Jordan wrote:
> macOS's Cocoa event handling must be done on the initial (main)
thread
> of the process. Furthermore, if library or application code uses > libdispatch, the main dispatch queue must be handling events on
the main
> thread as well.
>
> So far, this has affected Qemu in both the Cocoa and SDL UIs,
although
> in different ways: the Cocoa UI replaces the default qemu_main
function
> with one that spins Qemu's internal main event loop off onto a > background thread. SDL (which uses Cocoa internally) on the other
hand
> uses a polling approach within Qemu's main event loop. Events are > polled during the SDL UI's dpy_refresh callback, which happens to run > on the main thread by default.
>
> As UIs are mutually exclusive, this works OK as long as nothing else > needs platform-native event handling. In the next patch, a new
device is
> introduced based on the ParavirtualizedGraphics.framework in macOS. > This uses libdispatch internally, and only works when events are
being
> handled on the main runloop. With the current system, it works when > using either the Cocoa or the SDL UI. However, it does not when
running
> headless. Moreover, any attempt to install a similar scheme to the > Cocoa UI's main thread replacement fails when combined with the SDL > UI.
>
> This change tidies up main thread management to be more flexible. >
>   * The qemu_main global function pointer is a custom function
for the
>     main thread, and it may now be NULL. When it is, the main thread >     runs the main Qemu loop. This represents the traditional setup. >   * When non-null, spawning the main Qemu event loop on a separate >     thread is now done centrally rather than inside the Cocoa UI
code.
>   * For most platforms, qemu_main is indeed NULL by default, but on >     Darwin, it defaults to a function that runs the CFRunLoop. >   * The Cocoa UI sets qemu_main to a function which runs the >     NSApplication event handling runloop, as is usual for a Cocoa
app.
>   * The SDL UI overrides the qemu_main function to NULL, thus >     specifying that Qemu's main loop must run on the main >     thread.
>   * The GTK UI also overrides the qemu_main function to NULL. >   * For other UIs, or in the absence of UIs, the platform's default >     behaviour is followed.
>
> This means that on macOS, the platform's runloop events are always > handled, regardless of chosen UI. The new PV graphics device will > thus work in all configurations. There is no functional change on
other
> operating systems.
>
> Implementing this via a global function pointer variable is a bit > ugly, but it's probably worth investigating the existing UI
thread rule
> violations in the SDL (e.g. #2537) and GTK+ back-ends. Fixing those > issues might precipitate requirements similar but not identical
to those
> of the Cocoa UI; hopefully we'll see some kind of pattern emerge,
which
> can then be used as a basis for an overhaul. (In fact, it may turn > out to be simplest to split the UI/native platform event thread
from the
> QEMU main event loop on all platforms, with any UI or even none
at all.)
>
> Signed-off-by: Phil Dennis-Jordan <[email protected]
<mailto:[email protected]>>
> ---
>
> v5:
>
>   * Simplified the way of setting/clearing the main loop by going
back
>     to setting qemu_main directly, but narrowing the scope of what it >     needs to do, and it can now be NULL.
>
> v6:
>
>   * Folded function qemu_run_default_main_on_new_thread's code into >     main()
>   * Removed whitespace changes left over on lines near code removed >     between v4 and v5
>
> v9:
>
>   * Set qemu_main to NULL for GTK UI as well.
>
> v10:
>
>   * Added comments clarifying the functionality and purpose of
qemu_main.
>
> v11:
>
>   * Removed the qemu_main_fn typedef again.
>   * Consolidation of main, qemu_default_main, and
call_qemu_default_main
>     so that the latter has been eliminated altogether.
>   * Reinstated the #include <SDL.h> directive, added comment saying >     why it's needed.
>   * Improved the comment on the qemu_main global variable. >   * Expanded the commit message.
>
>   include/qemu-main.h | 14 +++++++++++-
>   system/main.c       | 37 +++++++++++++++++++++++++++---- >   ui/cocoa.m          | 54 ++++++++++
+----------------------------------
>   ui/gtk.c            |  8 +++++++
>   ui/sdl2.c           |  4 ++++
>   5 files changed, 71 insertions(+), 46 deletions(-)
>
> diff --git a/include/qemu-main.h b/include/qemu-main.h
> index 940960a7dbc..a926def7526 100644
> --- a/include/qemu-main.h
> +++ b/include/qemu-main.h
> @@ -5,7 +5,19 @@
>   #ifndef QEMU_MAIN_H
>   #define QEMU_MAIN_H
>
> -int qemu_default_main(void);
> +/*
> + * The function to run on the main (initial) thread of the process. > + * NULL means QEMU's main event loop.
> + * When non-NULL, QEMU's main event loop will run on a purposely
created
> + * thread, after which the provided function pointer will be
invoked on
> + * the initial thread.
> + * This is useful on platforms which treat the main thread as
special
> + * (macOS/Darwin) and/or require all UI API calls to occur from a > + * specific thread. Those platforms can initialise it to a
specific function,

Although the change from v10 looks good, I have a few comments:

Here, it says "require all UI API calls to occur from a specific thread", but it is clearer to say "require all UI API calls to occur from *the main thread*". If we only need to ensure all UI API calls to occur from one thread, arranging all calls to happen in the thread running QEMU's main loop is sufficient. This variable is necessary only when the thread is the one that called main().

Quoted 1 line

Is there a simple way to reliably run a block of code on the thread running QEMU's main loop? (*) BHs will run on any thread that's blocked in AIO_WAIT_WHILE(NULL, …) or similar, so those are not suitable. Apparently GTK+ on Win32 requires all API calls to originate from one thread, but it doesn't need to be the main thread, which is why I chose that phrasing. But I suppose if that's the only restriction, the UI can spawn its own thread and leave the main thread alone.

Setting qemu_main does not help in such a case because BHs may still run on other threads so it needs another approach.

I think iohandler_get_aio_context() does what we want, but it is not intended to be used to identify the thread to run the UI so using it is like a hack. Spawning a thread dedicated for UI is more appropriate.

Quoted 2 lines

(*) This would be good to know for fixing this bug https://gitlab.com/ qemu-project/qemu/-/issues/2537 <https://gitlab.com/qemu-project/qemu/-/ issues/2537> where the SDL UI code causes a hang by calling into SDL_SetWindowSize() from a CPU thread. My current thinking on that one is to use SDL_PushEvent() with a custom event type generated by SDL_RegisterEvents(), which then will be handled via the standard SDL event polling mechanism; but that seems awkward.

I think it's totally fine. If SDL (backed by Cocoa) insists to own the main thread, let it do so.

Quoted 251 lines
     > + * while UI implementations may reset it to NULL during their
    init if they
     > + * will handle system and UI events on the main thread via
    QEMU's own main
     > + * event loop.> + */
     >   extern int (*qemu_main)(void);
     >
     >   #endif /* QEMU_MAIN_H */
     > diff --git a/system/main.c b/system/main.c
     > index 9b91d21ea8c..668d0ecfe8c 100644
     > --- a/system/main.c
     > +++ b/system/main.c
     > @@ -24,26 +24,55 @@
     >
     >   #include "qemu/osdep.h"
     >   #include "qemu-main.h"
     > +#include "qemu/main-loop.h"
     >   #include "sysemu/sysemu.h"
     >
     >   #ifdef CONFIG_SDL
     > +/*
     > + * SDL insists on wrapping the main() function with its own
    implementation on
     > + * some platforms; it does so via a macro that renames our main
    function, so
     > + * <SDL.h> must be #included here even with no SDL code called
    from this file.
     > + */
     >   #include <SDL.h>
     >   #endif
     >
     > -int qemu_default_main(void)
     > +#ifdef CONFIG_DARWIN
     > +#include <CoreFoundation/CoreFoundation.h>
     > +#endif
     > +
     > +static void *qemu_default_main(void *opaque)
     >   {
     >       int status;
     >
     > +    bql_lock();
     >       status = qemu_main_loop();
     >       qemu_cleanup(status);
     > +    bql_unlock();
     >
     > -    return status;
     > +    exit(status);
     >   }
     >
     > -int (*qemu_main)(void) = qemu_default_main;
     > +int (*qemu_main)(void);
     > +
     > +#ifdef CONFIG_DARWIN
     > +static int os_darwin_cfrunloop_main(void)
     > +{
     > +    CFRunLoopRun();
     > +    g_assert_not_reached();
     > +}
     > +int (*qemu_main)(void) = os_darwin_cfrunloop_main;
     > +#endif
     >
     >   int main(int argc, char **argv)
     >   {
     >       qemu_init(argc, argv);
     > -    return qemu_main();
     > +    bql_unlock();
     > +    if (qemu_main) {
     > +        QemuThread main_loop_thread;
     > +        qemu_thread_create(&main_loop_thread, "qemu_main",
     > +                           qemu_default_main, NULL,
    QEMU_THREAD_DETACHED);
     > +        return qemu_main();
     > +    } else {
     > +        qemu_default_main(NULL);
     > +    }
     >   }
     > diff --git a/ui/cocoa.m b/ui/cocoa.m
     > index 4c2dd335323..30b8920d929 100644
     > --- a/ui/cocoa.m
     > +++ b/ui/cocoa.m
     > @@ -73,6 +73,8 @@
     >       int height;
     >   } QEMUScreen;
     >
     > +@class QemuCocoaPasteboardTypeOwner;
     > +
     >   static void cocoa_update(DisplayChangeListener *dcl,
     >                            int x, int y, int w, int h);
     >
     > @@ -107,6 +109,7 @@ static void
    cocoa_switch(DisplayChangeListener *dcl,
     >   static NSInteger cbchangecount = -1;
     >   static QemuClipboardInfo *cbinfo;
     >   static QemuEvent cbevent;
     > +static QemuCocoaPasteboardTypeOwner *cbowner;
     >
     >   // Utility functions to run specified code block with the BQL held
     >   typedef void (^CodeBlock)(void);
     > @@ -1321,8 +1324,10 @@ - (void) dealloc
     >   {
     >       COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
     >
     > -    if (cocoaView)
     > -        [cocoaView release];
     > +    [cocoaView release];
     > +    [cbowner release];
     > +    cbowner = nil;
     > +
     >       [super dealloc];
     >   }
     >
     > @@ -1938,8 +1943,6 @@ - (void)pasteboard:(NSPasteboard *)sender
    provideDataForType:(NSPasteboardType)t
     >
     >   @end
     >
     > -static QemuCocoaPasteboardTypeOwner *cbowner;
     > -
     >   static void cocoa_clipboard_notify(Notifier *notifier, void *data);
     >   static void cocoa_clipboard_request(QemuClipboardInfo *info,
     >                                       QemuClipboardType type);
     > @@ -2002,43 +2005,8 @@ static void
    cocoa_clipboard_request(QemuClipboardInfo *info,
     >       }
     >   }
     >
     > -/*
     > - * The startup process for the OSX/Cocoa UI is complicated, because
     > - * OSX insists that the UI runs on the initial main thread, and
    so we
     > - * need to start a second thread which runs the qemu_default_main():
     > - * in main():
     > - *  in cocoa_display_init():
     > - *   assign cocoa_main to qemu_main
     > - *   create application, menus, etc
     > - *  in cocoa_main():
     > - *   create qemu-main thread
     > - *   enter OSX run loop
     > - */
     > -
     > -static void *call_qemu_main(void *opaque)
     > -{
     > -    int status;
     > -
     > -    COCOA_DEBUG("Second thread: calling qemu_default_main()\n");
     > -    bql_lock();
     > -    status = qemu_default_main();
     > -    bql_unlock();
     > -    COCOA_DEBUG("Second thread: qemu_default_main() returned,
    exiting\n");
     > -    [cbowner release];
     > -    exit(status);
     > -}
     > -
     >   static int cocoa_main(void)
     >   {
     > -    QemuThread thread;
     > -
     > -    COCOA_DEBUG("Entered %s()\n", __func__);
     > -
     > -    bql_unlock();
     > -    qemu_thread_create(&thread, "qemu_main", call_qemu_main,
     > -                       NULL, QEMU_THREAD_DETACHED);
     > -
     > -    // Start the main event loop
     >       COCOA_DEBUG("Main thread: entering OSX run loop\n");
     >       [NSApp run];
     >       COCOA_DEBUG("Main thread: left OSX run loop, which should
    never happen\n");
     > @@ -2120,8 +2088,6 @@ static void cocoa_display_init(DisplayState
    *ds, DisplayOptions *opts)
     >
     >       COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
     >
     > -    qemu_main = cocoa_main;
     > -
     >       // Pull this console process up to being a fully-fledged
    graphical
     >       // app with a menubar and Dock icon
     >       ProcessSerialNumber psn = { 0, kCurrentProcess };
     > @@ -2185,6 +2151,12 @@ static void
    cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
     >       qemu_clipboard_peer_register(&cbpeer);
     >
     >       [pool release];
     > +
     > +    /*
     > +     * The Cocoa UI will run the NSApplication runloop on the
    main thread
     > +     * rather than the default Core Foundation one.
     > +     */
     > +    qemu_main = cocoa_main;
     >   }
     >
     >   static QemuDisplay qemu_display_cocoa = {
     > diff --git a/ui/gtk.c b/ui/gtk.c
     > index bf9d3dd679a..5e6ee5c12a2 100644
     > --- a/ui/gtk.c
     > +++ b/ui/gtk.c
     > @@ -38,6 +38,7 @@
     >   #include "qemu/cutils.h"
     >   #include "qemu/error-report.h"
     >   #include "qemu/main-loop.h"
     > +#include "qemu-main.h"
     >
     >   #include "ui/console.h"
     >   #include "ui/gtk.h"
     > @@ -2485,6 +2486,13 @@ static void gtk_display_init(DisplayState
    *ds, DisplayOptions *opts)
     >   #ifdef CONFIG_GTK_CLIPBOARD
     >       gd_clipboard_init(s);
     >   #endif /* CONFIG_GTK_CLIPBOARD */
     > +
     > +    /*
     > +     * GTK+ calls must happen on the main thread at least on
    some platforms,
     > +     * and on macOS the main runloop is polled via GTK+'s event
    handling.
     > +     * Don't allow QEMU's event loop to be moved off the main
    thread.
     > +     */
     > +    qemu_main = NULL;
     >   }
     >
     >   static void early_gtk_display_init(DisplayOptions *opts)
     > diff --git a/ui/sdl2.c b/ui/sdl2.c
     > index bd4f5a9da14..44ab2762262 100644
     > --- a/ui/sdl2.c
     > +++ b/ui/sdl2.c
     > @@ -34,6 +34,7 @@
     >   #include "sysemu/sysemu.h"
     >   #include "ui/win32-kbd-hook.h"
     >   #include "qemu/log.h"
     > +#include "qemu-main.h"
     >
     >   static int sdl2_num_outputs;
     >   static struct sdl2_console *sdl2_console;
     > @@ -965,6 +966,9 @@ static void sdl2_display_init(DisplayState
    *ds, DisplayOptions *o)
     >       }
     >
     >       atexit(sdl_cleanup);
     > +
     > +    /* SDL's event polling (in dpy_refresh) must happen on the
    main thread. */

    ui/gtk.c and ui/sdl2.c have the same background so the comments should
    also be identical except names.
Quoted 5 lines

Well, GTK doesn't currently do this, which is why it doesn't work on macOS, but hopefully this patch will be merged in some form, at which point it will:

https://patchew.org/QEMU/[email protected]/ <https://patchew.org/QEMU/[email protected]/>

But yeah, thanks to this patch we know that's a solution for GTK as well, and I can update the comment.

I only meant that SDL is not different from GTK in terms that its call and event handling needs to be done in the main thread.

I was not paying attention to the mention of dpy_refresh(). It is another topic whether dpy_refresh() is the best place for event handling, and I don't think so. dpy_refresh() is triggered when refreshing the display output, but event handling is not specific to the display output so it is awkward to handle events there.

The best approach is to do the same with ui/cocoa; override qemu_main to dedicate the main thread for the UI and decouple the UI from the BQL by calling GTK with g_main_context_invoke(), which corresponds to SDL_RegisterEvents() in SDL.

Quoted 6 lines
     > +    qemu_main = NULL;
     >   }
     >
     >   static QemuDisplay qemu_display_sdl2 = {
#5 lore raw

Re: [PATCH v11 01/15] ui & main loop: Redesign of system-specific main thread event handling

Quoted 183 lines · Akihiko Odaki
Quoted 14 lines · Phil Dennis-Jordan

On Thu, 28 Nov 2024 at 12:17, Akihiko Odaki <[email protected] <mailto:[email protected]>> wrote:

On 2024/11/28 0:02, Phil Dennis-Jordan wrote:
> macOS's Cocoa event handling must be done on the initial (main)
thread
> of the process. Furthermore, if library or application code uses > libdispatch, the main dispatch queue must be handling events on
the main
> thread as well.
>
> So far, this has affected Qemu in both the Cocoa and SDL UIs,

Quoted 8 lines

although
> in different ways: the Cocoa UI replaces the default qemu_main
function
> with one that spins Qemu's internal main event loop off onto a > background thread. SDL (which uses Cocoa internally) on the other
hand
> uses a polling approach within Qemu's main event loop. Events are > polled during the SDL UI's dpy_refresh callback, which happens to

run

Quoted 3 lines

> on the main thread by default.
>
> As UIs are mutually exclusive, this works OK as long as nothing

else

Quoted 3 lines

> needs platform-native event handling. In the next patch, a new
device is
> introduced based on the ParavirtualizedGraphics.framework in

macOS.

Quoted 3 lines

> This uses libdispatch internally, and only works when events are
being
> handled on the main runloop. With the current system, it works

when

Quoted 4 lines

> using either the Cocoa or the SDL UI. However, it does not when
running
> headless. Moreover, any attempt to install a similar scheme to the > Cocoa UI's main thread replacement fails when combined with the

SDL

Quoted 7 lines

> UI.
>
> This change tidies up main thread management to be more flexible. >
> * The qemu_main global function pointer is a custom function
for the
> main thread, and it may now be NULL. When it is, the main

thread

Quoted 1 line

> runs the main Qemu loop. This represents the traditional

setup.

Quoted 4 lines

> * When non-null, spawning the main Qemu event loop on a separate
> thread is now done centrally rather than inside the Cocoa UI
code.
> * For most platforms, qemu_main is indeed NULL by default, but

on

Quoted 9 lines

> Darwin, it defaults to a function that runs the CFRunLoop.
> * The Cocoa UI sets qemu_main to a function which runs the
> NSApplication event handling runloop, as is usual for a Cocoa
app.
> * The SDL UI overrides the qemu_main function to NULL, thus
> specifying that Qemu's main loop must run on the main
> thread.
> * The GTK UI also overrides the qemu_main function to NULL.
> * For other UIs, or in the absence of UIs, the platform's

default

Quoted 4 lines

> behaviour is followed.
>
> This means that on macOS, the platform's runloop events are always > handled, regardless of chosen UI. The new PV graphics device will

Quoted 8 lines

> thus work in all configurations. There is no functional change on
other
> operating systems.
>
> Implementing this via a global function pointer variable is a bit > ugly, but it's probably worth investigating the existing UI
thread rule
> violations in the SDL (e.g. #2537) and GTK+ back-ends. Fixing

those

Quoted 11 lines

> issues might precipitate requirements similar but not identical
to those
> of the Cocoa UI; hopefully we'll see some kind of pattern emerge,
which
> can then be used as a basis for an overhaul. (In fact, it may turn > out to be simplest to split the UI/native platform event thread
from the
> QEMU main event loop on all platforms, with any UI or even none
at all.)
>
> Signed-off-by: Phil Dennis-Jordan <[email protected]

Quoted 8 lines

<mailto:[email protected]>>
> ---
>
> v5:
>
> * Simplified the way of setting/clearing the main loop by going
back
> to setting qemu_main directly, but narrowing the scope of

what it

Quoted 5 lines
     >     needs to do, and it can now be NULL.
     >
     > v6:
     >
     >   * Folded function qemu_run_default_main_on_new_thread's code

into

Quoted 2 lines

> main()
> * Removed whitespace changes left over on lines near code

removed

Quoted 10 lines
     >     between v4 and v5
     >
     > v9:
     >
     >   * Set qemu_main to NULL for GTK UI as well.
     >
     > v10:
     >
     >   * Added comments clarifying the functionality and purpose of
    qemu_main.
Quoted 8 lines
     >
     > v11:
     >
     >   * Removed the qemu_main_fn typedef again.
     >   * Consolidation of main, qemu_default_main, and
    call_qemu_default_main
     >     so that the latter has been eliminated altogether.
     >   * Reinstated the #include <SDL.h> directive, added comment

saying

Quoted 15 lines
     >     why it's needed.
     >   * Improved the comment on the qemu_main global variable.
     >   * Expanded the commit message.
     >
     >   include/qemu-main.h | 14 +++++++++++-
     >   system/main.c       | 37 +++++++++++++++++++++++++++----
     >   ui/cocoa.m          | 54 ++++++++++
    +----------------------------------
     >   ui/gtk.c            |  8 +++++++
     >   ui/sdl2.c           |  4 ++++
     >   5 files changed, 71 insertions(+), 46 deletions(-)
     >
     > diff --git a/include/qemu-main.h b/include/qemu-main.h
     > index 940960a7dbc..a926def7526 100644
     > --- a/include/qemu-main.h
Quoted 8 lines
     > +++ b/include/qemu-main.h
     > @@ -5,7 +5,19 @@
     >   #ifndef QEMU_MAIN_H
     >   #define QEMU_MAIN_H
     >
     > -int qemu_default_main(void);
     > +/*
     > + * The function to run on the main (initial) thread of the

process.

Quoted 12 lines

> + * NULL means QEMU's main event loop.
> + * When non-NULL, QEMU's main event loop will run on a purposely
created
> + * thread, after which the provided function pointer will be
invoked on
> + * the initial thread.
> + * This is useful on platforms which treat the main thread as
special
> + * (macOS/Darwin) and/or require all UI API calls to occur from a > + * specific thread. Those platforms can initialise it to a
specific function,

Quoted 5 lines

Although the change from v10 looks good, I have a few comments:

Here, it says "require all UI API calls to occur from a specific thread", but it is clearer to say "require all UI API calls to occur from *the main thread*". If we only need to ensure all UI API calls

to

Quoted 2 lines

occur from one thread, arranging all calls to happen in the thread running QEMU's main loop is sufficient. This variable is necessary

only

Quoted 10 lines

when the thread is the one that called main().

Is there a simple way to reliably run a block of code on the thread running QEMU's main loop? (*) BHs will run on any thread that's blocked in AIO_WAIT_WHILE(NULL, …) or similar, so those are not suitable. Apparently GTK+ on Win32 requires all API calls to originate from one thread, but it doesn't need to be the main thread, which is why I chose that phrasing. But I suppose if that's the only restriction, the UI can spawn its own thread and leave the main thread alone.

Quoted 7 lines

Setting qemu_main does not help in such a case because BHs may still run on other threads so it needs another approach.

I think iohandler_get_aio_context() does what we want, but it is not intended to be used to identify the thread to run the UI so using it is like a hack. Spawning a thread dedicated for UI is more appropriate.

Ultimately, it may make sense to put the whole display and UI subsystem on its own dedicated AioContext and thread (main thread on macOS)… But that might require some tweaks to the AioContext system - I really don't know it (or the SDL and GTK code base) well enough to say with any certainty what the best approach would be right now.

Quoted 285 lines

(*) This would be good to know for fixing this bug https://gitlab.com/

Quoted 6 lines

qemu-project/qemu/-/issues/2537 <https://gitlab.com/qemu-project/qemu/-/
issues/2537> where the SDL UI code causes a hang by calling into SDL_SetWindowSize() from a CPU thread. My current thinking on that one is to use SDL_PushEvent() with a custom event type generated by SDL_RegisterEvents(), which then will be handled via the standard SDL event polling mechanism; but that seems awkward.

I think it's totally fine. If SDL (backed by Cocoa) insists to own the main thread, let it do so.

Quoted 90 lines
     > + * while UI implementations may reset it to NULL during their
    init if they
     > + * will handle system and UI events on the main thread via
    QEMU's own main
     > + * event loop.> + */
     >   extern int (*qemu_main)(void);
     >
     >   #endif /* QEMU_MAIN_H */
     > diff --git a/system/main.c b/system/main.c
     > index 9b91d21ea8c..668d0ecfe8c 100644
     > --- a/system/main.c
     > +++ b/system/main.c
     > @@ -24,26 +24,55 @@
     >
     >   #include "qemu/osdep.h"
     >   #include "qemu-main.h"
     > +#include "qemu/main-loop.h"
     >   #include "sysemu/sysemu.h"
     >
     >   #ifdef CONFIG_SDL
     > +/*
     > + * SDL insists on wrapping the main() function with its own
    implementation on
     > + * some platforms; it does so via a macro that renames our main
    function, so
     > + * <SDL.h> must be #included here even with no SDL code called
    from this file.
     > + */
     >   #include <SDL.h>
     >   #endif
     >
     > -int qemu_default_main(void)
     > +#ifdef CONFIG_DARWIN
     > +#include <CoreFoundation/CoreFoundation.h>
     > +#endif
     > +
     > +static void *qemu_default_main(void *opaque)
     >   {
     >       int status;
     >
     > +    bql_lock();
     >       status = qemu_main_loop();
     >       qemu_cleanup(status);
     > +    bql_unlock();
     >
     > -    return status;
     > +    exit(status);
     >   }
     >
     > -int (*qemu_main)(void) = qemu_default_main;
     > +int (*qemu_main)(void);
     > +
     > +#ifdef CONFIG_DARWIN
     > +static int os_darwin_cfrunloop_main(void)
     > +{
     > +    CFRunLoopRun();
     > +    g_assert_not_reached();
     > +}
     > +int (*qemu_main)(void) = os_darwin_cfrunloop_main;
     > +#endif
     >
     >   int main(int argc, char **argv)
     >   {
     >       qemu_init(argc, argv);
     > -    return qemu_main();
     > +    bql_unlock();
     > +    if (qemu_main) {
     > +        QemuThread main_loop_thread;
     > +        qemu_thread_create(&main_loop_thread, "qemu_main",
     > +                           qemu_default_main, NULL,
    QEMU_THREAD_DETACHED);
     > +        return qemu_main();
     > +    } else {
     > +        qemu_default_main(NULL);
     > +    }
     >   }
     > diff --git a/ui/cocoa.m b/ui/cocoa.m
     > index 4c2dd335323..30b8920d929 100644
     > --- a/ui/cocoa.m
     > +++ b/ui/cocoa.m
     > @@ -73,6 +73,8 @@
     >       int height;
     >   } QEMUScreen;
     >
     > +@class QemuCocoaPasteboardTypeOwner;
     > +
     >   static void cocoa_update(DisplayChangeListener *dcl,
     >                            int x, int y, int w, int h);
     >
Quoted 8 lines
     > @@ -107,6 +109,7 @@ static void
    cocoa_switch(DisplayChangeListener *dcl,
     >   static NSInteger cbchangecount = -1;
     >   static QemuClipboardInfo *cbinfo;
     >   static QemuEvent cbevent;
     > +static QemuCocoaPasteboardTypeOwner *cbowner;
     >
     >   // Utility functions to run specified code block with the BQL

held

Quoted 14 lines
     >   typedef void (^CodeBlock)(void);
     > @@ -1321,8 +1324,10 @@ - (void) dealloc
     >   {
     >       COCOA_DEBUG("QemuCocoaAppController: dealloc\n");
     >
     > -    if (cocoaView)
     > -        [cocoaView release];
     > +    [cocoaView release];
     > +    [cbowner release];
     > +    cbowner = nil;
     > +
     >       [super dealloc];
     >   }
     >
Quoted 8 lines
     > @@ -1938,8 +1943,6 @@ - (void)pasteboard:(NSPasteboard *)sender
    provideDataForType:(NSPasteboardType)t
     >
     >   @end
     >
     > -static QemuCocoaPasteboardTypeOwner *cbowner;
     > -
     >   static void cocoa_clipboard_notify(Notifier *notifier, void

*data);

Quoted 9 lines
     >   static void cocoa_clipboard_request(QemuClipboardInfo *info,
     >                                       QemuClipboardType type);
     > @@ -2002,43 +2005,8 @@ static void
    cocoa_clipboard_request(QemuClipboardInfo *info,
     >       }
     >   }
     >
     > -/*
     > - * The startup process for the OSX/Cocoa UI is complicated,

because

Quoted 3 lines

> - * OSX insists that the UI runs on the initial main thread, and
so we
> - * need to start a second thread which runs the

qemu_default_main():

Quoted 108 lines
     > - * in main():
     > - *  in cocoa_display_init():
     > - *   assign cocoa_main to qemu_main
     > - *   create application, menus, etc
     > - *  in cocoa_main():
     > - *   create qemu-main thread
     > - *   enter OSX run loop
     > - */
     > -
     > -static void *call_qemu_main(void *opaque)
     > -{
     > -    int status;
     > -
     > -    COCOA_DEBUG("Second thread: calling qemu_default_main()\n");
     > -    bql_lock();
     > -    status = qemu_default_main();
     > -    bql_unlock();
     > -    COCOA_DEBUG("Second thread: qemu_default_main() returned,
    exiting\n");
     > -    [cbowner release];
     > -    exit(status);
     > -}
     > -
     >   static int cocoa_main(void)
     >   {
     > -    QemuThread thread;
     > -
     > -    COCOA_DEBUG("Entered %s()\n", __func__);
     > -
     > -    bql_unlock();
     > -    qemu_thread_create(&thread, "qemu_main", call_qemu_main,
     > -                       NULL, QEMU_THREAD_DETACHED);
     > -
     > -    // Start the main event loop
     >       COCOA_DEBUG("Main thread: entering OSX run loop\n");
     >       [NSApp run];
     >       COCOA_DEBUG("Main thread: left OSX run loop, which should
    never happen\n");
     > @@ -2120,8 +2088,6 @@ static void cocoa_display_init(DisplayState
    *ds, DisplayOptions *opts)
     >
     >       COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n");
     >
     > -    qemu_main = cocoa_main;
     > -
     >       // Pull this console process up to being a fully-fledged
    graphical
     >       // app with a menubar and Dock icon
     >       ProcessSerialNumber psn = { 0, kCurrentProcess };
     > @@ -2185,6 +2151,12 @@ static void
    cocoa_display_init(DisplayState *ds, DisplayOptions *opts)
     >       qemu_clipboard_peer_register(&cbpeer);
     >
     >       [pool release];
     > +
     > +    /*
     > +     * The Cocoa UI will run the NSApplication runloop on the
    main thread
     > +     * rather than the default Core Foundation one.
     > +     */
     > +    qemu_main = cocoa_main;
     >   }
     >
     >   static QemuDisplay qemu_display_cocoa = {
     > diff --git a/ui/gtk.c b/ui/gtk.c
     > index bf9d3dd679a..5e6ee5c12a2 100644
     > --- a/ui/gtk.c
     > +++ b/ui/gtk.c
     > @@ -38,6 +38,7 @@
     >   #include "qemu/cutils.h"
     >   #include "qemu/error-report.h"
     >   #include "qemu/main-loop.h"
     > +#include "qemu-main.h"
     >
     >   #include "ui/console.h"
     >   #include "ui/gtk.h"
     > @@ -2485,6 +2486,13 @@ static void gtk_display_init(DisplayState
    *ds, DisplayOptions *opts)
     >   #ifdef CONFIG_GTK_CLIPBOARD
     >       gd_clipboard_init(s);
     >   #endif /* CONFIG_GTK_CLIPBOARD */
     > +
     > +    /*
     > +     * GTK+ calls must happen on the main thread at least on
    some platforms,
     > +     * and on macOS the main runloop is polled via GTK+'s event
    handling.
     > +     * Don't allow QEMU's event loop to be moved off the main
    thread.
     > +     */
     > +    qemu_main = NULL;
     >   }
     >
     >   static void early_gtk_display_init(DisplayOptions *opts)
     > diff --git a/ui/sdl2.c b/ui/sdl2.c
     > index bd4f5a9da14..44ab2762262 100644
     > --- a/ui/sdl2.c
     > +++ b/ui/sdl2.c
     > @@ -34,6 +34,7 @@
     >   #include "sysemu/sysemu.h"
     >   #include "ui/win32-kbd-hook.h"
     >   #include "qemu/log.h"
     > +#include "qemu-main.h"
     >
     >   static int sdl2_num_outputs;
     >   static struct sdl2_console *sdl2_console;
     > @@ -965,6 +966,9 @@ static void sdl2_display_init(DisplayState
    *ds, DisplayOptions *o)
Quoted 8 lines
     >       }
     >
     >       atexit(sdl_cleanup);
     > +
     > +    /* SDL's event polling (in dpy_refresh) must happen on the
    main thread. */

    ui/gtk.c and ui/sdl2.c have the same background so the comments

should

Quoted 7 lines

also be identical except names.

Well, GTK doesn't currently do this, which is why it doesn't work on macOS, but hopefully this patch will be merged in some form, at which point it will:

Quoted 5 lines

https://patchew.org/QEMU/[email protected]/
<https://patchew.org/QEMU/[email protected]/>

But yeah, thanks to this patch we know that's a solution for GTK as well, and I can update the comment.

I only meant that SDL is not different from GTK in terms that its call and event handling needs to be done in the main thread.

I was not paying attention to the mention of dpy_refresh(). It is another topic whether dpy_refresh() is the best place for event handling, and I don't think so. dpy_refresh() is triggered when refreshing the display output, but event handling is not specific to the display output so it is awkward to handle events there.

Quoted 5 lines

The best approach is to do the same with ui/cocoa; override qemu_main to dedicate the main thread for the UI and decouple the UI from the BQL by calling GTK with g_main_context_invoke(), which corresponds to SDL_RegisterEvents() in SDL.

It seems like a cleaner approach it theory, but QEMU's modified reimplementation of the GLib event loop could complicate matters, so I'm not sure it would be a quick or easy change to make. It's probably worth accepting the conceptually uglier fix via dpy_refresh() or an explicit timer for the moment, in preference to GTK not working at all on macOS. That is especially considering the SDL UI currently successfully does the exact same thing on all platforms at the moment. In any case, all of these considerations are beyond the scope of this immediate patch. I think the patch as is (with the proposed tweaks to the wording of comments) is a step in the right direction by pulling the main thread replacement logic out of the Cocoa UI code and making it generally available. The qemu_main = NULL; assignments can easily be amended in future.

Quoted 8 lines
Quoted 6 lines
     > +    qemu_main = NULL;
     >   }
     >
     >   static QemuDisplay qemu_display_sdl2 = {
#6 lore raw

Re: [PATCH v11 01/15] ui & main loop: Redesign of system-specific main thread event handling

Quoted 224 lines · Phil Dennis-Jordan

On Fri, 29 Nov 2024 at 11:07, Akihiko Odaki <[email protected] <mailto:[email protected]>> wrote:

On 2024/11/29 4:43, Phil Dennis-Jordan wrote:
>
>
> On Thu, 28 Nov 2024 at 12:17, Akihiko Odaki
<[email protected] <mailto:[email protected]>
> <mailto:[email protected]
<mailto:[email protected]>>> wrote:
>
>     On 2024/11/28 0:02, Phil Dennis-Jordan wrote:
>      > macOS's Cocoa event handling must be done on the initial
(main)
>     thread
>      > of the process. Furthermore, if library or application
code uses
>      > libdispatch, the main dispatch queue must be handling
events on
>     the main
>      > thread as well.
>      >
>      > So far, this has affected Qemu in both the Cocoa and SDL UIs, >     although
>      > in different ways: the Cocoa UI replaces the default qemu_main >     function
>      > with one that spins Qemu's internal main event loop off onto a >      > background thread. SDL (which uses Cocoa internally) on
the other
>     hand
>      > uses a polling approach within Qemu's main event loop.
Events are
>      > polled during the SDL UI's dpy_refresh callback, which
happens to run
>      > on the main thread by default.
>      >
>      > As UIs are mutually exclusive, this works OK as long as
nothing else
>      > needs platform-native event handling. In the next patch, a new >     device is
>      > introduced based on the ParavirtualizedGraphics.framework
in macOS.
>      > This uses libdispatch internally, and only works when
events are
>     being
>      > handled on the main runloop. With the current system, it
works when
>      > using either the Cocoa or the SDL UI. However, it does not
when
>     running
>      > headless. Moreover, any attempt to install a similar
scheme to the
>      > Cocoa UI's main thread replacement fails when combined
with the SDL
>      > UI.
>      >
>      > This change tidies up main thread management to be more
flexible.
>      >
>      >   * The qemu_main global function pointer is a custom function >     for the
>      >     main thread, and it may now be NULL. When it is, the
main thread
>      >     runs the main Qemu loop. This represents the
traditional setup.
>      >   * When non-null, spawning the main Qemu event loop on a
separate
>      >     thread is now done centrally rather than inside the
Cocoa UI
>     code.
>      >   * For most platforms, qemu_main is indeed NULL by
default, but on
>      >     Darwin, it defaults to a function that runs the CFRunLoop. >      >   * The Cocoa UI sets qemu_main to a function which runs the >      >     NSApplication event handling runloop, as is usual for
a Cocoa
>     app.
>      >   * The SDL UI overrides the qemu_main function to NULL, thus >      >     specifying that Qemu's main loop must run on the main >      >     thread.
>      >   * The GTK UI also overrides the qemu_main function to NULL. >      >   * For other UIs, or in the absence of UIs, the
platform's default
>      >     behaviour is followed.
>      >
>      > This means that on macOS, the platform's runloop events
are always
>      > handled, regardless of chosen UI. The new PV graphics
device will
>      > thus work in all configurations. There is no functional
change on
>     other
>      > operating systems.
>      >
>      > Implementing this via a global function pointer variable
is a bit
>      > ugly, but it's probably worth investigating the existing UI >     thread rule
>      > violations in the SDL (e.g. #2537) and GTK+ back-ends.
Fixing those
>      > issues might precipitate requirements similar but not
identical
>     to those
>      > of the Cocoa UI; hopefully we'll see some kind of pattern
emerge,
>     which
>      > can then be used as a basis for an overhaul. (In fact, it
may turn
>      > out to be simplest to split the UI/native platform event
thread
>     from the
>      > QEMU main event loop on all platforms, with any UI or even
none
>     at all.)
>      >
>      > Signed-off-by: Phil Dennis-Jordan <[email protected]
<mailto:[email protected]>
>     <mailto:[email protected] <mailto:[email protected]>>> >      > ---
>      >
>      > v5:
>      >
>      >   * Simplified the way of setting/clearing the main loop
by going
>     back
>      >     to setting qemu_main directly, but narrowing the scope
of what it
>      >     needs to do, and it can now be NULL.
>      >
>      > v6:
>      >
>      >   * Folded function qemu_run_default_main_on_new_thread's
code into
>      >     main()
>      >   * Removed whitespace changes left over on lines near
code removed
>      >     between v4 and v5
>      >
>      > v9:
>      >
>      >   * Set qemu_main to NULL for GTK UI as well.
>      >
>      > v10:
>      >
>      >   * Added comments clarifying the functionality and purpose of >     qemu_main.
>      >
>      > v11:
>      >
>      >   * Removed the qemu_main_fn typedef again.
>      >   * Consolidation of main, qemu_default_main, and >     call_qemu_default_main
>      >     so that the latter has been eliminated altogether. >      >   * Reinstated the #include <SDL.h> directive, added
comment saying
>      >     why it's needed.
>      >   * Improved the comment on the qemu_main global variable. >      >   * Expanded the commit message.
>      >
>      >   include/qemu-main.h | 14 +++++++++++-
>      >   system/main.c       | 37 +++++++++++++++++++++++++++---- >      >   ui/cocoa.m          | 54 ++++++++++
>     +----------------------------------
>      >   ui/gtk.c            |  8 +++++++
>      >   ui/sdl2.c           |  4 ++++
>      >   5 files changed, 71 insertions(+), 46 deletions(-) >      >
>      > diff --git a/include/qemu-main.h b/include/qemu-main.h >      > index 940960a7dbc..a926def7526 100644
>      > --- a/include/qemu-main.h
>      > +++ b/include/qemu-main.h
>      > @@ -5,7 +5,19 @@
>      >   #ifndef QEMU_MAIN_H
>      >   #define QEMU_MAIN_H
>      >
>      > -int qemu_default_main(void);
>      > +/*
>      > + * The function to run on the main (initial) thread of
the process.
>      > + * NULL means QEMU's main event loop.
>      > + * When non-NULL, QEMU's main event loop will run on a
purposely
>     created
>      > + * thread, after which the provided function pointer will be >     invoked on
>      > + * the initial thread.
>      > + * This is useful on platforms which treat the main thread as >     special
>      > + * (macOS/Darwin) and/or require all UI API calls to
occur from a
>      > + * specific thread. Those platforms can initialise it to a >     specific function,
>
>     Although the change from v10 looks good, I have a few comments:
>
>     Here, it says "require all UI API calls to occur from a specific >     thread", but it is clearer to say "require all UI API calls
to occur
>     from *the main thread*". If we only need to ensure all UI API
calls to
>     occur from one thread, arranging all calls to happen in the
thread
>     running QEMU's main loop is sufficient. This variable is
necessary only
>     when the thread is the one that called main().
>
>
> Is there a simple way to reliably run a block of code on the thread > running QEMU's main loop? (*) BHs will run on any thread that's
blocked
> in AIO_WAIT_WHILE(NULL, …) or similar, so those are not suitable. > Apparently GTK+ on Win32 requires all API calls to originate from
one
> thread, but it doesn't need to be the main thread, which is why I
chose
> that phrasing. But I suppose if that's the only restriction, the
UI can
> spawn its own thread and leave the main thread alone.

Setting qemu_main does not help in such a case because BHs may still run
on other threads so it needs another approach.

Quoted 6 lines

I think iohandler_get_aio_context() does what we want, but it is not intended to be used to identify the thread to run the UI so using it is like a hack. Spawning a thread dedicated for UI is more appropriate.

Ultimately, it may make sense to put the whole display and UI subsystem on its own dedicated AioContext and thread (main thread on macOS)… But that might require some tweaks to the AioContext system - I really don't know it (or the SDL and GTK code base) well enough to say with any certainty what the best approach would be right now.

SDL has its own event mechanism so having AioContext makes duplication of work. We can use SDL_PushEvent() for that platform to avoid that. The situation of GTK is no different except it will involve g_main_context_invoke() instead of SDL_PushEvent().

Quoted 306 lines

> (*) This would be good to know for fixing this bug https://
gitlab.com/ <https://gitlab.com/>
> qemu-project/qemu/-/issues/2537 <https://gitlab.com/qemu-project/
qemu/-/ <https://gitlab.com/qemu-project/qemu/-/>
> issues/2537> where the SDL UI code causes a hang by calling into > SDL_SetWindowSize() from a CPU thread. My current thinking on
that one
> is to use SDL_PushEvent() with a custom event type generated by > SDL_RegisterEvents(), which then will be handled via the standard
SDL
> event polling mechanism; but that seems awkward.
I think it's totally fine. If SDL (backed by Cocoa) insists to own the main thread, let it do so.

>
>      > + * while UI implementations may reset it to NULL during their >     init if they
>      > + * will handle system and UI events on the main thread via >     QEMU's own main
>      > + * event loop.> + */
>      >   extern int (*qemu_main)(void);
>      >
>      >   #endif /* QEMU_MAIN_H */
>      > diff --git a/system/main.c b/system/main.c
>      > index 9b91d21ea8c..668d0ecfe8c 100644
>      > --- a/system/main.c
>      > +++ b/system/main.c
>      > @@ -24,26 +24,55 @@
>      >
>      >   #include "qemu/osdep.h"
>      >   #include "qemu-main.h"
>      > +#include "qemu/main-loop.h"
>      >   #include "sysemu/sysemu.h"
>      >
>      >   #ifdef CONFIG_SDL
>      > +/*
>      > + * SDL insists on wrapping the main() function with its own >     implementation on
>      > + * some platforms; it does so via a macro that renames
our main
>     function, so
>      > + * <SDL.h> must be #included here even with no SDL code
called
>     from this file.
>      > + */
>      >   #include <SDL.h>
>      >   #endif
>      >
>      > -int qemu_default_main(void)
>      > +#ifdef CONFIG_DARWIN
>      > +#include <CoreFoundation/CoreFoundation.h>
>      > +#endif
>      > +
>      > +static void *qemu_default_main(void *opaque)
>      >   {
>      >       int status;
>      >
>      > +    bql_lock();
>      >       status = qemu_main_loop();
>      >       qemu_cleanup(status);
>      > +    bql_unlock();
>      >
>      > -    return status;
>      > +    exit(status);
>      >   }
>      >
>      > -int (*qemu_main)(void) = qemu_default_main;
>      > +int (*qemu_main)(void);
>      > +
>      > +#ifdef CONFIG_DARWIN
>      > +static int os_darwin_cfrunloop_main(void)
>      > +{
>      > +    CFRunLoopRun();
>      > +    g_assert_not_reached();
>      > +}
>      > +int (*qemu_main)(void) = os_darwin_cfrunloop_main; >      > +#endif
>      >
>      >   int main(int argc, char **argv)
>      >   {
>      >       qemu_init(argc, argv);
>      > -    return qemu_main();
>      > +    bql_unlock();
>      > +    if (qemu_main) {
>      > +        QemuThread main_loop_thread;
>      > +        qemu_thread_create(&main_loop_thread, "qemu_main", >      > +                           qemu_default_main, NULL, >     QEMU_THREAD_DETACHED);
>      > +        return qemu_main();
>      > +    } else {
>      > +        qemu_default_main(NULL);
>      > +    }
>      >   }
>      > diff --git a/ui/cocoa.m b/ui/cocoa.m
>      > index 4c2dd335323..30b8920d929 100644
>      > --- a/ui/cocoa.m
>      > +++ b/ui/cocoa.m
>      > @@ -73,6 +73,8 @@
>      >       int height;
>      >   } QEMUScreen;
>      >
>      > +@class QemuCocoaPasteboardTypeOwner;
>      > +
>      >   static void cocoa_update(DisplayChangeListener *dcl, >      >                            int x, int y, int w, int h); >      >
>      > @@ -107,6 +109,7 @@ static void
>     cocoa_switch(DisplayChangeListener *dcl,
>      >   static NSInteger cbchangecount = -1;
>      >   static QemuClipboardInfo *cbinfo;
>      >   static QemuEvent cbevent;
>      > +static QemuCocoaPasteboardTypeOwner *cbowner;
>      >
>      >   // Utility functions to run specified code block with
the BQL held
>      >   typedef void (^CodeBlock)(void);
>      > @@ -1321,8 +1324,10 @@ - (void) dealloc
>      >   {
>      >       COCOA_DEBUG("QemuCocoaAppController: dealloc\n"); >      >
>      > -    if (cocoaView)
>      > -        [cocoaView release];
>      > +    [cocoaView release];
>      > +    [cbowner release];
>      > +    cbowner = nil;
>      > +
>      >       [super dealloc];
>      >   }
>      >
>      > @@ -1938,8 +1943,6 @@ - (void)pasteboard:(NSPasteboard
*)sender
>     provideDataForType:(NSPasteboardType)t
>      >
>      >   @end
>      >
>      > -static QemuCocoaPasteboardTypeOwner *cbowner;
>      > -
>      >   static void cocoa_clipboard_notify(Notifier *notifier,
void *data);
>      >   static void cocoa_clipboard_request(QemuClipboardInfo *info, >      >                                       QemuClipboardType type); >      > @@ -2002,43 +2005,8 @@ static void
>     cocoa_clipboard_request(QemuClipboardInfo *info,
>      >       }
>      >   }
>      >
>      > -/*
>      > - * The startup process for the OSX/Cocoa UI is
complicated, because
>      > - * OSX insists that the UI runs on the initial main
thread, and
>     so we
>      > - * need to start a second thread which runs the
qemu_default_main():
>      > - * in main():
>      > - *  in cocoa_display_init():
>      > - *   assign cocoa_main to qemu_main
>      > - *   create application, menus, etc
>      > - *  in cocoa_main():
>      > - *   create qemu-main thread
>      > - *   enter OSX run loop
>      > - */
>      > -
>      > -static void *call_qemu_main(void *opaque)
>      > -{
>      > -    int status;
>      > -
>      > -    COCOA_DEBUG("Second thread: calling
qemu_default_main()\n");
>      > -    bql_lock();
>      > -    status = qemu_default_main();
>      > -    bql_unlock();
>      > -    COCOA_DEBUG("Second thread: qemu_default_main() returned, >     exiting\n");
>      > -    [cbowner release];
>      > -    exit(status);
>      > -}
>      > -
>      >   static int cocoa_main(void)
>      >   {
>      > -    QemuThread thread;
>      > -
>      > -    COCOA_DEBUG("Entered %s()\n", __func__);
>      > -
>      > -    bql_unlock();
>      > -    qemu_thread_create(&thread, "qemu_main", call_qemu_main, >      > -                       NULL, QEMU_THREAD_DETACHED); >      > -
>      > -    // Start the main event loop
>      >       COCOA_DEBUG("Main thread: entering OSX run loop\n"); >      >       [NSApp run];
>      >       COCOA_DEBUG("Main thread: left OSX run loop, which
should
>     never happen\n");
>      > @@ -2120,8 +2088,6 @@ static void
cocoa_display_init(DisplayState
>     *ds, DisplayOptions *opts)
>      >
>      >       COCOA_DEBUG("qemu_cocoa: cocoa_display_init\n"); >      >
>      > -    qemu_main = cocoa_main;
>      > -
>      >       // Pull this console process up to being a fully-fledged >     graphical
>      >       // app with a menubar and Dock icon
>      >       ProcessSerialNumber psn = { 0, kCurrentProcess }; >      > @@ -2185,6 +2151,12 @@ static void
>     cocoa_display_init(DisplayState *ds, DisplayOptions *opts) >      >       qemu_clipboard_peer_register(&cbpeer);
>      >
>      >       [pool release];
>      > +
>      > +    /*
>      > +     * The Cocoa UI will run the NSApplication runloop on the >     main thread
>      > +     * rather than the default Core Foundation one. >      > +     */
>      > +    qemu_main = cocoa_main;
>      >   }
>      >
>      >   static QemuDisplay qemu_display_cocoa = {
>      > diff --git a/ui/gtk.c b/ui/gtk.c
>      > index bf9d3dd679a..5e6ee5c12a2 100644
>      > --- a/ui/gtk.c
>      > +++ b/ui/gtk.c
>      > @@ -38,6 +38,7 @@
>      >   #include "qemu/cutils.h"
>      >   #include "qemu/error-report.h"
>      >   #include "qemu/main-loop.h"
>      > +#include "qemu-main.h"
>      >
>      >   #include "ui/console.h"
>      >   #include "ui/gtk.h"
>      > @@ -2485,6 +2486,13 @@ static void
gtk_display_init(DisplayState
>     *ds, DisplayOptions *opts)
>      >   #ifdef CONFIG_GTK_CLIPBOARD
>      >       gd_clipboard_init(s);
>      >   #endif /* CONFIG_GTK_CLIPBOARD */
>      > +
>      > +    /*
>      > +     * GTK+ calls must happen on the main thread at least on >     some platforms,
>      > +     * and on macOS the main runloop is polled via GTK+'s
event
>     handling.
>      > +     * Don't allow QEMU's event loop to be moved off the main >     thread.
>      > +     */
>      > +    qemu_main = NULL;
>      >   }
>      >
>      >   static void early_gtk_display_init(DisplayOptions *opts) >      > diff --git a/ui/sdl2.c b/ui/sdl2.c
>      > index bd4f5a9da14..44ab2762262 100644
>      > --- a/ui/sdl2.c
>      > +++ b/ui/sdl2.c
>      > @@ -34,6 +34,7 @@
>      >   #include "sysemu/sysemu.h"
>      >   #include "ui/win32-kbd-hook.h"
>      >   #include "qemu/log.h"
>      > +#include "qemu-main.h"
>      >
>      >   static int sdl2_num_outputs;
>      >   static struct sdl2_console *sdl2_console;
>      > @@ -965,6 +966,9 @@ static void sdl2_display_init(DisplayState >     *ds, DisplayOptions *o)
>      >       }
>      >
>      >       atexit(sdl_cleanup);
>      > +
>      > +    /* SDL's event polling (in dpy_refresh) must happen
on the
>     main thread. */
>
>     ui/gtk.c and ui/sdl2.c have the same background so the
comments should
>     also be identical except names.
>
>
> Well, GTK doesn't currently do this, which is why it doesn't work on > macOS, but hopefully this patch will be merged in some form, at
which
> point it will:
>
> https://patchew.org/QEMU/20241121162146.53643-1-
[email protected]/ <https://patchew.org/
QEMU/[email protected]/>
> <https://patchew.org/QEMU/20241121162146.53643-1-
[email protected]/ <https://patchew.org/
QEMU/[email protected]/>>
>
> But yeah, thanks to this patch we know that's a solution for GTK as > well, and I can update the comment.

I only meant that SDL is not different from GTK in terms that its call and event handling needs to be done in the main thread.

I was not paying attention to the mention of dpy_refresh(). It is another topic whether dpy_refresh() is the best place for event handling, and I don't think so. dpy_refresh() is triggered when refreshing the display output, but event handling is not specific to the
display output so it is awkward to handle events there.

Quoted 8 lines

The best approach is to do the same with ui/cocoa; override qemu_main to
dedicate the main thread for the UI and decouple the UI from the BQL by calling GTK with g_main_context_invoke(), which corresponds to SDL_RegisterEvents() in SDL.

It seems like a cleaner approach it theory, but QEMU's modified reimplementation of the GLib event loop could complicate matters, so I'm not sure it would be a quick or easy change to make. It's probably worth accepting the conceptually uglier fix via dpy_refresh() or an explicit timer for the moment, in preference to GTK not working at all on macOS. That is especially considering the SDL UI currently successfully does the exact same thing on all platforms at the moment. In any case, all of these considerations are beyond the scope of this immediate patch. I think the patch as is (with the proposed tweaks to the wording of comments) is a step in the right direction by pulling the main thread replacement logic out of the Cocoa UI code and making it generally available. The qemu_main = NULL; assignments can easily be amended in future.

I think we can rule out the possible complication due to the event loop reimplementation if a thread is dedicated for GTK.

SDL's success is somewhat imperfect due to the lack of guarantee that its code runs in the main thread, but certainly the imperfect is better than the complete breakage.

Quoted 8 lines
     >
     >      > +    qemu_main = NULL;
     >      >   }
     >      >
     >      >   static QemuDisplay qemu_display_sdl2 = {
     >
#7 lore raw

PATCH v11 2/15 hw/display/apple-gfx: Introduce ParavirtualizedGraphics.Framework support

In reply to Phil Dennis-Jordan

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, API use updates.
* Moved from hw/vmapple/ (useful outside that machine type)
* Overhaul of threading model, many thread safety improvements.
* Asynchronous rendering.
* Memory and object lifetime fixes.
* Refactoring to split generic and (vmapple) MMIO variant specific code.

Implementation wise, most of the complexity lies in the differing threading models of ParavirtualizedGraphics.framework, which uses libdispatch and internal locks, versus QEMU, which heavily uses the BQL, especially during memory-mapped device I/O. Great care has therefore been taken to prevent deadlocks by never calling into PVG methods while holding the BQL, and similarly never acquiring the BQL in a callback from PVG. Different strategies have been used (libdispatch, blocking and non-blocking BHs, RCU, etc.) depending on the specific requirements at each framework entry and exit point.

---

v2:

* 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

v3:

* Rebased on latest upstream, fixed breakages including switching to Resettable methods.
* Squashed patches dealing with dGPUs, MMIO area size, and GPU picking.
* Allow re-entrant MMIO; this simplifies the code and solves the divergence between x86-64 and arm64 variants.

v4:

* Renamed '-vmapple' device variant to '-mmio'
* MMIO device type now requires aarch64 host and guest
* Complete overhaul of the glue code for making Qemu's and ParavirtualizedGraphics.framework's threading and synchronisation models work together. Calls into PVG are from dispatch queues while the BQL-holding initiating thread processes AIO context events; callbacks from PVG are scheduled as BHs on the BQL/main AIO context, awaiting completion where necessary.
* Guest frame rendering state is covered by the BQL, with only the PVG calls outside the lock, and serialised on the named render_queue.
* Simplified logic for dropping frames in-flight during mode changes, fixed bug in pending frames logic.
* Addressed smaller code review notes such as: function naming, object type declarations, type names/declarations/casts, code formatting, #include order, over-cautious ObjC retain/release, what goes in init vs realize, etc.

v5:

* Smaller non-functional fixes in response to review comments, such as using NULL for the AIO_WAIT_WHILE context argument, type name formatting, deleting leftover debug code, logging improvements, state struct field order and documentation improvements, etc.
* Instead of a single condition variable for all synchronous BH job types, there is now one for each callback block. This reduces the number of threads being awoken unnecessarily to near zero.
* MMIO device variant: Unified the BH job for raising interrupts.
* Use DMA APIs for PVG framework's guest memory read requests.
* Thread safety improvements: ensure mutable AppleGFXState fields are not accessed outside the appropriate lock. Added dedicated mutex for the task list.
* Retain references to MemoryRegions for which there exist mappings in each PGTask, and for IOSurface mappings.

v6:

* Switched PGTask_s's' mapped_regions from GPtrArray to GArray
* Allow DisplaySurface to manage its own vram now that texture -> vram copy occurs under BQL.
* Memory mapping operations now use RCU_READ_LOCK_GUARD() where possible instead of a heavy-weight BH job to acquire the BQL.
* Changed PVG cursor and mode setting callbacks to kick off BHs instead of libdispatch tasks which then locked the BQL explicitly.
* The single remaining callback which must wait for a BH to complete now creates an ephemeral QemuSemaphore to await completion.
* Re-removed tracking of mapped surface manager memory regions. Just look up and ref/unref the memory regions in the map/unmap callbacks.
* Re-ordered functions in apple-gfx.m to group them by area of functionality.
* Improved comments and tweaked some names.

v7:

* Use g_ptr_array_find() helper function
* Error handling coding style tweak

v8:

* Renamed apple_gfx_host_address_for_gpa_range() to apple_gfx_host_ptr_for_gpa_range(), and made it return a void* instead of uintptr_t. Fixed up callers and related code.
* Some adjustments to types used.
* Variable naming tweaks for better clarity.
* Fixed leak in unlikely realize error case.
* Fixed typo in unmap call.
* Don't bother with dummy argument for g_ptr_array_find(), NULL works too.

v9:

* Pass device pointer to graphic_console_init().
* Slightly re-ordered initialisation code.
* Simplified error handling during realize().
* Simplified code without functional changes, adjusted code & comment formatting.

v10:

* Reworked the way frame rendering code is threaded to use BHs for sections requiring BQL.
* Fix for ./configure error on non-macOS platforms.
* Code formatting tweaks.

v11:

* Generate unique display serial number for each apple-gfx device instance.
* Dropped redundant local variable initialisation.

 hw/display/Kconfig          |   9 +
 hw/display/apple-gfx-mmio.m | 281 +++++++++++++
 hw/display/apple-gfx.h      |  67 ++++
 hw/display/apple-gfx.m      | 776 ++++++++++++++++++++++++++++++++++++
 hw/display/meson.build      |   6 +
 hw/display/trace-events     |  28 ++
 meson.build                 |   4 +
 7 files changed, 1171 insertions(+)
 create mode 100644 hw/display/apple-gfx-mmio.m
 create mode 100644 hw/display/apple-gfx.h
 create mode 100644 hw/display/apple-gfx.m
hw/display/Kconfig +9 -0
index 2250c740078..6a9b7b19ada 100644
@@ -140,3 +140,12 @@ config XLNX_DISPLAYPORT
 
 config DM163
     bool
+
+config MAC_PVG
+    bool
+    default y
+
+config MAC_PVG_MMIO
+    bool
+    depends on MAC_PVG && AARCH64
+
hw/display/apple-gfx-mmio.m new file +281 -0

281 lines not on this page · raw message

hw/display/apple-gfx.h new file +67 -0

67 lines not on this page · raw message

hw/display/apple-gfx.m new file +776 -0

776 lines not on this page · raw message

hw/display/meson.build +6 -0
index 20a94973fa2..cf9e6dd35d2 100644
@@ -61,6 +61,12 @@ 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])
 
+if host_os == 'darwin'
+  system_ss.add(when: 'CONFIG_MAC_PVG',         if_true: [files('apple-gfx.m'), pvg, metal])
+  if cpu == 'aarch64'
+    system_ss.add(when: 'CONFIG_MAC_PVG_MMIO',  if_true: [files('apple-gfx-mmio.m'), pvg, metal])
+  endif
+endif
 
 if config_all_devices.has_key('CONFIG_VIRTIO_GPU')
   virtio_gpu_ss = ss.source_set()
hw/display/trace-events +28 -0
index d26d663f963..a50e4eea0c0 100644
@@ -194,3 +194,31 @@ 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, unsigned int num_mapped_regions) "task=%p, task->mapped_regions->len=%u"
+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, void *source_ptr, uint64_t target) "retval=%"PRId64" source=%p 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_common_init(const char *device_name, size_t mmio_size) "device: %s; MMIO size: %zu bytes"
+
+# apple-gfx-mmio.m
+apple_gfx_mmio_iosfc_read(uint64_t offset, uint64_t res) "offset=0x%"PRIx64" res=0x%"PRIx64
+apple_gfx_mmio_iosfc_write(uint64_t offset, uint64_t val) "offset=0x%"PRIx64" val=0x%"PRIx64
+apple_gfx_iosfc_map_memory(uint64_t phys, uint64_t len, uint32_t ro, void *va, void *e, void *f, void* va_result) "phys=0x%"PRIx64" len=0x%"PRIx64" ro=%d va=%p e=%p f=%p -> *va=%p"
+apple_gfx_iosfc_map_memory_new_region(size_t i, void *region, uint64_t start, uint64_t end) "index=%zu, region=%p, 0x%"PRIx64"-0x%"PRIx64
+apple_gfx_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_gfx_iosfc_unmap_memory_region(void* mem, void *region) "unmapping @ %p from memory region %p"
+apple_gfx_iosfc_raise_irq(uint32_t vector) "vector=0x%x"
+
meson.build +4 -0
index e0b880e4e13..3c61238bc77 100644
@@ -794,6 +794,8 @@ socket = []
 version_res = []
 coref = []
 iokit = []
+pvg = not_found
+metal = []
 emulator_link_args = []
 midl = not_found
 widl = not_found
@@ -815,6 +817,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.5 (Apple Git-154)
#8 lore raw

Re: [PATCH v11 02/15] hw/display/apple-gfx: Introduce ParavirtualizedGraphics.Framework support

Quoted 776 lines · Phil Dennis-Jordan

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, API use updates.
* Moved from hw/vmapple/ (useful outside that machine type)
* Overhaul of threading model, many thread safety improvements.
* Asynchronous rendering.
* Memory and object lifetime fixes.
* Refactoring to split generic and (vmapple) MMIO variant specific code.

Implementation wise, most of the complexity lies in the differing threading models of ParavirtualizedGraphics.framework, which uses libdispatch and internal locks, versus QEMU, which heavily uses the BQL, especially during memory-mapped device I/O. Great care has therefore been taken to prevent deadlocks by never calling into PVG methods while holding the BQL, and similarly never acquiring the BQL in a callback from PVG. Different strategies have been used (libdispatch, blocking and non-blocking BHs, RCU, etc.) depending on the specific requirements at each framework entry and exit point.

---

v2:

* 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

v3:

* Rebased on latest upstream, fixed breakages including switching to Resettable methods.
* Squashed patches dealing with dGPUs, MMIO area size, and GPU picking.
* Allow re-entrant MMIO; this simplifies the code and solves the divergence between x86-64 and arm64 variants.

v4:

* Renamed '-vmapple' device variant to '-mmio'
* MMIO device type now requires aarch64 host and guest
* Complete overhaul of the glue code for making Qemu's and ParavirtualizedGraphics.framework's threading and synchronisation models work together. Calls into PVG are from dispatch queues while the BQL-holding initiating thread processes AIO context events; callbacks from PVG are scheduled as BHs on the BQL/main AIO context, awaiting completion where necessary.
* Guest frame rendering state is covered by the BQL, with only the PVG calls outside the lock, and serialised on the named render_queue.
* Simplified logic for dropping frames in-flight during mode changes, fixed bug in pending frames logic.
* Addressed smaller code review notes such as: function naming, object type declarations, type names/declarations/casts, code formatting, #include order, over-cautious ObjC retain/release, what goes in init vs realize, etc.

v5:

* Smaller non-functional fixes in response to review comments, such as using NULL for the AIO_WAIT_WHILE context argument, type name formatting, deleting leftover debug code, logging improvements, state struct field order and documentation improvements, etc.
* Instead of a single condition variable for all synchronous BH job types, there is now one for each callback block. This reduces the number of threads being awoken unnecessarily to near zero.
* MMIO device variant: Unified the BH job for raising interrupts.
* Use DMA APIs for PVG framework's guest memory read requests.
* Thread safety improvements: ensure mutable AppleGFXState fields are not accessed outside the appropriate lock. Added dedicated mutex for the task list.
* Retain references to MemoryRegions for which there exist mappings in each PGTask, and for IOSurface mappings.

v6:

* Switched PGTask_s's' mapped_regions from GPtrArray to GArray
* Allow DisplaySurface to manage its own vram now that texture -> vram copy occurs under BQL.
* Memory mapping operations now use RCU_READ_LOCK_GUARD() where possible instead of a heavy-weight BH job to acquire the BQL.
* Changed PVG cursor and mode setting callbacks to kick off BHs instead of libdispatch tasks which then locked the BQL explicitly.
* The single remaining callback which must wait for a BH to complete now creates an ephemeral QemuSemaphore to await completion.
* Re-removed tracking of mapped surface manager memory regions. Just look up and ref/unref the memory regions in the map/unmap callbacks.
* Re-ordered functions in apple-gfx.m to group them by area of functionality.
* Improved comments and tweaked some names.

v7:

* Use g_ptr_array_find() helper function
* Error handling coding style tweak

v8:

* Renamed apple_gfx_host_address_for_gpa_range() to apple_gfx_host_ptr_for_gpa_range(), and made it return a void* instead of uintptr_t. Fixed up callers and related code.
* Some adjustments to types used.
* Variable naming tweaks for better clarity.
* Fixed leak in unlikely realize error case.
* Fixed typo in unmap call.
* Don't bother with dummy argument for g_ptr_array_find(), NULL works too.

v9:

* Pass device pointer to graphic_console_init().
* Slightly re-ordered initialisation code.
* Simplified error handling during realize().
* Simplified code without functional changes, adjusted code & comment formatting.

v10:

* Reworked the way frame rendering code is threaded to use BHs for sections requiring BQL.
* Fix for ./configure error on non-macOS platforms.
* Code formatting tweaks.

v11:

* Generate unique display serial number for each apple-gfx device instance.
* Dropped redundant local variable initialisation.

  hw/display/Kconfig          |   9 +
  hw/display/apple-gfx-mmio.m | 281 +++++++++++++
  hw/display/apple-gfx.h      |  67 ++++
  hw/display/apple-gfx.m      | 776 ++++++++++++++++++++++++++++++++++++
  hw/display/meson.build      |   6 +
  hw/display/trace-events     |  28 ++
  meson.build                 |   4 +
  7 files changed, 1171 insertions(+)

create mode 100644 hw/display/apple-gfx-mmio.m
create mode 100644 hw/display/apple-gfx.h
create mode 100644 hw/display/apple-gfx.m

hw/display/Kconfig +9 -0
index 2250c740078..6a9b7b19ada 100644
@@ -140,3 +140,12 @@ config XLNX_DISPLAYPORT
 
  config DM163
      bool
+
+config MAC_PVG
+    bool
+    default y
+
+config MAC_PVG_MMIO
+    bool
+    depends on MAC_PVG && AARCH64
+
hw/display/apple-gfx-mmio.m new file +281 -0
new file mode 100644
index 00000000000..2d76e7375bd
@@ -0,0 +1,281 @@
+/*
+ * QEMU Apple ParavirtualizedGraphics.framework device, MMIO (arm64) variant
+ *
+ * Copyright © 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ *
+ * ParavirtualizedGraphics.framework is a set of libraries that macOS provides
+ * which implements 3d graphics passthrough to the host as well as a
+ * proprietary guest communication channel to drive it. This device model
+ * implements support to drive that library from within QEMU as an MMIO-based
+ * system device for macOS on arm64 VMs.
+ */
+
+#include "qemu/osdep.h"
+#import <ParavirtualizedGraphics/ParavirtualizedGraphics.h>
+#include "apple-gfx.h"
+#include "monitor/monitor.h"
+#include "hw/sysbus.h"
+#include "hw/irq.h"
+#include "trace.h"
+#include "qemu/log.h"
+
+OBJECT_DECLARE_SIMPLE_TYPE(AppleGFXMMIOState, APPLE_GFX_MMIO)
+
+/*
+ * ParavirtualizedGraphics.Framework only ships header files for the PCI
+ * variant which does not include IOSFC descriptors and host devices. We add
+ * their definitions here so that we can also work with the ARM version.
+ */
+typedef bool(^IOSFCRaiseInterrupt)(uint32_t vector);
+typedef bool(^IOSFCUnmapMemory)(
+    void *, void *, void *, void *, void *, void *);
+typedef bool(^IOSFCMapMemory)(
+    uint64_t phys, uint64_t len, bool ro, void **va, void *, void *);
+
+@interface PGDeviceDescriptor (IOSurfaceMapper)
+@property (readwrite, nonatomic) bool usingIOSurfaceMapper;
+@end
+
+@interface PGIOSurfaceHostDeviceDescriptor : NSObject
+-(PGIOSurfaceHostDeviceDescriptor *)init;
+@property (readwrite, nonatomic, copy, nullable) IOSFCMapMemory mapMemory;
+@property (readwrite, nonatomic, copy, nullable) IOSFCUnmapMemory unmapMemory;
+@property (readwrite, nonatomic, copy, nullable) IOSFCRaiseInterrupt raiseInterrupt;
+@end
+
+@interface PGIOSurfaceHostDevice : NSObject
+-(instancetype)initWithDescriptor:(PGIOSurfaceHostDeviceDescriptor *)desc;
+-(uint32_t)mmioReadAtOffset:(size_t)offset;
+-(void)mmioWriteAtOffset:(size_t)offset value:(uint32_t)value;
+@end
+
+struct AppleGFXMapSurfaceMemoryJob;
+struct AppleGFXMMIOState {
+    SysBusDevice parent_obj;
+
+    AppleGFXState common;
+
+    qemu_irq irq_gfx;
+    qemu_irq irq_iosfc;
+    MemoryRegion iomem_iosfc;
+    PGIOSurfaceHostDevice *pgiosfc;
+};
+
+typedef struct AppleGFXMMIOJob {
+    AppleGFXMMIOState *state;
+    uint64_t offset;
+    uint64_t value;
+    bool completed;
+} AppleGFXMMIOJob;
+
+static void iosfc_do_read(void *opaque)
+{
+    AppleGFXMMIOJob *job = opaque;
+    job->value = [job->state->pgiosfc mmioReadAtOffset:job->offset];
+    qatomic_set(&job->completed, true);
+    aio_wait_kick();
+}
+
+static uint64_t iosfc_read(void *opaque, hwaddr offset, unsigned size)
+{
+    AppleGFXMMIOJob job = {
+        .state = opaque,
+        .offset = offset,
+        .completed = false,
+    };
+    dispatch_queue_t queue =
+        dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
+
+    dispatch_async_f(queue, &job, iosfc_do_read);
+    AIO_WAIT_WHILE(NULL, !qatomic_read(&job.completed));
+
+    trace_apple_gfx_mmio_iosfc_read(offset, job.value);
+    return job.value;
+}
+
+static void iosfc_do_write(void *opaque)
+{
+    AppleGFXMMIOJob *job = opaque;
+    [job->state->pgiosfc mmioWriteAtOffset:job->offset value:job->value];
+    qatomic_set(&job->completed, true);
+    aio_wait_kick();
+}
+
+static void iosfc_write(void *opaque, hwaddr offset, uint64_t val,
+                        unsigned size)
+{
+    AppleGFXMMIOJob job = {
+        .state = opaque,
+        .offset = offset,
+        .value = val,
+        .completed = false,
+    };
+    dispatch_queue_t queue =
+        dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
+
+    dispatch_async_f(queue, &job, iosfc_do_write);
+    AIO_WAIT_WHILE(NULL, !qatomic_read(&job.completed));
+
+    trace_apple_gfx_mmio_iosfc_write(offset, val);
+}
+
+static const MemoryRegionOps apple_iosfc_ops = {
+    .read = iosfc_read,
+    .write = iosfc_write,
+    .endianness = DEVICE_LITTLE_ENDIAN,
+    .valid = {
+        .min_access_size = 4,
+        .max_access_size = 8,
+    },
+    .impl = {
+        .min_access_size = 4,
+        .max_access_size = 8,
+    },
+};
+
+static void raise_irq_bh(void *opaque)
+{
+    qemu_irq *irq = opaque;
+
+    qemu_irq_pulse(*irq);
+}
+
+static void *apple_gfx_mmio_map_surface_memory(uint64_t guest_physical_address,
+                                               uint64_t length, bool read_only)
+{
+    void *mem;
+    MemoryRegion *region = NULL;
+
+    RCU_READ_LOCK_GUARD();
+    mem = apple_gfx_host_ptr_for_gpa_range(guest_physical_address,
+                                           length, read_only, &region);
+    if (mem) {
+        memory_region_ref(region);
+    }
+    return mem;
+}
+
+static bool apple_gfx_mmio_unmap_surface_memory(void *ptr)
+{
+    MemoryRegion *region;
+    ram_addr_t offset = 0;
+
+    RCU_READ_LOCK_GUARD();
+    region = memory_region_from_host(ptr, &offset);
+    if (!region) {
+        qemu_log_mask(LOG_GUEST_ERROR, "%s: memory at %p to be unmapped not "
+                      "found.\n",
+                      __func__, ptr);
+        return false;
+    }
+
+    trace_apple_gfx_iosfc_unmap_memory_region(ptr, region);
+    memory_region_unref(region);
+    return true;
+}
+
+static PGIOSurfaceHostDevice *apple_gfx_prepare_iosurface_host_device(
+    AppleGFXMMIOState *s)
+{
+    PGIOSurfaceHostDeviceDescriptor *iosfc_desc =
+        [PGIOSurfaceHostDeviceDescriptor new];
+    PGIOSurfaceHostDevice *iosfc_host_dev = nil;
+
+    iosfc_desc.mapMemory =
+        ^bool(uint64_t phys, uint64_t len, bool ro, void **va, void *e, void *f) {
+            *va = apple_gfx_mmio_map_surface_memory(phys, len, ro);
+
+            trace_apple_gfx_iosfc_map_memory(phys, len, ro, va, e, f, *va);
+
+            return *va != NULL;
+        };
+
+    iosfc_desc.unmapMemory =
+        ^bool(void *va, void *b, void *c, void *d, void *e, void *f) {
+            return apple_gfx_mmio_unmap_surface_memory(va);
+        };
+
+    iosfc_desc.raiseInterrupt = ^bool(uint32_t vector) {
+        trace_apple_gfx_iosfc_raise_irq(vector);
+        aio_bh_schedule_oneshot(qemu_get_aio_context(),
+                                raise_irq_bh, &s->irq_iosfc);
+        return true;
+    };
+
+    iosfc_host_dev =
+        [[PGIOSurfaceHostDevice alloc] initWithDescriptor:iosfc_desc];
+    [iosfc_desc release];
+    return iosfc_host_dev;
+}
+
+static void apple_gfx_mmio_realize(DeviceState *dev, Error **errp)
+{
+    @autoreleasepool {
+        AppleGFXMMIOState *s = APPLE_GFX_MMIO(dev);
+        PGDeviceDescriptor *desc = [PGDeviceDescriptor new];
+
+        desc.raiseInterrupt = ^(uint32_t vector) {
+            trace_apple_gfx_raise_irq(vector);
+            aio_bh_schedule_oneshot(qemu_get_aio_context(),
+                                    raise_irq_bh, &s->irq_gfx);
+        };
+
+        desc.usingIOSurfaceMapper = true;
+        s->pgiosfc = apple_gfx_prepare_iosurface_host_device(s);
+
+        if (!apple_gfx_common_realize(&s->common, dev, desc, errp)) {
+            [s->pgiosfc release];
+            s->pgiosfc = nil;
+        }
+
+        [desc release];
+        desc = nil;
+    }
+}
+
+static void apple_gfx_mmio_init(Object *obj)
+{
+    AppleGFXMMIOState *s = APPLE_GFX_MMIO(obj);
+
+    apple_gfx_common_init(obj, &s->common, TYPE_APPLE_GFX_MMIO);
+
+    sysbus_init_mmio(SYS_BUS_DEVICE(s), &s->common.iomem_gfx);
+    memory_region_init_io(&s->iomem_iosfc, obj, &apple_iosfc_ops, s,
+                          TYPE_APPLE_GFX_MMIO, 0x10000);
+    sysbus_init_mmio(SYS_BUS_DEVICE(s), &s->iomem_iosfc);
+    sysbus_init_irq(SYS_BUS_DEVICE(s), &s->irq_gfx);
+    sysbus_init_irq(SYS_BUS_DEVICE(s), &s->irq_iosfc);
+}
+
+static void apple_gfx_mmio_reset(Object *obj, ResetType type)
+{
+    AppleGFXMMIOState *s = APPLE_GFX_MMIO(obj);
+    [s->common.pgdev reset];
+}
+
+
+static void apple_gfx_mmio_class_init(ObjectClass *klass, void *data)
+{
+    DeviceClass *dc = DEVICE_CLASS(klass);
+    ResettableClass *rc = RESETTABLE_CLASS(klass);
+
+    rc->phases.hold = apple_gfx_mmio_reset;
+    dc->hotpluggable = false;
+    dc->realize = apple_gfx_mmio_realize;
+}
+
+static TypeInfo apple_gfx_mmio_types[] = {
+    {
+        .name          = TYPE_APPLE_GFX_MMIO,
+        .parent        = TYPE_SYS_BUS_DEVICE,
+        .instance_size = sizeof(AppleGFXMMIOState),
+        .class_init    = apple_gfx_mmio_class_init,
+        .instance_init = apple_gfx_mmio_init,
+    }
+};
+DEFINE_TYPES(apple_gfx_mmio_types)
hw/display/apple-gfx.h new file +67 -0
new file mode 100644
index 00000000000..220276b7492
@@ -0,0 +1,67 @@
+/*
+ * Data structures and functions shared between variants of the macOS
+ * ParavirtualizedGraphics.framework based apple-gfx display adapter.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef QEMU_APPLE_GFX_H
+#define QEMU_APPLE_GFX_H
+
+#define TYPE_APPLE_GFX_MMIO         "apple-gfx-mmio"
+#define TYPE_APPLE_GFX_PCI          "apple-gfx-pci"
+
+#include "qemu/osdep.h"
+#include <dispatch/dispatch.h>
+#import <ParavirtualizedGraphics/ParavirtualizedGraphics.h>
+#include "qemu/typedefs.h"
+#include "exec/memory.h"
+#include "ui/surface.h"
+
+@class PGDeviceDescriptor;
+@protocol PGDevice;
+@protocol PGDisplay;
+@protocol MTLDevice;
+@protocol MTLTexture;
+@protocol MTLCommandQueue;
+
+typedef QTAILQ_HEAD(, PGTask_s) PGTaskList;
+
+typedef struct AppleGFXState {
+    /* Initialised on init/realize() */
+    MemoryRegion iomem_gfx;
+    id<PGDevice> pgdev;
+    id<PGDisplay> pgdisp;
+    QemuConsole *con;
+    id<MTLDevice> mtl;
+    id<MTLCommandQueue> mtl_queue;
+    dispatch_queue_t render_queue;
+
+    /* List `tasks` is protected by task_mutex */
+    QemuMutex task_mutex;
+    PGTaskList tasks;
+
+    /* Mutable state (BQL protected) */
+    QEMUCursor *cursor;
+    DisplaySurface *surface;
+    id<MTLTexture> texture;
+    int8_t pending_frames; /* # guest frames in the rendering pipeline */
+    bool gfx_update_requested; /* QEMU display system wants a new frame */
+    bool new_frame_ready; /* Guest has rendered a frame, ready to be used */
+    bool using_managed_texture_storage;
+    uint32_t rendering_frame_width;
+    uint32_t rendering_frame_height;
+
+    /* Mutable state (atomic) */
+    bool cursor_show;
+} AppleGFXState;
+
+void apple_gfx_common_init(Object *obj, AppleGFXState *s, const char* obj_name);
+bool apple_gfx_common_realize(AppleGFXState *s, DeviceState *dev,
+                              PGDeviceDescriptor *desc, Error **errp);
+void *apple_gfx_host_ptr_for_gpa_range(uint64_t guest_physical,
+                                       uint64_t length, bool read_only,
+                                       MemoryRegion **mapping_in_region);
+
+#endif
+
hw/display/apple-gfx.m new file +229 -0
new file mode 100644
index 00000000000..c3ea98424e1
@@ -0,0 +1,776 @@
+/*
+ * QEMU Apple ParavirtualizedGraphics.framework device
+ *
+ * Copyright © 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ *
+ * ParavirtualizedGraphics.framework is a set of libraries that macOS provides
+ * which implements 3d graphics passthrough to the host as well as a
+ * proprietary guest communication channel to drive it. This device model
+ * implements support to drive that library from within QEMU.
+ */
+
+#include "qemu/osdep.h"
+#import <ParavirtualizedGraphics/ParavirtualizedGraphics.h>
+#include <mach/mach_vm.h>
+#include "apple-gfx.h"
+#include "trace.h"
+#include "qemu-main.h"
+#include "exec/address-spaces.h"
+#include "migration/blocker.h"
+#include "monitor/monitor.h"
+#include "qemu/main-loop.h"
+#include "qemu/cutils.h"
+#include "qemu/log.h"
+#include "qapi/visitor.h"
+#include "qapi/error.h"
+#include "sysemu/dma.h"
+#include "ui/console.h"
+
+static const PGDisplayCoord_t apple_gfx_modes[] = {
+    { .x = 1440, .y = 1080 },
+    { .x = 1280, .y = 1024 },
+};
+
+/* ------ PGTask and task operations: new/destroy/map/unmap ------ */
+
+/*
+ * This implements the type declared in <ParavirtualizedGraphics/PGDevice.h>
+ * which is opaque from the framework's point of view. It is used in callbacks
+ * in the form of its typedef PGTask_t, which also already exists in the
+ * framework headers.
+ *
+ * A "task" in PVG terminology represents a host-virtual contiguous address
+ * range which is reserved in a large chunk on task creation. The mapMemory
+ * callback then requests ranges of guest system memory (identified by their
+ * GPA) to be mapped into subranges of this reserved address space.
+ * This type of operation isn't well-supported by QEMU's memory subsystem,
+ * but it is fortunately trivial to achieve with Darwin's mach_vm_remap() call,
+ * which allows us to refer to the same backing memory via multiple virtual
+ * address ranges. The Mach VM APIs are therefore used throughout for managing
+ * task memory.
+ */
+struct PGTask_s {
+    QTAILQ_ENTRY(PGTask_s) node;
+    AppleGFXState *s;
+    mach_vm_address_t address;
+    uint64_t len;
+    /*
+     * All unique MemoryRegions for which a mapping has been created in in this
+     * task, and on which we have thus called memory_region_ref(). There are
+     * usually very few regions of system RAM in total, so we expect this array
+     * to be very short. Therefore, no need for sorting or fancy search
+     * algorithms, linear search will do.
+     * Protected by AppleGFXState's task_mutex.
+     */
+    GPtrArray *mapped_regions;
+};
+
+static Error *apple_gfx_mig_blocker;
+
+static PGTask_t *apple_gfx_new_task(AppleGFXState *s, uint64_t len)
+{
+    mach_vm_address_t task_mem;
+    PGTask_t *task;
+    kern_return_t r;
+
+    r = mach_vm_allocate(mach_task_self(), &task_mem, len, VM_FLAGS_ANYWHERE);
+    if (r != KERN_SUCCESS) {
+        return NULL;
+    }
+
+    task = g_new0(PGTask_t, 1);
+    task->s = s;
+    task->address = task_mem;
+    task->len = len;
+    task->mapped_regions = g_ptr_array_sized_new(2 /* Usually enough */);
+
+    QEMU_LOCK_GUARD(&s->task_mutex);
+    QTAILQ_INSERT_TAIL(&s->tasks, task, node);
+
+    return task;
+}
+
+static void apple_gfx_destroy_task(AppleGFXState *s, PGTask_t *task)
+{
+    GPtrArray *regions = task->mapped_regions;
+    MemoryRegion *region;
+    size_t i;
+
+    for (i = 0; i < regions->len; ++i) {
+        region = g_ptr_array_index(regions, i);
+        memory_region_unref(region);
+    }
+    g_ptr_array_unref(regions);
+
+    mach_vm_deallocate(mach_task_self(), task->address, task->len);
+
+    QEMU_LOCK_GUARD(&s->task_mutex);
+    QTAILQ_REMOVE(&s->tasks, task, node);
+    g_free(task);
+}
+
+void *apple_gfx_host_ptr_for_gpa_range(uint64_t guest_physical,
+                                       uint64_t length, bool read_only,
+                                       MemoryRegion **mapping_in_region)
+{
+    MemoryRegion *ram_region;
+    char *host_ptr;
+    hwaddr ram_region_offset = 0;
+    hwaddr ram_region_length = length;
+
+    ram_region = address_space_translate(&address_space_memory,
+                                         guest_physical,
+                                         &ram_region_offset,
+                                         &ram_region_length, !read_only,
+                                         MEMTXATTRS_UNSPECIFIED);
+
+    if (!ram_region || ram_region_length < length ||
+        !memory_access_is_direct(ram_region, !read_only)) {
+        return NULL;
+    }
+
+    host_ptr = memory_region_get_ram_ptr(ram_region);
+    if (!host_ptr) {
+        return NULL;
+    }
+    host_ptr += ram_region_offset;
+    *mapping_in_region = ram_region;
+    return host_ptr;
+}
+
+static bool apple_gfx_task_map_memory(AppleGFXState *s, PGTask_t *task,
+                                      uint64_t virtual_offset,
+                                      PGPhysicalMemoryRange_t *ranges,
+                                      uint32_t range_count, bool read_only)
+{
+    kern_return_t r;
+    void *source_ptr;
+    mach_vm_address_t target;
+    vm_prot_t cur_protection, max_protection;
+    bool success = true;
+    MemoryRegion *region;
+
+    RCU_READ_LOCK_GUARD();
+    QEMU_LOCK_GUARD(&s->task_mutex);
+
+    trace_apple_gfx_map_memory(task, range_count, virtual_offset, read_only);
+    for (int i = 0; i < range_count; i++) {
+        PGPhysicalMemoryRange_t *range = &ranges[i];
+
+        target = task->address + virtual_offset;
+        virtual_offset += range->physicalLength;
+
+        trace_apple_gfx_map_memory_range(i, range->physicalAddress,
+                                         range->physicalLength);
+
+        region = NULL;
+        source_ptr = apple_gfx_host_ptr_for_gpa_range(range->physicalAddress,
+                                                      range->physicalLength,
+                                                      read_only, &region);
+        if (!source_ptr) {
+            success = false;
+            continue;
+        }
+
+        if (!g_ptr_array_find(task->mapped_regions, region, NULL)) {
+            g_ptr_array_add(task->mapped_regions, region);
+            memory_region_ref(region);
+        }
+
+        cur_protection = 0;
+        max_protection = 0;
+        /* Map guest RAM at range->physicalAddress into PG task memory range */
+        r = mach_vm_remap(mach_task_self(),
+                          &target, range->physicalLength, vm_page_size - 1,
+                          VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE,
+                          mach_task_self(), (mach_vm_address_t)source_ptr,
+                          false /* shared mapping, no copy */,
+                          &cur_protection, &max_protection,
+                          VM_INHERIT_COPY);
+        trace_apple_gfx_remap(r, source_ptr, target);
+        g_assert(r == KERN_SUCCESS);
+    }
+
+    return success;
+}
+
+static void apple_gfx_task_unmap_memory(AppleGFXState *s, PGTask_t *task,
+                                        uint64_t virtual_offset, uint64_t length)
+{
+    kern_return_t r;
+    mach_vm_address_t range_address;
+
+    trace_apple_gfx_unmap_memory(task, virtual_offset, length);
+
+    /*
+     * Replace task memory range with fresh 0 pages, undoing the mapping
+     * from guest RAM.
+     */
+    range_address = task->address + virtual_offset;
+    r = mach_vm_allocate(mach_task_self(), &range_address, length,
+                         VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE);
+    g_assert(r == KERN_SUCCESS);
+}
+
+/* ------ Rendering and frame management ------ */
+
+static void apple_gfx_render_frame_completed_bh(void *opaque);
+
+static void apple_gfx_render_new_frame(AppleGFXState *s)
+{
+    bool managed_texture = s->using_managed_texture_storage;
+    uint32_t width = surface_width(s->surface);
+    uint32_t height = surface_height(s->surface);
+    MTLRegion region = MTLRegionMake2D(0, 0, width, height);

hw/display/apple-gfx.m line 239

Quoted 10 lines
hw/display/apple-gfx.m new file +10 -0
+    id<MTLCommandBuffer> command_buffer = [s->mtl_queue commandBuffer];
+    id<MTLTexture> texture = s->texture;
+
+    assert(bql_locked());
+    [texture retain];
+
+    s->rendering_frame_width = width;
+    s->rendering_frame_height = height;
+
+    dispatch_async(s->render_queue, ^{

s->render_queue should no longer be necessary.

hw/display/apple-gfx.m line 250

Quoted 11 lines
hw/display/apple-gfx.m new file +11 -0
+        /*
+         * This is not safe to call from the BQL due to PVG-internal locks
+         * causing deadlocks.
+         */
+        bool r = [s->pgdisp encodeCurrentFrameToCommandBuffer:command_buffer
+                                                 texture:texture
+                                                  region:region];
+        if (!r) {
+            [texture release];
+            bql_lock();
+            --s->pending_frames;

I think you need to copy the following code from apple_gfx_render_frame_completed_bh() here:

    if (s->pending_frames > 0) {
        apple_gfx_render_new_frame(s);
    }
Quoted 474 lines
hw/display/apple-gfx.m new file +474 -0
+            bql_unlock();
+            qemu_log_mask(LOG_GUEST_ERROR,
+                          "%s: encodeCurrentFrameToCommandBuffer:texture:region: "
+                          "failed\n", __func__);
+            return;
+        }
+
+        if (managed_texture) {
+            /* "Managed" textures exist in both VRAM and RAM and must be synced. */
+            id<MTLBlitCommandEncoder> blit = [command_buffer blitCommandEncoder];
+            [blit synchronizeResource:texture];
+            [blit endEncoding];
+        }
+        [texture release];
+        [command_buffer addCompletedHandler:
+            ^(id<MTLCommandBuffer> cb)
+            {
+                aio_bh_schedule_oneshot(qemu_get_aio_context(),
+                                        apple_gfx_render_frame_completed_bh, s);
+
+            }];
+        [command_buffer commit];
+    });
+}
+
+static void copy_mtl_texture_to_surface_mem(id<MTLTexture> texture, void *vram)
+{
+    /*
+     * TODO: Skip this entirely on a pure Metal or headless/guest-only
+     * rendering path, else use a blit command encoder? Needs careful
+     * (double?) buffering design.
+     */
+    size_t width = texture.width, height = texture.height;
+    MTLRegion region = MTLRegionMake2D(0, 0, width, height);
+    [texture getBytes:vram
+          bytesPerRow:(width * 4)
+        bytesPerImage:(width * height * 4)
+           fromRegion:region
+          mipmapLevel:0
+                slice:0];
+}
+
+static void apple_gfx_render_frame_completed_bh(void *opaque)
+{
+    AppleGFXState *s = opaque;
+
+    --s->pending_frames;
+    assert(s->pending_frames >= 0);
+
+    /* Only update display if mode hasn't changed since we started rendering. */
+    if (s->rendering_frame_width == surface_width(s->surface) &&
+        s->rendering_frame_height == surface_height(s->surface)) {
+        copy_mtl_texture_to_surface_mem(s->texture, surface_data(s->surface));
+        if (s->gfx_update_requested) {
+            s->gfx_update_requested = false;
+            dpy_gfx_update_full(s->con);
+            graphic_hw_update_done(s->con);
+            s->new_frame_ready = false;
+        } else {
+            s->new_frame_ready = true;
+        }
+    }
+    if (s->pending_frames > 0) {
+        apple_gfx_render_new_frame(s);
+    }
+}
+
+static void apple_gfx_fb_update_display(void *opaque)
+{
+    AppleGFXState *s = opaque;
+
+    assert(bql_locked());
+    if (s->new_frame_ready) {
+        dpy_gfx_update_full(s->con);
+        s->new_frame_ready = false;
+        graphic_hw_update_done(s->con);
+    } else if (s->pending_frames > 0) {
+        s->gfx_update_requested = true;
+    } else {
+        graphic_hw_update_done(s->con);
+    }
+}
+
+static const GraphicHwOps apple_gfx_fb_ops = {
+    .gfx_update = apple_gfx_fb_update_display,
+    .gfx_update_async = true,
+};
+
+/* ------ Mouse cursor and display mode setting ------ */
+
+static void set_mode(AppleGFXState *s, uint32_t width, uint32_t height)
+{
+    MTLTextureDescriptor *textureDescriptor;
+
+    if (s->surface &&
+        width == surface_width(s->surface) &&
+        height == surface_height(s->surface)) {
+        return;
+    }
+
+    [s->texture release];
+
+    s->surface = qemu_create_displaysurface(width, height);
+
+    @autoreleasepool {
+        textureDescriptor =
+            [MTLTextureDescriptor
+                texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
+                                             width:width
+                                            height:height
+                                         mipmapped:NO];
+        textureDescriptor.usage = s->pgdisp.minimumTextureUsage;
+        s->texture = [s->mtl newTextureWithDescriptor:textureDescriptor];
+    }
+
+    s->using_managed_texture_storage =
+        (s->texture.storageMode == MTLStorageModeManaged);
+    dpy_gfx_replace_surface(s->con, s->surface);
+}
+
+static void update_cursor(AppleGFXState *s)
+{
+    assert(bql_locked());
+    dpy_mouse_set(s->con, s->pgdisp.cursorPosition.x,
+                  s->pgdisp.cursorPosition.y, qatomic_read(&s->cursor_show));
+}
+
+static void update_cursor_bh(void *opaque)
+{
+    AppleGFXState *s = opaque;
+    update_cursor(s);
+}
+
+typedef struct AppleGFXSetCursorGlyphJob {
+    AppleGFXState *s;
+    NSBitmapImageRep *glyph;
+    PGDisplayCoord_t hotspot;
+} AppleGFXSetCursorGlyphJob;
+
+static void set_cursor_glyph(void *opaque)
+{
+    AppleGFXSetCursorGlyphJob *job = opaque;
+    AppleGFXState *s = job->s;
+    NSBitmapImageRep *glyph = job->glyph;
+    uint32_t bpp = glyph.bitsPerPixel;
+    size_t width = glyph.pixelsWide;
+    size_t height = glyph.pixelsHigh;
+    size_t padding_bytes_per_row = glyph.bytesPerRow - width * 4;
+    const uint8_t* px_data = glyph.bitmapData;
+
+    trace_apple_gfx_cursor_set(bpp, width, height);
+
+    if (s->cursor) {
+        cursor_unref(s->cursor);
+        s->cursor = NULL;
+    }
+
+    if (bpp == 32) { /* Shouldn't be anything else, but just to be safe...*/
+        s->cursor = cursor_alloc(width, height);
+        s->cursor->hot_x = job->hotspot.x;
+        s->cursor->hot_y = job->hotspot.y;
+
+        uint32_t *dest_px = s->cursor->data;
+
+        for (size_t y = 0; y < height; ++y) {
+            for (size_t x = 0; x < width; ++x) {
+                /*
+                 * NSBitmapImageRep's red & blue channels are swapped
+                 * compared to QEMUCursor's.
+                 */
+                *dest_px =
+                    (px_data[0] << 16u) |
+                    (px_data[1] <<  8u) |
+                    (px_data[2] <<  0u) |
+                    (px_data[3] << 24u);
+                ++dest_px;
+                px_data += 4;
+            }
+            px_data += padding_bytes_per_row;
+        }
+        dpy_cursor_define(s->con, s->cursor);
+        update_cursor(s);
+    }
+    [glyph release];
+
+    g_free(job);
+}
+
+/* ------ DMA (device reading system memory) ------ */
+
+typedef struct AppleGFXReadMemoryJob {
+    QemuSemaphore sem;
+    hwaddr physical_address;
+    uint64_t length;
+    void *dst;
+    bool success;
+} AppleGFXReadMemoryJob;
+
+static void apple_gfx_do_read_memory(void *opaque)
+{
+    AppleGFXReadMemoryJob *job = opaque;
+    MemTxResult r;
+
+    r = dma_memory_read(&address_space_memory, job->physical_address,
+                        job->dst, job->length, MEMTXATTRS_UNSPECIFIED);
+    job->success = r == MEMTX_OK;
+
+    qemu_sem_post(&job->sem);
+}
+
+static bool apple_gfx_read_memory(AppleGFXState *s, hwaddr physical_address,
+                                  uint64_t length, void *dst)
+{
+    AppleGFXReadMemoryJob job = {
+        .physical_address = physical_address, .length = length, .dst = dst
+    };
+
+    trace_apple_gfx_read_memory(physical_address, length, dst);
+
+    /* Performing DMA requires BQL, so do it in a BH. */
+    qemu_sem_init(&job.sem, 0);
+    aio_bh_schedule_oneshot(qemu_get_aio_context(),
+                            apple_gfx_do_read_memory, &job);
+    qemu_sem_wait(&job.sem);
+    qemu_sem_destroy(&job.sem);
+    return job.success;
+}
+
+/* ------ Memory-mapped device I/O operations ------ */
+
+static dispatch_queue_t get_background_queue(void)
+{
+    return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
+}
+
+typedef struct AppleGFXIOJob {
+    AppleGFXState *state;
+    uint64_t offset;
+    uint64_t value;
+    bool completed;
+} AppleGFXIOJob;
+
+static void apple_gfx_do_read(void *opaque)
+{
+    AppleGFXIOJob *job = opaque;
+    job->value = [job->state->pgdev mmioReadAtOffset:job->offset];
+    qatomic_set(&job->completed, true);
+    aio_wait_kick();
+}
+
+static uint64_t apple_gfx_read(void *opaque, hwaddr offset, unsigned size)
+{
+    AppleGFXIOJob job = {
+        .state = opaque,
+        .offset = offset,
+        .completed = false,
+    };
+    dispatch_queue_t queue = get_background_queue();
+
+    dispatch_async_f(queue, &job, apple_gfx_do_read);
+    AIO_WAIT_WHILE(NULL, !qatomic_read(&job.completed));
+
+    trace_apple_gfx_read(offset, job.value);
+    return job.value;
+}
+
+static void apple_gfx_do_write(void *opaque)
+{
+    AppleGFXIOJob *job = opaque;
+    [job->state->pgdev mmioWriteAtOffset:job->offset value:job->value];
+    qatomic_set(&job->completed, true);
+    aio_wait_kick();
+}
+
+static void apple_gfx_write(void *opaque, hwaddr offset, uint64_t val,
+                            unsigned size)
+{
+    /*
+     * The methods mmioReadAtOffset: and especially mmioWriteAtOffset: can
+     * trigger synchronous operations on other dispatch queues, which in turn
+     * may call back out on one or more of the callback blocks. For this reason,
+     * and as we are holding the BQL, we invoke the I/O methods on a pool
+     * thread and handle AIO tasks while we wait. Any work in the callbacks
+     * requiring the BQL will in turn schedule BHs which this thread will
+     * process while waiting.
+     */
+    AppleGFXIOJob job = {
+        .state = opaque,
+        .offset = offset,
+        .value = val,
+        .completed = false,
+    };
+    dispatch_queue_t queue = get_background_queue();
+
+    dispatch_async_f(queue, &job, apple_gfx_do_write);
+    AIO_WAIT_WHILE(NULL, !qatomic_read(&job.completed));
+
+    trace_apple_gfx_write(offset, val);
+}
+
+static const MemoryRegionOps apple_gfx_ops = {
+    .read = apple_gfx_read,
+    .write = apple_gfx_write,
+    .endianness = DEVICE_LITTLE_ENDIAN,
+    .valid = {
+        .min_access_size = 4,
+        .max_access_size = 8,
+    },
+    .impl = {
+        .min_access_size = 4,
+        .max_access_size = 4,
+    },
+};
+
+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;
+}
+
+/* ------ Initialisation and startup ------ */
+
+void apple_gfx_common_init(Object *obj, AppleGFXState *s, const char* obj_name)
+{
+    size_t mmio_range_size = apple_gfx_get_default_mmio_range_size();
+
+    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! */
+}
+
+static void apple_gfx_register_task_mapping_handlers(AppleGFXState *s,
+                                                     PGDeviceDescriptor *desc)
+{
+    desc.createTask = ^(uint64_t vmSize, void * _Nullable * _Nonnull baseAddress) {
+        PGTask_t *task = apple_gfx_new_task(s, vmSize);
+        *baseAddress = (void *)task->address;
+        trace_apple_gfx_create_task(vmSize, *baseAddress);
+        return task;
+    };
+
+    desc.destroyTask = ^(PGTask_t * _Nonnull task) {
+        trace_apple_gfx_destroy_task(task, task->mapped_regions->len);
+
+        apple_gfx_destroy_task(s, task);
+    };
+
+    desc.mapMemory = ^bool(PGTask_t * _Nonnull task, uint32_t range_count,
+                           uint64_t virtual_offset, bool read_only,
+                           PGPhysicalMemoryRange_t * _Nonnull ranges) {
+        return apple_gfx_task_map_memory(s, task, virtual_offset,
+                                         ranges, range_count, read_only);
+    };
+
+    desc.unmapMemory = ^bool(PGTask_t * _Nonnull task, uint64_t virtual_offset,
+                             uint64_t length) {
+        apple_gfx_task_unmap_memory(s, task, virtual_offset, length);
+        return true;
+    };
+
+    desc.readMemory = ^bool(uint64_t physical_address, uint64_t length,
+                            void * _Nonnull dst) {
+        return apple_gfx_read_memory(s, physical_address, length, dst);
+    };
+}
+
+static void new_frame_handler_bh(void *opaque)
+{
+    AppleGFXState *s = opaque;
+
+    /* Drop frames if we get too far ahead. */
+    if (s->pending_frames >= 2) {
+        return;
+    }
+    ++s->pending_frames;
+    if (s->pending_frames > 1) {
+        return;
+    }
+    apple_gfx_render_new_frame(s);
+}
+
+static PGDisplayDescriptor *apple_gfx_prepare_display_descriptor(AppleGFXState *s)
+{
+    PGDisplayDescriptor *disp_desc = [PGDisplayDescriptor new];
+
+    disp_desc.name = @"QEMU display";
+    disp_desc.sizeInMillimeters = NSMakeSize(400., 300.); /* A 20" display */
+    disp_desc.queue = dispatch_get_main_queue();
+    disp_desc.newFrameEventHandler = ^(void) {
+        trace_apple_gfx_new_frame();
+        aio_bh_schedule_oneshot(qemu_get_aio_context(), new_frame_handler_bh, s);
+    };
+    disp_desc.modeChangeHandler = ^(PGDisplayCoord_t sizeInPixels,
+                                    OSType pixelFormat) {
+        trace_apple_gfx_mode_change(sizeInPixels.x, sizeInPixels.y);
+
+        BQL_LOCK_GUARD();
+        set_mode(s, sizeInPixels.x, sizeInPixels.y);
+    };
+    disp_desc.cursorGlyphHandler = ^(NSBitmapImageRep *glyph,
+                                     PGDisplayCoord_t hotspot) {
+        AppleGFXSetCursorGlyphJob *job = g_malloc0(sizeof(*job));
+        job->s = s;
+        job->glyph = glyph;
+        job->hotspot = hotspot;
+        [glyph retain];
+        aio_bh_schedule_oneshot(qemu_get_aio_context(),
+                                set_cursor_glyph, job);
+    };
+    disp_desc.cursorShowHandler = ^(BOOL show) {
+        trace_apple_gfx_cursor_show(show);
+        qatomic_set(&s->cursor_show, show);
+        aio_bh_schedule_oneshot(qemu_get_aio_context(),
+                                update_cursor_bh, s);
+    };
+    disp_desc.cursorMoveHandler = ^(void) {
+        trace_apple_gfx_cursor_move();
+        aio_bh_schedule_oneshot(qemu_get_aio_context(),
+                                update_cursor_bh, s);
+    };
+
+    return disp_desc;
+}
+
+static NSArray<PGDisplayMode*>* apple_gfx_prepare_display_mode_array(void)
+{
+    PGDisplayMode *modes[ARRAY_SIZE(apple_gfx_modes)];
+    NSArray<PGDisplayMode*>* mode_array;
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(apple_gfx_modes); i++) {
+        modes[i] =
+            [[PGDisplayMode alloc] initWithSizeInPixels:apple_gfx_modes[i] refreshRateInHz:60.];
+    }
+
+    mode_array = [NSArray arrayWithObjects:modes count:ARRAY_SIZE(apple_gfx_modes)];
+
+    for (i = 0; i < ARRAY_SIZE(apple_gfx_modes); i++) {
+        [modes[i] release];
+        modes[i] = nil;
+    }
+
+    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];

hw/display/apple-gfx.m line 734

Quoted 10 lines
hw/display/apple-gfx.m new file +10 -0
+
+    return dev;
+}
+
+static uint32_t next_pgdisplay_serial_num = 1;
+
+bool apple_gfx_common_realize(AppleGFXState *s, DeviceState *dev,
+                              PGDeviceDescriptor *desc, Error **errp)
+{
+    PGDisplayDescriptor *disp_desc = nil;

Omit the nil initialization here.

Quoted 117 lines
hw/display/apple-gfx.m new file +42 -0
+
+    if (apple_gfx_mig_blocker == NULL) {
+        error_setg(&apple_gfx_mig_blocker,
+                  "Migration state blocked by apple-gfx display device");
+        if (migrate_add_blocker(&apple_gfx_mig_blocker, errp) < 0) {
+            return false;
+        }
+    }
+
+    qemu_mutex_init(&s->task_mutex);
+    QTAILQ_INIT(&s->tasks);
+    s->render_queue = dispatch_queue_create("apple-gfx.render",
+                                            DISPATCH_QUEUE_SERIAL);
+    s->mtl = copy_suitable_metal_device();
+    s->mtl_queue = [s->mtl newCommandQueue];
+
+    desc.device = s->mtl;
+
+    apple_gfx_register_task_mapping_handlers(s, desc);
+
+    s->cursor_show = true;
+
+    s->pgdev = PGNewDeviceWithDescriptor(desc);
+
+    disp_desc = apple_gfx_prepare_display_descriptor(s);
+    /*
+     * Although the framework does, this integration currently does not support
+     * multiple virtual displays connected to a single PV graphics device.
+     * It is however possible to create
+     * more than one instance of the device, each with one display. The macOS
+     * guest will ignore these displays if they share the same serial number,
+     * so ensure each instance gets a unique one.
+     */
+    s->pgdisp = [s->pgdev newDisplayWithDescriptor:disp_desc
+                                              port:0
+                                         serialNum:next_pgdisplay_serial_num++];
+    [disp_desc release];
+    s->pgdisp.modeList = apple_gfx_prepare_display_mode_array();
+
+    s->con = graphic_console_init(dev, 0, &apple_gfx_fb_ops, s);
+    return true;
+}
hw/display/meson.build +6 -0
index 20a94973fa2..cf9e6dd35d2 100644
@@ -61,6 +61,12 @@ 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])
 
+if host_os == 'darwin'
+  system_ss.add(when: 'CONFIG_MAC_PVG',         if_true: [files('apple-gfx.m'), pvg, metal])
+  if cpu == 'aarch64'
+    system_ss.add(when: 'CONFIG_MAC_PVG_MMIO',  if_true: [files('apple-gfx-mmio.m'), pvg, metal])
+  endif
+endif
 
  if config_all_devices.has_key('CONFIG_VIRTIO_GPU')
    virtio_gpu_ss = ss.source_set()
hw/display/trace-events +28 -0
index d26d663f963..a50e4eea0c0 100644
@@ -194,3 +194,31 @@ 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, unsigned int num_mapped_regions) "task=%p, task->mapped_regions->len=%u"
+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, void *source_ptr, uint64_t target) "retval=%"PRId64" source=%p 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_common_init(const char *device_name, size_t mmio_size) "device: %s; MMIO size: %zu bytes"
+
+# apple-gfx-mmio.m
+apple_gfx_mmio_iosfc_read(uint64_t offset, uint64_t res) "offset=0x%"PRIx64" res=0x%"PRIx64
+apple_gfx_mmio_iosfc_write(uint64_t offset, uint64_t val) "offset=0x%"PRIx64" val=0x%"PRIx64
+apple_gfx_iosfc_map_memory(uint64_t phys, uint64_t len, uint32_t ro, void *va, void *e, void *f, void* va_result) "phys=0x%"PRIx64" len=0x%"PRIx64" ro=%d va=%p e=%p f=%p -> *va=%p"
+apple_gfx_iosfc_map_memory_new_region(size_t i, void *region, uint64_t start, uint64_t end) "index=%zu, region=%p, 0x%"PRIx64"-0x%"PRIx64
+apple_gfx_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_gfx_iosfc_unmap_memory_region(void* mem, void *region) "unmapping @ %p from memory region %p"
+apple_gfx_iosfc_raise_irq(uint32_t vector) "vector=0x%x"
+
meson.build +4 -0
index e0b880e4e13..3c61238bc77 100644
@@ -794,6 +794,8 @@ socket = []
  version_res = []
  coref = []
  iokit = []
+pvg = not_found
+metal = []
  emulator_link_args = []
  midl = not_found
  widl = not_found
@@ -815,6 +817,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'),
#9 lore raw

Re: [PATCH v11 02/15] hw/display/apple-gfx: Introduce ParavirtualizedGraphics.Framework support

Quoted 861 lines · Akihiko Odaki
Quoted 23 lines · Phil Dennis-Jordan

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, API use updates.
* Moved from hw/vmapple/ (useful outside that machine type)
* Overhaul of threading model, many thread safety improvements.
* Asynchronous rendering.
* Memory and object lifetime fixes.
* Refactoring to split generic and (vmapple) MMIO variant specific code.

Quoted 1 line

Implementation wise, most of the complexity lies in the differing

threading

Quoted 2 lines

models of ParavirtualizedGraphics.framework, which uses libdispatch and internal locks, versus QEMU, which heavily uses the BQL, especially

during

Quoted 3 lines

memory-mapped device I/O. Great care has therefore been taken to prevent deadlocks by never calling into PVG methods while holding the BQL, and similarly never acquiring the BQL in a callback from PVG. Different

strategies

Quoted 2 lines

have been used (libdispatch, blocking and non-blocking BHs, RCU, etc.) depending on the specific requirements at each framework entry and exit

point.

Quoted 26 lines

---

v2:

* 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

Quoted 3 lines

v3:

* Rebased on latest upstream, fixed breakages including switching to

Resettable methods.

Quoted 2 lines

* Squashed patches dealing with dGPUs, MMIO area size, and GPU picking.
* Allow re-entrant MMIO; this simplifies the code and solves the

divergence

Quoted 8 lines

between x86-64 and arm64 variants.

v4:

* Renamed '-vmapple' device variant to '-mmio'
* MMIO device type now requires aarch64 host and guest
* Complete overhaul of the glue code for making Qemu's and ParavirtualizedGraphics.framework's threading and synchronisation

models

Quoted 2 lines

work together. Calls into PVG are from dispatch queues while the BQL-holding initiating thread processes AIO context events;

callbacks from

Quoted 1 line

PVG are scheduled as BHs on the BQL/main AIO context, awaiting

completion

Quoted 2 lines

where necessary.
* Guest frame rendering state is covered by the BQL, with only the PVG

calls

Quoted 2 lines

outside the lock, and serialised on the named render_queue.
* Simplified logic for dropping frames in-flight during mode changes,

fixed

Quoted 2 lines

bug in pending frames logic.
* Addressed smaller code review notes such as: function naming, object

type

Quoted 1 line

declarations, type names/declarations/casts, code formatting,

#include

Quoted 1 line

order, over-cautious ObjC retain/release, what goes in init vs

realize,

Quoted 5 lines

etc.

v5:

* Smaller non-functional fixes in response to review comments, such as

using

Quoted 2 lines

NULL for the AIO_WAIT_WHILE context argument, type name formatting, deleting leftover debug code, logging improvements, state struct

field

Quoted 2 lines

order and documentation improvements, etc.
* Instead of a single condition variable for all synchronous BH job

types,

Quoted 5 lines

there is now one for each callback block. This reduces the number of threads being awoken unnecessarily to near zero.
* MMIO device variant: Unified the BH job for raising interrupts.
* Use DMA APIs for PVG framework's guest memory read requests.
* Thread safety improvements: ensure mutable AppleGFXState fields are

not

Quoted 1 line

accessed outside the appropriate lock. Added dedicated mutex for the

task

Quoted 2 lines

list.
* Retain references to MemoryRegions for which there exist mappings in

each

Quoted 6 lines

PGTask, and for IOSurface mappings.

v6:

* Switched PGTask_s's' mapped_regions from GPtrArray to GArray
* Allow DisplaySurface to manage its own vram now that texture -> vram

copy

Quoted 2 lines

occurs under BQL.
* Memory mapping operations now use RCU_READ_LOCK_GUARD() where

possible

Quoted 2 lines

instead of a heavy-weight BH job to acquire the BQL.
* Changed PVG cursor and mode setting callbacks to kick off BHs

instead of

Quoted 2 lines

libdispatch tasks which then locked the BQL explicitly.
* The single remaining callback which must wait for a BH to complete

now

Quoted 2 lines

creates an ephemeral QemuSemaphore to await completion.
* Re-removed tracking of mapped surface manager memory regions. Just

look up

Quoted 2 lines

and ref/unref the memory regions in the map/unmap callbacks.
* Re-ordered functions in apple-gfx.m to group them by area of

functionality.

Quoted 11 lines

* Improved comments and tweaked some names.

v7:

* Use g_ptr_array_find() helper function
* Error handling coding style tweak

v8:

* Renamed apple_gfx_host_address_for_gpa_range() to apple_gfx_host_ptr_for_gpa_range(), and made it return a void*

instead of

Quoted 6 lines

uintptr_t. Fixed up callers and related code.
* Some adjustments to types used.
* Variable naming tweaks for better clarity.
* Fixed leak in unlikely realize error case.
* Fixed typo in unmap call.
* Don't bother with dummy argument for g_ptr_array_find(), NULL works

too.

Quoted 9 lines

v9:

* Pass device pointer to graphic_console_init().
* Slightly re-ordered initialisation code.
* Simplified error handling during realize().
* Simplified code without functional changes, adjusted code & comment formatting.

Quoted 3 lines

v10:

* Reworked the way frame rendering code is threaded to use BHs for

sections

Quoted 7 lines

requiring BQL.
* Fix for ./configure error on non-macOS platforms.
* Code formatting tweaks.

v11:

* Generate unique display serial number for each apple-gfx device

instance.

Quoted 37 lines

* Dropped redundant local variable initialisation.

  hw/display/Kconfig          |   9 +
  hw/display/apple-gfx-mmio.m | 281 +++++++++++++
  hw/display/apple-gfx.h      |  67 ++++
  hw/display/apple-gfx.m      | 776 ++++++++++++++++++++++++++++++++++++
  hw/display/meson.build      |   6 +
  hw/display/trace-events     |  28 ++
  meson.build                 |   4 +
  7 files changed, 1171 insertions(+)

create mode 100644 hw/display/apple-gfx-mmio.m
create mode 100644 hw/display/apple-gfx.h
create mode 100644 hw/display/apple-gfx.m

hw/display/Kconfig +9 -0
index 2250c740078..6a9b7b19ada 100644
@@ -140,3 +140,12 @@ config XLNX_DISPLAYPORT
 
  config DM163
      bool
+
+config MAC_PVG
+    bool
+    default y
+
+config MAC_PVG_MMIO
+    bool
+    depends on MAC_PVG && AARCH64
+
hw/display/apple-gfx-mmio.m new file +0 -0
new file mode 100644
index 00000000000..2d76e7375bd

hw/display/apple-gfx-mmio.m line 2

Quoted 2 lines
hw/display/apple-gfx-mmio.m new file +2 -0
@@ -0,0 +1,281 @@
+/*
+ * QEMU Apple ParavirtualizedGraphics.framework device, MMIO (arm64)

variant

hw/display/apple-gfx-mmio.m line 4

Quoted 2 lines
hw/display/apple-gfx-mmio.m new file +2 -0
+ *
+ * Copyright © 2023 Amazon.com, Inc. or its affiliates. All Rights

Reserved.

hw/display/apple-gfx-mmio.m line 6

Quoted 2 lines
hw/display/apple-gfx-mmio.m new file +2 -0
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or

later.

hw/display/apple-gfx-mmio.m

Quoted 5 lines
hw/display/apple-gfx-mmio.m new file +5 -0
+ * See the COPYING file in the top-level directory.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ *
+ * ParavirtualizedGraphics.framework is a set of libraries that macOS

provides

hw/display/apple-gfx-mmio.m line 13

Quoted 2 lines
hw/display/apple-gfx-mmio.m new file +2 -0
+ * which implements 3d graphics passthrough to the host as well as a
+ * proprietary guest communication channel to drive it. This device

model

hw/display/apple-gfx-mmio.m line 14

Quoted 1 line
hw/display/apple-gfx-mmio.m new file +1 -0
+ * implements support to drive that library from within QEMU as an

MMIO-based

Quoted 7 lines
hw/display/apple-gfx-mmio.m new file +7 -0
+ * system device for macOS on arm64 VMs.
+ */
+
+#include "qemu/osdep.h"
+#import <ParavirtualizedGraphics/ParavirtualizedGraphics.h>
+#include "apple-gfx.h"
+#include "monitor/monitor.h"

hw/display/apple-gfx-mmio.m

Quoted 10 lines
hw/display/apple-gfx-mmio.m new file +10 -0
+#include "hw/sysbus.h"
+#include "hw/irq.h"
+#include "trace.h"
+#include "qemu/log.h"
+
+OBJECT_DECLARE_SIMPLE_TYPE(AppleGFXMMIOState, APPLE_GFX_MMIO)
+
+/*
+ * ParavirtualizedGraphics.Framework only ships header files for the PCI
+ * variant which does not include IOSFC descriptors and host devices.

We add

Quoted 5 lines
hw/display/apple-gfx-mmio.m new file +5 -0
+ * their definitions here so that we can also work with the ARM version.
+ */
+typedef bool(^IOSFCRaiseInterrupt)(uint32_t vector);
+typedef bool(^IOSFCUnmapMemory)(
+    void *, void *, void *, void *, void *, void *);

hw/display/apple-gfx-mmio.m

Quoted 10 lines
hw/display/apple-gfx-mmio.m new file +10 -0
+typedef bool(^IOSFCMapMemory)(
+    uint64_t phys, uint64_t len, bool ro, void **va, void *, void *);
+
+@interface PGDeviceDescriptor (IOSurfaceMapper)
+@property (readwrite, nonatomic) bool usingIOSurfaceMapper;
+@end
+
+@interface PGIOSurfaceHostDeviceDescriptor : NSObject
+-(PGIOSurfaceHostDeviceDescriptor *)init;
+@property (readwrite, nonatomic, copy, nullable) IOSFCMapMemory

mapMemory;

hw/display/apple-gfx-mmio.m line 47

Quoted 1 line
hw/display/apple-gfx-mmio.m new file +1 -0
+@property (readwrite, nonatomic, copy, nullable) IOSFCUnmapMemory

unmapMemory;

hw/display/apple-gfx-mmio.m line 48

Quoted 1 line
hw/display/apple-gfx-mmio.m new file +1 -0
+@property (readwrite, nonatomic, copy, nullable) IOSFCRaiseInterrupt

raiseInterrupt;

hw/display/apple-gfx-mmio.m

Quoted 4 lines
hw/display/apple-gfx-mmio.m new file +4 -0
+@end
+
+@interface PGIOSurfaceHostDevice : NSObject
+-(instancetype)initWithDescriptor:(PGIOSurfaceHostDeviceDescriptor

*)desc;

Quoted 42 lines
hw/display/apple-gfx-mmio.m new file +42 -0
+-(uint32_t)mmioReadAtOffset:(size_t)offset;
+-(void)mmioWriteAtOffset:(size_t)offset value:(uint32_t)value;
+@end
+
+struct AppleGFXMapSurfaceMemoryJob;
+struct AppleGFXMMIOState {
+    SysBusDevice parent_obj;
+
+    AppleGFXState common;
+
+    qemu_irq irq_gfx;
+    qemu_irq irq_iosfc;
+    MemoryRegion iomem_iosfc;
+    PGIOSurfaceHostDevice *pgiosfc;
+};
+
+typedef struct AppleGFXMMIOJob {
+    AppleGFXMMIOState *state;
+    uint64_t offset;
+    uint64_t value;
+    bool completed;
+} AppleGFXMMIOJob;
+
+static void iosfc_do_read(void *opaque)
+{
+    AppleGFXMMIOJob *job = opaque;
+    job->value = [job->state->pgiosfc mmioReadAtOffset:job->offset];
+    qatomic_set(&job->completed, true);
+    aio_wait_kick();
+}
+
+static uint64_t iosfc_read(void *opaque, hwaddr offset, unsigned size)
+{
+    AppleGFXMMIOJob job = {
+        .state = opaque,
+        .offset = offset,
+        .completed = false,
+    };
+    dispatch_queue_t queue =
+        dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
+
+    dispatch_async_f(queue, &job, iosfc_do_read);

hw/display/apple-gfx-mmio.m

Quoted 10 lines
hw/display/apple-gfx-mmio.m new file +10 -0
+    AIO_WAIT_WHILE(NULL, !qatomic_read(&job.completed));
+
+    trace_apple_gfx_mmio_iosfc_read(offset, job.value);
+    return job.value;
+}
+
+static void iosfc_do_write(void *opaque)
+{
+    AppleGFXMMIOJob *job = opaque;
+    [job->state->pgiosfc mmioWriteAtOffset:job->offset

value:job->value];

Quoted 34 lines
hw/display/apple-gfx-mmio.m new file +34 -0
+    qatomic_set(&job->completed, true);
+    aio_wait_kick();
+}
+
+static void iosfc_write(void *opaque, hwaddr offset, uint64_t val,
+                        unsigned size)
+{
+    AppleGFXMMIOJob job = {
+        .state = opaque,
+        .offset = offset,
+        .value = val,
+        .completed = false,
+    };
+    dispatch_queue_t queue =
+        dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
+
+    dispatch_async_f(queue, &job, iosfc_do_write);
+    AIO_WAIT_WHILE(NULL, !qatomic_read(&job.completed));
+
+    trace_apple_gfx_mmio_iosfc_write(offset, val);
+}
+
+static const MemoryRegionOps apple_iosfc_ops = {
+    .read = iosfc_read,
+    .write = iosfc_write,
+    .endianness = DEVICE_LITTLE_ENDIAN,
+    .valid = {
+        .min_access_size = 4,
+        .max_access_size = 8,
+    },
+    .impl = {
+        .min_access_size = 4,
+        .max_access_size = 8,
+    },

hw/display/apple-gfx-mmio.m

Quoted 10 lines
hw/display/apple-gfx-mmio.m new file +10 -0
+};
+
+static void raise_irq_bh(void *opaque)
+{
+    qemu_irq *irq = opaque;
+
+    qemu_irq_pulse(*irq);
+}
+
+static void *apple_gfx_mmio_map_surface_memory(uint64_t

guest_physical_address,

hw/display/apple-gfx-mmio.m line 149

Quoted 1 line
hw/display/apple-gfx-mmio.m new file +1 -0
+                                               uint64_t length, bool

read_only)

Quoted 12 lines
hw/display/apple-gfx-mmio.m new file +12 -0
+{
+    void *mem;
+    MemoryRegion *region = NULL;
+
+    RCU_READ_LOCK_GUARD();
+    mem = apple_gfx_host_ptr_for_gpa_range(guest_physical_address,
+                                           length, read_only, &region);
+    if (mem) {
+        memory_region_ref(region);
+    }
+    return mem;
+}

hw/display/apple-gfx-mmio.m

Quoted 10 lines
hw/display/apple-gfx-mmio.m new file +10 -0
+
+static bool apple_gfx_mmio_unmap_surface_memory(void *ptr)
+{
+    MemoryRegion *region;
+    ram_addr_t offset = 0;
+
+    RCU_READ_LOCK_GUARD();
+    region = memory_region_from_host(ptr, &offset);
+    if (!region) {
+        qemu_log_mask(LOG_GUEST_ERROR, "%s: memory at %p to be unmapped

not "

Quoted 9 lines
hw/display/apple-gfx-mmio.m new file +9 -0
+                      "found.\n",
+                      __func__, ptr);
+        return false;
+    }
+
+    trace_apple_gfx_iosfc_unmap_memory_region(ptr, region);
+    memory_region_unref(region);
+    return true;
+}

hw/display/apple-gfx-mmio.m

Quoted 10 lines
hw/display/apple-gfx-mmio.m new file +10 -0
+
+static PGIOSurfaceHostDevice *apple_gfx_prepare_iosurface_host_device(
+    AppleGFXMMIOState *s)
+{
+    PGIOSurfaceHostDeviceDescriptor *iosfc_desc =
+        [PGIOSurfaceHostDeviceDescriptor new];
+    PGIOSurfaceHostDevice *iosfc_host_dev = nil;
+
+    iosfc_desc.mapMemory =
+        ^bool(uint64_t phys, uint64_t len, bool ro, void **va, void *e,

void *f) {

hw/display/apple-gfx-mmio.m

Quoted 3 lines
hw/display/apple-gfx-mmio.m new file +3 -0
+            *va = apple_gfx_mmio_map_surface_memory(phys, len, ro);
+
+            trace_apple_gfx_iosfc_map_memory(phys, len, ro, va, e, f,

*va);

Quoted 132 lines
hw/display/apple-gfx-mmio.m new file +88 -0
+
+            return *va != NULL;
+        };
+
+    iosfc_desc.unmapMemory =
+        ^bool(void *va, void *b, void *c, void *d, void *e, void *f) {
+            return apple_gfx_mmio_unmap_surface_memory(va);
+        };
+
+    iosfc_desc.raiseInterrupt = ^bool(uint32_t vector) {
+        trace_apple_gfx_iosfc_raise_irq(vector);
+        aio_bh_schedule_oneshot(qemu_get_aio_context(),
+                                raise_irq_bh, &s->irq_iosfc);
+        return true;
+    };
+
+    iosfc_host_dev =
+        [[PGIOSurfaceHostDevice alloc] initWithDescriptor:iosfc_desc];
+    [iosfc_desc release];
+    return iosfc_host_dev;
+}
+
+static void apple_gfx_mmio_realize(DeviceState *dev, Error **errp)
+{
+    @autoreleasepool {
+        AppleGFXMMIOState *s = APPLE_GFX_MMIO(dev);
+        PGDeviceDescriptor *desc = [PGDeviceDescriptor new];
+
+        desc.raiseInterrupt = ^(uint32_t vector) {
+            trace_apple_gfx_raise_irq(vector);
+            aio_bh_schedule_oneshot(qemu_get_aio_context(),
+                                    raise_irq_bh, &s->irq_gfx);
+        };
+
+        desc.usingIOSurfaceMapper = true;
+        s->pgiosfc = apple_gfx_prepare_iosurface_host_device(s);
+
+        if (!apple_gfx_common_realize(&s->common, dev, desc, errp)) {
+            [s->pgiosfc release];
+            s->pgiosfc = nil;
+        }
+
+        [desc release];
+        desc = nil;
+    }
+}
+
+static void apple_gfx_mmio_init(Object *obj)
+{
+    AppleGFXMMIOState *s = APPLE_GFX_MMIO(obj);
+
+    apple_gfx_common_init(obj, &s->common, TYPE_APPLE_GFX_MMIO);
+
+    sysbus_init_mmio(SYS_BUS_DEVICE(s), &s->common.iomem_gfx);
+    memory_region_init_io(&s->iomem_iosfc, obj, &apple_iosfc_ops, s,
+                          TYPE_APPLE_GFX_MMIO, 0x10000);
+    sysbus_init_mmio(SYS_BUS_DEVICE(s), &s->iomem_iosfc);
+    sysbus_init_irq(SYS_BUS_DEVICE(s), &s->irq_gfx);
+    sysbus_init_irq(SYS_BUS_DEVICE(s), &s->irq_iosfc);
+}
+
+static void apple_gfx_mmio_reset(Object *obj, ResetType type)
+{
+    AppleGFXMMIOState *s = APPLE_GFX_MMIO(obj);
+    [s->common.pgdev reset];
+}
+
+
+static void apple_gfx_mmio_class_init(ObjectClass *klass, void *data)
+{
+    DeviceClass *dc = DEVICE_CLASS(klass);
+    ResettableClass *rc = RESETTABLE_CLASS(klass);
+
+    rc->phases.hold = apple_gfx_mmio_reset;
+    dc->hotpluggable = false;
+    dc->realize = apple_gfx_mmio_realize;
+}
+
+static TypeInfo apple_gfx_mmio_types[] = {
+    {
+        .name          = TYPE_APPLE_GFX_MMIO,
+        .parent        = TYPE_SYS_BUS_DEVICE,
+        .instance_size = sizeof(AppleGFXMMIOState),
+        .class_init    = apple_gfx_mmio_class_init,
+        .instance_init = apple_gfx_mmio_init,
+    }
+};
+DEFINE_TYPES(apple_gfx_mmio_types)
hw/display/apple-gfx.h new file +38 -0
new file mode 100644
index 00000000000..220276b7492
@@ -0,0 +1,67 @@
+/*
+ * Data structures and functions shared between variants of the macOS
+ * ParavirtualizedGraphics.framework based apple-gfx display adapter.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef QEMU_APPLE_GFX_H
+#define QEMU_APPLE_GFX_H
+
+#define TYPE_APPLE_GFX_MMIO         "apple-gfx-mmio"
+#define TYPE_APPLE_GFX_PCI          "apple-gfx-pci"
+
+#include "qemu/osdep.h"
+#include <dispatch/dispatch.h>
+#import <ParavirtualizedGraphics/ParavirtualizedGraphics.h>
+#include "qemu/typedefs.h"
+#include "exec/memory.h"
+#include "ui/surface.h"
+
+@class PGDeviceDescriptor;
+@protocol PGDevice;
+@protocol PGDisplay;
+@protocol MTLDevice;
+@protocol MTLTexture;
+@protocol MTLCommandQueue;
+
+typedef QTAILQ_HEAD(, PGTask_s) PGTaskList;
+
+typedef struct AppleGFXState {
+    /* Initialised on init/realize() */
+    MemoryRegion iomem_gfx;
+    id<PGDevice> pgdev;
+    id<PGDisplay> pgdisp;
+    QemuConsole *con;
+    id<MTLDevice> mtl;
+    id<MTLCommandQueue> mtl_queue;
+    dispatch_queue_t render_queue;

hw/display/apple-gfx.h line 48

Quoted 10 lines
hw/display/apple-gfx.h new file +10 -0
+
+    /* List `tasks` is protected by task_mutex */
+    QemuMutex task_mutex;
+    PGTaskList tasks;
+
+    /* Mutable state (BQL protected) */
+    QEMUCursor *cursor;
+    DisplaySurface *surface;
+    id<MTLTexture> texture;
+    int8_t pending_frames; /* # guest frames in the rendering pipeline

*/

hw/display/apple-gfx.h line 49

Quoted 1 line
hw/display/apple-gfx.h new file +1 -0
+    bool gfx_update_requested; /* QEMU display system wants a new frame

*/

hw/display/apple-gfx.h line 50

Quoted 1 line
hw/display/apple-gfx.h new file +1 -0
+    bool new_frame_ready; /* Guest has rendered a frame, ready to be

used */

hw/display/apple-gfx.h

Quoted 9 lines
hw/display/apple-gfx.h new file +9 -0
+    bool using_managed_texture_storage;
+    uint32_t rendering_frame_width;
+    uint32_t rendering_frame_height;
+
+    /* Mutable state (atomic) */
+    bool cursor_show;
+} AppleGFXState;
+
+void apple_gfx_common_init(Object *obj, AppleGFXState *s, const char*

obj_name);

hw/display/apple-gfx.h

Quoted 5 lines
hw/display/apple-gfx.h new file +5 -0
+bool apple_gfx_common_realize(AppleGFXState *s, DeviceState *dev,
+                              PGDeviceDescriptor *desc, Error **errp);
+void *apple_gfx_host_ptr_for_gpa_range(uint64_t guest_physical,
+                                       uint64_t length, bool read_only,
+                                       MemoryRegion

**mapping_in_region);

hw/display/apple-gfx.m line 4

Quoted 13 lines
hw/display/apple-gfx.h new file +3 -0
+
+#endif
+
hw/display/apple-gfx.m new file +4 -0
new file mode 100644
index 00000000000..c3ea98424e1
@@ -0,0 +1,776 @@
+/*
+ * QEMU Apple ParavirtualizedGraphics.framework device
+ *
+ * Copyright © 2023 Amazon.com, Inc. or its affiliates. All Rights

Reserved.

hw/display/apple-gfx.m line 6

Quoted 2 lines
hw/display/apple-gfx.m new file +2 -0
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or

later.

hw/display/apple-gfx.m line 11

Quoted 5 lines
hw/display/apple-gfx.m new file +5 -0
+ * See the COPYING file in the top-level directory.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ *
+ * ParavirtualizedGraphics.framework is a set of libraries that macOS

provides

hw/display/apple-gfx.m line 13

Quoted 2 lines
hw/display/apple-gfx.m new file +2 -0
+ * which implements 3d graphics passthrough to the host as well as a
+ * proprietary guest communication channel to drive it. This device

model

Quoted 19 lines
hw/display/apple-gfx.m new file +19 -0
+ * implements support to drive that library from within QEMU.
+ */
+
+#include "qemu/osdep.h"
+#import <ParavirtualizedGraphics/ParavirtualizedGraphics.h>
+#include <mach/mach_vm.h>
+#include "apple-gfx.h"
+#include "trace.h"
+#include "qemu-main.h"
+#include "exec/address-spaces.h"
+#include "migration/blocker.h"
+#include "monitor/monitor.h"
+#include "qemu/main-loop.h"
+#include "qemu/cutils.h"
+#include "qemu/log.h"
+#include "qapi/visitor.h"
+#include "qapi/error.h"
+#include "sysemu/dma.h"
+#include "ui/console.h"

hw/display/apple-gfx.m

Quoted 10 lines
hw/display/apple-gfx.m new file +10 -0
+
+static const PGDisplayCoord_t apple_gfx_modes[] = {
+    { .x = 1440, .y = 1080 },
+    { .x = 1280, .y = 1024 },
+};
+
+/* ------ PGTask and task operations: new/destroy/map/unmap ------ */
+
+/*
+ * This implements the type declared in

<ParavirtualizedGraphics/PGDevice.h>

hw/display/apple-gfx.m line 43

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+ * which is opaque from the framework's point of view. It is used in

callbacks

hw/display/apple-gfx.m

Quoted 4 lines
hw/display/apple-gfx.m new file +4 -0
+ * in the form of its typedef PGTask_t, which also already exists in the
+ * framework headers.
+ *
+ * A "task" in PVG terminology represents a host-virtual contiguous

address

hw/display/apple-gfx.m line 48

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+ * range which is reserved in a large chunk on task creation. The

mapMemory

hw/display/apple-gfx.m line 49

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+ * callback then requests ranges of guest system memory (identified by

their

hw/display/apple-gfx.m line 51

Quoted 2 lines
hw/display/apple-gfx.m new file +2 -0
+ * GPA) to be mapped into subranges of this reserved address space.
+ * This type of operation isn't well-supported by QEMU's memory

subsystem,

hw/display/apple-gfx.m line 52

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+ * but it is fortunately trivial to achieve with Darwin's

mach_vm_remap() call,

hw/display/apple-gfx.m line 53

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+ * which allows us to refer to the same backing memory via multiple

virtual

hw/display/apple-gfx.m line 54

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+ * address ranges. The Mach VM APIs are therefore used throughout for

managing

hw/display/apple-gfx.m

Quoted 9 lines
hw/display/apple-gfx.m new file +9 -0
+ * task memory.
+ */
+struct PGTask_s {
+    QTAILQ_ENTRY(PGTask_s) node;
+    AppleGFXState *s;
+    mach_vm_address_t address;
+    uint64_t len;
+    /*
+     * All unique MemoryRegions for which a mapping has been created in

in this

hw/display/apple-gfx.m line 64

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+     * task, and on which we have thus called memory_region_ref().

There are

hw/display/apple-gfx.m line 65

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+     * usually very few regions of system RAM in total, so we expect

this array

Quoted 6 lines
hw/display/apple-gfx.m new file +6 -0
+     * to be very short. Therefore, no need for sorting or fancy search
+     * algorithms, linear search will do.
+     * Protected by AppleGFXState's task_mutex.
+     */
+    GPtrArray *mapped_regions;
+};

hw/display/apple-gfx.m

Quoted 10 lines
hw/display/apple-gfx.m new file +10 -0
+
+static Error *apple_gfx_mig_blocker;
+
+static PGTask_t *apple_gfx_new_task(AppleGFXState *s, uint64_t len)
+{
+    mach_vm_address_t task_mem;
+    PGTask_t *task;
+    kern_return_t r;
+
+    r = mach_vm_allocate(mach_task_self(), &task_mem, len,

VM_FLAGS_ANYWHERE);

hw/display/apple-gfx.m

Quoted 9 lines
hw/display/apple-gfx.m new file +9 -0
+    if (r != KERN_SUCCESS) {
+        return NULL;
+    }
+
+    task = g_new0(PGTask_t, 1);
+    task->s = s;
+    task->address = task_mem;
+    task->len = len;
+    task->mapped_regions = g_ptr_array_sized_new(2 /* Usually enough

*/);

Quoted 49 lines
hw/display/apple-gfx.m new file +49 -0
+
+    QEMU_LOCK_GUARD(&s->task_mutex);
+    QTAILQ_INSERT_TAIL(&s->tasks, task, node);
+
+    return task;
+}
+
+static void apple_gfx_destroy_task(AppleGFXState *s, PGTask_t *task)
+{
+    GPtrArray *regions = task->mapped_regions;
+    MemoryRegion *region;
+    size_t i;
+
+    for (i = 0; i < regions->len; ++i) {
+        region = g_ptr_array_index(regions, i);
+        memory_region_unref(region);
+    }
+    g_ptr_array_unref(regions);
+
+    mach_vm_deallocate(mach_task_self(), task->address, task->len);
+
+    QEMU_LOCK_GUARD(&s->task_mutex);
+    QTAILQ_REMOVE(&s->tasks, task, node);
+    g_free(task);
+}
+
+void *apple_gfx_host_ptr_for_gpa_range(uint64_t guest_physical,
+                                       uint64_t length, bool read_only,
+                                       MemoryRegion **mapping_in_region)
+{
+    MemoryRegion *ram_region;
+    char *host_ptr;
+    hwaddr ram_region_offset = 0;
+    hwaddr ram_region_length = length;
+
+    ram_region = address_space_translate(&address_space_memory,
+                                         guest_physical,
+                                         &ram_region_offset,
+                                         &ram_region_length, !read_only,
+                                         MEMTXATTRS_UNSPECIFIED);
+
+    if (!ram_region || ram_region_length < length ||
+        !memory_access_is_direct(ram_region, !read_only)) {
+        return NULL;
+    }
+
+    host_ptr = memory_region_get_ram_ptr(ram_region);
+    if (!host_ptr) {
+        return NULL;

hw/display/apple-gfx.m

Quoted 10 lines
hw/display/apple-gfx.m new file +10 -0
+    }
+    host_ptr += ram_region_offset;
+    *mapping_in_region = ram_region;
+    return host_ptr;
+}
+
+static bool apple_gfx_task_map_memory(AppleGFXState *s, PGTask_t *task,
+                                      uint64_t virtual_offset,
+                                      PGPhysicalMemoryRange_t *ranges,
+                                      uint32_t range_count, bool

read_only)

hw/display/apple-gfx.m

Quoted 12 lines
hw/display/apple-gfx.m new file +12 -0
+{
+    kern_return_t r;
+    void *source_ptr;
+    mach_vm_address_t target;
+    vm_prot_t cur_protection, max_protection;
+    bool success = true;
+    MemoryRegion *region;
+
+    RCU_READ_LOCK_GUARD();
+    QEMU_LOCK_GUARD(&s->task_mutex);
+
+    trace_apple_gfx_map_memory(task, range_count, virtual_offset,

read_only);

hw/display/apple-gfx.m

Quoted 11 lines
hw/display/apple-gfx.m new file +11 -0
+    for (int i = 0; i < range_count; i++) {
+        PGPhysicalMemoryRange_t *range = &ranges[i];
+
+        target = task->address + virtual_offset;
+        virtual_offset += range->physicalLength;
+
+        trace_apple_gfx_map_memory_range(i, range->physicalAddress,
+                                         range->physicalLength);
+
+        region = NULL;
+        source_ptr =

apple_gfx_host_ptr_for_gpa_range(range->physicalAddress,

hw/display/apple-gfx.m line 173

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+

range->physicalLength,

hw/display/apple-gfx.m line 174

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+                                                      read_only,

&region);

hw/display/apple-gfx.m

Quoted 13 lines
hw/display/apple-gfx.m new file +13 -0
+        if (!source_ptr) {
+            success = false;
+            continue;
+        }
+
+        if (!g_ptr_array_find(task->mapped_regions, region, NULL)) {
+            g_ptr_array_add(task->mapped_regions, region);
+            memory_region_ref(region);
+        }
+
+        cur_protection = 0;
+        max_protection = 0;
+        /* Map guest RAM at range->physicalAddress into PG task memory

range */

hw/display/apple-gfx.m line 189

Quoted 2 lines
hw/display/apple-gfx.m new file +2 -0
+        r = mach_vm_remap(mach_task_self(),
+                          &target, range->physicalLength, vm_page_size

- 1,

hw/display/apple-gfx.m line 191

Quoted 2 lines
hw/display/apple-gfx.m new file +2 -0
+                          VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE,
+                          mach_task_self(),

(mach_vm_address_t)source_ptr,

hw/display/apple-gfx.m

Quoted 11 lines
hw/display/apple-gfx.m new file +11 -0
+                          false /* shared mapping, no copy */,
+                          &cur_protection, &max_protection,
+                          VM_INHERIT_COPY);
+        trace_apple_gfx_remap(r, source_ptr, target);
+        g_assert(r == KERN_SUCCESS);
+    }
+
+    return success;
+}
+
+static void apple_gfx_task_unmap_memory(AppleGFXState *s, PGTask_t

*task,

hw/display/apple-gfx.m line 147

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+                                        uint64_t virtual_offset,

uint64_t length)

Quoted 30 lines
hw/display/apple-gfx.m new file +30 -0
+{
+    kern_return_t r;
+    mach_vm_address_t range_address;
+
+    trace_apple_gfx_unmap_memory(task, virtual_offset, length);
+
+    /*
+     * Replace task memory range with fresh 0 pages, undoing the mapping
+     * from guest RAM.
+     */
+    range_address = task->address + virtual_offset;
+    r = mach_vm_allocate(mach_task_self(), &range_address, length,
+                         VM_FLAGS_FIXED | VM_FLAGS_OVERWRITE);
+    g_assert(r == KERN_SUCCESS);
+}
+
+/* ------ Rendering and frame management ------ */
+
+static void apple_gfx_render_frame_completed_bh(void *opaque);
+
+static void apple_gfx_render_new_frame(AppleGFXState *s)
+{
+    bool managed_texture = s->using_managed_texture_storage;
+    uint32_t width = surface_width(s->surface);
+    uint32_t height = surface_height(s->surface);
+    MTLRegion region = MTLRegionMake2D(0, 0, width, height);
+    id<MTLCommandBuffer> command_buffer = [s->mtl_queue commandBuffer];
+    id<MTLTexture> texture = s->texture;
+
+    assert(bql_locked());
Quoted 9 lines

hw/display/apple-gfx.m line 239

Quoted 6 lines
hw/display/apple-gfx.m new file +6 -0
+    [texture retain];
+
+    s->rendering_frame_width = width;
+    s->rendering_frame_height = height;
+
+    dispatch_async(s->render_queue, ^{

s->render_queue should no longer be necessary.

Are you saying we should switch to a generic background queue for this block? (get_background_queue())

I guess that should work as we are already
gating apple_gfx_render_new_frame() on s->pending_frames, so there is no particular need for using a serial dispatch queue.

Quoted 14 lines

hw/display/apple-gfx.m line 241

Quoted 2 lines
hw/display/apple-gfx.m new file +2 -0
+        /*
+         * This is not safe to call from the BQL due to PVG-internal

locks

hw/display/apple-gfx.m

Quoted 3 lines
hw/display/apple-gfx.m new file +3 -0
+         * causing deadlocks.
+         */
+        bool r = [s->pgdisp

encodeCurrentFrameToCommandBuffer:command_buffer

hw/display/apple-gfx.m line 250

Quoted 6 lines
hw/display/apple-gfx.m new file +6 -0
+                                                 texture:texture
+                                                  region:region];
+        if (!r) {
+            [texture release];
+            bql_lock();
+            --s->pending_frames;
Quoted 6 lines

I think you need to copy the following code from
apple_gfx_render_frame_completed_bh() here:

     if (s->pending_frames > 0) {
         apple_gfx_render_new_frame(s);
     }

if pending_frames > 0 at this stage, we will completely stop making any progress rendering new frames, so that does need fixing - not that it's at all clear under which conditions the encode…: method above might fail.

And although the other callers of apple_gfx_render_new_frame() call it from the context of a BH, I don't see a reason we can't call it from a background dispatch queue as long as the BQL is held, so yeah this should work.

Looking at everything else in this function more closely again, I notice that since the reworking to use BHs, we have been leaking the command_buffer, because [s->mtl_queue commandBuffer]; uses autorelease semantics, and unlike the dispatch queue tasks that were previously used, BHs don't create autorelease pools. We'll also need to retain/release the command buffer in the same manner as the texture.

I will wrap the affected BHs in @autoreleasepool blocks.

Quoted 514 lines

hw/display/apple-gfx.m

Quoted 3 lines
hw/display/apple-gfx.m new file +3 -0
+            bql_unlock();
+            qemu_log_mask(LOG_GUEST_ERROR,
+                          "%s:

encodeCurrentFrameToCommandBuffer:texture:region: "

hw/display/apple-gfx.m

Quoted 6 lines
hw/display/apple-gfx.m new file +6 -0
+                          "failed\n", __func__);
+            return;
+        }
+
+        if (managed_texture) {
+            /* "Managed" textures exist in both VRAM and RAM and must

be synced. */

hw/display/apple-gfx.m line 260

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+            id<MTLBlitCommandEncoder> blit = [command_buffer

blitCommandEncoder];

hw/display/apple-gfx.m line 270

Quoted 9 lines
hw/display/apple-gfx.m new file +9 -0
+            [blit synchronizeResource:texture];
+            [blit endEncoding];
+        }
+        [texture release];
+        [command_buffer addCompletedHandler:
+            ^(id<MTLCommandBuffer> cb)
+            {
+                aio_bh_schedule_oneshot(qemu_get_aio_context(),
+

apple_gfx_render_frame_completed_bh, s);

hw/display/apple-gfx.m

Quoted 7 lines
hw/display/apple-gfx.m new file +7 -0
+
+            }];
+        [command_buffer commit];
+    });
+}
+
+static void copy_mtl_texture_to_surface_mem(id<MTLTexture> texture,

void *vram)

Quoted 14 lines
hw/display/apple-gfx.m new file +14 -0
+{
+    /*
+     * TODO: Skip this entirely on a pure Metal or headless/guest-only
+     * rendering path, else use a blit command encoder? Needs careful
+     * (double?) buffering design.
+     */
+    size_t width = texture.width, height = texture.height;
+    MTLRegion region = MTLRegionMake2D(0, 0, width, height);
+    [texture getBytes:vram
+          bytesPerRow:(width * 4)
+        bytesPerImage:(width * height * 4)
+           fromRegion:region
+          mipmapLevel:0
+                slice:0];

hw/display/apple-gfx.m

Quoted 10 lines
hw/display/apple-gfx.m new file +10 -0
+}
+
+static void apple_gfx_render_frame_completed_bh(void *opaque)
+{
+    AppleGFXState *s = opaque;
+
+    --s->pending_frames;
+    assert(s->pending_frames >= 0);
+
+    /* Only update display if mode hasn't changed since we started

rendering. */

hw/display/apple-gfx.m

Quoted 3 lines
hw/display/apple-gfx.m new file +3 -0
+    if (s->rendering_frame_width == surface_width(s->surface) &&
+        s->rendering_frame_height == surface_height(s->surface)) {
+        copy_mtl_texture_to_surface_mem(s->texture,

surface_data(s->surface));

Quoted 45 lines
hw/display/apple-gfx.m new file +45 -0
+        if (s->gfx_update_requested) {
+            s->gfx_update_requested = false;
+            dpy_gfx_update_full(s->con);
+            graphic_hw_update_done(s->con);
+            s->new_frame_ready = false;
+        } else {
+            s->new_frame_ready = true;
+        }
+    }
+    if (s->pending_frames > 0) {
+        apple_gfx_render_new_frame(s);
+    }
+}
+
+static void apple_gfx_fb_update_display(void *opaque)
+{
+    AppleGFXState *s = opaque;
+
+    assert(bql_locked());
+    if (s->new_frame_ready) {
+        dpy_gfx_update_full(s->con);
+        s->new_frame_ready = false;
+        graphic_hw_update_done(s->con);
+    } else if (s->pending_frames > 0) {
+        s->gfx_update_requested = true;
+    } else {
+        graphic_hw_update_done(s->con);
+    }
+}
+
+static const GraphicHwOps apple_gfx_fb_ops = {
+    .gfx_update = apple_gfx_fb_update_display,
+    .gfx_update_async = true,
+};
+
+/* ------ Mouse cursor and display mode setting ------ */
+
+static void set_mode(AppleGFXState *s, uint32_t width, uint32_t height)
+{
+    MTLTextureDescriptor *textureDescriptor;
+
+    if (s->surface &&
+        width == surface_width(s->surface) &&
+        height == surface_height(s->surface)) {
+        return;

hw/display/apple-gfx.m line 365

Quoted 10 lines
hw/display/apple-gfx.m new file +10 -0
+    }
+
+    [s->texture release];
+
+    s->surface = qemu_create_displaysurface(width, height);
+
+    @autoreleasepool {
+        textureDescriptor =
+            [MTLTextureDescriptor
+

texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm

hw/display/apple-gfx.m

Quoted 5 lines
hw/display/apple-gfx.m new file +5 -0
+                                             width:width
+                                            height:height
+                                         mipmapped:NO];
+        textureDescriptor.usage = s->pgdisp.minimumTextureUsage;
+        s->texture = [s->mtl

newTextureWithDescriptor:textureDescriptor];

hw/display/apple-gfx.m

Quoted 12 lines
hw/display/apple-gfx.m new file +12 -0
+    }
+
+    s->using_managed_texture_storage =
+        (s->texture.storageMode == MTLStorageModeManaged);
+    dpy_gfx_replace_surface(s->con, s->surface);
+}
+
+static void update_cursor(AppleGFXState *s)
+{
+    assert(bql_locked());
+    dpy_mouse_set(s->con, s->pgdisp.cursorPosition.x,
+                  s->pgdisp.cursorPosition.y,

qatomic_read(&s->cursor_show));

Quoted 23 lines
hw/display/apple-gfx.m new file +23 -0
+}
+
+static void update_cursor_bh(void *opaque)
+{
+    AppleGFXState *s = opaque;
+    update_cursor(s);
+}
+
+typedef struct AppleGFXSetCursorGlyphJob {
+    AppleGFXState *s;
+    NSBitmapImageRep *glyph;
+    PGDisplayCoord_t hotspot;
+} AppleGFXSetCursorGlyphJob;
+
+static void set_cursor_glyph(void *opaque)
+{
+    AppleGFXSetCursorGlyphJob *job = opaque;
+    AppleGFXState *s = job->s;
+    NSBitmapImageRep *glyph = job->glyph;
+    uint32_t bpp = glyph.bitsPerPixel;
+    size_t width = glyph.pixelsWide;
+    size_t height = glyph.pixelsHigh;
+    size_t padding_bytes_per_row = glyph.bytesPerRow - width * 4;

hw/display/apple-gfx.m

Quoted 10 lines
hw/display/apple-gfx.m new file +10 -0
+    const uint8_t* px_data = glyph.bitmapData;
+
+    trace_apple_gfx_cursor_set(bpp, width, height);
+
+    if (s->cursor) {
+        cursor_unref(s->cursor);
+        s->cursor = NULL;
+    }
+
+    if (bpp == 32) { /* Shouldn't be anything else, but just to be

safe...*/

Quoted 43 lines
hw/display/apple-gfx.m new file +43 -0
+        s->cursor = cursor_alloc(width, height);
+        s->cursor->hot_x = job->hotspot.x;
+        s->cursor->hot_y = job->hotspot.y;
+
+        uint32_t *dest_px = s->cursor->data;
+
+        for (size_t y = 0; y < height; ++y) {
+            for (size_t x = 0; x < width; ++x) {
+                /*
+                 * NSBitmapImageRep's red & blue channels are swapped
+                 * compared to QEMUCursor's.
+                 */
+                *dest_px =
+                    (px_data[0] << 16u) |
+                    (px_data[1] <<  8u) |
+                    (px_data[2] <<  0u) |
+                    (px_data[3] << 24u);
+                ++dest_px;
+                px_data += 4;
+            }
+            px_data += padding_bytes_per_row;
+        }
+        dpy_cursor_define(s->con, s->cursor);
+        update_cursor(s);
+    }
+    [glyph release];
+
+    g_free(job);
+}
+
+/* ------ DMA (device reading system memory) ------ */
+
+typedef struct AppleGFXReadMemoryJob {
+    QemuSemaphore sem;
+    hwaddr physical_address;
+    uint64_t length;
+    void *dst;
+    bool success;
+} AppleGFXReadMemoryJob;
+
+static void apple_gfx_do_read_memory(void *opaque)
+{
+    AppleGFXReadMemoryJob *job = opaque;

hw/display/apple-gfx.m

Quoted 10 lines
hw/display/apple-gfx.m new file +10 -0
+    MemTxResult r;
+
+    r = dma_memory_read(&address_space_memory, job->physical_address,
+                        job->dst, job->length, MEMTXATTRS_UNSPECIFIED);
+    job->success = r == MEMTX_OK;
+
+    qemu_sem_post(&job->sem);
+}
+
+static bool apple_gfx_read_memory(AppleGFXState *s, hwaddr

physical_address,

hw/display/apple-gfx.m

Quoted 4 lines
hw/display/apple-gfx.m new file +4 -0
+                                  uint64_t length, void *dst)
+{
+    AppleGFXReadMemoryJob job = {
+        .physical_address = physical_address, .length = length, .dst =

dst

Quoted 8 lines
hw/display/apple-gfx.m new file +8 -0
+    };
+
+    trace_apple_gfx_read_memory(physical_address, length, dst);
+
+    /* Performing DMA requires BQL, so do it in a BH. */
+    qemu_sem_init(&job.sem, 0);
+    aio_bh_schedule_oneshot(qemu_get_aio_context(),
+                            apple_gfx_do_read_memory, &job);

hw/display/apple-gfx.m

Quoted 10 lines
hw/display/apple-gfx.m new file +10 -0
+    qemu_sem_wait(&job.sem);
+    qemu_sem_destroy(&job.sem);
+    return job.success;
+}
+
+/* ------ Memory-mapped device I/O operations ------ */
+
+static dispatch_queue_t get_background_queue(void)
+{
+    return dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,

0);

Quoted 8 lines
hw/display/apple-gfx.m new file +8 -0
+}
+
+typedef struct AppleGFXIOJob {
+    AppleGFXState *state;
+    uint64_t offset;
+    uint64_t value;
+    bool completed;
+} AppleGFXIOJob;

hw/display/apple-gfx.m

Quoted 10 lines
hw/display/apple-gfx.m new file +10 -0
+
+static void apple_gfx_do_read(void *opaque)
+{
+    AppleGFXIOJob *job = opaque;
+    job->value = [job->state->pgdev mmioReadAtOffset:job->offset];
+    qatomic_set(&job->completed, true);
+    aio_wait_kick();
+}
+
+static uint64_t apple_gfx_read(void *opaque, hwaddr offset, unsigned

size)

Quoted 18 lines
hw/display/apple-gfx.m new file +18 -0
+{
+    AppleGFXIOJob job = {
+        .state = opaque,
+        .offset = offset,
+        .completed = false,
+    };
+    dispatch_queue_t queue = get_background_queue();
+
+    dispatch_async_f(queue, &job, apple_gfx_do_read);
+    AIO_WAIT_WHILE(NULL, !qatomic_read(&job.completed));
+
+    trace_apple_gfx_read(offset, job.value);
+    return job.value;
+}
+
+static void apple_gfx_do_write(void *opaque)
+{
+    AppleGFXIOJob *job = opaque;

hw/display/apple-gfx.m

Quoted 10 lines
hw/display/apple-gfx.m new file +10 -0
+    [job->state->pgdev mmioWriteAtOffset:job->offset value:job->value];
+    qatomic_set(&job->completed, true);
+    aio_wait_kick();
+}
+
+static void apple_gfx_write(void *opaque, hwaddr offset, uint64_t val,
+                            unsigned size)
+{
+    /*
+     * The methods mmioReadAtOffset: and especially mmioWriteAtOffset:

can

hw/display/apple-gfx.m line 530

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+     * trigger synchronous operations on other dispatch queues, which

in turn

hw/display/apple-gfx.m line 531

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+     * may call back out on one or more of the callback blocks. For

this reason,

hw/display/apple-gfx.m line 532

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+     * and as we are holding the BQL, we invoke the I/O methods on a

pool

hw/display/apple-gfx.m line 533

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+     * thread and handle AIO tasks while we wait. Any work in the

callbacks

hw/display/apple-gfx.m line 534

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+     * requiring the BQL will in turn schedule BHs which this thread

will

Quoted 34 lines
hw/display/apple-gfx.m new file +34 -0
+     * process while waiting.
+     */
+    AppleGFXIOJob job = {
+        .state = opaque,
+        .offset = offset,
+        .value = val,
+        .completed = false,
+    };
+    dispatch_queue_t queue = get_background_queue();
+
+    dispatch_async_f(queue, &job, apple_gfx_do_write);
+    AIO_WAIT_WHILE(NULL, !qatomic_read(&job.completed));
+
+    trace_apple_gfx_write(offset, val);
+}
+
+static const MemoryRegionOps apple_gfx_ops = {
+    .read = apple_gfx_read,
+    .write = apple_gfx_write,
+    .endianness = DEVICE_LITTLE_ENDIAN,
+    .valid = {
+        .min_access_size = 4,
+        .max_access_size = 8,
+    },
+    .impl = {
+        .min_access_size = 4,
+        .max_access_size = 4,
+    },
+};
+
+static size_t apple_gfx_get_default_mmio_range_size(void)
+{
+    size_t mmio_range_size;
+    @autoreleasepool {

hw/display/apple-gfx.m

Quoted 10 lines
hw/display/apple-gfx.m new file +10 -0
+        PGDeviceDescriptor *desc = [PGDeviceDescriptor new];
+        mmio_range_size = desc.mmioLength;
+        [desc release];
+    }
+    return mmio_range_size;
+}
+
+/* ------ Initialisation and startup ------ */
+
+void apple_gfx_common_init(Object *obj, AppleGFXState *s, const char*

obj_name)

hw/display/apple-gfx.m

Quoted 5 lines
hw/display/apple-gfx.m new file +5 -0
+{
+    size_t mmio_range_size = apple_gfx_get_default_mmio_range_size();
+
+    trace_apple_gfx_common_init(obj_name, mmio_range_size);
+    memory_region_init_io(&s->iomem_gfx, obj, &apple_gfx_ops, s,

obj_name,

hw/display/apple-gfx.m

Quoted 3 lines
hw/display/apple-gfx.m new file +3 -0
+                          mmio_range_size);
+
+    /* TODO: PVG framework supports serialising device state: integrate

it! */

hw/display/apple-gfx.m

Quoted 4 lines
hw/display/apple-gfx.m new file +4 -0
+}
+
+static void apple_gfx_register_task_mapping_handlers(AppleGFXState *s,
+                                                     PGDeviceDescriptor

*desc)

hw/display/apple-gfx.m line 592

Quoted 2 lines
hw/display/apple-gfx.m new file +2 -0
+{
+    desc.createTask = ^(uint64_t vmSize, void * _Nullable * _Nonnull

baseAddress) {

hw/display/apple-gfx.m

Quoted 13 lines
hw/display/apple-gfx.m new file +13 -0
+        PGTask_t *task = apple_gfx_new_task(s, vmSize);
+        *baseAddress = (void *)task->address;
+        trace_apple_gfx_create_task(vmSize, *baseAddress);
+        return task;
+    };
+
+    desc.destroyTask = ^(PGTask_t * _Nonnull task) {
+        trace_apple_gfx_destroy_task(task, task->mapped_regions->len);
+
+        apple_gfx_destroy_task(s, task);
+    };
+
+    desc.mapMemory = ^bool(PGTask_t * _Nonnull task, uint32_t

range_count,

hw/display/apple-gfx.m

Quoted 4 lines
hw/display/apple-gfx.m new file +4 -0
+                           uint64_t virtual_offset, bool read_only,
+                           PGPhysicalMemoryRange_t * _Nonnull ranges) {
+        return apple_gfx_task_map_memory(s, task, virtual_offset,
+                                         ranges, range_count,

read_only);

hw/display/apple-gfx.m line 612

Quoted 3 lines
hw/display/apple-gfx.m new file +3 -0
+    };
+
+    desc.unmapMemory = ^bool(PGTask_t * _Nonnull task, uint64_t

virtual_offset,

Quoted 17 lines
hw/display/apple-gfx.m new file +17 -0
+                             uint64_t length) {
+        apple_gfx_task_unmap_memory(s, task, virtual_offset, length);
+        return true;
+    };
+
+    desc.readMemory = ^bool(uint64_t physical_address, uint64_t length,
+                            void * _Nonnull dst) {
+        return apple_gfx_read_memory(s, physical_address, length, dst);
+    };
+}
+
+static void new_frame_handler_bh(void *opaque)
+{
+    AppleGFXState *s = opaque;
+
+    /* Drop frames if we get too far ahead. */
+    if (s->pending_frames >= 2) {

hw/display/apple-gfx.m

Quoted 10 lines
hw/display/apple-gfx.m new file +10 -0
+        return;
+    }
+    ++s->pending_frames;
+    if (s->pending_frames > 1) {
+        return;
+    }
+    apple_gfx_render_new_frame(s);
+}
+
+static PGDisplayDescriptor

*apple_gfx_prepare_display_descriptor(AppleGFXState *s)

hw/display/apple-gfx.m

Quoted 5 lines
hw/display/apple-gfx.m new file +5 -0
+{
+    PGDisplayDescriptor *disp_desc = [PGDisplayDescriptor new];
+
+    disp_desc.name = @"QEMU display";
+    disp_desc.sizeInMillimeters = NSMakeSize(400., 300.); /* A 20"

display */

hw/display/apple-gfx.m line 664

Quoted 4 lines
hw/display/apple-gfx.m new file +4 -0
+    disp_desc.queue = dispatch_get_main_queue();
+    disp_desc.newFrameEventHandler = ^(void) {
+        trace_apple_gfx_new_frame();
+        aio_bh_schedule_oneshot(qemu_get_aio_context(),

new_frame_handler_bh, s);

Quoted 24 lines
hw/display/apple-gfx.m new file +24 -0
+    };
+    disp_desc.modeChangeHandler = ^(PGDisplayCoord_t sizeInPixels,
+                                    OSType pixelFormat) {
+        trace_apple_gfx_mode_change(sizeInPixels.x, sizeInPixels.y);
+
+        BQL_LOCK_GUARD();
+        set_mode(s, sizeInPixels.x, sizeInPixels.y);
+    };
+    disp_desc.cursorGlyphHandler = ^(NSBitmapImageRep *glyph,
+                                     PGDisplayCoord_t hotspot) {
+        AppleGFXSetCursorGlyphJob *job = g_malloc0(sizeof(*job));
+        job->s = s;
+        job->glyph = glyph;
+        job->hotspot = hotspot;
+        [glyph retain];
+        aio_bh_schedule_oneshot(qemu_get_aio_context(),
+                                set_cursor_glyph, job);
+    };
+    disp_desc.cursorShowHandler = ^(BOOL show) {
+        trace_apple_gfx_cursor_show(show);
+        qatomic_set(&s->cursor_show, show);
+        aio_bh_schedule_oneshot(qemu_get_aio_context(),
+                                update_cursor_bh, s);
+    };

hw/display/apple-gfx.m

Quoted 10 lines
hw/display/apple-gfx.m new file +10 -0
+    disp_desc.cursorMoveHandler = ^(void) {
+        trace_apple_gfx_cursor_move();
+        aio_bh_schedule_oneshot(qemu_get_aio_context(),
+                                update_cursor_bh, s);
+    };
+
+    return disp_desc;
+}
+
+static NSArray<PGDisplayMode*>*

apple_gfx_prepare_display_mode_array(void)

hw/display/apple-gfx.m

Quoted 8 lines
hw/display/apple-gfx.m new file +8 -0
+{
+    PGDisplayMode *modes[ARRAY_SIZE(apple_gfx_modes)];
+    NSArray<PGDisplayMode*>* mode_array;
+    int i;
+
+    for (i = 0; i < ARRAY_SIZE(apple_gfx_modes); i++) {
+        modes[i] =
+            [[PGDisplayMode alloc]

initWithSizeInPixels:apple_gfx_modes[i] refreshRateInHz:60.];

hw/display/apple-gfx.m line 693

Quoted 3 lines
hw/display/apple-gfx.m new file +3 -0
+    }
+
+    mode_array = [NSArray arrayWithObjects:modes

count:ARRAY_SIZE(apple_gfx_modes)];

Quoted 5 lines
hw/display/apple-gfx.m new file +5 -0
+
+    for (i = 0; i < ARRAY_SIZE(apple_gfx_modes); i++) {
+        [modes[i] release];
+        modes[i] = nil;
+    }

hw/display/apple-gfx.m

Quoted 10 lines
hw/display/apple-gfx.m new file +10 -0
+
+    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. */

Quoted 20 lines
hw/display/apple-gfx.m new file +20 -0
+    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;
+}
+
Quoted 9 lines

hw/display/apple-gfx.m line 734

Quoted 6 lines
hw/display/apple-gfx.m new file +6 -0
+static uint32_t next_pgdisplay_serial_num = 1;
+
+bool apple_gfx_common_realize(AppleGFXState *s, DeviceState *dev,
+                              PGDeviceDescriptor *desc, Error **errp)
+{
+    PGDisplayDescriptor *disp_desc = nil;

Omit the nil initialization here.

I've now gone through all the variable declarations in apple-gfx and together with an instance I found in -mmio, I've now hopefully removed all the redundant initialisations.

Quoted 151 lines

hw/display/apple-gfx.m

Quoted 4 lines
hw/display/apple-gfx.m new file +4 -0
+
+    if (apple_gfx_mig_blocker == NULL) {
+        error_setg(&apple_gfx_mig_blocker,
+                  "Migration state blocked by apple-gfx display

device");

Quoted 13 lines
hw/display/apple-gfx.m new file +13 -0
+        if (migrate_add_blocker(&apple_gfx_mig_blocker, errp) < 0) {
+            return false;
+        }
+    }
+
+    qemu_mutex_init(&s->task_mutex);
+    QTAILQ_INIT(&s->tasks);
+    s->render_queue = dispatch_queue_create("apple-gfx.render",
+                                            DISPATCH_QUEUE_SERIAL);
+    s->mtl = copy_suitable_metal_device();
+    s->mtl_queue = [s->mtl newCommandQueue];
+
+    desc.device = s->mtl;

hw/display/apple-gfx.m

Quoted 10 lines
hw/display/apple-gfx.m new file +10 -0
+
+    apple_gfx_register_task_mapping_handlers(s, desc);
+
+    s->cursor_show = true;
+
+    s->pgdev = PGNewDeviceWithDescriptor(desc);
+
+    disp_desc = apple_gfx_prepare_display_descriptor(s);
+    /*
+     * Although the framework does, this integration currently does not

support

hw/display/apple-gfx.m line 762

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+     * multiple virtual displays connected to a single PV graphics

device.

hw/display/apple-gfx.m line 764

Quoted 2 lines
hw/display/apple-gfx.m new file +2 -0
+     * It is however possible to create
+     * more than one instance of the device, each with one display. The

macOS

hw/display/apple-gfx.m line 765

Quoted 1 line
hw/display/apple-gfx.m new file +1 -0
+     * guest will ignore these displays if they share the same serial

number,

hw/display/apple-gfx.m line 773

Quoted 5 lines
hw/display/apple-gfx.m new file +5 -0
+     * so ensure each instance gets a unique one.
+     */
+    s->pgdisp = [s->pgdev newDisplayWithDescriptor:disp_desc
+                                              port:0
+

serialNum:next_pgdisplay_serial_num++];

hw/display/meson.build system_ss.add(when: 'CONFIG_ARTIST', if_true:

Quoted 11 lines
hw/display/apple-gfx.m new file +6 -0
+    [disp_desc release];
+    s->pgdisp.modeList = apple_gfx_prepare_display_mode_array();
+
+    s->con = graphic_console_init(dev, 0, &apple_gfx_fb_ops, s);
+    return true;
+}
hw/display/meson.build +0 -0
index 20a94973fa2..cf9e6dd35d2 100644
@@ -61,6 +61,12 @@ system_ss.add(when: 'CONFIG_ARTIST', if_true:

files('artist.c'))

hw/display/meson.build system_ss.add(when: 'CONFIG_ARTIST', if_true: · line 61

Quoted 2 lines
hw/display/meson.build +0 -0
  system_ss.add(when: 'CONFIG_ATI_VGA', if_true: [files('ati.c',

'ati_2d.c', 'ati_dbg.c'), pixman])

hw/display/meson.build system_ss.add(when: 'CONFIG_ARTIST', if_true: · line 63

Quoted 3 lines
hw/display/meson.build +2 -0
+if host_os == 'darwin'
+  system_ss.add(when: 'CONFIG_MAC_PVG',         if_true:

[files('apple-gfx.m'), pvg, metal])

hw/display/meson.build system_ss.add(when: 'CONFIG_ARTIST', if_true: · line 65

Quoted 2 lines
hw/display/meson.build +2 -0
+  if cpu == 'aarch64'
+    system_ss.add(when: 'CONFIG_MAC_PVG_MMIO',  if_true:

[files('apple-gfx-mmio.m'), pvg, metal])

hw/display/trace-events dm163_bits_ppi(unsigned dest_width) "dest_width :

Quoted 10 lines
hw/display/meson.build +2 -0
+  endif
+endif
 
  if config_all_devices.has_key('CONFIG_VIRTIO_GPU')
    virtio_gpu_ss = ss.source_set()
hw/display/trace-events +0 -0
index d26d663f963..a50e4eea0c0 100644
@@ -194,3 +194,31 @@ dm163_bits_ppi(unsigned dest_width) "dest_width :

%u"

hw/display/trace-events dm163_bits_ppi(unsigned dest_width) "dest_width : %u"

Quoted 6 lines
hw/display/trace-events +3 -0
  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

hw/display/trace-events dm163_bits_ppi(unsigned dest_width) "dest_width : · line 200

Quoted 1 line
hw/display/trace-events +1 -0
+apple_gfx_write(uint64_t offset, uint64_t val) "offset=0x%"PRIx64"

val=0x%"PRIx64

hw/display/trace-events dm163_bits_ppi(unsigned dest_width) "dest_width : · line 201

Quoted 1 line
hw/display/trace-events +1 -0
+apple_gfx_create_task(uint32_t vm_size, void *va) "vm_size=0x%x

base_addr=%p"

hw/display/trace-events dm163_bits_ppi(unsigned dest_width) "dest_width : · line 202

Quoted 1 line
hw/display/trace-events +1 -0
+apple_gfx_destroy_task(void *task, unsigned int num_mapped_regions)

"task=%p, task->mapped_regions->len=%u"

hw/display/trace-events dm163_bits_ppi(unsigned dest_width) "dest_width : · line 203

Quoted 1 line
hw/display/trace-events +1 -0
+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"

hw/display/trace-events dm163_bits_ppi(unsigned dest_width) "dest_width : · line 204

Quoted 1 line
hw/display/trace-events +1 -0
+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

hw/display/trace-events dm163_bits_ppi(unsigned dest_width) "dest_width : · line 205

Quoted 1 line
hw/display/trace-events +1 -0
+apple_gfx_remap(uint64_t retval, void *source_ptr, uint64_t target)

"retval=%"PRId64" source=%p target=0x%"PRIx64

hw/display/trace-events dm163_bits_ppi(unsigned dest_width) "dest_width : · line 206

Quoted 1 line
hw/display/trace-events +1 -0
+apple_gfx_unmap_memory(void *task, uint64_t virtual_offset, uint64_t

length) "task=%p virtual_offset=0x%"PRIx64" length=0x%"PRIx64

hw/display/trace-events dm163_bits_ppi(unsigned dest_width) "dest_width : · line 207

Quoted 1 line
hw/display/trace-events +1 -0
+apple_gfx_read_memory(uint64_t phys_address, uint64_t length, void

*dst) "phys_addr=0x%"PRIx64" length=0x%"PRIx64" dest=%p"

hw/display/trace-events dm163_bits_ppi(unsigned dest_width) "dest_width : %u"

Quoted 4 lines
hw/display/trace-events +4 -0
+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

hw/display/trace-events dm163_bits_ppi(unsigned dest_width) "dest_width : %u"

Quoted 3 lines
hw/display/trace-events +3 -0
+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"

hw/display/trace-events dm163_bits_ppi(unsigned dest_width) "dest_width : %u"

Quoted 3 lines
hw/display/trace-events +3 -0
+
+# apple-gfx-mmio.m
+apple_gfx_mmio_iosfc_read(uint64_t offset, uint64_t res)

"offset=0x%"PRIx64" res=0x%"PRIx64

hw/display/trace-events dm163_bits_ppi(unsigned dest_width) "dest_width : · line 218

Quoted 1 line
hw/display/trace-events +1 -0
+apple_gfx_mmio_iosfc_write(uint64_t offset, uint64_t val)

"offset=0x%"PRIx64" val=0x%"PRIx64

hw/display/trace-events dm163_bits_ppi(unsigned dest_width) "dest_width : · line 219

Quoted 1 line
hw/display/trace-events +1 -0
+apple_gfx_iosfc_map_memory(uint64_t phys, uint64_t len, uint32_t ro,

void *va, void *e, void *f, void* va_result) "phys=0x%"PRIx64" len=0x%"PRIx64" ro=%d va=%p e=%p f=%p -> *va=%p"

hw/display/trace-events dm163_bits_ppi(unsigned dest_width) "dest_width : · line 220

Quoted 1 line
hw/display/trace-events +1 -0
+apple_gfx_iosfc_map_memory_new_region(size_t i, void *region, uint64_t

start, uint64_t end) "index=%zu, region=%p, 0x%"PRIx64"-0x%"PRIx64

hw/display/trace-events dm163_bits_ppi(unsigned dest_width) "dest_width : · line 221

Quoted 1 line
hw/display/trace-events +1 -0
+apple_gfx_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"

hw/display/trace-events dm163_bits_ppi(unsigned dest_width) "dest_width : · line 222

Quoted 1 line
hw/display/trace-events +1 -0
+apple_gfx_iosfc_unmap_memory_region(void* mem, void *region) "unmapping

@ %p from memory region %p"

Quoted 16 lines
hw/display/trace-events +2 -0
+apple_gfx_iosfc_raise_irq(uint32_t vector) "vector=0x%x"
+
meson.build +2 -0
index e0b880e4e13..3c61238bc77 100644
@@ -794,6 +794,8 @@ socket = []
  version_res = []
  coref = []
  iokit = []
+pvg = not_found
+metal = []
  emulator_link_args = []
  midl = not_found
  widl = not_found

meson.build elif host_os == 'darwin' · line 818

Quoted 2 lines
meson.build +0 -0
@@ -815,6 +817,8 @@ elif host_os == 'darwin'
    coref = dependency('appleframeworks', modules: 'CoreFoundation')
    iokit = dependency('appleframeworks', modules: 'IOKit', required:

false)

meson.build elif host_os == 'darwin' · line 820

Quoted 2 lines
meson.build +1 -0
    host_dsosuf = '.dylib'
+  pvg = dependency('appleframeworks', modules:

'ParavirtualizedGraphics')

Quoted 4 lines
meson.build +1 -0
+  metal = dependency('appleframeworks', modules: 'Metal')
  elif host_os == 'sunos'
    socket = [cc.find_library('socket'),
              cc.find_library('nsl'),
#10 lore raw

PATCH v11 3/15 hw/display/apple-gfx: Adds PCI implementation

In reply to Phil Dennis-Jordan

This 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.

---

v4:

* Threading improvements analogous to those in common apple-gfx code and mmio device variant.
* Smaller code review issues addressed.

v5:

* Minor error handling improvement.

v6:

* Removed an unused function parameter.

v9:

* Fixup of changed common call.
* Whitespace and comment formatting tweaks.

v11:

* Comment formatting fix.

 hw/display/Kconfig         |   4 +
 hw/display/apple-gfx-pci.m | 150 +++++++++++++++++++++++++++++++++++++
 hw/display/meson.build     |   1 +
 3 files changed, 155 insertions(+)
 create mode 100644 hw/display/apple-gfx-pci.m
hw/display/Kconfig +4 -0
index 6a9b7b19ada..2b53dfd7d26 100644
@@ -149,3 +149,7 @@ config MAC_PVG_MMIO
     bool
     depends on MAC_PVG && AARCH64
 
+config MAC_PVG_PCI
+    bool
+    depends on MAC_PVG && PCI
+    default y if PCI_DEVICES
hw/display/apple-gfx-pci.m new file +150 -0

150 lines not on this page · raw message

hw/display/meson.build +1 -0
index cf9e6dd35d2..94f4f05d36f 100644
@@ -63,6 +63,7 @@ system_ss.add(when: 'CONFIG_ATI_VGA', if_true: [files('ati.c', 'ati_2d.c', 'ati_
 
 if host_os == 'darwin'
   system_ss.add(when: 'CONFIG_MAC_PVG',         if_true: [files('apple-gfx.m'), pvg, metal])
+  system_ss.add(when: 'CONFIG_MAC_PVG_PCI',     if_true: [files('apple-gfx-pci.m'), pvg, metal])
   if cpu == 'aarch64'
     system_ss.add(when: 'CONFIG_MAC_PVG_MMIO',  if_true: [files('apple-gfx-mmio.m'), pvg, metal])
   endif
Signature · 1 line
2.39.5 (Apple Git-154)
Reviewed-by on v11 3/15
#11 lore raw

Re: [PATCH v11 03/15] hw/display/apple-gfx: Adds PCI implementation

Quoted 6 lines · Phil Dennis-Jordan

This 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.

#12 lore raw

PATCH v11 4/15 hw/display/apple-gfx: Adds configurable mode list

In reply to Phil Dennis-Jordan

This change adds a property 'display_modes' on the graphics device which permits specifying a list of display modes. (screen resolution and refresh rate)

The property is an array of a custom type to make the syntax slightly less awkward to use, for example:

-device '{"driver":"apple-gfx-pci", "display-modes":["1920x1080@60", "3840x2160@60"]}'

---

v4:

* Switched to the native array property type, which recently gained command line support.
* The property has also been added to the -mmio variant.
* Tidied up the code a little.

v5:

* Better error handling and buffer management in property parsing and output.

v6:

* Switched to using NSMutableArray for the mode list to avoid need for allocating a temporary array - previously done with alloca.

v7:

* Simplified error handling in property parsing

v8:

* More consistent integer variable types.

v9:

* Re-ordered type definitions so we can drop a 'struct' keyword.

 hw/display/apple-gfx-mmio.m |   8 +++
 hw/display/apple-gfx-pci.m  |   9 ++-
 hw/display/apple-gfx.h      |  11 +++
 hw/display/apple-gfx.m      | 135 +++++++++++++++++++++++++++++++-----
 hw/display/trace-events     |   2 +
 5 files changed, 145 insertions(+), 20 deletions(-)
hw/display/apple-gfx-mmio.m +8 -0
index 2d76e7375bd..99935a155c7 100644
@@ -258,6 +258,12 @@ static void apple_gfx_mmio_reset(Object *obj, ResetType type)
     [s->common.pgdev reset];
 }
 
+static Property apple_gfx_mmio_properties[] = {
+    DEFINE_PROP_ARRAY("display-modes", AppleGFXMMIOState,
+                      common.num_display_modes, common.display_modes,
+                      qdev_prop_display_mode, AppleGFXDisplayMode),
+    DEFINE_PROP_END_OF_LIST(),
+};
 
 static void apple_gfx_mmio_class_init(ObjectClass *klass, void *data)
 {
@@ -267,6 +273,8 @@ static void apple_gfx_mmio_class_init(ObjectClass *klass, void *data)
     rc->phases.hold = apple_gfx_mmio_reset;
     dc->hotpluggable = false;
     dc->realize = apple_gfx_mmio_realize;
+
+    device_class_set_props(dc, apple_gfx_mmio_properties);
 }
 
 static TypeInfo apple_gfx_mmio_types[] = {
hw/display/apple-gfx-pci.m +8 -1
index 5ff6a487cfc..765b210287d 100644
@@ -114,6 +114,13 @@ static void apple_gfx_pci_reset(Object *obj, ResetType type)
     [s->common.pgdev reset];
 }
 
+static Property apple_gfx_pci_properties[] = {
+    DEFINE_PROP_ARRAY("display-modes", AppleGFXPCIState,
+                      common.num_display_modes, common.display_modes,
+                      qdev_prop_display_mode, AppleGFXDisplayMode),
+    DEFINE_PROP_END_OF_LIST(),
+};
+
 static void apple_gfx_pci_class_init(ObjectClass *klass, void *data)
 {
     DeviceClass *dc = DEVICE_CLASS(klass);
@@ -130,7 +137,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 +11 -0
index 220276b7492..a34c53cda34 100644
@@ -16,6 +16,7 @@
 #import <ParavirtualizedGraphics/ParavirtualizedGraphics.h>
 #include "qemu/typedefs.h"
 #include "exec/memory.h"
+#include "hw/qdev-properties.h"
 #include "ui/surface.h"
 
 @class PGDeviceDescriptor;
@@ -27,6 +28,12 @@
 
 typedef QTAILQ_HEAD(, PGTask_s) PGTaskList;
 
+typedef struct AppleGFXDisplayMode {
+    uint16_t width_px;
+    uint16_t height_px;
+    uint16_t refresh_rate_hz;
+} AppleGFXDisplayMode;
+
 typedef struct AppleGFXState {
     /* Initialised on init/realize() */
     MemoryRegion iomem_gfx;
@@ -36,6 +43,8 @@ typedef struct AppleGFXState {
     id<MTLDevice> mtl;
     id<MTLCommandQueue> mtl_queue;
     dispatch_queue_t render_queue;
+    AppleGFXDisplayMode *display_modes;
+    uint32_t num_display_modes;
 
     /* List `tasks` is protected by task_mutex */
     QemuMutex task_mutex;
@@ -63,5 +72,7 @@ void *apple_gfx_host_ptr_for_gpa_range(uint64_t guest_physical,
                                        uint64_t length, bool read_only,
                                        MemoryRegion **mapping_in_region);
 
+extern const PropertyInfo qdev_prop_display_mode;
+
 #endif
 
hw/display/apple-gfx.m +116 -19

161 lines not on this page · raw message

hw/display/trace-events +2 -0
index a50e4eea0c0..52786e6e184 100644
@@ -212,6 +212,8 @@ apple_gfx_cursor_set(uint32_t bpp, uint64_t width, uint64_t height) "bpp=%d widt
 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_common_realize_modes_property(uint32_t num_modes) "using %u modes supplied by 'display-modes' device property"
+apple_gfx_display_mode(uint32_t mode_idx, uint16_t width_px, uint16_t height_px) "mode %2"PRIu32": %4"PRIu16"x%4"PRIu16
 
 # apple-gfx-mmio.m
 apple_gfx_mmio_iosfc_read(uint64_t offset, uint64_t res) "offset=0x%"PRIx64" res=0x%"PRIx64
Signature · 1 line
2.39.5 (Apple Git-154)
#13 lore raw

PATCH v11 5/15 MAINTAINERS: Add myself as maintainer for apple-gfx, reviewer for HVF

In reply to Phil Dennis-Jordan

I'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
index 2b1c4abed65..08780eca5d1 100644
@@ -507,6 +507,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/
@@ -514,6 +515,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/
@@ -2610,6 +2612,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.5 (Apple Git-154)
#14 lore raw

PATCH v11 6/15 hw: Add vmapple subdir

In reply to Phil Dennis-Jordan

From: Alexander Graf <[email protected]>

We will introduce a number of devices that are specific to the vmapple target machine. To keep them all tidily together, let's put them into a single target directory.

---
 MAINTAINERS             | 7 +++++++
 hw/Kconfig              | 1 +
 hw/meson.build          | 1 +
 hw/vmapple/Kconfig      | 1 +
 hw/vmapple/meson.build  | 0
 hw/vmapple/trace-events | 2 ++
 hw/vmapple/trace.h      | 1 +
 meson.build             | 1 +
 8 files changed, 14 insertions(+)
 create mode 100644 hw/vmapple/Kconfig
 create mode 100644 hw/vmapple/meson.build
 create mode 100644 hw/vmapple/trace-events
 create mode 100644 hw/vmapple/trace.h
MAINTAINERS +7 -0
index 08780eca5d1..9e7fc6c050a 100644
@@ -2763,6 +2763,13 @@ F: hw/hyperv/hv-balloon*.h
 F: include/hw/hyperv/dynmem-proto.h
 F: include/hw/hyperv/hv-balloon.h
 
+VMapple
+M: Alexander Graf <[email protected]>
+R: Phil Dennis-Jordan <[email protected]>
+S: Maintained
+F: hw/vmapple/*
+F: include/hw/vmapple/*
+
 Subsystems
 ----------
 Overall Audio backends
hw/Kconfig +1 -0
index 1b4e9bb07f7..2871784cfdc 100644
@@ -41,6 +41,7 @@ source ufs/Kconfig
 source usb/Kconfig
 source virtio/Kconfig
 source vfio/Kconfig
+source vmapple/Kconfig
 source xen/Kconfig
 source watchdog/Kconfig
 
hw/meson.build +1 -0
index b827c82c5d7..9c4f6d0d636 100644
@@ -39,6 +39,7 @@ subdir('ufs')
 subdir('usb')
 subdir('vfio')
 subdir('virtio')
+subdir('vmapple')
 subdir('watchdog')
 subdir('xen')
 subdir('xenpv')
hw/vmapple/Kconfig new file +1 -0
new file mode 100644
index 00000000000..8b137891791
@@ -0,0 +1 @@
+
hw/vmapple/meson.build new file +0 -0
new file mode 100644
index 00000000000..e69de29bb2d
hw/vmapple/trace-events new file +2 -0
new file mode 100644
index 00000000000..9ccc5790487
@@ -0,0 +1,2 @@
+# See docs/devel/tracing.rst for syntax documentation.
+
hw/vmapple/trace.h new file +1 -0
new file mode 100644
index 00000000000..572adbefe04
@@ -0,0 +1 @@
+#include "trace/trace-hw_vmapple.h"
meson.build +1 -0
index 3c61238bc77..a5f76f27c12 100644
@@ -3592,6 +3592,7 @@ if have_system
     'hw/usb',
     'hw/vfio',
     'hw/virtio',
+    'hw/vmapple',
     'hw/watchdog',
     'hw/xen',
     'hw/gpio',
Signature · 1 line
2.39.5 (Apple Git-154)
#15 lore raw

PATCH v11 7/15 hw/misc/pvpanic: Add MMIO interface

In reply to Phil Dennis-Jordan

From: Alexander Graf <[email protected]>

In addition to the ISA and PCI variants of pvpanic, let's add an MMIO platform device that we can use in embedded arm environments.

---

v3:
* Rebased on upstream, updated a header path

 hw/misc/Kconfig           |  4 +++
 hw/misc/meson.build       |  1 +
 hw/misc/pvpanic-mmio.c    | 61 +++++++++++++++++++++++++++++++++++++++
 include/hw/misc/pvpanic.h |  1 +
 4 files changed, 67 insertions(+)
 create mode 100644 hw/misc/pvpanic-mmio.c
hw/misc/Kconfig +4 -0
index 1f1baa5dde9..5a6c1603b60 100644
@@ -145,6 +145,10 @@ config PVPANIC_ISA
     depends on ISA_BUS
     select PVPANIC_COMMON
 
+config PVPANIC_MMIO
+    bool
+    select PVPANIC_COMMON
+
 config AUX
     bool
     select I2C
hw/misc/meson.build +1 -0
index d02d96e403b..4de4db0a600 100644
@@ -122,6 +122,7 @@ system_ss.add(when: 'CONFIG_ARMSSE_MHU', if_true: files('armsse-mhu.c'))
 
 system_ss.add(when: 'CONFIG_PVPANIC_ISA', if_true: files('pvpanic-isa.c'))
 system_ss.add(when: 'CONFIG_PVPANIC_PCI', if_true: files('pvpanic-pci.c'))
+system_ss.add(when: 'CONFIG_PVPANIC_MMIO', if_true: files('pvpanic-mmio.c'))
 system_ss.add(when: 'CONFIG_AUX', if_true: files('auxbus.c'))
 system_ss.add(when: 'CONFIG_ASPEED_SOC', if_true: files(
   'aspeed_hace.c',
hw/misc/pvpanic-mmio.c new file +61 -0

61 lines not on this page · raw message

include/hw/misc/pvpanic.h +1 -0
index 9a71a5ad0d7..049a94c1125 100644
@@ -26,6 +26,7 @@
 
 #define TYPE_PVPANIC_ISA_DEVICE "pvpanic"
 #define TYPE_PVPANIC_PCI_DEVICE "pvpanic-pci"
+#define TYPE_PVPANIC_MMIO_DEVICE "pvpanic-mmio"
 
 #define PVPANIC_IOPORT_PROP "ioport"
 
Signature · 1 line
2.39.5 (Apple Git-154)
#16 lore raw

PATCH v11 8/15 hvf: arm: Ignore writes to CNTP_CTL_EL0

In reply to Phil Dennis-Jordan

From: Alexander Graf <[email protected]>

MacOS unconditionally disables interrupts of the physical timer on boot and then continues to use the virtual one. We don't really want to support a full physical timer emulation, so let's just ignore those writes.

---
 target/arm/hvf/hvf.c | 9 +++++++++
 1 file changed, 9 insertions(+)
target/arm/hvf/hvf.c +9 -0
index ca7ea92774a..d75e504dcda 100644
@@ -11,6 +11,7 @@
 
 #include "qemu/osdep.h"
 #include "qemu/error-report.h"
+#include "qemu/log.h"
 
 #include "sysemu/runstate.h"
 #include "sysemu/hvf.h"
@@ -184,6 +185,7 @@ void hvf_arm_init_debug(void)
 #define SYSREG_OSLSR_EL1      SYSREG(2, 0, 1, 1, 4)
 #define SYSREG_OSDLR_EL1      SYSREG(2, 0, 1, 3, 4)
 #define SYSREG_CNTPCT_EL0     SYSREG(3, 3, 14, 0, 1)
+#define SYSREG_CNTP_CTL_EL0   SYSREG(3, 3, 14, 2, 1)
 #define SYSREG_PMCR_EL0       SYSREG(3, 3, 9, 12, 0)
 #define SYSREG_PMUSERENR_EL0  SYSREG(3, 3, 9, 14, 0)
 #define SYSREG_PMCNTENSET_EL0 SYSREG(3, 3, 9, 12, 1)
@@ -1620,6 +1622,13 @@ static int hvf_sysreg_write(CPUState *cpu, uint32_t reg, uint64_t val)
     case SYSREG_OSLAR_EL1:
         env->cp15.oslsr_el1 = val & 1;
         return 0;
+    case SYSREG_CNTP_CTL_EL0:
+        /*
+         * Guests should not rely on the physical counter, but macOS emits
+         * disable writes to it. Let it do so, but ignore the requests.
+         */
+        qemu_log_mask(LOG_UNIMP, "Unsupported write to CNTP_CTL_EL0\n");
+        return 0;
     case SYSREG_OSDLR_EL1:
         /* Dummy register */
         return 0;
Signature · 1 line
2.39.5 (Apple Git-154)
#17 lore raw

PATCH v11 9/15 gpex: Allow more than 4 legacy IRQs

In reply to Phil Dennis-Jordan

From: Alexander Graf <[email protected]>

Some boards such as vmapple don't do real legacy PCI IRQ swizzling. Instead, they just keep allocating more board IRQ lines for each new legacy IRQ. Let's support that mode by giving instantiators a new "nr_irqs" property they can use to support more than 4 legacy IRQ lines. In this mode, GPEX will export more IRQ lines, one for each device.

---

v4:

* Turned pair of IRQ arrays into array of structs.
* Simplified swizzling logic selection.

 hw/arm/sbsa-ref.c          |  2 +-
 hw/arm/virt.c              |  2 +-
 hw/i386/microvm.c          |  2 +-
 hw/loongarch/virt.c        |  2 +-
 hw/mips/loongson3_virt.c   |  2 +-
 hw/openrisc/virt.c         | 12 +++++------
 hw/pci-host/gpex.c         | 43 ++++++++++++++++++++++++++++++--------
 hw/riscv/virt.c            | 12 +++++------
 hw/xtensa/virt.c           |  2 +-
 include/hw/pci-host/gpex.h |  7 +++----
 10 files changed, 55 insertions(+), 31 deletions(-)
hw/arm/sbsa-ref.c +1 -1
index e3195d54497..7e7322486c2 100644
@@ -673,7 +673,7 @@ static void create_pcie(SBSAMachineState *sms)
     /* Map IO port space */
     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 2, base_pio);
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
         sysbus_connect_irq(SYS_BUS_DEVICE(dev), i,
                            qdev_get_gpio_in(sms->gic, irq + i));
         gpex_set_irq_num(GPEX_HOST(dev), i, irq + i);
hw/arm/virt.c +1 -1
index 1a381e9a2bd..8aa22ea3155 100644
@@ -1547,7 +1547,7 @@ static void create_pcie(VirtMachineState *vms)
     /* Map IO port space */
     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 2, base_pio);
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
         sysbus_connect_irq(SYS_BUS_DEVICE(dev), i,
                            qdev_get_gpio_in(vms->gic, irq + i));
         gpex_set_irq_num(GPEX_HOST(dev), i, irq + i);
hw/i386/microvm.c +1 -1
index 86637afa0f3..ce80596c239 100644
@@ -139,7 +139,7 @@ static void create_gpex(MicrovmMachineState *mms)
                                     mms->gpex.mmio64.base, mmio64_alias);
     }
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
         sysbus_connect_irq(SYS_BUS_DEVICE(dev), i,
                            x86ms->gsi[mms->gpex.irq + i]);
     }
hw/loongarch/virt.c +1 -1
index 9a635d1d3d3..50056384994 100644
@@ -741,7 +741,7 @@ static void virt_devices_init(DeviceState *pch_pic,
     memory_region_add_subregion(get_system_memory(), VIRT_PCI_IO_BASE,
                                 pio_alias);
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
         sysbus_connect_irq(d, i,
                            qdev_get_gpio_in(pch_pic, 16 + i));
         gpex_set_irq_num(GPEX_HOST(gpex_dev), i, 16 + i);
hw/mips/loongson3_virt.c +1 -1
index f3b6326cc59..884b5f23a99 100644
@@ -458,7 +458,7 @@ static inline void loongson3_virt_devices_init(MachineState *machine,
                                 virt_memmap[VIRT_PCIE_PIO].base, s->pio_alias);
     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 2, virt_memmap[VIRT_PCIE_PIO].base);
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
         irq = qdev_get_gpio_in(pic, PCIE_IRQ_BASE + i);
         sysbus_connect_irq(SYS_BUS_DEVICE(dev), i, irq);
         gpex_set_irq_num(GPEX_HOST(dev), i, PCIE_IRQ_BASE + i);
hw/openrisc/virt.c +6 -6
index 47d2c9bd3c7..6f053bf48e0 100644
@@ -318,7 +318,7 @@ static void create_pcie_irq_map(void *fdt, char *nodename, int irq_base,
 {
     int pin, dev;
     uint32_t irq_map_stride = 0;
-    uint32_t full_irq_map[GPEX_NUM_IRQS * GPEX_NUM_IRQS * 6] = {};
+    uint32_t full_irq_map[PCI_NUM_PINS * PCI_NUM_PINS * 6] = {};
     uint32_t *irq_map = full_irq_map;
 
     /*
@@ -330,11 +330,11 @@ static void create_pcie_irq_map(void *fdt, char *nodename, int irq_base,
      * possible slot) seeing the interrupt-map-mask will allow the table
      * to wrap to any number of devices.
      */
-    for (dev = 0; dev < GPEX_NUM_IRQS; dev++) {
+    for (dev = 0; dev < PCI_NUM_PINS; dev++) {
         int devfn = dev << 3;
 
-        for (pin = 0; pin < GPEX_NUM_IRQS; pin++) {
-            int irq_nr = irq_base + ((pin + PCI_SLOT(devfn)) % GPEX_NUM_IRQS);
+        for (pin = 0; pin < PCI_NUM_PINS; pin++) {
+            int irq_nr = irq_base + ((pin + PCI_SLOT(devfn)) % PCI_NUM_PINS);
             int i = 0;
 
             /* Fill PCI address cells */
@@ -357,7 +357,7 @@ static void create_pcie_irq_map(void *fdt, char *nodename, int irq_base,
     }
 
     qemu_fdt_setprop(fdt, nodename, "interrupt-map", full_irq_map,
-                     GPEX_NUM_IRQS * GPEX_NUM_IRQS *
+                     PCI_NUM_PINS * PCI_NUM_PINS *
                      irq_map_stride * sizeof(uint32_t));
 
     qemu_fdt_setprop_cells(fdt, nodename, "interrupt-map-mask",
@@ -409,7 +409,7 @@ static void openrisc_virt_pcie_init(OR1KVirtState *state,
     memory_region_add_subregion(get_system_memory(), pio_base, alias);
 
     /* Connect IRQ lines. */
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
         pcie_irq = get_per_cpu_irq(cpus, num_cpus, irq_base + i);
 
         sysbus_connect_irq(SYS_BUS_DEVICE(dev), i, pcie_irq);
hw/pci-host/gpex.c +34 -9

110 lines not on this page · raw message

hw/riscv/virt.c +6 -6
index 45a8c4f8190..567fe92a136 100644
@@ -168,7 +168,7 @@ static void create_pcie_irq_map(RISCVVirtState *s, void *fdt, char *nodename,
 {
     int pin, dev;
     uint32_t irq_map_stride = 0;
-    uint32_t full_irq_map[GPEX_NUM_IRQS * GPEX_NUM_IRQS *
+    uint32_t full_irq_map[PCI_NUM_PINS * PCI_NUM_PINS *
                           FDT_MAX_INT_MAP_WIDTH] = {};
     uint32_t *irq_map = full_irq_map;
 
@@ -180,11 +180,11 @@ static void create_pcie_irq_map(RISCVVirtState *s, void *fdt, char *nodename,
      * possible slot) seeing the interrupt-map-mask will allow the table
      * to wrap to any number of devices.
      */
-    for (dev = 0; dev < GPEX_NUM_IRQS; dev++) {
+    for (dev = 0; dev < PCI_NUM_PINS; dev++) {
         int devfn = dev * 0x8;
 
-        for (pin = 0; pin < GPEX_NUM_IRQS; pin++) {
-            int irq_nr = PCIE_IRQ + ((pin + PCI_SLOT(devfn)) % GPEX_NUM_IRQS);
+        for (pin = 0; pin < PCI_NUM_PINS; pin++) {
+            int irq_nr = PCIE_IRQ + ((pin + PCI_SLOT(devfn)) % PCI_NUM_PINS);
             int i = 0;
 
             /* Fill PCI address cells */
@@ -210,7 +210,7 @@ static void create_pcie_irq_map(RISCVVirtState *s, void *fdt, char *nodename,
     }
 
     qemu_fdt_setprop(fdt, nodename, "interrupt-map", full_irq_map,
-                     GPEX_NUM_IRQS * GPEX_NUM_IRQS *
+                     PCI_NUM_PINS * PCI_NUM_PINS *
                      irq_map_stride * sizeof(uint32_t));
 
     qemu_fdt_setprop_cells(fdt, nodename, "interrupt-map-mask",
@@ -1182,7 +1182,7 @@ static inline DeviceState *gpex_pcie_init(MemoryRegion *sys_mem,
 
     sysbus_mmio_map(SYS_BUS_DEVICE(dev), 2, pio_base);
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
         irq = qdev_get_gpio_in(irqchip, PCIE_IRQ + i);
 
         sysbus_connect_irq(SYS_BUS_DEVICE(dev), i, irq);
hw/xtensa/virt.c +1 -1
index 5310a888613..8f5c2009d29 100644
@@ -93,7 +93,7 @@ static void create_pcie(MachineState *ms, CPUXtensaState *env, int irq_base,
     /* Connect IRQ lines. */
     extints = xtensa_get_extints(env);
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
         void *q = extints[irq_base + i];
 
         sysbus_connect_irq(SYS_BUS_DEVICE(dev), i, q);
include/hw/pci-host/gpex.h +3 -4
index dce883573ba..84471533af0 100644
@@ -32,8 +32,6 @@ OBJECT_DECLARE_SIMPLE_TYPE(GPEXHost, GPEX_HOST)
 #define TYPE_GPEX_ROOT_DEVICE "gpex-root"
 OBJECT_DECLARE_SIMPLE_TYPE(GPEXRootState, GPEX_ROOT_DEVICE)
 
-#define GPEX_NUM_IRQS 4
-
 struct GPEXRootState {
     /*< private >*/
     PCIDevice parent_obj;
@@ -49,6 +47,7 @@ struct GPEXConfig {
     PCIBus      *bus;
 };
 
+typedef struct GPEXIrq GPEXIrq;
 struct GPEXHost {
     /*< private >*/
     PCIExpressHost parent_obj;
@@ -60,8 +59,8 @@ struct GPEXHost {
     MemoryRegion io_mmio;
     MemoryRegion io_ioport_window;
     MemoryRegion io_mmio_window;
-    qemu_irq irq[GPEX_NUM_IRQS];
-    int irq_num[GPEX_NUM_IRQS];
+    GPEXIrq *irq;
+    uint8_t num_irqs;
 
     bool allow_unmapped_accesses;
 
Signature · 1 line
2.39.5 (Apple Git-154)
#18 lore raw

Re: [PATCH v11 09/15] gpex: Allow more than 4 legacy IRQs

Quoted 325 lines · Phil Dennis-Jordan

From: Alexander Graf <[email protected]>

Some boards such as vmapple don't do real legacy PCI IRQ swizzling. Instead, they just keep allocating more board IRQ lines for each new legacy IRQ. Let's support that mode by giving instantiators a new "nr_irqs" property they can use to support more than 4 legacy IRQ lines. In this mode, GPEX will export more IRQ lines, one for each device.

v4:

* Turned pair of IRQ arrays into array of structs.
* Simplified swizzling logic selection.

  hw/arm/sbsa-ref.c          |  2 +-
  hw/arm/virt.c              |  2 +-
  hw/i386/microvm.c          |  2 +-
  hw/loongarch/virt.c        |  2 +-
  hw/mips/loongson3_virt.c   |  2 +-
  hw/openrisc/virt.c         | 12 +++++------
  hw/pci-host/gpex.c         | 43 ++++++++++++++++++++++++++++++--------
  hw/riscv/virt.c            | 12 +++++------
  hw/xtensa/virt.c           |  2 +-
  include/hw/pci-host/gpex.h |  7 +++----
  10 files changed, 55 insertions(+), 31 deletions(-)
hw/arm/sbsa-ref.c +1 -1
index e3195d54497..7e7322486c2 100644
@@ -673,7 +673,7 @@ static void create_pcie(SBSAMachineState *sms)
      /* Map IO port space */
      sysbus_mmio_map(SYS_BUS_DEVICE(dev), 2, base_pio);
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
          sysbus_connect_irq(SYS_BUS_DEVICE(dev), i,
                             qdev_get_gpio_in(sms->gic, irq + i));
          gpex_set_irq_num(GPEX_HOST(dev), i, irq + i);
hw/arm/virt.c +1 -1
index 1a381e9a2bd..8aa22ea3155 100644
@@ -1547,7 +1547,7 @@ static void create_pcie(VirtMachineState *vms)
      /* Map IO port space */
      sysbus_mmio_map(SYS_BUS_DEVICE(dev), 2, base_pio);
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
          sysbus_connect_irq(SYS_BUS_DEVICE(dev), i,
                             qdev_get_gpio_in(vms->gic, irq + i));
          gpex_set_irq_num(GPEX_HOST(dev), i, irq + i);
hw/i386/microvm.c +1 -1
index 86637afa0f3..ce80596c239 100644
@@ -139,7 +139,7 @@ static void create_gpex(MicrovmMachineState *mms)
                                      mms->gpex.mmio64.base, mmio64_alias);
      }
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
          sysbus_connect_irq(SYS_BUS_DEVICE(dev), i,
                             x86ms->gsi[mms->gpex.irq + i]);
      }
hw/loongarch/virt.c +1 -1
index 9a635d1d3d3..50056384994 100644
@@ -741,7 +741,7 @@ static void virt_devices_init(DeviceState *pch_pic,
      memory_region_add_subregion(get_system_memory(), VIRT_PCI_IO_BASE,
                                  pio_alias);
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
          sysbus_connect_irq(d, i,
                             qdev_get_gpio_in(pch_pic, 16 + i));
          gpex_set_irq_num(GPEX_HOST(gpex_dev), i, 16 + i);
hw/mips/loongson3_virt.c +1 -1
index f3b6326cc59..884b5f23a99 100644
@@ -458,7 +458,7 @@ static inline void loongson3_virt_devices_init(MachineState *machine,
                                  virt_memmap[VIRT_PCIE_PIO].base, s->pio_alias);
      sysbus_mmio_map(SYS_BUS_DEVICE(dev), 2, virt_memmap[VIRT_PCIE_PIO].base);
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
          irq = qdev_get_gpio_in(pic, PCIE_IRQ_BASE + i);
          sysbus_connect_irq(SYS_BUS_DEVICE(dev), i, irq);
          gpex_set_irq_num(GPEX_HOST(dev), i, PCIE_IRQ_BASE + i);
hw/openrisc/virt.c +6 -6
index 47d2c9bd3c7..6f053bf48e0 100644
@@ -318,7 +318,7 @@ static void create_pcie_irq_map(void *fdt, char *nodename, int irq_base,
  {
      int pin, dev;
      uint32_t irq_map_stride = 0;
-    uint32_t full_irq_map[GPEX_NUM_IRQS * GPEX_NUM_IRQS * 6] = {};
+    uint32_t full_irq_map[PCI_NUM_PINS * PCI_NUM_PINS * 6] = {};
      uint32_t *irq_map = full_irq_map;
 
      /*
@@ -330,11 +330,11 @@ static void create_pcie_irq_map(void *fdt, char *nodename, int irq_base,
       * possible slot) seeing the interrupt-map-mask will allow the table
       * to wrap to any number of devices.
       */
-    for (dev = 0; dev < GPEX_NUM_IRQS; dev++) {
+    for (dev = 0; dev < PCI_NUM_PINS; dev++) {
          int devfn = dev << 3;
 
-        for (pin = 0; pin < GPEX_NUM_IRQS; pin++) {
-            int irq_nr = irq_base + ((pin + PCI_SLOT(devfn)) % GPEX_NUM_IRQS);
+        for (pin = 0; pin < PCI_NUM_PINS; pin++) {
+            int irq_nr = irq_base + ((pin + PCI_SLOT(devfn)) % PCI_NUM_PINS);
              int i = 0;
 
              /* Fill PCI address cells */
@@ -357,7 +357,7 @@ static void create_pcie_irq_map(void *fdt, char *nodename, int irq_base,
      }
 
      qemu_fdt_setprop(fdt, nodename, "interrupt-map", full_irq_map,
-                     GPEX_NUM_IRQS * GPEX_NUM_IRQS *
+                     PCI_NUM_PINS * PCI_NUM_PINS *
                       irq_map_stride * sizeof(uint32_t));
 
      qemu_fdt_setprop_cells(fdt, nodename, "interrupt-map-mask",
@@ -409,7 +409,7 @@ static void openrisc_virt_pcie_init(OR1KVirtState *state,
      memory_region_add_subregion(get_system_memory(), pio_base, alias);
 
      /* Connect IRQ lines. */
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
          pcie_irq = get_per_cpu_irq(cpus, num_cpus, irq_base + i);
 
          sysbus_connect_irq(SYS_BUS_DEVICE(dev), i, pcie_irq);
hw/pci-host/gpex.c +34 -9
index e9cf455bf52..cd63aa2d3cf 100644
@@ -32,6 +32,7 @@
  #include "qemu/osdep.h"
  #include "qapi/error.h"
  #include "hw/irq.h"
+#include "hw/pci/pci_bus.h"
  #include "hw/pci-host/gpex.h"
  #include "hw/qdev-properties.h"
  #include "migration/vmstate.h"
@@ -41,20 +42,25 @@
   * GPEX host
   */
 
+struct GPEXIrq {
+    qemu_irq irq;
+    int irq_num;
+};
+
  static void gpex_set_irq(void *opaque, int irq_num, int level)
  {
      GPEXHost *s = opaque;
 
-    qemu_set_irq(s->irq[irq_num], level);
+    qemu_set_irq(s->irq[irq_num].irq, level);
  }
 
  int gpex_set_irq_num(GPEXHost *s, int index, int gsi)
  {
-    if (index >= GPEX_NUM_IRQS) {
+    if (index >= s->num_irqs) {
          return -EINVAL;
      }
 
-    s->irq_num[index] = gsi;
+    s->irq[index].irq_num = gsi;
      return 0;
  }
 
@@ -62,7 +68,7 @@ static PCIINTxRoute gpex_route_intx_pin_to_irq(void *opaque, int pin)
  {
      PCIINTxRoute route;
      GPEXHost *s = opaque;
-    int gsi = s->irq_num[pin];
+    int gsi = s->irq[pin].irq_num;
 
      route.irq = gsi;
      if (gsi < 0) {
@@ -74,6 +80,13 @@ static PCIINTxRoute gpex_route_intx_pin_to_irq(void *opaque, int pin)
      return route;
  }
 
+static int gpex_swizzle_map_irq_fn(PCIDevice *pci_dev, int pin)
+{
+    PCIBus *bus = pci_device_root_bus(pci_dev);
+
+    return (PCI_SLOT(pci_dev->devfn) + pin) % bus->nirq;
+}
+
  static void gpex_host_realize(DeviceState *dev, Error **errp)
  {
      PCIHostState *pci = PCI_HOST_BRIDGE(dev);
@@ -82,6 +95,8 @@ static void gpex_host_realize(DeviceState *dev, Error **errp)
      PCIExpressHost *pex = PCIE_HOST_BRIDGE(dev);
      int i;
 
+    s->irq = g_malloc0_n(s->num_irqs, sizeof(*s->irq));
+
      pcie_host_mmcfg_init(pex, PCIE_MMCFG_SIZE_MAX);
      sysbus_init_mmio(sbd, &pex->mmio);
 
@@ -128,19 +143,27 @@ static void gpex_host_realize(DeviceState *dev, Error **errp)
          sysbus_init_mmio(sbd, &s->io_ioport);
      }
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
-        sysbus_init_irq(sbd, &s->irq[i]);
-        s->irq_num[i] = -1;
+    for (i = 0; i < s->num_irqs; i++) {
+        sysbus_init_irq(sbd, &s->irq[i].irq);
+        s->irq[i].irq_num = -1;
      }
 
      pci->bus = pci_register_root_bus(dev, "pcie.0", gpex_set_irq,
-                                     pci_swizzle_map_irq_fn, s, &s->io_mmio,
-                                     &s->io_ioport, 0, 4, TYPE_PCIE_BUS);
+                                     gpex_swizzle_map_irq_fn,
+                                     s, &s->io_mmio, &s->io_ioport, 0,
+                                     s->num_irqs, TYPE_PCIE_BUS);
 
      pci_bus_set_route_irq_fn(pci->bus, gpex_route_intx_pin_to_irq);
      qdev_realize(DEVICE(&s->gpex_root), BUS(pci->bus), &error_fatal);
  }
 
+static void gpex_host_unrealize(DeviceState *dev)
+{
+    GPEXHost *s = GPEX_HOST(dev);
+
+    g_free(s->irq);
+}
+
  static const char *gpex_host_root_bus_path(PCIHostState *host_bridge,
                                            PCIBus *rootbus)
  {
@@ -166,6 +189,7 @@ static Property gpex_host_properties[] = {
                         gpex_cfg.mmio64.base, 0),
      DEFINE_PROP_SIZE(PCI_HOST_ABOVE_4G_MMIO_SIZE, GPEXHost,
                       gpex_cfg.mmio64.size, 0),
+    DEFINE_PROP_UINT8("num-irqs", GPEXHost, num_irqs, PCI_NUM_PINS),
      DEFINE_PROP_END_OF_LIST(),
  };
 
@@ -176,6 +200,7 @@ static void gpex_host_class_init(ObjectClass *klass, void *data)
 
      hc->root_bus_path = gpex_host_root_bus_path;
      dc->realize = gpex_host_realize;
+    dc->unrealize = gpex_host_unrealize;
      set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);
      dc->fw_name = "pci";
      device_class_set_props(dc, gpex_host_properties);
hw/riscv/virt.c +6 -6
index 45a8c4f8190..567fe92a136 100644
@@ -168,7 +168,7 @@ static void create_pcie_irq_map(RISCVVirtState *s, void *fdt, char *nodename,
  {
      int pin, dev;
      uint32_t irq_map_stride = 0;
-    uint32_t full_irq_map[GPEX_NUM_IRQS * GPEX_NUM_IRQS *
+    uint32_t full_irq_map[PCI_NUM_PINS * PCI_NUM_PINS *
                            FDT_MAX_INT_MAP_WIDTH] = {};
      uint32_t *irq_map = full_irq_map;
 
@@ -180,11 +180,11 @@ static void create_pcie_irq_map(RISCVVirtState *s, void *fdt, char *nodename,
       * possible slot) seeing the interrupt-map-mask will allow the table
       * to wrap to any number of devices.
       */
-    for (dev = 0; dev < GPEX_NUM_IRQS; dev++) {
+    for (dev = 0; dev < PCI_NUM_PINS; dev++) {
          int devfn = dev * 0x8;
 
-        for (pin = 0; pin < GPEX_NUM_IRQS; pin++) {
-            int irq_nr = PCIE_IRQ + ((pin + PCI_SLOT(devfn)) % GPEX_NUM_IRQS);
+        for (pin = 0; pin < PCI_NUM_PINS; pin++) {
+            int irq_nr = PCIE_IRQ + ((pin + PCI_SLOT(devfn)) % PCI_NUM_PINS);
              int i = 0;
 
              /* Fill PCI address cells */
@@ -210,7 +210,7 @@ static void create_pcie_irq_map(RISCVVirtState *s, void *fdt, char *nodename,
      }
 
      qemu_fdt_setprop(fdt, nodename, "interrupt-map", full_irq_map,
-                     GPEX_NUM_IRQS * GPEX_NUM_IRQS *
+                     PCI_NUM_PINS * PCI_NUM_PINS *
                       irq_map_stride * sizeof(uint32_t));
 
      qemu_fdt_setprop_cells(fdt, nodename, "interrupt-map-mask",
@@ -1182,7 +1182,7 @@ static inline DeviceState *gpex_pcie_init(MemoryRegion *sys_mem,
 
      sysbus_mmio_map(SYS_BUS_DEVICE(dev), 2, pio_base);
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
          irq = qdev_get_gpio_in(irqchip, PCIE_IRQ + i);
 
          sysbus_connect_irq(SYS_BUS_DEVICE(dev), i, irq);
hw/xtensa/virt.c +1 -1
index 5310a888613..8f5c2009d29 100644
@@ -93,7 +93,7 @@ static void create_pcie(MachineState *ms, CPUXtensaState *env, int irq_base,
      /* Connect IRQ lines. */
      extints = xtensa_get_extints(env);
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
          void *q = extints[irq_base + i];
 
          sysbus_connect_irq(SYS_BUS_DEVICE(dev), i, q);
include/hw/pci-host/gpex.h +0 -0
index dce883573ba..84471533af0 100644

include/hw/pci-host/gpex.h OBJECT_DECLARE_SIMPLE_TYPE(GPEXHost, GPEX_HOST) · line 35

Quoted 4 lines
include/hw/pci-host/gpex.h +0 -1
@@ -32,8 +32,6 @@ OBJECT_DECLARE_SIMPLE_TYPE(GPEXHost, GPEX_HOST)
  #define TYPE_GPEX_ROOT_DEVICE "gpex-root"
  OBJECT_DECLARE_SIMPLE_TYPE(GPEXRootState, GPEX_ROOT_DEVICE)
 
-#define GPEX_NUM_IRQS 4

I found some references to GPEX_NUM_IRQS still remain:

$ git grep GPEX_NUM_IRQS
hw/loongarch/virt.c:    uint32_t full_irq_map[GPEX_NUM_IRQS *GPEX_NUM_IRQS * 10] = {};
hw/loongarch/virt.c:    for (dev = 0; dev < GPEX_NUM_IRQS; dev++) {
hw/loongarch/virt.c:        for (pin = 0; pin  < GPEX_NUM_IRQS; pin++) {
hw/loongarch/virt.c:            int irq_nr = 16 + ((pin + PCI_SLOT(devfn)) % GPEX_NUM_IRQS);
hw/loongarch/virt.c:                     GPEX_NUM_IRQS * GPEX_NUM_IRQS *
hw/vmapple/vmapple.c:#define GPEX_NUM_IRQS 16
hw/vmapple/vmapple.c:    qdev_prop_set_uint32(dev, "num-irqs", GPEX_NUM_IRQS);
hw/vmapple/vmapple.c:    for (i = 0; i < GPEX_NUM_IRQS; i++) {
hw/xen/xen-pvh-common.c:    for (i = 0; i < GPEX_NUM_IRQS; i++) {
Quoted 23 lines
include/hw/pci-host/gpex.h +3 -3
-
  struct GPEXRootState {
      /*< private >*/
      PCIDevice parent_obj;
@@ -49,6 +47,7 @@ struct GPEXConfig {
      PCIBus      *bus;
  };
 
+typedef struct GPEXIrq GPEXIrq;
  struct GPEXHost {
      /*< private >*/
      PCIExpressHost parent_obj;
@@ -60,8 +59,8 @@ struct GPEXHost {
      MemoryRegion io_mmio;
      MemoryRegion io_ioport_window;
      MemoryRegion io_mmio_window;
-    qemu_irq irq[GPEX_NUM_IRQS];
-    int irq_num[GPEX_NUM_IRQS];
+    GPEXIrq *irq;
+    uint8_t num_irqs;
 
      bool allow_unmapped_accesses;
 
#19 lore raw

Re: [PATCH v11 09/15] gpex: Allow more than 4 legacy IRQs

Quoted 359 lines · Akihiko Odaki
Quoted 59 lines · Phil Dennis-Jordan

From: Alexander Graf <[email protected]>

Some boards such as vmapple don't do real legacy PCI IRQ swizzling. Instead, they just keep allocating more board IRQ lines for each new legacy IRQ. Let's support that mode by giving instantiators a new "nr_irqs" property they can use to support more than 4 legacy IRQ lines. In this mode, GPEX will export more IRQ lines, one for each device.

v4:

* Turned pair of IRQ arrays into array of structs.
* Simplified swizzling logic selection.

  hw/arm/sbsa-ref.c          |  2 +-
  hw/arm/virt.c              |  2 +-
  hw/i386/microvm.c          |  2 +-
  hw/loongarch/virt.c        |  2 +-
  hw/mips/loongson3_virt.c   |  2 +-
  hw/openrisc/virt.c         | 12 +++++------
  hw/pci-host/gpex.c         | 43 ++++++++++++++++++++++++++++++--------
  hw/riscv/virt.c            | 12 +++++------
  hw/xtensa/virt.c           |  2 +-
  include/hw/pci-host/gpex.h |  7 +++----
  10 files changed, 55 insertions(+), 31 deletions(-)
hw/arm/sbsa-ref.c +1 -1
index e3195d54497..7e7322486c2 100644
@@ -673,7 +673,7 @@ static void create_pcie(SBSAMachineState *sms)
      /* Map IO port space */
      sysbus_mmio_map(SYS_BUS_DEVICE(dev), 2, base_pio);
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
          sysbus_connect_irq(SYS_BUS_DEVICE(dev), i,
                             qdev_get_gpio_in(sms->gic, irq + i));
          gpex_set_irq_num(GPEX_HOST(dev), i, irq + i);
hw/arm/virt.c +1 -1
index 1a381e9a2bd..8aa22ea3155 100644
@@ -1547,7 +1547,7 @@ static void create_pcie(VirtMachineState *vms)
      /* Map IO port space */
      sysbus_mmio_map(SYS_BUS_DEVICE(dev), 2, base_pio);
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
          sysbus_connect_irq(SYS_BUS_DEVICE(dev), i,
                             qdev_get_gpio_in(vms->gic, irq + i));
          gpex_set_irq_num(GPEX_HOST(dev), i, irq + i);
hw/i386/microvm.c +0 -0
index 86637afa0f3..ce80596c239 100644

hw/i386/microvm.c static void create_gpex(MicrovmMachineState *mms) · line 139

Quoted 1 line
hw/i386/microvm.c +0 -0
@@ -139,7 +139,7 @@ static void create_gpex(MicrovmMachineState *mms)
                                      mms->gpex.mmio64.base,

mmio64_alias);

hw/mips/loongson3_virt.c static inline void

Quoted 25 lines
hw/i386/microvm.c +1 -1
      }
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
          sysbus_connect_irq(SYS_BUS_DEVICE(dev), i,
                             x86ms->gsi[mms->gpex.irq + i]);
      }
hw/loongarch/virt.c +1 -1
index 9a635d1d3d3..50056384994 100644
@@ -741,7 +741,7 @@ static void virt_devices_init(DeviceState *pch_pic,
      memory_region_add_subregion(get_system_memory(), VIRT_PCI_IO_BASE,
                                  pio_alias);
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
          sysbus_connect_irq(d, i,
                             qdev_get_gpio_in(pch_pic, 16 + i));
          gpex_set_irq_num(GPEX_HOST(gpex_dev), i, 16 + i);
hw/mips/loongson3_virt.c +0 -0
index f3b6326cc59..884b5f23a99 100644
@@ -458,7 +458,7 @@ static inline void

loongson3_virt_devices_init(MachineState *machine,

hw/mips/loongson3_virt.c static inline void · line 458

Quoted 1 line
hw/mips/loongson3_virt.c +0 -0
                                  virt_memmap[VIRT_PCIE_PIO].base,

s->pio_alias);

hw/mips/loongson3_virt.c static inline void · line 459

Quoted 1 line
hw/mips/loongson3_virt.c +0 -0
      sysbus_mmio_map(SYS_BUS_DEVICE(dev), 2,

virt_memmap[VIRT_PCIE_PIO].base);

hw/openrisc/virt.c static void create_pcie_irq_map(void *fdt, char

Quoted 11 lines
hw/mips/loongson3_virt.c +1 -1
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
          irq = qdev_get_gpio_in(pic, PCIE_IRQ_BASE + i);
          sysbus_connect_irq(SYS_BUS_DEVICE(dev), i, irq);
          gpex_set_irq_num(GPEX_HOST(dev), i, PCIE_IRQ_BASE + i);
hw/openrisc/virt.c +0 -0
index 47d2c9bd3c7..6f053bf48e0 100644
@@ -318,7 +318,7 @@ static void create_pcie_irq_map(void *fdt, char

*nodename, int irq_base,

hw/openrisc/virt.c static void create_pcie_irq_map(void *fdt, char

Quoted 9 lines
hw/openrisc/virt.c +1 -1
  {
      int pin, dev;
      uint32_t irq_map_stride = 0;
-    uint32_t full_irq_map[GPEX_NUM_IRQS * GPEX_NUM_IRQS * 6] = {};
+    uint32_t full_irq_map[PCI_NUM_PINS * PCI_NUM_PINS * 6] = {};
      uint32_t *irq_map = full_irq_map;
 
      /*
@@ -330,11 +330,11 @@ static void create_pcie_irq_map(void *fdt, char

*nodename, int irq_base,

hw/openrisc/virt.c static void create_pcie_irq_map(void *fdt, char · line 330

Quoted 1 line
hw/openrisc/virt.c +0 -0
       * possible slot) seeing the interrupt-map-mask will allow the

table

hw/openrisc/virt.c static void create_pcie_irq_map(void *fdt, char *nodename, int irq_base,

Quoted 8 lines
hw/openrisc/virt.c +1 -3
       * to wrap to any number of devices.
       */
-    for (dev = 0; dev < GPEX_NUM_IRQS; dev++) {
+    for (dev = 0; dev < PCI_NUM_PINS; dev++) {
          int devfn = dev << 3;
 
-        for (pin = 0; pin < GPEX_NUM_IRQS; pin++) {
-            int irq_nr = irq_base + ((pin + PCI_SLOT(devfn)) %

GPEX_NUM_IRQS);

hw/openrisc/virt.c static void create_pcie_irq_map(void *fdt, char · line 337

Quoted 2 lines
hw/openrisc/virt.c +2 -0
+        for (pin = 0; pin < PCI_NUM_PINS; pin++) {
+            int irq_nr = irq_base + ((pin + PCI_SLOT(devfn)) %

PCI_NUM_PINS);

hw/openrisc/virt.c static void create_pcie_irq_map(void *fdt, char

Quoted 4 lines
hw/openrisc/virt.c +0 -0
              int i = 0;
 
              /* Fill PCI address cells */
@@ -357,7 +357,7 @@ static void create_pcie_irq_map(void *fdt, char

*nodename, int irq_base,

hw/openrisc/virt.c static void openrisc_virt_pcie_init(OR1KVirtState

Quoted 9 lines
hw/openrisc/virt.c +1 -1
      }
 
      qemu_fdt_setprop(fdt, nodename, "interrupt-map", full_irq_map,
-                     GPEX_NUM_IRQS * GPEX_NUM_IRQS *
+                     PCI_NUM_PINS * PCI_NUM_PINS *
                       irq_map_stride * sizeof(uint32_t));
 
      qemu_fdt_setprop_cells(fdt, nodename, "interrupt-map-mask",
@@ -409,7 +409,7 @@ static void openrisc_virt_pcie_init(OR1KVirtState

*state,

hw/pci-host/gpex.c static PCIINTxRoute gpex_route_intx_pin_to_irq(void

Quoted 50 lines
hw/openrisc/virt.c +1 -1
      memory_region_add_subregion(get_system_memory(), pio_base, alias);
 
      /* Connect IRQ lines. */
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
          pcie_irq = get_per_cpu_irq(cpus, num_cpus, irq_base + i);
 
          sysbus_connect_irq(SYS_BUS_DEVICE(dev), i, pcie_irq);
hw/pci-host/gpex.c +9 -3
index e9cf455bf52..cd63aa2d3cf 100644
@@ -32,6 +32,7 @@
  #include "qemu/osdep.h"
  #include "qapi/error.h"
  #include "hw/irq.h"
+#include "hw/pci/pci_bus.h"
  #include "hw/pci-host/gpex.h"
  #include "hw/qdev-properties.h"
  #include "migration/vmstate.h"
@@ -41,20 +42,25 @@
   * GPEX host
   */
 
+struct GPEXIrq {
+    qemu_irq irq;
+    int irq_num;
+};
+
  static void gpex_set_irq(void *opaque, int irq_num, int level)
  {
      GPEXHost *s = opaque;
 
-    qemu_set_irq(s->irq[irq_num], level);
+    qemu_set_irq(s->irq[irq_num].irq, level);
  }
 
  int gpex_set_irq_num(GPEXHost *s, int index, int gsi)
  {
-    if (index >= GPEX_NUM_IRQS) {
+    if (index >= s->num_irqs) {
          return -EINVAL;
      }
 
-    s->irq_num[index] = gsi;
+    s->irq[index].irq_num = gsi;
      return 0;
  }
 
@@ -62,7 +68,7 @@ static PCIINTxRoute gpex_route_intx_pin_to_irq(void

*opaque, int pin)

hw/pci-host/gpex.c static PCIINTxRoute gpex_route_intx_pin_to_irq(void

Quoted 9 lines
hw/pci-host/gpex.c +1 -1
  {
      PCIINTxRoute route;
      GPEXHost *s = opaque;
-    int gsi = s->irq_num[pin];
+    int gsi = s->irq[pin].irq_num;
 
      route.irq = gsi;
      if (gsi < 0) {
@@ -74,6 +80,13 @@ static PCIINTxRoute gpex_route_intx_pin_to_irq(void

*opaque, int pin)

hw/pci-host/gpex.c static void gpex_host_realize(DeviceState *dev, Error

Quoted 14 lines
hw/pci-host/gpex.c +7 -0
      return route;
  }
 
+static int gpex_swizzle_map_irq_fn(PCIDevice *pci_dev, int pin)
+{
+    PCIBus *bus = pci_device_root_bus(pci_dev);
+
+    return (PCI_SLOT(pci_dev->devfn) + pin) % bus->nirq;
+}
+
  static void gpex_host_realize(DeviceState *dev, Error **errp)
  {
      PCIHostState *pci = PCI_HOST_BRIDGE(dev);
@@ -82,6 +95,8 @@ static void gpex_host_realize(DeviceState *dev, Error

**errp)

hw/pci-host/gpex.c static void gpex_host_realize(DeviceState *dev,

Quoted 9 lines
hw/pci-host/gpex.c +2 -0
      PCIExpressHost *pex = PCIE_HOST_BRIDGE(dev);
      int i;
 
+    s->irq = g_malloc0_n(s->num_irqs, sizeof(*s->irq));
+
      pcie_host_mmcfg_init(pex, PCIE_MMCFG_SIZE_MAX);
      sysbus_init_mmio(sbd, &pex->mmio);
 
@@ -128,19 +143,27 @@ static void gpex_host_realize(DeviceState *dev,

Error **errp)

hw/pci-host/gpex.c static void gpex_host_realize(DeviceState *dev, Error **errp)

Quoted 13 lines
hw/pci-host/gpex.c +3 -4
          sysbus_init_mmio(sbd, &s->io_ioport);
      }
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
-        sysbus_init_irq(sbd, &s->irq[i]);
-        s->irq_num[i] = -1;
+    for (i = 0; i < s->num_irqs; i++) {
+        sysbus_init_irq(sbd, &s->irq[i].irq);
+        s->irq[i].irq_num = -1;
      }
 
      pci->bus = pci_register_root_bus(dev, "pcie.0", gpex_set_irq,
-                                     pci_swizzle_map_irq_fn, s,

&s->io_mmio,

hw/pci-host/gpex.c static void gpex_host_realize(DeviceState *dev, · line 138

Quoted 1 line
hw/pci-host/gpex.c +0 -1
-                                     &s->io_ioport, 0, 4,

TYPE_PCIE_BUS);

hw/pci-host/gpex.c static void gpex_host_class_init(ObjectClass *klass,

Quoted 27 lines
hw/pci-host/gpex.c +11 -0
+                                     gpex_swizzle_map_irq_fn,
+                                     s, &s->io_mmio, &s->io_ioport, 0,
+                                     s->num_irqs, TYPE_PCIE_BUS);
 
      pci_bus_set_route_irq_fn(pci->bus, gpex_route_intx_pin_to_irq);
      qdev_realize(DEVICE(&s->gpex_root), BUS(pci->bus), &error_fatal);
  }
 
+static void gpex_host_unrealize(DeviceState *dev)
+{
+    GPEXHost *s = GPEX_HOST(dev);
+
+    g_free(s->irq);
+}
+
  static const char *gpex_host_root_bus_path(PCIHostState *host_bridge,
                                            PCIBus *rootbus)
  {
@@ -166,6 +189,7 @@ static Property gpex_host_properties[] = {
                         gpex_cfg.mmio64.base, 0),
      DEFINE_PROP_SIZE(PCI_HOST_ABOVE_4G_MMIO_SIZE, GPEXHost,
                       gpex_cfg.mmio64.size, 0),
+    DEFINE_PROP_UINT8("num-irqs", GPEXHost, num_irqs, PCI_NUM_PINS),
      DEFINE_PROP_END_OF_LIST(),
  };
 
@@ -176,6 +200,7 @@ static void gpex_host_class_init(ObjectClass *klass,

void *data)

hw/riscv/virt.c static void create_pcie_irq_map(RISCVVirtState *s,

Quoted 12 lines
hw/pci-host/gpex.c +1 -0
      hc->root_bus_path = gpex_host_root_bus_path;
      dc->realize = gpex_host_realize;
+    dc->unrealize = gpex_host_unrealize;
      set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories);
      dc->fw_name = "pci";
      device_class_set_props(dc, gpex_host_properties);
hw/riscv/virt.c +0 -0
index 45a8c4f8190..567fe92a136 100644
@@ -168,7 +168,7 @@ static void create_pcie_irq_map(RISCVVirtState *s,

void *fdt, char *nodename,

hw/riscv/virt.c static void create_pcie_irq_map(RISCVVirtState *s,

Quoted 9 lines
hw/riscv/virt.c +1 -1
  {
      int pin, dev;
      uint32_t irq_map_stride = 0;
-    uint32_t full_irq_map[GPEX_NUM_IRQS * GPEX_NUM_IRQS *
+    uint32_t full_irq_map[PCI_NUM_PINS * PCI_NUM_PINS *
                            FDT_MAX_INT_MAP_WIDTH] = {};
      uint32_t *irq_map = full_irq_map;
 
@@ -180,11 +180,11 @@ static void create_pcie_irq_map(RISCVVirtState *s,

void *fdt, char *nodename,

hw/riscv/virt.c static void create_pcie_irq_map(RISCVVirtState *s, · line 180

Quoted 1 line
hw/riscv/virt.c +0 -0
       * possible slot) seeing the interrupt-map-mask will allow the

table

hw/riscv/virt.c static void create_pcie_irq_map(RISCVVirtState *s, void *fdt, char *nodename,

Quoted 8 lines
hw/riscv/virt.c +1 -3
       * to wrap to any number of devices.
       */
-    for (dev = 0; dev < GPEX_NUM_IRQS; dev++) {
+    for (dev = 0; dev < PCI_NUM_PINS; dev++) {
          int devfn = dev * 0x8;
 
-        for (pin = 0; pin < GPEX_NUM_IRQS; pin++) {
-            int irq_nr = PCIE_IRQ + ((pin + PCI_SLOT(devfn)) %

GPEX_NUM_IRQS);

hw/riscv/virt.c static void create_pcie_irq_map(RISCVVirtState *s, · line 187

Quoted 2 lines
hw/riscv/virt.c +2 -0
+        for (pin = 0; pin < PCI_NUM_PINS; pin++) {
+            int irq_nr = PCIE_IRQ + ((pin + PCI_SLOT(devfn)) %

PCI_NUM_PINS);

hw/riscv/virt.c static void create_pcie_irq_map(RISCVVirtState *s,

Quoted 4 lines
hw/riscv/virt.c +0 -0
              int i = 0;
 
              /* Fill PCI address cells */
@@ -210,7 +210,7 @@ static void create_pcie_irq_map(RISCVVirtState *s,

void *fdt, char *nodename,

hw/riscv/virt.c static inline DeviceState

Quoted 9 lines
hw/riscv/virt.c +1 -1
      }
 
      qemu_fdt_setprop(fdt, nodename, "interrupt-map", full_irq_map,
-                     GPEX_NUM_IRQS * GPEX_NUM_IRQS *
+                     PCI_NUM_PINS * PCI_NUM_PINS *
                       irq_map_stride * sizeof(uint32_t));
 
      qemu_fdt_setprop_cells(fdt, nodename, "interrupt-map-mask",
@@ -1182,7 +1182,7 @@ static inline DeviceState

*gpex_pcie_init(MemoryRegion *sys_mem,

hw/xtensa/virt.c static void create_pcie(MachineState *ms,

Quoted 13 lines
hw/riscv/virt.c +1 -1
      sysbus_mmio_map(SYS_BUS_DEVICE(dev), 2, pio_base);
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
          irq = qdev_get_gpio_in(irqchip, PCIE_IRQ + i);
 
          sysbus_connect_irq(SYS_BUS_DEVICE(dev), i, irq);
hw/xtensa/virt.c +0 -0
index 5310a888613..8f5c2009d29 100644
@@ -93,7 +93,7 @@ static void create_pcie(MachineState *ms,

CPUXtensaState *env, int irq_base,

Quoted 13 lines
hw/xtensa/virt.c +1 -1
      /* Connect IRQ lines. */
      extints = xtensa_get_extints(env);
 
-    for (i = 0; i < GPEX_NUM_IRQS; i++) {
+    for (i = 0; i < PCI_NUM_PINS; i++) {
          void *q = extints[irq_base + i];
 
          sysbus_connect_irq(SYS_BUS_DEVICE(dev), i, q);
include/hw/pci-host/gpex.h +0 -0
index dce883573ba..84471533af0 100644

include/hw/pci-host/gpex.h OBJECT_DECLARE_SIMPLE_TYPE(GPEXHost, GPEX_HOST) · line 35

Quoted 4 lines
include/hw/pci-host/gpex.h +0 -1
@@ -32,8 +32,6 @@ OBJECT_DECLARE_SIMPLE_TYPE(GPEXHost, GPEX_HOST)
  #define TYPE_GPEX_ROOT_DEVICE "gpex-root"
  OBJECT_DECLARE_SIMPLE_TYPE(GPEXRootState, GPEX_ROOT_DEVICE)
 
-#define GPEX_NUM_IRQS 4

I found some references to GPEX_NUM_IRQS still remain:

Quoted 15 lines
$ git grep GPEX_NUM_IRQS
hw/loongarch/virt.c:    uint32_t full_irq_map[GPEX_NUM_IRQS
*GPEX_NUM_IRQS * 10] = {};
hw/loongarch/virt.c:    for (dev = 0; dev < GPEX_NUM_IRQS; dev++) {
hw/loongarch/virt.c:        for (pin = 0; pin  < GPEX_NUM_IRQS; pin++) {
hw/loongarch/virt.c:            int irq_nr = 16 + ((pin +
PCI_SLOT(devfn)) % GPEX_NUM_IRQS);
hw/loongarch/virt.c:                     GPEX_NUM_IRQS * GPEX_NUM_IRQS *
hw/vmapple/vmapple.c:#define GPEX_NUM_IRQS 16
hw/vmapple/vmapple.c:    qdev_prop_set_uint32(dev, "num-irqs",
GPEX_NUM_IRQS);
hw/vmapple/vmapple.c:    for (i = 0; i < GPEX_NUM_IRQS; i++) {
hw/xen/xen-pvh-common.c:    for (i = 0; i < GPEX_NUM_IRQS; i++) {

Good catch! These were added to the code base long after v1 of the patch was posted…
It looks like all of these are safe to replace with PCI_NUM_PINS. (Except the ones in vmapple.c, which #defines its own local value and is intentional.)

Quoted 25 lines
Quoted 23 lines
include/hw/pci-host/gpex.h +3 -3
-
  struct GPEXRootState {
      /*< private >*/
      PCIDevice parent_obj;
@@ -49,6 +47,7 @@ struct GPEXConfig {
      PCIBus      *bus;
  };
 
+typedef struct GPEXIrq GPEXIrq;
  struct GPEXHost {
      /*< private >*/
      PCIExpressHost parent_obj;
@@ -60,8 +59,8 @@ struct GPEXHost {
      MemoryRegion io_mmio;
      MemoryRegion io_ioport_window;
      MemoryRegion io_mmio_window;
-    qemu_irq irq[GPEX_NUM_IRQS];
-    int irq_num[GPEX_NUM_IRQS];
+    GPEXIrq *irq;
+    uint8_t num_irqs;
 
      bool allow_unmapped_accesses;
 
#20 lore raw

PATCH v11 10/15 hw/vmapple/aes: Introduce aes engine

In reply to Phil Dennis-Jordan

From: Alexander Graf <[email protected]>

VMApple contains an "aes" engine device that it uses to encrypt and decrypt its nvram. It has trivial hard coded keys it uses for that purpose.

Add device emulation for this device model.

---

v3:

* Rebased on latest upstream and fixed minor breakages.
* Replaced legacy device reset method with Resettable method

v4:

* Improved logging of unimplemented functions and guest errors.
* Better adherence to naming and coding conventions.
* Cleaner error handling and recovery, including using g_autoptr

v5:

* More logging improvements
* Use xxx64_overflow() functions for hexdump buffer size calculations.

v7:

* Coding style tweaks.

v8:

* Further improved logging of guest errors.

v9:

* Replaced a use of cpu_physical_memory_write with dma_memory_write.
* Dropped unnecessary use of ternary operator for bool -> 0/1.

v10:

* Code style and comment improvements.

 hw/vmapple/Kconfig           |   2 +
 hw/vmapple/aes.c             | 581 +++++++++++++++++++++++++++++++++++
 hw/vmapple/meson.build       |   1 +
 hw/vmapple/trace-events      |  14 +
 include/hw/vmapple/vmapple.h |  17 +
 include/qemu/cutils.h        |  15 +
 util/hexdump.c               |  18 ++
 7 files changed, 648 insertions(+)
 create mode 100644 hw/vmapple/aes.c
 create mode 100644 include/hw/vmapple/vmapple.h
hw/vmapple/Kconfig +2 -0
index 8b137891791..a73504d5999 100644
@@ -1 +1,3 @@
+config VMAPPLE_AES
+    bool
 
hw/vmapple/aes.c new file +581 -0

581 lines not on this page · raw message

hw/vmapple/meson.build +1 -0
index e69de29bb2d..bcd4dcb28d2 100644
@@ -0,0 +1 @@
+system_ss.add(when: 'CONFIG_VMAPPLE_AES',  if_true: files('aes.c'))
hw/vmapple/trace-events +14 -0
index 9ccc5790487..0d4a73d7d1c 100644
@@ -1,2 +1,16 @@
 # See docs/devel/tracing.rst for syntax documentation.
 
+# aes.c
+aes_read(uint64_t offset, uint64_t res) "offset=0x%"PRIx64" res=0x%"PRIx64
+aes_cmd_key_select_builtin(uint32_t ctx, uint32_t key_id, const char *direction, const char *cipher) "[%d] Selecting builtin key %d to %scrypt with %s"
+aes_cmd_key_select_new(uint32_t ctx, uint32_t key_len, const char *direction, const char *cipher) "[%d] Selecting new key size=%d to %scrypt with %s"
+aes_cmd_iv(uint32_t ctx, uint32_t iv0, uint32_t iv1, uint32_t iv2, uint32_t iv3) "[%d] 0x%08x 0x%08x 0x%08x 0x%08x"
+aes_cmd_data(uint32_t key, uint32_t iv, uint64_t src, uint64_t dst, uint32_t len) "[key=%d iv=%d] src=0x%"PRIx64" dst=0x%"PRIx64" len=0x%x"
+aes_cmd_store_iv(uint32_t ctx, uint64_t addr, uint32_t iv0, uint32_t iv1, uint32_t iv2, uint32_t iv3) "[%d] addr=0x%"PRIx64"x -> 0x%08x 0x%08x 0x%08x 0x%08x"
+aes_cmd_flag(uint32_t raise, uint32_t flag_info) "raise=%d flag_info=0x%x"
+aes_fifo_process(uint32_t cmd, bool success) "cmd=%d success=%d"
+aes_write(uint64_t offset, uint64_t val) "offset=0x%"PRIx64" val=0x%"PRIx64
+aes_2_read(uint64_t offset, uint64_t res) "offset=0x%"PRIx64" res=0x%"PRIx64
+aes_2_write(uint64_t offset, uint64_t val) "offset=0x%"PRIx64" val=0x%"PRIx64
+aes_dump_data(const char *desc, const char *hex) "%s%s"
+
include/hw/vmapple/vmapple.h new file +17 -0
new file mode 100644
index 00000000000..6762b6c869f
@@ -0,0 +1,17 @@
+/*
+ * Devices specific to the VMApple machine type
+ *
+ * Copyright © 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ *
+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
+ * See the COPYING file in the top-level directory.
+ *
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ */
+
+#ifndef HW_VMAPPLE_VMAPPLE_H
+#define HW_VMAPPLE_VMAPPLE_H
+
+#define TYPE_APPLE_AES "apple-aes"
+
+#endif /* HW_VMAPPLE_VMAPPLE_H */
include/qemu/cutils.h +15 -0
index 34a9b9b2204..36c68ce86c5 100644
@@ -302,4 +302,19 @@ GString *qemu_hexdump_line(GString *str, const void *buf, size_t len,
 void qemu_hexdump(FILE *fp, const char *prefix,
                   const void *bufptr, size_t size);
 
+/**
+ * qemu_hexdump_to_buffer:
+ * @buffer: output string buffer
+ * @buffer_size: amount of available space in buffer. Must be at least
+ *               data_size*2+1.
+ * @data: input bytes
+ * @data_size: number of bytes in data
+ *
+ * Converts the @data_size bytes in @data into hex digit pairs, writing them to
+ * @buffer. Finally, a nul terminating character is written; @buffer therefore
+ * needs space for (data_size*2+1) chars.
+ */
+void qemu_hexdump_to_buffer(char *restrict buffer, size_t buffer_size,
+                            const uint8_t *restrict data, size_t data_size);
+
 #endif
util/hexdump.c +18 -0
index ae0d4992dcf..f29ffceb746 100644
@@ -15,6 +15,7 @@
 
 #include "qemu/osdep.h"
 #include "qemu/cutils.h"
+#include "qemu/host-utils.h"
 
 static inline char hexdump_nibble(unsigned x)
 {
@@ -97,3 +98,20 @@ void qemu_hexdump(FILE *fp, const char *prefix,
     }
 
 }
+
+void qemu_hexdump_to_buffer(char *restrict buffer, size_t buffer_size,
+                            const uint8_t *restrict data, size_t data_size)
+{
+    size_t i;
+    uint64_t required_buffer_size;
+    bool overflow = umul64_overflow(data_size, 2, &required_buffer_size);
+    overflow |= uadd64_overflow(required_buffer_size, 1, &required_buffer_size);
+    assert(!overflow && buffer_size >= required_buffer_size);
+
+    for (i = 0; i < data_size; i++) {
+        uint8_t val = data[i];
+        *(buffer++) = hexdump_nibble(val >> 4);
+        *(buffer++) = hexdump_nibble(val & 0xf);
+    }
+    *buffer = '\0';
+}
Signature · 1 line
2.39.5 (Apple Git-154)
#21 lore raw

PATCH v11 11/15 hw/vmapple/bdif: Introduce vmapple backdoor interface

In reply to Phil Dennis-Jordan

From: Alexander Graf <[email protected]>

The VMApple machine exposes AUX and ROOT block devices (as well as USB OTG emulation) via virtio-pci as well as a special, simple backdoor platform device.

This patch implements this backdoor platform device to the best of my understanding. I left out any USB OTG parts; they're only needed for guest recovery and I don't understand the protocol yet.

---

v4:

* Moved most header code to .c, rest to vmapple.h
* Better compliance with coding, naming, and formatting conventions.

v8:

* Replaced uses of cpu_physical_memory_read with dma_memory_read.
* Replaced an instance of g_free with g_autofree.

v9:

* Replaced uses of cpu_physical_memory_write with dma_memory_write.

 hw/vmapple/Kconfig           |   3 +
 hw/vmapple/bdif.c            | 275 +++++++++++++++++++++++++++++++++++
 hw/vmapple/meson.build       |   1 +
 hw/vmapple/trace-events      |   5 +
 include/hw/vmapple/vmapple.h |   2 +
 5 files changed, 286 insertions(+)
 create mode 100644 hw/vmapple/bdif.c
hw/vmapple/Kconfig +3 -0
index a73504d5999..68f88876eb9 100644
@@ -1,3 +1,6 @@
 config VMAPPLE_AES
     bool
 
+config VMAPPLE_BDIF
+    bool
+
hw/vmapple/bdif.c new file +275 -0

275 lines not on this page · raw message

hw/vmapple/meson.build +1 -0
index bcd4dcb28d2..d4624713deb 100644
@@ -1 +1,2 @@
 system_ss.add(when: 'CONFIG_VMAPPLE_AES',  if_true: files('aes.c'))
+system_ss.add(when: 'CONFIG_VMAPPLE_BDIF', if_true: files('bdif.c'))
hw/vmapple/trace-events +5 -0
index 0d4a73d7d1c..d86f64d50fe 100644
@@ -14,3 +14,8 @@ aes_2_read(uint64_t offset, uint64_t res) "offset=0x%"PRIx64" res=0x%"PRIx64
 aes_2_write(uint64_t offset, uint64_t val) "offset=0x%"PRIx64" val=0x%"PRIx64
 aes_dump_data(const char *desc, const char *hex) "%s%s"
 
+# bdif.c
+bdif_read(uint64_t offset, uint32_t size, uint64_t value) "offset=0x%"PRIx64" size=0x%x value=0x%"PRIx64
+bdif_write(uint64_t offset, uint32_t size, uint64_t value) "offset=0x%"PRIx64" size=0x%x value=0x%"PRIx64
+bdif_vblk_read(const char *dev, uint64_t addr, uint64_t offset, uint32_t len, int r) "dev=%s addr=0x%"PRIx64" off=0x%"PRIx64" size=0x%x r=%d"
+
include/hw/vmapple/vmapple.h +2 -0
index 6762b6c869f..9090e9c5ac8 100644
@@ -14,4 +14,6 @@
 
 #define TYPE_APPLE_AES "apple-aes"
 
+#define TYPE_VMAPPLE_BDIF "vmapple-bdif"
+
 #endif /* HW_VMAPPLE_VMAPPLE_H */
Signature · 1 line
2.39.5 (Apple Git-154)
#22 lore raw

PATCH v11 12/15 hw/vmapple/cfg: Introduce vmapple cfg region

In reply to Phil Dennis-Jordan

From: Alexander Graf <[email protected]>

Instead of device tree or other more standardized means, VMApple passes platform configuration to the first stage boot loader in a binary encoded format that resides at a dedicated RAM region in physical address space.

This patch models this configuration space as a qdev device which we can then map at the fixed location in the address space. That way, we can influence and annotate all configuration fields easily.

---

v3:

* Replaced legacy device reset method with Resettable method

v4:

* Fixed initialisation of default values for properties
* Dropped superfluous endianness conversions
* Moved most header code to .c, device name #define goes in vmapple.h

v5:

* Improved error reporting in case of string property buffer overflow.

v7:

* Changed error messages for overrun of properties with fixed-length strings to be more useful to users than developers.

v8:

* Consistent parenthesising of macro arguments for better safety.

v10:

* Slightly tidier error reporting for overlong property values.

 hw/vmapple/Kconfig           |   3 +
 hw/vmapple/cfg.c             | 196 +++++++++++++++++++++++++++++++++++
 hw/vmapple/meson.build       |   1 +
 include/hw/vmapple/vmapple.h |   2 +
 4 files changed, 202 insertions(+)
 create mode 100644 hw/vmapple/cfg.c
hw/vmapple/Kconfig +3 -0
index 68f88876eb9..8bbeb9a9237 100644
@@ -4,3 +4,6 @@ config VMAPPLE_AES
 config VMAPPLE_BDIF
     bool
 
+config VMAPPLE_CFG
+    bool
+
hw/vmapple/cfg.c new file +196 -0

196 lines not on this page · raw message

hw/vmapple/meson.build +1 -0
index d4624713deb..64b78693a31 100644
@@ -1,2 +1,3 @@
 system_ss.add(when: 'CONFIG_VMAPPLE_AES',  if_true: files('aes.c'))
 system_ss.add(when: 'CONFIG_VMAPPLE_BDIF', if_true: files('bdif.c'))
+system_ss.add(when: 'CONFIG_VMAPPLE_CFG',  if_true: files('cfg.c'))
include/hw/vmapple/vmapple.h +2 -0
index 9090e9c5ac8..3bba59f5ec7 100644
@@ -16,4 +16,6 @@
 
 #define TYPE_VMAPPLE_BDIF "vmapple-bdif"
 
+#define TYPE_VMAPPLE_CFG "vmapple-cfg"
+
 #endif /* HW_VMAPPLE_VMAPPLE_H */
Signature · 1 line
2.39.5 (Apple Git-154)
#23 lore raw

PATCH v11 13/15 hw/vmapple/virtio-blk: Add support for apple virtio-blk

In reply to Phil Dennis-Jordan

From: Alexander Graf <[email protected]>

Apple has its own virtio-blk PCI device ID where it deviates from the official virtio-pci spec slightly: It puts a new "apple type" field at a static offset in config space and introduces a new barrier command.

This patch first creates a mechanism for virtio-blk downstream classes to handle unknown commands. It then creates such a downstream class and a new vmapple-virtio-blk-pci class which support the additional apple type config identifier as well as the barrier command.

The 'aux' or 'root' device type are selected using the 'variant' property.

---

v4:

* Use recommended object type declaration pattern.
* Correctly log unimplemented code paths.
* Most header code moved to .c, type name #defines moved to vmapple.h

v5:

* Corrected handling of potentially unaligned writes to virtio config area.
* Simplified passing through device variant type to subobject.

v9:

* Correctly specify class_size for VMAppleVirtIOBlkClass

v10:

* Folded v9 patch 16/16 into this one, changing the device type design to provide a single device type with a variant property instead of 2 different subtypes for aux and root volumes.
* Tidied up error reporting for the variant property.

 hw/block/virtio-blk.c               |  19 ++-
 hw/core/qdev-properties-system.c    |   8 ++
 hw/vmapple/Kconfig                  |   3 +
 hw/vmapple/meson.build              |   1 +
 hw/vmapple/virtio-blk.c             | 205 ++++++++++++++++++++++++++++
 include/hw/pci/pci_ids.h            |   1 +
 include/hw/qdev-properties-system.h |   5 +
 include/hw/virtio/virtio-blk.h      |  12 +-
 include/hw/vmapple/vmapple.h        |   2 +
 qapi/virtio.json                    |  14 ++
 10 files changed, 265 insertions(+), 5 deletions(-)
 create mode 100644 hw/vmapple/virtio-blk.c
hw/block/virtio-blk.c +15 -4
index 9166d7974d4..9e8337bb639 100644
@@ -50,12 +50,12 @@ static void virtio_blk_init_request(VirtIOBlock *s, VirtQueue *vq,
     req->mr_next = NULL;
 }
 
-static void virtio_blk_free_request(VirtIOBlockReq *req)
+void virtio_blk_free_request(VirtIOBlockReq *req)
 {
     g_free(req);
 }
 
-static void virtio_blk_req_complete(VirtIOBlockReq *req, unsigned char status)
+void virtio_blk_req_complete(VirtIOBlockReq *req, unsigned char status)
 {
     VirtIOBlock *s = req->dev;
     VirtIODevice *vdev = VIRTIO_DEVICE(s);
@@ -966,8 +966,18 @@ static int virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
         break;
     }
     default:
-        virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
-        virtio_blk_free_request(req);
+    {
+        /*
+         * Give subclasses a chance to handle unknown requests. This way the
+         * class lookup is not in the hot path.
+         */
+        VirtIOBlkClass *vbk = VIRTIO_BLK_GET_CLASS(s);
+        if (!vbk->handle_unknown_request ||
+            !vbk->handle_unknown_request(req, mrb, type)) {
+            virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
+            virtio_blk_free_request(req);
+        }
+    }
     }
     return 0;
 }
@@ -2044,6 +2054,7 @@ static const TypeInfo virtio_blk_info = {
     .instance_size = sizeof(VirtIOBlock),
     .instance_init = virtio_blk_instance_init,
     .class_init = virtio_blk_class_init,
+    .class_size = sizeof(VirtIOBlkClass),
 };
 
 static void virtio_register_types(void)
hw/core/qdev-properties-system.c +8 -0
index 22ea1ed3583..32abfc20b31 100644
@@ -1283,3 +1283,11 @@ const PropertyInfo qdev_prop_iothread_vq_mapping_list = {
     .set = set_iothread_vq_mapping_list,
     .release = release_iothread_vq_mapping_list,
 };
+
+const PropertyInfo qdev_prop_vmapple_virtio_blk_variant = {
+    .name  = "VMAppleVirtioBlkVariant",
+    .enum_table  = &VMAppleVirtioBlkVariant_lookup,
+    .get   = qdev_propinfo_get_enum,
+    .set   = qdev_propinfo_set_enum,
+    .set_default_value = qdev_propinfo_set_default_value_enum,
+};
hw/vmapple/Kconfig +3 -0
index 8bbeb9a9237..bcd1be63e3c 100644
@@ -7,3 +7,6 @@ config VMAPPLE_BDIF
 config VMAPPLE_CFG
     bool
 
+config VMAPPLE_VIRTIO_BLK
+    bool
+
hw/vmapple/meson.build +1 -0
index 64b78693a31..bf17cf906c9 100644
@@ -1,3 +1,4 @@
 system_ss.add(when: 'CONFIG_VMAPPLE_AES',  if_true: files('aes.c'))
 system_ss.add(when: 'CONFIG_VMAPPLE_BDIF', if_true: files('bdif.c'))
 system_ss.add(when: 'CONFIG_VMAPPLE_CFG',  if_true: files('cfg.c'))
+system_ss.add(when: 'CONFIG_VMAPPLE_VIRTIO_BLK',  if_true: files('virtio-blk.c'))
hw/vmapple/virtio-blk.c new file +205 -0

205 lines not on this page · raw message

include/hw/pci/pci_ids.h +1 -0
index f1a53fea8d6..33e2898be95 100644
@@ -191,6 +191,7 @@
 #define PCI_DEVICE_ID_APPLE_UNI_N_AGP    0x0020
 #define PCI_DEVICE_ID_APPLE_U3_AGP       0x004b
 #define PCI_DEVICE_ID_APPLE_UNI_N_GMAC   0x0021
+#define PCI_DEVICE_ID_APPLE_VIRTIO_BLK   0x1a00
 
 #define PCI_VENDOR_ID_SUN                0x108e
 #define PCI_DEVICE_ID_SUN_EBUS           0x1000
include/hw/qdev-properties-system.h +5 -0
index 7ec37f6316c..3631e309690 100644
@@ -30,6 +30,7 @@ extern const PropertyInfo qdev_prop_pcie_link_speed;
 extern const PropertyInfo qdev_prop_pcie_link_width;
 extern const PropertyInfo qdev_prop_cpus390entitlement;
 extern const PropertyInfo qdev_prop_iothread_vq_mapping_list;
+extern const PropertyInfo qdev_prop_vmapple_virtio_blk_variant;
 
 #define DEFINE_PROP_PCI_DEVFN(_n, _s, _f, _d)                   \
     DEFINE_PROP_SIGNED(_n, _s, _f, _d, qdev_prop_pci_devfn, int32_t)
@@ -97,4 +98,8 @@ extern const PropertyInfo qdev_prop_iothread_vq_mapping_list;
     DEFINE_PROP(_name, _state, _field, qdev_prop_iothread_vq_mapping_list, \
                 IOThreadVirtQueueMappingList *)
 
+#define DEFINE_PROP_VMAPPLE_VIRTIO_BLK_VARIANT(_n, _s, _f, _d) \
+    DEFINE_PROP_SIGNED(_n, _s, _f, _d, qdev_prop_vmapple_virtio_blk_variant, \
+                       VMAppleVirtioBlkVariant)
+
 #endif
include/hw/virtio/virtio-blk.h +11 -1
index 5c14110c4b1..28d5046ea6c 100644
@@ -24,7 +24,7 @@
 #include "qapi/qapi-types-virtio.h"
 
 #define TYPE_VIRTIO_BLK "virtio-blk-device"
-OBJECT_DECLARE_SIMPLE_TYPE(VirtIOBlock, VIRTIO_BLK)
+OBJECT_DECLARE_TYPE(VirtIOBlock, VirtIOBlkClass, VIRTIO_BLK)
 
 /* This is the last element of the write scatter-gather list */
 struct virtio_blk_inhdr
@@ -100,6 +100,16 @@ typedef struct MultiReqBuffer {
     bool is_write;
 } MultiReqBuffer;
 
+typedef struct VirtIOBlkClass {
+    /*< private >*/
+    VirtioDeviceClass parent;
+    /*< public >*/
+    bool (*handle_unknown_request)(VirtIOBlockReq *req, MultiReqBuffer *mrb,
+                                   uint32_t type);
+} VirtIOBlkClass;
+
 void virtio_blk_handle_vq(VirtIOBlock *s, VirtQueue *vq);
+void virtio_blk_free_request(VirtIOBlockReq *req);
+void virtio_blk_req_complete(VirtIOBlockReq *req, unsigned char status);
 
 #endif
include/hw/vmapple/vmapple.h +2 -0
index 3bba59f5ec7..9c1ad1bd8c3 100644
@@ -18,4 +18,6 @@
 
 #define TYPE_VMAPPLE_CFG "vmapple-cfg"
 
+#define TYPE_VMAPPLE_VIRTIO_BLK_PCI "vmapple-virtio-blk-pci"
+
 #endif /* HW_VMAPPLE_VMAPPLE_H */
qapi/virtio.json +14 -0
index 2529c2d8b20..d351d2166ef 100644
@@ -992,3 +992,17 @@
 ##
 { 'enum': 'GranuleMode',
   'data': [ '4k', '8k', '16k', '64k', 'host' ] }
+
+##
+# @VMAppleVirtioBlkVariant:
+#
+# @unspecified: The default, not a valid setting.
+#
+# @root: Block device holding the root volume
+#
+# @aux: Block device holding auxiliary data required for boot
+#
+# Since: 9.2
+##
+{ 'enum': 'VMAppleVirtioBlkVariant',
+  'data': [ 'unspecified', 'root', 'aux' ] }
Signature · 1 line
2.39.5 (Apple Git-154)
#24 lore raw

PATCH v11 14/15 hw/block/virtio-blk: Replaces request free function with g_free

In reply to Phil Dennis-Jordan

The virtio_blk_free_request() function has been a 1-liner forwarding to g_free() for a while now. We may as well call g_free on the request pointer directly.

---
 hw/block/virtio-blk.c          | 43 +++++++++++++++-------------------
 hw/vmapple/virtio-blk.c        |  2 +-
 include/hw/virtio/virtio-blk.h |  1 -
 3 files changed, 20 insertions(+), 26 deletions(-)
hw/block/virtio-blk.c +19 -24
index 9e8337bb639..40d2c9bc591 100644
@@ -50,11 +50,6 @@ static void virtio_blk_init_request(VirtIOBlock *s, VirtQueue *vq,
     req->mr_next = NULL;
 }
 
-void virtio_blk_free_request(VirtIOBlockReq *req)
-{
-    g_free(req);
-}
-
 void virtio_blk_req_complete(VirtIOBlockReq *req, unsigned char status)
 {
     VirtIOBlock *s = req->dev;
@@ -93,7 +88,7 @@ static int virtio_blk_handle_rw_error(VirtIOBlockReq *req, int error,
         if (acct_failed) {
             block_acct_failed(blk_get_stats(s->blk), &req->acct);
         }
-        virtio_blk_free_request(req);
+        g_free(req);
     }
 
     blk_error_action(s->blk, action, is_read, error);
@@ -136,7 +131,7 @@ static void virtio_blk_rw_complete(void *opaque, int ret)
 
         virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
         block_acct_done(blk_get_stats(s->blk), &req->acct);
-        virtio_blk_free_request(req);
+        g_free(req);
     }
 }
 
@@ -151,7 +146,7 @@ static void virtio_blk_flush_complete(void *opaque, int ret)
 
     virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
     block_acct_done(blk_get_stats(s->blk), &req->acct);
-    virtio_blk_free_request(req);
+    g_free(req);
 }
 
 static void virtio_blk_discard_write_zeroes_complete(void *opaque, int ret)
@@ -169,7 +164,7 @@ static void virtio_blk_discard_write_zeroes_complete(void *opaque, int ret)
     if (is_write_zeroes) {
         block_acct_done(blk_get_stats(s->blk), &req->acct);
     }
-    virtio_blk_free_request(req);
+    g_free(req);
 }
 
 static VirtIOBlockReq *virtio_blk_get_request(VirtIOBlock *s, VirtQueue *vq)
@@ -214,7 +209,7 @@ static void virtio_blk_handle_scsi(VirtIOBlockReq *req)
 
 fail:
     virtio_blk_req_complete(req, status);
-    virtio_blk_free_request(req);
+    g_free(req);
 }
 
 static inline void submit_requests(VirtIOBlock *s, MultiReqBuffer *mrb,
@@ -612,7 +607,7 @@ static void virtio_blk_zone_report_complete(void *opaque, int ret)
 
 out:
     virtio_blk_req_complete(req, err_status);
-    virtio_blk_free_request(req);
+    g_free(req);
     g_free(data->zone_report_data.zones);
     g_free(data);
 }
@@ -661,7 +656,7 @@ static void virtio_blk_handle_zone_report(VirtIOBlockReq *req,
     return;
 out:
     virtio_blk_req_complete(req, err_status);
-    virtio_blk_free_request(req);
+    g_free(req);
 }
 
 static void virtio_blk_zone_mgmt_complete(void *opaque, int ret)
@@ -677,7 +672,7 @@ static void virtio_blk_zone_mgmt_complete(void *opaque, int ret)
     }
 
     virtio_blk_req_complete(req, err_status);
-    virtio_blk_free_request(req);
+    g_free(req);
 }
 
 static int virtio_blk_handle_zone_mgmt(VirtIOBlockReq *req, BlockZoneOp op)
@@ -719,7 +714,7 @@ static int virtio_blk_handle_zone_mgmt(VirtIOBlockReq *req, BlockZoneOp op)
     return 0;
 out:
     virtio_blk_req_complete(req, err_status);
-    virtio_blk_free_request(req);
+    g_free(req);
     return err_status;
 }
 
@@ -750,7 +745,7 @@ static void virtio_blk_zone_append_complete(void *opaque, int ret)
 
 out:
     virtio_blk_req_complete(req, err_status);
-    virtio_blk_free_request(req);
+    g_free(req);
     g_free(data);
 }
 
@@ -788,7 +783,7 @@ static int virtio_blk_handle_zone_append(VirtIOBlockReq *req,
 
 out:
     virtio_blk_req_complete(req, err_status);
-    virtio_blk_free_request(req);
+    g_free(req);
     return err_status;
 }
 
@@ -855,7 +850,7 @@ static int virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
             virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
             block_acct_invalid(blk_get_stats(s->blk),
                                is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
-            virtio_blk_free_request(req);
+            g_free(req);
             return 0;
         }
 
@@ -911,7 +906,7 @@ static int virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
                               VIRTIO_BLK_ID_BYTES));
         iov_from_buf(in_iov, in_num, 0, serial, size);
         virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
-        virtio_blk_free_request(req);
+        g_free(req);
         break;
     }
     case VIRTIO_BLK_T_ZONE_APPEND & ~VIRTIO_BLK_T_OUT:
@@ -943,7 +938,7 @@ static int virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
         if (unlikely(!(type & VIRTIO_BLK_T_OUT) ||
                      out_len > sizeof(dwz_hdr))) {
             virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
-            virtio_blk_free_request(req);
+            g_free(req);
             return 0;
         }
 
@@ -960,7 +955,7 @@ static int virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
                                                             is_write_zeroes);
         if (err_status != VIRTIO_BLK_S_OK) {
             virtio_blk_req_complete(req, err_status);
-            virtio_blk_free_request(req);
+            g_free(req);
         }
 
         break;
@@ -975,7 +970,7 @@ static int virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
         if (!vbk->handle_unknown_request ||
             !vbk->handle_unknown_request(req, mrb, type)) {
             virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
-            virtio_blk_free_request(req);
+            g_free(req);
         }
     }
     }
@@ -998,7 +993,7 @@ void virtio_blk_handle_vq(VirtIOBlock *s, VirtQueue *vq)
         while ((req = virtio_blk_get_request(s, vq))) {
             if (virtio_blk_handle_request(req, &mrb)) {
                 virtqueue_detach_element(req->vq, &req->elem, 0);
-                virtio_blk_free_request(req);
+                g_free(req);
                 break;
             }
         }
@@ -1048,7 +1043,7 @@ static void virtio_blk_dma_restart_bh(void *opaque)
             while (req) {
                 next = req->next;
                 virtqueue_detach_element(req->vq, &req->elem, 0);
-                virtio_blk_free_request(req);
+                g_free(req);
                 req = next;
             }
             break;
@@ -1131,7 +1126,7 @@ static void virtio_blk_reset(VirtIODevice *vdev)
             /* No other threads can access req->vq here */
             virtqueue_detach_element(req->vq, &req->elem, 0);
 
-            virtio_blk_free_request(req);
+            g_free(req);
         }
     }
 
hw/vmapple/virtio-blk.c +1 -1
index 9aeb2931922..52d857166bd 100644
@@ -55,7 +55,7 @@ static bool vmapple_virtio_blk_handle_unknown_request(VirtIOBlockReq *req,
         qemu_log_mask(LOG_UNIMP, "%s: Barrier requests are currently no-ops\n",
                       __func__);
         virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
-        virtio_blk_free_request(req);
+        g_free(req);
         return true;
     default:
         return false;
include/hw/virtio/virtio-blk.h +0 -1
index 28d5046ea6c..dcb2c89aed5 100644
@@ -109,7 +109,6 @@ typedef struct VirtIOBlkClass {
 } VirtIOBlkClass;
 
 void virtio_blk_handle_vq(VirtIOBlock *s, VirtQueue *vq);
-void virtio_blk_free_request(VirtIOBlockReq *req);
 void virtio_blk_req_complete(VirtIOBlockReq *req, unsigned char status);
 
 #endif
Signature · 1 line
2.39.5 (Apple Git-154)
#25 lore raw

PATCH v11 15/15 hw/vmapple/vmapple: Add vmapple machine type

In reply to Phil Dennis-Jordan

From: Alexander Graf <[email protected]>

Apple defines a new "vmapple" machine type as part of its proprietary macOS Virtualization.Framework vmm. This machine type is similar to the virt one, but with subtle differences in base devices, a few special vmapple device additions and a vastly different boot chain.

This patch reimplements this machine type in QEMU. To use it, you have to have a readily installed version of macOS for VMApple, run on macOS with -accel hvf, pass the Virtualization.Framework boot rom (AVPBooter) in via -bios, pass the aux and root volume as pflash and pass aux and root volume as virtio drives. In addition, you also need to find the machine UUID and pass that as -M vmapple,uuid= parameter:

$ qemu-system-aarch64 -accel hvf -M vmapple,uuid=0x1234 -m 4G \
    -bios /System/Library/Frameworks/Virtualization.framework/Versions/A/Resources/AVPBooter.vmapple2.bin
    -drive file=aux,if=pflash,format=raw \
    -drive file=root,if=pflash,format=raw \
    -drive file=aux,if=none,id=aux,format=raw \
    -device vmapple-virtio-aux,drive=aux \
    -drive file=root,if=none,id=root,format=raw \
    -device vmapple-virtio-root,drive=root

With all these in place, you should be able to see macOS booting successfully.

Known issues:
- Keyboard and mouse/tablet input is laggy. The reason for this is either that macOS's XHCI driver is broken when the device/platform does not support MSI/MSI-X, or there's some unfortunate interplay with Qemu's XHCI implementation in this scenario.
- Currently only macOS 12 guests are supported. The boot process for 13+ will need further investigation and adjustment.

---

v3:
* Rebased on latest upstream, updated affinity and NIC creation
API usage
* Included Apple-variant virtio-blk in build dependency
* Updated API usage for setting 'redist-region-count' array-typed property on GIC.
* Switched from virtio HID devices (for which macOS 12 does not contain drivers) to an XHCI USB controller and USB HID devices.

v4:
* Fixups for v4 changes to the other patches in the set.
* Corrected the assert macro to use
* Removed superfluous endian conversions corresponding to cfg's.
* Init error handling improvement.
* No need to select CPU type on TCG, as only HVF is supported.
* Machine type version bumped to 9.2
* #include order improved

v5:
* Fixed memory reservation for ecam alias region.
* Better error handling setting properties on devices.
* Simplified the machine ECID/UUID extraction script and actually created a file for it rather than quoting its code in documentation.

v7:
* Tiny error handling fix, un-inlined function.

v8:
* Use object_property_add_uint64_ptr rather than defining custom UUID property get/set functions.

v9:
* Documentation improvements
* Fixed variable name and struct field used during pvpanic device creation.

v10:
* Documentation fixup for changed virtio-blk device type.
* Small improvements to shell commands in documentation.
* Improved propagation of errors during cfg device instantiation.

v11:
* Quoted more strings in the documentation's shell script code.

 MAINTAINERS                 |   1 +
 contrib/vmapple/uuid.sh     |   9 +
 docs/system/arm/vmapple.rst |  63 ++++
 docs/system/target-arm.rst  |   1 +
 hw/vmapple/Kconfig          |  20 ++
 hw/vmapple/meson.build      |   1 +
 hw/vmapple/vmapple.c        | 646 ++++++++++++++++++++++++++++++++++++
 7 files changed, 741 insertions(+)
 create mode 100755 contrib/vmapple/uuid.sh
 create mode 100644 docs/system/arm/vmapple.rst
 create mode 100644 hw/vmapple/vmapple.c
MAINTAINERS +1 -0
index 9e7fc6c050a..a9a98ef4917 100644
@@ -2769,6 +2769,7 @@ R: Phil Dennis-Jordan <[email protected]>
 S: Maintained
 F: hw/vmapple/*
 F: include/hw/vmapple/*
+F: docs/system/arm/vmapple.rst
 
 Subsystems
 ----------
contrib/vmapple/uuid.sh new file +9 -0
new file mode 100755
index 00000000000..956e8c3afed
@@ -0,0 +1,9 @@
+#!/bin/sh
+# Used for converting a guest provisioned using Virtualization.framework
+# for use with the QEMU 'vmapple' aarch64 machine type.
+#
+# Extracts the Machine UUID from Virtualization.framework VM JSON file.
+# (as produced by 'macosvm', passed as command line argument)
+
+plutil -extract machineId raw "$1" | base64 -d | plutil -extract ECID raw -
+
docs/system/arm/vmapple.rst new file +63 -0

63 lines not on this page · raw message

docs/system/target-arm.rst +1 -0
index 9aaa9c414c9..3426f79100b 100644
@@ -102,6 +102,7 @@ Board-specific documentation
    arm/stellaris
    arm/stm32
    arm/virt
+   arm/vmapple
    arm/xenpvh
    arm/xlnx-versal-virt
    arm/xlnx-zynq
hw/vmapple/Kconfig +20 -0
index bcd1be63e3c..6a4c4a7fa2e 100644
@@ -10,3 +10,23 @@ config VMAPPLE_CFG
 config VMAPPLE_VIRTIO_BLK
     bool
 
+config VMAPPLE
+    bool
+    depends on ARM
+    depends on HVF
+    default y if ARM
+    imply PCI_DEVICES
+    select ARM_GIC
+    select PLATFORM_BUS
+    select PCI_EXPRESS
+    select PCI_EXPRESS_GENERIC_BRIDGE
+    select PL011 # UART
+    select PL031 # RTC
+    select PL061 # GPIO
+    select GPIO_PWR
+    select PVPANIC_MMIO
+    select VMAPPLE_AES
+    select VMAPPLE_BDIF
+    select VMAPPLE_CFG
+    select MAC_PVG_MMIO
+    select VMAPPLE_VIRTIO_BLK
hw/vmapple/meson.build +1 -0
index bf17cf906c9..e572f7d5602 100644
@@ -2,3 +2,4 @@ system_ss.add(when: 'CONFIG_VMAPPLE_AES',  if_true: files('aes.c'))
 system_ss.add(when: 'CONFIG_VMAPPLE_BDIF', if_true: files('bdif.c'))
 system_ss.add(when: 'CONFIG_VMAPPLE_CFG',  if_true: files('cfg.c'))
 system_ss.add(when: 'CONFIG_VMAPPLE_VIRTIO_BLK',  if_true: files('virtio-blk.c'))
+specific_ss.add(when: 'CONFIG_VMAPPLE',     if_true: files('vmapple.c'))
hw/vmapple/vmapple.c new file +646 -0

646 lines not on this page · raw message

Signature · 1 line
2.39.5 (Apple Git-154)
Reviewed-by on v11 15/15
#26 lore raw

Re: [PATCH v11 15/15] hw/vmapple/vmapple: Add vmapple machine type

Quoted 34 lines · Phil Dennis-Jordan

From: Alexander Graf <[email protected]>

Apple defines a new "vmapple" machine type as part of its proprietary macOS Virtualization.Framework vmm. This machine type is similar to the virt one, but with subtle differences in base devices, a few special vmapple device additions and a vastly different boot chain.

This patch reimplements this machine type in QEMU. To use it, you have to have a readily installed version of macOS for VMApple, run on macOS with -accel hvf, pass the Virtualization.Framework boot rom (AVPBooter) in via -bios, pass the aux and root volume as pflash and pass aux and root volume as virtio drives. In addition, you also need to find the machine UUID and pass that as -M vmapple,uuid= parameter:

$ qemu-system-aarch64 -accel hvf -M vmapple,uuid=0x1234 -m 4G \
     -bios /System/Library/Frameworks/Virtualization.framework/Versions/A/Resources/AVPBooter.vmapple2.bin
     -drive file=aux,if=pflash,format=raw \
     -drive file=root,if=pflash,format=raw \
     -drive file=aux,if=none,id=aux,format=raw \
     -device vmapple-virtio-aux,drive=aux \
     -drive file=root,if=none,id=root,format=raw \
     -device vmapple-virtio-root,drive=root

With all these in place, you should be able to see macOS booting successfully.

Known issues:
- Keyboard and mouse/tablet input is laggy. The reason for this is either that macOS's XHCI driver is broken when the device/platform does not support MSI/MSI-X, or there's some unfortunate interplay with Qemu's XHCI implementation in this scenario.
- Currently only macOS 12 guests are supported. The boot process for 13+ will need further investigation and adjustment.

Quoted 3 lines