Skip to contentSkip to conversation

block layer: split block APIs in global state and I/O

RFC PATCH Superseded Emanuele Giuseppe Esposito 5 participants 74 messages Oct 5, 2021 – Oct 11, 2021

Subsystems (2)

v2 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

v2 cover block layer: split block APIs in global state and I/O

Currently, block layer APIs like block-backend.h contain a mix of functions that are either running in the main loop and under the BQL, or are thread-safe functions and run in iothreads performing I/O. The functions running under BQL also take care of modifying the block graph, by using drain and/or aio_context_acquire/release. This makes it very confusing to understand where each function runs, and what assumptions it provided with regards to thread safety.

We call the functions running under BQL "global state (GS) API", and distinguish them from the thread-safe "I/O API".

The aim of this series is to split the relevant block headers in global state and I/O sub-headers. The division will be done in this way:
header.h will be split in header-global-state.h, header-io.h and header-common.h. The latter will just contain the data structures needed by header-global-state and header-io, and common helpers that are neither in GS nor in I/O. header.h will stay for legacy and to avoid changing all includes in all QEMU c files, but will only include the two new headers. No function shall be added in header.c .
Once we split all relevant headers, it will be much easier to see what uses the AioContext lock and remove it, which is the overall main goal of this and other series that I posted/will post.

In addition to splitting the relevant headers shown in this series, it is also very helpful splitting the function pointers in some block structures, to understand what runs under AioContext lock and what doesn't. This is what patches 19-25 do.

Each function in the GS API will have an assertion, checking that it is always running under BQL.
I/O functions are instead thread safe (or so should be), meaning that they *can* run under BQL, but also in an iothread in another AioContext. Therefore they do not provide any assertion, and need to be audited manually to verify the correctness.

Adding assetions has helped finding 2 bugs already, as shown in my series "Migration: fix missing iothread locking". This series depends on those two fixes, as some assertions will fail because some iothread locks are missing.

Tested this series by running unit tests, qemu-iotests and qtests (x86_64)
Some functions in the GS API are used everywhere but not properly tested. Therefore their assertion is never actually run in the tests, so despite my very careful auditing, it is not impossible to exclude that some will trigger while actually using QEMU.

Patch 1 introduces qemu_in_main_thread(), the function used in all assertions. This had to be introduced otherwise all unit tests would fail, since they run in the main loop but use the code in stubs/iothread.c
Patches 2-14 and 19-25 (with the exception of patch 9, that is an additional assert) are all structured in the same way: first we split the header and in the next (even) patch we add assertions.
The rest of the patches ontain either both assertions and split, or have no assertions.

Next steps once this get reviewed:
1) audit the GS API and replace the AioContext lock with drains, or remove them when not necessary (requires further discussion).
2) [optional as it should be already the case] audit the I/O API and check that thread safety is guaranteed

Based-on: <[email protected]>

---
v1 -> v2:
* remove the iothread locking bug fix, and send it as separate patch
* rename graph API -> global state API
* better documented patch 1 (qemu_in_main_thread)
* add and split all other block layer headers
* fix warnings given by checkpatch on multiline comments

Emanuele Giuseppe Esposito (25):
main-loop.h: introduce qemu_in_main_thread() include/sysemu/block-backend: split header into I/O and global state
(GS) API
block/block-backend.c: assertions for block-backend include/block/block: split header into I/O and global state API assertions for block global state API include/block/block_int: split header into I/O and global state API assertions for block_int global state API
block: introduce assert_bdrv_graph_writable include/block/blockjob_int.h: split header into I/O and GS API assertions for blockjob_int.h
include/block/blockjob.h: global state API
assertions for blockob.h global state API include/systemu/blockdev.h: global state API
assertions for blockdev.h global state API include/block/snapshot: global state API + assertions block/backup-top.h: global state API + assertions include/block/transactions: global state API + assertions block/coroutines: I/O API
block_int-common.h: split function pointers in BlockDriver block_int-common.h: assertion in the callers of BlockDriver function
pointers
block_int-common.h: split function pointers in BdrvChildClass block_int-common.h: assertions in the callers of BdrvChildClass
function pointers
block-backend-common.h: split function pointers in BlockDevOps job.h: split function pointers in JobDriver
job.h: assertions in the callers of JobDriver funcion pointers

 block.c                                     |  186 ++-
 block/backup-top.c                          |    2 +
 block/backup-top.h                          |   11 +
 block/backup.c                              |    1 +
 block/block-backend.c                       |  104 +-
 block/commit.c                              |    4 +
 block/coroutines.h                          |    6 +
 block/dirty-bitmap.c                        |    2 +
 block/io.c                                  |   31 +
 block/meson.build                           |    7 +-
 block/mirror.c                              |    4 +
 block/monitor/bitmap-qmp-cmds.c             |    6 +
 block/snapshot.c                            |   28 +
 block/stream.c                              |    2 +
 blockdev.c                                  |   25 +
 blockjob.c                                  |   14 +
 include/block/block-common.h                |  389 +++++
 include/block/block-global-state.h          |  263 ++++
 include/block/block-io.h                    |  278 ++++
 include/block/block.h                       |  859 +----------
 include/block/block_int-common.h            | 1179 ++++++++++++++++
 include/block/block_int-global-state.h      |  352 +++++
 include/block/block_int-io.h                |  124 ++
 include/block/block_int.h                   | 1412 +------------------
 include/block/blockjob.h                    |   23 +
 include/block/blockjob_int.h                |   55 +
 include/block/snapshot.h                    |   21 +
 include/qemu/job.h                          |   31 +
 include/qemu/main-loop.h                    |   13 +
 include/qemu/transactions.h                 |   24 +
 include/sysemu/block-backend-common.h       |  106 ++
 include/sysemu/block-backend-global-state.h |  136 ++
 include/sysemu/block-backend-io.h           |  130 ++
 include/sysemu/block-backend.h              |  262 +---
 include/sysemu/blockdev.h                   |   35 +-
 job.c                                       |    9 +
 migration/savevm.c                          |    2 +
 softmmu/cpus.c                              |    5 +
 softmmu/qdev-monitor.c                      |    2 +
 stubs/iothread-lock.c                       |    5 +
 util/transactions.c                         |    4 +
 41 files changed, 3615 insertions(+), 2537 deletions(-)
 create mode 100644 include/block/block-common.h
 create mode 100644 include/block/block-global-state.h
 create mode 100644 include/block/block-io.h
 create mode 100644 include/block/block_int-common.h
 create mode 100644 include/block/block_int-global-state.h
 create mode 100644 include/block/block_int-io.h
 create mode 100644 include/sysemu/block-backend-common.h
 create mode 100644 include/sysemu/block-backend-global-state.h
 create mode 100644 include/sysemu/block-backend-io.h
Signature · 1 line
2.27.0
#1 lore raw

RFC PATCH v2 1/25 main-loop.h: introduce qemu_in_main_thread()

When invoked from the main loop, this function is the same as qemu_mutex_iothread_locked, and returns true if the BQL is held. When invoked from iothreads or tests, it returns true only if the current AioContext is the Main Loop.

This essentially just extends qemu_mutex_iothread_locked to work also in unit tests or other users like storage-daemon, that run in the Main Loop but end up using the implementation in stubs/iothread-lock.c.

Using qemu_mutex_iothread_locked in unit tests defaults to false because they use the implementation in stubs/iothread-lock, making all assertions added in next patches fail despite the AioContext is still the main loop.

---
 include/qemu/main-loop.h | 13 +++++++++++++
 softmmu/cpus.c           |  5 +++++
 stubs/iothread-lock.c    |  5 +++++
 3 files changed, 23 insertions(+)
include/qemu/main-loop.h +13 -0
index 8dbc6fcb89..6b8fa57c5d 100644
@@ -245,6 +245,19 @@ AioContext *iohandler_get_aio_context(void);
  */
 bool qemu_mutex_iothread_locked(void);
 
+/**
+ * qemu_in_main_thread: same as qemu_mutex_iothread_locked when
+ * softmmu/cpus.c implementation is linked. Otherwise this function
+ * checks that the current AioContext is the global AioContext
+ * (main loop).
+ *
+ * This is useful when checking that the BQL is held, to avoid
+ * returning false when invoked by unit tests or other users like
+ * storage-daemon that end up using stubs/iothread-lock.c
+ * implementation.
+ */
+bool qemu_in_main_thread(void);
+
 /**
  * qemu_mutex_lock_iothread: Lock the main loop mutex.
  *
softmmu/cpus.c +5 -0
index 071085f840..3f61a3c31d 100644
@@ -481,6 +481,11 @@ bool qemu_mutex_iothread_locked(void)
     return iothread_locked;
 }
 
+bool qemu_in_main_thread(void)
+{
+    return qemu_mutex_iothread_locked();
+}
+
 /*
  * The BQL is taken from so many places that it is worth profiling the
  * callers directly, instead of funneling them all through a single function.
stubs/iothread-lock.c +5 -0
index 5b45b7fc8b..ff7386e42c 100644
@@ -6,6 +6,11 @@ bool qemu_mutex_iothread_locked(void)
     return false;
 }
 
+bool qemu_in_main_thread(void)
+{
+    return qemu_get_current_aio_context() == qemu_get_aio_context();
+}
+
 void qemu_mutex_lock_iothread_impl(const char *file, int line)
 {
 }
Signature · 1 line
2.27.0
#3 lore raw

RFC PATCH v2 2/25 include/sysemu/block-backend: split header into I/O and global state (GS) API

In reply to Emanuele Giuseppe Esposito

block-backend.h currently contains a mix of functions:
some of them run under the BQL and modify the block layer graph, others are instead thread-safe and perform I/O in iothreads. It is not easy to understand which function is part of which group (I/O vs GS), and this patch aims to clarify it.

The "GS" functions need the BQL, and often use aio_context_acquire/release and/or drain to be sure they can modify the graph safely.
The I/O function are instead thread safe, and can run in any AioContext.

By splitting the header in two files, block-backend-io.h and block-backend-global-state.h we have a clearer view on what needs what kind of protection. block-backend-common.h instead contains common structures shared by both headers.

In addition, remove "block/block.h" include as it seems it is not necessary anymore, together with "qemu/iov.h"

block-backend.h is left there for legacy and to avoid changing all includes in all c files that use the block-backend APIs.

Assertions are added in the next patch.

---
 block/block-backend.c                       |  10 +-
 include/sysemu/block-backend-common.h       |  74 ++++++
 include/sysemu/block-backend-global-state.h | 136 ++++++++++
 include/sysemu/block-backend-io.h           | 130 ++++++++++
 include/sysemu/block-backend.h              | 262 +-------------------
 5 files changed, 350 insertions(+), 262 deletions(-)
 create mode 100644 include/sysemu/block-backend-common.h
 create mode 100644 include/sysemu/block-backend-global-state.h
 create mode 100644 include/sysemu/block-backend-io.h
block/block-backend.c +7 -3
index deb55c272e..d31ae16b99 100644
@@ -78,6 +78,7 @@ struct BlockBackend {
     bool allow_aio_context_change;
     bool allow_write_beyond_eof;
 
+    /* Protected by BQL lock */
     NotifierList remove_bs_notifiers, insert_bs_notifiers;
     QLIST_HEAD(, BlockBackendAioNotifier) aio_notifiers;
 
