OSDN Git Service

job: Add job_cancel_requested()
[qmiga/qemu.git] / job.c
1 /*
2  * Background jobs (long-running operations)
3  *
4  * Copyright (c) 2011 IBM Corp.
5  * Copyright (c) 2012, 2018 Red Hat, Inc.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25
26 #include "qemu/osdep.h"
27 #include "qapi/error.h"
28 #include "qemu/job.h"
29 #include "qemu/id.h"
30 #include "qemu/main-loop.h"
31 #include "block/aio-wait.h"
32 #include "trace/trace-root.h"
33 #include "qapi/qapi-events-job.h"
34
35 static QLIST_HEAD(, Job) jobs = QLIST_HEAD_INITIALIZER(jobs);
36
37 /* Job State Transition Table */
38 bool JobSTT[JOB_STATUS__MAX][JOB_STATUS__MAX] = {
39                                     /* U, C, R, P, Y, S, W, D, X, E, N */
40     /* U: */ [JOB_STATUS_UNDEFINED] = {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
41     /* C: */ [JOB_STATUS_CREATED]   = {0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1},
42     /* R: */ [JOB_STATUS_RUNNING]   = {0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0},
43     /* P: */ [JOB_STATUS_PAUSED]    = {0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
44     /* Y: */ [JOB_STATUS_READY]     = {0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0},
45     /* S: */ [JOB_STATUS_STANDBY]   = {0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0},
46     /* W: */ [JOB_STATUS_WAITING]   = {0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0},
47     /* D: */ [JOB_STATUS_PENDING]   = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0},
48     /* X: */ [JOB_STATUS_ABORTING]  = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0},
49     /* E: */ [JOB_STATUS_CONCLUDED] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
50     /* N: */ [JOB_STATUS_NULL]      = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
51 };
52
53 bool JobVerbTable[JOB_VERB__MAX][JOB_STATUS__MAX] = {
54                                     /* U, C, R, P, Y, S, W, D, X, E, N */
55     [JOB_VERB_CANCEL]               = {0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0},
56     [JOB_VERB_PAUSE]                = {0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0},
57     [JOB_VERB_RESUME]               = {0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0},
58     [JOB_VERB_SET_SPEED]            = {0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0},
59     [JOB_VERB_COMPLETE]             = {0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0},
60     [JOB_VERB_FINALIZE]             = {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0},
61     [JOB_VERB_DISMISS]              = {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0},
62 };
63
64 /* Transactional group of jobs */
65 struct JobTxn {
66
67     /* Is this txn being cancelled? */
68     bool aborting;
69
70     /* List of jobs */
71     QLIST_HEAD(, Job) jobs;
72
73     /* Reference count */
74     int refcnt;
75 };
76
77 /* Right now, this mutex is only needed to synchronize accesses to job->busy
78  * and job->sleep_timer, such as concurrent calls to job_do_yield and
79  * job_enter. */
80 static QemuMutex job_mutex;
81
82 static void job_lock(void)
83 {
84     qemu_mutex_lock(&job_mutex);
85 }
86
87 static void job_unlock(void)
88 {
89     qemu_mutex_unlock(&job_mutex);
90 }
91
92 static void __attribute__((__constructor__)) job_init(void)
93 {
94     qemu_mutex_init(&job_mutex);
95 }
96
97 JobTxn *job_txn_new(void)
98 {
99     JobTxn *txn = g_new0(JobTxn, 1);
100     QLIST_INIT(&txn->jobs);
101     txn->refcnt = 1;
102     return txn;
103 }
104
105 static void job_txn_ref(JobTxn *txn)
106 {
107     txn->refcnt++;
108 }
109
110 void job_txn_unref(JobTxn *txn)
111 {
112     if (txn && --txn->refcnt == 0) {
113         g_free(txn);
114     }
115 }
116
117 void job_txn_add_job(JobTxn *txn, Job *job)
118 {
119     if (!txn) {
120         return;
121     }
122
123     assert(!job->txn);
124     job->txn = txn;
125
126     QLIST_INSERT_HEAD(&txn->jobs, job, txn_list);
127     job_txn_ref(txn);
128 }
129
130 static void job_txn_del_job(Job *job)
131 {
132     if (job->txn) {
133         QLIST_REMOVE(job, txn_list);
134         job_txn_unref(job->txn);
135         job->txn = NULL;
136     }
137 }
138
139 static int job_txn_apply(Job *job, int fn(Job *))
140 {
141     AioContext *inner_ctx;
142     Job *other_job, *next;
143     JobTxn *txn = job->txn;
144     int rc = 0;
145
146     /*
147      * Similar to job_completed_txn_abort, we take each job's lock before
148      * applying fn, but since we assume that outer_ctx is held by the caller,
149      * we need to release it here to avoid holding the lock twice - which would
150      * break AIO_WAIT_WHILE from within fn.
151      */
152     job_ref(job);
153     aio_context_release(job->aio_context);
154
155     QLIST_FOREACH_SAFE(other_job, &txn->jobs, txn_list, next) {
156         inner_ctx = other_job->aio_context;
157         aio_context_acquire(inner_ctx);
158         rc = fn(other_job);
159         aio_context_release(inner_ctx);
160         if (rc) {
161             break;
162         }
163     }
164
165     /*
166      * Note that job->aio_context might have been changed by calling fn, so we
167      * can't use a local variable to cache it.
168      */
169     aio_context_acquire(job->aio_context);
170     job_unref(job);
171     return rc;
172 }
173
174 bool job_is_internal(Job *job)
175 {
176     return (job->id == NULL);
177 }
178
179 static void job_state_transition(Job *job, JobStatus s1)
180 {
181     JobStatus s0 = job->status;
182     assert(s1 >= 0 && s1 < JOB_STATUS__MAX);
183     trace_job_state_transition(job, job->ret,
184                                JobSTT[s0][s1] ? "allowed" : "disallowed",
185                                JobStatus_str(s0), JobStatus_str(s1));
186     assert(JobSTT[s0][s1]);
187     job->status = s1;
188
189     if (!job_is_internal(job) && s1 != s0) {
190         qapi_event_send_job_status_change(job->id, job->status);
191     }
192 }
193
194 int job_apply_verb(Job *job, JobVerb verb, Error **errp)
195 {
196     JobStatus s0 = job->status;
197     assert(verb >= 0 && verb < JOB_VERB__MAX);
198     trace_job_apply_verb(job, JobStatus_str(s0), JobVerb_str(verb),
199                          JobVerbTable[verb][s0] ? "allowed" : "prohibited");
200     if (JobVerbTable[verb][s0]) {
201         return 0;
202     }
203     error_setg(errp, "Job '%s' in state '%s' cannot accept command verb '%s'",
204                job->id, JobStatus_str(s0), JobVerb_str(verb));
205     return -EPERM;
206 }
207
208 JobType job_type(const Job *job)
209 {
210     return job->driver->job_type;
211 }
212
213 const char *job_type_str(const Job *job)
214 {
215     return JobType_str(job_type(job));
216 }
217
218 bool job_is_cancelled(Job *job)
219 {
220     return job->cancelled && job->force_cancel;
221 }
222
223 bool job_cancel_requested(Job *job)
224 {
225     return job->cancelled;
226 }
227
228 bool job_is_ready(Job *job)
229 {
230     switch (job->status) {
231     case JOB_STATUS_UNDEFINED:
232     case JOB_STATUS_CREATED:
233     case JOB_STATUS_RUNNING:
234     case JOB_STATUS_PAUSED:
235     case JOB_STATUS_WAITING:
236     case JOB_STATUS_PENDING:
237     case JOB_STATUS_ABORTING:
238     case JOB_STATUS_CONCLUDED:
239     case JOB_STATUS_NULL:
240         return false;
241     case JOB_STATUS_READY:
242     case JOB_STATUS_STANDBY:
243         return true;
244     default:
245         g_assert_not_reached();
246     }
247     return false;
248 }
249
250 bool job_is_completed(Job *job)
251 {
252     switch (job->status) {
253     case JOB_STATUS_UNDEFINED:
254     case JOB_STATUS_CREATED:
255     case JOB_STATUS_RUNNING:
256     case JOB_STATUS_PAUSED:
257     case JOB_STATUS_READY:
258     case JOB_STATUS_STANDBY:
259         return false;
260     case JOB_STATUS_WAITING:
261     case JOB_STATUS_PENDING:
262     case JOB_STATUS_ABORTING:
263     case JOB_STATUS_CONCLUDED:
264     case JOB_STATUS_NULL:
265         return true;
266     default:
267         g_assert_not_reached();
268     }
269     return false;
270 }
271
272 static bool job_started(Job *job)
273 {
274     return job->co;
275 }
276
277 static bool job_should_pause(Job *job)
278 {
279     return job->pause_count > 0;
280 }
281
282 Job *job_next(Job *job)
283 {
284     if (!job) {
285         return QLIST_FIRST(&jobs);
286     }
287     return QLIST_NEXT(job, job_list);
288 }
289
290 Job *job_get(const char *id)
291 {
292     Job *job;
293
294     QLIST_FOREACH(job, &jobs, job_list) {
295         if (job->id && !strcmp(id, job->id)) {
296             return job;
297         }
298     }
299
300     return NULL;
301 }
302
303 static void job_sleep_timer_cb(void *opaque)
304 {
305     Job *job = opaque;
306
307     job_enter(job);
308 }
309
310 void *job_create(const char *job_id, const JobDriver *driver, JobTxn *txn,
311                  AioContext *ctx, int flags, BlockCompletionFunc *cb,
312                  void *opaque, Error **errp)
313 {
314     Job *job;
315
316     if (job_id) {
317         if (flags & JOB_INTERNAL) {
318             error_setg(errp, "Cannot specify job ID for internal job");
319             return NULL;
320         }
321         if (!id_wellformed(job_id)) {
322             error_setg(errp, "Invalid job ID '%s'", job_id);
323             return NULL;
324         }
325         if (job_get(job_id)) {
326             error_setg(errp, "Job ID '%s' already in use", job_id);
327             return NULL;
328         }
329     } else if (!(flags & JOB_INTERNAL)) {
330         error_setg(errp, "An explicit job ID is required");
331         return NULL;
332     }
333
334     job = g_malloc0(driver->instance_size);
335     job->driver        = driver;
336     job->id            = g_strdup(job_id);
337     job->refcnt        = 1;
338     job->aio_context   = ctx;
339     job->busy          = false;
340     job->paused        = true;
341     job->pause_count   = 1;
342     job->auto_finalize = !(flags & JOB_MANUAL_FINALIZE);
343     job->auto_dismiss  = !(flags & JOB_MANUAL_DISMISS);
344     job->cb            = cb;
345     job->opaque        = opaque;
346
347     progress_init(&job->progress);
348
349     notifier_list_init(&job->on_finalize_cancelled);
350     notifier_list_init(&job->on_finalize_completed);
351     notifier_list_init(&job->on_pending);
352     notifier_list_init(&job->on_ready);
353
354     job_state_transition(job, JOB_STATUS_CREATED);
355     aio_timer_init(qemu_get_aio_context(), &job->sleep_timer,
356                    QEMU_CLOCK_REALTIME, SCALE_NS,
357                    job_sleep_timer_cb, job);
358
359     QLIST_INSERT_HEAD(&jobs, job, job_list);
360
361     /* Single jobs are modeled as single-job transactions for sake of
362      * consolidating the job management logic */
363     if (!txn) {
364         txn = job_txn_new();
365         job_txn_add_job(txn, job);
366         job_txn_unref(txn);
367     } else {
368         job_txn_add_job(txn, job);
369     }
370
371     return job;
372 }
373
374 void job_ref(Job *job)
375 {
376     ++job->refcnt;
377 }
378
379 void job_unref(Job *job)
380 {
381     if (--job->refcnt == 0) {
382         assert(job->status == JOB_STATUS_NULL);
383         assert(!timer_pending(&job->sleep_timer));
384         assert(!job->txn);
385
386         if (job->driver->free) {
387             job->driver->free(job);
388         }
389
390         QLIST_REMOVE(job, job_list);
391
392         progress_destroy(&job->progress);
393         error_free(job->err);
394         g_free(job->id);
395         g_free(job);
396     }
397 }
398
399 void job_progress_update(Job *job, uint64_t done)
400 {
401     progress_work_done(&job->progress, done);
402 }
403
404 void job_progress_set_remaining(Job *job, uint64_t remaining)
405 {
406     progress_set_remaining(&job->progress, remaining);
407 }
408
409 void job_progress_increase_remaining(Job *job, uint64_t delta)
410 {
411     progress_increase_remaining(&job->progress, delta);
412 }
413
414 void job_event_cancelled(Job *job)
415 {
416     notifier_list_notify(&job->on_finalize_cancelled, job);
417 }
418
419 void job_event_completed(Job *job)
420 {
421     notifier_list_notify(&job->on_finalize_completed, job);
422 }
423
424 static void job_event_pending(Job *job)
425 {
426     notifier_list_notify(&job->on_pending, job);
427 }
428
429 static void job_event_ready(Job *job)
430 {
431     notifier_list_notify(&job->on_ready, job);
432 }
433
434 static void job_event_idle(Job *job)
435 {
436     notifier_list_notify(&job->on_idle, job);
437 }
438
439 void job_enter_cond(Job *job, bool(*fn)(Job *job))
440 {
441     if (!job_started(job)) {
442         return;
443     }
444     if (job->deferred_to_main_loop) {
445         return;
446     }
447
448     job_lock();
449     if (job->busy) {
450         job_unlock();
451         return;
452     }
453
454     if (fn && !fn(job)) {
455         job_unlock();
456         return;
457     }
458
459     assert(!job->deferred_to_main_loop);
460     timer_del(&job->sleep_timer);
461     job->busy = true;
462     job_unlock();
463     aio_co_enter(job->aio_context, job->co);
464 }
465
466 void job_enter(Job *job)
467 {
468     job_enter_cond(job, NULL);
469 }
470
471 /* Yield, and schedule a timer to reenter the coroutine after @ns nanoseconds.
472  * Reentering the job coroutine with job_enter() before the timer has expired
473  * is allowed and cancels the timer.
474  *
475  * If @ns is (uint64_t) -1, no timer is scheduled and job_enter() must be
476  * called explicitly. */
477 static void coroutine_fn job_do_yield(Job *job, uint64_t ns)
478 {
479     job_lock();
480     if (ns != -1) {
481         timer_mod(&job->sleep_timer, ns);
482     }
483     job->busy = false;
484     job_event_idle(job);
485     job_unlock();
486     qemu_coroutine_yield();
487
488     /* Set by job_enter_cond() before re-entering the coroutine.  */
489     assert(job->busy);
490 }
491
492 void coroutine_fn job_pause_point(Job *job)
493 {
494     assert(job && job_started(job));
495
496     if (!job_should_pause(job)) {
497         return;
498     }
499     if (job_is_cancelled(job)) {
500         return;
501     }
502
503     if (job->driver->pause) {
504         job->driver->pause(job);
505     }
506
507     if (job_should_pause(job) && !job_is_cancelled(job)) {
508         JobStatus status = job->status;
509         job_state_transition(job, status == JOB_STATUS_READY
510                                   ? JOB_STATUS_STANDBY
511                                   : JOB_STATUS_PAUSED);
512         job->paused = true;
513         job_do_yield(job, -1);
514         job->paused = false;
515         job_state_transition(job, status);
516     }
517
518     if (job->driver->resume) {
519         job->driver->resume(job);
520     }
521 }
522
523 void job_yield(Job *job)
524 {
525     assert(job->busy);
526
527     /* Check cancellation *before* setting busy = false, too!  */
528     if (job_is_cancelled(job)) {
529         return;
530     }
531
532     if (!job_should_pause(job)) {
533         job_do_yield(job, -1);
534     }
535
536     job_pause_point(job);
537 }
538
539 void coroutine_fn job_sleep_ns(Job *job, int64_t ns)
540 {
541     assert(job->busy);
542
543     /* Check cancellation *before* setting busy = false, too!  */
544     if (job_is_cancelled(job)) {
545         return;
546     }
547
548     if (!job_should_pause(job)) {
549         job_do_yield(job, qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + ns);
550     }
551
552     job_pause_point(job);
553 }
554
555 /* Assumes the block_job_mutex is held */
556 static bool job_timer_not_pending(Job *job)
557 {
558     return !timer_pending(&job->sleep_timer);
559 }
560
561 void job_pause(Job *job)
562 {
563     job->pause_count++;
564     if (!job->paused) {
565         job_enter(job);
566     }
567 }
568
569 void job_resume(Job *job)
570 {
571     assert(job->pause_count > 0);
572     job->pause_count--;
573     if (job->pause_count) {
574         return;
575     }
576
577     /* kick only if no timer is pending */
578     job_enter_cond(job, job_timer_not_pending);
579 }
580
581 void job_user_pause(Job *job, Error **errp)
582 {
583     if (job_apply_verb(job, JOB_VERB_PAUSE, errp)) {
584         return;
585     }
586     if (job->user_paused) {
587         error_setg(errp, "Job is already paused");
588         return;
589     }
590     job->user_paused = true;
591     job_pause(job);
592 }
593
594 bool job_user_paused(Job *job)
595 {
596     return job->user_paused;
597 }
598
599 void job_user_resume(Job *job, Error **errp)
600 {
601     assert(job);
602     if (!job->user_paused || job->pause_count <= 0) {
603         error_setg(errp, "Can't resume a job that was not paused");
604         return;
605     }
606     if (job_apply_verb(job, JOB_VERB_RESUME, errp)) {
607         return;
608     }
609     if (job->driver->user_resume) {
610         job->driver->user_resume(job);
611     }
612     job->user_paused = false;
613     job_resume(job);
614 }
615
616 static void job_do_dismiss(Job *job)
617 {
618     assert(job);
619     job->busy = false;
620     job->paused = false;
621     job->deferred_to_main_loop = true;
622
623     job_txn_del_job(job);
624
625     job_state_transition(job, JOB_STATUS_NULL);
626     job_unref(job);
627 }
628
629 void job_dismiss(Job **jobptr, Error **errp)
630 {
631     Job *job = *jobptr;
632     /* similarly to _complete, this is QMP-interface only. */
633     assert(job->id);
634     if (job_apply_verb(job, JOB_VERB_DISMISS, errp)) {
635         return;
636     }
637
638     job_do_dismiss(job);
639     *jobptr = NULL;
640 }
641
642 void job_early_fail(Job *job)
643 {
644     assert(job->status == JOB_STATUS_CREATED);
645     job_do_dismiss(job);
646 }
647
648 static void job_conclude(Job *job)
649 {
650     job_state_transition(job, JOB_STATUS_CONCLUDED);
651     if (job->auto_dismiss || !job_started(job)) {
652         job_do_dismiss(job);
653     }
654 }
655
656 static void job_update_rc(Job *job)
657 {
658     if (!job->ret && job_is_cancelled(job)) {
659         job->ret = -ECANCELED;
660     }
661     if (job->ret) {
662         if (!job->err) {
663             error_setg(&job->err, "%s", strerror(-job->ret));
664         }
665         job_state_transition(job, JOB_STATUS_ABORTING);
666     }
667 }
668
669 static void job_commit(Job *job)
670 {
671     assert(!job->ret);
672     if (job->driver->commit) {
673         job->driver->commit(job);
674     }
675 }
676
677 static void job_abort(Job *job)
678 {
679     assert(job->ret);
680     if (job->driver->abort) {
681         job->driver->abort(job);
682     }
683 }
684
685 static void job_clean(Job *job)
686 {
687     if (job->driver->clean) {
688         job->driver->clean(job);
689     }
690 }
691
692 static int job_finalize_single(Job *job)
693 {
694     assert(job_is_completed(job));
695
696     /* Ensure abort is called for late-transactional failures */
697     job_update_rc(job);
698
699     if (!job->ret) {
700         job_commit(job);
701     } else {
702         job_abort(job);
703     }
704     job_clean(job);
705
706     if (job->cb) {
707         job->cb(job->opaque, job->ret);
708     }
709
710     /* Emit events only if we actually started */
711     if (job_started(job)) {
712         if (job_is_cancelled(job)) {
713             job_event_cancelled(job);
714         } else {
715             job_event_completed(job);
716         }
717     }
718
719     job_txn_del_job(job);
720     job_conclude(job);
721     return 0;
722 }
723
724 static void job_cancel_async(Job *job, bool force)
725 {
726     if (job->driver->cancel) {
727         force = job->driver->cancel(job, force);
728     } else {
729         /* No .cancel() means the job will behave as if force-cancelled */
730         force = true;
731     }
732
733     if (job->user_paused) {
734         /* Do not call job_enter here, the caller will handle it.  */
735         if (job->driver->user_resume) {
736             job->driver->user_resume(job);
737         }
738         job->user_paused = false;
739         assert(job->pause_count > 0);
740         job->pause_count--;
741     }
742
743     /*
744      * Ignore soft cancel requests after the job is already done
745      * (We will still invoke job->driver->cancel() above, but if the
746      * job driver supports soft cancelling and the job is done, that
747      * should be a no-op, too.  We still call it so it can override
748      * @force.)
749      */
750     if (force || !job->deferred_to_main_loop) {
751         job->cancelled = true;
752         /* To prevent 'force == false' overriding a previous 'force == true' */
753         job->force_cancel |= force;
754     }
755 }
756
757 static void job_completed_txn_abort(Job *job)
758 {
759     AioContext *ctx;
760     JobTxn *txn = job->txn;
761     Job *other_job;
762
763     if (txn->aborting) {
764         /*
765          * We are cancelled by another job, which will handle everything.
766          */
767         return;
768     }
769     txn->aborting = true;
770     job_txn_ref(txn);
771
772     /*
773      * We can only hold the single job's AioContext lock while calling
774      * job_finalize_single() because the finalization callbacks can involve
775      * calls of AIO_WAIT_WHILE(), which could deadlock otherwise.
776      * Note that the job's AioContext may change when it is finalized.
777      */
778     job_ref(job);
779     aio_context_release(job->aio_context);
780
781     /* Other jobs are effectively cancelled by us, set the status for
782      * them; this job, however, may or may not be cancelled, depending
783      * on the caller, so leave it. */
784     QLIST_FOREACH(other_job, &txn->jobs, txn_list) {
785         if (other_job != job) {
786             ctx = other_job->aio_context;
787             aio_context_acquire(ctx);
788             /*
789              * This is a transaction: If one job failed, no result will matter.
790              * Therefore, pass force=true to terminate all other jobs as quickly
791              * as possible.
792              */
793             job_cancel_async(other_job, true);
794             aio_context_release(ctx);
795         }
796     }
797     while (!QLIST_EMPTY(&txn->jobs)) {
798         other_job = QLIST_FIRST(&txn->jobs);
799         /*
800          * The job's AioContext may change, so store it in @ctx so we
801          * release the same context that we have acquired before.
802          */
803         ctx = other_job->aio_context;
804         aio_context_acquire(ctx);
805         if (!job_is_completed(other_job)) {
806             assert(job_cancel_requested(other_job));
807             job_finish_sync(other_job, NULL, NULL);
808         }
809         job_finalize_single(other_job);
810         aio_context_release(ctx);
811     }
812
813     /*
814      * Use job_ref()/job_unref() so we can read the AioContext here
815      * even if the job went away during job_finalize_single().
816      */
817     aio_context_acquire(job->aio_context);
818     job_unref(job);
819
820     job_txn_unref(txn);
821 }
822
823 static int job_prepare(Job *job)
824 {
825     if (job->ret == 0 && job->driver->prepare) {
826         job->ret = job->driver->prepare(job);
827         job_update_rc(job);
828     }
829     return job->ret;
830 }
831
832 static int job_needs_finalize(Job *job)
833 {
834     return !job->auto_finalize;
835 }
836
837 static void job_do_finalize(Job *job)
838 {
839     int rc;
840     assert(job && job->txn);
841
842     /* prepare the transaction to complete */
843     rc = job_txn_apply(job, job_prepare);
844     if (rc) {
845         job_completed_txn_abort(job);
846     } else {
847         job_txn_apply(job, job_finalize_single);
848     }
849 }
850
851 void job_finalize(Job *job, Error **errp)
852 {
853     assert(job && job->id);
854     if (job_apply_verb(job, JOB_VERB_FINALIZE, errp)) {
855         return;
856     }
857     job_do_finalize(job);
858 }
859
860 static int job_transition_to_pending(Job *job)
861 {
862     job_state_transition(job, JOB_STATUS_PENDING);
863     if (!job->auto_finalize) {
864         job_event_pending(job);
865     }
866     return 0;
867 }
868
869 void job_transition_to_ready(Job *job)
870 {
871     job_state_transition(job, JOB_STATUS_READY);
872     job_event_ready(job);
873 }
874
875 static void job_completed_txn_success(Job *job)
876 {
877     JobTxn *txn = job->txn;
878     Job *other_job;
879
880     job_state_transition(job, JOB_STATUS_WAITING);
881
882     /*
883      * Successful completion, see if there are other running jobs in this
884      * txn.
885      */
886     QLIST_FOREACH(other_job, &txn->jobs, txn_list) {
887         if (!job_is_completed(other_job)) {
888             return;
889         }
890         assert(other_job->ret == 0);
891     }
892
893     job_txn_apply(job, job_transition_to_pending);
894
895     /* If no jobs need manual finalization, automatically do so */
896     if (job_txn_apply(job, job_needs_finalize) == 0) {
897         job_do_finalize(job);
898     }
899 }
900
901 static void job_completed(Job *job)
902 {
903     assert(job && job->txn && !job_is_completed(job));
904
905     job_update_rc(job);
906     trace_job_completed(job, job->ret);
907     if (job->ret) {
908         job_completed_txn_abort(job);
909     } else {
910         job_completed_txn_success(job);
911     }
912 }
913
914 /** Useful only as a type shim for aio_bh_schedule_oneshot. */
915 static void job_exit(void *opaque)
916 {
917     Job *job = (Job *)opaque;
918     AioContext *ctx;
919
920     job_ref(job);
921     aio_context_acquire(job->aio_context);
922
923     /* This is a lie, we're not quiescent, but still doing the completion
924      * callbacks. However, completion callbacks tend to involve operations that
925      * drain block nodes, and if .drained_poll still returned true, we would
926      * deadlock. */
927     job->busy = false;
928     job_event_idle(job);
929
930     job_completed(job);
931
932     /*
933      * Note that calling job_completed can move the job to a different
934      * aio_context, so we cannot cache from above. job_txn_apply takes care of
935      * acquiring the new lock, and we ref/unref to avoid job_completed freeing
936      * the job underneath us.
937      */
938     ctx = job->aio_context;
939     job_unref(job);
940     aio_context_release(ctx);
941 }
942
943 /**
944  * All jobs must allow a pause point before entering their job proper. This
945  * ensures that jobs can be paused prior to being started, then resumed later.
946  */
947 static void coroutine_fn job_co_entry(void *opaque)
948 {
949     Job *job = opaque;
950
951     assert(job && job->driver && job->driver->run);
952     job_pause_point(job);
953     job->ret = job->driver->run(job, &job->err);
954     job->deferred_to_main_loop = true;
955     job->busy = true;
956     aio_bh_schedule_oneshot(qemu_get_aio_context(), job_exit, job);
957 }
958
959 void job_start(Job *job)
960 {
961     assert(job && !job_started(job) && job->paused &&
962            job->driver && job->driver->run);
963     job->co = qemu_coroutine_create(job_co_entry, job);
964     job->pause_count--;
965     job->busy = true;
966     job->paused = false;
967     job_state_transition(job, JOB_STATUS_RUNNING);
968     aio_co_enter(job->aio_context, job->co);
969 }
970
971 void job_cancel(Job *job, bool force)
972 {
973     if (job->status == JOB_STATUS_CONCLUDED) {
974         job_do_dismiss(job);
975         return;
976     }
977     job_cancel_async(job, force);
978     if (!job_started(job)) {
979         job_completed(job);
980     } else if (job->deferred_to_main_loop) {
981         /*
982          * job_cancel_async() ignores soft-cancel requests for jobs
983          * that are already done (i.e. deferred to the main loop).  We
984          * have to check again whether the job is really cancelled.
985          * (job_cancel_requested() and job_is_cancelled() are equivalent
986          * here, because job_cancel_async() will make soft-cancel
987          * requests no-ops when deferred_to_main_loop is true.  We
988          * choose to call job_is_cancelled() to show that we invoke
989          * job_completed_txn_abort() only for force-cancelled jobs.)
990          */
991         if (job_is_cancelled(job)) {
992             job_completed_txn_abort(job);
993         }
994     } else {
995         job_enter(job);
996     }
997 }
998
999 void job_user_cancel(Job *job, bool force, Error **errp)
1000 {
1001     if (job_apply_verb(job, JOB_VERB_CANCEL, errp)) {
1002         return;
1003     }
1004     job_cancel(job, force);
1005 }
1006
1007 /* A wrapper around job_cancel() taking an Error ** parameter so it may be
1008  * used with job_finish_sync() without the need for (rather nasty) function
1009  * pointer casts there. */
1010 static void job_cancel_err(Job *job, Error **errp)
1011 {
1012     job_cancel(job, false);
1013 }
1014
1015 /**
1016  * Same as job_cancel_err(), but force-cancel.
1017  */
1018 static void job_force_cancel_err(Job *job, Error **errp)
1019 {
1020     job_cancel(job, true);
1021 }
1022
1023 int job_cancel_sync(Job *job, bool force)
1024 {
1025     if (force) {
1026         return job_finish_sync(job, &job_force_cancel_err, NULL);
1027     } else {
1028         return job_finish_sync(job, &job_cancel_err, NULL);
1029     }
1030 }
1031
1032 void job_cancel_sync_all(void)
1033 {
1034     Job *job;
1035     AioContext *aio_context;
1036
1037     while ((job = job_next(NULL))) {
1038         aio_context = job->aio_context;
1039         aio_context_acquire(aio_context);
1040         job_cancel_sync(job, true);
1041         aio_context_release(aio_context);
1042     }
1043 }
1044
1045 int job_complete_sync(Job *job, Error **errp)
1046 {
1047     return job_finish_sync(job, job_complete, errp);
1048 }
1049
1050 void job_complete(Job *job, Error **errp)
1051 {
1052     /* Should not be reachable via external interface for internal jobs */
1053     assert(job->id);
1054     if (job_apply_verb(job, JOB_VERB_COMPLETE, errp)) {
1055         return;
1056     }
1057     if (job_cancel_requested(job) || !job->driver->complete) {
1058         error_setg(errp, "The active block job '%s' cannot be completed",
1059                    job->id);
1060         return;
1061     }
1062
1063     job->driver->complete(job, errp);
1064 }
1065
1066 int job_finish_sync(Job *job, void (*finish)(Job *, Error **errp), Error **errp)
1067 {
1068     Error *local_err = NULL;
1069     int ret;
1070
1071     job_ref(job);
1072
1073     if (finish) {
1074         finish(job, &local_err);
1075     }
1076     if (local_err) {
1077         error_propagate(errp, local_err);
1078         job_unref(job);
1079         return -EBUSY;
1080     }
1081
1082     AIO_WAIT_WHILE(job->aio_context,
1083                    (job_enter(job), !job_is_completed(job)));
1084
1085     ret = (job_is_cancelled(job) && job->ret == 0) ? -ECANCELED : job->ret;
1086     job_unref(job);
1087     return ret;
1088 }