Skip to contentSkip to conversation

job: replace AioContext lock with job_mutex

PATCH Superseded Emanuele Giuseppe Esposito 3 participants 59 messages Jun 29, 2022 – Jul 6, 2022 Block layer

v8 of 12 Superseded Latest is v12 →

lore
Share & tools
lore
#0 lore raw

v8 cover job: replace AioContext lock with job_mutex

In this series, we want to remove the AioContext lock and instead use the already existent job_mutex to protect the job structures and list. This is part of the work to get rid of AioContext lock usage in favour of smaller granularity locks.

In order to simplify reviewer's job, job lock/unlock functions and macros are added as empty prototypes (nop) in patch 1. They are converted to use the actual job mutex only in the last patch. In this way we can freely create locking sections without worrying about deadlocks with the aiocontext lock.

Patch 2 defines what fields in the job structure need protection. Patches 3-6 are in preparation to the job locks, moving functions from global to static and introducing helpers.

Patch 7-9 introduce the (nop) job lock into the job API and its users, and patches 10-13 categorize respectively locked and unlocked functions in the job API.

Patches 14-17 take care of protecting job->aio_context, and finally patch 18 makes the prototypes in patch 1 use the job_mutex and removes all aiocontext lock at the same time.

Tested this series by running unit tests, qemu-iotests and qtests (x86_64).

---
v8:
* reorganize patch ordering according with Vladimir proposal
* minor nitpicks

v7:
* s/temporary/temporarly
* double identical locking comment to the same function
* patch 2: add "Protected by AioContext lock" to better categorize fields in job.h
* use same comment style in all function headers ("Just like {funct}, but called between job_lock and job_unlock")

v6:
* patch 4 and 6 squashed with patch 19 (enable job lock and reduce/remove AioContext lock)
* patch 19: job_unref_locked read the aiocontext inside the job lock.

v5:
* just restructured patches a little bit better, as there were functions used before they were defined.
* rebased on kwolf/block branch and API split serie

v4:
* move "protected by job_mutex" from patch 2 to 15, where the job_mutex is actually added.
* s/aio_co_enter/aio_co_schedule in job.c, and adjust tests accordingly.
* remove job_get_aio_context, add job_set_aio_context. Use "fake rwlock" to protect job->aiocontext.
* get rid of useless getters method, namely:
job_get_status
job_get_pause_count
job_get_paused
job_get_busy
They are all used only by tests, and such getter is pretty useless. Replace with job_lock(); assert(); job_unlock();
* use job lock macros instead of job lock/unlock in unit tests.
* convert also blockjob functions to have _locked
* put the job_lock/unlock patches before the _locked ones
* replace aio_co_enter in job.c and detect change of context

v3:
* add "_locked" suffix to the functions called under job_mutex lock
* rename _job_lock in real_job_lock
* job_mutex is now public, and drivers like monitor use it directly
* introduce and protect job_get_aio_context
* remove mirror-specific APIs and just use WITH_JOB_GUARD
* more extensive use of WITH_JOB_GUARD and JOB_LOCK_GUARD

RFC v2:
* use JOB_LOCK_GUARD and WITH_JOB_LOCK_GUARD
* mu(u)ltiple typos in commit messages
* job API split patches are sent separately in another series
* use of empty job_{lock/unlock} and JOB_LOCK_GUARD/WITH_JOB_LOCK_GUARD to avoid deadlocks and simplify the reviewer job
* move patch 11 (block_job_query: remove atomic read) as last

Emanuele Giuseppe Esposito (19):
job.c: make job_mutex and job_lock/unlock() public job.h: categorize fields in struct Job
job.c: API functions not used outside should be static aio-wait.h: introduce AIO_WAIT_WHILE_UNLOCKED
job.c: add job_lock/unlock while keeping job.h intact job.h: define functions called without job lock held job.h: add _locked public functions
blockjob.h: introduce block_job _locked() APIs
blockjob: rename notifier callbacks as _locked
jobs: add job lock in find_* functions
jobs: use job locks also in the unit tests block/mirror.c: use of job helpers in drivers to avoid TOC/TOU
jobs: group together API calls under the same job lock commit and mirror: create new nodes using bdrv_get_aio_context, and
not the job aiocontext
jobs: protect job.aio_context with BQL and job_mutex job.c: enable job lock/unlock and remove Aiocontext locks
block_job_query: remove atomic read
blockjob: remove unused functions
job: remove unused functions

Paolo Bonzini (1):
job: detect change of aiocontext within job coroutine

 block.c                          |  20 +-
 block/commit.c                   |   4 +-
 block/mirror.c                   |  21 +-
 block/replication.c              |   6 +-
 blockdev.c                       | 129 +++---
 blockjob.c                       | 126 +++---
 include/block/aio-wait.h         |  17 +-
 include/block/blockjob.h         |  28 +-
 include/qemu/job.h               | 268 +++++++++----
 job-qmp.c                        |  87 ++--
 job.c                            | 654 +++++++++++++++++++------------
 monitor/qmp-cmds.c               |   7 +-
 qemu-img.c                       |  41 +-
 tests/unit/test-bdrv-drain.c     |  80 ++--
 tests/unit/test-block-iothread.c |   8 +-
 tests/unit/test-blockjob-txn.c   |  24 +-
 tests/unit/test-blockjob.c       | 107 +++--
 17 files changed, 999 insertions(+), 628 deletions(-)
Signature · 1 line
2.31.1
#1 lore raw

PATCH v8 1/20 job.c: make job_mutex and job_lock/unlock() public

job mutex will be used to protect the job struct elements and list, replacing AioContext locks.

Right now use a shared lock for all jobs, in order to keep things simple. Once the AioContext lock is gone, we can introduce per-job locks.

To simplify the switch from aiocontext to job lock, introduce *nop* lock/unlock functions and macros.
We want to always call job_lock/unlock outside the AioContext locks, and not vice-versa, otherwise we might get a deadlock. This is not straightforward to do, and that's why we start with nop functions. Once everything is protected by job_lock/unlock, we can change the nop into an actual mutex and remove the aiocontext lock.

Since job_mutex is already being used, add static
real_job_{lock/unlock} for the existing usage.

---
 include/qemu/job.h | 24 ++++++++++++++++++++++++
 job.c              | 35 +++++++++++++++++++++++------------
 2 files changed, 47 insertions(+), 12 deletions(-)
include/qemu/job.h +24 -0
index c105b31076..d1192ffd61 100644
@@ -303,6 +303,30 @@ typedef enum JobCreateFlags {
     JOB_MANUAL_DISMISS = 0x04,
 } JobCreateFlags;
 
+extern QemuMutex job_mutex;
+
+#define JOB_LOCK_GUARD() /* QEMU_LOCK_GUARD(&job_mutex) */
+
+#define WITH_JOB_LOCK_GUARD() /* WITH_QEMU_LOCK_GUARD(&job_mutex) */
+
+/**
+ * job_lock:
+ *
+ * Take the mutex protecting the list of jobs and their status.
+ * Most functions called by the monitor need to call job_lock
+ * and job_unlock manually.  On the other hand, function called
+ * by the block jobs themselves and by the block layer will take the
+ * lock for you.
+ */
+void job_lock(void);
+
+/**
+ * job_unlock:
+ *
+ * Release the mutex protecting the list of jobs and their status.
+ */
+void job_unlock(void);
+
 /**
  * Allocate and return a new job transaction. Jobs can be added to the
  * transaction using job_txn_add_job().
job.c +23 -12
index 075c6f3a20..2b4ffca9d4 100644
@@ -32,6 +32,12 @@
 #include "trace/trace-root.h"
 #include "qapi/qapi-events-job.h"
 
+/*
+ * job_mutex protects the jobs list, but also makes the
+ * struct job fields thread-safe.
+ */
+QemuMutex job_mutex;
+
 static QLIST_HEAD(, Job) jobs = QLIST_HEAD_INITIALIZER(jobs);
 
 /* Job State Transition Table */
@@ -74,17 +80,22 @@ struct JobTxn {
     int refcnt;
 };
 
-/* Right now, this mutex is only needed to synchronize accesses to job->busy
- * and job->sleep_timer, such as concurrent calls to job_do_yield and
- * job_enter. */
-static QemuMutex job_mutex;
+void job_lock(void)
+{
+    /* nop */
+}
+
+void job_unlock(void)
+{
+    /* nop */
+}
 
-static void job_lock(void)
+static void real_job_lock(void)
 {
     qemu_mutex_lock(&job_mutex);
 }
 
-static void job_unlock(void)
+static void real_job_unlock(void)
 {
     qemu_mutex_unlock(&job_mutex);
 }
@@ -450,21 +461,21 @@ void job_enter_cond(Job *job, bool(*fn)(Job *job))
         return;
     }
 
-    job_lock();
+    real_job_lock();
     if (job->busy) {
-        job_unlock();
+        real_job_unlock();
         return;
     }
 
     if (fn && !fn(job)) {
-        job_unlock();
+        real_job_unlock();
         return;
     }
 
     assert(!job->deferred_to_main_loop);
     timer_del(&job->sleep_timer);
     job->busy = true;
-    job_unlock();
+    real_job_unlock();
     aio_co_enter(job->aio_context, job->co);
 }
 
