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