]> git.proxmox.com Git - mirror_qemu.git/blame - blockjob.c
vfio/pci: Emulate BARs
[mirror_qemu.git] / blockjob.c
CommitLineData
2f0c9fe6
PB
1/*
2 * QEMU System Emulator block driver
3 *
4 * Copyright (c) 2011 IBM Corp.
5 * Copyright (c) 2012 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
d38ea87a 26#include "qemu/osdep.h"
2f0c9fe6 27#include "qemu-common.h"
737e150e 28#include "block/block.h"
c87621ea 29#include "block/blockjob_int.h"
737e150e 30#include "block/block_int.h"
373340b2 31#include "sysemu/block-backend.h"
cc7a8ea7 32#include "qapi/qmp/qerror.h"
7b1b5d19 33#include "qapi/qmp/qjson.h"
10817bf0 34#include "qemu/coroutine.h"
7f0317cf 35#include "qemu/id.h"
2f0c9fe6 36#include "qmp-commands.h"
1de7afc9 37#include "qemu/timer.h"
5a2d2cbd 38#include "qapi-event.h"
2f0c9fe6 39
fc24908e
PB
40/* Right now, this mutex is only needed to synchronize accesses to job->busy
41 * and job->sleep_timer, such as concurrent calls to block_job_do_yield and
42 * block_job_enter. */
43static QemuMutex block_job_mutex;
44
45static void block_job_lock(void)
46{
47 qemu_mutex_lock(&block_job_mutex);
48}
49
50static void block_job_unlock(void)
51{
52 qemu_mutex_unlock(&block_job_mutex);
53}
54
55static void __attribute__((__constructor__)) block_job_init(void)
56{
57 qemu_mutex_init(&block_job_mutex);
58}
59
8254b6d9
JS
60static void block_job_event_cancelled(BlockJob *job);
61static void block_job_event_completed(BlockJob *job, const char *msg);
aa9ef2e6 62static void block_job_enter_cond(BlockJob *job, bool(*fn)(BlockJob *job));
8254b6d9 63
c55a832f
FZ
64/* Transactional group of block jobs */
65struct BlockJobTxn {
66
67 /* Is this txn being cancelled? */
68 bool aborting;
69
70 /* List of jobs */
71 QLIST_HEAD(, BlockJob) jobs;
72
73 /* Reference count */
74 int refcnt;
75};
76
a7112795
AG
77static QLIST_HEAD(, BlockJob) block_jobs = QLIST_HEAD_INITIALIZER(block_jobs);
78
88691b37
PB
79/*
80 * The block job API is composed of two categories of functions.
81 *
82 * The first includes functions used by the monitor. The monitor is
83 * peculiar in that it accesses the block job list with block_job_get, and
84 * therefore needs consistency across block_job_get and the actual operation
85 * (e.g. block_job_set_speed). The consistency is achieved with
86 * aio_context_acquire/release. These functions are declared in blockjob.h.
87 *
88 * The second includes functions used by the block job drivers and sometimes
89 * by the core block layer. These do not care about locking, because the
90 * whole coroutine runs under the AioContext lock, and are declared in
91 * blockjob_int.h.
92 */
93
a7112795
AG
94BlockJob *block_job_next(BlockJob *job)
95{
96 if (!job) {
97 return QLIST_FIRST(&block_jobs);
98 }
99 return QLIST_NEXT(job, job_list);
100}
101
ffb1f10c
AG
102BlockJob *block_job_get(const char *id)
103{
104 BlockJob *job;
105
106 QLIST_FOREACH(job, &block_jobs, job_list) {
559b935f 107 if (job->id && !strcmp(id, job->id)) {
ffb1f10c
AG
108 return job;
109 }
110 }
111
112 return NULL;
113}
114
c8ab5c2d
PB
115BlockJobTxn *block_job_txn_new(void)
116{
117 BlockJobTxn *txn = g_new0(BlockJobTxn, 1);
118 QLIST_INIT(&txn->jobs);
119 txn->refcnt = 1;
120 return txn;
121}
122
123static void block_job_txn_ref(BlockJobTxn *txn)
124{
125 txn->refcnt++;
126}
127
128void block_job_txn_unref(BlockJobTxn *txn)
129{
130 if (txn && --txn->refcnt == 0) {
131 g_free(txn);
132 }
133}
134
135void block_job_txn_add_job(BlockJobTxn *txn, BlockJob *job)
136{
137 if (!txn) {
138 return;
139 }
140
141 assert(!job->txn);
142 job->txn = txn;
143
144 QLIST_INSERT_HEAD(&txn->jobs, job, txn_list);
145 block_job_txn_ref(txn);
146}
147
f321dcb5
PB
148static void block_job_pause(BlockJob *job)
149{
150 job->pause_count++;
151}
152
153static void block_job_resume(BlockJob *job)
154{
155 assert(job->pause_count > 0);
156 job->pause_count--;
157 if (job->pause_count) {
158 return;
159 }
160 block_job_enter(job);
161}
162
4172a003 163void block_job_ref(BlockJob *job)
05b0d8e3
PB
164{
165 ++job->refcnt;
166}
167
168static void block_job_attached_aio_context(AioContext *new_context,
169 void *opaque);
170static void block_job_detach_aio_context(void *opaque);
171
4172a003 172void block_job_unref(BlockJob *job)
05b0d8e3
PB
173{
174 if (--job->refcnt == 0) {
175 BlockDriverState *bs = blk_bs(job->blk);
0a3e155f 176 QLIST_REMOVE(job, job_list);
05b0d8e3
PB
177 bs->job = NULL;
178 block_job_remove_all_bdrv(job);
179 blk_remove_aio_context_notifier(job->blk,
180 block_job_attached_aio_context,
181 block_job_detach_aio_context, job);
182 blk_unref(job->blk);
183 error_free(job->blocker);
184 g_free(job->id);
fc24908e 185 assert(!timer_pending(&job->sleep_timer));
05b0d8e3
PB
186 g_free(job);
187 }
188}
189
463e0be1
SH
190static void block_job_attached_aio_context(AioContext *new_context,
191 void *opaque)
192{
193 BlockJob *job = opaque;
194
195 if (job->driver->attached_aio_context) {
196 job->driver->attached_aio_context(job, new_context);
197 }
198
199 block_job_resume(job);
200}
201
bae8196d
PB
202static void block_job_drain(BlockJob *job)
203{
204 /* If job is !job->busy this kicks it into the next pause point. */
205 block_job_enter(job);
206
207 blk_drain(job->blk);
208 if (job->driver->drain) {
209 job->driver->drain(job);
210 }
211}
212
463e0be1
SH
213static void block_job_detach_aio_context(void *opaque)
214{
215 BlockJob *job = opaque;
216
217 /* In case the job terminates during aio_poll()... */
218 block_job_ref(job);
219
220 block_job_pause(job);
221
463e0be1 222 while (!job->paused && !job->completed) {
bae8196d 223 block_job_drain(job);
463e0be1
SH
224 }
225
226 block_job_unref(job);
227}
228
f321dcb5
PB
229static char *child_job_get_parent_desc(BdrvChild *c)
230{
231 BlockJob *job = c->opaque;
232 return g_strdup_printf("%s job '%s'",
977c736f 233 BlockJobType_str(job->driver->job_type),
f321dcb5
PB
234 job->id);
235}
236
ad90feba 237static void child_job_drained_begin(BdrvChild *c)
f321dcb5 238{
ad90feba 239 BlockJob *job = c->opaque;
f321dcb5
PB
240 block_job_pause(job);
241}
242
ad90feba 243static void child_job_drained_end(BdrvChild *c)
f321dcb5 244{
ad90feba 245 BlockJob *job = c->opaque;
f321dcb5
PB
246 block_job_resume(job);
247}
248
ad90feba
KW
249static const BdrvChildRole child_job = {
250 .get_parent_desc = child_job_get_parent_desc,
251 .drained_begin = child_job_drained_begin,
252 .drained_end = child_job_drained_end,
253 .stay_at_node = true,
f321dcb5
PB
254};
255
bbc02b90
KW
256void block_job_remove_all_bdrv(BlockJob *job)
257{
258 GSList *l;
259 for (l = job->nodes; l; l = l->next) {
260 BdrvChild *c = l->data;
261 bdrv_op_unblock_all(c->bs, job->blocker);
262 bdrv_root_unref_child(c);
263 }
264 g_slist_free(job->nodes);
265 job->nodes = NULL;
266}
267
76d554e2
KW
268int block_job_add_bdrv(BlockJob *job, const char *name, BlockDriverState *bs,
269 uint64_t perm, uint64_t shared_perm, Error **errp)
23d402d4 270{
76d554e2
KW
271 BdrvChild *c;
272
273 c = bdrv_root_attach_child(bs, name, &child_job, perm, shared_perm,
274 job, errp);
275 if (c == NULL) {
276 return -EPERM;
277 }
278
279 job->nodes = g_slist_prepend(job->nodes, c);
23d402d4
AG
280 bdrv_ref(bs);
281 bdrv_op_block_all(bs, job->blocker);
76d554e2
KW
282
283 return 0;
23d402d4
AG
284}
285
559b935f
JS
286bool block_job_is_internal(BlockJob *job)
287{
288 return (job->id == NULL);
289}
290
5ccac6f1
JS
291static bool block_job_started(BlockJob *job)
292{
293 return job->co;
294}
295
e3796a24
JS
296/**
297 * All jobs must allow a pause point before entering their job proper. This
298 * ensures that jobs can be paused prior to being started, then resumed later.
299 */
300static void coroutine_fn block_job_co_entry(void *opaque)
301{
302 BlockJob *job = opaque;
303
304 assert(job && job->driver && job->driver->start);
305 block_job_pause_point(job);
306 job->driver->start(job);
307}
308
fc24908e
PB
309static void block_job_sleep_timer_cb(void *opaque)
310{
311 BlockJob *job = opaque;
312
313 block_job_enter(job);
314}
315
5ccac6f1
JS
316void block_job_start(BlockJob *job)
317{
318 assert(job && !block_job_started(job) && job->paused &&
e3796a24
JS
319 job->driver && job->driver->start);
320 job->co = qemu_coroutine_create(block_job_co_entry, job);
321 job->pause_count--;
322 job->busy = true;
323 job->paused = false;
aef4278c 324 bdrv_coroutine_enter(blk_bs(job->blk), job->co);
5ccac6f1
JS
325}
326
c55a832f
FZ
327static void block_job_completed_single(BlockJob *job)
328{
4fb588e9
PB
329 assert(job->completed);
330
c55a832f
FZ
331 if (!job->ret) {
332 if (job->driver->commit) {
333 job->driver->commit(job);
334 }
335 } else {
336 if (job->driver->abort) {
337 job->driver->abort(job);
338 }
339 }
e8a40bf7
JS
340 if (job->driver->clean) {
341 job->driver->clean(job);
342 }
8254b6d9
JS
343
344 if (job->cb) {
345 job->cb(job->opaque, job->ret);
346 }
5ccac6f1
JS
347
348 /* Emit events only if we actually started */
349 if (block_job_started(job)) {
350 if (block_job_is_cancelled(job)) {
351 block_job_event_cancelled(job);
352 } else {
353 const char *msg = NULL;
354 if (job->ret < 0) {
355 msg = strerror(-job->ret);
356 }
357 block_job_event_completed(job, msg);
8254b6d9 358 }
8254b6d9
JS
359 }
360
c55a832f 361 if (job->txn) {
1e93b9fb 362 QLIST_REMOVE(job, txn_list);
c55a832f
FZ
363 block_job_txn_unref(job->txn);
364 }
365 block_job_unref(job);
366}
367
4c241cf5
PB
368static void block_job_cancel_async(BlockJob *job)
369{
370 if (job->iostatus != BLOCK_DEVICE_IO_STATUS_OK) {
371 block_job_iostatus_reset(job);
372 }
373 if (job->user_paused) {
374 /* Do not call block_job_enter here, the caller will handle it. */
375 job->user_paused = false;
376 job->pause_count--;
377 }
378 job->cancelled = true;
379}
380
c8ab5c2d
PB
381static int block_job_finish_sync(BlockJob *job,
382 void (*finish)(BlockJob *, Error **errp),
383 Error **errp)
384{
385 Error *local_err = NULL;
386 int ret;
387
388 assert(blk_bs(job->blk)->job == job);
389
390 block_job_ref(job);
391
4fb588e9
PB
392 if (finish) {
393 finish(job, &local_err);
394 }
c8ab5c2d
PB
395 if (local_err) {
396 error_propagate(errp, local_err);
397 block_job_unref(job);
398 return -EBUSY;
399 }
400 /* block_job_drain calls block_job_enter, and it should be enough to
401 * induce progress until the job completes or moves to the main thread.
402 */
403 while (!job->deferred_to_main_loop && !job->completed) {
404 block_job_drain(job);
405 }
406 while (!job->completed) {
407 aio_poll(qemu_get_aio_context(), true);
408 }
409 ret = (job->cancelled && job->ret == 0) ? -ECANCELED : job->ret;
410 block_job_unref(job);
411 return ret;
412}
413
c55a832f
FZ
414static void block_job_completed_txn_abort(BlockJob *job)
415{
416 AioContext *ctx;
417 BlockJobTxn *txn = job->txn;
4fb588e9 418 BlockJob *other_job;
c55a832f
FZ
419
420 if (txn->aborting) {
421 /*
422 * We are cancelled by another job, which will handle everything.
423 */
424 return;
425 }
426 txn->aborting = true;
4fb588e9
PB
427 block_job_txn_ref(txn);
428
c55a832f
FZ
429 /* We are the first failed job. Cancel other jobs. */
430 QLIST_FOREACH(other_job, &txn->jobs, txn_list) {
b6d2e599 431 ctx = blk_get_aio_context(other_job->blk);
c55a832f
FZ
432 aio_context_acquire(ctx);
433 }
4fb588e9
PB
434
435 /* Other jobs are effectively cancelled by us, set the status for
436 * them; this job, however, may or may not be cancelled, depending
437 * on the caller, so leave it. */
c55a832f 438 QLIST_FOREACH(other_job, &txn->jobs, txn_list) {
4fb588e9
PB
439 if (other_job != job) {
440 block_job_cancel_async(other_job);
c55a832f 441 }
c55a832f 442 }
4fb588e9
PB
443 while (!QLIST_EMPTY(&txn->jobs)) {
444 other_job = QLIST_FIRST(&txn->jobs);
b6d2e599 445 ctx = blk_get_aio_context(other_job->blk);
4fb588e9
PB
446 if (!other_job->completed) {
447 assert(other_job->cancelled);
448 block_job_finish_sync(other_job, NULL, NULL);
449 }
c55a832f
FZ
450 block_job_completed_single(other_job);
451 aio_context_release(ctx);
452 }
4fb588e9
PB
453
454 block_job_txn_unref(txn);
c55a832f
FZ
455}
456
457static void block_job_completed_txn_success(BlockJob *job)
458{
459 AioContext *ctx;
460 BlockJobTxn *txn = job->txn;
461 BlockJob *other_job, *next;
462 /*
463 * Successful completion, see if there are other running jobs in this
464 * txn.
465 */
466 QLIST_FOREACH(other_job, &txn->jobs, txn_list) {
467 if (!other_job->completed) {
468 return;
469 }
470 }
471 /* We are the last completed job, commit the transaction. */
472 QLIST_FOREACH_SAFE(other_job, &txn->jobs, txn_list, next) {
b6d2e599 473 ctx = blk_get_aio_context(other_job->blk);
c55a832f
FZ
474 aio_context_acquire(ctx);
475 assert(other_job->ret == 0);
476 block_job_completed_single(other_job);
477 aio_context_release(ctx);
478 }
479}
480
aa9ef2e6
JS
481/* Assumes the block_job_mutex is held */
482static bool block_job_timer_pending(BlockJob *job)
483{
484 return timer_pending(&job->sleep_timer);
485}
486
2f0c9fe6
PB
487void block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
488{
489 Error *local_err = NULL;
aa9ef2e6 490 int64_t old_speed = job->speed;
2f0c9fe6 491
3fc4b10a 492 if (!job->driver->set_speed) {
c6bd8c70 493 error_setg(errp, QERR_UNSUPPORTED);
2f0c9fe6
PB
494 return;
495 }
3fc4b10a 496 job->driver->set_speed(job, speed, &local_err);
84d18f06 497 if (local_err) {
2f0c9fe6
PB
498 error_propagate(errp, local_err);
499 return;
500 }
501
502 job->speed = speed;
aa9ef2e6
JS
503 if (speed <= old_speed) {
504 return;
505 }
506
507 /* kick only if a timer is pending */
508 block_job_enter_cond(job, block_job_timer_pending);
2f0c9fe6
PB
509}
510
aeae883b
PB
511void block_job_complete(BlockJob *job, Error **errp)
512{
559b935f
JS
513 /* Should not be reachable via external interface for internal jobs */
514 assert(job->id);
5ccac6f1
JS
515 if (job->pause_count || job->cancelled ||
516 !block_job_started(job) || !job->driver->complete) {
9df229c3
AG
517 error_setg(errp, "The active block job '%s' cannot be completed",
518 job->id);
aeae883b
PB
519 return;
520 }
521
3fc4b10a 522 job->driver->complete(job, errp);
aeae883b
PB
523}
524
0df4ba58
JS
525void block_job_user_pause(BlockJob *job)
526{
527 job->user_paused = true;
528 block_job_pause(job);
529}
530
0df4ba58
JS
531bool block_job_user_paused(BlockJob *job)
532{
6573d9c6 533 return job->user_paused;
0df4ba58
JS
534}
535
0df4ba58
JS
536void block_job_user_resume(BlockJob *job)
537{
538 if (job && job->user_paused && job->pause_count > 0) {
2caf63a9 539 block_job_iostatus_reset(job);
4c241cf5 540 job->user_paused = false;
0df4ba58
JS
541 block_job_resume(job);
542 }
543}
544
8acc72a4
PB
545void block_job_cancel(BlockJob *job)
546{
5ccac6f1 547 if (block_job_started(job)) {
4c241cf5 548 block_job_cancel_async(job);
5ccac6f1
JS
549 block_job_enter(job);
550 } else {
551 block_job_completed(job, -ECANCELED);
552 }
8acc72a4
PB
553}
554
345f9e1b
HR
555/* A wrapper around block_job_cancel() taking an Error ** parameter so it may be
556 * used with block_job_finish_sync() without the need for (rather nasty)
557 * function pointer casts there. */
558static void block_job_cancel_err(BlockJob *job, Error **errp)
559{
560 block_job_cancel(job);
561}
562
563int block_job_cancel_sync(BlockJob *job)
564{
565 return block_job_finish_sync(job, &block_job_cancel_err, NULL);
566}
567
a1a2af07
KW
568void block_job_cancel_sync_all(void)
569{
570 BlockJob *job;
571 AioContext *aio_context;
572
573 while ((job = QLIST_FIRST(&block_jobs))) {
b6d2e599 574 aio_context = blk_get_aio_context(job->blk);
a1a2af07
KW
575 aio_context_acquire(aio_context);
576 block_job_cancel_sync(job);
577 aio_context_release(aio_context);
578 }
579}
580
345f9e1b
HR
581int block_job_complete_sync(BlockJob *job, Error **errp)
582{
583 return block_job_finish_sync(job, &block_job_complete, errp);
584}
585
559b935f 586BlockJobInfo *block_job_query(BlockJob *job, Error **errp)
30e628b7 587{
559b935f
JS
588 BlockJobInfo *info;
589
590 if (block_job_is_internal(job)) {
591 error_setg(errp, "Cannot query QEMU internal jobs");
592 return NULL;
593 }
594 info = g_new0(BlockJobInfo, 1);
977c736f 595 info->type = g_strdup(BlockJobType_str(job->driver->job_type));
8ccb9569 596 info->device = g_strdup(job->id);
32c81a4a 597 info->len = job->len;
fc24908e 598 info->busy = atomic_read(&job->busy);
751ebd76 599 info->paused = job->pause_count > 0;
32c81a4a
PB
600 info->offset = job->offset;
601 info->speed = job->speed;
602 info->io_status = job->iostatus;
ef6dbf1e 603 info->ready = job->ready;
30e628b7
PB
604 return info;
605}
32c81a4a
PB
606
607static void block_job_iostatus_set_err(BlockJob *job, int error)
608{
609 if (job->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
610 job->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
611 BLOCK_DEVICE_IO_STATUS_FAILED;
612 }
613}
614
8254b6d9 615static void block_job_event_cancelled(BlockJob *job)
bcada37b 616{
559b935f
JS
617 if (block_job_is_internal(job)) {
618 return;
619 }
620
bcada37b 621 qapi_event_send_block_job_cancelled(job->driver->job_type,
8ccb9569 622 job->id,
bcada37b
WX
623 job->len,
624 job->offset,
625 job->speed,
626 &error_abort);
627}
32c81a4a 628
8254b6d9 629static void block_job_event_completed(BlockJob *job, const char *msg)
a66a2a36 630{
559b935f
JS
631 if (block_job_is_internal(job)) {
632 return;
633 }
634
bcada37b 635 qapi_event_send_block_job_completed(job->driver->job_type,
8ccb9569 636 job->id,
bcada37b
WX
637 job->len,
638 job->offset,
639 job->speed,
640 !!msg,
641 msg,
642 &error_abort);
a66a2a36
PB
643}
644
88691b37
PB
645/*
646 * API for block job drivers and the block layer. These functions are
647 * declared in blockjob_int.h.
648 */
649
650void *block_job_create(const char *job_id, const BlockJobDriver *driver,
651 BlockDriverState *bs, uint64_t perm,
652 uint64_t shared_perm, int64_t speed, int flags,
653 BlockCompletionFunc *cb, void *opaque, Error **errp)
654{
655 BlockBackend *blk;
656 BlockJob *job;
657 int ret;
658
659 if (bs->job) {
660 error_setg(errp, QERR_DEVICE_IN_USE, bdrv_get_device_name(bs));
661 return NULL;
662 }
663
664 if (job_id == NULL && !(flags & BLOCK_JOB_INTERNAL)) {
665 job_id = bdrv_get_device_name(bs);
666 if (!*job_id) {
667 error_setg(errp, "An explicit job ID is required for this node");
668 return NULL;
669 }
670 }
671
672 if (job_id) {
673 if (flags & BLOCK_JOB_INTERNAL) {
674 error_setg(errp, "Cannot specify job ID for internal block job");
675 return NULL;
676 }
677
678 if (!id_wellformed(job_id)) {
679 error_setg(errp, "Invalid job ID '%s'", job_id);
680 return NULL;
681 }
682
683 if (block_job_get(job_id)) {
684 error_setg(errp, "Job ID '%s' already in use", job_id);
685 return NULL;
686 }
687 }
688
689 blk = blk_new(perm, shared_perm);
690 ret = blk_insert_bs(blk, bs, errp);
691 if (ret < 0) {
692 blk_unref(blk);
693 return NULL;
694 }
695
696 job = g_malloc0(driver->instance_size);
697 job->driver = driver;
698 job->id = g_strdup(job_id);
699 job->blk = blk;
700 job->cb = cb;
701 job->opaque = opaque;
702 job->busy = false;
703 job->paused = true;
704 job->pause_count = 1;
705 job->refcnt = 1;
fc24908e
PB
706 aio_timer_init(qemu_get_aio_context(), &job->sleep_timer,
707 QEMU_CLOCK_REALTIME, SCALE_NS,
708 block_job_sleep_timer_cb, job);
88691b37
PB
709
710 error_setg(&job->blocker, "block device is in use by block job: %s",
977c736f 711 BlockJobType_str(driver->job_type));
88691b37
PB
712 block_job_add_bdrv(job, "main node", bs, 0, BLK_PERM_ALL, &error_abort);
713 bs->job = job;
714
88691b37
PB
715 bdrv_op_unblock(bs, BLOCK_OP_TYPE_DATAPLANE, job->blocker);
716
717 QLIST_INSERT_HEAD(&block_jobs, job, job_list);
718
719 blk_add_aio_context_notifier(blk, block_job_attached_aio_context,
720 block_job_detach_aio_context, job);
721
722 /* Only set speed when necessary to avoid NotSupported error */
723 if (speed != 0) {
724 Error *local_err = NULL;
725
726 block_job_set_speed(job, speed, &local_err);
727 if (local_err) {
728 block_job_unref(job);
729 error_propagate(errp, local_err);
730 return NULL;
731 }
732 }
733 return job;
734}
735
f321dcb5
PB
736void block_job_pause_all(void)
737{
738 BlockJob *job = NULL;
739 while ((job = block_job_next(job))) {
740 AioContext *aio_context = blk_get_aio_context(job->blk);
741
742 aio_context_acquire(aio_context);
3d5d319e 743 block_job_ref(job);
f321dcb5
PB
744 block_job_pause(job);
745 aio_context_release(aio_context);
746 }
747}
748
88691b37
PB
749void block_job_early_fail(BlockJob *job)
750{
751 block_job_unref(job);
752}
753
754void block_job_completed(BlockJob *job, int ret)
755{
756 assert(blk_bs(job->blk)->job == job);
757 assert(!job->completed);
758 job->completed = true;
759 job->ret = ret;
760 if (!job->txn) {
761 block_job_completed_single(job);
762 } else if (ret < 0 || block_job_is_cancelled(job)) {
763 block_job_completed_txn_abort(job);
764 } else {
765 block_job_completed_txn_success(job);
766 }
767}
768
769static bool block_job_should_pause(BlockJob *job)
770{
771 return job->pause_count > 0;
772}
773
fc24908e
PB
774/* Yield, and schedule a timer to reenter the coroutine after @ns nanoseconds.
775 * Reentering the job coroutine with block_job_enter() before the timer has
776 * expired is allowed and cancels the timer.
777 *
778 * If @ns is (uint64_t) -1, no timer is scheduled and block_job_enter() must be
779 * called explicitly. */
780static void block_job_do_yield(BlockJob *job, uint64_t ns)
356f59b8 781{
fc24908e
PB
782 block_job_lock();
783 if (ns != -1) {
784 timer_mod(&job->sleep_timer, ns);
785 }
356f59b8 786 job->busy = false;
fc24908e 787 block_job_unlock();
356f59b8
PB
788 qemu_coroutine_yield();
789
790 /* Set by block_job_enter before re-entering the coroutine. */
791 assert(job->busy);
792}
793
88691b37
PB
794void coroutine_fn block_job_pause_point(BlockJob *job)
795{
796 assert(job && block_job_started(job));
797
798 if (!block_job_should_pause(job)) {
799 return;
800 }
801 if (block_job_is_cancelled(job)) {
802 return;
803 }
804
805 if (job->driver->pause) {
806 job->driver->pause(job);
807 }
808
809 if (block_job_should_pause(job) && !block_job_is_cancelled(job)) {
810 job->paused = true;
fc24908e 811 block_job_do_yield(job, -1);
88691b37
PB
812 job->paused = false;
813 }
814
815 if (job->driver->resume) {
816 job->driver->resume(job);
817 }
818}
819
f321dcb5
PB
820void block_job_resume_all(void)
821{
3d5d319e
AG
822 BlockJob *job, *next;
823
824 QLIST_FOREACH_SAFE(job, &block_jobs, job_list, next) {
f321dcb5
PB
825 AioContext *aio_context = blk_get_aio_context(job->blk);
826
827 aio_context_acquire(aio_context);
828 block_job_resume(job);
3d5d319e 829 block_job_unref(job);
f321dcb5
PB
830 aio_context_release(aio_context);
831 }
832}
833
aa9ef2e6
JS
834/*
835 * Conditionally enter a block_job pending a call to fn() while
836 * under the block_job_lock critical section.
837 */
838static void block_job_enter_cond(BlockJob *job, bool(*fn)(BlockJob *job))
88691b37 839{
eb05e011
PB
840 if (!block_job_started(job)) {
841 return;
842 }
843 if (job->deferred_to_main_loop) {
844 return;
845 }
846
fc24908e 847 block_job_lock();
356f59b8 848 if (job->busy) {
fc24908e 849 block_job_unlock();
356f59b8 850 return;
88691b37 851 }
356f59b8 852
aa9ef2e6
JS
853 if (fn && !fn(job)) {
854 block_job_unlock();
855 return;
856 }
857
fc24908e
PB
858 assert(!job->deferred_to_main_loop);
859 timer_del(&job->sleep_timer);
356f59b8 860 job->busy = true;
fc24908e 861 block_job_unlock();
356f59b8 862 aio_co_wake(job->co);
88691b37
PB
863}
864
aa9ef2e6
JS
865void block_job_enter(BlockJob *job)
866{
867 block_job_enter_cond(job, NULL);
868}
869
88691b37
PB
870bool block_job_is_cancelled(BlockJob *job)
871{
872 return job->cancelled;
873}
874
5bf1d5a7 875void block_job_sleep_ns(BlockJob *job, int64_t ns)
88691b37
PB
876{
877 assert(job->busy);
878
879 /* Check cancellation *before* setting busy = false, too! */
880 if (block_job_is_cancelled(job)) {
881 return;
882 }
883
88691b37 884 if (!block_job_should_pause(job)) {
fc24908e 885 block_job_do_yield(job, qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + ns);
88691b37 886 }
88691b37
PB
887
888 block_job_pause_point(job);
889}
890
891void block_job_yield(BlockJob *job)
892{
893 assert(job->busy);
894
895 /* Check cancellation *before* setting busy = false, too! */
896 if (block_job_is_cancelled(job)) {
897 return;
898 }
899
88691b37 900 if (!block_job_should_pause(job)) {
fc24908e 901 block_job_do_yield(job, -1);
88691b37 902 }
88691b37
PB
903
904 block_job_pause_point(job);
905}
906
2caf63a9
PB
907void block_job_iostatus_reset(BlockJob *job)
908{
4c241cf5
PB
909 if (job->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
910 return;
911 }
912 assert(job->user_paused && job->pause_count > 0);
2caf63a9
PB
913 job->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
914}
915
bcada37b 916void block_job_event_ready(BlockJob *job)
a66a2a36 917{
ef6dbf1e
HR
918 job->ready = true;
919
559b935f
JS
920 if (block_job_is_internal(job)) {
921 return;
922 }
923
518848a2 924 qapi_event_send_block_job_ready(job->driver->job_type,
8ccb9569 925 job->id,
518848a2
MA
926 job->len,
927 job->offset,
928 job->speed, &error_abort);
a66a2a36
PB
929}
930
81e254dc 931BlockErrorAction block_job_error_action(BlockJob *job, BlockdevOnError on_err,
32c81a4a
PB
932 int is_read, int error)
933{
934 BlockErrorAction action;
935
936 switch (on_err) {
937 case BLOCKDEV_ON_ERROR_ENOSPC:
8c398252 938 case BLOCKDEV_ON_ERROR_AUTO:
a589569f
WX
939 action = (error == ENOSPC) ?
940 BLOCK_ERROR_ACTION_STOP : BLOCK_ERROR_ACTION_REPORT;
32c81a4a
PB
941 break;
942 case BLOCKDEV_ON_ERROR_STOP:
a589569f 943 action = BLOCK_ERROR_ACTION_STOP;
32c81a4a
PB
944 break;
945 case BLOCKDEV_ON_ERROR_REPORT:
a589569f 946 action = BLOCK_ERROR_ACTION_REPORT;
32c81a4a
PB
947 break;
948 case BLOCKDEV_ON_ERROR_IGNORE:
a589569f 949 action = BLOCK_ERROR_ACTION_IGNORE;
32c81a4a
PB
950 break;
951 default:
952 abort();
953 }
559b935f
JS
954 if (!block_job_is_internal(job)) {
955 qapi_event_send_block_job_error(job->id,
956 is_read ? IO_OPERATION_TYPE_READ :
957 IO_OPERATION_TYPE_WRITE,
958 action, &error_abort);
959 }
a589569f 960 if (action == BLOCK_ERROR_ACTION_STOP) {
751ebd76 961 /* make the pause user visible, which will be resumed from QMP. */
0df4ba58 962 block_job_user_pause(job);
32c81a4a 963 block_job_iostatus_set_err(job, error);
32c81a4a
PB
964 }
965 return action;
966}
dec7d421
SH
967
968typedef struct {
969 BlockJob *job;
dec7d421
SH
970 AioContext *aio_context;
971 BlockJobDeferToMainLoopFn *fn;
972 void *opaque;
973} BlockJobDeferToMainLoopData;
974
975static void block_job_defer_to_main_loop_bh(void *opaque)
976{
977 BlockJobDeferToMainLoopData *data = opaque;
978 AioContext *aio_context;
979
dec7d421
SH
980 /* Prevent race with block_job_defer_to_main_loop() */
981 aio_context_acquire(data->aio_context);
982
983 /* Fetch BDS AioContext again, in case it has changed */
b6d2e599 984 aio_context = blk_get_aio_context(data->job->blk);
d79df2a2
PB
985 if (aio_context != data->aio_context) {
986 aio_context_acquire(aio_context);
987 }
dec7d421
SH
988
989 data->fn(data->job, data->opaque);
990
d79df2a2
PB
991 if (aio_context != data->aio_context) {
992 aio_context_release(aio_context);
993 }
dec7d421
SH
994
995 aio_context_release(data->aio_context);
996
997 g_free(data);
998}
999
1000void block_job_defer_to_main_loop(BlockJob *job,
1001 BlockJobDeferToMainLoopFn *fn,
1002 void *opaque)
1003{
1004 BlockJobDeferToMainLoopData *data = g_malloc(sizeof(*data));
1005 data->job = job;
b6d2e599 1006 data->aio_context = blk_get_aio_context(job->blk);
dec7d421
SH
1007 data->fn = fn;
1008 data->opaque = opaque;
794f0141 1009 job->deferred_to_main_loop = true;
dec7d421 1010
fffb6e12
PB
1011 aio_bh_schedule_oneshot(qemu_get_aio_context(),
1012 block_job_defer_to_main_loop_bh, data);
dec7d421 1013}