xref: /openbmc/qemu/job.c (revision 1d52866f)
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 "qemu-common.h"
28 #include "qapi/error.h"
29 #include "qemu/job.h"
30 #include "qemu/id.h"
31 #include "qemu/main-loop.h"
32 #include "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, 0, 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(JobTxn *txn, int fn(Job *), bool lock)
140 {
141     AioContext *ctx;
142     Job *job, *next;
143     int rc = 0;
144 
145     QLIST_FOREACH_SAFE(job, &txn->jobs, txn_list, next) {
146         if (lock) {
147             ctx = job->aio_context;
148             aio_context_acquire(ctx);
149         }
150         rc = fn(job);
151         if (lock) {
152             aio_context_release(ctx);
153         }
154         if (rc) {
155             break;
156         }
157     }
158     return rc;
159 }
160 
161 bool job_is_internal(Job *job)
162 {
163     return (job->id == NULL);
164 }
165 
166 static void job_state_transition(Job *job, JobStatus s1)
167 {
168     JobStatus s0 = job->status;
169     assert(s1 >= 0 && s1 <= JOB_STATUS__MAX);
170     trace_job_state_transition(job, job->ret,
171                                JobSTT[s0][s1] ? "allowed" : "disallowed",
172                                JobStatus_str(s0), JobStatus_str(s1));
173     assert(JobSTT[s0][s1]);
174     job->status = s1;
175 
176     if (!job_is_internal(job) && s1 != s0) {
177         qapi_event_send_job_status_change(job->id, job->status, &error_abort);
178     }
179 }
180 
181 int job_apply_verb(Job *job, JobVerb verb, Error **errp)
182 {
183     JobStatus s0 = job->status;
184     assert(verb >= 0 && verb <= JOB_VERB__MAX);
185     trace_job_apply_verb(job, JobStatus_str(s0), JobVerb_str(verb),
186                          JobVerbTable[verb][s0] ? "allowed" : "prohibited");
187     if (JobVerbTable[verb][s0]) {
188         return 0;
189     }
190     error_setg(errp, "Job '%s' in state '%s' cannot accept command verb '%s'",
191                job->id, JobStatus_str(s0), JobVerb_str(verb));
192     return -EPERM;
193 }
194 
195 JobType job_type(const Job *job)
196 {
197     return job->driver->job_type;
198 }
199 
200 const char *job_type_str(const Job *job)
201 {
202     return JobType_str(job_type(job));
203 }
204 
205 bool job_is_cancelled(Job *job)
206 {
207     return job->cancelled;
208 }
209 
210 bool job_is_ready(Job *job)
211 {
212     switch (job->status) {
213     case JOB_STATUS_UNDEFINED:
214     case JOB_STATUS_CREATED:
215     case JOB_STATUS_RUNNING:
216     case JOB_STATUS_PAUSED:
217     case JOB_STATUS_WAITING:
218     case JOB_STATUS_PENDING:
219     case JOB_STATUS_ABORTING:
220     case JOB_STATUS_CONCLUDED:
221     case JOB_STATUS_NULL:
222         return false;
223     case JOB_STATUS_READY:
224     case JOB_STATUS_STANDBY:
225         return true;
226     default:
227         g_assert_not_reached();
228     }
229     return false;
230 }
231 
232 bool job_is_completed(Job *job)
233 {
234     switch (job->status) {
235     case JOB_STATUS_UNDEFINED:
236     case JOB_STATUS_CREATED:
237     case JOB_STATUS_RUNNING:
238     case JOB_STATUS_PAUSED:
239     case JOB_STATUS_READY:
240     case JOB_STATUS_STANDBY:
241         return false;
242     case JOB_STATUS_WAITING:
243     case JOB_STATUS_PENDING:
244     case JOB_STATUS_ABORTING:
245     case JOB_STATUS_CONCLUDED:
246     case JOB_STATUS_NULL:
247         return true;
248     default:
249         g_assert_not_reached();
250     }
251     return false;
252 }
253 
254 static bool job_started(Job *job)
255 {
256     return job->co;
257 }
258 
259 static bool job_should_pause(Job *job)
260 {
261     return job->pause_count > 0;
262 }
263 
264 Job *job_next(Job *job)
265 {
266     if (!job) {
267         return QLIST_FIRST(&jobs);
268     }
269     return QLIST_NEXT(job, job_list);
270 }
271 
272 Job *job_get(const char *id)
273 {
274     Job *job;
275 
276     QLIST_FOREACH(job, &jobs, job_list) {
277         if (job->id && !strcmp(id, job->id)) {
278             return job;
279         }
280     }
281 
282     return NULL;
283 }
284 
285 static void job_sleep_timer_cb(void *opaque)
286 {
287     Job *job = opaque;
288 
289     job_enter(job);
290 }
291 
292 void *job_create(const char *job_id, const JobDriver *driver, JobTxn *txn,
293                  AioContext *ctx, int flags, BlockCompletionFunc *cb,
294                  void *opaque, Error **errp)
295 {
296     Job *job;
297 
298     if (job_id) {
299         if (flags & JOB_INTERNAL) {
300             error_setg(errp, "Cannot specify job ID for internal job");
301             return NULL;
302         }
303         if (!id_wellformed(job_id)) {
304             error_setg(errp, "Invalid job ID '%s'", job_id);
305             return NULL;
306         }
307         if (job_get(job_id)) {
308             error_setg(errp, "Job ID '%s' already in use", job_id);
309             return NULL;
310         }
311     } else if (!(flags & JOB_INTERNAL)) {
312         error_setg(errp, "An explicit job ID is required");
313         return NULL;
314     }
315 
316     job = g_malloc0(driver->instance_size);
317     job->driver        = driver;
318     job->id            = g_strdup(job_id);
319     job->refcnt        = 1;
320     job->aio_context   = ctx;
321     job->busy          = false;
322     job->paused        = true;
323     job->pause_count   = 1;
324     job->auto_finalize = !(flags & JOB_MANUAL_FINALIZE);
325     job->auto_dismiss  = !(flags & JOB_MANUAL_DISMISS);
326     job->cb            = cb;
327     job->opaque        = opaque;
328 
329     notifier_list_init(&job->on_finalize_cancelled);
330     notifier_list_init(&job->on_finalize_completed);
331     notifier_list_init(&job->on_pending);
332     notifier_list_init(&job->on_ready);
333 
334     job_state_transition(job, JOB_STATUS_CREATED);
335     aio_timer_init(qemu_get_aio_context(), &job->sleep_timer,
336                    QEMU_CLOCK_REALTIME, SCALE_NS,
337                    job_sleep_timer_cb, job);
338 
339     QLIST_INSERT_HEAD(&jobs, job, job_list);
340 
341     /* Single jobs are modeled as single-job transactions for sake of
342      * consolidating the job management logic */
343     if (!txn) {
344         txn = job_txn_new();
345         job_txn_add_job(txn, job);
346         job_txn_unref(txn);
347     } else {
348         job_txn_add_job(txn, job);
349     }
350 
351     return job;
352 }
353 
354 void job_ref(Job *job)
355 {
356     ++job->refcnt;
357 }
358 
359 void job_unref(Job *job)
360 {
361     if (--job->refcnt == 0) {
362         assert(job->status == JOB_STATUS_NULL);
363         assert(!timer_pending(&job->sleep_timer));
364         assert(!job->txn);
365 
366         if (job->driver->free) {
367             job->driver->free(job);
368         }
369 
370         QLIST_REMOVE(job, job_list);
371 
372         g_free(job->error);
373         g_free(job->id);
374         g_free(job);
375     }
376 }
377 
378 void job_progress_update(Job *job, uint64_t done)
379 {
380     job->progress_current += done;
381 }
382 
383 void job_progress_set_remaining(Job *job, uint64_t remaining)
384 {
385     job->progress_total = job->progress_current + remaining;
386 }
387 
388 void job_progress_increase_remaining(Job *job, uint64_t delta)
389 {
390     job->progress_total += delta;
391 }
392 
393 void job_event_cancelled(Job *job)
394 {
395     notifier_list_notify(&job->on_finalize_cancelled, job);
396 }
397 
398 void job_event_completed(Job *job)
399 {
400     notifier_list_notify(&job->on_finalize_completed, job);
401 }
402 
403 static void job_event_pending(Job *job)
404 {
405     notifier_list_notify(&job->on_pending, job);
406 }
407 
408 static void job_event_ready(Job *job)
409 {
410     notifier_list_notify(&job->on_ready, job);
411 }
412 
413 void job_enter_cond(Job *job, bool(*fn)(Job *job))
414 {
415     if (!job_started(job)) {
416         return;
417     }
418     if (job->deferred_to_main_loop) {
419         return;
420     }
421 
422     job_lock();
423     if (job->busy) {
424         job_unlock();
425         return;
426     }
427 
428     if (fn && !fn(job)) {
429         job_unlock();
430         return;
431     }
432 
433     assert(!job->deferred_to_main_loop);
434     timer_del(&job->sleep_timer);
435     job->busy = true;
436     job_unlock();
437     aio_co_wake(job->co);
438 }
439 
440 void job_enter(Job *job)
441 {
442     job_enter_cond(job, NULL);
443 }
444 
445 /* Yield, and schedule a timer to reenter the coroutine after @ns nanoseconds.
446  * Reentering the job coroutine with job_enter() before the timer has expired
447  * is allowed and cancels the timer.
448  *
449  * If @ns is (uint64_t) -1, no timer is scheduled and job_enter() must be
450  * called explicitly. */
451 static void coroutine_fn job_do_yield(Job *job, uint64_t ns)
452 {
453     job_lock();
454     if (ns != -1) {
455         timer_mod(&job->sleep_timer, ns);
456     }
457     job->busy = false;
458     job_unlock();
459     qemu_coroutine_yield();
460 
461     /* Set by job_enter_cond() before re-entering the coroutine.  */
462     assert(job->busy);
463 }
464 
465 void coroutine_fn job_pause_point(Job *job)
466 {
467     assert(job && job_started(job));
468 
469     if (!job_should_pause(job)) {
470         return;
471     }
472     if (job_is_cancelled(job)) {
473         return;
474     }
475 
476     if (job->driver->pause) {
477         job->driver->pause(job);
478     }
479 
480     if (job_should_pause(job) && !job_is_cancelled(job)) {
481         JobStatus status = job->status;
482         job_state_transition(job, status == JOB_STATUS_READY
483                                   ? JOB_STATUS_STANDBY
484                                   : JOB_STATUS_PAUSED);
485         job->paused = true;
486         job_do_yield(job, -1);
487         job->paused = false;
488         job_state_transition(job, status);
489     }
490 
491     if (job->driver->resume) {
492         job->driver->resume(job);
493     }
494 }
495 
496 void job_yield(Job *job)
497 {
498     assert(job->busy);
499 
500     /* Check cancellation *before* setting busy = false, too!  */
501     if (job_is_cancelled(job)) {
502         return;
503     }
504 
505     if (!job_should_pause(job)) {
506         job_do_yield(job, -1);
507     }
508 
509     job_pause_point(job);
510 }
511 
512 void coroutine_fn job_sleep_ns(Job *job, int64_t ns)
513 {
514     assert(job->busy);
515 
516     /* Check cancellation *before* setting busy = false, too!  */
517     if (job_is_cancelled(job)) {
518         return;
519     }
520 
521     if (!job_should_pause(job)) {
522         job_do_yield(job, qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + ns);
523     }
524 
525     job_pause_point(job);
526 }
527 
528 void job_drain(Job *job)
529 {
530     /* If job is !busy this kicks it into the next pause point. */
531     job_enter(job);
532 
533     if (job->driver->drain) {
534         job->driver->drain(job);
535     }
536 }
537 
538 
539 /**
540  * All jobs must allow a pause point before entering their job proper. This
541  * ensures that jobs can be paused prior to being started, then resumed later.
542  */
543 static void coroutine_fn job_co_entry(void *opaque)
544 {
545     Job *job = opaque;
546 
547     assert(job && job->driver && job->driver->start);
548     job_pause_point(job);
549     job->driver->start(job);
550 }
551 
552 
553 void job_start(Job *job)
554 {
555     assert(job && !job_started(job) && job->paused &&
556            job->driver && job->driver->start);
557     job->co = qemu_coroutine_create(job_co_entry, job);
558     job->pause_count--;
559     job->busy = true;
560     job->paused = false;
561     job_state_transition(job, JOB_STATUS_RUNNING);
562     aio_co_enter(job->aio_context, job->co);
563 }
564 
565 /* Assumes the block_job_mutex is held */
566 static bool job_timer_not_pending(Job *job)
567 {
568     return !timer_pending(&job->sleep_timer);
569 }
570 
571 void job_pause(Job *job)
572 {
573     job->pause_count++;
574 }
575 
576 void job_resume(Job *job)
577 {
578     assert(job->pause_count > 0);
579     job->pause_count--;
580     if (job->pause_count) {
581         return;
582     }
583 
584     /* kick only if no timer is pending */
585     job_enter_cond(job, job_timer_not_pending);
586 }
587 
588 void job_user_pause(Job *job, Error **errp)
589 {
590     if (job_apply_verb(job, JOB_VERB_PAUSE, errp)) {
591         return;
592     }
593     if (job->user_paused) {
594         error_setg(errp, "Job is already paused");
595         return;
596     }
597     job->user_paused = true;
598     job_pause(job);
599 }
600 
601 bool job_user_paused(Job *job)
602 {
603     return job->user_paused;
604 }
605 
606 void job_user_resume(Job *job, Error **errp)
607 {
608     assert(job);
609     if (!job->user_paused || job->pause_count <= 0) {
610         error_setg(errp, "Can't resume a job that was not paused");
611         return;
612     }
613     if (job_apply_verb(job, JOB_VERB_RESUME, errp)) {
614         return;
615     }
616     if (job->driver->user_resume) {
617         job->driver->user_resume(job);
618     }
619     job->user_paused = false;
620     job_resume(job);
621 }
622 
623 static void job_do_dismiss(Job *job)
624 {
625     assert(job);
626     job->busy = false;
627     job->paused = false;
628     job->deferred_to_main_loop = true;
629 
630     job_txn_del_job(job);
631 
632     job_state_transition(job, JOB_STATUS_NULL);
633     job_unref(job);
634 }
635 
636 void job_dismiss(Job **jobptr, Error **errp)
637 {
638     Job *job = *jobptr;
639     /* similarly to _complete, this is QMP-interface only. */
640     assert(job->id);
641     if (job_apply_verb(job, JOB_VERB_DISMISS, errp)) {
642         return;
643     }
644 
645     job_do_dismiss(job);
646     *jobptr = NULL;
647 }
648 
649 void job_early_fail(Job *job)
650 {
651     assert(job->status == JOB_STATUS_CREATED);
652     job_do_dismiss(job);
653 }
654 
655 static void job_conclude(Job *job)
656 {
657     job_state_transition(job, JOB_STATUS_CONCLUDED);
658     if (job->auto_dismiss || !job_started(job)) {
659         job_do_dismiss(job);
660     }
661 }
662 
663 static void job_update_rc(Job *job)
664 {
665     if (!job->ret && job_is_cancelled(job)) {
666         job->ret = -ECANCELED;
667     }
668     if (job->ret) {
669         if (!job->error) {
670             job->error = g_strdup(strerror(-job->ret));
671         }
672         job_state_transition(job, JOB_STATUS_ABORTING);
673     }
674 }
675 
676 static void job_commit(Job *job)
677 {
678     assert(!job->ret);
679     if (job->driver->commit) {
680         job->driver->commit(job);
681     }
682 }
683 
684 static void job_abort(Job *job)
685 {
686     assert(job->ret);
687     if (job->driver->abort) {
688         job->driver->abort(job);
689     }
690 }
691 
692 static void job_clean(Job *job)
693 {
694     if (job->driver->clean) {
695         job->driver->clean(job);
696     }
697 }
698 
699 static int job_finalize_single(Job *job)
700 {
701     assert(job_is_completed(job));
702 
703     /* Ensure abort is called for late-transactional failures */
704     job_update_rc(job);
705 
706     if (!job->ret) {
707         job_commit(job);
708     } else {
709         job_abort(job);
710     }
711     job_clean(job);
712 
713     if (job->cb) {
714         job->cb(job->opaque, job->ret);
715     }
716 
717     /* Emit events only if we actually started */
718     if (job_started(job)) {
719         if (job_is_cancelled(job)) {
720             job_event_cancelled(job);
721         } else {
722             job_event_completed(job);
723         }
724     }
725 
726     job_txn_del_job(job);
727     job_conclude(job);
728     return 0;
729 }
730 
731 static void job_cancel_async(Job *job, bool force)
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     job->cancelled = true;
743     /* To prevent 'force == false' overriding a previous 'force == true' */
744     job->force_cancel |= force;
745 }
746 
747 static void job_completed_txn_abort(Job *job)
748 {
749     AioContext *ctx;
750     JobTxn *txn = job->txn;
751     Job *other_job;
752 
753     if (txn->aborting) {
754         /*
755          * We are cancelled by another job, which will handle everything.
756          */
757         return;
758     }
759     txn->aborting = true;
760     job_txn_ref(txn);
761 
762     /* We are the first failed job. Cancel other jobs. */
763     QLIST_FOREACH(other_job, &txn->jobs, txn_list) {
764         ctx = other_job->aio_context;
765         aio_context_acquire(ctx);
766     }
767 
768     /* Other jobs are effectively cancelled by us, set the status for
769      * them; this job, however, may or may not be cancelled, depending
770      * on the caller, so leave it. */
771     QLIST_FOREACH(other_job, &txn->jobs, txn_list) {
772         if (other_job != job) {
773             job_cancel_async(other_job, false);
774         }
775     }
776     while (!QLIST_EMPTY(&txn->jobs)) {
777         other_job = QLIST_FIRST(&txn->jobs);
778         ctx = other_job->aio_context;
779         if (!job_is_completed(other_job)) {
780             assert(job_is_cancelled(other_job));
781             job_finish_sync(other_job, NULL, NULL);
782         }
783         job_finalize_single(other_job);
784         aio_context_release(ctx);
785     }
786 
787     job_txn_unref(txn);
788 }
789 
790 static int job_prepare(Job *job)
791 {
792     if (job->ret == 0 && job->driver->prepare) {
793         job->ret = job->driver->prepare(job);
794         job_update_rc(job);
795     }
796     return job->ret;
797 }
798 
799 static int job_needs_finalize(Job *job)
800 {
801     return !job->auto_finalize;
802 }
803 
804 static void job_do_finalize(Job *job)
805 {
806     int rc;
807     assert(job && job->txn);
808 
809     /* prepare the transaction to complete */
810     rc = job_txn_apply(job->txn, job_prepare, true);
811     if (rc) {
812         job_completed_txn_abort(job);
813     } else {
814         job_txn_apply(job->txn, job_finalize_single, true);
815     }
816 }
817 
818 void job_finalize(Job *job, Error **errp)
819 {
820     assert(job && job->id);
821     if (job_apply_verb(job, JOB_VERB_FINALIZE, errp)) {
822         return;
823     }
824     job_do_finalize(job);
825 }
826 
827 static int job_transition_to_pending(Job *job)
828 {
829     job_state_transition(job, JOB_STATUS_PENDING);
830     if (!job->auto_finalize) {
831         job_event_pending(job);
832     }
833     return 0;
834 }
835 
836 void job_transition_to_ready(Job *job)
837 {
838     job_state_transition(job, JOB_STATUS_READY);
839     job_event_ready(job);
840 }
841 
842 static void job_completed_txn_success(Job *job)
843 {
844     JobTxn *txn = job->txn;
845     Job *other_job;
846 
847     job_state_transition(job, JOB_STATUS_WAITING);
848 
849     /*
850      * Successful completion, see if there are other running jobs in this
851      * txn.
852      */
853     QLIST_FOREACH(other_job, &txn->jobs, txn_list) {
854         if (!job_is_completed(other_job)) {
855             return;
856         }
857         assert(other_job->ret == 0);
858     }
859 
860     job_txn_apply(txn, job_transition_to_pending, false);
861 
862     /* If no jobs need manual finalization, automatically do so */
863     if (job_txn_apply(txn, job_needs_finalize, false) == 0) {
864         job_do_finalize(job);
865     }
866 }
867 
868 void job_completed(Job *job, int ret, Error *error)
869 {
870     assert(job && job->txn && !job_is_completed(job));
871 
872     job->ret = ret;
873     if (error) {
874         assert(job->ret < 0);
875         job->error = g_strdup(error_get_pretty(error));
876         error_free(error);
877     }
878 
879     job_update_rc(job);
880     trace_job_completed(job, ret, job->ret);
881     if (job->ret) {
882         job_completed_txn_abort(job);
883     } else {
884         job_completed_txn_success(job);
885     }
886 }
887 
888 void job_cancel(Job *job, bool force)
889 {
890     if (job->status == JOB_STATUS_CONCLUDED) {
891         job_do_dismiss(job);
892         return;
893     }
894     job_cancel_async(job, force);
895     if (!job_started(job)) {
896         job_completed(job, -ECANCELED, NULL);
897     } else if (job->deferred_to_main_loop) {
898         job_completed_txn_abort(job);
899     } else {
900         job_enter(job);
901     }
902 }
903 
904 void job_user_cancel(Job *job, bool force, Error **errp)
905 {
906     if (job_apply_verb(job, JOB_VERB_CANCEL, errp)) {
907         return;
908     }
909     job_cancel(job, force);
910 }
911 
912 /* A wrapper around job_cancel() taking an Error ** parameter so it may be
913  * used with job_finish_sync() without the need for (rather nasty) function
914  * pointer casts there. */
915 static void job_cancel_err(Job *job, Error **errp)
916 {
917     job_cancel(job, false);
918 }
919 
920 int job_cancel_sync(Job *job)
921 {
922     return job_finish_sync(job, &job_cancel_err, NULL);
923 }
924 
925 void job_cancel_sync_all(void)
926 {
927     Job *job;
928     AioContext *aio_context;
929 
930     while ((job = job_next(NULL))) {
931         aio_context = job->aio_context;
932         aio_context_acquire(aio_context);
933         job_cancel_sync(job);
934         aio_context_release(aio_context);
935     }
936 }
937 
938 int job_complete_sync(Job *job, Error **errp)
939 {
940     return job_finish_sync(job, job_complete, errp);
941 }
942 
943 void job_complete(Job *job, Error **errp)
944 {
945     /* Should not be reachable via external interface for internal jobs */
946     assert(job->id);
947     if (job_apply_verb(job, JOB_VERB_COMPLETE, errp)) {
948         return;
949     }
950     if (job->pause_count || job_is_cancelled(job) || !job->driver->complete) {
951         error_setg(errp, "The active block job '%s' cannot be completed",
952                    job->id);
953         return;
954     }
955 
956     job->driver->complete(job, errp);
957 }
958 
959 
960 typedef struct {
961     Job *job;
962     JobDeferToMainLoopFn *fn;
963     void *opaque;
964 } JobDeferToMainLoopData;
965 
966 static void job_defer_to_main_loop_bh(void *opaque)
967 {
968     JobDeferToMainLoopData *data = opaque;
969     Job *job = data->job;
970     AioContext *aio_context = job->aio_context;
971 
972     aio_context_acquire(aio_context);
973     data->fn(data->job, data->opaque);
974     aio_context_release(aio_context);
975 
976     g_free(data);
977 }
978 
979 void job_defer_to_main_loop(Job *job, JobDeferToMainLoopFn *fn, void *opaque)
980 {
981     JobDeferToMainLoopData *data = g_malloc(sizeof(*data));
982     data->job = job;
983     data->fn = fn;
984     data->opaque = opaque;
985     job->deferred_to_main_loop = true;
986 
987     aio_bh_schedule_oneshot(qemu_get_aio_context(),
988                             job_defer_to_main_loop_bh, data);
989 }
990 
991 int job_finish_sync(Job *job, void (*finish)(Job *, Error **errp), Error **errp)
992 {
993     Error *local_err = NULL;
994     int ret;
995 
996     job_ref(job);
997 
998     if (finish) {
999         finish(job, &local_err);
1000     }
1001     if (local_err) {
1002         error_propagate(errp, local_err);
1003         job_unref(job);
1004         return -EBUSY;
1005     }
1006     /* job_drain calls job_enter, and it should be enough to induce progress
1007      * until the job completes or moves to the main thread. */
1008     while (!job->deferred_to_main_loop && !job_is_completed(job)) {
1009         job_drain(job);
1010     }
1011     while (!job_is_completed(job)) {
1012         aio_poll(qemu_get_aio_context(), true);
1013     }
1014     ret = (job_is_cancelled(job) && job->ret == 0) ? -ECANCELED : job->ret;
1015     job_unref(job);
1016     return ret;
1017 }
1018