xref: /openbmc/qemu/block.c (revision 56d1b4d21d444619302d3f1291a133b1c2b9b072)
1fc01f7e7Sbellard /*
2fc01f7e7Sbellard  * QEMU System Emulator block driver
3fc01f7e7Sbellard  *
4fc01f7e7Sbellard  * Copyright (c) 2003 Fabrice Bellard
5fc01f7e7Sbellard  *
6fc01f7e7Sbellard  * Permission is hereby granted, free of charge, to any person obtaining a copy
7fc01f7e7Sbellard  * of this software and associated documentation files (the "Software"), to deal
8fc01f7e7Sbellard  * in the Software without restriction, including without limitation the rights
9fc01f7e7Sbellard  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10fc01f7e7Sbellard  * copies of the Software, and to permit persons to whom the Software is
11fc01f7e7Sbellard  * furnished to do so, subject to the following conditions:
12fc01f7e7Sbellard  *
13fc01f7e7Sbellard  * The above copyright notice and this permission notice shall be included in
14fc01f7e7Sbellard  * all copies or substantial portions of the Software.
15fc01f7e7Sbellard  *
16fc01f7e7Sbellard  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17fc01f7e7Sbellard  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18fc01f7e7Sbellard  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19fc01f7e7Sbellard  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20fc01f7e7Sbellard  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21fc01f7e7Sbellard  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22fc01f7e7Sbellard  * THE SOFTWARE.
23fc01f7e7Sbellard  */
243990d09aSblueswir1 #include "config-host.h"
25faf07963Spbrook #include "qemu-common.h"
266d519a5fSStefan Hajnoczi #include "trace.h"
2783c9089eSPaolo Bonzini #include "monitor/monitor.h"
28737e150eSPaolo Bonzini #include "block/block_int.h"
29737e150eSPaolo Bonzini #include "block/blockjob.h"
301de7afc9SPaolo Bonzini #include "qemu/module.h"
317b1b5d19SPaolo Bonzini #include "qapi/qmp/qjson.h"
329c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
331de7afc9SPaolo Bonzini #include "qemu/notify.h"
34737e150eSPaolo Bonzini #include "block/coroutine.h"
35b2023818SLuiz Capitulino #include "qmp-commands.h"
361de7afc9SPaolo Bonzini #include "qemu/timer.h"
37fc01f7e7Sbellard 
3871e72a19SJuan Quintela #ifdef CONFIG_BSD
397674e7bfSbellard #include <sys/types.h>
407674e7bfSbellard #include <sys/stat.h>
417674e7bfSbellard #include <sys/ioctl.h>
4272cf2d4fSBlue Swirl #include <sys/queue.h>
43c5e97233Sblueswir1 #ifndef __DragonFly__
447674e7bfSbellard #include <sys/disk.h>
457674e7bfSbellard #endif
46c5e97233Sblueswir1 #endif
477674e7bfSbellard 
4849dc768dSaliguori #ifdef _WIN32
4949dc768dSaliguori #include <windows.h>
5049dc768dSaliguori #endif
5149dc768dSaliguori 
521c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
531c9805a3SStefan Hajnoczi 
54470c0504SStefan Hajnoczi typedef enum {
55470c0504SStefan Hajnoczi     BDRV_REQ_COPY_ON_READ = 0x1,
56f08f2ddaSStefan Hajnoczi     BDRV_REQ_ZERO_WRITE   = 0x2,
57470c0504SStefan Hajnoczi } BdrvRequestFlags;
58470c0504SStefan Hajnoczi 
597d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
60f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
61f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
62c87c0672Saliguori         BlockDriverCompletionFunc *cb, void *opaque);
63f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
64f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
65ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque);
66f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
67f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
68f9f05dc5SKevin Wolf                                          QEMUIOVector *iov);
69f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
70f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
71f9f05dc5SKevin Wolf                                          QEMUIOVector *iov);
72c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
73470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
74470c0504SStefan Hajnoczi     BdrvRequestFlags flags);
751c9805a3SStefan Hajnoczi static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
76f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
77f08f2ddaSStefan Hajnoczi     BdrvRequestFlags flags);
78b2a61371SStefan Hajnoczi static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
79b2a61371SStefan Hajnoczi                                                int64_t sector_num,
80b2a61371SStefan Hajnoczi                                                QEMUIOVector *qiov,
81b2a61371SStefan Hajnoczi                                                int nb_sectors,
82b2a61371SStefan Hajnoczi                                                BlockDriverCompletionFunc *cb,
83b2a61371SStefan Hajnoczi                                                void *opaque,
848c5873d6SStefan Hajnoczi                                                bool is_write);
85b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque);
86621f0589SKevin Wolf static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
87621f0589SKevin Wolf     int64_t sector_num, int nb_sectors);
88ec530c81Sbellard 
8998f90dbaSZhi Yong Wu static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
9098f90dbaSZhi Yong Wu         bool is_write, double elapsed_time, uint64_t *wait);
9198f90dbaSZhi Yong Wu static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
9298f90dbaSZhi Yong Wu         double elapsed_time, uint64_t *wait);
9398f90dbaSZhi Yong Wu static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
9498f90dbaSZhi Yong Wu         bool is_write, int64_t *wait);
9598f90dbaSZhi Yong Wu 
961b7bdbc1SStefan Hajnoczi static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
971b7bdbc1SStefan Hajnoczi     QTAILQ_HEAD_INITIALIZER(bdrv_states);
987ee930d0Sblueswir1 
998a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
1008a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
101ea2384d3Sbellard 
102f9092b10SMarkus Armbruster /* The device to use for VM snapshots */
103f9092b10SMarkus Armbruster static BlockDriverState *bs_snapshots;
104f9092b10SMarkus Armbruster 
105eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
106eb852011SMarkus Armbruster static int use_bdrv_whitelist;
107eb852011SMarkus Armbruster 
1089e0b22f4SStefan Hajnoczi #ifdef _WIN32
1099e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
1109e0b22f4SStefan Hajnoczi {
1119e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
1129e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
1139e0b22f4SStefan Hajnoczi             filename[1] == ':');
1149e0b22f4SStefan Hajnoczi }
1159e0b22f4SStefan Hajnoczi 
1169e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
1179e0b22f4SStefan Hajnoczi {
1189e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
1199e0b22f4SStefan Hajnoczi         filename[2] == '\0')
1209e0b22f4SStefan Hajnoczi         return 1;
1219e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
1229e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
1239e0b22f4SStefan Hajnoczi         return 1;
1249e0b22f4SStefan Hajnoczi     return 0;
1259e0b22f4SStefan Hajnoczi }
1269e0b22f4SStefan Hajnoczi #endif
1279e0b22f4SStefan Hajnoczi 
1280563e191SZhi Yong Wu /* throttling disk I/O limits */
12998f90dbaSZhi Yong Wu void bdrv_io_limits_disable(BlockDriverState *bs)
13098f90dbaSZhi Yong Wu {
13198f90dbaSZhi Yong Wu     bs->io_limits_enabled = false;
13298f90dbaSZhi Yong Wu 
13398f90dbaSZhi Yong Wu     while (qemu_co_queue_next(&bs->throttled_reqs));
13498f90dbaSZhi Yong Wu 
13598f90dbaSZhi Yong Wu     if (bs->block_timer) {
13698f90dbaSZhi Yong Wu         qemu_del_timer(bs->block_timer);
13798f90dbaSZhi Yong Wu         qemu_free_timer(bs->block_timer);
13898f90dbaSZhi Yong Wu         bs->block_timer = NULL;
13998f90dbaSZhi Yong Wu     }
14098f90dbaSZhi Yong Wu 
14198f90dbaSZhi Yong Wu     bs->slice_start = 0;
14298f90dbaSZhi Yong Wu     bs->slice_end   = 0;
14398f90dbaSZhi Yong Wu }
14498f90dbaSZhi Yong Wu 
1450563e191SZhi Yong Wu static void bdrv_block_timer(void *opaque)
1460563e191SZhi Yong Wu {
1470563e191SZhi Yong Wu     BlockDriverState *bs = opaque;
1480563e191SZhi Yong Wu 
1490563e191SZhi Yong Wu     qemu_co_queue_next(&bs->throttled_reqs);
1500563e191SZhi Yong Wu }
1510563e191SZhi Yong Wu 
1520563e191SZhi Yong Wu void bdrv_io_limits_enable(BlockDriverState *bs)
1530563e191SZhi Yong Wu {
1540563e191SZhi Yong Wu     qemu_co_queue_init(&bs->throttled_reqs);
1550563e191SZhi Yong Wu     bs->block_timer = qemu_new_timer_ns(vm_clock, bdrv_block_timer, bs);
1560563e191SZhi Yong Wu     bs->io_limits_enabled = true;
1570563e191SZhi Yong Wu }
1580563e191SZhi Yong Wu 
1590563e191SZhi Yong Wu bool bdrv_io_limits_enabled(BlockDriverState *bs)
1600563e191SZhi Yong Wu {
1610563e191SZhi Yong Wu     BlockIOLimit *io_limits = &bs->io_limits;
1620563e191SZhi Yong Wu     return io_limits->bps[BLOCK_IO_LIMIT_READ]
1630563e191SZhi Yong Wu          || io_limits->bps[BLOCK_IO_LIMIT_WRITE]
1640563e191SZhi Yong Wu          || io_limits->bps[BLOCK_IO_LIMIT_TOTAL]
1650563e191SZhi Yong Wu          || io_limits->iops[BLOCK_IO_LIMIT_READ]
1660563e191SZhi Yong Wu          || io_limits->iops[BLOCK_IO_LIMIT_WRITE]
1670563e191SZhi Yong Wu          || io_limits->iops[BLOCK_IO_LIMIT_TOTAL];
1680563e191SZhi Yong Wu }
1690563e191SZhi Yong Wu 
17098f90dbaSZhi Yong Wu static void bdrv_io_limits_intercept(BlockDriverState *bs,
17198f90dbaSZhi Yong Wu                                      bool is_write, int nb_sectors)
17298f90dbaSZhi Yong Wu {
17398f90dbaSZhi Yong Wu     int64_t wait_time = -1;
17498f90dbaSZhi Yong Wu 
17598f90dbaSZhi Yong Wu     if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
17698f90dbaSZhi Yong Wu         qemu_co_queue_wait(&bs->throttled_reqs);
17798f90dbaSZhi Yong Wu     }
17898f90dbaSZhi Yong Wu 
17998f90dbaSZhi Yong Wu     /* In fact, we hope to keep each request's timing, in FIFO mode. The next
18098f90dbaSZhi Yong Wu      * throttled requests will not be dequeued until the current request is
18198f90dbaSZhi Yong Wu      * allowed to be serviced. So if the current request still exceeds the
18298f90dbaSZhi Yong Wu      * limits, it will be inserted to the head. All requests followed it will
18398f90dbaSZhi Yong Wu      * be still in throttled_reqs queue.
18498f90dbaSZhi Yong Wu      */
18598f90dbaSZhi Yong Wu 
18698f90dbaSZhi Yong Wu     while (bdrv_exceed_io_limits(bs, nb_sectors, is_write, &wait_time)) {
18798f90dbaSZhi Yong Wu         qemu_mod_timer(bs->block_timer,
18898f90dbaSZhi Yong Wu                        wait_time + qemu_get_clock_ns(vm_clock));
18998f90dbaSZhi Yong Wu         qemu_co_queue_wait_insert_head(&bs->throttled_reqs);
19098f90dbaSZhi Yong Wu     }
19198f90dbaSZhi Yong Wu 
19298f90dbaSZhi Yong Wu     qemu_co_queue_next(&bs->throttled_reqs);
19398f90dbaSZhi Yong Wu }
19498f90dbaSZhi Yong Wu 
1959e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
1969e0b22f4SStefan Hajnoczi static int path_has_protocol(const char *path)
1979e0b22f4SStefan Hajnoczi {
198947995c0SPaolo Bonzini     const char *p;
199947995c0SPaolo Bonzini 
2009e0b22f4SStefan Hajnoczi #ifdef _WIN32
2019e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
2029e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
2039e0b22f4SStefan Hajnoczi         return 0;
2049e0b22f4SStefan Hajnoczi     }
205947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
206947995c0SPaolo Bonzini #else
207947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
2089e0b22f4SStefan Hajnoczi #endif
2099e0b22f4SStefan Hajnoczi 
210947995c0SPaolo Bonzini     return *p == ':';
2119e0b22f4SStefan Hajnoczi }
2129e0b22f4SStefan Hajnoczi 
21383f64091Sbellard int path_is_absolute(const char *path)
21483f64091Sbellard {
21521664424Sbellard #ifdef _WIN32
21621664424Sbellard     /* specific case for names like: "\\.\d:" */
217f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
21821664424Sbellard         return 1;
219f53f4da9SPaolo Bonzini     }
220f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
2213b9f94e1Sbellard #else
222f53f4da9SPaolo Bonzini     return (*path == '/');
2233b9f94e1Sbellard #endif
22483f64091Sbellard }
22583f64091Sbellard 
22683f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
22783f64091Sbellard    path to it by considering it is relative to base_path. URL are
22883f64091Sbellard    supported. */
22983f64091Sbellard void path_combine(char *dest, int dest_size,
23083f64091Sbellard                   const char *base_path,
23183f64091Sbellard                   const char *filename)
23283f64091Sbellard {
23383f64091Sbellard     const char *p, *p1;
23483f64091Sbellard     int len;
23583f64091Sbellard 
23683f64091Sbellard     if (dest_size <= 0)
23783f64091Sbellard         return;
23883f64091Sbellard     if (path_is_absolute(filename)) {
23983f64091Sbellard         pstrcpy(dest, dest_size, filename);
24083f64091Sbellard     } else {
24183f64091Sbellard         p = strchr(base_path, ':');
24283f64091Sbellard         if (p)
24383f64091Sbellard             p++;
24483f64091Sbellard         else
24583f64091Sbellard             p = base_path;
2463b9f94e1Sbellard         p1 = strrchr(base_path, '/');
2473b9f94e1Sbellard #ifdef _WIN32
2483b9f94e1Sbellard         {
2493b9f94e1Sbellard             const char *p2;
2503b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
2513b9f94e1Sbellard             if (!p1 || p2 > p1)
2523b9f94e1Sbellard                 p1 = p2;
2533b9f94e1Sbellard         }
2543b9f94e1Sbellard #endif
25583f64091Sbellard         if (p1)
25683f64091Sbellard             p1++;
25783f64091Sbellard         else
25883f64091Sbellard             p1 = base_path;
25983f64091Sbellard         if (p1 > p)
26083f64091Sbellard             p = p1;
26183f64091Sbellard         len = p - base_path;
26283f64091Sbellard         if (len > dest_size - 1)
26383f64091Sbellard             len = dest_size - 1;
26483f64091Sbellard         memcpy(dest, base_path, len);
26583f64091Sbellard         dest[len] = '\0';
26683f64091Sbellard         pstrcat(dest, dest_size, filename);
26783f64091Sbellard     }
26883f64091Sbellard }
26983f64091Sbellard 
270dc5a1371SPaolo Bonzini void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
271dc5a1371SPaolo Bonzini {
272dc5a1371SPaolo Bonzini     if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
273dc5a1371SPaolo Bonzini         pstrcpy(dest, sz, bs->backing_file);
274dc5a1371SPaolo Bonzini     } else {
275dc5a1371SPaolo Bonzini         path_combine(dest, sz, bs->filename, bs->backing_file);
276dc5a1371SPaolo Bonzini     }
277dc5a1371SPaolo Bonzini }
278dc5a1371SPaolo Bonzini 
2795efa9d5aSAnthony Liguori void bdrv_register(BlockDriver *bdrv)
280ea2384d3Sbellard {
2818c5873d6SStefan Hajnoczi     /* Block drivers without coroutine functions need emulation */
2828c5873d6SStefan Hajnoczi     if (!bdrv->bdrv_co_readv) {
283f9f05dc5SKevin Wolf         bdrv->bdrv_co_readv = bdrv_co_readv_em;
284f9f05dc5SKevin Wolf         bdrv->bdrv_co_writev = bdrv_co_writev_em;
285f9f05dc5SKevin Wolf 
286f8c35c1dSStefan Hajnoczi         /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
287f8c35c1dSStefan Hajnoczi          * the block driver lacks aio we need to emulate that too.
288f8c35c1dSStefan Hajnoczi          */
289f9f05dc5SKevin Wolf         if (!bdrv->bdrv_aio_readv) {
29083f64091Sbellard             /* add AIO emulation layer */
291f141eafeSaliguori             bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
292f141eafeSaliguori             bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
29383f64091Sbellard         }
294f9f05dc5SKevin Wolf     }
295b2e12bc6SChristoph Hellwig 
2968a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
297ea2384d3Sbellard }
298b338082bSbellard 
299b338082bSbellard /* create a new block device (by default it is empty) */
300b338082bSbellard BlockDriverState *bdrv_new(const char *device_name)
301fc01f7e7Sbellard {
3021b7bdbc1SStefan Hajnoczi     BlockDriverState *bs;
303b338082bSbellard 
3047267c094SAnthony Liguori     bs = g_malloc0(sizeof(BlockDriverState));
305b338082bSbellard     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
306ea2384d3Sbellard     if (device_name[0] != '\0') {
3071b7bdbc1SStefan Hajnoczi         QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
308ea2384d3Sbellard     }
30928a7282aSLuiz Capitulino     bdrv_iostatus_disable(bs);
310d7d512f6SPaolo Bonzini     notifier_list_init(&bs->close_notifiers);
311d7d512f6SPaolo Bonzini 
312b338082bSbellard     return bs;
313b338082bSbellard }
314b338082bSbellard 
315d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
316d7d512f6SPaolo Bonzini {
317d7d512f6SPaolo Bonzini     notifier_list_add(&bs->close_notifiers, notify);
318d7d512f6SPaolo Bonzini }
319d7d512f6SPaolo Bonzini 
320ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
321ea2384d3Sbellard {
322ea2384d3Sbellard     BlockDriver *drv1;
3238a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
3248a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
325ea2384d3Sbellard             return drv1;
326ea2384d3Sbellard         }
3278a22f02aSStefan Hajnoczi     }
328ea2384d3Sbellard     return NULL;
329ea2384d3Sbellard }
330ea2384d3Sbellard 
331eb852011SMarkus Armbruster static int bdrv_is_whitelisted(BlockDriver *drv)
332eb852011SMarkus Armbruster {
333eb852011SMarkus Armbruster     static const char *whitelist[] = {
334eb852011SMarkus Armbruster         CONFIG_BDRV_WHITELIST
335eb852011SMarkus Armbruster     };
336eb852011SMarkus Armbruster     const char **p;
337eb852011SMarkus Armbruster 
338eb852011SMarkus Armbruster     if (!whitelist[0])
339eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
340eb852011SMarkus Armbruster 
341eb852011SMarkus Armbruster     for (p = whitelist; *p; p++) {
342eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
343eb852011SMarkus Armbruster             return 1;
344eb852011SMarkus Armbruster         }
345eb852011SMarkus Armbruster     }
346eb852011SMarkus Armbruster     return 0;
347eb852011SMarkus Armbruster }
348eb852011SMarkus Armbruster 
349eb852011SMarkus Armbruster BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
350eb852011SMarkus Armbruster {
351eb852011SMarkus Armbruster     BlockDriver *drv = bdrv_find_format(format_name);
352eb852011SMarkus Armbruster     return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
353eb852011SMarkus Armbruster }
354eb852011SMarkus Armbruster 
3555b7e1542SZhi Yong Wu typedef struct CreateCo {
3565b7e1542SZhi Yong Wu     BlockDriver *drv;
3575b7e1542SZhi Yong Wu     char *filename;
3585b7e1542SZhi Yong Wu     QEMUOptionParameter *options;
3595b7e1542SZhi Yong Wu     int ret;
3605b7e1542SZhi Yong Wu } CreateCo;
3615b7e1542SZhi Yong Wu 
3625b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
3635b7e1542SZhi Yong Wu {
3645b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
3655b7e1542SZhi Yong Wu     assert(cco->drv);
3665b7e1542SZhi Yong Wu 
3675b7e1542SZhi Yong Wu     cco->ret = cco->drv->bdrv_create(cco->filename, cco->options);
3685b7e1542SZhi Yong Wu }
3695b7e1542SZhi Yong Wu 
3700e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
3710e7e1989SKevin Wolf     QEMUOptionParameter *options)
372ea2384d3Sbellard {
3735b7e1542SZhi Yong Wu     int ret;
3740e7e1989SKevin Wolf 
3755b7e1542SZhi Yong Wu     Coroutine *co;
3765b7e1542SZhi Yong Wu     CreateCo cco = {
3775b7e1542SZhi Yong Wu         .drv = drv,
3785b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
3795b7e1542SZhi Yong Wu         .options = options,
3805b7e1542SZhi Yong Wu         .ret = NOT_DONE,
3815b7e1542SZhi Yong Wu     };
3825b7e1542SZhi Yong Wu 
3835b7e1542SZhi Yong Wu     if (!drv->bdrv_create) {
38480168bffSLuiz Capitulino         ret = -ENOTSUP;
38580168bffSLuiz Capitulino         goto out;
3865b7e1542SZhi Yong Wu     }
3875b7e1542SZhi Yong Wu 
3885b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
3895b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
3905b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
3915b7e1542SZhi Yong Wu     } else {
3925b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
3935b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
3945b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
3955b7e1542SZhi Yong Wu             qemu_aio_wait();
3965b7e1542SZhi Yong Wu         }
3975b7e1542SZhi Yong Wu     }
3985b7e1542SZhi Yong Wu 
3995b7e1542SZhi Yong Wu     ret = cco.ret;
4005b7e1542SZhi Yong Wu 
40180168bffSLuiz Capitulino out:
40280168bffSLuiz Capitulino     g_free(cco.filename);
4035b7e1542SZhi Yong Wu     return ret;
404ea2384d3Sbellard }
405ea2384d3Sbellard 
40684a12e66SChristoph Hellwig int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
40784a12e66SChristoph Hellwig {
40884a12e66SChristoph Hellwig     BlockDriver *drv;
40984a12e66SChristoph Hellwig 
410b50cbabcSMORITA Kazutaka     drv = bdrv_find_protocol(filename);
41184a12e66SChristoph Hellwig     if (drv == NULL) {
41216905d71SStefan Hajnoczi         return -ENOENT;
41384a12e66SChristoph Hellwig     }
41484a12e66SChristoph Hellwig 
41584a12e66SChristoph Hellwig     return bdrv_create(drv, filename, options);
41684a12e66SChristoph Hellwig }
41784a12e66SChristoph Hellwig 
418eba25057SJim Meyering /*
419eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
420eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
421eba25057SJim Meyering  */
422eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
423eba25057SJim Meyering {
424d5249393Sbellard #ifdef _WIN32
4253b9f94e1Sbellard     char temp_dir[MAX_PATH];
426eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
427eba25057SJim Meyering        have length MAX_PATH or greater.  */
428eba25057SJim Meyering     assert(size >= MAX_PATH);
429eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
430eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
431eba25057SJim Meyering             ? 0 : -GetLastError());
432d5249393Sbellard #else
433ea2384d3Sbellard     int fd;
4347ccfb2ebSblueswir1     const char *tmpdir;
4350badc1eeSaurel32     tmpdir = getenv("TMPDIR");
4360badc1eeSaurel32     if (!tmpdir)
4370badc1eeSaurel32         tmpdir = "/tmp";
438eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
439eba25057SJim Meyering         return -EOVERFLOW;
440ea2384d3Sbellard     }
441eba25057SJim Meyering     fd = mkstemp(filename);
442fe235a06SDunrong Huang     if (fd < 0) {
443fe235a06SDunrong Huang         return -errno;
444fe235a06SDunrong Huang     }
445fe235a06SDunrong Huang     if (close(fd) != 0) {
446fe235a06SDunrong Huang         unlink(filename);
447eba25057SJim Meyering         return -errno;
448eba25057SJim Meyering     }
449eba25057SJim Meyering     return 0;
450d5249393Sbellard #endif
451eba25057SJim Meyering }
452ea2384d3Sbellard 
453f3a5d3f8SChristoph Hellwig /*
454f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
455f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
456f3a5d3f8SChristoph Hellwig  */
457f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
458f3a5d3f8SChristoph Hellwig {
459508c7cb3SChristoph Hellwig     int score_max = 0, score;
460508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
461f3a5d3f8SChristoph Hellwig 
4628a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
463508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
464508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
465508c7cb3SChristoph Hellwig             if (score > score_max) {
466508c7cb3SChristoph Hellwig                 score_max = score;
467508c7cb3SChristoph Hellwig                 drv = d;
468f3a5d3f8SChristoph Hellwig             }
469508c7cb3SChristoph Hellwig         }
470f3a5d3f8SChristoph Hellwig     }
471f3a5d3f8SChristoph Hellwig 
472508c7cb3SChristoph Hellwig     return drv;
473f3a5d3f8SChristoph Hellwig }
474f3a5d3f8SChristoph Hellwig 
475b50cbabcSMORITA Kazutaka BlockDriver *bdrv_find_protocol(const char *filename)
47684a12e66SChristoph Hellwig {
47784a12e66SChristoph Hellwig     BlockDriver *drv1;
47884a12e66SChristoph Hellwig     char protocol[128];
47984a12e66SChristoph Hellwig     int len;
48084a12e66SChristoph Hellwig     const char *p;
48184a12e66SChristoph Hellwig 
48266f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
48366f82ceeSKevin Wolf 
48439508e7aSChristoph Hellwig     /*
48539508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
48639508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
48739508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
48839508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
48939508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
49039508e7aSChristoph Hellwig      */
49184a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
49239508e7aSChristoph Hellwig     if (drv1) {
49384a12e66SChristoph Hellwig         return drv1;
49484a12e66SChristoph Hellwig     }
49539508e7aSChristoph Hellwig 
4969e0b22f4SStefan Hajnoczi     if (!path_has_protocol(filename)) {
49739508e7aSChristoph Hellwig         return bdrv_find_format("file");
49839508e7aSChristoph Hellwig     }
4999e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
5009e0b22f4SStefan Hajnoczi     assert(p != NULL);
50184a12e66SChristoph Hellwig     len = p - filename;
50284a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
50384a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
50484a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
50584a12e66SChristoph Hellwig     protocol[len] = '\0';
50684a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
50784a12e66SChristoph Hellwig         if (drv1->protocol_name &&
50884a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
50984a12e66SChristoph Hellwig             return drv1;
51084a12e66SChristoph Hellwig         }
51184a12e66SChristoph Hellwig     }
51284a12e66SChristoph Hellwig     return NULL;
51384a12e66SChristoph Hellwig }
51484a12e66SChristoph Hellwig 
515f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
516f500a6d3SKevin Wolf                              BlockDriver **pdrv)
517ea2384d3Sbellard {
518f500a6d3SKevin Wolf     int score, score_max;
519ea2384d3Sbellard     BlockDriver *drv1, *drv;
52083f64091Sbellard     uint8_t buf[2048];
521f500a6d3SKevin Wolf     int ret = 0;
522f8ea0b00SNicholas Bellinger 
52308a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
5248e895599SPaolo Bonzini     if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
525c98ac35dSStefan Weil         drv = bdrv_find_format("raw");
526c98ac35dSStefan Weil         if (!drv) {
527c98ac35dSStefan Weil             ret = -ENOENT;
528c98ac35dSStefan Weil         }
529c98ac35dSStefan Weil         *pdrv = drv;
530c98ac35dSStefan Weil         return ret;
5311a396859SNicholas A. Bellinger     }
532f8ea0b00SNicholas Bellinger 
53383f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
534ea2384d3Sbellard     if (ret < 0) {
535c98ac35dSStefan Weil         *pdrv = NULL;
536c98ac35dSStefan Weil         return ret;
537ea2384d3Sbellard     }
538ea2384d3Sbellard 
539ea2384d3Sbellard     score_max = 0;
54084a12e66SChristoph Hellwig     drv = NULL;
5418a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
54283f64091Sbellard         if (drv1->bdrv_probe) {
543ea2384d3Sbellard             score = drv1->bdrv_probe(buf, ret, filename);
544ea2384d3Sbellard             if (score > score_max) {
545ea2384d3Sbellard                 score_max = score;
546ea2384d3Sbellard                 drv = drv1;
547ea2384d3Sbellard             }
548ea2384d3Sbellard         }
54983f64091Sbellard     }
550c98ac35dSStefan Weil     if (!drv) {
551c98ac35dSStefan Weil         ret = -ENOENT;
552c98ac35dSStefan Weil     }
553c98ac35dSStefan Weil     *pdrv = drv;
554c98ac35dSStefan Weil     return ret;
555ea2384d3Sbellard }
556ea2384d3Sbellard 
55751762288SStefan Hajnoczi /**
55851762288SStefan Hajnoczi  * Set the current 'total_sectors' value
55951762288SStefan Hajnoczi  */
56051762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
56151762288SStefan Hajnoczi {
56251762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
56351762288SStefan Hajnoczi 
564396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
565396759adSNicholas Bellinger     if (bs->sg)
566396759adSNicholas Bellinger         return 0;
567396759adSNicholas Bellinger 
56851762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
56951762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
57051762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
57151762288SStefan Hajnoczi         if (length < 0) {
57251762288SStefan Hajnoczi             return length;
57351762288SStefan Hajnoczi         }
57451762288SStefan Hajnoczi         hint = length >> BDRV_SECTOR_BITS;
57551762288SStefan Hajnoczi     }
57651762288SStefan Hajnoczi 
57751762288SStefan Hajnoczi     bs->total_sectors = hint;
57851762288SStefan Hajnoczi     return 0;
57951762288SStefan Hajnoczi }
58051762288SStefan Hajnoczi 
581c3993cdcSStefan Hajnoczi /**
5829e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
5839e8f1835SPaolo Bonzini  *
5849e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
5859e8f1835SPaolo Bonzini  */
5869e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
5879e8f1835SPaolo Bonzini {
5889e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
5899e8f1835SPaolo Bonzini 
5909e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
5919e8f1835SPaolo Bonzini         /* do nothing */
5929e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
5939e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
5949e8f1835SPaolo Bonzini     } else {
5959e8f1835SPaolo Bonzini         return -1;
5969e8f1835SPaolo Bonzini     }
5979e8f1835SPaolo Bonzini 
5989e8f1835SPaolo Bonzini     return 0;
5999e8f1835SPaolo Bonzini }
6009e8f1835SPaolo Bonzini 
6019e8f1835SPaolo Bonzini /**
602c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
603c3993cdcSStefan Hajnoczi  *
604c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
605c3993cdcSStefan Hajnoczi  */
606c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
607c3993cdcSStefan Hajnoczi {
608c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
609c3993cdcSStefan Hajnoczi 
610c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
611c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
61292196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
61392196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
614c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
615c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
616c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
617c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
618c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
619c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
620c3993cdcSStefan Hajnoczi         /* this is the default */
621c3993cdcSStefan Hajnoczi     } else {
622c3993cdcSStefan Hajnoczi         return -1;
623c3993cdcSStefan Hajnoczi     }
624c3993cdcSStefan Hajnoczi 
625c3993cdcSStefan Hajnoczi     return 0;
626c3993cdcSStefan Hajnoczi }
627c3993cdcSStefan Hajnoczi 
62853fec9d3SStefan Hajnoczi /**
62953fec9d3SStefan Hajnoczi  * The copy-on-read flag is actually a reference count so multiple users may
63053fec9d3SStefan Hajnoczi  * use the feature without worrying about clobbering its previous state.
63153fec9d3SStefan Hajnoczi  * Copy-on-read stays enabled until all users have called to disable it.
63253fec9d3SStefan Hajnoczi  */
63353fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs)
63453fec9d3SStefan Hajnoczi {
63553fec9d3SStefan Hajnoczi     bs->copy_on_read++;
63653fec9d3SStefan Hajnoczi }
63753fec9d3SStefan Hajnoczi 
63853fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs)
63953fec9d3SStefan Hajnoczi {
64053fec9d3SStefan Hajnoczi     assert(bs->copy_on_read > 0);
64153fec9d3SStefan Hajnoczi     bs->copy_on_read--;
64253fec9d3SStefan Hajnoczi }
64353fec9d3SStefan Hajnoczi 
6447b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
6457b272452SKevin Wolf {
6467b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
6477b272452SKevin Wolf 
6487b272452SKevin Wolf     /*
6497b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
6507b272452SKevin Wolf      * image.
6517b272452SKevin Wolf      */
6527b272452SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
6537b272452SKevin Wolf 
6547b272452SKevin Wolf     /*
6557b272452SKevin Wolf      * Snapshots should be writable.
6567b272452SKevin Wolf      */
6577b272452SKevin Wolf     if (bs->is_temporary) {
6587b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
6597b272452SKevin Wolf     }
6607b272452SKevin Wolf 
6617b272452SKevin Wolf     return open_flags;
6627b272452SKevin Wolf }
6637b272452SKevin Wolf 
664b6ce07aaSKevin Wolf /*
66557915332SKevin Wolf  * Common part for opening disk images and files
666b6ad491aSKevin Wolf  *
667b6ad491aSKevin Wolf  * Removes all processed options from *options.
66857915332SKevin Wolf  */
669f500a6d3SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
670035fccdfSKevin Wolf     QDict *options, int flags, BlockDriver *drv)
67157915332SKevin Wolf {
67257915332SKevin Wolf     int ret, open_flags;
673035fccdfSKevin Wolf     const char *filename;
67457915332SKevin Wolf 
67557915332SKevin Wolf     assert(drv != NULL);
6766405875cSPaolo Bonzini     assert(bs->file == NULL);
677707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
67857915332SKevin Wolf 
67928dcee10SStefan Hajnoczi     trace_bdrv_open_common(bs, filename, flags, drv->format_name);
68028dcee10SStefan Hajnoczi 
6815d186eb0SKevin Wolf     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
6825d186eb0SKevin Wolf         return -ENOTSUP;
6835d186eb0SKevin Wolf     }
6845d186eb0SKevin Wolf 
6855d186eb0SKevin Wolf     /* bdrv_open() with directly using a protocol as drv. This layer is already
6865d186eb0SKevin Wolf      * opened, so assign it to bs (while file becomes a closed BlockDriverState)
6875d186eb0SKevin Wolf      * and return immediately. */
6885d186eb0SKevin Wolf     if (file != NULL && drv->bdrv_file_open) {
6895d186eb0SKevin Wolf         bdrv_swap(file, bs);
6905d186eb0SKevin Wolf         return 0;
6915d186eb0SKevin Wolf     }
6925d186eb0SKevin Wolf 
69357915332SKevin Wolf     bs->open_flags = flags;
69457915332SKevin Wolf     bs->buffer_alignment = 512;
69557915332SKevin Wolf 
69653fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
69753fec9d3SStefan Hajnoczi     if ((flags & BDRV_O_RDWR) && (flags & BDRV_O_COPY_ON_READ)) {
69853fec9d3SStefan Hajnoczi         bdrv_enable_copy_on_read(bs);
69953fec9d3SStefan Hajnoczi     }
70053fec9d3SStefan Hajnoczi 
701035fccdfSKevin Wolf     if (file != NULL) {
702035fccdfSKevin Wolf         filename = file->filename;
703035fccdfSKevin Wolf     } else {
704035fccdfSKevin Wolf         filename = qdict_get_try_str(options, "filename");
705035fccdfSKevin Wolf     }
706035fccdfSKevin Wolf 
707c2ad1b0cSKevin Wolf     if (filename != NULL) {
70857915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
709c2ad1b0cSKevin Wolf     } else {
710c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
711c2ad1b0cSKevin Wolf     }
71257915332SKevin Wolf 
71357915332SKevin Wolf     bs->drv = drv;
7147267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
71557915332SKevin Wolf 
71603f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
7177b272452SKevin Wolf     open_flags = bdrv_open_flags(bs, flags);
71857915332SKevin Wolf 
719be028adcSJeff Cody     bs->read_only = !(open_flags & BDRV_O_RDWR);
720e7c63796SStefan Hajnoczi 
72166f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
72266f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
7235d186eb0SKevin Wolf         assert(file == NULL);
724c2ad1b0cSKevin Wolf         assert(drv->bdrv_parse_filename || filename != NULL);
725*56d1b4d2SKevin Wolf         ret = drv->bdrv_file_open(bs, options, open_flags);
726f500a6d3SKevin Wolf     } else {
7272af5ef70SKevin Wolf         if (file == NULL) {
7282af5ef70SKevin Wolf             qerror_report(ERROR_CLASS_GENERIC_ERROR, "Can't use '%s' as a "
7292af5ef70SKevin Wolf                           "block driver for the protocol level",
7302af5ef70SKevin Wolf                           drv->format_name);
7312af5ef70SKevin Wolf             ret = -EINVAL;
7322af5ef70SKevin Wolf             goto free_and_fail;
7332af5ef70SKevin Wolf         }
734f500a6d3SKevin Wolf         assert(file != NULL);
735f500a6d3SKevin Wolf         bs->file = file;
736b6ad491aSKevin Wolf         ret = drv->bdrv_open(bs, options, open_flags);
73766f82ceeSKevin Wolf     }
73866f82ceeSKevin Wolf 
73957915332SKevin Wolf     if (ret < 0) {
74057915332SKevin Wolf         goto free_and_fail;
74157915332SKevin Wolf     }
74257915332SKevin Wolf 
74351762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
74451762288SStefan Hajnoczi     if (ret < 0) {
74551762288SStefan Hajnoczi         goto free_and_fail;
74657915332SKevin Wolf     }
74751762288SStefan Hajnoczi 
74857915332SKevin Wolf #ifndef _WIN32
74957915332SKevin Wolf     if (bs->is_temporary) {
750c2ad1b0cSKevin Wolf         assert(filename != NULL);
75157915332SKevin Wolf         unlink(filename);
75257915332SKevin Wolf     }
75357915332SKevin Wolf #endif
75457915332SKevin Wolf     return 0;
75557915332SKevin Wolf 
75657915332SKevin Wolf free_and_fail:
75766f82ceeSKevin Wolf     bs->file = NULL;
7587267c094SAnthony Liguori     g_free(bs->opaque);
75957915332SKevin Wolf     bs->opaque = NULL;
76057915332SKevin Wolf     bs->drv = NULL;
76157915332SKevin Wolf     return ret;
76257915332SKevin Wolf }
76357915332SKevin Wolf 
76457915332SKevin Wolf /*
765b6ce07aaSKevin Wolf  * Opens a file using a protocol (file, host_device, nbd, ...)
766787e4a85SKevin Wolf  *
767787e4a85SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
768787e4a85SKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
769787e4a85SKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
770787e4a85SKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_file_open.
771b6ce07aaSKevin Wolf  */
772787e4a85SKevin Wolf int bdrv_file_open(BlockDriverState **pbs, const char *filename,
773787e4a85SKevin Wolf                    QDict *options, int flags)
774b338082bSbellard {
77583f64091Sbellard     BlockDriverState *bs;
7766db95603SChristoph Hellwig     BlockDriver *drv;
777c2ad1b0cSKevin Wolf     const char *drvname;
77883f64091Sbellard     int ret;
7793b0d4f61Sbellard 
780707ff828SKevin Wolf     /* NULL means an empty set of options */
781707ff828SKevin Wolf     if (options == NULL) {
782707ff828SKevin Wolf         options = qdict_new();
7833b0d4f61Sbellard     }
784707ff828SKevin Wolf 
785707ff828SKevin Wolf     bs = bdrv_new("");
786707ff828SKevin Wolf     bs->options = options;
787707ff828SKevin Wolf     options = qdict_clone_shallow(options);
788707ff828SKevin Wolf 
789035fccdfSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
790035fccdfSKevin Wolf     if (!filename) {
791035fccdfSKevin Wolf         filename = qdict_get_try_str(options, "filename");
792035fccdfSKevin Wolf     } else if (filename && !qdict_haskey(options, "filename")) {
793035fccdfSKevin Wolf         qdict_put(options, "filename", qstring_from_str(filename));
794035fccdfSKevin Wolf     } else {
795035fccdfSKevin Wolf         qerror_report(ERROR_CLASS_GENERIC_ERROR, "Can't specify 'file' and "
796035fccdfSKevin Wolf                       "'filename' options at the same time");
797035fccdfSKevin Wolf         ret = -EINVAL;
798035fccdfSKevin Wolf         goto fail;
799035fccdfSKevin Wolf     }
800035fccdfSKevin Wolf 
801c2ad1b0cSKevin Wolf     /* Find the right block driver */
802c2ad1b0cSKevin Wolf     drvname = qdict_get_try_str(options, "driver");
803c2ad1b0cSKevin Wolf     if (drvname) {
804c2ad1b0cSKevin Wolf         drv = bdrv_find_whitelisted_format(drvname);
805c2ad1b0cSKevin Wolf         qdict_del(options, "driver");
806c2ad1b0cSKevin Wolf     } else if (filename) {
807c2ad1b0cSKevin Wolf         drv = bdrv_find_protocol(filename);
808c2ad1b0cSKevin Wolf     } else {
809c2ad1b0cSKevin Wolf         qerror_report(ERROR_CLASS_GENERIC_ERROR,
810c2ad1b0cSKevin Wolf                       "Must specify either driver or file");
811c2ad1b0cSKevin Wolf         drv = NULL;
812c2ad1b0cSKevin Wolf     }
813c2ad1b0cSKevin Wolf 
814c2ad1b0cSKevin Wolf     if (!drv) {
815c2ad1b0cSKevin Wolf         ret = -ENOENT;
816c2ad1b0cSKevin Wolf         goto fail;
817c2ad1b0cSKevin Wolf     }
818c2ad1b0cSKevin Wolf 
819c2ad1b0cSKevin Wolf     /* Parse the filename and open it */
820c2ad1b0cSKevin Wolf     if (drv->bdrv_parse_filename && filename) {
8216963a30dSKevin Wolf         Error *local_err = NULL;
8226963a30dSKevin Wolf         drv->bdrv_parse_filename(filename, options, &local_err);
8236963a30dSKevin Wolf         if (error_is_set(&local_err)) {
8246963a30dSKevin Wolf             qerror_report_err(local_err);
8256963a30dSKevin Wolf             error_free(local_err);
8266963a30dSKevin Wolf             ret = -EINVAL;
8276963a30dSKevin Wolf             goto fail;
8286963a30dSKevin Wolf         }
829*56d1b4d2SKevin Wolf         qdict_del(options, "filename");
830c2ad1b0cSKevin Wolf     } else if (!drv->bdrv_parse_filename && !filename) {
831c2ad1b0cSKevin Wolf         qerror_report(ERROR_CLASS_GENERIC_ERROR,
832c2ad1b0cSKevin Wolf                       "The '%s' block driver requires a file name",
833c2ad1b0cSKevin Wolf                       drv->format_name);
834c2ad1b0cSKevin Wolf         ret = -EINVAL;
835c2ad1b0cSKevin Wolf         goto fail;
8366963a30dSKevin Wolf     }
8376963a30dSKevin Wolf 
838035fccdfSKevin Wolf     ret = bdrv_open_common(bs, NULL, options, flags, drv);
839707ff828SKevin Wolf     if (ret < 0) {
840707ff828SKevin Wolf         goto fail;
841707ff828SKevin Wolf     }
842707ff828SKevin Wolf 
843707ff828SKevin Wolf     /* Check if any unknown options were used */
844707ff828SKevin Wolf     if (qdict_size(options) != 0) {
845707ff828SKevin Wolf         const QDictEntry *entry = qdict_first(options);
846707ff828SKevin Wolf         qerror_report(ERROR_CLASS_GENERIC_ERROR, "Block protocol '%s' doesn't "
847707ff828SKevin Wolf                       "support the option '%s'",
848707ff828SKevin Wolf                       drv->format_name, entry->key);
849707ff828SKevin Wolf         ret = -EINVAL;
850707ff828SKevin Wolf         goto fail;
851707ff828SKevin Wolf     }
852707ff828SKevin Wolf     QDECREF(options);
853707ff828SKevin Wolf 
85471d0770cSaliguori     bs->growable = 1;
85583f64091Sbellard     *pbs = bs;
85683f64091Sbellard     return 0;
857707ff828SKevin Wolf 
858707ff828SKevin Wolf fail:
859707ff828SKevin Wolf     QDECREF(options);
860707ff828SKevin Wolf     if (!bs->drv) {
861707ff828SKevin Wolf         QDECREF(bs->options);
862707ff828SKevin Wolf     }
863707ff828SKevin Wolf     bdrv_delete(bs);
864707ff828SKevin Wolf     return ret;
8653b0d4f61Sbellard }
8663b0d4f61Sbellard 
86731ca6d07SKevin Wolf /*
86831ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
86931ca6d07SKevin Wolf  *
87031ca6d07SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
87131ca6d07SKevin Wolf  * empty set of options. The reference to the QDict is transferred to this
87231ca6d07SKevin Wolf  * function (even on failure), so if the caller intends to reuse the dictionary,
87331ca6d07SKevin Wolf  * it needs to use QINCREF() before calling bdrv_file_open.
87431ca6d07SKevin Wolf  */
87531ca6d07SKevin Wolf int bdrv_open_backing_file(BlockDriverState *bs, QDict *options)
8769156df12SPaolo Bonzini {
8779156df12SPaolo Bonzini     char backing_filename[PATH_MAX];
8789156df12SPaolo Bonzini     int back_flags, ret;
8799156df12SPaolo Bonzini     BlockDriver *back_drv = NULL;
8809156df12SPaolo Bonzini 
8819156df12SPaolo Bonzini     if (bs->backing_hd != NULL) {
88231ca6d07SKevin Wolf         QDECREF(options);
8839156df12SPaolo Bonzini         return 0;
8849156df12SPaolo Bonzini     }
8859156df12SPaolo Bonzini 
88631ca6d07SKevin Wolf     /* NULL means an empty set of options */
88731ca6d07SKevin Wolf     if (options == NULL) {
88831ca6d07SKevin Wolf         options = qdict_new();
88931ca6d07SKevin Wolf     }
89031ca6d07SKevin Wolf 
8919156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
89231ca6d07SKevin Wolf     if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
89331ca6d07SKevin Wolf         QDECREF(options);
8949156df12SPaolo Bonzini         return 0;
8959156df12SPaolo Bonzini     }
8969156df12SPaolo Bonzini 
8979156df12SPaolo Bonzini     bs->backing_hd = bdrv_new("");
8989156df12SPaolo Bonzini     bdrv_get_full_backing_filename(bs, backing_filename,
8999156df12SPaolo Bonzini                                    sizeof(backing_filename));
9009156df12SPaolo Bonzini 
9019156df12SPaolo Bonzini     if (bs->backing_format[0] != '\0') {
9029156df12SPaolo Bonzini         back_drv = bdrv_find_format(bs->backing_format);
9039156df12SPaolo Bonzini     }
9049156df12SPaolo Bonzini 
9059156df12SPaolo Bonzini     /* backing files always opened read-only */
9069156df12SPaolo Bonzini     back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT);
9079156df12SPaolo Bonzini 
90831ca6d07SKevin Wolf     ret = bdrv_open(bs->backing_hd,
90931ca6d07SKevin Wolf                     *backing_filename ? backing_filename : NULL, options,
910de9c0cecSKevin Wolf                     back_flags, back_drv);
9119156df12SPaolo Bonzini     if (ret < 0) {
9129156df12SPaolo Bonzini         bdrv_delete(bs->backing_hd);
9139156df12SPaolo Bonzini         bs->backing_hd = NULL;
9149156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
9159156df12SPaolo Bonzini         return ret;
9169156df12SPaolo Bonzini     }
9179156df12SPaolo Bonzini     return 0;
9189156df12SPaolo Bonzini }
9199156df12SPaolo Bonzini 
920707ff828SKevin Wolf static void extract_subqdict(QDict *src, QDict **dst, const char *start)
921707ff828SKevin Wolf {
922707ff828SKevin Wolf     const QDictEntry *entry, *next;
923707ff828SKevin Wolf     const char *p;
924707ff828SKevin Wolf 
925707ff828SKevin Wolf     *dst = qdict_new();
926707ff828SKevin Wolf     entry = qdict_first(src);
927707ff828SKevin Wolf 
928707ff828SKevin Wolf     while (entry != NULL) {
929707ff828SKevin Wolf         next = qdict_next(src, entry);
930707ff828SKevin Wolf         if (strstart(entry->key, start, &p)) {
931707ff828SKevin Wolf             qobject_incref(entry->value);
932707ff828SKevin Wolf             qdict_put_obj(*dst, p, entry->value);
933707ff828SKevin Wolf             qdict_del(src, entry->key);
934707ff828SKevin Wolf         }
935707ff828SKevin Wolf         entry = next;
936707ff828SKevin Wolf     }
937707ff828SKevin Wolf }
938707ff828SKevin Wolf 
939b6ce07aaSKevin Wolf /*
940b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
941de9c0cecSKevin Wolf  *
942de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
943de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
944de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
945de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
946b6ce07aaSKevin Wolf  */
947de9c0cecSKevin Wolf int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,
948de9c0cecSKevin Wolf               int flags, BlockDriver *drv)
949ea2384d3Sbellard {
950b6ce07aaSKevin Wolf     int ret;
95189c9bc3dSStefan Weil     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
95289c9bc3dSStefan Weil     char tmp_filename[PATH_MAX + 1];
953f500a6d3SKevin Wolf     BlockDriverState *file = NULL;
954707ff828SKevin Wolf     QDict *file_options = NULL;
95533e3963eSbellard 
956de9c0cecSKevin Wolf     /* NULL means an empty set of options */
957de9c0cecSKevin Wolf     if (options == NULL) {
958de9c0cecSKevin Wolf         options = qdict_new();
959de9c0cecSKevin Wolf     }
960de9c0cecSKevin Wolf 
961de9c0cecSKevin Wolf     bs->options = options;
962b6ad491aSKevin Wolf     options = qdict_clone_shallow(options);
963de9c0cecSKevin Wolf 
964de9c0cecSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay */
96583f64091Sbellard     if (flags & BDRV_O_SNAPSHOT) {
966ea2384d3Sbellard         BlockDriverState *bs1;
967ea2384d3Sbellard         int64_t total_size;
96891a073a9SKevin Wolf         BlockDriver *bdrv_qcow2;
96908b392e1SKevin Wolf         QEMUOptionParameter *create_options;
970b6ce07aaSKevin Wolf         char backing_filename[PATH_MAX];
97133e3963eSbellard 
972c2ad1b0cSKevin Wolf         if (qdict_size(options) != 0) {
973c2ad1b0cSKevin Wolf             error_report("Can't use snapshot=on with driver-specific options");
974c2ad1b0cSKevin Wolf             ret = -EINVAL;
975c2ad1b0cSKevin Wolf             goto fail;
976c2ad1b0cSKevin Wolf         }
977c2ad1b0cSKevin Wolf         assert(filename != NULL);
978c2ad1b0cSKevin Wolf 
979ea2384d3Sbellard         /* if snapshot, we create a temporary backing file and open it
980ea2384d3Sbellard            instead of opening 'filename' directly */
981ea2384d3Sbellard 
982ea2384d3Sbellard         /* if there is a backing file, use it */
983ea2384d3Sbellard         bs1 = bdrv_new("");
984de9c0cecSKevin Wolf         ret = bdrv_open(bs1, filename, NULL, 0, drv);
98551d7c00cSaliguori         if (ret < 0) {
986ea2384d3Sbellard             bdrv_delete(bs1);
987de9c0cecSKevin Wolf             goto fail;
988ea2384d3Sbellard         }
9893e82990bSJes Sorensen         total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
9907c96d46eSaliguori 
991ea2384d3Sbellard         bdrv_delete(bs1);
992ea2384d3Sbellard 
993eba25057SJim Meyering         ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
994eba25057SJim Meyering         if (ret < 0) {
995de9c0cecSKevin Wolf             goto fail;
996eba25057SJim Meyering         }
9977c96d46eSaliguori 
9987c96d46eSaliguori         /* Real path is meaningless for protocols */
9994d70655bSStefan Hajnoczi         if (path_has_protocol(filename)) {
10007c96d46eSaliguori             snprintf(backing_filename, sizeof(backing_filename),
10017c96d46eSaliguori                      "%s", filename);
1002de9c0cecSKevin Wolf         } else if (!realpath(filename, backing_filename)) {
1003de9c0cecSKevin Wolf             ret = -errno;
1004de9c0cecSKevin Wolf             goto fail;
1005de9c0cecSKevin Wolf         }
10067c96d46eSaliguori 
100791a073a9SKevin Wolf         bdrv_qcow2 = bdrv_find_format("qcow2");
100808b392e1SKevin Wolf         create_options = parse_option_parameters("", bdrv_qcow2->create_options,
100908b392e1SKevin Wolf                                                  NULL);
101091a073a9SKevin Wolf 
101108b392e1SKevin Wolf         set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);
101208b392e1SKevin Wolf         set_option_parameter(create_options, BLOCK_OPT_BACKING_FILE,
101308b392e1SKevin Wolf                              backing_filename);
101491a073a9SKevin Wolf         if (drv) {
101508b392e1SKevin Wolf             set_option_parameter(create_options, BLOCK_OPT_BACKING_FMT,
101691a073a9SKevin Wolf                 drv->format_name);
101791a073a9SKevin Wolf         }
101891a073a9SKevin Wolf 
101908b392e1SKevin Wolf         ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options);
102008b392e1SKevin Wolf         free_option_parameters(create_options);
102151d7c00cSaliguori         if (ret < 0) {
1022de9c0cecSKevin Wolf             goto fail;
1023ea2384d3Sbellard         }
102491a073a9SKevin Wolf 
1025ea2384d3Sbellard         filename = tmp_filename;
102691a073a9SKevin Wolf         drv = bdrv_qcow2;
1027ea2384d3Sbellard         bs->is_temporary = 1;
1028ea2384d3Sbellard     }
1029ea2384d3Sbellard 
1030f500a6d3SKevin Wolf     /* Open image file without format layer */
1031be028adcSJeff Cody     if (flags & BDRV_O_RDWR) {
1032be028adcSJeff Cody         flags |= BDRV_O_ALLOW_RDWR;
1033be028adcSJeff Cody     }
1034be028adcSJeff Cody 
1035707ff828SKevin Wolf     extract_subqdict(options, &file_options, "file.");
1036707ff828SKevin Wolf 
1037707ff828SKevin Wolf     ret = bdrv_file_open(&file, filename, file_options,
1038707ff828SKevin Wolf                          bdrv_open_flags(bs, flags));
1039f500a6d3SKevin Wolf     if (ret < 0) {
1040de9c0cecSKevin Wolf         goto fail;
1041f500a6d3SKevin Wolf     }
1042f500a6d3SKevin Wolf 
1043f500a6d3SKevin Wolf     /* Find the right image format driver */
1044f500a6d3SKevin Wolf     if (!drv) {
1045f500a6d3SKevin Wolf         ret = find_image_format(file, filename, &drv);
1046f500a6d3SKevin Wolf     }
1047f500a6d3SKevin Wolf 
1048f500a6d3SKevin Wolf     if (!drv) {
1049f500a6d3SKevin Wolf         goto unlink_and_fail;
1050f500a6d3SKevin Wolf     }
1051f500a6d3SKevin Wolf 
1052b6ce07aaSKevin Wolf     /* Open the image */
1053035fccdfSKevin Wolf     ret = bdrv_open_common(bs, file, options, flags, drv);
1054b6ce07aaSKevin Wolf     if (ret < 0) {
10556987307cSChristoph Hellwig         goto unlink_and_fail;
10566987307cSChristoph Hellwig     }
10576987307cSChristoph Hellwig 
1058f500a6d3SKevin Wolf     if (bs->file != file) {
1059f500a6d3SKevin Wolf         bdrv_delete(file);
1060f500a6d3SKevin Wolf         file = NULL;
1061f500a6d3SKevin Wolf     }
1062f500a6d3SKevin Wolf 
1063b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
10649156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
106531ca6d07SKevin Wolf         QDict *backing_options;
106631ca6d07SKevin Wolf 
106731ca6d07SKevin Wolf         extract_subqdict(options, &backing_options, "backing.");
106831ca6d07SKevin Wolf         ret = bdrv_open_backing_file(bs, backing_options);
1069b6ce07aaSKevin Wolf         if (ret < 0) {
1070b6ad491aSKevin Wolf             goto close_and_fail;
1071b6ce07aaSKevin Wolf         }
1072b6ce07aaSKevin Wolf     }
1073b6ce07aaSKevin Wolf 
1074b6ad491aSKevin Wolf     /* Check if any unknown options were used */
1075b6ad491aSKevin Wolf     if (qdict_size(options) != 0) {
1076b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
1077b6ad491aSKevin Wolf         qerror_report(ERROR_CLASS_GENERIC_ERROR, "Block format '%s' used by "
1078b6ad491aSKevin Wolf             "device '%s' doesn't support the option '%s'",
1079b6ad491aSKevin Wolf             drv->format_name, bs->device_name, entry->key);
1080b6ad491aSKevin Wolf 
1081b6ad491aSKevin Wolf         ret = -EINVAL;
1082b6ad491aSKevin Wolf         goto close_and_fail;
1083b6ad491aSKevin Wolf     }
1084b6ad491aSKevin Wolf     QDECREF(options);
1085b6ad491aSKevin Wolf 
1086b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
10877d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
1088b6ce07aaSKevin Wolf     }
1089b6ce07aaSKevin Wolf 
109098f90dbaSZhi Yong Wu     /* throttling disk I/O limits */
109198f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
109298f90dbaSZhi Yong Wu         bdrv_io_limits_enable(bs);
109398f90dbaSZhi Yong Wu     }
109498f90dbaSZhi Yong Wu 
1095b6ce07aaSKevin Wolf     return 0;
1096b6ce07aaSKevin Wolf 
1097b6ce07aaSKevin Wolf unlink_and_fail:
1098f500a6d3SKevin Wolf     if (file != NULL) {
1099f500a6d3SKevin Wolf         bdrv_delete(file);
1100f500a6d3SKevin Wolf     }
1101b6ce07aaSKevin Wolf     if (bs->is_temporary) {
1102b6ce07aaSKevin Wolf         unlink(filename);
1103b6ce07aaSKevin Wolf     }
1104de9c0cecSKevin Wolf fail:
1105de9c0cecSKevin Wolf     QDECREF(bs->options);
1106b6ad491aSKevin Wolf     QDECREF(options);
1107de9c0cecSKevin Wolf     bs->options = NULL;
1108b6ad491aSKevin Wolf     return ret;
1109de9c0cecSKevin Wolf 
1110b6ad491aSKevin Wolf close_and_fail:
1111b6ad491aSKevin Wolf     bdrv_close(bs);
1112b6ad491aSKevin Wolf     QDECREF(options);
1113b6ce07aaSKevin Wolf     return ret;
1114b6ce07aaSKevin Wolf }
1115b6ce07aaSKevin Wolf 
1116e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1117e971aa12SJeff Cody      bool prepared;
1118e971aa12SJeff Cody      BDRVReopenState state;
1119e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1120e971aa12SJeff Cody } BlockReopenQueueEntry;
1121e971aa12SJeff Cody 
1122e971aa12SJeff Cody /*
1123e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1124e971aa12SJeff Cody  * reopen of multiple devices.
1125e971aa12SJeff Cody  *
1126e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1127e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1128e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1129e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1130e971aa12SJeff Cody  * atomic 'set'.
1131e971aa12SJeff Cody  *
1132e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1133e971aa12SJeff Cody  *
1134e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1135e971aa12SJeff Cody  *
1136e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1137e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1138e971aa12SJeff Cody  *
1139e971aa12SJeff Cody  */
1140e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1141e971aa12SJeff Cody                                     BlockDriverState *bs, int flags)
1142e971aa12SJeff Cody {
1143e971aa12SJeff Cody     assert(bs != NULL);
1144e971aa12SJeff Cody 
1145e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
1146e971aa12SJeff Cody     if (bs_queue == NULL) {
1147e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1148e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1149e971aa12SJeff Cody     }
1150e971aa12SJeff Cody 
1151e971aa12SJeff Cody     if (bs->file) {
1152e971aa12SJeff Cody         bdrv_reopen_queue(bs_queue, bs->file, flags);
1153e971aa12SJeff Cody     }
1154e971aa12SJeff Cody 
1155e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1156e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1157e971aa12SJeff Cody 
1158e971aa12SJeff Cody     bs_entry->state.bs = bs;
1159e971aa12SJeff Cody     bs_entry->state.flags = flags;
1160e971aa12SJeff Cody 
1161e971aa12SJeff Cody     return bs_queue;
1162e971aa12SJeff Cody }
1163e971aa12SJeff Cody 
1164e971aa12SJeff Cody /*
1165e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1166e971aa12SJeff Cody  *
1167e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1168e971aa12SJeff Cody  * via bdrv_reopen_queue().
1169e971aa12SJeff Cody  *
1170e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1171e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1172e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1173e971aa12SJeff Cody  * data cleaned up.
1174e971aa12SJeff Cody  *
1175e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1176e971aa12SJeff Cody  * to all devices.
1177e971aa12SJeff Cody  *
1178e971aa12SJeff Cody  */
1179e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1180e971aa12SJeff Cody {
1181e971aa12SJeff Cody     int ret = -1;
1182e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1183e971aa12SJeff Cody     Error *local_err = NULL;
1184e971aa12SJeff Cody 
1185e971aa12SJeff Cody     assert(bs_queue != NULL);
1186e971aa12SJeff Cody 
1187e971aa12SJeff Cody     bdrv_drain_all();
1188e971aa12SJeff Cody 
1189e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1190e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1191e971aa12SJeff Cody             error_propagate(errp, local_err);
1192e971aa12SJeff Cody             goto cleanup;
1193e971aa12SJeff Cody         }
1194e971aa12SJeff Cody         bs_entry->prepared = true;
1195e971aa12SJeff Cody     }
1196e971aa12SJeff Cody 
1197e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1198e971aa12SJeff Cody      * changes
1199e971aa12SJeff Cody      */
1200e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1201e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1202e971aa12SJeff Cody     }
1203e971aa12SJeff Cody 
1204e971aa12SJeff Cody     ret = 0;
1205e971aa12SJeff Cody 
1206e971aa12SJeff Cody cleanup:
1207e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1208e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1209e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1210e971aa12SJeff Cody         }
1211e971aa12SJeff Cody         g_free(bs_entry);
1212e971aa12SJeff Cody     }
1213e971aa12SJeff Cody     g_free(bs_queue);
1214e971aa12SJeff Cody     return ret;
1215e971aa12SJeff Cody }
1216e971aa12SJeff Cody 
1217e971aa12SJeff Cody 
1218e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1219e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1220e971aa12SJeff Cody {
1221e971aa12SJeff Cody     int ret = -1;
1222e971aa12SJeff Cody     Error *local_err = NULL;
1223e971aa12SJeff Cody     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1224e971aa12SJeff Cody 
1225e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1226e971aa12SJeff Cody     if (local_err != NULL) {
1227e971aa12SJeff Cody         error_propagate(errp, local_err);
1228e971aa12SJeff Cody     }
1229e971aa12SJeff Cody     return ret;
1230e971aa12SJeff Cody }
1231e971aa12SJeff Cody 
1232e971aa12SJeff Cody 
1233e971aa12SJeff Cody /*
1234e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1235e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1236e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1237e971aa12SJeff Cody  *
1238e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1239e971aa12SJeff Cody  * flags are the new open flags
1240e971aa12SJeff Cody  * queue is the reopen queue
1241e971aa12SJeff Cody  *
1242e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1243e971aa12SJeff Cody  * as well.
1244e971aa12SJeff Cody  *
1245e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1246e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1247e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1248e971aa12SJeff Cody  *
1249e971aa12SJeff Cody  */
1250e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1251e971aa12SJeff Cody                         Error **errp)
1252e971aa12SJeff Cody {
1253e971aa12SJeff Cody     int ret = -1;
1254e971aa12SJeff Cody     Error *local_err = NULL;
1255e971aa12SJeff Cody     BlockDriver *drv;
1256e971aa12SJeff Cody 
1257e971aa12SJeff Cody     assert(reopen_state != NULL);
1258e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1259e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1260e971aa12SJeff Cody 
1261e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1262e971aa12SJeff Cody      * to r/w */
1263e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1264e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
1265e971aa12SJeff Cody         error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1266e971aa12SJeff Cody                   reopen_state->bs->device_name);
1267e971aa12SJeff Cody         goto error;
1268e971aa12SJeff Cody     }
1269e971aa12SJeff Cody 
1270e971aa12SJeff Cody 
1271e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1272e971aa12SJeff Cody     if (ret) {
1273e971aa12SJeff Cody         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1274e971aa12SJeff Cody                   strerror(-ret));
1275e971aa12SJeff Cody         goto error;
1276e971aa12SJeff Cody     }
1277e971aa12SJeff Cody 
1278e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1279e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1280e971aa12SJeff Cody         if (ret) {
1281e971aa12SJeff Cody             if (local_err != NULL) {
1282e971aa12SJeff Cody                 error_propagate(errp, local_err);
1283e971aa12SJeff Cody             } else {
1284e971aa12SJeff Cody                 error_set(errp, QERR_OPEN_FILE_FAILED,
1285e971aa12SJeff Cody                           reopen_state->bs->filename);
1286e971aa12SJeff Cody             }
1287e971aa12SJeff Cody             goto error;
1288e971aa12SJeff Cody         }
1289e971aa12SJeff Cody     } else {
1290e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1291e971aa12SJeff Cody          * handler for each supported drv. */
1292e971aa12SJeff Cody         error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1293e971aa12SJeff Cody                   drv->format_name, reopen_state->bs->device_name,
1294e971aa12SJeff Cody                  "reopening of file");
1295e971aa12SJeff Cody         ret = -1;
1296e971aa12SJeff Cody         goto error;
1297e971aa12SJeff Cody     }
1298e971aa12SJeff Cody 
1299e971aa12SJeff Cody     ret = 0;
1300e971aa12SJeff Cody 
1301e971aa12SJeff Cody error:
1302e971aa12SJeff Cody     return ret;
1303e971aa12SJeff Cody }
1304e971aa12SJeff Cody 
1305e971aa12SJeff Cody /*
1306e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1307e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1308e971aa12SJeff Cody  * the active BlockDriverState contents.
1309e971aa12SJeff Cody  */
1310e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1311e971aa12SJeff Cody {
1312e971aa12SJeff Cody     BlockDriver *drv;
1313e971aa12SJeff Cody 
1314e971aa12SJeff Cody     assert(reopen_state != NULL);
1315e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1316e971aa12SJeff Cody     assert(drv != NULL);
1317e971aa12SJeff Cody 
1318e971aa12SJeff Cody     /* If there are any driver level actions to take */
1319e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1320e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1321e971aa12SJeff Cody     }
1322e971aa12SJeff Cody 
1323e971aa12SJeff Cody     /* set BDS specific flags now */
1324e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1325e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1326e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1327e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1328e971aa12SJeff Cody }
1329e971aa12SJeff Cody 
1330e971aa12SJeff Cody /*
1331e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1332e971aa12SJeff Cody  * reopen_state
1333e971aa12SJeff Cody  */
1334e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1335e971aa12SJeff Cody {
1336e971aa12SJeff Cody     BlockDriver *drv;
1337e971aa12SJeff Cody 
1338e971aa12SJeff Cody     assert(reopen_state != NULL);
1339e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1340e971aa12SJeff Cody     assert(drv != NULL);
1341e971aa12SJeff Cody 
1342e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1343e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1344e971aa12SJeff Cody     }
1345e971aa12SJeff Cody }
1346e971aa12SJeff Cody 
1347e971aa12SJeff Cody 
1348fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1349fc01f7e7Sbellard {
135080ccf93bSLiu Yuan     bdrv_flush(bs);
13513e914655SPaolo Bonzini     if (bs->job) {
13523e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
13533e914655SPaolo Bonzini     }
13547094f12fSKevin Wolf     bdrv_drain_all();
1355d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
13567094f12fSKevin Wolf 
13573cbc002cSPaolo Bonzini     if (bs->drv) {
1358f9092b10SMarkus Armbruster         if (bs == bs_snapshots) {
1359f9092b10SMarkus Armbruster             bs_snapshots = NULL;
1360f9092b10SMarkus Armbruster         }
1361557df6acSStefan Hajnoczi         if (bs->backing_hd) {
1362ea2384d3Sbellard             bdrv_delete(bs->backing_hd);
1363557df6acSStefan Hajnoczi             bs->backing_hd = NULL;
1364557df6acSStefan Hajnoczi         }
1365ea2384d3Sbellard         bs->drv->bdrv_close(bs);
13667267c094SAnthony Liguori         g_free(bs->opaque);
1367ea2384d3Sbellard #ifdef _WIN32
1368ea2384d3Sbellard         if (bs->is_temporary) {
1369ea2384d3Sbellard             unlink(bs->filename);
1370ea2384d3Sbellard         }
137167b915a5Sbellard #endif
1372ea2384d3Sbellard         bs->opaque = NULL;
1373ea2384d3Sbellard         bs->drv = NULL;
137453fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1375a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1376a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
13776405875cSPaolo Bonzini         bs->total_sectors = 0;
13786405875cSPaolo Bonzini         bs->encrypted = 0;
13796405875cSPaolo Bonzini         bs->valid_key = 0;
13806405875cSPaolo Bonzini         bs->sg = 0;
13816405875cSPaolo Bonzini         bs->growable = 0;
1382de9c0cecSKevin Wolf         QDECREF(bs->options);
1383de9c0cecSKevin Wolf         bs->options = NULL;
1384b338082bSbellard 
138566f82ceeSKevin Wolf         if (bs->file != NULL) {
13860ac9377dSPaolo Bonzini             bdrv_delete(bs->file);
13870ac9377dSPaolo Bonzini             bs->file = NULL;
138866f82ceeSKevin Wolf         }
13899ca11154SPavel Hrdina     }
139066f82ceeSKevin Wolf 
13917d4b4ba5SMarkus Armbruster     bdrv_dev_change_media_cb(bs, false);
139298f90dbaSZhi Yong Wu 
139398f90dbaSZhi Yong Wu     /*throttling disk I/O limits*/
139498f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
139598f90dbaSZhi Yong Wu         bdrv_io_limits_disable(bs);
139698f90dbaSZhi Yong Wu     }
1397b338082bSbellard }
1398b338082bSbellard 
13992bc93fedSMORITA Kazutaka void bdrv_close_all(void)
14002bc93fedSMORITA Kazutaka {
14012bc93fedSMORITA Kazutaka     BlockDriverState *bs;
14022bc93fedSMORITA Kazutaka 
14032bc93fedSMORITA Kazutaka     QTAILQ_FOREACH(bs, &bdrv_states, list) {
14042bc93fedSMORITA Kazutaka         bdrv_close(bs);
14052bc93fedSMORITA Kazutaka     }
14062bc93fedSMORITA Kazutaka }
14072bc93fedSMORITA Kazutaka 
1408922453bcSStefan Hajnoczi /*
1409922453bcSStefan Hajnoczi  * Wait for pending requests to complete across all BlockDriverStates
1410922453bcSStefan Hajnoczi  *
1411922453bcSStefan Hajnoczi  * This function does not flush data to disk, use bdrv_flush_all() for that
1412922453bcSStefan Hajnoczi  * after calling this function.
14134c355d53SZhi Yong Wu  *
14144c355d53SZhi Yong Wu  * Note that completion of an asynchronous I/O operation can trigger any
14154c355d53SZhi Yong Wu  * number of other I/O operations on other devices---for example a coroutine
14164c355d53SZhi Yong Wu  * can be arbitrarily complex and a constant flow of I/O can come until the
14174c355d53SZhi Yong Wu  * coroutine is complete.  Because of this, it is not possible to have a
14184c355d53SZhi Yong Wu  * function to drain a single device's I/O queue.
1419922453bcSStefan Hajnoczi  */
1420922453bcSStefan Hajnoczi void bdrv_drain_all(void)
1421922453bcSStefan Hajnoczi {
1422922453bcSStefan Hajnoczi     BlockDriverState *bs;
14234c355d53SZhi Yong Wu     bool busy;
1424922453bcSStefan Hajnoczi 
14254c355d53SZhi Yong Wu     do {
14264c355d53SZhi Yong Wu         busy = qemu_aio_wait();
14274c355d53SZhi Yong Wu 
14284c355d53SZhi Yong Wu         /* FIXME: We do not have timer support here, so this is effectively
14294c355d53SZhi Yong Wu          * a busy wait.
14304c355d53SZhi Yong Wu          */
14314c355d53SZhi Yong Wu         QTAILQ_FOREACH(bs, &bdrv_states, list) {
14324c355d53SZhi Yong Wu             if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
14334c355d53SZhi Yong Wu                 qemu_co_queue_restart_all(&bs->throttled_reqs);
14344c355d53SZhi Yong Wu                 busy = true;
14354c355d53SZhi Yong Wu             }
14364c355d53SZhi Yong Wu         }
14374c355d53SZhi Yong Wu     } while (busy);
1438922453bcSStefan Hajnoczi 
1439922453bcSStefan Hajnoczi     /* If requests are still pending there is a bug somewhere */
1440922453bcSStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1441922453bcSStefan Hajnoczi         assert(QLIST_EMPTY(&bs->tracked_requests));
1442922453bcSStefan Hajnoczi         assert(qemu_co_queue_empty(&bs->throttled_reqs));
1443922453bcSStefan Hajnoczi     }
1444922453bcSStefan Hajnoczi }
1445922453bcSStefan Hajnoczi 
1446d22b2f41SRyan Harper /* make a BlockDriverState anonymous by removing from bdrv_state list.
1447d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
1448d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
1449d22b2f41SRyan Harper {
1450d22b2f41SRyan Harper     if (bs->device_name[0] != '\0') {
1451d22b2f41SRyan Harper         QTAILQ_REMOVE(&bdrv_states, bs, list);
1452d22b2f41SRyan Harper     }
1453d22b2f41SRyan Harper     bs->device_name[0] = '\0';
1454d22b2f41SRyan Harper }
1455d22b2f41SRyan Harper 
1456e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs)
1457e023b2e2SPaolo Bonzini {
1458e023b2e2SPaolo Bonzini     if (bs->drv && bs->drv->bdrv_rebind) {
1459e023b2e2SPaolo Bonzini         bs->drv->bdrv_rebind(bs);
1460e023b2e2SPaolo Bonzini     }
1461e023b2e2SPaolo Bonzini }
1462e023b2e2SPaolo Bonzini 
14634ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
14644ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
14654ddc07caSPaolo Bonzini {
14664ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
14674ddc07caSPaolo Bonzini     bs_dest->open_flags         = bs_src->open_flags;
14684ddc07caSPaolo Bonzini 
14694ddc07caSPaolo Bonzini     /* dev info */
14704ddc07caSPaolo Bonzini     bs_dest->dev_ops            = bs_src->dev_ops;
14714ddc07caSPaolo Bonzini     bs_dest->dev_opaque         = bs_src->dev_opaque;
14724ddc07caSPaolo Bonzini     bs_dest->dev                = bs_src->dev;
14734ddc07caSPaolo Bonzini     bs_dest->buffer_alignment   = bs_src->buffer_alignment;
14744ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
14754ddc07caSPaolo Bonzini 
14764ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
14774ddc07caSPaolo Bonzini 
14784ddc07caSPaolo Bonzini     /* i/o timing parameters */
14794ddc07caSPaolo Bonzini     bs_dest->slice_start        = bs_src->slice_start;
14804ddc07caSPaolo Bonzini     bs_dest->slice_end          = bs_src->slice_end;
14815905fbc9SStefan Hajnoczi     bs_dest->slice_submitted    = bs_src->slice_submitted;
14824ddc07caSPaolo Bonzini     bs_dest->io_limits          = bs_src->io_limits;
14834ddc07caSPaolo Bonzini     bs_dest->throttled_reqs     = bs_src->throttled_reqs;
14844ddc07caSPaolo Bonzini     bs_dest->block_timer        = bs_src->block_timer;
14854ddc07caSPaolo Bonzini     bs_dest->io_limits_enabled  = bs_src->io_limits_enabled;
14864ddc07caSPaolo Bonzini 
14874ddc07caSPaolo Bonzini     /* r/w error */
14884ddc07caSPaolo Bonzini     bs_dest->on_read_error      = bs_src->on_read_error;
14894ddc07caSPaolo Bonzini     bs_dest->on_write_error     = bs_src->on_write_error;
14904ddc07caSPaolo Bonzini 
14914ddc07caSPaolo Bonzini     /* i/o status */
14924ddc07caSPaolo Bonzini     bs_dest->iostatus_enabled   = bs_src->iostatus_enabled;
14934ddc07caSPaolo Bonzini     bs_dest->iostatus           = bs_src->iostatus;
14944ddc07caSPaolo Bonzini 
14954ddc07caSPaolo Bonzini     /* dirty bitmap */
14964ddc07caSPaolo Bonzini     bs_dest->dirty_bitmap       = bs_src->dirty_bitmap;
14974ddc07caSPaolo Bonzini 
14984ddc07caSPaolo Bonzini     /* job */
14994ddc07caSPaolo Bonzini     bs_dest->in_use             = bs_src->in_use;
15004ddc07caSPaolo Bonzini     bs_dest->job                = bs_src->job;
15014ddc07caSPaolo Bonzini 
15024ddc07caSPaolo Bonzini     /* keep the same entry in bdrv_states */
15034ddc07caSPaolo Bonzini     pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
15044ddc07caSPaolo Bonzini             bs_src->device_name);
15054ddc07caSPaolo Bonzini     bs_dest->list = bs_src->list;
15064ddc07caSPaolo Bonzini }
15074ddc07caSPaolo Bonzini 
15084ddc07caSPaolo Bonzini /*
15094ddc07caSPaolo Bonzini  * Swap bs contents for two image chains while they are live,
15104ddc07caSPaolo Bonzini  * while keeping required fields on the BlockDriverState that is
15114ddc07caSPaolo Bonzini  * actually attached to a device.
15124ddc07caSPaolo Bonzini  *
15134ddc07caSPaolo Bonzini  * This will modify the BlockDriverState fields, and swap contents
15144ddc07caSPaolo Bonzini  * between bs_new and bs_old. Both bs_new and bs_old are modified.
15154ddc07caSPaolo Bonzini  *
15164ddc07caSPaolo Bonzini  * bs_new is required to be anonymous.
15174ddc07caSPaolo Bonzini  *
15184ddc07caSPaolo Bonzini  * This function does not create any image files.
15194ddc07caSPaolo Bonzini  */
15204ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
15214ddc07caSPaolo Bonzini {
15224ddc07caSPaolo Bonzini     BlockDriverState tmp;
15234ddc07caSPaolo Bonzini 
15244ddc07caSPaolo Bonzini     /* bs_new must be anonymous and shouldn't have anything fancy enabled */
15254ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
15264ddc07caSPaolo Bonzini     assert(bs_new->dirty_bitmap == NULL);
15274ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
15284ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
15294ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
15304ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
15314ddc07caSPaolo Bonzini     assert(bs_new->block_timer == NULL);
15324ddc07caSPaolo Bonzini 
15334ddc07caSPaolo Bonzini     tmp = *bs_new;
15344ddc07caSPaolo Bonzini     *bs_new = *bs_old;
15354ddc07caSPaolo Bonzini     *bs_old = tmp;
15364ddc07caSPaolo Bonzini 
15374ddc07caSPaolo Bonzini     /* there are some fields that should not be swapped, move them back */
15384ddc07caSPaolo Bonzini     bdrv_move_feature_fields(&tmp, bs_old);
15394ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_old, bs_new);
15404ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_new, &tmp);
15414ddc07caSPaolo Bonzini 
15424ddc07caSPaolo Bonzini     /* bs_new shouldn't be in bdrv_states even after the swap!  */
15434ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
15444ddc07caSPaolo Bonzini 
15454ddc07caSPaolo Bonzini     /* Check a few fields that should remain attached to the device */
15464ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
15474ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
15484ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
15494ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
15504ddc07caSPaolo Bonzini     assert(bs_new->block_timer == NULL);
15514ddc07caSPaolo Bonzini 
15524ddc07caSPaolo Bonzini     bdrv_rebind(bs_new);
15534ddc07caSPaolo Bonzini     bdrv_rebind(bs_old);
15544ddc07caSPaolo Bonzini }
15554ddc07caSPaolo Bonzini 
15568802d1fdSJeff Cody /*
15578802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
15588802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
15598802d1fdSJeff Cody  *
15608802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
15618802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
15628802d1fdSJeff Cody  *
1563f6801b83SJeff Cody  * bs_new is required to be anonymous.
1564f6801b83SJeff Cody  *
15658802d1fdSJeff Cody  * This function does not create any image files.
15668802d1fdSJeff Cody  */
15678802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
15688802d1fdSJeff Cody {
15694ddc07caSPaolo Bonzini     bdrv_swap(bs_new, bs_top);
15708802d1fdSJeff Cody 
15718802d1fdSJeff Cody     /* The contents of 'tmp' will become bs_top, as we are
15728802d1fdSJeff Cody      * swapping bs_new and bs_top contents. */
15734ddc07caSPaolo Bonzini     bs_top->backing_hd = bs_new;
15744ddc07caSPaolo Bonzini     bs_top->open_flags &= ~BDRV_O_NO_BACKING;
15754ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
15764ddc07caSPaolo Bonzini             bs_new->filename);
15774ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
15784ddc07caSPaolo Bonzini             bs_new->drv ? bs_new->drv->format_name : "");
15798802d1fdSJeff Cody }
15808802d1fdSJeff Cody 
1581b338082bSbellard void bdrv_delete(BlockDriverState *bs)
1582b338082bSbellard {
1583fa879d62SMarkus Armbruster     assert(!bs->dev);
15843e914655SPaolo Bonzini     assert(!bs->job);
15853e914655SPaolo Bonzini     assert(!bs->in_use);
158618846deeSMarkus Armbruster 
15871b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
1588d22b2f41SRyan Harper     bdrv_make_anon(bs);
158934c6f050Saurel32 
1590b338082bSbellard     bdrv_close(bs);
159166f82ceeSKevin Wolf 
1592f9092b10SMarkus Armbruster     assert(bs != bs_snapshots);
15937267c094SAnthony Liguori     g_free(bs);
1594fc01f7e7Sbellard }
1595fc01f7e7Sbellard 
1596fa879d62SMarkus Armbruster int bdrv_attach_dev(BlockDriverState *bs, void *dev)
1597fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
159818846deeSMarkus Armbruster {
1599fa879d62SMarkus Armbruster     if (bs->dev) {
160018846deeSMarkus Armbruster         return -EBUSY;
160118846deeSMarkus Armbruster     }
1602fa879d62SMarkus Armbruster     bs->dev = dev;
160328a7282aSLuiz Capitulino     bdrv_iostatus_reset(bs);
160418846deeSMarkus Armbruster     return 0;
160518846deeSMarkus Armbruster }
160618846deeSMarkus Armbruster 
1607fa879d62SMarkus Armbruster /* TODO qdevified devices don't use this, remove when devices are qdevified */
1608fa879d62SMarkus Armbruster void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
160918846deeSMarkus Armbruster {
1610fa879d62SMarkus Armbruster     if (bdrv_attach_dev(bs, dev) < 0) {
1611fa879d62SMarkus Armbruster         abort();
1612fa879d62SMarkus Armbruster     }
1613fa879d62SMarkus Armbruster }
1614fa879d62SMarkus Armbruster 
1615fa879d62SMarkus Armbruster void bdrv_detach_dev(BlockDriverState *bs, void *dev)
1616fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
1617fa879d62SMarkus Armbruster {
1618fa879d62SMarkus Armbruster     assert(bs->dev == dev);
1619fa879d62SMarkus Armbruster     bs->dev = NULL;
16200e49de52SMarkus Armbruster     bs->dev_ops = NULL;
16210e49de52SMarkus Armbruster     bs->dev_opaque = NULL;
162229e05f20SMarkus Armbruster     bs->buffer_alignment = 512;
162318846deeSMarkus Armbruster }
162418846deeSMarkus Armbruster 
1625fa879d62SMarkus Armbruster /* TODO change to return DeviceState * when all users are qdevified */
1626fa879d62SMarkus Armbruster void *bdrv_get_attached_dev(BlockDriverState *bs)
162718846deeSMarkus Armbruster {
1628fa879d62SMarkus Armbruster     return bs->dev;
162918846deeSMarkus Armbruster }
163018846deeSMarkus Armbruster 
16310e49de52SMarkus Armbruster void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
16320e49de52SMarkus Armbruster                       void *opaque)
16330e49de52SMarkus Armbruster {
16340e49de52SMarkus Armbruster     bs->dev_ops = ops;
16350e49de52SMarkus Armbruster     bs->dev_opaque = opaque;
16362c6942faSMarkus Armbruster     if (bdrv_dev_has_removable_media(bs) && bs == bs_snapshots) {
16372c6942faSMarkus Armbruster         bs_snapshots = NULL;
16382c6942faSMarkus Armbruster     }
16390e49de52SMarkus Armbruster }
16400e49de52SMarkus Armbruster 
164132c81a4aSPaolo Bonzini void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
164232c81a4aSPaolo Bonzini                                enum MonitorEvent ev,
16431ceee0d5SPaolo Bonzini                                BlockErrorAction action, bool is_read)
1644329c0a48SLuiz Capitulino {
1645329c0a48SLuiz Capitulino     QObject *data;
1646329c0a48SLuiz Capitulino     const char *action_str;
1647329c0a48SLuiz Capitulino 
1648329c0a48SLuiz Capitulino     switch (action) {
1649329c0a48SLuiz Capitulino     case BDRV_ACTION_REPORT:
1650329c0a48SLuiz Capitulino         action_str = "report";
1651329c0a48SLuiz Capitulino         break;
1652329c0a48SLuiz Capitulino     case BDRV_ACTION_IGNORE:
1653329c0a48SLuiz Capitulino         action_str = "ignore";
1654329c0a48SLuiz Capitulino         break;
1655329c0a48SLuiz Capitulino     case BDRV_ACTION_STOP:
1656329c0a48SLuiz Capitulino         action_str = "stop";
1657329c0a48SLuiz Capitulino         break;
1658329c0a48SLuiz Capitulino     default:
1659329c0a48SLuiz Capitulino         abort();
1660329c0a48SLuiz Capitulino     }
1661329c0a48SLuiz Capitulino 
1662329c0a48SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1663329c0a48SLuiz Capitulino                               bdrv->device_name,
1664329c0a48SLuiz Capitulino                               action_str,
1665329c0a48SLuiz Capitulino                               is_read ? "read" : "write");
166632c81a4aSPaolo Bonzini     monitor_protocol_event(ev, data);
1667329c0a48SLuiz Capitulino 
1668329c0a48SLuiz Capitulino     qobject_decref(data);
1669329c0a48SLuiz Capitulino }
1670329c0a48SLuiz Capitulino 
16716f382ed2SLuiz Capitulino static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
16726f382ed2SLuiz Capitulino {
16736f382ed2SLuiz Capitulino     QObject *data;
16746f382ed2SLuiz Capitulino 
16756f382ed2SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
16766f382ed2SLuiz Capitulino                               bdrv_get_device_name(bs), ejected);
16776f382ed2SLuiz Capitulino     monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
16786f382ed2SLuiz Capitulino 
16796f382ed2SLuiz Capitulino     qobject_decref(data);
16806f382ed2SLuiz Capitulino }
16816f382ed2SLuiz Capitulino 
16827d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
16830e49de52SMarkus Armbruster {
1684145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->change_media_cb) {
16856f382ed2SLuiz Capitulino         bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
16867d4b4ba5SMarkus Armbruster         bs->dev_ops->change_media_cb(bs->dev_opaque, load);
16876f382ed2SLuiz Capitulino         if (tray_was_closed) {
16886f382ed2SLuiz Capitulino             /* tray open */
16896f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, true);
16906f382ed2SLuiz Capitulino         }
16916f382ed2SLuiz Capitulino         if (load) {
16926f382ed2SLuiz Capitulino             /* tray close */
16936f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, false);
16946f382ed2SLuiz Capitulino         }
1695145feb17SMarkus Armbruster     }
1696145feb17SMarkus Armbruster }
1697145feb17SMarkus Armbruster 
16982c6942faSMarkus Armbruster bool bdrv_dev_has_removable_media(BlockDriverState *bs)
16992c6942faSMarkus Armbruster {
17002c6942faSMarkus Armbruster     return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
17012c6942faSMarkus Armbruster }
17022c6942faSMarkus Armbruster 
1703025ccaa7SPaolo Bonzini void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
1704025ccaa7SPaolo Bonzini {
1705025ccaa7SPaolo Bonzini     if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
1706025ccaa7SPaolo Bonzini         bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
1707025ccaa7SPaolo Bonzini     }
1708025ccaa7SPaolo Bonzini }
1709025ccaa7SPaolo Bonzini 
1710e4def80bSMarkus Armbruster bool bdrv_dev_is_tray_open(BlockDriverState *bs)
1711e4def80bSMarkus Armbruster {
1712e4def80bSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_tray_open) {
1713e4def80bSMarkus Armbruster         return bs->dev_ops->is_tray_open(bs->dev_opaque);
1714e4def80bSMarkus Armbruster     }
1715e4def80bSMarkus Armbruster     return false;
1716e4def80bSMarkus Armbruster }
1717e4def80bSMarkus Armbruster 
1718145feb17SMarkus Armbruster static void bdrv_dev_resize_cb(BlockDriverState *bs)
1719145feb17SMarkus Armbruster {
1720145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->resize_cb) {
1721145feb17SMarkus Armbruster         bs->dev_ops->resize_cb(bs->dev_opaque);
17220e49de52SMarkus Armbruster     }
17230e49de52SMarkus Armbruster }
17240e49de52SMarkus Armbruster 
1725f107639aSMarkus Armbruster bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
1726f107639aSMarkus Armbruster {
1727f107639aSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
1728f107639aSMarkus Armbruster         return bs->dev_ops->is_medium_locked(bs->dev_opaque);
1729f107639aSMarkus Armbruster     }
1730f107639aSMarkus Armbruster     return false;
1731f107639aSMarkus Armbruster }
1732f107639aSMarkus Armbruster 
1733e97fc193Saliguori /*
1734e97fc193Saliguori  * Run consistency checks on an image
1735e97fc193Saliguori  *
1736e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
1737a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
1738e076f338SKevin Wolf  * check are stored in res.
1739e97fc193Saliguori  */
17404534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
1741e97fc193Saliguori {
1742e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
1743e97fc193Saliguori         return -ENOTSUP;
1744e97fc193Saliguori     }
1745e97fc193Saliguori 
1746e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
17474534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
1748e97fc193Saliguori }
1749e97fc193Saliguori 
17508a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
17518a426614SKevin Wolf 
175233e3963eSbellard /* commit COW file into the raw image */
175333e3963eSbellard int bdrv_commit(BlockDriverState *bs)
175433e3963eSbellard {
175519cb3738Sbellard     BlockDriver *drv = bs->drv;
17568a426614SKevin Wolf     int64_t sector, total_sectors;
17578a426614SKevin Wolf     int n, ro, open_flags;
17580bce597dSJeff Cody     int ret = 0;
17598a426614SKevin Wolf     uint8_t *buf;
1760c2cba3d9SJim Meyering     char filename[PATH_MAX];
176133e3963eSbellard 
176219cb3738Sbellard     if (!drv)
176319cb3738Sbellard         return -ENOMEDIUM;
176433e3963eSbellard 
17654dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
17664dca4b63SNaphtali Sprei         return -ENOTSUP;
17674dca4b63SNaphtali Sprei     }
17684dca4b63SNaphtali Sprei 
17692d3735d3SStefan Hajnoczi     if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
17702d3735d3SStefan Hajnoczi         return -EBUSY;
17712d3735d3SStefan Hajnoczi     }
17722d3735d3SStefan Hajnoczi 
17734dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
1774c2cba3d9SJim Meyering     /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
1775c2cba3d9SJim Meyering     pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
17764dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
17774dca4b63SNaphtali Sprei 
17784dca4b63SNaphtali Sprei     if (ro) {
17790bce597dSJeff Cody         if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
17800bce597dSJeff Cody             return -EACCES;
17814dca4b63SNaphtali Sprei         }
1782ea2384d3Sbellard     }
1783ea2384d3Sbellard 
17846ea44308SJan Kiszka     total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
17857267c094SAnthony Liguori     buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
17868a426614SKevin Wolf 
17878a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
178805c4af54SStefan Hajnoczi         if (bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
17898a426614SKevin Wolf 
17908a426614SKevin Wolf             if (bdrv_read(bs, sector, buf, n) != 0) {
17914dca4b63SNaphtali Sprei                 ret = -EIO;
17924dca4b63SNaphtali Sprei                 goto ro_cleanup;
179333e3963eSbellard             }
179433e3963eSbellard 
17958a426614SKevin Wolf             if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
17964dca4b63SNaphtali Sprei                 ret = -EIO;
17974dca4b63SNaphtali Sprei                 goto ro_cleanup;
179833e3963eSbellard             }
179933e3963eSbellard         }
180033e3963eSbellard     }
180195389c86Sbellard 
18021d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
18031d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
18041d44952fSChristoph Hellwig         bdrv_flush(bs);
18051d44952fSChristoph Hellwig     }
180695389c86Sbellard 
18073f5075aeSChristoph Hellwig     /*
18083f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
18093f5075aeSChristoph Hellwig      * stable on disk.
18103f5075aeSChristoph Hellwig      */
18113f5075aeSChristoph Hellwig     if (bs->backing_hd)
18123f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
18134dca4b63SNaphtali Sprei 
18144dca4b63SNaphtali Sprei ro_cleanup:
18157267c094SAnthony Liguori     g_free(buf);
18164dca4b63SNaphtali Sprei 
18174dca4b63SNaphtali Sprei     if (ro) {
18180bce597dSJeff Cody         /* ignoring error return here */
18190bce597dSJeff Cody         bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
18204dca4b63SNaphtali Sprei     }
18214dca4b63SNaphtali Sprei 
18221d44952fSChristoph Hellwig     return ret;
182333e3963eSbellard }
182433e3963eSbellard 
1825e8877497SStefan Hajnoczi int bdrv_commit_all(void)
18266ab4b5abSMarkus Armbruster {
18276ab4b5abSMarkus Armbruster     BlockDriverState *bs;
18286ab4b5abSMarkus Armbruster 
18296ab4b5abSMarkus Armbruster     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1830272d2d8eSJeff Cody         if (bs->drv && bs->backing_hd) {
1831e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
1832e8877497SStefan Hajnoczi             if (ret < 0) {
1833e8877497SStefan Hajnoczi                 return ret;
18346ab4b5abSMarkus Armbruster             }
18356ab4b5abSMarkus Armbruster         }
1836272d2d8eSJeff Cody     }
1837e8877497SStefan Hajnoczi     return 0;
1838e8877497SStefan Hajnoczi }
18396ab4b5abSMarkus Armbruster 
1840dbffbdcfSStefan Hajnoczi struct BdrvTrackedRequest {
1841dbffbdcfSStefan Hajnoczi     BlockDriverState *bs;
1842dbffbdcfSStefan Hajnoczi     int64_t sector_num;
1843dbffbdcfSStefan Hajnoczi     int nb_sectors;
1844dbffbdcfSStefan Hajnoczi     bool is_write;
1845dbffbdcfSStefan Hajnoczi     QLIST_ENTRY(BdrvTrackedRequest) list;
18465f8b6491SStefan Hajnoczi     Coroutine *co; /* owner, used for deadlock detection */
1847f4658285SStefan Hajnoczi     CoQueue wait_queue; /* coroutines blocked on this request */
1848dbffbdcfSStefan Hajnoczi };
1849dbffbdcfSStefan Hajnoczi 
1850dbffbdcfSStefan Hajnoczi /**
1851dbffbdcfSStefan Hajnoczi  * Remove an active request from the tracked requests list
1852dbffbdcfSStefan Hajnoczi  *
1853dbffbdcfSStefan Hajnoczi  * This function should be called when a tracked request is completing.
1854dbffbdcfSStefan Hajnoczi  */
1855dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req)
1856dbffbdcfSStefan Hajnoczi {
1857dbffbdcfSStefan Hajnoczi     QLIST_REMOVE(req, list);
1858f4658285SStefan Hajnoczi     qemu_co_queue_restart_all(&req->wait_queue);
1859dbffbdcfSStefan Hajnoczi }
1860dbffbdcfSStefan Hajnoczi 
1861dbffbdcfSStefan Hajnoczi /**
1862dbffbdcfSStefan Hajnoczi  * Add an active request to the tracked requests list
1863dbffbdcfSStefan Hajnoczi  */
1864dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req,
1865dbffbdcfSStefan Hajnoczi                                   BlockDriverState *bs,
1866dbffbdcfSStefan Hajnoczi                                   int64_t sector_num,
1867dbffbdcfSStefan Hajnoczi                                   int nb_sectors, bool is_write)
1868dbffbdcfSStefan Hajnoczi {
1869dbffbdcfSStefan Hajnoczi     *req = (BdrvTrackedRequest){
1870dbffbdcfSStefan Hajnoczi         .bs = bs,
1871dbffbdcfSStefan Hajnoczi         .sector_num = sector_num,
1872dbffbdcfSStefan Hajnoczi         .nb_sectors = nb_sectors,
1873dbffbdcfSStefan Hajnoczi         .is_write = is_write,
18745f8b6491SStefan Hajnoczi         .co = qemu_coroutine_self(),
1875dbffbdcfSStefan Hajnoczi     };
1876dbffbdcfSStefan Hajnoczi 
1877f4658285SStefan Hajnoczi     qemu_co_queue_init(&req->wait_queue);
1878f4658285SStefan Hajnoczi 
1879dbffbdcfSStefan Hajnoczi     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
1880dbffbdcfSStefan Hajnoczi }
1881dbffbdcfSStefan Hajnoczi 
1882d83947acSStefan Hajnoczi /**
1883d83947acSStefan Hajnoczi  * Round a region to cluster boundaries
1884d83947acSStefan Hajnoczi  */
1885343bded4SPaolo Bonzini void bdrv_round_to_clusters(BlockDriverState *bs,
1886d83947acSStefan Hajnoczi                             int64_t sector_num, int nb_sectors,
1887d83947acSStefan Hajnoczi                             int64_t *cluster_sector_num,
1888d83947acSStefan Hajnoczi                             int *cluster_nb_sectors)
1889d83947acSStefan Hajnoczi {
1890d83947acSStefan Hajnoczi     BlockDriverInfo bdi;
1891d83947acSStefan Hajnoczi 
1892d83947acSStefan Hajnoczi     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
1893d83947acSStefan Hajnoczi         *cluster_sector_num = sector_num;
1894d83947acSStefan Hajnoczi         *cluster_nb_sectors = nb_sectors;
1895d83947acSStefan Hajnoczi     } else {
1896d83947acSStefan Hajnoczi         int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
1897d83947acSStefan Hajnoczi         *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
1898d83947acSStefan Hajnoczi         *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
1899d83947acSStefan Hajnoczi                                             nb_sectors, c);
1900d83947acSStefan Hajnoczi     }
1901d83947acSStefan Hajnoczi }
1902d83947acSStefan Hajnoczi 
1903f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req,
1904f4658285SStefan Hajnoczi                                      int64_t sector_num, int nb_sectors) {
1905d83947acSStefan Hajnoczi     /*        aaaa   bbbb */
1906d83947acSStefan Hajnoczi     if (sector_num >= req->sector_num + req->nb_sectors) {
1907d83947acSStefan Hajnoczi         return false;
1908d83947acSStefan Hajnoczi     }
1909d83947acSStefan Hajnoczi     /* bbbb   aaaa        */
1910d83947acSStefan Hajnoczi     if (req->sector_num >= sector_num + nb_sectors) {
1911d83947acSStefan Hajnoczi         return false;
1912d83947acSStefan Hajnoczi     }
1913d83947acSStefan Hajnoczi     return true;
1914f4658285SStefan Hajnoczi }
1915f4658285SStefan Hajnoczi 
1916f4658285SStefan Hajnoczi static void coroutine_fn wait_for_overlapping_requests(BlockDriverState *bs,
1917f4658285SStefan Hajnoczi         int64_t sector_num, int nb_sectors)
1918f4658285SStefan Hajnoczi {
1919f4658285SStefan Hajnoczi     BdrvTrackedRequest *req;
1920d83947acSStefan Hajnoczi     int64_t cluster_sector_num;
1921d83947acSStefan Hajnoczi     int cluster_nb_sectors;
1922f4658285SStefan Hajnoczi     bool retry;
1923f4658285SStefan Hajnoczi 
1924d83947acSStefan Hajnoczi     /* If we touch the same cluster it counts as an overlap.  This guarantees
1925d83947acSStefan Hajnoczi      * that allocating writes will be serialized and not race with each other
1926d83947acSStefan Hajnoczi      * for the same cluster.  For example, in copy-on-read it ensures that the
1927d83947acSStefan Hajnoczi      * CoR read and write operations are atomic and guest writes cannot
1928d83947acSStefan Hajnoczi      * interleave between them.
1929d83947acSStefan Hajnoczi      */
1930343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
1931d83947acSStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
1932d83947acSStefan Hajnoczi 
1933f4658285SStefan Hajnoczi     do {
1934f4658285SStefan Hajnoczi         retry = false;
1935f4658285SStefan Hajnoczi         QLIST_FOREACH(req, &bs->tracked_requests, list) {
1936d83947acSStefan Hajnoczi             if (tracked_request_overlaps(req, cluster_sector_num,
1937d83947acSStefan Hajnoczi                                          cluster_nb_sectors)) {
19385f8b6491SStefan Hajnoczi                 /* Hitting this means there was a reentrant request, for
19395f8b6491SStefan Hajnoczi                  * example, a block driver issuing nested requests.  This must
19405f8b6491SStefan Hajnoczi                  * never happen since it means deadlock.
19415f8b6491SStefan Hajnoczi                  */
19425f8b6491SStefan Hajnoczi                 assert(qemu_coroutine_self() != req->co);
19435f8b6491SStefan Hajnoczi 
1944f4658285SStefan Hajnoczi                 qemu_co_queue_wait(&req->wait_queue);
1945f4658285SStefan Hajnoczi                 retry = true;
1946f4658285SStefan Hajnoczi                 break;
1947f4658285SStefan Hajnoczi             }
1948f4658285SStefan Hajnoczi         }
1949f4658285SStefan Hajnoczi     } while (retry);
1950f4658285SStefan Hajnoczi }
1951f4658285SStefan Hajnoczi 
1952756e6736SKevin Wolf /*
1953756e6736SKevin Wolf  * Return values:
1954756e6736SKevin Wolf  * 0        - success
1955756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
1956756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
1957756e6736SKevin Wolf  *            image file header
1958756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
1959756e6736SKevin Wolf  */
1960756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
1961756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
1962756e6736SKevin Wolf {
1963756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
1964469ef350SPaolo Bonzini     int ret;
1965756e6736SKevin Wolf 
19665f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
19675f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
19685f377794SPaolo Bonzini         return -EINVAL;
19695f377794SPaolo Bonzini     }
19705f377794SPaolo Bonzini 
1971756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
1972469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
1973756e6736SKevin Wolf     } else {
1974469ef350SPaolo Bonzini         ret = -ENOTSUP;
1975756e6736SKevin Wolf     }
1976469ef350SPaolo Bonzini 
1977469ef350SPaolo Bonzini     if (ret == 0) {
1978469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1979469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1980469ef350SPaolo Bonzini     }
1981469ef350SPaolo Bonzini     return ret;
1982756e6736SKevin Wolf }
1983756e6736SKevin Wolf 
19846ebdcee2SJeff Cody /*
19856ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
19866ebdcee2SJeff Cody  *
19876ebdcee2SJeff Cody  * active is the current topmost image.
19886ebdcee2SJeff Cody  *
19896ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
19906ebdcee2SJeff Cody  * or if active == bs.
19916ebdcee2SJeff Cody  */
19926ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
19936ebdcee2SJeff Cody                                     BlockDriverState *bs)
19946ebdcee2SJeff Cody {
19956ebdcee2SJeff Cody     BlockDriverState *overlay = NULL;
19966ebdcee2SJeff Cody     BlockDriverState *intermediate;
19976ebdcee2SJeff Cody 
19986ebdcee2SJeff Cody     assert(active != NULL);
19996ebdcee2SJeff Cody     assert(bs != NULL);
20006ebdcee2SJeff Cody 
20016ebdcee2SJeff Cody     /* if bs is the same as active, then by definition it has no overlay
20026ebdcee2SJeff Cody      */
20036ebdcee2SJeff Cody     if (active == bs) {
20046ebdcee2SJeff Cody         return NULL;
20056ebdcee2SJeff Cody     }
20066ebdcee2SJeff Cody 
20076ebdcee2SJeff Cody     intermediate = active;
20086ebdcee2SJeff Cody     while (intermediate->backing_hd) {
20096ebdcee2SJeff Cody         if (intermediate->backing_hd == bs) {
20106ebdcee2SJeff Cody             overlay = intermediate;
20116ebdcee2SJeff Cody             break;
20126ebdcee2SJeff Cody         }
20136ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
20146ebdcee2SJeff Cody     }
20156ebdcee2SJeff Cody 
20166ebdcee2SJeff Cody     return overlay;
20176ebdcee2SJeff Cody }
20186ebdcee2SJeff Cody 
20196ebdcee2SJeff Cody typedef struct BlkIntermediateStates {
20206ebdcee2SJeff Cody     BlockDriverState *bs;
20216ebdcee2SJeff Cody     QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
20226ebdcee2SJeff Cody } BlkIntermediateStates;
20236ebdcee2SJeff Cody 
20246ebdcee2SJeff Cody 
20256ebdcee2SJeff Cody /*
20266ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
20276ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
20286ebdcee2SJeff Cody  *
20296ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
20306ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
20316ebdcee2SJeff Cody  *
20326ebdcee2SJeff Cody  * E.g., this will convert the following chain:
20336ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
20346ebdcee2SJeff Cody  *
20356ebdcee2SJeff Cody  * to
20366ebdcee2SJeff Cody  *
20376ebdcee2SJeff Cody  * bottom <- base <- active
20386ebdcee2SJeff Cody  *
20396ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
20406ebdcee2SJeff Cody  *
20416ebdcee2SJeff Cody  * base <- intermediate <- top <- active
20426ebdcee2SJeff Cody  *
20436ebdcee2SJeff Cody  * to
20446ebdcee2SJeff Cody  *
20456ebdcee2SJeff Cody  * base <- active
20466ebdcee2SJeff Cody  *
20476ebdcee2SJeff Cody  * Error conditions:
20486ebdcee2SJeff Cody  *  if active == top, that is considered an error
20496ebdcee2SJeff Cody  *
20506ebdcee2SJeff Cody  */
20516ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
20526ebdcee2SJeff Cody                            BlockDriverState *base)
20536ebdcee2SJeff Cody {
20546ebdcee2SJeff Cody     BlockDriverState *intermediate;
20556ebdcee2SJeff Cody     BlockDriverState *base_bs = NULL;
20566ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
20576ebdcee2SJeff Cody     BlkIntermediateStates *intermediate_state, *next;
20586ebdcee2SJeff Cody     int ret = -EIO;
20596ebdcee2SJeff Cody 
20606ebdcee2SJeff Cody     QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
20616ebdcee2SJeff Cody     QSIMPLEQ_INIT(&states_to_delete);
20626ebdcee2SJeff Cody 
20636ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
20646ebdcee2SJeff Cody         goto exit;
20656ebdcee2SJeff Cody     }
20666ebdcee2SJeff Cody 
20676ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
20686ebdcee2SJeff Cody 
20696ebdcee2SJeff Cody     if (new_top_bs == NULL) {
20706ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
20716ebdcee2SJeff Cody         goto exit;
20726ebdcee2SJeff Cody     }
20736ebdcee2SJeff Cody 
20746ebdcee2SJeff Cody     /* special case of new_top_bs->backing_hd already pointing to base - nothing
20756ebdcee2SJeff Cody      * to do, no intermediate images */
20766ebdcee2SJeff Cody     if (new_top_bs->backing_hd == base) {
20776ebdcee2SJeff Cody         ret = 0;
20786ebdcee2SJeff Cody         goto exit;
20796ebdcee2SJeff Cody     }
20806ebdcee2SJeff Cody 
20816ebdcee2SJeff Cody     intermediate = top;
20826ebdcee2SJeff Cody 
20836ebdcee2SJeff Cody     /* now we will go down through the list, and add each BDS we find
20846ebdcee2SJeff Cody      * into our deletion queue, until we hit the 'base'
20856ebdcee2SJeff Cody      */
20866ebdcee2SJeff Cody     while (intermediate) {
20876ebdcee2SJeff Cody         intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
20886ebdcee2SJeff Cody         intermediate_state->bs = intermediate;
20896ebdcee2SJeff Cody         QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
20906ebdcee2SJeff Cody 
20916ebdcee2SJeff Cody         if (intermediate->backing_hd == base) {
20926ebdcee2SJeff Cody             base_bs = intermediate->backing_hd;
20936ebdcee2SJeff Cody             break;
20946ebdcee2SJeff Cody         }
20956ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
20966ebdcee2SJeff Cody     }
20976ebdcee2SJeff Cody     if (base_bs == NULL) {
20986ebdcee2SJeff Cody         /* something went wrong, we did not end at the base. safely
20996ebdcee2SJeff Cody          * unravel everything, and exit with error */
21006ebdcee2SJeff Cody         goto exit;
21016ebdcee2SJeff Cody     }
21026ebdcee2SJeff Cody 
21036ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
21046ebdcee2SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
21056ebdcee2SJeff Cody                                    base_bs->drv ? base_bs->drv->format_name : "");
21066ebdcee2SJeff Cody     if (ret) {
21076ebdcee2SJeff Cody         goto exit;
21086ebdcee2SJeff Cody     }
21096ebdcee2SJeff Cody     new_top_bs->backing_hd = base_bs;
21106ebdcee2SJeff Cody 
21116ebdcee2SJeff Cody 
21126ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
21136ebdcee2SJeff Cody         /* so that bdrv_close() does not recursively close the chain */
21146ebdcee2SJeff Cody         intermediate_state->bs->backing_hd = NULL;
21156ebdcee2SJeff Cody         bdrv_delete(intermediate_state->bs);
21166ebdcee2SJeff Cody     }
21176ebdcee2SJeff Cody     ret = 0;
21186ebdcee2SJeff Cody 
21196ebdcee2SJeff Cody exit:
21206ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
21216ebdcee2SJeff Cody         g_free(intermediate_state);
21226ebdcee2SJeff Cody     }
21236ebdcee2SJeff Cody     return ret;
21246ebdcee2SJeff Cody }
21256ebdcee2SJeff Cody 
21266ebdcee2SJeff Cody 
212771d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
212871d0770cSaliguori                                    size_t size)
212971d0770cSaliguori {
213071d0770cSaliguori     int64_t len;
213171d0770cSaliguori 
213271d0770cSaliguori     if (!bdrv_is_inserted(bs))
213371d0770cSaliguori         return -ENOMEDIUM;
213471d0770cSaliguori 
213571d0770cSaliguori     if (bs->growable)
213671d0770cSaliguori         return 0;
213771d0770cSaliguori 
213871d0770cSaliguori     len = bdrv_getlength(bs);
213971d0770cSaliguori 
2140fbb7b4e0SKevin Wolf     if (offset < 0)
2141fbb7b4e0SKevin Wolf         return -EIO;
2142fbb7b4e0SKevin Wolf 
2143fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
214471d0770cSaliguori         return -EIO;
214571d0770cSaliguori 
214671d0770cSaliguori     return 0;
214771d0770cSaliguori }
214871d0770cSaliguori 
214971d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
215071d0770cSaliguori                               int nb_sectors)
215171d0770cSaliguori {
2152eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
2153eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
215471d0770cSaliguori }
215571d0770cSaliguori 
21561c9805a3SStefan Hajnoczi typedef struct RwCo {
21571c9805a3SStefan Hajnoczi     BlockDriverState *bs;
21581c9805a3SStefan Hajnoczi     int64_t sector_num;
21591c9805a3SStefan Hajnoczi     int nb_sectors;
21601c9805a3SStefan Hajnoczi     QEMUIOVector *qiov;
21611c9805a3SStefan Hajnoczi     bool is_write;
21621c9805a3SStefan Hajnoczi     int ret;
21631c9805a3SStefan Hajnoczi } RwCo;
21641c9805a3SStefan Hajnoczi 
21651c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque)
2166fc01f7e7Sbellard {
21671c9805a3SStefan Hajnoczi     RwCo *rwco = opaque;
2168fc01f7e7Sbellard 
21691c9805a3SStefan Hajnoczi     if (!rwco->is_write) {
21701c9805a3SStefan Hajnoczi         rwco->ret = bdrv_co_do_readv(rwco->bs, rwco->sector_num,
2171470c0504SStefan Hajnoczi                                      rwco->nb_sectors, rwco->qiov, 0);
21721c9805a3SStefan Hajnoczi     } else {
21731c9805a3SStefan Hajnoczi         rwco->ret = bdrv_co_do_writev(rwco->bs, rwco->sector_num,
2174f08f2ddaSStefan Hajnoczi                                       rwco->nb_sectors, rwco->qiov, 0);
21751c9805a3SStefan Hajnoczi     }
21761c9805a3SStefan Hajnoczi }
2177e7a8a783SKevin Wolf 
21781c9805a3SStefan Hajnoczi /*
21798d3b1a2dSKevin Wolf  * Process a vectored synchronous request using coroutines
21801c9805a3SStefan Hajnoczi  */
21818d3b1a2dSKevin Wolf static int bdrv_rwv_co(BlockDriverState *bs, int64_t sector_num,
21828d3b1a2dSKevin Wolf                        QEMUIOVector *qiov, bool is_write)
21831c9805a3SStefan Hajnoczi {
21841c9805a3SStefan Hajnoczi     Coroutine *co;
21851c9805a3SStefan Hajnoczi     RwCo rwco = {
21861c9805a3SStefan Hajnoczi         .bs = bs,
21871c9805a3SStefan Hajnoczi         .sector_num = sector_num,
21888d3b1a2dSKevin Wolf         .nb_sectors = qiov->size >> BDRV_SECTOR_BITS,
21898d3b1a2dSKevin Wolf         .qiov = qiov,
21901c9805a3SStefan Hajnoczi         .is_write = is_write,
21911c9805a3SStefan Hajnoczi         .ret = NOT_DONE,
21921c9805a3SStefan Hajnoczi     };
21938d3b1a2dSKevin Wolf     assert((qiov->size & (BDRV_SECTOR_SIZE - 1)) == 0);
21941c9805a3SStefan Hajnoczi 
2195498e386cSZhi Yong Wu     /**
2196498e386cSZhi Yong Wu      * In sync call context, when the vcpu is blocked, this throttling timer
2197498e386cSZhi Yong Wu      * will not fire; so the I/O throttling function has to be disabled here
2198498e386cSZhi Yong Wu      * if it has been enabled.
2199498e386cSZhi Yong Wu      */
2200498e386cSZhi Yong Wu     if (bs->io_limits_enabled) {
2201498e386cSZhi Yong Wu         fprintf(stderr, "Disabling I/O throttling on '%s' due "
2202498e386cSZhi Yong Wu                         "to synchronous I/O.\n", bdrv_get_device_name(bs));
2203498e386cSZhi Yong Wu         bdrv_io_limits_disable(bs);
2204498e386cSZhi Yong Wu     }
2205498e386cSZhi Yong Wu 
22061c9805a3SStefan Hajnoczi     if (qemu_in_coroutine()) {
22071c9805a3SStefan Hajnoczi         /* Fast-path if already in coroutine context */
22081c9805a3SStefan Hajnoczi         bdrv_rw_co_entry(&rwco);
22091c9805a3SStefan Hajnoczi     } else {
22101c9805a3SStefan Hajnoczi         co = qemu_coroutine_create(bdrv_rw_co_entry);
22111c9805a3SStefan Hajnoczi         qemu_coroutine_enter(co, &rwco);
22121c9805a3SStefan Hajnoczi         while (rwco.ret == NOT_DONE) {
22131c9805a3SStefan Hajnoczi             qemu_aio_wait();
22141c9805a3SStefan Hajnoczi         }
22151c9805a3SStefan Hajnoczi     }
22161c9805a3SStefan Hajnoczi     return rwco.ret;
2217e7a8a783SKevin Wolf }
2218e7a8a783SKevin Wolf 
22198d3b1a2dSKevin Wolf /*
22208d3b1a2dSKevin Wolf  * Process a synchronous request using coroutines
22218d3b1a2dSKevin Wolf  */
22228d3b1a2dSKevin Wolf static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
22238d3b1a2dSKevin Wolf                       int nb_sectors, bool is_write)
22248d3b1a2dSKevin Wolf {
22258d3b1a2dSKevin Wolf     QEMUIOVector qiov;
22268d3b1a2dSKevin Wolf     struct iovec iov = {
22278d3b1a2dSKevin Wolf         .iov_base = (void *)buf,
22288d3b1a2dSKevin Wolf         .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
22298d3b1a2dSKevin Wolf     };
22308d3b1a2dSKevin Wolf 
22318d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
22328d3b1a2dSKevin Wolf     return bdrv_rwv_co(bs, sector_num, &qiov, is_write);
22338d3b1a2dSKevin Wolf }
22348d3b1a2dSKevin Wolf 
22351c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */
22361c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num,
22371c9805a3SStefan Hajnoczi               uint8_t *buf, int nb_sectors)
22381c9805a3SStefan Hajnoczi {
22391c9805a3SStefan Hajnoczi     return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false);
224083f64091Sbellard }
2241fc01f7e7Sbellard 
224207d27a44SMarkus Armbruster /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
224307d27a44SMarkus Armbruster int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
224407d27a44SMarkus Armbruster                           uint8_t *buf, int nb_sectors)
224507d27a44SMarkus Armbruster {
224607d27a44SMarkus Armbruster     bool enabled;
224707d27a44SMarkus Armbruster     int ret;
224807d27a44SMarkus Armbruster 
224907d27a44SMarkus Armbruster     enabled = bs->io_limits_enabled;
225007d27a44SMarkus Armbruster     bs->io_limits_enabled = false;
225107d27a44SMarkus Armbruster     ret = bdrv_read(bs, 0, buf, 1);
225207d27a44SMarkus Armbruster     bs->io_limits_enabled = enabled;
225307d27a44SMarkus Armbruster     return ret;
225407d27a44SMarkus Armbruster }
225507d27a44SMarkus Armbruster 
225619cb3738Sbellard /* Return < 0 if error. Important errors are:
225719cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
225819cb3738Sbellard   -ENOMEDIUM   No media inserted.
225919cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
226019cb3738Sbellard   -EACCES      Trying to write a read-only device
226119cb3738Sbellard */
2262fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
2263fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
2264fc01f7e7Sbellard {
22651c9805a3SStefan Hajnoczi     return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true);
226683f64091Sbellard }
226783f64091Sbellard 
22688d3b1a2dSKevin Wolf int bdrv_writev(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov)
22698d3b1a2dSKevin Wolf {
22708d3b1a2dSKevin Wolf     return bdrv_rwv_co(bs, sector_num, qiov, true);
22718d3b1a2dSKevin Wolf }
22728d3b1a2dSKevin Wolf 
2273eda578e5Saliguori int bdrv_pread(BlockDriverState *bs, int64_t offset,
2274eda578e5Saliguori                void *buf, int count1)
227583f64091Sbellard {
22766ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
227783f64091Sbellard     int len, nb_sectors, count;
227883f64091Sbellard     int64_t sector_num;
22799a8c4cceSKevin Wolf     int ret;
228083f64091Sbellard 
228183f64091Sbellard     count = count1;
228283f64091Sbellard     /* first read to align to sector start */
22836ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
228483f64091Sbellard     if (len > count)
228583f64091Sbellard         len = count;
22866ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
228783f64091Sbellard     if (len > 0) {
22889a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
22899a8c4cceSKevin Wolf             return ret;
22906ea44308SJan Kiszka         memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
229183f64091Sbellard         count -= len;
229283f64091Sbellard         if (count == 0)
229383f64091Sbellard             return count1;
229483f64091Sbellard         sector_num++;
229583f64091Sbellard         buf += len;
229683f64091Sbellard     }
229783f64091Sbellard 
229883f64091Sbellard     /* read the sectors "in place" */
22996ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
230083f64091Sbellard     if (nb_sectors > 0) {
23019a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
23029a8c4cceSKevin Wolf             return ret;
230383f64091Sbellard         sector_num += nb_sectors;
23046ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
230583f64091Sbellard         buf += len;
230683f64091Sbellard         count -= len;
230783f64091Sbellard     }
230883f64091Sbellard 
230983f64091Sbellard     /* add data from the last sector */
231083f64091Sbellard     if (count > 0) {
23119a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
23129a8c4cceSKevin Wolf             return ret;
231383f64091Sbellard         memcpy(buf, tmp_buf, count);
231483f64091Sbellard     }
231583f64091Sbellard     return count1;
231683f64091Sbellard }
231783f64091Sbellard 
23188d3b1a2dSKevin Wolf int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
231983f64091Sbellard {
23206ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
232183f64091Sbellard     int len, nb_sectors, count;
232283f64091Sbellard     int64_t sector_num;
23239a8c4cceSKevin Wolf     int ret;
232483f64091Sbellard 
23258d3b1a2dSKevin Wolf     count = qiov->size;
23268d3b1a2dSKevin Wolf 
232783f64091Sbellard     /* first write to align to sector start */
23286ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
232983f64091Sbellard     if (len > count)
233083f64091Sbellard         len = count;
23316ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
233283f64091Sbellard     if (len > 0) {
23339a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
23349a8c4cceSKevin Wolf             return ret;
23358d3b1a2dSKevin Wolf         qemu_iovec_to_buf(qiov, 0, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)),
23368d3b1a2dSKevin Wolf                           len);
23379a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
23389a8c4cceSKevin Wolf             return ret;
233983f64091Sbellard         count -= len;
234083f64091Sbellard         if (count == 0)
23418d3b1a2dSKevin Wolf             return qiov->size;
234283f64091Sbellard         sector_num++;
234383f64091Sbellard     }
234483f64091Sbellard 
234583f64091Sbellard     /* write the sectors "in place" */
23466ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
234783f64091Sbellard     if (nb_sectors > 0) {
23488d3b1a2dSKevin Wolf         QEMUIOVector qiov_inplace;
23498d3b1a2dSKevin Wolf 
23508d3b1a2dSKevin Wolf         qemu_iovec_init(&qiov_inplace, qiov->niov);
23518d3b1a2dSKevin Wolf         qemu_iovec_concat(&qiov_inplace, qiov, len,
23528d3b1a2dSKevin Wolf                           nb_sectors << BDRV_SECTOR_BITS);
23538d3b1a2dSKevin Wolf         ret = bdrv_writev(bs, sector_num, &qiov_inplace);
23548d3b1a2dSKevin Wolf         qemu_iovec_destroy(&qiov_inplace);
23558d3b1a2dSKevin Wolf         if (ret < 0) {
23569a8c4cceSKevin Wolf             return ret;
23578d3b1a2dSKevin Wolf         }
23588d3b1a2dSKevin Wolf 
235983f64091Sbellard         sector_num += nb_sectors;
23606ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
236183f64091Sbellard         count -= len;
236283f64091Sbellard     }
236383f64091Sbellard 
236483f64091Sbellard     /* add data from the last sector */
236583f64091Sbellard     if (count > 0) {
23669a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
23679a8c4cceSKevin Wolf             return ret;
23688d3b1a2dSKevin Wolf         qemu_iovec_to_buf(qiov, qiov->size - count, tmp_buf, count);
23699a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
23709a8c4cceSKevin Wolf             return ret;
237183f64091Sbellard     }
23728d3b1a2dSKevin Wolf     return qiov->size;
23738d3b1a2dSKevin Wolf }
23748d3b1a2dSKevin Wolf 
23758d3b1a2dSKevin Wolf int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
23768d3b1a2dSKevin Wolf                 const void *buf, int count1)
23778d3b1a2dSKevin Wolf {
23788d3b1a2dSKevin Wolf     QEMUIOVector qiov;
23798d3b1a2dSKevin Wolf     struct iovec iov = {
23808d3b1a2dSKevin Wolf         .iov_base   = (void *) buf,
23818d3b1a2dSKevin Wolf         .iov_len    = count1,
23828d3b1a2dSKevin Wolf     };
23838d3b1a2dSKevin Wolf 
23848d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
23858d3b1a2dSKevin Wolf     return bdrv_pwritev(bs, offset, &qiov);
238683f64091Sbellard }
238783f64091Sbellard 
2388f08145feSKevin Wolf /*
2389f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
2390f08145feSKevin Wolf  * request (acts as a barrier)
2391f08145feSKevin Wolf  *
2392f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
2393f08145feSKevin Wolf  */
2394f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2395f08145feSKevin Wolf     const void *buf, int count)
2396f08145feSKevin Wolf {
2397f08145feSKevin Wolf     int ret;
2398f08145feSKevin Wolf 
2399f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
2400f08145feSKevin Wolf     if (ret < 0) {
2401f08145feSKevin Wolf         return ret;
2402f08145feSKevin Wolf     }
2403f08145feSKevin Wolf 
2404f05fa4adSPaolo Bonzini     /* No flush needed for cache modes that already do it */
2405f05fa4adSPaolo Bonzini     if (bs->enable_write_cache) {
2406f08145feSKevin Wolf         bdrv_flush(bs);
2407f08145feSKevin Wolf     }
2408f08145feSKevin Wolf 
2409f08145feSKevin Wolf     return 0;
2410f08145feSKevin Wolf }
2411f08145feSKevin Wolf 
2412470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
2413ab185921SStefan Hajnoczi         int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2414ab185921SStefan Hajnoczi {
2415ab185921SStefan Hajnoczi     /* Perform I/O through a temporary buffer so that users who scribble over
2416ab185921SStefan Hajnoczi      * their read buffer while the operation is in progress do not end up
2417ab185921SStefan Hajnoczi      * modifying the image file.  This is critical for zero-copy guest I/O
2418ab185921SStefan Hajnoczi      * where anything might happen inside guest memory.
2419ab185921SStefan Hajnoczi      */
2420ab185921SStefan Hajnoczi     void *bounce_buffer;
2421ab185921SStefan Hajnoczi 
242279c053bdSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2423ab185921SStefan Hajnoczi     struct iovec iov;
2424ab185921SStefan Hajnoczi     QEMUIOVector bounce_qiov;
2425ab185921SStefan Hajnoczi     int64_t cluster_sector_num;
2426ab185921SStefan Hajnoczi     int cluster_nb_sectors;
2427ab185921SStefan Hajnoczi     size_t skip_bytes;
2428ab185921SStefan Hajnoczi     int ret;
2429ab185921SStefan Hajnoczi 
2430ab185921SStefan Hajnoczi     /* Cover entire cluster so no additional backing file I/O is required when
2431ab185921SStefan Hajnoczi      * allocating cluster in the image file.
2432ab185921SStefan Hajnoczi      */
2433343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2434ab185921SStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
2435ab185921SStefan Hajnoczi 
2436470c0504SStefan Hajnoczi     trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2437ab185921SStefan Hajnoczi                                    cluster_sector_num, cluster_nb_sectors);
2438ab185921SStefan Hajnoczi 
2439ab185921SStefan Hajnoczi     iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2440ab185921SStefan Hajnoczi     iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
2441ab185921SStefan Hajnoczi     qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2442ab185921SStefan Hajnoczi 
244379c053bdSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2444ab185921SStefan Hajnoczi                              &bounce_qiov);
2445ab185921SStefan Hajnoczi     if (ret < 0) {
2446ab185921SStefan Hajnoczi         goto err;
2447ab185921SStefan Hajnoczi     }
2448ab185921SStefan Hajnoczi 
244979c053bdSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes &&
245079c053bdSStefan Hajnoczi         buffer_is_zero(bounce_buffer, iov.iov_len)) {
2451621f0589SKevin Wolf         ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
245279c053bdSStefan Hajnoczi                                       cluster_nb_sectors);
245379c053bdSStefan Hajnoczi     } else {
2454f05fa4adSPaolo Bonzini         /* This does not change the data on the disk, it is not necessary
2455f05fa4adSPaolo Bonzini          * to flush even in cache=writethrough mode.
2456f05fa4adSPaolo Bonzini          */
245779c053bdSStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
2458ab185921SStefan Hajnoczi                                   &bounce_qiov);
245979c053bdSStefan Hajnoczi     }
246079c053bdSStefan Hajnoczi 
2461ab185921SStefan Hajnoczi     if (ret < 0) {
2462ab185921SStefan Hajnoczi         /* It might be okay to ignore write errors for guest requests.  If this
2463ab185921SStefan Hajnoczi          * is a deliberate copy-on-read then we don't want to ignore the error.
2464ab185921SStefan Hajnoczi          * Simply report it in all cases.
2465ab185921SStefan Hajnoczi          */
2466ab185921SStefan Hajnoczi         goto err;
2467ab185921SStefan Hajnoczi     }
2468ab185921SStefan Hajnoczi 
2469ab185921SStefan Hajnoczi     skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
247003396148SMichael Tokarev     qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
2471ab185921SStefan Hajnoczi                         nb_sectors * BDRV_SECTOR_SIZE);
2472ab185921SStefan Hajnoczi 
2473ab185921SStefan Hajnoczi err:
2474ab185921SStefan Hajnoczi     qemu_vfree(bounce_buffer);
2475ab185921SStefan Hajnoczi     return ret;
2476ab185921SStefan Hajnoczi }
2477ab185921SStefan Hajnoczi 
2478c5fbe571SStefan Hajnoczi /*
2479c5fbe571SStefan Hajnoczi  * Handle a read request in coroutine context
2480c5fbe571SStefan Hajnoczi  */
2481c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
2482470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2483470c0504SStefan Hajnoczi     BdrvRequestFlags flags)
2484da1fa91dSKevin Wolf {
2485da1fa91dSKevin Wolf     BlockDriver *drv = bs->drv;
2486dbffbdcfSStefan Hajnoczi     BdrvTrackedRequest req;
2487dbffbdcfSStefan Hajnoczi     int ret;
2488da1fa91dSKevin Wolf 
2489da1fa91dSKevin Wolf     if (!drv) {
2490da1fa91dSKevin Wolf         return -ENOMEDIUM;
2491da1fa91dSKevin Wolf     }
2492da1fa91dSKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2493da1fa91dSKevin Wolf         return -EIO;
2494da1fa91dSKevin Wolf     }
2495da1fa91dSKevin Wolf 
249698f90dbaSZhi Yong Wu     /* throttling disk read I/O */
249798f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
249898f90dbaSZhi Yong Wu         bdrv_io_limits_intercept(bs, false, nb_sectors);
249998f90dbaSZhi Yong Wu     }
250098f90dbaSZhi Yong Wu 
2501f4658285SStefan Hajnoczi     if (bs->copy_on_read) {
2502470c0504SStefan Hajnoczi         flags |= BDRV_REQ_COPY_ON_READ;
2503470c0504SStefan Hajnoczi     }
2504470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2505470c0504SStefan Hajnoczi         bs->copy_on_read_in_flight++;
2506470c0504SStefan Hajnoczi     }
2507470c0504SStefan Hajnoczi 
2508470c0504SStefan Hajnoczi     if (bs->copy_on_read_in_flight) {
2509f4658285SStefan Hajnoczi         wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2510f4658285SStefan Hajnoczi     }
2511f4658285SStefan Hajnoczi 
2512dbffbdcfSStefan Hajnoczi     tracked_request_begin(&req, bs, sector_num, nb_sectors, false);
2513ab185921SStefan Hajnoczi 
2514470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2515ab185921SStefan Hajnoczi         int pnum;
2516ab185921SStefan Hajnoczi 
2517ab185921SStefan Hajnoczi         ret = bdrv_co_is_allocated(bs, sector_num, nb_sectors, &pnum);
2518ab185921SStefan Hajnoczi         if (ret < 0) {
2519ab185921SStefan Hajnoczi             goto out;
2520ab185921SStefan Hajnoczi         }
2521ab185921SStefan Hajnoczi 
2522ab185921SStefan Hajnoczi         if (!ret || pnum != nb_sectors) {
2523470c0504SStefan Hajnoczi             ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
2524ab185921SStefan Hajnoczi             goto out;
2525ab185921SStefan Hajnoczi         }
2526ab185921SStefan Hajnoczi     }
2527ab185921SStefan Hajnoczi 
2528dbffbdcfSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
2529ab185921SStefan Hajnoczi 
2530ab185921SStefan Hajnoczi out:
2531dbffbdcfSStefan Hajnoczi     tracked_request_end(&req);
2532470c0504SStefan Hajnoczi 
2533470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2534470c0504SStefan Hajnoczi         bs->copy_on_read_in_flight--;
2535470c0504SStefan Hajnoczi     }
2536470c0504SStefan Hajnoczi 
2537dbffbdcfSStefan Hajnoczi     return ret;
2538da1fa91dSKevin Wolf }
2539da1fa91dSKevin Wolf 
2540c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
2541da1fa91dSKevin Wolf     int nb_sectors, QEMUIOVector *qiov)
2542da1fa91dSKevin Wolf {
2543c5fbe571SStefan Hajnoczi     trace_bdrv_co_readv(bs, sector_num, nb_sectors);
2544da1fa91dSKevin Wolf 
2545470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
2546470c0504SStefan Hajnoczi }
2547470c0504SStefan Hajnoczi 
2548470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
2549470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2550470c0504SStefan Hajnoczi {
2551470c0504SStefan Hajnoczi     trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
2552470c0504SStefan Hajnoczi 
2553470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
2554470c0504SStefan Hajnoczi                             BDRV_REQ_COPY_ON_READ);
2555c5fbe571SStefan Hajnoczi }
2556c5fbe571SStefan Hajnoczi 
2557f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
2558f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors)
2559f08f2ddaSStefan Hajnoczi {
2560f08f2ddaSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2561f08f2ddaSStefan Hajnoczi     QEMUIOVector qiov;
2562f08f2ddaSStefan Hajnoczi     struct iovec iov;
2563f08f2ddaSStefan Hajnoczi     int ret;
2564f08f2ddaSStefan Hajnoczi 
2565621f0589SKevin Wolf     /* TODO Emulate only part of misaligned requests instead of letting block
2566621f0589SKevin Wolf      * drivers return -ENOTSUP and emulate everything */
2567621f0589SKevin Wolf 
2568f08f2ddaSStefan Hajnoczi     /* First try the efficient write zeroes operation */
2569f08f2ddaSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes) {
2570621f0589SKevin Wolf         ret = drv->bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2571621f0589SKevin Wolf         if (ret != -ENOTSUP) {
2572621f0589SKevin Wolf             return ret;
2573621f0589SKevin Wolf         }
2574f08f2ddaSStefan Hajnoczi     }
2575f08f2ddaSStefan Hajnoczi 
2576f08f2ddaSStefan Hajnoczi     /* Fall back to bounce buffer if write zeroes is unsupported */
2577f08f2ddaSStefan Hajnoczi     iov.iov_len  = nb_sectors * BDRV_SECTOR_SIZE;
2578f08f2ddaSStefan Hajnoczi     iov.iov_base = qemu_blockalign(bs, iov.iov_len);
2579f08f2ddaSStefan Hajnoczi     memset(iov.iov_base, 0, iov.iov_len);
2580f08f2ddaSStefan Hajnoczi     qemu_iovec_init_external(&qiov, &iov, 1);
2581f08f2ddaSStefan Hajnoczi 
2582f08f2ddaSStefan Hajnoczi     ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
2583f08f2ddaSStefan Hajnoczi 
2584f08f2ddaSStefan Hajnoczi     qemu_vfree(iov.iov_base);
2585f08f2ddaSStefan Hajnoczi     return ret;
2586f08f2ddaSStefan Hajnoczi }
2587f08f2ddaSStefan Hajnoczi 
2588c5fbe571SStefan Hajnoczi /*
2589c5fbe571SStefan Hajnoczi  * Handle a write request in coroutine context
2590c5fbe571SStefan Hajnoczi  */
2591c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
2592f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2593f08f2ddaSStefan Hajnoczi     BdrvRequestFlags flags)
2594c5fbe571SStefan Hajnoczi {
2595c5fbe571SStefan Hajnoczi     BlockDriver *drv = bs->drv;
2596dbffbdcfSStefan Hajnoczi     BdrvTrackedRequest req;
25976b7cb247SStefan Hajnoczi     int ret;
2598da1fa91dSKevin Wolf 
2599da1fa91dSKevin Wolf     if (!bs->drv) {
2600da1fa91dSKevin Wolf         return -ENOMEDIUM;
2601da1fa91dSKevin Wolf     }
2602da1fa91dSKevin Wolf     if (bs->read_only) {
2603da1fa91dSKevin Wolf         return -EACCES;
2604da1fa91dSKevin Wolf     }
2605da1fa91dSKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2606da1fa91dSKevin Wolf         return -EIO;
2607da1fa91dSKevin Wolf     }
2608da1fa91dSKevin Wolf 
260998f90dbaSZhi Yong Wu     /* throttling disk write I/O */
261098f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
261198f90dbaSZhi Yong Wu         bdrv_io_limits_intercept(bs, true, nb_sectors);
261298f90dbaSZhi Yong Wu     }
261398f90dbaSZhi Yong Wu 
2614470c0504SStefan Hajnoczi     if (bs->copy_on_read_in_flight) {
2615f4658285SStefan Hajnoczi         wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2616f4658285SStefan Hajnoczi     }
2617f4658285SStefan Hajnoczi 
2618dbffbdcfSStefan Hajnoczi     tracked_request_begin(&req, bs, sector_num, nb_sectors, true);
2619dbffbdcfSStefan Hajnoczi 
2620f08f2ddaSStefan Hajnoczi     if (flags & BDRV_REQ_ZERO_WRITE) {
2621f08f2ddaSStefan Hajnoczi         ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors);
2622f08f2ddaSStefan Hajnoczi     } else {
26236b7cb247SStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
2624f08f2ddaSStefan Hajnoczi     }
26256b7cb247SStefan Hajnoczi 
2626f05fa4adSPaolo Bonzini     if (ret == 0 && !bs->enable_write_cache) {
2627f05fa4adSPaolo Bonzini         ret = bdrv_co_flush(bs);
2628f05fa4adSPaolo Bonzini     }
2629f05fa4adSPaolo Bonzini 
2630da1fa91dSKevin Wolf     if (bs->dirty_bitmap) {
26311755da16SPaolo Bonzini         bdrv_set_dirty(bs, sector_num, nb_sectors);
2632da1fa91dSKevin Wolf     }
2633da1fa91dSKevin Wolf 
2634da1fa91dSKevin Wolf     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2635da1fa91dSKevin Wolf         bs->wr_highest_sector = sector_num + nb_sectors - 1;
2636da1fa91dSKevin Wolf     }
2637da1fa91dSKevin Wolf 
2638dbffbdcfSStefan Hajnoczi     tracked_request_end(&req);
2639dbffbdcfSStefan Hajnoczi 
26406b7cb247SStefan Hajnoczi     return ret;
2641da1fa91dSKevin Wolf }
2642da1fa91dSKevin Wolf 
2643c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
2644c5fbe571SStefan Hajnoczi     int nb_sectors, QEMUIOVector *qiov)
2645c5fbe571SStefan Hajnoczi {
2646c5fbe571SStefan Hajnoczi     trace_bdrv_co_writev(bs, sector_num, nb_sectors);
2647c5fbe571SStefan Hajnoczi 
2648f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
2649f08f2ddaSStefan Hajnoczi }
2650f08f2ddaSStefan Hajnoczi 
2651f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
2652f08f2ddaSStefan Hajnoczi                                       int64_t sector_num, int nb_sectors)
2653f08f2ddaSStefan Hajnoczi {
2654f08f2ddaSStefan Hajnoczi     trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2655f08f2ddaSStefan Hajnoczi 
2656f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
2657f08f2ddaSStefan Hajnoczi                              BDRV_REQ_ZERO_WRITE);
2658c5fbe571SStefan Hajnoczi }
2659c5fbe571SStefan Hajnoczi 
266083f64091Sbellard /**
266183f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
266283f64091Sbellard  */
266383f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
266483f64091Sbellard {
266583f64091Sbellard     BlockDriver *drv = bs->drv;
266651762288SStefan Hajnoczi     int ret;
266783f64091Sbellard     if (!drv)
266819cb3738Sbellard         return -ENOMEDIUM;
266983f64091Sbellard     if (!drv->bdrv_truncate)
267083f64091Sbellard         return -ENOTSUP;
267159f2689dSNaphtali Sprei     if (bs->read_only)
267259f2689dSNaphtali Sprei         return -EACCES;
26738591675fSMarcelo Tosatti     if (bdrv_in_use(bs))
26748591675fSMarcelo Tosatti         return -EBUSY;
267551762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
267651762288SStefan Hajnoczi     if (ret == 0) {
267751762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2678145feb17SMarkus Armbruster         bdrv_dev_resize_cb(bs);
267951762288SStefan Hajnoczi     }
268051762288SStefan Hajnoczi     return ret;
268183f64091Sbellard }
268283f64091Sbellard 
268383f64091Sbellard /**
26844a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
26854a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
26864a1d5e1fSFam Zheng  */
26874a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
26884a1d5e1fSFam Zheng {
26894a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
26904a1d5e1fSFam Zheng     if (!drv) {
26914a1d5e1fSFam Zheng         return -ENOMEDIUM;
26924a1d5e1fSFam Zheng     }
26934a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
26944a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
26954a1d5e1fSFam Zheng     }
26964a1d5e1fSFam Zheng     if (bs->file) {
26974a1d5e1fSFam Zheng         return bdrv_get_allocated_file_size(bs->file);
26984a1d5e1fSFam Zheng     }
26994a1d5e1fSFam Zheng     return -ENOTSUP;
27004a1d5e1fSFam Zheng }
27014a1d5e1fSFam Zheng 
27024a1d5e1fSFam Zheng /**
270383f64091Sbellard  * Length of a file in bytes. Return < 0 if error or unknown.
270483f64091Sbellard  */
270583f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs)
270683f64091Sbellard {
270783f64091Sbellard     BlockDriver *drv = bs->drv;
270883f64091Sbellard     if (!drv)
270919cb3738Sbellard         return -ENOMEDIUM;
271051762288SStefan Hajnoczi 
27112c6942faSMarkus Armbruster     if (bs->growable || bdrv_dev_has_removable_media(bs)) {
271246a4e4e6SStefan Hajnoczi         if (drv->bdrv_getlength) {
271383f64091Sbellard             return drv->bdrv_getlength(bs);
2714fc01f7e7Sbellard         }
271546a4e4e6SStefan Hajnoczi     }
271646a4e4e6SStefan Hajnoczi     return bs->total_sectors * BDRV_SECTOR_SIZE;
271746a4e4e6SStefan Hajnoczi }
2718fc01f7e7Sbellard 
271919cb3738Sbellard /* return 0 as number of sectors if no device present or error */
272096b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2721fc01f7e7Sbellard {
272219cb3738Sbellard     int64_t length;
272319cb3738Sbellard     length = bdrv_getlength(bs);
272419cb3738Sbellard     if (length < 0)
272519cb3738Sbellard         length = 0;
272619cb3738Sbellard     else
27276ea44308SJan Kiszka         length = length >> BDRV_SECTOR_BITS;
272819cb3738Sbellard     *nb_sectors_ptr = length;
2729fc01f7e7Sbellard }
2730cf98951bSbellard 
27310563e191SZhi Yong Wu /* throttling disk io limits */
27320563e191SZhi Yong Wu void bdrv_set_io_limits(BlockDriverState *bs,
27330563e191SZhi Yong Wu                         BlockIOLimit *io_limits)
27340563e191SZhi Yong Wu {
27350563e191SZhi Yong Wu     bs->io_limits = *io_limits;
27360563e191SZhi Yong Wu     bs->io_limits_enabled = bdrv_io_limits_enabled(bs);
27370563e191SZhi Yong Wu }
27380563e191SZhi Yong Wu 
2739ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
2740ff06f5f3SPaolo Bonzini                        BlockdevOnError on_write_error)
2741abd7f68dSMarkus Armbruster {
2742abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
2743abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
2744abd7f68dSMarkus Armbruster }
2745abd7f68dSMarkus Armbruster 
27461ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
2747abd7f68dSMarkus Armbruster {
2748abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
2749abd7f68dSMarkus Armbruster }
2750abd7f68dSMarkus Armbruster 
27513e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
27523e1caa5fSPaolo Bonzini {
27533e1caa5fSPaolo Bonzini     BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
27543e1caa5fSPaolo Bonzini 
27553e1caa5fSPaolo Bonzini     switch (on_err) {
27563e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_ENOSPC:
27573e1caa5fSPaolo Bonzini         return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT;
27583e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_STOP:
27593e1caa5fSPaolo Bonzini         return BDRV_ACTION_STOP;
27603e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_REPORT:
27613e1caa5fSPaolo Bonzini         return BDRV_ACTION_REPORT;
27623e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_IGNORE:
27633e1caa5fSPaolo Bonzini         return BDRV_ACTION_IGNORE;
27643e1caa5fSPaolo Bonzini     default:
27653e1caa5fSPaolo Bonzini         abort();
27663e1caa5fSPaolo Bonzini     }
27673e1caa5fSPaolo Bonzini }
27683e1caa5fSPaolo Bonzini 
27693e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows
27703e1caa5fSPaolo Bonzini  * about the error, it does not know whether an operation comes from
27713e1caa5fSPaolo Bonzini  * the device or the block layer (from a job, for example).
27723e1caa5fSPaolo Bonzini  */
27733e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
27743e1caa5fSPaolo Bonzini                        bool is_read, int error)
27753e1caa5fSPaolo Bonzini {
27763e1caa5fSPaolo Bonzini     assert(error >= 0);
277732c81a4aSPaolo Bonzini     bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);
27783e1caa5fSPaolo Bonzini     if (action == BDRV_ACTION_STOP) {
27793e1caa5fSPaolo Bonzini         vm_stop(RUN_STATE_IO_ERROR);
27803e1caa5fSPaolo Bonzini         bdrv_iostatus_set_err(bs, error);
27813e1caa5fSPaolo Bonzini     }
27823e1caa5fSPaolo Bonzini }
27833e1caa5fSPaolo Bonzini 
2784b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2785b338082bSbellard {
2786b338082bSbellard     return bs->read_only;
2787b338082bSbellard }
2788b338082bSbellard 
2789985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2790985a03b0Sths {
2791985a03b0Sths     return bs->sg;
2792985a03b0Sths }
2793985a03b0Sths 
2794e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
2795e900a7b7SChristoph Hellwig {
2796e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
2797e900a7b7SChristoph Hellwig }
2798e900a7b7SChristoph Hellwig 
2799425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2800425b0148SPaolo Bonzini {
2801425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
280255b110f2SJeff Cody 
280355b110f2SJeff Cody     /* so a reopen() will preserve wce */
280455b110f2SJeff Cody     if (wce) {
280555b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
280655b110f2SJeff Cody     } else {
280755b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
280855b110f2SJeff Cody     }
2809425b0148SPaolo Bonzini }
2810425b0148SPaolo Bonzini 
2811ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2812ea2384d3Sbellard {
2813ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
2814ea2384d3Sbellard         return 1;
2815ea2384d3Sbellard     return bs->encrypted;
2816ea2384d3Sbellard }
2817ea2384d3Sbellard 
2818c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2819c0f4ce77Saliguori {
2820c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
2821c0f4ce77Saliguori 
2822c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
2823c0f4ce77Saliguori         return 1;
2824c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2825c0f4ce77Saliguori }
2826c0f4ce77Saliguori 
2827ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2828ea2384d3Sbellard {
2829ea2384d3Sbellard     int ret;
2830ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
2831ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
2832ea2384d3Sbellard         if (ret < 0)
2833ea2384d3Sbellard             return ret;
2834ea2384d3Sbellard         if (!bs->encrypted)
2835ea2384d3Sbellard             return 0;
2836ea2384d3Sbellard     }
2837fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2838fd04a2aeSShahar Havivi         return -EINVAL;
2839fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2840fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2841fd04a2aeSShahar Havivi     }
2842c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2843bb5fc20fSaliguori     if (ret < 0) {
2844bb5fc20fSaliguori         bs->valid_key = 0;
2845bb5fc20fSaliguori     } else if (!bs->valid_key) {
2846bb5fc20fSaliguori         bs->valid_key = 1;
2847bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
28487d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
2849bb5fc20fSaliguori     }
2850c0f4ce77Saliguori     return ret;
2851ea2384d3Sbellard }
2852ea2384d3Sbellard 
2853f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
2854ea2384d3Sbellard {
2855f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
2856ea2384d3Sbellard }
2857ea2384d3Sbellard 
2858ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2859ea2384d3Sbellard                          void *opaque)
2860ea2384d3Sbellard {
2861ea2384d3Sbellard     BlockDriver *drv;
2862ea2384d3Sbellard 
28638a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2864ea2384d3Sbellard         it(opaque, drv->format_name);
2865ea2384d3Sbellard     }
2866ea2384d3Sbellard }
2867ea2384d3Sbellard 
2868b338082bSbellard BlockDriverState *bdrv_find(const char *name)
2869b338082bSbellard {
2870b338082bSbellard     BlockDriverState *bs;
2871b338082bSbellard 
28721b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
28731b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
2874b338082bSbellard             return bs;
2875b338082bSbellard         }
28761b7bdbc1SStefan Hajnoczi     }
2877b338082bSbellard     return NULL;
2878b338082bSbellard }
2879b338082bSbellard 
28802f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
28812f399b0aSMarkus Armbruster {
28822f399b0aSMarkus Armbruster     if (!bs) {
28832f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
28842f399b0aSMarkus Armbruster     }
28852f399b0aSMarkus Armbruster     return QTAILQ_NEXT(bs, list);
28862f399b0aSMarkus Armbruster }
28872f399b0aSMarkus Armbruster 
288851de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
288981d0912dSbellard {
289081d0912dSbellard     BlockDriverState *bs;
289181d0912dSbellard 
28921b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
289351de9760Saliguori         it(opaque, bs);
289481d0912dSbellard     }
289581d0912dSbellard }
289681d0912dSbellard 
2897ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
2898ea2384d3Sbellard {
2899ea2384d3Sbellard     return bs->device_name;
2900ea2384d3Sbellard }
2901ea2384d3Sbellard 
2902c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
2903c8433287SMarkus Armbruster {
2904c8433287SMarkus Armbruster     return bs->open_flags;
2905c8433287SMarkus Armbruster }
2906c8433287SMarkus Armbruster 
2907c6ca28d6Saliguori void bdrv_flush_all(void)
2908c6ca28d6Saliguori {
2909c6ca28d6Saliguori     BlockDriverState *bs;
2910c6ca28d6Saliguori 
29111b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
2912c6ca28d6Saliguori         bdrv_flush(bs);
2913c6ca28d6Saliguori     }
29141b7bdbc1SStefan Hajnoczi }
2915c6ca28d6Saliguori 
2916f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
2917f2feebbdSKevin Wolf {
2918f2feebbdSKevin Wolf     assert(bs->drv);
2919f2feebbdSKevin Wolf 
2920336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
2921336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
2922f2feebbdSKevin Wolf     }
2923f2feebbdSKevin Wolf 
2924f2feebbdSKevin Wolf     return 1;
2925f2feebbdSKevin Wolf }
2926f2feebbdSKevin Wolf 
2927376ae3f1SStefan Hajnoczi typedef struct BdrvCoIsAllocatedData {
2928376ae3f1SStefan Hajnoczi     BlockDriverState *bs;
2929b35b2bbaSMiroslav Rezanina     BlockDriverState *base;
2930376ae3f1SStefan Hajnoczi     int64_t sector_num;
2931376ae3f1SStefan Hajnoczi     int nb_sectors;
2932376ae3f1SStefan Hajnoczi     int *pnum;
2933376ae3f1SStefan Hajnoczi     int ret;
2934376ae3f1SStefan Hajnoczi     bool done;
2935376ae3f1SStefan Hajnoczi } BdrvCoIsAllocatedData;
2936376ae3f1SStefan Hajnoczi 
2937f58c7b35Sths /*
2938f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
2939f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
2940f58c7b35Sths  * hence all their sectors are reported as allocated.
2941f58c7b35Sths  *
2942bd9533e3SStefan Hajnoczi  * If 'sector_num' is beyond the end of the disk image the return value is 0
2943bd9533e3SStefan Hajnoczi  * and 'pnum' is set to 0.
2944bd9533e3SStefan Hajnoczi  *
2945f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
2946f58c7b35Sths  * the specified sector) that are known to be in the same
2947f58c7b35Sths  * allocated/unallocated state.
2948f58c7b35Sths  *
2949bd9533e3SStefan Hajnoczi  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
2950bd9533e3SStefan Hajnoczi  * beyond the end of the disk image it will be clamped.
2951f58c7b35Sths  */
2952060f51c9SStefan Hajnoczi int coroutine_fn bdrv_co_is_allocated(BlockDriverState *bs, int64_t sector_num,
2953060f51c9SStefan Hajnoczi                                       int nb_sectors, int *pnum)
2954f58c7b35Sths {
2955f58c7b35Sths     int64_t n;
2956bd9533e3SStefan Hajnoczi 
29576aebab14SStefan Hajnoczi     if (sector_num >= bs->total_sectors) {
29586aebab14SStefan Hajnoczi         *pnum = 0;
29596aebab14SStefan Hajnoczi         return 0;
29606aebab14SStefan Hajnoczi     }
2961bd9533e3SStefan Hajnoczi 
29626aebab14SStefan Hajnoczi     n = bs->total_sectors - sector_num;
2963bd9533e3SStefan Hajnoczi     if (n < nb_sectors) {
2964bd9533e3SStefan Hajnoczi         nb_sectors = n;
2965bd9533e3SStefan Hajnoczi     }
2966bd9533e3SStefan Hajnoczi 
2967bd9533e3SStefan Hajnoczi     if (!bs->drv->bdrv_co_is_allocated) {
2968bd9533e3SStefan Hajnoczi         *pnum = nb_sectors;
29696aebab14SStefan Hajnoczi         return 1;
29706aebab14SStefan Hajnoczi     }
29716aebab14SStefan Hajnoczi 
2972060f51c9SStefan Hajnoczi     return bs->drv->bdrv_co_is_allocated(bs, sector_num, nb_sectors, pnum);
2973060f51c9SStefan Hajnoczi }
2974060f51c9SStefan Hajnoczi 
2975060f51c9SStefan Hajnoczi /* Coroutine wrapper for bdrv_is_allocated() */
2976060f51c9SStefan Hajnoczi static void coroutine_fn bdrv_is_allocated_co_entry(void *opaque)
2977060f51c9SStefan Hajnoczi {
2978060f51c9SStefan Hajnoczi     BdrvCoIsAllocatedData *data = opaque;
2979060f51c9SStefan Hajnoczi     BlockDriverState *bs = data->bs;
2980060f51c9SStefan Hajnoczi 
2981060f51c9SStefan Hajnoczi     data->ret = bdrv_co_is_allocated(bs, data->sector_num, data->nb_sectors,
2982060f51c9SStefan Hajnoczi                                      data->pnum);
2983060f51c9SStefan Hajnoczi     data->done = true;
2984060f51c9SStefan Hajnoczi }
2985060f51c9SStefan Hajnoczi 
2986060f51c9SStefan Hajnoczi /*
2987060f51c9SStefan Hajnoczi  * Synchronous wrapper around bdrv_co_is_allocated().
2988060f51c9SStefan Hajnoczi  *
2989060f51c9SStefan Hajnoczi  * See bdrv_co_is_allocated() for details.
2990060f51c9SStefan Hajnoczi  */
2991060f51c9SStefan Hajnoczi int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
2992060f51c9SStefan Hajnoczi                       int *pnum)
2993060f51c9SStefan Hajnoczi {
2994376ae3f1SStefan Hajnoczi     Coroutine *co;
2995376ae3f1SStefan Hajnoczi     BdrvCoIsAllocatedData data = {
2996376ae3f1SStefan Hajnoczi         .bs = bs,
2997376ae3f1SStefan Hajnoczi         .sector_num = sector_num,
2998376ae3f1SStefan Hajnoczi         .nb_sectors = nb_sectors,
2999376ae3f1SStefan Hajnoczi         .pnum = pnum,
3000376ae3f1SStefan Hajnoczi         .done = false,
3001376ae3f1SStefan Hajnoczi     };
3002376ae3f1SStefan Hajnoczi 
3003376ae3f1SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_is_allocated_co_entry);
3004376ae3f1SStefan Hajnoczi     qemu_coroutine_enter(co, &data);
3005376ae3f1SStefan Hajnoczi     while (!data.done) {
3006376ae3f1SStefan Hajnoczi         qemu_aio_wait();
3007376ae3f1SStefan Hajnoczi     }
3008376ae3f1SStefan Hajnoczi     return data.ret;
3009376ae3f1SStefan Hajnoczi }
3010f58c7b35Sths 
3011188a7bbfSPaolo Bonzini /*
3012188a7bbfSPaolo Bonzini  * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
3013188a7bbfSPaolo Bonzini  *
3014188a7bbfSPaolo Bonzini  * Return true if the given sector is allocated in any image between
3015188a7bbfSPaolo Bonzini  * BASE and TOP (inclusive).  BASE can be NULL to check if the given
3016188a7bbfSPaolo Bonzini  * sector is allocated in any image of the chain.  Return false otherwise.
3017188a7bbfSPaolo Bonzini  *
3018188a7bbfSPaolo Bonzini  * 'pnum' is set to the number of sectors (including and immediately following
3019188a7bbfSPaolo Bonzini  *  the specified sector) that are known to be in the same
3020188a7bbfSPaolo Bonzini  *  allocated/unallocated state.
3021188a7bbfSPaolo Bonzini  *
3022188a7bbfSPaolo Bonzini  */
3023188a7bbfSPaolo Bonzini int coroutine_fn bdrv_co_is_allocated_above(BlockDriverState *top,
3024188a7bbfSPaolo Bonzini                                             BlockDriverState *base,
3025188a7bbfSPaolo Bonzini                                             int64_t sector_num,
3026188a7bbfSPaolo Bonzini                                             int nb_sectors, int *pnum)
3027188a7bbfSPaolo Bonzini {
3028188a7bbfSPaolo Bonzini     BlockDriverState *intermediate;
3029188a7bbfSPaolo Bonzini     int ret, n = nb_sectors;
3030188a7bbfSPaolo Bonzini 
3031188a7bbfSPaolo Bonzini     intermediate = top;
3032188a7bbfSPaolo Bonzini     while (intermediate && intermediate != base) {
3033188a7bbfSPaolo Bonzini         int pnum_inter;
3034188a7bbfSPaolo Bonzini         ret = bdrv_co_is_allocated(intermediate, sector_num, nb_sectors,
3035188a7bbfSPaolo Bonzini                                    &pnum_inter);
3036188a7bbfSPaolo Bonzini         if (ret < 0) {
3037188a7bbfSPaolo Bonzini             return ret;
3038188a7bbfSPaolo Bonzini         } else if (ret) {
3039188a7bbfSPaolo Bonzini             *pnum = pnum_inter;
3040188a7bbfSPaolo Bonzini             return 1;
3041188a7bbfSPaolo Bonzini         }
3042188a7bbfSPaolo Bonzini 
3043188a7bbfSPaolo Bonzini         /*
3044188a7bbfSPaolo Bonzini          * [sector_num, nb_sectors] is unallocated on top but intermediate
3045188a7bbfSPaolo Bonzini          * might have
3046188a7bbfSPaolo Bonzini          *
3047188a7bbfSPaolo Bonzini          * [sector_num+x, nr_sectors] allocated.
3048188a7bbfSPaolo Bonzini          */
304963ba17d3SVishvananda Ishaya         if (n > pnum_inter &&
305063ba17d3SVishvananda Ishaya             (intermediate == top ||
305163ba17d3SVishvananda Ishaya              sector_num + pnum_inter < intermediate->total_sectors)) {
3052188a7bbfSPaolo Bonzini             n = pnum_inter;
3053188a7bbfSPaolo Bonzini         }
3054188a7bbfSPaolo Bonzini 
3055188a7bbfSPaolo Bonzini         intermediate = intermediate->backing_hd;
3056188a7bbfSPaolo Bonzini     }
3057188a7bbfSPaolo Bonzini 
3058188a7bbfSPaolo Bonzini     *pnum = n;
3059188a7bbfSPaolo Bonzini     return 0;
3060188a7bbfSPaolo Bonzini }
3061188a7bbfSPaolo Bonzini 
3062b35b2bbaSMiroslav Rezanina /* Coroutine wrapper for bdrv_is_allocated_above() */
3063b35b2bbaSMiroslav Rezanina static void coroutine_fn bdrv_is_allocated_above_co_entry(void *opaque)
3064b35b2bbaSMiroslav Rezanina {
3065b35b2bbaSMiroslav Rezanina     BdrvCoIsAllocatedData *data = opaque;
3066b35b2bbaSMiroslav Rezanina     BlockDriverState *top = data->bs;
3067b35b2bbaSMiroslav Rezanina     BlockDriverState *base = data->base;
3068b35b2bbaSMiroslav Rezanina 
3069b35b2bbaSMiroslav Rezanina     data->ret = bdrv_co_is_allocated_above(top, base, data->sector_num,
3070b35b2bbaSMiroslav Rezanina                                            data->nb_sectors, data->pnum);
3071b35b2bbaSMiroslav Rezanina     data->done = true;
3072b35b2bbaSMiroslav Rezanina }
3073b35b2bbaSMiroslav Rezanina 
3074b35b2bbaSMiroslav Rezanina /*
3075b35b2bbaSMiroslav Rezanina  * Synchronous wrapper around bdrv_co_is_allocated_above().
3076b35b2bbaSMiroslav Rezanina  *
3077b35b2bbaSMiroslav Rezanina  * See bdrv_co_is_allocated_above() for details.
3078b35b2bbaSMiroslav Rezanina  */
3079b35b2bbaSMiroslav Rezanina int bdrv_is_allocated_above(BlockDriverState *top, BlockDriverState *base,
3080b35b2bbaSMiroslav Rezanina                             int64_t sector_num, int nb_sectors, int *pnum)
3081b35b2bbaSMiroslav Rezanina {
3082b35b2bbaSMiroslav Rezanina     Coroutine *co;
3083b35b2bbaSMiroslav Rezanina     BdrvCoIsAllocatedData data = {
3084b35b2bbaSMiroslav Rezanina         .bs = top,
3085b35b2bbaSMiroslav Rezanina         .base = base,
3086b35b2bbaSMiroslav Rezanina         .sector_num = sector_num,
3087b35b2bbaSMiroslav Rezanina         .nb_sectors = nb_sectors,
3088b35b2bbaSMiroslav Rezanina         .pnum = pnum,
3089b35b2bbaSMiroslav Rezanina         .done = false,
3090b35b2bbaSMiroslav Rezanina     };
3091b35b2bbaSMiroslav Rezanina 
3092b35b2bbaSMiroslav Rezanina     co = qemu_coroutine_create(bdrv_is_allocated_above_co_entry);
3093b35b2bbaSMiroslav Rezanina     qemu_coroutine_enter(co, &data);
3094b35b2bbaSMiroslav Rezanina     while (!data.done) {
3095b35b2bbaSMiroslav Rezanina         qemu_aio_wait();
3096b35b2bbaSMiroslav Rezanina     }
3097b35b2bbaSMiroslav Rezanina     return data.ret;
3098b35b2bbaSMiroslav Rezanina }
3099b35b2bbaSMiroslav Rezanina 
3100ac84adacSPaolo Bonzini BlockInfo *bdrv_query_info(BlockDriverState *bs)
3101ac84adacSPaolo Bonzini {
3102ac84adacSPaolo Bonzini     BlockInfo *info = g_malloc0(sizeof(*info));
3103ac84adacSPaolo Bonzini     info->device = g_strdup(bs->device_name);
3104ac84adacSPaolo Bonzini     info->type = g_strdup("unknown");
3105ac84adacSPaolo Bonzini     info->locked = bdrv_dev_is_medium_locked(bs);
3106ac84adacSPaolo Bonzini     info->removable = bdrv_dev_has_removable_media(bs);
3107ac84adacSPaolo Bonzini 
3108ac84adacSPaolo Bonzini     if (bdrv_dev_has_removable_media(bs)) {
3109ac84adacSPaolo Bonzini         info->has_tray_open = true;
3110ac84adacSPaolo Bonzini         info->tray_open = bdrv_dev_is_tray_open(bs);
3111ac84adacSPaolo Bonzini     }
3112ac84adacSPaolo Bonzini 
3113ac84adacSPaolo Bonzini     if (bdrv_iostatus_is_enabled(bs)) {
3114ac84adacSPaolo Bonzini         info->has_io_status = true;
3115ac84adacSPaolo Bonzini         info->io_status = bs->iostatus;
3116ac84adacSPaolo Bonzini     }
3117ac84adacSPaolo Bonzini 
3118b9a9b3a4SPaolo Bonzini     if (bs->dirty_bitmap) {
3119b9a9b3a4SPaolo Bonzini         info->has_dirty = true;
3120b9a9b3a4SPaolo Bonzini         info->dirty = g_malloc0(sizeof(*info->dirty));
3121acc906c6SPaolo Bonzini         info->dirty->count = bdrv_get_dirty_count(bs) * BDRV_SECTOR_SIZE;
312250717e94SPaolo Bonzini         info->dirty->granularity =
312350717e94SPaolo Bonzini             ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bs->dirty_bitmap));
3124b9a9b3a4SPaolo Bonzini     }
3125b9a9b3a4SPaolo Bonzini 
3126ac84adacSPaolo Bonzini     if (bs->drv) {
3127ac84adacSPaolo Bonzini         info->has_inserted = true;
3128ac84adacSPaolo Bonzini         info->inserted = g_malloc0(sizeof(*info->inserted));
3129ac84adacSPaolo Bonzini         info->inserted->file = g_strdup(bs->filename);
3130ac84adacSPaolo Bonzini         info->inserted->ro = bs->read_only;
3131ac84adacSPaolo Bonzini         info->inserted->drv = g_strdup(bs->drv->format_name);
3132ac84adacSPaolo Bonzini         info->inserted->encrypted = bs->encrypted;
3133ac84adacSPaolo Bonzini         info->inserted->encryption_key_missing = bdrv_key_required(bs);
3134ac84adacSPaolo Bonzini 
3135ac84adacSPaolo Bonzini         if (bs->backing_file[0]) {
3136ac84adacSPaolo Bonzini             info->inserted->has_backing_file = true;
3137ac84adacSPaolo Bonzini             info->inserted->backing_file = g_strdup(bs->backing_file);
3138ac84adacSPaolo Bonzini         }
3139ac84adacSPaolo Bonzini 
3140ac84adacSPaolo Bonzini         info->inserted->backing_file_depth = bdrv_get_backing_file_depth(bs);
3141ac84adacSPaolo Bonzini 
3142ac84adacSPaolo Bonzini         if (bs->io_limits_enabled) {
3143ac84adacSPaolo Bonzini             info->inserted->bps =
3144ac84adacSPaolo Bonzini                            bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
3145ac84adacSPaolo Bonzini             info->inserted->bps_rd =
3146ac84adacSPaolo Bonzini                            bs->io_limits.bps[BLOCK_IO_LIMIT_READ];
3147ac84adacSPaolo Bonzini             info->inserted->bps_wr =
3148ac84adacSPaolo Bonzini                            bs->io_limits.bps[BLOCK_IO_LIMIT_WRITE];
3149ac84adacSPaolo Bonzini             info->inserted->iops =
3150ac84adacSPaolo Bonzini                            bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
3151ac84adacSPaolo Bonzini             info->inserted->iops_rd =
3152ac84adacSPaolo Bonzini                            bs->io_limits.iops[BLOCK_IO_LIMIT_READ];
3153ac84adacSPaolo Bonzini             info->inserted->iops_wr =
3154ac84adacSPaolo Bonzini                            bs->io_limits.iops[BLOCK_IO_LIMIT_WRITE];
3155ac84adacSPaolo Bonzini         }
3156ac84adacSPaolo Bonzini     }
3157ac84adacSPaolo Bonzini     return info;
3158ac84adacSPaolo Bonzini }
3159ac84adacSPaolo Bonzini 
3160b2023818SLuiz Capitulino BlockInfoList *qmp_query_block(Error **errp)
3161b338082bSbellard {
3162ac84adacSPaolo Bonzini     BlockInfoList *head = NULL, **p_next = &head;
3163d15e5465SLuiz Capitulino     BlockDriverState *bs;
3164d15e5465SLuiz Capitulino 
31651b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
3166b2023818SLuiz Capitulino         BlockInfoList *info = g_malloc0(sizeof(*info));
3167ac84adacSPaolo Bonzini         info->value = bdrv_query_info(bs);
3168d15e5465SLuiz Capitulino 
3169ac84adacSPaolo Bonzini         *p_next = info;
3170ac84adacSPaolo Bonzini         p_next = &info->next;
3171d15e5465SLuiz Capitulino     }
3172d15e5465SLuiz Capitulino 
3173b2023818SLuiz Capitulino     return head;
3174b338082bSbellard }
3175a36e69ddSths 
31769887b616SPaolo Bonzini BlockStats *bdrv_query_stats(const BlockDriverState *bs)
3177a36e69ddSths {
3178f11f57e4SLuiz Capitulino     BlockStats *s;
3179218a536aSLuiz Capitulino 
3180f11f57e4SLuiz Capitulino     s = g_malloc0(sizeof(*s));
3181218a536aSLuiz Capitulino 
3182f11f57e4SLuiz Capitulino     if (bs->device_name[0]) {
3183f11f57e4SLuiz Capitulino         s->has_device = true;
3184f11f57e4SLuiz Capitulino         s->device = g_strdup(bs->device_name);
3185218a536aSLuiz Capitulino     }
3186218a536aSLuiz Capitulino 
3187f11f57e4SLuiz Capitulino     s->stats = g_malloc0(sizeof(*s->stats));
3188f11f57e4SLuiz Capitulino     s->stats->rd_bytes = bs->nr_bytes[BDRV_ACCT_READ];
3189f11f57e4SLuiz Capitulino     s->stats->wr_bytes = bs->nr_bytes[BDRV_ACCT_WRITE];
3190f11f57e4SLuiz Capitulino     s->stats->rd_operations = bs->nr_ops[BDRV_ACCT_READ];
3191f11f57e4SLuiz Capitulino     s->stats->wr_operations = bs->nr_ops[BDRV_ACCT_WRITE];
3192f11f57e4SLuiz Capitulino     s->stats->wr_highest_offset = bs->wr_highest_sector * BDRV_SECTOR_SIZE;
3193f11f57e4SLuiz Capitulino     s->stats->flush_operations = bs->nr_ops[BDRV_ACCT_FLUSH];
3194f11f57e4SLuiz Capitulino     s->stats->wr_total_time_ns = bs->total_time_ns[BDRV_ACCT_WRITE];
3195f11f57e4SLuiz Capitulino     s->stats->rd_total_time_ns = bs->total_time_ns[BDRV_ACCT_READ];
3196f11f57e4SLuiz Capitulino     s->stats->flush_total_time_ns = bs->total_time_ns[BDRV_ACCT_FLUSH];
3197294cc35fSKevin Wolf 
3198294cc35fSKevin Wolf     if (bs->file) {
3199f11f57e4SLuiz Capitulino         s->has_parent = true;
32009887b616SPaolo Bonzini         s->parent = bdrv_query_stats(bs->file);
3201294cc35fSKevin Wolf     }
3202294cc35fSKevin Wolf 
3203f11f57e4SLuiz Capitulino     return s;
3204294cc35fSKevin Wolf }
3205294cc35fSKevin Wolf 
3206f11f57e4SLuiz Capitulino BlockStatsList *qmp_query_blockstats(Error **errp)
3207218a536aSLuiz Capitulino {
32089887b616SPaolo Bonzini     BlockStatsList *head = NULL, **p_next = &head;
3209a36e69ddSths     BlockDriverState *bs;
3210a36e69ddSths 
32111b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
3212f11f57e4SLuiz Capitulino         BlockStatsList *info = g_malloc0(sizeof(*info));
32139887b616SPaolo Bonzini         info->value = bdrv_query_stats(bs);
3214f11f57e4SLuiz Capitulino 
32159887b616SPaolo Bonzini         *p_next = info;
32169887b616SPaolo Bonzini         p_next = &info->next;
3217a36e69ddSths     }
3218218a536aSLuiz Capitulino 
3219f11f57e4SLuiz Capitulino     return head;
3220a36e69ddSths }
3221ea2384d3Sbellard 
3222045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3223045df330Saliguori {
3224045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
3225045df330Saliguori         return bs->backing_file;
3226045df330Saliguori     else if (bs->encrypted)
3227045df330Saliguori         return bs->filename;
3228045df330Saliguori     else
3229045df330Saliguori         return NULL;
3230045df330Saliguori }
3231045df330Saliguori 
323283f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
323383f64091Sbellard                                char *filename, int filename_size)
323483f64091Sbellard {
323583f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
323683f64091Sbellard }
323783f64091Sbellard 
3238faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
3239faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
3240faea38e7Sbellard {
3241faea38e7Sbellard     BlockDriver *drv = bs->drv;
3242faea38e7Sbellard     if (!drv)
324319cb3738Sbellard         return -ENOMEDIUM;
3244faea38e7Sbellard     if (!drv->bdrv_write_compressed)
3245faea38e7Sbellard         return -ENOTSUP;
3246fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
3247fbb7b4e0SKevin Wolf         return -EIO;
32487cd1e32aSlirans@il.ibm.com 
32491755da16SPaolo Bonzini     assert(!bs->dirty_bitmap);
32507cd1e32aSlirans@il.ibm.com 
3251faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
3252faea38e7Sbellard }
3253faea38e7Sbellard 
3254faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3255faea38e7Sbellard {
3256faea38e7Sbellard     BlockDriver *drv = bs->drv;
3257faea38e7Sbellard     if (!drv)
325819cb3738Sbellard         return -ENOMEDIUM;
3259faea38e7Sbellard     if (!drv->bdrv_get_info)
3260faea38e7Sbellard         return -ENOTSUP;
3261faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
3262faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
3263faea38e7Sbellard }
3264faea38e7Sbellard 
326545566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
326645566e9cSChristoph Hellwig                       int64_t pos, int size)
3267178e08a5Saliguori {
3268cf8074b3SKevin Wolf     QEMUIOVector qiov;
3269cf8074b3SKevin Wolf     struct iovec iov = {
3270cf8074b3SKevin Wolf         .iov_base   = (void *) buf,
3271cf8074b3SKevin Wolf         .iov_len    = size,
3272cf8074b3SKevin Wolf     };
3273cf8074b3SKevin Wolf 
3274cf8074b3SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
3275cf8074b3SKevin Wolf     return bdrv_writev_vmstate(bs, &qiov, pos);
3276cf8074b3SKevin Wolf }
3277cf8074b3SKevin Wolf 
3278cf8074b3SKevin Wolf int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
3279cf8074b3SKevin Wolf {
3280178e08a5Saliguori     BlockDriver *drv = bs->drv;
3281cf8074b3SKevin Wolf 
3282cf8074b3SKevin Wolf     if (!drv) {
3283178e08a5Saliguori         return -ENOMEDIUM;
3284cf8074b3SKevin Wolf     } else if (drv->bdrv_save_vmstate) {
3285cf8074b3SKevin Wolf         return drv->bdrv_save_vmstate(bs, qiov, pos);
3286cf8074b3SKevin Wolf     } else if (bs->file) {
3287cf8074b3SKevin Wolf         return bdrv_writev_vmstate(bs->file, qiov, pos);
3288cf8074b3SKevin Wolf     }
3289cf8074b3SKevin Wolf 
32907cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3291178e08a5Saliguori }
3292178e08a5Saliguori 
329345566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
329445566e9cSChristoph Hellwig                       int64_t pos, int size)
3295178e08a5Saliguori {
3296178e08a5Saliguori     BlockDriver *drv = bs->drv;
3297178e08a5Saliguori     if (!drv)
3298178e08a5Saliguori         return -ENOMEDIUM;
32997cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
330045566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
33017cdb1f6dSMORITA Kazutaka     if (bs->file)
33027cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
33037cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3304178e08a5Saliguori }
3305178e08a5Saliguori 
33068b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
33078b9b0cc2SKevin Wolf {
33088b9b0cc2SKevin Wolf     BlockDriver *drv = bs->drv;
33098b9b0cc2SKevin Wolf 
33108b9b0cc2SKevin Wolf     if (!drv || !drv->bdrv_debug_event) {
33118b9b0cc2SKevin Wolf         return;
33128b9b0cc2SKevin Wolf     }
33138b9b0cc2SKevin Wolf 
33140ed8b6f6SBlue Swirl     drv->bdrv_debug_event(bs, event);
331541c695c7SKevin Wolf }
33168b9b0cc2SKevin Wolf 
331741c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
331841c695c7SKevin Wolf                           const char *tag)
331941c695c7SKevin Wolf {
332041c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
332141c695c7SKevin Wolf         bs = bs->file;
332241c695c7SKevin Wolf     }
332341c695c7SKevin Wolf 
332441c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
332541c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
332641c695c7SKevin Wolf     }
332741c695c7SKevin Wolf 
332841c695c7SKevin Wolf     return -ENOTSUP;
332941c695c7SKevin Wolf }
333041c695c7SKevin Wolf 
333141c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
333241c695c7SKevin Wolf {
333341c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_resume) {
333441c695c7SKevin Wolf         bs = bs->file;
333541c695c7SKevin Wolf     }
333641c695c7SKevin Wolf 
333741c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
333841c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
333941c695c7SKevin Wolf     }
334041c695c7SKevin Wolf 
334141c695c7SKevin Wolf     return -ENOTSUP;
334241c695c7SKevin Wolf }
334341c695c7SKevin Wolf 
334441c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
334541c695c7SKevin Wolf {
334641c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
334741c695c7SKevin Wolf         bs = bs->file;
334841c695c7SKevin Wolf     }
334941c695c7SKevin Wolf 
335041c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
335141c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
335241c695c7SKevin Wolf     }
335341c695c7SKevin Wolf 
335441c695c7SKevin Wolf     return false;
33558b9b0cc2SKevin Wolf }
33568b9b0cc2SKevin Wolf 
3357faea38e7Sbellard /**************************************************************/
3358faea38e7Sbellard /* handling of snapshots */
3359faea38e7Sbellard 
3360feeee5acSMiguel Di Ciurcio Filho int bdrv_can_snapshot(BlockDriverState *bs)
3361feeee5acSMiguel Di Ciurcio Filho {
3362feeee5acSMiguel Di Ciurcio Filho     BlockDriver *drv = bs->drv;
336307b70bfbSMarkus Armbruster     if (!drv || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
3364feeee5acSMiguel Di Ciurcio Filho         return 0;
3365feeee5acSMiguel Di Ciurcio Filho     }
3366feeee5acSMiguel Di Ciurcio Filho 
3367feeee5acSMiguel Di Ciurcio Filho     if (!drv->bdrv_snapshot_create) {
3368feeee5acSMiguel Di Ciurcio Filho         if (bs->file != NULL) {
3369feeee5acSMiguel Di Ciurcio Filho             return bdrv_can_snapshot(bs->file);
3370feeee5acSMiguel Di Ciurcio Filho         }
3371feeee5acSMiguel Di Ciurcio Filho         return 0;
3372feeee5acSMiguel Di Ciurcio Filho     }
3373feeee5acSMiguel Di Ciurcio Filho 
3374feeee5acSMiguel Di Ciurcio Filho     return 1;
3375feeee5acSMiguel Di Ciurcio Filho }
3376feeee5acSMiguel Di Ciurcio Filho 
3377199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
3378199630b6SBlue Swirl {
3379199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3380199630b6SBlue Swirl }
3381199630b6SBlue Swirl 
3382f9092b10SMarkus Armbruster BlockDriverState *bdrv_snapshots(void)
3383f9092b10SMarkus Armbruster {
3384f9092b10SMarkus Armbruster     BlockDriverState *bs;
3385f9092b10SMarkus Armbruster 
33863ac906f7SMarkus Armbruster     if (bs_snapshots) {
3387f9092b10SMarkus Armbruster         return bs_snapshots;
33883ac906f7SMarkus Armbruster     }
3389f9092b10SMarkus Armbruster 
3390f9092b10SMarkus Armbruster     bs = NULL;
3391f9092b10SMarkus Armbruster     while ((bs = bdrv_next(bs))) {
3392f9092b10SMarkus Armbruster         if (bdrv_can_snapshot(bs)) {
33933ac906f7SMarkus Armbruster             bs_snapshots = bs;
33943ac906f7SMarkus Armbruster             return bs;
3395f9092b10SMarkus Armbruster         }
3396f9092b10SMarkus Armbruster     }
3397f9092b10SMarkus Armbruster     return NULL;
3398f9092b10SMarkus Armbruster }
3399f9092b10SMarkus Armbruster 
3400faea38e7Sbellard int bdrv_snapshot_create(BlockDriverState *bs,
3401faea38e7Sbellard                          QEMUSnapshotInfo *sn_info)
3402faea38e7Sbellard {
3403faea38e7Sbellard     BlockDriver *drv = bs->drv;
3404faea38e7Sbellard     if (!drv)
340519cb3738Sbellard         return -ENOMEDIUM;
34067cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_create)
3407faea38e7Sbellard         return drv->bdrv_snapshot_create(bs, sn_info);
34087cdb1f6dSMORITA Kazutaka     if (bs->file)
34097cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_create(bs->file, sn_info);
34107cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3411faea38e7Sbellard }
3412faea38e7Sbellard 
3413faea38e7Sbellard int bdrv_snapshot_goto(BlockDriverState *bs,
3414faea38e7Sbellard                        const char *snapshot_id)
3415faea38e7Sbellard {
3416faea38e7Sbellard     BlockDriver *drv = bs->drv;
34177cdb1f6dSMORITA Kazutaka     int ret, open_ret;
34187cdb1f6dSMORITA Kazutaka 
3419faea38e7Sbellard     if (!drv)
342019cb3738Sbellard         return -ENOMEDIUM;
34217cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_goto)
3422faea38e7Sbellard         return drv->bdrv_snapshot_goto(bs, snapshot_id);
34237cdb1f6dSMORITA Kazutaka 
34247cdb1f6dSMORITA Kazutaka     if (bs->file) {
34257cdb1f6dSMORITA Kazutaka         drv->bdrv_close(bs);
34267cdb1f6dSMORITA Kazutaka         ret = bdrv_snapshot_goto(bs->file, snapshot_id);
34271a86938fSKevin Wolf         open_ret = drv->bdrv_open(bs, NULL, bs->open_flags);
34287cdb1f6dSMORITA Kazutaka         if (open_ret < 0) {
34297cdb1f6dSMORITA Kazutaka             bdrv_delete(bs->file);
34307cdb1f6dSMORITA Kazutaka             bs->drv = NULL;
34317cdb1f6dSMORITA Kazutaka             return open_ret;
34327cdb1f6dSMORITA Kazutaka         }
34337cdb1f6dSMORITA Kazutaka         return ret;
34347cdb1f6dSMORITA Kazutaka     }
34357cdb1f6dSMORITA Kazutaka 
34367cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3437faea38e7Sbellard }
3438faea38e7Sbellard 
3439faea38e7Sbellard int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
3440faea38e7Sbellard {
3441faea38e7Sbellard     BlockDriver *drv = bs->drv;
3442faea38e7Sbellard     if (!drv)
344319cb3738Sbellard         return -ENOMEDIUM;
34447cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_delete)
3445faea38e7Sbellard         return drv->bdrv_snapshot_delete(bs, snapshot_id);
34467cdb1f6dSMORITA Kazutaka     if (bs->file)
34477cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_delete(bs->file, snapshot_id);
34487cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3449faea38e7Sbellard }
3450faea38e7Sbellard 
3451faea38e7Sbellard int bdrv_snapshot_list(BlockDriverState *bs,
3452faea38e7Sbellard                        QEMUSnapshotInfo **psn_info)
3453faea38e7Sbellard {
3454faea38e7Sbellard     BlockDriver *drv = bs->drv;
3455faea38e7Sbellard     if (!drv)
345619cb3738Sbellard         return -ENOMEDIUM;
34577cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_list)
3458faea38e7Sbellard         return drv->bdrv_snapshot_list(bs, psn_info);
34597cdb1f6dSMORITA Kazutaka     if (bs->file)
34607cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_list(bs->file, psn_info);
34617cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3462faea38e7Sbellard }
3463faea38e7Sbellard 
346451ef6727Sedison int bdrv_snapshot_load_tmp(BlockDriverState *bs,
346551ef6727Sedison         const char *snapshot_name)
346651ef6727Sedison {
346751ef6727Sedison     BlockDriver *drv = bs->drv;
346851ef6727Sedison     if (!drv) {
346951ef6727Sedison         return -ENOMEDIUM;
347051ef6727Sedison     }
347151ef6727Sedison     if (!bs->read_only) {
347251ef6727Sedison         return -EINVAL;
347351ef6727Sedison     }
347451ef6727Sedison     if (drv->bdrv_snapshot_load_tmp) {
347551ef6727Sedison         return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
347651ef6727Sedison     }
347751ef6727Sedison     return -ENOTSUP;
347851ef6727Sedison }
347951ef6727Sedison 
3480b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
3481b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
3482b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
3483b1b1d783SJeff Cody  * the CWD rather than the chain. */
3484e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3485e8a6bb9cSMarcelo Tosatti         const char *backing_file)
3486e8a6bb9cSMarcelo Tosatti {
3487b1b1d783SJeff Cody     char *filename_full = NULL;
3488b1b1d783SJeff Cody     char *backing_file_full = NULL;
3489b1b1d783SJeff Cody     char *filename_tmp = NULL;
3490b1b1d783SJeff Cody     int is_protocol = 0;
3491b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
3492b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
3493b1b1d783SJeff Cody 
3494b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
3495e8a6bb9cSMarcelo Tosatti         return NULL;
3496e8a6bb9cSMarcelo Tosatti     }
3497e8a6bb9cSMarcelo Tosatti 
3498b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
3499b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
3500b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
3501b1b1d783SJeff Cody 
3502b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
3503b1b1d783SJeff Cody 
3504b1b1d783SJeff Cody     for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
3505b1b1d783SJeff Cody 
3506b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
3507b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
3508b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3509b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3510b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
3511b1b1d783SJeff Cody                 break;
3512b1b1d783SJeff Cody             }
3513e8a6bb9cSMarcelo Tosatti         } else {
3514b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
3515b1b1d783SJeff Cody              * image's filename path */
3516b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3517b1b1d783SJeff Cody                          backing_file);
3518b1b1d783SJeff Cody 
3519b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
3520b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
3521b1b1d783SJeff Cody                 continue;
3522b1b1d783SJeff Cody             }
3523b1b1d783SJeff Cody 
3524b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
3525b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
3526b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3527b1b1d783SJeff Cody                          curr_bs->backing_file);
3528b1b1d783SJeff Cody 
3529b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
3530b1b1d783SJeff Cody                 continue;
3531b1b1d783SJeff Cody             }
3532b1b1d783SJeff Cody 
3533b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
3534b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
3535b1b1d783SJeff Cody                 break;
3536b1b1d783SJeff Cody             }
3537e8a6bb9cSMarcelo Tosatti         }
3538e8a6bb9cSMarcelo Tosatti     }
3539e8a6bb9cSMarcelo Tosatti 
3540b1b1d783SJeff Cody     g_free(filename_full);
3541b1b1d783SJeff Cody     g_free(backing_file_full);
3542b1b1d783SJeff Cody     g_free(filename_tmp);
3543b1b1d783SJeff Cody     return retval;
3544e8a6bb9cSMarcelo Tosatti }
3545e8a6bb9cSMarcelo Tosatti 
3546f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
3547f198fd1cSBenoît Canet {
3548f198fd1cSBenoît Canet     if (!bs->drv) {
3549f198fd1cSBenoît Canet         return 0;
3550f198fd1cSBenoît Canet     }
3551f198fd1cSBenoît Canet 
3552f198fd1cSBenoît Canet     if (!bs->backing_hd) {
3553f198fd1cSBenoît Canet         return 0;
3554f198fd1cSBenoît Canet     }
3555f198fd1cSBenoît Canet 
3556f198fd1cSBenoît Canet     return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
3557f198fd1cSBenoît Canet }
3558f198fd1cSBenoît Canet 
355979fac568SJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
356079fac568SJeff Cody {
356179fac568SJeff Cody     BlockDriverState *curr_bs = NULL;
356279fac568SJeff Cody 
356379fac568SJeff Cody     if (!bs) {
356479fac568SJeff Cody         return NULL;
356579fac568SJeff Cody     }
356679fac568SJeff Cody 
356779fac568SJeff Cody     curr_bs = bs;
356879fac568SJeff Cody 
356979fac568SJeff Cody     while (curr_bs->backing_hd) {
357079fac568SJeff Cody         curr_bs = curr_bs->backing_hd;
357179fac568SJeff Cody     }
357279fac568SJeff Cody     return curr_bs;
357379fac568SJeff Cody }
357479fac568SJeff Cody 
3575faea38e7Sbellard #define NB_SUFFIXES 4
3576faea38e7Sbellard 
3577faea38e7Sbellard char *get_human_readable_size(char *buf, int buf_size, int64_t size)
3578faea38e7Sbellard {
3579faea38e7Sbellard     static const char suffixes[NB_SUFFIXES] = "KMGT";
3580faea38e7Sbellard     int64_t base;
3581faea38e7Sbellard     int i;
3582faea38e7Sbellard 
3583faea38e7Sbellard     if (size <= 999) {
3584faea38e7Sbellard         snprintf(buf, buf_size, "%" PRId64, size);
3585faea38e7Sbellard     } else {
3586faea38e7Sbellard         base = 1024;
3587faea38e7Sbellard         for(i = 0; i < NB_SUFFIXES; i++) {
3588faea38e7Sbellard             if (size < (10 * base)) {
3589faea38e7Sbellard                 snprintf(buf, buf_size, "%0.1f%c",
3590faea38e7Sbellard                          (double)size / base,
3591faea38e7Sbellard                          suffixes[i]);
3592faea38e7Sbellard                 break;
3593faea38e7Sbellard             } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
3594faea38e7Sbellard                 snprintf(buf, buf_size, "%" PRId64 "%c",
3595faea38e7Sbellard                          ((size + (base >> 1)) / base),
3596faea38e7Sbellard                          suffixes[i]);
3597faea38e7Sbellard                 break;
3598faea38e7Sbellard             }
3599faea38e7Sbellard             base = base * 1024;
3600faea38e7Sbellard         }
3601faea38e7Sbellard     }
3602faea38e7Sbellard     return buf;
3603faea38e7Sbellard }
3604faea38e7Sbellard 
3605faea38e7Sbellard char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
3606faea38e7Sbellard {
3607faea38e7Sbellard     char buf1[128], date_buf[128], clock_buf[128];
3608faea38e7Sbellard     struct tm tm;
3609faea38e7Sbellard     time_t ti;
3610faea38e7Sbellard     int64_t secs;
3611faea38e7Sbellard 
3612faea38e7Sbellard     if (!sn) {
3613faea38e7Sbellard         snprintf(buf, buf_size,
3614faea38e7Sbellard                  "%-10s%-20s%7s%20s%15s",
3615faea38e7Sbellard                  "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
3616faea38e7Sbellard     } else {
3617faea38e7Sbellard         ti = sn->date_sec;
3618faea38e7Sbellard         localtime_r(&ti, &tm);
3619faea38e7Sbellard         strftime(date_buf, sizeof(date_buf),
3620faea38e7Sbellard                  "%Y-%m-%d %H:%M:%S", &tm);
3621faea38e7Sbellard         secs = sn->vm_clock_nsec / 1000000000;
3622faea38e7Sbellard         snprintf(clock_buf, sizeof(clock_buf),
3623faea38e7Sbellard                  "%02d:%02d:%02d.%03d",
3624faea38e7Sbellard                  (int)(secs / 3600),
3625faea38e7Sbellard                  (int)((secs / 60) % 60),
3626faea38e7Sbellard                  (int)(secs % 60),
3627faea38e7Sbellard                  (int)((sn->vm_clock_nsec / 1000000) % 1000));
3628faea38e7Sbellard         snprintf(buf, buf_size,
3629faea38e7Sbellard                  "%-10s%-20s%7s%20s%15s",
3630faea38e7Sbellard                  sn->id_str, sn->name,
3631faea38e7Sbellard                  get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
3632faea38e7Sbellard                  date_buf,
3633faea38e7Sbellard                  clock_buf);
3634faea38e7Sbellard     }
3635faea38e7Sbellard     return buf;
3636faea38e7Sbellard }
3637faea38e7Sbellard 
3638ea2384d3Sbellard /**************************************************************/
363983f64091Sbellard /* async I/Os */
3640ea2384d3Sbellard 
36413b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
3642f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
364383f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
3644ea2384d3Sbellard {
3645bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
3646bbf0a440SStefan Hajnoczi 
3647b2a61371SStefan Hajnoczi     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
36488c5873d6SStefan Hajnoczi                                  cb, opaque, false);
364983f64091Sbellard }
365083f64091Sbellard 
3651f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
3652f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
365383f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
36547674e7bfSbellard {
3655bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
3656bbf0a440SStefan Hajnoczi 
36571a6e115bSStefan Hajnoczi     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
36588c5873d6SStefan Hajnoczi                                  cb, opaque, true);
365983f64091Sbellard }
366083f64091Sbellard 
366140b4f539SKevin Wolf 
366240b4f539SKevin Wolf typedef struct MultiwriteCB {
366340b4f539SKevin Wolf     int error;
366440b4f539SKevin Wolf     int num_requests;
366540b4f539SKevin Wolf     int num_callbacks;
366640b4f539SKevin Wolf     struct {
366740b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
366840b4f539SKevin Wolf         void *opaque;
366940b4f539SKevin Wolf         QEMUIOVector *free_qiov;
367040b4f539SKevin Wolf     } callbacks[];
367140b4f539SKevin Wolf } MultiwriteCB;
367240b4f539SKevin Wolf 
367340b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
367440b4f539SKevin Wolf {
367540b4f539SKevin Wolf     int i;
367640b4f539SKevin Wolf 
367740b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
367840b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
36791e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
36801e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
36811e1ea48dSStefan Hajnoczi         }
36827267c094SAnthony Liguori         g_free(mcb->callbacks[i].free_qiov);
368340b4f539SKevin Wolf     }
368440b4f539SKevin Wolf }
368540b4f539SKevin Wolf 
368640b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
368740b4f539SKevin Wolf {
368840b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
368940b4f539SKevin Wolf 
36906d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
36916d519a5fSStefan Hajnoczi 
3692cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
369340b4f539SKevin Wolf         mcb->error = ret;
369440b4f539SKevin Wolf     }
369540b4f539SKevin Wolf 
369640b4f539SKevin Wolf     mcb->num_requests--;
369740b4f539SKevin Wolf     if (mcb->num_requests == 0) {
369840b4f539SKevin Wolf         multiwrite_user_cb(mcb);
36997267c094SAnthony Liguori         g_free(mcb);
370040b4f539SKevin Wolf     }
370140b4f539SKevin Wolf }
370240b4f539SKevin Wolf 
370340b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
370440b4f539SKevin Wolf {
370577be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
370677be4366SChristoph Hellwig 
370777be4366SChristoph Hellwig     /*
370877be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
370977be4366SChristoph Hellwig      * here as that could overflow the return value.
371077be4366SChristoph Hellwig      */
371177be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
371277be4366SChristoph Hellwig         return 1;
371377be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
371477be4366SChristoph Hellwig         return -1;
371577be4366SChristoph Hellwig     } else {
371677be4366SChristoph Hellwig         return 0;
371777be4366SChristoph Hellwig     }
371840b4f539SKevin Wolf }
371940b4f539SKevin Wolf 
372040b4f539SKevin Wolf /*
372140b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
372240b4f539SKevin Wolf  * requests that remain after merging.
372340b4f539SKevin Wolf  */
372440b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
372540b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
372640b4f539SKevin Wolf {
372740b4f539SKevin Wolf     int i, outidx;
372840b4f539SKevin Wolf 
372940b4f539SKevin Wolf     // Sort requests by start sector
373040b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
373140b4f539SKevin Wolf 
373240b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
373340b4f539SKevin Wolf     // filling up gaps with zero sectors.
373440b4f539SKevin Wolf     outidx = 0;
373540b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
373640b4f539SKevin Wolf         int merge = 0;
373740b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
373840b4f539SKevin Wolf 
3739b6a127a1SPaolo Bonzini         // Handle exactly sequential writes and overlapping writes.
374040b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
374140b4f539SKevin Wolf             merge = 1;
374240b4f539SKevin Wolf         }
374340b4f539SKevin Wolf 
3744e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
3745e2a305fbSChristoph Hellwig             merge = 0;
3746e2a305fbSChristoph Hellwig         }
3747e2a305fbSChristoph Hellwig 
374840b4f539SKevin Wolf         if (merge) {
374940b4f539SKevin Wolf             size_t size;
37507267c094SAnthony Liguori             QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
375140b4f539SKevin Wolf             qemu_iovec_init(qiov,
375240b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
375340b4f539SKevin Wolf 
375440b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
375540b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
375640b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
37571b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
375840b4f539SKevin Wolf 
3759b6a127a1SPaolo Bonzini             // We should need to add any zeros between the two requests
3760b6a127a1SPaolo Bonzini             assert (reqs[i].sector <= oldreq_last);
376140b4f539SKevin Wolf 
376240b4f539SKevin Wolf             // Add the second request
37631b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
376440b4f539SKevin Wolf 
3765cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
376640b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
376740b4f539SKevin Wolf 
376840b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
376940b4f539SKevin Wolf         } else {
377040b4f539SKevin Wolf             outidx++;
377140b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
377240b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
377340b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
377440b4f539SKevin Wolf         }
377540b4f539SKevin Wolf     }
377640b4f539SKevin Wolf 
377740b4f539SKevin Wolf     return outidx + 1;
377840b4f539SKevin Wolf }
377940b4f539SKevin Wolf 
378040b4f539SKevin Wolf /*
378140b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
378240b4f539SKevin Wolf  *
378340b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
378440b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
378540b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
378640b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
378740b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
378840b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
378940b4f539SKevin Wolf  *
379040b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
379140b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
379240b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
379340b4f539SKevin Wolf  */
379440b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
379540b4f539SKevin Wolf {
379640b4f539SKevin Wolf     MultiwriteCB *mcb;
379740b4f539SKevin Wolf     int i;
379840b4f539SKevin Wolf 
3799301db7c2SRyan Harper     /* don't submit writes if we don't have a medium */
3800301db7c2SRyan Harper     if (bs->drv == NULL) {
3801301db7c2SRyan Harper         for (i = 0; i < num_reqs; i++) {
3802301db7c2SRyan Harper             reqs[i].error = -ENOMEDIUM;
3803301db7c2SRyan Harper         }
3804301db7c2SRyan Harper         return -1;
3805301db7c2SRyan Harper     }
3806301db7c2SRyan Harper 
380740b4f539SKevin Wolf     if (num_reqs == 0) {
380840b4f539SKevin Wolf         return 0;
380940b4f539SKevin Wolf     }
381040b4f539SKevin Wolf 
381140b4f539SKevin Wolf     // Create MultiwriteCB structure
38127267c094SAnthony Liguori     mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
381340b4f539SKevin Wolf     mcb->num_requests = 0;
381440b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
381540b4f539SKevin Wolf 
381640b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
381740b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
381840b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
381940b4f539SKevin Wolf     }
382040b4f539SKevin Wolf 
382140b4f539SKevin Wolf     // Check for mergable requests
382240b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
382340b4f539SKevin Wolf 
38246d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
38256d519a5fSStefan Hajnoczi 
3826df9309fbSPaolo Bonzini     /* Run the aio requests. */
3827df9309fbSPaolo Bonzini     mcb->num_requests = num_reqs;
382840b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
3829ad54ae80SPaolo Bonzini         bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
383040b4f539SKevin Wolf             reqs[i].nb_sectors, multiwrite_cb, mcb);
383140b4f539SKevin Wolf     }
383240b4f539SKevin Wolf 
383340b4f539SKevin Wolf     return 0;
383440b4f539SKevin Wolf }
383540b4f539SKevin Wolf 
383683f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
383783f64091Sbellard {
3838d7331bedSStefan Hajnoczi     acb->aiocb_info->cancel(acb);
383983f64091Sbellard }
384083f64091Sbellard 
384198f90dbaSZhi Yong Wu /* block I/O throttling */
384298f90dbaSZhi Yong Wu static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
384398f90dbaSZhi Yong Wu                  bool is_write, double elapsed_time, uint64_t *wait)
384498f90dbaSZhi Yong Wu {
384598f90dbaSZhi Yong Wu     uint64_t bps_limit = 0;
3846ae29d6c6SStefan Hajnoczi     uint64_t extension;
384798f90dbaSZhi Yong Wu     double   bytes_limit, bytes_base, bytes_res;
384898f90dbaSZhi Yong Wu     double   slice_time, wait_time;
384998f90dbaSZhi Yong Wu 
385098f90dbaSZhi Yong Wu     if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
385198f90dbaSZhi Yong Wu         bps_limit = bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
385298f90dbaSZhi Yong Wu     } else if (bs->io_limits.bps[is_write]) {
385398f90dbaSZhi Yong Wu         bps_limit = bs->io_limits.bps[is_write];
385498f90dbaSZhi Yong Wu     } else {
385598f90dbaSZhi Yong Wu         if (wait) {
385698f90dbaSZhi Yong Wu             *wait = 0;
385798f90dbaSZhi Yong Wu         }
385898f90dbaSZhi Yong Wu 
385998f90dbaSZhi Yong Wu         return false;
386098f90dbaSZhi Yong Wu     }
386198f90dbaSZhi Yong Wu 
386298f90dbaSZhi Yong Wu     slice_time = bs->slice_end - bs->slice_start;
386398f90dbaSZhi Yong Wu     slice_time /= (NANOSECONDS_PER_SECOND);
386498f90dbaSZhi Yong Wu     bytes_limit = bps_limit * slice_time;
38655905fbc9SStefan Hajnoczi     bytes_base  = bs->slice_submitted.bytes[is_write];
386698f90dbaSZhi Yong Wu     if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
38675905fbc9SStefan Hajnoczi         bytes_base += bs->slice_submitted.bytes[!is_write];
386898f90dbaSZhi Yong Wu     }
386998f90dbaSZhi Yong Wu 
387098f90dbaSZhi Yong Wu     /* bytes_base: the bytes of data which have been read/written; and
387198f90dbaSZhi Yong Wu      *             it is obtained from the history statistic info.
387298f90dbaSZhi Yong Wu      * bytes_res: the remaining bytes of data which need to be read/written.
387398f90dbaSZhi Yong Wu      * (bytes_base + bytes_res) / bps_limit: used to calcuate
387498f90dbaSZhi Yong Wu      *             the total time for completing reading/writting all data.
387598f90dbaSZhi Yong Wu      */
387698f90dbaSZhi Yong Wu     bytes_res   = (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
387798f90dbaSZhi Yong Wu 
387898f90dbaSZhi Yong Wu     if (bytes_base + bytes_res <= bytes_limit) {
387998f90dbaSZhi Yong Wu         if (wait) {
388098f90dbaSZhi Yong Wu             *wait = 0;
388198f90dbaSZhi Yong Wu         }
388298f90dbaSZhi Yong Wu 
388398f90dbaSZhi Yong Wu         return false;
388498f90dbaSZhi Yong Wu     }
388598f90dbaSZhi Yong Wu 
388698f90dbaSZhi Yong Wu     /* Calc approx time to dispatch */
388798f90dbaSZhi Yong Wu     wait_time = (bytes_base + bytes_res) / bps_limit - elapsed_time;
388898f90dbaSZhi Yong Wu 
388998f90dbaSZhi Yong Wu     /* When the I/O rate at runtime exceeds the limits,
389098f90dbaSZhi Yong Wu      * bs->slice_end need to be extended in order that the current statistic
389198f90dbaSZhi Yong Wu      * info can be kept until the timer fire, so it is increased and tuned
389298f90dbaSZhi Yong Wu      * based on the result of experiment.
389398f90dbaSZhi Yong Wu      */
3894ae29d6c6SStefan Hajnoczi     extension = wait_time * NANOSECONDS_PER_SECOND;
3895ae29d6c6SStefan Hajnoczi     extension = DIV_ROUND_UP(extension, BLOCK_IO_SLICE_TIME) *
3896ae29d6c6SStefan Hajnoczi                 BLOCK_IO_SLICE_TIME;
3897ae29d6c6SStefan Hajnoczi     bs->slice_end += extension;
389898f90dbaSZhi Yong Wu     if (wait) {
38990775437fSStefan Hajnoczi         *wait = wait_time * NANOSECONDS_PER_SECOND;
390098f90dbaSZhi Yong Wu     }
390198f90dbaSZhi Yong Wu 
390298f90dbaSZhi Yong Wu     return true;
390398f90dbaSZhi Yong Wu }
390498f90dbaSZhi Yong Wu 
390598f90dbaSZhi Yong Wu static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
390698f90dbaSZhi Yong Wu                              double elapsed_time, uint64_t *wait)
390798f90dbaSZhi Yong Wu {
390898f90dbaSZhi Yong Wu     uint64_t iops_limit = 0;
390998f90dbaSZhi Yong Wu     double   ios_limit, ios_base;
391098f90dbaSZhi Yong Wu     double   slice_time, wait_time;
391198f90dbaSZhi Yong Wu 
391298f90dbaSZhi Yong Wu     if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
391398f90dbaSZhi Yong Wu         iops_limit = bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
391498f90dbaSZhi Yong Wu     } else if (bs->io_limits.iops[is_write]) {
391598f90dbaSZhi Yong Wu         iops_limit = bs->io_limits.iops[is_write];
391698f90dbaSZhi Yong Wu     } else {
391798f90dbaSZhi Yong Wu         if (wait) {
391898f90dbaSZhi Yong Wu             *wait = 0;
391998f90dbaSZhi Yong Wu         }
392098f90dbaSZhi Yong Wu 
392198f90dbaSZhi Yong Wu         return false;
392298f90dbaSZhi Yong Wu     }
392398f90dbaSZhi Yong Wu 
392498f90dbaSZhi Yong Wu     slice_time = bs->slice_end - bs->slice_start;
392598f90dbaSZhi Yong Wu     slice_time /= (NANOSECONDS_PER_SECOND);
392698f90dbaSZhi Yong Wu     ios_limit  = iops_limit * slice_time;
39275905fbc9SStefan Hajnoczi     ios_base   = bs->slice_submitted.ios[is_write];
392898f90dbaSZhi Yong Wu     if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
39295905fbc9SStefan Hajnoczi         ios_base += bs->slice_submitted.ios[!is_write];
393098f90dbaSZhi Yong Wu     }
393198f90dbaSZhi Yong Wu 
393298f90dbaSZhi Yong Wu     if (ios_base + 1 <= ios_limit) {
393398f90dbaSZhi Yong Wu         if (wait) {
393498f90dbaSZhi Yong Wu             *wait = 0;
393598f90dbaSZhi Yong Wu         }
393698f90dbaSZhi Yong Wu 
393798f90dbaSZhi Yong Wu         return false;
393898f90dbaSZhi Yong Wu     }
393998f90dbaSZhi Yong Wu 
39400775437fSStefan Hajnoczi     /* Calc approx time to dispatch, in seconds */
394198f90dbaSZhi Yong Wu     wait_time = (ios_base + 1) / iops_limit;
394298f90dbaSZhi Yong Wu     if (wait_time > elapsed_time) {
394398f90dbaSZhi Yong Wu         wait_time = wait_time - elapsed_time;
394498f90dbaSZhi Yong Wu     } else {
394598f90dbaSZhi Yong Wu         wait_time = 0;
394698f90dbaSZhi Yong Wu     }
394798f90dbaSZhi Yong Wu 
3948ae29d6c6SStefan Hajnoczi     /* Exceeded current slice, extend it by another slice time */
3949ae29d6c6SStefan Hajnoczi     bs->slice_end += BLOCK_IO_SLICE_TIME;
395098f90dbaSZhi Yong Wu     if (wait) {
39510775437fSStefan Hajnoczi         *wait = wait_time * NANOSECONDS_PER_SECOND;
395298f90dbaSZhi Yong Wu     }
395398f90dbaSZhi Yong Wu 
395498f90dbaSZhi Yong Wu     return true;
395598f90dbaSZhi Yong Wu }
395698f90dbaSZhi Yong Wu 
395798f90dbaSZhi Yong Wu static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
395898f90dbaSZhi Yong Wu                            bool is_write, int64_t *wait)
395998f90dbaSZhi Yong Wu {
396098f90dbaSZhi Yong Wu     int64_t  now, max_wait;
396198f90dbaSZhi Yong Wu     uint64_t bps_wait = 0, iops_wait = 0;
396298f90dbaSZhi Yong Wu     double   elapsed_time;
396398f90dbaSZhi Yong Wu     int      bps_ret, iops_ret;
396498f90dbaSZhi Yong Wu 
396598f90dbaSZhi Yong Wu     now = qemu_get_clock_ns(vm_clock);
3966e660fb8bSStefan Hajnoczi     if (now > bs->slice_end) {
396798f90dbaSZhi Yong Wu         bs->slice_start = now;
3968ae29d6c6SStefan Hajnoczi         bs->slice_end   = now + BLOCK_IO_SLICE_TIME;
39695905fbc9SStefan Hajnoczi         memset(&bs->slice_submitted, 0, sizeof(bs->slice_submitted));
397098f90dbaSZhi Yong Wu     }
397198f90dbaSZhi Yong Wu 
397298f90dbaSZhi Yong Wu     elapsed_time  = now - bs->slice_start;
397398f90dbaSZhi Yong Wu     elapsed_time  /= (NANOSECONDS_PER_SECOND);
397498f90dbaSZhi Yong Wu 
397598f90dbaSZhi Yong Wu     bps_ret  = bdrv_exceed_bps_limits(bs, nb_sectors,
397698f90dbaSZhi Yong Wu                                       is_write, elapsed_time, &bps_wait);
397798f90dbaSZhi Yong Wu     iops_ret = bdrv_exceed_iops_limits(bs, is_write,
397898f90dbaSZhi Yong Wu                                       elapsed_time, &iops_wait);
397998f90dbaSZhi Yong Wu     if (bps_ret || iops_ret) {
398098f90dbaSZhi Yong Wu         max_wait = bps_wait > iops_wait ? bps_wait : iops_wait;
398198f90dbaSZhi Yong Wu         if (wait) {
398298f90dbaSZhi Yong Wu             *wait = max_wait;
398398f90dbaSZhi Yong Wu         }
398498f90dbaSZhi Yong Wu 
398598f90dbaSZhi Yong Wu         now = qemu_get_clock_ns(vm_clock);
398698f90dbaSZhi Yong Wu         if (bs->slice_end < now + max_wait) {
398798f90dbaSZhi Yong Wu             bs->slice_end = now + max_wait;
398898f90dbaSZhi Yong Wu         }
398998f90dbaSZhi Yong Wu 
399098f90dbaSZhi Yong Wu         return true;
399198f90dbaSZhi Yong Wu     }
399298f90dbaSZhi Yong Wu 
399398f90dbaSZhi Yong Wu     if (wait) {
399498f90dbaSZhi Yong Wu         *wait = 0;
399598f90dbaSZhi Yong Wu     }
399698f90dbaSZhi Yong Wu 
39975905fbc9SStefan Hajnoczi     bs->slice_submitted.bytes[is_write] += (int64_t)nb_sectors *
39985905fbc9SStefan Hajnoczi                                            BDRV_SECTOR_SIZE;
39995905fbc9SStefan Hajnoczi     bs->slice_submitted.ios[is_write]++;
40005905fbc9SStefan Hajnoczi 
400198f90dbaSZhi Yong Wu     return false;
400298f90dbaSZhi Yong Wu }
400383f64091Sbellard 
400483f64091Sbellard /**************************************************************/
400583f64091Sbellard /* async block device emulation */
400683f64091Sbellard 
4007c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
4008c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
4009c16b5a2cSChristoph Hellwig     QEMUBH *bh;
4010c16b5a2cSChristoph Hellwig     int ret;
4011c16b5a2cSChristoph Hellwig     /* vector translation state */
4012c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
4013c16b5a2cSChristoph Hellwig     uint8_t *bounce;
4014c16b5a2cSChristoph Hellwig     int is_write;
4015c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
4016c16b5a2cSChristoph Hellwig 
4017c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
4018c16b5a2cSChristoph Hellwig {
4019b666d239SKevin Wolf     BlockDriverAIOCBSync *acb =
4020b666d239SKevin Wolf         container_of(blockacb, BlockDriverAIOCBSync, common);
40216a7ad299SDor Laor     qemu_bh_delete(acb->bh);
402236afc451SAvi Kivity     acb->bh = NULL;
4023c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
4024c16b5a2cSChristoph Hellwig }
4025c16b5a2cSChristoph Hellwig 
4026d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_aiocb_info = {
4027c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
4028c16b5a2cSChristoph Hellwig     .cancel             = bdrv_aio_cancel_em,
4029c16b5a2cSChristoph Hellwig };
4030c16b5a2cSChristoph Hellwig 
403183f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
4032beac80cdSbellard {
4033ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
4034f141eafeSaliguori 
4035f141eafeSaliguori     if (!acb->is_write)
403603396148SMichael Tokarev         qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
4037ceb42de8Saliguori     qemu_vfree(acb->bounce);
4038ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
40396a7ad299SDor Laor     qemu_bh_delete(acb->bh);
404036afc451SAvi Kivity     acb->bh = NULL;
4041ce1a14dcSpbrook     qemu_aio_release(acb);
4042beac80cdSbellard }
4043beac80cdSbellard 
4044f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
4045f141eafeSaliguori                                             int64_t sector_num,
4046f141eafeSaliguori                                             QEMUIOVector *qiov,
4047f141eafeSaliguori                                             int nb_sectors,
4048f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
4049f141eafeSaliguori                                             void *opaque,
4050f141eafeSaliguori                                             int is_write)
4051f141eafeSaliguori 
4052ea2384d3Sbellard {
4053ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
405483f64091Sbellard 
4055d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
4056f141eafeSaliguori     acb->is_write = is_write;
4057f141eafeSaliguori     acb->qiov = qiov;
4058e268ca52Saliguori     acb->bounce = qemu_blockalign(bs, qiov->size);
4059ce1a14dcSpbrook     acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
4060f141eafeSaliguori 
4061f141eafeSaliguori     if (is_write) {
4062d5e6b161SMichael Tokarev         qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
40631ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
4064f141eafeSaliguori     } else {
40651ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
4066f141eafeSaliguori     }
4067f141eafeSaliguori 
4068ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
4069f141eafeSaliguori 
4070ce1a14dcSpbrook     return &acb->common;
40717a6cba61Spbrook }
40727a6cba61Spbrook 
4073f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
4074f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4075ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
407683f64091Sbellard {
4077f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
407883f64091Sbellard }
407983f64091Sbellard 
4080f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
4081f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4082f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
4083f141eafeSaliguori {
4084f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
4085f141eafeSaliguori }
4086f141eafeSaliguori 
408768485420SKevin Wolf 
408868485420SKevin Wolf typedef struct BlockDriverAIOCBCoroutine {
408968485420SKevin Wolf     BlockDriverAIOCB common;
409068485420SKevin Wolf     BlockRequest req;
409168485420SKevin Wolf     bool is_write;
4092d318aea9SKevin Wolf     bool *done;
409368485420SKevin Wolf     QEMUBH* bh;
409468485420SKevin Wolf } BlockDriverAIOCBCoroutine;
409568485420SKevin Wolf 
409668485420SKevin Wolf static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
409768485420SKevin Wolf {
4098d318aea9SKevin Wolf     BlockDriverAIOCBCoroutine *acb =
4099d318aea9SKevin Wolf         container_of(blockacb, BlockDriverAIOCBCoroutine, common);
4100d318aea9SKevin Wolf     bool done = false;
4101d318aea9SKevin Wolf 
4102d318aea9SKevin Wolf     acb->done = &done;
4103d318aea9SKevin Wolf     while (!done) {
4104d318aea9SKevin Wolf         qemu_aio_wait();
4105d318aea9SKevin Wolf     }
410668485420SKevin Wolf }
410768485420SKevin Wolf 
4108d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_co_aiocb_info = {
410968485420SKevin Wolf     .aiocb_size         = sizeof(BlockDriverAIOCBCoroutine),
411068485420SKevin Wolf     .cancel             = bdrv_aio_co_cancel_em,
411168485420SKevin Wolf };
411268485420SKevin Wolf 
411335246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque)
411468485420SKevin Wolf {
411568485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb = opaque;
411668485420SKevin Wolf 
411768485420SKevin Wolf     acb->common.cb(acb->common.opaque, acb->req.error);
4118d318aea9SKevin Wolf 
4119d318aea9SKevin Wolf     if (acb->done) {
4120d318aea9SKevin Wolf         *acb->done = true;
4121d318aea9SKevin Wolf     }
4122d318aea9SKevin Wolf 
412368485420SKevin Wolf     qemu_bh_delete(acb->bh);
412468485420SKevin Wolf     qemu_aio_release(acb);
412568485420SKevin Wolf }
412668485420SKevin Wolf 
4127b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
4128b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque)
4129b2a61371SStefan Hajnoczi {
4130b2a61371SStefan Hajnoczi     BlockDriverAIOCBCoroutine *acb = opaque;
4131b2a61371SStefan Hajnoczi     BlockDriverState *bs = acb->common.bs;
4132b2a61371SStefan Hajnoczi 
4133b2a61371SStefan Hajnoczi     if (!acb->is_write) {
4134b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
4135470c0504SStefan Hajnoczi             acb->req.nb_sectors, acb->req.qiov, 0);
4136b2a61371SStefan Hajnoczi     } else {
4137b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
4138f08f2ddaSStefan Hajnoczi             acb->req.nb_sectors, acb->req.qiov, 0);
4139b2a61371SStefan Hajnoczi     }
4140b2a61371SStefan Hajnoczi 
414135246a68SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4142b2a61371SStefan Hajnoczi     qemu_bh_schedule(acb->bh);
4143b2a61371SStefan Hajnoczi }
4144b2a61371SStefan Hajnoczi 
414568485420SKevin Wolf static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
414668485420SKevin Wolf                                                int64_t sector_num,
414768485420SKevin Wolf                                                QEMUIOVector *qiov,
414868485420SKevin Wolf                                                int nb_sectors,
414968485420SKevin Wolf                                                BlockDriverCompletionFunc *cb,
415068485420SKevin Wolf                                                void *opaque,
41518c5873d6SStefan Hajnoczi                                                bool is_write)
415268485420SKevin Wolf {
415368485420SKevin Wolf     Coroutine *co;
415468485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb;
415568485420SKevin Wolf 
4156d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
415768485420SKevin Wolf     acb->req.sector = sector_num;
415868485420SKevin Wolf     acb->req.nb_sectors = nb_sectors;
415968485420SKevin Wolf     acb->req.qiov = qiov;
416068485420SKevin Wolf     acb->is_write = is_write;
4161d318aea9SKevin Wolf     acb->done = NULL;
416268485420SKevin Wolf 
41638c5873d6SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_co_do_rw);
416468485420SKevin Wolf     qemu_coroutine_enter(co, acb);
416568485420SKevin Wolf 
416668485420SKevin Wolf     return &acb->common;
416768485420SKevin Wolf }
416868485420SKevin Wolf 
416907f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
4170b2e12bc6SChristoph Hellwig {
417107f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
417207f07615SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
4173b2e12bc6SChristoph Hellwig 
417407f07615SPaolo Bonzini     acb->req.error = bdrv_co_flush(bs);
417507f07615SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4176b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
4177b2e12bc6SChristoph Hellwig }
4178b2e12bc6SChristoph Hellwig 
417907f07615SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
4180016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
4181016f5cf6SAlexander Graf {
418207f07615SPaolo Bonzini     trace_bdrv_aio_flush(bs, opaque);
4183016f5cf6SAlexander Graf 
418407f07615SPaolo Bonzini     Coroutine *co;
418507f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
4186016f5cf6SAlexander Graf 
4187d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4188d318aea9SKevin Wolf     acb->done = NULL;
4189d318aea9SKevin Wolf 
419007f07615SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
419107f07615SPaolo Bonzini     qemu_coroutine_enter(co, acb);
4192016f5cf6SAlexander Graf 
4193016f5cf6SAlexander Graf     return &acb->common;
4194016f5cf6SAlexander Graf }
4195016f5cf6SAlexander Graf 
41964265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
41974265d620SPaolo Bonzini {
41984265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
41994265d620SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
42004265d620SPaolo Bonzini 
42014265d620SPaolo Bonzini     acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
42024265d620SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
42034265d620SPaolo Bonzini     qemu_bh_schedule(acb->bh);
42044265d620SPaolo Bonzini }
42054265d620SPaolo Bonzini 
42064265d620SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
42074265d620SPaolo Bonzini         int64_t sector_num, int nb_sectors,
42084265d620SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
42094265d620SPaolo Bonzini {
42104265d620SPaolo Bonzini     Coroutine *co;
42114265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
42124265d620SPaolo Bonzini 
42134265d620SPaolo Bonzini     trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
42144265d620SPaolo Bonzini 
4215d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
42164265d620SPaolo Bonzini     acb->req.sector = sector_num;
42174265d620SPaolo Bonzini     acb->req.nb_sectors = nb_sectors;
4218d318aea9SKevin Wolf     acb->done = NULL;
42194265d620SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
42204265d620SPaolo Bonzini     qemu_coroutine_enter(co, acb);
42214265d620SPaolo Bonzini 
42224265d620SPaolo Bonzini     return &acb->common;
42234265d620SPaolo Bonzini }
42244265d620SPaolo Bonzini 
4225ea2384d3Sbellard void bdrv_init(void)
4226ea2384d3Sbellard {
42275efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
4228ea2384d3Sbellard }
4229ce1a14dcSpbrook 
4230eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
4231eb852011SMarkus Armbruster {
4232eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
4233eb852011SMarkus Armbruster     bdrv_init();
4234eb852011SMarkus Armbruster }
4235eb852011SMarkus Armbruster 
4236d7331bedSStefan Hajnoczi void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
42376bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
42386bbff9a0Saliguori {
4239ce1a14dcSpbrook     BlockDriverAIOCB *acb;
4240ce1a14dcSpbrook 
4241d7331bedSStefan Hajnoczi     acb = g_slice_alloc(aiocb_info->aiocb_size);
4242d7331bedSStefan Hajnoczi     acb->aiocb_info = aiocb_info;
4243ce1a14dcSpbrook     acb->bs = bs;
4244ce1a14dcSpbrook     acb->cb = cb;
4245ce1a14dcSpbrook     acb->opaque = opaque;
4246ce1a14dcSpbrook     return acb;
4247ce1a14dcSpbrook }
4248ce1a14dcSpbrook 
4249ce1a14dcSpbrook void qemu_aio_release(void *p)
4250ce1a14dcSpbrook {
4251d37c975fSStefan Hajnoczi     BlockDriverAIOCB *acb = p;
4252d7331bedSStefan Hajnoczi     g_slice_free1(acb->aiocb_info->aiocb_size, acb);
4253ce1a14dcSpbrook }
425419cb3738Sbellard 
425519cb3738Sbellard /**************************************************************/
4256f9f05dc5SKevin Wolf /* Coroutine block device emulation */
4257f9f05dc5SKevin Wolf 
4258f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion {
4259f9f05dc5SKevin Wolf     Coroutine *coroutine;
4260f9f05dc5SKevin Wolf     int ret;
4261f9f05dc5SKevin Wolf } CoroutineIOCompletion;
4262f9f05dc5SKevin Wolf 
4263f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret)
4264f9f05dc5SKevin Wolf {
4265f9f05dc5SKevin Wolf     CoroutineIOCompletion *co = opaque;
4266f9f05dc5SKevin Wolf 
4267f9f05dc5SKevin Wolf     co->ret = ret;
4268f9f05dc5SKevin Wolf     qemu_coroutine_enter(co->coroutine, NULL);
4269f9f05dc5SKevin Wolf }
4270f9f05dc5SKevin Wolf 
4271f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
4272f9f05dc5SKevin Wolf                                       int nb_sectors, QEMUIOVector *iov,
4273f9f05dc5SKevin Wolf                                       bool is_write)
4274f9f05dc5SKevin Wolf {
4275f9f05dc5SKevin Wolf     CoroutineIOCompletion co = {
4276f9f05dc5SKevin Wolf         .coroutine = qemu_coroutine_self(),
4277f9f05dc5SKevin Wolf     };
4278f9f05dc5SKevin Wolf     BlockDriverAIOCB *acb;
4279f9f05dc5SKevin Wolf 
4280f9f05dc5SKevin Wolf     if (is_write) {
4281a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
4282f9f05dc5SKevin Wolf                                        bdrv_co_io_em_complete, &co);
4283f9f05dc5SKevin Wolf     } else {
4284a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
4285f9f05dc5SKevin Wolf                                       bdrv_co_io_em_complete, &co);
4286f9f05dc5SKevin Wolf     }
4287f9f05dc5SKevin Wolf 
428859370aaaSStefan Hajnoczi     trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
4289f9f05dc5SKevin Wolf     if (!acb) {
4290f9f05dc5SKevin Wolf         return -EIO;
4291f9f05dc5SKevin Wolf     }
4292f9f05dc5SKevin Wolf     qemu_coroutine_yield();
4293f9f05dc5SKevin Wolf 
4294f9f05dc5SKevin Wolf     return co.ret;
4295f9f05dc5SKevin Wolf }
4296f9f05dc5SKevin Wolf 
4297f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
4298f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4299f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4300f9f05dc5SKevin Wolf {
4301f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
4302f9f05dc5SKevin Wolf }
4303f9f05dc5SKevin Wolf 
4304f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
4305f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4306f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4307f9f05dc5SKevin Wolf {
4308f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
4309f9f05dc5SKevin Wolf }
4310f9f05dc5SKevin Wolf 
431107f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque)
4312e7a8a783SKevin Wolf {
431307f07615SPaolo Bonzini     RwCo *rwco = opaque;
431407f07615SPaolo Bonzini 
431507f07615SPaolo Bonzini     rwco->ret = bdrv_co_flush(rwco->bs);
431607f07615SPaolo Bonzini }
431707f07615SPaolo Bonzini 
431807f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
431907f07615SPaolo Bonzini {
4320eb489bb1SKevin Wolf     int ret;
4321eb489bb1SKevin Wolf 
432229cdb251SPaolo Bonzini     if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
432307f07615SPaolo Bonzini         return 0;
4324eb489bb1SKevin Wolf     }
4325eb489bb1SKevin Wolf 
4326ca716364SKevin Wolf     /* Write back cached data to the OS even with cache=unsafe */
4327eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_os) {
4328eb489bb1SKevin Wolf         ret = bs->drv->bdrv_co_flush_to_os(bs);
4329eb489bb1SKevin Wolf         if (ret < 0) {
4330eb489bb1SKevin Wolf             return ret;
4331eb489bb1SKevin Wolf         }
4332eb489bb1SKevin Wolf     }
4333eb489bb1SKevin Wolf 
4334ca716364SKevin Wolf     /* But don't actually force it to the disk with cache=unsafe */
4335ca716364SKevin Wolf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
4336d4c82329SKevin Wolf         goto flush_parent;
4337ca716364SKevin Wolf     }
4338ca716364SKevin Wolf 
4339eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_disk) {
434029cdb251SPaolo Bonzini         ret = bs->drv->bdrv_co_flush_to_disk(bs);
434107f07615SPaolo Bonzini     } else if (bs->drv->bdrv_aio_flush) {
434207f07615SPaolo Bonzini         BlockDriverAIOCB *acb;
4343e7a8a783SKevin Wolf         CoroutineIOCompletion co = {
4344e7a8a783SKevin Wolf             .coroutine = qemu_coroutine_self(),
4345e7a8a783SKevin Wolf         };
4346e7a8a783SKevin Wolf 
434707f07615SPaolo Bonzini         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
434807f07615SPaolo Bonzini         if (acb == NULL) {
434929cdb251SPaolo Bonzini             ret = -EIO;
435007f07615SPaolo Bonzini         } else {
4351e7a8a783SKevin Wolf             qemu_coroutine_yield();
435229cdb251SPaolo Bonzini             ret = co.ret;
4353e7a8a783SKevin Wolf         }
435407f07615SPaolo Bonzini     } else {
435507f07615SPaolo Bonzini         /*
435607f07615SPaolo Bonzini          * Some block drivers always operate in either writethrough or unsafe
435707f07615SPaolo Bonzini          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
435807f07615SPaolo Bonzini          * know how the server works (because the behaviour is hardcoded or
435907f07615SPaolo Bonzini          * depends on server-side configuration), so we can't ensure that
436007f07615SPaolo Bonzini          * everything is safe on disk. Returning an error doesn't work because
436107f07615SPaolo Bonzini          * that would break guests even if the server operates in writethrough
436207f07615SPaolo Bonzini          * mode.
436307f07615SPaolo Bonzini          *
436407f07615SPaolo Bonzini          * Let's hope the user knows what he's doing.
436507f07615SPaolo Bonzini          */
436629cdb251SPaolo Bonzini         ret = 0;
436707f07615SPaolo Bonzini     }
436829cdb251SPaolo Bonzini     if (ret < 0) {
436929cdb251SPaolo Bonzini         return ret;
437029cdb251SPaolo Bonzini     }
437129cdb251SPaolo Bonzini 
437229cdb251SPaolo Bonzini     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
437329cdb251SPaolo Bonzini      * in the case of cache=unsafe, so there are no useless flushes.
437429cdb251SPaolo Bonzini      */
4375d4c82329SKevin Wolf flush_parent:
437629cdb251SPaolo Bonzini     return bdrv_co_flush(bs->file);
437707f07615SPaolo Bonzini }
437807f07615SPaolo Bonzini 
43790f15423cSAnthony Liguori void bdrv_invalidate_cache(BlockDriverState *bs)
43800f15423cSAnthony Liguori {
43810f15423cSAnthony Liguori     if (bs->drv && bs->drv->bdrv_invalidate_cache) {
43820f15423cSAnthony Liguori         bs->drv->bdrv_invalidate_cache(bs);
43830f15423cSAnthony Liguori     }
43840f15423cSAnthony Liguori }
43850f15423cSAnthony Liguori 
43860f15423cSAnthony Liguori void bdrv_invalidate_cache_all(void)
43870f15423cSAnthony Liguori {
43880f15423cSAnthony Liguori     BlockDriverState *bs;
43890f15423cSAnthony Liguori 
43900f15423cSAnthony Liguori     QTAILQ_FOREACH(bs, &bdrv_states, list) {
43910f15423cSAnthony Liguori         bdrv_invalidate_cache(bs);
43920f15423cSAnthony Liguori     }
43930f15423cSAnthony Liguori }
43940f15423cSAnthony Liguori 
439507789269SBenoît Canet void bdrv_clear_incoming_migration_all(void)
439607789269SBenoît Canet {
439707789269SBenoît Canet     BlockDriverState *bs;
439807789269SBenoît Canet 
439907789269SBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, list) {
440007789269SBenoît Canet         bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
440107789269SBenoît Canet     }
440207789269SBenoît Canet }
440307789269SBenoît Canet 
440407f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs)
440507f07615SPaolo Bonzini {
440607f07615SPaolo Bonzini     Coroutine *co;
440707f07615SPaolo Bonzini     RwCo rwco = {
440807f07615SPaolo Bonzini         .bs = bs,
440907f07615SPaolo Bonzini         .ret = NOT_DONE,
441007f07615SPaolo Bonzini     };
441107f07615SPaolo Bonzini 
441207f07615SPaolo Bonzini     if (qemu_in_coroutine()) {
441307f07615SPaolo Bonzini         /* Fast-path if already in coroutine context */
441407f07615SPaolo Bonzini         bdrv_flush_co_entry(&rwco);
441507f07615SPaolo Bonzini     } else {
441607f07615SPaolo Bonzini         co = qemu_coroutine_create(bdrv_flush_co_entry);
441707f07615SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
441807f07615SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
441907f07615SPaolo Bonzini             qemu_aio_wait();
442007f07615SPaolo Bonzini         }
442107f07615SPaolo Bonzini     }
442207f07615SPaolo Bonzini 
442307f07615SPaolo Bonzini     return rwco.ret;
442407f07615SPaolo Bonzini }
4425e7a8a783SKevin Wolf 
44264265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque)
44274265d620SPaolo Bonzini {
44284265d620SPaolo Bonzini     RwCo *rwco = opaque;
44294265d620SPaolo Bonzini 
44304265d620SPaolo Bonzini     rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
44314265d620SPaolo Bonzini }
44324265d620SPaolo Bonzini 
44334265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
44344265d620SPaolo Bonzini                                  int nb_sectors)
44354265d620SPaolo Bonzini {
44364265d620SPaolo Bonzini     if (!bs->drv) {
44374265d620SPaolo Bonzini         return -ENOMEDIUM;
44384265d620SPaolo Bonzini     } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
44394265d620SPaolo Bonzini         return -EIO;
44404265d620SPaolo Bonzini     } else if (bs->read_only) {
44414265d620SPaolo Bonzini         return -EROFS;
4442df702c9bSPaolo Bonzini     }
4443df702c9bSPaolo Bonzini 
4444df702c9bSPaolo Bonzini     if (bs->dirty_bitmap) {
44458f0720ecSPaolo Bonzini         bdrv_reset_dirty(bs, sector_num, nb_sectors);
4446df702c9bSPaolo Bonzini     }
4447df702c9bSPaolo Bonzini 
44489e8f1835SPaolo Bonzini     /* Do nothing if disabled.  */
44499e8f1835SPaolo Bonzini     if (!(bs->open_flags & BDRV_O_UNMAP)) {
44509e8f1835SPaolo Bonzini         return 0;
44519e8f1835SPaolo Bonzini     }
44529e8f1835SPaolo Bonzini 
4453df702c9bSPaolo Bonzini     if (bs->drv->bdrv_co_discard) {
44544265d620SPaolo Bonzini         return bs->drv->bdrv_co_discard(bs, sector_num, nb_sectors);
44554265d620SPaolo Bonzini     } else if (bs->drv->bdrv_aio_discard) {
44564265d620SPaolo Bonzini         BlockDriverAIOCB *acb;
44574265d620SPaolo Bonzini         CoroutineIOCompletion co = {
44584265d620SPaolo Bonzini             .coroutine = qemu_coroutine_self(),
44594265d620SPaolo Bonzini         };
44604265d620SPaolo Bonzini 
44614265d620SPaolo Bonzini         acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
44624265d620SPaolo Bonzini                                         bdrv_co_io_em_complete, &co);
44634265d620SPaolo Bonzini         if (acb == NULL) {
44644265d620SPaolo Bonzini             return -EIO;
44654265d620SPaolo Bonzini         } else {
44664265d620SPaolo Bonzini             qemu_coroutine_yield();
44674265d620SPaolo Bonzini             return co.ret;
44684265d620SPaolo Bonzini         }
44694265d620SPaolo Bonzini     } else {
44704265d620SPaolo Bonzini         return 0;
44714265d620SPaolo Bonzini     }
44724265d620SPaolo Bonzini }
44734265d620SPaolo Bonzini 
44744265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
44754265d620SPaolo Bonzini {
44764265d620SPaolo Bonzini     Coroutine *co;
44774265d620SPaolo Bonzini     RwCo rwco = {
44784265d620SPaolo Bonzini         .bs = bs,
44794265d620SPaolo Bonzini         .sector_num = sector_num,
44804265d620SPaolo Bonzini         .nb_sectors = nb_sectors,
44814265d620SPaolo Bonzini         .ret = NOT_DONE,
44824265d620SPaolo Bonzini     };
44834265d620SPaolo Bonzini 
44844265d620SPaolo Bonzini     if (qemu_in_coroutine()) {
44854265d620SPaolo Bonzini         /* Fast-path if already in coroutine context */
44864265d620SPaolo Bonzini         bdrv_discard_co_entry(&rwco);
44874265d620SPaolo Bonzini     } else {
44884265d620SPaolo Bonzini         co = qemu_coroutine_create(bdrv_discard_co_entry);
44894265d620SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
44904265d620SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
44914265d620SPaolo Bonzini             qemu_aio_wait();
44924265d620SPaolo Bonzini         }
44934265d620SPaolo Bonzini     }
44944265d620SPaolo Bonzini 
44954265d620SPaolo Bonzini     return rwco.ret;
44964265d620SPaolo Bonzini }
44974265d620SPaolo Bonzini 
4498f9f05dc5SKevin Wolf /**************************************************************/
449919cb3738Sbellard /* removable device support */
450019cb3738Sbellard 
450119cb3738Sbellard /**
450219cb3738Sbellard  * Return TRUE if the media is present
450319cb3738Sbellard  */
450419cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
450519cb3738Sbellard {
450619cb3738Sbellard     BlockDriver *drv = bs->drv;
4507a1aff5bfSMarkus Armbruster 
450819cb3738Sbellard     if (!drv)
450919cb3738Sbellard         return 0;
451019cb3738Sbellard     if (!drv->bdrv_is_inserted)
4511a1aff5bfSMarkus Armbruster         return 1;
4512a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
451319cb3738Sbellard }
451419cb3738Sbellard 
451519cb3738Sbellard /**
45168e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
45178e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
451819cb3738Sbellard  */
451919cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
452019cb3738Sbellard {
452119cb3738Sbellard     BlockDriver *drv = bs->drv;
452219cb3738Sbellard 
45238e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
45248e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
45258e49ca46SMarkus Armbruster     }
45268e49ca46SMarkus Armbruster     return -ENOTSUP;
452719cb3738Sbellard }
452819cb3738Sbellard 
452919cb3738Sbellard /**
453019cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
453119cb3738Sbellard  */
4532f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
453319cb3738Sbellard {
453419cb3738Sbellard     BlockDriver *drv = bs->drv;
453519cb3738Sbellard 
4536822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
4537822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
453819cb3738Sbellard     }
45396f382ed2SLuiz Capitulino 
45406f382ed2SLuiz Capitulino     if (bs->device_name[0] != '\0') {
45416f382ed2SLuiz Capitulino         bdrv_emit_qmp_eject_event(bs, eject_flag);
45426f382ed2SLuiz Capitulino     }
454319cb3738Sbellard }
454419cb3738Sbellard 
454519cb3738Sbellard /**
454619cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
454719cb3738Sbellard  * to eject it manually).
454819cb3738Sbellard  */
4549025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
455019cb3738Sbellard {
455119cb3738Sbellard     BlockDriver *drv = bs->drv;
455219cb3738Sbellard 
4553025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
4554b8c6d095SStefan Hajnoczi 
4555025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
4556025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
455719cb3738Sbellard     }
455819cb3738Sbellard }
4559985a03b0Sths 
4560985a03b0Sths /* needed for generic scsi interface */
4561985a03b0Sths 
4562985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
4563985a03b0Sths {
4564985a03b0Sths     BlockDriver *drv = bs->drv;
4565985a03b0Sths 
4566985a03b0Sths     if (drv && drv->bdrv_ioctl)
4567985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
4568985a03b0Sths     return -ENOTSUP;
4569985a03b0Sths }
45707d780669Saliguori 
4571221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
4572221f715dSaliguori         unsigned long int req, void *buf,
45737d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
45747d780669Saliguori {
4575221f715dSaliguori     BlockDriver *drv = bs->drv;
45767d780669Saliguori 
4577221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
4578221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
4579221f715dSaliguori     return NULL;
45807d780669Saliguori }
4581e268ca52Saliguori 
45827b6f9300SMarkus Armbruster void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
45837b6f9300SMarkus Armbruster {
45847b6f9300SMarkus Armbruster     bs->buffer_alignment = align;
45857b6f9300SMarkus Armbruster }
45867cd1e32aSlirans@il.ibm.com 
4587e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
4588e268ca52Saliguori {
4589e268ca52Saliguori     return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
4590e268ca52Saliguori }
45917cd1e32aSlirans@il.ibm.com 
4592c53b1c51SStefan Hajnoczi /*
4593c53b1c51SStefan Hajnoczi  * Check if all memory in this vector is sector aligned.
4594c53b1c51SStefan Hajnoczi  */
4595c53b1c51SStefan Hajnoczi bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
4596c53b1c51SStefan Hajnoczi {
4597c53b1c51SStefan Hajnoczi     int i;
4598c53b1c51SStefan Hajnoczi 
4599c53b1c51SStefan Hajnoczi     for (i = 0; i < qiov->niov; i++) {
4600c53b1c51SStefan Hajnoczi         if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {
4601c53b1c51SStefan Hajnoczi             return false;
4602c53b1c51SStefan Hajnoczi         }
4603c53b1c51SStefan Hajnoczi     }
4604c53b1c51SStefan Hajnoczi 
4605c53b1c51SStefan Hajnoczi     return true;
4606c53b1c51SStefan Hajnoczi }
4607c53b1c51SStefan Hajnoczi 
460850717e94SPaolo Bonzini void bdrv_set_dirty_tracking(BlockDriverState *bs, int granularity)
46097cd1e32aSlirans@il.ibm.com {
46107cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
4611a55eb92cSJan Kiszka 
461250717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
461350717e94SPaolo Bonzini 
461450717e94SPaolo Bonzini     if (granularity) {
461550717e94SPaolo Bonzini         granularity >>= BDRV_SECTOR_BITS;
461650717e94SPaolo Bonzini         assert(!bs->dirty_bitmap);
46178f0720ecSPaolo Bonzini         bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS);
461850717e94SPaolo Bonzini         bs->dirty_bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
46197cd1e32aSlirans@il.ibm.com     } else {
4620c6d22830SJan Kiszka         if (bs->dirty_bitmap) {
46218f0720ecSPaolo Bonzini             hbitmap_free(bs->dirty_bitmap);
4622c6d22830SJan Kiszka             bs->dirty_bitmap = NULL;
46237cd1e32aSlirans@il.ibm.com         }
46247cd1e32aSlirans@il.ibm.com     }
46257cd1e32aSlirans@il.ibm.com }
46267cd1e32aSlirans@il.ibm.com 
46277cd1e32aSlirans@il.ibm.com int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
46287cd1e32aSlirans@il.ibm.com {
46298f0720ecSPaolo Bonzini     if (bs->dirty_bitmap) {
46308f0720ecSPaolo Bonzini         return hbitmap_get(bs->dirty_bitmap, sector);
46317cd1e32aSlirans@il.ibm.com     } else {
46327cd1e32aSlirans@il.ibm.com         return 0;
46337cd1e32aSlirans@il.ibm.com     }
46347cd1e32aSlirans@il.ibm.com }
46357cd1e32aSlirans@il.ibm.com 
46368f0720ecSPaolo Bonzini void bdrv_dirty_iter_init(BlockDriverState *bs, HBitmapIter *hbi)
46371755da16SPaolo Bonzini {
46388f0720ecSPaolo Bonzini     hbitmap_iter_init(hbi, bs->dirty_bitmap, 0);
46391755da16SPaolo Bonzini }
46401755da16SPaolo Bonzini 
46411755da16SPaolo Bonzini void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
46421755da16SPaolo Bonzini                     int nr_sectors)
46431755da16SPaolo Bonzini {
46448f0720ecSPaolo Bonzini     hbitmap_set(bs->dirty_bitmap, cur_sector, nr_sectors);
46451755da16SPaolo Bonzini }
46461755da16SPaolo Bonzini 
46477cd1e32aSlirans@il.ibm.com void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
46487cd1e32aSlirans@il.ibm.com                       int nr_sectors)
46497cd1e32aSlirans@il.ibm.com {
46508f0720ecSPaolo Bonzini     hbitmap_reset(bs->dirty_bitmap, cur_sector, nr_sectors);
46517cd1e32aSlirans@il.ibm.com }
4652aaa0eb75SLiran Schour 
4653aaa0eb75SLiran Schour int64_t bdrv_get_dirty_count(BlockDriverState *bs)
4654aaa0eb75SLiran Schour {
46558f0720ecSPaolo Bonzini     if (bs->dirty_bitmap) {
4656acc906c6SPaolo Bonzini         return hbitmap_count(bs->dirty_bitmap);
46578f0720ecSPaolo Bonzini     } else {
46588f0720ecSPaolo Bonzini         return 0;
46598f0720ecSPaolo Bonzini     }
4660aaa0eb75SLiran Schour }
4661f88e1a42SJes Sorensen 
4662db593f25SMarcelo Tosatti void bdrv_set_in_use(BlockDriverState *bs, int in_use)
4663db593f25SMarcelo Tosatti {
4664db593f25SMarcelo Tosatti     assert(bs->in_use != in_use);
4665db593f25SMarcelo Tosatti     bs->in_use = in_use;
4666db593f25SMarcelo Tosatti }
4667db593f25SMarcelo Tosatti 
4668db593f25SMarcelo Tosatti int bdrv_in_use(BlockDriverState *bs)
4669db593f25SMarcelo Tosatti {
4670db593f25SMarcelo Tosatti     return bs->in_use;
4671db593f25SMarcelo Tosatti }
4672db593f25SMarcelo Tosatti 
467328a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
467428a7282aSLuiz Capitulino {
4675d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
467658e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
467728a7282aSLuiz Capitulino }
467828a7282aSLuiz Capitulino 
467928a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
468028a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
468128a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
468228a7282aSLuiz Capitulino {
4683d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
468492aa5c6dSPaolo Bonzini            (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
468592aa5c6dSPaolo Bonzini             bs->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
468692aa5c6dSPaolo Bonzini             bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
468728a7282aSLuiz Capitulino }
468828a7282aSLuiz Capitulino 
468928a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
469028a7282aSLuiz Capitulino {
4691d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
469228a7282aSLuiz Capitulino }
469328a7282aSLuiz Capitulino 
469428a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
469528a7282aSLuiz Capitulino {
469628a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
469758e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
46983bd293c3SPaolo Bonzini         if (bs->job) {
46993bd293c3SPaolo Bonzini             block_job_iostatus_reset(bs->job);
47003bd293c3SPaolo Bonzini         }
470128a7282aSLuiz Capitulino     }
470228a7282aSLuiz Capitulino }
470328a7282aSLuiz Capitulino 
470428a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
470528a7282aSLuiz Capitulino {
47063e1caa5fSPaolo Bonzini     assert(bdrv_iostatus_is_enabled(bs));
47073e1caa5fSPaolo Bonzini     if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
470858e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
470958e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
471028a7282aSLuiz Capitulino     }
471128a7282aSLuiz Capitulino }
471228a7282aSLuiz Capitulino 
4713a597e79cSChristoph Hellwig void
4714a597e79cSChristoph Hellwig bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
4715a597e79cSChristoph Hellwig         enum BlockAcctType type)
4716a597e79cSChristoph Hellwig {
4717a597e79cSChristoph Hellwig     assert(type < BDRV_MAX_IOTYPE);
4718a597e79cSChristoph Hellwig 
4719a597e79cSChristoph Hellwig     cookie->bytes = bytes;
4720c488c7f6SChristoph Hellwig     cookie->start_time_ns = get_clock();
4721a597e79cSChristoph Hellwig     cookie->type = type;
4722a597e79cSChristoph Hellwig }
4723a597e79cSChristoph Hellwig 
4724a597e79cSChristoph Hellwig void
4725a597e79cSChristoph Hellwig bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
4726a597e79cSChristoph Hellwig {
4727a597e79cSChristoph Hellwig     assert(cookie->type < BDRV_MAX_IOTYPE);
4728a597e79cSChristoph Hellwig 
4729a597e79cSChristoph Hellwig     bs->nr_bytes[cookie->type] += cookie->bytes;
4730a597e79cSChristoph Hellwig     bs->nr_ops[cookie->type]++;
4731c488c7f6SChristoph Hellwig     bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
4732a597e79cSChristoph Hellwig }
4733a597e79cSChristoph Hellwig 
4734d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
4735f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
4736f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
4737f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
4738f88e1a42SJes Sorensen {
4739f88e1a42SJes Sorensen     QEMUOptionParameter *param = NULL, *create_options = NULL;
4740d220894eSKevin Wolf     QEMUOptionParameter *backing_fmt, *backing_file, *size;
4741f88e1a42SJes Sorensen     BlockDriverState *bs = NULL;
4742f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
474396df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
4744f88e1a42SJes Sorensen     int ret = 0;
4745f88e1a42SJes Sorensen 
4746f88e1a42SJes Sorensen     /* Find driver and parse its options */
4747f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
4748f88e1a42SJes Sorensen     if (!drv) {
474971c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
4750d92ada22SLuiz Capitulino         return;
4751f88e1a42SJes Sorensen     }
4752f88e1a42SJes Sorensen 
4753f88e1a42SJes Sorensen     proto_drv = bdrv_find_protocol(filename);
4754f88e1a42SJes Sorensen     if (!proto_drv) {
475571c79813SLuiz Capitulino         error_setg(errp, "Unknown protocol '%s'", filename);
4756d92ada22SLuiz Capitulino         return;
4757f88e1a42SJes Sorensen     }
4758f88e1a42SJes Sorensen 
4759f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
4760f88e1a42SJes Sorensen                                               drv->create_options);
4761f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
4762f88e1a42SJes Sorensen                                               proto_drv->create_options);
4763f88e1a42SJes Sorensen 
4764f88e1a42SJes Sorensen     /* Create parameter list with default values */
4765f88e1a42SJes Sorensen     param = parse_option_parameters("", create_options, param);
4766f88e1a42SJes Sorensen 
4767f88e1a42SJes Sorensen     set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
4768f88e1a42SJes Sorensen 
4769f88e1a42SJes Sorensen     /* Parse -o options */
4770f88e1a42SJes Sorensen     if (options) {
4771f88e1a42SJes Sorensen         param = parse_option_parameters(options, create_options, param);
4772f88e1a42SJes Sorensen         if (param == NULL) {
477371c79813SLuiz Capitulino             error_setg(errp, "Invalid options for file format '%s'.", fmt);
4774f88e1a42SJes Sorensen             goto out;
4775f88e1a42SJes Sorensen         }
4776f88e1a42SJes Sorensen     }
4777f88e1a42SJes Sorensen 
4778f88e1a42SJes Sorensen     if (base_filename) {
4779f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
4780f88e1a42SJes Sorensen                                  base_filename)) {
478171c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
478271c79813SLuiz Capitulino                        fmt);
4783f88e1a42SJes Sorensen             goto out;
4784f88e1a42SJes Sorensen         }
4785f88e1a42SJes Sorensen     }
4786f88e1a42SJes Sorensen 
4787f88e1a42SJes Sorensen     if (base_fmt) {
4788f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
478971c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
479071c79813SLuiz Capitulino                              "format '%s'", fmt);
4791f88e1a42SJes Sorensen             goto out;
4792f88e1a42SJes Sorensen         }
4793f88e1a42SJes Sorensen     }
4794f88e1a42SJes Sorensen 
4795792da93aSJes Sorensen     backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
4796792da93aSJes Sorensen     if (backing_file && backing_file->value.s) {
4797792da93aSJes Sorensen         if (!strcmp(filename, backing_file->value.s)) {
479871c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
479971c79813SLuiz Capitulino                              "same filename as the backing file");
4800792da93aSJes Sorensen             goto out;
4801792da93aSJes Sorensen         }
4802792da93aSJes Sorensen     }
4803792da93aSJes Sorensen 
4804f88e1a42SJes Sorensen     backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
4805f88e1a42SJes Sorensen     if (backing_fmt && backing_fmt->value.s) {
480696df67d1SStefan Hajnoczi         backing_drv = bdrv_find_format(backing_fmt->value.s);
480796df67d1SStefan Hajnoczi         if (!backing_drv) {
480871c79813SLuiz Capitulino             error_setg(errp, "Unknown backing file format '%s'",
480971c79813SLuiz Capitulino                        backing_fmt->value.s);
4810f88e1a42SJes Sorensen             goto out;
4811f88e1a42SJes Sorensen         }
4812f88e1a42SJes Sorensen     }
4813f88e1a42SJes Sorensen 
4814f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
4815f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
4816d220894eSKevin Wolf     size = get_option_parameter(param, BLOCK_OPT_SIZE);
4817d220894eSKevin Wolf     if (size && size->value.n == -1) {
4818f88e1a42SJes Sorensen         if (backing_file && backing_file->value.s) {
4819f88e1a42SJes Sorensen             uint64_t size;
4820f88e1a42SJes Sorensen             char buf[32];
482163090dacSPaolo Bonzini             int back_flags;
482263090dacSPaolo Bonzini 
482363090dacSPaolo Bonzini             /* backing files always opened read-only */
482463090dacSPaolo Bonzini             back_flags =
482563090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
4826f88e1a42SJes Sorensen 
4827f88e1a42SJes Sorensen             bs = bdrv_new("");
4828f88e1a42SJes Sorensen 
4829de9c0cecSKevin Wolf             ret = bdrv_open(bs, backing_file->value.s, NULL, back_flags,
4830de9c0cecSKevin Wolf                             backing_drv);
4831f88e1a42SJes Sorensen             if (ret < 0) {
483271c79813SLuiz Capitulino                 error_setg_errno(errp, -ret, "Could not open '%s'",
483371c79813SLuiz Capitulino                                  backing_file->value.s);
4834f88e1a42SJes Sorensen                 goto out;
4835f88e1a42SJes Sorensen             }
4836f88e1a42SJes Sorensen             bdrv_get_geometry(bs, &size);
4837f88e1a42SJes Sorensen             size *= 512;
4838f88e1a42SJes Sorensen 
4839f88e1a42SJes Sorensen             snprintf(buf, sizeof(buf), "%" PRId64, size);
4840f88e1a42SJes Sorensen             set_option_parameter(param, BLOCK_OPT_SIZE, buf);
4841f88e1a42SJes Sorensen         } else {
484271c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
4843f88e1a42SJes Sorensen             goto out;
4844f88e1a42SJes Sorensen         }
4845f88e1a42SJes Sorensen     }
4846f88e1a42SJes Sorensen 
4847f382d43aSMiroslav Rezanina     if (!quiet) {
4848f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
4849f88e1a42SJes Sorensen         print_option_parameters(param);
4850f88e1a42SJes Sorensen         puts("");
4851f382d43aSMiroslav Rezanina     }
4852f88e1a42SJes Sorensen     ret = bdrv_create(drv, filename, param);
4853f88e1a42SJes Sorensen     if (ret < 0) {
4854f88e1a42SJes Sorensen         if (ret == -ENOTSUP) {
485571c79813SLuiz Capitulino             error_setg(errp,"Formatting or formatting option not supported for "
485671c79813SLuiz Capitulino                             "file format '%s'", fmt);
4857f88e1a42SJes Sorensen         } else if (ret == -EFBIG) {
485871c79813SLuiz Capitulino             error_setg(errp, "The image size is too large for file format '%s'",
485971c79813SLuiz Capitulino                        fmt);
4860f88e1a42SJes Sorensen         } else {
486171c79813SLuiz Capitulino             error_setg(errp, "%s: error while creating %s: %s", filename, fmt,
486271c79813SLuiz Capitulino                        strerror(-ret));
4863f88e1a42SJes Sorensen         }
4864f88e1a42SJes Sorensen     }
4865f88e1a42SJes Sorensen 
4866f88e1a42SJes Sorensen out:
4867f88e1a42SJes Sorensen     free_option_parameters(create_options);
4868f88e1a42SJes Sorensen     free_option_parameters(param);
4869f88e1a42SJes Sorensen 
4870f88e1a42SJes Sorensen     if (bs) {
4871f88e1a42SJes Sorensen         bdrv_delete(bs);
4872f88e1a42SJes Sorensen     }
4873f88e1a42SJes Sorensen }
487485d126f3SStefan Hajnoczi 
487585d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
487685d126f3SStefan Hajnoczi {
487785d126f3SStefan Hajnoczi     /* Currently BlockDriverState always uses the main loop AioContext */
487885d126f3SStefan Hajnoczi     return qemu_get_aio_context();
487985d126f3SStefan Hajnoczi }
4880