xref: /openbmc/qemu/block/block-backend.c (revision f348b6d1a53e5271cf1c9f9acc4646b4b98c1771)
1 /*
2  * QEMU Block backends
3  *
4  * Copyright (C) 2014 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-event.h"
21 #include "qemu/id.h"
22 
23 /* Number of coroutines to reserve per attached device model */
24 #define COROUTINE_POOL_RESERVATION 64
25 
26 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
27 
28 static AioContext *blk_aiocb_get_aio_context(BlockAIOCB *acb);
29 
30 struct BlockBackend {
31     char *name;
32     int refcnt;
33     BdrvChild *root;
34     DriveInfo *legacy_dinfo;    /* null unless created by drive_new() */
35     QTAILQ_ENTRY(BlockBackend) link;         /* for block_backends */
36     QTAILQ_ENTRY(BlockBackend) monitor_link; /* for monitor_block_backends */
37 
38     void *dev;                  /* attached device model, if any */
39     /* TODO change to DeviceState when all users are qdevified */
40     const BlockDevOps *dev_ops;
41     void *dev_opaque;
42 
43     /* the block size for which the guest device expects atomicity */
44     int guest_block_size;
45 
46     /* If the BDS tree is removed, some of its options are stored here (which
47      * can be used to restore those options in the new BDS on insert) */
48     BlockBackendRootState root_state;
49 
50     /* I/O stats (display with "info blockstats"). */
51     BlockAcctStats stats;
52 
53     BlockdevOnError on_read_error, on_write_error;
54     bool iostatus_enabled;
55     BlockDeviceIoStatus iostatus;
56 
57     bool allow_write_beyond_eof;
58 
59     NotifierList remove_bs_notifiers, insert_bs_notifiers;
60 };
61 
62 typedef struct BlockBackendAIOCB {
63     BlockAIOCB common;
64     QEMUBH *bh;
65     BlockBackend *blk;
66     int ret;
67 } BlockBackendAIOCB;
68 
69 static const AIOCBInfo block_backend_aiocb_info = {
70     .get_aio_context = blk_aiocb_get_aio_context,
71     .aiocb_size = sizeof(BlockBackendAIOCB),
72 };
73 
74 static void drive_info_del(DriveInfo *dinfo);
75 
76 /* All BlockBackends */
77 static QTAILQ_HEAD(, BlockBackend) block_backends =
78     QTAILQ_HEAD_INITIALIZER(block_backends);
79 
80 /* All BlockBackends referenced by the monitor and which are iterated through by
81  * blk_next() */
82 static QTAILQ_HEAD(, BlockBackend) monitor_block_backends =
83     QTAILQ_HEAD_INITIALIZER(monitor_block_backends);
84 
85 static void blk_root_inherit_options(int *child_flags, QDict *child_options,
86                                      int parent_flags, QDict *parent_options)
87 {
88     /* We're not supposed to call this function for root nodes */
89     abort();
90 }
91 
92 static const BdrvChildRole child_root = {
93     .inherit_options = blk_root_inherit_options,
94 };
95 
96 /*
97  * Create a new BlockBackend with a reference count of one.
98  * Store an error through @errp on failure, unless it's null.
99  * Return the new BlockBackend on success, null on failure.
100  */
101 BlockBackend *blk_new(Error **errp)
102 {
103     BlockBackend *blk;
104 
105     blk = g_new0(BlockBackend, 1);
106     blk->refcnt = 1;
107     notifier_list_init(&blk->remove_bs_notifiers);
108     notifier_list_init(&blk->insert_bs_notifiers);
109     QTAILQ_INSERT_TAIL(&block_backends, blk, link);
110     return blk;
111 }
112 
113 /*
114  * Create a new BlockBackend with a new BlockDriverState attached.
115  * Otherwise just like blk_new(), which see.
116  */
117 BlockBackend *blk_new_with_bs(Error **errp)
118 {
119     BlockBackend *blk;
120     BlockDriverState *bs;
121 
122     blk = blk_new(errp);
123     if (!blk) {
124         return NULL;
125     }
126 
127     bs = bdrv_new_root();
128     blk->root = bdrv_root_attach_child(bs, "root", &child_root);
129     bs->blk = blk;
130     return blk;
131 }
132 
133 /*
134  * Calls blk_new_with_bs() and then calls bdrv_open() on the BlockDriverState.
135  *
136  * Just as with bdrv_open(), after having called this function the reference to
137  * @options belongs to the block layer (even on failure).
138  *
139  * TODO: Remove @filename and @flags; it should be possible to specify a whole
140  * BDS tree just by specifying the @options QDict (or @reference,
141  * alternatively). At the time of adding this function, this is not possible,
142  * though, so callers of this function have to be able to specify @filename and
143  * @flags.
144  */
145 BlockBackend *blk_new_open(const char *filename, const char *reference,
146                            QDict *options, int flags, Error **errp)
147 {
148     BlockBackend *blk;
149     int ret;
150 
151     blk = blk_new_with_bs(errp);
152     if (!blk) {
153         QDECREF(options);
154         return NULL;
155     }
156 
157     ret = bdrv_open(&blk->root->bs, filename, reference, options, flags, errp);
158     if (ret < 0) {
159         blk_unref(blk);
160         return NULL;
161     }
162 
163     return blk;
164 }
165 
166 static void blk_delete(BlockBackend *blk)
167 {
168     assert(!blk->refcnt);
169     assert(!blk->name);
170     assert(!blk->dev);
171     if (blk->root) {
172         blk_remove_bs(blk);
173     }
174     assert(QLIST_EMPTY(&blk->remove_bs_notifiers.notifiers));
175     assert(QLIST_EMPTY(&blk->insert_bs_notifiers.notifiers));
176     if (blk->root_state.throttle_state) {
177         g_free(blk->root_state.throttle_group);
178         throttle_group_unref(blk->root_state.throttle_state);
179     }
180     QTAILQ_REMOVE(&block_backends, blk, link);
181     drive_info_del(blk->legacy_dinfo);
182     block_acct_cleanup(&blk->stats);
183     g_free(blk);
184 }
185 
186 static void drive_info_del(DriveInfo *dinfo)
187 {
188     if (!dinfo) {
189         return;
190     }
191     qemu_opts_del(dinfo->opts);
192     g_free(dinfo->serial);
193     g_free(dinfo);
194 }
195 
196 int blk_get_refcnt(BlockBackend *blk)
197 {
198     return blk ? blk->refcnt : 0;
199 }
200 
201 /*
202  * Increment @blk's reference count.
203  * @blk must not be null.
204  */
205 void blk_ref(BlockBackend *blk)
206 {
207     blk->refcnt++;
208 }
209 
210 /*
211  * Decrement @blk's reference count.
212  * If this drops it to zero, destroy @blk.
213  * For convenience, do nothing if @blk is null.
214  */
215 void blk_unref(BlockBackend *blk)
216 {
217     if (blk) {
218         assert(blk->refcnt > 0);
219         if (!--blk->refcnt) {
220             blk_delete(blk);
221         }
222     }
223 }
224 
225 /*
226  * Behaves similarly to blk_next() but iterates over all BlockBackends, even the
227  * ones which are hidden (i.e. are not referenced by the monitor).
228  */
229 static BlockBackend *blk_all_next(BlockBackend *blk)
230 {
231     return blk ? QTAILQ_NEXT(blk, link)
232                : QTAILQ_FIRST(&block_backends);
233 }
234 
235 void blk_remove_all_bs(void)
236 {
237     BlockBackend *blk = NULL;
238 
239     while ((blk = blk_all_next(blk)) != NULL) {
240         AioContext *ctx = blk_get_aio_context(blk);
241 
242         aio_context_acquire(ctx);
243         if (blk->root) {
244             blk_remove_bs(blk);
245         }
246         aio_context_release(ctx);
247     }
248 }
249 
250 /*
251  * Return the monitor-owned BlockBackend after @blk.
252  * If @blk is null, return the first one.
253  * Else, return @blk's next sibling, which may be null.
254  *
255  * To iterate over all BlockBackends, do
256  * for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
257  *     ...
258  * }
259  */
260 BlockBackend *blk_next(BlockBackend *blk)
261 {
262     return blk ? QTAILQ_NEXT(blk, monitor_link)
263                : QTAILQ_FIRST(&monitor_block_backends);
264 }
265 
266 /*
267  * Iterates over all BlockDriverStates which are attached to a BlockBackend.
268  * This function is for use by bdrv_next().
269  *
270  * @bs must be NULL or a BDS that is attached to a BB.
271  */
272 BlockDriverState *blk_next_root_bs(BlockDriverState *bs)
273 {
274     BlockBackend *blk;
275 
276     if (bs) {
277         assert(bs->blk);
278         blk = bs->blk;
279     } else {
280         blk = NULL;
281     }
282 
283     do {
284         blk = blk_all_next(blk);
285     } while (blk && !blk->root);
286 
287     return blk ? blk->root->bs : NULL;
288 }
289 
290 /*
291  * Add a BlockBackend into the list of backends referenced by the monitor, with
292  * the given @name acting as the handle for the monitor.
293  * Strictly for use by blockdev.c.
294  *
295  * @name must not be null or empty.
296  *
297  * Returns true on success and false on failure. In the latter case, an Error
298  * object is returned through @errp.
299  */
300 bool monitor_add_blk(BlockBackend *blk, const char *name, Error **errp)
301 {
302     assert(!blk->name);
303     assert(name && name[0]);
304 
305     if (!id_wellformed(name)) {
306         error_setg(errp, "Invalid device name");
307         return false;
308     }
309     if (blk_by_name(name)) {
310         error_setg(errp, "Device with id '%s' already exists", name);
311         return false;
312     }
313     if (bdrv_find_node(name)) {
314         error_setg(errp,
315                    "Device name '%s' conflicts with an existing node name",
316                    name);
317         return false;
318     }
319 
320     blk->name = g_strdup(name);
321     QTAILQ_INSERT_TAIL(&monitor_block_backends, blk, monitor_link);
322     return true;
323 }
324 
325 /*
326  * Remove a BlockBackend from the list of backends referenced by the monitor.
327  * Strictly for use by blockdev.c.
328  */
329 void monitor_remove_blk(BlockBackend *blk)
330 {
331     if (!blk->name) {
332         return;
333     }
334 
335     QTAILQ_REMOVE(&monitor_block_backends, blk, monitor_link);
336     g_free(blk->name);
337     blk->name = NULL;
338 }
339 
340 /*
341  * Return @blk's name, a non-null string.
342  * Returns an empty string iff @blk is not referenced by the monitor.
343  */
344 const char *blk_name(BlockBackend *blk)
345 {
346     return blk->name ?: "";
347 }
348 
349 /*
350  * Return the BlockBackend with name @name if it exists, else null.
351  * @name must not be null.
352  */
353 BlockBackend *blk_by_name(const char *name)
354 {
355     BlockBackend *blk = NULL;
356 
357     assert(name);
358     while ((blk = blk_next(blk)) != NULL) {
359         if (!strcmp(name, blk->name)) {
360             return blk;
361         }
362     }
363     return NULL;
364 }
365 
366 /*
367  * Return the BlockDriverState attached to @blk if any, else null.
368  */
369 BlockDriverState *blk_bs(BlockBackend *blk)
370 {
371     return blk->root ? blk->root->bs : NULL;
372 }
373 
374 /*
375  * Changes the BlockDriverState attached to @blk
376  */
377 void blk_set_bs(BlockBackend *blk, BlockDriverState *bs)
378 {
379     bdrv_ref(bs);
380 
381     if (blk->root) {
382         blk->root->bs->blk = NULL;
383         bdrv_root_unref_child(blk->root);
384     }
385     assert(bs->blk == NULL);
386 
387     blk->root = bdrv_root_attach_child(bs, "root", &child_root);
388     bs->blk = blk;
389 }
390 
391 /*
392  * Return @blk's DriveInfo if any, else null.
393  */
394 DriveInfo *blk_legacy_dinfo(BlockBackend *blk)
395 {
396     return blk->legacy_dinfo;
397 }
398 
399 /*
400  * Set @blk's DriveInfo to @dinfo, and return it.
401  * @blk must not have a DriveInfo set already.
402  * No other BlockBackend may have the same DriveInfo set.
403  */
404 DriveInfo *blk_set_legacy_dinfo(BlockBackend *blk, DriveInfo *dinfo)
405 {
406     assert(!blk->legacy_dinfo);
407     return blk->legacy_dinfo = dinfo;
408 }
409 
410 /*
411  * Return the BlockBackend with DriveInfo @dinfo.
412  * It must exist.
413  */
414 BlockBackend *blk_by_legacy_dinfo(DriveInfo *dinfo)
415 {
416     BlockBackend *blk = NULL;
417 
418     while ((blk = blk_next(blk)) != NULL) {
419         if (blk->legacy_dinfo == dinfo) {
420             return blk;
421         }
422     }
423     abort();
424 }
425 
426 /*
427  * Disassociates the currently associated BlockDriverState from @blk.
428  */
429 void blk_remove_bs(BlockBackend *blk)
430 {
431     assert(blk->root->bs->blk == blk);
432 
433     notifier_list_notify(&blk->remove_bs_notifiers, blk);
434 
435     blk_update_root_state(blk);
436 
437     blk->root->bs->blk = NULL;
438     bdrv_root_unref_child(blk->root);
439     blk->root = NULL;
440 }
441 
442 /*
443  * Associates a new BlockDriverState with @blk.
444  */
445 void blk_insert_bs(BlockBackend *blk, BlockDriverState *bs)
446 {
447     assert(!blk->root && !bs->blk);
448     bdrv_ref(bs);
449     blk->root = bdrv_root_attach_child(bs, "root", &child_root);
450     bs->blk = blk;
451 
452     notifier_list_notify(&blk->insert_bs_notifiers, blk);
453 }
454 
455 /*
456  * Attach device model @dev to @blk.
457  * Return 0 on success, -EBUSY when a device model is attached already.
458  */
459 int blk_attach_dev(BlockBackend *blk, void *dev)
460 /* TODO change to DeviceState *dev when all users are qdevified */
461 {
462     if (blk->dev) {
463         return -EBUSY;
464     }
465     blk_ref(blk);
466     blk->dev = dev;
467     blk_iostatus_reset(blk);
468     return 0;
469 }
470 
471 /*
472  * Attach device model @dev to @blk.
473  * @blk must not have a device model attached already.
474  * TODO qdevified devices don't use this, remove when devices are qdevified
475  */
476 void blk_attach_dev_nofail(BlockBackend *blk, void *dev)
477 {
478     if (blk_attach_dev(blk, dev) < 0) {
479         abort();
480     }
481 }
482 
483 /*
484  * Detach device model @dev from @blk.
485  * @dev must be currently attached to @blk.
486  */
487 void blk_detach_dev(BlockBackend *blk, void *dev)
488 /* TODO change to DeviceState *dev when all users are qdevified */
489 {
490     assert(blk->dev == dev);
491     blk->dev = NULL;
492     blk->dev_ops = NULL;
493     blk->dev_opaque = NULL;
494     blk->guest_block_size = 512;
495     blk_unref(blk);
496 }
497 
498 /*
499  * Return the device model attached to @blk if any, else null.
500  */
501 void *blk_get_attached_dev(BlockBackend *blk)
502 /* TODO change to return DeviceState * when all users are qdevified */
503 {
504     return blk->dev;
505 }
506 
507 /*
508  * Set @blk's device model callbacks to @ops.
509  * @opaque is the opaque argument to pass to the callbacks.
510  * This is for use by device models.
511  */
512 void blk_set_dev_ops(BlockBackend *blk, const BlockDevOps *ops,
513                      void *opaque)
514 {
515     blk->dev_ops = ops;
516     blk->dev_opaque = opaque;
517 }
518 
519 /*
520  * Notify @blk's attached device model of media change.
521  * If @load is true, notify of media load.
522  * Else, notify of media eject.
523  * Also send DEVICE_TRAY_MOVED events as appropriate.
524  */
525 void blk_dev_change_media_cb(BlockBackend *blk, bool load)
526 {
527     if (blk->dev_ops && blk->dev_ops->change_media_cb) {
528         bool tray_was_open, tray_is_open;
529 
530         tray_was_open = blk_dev_is_tray_open(blk);
531         blk->dev_ops->change_media_cb(blk->dev_opaque, load);
532         tray_is_open = blk_dev_is_tray_open(blk);
533 
534         if (tray_was_open != tray_is_open) {
535             qapi_event_send_device_tray_moved(blk_name(blk), tray_is_open,
536                                               &error_abort);
537         }
538     }
539 }
540 
541 /*
542  * Does @blk's attached device model have removable media?
543  * %true if no device model is attached.
544  */
545 bool blk_dev_has_removable_media(BlockBackend *blk)
546 {
547     return !blk->dev || (blk->dev_ops && blk->dev_ops->change_media_cb);
548 }
549 
550 /*
551  * Does @blk's attached device model have a tray?
552  */
553 bool blk_dev_has_tray(BlockBackend *blk)
554 {
555     return blk->dev_ops && blk->dev_ops->is_tray_open;
556 }
557 
558 /*
559  * Notify @blk's attached device model of a media eject request.
560  * If @force is true, the medium is about to be yanked out forcefully.
561  */
562 void blk_dev_eject_request(BlockBackend *blk, bool force)
563 {
564     if (blk->dev_ops && blk->dev_ops->eject_request_cb) {
565         blk->dev_ops->eject_request_cb(blk->dev_opaque, force);
566     }
567 }
568 
569 /*
570  * Does @blk's attached device model have a tray, and is it open?
571  */
572 bool blk_dev_is_tray_open(BlockBackend *blk)
573 {
574     if (blk_dev_has_tray(blk)) {
575         return blk->dev_ops->is_tray_open(blk->dev_opaque);
576     }
577     return false;
578 }
579 
580 /*
581  * Does @blk's attached device model have the medium locked?
582  * %false if the device model has no such lock.
583  */
584 bool blk_dev_is_medium_locked(BlockBackend *blk)
585 {
586     if (blk->dev_ops && blk->dev_ops->is_medium_locked) {
587         return blk->dev_ops->is_medium_locked(blk->dev_opaque);
588     }
589     return false;
590 }
591 
592 /*
593  * Notify @blk's attached device model of a backend size change.
594  */
595 void blk_dev_resize_cb(BlockBackend *blk)
596 {
597     if (blk->dev_ops && blk->dev_ops->resize_cb) {
598         blk->dev_ops->resize_cb(blk->dev_opaque);
599     }
600 }
601 
602 void blk_iostatus_enable(BlockBackend *blk)
603 {
604     blk->iostatus_enabled = true;
605     blk->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
606 }
607 
608 /* The I/O status is only enabled if the drive explicitly
609  * enables it _and_ the VM is configured to stop on errors */
610 bool blk_iostatus_is_enabled(const BlockBackend *blk)
611 {
612     return (blk->iostatus_enabled &&
613            (blk->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
614             blk->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
615             blk->on_read_error == BLOCKDEV_ON_ERROR_STOP));
616 }
617 
618 BlockDeviceIoStatus blk_iostatus(const BlockBackend *blk)
619 {
620     return blk->iostatus;
621 }
622 
623 void blk_iostatus_disable(BlockBackend *blk)
624 {
625     blk->iostatus_enabled = false;
626 }
627 
628 void blk_iostatus_reset(BlockBackend *blk)
629 {
630     if (blk_iostatus_is_enabled(blk)) {
631         BlockDriverState *bs = blk_bs(blk);
632         blk->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
633         if (bs && bs->job) {
634             block_job_iostatus_reset(bs->job);
635         }
636     }
637 }
638 
639 void blk_iostatus_set_err(BlockBackend *blk, int error)
640 {
641     assert(blk_iostatus_is_enabled(blk));
642     if (blk->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
643         blk->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
644                                           BLOCK_DEVICE_IO_STATUS_FAILED;
645     }
646 }
647 
648 void blk_set_allow_write_beyond_eof(BlockBackend *blk, bool allow)
649 {
650     blk->allow_write_beyond_eof = allow;
651 }
652 
653 static int blk_check_byte_request(BlockBackend *blk, int64_t offset,
654                                   size_t size)
655 {
656     int64_t len;
657 
658     if (size > INT_MAX) {
659         return -EIO;
660     }
661 
662     if (!blk_is_available(blk)) {
663         return -ENOMEDIUM;
664     }
665 
666     if (offset < 0) {
667         return -EIO;
668     }
669 
670     if (!blk->allow_write_beyond_eof) {
671         len = blk_getlength(blk);
672         if (len < 0) {
673             return len;
674         }
675 
676         if (offset > len || len - offset < size) {
677             return -EIO;
678         }
679     }
680 
681     return 0;
682 }
683 
684 static int blk_check_request(BlockBackend *blk, int64_t sector_num,
685                              int nb_sectors)
686 {
687     if (sector_num < 0 || sector_num > INT64_MAX / BDRV_SECTOR_SIZE) {
688         return -EIO;
689     }
690 
691     if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) {
692         return -EIO;
693     }
694 
695     return blk_check_byte_request(blk, sector_num * BDRV_SECTOR_SIZE,
696                                   nb_sectors * BDRV_SECTOR_SIZE);
697 }
698 
699 static int coroutine_fn blk_co_preadv(BlockBackend *blk, int64_t offset,
700                                       unsigned int bytes, QEMUIOVector *qiov,
701                                       BdrvRequestFlags flags)
702 {
703     int ret = blk_check_byte_request(blk, offset, bytes);
704     if (ret < 0) {
705         return ret;
706     }
707 
708     return bdrv_co_do_preadv(blk_bs(blk), offset, bytes, qiov, flags);
709 }
710 
711 static int coroutine_fn blk_co_pwritev(BlockBackend *blk, int64_t offset,
712                                       unsigned int bytes, QEMUIOVector *qiov,
713                                       BdrvRequestFlags flags)
714 {
715     int ret = blk_check_byte_request(blk, offset, bytes);
716     if (ret < 0) {
717         return ret;
718     }
719 
720     return bdrv_co_do_pwritev(blk_bs(blk), offset, bytes, qiov, flags);
721 }
722 
723 typedef struct BlkRwCo {
724     BlockBackend *blk;
725     int64_t offset;
726     QEMUIOVector *qiov;
727     int ret;
728     BdrvRequestFlags flags;
729 } BlkRwCo;
730 
731 static void blk_read_entry(void *opaque)
732 {
733     BlkRwCo *rwco = opaque;
734 
735     rwco->ret = blk_co_preadv(rwco->blk, rwco->offset, rwco->qiov->size,
736                               rwco->qiov, rwco->flags);
737 }
738 
739 static void blk_write_entry(void *opaque)
740 {
741     BlkRwCo *rwco = opaque;
742 
743     rwco->ret = blk_co_pwritev(rwco->blk, rwco->offset, rwco->qiov->size,
744                                rwco->qiov, rwco->flags);
745 }
746 
747 static int blk_prw(BlockBackend *blk, int64_t offset, uint8_t *buf,
748                    int64_t bytes, CoroutineEntry co_entry,
749                    BdrvRequestFlags flags)
750 {
751     AioContext *aio_context;
752     QEMUIOVector qiov;
753     struct iovec iov;
754     Coroutine *co;
755     BlkRwCo rwco;
756 
757     iov = (struct iovec) {
758         .iov_base = buf,
759         .iov_len = bytes,
760     };
761     qemu_iovec_init_external(&qiov, &iov, 1);
762 
763     rwco = (BlkRwCo) {
764         .blk    = blk,
765         .offset = offset,
766         .qiov   = &qiov,
767         .flags  = flags,
768         .ret    = NOT_DONE,
769     };
770 
771     co = qemu_coroutine_create(co_entry);
772     qemu_coroutine_enter(co, &rwco);
773 
774     aio_context = blk_get_aio_context(blk);
775     while (rwco.ret == NOT_DONE) {
776         aio_poll(aio_context, true);
777     }
778 
779     return rwco.ret;
780 }
781 
782 static int blk_rw(BlockBackend *blk, int64_t sector_num, uint8_t *buf,
783                   int nb_sectors, CoroutineEntry co_entry,
784                   BdrvRequestFlags flags)
785 {
786     if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
787         return -EINVAL;
788     }
789 
790     return blk_prw(blk, sector_num << BDRV_SECTOR_BITS, buf,
791                    nb_sectors << BDRV_SECTOR_BITS, co_entry, flags);
792 }
793 
794 int blk_read(BlockBackend *blk, int64_t sector_num, uint8_t *buf,
795              int nb_sectors)
796 {
797     return blk_rw(blk, sector_num, buf, nb_sectors, blk_read_entry, 0);
798 }
799 
800 int blk_read_unthrottled(BlockBackend *blk, int64_t sector_num, uint8_t *buf,
801                          int nb_sectors)
802 {
803     BlockDriverState *bs = blk_bs(blk);
804     bool enabled;
805     int ret;
806 
807     ret = blk_check_request(blk, sector_num, nb_sectors);
808     if (ret < 0) {
809         return ret;
810     }
811 
812     enabled = bs->io_limits_enabled;
813     bs->io_limits_enabled = false;
814     ret = blk_read(blk, sector_num, buf, nb_sectors);
815     bs->io_limits_enabled = enabled;
816     return ret;
817 }
818 
819 int blk_write(BlockBackend *blk, int64_t sector_num, const uint8_t *buf,
820               int nb_sectors)
821 {
822     return blk_rw(blk, sector_num, (uint8_t*) buf, nb_sectors,
823                   blk_write_entry, 0);
824 }
825 
826 int blk_write_zeroes(BlockBackend *blk, int64_t sector_num,
827                      int nb_sectors, BdrvRequestFlags flags)
828 {
829     return blk_rw(blk, sector_num, NULL, nb_sectors, blk_write_entry,
830                   BDRV_REQ_ZERO_WRITE);
831 }
832 
833 static void error_callback_bh(void *opaque)
834 {
835     struct BlockBackendAIOCB *acb = opaque;
836     qemu_bh_delete(acb->bh);
837     acb->common.cb(acb->common.opaque, acb->ret);
838     qemu_aio_unref(acb);
839 }
840 
841 BlockAIOCB *blk_abort_aio_request(BlockBackend *blk,
842                                   BlockCompletionFunc *cb,
843                                   void *opaque, int ret)
844 {
845     struct BlockBackendAIOCB *acb;
846     QEMUBH *bh;
847 
848     acb = blk_aio_get(&block_backend_aiocb_info, blk, cb, opaque);
849     acb->blk = blk;
850     acb->ret = ret;
851 
852     bh = aio_bh_new(blk_get_aio_context(blk), error_callback_bh, acb);
853     acb->bh = bh;
854     qemu_bh_schedule(bh);
855 
856     return &acb->common;
857 }
858 
859 typedef struct BlkAioEmAIOCB {
860     BlockAIOCB common;
861     BlkRwCo rwco;
862     bool has_returned;
863     QEMUBH* bh;
864 } BlkAioEmAIOCB;
865 
866 static const AIOCBInfo blk_aio_em_aiocb_info = {
867     .aiocb_size         = sizeof(BlkAioEmAIOCB),
868 };
869 
870 static void blk_aio_complete(BlkAioEmAIOCB *acb)
871 {
872     if (acb->bh) {
873         assert(acb->has_returned);
874         qemu_bh_delete(acb->bh);
875     }
876     if (acb->has_returned) {
877         acb->common.cb(acb->common.opaque, acb->rwco.ret);
878         qemu_aio_unref(acb);
879     }
880 }
881 
882 static void blk_aio_complete_bh(void *opaque)
883 {
884     blk_aio_complete(opaque);
885 }
886 
887 static BlockAIOCB *blk_aio_prwv(BlockBackend *blk, int64_t offset,
888                                 QEMUIOVector *qiov, CoroutineEntry co_entry,
889                                 BdrvRequestFlags flags,
890                                 BlockCompletionFunc *cb, void *opaque)
891 {
892     BlkAioEmAIOCB *acb;
893     Coroutine *co;
894 
895     acb = blk_aio_get(&blk_aio_em_aiocb_info, blk, cb, opaque);
896     acb->rwco = (BlkRwCo) {
897         .blk    = blk,
898         .offset = offset,
899         .qiov   = qiov,
900         .flags  = flags,
901         .ret    = NOT_DONE,
902     };
903     acb->bh = NULL;
904     acb->has_returned = false;
905 
906     co = qemu_coroutine_create(co_entry);
907     qemu_coroutine_enter(co, acb);
908 
909     acb->has_returned = true;
910     if (acb->rwco.ret != NOT_DONE) {
911         acb->bh = aio_bh_new(blk_get_aio_context(blk), blk_aio_complete_bh, acb);
912         qemu_bh_schedule(acb->bh);
913     }
914 
915     return &acb->common;
916 }
917 
918 static void blk_aio_read_entry(void *opaque)
919 {
920     BlkAioEmAIOCB *acb = opaque;
921     BlkRwCo *rwco = &acb->rwco;
922 
923     rwco->ret = blk_co_preadv(rwco->blk, rwco->offset, rwco->qiov->size,
924                               rwco->qiov, rwco->flags);
925     blk_aio_complete(acb);
926 }
927 
928 static void blk_aio_write_entry(void *opaque)
929 {
930     BlkAioEmAIOCB *acb = opaque;
931     BlkRwCo *rwco = &acb->rwco;
932 
933     rwco->ret = blk_co_pwritev(rwco->blk, rwco->offset,
934                                rwco->qiov ? rwco->qiov->size : 0,
935                                rwco->qiov, rwco->flags);
936     blk_aio_complete(acb);
937 }
938 
939 BlockAIOCB *blk_aio_write_zeroes(BlockBackend *blk, int64_t sector_num,
940                                  int nb_sectors, BdrvRequestFlags flags,
941                                  BlockCompletionFunc *cb, void *opaque)
942 {
943     if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
944         return blk_abort_aio_request(blk, cb, opaque, -EINVAL);
945     }
946 
947     return blk_aio_prwv(blk, sector_num << BDRV_SECTOR_BITS, NULL,
948                         blk_aio_write_entry, BDRV_REQ_ZERO_WRITE, cb, opaque);
949 }
950 
951 int blk_pread(BlockBackend *blk, int64_t offset, void *buf, int count)
952 {
953     int ret = blk_prw(blk, offset, buf, count, blk_read_entry, 0);
954     if (ret < 0) {
955         return ret;
956     }
957     return count;
958 }
959 
960 int blk_pwrite(BlockBackend *blk, int64_t offset, const void *buf, int count)
961 {
962     int ret = blk_prw(blk, offset, (void*) buf, count, blk_write_entry, 0);
963     if (ret < 0) {
964         return ret;
965     }
966     return count;
967 }
968 
969 int64_t blk_getlength(BlockBackend *blk)
970 {
971     if (!blk_is_available(blk)) {
972         return -ENOMEDIUM;
973     }
974 
975     return bdrv_getlength(blk_bs(blk));
976 }
977 
978 void blk_get_geometry(BlockBackend *blk, uint64_t *nb_sectors_ptr)
979 {
980     if (!blk_bs(blk)) {
981         *nb_sectors_ptr = 0;
982     } else {
983         bdrv_get_geometry(blk_bs(blk), nb_sectors_ptr);
984     }
985 }
986 
987 int64_t blk_nb_sectors(BlockBackend *blk)
988 {
989     if (!blk_is_available(blk)) {
990         return -ENOMEDIUM;
991     }
992 
993     return bdrv_nb_sectors(blk_bs(blk));
994 }
995 
996 BlockAIOCB *blk_aio_readv(BlockBackend *blk, int64_t sector_num,
997                           QEMUIOVector *iov, int nb_sectors,
998                           BlockCompletionFunc *cb, void *opaque)
999 {
1000     if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
1001         return blk_abort_aio_request(blk, cb, opaque, -EINVAL);
1002     }
1003 
1004     return blk_aio_prwv(blk, sector_num << BDRV_SECTOR_BITS, iov,
1005                         blk_aio_read_entry, 0, cb, opaque);
1006 }
1007 
1008 BlockAIOCB *blk_aio_writev(BlockBackend *blk, int64_t sector_num,
1009                            QEMUIOVector *iov, int nb_sectors,
1010                            BlockCompletionFunc *cb, void *opaque)
1011 {
1012     if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
1013         return blk_abort_aio_request(blk, cb, opaque, -EINVAL);
1014     }
1015 
1016     return blk_aio_prwv(blk, sector_num << BDRV_SECTOR_BITS, iov,
1017                         blk_aio_write_entry, 0, cb, opaque);
1018 }
1019 
1020 BlockAIOCB *blk_aio_flush(BlockBackend *blk,
1021                           BlockCompletionFunc *cb, void *opaque)
1022 {
1023     if (!blk_is_available(blk)) {
1024         return blk_abort_aio_request(blk, cb, opaque, -ENOMEDIUM);
1025     }
1026 
1027     return bdrv_aio_flush(blk_bs(blk), cb, opaque);
1028 }
1029 
1030 BlockAIOCB *blk_aio_discard(BlockBackend *blk,
1031                             int64_t sector_num, int nb_sectors,
1032                             BlockCompletionFunc *cb, void *opaque)
1033 {
1034     int ret = blk_check_request(blk, sector_num, nb_sectors);
1035     if (ret < 0) {
1036         return blk_abort_aio_request(blk, cb, opaque, ret);
1037     }
1038 
1039     return bdrv_aio_discard(blk_bs(blk), sector_num, nb_sectors, cb, opaque);
1040 }
1041 
1042 void blk_aio_cancel(BlockAIOCB *acb)
1043 {
1044     bdrv_aio_cancel(acb);
1045 }
1046 
1047 void blk_aio_cancel_async(BlockAIOCB *acb)
1048 {
1049     bdrv_aio_cancel_async(acb);
1050 }
1051 
1052 int blk_aio_multiwrite(BlockBackend *blk, BlockRequest *reqs, int num_reqs)
1053 {
1054     int i, ret;
1055 
1056     for (i = 0; i < num_reqs; i++) {
1057         ret = blk_check_request(blk, reqs[i].sector, reqs[i].nb_sectors);
1058         if (ret < 0) {
1059             return ret;
1060         }
1061     }
1062 
1063     return bdrv_aio_multiwrite(blk_bs(blk), reqs, num_reqs);
1064 }
1065 
1066 int blk_ioctl(BlockBackend *blk, unsigned long int req, void *buf)
1067 {
1068     if (!blk_is_available(blk)) {
1069         return -ENOMEDIUM;
1070     }
1071 
1072     return bdrv_ioctl(blk_bs(blk), req, buf);
1073 }
1074 
1075 BlockAIOCB *blk_aio_ioctl(BlockBackend *blk, unsigned long int req, void *buf,
1076                           BlockCompletionFunc *cb, void *opaque)
1077 {
1078     if (!blk_is_available(blk)) {
1079         return blk_abort_aio_request(blk, cb, opaque, -ENOMEDIUM);
1080     }
1081 
1082     return bdrv_aio_ioctl(blk_bs(blk), req, buf, cb, opaque);
1083 }
1084 
1085 int blk_co_discard(BlockBackend *blk, int64_t sector_num, int nb_sectors)
1086 {
1087     int ret = blk_check_request(blk, sector_num, nb_sectors);
1088     if (ret < 0) {
1089         return ret;
1090     }
1091 
1092     return bdrv_co_discard(blk_bs(blk), sector_num, nb_sectors);
1093 }
1094 
1095 int blk_co_flush(BlockBackend *blk)
1096 {
1097     if (!blk_is_available(blk)) {
1098         return -ENOMEDIUM;
1099     }
1100 
1101     return bdrv_co_flush(blk_bs(blk));
1102 }
1103 
1104 int blk_flush(BlockBackend *blk)
1105 {
1106     if (!blk_is_available(blk)) {
1107         return -ENOMEDIUM;
1108     }
1109 
1110     return bdrv_flush(blk_bs(blk));
1111 }
1112 
1113 void blk_drain(BlockBackend *blk)
1114 {
1115     if (blk_bs(blk)) {
1116         bdrv_drain(blk_bs(blk));
1117     }
1118 }
1119 
1120 void blk_drain_all(void)
1121 {
1122     bdrv_drain_all();
1123 }
1124 
1125 void blk_set_on_error(BlockBackend *blk, BlockdevOnError on_read_error,
1126                       BlockdevOnError on_write_error)
1127 {
1128     blk->on_read_error = on_read_error;
1129     blk->on_write_error = on_write_error;
1130 }
1131 
1132 BlockdevOnError blk_get_on_error(BlockBackend *blk, bool is_read)
1133 {
1134     return is_read ? blk->on_read_error : blk->on_write_error;
1135 }
1136 
1137 BlockErrorAction blk_get_error_action(BlockBackend *blk, bool is_read,
1138                                       int error)
1139 {
1140     BlockdevOnError on_err = blk_get_on_error(blk, is_read);
1141 
1142     switch (on_err) {
1143     case BLOCKDEV_ON_ERROR_ENOSPC:
1144         return (error == ENOSPC) ?
1145                BLOCK_ERROR_ACTION_STOP : BLOCK_ERROR_ACTION_REPORT;
1146     case BLOCKDEV_ON_ERROR_STOP:
1147         return BLOCK_ERROR_ACTION_STOP;
1148     case BLOCKDEV_ON_ERROR_REPORT:
1149         return BLOCK_ERROR_ACTION_REPORT;
1150     case BLOCKDEV_ON_ERROR_IGNORE:
1151         return BLOCK_ERROR_ACTION_IGNORE;
1152     default:
1153         abort();
1154     }
1155 }
1156 
1157 static void send_qmp_error_event(BlockBackend *blk,
1158                                  BlockErrorAction action,
1159                                  bool is_read, int error)
1160 {
1161     IoOperationType optype;
1162 
1163     optype = is_read ? IO_OPERATION_TYPE_READ : IO_OPERATION_TYPE_WRITE;
1164     qapi_event_send_block_io_error(blk_name(blk), optype, action,
1165                                    blk_iostatus_is_enabled(blk),
1166                                    error == ENOSPC, strerror(error),
1167                                    &error_abort);
1168 }
1169 
1170 /* This is done by device models because, while the block layer knows
1171  * about the error, it does not know whether an operation comes from
1172  * the device or the block layer (from a job, for example).
1173  */
1174 void blk_error_action(BlockBackend *blk, BlockErrorAction action,
1175                       bool is_read, int error)
1176 {
1177     assert(error >= 0);
1178 
1179     if (action == BLOCK_ERROR_ACTION_STOP) {
1180         /* First set the iostatus, so that "info block" returns an iostatus
1181          * that matches the events raised so far (an additional error iostatus
1182          * is fine, but not a lost one).
1183          */
1184         blk_iostatus_set_err(blk, error);
1185 
1186         /* Then raise the request to stop the VM and the event.
1187          * qemu_system_vmstop_request_prepare has two effects.  First,
1188          * it ensures that the STOP event always comes after the
1189          * BLOCK_IO_ERROR event.  Second, it ensures that even if management
1190          * can observe the STOP event and do a "cont" before the STOP
1191          * event is issued, the VM will not stop.  In this case, vm_start()
1192          * also ensures that the STOP/RESUME pair of events is emitted.
1193          */
1194         qemu_system_vmstop_request_prepare();
1195         send_qmp_error_event(blk, action, is_read, error);
1196         qemu_system_vmstop_request(RUN_STATE_IO_ERROR);
1197     } else {
1198         send_qmp_error_event(blk, action, is_read, error);
1199     }
1200 }
1201 
1202 int blk_is_read_only(BlockBackend *blk)
1203 {
1204     BlockDriverState *bs = blk_bs(blk);
1205 
1206     if (bs) {
1207         return bdrv_is_read_only(bs);
1208     } else {
1209         return blk->root_state.read_only;
1210     }
1211 }
1212 
1213 int blk_is_sg(BlockBackend *blk)
1214 {
1215     BlockDriverState *bs = blk_bs(blk);
1216 
1217     if (!bs) {
1218         return 0;
1219     }
1220 
1221     return bdrv_is_sg(bs);
1222 }
1223 
1224 int blk_enable_write_cache(BlockBackend *blk)
1225 {
1226     BlockDriverState *bs = blk_bs(blk);
1227 
1228     if (bs) {
1229         return bdrv_enable_write_cache(bs);
1230     } else {
1231         return !!(blk->root_state.open_flags & BDRV_O_CACHE_WB);
1232     }
1233 }
1234 
1235 void blk_set_enable_write_cache(BlockBackend *blk, bool wce)
1236 {
1237     BlockDriverState *bs = blk_bs(blk);
1238 
1239     if (bs) {
1240         bdrv_set_enable_write_cache(bs, wce);
1241     } else {
1242         if (wce) {
1243             blk->root_state.open_flags |= BDRV_O_CACHE_WB;
1244         } else {
1245             blk->root_state.open_flags &= ~BDRV_O_CACHE_WB;
1246         }
1247     }
1248 }
1249 
1250 void blk_invalidate_cache(BlockBackend *blk, Error **errp)
1251 {
1252     BlockDriverState *bs = blk_bs(blk);
1253 
1254     if (!bs) {
1255         error_setg(errp, "Device '%s' has no medium", blk->name);
1256         return;
1257     }
1258 
1259     bdrv_invalidate_cache(bs, errp);
1260 }
1261 
1262 bool blk_is_inserted(BlockBackend *blk)
1263 {
1264     BlockDriverState *bs = blk_bs(blk);
1265 
1266     return bs && bdrv_is_inserted(bs);
1267 }
1268 
1269 bool blk_is_available(BlockBackend *blk)
1270 {
1271     return blk_is_inserted(blk) && !blk_dev_is_tray_open(blk);
1272 }
1273 
1274 void blk_lock_medium(BlockBackend *blk, bool locked)
1275 {
1276     BlockDriverState *bs = blk_bs(blk);
1277 
1278     if (bs) {
1279         bdrv_lock_medium(bs, locked);
1280     }
1281 }
1282 
1283 void blk_eject(BlockBackend *blk, bool eject_flag)
1284 {
1285     BlockDriverState *bs = blk_bs(blk);
1286 
1287     if (bs) {
1288         bdrv_eject(bs, eject_flag);
1289     }
1290 }
1291 
1292 int blk_get_flags(BlockBackend *blk)
1293 {
1294     BlockDriverState *bs = blk_bs(blk);
1295 
1296     if (bs) {
1297         return bdrv_get_flags(bs);
1298     } else {
1299         return blk->root_state.open_flags;
1300     }
1301 }
1302 
1303 int blk_get_max_transfer_length(BlockBackend *blk)
1304 {
1305     BlockDriverState *bs = blk_bs(blk);
1306 
1307     if (bs) {
1308         return bs->bl.max_transfer_length;
1309     } else {
1310         return 0;
1311     }
1312 }
1313 
1314 int blk_get_max_iov(BlockBackend *blk)
1315 {
1316     return blk->root->bs->bl.max_iov;
1317 }
1318 
1319 void blk_set_guest_block_size(BlockBackend *blk, int align)
1320 {
1321     blk->guest_block_size = align;
1322 }
1323 
1324 void *blk_try_blockalign(BlockBackend *blk, size_t size)
1325 {
1326     return qemu_try_blockalign(blk ? blk_bs(blk) : NULL, size);
1327 }
1328 
1329 void *blk_blockalign(BlockBackend *blk, size_t size)
1330 {
1331     return qemu_blockalign(blk ? blk_bs(blk) : NULL, size);
1332 }
1333 
1334 bool blk_op_is_blocked(BlockBackend *blk, BlockOpType op, Error **errp)
1335 {
1336     BlockDriverState *bs = blk_bs(blk);
1337 
1338     if (!bs) {
1339         return false;
1340     }
1341 
1342     return bdrv_op_is_blocked(bs, op, errp);
1343 }
1344 
1345 void blk_op_unblock(BlockBackend *blk, BlockOpType op, Error *reason)
1346 {
1347     BlockDriverState *bs = blk_bs(blk);
1348 
1349     if (bs) {
1350         bdrv_op_unblock(bs, op, reason);
1351     }
1352 }
1353 
1354 void blk_op_block_all(BlockBackend *blk, Error *reason)
1355 {
1356     BlockDriverState *bs = blk_bs(blk);
1357 
1358     if (bs) {
1359         bdrv_op_block_all(bs, reason);
1360     }
1361 }
1362 
1363 void blk_op_unblock_all(BlockBackend *blk, Error *reason)
1364 {
1365     BlockDriverState *bs = blk_bs(blk);
1366 
1367     if (bs) {
1368         bdrv_op_unblock_all(bs, reason);
1369     }
1370 }
1371 
1372 AioContext *blk_get_aio_context(BlockBackend *blk)
1373 {
1374     BlockDriverState *bs = blk_bs(blk);
1375 
1376     if (bs) {
1377         return bdrv_get_aio_context(bs);
1378     } else {
1379         return qemu_get_aio_context();
1380     }
1381 }
1382 
1383 static AioContext *blk_aiocb_get_aio_context(BlockAIOCB *acb)
1384 {
1385     BlockBackendAIOCB *blk_acb = DO_UPCAST(BlockBackendAIOCB, common, acb);
1386     return blk_get_aio_context(blk_acb->blk);
1387 }
1388 
1389 void blk_set_aio_context(BlockBackend *blk, AioContext *new_context)
1390 {
1391     BlockDriverState *bs = blk_bs(blk);
1392 
1393     if (bs) {
1394         bdrv_set_aio_context(bs, new_context);
1395     }
1396 }
1397 
1398 void blk_add_aio_context_notifier(BlockBackend *blk,
1399         void (*attached_aio_context)(AioContext *new_context, void *opaque),
1400         void (*detach_aio_context)(void *opaque), void *opaque)
1401 {
1402     BlockDriverState *bs = blk_bs(blk);
1403 
1404     if (bs) {
1405         bdrv_add_aio_context_notifier(bs, attached_aio_context,
1406                                       detach_aio_context, opaque);
1407     }
1408 }
1409 
1410 void blk_remove_aio_context_notifier(BlockBackend *blk,
1411                                      void (*attached_aio_context)(AioContext *,
1412                                                                   void *),
1413                                      void (*detach_aio_context)(void *),
1414                                      void *opaque)
1415 {
1416     BlockDriverState *bs = blk_bs(blk);
1417 
1418     if (bs) {
1419         bdrv_remove_aio_context_notifier(bs, attached_aio_context,
1420                                          detach_aio_context, opaque);
1421     }
1422 }
1423 
1424 void blk_add_remove_bs_notifier(BlockBackend *blk, Notifier *notify)
1425 {
1426     notifier_list_add(&blk->remove_bs_notifiers, notify);
1427 }
1428 
1429 void blk_add_insert_bs_notifier(BlockBackend *blk, Notifier *notify)
1430 {
1431     notifier_list_add(&blk->insert_bs_notifiers, notify);
1432 }
1433 
1434 void blk_io_plug(BlockBackend *blk)
1435 {
1436     BlockDriverState *bs = blk_bs(blk);
1437 
1438     if (bs) {
1439         bdrv_io_plug(bs);
1440     }
1441 }
1442 
1443 void blk_io_unplug(BlockBackend *blk)
1444 {
1445     BlockDriverState *bs = blk_bs(blk);
1446 
1447     if (bs) {
1448         bdrv_io_unplug(bs);
1449     }
1450 }
1451 
1452 BlockAcctStats *blk_get_stats(BlockBackend *blk)
1453 {
1454     return &blk->stats;
1455 }
1456 
1457 void *blk_aio_get(const AIOCBInfo *aiocb_info, BlockBackend *blk,
1458                   BlockCompletionFunc *cb, void *opaque)
1459 {
1460     return qemu_aio_get(aiocb_info, blk_bs(blk), cb, opaque);
1461 }
1462 
1463 int coroutine_fn blk_co_write_zeroes(BlockBackend *blk, int64_t sector_num,
1464                                      int nb_sectors, BdrvRequestFlags flags)
1465 {
1466     if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
1467         return -EINVAL;
1468     }
1469 
1470     return blk_co_pwritev(blk, sector_num << BDRV_SECTOR_BITS,
1471                           nb_sectors << BDRV_SECTOR_BITS, NULL,
1472                           BDRV_REQ_ZERO_WRITE);
1473 }
1474 
1475 int blk_write_compressed(BlockBackend *blk, int64_t sector_num,
1476                          const uint8_t *buf, int nb_sectors)
1477 {
1478     int ret = blk_check_request(blk, sector_num, nb_sectors);
1479     if (ret < 0) {
1480         return ret;
1481     }
1482 
1483     return bdrv_write_compressed(blk_bs(blk), sector_num, buf, nb_sectors);
1484 }
1485 
1486 int blk_truncate(BlockBackend *blk, int64_t offset)
1487 {
1488     if (!blk_is_available(blk)) {
1489         return -ENOMEDIUM;
1490     }
1491 
1492     return bdrv_truncate(blk_bs(blk), offset);
1493 }
1494 
1495 int blk_discard(BlockBackend *blk, int64_t sector_num, int nb_sectors)
1496 {
1497     int ret = blk_check_request(blk, sector_num, nb_sectors);
1498     if (ret < 0) {
1499         return ret;
1500     }
1501 
1502     return bdrv_discard(blk_bs(blk), sector_num, nb_sectors);
1503 }
1504 
1505 int blk_save_vmstate(BlockBackend *blk, const uint8_t *buf,
1506                      int64_t pos, int size)
1507 {
1508     if (!blk_is_available(blk)) {
1509         return -ENOMEDIUM;
1510     }
1511 
1512     return bdrv_save_vmstate(blk_bs(blk), buf, pos, size);
1513 }
1514 
1515 int blk_load_vmstate(BlockBackend *blk, uint8_t *buf, int64_t pos, int size)
1516 {
1517     if (!blk_is_available(blk)) {
1518         return -ENOMEDIUM;
1519     }
1520 
1521     return bdrv_load_vmstate(blk_bs(blk), buf, pos, size);
1522 }
1523 
1524 int blk_probe_blocksizes(BlockBackend *blk, BlockSizes *bsz)
1525 {
1526     if (!blk_is_available(blk)) {
1527         return -ENOMEDIUM;
1528     }
1529 
1530     return bdrv_probe_blocksizes(blk_bs(blk), bsz);
1531 }
1532 
1533 int blk_probe_geometry(BlockBackend *blk, HDGeometry *geo)
1534 {
1535     if (!blk_is_available(blk)) {
1536         return -ENOMEDIUM;
1537     }
1538 
1539     return bdrv_probe_geometry(blk_bs(blk), geo);
1540 }
1541 
1542 /*
1543  * Updates the BlockBackendRootState object with data from the currently
1544  * attached BlockDriverState.
1545  */
1546 void blk_update_root_state(BlockBackend *blk)
1547 {
1548     assert(blk->root);
1549 
1550     blk->root_state.open_flags    = blk->root->bs->open_flags;
1551     blk->root_state.read_only     = blk->root->bs->read_only;
1552     blk->root_state.detect_zeroes = blk->root->bs->detect_zeroes;
1553 
1554     if (blk->root_state.throttle_group) {
1555         g_free(blk->root_state.throttle_group);
1556         throttle_group_unref(blk->root_state.throttle_state);
1557     }
1558     if (blk->root->bs->throttle_state) {
1559         const char *name = throttle_group_get_name(blk->root->bs);
1560         blk->root_state.throttle_group = g_strdup(name);
1561         blk->root_state.throttle_state = throttle_group_incref(name);
1562     } else {
1563         blk->root_state.throttle_group = NULL;
1564         blk->root_state.throttle_state = NULL;
1565     }
1566 }
1567 
1568 /*
1569  * Applies the information in the root state to the given BlockDriverState. This
1570  * does not include the flags which have to be specified for bdrv_open(), use
1571  * blk_get_open_flags_from_root_state() to inquire them.
1572  */
1573 void blk_apply_root_state(BlockBackend *blk, BlockDriverState *bs)
1574 {
1575     bs->detect_zeroes = blk->root_state.detect_zeroes;
1576     if (blk->root_state.throttle_group) {
1577         bdrv_io_limits_enable(bs, blk->root_state.throttle_group);
1578     }
1579 }
1580 
1581 /*
1582  * Returns the flags to be used for bdrv_open() of a BlockDriverState which is
1583  * supposed to inherit the root state.
1584  */
1585 int blk_get_open_flags_from_root_state(BlockBackend *blk)
1586 {
1587     int bs_flags;
1588 
1589     bs_flags = blk->root_state.read_only ? 0 : BDRV_O_RDWR;
1590     bs_flags |= blk->root_state.open_flags & ~BDRV_O_RDWR;
1591 
1592     return bs_flags;
1593 }
1594 
1595 BlockBackendRootState *blk_get_root_state(BlockBackend *blk)
1596 {
1597     return &blk->root_state;
1598 }
1599 
1600 int blk_commit_all(void)
1601 {
1602     BlockBackend *blk = NULL;
1603 
1604     while ((blk = blk_all_next(blk)) != NULL) {
1605         AioContext *aio_context = blk_get_aio_context(blk);
1606 
1607         aio_context_acquire(aio_context);
1608         if (blk_is_inserted(blk) && blk->root->bs->backing) {
1609             int ret = bdrv_commit(blk->root->bs);
1610             if (ret < 0) {
1611                 aio_context_release(aio_context);
1612                 return ret;
1613             }
1614         }
1615         aio_context_release(aio_context);
1616     }
1617     return 0;
1618 }
1619 
1620 int blk_flush_all(void)
1621 {
1622     BlockBackend *blk = NULL;
1623     int result = 0;
1624 
1625     while ((blk = blk_all_next(blk)) != NULL) {
1626         AioContext *aio_context = blk_get_aio_context(blk);
1627         int ret;
1628 
1629         aio_context_acquire(aio_context);
1630         if (blk_is_inserted(blk)) {
1631             ret = blk_flush(blk);
1632             if (ret < 0 && !result) {
1633                 result = ret;
1634             }
1635         }
1636         aio_context_release(aio_context);
1637     }
1638 
1639     return result;
1640 }
1641