@@ -110,12 +111,14 @@ static const AIOCBInfo block_backend_aiocb_info = {
 static void drive_info_del(DriveInfo *dinfo);
 static BlockBackend *bdrv_first_blk(BlockDriverState *bs);
 
-/* All BlockBackends */
+/* All BlockBackends. Protected by BQL lock. */
 static QTAILQ_HEAD(, BlockBackend) block_backends =
     QTAILQ_HEAD_INITIALIZER(block_backends);
 
-/* All BlockBackends referenced by the monitor and which are iterated through by
- * blk_next() */
+/*
+ * All BlockBackends referenced by the monitor and which are iterated through by
+ * blk_next(). Protected by BQL lock.
+ */
 static QTAILQ_HEAD(, BlockBackend) monitor_block_backends =
     QTAILQ_HEAD_INITIALIZER(monitor_block_backends);
 
@@ -985,6 +988,7 @@ BlockBackend *blk_by_dev(void *dev)
 void blk_set_dev_ops(BlockBackend *blk, const BlockDevOps *ops,
                      void *opaque)
 {
+    g_assert(qemu_in_main_thread());
     blk->dev_ops = ops;
     blk->dev_opaque = opaque;
 
include/sysemu/block-backend-common.h new file +74 -0

74 lines not on this page · raw message

include/sysemu/block-backend-global-state.h new file +136 -0

136 lines not on this page · raw message

include/sysemu/block-backend-io.h new file +130 -0

130 lines not on this page · raw message

include/sysemu/block-backend.h +3 -259

268 lines not on this page · raw message

Signature · 1 line
2.27.0
#9 lore raw

RFC PATCH v2 4/25 include/block/block: split header into I/O and global state API

In reply to Emanuele Giuseppe Esposito

Similarly to the previous patch, split block.h
in block-io.h and block-global-state.h

block-common.h contains the structures shared between the two headers, and the functions that can't be categorized as I/O or global state.

Assertions are added in the next patch.

---
 block.c                            |   3 +
 block/meson.build                  |   7 +-
 include/block/block-common.h       | 389 +++++++++++++
 include/block/block-global-state.h | 263 +++++++++
 include/block/block-io.h           | 278 ++++++++++
 include/block/block.h              | 859 +----------------------------
 6 files changed, 942 insertions(+), 857 deletions(-)
 create mode 100644 include/block/block-common.h
 create mode 100644 include/block/block-global-state.h
 create mode 100644 include/block/block-io.h
block.c +3 -0
index e97ce0b1c8..d31543ac37 100644
@@ -65,12 +65,15 @@
 
 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
 
+/* Protected by BQL */
 static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
 
+/* Protected by BQL */
 static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
     QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
 
+/* Protected by BQL */
 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
     QLIST_HEAD_INITIALIZER(bdrv_drivers);
 
block/meson.build +5 -2
index 0450914c7a..f5c942c697 100644
@@ -113,8 +113,11 @@ block_ss.add(module_block_h)
 wrapper_py = find_program('../scripts/block-coroutine-wrapper.py')
 block_gen_c = custom_target('block-gen.c',
                             output: 'block-gen.c',
-                            input: files('../include/block/block.h',
-                                         'coroutines.h'),
+                            input: files(
+                                      '../include/block/block-io.h',
+                                      '../include/block/block-global-state.h',
+                                      'coroutines.h'
+                                      ),
                             command: [wrapper_py, '@OUTPUT@', '@INPUT@'])
 block_ss.add(block_gen_c)
 
include/block/block-common.h new file +389 -0

389 lines not on this page · raw message

include/block/block-global-state.h new file +263 -0

263 lines not on this page · raw message

include/block/block-io.h new file +278 -0

278 lines not on this page · raw message

include/block/block.h +4 -855

864 lines not on this page · raw message

Signature · 1 line
2.27.0
#19 lore raw

RFC PATCH v2 6/25 include/block/block_int: split header into I/O and global state API

In reply to Emanuele Giuseppe Esposito

Similarly to the previous patch, split block_int.h in block_int-io.h and block_int-global-state.h

block_int-common.h contains the structures shared between the two headers, and the functions that can't be categorized as I/O or global state.

Assertions are added in the next patch.

---
 blockdev.c                             |    5 +
 include/block/block_int-common.h       | 1122 +++++++++++++++++++
 include/block/block_int-global-state.h |  346 ++++++
 include/block/block_int-io.h           |  124 +++
 include/block/block_int.h              | 1412 +-----------------------
 5 files changed, 1600 insertions(+), 1409 deletions(-)
 create mode 100644 include/block/block_int-common.h
 create mode 100644 include/block/block_int-global-state.h
 create mode 100644 include/block/block_int-io.h
blockdev.c +5 -0
index 44c419545c..75407cbf67 100644
@@ -64,6 +64,7 @@
 #include "qemu/main-loop.h"
 #include "qemu/throttle-options.h"
 
+/* Protected by BQL lock */
 QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
     QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
 
@@ -1208,6 +1209,8 @@ typedef struct BlkActionState BlkActionState;
  *
  * Only prepare() may fail. In a single transaction, only one of commit() or
  * abort() will be called. clean() will always be called if it is present.
+ *
+ * Always run under BQL.
  */
 typedef struct BlkActionOps {
     size_t instance_size;
@@ -2317,6 +2320,8 @@ static TransactionProperties *get_transaction_properties(
 /*
  * 'Atomic' group operations.  The operations are performed as a set, and if
  * any fail then we roll back all operations in the group.
+ *
+ * Always run under BQL.
  */
 void qmp_transaction(TransactionActionList *dev_list,
                      bool has_props,
include/block/block_int-common.h new file +1122 -0

1,122 lines not on this page · raw message

include/block/block_int-global-state.h new file +346 -0

346 lines not on this page · raw message

include/block/block_int-io.h new file +124 -0

124 lines not on this page · raw message

include/block/block_int.h +3 -1409

1,385 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.27.0

Part of the diff is not shown here. View the raw message.

#5 lore raw

RFC PATCH v2 3/25 block/block-backend.c: assertions for block-backend

In reply to Emanuele Giuseppe Esposito

All the global state (GS) API functions will check that qemu_in_main_thread() returns true. If not, it means that the safety of BQL cannot be guaranteed, and they need to be moved to I/O.

---
 block/block-backend.c  | 89 +++++++++++++++++++++++++++++++++++++++++-
 softmmu/qdev-monitor.c |  2 +
 2 files changed, 90 insertions(+), 1 deletion(-)
block/block-backend.c +88 -1
index d31ae16b99..9cd3b27b53 100644
@@ -227,6 +227,7 @@ static void blk_root_activate(BdrvChild *child, Error **errp)
 
 void blk_set_force_allow_inactivate(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     blk->force_allow_inactivate = true;
 }
 
@@ -345,6 +346,8 @@ BlockBackend *blk_new(AioContext *ctx, uint64_t perm, uint64_t shared_perm)
 {
     BlockBackend *blk;
 
+    g_assert(qemu_in_main_thread());
+
     blk = g_new0(BlockBackend, 1);
     blk->refcnt = 1;
     blk->ctx = ctx;
@@ -382,6 +385,8 @@ BlockBackend *blk_new_with_bs(BlockDriverState *bs, uint64_t perm,
 {
     BlockBackend *blk = blk_new(bdrv_get_aio_context(bs), perm, shared_perm);
 
+    g_assert(qemu_in_main_thread());
+
     if (blk_insert_bs(blk, bs, errp) < 0) {
         blk_unref(blk);
         return NULL;
@@ -410,6 +415,8 @@ BlockBackend *blk_new_open(const char *filename, const char *reference,
     uint64_t perm = 0;
     uint64_t shared = BLK_PERM_ALL;
 
+    g_assert(qemu_in_main_thread());
+
     /*
      * blk_new_open() is mainly used in .bdrv_create implementations and the
      * tools where sharing isn't a major concern because the BDS stays private
@@ -487,6 +494,7 @@ static void drive_info_del(DriveInfo *dinfo)
 
 int blk_get_refcnt(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     return blk ? blk->refcnt : 0;
 }
 
@@ -497,6 +505,7 @@ int blk_get_refcnt(BlockBackend *blk)
 void blk_ref(BlockBackend *blk)
 {
     assert(blk->refcnt > 0);
+    g_assert(qemu_in_main_thread());
     blk->refcnt++;
 }
 
@@ -507,6 +516,7 @@ void blk_ref(BlockBackend *blk)
  */
 void blk_unref(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     if (blk) {
         assert(blk->refcnt > 0);
         if (blk->refcnt > 1) {
@@ -527,6 +537,7 @@ void blk_unref(BlockBackend *blk)
  */
 BlockBackend *blk_all_next(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     return blk ? QTAILQ_NEXT(blk, link)
                : QTAILQ_FIRST(&block_backends);
 }
@@ -535,6 +546,8 @@ void blk_remove_all_bs(void)
 {
     BlockBackend *blk = NULL;
 
+    g_assert(qemu_in_main_thread());
+
     while ((blk = blk_all_next(blk)) != NULL) {
         AioContext *ctx = blk_get_aio_context(blk);
 
@@ -558,6 +571,7 @@ void blk_remove_all_bs(void)
  */
 BlockBackend *blk_next(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     return blk ? QTAILQ_NEXT(blk, monitor_link)
                : QTAILQ_FIRST(&monitor_block_backends);
 }
@@ -624,6 +638,7 @@ static void bdrv_next_reset(BdrvNextIterator *it)
 
 BlockDriverState *bdrv_first(BdrvNextIterator *it)
 {
+    g_assert(qemu_in_main_thread());
     bdrv_next_reset(it);
     return bdrv_next(it);
 }
@@ -661,6 +676,7 @@ bool monitor_add_blk(BlockBackend *blk, const char *name, Error **errp)
 {
     assert(!blk->name);
     assert(name && name[0]);
+    g_assert(qemu_in_main_thread());
 
     if (!id_wellformed(name)) {
         error_setg(errp, "Invalid device name");
@@ -688,6 +704,8 @@ bool monitor_add_blk(BlockBackend *blk, const char *name, Error **errp)
  */
 void monitor_remove_blk(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
+
     if (!blk->name) {
         return;
     }
@@ -703,6 +721,7 @@ void monitor_remove_blk(BlockBackend *blk)
  */
 const char *blk_name(const BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     return blk->name ?: "";
 }
 
@@ -714,6 +733,7 @@ BlockBackend *blk_by_name(const char *name)
 {
     BlockBackend *blk = NULL;
 
+    g_assert(qemu_in_main_thread());
     assert(name);
     while ((blk = blk_next(blk)) != NULL) {
         if (!strcmp(name, blk->name)) {
@@ -748,6 +768,7 @@ static BlockBackend *bdrv_first_blk(BlockDriverState *bs)
  */
 bool bdrv_has_blk(BlockDriverState *bs)
 {
+    g_assert(qemu_in_main_thread());
     return bdrv_first_blk(bs) != NULL;
 }
 
@@ -758,6 +779,7 @@ bool bdrv_is_root_node(BlockDriverState *bs)
 {
     BdrvChild *c;
 
+    g_assert(qemu_in_main_thread());
     QLIST_FOREACH(c, &bs->parents, next_parent) {
         if (c->klass != &child_root) {
             return false;
@@ -807,6 +829,7 @@ BlockBackend *blk_by_legacy_dinfo(DriveInfo *dinfo)
  */
 BlockBackendPublic *blk_get_public(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     return &blk->public;
 }
 
@@ -815,6 +838,7 @@ BlockBackendPublic *blk_get_public(BlockBackend *blk)
  */
 BlockBackend *blk_by_public(BlockBackendPublic *public)
 {
+    g_assert(qemu_in_main_thread());
     return container_of(public, BlockBackend, public);
 }
 
@@ -827,6 +851,8 @@ void blk_remove_bs(BlockBackend *blk)
     BlockDriverState *bs;
     BdrvChild *root;
 
+    g_assert(qemu_in_main_thread());
+
     notifier_list_notify(&blk->remove_bs_notifiers, blk);
     if (tgm->throttle_state) {
         bs = blk_bs(blk);
@@ -854,6 +880,7 @@ void blk_remove_bs(BlockBackend *blk)
 int blk_insert_bs(BlockBackend *blk, BlockDriverState *bs, Error **errp)
 {
     ThrottleGroupMember *tgm = &blk->public.throttle_group_member;
+    g_assert(qemu_in_main_thread());
     bdrv_ref(bs);
     blk->root = bdrv_root_attach_child(bs, "root", &child_root,
                                        BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY,
@@ -880,6 +907,7 @@ int blk_set_perm(BlockBackend *blk, uint64_t perm, uint64_t shared_perm,
 {
     int ret;
 
+    g_assert(qemu_in_main_thread());
     if (blk->root && !blk->disable_perm) {
         ret = bdrv_child_try_set_perm(blk->root, perm, shared_perm, errp);
         if (ret < 0) {
@@ -895,6 +923,7 @@ int blk_set_perm(BlockBackend *blk, uint64_t perm, uint64_t shared_perm,
 
 void blk_get_perm(BlockBackend *blk, uint64_t *perm, uint64_t *shared_perm)
 {
+    g_assert(qemu_in_main_thread());
     *perm = blk->perm;
     *shared_perm = blk->shared_perm;
 }
@@ -905,6 +934,7 @@ void blk_get_perm(BlockBackend *blk, uint64_t *perm, uint64_t *shared_perm)
  */
 int blk_attach_dev(BlockBackend *blk, DeviceState *dev)
 {
+    g_assert(qemu_in_main_thread());
     if (blk->dev) {
         return -EBUSY;
     }
@@ -930,6 +960,7 @@ int blk_attach_dev(BlockBackend *blk, DeviceState *dev)
 void blk_detach_dev(BlockBackend *blk, DeviceState *dev)
 {
     assert(blk->dev == dev);
+    g_assert(qemu_in_main_thread());
     blk->dev = NULL;
     blk->dev_ops = NULL;
     blk->dev_opaque = NULL;
@@ -943,6 +974,7 @@ void blk_detach_dev(BlockBackend *blk, DeviceState *dev)
  */
 DeviceState *blk_get_attached_dev(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     return blk->dev;
 }
 
@@ -951,6 +983,7 @@ DeviceState *blk_get_attached_dev(BlockBackend *blk)
 char *blk_get_attached_dev_id(BlockBackend *blk)
 {
     DeviceState *dev = blk->dev;
+    g_assert(qemu_in_main_thread());
 
     if (!dev) {
         return g_strdup("");
@@ -971,6 +1004,8 @@ BlockBackend *blk_by_dev(void *dev)
 {
     BlockBackend *blk = NULL;
 
+    g_assert(qemu_in_main_thread());
+
     assert(dev != NULL);
     while ((blk = blk_all_next(blk)) != NULL) {
         if (blk->dev == dev) {
@@ -1010,6 +1045,7 @@ void blk_set_dev_ops(BlockBackend *blk, const BlockDevOps *ops,
  */
 void blk_dev_change_media_cb(BlockBackend *blk, bool load, Error **errp)
 {
+    g_assert(qemu_in_main_thread());
     if (blk->dev_ops && blk->dev_ops->change_media_cb) {
         bool tray_was_open, tray_is_open;
         Error *local_err = NULL;
@@ -1101,6 +1137,7 @@ static void blk_root_resize(BdrvChild *child)
 
 void blk_iostatus_enable(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     blk->iostatus_enabled = true;
     blk->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
 }
@@ -1109,6 +1146,7 @@ void blk_iostatus_enable(BlockBackend *blk)
  * enables it _and_ the VM is configured to stop on errors */
 bool blk_iostatus_is_enabled(const BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     return (blk->iostatus_enabled &&
            (blk->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
             blk->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
@@ -1117,16 +1155,19 @@ bool blk_iostatus_is_enabled(const BlockBackend *blk)
 
 BlockDeviceIoStatus blk_iostatus(const BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     return blk->iostatus;
 }
 
 void blk_iostatus_disable(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     blk->iostatus_enabled = false;
 }
 
 void blk_iostatus_reset(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     if (blk_iostatus_is_enabled(blk)) {
         blk->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
     }
@@ -1134,6 +1175,7 @@ void blk_iostatus_reset(BlockBackend *blk)
 
 void blk_iostatus_set_err(BlockBackend *blk, int error)
 {
+    g_assert(qemu_in_main_thread());
     assert(blk_iostatus_is_enabled(blk));
     if (blk->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
         blk->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
@@ -1366,6 +1408,7 @@ int blk_pwrite_zeroes(BlockBackend *blk, int64_t offset,
 
 int blk_make_zero(BlockBackend *blk, BdrvRequestFlags flags)
 {
+    g_assert(qemu_in_main_thread());
     return bdrv_make_zero(blk->root, flags);
 }
 
@@ -1394,6 +1437,7 @@ BlockAIOCB *blk_abort_aio_request(BlockBackend *blk,
                                   void *opaque, int ret)
 {
     struct BlockBackendAIOCB *acb;
+    g_assert(qemu_in_main_thread());
 
     blk_inc_in_flight(blk);
     acb = blk_aio_get(&block_backend_aiocb_info, blk, cb, opaque);
@@ -1544,6 +1588,7 @@ void blk_get_geometry(BlockBackend *blk, uint64_t *nb_sectors_ptr)
 
 int64_t blk_nb_sectors(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     if (!blk_is_available(blk)) {
         return -ENOMEDIUM;
     }
@@ -1569,6 +1614,7 @@ BlockAIOCB *blk_aio_pwritev(BlockBackend *blk, int64_t offset,
 
 void blk_aio_cancel(BlockAIOCB *acb)
 {
+    g_assert(qemu_in_main_thread());
     bdrv_aio_cancel(acb);
 }
 
@@ -1732,6 +1778,8 @@ void blk_drain(BlockBackend *blk)
 {
     BlockDriverState *bs = blk_bs(blk);
 
+    g_assert(qemu_in_main_thread());
+
     if (bs) {
         bdrv_drained_begin(bs);
     }
@@ -1749,6 +1797,8 @@ void blk_drain_all(void)
 {
     BlockBackend *blk = NULL;
 
+    g_assert(qemu_in_main_thread());
+
     bdrv_drain_all_begin();
 
     while ((blk = blk_all_next(blk)) != NULL) {
@@ -1768,6 +1818,7 @@ void blk_drain_all(void)
 void blk_set_on_error(BlockBackend *blk, BlockdevOnError on_read_error,
                       BlockdevOnError on_write_error)
 {
+    g_assert(qemu_in_main_thread());
     blk->on_read_error = on_read_error;
     blk->on_write_error = on_write_error;
 }
@@ -1851,6 +1902,7 @@ void blk_error_action(BlockBackend *blk, BlockErrorAction action,
 bool blk_supports_write_perm(BlockBackend *blk)
 {
     BlockDriverState *bs = blk_bs(blk);
+    g_assert(qemu_in_main_thread());
 
     if (bs) {
         return !bdrv_is_read_only(bs);
@@ -1871,6 +1923,7 @@ bool blk_is_writable(BlockBackend *blk)
 bool blk_is_sg(BlockBackend *blk)
 {
     BlockDriverState *bs = blk_bs(blk);
+    g_assert(qemu_in_main_thread());
 
     if (!bs) {
         return false;
@@ -1881,17 +1934,20 @@ bool blk_is_sg(BlockBackend *blk)
 
 bool blk_enable_write_cache(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     return blk->enable_write_cache;
 }
 
 void blk_set_enable_write_cache(BlockBackend *blk, bool wce)
 {
+    g_assert(qemu_in_main_thread());
     blk->enable_write_cache = wce;
 }
 
 void blk_invalidate_cache(BlockBackend *blk, Error **errp)
 {
     BlockDriverState *bs = blk_bs(blk);
+    g_assert(qemu_in_main_thread());
 
     if (!bs) {
         error_setg(errp, "Device '%s' has no medium", blk->name);
@@ -1904,7 +1960,6 @@ void blk_invalidate_cache(BlockBackend *blk, Error **errp)
 bool blk_is_inserted(BlockBackend *blk)
 {
     BlockDriverState *bs = blk_bs(blk);
-
     return bs && bdrv_is_inserted(bs);
 }
 
@@ -1916,6 +1971,7 @@ bool blk_is_available(BlockBackend *blk)
 void blk_lock_medium(BlockBackend *blk, bool locked)
 {
     BlockDriverState *bs = blk_bs(blk);
+    g_assert(qemu_in_main_thread());
 
     if (bs) {
         bdrv_lock_medium(bs, locked);
@@ -1925,6 +1981,8 @@ void blk_lock_medium(BlockBackend *blk, bool locked)
 void blk_eject(BlockBackend *blk, bool eject_flag)
 {
     BlockDriverState *bs = blk_bs(blk);
+    g_assert(qemu_in_main_thread());
+
     char *id;
 
     if (bs) {
@@ -1942,6 +2000,7 @@ void blk_eject(BlockBackend *blk, bool eject_flag)
 int blk_get_flags(BlockBackend *blk)
 {
     BlockDriverState *bs = blk_bs(blk);
+    g_assert(qemu_in_main_thread());
 
     if (bs) {
         return bdrv_get_flags(bs);
@@ -1989,6 +2048,7 @@ int blk_get_max_iov(BlockBackend *blk)
 
 void blk_set_guest_block_size(BlockBackend *blk, int align)
 {
+    g_assert(qemu_in_main_thread());
     blk->guest_block_size = align;
 }
 
@@ -2005,6 +2065,7 @@ void *blk_blockalign(BlockBackend *blk, size_t size)
 bool blk_op_is_blocked(BlockBackend *blk, BlockOpType op, Error **errp)
 {
     BlockDriverState *bs = blk_bs(blk);
+    g_assert(qemu_in_main_thread());
 
     if (!bs) {
         return false;
@@ -2016,6 +2077,7 @@ bool blk_op_is_blocked(BlockBackend *blk, BlockOpType op, Error **errp)
 void blk_op_unblock(BlockBackend *blk, BlockOpType op, Error *reason)
 {
     BlockDriverState *bs = blk_bs(blk);
+    g_assert(qemu_in_main_thread());
 
     if (bs) {
         bdrv_op_unblock(bs, op, reason);
@@ -2025,6 +2087,7 @@ void blk_op_unblock(BlockBackend *blk, BlockOpType op, Error *reason)
 void blk_op_block_all(BlockBackend *blk, Error *reason)
 {
     BlockDriverState *bs = blk_bs(blk);
+    g_assert(qemu_in_main_thread());
 
     if (bs) {
         bdrv_op_block_all(bs, reason);
@@ -2034,6 +2097,7 @@ void blk_op_block_all(BlockBackend *blk, Error *reason)
 void blk_op_unblock_all(BlockBackend *blk, Error *reason)
 {
     BlockDriverState *bs = blk_bs(blk);
+    g_assert(qemu_in_main_thread());
 
     if (bs) {
         bdrv_op_unblock_all(bs, reason);
@@ -2088,6 +2152,7 @@ static int blk_do_set_aio_context(BlockBackend *blk, AioContext *new_context,
 int blk_set_aio_context(BlockBackend *blk, AioContext *new_context,
                         Error **errp)
 {
+    g_assert(qemu_in_main_thread());
     return blk_do_set_aio_context(blk, new_context, true, errp);
 }
 
@@ -2124,6 +2189,7 @@ void blk_add_aio_context_notifier(BlockBackend *blk,
 {
     BlockBackendAioNotifier *notifier;
     BlockDriverState *bs = blk_bs(blk);
+    g_assert(qemu_in_main_thread());
 
     notifier = g_new(BlockBackendAioNotifier, 1);
     notifier->attached_aio_context = attached_aio_context;
@@ -2146,6 +2212,8 @@ void blk_remove_aio_context_notifier(BlockBackend *blk,
     BlockBackendAioNotifier *notifier;
     BlockDriverState *bs = blk_bs(blk);
 
+    g_assert(qemu_in_main_thread());
+
     if (bs) {
         bdrv_remove_aio_context_notifier(bs, attached_aio_context,
                                          detach_aio_context, opaque);
@@ -2166,11 +2234,13 @@ void blk_remove_aio_context_notifier(BlockBackend *blk,
 
 void blk_add_remove_bs_notifier(BlockBackend *blk, Notifier *notify)
 {
+    g_assert(qemu_in_main_thread());
     notifier_list_add(&blk->remove_bs_notifiers, notify);
 }
 
 void blk_add_insert_bs_notifier(BlockBackend *blk, Notifier *notify)
 {
+    g_assert(qemu_in_main_thread());
     notifier_list_add(&blk->insert_bs_notifiers, notify);
 }
 
@@ -2232,6 +2302,7 @@ int blk_save_vmstate(BlockBackend *blk, const uint8_t *buf,
                      int64_t pos, int size)
 {
     int ret;
+    g_assert(qemu_in_main_thread());
 
     if (!blk_is_available(blk)) {
         return -ENOMEDIUM;
@@ -2251,6 +2322,7 @@ int blk_save_vmstate(BlockBackend *blk, const uint8_t *buf,
 
 int blk_load_vmstate(BlockBackend *blk, uint8_t *buf, int64_t pos, int size)
 {
+    g_assert(qemu_in_main_thread());
     if (!blk_is_available(blk)) {
         return -ENOMEDIUM;
     }
@@ -2260,6 +2332,7 @@ int blk_load_vmstate(BlockBackend *blk, uint8_t *buf, int64_t pos, int size)
 
 int blk_probe_blocksizes(BlockBackend *blk, BlockSizes *bsz)
 {
+    g_assert(qemu_in_main_thread());
     if (!blk_is_available(blk)) {
         return -ENOMEDIUM;
     }
@@ -2269,6 +2342,7 @@ int blk_probe_blocksizes(BlockBackend *blk, BlockSizes *bsz)
 
 int blk_probe_geometry(BlockBackend *blk, HDGeometry *geo)
 {
+    g_assert(qemu_in_main_thread());
     if (!blk_is_available(blk)) {
         return -ENOMEDIUM;
     }
@@ -2282,6 +2356,7 @@ int blk_probe_geometry(BlockBackend *blk, HDGeometry *geo)
  */
 void blk_update_root_state(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     assert(blk->root);
 
     blk->root_state.open_flags    = blk->root->bs->open_flags;
@@ -2294,6 +2369,7 @@ void blk_update_root_state(BlockBackend *blk)
  */
 bool blk_get_detect_zeroes_from_root_state(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     return blk->root_state.detect_zeroes;
 }
 
@@ -2303,17 +2379,20 @@ bool blk_get_detect_zeroes_from_root_state(BlockBackend *blk)
  */
 int blk_get_open_flags_from_root_state(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     return blk->root_state.open_flags;
 }
 
 BlockBackendRootState *blk_get_root_state(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     return &blk->root_state;
 }
 
 int blk_commit_all(void)
 {
     BlockBackend *blk = NULL;
+    g_assert(qemu_in_main_thread());
 
     while ((blk = blk_all_next(blk)) != NULL) {
         AioContext *aio_context = blk_get_aio_context(blk);
@@ -2338,6 +2417,7 @@ int blk_commit_all(void)
 /* throttling disk I/O limits */
 void blk_set_io_limits(BlockBackend *blk, ThrottleConfig *cfg)
 {
+    g_assert(qemu_in_main_thread());
     throttle_group_config(&blk->public.throttle_group_member, cfg);
 }
 
@@ -2346,6 +2426,7 @@ void blk_io_limits_disable(BlockBackend *blk)
     BlockDriverState *bs = blk_bs(blk);
     ThrottleGroupMember *tgm = &blk->public.throttle_group_member;
     assert(tgm->throttle_state);
+    g_assert(qemu_in_main_thread());
     if (bs) {
         bdrv_drained_begin(bs);
     }
@@ -2359,12 +2440,14 @@ void blk_io_limits_disable(BlockBackend *blk)
 void blk_io_limits_enable(BlockBackend *blk, const char *group)
 {
     assert(!blk->public.throttle_group_member.throttle_state);
+    g_assert(qemu_in_main_thread());
     throttle_group_register_tgm(&blk->public.throttle_group_member,
                                 group, blk_get_aio_context(blk));
 }
 
 void blk_io_limits_update_group(BlockBackend *blk, const char *group)
 {
+    g_assert(qemu_in_main_thread());
     /* this BB is not part of any group */
     if (!blk->public.throttle_group_member.throttle_state) {
         return;
@@ -2432,11 +2515,13 @@ static void blk_root_drained_end(BdrvChild *child, int *drained_end_counter)
 
 void blk_register_buf(BlockBackend *blk, void *host, size_t size)
 {
+    g_assert(qemu_in_main_thread());
     bdrv_register_buf(blk_bs(blk), host, size);
 }
 
 void blk_unregister_buf(BlockBackend *blk, void *host)
 {
+    g_assert(qemu_in_main_thread());
     bdrv_unregister_buf(blk_bs(blk), host);
 }
 
@@ -2461,11 +2546,13 @@ int coroutine_fn blk_co_copy_range(BlockBackend *blk_in, int64_t off_in,
 
 const BdrvChild *blk_root(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     return blk->root;
 }
 
 int blk_make_empty(BlockBackend *blk, Error **errp)
 {
+    g_assert(qemu_in_main_thread());
     if (!blk_is_available(blk)) {
         error_setg(errp, "No medium inserted");
         return -ENOMEDIUM;
softmmu/qdev-monitor.c +2 -0
index 721dec2d82..dcf298b6af 100644
@@ -928,6 +928,8 @@ BlockBackend *blk_by_qdev_id(const char *id, Error **errp)
     DeviceState *dev;
     BlockBackend *blk;
 
+    g_assert(qemu_in_main_thread());
+
     dev = find_device_state(id, errp);
     if (dev == NULL) {
         return NULL;
Signature · 1 line
2.27.0
#17 lore raw

RFC PATCH v2 5/25 assertions for block global state API

In reply to Emanuele Giuseppe Esposito
---
 block.c        | 135 +++++++++++++++++++++++++++++++++++++++++++++++--
 block/commit.c |   2 +
 block/io.c     |  20 ++++++++
 blockdev.c     |   1 +
 4 files changed, 155 insertions(+), 3 deletions(-)
block.c +132 -3
index d31543ac37..6121af7040 100644
@@ -384,6 +384,7 @@ char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
 void bdrv_register(BlockDriver *bdrv)
 {
     assert(bdrv->format_name);
+    g_assert(qemu_in_main_thread());
     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
 }
 
@@ -392,6 +393,8 @@ BlockDriverState *bdrv_new(void)
     BlockDriverState *bs;
     int i;
 
+    g_assert(qemu_in_main_thread());
+
     bs = g_new0(BlockDriverState, 1);
     QLIST_INIT(&bs->dirty_bitmaps);
     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
@@ -416,6 +419,7 @@ BlockDriverState *bdrv_new(void)
 static BlockDriver *bdrv_do_find_format(const char *format_name)
 {
     BlockDriver *drv1;
+    g_assert(qemu_in_main_thread());
 
     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
         if (!strcmp(drv1->format_name, format_name)) {
@@ -431,6 +435,8 @@ BlockDriver *bdrv_find_format(const char *format_name)
     BlockDriver *drv1;
     int i;
 
+    g_assert(qemu_in_main_thread());
+
     drv1 = bdrv_do_find_format(format_name);
     if (drv1) {
         return drv1;
@@ -480,11 +486,13 @@ static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
 
 int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
 {
+    g_assert(qemu_in_main_thread());
     return bdrv_format_is_whitelisted(drv->format_name, read_only);
 }
 
 bool bdrv_uses_whitelist(void)
 {
+    g_assert(qemu_in_main_thread());
     return use_bdrv_whitelist;
 }
 
@@ -515,6 +523,8 @@ int bdrv_create(BlockDriver *drv, const char* filename,
 {
     int ret;
 
+    g_assert(qemu_in_main_thread());
+
     Coroutine *co;
     CreateCo cco = {
         .drv = drv,
@@ -690,6 +700,8 @@ int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
     QDict *qdict;
     int ret;
 
+    g_assert(qemu_in_main_thread());
+
     drv = bdrv_find_protocol(filename, true, errp);
     if (drv == NULL) {
         return -ENOENT;
@@ -787,6 +799,7 @@ int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
 {
     BlockDriver *drv = bs->drv;
     BlockDriverState *filtered = bdrv_filter_bs(bs);
+    g_assert(qemu_in_main_thread());
 
     if (drv && drv->bdrv_probe_blocksizes) {
         return drv->bdrv_probe_blocksizes(bs, bsz);
@@ -807,6 +820,7 @@ int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
 {
     BlockDriver *drv = bs->drv;
     BlockDriverState *filtered = bdrv_filter_bs(bs);
+    g_assert(qemu_in_main_thread());
 
     if (drv && drv->bdrv_probe_geometry) {
         return drv->bdrv_probe_geometry(bs, geo);
@@ -861,6 +875,7 @@ static BlockDriver *find_hdev_driver(const char *filename)
 {
     int score_max = 0, score;
     BlockDriver *drv = NULL, *d;
+    g_assert(qemu_in_main_thread());
 
     QLIST_FOREACH(d, &bdrv_drivers, list) {
         if (d->bdrv_probe_device) {
@@ -878,6 +893,7 @@ static BlockDriver *find_hdev_driver(const char *filename)
 static BlockDriver *bdrv_do_find_protocol(const char *protocol)
 {
     BlockDriver *drv1;
+    g_assert(qemu_in_main_thread());
 
     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
         if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
@@ -898,6 +914,7 @@ BlockDriver *bdrv_find_protocol(const char *filename,
     const char *p;
     int i;
 
+    g_assert(qemu_in_main_thread());
     /* TODO Drivers without bdrv_file_open must be specified explicitly */
 
     /*
@@ -963,6 +980,7 @@ BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
 {
     int score_max = 0, score;
     BlockDriver *drv = NULL, *d;
+    g_assert(qemu_in_main_thread());
 
     QLIST_FOREACH(d, &bdrv_drivers, list) {
         if (d->bdrv_probe) {
@@ -1110,6 +1128,7 @@ int bdrv_parse_aio(const char *mode, int *flags)
  */
 int bdrv_parse_discard_flags(const char *mode, int *flags)
 {
+    g_assert(qemu_in_main_thread());
     *flags &= ~BDRV_O_UNMAP;
 
     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
@@ -1130,6 +1149,7 @@ int bdrv_parse_discard_flags(const char *mode, int *flags)
  */
 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
 {
+    g_assert(qemu_in_main_thread());
     *flags &= ~BDRV_O_CACHE_MASK;
 
     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
@@ -1494,6 +1514,7 @@ static void bdrv_assign_node_name(BlockDriverState *bs,
                                   Error **errp)
 {
     char *gen_node_name = NULL;
+    g_assert(qemu_in_main_thread());
 
     if (!node_name) {
         node_name = gen_node_name = id_generate(ID_BLOCK);
@@ -1608,6 +1629,8 @@ BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
     BlockDriverState *bs;
     int ret;
 
+    g_assert(qemu_in_main_thread());
+
     bs = bdrv_new();
     bs->open_flags = flags;
     bs->explicit_options = qdict_new();
@@ -1720,6 +1743,7 @@ static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
 
     assert(bs->file == NULL);
     assert(options != NULL && bs->options != options);
+    g_assert(qemu_in_main_thread());
 
     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
     if (!qemu_opts_absorb_qdict(opts, options, errp)) {
@@ -2977,6 +3001,8 @@ BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
     BdrvChild *child = NULL;
     Transaction *tran = tran_new();
 
+    g_assert(qemu_in_main_thread());
+
     ret = bdrv_attach_child_noperm(parent_bs, child_bs, child_name, child_class,
                                    child_role, &child, tran, errp);
     if (ret < 0) {
@@ -3003,6 +3029,8 @@ void bdrv_root_unref_child(BdrvChild *child)
 {
     BlockDriverState *child_bs;
 
+    g_assert(qemu_in_main_thread());
+
     child_bs = child->bs;
     bdrv_detach_child(child);
     bdrv_unref(child_bs);
@@ -3077,6 +3105,7 @@ static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
 /* Callers must ensure that child->frozen is false. */
 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
 {
+    g_assert(qemu_in_main_thread());
     if (child == NULL) {
         return;
     }
@@ -3227,6 +3256,8 @@ int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
     int ret;
     Transaction *tran = tran_new();
 
+    g_assert(qemu_in_main_thread());
+
     ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
     if (ret < 0) {
         goto out;
@@ -3262,6 +3293,8 @@ int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
     QDict *tmp_parent_options = NULL;
     Error *local_err = NULL;
 
+    g_assert(qemu_in_main_thread());
+
     if (bs->backing != NULL) {
         goto free_exit;
     }
@@ -3421,6 +3454,8 @@ BdrvChild *bdrv_open_child(const char *filename,
 {
     BlockDriverState *bs;
 
+    g_assert(qemu_in_main_thread());
+
     bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
                             child_role, allow_none, errp);
     if (bs == NULL) {
@@ -3443,6 +3478,8 @@ BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
     const char *reference = NULL;
     Visitor *v = NULL;
 
+    g_assert(qemu_in_main_thread());
+
     if (ref->type == QTYPE_QSTRING) {
         reference = ref->u.reference;
     } else {
@@ -3840,6 +3877,8 @@ close_and_fail:
 BlockDriverState *bdrv_open(const char *filename, const char *reference,
                             QDict *options, int flags, Error **errp)
 {
+    g_assert(qemu_in_main_thread());
+
     return bdrv_open_inherit(filename, reference, options, flags, NULL,
                              NULL, 0, errp);
 }
@@ -4094,12 +4133,15 @@ BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
                                     BlockDriverState *bs,
                                     QDict *options, bool keep_old_opts)
 {
+    g_assert(qemu_in_main_thread());
+
     return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
                                    NULL, 0, keep_old_opts);
 }
 
 void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
 {
+    g_assert(qemu_in_main_thread());
     if (bs_queue) {
         BlockReopenQueueEntry *bs_entry, *next;
         QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
@@ -4247,6 +4289,8 @@ int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
     BlockReopenQueue *queue;
     int ret;
 
+    g_assert(qemu_in_main_thread());
+
     bdrv_subtree_drained_begin(bs);
     if (ctx != qemu_get_aio_context()) {
         aio_context_release(ctx);
@@ -4268,6 +4312,8 @@ int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
 {
     QDict *opts = qdict_new();
 
+    g_assert(qemu_in_main_thread());
+
     qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
 
     return bdrv_reopen(bs, opts, true, errp);
@@ -4720,6 +4766,7 @@ static void bdrv_close(BlockDriverState *bs)
 void bdrv_close_all(void)
 {
     assert(job_next(NULL) == NULL);
+    g_assert(qemu_in_main_thread());
 
     /* Drop references from requests still in flight, such as canceled block
      * jobs whose AIO context has not been polled yet */
@@ -5001,11 +5048,15 @@ out:
 int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
                       Error **errp)
 {
+    g_assert(qemu_in_main_thread());
+
     return bdrv_replace_node_common(from, to, true, false, errp);
 }
 
 int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
 {
+    g_assert(qemu_in_main_thread());
+
     return bdrv_replace_node_common(bs, bdrv_filter_or_cow_bs(bs), true, true,
                                     errp);
 }
@@ -5028,6 +5079,8 @@ int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
     int ret;
     Transaction *tran = tran_new();
 
+    g_assert(qemu_in_main_thread());
+
     assert(!bs_new->backing);
 
     ret = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
@@ -5055,6 +5108,7 @@ static void bdrv_delete(BlockDriverState *bs)
 {
     assert(bdrv_op_blocker_is_empty(bs));
     assert(!bs->refcnt);
+    g_assert(qemu_in_main_thread());
 
     /* remove from list, if necessary */
     if (bs->node_name[0] != '\0') {
@@ -5073,6 +5127,8 @@ BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *node_options,
     BlockDriverState *new_node_bs;
     Error *local_err = NULL;
 
+    g_assert(qemu_in_main_thread());
+
     new_node_bs = bdrv_open(NULL, NULL, node_options, flags, errp);
     if (new_node_bs == NULL) {
         error_prepend(errp, "Could not create node: ");
@@ -5127,6 +5183,8 @@ int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
     BlockDriver *drv = bs->drv;
     int ret;
 
+    g_assert(qemu_in_main_thread());
+
     if (!drv) {
         return -ENOMEDIUM;
     }
@@ -5168,6 +5226,9 @@ int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
                                     BlockDriverState *bs)
 {
+
+    g_assert(qemu_in_main_thread());
+
     bs = bdrv_skip_filters(bs);
     active = bdrv_skip_filters(active);
 
@@ -5185,6 +5246,8 @@ BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
 /* Given a BDS, searches for the base layer. */
 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
 {
+    g_assert(qemu_in_main_thread());
+
     return bdrv_find_overlay(bs, NULL);
 }
 
@@ -5199,6 +5262,8 @@ bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
     BlockDriverState *i;
     BdrvChild *child;
 
+    g_assert(qemu_in_main_thread());
+
     for (i = bs; i != base; i = child_bs(child)) {
         child = bdrv_filter_or_cow_child(i);
 
@@ -5225,6 +5290,8 @@ int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
     BlockDriverState *i;
     BdrvChild *child;
 
+    g_assert(qemu_in_main_thread());
+
     if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
         return -EPERM;
     }
@@ -5259,6 +5326,8 @@ void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
     BlockDriverState *i;
     BdrvChild *child;
 
+    g_assert(qemu_in_main_thread());
+
     for (i = bs; i != base; i = child_bs(child)) {
         child = bdrv_filter_or_cow_child(i);
         if (child) {
@@ -5308,6 +5377,8 @@ int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
     g_autoptr(GSList) updated_children = NULL;
     GSList *p;
 
+    g_assert(qemu_in_main_thread());
+
     bdrv_ref(top);
     bdrv_subtree_drained_begin(top);
 
@@ -5519,7 +5590,6 @@ int64_t bdrv_getlength(BlockDriverState *bs)
 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
 {
     int64_t nb_sectors = bdrv_nb_sectors(bs);
-
     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
 }
 
@@ -5569,6 +5639,8 @@ void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
     int i;
     const char **formats = NULL;
 
+    g_assert(qemu_in_main_thread());
+
     QLIST_FOREACH(drv, &bdrv_drivers, list) {
         if (drv->format_name) {
             bool found = false;
@@ -5627,6 +5699,7 @@ BlockDriverState *bdrv_find_node(const char *node_name)
     BlockDriverState *bs;
 
     assert(node_name);
+    g_assert(qemu_in_main_thread());
 
     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
         if (!strcmp(node_name, bs->node_name)) {
@@ -5643,6 +5716,8 @@ BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
     BlockDeviceInfoList *list;
     BlockDriverState *bs;
 
+    g_assert(qemu_in_main_thread());
+
     list = NULL;
     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
         BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
@@ -5748,6 +5823,8 @@ XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
     BdrvChild *child;
     XDbgBlockGraphConstructor *gr = xdbg_graph_new();
 
+    g_assert(qemu_in_main_thread());
+
     for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
         char *allocated_name = NULL;
         const char *name = blk_name(blk);
@@ -5791,6 +5868,8 @@ BlockDriverState *bdrv_lookup_bs(const char *device,
     BlockBackend *blk;
     BlockDriverState *bs;
 
+    g_assert(qemu_in_main_thread());
+
     if (device) {
         blk = blk_by_name(device);
 
@@ -5822,6 +5901,9 @@ BlockDriverState *bdrv_lookup_bs(const char *device,
  * return false.  If either argument is NULL, return false. */
 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
 {
+
+    g_assert(qemu_in_main_thread());
+
     while (top && top != base) {
         top = bdrv_filter_or_cow_bs(top);
     }
@@ -5831,6 +5913,7 @@ bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
 
 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
 {
+    g_assert(qemu_in_main_thread());
     if (!bs) {
         return QTAILQ_FIRST(&graph_bdrv_states);
     }
@@ -5839,6 +5922,7 @@ BlockDriverState *bdrv_next_node(BlockDriverState *bs)
 
 BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
 {
+    g_assert(qemu_in_main_thread());
     if (!bs) {
         return QTAILQ_FIRST(&all_bdrv_states);
     }
@@ -5871,6 +5955,7 @@ const char *bdrv_get_parent_name(const BlockDriverState *bs)
 /* TODO check what callers really want: bs->node_name or blk_name() */
 const char *bdrv_get_device_name(const BlockDriverState *bs)
 {
+    g_assert(qemu_in_main_thread());
     return bdrv_get_parent_name(bs) ?: "";
 }
 
@@ -5880,22 +5965,26 @@ const char *bdrv_get_device_name(const BlockDriverState *bs)
  * absent, then this returns an empty (non-null) string. */
 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
 {
+    g_assert(qemu_in_main_thread());
     return bdrv_get_parent_name(bs) ?: bs->node_name;
 }
 
 int bdrv_get_flags(BlockDriverState *bs)
 {
+    g_assert(qemu_in_main_thread());
     return bs->open_flags;
 }
 
 int bdrv_has_zero_init_1(BlockDriverState *bs)
 {
+    g_assert(qemu_in_main_thread());
     return 1;
 }
 
 int bdrv_has_zero_init(BlockDriverState *bs)
 {
     BlockDriverState *filtered;
+    g_assert(qemu_in_main_thread());
 
     if (!bs->drv) {
         return 0;
@@ -5992,6 +6081,7 @@ void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
 
 static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
 {
+    g_assert(qemu_in_main_thread());
     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
         bs = bdrv_primary_bs(bs);
     }
@@ -6007,6 +6097,7 @@ static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
                           const char *tag)
 {
+    g_assert(qemu_in_main_thread());
     bs = bdrv_find_debug_node(bs);
     if (bs) {
         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
@@ -6017,6 +6108,7 @@ int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
 
 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
 {
+    g_assert(qemu_in_main_thread());
     bs = bdrv_find_debug_node(bs);
     if (bs) {
         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
@@ -6027,6 +6119,7 @@ int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
 
 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
 {
+    g_assert(qemu_in_main_thread());
     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
         bs = bdrv_primary_bs(bs);
     }
@@ -6040,6 +6133,7 @@ int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
 
 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
 {
+    g_assert(qemu_in_main_thread());
     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
         bs = bdrv_primary_bs(bs);
     }
@@ -6067,6 +6161,8 @@ BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
     BlockDriverState *retval = NULL;
     BlockDriverState *bs_below;
 
+    g_assert(qemu_in_main_thread());
+
     if (!bs || !bs->drv || !backing_file) {
         return NULL;
     }
@@ -6165,6 +6261,7 @@ BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
 
 void bdrv_init(void)
 {
+    g_assert(qemu_in_main_thread());
 #ifdef CONFIG_BDRV_WHITELIST_TOOLS
     use_bdrv_whitelist = 1;
 #endif
@@ -6173,6 +6270,7 @@ void bdrv_init(void)
 
 void bdrv_init_with_whitelist(void)
 {
+    g_assert(qemu_in_main_thread());
     use_bdrv_whitelist = 1;
     bdrv_init();
 }
@@ -6257,6 +6355,8 @@ void bdrv_invalidate_cache_all(Error **errp)
     BlockDriverState *bs;
     BdrvNextIterator it;
 
+    g_assert(qemu_in_main_thread());
+
     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
         AioContext *aio_context = bdrv_get_aio_context(bs);
         int ret;
@@ -6348,6 +6448,8 @@ int bdrv_inactivate_all(void)
     int ret = 0;
     GSList *aio_ctxs = NULL, *ctx;
 
+    g_assert(qemu_in_main_thread());
+
     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
         AioContext *aio_context = bdrv_get_aio_context(bs);
 
@@ -6425,6 +6527,7 @@ void bdrv_eject(BlockDriverState *bs, bool eject_flag)
 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
 {
     BlockDriver *drv = bs->drv;
+    g_assert(qemu_in_main_thread());
 
     trace_bdrv_lock_medium(bs, locked);
 
@@ -6436,6 +6539,7 @@ void bdrv_lock_medium(BlockDriverState *bs, bool locked)
 /* Get a reference to bs */
 void bdrv_ref(BlockDriverState *bs)
 {
+    g_assert(qemu_in_main_thread());
     bs->refcnt++;
 }
 
@@ -6444,6 +6548,7 @@ void bdrv_ref(BlockDriverState *bs)
  * deleted. */
 void bdrv_unref(BlockDriverState *bs)
 {
+    g_assert(qemu_in_main_thread());
     if (!bs) {
         return;
     }
@@ -6461,6 +6566,7 @@ struct BdrvOpBlocker {
 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
 {
     BdrvOpBlocker *blocker;
+    g_assert(qemu_in_main_thread());
     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
         blocker = QLIST_FIRST(&bs->op_blockers[op]);
@@ -6475,6 +6581,7 @@ bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
 {
     BdrvOpBlocker *blocker;
+    g_assert(qemu_in_main_thread());
     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
 
     blocker = g_new0(BdrvOpBlocker, 1);
@@ -6485,6 +6592,7 @@ void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
 {
     BdrvOpBlocker *blocker, *next;
+    g_assert(qemu_in_main_thread());
     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
         if (blocker->reason == reason) {
@@ -6497,6 +6605,7 @@ void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
 {
     int i;
+    g_assert(qemu_in_main_thread());
     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
         bdrv_op_block(bs, i, reason);
     }
@@ -6505,6 +6614,7 @@ void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
 {
     int i;
+    g_assert(qemu_in_main_thread());
     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
         bdrv_op_unblock(bs, i, reason);
     }
@@ -6513,7 +6623,7 @@ void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
 {
     int i;
-
+    g_assert(qemu_in_main_thread());
     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
             return false;
@@ -6535,6 +6645,8 @@ void bdrv_img_create(const char *filename, const char *fmt,
     Error *local_err = NULL;
     int ret = 0;
 
+    g_assert(qemu_in_main_thread());
+
     /* Find driver and parse its options */
     drv = bdrv_find_format(fmt);
     if (!drv) {
@@ -6951,6 +7063,7 @@ static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
 bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
                                     GSList **ignore, Error **errp)
 {
+    g_assert(qemu_in_main_thread());
     if (g_slist_find(*ignore, c)) {
         return true;
     }
@@ -6969,6 +7082,8 @@ bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
         return true;
     }
 
+    g_assert(qemu_in_main_thread());
+
     QLIST_FOREACH(c, &bs->parents, next_parent) {
         if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
             return false;
@@ -6989,6 +7104,8 @@ int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
     GSList *ignore;
     bool ret;
 
+    g_assert(qemu_in_main_thread());
+
     ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
     ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
     g_slist_free(ignore);
@@ -7007,6 +7124,7 @@ int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
 int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
                              Error **errp)
 {
+    g_assert(qemu_in_main_thread());
     return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
 }
 
@@ -7020,6 +7138,7 @@ void bdrv_add_aio_context_notifier(BlockDriverState *bs,
         .detach_aio_context   = detach_aio_context,
         .opaque               = opaque
     };
+    g_assert(qemu_in_main_thread());
 
     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
 }
@@ -7031,6 +7150,7 @@ void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
                                       void *opaque)
 {
     BdrvAioNotifier *ban, *ban_next;
+    g_assert(qemu_in_main_thread());
 
     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
         if (ban->attached_aio_context == attached_aio_context &&
@@ -7055,6 +7175,7 @@ int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
                        bool force,
                        Error **errp)
 {
+    g_assert(qemu_in_main_thread());
     if (!bs->drv) {
         error_setg(errp, "Node is ejected");
         return -ENOMEDIUM;
@@ -7125,6 +7246,8 @@ BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
     AioContext *aio_context;
 
+    g_assert(qemu_in_main_thread());
+
     if (!to_replace_bs) {
         error_setg(errp, "Failed to find node with node-name='%s'", node_name);
         return NULL;
@@ -7286,6 +7409,8 @@ void bdrv_refresh_filename(BlockDriverState *bs)
     bool generate_json_filename; /* Whether our default implementation should
                                     fill exact_filename (false) or not (true) */
 
+    g_assert(qemu_in_main_thread());
+
     if (!drv) {
         return;
     }
@@ -7408,6 +7533,8 @@ char *bdrv_dirname(BlockDriverState *bs, Error **errp)
     BlockDriver *drv = bs->drv;
     BlockDriverState *child_bs;
 
+    g_assert(qemu_in_main_thread());
+
     if (!drv) {
         error_setg(errp, "Node '%s' is ejected", bs->node_name);
         return NULL;
@@ -7439,7 +7566,7 @@ char *bdrv_dirname(BlockDriverState *bs, Error **errp)
 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
                     Error **errp)
 {
-
+    g_assert(qemu_in_main_thread());
     if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
         error_setg(errp, "The node %s does not support adding a child",
                    bdrv_get_device_or_node_name(parent_bs));
@@ -7459,6 +7586,7 @@ void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
 {
     BdrvChild *tmp;
 
+    g_assert(qemu_in_main_thread());
     if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
         error_setg(errp, "The node %s does not support removing a child",
                    bdrv_get_device_or_node_name(parent_bs));
@@ -7486,6 +7614,7 @@ int bdrv_make_empty(BdrvChild *c, Error **errp)
     BlockDriver *drv = c->bs->drv;
     int ret;
 
+    g_assert(qemu_in_main_thread());
     assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
 
     if (!drv->bdrv_make_empty) {
block/commit.c +2 -0
index 42792b4556..87d7a764d8 100644
@@ -433,6 +433,8 @@ int bdrv_commit(BlockDriverState *bs)
     QEMU_AUTO_VFREE uint8_t *buf = NULL;
     Error *local_err = NULL;
 
+    g_assert(qemu_in_main_thread());
+
     if (!drv)
         return -ENOMEDIUM;
 
block/io.c +20 -0
index a19942718b..85242c0302 100644
@@ -163,6 +163,8 @@ void bdrv_refresh_limits(BlockDriverState *bs, Transaction *tran, Error **errp)
     BdrvChild *c;
     bool have_limits;
 
+    g_assert(qemu_in_main_thread());
+
     if (tran) {
         BdrvRefreshLimitsState *s = g_new(BdrvRefreshLimitsState, 1);
         *s = (BdrvRefreshLimitsState) {
@@ -543,6 +545,7 @@ void bdrv_drained_end(BlockDriverState *bs)
 
 void bdrv_drained_end_no_poll(BlockDriverState *bs, int *drained_end_counter)
 {
+    g_assert(qemu_in_main_thread());
     bdrv_do_drained_end(bs, false, NULL, false, drained_end_counter);
 }
 
@@ -585,12 +588,14 @@ void bdrv_unapply_subtree_drain(BdrvChild *child, BlockDriverState *old_parent)
 void coroutine_fn bdrv_co_drain(BlockDriverState *bs)
 {
     assert(qemu_in_coroutine());
+    g_assert(qemu_in_main_thread());
     bdrv_drained_begin(bs);
     bdrv_drained_end(bs);
 }
 
 void bdrv_drain(BlockDriverState *bs)
 {
+    g_assert(qemu_in_main_thread());
     bdrv_drained_begin(bs);
     bdrv_drained_end(bs);
 }
@@ -611,6 +616,7 @@ static bool bdrv_drain_all_poll(void)
 {
     BlockDriverState *bs = NULL;
     bool result = false;
+    g_assert(qemu_in_main_thread());
 
     /* bdrv_drain_poll() can't make changes to the graph and we are holding the
      * main AioContext lock, so iterating bdrv_next_all_states() is safe. */
@@ -639,6 +645,7 @@ static bool bdrv_drain_all_poll(void)
 void bdrv_drain_all_begin(void)
 {
     BlockDriverState *bs = NULL;
+    g_assert(qemu_in_main_thread());
 
     if (qemu_in_coroutine()) {
         bdrv_co_yield_to_drain(NULL, true, false, NULL, true, true, NULL);
@@ -695,6 +702,7 @@ void bdrv_drain_all_end(void)
 {
     BlockDriverState *bs = NULL;
     int drained_end_counter = 0;
+    g_assert(qemu_in_main_thread());
 
     /*
      * bdrv queue is managed by record/replay,
@@ -722,6 +730,7 @@ void bdrv_drain_all_end(void)
 
 void bdrv_drain_all(void)
 {
+    g_assert(qemu_in_main_thread());
     bdrv_drain_all_begin();
     bdrv_drain_all_end();
 }
@@ -2334,6 +2343,8 @@ int bdrv_flush_all(void)
     BlockDriverState *bs = NULL;
     int result = 0;
 
+    g_assert(qemu_in_main_thread());
+
     /*
      * bdrv queue is managed by record/replay,
      * creating new flush request for stopping
@@ -2664,6 +2675,7 @@ int bdrv_block_status_above(BlockDriverState *bs, BlockDriverState *base,
 int bdrv_block_status(BlockDriverState *bs, int64_t offset, int64_t bytes,
                       int64_t *pnum, int64_t *map, BlockDriverState **file)
 {
+    g_assert(qemu_in_main_thread());
     return bdrv_block_status_above(bs, bdrv_filter_or_cow_bs(bs),
                                    offset, bytes, pnum, map, file);
 }
@@ -2733,6 +2745,7 @@ int bdrv_is_allocated_above(BlockDriverState *top,
                             int64_t bytes, int64_t *pnum)
 {
     int depth;
+
     int ret = bdrv_common_block_status_above(top, base, include_base, false,
                                              offset, bytes, pnum, NULL, NULL,
                                              &depth);
@@ -2797,6 +2810,7 @@ bdrv_co_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
                       int64_t pos, int size)
 {
+    g_assert(qemu_in_main_thread());
     QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
     int ret = bdrv_writev_vmstate(bs, &qiov, pos);
 
@@ -2806,6 +2820,7 @@ int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
                       int64_t pos, int size)
 {
+    g_assert(qemu_in_main_thread());
     QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
     int ret = bdrv_readv_vmstate(bs, &qiov, pos);
 
@@ -2817,6 +2832,7 @@ int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
 
 void bdrv_aio_cancel(BlockAIOCB *acb)
 {
+    g_assert(qemu_in_main_thread());
     qemu_aio_ref(acb);
     bdrv_aio_cancel_async(acb);
     while (acb->refcnt > 1) {
@@ -2841,6 +2857,7 @@ void bdrv_aio_cancel(BlockAIOCB *acb)
  * In either case the completion callback must be called. */
 void bdrv_aio_cancel_async(BlockAIOCB *acb)
 {
+    g_assert(qemu_in_main_thread());
     if (acb->aiocb_info->cancel_async) {
         acb->aiocb_info->cancel_async(acb);
     }
@@ -3207,6 +3224,7 @@ void bdrv_register_buf(BlockDriverState *bs, void *host, size_t size)
 {
     BdrvChild *child;
 
+    g_assert(qemu_in_main_thread());
     if (bs->drv && bs->drv->bdrv_register_buf) {
         bs->drv->bdrv_register_buf(bs, host, size);
     }
@@ -3219,6 +3237,7 @@ void bdrv_unregister_buf(BlockDriverState *bs, void *host)
 {
     BdrvChild *child;
 
+    g_assert(qemu_in_main_thread());
     if (bs->drv && bs->drv->bdrv_unregister_buf) {
         bs->drv->bdrv_unregister_buf(bs, host);
     }
@@ -3490,6 +3509,7 @@ out:
 
 void bdrv_cancel_in_flight(BlockDriverState *bs)
 {
+    g_assert(qemu_in_main_thread());
     if (!bs || !bs->drv) {
         return;
     }
blockdev.c +1 -0
index 3d8ac368a1..44c419545c 100644
@@ -691,6 +691,7 @@ void blockdev_close_all_bdrv_states(void)
 /* Iterates over the list of monitor-owned BlockDriverStates */
 BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
 {
+    g_assert(qemu_in_main_thread());
     return bs ? QTAILQ_NEXT(bs, monitor_list)
               : QTAILQ_FIRST(&monitor_bdrv_states);
 }
Signature · 1 line
2.27.0
#38 lore raw

RFC PATCH v2 12/25 assertions for blockob.h global state API

In reply to Emanuele Giuseppe Esposito
---
 blockjob.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
blockjob.c +10 -0
index 9878e255c6..3b224136c0 100644
@@ -61,6 +61,7 @@ static bool is_block_job(Job *job)
 
 BlockJob *block_job_next(BlockJob *bjob)
 {
+    g_assert(qemu_in_main_thread());
     Job *job = bjob ? &bjob->job : NULL;
 
     do {
@@ -72,6 +73,7 @@ BlockJob *block_job_next(BlockJob *bjob)
 
 BlockJob *block_job_get(const char *id)
 {
+    g_assert(qemu_in_main_thread());
     Job *job = job_get(id);
 
     if (job && is_block_job(job)) {
@@ -185,6 +187,7 @@ static const BdrvChildClass child_job = {
 
 void block_job_remove_all_bdrv(BlockJob *job)
 {
+    g_assert(qemu_in_main_thread());
     /*
      * bdrv_root_unref_child() may reach child_job_[can_]set_aio_ctx(),
      * which will also traverse job->nodes, so consume the list one by
@@ -207,6 +210,7 @@ void block_job_remove_all_bdrv(BlockJob *job)
 bool block_job_has_bdrv(BlockJob *job, BlockDriverState *bs)
 {
     GSList *el;
+    g_assert(qemu_in_main_thread());
 
     for (el = job->nodes; el; el = el->next) {
         BdrvChild *c = el->data;
@@ -223,6 +227,7 @@ int block_job_add_bdrv(BlockJob *job, const char *name, BlockDriverState *bs,
 {
     BdrvChild *c;
     bool need_context_ops;
+    g_assert(qemu_in_main_thread());
 
     bdrv_ref(bs);
 
@@ -272,6 +277,8 @@ bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
     const BlockJobDriver *drv = block_job_driver(job);
     int64_t old_speed = job->speed;
 
+    g_assert(qemu_in_main_thread());
+
     if (job_apply_verb(&job->job, JOB_VERB_SET_SPEED, errp) < 0) {
         return false;
     }
@@ -309,6 +316,8 @@ BlockJobInfo *block_job_query(BlockJob *job, Error **errp)
     BlockJobInfo *info;
     uint64_t progress_current, progress_total;
 
+    g_assert(qemu_in_main_thread());
+
     if (block_job_is_internal(job)) {
         error_setg(errp, "Cannot query QEMU internal jobs");
         return NULL;
@@ -498,6 +507,7 @@ void *block_job_create(const char *job_id, const BlockJobDriver *driver,
 
 void block_job_iostatus_reset(BlockJob *job)
 {
+    g_assert(qemu_in_main_thread());
     if (job->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
         return;
     }
Signature · 1 line
2.27.0
#25 lore raw

RFC PATCH v2 8/25 block: introduce assert_bdrv_graph_writable

In reply to Emanuele Giuseppe Esposito

We want to be sure that the functions that write the child and parent list of a bs are either under BQL or drain.
If this guarantee holds, then we can read the list also in the I/O APIs.

---
 block.c                                | 5 +++++
 block/io.c                             | 5 +++++
 include/block/block_int-global-state.h | 8 +++++++-
 3 files changed, 17 insertions(+), 1 deletion(-)
block.c +5 -0
index b912f517a4..7d1eb847a4 100644
@@ -2711,12 +2711,14 @@ static void bdrv_replace_child_noperm(BdrvChild *child,
         if (child->klass->detach) {
             child->klass->detach(child);
         }
+        assert_bdrv_graph_writable(old_bs);
         QLIST_REMOVE(child, next_parent);
     }
 
     child->bs = new_bs;
 
     if (new_bs) {
+        assert_bdrv_graph_writable(new_bs);
         QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
 
         /*
@@ -2917,6 +2919,7 @@ static int bdrv_attach_child_noperm(BlockDriverState *parent_bs,
         return ret;
     }
 
+    assert_bdrv_graph_writable(parent_bs);
     QLIST_INSERT_HEAD(&parent_bs->children, *child, next);
     /*
      * child is removed in bdrv_attach_child_common_abort(), so don't care to
@@ -3117,6 +3120,7 @@ static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
 {
     g_assert(qemu_in_main_thread());
+    assert_bdrv_graph_writable(parent);
     if (child == NULL) {
         return;
     }
@@ -4878,6 +4882,7 @@ static void bdrv_remove_filter_or_cow_child_abort(void *opaque)
     BdrvRemoveFilterOrCowChild *s = opaque;
     BlockDriverState *parent_bs = s->child->opaque;
 
+    assert_bdrv_graph_writable(parent_bs);
     QLIST_INSERT_HEAD(&parent_bs->children, s->child, next);
     if (s->is_backing) {
         parent_bs->backing = s->child;
block/io.c +5 -0
index 21dcc5d962..d184183b07 100644
@@ -739,6 +739,11 @@ void bdrv_drain_all(void)
     bdrv_drain_all_end();
 }
 
+void assert_bdrv_graph_writable(BlockDriverState *bs)
+{
+    g_assert(qatomic_read(&bs->quiesce_counter) > 0 || qemu_in_main_thread());
+}
+
 /**
  * Remove an active request from the tracked requests list
  *
include/block/block_int-global-state.h +7 -1
index aad549cb85..a53ab146fc 100644
@@ -343,4 +343,10 @@ void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
  */
 void bdrv_drain_all_end_quiesce(BlockDriverState *bs);
 
-#endif /* BLOCK_INT_GLOBAL_STATE*/
+/**
+ * Make sure that the function is either running under
+ * drain, or under BQL.
+ */
+void assert_bdrv_graph_writable(BlockDriverState *bs);
+
+#endif /* BLOCK_INT_GLOBAL_STATE */
Signature · 1 line
2.27.0
#34 lore raw

RFC PATCH v2 11/25 include/block/blockjob.h: global state API

In reply to Emanuele Giuseppe Esposito

blockjob functions run always under the BQL lock.

---
 include/block/blockjob.h | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)
include/block/blockjob.h +23 -0
index d200f33c10..3bf384f8bf 100644
@@ -77,6 +77,27 @@ typedef struct BlockJob {
     GSList *nodes;
 } BlockJob;
 
+/*
+ * Global state (GS) API. These functions run under the BQL lock.
+ *
+ * If a function modifies the graph, it also uses drain and/or
+ * aio_context_acquire/release to be sure it has unique access.
+ * aio_context locking is needed together with BQL because of
+ * the thread-safe I/O API that concurrently runs and accesses
+ * the graph without the BQL.
+ *
+ * It is important to note that not all of these functions are
+ * necessarily limited to running under the BQL, but they would
+ * require additional auditing and may small thread-safety changes
+ * to move them into the I/O API. Often it's not worth doing that
+ * work since the APIs are only used with the BQL held at the
+ * moment, so they have been placed in the GS API (for now).
+ *
+ * All functions below must use this assertion:
+ * g_assert(qemu_in_main_thread());
+ * to catch when they are accidentally called without the BQL.
+ */
+
 /**
  * block_job_next:
  * @job: A block job, or %NULL.
@@ -158,6 +179,8 @@ BlockJobInfo *block_job_query(BlockJob *job, Error **errp);
  */
 void block_job_iostatus_reset(BlockJob *job);
 
+/* Common functions that are neither I/O nor Global State */
+
 /**
  * block_job_is_internal:
  * @job: The job to determine if it is user-visible or not.
Signature · 1 line
2.27.0
#23 lore raw

RFC PATCH v2 7/25 assertions for block_int global state API

In reply to Emanuele Giuseppe Esposito
---
 block.c                         | 17 +++++++++++++++++
 block/backup.c                  |  1 +
 block/block-backend.c           |  3 +++
 block/commit.c                  |  2 ++
 block/dirty-bitmap.c            |  2 ++
 block/io.c                      |  6 ++++++
 block/mirror.c                  |  4 ++++
 block/monitor/bitmap-qmp-cmds.c |  6 ++++++
 block/stream.c                  |  2 ++
 blockdev.c                      |  7 +++++++
 10 files changed, 50 insertions(+)
block.c +17 -0
index 6121af7040..b912f517a4 100644
@@ -648,6 +648,8 @@ int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
     Error *local_err = NULL;
     int ret;
 
+    g_assert(qemu_in_main_thread());
+
     size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
     prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
@@ -2405,6 +2407,8 @@ void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
     uint64_t cumulative_perms = 0;
     uint64_t cumulative_shared_perms = BLK_PERM_ALL;
 
+    g_assert(qemu_in_main_thread());
+
     QLIST_FOREACH(c, &bs->parents, next_parent) {
         cumulative_perms |= c->perm;
         cumulative_shared_perms &= c->shared_perm;
@@ -2463,6 +2467,8 @@ int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
     Transaction *tran = tran_new();
     int ret;
 
+    g_assert(qemu_in_main_thread());
+
     bdrv_child_set_perm(c, perm, shared, tran);
 
     ret = bdrv_refresh_perms(c->bs, &local_err);
@@ -2493,6 +2499,8 @@ int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
     uint64_t parent_perms, parent_shared;
     uint64_t perms, shared;
 
+    g_assert(qemu_in_main_thread());
+
     bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
     bdrv_child_perm(bs, c->bs, c, c->role, NULL,
                     parent_perms, parent_shared, &perms, &shared);
@@ -2635,6 +2643,7 @@ void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
                         uint64_t perm, uint64_t shared,
                         uint64_t *nperm, uint64_t *nshared)
 {
+    g_assert(qemu_in_main_thread());
     if (role & BDRV_CHILD_FILTERED) {
         assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
                          BDRV_CHILD_COW)));
@@ -2961,6 +2970,8 @@ BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
     BdrvChild *child = NULL;
     Transaction *tran = tran_new();
 
+    g_assert(qemu_in_main_thread());
+
     ret = bdrv_attach_child_common(child_bs, child_name, child_class,
                                    child_role, perm, shared_perm, opaque,
                                    &child, tran, errp);
@@ -5939,6 +5950,8 @@ const char *bdrv_get_parent_name(const BlockDriverState *bs)
     BdrvChild *c;
     const char *name;
 
+    g_assert(qemu_in_main_thread());
+
     /* If multiple parents have a name, just pick the first one. */
     QLIST_FOREACH(c, &bs->parents, next_parent) {
         if (c->klass->get_name) {
@@ -7206,6 +7219,8 @@ bool bdrv_recurse_can_replace(BlockDriverState *bs,
 {
     BlockDriverState *filtered;
 
+    g_assert(qemu_in_main_thread());
+
     if (!bs || !bs->drv) {
         return false;
     }
@@ -7377,6 +7392,7 @@ static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
  * would result in exactly bs->backing. */
 bool bdrv_backing_overridden(BlockDriverState *bs)
 {
+    g_assert(qemu_in_main_thread());
     if (bs->backing) {
         return strcmp(bs->auto_backing_file,
                       bs->backing->bs->filename);
@@ -7765,6 +7781,7 @@ static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
  */
 BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
 {
+    g_assert(qemu_in_main_thread());
     return bdrv_do_skip_filters(bs, true);
 }
 
block/backup.c +1 -0
index bd3614ce70..8677dd44dc 100644
@@ -413,6 +413,7 @@ BlockJob *backup_job_create(const char *job_id, BlockDriverState *bs,
 
     assert(bs);
     assert(target);
+    g_assert(qemu_in_main_thread());
 
     /* QMP interface protects us from these cases */
     assert(sync_mode != MIRROR_SYNC_MODE_INCREMENTAL);
block/block-backend.c +3 -0
index 9cd3b27b53..9f09245069 100644
@@ -1078,6 +1078,7 @@ static void blk_root_change_media(BdrvChild *child, bool load)
  */
 bool blk_dev_has_removable_media(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     return !blk->dev || (blk->dev_ops && blk->dev_ops->change_media_cb);
 }
 
@@ -1095,6 +1096,7 @@ bool blk_dev_has_tray(BlockBackend *blk)
  */
 void blk_dev_eject_request(BlockBackend *blk, bool force)
 {
+    g_assert(qemu_in_main_thread());
     if (blk->dev_ops && blk->dev_ops->eject_request_cb) {
         blk->dev_ops->eject_request_cb(blk->dev_opaque, force);
     }
@@ -1117,6 +1119,7 @@ bool blk_dev_is_tray_open(BlockBackend *blk)
  */
 bool blk_dev_is_medium_locked(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());
     if (blk->dev_ops && blk->dev_ops->is_medium_locked) {
         return blk->dev_ops->is_medium_locked(blk->dev_opaque);
     }
block/commit.c +2 -0
index 87d7a764d8..a030e0afbf 100644
@@ -253,6 +253,8 @@ void commit_start(const char *job_id, BlockDriverState *bs,
     uint64_t base_perms, iter_shared_perms;
     int ret;
 
+    g_assert(qemu_in_main_thread());
+
     assert(top != bs);
     if (bdrv_skip_filters(top) == bdrv_skip_filters(base)) {
         error_setg(errp, "Invalid files for merge: top and base are the same");
block/dirty-bitmap.c +2 -0
index 0ef46163e3..a9e87d92d9 100644
@@ -657,6 +657,7 @@ void bdrv_reset_dirty_bitmap(BdrvDirtyBitmap *bitmap,
 void bdrv_clear_dirty_bitmap(BdrvDirtyBitmap *bitmap, HBitmap **out)
 {
     assert(!bdrv_dirty_bitmap_readonly(bitmap));
+    g_assert(qemu_in_main_thread());
     bdrv_dirty_bitmaps_lock(bitmap->bs);
     if (!out) {
         hbitmap_reset_all(bitmap->bitmap);
@@ -673,6 +674,7 @@ void bdrv_restore_dirty_bitmap(BdrvDirtyBitmap *bitmap, HBitmap *backup)
 {
     HBitmap *tmp = bitmap->bitmap;
     assert(!bdrv_dirty_bitmap_readonly(bitmap));
+    g_assert(qemu_in_main_thread());
     bitmap->bitmap = backup;
     hbitmap_free(tmp);
 }
block/io.c +6 -0
index 85242c0302..21dcc5d962 100644
@@ -559,6 +559,7 @@ void bdrv_subtree_drained_end(BlockDriverState *bs)
 void bdrv_apply_subtree_drain(BdrvChild *child, BlockDriverState *new_parent)
 {
     int i;
+    g_assert(qemu_in_main_thread());
 
     for (i = 0; i < new_parent->recursive_quiesce_counter; i++) {
         bdrv_do_drained_begin(child->bs, true, child, false, true);
@@ -570,6 +571,8 @@ void bdrv_unapply_subtree_drain(BdrvChild *child, BlockDriverState *old_parent)
     int drained_end_counter = 0;
     int i;
 
+    g_assert(qemu_in_main_thread());
+
     for (i = 0; i < old_parent->recursive_quiesce_counter; i++) {
         bdrv_do_drained_end(child->bs, true, child, false,
                             &drained_end_counter);
@@ -689,6 +692,7 @@ void bdrv_drain_all_end_quiesce(BlockDriverState *bs)
 {
     int drained_end_counter = 0;
 
+    g_assert(qemu_in_main_thread());
     g_assert(bs->quiesce_counter > 0);
     g_assert(!bs->refcnt);
 
@@ -3334,6 +3338,7 @@ int coroutine_fn bdrv_co_copy_range_from(BdrvChild *src, int64_t src_offset,
 {
     trace_bdrv_co_copy_range_from(src, src_offset, dst, dst_offset, bytes,
                                   read_flags, write_flags);
+    g_assert(qemu_in_main_thread());
     return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
                                        bytes, read_flags, write_flags, true);
 }
@@ -3350,6 +3355,7 @@ int coroutine_fn bdrv_co_copy_range_to(BdrvChild *src, int64_t src_offset,
 {
     trace_bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
                                 read_flags, write_flags);
+    g_assert(qemu_in_main_thread());
     return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
                                        bytes, read_flags, write_flags, false);
 }
block/mirror.c +4 -0
index 98fc66eabf..589dd35b16 100644
@@ -1865,6 +1865,8 @@ void mirror_start(const char *job_id, BlockDriverState *bs,
     bool is_none_mode;
     BlockDriverState *base;
 
+    g_assert(qemu_in_main_thread());
+
     if ((mode == MIRROR_SYNC_MODE_INCREMENTAL) ||
         (mode == MIRROR_SYNC_MODE_BITMAP)) {
         error_setg(errp, "Sync mode '%s' not supported",
@@ -1890,6 +1892,8 @@ BlockJob *commit_active_start(const char *job_id, BlockDriverState *bs,
     bool base_read_only;
     BlockJob *job;
 
+    g_assert(qemu_in_main_thread());
+
     base_read_only = bdrv_is_read_only(base);
 
     if (base_read_only) {
block/monitor/bitmap-qmp-cmds.c +6 -0
index 9f11deec64..787ca17834 100644
@@ -56,6 +56,8 @@ BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
     BlockDriverState *bs;
     BdrvDirtyBitmap *bitmap;
 
+    g_assert(qemu_in_main_thread());
+
     if (!node) {
         error_setg(errp, "Node cannot be NULL");
         return NULL;
@@ -155,6 +157,8 @@ BdrvDirtyBitmap *block_dirty_bitmap_remove(const char *node, const char *name,
     BdrvDirtyBitmap *bitmap;
     AioContext *aio_context;
 
+    g_assert(qemu_in_main_thread());
+
     bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
     if (!bitmap || !bs) {
         return NULL;
@@ -261,6 +265,8 @@ BdrvDirtyBitmap *block_dirty_bitmap_merge(const char *node, const char *target,
     BlockDirtyBitmapMergeSourceList *lst;
     Error *local_err = NULL;
 
+    g_assert(qemu_in_main_thread());
+
     dst = block_dirty_bitmap_lookup(node, target, &bs, errp);
     if (!dst) {
         return NULL;
block/stream.c +2 -0
index 97bee482dc..a079c3c10d 100644
@@ -216,6 +216,8 @@ void stream_start(const char *job_id, BlockDriverState *bs,
     QDict *opts;
     int ret;
 
+    g_assert(qemu_in_main_thread());
+
     assert(!(base && bottom));
     assert(!(backing_file_str && bottom));
 
blockdev.c +7 -0
index 75407cbf67..5608b78f8f 100644
@@ -70,6 +70,7 @@ QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
 
 void bdrv_set_monitor_owned(BlockDriverState *bs)
 {
+    g_assert(qemu_in_main_thread());
     QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
 }
 
@@ -662,6 +663,7 @@ BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
 {
     int bdrv_flags = 0;
 
+    g_assert(qemu_in_main_thread());
     /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
      * with other callers) rather than what we want as the real defaults.
      * Apply the defaults here instead. */
@@ -680,6 +682,7 @@ void blockdev_close_all_bdrv_states(void)
 {
     BlockDriverState *bs, *next_bs;
 
+    g_assert(qemu_in_main_thread());
     QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
         AioContext *ctx = bdrv_get_aio_context(bs);
 
@@ -2333,6 +2336,8 @@ void qmp_transaction(TransactionActionList *dev_list,
     BlkActionState *state, *next;
     Error *local_err = NULL;
 
+    g_assert(qemu_in_main_thread());
+
     QTAILQ_HEAD(, BlkActionState) snap_bdrv_states;
     QTAILQ_INIT(&snap_bdrv_states);
 
@@ -3626,6 +3631,8 @@ void qmp_blockdev_del(const char *node_name, Error **errp)
     AioContext *aio_context;
     BlockDriverState *bs;
 
+    g_assert(qemu_in_main_thread());
+
     bs = bdrv_find_node(node_name);
     if (!bs) {
         error_setg(errp, "Failed to find node with node-name='%s'", node_name);
Signature · 1 line
2.27.0
#32 lore raw

RFC PATCH v2 10/25 assertions for blockjob_int.h

In reply to Emanuele Giuseppe Esposito
---
 blockjob.c | 4 ++++
 1 file changed, 4 insertions(+)
blockjob.c +4 -0
index 4bad1408cb..9878e255c6 100644
@@ -83,6 +83,7 @@ BlockJob *block_job_get(const char *id)
 
 void block_job_free(Job *job)
 {
+    g_assert(qemu_in_main_thread());
     BlockJob *bjob = container_of(job, BlockJob, job);
 
     block_job_remove_all_bdrv(bjob);
@@ -436,6 +437,8 @@ void *block_job_create(const char *job_id, const BlockJobDriver *driver,
     BlockBackend *blk;
     BlockJob *job;
 
+    g_assert(qemu_in_main_thread());
+
     if (job_id == NULL && !(flags & JOB_INTERNAL)) {
         job_id = bdrv_get_device_name(bs);
     }
@@ -504,6 +507,7 @@ void block_job_iostatus_reset(BlockJob *job)
 
 void block_job_user_resume(Job *job)
 {
+    g_assert(qemu_in_main_thread());
     BlockJob *bjob = container_of(job, BlockJob, job);
     block_job_iostatus_reset(bjob);
 }
Signature · 1 line
2.27.0
#58 lore raw

RFC PATCH v2 19/25 block_int-common.h: split function pointers in BlockDriver

In reply to Emanuele Giuseppe Esposito

Similar to the header split, also the function pointers in BlockDriver can be split in I/O and global state.

---
 include/block/block_int-common.h | 472 ++++++++++++++++---------------
 1 file changed, 251 insertions(+), 221 deletions(-)
include/block/block_int-common.h +251 -221
index 23f0d9c090..184cfab2d6 100644
@@ -95,6 +95,7 @@ typedef struct BdrvTrackedRequest {
 
 
 struct BlockDriver {
+    /* Fields initialized in struct definition and never changed. */
     const char *format_name;
     int instance_size;
 
@@ -120,23 +121,7 @@ struct BlockDriver {
      * on those children.
      */
     bool is_format;
-    /*
-     * Return true if @to_replace can be replaced by a BDS with the
-     * same data as @bs without it affecting @bs's behavior (that is,
-     * without it being visible to @bs's parents).
-     */
-    bool (*bdrv_recurse_can_replace)(BlockDriverState *bs,
-                                     BlockDriverState *to_replace);
 
-    int (*bdrv_probe)(const uint8_t *buf, int buf_size, const char *filename);
-    int (*bdrv_probe_device)(const char *filename);
-
-    /*
-     * Any driver implementing this callback is expected to be able to handle
-     * NULL file names in its .bdrv_open() implementation.
-     */
-    void (*bdrv_parse_filename)(const char *filename, QDict *options,
-                                Error **errp);
     /*
      * Drivers not implementing bdrv_parse_filename nor bdrv_open should have
      * this field set to true, except ones that are defined only by their
@@ -158,7 +143,81 @@ struct BlockDriver {
      */
     bool supports_backing;
 
-    /* For handling image reopen for split or non-split files */
+    /*
+     * Drivers setting this field must be able to work with just a plain
+     * filename with '<protocol_name>:' as a prefix, and no other options.
+     * Options may be extracted from the filename by implementing
+     * bdrv_parse_filename.
+     */
+    const char *protocol_name;
+
+    /* List of options for creating images, terminated by name == NULL */
+    QemuOptsList *create_opts;
+
+    /* List of options for image amend */
+    QemuOptsList *amend_opts;
+
+    /*
+     * If this driver supports reopening images this contains a
+     * NULL-terminated list of the runtime options that can be
+     * modified. If an option in this list is unspecified during
+     * reopen then it _must_ be reset to its default value or return
+     * an error.
+     */
+    const char *const *mutable_opts;
+
+    /*
+     * Pointer to a NULL-terminated array of names of strong options
+     * that can be specified for bdrv_open(). A strong option is one
+     * that changes the data of a BDS.
+     * If this pointer is NULL, the array is considered empty.
+     * "filename" and "driver" are always considered strong.
+     */
+    const char *const *strong_runtime_opts;
+
+    /*
+     * Global state (GS) API. These functions run under the BQL lock.
+     *
+     * If a function modifies the graph, it also uses drain and/or
+     * aio_context_acquire/release to be sure it has unique access.
+     * aio_context locking is needed together with BQL because of
+     * the thread-safe I/O API that concurrently runs and accesses
+     * the graph without the BQL.
+     *
+     * It is important to note that not all of these functions are
+     * necessarily limited to running under the BQL, but they would
+     * require additional auditing and may small thread-safety changes
+     * to move them into the I/O API. Often it's not worth doing that
+     * work since the APIs are only used with the BQL held at the
+     * moment, so they have been placed in the GS API (for now).
+     *
+     * All bdrv_* callers that use these function pointers must
+     * use this assertion:
+     * g_assert(qemu_in_main_thread());
+     * to catch when they are accidentally called without the BQL.
+     */
+
+    /*
+     * Return true if @to_replace can be replaced by a BDS with the
+     * same data as @bs without it affecting @bs's behavior (that is,
+     * without it being visible to @bs's parents).
+     */
+    bool (*bdrv_recurse_can_replace)(BlockDriverState *bs,
+                                     BlockDriverState *to_replace);
+
+    int (*bdrv_probe)(const uint8_t *buf, int buf_size, const char *filename);
+    int (*bdrv_probe_device)(const char *filename);
+
+    /*
+     * Any driver implementing this callback is expected to be able to handle
+     * NULL file names in its .bdrv_open() implementation.
+     */
+    void (*bdrv_parse_filename)(const char *filename, QDict *options,
+                                Error **errp);
+
+    /*
+     * For handling image reopen for split or non-split files.
+     */
     int (*bdrv_reopen_prepare)(BDRVReopenState *reopen_state,
                                BlockReopenQueue *queue, Error **errp);
     void (*bdrv_reopen_commit)(BDRVReopenState *reopen_state);
@@ -174,19 +233,6 @@ struct BlockDriver {
                           Error **errp);
     void (*bdrv_close)(BlockDriverState *bs);
 
-
-    int coroutine_fn (*bdrv_co_create)(BlockdevCreateOptions *opts,
-                                       Error **errp);
-    int coroutine_fn (*bdrv_co_create_opts)(BlockDriver *drv,
-                                            const char *filename,
-                                            QemuOpts *opts,
-                                            Error **errp);
-
-    int coroutine_fn (*bdrv_co_amend)(BlockDriverState *bs,
-                                      BlockdevAmendOptions *opts,
-                                      bool force,
-                                      Error **errp);
-
     int (*bdrv_amend_options)(BlockDriverState *bs,
                               QemuOpts *opts,
                               BlockDriverAmendStatusCB *status_cb,
@@ -233,6 +279,181 @@ struct BlockDriver {
      */
     char *(*bdrv_dirname)(BlockDriverState *bs, Error **errp);
 
+    /*
+     * This informs the driver that we are no longer interested in the result
+     * of in-flight requests, so don't waste the time if possible.
+     *
+     * One example usage is to avoid waiting for an nbd target node reconnect
+     * timeout during job-cancel with force=true.
+     */
+    void (*bdrv_cancel_in_flight)(BlockDriverState *bs);
+
+    int (*bdrv_inactivate)(BlockDriverState *bs);
+
+    int (*bdrv_snapshot_create)(BlockDriverState *bs,
+                                QEMUSnapshotInfo *sn_info);
+    int (*bdrv_snapshot_goto)(BlockDriverState *bs,
+                              const char *snapshot_id);
+    int (*bdrv_snapshot_delete)(BlockDriverState *bs,
+                                const char *snapshot_id,
+                                const char *name,
+                                Error **errp);
+    int (*bdrv_snapshot_list)(BlockDriverState *bs,
+                              QEMUSnapshotInfo **psn_info);
+    int (*bdrv_snapshot_load_tmp)(BlockDriverState *bs,
+                                  const char *snapshot_id,
+                                  const char *name,
+                                  Error **errp);
+
+    int coroutine_fn (*bdrv_save_vmstate)(BlockDriverState *bs,
+                                          QEMUIOVector *qiov,
+                                          int64_t pos);
+    int coroutine_fn (*bdrv_load_vmstate)(BlockDriverState *bs,
+                                          QEMUIOVector *qiov,
+                                          int64_t pos);
+
+    int (*bdrv_change_backing_file)(BlockDriverState *bs,
+        const char *backing_file, const char *backing_fmt);
+
+    void (*bdrv_eject)(BlockDriverState *bs, bool eject_flag);
+    void (*bdrv_lock_medium)(BlockDriverState *bs, bool locked);
+
+    /* TODO Better pass a option string/QDict/QemuOpts to add any rule? */
+    int (*bdrv_debug_breakpoint)(BlockDriverState *bs, const char *event,
+        const char *tag);
+    int (*bdrv_debug_remove_breakpoint)(BlockDriverState *bs,
+        const char *tag);
+    int (*bdrv_debug_resume)(BlockDriverState *bs, const char *tag);
+    bool (*bdrv_debug_is_suspended)(BlockDriverState *bs, const char *tag);
+    void (*bdrv_refresh_limits)(BlockDriverState *bs, Error **errp);
+
+    /*
+     * Returns 1 if newly created images are guaranteed to contain only
+     * zeros, 0 otherwise.
+     */
+    int (*bdrv_has_zero_init)(BlockDriverState *bs);
+
+    /*
+     * Remove fd handlers, timers, and other event loop callbacks so the event
+     * loop is no longer in use.  Called with no in-flight requests and in
+     * depth-first traversal order with parents before child nodes.
+     */
+    void (*bdrv_detach_aio_context)(BlockDriverState *bs);
+
+    /*
+     * Add fd handlers, timers, and other event loop callbacks so I/O requests
+     * can be processed again.  Called with no in-flight requests and in
+     * depth-first traversal order with child nodes before parent nodes.
+     */
+    void (*bdrv_attach_aio_context)(BlockDriverState *bs,
+                                    AioContext *new_context);
+
+    /**
+     * Try to get @bs's logical and physical block size.
+     * On success, store them in @bsz and return zero.
+     * On failure, return negative errno.
+     */
+    int (*bdrv_probe_blocksizes)(BlockDriverState *bs, BlockSizes *bsz);
+    /**
+     * Try to get @bs's geometry (cyls, heads, sectors)
+     * On success, store them in @geo and return 0.
+     * On failure return -errno.
+     * Only drivers that want to override guest geometry implement this
+     * callback; see hd_geometry_guess().
+     */
+    int (*bdrv_probe_geometry)(BlockDriverState *bs, HDGeometry *geo);
+
+    void (*bdrv_add_child)(BlockDriverState *parent, BlockDriverState *child,
+                           Error **errp);
+    void (*bdrv_del_child)(BlockDriverState *parent, BdrvChild *child,
+                           Error **errp);
+
+    /**
+     * Informs the block driver that a permission change is intended. The
+     * driver checks whether the change is permissible and may take other
+     * preparations for the change (e.g. get file system locks). This operation
+     * is always followed either by a call to either .bdrv_set_perm or
+     * .bdrv_abort_perm_update.
+     *
+     * Checks whether the requested set of cumulative permissions in @perm
+     * can be granted for accessing @bs and whether no other users are using
+     * permissions other than those given in @shared (both arguments take
+     * BLK_PERM_* bitmasks).
+     *
+     * If both conditions are met, 0 is returned. Otherwise, -errno is returned
+     * and errp is set to an error describing the conflict.
+     */
+    int (*bdrv_check_perm)(BlockDriverState *bs, uint64_t perm,
+                           uint64_t shared, Error **errp);
+
+    /**
+     * Called to inform the driver that the set of cumulative set of used
+     * permissions for @bs has changed to @perm, and the set of sharable
+     * permission to @shared. The driver can use this to propagate changes to
+     * its children (i.e. request permissions only if a parent actually needs
+     * them).
+     *
+     * This function is only invoked after bdrv_check_perm(), so block drivers
+     * may rely on preparations made in their .bdrv_check_perm implementation.
+     */
+    void (*bdrv_set_perm)(BlockDriverState *bs, uint64_t perm, uint64_t shared);
+
+    /*
+     * Called to inform the driver that after a previous bdrv_check_perm()
+     * call, the permission update is not performed and any preparations made
+     * for it (e.g. taken file locks) need to be undone.
+     *
+     * This function can be called even for nodes that never saw a
+     * bdrv_check_perm() call. It is a no-op then.
+     */
+    void (*bdrv_abort_perm_update)(BlockDriverState *bs);
+
+    /**
+     * Returns in @nperm and @nshared the permissions that the driver for @bs
+     * needs on its child @c, based on the cumulative permissions requested by
+     * the parents in @parent_perm and @parent_shared.
+     *
+     * If @c is NULL, return the permissions for attaching a new child for the
+     * given @child_class and @role.
+     *
+     * If @reopen_queue is non-NULL, don't return the currently needed
+     * permissions, but those that will be needed after applying the
+     * @reopen_queue.
+     */
+     void (*bdrv_child_perm)(BlockDriverState *bs, BdrvChild *c,
+                             BdrvChildRole role,
+                             BlockReopenQueue *reopen_queue,
+                             uint64_t parent_perm, uint64_t parent_shared,
+                             uint64_t *nperm, uint64_t *nshared);
+
+    /**
+     * Register/unregister a buffer for I/O. For example, when the driver is
+     * interested to know the memory areas that will later be used in iovs, so
+     * that it can do IOMMU mapping with VFIO etc., in order to get better
+     * performance. In the case of VFIO drivers, this callback is used to do
+     * DMA mapping for hot buffers.
+     */
+    void (*bdrv_register_buf)(BlockDriverState *bs, void *host, size_t size);
+    void (*bdrv_unregister_buf)(BlockDriverState *bs, void *host);
+    QLIST_ENTRY(BlockDriver) list;
+
+    /*
+     * I/O API functions. These functions are thread-safe, and therefore
+     * can run in any thread as long as they have called
+     * aio_context_acquire/release().
+     */
+
+    int coroutine_fn (*bdrv_co_create)(BlockdevCreateOptions *opts,
+                                       Error **errp);
+    int coroutine_fn (*bdrv_co_create_opts)(BlockDriver *drv,
+                                            const char *filename,
+                                            QemuOpts *opts,
+                                            Error **errp);
+    int coroutine_fn (*bdrv_co_amend)(BlockDriverState *bs,
+                                      BlockdevAmendOptions *opts,
+                                      bool force,
+                                      Error **errp);
+
     /* aio */
     BlockAIOCB *(*bdrv_aio_preadv)(BlockDriverState *bs,
         uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags,
@@ -360,21 +581,11 @@ struct BlockDriver {
         bool want_zero, int64_t offset, int64_t bytes, int64_t *pnum,
         int64_t *map, BlockDriverState **file);
 
-    /*
-     * This informs the driver that we are no longer interested in the result
-     * of in-flight requests, so don't waste the time if possible.
-     *
-     * One example usage is to avoid waiting for an nbd target node reconnect
-     * timeout during job-cancel with force=true.
-     */
-    void (*bdrv_cancel_in_flight)(BlockDriverState *bs);
-
     /*
      * Invalidate any cached meta-data.
      */
     void coroutine_fn (*bdrv_co_invalidate_cache)(BlockDriverState *bs,
                                                   Error **errp);
-    int (*bdrv_inactivate)(BlockDriverState *bs);
 
     /*
      * Flushes all data for all layers by calling bdrv_co_flush for underlying
@@ -400,14 +611,6 @@ struct BlockDriver {
      */
     int coroutine_fn (*bdrv_co_flush_to_os)(BlockDriverState *bs);
 
-    /*
-     * Drivers setting this field must be able to work with just a plain
-     * filename with '<protocol_name>:' as a prefix, and no other options.
-     * Options may be extracted from the filename by implementing
-     * bdrv_parse_filename.
-     */
-    const char *protocol_name;
-
     /*
      * Truncate @bs to @offset bytes using the given @prealloc mode
      * when growing.  Modes other than PREALLOC_MODE_OFF should be
@@ -429,47 +632,20 @@ struct BlockDriver {
     int64_t (*bdrv_get_allocated_file_size)(BlockDriverState *bs);
     BlockMeasureInfo *(*bdrv_measure)(QemuOpts *opts, BlockDriverState *in_bs,
                                       Error **errp);
-
     int coroutine_fn (*bdrv_co_pwritev_compressed)(BlockDriverState *bs,
         uint64_t offset, uint64_t bytes, QEMUIOVector *qiov);
     int coroutine_fn (*bdrv_co_pwritev_compressed_part)(BlockDriverState *bs,
         uint64_t offset, uint64_t bytes, QEMUIOVector *qiov,
         size_t qiov_offset);
 
-    int (*bdrv_snapshot_create)(BlockDriverState *bs,
-                                QEMUSnapshotInfo *sn_info);
-    int (*bdrv_snapshot_goto)(BlockDriverState *bs,
-                              const char *snapshot_id);
-    int (*bdrv_snapshot_delete)(BlockDriverState *bs,
-                                const char *snapshot_id,
-                                const char *name,
-                                Error **errp);
-    int (*bdrv_snapshot_list)(BlockDriverState *bs,
-                              QEMUSnapshotInfo **psn_info);
-    int (*bdrv_snapshot_load_tmp)(BlockDriverState *bs,
-                                  const char *snapshot_id,
-                                  const char *name,
-                                  Error **errp);
     int (*bdrv_get_info)(BlockDriverState *bs, BlockDriverInfo *bdi);
 
     ImageInfoSpecific *(*bdrv_get_specific_info)(BlockDriverState *bs,
                                                  Error **errp);
     BlockStatsSpecific *(*bdrv_get_specific_stats)(BlockDriverState *bs);
 
-    int coroutine_fn (*bdrv_save_vmstate)(BlockDriverState *bs,
-                                          QEMUIOVector *qiov,
-                                          int64_t pos);
-    int coroutine_fn (*bdrv_load_vmstate)(BlockDriverState *bs,
-                                          QEMUIOVector *qiov,
-                                          int64_t pos);
-
-    int (*bdrv_change_backing_file)(BlockDriverState *bs,
-        const char *backing_file, const char *backing_fmt);
-
     /* removable device specific */
     bool (*bdrv_is_inserted)(BlockDriverState *bs);
-    void (*bdrv_eject)(BlockDriverState *bs, bool eject_flag);
-    void (*bdrv_lock_medium)(BlockDriverState *bs, bool locked);
 
     /* to control generic scsi devices */
     BlockAIOCB *(*bdrv_aio_ioctl)(BlockDriverState *bs,
@@ -478,21 +654,6 @@ struct BlockDriver {
     int coroutine_fn (*bdrv_co_ioctl)(BlockDriverState *bs,
                                       unsigned long int req, void *buf);
 
-    /* List of options for creating images, terminated by name == NULL */
-    QemuOptsList *create_opts;
-
-    /* List of options for image amend */
-    QemuOptsList *amend_opts;
-
-    /*
-     * If this driver supports reopening images this contains a
-     * NULL-terminated list of the runtime options that can be
-     * modified. If an option in this list is unspecified during
-     * reopen then it _must_ be reset to its default value or return
-     * an error.
-     */
-    const char *const *mutable_opts;
-
     /*
      * Returns 0 for completed check, -errno for internal errors.
      * The check results are stored in result.
@@ -503,58 +664,10 @@ struct BlockDriver {
 
     void (*bdrv_debug_event)(BlockDriverState *bs, BlkdebugEvent event);
 
-    /* TODO Better pass a option string/QDict/QemuOpts to add any rule? */
-    int (*bdrv_debug_breakpoint)(BlockDriverState *bs, const char *event,
-        const char *tag);
-    int (*bdrv_debug_remove_breakpoint)(BlockDriverState *bs,
-        const char *tag);
-    int (*bdrv_debug_resume)(BlockDriverState *bs, const char *tag);
-    bool (*bdrv_debug_is_suspended)(BlockDriverState *bs, const char *tag);
-
-    void (*bdrv_refresh_limits)(BlockDriverState *bs, Error **errp);
-
-    /*
-     * Returns 1 if newly created images are guaranteed to contain only
-     * zeros, 0 otherwise.
-     */
-    int (*bdrv_has_zero_init)(BlockDriverState *bs);
-
-    /*
-     * Remove fd handlers, timers, and other event loop callbacks so the event
-     * loop is no longer in use.  Called with no in-flight requests and in
-     * depth-first traversal order with parents before child nodes.
-     */
-    void (*bdrv_detach_aio_context)(BlockDriverState *bs);
-
-    /*
-     * Add fd handlers, timers, and other event loop callbacks so I/O requests
-     * can be processed again.  Called with no in-flight requests and in
-     * depth-first traversal order with child nodes before parent nodes.
-     */
-    void (*bdrv_attach_aio_context)(BlockDriverState *bs,
-                                    AioContext *new_context);
-
     /* io queue for linux-aio */
     void (*bdrv_io_plug)(BlockDriverState *bs);
     void (*bdrv_io_unplug)(BlockDriverState *bs);
 
-    /**
-     * Try to get @bs's logical and physical block size.
-     * On success, store them in @bsz and return zero.
-     * On failure, return negative errno.
-     */
-    /* I/O API, even though if it's a filter jumps on parent */
-    int (*bdrv_probe_blocksizes)(BlockDriverState *bs, BlockSizes *bsz);
-    /**
-     * Try to get @bs's geometry (cyls, heads, sectors)
-     * On success, store them in @geo and return 0.
-     * On failure return -errno.
-     * Only drivers that want to override guest geometry implement this
-     * callback; see hd_geometry_guess().
-     */
-    /* I/O API, even though if it's a filter jumps on parent */
-    int (*bdrv_probe_geometry)(BlockDriverState *bs, HDGeometry *geo);
-
     /**
      * bdrv_co_drain_begin is called if implemented in the beginning of a
      * drain operation to drain and stop any internal sources of requests in
@@ -568,69 +681,6 @@ struct BlockDriver {
     void coroutine_fn (*bdrv_co_drain_begin)(BlockDriverState *bs);
     void coroutine_fn (*bdrv_co_drain_end)(BlockDriverState *bs);
 
-    void (*bdrv_add_child)(BlockDriverState *parent, BlockDriverState *child,
-                           Error **errp);
-    void (*bdrv_del_child)(BlockDriverState *parent, BdrvChild *child,
-                           Error **errp);
-
-    /**
-     * Informs the block driver that a permission change is intended. The
-     * driver checks whether the change is permissible and may take other
-     * preparations for the change (e.g. get file system locks). This operation
-     * is always followed either by a call to either .bdrv_set_perm or
-     * .bdrv_abort_perm_update.
-     *
-     * Checks whether the requested set of cumulative permissions in @perm
-     * can be granted for accessing @bs and whether no other users are using
-     * permissions other than those given in @shared (both arguments take
-     * BLK_PERM_* bitmasks).
-     *
-     * If both conditions are met, 0 is returned. Otherwise, -errno is returned
-     * and errp is set to an error describing the conflict.
-     */
-    int (*bdrv_check_perm)(BlockDriverState *bs, uint64_t perm,
-                           uint64_t shared, Error **errp);
-
-    /**
-     * Called to inform the driver that the set of cumulative set of used
-     * permissions for @bs has changed to @perm, and the set of sharable
-     * permission to @shared. The driver can use this to propagate changes to
-     * its children (i.e. request permissions only if a parent actually needs
-     * them).
-     *
-     * This function is only invoked after bdrv_check_perm(), so block drivers
-     * may rely on preparations made in their .bdrv_check_perm implementation.
-     */
-    void (*bdrv_set_perm)(BlockDriverState *bs, uint64_t perm, uint64_t shared);
-
-    /*
-     * Called to inform the driver that after a previous bdrv_check_perm()
-     * call, the permission update is not performed and any preparations made
-     * for it (e.g. taken file locks) need to be undone.
-     *
-     * This function can be called even for nodes that never saw a
-     * bdrv_check_perm() call. It is a no-op then.
-     */
-    void (*bdrv_abort_perm_update)(BlockDriverState *bs);
-
-    /**
-     * Returns in @nperm and @nshared the permissions that the driver for @bs
-     * needs on its child @c, based on the cumulative permissions requested by
-     * the parents in @parent_perm and @parent_shared.
-     *
-     * If @c is NULL, return the permissions for attaching a new child for the
-     * given @child_class and @role.
-     *
-     * If @reopen_queue is non-NULL, don't return the currently needed
-     * permissions, but those that will be needed after applying the
-     * @reopen_queue.
-     */
-     void (*bdrv_child_perm)(BlockDriverState *bs, BdrvChild *c,
-                             BdrvChildRole role,
-                             BlockReopenQueue *reopen_queue,
-                             uint64_t parent_perm, uint64_t parent_shared,
-                             uint64_t *nperm, uint64_t *nshared);
-
     bool (*bdrv_supports_persistent_dirty_bitmap)(BlockDriverState *bs);
     bool (*bdrv_co_can_store_new_dirty_bitmap)(BlockDriverState *bs,
                                                const char *name,
@@ -639,26 +689,6 @@ struct BlockDriver {
     int (*bdrv_co_remove_persistent_dirty_bitmap)(BlockDriverState *bs,
                                                   const char *name,
                                                   Error **errp);
-
-    /**
-     * Register/unregister a buffer for I/O. For example, when the driver is
-     * interested to know the memory areas that will later be used in iovs, so
-     * that it can do IOMMU mapping with VFIO etc., in order to get better
-     * performance. In the case of VFIO drivers, this callback is used to do
-     * DMA mapping for hot buffers.
-     */
-    void (*bdrv_register_buf)(BlockDriverState *bs, void *host, size_t size);
-    void (*bdrv_unregister_buf)(BlockDriverState *bs, void *host);
-    QLIST_ENTRY(BlockDriver) list;
-
-    /*
-     * Pointer to a NULL-terminated array of names of strong options
-     * that can be specified for bdrv_open(). A strong option is one
-     * that changes the data of a BDS.
-     * If this pointer is NULL, the array is considered empty.
-     * "filename" and "driver" are always considered strong.
-     */
-    const char *const *strong_runtime_opts;
 };
 
 static inline bool block_driver_can_compress(BlockDriver *drv)
Signature · 1 line
2.27.0
#40 lore raw

RFC PATCH v2 13/25 include/systemu/blockdev.h: global state API

In reply to Emanuele Giuseppe Esposito

blockdev functions run always under the BQL lock.

---
 include/sysemu/blockdev.h | 35 ++++++++++++++++++++++++++++++-----
 1 file changed, 30 insertions(+), 5 deletions(-)
include/sysemu/blockdev.h +30 -5
index 32c2d6023c..28233f6b63 100644
@@ -38,24 +38,49 @@ struct DriveInfo {
     QTAILQ_ENTRY(DriveInfo) next;
 };
 
-DriveInfo *blk_legacy_dinfo(BlockBackend *blk);
+/*
+ * Global state (GS) API. These functions run under the BQL lock.
+ *
+ * If a function modifies the graph, it also uses drain and/or
+ * aio_context_acquire/release to be sure it has unique access.
+ * aio_context locking is needed together with BQL because of
+ * the thread-safe I/O API that concurrently runs and accesses
+ * the graph without the BQL.
+ *
+ * It is important to note that not all of these functions are
+ * necessarily limited to running under the BQL, but they would
+ * require additional auditing and may small thread-safety changes
+ * to move them into the I/O API. Often it's not worth doing that
+ * work since the APIs are only used with the BQL held at the
+ * moment, so they have been placed in the GS API (for now).
+ *
+ * All functions in this header must use this assertion:
+ * g_assert(qemu_in_main_thread());
+ * to catch when they are accidentally called without the BQL.
+ */
+
 DriveInfo *blk_set_legacy_dinfo(BlockBackend *blk, DriveInfo *dinfo);
 BlockBackend *blk_by_legacy_dinfo(DriveInfo *dinfo);
 
 void override_max_devs(BlockInterfaceType type, int max_devs);
 
 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit);
-void drive_mark_claimed_by_board(void);
 void drive_check_orphaned(void);
 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index);
 int drive_get_max_bus(BlockInterfaceType type);
-int drive_get_max_devs(BlockInterfaceType type);
 DriveInfo *drive_get_next(BlockInterfaceType type);
 
+DriveInfo *drive_new(QemuOpts *arg, BlockInterfaceType block_default_type,
+                     Error **errp);
+
+/* Common functions that are neither I/O nor Global State */
+
+DriveInfo *blk_legacy_dinfo(BlockBackend *blk);
+int drive_get_max_devs(BlockInterfaceType type);
+
 QemuOpts *drive_def(const char *optstr);
+
 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
                     const char *optstr);
-DriveInfo *drive_new(QemuOpts *arg, BlockInterfaceType block_default_type,
-                     Error **errp);
 
 #endif
Signature · 1 line
2.27.0
#43 lore raw

RFC PATCH v2 14/25 assertions for blockdev.h global state API

In reply to Emanuele Giuseppe Esposito
---
 block/block-backend.c |  2 ++
 blockdev.c            | 12 ++++++++++++
 2 files changed, 14 insertions(+)
block/block-backend.c +2 -0
index 9f09245069..18791c4fdc 100644
@@ -805,6 +805,7 @@ DriveInfo *blk_legacy_dinfo(BlockBackend *blk)
 DriveInfo *blk_set_legacy_dinfo(BlockBackend *blk, DriveInfo *dinfo)
 {
     assert(!blk->legacy_dinfo);
+    g_assert(qemu_in_main_thread());
     return blk->legacy_dinfo = dinfo;
 }
 
@@ -815,6 +816,7 @@ DriveInfo *blk_set_legacy_dinfo(BlockBackend *blk, DriveInfo *dinfo)
 BlockBackend *blk_by_legacy_dinfo(DriveInfo *dinfo)
 {
     BlockBackend *blk = NULL;
+    g_assert(qemu_in_main_thread());
 
     while ((blk = blk_next(blk)) != NULL) {
         if (blk->legacy_dinfo == dinfo) {
blockdev.c +12 -0
index 5608b78f8f..917bcf8cbc 100644
@@ -114,6 +114,8 @@ void override_max_devs(BlockInterfaceType type, int max_devs)
     BlockBackend *blk;
     DriveInfo *dinfo;
 
+    g_assert(qemu_in_main_thread());
+
     if (max_devs <= 0) {
         return;
     }
@@ -230,6 +232,8 @@ DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
     BlockBackend *blk;
     DriveInfo *dinfo;
 
+    g_assert(qemu_in_main_thread());
+
     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
         dinfo = blk_legacy_dinfo(blk);
         if (dinfo && dinfo->type == type
@@ -252,6 +256,8 @@ void drive_check_orphaned(void)
     Location loc;
     bool orphans = false;
 
+    g_assert(qemu_in_main_thread());
+
     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
         dinfo = blk_legacy_dinfo(blk);
         /*
@@ -285,6 +291,7 @@ void drive_check_orphaned(void)
 
 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
 {
+    g_assert(qemu_in_main_thread());
     return drive_get(type,
                      drive_index_to_bus_id(type, index),
                      drive_index_to_unit_id(type, index));
@@ -296,6 +303,8 @@ int drive_get_max_bus(BlockInterfaceType type)
     BlockBackend *blk;
     DriveInfo *dinfo;
 
+    g_assert(qemu_in_main_thread());
+
     max_bus = -1;
     for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
         dinfo = blk_legacy_dinfo(blk);
@@ -312,6 +321,7 @@ int drive_get_max_bus(BlockInterfaceType type)
 DriveInfo *drive_get_next(BlockInterfaceType type)
 {
     static int next_block_unit[IF_COUNT];
+    g_assert(qemu_in_main_thread());
 
     return drive_get(type, 0, next_block_unit[type]++);
 }
@@ -792,6 +802,8 @@ DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type,
     const char *filename;
     int i;
 
+    g_assert(qemu_in_main_thread());
+
     /* Change legacy command line options into QMP ones */
     static const struct {
         const char *from;
Signature · 1 line
2.27.0
#30 lore raw

RFC PATCH v2 9/25 include/block/blockjob_int.h: split header into I/O and GS API

In reply to Emanuele Giuseppe Esposito

Since the I/O functions are not many, keep a single file. Also split the function pointers in BlockJobDriver.

---
 include/block/blockjob_int.h | 55 ++++++++++++++++++++++++++++++++++++
 1 file changed, 55 insertions(+)
include/block/blockjob_int.h +55 -0
index 6633d83da2..bac4e8f46d 100644
@@ -38,6 +38,12 @@ struct BlockJobDriver {
     /** Generic JobDriver callbacks and settings */
     JobDriver job_driver;
 
+    /*
+     * I/O API functions. These functions are thread-safe, and therefore
+     * can run in any thread as long as they have called
+     * aio_context_acquire/release().
+     */
+
     /*
      * Returns whether the job has pending requests for the child or will
      * submit new requests before the next pause point. This callback is polled
@@ -46,6 +52,28 @@ struct BlockJobDriver {
      */
     bool (*drained_poll)(BlockJob *job);
 
+    /*
+     * Global state (GS) API. These functions run under the BQL lock.
+     *
+     * If a function modifies the graph, it also uses drain and/or
+     * aio_context_acquire/release to be sure it has unique access.
+     * aio_context locking is needed together with BQL because of
+     * the thread-safe I/O API that concurrently runs and accesses
+     * the graph without the BQL.
+     *
+     * It is important to note that not all of these functions are
+     * necessarily limited to running under the BQL, but they would
+     * require additional auditing and may small thread-safety changes
+     * to move them into the I/O API. Often it's not worth doing that
+     * work since the APIs are only used with the BQL held at the
+     * moment, so they have been placed in the GS API (for now).
+     *
+     * All callers that use these function pointers must
+     * use this assertion:
+     * g_assert(qemu_in_main_thread());
+     * to catch when they are accidentally called without the BQL.
+     */
+
     /*
      * If the callback is not NULL, it will be invoked before the job is
      * resumed in a new AioContext.  This is the place to move any resources
@@ -56,6 +84,27 @@ struct BlockJobDriver {
     void (*set_speed)(BlockJob *job, int64_t speed);
 };
 
+/*
+ * Global state (GS) API. These functions run under the BQL lock.
+ *
+ * If a function modifies the graph, it also uses drain and/or
+ * aio_context_acquire/release to be sure it has unique access.
+ * aio_context locking is needed together with BQL because of
+ * the thread-safe I/O API that concurrently runs and accesses
+ * the graph without the BQL.
+ *
+ * It is important to note that not all of these functions are
+ * necessarily limited to running under the BQL, but they would
+ * require additional auditing and may small thread-safety changes
+ * to move them into the I/O API. Often it's not worth doing that
+ * work since the APIs are only used with the BQL held at the
+ * moment, so they have been placed in the GS API (for now).
+ *
+ * All functions below must use this assertion:
+ * g_assert(qemu_in_main_thread());
+ * to catch when they are accidentally called without the BQL.
+ */
+
 /**
  * block_job_create:
  * @job_id: The id of the newly-created job, or %NULL to have one
@@ -98,6 +147,12 @@ void block_job_free(Job *job);
  */
 void block_job_user_resume(Job *job);
 
+/*
+ * I/O API functions. These functions are thread-safe, and therefore
+ * can run in any thread as long as they have called
+ * aio_context_acquire/release().
+ */
+
 /**
  * block_job_ratelimit_get_delay:
  *
Signature · 1 line
2.27.0
#60 lore raw

RFC PATCH v2 20/25 block_int-common.h: assertion in the callers of BlockDriver function pointers

In reply to Emanuele Giuseppe Esposito
---
 block.c | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
block.c +16 -0
index 7d1eb847a4..a921066d4d 100644
@@ -1069,6 +1069,7 @@ int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
 static void bdrv_join_options(BlockDriverState *bs, QDict *options,
                               QDict *old_options)
 {
+    g_assert(qemu_in_main_thread());
     if (bs->drv && bs->drv->bdrv_join_options) {
         bs->drv->bdrv_join_options(options, old_options);
     } else {
@@ -1561,6 +1562,7 @@ static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
 {
     Error *local_err = NULL;
     int i, ret;
+    g_assert(qemu_in_main_thread());
 
     bdrv_assign_node_name(bs, node_name, &local_err);
     if (local_err) {
@@ -1932,6 +1934,8 @@ static int bdrv_fill_options(QDict **options, const char *filename,
     BlockDriver *drv = NULL;
     Error *local_err = NULL;
 
+    g_assert(qemu_in_main_thread());
+
     /*
      * Caution: while qdict_get_try_str() is fine, getting non-string
      * types would require more care.  When @options come from
@@ -2125,6 +2129,7 @@ static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
                             uint64_t *nperm, uint64_t *nshared)
 {
     assert(bs->drv && bs->drv->bdrv_child_perm);
+    g_assert(qemu_in_main_thread());
     bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
                              parent_perm, parent_shared,
                              nperm, nshared);
@@ -2208,6 +2213,7 @@ static void bdrv_drv_set_perm_commit(void *opaque)
 {
     BlockDriverState *bs = opaque;
     uint64_t cumulative_perms, cumulative_shared_perms;
+    g_assert(qemu_in_main_thread());
 
     if (bs->drv->bdrv_set_perm) {
         bdrv_get_cumulative_perm(bs, &cumulative_perms,
@@ -2219,6 +2225,7 @@ static void bdrv_drv_set_perm_commit(void *opaque)
 static void bdrv_drv_set_perm_abort(void *opaque)
 {
     BlockDriverState *bs = opaque;
+    g_assert(qemu_in_main_thread());
 
     if (bs->drv->bdrv_abort_perm_update) {
         bs->drv->bdrv_abort_perm_update(bs);
@@ -2234,6 +2241,7 @@ static int bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm,
                              uint64_t shared_perm, Transaction *tran,
                              Error **errp)
 {
+    g_assert(qemu_in_main_thread());
     if (!bs->drv) {
         return 0;
     }
@@ -4198,6 +4206,7 @@ int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
 
     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
     assert(bs_queue != NULL);
+    g_assert(qemu_in_main_thread());
 
     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
         ctx = bdrv_get_aio_context(bs_entry->state.bs);
@@ -4461,6 +4470,7 @@ static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
 
     assert(reopen_state != NULL);
     assert(reopen_state->bs->drv != NULL);
+    g_assert(qemu_in_main_thread());
     drv = reopen_state->bs->drv;
 
     /* This function and each driver's bdrv_reopen_prepare() remove
@@ -4671,6 +4681,7 @@ static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
     bs = reopen_state->bs;
     drv = bs->drv;
     assert(drv != NULL);
+    g_assert(qemu_in_main_thread());
 
     /* If there are any driver level actions to take */
     if (drv->bdrv_reopen_commit) {
@@ -4712,6 +4723,7 @@ static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
     assert(reopen_state != NULL);
     drv = reopen_state->bs->drv;
     assert(drv != NULL);
+    g_assert(qemu_in_main_thread());
 
     if (drv->bdrv_reopen_abort) {
         drv->bdrv_reopen_abort(reopen_state);
@@ -4725,6 +4737,7 @@ static void bdrv_close(BlockDriverState *bs)
     BdrvChild *child, *next;
 
     assert(!bs->refcnt);
+    g_assert(qemu_in_main_thread());
 
     bdrv_drained_begin(bs); /* complete I/O */
     bdrv_flush(bs);
@@ -6409,6 +6422,7 @@ static int bdrv_inactivate_recurse(BlockDriverState *bs)
 {
     BdrvChild *child, *parent;
     int ret;
+    g_assert(qemu_in_main_thread());
 
     if (!bs->drv) {
         return -ENOMEDIUM;
@@ -6911,6 +6925,7 @@ static void bdrv_detach_aio_context(BlockDriverState *bs)
     BdrvAioNotifier *baf, *baf_tmp;
 
     assert(!bs->walking_aio_notifiers);
+    g_assert(qemu_in_main_thread());
     bs->walking_aio_notifiers = true;
     QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
         if (baf->deleted) {
@@ -6938,6 +6953,7 @@ static void bdrv_attach_aio_context(BlockDriverState *bs,
                                     AioContext *new_context)
 {
     BdrvAioNotifier *ban, *ban_tmp;
+    g_assert(qemu_in_main_thread());
 
     if (bs->quiesce_counter) {
         aio_disable_external(new_context);
Signature · 1 line
2.27.0
#72 lore raw

RFC PATCH v2 25/25 job.h: assertions in the callers of JobDriver funcion pointers

In reply to Emanuele Giuseppe Esposito
---
 job.c | 9 +++++++++
 1 file changed, 9 insertions(+)
job.c +9 -0
index e7a5d28854..62a13b6982 100644
@@ -373,6 +373,8 @@ void job_ref(Job *job)
 
 void job_unref(Job *job)
 {
+    g_assert(qemu_in_main_thread());
+
     if (--job->refcnt == 0) {
         assert(job->status == JOB_STATUS_NULL);
         assert(!timer_pending(&job->sleep_timer));
@@ -594,6 +596,7 @@ bool job_user_paused(Job *job)
 void job_user_resume(Job *job, Error **errp)
 {
     assert(job);
+    g_assert(qemu_in_main_thread());
     if (!job->user_paused || job->pause_count <= 0) {
         error_setg(errp, "Can't resume a job that was not paused");
         return;
@@ -664,6 +667,7 @@ static void job_update_rc(Job *job)
 static void job_commit(Job *job)
 {
     assert(!job->ret);
+    g_assert(qemu_in_main_thread());
     if (job->driver->commit) {
         job->driver->commit(job);
     }
@@ -672,6 +676,7 @@ static void job_commit(Job *job)
 static void job_abort(Job *job)
 {
     assert(job->ret);
+    g_assert(qemu_in_main_thread());
     if (job->driver->abort) {
         job->driver->abort(job);
     }
@@ -679,6 +684,7 @@ static void job_abort(Job *job)
 
 static void job_clean(Job *job)
 {
+    g_assert(qemu_in_main_thread());
     if (job->driver->clean) {
         job->driver->clean(job);
     }
@@ -718,6 +724,7 @@ static int job_finalize_single(Job *job)
 
 static void job_cancel_async(Job *job, bool force)
 {
+    g_assert(qemu_in_main_thread());
     if (job->driver->cancel) {
         job->driver->cancel(job, force);
     }
@@ -786,6 +793,7 @@ static void job_completed_txn_abort(Job *job)
 
 static int job_prepare(Job *job)
 {
+    g_assert(qemu_in_main_thread());
     if (job->ret == 0 && job->driver->prepare) {
         job->ret = job->driver->prepare(job);
         job_update_rc(job);
@@ -991,6 +999,7 @@ void job_complete(Job *job, Error **errp)
 {
     /* Should not be reachable via external interface for internal jobs */
     assert(job->id);
+    g_assert(qemu_in_main_thread());
     if (job_apply_verb(job, JOB_VERB_COMPLETE, errp)) {
         return;
     }
Signature · 1 line
2.27.0
#49 lore raw

RFC PATCH v2 16/25 block/backup-top.h: global state API + assertions

In reply to Emanuele Giuseppe Esposito

backup-top functions always run under BQL lock.

---
 block/backup-top.c |  2 ++
 block/backup-top.h | 11 +++++++++++
 2 files changed, 13 insertions(+)
block/backup-top.c +2 -0
index 425e3778be..8b58a909f7 100644
@@ -182,6 +182,7 @@ BlockDriverState *bdrv_backup_top_append(BlockDriverState *source,
     bool appended = false;
 
     assert(source->total_sectors == target->total_sectors);
+    g_assert(qemu_in_main_thread());
 
     top = bdrv_new_open_driver(&bdrv_backup_top_filter, filter_node_name,
                                BDRV_O_RDWR, errp);
@@ -244,6 +245,7 @@ fail:
 void bdrv_backup_top_drop(BlockDriverState *bs)
 {
     BDRVBackupTopState *s = bs->opaque;
+    g_assert(qemu_in_main_thread());
 
     bdrv_drop_filter(bs, &error_abort);
 
block/backup-top.h +11 -0
index b28b0031c4..8cb6f62869 100644
@@ -29,6 +29,17 @@
 #include "block/block_int.h"
 #include "block/block-copy.h"
 
+/*
+ * Graph API. These functions run under the BQL lock.
+ *
+ * If a function modifies the graph, it uses drain and/or
+ * aio_context_acquire/release to be sure it has unique access.
+ *
+ * All functions in this header must use this assertion:
+ * g_assert(qemu_in_main_thread());
+ * to be sure they belong here.
+ */
+
 BlockDriverState *bdrv_backup_top_append(BlockDriverState *source,
                                          BlockDriverState *target,
                                          const char *filter_node_name,
Signature · 1 line
2.27.0
#64 lore raw

RFC PATCH v2 22/25 block_int-common.h: assertions in the callers of BdrvChildClass function pointers

In reply to Emanuele Giuseppe Esposito
---
 block.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
block.c +10 -0
index a921066d4d..e4b3d40094 100644
@@ -1457,6 +1457,7 @@ const BdrvChildClass child_of_bds = {
 
 AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
 {
+    g_assert(qemu_in_main_thread());
     return c->klass->get_parent_aio_context(c);
 }
 
@@ -2062,6 +2063,7 @@ bool bdrv_is_writable(BlockDriverState *bs)
 
 static char *bdrv_child_user_desc(BdrvChild *c)
 {
+    g_assert(qemu_in_main_thread());
     return c->klass->get_parent_desc(c);
 }
 
@@ -2695,6 +2697,7 @@ static void bdrv_replace_child_noperm(BdrvChild *child,
     int drain_saldo;
 
     assert(!child->frozen);
+    g_assert(qemu_in_main_thread());
 
     if (old_bs && new_bs) {
         assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
@@ -2783,6 +2786,8 @@ static void bdrv_attach_child_common_abort(void *opaque)
     BdrvChild *child = *s->child;
     BlockDriverState *bs = child->bs;
 
+    g_assert(qemu_in_main_thread());
+
     bdrv_replace_child_noperm(child, NULL);
 
     if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
@@ -3141,6 +3146,7 @@ void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
 {
     BdrvChild *c;
+    g_assert(qemu_in_main_thread());
     QLIST_FOREACH(c, &bs->parents, next_parent) {
         if (c->klass->change_media) {
             c->klass->change_media(c, load);
@@ -3632,6 +3638,7 @@ static BlockDriverState *bdrv_open_inherit(const char *filename,
 
     assert(!child_class || !flags);
     assert(!child_class == !parent);
+    g_assert(qemu_in_main_thread());
 
     if (reference) {
         bool options_non_empty = options ? qdict_size(options) : false;
@@ -4018,6 +4025,7 @@ static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
      * important to avoid graph changes between the recursive queuing here and
      * bdrv_reopen_multiple(). */
     assert(bs->quiesce_counter > 0);
+    g_assert(qemu_in_main_thread());
 
     if (bs_queue == NULL) {
         bs_queue = g_new0(BlockReopenQueue, 1);
@@ -7000,6 +7008,7 @@ void bdrv_set_aio_context_ignore(BlockDriverState *bs,
     BdrvChild *child, *parent;
 
     g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
+    g_assert(qemu_in_main_thread());
 
     if (old_context == new_context) {
         return;
@@ -7076,6 +7085,7 @@ static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
         return true;
     }
     *ignore = g_slist_prepend(*ignore, c);
+    g_assert(qemu_in_main_thread());
 
     /*
      * A BdrvChildClass that doesn't handle AioContext changes cannot
Signature · 1 line
2.27.0
#68 lore raw

RFC PATCH v2 24/25 job.h: split function pointers in JobDriver

In reply to Emanuele Giuseppe Esposito

The job API will be handled separately in another serie.

---
 include/qemu/job.h | 31 +++++++++++++++++++++++++++++++
 1 file changed, 31 insertions(+)
include/qemu/job.h +31 -0
index 41162ed494..c236c43026 100644
@@ -169,12 +169,21 @@ typedef struct Job {
  * Callbacks and other information about a Job driver.
  */
 struct JobDriver {
+
+    /* Fields initialized in struct definition and never changed. */
+
     /** Derived Job struct size */
     size_t instance_size;
 
     /** Enum describing the operation */
     JobType job_type;
 
+    /*
+     * I/O API functions. These functions are thread-safe, and therefore
+     * can run in any thread as long as they have called
+     * aio_context_acquire/release().
+     */
+
     /**
      * Mandatory: Entrypoint for the Coroutine.
      *
@@ -201,6 +210,28 @@ struct JobDriver {
      */
     void coroutine_fn (*resume)(Job *job);
 
+    /*
+     * Global state (GS) API. These functions run under the BQL lock.
+     *
+     * If a function modifies the graph, it also uses drain and/or
+     * aio_context_acquire/release to be sure it has unique access.
+     * aio_context locking is needed together with BQL because of
+     * the thread-safe I/O API that concurrently runs and accesses
+     * the graph without the BQL.
+     *
+     * It is important to note that not all of these functions are
+     * necessarily limited to running under the BQL, but they would
+     * require additional auditing and may small thread-safety changes
+     * to move them into the I/O API. Often it's not worth doing that
+     * work since the APIs are only used with the BQL held at the
+     * moment, so they have been placed in the GS API (for now).
+     *
+     * All callers that use these function pointers must
+     * use this assertion:
+     * g_assert(qemu_in_main_thread());
+     * to catch when they are accidentally called without the BQL.
+     */
+
     /**
      * Called when the job is resumed by the user (i.e. user_paused becomes
      * false). .user_resume is called before .resume.
Signature · 1 line
2.27.0
#66 lore raw

RFC PATCH v2 23/25 block-backend-common.h: split function pointers in BlockDevOps

In reply to Emanuele Giuseppe Esposito

Assertions in the callers of the funciton pointrs are already added by previous patches.

---
 include/sysemu/block-backend-common.h | 42 +++++++++++++++++++++++----
 1 file changed, 37 insertions(+), 5 deletions(-)
include/sysemu/block-backend-common.h +37 -5
index 52ff6a4d26..25f34917b6 100644
@@ -17,6 +17,29 @@
 
 /* Callbacks for block device models */
 typedef struct BlockDevOps {
+
+    /*
+     * Global state (GS) API. These functions run under the BQL lock.
+     *
+     * If a function modifies the graph, it also uses drain and/or
+     * aio_context_acquire/release to be sure it has unique access.
+     * aio_context locking is needed together with BQL because of
+     * the thread-safe I/O API that concurrently runs and accesses
+     * the graph without the BQL.
+     *
+     * It is important to note that not all of these functions are
+     * necessarily limited to running under the BQL, but they would
+     * require additional auditing and may small thread-safety changes
+     * to move them into the I/O API. Often it's not worth doing that
+     * work since the APIs are only used with the BQL held at the
+     * moment, so they have been placed in the GS API (for now).
+     *
+     * All bdrv_* callers that use these function pointers must
+     * use this assertion:
+     * g_assert(qemu_in_main_thread());
+     * to catch when they are accidentally called without the BQL.
+     */
+
     /*
      * Runs when virtual media changed (monitor commands eject, change)
      * Argument load is true on load and false on eject.
@@ -34,16 +57,25 @@ typedef struct BlockDevOps {
      * true, even if they do not support eject requests.
      */
     void (*eject_request_cb)(void *opaque, bool force);
-    /*
-     * Is the virtual tray open?
-     * Device models implement this only when the device has a tray.
-     */
-    bool (*is_tray_open)(void *opaque);
+
     /*
      * Is the virtual medium locked into the device?
      * Device models implement this only when device has such a lock.
      */
     bool (*is_medium_locked)(void *opaque);
+
+    /*
+     * I/O API functions. These functions are thread-safe, and therefore
+     * can run in any thread as long as they have called
+     * aio_context_acquire/release().
+     */
+
+    /*
+     * Is the virtual tray open?
+     * Device models implement this only when the device has a tray.
+     */
+    bool (*is_tray_open)(void *opaque);
+
     /*
      * Runs when the size changed (e.g. monitor command block_resize)
      */
Signature · 1 line
2.27.0
#55 lore raw

RFC PATCH v2 18/25 block/coroutines: I/O API

In reply to Emanuele Giuseppe Esposito

block coroutines functions run in different aiocontext, and are not protected by the BQL. Therefore are I/O.

---
 block/coroutines.h | 6 ++++++
 1 file changed, 6 insertions(+)
block/coroutines.h +6 -0
index 514d169d23..105e0ce2a9 100644
@@ -27,6 +27,12 @@
 
 #include "block/block_int.h"
 
+/*
+ * I/O API functions. These functions are thread-safe, and therefore
+ * can run in any thread as long as they have called
+ * aio_context_acquire/release().
+ */
+
 int coroutine_fn bdrv_co_check(BlockDriverState *bs,
                                BdrvCheckResult *res, BdrvCheckMode fix);
 int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp);
Signature · 1 line
2.27.0
#52 lore raw

RFC PATCH v2 17/25 include/block/transactions: global state API + assertions

In reply to Emanuele Giuseppe Esposito

transactions run always under the BQL lock, so they are all in the global state API.

---
 include/qemu/transactions.h | 24 ++++++++++++++++++++++++
 util/transactions.c         |  4 ++++
 2 files changed, 28 insertions(+)
include/qemu/transactions.h +24 -0
index 92c5965235..f4a7c473fa 100644
@@ -37,6 +37,29 @@
 #define QEMU_TRANSACTIONS_H
 
 #include <gmodule.h>
+#include "qemu/main-loop.h"
+
+/*
+ * Global state (GS) API. These functions run under the BQL lock.
+ *
+ * If a function modifies the graph, it also uses drain and/or
+ * aio_context_acquire/release to be sure it has unique access.
+ * aio_context locking is needed together with BQL because of
+ * the thread-safe I/O API that concurrently runs and accesses
+ * the graph without the BQL.
+ *
+ * It is important to note that not all of these functions are
+ * necessarily limited to running under the BQL, but they would
+ * require additional auditing and may small thread-safety changes
+ * to move them into the I/O API. Often it's not worth doing that
+ * work since the APIs are only used with the BQL held at the
+ * moment, so they have been placed in the GS API (for now).
+ *
+ * All functions and function pointers in this header must use
+ * this assertion:
+ * g_assert(qemu_in_main_thread());
+ * to catch when they are accidentally called without the BQL.
+ */
 
 typedef struct TransactionActionDrv {
     void (*abort)(void *opaque);
@@ -53,6 +76,7 @@ void tran_commit(Transaction *tran);
 
 static inline void tran_finalize(Transaction *tran, int ret)
 {
+    g_assert(qemu_in_main_thread());
     if (ret < 0) {
         tran_abort(tran);
     } else {
util/transactions.c +4 -0
index d0bc9a3e73..20c3dafdb8 100644
@@ -23,6 +23,7 @@
 #include "qemu/osdep.h"
 
 #include "qemu/transactions.h"
+#include "qemu/main-loop.h"
 #include "qemu/queue.h"
 
 typedef struct TransactionAction {
@@ -47,6 +48,7 @@ Transaction *tran_new(void)
 void tran_add(Transaction *tran, TransactionActionDrv *drv, void *opaque)
 {
     TransactionAction *act;
+    g_assert(qemu_in_main_thread());
 
     act = g_new(TransactionAction, 1);
     *act = (TransactionAction) {
@@ -60,6 +62,7 @@ void tran_add(Transaction *tran, TransactionActionDrv *drv, void *opaque)
 void tran_abort(Transaction *tran)
 {
     TransactionAction *act, *next;
+    g_assert(qemu_in_main_thread());
 
     QSLIST_FOREACH_SAFE(act, &tran->actions, entry, next) {
         if (act->drv->abort) {
@@ -79,6 +82,7 @@ void tran_abort(Transaction *tran)
 void tran_commit(Transaction *tran)
 {
     TransactionAction *act, *next;
+    g_assert(qemu_in_main_thread());
 
     QSLIST_FOREACH_SAFE(act, &tran->actions, entry, next) {
         if (act->drv->commit) {
Signature · 1 line
2.27.0
#46 lore raw

RFC PATCH v2 15/25 include/block/snapshot: global state API + assertions

In reply to Emanuele Giuseppe Esposito

Snapshots run also under the BQL lock, so they all are in the global state API. The aiocontext lock that they hold is currently an overkill and in future could be removed.

---
 block/snapshot.c         | 28 ++++++++++++++++++++++++++++
 include/block/snapshot.h | 21 +++++++++++++++++++++
 migration/savevm.c       |  2 ++
 3 files changed, 51 insertions(+)
block/snapshot.c +28 -0
index ccacda8bd5..e8756f7f90 100644
@@ -57,6 +57,8 @@ int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
     QEMUSnapshotInfo *sn_tab, *sn;
     int nb_sns, i, ret;
 
+    g_assert(qemu_in_main_thread());
+
     ret = -ENOENT;
     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
     if (nb_sns < 0) {
@@ -105,6 +107,7 @@ bool bdrv_snapshot_find_by_id_and_name(BlockDriverState *bs,
     bool ret = false;
 
     assert(id || name);
+    g_assert(qemu_in_main_thread());
 
     nb_sns = bdrv_snapshot_list(bs, &sn_tab);
     if (nb_sns < 0) {
@@ -200,6 +203,7 @@ static BlockDriverState *bdrv_snapshot_fallback(BlockDriverState *bs)
 int bdrv_can_snapshot(BlockDriverState *bs)
 {
     BlockDriver *drv = bs->drv;
+    g_assert(qemu_in_main_thread());
     if (!drv || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
         return 0;
     }
@@ -220,6 +224,9 @@ int bdrv_snapshot_create(BlockDriverState *bs,
 {
     BlockDriver *drv = bs->drv;
     BlockDriverState *fallback_bs = bdrv_snapshot_fallback(bs);
+
+    g_assert(qemu_in_main_thread());
+
     if (!drv) {
         return -ENOMEDIUM;
     }
@@ -240,6 +247,8 @@ int bdrv_snapshot_goto(BlockDriverState *bs,
     BdrvChild **fallback_ptr;
     int ret, open_ret;
 
+    g_assert(qemu_in_main_thread());
+
     if (!drv) {
         error_setg(errp, "Block driver is closed");
         return -ENOMEDIUM;
@@ -348,6 +357,8 @@ int bdrv_snapshot_delete(BlockDriverState *bs,
     BlockDriverState *fallback_bs = bdrv_snapshot_fallback(bs);
     int ret;
 
+    g_assert(qemu_in_main_thread());
+
     if (!drv) {
         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, bdrv_get_device_name(bs));
         return -ENOMEDIUM;
@@ -380,6 +391,8 @@ int bdrv_snapshot_list(BlockDriverState *bs,
 {
     BlockDriver *drv = bs->drv;
     BlockDriverState *fallback_bs = bdrv_snapshot_fallback(bs);
+
+    g_assert(qemu_in_main_thread());
     if (!drv) {
         return -ENOMEDIUM;
     }
@@ -419,6 +432,8 @@ int bdrv_snapshot_load_tmp(BlockDriverState *bs,
 {
     BlockDriver *drv = bs->drv;
 
+    g_assert(qemu_in_main_thread());
+
     if (!drv) {
         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, bdrv_get_device_name(bs));
         return -ENOMEDIUM;
@@ -447,6 +462,8 @@ int bdrv_snapshot_load_tmp_by_id_or_name(BlockDriverState *bs,
     int ret;
     Error *local_err = NULL;
 
+    g_assert(qemu_in_main_thread());
+
     ret = bdrv_snapshot_load_tmp(bs, id_or_name, NULL, &local_err);
     if (ret == -ENOENT || ret == -EINVAL) {
         error_free(local_err);
@@ -515,6 +532,8 @@ bool bdrv_all_can_snapshot(bool has_devices, strList *devices,
     g_autoptr(GList) bdrvs = NULL;
     GList *iterbdrvs;
 
+    g_assert(qemu_in_main_thread());
+
     if (bdrv_all_get_snapshot_devices(has_devices, devices, &bdrvs, errp) < 0) {
         return false;
     }
@@ -549,6 +568,8 @@ int bdrv_all_delete_snapshot(const char *name,
     g_autoptr(GList) bdrvs = NULL;
     GList *iterbdrvs;
 
+    g_assert(qemu_in_main_thread());
+
     if (bdrv_all_get_snapshot_devices(has_devices, devices, &bdrvs, errp) < 0) {
         return -1;
     }
@@ -588,6 +609,8 @@ int bdrv_all_goto_snapshot(const char *name,
     g_autoptr(GList) bdrvs = NULL;
     GList *iterbdrvs;
 
+    g_assert(qemu_in_main_thread());
+
     if (bdrv_all_get_snapshot_devices(has_devices, devices, &bdrvs, errp) < 0) {
         return -1;
     }
@@ -622,6 +645,8 @@ int bdrv_all_has_snapshot(const char *name,
     g_autoptr(GList) bdrvs = NULL;
     GList *iterbdrvs;
 
+    g_assert(qemu_in_main_thread());
+
     if (bdrv_all_get_snapshot_devices(has_devices, devices, &bdrvs, errp) < 0) {
         return -1;
     }
@@ -663,6 +688,7 @@ int bdrv_all_create_snapshot(QEMUSnapshotInfo *sn,
 {
     g_autoptr(GList) bdrvs = NULL;
     GList *iterbdrvs;
+    g_assert(qemu_in_main_thread());
 
     if (bdrv_all_get_snapshot_devices(has_devices, devices, &bdrvs, errp) < 0) {
         return -1;
@@ -703,6 +729,8 @@ BlockDriverState *bdrv_all_find_vmstate_bs(const char *vmstate_bs,
     g_autoptr(GList) bdrvs = NULL;
     GList *iterbdrvs;
 
+    g_assert(qemu_in_main_thread());
+
     if (bdrv_all_get_snapshot_devices(has_devices, devices, &bdrvs, errp) < 0) {
         return NULL;
     }
include/block/snapshot.h +21 -0
index 940345692f..3a84849388 100644
@@ -45,6 +45,27 @@ typedef struct QEMUSnapshotInfo {
     uint64_t icount; /* record/replay step */
 } QEMUSnapshotInfo;
 
+/*
+ * Global state (GS) API. These functions run under the BQL lock.
+ *
+ * If a function modifies the graph, it also uses drain and/or
+ * aio_context_acquire/release to be sure it has unique access.
+ * aio_context locking is needed together with BQL because of
+ * the thread-safe I/O API that concurrently runs and accesses
+ * the graph without the BQL.
+ *
+ * It is important to note that not all of these functions are
+ * necessarily limited to running under the BQL, but they would
+ * require additional auditing and may small thread-safety changes
+ * to move them into the I/O API. Often it's not worth doing that
+ * work since the APIs are only used with the BQL held at the
+ * moment, so they have been placed in the GS API (for now).
+ *
+ * All functions in this header must use this assertion:
+ * g_assert(qemu_in_main_thread());
+ * to catch when they are accidentally called without the BQL.
+ */
+
 int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
                        const char *name);
 bool bdrv_snapshot_find_by_id_and_name(BlockDriverState *bs,
migration/savevm.c +2 -0
index 7b7b64bd13..439f736ad5 100644
@@ -2785,6 +2785,8 @@ bool save_snapshot(const char *name, bool overwrite, const char *vmstate,
     g_autoptr(GDateTime) now = g_date_time_new_now_local();
     AioContext *aio_context;
 
+    g_assert(qemu_in_main_thread());
+
     if (migration_is_blocked(errp)) {
         return false;
     }
Signature · 1 line
2.27.0
#62 lore raw

RFC PATCH v2 21/25 block_int-common.h: split function pointers in BdrvChildClass

In reply to Emanuele Giuseppe Esposito
---
 include/block/block_int-common.h | 65 ++++++++++++++++++++++----------
 1 file changed, 46 insertions(+), 19 deletions(-)
include/block/block_int-common.h +46 -19
index 184cfab2d6..a6ea824b64 100644
@@ -798,12 +798,31 @@ struct BdrvChildClass {
      */
     bool parent_is_bds;
 
+    /*
+     * Global state (GS) API. These functions run under the BQL lock.
+     *
+     * If a function modifies the graph, it also uses drain and/or
+     * aio_context_acquire/release to be sure it has unique access.
+     * aio_context locking is needed together with BQL because of
+     * the thread-safe I/O API that concurrently runs and accesses
+     * the graph without the BQL.
+     *
+     * It is important to note that not all of these functions are
+     * necessarily limited to running under the BQL, but they would
+     * require additional auditing and may small thread-safety changes
+     * to move them into the I/O API. Often it's not worth doing that
+     * work since the APIs are only used with the BQL held at the
+     * moment, so they have been placed in the GS API (for now).
+     *
+     * All callers that use these function pointers must
+     * use this assertion:
+     * g_assert(qemu_in_main_thread());
+     * to catch when they are accidentally called without the BQL.
+     */
     void (*inherit_options)(BdrvChildRole role, bool parent_is_format,
                             int *child_flags, QDict *child_options,
                             int parent_flags, QDict *parent_options);
-
     void (*change_media)(BdrvChild *child, bool load);
-    void (*resize)(BdrvChild *child);
 
     /*
      * Returns a name that is supposedly more useful for human users than the
@@ -820,6 +839,31 @@ struct BdrvChildClass {
      */
     char *(*get_parent_desc)(BdrvChild *child);
 
+    void (*attach)(BdrvChild *child);
+    void (*detach)(BdrvChild *child);
+
+    /*
+     * Notifies the parent that the filename of its child has changed (e.g.
+     * because the direct child was removed from the backing chain), so that it
+     * can update its reference.
+     */
+    int (*update_filename)(BdrvChild *child, BlockDriverState *new_base,
+                           const char *filename, Error **errp);
+
+    bool (*can_set_aio_ctx)(BdrvChild *child, AioContext *ctx,
+                        GSList **ignore, Error **errp);
+    void (*set_aio_ctx)(BdrvChild *child, AioContext *ctx, GSList **ignore);
+
+    AioContext *(*get_parent_aio_context)(BdrvChild *child);
+
+    /*
+     * I/O API functions. These functions are thread-safe, and therefore
+     * can run in any thread as long as they have called
+     * aio_context_acquire/release().
+     */
+
+    void (*resize)(BdrvChild *child);
+
     /*
      * If this pair of functions is implemented, the parent doesn't issue new
      * requests after returning from .drained_begin() until .drained_end() is
@@ -852,23 +896,6 @@ struct BdrvChildClass {
      */
     void (*activate)(BdrvChild *child, Error **errp);
     int (*inactivate)(BdrvChild *child);
-
-    void (*attach)(BdrvChild *child);
-    void (*detach)(BdrvChild *child);
-
-    /*
-     * Notifies the parent that the filename of its child has changed (e.g.
-     * because the direct child was removed from the backing chain), so that it
-     * can update its reference.
-     */
-    int (*update_filename)(BdrvChild *child, BlockDriverState *new_base,
-                           const char *filename, Error **errp);
-
-    bool (*can_set_aio_ctx)(BdrvChild *child, AioContext *ctx,
-                            GSList **ignore, Error **errp);
-    void (*set_aio_ctx)(BdrvChild *child, AioContext *ctx, GSList **ignore);
-
-    AioContext *(*get_parent_aio_context)(BdrvChild *child);
 };
 
 extern const BdrvChildClass child_of_bds;
Signature · 1 line
2.27.0
#6 lore raw

Re: [RFC PATCH v2 03/25] block/block-backend.c: assertions for block-backend

In reply to Emanuele Giuseppe Esposito
Quoted 16 lines · Emanuele Giuseppe Esposito

All the global state (GS) API functions will check that qemu_in_main_thread() returns true. If not, it means that the safety of BQL cannot be guaranteed, and they need to be moved to I/O.

---
 block/block-backend.c  | 89 +++++++++++++++++++++++++++++++++++++++++-
 softmmu/qdev-monitor.c |  2 +
 2 files changed, 90 insertions(+), 1 deletion(-)
block/block-backend.c +0 -0
index d31ae16b99..9cd3b27b53 100644

block/block-backend.c static void blk_root_activate(BdrvChild *child, Error **errp) · line 230

Quoted 4 lines
block/block-backend.c +1 -0
@@ -227,6 +227,7 @@ static void blk_root_activate(BdrvChild *child, Error **errp)
 
 void blk_set_force_allow_inactivate(BlockBackend *blk)
 {
+    g_assert(qemu_in_main_thread());

Why g_assert()?

block/block-backend.c bool monitor_add_blk(BlockBackend *blk, const char *name, Error **errp) · line 679

Quoted 5 lines
block/block-backend.c +1 -0
@@ -661,6 +676,7 @@ bool monitor_add_blk(BlockBackend *blk, const char *name, Error **errp)
 {
     assert(!blk->name);
     assert(name && name[0]);
+    g_assert(qemu_in_main_thread());

especially why mixed spellings?

Per osdep.h, we don't support builds with NDEBUG or G_DISABLE_ASSERT defined to their non-default values, so behavior isn't really different, but consistency says we use 'assert' more frequently than 'g_assert'.

Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3266
Virtualization:  qemu.org | libvirt.org
#7 lore raw

Re: [RFC PATCH v2 03/25] block/block-backend.c: assertions for block-backend

Quoted 32 lines · Eric Blake
Quoted 16 lines · Emanuele Giuseppe Esposito

All the global state (GS) API functions will check that qemu_in_main_thread() returns true. If not, it means that the safety of BQL cannot be guaranteed, and they need to be moved to I/O.

---
  block/block-backend.c  | 89 +++++++++++++++++++++++++++++++++++++++++-
  softmmu/qdev-monitor.c |  2 +
  2 files changed, 90 insertions(+), 1 deletion(-)
block/block-backend.c +0 -0
index d31ae16b99..9cd3b27b53 100644

block/block-backend.c static void blk_root_activate(BdrvChild *child, Error **errp) · line 230

Quoted 4 lines
block/block-backend.c +1 -0
@@ -227,6 +227,7 @@ static void blk_root_activate(BdrvChild *child, Error **errp)
 
  void blk_set_force_allow_inactivate(BlockBackend *blk)
  {
+    g_assert(qemu_in_main_thread());

Why g_assert()?

block/block-backend.c bool monitor_add_blk(BlockBackend *blk, const char *name, Error **errp) · line 679

Quoted 5 lines
block/block-backend.c +1 -0
@@ -661,6 +676,7 @@ bool monitor_add_blk(BlockBackend *blk, const char *name, Error **errp)
  {
      assert(!blk->name);
      assert(name && name[0]);
+    g_assert(qemu_in_main_thread());

especially why mixed spellings?

Quoted 5 lines

Per osdep.h, we don't support builds with NDEBUG or G_DISABLE_ASSERT defined to their non-default values, so behavior isn't really different, but consistency says we use 'assert' more frequently than 'g_assert'.

You are right, I did not put that much attention to this. Will change it in assert().

Thank you,
Emanuele

Reviewed-by on v2 1/25
#2 lore raw

Re: [RFC PATCH v2 01/25] main-loop.h: introduce qemu_in_main_thread()

In reply to Emanuele Giuseppe Esposito
Quoted 15 lines · Emanuele Giuseppe Esposito

When invoked from the main loop, this function is the same as qemu_mutex_iothread_locked, and returns true if the BQL is held. When invoked from iothreads or tests, it returns true only if the current AioContext is the Main Loop.

This essentially just extends qemu_mutex_iothread_locked to work also in unit tests or other users like storage-daemon, that run in the Main Loop but end up using the implementation in stubs/iothread-lock.c.

Using qemu_mutex_iothread_locked in unit tests defaults to false because they use the implementation in stubs/iothread-lock, making all assertions added in next patches fail despite the AioContext is still the main loop.

Quoted 6 lines
---
 include/qemu/main-loop.h | 13 +++++++++++++
 softmmu/cpus.c           |  5 +++++
 stubs/iothread-lock.c    |  5 +++++
 3 files changed, 23 insertions(+)
Reviewed-by on v2 2/25
#4 lore raw

Re: [RFC PATCH v2 02/25] include/sysemu/block-backend: split header into I/O and global state (GS) API

In reply to Emanuele Giuseppe Esposito
Quoted 4 lines · Emanuele Giuseppe Esposito

+/*
+ * Global state (GS) API. These functions run under the BQL lock.
+ *
+ * If a function modifies the graph, it also uses drain and/or

Quoted 8 lines

+ * aio_context_acquire/release to be sure it has unique access.
+ * aio_context locking is needed together with BQL because of
+ * the thread-safe I/O API that concurrently runs and accesses
+ * the graph without the BQL.
+ *
+ * It is important to note that not all of these functions are
+ * necessarily limited to running under the BQL, but they would
+ * require additional auditing and may small thread-safety changes

s/may/many/

Quoted 17 lines
include/sysemu/block-backend-io.h new file +11 -0
new file mode 100644
index 0000000000..a77b2080ce
@@ -0,0 +1,130 @@
+/*
+ * QEMU Block backends
+ *
+ * Copyright (C) 2014-2016 Red Hat, Inc.
+ *
+ * Authors:
+ *  Markus Armbruster <[email protected]>,
+ *
+ * This work is licensed under the terms of the GNU LGPL, version 2.1
+ * or later.  See the COPYING.LIB file in the top-level directory.
+ */

include/sysemu/block-backend-io.h line 21

Quoted 10 lines
include/sysemu/block-backend-io.h new file +10 -0
+
+#ifndef BLOCK_BACKEND_IO_H
+#define BLOCK_BACKEND_IO_H
+
+#include "block-backend-common.h"
+
+/*
+ * I/O API functions. These functions are thread-safe, and therefore
+ * can run in any thread as long as they have called
+ * aio_context_acquire/release().

The meaning of "they" is not 100% clear. It could be the thread or the I/O API functions. I suggest making it explicit:

s/they have/the thread has/

Otherwise:

#10 lore raw

Re: [RFC PATCH v2 04/25] include/block/block: split header into I/O and global state API

In reply to Emanuele Giuseppe Esposito

include/block/block-global-state.h line 77

Quoted 2 lines · Emanuele Giuseppe Esposito
include/block/block-global-state.h new file +2 -0
+int bdrv_pwrite_sync(BdrvChild *child, int64_t offset,
+                     const void *buf, int64_t bytes);

Why is this bit of a surprise since the other synchronous I/O functions aren't included in this header. Why did you put it here? This one may be safe to move to the I/O API.

include/block/block-global-state.h line 136

Quoted 3 lines
include/block/block-global-state.h new file +3 -0
+int bdrv_block_status(BlockDriverState *bs, int64_t offset,
+                      int64_t bytes, int64_t *pnum, int64_t *map,
+                      BlockDriverState **file);

This function just called bdrv_block_status_above(), which is in the I/O API. I think it's safe to move this to the I/O API or else bdrv_block_status_above() shouldn't be there :).

Reviewed-by on v2 5/25
#18 lore raw

Re: [RFC PATCH v2 05/25] assertions for block global state API

In reply to Emanuele Giuseppe Esposito
Quoted 7 lines · Emanuele Giuseppe Esposito
---
 block.c        | 135 +++++++++++++++++++++++++++++++++++++++++++++++--
 block/commit.c |   2 +
 block/io.c     |  20 ++++++++
 blockdev.c     |   1 +
 4 files changed, 155 insertions(+), 3 deletions(-)
Reviewed-by on v2 3/25
#8 lore raw

Re: [RFC PATCH v2 03/25] block/block-backend.c: assertions for block-backend

In reply to Emanuele Giuseppe Esposito
Quoted 10 lines · Emanuele Giuseppe Esposito

All the global state (GS) API functions will check that qemu_in_main_thread() returns true. If not, it means that the safety of BQL cannot be guaranteed, and they need to be moved to I/O.

---
 block/block-backend.c  | 89 +++++++++++++++++++++++++++++++++++++++++-
 softmmu/qdev-monitor.c |  2 +
 2 files changed, 90 insertions(+), 1 deletion(-)

Modulo Eric's comment:

Reviewed-by on v2 6/25
#20 lore raw

Re: [RFC PATCH v2 06/25] include/block/block_int: split header into I/O and global state API

In reply to Emanuele Giuseppe Esposito

include/block/block_int-global-state.h line 279

Quoted 10 lines · Emanuele Giuseppe Esposito
include/block/block_int-global-state.h new file +10 -0
+int coroutine_fn bdrv_co_copy_range_from(BdrvChild *src, int64_t src_offset,
+                                         BdrvChild *dst, int64_t dst_offset,
+                                         int64_t bytes,
+                                         BdrvRequestFlags read_flags,
+                                         BdrvRequestFlags write_flags);
+int coroutine_fn bdrv_co_copy_range_to(BdrvChild *src, int64_t src_offset,
+                                       BdrvChild *dst, int64_t dst_offset,
+                                       int64_t bytes,
+                                       BdrvRequestFlags read_flags,
+                                       BdrvRequestFlags write_flags);

These look like I/O APIs to me. Are they in the GS API because only qemu-img.c call copy_range? I thought SCSI emulation might call it too, but grep says otherwise.

Otherwise:

#11 lore raw

Re: [RFC PATCH v2 04/25] include/block/block: split header into I/O and global state API

In reply to Stefan Hajnoczi
Quoted 7 lines · Stefan Hajnoczi

include/block/block-global-state.h line 77

Quoted 2 lines · Emanuele Giuseppe Esposito
include/block/block-global-state.h new file +2 -0
+int bdrv_pwrite_sync(BdrvChild *child, int64_t offset,
+                     const void *buf, int64_t bytes);

Why is this bit of a surprise since the other synchronous I/O functions aren't included in this header. Why did you put it here? This one may be safe to move to the I/O API.

Considering that in the next patch I did not even add an assertion for it, I am confident enough that it was a copy-paste mistake. This goes into I/O.

Quoted 9 lines

include/block/block-global-state.h line 136

Quoted 4 lines
include/block/block-global-state.h new file +3 -0
+int bdrv_block_status(BlockDriverState *bs, int64_t offset,
+                      int64_t bytes, int64_t *pnum, int64_t *map,
+                      BlockDriverState **file);

This function just called bdrv_block_status_above(), which is in the I/O API. I think it's safe to move this to the I/O API or else bdrv_block_status_above() shouldn't be there :).

It *seems* that while bdrv_block_status_above() is an I/O, probably running in some coroutine (from here its internal qemu_in_coroutine check), bdrv_block_status might be called from the main loop (or alternatively the function is never invoked in the tests, so the assertion never triggered).

Maybe bdrv_block_status_above is one of the few functions that are both I/O and Main loop? I put it in I/O as it can't have the assertion.

Thank you,
Emanuele

#21 lore raw

Re: [RFC PATCH v2 06/25] include/block/block_int: split header into I/O and global state API

In reply to Stefan Hajnoczi
Quoted 15 lines · Stefan Hajnoczi

include/block/block_int-global-state.h line 279

Quoted 10 lines · Emanuele Giuseppe Esposito
include/block/block_int-global-state.h new file +10 -0
+int coroutine_fn bdrv_co_copy_range_from(BdrvChild *src, int64_t src_offset,
+                                         BdrvChild *dst, int64_t dst_offset,
+                                         int64_t bytes,
+                                         BdrvRequestFlags read_flags,
+                                         BdrvRequestFlags write_flags);
+int coroutine_fn bdrv_co_copy_range_to(BdrvChild *src, int64_t src_offset,
+                                       BdrvChild *dst, int64_t dst_offset,
+                                       int64_t bytes,
+                                       BdrvRequestFlags read_flags,
+                                       BdrvRequestFlags write_flags);

These look like I/O APIs to me. Are they in the GS API because only qemu-img.c call copy_range? I thought SCSI emulation might call it too, but grep says otherwise.

SCSI (iscsi.c) implements the function pointer (*bdrv_co_copy_range_from/to), but does not call the function itself. However, later in the patches I put the function pointer as I/O.

These two functions are only tested by test-replication and thus are always under BQL when tested. But after looking at them again, and since they internally use only I/O APIs, I think we can move them to the I/O API.

Thank you,
Emanuele

#14 lore raw

Re: [RFC PATCH v2 04/25] include/block/block: split header into I/O and global state API

In reply to Emanuele Giuseppe Esposito
Quoted 6 lines · Emanuele Giuseppe Esposito

Similarly to the previous patch, split block.h
in block-io.h and block-global-state.h

block-common.h contains the structures shared between the two headers, and the functions that can't be categorized as I/O or global state.

This is nice from a code organization POV, but it doesn't do all that much from a code reviewer / author POV as I doubt anyone will remember which header file the respective APIs/structures/ constants are in, without having to look it up each time.

It would make life easier if we had distinct namning conventions for APIs/struct/contsants in the respective headers.

eg instead of "bdrv_" have "bdrv_state_" and "bdrv_io_" as the two naming conventions for -global-state.h and -io.h respectively, nad only use the bare 'bdrv_' for -common.h

Yes, this would be major code churn, but I think it'd make the code clearer to understand which will be a win over the long term.

NB, I'm not suggesting doing a rename as part of this patch though. Any rename would have to be separate, and likely split over many patches to make it manageable.

Regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
#12 lore raw

Re: [RFC PATCH v2 04/25] include/block/block: split header into I/O and global state API

In reply to Emanuele Giuseppe Esposito
Quoted 5 lines · Emanuele Giuseppe Esposito
Quoted 5 lines
Quoted 4 lines

+int bdrv_block_status(BlockDriverState *bs, int64_t offset, +                      int64_t bytes, int64_t *pnum, int64_t *map, +                      BlockDriverState **file);

Quoted 8 lines
Quoted 4 lines

This function just called bdrv_block_status_above(), which is in the I/O API. I think it's safe to move this to the I/O API or else bdrv_block_status_above() shouldn't be there :).

It *seems* that while bdrv_block_status_above() is an I/O, probably running in some coroutine (from here its internal qemu_in_coroutine check), bdrv_block_status might be called from the main loop (or alternatively the function is never invoked in the tests, so the assertion never triggered).

Maybe bdrv_block_status_above is one of the few functions that are both I/O and Main loop? I put it in I/O as it can't have the assertion.

No, they are both I/O. Callers of bdrv_block_status are hw/nvme and qemu-img.c; while the latter can be either (it does not have iothreads), hw/nvme is definitely I/O.

Paolo

Reviewed-by on v2 18/25
#56 lore raw

Re: [RFC PATCH v2 18/25] block/coroutines: I/O API

In reply to Emanuele Giuseppe Esposito
Quoted 16 lines · Emanuele Giuseppe Esposito

block coroutines functions run in different aiocontext, and are not protected by the BQL. Therefore are I/O.

---
  block/coroutines.h | 6 ++++++
  1 file changed, 6 insertions(+)
block/coroutines.h +0 -0
index 514d169d23..105e0ce2a9 100644
@@ -27,6 +27,12 @@
 
  #include "block/block_int.h"

block/coroutines.h line 38

Quoted 10 lines
block/coroutines.h +6 -0
 
+/*
+ * I/O API functions. These functions are thread-safe, and therefore
+ * can run in any thread as long as they have called
+ * aio_context_acquire/release().
+ */
+
  int coroutine_fn bdrv_co_check(BlockDriverState *bs,
                                 BdrvCheckResult *res, BdrvCheckMode fix);
  int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp);

except for the same comment about "they" that was in patch 2.

Paolo

Reviewed-by on v2 13/25
#41 lore raw

Re: [RFC PATCH v2 13/25] include/systemu/blockdev.h: global state API

In reply to Emanuele Giuseppe Esposito
Quoted 6 lines · Emanuele Giuseppe Esposito
  DriveInfo *drive_get_next(BlockInterfaceType type);
include/sysemu/blockdev.h +4 -0
+DriveInfo *drive_new(QemuOpts *arg, BlockInterfaceType block_default_type,
+                     Error **errp);
+
+/* Common functions that are neither I/O nor Global State */

include/sysemu/blockdev.h struct DriveInfo { · line 59

Quoted 10 lines
include/sysemu/blockdev.h +5 -2
+
+DriveInfo *blk_legacy_dinfo(BlockBackend *blk);
+int drive_get_max_devs(BlockInterfaceType type);
+
  QemuOpts *drive_def(const char *optstr);
+
  QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
                      const char *optstr);
-DriveInfo *drive_new(QemuOpts *arg, BlockInterfaceType block_default_type,
-                     Error **errp);

drive_add and drive_def touch global state (QemuOpts). But really neither should be in this header: drive_add can be moved to softmmu/vl.c, while drive_def can be inlined into its two callers. With that changed,

Reviewed-by on v2 8/25
#26 lore raw

Re: [RFC PATCH v2 08/25] block: introduce assert_bdrv_graph_writable

In reply to Emanuele Giuseppe Esposito
Quoted 77 lines · Emanuele Giuseppe Esposito

We want to be sure that the functions that write the child and parent list of a bs are either under BQL or drain.
If this guarantee holds, then we can read the list also in the I/O APIs.

---
  block.c                                | 5 +++++
  block/io.c                             | 5 +++++
  include/block/block_int-global-state.h | 8 +++++++-
  3 files changed, 17 insertions(+), 1 deletion(-)
block.c +5 -0
index b912f517a4..7d1eb847a4 100644
@@ -2711,12 +2711,14 @@ static void bdrv_replace_child_noperm(BdrvChild *child,
          if (child->klass->detach) {
              child->klass->detach(child);
          }
+        assert_bdrv_graph_writable(old_bs);
          QLIST_REMOVE(child, next_parent);
      }
 
      child->bs = new_bs;
 
      if (new_bs) {
+        assert_bdrv_graph_writable(new_bs);
          QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
 
          /*
@@ -2917,6 +2919,7 @@ static int bdrv_attach_child_noperm(BlockDriverState *parent_bs,
          return ret;
      }
 
+    assert_bdrv_graph_writable(parent_bs);
      QLIST_INSERT_HEAD(&parent_bs->children, *child, next);
      /*
       * child is removed in bdrv_attach_child_common_abort(), so don't care to
@@ -3117,6 +3120,7 @@ static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
  void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
  {
      g_assert(qemu_in_main_thread());
+    assert_bdrv_graph_writable(parent);
      if (child == NULL) {
          return;
      }
@@ -4878,6 +4882,7 @@ static void bdrv_remove_filter_or_cow_child_abort(void *opaque)
      BdrvRemoveFilterOrCowChild *s = opaque;
      BlockDriverState *parent_bs = s->child->opaque;
 
+    assert_bdrv_graph_writable(parent_bs);
      QLIST_INSERT_HEAD(&parent_bs->children, s->child, next);
      if (s->is_backing) {
          parent_bs->backing = s->child;
block/io.c +5 -0
index 21dcc5d962..d184183b07 100644
@@ -739,6 +739,11 @@ void bdrv_drain_all(void)
      bdrv_drain_all_end();
  }
 
+void assert_bdrv_graph_writable(BlockDriverState *bs)
+{
+    g_assert(qatomic_read(&bs->quiesce_counter) > 0 || qemu_in_main_thread());
+}
+
  /**
   * Remove an active request from the tracked requests list
   *
include/block/block_int-global-state.h +0 -0
index aad549cb85..a53ab146fc 100644
@@ -343,4 +343,10 @@ void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
   */

include/block/block_int-global-state.h void bdrv_remove_aio_context_notifier(BlockDriverState *bs, · line 352

Quoted 10 lines
include/block/block_int-global-state.h +7 -1
  void bdrv_drain_all_end_quiesce(BlockDriverState *bs);
 
-#endif /* BLOCK_INT_GLOBAL_STATE*/
+/**
+ * Make sure that the function is either running under
+ * drain, or under BQL.
+ */
+void assert_bdrv_graph_writable(BlockDriverState *bs);
+
+#endif /* BLOCK_INT_GLOBAL_STATE */
#27 lore raw

Re: [RFC PATCH v2 08/25] block: introduce assert_bdrv_graph_writable

In reply to Emanuele Giuseppe Esposito
Quoted 59 lines · Emanuele Giuseppe Esposito

We want to be sure that the functions that write the child and parent list of a bs are either under BQL or drain.
If this guarantee holds, then we can read the list also in the I/O APIs.

---
  block.c                                | 5 +++++
  block/io.c                             | 5 +++++
  include/block/block_int-global-state.h | 8 +++++++-
  3 files changed, 17 insertions(+), 1 deletion(-)
block.c +5 -0
index b912f517a4..7d1eb847a4 100644
@@ -2711,12 +2711,14 @@ static void bdrv_replace_child_noperm(BdrvChild *child,
          if (child->klass->detach) {
              child->klass->detach(child);
          }
+        assert_bdrv_graph_writable(old_bs);
          QLIST_REMOVE(child, next_parent);
      }
 
      child->bs = new_bs;
 
      if (new_bs) {
+        assert_bdrv_graph_writable(new_bs);
          QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
 
          /*
@@ -2917,6 +2919,7 @@ static int bdrv_attach_child_noperm(BlockDriverState *parent_bs,
          return ret;
      }
 
+    assert_bdrv_graph_writable(parent_bs);
      QLIST_INSERT_HEAD(&parent_bs->children, *child, next);
      /*
       * child is removed in bdrv_attach_child_common_abort(), so don't care to
@@ -3117,6 +3120,7 @@ static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
  void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
  {
      g_assert(qemu_in_main_thread());
+    assert_bdrv_graph_writable(parent);
      if (child == NULL) {
          return;
      }
@@ -4878,6 +4882,7 @@ static void bdrv_remove_filter_or_cow_child_abort(void *opaque)
      BdrvRemoveFilterOrCowChild *s = opaque;
      BlockDriverState *parent_bs = s->child->opaque;
 
+    assert_bdrv_graph_writable(parent_bs);
      QLIST_INSERT_HEAD(&parent_bs->children, s->child, next);
      if (s->is_backing) {
          parent_bs->backing = s->child;
block/io.c +0 -0
index 21dcc5d962..d184183b07 100644

block/io.c void bdrv_drain_all(void) · line 745

Quoted 7 lines
block/io.c +4 -0
@@ -739,6 +739,11 @@ void bdrv_drain_all(void)
      bdrv_drain_all_end();
  }
 
+void assert_bdrv_graph_writable(BlockDriverState *bs)
+{
+    g_assert(qatomic_read(&bs->quiesce_counter) > 0 || qemu_in_main_thread());
+}

Hmm, wait - I think this should be an "&&", not an OR?

Paolo

Quoted 21 lines
block/io.c +1 -0
+
  /**
   * Remove an active request from the tracked requests list
   *
include/block/block_int-global-state.h +7 -1
index aad549cb85..a53ab146fc 100644
@@ -343,4 +343,10 @@ void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
   */
  void bdrv_drain_all_end_quiesce(BlockDriverState *bs);
 
-#endif /* BLOCK_INT_GLOBAL_STATE*/
+/**
+ * Make sure that the function is either running under
+ * drain, or under BQL.
+ */
+void assert_bdrv_graph_writable(BlockDriverState *bs);
+
+#endif /* BLOCK_INT_GLOBAL_STATE */
Reviewed-by on v2 14/25
#44 lore raw

Re: [RFC PATCH v2 14/25] assertions for blockdev.h global state API

In reply to Emanuele Giuseppe Esposito
Quoted 84 lines · Emanuele Giuseppe Esposito
---
  block/block-backend.c |  2 ++
  blockdev.c            | 12 ++++++++++++
  2 files changed, 14 insertions(+)
block/block-backend.c +2 -0
index 9f09245069..18791c4fdc 100644
@@ -805,6 +805,7 @@ DriveInfo *blk_legacy_dinfo(BlockBackend *blk)
  DriveInfo *blk_set_legacy_dinfo(BlockBackend *blk, DriveInfo *dinfo)
  {
      assert(!blk->legacy_dinfo);
+    g_assert(qemu_in_main_thread());
      return blk->legacy_dinfo = dinfo;
  }
 
@@ -815,6 +816,7 @@ DriveInfo *blk_set_legacy_dinfo(BlockBackend *blk, DriveInfo *dinfo)
  BlockBackend *blk_by_legacy_dinfo(DriveInfo *dinfo)
  {
      BlockBackend *blk = NULL;
+    g_assert(qemu_in_main_thread());
 
      while ((blk = blk_next(blk)) != NULL) {
          if (blk->legacy_dinfo == dinfo) {
blockdev.c +10 -0
index 5608b78f8f..917bcf8cbc 100644
@@ -114,6 +114,8 @@ void override_max_devs(BlockInterfaceType type, int max_devs)
      BlockBackend *blk;
      DriveInfo *dinfo;
 
+    g_assert(qemu_in_main_thread());
+
      if (max_devs <= 0) {
          return;
      }
@@ -230,6 +232,8 @@ DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
      BlockBackend *blk;
      DriveInfo *dinfo;
 
+    g_assert(qemu_in_main_thread());
+
      for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
          dinfo = blk_legacy_dinfo(blk);
          if (dinfo && dinfo->type == type
@@ -252,6 +256,8 @@ void drive_check_orphaned(void)
      Location loc;
      bool orphans = false;
 
+    g_assert(qemu_in_main_thread());
+
      for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
          dinfo = blk_legacy_dinfo(blk);
          /*
@@ -285,6 +291,7 @@ void drive_check_orphaned(void)
 
  DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
  {
+    g_assert(qemu_in_main_thread());
      return drive_get(type,
                       drive_index_to_bus_id(type, index),
                       drive_index_to_unit_id(type, index));
@@ -296,6 +303,8 @@ int drive_get_max_bus(BlockInterfaceType type)
      BlockBackend *blk;
      DriveInfo *dinfo;
 
+    g_assert(qemu_in_main_thread());
+
      max_bus = -1;
      for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
          dinfo = blk_legacy_dinfo(blk);
@@ -312,6 +321,7 @@ int drive_get_max_bus(BlockInterfaceType type)
  DriveInfo *drive_get_next(BlockInterfaceType type)
  {
      static int next_block_unit[IF_COUNT];
+    g_assert(qemu_in_main_thread());
 
      return drive_get(type, 0, next_block_unit[type]++);
  }

blockdev.c DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type, · line 809

Quoted 8 lines
blockdev.c +2 -0
@@ -792,6 +802,8 @@ DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type,
      const char *filename;
      int i;
 
+    g_assert(qemu_in_main_thread());
+
      /* Change legacy command line options into QMP ones */
      static const struct {
          const char *from;
Reviewed-by on v2 15/25
#47 lore raw

Re: [RFC PATCH v2 15/25] include/block/snapshot: global state API + assertions

In reply to Emanuele Giuseppe Esposito
Quoted 158 lines · Emanuele Giuseppe Esposito

Snapshots run also under the BQL lock, so they all are in the global state API. The aiocontext lock that they hold is currently an overkill and in future could be removed.

---
  block/snapshot.c         | 28 ++++++++++++++++++++++++++++
  include/block/snapshot.h | 21 +++++++++++++++++++++
  migration/savevm.c       |  2 ++
  3 files changed, 51 insertions(+)
block/snapshot.c +28 -0
index ccacda8bd5..e8756f7f90 100644
@@ -57,6 +57,8 @@ int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
      QEMUSnapshotInfo *sn_tab, *sn;
      int nb_sns, i, ret;
 
+    g_assert(qemu_in_main_thread());
+
      ret = -ENOENT;
      nb_sns = bdrv_snapshot_list(bs, &sn_tab);
      if (nb_sns < 0) {
@@ -105,6 +107,7 @@ bool bdrv_snapshot_find_by_id_and_name(BlockDriverState *bs,
      bool ret = false;
 
      assert(id || name);
+    g_assert(qemu_in_main_thread());
 
      nb_sns = bdrv_snapshot_list(bs, &sn_tab);
      if (nb_sns < 0) {
@@ -200,6 +203,7 @@ static BlockDriverState *bdrv_snapshot_fallback(BlockDriverState *bs)
  int bdrv_can_snapshot(BlockDriverState *bs)
  {
      BlockDriver *drv = bs->drv;
+    g_assert(qemu_in_main_thread());
      if (!drv || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
          return 0;
      }
@@ -220,6 +224,9 @@ int bdrv_snapshot_create(BlockDriverState *bs,
  {
      BlockDriver *drv = bs->drv;
      BlockDriverState *fallback_bs = bdrv_snapshot_fallback(bs);
+
+    g_assert(qemu_in_main_thread());
+
      if (!drv) {
          return -ENOMEDIUM;
      }
@@ -240,6 +247,8 @@ int bdrv_snapshot_goto(BlockDriverState *bs,
      BdrvChild **fallback_ptr;
      int ret, open_ret;
 
+    g_assert(qemu_in_main_thread());
+
      if (!drv) {
          error_setg(errp, "Block driver is closed");
          return -ENOMEDIUM;
@@ -348,6 +357,8 @@ int bdrv_snapshot_delete(BlockDriverState *bs,
      BlockDriverState *fallback_bs = bdrv_snapshot_fallback(bs);
      int ret;
 
+    g_assert(qemu_in_main_thread());
+
      if (!drv) {
          error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, bdrv_get_device_name(bs));
          return -ENOMEDIUM;
@@ -380,6 +391,8 @@ int bdrv_snapshot_list(BlockDriverState *bs,
  {
      BlockDriver *drv = bs->drv;
      BlockDriverState *fallback_bs = bdrv_snapshot_fallback(bs);
+
+    g_assert(qemu_in_main_thread());
      if (!drv) {
          return -ENOMEDIUM;
      }
@@ -419,6 +432,8 @@ int bdrv_snapshot_load_tmp(BlockDriverState *bs,
  {
      BlockDriver *drv = bs->drv;
 
+    g_assert(qemu_in_main_thread());
+
      if (!drv) {
          error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, bdrv_get_device_name(bs));
          return -ENOMEDIUM;
@@ -447,6 +462,8 @@ int bdrv_snapshot_load_tmp_by_id_or_name(BlockDriverState *bs,
      int ret;
      Error *local_err = NULL;
 
+    g_assert(qemu_in_main_thread());
+
      ret = bdrv_snapshot_load_tmp(bs, id_or_name, NULL, &local_err);
      if (ret == -ENOENT || ret == -EINVAL) {
          error_free(local_err);
@@ -515,6 +532,8 @@ bool bdrv_all_can_snapshot(bool has_devices, strList *devices,
      g_autoptr(GList) bdrvs = NULL;
      GList *iterbdrvs;
 
+    g_assert(qemu_in_main_thread());
+
      if (bdrv_all_get_snapshot_devices(has_devices, devices, &bdrvs, errp) < 0) {
          return false;
      }
@@ -549,6 +568,8 @@ int bdrv_all_delete_snapshot(const char *name,
      g_autoptr(GList) bdrvs = NULL;
      GList *iterbdrvs;
 
+    g_assert(qemu_in_main_thread());
+
      if (bdrv_all_get_snapshot_devices(has_devices, devices, &bdrvs, errp) < 0) {
          return -1;
      }
@@ -588,6 +609,8 @@ int bdrv_all_goto_snapshot(const char *name,
      g_autoptr(GList) bdrvs = NULL;
      GList *iterbdrvs;
 
+    g_assert(qemu_in_main_thread());
+
      if (bdrv_all_get_snapshot_devices(has_devices, devices, &bdrvs, errp) < 0) {
          return -1;
      }
@@ -622,6 +645,8 @@ int bdrv_all_has_snapshot(const char *name,
      g_autoptr(GList) bdrvs = NULL;
      GList *iterbdrvs;
 
+    g_assert(qemu_in_main_thread());
+
      if (bdrv_all_get_snapshot_devices(has_devices, devices, &bdrvs, errp) < 0) {
          return -1;
      }
@@ -663,6 +688,7 @@ int bdrv_all_create_snapshot(QEMUSnapshotInfo *sn,
  {
      g_autoptr(GList) bdrvs = NULL;
      GList *iterbdrvs;
+    g_assert(qemu_in_main_thread());
 
      if (bdrv_all_get_snapshot_devices(has_devices, devices, &bdrvs, errp) < 0) {
          return -1;
@@ -703,6 +729,8 @@ BlockDriverState *bdrv_all_find_vmstate_bs(const char *vmstate_bs,
      g_autoptr(GList) bdrvs = NULL;
      GList *iterbdrvs;
 
+    g_assert(qemu_in_main_thread());
+
      if (bdrv_all_get_snapshot_devices(has_devices, devices, &bdrvs, errp) < 0) {
          return NULL;
      }
include/block/snapshot.h +2 -0
index 940345692f..3a84849388 100644
@@ -45,6 +45,27 @@ typedef struct QEMUSnapshotInfo {
      uint64_t icount; /* record/replay step */
  } QEMUSnapshotInfo;
 
+/*
+ * Global state (GS) API. These functions run under the BQL lock.

include/block/snapshot.h typedef struct QEMUSnapshotInfo { · line 59

Quoted 10 lines
include/block/snapshot.h +10 -0
+ *
+ * If a function modifies the graph, it also uses drain and/or
+ * aio_context_acquire/release to be sure it has unique access.
+ * aio_context locking is needed together with BQL because of
+ * the thread-safe I/O API that concurrently runs and accesses
+ * the graph without the BQL.
+ *
+ * It is important to note that not all of these functions are
+ * necessarily limited to running under the BQL, but they would
+ * require additional auditing and may small thread-safety changes

Apart from the usual comment about s/may/many/,

Quoted 26 lines
include/block/snapshot.h +9 -0
+ * to move them into the I/O API. Often it's not worth doing that
+ * work since the APIs are only used with the BQL held at the
+ * moment, so they have been placed in the GS API (for now).
+ *
+ * All functions in this header must use this assertion:
+ * g_assert(qemu_in_main_thread());
+ * to catch when they are accidentally called without the BQL.
+ */
+
  int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
                         const char *name);
  bool bdrv_snapshot_find_by_id_and_name(BlockDriverState *bs,
migration/savevm.c +2 -0
index 7b7b64bd13..439f736ad5 100644
@@ -2785,6 +2785,8 @@ bool save_snapshot(const char *name, bool overwrite, const char *vmstate,
      g_autoptr(GDateTime) now = g_date_time_new_now_local();
      AioContext *aio_context;
 
+    g_assert(qemu_in_main_thread());
+
      if (migration_is_blocked(errp)) {
          return false;
      }
Reviewed-by on v2 16/25
#50 lore raw

Re: [RFC PATCH v2 16/25] block/backup-top.h: global state API + assertions

In reply to Emanuele Giuseppe Esposito
Quoted 41 lines · Emanuele Giuseppe Esposito

backup-top functions always run under BQL lock.

---
  block/backup-top.c |  2 ++
  block/backup-top.h | 11 +++++++++++
  2 files changed, 13 insertions(+)
block/backup-top.c +2 -0
index 425e3778be..8b58a909f7 100644
@@ -182,6 +182,7 @@ BlockDriverState *bdrv_backup_top_append(BlockDriverState *source,
      bool appended = false;
 
      assert(source->total_sectors == target->total_sectors);
+    g_assert(qemu_in_main_thread());
 
      top = bdrv_new_open_driver(&bdrv_backup_top_filter, filter_node_name,
                                 BDRV_O_RDWR, errp);
@@ -244,6 +245,7 @@ fail:
  void bdrv_backup_top_drop(BlockDriverState *bs)
  {
      BDRVBackupTopState *s = bs->opaque;
+    g_assert(qemu_in_main_thread());
 
      bdrv_drop_filter(bs, &error_abort);
 
block/backup-top.h +4 -0
index b28b0031c4..8cb6f62869 100644
@@ -29,6 +29,17 @@
  #include "block/block_int.h"
  #include "block/block-copy.h"
 
+/*
+ * Graph API. These functions run under the BQL lock.
+ *
+ * If a function modifies the graph, it uses drain and/or

block/backup-top.h line 45

Quoted 10 lines
block/backup-top.h +7 -0
+ * aio_context_acquire/release to be sure it has unique access.
+ *
+ * All functions in this header must use this assertion:
+ * g_assert(qemu_in_main_thread());
+ * to be sure they belong here.
+ */
+
  BlockDriverState *bdrv_backup_top_append(BlockDriverState *source,
                                           BlockDriverState *target,
                                           const char *filter_node_name,

This is now bdrv_cbw_append, but anyway:

#15 lore raw

Re: [RFC PATCH v2 04/25] include/block/block: split header into I/O and global state API

In reply to Daniel P. Berrangé
Quoted 20 lines · Daniel P. Berrangé
Quoted 6 lines · Emanuele Giuseppe Esposito

Similarly to the previous patch, split block.h
in block-io.h and block-global-state.h

block-common.h contains the structures shared between the two headers, and the functions that can't be categorized as I/O or global state.

This is nice from a code organization POV, but it doesn't do all that much from a code reviewer / author POV as I doubt anyone will remember which header file the respective APIs/structures/ constants are in, without having to look it up each time.

It would make life easier if we had distinct namning conventions for APIs/struct/contsants in the respective headers.

eg instead of "bdrv_" have "bdrv_state_" and "bdrv_io_" as the two naming conventions for -global-state.h and -io.h respectively, nad only use the bare 'bdrv_' for -common.h

Quoted 7 lines

Yes, this would be major code churn, but I think it'd make the code clearer to understand which will be a win over the long term.

NB, I'm not suggesting doing a rename as part of this patch though. Any rename would have to be separate, and likely split over many patches to make it manageable.

Yes. Taking it one step further, BlockDriverState could be split into two struct so that I/O code doesn't even have access to the struct needed to invoke GS APIs. This is a type-safe way of enforcing the API split.

Unfortunately that's a lot of code churn and I think the separation is not very clean. For example, block drivers need to forward requests to their children, so they need to traverse the graph (which we think of as global state).

Stefan

#13 lore raw

Re: [RFC PATCH v2 04/25] include/block/block: split header into I/O and global state API

In reply to Paolo Bonzini
Quoted 17 lines · Paolo Bonzini
Quoted 16 lines · Emanuele Giuseppe Esposito
Quoted 9 lines
Quoted 4 lines

+int bdrv_block_status(BlockDriverState *bs, int64_t offset, +                      int64_t bytes, int64_t *pnum, int64_t *map, +                      BlockDriverState **file);

This function just called bdrv_block_status_above(), which is in the I/O API. I think it's safe to move this to the I/O API or else bdrv_block_status_above() shouldn't be there :).

It *seems* that while bdrv_block_status_above() is an I/O, probably running in some coroutine (from here its internal qemu_in_coroutine check), bdrv_block_status might be called from the main loop (or alternatively the function is never invoked in the tests, so the assertion never triggered).

Quoted 6 lines
Quoted 2 lines

Maybe bdrv_block_status_above is one of the few functions that are both I/O and Main loop? I put it in I/O as it can't have the assertion.

No, they are both I/O. Callers of bdrv_block_status are hw/nvme and qemu-img.c; while the latter can be either (it does not have iothreads), hw/nvme is definitely I/O.

nbd/server.c also uses bdrv_block_status_above as part of its I/O path to serve NBD_CMD_BLOCK_STATUS.

Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3266
Virtualization:  qemu.org | libvirt.org
#22 lore raw

Re: [RFC PATCH v2 06/25] include/block/block_int: split header into I/O and global state API

In reply to Emanuele Giuseppe Esposito
Quoted 19 lines · Emanuele Giuseppe Esposito
Quoted 15 lines · Stefan Hajnoczi

include/block/block_int-global-state.h line 279

Quoted 10 lines · Emanuele Giuseppe Esposito
include/block/block_int-global-state.h new file +10 -0
+int coroutine_fn bdrv_co_copy_range_from(BdrvChild *src, int64_t src_offset,
+                                         BdrvChild *dst, int64_t dst_offset,
+                                         int64_t bytes,
+                                         BdrvRequestFlags read_flags,
+                                         BdrvRequestFlags write_flags);
+int coroutine_fn bdrv_co_copy_range_to(BdrvChild *src, int64_t src_offset,
+                                       BdrvChild *dst, int64_t dst_offset,
+                                       int64_t bytes,
+                                       BdrvRequestFlags read_flags,
+                                       BdrvRequestFlags write_flags);

These look like I/O APIs to me. Are they in the GS API because only qemu-img.c call copy_range? I thought SCSI emulation might call it too, but grep says otherwise.

Quoted 3 lines

SCSI (iscsi.c) implements the function pointer (*bdrv_co_copy_range_from/to), but does not call the function itself. However, later in the patches I put the function pointer as I/O.

I meant the SCSI target emulation in hw/scsi/ where the SCSI commands that require copy_range could be handled.

Quoted 3 lines

These two functions are only tested by test-replication and thus are always under BQL when tested. But after looking at them again, and since they internally use only I/O APIs, I think we can move them to the I/O API.

Okay, great.

Stefan

#28 lore raw

Re: [RFC PATCH v2 08/25] block: introduce assert_bdrv_graph_writable

In reply to Paolo Bonzini
Quoted 4 lines · Paolo Bonzini
Quoted 4 lines
block/io.c +0 -0
@@ -739,6 +739,11 @@ void bdrv_drain_all(void)
       bdrv_drain_all_end();
Quoted 9 lines

block/io.c void bdrv_drain_all(void) · line 745

Quoted 6 lines
block/io.c +4 -0
   }
+void assert_bdrv_graph_writable(BlockDriverState *bs)
+{
+    g_assert(qatomic_read(&bs->quiesce_counter) > 0 || 
 qemu_in_main_thread());
+}

Hmm, wait - I think this should be an "&&", not an OR?

You are right, && makes more sense. But as you said, using an AND will make the assertion fail in multiple places, because the necessary drains are missing. So I am going to remove the check for drains and leave it as todo. I will handle this case in another patch.

Thank you,
Emanuele

#29 lore raw

Re: [RFC PATCH v2 08/25] block: introduce assert_bdrv_graph_writable

Quoted 17 lines · Emanuele Giuseppe Esposito
Quoted 4 lines · Paolo Bonzini
Quoted 4 lines
block/io.c +0 -0
@@ -739,6 +739,11 @@ void bdrv_drain_all(void)
       bdrv_drain_all_end();
Quoted 9 lines

block/io.c void bdrv_drain_all(void) · line 745

Quoted 6 lines
block/io.c +4 -0
   }
+void assert_bdrv_graph_writable(BlockDriverState *bs)
+{
+    g_assert(qatomic_read(&bs->quiesce_counter) > 0 ||
 qemu_in_main_thread());
+}

Hmm, wait - I think this should be an "&&", not an OR?

Quoted 4 lines

You are right, && makes more sense. But as you said, using an AND will make the assertion fail in multiple places, because the necessary drains are missing. So I am going to remove the check for drains and leave it as todo. I will handle this case in another patch.

BTW when an assertion expression tests unrelated things it helps to use separate assert() calls instead of &&. That way it's obvious which sub-expression failed from the error message and it's not necessary to inspect the coredump.

In other words:

assert(a && b) -> Assertion a && b failed.

This doesn't tell me whether it was a or b that was false. The assertion failure is easier to diagnose if you split it:

assert(a); -> Assertion a failed.
assert(b); -> Assertion b failed.

Stefan

Reviewed-by on v2 7/25
#24 lore raw

Re: [RFC PATCH v2 07/25] assertions for block_int global state API

In reply to Emanuele Giuseppe Esposito
Quoted 13 lines · Emanuele Giuseppe Esposito
---
 block.c                         | 17 +++++++++++++++++
 block/backup.c                  |  1 +
 block/block-backend.c           |  3 +++
 block/commit.c                  |  2 ++
 block/dirty-bitmap.c            |  2 ++
 block/io.c                      |  6 ++++++
 block/mirror.c                  |  4 ++++
 block/monitor/bitmap-qmp-cmds.c |  6 ++++++
 block/stream.c                  |  2 ++
 blockdev.c                      |  7 +++++++
 10 files changed, 50 insertions(+)

Except copy_range:

Reviewed-by on v2 9/25
#31 lore raw

Re: [RFC PATCH v2 09/25] include/block/blockjob_int.h: split header into I/O and GS API

In reply to Emanuele Giuseppe Esposito
Quoted 7 lines · Emanuele Giuseppe Esposito

Since the I/O functions are not many, keep a single file. Also split the function pointers in BlockJobDriver.

---
 include/block/blockjob_int.h | 55 ++++++++++++++++++++++++++++++++++++
 1 file changed, 55 insertions(+)
#35 lore raw

Re: [RFC PATCH v2 11/25] include/block/blockjob.h: global state API

In reply to Emanuele Giuseppe Esposito
Quoted 25 lines · Emanuele Giuseppe Esposito

blockjob functions run always under the BQL lock.

---
 include/block/blockjob.h | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)
include/block/blockjob.h +10 -0
index d200f33c10..3bf384f8bf 100644
@@ -77,6 +77,27 @@ typedef struct BlockJob {
     GSList *nodes;
 } BlockJob;
 
+/*
+ * Global state (GS) API. These functions run under the BQL lock.
+ *
+ * If a function modifies the graph, it also uses drain and/or
+ * aio_context_acquire/release to be sure it has unique access.
+ * aio_context locking is needed together with BQL because of
+ * the thread-safe I/O API that concurrently runs and accesses
+ * the graph without the BQL.
+ *
+ * It is important to note that not all of these functions are

include/block/blockjob.h typedef struct BlockJob { · line 99

Quoted 10 lines
include/block/blockjob.h +10 -0
+ * necessarily limited to running under the BQL, but they would
+ * require additional auditing and may small thread-safety changes
+ * to move them into the I/O API. Often it's not worth doing that
+ * work since the APIs are only used with the BQL held at the
+ * moment, so they have been placed in the GS API (for now).
+ *
+ * All functions below must use this assertion:
+ * g_assert(qemu_in_main_thread());
+ * to catch when they are accidentally called without the BQL.
+ */

This is comment is duplicated in many places. I suggest explaining it in one place and using references in the other files:

/*
* Global state (GS) API. These functions run under the BQL lock. *
* See include/block/block.h for more information about the GS API. */

Reviewed-by on v2 13/25
#42 lore raw

Re: [RFC PATCH v2 13/25] include/systemu/blockdev.h: global state API

In reply to Emanuele Giuseppe Esposito
Quoted 34 lines · Emanuele Giuseppe Esposito

blockdev functions run always under the BQL lock.

---
 include/sysemu/blockdev.h | 35 ++++++++++++++++++++++++++++++-----
 1 file changed, 30 insertions(+), 5 deletions(-)
include/sysemu/blockdev.h +18 -1
index 32c2d6023c..28233f6b63 100644
@@ -38,24 +38,49 @@ struct DriveInfo {
     QTAILQ_ENTRY(DriveInfo) next;
 };
 
-DriveInfo *blk_legacy_dinfo(BlockBackend *blk);
+/*
+ * Global state (GS) API. These functions run under the BQL lock.
+ *
+ * If a function modifies the graph, it also uses drain and/or
+ * aio_context_acquire/release to be sure it has unique access.
+ * aio_context locking is needed together with BQL because of
+ * the thread-safe I/O API that concurrently runs and accesses
+ * the graph without the BQL.
+ *
+ * It is important to note that not all of these functions are
+ * necessarily limited to running under the BQL, but they would
+ * require additional auditing and may small thread-safety changes
+ * to move them into the I/O API. Often it's not worth doing that
+ * work since the APIs are only used with the BQL held at the
+ * moment, so they have been placed in the GS API (for now).
+ *
+ * All functions in this header must use this assertion:
+ * g_assert(qemu_in_main_thread());

include/sysemu/blockdev.h struct DriveInfo { · line 48

Quoted 10 lines
include/sysemu/blockdev.h +3 -1
+ * to catch when they are accidentally called without the BQL.
+ */
+
 DriveInfo *blk_set_legacy_dinfo(BlockBackend *blk, DriveInfo *dinfo);
 BlockBackend *blk_by_legacy_dinfo(DriveInfo *dinfo);
 
 void override_max_devs(BlockInterfaceType type, int max_devs);
 
 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit);
-void drive_mark_claimed_by_board(void);

This function prototype is no longer used. Please make a note of this in the commit description so reviewers know the deletion is intentional and the reason for it. (It could have been an accident so I had to grep the code to figure out why you did this.)

Otherwise:

Reviewed-by on v2 15/25
#48 lore raw

Re: [RFC PATCH v2 15/25] include/block/snapshot: global state API + assertions

In reply to Emanuele Giuseppe Esposito
Quoted 10 lines · Emanuele Giuseppe Esposito

Snapshots run also under the BQL lock, so they all are in the global state API. The aiocontext lock that they hold is currently an overkill and in future could be removed.

---
 block/snapshot.c         | 28 ++++++++++++++++++++++++++++
 include/block/snapshot.h | 21 +++++++++++++++++++++
 migration/savevm.c       |  2 ++
 3 files changed, 51 insertions(+)
#53 lore raw

Re: [RFC PATCH v2 17/25] include/block/transactions: global state API + assertions

In reply to Emanuele Giuseppe Esposito
Quoted 8 lines · Emanuele Giuseppe Esposito

transactions run always under the BQL lock, so they are all in the global state API.

---
 include/qemu/transactions.h | 24 ++++++++++++++++++++++++
 util/transactions.c         |  4 ++++
 2 files changed, 28 insertions(+)

Hmm...not sure about this. Maybe Vladimir can share his thoughts.

This seems like a library that can be used in various situations. It has no connection to the BQL. There's no need to declare it GS or I/O because it's just a utility just like QEMUIOVector, etc.

Reviewed-by on v2 19/25
#59 lore raw

Re: [RFC PATCH v2 19/25] block_int-common.h: split function pointers in BlockDriver

In reply to Emanuele Giuseppe Esposito
Quoted 7 lines · Emanuele Giuseppe Esposito

Similar to the header split, also the function pointers in BlockDriver can be split in I/O and global state.

---
 include/block/block_int-common.h | 472 ++++++++++++++++---------------
 1 file changed, 251 insertions(+), 221 deletions(-)
Reviewed-by on v2 24/25
#69 lore raw

Re: [RFC PATCH v2 24/25] job.h: split function pointers in JobDriver

In reply to Emanuele Giuseppe Esposito
Quoted 19 lines · Emanuele Giuseppe Esposito

The job API will be handled separately in another serie.

---
 include/qemu/job.h | 31 +++++++++++++++++++++++++++++++
 1 file changed, 31 insertions(+)
include/qemu/job.h +3 -0
index 41162ed494..c236c43026 100644
@@ -169,12 +169,21 @@ typedef struct Job {
  * Callbacks and other information about a Job driver.
  */
 struct JobDriver {
+
+    /* Fields initialized in struct definition and never changed. */
+
     /** Derived Job struct size */

include/qemu/job.h typedef struct Job { · line 185

Quoted 10 lines
include/qemu/job.h +5 -0
     size_t instance_size;
 
     /** Enum describing the operation */
     JobType job_type;
 
+    /*
+     * I/O API functions. These functions are thread-safe, and therefore
+     * can run in any thread as long as they have called
+     * aio_context_acquire/release().
+     */

This comment described the block layer well but job.h is more generic. I don't think these functions are necessarily thread-safe (they shouldn't be invoked from multiple threads at the same time). It's just that they are run without regard to the BQL and may run in an arbitrary thread.

Other than that:

Reviewed-by on v2 23/25
#67 lore raw

Re: [RFC PATCH v2 23/25] block-backend-common.h: split function pointers in BlockDevOps

In reply to Emanuele Giuseppe Esposito
Quoted 7 lines · Emanuele Giuseppe Esposito

Assertions in the callers of the funciton pointrs are already added by previous patches.

---
 include/sysemu/block-backend-common.h | 42 +++++++++++++++++++++++----
 1 file changed, 37 insertions(+), 5 deletions(-)
#54 lore raw

Re: [RFC PATCH v2 17/25] include/block/transactions: global state API + assertions

In reply to Stefan Hajnoczi
Quoted 10 lines · Stefan Hajnoczi
Quoted 8 lines · Emanuele Giuseppe Esposito

transactions run always under the BQL lock, so they are all in the global state API.

---
  include/qemu/transactions.h | 24 ++++++++++++++++++++++++
  util/transactions.c         |  4 ++++
  2 files changed, 28 insertions(+)
Quoted 6 lines

Hmm...not sure about this. Maybe Vladimir can share his thoughts.

This seems like a library that can be used in various situations. It has no connection to the BQL. There's no need to declare it GS or I/O because it's just a utility just like QEMUIOVector, etc.

Ok, I can remove this patch for next version, and then we can discuss whether to add it or not.

Thank you,
Emanuele

#36 lore raw

Re: [RFC PATCH v2 11/25] include/block/blockjob.h: global state API

In reply to Stefan Hajnoczi
Quoted 22 lines
Quoted 13 lines

+/*
+ * Global state (GS) API. These functions run under the BQL lock.
+ *
+ * If a function modifies the graph, it also uses drain and/or
+ * aio_context_acquire/release to be sure it has unique access.
+ * aio_context locking is needed together with BQL because of
+ * the thread-safe I/O API that concurrently runs and accesses
+ * the graph without the BQL.
+ *
+ * It is important to note that not all of these functions are
+ * necessarily limited to running under the BQL, but they would
+ * require additional auditing and may small thread-safety changes

Quoted 8 lines

+ * to move them into the I/O API. Often it's not worth doing that
+ * work since the APIs are only used with the BQL held at the
+ * moment, so they have been placed in the GS API (for now).
+ *
+ * All functions below must use this assertion:
+ * g_assert(qemu_in_main_thread());
+ * to catch when they are accidentally called without the BQL.
+ */

Quoted 9 lines

This is comment is duplicated in many places. I suggest explaining it in one place and using references in the other files:

   /*
    * Global state (GS) API. These functions run under the BQL lock.
    *
    * See include/block/block.h for more information about the GS API.
    */

Good idea. Should I also do that for I/O, or it's not worth for very few lines?

Thank you,
Emanuele

#16 lore raw

Re: [RFC PATCH v2 04/25] include/block/block: split header into I/O and global state API

In reply to Stefan Hajnoczi
Quoted 5 lines · Stefan Hajnoczi
Quoted 4 lines · Daniel P. Berrangé
Quoted 3 lines · Emanuele Giuseppe Esposito

Similarly to the previous patch, split block.h
in block-io.h and block-global-state.h

Quoted 8 lines
Quoted 8 lines
Quoted 3 lines

block-common.h contains the structures shared between the two headers, and the functions that can't be categorized as I/O or global state.

This is nice from a code organization POV, but it doesn't do all that much from a code reviewer / author POV as I doubt anyone will remember which header file the respective APIs/structures/ constants are in, without having to look it up each time.

Another thing to consider is with regards the function pointers API split I do in patches 19-25. There we don't even have a file separation, so if someone misses the head comment separating I/O from GS, a new function can end up under the wrong API.

Maybe as Stefan suggests below we can at least split the function pointers in two separate structs, with bdrv_state_* and bdrv_io_* struct naming conventions.

But anyways thank you for the suggestions, I will add them to my TODO list.

Emanuele

Quoted 28 lines
Quoted 8 lines

It would make life easier if we had distinct namning conventions for APIs/struct/contsants in the respective headers.

eg instead of "bdrv_" have "bdrv_state_" and "bdrv_io_" as the two naming conventions for -global-state.h and -io.h respectively, nad only use the bare 'bdrv_' for -common.h

Quoted 7 lines

Yes, this would be major code churn, but I think it'd make the code clearer to understand which will be a win over the long term.

NB, I'm not suggesting doing a rename as part of this patch though. Any rename would have to be separate, and likely split over many patches to make it manageable.

Yes. Taking it one step further, BlockDriverState could be split into two struct so that I/O code doesn't even have access to the struct needed to invoke GS APIs. This is a type-safe way of enforcing the API split.

Unfortunately that's a lot of code churn and I think the separation is not very clean. For example, block drivers need to forward requests to their children, so they need to traverse the graph (which we think of as global state).

Stefan

#70 lore raw

Re: [RFC PATCH v2 24/25] job.h: split function pointers in JobDriver

In reply to Stefan Hajnoczi
Quoted 25 lines · Stefan Hajnoczi
Quoted 24 lines · Emanuele Giuseppe Esposito

The job API will be handled separately in another serie.

---
  include/qemu/job.h | 31 +++++++++++++++++++++++++++++++
  1 file changed, 31 insertions(+)
include/qemu/job.h +3 -0
index 41162ed494..c236c43026 100644
@@ -169,12 +169,21 @@ typedef struct Job {
   * Callbacks and other information about a Job driver.
   */
  struct JobDriver {
+
+    /* Fields initialized in struct definition and never changed. */
+
      /** Derived Job struct size */
      size_t instance_size;
 
      /** Enum describing the operation */
      JobType job_type;
 
Quoted 10 lines

include/qemu/job.h typedef struct Job { · line 185

Quoted 5 lines
include/qemu/job.h +5 -0
+    /*
+     * I/O API functions. These functions are thread-safe, and therefore
+     * can run in any thread as long as they have called
+     * aio_context_acquire/release().
+     */

This comment described the block layer well but job.h is more generic. I don't think these functions are necessarily thread-safe (they shouldn't be invoked from multiple threads at the same time). It's just that they are run without regard to the BQL and may run in an arbitrary thread.

Ok, in this instance I will change it to:

/*
* Functions run without regard to the BQL and may run in any
* arbitrary thread.
*/

Thank you,
Emanuele

Quoted 5 lines

Other than that:

#37 lore raw

Re: [RFC PATCH v2 11/25] include/block/blockjob.h: global state API

In reply to Emanuele Giuseppe Esposito
Quoted 32 lines · Emanuele Giuseppe Esposito
Quoted 22 lines
Quoted 13 lines

+/*
+ * Global state (GS) API. These functions run under the BQL lock.
+ *
+ * If a function modifies the graph, it also uses drain and/or
+ * aio_context_acquire/release to be sure it has unique access.
+ * aio_context locking is needed together with BQL because of
+ * the thread-safe I/O API that concurrently runs and accesses
+ * the graph without the BQL.
+ *
+ * It is important to note that not all of these functions are
+ * necessarily limited to running under the BQL, but they would
+ * require additional auditing and may small thread-safety changes

Quoted 8 lines

+ * to move them into the I/O API. Often it's not worth doing that
+ * work since the APIs are only used with the BQL held at the
+ * moment, so they have been placed in the GS API (for now).
+ *
+ * All functions below must use this assertion:
+ * g_assert(qemu_in_main_thread());
+ * to catch when they are accidentally called without the BQL.
+ */

Quoted 9 lines

This is comment is duplicated in many places. I suggest explaining it in one place and using references in the other files:

   /*
    * Global state (GS) API. These functions run under the BQL lock.
    *
    * See include/block/block.h for more information about the GS API.
    */
Quoted 2 lines

Good idea. Should I also do that for I/O, or it's not worth for very few lines?

Up to you, but I think it makes sense to have a minimal comment for both the GS and I/O API.

Stefan

#71 lore raw

Re: [RFC PATCH v2 24/25] job.h: split function pointers in JobDriver

In reply to Emanuele Giuseppe Esposito
Quoted 37 lines · Emanuele Giuseppe Esposito
Quoted 25 lines · Stefan Hajnoczi
Quoted 24 lines · Emanuele Giuseppe Esposito

The job API will be handled separately in another serie.

---
  include/qemu/job.h | 31 +++++++++++++++++++++++++++++++
  1 file changed, 31 insertions(+)
include/qemu/job.h +5 -0
index 41162ed494..c236c43026 100644
@@ -169,12 +169,21 @@ typedef struct Job {
   * Callbacks and other information about a Job driver.
   */
  struct JobDriver {
+
+    /* Fields initialized in struct definition and never changed. */
+
      /** Derived Job struct size */
      size_t instance_size;
      /** Enum describing the operation */
      JobType job_type;
+    /*
+     * I/O API functions. These functions are thread-safe, and therefore
Quoted 8 lines

include/qemu/job.h typedef struct Job { · line 185

Quoted 3 lines
include/qemu/job.h +3 -0
+     * can run in any thread as long as they have called
+     * aio_context_acquire/release().
+     */

This comment described the block layer well but job.h is more generic. I don't think these functions are necessarily thread-safe (they shouldn't be invoked from multiple threads at the same time). It's just that they are run without regard to the BQL and may run in an arbitrary thread.

Quoted 6 lines

Ok, in this instance I will change it to:

/*
* Functions run without regard to the BQL and may run in any
* arbitrary thread.
*/

It's not clear from that comment whether the functions need to be thread-safe (re-entrancy safe) or not. I think the answer is "no" since the caller ensures they are called from one thread at a time.

Stefan