Skip to contentSkip to conversation

ui/cocoa: Run qemu_init in the main thread

PATCH Superseded Akihiko Odaki 2 participants 9 messages Jul 15, 2022 – Jul 17, 2022 Arm/Amlogic Meson SoC support

v3 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

v3 cover ui/cocoa: Run qemu_init in the main thread

This work is based on:
https://patchew.org/QEMU/[email protected]/

Simplify the initialization dance by running qemu_init() in the main thread before the Cocoa event loop starts. The secondary thread only runs only qemu_main_loop() and qemu_cleanup().

This fixes a case where addRemovableDevicesMenuItems() calls qmp_query_block() while expecting the main thread to still hold the BQL.

Overriding the code after calling qemu_init() is done by dynamically replacing a function pointer variable, qemu_main when initializing ui/cocoa, which unifies the static implementation of main() for builds with ui/cocoa and ones without ui/cocoa.

v3: Document functions involved in startup. (Peter Maydell)

v2: Restore allow_events flag to fix the crash reported by
Philippe Mathieu-Daudé.

Akihiko Odaki (3):
ui/cocoa: Run qemu_init in the main thread
Revert "main-loop: Disable block backend global state assertion on
Cocoa"
meson: Allow to enable gtk and sdl while cocoa is enabled

 docs/devel/fuzzing.rst   |   4 +-
 include/qemu-main.h      |   3 +-
 include/qemu/main-loop.h |  13 ---
 include/sysemu/sysemu.h  |   2 +-
 meson.build              |  10 +--
 softmmu/main.c           |  14 ++--
 softmmu/vl.c             |   2 +-
 tests/qtest/fuzz/fuzz.c  |   2 +-
 ui/cocoa.m               | 172 ++++++++++++++-------------------------
 9 files changed, 78 insertions(+), 144 deletions(-)
Signature · 1 line
2.32.1 (Apple Git-133)
#1 lore raw

PATCH v3 1/3 ui/cocoa: Run qemu_init in the main thread

This work is based on:
https://patchew.org/QEMU/[email protected]/

Simplify the initialization dance by running qemu_init() in the main thread before the Cocoa event loop starts. The secondary thread only runs only qemu_main_loop() and qemu_cleanup().

This fixes a case where addRemovableDevicesMenuItems() calls qmp_query_block() while expecting the main thread to still hold the BQL.

Overriding the code after calling qemu_init() is done by dynamically replacing a function pointer variable, qemu_main when initializing ui/cocoa, which unifies the static implementation of main() for builds with ui/cocoa and ones without ui/cocoa.

---
 docs/devel/fuzzing.rst  |   4 +-
 include/qemu-main.h     |   3 +-
 include/sysemu/sysemu.h |   2 +-
 softmmu/main.c          |  14 ++--
 softmmu/vl.c            |   2 +-
 tests/qtest/fuzz/fuzz.c |   2 +-
 ui/cocoa.m              | 172 +++++++++++++++-------------------------
 7 files changed, 76 insertions(+), 123 deletions(-)
docs/devel/fuzzing.rst +2 -2
index 784ecb99e66..715330c8561 100644
@@ -287,8 +287,8 @@ select the fuzz target. Then, the qtest client is initialized. If the target
 requires qos, qgraph is set up and the QOM/LIBQOS modules are initialized.
 Then the QGraph is walked and the QEMU cmd_line is determined and saved.
 
-After this, the ``vl.c:qemu_main`` is called to set up the guest. There are
-target-specific hooks that can be called before and after qemu_main, for
+After this, the ``vl.c:main`` is called to set up the guest. There are
+target-specific hooks that can be called before and after main, for
 additional setup(e.g. PCI setup, or VM snapshotting).
 
 ``LLVMFuzzerTestOneInput``: Uses qtest/qos functions to act based on the fuzz
include/qemu-main.h +2 -1
index 6a3e90d0ad5..6889375e7c2 100644
@@ -5,6 +5,7 @@
 #ifndef QEMU_MAIN_H
 #define QEMU_MAIN_H
 
-int qemu_main(int argc, char **argv, char **envp);
+void qemu_default_main(void);
+extern void (*qemu_main)(void);
 
 #endif /* QEMU_MAIN_H */
include/sysemu/sysemu.h +1 -1
index 812f66a31a9..254c1eabf57 100644
@@ -102,7 +102,7 @@ void qemu_boot_set(const char *boot_order, Error **errp);
 
 bool defaults_enabled(void);
 