@@ -481,13 +492,13 @@ void job_enter(Job *job)
  * called explicitly. */
 static void coroutine_fn job_do_yield(Job *job, uint64_t ns)
 {
-    job_lock();
+    real_job_lock();
     if (ns != -1) {
         timer_mod(&job->sleep_timer, ns);
     }
     job->busy = false;
     job_event_idle(job);
-    job_unlock();
+    real_job_unlock();
     qemu_coroutine_yield();
 
     /* Set by job_enter_cond() before re-entering the coroutine.  */
Signature · 1 line
2.31.1
#2 lore raw

PATCH v8 2/20 job.h: categorize fields in struct Job

In reply to Emanuele Giuseppe Esposito

Categorize the fields in struct Job to understand which ones need to be protected by the job mutex and which don't.

---
 include/qemu/job.h | 61 +++++++++++++++++++++++++++-------------------
 1 file changed, 36 insertions(+), 25 deletions(-)
include/qemu/job.h +36 -25
index d1192ffd61..876e13d549 100644
@@ -40,27 +40,52 @@ typedef struct JobTxn JobTxn;
  * Long-running operation.
  */
 typedef struct Job {
+
+    /* Fields set at initialization (job_create), and never modified */
+
     /** The ID of the job. May be NULL for internal jobs. */
     char *id;
 
-    /** The type of this job. */
+    /**
+     * The type of this job.
+     * All callbacks are called with job_mutex *not* held.
+     */
     const JobDriver *driver;
 
-    /** Reference count of the block job */
-    int refcnt;
-
-    /** Current state; See @JobStatus for details. */
-    JobStatus status;
-
-    /** AioContext to run the job coroutine in */
-    AioContext *aio_context;
-
     /**
      * The coroutine that executes the job.  If not NULL, it is reentered when
      * busy is false and the job is cancelled.
+     * Initialized in job_start()
      */
     Coroutine *co;
 
+    /** True if this job should automatically finalize itself */
+    bool auto_finalize;
+
+    /** True if this job should automatically dismiss itself */
+    bool auto_dismiss;
+
+    /** The completion function that will be called when the job completes.  */
+    BlockCompletionFunc *cb;
+
+    /** The opaque value that is passed to the completion function.  */
+    void *opaque;
+
+    /* ProgressMeter API is thread-safe */
+    ProgressMeter progress;
+
+
+    /** Protected by AioContext lock */
+
+    /** AioContext to run the job coroutine in */
+    AioContext *aio_context;
+
+    /** Reference count of the block job */
+    int refcnt;
+
+    /** Current state; See @JobStatus for details. */
+    JobStatus status;
+
     /**
      * Timer that is used by @job_sleep_ns. Accessed under job_mutex (in
      * job.c).
@@ -112,14 +137,6 @@ typedef struct Job {
     /** Set to true when the job has deferred work to the main loop. */
     bool deferred_to_main_loop;
 
-    /** True if this job should automatically finalize itself */
-    bool auto_finalize;
-
-    /** True if this job should automatically dismiss itself */
-    bool auto_dismiss;
-
-    ProgressMeter progress;
-
     /**
      * Return code from @run and/or @prepare callback(s).
      * Not final until the job has reached the CONCLUDED status.
@@ -134,12 +151,6 @@ typedef struct Job {
      */
     Error *err;
 
-    /** The completion function that will be called when the job completes.  */
-    BlockCompletionFunc *cb;
-
-    /** The opaque value that is passed to the completion function.  */
-    void *opaque;
-
     /** Notifiers called when a cancelled job is finalised */
     NotifierList on_finalize_cancelled;
 
@@ -167,6 +178,7 @@ typedef struct Job {
 
 /**
  * Callbacks and other information about a Job driver.
+ * All callbacks are invoked with job_mutex *not* held.
  */
 struct JobDriver {
 
@@ -472,7 +484,6 @@ void job_yield(Job *job);
  */
 void coroutine_fn job_sleep_ns(Job *job, int64_t ns);
 
-
 /** Returns the JobType of a given Job. */
 JobType job_type(const Job *job);
 
Signature · 1 line
2.31.1
Reviewed-by on v8 2/20
#3 lore raw

Re: [PATCH v8 02/20] job.h: categorize fields in struct Job

Quoted 8 lines · Emanuele Giuseppe Esposito

Categorize the fields in struct Job to understand which ones need to be protected by the job mutex and which don't.

---
 include/qemu/job.h | 61 +++++++++++++++++++++++++++-------------------
 1 file changed, 36 insertions(+), 25 deletions(-)
#4 lore raw

PATCH v8 3/20 job.c: API functions not used outside should be static

In reply to Emanuele Giuseppe Esposito

job_event_* functions can all be static, as they are not used outside job.c.

Same applies for job_txn_add_job().

---
 include/qemu/job.h | 18 ------------------
 job.c              | 22 +++++++++++++++++++---
 2 files changed, 19 insertions(+), 21 deletions(-)
include/qemu/job.h +0 -18
index 876e13d549..4b64eb15f7 100644
@@ -358,18 +358,6 @@ JobTxn *job_txn_new(void);
  */
 void job_txn_unref(JobTxn *txn);
 
-/**
- * @txn: The transaction (may be NULL)
- * @job: Job to add to the transaction
- *
- * Add @job to the transaction.  The @job must not already be in a transaction.
- * The caller must call either job_txn_unref() or job_completed() to release
- * the reference that is automatically grabbed here.
- *
- * If @txn is NULL, the function does nothing.
- */
-void job_txn_add_job(JobTxn *txn, Job *job);
-
 /**
  * Create a new long-running job and return it.
  *
@@ -431,12 +419,6 @@ void job_progress_set_remaining(Job *job, uint64_t remaining);
  */
 void job_progress_increase_remaining(Job *job, uint64_t delta);
 
-/** To be called when a cancelled job is finalised. */
-void job_event_cancelled(Job *job);
-
-/** To be called when a successfully completed job is finalised. */
-void job_event_completed(Job *job);
-
 /**
  * Conditionally enter the job coroutine if the job is ready to run, not
  * already busy and fn() returns true. fn() is called while under the job_lock
job.c +19 -3
index 2b4ffca9d4..cafd597ba4 100644
@@ -125,7 +125,17 @@ void job_txn_unref(JobTxn *txn)
     }
 }
 
-void job_txn_add_job(JobTxn *txn, Job *job)
+/**
+ * @txn: The transaction (may be NULL)
+ * @job: Job to add to the transaction
+ *
+ * Add @job to the transaction.  The @job must not already be in a transaction.
+ * The caller must call either job_txn_unref() or job_completed() to release
+ * the reference that is automatically grabbed here.
+ *
+ * If @txn is NULL, the function does nothing.
+ */
+static void job_txn_add_job(JobTxn *txn, Job *job)
 {
     if (!txn) {
         return;
@@ -427,12 +437,18 @@ void job_progress_increase_remaining(Job *job, uint64_t delta)
     progress_increase_remaining(&job->progress, delta);
 }
 
-void job_event_cancelled(Job *job)
+/**
+ * To be called when a cancelled job is finalised.
+ */
+static void job_event_cancelled(Job *job)
 {
     notifier_list_notify(&job->on_finalize_cancelled, job);
 }
 
-void job_event_completed(Job *job)
+/**
+ * To be called when a successfully completed job is finalised.
+ */
+static void job_event_completed(Job *job)
 {
     notifier_list_notify(&job->on_finalize_completed, job);
 }
Signature · 1 line
2.31.1
#5 lore raw

PATCH v8 4/20 aio-wait.h: introduce AIO_WAIT_WHILE_UNLOCKED

In reply to Emanuele Giuseppe Esposito

Same as AIO_WAIT_WHILE macro, but if we are in the Main loop do not release and then acquire ctx_ 's aiocontext.

Once all Aiocontext locks go away, this macro will replace AIO_WAIT_WHILE.

---
 include/block/aio-wait.h | 17 +++++++++++++----
 1 file changed, 13 insertions(+), 4 deletions(-)
include/block/aio-wait.h +13 -4
index 54840f8622..a61f82c617 100644
@@ -59,10 +59,13 @@ typedef struct {
 extern AioWait global_aio_wait;
 
 /**
- * AIO_WAIT_WHILE:
+ * _AIO_WAIT_WHILE:
  * @ctx: the aio context, or NULL if multiple aio contexts (for which the
  *       caller does not hold a lock) are involved in the polling condition.
  * @cond: wait while this conditional expression is true
+ * @unlock: whether to unlock and then lock again @ctx. This apples
+ * only when waiting for another AioContext from the main loop.
+ * Otherwise it's ignored.
  *
  * Wait while a condition is true.  Use this to implement synchronous
  * operations that require event loop activity.
@@ -75,7 +78,7 @@ extern AioWait global_aio_wait;
  * wait on conditions between two IOThreads since that could lead to deadlock,
  * go via the main loop instead.
  */
-#define AIO_WAIT_WHILE(ctx, cond) ({                               \
+#define _AIO_WAIT_WHILE(ctx, cond, unlock) ({                      \
     bool waited_ = false;                                          \
     AioWait *wait_ = &global_aio_wait;                             \
     AioContext *ctx_ = (ctx);                                      \
@@ -92,11 +95,11 @@ extern AioWait global_aio_wait;
         assert(qemu_get_current_aio_context() ==                   \
                qemu_get_aio_context());                            \
         while ((cond)) {                                           \
-            if (ctx_) {                                            \
+            if (unlock && ctx_) {                                  \
                 aio_context_release(ctx_);                         \
             }                                                      \
             aio_poll(qemu_get_aio_context(), true);                \
-            if (ctx_) {                                            \
+            if (unlock && ctx_) {                                  \
                 aio_context_acquire(ctx_);                         \
             }                                                      \
             waited_ = true;                                        \
@@ -105,6 +108,12 @@ extern AioWait global_aio_wait;
     qatomic_dec(&wait_->num_waiters);                              \
     waited_; })
 
+#define AIO_WAIT_WHILE(ctx, cond)                                  \
+    _AIO_WAIT_WHILE(ctx, cond, true)
+
+#define AIO_WAIT_WHILE_UNLOCKED(ctx, cond)                         \
+    _AIO_WAIT_WHILE(ctx, cond, false)
+
 /**
  * aio_wait_kick:
  * Wake up the main thread if it is waiting on AIO_WAIT_WHILE().  During
Signature · 1 line
2.31.1
#6 lore raw

PATCH v8 5/20 job.c: add job_lock/unlock while keeping job.h intact

In reply to Emanuele Giuseppe Esposito

With "intact" we mean that all job.h functions implicitly take the lock. Therefore API callers are unmodified.

This means that:
- all static functions become _locked, and call _locked functions
- all public functions take the lock internally, and call _locked functions
- all public functions called internally by other functions in job.c will have a _locked counterpart, to avoid deadlocks (job lock already taken)
- public functions called only from exernal files (not job.c) do not have _locked() counterpart and take the lock inside

job_{lock/unlock} is independent from real_job_{lock/unlock}.

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*

.Signed-off-by: Emanuele Giuseppe Esposito <[email protected]>

---
 include/qemu/job.h |  73 +++++-
 job.c              | 607 +++++++++++++++++++++++++++++++--------------
 2 files changed, 499 insertions(+), 181 deletions(-)
include/qemu/job.h +72 -1
index 4b64eb15f7..99960cc9a3 100644
@@ -358,6 +358,9 @@ JobTxn *job_txn_new(void);
  */
 void job_txn_unref(JobTxn *txn);
 
+/* Same as job_txn_unref(), but called with job lock held. */
+void job_txn_unref_locked(JobTxn *txn);
+
 /**
  * Create a new long-running job and return it.
  *
@@ -380,12 +383,18 @@ void *job_create(const char *job_id, const JobDriver *driver, JobTxn *txn,
  */
 void job_ref(Job *job);
 
+/* Same as job_ref(), but called with job lock held. */
+void job_ref_locked(Job *job);
+
 /**
  * Release a reference that was previously acquired with job_ref() or
  * job_create(). If it's the last reference to the object, it will be freed.
  */
 void job_unref(Job *job);
 
+/* Same as job_unref(), but called with job lock held. */
+void job_unref_locked(Job *job);
+
 /**
  * @job: The job that has made progress
  * @done: How much progress the job made since the last call
@@ -426,6 +435,9 @@ void job_progress_increase_remaining(Job *job, uint64_t delta);
  */
 void job_enter_cond(Job *job, bool(*fn)(Job *job));
 
+/* Same as job_enter_cond(), but called with job lock held. */
+void job_enter_cond_locked(Job *job, bool(*fn)(Job *job));
+
 /**
  * @job: A job that has not yet been started.
  *
@@ -478,6 +490,9 @@ bool job_is_internal(Job *job);
 /** Returns whether the job is being cancelled. */
 bool job_is_cancelled(Job *job);
 
+/* Same as job_is_cancelled(), but called with job lock held. */
+bool job_is_cancelled_locked(Job *job);
+
 /**
  * Returns whether the job is scheduled for cancellation (at an
  * indefinite point).
@@ -487,9 +502,15 @@ bool job_cancel_requested(Job *job);
 /** Returns whether the job is in a completed state. */
 bool job_is_completed(Job *job);
 
+/* Same as job_is_completed(), but called with job lock held. */
+bool job_is_completed_locked(Job *job);
+
 /** Returns whether the job is ready to be completed. */
 bool job_is_ready(Job *job);
 
+/* Same as job_is_ready(), but called with job lock held. */
+bool job_is_ready_locked(Job *job);
+
 /**
  * Request @job to pause at the next pause point. Must be paired with
  * job_resume(). If the job is supposed to be resumed by user action, call
@@ -497,24 +518,39 @@ bool job_is_ready(Job *job);
  */
 void job_pause(Job *job);
 
+/* Same as job_pause(), but called with job lock held. */
+void job_pause_locked(Job *job);
+
 /** Resumes a @job paused with job_pause. */
 void job_resume(Job *job);
 
+/* Same as job_resume(), but called with job lock held. */
+void job_resume_locked(Job *job);
+
 /**
  * Asynchronously pause the specified @job.
  * Do not allow a resume until a matching call to job_user_resume.
  */
 void job_user_pause(Job *job, Error **errp);
 
+/* Same as job_user_pause(), but called with job lock held. */
+void job_user_pause_locked(Job *job, Error **errp);
+
 /** Returns true if the job is user-paused. */
 bool job_user_paused(Job *job);
 
+/* Same as job_user_paused(), but called with job lock held. */
+bool job_user_paused_locked(Job *job);
+
 /**
  * Resume the specified @job.
  * Must be paired with a preceding job_user_pause.
  */
 void job_user_resume(Job *job, Error **errp);
 
+/* Same as job_user_resume(), but called with job lock held. */
+void job_user_resume_locked(Job *job, Error **errp);
+
 /**
  * Get the next element from the list of block jobs after @job, or the
  * first one if @job is %NULL.
@@ -523,6 +559,9 @@ void job_user_resume(Job *job, Error **errp);
  */
 Job *job_next(Job *job);
 
+/* Same as job_next(), but called with job lock held. */
+Job *job_next_locked(Job *job);
+
 /**
  * Get the job identified by @id (which must not be %NULL).
  *
@@ -530,6 +569,9 @@ Job *job_next(Job *job);
  */
 Job *job_get(const char *id);
 
+/* Same as job_get(), but called with job lock held. */
+Job *job_get_locked(const char *id);
+
 /**
  * Check whether the verb @verb can be applied to @job in its current state.
  * Returns 0 if the verb can be applied; otherwise errp is set and -EPERM
@@ -537,6 +579,9 @@ Job *job_get(const char *id);
  */
 int job_apply_verb(Job *job, JobVerb verb, Error **errp);
 
+/* Same as job_apply_verb, but called with job lock held. */
+int job_apply_verb_locked(Job *job, JobVerb verb, Error **errp);
+
 /** The @job could not be started, free it. */
 void job_early_fail(Job *job);
 
@@ -546,18 +591,27 @@ void job_transition_to_ready(Job *job);
 /** Asynchronously complete the specified @job. */
 void job_complete(Job *job, Error **errp);
 
+/* Same as job_complete(), but called with job lock held. */
+void job_complete_locked(Job *job, Error **errp);
+
 /**
  * Asynchronously cancel the specified @job. If @force is true, the job should
  * be cancelled immediately without waiting for a consistent state.
  */
 void job_cancel(Job *job, bool force);
 
+/* Same as job_cancel(), but called with job lock held. */
+void job_cancel_locked(Job *job, bool force);
+
 /**
  * Cancels the specified job like job_cancel(), but may refuse to do so if the
  * operation isn't meaningful in the current state of the job.
  */
 void job_user_cancel(Job *job, bool force, Error **errp);
 
+/* Same as job_user_cancel(), but called with job lock held. */
+void job_user_cancel_locked(Job *job, bool force, Error **errp);
+
 /**
  * Synchronously cancel the @job.  The completion callback is called
  * before the function returns.  If @force is false, the job may
@@ -571,6 +625,9 @@ void job_user_cancel(Job *job, bool force, Error **errp);
  */
 int job_cancel_sync(Job *job, bool force);
 
+/* Same as job_cancel_sync, but called with job lock held. */
+int job_cancel_sync_locked(Job *job, bool force);
+
 /** Synchronously force-cancels all jobs using job_cancel_sync(). */
 void job_cancel_sync_all(void);
 
@@ -590,6 +647,9 @@ void job_cancel_sync_all(void);
  */
 int job_complete_sync(Job *job, Error **errp);
 
+/* Same as job_complete_sync, but called with job lock held. */
+int job_complete_sync_locked(Job *job, Error **errp);
+
 /**
  * For a @job that has finished its work and is pending awaiting explicit
  * acknowledgement to commit its work, this will commit that work.
@@ -600,12 +660,18 @@ int job_complete_sync(Job *job, Error **errp);
  */
 void job_finalize(Job *job, Error **errp);
 
+/* Same as job_finalize(), but called with job lock held. */
+void job_finalize_locked(Job *job, Error **errp);
+
 /**
  * Remove the concluded @job from the query list and resets the passed pointer
  * to %NULL. Returns an error if the job is not actually concluded.
  */
 void job_dismiss(Job **job, Error **errp);
 
+/* Same as job_dismiss(), but called with job lock held. */
+void job_dismiss_locked(Job **job, Error **errp);
+
 /**
  * Synchronously finishes the given @job. If @finish is given, it is called to
  * trigger completion or cancellation of the job.
@@ -615,6 +681,11 @@ void job_dismiss(Job **job, Error **errp);
  *
  * Callers must hold the AioContext lock of job->aio_context.
  */
-int job_finish_sync(Job *job, void (*finish)(Job *, Error **errp), Error **errp);
+int job_finish_sync(Job *job, void (*finish)(Job *, Error **errp),
+                    Error **errp);
+
+/* Same as job_finish_sync, but called with job lock held. */
+int job_finish_sync_locked(Job *job, void (*finish)(Job *, Error **errp),
+                           Error **errp);
 
 #endif
job.c +427 -180

1,232 lines not on this page · raw message

Signature · 1 line
2.31.1
#7 lore raw

Re: [PATCH v8 05/20] job.c: add job_lock/unlock while keeping job.h intact

job.c void *job_create(const char *job_id, const JobDriver *driver, JobTxn *txn, · line 466

Quoted 5 lines · Emanuele Giuseppe Esposito
job.c +5 -0
+void job_ref(Job *job)
+{
+    JOB_LOCK_GUARD();
+    job_ref_locked(job);
+}

You don't need to fix this, but just a note:

This API seems dangerous. If we don't hold the lock, how can we be sure job won't be unreferenced before we call job_ref()? We would need to be sure there exists another reference that won't be released until job_ref() returns...

#8 lore raw

Re: [PATCH v8 05/20] job.c: add job_lock/unlock while keeping job.h intact

Am 05/07/2022 um 09:39 schrieb Stefan Hajnoczi:

Quoted 9 lines · Emanuele Giuseppe Esposito

job.c void *job_create(const char *job_id, const JobDriver *driver, JobTxn *txn, · line 466

Quoted 5 lines
job.c +5 -0
+void job_ref(Job *job)
+{
+    JOB_LOCK_GUARD();
+    job_ref_locked(job);
+}

You don't need to fix this, but just a note:

Quoted 5 lines

This API seems dangerous. If we don't hold the lock, how can we be sure job won't be unreferenced before we call job_ref()? We would need to be sure there exists another reference that won't be released until job_ref() returns...

I guess that's a drawback of using this new serie organization :)

This function is just a temporary placeholder to avoid having _locked functions being called without the lock held (see previous serie suggestions from Vladimir and Kevin).

Emanuele

#9 lore raw

Re: [PATCH v8 05/20] job.c: add job_lock/unlock while keeping job.h intact

Quoted 18 lines · Emanuele Giuseppe Esposito

Am 05/07/2022 um 09:39 schrieb Stefan Hajnoczi:

Quoted 9 lines · Emanuele Giuseppe Esposito

job.c void *job_create(const char *job_id, const JobDriver *driver, JobTxn *txn, · line 466

Quoted 5 lines
job.c +5 -0
+void job_ref(Job *job)
+{
+    JOB_LOCK_GUARD();
+    job_ref_locked(job);
+}

You don't need to fix this, but just a note:

Quoted 5 lines

This API seems dangerous. If we don't hold the lock, how can we be sure job won't be unreferenced before we call job_ref()? We would need to be sure there exists another reference that won't be released until job_ref() returns...

Quoted 5 lines

I guess that's a drawback of using this new serie organization :)

This function is just a temporary placeholder to avoid having _locked functions being called without the lock held (see previous serie suggestions from Vladimir and Kevin).

Ah, yes, I saw non-locked functions being removed after I reviewed this patch. A comment would help explain this to reviewers but there's no need to change it now.

Thanks,
Stefan

Reviewed-by on v8 5/20
#10 lore raw

Re: [PATCH v8 05/20] job.c: add job_lock/unlock while keeping job.h intact

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

With "intact" we mean that all job.h functions implicitly take the lock. Therefore API callers are unmodified.

This means that:
- all static functions become _locked, and call _locked functions
- all public functions take the lock internally, and call _locked functions
- all public functions called internally by other functions in job.c will have a _locked counterpart, to avoid deadlocks (job lock already taken)
- public functions called only from exernal files (not job.c) do not have _locked() counterpart and take the lock inside

job_{lock/unlock} is independent from real_job_{lock/unlock}.

Quoted 8 lines

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*

.Signed-off-by: Emanuele Giuseppe Esposito <[email protected]>

---
 include/qemu/job.h |  73 +++++-
 job.c              | 607 +++++++++++++++++++++++++++++++--------------
 2 files changed, 499 insertions(+), 181 deletions(-)
#11 lore raw

Re: [PATCH v8 05/20] job.c: add job_lock/unlock while keeping job.h intact

In reply to Emanuele Giuseppe Esposito

In general looks good to me.

Quoted 5 lines · Emanuele Giuseppe Esposito

With "intact" we mean that all job.h functions implicitly take the lock. Therefore API callers are unmodified.

This means that:
- all static functions become _locked, and call _locked functions

Some static functions don't have _locked prefix.. That's, maybe, not wrong. But it contradicts with commit message and looks inconsistent.

For example job_started and job_should_pause are similar simple getters, job_shoud_pause is updated to be _locked, but job_started is not updated..

job_exit, job_co_entry are correct exclusions

Quoted 2 lines

- all public functions take the lock internally, and call _locked functions

may be just, "all public function take the lock internally if needed", as some public funcitons don't need the lock, like job_txn_new or job_progress_* functions

Quoted 2 lines

- all public functions called internally by other functions in job.c will have a _locked counterpart, to avoid deadlocks (job lock already taken)

counterparts sometimes made public and are unused for now. That's OK, just mention.

Quoted 2 lines

- public functions called only from exernal files (not job.c) do not have _locked() counterpart and take the lock inside

Some small public functions still don't take the lock inside and don't have _locked() prefix.

job_is_internal
job_type
job_type_str

job_sleep_timer_cb is static, but it's called only by external source, so it should take lock inside, like public functions. (and like job_exit)

job_pause_point_locked, job_user_resume_locked, job_complete_locked: need to mention in a comment, that function may temporarily unlock the mutex

Also, the commennt "realeases it temporarily" should be propagated to all _locked callers of the function

Quoted 10 lines

job_{lock/unlock} is independent from real_job_{lock/unlock}.

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*

.Signed-off-by: Emanuele Giuseppe Esposito <[email protected]>

---
  include/qemu/job.h |  73 +++++-
  job.c              | 607 +++++++++++++++++++++++++++++++--------------

[..]

job.c void job_cancel(Job *job, bool force) · line 1362

Quoted 6 lines
job.c +3 -2
-    AIO_WAIT_WHILE(job->aio_context,
-                   (job_enter(job), !job_is_completed(job)));
+    job_unlock();
+    AIO_WAIT_WHILE_UNLOCKED(job->aio_context,
+                            (job_enter(job), !job_is_completed(job)));

Is it correct here to move to UNLOCKED wait? We don't touch any other aio-context related things in this patch..

Even if it's OK, it should be in another commit I think.

Quoted 6 lines
job.c +3 -2
+    job_lock();
 
-    ret = (job_is_cancelled(job) && job->ret == 0) ? -ECANCELED : job->ret;
-    job_unref(job);
+    ret = (job_is_cancelled_locked(job) && job->ret == 0)
+          ? -ECANCELED : job->ret;

job.c void job_cancel(Job *job, bool force) · line 1375

Quoted 10 lines
job.c +7 -0
+    job_unref_locked(job);
      return ret;
  }
+
+int job_finish_sync(Job *job, void (*finish)(Job *, Error **errp), Error **errp)
+{
+    JOB_LOCK_GUARD();
+    return job_finish_sync_locked(job, finish, errp);
+}
\ No newline at end of file

No newline at end of file... I think, good to add one)

Signature · 2 lines
Best regards,
Vladimir
#12 lore raw

PATCH v8 6/20 job.h: define functions called without job lock held

In reply to Emanuele Giuseppe Esposito

These functions don't need a _locked() counterpart, since they are all called outside job.c and take the lock only internally.

Update also the comments in blockjob.c (and move them in job.c).

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

No functional change intended.

---
 blockjob.c         | 20 --------------------
 include/qemu/job.h | 37 ++++++++++++++++++++++++++++++++++---
 job.c              | 15 +++++++++++++++
 3 files changed, 49 insertions(+), 23 deletions(-)
blockjob.c +0 -20
index 4868453d74..7da59a1f1c 100644
@@ -36,21 +36,6 @@
 #include "qemu/main-loop.h"
 #include "qemu/timer.h"
 
-/*
- * The block job API is composed of two categories of functions.
- *
- * The first includes functions used by the monitor.  The monitor is
- * peculiar in that it accesses the block job list with block_job_get, and
- * therefore needs consistency across block_job_get and the actual operation
- * (e.g. block_job_set_speed).  The consistency is achieved with
- * aio_context_acquire/release.  These functions are declared in blockjob.h.
- *
- * The second includes functions used by the block job drivers and sometimes
- * by the core block layer.  These do not care about locking, because the
- * whole coroutine runs under the AioContext lock, and are declared in
- * blockjob_int.h.
- */
-
 static bool is_block_job(Job *job)
 {
     return job_type(job) == JOB_TYPE_BACKUP ||
@@ -433,11 +418,6 @@ static void block_job_event_ready(Notifier *n, void *opaque)
 }
 
 
-/*
- * API for block job drivers and the block layer.  These functions are
- * declared in blockjob_int.h.
- */
-
 void *block_job_create(const char *job_id, const BlockJobDriver *driver,
                        JobTxn *txn, BlockDriverState *bs, uint64_t perm,
                        uint64_t shared_perm, int64_t speed, int flags,
include/qemu/job.h +34 -3
index 99960cc9a3..b714236c1a 100644
@@ -363,6 +363,7 @@ void job_txn_unref_locked(JobTxn *txn);
 
 /**
  * Create a new long-running job and return it.
+ * Called with job_mutex *not* held.
  *
  * @job_id: The id of the newly-created job, or %NULL for internal jobs
  * @driver: The class object for the newly-created job.
@@ -400,6 +401,8 @@ void job_unref_locked(Job *job);
  * @done: How much progress the job made since the last call
  *
  * Updates the progress counter of the job.
+ *
+ * Progress API is thread safe.
  */
 void job_progress_update(Job *job, uint64_t done);
 
@@ -410,6 +413,8 @@ void job_progress_update(Job *job, uint64_t done);
  *
  * Sets the expected end value of the progress counter of a job so that a
  * completion percentage can be calculated when the progress is updated.
+ *
+ * Progress API is thread safe.
  */
 void job_progress_set_remaining(Job *job, uint64_t remaining);
 
@@ -425,6 +430,8 @@ void job_progress_set_remaining(Job *job, uint64_t remaining);
  * length before, and job_progress_update() afterwards.
  * (So the operation acts as a parenthesis in regards to the main job
  * operation running in background.)
+ *
+ * Progress API is thread safe.
  */
 void job_progress_increase_remaining(Job *job, uint64_t delta);
 
@@ -443,6 +450,8 @@ void job_enter_cond_locked(Job *job, bool(*fn)(Job *job));
  *
  * Begins execution of a job.
  * Takes ownership of one reference to the job object.
+ *
+ * Called with job_mutex *not* held.
  */
 void job_start(Job *job);
 
@@ -450,6 +459,7 @@ void job_start(Job *job);
  * @job: The job to enter.
  *
  * Continue the specified job by entering the coroutine.
+ * Called with job_mutex *not* held.
  */
 void job_enter(Job *job);
 
@@ -458,6 +468,9 @@ void job_enter(Job *job);
  *
  * Pause now if job_pause() has been called. Jobs that perform lots of I/O
  * must call this between requests so that the job can be paused.
+ *
+ * Called with job_mutex *not* held (we don't want the coroutine
+ * to yield with the lock held!).
  */
 void coroutine_fn job_pause_point(Job *job);
 
@@ -465,6 +478,8 @@ void coroutine_fn job_pause_point(Job *job);
  * @job: The job that calls the function.
  *
  * Yield the job coroutine.
+ * Called with job_mutex *not* held (we don't want the coroutine
+ * to yield with the lock held!).
  */
 void job_yield(Job *job);
 
@@ -475,6 +490,9 @@ void job_yield(Job *job);
  * Put the job to sleep (assuming that it wasn't canceled) for @ns
  * %QEMU_CLOCK_REALTIME nanoseconds.  Canceling the job will immediately
  * interrupt the wait.
+ *
+ * Called with job_mutex *not* held (we don't want the coroutine
+ * to yield with the lock held!).
  */
 void coroutine_fn job_sleep_ns(Job *job, int64_t ns);
 
@@ -496,6 +514,7 @@ bool job_is_cancelled_locked(Job *job);
 /**
  * Returns whether the job is scheduled for cancellation (at an
  * indefinite point).
+ * Called with job_mutex *not* held.
  */
 bool job_cancel_requested(Job *job);
 
@@ -582,10 +601,16 @@ int job_apply_verb(Job *job, JobVerb verb, Error **errp);
 /* Same as job_apply_verb, but called with job lock held. */
 int job_apply_verb_locked(Job *job, JobVerb verb, Error **errp);
 
-/** The @job could not be started, free it. */
+/**
+ * The @job could not be started, free it.
+ * Called with job_mutex *not* held.
+ */
 void job_early_fail(Job *job);
 
-/** Moves the @job from RUNNING to READY */
+/**
+ * Moves the @job from RUNNING to READY.
+ * Called with job_mutex *not* held.
+ */
 void job_transition_to_ready(Job *job);
 
 /** Asynchronously complete the specified @job. */
@@ -628,7 +653,13 @@ int job_cancel_sync(Job *job, bool force);
 /* Same as job_cancel_sync, but called with job lock held. */
 int job_cancel_sync_locked(Job *job, bool force);
 
-/** Synchronously force-cancels all jobs using job_cancel_sync(). */
+/**
+ * Synchronously force-cancels all jobs using job_cancel_sync_locked().
+ *
+ * Called with job_lock *not* held, unlike most other APIs consumed
+ * by the monitor! This is primarly to avoid adding unnecessary lock-unlock
+ * patterns in the caller.
+ */
 void job_cancel_sync_all(void);
 
 /**
job.c +15 -0
index dd44fac8dd..7a3cc93f66 100644
@@ -32,12 +32,27 @@
 #include "trace/trace-root.h"
 #include "qapi/qapi-events-job.h"
 
+/*
+ * The job API is composed of two categories of functions.
+ *
+ * The first includes functions used by the monitor.  The monitor is
+ * peculiar in that it accesses the block job list with job_get, and
+ * therefore needs consistency across job_get and the actual operation
+ * (e.g. job_user_cancel). To achieve this consistency, the caller
+ * calls job_lock/job_unlock itself around the whole operation.
+ *
+ *
+ * The second includes functions used by the block job drivers and sometimes
+ * by the core block layer. These delegate the locking to the callee instead.
+ */
+
 /*
  * job_mutex protects the jobs list, but also makes the
  * struct job fields thread-safe.
  */
 QemuMutex job_mutex;
 
+/* Protected by job_mutex */
 static QLIST_HEAD(, Job) jobs = QLIST_HEAD_INITIALIZER(jobs);
 
 /* Job State Transition Table */
Signature · 1 line
2.31.1
Reviewed-by on v8 6/20
#13 lore raw

Re: [PATCH v8 06/20] job.h: define functions called without job lock held

Quoted 9 lines · Emanuele Giuseppe Esposito

These functions don't need a _locked() counterpart, since they are all called outside job.c and take the lock only internally.

Update also the comments in blockjob.c (and move them in job.c).

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

Quoted 8 lines

No functional change intended.

---
 blockjob.c         | 20 --------------------
 include/qemu/job.h | 37 ++++++++++++++++++++++++++++++++++---
 job.c              | 15 +++++++++++++++
 3 files changed, 49 insertions(+), 23 deletions(-)
#14 lore raw

Re: [PATCH v8 06/20] job.h: define functions called without job lock held

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

These functions don't need a _locked() counterpart, since they are all called outside job.c and take the lock only internally.

Update also the comments in blockjob.c (and move them in job.c).

Still, that would be better as a separate patch.

Quoted 64 lines

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

No functional change intended.

---
  blockjob.c         | 20 --------------------
  include/qemu/job.h | 37 ++++++++++++++++++++++++++++++++++---
  job.c              | 15 +++++++++++++++
  3 files changed, 49 insertions(+), 23 deletions(-)
blockjob.c +0 -20
index 4868453d74..7da59a1f1c 100644
@@ -36,21 +36,6 @@
  #include "qemu/main-loop.h"
  #include "qemu/timer.h"
 
-/*
- * The block job API is composed of two categories of functions.
- *
- * The first includes functions used by the monitor.  The monitor is
- * peculiar in that it accesses the block job list with block_job_get, and
- * therefore needs consistency across block_job_get and the actual operation
- * (e.g. block_job_set_speed).  The consistency is achieved with
- * aio_context_acquire/release.  These functions are declared in blockjob.h.
- *
- * The second includes functions used by the block job drivers and sometimes
- * by the core block layer.  These do not care about locking, because the
- * whole coroutine runs under the AioContext lock, and are declared in
- * blockjob_int.h.
- */
-
  static bool is_block_job(Job *job)
  {
      return job_type(job) == JOB_TYPE_BACKUP ||
@@ -433,11 +418,6 @@ static void block_job_event_ready(Notifier *n, void *opaque)
  }
 
 
-/*
- * API for block job drivers and the block layer.  These functions are
- * declared in blockjob_int.h.
- */
-
  void *block_job_create(const char *job_id, const BlockJobDriver *driver,
                         JobTxn *txn, BlockDriverState *bs, uint64_t perm,
                         uint64_t shared_perm, int64_t speed, int flags,
include/qemu/job.h +1 -0
index 99960cc9a3..b714236c1a 100644
@@ -363,6 +363,7 @@ void job_txn_unref_locked(JobTxn *txn);
 
  /**
   * Create a new long-running job and return it.
+ * Called with job_mutex *not* held.
   *
   * @job_id: The id of the newly-created job, or %NULL for internal jobs
   * @driver: The class object for the newly-created job.

include/qemu/job.h void job_unref_locked(Job *job); · line 405

Quoted 5 lines
include/qemu/job.h +2 -0
@@ -400,6 +401,8 @@ void job_unref_locked(Job *job);
   * @done: How much progress the job made since the last call
   *
   * Updates the progress counter of the job.
+ *
+ * Progress API is thread safe.

This tell nothing for function user. Finally the whole job_ API will be thread safe, isn't it?

I think here we need simply "called with mutex not held". (Or even "may be called with mutex held or not held" if we need it, or just nothing)

and note about progress API should be somewhere in job.c, as that's implementation details.

Quoted 39 lines
include/qemu/job.h +7 -0
   */
  void job_progress_update(Job *job, uint64_t done);
 
@@ -410,6 +413,8 @@ void job_progress_update(Job *job, uint64_t done);
   *
   * Sets the expected end value of the progress counter of a job so that a
   * completion percentage can be calculated when the progress is updated.
+ *
+ * Progress API is thread safe.
   */
  void job_progress_set_remaining(Job *job, uint64_t remaining);
 
@@ -425,6 +430,8 @@ void job_progress_set_remaining(Job *job, uint64_t remaining);
   * length before, and job_progress_update() afterwards.
   * (So the operation acts as a parenthesis in regards to the main job
   * operation running in background.)
+ *
+ * Progress API is thread safe.
   */
  void job_progress_increase_remaining(Job *job, uint64_t delta);
 
@@ -443,6 +450,8 @@ void job_enter_cond_locked(Job *job, bool(*fn)(Job *job));
   *
   * Begins execution of a job.
   * Takes ownership of one reference to the job object.
+ *
+ * Called with job_mutex *not* held.
   */
  void job_start(Job *job);
 
@@ -450,6 +459,7 @@ void job_start(Job *job);
   * @job: The job to enter.
   *
   * Continue the specified job by entering the coroutine.
+ * Called with job_mutex *not* held.
   */
  void job_enter(Job *job);
 

include/qemu/job.h void job_enter(Job *job); · line 473

Quoted 6 lines
include/qemu/job.h +3 -0
@@ -458,6 +468,9 @@ void job_enter(Job *job);
   *
   * Pause now if job_pause() has been called. Jobs that perform lots of I/O
   * must call this between requests so that the job can be paused.
+ *
+ * Called with job_mutex *not* held (we don't want the coroutine
+ * to yield with the lock held!).

The comment in () looks strange, as we know that job_pause_point take the mutex inside.

include/qemu/job.h void coroutine_fn job_pause_point(Job *job); · line 482

Quoted 9 lines
include/qemu/job.h +2 -0
   */
  void coroutine_fn job_pause_point(Job *job);
 
@@ -465,6 +478,8 @@ void coroutine_fn job_pause_point(Job *job);
   * @job: The job that calls the function.
   *
   * Yield the job coroutine.
+ * Called with job_mutex *not* held (we don't want the coroutine
+ * to yield with the lock held!).

same here.

Quoted 42 lines
include/qemu/job.h +12 -2
   */
  void job_yield(Job *job);
 
@@ -475,6 +490,9 @@ void job_yield(Job *job);
   * Put the job to sleep (assuming that it wasn't canceled) for @ns
   * %QEMU_CLOCK_REALTIME nanoseconds.  Canceling the job will immediately
   * interrupt the wait.
+ *
+ * Called with job_mutex *not* held (we don't want the coroutine
+ * to yield with the lock held!).
   */
  void coroutine_fn job_sleep_ns(Job *job, int64_t ns);
 
@@ -496,6 +514,7 @@ bool job_is_cancelled_locked(Job *job);
  /**
   * Returns whether the job is scheduled for cancellation (at an
   * indefinite point).
+ * Called with job_mutex *not* held.
   */
  bool job_cancel_requested(Job *job);
 
@@ -582,10 +601,16 @@ int job_apply_verb(Job *job, JobVerb verb, Error **errp);
  /* Same as job_apply_verb, but called with job lock held. */
  int job_apply_verb_locked(Job *job, JobVerb verb, Error **errp);
 
-/** The @job could not be started, free it. */
+/**
+ * The @job could not be started, free it.
+ * Called with job_mutex *not* held.
+ */
  void job_early_fail(Job *job);
 
-/** Moves the @job from RUNNING to READY */
+/**
+ * Moves the @job from RUNNING to READY.
+ * Called with job_mutex *not* held.
+ */
  void job_transition_to_ready(Job *job);
 
  /** Asynchronously complete the specified @job. */
@@ -628,7 +653,13 @@ int job_cancel_sync(Job *job, bool force);
  /* Same as job_cancel_sync, but called with job lock held. */

include/qemu/job.h int job_cancel_sync(Job *job, bool force); · line 662

Quoted 10 lines
include/qemu/job.h +7 -1
  int job_cancel_sync_locked(Job *job, bool force);
 
-/** Synchronously force-cancels all jobs using job_cancel_sync(). */
+/**
+ * Synchronously force-cancels all jobs using job_cancel_sync_locked().
+ *
+ * Called with job_lock *not* held, unlike most other APIs consumed
+ * by the monitor! This is primarly to avoid adding unnecessary lock-unlock
+ * patterns in the caller.
+ */

I'd prefer just "Called with job_lock *not* held". The function is not exclusion in any manner:
it's normal for functions without _locked suffix to require that mutex is not held.

I'd merge all new comments in job.h to the previous commit, as they are related to the questions risen by it.

Quoted 25 lines
include/qemu/job.h +0 -0
  void job_cancel_sync_all(void);
 
  /**
job.c +14 -0
index dd44fac8dd..7a3cc93f66 100644
@@ -32,12 +32,27 @@
  #include "trace/trace-root.h"
  #include "qapi/qapi-events-job.h"
 
+/*
+ * The job API is composed of two categories of functions.
+ *
+ * The first includes functions used by the monitor.  The monitor is
+ * peculiar in that it accesses the block job list with job_get, and
+ * therefore needs consistency across job_get and the actual operation
+ * (e.g. job_user_cancel). To achieve this consistency, the caller
+ * calls job_lock/job_unlock itself around the whole operation.
+ *
+ *
+ * The second includes functions used by the block job drivers and sometimes
+ * by the core block layer. These delegate the locking to the callee instead.
+ */
+

job.c line 58

Quoted 10 lines
job.c +1 -0
  /*
   * job_mutex protects the jobs list, but also makes the
   * struct job fields thread-safe.
   */
  QemuMutex job_mutex;
 
+/* Protected by job_mutex */
  static QLIST_HEAD(, Job) jobs = QLIST_HEAD_INITIALIZER(jobs);
 
  /* Job State Transition Table */

So the logic is: the function that doesn't have public _locked counterpart has explicit comment that mutex should be not held. OK.

Signature · 2 lines
Best regards,
Vladimir
#15 lore raw

Re: [PATCH v8 06/20] job.h: define functions called without job lock held

Am 05/07/2022 um 12:53 schrieb Vladimir Sementsov-Ogievskiy:

Quoted 86 lines · Emanuele Giuseppe Esposito
Quoted 5 lines

These functions don't need a _locked() counterpart, since they are all called outside job.c and take the lock only internally.

Update also the comments in blockjob.c (and move them in job.c).

Still, that would be better as a separate patch.

Quoted 68 lines

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

No functional change intended.

---
  blockjob.c         | 20 -------------------- include/qemu/job.h | 37 ++++++++++++++++++++++++++++++++++--- job.c              | 15 +++++++++++++++

  3 files changed, 49 insertions(+), 23 deletions(-)
blockjob.c +0 -0
index 4868453d74..7da59a1f1c 100644
@@ -36,21 +36,6 @@
   #include "qemu/main-loop.h"
   #include "qemu/timer.h"

  -/*
- * The block job API is composed of two categories of functions.
- *
- * The first includes functions used by the monitor.  The monitor is
- * peculiar in that it accesses the block job list with block_job_get, and
- * therefore needs consistency across block_job_get and the actual operation
- * (e.g. block_job_set_speed).  The consistency is achieved with
- * aio_context_acquire/release.  These functions are declared in blockjob.h.
- *
- * The second includes functions used by the block job drivers and sometimes
- * by the core block layer.  These do not care about locking, because the
- * whole coroutine runs under the AioContext lock, and are declared in
- * blockjob_int.h.
- */
-
  static bool is_block_job(Job *job)
  {
      return job_type(job) == JOB_TYPE_BACKUP ||

blockjob.c +0 -0
@@ -433,11 +418,6 @@ static void block_job_event_ready(Notifier *n,
 void *opaque)
   }

    -/*
- * API for block job drivers and the block layer.  These functions are
- * declared in blockjob_int.h.
- */
-
  void *block_job_create(const char *job_id, const BlockJobDriver *driver,
                         JobTxn *txn, BlockDriverState *bs, uint64_t perm,
                         uint64_t shared_perm, int64_t speed, int flags,

include/qemu/job.h +1 -0
index 99960cc9a3..b714236c1a 100644
@@ -363,6 +363,7 @@ void job_txn_unref_locked(JobTxn *txn);
     /**
    * Create a new long-running job and return it.
+ * Called with job_mutex *not* held.
    *
    * @job_id: The id of the newly-created job, or %NULL for internal jobs
    * @driver: The class object for the newly-created job.

include/qemu/job.h void job_unref_locked(Job *job); · line 405

Quoted 5 lines
include/qemu/job.h +2 -0
@@ -400,6 +401,8 @@ void job_unref_locked(Job *job);
    * @done: How much progress the job made since the last call
    *
    * Updates the progress counter of the job.
+ *
+ * Progress API is thread safe.

This tell nothing for function user. Finally the whole job_ API will be thread safe, isn't it?

Quoted 5 lines

I think here we need simply "called with mutex not held". (Or even "may be called with mutex held or not held" if we need it, or just nothing)

and note about progress API should be somewhere in job.c, as that's implementation details.

What about "Progress API is thread safe. Can be called with job mutex held or not"?

Quoted 1 line

[...]

Quoted 3 lines

I'd merge all new comments in job.h to the previous commit, as they are related to the questions risen by it.

I disagree, I think it will be a mess of functions again if we mix these one that don't need the lock held and the ones that need it.

You understand it because you got the logic of this serie, but others may not.

Quoted 40 lines
Quoted 27 lines

  void job_cancel_sync_all(void);
    /**

job.c +0 -0
index dd44fac8dd..7a3cc93f66 100644
@@ -32,12 +32,27 @@
   #include "trace/trace-root.h"
   #include "qapi/qapi-events-job.h"

  +/*
+ * The job API is composed of two categories of functions.
+ *
+ * The first includes functions used by the monitor.  The monitor is
+ * peculiar in that it accesses the block job list with job_get, and
+ * therefore needs consistency across job_get and the actual operation
+ * (e.g. job_user_cancel). To achieve this consistency, the caller
+ * calls job_lock/job_unlock itself around the whole operation.
+ *
+ *
+ * The second includes functions used by the block job drivers and sometimes
+ * by the core block layer. These delegate the locking to the callee instead.
+ */
+

Quoted 8 lines

  /*
   * job_mutex protects the jobs list, but also makes the
   * struct job fields thread-safe.
   */
  QemuMutex job_mutex;
  +/* Protected by job_mutex */
  static QLIST_HEAD(, Job) jobs = QLIST_HEAD_INITIALIZER(jobs); /* Job State Transition Table */

So the logic is: the function that doesn't have public _locked counterpart has explicit comment that mutex should be not held. OK.

#16 lore raw

Re: [PATCH v8 06/20] job.h: define functions called without job lock held

Quoted 89 lines · Emanuele Giuseppe Esposito

Am 05/07/2022 um 12:53 schrieb Vladimir Sementsov-Ogievskiy:

Quoted 86 lines · Emanuele Giuseppe Esposito
Quoted 5 lines

These functions don't need a _locked() counterpart, since they are all called outside job.c and take the lock only internally.

Update also the comments in blockjob.c (and move them in job.c).

Still, that would be better as a separate patch.

Quoted 68 lines

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

No functional change intended.

---
   blockjob.c         | 20 --------------------
   include/qemu/job.h | 37 ++++++++++++++++++++++++++++++++++---
   job.c              | 15 +++++++++++++++
   3 files changed, 49 insertions(+), 23 deletions(-)
blockjob.c +0 -4
index 4868453d74..7da59a1f1c 100644
@@ -36,21 +36,6 @@
   #include "qemu/main-loop.h"
   #include "qemu/timer.h"
   -/*
- * The block job API is composed of two categories of functions.
- *
- * The first includes functions used by the monitor.  The monitor is
- * peculiar in that it accesses the block job list with

block_job_get, and
- * therefore needs consistency across block_job_get and the actual operation
- * (e.g. block_job_set_speed).  The consistency is achieved with
- * aio_context_acquire/release.  These functions are declared in blockjob.h.
- *
- * The second includes functions used by the block job drivers and sometimes
- * by the core block layer.  These do not care about locking, because the
- * whole coroutine runs under the AioContext lock, and are declared in
- * blockjob_int.h.
- */

blockjob.c +0 -5
-
   static bool is_block_job(Job *job)
   {
       return job_type(job) == JOB_TYPE_BACKUP ||
@@ -433,11 +418,6 @@ static void block_job_event_ready(Notifier *n,
 void *opaque)
   }
     -/*
- * API for block job drivers and the block layer.  These functions are
- * declared in blockjob_int.h.
- */
-
   void *block_job_create(const char *job_id, const BlockJobDriver
 *driver,
                          JobTxn *txn, BlockDriverState *bs, uint64_t

perm,
                         uint64_t shared_perm, int64_t speed, int flags,

include/qemu/job.h +1 -0
index 99960cc9a3..b714236c1a 100644
@@ -363,6 +363,7 @@ void job_txn_unref_locked(JobTxn *txn);
     /**
    * Create a new long-running job and return it.
+ * Called with job_mutex *not* held.
    *
    * @job_id: The id of the newly-created job, or %NULL for internal jobs
    * @driver: The class object for the newly-created job.

include/qemu/job.h void job_unref_locked(Job *job); · line 405

Quoted 5 lines
include/qemu/job.h +2 -0
@@ -400,6 +401,8 @@ void job_unref_locked(Job *job);
    * @done: How much progress the job made since the last call
    *
    * Updates the progress counter of the job.
+ *
+ * Progress API is thread safe.

This tell nothing for function user. Finally the whole job_ API will be thread safe, isn't it?

Quoted 8 lines
Quoted 5 lines

I think here we need simply "called with mutex not held". (Or even "may be called with mutex held or not held" if we need it, or just nothing)

and note about progress API should be somewhere in job.c, as that's implementation details.

What about "Progress API is thread safe. Can be called with job mutex held or not"?

OK, if you like, that's not critical. Still, I think that after this series the whole job API should be thread safe, which make a comment about progress API misleading: user will think "hmm.. OK, progress related functions are thread safe. Others are not?"

Quoted 4 lines
Quoted 2 lines

[...]

Quoted 1 line
Quoted 9 lines
Quoted 2 lines

I'd merge all new comments in job.h to the previous commit, as they are related to the questions risen by it.

I disagree, I think it will be a mess of functions again if we mix these one that don't need the lock held and the ones that need it.

You understand it because you got the logic of this serie, but others may not.

That's not critical.. Why it seems better in one patch for me:

For a patch like 05 I anyway have to review the whole job.c/job.h checking that everything is correct. When I see that something was not updated, it looks like a mistake to me. Than I find missed part in the next commit..

Quoted 41 lines
Quoted 40 lines
Quoted 27 lines

  void job_cancel_sync_all(void);
    /**

job.c +10 -0
index dd44fac8dd..7a3cc93f66 100644
@@ -32,12 +32,27 @@
   #include "trace/trace-root.h"
   #include "qapi/qapi-events-job.h"
   +/*
+ * The job API is composed of two categories of functions.
+ *
+ * The first includes functions used by the monitor.  The monitor is
+ * peculiar in that it accesses the block job list with job_get, and
+ * therefore needs consistency across job_get and the actual operation
+ * (e.g. job_user_cancel). To achieve this consistency, the caller
+ * calls job_lock/job_unlock itself around the whole operation.
+ *
+ *
+ * The second includes functions used by the block job drivers and

sometimes
+ * by the core block layer. These delegate the locking to the callee instead.
+ */
+

Quoted 8 lines

  /*
   * job_mutex protects the jobs list, but also makes the
   * struct job fields thread-safe.
   */
  QemuMutex job_mutex;
  +/* Protected by job_mutex */
  static QLIST_HEAD(, Job) jobs = QLIST_HEAD_INITIALIZER(jobs); /* Job State Transition Table */

So the logic is: the function that doesn't have public _locked counterpart has explicit comment that mutex should be not held. OK.

Signature · 2 lines
Best regards,
Vladimir
#18 lore raw

Re: [PATCH v8 06/20] job.h: define functions called without job lock held

Am 05/07/2022 um 12:54 schrieb Vladimir Sementsov-Ogievskiy:

Quoted 2 lines

To subject: hmm, the commit don't define any function..

mark functions called without job lock held?

#19 lore raw

Re: [PATCH v8 06/20] job.h: define functions called without job lock held

Quoted 7 lines · Emanuele Giuseppe Esposito

Am 05/07/2022 um 12:54 schrieb Vladimir Sementsov-Ogievskiy:

Quoted 2 lines

To subject: hmm, the commit don't define any function..

mark functions called without job lock held?

Yes, that's better)

Signature · 2 lines
Best regards,
Vladimir
#20 lore raw

PATCH v8 7/20 job.h: add _locked public functions

In reply to Emanuele Giuseppe Esposito

These functions will be used later when we use the job lock.

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

---
 include/qemu/job.h | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)
include/qemu/job.h +12 -3
index b714236c1a..e887f88cb2 100644
@@ -505,7 +505,10 @@ const char *job_type_str(const Job *job);
 /** Returns true if the job should not be visible to the management layer. */
 bool job_is_internal(Job *job);
 
-/** Returns whether the job is being cancelled. */
+/**
+ * Returns whether the job is being cancelled.
+ * Called with job_mutex *not* held.
+ */
 bool job_is_cancelled(Job *job);
 
 /* Same as job_is_cancelled(), but called with job lock held. */
@@ -518,13 +521,19 @@ bool job_is_cancelled_locked(Job *job);
  */
 bool job_cancel_requested(Job *job);
 
-/** Returns whether the job is in a completed state. */
+/**
+ * Returns whether the job is in a completed state.
+ * Called with job_mutex *not* held.
+ */
 bool job_is_completed(Job *job);
 
 /* Same as job_is_completed(), but called with job lock held. */
 bool job_is_completed_locked(Job *job);
 
-/** Returns whether the job is ready to be completed. */
+/**
+ * Returns whether the job is ready to be completed.
+ * Called with job_mutex *not* held.
+ */
 bool job_is_ready(Job *job);
 
 /* Same as job_is_ready(), but called with job lock held. */
Signature · 1 line
2.31.1
Reviewed-by on v8 7/20
#21 lore raw

Re: [PATCH v8 07/20] job.h: add _locked public functions

Quoted 9 lines · Emanuele Giuseppe Esposito

These functions will be used later when we use the job lock.

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

---
 include/qemu/job.h | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)
#22 lore raw

Re: [PATCH v8 07/20] job.h: add _locked public functions

In reply to Emanuele Giuseppe Esposito

First, to subject: no function is added in this commit

Second, to my comment on previous patch: so, you decided to add "not held" comment to all functions, even that have public _locked() counterpart. Not sure we really need it, but it's OK. Anyway, let's just add all these comments together with the functions themselves in patch 05.

Quoted 48 lines · Emanuele Giuseppe Esposito

These functions will be used later when we use the job lock.

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

---
  include/qemu/job.h | 15 ++++++++++++---
  1 file changed, 12 insertions(+), 3 deletions(-)
include/qemu/job.h +12 -3
index b714236c1a..e887f88cb2 100644
@@ -505,7 +505,10 @@ const char *job_type_str(const Job *job);
  /** Returns true if the job should not be visible to the management layer. */
  bool job_is_internal(Job *job);
 
-/** Returns whether the job is being cancelled. */
+/**
+ * Returns whether the job is being cancelled.
+ * Called with job_mutex *not* held.
+ */
  bool job_is_cancelled(Job *job);
 
  /* Same as job_is_cancelled(), but called with job lock held. */
@@ -518,13 +521,19 @@ bool job_is_cancelled_locked(Job *job);
   */
  bool job_cancel_requested(Job *job);
 
-/** Returns whether the job is in a completed state. */
+/**
+ * Returns whether the job is in a completed state.
+ * Called with job_mutex *not* held.
+ */
  bool job_is_completed(Job *job);
 
  /* Same as job_is_completed(), but called with job lock held. */
  bool job_is_completed_locked(Job *job);
 
-/** Returns whether the job is ready to be completed. */
+/**
+ * Returns whether the job is ready to be completed.
+ * Called with job_mutex *not* held.
+ */
  bool job_is_ready(Job *job);
 
  /* Same as job_is_ready(), but called with job lock held. */
Signature · 2 lines
Best regards,
Vladimir
#23 lore raw

PATCH v8 8/20 blockjob.h: introduce block_job _locked() APIs

In reply to Emanuele Giuseppe Esposito

Just as done with job.h, create _locked() functions in blockjob.h

These functions will be later useful when caller has already taken the lock. All blockjob _locked functions call job _locked functions.

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

---
 blockjob.c               | 52 ++++++++++++++++++++++++++++++++--------
 include/block/blockjob.h | 15 ++++++++++++
 2 files changed, 57 insertions(+), 10 deletions(-)
blockjob.c +42 -10
index 7da59a1f1c..0d59aba439 100644
@@ -44,21 +44,27 @@ static bool is_block_job(Job *job)
            job_type(job) == JOB_TYPE_STREAM;
 }
 
-BlockJob *block_job_next(BlockJob *bjob)
+BlockJob *block_job_next_locked(BlockJob *bjob)
 {
     Job *job = bjob ? &bjob->job : NULL;
     GLOBAL_STATE_CODE();
 
     do {
-        job = job_next(job);
+        job = job_next_locked(job);
     } while (job && !is_block_job(job));
 
     return job ? container_of(job, BlockJob, job) : NULL;
 }
 
-BlockJob *block_job_get(const char *id)
+BlockJob *block_job_next(BlockJob *bjob)
 {
-    Job *job = job_get(id);
+    JOB_LOCK_GUARD();
+    return block_job_next_locked(bjob);
+}
+
+BlockJob *block_job_get_locked(const char *id)
+{
+    Job *job = job_get_locked(id);
     GLOBAL_STATE_CODE();
 
     if (job && is_block_job(job)) {
@@ -68,6 +74,12 @@ BlockJob *block_job_get(const char *id)
     }
 }
 
+BlockJob *block_job_get(const char *id)
+{
+    JOB_LOCK_GUARD();
+    return block_job_get_locked(id);
+}
+
 void block_job_free(Job *job)
 {
     BlockJob *bjob = container_of(job, BlockJob, job);
@@ -256,14 +268,14 @@ static bool job_timer_pending(Job *job)
     return timer_pending(&job->sleep_timer);
 }
 
-bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
+bool block_job_set_speed_locked(BlockJob *job, int64_t speed, Error **errp)
 {
     const BlockJobDriver *drv = block_job_driver(job);
     int64_t old_speed = job->speed;
 
     GLOBAL_STATE_CODE();
 
-    if (job_apply_verb(&job->job, JOB_VERB_SET_SPEED, errp) < 0) {
+    if (job_apply_verb_locked(&job->job, JOB_VERB_SET_SPEED, errp) < 0) {
         return false;
     }
     if (speed < 0) {
@@ -277,7 +289,9 @@ bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
     job->speed = speed;
 
     if (drv->set_speed) {
+        job_unlock();
         drv->set_speed(job, speed);
+        job_lock();
     }
 
     if (speed && speed <= old_speed) {
@@ -285,18 +299,24 @@ bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
     }
 
     /* kick only if a timer is pending */
-    job_enter_cond(&job->job, job_timer_pending);
+    job_enter_cond_locked(&job->job, job_timer_pending);
 
     return true;
 }
 
+bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
+{
+    JOB_LOCK_GUARD();
+    return block_job_set_speed_locked(job, speed, errp);
+}
+
 int64_t block_job_ratelimit_get_delay(BlockJob *job, uint64_t n)
 {
     IO_CODE();
     return ratelimit_calculate_delay(&job->limit, n);
 }
 
-BlockJobInfo *block_job_query(BlockJob *job, Error **errp)
+BlockJobInfo *block_job_query_locked(BlockJob *job, Error **errp)
 {
     BlockJobInfo *info;
     uint64_t progress_current, progress_total;
@@ -320,7 +340,7 @@ BlockJobInfo *block_job_query(BlockJob *job, Error **errp)
     info->len       = progress_total;
     info->speed     = job->speed;
     info->io_status = job->iostatus;
-    info->ready     = job_is_ready(&job->job),
+    info->ready     = job_is_ready_locked(&job->job),
     info->status    = job->job.status;
     info->auto_finalize = job->job.auto_finalize;
     info->auto_dismiss  = job->job.auto_dismiss;
@@ -333,6 +353,12 @@ BlockJobInfo *block_job_query(BlockJob *job, Error **errp)
     return info;
 }
 
+BlockJobInfo *block_job_query(BlockJob *job, Error **errp)
+{
+    JOB_LOCK_GUARD();
+    return block_job_query_locked(job, errp);
+}
+
 static void block_job_iostatus_set_err(BlockJob *job, int error)
 {
     if (job->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
@@ -478,7 +504,7 @@ fail:
     return NULL;
 }
 
-void block_job_iostatus_reset(BlockJob *job)
+void block_job_iostatus_reset_locked(BlockJob *job)
 {
     GLOBAL_STATE_CODE();
     if (job->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
@@ -488,6 +514,12 @@ void block_job_iostatus_reset(BlockJob *job)
     job->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
 }
 
+void block_job_iostatus_reset(BlockJob *job)
+{
+    JOB_LOCK_GUARD();
+    block_job_iostatus_reset_locked(job);
+}
+
 void block_job_user_resume(Job *job)
 {
     BlockJob *bjob = container_of(job, BlockJob, job);
include/block/blockjob.h +15 -0
index 6525e16fd5..3959a98612 100644
@@ -92,6 +92,9 @@ typedef struct BlockJob {
  */
 BlockJob *block_job_next(BlockJob *job);
 
+/* Same as block_job_next(), but called with job lock held. */
+BlockJob *block_job_next_locked(BlockJob *job);
+
 /**
  * block_job_get:
  * @id: The id of the block job.
@@ -102,6 +105,9 @@ BlockJob *block_job_next(BlockJob *job);
  */
 BlockJob *block_job_get(const char *id);
 
+/* Same as block_job_get(), but called with job lock held. */
+BlockJob *block_job_get_locked(const char *id);
+
 /**
  * block_job_add_bdrv:
  * @job: A block job
@@ -145,6 +151,9 @@ bool block_job_has_bdrv(BlockJob *job, BlockDriverState *bs);
  */
 bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp);
 
+/* Same as block_job_set_speed(), but called with job lock held. */
+bool block_job_set_speed_locked(BlockJob *job, int64_t speed, Error **errp);
+
 /**
  * block_job_query:
  * @job: The job to get information about.
@@ -153,6 +162,9 @@ bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp);
  */
 BlockJobInfo *block_job_query(BlockJob *job, Error **errp);
 
+/* Same as block_job_query(), but called with job lock held. */
+BlockJobInfo *block_job_query_locked(BlockJob *job, Error **errp);
+
 /**
  * block_job_iostatus_reset:
  * @job: The job whose I/O status should be reset.
@@ -162,6 +174,9 @@ BlockJobInfo *block_job_query(BlockJob *job, Error **errp);
  */
 void block_job_iostatus_reset(BlockJob *job);
 
+/* Same as block_job_iostatus_reset(), but called with job lock held. */
+void block_job_iostatus_reset_locked(BlockJob *job);
+
 /*
  * block_job_get_aio_context:
  *
Signature · 1 line
2.31.1
#24 lore raw

Re: [PATCH v8 08/20] blockjob.h: introduce block_job _locked() APIs

blockjob.c static bool is_block_job(Job *job) · line 63

Quoted 6 lines · Emanuele Giuseppe Esposito
blockjob.c +4 -1
+BlockJob *block_job_next(BlockJob *bjob)
 {
-    Job *job = job_get(id);
+    JOB_LOCK_GUARD();
+    return block_job_next_locked(bjob);
+}

This seems unsafe for the same reason as job_ref(). How can the caller be sure bjob is still valid if it doesn't hold the mutex and has no reference to it?

Maybe the assumption is that the next()/get()/unref() APIs are GLOBAL_STATE_CODE(), so there can be no race between them?

#25 lore raw

Re: [PATCH v8 08/20] blockjob.h: introduce block_job _locked() APIs

Am 05/07/2022 um 09:58 schrieb Stefan Hajnoczi:

Quoted 12 lines · Emanuele Giuseppe Esposito

blockjob.c static bool is_block_job(Job *job) · line 63

Quoted 6 lines
blockjob.c +4 -1
+BlockJob *block_job_next(BlockJob *bjob)
 {
-    Job *job = job_get(id);
+    JOB_LOCK_GUARD();
+    return block_job_next_locked(bjob);
+}

This seems unsafe for the same reason as job_ref(). How can the caller be sure bjob is still valid if it doesn't hold the mutex and has no reference to it?

Quoted 3 lines

Maybe the assumption is that the next()/get()/unref() APIs are GLOBAL_STATE_CODE(), so there can be no race between them?

Same answer as job_ref. Unfortunately if we want to keep this logic in this serie that's the price to pay (even though it's just till patch 13). No assumption I would say.

Emanuele

#26 lore raw

Re: [PATCH v8 08/20] blockjob.h: introduce block_job _locked() APIs

In reply to Emanuele Giuseppe Esposito
Quoted 1 line · Emanuele Giuseppe Esposito

Just as done with job.h, create _locked() functions in blockjob.h

We modify not only blockjob.h, I'd s/blockjob.h/blockjob/ in subject.

Also, we start to introduce _locked block_job_* APIs.

Does it mean that BlockJob and Job share the global mutex to protect themselves? Than I think we should document in BlockJob struct what is protected by job_mutex.

And please, let's be consistent on whether we add or not add "with mutex held" / "with mutex not held" comments. For job API you mostly add it for each function.. Let's do same here? Same for "temporary unlock" comments.

Quoted 214 lines

These functions will be later useful when caller has already taken the lock. All blockjob _locked functions call job _locked functions.

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

---
  blockjob.c               | 52 ++++++++++++++++++++++++++++++++--------
  include/block/blockjob.h | 15 ++++++++++++
  2 files changed, 57 insertions(+), 10 deletions(-)
blockjob.c +42 -10
index 7da59a1f1c..0d59aba439 100644
@@ -44,21 +44,27 @@ static bool is_block_job(Job *job)
             job_type(job) == JOB_TYPE_STREAM;
  }
 
-BlockJob *block_job_next(BlockJob *bjob)
+BlockJob *block_job_next_locked(BlockJob *bjob)
  {
      Job *job = bjob ? &bjob->job : NULL;
      GLOBAL_STATE_CODE();
 
      do {
-        job = job_next(job);
+        job = job_next_locked(job);
      } while (job && !is_block_job(job));
 
      return job ? container_of(job, BlockJob, job) : NULL;
  }
 
-BlockJob *block_job_get(const char *id)
+BlockJob *block_job_next(BlockJob *bjob)
  {
-    Job *job = job_get(id);
+    JOB_LOCK_GUARD();
+    return block_job_next_locked(bjob);
+}
+
+BlockJob *block_job_get_locked(const char *id)
+{
+    Job *job = job_get_locked(id);
      GLOBAL_STATE_CODE();
 
      if (job && is_block_job(job)) {
@@ -68,6 +74,12 @@ BlockJob *block_job_get(const char *id)
      }
  }
 
+BlockJob *block_job_get(const char *id)
+{
+    JOB_LOCK_GUARD();
+    return block_job_get_locked(id);
+}
+
  void block_job_free(Job *job)
  {
      BlockJob *bjob = container_of(job, BlockJob, job);
@@ -256,14 +268,14 @@ static bool job_timer_pending(Job *job)
      return timer_pending(&job->sleep_timer);
  }
 
-bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
+bool block_job_set_speed_locked(BlockJob *job, int64_t speed, Error **errp)
  {
      const BlockJobDriver *drv = block_job_driver(job);
      int64_t old_speed = job->speed;
 
      GLOBAL_STATE_CODE();
 
-    if (job_apply_verb(&job->job, JOB_VERB_SET_SPEED, errp) < 0) {
+    if (job_apply_verb_locked(&job->job, JOB_VERB_SET_SPEED, errp) < 0) {
          return false;
      }
      if (speed < 0) {
@@ -277,7 +289,9 @@ bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
      job->speed = speed;
 
      if (drv->set_speed) {
+        job_unlock();
          drv->set_speed(job, speed);
+        job_lock();
      }
 
      if (speed && speed <= old_speed) {
@@ -285,18 +299,24 @@ bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
      }
 
      /* kick only if a timer is pending */
-    job_enter_cond(&job->job, job_timer_pending);
+    job_enter_cond_locked(&job->job, job_timer_pending);
 
      return true;
  }
 
+bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
+{
+    JOB_LOCK_GUARD();
+    return block_job_set_speed_locked(job, speed, errp);
+}
+
  int64_t block_job_ratelimit_get_delay(BlockJob *job, uint64_t n)
  {
      IO_CODE();
      return ratelimit_calculate_delay(&job->limit, n);
  }
 
-BlockJobInfo *block_job_query(BlockJob *job, Error **errp)
+BlockJobInfo *block_job_query_locked(BlockJob *job, Error **errp)
  {
      BlockJobInfo *info;
      uint64_t progress_current, progress_total;
@@ -320,7 +340,7 @@ BlockJobInfo *block_job_query(BlockJob *job, Error **errp)
      info->len       = progress_total;
      info->speed     = job->speed;
      info->io_status = job->iostatus;
-    info->ready     = job_is_ready(&job->job),
+    info->ready     = job_is_ready_locked(&job->job),
      info->status    = job->job.status;
      info->auto_finalize = job->job.auto_finalize;
      info->auto_dismiss  = job->job.auto_dismiss;
@@ -333,6 +353,12 @@ BlockJobInfo *block_job_query(BlockJob *job, Error **errp)
      return info;
  }
 
+BlockJobInfo *block_job_query(BlockJob *job, Error **errp)
+{
+    JOB_LOCK_GUARD();
+    return block_job_query_locked(job, errp);
+}
+
  static void block_job_iostatus_set_err(BlockJob *job, int error)
  {
      if (job->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
@@ -478,7 +504,7 @@ fail:
      return NULL;
  }
 
-void block_job_iostatus_reset(BlockJob *job)
+void block_job_iostatus_reset_locked(BlockJob *job)
  {
      GLOBAL_STATE_CODE();
      if (job->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
@@ -488,6 +514,12 @@ void block_job_iostatus_reset(BlockJob *job)
      job->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
  }
 
+void block_job_iostatus_reset(BlockJob *job)
+{
+    JOB_LOCK_GUARD();
+    block_job_iostatus_reset_locked(job);
+}
+
  void block_job_user_resume(Job *job)
  {
      BlockJob *bjob = container_of(job, BlockJob, job);
include/block/blockjob.h +15 -0
index 6525e16fd5..3959a98612 100644
@@ -92,6 +92,9 @@ typedef struct BlockJob {
   */
  BlockJob *block_job_next(BlockJob *job);
 
+/* Same as block_job_next(), but called with job lock held. */
+BlockJob *block_job_next_locked(BlockJob *job);
+
  /**
   * block_job_get:
   * @id: The id of the block job.
@@ -102,6 +105,9 @@ BlockJob *block_job_next(BlockJob *job);
   */
  BlockJob *block_job_get(const char *id);
 
+/* Same as block_job_get(), but called with job lock held. */
+BlockJob *block_job_get_locked(const char *id);
+
  /**
   * block_job_add_bdrv:
   * @job: A block job
@@ -145,6 +151,9 @@ bool block_job_has_bdrv(BlockJob *job, BlockDriverState *bs);
   */
  bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp);
 
+/* Same as block_job_set_speed(), but called with job lock held. */
+bool block_job_set_speed_locked(BlockJob *job, int64_t speed, Error **errp);
+
  /**
   * block_job_query:
   * @job: The job to get information about.
@@ -153,6 +162,9 @@ bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp);
   */
  BlockJobInfo *block_job_query(BlockJob *job, Error **errp);
 
+/* Same as block_job_query(), but called with job lock held. */
+BlockJobInfo *block_job_query_locked(BlockJob *job, Error **errp);
+
  /**
   * block_job_iostatus_reset:
   * @job: The job whose I/O status should be reset.
@@ -162,6 +174,9 @@ BlockJobInfo *block_job_query(BlockJob *job, Error **errp);
   */
  void block_job_iostatus_reset(BlockJob *job);
 
+/* Same as block_job_iostatus_reset(), but called with job lock held. */
+void block_job_iostatus_reset_locked(BlockJob *job);
+
  /*
   * block_job_get_aio_context:
   *
Signature · 2 lines
Best regards,
Vladimir
#27 lore raw

Re: [PATCH v8 08/20] blockjob.h: introduce block_job _locked() APIs

Am 05/07/2022 um 17:01 schrieb Vladimir Sementsov-Ogievskiy:

Quoted 10 lines · Emanuele Giuseppe Esposito
Quoted 1 line

Just as done with job.h, create _locked() functions in blockjob.h

We modify not only blockjob.h, I'd s/blockjob.h/blockjob/ in subject.

Also, we start to introduce _locked block_job_* APIs.

Does it mean that BlockJob and Job share the global mutex to protect themselves? Than I think we should document in BlockJob struct what is protected by job_mutex.

There is nothing in the struct (apart from Job) that is protected by the job lock. I can add a comment "Protected by job mutex" on top of Job job field?

Quoted 5 lines

And please, let's be consistent on whether we add or not add "with mutex held" / "with mutex not held" comments. For job API you mostly add it for each function.. Let's do same here? Same for "temporary unlock" comments.

Where did I miss the mutex lock/unlock comments? Yes I forgot the "temporary unlock" thing but apart from that all functions have a comment saying if they take the lock or not.

Quoted 205 lines
Quoted 203 lines

These functions will be later useful when caller has already taken the lock. All blockjob _locked functions call job _locked functions.

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

---
  blockjob.c               | 52 ++++++++++++++++++++++++++++++++-------- include/block/blockjob.h | 15 ++++++++++++

  2 files changed, 57 insertions(+), 10 deletions(-)
blockjob.c +17 -2
index 7da59a1f1c..0d59aba439 100644
@@ -44,21 +44,27 @@ static bool is_block_job(Job *job)
              job_type(job) == JOB_TYPE_STREAM;
   }
   -BlockJob *block_job_next(BlockJob *bjob)
+BlockJob *block_job_next_locked(BlockJob *bjob)
   {
       Job *job = bjob ? &bjob->job : NULL;
       GLOBAL_STATE_CODE();
         do {
-        job = job_next(job);
+        job = job_next_locked(job);
       } while (job && !is_block_job(job));
         return job ? container_of(job, BlockJob, job) : NULL;
   }
   -BlockJob *block_job_get(const char *id)
+BlockJob *block_job_next(BlockJob *bjob)
   {
-    Job *job = job_get(id);
+    JOB_LOCK_GUARD();
+    return block_job_next_locked(bjob);
+}
+
+BlockJob *block_job_get_locked(const char *id)
+{
+    Job *job = job_get_locked(id);
       GLOBAL_STATE_CODE();
         if (job && is_block_job(job)) {
@@ -68,6 +74,12 @@ BlockJob *block_job_get(const char *id)
       }
   }
   +BlockJob *block_job_get(const char *id)
+{
+    JOB_LOCK_GUARD();
+    return block_job_get_locked(id);
+}
+
   void block_job_free(Job *job)
   {
       BlockJob *bjob = container_of(job, BlockJob, job);
@@ -256,14 +268,14 @@ static bool job_timer_pending(Job *job)
       return timer_pending(&job->sleep_timer);
   }
   -bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
+bool block_job_set_speed_locked(BlockJob *job, int64_t speed, Error
 **errp)
   {
       const BlockJobDriver *drv = block_job_driver(job);
       int64_t old_speed = job->speed;
         GLOBAL_STATE_CODE();
   -    if (job_apply_verb(&job->job, JOB_VERB_SET_SPEED, errp) < 0) {
+    if (job_apply_verb_locked(&job->job, JOB_VERB_SET_SPEED, errp) <
 0) {
           return false;
       }

      if (speed < 0) {

blockjob.c +10 -2
@@ -277,7 +289,9 @@ bool block_job_set_speed(BlockJob *job, int64_t
 speed, Error **errp)
       job->speed = speed;
         if (drv->set_speed) {
+        job_unlock();
           drv->set_speed(job, speed);
+        job_lock();
       }
         if (speed && speed <= old_speed) {
@@ -285,18 +299,24 @@ bool block_job_set_speed(BlockJob *job, int64_t
 speed, Error **errp)
       }
         /* kick only if a timer is pending */
-    job_enter_cond(&job->job, job_timer_pending);
+    job_enter_cond_locked(&job->job, job_timer_pending);
         return true;
   }
   +bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
+{
+    JOB_LOCK_GUARD();
+    return block_job_set_speed_locked(job, speed, errp);
+}
+
   int64_t block_job_ratelimit_get_delay(BlockJob *job, uint64_t n)
   {
       IO_CODE();
       return ratelimit_calculate_delay(&job->limit, n);
   }
   -BlockJobInfo *block_job_query(BlockJob *job, Error **errp)
+BlockJobInfo *block_job_query_locked(BlockJob *job, Error **errp)
   {
       BlockJobInfo *info;
       uint64_t progress_current, progress_total;
@@ -320,7 +340,7 @@ BlockJobInfo *block_job_query(BlockJob *job, Error
 **errp)
       info->len       = progress_total;
       info->speed     = job->speed;
       info->io_status = job->iostatus;
-    info->ready     = job_is_ready(&job->job),
+    info->ready     = job_is_ready_locked(&job->job),
       info->status    = job->job.status;
       info->auto_finalize = job->job.auto_finalize;

      info->auto_dismiss  = job->job.auto_dismiss;

blockjob.c +5 -0
@@ -333,6 +353,12 @@ BlockJobInfo *block_job_query(BlockJob *job,
 Error **errp)
       return info;
   }
   +BlockJobInfo *block_job_query(BlockJob *job, Error **errp)
+{
+    JOB_LOCK_GUARD();
+    return block_job_query_locked(job, errp);
+}
+
   static void block_job_iostatus_set_err(BlockJob *job, int error)
   {

      if (job->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {

blockjob.c +6 -0
@@ -478,7 +504,7 @@ fail:
       return NULL;
   }
   -void block_job_iostatus_reset(BlockJob *job)
+void block_job_iostatus_reset_locked(BlockJob *job)
   {
       GLOBAL_STATE_CODE();
       if (job->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
@@ -488,6 +514,12 @@ void block_job_iostatus_reset(BlockJob *job)
       job->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
   }
   +void block_job_iostatus_reset(BlockJob *job)
+{
+    JOB_LOCK_GUARD();
+    block_job_iostatus_reset_locked(job);
+}
+
   void block_job_user_resume(Job *job)
   {
       BlockJob *bjob = container_of(job, BlockJob, job);
include/block/blockjob.h +0 -0
index 6525e16fd5..3959a98612 100644
@@ -92,6 +92,9 @@ typedef struct BlockJob {
    */
   BlockJob *block_job_next(BlockJob *job);

  +/* Same as block_job_next(), but called with job lock held. */

include/block/blockjob.h +2 -0
+BlockJob *block_job_next_locked(BlockJob *job);
+

  /**
   * block_job_get:
   * @id: The id of the block job.

include/block/blockjob.h +0 -0
@@ -102,6 +105,9 @@ BlockJob *block_job_next(BlockJob *job);
    */
   BlockJob *block_job_get(const char *id);

  +/* Same as block_job_get(), but called with job lock held. */

include/block/blockjob.h +2 -0
+BlockJob *block_job_get_locked(const char *id);
+

  /**
   * block_job_add_bdrv:
   * @job: A block job

include/block/blockjob.h +0 -0
@@ -145,6 +151,9 @@ bool block_job_has_bdrv(BlockJob *job,
 BlockDriverState *bs);
    */
   bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp);

  +/* Same as block_job_set_speed(), but called with job lock held. */ +bool block_job_set_speed_locked(BlockJob *job, int64_t speed, Error **errp);
+
  /**
   * block_job_query:
   * @job: The job to get information about.

include/block/blockjob.h +0 -0
@@ -153,6 +162,9 @@ bool block_job_set_speed(BlockJob *job, int64_t
 speed, Error **errp);
    */
   BlockJobInfo *block_job_query(BlockJob *job, Error **errp);

  +/* Same as block_job_query(), but called with job lock held. */

include/block/blockjob.h +2 -0
+BlockJobInfo *block_job_query_locked(BlockJob *job, Error **errp);
+

  /**
   * block_job_iostatus_reset:
   * @job: The job whose I/O status should be reset.

include/block/blockjob.h +0 -0
@@ -162,6 +174,9 @@ BlockJobInfo *block_job_query(BlockJob *job, Error
 **errp);
    */
   void block_job_iostatus_reset(BlockJob *job);

  +/* Same as block_job_iostatus_reset(), but called with job lock held. */

include/block/blockjob.h +2 -0
+void block_job_iostatus_reset_locked(BlockJob *job);
+

  /*
   * block_job_get_aio_context:
   *

#28 lore raw

Re: [PATCH v8 08/20] blockjob.h: introduce block_job _locked() APIs

Quoted 10 lines · Emanuele Giuseppe Esposito

Am 05/07/2022 um 17:01 schrieb Vladimir Sementsov-Ogievskiy:

Quoted 7 lines · Emanuele Giuseppe Esposito
Quoted 1 line

Just as done with job.h, create _locked() functions in blockjob.h

We modify not only blockjob.h, I'd s/blockjob.h/blockjob/ in subject.

Also, we start to introduce _locked block_job_* APIs.

Quoted 7 lines
Quoted 3 lines

Does it mean that BlockJob and Job share the global mutex to protect themselves? Than I think we should document in BlockJob struct what is protected by job_mutex.

There is nothing in the struct (apart from Job) that is protected by the job lock. I can add a comment "Protected by job mutex" on top of Job job field?

Yes, I think that's worth doing.

Other fields doesn't need the lock?

Quoted 10 lines
Quoted 6 lines

And please, let's be consistent on whether we add or not add "with mutex held" / "with mutex not held" comments. For job API you mostly add it for each function.. Let's do same here? Same for "temporary unlock" comments.

Where did I miss the mutex lock/unlock comments? Yes I forgot the "temporary unlock" thing but apart from that all functions have a comment saying if they take the lock or not.

Probably that's my impression because you add some comments in separate patches. OK.

Quoted 207 lines
Quoted 206 lines
Quoted 204 lines

These functions will be later useful when caller has already taken the lock. All blockjob _locked functions call job _locked functions.

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

---
   blockjob.c               | 52 ++++++++++++++++++++++++++++++++--------
   include/block/blockjob.h | 15 ++++++++++++
   2 files changed, 57 insertions(+), 10 deletions(-)
blockjob.c +27 -4
index 7da59a1f1c..0d59aba439 100644
@@ -44,21 +44,27 @@ static bool is_block_job(Job *job)
              job_type(job) == JOB_TYPE_STREAM;
   }
   -BlockJob *block_job_next(BlockJob *bjob)
+BlockJob *block_job_next_locked(BlockJob *bjob)
   {
       Job *job = bjob ? &bjob->job : NULL;
       GLOBAL_STATE_CODE();
         do {
-        job = job_next(job);
+        job = job_next_locked(job);
       } while (job && !is_block_job(job));
         return job ? container_of(job, BlockJob, job) : NULL;
   }
   -BlockJob *block_job_get(const char *id)
+BlockJob *block_job_next(BlockJob *bjob)
   {
-    Job *job = job_get(id);
+    JOB_LOCK_GUARD();
+    return block_job_next_locked(bjob);
+}
+
+BlockJob *block_job_get_locked(const char *id)
+{
+    Job *job = job_get_locked(id);
       GLOBAL_STATE_CODE();
         if (job && is_block_job(job)) {
@@ -68,6 +74,12 @@ BlockJob *block_job_get(const char *id)
       }
   }
   +BlockJob *block_job_get(const char *id)
+{
+    JOB_LOCK_GUARD();
+    return block_job_get_locked(id);
+}
+
   void block_job_free(Job *job)
   {
       BlockJob *bjob = container_of(job, BlockJob, job);
@@ -256,14 +268,14 @@ static bool job_timer_pending(Job *job)
       return timer_pending(&job->sleep_timer);
   }
   -bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
+bool block_job_set_speed_locked(BlockJob *job, int64_t speed, Error
 **errp)
   {
       const BlockJobDriver *drv = block_job_driver(job);
       int64_t old_speed = job->speed;
         GLOBAL_STATE_CODE();
   -    if (job_apply_verb(&job->job, JOB_VERB_SET_SPEED, errp) < 0) {
+    if (job_apply_verb_locked(&job->job, JOB_VERB_SET_SPEED, errp) <
 0) {
           return false;
       }
       if (speed < 0) {
@@ -277,7 +289,9 @@ bool block_job_set_speed(BlockJob *job, int64_t
 speed, Error **errp)
       job->speed = speed;
         if (drv->set_speed) {
+        job_unlock();
           drv->set_speed(job, speed);
+        job_lock();
       }
         if (speed && speed <= old_speed) {
@@ -285,18 +299,24 @@ bool block_job_set_speed(BlockJob *job, int64_t
 speed, Error **errp)
       }
         /* kick only if a timer is pending */
-    job_enter_cond(&job->job, job_timer_pending);
+    job_enter_cond_locked(&job->job, job_timer_pending);
         return true;
   }
   +bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
+{
+    JOB_LOCK_GUARD();
+    return block_job_set_speed_locked(job, speed, errp);
+}
+
   int64_t block_job_ratelimit_get_delay(BlockJob *job, uint64_t n)
   {
       IO_CODE();
       return ratelimit_calculate_delay(&job->limit, n);
   }
   -BlockJobInfo *block_job_query(BlockJob *job, Error **errp)
+BlockJobInfo *block_job_query_locked(BlockJob *job, Error **errp)
   {
       BlockJobInfo *info;
       uint64_t progress_current, progress_total;
@@ -320,7 +340,7 @@ BlockJobInfo *block_job_query(BlockJob *job, Error
 **errp)
       info->len       = progress_total;
       info->speed     = job->speed;
       info->io_status = job->iostatus;
-    info->ready     = job_is_ready(&job->job),
+    info->ready     = job_is_ready_locked(&job->job),
       info->status    = job->job.status;
       info->auto_finalize = job->job.auto_finalize;

      info->auto_dismiss  = job->job.auto_dismiss;

blockjob.c +11 -0
@@ -333,6 +353,12 @@ BlockJobInfo *block_job_query(BlockJob *job,
 Error **errp)
       return info;
   }
   +BlockJobInfo *block_job_query(BlockJob *job, Error **errp)
+{
+    JOB_LOCK_GUARD();
+    return block_job_query_locked(job, errp);
+}
+
   static void block_job_iostatus_set_err(BlockJob *job, int error)
   {
       if (job->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
@@ -478,7 +504,7 @@ fail:
       return NULL;
   }
   -void block_job_iostatus_reset(BlockJob *job)
+void block_job_iostatus_reset_locked(BlockJob *job)
   {
       GLOBAL_STATE_CODE();
       if (job->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
@@ -488,6 +514,12 @@ void block_job_iostatus_reset(BlockJob *job)
       job->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
   }
   +void block_job_iostatus_reset(BlockJob *job)
+{
+    JOB_LOCK_GUARD();
+    block_job_iostatus_reset_locked(job);
+}
+
   void block_job_user_resume(Job *job)
   {
       BlockJob *bjob = container_of(job, BlockJob, job);
include/block/blockjob.h +8 -0
index 6525e16fd5..3959a98612 100644
@@ -92,6 +92,9 @@ typedef struct BlockJob {
    */
   BlockJob *block_job_next(BlockJob *job);
   +/* Same as block_job_next(), but called with job lock held. */
+BlockJob *block_job_next_locked(BlockJob *job);
+
   /**
    * block_job_get:
    * @id: The id of the block job.
@@ -102,6 +105,9 @@ BlockJob *block_job_next(BlockJob *job);
    */
   BlockJob *block_job_get(const char *id);
   +/* Same as block_job_get(), but called with job lock held. */
+BlockJob *block_job_get_locked(const char *id);
+
   /**
    * block_job_add_bdrv:
    * @job: A block job
@@ -145,6 +151,9 @@ bool block_job_has_bdrv(BlockJob *job,
 BlockDriverState *bs);
    */
   bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp);
   +/* Same as block_job_set_speed(), but called with job lock held. */
+bool block_job_set_speed_locked(BlockJob *job, int64_t speed, Error
 **errp);
+
   /**
    * block_job_query:
    * @job: The job to get information about.
@@ -153,6 +162,9 @@ bool block_job_set_speed(BlockJob *job, int64_t
 speed, Error **errp);
    */
   BlockJobInfo *block_job_query(BlockJob *job, Error **errp);
   +/* Same as block_job_query(), but called with job lock held. */
+BlockJobInfo *block_job_query_locked(BlockJob *job, Error **errp);
+
   /**
    * block_job_iostatus_reset:
    * @job: The job whose I/O status should be reset.
@@ -162,6 +174,9 @@ BlockJobInfo *block_job_query(BlockJob *job, Error
 **errp);
    */
   void block_job_iostatus_reset(BlockJob *job);
   +/* Same as block_job_iostatus_reset(), but called with job lock

held. */

include/block/blockjob.h +2 -0
+void block_job_iostatus_reset_locked(BlockJob *job);
+
   /*
    * block_job_get_aio_context:
    *
Signature · 2 lines
Best regards,
Vladimir
#29 lore raw

Re: [PATCH v8 08/20] blockjob.h: introduce block_job _locked() APIs

Am 06/07/2022 um 14:23 schrieb Vladimir Sementsov-Ogievskiy:

Quoted 15 lines · Emanuele Giuseppe Esposito
Quoted 14 lines

Am 05/07/2022 um 17:01 schrieb Vladimir Sementsov-Ogievskiy:

Quoted 10 lines · Emanuele Giuseppe Esposito
Quoted 1 line

Just as done with job.h, create _locked() functions in blockjob.h

We modify not only blockjob.h, I'd s/blockjob.h/blockjob/ in subject.

Also, we start to introduce _locked block_job_* APIs.

Does it mean that BlockJob and Job share the global mutex to protect themselves? Than I think we should document in BlockJob struct what is protected by job_mutex.

Quoted 8 lines
Quoted 3 lines

There is nothing in the struct (apart from Job) that is protected by the job lock. I can add a comment "Protected by job mutex" on top of Job job field?

Yes, I think that's worth doing.

Other fields doesn't need the lock?

Well I didn't plan to actually look at it but now that you ask:

/** needs protection, so it can go under job lock */ BlockDeviceIoStatus iostatus;

/** mostly under lock, not sure when it is called as notifier callback though. I think they are GLOBAL_STATE, what do you think? */ int64_t speed;

/** thread safe API */
RateLimit limit;

/** I think it's also thread safe */
Error *blocker;

/* always under job lock */
Notifier finalize_cancelled_notifier;
Notifier finalize_completed_notifier;
Notifier pending_notifier;
Notifier ready_notifier;
Notifier idle_notifier;

Not sure about blockjob->speed though.

Emanuele

#30 lore raw

Re: [PATCH v8 08/20] blockjob.h: introduce block_job _locked() APIs

Am 06/07/2022 um 14:36 schrieb Emanuele Giuseppe Esposito:

Quoted 35 lines

Am 06/07/2022 um 14:23 schrieb Vladimir Sementsov-Ogievskiy:

Quoted 15 lines · Emanuele Giuseppe Esposito
Quoted 14 lines

Am 05/07/2022 um 17:01 schrieb Vladimir Sementsov-Ogievskiy:

Quoted 10 lines · Emanuele Giuseppe Esposito
Quoted 1 line

Just as done with job.h, create _locked() functions in blockjob.h

We modify not only blockjob.h, I'd s/blockjob.h/blockjob/ in subject.

Also, we start to introduce _locked block_job_* APIs.

Does it mean that BlockJob and Job share the global mutex to protect themselves? Than I think we should document in BlockJob struct what is protected by job_mutex.

Quoted 8 lines
Quoted 3 lines

There is nothing in the struct (apart from Job) that is protected by the job lock. I can add a comment "Protected by job mutex" on top of Job job field?

Yes, I think that's worth doing.

Other fields doesn't need the lock?

Well I didn't plan to actually look at it but now that you ask:

/** needs protection, so it can go under job lock */ BlockDeviceIoStatus iostatus;

/** mostly under lock, not sure when it is called as notifier callback though. I think they are GLOBAL_STATE, what do you think? */ int64_t speed;

Quoted 7 lines

/** thread safe API */
RateLimit limit;

/** I think it's also thread safe */
Error *blocker;

/* always under job lock */

Actually that's wrong, they are just set once and never modified.

And GSList *nodes; is also always called under GS.

So there's only iostatus to protect and maybe speed.

Emanuele

Quoted 10 lines

Notifier finalize_cancelled_notifier;
Notifier finalize_completed_notifier;
Notifier pending_notifier;
Notifier ready_notifier;
Notifier idle_notifier;

Not sure about blockjob->speed though.

Emanuele

#31 lore raw

Re: [PATCH v8 08/20] blockjob.h: introduce block_job _locked() APIs

Quoted 37 lines · Emanuele Giuseppe Esposito

Am 06/07/2022 um 14:36 schrieb Emanuele Giuseppe Esposito:

Quoted 34 lines

Am 06/07/2022 um 14:23 schrieb Vladimir Sementsov-Ogievskiy:

Quoted 15 lines · Emanuele Giuseppe Esposito
Quoted 14 lines

Am 05/07/2022 um 17:01 schrieb Vladimir Sementsov-Ogievskiy:

Quoted 10 lines · Emanuele Giuseppe Esposito
Quoted 1 line

Just as done with job.h, create _locked() functions in blockjob.h

We modify not only blockjob.h, I'd s/blockjob.h/blockjob/ in subject.

Also, we start to introduce _locked block_job_* APIs.

Does it mean that BlockJob and Job share the global mutex to protect themselves? Than I think we should document in BlockJob struct what is protected by job_mutex.

Quoted 8 lines
Quoted 3 lines

There is nothing in the struct (apart from Job) that is protected by the job lock. I can add a comment "Protected by job mutex" on top of Job job field?

Yes, I think that's worth doing.

Other fields doesn't need the lock?

Well I didn't plan to actually look at it but now that you ask:

/** needs protection, so it can go under job lock */ BlockDeviceIoStatus iostatus;

/** mostly under lock, not sure when it is called as notifier callback though. I think they are GLOBAL_STATE, what do you think? */ int64_t speed;

Hmm I doubt that notifier callbacks are always called from GS code.. But reading .speed to send an event doesn't seem to worth any locking.

Quoted 14 lines
Quoted 8 lines

/** thread safe API */
RateLimit limit;

/** I think it's also thread safe */
Error *blocker;

/* always under job lock */

Actually that's wrong, they are just set once and never modified.

And GSList *nodes; is also always called under GS.

So there's only iostatus to protect and maybe speed.

Signature · 2 lines
Best regards,
Vladimir
#32 lore raw

PATCH v8 9/20 blockjob: rename notifier callbacks as _locked

In reply to Emanuele Giuseppe Esposito

They all are called with job_lock held, in job_event_*_locked()

---
 blockjob.c | 25 +++++++++++++++----------
 1 file changed, 15 insertions(+), 10 deletions(-)
blockjob.c +15 -10
index 0d59aba439..70952879d8 100644
@@ -247,7 +247,8 @@ int block_job_add_bdrv(BlockJob *job, const char *name, BlockDriverState *bs,
     return 0;
 }
 
-static void block_job_on_idle(Notifier *n, void *opaque)
+/* Called with job_mutex lock held. */
+static void block_job_on_idle_locked(Notifier *n, void *opaque)
 {
     aio_wait_kick();
 }
@@ -367,7 +368,8 @@ static void block_job_iostatus_set_err(BlockJob *job, int error)
     }
 }
 
-static void block_job_event_cancelled(Notifier *n, void *opaque)
+/* Called with job_mutex lock held. */
+static void block_job_event_cancelled_locked(Notifier *n, void *opaque)
 {
     BlockJob *job = opaque;
     uint64_t progress_current, progress_total;
@@ -386,7 +388,8 @@ static void block_job_event_cancelled(Notifier *n, void *opaque)
                                         job->speed);
 }
 
-static void block_job_event_completed(Notifier *n, void *opaque)
+/* Called with job_mutex lock held. */
+static void block_job_event_completed_locked(Notifier *n, void *opaque)
 {
     BlockJob *job = opaque;
     const char *msg = NULL;
@@ -412,7 +415,8 @@ static void block_job_event_completed(Notifier *n, void *opaque)
                                         msg);
 }
 
-static void block_job_event_pending(Notifier *n, void *opaque)
+/* Called with job_mutex lock held. */
+static void block_job_event_pending_locked(Notifier *n, void *opaque)
 {
     BlockJob *job = opaque;
 
@@ -424,7 +428,8 @@ static void block_job_event_pending(Notifier *n, void *opaque)
                                       job->job.id);
 }
 
-static void block_job_event_ready(Notifier *n, void *opaque)
+/* Called with job_mutex lock held. */
+static void block_job_event_ready_locked(Notifier *n, void *opaque)
 {
     BlockJob *job = opaque;
     uint64_t progress_current, progress_total;
@@ -469,11 +474,11 @@ void *block_job_create(const char *job_id, const BlockJobDriver *driver,
 
     ratelimit_init(&job->limit);
 
-    job->finalize_cancelled_notifier.notify = block_job_event_cancelled;
-    job->finalize_completed_notifier.notify = block_job_event_completed;
-    job->pending_notifier.notify = block_job_event_pending;
-    job->ready_notifier.notify = block_job_event_ready;
-    job->idle_notifier.notify = block_job_on_idle;
+    job->finalize_cancelled_notifier.notify = block_job_event_cancelled_locked;
+    job->finalize_completed_notifier.notify = block_job_event_completed_locked;
+    job->pending_notifier.notify = block_job_event_pending_locked;
+    job->ready_notifier.notify = block_job_event_ready_locked;
+    job->idle_notifier.notify = block_job_on_idle_locked;
 
     notifier_list_add(&job->job.on_finalize_cancelled,
                       &job->finalize_cancelled_notifier);
Signature · 1 line
2.31.1
#34 lore raw

PATCH v8 10/20 jobs: add job lock in find_* functions

In reply to Emanuele Giuseppe Esposito

Both blockdev.c and job-qmp.c have TOC/TOU conditions, because they first search for the job and then perform an action on it. Therefore, we need to do the search + action under the same job mutex critical section.

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

---
 blockdev.c | 67 +++++++++++++++++++++++++++++++++++++-----------------
 job-qmp.c  | 55 ++++++++++++++++++++++++++++++--------------
 2 files changed, 84 insertions(+), 38 deletions(-)
blockdev.c +46 -21
index 9230888e34..71f793c4ab 100644
@@ -3302,9 +3302,13 @@ out:
     aio_context_release(aio_context);
 }
 
-/* Get a block job using its ID and acquire its AioContext */
-static BlockJob *find_block_job(const char *id, AioContext **aio_context,
-                                Error **errp)
+/*
+ * Get a block job using its ID and acquire its AioContext.
+ * Called with job_mutex held.
+ */
+static BlockJob *find_block_job_locked(const char *id,
+                                       AioContext **aio_context,
+                                       Error **errp)
 {
     BlockJob *job;
 
@@ -3312,7 +3316,7 @@ static BlockJob *find_block_job(const char *id, AioContext **aio_context,
 
     *aio_context = NULL;
 
-    job = block_job_get(id);
+    job = block_job_get_locked(id);
 
     if (!job) {
         error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
@@ -3329,13 +3333,16 @@ static BlockJob *find_block_job(const char *id, AioContext **aio_context,
 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
 {
     AioContext *aio_context;
-    BlockJob *job = find_block_job(device, &aio_context, errp);
+    BlockJob *job;
+
+    JOB_LOCK_GUARD();
+    job = find_block_job_locked(device, &aio_context, errp);
 
     if (!job) {
         return;
     }
 
-    block_job_set_speed(job, speed, errp);
+    block_job_set_speed_locked(job, speed, errp);
     aio_context_release(aio_context);
 }
 
@@ -3343,7 +3350,10 @@ void qmp_block_job_cancel(const char *device,
                           bool has_force, bool force, Error **errp)
 {
     AioContext *aio_context;
-    BlockJob *job = find_block_job(device, &aio_context, errp);
+    BlockJob *job;
+
+    JOB_LOCK_GUARD();
+    job = find_block_job_locked(device, &aio_context, errp);
 
     if (!job) {
         return;
@@ -3353,14 +3363,14 @@ void qmp_block_job_cancel(const char *device,
         force = false;
     }
 
-    if (job_user_paused(&job->job) && !force) {
+    if (job_user_paused_locked(&job->job) && !force) {
         error_setg(errp, "The block job for device '%s' is currently paused",
                    device);
         goto out;
     }
 
     trace_qmp_block_job_cancel(job);
-    job_user_cancel(&job->job, force, errp);
+    job_user_cancel_locked(&job->job, force, errp);
 out:
     aio_context_release(aio_context);
 }
@@ -3368,57 +3378,69 @@ out:
 void qmp_block_job_pause(const char *device, Error **errp)
 {
     AioContext *aio_context;
-    BlockJob *job = find_block_job(device, &aio_context, errp);
+    BlockJob *job;
+
+    JOB_LOCK_GUARD();
+    job = find_block_job_locked(device, &aio_context, errp);
 
     if (!job) {
         return;
     }
 
     trace_qmp_block_job_pause(job);
-    job_user_pause(&job->job, errp);
+    job_user_pause_locked(&job->job, errp);
     aio_context_release(aio_context);
 }
 
 void qmp_block_job_resume(const char *device, Error **errp)
 {
     AioContext *aio_context;
-    BlockJob *job = find_block_job(device, &aio_context, errp);
+    BlockJob *job;
+
+    JOB_LOCK_GUARD();
+    job = find_block_job_locked(device, &aio_context, errp);
 
     if (!job) {
         return;
     }
 
     trace_qmp_block_job_resume(job);
-    job_user_resume(&job->job, errp);
+    job_user_resume_locked(&job->job, errp);
     aio_context_release(aio_context);
 }
 
 void qmp_block_job_complete(const char *device, Error **errp)
 {
     AioContext *aio_context;
-    BlockJob *job = find_block_job(device, &aio_context, errp);
+    BlockJob *job;
+
+    JOB_LOCK_GUARD();
+    job = find_block_job_locked(device, &aio_context, errp);
 
     if (!job) {
         return;
     }
 
     trace_qmp_block_job_complete(job);
-    job_complete(&job->job, errp);
+    job_complete_locked(&job->job, errp);
     aio_context_release(aio_context);
 }
 
 void qmp_block_job_finalize(const char *id, Error **errp)
 {
     AioContext *aio_context;
-    BlockJob *job = find_block_job(id, &aio_context, errp);
+    BlockJob *job;
+
+    JOB_LOCK_GUARD();
+    job = find_block_job_locked(id, &aio_context, errp);
 
     if (!job) {
         return;
     }
 
     trace_qmp_block_job_finalize(job);
-    job_ref(&job->job);
-    job_finalize(&job->job, errp);
+    job_ref_locked(&job->job);
+    job_finalize_locked(&job->job, errp);
 
     /*
      * Job's context might have changed via job_finalize (and job_txn_apply
@@ -3426,23 +3448,26 @@ void qmp_block_job_finalize(const char *id, Error **errp)
      * one.
      */
     aio_context = block_job_get_aio_context(job);
-    job_unref(&job->job);
+    job_unref_locked(&job->job);
     aio_context_release(aio_context);
 }
 
 void qmp_block_job_dismiss(const char *id, Error **errp)
 {
     AioContext *aio_context;
-    BlockJob *bjob = find_block_job(id, &aio_context, errp);
+    BlockJob *bjob;
     Job *job;
 
+    JOB_LOCK_GUARD();
+    bjob = find_block_job_locked(id, &aio_context, errp);
+
     if (!bjob) {
         return;
     }
 
     trace_qmp_block_job_dismiss(bjob);
     job = &bjob->job;
-    job_dismiss(&job, errp);
+    job_dismiss_locked(&job, errp);
     aio_context_release(aio_context);
 }
 
job-qmp.c +38 -17

144 lines not on this page · raw message

Signature · 1 line
2.31.1
Reviewed-by on v8 10/20
#35 lore raw

Re: [PATCH v8 10/20] jobs: add job lock in find_* functions

Quoted 5 lines · Emanuele Giuseppe Esposito

Both blockdev.c and job-qmp.c have TOC/TOU conditions, because they first search for the job and then perform an action on it. Therefore, we need to do the search + action under the same job mutex critical section.

Quoted 8 lines

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

---
 blockdev.c | 67 +++++++++++++++++++++++++++++++++++++-----------------
 job-qmp.c  | 55 ++++++++++++++++++++++++++++++--------------
 2 files changed, 84 insertions(+), 38 deletions(-)
#36 lore raw

PATCH v8 11/20 jobs: use job locks also in the unit tests

In reply to Emanuele Giuseppe Esposito

Add missing job synchronization in the unit tests, with explicit locks.

We are deliberately using _locked functions wrapped by a guard instead of a normal call because the normal call will be removed in future, as the only usage is limited to the tests.

In other words, if a function like job_pause() is/will be only used in tests to avoid:

WITH_JOB_LOCK_GUARD(){
    job_pause_locked();
}

then it is not worth keeping job_pause(), and just use the guard.

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

---
 tests/unit/test-bdrv-drain.c     | 76 +++++++++++++++++---------
 tests/unit/test-block-iothread.c |  8 ++-
 tests/unit/test-blockjob-txn.c   | 24 +++++---
 tests/unit/test-blockjob.c       | 94 ++++++++++++++++++++++++--------
 4 files changed, 141 insertions(+), 61 deletions(-)
tests/unit/test-bdrv-drain.c +49 -27
index 36be84ae55..0db056ea63 100644
@@ -943,61 +943,83 @@ static void test_blockjob_common_drain_node(enum drain_type drain_type,
         }
     }
 
-    g_assert_cmpint(job->job.pause_count, ==, 0);
-    g_assert_false(job->job.paused);
-    g_assert_true(tjob->running);
-    g_assert_true(job->job.busy); /* We're in qemu_co_sleep_ns() */
+    WITH_JOB_LOCK_GUARD() {
+        g_assert_cmpint(job->job.pause_count, ==, 0);
+        g_assert_false(job->job.paused);
+        g_assert_true(tjob->running);
+        g_assert_true(job->job.busy); /* We're in qemu_co_sleep_ns() */
+    }
 
     do_drain_begin_unlocked(drain_type, drain_bs);
 
-    if (drain_type == BDRV_DRAIN_ALL) {
-        /* bdrv_drain_all() drains both src and target */
-        g_assert_cmpint(job->job.pause_count, ==, 2);
-    } else {
-        g_assert_cmpint(job->job.pause_count, ==, 1);
+    WITH_JOB_LOCK_GUARD() {
+        if (drain_type == BDRV_DRAIN_ALL) {
+            /* bdrv_drain_all() drains both src and target */
+            g_assert_cmpint(job->job.pause_count, ==, 2);
+        } else {
+            g_assert_cmpint(job->job.pause_count, ==, 1);
+        }
+        g_assert_true(job->job.paused);
+        g_assert_false(job->job.busy); /* The job is paused */
     }
-    g_assert_true(job->job.paused);
-    g_assert_false(job->job.busy); /* The job is paused */
 
     do_drain_end_unlocked(drain_type, drain_bs);
 
     if (use_iothread) {
-        /* paused is reset in the I/O thread, wait for it */
+        /*
+         * Here we are waiting for the paused status to change,
+         * so don't bother protecting the read every time.
+         *
+         * paused is reset in the I/O thread, wait for it
+         */
         while (job->job.paused) {
             aio_poll(qemu_get_aio_context(), false);
         }
     }
 
-    g_assert_cmpint(job->job.pause_count, ==, 0);
-    g_assert_false(job->job.paused);
-    g_assert_true(job->job.busy); /* We're in qemu_co_sleep_ns() */
+    WITH_JOB_LOCK_GUARD() {
+        g_assert_cmpint(job->job.pause_count, ==, 0);
+        g_assert_false(job->job.paused);
+        g_assert_true(job->job.busy); /* We're in qemu_co_sleep_ns() */
+    }
 
     do_drain_begin_unlocked(drain_type, target);
 
-    if (drain_type == BDRV_DRAIN_ALL) {
-        /* bdrv_drain_all() drains both src and target */
-        g_assert_cmpint(job->job.pause_count, ==, 2);
-    } else {
-        g_assert_cmpint(job->job.pause_count, ==, 1);
+    WITH_JOB_LOCK_GUARD() {
+        if (drain_type == BDRV_DRAIN_ALL) {
+            /* bdrv_drain_all() drains both src and target */
+            g_assert_cmpint(job->job.pause_count, ==, 2);
+        } else {
+            g_assert_cmpint(job->job.pause_count, ==, 1);
+        }
+        g_assert_true(job->job.paused);
+        g_assert_false(job->job.busy); /* The job is paused */
     }
-    g_assert_true(job->job.paused);
-    g_assert_false(job->job.busy); /* The job is paused */
 
     do_drain_end_unlocked(drain_type, target);
 
     if (use_iothread) {
-        /* paused is reset in the I/O thread, wait for it */
+        /*
+         * Here we are waiting for the paused status to change,
+         * so don't bother protecting the read every time.
+         *
+         * paused is reset in the I/O thread, wait for it
+         */
         while (job->job.paused) {
             aio_poll(qemu_get_aio_context(), false);
         }
     }
 
-    g_assert_cmpint(job->job.pause_count, ==, 0);
-    g_assert_false(job->job.paused);
-    g_assert_true(job->job.busy); /* We're in qemu_co_sleep_ns() */
+    WITH_JOB_LOCK_GUARD() {
+        g_assert_cmpint(job->job.pause_count, ==, 0);
+        g_assert_false(job->job.paused);
+        g_assert_true(job->job.busy); /* We're in qemu_co_sleep_ns() */
+    }
 
     aio_context_acquire(ctx);
-    ret = job_complete_sync(&job->job, &error_abort);
+    WITH_JOB_LOCK_GUARD() {
+        ret = job_complete_sync_locked(&job->job, &error_abort);
+    }
     g_assert_cmpint(ret, ==, (result == TEST_JOB_SUCCESS ? 0 : -EIO));
 
     if (use_iothread) {
tests/unit/test-block-iothread.c +6 -2
index 94718c9319..89e7f0fffb 100644
@@ -456,7 +456,9 @@ static void test_attach_blockjob(void)
     }
 
     aio_context_acquire(ctx);
-    job_complete_sync(&tjob->common.job, &error_abort);
+    WITH_JOB_LOCK_GUARD() {
+        job_complete_sync_locked(&tjob->common.job, &error_abort);
+    }
     blk_set_aio_context(blk, qemu_get_aio_context(), &error_abort);
     aio_context_release(ctx);
 
@@ -630,7 +632,9 @@ static void test_propagate_mirror(void)
                  BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,
                  false, "filter_node", MIRROR_COPY_MODE_BACKGROUND,
                  &error_abort);
-    job = job_get("job0");
+    WITH_JOB_LOCK_GUARD() {
+        job = job_get_locked("job0");
+    }
     filter = bdrv_find_node("filter_node");
 
     /* Change the AioContext of src */
tests/unit/test-blockjob-txn.c +15 -9
index c69028b450..d3b0bb24be 100644
@@ -116,8 +116,10 @@ static void test_single_job(int expected)
     job = test_block_job_start(1, true, expected, &result, txn);
     job_start(&job->job);
 
-    if (expected == -ECANCELED) {
-        job_cancel(&job->job, false);
+    WITH_JOB_LOCK_GUARD() {
+        if (expected == -ECANCELED) {
+            job_cancel_locked(&job->job, false);
+        }
     }
 
     while (result == -EINPROGRESS) {
@@ -160,13 +162,15 @@ static void test_pair_jobs(int expected1, int expected2)
     /* Release our reference now to trigger as many nice
      * use-after-free bugs as possible.
      */
-    job_txn_unref(txn);
+    WITH_JOB_LOCK_GUARD() {
+        job_txn_unref_locked(txn);
 
-    if (expected1 == -ECANCELED) {
-        job_cancel(&job1->job, false);
-    }
-    if (expected2 == -ECANCELED) {
-        job_cancel(&job2->job, false);
+        if (expected1 == -ECANCELED) {
+            job_cancel_locked(&job1->job, false);
+        }
+        if (expected2 == -ECANCELED) {
+            job_cancel_locked(&job2->job, false);
+        }
     }
 
     while (result1 == -EINPROGRESS || result2 == -EINPROGRESS) {
@@ -219,7 +223,9 @@ static void test_pair_jobs_fail_cancel_race(void)
     job_start(&job1->job);
     job_start(&job2->job);
 
-    job_cancel(&job1->job, false);
+    WITH_JOB_LOCK_GUARD() {
+        job_cancel_locked(&job1->job, false);
+    }
 
     /* Now make job2 finish before the main loop kicks jobs.  This simulates
      * the race between a pending kick and another job completing.
tests/unit/test-blockjob.c +71 -23

198 lines not on this page · raw message

Signature · 1 line
2.31.1
Reviewed-by on v8 11/20
#37 lore raw

Re: [PATCH v8 11/20] jobs: use job locks also in the unit tests

Quoted 19 lines · Emanuele Giuseppe Esposito

Add missing job synchronization in the unit tests, with explicit locks.

We are deliberately using _locked functions wrapped by a guard instead of a normal call because the normal call will be removed in future, as the only usage is limited to the tests.

In other words, if a function like job_pause() is/will be only used in tests to avoid:

WITH_JOB_LOCK_GUARD(){
    job_pause_locked();
}

then it is not worth keeping job_pause(), and just use the guard.

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

Quoted 7 lines
---
 tests/unit/test-bdrv-drain.c     | 76 +++++++++++++++++---------
 tests/unit/test-block-iothread.c |  8 ++-
 tests/unit/test-blockjob-txn.c   | 24 +++++---
 tests/unit/test-blockjob.c       | 94 ++++++++++++++++++++++++--------
 4 files changed, 141 insertions(+), 61 deletions(-)
#38 lore raw

PATCH v8 12/20 block/mirror.c: use of job helpers in drivers to avoid TOC/TOU

In reply to Emanuele Giuseppe Esposito

Once job lock is used and aiocontext is removed, mirror has to perform job operations under the same critical section, using the helpers prepared in previous commit.

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

---
 block/mirror.c | 19 ++++++++++++++-----
 1 file changed, 14 insertions(+), 5 deletions(-)
block/mirror.c +14 -5
index d8ecb9efa2..b38676e19d 100644
@@ -654,9 +654,13 @@ static int mirror_exit_common(Job *job)
     BlockDriverState *target_bs;
     BlockDriverState *mirror_top_bs;
     Error *local_err = NULL;
-    bool abort = job->ret < 0;
+    bool abort;
     int ret = 0;
 
+    WITH_JOB_LOCK_GUARD() {
+        abort = job->ret < 0;
+    }
+
     if (s->prepared) {
         return 0;
     }
@@ -1152,8 +1156,10 @@ static void mirror_complete(Job *job, Error **errp)
     s->should_complete = true;
 
     /* If the job is paused, it will be re-entered when it is resumed */
-    if (!job->paused) {
-        job_enter(job);
+    WITH_JOB_LOCK_GUARD() {
+        if (!job->paused) {
+            job_enter_cond_locked(job, NULL);
+        }
     }
 }
 
@@ -1173,8 +1179,11 @@ static bool mirror_drained_poll(BlockJob *job)
      * from one of our own drain sections, to avoid a deadlock waiting for
      * ourselves.
      */
-    if (!s->common.job.paused && !job_is_cancelled(&job->job) && !s->in_drain) {
-        return true;
+    WITH_JOB_LOCK_GUARD() {
+        if (!s->common.job.paused && !job_is_cancelled_locked(&job->job)
+            && !s->in_drain) {
+            return true;
+        }
     }
 
     return !!s->in_flight;
Signature · 1 line
2.31.1
#39 lore raw

PATCH v8 13/20 jobs: group together API calls under the same job lock

In reply to Emanuele Giuseppe Esposito

Now that the API offers also _locked() functions, take advantage of it and give also the caller control to take the lock and call _locked functions.

This makes sense especially when we have for loops, because it makes no sense to have:

for(job = job_next(); ...)

where each job_next() takes the lock internally.
Instead we want

JOB_LOCK_GUARD();
for(job = job_next_locked(); ...)

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

---
 block.c            | 20 +++++++++++-------
 blockdev.c         | 12 ++++++++---
 blockjob.c         | 52 +++++++++++++++++++++++++++++++---------------
 job-qmp.c          |  4 +++-
 job.c              | 13 +++++++-----
 monitor/qmp-cmds.c |  7 +++++--
 qemu-img.c         | 41 +++++++++++++++++++++---------------
 7 files changed, 97 insertions(+), 52 deletions(-)
block.c +13 -7
index 2c00dddd80..d0db104d71 100644
@@ -4978,9 +4978,12 @@ static void bdrv_close(BlockDriverState *bs)
 
 void bdrv_close_all(void)
 {
-    assert(job_next(NULL) == NULL);
     GLOBAL_STATE_CODE();
 
+    WITH_JOB_LOCK_GUARD() {
+        assert(job_next_locked(NULL) == NULL);
+    }
+
     /* Drop references from requests still in flight, such as canceled block
      * jobs whose AIO context has not been polled yet */
     bdrv_drain_all();
@@ -6165,13 +6168,16 @@ XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
         }
     }
 
-    for (job = block_job_next(NULL); job; job = block_job_next(job)) {
-        GSList *el;
+    WITH_JOB_LOCK_GUARD() {
+        for (job = block_job_next_locked(NULL); job;
+             job = block_job_next_locked(job)) {
+            GSList *el;
 
-        xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
-                           job->job.id);
-        for (el = job->nodes; el; el = el->next) {
-            xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
+            xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
+                                job->job.id);
+            for (el = job->nodes; el; el = el->next) {
+                xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
+            }
         }
     }
 
blockdev.c +9 -3
index 71f793c4ab..5b79093155 100644
@@ -150,12 +150,15 @@ void blockdev_mark_auto_del(BlockBackend *blk)
         return;
     }
 
-    for (job = block_job_next(NULL); job; job = block_job_next(job)) {
+    JOB_LOCK_GUARD();
+
+    for (job = block_job_next_locked(NULL); job;
+         job = block_job_next_locked(job)) {
         if (block_job_has_bdrv(job, blk_bs(blk))) {
             AioContext *aio_context = job->job.aio_context;
             aio_context_acquire(aio_context);
 
-            job_cancel(&job->job, false);
+            job_cancel_locked(&job->job, false);
 
             aio_context_release(aio_context);
         }
@@ -3745,7 +3748,10 @@ BlockJobInfoList *qmp_query_block_jobs(Error **errp)
     BlockJobInfoList *head = NULL, **tail = &head;
     BlockJob *job;
 
-    for (job = block_job_next(NULL); job; job = block_job_next(job)) {
+    JOB_LOCK_GUARD();
+
+    for (job = block_job_next_locked(NULL); job;
+         job = block_job_next_locked(job)) {
         BlockJobInfo *value;
         AioContext *aio_context;
 
blockjob.c +35 -17

94 lines not on this page · raw message

job-qmp.c +3 -1
index 8ce3b7965e..6eff7016b2 100644
@@ -192,7 +192,9 @@ JobInfoList *qmp_query_jobs(Error **errp)
     JobInfoList *head = NULL, **tail = &head;
     Job *job;
 
-    for (job = job_next(NULL); job; job = job_next(job)) {
+    JOB_LOCK_GUARD();
+
+    for (job = job_next_locked(NULL); job; job = job_next_locked(job)) {
         JobInfo *value;
         AioContext *aio_context;
 
job.c +8 -5
index 7a3cc93f66..19d711dc73 100644
@@ -1045,11 +1045,14 @@ static void job_completed_txn_abort_locked(Job *job)
 /* Called with job_mutex held, but releases it temporarily */
 static int job_prepare_locked(Job *job)
 {
+    int ret;
+
     GLOBAL_STATE_CODE();
     if (job->ret == 0 && job->driver->prepare) {
         job_unlock();
-        job->ret = job->driver->prepare(job);
+        ret = job->driver->prepare(job);
         job_lock();
+        job->ret = ret;
         job_update_rc_locked(job);
     }
     return job->ret;
@@ -1235,10 +1238,10 @@ void job_cancel_locked(Job *job, bool force)
          * job_cancel_async() ignores soft-cancel requests for jobs
          * that are already done (i.e. deferred to the main loop).  We
          * have to check again whether the job is really cancelled.
-         * (job_cancel_requested() and job_is_cancelled() are equivalent
-         * here, because job_cancel_async() will make soft-cancel
-         * requests no-ops when deferred_to_main_loop is true.  We
-         * choose to call job_is_cancelled() to show that we invoke
+         * (job_cancel_requested_locked() and job_is_cancelled_locked()
+         * are equivalent here, because job_cancel_async() will
+         * make soft-cancel requests no-ops when deferred_to_main_loop is true.
+         * We choose to call job_is_cancelled_locked() to show that we invoke
          * job_completed_txn_abort() only for force-cancelled jobs.)
          */
         if (job_is_cancelled_locked(job)) {
monitor/qmp-cmds.c +5 -2
index 1ebb89f46c..1897ed7a13 100644
@@ -133,8 +133,11 @@ void qmp_cont(Error **errp)
         blk_iostatus_reset(blk);
     }
 
-    for (job = block_job_next(NULL); job; job = block_job_next(job)) {
-        block_job_iostatus_reset(job);
+    WITH_JOB_LOCK_GUARD() {
+        for (job = block_job_next_locked(NULL); job;
+             job = block_job_next_locked(job)) {
+            block_job_iostatus_reset_locked(job);
+        }
     }
 
     /* Continuing after completed migration. Images have been inactivated to
qemu-img.c +24 -17

56 lines not on this page · raw message

Signature · 1 line
2.31.1
#40 lore raw

Re: [PATCH v8 13/20] jobs: group together API calls under the same job lock

Quoted 6 lines · Emanuele Giuseppe Esposito
blockdev.c +0 -0
index 71f793c4ab..5b79093155 100644
@@ -150,12 +150,15 @@ void blockdev_mark_auto_del(BlockBackend *blk)
         return;

blockdev.c void blockdev_mark_auto_del(BlockBackend *blk) · line 159

Quoted 10 lines
blockdev.c +4 -1
     }
 
-    for (job = block_job_next(NULL); job; job = block_job_next(job)) {
+    JOB_LOCK_GUARD();
+
+    for (job = block_job_next_locked(NULL); job;
+         job = block_job_next_locked(job)) {
         if (block_job_has_bdrv(job, blk_bs(blk))) {
             AioContext *aio_context = job->job.aio_context;
             aio_context_acquire(aio_context);

Is there a lock ordering rule for job_mutex and the AioContext lock? I haven't audited the code, but there might be ABBA lock ordering issues.

qemu-img.c static void run_block_job(BlockJob *job, Error **errp) · line 915

Quoted 13 lines
qemu-img.c +1 -4
index 4cf4d2423d..289d88a156 100644
@@ -912,25 +912,30 @@ static void run_block_job(BlockJob *job, Error **errp)
     int ret = 0;
 
     aio_context_acquire(aio_context);
-    job_ref(&job->job);
-    do {
-        float progress = 0.0f;
-        aio_poll(aio_context, true);
+    WITH_JOB_LOCK_GUARD() {

Here the lock order is the opposite of above.

#41 lore raw

Re: [PATCH v8 13/20] jobs: group together API calls under the same job lock

Am 05/07/2022 um 10:14 schrieb Stefan Hajnoczi:

Quoted 9 lines · Emanuele Giuseppe Esposito
Quoted 8 lines
blockdev.c +0 -0
index 71f793c4ab..5b79093155 100644
@@ -150,12 +150,15 @@ void blockdev_mark_auto_del(BlockBackend *blk)
         return;
     }
 
Quoted 11 lines

blockdev.c void blockdev_mark_auto_del(BlockBackend *blk) · line 159

Quoted 8 lines
blockdev.c +4 -1
-    for (job = block_job_next(NULL); job; job = block_job_next(job)) {
+    JOB_LOCK_GUARD();
+
+    for (job = block_job_next_locked(NULL); job;
+         job = block_job_next_locked(job)) {
         if (block_job_has_bdrv(job, blk_bs(blk))) {
             AioContext *aio_context = job->job.aio_context;
             aio_context_acquire(aio_context);

Is there a lock ordering rule for job_mutex and the AioContext lock? I haven't audited the code, but there might be ABBA lock ordering issues.

Doesn't really matter here, as lock is nop. To be honest I forgot which one should go first, probably job_lock because the aiocontext lock can be taken and released in callbacks.

Should I resend with ordering fixed? Just to have a consistent logic

Quoted 17 lines
Quoted 6 lines
qemu-img.c +0 -0
index 4cf4d2423d..289d88a156 100644

qemu-img.c static void run_block_job(BlockJob *job, Error **errp) · line 915

Quoted 8 lines
qemu-img.c +1 -4
@@ -912,25 +912,30 @@ static void run_block_job(BlockJob *job, Error **errp)
     int ret = 0;
 
     aio_context_acquire(aio_context);
-    job_ref(&job->job);
-    do {
-        float progress = 0.0f;
-        aio_poll(aio_context, true);
+    WITH_JOB_LOCK_GUARD() {

Here the lock order is the opposite of above.

#42 lore raw

Re: [PATCH v8 13/20] jobs: group together API calls under the same job lock

Am 05/07/2022 um 10:17 schrieb Emanuele Giuseppe Esposito:

Quoted 24 lines

Am 05/07/2022 um 10:14 schrieb Stefan Hajnoczi:

Quoted 9 lines · Emanuele Giuseppe Esposito
Quoted 8 lines
blockdev.c +0 -0
index 71f793c4ab..5b79093155 100644
@@ -150,12 +150,15 @@ void blockdev_mark_auto_del(BlockBackend *blk)
         return;
     }
 
Quoted 11 lines

blockdev.c void blockdev_mark_auto_del(BlockBackend *blk) · line 159

Quoted 8 lines
blockdev.c +4 -1
-    for (job = block_job_next(NULL); job; job = block_job_next(job)) {
+    JOB_LOCK_GUARD();
+
+    for (job = block_job_next_locked(NULL); job;
+         job = block_job_next_locked(job)) {
         if (block_job_has_bdrv(job, blk_bs(blk))) {
             AioContext *aio_context = job->job.aio_context;
             aio_context_acquire(aio_context);

Is there a lock ordering rule for job_mutex and the AioContext lock? I haven't audited the code, but there might be ABBA lock ordering issues.

Quoted 5 lines

Doesn't really matter here, as lock is nop. To be honest I forgot which one should go first, probably job_lock because the aiocontext lock can be taken and released in callbacks.

Should I resend with ordering fixed? Just to have a consistent logic

Well actually how do I fix that? I would just add useless additional changes into the diff, because for example in the case below I am not even sure what exactly is the aiocontext protecting.

So I guess I'll leave as it is. I will just update the commit message to make sure it is clear that the lock is nop and ordering is mixed.

Thank you,
Emanuele

Quoted 18 lines
Quoted 18 lines
Quoted 7 lines
qemu-img.c +0 -0
index 4cf4d2423d..289d88a156 100644

qemu-img.c static void run_block_job(BlockJob *job, Error **errp) · line 915

Quoted 8 lines
qemu-img.c +1 -4
@@ -912,25 +912,30 @@ static void run_block_job(BlockJob *job, Error **errp)
     int ret = 0;
 
     aio_context_acquire(aio_context);
-    job_ref(&job->job);
-    do {
-        float progress = 0.0f;
-        aio_poll(aio_context, true);
+    WITH_JOB_LOCK_GUARD() {

Here the lock order is the opposite of above.

#43 lore raw

Re: [PATCH v8 13/20] jobs: group together API calls under the same job lock

Quoted 31 lines · Emanuele Giuseppe Esposito

Am 05/07/2022 um 10:17 schrieb Emanuele Giuseppe Esposito:

Quoted 28 lines

Am 05/07/2022 um 10:14 schrieb Stefan Hajnoczi:

Quoted 9 lines · Emanuele Giuseppe Esposito
Quoted 8 lines
blockdev.c +0 -0
index 71f793c4ab..5b79093155 100644
@@ -150,12 +150,15 @@ void blockdev_mark_auto_del(BlockBackend *blk)
          return;
      }
 
Quoted 11 lines

blockdev.c void blockdev_mark_auto_del(BlockBackend *blk) · line 159

Quoted 8 lines
blockdev.c +4 -1
-    for (job = block_job_next(NULL); job; job = block_job_next(job)) {
+    JOB_LOCK_GUARD();
+
+    for (job = block_job_next_locked(NULL); job;
+         job = block_job_next_locked(job)) {
          if (block_job_has_bdrv(job, blk_bs(blk))) {
              AioContext *aio_context = job->job.aio_context;
              aio_context_acquire(aio_context);

Is there a lock ordering rule for job_mutex and the AioContext lock? I haven't audited the code, but there might be ABBA lock ordering issues.

Doesn't really matter here, as lock is nop. To be honest I forgot which one should go first, probably job_lock because the aiocontext lock can be taken and released in callbacks.

Quoted 9 lines
Quoted 1 line

Should I resend with ordering fixed? Just to have a consistent logic

Well actually how do I fix that? I would just add useless additional changes into the diff, because for example in the case below I am not even sure what exactly is the aiocontext protecting.

So I guess I'll leave as it is. I will just update the commit message to make sure it is clear that the lock is nop and ordering is mixed.

Yes, I think it's OK.

As far as I understand, our final ordering rule is that job_mutex can be taken under aio context lock but not visa-versa.

Still, there some aio-context-lock critical sections that are inside job_mutex-lock critical section during the series, just because we don't know the way to avoid it except just merge almost the whole series into one patch. That's why job_mutex is a noop during the series and should become real mutex in the same time with removing these aio-context-lock critical section which breaks the ordering rule.

Signature · 2 lines
Best regards,
Vladimir
#44 lore raw

Re: [PATCH v8 13/20] jobs: group together API calls under the same job lock

Quoted 37 lines · Vladimir Sementsov-Ogievskiy
Quoted 36 lines · Emanuele Giuseppe Esposito

Am 05/07/2022 um 10:17 schrieb Emanuele Giuseppe Esposito:

Quoted 23 lines

Am 05/07/2022 um 10:14 schrieb Stefan Hajnoczi:

Quoted 11 lines · Emanuele Giuseppe Esposito
Quoted 10 lines
blockdev.c +2 -1
index 71f793c4ab..5b79093155 100644
@@ -150,12 +150,15 @@ void blockdev_mark_auto_del(BlockBackend *blk)
          return;
      }
-    for (job = block_job_next(NULL); job; job = block_job_next(job)) {
+    JOB_LOCK_GUARD();
+
Quoted 8 lines

blockdev.c void blockdev_mark_auto_del(BlockBackend *blk) · line 159

Quoted 5 lines
blockdev.c +2 -0
+    for (job = block_job_next_locked(NULL); job;
+         job = block_job_next_locked(job)) {
          if (block_job_has_bdrv(job, blk_bs(blk))) {
              AioContext *aio_context = job->job.aio_context;
              aio_context_acquire(aio_context);

Is there a lock ordering rule for job_mutex and the AioContext lock? I haven't audited the code, but there might be ABBA lock ordering issues.

Quoted 5 lines

Doesn't really matter here, as lock is nop. To be honest I forgot which one should go first, probably job_lock because the aiocontext lock can be taken and released in callbacks.

Should I resend with ordering fixed? Just to have a consistent logic

Well actually how do I fix that? I would just add useless additional changes into the diff, because for example in the case below I am not even sure what exactly is the aiocontext protecting.

Quoted 7 lines
Quoted 3 lines

So I guess I'll leave as it is. I will just update the commit message to make sure it is clear that the lock is nop and ordering is mixed.

Yes, I think it's OK.

As far as I understand, our final ordering rule is that job_mutex can be taken under aio context lock but not visa-versa.

I'm also fine with resolving the ordering in a later patch.

Stefan

#45 lore raw

Re: [PATCH v8 13/20] jobs: group together API calls under the same job lock

In reply to Emanuele Giuseppe Esposito
Quoted 23 lines · Emanuele Giuseppe Esposito
job.c +4 -2
@@ -1045,11 +1045,14 @@ static void job_completed_txn_abort_locked(Job *job)
  /* Called with job_mutex held, but releases it temporarily */
  static int job_prepare_locked(Job *job)
  {
+    int ret;
+
      GLOBAL_STATE_CODE();
      if (job->ret == 0 && job->driver->prepare) {
          job_unlock();
-        job->ret = job->driver->prepare(job);
+        ret = job->driver->prepare(job);
          job_lock();
+        job->ret = ret;
          job_update_rc_locked(job);
      }
      return job->ret;
@@ -1235,10 +1238,10 @@ void job_cancel_locked(Job *job, bool force)
           * job_cancel_async() ignores soft-cancel requests for jobs
           * that are already done (i.e. deferred to the main loop).  We
           * have to check again whether the job is really cancelled.
-         * (job_cancel_requested() and job_is_cancelled() are equivalent

job.c void job_cancel_locked(Job *job, bool force) · line 1247

Quoted 10 lines
job.c +4 -3
-         * here, because job_cancel_async() will make soft-cancel
-         * requests no-ops when deferred_to_main_loop is true.  We
-         * choose to call job_is_cancelled() to show that we invoke
+         * (job_cancel_requested_locked() and job_is_cancelled_locked()
+         * are equivalent here, because job_cancel_async() will
+         * make soft-cancel requests no-ops when deferred_to_main_loop is true.
+         * We choose to call job_is_cancelled_locked() to show that we invoke
           * job_completed_txn_abort() only for force-cancelled jobs.)
           */
          if (job_is_cancelled_locked(job)) {

that's definitely part of commit 05

Signature · 2 lines
Best regards,
Vladimir
#46 lore raw

PATCH v8 14/20 commit and mirror: create new nodes using bdrv_get_aio_context, and not the job aiocontext

In reply to Emanuele Giuseppe Esposito

We are always using the given bs AioContext, so there is no need to take the job ones (which is identical anyways). This also reduces the point we need to check when protecting job.aio_context field.

---
 block/commit.c | 4 ++--
 block/mirror.c | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)
block/commit.c +2 -2
index 851d1c557a..336f799172 100644
@@ -370,7 +370,7 @@ void commit_start(const char *job_id, BlockDriverState *bs,
         goto fail;
     }
 
-    s->base = blk_new(s->common.job.aio_context,
+    s->base = blk_new(bdrv_get_aio_context(bs),
                       base_perms,
                       BLK_PERM_CONSISTENT_READ
                       | BLK_PERM_WRITE_UNCHANGED);
@@ -382,7 +382,7 @@ void commit_start(const char *job_id, BlockDriverState *bs,
     s->base_bs = base;
 
     /* Required permissions are already taken with block_job_add_bdrv() */
-    s->top = blk_new(s->common.job.aio_context, 0, BLK_PERM_ALL);
+    s->top = blk_new(bdrv_get_aio_context(bs), 0, BLK_PERM_ALL);
     ret = blk_insert_bs(s->top, top, errp);
     if (ret < 0) {
         goto fail;
block/mirror.c +1 -1
index b38676e19d..1977e25171 100644
@@ -1728,7 +1728,7 @@ static BlockJob *mirror_start_job(
         goto fail;
     }
 
-    s->target = blk_new(s->common.job.aio_context,
+    s->target = blk_new(bdrv_get_aio_context(bs),
                         target_perms, target_shared_perms);
     ret = blk_insert_bs(s->target, target, errp);
     if (ret < 0) {
Signature · 1 line
2.31.1
#47 lore raw

PATCH v8 15/20 job: detect change of aiocontext within job coroutine

In reply to Emanuele Giuseppe Esposito

From: Paolo Bonzini <[email protected]>

We want to make sure access of job->aio_context is always done under either BQL or job_mutex. The problem is that using aio_co_enter(job->aiocontext, job->co) in job_start and job_enter_cond makes the coroutine immediately resume, so we can't hold the job lock. And caching it is not safe either, as it might change.

job_start is under BQL, so it can freely read job->aiocontext, but job_enter_cond is not. In order to fix this, use aio_co_wake():
the advantage is that it won't use job->aiocontext, but the main disadvantage is that it won't be able to detect a change of job AioContext.

Calling bdrv_try_set_aio_context() will issue the following calls (simplified):
* in terms of bdrv callbacks:
.drained_begin -> .set_aio_context -> .drained_end
* in terms of child_job functions:
child_job_drained_begin -> child_job_set_aio_context -> child_job_drained_end
* in terms of job functions:
job_pause_locked -> job_set_aio_context -> job_resume_locked

We can see that after setting the new aio_context, job_resume_locked calls again job_enter_cond, which then invokes aio_co_wake(). But while job->aiocontext has been set in job_set_aio_context, job->co->ctx has not changed, so the coroutine would be entering in the wrong aiocontext.

Using aio_co_schedule in job_resume_locked() might seem as a valid alternative, but the problem is that the bh resuming the coroutine is not scheduled immediately, and if in the meanwhile another bdrv_try_set_aio_context() is run (see test_propagate_mirror() in test-block-iothread.c), we would have the first schedule in the wrong aiocontext, and the second set of drains won't even manage to schedule the coroutine, as job->busy would still be true from the previous job_resume_locked().

The solution is to stick with aio_co_wake(), but then detect every time the coroutine resumes back from yielding if job->aio_context has changed. If so, we can reschedule it to the new context.

Check for the aiocontext change in job_do_yield_locked because:
1) aio_co_reschedule_self requires to be in the running coroutine
2) since child_job_set_aio_context allows changing the aiocontext only while the job is paused, this is the exact place where the coroutine resumes, before running JobDriver's code.

---
 job.c | 22 +++++++++++++++++++---
 1 file changed, 19 insertions(+), 3 deletions(-)
job.c +19 -3
index 19d711dc73..8db80b8086 100644
@@ -581,11 +581,12 @@ void job_enter_cond_locked(Job *job, bool(*fn)(Job *job))
         return;
     }
 
-    assert(!job->deferred_to_main_loop);
     timer_del(&job->sleep_timer);
     job->busy = true;
     real_job_unlock();
-    aio_co_enter(job->aio_context, job->co);
+    job_unlock();
+    aio_co_wake(job->co);
+    job_lock();
 }
 
 void job_enter_cond(Job *job, bool(*fn)(Job *job))
@@ -611,6 +612,8 @@ void job_enter(Job *job)
  */
 static void coroutine_fn job_do_yield_locked(Job *job, uint64_t ns)
 {
+    AioContext *next_aio_context;
+
     real_job_lock();
     if (ns != -1) {
         timer_mod(&job->sleep_timer, ns);
@@ -622,7 +625,20 @@ static void coroutine_fn job_do_yield_locked(Job *job, uint64_t ns)
     qemu_coroutine_yield();
     job_lock();
 
-    /* Set by job_enter_cond() before re-entering the coroutine.  */
+    next_aio_context = job->aio_context;
+    /*
+     * Coroutine has resumed, but in the meanwhile the job AioContext
+     * might have changed via bdrv_try_set_aio_context(), so we need to move
+     * the coroutine too in the new aiocontext.
+     */
+    while (qemu_get_current_aio_context() != next_aio_context) {
+        job_unlock();
+        aio_co_reschedule_self(next_aio_context);
+        job_lock();
+        next_aio_context = job->aio_context;
+    }
+
+    /* Set by job_enter_cond_locked() before re-entering the coroutine.  */
     assert(job->busy);
 }
 
Signature · 1 line
2.31.1
#48 lore raw

PATCH v8 16/20 jobs: protect job.aio_context with BQL and job_mutex

In reply to Emanuele Giuseppe Esposito

In order to make it thread safe, implement a "fake rwlock", where we allow reads under BQL *or* job_mutex held, but writes only under BQL *and* job_mutex.

The only write we have is in child_job_set_aio_ctx, which always happens under drain (so the job is paused).
For this reason, introduce job_set_aio_context and make sure that the context is set under BQL, job_mutex and drain.
Also make sure all other places where the aiocontext is read are protected.

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

---
 block/replication.c |  6 ++++--
 blockjob.c          |  3 ++-
 include/qemu/job.h  | 19 ++++++++++++++++++-
 job.c               | 12 ++++++++++++
 4 files changed, 36 insertions(+), 4 deletions(-)
block/replication.c +4 -2
index 55c8f894aa..2189863df1 100644
@@ -148,8 +148,10 @@ static void replication_close(BlockDriverState *bs)
     }
     if (s->stage == BLOCK_REPLICATION_FAILOVER) {
         commit_job = &s->commit_job->job;
-        assert(commit_job->aio_context == qemu_get_current_aio_context());
-        job_cancel_sync(commit_job, false);
+        WITH_JOB_LOCK_GUARD() {
+            assert(commit_job->aio_context == qemu_get_current_aio_context());
+            job_cancel_sync_locked(commit_job, false);
+        }
     }
 
     if (s->mode == REPLICATION_MODE_SECONDARY) {
blockjob.c +2 -1
index 1075def475..2293a00b4a 100644
@@ -166,12 +166,13 @@ static void child_job_set_aio_ctx(BdrvChild *c, AioContext *ctx,
         bdrv_set_aio_context_ignore(sibling->bs, ctx, ignore);
     }
 
-    job->job.aio_context = ctx;
+    job_set_aio_context(&job->job, ctx);
 }
 
 static AioContext *child_job_get_parent_aio_context(BdrvChild *c)
 {
     BlockJob *job = c->opaque;
+    assert(qemu_in_main_thread());
 
     return job->job.aio_context;
 }
include/qemu/job.h +18 -1
index e887f88cb2..8f13c3de61 100644
@@ -77,7 +77,12 @@ typedef struct Job {
 
     /** Protected by AioContext lock */
 
-    /** AioContext to run the job coroutine in */
+    /**
+     * AioContext to run the job coroutine in.
+     * This field can be read when holding either the BQL (so we are in
+     * the main loop) or the job_mutex.
+     * It can be only written when we hold *both* BQL and job_mutex.
+     */
     AioContext *aio_context;
 
     /** Reference count of the block job */
@@ -728,4 +733,16 @@ int job_finish_sync(Job *job, void (*finish)(Job *, Error **errp),
 int job_finish_sync_locked(Job *job, void (*finish)(Job *, Error **errp),
                            Error **errp);
 
+/**
+ * Sets the @job->aio_context.
+ * Called with job_mutex *not* held.
+ *
+ * This function must run in the main thread to protect against
+ * concurrent read in job_finish_sync_locked(),
+ * takes the job_mutex lock to protect against the read in
+ * job_do_yield_locked(), and must be called when the coroutine
+ * is quiescent.
+ */
+void job_set_aio_context(Job *job, AioContext *ctx);
+
 #endif
job.c +12 -0
index 8db80b8086..ad2badd107 100644
@@ -394,6 +394,17 @@ Job *job_get(const char *id)
     return job_get_locked(id);
 }
 
+void job_set_aio_context(Job *job, AioContext *ctx)
+{
+    /* protect against read in job_finish_sync_locked and job_start */
+    assert(qemu_in_main_thread());
+    /* protect against read in job_do_yield_locked */
+    JOB_LOCK_GUARD();
+    /* ensure the coroutine is quiescent while the AioContext is changed */
+    assert(job->pause_count > 0);
+    job->aio_context = ctx;
+}
+
 /* Called with job_mutex *not* held. */
 static void job_sleep_timer_cb(void *opaque)
 {
@@ -1379,6 +1390,7 @@ int job_finish_sync_locked(Job *job,
 {
     Error *local_err = NULL;
     int ret;
+    assert(qemu_in_main_thread());
 
     job_ref_locked(job);
 
Signature · 1 line
2.31.1
Reviewed-by on v8 16/20
#49 lore raw

Re: [PATCH v8 16/20] jobs: protect job.aio_context with BQL and job_mutex

Quoted 14 lines · Emanuele Giuseppe Esposito

In order to make it thread safe, implement a "fake rwlock", where we allow reads under BQL *or* job_mutex held, but writes only under BQL *and* job_mutex.

The only write we have is in child_job_set_aio_ctx, which always happens under drain (so the job is paused).
For this reason, introduce job_set_aio_context and make sure that the context is set under BQL, job_mutex and drain.
Also make sure all other places where the aiocontext is read are protected.

Note: at this stage, job_{lock/unlock} and job lock guard macros are *nop*.

Quoted 8 lines
---
 block/replication.c |  6 ++++--
 blockjob.c          |  3 ++-
 include/qemu/job.h  | 19 ++++++++++++++++++-
 job.c               | 12 ++++++++++++
 4 files changed, 36 insertions(+), 4 deletions(-)
#50 lore raw

PATCH v8 17/20 job.c: enable job lock/unlock and remove Aiocontext locks

In reply to Emanuele Giuseppe Esposito

Change the job_{lock/unlock} and macros to use job_mutex.

Now that they are not nop anymore, remove the aiocontext to avoid deadlocks.

Therefore:
- when possible, remove completely the aiocontext lock/unlock pair
- if it is used by some other function too, reduce the locking section as much as possible, leaving the job API outside.

There is only one JobDriver callback, ->free() that assumes that the aiocontext lock is held (because it calls bdrv_unref), so for now keep that under aiocontext lock.

Also remove real_job_{lock/unlock}, as they are replaced by the public functions.

---
 blockdev.c                       | 74 +++++-----------------------
 include/qemu/job.h               | 22 ++++-----
 job-qmp.c                        | 44 ++++-------------
 job.c                            | 82 ++++++--------------------------
 tests/unit/test-bdrv-drain.c     |  4 +-
 tests/unit/test-block-iothread.c |  2 +-
 tests/unit/test-blockjob.c       | 13 ++---
 7 files changed, 51 insertions(+), 190 deletions(-)
blockdev.c +11 -63
index 5b79093155..2cd84d206c 100644
@@ -155,12 +155,7 @@ void blockdev_mark_auto_del(BlockBackend *blk)
     for (job = block_job_next_locked(NULL); job;
          job = block_job_next_locked(job)) {
         if (block_job_has_bdrv(job, blk_bs(blk))) {
-            AioContext *aio_context = job->job.aio_context;
-            aio_context_acquire(aio_context);
-
             job_cancel_locked(&job->job, false);
-
-            aio_context_release(aio_context);
         }
     }
 
@@ -1836,14 +1831,7 @@ static void drive_backup_abort(BlkActionState *common)
     DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
 
     if (state->job) {
-        AioContext *aio_context;
-
-        aio_context = bdrv_get_aio_context(state->bs);
-        aio_context_acquire(aio_context);
-
         job_cancel_sync(&state->job->job, true);
-
-        aio_context_release(aio_context);
     }
 }
 
@@ -1937,14 +1925,7 @@ static void blockdev_backup_abort(BlkActionState *common)
     BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
 
     if (state->job) {
-        AioContext *aio_context;
-
-        aio_context = bdrv_get_aio_context(state->bs);
-        aio_context_acquire(aio_context);
-
         job_cancel_sync(&state->job->job, true);
-
-        aio_context_release(aio_context);
     }
 }
 
@@ -3306,19 +3287,14 @@ out:
 }
 
 /*
- * Get a block job using its ID and acquire its AioContext.
- * Called with job_mutex held.
+ * Get a block job using its ID. Called with job_mutex held.
  */
-static BlockJob *find_block_job_locked(const char *id,
-                                       AioContext **aio_context,
-                                       Error **errp)
+static BlockJob *find_block_job_locked(const char *id, Error **errp)
 {
     BlockJob *job;
 
     assert(id != NULL);
 
-    *aio_context = NULL;
-
     job = block_job_get_locked(id);
 
     if (!job) {
@@ -3327,36 +3303,30 @@ static BlockJob *find_block_job_locked(const char *id,
         return NULL;
     }
 
-    *aio_context = block_job_get_aio_context(job);
-    aio_context_acquire(*aio_context);
-
     return job;
 }
 
 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
 {
-    AioContext *aio_context;
     BlockJob *job;
 
     JOB_LOCK_GUARD();
-    job = find_block_job_locked(device, &aio_context, errp);
+    job = find_block_job_locked(device, errp);
 
     if (!job) {
         return;
     }
 
     block_job_set_speed_locked(job, speed, errp);
-    aio_context_release(aio_context);
 }
 
 void qmp_block_job_cancel(const char *device,
                           bool has_force, bool force, Error **errp)
 {
-    AioContext *aio_context;
     BlockJob *job;
 
     JOB_LOCK_GUARD();
-    job = find_block_job_locked(device, &aio_context, errp);
+    job = find_block_job_locked(device, errp);
 
     if (!job) {
         return;
@@ -3369,22 +3339,19 @@ void qmp_block_job_cancel(const char *device,
     if (job_user_paused_locked(&job->job) && !force) {
         error_setg(errp, "The block job for device '%s' is currently paused",
                    device);
-        goto out;
+        return;
     }
 
     trace_qmp_block_job_cancel(job);
     job_user_cancel_locked(&job->job, force, errp);
-out:
-    aio_context_release(aio_context);
 }
 
 void qmp_block_job_pause(const char *device, Error **errp)
 {
-    AioContext *aio_context;
     BlockJob *job;
 
     JOB_LOCK_GUARD();
-    job = find_block_job_locked(device, &aio_context, errp);
+    job = find_block_job_locked(device, errp);
 
     if (!job) {
         return;
@@ -3392,16 +3359,14 @@ void qmp_block_job_pause(const char *device, Error **errp)
 
     trace_qmp_block_job_pause(job);
     job_user_pause_locked(&job->job, errp);
-    aio_context_release(aio_context);
 }
 
 void qmp_block_job_resume(const char *device, Error **errp)
 {
-    AioContext *aio_context;
     BlockJob *job;
 
     JOB_LOCK_GUARD();
-    job = find_block_job_locked(device, &aio_context, errp);
+    job = find_block_job_locked(device, errp);
 
     if (!job) {
         return;
@@ -3409,16 +3374,14 @@ void qmp_block_job_resume(const char *device, Error **errp)
 
     trace_qmp_block_job_resume(job);
     job_user_resume_locked(&job->job, errp);
-    aio_context_release(aio_context);
 }
 
 void qmp_block_job_complete(const char *device, Error **errp)
 {
-    AioContext *aio_context;
     BlockJob *job;
 
     JOB_LOCK_GUARD();
-    job = find_block_job_locked(device, &aio_context, errp);
+    job = find_block_job_locked(device, errp);
 
     if (!job) {
         return;
@@ -3426,16 +3389,14 @@ void qmp_block_job_complete(const char *device, Error **errp)
 
     trace_qmp_block_job_complete(job);
     job_complete_locked(&job->job, errp);
-    aio_context_release(aio_context);
 }
 
 void qmp_block_job_finalize(const char *id, Error **errp)
 {
-    AioContext *aio_context;
     BlockJob *job;
 
     JOB_LOCK_GUARD();
-    job = find_block_job_locked(id, &aio_context, errp);
+    job = find_block_job_locked(id, errp);
 
     if (!job) {
         return;
@@ -3445,24 +3406,16 @@ void qmp_block_job_finalize(const char *id, Error **errp)
     job_ref_locked(&job->job);
     job_finalize_locked(&job->job, errp);
 
-    /*
-     * Job's context might have changed via job_finalize (and job_txn_apply
-     * automatically acquires the new one), so make sure we release the correct
-     * one.
-     */
-    aio_context = block_job_get_aio_context(job);
     job_unref_locked(&job->job);
-    aio_context_release(aio_context);
 }
 
 void qmp_block_job_dismiss(const char *id, Error **errp)
 {
-    AioContext *aio_context;
     BlockJob *bjob;
     Job *job;
 
     JOB_LOCK_GUARD();
-    bjob = find_block_job_locked(id, &aio_context, errp);
+    bjob = find_block_job_locked(id, errp);
 
     if (!bjob) {
         return;
@@ -3471,7 +3424,6 @@ void qmp_block_job_dismiss(const char *id, Error **errp)
     trace_qmp_block_job_dismiss(bjob);
     job = &bjob->job;
     job_dismiss_locked(&job, errp);
-    aio_context_release(aio_context);
 }
 
 void qmp_change_backing_file(const char *device,
@@ -3753,15 +3705,11 @@ BlockJobInfoList *qmp_query_block_jobs(Error **errp)
     for (job = block_job_next_locked(NULL); job;
          job = block_job_next_locked(job)) {
         BlockJobInfo *value;
-        AioContext *aio_context;
 
         if (block_job_is_internal(job)) {
             continue;
         }
-        aio_context = block_job_get_aio_context(job);
-        aio_context_acquire(aio_context);
-        value = block_job_query(job, errp);
-        aio_context_release(aio_context);
+        value = block_job_query_locked(job, errp);
         if (!value) {
             qapi_free_BlockJobInfoList(head);
             return NULL;
include/qemu/job.h +11 -11
index 8f13c3de61..5db35f765c 100644
@@ -75,13 +75,14 @@ typedef struct Job {
     ProgressMeter progress;
 
 
-    /** Protected by AioContext lock */
+    /** Protected by job_mutex */
 
     /**
      * AioContext to run the job coroutine in.
-     * This field can be read when holding either the BQL (so we are in
-     * the main loop) or the job_mutex.
-     * It can be only written when we hold *both* BQL and job_mutex.
+     * The job Aiocontext can be read when holding *either*
+     * the BQL (so we are in the main loop) or the job_mutex.
+     * It can only be written when we hold *both* BQL
+     * and the job_mutex.
      */
     AioContext *aio_context;
 
@@ -106,7 +107,7 @@ typedef struct Job {
     /**
      * Set to false by the job while the coroutine has yielded and may be
      * re-entered by job_enter(). There may still be I/O or event loop activity
-     * pending. Accessed under block_job_mutex (in blockjob.c).
+     * pending. Accessed under job_mutex.
      *
      * When the job is deferred to the main loop, busy is true as long as the
      * bottom half is still pending.
@@ -322,9 +323,9 @@ typedef enum JobCreateFlags {
 
 extern QemuMutex job_mutex;
 
-#define JOB_LOCK_GUARD() /* QEMU_LOCK_GUARD(&job_mutex) */
+#define JOB_LOCK_GUARD() QEMU_LOCK_GUARD(&job_mutex)
 
-#define WITH_JOB_LOCK_GUARD() /* WITH_QEMU_LOCK_GUARD(&job_mutex) */
+#define WITH_JOB_LOCK_GUARD() WITH_QEMU_LOCK_GUARD(&job_mutex)
 
 /**
  * job_lock:
@@ -660,7 +661,7 @@ void job_user_cancel_locked(Job *job, bool force, Error **errp);
  * Returns the return value from the job if the job actually completed
  * during the call, or -ECANCELED if it was canceled.
  *
- * Callers must hold the AioContext lock of job->aio_context.
+ * Called with job_lock held.
  */
 int job_cancel_sync(Job *job, bool force);
 
@@ -687,8 +688,7 @@ void job_cancel_sync_all(void);
  * function).
  *
  * Returns the return value from the job.
- *
- * Callers must hold the AioContext lock of job->aio_context.
+ * Called with job_lock held.
  */
 int job_complete_sync(Job *job, Error **errp);
 
@@ -724,7 +724,7 @@ void job_dismiss_locked(Job **job, Error **errp);
  * Returns 0 if the job is successfully completed, -ECANCELED if the job was
  * cancelled before completing, and -errno in other error cases.
  *
- * Callers must hold the AioContext lock of job->aio_context.
+ * Called with job_lock held.
  */
 int job_finish_sync(Job *job, void (*finish)(Job *, Error **errp),
                     Error **errp);
job-qmp.c +8 -36

151 lines not on this page · raw message

job.c +15 -67

242 lines not on this page · raw message

tests/unit/test-bdrv-drain.c +2 -2
index 0db056ea63..4924ceb562 100644
@@ -930,9 +930,9 @@ static void test_blockjob_common_drain_node(enum drain_type drain_type,
         tjob->prepare_ret = -EIO;
         break;
     }
+    aio_context_release(ctx);
 
     job_start(&job->job);
-    aio_context_release(ctx);
 
     if (use_iothread) {
         /* job_co_entry() is run in the I/O thread, wait for the actual job
@@ -1016,12 +1016,12 @@ static void test_blockjob_common_drain_node(enum drain_type drain_type,
         g_assert_true(job->job.busy); /* We're in qemu_co_sleep_ns() */
     }
 
-    aio_context_acquire(ctx);
     WITH_JOB_LOCK_GUARD() {
         ret = job_complete_sync_locked(&job->job, &error_abort);
     }
     g_assert_cmpint(ret, ==, (result == TEST_JOB_SUCCESS ? 0 : -EIO));
 
+    aio_context_acquire(ctx);
     if (use_iothread) {
         blk_set_aio_context(blk_src, qemu_get_aio_context(), &error_abort);
         assert(blk_get_aio_context(blk_target) == qemu_get_aio_context());
tests/unit/test-block-iothread.c +1 -1
index 89e7f0fffb..9d7c8be00f 100644
@@ -455,10 +455,10 @@ static void test_attach_blockjob(void)
         aio_poll(qemu_get_aio_context(), false);
     }
 
-    aio_context_acquire(ctx);
     WITH_JOB_LOCK_GUARD() {
         job_complete_sync_locked(&tjob->common.job, &error_abort);
     }
+    aio_context_acquire(ctx);
     blk_set_aio_context(blk, qemu_get_aio_context(), &error_abort);
     aio_context_release(ctx);
 
tests/unit/test-blockjob.c +3 -10
index 17755e58db..535827ffd9 100644
@@ -228,10 +228,6 @@ static void cancel_common(CancelJob *s)
     BlockJob *job = &s->common;
     BlockBackend *blk = s->blk;
     JobStatus sts = job->job.status;
-    AioContext *ctx;
-
-    ctx = job->job.aio_context;
-    aio_context_acquire(ctx);
 
     job_cancel_sync(&job->job, true);
     WITH_JOB_LOCK_GUARD() {
@@ -244,7 +240,6 @@ static void cancel_common(CancelJob *s)
     }
     destroy_blk(blk);
 
-    aio_context_release(ctx);
 }
 
 static void test_cancel_created(void)
@@ -405,11 +400,9 @@ static void test_cancel_concluded(void)
     aio_poll(qemu_get_aio_context(), true);
     assert(job->status == JOB_STATUS_PENDING);
 
-    aio_context_acquire(job->aio_context);
     WITH_JOB_LOCK_GUARD() {
         job_finalize_locked(job, &error_abort);
     }
-    aio_context_release(job->aio_context);
     assert(job->status == JOB_STATUS_CONCLUDED);
 
     cancel_common(s);
@@ -503,13 +496,11 @@ static void test_complete_in_standby(void)
 
     /* Wait for the job to become READY */
     job_start(job);
-    aio_context_acquire(ctx);
     /*
      * Here we are waiting for the status to change, so don't bother
      * protecting the read every time.
      */
-    AIO_WAIT_WHILE(ctx, job->status != JOB_STATUS_READY);
-    aio_context_release(ctx);
+    AIO_WAIT_WHILE_UNLOCKED(ctx, job->status != JOB_STATUS_READY);
 
     /* Begin the drained section, pausing the job */
     bdrv_drain_all_begin();
@@ -529,6 +520,7 @@ static void test_complete_in_standby(void)
         job_complete_locked(job, &error_abort);
 
         /* The test is done now, clean up. */
+        aio_context_release(ctx);
         job_finish_sync_locked(job, NULL, &error_abort);
         assert(job->status == JOB_STATUS_PENDING);
 
@@ -538,6 +530,7 @@ static void test_complete_in_standby(void)
         job_dismiss_locked(&job, &error_abort);
     }
 
+    aio_context_acquire(ctx);
     destroy_blk(blk);
     aio_context_release(ctx);
     iothread_join(iothread);
Signature · 1 line
2.31.1
Reviewed-by on v8 17/20
#51 lore raw

Re: [PATCH v8 17/20] job.c: enable job lock/unlock and remove Aiocontext locks

Quoted 5 lines · Emanuele Giuseppe Esposito

Change the job_{lock/unlock} and macros to use job_mutex.

Now that they are not nop anymore, remove the aiocontext to avoid deadlocks.

Quoted 8 lines

Therefore:
- when possible, remove completely the aiocontext lock/unlock pair
- if it is used by some other function too, reduce the locking section as much as possible, leaving the job API outside.

There is only one JobDriver callback, ->free() that assumes that the aiocontext lock is held (because it calls bdrv_unref), so for now keep that under aiocontext lock.

This discussion shouldn't hold up the patch series, it's a separate issue:

Why does bdrv_unref() need the AioContext lock? The reference count itself is protected by the BQL (bdrv_ref() is GS too). I/O requests should be using fine-grained locks now, so I'm not sure if we still need to hold the AioContext lock to drain them?

#52 lore raw

Re: [PATCH v8 17/20] job.c: enable job lock/unlock and remove Aiocontext locks

Am 05/07/2022 um 15:07 schrieb Stefan Hajnoczi:

Quoted 15 lines · Emanuele Giuseppe Esposito
Quoted 5 lines

Change the job_{lock/unlock} and macros to use job_mutex.

Now that they are not nop anymore, remove the aiocontext to avoid deadlocks.

Quoted 8 lines

Therefore:
- when possible, remove completely the aiocontext lock/unlock pair
- if it is used by some other function too, reduce the locking section as much as possible, leaving the job API outside.

There is only one JobDriver callback, ->free() that assumes that the aiocontext lock is held (because it calls bdrv_unref), so for now keep that under aiocontext lock.

Quoted 7 lines

This discussion shouldn't hold up the patch series, it's a separate issue:

Why does bdrv_unref() need the AioContext lock? The reference count itself is protected by the BQL (bdrv_ref() is GS too). I/O requests should be using fine-grained locks now, so I'm not sure if we still need to hold the AioContext lock to drain them?

If I remove the AioContex lock/unlock in job_unref_locked, I see that test 200 and test-bdrv-drain are failing.

The reason is that job->free() is calling block_job_free and then we eventually get to bdrv_detach_child claling bdrv_try_set_aio_context from the main loop, on a node that is in another AioContext lock.

So it isn't really about bdrv_unref, but more bdrv_try_set_aio_context. Until we don't find a solution to that, we can't get rid of this aiocontext lock.

That's the shared call stack from both tests:

#0 __pthread_kill_implementation (threadid=<optimized out>,

    signo=signo@entry=6, no_tid=no_tid@entry=0) at pthread_kill.c:44
#1  0x00007ffff66a64a3 in __pthread_kill_internal (signo=6,
    threadid=<optimized out>) at pthread_kill.c:78
#2  0x00007ffff6659d06 in __GI_raise (sig=sig@entry=6)
    at ../sysdeps/posix/raise.c:26
#3  0x00007ffff662c7d3 in __GI_abort () at abort.c:79
#4  0x0000555555d6411f in error_exit (err=<optimized out>,
    msg=msg@entry=0x555555f49b30 <__func__.20> "qemu_mutex_unlock_impl")
    at ../util/qemu-thread-posix.c:38

--Type <RET> for more, q to quit, c to continue without paging-- #5 0x0000555555d64965 in qemu_mutex_unlock_impl (mutex=0x5555568d0620,
file=<optimized out>, line=<optimized out>)
at ../util/qemu-thread-posix.c:118
#6 0x0000555555c39c06 in bdrv_set_aio_context_ignore (bs=0x5555575133e0,

    new_context=0x5555566a2ad0, ignore=0x7fffffffd110) at ../block.c:7399
#7  0x0000555555c3a100 in bdrv_child_try_set_aio_context (
    bs=bs@entry=0x5555575133e0, ctx=ctx@entry=0x5555566a2ad0,
    ignore_child=ignore_child@entry=0x0, errp=errp@entry=0x0)
    at ../block.c:7493
#8  0x0000555555c3a1f6 in bdrv_try_set_aio_context (errp=0x0,
--Type <RET> for more, q to quit, c to continue without paging--
    ctx=0x5555566a2ad0, bs=0x5555575133e0) at ../block.c:7503
#9  bdrv_detach_child (childp=0x7fffffffd168) at ../block.c:3130
#10 bdrv_root_unref_child (child=<optimized out>,
child@entry=0x55555732dc00)
    at ../block.c:3228
#11 0x0000555555c4265f in block_job_remove_all_bdrv (job=0x5555575b6a30)
    at ../blockjob.c:195
#12 0x0000555555c426b5 in block_job_free (job=0x5555575b6a30)
    at ../blockjob.c:76
#13 0x0000555555c4472e in job_unref_locked (job=0x5555575b6a30)
    at ../job.c:464

--Type <RET> for more, q to quit, c to continue without paging-- #14 job_unref_locked (job=0x5555575b6a30) at ../job.c:450

Quoted 3 lines
#53 lore raw

PATCH v8 18/20 block_job_query: remove atomic read

In reply to Emanuele Giuseppe Esposito

Not sure what the atomic here was supposed to do, since job.busy is protected by the job lock. Since the whole function is called under job_mutex, just remove the atomic.

---
 blockjob.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
blockjob.c +1 -1
index 2293a00b4a..a2559b97a7 100644
@@ -342,7 +342,7 @@ BlockJobInfo *block_job_query_locked(BlockJob *job, Error **errp)
     info = g_new0(BlockJobInfo, 1);
     info->type      = g_strdup(job_type_str(&job->job));
     info->device    = g_strdup(job->job.id);
-    info->busy      = qatomic_read(&job->job.busy);
+    info->busy      = job->job.busy;
     info->paused    = job->job.pause_count > 0;
     info->offset    = progress_current;
     info->len       = progress_total;
Signature · 1 line
2.31.1
#54 lore raw

PATCH v8 19/20 blockjob: remove unused functions

In reply to Emanuele Giuseppe Esposito

These public functions are not used anywhere, thus can be dropped.

---
 blockjob.c               | 30 ------------------------------
 include/block/blockjob.h | 33 +++++++++++++--------------------
 2 files changed, 13 insertions(+), 50 deletions(-)
blockjob.c +0 -30
index a2559b97a7..d84ddca363 100644
@@ -56,12 +56,6 @@ BlockJob *block_job_next_locked(BlockJob *bjob)
     return job ? container_of(job, BlockJob, job) : NULL;
 }
 
-BlockJob *block_job_next(BlockJob *bjob)
-{
-    JOB_LOCK_GUARD();
-    return block_job_next_locked(bjob);
-}
-
 BlockJob *block_job_get_locked(const char *id)
 {
     Job *job = job_get_locked(id);
@@ -74,12 +68,6 @@ BlockJob *block_job_get_locked(const char *id)
     }
 }
 
-BlockJob *block_job_get(const char *id)
-{
-    JOB_LOCK_GUARD();
-    return block_job_get_locked(id);
-}
-
 void block_job_free(Job *job)
 {
     BlockJob *bjob = container_of(job, BlockJob, job);
@@ -312,12 +300,6 @@ bool block_job_set_speed_locked(BlockJob *job, int64_t speed, Error **errp)
     return true;
 }
 
-bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
-{
-    JOB_LOCK_GUARD();
-    return block_job_set_speed_locked(job, speed, errp);
-}
-
 int64_t block_job_ratelimit_get_delay(BlockJob *job, uint64_t n)
 {
     IO_CODE();
@@ -361,12 +343,6 @@ BlockJobInfo *block_job_query_locked(BlockJob *job, Error **errp)
     return info;
 }
 
-BlockJobInfo *block_job_query(BlockJob *job, Error **errp)
-{
-    JOB_LOCK_GUARD();
-    return block_job_query_locked(job, errp);
-}
-
 static void block_job_iostatus_set_err(BlockJob *job, int error)
 {
     if (job->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
@@ -531,12 +507,6 @@ void block_job_iostatus_reset_locked(BlockJob *job)
     job->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
 }
 
-void block_job_iostatus_reset(BlockJob *job)
-{
-    JOB_LOCK_GUARD();
-    block_job_iostatus_reset_locked(job);
-}
-
 void block_job_user_resume(Job *job)
 {
     BlockJob *bjob = container_of(job, BlockJob, job);
include/block/blockjob.h +13 -20
index 3959a98612..753862e1f2 100644
@@ -82,30 +82,26 @@ typedef struct BlockJob {
  */
 
 /**
- * block_job_next:
+ * block_job_next_locked:
  * @job: A block job, or %NULL.
  *
  * Get the next element from the list of block jobs after @job, or the
  * first one if @job is %NULL.
  *
  * Returns the requested job, or %NULL if there are no more jobs left.
+ * Called with job lock held.
  */
-BlockJob *block_job_next(BlockJob *job);
-
-/* Same as block_job_next(), but called with job lock held. */
 BlockJob *block_job_next_locked(BlockJob *job);
 
 /**
- * block_job_get:
+ * block_job_get_locked:
  * @id: The id of the block job.
  *
  * Get the block job identified by @id (which must not be %NULL).
  *
  * Returns the requested job, or %NULL if it doesn't exist.
+ * Called with job lock held.
  */
-BlockJob *block_job_get(const char *id);
-
-/* Same as block_job_get(), but called with job lock held. */
 BlockJob *block_job_get_locked(const char *id);
 
 /**
@@ -141,40 +137,37 @@ void block_job_remove_all_bdrv(BlockJob *job);
 bool block_job_has_bdrv(BlockJob *job, BlockDriverState *bs);
 
 /**
- * block_job_set_speed:
+ * block_job_set_speed_locked:
  * @job: The job to set the speed for.
  * @speed: The new value
  * @errp: Error object.
  *
  * Set a rate-limiting parameter for the job; the actual meaning may
  * vary depending on the job type.
+ *
+ * Called with job lock held.
  */
-bool block_job_set_speed(BlockJob *job, int64_t speed, Error **errp);
-
-/* Same as block_job_set_speed(), but called with job lock held. */
 bool block_job_set_speed_locked(BlockJob *job, int64_t speed, Error **errp);
 
 /**
- * block_job_query:
+ * block_job_query_locked:
  * @job: The job to get information about.
  *
  * Return information about a job.
+ *
+ * Called with job lock held.
  */
-BlockJobInfo *block_job_query(BlockJob *job, Error **errp);
-
-/* Same as block_job_query(), but called with job lock held. */
 BlockJobInfo *block_job_query_locked(BlockJob *job, Error **errp);
 
 /**
- * block_job_iostatus_reset:
+ * block_job_iostatus_reset_locked:
  * @job: The job whose I/O status should be reset.
  *
  * Reset I/O status on @job and on BlockDriverState objects it uses,
  * other than job->blk.
+ *
+ * Called with job lock held.
  */
-void block_job_iostatus_reset(BlockJob *job);
-
-/* Same as block_job_iostatus_reset(), but called with job lock held. */
 void block_job_iostatus_reset_locked(BlockJob *job);
 
 /*
Signature · 1 line
2.31.1
Reviewed-by on v8 19/20
#55 lore raw

Re: [PATCH v8 19/20] blockjob: remove unused functions

Quoted 7 lines · Emanuele Giuseppe Esposito

These public functions are not used anywhere, thus can be dropped.

---
 blockjob.c               | 30 ------------------------------
 include/block/blockjob.h | 33 +++++++++++++--------------------
 2 files changed, 13 insertions(+), 50 deletions(-)
#56 lore raw

PATCH v8 20/20 job: remove unused functions

In reply to Emanuele Giuseppe Esposito

These public functions are not used anywhere, thus can be dropped. Also, since this is the final job API that doesn't use AioContext lock and replaces it with job_lock, adjust all remaining function documentation to clearly specify if the job lock is taken or not.

---
 include/qemu/job.h |  97 +++++++++++++----------------------
 job.c              | 122 ++-------------------------------------------
 2 files changed, 40 insertions(+), 179 deletions(-)
include/qemu/job.h +35 -62
index 5db35f765c..f3d0694512 100644
@@ -361,6 +361,8 @@ JobTxn *job_txn_new(void);
 /**
  * Release a reference that was previously acquired with job_txn_add_job or
  * job_txn_new. If it's the last reference to the object, it will be freed.
+ *
+ * Called with job lock *not* held.
  */
 void job_txn_unref(JobTxn *txn);
 
@@ -387,19 +389,17 @@ void *job_create(const char *job_id, const JobDriver *driver, JobTxn *txn,
 /**
  * Add a reference to Job refcnt, it will be decreased with job_unref, and then
  * be freed if it comes to be the last reference.
+ *
+ * Called with job lock held.
  */
-void job_ref(Job *job);
-
-/* Same as job_ref(), but called with job lock held. */
 void job_ref_locked(Job *job);
 
 /**
  * Release a reference that was previously acquired with job_ref() or
  * job_create(). If it's the last reference to the object, it will be freed.
+ *
+ * Called with job lock held.
  */
-void job_unref(Job *job);
-
-/* Same as job_unref(), but called with job lock held. */
 void job_unref_locked(Job *job);
 
 /**
@@ -445,10 +445,9 @@ void job_progress_increase_remaining(Job *job, uint64_t delta);
  * Conditionally enter the job coroutine if the job is ready to run, not
  * already busy and fn() returns true. fn() is called while under the job_lock
  * critical section.
+ *
+ * Called with job lock held, but might release it temporarily.
  */
-void job_enter_cond(Job *job, bool(*fn)(Job *job));
-
-/* Same as job_enter_cond(), but called with job lock held. */
 void job_enter_cond_locked(Job *job, bool(*fn)(Job *job));
 
 /**
@@ -529,11 +528,8 @@ bool job_cancel_requested(Job *job);
 
 /**
  * Returns whether the job is in a completed state.
- * Called with job_mutex *not* held.
+ * Called with job lock held.
  */
-bool job_is_completed(Job *job);
-
-/* Same as job_is_completed(), but called with job lock held. */
 bool job_is_completed_locked(Job *job);
 
 /**
@@ -549,40 +545,35 @@ bool job_is_ready_locked(Job *job);
  * Request @job to pause at the next pause point. Must be paired with
  * job_resume(). If the job is supposed to be resumed by user action, call
  * job_user_pause() instead.
+ *
+ * Called with job lock held.
  */
-void job_pause(Job *job);
-
-/* Same as job_pause(), but called with job lock held. */
 void job_pause_locked(Job *job);
 
-/** Resumes a @job paused with job_pause. */
-void job_resume(Job *job);
-
-/* Same as job_resume(), but called with job lock held. */
+/**
+ * Resumes a @job paused with job_pause.
+ * Called with job lock held, but might release it temporarily.
+ */
 void job_resume_locked(Job *job);
 
 /**
  * Asynchronously pause the specified @job.
  * Do not allow a resume until a matching call to job_user_resume.
+ * Called with job lock held.
  */
-void job_user_pause(Job *job, Error **errp);
-
-/* Same as job_user_pause(), but called with job lock held. */
 void job_user_pause_locked(Job *job, Error **errp);
 
-/** Returns true if the job is user-paused. */
-bool job_user_paused(Job *job);
-
-/* Same as job_user_paused(), but called with job lock held. */
+/**
+ * Returns true if the job is user-paused.
+ * Called with job lock held.
+ */
 bool job_user_paused_locked(Job *job);
 
 /**
  * Resume the specified @job.
  * Must be paired with a preceding job_user_pause.
+ * Called with job lock held.
  */
-void job_user_resume(Job *job, Error **errp);
-
-/* Same as job_user_resume(), but called with job lock held. */
 void job_user_resume_locked(Job *job, Error **errp);
 
 /**
@@ -590,30 +581,25 @@ void job_user_resume_locked(Job *job, Error **errp);
  * first one if @job is %NULL.
  *
  * Returns the requested job, or %NULL if there are no more jobs left.
+ * Called with job lock held.
  */
-Job *job_next(Job *job);
-
-/* Same as job_next(), but called with job lock held. */
 Job *job_next_locked(Job *job);
 
 /**
  * Get the job identified by @id (which must not be %NULL).
  *
  * Returns the requested job, or %NULL if it doesn't exist.
+ * Called with job lock held.
  */
-Job *job_get(const char *id);
-
-/* Same as job_get(), but called with job lock held. */
 Job *job_get_locked(const char *id);
 
 /**
  * Check whether the verb @verb can be applied to @job in its current state.
  * Returns 0 if the verb can be applied; otherwise errp is set and -EPERM
  * returned.
+ *
+ * Called with job lock held.
  */
-int job_apply_verb(Job *job, JobVerb verb, Error **errp);
-
-/* Same as job_apply_verb, but called with job lock held. */
 int job_apply_verb_locked(Job *job, JobVerb verb, Error **errp);
 
 /**
@@ -628,28 +614,24 @@ void job_early_fail(Job *job);
  */
 void job_transition_to_ready(Job *job);
 
-/** Asynchronously complete the specified @job. */
-void job_complete(Job *job, Error **errp);
-
-/* Same as job_complete(), but called with job lock held. */
+/**
+ * Asynchronously complete the specified @job.
+ * Called with job lock held, but might release it temporarily.
+ */
 void job_complete_locked(Job *job, Error **errp);
 
 /**
  * Asynchronously cancel the specified @job. If @force is true, the job should
  * be cancelled immediately without waiting for a consistent state.
+ * Called with job lock held.
  */
-void job_cancel(Job *job, bool force);
-
-/* Same as job_cancel(), but called with job lock held. */
 void job_cancel_locked(Job *job, bool force);
 
 /**
  * Cancels the specified job like job_cancel(), but may refuse to do so if the
  * operation isn't meaningful in the current state of the job.
+ * Called with job lock held.
  */
-void job_user_cancel(Job *job, bool force, Error **errp);
-
-/* Same as job_user_cancel(), but called with job lock held. */
 void job_user_cancel_locked(Job *job, bool force, Error **errp);
 
 /**
@@ -690,9 +672,6 @@ void job_cancel_sync_all(void);
  * Returns the return value from the job.
  * Called with job_lock held.
  */
-int job_complete_sync(Job *job, Error **errp);
-
-/* Same as job_complete_sync, but called with job lock held. */
 int job_complete_sync_locked(Job *job, Error **errp);
 
 /**
@@ -702,19 +681,17 @@ int job_complete_sync_locked(Job *job, Error **errp);
  * FIXME: Make the below statement universally true:
  * For jobs that support the manual workflow mode, all graph changes that occur
  * as a result will occur after this command and before a successful reply.
+ *
+ * Called with job lock held.
  */
-void job_finalize(Job *job, Error **errp);
-
-/* Same as job_finalize(), but called with job lock held. */
 void job_finalize_locked(Job *job, Error **errp);
 
 /**
  * Remove the concluded @job from the query list and resets the passed pointer
  * to %NULL. Returns an error if the job is not actually concluded.
+ *
+ * Called with job lock held.
  */
-void job_dismiss(Job **job, Error **errp);
-
-/* Same as job_dismiss(), but called with job lock held. */
 void job_dismiss_locked(Job **job, Error **errp);
 
 /**
@@ -726,10 +703,6 @@ void job_dismiss_locked(Job **job, Error **errp);
  *
  * Called with job_lock held.
  */
-int job_finish_sync(Job *job, void (*finish)(Job *, Error **errp),
-                    Error **errp);
-
-/* Same as job_finish_sync, but called with job lock held. */
 int job_finish_sync_locked(Job *job, void (*finish)(Job *, Error **errp),
                            Error **errp);
 
job.c +5 -117

252 lines not on this page · raw message

Signature · 1 line
2.31.1
Reviewed-by on v8 20/20
#57 lore raw

Re: [PATCH v8 20/20] job: remove unused functions

Quoted 10 lines · Emanuele Giuseppe Esposito

These public functions are not used anywhere, thus can be dropped. Also, since this is the final job API that doesn't use AioContext lock and replaces it with job_lock, adjust all remaining function documentation to clearly specify if the job lock is taken or not.

---
 include/qemu/job.h |  97 +++++++++++++----------------------
 job.c              | 122 ++-------------------------------------------
 2 files changed, 40 insertions(+), 179 deletions(-)
#58 lore raw
In reply to Emanuele Giuseppe Esposito
Quoted 23 lines · Emanuele Giuseppe Esposito

In this series, we want to remove the AioContext lock and instead use the already existent job_mutex to protect the job structures and list. This is part of the work to get rid of AioContext lock usage in favour of smaller granularity locks.

In order to simplify reviewer's job, job lock/unlock functions and macros are added as empty prototypes (nop) in patch 1. They are converted to use the actual job mutex only in the last patch. In this way we can freely create locking sections without worrying about deadlocks with the aiocontext lock.

Patch 2 defines what fields in the job structure need protection. Patches 3-6 are in preparation to the job locks, moving functions from global to static and introducing helpers.

Patch 7-9 introduce the (nop) job lock into the job API and its users, and patches 10-13 categorize respectively locked and unlocked functions in the job API.

Patches 14-17 take care of protecting job->aio_context, and finally patch 18 makes the prototypes in patch 1 use the job_mutex and removes all aiocontext lock at the same time.

Quoted 7 lines

Tested this series by running unit tests, qemu-iotests and qtests (x86_64).

---
v8:
* reorganize patch ordering according with Vladimir proposal
* minor nitpicks

I have posted some comments but I didn't spot any major issues.

Stefan