]> git.proxmox.com Git - mirror_qemu.git/blob - block/block-backend.c
block-backend: implement .change_aio_ctx in child_root
[mirror_qemu.git] / block / block-backend.c
1 /*
2 * QEMU Block backends
3 *
4 * Copyright (C) 2014-2016 Red Hat, Inc.
5 *
6 * Authors:
7 * Markus Armbruster <armbru@redhat.com>,
8 *
9 * This work is licensed under the terms of the GNU LGPL, version 2.1
10 * or later. See the COPYING.LIB file in the top-level directory.
11 */
12
13 #include "qemu/osdep.h"
14 #include "sysemu/block-backend.h"
15 #include "block/block_int.h"
16 #include "block/blockjob.h"
17 #include "block/coroutines.h"
18 #include "block/throttle-groups.h"
19 #include "hw/qdev-core.h"
20 #include "sysemu/blockdev.h"
21 #include "sysemu/runstate.h"
22 #include "sysemu/replay.h"
23 #include "qapi/error.h"
24 #include "qapi/qapi-events-block.h"
25 #include "qemu/id.h"
26 #include "qemu/main-loop.h"
27 #include "qemu/option.h"
28 #include "trace.h"
29 #include "migration/misc.h"
30
31 /* Number of coroutines to reserve per attached device model */
32 #define COROUTINE_POOL_RESERVATION 64
33
34 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
35
36 static AioContext *blk_aiocb_get_aio_context(BlockAIOCB *acb);
37
38 typedef struct BlockBackendAioNotifier {
39 void (*attached_aio_context)(AioContext *new_context, void *opaque);
40 void (*detach_aio_context)(void *opaque);
41 void *opaque;
42 QLIST_ENTRY(BlockBackendAioNotifier) list;
43 } BlockBackendAioNotifier;
44
45 struct BlockBackend {
46 char *name;
47 int refcnt;
48 BdrvChild *root;
49 AioContext *ctx;
50 DriveInfo *legacy_dinfo; /* null unless created by drive_new() */
51 QTAILQ_ENTRY(BlockBackend) link; /* for block_backends */
52 QTAILQ_ENTRY(BlockBackend) monitor_link; /* for monitor_block_backends */
53 BlockBackendPublic public;
54
55 DeviceState *dev; /* attached device model, if any */
56 const BlockDevOps *dev_ops;
57 void *dev_opaque;
58
59 /* If the BDS tree is removed, some of its options are stored here (which
60 * can be used to restore those options in the new BDS on insert) */
61 BlockBackendRootState root_state;
62
63 bool enable_write_cache;
64
65 /* I/O stats (display with "info blockstats"). */
66 BlockAcctStats stats;
67
68 BlockdevOnError on_read_error, on_write_error;
69 bool iostatus_enabled;
70 BlockDeviceIoStatus iostatus;
71
72 uint64_t perm;
73 uint64_t shared_perm;
74 bool disable_perm;
75
76 bool allow_aio_context_change;
77 bool allow_write_beyond_eof;
78
79 /* Protected by BQL */
80 NotifierList remove_bs_notifiers, insert_bs_notifiers;
81 QLIST_HEAD(, BlockBackendAioNotifier) aio_notifiers;
82
83 int quiesce_counter;
84 CoQueue queued_requests;
85 bool disable_request_queuing;
86
87 VMChangeStateEntry *vmsh;
88 bool force_allow_inactivate;
89
90 /* Number of in-flight aio requests. BlockDriverState also counts
91 * in-flight requests but aio requests can exist even when blk->root is
92 * NULL, so we cannot rely on its counter for that case.
93 * Accessed with atomic ops.
94 */
95 unsigned int in_flight;
96 };
97
98 typedef struct BlockBackendAIOCB {
99 BlockAIOCB common;
100 BlockBackend *blk;
101 int ret;
102 } BlockBackendAIOCB;
103
104 static const AIOCBInfo block_backend_aiocb_info = {
105 .get_aio_context = blk_aiocb_get_aio_context,
106 .aiocb_size = sizeof(BlockBackendAIOCB),
107 };
108
109 static void drive_info_del(DriveInfo *dinfo);
110 static BlockBackend *bdrv_first_blk(BlockDriverState *bs);
111
112 /* All BlockBackends. Protected by BQL. */
113 static QTAILQ_HEAD(, BlockBackend) block_backends =
114 QTAILQ_HEAD_INITIALIZER(block_backends);
115
116 /*
117 * All BlockBackends referenced by the monitor and which are iterated through by
118 * blk_next(). Protected by BQL.
119 */
120 static QTAILQ_HEAD(, BlockBackend) monitor_block_backends =
121 QTAILQ_HEAD_INITIALIZER(monitor_block_backends);
122
123 static void blk_root_inherit_options(BdrvChildRole role, bool parent_is_format,
124 int *child_flags, QDict *child_options,
125 int parent_flags, QDict *parent_options)
126 {
127 /* We're not supposed to call this function for root nodes */
128 abort();
129 }
130 static void blk_root_drained_begin(BdrvChild *child);
131 static bool blk_root_drained_poll(BdrvChild *child);
132 static void blk_root_drained_end(BdrvChild *child, int *drained_end_counter);
133
134 static void blk_root_change_media(BdrvChild *child, bool load);
135 static void blk_root_resize(BdrvChild *child);
136
137 static bool blk_root_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
138 GSList **ignore, Error **errp);
139 static void blk_root_set_aio_ctx(BdrvChild *child, AioContext *ctx,
140 GSList **ignore);
141 static bool blk_root_change_aio_ctx(BdrvChild *child, AioContext *ctx,
142 GHashTable *visited, Transaction *tran,
143 Error **errp);
144
145 static char *blk_root_get_parent_desc(BdrvChild *child)
146 {
147 BlockBackend *blk = child->opaque;
148 g_autofree char *dev_id = NULL;
149
150 if (blk->name) {
151 return g_strdup_printf("block device '%s'", blk->name);
152 }
153
154 dev_id = blk_get_attached_dev_id(blk);
155 if (*dev_id) {
156 return g_strdup_printf("block device '%s'", dev_id);
157 } else {
158 /* TODO Callback into the BB owner for something more detailed */
159 return g_strdup("an unnamed block device");
160 }
161 }
162
163 static const char *blk_root_get_name(BdrvChild *child)
164 {
165 return blk_name(child->opaque);
166 }
167
168 static void blk_vm_state_changed(void *opaque, bool running, RunState state)
169 {
170 Error *local_err = NULL;
171 BlockBackend *blk = opaque;
172
173 if (state == RUN_STATE_INMIGRATE) {
174 return;
175 }
176
177 qemu_del_vm_change_state_handler(blk->vmsh);
178 blk->vmsh = NULL;
179 blk_set_perm(blk, blk->perm, blk->shared_perm, &local_err);
180 if (local_err) {
181 error_report_err(local_err);
182 }
183 }
184
185 /*
186 * Notifies the user of the BlockBackend that migration has completed. qdev
187 * devices can tighten their permissions in response (specifically revoke
188 * shared write permissions that we needed for storage migration).
189 *
190 * If an error is returned, the VM cannot be allowed to be resumed.
191 */
192 static void blk_root_activate(BdrvChild *child, Error **errp)
193 {
194 BlockBackend *blk = child->opaque;
195 Error *local_err = NULL;
196 uint64_t saved_shared_perm;
197
198 if (!blk->disable_perm) {
199 return;
200 }
201
202 blk->disable_perm = false;
203
204 /*
205 * blk->shared_perm contains the permissions we want to share once
206 * migration is really completely done. For now, we need to share
207 * all; but we also need to retain blk->shared_perm, which is
208 * overwritten by a successful blk_set_perm() call. Save it and
209 * restore it below.
210 */
211 saved_shared_perm = blk->shared_perm;
212
213 blk_set_perm(blk, blk->perm, BLK_PERM_ALL, &local_err);
214 if (local_err) {
215 error_propagate(errp, local_err);
216 blk->disable_perm = true;
217 return;
218 }
219 blk->shared_perm = saved_shared_perm;
220
221 if (runstate_check(RUN_STATE_INMIGRATE)) {
222 /* Activation can happen when migration process is still active, for
223 * example when nbd_server_add is called during non-shared storage
224 * migration. Defer the shared_perm update to migration completion. */
225 if (!blk->vmsh) {
226 blk->vmsh = qemu_add_vm_change_state_handler(blk_vm_state_changed,
227 blk);
228 }
229 return;
230 }
231
232 blk_set_perm(blk, blk->perm, blk->shared_perm, &local_err);
233 if (local_err) {
234 error_propagate(errp, local_err);
235 blk->disable_perm = true;
236 return;
237 }
238 }
239
240 void blk_set_force_allow_inactivate(BlockBackend *blk)
241 {
242 GLOBAL_STATE_CODE();
243 blk->force_allow_inactivate = true;
244 }
245
246 static bool blk_can_inactivate(BlockBackend *blk)
247 {
248 /* If it is a guest device, inactivate is ok. */
249 if (blk->dev || blk_name(blk)[0]) {
250 return true;
251 }
252
253 /* Inactivating means no more writes to the image can be done,
254 * even if those writes would be changes invisible to the
255 * guest. For block job BBs that satisfy this, we can just allow
256 * it. This is the case for mirror job source, which is required
257 * by libvirt non-shared block migration. */
258 if (!(blk->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED))) {
259 return true;
260 }
261
262 return blk->force_allow_inactivate;
263 }
264
265 static int blk_root_inactivate(BdrvChild *child)
266 {
267 BlockBackend *blk = child->opaque;
268
269 if (blk->disable_perm) {
270 return 0;
271 }
272
273 if (!blk_can_inactivate(blk)) {
274 return -EPERM;
275 }
276
277 blk->disable_perm = true;
278 if (blk->root) {
279 bdrv_child_try_set_perm(blk->root, 0, BLK_PERM_ALL, &error_abort);
280 }
281
282 return 0;
283 }
284
285 static void blk_root_attach(BdrvChild *child)
286 {
287 BlockBackend *blk = child->opaque;
288 BlockBackendAioNotifier *notifier;
289
290 trace_blk_root_attach(child, blk, child->bs);
291
292 QLIST_FOREACH(notifier, &blk->aio_notifiers, list) {
293 bdrv_add_aio_context_notifier(child->bs,
294 notifier->attached_aio_context,
295 notifier->detach_aio_context,
296 notifier->opaque);
297 }
298 }
299
300 static void blk_root_detach(BdrvChild *child)
301 {
302 BlockBackend *blk = child->opaque;
303 BlockBackendAioNotifier *notifier;
304
305 trace_blk_root_detach(child, blk, child->bs);
306
307 QLIST_FOREACH(notifier, &blk->aio_notifiers, list) {
308 bdrv_remove_aio_context_notifier(child->bs,
309 notifier->attached_aio_context,
310 notifier->detach_aio_context,
311 notifier->opaque);
312 }
313 }
314
315 static AioContext *blk_root_get_parent_aio_context(BdrvChild *c)
316 {
317 BlockBackend *blk = c->opaque;
318
319 return blk_get_aio_context(blk);
320 }
321
322 static const BdrvChildClass child_root = {
323 .inherit_options = blk_root_inherit_options,
324
325 .change_media = blk_root_change_media,
326 .resize = blk_root_resize,
327 .get_name = blk_root_get_name,
328 .get_parent_desc = blk_root_get_parent_desc,
329
330 .drained_begin = blk_root_drained_begin,
331 .drained_poll = blk_root_drained_poll,
332 .drained_end = blk_root_drained_end,
333
334 .activate = blk_root_activate,
335 .inactivate = blk_root_inactivate,
336
337 .attach = blk_root_attach,
338 .detach = blk_root_detach,
339
340 .can_set_aio_ctx = blk_root_can_set_aio_ctx,
341 .set_aio_ctx = blk_root_set_aio_ctx,
342 .change_aio_ctx = blk_root_change_aio_ctx,
343
344 .get_parent_aio_context = blk_root_get_parent_aio_context,
345 };
346
347 /*
348 * Create a new BlockBackend with a reference count of one.
349 *
350 * @perm is a bitmasks of BLK_PERM_* constants which describes the permissions
351 * to request for a block driver node that is attached to this BlockBackend.
352 * @shared_perm is a bitmask which describes which permissions may be granted
353 * to other users of the attached node.
354 * Both sets of permissions can be changed later using blk_set_perm().
355 *
356 * Return the new BlockBackend on success, null on failure.
357 */
358 BlockBackend *blk_new(AioContext *ctx, uint64_t perm, uint64_t shared_perm)
359 {
360 BlockBackend *blk;
361
362 GLOBAL_STATE_CODE();
363
364 blk = g_new0(BlockBackend, 1);
365 blk->refcnt = 1;
366 blk->ctx = ctx;
367 blk->perm = perm;
368 blk->shared_perm = shared_perm;
369 blk_set_enable_write_cache(blk, true);
370
371 blk->on_read_error = BLOCKDEV_ON_ERROR_REPORT;
372 blk->on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
373
374 block_acct_init(&blk->stats);
375
376 qemu_co_queue_init(&blk->queued_requests);
377 notifier_list_init(&blk->remove_bs_notifiers);
378 notifier_list_init(&blk->insert_bs_notifiers);
379 QLIST_INIT(&blk->aio_notifiers);
380
381 QTAILQ_INSERT_TAIL(&block_backends, blk, link);
382 return blk;
383 }
384
385 /*
386 * Create a new BlockBackend connected to an existing BlockDriverState.
387 *
388 * @perm is a bitmasks of BLK_PERM_* constants which describes the
389 * permissions to request for @bs that is attached to this
390 * BlockBackend. @shared_perm is a bitmask which describes which
391 * permissions may be granted to other users of the attached node.
392 * Both sets of permissions can be changed later using blk_set_perm().
393 *
394 * Return the new BlockBackend on success, null on failure.
395 */
396 BlockBackend *blk_new_with_bs(BlockDriverState *bs, uint64_t perm,
397 uint64_t shared_perm, Error **errp)
398 {
399 BlockBackend *blk = blk_new(bdrv_get_aio_context(bs), perm, shared_perm);
400
401 GLOBAL_STATE_CODE();
402
403 if (blk_insert_bs(blk, bs, errp) < 0) {
404 blk_unref(blk);
405 return NULL;
406 }
407 return blk;
408 }
409
410 /*
411 * Creates a new BlockBackend, opens a new BlockDriverState, and connects both.
412 * The new BlockBackend is in the main AioContext.
413 *
414 * Just as with bdrv_open(), after having called this function the reference to
415 * @options belongs to the block layer (even on failure).
416 *
417 * TODO: Remove @filename and @flags; it should be possible to specify a whole
418 * BDS tree just by specifying the @options QDict (or @reference,
419 * alternatively). At the time of adding this function, this is not possible,
420 * though, so callers of this function have to be able to specify @filename and
421 * @flags.
422 */
423 BlockBackend *blk_new_open(const char *filename, const char *reference,
424 QDict *options, int flags, Error **errp)
425 {
426 BlockBackend *blk;
427 BlockDriverState *bs;
428 uint64_t perm = 0;
429 uint64_t shared = BLK_PERM_ALL;
430
431 GLOBAL_STATE_CODE();
432
433 /*
434 * blk_new_open() is mainly used in .bdrv_create implementations and the
435 * tools where sharing isn't a major concern because the BDS stays private
436 * and the file is generally not supposed to be used by a second process,
437 * so we just request permission according to the flags.
438 *
439 * The exceptions are xen_disk and blockdev_init(); in these cases, the
440 * caller of blk_new_open() doesn't make use of the permissions, but they
441 * shouldn't hurt either. We can still share everything here because the
442 * guest devices will add their own blockers if they can't share.
443 */
444 if ((flags & BDRV_O_NO_IO) == 0) {
445 perm |= BLK_PERM_CONSISTENT_READ;
446 if (flags & BDRV_O_RDWR) {
447 perm |= BLK_PERM_WRITE;
448 }
449 }
450 if (flags & BDRV_O_RESIZE) {
451 perm |= BLK_PERM_RESIZE;
452 }
453 if (flags & BDRV_O_NO_SHARE) {
454 shared = BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
455 }
456
457 blk = blk_new(qemu_get_aio_context(), perm, shared);
458 bs = bdrv_open(filename, reference, options, flags, errp);
459 if (!bs) {
460 blk_unref(blk);
461 return NULL;
462 }
463
464 blk->root = bdrv_root_attach_child(bs, "root", &child_root,
465 BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY,
466 perm, shared, blk, errp);
467 if (!blk->root) {
468 blk_unref(blk);
469 return NULL;
470 }
471
472 return blk;
473 }
474
475 static void blk_delete(BlockBackend *blk)
476 {
477 assert(!blk->refcnt);
478 assert(!blk->name);
479 assert(!blk->dev);
480 if (blk->public.throttle_group_member.throttle_state) {
481 blk_io_limits_disable(blk);
482 }
483 if (blk->root) {
484 blk_remove_bs(blk);
485 }
486 if (blk->vmsh) {
487 qemu_del_vm_change_state_handler(blk->vmsh);
488 blk->vmsh = NULL;
489 }
490 assert(QLIST_EMPTY(&blk->remove_bs_notifiers.notifiers));
491 assert(QLIST_EMPTY(&blk->insert_bs_notifiers.notifiers));
492 assert(QLIST_EMPTY(&blk->aio_notifiers));
493 QTAILQ_REMOVE(&block_backends, blk, link);
494 drive_info_del(blk->legacy_dinfo);
495 block_acct_cleanup(&blk->stats);
496 g_free(blk);
497 }
498
499 static void drive_info_del(DriveInfo *dinfo)
500 {
501 if (!dinfo) {
502 return;
503 }
504 qemu_opts_del(dinfo->opts);
505 g_free(dinfo);
506 }
507
508 int blk_get_refcnt(BlockBackend *blk)
509 {
510 GLOBAL_STATE_CODE();
511 return blk ? blk->refcnt : 0;
512 }
513
514 /*
515 * Increment @blk's reference count.
516 * @blk must not be null.
517 */
518 void blk_ref(BlockBackend *blk)
519 {
520 assert(blk->refcnt > 0);
521 GLOBAL_STATE_CODE();
522 blk->refcnt++;
523 }
524
525 /*
526 * Decrement @blk's reference count.
527 * If this drops it to zero, destroy @blk.
528 * For convenience, do nothing if @blk is null.
529 */
530 void blk_unref(BlockBackend *blk)
531 {
532 GLOBAL_STATE_CODE();
533 if (blk) {
534 assert(blk->refcnt > 0);
535 if (blk->refcnt > 1) {
536 blk->refcnt--;
537 } else {
538 blk_drain(blk);
539 /* blk_drain() cannot resurrect blk, nobody held a reference */
540 assert(blk->refcnt == 1);
541 blk->refcnt = 0;
542 blk_delete(blk);
543 }
544 }
545 }
546
547 /*
548 * Behaves similarly to blk_next() but iterates over all BlockBackends, even the
549 * ones which are hidden (i.e. are not referenced by the monitor).
550 */
551 BlockBackend *blk_all_next(BlockBackend *blk)
552 {
553 GLOBAL_STATE_CODE();
554 return blk ? QTAILQ_NEXT(blk, link)
555 : QTAILQ_FIRST(&block_backends);
556 }
557
558 void blk_remove_all_bs(void)
559 {
560 BlockBackend *blk = NULL;
561
562 GLOBAL_STATE_CODE();
563
564 while ((blk = blk_all_next(blk)) != NULL) {
565 AioContext *ctx = blk_get_aio_context(blk);
566
567 aio_context_acquire(ctx);
568 if (blk->root) {
569 blk_remove_bs(blk);
570 }
571 aio_context_release(ctx);
572 }
573 }
574
575 /*
576 * Return the monitor-owned BlockBackend after @blk.
577 * If @blk is null, return the first one.
578 * Else, return @blk's next sibling, which may be null.
579 *
580 * To iterate over all BlockBackends, do
581 * for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
582 * ...
583 * }
584 */
585 BlockBackend *blk_next(BlockBackend *blk)
586 {
587 GLOBAL_STATE_CODE();
588 return blk ? QTAILQ_NEXT(blk, monitor_link)
589 : QTAILQ_FIRST(&monitor_block_backends);
590 }
591
592 /* Iterates over all top-level BlockDriverStates, i.e. BDSs that are owned by
593 * the monitor or attached to a BlockBackend */
594 BlockDriverState *bdrv_next(BdrvNextIterator *it)
595 {
596 BlockDriverState *bs, *old_bs;
597
598 /* Must be called from the main loop */
599 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
600
601 /* First, return all root nodes of BlockBackends. In order to avoid
602 * returning a BDS twice when multiple BBs refer to it, we only return it
603 * if the BB is the first one in the parent list of the BDS. */
604 if (it->phase == BDRV_NEXT_BACKEND_ROOTS) {
605 BlockBackend *old_blk = it->blk;
606
607 old_bs = old_blk ? blk_bs(old_blk) : NULL;
608
609 do {
610 it->blk = blk_all_next(it->blk);
611 bs = it->blk ? blk_bs(it->blk) : NULL;
612 } while (it->blk && (bs == NULL || bdrv_first_blk(bs) != it->blk));
613
614 if (it->blk) {
615 blk_ref(it->blk);
616 }
617 blk_unref(old_blk);
618
619 if (bs) {
620 bdrv_ref(bs);
621 bdrv_unref(old_bs);
622 return bs;
623 }
624 it->phase = BDRV_NEXT_MONITOR_OWNED;
625 } else {
626 old_bs = it->bs;
627 }
628
629 /* Then return the monitor-owned BDSes without a BB attached. Ignore all
630 * BDSes that are attached to a BlockBackend here; they have been handled
631 * by the above block already */
632 do {
633 it->bs = bdrv_next_monitor_owned(it->bs);
634 bs = it->bs;
635 } while (bs && bdrv_has_blk(bs));
636
637 if (bs) {
638 bdrv_ref(bs);
639 }
640 bdrv_unref(old_bs);
641
642 return bs;
643 }
644
645 static void bdrv_next_reset(BdrvNextIterator *it)
646 {
647 *it = (BdrvNextIterator) {
648 .phase = BDRV_NEXT_BACKEND_ROOTS,
649 };
650 }
651
652 BlockDriverState *bdrv_first(BdrvNextIterator *it)
653 {
654 GLOBAL_STATE_CODE();
655 bdrv_next_reset(it);
656 return bdrv_next(it);
657 }
658
659 /* Must be called when aborting a bdrv_next() iteration before
660 * bdrv_next() returns NULL */
661 void bdrv_next_cleanup(BdrvNextIterator *it)
662 {
663 /* Must be called from the main loop */
664 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
665
666 if (it->phase == BDRV_NEXT_BACKEND_ROOTS) {
667 if (it->blk) {
668 bdrv_unref(blk_bs(it->blk));
669 blk_unref(it->blk);
670 }
671 } else {
672 bdrv_unref(it->bs);
673 }
674
675 bdrv_next_reset(it);
676 }
677
678 /*
679 * Add a BlockBackend into the list of backends referenced by the monitor, with
680 * the given @name acting as the handle for the monitor.
681 * Strictly for use by blockdev.c.
682 *
683 * @name must not be null or empty.
684 *
685 * Returns true on success and false on failure. In the latter case, an Error
686 * object is returned through @errp.
687 */
688 bool monitor_add_blk(BlockBackend *blk, const char *name, Error **errp)
689 {
690 assert(!blk->name);
691 assert(name && name[0]);
692 GLOBAL_STATE_CODE();
693
694 if (!id_wellformed(name)) {
695 error_setg(errp, "Invalid device name");
696 return false;
697 }
698 if (blk_by_name(name)) {
699 error_setg(errp, "Device with id '%s' already exists", name);
700 return false;
701 }
702 if (bdrv_find_node(name)) {
703 error_setg(errp,
704 "Device name '%s' conflicts with an existing node name",
705 name);
706 return false;
707 }
708
709 blk->name = g_strdup(name);
710 QTAILQ_INSERT_TAIL(&monitor_block_backends, blk, monitor_link);
711 return true;
712 }
713
714 /*
715 * Remove a BlockBackend from the list of backends referenced by the monitor.
716 * Strictly for use by blockdev.c.
717 */
718 void monitor_remove_blk(BlockBackend *blk)
719 {
720 GLOBAL_STATE_CODE();
721
722 if (!blk->name) {
723 return;
724 }
725
726 QTAILQ_REMOVE(&monitor_block_backends, blk, monitor_link);
727 g_free(blk->name);
728 blk->name = NULL;
729 }
730
731 /*
732 * Return @blk's name, a non-null string.
733 * Returns an empty string iff @blk is not referenced by the monitor.
734 */
735 const char *blk_name(const BlockBackend *blk)
736 {
737 IO_CODE();
738 return blk->name ?: "";
739 }
740
741 /*
742 * Return the BlockBackend with name @name if it exists, else null.
743 * @name must not be null.
744 */
745 BlockBackend *blk_by_name(const char *name)
746 {
747 BlockBackend *blk = NULL;
748
749 GLOBAL_STATE_CODE();
750 assert(name);
751 while ((blk = blk_next(blk)) != NULL) {
752 if (!strcmp(name, blk->name)) {
753 return blk;
754 }
755 }
756 return NULL;
757 }
758
759 /*
760 * Return the BlockDriverState attached to @blk if any, else null.
761 */
762 BlockDriverState *blk_bs(BlockBackend *blk)
763 {
764 IO_CODE();
765 return blk->root ? blk->root->bs : NULL;
766 }
767
768 static BlockBackend *bdrv_first_blk(BlockDriverState *bs)
769 {
770 BdrvChild *child;
771
772 GLOBAL_STATE_CODE();
773
774 QLIST_FOREACH(child, &bs->parents, next_parent) {
775 if (child->klass == &child_root) {
776 return child->opaque;
777 }
778 }
779
780 return NULL;
781 }
782
783 /*
784 * Returns true if @bs has an associated BlockBackend.
785 */
786 bool bdrv_has_blk(BlockDriverState *bs)
787 {
788 GLOBAL_STATE_CODE();
789 return bdrv_first_blk(bs) != NULL;
790 }
791
792 /*
793 * Returns true if @bs has only BlockBackends as parents.
794 */
795 bool bdrv_is_root_node(BlockDriverState *bs)
796 {
797 BdrvChild *c;
798
799 GLOBAL_STATE_CODE();
800 QLIST_FOREACH(c, &bs->parents, next_parent) {
801 if (c->klass != &child_root) {
802 return false;
803 }
804 }
805
806 return true;
807 }
808
809 /*
810 * Return @blk's DriveInfo if any, else null.
811 */
812 DriveInfo *blk_legacy_dinfo(BlockBackend *blk)
813 {
814 GLOBAL_STATE_CODE();
815 return blk->legacy_dinfo;
816 }
817
818 /*
819 * Set @blk's DriveInfo to @dinfo, and return it.
820 * @blk must not have a DriveInfo set already.
821 * No other BlockBackend may have the same DriveInfo set.
822 */
823 DriveInfo *blk_set_legacy_dinfo(BlockBackend *blk, DriveInfo *dinfo)
824 {
825 assert(!blk->legacy_dinfo);
826 GLOBAL_STATE_CODE();
827 return blk->legacy_dinfo = dinfo;
828 }
829
830 /*
831 * Return the BlockBackend with DriveInfo @dinfo.
832 * It must exist.
833 */
834 BlockBackend *blk_by_legacy_dinfo(DriveInfo *dinfo)
835 {
836 BlockBackend *blk = NULL;
837 GLOBAL_STATE_CODE();
838
839 while ((blk = blk_next(blk)) != NULL) {
840 if (blk->legacy_dinfo == dinfo) {
841 return blk;
842 }
843 }
844 abort();
845 }
846
847 /*
848 * Returns a pointer to the publicly accessible fields of @blk.
849 */
850 BlockBackendPublic *blk_get_public(BlockBackend *blk)
851 {
852 GLOBAL_STATE_CODE();
853 return &blk->public;
854 }
855
856 /*
857 * Returns a BlockBackend given the associated @public fields.
858 */
859 BlockBackend *blk_by_public(BlockBackendPublic *public)
860 {
861 GLOBAL_STATE_CODE();
862 return container_of(public, BlockBackend, public);
863 }
864
865 /*
866 * Disassociates the currently associated BlockDriverState from @blk.
867 */
868 void blk_remove_bs(BlockBackend *blk)
869 {
870 ThrottleGroupMember *tgm = &blk->public.throttle_group_member;
871 BdrvChild *root;
872
873 GLOBAL_STATE_CODE();
874
875 notifier_list_notify(&blk->remove_bs_notifiers, blk);
876 if (tgm->throttle_state) {
877 BlockDriverState *bs = blk_bs(blk);
878
879 /*
880 * Take a ref in case blk_bs() changes across bdrv_drained_begin(), for
881 * example, if a temporary filter node is removed by a blockjob.
882 */
883 bdrv_ref(bs);
884 bdrv_drained_begin(bs);
885 throttle_group_detach_aio_context(tgm);
886 throttle_group_attach_aio_context(tgm, qemu_get_aio_context());
887 bdrv_drained_end(bs);
888 bdrv_unref(bs);
889 }
890
891 blk_update_root_state(blk);
892
893 /* bdrv_root_unref_child() will cause blk->root to become stale and may
894 * switch to a completion coroutine later on. Let's drain all I/O here
895 * to avoid that and a potential QEMU crash.
896 */
897 blk_drain(blk);
898 root = blk->root;
899 blk->root = NULL;
900 bdrv_root_unref_child(root);
901 }
902
903 /*
904 * Associates a new BlockDriverState with @blk.
905 */
906 int blk_insert_bs(BlockBackend *blk, BlockDriverState *bs, Error **errp)
907 {
908 ThrottleGroupMember *tgm = &blk->public.throttle_group_member;
909 GLOBAL_STATE_CODE();
910 bdrv_ref(bs);
911 blk->root = bdrv_root_attach_child(bs, "root", &child_root,
912 BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY,
913 blk->perm, blk->shared_perm,
914 blk, errp);
915 if (blk->root == NULL) {
916 return -EPERM;
917 }
918
919 notifier_list_notify(&blk->insert_bs_notifiers, blk);
920 if (tgm->throttle_state) {
921 throttle_group_detach_aio_context(tgm);
922 throttle_group_attach_aio_context(tgm, bdrv_get_aio_context(bs));
923 }
924
925 return 0;
926 }
927
928 /*
929 * Change BlockDriverState associated with @blk.
930 */
931 int blk_replace_bs(BlockBackend *blk, BlockDriverState *new_bs, Error **errp)
932 {
933 GLOBAL_STATE_CODE();
934 return bdrv_replace_child_bs(blk->root, new_bs, errp);
935 }
936
937 /*
938 * Sets the permission bitmasks that the user of the BlockBackend needs.
939 */
940 int blk_set_perm(BlockBackend *blk, uint64_t perm, uint64_t shared_perm,
941 Error **errp)
942 {
943 int ret;
944 GLOBAL_STATE_CODE();
945
946 if (blk->root && !blk->disable_perm) {
947 ret = bdrv_child_try_set_perm(blk->root, perm, shared_perm, errp);
948 if (ret < 0) {
949 return ret;
950 }
951 }
952
953 blk->perm = perm;
954 blk->shared_perm = shared_perm;
955
956 return 0;
957 }
958
959 void blk_get_perm(BlockBackend *blk, uint64_t *perm, uint64_t *shared_perm)
960 {
961 GLOBAL_STATE_CODE();
962 *perm = blk->perm;
963 *shared_perm = blk->shared_perm;
964 }
965
966 /*
967 * Attach device model @dev to @blk.
968 * Return 0 on success, -EBUSY when a device model is attached already.
969 */
970 int blk_attach_dev(BlockBackend *blk, DeviceState *dev)
971 {
972 GLOBAL_STATE_CODE();
973 if (blk->dev) {
974 return -EBUSY;
975 }
976
977 /* While migration is still incoming, we don't need to apply the
978 * permissions of guest device BlockBackends. We might still have a block
979 * job or NBD server writing to the image for storage migration. */
980 if (runstate_check(RUN_STATE_INMIGRATE)) {
981 blk->disable_perm = true;
982 }
983
984 blk_ref(blk);
985 blk->dev = dev;
986 blk_iostatus_reset(blk);
987
988 return 0;
989 }
990
991 /*
992 * Detach device model @dev from @blk.
993 * @dev must be currently attached to @blk.
994 */
995 void blk_detach_dev(BlockBackend *blk, DeviceState *dev)
996 {
997 assert(blk->dev == dev);
998 GLOBAL_STATE_CODE();
999 blk->dev = NULL;
1000 blk->dev_ops = NULL;
1001 blk->dev_opaque = NULL;
1002 blk_set_perm(blk, 0, BLK_PERM_ALL, &error_abort);
1003 blk_unref(blk);
1004 }
1005
1006 /*
1007 * Return the device model attached to @blk if any, else null.
1008 */
1009 DeviceState *blk_get_attached_dev(BlockBackend *blk)
1010 {
1011 GLOBAL_STATE_CODE();
1012 return blk->dev;
1013 }
1014
1015 /* Return the qdev ID, or if no ID is assigned the QOM path, of the block
1016 * device attached to the BlockBackend. */
1017 char *blk_get_attached_dev_id(BlockBackend *blk)
1018 {
1019 DeviceState *dev = blk->dev;
1020 IO_CODE();
1021
1022 if (!dev) {
1023 return g_strdup("");
1024 } else if (dev->id) {
1025 return g_strdup(dev->id);
1026 }
1027
1028 return object_get_canonical_path(OBJECT(dev)) ?: g_strdup("");
1029 }
1030
1031 /*
1032 * Return the BlockBackend which has the device model @dev attached if it
1033 * exists, else null.
1034 *
1035 * @dev must not be null.
1036 */
1037 BlockBackend *blk_by_dev(void *dev)
1038 {
1039 BlockBackend *blk = NULL;
1040
1041 GLOBAL_STATE_CODE();
1042
1043 assert(dev != NULL);
1044 while ((blk = blk_all_next(blk)) != NULL) {
1045 if (blk->dev == dev) {
1046 return blk;
1047 }
1048 }
1049 return NULL;
1050 }
1051
1052 /*
1053 * Set @blk's device model callbacks to @ops.
1054 * @opaque is the opaque argument to pass to the callbacks.
1055 * This is for use by device models.
1056 */
1057 void blk_set_dev_ops(BlockBackend *blk, const BlockDevOps *ops,
1058 void *opaque)
1059 {
1060 GLOBAL_STATE_CODE();
1061 blk->dev_ops = ops;
1062 blk->dev_opaque = opaque;
1063
1064 /* Are we currently quiesced? Should we enforce this right now? */
1065 if (blk->quiesce_counter && ops && ops->drained_begin) {
1066 ops->drained_begin(opaque);
1067 }
1068 }
1069
1070 /*
1071 * Notify @blk's attached device model of media change.
1072 *
1073 * If @load is true, notify of media load. This action can fail, meaning that
1074 * the medium cannot be loaded. @errp is set then.
1075 *
1076 * If @load is false, notify of media eject. This can never fail.
1077 *
1078 * Also send DEVICE_TRAY_MOVED events as appropriate.
1079 */
1080 void blk_dev_change_media_cb(BlockBackend *blk, bool load, Error **errp)
1081 {
1082 GLOBAL_STATE_CODE();
1083 if (blk->dev_ops && blk->dev_ops->change_media_cb) {
1084 bool tray_was_open, tray_is_open;
1085 Error *local_err = NULL;
1086
1087 tray_was_open = blk_dev_is_tray_open(blk);
1088 blk->dev_ops->change_media_cb(blk->dev_opaque, load, &local_err);
1089 if (local_err) {
1090 assert(load == true);
1091 error_propagate(errp, local_err);
1092 return;
1093 }
1094 tray_is_open = blk_dev_is_tray_open(blk);
1095
1096 if (tray_was_open != tray_is_open) {
1097 char *id = blk_get_attached_dev_id(blk);
1098 qapi_event_send_device_tray_moved(blk_name(blk), id, tray_is_open);
1099 g_free(id);
1100 }
1101 }
1102 }
1103
1104 static void blk_root_change_media(BdrvChild *child, bool load)
1105 {
1106 blk_dev_change_media_cb(child->opaque, load, NULL);
1107 }
1108
1109 /*
1110 * Does @blk's attached device model have removable media?
1111 * %true if no device model is attached.
1112 */
1113 bool blk_dev_has_removable_media(BlockBackend *blk)
1114 {
1115 GLOBAL_STATE_CODE();
1116 return !blk->dev || (blk->dev_ops && blk->dev_ops->change_media_cb);
1117 }
1118
1119 /*
1120 * Does @blk's attached device model have a tray?
1121 */
1122 bool blk_dev_has_tray(BlockBackend *blk)
1123 {
1124 IO_CODE();
1125 return blk->dev_ops && blk->dev_ops->is_tray_open;
1126 }
1127
1128 /*
1129 * Notify @blk's attached device model of a media eject request.
1130 * If @force is true, the medium is about to be yanked out forcefully.
1131 */
1132 void blk_dev_eject_request(BlockBackend *blk, bool force)
1133 {
1134 GLOBAL_STATE_CODE();
1135 if (blk->dev_ops && blk->dev_ops->eject_request_cb) {
1136 blk->dev_ops->eject_request_cb(blk->dev_opaque, force);
1137 }
1138 }
1139
1140 /*
1141 * Does @blk's attached device model have a tray, and is it open?
1142 */
1143 bool blk_dev_is_tray_open(BlockBackend *blk)
1144 {
1145 IO_CODE();
1146 if (blk_dev_has_tray(blk)) {
1147 return blk->dev_ops->is_tray_open(blk->dev_opaque);
1148 }
1149 return false;
1150 }
1151
1152 /*
1153 * Does @blk's attached device model have the medium locked?
1154 * %false if the device model has no such lock.
1155 */
1156 bool blk_dev_is_medium_locked(BlockBackend *blk)
1157 {
1158 GLOBAL_STATE_CODE();
1159 if (blk->dev_ops && blk->dev_ops->is_medium_locked) {
1160 return blk->dev_ops->is_medium_locked(blk->dev_opaque);
1161 }
1162 return false;
1163 }
1164
1165 /*
1166 * Notify @blk's attached device model of a backend size change.
1167 */
1168 static void blk_root_resize(BdrvChild *child)
1169 {
1170 BlockBackend *blk = child->opaque;
1171
1172 if (blk->dev_ops && blk->dev_ops->resize_cb) {
1173 blk->dev_ops->resize_cb(blk->dev_opaque);
1174 }
1175 }
1176
1177 void blk_iostatus_enable(BlockBackend *blk)
1178 {
1179 GLOBAL_STATE_CODE();
1180 blk->iostatus_enabled = true;
1181 blk->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
1182 }
1183
1184 /* The I/O status is only enabled if the drive explicitly
1185 * enables it _and_ the VM is configured to stop on errors */
1186 bool blk_iostatus_is_enabled(const BlockBackend *blk)
1187 {
1188 IO_CODE();
1189 return (blk->iostatus_enabled &&
1190 (blk->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
1191 blk->on_write_error == BLOCKDEV_ON_ERROR_STOP ||
1192 blk->on_read_error == BLOCKDEV_ON_ERROR_STOP));
1193 }
1194
1195 BlockDeviceIoStatus blk_iostatus(const BlockBackend *blk)
1196 {
1197 GLOBAL_STATE_CODE();
1198 return blk->iostatus;
1199 }
1200
1201 void blk_iostatus_disable(BlockBackend *blk)
1202 {
1203 GLOBAL_STATE_CODE();
1204 blk->iostatus_enabled = false;
1205 }
1206
1207 void blk_iostatus_reset(BlockBackend *blk)
1208 {
1209 GLOBAL_STATE_CODE();
1210 if (blk_iostatus_is_enabled(blk)) {
1211 blk->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
1212 }
1213 }
1214
1215 void blk_iostatus_set_err(BlockBackend *blk, int error)
1216 {
1217 IO_CODE();
1218 assert(blk_iostatus_is_enabled(blk));
1219 if (blk->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
1220 blk->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
1221 BLOCK_DEVICE_IO_STATUS_FAILED;
1222 }
1223 }
1224
1225 void blk_set_allow_write_beyond_eof(BlockBackend *blk, bool allow)
1226 {
1227 IO_CODE();
1228 blk->allow_write_beyond_eof = allow;
1229 }
1230
1231 void blk_set_allow_aio_context_change(BlockBackend *blk, bool allow)
1232 {
1233 IO_CODE();
1234 blk->allow_aio_context_change = allow;
1235 }
1236
1237 void blk_set_disable_request_queuing(BlockBackend *blk, bool disable)
1238 {
1239 IO_CODE();
1240 blk->disable_request_queuing = disable;
1241 }
1242
1243 static int blk_check_byte_request(BlockBackend *blk, int64_t offset,
1244 int64_t bytes)
1245 {
1246 int64_t len;
1247
1248 if (bytes < 0) {
1249 return -EIO;
1250 }
1251
1252 if (!blk_is_available(blk)) {
1253 return -ENOMEDIUM;
1254 }
1255
1256 if (offset < 0) {
1257 return -EIO;
1258 }
1259
1260 if (!blk->allow_write_beyond_eof) {
1261 len = blk_getlength(blk);
1262 if (len < 0) {
1263 return len;
1264 }
1265
1266 if (offset > len || len - offset < bytes) {
1267 return -EIO;
1268 }
1269 }
1270
1271 return 0;
1272 }
1273
1274 /* To be called between exactly one pair of blk_inc/dec_in_flight() */
1275 static void coroutine_fn blk_wait_while_drained(BlockBackend *blk)
1276 {
1277 assert(blk->in_flight > 0);
1278
1279 if (blk->quiesce_counter && !blk->disable_request_queuing) {
1280 blk_dec_in_flight(blk);
1281 qemu_co_queue_wait(&blk->queued_requests, NULL);
1282 blk_inc_in_flight(blk);
1283 }
1284 }
1285
1286 /* To be called between exactly one pair of blk_inc/dec_in_flight() */
1287 static int coroutine_fn
1288 blk_co_do_preadv_part(BlockBackend *blk, int64_t offset, int64_t bytes,
1289 QEMUIOVector *qiov, size_t qiov_offset,
1290 BdrvRequestFlags flags)
1291 {
1292 int ret;
1293 BlockDriverState *bs;
1294 IO_CODE();
1295
1296 blk_wait_while_drained(blk);
1297
1298 /* Call blk_bs() only after waiting, the graph may have changed */
1299 bs = blk_bs(blk);
1300 trace_blk_co_preadv(blk, bs, offset, bytes, flags);
1301
1302 ret = blk_check_byte_request(blk, offset, bytes);
1303 if (ret < 0) {
1304 return ret;
1305 }
1306
1307 bdrv_inc_in_flight(bs);
1308
1309 /* throttling disk I/O */
1310 if (blk->public.throttle_group_member.throttle_state) {
1311 throttle_group_co_io_limits_intercept(&blk->public.throttle_group_member,
1312 bytes, false);
1313 }
1314
1315 ret = bdrv_co_preadv_part(blk->root, offset, bytes, qiov, qiov_offset,
1316 flags);
1317 bdrv_dec_in_flight(bs);
1318 return ret;
1319 }
1320
1321 int coroutine_fn blk_co_pread(BlockBackend *blk, int64_t offset, int64_t bytes,
1322 void *buf, BdrvRequestFlags flags)
1323 {
1324 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, bytes);
1325 IO_OR_GS_CODE();
1326
1327 assert(bytes <= SIZE_MAX);
1328
1329 return blk_co_preadv(blk, offset, bytes, &qiov, flags);
1330 }
1331
1332 int coroutine_fn blk_co_preadv(BlockBackend *blk, int64_t offset,
1333 int64_t bytes, QEMUIOVector *qiov,
1334 BdrvRequestFlags flags)
1335 {
1336 int ret;
1337 IO_OR_GS_CODE();
1338
1339 blk_inc_in_flight(blk);
1340 ret = blk_co_do_preadv_part(blk, offset, bytes, qiov, 0, flags);
1341 blk_dec_in_flight(blk);
1342
1343 return ret;
1344 }
1345
1346 int coroutine_fn blk_co_preadv_part(BlockBackend *blk, int64_t offset,
1347 int64_t bytes, QEMUIOVector *qiov,
1348 size_t qiov_offset, BdrvRequestFlags flags)
1349 {
1350 int ret;
1351 IO_OR_GS_CODE();
1352
1353 blk_inc_in_flight(blk);
1354 ret = blk_co_do_preadv_part(blk, offset, bytes, qiov, qiov_offset, flags);
1355 blk_dec_in_flight(blk);
1356
1357 return ret;
1358 }
1359
1360 /* To be called between exactly one pair of blk_inc/dec_in_flight() */
1361 static int coroutine_fn
1362 blk_co_do_pwritev_part(BlockBackend *blk, int64_t offset, int64_t bytes,
1363 QEMUIOVector *qiov, size_t qiov_offset,
1364 BdrvRequestFlags flags)
1365 {
1366 int ret;
1367 BlockDriverState *bs;
1368 IO_CODE();
1369
1370 blk_wait_while_drained(blk);
1371
1372 /* Call blk_bs() only after waiting, the graph may have changed */
1373 bs = blk_bs(blk);
1374 trace_blk_co_pwritev(blk, bs, offset, bytes, flags);
1375
1376 ret = blk_check_byte_request(blk, offset, bytes);
1377 if (ret < 0) {
1378 return ret;
1379 }
1380
1381 bdrv_inc_in_flight(bs);
1382 /* throttling disk I/O */
1383 if (blk->public.throttle_group_member.throttle_state) {
1384 throttle_group_co_io_limits_intercept(&blk->public.throttle_group_member,
1385 bytes, true);
1386 }
1387
1388 if (!blk->enable_write_cache) {
1389 flags |= BDRV_REQ_FUA;
1390 }
1391
1392 ret = bdrv_co_pwritev_part(blk->root, offset, bytes, qiov, qiov_offset,
1393 flags);
1394 bdrv_dec_in_flight(bs);
1395 return ret;
1396 }
1397
1398 int coroutine_fn blk_co_pwritev_part(BlockBackend *blk, int64_t offset,
1399 int64_t bytes,
1400 QEMUIOVector *qiov, size_t qiov_offset,
1401 BdrvRequestFlags flags)
1402 {
1403 int ret;
1404 IO_OR_GS_CODE();
1405
1406 blk_inc_in_flight(blk);
1407 ret = blk_co_do_pwritev_part(blk, offset, bytes, qiov, qiov_offset, flags);
1408 blk_dec_in_flight(blk);
1409
1410 return ret;
1411 }
1412
1413 int coroutine_fn blk_co_pwrite(BlockBackend *blk, int64_t offset, int64_t bytes,
1414 const void *buf, BdrvRequestFlags flags)
1415 {
1416 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, bytes);
1417 IO_OR_GS_CODE();
1418
1419 assert(bytes <= SIZE_MAX);
1420
1421 return blk_co_pwritev(blk, offset, bytes, &qiov, flags);
1422 }
1423
1424 int coroutine_fn blk_co_pwritev(BlockBackend *blk, int64_t offset,
1425 int64_t bytes, QEMUIOVector *qiov,
1426 BdrvRequestFlags flags)
1427 {
1428 IO_OR_GS_CODE();
1429 return blk_co_pwritev_part(blk, offset, bytes, qiov, 0, flags);
1430 }
1431
1432 typedef struct BlkRwCo {
1433 BlockBackend *blk;
1434 int64_t offset;
1435 void *iobuf;
1436 int ret;
1437 BdrvRequestFlags flags;
1438 } BlkRwCo;
1439
1440 int blk_make_zero(BlockBackend *blk, BdrvRequestFlags flags)
1441 {
1442 GLOBAL_STATE_CODE();
1443 return bdrv_make_zero(blk->root, flags);
1444 }
1445
1446 void blk_inc_in_flight(BlockBackend *blk)
1447 {
1448 IO_CODE();
1449 qatomic_inc(&blk->in_flight);
1450 }
1451
1452 void blk_dec_in_flight(BlockBackend *blk)
1453 {
1454 IO_CODE();
1455 qatomic_dec(&blk->in_flight);
1456 aio_wait_kick();
1457 }
1458
1459 static void error_callback_bh(void *opaque)
1460 {
1461 struct BlockBackendAIOCB *acb = opaque;
1462
1463 blk_dec_in_flight(acb->blk);
1464 acb->common.cb(acb->common.opaque, acb->ret);
1465 qemu_aio_unref(acb);
1466 }
1467
1468 BlockAIOCB *blk_abort_aio_request(BlockBackend *blk,
1469 BlockCompletionFunc *cb,
1470 void *opaque, int ret)
1471 {
1472 struct BlockBackendAIOCB *acb;
1473 IO_CODE();
1474
1475 blk_inc_in_flight(blk);
1476 acb = blk_aio_get(&block_backend_aiocb_info, blk, cb, opaque);
1477 acb->blk = blk;
1478 acb->ret = ret;
1479
1480 replay_bh_schedule_oneshot_event(blk_get_aio_context(blk),
1481 error_callback_bh, acb);
1482 return &acb->common;
1483 }
1484
1485 typedef struct BlkAioEmAIOCB {
1486 BlockAIOCB common;
1487 BlkRwCo rwco;
1488 int64_t bytes;
1489 bool has_returned;
1490 } BlkAioEmAIOCB;
1491
1492 static AioContext *blk_aio_em_aiocb_get_aio_context(BlockAIOCB *acb_)
1493 {
1494 BlkAioEmAIOCB *acb = container_of(acb_, BlkAioEmAIOCB, common);
1495
1496 return blk_get_aio_context(acb->rwco.blk);
1497 }
1498
1499 static const AIOCBInfo blk_aio_em_aiocb_info = {
1500 .aiocb_size = sizeof(BlkAioEmAIOCB),
1501 .get_aio_context = blk_aio_em_aiocb_get_aio_context,
1502 };
1503
1504 static void blk_aio_complete(BlkAioEmAIOCB *acb)
1505 {
1506 if (acb->has_returned) {
1507 acb->common.cb(acb->common.opaque, acb->rwco.ret);
1508 blk_dec_in_flight(acb->rwco.blk);
1509 qemu_aio_unref(acb);
1510 }
1511 }
1512
1513 static void blk_aio_complete_bh(void *opaque)
1514 {
1515 BlkAioEmAIOCB *acb = opaque;
1516 assert(acb->has_returned);
1517 blk_aio_complete(acb);
1518 }
1519
1520 static BlockAIOCB *blk_aio_prwv(BlockBackend *blk, int64_t offset,
1521 int64_t bytes,
1522 void *iobuf, CoroutineEntry co_entry,
1523 BdrvRequestFlags flags,
1524 BlockCompletionFunc *cb, void *opaque)
1525 {
1526 BlkAioEmAIOCB *acb;
1527 Coroutine *co;
1528
1529 blk_inc_in_flight(blk);
1530 acb = blk_aio_get(&blk_aio_em_aiocb_info, blk, cb, opaque);
1531 acb->rwco = (BlkRwCo) {
1532 .blk = blk,
1533 .offset = offset,
1534 .iobuf = iobuf,
1535 .flags = flags,
1536 .ret = NOT_DONE,
1537 };
1538 acb->bytes = bytes;
1539 acb->has_returned = false;
1540
1541 co = qemu_coroutine_create(co_entry, acb);
1542 bdrv_coroutine_enter(blk_bs(blk), co);
1543
1544 acb->has_returned = true;
1545 if (acb->rwco.ret != NOT_DONE) {
1546 replay_bh_schedule_oneshot_event(blk_get_aio_context(blk),
1547 blk_aio_complete_bh, acb);
1548 }
1549
1550 return &acb->common;
1551 }
1552
1553 static void coroutine_fn blk_aio_read_entry(void *opaque)
1554 {
1555 BlkAioEmAIOCB *acb = opaque;
1556 BlkRwCo *rwco = &acb->rwco;
1557 QEMUIOVector *qiov = rwco->iobuf;
1558
1559 assert(qiov->size == acb->bytes);
1560 rwco->ret = blk_co_do_preadv_part(rwco->blk, rwco->offset, acb->bytes, qiov,
1561 0, rwco->flags);
1562 blk_aio_complete(acb);
1563 }
1564
1565 static void coroutine_fn blk_aio_write_entry(void *opaque)
1566 {
1567 BlkAioEmAIOCB *acb = opaque;
1568 BlkRwCo *rwco = &acb->rwco;
1569 QEMUIOVector *qiov = rwco->iobuf;
1570
1571 assert(!qiov || qiov->size == acb->bytes);
1572 rwco->ret = blk_co_do_pwritev_part(rwco->blk, rwco->offset, acb->bytes,
1573 qiov, 0, rwco->flags);
1574 blk_aio_complete(acb);
1575 }
1576
1577 BlockAIOCB *blk_aio_pwrite_zeroes(BlockBackend *blk, int64_t offset,
1578 int64_t bytes, BdrvRequestFlags flags,
1579 BlockCompletionFunc *cb, void *opaque)
1580 {
1581 IO_CODE();
1582 return blk_aio_prwv(blk, offset, bytes, NULL, blk_aio_write_entry,
1583 flags | BDRV_REQ_ZERO_WRITE, cb, opaque);
1584 }
1585
1586 int64_t blk_getlength(BlockBackend *blk)
1587 {
1588 IO_CODE();
1589 if (!blk_is_available(blk)) {
1590 return -ENOMEDIUM;
1591 }
1592
1593 return bdrv_getlength(blk_bs(blk));
1594 }
1595
1596 void blk_get_geometry(BlockBackend *blk, uint64_t *nb_sectors_ptr)
1597 {
1598 IO_CODE();
1599 if (!blk_bs(blk)) {
1600 *nb_sectors_ptr = 0;
1601 } else {
1602 bdrv_get_geometry(blk_bs(blk), nb_sectors_ptr);
1603 }
1604 }
1605
1606 int64_t blk_nb_sectors(BlockBackend *blk)
1607 {
1608 IO_CODE();
1609 if (!blk_is_available(blk)) {
1610 return -ENOMEDIUM;
1611 }
1612
1613 return bdrv_nb_sectors(blk_bs(blk));
1614 }
1615
1616 BlockAIOCB *blk_aio_preadv(BlockBackend *blk, int64_t offset,
1617 QEMUIOVector *qiov, BdrvRequestFlags flags,
1618 BlockCompletionFunc *cb, void *opaque)
1619 {
1620 IO_CODE();
1621 assert((uint64_t)qiov->size <= INT64_MAX);
1622 return blk_aio_prwv(blk, offset, qiov->size, qiov,
1623 blk_aio_read_entry, flags, cb, opaque);
1624 }
1625
1626 BlockAIOCB *blk_aio_pwritev(BlockBackend *blk, int64_t offset,
1627 QEMUIOVector *qiov, BdrvRequestFlags flags,
1628 BlockCompletionFunc *cb, void *opaque)
1629 {
1630 IO_CODE();
1631 assert((uint64_t)qiov->size <= INT64_MAX);
1632 return blk_aio_prwv(blk, offset, qiov->size, qiov,
1633 blk_aio_write_entry, flags, cb, opaque);
1634 }
1635
1636 void blk_aio_cancel(BlockAIOCB *acb)
1637 {
1638 GLOBAL_STATE_CODE();
1639 bdrv_aio_cancel(acb);
1640 }
1641
1642 void blk_aio_cancel_async(BlockAIOCB *acb)
1643 {
1644 IO_CODE();
1645 bdrv_aio_cancel_async(acb);
1646 }
1647
1648 /* To be called between exactly one pair of blk_inc/dec_in_flight() */
1649 static int coroutine_fn
1650 blk_co_do_ioctl(BlockBackend *blk, unsigned long int req, void *buf)
1651 {
1652 IO_CODE();
1653
1654 blk_wait_while_drained(blk);
1655
1656 if (!blk_is_available(blk)) {
1657 return -ENOMEDIUM;
1658 }
1659
1660 return bdrv_co_ioctl(blk_bs(blk), req, buf);
1661 }
1662
1663 int coroutine_fn blk_co_ioctl(BlockBackend *blk, unsigned long int req,
1664 void *buf)
1665 {
1666 int ret;
1667 IO_OR_GS_CODE();
1668
1669 blk_inc_in_flight(blk);
1670 ret = blk_co_do_ioctl(blk, req, buf);
1671 blk_dec_in_flight(blk);
1672
1673 return ret;
1674 }
1675
1676 static void coroutine_fn blk_aio_ioctl_entry(void *opaque)
1677 {
1678 BlkAioEmAIOCB *acb = opaque;
1679 BlkRwCo *rwco = &acb->rwco;
1680
1681 rwco->ret = blk_co_do_ioctl(rwco->blk, rwco->offset, rwco->iobuf);
1682
1683 blk_aio_complete(acb);
1684 }
1685
1686 BlockAIOCB *blk_aio_ioctl(BlockBackend *blk, unsigned long int req, void *buf,
1687 BlockCompletionFunc *cb, void *opaque)
1688 {
1689 IO_CODE();
1690 return blk_aio_prwv(blk, req, 0, buf, blk_aio_ioctl_entry, 0, cb, opaque);
1691 }
1692
1693 /* To be called between exactly one pair of blk_inc/dec_in_flight() */
1694 static int coroutine_fn
1695 blk_co_do_pdiscard(BlockBackend *blk, int64_t offset, int64_t bytes)
1696 {
1697 int ret;
1698 IO_CODE();
1699
1700 blk_wait_while_drained(blk);
1701
1702 ret = blk_check_byte_request(blk, offset, bytes);
1703 if (ret < 0) {
1704 return ret;
1705 }
1706
1707 return bdrv_co_pdiscard(blk->root, offset, bytes);
1708 }
1709
1710 static void coroutine_fn blk_aio_pdiscard_entry(void *opaque)
1711 {
1712 BlkAioEmAIOCB *acb = opaque;
1713 BlkRwCo *rwco = &acb->rwco;
1714
1715 rwco->ret = blk_co_do_pdiscard(rwco->blk, rwco->offset, acb->bytes);
1716 blk_aio_complete(acb);
1717 }
1718
1719 BlockAIOCB *blk_aio_pdiscard(BlockBackend *blk,
1720 int64_t offset, int64_t bytes,
1721 BlockCompletionFunc *cb, void *opaque)
1722 {
1723 IO_CODE();
1724 return blk_aio_prwv(blk, offset, bytes, NULL, blk_aio_pdiscard_entry, 0,
1725 cb, opaque);
1726 }
1727
1728 int coroutine_fn blk_co_pdiscard(BlockBackend *blk, int64_t offset,
1729 int64_t bytes)
1730 {
1731 int ret;
1732 IO_OR_GS_CODE();
1733
1734 blk_inc_in_flight(blk);
1735 ret = blk_co_do_pdiscard(blk, offset, bytes);
1736 blk_dec_in_flight(blk);
1737
1738 return ret;
1739 }
1740
1741 /* To be called between exactly one pair of blk_inc/dec_in_flight() */
1742 static int coroutine_fn blk_co_do_flush(BlockBackend *blk)
1743 {
1744 blk_wait_while_drained(blk);
1745 IO_CODE();
1746
1747 if (!blk_is_available(blk)) {
1748 return -ENOMEDIUM;
1749 }
1750
1751 return bdrv_co_flush(blk_bs(blk));
1752 }
1753
1754 static void coroutine_fn blk_aio_flush_entry(void *opaque)
1755 {
1756 BlkAioEmAIOCB *acb = opaque;
1757 BlkRwCo *rwco = &acb->rwco;
1758
1759 rwco->ret = blk_co_do_flush(rwco->blk);
1760 blk_aio_complete(acb);
1761 }
1762
1763 BlockAIOCB *blk_aio_flush(BlockBackend *blk,
1764 BlockCompletionFunc *cb, void *opaque)
1765 {
1766 IO_CODE();
1767 return blk_aio_prwv(blk, 0, 0, NULL, blk_aio_flush_entry, 0, cb, opaque);
1768 }
1769
1770 int coroutine_fn blk_co_flush(BlockBackend *blk)
1771 {
1772 int ret;
1773 IO_OR_GS_CODE();
1774
1775 blk_inc_in_flight(blk);
1776 ret = blk_co_do_flush(blk);
1777 blk_dec_in_flight(blk);
1778
1779 return ret;
1780 }
1781
1782 void blk_drain(BlockBackend *blk)
1783 {
1784 BlockDriverState *bs = blk_bs(blk);
1785 GLOBAL_STATE_CODE();
1786
1787 if (bs) {
1788 bdrv_ref(bs);
1789 bdrv_drained_begin(bs);
1790 }
1791
1792 /* We may have -ENOMEDIUM completions in flight */
1793 AIO_WAIT_WHILE(blk_get_aio_context(blk),
1794 qatomic_mb_read(&blk->in_flight) > 0);
1795
1796 if (bs) {
1797 bdrv_drained_end(bs);
1798 bdrv_unref(bs);
1799 }
1800 }
1801
1802 void blk_drain_all(void)
1803 {
1804 BlockBackend *blk = NULL;
1805
1806 GLOBAL_STATE_CODE();
1807
1808 bdrv_drain_all_begin();
1809
1810 while ((blk = blk_all_next(blk)) != NULL) {
1811 AioContext *ctx = blk_get_aio_context(blk);
1812
1813 aio_context_acquire(ctx);
1814
1815 /* We may have -ENOMEDIUM completions in flight */
1816 AIO_WAIT_WHILE(ctx, qatomic_mb_read(&blk->in_flight) > 0);
1817
1818 aio_context_release(ctx);
1819 }
1820
1821 bdrv_drain_all_end();
1822 }
1823
1824 void blk_set_on_error(BlockBackend *blk, BlockdevOnError on_read_error,
1825 BlockdevOnError on_write_error)
1826 {
1827 GLOBAL_STATE_CODE();
1828 blk->on_read_error = on_read_error;
1829 blk->on_write_error = on_write_error;
1830 }
1831
1832 BlockdevOnError blk_get_on_error(BlockBackend *blk, bool is_read)
1833 {
1834 IO_CODE();
1835 return is_read ? blk->on_read_error : blk->on_write_error;
1836 }
1837
1838 BlockErrorAction blk_get_error_action(BlockBackend *blk, bool is_read,
1839 int error)
1840 {
1841 BlockdevOnError on_err = blk_get_on_error(blk, is_read);
1842 IO_CODE();
1843
1844 switch (on_err) {
1845 case BLOCKDEV_ON_ERROR_ENOSPC:
1846 return (error == ENOSPC) ?
1847 BLOCK_ERROR_ACTION_STOP : BLOCK_ERROR_ACTION_REPORT;
1848 case BLOCKDEV_ON_ERROR_STOP:
1849 return BLOCK_ERROR_ACTION_STOP;
1850 case BLOCKDEV_ON_ERROR_REPORT:
1851 return BLOCK_ERROR_ACTION_REPORT;
1852 case BLOCKDEV_ON_ERROR_IGNORE:
1853 return BLOCK_ERROR_ACTION_IGNORE;
1854 case BLOCKDEV_ON_ERROR_AUTO:
1855 default:
1856 abort();
1857 }
1858 }
1859
1860 static void send_qmp_error_event(BlockBackend *blk,
1861 BlockErrorAction action,
1862 bool is_read, int error)
1863 {
1864 IoOperationType optype;
1865 BlockDriverState *bs = blk_bs(blk);
1866
1867 optype = is_read ? IO_OPERATION_TYPE_READ : IO_OPERATION_TYPE_WRITE;
1868 qapi_event_send_block_io_error(blk_name(blk), !!bs,
1869 bs ? bdrv_get_node_name(bs) : NULL, optype,
1870 action, blk_iostatus_is_enabled(blk),
1871 error == ENOSPC, strerror(error));
1872 }
1873
1874 /* This is done by device models because, while the block layer knows
1875 * about the error, it does not know whether an operation comes from
1876 * the device or the block layer (from a job, for example).
1877 */
1878 void blk_error_action(BlockBackend *blk, BlockErrorAction action,
1879 bool is_read, int error)
1880 {
1881 assert(error >= 0);
1882 IO_CODE();
1883
1884 if (action == BLOCK_ERROR_ACTION_STOP) {
1885 /* First set the iostatus, so that "info block" returns an iostatus
1886 * that matches the events raised so far (an additional error iostatus
1887 * is fine, but not a lost one).
1888 */
1889 blk_iostatus_set_err(blk, error);
1890
1891 /* Then raise the request to stop the VM and the event.
1892 * qemu_system_vmstop_request_prepare has two effects. First,
1893 * it ensures that the STOP event always comes after the
1894 * BLOCK_IO_ERROR event. Second, it ensures that even if management
1895 * can observe the STOP event and do a "cont" before the STOP
1896 * event is issued, the VM will not stop. In this case, vm_start()
1897 * also ensures that the STOP/RESUME pair of events is emitted.
1898 */
1899 qemu_system_vmstop_request_prepare();
1900 send_qmp_error_event(blk, action, is_read, error);
1901 qemu_system_vmstop_request(RUN_STATE_IO_ERROR);
1902 } else {
1903 send_qmp_error_event(blk, action, is_read, error);
1904 }
1905 }
1906
1907 /*
1908 * Returns true if the BlockBackend can support taking write permissions
1909 * (because its root node is not read-only).
1910 */
1911 bool blk_supports_write_perm(BlockBackend *blk)
1912 {
1913 BlockDriverState *bs = blk_bs(blk);
1914 GLOBAL_STATE_CODE();
1915
1916 if (bs) {
1917 return !bdrv_is_read_only(bs);
1918 } else {
1919 return blk->root_state.open_flags & BDRV_O_RDWR;
1920 }
1921 }
1922
1923 /*
1924 * Returns true if the BlockBackend can be written to in its current
1925 * configuration (i.e. if write permission have been requested)
1926 */
1927 bool blk_is_writable(BlockBackend *blk)
1928 {
1929 IO_CODE();
1930 return blk->perm & BLK_PERM_WRITE;
1931 }
1932
1933 bool blk_is_sg(BlockBackend *blk)
1934 {
1935 BlockDriverState *bs = blk_bs(blk);
1936 GLOBAL_STATE_CODE();
1937
1938 if (!bs) {
1939 return false;
1940 }
1941
1942 return bdrv_is_sg(bs);
1943 }
1944
1945 bool blk_enable_write_cache(BlockBackend *blk)
1946 {
1947 IO_CODE();
1948 return blk->enable_write_cache;
1949 }
1950
1951 void blk_set_enable_write_cache(BlockBackend *blk, bool wce)
1952 {
1953 GLOBAL_STATE_CODE();
1954 blk->enable_write_cache = wce;
1955 }
1956
1957 void blk_activate(BlockBackend *blk, Error **errp)
1958 {
1959 BlockDriverState *bs = blk_bs(blk);
1960 GLOBAL_STATE_CODE();
1961
1962 if (!bs) {
1963 error_setg(errp, "Device '%s' has no medium", blk->name);
1964 return;
1965 }
1966
1967 bdrv_activate(bs, errp);
1968 }
1969
1970 bool blk_is_inserted(BlockBackend *blk)
1971 {
1972 BlockDriverState *bs = blk_bs(blk);
1973 IO_CODE();
1974
1975 return bs && bdrv_is_inserted(bs);
1976 }
1977
1978 bool blk_is_available(BlockBackend *blk)
1979 {
1980 IO_CODE();
1981 return blk_is_inserted(blk) && !blk_dev_is_tray_open(blk);
1982 }
1983
1984 void blk_lock_medium(BlockBackend *blk, bool locked)
1985 {
1986 BlockDriverState *bs = blk_bs(blk);
1987 IO_CODE();
1988
1989 if (bs) {
1990 bdrv_lock_medium(bs, locked);
1991 }
1992 }
1993
1994 void blk_eject(BlockBackend *blk, bool eject_flag)
1995 {
1996 BlockDriverState *bs = blk_bs(blk);
1997 char *id;
1998 IO_CODE();
1999
2000 if (bs) {
2001 bdrv_eject(bs, eject_flag);
2002 }
2003
2004 /* Whether or not we ejected on the backend,
2005 * the frontend experienced a tray event. */
2006 id = blk_get_attached_dev_id(blk);
2007 qapi_event_send_device_tray_moved(blk_name(blk), id,
2008 eject_flag);
2009 g_free(id);
2010 }
2011
2012 int blk_get_flags(BlockBackend *blk)
2013 {
2014 BlockDriverState *bs = blk_bs(blk);
2015 GLOBAL_STATE_CODE();
2016
2017 if (bs) {
2018 return bdrv_get_flags(bs);
2019 } else {
2020 return blk->root_state.open_flags;
2021 }
2022 }
2023
2024 /* Returns the minimum request alignment, in bytes; guaranteed nonzero */
2025 uint32_t blk_get_request_alignment(BlockBackend *blk)
2026 {
2027 BlockDriverState *bs = blk_bs(blk);
2028 IO_CODE();
2029 return bs ? bs->bl.request_alignment : BDRV_SECTOR_SIZE;
2030 }
2031
2032 /* Returns the maximum hardware transfer length, in bytes; guaranteed nonzero */
2033 uint64_t blk_get_max_hw_transfer(BlockBackend *blk)
2034 {
2035 BlockDriverState *bs = blk_bs(blk);
2036 uint64_t max = INT_MAX;
2037 IO_CODE();
2038
2039 if (bs) {
2040 max = MIN_NON_ZERO(max, bs->bl.max_hw_transfer);
2041 max = MIN_NON_ZERO(max, bs->bl.max_transfer);
2042 }
2043 return ROUND_DOWN(max, blk_get_request_alignment(blk));
2044 }
2045
2046 /* Returns the maximum transfer length, in bytes; guaranteed nonzero */
2047 uint32_t blk_get_max_transfer(BlockBackend *blk)
2048 {
2049 BlockDriverState *bs = blk_bs(blk);
2050 uint32_t max = INT_MAX;
2051 IO_CODE();
2052
2053 if (bs) {
2054 max = MIN_NON_ZERO(max, bs->bl.max_transfer);
2055 }
2056 return ROUND_DOWN(max, blk_get_request_alignment(blk));
2057 }
2058
2059 int blk_get_max_hw_iov(BlockBackend *blk)
2060 {
2061 IO_CODE();
2062 return MIN_NON_ZERO(blk->root->bs->bl.max_hw_iov,
2063 blk->root->bs->bl.max_iov);
2064 }
2065
2066 int blk_get_max_iov(BlockBackend *blk)
2067 {
2068 IO_CODE();
2069 return blk->root->bs->bl.max_iov;
2070 }
2071
2072 void *blk_try_blockalign(BlockBackend *blk, size_t size)
2073 {
2074 IO_CODE();
2075 return qemu_try_blockalign(blk ? blk_bs(blk) : NULL, size);
2076 }
2077
2078 void *blk_blockalign(BlockBackend *blk, size_t size)
2079 {
2080 IO_CODE();
2081 return qemu_blockalign(blk ? blk_bs(blk) : NULL, size);
2082 }
2083
2084 bool blk_op_is_blocked(BlockBackend *blk, BlockOpType op, Error **errp)
2085 {
2086 BlockDriverState *bs = blk_bs(blk);
2087 GLOBAL_STATE_CODE();
2088
2089 if (!bs) {
2090 return false;
2091 }
2092
2093 return bdrv_op_is_blocked(bs, op, errp);
2094 }
2095
2096 void blk_op_unblock(BlockBackend *blk, BlockOpType op, Error *reason)
2097 {
2098 BlockDriverState *bs = blk_bs(blk);
2099 GLOBAL_STATE_CODE();
2100
2101 if (bs) {
2102 bdrv_op_unblock(bs, op, reason);
2103 }
2104 }
2105
2106 void blk_op_block_all(BlockBackend *blk, Error *reason)
2107 {
2108 BlockDriverState *bs = blk_bs(blk);
2109 GLOBAL_STATE_CODE();
2110
2111 if (bs) {
2112 bdrv_op_block_all(bs, reason);
2113 }
2114 }
2115
2116 void blk_op_unblock_all(BlockBackend *blk, Error *reason)
2117 {
2118 BlockDriverState *bs = blk_bs(blk);
2119 GLOBAL_STATE_CODE();
2120
2121 if (bs) {
2122 bdrv_op_unblock_all(bs, reason);
2123 }
2124 }
2125
2126 AioContext *blk_get_aio_context(BlockBackend *blk)
2127 {
2128 BlockDriverState *bs = blk_bs(blk);
2129 IO_CODE();
2130
2131 if (bs) {
2132 AioContext *ctx = bdrv_get_aio_context(blk_bs(blk));
2133 assert(ctx == blk->ctx);
2134 }
2135
2136 return blk->ctx;
2137 }
2138
2139 static AioContext *blk_aiocb_get_aio_context(BlockAIOCB *acb)
2140 {
2141 BlockBackendAIOCB *blk_acb = DO_UPCAST(BlockBackendAIOCB, common, acb);
2142 return blk_get_aio_context(blk_acb->blk);
2143 }
2144
2145 static int blk_do_set_aio_context(BlockBackend *blk, AioContext *new_context,
2146 bool update_root_node, Error **errp)
2147 {
2148 BlockDriverState *bs = blk_bs(blk);
2149 ThrottleGroupMember *tgm = &blk->public.throttle_group_member;
2150 int ret;
2151
2152 if (bs) {
2153 bdrv_ref(bs);
2154
2155 if (update_root_node) {
2156 ret = bdrv_child_try_set_aio_context(bs, new_context, blk->root,
2157 errp);
2158 if (ret < 0) {
2159 bdrv_unref(bs);
2160 return ret;
2161 }
2162 }
2163 if (tgm->throttle_state) {
2164 bdrv_drained_begin(bs);
2165 throttle_group_detach_aio_context(tgm);
2166 throttle_group_attach_aio_context(tgm, new_context);
2167 bdrv_drained_end(bs);
2168 }
2169
2170 bdrv_unref(bs);
2171 }
2172
2173 blk->ctx = new_context;
2174 return 0;
2175 }
2176
2177 int blk_set_aio_context(BlockBackend *blk, AioContext *new_context,
2178 Error **errp)
2179 {
2180 GLOBAL_STATE_CODE();
2181 return blk_do_set_aio_context(blk, new_context, true, errp);
2182 }
2183
2184 typedef struct BdrvStateBlkRootContext {
2185 AioContext *new_ctx;
2186 BlockBackend *blk;
2187 } BdrvStateBlkRootContext;
2188
2189 static void blk_root_set_aio_ctx_commit(void *opaque)
2190 {
2191 BdrvStateBlkRootContext *s = opaque;
2192 BlockBackend *blk = s->blk;
2193
2194 blk_do_set_aio_context(blk, s->new_ctx, false, &error_abort);
2195 }
2196
2197 static TransactionActionDrv set_blk_root_context = {
2198 .commit = blk_root_set_aio_ctx_commit,
2199 .clean = g_free,
2200 };
2201
2202 static bool blk_root_change_aio_ctx(BdrvChild *child, AioContext *ctx,
2203 GHashTable *visited, Transaction *tran,
2204 Error **errp)
2205 {
2206 BlockBackend *blk = child->opaque;
2207 BdrvStateBlkRootContext *s;
2208
2209 if (!blk->allow_aio_context_change) {
2210 /*
2211 * Manually created BlockBackends (those with a name) that are not
2212 * attached to anything can change their AioContext without updating
2213 * their user; return an error for others.
2214 */
2215 if (!blk->name || blk->dev) {
2216 /* TODO Add BB name/QOM path */
2217 error_setg(errp, "Cannot change iothread of active block backend");
2218 return false;
2219 }
2220 }
2221
2222 s = g_new(BdrvStateBlkRootContext, 1);
2223 *s = (BdrvStateBlkRootContext) {
2224 .new_ctx = ctx,
2225 .blk = blk,
2226 };
2227
2228 tran_add(tran, &set_blk_root_context, s);
2229 return true;
2230 }
2231
2232 static bool blk_root_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
2233 GSList **ignore, Error **errp)
2234 {
2235 BlockBackend *blk = child->opaque;
2236
2237 if (blk->allow_aio_context_change) {
2238 return true;
2239 }
2240
2241 /* Only manually created BlockBackends that are not attached to anything
2242 * can change their AioContext without updating their user. */
2243 if (!blk->name || blk->dev) {
2244 /* TODO Add BB name/QOM path */
2245 error_setg(errp, "Cannot change iothread of active block backend");
2246 return false;
2247 }
2248
2249 return true;
2250 }
2251
2252 static void blk_root_set_aio_ctx(BdrvChild *child, AioContext *ctx,
2253 GSList **ignore)
2254 {
2255 BlockBackend *blk = child->opaque;
2256 blk_do_set_aio_context(blk, ctx, false, &error_abort);
2257 }
2258
2259 void blk_add_aio_context_notifier(BlockBackend *blk,
2260 void (*attached_aio_context)(AioContext *new_context, void *opaque),
2261 void (*detach_aio_context)(void *opaque), void *opaque)
2262 {
2263 BlockBackendAioNotifier *notifier;
2264 BlockDriverState *bs = blk_bs(blk);
2265 GLOBAL_STATE_CODE();
2266
2267 notifier = g_new(BlockBackendAioNotifier, 1);
2268 notifier->attached_aio_context = attached_aio_context;
2269 notifier->detach_aio_context = detach_aio_context;
2270 notifier->opaque = opaque;
2271 QLIST_INSERT_HEAD(&blk->aio_notifiers, notifier, list);
2272
2273 if (bs) {
2274 bdrv_add_aio_context_notifier(bs, attached_aio_context,
2275 detach_aio_context, opaque);
2276 }
2277 }
2278
2279 void blk_remove_aio_context_notifier(BlockBackend *blk,
2280 void (*attached_aio_context)(AioContext *,
2281 void *),
2282 void (*detach_aio_context)(void *),
2283 void *opaque)
2284 {
2285 BlockBackendAioNotifier *notifier;
2286 BlockDriverState *bs = blk_bs(blk);
2287
2288 GLOBAL_STATE_CODE();
2289
2290 if (bs) {
2291 bdrv_remove_aio_context_notifier(bs, attached_aio_context,
2292 detach_aio_context, opaque);
2293 }
2294
2295 QLIST_FOREACH(notifier, &blk->aio_notifiers, list) {
2296 if (notifier->attached_aio_context == attached_aio_context &&
2297 notifier->detach_aio_context == detach_aio_context &&
2298 notifier->opaque == opaque) {
2299 QLIST_REMOVE(notifier, list);
2300 g_free(notifier);
2301 return;
2302 }
2303 }
2304
2305 abort();
2306 }
2307
2308 void blk_add_remove_bs_notifier(BlockBackend *blk, Notifier *notify)
2309 {
2310 GLOBAL_STATE_CODE();
2311 notifier_list_add(&blk->remove_bs_notifiers, notify);
2312 }
2313
2314 void blk_add_insert_bs_notifier(BlockBackend *blk, Notifier *notify)
2315 {
2316 GLOBAL_STATE_CODE();
2317 notifier_list_add(&blk->insert_bs_notifiers, notify);
2318 }
2319
2320 void blk_io_plug(BlockBackend *blk)
2321 {
2322 BlockDriverState *bs = blk_bs(blk);
2323 IO_CODE();
2324
2325 if (bs) {
2326 bdrv_io_plug(bs);
2327 }
2328 }
2329
2330 void blk_io_unplug(BlockBackend *blk)
2331 {
2332 BlockDriverState *bs = blk_bs(blk);
2333 IO_CODE();
2334
2335 if (bs) {
2336 bdrv_io_unplug(bs);
2337 }
2338 }
2339
2340 BlockAcctStats *blk_get_stats(BlockBackend *blk)
2341 {
2342 IO_CODE();
2343 return &blk->stats;
2344 }
2345
2346 void *blk_aio_get(const AIOCBInfo *aiocb_info, BlockBackend *blk,
2347 BlockCompletionFunc *cb, void *opaque)
2348 {
2349 IO_CODE();
2350 return qemu_aio_get(aiocb_info, blk_bs(blk), cb, opaque);
2351 }
2352
2353 int coroutine_fn blk_co_pwrite_zeroes(BlockBackend *blk, int64_t offset,
2354 int64_t bytes, BdrvRequestFlags flags)
2355 {
2356 IO_OR_GS_CODE();
2357 return blk_co_pwritev(blk, offset, bytes, NULL,
2358 flags | BDRV_REQ_ZERO_WRITE);
2359 }
2360
2361 int coroutine_fn blk_co_pwrite_compressed(BlockBackend *blk, int64_t offset,
2362 int64_t bytes, const void *buf)
2363 {
2364 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, bytes);
2365 IO_OR_GS_CODE();
2366 return blk_co_pwritev_part(blk, offset, bytes, &qiov, 0,
2367 BDRV_REQ_WRITE_COMPRESSED);
2368 }
2369
2370 int coroutine_fn blk_co_truncate(BlockBackend *blk, int64_t offset, bool exact,
2371 PreallocMode prealloc, BdrvRequestFlags flags,
2372 Error **errp)
2373 {
2374 IO_OR_GS_CODE();
2375 if (!blk_is_available(blk)) {
2376 error_setg(errp, "No medium inserted");
2377 return -ENOMEDIUM;
2378 }
2379
2380 return bdrv_co_truncate(blk->root, offset, exact, prealloc, flags, errp);
2381 }
2382
2383 int blk_save_vmstate(BlockBackend *blk, const uint8_t *buf,
2384 int64_t pos, int size)
2385 {
2386 int ret;
2387 GLOBAL_STATE_CODE();
2388
2389 if (!blk_is_available(blk)) {
2390 return -ENOMEDIUM;
2391 }
2392
2393 ret = bdrv_save_vmstate(blk_bs(blk), buf, pos, size);
2394 if (ret < 0) {
2395 return ret;
2396 }
2397
2398 if (ret == size && !blk->enable_write_cache) {
2399 ret = bdrv_flush(blk_bs(blk));
2400 }
2401
2402 return ret < 0 ? ret : size;
2403 }
2404
2405 int blk_load_vmstate(BlockBackend *blk, uint8_t *buf, int64_t pos, int size)
2406 {
2407 GLOBAL_STATE_CODE();
2408 if (!blk_is_available(blk)) {
2409 return -ENOMEDIUM;
2410 }
2411
2412 return bdrv_load_vmstate(blk_bs(blk), buf, pos, size);
2413 }
2414
2415 int blk_probe_blocksizes(BlockBackend *blk, BlockSizes *bsz)
2416 {
2417 GLOBAL_STATE_CODE();
2418 if (!blk_is_available(blk)) {
2419 return -ENOMEDIUM;
2420 }
2421
2422 return bdrv_probe_blocksizes(blk_bs(blk), bsz);
2423 }
2424
2425 int blk_probe_geometry(BlockBackend *blk, HDGeometry *geo)
2426 {
2427 GLOBAL_STATE_CODE();
2428 if (!blk_is_available(blk)) {
2429 return -ENOMEDIUM;
2430 }
2431
2432 return bdrv_probe_geometry(blk_bs(blk), geo);
2433 }
2434
2435 /*
2436 * Updates the BlockBackendRootState object with data from the currently
2437 * attached BlockDriverState.
2438 */
2439 void blk_update_root_state(BlockBackend *blk)
2440 {
2441 GLOBAL_STATE_CODE();
2442 assert(blk->root);
2443
2444 blk->root_state.open_flags = blk->root->bs->open_flags;
2445 blk->root_state.detect_zeroes = blk->root->bs->detect_zeroes;
2446 }
2447
2448 /*
2449 * Returns the detect-zeroes setting to be used for bdrv_open() of a
2450 * BlockDriverState which is supposed to inherit the root state.
2451 */
2452 bool blk_get_detect_zeroes_from_root_state(BlockBackend *blk)
2453 {
2454 GLOBAL_STATE_CODE();
2455 return blk->root_state.detect_zeroes;
2456 }
2457
2458 /*
2459 * Returns the flags to be used for bdrv_open() of a BlockDriverState which is
2460 * supposed to inherit the root state.
2461 */
2462 int blk_get_open_flags_from_root_state(BlockBackend *blk)
2463 {
2464 GLOBAL_STATE_CODE();
2465 return blk->root_state.open_flags;
2466 }
2467
2468 BlockBackendRootState *blk_get_root_state(BlockBackend *blk)
2469 {
2470 GLOBAL_STATE_CODE();
2471 return &blk->root_state;
2472 }
2473
2474 int blk_commit_all(void)
2475 {
2476 BlockBackend *blk = NULL;
2477 GLOBAL_STATE_CODE();
2478
2479 while ((blk = blk_all_next(blk)) != NULL) {
2480 AioContext *aio_context = blk_get_aio_context(blk);
2481 BlockDriverState *unfiltered_bs = bdrv_skip_filters(blk_bs(blk));
2482
2483 aio_context_acquire(aio_context);
2484 if (blk_is_inserted(blk) && bdrv_cow_child(unfiltered_bs)) {
2485 int ret;
2486
2487 ret = bdrv_commit(unfiltered_bs);
2488 if (ret < 0) {
2489 aio_context_release(aio_context);
2490 return ret;
2491 }
2492 }
2493 aio_context_release(aio_context);
2494 }
2495 return 0;
2496 }
2497
2498
2499 /* throttling disk I/O limits */
2500 void blk_set_io_limits(BlockBackend *blk, ThrottleConfig *cfg)
2501 {
2502 GLOBAL_STATE_CODE();
2503 throttle_group_config(&blk->public.throttle_group_member, cfg);
2504 }
2505
2506 void blk_io_limits_disable(BlockBackend *blk)
2507 {
2508 BlockDriverState *bs = blk_bs(blk);
2509 ThrottleGroupMember *tgm = &blk->public.throttle_group_member;
2510 assert(tgm->throttle_state);
2511 GLOBAL_STATE_CODE();
2512 if (bs) {
2513 bdrv_ref(bs);
2514 bdrv_drained_begin(bs);
2515 }
2516 throttle_group_unregister_tgm(tgm);
2517 if (bs) {
2518 bdrv_drained_end(bs);
2519 bdrv_unref(bs);
2520 }
2521 }
2522
2523 /* should be called before blk_set_io_limits if a limit is set */
2524 void blk_io_limits_enable(BlockBackend *blk, const char *group)
2525 {
2526 assert(!blk->public.throttle_group_member.throttle_state);
2527 GLOBAL_STATE_CODE();
2528 throttle_group_register_tgm(&blk->public.throttle_group_member,
2529 group, blk_get_aio_context(blk));
2530 }
2531
2532 void blk_io_limits_update_group(BlockBackend *blk, const char *group)
2533 {
2534 GLOBAL_STATE_CODE();
2535 /* this BB is not part of any group */
2536 if (!blk->public.throttle_group_member.throttle_state) {
2537 return;
2538 }
2539
2540 /* this BB is a part of the same group than the one we want */
2541 if (!g_strcmp0(throttle_group_get_name(&blk->public.throttle_group_member),
2542 group)) {
2543 return;
2544 }
2545
2546 /* need to change the group this bs belong to */
2547 blk_io_limits_disable(blk);
2548 blk_io_limits_enable(blk, group);
2549 }
2550
2551 static void blk_root_drained_begin(BdrvChild *child)
2552 {
2553 BlockBackend *blk = child->opaque;
2554 ThrottleGroupMember *tgm = &blk->public.throttle_group_member;
2555
2556 if (++blk->quiesce_counter == 1) {
2557 if (blk->dev_ops && blk->dev_ops->drained_begin) {
2558 blk->dev_ops->drained_begin(blk->dev_opaque);
2559 }
2560 }
2561
2562 /* Note that blk->root may not be accessible here yet if we are just
2563 * attaching to a BlockDriverState that is drained. Use child instead. */
2564
2565 if (qatomic_fetch_inc(&tgm->io_limits_disabled) == 0) {
2566 throttle_group_restart_tgm(tgm);
2567 }
2568 }
2569
2570 static bool blk_root_drained_poll(BdrvChild *child)
2571 {
2572 BlockBackend *blk = child->opaque;
2573 bool busy = false;
2574 assert(blk->quiesce_counter);
2575
2576 if (blk->dev_ops && blk->dev_ops->drained_poll) {
2577 busy = blk->dev_ops->drained_poll(blk->dev_opaque);
2578 }
2579 return busy || !!blk->in_flight;
2580 }
2581
2582 static void blk_root_drained_end(BdrvChild *child, int *drained_end_counter)
2583 {
2584 BlockBackend *blk = child->opaque;
2585 assert(blk->quiesce_counter);
2586
2587 assert(blk->public.throttle_group_member.io_limits_disabled);
2588 qatomic_dec(&blk->public.throttle_group_member.io_limits_disabled);
2589
2590 if (--blk->quiesce_counter == 0) {
2591 if (blk->dev_ops && blk->dev_ops->drained_end) {
2592 blk->dev_ops->drained_end(blk->dev_opaque);
2593 }
2594 while (qemu_co_enter_next(&blk->queued_requests, NULL)) {
2595 /* Resume all queued requests */
2596 }
2597 }
2598 }
2599
2600 void blk_register_buf(BlockBackend *blk, void *host, size_t size)
2601 {
2602 GLOBAL_STATE_CODE();
2603 bdrv_register_buf(blk_bs(blk), host, size);
2604 }
2605
2606 void blk_unregister_buf(BlockBackend *blk, void *host)
2607 {
2608 GLOBAL_STATE_CODE();
2609 bdrv_unregister_buf(blk_bs(blk), host);
2610 }
2611
2612 int coroutine_fn blk_co_copy_range(BlockBackend *blk_in, int64_t off_in,
2613 BlockBackend *blk_out, int64_t off_out,
2614 int64_t bytes, BdrvRequestFlags read_flags,
2615 BdrvRequestFlags write_flags)
2616 {
2617 int r;
2618 IO_CODE();
2619
2620 r = blk_check_byte_request(blk_in, off_in, bytes);
2621 if (r) {
2622 return r;
2623 }
2624 r = blk_check_byte_request(blk_out, off_out, bytes);
2625 if (r) {
2626 return r;
2627 }
2628 return bdrv_co_copy_range(blk_in->root, off_in,
2629 blk_out->root, off_out,
2630 bytes, read_flags, write_flags);
2631 }
2632
2633 const BdrvChild *blk_root(BlockBackend *blk)
2634 {
2635 GLOBAL_STATE_CODE();
2636 return blk->root;
2637 }
2638
2639 int blk_make_empty(BlockBackend *blk, Error **errp)
2640 {
2641 GLOBAL_STATE_CODE();
2642 if (!blk_is_available(blk)) {
2643 error_setg(errp, "No medium inserted");
2644 return -ENOMEDIUM;
2645 }
2646
2647 return bdrv_make_empty(blk->root, errp);
2648 }