s390x/cpumodel: document S390FeatDef.bit not applicable
[qemu/ar7.git] / block / block-backend.c
blob0266ac990b3f0eb9344a9dbfefce72575f72aaa8
1 /*
2 * QEMU Block backends
4 * Copyright (C) 2014-2016 Red Hat, Inc.
6 * Authors:
7 * Markus Armbruster <armbru@redhat.com>,
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.
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/throttle-groups.h"
18 #include "sysemu/blockdev.h"
19 #include "sysemu/sysemu.h"
20 #include "qapi-event.h"
21 #include "qapi/error.h"
22 #include "qemu/id.h"
23 #include "qemu/option.h"
24 #include "trace.h"
25 #include "migration/misc.h"
27 /* Number of coroutines to reserve per attached device model */
28 #define COROUTINE_POOL_RESERVATION 64
30 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
32 static AioContext *blk_aiocb_get_aio_context(BlockAIOCB *acb);
34 struct BlockBackend {
35 char *name;
36 int refcnt;
37 BdrvChild *root;
38 DriveInfo *legacy_dinfo; /* null unless created by drive_new() */
39 QTAILQ_ENTRY(BlockBackend) link; /* for block_backends */
40 QTAILQ_ENTRY(BlockBackend) monitor_link; /* for monitor_block_backends */
41 BlockBackendPublic public;
43 void *dev; /* attached device model, if any */
44 bool legacy_dev; /* true if dev is not a DeviceState */
45 /* TODO change to DeviceState when all users are qdevified */
46 const BlockDevOps *dev_ops;
47 void *dev_opaque;
49 /* the block size for which the guest device expects atomicity */
50 int guest_block_size;
52 /* If the BDS tree is removed, some of its options are stored here (which
53 * can be used to restore those options in the new BDS on insert) */
54 BlockBackendRootState root_state;
56 bool enable_write_cache;
58 /* I/O stats (display with "info blockstats"). */
59 BlockAcctStats stats;
61 BlockdevOnError on_read_error, on_write_error;
62 bool iostatus_enabled;
63 BlockDeviceIoStatus iostatus;
65 uint64_t perm;
66 uint64_t shared_perm;
67 bool disable_perm;
69 bool allow_write_beyond_eof;
71 NotifierList remove_bs_notifiers, insert_bs_notifiers;
73 int quiesce_counter;
74 VMChangeStateEntry *vmsh;
75 bool force_allow_inactivate;
78 typedef struct BlockBackendAIOCB {
79 BlockAIOCB common;
80 BlockBackend *blk;
81 int ret;
82 } BlockBackendAIOCB;
84 static const AIOCBInfo block_backend_aiocb_info = {
85 .get_aio_context = blk_aiocb_get_aio_context,
86 .aiocb_size = sizeof(BlockBackendAIOCB),
89 static void drive_info_del(DriveInfo *dinfo);
90 static BlockBackend *bdrv_first_blk(BlockDriverState *bs);
92 /* All BlockBackends */
93 static QTAILQ_HEAD(, BlockBackend) block_backends =
94 QTAILQ_HEAD_INITIALIZER(block_backends);
96 /* All BlockBackends referenced by the monitor and which are iterated through by
97 * blk_next() */
98 static QTAILQ_HEAD(, BlockBackend) monitor_block_backends =
99 QTAILQ_HEAD_INITIALIZER(monitor_block_backends);
101 static void blk_root_inherit_options(int *child_flags, QDict *child_options,
102 int parent_flags, QDict *parent_options)
104 /* We're not supposed to call this function for root nodes */
105 abort();
107 static void blk_root_drained_begin(BdrvChild *child);
108 static void blk_root_drained_end(BdrvChild *child);
110 static void blk_root_change_media(BdrvChild *child, bool load);
111 static void blk_root_resize(BdrvChild *child);
113 static char *blk_root_get_parent_desc(BdrvChild *child)
115 BlockBackend *blk = child->opaque;
116 char *dev_id;
118 if (blk->name) {
119 return g_strdup(blk->name);
122 dev_id = blk_get_attached_dev_id(blk);
123 if (*dev_id) {
124 return dev_id;
125 } else {
126 /* TODO Callback into the BB owner for something more detailed */
127 g_free(dev_id);
128 return g_strdup("a block device");
132 static const char *blk_root_get_name(BdrvChild *child)
134 return blk_name(child->opaque);
137 static void blk_vm_state_changed(void *opaque, int running, RunState state)
139 Error *local_err = NULL;
140 BlockBackend *blk = opaque;
142 if (state == RUN_STATE_INMIGRATE) {
143 return;
146 qemu_del_vm_change_state_handler(blk->vmsh);
147 blk->vmsh = NULL;
148 blk_set_perm(blk, blk->perm, blk->shared_perm, &local_err);
149 if (local_err) {
150 error_report_err(local_err);
155 * Notifies the user of the BlockBackend that migration has completed. qdev
156 * devices can tighten their permissions in response (specifically revoke
157 * shared write permissions that we needed for storage migration).
159 * If an error is returned, the VM cannot be allowed to be resumed.
161 static void blk_root_activate(BdrvChild *child, Error **errp)
163 BlockBackend *blk = child->opaque;
164 Error *local_err = NULL;
166 if (!blk->disable_perm) {
167 return;
170 blk->disable_perm = false;
172 blk_set_perm(blk, blk->perm, BLK_PERM_ALL, &local_err);
173 if (local_err) {
174 error_propagate(errp, local_err);
175 blk->disable_perm = true;
176 return;
179 if (runstate_check(RUN_STATE_INMIGRATE)) {
180 /* Activation can happen when migration process is still active, for
181 * example when nbd_server_add is called during non-shared storage
182 * migration. Defer the shared_perm update to migration completion. */
183 if (!blk->vmsh) {
184 blk->vmsh = qemu_add_vm_change_state_handler(blk_vm_state_changed,
185 blk);
187 return;
190 blk_set_perm(blk, blk->perm, blk->shared_perm, &local_err);
191 if (local_err) {
192 error_propagate(errp, local_err);
193 blk->disable_perm = true;
194 return;
198 void blk_set_force_allow_inactivate(BlockBackend *blk)
200 blk->force_allow_inactivate = true;
203 static bool blk_can_inactivate(BlockBackend *blk)
205 /* If it is a guest device, inactivate is ok. */
206 if (blk->dev || blk_name(blk)[0]) {
207 return true;
210 /* Inactivating means no more writes to the image can be done,
211 * even if those writes would be changes invisible to the
212 * guest. For block job BBs that satisfy this, we can just allow
213 * it. This is the case for mirror job source, which is required
214 * by libvirt non-shared block migration. */
215 if (!(blk->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED))) {
216 return true;
219 return blk->force_allow_inactivate;
222 static int blk_root_inactivate(BdrvChild *child)
224 BlockBackend *blk = child->opaque;
226 if (blk->disable_perm) {
227 return 0;
230 if (!blk_can_inactivate(blk)) {
231 return -EPERM;
234 blk->disable_perm = true;
235 if (blk->root) {
236 bdrv_child_try_set_perm(blk->root, 0, BLK_PERM_ALL, &error_abort);
239 return 0;
242 static const BdrvChildRole child_root = {
243 .inherit_options = blk_root_inherit_options,
245 .change_media = blk_root_change_media,
246 .resize = blk_root_resize,
247 .get_name = blk_root_get_name,
248 .get_parent_desc = blk_root_get_parent_desc,
250 .drained_begin = blk_root_drained_begin,
251 .drained_end = blk_root_drained_end,
253 .activate = blk_root_activate,
254 .inactivate = blk_root_inactivate,
258 * Create a new BlockBackend with a reference count of one.
260 * @perm is a bitmasks of BLK_PERM_* constants which describes the permissions
261 * to request for a block driver node that is attached to this BlockBackend.
262 * @shared_perm is a bitmask which describes which permissions may be granted
263 * to other users of the attached node.
264 * Both sets of permissions can be changed later using blk_set_perm().
266 * Return the new BlockBackend on success, null on failure.
268 BlockBackend *blk_new(uint64_t perm, uint64_t shared_perm)
270 BlockBackend *blk;
272 blk = g_new0(BlockBackend, 1);
273 blk->refcnt = 1;
274 blk->perm = perm;
275 blk->shared_perm = shared_perm;
276 blk_set_enable_write_cache(blk, true);
278 block_acct_init(&blk->stats);
280 notifier_list_init(&blk->remove_bs_notifiers);
281 notifier_list_init(&blk->insert_bs_notifiers);
283 QTAILQ_INSERT_TAIL(&block_backends, blk, link);
284 return blk;
288 * Creates a new BlockBackend, opens a new BlockDriverState, and connects both.
290 * Just as with bdrv_open(), after having called this function the reference to
291 * @options belongs to the block layer (even on failure).
293 * TODO: Remove @filename and @flags; it should be possible to specify a whole
294 * BDS tree just by specifying the @options QDict (or @reference,
295 * alternatively). At the time of adding this function, this is not possible,
296 * though, so callers of this function have to be able to specify @filename and
297 * @flags.
299 BlockBackend *blk_new_open(const char *filename, const char *reference,
300 QDict *options, int flags, Error **errp)
302 BlockBackend *blk;
303 BlockDriverState *bs;
304 uint64_t perm = 0;
306 /* blk_new_open() is mainly used in .bdrv_create implementations and the
307 * tools where sharing isn't a concern because the BDS stays private, so we
308 * just request permission according to the flags.
310 * The exceptions are xen_disk and blockdev_init(); in these cases, the
311 * caller of blk_new_open() doesn't make use of the permissions, but they
312 * shouldn't hurt either. We can still share everything here because the
313 * guest devices will add their own blockers if they can't share. */
314 if ((flags & BDRV_O_NO_IO) == 0) {
315 perm |= BLK_PERM_CONSISTENT_READ;
316 if (flags & BDRV_O_RDWR) {
317 perm |= BLK_PERM_WRITE;
320 if (flags & BDRV_O_RESIZE) {
321 perm |= BLK_PERM_RESIZE;
324 blk = blk_new(perm, BLK_PERM_ALL);
325 bs = bdrv_open(filename, reference, options, flags, errp);
326 if (!bs) {
327 blk_unref(blk);
328 return NULL;
331 blk->root = bdrv_root_attach_child(bs, "root", &child_root,
332 perm, BLK_PERM_ALL, blk, errp);
333 if (!blk->root) {
334 bdrv_unref(bs);
335 blk_unref(blk);
336 return NULL;
339 return blk;
342 static void blk_delete(BlockBackend *blk)
344 assert(!blk->refcnt);
345 assert(!blk->name);
346 assert(!blk->dev);
347 if (blk->public.throttle_group_member.throttle_state) {
348 blk_io_limits_disable(blk);
350 if (blk->root) {
351 blk_remove_bs(blk);
353 if (blk->vmsh) {
354 qemu_del_vm_change_state_handler(blk->vmsh);
355 blk->vmsh = NULL;
357 assert(QLIST_EMPTY(&blk->remove_bs_notifiers.notifiers));
358 assert(QLIST_EMPTY(&blk->insert_bs_notifiers.notifiers));
359 QTAILQ_REMOVE(&block_backends, blk, link);
360 drive_info_del(blk->legacy_dinfo);
361 block_acct_cleanup(&blk->stats);
362 g_free(blk);
365 static void drive_info_del(DriveInfo *dinfo)
367 if (!dinfo) {
368 return;
370 qemu_opts_del(dinfo->opts);
371 g_free(dinfo->serial);
372 g_free(dinfo);
375 int blk_get_refcnt(BlockBackend *blk)
377 return blk ? blk->refcnt : 0;
381 * Increment @blk's reference count.
382 * @blk must not be null.
384 void blk_ref(BlockBackend *blk)
386 blk->refcnt++;
390 * Decrement @blk's reference count.
391 * If this drops it to zero, destroy @blk.
392 * For convenience, do nothing if @blk is null.
394 void blk_unref(BlockBackend *blk)
396 if (blk) {
397 assert(blk->refcnt > 0);
398 if (!--blk->refcnt) {
399 blk_delete(blk);
405 * Behaves similarly to blk_next() but iterates over all BlockBackends, even the
406 * ones which are hidden (i.e. are not referenced by the monitor).
408 BlockBackend *blk_all_next(BlockBackend *blk)
410 return blk ? QTAILQ_NEXT(blk, link)
411 : QTAILQ_FIRST(&block_backends);
414 void blk_remove_all_bs(void)
416 BlockBackend *blk = NULL;
418 while ((blk = blk_all_next(blk)) != NULL) {
419 AioContext *ctx = blk_get_aio_context(blk);
421 aio_context_acquire(ctx);
422 if (blk->root) {
423 blk_remove_bs(blk);
425 aio_context_release(ctx);
430 * Return the monitor-owned BlockBackend after @blk.
431 * If @blk is null, return the first one.
432 * Else, return @blk's next sibling, which may be null.
434 * To iterate over all BlockBackends, do
435 * for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
436 * ...
439 BlockBackend *blk_next(BlockBackend *blk)
441 return blk ? QTAILQ_NEXT(blk, monitor_link)
442 : QTAILQ_FIRST(&monitor_block_backends);
445 /* Iterates over all top-level BlockDriverStates, i.e. BDSs that are owned by
446 * the monitor or attached to a BlockBackend */
447 BlockDriverState *bdrv_next(BdrvNextIterator *it)
449 BlockDriverState *bs, *old_bs;
451 /* Must be called from the main loop */
452 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
454 /* First, return all root nodes of BlockBackends. In order to avoid
455 * returning a BDS twice when multiple BBs refer to it, we only return it
456 * if the BB is the first one in the parent list of the BDS. */
457 if (it->phase == BDRV_NEXT_BACKEND_ROOTS) {
458 BlockBackend *old_blk = it->blk;
460 old_bs = old_blk ? blk_bs(old_blk) : NULL;
462 do {
463 it->blk = blk_all_next(it->blk);
464 bs = it->blk ? blk_bs(it->blk) : NULL;
465 } while (it->blk && (bs == NULL || bdrv_first_blk(bs) != it->blk));
467 if (it->blk) {
468 blk_ref(it->blk);
470 blk_unref(old_blk);
472 if (bs) {
473 bdrv_ref(bs);
474 bdrv_unref(old_bs);
475 return bs;
477 it->phase = BDRV_NEXT_MONITOR_OWNED;
478 } else {
479 old_bs = it->bs;
482 /* Then return the monitor-owned BDSes without a BB attached. Ignore all
483 * BDSes that are attached to a BlockBackend here; they have been handled
484 * by the above block already */
485 do {
486 it->bs = bdrv_next_monitor_owned(it->bs);
487 bs = it->bs;
488 } while (bs && bdrv_has_blk(bs));
490 if (bs) {
491 bdrv_ref(bs);
493 bdrv_unref(old_bs);
495 return bs;
498 static void bdrv_next_reset(BdrvNextIterator *it)
500 *it = (BdrvNextIterator) {
501 .phase = BDRV_NEXT_BACKEND_ROOTS,
505 BlockDriverState *bdrv_first(BdrvNextIterator *it)
507 bdrv_next_reset(it);
508 return bdrv_next(it);
511 /* Must be called when aborting a bdrv_next() iteration before
512 * bdrv_next() returns NULL */
513 void bdrv_next_cleanup(BdrvNextIterator *it)
515 /* Must be called from the main loop */
516 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
518 if (it->phase == BDRV_NEXT_BACKEND_ROOTS) {
519 if (it->blk) {
520 bdrv_unref(blk_bs(it->blk));
521 blk_unref(it->blk);
523 } else {
524 bdrv_unref(it->bs);
527 bdrv_next_reset(it);
531 * Add a BlockBackend into the list of backends referenced by the monitor, with
532 * the given @name acting as the handle for the monitor.
533 * Strictly for use by blockdev.c.
535 * @name must not be null or empty.
537 * Returns true on success and false on failure. In the latter case, an Error
538 * object is returned through @errp.
540 bool monitor_add_blk(BlockBackend *blk, const char *name, Error **errp)
542 assert(!blk->name);
543 assert(name && name[0]);
545 if (!id_wellformed(name)) {
546 error_setg(errp, "Invalid device name");
547 return false;
549 if (blk_by_name(name)) {
550 error_setg(errp, "Device with id '%s' already exists", name);
551 return false;
553 if (bdrv_find_node(name)) {
554 error_setg(errp,
555 "Device name '%s' conflicts with an existing node name",
556 name);
557 return false;
560 blk->name = g_strdup(name);
561 QTAILQ_INSERT_TAIL(&monitor_block_backends, blk, monitor_link);
562 return true;
566 * Remove a BlockBackend from the list of backends referenced by the monitor.
567 * Strictly for use by blockdev.c.
569 void monitor_remove_blk(BlockBackend *blk)
571 if (!blk->name) {
572 return;
575 QTAILQ_REMOVE(&monitor_block_backends, blk, monitor_link);
576 g_free(blk->name);
577 blk->name = NULL;
581 * Return @blk's name, a non-null string.
582 * Returns an empty string iff @blk is not referenced by the monitor.
584 const char *blk_name(const BlockBackend *blk)
586 return blk->name ?: "";
590 * Return the BlockBackend with name @name if it exists, else null.
591 * @name must not be null.
593 BlockBackend *blk_by_name(const char *name)
595 BlockBackend *blk = NULL;
597 assert(name);
598 while ((blk = blk_next(blk)) != NULL) {
599 if (!strcmp(name, blk->name)) {
600 return blk;
603 return NULL;
607 * Return the BlockDriverState attached to @blk if any, else null.
609 BlockDriverState *blk_bs(BlockBackend *blk)
611 return blk->root ? blk->root->bs : NULL;
614 static BlockBackend *bdrv_first_blk(BlockDriverState *bs)
616 BdrvChild *child;
617 QLIST_FOREACH(child, &bs->parents, next_parent) {
618 if (child->role == &child_root) {
619 return child->opaque;
623 return NULL;
627 * Returns true if @bs has an associated BlockBackend.
629 bool bdrv_has_blk(BlockDriverState *bs)
631 return bdrv_first_blk(bs) != NULL;
635 * Returns true if @bs has only BlockBackends as parents.
637 bool bdrv_is_root_node(BlockDriverState *bs)
639 BdrvChild *c;
641 QLIST_FOREACH(c, &bs->parents, next_parent) {
642 if (c->role != &child_root) {
643 return false;
647 return true;
651 * Return @blk's DriveInfo if any, else null.
653 DriveInfo *blk_legacy_dinfo(BlockBackend *blk)
655 return blk->legacy_dinfo;
659 * Set @blk's DriveInfo to @dinfo, and return it.
660 * @blk must not have a DriveInfo set already.
661 * No other BlockBackend may have the same DriveInfo set.
663 DriveInfo *blk_set_legacy_dinfo(BlockBackend *blk, DriveInfo *dinfo)
665 assert(!blk->legacy_dinfo);
666 return blk->legacy_dinfo = dinfo;
670 * Return the BlockBackend with DriveInfo @dinfo.
671 * It must exist.
673 BlockBackend *blk_by_legacy_dinfo(DriveInfo *dinfo)
675 BlockBackend *blk = NULL;
677 while ((blk = blk_next(blk)) != NULL) {
678 if (blk->legacy_dinfo == dinfo) {
679 return blk;
682 abort();
686 * Returns a pointer to the publicly accessible fields of @blk.
688 BlockBackendPublic *blk_get_public(BlockBackend *blk)
690 return &blk->public;
694 * Returns a BlockBackend given the associated @public fields.
696 BlockBackend *blk_by_public(BlockBackendPublic *public)
698 return container_of(public, BlockBackend, public);
702 * Disassociates the currently associated BlockDriverState from @blk.
704 void blk_remove_bs(BlockBackend *blk)
706 ThrottleGroupMember *tgm = &blk->public.throttle_group_member;
707 BlockDriverState *bs;
709 notifier_list_notify(&blk->remove_bs_notifiers, blk);
710 if (tgm->throttle_state) {
711 bs = blk_bs(blk);
712 bdrv_drained_begin(bs);
713 throttle_group_detach_aio_context(tgm);
714 throttle_group_attach_aio_context(tgm, qemu_get_aio_context());
715 bdrv_drained_end(bs);
718 blk_update_root_state(blk);
720 bdrv_root_unref_child(blk->root);
721 blk->root = NULL;
725 * Associates a new BlockDriverState with @blk.
727 int blk_insert_bs(BlockBackend *blk, BlockDriverState *bs, Error **errp)
729 ThrottleGroupMember *tgm = &blk->public.throttle_group_member;
730 blk->root = bdrv_root_attach_child(bs, "root", &child_root,
731 blk->perm, blk->shared_perm, blk, errp);
732 if (blk->root == NULL) {
733 return -EPERM;
735 bdrv_ref(bs);
737 notifier_list_notify(&blk->insert_bs_notifiers, blk);
738 if (tgm->throttle_state) {
739 throttle_group_detach_aio_context(tgm);
740 throttle_group_attach_aio_context(tgm, bdrv_get_aio_context(bs));
743 return 0;
747 * Sets the permission bitmasks that the user of the BlockBackend needs.
749 int blk_set_perm(BlockBackend *blk, uint64_t perm, uint64_t shared_perm,
750 Error **errp)
752 int ret;
754 if (blk->root && !blk->disable_perm) {
755 ret = bdrv_child_try_set_perm(blk->root, perm, shared_perm, errp);
756 if (ret < 0) {
757 return ret;
761 blk->perm = perm;
762 blk->shared_perm = shared_perm;
764 return 0;
767 void blk_get_perm(BlockBackend *blk, uint64_t *perm, uint64_t *shared_perm)
769 *perm = blk->perm;
770 *shared_perm = blk->shared_perm;
773 static int blk_do_attach_dev(BlockBackend *blk, void *dev)
775 if (blk->dev) {
776 return -EBUSY;
779 /* While migration is still incoming, we don't need to apply the
780 * permissions of guest device BlockBackends. We might still have a block
781 * job or NBD server writing to the image for storage migration. */
782 if (runstate_check(RUN_STATE_INMIGRATE)) {
783 blk->disable_perm = true;
786 blk_ref(blk);
787 blk->dev = dev;
788 blk->legacy_dev = false;
789 blk_iostatus_reset(blk);
791 return 0;
795 * Attach device model @dev to @blk.
796 * Return 0 on success, -EBUSY when a device model is attached already.
798 int blk_attach_dev(BlockBackend *blk, DeviceState *dev)
800 return blk_do_attach_dev(blk, dev);
804 * Attach device model @dev to @blk.
805 * @blk must not have a device model attached already.
806 * TODO qdevified devices don't use this, remove when devices are qdevified
808 void blk_attach_dev_legacy(BlockBackend *blk, void *dev)
810 if (blk_do_attach_dev(blk, dev) < 0) {
811 abort();
813 blk->legacy_dev = true;
817 * Detach device model @dev from @blk.
818 * @dev must be currently attached to @blk.
820 void blk_detach_dev(BlockBackend *blk, void *dev)
821 /* TODO change to DeviceState *dev when all users are qdevified */
823 assert(blk->dev == dev);
824 blk->dev = NULL;
825 blk->dev_ops = NULL;
826 blk->dev_opaque = NULL;
827 blk->guest_block_size = 512;
828 blk_set_perm(blk, 0, BLK_PERM_ALL, &error_abort);
829 blk_unref(blk);
833 * Return the device model attached to @blk if any, else null.
835 void *blk_get_attached_dev(BlockBackend *blk)
836 /* TODO change to return DeviceState * when all users are qdevified */
838 return blk->dev;
841 /* Return the qdev ID, or if no ID is assigned the QOM path, of the block
842 * device attached to the BlockBackend. */
843 char *blk_get_attached_dev_id(BlockBackend *blk)
845 DeviceState *dev;
847 assert(!blk->legacy_dev);
848 dev = blk->dev;
850 if (!dev) {
851 return g_strdup("");
852 } else if (dev->id) {
853 return g_strdup(dev->id);
855 return object_get_canonical_path(OBJECT(dev));
859 * Return the BlockBackend which has the device model @dev attached if it
860 * exists, else null.
862 * @dev must not be null.
864 BlockBackend *blk_by_dev(void *dev)
866 BlockBackend *blk = NULL;
868 assert(dev != NULL);
869 while ((blk = blk_all_next(blk)) != NULL) {
870 if (blk->dev == dev) {
871 return blk;
874 return NULL;
878 * Set @blk's device model callbacks to @ops.
879 * @opaque is the opaque argument to pass to the callbacks.
880 * This is for use by device models.
882 void blk_set_dev_ops(BlockBackend *blk, const BlockDevOps *ops,
883 void *opaque)
885 /* All drivers that use blk_set_dev_ops() are qdevified and we want to keep
886 * it that way, so we can assume blk->dev, if present, is a DeviceState if
887 * blk->dev_ops is set. Non-device users may use dev_ops without device. */
888 assert(!blk->legacy_dev);
890 blk->dev_ops = ops;
891 blk->dev_opaque = opaque;
893 /* Are we currently quiesced? Should we enforce this right now? */
894 if (blk->quiesce_counter && ops->drained_begin) {
895 ops->drained_begin(opaque);
900 * Notify @blk's attached device model of media change.
902 * If @load is true, notify of media load. This action can fail, meaning that
903 * the medium cannot be loaded. @errp is set then.
905 * If @load is false, notify of media eject. This can never fail.
907 * Also send DEVICE_TRAY_MOVED events as appropriate.
909 void blk_dev_change_media_cb(BlockBackend *blk, bool load, Error **errp)
911 if (blk->dev_ops && blk->dev_ops->change_media_cb) {
912 bool tray_was_open, tray_is_open;
913 Error *local_err = NULL;
915 assert(!blk->legacy_dev);
917 tray_was_open = blk_dev_is_tray_open(blk);
918 blk->dev_ops->change_media_cb(blk->dev_opaque, load, &local_err);
919 if (local_err) {
920 assert(load == true);
921 error_propagate(errp, local_err);
922 return;
924 tray_is_open = blk_dev_is_tray_open(blk);
926 if (tray_was_open != tray_is_open) {
927 char *id = blk_get_attached_dev_id(blk);
928 qapi_event_send_device_tray_moved(blk_name(blk), id, tray_is_open,
929 &error_abort);
930 g_free(id);
935 static void blk_root_change_media(BdrvChild *child, bool load)
937 blk_dev_change_media_cb(child->opaque, load, NULL);
941 * Does @blk's attached device model have removable media?
942 * %true if no device model is attached.
944 bool blk_dev_has_removable_media(BlockBackend *blk)
946 return !blk->dev || (blk->dev_ops && blk->dev_ops->change_media_cb);
950 * Does @blk's attached device model have a tray?
952 bool blk_dev_has_tray(BlockBackend *blk)
954 return blk->dev_ops && blk->dev_ops->is_tray_open;
958 * Notify @blk's attached device model of a media eject request.
959 * If @force is true, the medium is about to be yanked out forcefully.
961 void blk_dev_eject_request(BlockBackend *blk, bool force)
963 if (blk->dev_ops && blk->dev_ops->eject_request_cb) {
964 blk->dev_ops->eject_request_cb(blk->dev_opaque, force);
969 * Does @blk's attached device model have a tray, and is it open?
971 bool blk_dev_is_tray_open(BlockBackend *blk)
973 if (blk_dev_has_tray(blk)) {
974 return blk->dev_ops->is_tray_open(blk->dev_opaque);
976 return false;
980 * Does @blk's attached device model have the medium locked?
981 * %false if the device model has no such lock.
983 bool blk_dev_is_medium_locked(BlockBackend *blk)
985 if (blk->dev_ops && blk->dev_ops->is_medium_locked) {
986 return blk->dev_ops->is_medium_locked(blk->dev_opaque);
988 return false;
992 * Notify @blk's attached device model of a backend size change.
994 static void blk_root_resize(BdrvChild *child)
996 BlockBackend *blk = child->opaque;
998 if (blk->dev_ops && blk->dev_ops->resize_cb) {
999 blk->dev_ops->resize_cb(blk->dev_opaque);
1003 void blk_iostatus_enable(BlockBackend *blk)
1005 blk->iostatus_enabled = true;
1006 blk->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
1009 /* The I/O status is only enabled if the drive explicitly
1010 * enables it _and_ the VM is configured to stop on errors */
1011 bool blk_iostatus_is_enabled(const BlockBackend *blk)
1013 return (blk->iostatus_enabled &&
1014 (blk->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
1015 blk->on_write_error == BLOCKDEV_ON_ERROR_STOP ||
1016 blk->on_read_error == BLOCKDEV_ON_ERROR_STOP));
1019 BlockDeviceIoStatus blk_iostatus(const BlockBackend *blk)
1021 return blk->iostatus;
1024 void blk_iostatus_disable(BlockBackend *blk)
1026 blk->iostatus_enabled = false;
1029 void blk_iostatus_reset(BlockBackend *blk)
1031 if (blk_iostatus_is_enabled(blk)) {
1032 BlockDriverState *bs = blk_bs(blk);
1033 blk->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
1034 if (bs && bs->job) {
1035 block_job_iostatus_reset(bs->job);
1040 void blk_iostatus_set_err(BlockBackend *blk, int error)
1042 assert(blk_iostatus_is_enabled(blk));
1043 if (blk->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
1044 blk->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
1045 BLOCK_DEVICE_IO_STATUS_FAILED;
1049 void blk_set_allow_write_beyond_eof(BlockBackend *blk, bool allow)
1051 blk->allow_write_beyond_eof = allow;
1054 static int blk_check_byte_request(BlockBackend *blk, int64_t offset,
1055 size_t size)
1057 int64_t len;
1059 if (size > INT_MAX) {
1060 return -EIO;
1063 if (!blk_is_available(blk)) {
1064 return -ENOMEDIUM;
1067 if (offset < 0) {
1068 return -EIO;
1071 if (!blk->allow_write_beyond_eof) {
1072 len = blk_getlength(blk);
1073 if (len < 0) {
1074 return len;
1077 if (offset > len || len - offset < size) {
1078 return -EIO;
1082 return 0;
1085 int coroutine_fn blk_co_preadv(BlockBackend *blk, int64_t offset,
1086 unsigned int bytes, QEMUIOVector *qiov,
1087 BdrvRequestFlags flags)
1089 int ret;
1090 BlockDriverState *bs = blk_bs(blk);
1092 trace_blk_co_preadv(blk, bs, offset, bytes, flags);
1094 ret = blk_check_byte_request(blk, offset, bytes);
1095 if (ret < 0) {
1096 return ret;
1099 bdrv_inc_in_flight(bs);
1101 /* throttling disk I/O */
1102 if (blk->public.throttle_group_member.throttle_state) {
1103 throttle_group_co_io_limits_intercept(&blk->public.throttle_group_member,
1104 bytes, false);
1107 ret = bdrv_co_preadv(blk->root, offset, bytes, qiov, flags);
1108 bdrv_dec_in_flight(bs);
1109 return ret;
1112 int coroutine_fn blk_co_pwritev(BlockBackend *blk, int64_t offset,
1113 unsigned int bytes, QEMUIOVector *qiov,
1114 BdrvRequestFlags flags)
1116 int ret;
1117 BlockDriverState *bs = blk_bs(blk);
1119 trace_blk_co_pwritev(blk, bs, offset, bytes, flags);
1121 ret = blk_check_byte_request(blk, offset, bytes);
1122 if (ret < 0) {
1123 return ret;
1126 bdrv_inc_in_flight(bs);
1127 /* throttling disk I/O */
1128 if (blk->public.throttle_group_member.throttle_state) {
1129 throttle_group_co_io_limits_intercept(&blk->public.throttle_group_member,
1130 bytes, true);
1133 if (!blk->enable_write_cache) {
1134 flags |= BDRV_REQ_FUA;
1137 ret = bdrv_co_pwritev(blk->root, offset, bytes, qiov, flags);
1138 bdrv_dec_in_flight(bs);
1139 return ret;
1142 typedef struct BlkRwCo {
1143 BlockBackend *blk;
1144 int64_t offset;
1145 QEMUIOVector *qiov;
1146 int ret;
1147 BdrvRequestFlags flags;
1148 } BlkRwCo;
1150 static void blk_read_entry(void *opaque)
1152 BlkRwCo *rwco = opaque;
1154 rwco->ret = blk_co_preadv(rwco->blk, rwco->offset, rwco->qiov->size,
1155 rwco->qiov, rwco->flags);
1158 static void blk_write_entry(void *opaque)
1160 BlkRwCo *rwco = opaque;
1162 rwco->ret = blk_co_pwritev(rwco->blk, rwco->offset, rwco->qiov->size,
1163 rwco->qiov, rwco->flags);
1166 static int blk_prw(BlockBackend *blk, int64_t offset, uint8_t *buf,
1167 int64_t bytes, CoroutineEntry co_entry,
1168 BdrvRequestFlags flags)
1170 QEMUIOVector qiov;
1171 struct iovec iov;
1172 BlkRwCo rwco;
1174 iov = (struct iovec) {
1175 .iov_base = buf,
1176 .iov_len = bytes,
1178 qemu_iovec_init_external(&qiov, &iov, 1);
1180 rwco = (BlkRwCo) {
1181 .blk = blk,
1182 .offset = offset,
1183 .qiov = &qiov,
1184 .flags = flags,
1185 .ret = NOT_DONE,
1188 if (qemu_in_coroutine()) {
1189 /* Fast-path if already in coroutine context */
1190 co_entry(&rwco);
1191 } else {
1192 Coroutine *co = qemu_coroutine_create(co_entry, &rwco);
1193 bdrv_coroutine_enter(blk_bs(blk), co);
1194 BDRV_POLL_WHILE(blk_bs(blk), rwco.ret == NOT_DONE);
1197 return rwco.ret;
1200 int blk_pread_unthrottled(BlockBackend *blk, int64_t offset, uint8_t *buf,
1201 int count)
1203 int ret;
1205 ret = blk_check_byte_request(blk, offset, count);
1206 if (ret < 0) {
1207 return ret;
1210 blk_root_drained_begin(blk->root);
1211 ret = blk_pread(blk, offset, buf, count);
1212 blk_root_drained_end(blk->root);
1213 return ret;
1216 int blk_pwrite_zeroes(BlockBackend *blk, int64_t offset,
1217 int bytes, BdrvRequestFlags flags)
1219 return blk_prw(blk, offset, NULL, bytes, blk_write_entry,
1220 flags | BDRV_REQ_ZERO_WRITE);
1223 int blk_make_zero(BlockBackend *blk, BdrvRequestFlags flags)
1225 return bdrv_make_zero(blk->root, flags);
1228 static void error_callback_bh(void *opaque)
1230 struct BlockBackendAIOCB *acb = opaque;
1232 bdrv_dec_in_flight(acb->common.bs);
1233 acb->common.cb(acb->common.opaque, acb->ret);
1234 qemu_aio_unref(acb);
1237 BlockAIOCB *blk_abort_aio_request(BlockBackend *blk,
1238 BlockCompletionFunc *cb,
1239 void *opaque, int ret)
1241 struct BlockBackendAIOCB *acb;
1243 bdrv_inc_in_flight(blk_bs(blk));
1244 acb = blk_aio_get(&block_backend_aiocb_info, blk, cb, opaque);
1245 acb->blk = blk;
1246 acb->ret = ret;
1248 aio_bh_schedule_oneshot(blk_get_aio_context(blk), error_callback_bh, acb);
1249 return &acb->common;
1252 typedef struct BlkAioEmAIOCB {
1253 BlockAIOCB common;
1254 BlkRwCo rwco;
1255 int bytes;
1256 bool has_returned;
1257 } BlkAioEmAIOCB;
1259 static const AIOCBInfo blk_aio_em_aiocb_info = {
1260 .aiocb_size = sizeof(BlkAioEmAIOCB),
1263 static void blk_aio_complete(BlkAioEmAIOCB *acb)
1265 if (acb->has_returned) {
1266 bdrv_dec_in_flight(acb->common.bs);
1267 acb->common.cb(acb->common.opaque, acb->rwco.ret);
1268 qemu_aio_unref(acb);
1272 static void blk_aio_complete_bh(void *opaque)
1274 BlkAioEmAIOCB *acb = opaque;
1275 assert(acb->has_returned);
1276 blk_aio_complete(acb);
1279 static BlockAIOCB *blk_aio_prwv(BlockBackend *blk, int64_t offset, int bytes,
1280 QEMUIOVector *qiov, CoroutineEntry co_entry,
1281 BdrvRequestFlags flags,
1282 BlockCompletionFunc *cb, void *opaque)
1284 BlkAioEmAIOCB *acb;
1285 Coroutine *co;
1287 bdrv_inc_in_flight(blk_bs(blk));
1288 acb = blk_aio_get(&blk_aio_em_aiocb_info, blk, cb, opaque);
1289 acb->rwco = (BlkRwCo) {
1290 .blk = blk,
1291 .offset = offset,
1292 .qiov = qiov,
1293 .flags = flags,
1294 .ret = NOT_DONE,
1296 acb->bytes = bytes;
1297 acb->has_returned = false;
1299 co = qemu_coroutine_create(co_entry, acb);
1300 bdrv_coroutine_enter(blk_bs(blk), co);
1302 acb->has_returned = true;
1303 if (acb->rwco.ret != NOT_DONE) {
1304 aio_bh_schedule_oneshot(blk_get_aio_context(blk),
1305 blk_aio_complete_bh, acb);
1308 return &acb->common;
1311 static void blk_aio_read_entry(void *opaque)
1313 BlkAioEmAIOCB *acb = opaque;
1314 BlkRwCo *rwco = &acb->rwco;
1316 assert(rwco->qiov->size == acb->bytes);
1317 rwco->ret = blk_co_preadv(rwco->blk, rwco->offset, acb->bytes,
1318 rwco->qiov, rwco->flags);
1319 blk_aio_complete(acb);
1322 static void blk_aio_write_entry(void *opaque)
1324 BlkAioEmAIOCB *acb = opaque;
1325 BlkRwCo *rwco = &acb->rwco;
1327 assert(!rwco->qiov || rwco->qiov->size == acb->bytes);
1328 rwco->ret = blk_co_pwritev(rwco->blk, rwco->offset, acb->bytes,
1329 rwco->qiov, rwco->flags);
1330 blk_aio_complete(acb);
1333 BlockAIOCB *blk_aio_pwrite_zeroes(BlockBackend *blk, int64_t offset,
1334 int count, BdrvRequestFlags flags,
1335 BlockCompletionFunc *cb, void *opaque)
1337 return blk_aio_prwv(blk, offset, count, NULL, blk_aio_write_entry,
1338 flags | BDRV_REQ_ZERO_WRITE, cb, opaque);
1341 int blk_pread(BlockBackend *blk, int64_t offset, void *buf, int count)
1343 int ret = blk_prw(blk, offset, buf, count, blk_read_entry, 0);
1344 if (ret < 0) {
1345 return ret;
1347 return count;
1350 int blk_pwrite(BlockBackend *blk, int64_t offset, const void *buf, int count,
1351 BdrvRequestFlags flags)
1353 int ret = blk_prw(blk, offset, (void *) buf, count, blk_write_entry,
1354 flags);
1355 if (ret < 0) {
1356 return ret;
1358 return count;
1361 int64_t blk_getlength(BlockBackend *blk)
1363 if (!blk_is_available(blk)) {
1364 return -ENOMEDIUM;
1367 return bdrv_getlength(blk_bs(blk));
1370 void blk_get_geometry(BlockBackend *blk, uint64_t *nb_sectors_ptr)
1372 if (!blk_bs(blk)) {
1373 *nb_sectors_ptr = 0;
1374 } else {
1375 bdrv_get_geometry(blk_bs(blk), nb_sectors_ptr);
1379 int64_t blk_nb_sectors(BlockBackend *blk)
1381 if (!blk_is_available(blk)) {
1382 return -ENOMEDIUM;
1385 return bdrv_nb_sectors(blk_bs(blk));
1388 BlockAIOCB *blk_aio_preadv(BlockBackend *blk, int64_t offset,
1389 QEMUIOVector *qiov, BdrvRequestFlags flags,
1390 BlockCompletionFunc *cb, void *opaque)
1392 return blk_aio_prwv(blk, offset, qiov->size, qiov,
1393 blk_aio_read_entry, flags, cb, opaque);
1396 BlockAIOCB *blk_aio_pwritev(BlockBackend *blk, int64_t offset,
1397 QEMUIOVector *qiov, BdrvRequestFlags flags,
1398 BlockCompletionFunc *cb, void *opaque)
1400 return blk_aio_prwv(blk, offset, qiov->size, qiov,
1401 blk_aio_write_entry, flags, cb, opaque);
1404 static void blk_aio_flush_entry(void *opaque)
1406 BlkAioEmAIOCB *acb = opaque;
1407 BlkRwCo *rwco = &acb->rwco;
1409 rwco->ret = blk_co_flush(rwco->blk);
1410 blk_aio_complete(acb);
1413 BlockAIOCB *blk_aio_flush(BlockBackend *blk,
1414 BlockCompletionFunc *cb, void *opaque)
1416 return blk_aio_prwv(blk, 0, 0, NULL, blk_aio_flush_entry, 0, cb, opaque);
1419 static void blk_aio_pdiscard_entry(void *opaque)
1421 BlkAioEmAIOCB *acb = opaque;
1422 BlkRwCo *rwco = &acb->rwco;
1424 rwco->ret = blk_co_pdiscard(rwco->blk, rwco->offset, acb->bytes);
1425 blk_aio_complete(acb);
1428 BlockAIOCB *blk_aio_pdiscard(BlockBackend *blk,
1429 int64_t offset, int bytes,
1430 BlockCompletionFunc *cb, void *opaque)
1432 return blk_aio_prwv(blk, offset, bytes, NULL, blk_aio_pdiscard_entry, 0,
1433 cb, opaque);
1436 void blk_aio_cancel(BlockAIOCB *acb)
1438 bdrv_aio_cancel(acb);
1441 void blk_aio_cancel_async(BlockAIOCB *acb)
1443 bdrv_aio_cancel_async(acb);
1446 int blk_co_ioctl(BlockBackend *blk, unsigned long int req, void *buf)
1448 if (!blk_is_available(blk)) {
1449 return -ENOMEDIUM;
1452 return bdrv_co_ioctl(blk_bs(blk), req, buf);
1455 static void blk_ioctl_entry(void *opaque)
1457 BlkRwCo *rwco = opaque;
1458 rwco->ret = blk_co_ioctl(rwco->blk, rwco->offset,
1459 rwco->qiov->iov[0].iov_base);
1462 int blk_ioctl(BlockBackend *blk, unsigned long int req, void *buf)
1464 return blk_prw(blk, req, buf, 0, blk_ioctl_entry, 0);
1467 static void blk_aio_ioctl_entry(void *opaque)
1469 BlkAioEmAIOCB *acb = opaque;
1470 BlkRwCo *rwco = &acb->rwco;
1472 rwco->ret = blk_co_ioctl(rwco->blk, rwco->offset,
1473 rwco->qiov->iov[0].iov_base);
1474 blk_aio_complete(acb);
1477 BlockAIOCB *blk_aio_ioctl(BlockBackend *blk, unsigned long int req, void *buf,
1478 BlockCompletionFunc *cb, void *opaque)
1480 QEMUIOVector qiov;
1481 struct iovec iov;
1483 iov = (struct iovec) {
1484 .iov_base = buf,
1485 .iov_len = 0,
1487 qemu_iovec_init_external(&qiov, &iov, 1);
1489 return blk_aio_prwv(blk, req, 0, &qiov, blk_aio_ioctl_entry, 0, cb, opaque);
1492 int blk_co_pdiscard(BlockBackend *blk, int64_t offset, int bytes)
1494 int ret = blk_check_byte_request(blk, offset, bytes);
1495 if (ret < 0) {
1496 return ret;
1499 return bdrv_co_pdiscard(blk_bs(blk), offset, bytes);
1502 int blk_co_flush(BlockBackend *blk)
1504 if (!blk_is_available(blk)) {
1505 return -ENOMEDIUM;
1508 return bdrv_co_flush(blk_bs(blk));
1511 static void blk_flush_entry(void *opaque)
1513 BlkRwCo *rwco = opaque;
1514 rwco->ret = blk_co_flush(rwco->blk);
1517 int blk_flush(BlockBackend *blk)
1519 return blk_prw(blk, 0, NULL, 0, blk_flush_entry, 0);
1522 void blk_drain(BlockBackend *blk)
1524 if (blk_bs(blk)) {
1525 bdrv_drain(blk_bs(blk));
1529 void blk_drain_all(void)
1531 bdrv_drain_all();
1534 void blk_set_on_error(BlockBackend *blk, BlockdevOnError on_read_error,
1535 BlockdevOnError on_write_error)
1537 blk->on_read_error = on_read_error;
1538 blk->on_write_error = on_write_error;
1541 BlockdevOnError blk_get_on_error(BlockBackend *blk, bool is_read)
1543 return is_read ? blk->on_read_error : blk->on_write_error;
1546 BlockErrorAction blk_get_error_action(BlockBackend *blk, bool is_read,
1547 int error)
1549 BlockdevOnError on_err = blk_get_on_error(blk, is_read);
1551 switch (on_err) {
1552 case BLOCKDEV_ON_ERROR_ENOSPC:
1553 return (error == ENOSPC) ?
1554 BLOCK_ERROR_ACTION_STOP : BLOCK_ERROR_ACTION_REPORT;
1555 case BLOCKDEV_ON_ERROR_STOP:
1556 return BLOCK_ERROR_ACTION_STOP;
1557 case BLOCKDEV_ON_ERROR_REPORT:
1558 return BLOCK_ERROR_ACTION_REPORT;
1559 case BLOCKDEV_ON_ERROR_IGNORE:
1560 return BLOCK_ERROR_ACTION_IGNORE;
1561 case BLOCKDEV_ON_ERROR_AUTO:
1562 default:
1563 abort();
1567 static void send_qmp_error_event(BlockBackend *blk,
1568 BlockErrorAction action,
1569 bool is_read, int error)
1571 IoOperationType optype;
1573 optype = is_read ? IO_OPERATION_TYPE_READ : IO_OPERATION_TYPE_WRITE;
1574 qapi_event_send_block_io_error(blk_name(blk),
1575 bdrv_get_node_name(blk_bs(blk)), optype,
1576 action, blk_iostatus_is_enabled(blk),
1577 error == ENOSPC, strerror(error),
1578 &error_abort);
1581 /* This is done by device models because, while the block layer knows
1582 * about the error, it does not know whether an operation comes from
1583 * the device or the block layer (from a job, for example).
1585 void blk_error_action(BlockBackend *blk, BlockErrorAction action,
1586 bool is_read, int error)
1588 assert(error >= 0);
1590 if (action == BLOCK_ERROR_ACTION_STOP) {
1591 /* First set the iostatus, so that "info block" returns an iostatus
1592 * that matches the events raised so far (an additional error iostatus
1593 * is fine, but not a lost one).
1595 blk_iostatus_set_err(blk, error);
1597 /* Then raise the request to stop the VM and the event.
1598 * qemu_system_vmstop_request_prepare has two effects. First,
1599 * it ensures that the STOP event always comes after the
1600 * BLOCK_IO_ERROR event. Second, it ensures that even if management
1601 * can observe the STOP event and do a "cont" before the STOP
1602 * event is issued, the VM will not stop. In this case, vm_start()
1603 * also ensures that the STOP/RESUME pair of events is emitted.
1605 qemu_system_vmstop_request_prepare();
1606 send_qmp_error_event(blk, action, is_read, error);
1607 qemu_system_vmstop_request(RUN_STATE_IO_ERROR);
1608 } else {
1609 send_qmp_error_event(blk, action, is_read, error);
1613 int blk_is_read_only(BlockBackend *blk)
1615 BlockDriverState *bs = blk_bs(blk);
1617 if (bs) {
1618 return bdrv_is_read_only(bs);
1619 } else {
1620 return blk->root_state.read_only;
1624 int blk_is_sg(BlockBackend *blk)
1626 BlockDriverState *bs = blk_bs(blk);
1628 if (!bs) {
1629 return 0;
1632 return bdrv_is_sg(bs);
1635 int blk_enable_write_cache(BlockBackend *blk)
1637 return blk->enable_write_cache;
1640 void blk_set_enable_write_cache(BlockBackend *blk, bool wce)
1642 blk->enable_write_cache = wce;
1645 void blk_invalidate_cache(BlockBackend *blk, Error **errp)
1647 BlockDriverState *bs = blk_bs(blk);
1649 if (!bs) {
1650 error_setg(errp, "Device '%s' has no medium", blk->name);
1651 return;
1654 bdrv_invalidate_cache(bs, errp);
1657 bool blk_is_inserted(BlockBackend *blk)
1659 BlockDriverState *bs = blk_bs(blk);
1661 return bs && bdrv_is_inserted(bs);
1664 bool blk_is_available(BlockBackend *blk)
1666 return blk_is_inserted(blk) && !blk_dev_is_tray_open(blk);
1669 void blk_lock_medium(BlockBackend *blk, bool locked)
1671 BlockDriverState *bs = blk_bs(blk);
1673 if (bs) {
1674 bdrv_lock_medium(bs, locked);
1678 void blk_eject(BlockBackend *blk, bool eject_flag)
1680 BlockDriverState *bs = blk_bs(blk);
1681 char *id;
1683 /* blk_eject is only called by qdevified devices */
1684 assert(!blk->legacy_dev);
1686 if (bs) {
1687 bdrv_eject(bs, eject_flag);
1690 /* Whether or not we ejected on the backend,
1691 * the frontend experienced a tray event. */
1692 id = blk_get_attached_dev_id(blk);
1693 qapi_event_send_device_tray_moved(blk_name(blk), id,
1694 eject_flag, &error_abort);
1695 g_free(id);
1698 int blk_get_flags(BlockBackend *blk)
1700 BlockDriverState *bs = blk_bs(blk);
1702 if (bs) {
1703 return bdrv_get_flags(bs);
1704 } else {
1705 return blk->root_state.open_flags;
1709 /* Returns the maximum transfer length, in bytes; guaranteed nonzero */
1710 uint32_t blk_get_max_transfer(BlockBackend *blk)
1712 BlockDriverState *bs = blk_bs(blk);
1713 uint32_t max = 0;
1715 if (bs) {
1716 max = bs->bl.max_transfer;
1718 return MIN_NON_ZERO(max, INT_MAX);
1721 int blk_get_max_iov(BlockBackend *blk)
1723 return blk->root->bs->bl.max_iov;
1726 void blk_set_guest_block_size(BlockBackend *blk, int align)
1728 blk->guest_block_size = align;
1731 void *blk_try_blockalign(BlockBackend *blk, size_t size)
1733 return qemu_try_blockalign(blk ? blk_bs(blk) : NULL, size);
1736 void *blk_blockalign(BlockBackend *blk, size_t size)
1738 return qemu_blockalign(blk ? blk_bs(blk) : NULL, size);
1741 bool blk_op_is_blocked(BlockBackend *blk, BlockOpType op, Error **errp)
1743 BlockDriverState *bs = blk_bs(blk);
1745 if (!bs) {
1746 return false;
1749 return bdrv_op_is_blocked(bs, op, errp);
1752 void blk_op_unblock(BlockBackend *blk, BlockOpType op, Error *reason)
1754 BlockDriverState *bs = blk_bs(blk);
1756 if (bs) {
1757 bdrv_op_unblock(bs, op, reason);
1761 void blk_op_block_all(BlockBackend *blk, Error *reason)
1763 BlockDriverState *bs = blk_bs(blk);
1765 if (bs) {
1766 bdrv_op_block_all(bs, reason);
1770 void blk_op_unblock_all(BlockBackend *blk, Error *reason)
1772 BlockDriverState *bs = blk_bs(blk);
1774 if (bs) {
1775 bdrv_op_unblock_all(bs, reason);
1779 AioContext *blk_get_aio_context(BlockBackend *blk)
1781 BlockDriverState *bs = blk_bs(blk);
1783 if (bs) {
1784 return bdrv_get_aio_context(bs);
1785 } else {
1786 return qemu_get_aio_context();
1790 static AioContext *blk_aiocb_get_aio_context(BlockAIOCB *acb)
1792 BlockBackendAIOCB *blk_acb = DO_UPCAST(BlockBackendAIOCB, common, acb);
1793 return blk_get_aio_context(blk_acb->blk);
1796 void blk_set_aio_context(BlockBackend *blk, AioContext *new_context)
1798 BlockDriverState *bs = blk_bs(blk);
1799 ThrottleGroupMember *tgm = &blk->public.throttle_group_member;
1801 if (bs) {
1802 if (tgm->throttle_state) {
1803 bdrv_drained_begin(bs);
1804 throttle_group_detach_aio_context(tgm);
1805 throttle_group_attach_aio_context(tgm, new_context);
1806 bdrv_drained_end(bs);
1808 bdrv_set_aio_context(bs, new_context);
1812 void blk_add_aio_context_notifier(BlockBackend *blk,
1813 void (*attached_aio_context)(AioContext *new_context, void *opaque),
1814 void (*detach_aio_context)(void *opaque), void *opaque)
1816 BlockDriverState *bs = blk_bs(blk);
1818 if (bs) {
1819 bdrv_add_aio_context_notifier(bs, attached_aio_context,
1820 detach_aio_context, opaque);
1824 void blk_remove_aio_context_notifier(BlockBackend *blk,
1825 void (*attached_aio_context)(AioContext *,
1826 void *),
1827 void (*detach_aio_context)(void *),
1828 void *opaque)
1830 BlockDriverState *bs = blk_bs(blk);
1832 if (bs) {
1833 bdrv_remove_aio_context_notifier(bs, attached_aio_context,
1834 detach_aio_context, opaque);
1838 void blk_add_remove_bs_notifier(BlockBackend *blk, Notifier *notify)
1840 notifier_list_add(&blk->remove_bs_notifiers, notify);
1843 void blk_add_insert_bs_notifier(BlockBackend *blk, Notifier *notify)
1845 notifier_list_add(&blk->insert_bs_notifiers, notify);
1848 void blk_io_plug(BlockBackend *blk)
1850 BlockDriverState *bs = blk_bs(blk);
1852 if (bs) {
1853 bdrv_io_plug(bs);
1857 void blk_io_unplug(BlockBackend *blk)
1859 BlockDriverState *bs = blk_bs(blk);
1861 if (bs) {
1862 bdrv_io_unplug(bs);
1866 BlockAcctStats *blk_get_stats(BlockBackend *blk)
1868 return &blk->stats;
1871 void *blk_aio_get(const AIOCBInfo *aiocb_info, BlockBackend *blk,
1872 BlockCompletionFunc *cb, void *opaque)
1874 return qemu_aio_get(aiocb_info, blk_bs(blk), cb, opaque);
1877 int coroutine_fn blk_co_pwrite_zeroes(BlockBackend *blk, int64_t offset,
1878 int bytes, BdrvRequestFlags flags)
1880 return blk_co_pwritev(blk, offset, bytes, NULL,
1881 flags | BDRV_REQ_ZERO_WRITE);
1884 int blk_pwrite_compressed(BlockBackend *blk, int64_t offset, const void *buf,
1885 int count)
1887 return blk_prw(blk, offset, (void *) buf, count, blk_write_entry,
1888 BDRV_REQ_WRITE_COMPRESSED);
1891 int blk_truncate(BlockBackend *blk, int64_t offset, PreallocMode prealloc,
1892 Error **errp)
1894 if (!blk_is_available(blk)) {
1895 error_setg(errp, "No medium inserted");
1896 return -ENOMEDIUM;
1899 return bdrv_truncate(blk->root, offset, prealloc, errp);
1902 static void blk_pdiscard_entry(void *opaque)
1904 BlkRwCo *rwco = opaque;
1905 rwco->ret = blk_co_pdiscard(rwco->blk, rwco->offset, rwco->qiov->size);
1908 int blk_pdiscard(BlockBackend *blk, int64_t offset, int bytes)
1910 return blk_prw(blk, offset, NULL, bytes, blk_pdiscard_entry, 0);
1913 int blk_save_vmstate(BlockBackend *blk, const uint8_t *buf,
1914 int64_t pos, int size)
1916 int ret;
1918 if (!blk_is_available(blk)) {
1919 return -ENOMEDIUM;
1922 ret = bdrv_save_vmstate(blk_bs(blk), buf, pos, size);
1923 if (ret < 0) {
1924 return ret;
1927 if (ret == size && !blk->enable_write_cache) {
1928 ret = bdrv_flush(blk_bs(blk));
1931 return ret < 0 ? ret : size;
1934 int blk_load_vmstate(BlockBackend *blk, uint8_t *buf, int64_t pos, int size)
1936 if (!blk_is_available(blk)) {
1937 return -ENOMEDIUM;
1940 return bdrv_load_vmstate(blk_bs(blk), buf, pos, size);
1943 int blk_probe_blocksizes(BlockBackend *blk, BlockSizes *bsz)
1945 if (!blk_is_available(blk)) {
1946 return -ENOMEDIUM;
1949 return bdrv_probe_blocksizes(blk_bs(blk), bsz);
1952 int blk_probe_geometry(BlockBackend *blk, HDGeometry *geo)
1954 if (!blk_is_available(blk)) {
1955 return -ENOMEDIUM;
1958 return bdrv_probe_geometry(blk_bs(blk), geo);
1962 * Updates the BlockBackendRootState object with data from the currently
1963 * attached BlockDriverState.
1965 void blk_update_root_state(BlockBackend *blk)
1967 assert(blk->root);
1969 blk->root_state.open_flags = blk->root->bs->open_flags;
1970 blk->root_state.read_only = blk->root->bs->read_only;
1971 blk->root_state.detect_zeroes = blk->root->bs->detect_zeroes;
1975 * Returns the detect-zeroes setting to be used for bdrv_open() of a
1976 * BlockDriverState which is supposed to inherit the root state.
1978 bool blk_get_detect_zeroes_from_root_state(BlockBackend *blk)
1980 return blk->root_state.detect_zeroes;
1984 * Returns the flags to be used for bdrv_open() of a BlockDriverState which is
1985 * supposed to inherit the root state.
1987 int blk_get_open_flags_from_root_state(BlockBackend *blk)
1989 int bs_flags;
1991 bs_flags = blk->root_state.read_only ? 0 : BDRV_O_RDWR;
1992 bs_flags |= blk->root_state.open_flags & ~BDRV_O_RDWR;
1994 return bs_flags;
1997 BlockBackendRootState *blk_get_root_state(BlockBackend *blk)
1999 return &blk->root_state;
2002 int blk_commit_all(void)
2004 BlockBackend *blk = NULL;
2006 while ((blk = blk_all_next(blk)) != NULL) {
2007 AioContext *aio_context = blk_get_aio_context(blk);
2009 aio_context_acquire(aio_context);
2010 if (blk_is_inserted(blk) && blk->root->bs->backing) {
2011 int ret = bdrv_commit(blk->root->bs);
2012 if (ret < 0) {
2013 aio_context_release(aio_context);
2014 return ret;
2017 aio_context_release(aio_context);
2019 return 0;
2023 /* throttling disk I/O limits */
2024 void blk_set_io_limits(BlockBackend *blk, ThrottleConfig *cfg)
2026 throttle_group_config(&blk->public.throttle_group_member, cfg);
2029 void blk_io_limits_disable(BlockBackend *blk)
2031 BlockDriverState *bs = blk_bs(blk);
2032 ThrottleGroupMember *tgm = &blk->public.throttle_group_member;
2033 assert(tgm->throttle_state);
2034 if (bs) {
2035 bdrv_drained_begin(bs);
2037 throttle_group_unregister_tgm(tgm);
2038 if (bs) {
2039 bdrv_drained_end(bs);
2043 /* should be called before blk_set_io_limits if a limit is set */
2044 void blk_io_limits_enable(BlockBackend *blk, const char *group)
2046 assert(!blk->public.throttle_group_member.throttle_state);
2047 throttle_group_register_tgm(&blk->public.throttle_group_member,
2048 group, blk_get_aio_context(blk));
2051 void blk_io_limits_update_group(BlockBackend *blk, const char *group)
2053 /* this BB is not part of any group */
2054 if (!blk->public.throttle_group_member.throttle_state) {
2055 return;
2058 /* this BB is a part of the same group than the one we want */
2059 if (!g_strcmp0(throttle_group_get_name(&blk->public.throttle_group_member),
2060 group)) {
2061 return;
2064 /* need to change the group this bs belong to */
2065 blk_io_limits_disable(blk);
2066 blk_io_limits_enable(blk, group);
2069 static void blk_root_drained_begin(BdrvChild *child)
2071 BlockBackend *blk = child->opaque;
2073 if (++blk->quiesce_counter == 1) {
2074 if (blk->dev_ops && blk->dev_ops->drained_begin) {
2075 blk->dev_ops->drained_begin(blk->dev_opaque);
2079 /* Note that blk->root may not be accessible here yet if we are just
2080 * attaching to a BlockDriverState that is drained. Use child instead. */
2082 if (atomic_fetch_inc(&blk->public.throttle_group_member.io_limits_disabled) == 0) {
2083 throttle_group_restart_tgm(&blk->public.throttle_group_member);
2087 static void blk_root_drained_end(BdrvChild *child)
2089 BlockBackend *blk = child->opaque;
2090 assert(blk->quiesce_counter);
2092 assert(blk->public.throttle_group_member.io_limits_disabled);
2093 atomic_dec(&blk->public.throttle_group_member.io_limits_disabled);
2095 if (--blk->quiesce_counter == 0) {
2096 if (blk->dev_ops && blk->dev_ops->drained_end) {
2097 blk->dev_ops->drained_end(blk->dev_opaque);
2102 void blk_register_buf(BlockBackend *blk, void *host, size_t size)
2104 bdrv_register_buf(blk_bs(blk), host, size);
2107 void blk_unregister_buf(BlockBackend *blk, void *host)
2109 bdrv_unregister_buf(blk_bs(blk), host);