-void qemu_init(int argc, char **argv, char **envp);
+void qemu_init(int argc, char **argv);
 void qemu_main_loop(void);
 void qemu_cleanup(void);
 
softmmu/main.c +7 -7
index c00432ff098..41a091f2c72 100644
@@ -30,18 +30,18 @@
 #include <SDL.h>
 #endif
 
-int qemu_main(int argc, char **argv, char **envp)
+void qemu_default_main(void)
 {
-    qemu_init(argc, argv, envp);
     qemu_main_loop();
     qemu_cleanup();
-
-    return 0;
 }
 
-#ifndef CONFIG_COCOA
+void (*qemu_main)(void) = qemu_default_main;
+
 int main(int argc, char **argv)
 {
-    return qemu_main(argc, argv, NULL);
+    qemu_init(argc, argv);
+    qemu_main();
+
+    return 0;
 }
-#endif
softmmu/vl.c +1 -1
index 3f264d4b093..e8c73d0bb40 100644
@@ -2589,7 +2589,7 @@ void qmp_x_exit_preconfig(Error **errp)
     }
 }
 
-void qemu_init(int argc, char **argv, char **envp)
+void qemu_init(int argc, char **argv)
 {
     QemuOpts *opts;
     QemuOpts *icount_opts = NULL, *accel_opts = NULL;
tests/qtest/fuzz/fuzz.c +1 -1
index 0ad4ba9e94d..678c312923a 100644
@@ -236,7 +236,7 @@ int LLVMFuzzerInitialize(int *argc, char ***argv, char ***envp)
         g_free(pretty_cmd_line);
     }
 
-    qemu_init(result.we_wordc, result.we_wordv, NULL);
+    qemu_init(result.we_wordc, result.we_wordv);
 
     /* re-enable the rcu atfork, which was previously disabled in qemu_init */
     rcu_enable_atfork();
ui/cocoa.m +62 -110

252 lines not on this page · raw message

Signature · 1 line
2.32.1 (Apple Git-133)
#2 lore raw
Quoted 5 lines · Akihiko Odaki

static void *call_qemu_main(void *opaque)

  {
     ...

+ [NSApp terminate:nil];

Is this thread-safe? I think it should be something like:

- here:

    /*
     * Nothing more to do in the QEMU thread, ask the application
     * to exit.
     */
    dispatch_async(dispatch_get_main_queue(), ^{
        [NSApp terminate: nil];
    });

- in verifyQuit:

    if([alert runModal] == NSAlertSecondButtonReturn) {
        with_iothread_lock(^{
            shutdown_action = SHUTDOWN_ACTION_POWEROFF;
            qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
        });
    }
    /* and just return void */

- applicationShouldTerminate: should be just

    if (qatomic_read(&qemu_main_terminating)) {
        return NSTerminateNow;
    } else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self verifyQuit];
        });
    }
    return NSTerminateCancel;

- applicationWillTerminate: can be just the qemu_thread_join

Paolo

#3 lore raw
Quoted 6 lines · Paolo Bonzini
Quoted 4 lines · Akihiko Odaki

  static void *call_qemu_main(void *opaque)
  {
     ...
+    [NSApp terminate:nil];

Is this thread-safe?  I think it should be something like:

Yes, -[NSApplication terminate:] is thread-safe. Methods of NSApplication handle dispatches to the main thread by themselves.

Regards,
Akihiko Odaki

Quoted 35 lines

- here:

    /*
     * Nothing more to do in the QEMU thread, ask the application
     * to exit.
     */
    dispatch_async(dispatch_get_main_queue(), ^{ [NSApp terminate: nil];
    });

- in verifyQuit:

    if([alert runModal] == NSAlertSecondButtonReturn) { with_iothread_lock(^{
            shutdown_action = SHUTDOWN_ACTION_POWEROFF; qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI); });
    }
    /* and just return void */

- applicationShouldTerminate: should be just

    if (qatomic_read(&qemu_main_terminating)) { return NSTerminateNow;
    } else { dispatch_async(dispatch_get_main_queue(), ^{ [self verifyQuit];
        });
    }
    return NSTerminateCancel;

- applicationWillTerminate: can be just the qemu_thread_join

Paolo

#4 lore raw

