xref: /openbmc/qemu/block/block-backend.c (revision 9af2398977a78d37bf184d6ff6bd04c72bfbf006)
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/throttle-groups.h"
18 #include "sysemu/blockdev.h"
19 #include "sysemu/sysemu.h"
20 #include "qapi/error.h"
21 #include "qapi/qapi-events-block.h"
22 #include "qemu/id.h"
23 #include "qemu/option.h"
24 #include "trace.h"
25 #include "migration/misc.h"
26 
27 /* Number of coroutines to reserve per attached device model */
28 #define COROUTINE_POOL_RESERVATION 64
29 
30 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
31 
32 static AioContext *blk_aiocb_get_aio_context(BlockAIOCB *acb);
33 
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;
42 
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;
48 
49     /* the block size for which the guest device expects atomicity */
50     int guest_block_size;
51 
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;
55 
56     bool enable_write_cache;
57 
58     /* I/O stats (display with "info blockstats"). */
59     BlockAcctStats stats;
60 
61     BlockdevOnError on_read_error, on_write_error;
62     bool iostatus_enabled;
63     BlockDeviceIoStatus iostatus;
64 
65     uint64_t perm;
66     uint64_t shared_perm;
67     bool disable_perm;
68 
69     bool allow_write_beyond_eof;
70 
71     NotifierList remove_bs_notifiers, insert_bs_notifiers;
72 
73     int quiesce_counter;
74     VMChangeStateEntry *vmsh;
75     bool force_allow_inactivate;
76 };
77 
78 typedef struct BlockBackendAIOCB {
79     BlockAIOCB common;
80     BlockBackend *blk;
81     int ret;
82 } BlockBackendAIOCB;
83 
84 static const AIOCBInfo block_backend_aiocb_info = {
85     .get_aio_context = blk_aiocb_get_aio_context,
86     .aiocb_size = sizeof(BlockBackendAIOCB),
87 };
88 
89 static void drive_info_del(DriveInfo *dinfo);
90 static BlockBackend *bdrv_first_blk(BlockDriverState *bs);
91 
92 /* All BlockBackends */
93 static QTAILQ_HEAD(, BlockBackend) block_backends =
94     QTAILQ_HEAD_INITIALIZER(block_backends);
95 
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);
100 
101 static void blk_root_inherit_options(int *child_flags, QDict *child_options,
102                                      int parent_flags, QDict *parent_options)
103 {
104     /* We're not supposed to call this function for root nodes */
105     abort();
106 }
107 static void blk_root_drained_begin(BdrvChild *child);
108 static void blk_root_drained_end(BdrvChild *child);
109 
110 static void blk_root_change_media(BdrvChild *child, bool load);
111 static void blk_root_resize(BdrvChild *child);
112 
113 static char *blk_root_get_parent_desc(BdrvChild *child)
114 {
115     BlockBackend *blk = child->opaque;
116     char *dev_id;
117 
118     if (blk->name) {
119         return g_strdup(blk->name);
120     }
121 
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");
129     }
130 }
131 
132 static const char *blk_root_get_name(BdrvChild *child)
133 {
134     return blk_name(child->opaque);
135 }
136 
137 static void blk_vm_state_changed(void *opaque, int running, RunState state)
138 {
139     Error *local_err = NULL;
140     BlockBackend *blk = opaque;
141 
142     if (state == RUN_STATE_INMIGRATE) {
143         return;
144     }
145 
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);
151     }
152 }
153 
154 /*
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).
158  *
159  * If an error is returned, the VM cannot be allowed to be resumed.
160  */
161 static void blk_root_activate(BdrvChild *child, Error **errp)
162 {
163     BlockBackend *blk = child->opaque;
164     Error *local_err = NULL;
165 
166     if (!blk->disable_perm) {
167         return;
168     }
169 
170     blk->disable_perm = false;
171 
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;
177     }
178 
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);
186         }
187         return;
188     }
189 
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;
195     }
196 }
197 
198 void blk_set_force_allow_inactivate(BlockBackend *blk)
199 {
200     blk->force_allow_inactivate = true;
201 }
202 
203 static bool blk_can_inactivate(BlockBackend *blk)
204 {
205     /* If it is a guest device, inactivate is ok. */
206     if (blk->dev || blk_name(blk)[0]) {
207         return true;
208     }
209 
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;
217     }
218 
219     return blk->force_allow_inactivate;
220 }
221 
222 static int blk_root_inactivate(BdrvChild *child)
223 {
224     BlockBackend *blk = child->opaque;
225 
226     if (blk->disable_perm) {
227         return 0;
228     }
229 
230     if (!blk_can_inactivate(blk)) {
231         return -EPERM;
232     }
233 
234     blk->disable_perm = true;
235     if (blk->root) {
236         bdrv_child_try_set_perm(blk->root, 0, BLK_PERM_ALL, &error_abort);
237     }
238 
239     return 0;
240 }
241 
242 static const BdrvChildRole child_root = {
243     .inherit_options    = blk_root_inherit_options,
244 
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,
249 
250     .drained_begin      = blk_root_drained_begin,
251     .drained_end        = blk_root_drained_end,
252 
253     .activate           = blk_root_activate,
254     .inactivate         = blk_root_inactivate,
255 };
256 
257 /*
258  * Create a new BlockBackend with a reference count of one.
259  *
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().
265  *
266  * Return the new BlockBackend on success, null on failure.
267  */
268 BlockBackend *blk_new(uint64_t perm, uint64_t shared_perm)
269 {
270     BlockBackend *blk;
271 
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);
277 
278     block_acct_init(&blk->stats);
279 
280     notifier_list_init(&blk->remove_bs_notifiers);
281     notifier_list_init(&blk->insert_bs_notifiers);
282 
283     QTAILQ_INSERT_TAIL(&block_backends, blk, link);
284     return blk;
285 }
286 
287 /*
288  * Creates a new BlockBackend, opens a new BlockDriverState, and connects both.
289  *
290  * Just as with bdrv_open(), after having called this function the reference to
291  * @options belongs to the block layer (even on failure).
292  *
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.
298  */
299 BlockBackend *blk_new_open(const char *filename, const char *reference,
300                            QDict *options, int flags, Error **errp)
301 {
302     BlockBackend *blk;
303     BlockDriverState *bs;
304     uint64_t perm = 0;
305 
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.
309      *
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;
318         }
319     }
320     if (flags & BDRV_O_RESIZE) {
321         perm |= BLK_PERM_RESIZE;
322     }
323 
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;
329     }
330 
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;
337     }
338 
339     return blk;
340 }
341 
342 static void blk_delete(BlockBackend *blk)
343 {
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);
349     }
350     if (blk->root) {
351         blk_remove_bs(blk);
352     }
353     if (blk->vmsh) {
354         qemu_del_vm_change_state_handler(blk->vmsh);
355         blk->vmsh = NULL;
356     }
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);
363 }
364 
365 static void drive_info_del(DriveInfo *dinfo)
366 {
367     if (!dinfo) {
368         return;
369     }
370     qemu_opts_del(dinfo->opts);
371     g_free(dinfo->serial);
372     g_free(dinfo);
373 }
374 
375 int blk_get_refcnt(BlockBackend *blk)
376 {
377     return blk ? blk->refcnt : 0;
378 }
379 
380 /*
381  * Increment @blk's reference count.
382  * @blk must not be null.
383  */
384 void blk_ref(BlockBackend *blk)
385 {
386     blk->refcnt++;
387 }
388 
389 /*
390  * Decrement @blk's reference count.
391  * If this drops it to zero, destroy @blk.
392  * For convenience, do nothing if @blk is null.
393  */
394 void blk_unref(BlockBackend *blk)
395 {
396     if (blk) {
397         assert(blk->refcnt > 0);
398         if (!--blk->refcnt) {
399             blk_delete(blk);
400         }
401     }
402 }
403 
404 /*
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).
407  */
408 BlockBackend *blk_all_next(BlockBackend *blk)
409 {
410     return blk ? QTAILQ_NEXT(blk, link)
411                : QTAILQ_FIRST(&block_backends);
412 }
413 
414 void blk_remove_all_bs(void)
415 {
416     BlockBackend *blk = NULL;
417 
418     while ((blk = blk_all_next(blk)) != NULL) {
419         AioContext *ctx = blk_get_aio_context(blk);
420 
421         aio_context_acquire(ctx);
422         if (blk->root) {
423             blk_remove_bs(blk);
424         }
425         aio_context_release(ctx);
426     }
427 }
428 
429 /*
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.
433  *
434  * To iterate over all BlockBackends, do
435  * for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
436  *     ...
437  * }
438  */
439 BlockBackend *blk_next(BlockBackend *blk)
440 {
441     return blk ? QTAILQ_NEXT(blk, monitor_link)
442                : QTAILQ_FIRST(&monitor_block_backends);
443 }
444 
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)
448 {
449     BlockDriverState *bs, *old_bs;
450 
451     /* Must be called from the main loop */
452     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
453 
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;
459 
460         old_bs = old_blk ? blk_bs(old_blk) : NULL;
461 
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));
466 
467         if (it->blk) {
468             blk_ref(it->blk);
469         }
470         blk_unref(old_blk);
471 
472         if (bs) {
473             bdrv_ref(bs);
474             bdrv_unref(old_bs);
475             return bs;
476         }
477         it->phase = BDRV_NEXT_MONITOR_OWNED;
478     } else {
479         old_bs = it->bs;
480     }
481 
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));
489 
490     if (bs) {
491         bdrv_ref(bs);
492     }
493     bdrv_unref(old_bs);
494 
495     return bs;
496 }
497 
498 static void bdrv_next_reset(BdrvNextIterator *it)
499 {
500     *it = (BdrvNextIterator) {
501         .phase = BDRV_NEXT_BACKEND_ROOTS,
502     };
503 }
504 
505 BlockDriverState *bdrv_first(BdrvNextIterator *it)
506 {
507     bdrv_next_reset(it);
508     return bdrv_next(it);
509 }
510 
511 /* Must be called when aborting a bdrv_next() iteration before
512  * bdrv_next() returns NULL */
513 void bdrv_next_cleanup(BdrvNextIterator *it)
514 {
515     /* Must be called from the main loop */
516     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
517 
518     if (it->phase == BDRV_NEXT_BACKEND_ROOTS) {
519         if (it->blk) {
520             bdrv_unref(blk_bs(it->blk));
521             blk_unref(it->blk);
522         }
523     } else {
524         bdrv_unref(it->bs);
525     }
526 
527     bdrv_next_reset(it);
528 }
529 
530 /*
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.
534  *
535  * @name must not be null or empty.
536  *
537  * Returns true on success and false on failure. In the latter case, an Error
538  * object is returned through @errp.
539  */
540 bool monitor_add_blk(BlockBackend *blk, const char *name, Error **errp)
541 {
542     assert(!blk->name);
543     assert(name && name[0]);
544 
545     if (!id_wellformed(name)) {
546         error_setg(errp, "Invalid device name");
547         return false;
548     }
549     if (blk_by_name(name)) {
550         error_setg(errp, "Device with id '%s' already exists", name);
551         return false;
552     }
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;
558     }
559 
560     blk->name = g_strdup(name);
561     QTAILQ_INSERT_TAIL(&monitor_block_backends, blk, monitor_link);
562     return true;
563 }
564 
565 /*
566  * Remove a BlockBackend from the list of backends referenced by the monitor.
567  * Strictly for use by blockdev.c.
568  */
569 void monitor_remove_blk(BlockBackend *blk)
570 {
571     if (!blk->name) {
572         return;
573     }
574 
575     QTAILQ_REMOVE(&monitor_block_backends, blk, monitor_link);
576     g_free(blk->name);
577     blk->name = NULL;
578 }
579 
580 /*
581  * Return @blk's name, a non-null string.
582  * Returns an empty string iff @blk is not referenced by the monitor.
583  */
584 const char *blk_name(const BlockBackend *blk)
585 {
586     return blk->name ?: "";
587 }
588 
589 /*
590  * Return the BlockBackend with name @name if it exists, else null.
591  * @name must not be null.
592  */
593 BlockBackend *blk_by_name(const char *name)
594 {
595     BlockBackend *blk = NULL;
596 
597     assert(name);
598     while ((blk = blk_next(blk)) != NULL) {
599         if (!strcmp(name, blk->name)) {
600             return blk;
601         }
602     }
603     return NULL;
604 }
605 
606 /*
607  * Return the BlockDriverState attached to @blk if any, else null.
608  */
609 BlockDriverState *blk_bs(BlockBackend *blk)
610 {
611     return blk->root ? blk->root->bs : NULL;
612 }
613 
614 static BlockBackend *bdrv_first_blk(BlockDriverState *bs)
615 {
616     BdrvChild *child;
617     QLIST_FOREACH(child, &bs->parents, next_parent) {
618         if (child->role == &child_root) {
619             return child->opaque;
620         }
621     }
622 
623     return NULL;
624 }
625 
626 /*
627  * Returns true if @bs has an associated BlockBackend.
628  */
629 bool bdrv_has_blk(BlockDriverState *bs)
630 {
631     return bdrv_first_blk(bs) != NULL;
632 }
633 
634 /*
635  * Returns true if @bs has only BlockBackends as parents.
636  */
637 bool bdrv_is_root_node(BlockDriverState *bs)
638 {
639     BdrvChild *c;
640 
641     QLIST_FOREACH(c, &bs->parents, next_parent) {
642         if (c->role != &child_root) {
643             return false;
644         }
645     }
646 
647     return true;
648 }
649 
650 /*
651  * Return @blk's DriveInfo if any, else null.
652  */
653 DriveInfo *blk_legacy_dinfo(BlockBackend *blk)
654 {
655     return blk->legacy_dinfo;
656 }
657 
658 /*
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.
662  */
663 DriveInfo *blk_set_legacy_dinfo(BlockBackend *blk, DriveInfo *dinfo)
664 {
665     assert(!blk->legacy_dinfo);
666     return blk->legacy_dinfo = dinfo;
667 }
668 
669 /*
670  * Return the BlockBackend with DriveInfo @dinfo.
671  * It must exist.
672  */
673 BlockBackend *blk_by_legacy_dinfo(DriveInfo *dinfo)
674 {
675     BlockBackend *blk = NULL;
676 
677     while ((blk = blk_next(blk)) != NULL) {
678         if (blk->legacy_dinfo == dinfo) {
679             return blk;
680         }
681     }
682     abort();
683 }
684 
685 /*
686  * Returns a pointer to the publicly accessible fields of @blk.
687  */
688 BlockBackendPublic *blk_get_public(BlockBackend *blk)
689 {
690     return &blk->public;
691 }
692 
693 /*
694  * Returns a BlockBackend given the associated @public fields.
695  */
696 BlockBackend *blk_by_public(BlockBackendPublic *public)
697 {
698     return container_of(public, BlockBackend, public);
699 }
700 
701 /*
702  * Disassociates the currently associated BlockDriverState from @blk.
703  */
704 void blk_remove_bs(BlockBackend *blk)
705 {
706     ThrottleGroupMember *tgm = &blk->public.throttle_group_member;
707     BlockDriverState *bs;
708 
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);
716     }
717 
718     blk_update_root_state(blk);
719 
720     bdrv_root_unref_child(blk->root);
721     blk->root = NULL;
722 }
723 
724 /*
725  * Associates a new BlockDriverState with @blk.
726  */
727 int blk_insert_bs(BlockBackend *blk, BlockDriverState *bs, Error **errp)
728 {
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;
734     }
735     bdrv_ref(bs);
736 
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));
741     }
742 
743     return 0;
744 }
745 
746 /*
747  * Sets the permission bitmasks that the user of the BlockBackend needs.
748  */
749 int blk_set_perm(BlockBackend *blk, uint64_t perm, uint64_t shared_perm,
750                  Error **errp)
751 {
752     int ret;
753 
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;
758         }
759     }
760 
761     blk->perm = perm;
762     blk->shared_perm = shared_perm;
763 
764     return 0;
765 }
766 
767 void blk_get_perm(BlockBackend *blk, uint64_t *perm, uint64_t *shared_perm)
768 {
769     *perm = blk->perm;
770     *shared_perm = blk->shared_perm;
771 }
772 
773 static int blk_do_attach_dev(BlockBackend *blk, void *dev)
774 {
775     if (blk->dev) {
776         return -EBUSY;
777     }
778 
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;
784     }
785 
786     blk_ref(blk);
787     blk->dev = dev;
788     blk->legacy_dev = false;
789     blk_iostatus_reset(blk);
790 
791     return 0;
792 }
793 
794 /*
795  * Attach device model @dev to @blk.
796  * Return 0 on success, -EBUSY when a device model is attached already.
797  */
798 int blk_attach_dev(BlockBackend *blk, DeviceState *dev)
799 {
800     return blk_do_attach_dev(blk, dev);
801 }
802 
803 /*
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
807  */
808 void blk_attach_dev_legacy(BlockBackend *blk, void *dev)
809 {
810     if (blk_do_attach_dev(blk, dev) < 0) {
811         abort();
812     }
813     blk->legacy_dev = true;
814 }
815 
816 /*
817  * Detach device model @dev from @blk.
818  * @dev must be currently attached to @blk.
819  */
820 void blk_detach_dev(BlockBackend *blk, void *dev)
821 /* TODO change to DeviceState *dev when all users are qdevified */
822 {
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);
830 }
831 
832 /*
833  * Return the device model attached to @blk if any, else null.
834  */
835 void *blk_get_attached_dev(BlockBackend *blk)
836 /* TODO change to return DeviceState * when all users are qdevified */
837 {
838     return blk->dev;
839 }
840 
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)
844 {
845     DeviceState *dev;
846 
847     assert(!blk->legacy_dev);
848     dev = blk->dev;
849 
850     if (!dev) {
851         return g_strdup("");
852     } else if (dev->id) {
853         return g_strdup(dev->id);
854     }
855     return object_get_canonical_path(OBJECT(dev));
856 }
857 
858 /*
859  * Return the BlockBackend which has the device model @dev attached if it
860  * exists, else null.
861  *
862  * @dev must not be null.
863  */
864 BlockBackend *blk_by_dev(void *dev)
865 {
866     BlockBackend *blk = NULL;
867 
868     assert(dev != NULL);
869     while ((blk = blk_all_next(blk)) != NULL) {
870         if (blk->dev == dev) {
871             return blk;
872         }
873     }
874     return NULL;
875 }
876 
877 /*
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.
881  */
882 void blk_set_dev_ops(BlockBackend *blk, const BlockDevOps *ops,
883                      void *opaque)
884 {
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);
889 
890     blk->dev_ops = ops;
891     blk->dev_opaque = opaque;
892 
893     /* Are we currently quiesced? Should we enforce this right now? */
894     if (blk->quiesce_counter && ops->drained_begin) {
895         ops->drained_begin(opaque);
896     }
897 }
898 
899 /*
900  * Notify @blk's attached device model of media change.
901  *
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.
904  *
905  * If @load is false, notify of media eject. This can never fail.
906  *
907  * Also send DEVICE_TRAY_MOVED events as appropriate.
908  */
909 void blk_dev_change_media_cb(BlockBackend *blk, bool load, Error **errp)
910 {
911     if (blk->dev_ops && blk->dev_ops->change_media_cb) {
912         bool tray_was_open, tray_is_open;
913         Error *local_err = NULL;
914 
915         assert(!blk->legacy_dev);
916 
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;
923         }
924         tray_is_open = blk_dev_is_tray_open(blk);
925 
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);
931         }
932     }
933 }
934 
935 static void blk_root_change_media(BdrvChild *child, bool load)
936 {
937     blk_dev_change_media_cb(child->opaque, load, NULL);
938 }
939 
940 /*
941  * Does @blk's attached device model have removable media?
942  * %true if no device model is attached.
943  */
944 bool blk_dev_has_removable_media(BlockBackend *blk)
945 {
946     return !blk->dev || (blk->dev_ops && blk->dev_ops->change_media_cb);
947 }
948 
949 /*
950  * Does @blk's attached device model have a tray?
951  */
952 bool blk_dev_has_tray(BlockBackend *blk)
953 {
954     return blk->dev_ops && blk->dev_ops->is_tray_open;
955 }
956 
957 /*
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.
960  */
961 void blk_dev_eject_request(BlockBackend *blk, bool force)
962 {
963     if (blk->dev_ops && blk->dev_ops->eject_request_cb) {
964         blk->dev_ops->eject_request_cb(blk->dev_opaque, force);
965     }
966 }
967 
968 /*
969  * Does @blk's attached device model have a tray, and is it open?
970  */
971 bool blk_dev_is_tray_open(BlockBackend *blk)
972 {
973     if (blk_dev_has_tray(blk)) {
974         return blk->dev_ops->is_tray_open(blk->dev_opaque);
975     }
976     return false;
977 }
978 
979 /*
980  * Does @blk's attached device model have the medium locked?
981  * %false if the device model has no such lock.
982  */
983 bool blk_dev_is_medium_locked(BlockBackend *blk)
984 {
985     if (blk->dev_ops && blk->dev_ops->is_medium_locked) {
986         return blk->dev_ops->is_medium_locked(blk->dev_opaque);
987     }
988     return false;
989 }
990 
991 /*
992  * Notify @blk's attached device model of a backend size change.
993  */
994 static void blk_root_resize(BdrvChild *child)
995 {
996     BlockBackend *blk = child->opaque;
997 
998     if (blk->dev_ops && blk->dev_ops->resize_cb) {
999         blk->dev_ops->resize_cb(blk->dev_opaque);
1000     }
1001 }
1002 
1003 void blk_iostatus_enable(BlockBackend *blk)
1004 {
1005     blk->iostatus_enabled = true;
1006     blk->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
1007 }
1008 
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)
1012 {
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));
1017 }
1018 
1019 BlockDeviceIoStatus blk_iostatus(const BlockBackend *blk)
1020 {
1021     return blk->iostatus;
1022 }
1023 
1024 void blk_iostatus_disable(BlockBackend *blk)
1025 {
1026     blk->iostatus_enabled = false;
1027 }
1028 
1029 void blk_iostatus_reset(BlockBackend *blk)
1030 {
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);
1036         }
1037     }
1038 }
1039 
1040 void blk_iostatus_set_err(BlockBackend *blk, int error)
1041 {
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;
1046     }
1047 }
1048 
1049 void blk_set_allow_write_beyond_eof(BlockBackend *blk, bool allow)
1050 {
1051     blk->allow_write_beyond_eof = allow;
1052 }
1053 
1054 static int blk_check_byte_request(BlockBackend *blk, int64_t offset,
1055                                   size_t size)
1056 {
1057     int64_t len;
1058 
1059     if (size > INT_MAX) {
1060         return -EIO;
1061     }
1062 
1063     if (!blk_is_available(blk)) {
1064         return -ENOMEDIUM;
1065     }
1066 
1067     if (offset < 0) {
1068         return -EIO;
1069     }
1070 
1071     if (!blk->allow_write_beyond_eof) {
1072         len = blk_getlength(blk);
1073         if (len < 0) {
1074             return len;
1075         }
1076 
1077         if (offset > len || len - offset < size) {
1078             return -EIO;
1079         }
1080     }
1081 
1082     return 0;
1083 }
1084 
1085 int coroutine_fn blk_co_preadv(BlockBackend *blk, int64_t offset,
1086                                unsigned int bytes, QEMUIOVector *qiov,
1087                                BdrvRequestFlags flags)
1088 {
1089     int ret;
1090     BlockDriverState *bs = blk_bs(blk);
1091 
1092     trace_blk_co_preadv(blk, bs, offset, bytes, flags);
1093 
1094     ret = blk_check_byte_request(blk, offset, bytes);
1095     if (ret < 0) {
1096         return ret;
1097     }
1098 
1099     bdrv_inc_in_flight(bs);
1100 
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);
1105     }
1106 
1107     ret = bdrv_co_preadv(blk->root, offset, bytes, qiov, flags);
1108     bdrv_dec_in_flight(bs);
1109     return ret;
1110 }
1111 
1112 int coroutine_fn blk_co_pwritev(BlockBackend *blk, int64_t offset,
1113                                 unsigned int bytes, QEMUIOVector *qiov,
1114                                 BdrvRequestFlags flags)
1115 {
1116     int ret;
1117     BlockDriverState *bs = blk_bs(blk);
1118 
1119     trace_blk_co_pwritev(blk, bs, offset, bytes, flags);
1120 
1121     ret = blk_check_byte_request(blk, offset, bytes);
1122     if (ret < 0) {
1123         return ret;
1124     }
1125 
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);
1131     }
1132 
1133     if (!blk->enable_write_cache) {
1134         flags |= BDRV_REQ_FUA;
1135     }
1136 
1137     ret = bdrv_co_pwritev(blk->root, offset, bytes, qiov, flags);
1138     bdrv_dec_in_flight(bs);
1139     return ret;
1140 }
1141 
1142 typedef struct BlkRwCo {
1143     BlockBackend *blk;
1144     int64_t offset;
1145     QEMUIOVector *qiov;
1146     int ret;
1147     BdrvRequestFlags flags;
1148 } BlkRwCo;
1149 
1150 static void blk_read_entry(void *opaque)
1151 {
1152     BlkRwCo *rwco = opaque;
1153 
1154     rwco->ret = blk_co_preadv(rwco->blk, rwco->offset, rwco->qiov->size,
1155                               rwco->qiov, rwco->flags);
1156 }
1157 
1158 static void blk_write_entry(void *opaque)
1159 {
1160     BlkRwCo *rwco = opaque;
1161 
1162     rwco->ret = blk_co_pwritev(rwco->blk, rwco->offset, rwco->qiov->size,
1163                                rwco->qiov, rwco->flags);
1164 }
1165 
1166 static int blk_prw(BlockBackend *blk, int64_t offset, uint8_t *buf,
1167                    int64_t bytes, CoroutineEntry co_entry,
1168                    BdrvRequestFlags flags)
1169 {
1170     QEMUIOVector qiov;
1171     struct iovec iov;
1172     BlkRwCo rwco;
1173 
1174     iov = (struct iovec) {
1175         .iov_base = buf,
1176         .iov_len = bytes,
1177     };
1178     qemu_iovec_init_external(&qiov, &iov, 1);
1179 
1180     rwco = (BlkRwCo) {
1181         .blk    = blk,
1182         .offset = offset,
1183         .qiov   = &qiov,
1184         .flags  = flags,
1185         .ret    = NOT_DONE,
1186     };
1187 
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);
1195     }
1196 
1197     return rwco.ret;
1198 }
1199 
1200 int blk_pread_unthrottled(BlockBackend *blk, int64_t offset, uint8_t *buf,
1201                           int count)
1202 {
1203     int ret;
1204 
1205     ret = blk_check_byte_request(blk, offset, count);
1206     if (ret < 0) {
1207         return ret;
1208     }
1209 
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;
1214 }
1215 
1216 int blk_pwrite_zeroes(BlockBackend *blk, int64_t offset,
1217                       int bytes, BdrvRequestFlags flags)
1218 {
1219     return blk_prw(blk, offset, NULL, bytes, blk_write_entry,
1220                    flags | BDRV_REQ_ZERO_WRITE);
1221 }
1222 
1223 int blk_make_zero(BlockBackend *blk, BdrvRequestFlags flags)
1224 {
1225     return bdrv_make_zero(blk->root, flags);
1226 }
1227 
1228 static void error_callback_bh(void *opaque)
1229 {
1230     struct BlockBackendAIOCB *acb = opaque;
1231 
1232     bdrv_dec_in_flight(acb->common.bs);
1233     acb->common.cb(acb->common.opaque, acb->ret);
1234     qemu_aio_unref(acb);
1235 }
1236 
1237 BlockAIOCB *blk_abort_aio_request(BlockBackend *blk,
1238                                   BlockCompletionFunc *cb,
1239                                   void *opaque, int ret)
1240 {
1241     struct BlockBackendAIOCB *acb;
1242 
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;
1247 
1248     aio_bh_schedule_oneshot(blk_get_aio_context(blk), error_callback_bh, acb);
1249     return &acb->common;
1250 }
1251 
1252 typedef struct BlkAioEmAIOCB {
1253     BlockAIOCB common;
1254     BlkRwCo rwco;
1255     int bytes;
1256     bool has_returned;
1257 } BlkAioEmAIOCB;
1258 
1259 static const AIOCBInfo blk_aio_em_aiocb_info = {
1260     .aiocb_size         = sizeof(BlkAioEmAIOCB),
1261 };
1262 
1263 static void blk_aio_complete(BlkAioEmAIOCB *acb)
1264 {
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);
1269     }
1270 }
1271 
1272 static void blk_aio_complete_bh(void *opaque)
1273 {
1274     BlkAioEmAIOCB *acb = opaque;
1275     assert(acb->has_returned);
1276     blk_aio_complete(acb);
1277 }
1278 
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)
1283 {
1284     BlkAioEmAIOCB *acb;
1285     Coroutine *co;
1286 
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,
1295     };
1296     acb->bytes = bytes;
1297     acb->has_returned = false;
1298 
1299     co = qemu_coroutine_create(co_entry, acb);
1300     bdrv_coroutine_enter(blk_bs(blk), co);
1301 
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);
1306     }
1307 
1308     return &acb->common;
1309 }
1310 
1311 static void blk_aio_read_entry(void *opaque)
1312 {
1313     BlkAioEmAIOCB *acb = opaque;
1314     BlkRwCo *rwco = &acb->rwco;
1315 
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);
1320 }
1321 
1322 static void blk_aio_write_entry(void *opaque)
1323 {
1324     BlkAioEmAIOCB *acb = opaque;
1325     BlkRwCo *rwco = &acb->rwco;
1326 
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);
1331 }
1332 
1333 BlockAIOCB *blk_aio_pwrite_zeroes(BlockBackend *blk, int64_t offset,
1334                                   int count, BdrvRequestFlags flags,
1335                                   BlockCompletionFunc *cb, void *opaque)
1336 {
1337     return blk_aio_prwv(blk, offset, count, NULL, blk_aio_write_entry,
1338                         flags | BDRV_REQ_ZERO_WRITE, cb, opaque);
1339 }
1340 
1341 int blk_pread(BlockBackend *blk, int64_t offset, void *buf, int count)
1342 {
1343     int ret = blk_prw(blk, offset, buf, count, blk_read_entry, 0);
1344     if (ret < 0) {
1345         return ret;
1346     }
1347     return count;
1348 }
1349 
1350 int blk_pwrite(BlockBackend *blk, int64_t offset, const void *buf, int count,
1351                BdrvRequestFlags flags)
1352 {
1353     int ret = blk_prw(blk, offset, (void *) buf, count, blk_write_entry,
1354                       flags);
1355     if (ret < 0) {
1356         return ret;
1357     }
1358     return count;
1359 }
1360 
1361 int64_t blk_getlength(BlockBackend *blk)
1362 {
1363     if (!blk_is_available(blk)) {
1364         return -ENOMEDIUM;
1365     }
1366 
1367     return bdrv_getlength(blk_bs(blk));
1368 }
1369 
1370 void blk_get_geometry(BlockBackend *blk, uint64_t *nb_sectors_ptr)
1371 {
1372     if (!blk_bs(blk)) {
1373         *nb_sectors_ptr = 0;
1374     } else {
1375         bdrv_get_geometry(blk_bs(blk), nb_sectors_ptr);
1376     }
1377 }
1378 
1379 int64_t blk_nb_sectors(BlockBackend *blk)
1380 {
1381     if (!blk_is_available(blk)) {
1382         return -ENOMEDIUM;
1383     }
1384 
1385     return bdrv_nb_sectors(blk_bs(blk));
1386 }
1387 
1388 BlockAIOCB *blk_aio_preadv(BlockBackend *blk, int64_t offset,
1389                            QEMUIOVector *qiov, BdrvRequestFlags flags,
1390                            BlockCompletionFunc *cb, void *opaque)
1391 {
1392     return blk_aio_prwv(blk, offset, qiov->size, qiov,
1393                         blk_aio_read_entry, flags, cb, opaque);
1394 }
1395 
1396 BlockAIOCB *blk_aio_pwritev(BlockBackend *blk, int64_t offset,
1397                             QEMUIOVector *qiov, BdrvRequestFlags flags,
1398                             BlockCompletionFunc *cb, void *opaque)
1399 {
1400     return blk_aio_prwv(blk, offset, qiov->size, qiov,
1401                         blk_aio_write_entry, flags, cb, opaque);
1402 }
1403 
1404 static void blk_aio_flush_entry(void *opaque)
1405 {
1406     BlkAioEmAIOCB *acb = opaque;
1407     BlkRwCo *rwco = &acb->rwco;
1408 
1409     rwco->ret = blk_co_flush(rwco->blk);
1410     blk_aio_complete(acb);
1411 }
1412 
1413 BlockAIOCB *blk_aio_flush(BlockBackend *blk,
1414                           BlockCompletionFunc *cb, void *opaque)
1415 {
1416     return blk_aio_prwv(blk, 0, 0, NULL, blk_aio_flush_entry, 0, cb, opaque);
1417 }
1418 
1419 static void blk_aio_pdiscard_entry(void *opaque)
1420 {
1421     BlkAioEmAIOCB *acb = opaque;
1422     BlkRwCo *rwco = &acb->rwco;
1423 
1424     rwco->ret = blk_co_pdiscard(rwco->blk, rwco->offset, acb->bytes);
1425     blk_aio_complete(acb);
1426 }
1427 
1428 BlockAIOCB *blk_aio_pdiscard(BlockBackend *blk,
1429                              int64_t offset, int bytes,
1430                              BlockCompletionFunc *cb, void *opaque)
1431 {
1432     return blk_aio_prwv(blk, offset, bytes, NULL, blk_aio_pdiscard_entry, 0,
1433                         cb, opaque);
1434 }
1435 
1436 void blk_aio_cancel(BlockAIOCB *acb)
1437 {
1438     bdrv_aio_cancel(acb);
1439 }
1440 
1441 void blk_aio_cancel_async(BlockAIOCB *acb)
1442 {
1443     bdrv_aio_cancel_async(acb);
1444 }
1445 
1446 int blk_co_ioctl(BlockBackend *blk, unsigned long int req, void *buf)
1447 {
1448     if (!blk_is_available(blk)) {
1449         return -ENOMEDIUM;
1450     }
1451 
1452     return bdrv_co_ioctl(blk_bs(blk), req, buf);
1453 }
1454 
1455 static void blk_ioctl_entry(void *opaque)
1456 {
1457     BlkRwCo *rwco = opaque;
1458     rwco->ret = blk_co_ioctl(rwco->blk, rwco->offset,
1459                              rwco->qiov->iov[0].iov_base);
1460 }
1461 
1462 int blk_ioctl(BlockBackend *blk, unsigned long int req, void *buf)
1463 {
1464     return blk_prw(blk, req, buf, 0, blk_ioctl_entry, 0);
1465 }
1466 
1467 static void blk_aio_ioctl_entry(void *opaque)
1468 {
1469     BlkAioEmAIOCB *acb = opaque;
1470     BlkRwCo *rwco = &acb->rwco;
1471 
1472     rwco->ret = blk_co_ioctl(rwco->blk, rwco->offset,
1473                              rwco->qiov->iov[0].iov_base);
1474     blk_aio_complete(acb);
1475 }
1476 
1477 BlockAIOCB *blk_aio_ioctl(BlockBackend *blk, unsigned long int req, void *buf,
1478                           BlockCompletionFunc *cb, void *opaque)
1479 {
1480     QEMUIOVector qiov;
1481     struct iovec iov;
1482 
1483     iov = (struct iovec) {
1484         .iov_base = buf,
1485         .iov_len = 0,
1486     };
1487     qemu_iovec_init_external(&qiov, &iov, 1);
1488 
1489     return blk_aio_prwv(blk, req, 0, &qiov, blk_aio_ioctl_entry, 0, cb, opaque);
1490 }
1491 
1492 int blk_co_pdiscard(BlockBackend *blk, int64_t offset, int bytes)
1493 {
1494     int ret = blk_check_byte_request(blk, offset, bytes);
1495     if (ret < 0) {
1496         return ret;
1497     }
1498 
1499     return bdrv_co_pdiscard(blk_bs(blk), offset, bytes);
1500 }
1501 
1502 int blk_co_flush(BlockBackend *blk)
1503 {
1504     if (!blk_is_available(blk)) {
1505         return -ENOMEDIUM;
1506     }
1507 
1508     return bdrv_co_flush(blk_bs(blk));
1509 }
1510 
1511 static void blk_flush_entry(void *opaque)
1512 {
1513     BlkRwCo *rwco = opaque;
1514     rwco->ret = blk_co_flush(rwco->blk);
1515 }
1516 
1517 int blk_flush(BlockBackend *blk)
1518 {
1519     return blk_prw(blk, 0, NULL, 0, blk_flush_entry, 0);
1520 }
1521 
1522 void blk_drain(BlockBackend *blk)
1523 {
1524     if (blk_bs(blk)) {
1525         bdrv_drain(blk_bs(blk));
1526     }
1527 }
1528 
1529 void blk_drain_all(void)
1530 {
1531     bdrv_drain_all();
1532 }
1533 
1534 void blk_set_on_error(BlockBackend *blk, BlockdevOnError on_read_error,
1535                       BlockdevOnError on_write_error)
1536 {
1537     blk->on_read_error = on_read_error;
1538     blk->on_write_error = on_write_error;
1539 }
1540 
1541 BlockdevOnError blk_get_on_error(BlockBackend *blk, bool is_read)
1542 {
1543     return is_read ? blk->on_read_error : blk->on_write_error;
1544 }
1545 
1546 BlockErrorAction blk_get_error_action(BlockBackend *blk, bool is_read,
1547                                       int error)
1548 {
1549     BlockdevOnError on_err = blk_get_on_error(blk, is_read);
1550 
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();
1564     }
1565 }
1566 
1567 static void send_qmp_error_event(BlockBackend *blk,
1568                                  BlockErrorAction action,
1569                                  bool is_read, int error)
1570 {
1571     IoOperationType optype;
1572 
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);
1579 }
1580 
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).
1584  */
1585 void blk_error_action(BlockBackend *blk, BlockErrorAction action,
1586                       bool is_read, int error)
1587 {
1588     assert(error >= 0);
1589 
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).
1594          */
1595         blk_iostatus_set_err(blk, error);
1596 
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.
1604          */
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);
1610     }
1611 }
1612 
1613 int blk_is_read_only(BlockBackend *blk)
1614 {
1615     BlockDriverState *bs = blk_bs(blk);
1616 
1617     if (bs) {
1618         return bdrv_is_read_only(bs);
1619     } else {
1620         return blk->root_state.read_only;
1621     }
1622 }
1623 
1624 int blk_is_sg(BlockBackend *blk)
1625 {
1626     BlockDriverState *bs = blk_bs(blk);
1627 
1628     if (!bs) {
1629         return 0;
1630     }
1631 
1632     return bdrv_is_sg(bs);
1633 }
1634 
1635 int blk_enable_write_cache(BlockBackend *blk)
1636 {
1637     return blk->enable_write_cache;
1638 }
1639 
1640 void blk_set_enable_write_cache(BlockBackend *blk, bool wce)
1641 {
1642     blk->enable_write_cache = wce;
1643 }
1644 
1645 void blk_invalidate_cache(BlockBackend *blk, Error **errp)
1646 {
1647     BlockDriverState *bs = blk_bs(blk);
1648 
1649     if (!bs) {
1650         error_setg(errp, "Device '%s' has no medium", blk->name);
1651         return;
1652     }
1653 
1654     bdrv_invalidate_cache(bs, errp);
1655 }
1656 
1657 bool blk_is_inserted(BlockBackend *blk)
1658 {
1659     BlockDriverState *bs = blk_bs(blk);
1660 
1661     return bs && bdrv_is_inserted(bs);
1662 }
1663 
1664 bool blk_is_available(BlockBackend *blk)
1665 {
1666     return blk_is_inserted(blk) && !blk_dev_is_tray_open(blk);
1667 }
1668 
1669 void blk_lock_medium(BlockBackend *blk, bool locked)
1670 {
1671     BlockDriverState *bs = blk_bs(blk);
1672 
1673     if (bs) {
1674         bdrv_lock_medium(bs, locked);
1675     }
1676 }
1677 
1678 void blk_eject(BlockBackend *blk, bool eject_flag)
1679 {
1680     BlockDriverState *bs = blk_bs(blk);
1681     char *id;
1682 
1683     /* blk_eject is only called by qdevified devices */
1684     assert(!blk->legacy_dev);
1685 
1686     if (bs) {
1687         bdrv_eject(bs, eject_flag);
1688     }
1689 
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);
1696 }
1697 
1698 int blk_get_flags(BlockBackend *blk)
1699 {
1700     BlockDriverState *bs = blk_bs(blk);
1701 
1702     if (bs) {
1703         return bdrv_get_flags(bs);
1704     } else {
1705         return blk->root_state.open_flags;
1706     }
1707 }
1708 
1709 /* Returns the maximum transfer length, in bytes; guaranteed nonzero */
1710 uint32_t blk_get_max_transfer(BlockBackend *blk)
1711 {
1712     BlockDriverState *bs = blk_bs(blk);
1713     uint32_t max = 0;
1714 
1715     if (bs) {
1716         max = bs->bl.max_transfer;
1717     }
1718     return MIN_NON_ZERO(max, INT_MAX);
1719 }
1720 
1721 int blk_get_max_iov(BlockBackend *blk)
1722 {
1723     return blk->root->bs->bl.max_iov;
1724 }
1725 
1726 void blk_set_guest_block_size(BlockBackend *blk, int align)
1727 {
1728     blk->guest_block_size = align;
1729 }
1730 
1731 void *blk_try_blockalign(BlockBackend *blk, size_t size)
1732 {
1733     return qemu_try_blockalign(blk ? blk_bs(blk) : NULL, size);
1734 }
1735 
1736 void *blk_blockalign(BlockBackend *blk, size_t size)
1737 {
1738     return qemu_blockalign(blk ? blk_bs(blk) : NULL, size);
1739 }
1740 
1741 bool blk_op_is_blocked(BlockBackend *blk, BlockOpType op, Error **errp)
1742 {
1743     BlockDriverState *bs = blk_bs(blk);
1744 
1745     if (!bs) {
1746         return false;
1747     }
1748 
1749     return bdrv_op_is_blocked(bs, op, errp);
1750 }
1751 
1752 void blk_op_unblock(BlockBackend *blk, BlockOpType op, Error *reason)
1753 {
1754     BlockDriverState *bs = blk_bs(blk);
1755 
1756     if (bs) {
1757         bdrv_op_unblock(bs, op, reason);
1758     }
1759 }
1760 
1761 void blk_op_block_all(BlockBackend *blk, Error *reason)
1762 {
1763     BlockDriverState *bs = blk_bs(blk);
1764 
1765     if (bs) {
1766         bdrv_op_block_all(bs, reason);
1767     }
1768 }
1769 
1770 void blk_op_unblock_all(BlockBackend *blk, Error *reason)
1771 {
1772     BlockDriverState *bs = blk_bs(blk);
1773 
1774     if (bs) {
1775         bdrv_op_unblock_all(bs, reason);
1776     }
1777 }
1778 
1779 AioContext *blk_get_aio_context(BlockBackend *blk)
1780 {
1781     BlockDriverState *bs = blk_bs(blk);
1782 
1783     if (bs) {
1784         return bdrv_get_aio_context(bs);
1785     } else {
1786         return qemu_get_aio_context();
1787     }
1788 }
1789 
1790 static AioContext *blk_aiocb_get_aio_context(BlockAIOCB *acb)
1791 {
1792     BlockBackendAIOCB *blk_acb = DO_UPCAST(BlockBackendAIOCB, common, acb);
1793     return blk_get_aio_context(blk_acb->blk);
1794 }
1795 
1796 void blk_set_aio_context(BlockBackend *blk, AioContext *new_context)
1797 {
1798     BlockDriverState *bs = blk_bs(blk);
1799     ThrottleGroupMember *tgm = &blk->public.throttle_group_member;
1800 
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);
1807         }
1808         bdrv_set_aio_context(bs, new_context);
1809     }
1810 }
1811 
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)
1815 {
1816     BlockDriverState *bs = blk_bs(blk);
1817 
1818     if (bs) {
1819         bdrv_add_aio_context_notifier(bs, attached_aio_context,
1820                                       detach_aio_context, opaque);
1821     }
1822 }
1823 
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)
1829 {
1830     BlockDriverState *bs = blk_bs(blk);
1831 
1832     if (bs) {
1833         bdrv_remove_aio_context_notifier(bs, attached_aio_context,
1834                                          detach_aio_context, opaque);
1835     }
1836 }
1837 
1838 void blk_add_remove_bs_notifier(BlockBackend *blk, Notifier *notify)
1839 {
1840     notifier_list_add(&blk->remove_bs_notifiers, notify);
1841 }
1842 
1843 void blk_add_insert_bs_notifier(BlockBackend *blk, Notifier *notify)
1844 {
1845     notifier_list_add(&blk->insert_bs_notifiers, notify);
1846 }
1847 
1848 void blk_io_plug(BlockBackend *blk)
1849 {
1850     BlockDriverState *bs = blk_bs(blk);
1851 
1852     if (bs) {
1853         bdrv_io_plug(bs);
1854     }
1855 }
1856 
1857 void blk_io_unplug(BlockBackend *blk)
1858 {
1859     BlockDriverState *bs = blk_bs(blk);
1860 
1861     if (bs) {
1862         bdrv_io_unplug(bs);
1863     }
1864 }
1865 
1866 BlockAcctStats *blk_get_stats(BlockBackend *blk)
1867 {
1868     return &blk->stats;
1869 }
1870 
1871 void *blk_aio_get(const AIOCBInfo *aiocb_info, BlockBackend *blk,
1872                   BlockCompletionFunc *cb, void *opaque)
1873 {
1874     return qemu_aio_get(aiocb_info, blk_bs(blk), cb, opaque);
1875 }
1876 
1877 int coroutine_fn blk_co_pwrite_zeroes(BlockBackend *blk, int64_t offset,
1878                                       int bytes, BdrvRequestFlags flags)
1879 {
1880     return blk_co_pwritev(blk, offset, bytes, NULL,
1881                           flags | BDRV_REQ_ZERO_WRITE);
1882 }
1883 
1884 int blk_pwrite_compressed(BlockBackend *blk, int64_t offset, const void *buf,
1885                           int count)
1886 {
1887     return blk_prw(blk, offset, (void *) buf, count, blk_write_entry,
1888                    BDRV_REQ_WRITE_COMPRESSED);
1889 }
1890 
1891 int blk_truncate(BlockBackend *blk, int64_t offset, PreallocMode prealloc,
1892                  Error **errp)
1893 {
1894     if (!blk_is_available(blk)) {
1895         error_setg(errp, "No medium inserted");
1896         return -ENOMEDIUM;
1897     }
1898 
1899     return bdrv_truncate(blk->root, offset, prealloc, errp);
1900 }
1901 
1902 static void blk_pdiscard_entry(void *opaque)
1903 {
1904     BlkRwCo *rwco = opaque;
1905     rwco->ret = blk_co_pdiscard(rwco->blk, rwco->offset, rwco->qiov->size);
1906 }
1907 
1908 int blk_pdiscard(BlockBackend *blk, int64_t offset, int bytes)
1909 {
1910     return blk_prw(blk, offset, NULL, bytes, blk_pdiscard_entry, 0);
1911 }
1912 
1913 int blk_save_vmstate(BlockBackend *blk, const uint8_t *buf,
1914                      int64_t pos, int size)
1915 {
1916     int ret;
1917 
1918     if (!blk_is_available(blk)) {
1919         return -ENOMEDIUM;
1920     }
1921 
1922     ret = bdrv_save_vmstate(blk_bs(blk), buf, pos, size);
1923     if (ret < 0) {
1924         return ret;
1925     }
1926 
1927     if (ret == size && !blk->enable_write_cache) {
1928         ret = bdrv_flush(blk_bs(blk));
1929     }
1930 
1931     return ret < 0 ? ret : size;
1932 }
1933 
1934 int blk_load_vmstate(BlockBackend *blk, uint8_t *buf, int64_t pos, int size)
1935 {
1936     if (!blk_is_available(blk)) {
1937         return -ENOMEDIUM;
1938     }
1939 
1940     return bdrv_load_vmstate(blk_bs(blk), buf, pos, size);
1941 }
1942 
1943 int blk_probe_blocksizes(BlockBackend *blk, BlockSizes *bsz)
1944 {
1945     if (!blk_is_available(blk)) {
1946         return -ENOMEDIUM;
1947     }
1948 
1949     return bdrv_probe_blocksizes(blk_bs(blk), bsz);
1950 }
1951 
1952 int blk_probe_geometry(BlockBackend *blk, HDGeometry *geo)
1953 {
1954     if (!blk_is_available(blk)) {
1955         return -ENOMEDIUM;
1956     }
1957 
1958     return bdrv_probe_geometry(blk_bs(blk), geo);
1959 }
1960 
1961 /*
1962  * Updates the BlockBackendRootState object with data from the currently
1963  * attached BlockDriverState.
1964  */
1965 void blk_update_root_state(BlockBackend *blk)
1966 {
1967     assert(blk->root);
1968 
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;
1972 }
1973 
1974 /*
1975  * Returns the detect-zeroes setting to be used for bdrv_open() of a
1976  * BlockDriverState which is supposed to inherit the root state.
1977  */
1978 bool blk_get_detect_zeroes_from_root_state(BlockBackend *blk)
1979 {
1980     return blk->root_state.detect_zeroes;
1981 }
1982 
1983 /*
1984  * Returns the flags to be used for bdrv_open() of a BlockDriverState which is
1985  * supposed to inherit the root state.
1986  */
1987 int blk_get_open_flags_from_root_state(BlockBackend *blk)
1988 {
1989     int bs_flags;
1990 
1991     bs_flags = blk->root_state.read_only ? 0 : BDRV_O_RDWR;
1992     bs_flags |= blk->root_state.open_flags & ~BDRV_O_RDWR;
1993 
1994     return bs_flags;
1995 }
1996 
1997 BlockBackendRootState *blk_get_root_state(BlockBackend *blk)
1998 {
1999     return &blk->root_state;
2000 }
2001 
2002 int blk_commit_all(void)
2003 {
2004     BlockBackend *blk = NULL;
2005 
2006     while ((blk = blk_all_next(blk)) != NULL) {
2007         AioContext *aio_context = blk_get_aio_context(blk);
2008 
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;
2015             }
2016         }
2017         aio_context_release(aio_context);
2018     }
2019     return 0;
2020 }
2021 
2022 
2023 /* throttling disk I/O limits */
2024 void blk_set_io_limits(BlockBackend *blk, ThrottleConfig *cfg)
2025 {
2026     throttle_group_config(&blk->public.throttle_group_member, cfg);
2027 }
2028 
2029 void blk_io_limits_disable(BlockBackend *blk)
2030 {
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);
2036     }
2037     throttle_group_unregister_tgm(tgm);
2038     if (bs) {
2039         bdrv_drained_end(bs);
2040     }
2041 }
2042 
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)
2045 {
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));
2049 }
2050 
2051 void blk_io_limits_update_group(BlockBackend *blk, const char *group)
2052 {
2053     /* this BB is not part of any group */
2054     if (!blk->public.throttle_group_member.throttle_state) {
2055         return;
2056     }
2057 
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;
2062     }
2063 
2064     /* need to change the group this bs belong to */
2065     blk_io_limits_disable(blk);
2066     blk_io_limits_enable(blk, group);
2067 }
2068 
2069 static void blk_root_drained_begin(BdrvChild *child)
2070 {
2071     BlockBackend *blk = child->opaque;
2072 
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);
2076         }
2077     }
2078 
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. */
2081 
2082     if (atomic_fetch_inc(&blk->public.throttle_group_member.io_limits_disabled) == 0) {
2083         throttle_group_restart_tgm(&blk->public.throttle_group_member);
2084     }
2085 }
2086 
2087 static void blk_root_drained_end(BdrvChild *child)
2088 {
2089     BlockBackend *blk = child->opaque;
2090     assert(blk->quiesce_counter);
2091 
2092     assert(blk->public.throttle_group_member.io_limits_disabled);
2093     atomic_dec(&blk->public.throttle_group_member.io_limits_disabled);
2094 
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);
2098         }
2099     }
2100 }
2101 
2102 void blk_register_buf(BlockBackend *blk, void *host, size_t size)
2103 {
2104     bdrv_register_buf(blk_bs(blk), host, size);
2105 }
2106 
2107 void blk_unregister_buf(BlockBackend *blk, void *host)
2108 {
2109     bdrv_unregister_buf(blk_bs(blk), host);
2110 }
2111