]> Git Repo - qemu.git/blob - block/block-backend.c
Include qapi/error.h exactly where needed
[qemu.git] / block / block-backend.c
1 /*
2  * QEMU Block backends
3  *
4  * Copyright (C) 2014-2016 Red Hat, Inc.
5  *
6  * Authors:
7  *  Markus Armbruster <[email protected]>,
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-event.h"
21 #include "qapi/error.h"
22 #include "qemu/id.h"
23 #include "trace.h"
24 #include "migration/misc.h"
25
26 /* Number of coroutines to reserve per attached device model */
27 #define COROUTINE_POOL_RESERVATION 64
28
29 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
30
31 static AioContext *blk_aiocb_get_aio_context(BlockAIOCB *acb);
32
33 struct BlockBackend {
34     char *name;
35     int refcnt;
36     BdrvChild *root;
37     DriveInfo *legacy_dinfo;    /* null unless created by drive_new() */
38     QTAILQ_ENTRY(BlockBackend) link;         /* for block_backends */
39     QTAILQ_ENTRY(BlockBackend) monitor_link; /* for monitor_block_backends */
40     BlockBackendPublic public;
41
42     void *dev;                  /* attached device model, if any */
43     bool legacy_dev;            /* true if dev is not a DeviceState */
44     /* TODO change to DeviceState when all users are qdevified */
45     const BlockDevOps *dev_ops;
46     void *dev_opaque;
47
48     /* the block size for which the guest device expects atomicity */
49     int guest_block_size;
50
51     /* If the BDS tree is removed, some of its options are stored here (which
52      * can be used to restore those options in the new BDS on insert) */
53     BlockBackendRootState root_state;
54
55     bool enable_write_cache;
56
57     /* I/O stats (display with "info blockstats"). */
58     BlockAcctStats stats;
59
60     BlockdevOnError on_read_error, on_write_error;
61     bool iostatus_enabled;
62     BlockDeviceIoStatus iostatus;
63
64     uint64_t perm;
65     uint64_t shared_perm;
66     bool disable_perm;
67
68     bool allow_write_beyond_eof;
69
70     NotifierList remove_bs_notifiers, insert_bs_notifiers;
71
72     int quiesce_counter;
73     VMChangeStateEntry *vmsh;
74     bool force_allow_inactivate;
75 };
76
77 typedef struct BlockBackendAIOCB {
78     BlockAIOCB common;
79     BlockBackend *blk;
80     int ret;
81 } BlockBackendAIOCB;
82
83 static const AIOCBInfo block_backend_aiocb_info = {
84     .get_aio_context = blk_aiocb_get_aio_context,
85     .aiocb_size = sizeof(BlockBackendAIOCB),
86 };
87
88 static void drive_info_del(DriveInfo *dinfo);
89 static BlockBackend *bdrv_first_blk(BlockDriverState *bs);
90
91 /* All BlockBackends */
92 static QTAILQ_HEAD(, BlockBackend) block_backends =
93     QTAILQ_HEAD_INITIALIZER(block_backends);
94
95 /* All BlockBackends referenced by the monitor and which are iterated through by
96  * blk_next() */
97 static QTAILQ_HEAD(, BlockBackend) monitor_block_backends =
98     QTAILQ_HEAD_INITIALIZER(monitor_block_backends);
99
100 static void blk_root_inherit_options(int *child_flags, QDict *child_options,
101                                      int parent_flags, QDict *parent_options)
102 {
103     /* We're not supposed to call this function for root nodes */
104     abort();
105 }
106 static void blk_root_drained_begin(BdrvChild *child);
107 static void blk_root_drained_end(BdrvChild *child);
108
109 static void blk_root_change_media(BdrvChild *child, bool load);
110 static void blk_root_resize(BdrvChild *child);
111
112 static char *blk_root_get_parent_desc(BdrvChild *child)
113 {
114     BlockBackend *blk = child->opaque;
115     char *dev_id;
116
117     if (blk->name) {
118         return g_strdup(blk->name);
119     }
120
121     dev_id = blk_get_attached_dev_id(blk);
122     if (*dev_id) {
123         return dev_id;
124     } else {
125         /* TODO Callback into the BB owner for something more detailed */
126         g_free(dev_id);
127         return g_strdup("a block device");
128     }
129 }
130
131 static const char *blk_root_get_name(BdrvChild *child)
132 {
133     return blk_name(child->opaque);
134 }
135
136 static void blk_vm_state_changed(void *opaque, int running, RunState state)
137 {
138     Error *local_err = NULL;
139     BlockBackend *blk = opaque;
140
141     if (state == RUN_STATE_INMIGRATE) {
142         return;
143     }
144
145     qemu_del_vm_change_state_handler(blk->vmsh);
146     blk->vmsh = NULL;
147     blk_set_perm(blk, blk->perm, blk->shared_perm, &local_err);
148     if (local_err) {
149         error_report_err(local_err);
150     }
151 }
152
153 /*
154  * Notifies the user of the BlockBackend that migration has completed. qdev
155  * devices can tighten their permissions in response (specifically revoke
156  * shared write permissions that we needed for storage migration).
157  *
158  * If an error is returned, the VM cannot be allowed to be resumed.
159  */
160 static void blk_root_activate(BdrvChild *child, Error **errp)
161 {
162     BlockBackend *blk = child->opaque;
163     Error *local_err = NULL;
164
165     if (!blk->disable_perm) {
166         return;
167     }
168
169     blk->disable_perm = false;
170
171     blk_set_perm(blk, blk->perm, BLK_PERM_ALL, &local_err);
172     if (local_err) {
173         error_propagate(errp, local_err);
174         blk->disable_perm = true;
175         return;
176     }
177
178     if (runstate_check(RUN_STATE_INMIGRATE)) {
179         /* Activation can happen when migration process is still active, for
180          * example when nbd_server_add is called during non-shared storage
181          * migration. Defer the shared_perm update to migration completion. */
182         if (!blk->vmsh) {
183             blk->vmsh = qemu_add_vm_change_state_handler(blk_vm_state_changed,
184                                                          blk);
185         }
186         return;
187     }
188
189     blk_set_perm(blk, blk->perm, blk->shared_perm, &local_err);
190     if (local_err) {
191         error_propagate(errp, local_err);
192         blk->disable_perm = true;
193         return;
194     }
195 }
196
197 void blk_set_force_allow_inactivate(BlockBackend *blk)
198 {
199     blk->force_allow_inactivate = true;
200 }
201
202 static bool blk_can_inactivate(BlockBackend *blk)
203 {
204     /* If it is a guest device, inactivate is ok. */
205     if (blk->dev || blk_name(blk)[0]) {
206         return true;
207     }
208
209     /* Inactivating means no more writes to the image can be done,
210      * even if those writes would be changes invisible to the
211      * guest.  For block job BBs that satisfy this, we can just allow
212      * it.  This is the case for mirror job source, which is required
213      * by libvirt non-shared block migration. */
214     if (!(blk->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED))) {
215         return true;
216     }
217
218     return blk->force_allow_inactivate;
219 }
220
221 static int blk_root_inactivate(BdrvChild *child)
222 {
223     BlockBackend *blk = child->opaque;
224
225     if (blk->disable_perm) {
226         return 0;
227     }
228
229     if (!blk_can_inactivate(blk)) {
230         return -EPERM;
231     }
232
233     blk->disable_perm = true;
234     if (blk->root) {
235         bdrv_child_try_set_perm(blk->root, 0, BLK_PERM_ALL, &error_abort);
236     }
237
238     return 0;
239 }
240
241 static const BdrvChildRole child_root = {
242     .inherit_options    = blk_root_inherit_options,
243
244     .change_media       = blk_root_change_media,
245     .resize             = blk_root_resize,
246     .get_name           = blk_root_get_name,
247     .get_parent_desc    = blk_root_get_parent_desc,
248
249     .drained_begin      = blk_root_drained_begin,
250     .drained_end        = blk_root_drained_end,
251
252     .activate           = blk_root_activate,
253     .inactivate         = blk_root_inactivate,
254 };
255
256 /*
257  * Create a new BlockBackend with a reference count of one.
258  *
259  * @perm is a bitmasks of BLK_PERM_* constants which describes the permissions
260  * to request for a block driver node that is attached to this BlockBackend.
261  * @shared_perm is a bitmask which describes which permissions may be granted
262  * to other users of the attached node.
263  * Both sets of permissions can be changed later using blk_set_perm().
264  *
265  * Return the new BlockBackend on success, null on failure.
266  */
267 BlockBackend *blk_new(uint64_t perm, uint64_t shared_perm)
268 {
269     BlockBackend *blk;
270
271     blk = g_new0(BlockBackend, 1);
272     blk->refcnt = 1;
273     blk->perm = perm;
274     blk->shared_perm = shared_perm;
275     blk_set_enable_write_cache(blk, true);
276
277     block_acct_init(&blk->stats);
278
279     notifier_list_init(&blk->remove_bs_notifiers);
280     notifier_list_init(&blk->insert_bs_notifiers);
281
282     QTAILQ_INSERT_TAIL(&block_backends, blk, link);
283     return blk;
284 }
285
286 /*
287  * Creates a new BlockBackend, opens a new BlockDriverState, and connects both.
288  *
289  * Just as with bdrv_open(), after having called this function the reference to
290  * @options belongs to the block layer (even on failure).
291  *
292  * TODO: Remove @filename and @flags; it should be possible to specify a whole
293  * BDS tree just by specifying the @options QDict (or @reference,
294  * alternatively). At the time of adding this function, this is not possible,
295  * though, so callers of this function have to be able to specify @filename and
296  * @flags.
297  */
298 BlockBackend *blk_new_open(const char *filename, const char *reference,
299                            QDict *options, int flags, Error **errp)
300 {
301     BlockBackend *blk;
302     BlockDriverState *bs;
303     uint64_t perm = 0;
304
305     /* blk_new_open() is mainly used in .bdrv_create implementations and the
306      * tools where sharing isn't a concern because the BDS stays private, so we
307      * just request permission according to the flags.
308      *
309      * The exceptions are xen_disk and blockdev_init(); in these cases, the
310      * caller of blk_new_open() doesn't make use of the permissions, but they
311      * shouldn't hurt either. We can still share everything here because the
312      * guest devices will add their own blockers if they can't share. */
313     if ((flags & BDRV_O_NO_IO) == 0) {
314         perm |= BLK_PERM_CONSISTENT_READ;
315         if (flags & BDRV_O_RDWR) {
316             perm |= BLK_PERM_WRITE;
317         }
318     }
319     if (flags & BDRV_O_RESIZE) {
320         perm |= BLK_PERM_RESIZE;
321     }
322
323     blk = blk_new(perm, BLK_PERM_ALL);
324     bs = bdrv_open(filename, reference, options, flags, errp);
325     if (!bs) {
326         blk_unref(blk);
327         return NULL;
328     }
329
330     blk->root = bdrv_root_attach_child(bs, "root", &child_root,
331                                        perm, BLK_PERM_ALL, blk, errp);
332     if (!blk->root) {
333         bdrv_unref(bs);
334         blk_unref(blk);
335         return NULL;
336     }
337
338     return blk;
339 }
340
341 static void blk_delete(BlockBackend *blk)
342 {
343     assert(!blk->refcnt);
344     assert(!blk->name);
345     assert(!blk->dev);
346     if (blk->public.throttle_group_member.throttle_state) {
347         blk_io_limits_disable(blk);
348     }
349     if (blk->root) {
350         blk_remove_bs(blk);
351     }
352     if (blk->vmsh) {
353         qemu_del_vm_change_state_handler(blk->vmsh);
354         blk->vmsh = NULL;
355     }
356     assert(QLIST_EMPTY(&blk->remove_bs_notifiers.notifiers));
357     assert(QLIST_EMPTY(&blk->insert_bs_notifiers.notifiers));
358     QTAILQ_REMOVE(&block_backends, blk, link);
359     drive_info_del(blk->legacy_dinfo);
360     block_acct_cleanup(&blk->stats);
361     g_free(blk);
362 }
363
364 static void drive_info_del(DriveInfo *dinfo)
365 {
366     if (!dinfo) {
367         return;
368     }
369     qemu_opts_del(dinfo->opts);
370     g_free(dinfo->serial);
371     g_free(dinfo);
372 }
373
374 int blk_get_refcnt(BlockBackend *blk)
375 {
376     return blk ? blk->refcnt : 0;
377 }
378
379 /*
380  * Increment @blk's reference count.
381  * @blk must not be null.
382  */
383 void blk_ref(BlockBackend *blk)
384 {
385     blk->refcnt++;
386 }
387
388 /*
389  * Decrement @blk's reference count.
390  * If this drops it to zero, destroy @blk.
391  * For convenience, do nothing if @blk is null.
392  */
393 void blk_unref(BlockBackend *blk)
394 {
395     if (blk) {
396         assert(blk->refcnt > 0);
397         if (!--blk->refcnt) {
398             blk_delete(blk);
399         }
400     }
401 }
402
403 /*
404  * Behaves similarly to blk_next() but iterates over all BlockBackends, even the
405  * ones which are hidden (i.e. are not referenced by the monitor).
406  */
407 BlockBackend *blk_all_next(BlockBackend *blk)
408 {
409     return blk ? QTAILQ_NEXT(blk, link)
410                : QTAILQ_FIRST(&block_backends);
411 }
412
413 void blk_remove_all_bs(void)
414 {
415     BlockBackend *blk = NULL;
416
417     while ((blk = blk_all_next(blk)) != NULL) {
418         AioContext *ctx = blk_get_aio_context(blk);
419
420         aio_context_acquire(ctx);
421         if (blk->root) {
422             blk_remove_bs(blk);
423         }
424         aio_context_release(ctx);
425     }
426 }
427
428 /*
429  * Return the monitor-owned BlockBackend after @blk.
430  * If @blk is null, return the first one.
431  * Else, return @blk's next sibling, which may be null.
432  *
433  * To iterate over all BlockBackends, do
434  * for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
435  *     ...
436  * }
437  */
438 BlockBackend *blk_next(BlockBackend *blk)
439 {
440     return blk ? QTAILQ_NEXT(blk, monitor_link)
441                : QTAILQ_FIRST(&monitor_block_backends);
442 }
443
444 /* Iterates over all top-level BlockDriverStates, i.e. BDSs that are owned by
445  * the monitor or attached to a BlockBackend */
446 BlockDriverState *bdrv_next(BdrvNextIterator *it)
447 {
448     BlockDriverState *bs, *old_bs;
449
450     /* Must be called from the main loop */
451     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
452
453     /* First, return all root nodes of BlockBackends. In order to avoid
454      * returning a BDS twice when multiple BBs refer to it, we only return it
455      * if the BB is the first one in the parent list of the BDS. */
456     if (it->phase == BDRV_NEXT_BACKEND_ROOTS) {
457         BlockBackend *old_blk = it->blk;
458
459         old_bs = old_blk ? blk_bs(old_blk) : NULL;
460
461         do {
462             it->blk = blk_all_next(it->blk);
463             bs = it->blk ? blk_bs(it->blk) : NULL;
464         } while (it->blk && (bs == NULL || bdrv_first_blk(bs) != it->blk));
465
466         if (it->blk) {
467             blk_ref(it->blk);
468         }
469         blk_unref(old_blk);
470
471         if (bs) {
472             bdrv_ref(bs);
473             bdrv_unref(old_bs);
474             return bs;
475         }
476         it->phase = BDRV_NEXT_MONITOR_OWNED;
477     } else {
478         old_bs = it->bs;
479     }
480
481     /* Then return the monitor-owned BDSes without a BB attached. Ignore all
482      * BDSes that are attached to a BlockBackend here; they have been handled
483      * by the above block already */
484     do {
485         it->bs = bdrv_next_monitor_owned(it->bs);
486         bs = it->bs;
487     } while (bs && bdrv_has_blk(bs));
488
489     if (bs) {
490         bdrv_ref(bs);
491     }
492     bdrv_unref(old_bs);
493
494     return bs;
495 }
496
497 static void bdrv_next_reset(BdrvNextIterator *it)
498 {
499     *it = (BdrvNextIterator) {
500         .phase = BDRV_NEXT_BACKEND_ROOTS,
501     };
502 }
503
504 BlockDriverState *bdrv_first(BdrvNextIterator *it)
505 {
506     bdrv_next_reset(it);
507     return bdrv_next(it);
508 }
509
510 /* Must be called when aborting a bdrv_next() iteration before
511  * bdrv_next() returns NULL */
512 void bdrv_next_cleanup(BdrvNextIterator *it)
513 {
514     /* Must be called from the main loop */
515     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
516
517     if (it->phase == BDRV_NEXT_BACKEND_ROOTS) {
518         if (it->blk) {
519             bdrv_unref(blk_bs(it->blk));
520             blk_unref(it->blk);
521         }
522     } else {
523         bdrv_unref(it->bs);
524     }
525
526     bdrv_next_reset(it);
527 }
528
529 /*
530  * Add a BlockBackend into the list of backends referenced by the monitor, with
531  * the given @name acting as the handle for the monitor.
532  * Strictly for use by blockdev.c.
533  *
534  * @name must not be null or empty.
535  *
536  * Returns true on success and false on failure. In the latter case, an Error
537  * object is returned through @errp.
538  */
539 bool monitor_add_blk(BlockBackend *blk, const char *name, Error **errp)
540 {
541     assert(!blk->name);
542     assert(name && name[0]);
543
544     if (!id_wellformed(name)) {
545         error_setg(errp, "Invalid device name");
546         return false;
547     }
548     if (blk_by_name(name)) {
549         error_setg(errp, "Device with id '%s' already exists", name);
550         return false;
551     }
552     if (bdrv_find_node(name)) {
553         error_setg(errp,
554                    "Device name '%s' conflicts with an existing node name",
555                    name);
556         return false;
557     }
558
559     blk->name = g_strdup(name);
560     QTAILQ_INSERT_TAIL(&monitor_block_backends, blk, monitor_link);
561     return true;
562 }
563
564 /*
565  * Remove a BlockBackend from the list of backends referenced by the monitor.
566  * Strictly for use by blockdev.c.
567  */
568 void monitor_remove_blk(BlockBackend *blk)
569 {
570     if (!blk->name) {
571         return;
572     }
573
574     QTAILQ_REMOVE(&monitor_block_backends, blk, monitor_link);
575     g_free(blk->name);
576     blk->name = NULL;
577 }
578
579 /*
580  * Return @blk's name, a non-null string.
581  * Returns an empty string iff @blk is not referenced by the monitor.
582  */
583 const char *blk_name(const BlockBackend *blk)
584 {
585     return blk->name ?: "";
586 }
587
588 /*
589  * Return the BlockBackend with name @name if it exists, else null.
590  * @name must not be null.
591  */
592 BlockBackend *blk_by_name(const char *name)
593 {
594     BlockBackend *blk = NULL;
595
596     assert(name);
597     while ((blk = blk_next(blk)) != NULL) {
598         if (!strcmp(name, blk->name)) {
599             return blk;
600         }
601     }
602     return NULL;
603 }
604
605 /*
606  * Return the BlockDriverState attached to @blk if any, else null.
607  */
608 BlockDriverState *blk_bs(BlockBackend *blk)
609 {
610     return blk->root ? blk->root->bs : NULL;
611 }
612
613 static BlockBackend *bdrv_first_blk(BlockDriverState *bs)
614 {
615     BdrvChild *child;
616     QLIST_FOREACH(child, &bs->parents, next_parent) {
617         if (child->role == &child_root) {
618             return child->opaque;
619         }
620     }
621
622     return NULL;
623 }
624
625 /*
626  * Returns true if @bs has an associated BlockBackend.
627  */
628 bool bdrv_has_blk(BlockDriverState *bs)
629 {
630     return bdrv_first_blk(bs) != NULL;
631 }
632
633 /*
634  * Returns true if @bs has only BlockBackends as parents.
635  */
636 bool bdrv_is_root_node(BlockDriverState *bs)
637 {
638     BdrvChild *c;
639
640     QLIST_FOREACH(c, &bs->parents, next_parent) {
641         if (c->role != &child_root) {
642             return false;
643         }
644     }
645
646     return true;
647 }
648
649 /*
650  * Return @blk's DriveInfo if any, else null.
651  */
652 DriveInfo *blk_legacy_dinfo(BlockBackend *blk)
653 {
654     return blk->legacy_dinfo;
655 }
656
657 /*
658  * Set @blk's DriveInfo to @dinfo, and return it.
659  * @blk must not have a DriveInfo set already.
660  * No other BlockBackend may have the same DriveInfo set.
661  */
662 DriveInfo *blk_set_legacy_dinfo(BlockBackend *blk, DriveInfo *dinfo)
663 {
664     assert(!blk->legacy_dinfo);
665     return blk->legacy_dinfo = dinfo;
666 }
667
668 /*
669  * Return the BlockBackend with DriveInfo @dinfo.
670  * It must exist.
671  */
672 BlockBackend *blk_by_legacy_dinfo(DriveInfo *dinfo)
673 {
674     BlockBackend *blk = NULL;
675
676     while ((blk = blk_next(blk)) != NULL) {
677         if (blk->legacy_dinfo == dinfo) {
678             return blk;
679         }
680     }
681     abort();
682 }
683
684 /*
685  * Returns a pointer to the publicly accessible fields of @blk.
686  */
687 BlockBackendPublic *blk_get_public(BlockBackend *blk)
688 {
689     return &blk->public;
690 }
691
692 /*
693  * Returns a BlockBackend given the associated @public fields.
694  */
695 BlockBackend *blk_by_public(BlockBackendPublic *public)
696 {
697     return container_of(public, BlockBackend, public);
698 }
699
700 /*
701  * Disassociates the currently associated BlockDriverState from @blk.
702  */
703 void blk_remove_bs(BlockBackend *blk)
704 {
705     ThrottleGroupMember *tgm = &blk->public.throttle_group_member;
706     BlockDriverState *bs;
707
708     notifier_list_notify(&blk->remove_bs_notifiers, blk);
709     if (tgm->throttle_state) {
710         bs = blk_bs(blk);
711         bdrv_drained_begin(bs);
712         throttle_group_detach_aio_context(tgm);
713         throttle_group_attach_aio_context(tgm, qemu_get_aio_context());
714         bdrv_drained_end(bs);
715     }
716
717     blk_update_root_state(blk);
718
719     bdrv_root_unref_child(blk->root);
720     blk->root = NULL;
721 }
722
723 /*
724  * Associates a new BlockDriverState with @blk.
725  */
726 int blk_insert_bs(BlockBackend *blk, BlockDriverState *bs, Error **errp)
727 {
728     ThrottleGroupMember *tgm = &blk->public.throttle_group_member;
729     blk->root = bdrv_root_attach_child(bs, "root", &child_root,
730                                        blk->perm, blk->shared_perm, blk, errp);
731     if (blk->root == NULL) {
732         return -EPERM;
733     }
734     bdrv_ref(bs);
735
736     notifier_list_notify(&blk->insert_bs_notifiers, blk);
737     if (tgm->throttle_state) {
738         throttle_group_detach_aio_context(tgm);
739         throttle_group_attach_aio_context(tgm, bdrv_get_aio_context(bs));
740     }
741
742     return 0;
743 }
744
745 /*
746  * Sets the permission bitmasks that the user of the BlockBackend needs.
747  */
748 int blk_set_perm(BlockBackend *blk, uint64_t perm, uint64_t shared_perm,
749                  Error **errp)
750 {
751     int ret;
752
753     if (blk->root && !blk->disable_perm) {
754         ret = bdrv_child_try_set_perm(blk->root, perm, shared_perm, errp);
755         if (ret < 0) {
756             return ret;
757         }
758     }
759
760     blk->perm = perm;
761     blk->shared_perm = shared_perm;
762
763     return 0;
764 }
765
766 void blk_get_perm(BlockBackend *blk, uint64_t *perm, uint64_t *shared_perm)
767 {
768     *perm = blk->perm;
769     *shared_perm = blk->shared_perm;
770 }
771
772 static int blk_do_attach_dev(BlockBackend *blk, void *dev)
773 {
774     if (blk->dev) {
775         return -EBUSY;
776     }
777
778     /* While migration is still incoming, we don't need to apply the
779      * permissions of guest device BlockBackends. We might still have a block
780      * job or NBD server writing to the image for storage migration. */
781     if (runstate_check(RUN_STATE_INMIGRATE)) {
782         blk->disable_perm = true;
783     }
784
785     blk_ref(blk);
786     blk->dev = dev;
787     blk->legacy_dev = false;
788     blk_iostatus_reset(blk);
789
790     return 0;
791 }
792
793 /*
794  * Attach device model @dev to @blk.
795  * Return 0 on success, -EBUSY when a device model is attached already.
796  */
797 int blk_attach_dev(BlockBackend *blk, DeviceState *dev)
798 {
799     return blk_do_attach_dev(blk, dev);
800 }
801
802 /*
803  * Attach device model @dev to @blk.
804  * @blk must not have a device model attached already.
805  * TODO qdevified devices don't use this, remove when devices are qdevified
806  */
807 void blk_attach_dev_legacy(BlockBackend *blk, void *dev)
808 {
809     if (blk_do_attach_dev(blk, dev) < 0) {
810         abort();
811     }
812     blk->legacy_dev = true;
813 }
814
815 /*
816  * Detach device model @dev from @blk.
817  * @dev must be currently attached to @blk.
818  */
819 void blk_detach_dev(BlockBackend *blk, void *dev)
820 /* TODO change to DeviceState *dev when all users are qdevified */
821 {
822     assert(blk->dev == dev);
823     blk->dev = NULL;
824     blk->dev_ops = NULL;
825     blk->dev_opaque = NULL;
826     blk->guest_block_size = 512;
827     blk_set_perm(blk, 0, BLK_PERM_ALL, &error_abort);
828     blk_unref(blk);
829 }
830
831 /*
832  * Return the device model attached to @blk if any, else null.
833  */
834 void *blk_get_attached_dev(BlockBackend *blk)
835 /* TODO change to return DeviceState * when all users are qdevified */
836 {
837     return blk->dev;
838 }
839
840 /* Return the qdev ID, or if no ID is assigned the QOM path, of the block
841  * device attached to the BlockBackend. */
842 char *blk_get_attached_dev_id(BlockBackend *blk)
843 {
844     DeviceState *dev;
845
846     assert(!blk->legacy_dev);
847     dev = blk->dev;
848
849     if (!dev) {
850         return g_strdup("");
851     } else if (dev->id) {
852         return g_strdup(dev->id);
853     }
854     return object_get_canonical_path(OBJECT(dev));
855 }
856
857 /*
858  * Return the BlockBackend which has the device model @dev attached if it
859  * exists, else null.
860  *
861  * @dev must not be null.
862  */
863 BlockBackend *blk_by_dev(void *dev)
864 {
865     BlockBackend *blk = NULL;
866
867     assert(dev != NULL);
868     while ((blk = blk_all_next(blk)) != NULL) {
869         if (blk->dev == dev) {
870             return blk;
871         }
872     }
873     return NULL;
874 }
875
876 /*
877  * Set @blk's device model callbacks to @ops.
878  * @opaque is the opaque argument to pass to the callbacks.
879  * This is for use by device models.
880  */
881 void blk_set_dev_ops(BlockBackend *blk, const BlockDevOps *ops,
882                      void *opaque)
883 {
884     /* All drivers that use blk_set_dev_ops() are qdevified and we want to keep
885      * it that way, so we can assume blk->dev, if present, is a DeviceState if
886      * blk->dev_ops is set. Non-device users may use dev_ops without device. */
887     assert(!blk->legacy_dev);
888
889     blk->dev_ops = ops;
890     blk->dev_opaque = opaque;
891
892     /* Are we currently quiesced? Should we enforce this right now? */
893     if (blk->quiesce_counter && ops->drained_begin) {
894         ops->drained_begin(opaque);
895     }
896 }
897
898 /*
899  * Notify @blk's attached device model of media change.
900  *
901  * If @load is true, notify of media load. This action can fail, meaning that
902  * the medium cannot be loaded. @errp is set then.
903  *
904  * If @load is false, notify of media eject. This can never fail.
905  *
906  * Also send DEVICE_TRAY_MOVED events as appropriate.
907  */
908 void blk_dev_change_media_cb(BlockBackend *blk, bool load, Error **errp)
909 {
910     if (blk->dev_ops && blk->dev_ops->change_media_cb) {
911         bool tray_was_open, tray_is_open;
912         Error *local_err = NULL;
913
914         assert(!blk->legacy_dev);
915
916         tray_was_open = blk_dev_is_tray_open(blk);
917         blk->dev_ops->change_media_cb(blk->dev_opaque, load, &local_err);
918         if (local_err) {
919             assert(load == true);
920             error_propagate(errp, local_err);
921             return;
922         }
923         tray_is_open = blk_dev_is_tray_open(blk);
924
925         if (tray_was_open != tray_is_open) {
926             char *id = blk_get_attached_dev_id(blk);
927             qapi_event_send_device_tray_moved(blk_name(blk), id, tray_is_open,
928                                               &error_abort);
929             g_free(id);
930         }
931     }
932 }
933
934 static void blk_root_change_media(BdrvChild *child, bool load)
935 {
936     blk_dev_change_media_cb(child->opaque, load, NULL);
937 }
938
939 /*
940  * Does @blk's attached device model have removable media?
941  * %true if no device model is attached.
942  */
943 bool blk_dev_has_removable_media(BlockBackend *blk)
944 {
945     return !blk->dev || (blk->dev_ops && blk->dev_ops->change_media_cb);
946 }
947
948 /*
949  * Does @blk's attached device model have a tray?
950  */
951 bool blk_dev_has_tray(BlockBackend *blk)
952 {
953     return blk->dev_ops && blk->dev_ops->is_tray_open;
954 }
955
956 /*
957  * Notify @blk's attached device model of a media eject request.
958  * If @force is true, the medium is about to be yanked out forcefully.
959  */
960 void blk_dev_eject_request(BlockBackend *blk, bool force)
961 {
962     if (blk->dev_ops && blk->dev_ops->eject_request_cb) {
963         blk->dev_ops->eject_request_cb(blk->dev_opaque, force);
964     }
965 }
966
967 /*
968  * Does @blk's attached device model have a tray, and is it open?
969  */
970 bool blk_dev_is_tray_open(BlockBackend *blk)
971 {
972     if (blk_dev_has_tray(blk)) {
973         return blk->dev_ops->is_tray_open(blk->dev_opaque);
974     }
975     return false;
976 }
977
978 /*
979  * Does @blk's attached device model have the medium locked?
980  * %false if the device model has no such lock.
981  */
982 bool blk_dev_is_medium_locked(BlockBackend *blk)
983 {
984     if (blk->dev_ops && blk->dev_ops->is_medium_locked) {
985         return blk->dev_ops->is_medium_locked(blk->dev_opaque);
986     }
987     return false;
988 }
989
990 /*
991  * Notify @blk's attached device model of a backend size change.
992  */
993 static void blk_root_resize(BdrvChild *child)
994 {
995     BlockBackend *blk = child->opaque;
996
997     if (blk->dev_ops && blk->dev_ops->resize_cb) {
998         blk->dev_ops->resize_cb(blk->dev_opaque);
999     }
1000 }
1001
1002 void blk_iostatus_enable(BlockBackend *blk)
1003 {
1004     blk->iostatus_enabled = true;
1005     blk->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
1006 }
1007
1008 /* The I/O status is only enabled if the drive explicitly
1009  * enables it _and_ the VM is configured to stop on errors */
1010 bool blk_iostatus_is_enabled(const BlockBackend *blk)
1011 {
1012     return (blk->iostatus_enabled &&
1013            (blk->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
1014             blk->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
1015             blk->on_read_error == BLOCKDEV_ON_ERROR_STOP));
1016 }
1017
1018 BlockDeviceIoStatus blk_iostatus(const BlockBackend *blk)
1019 {
1020     return blk->iostatus;
1021 }
1022
1023 void blk_iostatus_disable(BlockBackend *blk)
1024 {
1025     blk->iostatus_enabled = false;
1026 }
1027
1028 void blk_iostatus_reset(BlockBackend *blk)
1029 {
1030     if (blk_iostatus_is_enabled(blk)) {
1031         BlockDriverState *bs = blk_bs(blk);
1032         blk->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
1033         if (bs && bs->job) {
1034             block_job_iostatus_reset(bs->job);
1035         }
1036     }
1037 }
1038
1039 void blk_iostatus_set_err(BlockBackend *blk, int error)
1040 {
1041     assert(blk_iostatus_is_enabled(blk));
1042     if (blk->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
1043         blk->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
1044                                           BLOCK_DEVICE_IO_STATUS_FAILED;
1045     }
1046 }
1047
1048 void blk_set_allow_write_beyond_eof(BlockBackend *blk, bool allow)
1049 {
1050     blk->allow_write_beyond_eof = allow;
1051 }
1052
1053 static int blk_check_byte_request(BlockBackend *blk, int64_t offset,
1054                                   size_t size)
1055 {
1056     int64_t len;
1057
1058     if (size > INT_MAX) {
1059         return -EIO;
1060     }
1061
1062     if (!blk_is_available(blk)) {
1063         return -ENOMEDIUM;
1064     }
1065
1066     if (offset < 0) {
1067         return -EIO;
1068     }
1069
1070     if (!blk->allow_write_beyond_eof) {
1071         len = blk_getlength(blk);
1072         if (len < 0) {
1073             return len;
1074         }
1075
1076         if (offset > len || len - offset < size) {
1077             return -EIO;
1078         }
1079     }
1080
1081     return 0;
1082 }
1083
1084 int coroutine_fn blk_co_preadv(BlockBackend *blk, int64_t offset,
1085                                unsigned int bytes, QEMUIOVector *qiov,
1086                                BdrvRequestFlags flags)
1087 {
1088     int ret;
1089     BlockDriverState *bs = blk_bs(blk);
1090
1091     trace_blk_co_preadv(blk, bs, offset, bytes, flags);
1092
1093     ret = blk_check_byte_request(blk, offset, bytes);
1094     if (ret < 0) {
1095         return ret;
1096     }
1097
1098     bdrv_inc_in_flight(bs);
1099
1100     /* throttling disk I/O */
1101     if (blk->public.throttle_group_member.throttle_state) {
1102         throttle_group_co_io_limits_intercept(&blk->public.throttle_group_member,
1103                 bytes, false);
1104     }
1105
1106     ret = bdrv_co_preadv(blk->root, offset, bytes, qiov, flags);
1107     bdrv_dec_in_flight(bs);
1108     return ret;
1109 }
1110
1111 int coroutine_fn blk_co_pwritev(BlockBackend *blk, int64_t offset,
1112                                 unsigned int bytes, QEMUIOVector *qiov,
1113                                 BdrvRequestFlags flags)
1114 {
1115     int ret;
1116     BlockDriverState *bs = blk_bs(blk);
1117
1118     trace_blk_co_pwritev(blk, bs, offset, bytes, flags);
1119
1120     ret = blk_check_byte_request(blk, offset, bytes);
1121     if (ret < 0) {
1122         return ret;
1123     }
1124
1125     bdrv_inc_in_flight(bs);
1126     /* throttling disk I/O */
1127     if (blk->public.throttle_group_member.throttle_state) {
1128         throttle_group_co_io_limits_intercept(&blk->public.throttle_group_member,
1129                 bytes, true);
1130     }
1131
1132     if (!blk->enable_write_cache) {
1133         flags |= BDRV_REQ_FUA;
1134     }
1135
1136     ret = bdrv_co_pwritev(blk->root, offset, bytes, qiov, flags);
1137     bdrv_dec_in_flight(bs);
1138     return ret;
1139 }
1140
1141 typedef struct BlkRwCo {
1142     BlockBackend *blk;
1143     int64_t offset;
1144     QEMUIOVector *qiov;
1145     int ret;
1146     BdrvRequestFlags flags;
1147 } BlkRwCo;
1148
1149 static void blk_read_entry(void *opaque)
1150 {
1151     BlkRwCo *rwco = opaque;
1152
1153     rwco->ret = blk_co_preadv(rwco->blk, rwco->offset, rwco->qiov->size,
1154                               rwco->qiov, rwco->flags);
1155 }
1156
1157 static void blk_write_entry(void *opaque)
1158 {
1159     BlkRwCo *rwco = opaque;
1160
1161     rwco->ret = blk_co_pwritev(rwco->blk, rwco->offset, rwco->qiov->size,
1162                                rwco->qiov, rwco->flags);
1163 }
1164
1165 static int blk_prw(BlockBackend *blk, int64_t offset, uint8_t *buf,
1166                    int64_t bytes, CoroutineEntry co_entry,
1167                    BdrvRequestFlags flags)
1168 {
1169     QEMUIOVector qiov;
1170     struct iovec iov;
1171     BlkRwCo rwco;
1172
1173     iov = (struct iovec) {
1174         .iov_base = buf,
1175         .iov_len = bytes,
1176     };
1177     qemu_iovec_init_external(&qiov, &iov, 1);
1178
1179     rwco = (BlkRwCo) {
1180         .blk    = blk,
1181         .offset = offset,
1182         .qiov   = &qiov,
1183         .flags  = flags,
1184         .ret    = NOT_DONE,
1185     };
1186
1187     if (qemu_in_coroutine()) {
1188         /* Fast-path if already in coroutine context */
1189         co_entry(&rwco);
1190     } else {
1191         Coroutine *co = qemu_coroutine_create(co_entry, &rwco);
1192         bdrv_coroutine_enter(blk_bs(blk), co);
1193         BDRV_POLL_WHILE(blk_bs(blk), rwco.ret == NOT_DONE);
1194     }
1195
1196     return rwco.ret;
1197 }
1198
1199 int blk_pread_unthrottled(BlockBackend *blk, int64_t offset, uint8_t *buf,
1200                           int count)
1201 {
1202     int ret;
1203
1204     ret = blk_check_byte_request(blk, offset, count);
1205     if (ret < 0) {
1206         return ret;
1207     }
1208
1209     blk_root_drained_begin(blk->root);
1210     ret = blk_pread(blk, offset, buf, count);
1211     blk_root_drained_end(blk->root);
1212     return ret;
1213 }
1214
1215 int blk_pwrite_zeroes(BlockBackend *blk, int64_t offset,
1216                       int bytes, BdrvRequestFlags flags)
1217 {
1218     return blk_prw(blk, offset, NULL, bytes, blk_write_entry,
1219                    flags | BDRV_REQ_ZERO_WRITE);
1220 }
1221
1222 int blk_make_zero(BlockBackend *blk, BdrvRequestFlags flags)
1223 {
1224     return bdrv_make_zero(blk->root, flags);
1225 }
1226
1227 static void error_callback_bh(void *opaque)
1228 {
1229     struct BlockBackendAIOCB *acb = opaque;
1230
1231     bdrv_dec_in_flight(acb->common.bs);
1232     acb->common.cb(acb->common.opaque, acb->ret);
1233     qemu_aio_unref(acb);
1234 }
1235
1236 BlockAIOCB *blk_abort_aio_request(BlockBackend *blk,
1237                                   BlockCompletionFunc *cb,
1238                                   void *opaque, int ret)
1239 {
1240     struct BlockBackendAIOCB *acb;
1241
1242     bdrv_inc_in_flight(blk_bs(blk));
1243     acb = blk_aio_get(&block_backend_aiocb_info, blk, cb, opaque);
1244     acb->blk = blk;
1245     acb->ret = ret;
1246
1247     aio_bh_schedule_oneshot(blk_get_aio_context(blk), error_callback_bh, acb);
1248     return &acb->common;
1249 }
1250
1251 typedef struct BlkAioEmAIOCB {
1252     BlockAIOCB common;
1253     BlkRwCo rwco;
1254     int bytes;
1255     bool has_returned;
1256 } BlkAioEmAIOCB;
1257
1258 static const AIOCBInfo blk_aio_em_aiocb_info = {
1259     .aiocb_size         = sizeof(BlkAioEmAIOCB),
1260 };
1261
1262 static void blk_aio_complete(BlkAioEmAIOCB *acb)
1263 {
1264     if (acb->has_returned) {
1265         bdrv_dec_in_flight(acb->common.bs);
1266         acb->common.cb(acb->common.opaque, acb->rwco.ret);
1267         qemu_aio_unref(acb);
1268     }
1269 }
1270
1271 static void blk_aio_complete_bh(void *opaque)
1272 {
1273     BlkAioEmAIOCB *acb = opaque;
1274     assert(acb->has_returned);
1275     blk_aio_complete(acb);
1276 }
1277
1278 static BlockAIOCB *blk_aio_prwv(BlockBackend *blk, int64_t offset, int bytes,
1279                                 QEMUIOVector *qiov, CoroutineEntry co_entry,
1280                                 BdrvRequestFlags flags,
1281                                 BlockCompletionFunc *cb, void *opaque)
1282 {
1283     BlkAioEmAIOCB *acb;
1284     Coroutine *co;
1285
1286     bdrv_inc_in_flight(blk_bs(blk));
1287     acb = blk_aio_get(&blk_aio_em_aiocb_info, blk, cb, opaque);
1288     acb->rwco = (BlkRwCo) {
1289         .blk    = blk,
1290         .offset = offset,
1291         .qiov   = qiov,
1292         .flags  = flags,
1293         .ret    = NOT_DONE,
1294     };
1295     acb->bytes = bytes;
1296     acb->has_returned = false;
1297
1298     co = qemu_coroutine_create(co_entry, acb);
1299     bdrv_coroutine_enter(blk_bs(blk), co);
1300
1301     acb->has_returned = true;
1302     if (acb->rwco.ret != NOT_DONE) {
1303         aio_bh_schedule_oneshot(blk_get_aio_context(blk),
1304                                 blk_aio_complete_bh, acb);
1305     }
1306
1307     return &acb->common;
1308 }
1309
1310 static void blk_aio_read_entry(void *opaque)
1311 {
1312     BlkAioEmAIOCB *acb = opaque;
1313     BlkRwCo *rwco = &acb->rwco;
1314
1315     assert(rwco->qiov->size == acb->bytes);
1316     rwco->ret = blk_co_preadv(rwco->blk, rwco->offset, acb->bytes,
1317                               rwco->qiov, rwco->flags);
1318     blk_aio_complete(acb);
1319 }
1320
1321 static void blk_aio_write_entry(void *opaque)
1322 {
1323     BlkAioEmAIOCB *acb = opaque;
1324     BlkRwCo *rwco = &acb->rwco;
1325
1326     assert(!rwco->qiov || rwco->qiov->size == acb->bytes);
1327     rwco->ret = blk_co_pwritev(rwco->blk, rwco->offset, acb->bytes,
1328                                rwco->qiov, rwco->flags);
1329     blk_aio_complete(acb);
1330 }
1331
1332 BlockAIOCB *blk_aio_pwrite_zeroes(BlockBackend *blk, int64_t offset,
1333                                   int count, BdrvRequestFlags flags,
1334                                   BlockCompletionFunc *cb, void *opaque)
1335 {
1336     return blk_aio_prwv(blk, offset, count, NULL, blk_aio_write_entry,
1337                         flags | BDRV_REQ_ZERO_WRITE, cb, opaque);
1338 }
1339
1340 int blk_pread(BlockBackend *blk, int64_t offset, void *buf, int count)
1341 {
1342     int ret = blk_prw(blk, offset, buf, count, blk_read_entry, 0);
1343     if (ret < 0) {
1344         return ret;
1345     }
1346     return count;
1347 }
1348
1349 int blk_pwrite(BlockBackend *blk, int64_t offset, const void *buf, int count,
1350                BdrvRequestFlags flags)
1351 {
1352     int ret = blk_prw(blk, offset, (void *) buf, count, blk_write_entry,
1353                       flags);
1354     if (ret < 0) {
1355         return ret;
1356     }
1357     return count;
1358 }
1359
1360 int64_t blk_getlength(BlockBackend *blk)
1361 {
1362     if (!blk_is_available(blk)) {
1363         return -ENOMEDIUM;
1364     }
1365
1366     return bdrv_getlength(blk_bs(blk));
1367 }
1368
1369 void blk_get_geometry(BlockBackend *blk, uint64_t *nb_sectors_ptr)
1370 {
1371     if (!blk_bs(blk)) {
1372         *nb_sectors_ptr = 0;
1373     } else {
1374         bdrv_get_geometry(blk_bs(blk), nb_sectors_ptr);
1375     }
1376 }
1377
1378 int64_t blk_nb_sectors(BlockBackend *blk)
1379 {
1380     if (!blk_is_available(blk)) {
1381         return -ENOMEDIUM;
1382     }
1383
1384     return bdrv_nb_sectors(blk_bs(blk));
1385 }
1386
1387 BlockAIOCB *blk_aio_preadv(BlockBackend *blk, int64_t offset,
1388                            QEMUIOVector *qiov, BdrvRequestFlags flags,
1389                            BlockCompletionFunc *cb, void *opaque)
1390 {
1391     return blk_aio_prwv(blk, offset, qiov->size, qiov,
1392                         blk_aio_read_entry, flags, cb, opaque);
1393 }
1394
1395 BlockAIOCB *blk_aio_pwritev(BlockBackend *blk, int64_t offset,
1396                             QEMUIOVector *qiov, BdrvRequestFlags flags,
1397                             BlockCompletionFunc *cb, void *opaque)
1398 {
1399     return blk_aio_prwv(blk, offset, qiov->size, qiov,
1400                         blk_aio_write_entry, flags, cb, opaque);
1401 }
1402
1403 static void blk_aio_flush_entry(void *opaque)
1404 {
1405     BlkAioEmAIOCB *acb = opaque;
1406     BlkRwCo *rwco = &acb->rwco;
1407
1408     rwco->ret = blk_co_flush(rwco->blk);
1409     blk_aio_complete(acb);
1410 }
1411
1412 BlockAIOCB *blk_aio_flush(BlockBackend *blk,
1413                           BlockCompletionFunc *cb, void *opaque)
1414 {
1415     return blk_aio_prwv(blk, 0, 0, NULL, blk_aio_flush_entry, 0, cb, opaque);
1416 }
1417
1418 static void blk_aio_pdiscard_entry(void *opaque)
1419 {
1420     BlkAioEmAIOCB *acb = opaque;
1421     BlkRwCo *rwco = &acb->rwco;
1422
1423     rwco->ret = blk_co_pdiscard(rwco->blk, rwco->offset, acb->bytes);
1424     blk_aio_complete(acb);
1425 }
1426
1427 BlockAIOCB *blk_aio_pdiscard(BlockBackend *blk,
1428                              int64_t offset, int bytes,
1429                              BlockCompletionFunc *cb, void *opaque)
1430 {
1431     return blk_aio_prwv(blk, offset, bytes, NULL, blk_aio_pdiscard_entry, 0,
1432                         cb, opaque);
1433 }
1434
1435 void blk_aio_cancel(BlockAIOCB *acb)
1436 {
1437     bdrv_aio_cancel(acb);
1438 }
1439
1440 void blk_aio_cancel_async(BlockAIOCB *acb)
1441 {
1442     bdrv_aio_cancel_async(acb);
1443 }
1444
1445 int blk_co_ioctl(BlockBackend *blk, unsigned long int req, void *buf)
1446 {
1447     if (!blk_is_available(blk)) {
1448         return -ENOMEDIUM;
1449     }
1450
1451     return bdrv_co_ioctl(blk_bs(blk), req, buf);
1452 }
1453
1454 static void blk_ioctl_entry(void *opaque)
1455 {
1456     BlkRwCo *rwco = opaque;
1457     rwco->ret = blk_co_ioctl(rwco->blk, rwco->offset,
1458                              rwco->qiov->iov[0].iov_base);
1459 }
1460
1461 int blk_ioctl(BlockBackend *blk, unsigned long int req, void *buf)
1462 {
1463     return blk_prw(blk, req, buf, 0, blk_ioctl_entry, 0);
1464 }
1465
1466 static void blk_aio_ioctl_entry(void *opaque)
1467 {
1468     BlkAioEmAIOCB *acb = opaque;
1469     BlkRwCo *rwco = &acb->rwco;
1470
1471     rwco->ret = blk_co_ioctl(rwco->blk, rwco->offset,
1472                              rwco->qiov->iov[0].iov_base);
1473     blk_aio_complete(acb);
1474 }
1475
1476 BlockAIOCB *blk_aio_ioctl(BlockBackend *blk, unsigned long int req, void *buf,
1477                           BlockCompletionFunc *cb, void *opaque)
1478 {
1479     QEMUIOVector qiov;
1480     struct iovec iov;
1481
1482     iov = (struct iovec) {
1483         .iov_base = buf,
1484         .iov_len = 0,
1485     };
1486     qemu_iovec_init_external(&qiov, &iov, 1);
1487
1488     return blk_aio_prwv(blk, req, 0, &qiov, blk_aio_ioctl_entry, 0, cb, opaque);
1489 }
1490
1491 int blk_co_pdiscard(BlockBackend *blk, int64_t offset, int bytes)
1492 {
1493     int ret = blk_check_byte_request(blk, offset, bytes);
1494     if (ret < 0) {
1495         return ret;
1496     }
1497
1498     return bdrv_co_pdiscard(blk_bs(blk), offset, bytes);
1499 }
1500
1501 int blk_co_flush(BlockBackend *blk)
1502 {
1503     if (!blk_is_available(blk)) {
1504         return -ENOMEDIUM;
1505     }
1506
1507     return bdrv_co_flush(blk_bs(blk));
1508 }
1509
1510 static void blk_flush_entry(void *opaque)
1511 {
1512     BlkRwCo *rwco = opaque;
1513     rwco->ret = blk_co_flush(rwco->blk);
1514 }
1515
1516 int blk_flush(BlockBackend *blk)
1517 {
1518     return blk_prw(blk, 0, NULL, 0, blk_flush_entry, 0);
1519 }
1520
1521 void blk_drain(BlockBackend *blk)
1522 {
1523     if (blk_bs(blk)) {
1524         bdrv_drain(blk_bs(blk));
1525     }
1526 }
1527
1528 void blk_drain_all(void)
1529 {
1530     bdrv_drain_all();
1531 }
1532
1533 void blk_set_on_error(BlockBackend *blk, BlockdevOnError on_read_error,
1534                       BlockdevOnError on_write_error)
1535 {
1536     blk->on_read_error = on_read_error;
1537     blk->on_write_error = on_write_error;
1538 }
1539
1540 BlockdevOnError blk_get_on_error(BlockBackend *blk, bool is_read)
1541 {
1542     return is_read ? blk->on_read_error : blk->on_write_error;
1543 }
1544
1545 BlockErrorAction blk_get_error_action(BlockBackend *blk, bool is_read,
1546                                       int error)
1547 {
1548     BlockdevOnError on_err = blk_get_on_error(blk, is_read);
1549
1550     switch (on_err) {
1551     case BLOCKDEV_ON_ERROR_ENOSPC:
1552         return (error == ENOSPC) ?
1553                BLOCK_ERROR_ACTION_STOP : BLOCK_ERROR_ACTION_REPORT;
1554     case BLOCKDEV_ON_ERROR_STOP:
1555         return BLOCK_ERROR_ACTION_STOP;
1556     case BLOCKDEV_ON_ERROR_REPORT:
1557         return BLOCK_ERROR_ACTION_REPORT;
1558     case BLOCKDEV_ON_ERROR_IGNORE:
1559         return BLOCK_ERROR_ACTION_IGNORE;
1560     case BLOCKDEV_ON_ERROR_AUTO:
1561     default:
1562         abort();
1563     }
1564 }
1565
1566 static void send_qmp_error_event(BlockBackend *blk,
1567                                  BlockErrorAction action,
1568                                  bool is_read, int error)
1569 {
1570     IoOperationType optype;
1571
1572     optype = is_read ? IO_OPERATION_TYPE_READ : IO_OPERATION_TYPE_WRITE;
1573     qapi_event_send_block_io_error(blk_name(blk),
1574                                    bdrv_get_node_name(blk_bs(blk)), optype,
1575                                    action, blk_iostatus_is_enabled(blk),
1576                                    error == ENOSPC, strerror(error),
1577                                    &error_abort);
1578 }
1579
1580 /* This is done by device models because, while the block layer knows
1581  * about the error, it does not know whether an operation comes from
1582  * the device or the block layer (from a job, for example).
1583  */
1584 void blk_error_action(BlockBackend *blk, BlockErrorAction action,
1585                       bool is_read, int error)
1586 {
1587     assert(error >= 0);
1588
1589     if (action == BLOCK_ERROR_ACTION_STOP) {
1590         /* First set the iostatus, so that "info block" returns an iostatus
1591          * that matches the events raised so far (an additional error iostatus
1592          * is fine, but not a lost one).
1593          */
1594         blk_iostatus_set_err(blk, error);
1595
1596         /* Then raise the request to stop the VM and the event.
1597          * qemu_system_vmstop_request_prepare has two effects.  First,
1598          * it ensures that the STOP event always comes after the
1599          * BLOCK_IO_ERROR event.  Second, it ensures that even if management
1600          * can observe the STOP event and do a "cont" before the STOP
1601          * event is issued, the VM will not stop.  In this case, vm_start()
1602          * also ensures that the STOP/RESUME pair of events is emitted.
1603          */
1604         qemu_system_vmstop_request_prepare();
1605         send_qmp_error_event(blk, action, is_read, error);
1606         qemu_system_vmstop_request(RUN_STATE_IO_ERROR);
1607     } else {
1608         send_qmp_error_event(blk, action, is_read, error);
1609     }
1610 }
1611
1612 int blk_is_read_only(BlockBackend *blk)
1613 {
1614     BlockDriverState *bs = blk_bs(blk);
1615
1616     if (bs) {
1617         return bdrv_is_read_only(bs);
1618     } else {
1619         return blk->root_state.read_only;
1620     }
1621 }
1622
1623 int blk_is_sg(BlockBackend *blk)
1624 {
1625     BlockDriverState *bs = blk_bs(blk);
1626
1627     if (!bs) {
1628         return 0;
1629     }
1630
1631     return bdrv_is_sg(bs);
1632 }
1633
1634 int blk_enable_write_cache(BlockBackend *blk)
1635 {
1636     return blk->enable_write_cache;
1637 }
1638
1639 void blk_set_enable_write_cache(BlockBackend *blk, bool wce)
1640 {
1641     blk->enable_write_cache = wce;
1642 }
1643
1644 void blk_invalidate_cache(BlockBackend *blk, Error **errp)
1645 {
1646     BlockDriverState *bs = blk_bs(blk);
1647
1648     if (!bs) {
1649         error_setg(errp, "Device '%s' has no medium", blk->name);
1650         return;
1651     }
1652
1653     bdrv_invalidate_cache(bs, errp);
1654 }
1655
1656 bool blk_is_inserted(BlockBackend *blk)
1657 {
1658     BlockDriverState *bs = blk_bs(blk);
1659
1660     return bs && bdrv_is_inserted(bs);
1661 }
1662
1663 bool blk_is_available(BlockBackend *blk)
1664 {
1665     return blk_is_inserted(blk) && !blk_dev_is_tray_open(blk);
1666 }
1667
1668 void blk_lock_medium(BlockBackend *blk, bool locked)
1669 {
1670     BlockDriverState *bs = blk_bs(blk);
1671
1672     if (bs) {
1673         bdrv_lock_medium(bs, locked);
1674     }
1675 }
1676
1677 void blk_eject(BlockBackend *blk, bool eject_flag)
1678 {
1679     BlockDriverState *bs = blk_bs(blk);
1680     char *id;
1681
1682     /* blk_eject is only called by qdevified devices */
1683     assert(!blk->legacy_dev);
1684
1685     if (bs) {
1686         bdrv_eject(bs, eject_flag);
1687     }
1688
1689     /* Whether or not we ejected on the backend,
1690      * the frontend experienced a tray event. */
1691     id = blk_get_attached_dev_id(blk);
1692     qapi_event_send_device_tray_moved(blk_name(blk), id,
1693                                       eject_flag, &error_abort);
1694     g_free(id);
1695 }
1696
1697 int blk_get_flags(BlockBackend *blk)
1698 {
1699     BlockDriverState *bs = blk_bs(blk);
1700
1701     if (bs) {
1702         return bdrv_get_flags(bs);
1703     } else {
1704         return blk->root_state.open_flags;
1705     }
1706 }
1707
1708 /* Returns the maximum transfer length, in bytes; guaranteed nonzero */
1709 uint32_t blk_get_max_transfer(BlockBackend *blk)
1710 {
1711     BlockDriverState *bs = blk_bs(blk);
1712     uint32_t max = 0;
1713
1714     if (bs) {
1715         max = bs->bl.max_transfer;
1716     }
1717     return MIN_NON_ZERO(max, INT_MAX);
1718 }
1719
1720 int blk_get_max_iov(BlockBackend *blk)
1721 {
1722     return blk->root->bs->bl.max_iov;
1723 }
1724
1725 void blk_set_guest_block_size(BlockBackend *blk, int align)
1726 {
1727     blk->guest_block_size = align;
1728 }
1729
1730 void *blk_try_blockalign(BlockBackend *blk, size_t size)
1731 {
1732     return qemu_try_blockalign(blk ? blk_bs(blk) : NULL, size);
1733 }
1734
1735 void *blk_blockalign(BlockBackend *blk, size_t size)
1736 {
1737     return qemu_blockalign(blk ? blk_bs(blk) : NULL, size);
1738 }
1739
1740 bool blk_op_is_blocked(BlockBackend *blk, BlockOpType op, Error **errp)
1741 {
1742     BlockDriverState *bs = blk_bs(blk);
1743
1744     if (!bs) {
1745         return false;
1746     }
1747
1748     return bdrv_op_is_blocked(bs, op, errp);
1749 }
1750
1751 void blk_op_unblock(BlockBackend *blk, BlockOpType op, Error *reason)
1752 {
1753     BlockDriverState *bs = blk_bs(blk);
1754
1755     if (bs) {
1756         bdrv_op_unblock(bs, op, reason);
1757     }
1758 }
1759
1760 void blk_op_block_all(BlockBackend *blk, Error *reason)
1761 {
1762     BlockDriverState *bs = blk_bs(blk);
1763
1764     if (bs) {
1765         bdrv_op_block_all(bs, reason);
1766     }
1767 }
1768
1769 void blk_op_unblock_all(BlockBackend *blk, Error *reason)
1770 {
1771     BlockDriverState *bs = blk_bs(blk);
1772
1773     if (bs) {
1774         bdrv_op_unblock_all(bs, reason);
1775     }
1776 }
1777
1778 AioContext *blk_get_aio_context(BlockBackend *blk)
1779 {
1780     BlockDriverState *bs = blk_bs(blk);
1781
1782     if (bs) {
1783         return bdrv_get_aio_context(bs);
1784     } else {
1785         return qemu_get_aio_context();
1786     }
1787 }
1788
1789 static AioContext *blk_aiocb_get_aio_context(BlockAIOCB *acb)
1790 {
1791     BlockBackendAIOCB *blk_acb = DO_UPCAST(BlockBackendAIOCB, common, acb);
1792     return blk_get_aio_context(blk_acb->blk);
1793 }
1794
1795 void blk_set_aio_context(BlockBackend *blk, AioContext *new_context)
1796 {
1797     BlockDriverState *bs = blk_bs(blk);
1798     ThrottleGroupMember *tgm = &blk->public.throttle_group_member;
1799
1800     if (bs) {
1801         if (tgm->throttle_state) {
1802             bdrv_drained_begin(bs);
1803             throttle_group_detach_aio_context(tgm);
1804             throttle_group_attach_aio_context(tgm, new_context);
1805             bdrv_drained_end(bs);
1806         }
1807         bdrv_set_aio_context(bs, new_context);
1808     }
1809 }
1810
1811 void blk_add_aio_context_notifier(BlockBackend *blk,
1812         void (*attached_aio_context)(AioContext *new_context, void *opaque),
1813         void (*detach_aio_context)(void *opaque), void *opaque)
1814 {
1815     BlockDriverState *bs = blk_bs(blk);
1816
1817     if (bs) {
1818         bdrv_add_aio_context_notifier(bs, attached_aio_context,
1819                                       detach_aio_context, opaque);
1820     }
1821 }
1822
1823 void blk_remove_aio_context_notifier(BlockBackend *blk,
1824                                      void (*attached_aio_context)(AioContext *,
1825                                                                   void *),
1826                                      void (*detach_aio_context)(void *),
1827                                      void *opaque)
1828 {
1829     BlockDriverState *bs = blk_bs(blk);
1830
1831     if (bs) {
1832         bdrv_remove_aio_context_notifier(bs, attached_aio_context,
1833                                          detach_aio_context, opaque);
1834     }
1835 }
1836
1837 void blk_add_remove_bs_notifier(BlockBackend *blk, Notifier *notify)
1838 {
1839     notifier_list_add(&blk->remove_bs_notifiers, notify);
1840 }
1841
1842 void blk_add_insert_bs_notifier(BlockBackend *blk, Notifier *notify)
1843 {
1844     notifier_list_add(&blk->insert_bs_notifiers, notify);
1845 }
1846
1847 void blk_io_plug(BlockBackend *blk)
1848 {
1849     BlockDriverState *bs = blk_bs(blk);
1850
1851     if (bs) {
1852         bdrv_io_plug(bs);
1853     }
1854 }
1855
1856 void blk_io_unplug(BlockBackend *blk)
1857 {
1858     BlockDriverState *bs = blk_bs(blk);
1859
1860     if (bs) {
1861         bdrv_io_unplug(bs);
1862     }
1863 }
1864
1865 BlockAcctStats *blk_get_stats(BlockBackend *blk)
1866 {
1867     return &blk->stats;
1868 }
1869
1870 void *blk_aio_get(const AIOCBInfo *aiocb_info, BlockBackend *blk,
1871                   BlockCompletionFunc *cb, void *opaque)
1872 {
1873     return qemu_aio_get(aiocb_info, blk_bs(blk), cb, opaque);
1874 }
1875
1876 int coroutine_fn blk_co_pwrite_zeroes(BlockBackend *blk, int64_t offset,
1877                                       int bytes, BdrvRequestFlags flags)
1878 {
1879     return blk_co_pwritev(blk, offset, bytes, NULL,
1880                           flags | BDRV_REQ_ZERO_WRITE);
1881 }
1882
1883 int blk_pwrite_compressed(BlockBackend *blk, int64_t offset, const void *buf,
1884                           int count)
1885 {
1886     return blk_prw(blk, offset, (void *) buf, count, blk_write_entry,
1887                    BDRV_REQ_WRITE_COMPRESSED);
1888 }
1889
1890 int blk_truncate(BlockBackend *blk, int64_t offset, PreallocMode prealloc,
1891                  Error **errp)
1892 {
1893     if (!blk_is_available(blk)) {
1894         error_setg(errp, "No medium inserted");
1895         return -ENOMEDIUM;
1896     }
1897
1898     return bdrv_truncate(blk->root, offset, prealloc, errp);
1899 }
1900
1901 static void blk_pdiscard_entry(void *opaque)
1902 {
1903     BlkRwCo *rwco = opaque;
1904     rwco->ret = blk_co_pdiscard(rwco->blk, rwco->offset, rwco->qiov->size);
1905 }
1906
1907 int blk_pdiscard(BlockBackend *blk, int64_t offset, int bytes)
1908 {
1909     return blk_prw(blk, offset, NULL, bytes, blk_pdiscard_entry, 0);
1910 }
1911
1912 int blk_save_vmstate(BlockBackend *blk, const uint8_t *buf,
1913                      int64_t pos, int size)
1914 {
1915     int ret;
1916
1917     if (!blk_is_available(blk)) {
1918         return -ENOMEDIUM;
1919     }
1920
1921     ret = bdrv_save_vmstate(blk_bs(blk), buf, pos, size);
1922     if (ret < 0) {
1923         return ret;
1924     }
1925
1926     if (ret == size && !blk->enable_write_cache) {
1927         ret = bdrv_flush(blk_bs(blk));
1928     }
1929
1930     return ret < 0 ? ret : size;
1931 }
1932
1933 int blk_load_vmstate(BlockBackend *blk, uint8_t *buf, int64_t pos, int size)
1934 {
1935     if (!blk_is_available(blk)) {
1936         return -ENOMEDIUM;
1937     }
1938
1939     return bdrv_load_vmstate(blk_bs(blk), buf, pos, size);
1940 }
1941
1942 int blk_probe_blocksizes(BlockBackend *blk, BlockSizes *bsz)
1943 {
1944     if (!blk_is_available(blk)) {
1945         return -ENOMEDIUM;
1946     }
1947
1948     return bdrv_probe_blocksizes(blk_bs(blk), bsz);
1949 }
1950
1951 int blk_probe_geometry(BlockBackend *blk, HDGeometry *geo)
1952 {
1953     if (!blk_is_available(blk)) {
1954         return -ENOMEDIUM;
1955     }
1956
1957     return bdrv_probe_geometry(blk_bs(blk), geo);
1958 }
1959
1960 /*
1961  * Updates the BlockBackendRootState object with data from the currently
1962  * attached BlockDriverState.
1963  */
1964 void blk_update_root_state(BlockBackend *blk)
1965 {
1966     assert(blk->root);
1967
1968     blk->root_state.open_flags    = blk->root->bs->open_flags;
1969     blk->root_state.read_only     = blk->root->bs->read_only;
1970     blk->root_state.detect_zeroes = blk->root->bs->detect_zeroes;
1971 }
1972
1973 /*
1974  * Returns the detect-zeroes setting to be used for bdrv_open() of a
1975  * BlockDriverState which is supposed to inherit the root state.
1976  */
1977 bool blk_get_detect_zeroes_from_root_state(BlockBackend *blk)
1978 {
1979     return blk->root_state.detect_zeroes;
1980 }
1981
1982 /*
1983  * Returns the flags to be used for bdrv_open() of a BlockDriverState which is
1984  * supposed to inherit the root state.
1985  */
1986 int blk_get_open_flags_from_root_state(BlockBackend *blk)
1987 {
1988     int bs_flags;
1989
1990     bs_flags = blk->root_state.read_only ? 0 : BDRV_O_RDWR;
1991     bs_flags |= blk->root_state.open_flags & ~BDRV_O_RDWR;
1992
1993     return bs_flags;
1994 }
1995
1996 BlockBackendRootState *blk_get_root_state(BlockBackend *blk)
1997 {
1998     return &blk->root_state;
1999 }
2000
2001 int blk_commit_all(void)
2002 {
2003     BlockBackend *blk = NULL;
2004
2005     while ((blk = blk_all_next(blk)) != NULL) {
2006         AioContext *aio_context = blk_get_aio_context(blk);
2007
2008         aio_context_acquire(aio_context);
2009         if (blk_is_inserted(blk) && blk->root->bs->backing) {
2010             int ret = bdrv_commit(blk->root->bs);
2011             if (ret < 0) {
2012                 aio_context_release(aio_context);
2013                 return ret;
2014             }
2015         }
2016         aio_context_release(aio_context);
2017     }
2018     return 0;
2019 }
2020
2021
2022 /* throttling disk I/O limits */
2023 void blk_set_io_limits(BlockBackend *blk, ThrottleConfig *cfg)
2024 {
2025     throttle_group_config(&blk->public.throttle_group_member, cfg);
2026 }
2027
2028 void blk_io_limits_disable(BlockBackend *blk)
2029 {
2030     BlockDriverState *bs = blk_bs(blk);
2031     ThrottleGroupMember *tgm = &blk->public.throttle_group_member;
2032     assert(tgm->throttle_state);
2033     if (bs) {
2034         bdrv_drained_begin(bs);
2035     }
2036     throttle_group_unregister_tgm(tgm);
2037     if (bs) {
2038         bdrv_drained_end(bs);
2039     }
2040 }
2041
2042 /* should be called before blk_set_io_limits if a limit is set */
2043 void blk_io_limits_enable(BlockBackend *blk, const char *group)
2044 {
2045     assert(!blk->public.throttle_group_member.throttle_state);
2046     throttle_group_register_tgm(&blk->public.throttle_group_member,
2047                                 group, blk_get_aio_context(blk));
2048 }
2049
2050 void blk_io_limits_update_group(BlockBackend *blk, const char *group)
2051 {
2052     /* this BB is not part of any group */
2053     if (!blk->public.throttle_group_member.throttle_state) {
2054         return;
2055     }
2056
2057     /* this BB is a part of the same group than the one we want */
2058     if (!g_strcmp0(throttle_group_get_name(&blk->public.throttle_group_member),
2059                 group)) {
2060         return;
2061     }
2062
2063     /* need to change the group this bs belong to */
2064     blk_io_limits_disable(blk);
2065     blk_io_limits_enable(blk, group);
2066 }
2067
2068 static void blk_root_drained_begin(BdrvChild *child)
2069 {
2070     BlockBackend *blk = child->opaque;
2071
2072     if (++blk->quiesce_counter == 1) {
2073         if (blk->dev_ops && blk->dev_ops->drained_begin) {
2074             blk->dev_ops->drained_begin(blk->dev_opaque);
2075         }
2076     }
2077
2078     /* Note that blk->root may not be accessible here yet if we are just
2079      * attaching to a BlockDriverState that is drained. Use child instead. */
2080
2081     if (atomic_fetch_inc(&blk->public.throttle_group_member.io_limits_disabled) == 0) {
2082         throttle_group_restart_tgm(&blk->public.throttle_group_member);
2083     }
2084 }
2085
2086 static void blk_root_drained_end(BdrvChild *child)
2087 {
2088     BlockBackend *blk = child->opaque;
2089     assert(blk->quiesce_counter);
2090
2091     assert(blk->public.throttle_group_member.io_limits_disabled);
2092     atomic_dec(&blk->public.throttle_group_member.io_limits_disabled);
2093
2094     if (--blk->quiesce_counter == 0) {
2095         if (blk->dev_ops && blk->dev_ops->drained_end) {
2096             blk->dev_ops->drained_end(blk->dev_opaque);
2097         }
2098     }
2099 }
2100
2101 void blk_register_buf(BlockBackend *blk, void *host, size_t size)
2102 {
2103     bdrv_register_buf(blk_bs(blk), host, size);
2104 }
2105
2106 void blk_unregister_buf(BlockBackend *blk, void *host)
2107 {
2108     bdrv_unregister_buf(blk_bs(blk), host);
2109 }
This page took 0.145671 seconds and 4 git commands to generate.