Il sab 16 lug 2022, 13:30 Akihiko Odaki <[email protected]> ha scritto:

Quoted 11 lines · Paolo Bonzini
Quoted 6 lines · Akihiko Odaki
Quoted 4 lines

static void *call_qemu_main(void *opaque)

  {
     ...

+ [NSApp terminate:nil];

Is this thread-safe? I think it should be something like:

Yes, -[NSApplication terminate:] is thread-safe. Methods of NSApplication handle dispatches to the main thread by themselves.

Is this documented anywhere?

Paolo

Regards,

Quoted 39 lines

Akihiko Odaki

Quoted 35 lines

- here:

     /*
      * Nothing more to do in the QEMU thread, ask the application
      * to exit.
      */
     dispatch_async(dispatch_get_main_queue(), ^{
         [NSApp terminate: nil];
     });

- in verifyQuit:

     if([alert runModal] == NSAlertSecondButtonReturn) {
         with_iothread_lock(^{
             shutdown_action = SHUTDOWN_ACTION_POWEROFF;
             qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
         });
     }
     /* and just return void */

- applicationShouldTerminate: should be just

     if (qatomic_read(&qemu_main_terminating)) {
         return NSTerminateNow;
     } else {
         dispatch_async(dispatch_get_main_queue(), ^{
             [self verifyQuit];
         });
     }
     return NSTerminateCancel;

- applicationWillTerminate: can be just the qemu_thread_join

Paolo

#5 lore raw
Quoted 9 lines · Paolo Bonzini

Il sab 16 lug 2022, 13:30 Akihiko Odaki <[email protected]> ha scritto:

Quoted 6 lines · Paolo Bonzini
Quoted 5 lines · Akihiko Odaki
Quoted 4 lines
   static void *call_qemu_main(void *opaque)
   {
      ...

+ [NSApp terminate:nil];

Quoted 7 lines
Quoted 5 lines
Quoted 1 line

Is this thread-safe? I think it should be something like:

Yes, -[NSApplication terminate:] is thread-safe. Methods of NSApplication handle dispatches to the main thread by themselves.

Is this documented anywhere?

Thread-unsafe classes (and more importantly, main thread only classes) are rather exceptional, and they are listed at:
https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html

Regards,
Akihiko Odaki

Quoted 44 lines

Paolo

Regards,

Quoted 39 lines

Akihiko Odaki

Quoted 35 lines

- here:

      /*
       * Nothing more to do in the QEMU thread, ask the application
       * to exit.
       */
      dispatch_async(dispatch_get_main_queue(), ^{
          [NSApp terminate: nil];
      });

- in verifyQuit:

      if([alert runModal] == NSAlertSecondButtonReturn) {
          with_iothread_lock(^{
              shutdown_action = SHUTDOWN_ACTION_POWEROFF;
              qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
          });
      }
      /* and just return void */

- applicationShouldTerminate: should be just

      if (qatomic_read(&qemu_main_terminating)) {
          return NSTerminateNow;
      } else {
          dispatch_async(dispatch_get_main_queue(), ^{
              [self verifyQuit];
          });
      }
      return NSTerminateCancel;

- applicationWillTerminate: can be just the qemu_thread_join

Paolo

#6 lore raw

Il sab 16 lug 2022, 22:42 Akihiko Odaki <[email protected]> ha scritto:

Quoted 6 lines
Quoted 1 line

Is this documented anywhere?

Thread-unsafe classes (and more importantly, main thread only classes) are rather exceptional, and they are listed at:

https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html

Being thread-safe is not the same thing as deferring to the main thread though.

Here are a couple of examples of how things can go wrong, depending on the implementation of Cocoa:

- applicationWillTerminate is a notification, and as such will run in the main thread, but will applicationShouldTerminate also be called only from the main thread? If not, is it safe to show the alert in verifyQuit?

- is the secondary thread still in terminate: when applicationWillTerminate runs, and is it waiting for applicationWillTerminate to finish? If so, qemu_thread_join will deadlock (because the waited thread will not exit until applicationWillTerminate returns)

In both cases the problem is not thread-unsafety of Cocoa, but thread-unsafety of the QEMU application delegate.

Paolo

Quoted 49 lines

Regards,
Akihiko Odaki

Quoted 44 lines

Paolo

Regards,

Quoted 39 lines

Akihiko Odaki

Quoted 35 lines

- here:

      /*
       * Nothing more to do in the QEMU thread, ask the application
       * to exit.
       */
      dispatch_async(dispatch_get_main_queue(), ^{
          [NSApp terminate: nil];
      });

- in verifyQuit:

      if([alert runModal] == NSAlertSecondButtonReturn) {
          with_iothread_lock(^{
              shutdown_action = SHUTDOWN_ACTION_POWEROFF;
              qemu_system_shutdown_request(SHUTDOWN_CAUSE_HOST_UI);
          });
      }
      /* and just return void */

- applicationShouldTerminate: should be just

      if (qatomic_read(&qemu_main_terminating)) {
          return NSTerminateNow;
      } else {
          dispatch_async(dispatch_get_main_queue(), ^{
              [self verifyQuit];
          });
      }
      return NSTerminateCancel;

- applicationWillTerminate: can be just the qemu_thread_join

Paolo

#7 lore raw

PATCH v3 2/3 Revert "main-loop: Disable block backend global state assertion on Cocoa"

In reply to Akihiko Odaki

This reverts commit 47281859f66bdab1974fb122cab2cbb4a1c9af7f.

---
 include/qemu/main-loop.h | 13 -------------
 1 file changed, 13 deletions(-)
include/qemu/main-loop.h +0 -13
index 5518845299d..0aa36a4f17e 100644
@@ -280,23 +280,10 @@ bool qemu_mutex_iothread_locked(void);
 bool qemu_in_main_thread(void);
 
 /* Mark and check that the function is part of the global state API. */
-#ifdef CONFIG_COCOA
-/*
- * When using the Cocoa UI, addRemovableDevicesMenuItems() is called from
- * a thread different from the QEMU main thread and can not take the BQL,
- * triggering this assertions in the block layer (commit 0439c5a462).
- * As the Cocoa fix is not trivial, disable this assertion for the v7.0.0
- * release (when using Cocoa); we will restore it immediately after the
- * release.
- * This issue is tracked as https://gitlab.com/qemu-project/qemu/-/issues/926
- */
-#define GLOBAL_STATE_CODE()
-#else
 #define GLOBAL_STATE_CODE()                                         \
     do {                                                            \
         assert(qemu_in_main_thread());                              \
     } while (0)
-#endif /* CONFIG_COCOA */
 
 /* Mark and check that the function is part of the I/O API. */
 #define IO_CODE()                                                   \
Signature · 1 line
2.32.1 (Apple Git-133)
#8 lore raw

PATCH v3 3/3 meson: Allow to enable gtk and sdl while cocoa is enabled

In reply to Akihiko Odaki

As ui/cocoa does no longer override main(), ui/gtk and ui/sdl can be enabled even ui/cocoa is enabled.

---
 meson.build | 10 ++--------
 1 file changed, 2 insertions(+), 8 deletions(-)
meson.build +2 -8
index bc5569ace15..7baec7896ef 100644
@@ -583,12 +583,6 @@ if get_option('attr').allowed()
 endif
 
 cocoa = dependency('appleframeworks', modules: 'Cocoa', required: get_option('cocoa'))
-if cocoa.found() and get_option('sdl').enabled()
-  error('Cocoa and SDL cannot be enabled at the same time')
-endif
-if cocoa.found() and get_option('gtk').enabled()
-  error('Cocoa and GTK+ cannot be enabled at the same time')
-endif
 
 vmnet = dependency('appleframeworks', modules: 'vmnet', required: get_option('vmnet'))
 if vmnet.found() and not cc.has_header_symbol('vmnet/vmnet.h',
@@ -915,7 +909,7 @@ if not get_option('brlapi').auto() or have_system
 endif
 
 sdl = not_found
-if not get_option('sdl').auto() or (have_system and not cocoa.found())
+if not get_option('sdl').auto() or have_system
   sdl = dependency('sdl2', required: get_option('sdl'), kwargs: static_kwargs)
   sdl_image = not_found
 endif
@@ -1181,7 +1175,7 @@ endif
 gtk = not_found
 gtkx11 = not_found
 vte = not_found
-if not get_option('gtk').auto() or (have_system and not cocoa.found())
+if not get_option('gtk').auto() or have_system
   gtk = dependency('gtk+-3.0', version: '>=3.22.0',
                    method: 'pkg-config',
                    required: get_option('gtk'),
Signature · 1 line
2.32.1 (Apple Git-133)