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