xref: /openbmc/qemu/block.c (revision 2f0c9fe64c6a2887047b7eab05cd85b2643234c8)
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"
27376253ecSaliguori #include "monitor.h"
28ea2384d3Sbellard #include "block_int.h"
29*2f0c9fe6SPaolo Bonzini #include "blockjob.h"
305efa9d5aSAnthony Liguori #include "module.h"
31f795e743SLuiz Capitulino #include "qjson.h"
3268485420SKevin Wolf #include "qemu-coroutine.h"
33b2023818SLuiz Capitulino #include "qmp-commands.h"
340563e191SZhi Yong Wu #include "qemu-timer.h"
35fc01f7e7Sbellard 
3671e72a19SJuan Quintela #ifdef CONFIG_BSD
377674e7bfSbellard #include <sys/types.h>
387674e7bfSbellard #include <sys/stat.h>
397674e7bfSbellard #include <sys/ioctl.h>
4072cf2d4fSBlue Swirl #include <sys/queue.h>
41c5e97233Sblueswir1 #ifndef __DragonFly__
427674e7bfSbellard #include <sys/disk.h>
437674e7bfSbellard #endif
44c5e97233Sblueswir1 #endif
457674e7bfSbellard 
4649dc768dSaliguori #ifdef _WIN32
4749dc768dSaliguori #include <windows.h>
4849dc768dSaliguori #endif
4949dc768dSaliguori 
501c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
511c9805a3SStefan Hajnoczi 
52470c0504SStefan Hajnoczi typedef enum {
53470c0504SStefan Hajnoczi     BDRV_REQ_COPY_ON_READ = 0x1,
54f08f2ddaSStefan Hajnoczi     BDRV_REQ_ZERO_WRITE   = 0x2,
55470c0504SStefan Hajnoczi } BdrvRequestFlags;
56470c0504SStefan Hajnoczi 
577d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
58f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
59f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
60c87c0672Saliguori         BlockDriverCompletionFunc *cb, void *opaque);
61f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
62f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
63ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque);
64f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
65f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
66f9f05dc5SKevin Wolf                                          QEMUIOVector *iov);
67f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
68f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
69f9f05dc5SKevin Wolf                                          QEMUIOVector *iov);
70c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
71470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
72470c0504SStefan Hajnoczi     BdrvRequestFlags flags);
731c9805a3SStefan Hajnoczi static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
74f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
75f08f2ddaSStefan Hajnoczi     BdrvRequestFlags flags);
76b2a61371SStefan Hajnoczi static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
77b2a61371SStefan Hajnoczi                                                int64_t sector_num,
78b2a61371SStefan Hajnoczi                                                QEMUIOVector *qiov,
79b2a61371SStefan Hajnoczi                                                int nb_sectors,
80b2a61371SStefan Hajnoczi                                                BlockDriverCompletionFunc *cb,
81b2a61371SStefan Hajnoczi                                                void *opaque,
828c5873d6SStefan Hajnoczi                                                bool is_write);
83b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque);
84621f0589SKevin Wolf static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
85621f0589SKevin Wolf     int64_t sector_num, int nb_sectors);
86ec530c81Sbellard 
8798f90dbaSZhi Yong Wu static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
8898f90dbaSZhi Yong Wu         bool is_write, double elapsed_time, uint64_t *wait);
8998f90dbaSZhi Yong Wu static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
9098f90dbaSZhi Yong Wu         double elapsed_time, uint64_t *wait);
9198f90dbaSZhi Yong Wu static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
9298f90dbaSZhi Yong Wu         bool is_write, int64_t *wait);
9398f90dbaSZhi Yong Wu 
941b7bdbc1SStefan Hajnoczi static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
951b7bdbc1SStefan Hajnoczi     QTAILQ_HEAD_INITIALIZER(bdrv_states);
967ee930d0Sblueswir1 
978a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
988a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
99ea2384d3Sbellard 
100f9092b10SMarkus Armbruster /* The device to use for VM snapshots */
101f9092b10SMarkus Armbruster static BlockDriverState *bs_snapshots;
102f9092b10SMarkus Armbruster 
103eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
104eb852011SMarkus Armbruster static int use_bdrv_whitelist;
105eb852011SMarkus Armbruster 
1069e0b22f4SStefan Hajnoczi #ifdef _WIN32
1079e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
1089e0b22f4SStefan Hajnoczi {
1099e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
1109e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
1119e0b22f4SStefan Hajnoczi             filename[1] == ':');
1129e0b22f4SStefan Hajnoczi }
1139e0b22f4SStefan Hajnoczi 
1149e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
1159e0b22f4SStefan Hajnoczi {
1169e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
1179e0b22f4SStefan Hajnoczi         filename[2] == '\0')
1189e0b22f4SStefan Hajnoczi         return 1;
1199e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
1209e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
1219e0b22f4SStefan Hajnoczi         return 1;
1229e0b22f4SStefan Hajnoczi     return 0;
1239e0b22f4SStefan Hajnoczi }
1249e0b22f4SStefan Hajnoczi #endif
1259e0b22f4SStefan Hajnoczi 
1260563e191SZhi Yong Wu /* throttling disk I/O limits */
12798f90dbaSZhi Yong Wu void bdrv_io_limits_disable(BlockDriverState *bs)
12898f90dbaSZhi Yong Wu {
12998f90dbaSZhi Yong Wu     bs->io_limits_enabled = false;
13098f90dbaSZhi Yong Wu 
13198f90dbaSZhi Yong Wu     while (qemu_co_queue_next(&bs->throttled_reqs));
13298f90dbaSZhi Yong Wu 
13398f90dbaSZhi Yong Wu     if (bs->block_timer) {
13498f90dbaSZhi Yong Wu         qemu_del_timer(bs->block_timer);
13598f90dbaSZhi Yong Wu         qemu_free_timer(bs->block_timer);
13698f90dbaSZhi Yong Wu         bs->block_timer = NULL;
13798f90dbaSZhi Yong Wu     }
13898f90dbaSZhi Yong Wu 
13998f90dbaSZhi Yong Wu     bs->slice_start = 0;
14098f90dbaSZhi Yong Wu     bs->slice_end   = 0;
14198f90dbaSZhi Yong Wu     bs->slice_time  = 0;
14298f90dbaSZhi Yong Wu     memset(&bs->io_base, 0, sizeof(bs->io_base));
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->slice_time  = 5 * BLOCK_IO_SLICE_TIME;
1570563e191SZhi Yong Wu     bs->slice_start = qemu_get_clock_ns(vm_clock);
1580563e191SZhi Yong Wu     bs->slice_end   = bs->slice_start + bs->slice_time;
1590563e191SZhi Yong Wu     memset(&bs->io_base, 0, sizeof(bs->io_base));
1600563e191SZhi Yong Wu     bs->io_limits_enabled = true;
1610563e191SZhi Yong Wu }
1620563e191SZhi Yong Wu 
1630563e191SZhi Yong Wu bool bdrv_io_limits_enabled(BlockDriverState *bs)
1640563e191SZhi Yong Wu {
1650563e191SZhi Yong Wu     BlockIOLimit *io_limits = &bs->io_limits;
1660563e191SZhi Yong Wu     return io_limits->bps[BLOCK_IO_LIMIT_READ]
1670563e191SZhi Yong Wu          || io_limits->bps[BLOCK_IO_LIMIT_WRITE]
1680563e191SZhi Yong Wu          || io_limits->bps[BLOCK_IO_LIMIT_TOTAL]
1690563e191SZhi Yong Wu          || io_limits->iops[BLOCK_IO_LIMIT_READ]
1700563e191SZhi Yong Wu          || io_limits->iops[BLOCK_IO_LIMIT_WRITE]
1710563e191SZhi Yong Wu          || io_limits->iops[BLOCK_IO_LIMIT_TOTAL];
1720563e191SZhi Yong Wu }
1730563e191SZhi Yong Wu 
17498f90dbaSZhi Yong Wu static void bdrv_io_limits_intercept(BlockDriverState *bs,
17598f90dbaSZhi Yong Wu                                      bool is_write, int nb_sectors)
17698f90dbaSZhi Yong Wu {
17798f90dbaSZhi Yong Wu     int64_t wait_time = -1;
17898f90dbaSZhi Yong Wu 
17998f90dbaSZhi Yong Wu     if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
18098f90dbaSZhi Yong Wu         qemu_co_queue_wait(&bs->throttled_reqs);
18198f90dbaSZhi Yong Wu     }
18298f90dbaSZhi Yong Wu 
18398f90dbaSZhi Yong Wu     /* In fact, we hope to keep each request's timing, in FIFO mode. The next
18498f90dbaSZhi Yong Wu      * throttled requests will not be dequeued until the current request is
18598f90dbaSZhi Yong Wu      * allowed to be serviced. So if the current request still exceeds the
18698f90dbaSZhi Yong Wu      * limits, it will be inserted to the head. All requests followed it will
18798f90dbaSZhi Yong Wu      * be still in throttled_reqs queue.
18898f90dbaSZhi Yong Wu      */
18998f90dbaSZhi Yong Wu 
19098f90dbaSZhi Yong Wu     while (bdrv_exceed_io_limits(bs, nb_sectors, is_write, &wait_time)) {
19198f90dbaSZhi Yong Wu         qemu_mod_timer(bs->block_timer,
19298f90dbaSZhi Yong Wu                        wait_time + qemu_get_clock_ns(vm_clock));
19398f90dbaSZhi Yong Wu         qemu_co_queue_wait_insert_head(&bs->throttled_reqs);
19498f90dbaSZhi Yong Wu     }
19598f90dbaSZhi Yong Wu 
19698f90dbaSZhi Yong Wu     qemu_co_queue_next(&bs->throttled_reqs);
19798f90dbaSZhi Yong Wu }
19898f90dbaSZhi Yong Wu 
1999e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
2009e0b22f4SStefan Hajnoczi static int path_has_protocol(const char *path)
2019e0b22f4SStefan Hajnoczi {
202947995c0SPaolo Bonzini     const char *p;
203947995c0SPaolo Bonzini 
2049e0b22f4SStefan Hajnoczi #ifdef _WIN32
2059e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
2069e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
2079e0b22f4SStefan Hajnoczi         return 0;
2089e0b22f4SStefan Hajnoczi     }
209947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
210947995c0SPaolo Bonzini #else
211947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
2129e0b22f4SStefan Hajnoczi #endif
2139e0b22f4SStefan Hajnoczi 
214947995c0SPaolo Bonzini     return *p == ':';
2159e0b22f4SStefan Hajnoczi }
2169e0b22f4SStefan Hajnoczi 
21783f64091Sbellard int path_is_absolute(const char *path)
21883f64091Sbellard {
21921664424Sbellard #ifdef _WIN32
22021664424Sbellard     /* specific case for names like: "\\.\d:" */
221f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
22221664424Sbellard         return 1;
223f53f4da9SPaolo Bonzini     }
224f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
2253b9f94e1Sbellard #else
226f53f4da9SPaolo Bonzini     return (*path == '/');
2273b9f94e1Sbellard #endif
22883f64091Sbellard }
22983f64091Sbellard 
23083f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
23183f64091Sbellard    path to it by considering it is relative to base_path. URL are
23283f64091Sbellard    supported. */
23383f64091Sbellard void path_combine(char *dest, int dest_size,
23483f64091Sbellard                   const char *base_path,
23583f64091Sbellard                   const char *filename)
23683f64091Sbellard {
23783f64091Sbellard     const char *p, *p1;
23883f64091Sbellard     int len;
23983f64091Sbellard 
24083f64091Sbellard     if (dest_size <= 0)
24183f64091Sbellard         return;
24283f64091Sbellard     if (path_is_absolute(filename)) {
24383f64091Sbellard         pstrcpy(dest, dest_size, filename);
24483f64091Sbellard     } else {
24583f64091Sbellard         p = strchr(base_path, ':');
24683f64091Sbellard         if (p)
24783f64091Sbellard             p++;
24883f64091Sbellard         else
24983f64091Sbellard             p = base_path;
2503b9f94e1Sbellard         p1 = strrchr(base_path, '/');
2513b9f94e1Sbellard #ifdef _WIN32
2523b9f94e1Sbellard         {
2533b9f94e1Sbellard             const char *p2;
2543b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
2553b9f94e1Sbellard             if (!p1 || p2 > p1)
2563b9f94e1Sbellard                 p1 = p2;
2573b9f94e1Sbellard         }
2583b9f94e1Sbellard #endif
25983f64091Sbellard         if (p1)
26083f64091Sbellard             p1++;
26183f64091Sbellard         else
26283f64091Sbellard             p1 = base_path;
26383f64091Sbellard         if (p1 > p)
26483f64091Sbellard             p = p1;
26583f64091Sbellard         len = p - base_path;
26683f64091Sbellard         if (len > dest_size - 1)
26783f64091Sbellard             len = dest_size - 1;
26883f64091Sbellard         memcpy(dest, base_path, len);
26983f64091Sbellard         dest[len] = '\0';
27083f64091Sbellard         pstrcat(dest, dest_size, filename);
27183f64091Sbellard     }
27283f64091Sbellard }
27383f64091Sbellard 
274dc5a1371SPaolo Bonzini void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
275dc5a1371SPaolo Bonzini {
276dc5a1371SPaolo Bonzini     if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
277dc5a1371SPaolo Bonzini         pstrcpy(dest, sz, bs->backing_file);
278dc5a1371SPaolo Bonzini     } else {
279dc5a1371SPaolo Bonzini         path_combine(dest, sz, bs->filename, bs->backing_file);
280dc5a1371SPaolo Bonzini     }
281dc5a1371SPaolo Bonzini }
282dc5a1371SPaolo Bonzini 
2835efa9d5aSAnthony Liguori void bdrv_register(BlockDriver *bdrv)
284ea2384d3Sbellard {
2858c5873d6SStefan Hajnoczi     /* Block drivers without coroutine functions need emulation */
2868c5873d6SStefan Hajnoczi     if (!bdrv->bdrv_co_readv) {
287f9f05dc5SKevin Wolf         bdrv->bdrv_co_readv = bdrv_co_readv_em;
288f9f05dc5SKevin Wolf         bdrv->bdrv_co_writev = bdrv_co_writev_em;
289f9f05dc5SKevin Wolf 
290f8c35c1dSStefan Hajnoczi         /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
291f8c35c1dSStefan Hajnoczi          * the block driver lacks aio we need to emulate that too.
292f8c35c1dSStefan Hajnoczi          */
293f9f05dc5SKevin Wolf         if (!bdrv->bdrv_aio_readv) {
29483f64091Sbellard             /* add AIO emulation layer */
295f141eafeSaliguori             bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
296f141eafeSaliguori             bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
29783f64091Sbellard         }
298f9f05dc5SKevin Wolf     }
299b2e12bc6SChristoph Hellwig 
3008a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
301ea2384d3Sbellard }
302b338082bSbellard 
303b338082bSbellard /* create a new block device (by default it is empty) */
304b338082bSbellard BlockDriverState *bdrv_new(const char *device_name)
305fc01f7e7Sbellard {
3061b7bdbc1SStefan Hajnoczi     BlockDriverState *bs;
307b338082bSbellard 
3087267c094SAnthony Liguori     bs = g_malloc0(sizeof(BlockDriverState));
309b338082bSbellard     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
310ea2384d3Sbellard     if (device_name[0] != '\0') {
3111b7bdbc1SStefan Hajnoczi         QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
312ea2384d3Sbellard     }
31328a7282aSLuiz Capitulino     bdrv_iostatus_disable(bs);
314b338082bSbellard     return bs;
315b338082bSbellard }
316b338082bSbellard 
317ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
318ea2384d3Sbellard {
319ea2384d3Sbellard     BlockDriver *drv1;
3208a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
3218a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
322ea2384d3Sbellard             return drv1;
323ea2384d3Sbellard         }
3248a22f02aSStefan Hajnoczi     }
325ea2384d3Sbellard     return NULL;
326ea2384d3Sbellard }
327ea2384d3Sbellard 
328eb852011SMarkus Armbruster static int bdrv_is_whitelisted(BlockDriver *drv)
329eb852011SMarkus Armbruster {
330eb852011SMarkus Armbruster     static const char *whitelist[] = {
331eb852011SMarkus Armbruster         CONFIG_BDRV_WHITELIST
332eb852011SMarkus Armbruster     };
333eb852011SMarkus Armbruster     const char **p;
334eb852011SMarkus Armbruster 
335eb852011SMarkus Armbruster     if (!whitelist[0])
336eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
337eb852011SMarkus Armbruster 
338eb852011SMarkus Armbruster     for (p = whitelist; *p; p++) {
339eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
340eb852011SMarkus Armbruster             return 1;
341eb852011SMarkus Armbruster         }
342eb852011SMarkus Armbruster     }
343eb852011SMarkus Armbruster     return 0;
344eb852011SMarkus Armbruster }
345eb852011SMarkus Armbruster 
346eb852011SMarkus Armbruster BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
347eb852011SMarkus Armbruster {
348eb852011SMarkus Armbruster     BlockDriver *drv = bdrv_find_format(format_name);
349eb852011SMarkus Armbruster     return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
350eb852011SMarkus Armbruster }
351eb852011SMarkus Armbruster 
3525b7e1542SZhi Yong Wu typedef struct CreateCo {
3535b7e1542SZhi Yong Wu     BlockDriver *drv;
3545b7e1542SZhi Yong Wu     char *filename;
3555b7e1542SZhi Yong Wu     QEMUOptionParameter *options;
3565b7e1542SZhi Yong Wu     int ret;
3575b7e1542SZhi Yong Wu } CreateCo;
3585b7e1542SZhi Yong Wu 
3595b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
3605b7e1542SZhi Yong Wu {
3615b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
3625b7e1542SZhi Yong Wu     assert(cco->drv);
3635b7e1542SZhi Yong Wu 
3645b7e1542SZhi Yong Wu     cco->ret = cco->drv->bdrv_create(cco->filename, cco->options);
3655b7e1542SZhi Yong Wu }
3665b7e1542SZhi Yong Wu 
3670e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
3680e7e1989SKevin Wolf     QEMUOptionParameter *options)
369ea2384d3Sbellard {
3705b7e1542SZhi Yong Wu     int ret;
3710e7e1989SKevin Wolf 
3725b7e1542SZhi Yong Wu     Coroutine *co;
3735b7e1542SZhi Yong Wu     CreateCo cco = {
3745b7e1542SZhi Yong Wu         .drv = drv,
3755b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
3765b7e1542SZhi Yong Wu         .options = options,
3775b7e1542SZhi Yong Wu         .ret = NOT_DONE,
3785b7e1542SZhi Yong Wu     };
3795b7e1542SZhi Yong Wu 
3805b7e1542SZhi Yong Wu     if (!drv->bdrv_create) {
3815b7e1542SZhi Yong Wu         return -ENOTSUP;
3825b7e1542SZhi Yong Wu     }
3835b7e1542SZhi Yong Wu 
3845b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
3855b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
3865b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
3875b7e1542SZhi Yong Wu     } else {
3885b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
3895b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
3905b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
3915b7e1542SZhi Yong Wu             qemu_aio_wait();
3925b7e1542SZhi Yong Wu         }
3935b7e1542SZhi Yong Wu     }
3945b7e1542SZhi Yong Wu 
3955b7e1542SZhi Yong Wu     ret = cco.ret;
3965b7e1542SZhi Yong Wu     g_free(cco.filename);
3975b7e1542SZhi Yong Wu 
3985b7e1542SZhi Yong Wu     return ret;
399ea2384d3Sbellard }
400ea2384d3Sbellard 
40184a12e66SChristoph Hellwig int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
40284a12e66SChristoph Hellwig {
40384a12e66SChristoph Hellwig     BlockDriver *drv;
40484a12e66SChristoph Hellwig 
405b50cbabcSMORITA Kazutaka     drv = bdrv_find_protocol(filename);
40684a12e66SChristoph Hellwig     if (drv == NULL) {
40716905d71SStefan Hajnoczi         return -ENOENT;
40884a12e66SChristoph Hellwig     }
40984a12e66SChristoph Hellwig 
41084a12e66SChristoph Hellwig     return bdrv_create(drv, filename, options);
41184a12e66SChristoph Hellwig }
41284a12e66SChristoph Hellwig 
413eba25057SJim Meyering /*
414eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
415eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
416eba25057SJim Meyering  */
417eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
418eba25057SJim Meyering {
419d5249393Sbellard #ifdef _WIN32
4203b9f94e1Sbellard     char temp_dir[MAX_PATH];
421eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
422eba25057SJim Meyering        have length MAX_PATH or greater.  */
423eba25057SJim Meyering     assert(size >= MAX_PATH);
424eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
425eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
426eba25057SJim Meyering             ? 0 : -GetLastError());
427d5249393Sbellard #else
428ea2384d3Sbellard     int fd;
4297ccfb2ebSblueswir1     const char *tmpdir;
4300badc1eeSaurel32     tmpdir = getenv("TMPDIR");
4310badc1eeSaurel32     if (!tmpdir)
4320badc1eeSaurel32         tmpdir = "/tmp";
433eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
434eba25057SJim Meyering         return -EOVERFLOW;
435ea2384d3Sbellard     }
436eba25057SJim Meyering     fd = mkstemp(filename);
437fe235a06SDunrong Huang     if (fd < 0) {
438fe235a06SDunrong Huang         return -errno;
439fe235a06SDunrong Huang     }
440fe235a06SDunrong Huang     if (close(fd) != 0) {
441fe235a06SDunrong Huang         unlink(filename);
442eba25057SJim Meyering         return -errno;
443eba25057SJim Meyering     }
444eba25057SJim Meyering     return 0;
445d5249393Sbellard #endif
446eba25057SJim Meyering }
447ea2384d3Sbellard 
448f3a5d3f8SChristoph Hellwig /*
449f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
450f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
451f3a5d3f8SChristoph Hellwig  */
452f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
453f3a5d3f8SChristoph Hellwig {
454508c7cb3SChristoph Hellwig     int score_max = 0, score;
455508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
456f3a5d3f8SChristoph Hellwig 
4578a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
458508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
459508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
460508c7cb3SChristoph Hellwig             if (score > score_max) {
461508c7cb3SChristoph Hellwig                 score_max = score;
462508c7cb3SChristoph Hellwig                 drv = d;
463f3a5d3f8SChristoph Hellwig             }
464508c7cb3SChristoph Hellwig         }
465f3a5d3f8SChristoph Hellwig     }
466f3a5d3f8SChristoph Hellwig 
467508c7cb3SChristoph Hellwig     return drv;
468f3a5d3f8SChristoph Hellwig }
469f3a5d3f8SChristoph Hellwig 
470b50cbabcSMORITA Kazutaka BlockDriver *bdrv_find_protocol(const char *filename)
47184a12e66SChristoph Hellwig {
47284a12e66SChristoph Hellwig     BlockDriver *drv1;
47384a12e66SChristoph Hellwig     char protocol[128];
47484a12e66SChristoph Hellwig     int len;
47584a12e66SChristoph Hellwig     const char *p;
47684a12e66SChristoph Hellwig 
47766f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
47866f82ceeSKevin Wolf 
47939508e7aSChristoph Hellwig     /*
48039508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
48139508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
48239508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
48339508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
48439508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
48539508e7aSChristoph Hellwig      */
48684a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
48739508e7aSChristoph Hellwig     if (drv1) {
48884a12e66SChristoph Hellwig         return drv1;
48984a12e66SChristoph Hellwig     }
49039508e7aSChristoph Hellwig 
4919e0b22f4SStefan Hajnoczi     if (!path_has_protocol(filename)) {
49239508e7aSChristoph Hellwig         return bdrv_find_format("file");
49339508e7aSChristoph Hellwig     }
4949e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
4959e0b22f4SStefan Hajnoczi     assert(p != NULL);
49684a12e66SChristoph Hellwig     len = p - filename;
49784a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
49884a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
49984a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
50084a12e66SChristoph Hellwig     protocol[len] = '\0';
50184a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
50284a12e66SChristoph Hellwig         if (drv1->protocol_name &&
50384a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
50484a12e66SChristoph Hellwig             return drv1;
50584a12e66SChristoph Hellwig         }
50684a12e66SChristoph Hellwig     }
50784a12e66SChristoph Hellwig     return NULL;
50884a12e66SChristoph Hellwig }
50984a12e66SChristoph Hellwig 
510c98ac35dSStefan Weil static int find_image_format(const char *filename, BlockDriver **pdrv)
511ea2384d3Sbellard {
51283f64091Sbellard     int ret, score, score_max;
513ea2384d3Sbellard     BlockDriver *drv1, *drv;
51483f64091Sbellard     uint8_t buf[2048];
51583f64091Sbellard     BlockDriverState *bs;
516ea2384d3Sbellard 
517f5edb014SNaphtali Sprei     ret = bdrv_file_open(&bs, filename, 0);
518c98ac35dSStefan Weil     if (ret < 0) {
519c98ac35dSStefan Weil         *pdrv = NULL;
520c98ac35dSStefan Weil         return ret;
521c98ac35dSStefan Weil     }
522f8ea0b00SNicholas Bellinger 
52308a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
52408a00559SKevin Wolf     if (bs->sg || !bdrv_is_inserted(bs)) {
5251a396859SNicholas A. Bellinger         bdrv_delete(bs);
526c98ac35dSStefan Weil         drv = bdrv_find_format("raw");
527c98ac35dSStefan Weil         if (!drv) {
528c98ac35dSStefan Weil             ret = -ENOENT;
529c98ac35dSStefan Weil         }
530c98ac35dSStefan Weil         *pdrv = drv;
531c98ac35dSStefan Weil         return ret;
5321a396859SNicholas A. Bellinger     }
533f8ea0b00SNicholas Bellinger 
53483f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
53583f64091Sbellard     bdrv_delete(bs);
536ea2384d3Sbellard     if (ret < 0) {
537c98ac35dSStefan Weil         *pdrv = NULL;
538c98ac35dSStefan Weil         return ret;
539ea2384d3Sbellard     }
540ea2384d3Sbellard 
541ea2384d3Sbellard     score_max = 0;
54284a12e66SChristoph Hellwig     drv = NULL;
5438a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
54483f64091Sbellard         if (drv1->bdrv_probe) {
545ea2384d3Sbellard             score = drv1->bdrv_probe(buf, ret, filename);
546ea2384d3Sbellard             if (score > score_max) {
547ea2384d3Sbellard                 score_max = score;
548ea2384d3Sbellard                 drv = drv1;
549ea2384d3Sbellard             }
550ea2384d3Sbellard         }
55183f64091Sbellard     }
552c98ac35dSStefan Weil     if (!drv) {
553c98ac35dSStefan Weil         ret = -ENOENT;
554c98ac35dSStefan Weil     }
555c98ac35dSStefan Weil     *pdrv = drv;
556c98ac35dSStefan Weil     return ret;
557ea2384d3Sbellard }
558ea2384d3Sbellard 
55951762288SStefan Hajnoczi /**
56051762288SStefan Hajnoczi  * Set the current 'total_sectors' value
56151762288SStefan Hajnoczi  */
56251762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
56351762288SStefan Hajnoczi {
56451762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
56551762288SStefan Hajnoczi 
566396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
567396759adSNicholas Bellinger     if (bs->sg)
568396759adSNicholas Bellinger         return 0;
569396759adSNicholas Bellinger 
57051762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
57151762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
57251762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
57351762288SStefan Hajnoczi         if (length < 0) {
57451762288SStefan Hajnoczi             return length;
57551762288SStefan Hajnoczi         }
57651762288SStefan Hajnoczi         hint = length >> BDRV_SECTOR_BITS;
57751762288SStefan Hajnoczi     }
57851762288SStefan Hajnoczi 
57951762288SStefan Hajnoczi     bs->total_sectors = hint;
58051762288SStefan Hajnoczi     return 0;
58151762288SStefan Hajnoczi }
58251762288SStefan Hajnoczi 
583c3993cdcSStefan Hajnoczi /**
584c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
585c3993cdcSStefan Hajnoczi  *
586c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
587c3993cdcSStefan Hajnoczi  */
588c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
589c3993cdcSStefan Hajnoczi {
590c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
591c3993cdcSStefan Hajnoczi 
592c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
593c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
59492196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
59592196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
596c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
597c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
598c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
599c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
600c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
601c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
602c3993cdcSStefan Hajnoczi         /* this is the default */
603c3993cdcSStefan Hajnoczi     } else {
604c3993cdcSStefan Hajnoczi         return -1;
605c3993cdcSStefan Hajnoczi     }
606c3993cdcSStefan Hajnoczi 
607c3993cdcSStefan Hajnoczi     return 0;
608c3993cdcSStefan Hajnoczi }
609c3993cdcSStefan Hajnoczi 
61053fec9d3SStefan Hajnoczi /**
61153fec9d3SStefan Hajnoczi  * The copy-on-read flag is actually a reference count so multiple users may
61253fec9d3SStefan Hajnoczi  * use the feature without worrying about clobbering its previous state.
61353fec9d3SStefan Hajnoczi  * Copy-on-read stays enabled until all users have called to disable it.
61453fec9d3SStefan Hajnoczi  */
61553fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs)
61653fec9d3SStefan Hajnoczi {
61753fec9d3SStefan Hajnoczi     bs->copy_on_read++;
61853fec9d3SStefan Hajnoczi }
61953fec9d3SStefan Hajnoczi 
62053fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs)
62153fec9d3SStefan Hajnoczi {
62253fec9d3SStefan Hajnoczi     assert(bs->copy_on_read > 0);
62353fec9d3SStefan Hajnoczi     bs->copy_on_read--;
62453fec9d3SStefan Hajnoczi }
62553fec9d3SStefan Hajnoczi 
626b6ce07aaSKevin Wolf /*
62757915332SKevin Wolf  * Common part for opening disk images and files
62857915332SKevin Wolf  */
62957915332SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, const char *filename,
63057915332SKevin Wolf     int flags, BlockDriver *drv)
63157915332SKevin Wolf {
63257915332SKevin Wolf     int ret, open_flags;
63357915332SKevin Wolf 
63457915332SKevin Wolf     assert(drv != NULL);
6356405875cSPaolo Bonzini     assert(bs->file == NULL);
63657915332SKevin Wolf 
63728dcee10SStefan Hajnoczi     trace_bdrv_open_common(bs, filename, flags, drv->format_name);
63828dcee10SStefan Hajnoczi 
63957915332SKevin Wolf     bs->open_flags = flags;
64057915332SKevin Wolf     bs->buffer_alignment = 512;
64157915332SKevin Wolf 
64253fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
64353fec9d3SStefan Hajnoczi     if ((flags & BDRV_O_RDWR) && (flags & BDRV_O_COPY_ON_READ)) {
64453fec9d3SStefan Hajnoczi         bdrv_enable_copy_on_read(bs);
64553fec9d3SStefan Hajnoczi     }
64653fec9d3SStefan Hajnoczi 
64757915332SKevin Wolf     pstrcpy(bs->filename, sizeof(bs->filename), filename);
64857915332SKevin Wolf 
64957915332SKevin Wolf     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
65057915332SKevin Wolf         return -ENOTSUP;
65157915332SKevin Wolf     }
65257915332SKevin Wolf 
65357915332SKevin Wolf     bs->drv = drv;
6547267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
65557915332SKevin Wolf 
65603f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
657e1e9b0acSPaolo Bonzini     open_flags = flags | BDRV_O_CACHE_WB;
65857915332SKevin Wolf 
65957915332SKevin Wolf     /*
66057915332SKevin Wolf      * Clear flags that are internal to the block layer before opening the
66157915332SKevin Wolf      * image.
66257915332SKevin Wolf      */
663e1e9b0acSPaolo Bonzini     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
66457915332SKevin Wolf 
66557915332SKevin Wolf     /*
666ebabb67aSStefan Weil      * Snapshots should be writable.
66757915332SKevin Wolf      */
66857915332SKevin Wolf     if (bs->is_temporary) {
66957915332SKevin Wolf         open_flags |= BDRV_O_RDWR;
67057915332SKevin Wolf     }
67157915332SKevin Wolf 
672be028adcSJeff Cody     bs->read_only = !(open_flags & BDRV_O_RDWR);
673e7c63796SStefan Hajnoczi 
67466f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
67566f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
67666f82ceeSKevin Wolf         ret = drv->bdrv_file_open(bs, filename, open_flags);
67766f82ceeSKevin Wolf     } else {
67866f82ceeSKevin Wolf         ret = bdrv_file_open(&bs->file, filename, open_flags);
67966f82ceeSKevin Wolf         if (ret >= 0) {
68066f82ceeSKevin Wolf             ret = drv->bdrv_open(bs, open_flags);
68166f82ceeSKevin Wolf         }
68266f82ceeSKevin Wolf     }
68366f82ceeSKevin Wolf 
68457915332SKevin Wolf     if (ret < 0) {
68557915332SKevin Wolf         goto free_and_fail;
68657915332SKevin Wolf     }
68757915332SKevin Wolf 
68851762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
68951762288SStefan Hajnoczi     if (ret < 0) {
69051762288SStefan Hajnoczi         goto free_and_fail;
69157915332SKevin Wolf     }
69251762288SStefan Hajnoczi 
69357915332SKevin Wolf #ifndef _WIN32
69457915332SKevin Wolf     if (bs->is_temporary) {
69557915332SKevin Wolf         unlink(filename);
69657915332SKevin Wolf     }
69757915332SKevin Wolf #endif
69857915332SKevin Wolf     return 0;
69957915332SKevin Wolf 
70057915332SKevin Wolf free_and_fail:
70166f82ceeSKevin Wolf     if (bs->file) {
70266f82ceeSKevin Wolf         bdrv_delete(bs->file);
70366f82ceeSKevin Wolf         bs->file = NULL;
70466f82ceeSKevin Wolf     }
7057267c094SAnthony Liguori     g_free(bs->opaque);
70657915332SKevin Wolf     bs->opaque = NULL;
70757915332SKevin Wolf     bs->drv = NULL;
70857915332SKevin Wolf     return ret;
70957915332SKevin Wolf }
71057915332SKevin Wolf 
71157915332SKevin Wolf /*
712b6ce07aaSKevin Wolf  * Opens a file using a protocol (file, host_device, nbd, ...)
713b6ce07aaSKevin Wolf  */
71483f64091Sbellard int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
715b338082bSbellard {
71683f64091Sbellard     BlockDriverState *bs;
7176db95603SChristoph Hellwig     BlockDriver *drv;
71883f64091Sbellard     int ret;
7193b0d4f61Sbellard 
720b50cbabcSMORITA Kazutaka     drv = bdrv_find_protocol(filename);
7216db95603SChristoph Hellwig     if (!drv) {
7226db95603SChristoph Hellwig         return -ENOENT;
7236db95603SChristoph Hellwig     }
7246db95603SChristoph Hellwig 
72583f64091Sbellard     bs = bdrv_new("");
726b6ce07aaSKevin Wolf     ret = bdrv_open_common(bs, filename, flags, drv);
72783f64091Sbellard     if (ret < 0) {
72883f64091Sbellard         bdrv_delete(bs);
72983f64091Sbellard         return ret;
7303b0d4f61Sbellard     }
73171d0770cSaliguori     bs->growable = 1;
73283f64091Sbellard     *pbs = bs;
73383f64091Sbellard     return 0;
7343b0d4f61Sbellard }
7353b0d4f61Sbellard 
736b6ce07aaSKevin Wolf /*
737b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
738b6ce07aaSKevin Wolf  */
739d6e9098eSKevin Wolf int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
740ea2384d3Sbellard               BlockDriver *drv)
741ea2384d3Sbellard {
742b6ce07aaSKevin Wolf     int ret;
7432b572816SKevin Wolf     char tmp_filename[PATH_MAX];
74433e3963eSbellard 
74583f64091Sbellard     if (flags & BDRV_O_SNAPSHOT) {
746ea2384d3Sbellard         BlockDriverState *bs1;
747ea2384d3Sbellard         int64_t total_size;
7487c96d46eSaliguori         int is_protocol = 0;
74991a073a9SKevin Wolf         BlockDriver *bdrv_qcow2;
75091a073a9SKevin Wolf         QEMUOptionParameter *options;
751b6ce07aaSKevin Wolf         char backing_filename[PATH_MAX];
75233e3963eSbellard 
753ea2384d3Sbellard         /* if snapshot, we create a temporary backing file and open it
754ea2384d3Sbellard            instead of opening 'filename' directly */
755ea2384d3Sbellard 
756ea2384d3Sbellard         /* if there is a backing file, use it */
757ea2384d3Sbellard         bs1 = bdrv_new("");
758d6e9098eSKevin Wolf         ret = bdrv_open(bs1, filename, 0, drv);
75951d7c00cSaliguori         if (ret < 0) {
760ea2384d3Sbellard             bdrv_delete(bs1);
76151d7c00cSaliguori             return ret;
762ea2384d3Sbellard         }
7633e82990bSJes Sorensen         total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
7647c96d46eSaliguori 
7657c96d46eSaliguori         if (bs1->drv && bs1->drv->protocol_name)
7667c96d46eSaliguori             is_protocol = 1;
7677c96d46eSaliguori 
768ea2384d3Sbellard         bdrv_delete(bs1);
769ea2384d3Sbellard 
770eba25057SJim Meyering         ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
771eba25057SJim Meyering         if (ret < 0) {
772eba25057SJim Meyering             return ret;
773eba25057SJim Meyering         }
7747c96d46eSaliguori 
7757c96d46eSaliguori         /* Real path is meaningless for protocols */
7767c96d46eSaliguori         if (is_protocol)
7777c96d46eSaliguori             snprintf(backing_filename, sizeof(backing_filename),
7787c96d46eSaliguori                      "%s", filename);
779114cdfa9SKirill A. Shutemov         else if (!realpath(filename, backing_filename))
780114cdfa9SKirill A. Shutemov             return -errno;
7817c96d46eSaliguori 
78291a073a9SKevin Wolf         bdrv_qcow2 = bdrv_find_format("qcow2");
78391a073a9SKevin Wolf         options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
78491a073a9SKevin Wolf 
7853e82990bSJes Sorensen         set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
78691a073a9SKevin Wolf         set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
78791a073a9SKevin Wolf         if (drv) {
78891a073a9SKevin Wolf             set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
78991a073a9SKevin Wolf                 drv->format_name);
79091a073a9SKevin Wolf         }
79191a073a9SKevin Wolf 
79291a073a9SKevin Wolf         ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
793d748768cSJan Kiszka         free_option_parameters(options);
79451d7c00cSaliguori         if (ret < 0) {
79551d7c00cSaliguori             return ret;
796ea2384d3Sbellard         }
79791a073a9SKevin Wolf 
798ea2384d3Sbellard         filename = tmp_filename;
79991a073a9SKevin Wolf         drv = bdrv_qcow2;
800ea2384d3Sbellard         bs->is_temporary = 1;
801ea2384d3Sbellard     }
802ea2384d3Sbellard 
803b6ce07aaSKevin Wolf     /* Find the right image format driver */
8046db95603SChristoph Hellwig     if (!drv) {
805c98ac35dSStefan Weil         ret = find_image_format(filename, &drv);
806ea2384d3Sbellard     }
8076987307cSChristoph Hellwig 
80851d7c00cSaliguori     if (!drv) {
80951d7c00cSaliguori         goto unlink_and_fail;
81083f64091Sbellard     }
811b6ce07aaSKevin Wolf 
812be028adcSJeff Cody     if (flags & BDRV_O_RDWR) {
813be028adcSJeff Cody         flags |= BDRV_O_ALLOW_RDWR;
814be028adcSJeff Cody     }
815be028adcSJeff Cody 
816b6ce07aaSKevin Wolf     /* Open the image */
817b6ce07aaSKevin Wolf     ret = bdrv_open_common(bs, filename, flags, drv);
818b6ce07aaSKevin Wolf     if (ret < 0) {
8196987307cSChristoph Hellwig         goto unlink_and_fail;
8206987307cSChristoph Hellwig     }
8216987307cSChristoph Hellwig 
822b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
823b6ce07aaSKevin Wolf     if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
824b6ce07aaSKevin Wolf         char backing_filename[PATH_MAX];
825b6ce07aaSKevin Wolf         int back_flags;
826b6ce07aaSKevin Wolf         BlockDriver *back_drv = NULL;
827b6ce07aaSKevin Wolf 
828b6ce07aaSKevin Wolf         bs->backing_hd = bdrv_new("");
829dc5a1371SPaolo Bonzini         bdrv_get_full_backing_filename(bs, backing_filename,
830dc5a1371SPaolo Bonzini                                        sizeof(backing_filename));
831df2dbb4aSStefan Hajnoczi 
832df2dbb4aSStefan Hajnoczi         if (bs->backing_format[0] != '\0') {
833b6ce07aaSKevin Wolf             back_drv = bdrv_find_format(bs->backing_format);
834df2dbb4aSStefan Hajnoczi         }
835b6ce07aaSKevin Wolf 
836b6ce07aaSKevin Wolf         /* backing files always opened read-only */
837b6ce07aaSKevin Wolf         back_flags =
838b6ce07aaSKevin Wolf             flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
839b6ce07aaSKevin Wolf 
840b6ce07aaSKevin Wolf         ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
841b6ce07aaSKevin Wolf         if (ret < 0) {
842b6ce07aaSKevin Wolf             bdrv_close(bs);
843b6ce07aaSKevin Wolf             return ret;
844b6ce07aaSKevin Wolf         }
845b6ce07aaSKevin Wolf     }
846b6ce07aaSKevin Wolf 
847b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
8487d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
849b6ce07aaSKevin Wolf     }
850b6ce07aaSKevin Wolf 
85198f90dbaSZhi Yong Wu     /* throttling disk I/O limits */
85298f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
85398f90dbaSZhi Yong Wu         bdrv_io_limits_enable(bs);
85498f90dbaSZhi Yong Wu     }
85598f90dbaSZhi Yong Wu 
856b6ce07aaSKevin Wolf     return 0;
857b6ce07aaSKevin Wolf 
858b6ce07aaSKevin Wolf unlink_and_fail:
859b6ce07aaSKevin Wolf     if (bs->is_temporary) {
860b6ce07aaSKevin Wolf         unlink(filename);
861b6ce07aaSKevin Wolf     }
862b6ce07aaSKevin Wolf     return ret;
863b6ce07aaSKevin Wolf }
864b6ce07aaSKevin Wolf 
865e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
866e971aa12SJeff Cody      bool prepared;
867e971aa12SJeff Cody      BDRVReopenState state;
868e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
869e971aa12SJeff Cody } BlockReopenQueueEntry;
870e971aa12SJeff Cody 
871e971aa12SJeff Cody /*
872e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
873e971aa12SJeff Cody  * reopen of multiple devices.
874e971aa12SJeff Cody  *
875e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
876e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
877e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
878e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
879e971aa12SJeff Cody  * atomic 'set'.
880e971aa12SJeff Cody  *
881e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
882e971aa12SJeff Cody  *
883e971aa12SJeff Cody  * flags contains the open flags for the associated bs
884e971aa12SJeff Cody  *
885e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
886e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
887e971aa12SJeff Cody  *
888e971aa12SJeff Cody  */
889e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
890e971aa12SJeff Cody                                     BlockDriverState *bs, int flags)
891e971aa12SJeff Cody {
892e971aa12SJeff Cody     assert(bs != NULL);
893e971aa12SJeff Cody 
894e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
895e971aa12SJeff Cody     if (bs_queue == NULL) {
896e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
897e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
898e971aa12SJeff Cody     }
899e971aa12SJeff Cody 
900e971aa12SJeff Cody     if (bs->file) {
901e971aa12SJeff Cody         bdrv_reopen_queue(bs_queue, bs->file, flags);
902e971aa12SJeff Cody     }
903e971aa12SJeff Cody 
904e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
905e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
906e971aa12SJeff Cody 
907e971aa12SJeff Cody     bs_entry->state.bs = bs;
908e971aa12SJeff Cody     bs_entry->state.flags = flags;
909e971aa12SJeff Cody 
910e971aa12SJeff Cody     return bs_queue;
911e971aa12SJeff Cody }
912e971aa12SJeff Cody 
913e971aa12SJeff Cody /*
914e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
915e971aa12SJeff Cody  *
916e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
917e971aa12SJeff Cody  * via bdrv_reopen_queue().
918e971aa12SJeff Cody  *
919e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
920e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
921e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
922e971aa12SJeff Cody  * data cleaned up.
923e971aa12SJeff Cody  *
924e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
925e971aa12SJeff Cody  * to all devices.
926e971aa12SJeff Cody  *
927e971aa12SJeff Cody  */
928e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
929e971aa12SJeff Cody {
930e971aa12SJeff Cody     int ret = -1;
931e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
932e971aa12SJeff Cody     Error *local_err = NULL;
933e971aa12SJeff Cody 
934e971aa12SJeff Cody     assert(bs_queue != NULL);
935e971aa12SJeff Cody 
936e971aa12SJeff Cody     bdrv_drain_all();
937e971aa12SJeff Cody 
938e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
939e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
940e971aa12SJeff Cody             error_propagate(errp, local_err);
941e971aa12SJeff Cody             goto cleanup;
942e971aa12SJeff Cody         }
943e971aa12SJeff Cody         bs_entry->prepared = true;
944e971aa12SJeff Cody     }
945e971aa12SJeff Cody 
946e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
947e971aa12SJeff Cody      * changes
948e971aa12SJeff Cody      */
949e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
950e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
951e971aa12SJeff Cody     }
952e971aa12SJeff Cody 
953e971aa12SJeff Cody     ret = 0;
954e971aa12SJeff Cody 
955e971aa12SJeff Cody cleanup:
956e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
957e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
958e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
959e971aa12SJeff Cody         }
960e971aa12SJeff Cody         g_free(bs_entry);
961e971aa12SJeff Cody     }
962e971aa12SJeff Cody     g_free(bs_queue);
963e971aa12SJeff Cody     return ret;
964e971aa12SJeff Cody }
965e971aa12SJeff Cody 
966e971aa12SJeff Cody 
967e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
968e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
969e971aa12SJeff Cody {
970e971aa12SJeff Cody     int ret = -1;
971e971aa12SJeff Cody     Error *local_err = NULL;
972e971aa12SJeff Cody     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
973e971aa12SJeff Cody 
974e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
975e971aa12SJeff Cody     if (local_err != NULL) {
976e971aa12SJeff Cody         error_propagate(errp, local_err);
977e971aa12SJeff Cody     }
978e971aa12SJeff Cody     return ret;
979e971aa12SJeff Cody }
980e971aa12SJeff Cody 
981e971aa12SJeff Cody 
982e971aa12SJeff Cody /*
983e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
984e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
985e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
986e971aa12SJeff Cody  *
987e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
988e971aa12SJeff Cody  * flags are the new open flags
989e971aa12SJeff Cody  * queue is the reopen queue
990e971aa12SJeff Cody  *
991e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
992e971aa12SJeff Cody  * as well.
993e971aa12SJeff Cody  *
994e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
995e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
996e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
997e971aa12SJeff Cody  *
998e971aa12SJeff Cody  */
999e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1000e971aa12SJeff Cody                         Error **errp)
1001e971aa12SJeff Cody {
1002e971aa12SJeff Cody     int ret = -1;
1003e971aa12SJeff Cody     Error *local_err = NULL;
1004e971aa12SJeff Cody     BlockDriver *drv;
1005e971aa12SJeff Cody 
1006e971aa12SJeff Cody     assert(reopen_state != NULL);
1007e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1008e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1009e971aa12SJeff Cody 
1010e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1011e971aa12SJeff Cody      * to r/w */
1012e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1013e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
1014e971aa12SJeff Cody         error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1015e971aa12SJeff Cody                   reopen_state->bs->device_name);
1016e971aa12SJeff Cody         goto error;
1017e971aa12SJeff Cody     }
1018e971aa12SJeff Cody 
1019e971aa12SJeff Cody 
1020e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1021e971aa12SJeff Cody     if (ret) {
1022e971aa12SJeff Cody         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1023e971aa12SJeff Cody                   strerror(-ret));
1024e971aa12SJeff Cody         goto error;
1025e971aa12SJeff Cody     }
1026e971aa12SJeff Cody 
1027e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1028e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1029e971aa12SJeff Cody         if (ret) {
1030e971aa12SJeff Cody             if (local_err != NULL) {
1031e971aa12SJeff Cody                 error_propagate(errp, local_err);
1032e971aa12SJeff Cody             } else {
1033e971aa12SJeff Cody                 error_set(errp, QERR_OPEN_FILE_FAILED,
1034e971aa12SJeff Cody                           reopen_state->bs->filename);
1035e971aa12SJeff Cody             }
1036e971aa12SJeff Cody             goto error;
1037e971aa12SJeff Cody         }
1038e971aa12SJeff Cody     } else {
1039e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1040e971aa12SJeff Cody          * handler for each supported drv. */
1041e971aa12SJeff Cody         error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1042e971aa12SJeff Cody                   drv->format_name, reopen_state->bs->device_name,
1043e971aa12SJeff Cody                  "reopening of file");
1044e971aa12SJeff Cody         ret = -1;
1045e971aa12SJeff Cody         goto error;
1046e971aa12SJeff Cody     }
1047e971aa12SJeff Cody 
1048e971aa12SJeff Cody     ret = 0;
1049e971aa12SJeff Cody 
1050e971aa12SJeff Cody error:
1051e971aa12SJeff Cody     return ret;
1052e971aa12SJeff Cody }
1053e971aa12SJeff Cody 
1054e971aa12SJeff Cody /*
1055e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1056e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1057e971aa12SJeff Cody  * the active BlockDriverState contents.
1058e971aa12SJeff Cody  */
1059e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1060e971aa12SJeff Cody {
1061e971aa12SJeff Cody     BlockDriver *drv;
1062e971aa12SJeff Cody 
1063e971aa12SJeff Cody     assert(reopen_state != NULL);
1064e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1065e971aa12SJeff Cody     assert(drv != NULL);
1066e971aa12SJeff Cody 
1067e971aa12SJeff Cody     /* If there are any driver level actions to take */
1068e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1069e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1070e971aa12SJeff Cody     }
1071e971aa12SJeff Cody 
1072e971aa12SJeff Cody     /* set BDS specific flags now */
1073e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1074e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1075e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1076e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1077e971aa12SJeff Cody }
1078e971aa12SJeff Cody 
1079e971aa12SJeff Cody /*
1080e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1081e971aa12SJeff Cody  * reopen_state
1082e971aa12SJeff Cody  */
1083e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1084e971aa12SJeff Cody {
1085e971aa12SJeff Cody     BlockDriver *drv;
1086e971aa12SJeff Cody 
1087e971aa12SJeff Cody     assert(reopen_state != NULL);
1088e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1089e971aa12SJeff Cody     assert(drv != NULL);
1090e971aa12SJeff Cody 
1091e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1092e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1093e971aa12SJeff Cody     }
1094e971aa12SJeff Cody }
1095e971aa12SJeff Cody 
1096e971aa12SJeff Cody 
1097fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1098fc01f7e7Sbellard {
109980ccf93bSLiu Yuan     bdrv_flush(bs);
110019cb3738Sbellard     if (bs->drv) {
11013e914655SPaolo Bonzini         if (bs->job) {
11023e914655SPaolo Bonzini             block_job_cancel_sync(bs->job);
11033e914655SPaolo Bonzini         }
11047094f12fSKevin Wolf         bdrv_drain_all();
11057094f12fSKevin Wolf 
1106f9092b10SMarkus Armbruster         if (bs == bs_snapshots) {
1107f9092b10SMarkus Armbruster             bs_snapshots = NULL;
1108f9092b10SMarkus Armbruster         }
1109557df6acSStefan Hajnoczi         if (bs->backing_hd) {
1110ea2384d3Sbellard             bdrv_delete(bs->backing_hd);
1111557df6acSStefan Hajnoczi             bs->backing_hd = NULL;
1112557df6acSStefan Hajnoczi         }
1113ea2384d3Sbellard         bs->drv->bdrv_close(bs);
11147267c094SAnthony Liguori         g_free(bs->opaque);
1115ea2384d3Sbellard #ifdef _WIN32
1116ea2384d3Sbellard         if (bs->is_temporary) {
1117ea2384d3Sbellard             unlink(bs->filename);
1118ea2384d3Sbellard         }
111967b915a5Sbellard #endif
1120ea2384d3Sbellard         bs->opaque = NULL;
1121ea2384d3Sbellard         bs->drv = NULL;
112253fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1123a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1124a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
11256405875cSPaolo Bonzini         bs->total_sectors = 0;
11266405875cSPaolo Bonzini         bs->encrypted = 0;
11276405875cSPaolo Bonzini         bs->valid_key = 0;
11286405875cSPaolo Bonzini         bs->sg = 0;
11296405875cSPaolo Bonzini         bs->growable = 0;
1130b338082bSbellard 
113166f82ceeSKevin Wolf         if (bs->file != NULL) {
11320ac9377dSPaolo Bonzini             bdrv_delete(bs->file);
11330ac9377dSPaolo Bonzini             bs->file = NULL;
113466f82ceeSKevin Wolf         }
11359ca11154SPavel Hrdina     }
113666f82ceeSKevin Wolf 
11377d4b4ba5SMarkus Armbruster     bdrv_dev_change_media_cb(bs, false);
113898f90dbaSZhi Yong Wu 
113998f90dbaSZhi Yong Wu     /*throttling disk I/O limits*/
114098f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
114198f90dbaSZhi Yong Wu         bdrv_io_limits_disable(bs);
114298f90dbaSZhi Yong Wu     }
1143b338082bSbellard }
1144b338082bSbellard 
11452bc93fedSMORITA Kazutaka void bdrv_close_all(void)
11462bc93fedSMORITA Kazutaka {
11472bc93fedSMORITA Kazutaka     BlockDriverState *bs;
11482bc93fedSMORITA Kazutaka 
11492bc93fedSMORITA Kazutaka     QTAILQ_FOREACH(bs, &bdrv_states, list) {
11502bc93fedSMORITA Kazutaka         bdrv_close(bs);
11512bc93fedSMORITA Kazutaka     }
11522bc93fedSMORITA Kazutaka }
11532bc93fedSMORITA Kazutaka 
1154922453bcSStefan Hajnoczi /*
1155922453bcSStefan Hajnoczi  * Wait for pending requests to complete across all BlockDriverStates
1156922453bcSStefan Hajnoczi  *
1157922453bcSStefan Hajnoczi  * This function does not flush data to disk, use bdrv_flush_all() for that
1158922453bcSStefan Hajnoczi  * after calling this function.
11594c355d53SZhi Yong Wu  *
11604c355d53SZhi Yong Wu  * Note that completion of an asynchronous I/O operation can trigger any
11614c355d53SZhi Yong Wu  * number of other I/O operations on other devices---for example a coroutine
11624c355d53SZhi Yong Wu  * can be arbitrarily complex and a constant flow of I/O can come until the
11634c355d53SZhi Yong Wu  * coroutine is complete.  Because of this, it is not possible to have a
11644c355d53SZhi Yong Wu  * function to drain a single device's I/O queue.
1165922453bcSStefan Hajnoczi  */
1166922453bcSStefan Hajnoczi void bdrv_drain_all(void)
1167922453bcSStefan Hajnoczi {
1168922453bcSStefan Hajnoczi     BlockDriverState *bs;
11694c355d53SZhi Yong Wu     bool busy;
1170922453bcSStefan Hajnoczi 
11714c355d53SZhi Yong Wu     do {
11724c355d53SZhi Yong Wu         busy = qemu_aio_wait();
11734c355d53SZhi Yong Wu 
11744c355d53SZhi Yong Wu         /* FIXME: We do not have timer support here, so this is effectively
11754c355d53SZhi Yong Wu          * a busy wait.
11764c355d53SZhi Yong Wu          */
11774c355d53SZhi Yong Wu         QTAILQ_FOREACH(bs, &bdrv_states, list) {
11784c355d53SZhi Yong Wu             if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
11794c355d53SZhi Yong Wu                 qemu_co_queue_restart_all(&bs->throttled_reqs);
11804c355d53SZhi Yong Wu                 busy = true;
11814c355d53SZhi Yong Wu             }
11824c355d53SZhi Yong Wu         }
11834c355d53SZhi Yong Wu     } while (busy);
1184922453bcSStefan Hajnoczi 
1185922453bcSStefan Hajnoczi     /* If requests are still pending there is a bug somewhere */
1186922453bcSStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1187922453bcSStefan Hajnoczi         assert(QLIST_EMPTY(&bs->tracked_requests));
1188922453bcSStefan Hajnoczi         assert(qemu_co_queue_empty(&bs->throttled_reqs));
1189922453bcSStefan Hajnoczi     }
1190922453bcSStefan Hajnoczi }
1191922453bcSStefan Hajnoczi 
1192d22b2f41SRyan Harper /* make a BlockDriverState anonymous by removing from bdrv_state list.
1193d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
1194d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
1195d22b2f41SRyan Harper {
1196d22b2f41SRyan Harper     if (bs->device_name[0] != '\0') {
1197d22b2f41SRyan Harper         QTAILQ_REMOVE(&bdrv_states, bs, list);
1198d22b2f41SRyan Harper     }
1199d22b2f41SRyan Harper     bs->device_name[0] = '\0';
1200d22b2f41SRyan Harper }
1201d22b2f41SRyan Harper 
1202e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs)
1203e023b2e2SPaolo Bonzini {
1204e023b2e2SPaolo Bonzini     if (bs->drv && bs->drv->bdrv_rebind) {
1205e023b2e2SPaolo Bonzini         bs->drv->bdrv_rebind(bs);
1206e023b2e2SPaolo Bonzini     }
1207e023b2e2SPaolo Bonzini }
1208e023b2e2SPaolo Bonzini 
12094ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
12104ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
12114ddc07caSPaolo Bonzini {
12124ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
12134ddc07caSPaolo Bonzini     bs_dest->open_flags         = bs_src->open_flags;
12144ddc07caSPaolo Bonzini 
12154ddc07caSPaolo Bonzini     /* dev info */
12164ddc07caSPaolo Bonzini     bs_dest->dev_ops            = bs_src->dev_ops;
12174ddc07caSPaolo Bonzini     bs_dest->dev_opaque         = bs_src->dev_opaque;
12184ddc07caSPaolo Bonzini     bs_dest->dev                = bs_src->dev;
12194ddc07caSPaolo Bonzini     bs_dest->buffer_alignment   = bs_src->buffer_alignment;
12204ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
12214ddc07caSPaolo Bonzini 
12224ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
12234ddc07caSPaolo Bonzini 
12244ddc07caSPaolo Bonzini     /* i/o timing parameters */
12254ddc07caSPaolo Bonzini     bs_dest->slice_time         = bs_src->slice_time;
12264ddc07caSPaolo Bonzini     bs_dest->slice_start        = bs_src->slice_start;
12274ddc07caSPaolo Bonzini     bs_dest->slice_end          = bs_src->slice_end;
12284ddc07caSPaolo Bonzini     bs_dest->io_limits          = bs_src->io_limits;
12294ddc07caSPaolo Bonzini     bs_dest->io_base            = bs_src->io_base;
12304ddc07caSPaolo Bonzini     bs_dest->throttled_reqs     = bs_src->throttled_reqs;
12314ddc07caSPaolo Bonzini     bs_dest->block_timer        = bs_src->block_timer;
12324ddc07caSPaolo Bonzini     bs_dest->io_limits_enabled  = bs_src->io_limits_enabled;
12334ddc07caSPaolo Bonzini 
12344ddc07caSPaolo Bonzini     /* r/w error */
12354ddc07caSPaolo Bonzini     bs_dest->on_read_error      = bs_src->on_read_error;
12364ddc07caSPaolo Bonzini     bs_dest->on_write_error     = bs_src->on_write_error;
12374ddc07caSPaolo Bonzini 
12384ddc07caSPaolo Bonzini     /* i/o status */
12394ddc07caSPaolo Bonzini     bs_dest->iostatus_enabled   = bs_src->iostatus_enabled;
12404ddc07caSPaolo Bonzini     bs_dest->iostatus           = bs_src->iostatus;
12414ddc07caSPaolo Bonzini 
12424ddc07caSPaolo Bonzini     /* dirty bitmap */
12434ddc07caSPaolo Bonzini     bs_dest->dirty_count        = bs_src->dirty_count;
12444ddc07caSPaolo Bonzini     bs_dest->dirty_bitmap       = bs_src->dirty_bitmap;
12454ddc07caSPaolo Bonzini 
12464ddc07caSPaolo Bonzini     /* job */
12474ddc07caSPaolo Bonzini     bs_dest->in_use             = bs_src->in_use;
12484ddc07caSPaolo Bonzini     bs_dest->job                = bs_src->job;
12494ddc07caSPaolo Bonzini 
12504ddc07caSPaolo Bonzini     /* keep the same entry in bdrv_states */
12514ddc07caSPaolo Bonzini     pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
12524ddc07caSPaolo Bonzini             bs_src->device_name);
12534ddc07caSPaolo Bonzini     bs_dest->list = bs_src->list;
12544ddc07caSPaolo Bonzini }
12554ddc07caSPaolo Bonzini 
12564ddc07caSPaolo Bonzini /*
12574ddc07caSPaolo Bonzini  * Swap bs contents for two image chains while they are live,
12584ddc07caSPaolo Bonzini  * while keeping required fields on the BlockDriverState that is
12594ddc07caSPaolo Bonzini  * actually attached to a device.
12604ddc07caSPaolo Bonzini  *
12614ddc07caSPaolo Bonzini  * This will modify the BlockDriverState fields, and swap contents
12624ddc07caSPaolo Bonzini  * between bs_new and bs_old. Both bs_new and bs_old are modified.
12634ddc07caSPaolo Bonzini  *
12644ddc07caSPaolo Bonzini  * bs_new is required to be anonymous.
12654ddc07caSPaolo Bonzini  *
12664ddc07caSPaolo Bonzini  * This function does not create any image files.
12674ddc07caSPaolo Bonzini  */
12684ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
12694ddc07caSPaolo Bonzini {
12704ddc07caSPaolo Bonzini     BlockDriverState tmp;
12714ddc07caSPaolo Bonzini 
12724ddc07caSPaolo Bonzini     /* bs_new must be anonymous and shouldn't have anything fancy enabled */
12734ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
12744ddc07caSPaolo Bonzini     assert(bs_new->dirty_bitmap == NULL);
12754ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
12764ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
12774ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
12784ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
12794ddc07caSPaolo Bonzini     assert(bs_new->block_timer == NULL);
12804ddc07caSPaolo Bonzini 
12814ddc07caSPaolo Bonzini     tmp = *bs_new;
12824ddc07caSPaolo Bonzini     *bs_new = *bs_old;
12834ddc07caSPaolo Bonzini     *bs_old = tmp;
12844ddc07caSPaolo Bonzini 
12854ddc07caSPaolo Bonzini     /* there are some fields that should not be swapped, move them back */
12864ddc07caSPaolo Bonzini     bdrv_move_feature_fields(&tmp, bs_old);
12874ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_old, bs_new);
12884ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_new, &tmp);
12894ddc07caSPaolo Bonzini 
12904ddc07caSPaolo Bonzini     /* bs_new shouldn't be in bdrv_states even after the swap!  */
12914ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
12924ddc07caSPaolo Bonzini 
12934ddc07caSPaolo Bonzini     /* Check a few fields that should remain attached to the device */
12944ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
12954ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
12964ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
12974ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
12984ddc07caSPaolo Bonzini     assert(bs_new->block_timer == NULL);
12994ddc07caSPaolo Bonzini 
13004ddc07caSPaolo Bonzini     bdrv_rebind(bs_new);
13014ddc07caSPaolo Bonzini     bdrv_rebind(bs_old);
13024ddc07caSPaolo Bonzini }
13034ddc07caSPaolo Bonzini 
13048802d1fdSJeff Cody /*
13058802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
13068802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
13078802d1fdSJeff Cody  *
13088802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
13098802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
13108802d1fdSJeff Cody  *
1311f6801b83SJeff Cody  * bs_new is required to be anonymous.
1312f6801b83SJeff Cody  *
13138802d1fdSJeff Cody  * This function does not create any image files.
13148802d1fdSJeff Cody  */
13158802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
13168802d1fdSJeff Cody {
13174ddc07caSPaolo Bonzini     bdrv_swap(bs_new, bs_top);
13188802d1fdSJeff Cody 
13198802d1fdSJeff Cody     /* The contents of 'tmp' will become bs_top, as we are
13208802d1fdSJeff Cody      * swapping bs_new and bs_top contents. */
13214ddc07caSPaolo Bonzini     bs_top->backing_hd = bs_new;
13224ddc07caSPaolo Bonzini     bs_top->open_flags &= ~BDRV_O_NO_BACKING;
13234ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
13244ddc07caSPaolo Bonzini             bs_new->filename);
13254ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
13264ddc07caSPaolo Bonzini             bs_new->drv ? bs_new->drv->format_name : "");
13278802d1fdSJeff Cody }
13288802d1fdSJeff Cody 
1329b338082bSbellard void bdrv_delete(BlockDriverState *bs)
1330b338082bSbellard {
1331fa879d62SMarkus Armbruster     assert(!bs->dev);
13323e914655SPaolo Bonzini     assert(!bs->job);
13333e914655SPaolo Bonzini     assert(!bs->in_use);
133418846deeSMarkus Armbruster 
13351b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
1336d22b2f41SRyan Harper     bdrv_make_anon(bs);
133734c6f050Saurel32 
1338b338082bSbellard     bdrv_close(bs);
133966f82ceeSKevin Wolf 
1340f9092b10SMarkus Armbruster     assert(bs != bs_snapshots);
13417267c094SAnthony Liguori     g_free(bs);
1342fc01f7e7Sbellard }
1343fc01f7e7Sbellard 
1344fa879d62SMarkus Armbruster int bdrv_attach_dev(BlockDriverState *bs, void *dev)
1345fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
134618846deeSMarkus Armbruster {
1347fa879d62SMarkus Armbruster     if (bs->dev) {
134818846deeSMarkus Armbruster         return -EBUSY;
134918846deeSMarkus Armbruster     }
1350fa879d62SMarkus Armbruster     bs->dev = dev;
135128a7282aSLuiz Capitulino     bdrv_iostatus_reset(bs);
135218846deeSMarkus Armbruster     return 0;
135318846deeSMarkus Armbruster }
135418846deeSMarkus Armbruster 
1355fa879d62SMarkus Armbruster /* TODO qdevified devices don't use this, remove when devices are qdevified */
1356fa879d62SMarkus Armbruster void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
135718846deeSMarkus Armbruster {
1358fa879d62SMarkus Armbruster     if (bdrv_attach_dev(bs, dev) < 0) {
1359fa879d62SMarkus Armbruster         abort();
1360fa879d62SMarkus Armbruster     }
1361fa879d62SMarkus Armbruster }
1362fa879d62SMarkus Armbruster 
1363fa879d62SMarkus Armbruster void bdrv_detach_dev(BlockDriverState *bs, void *dev)
1364fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
1365fa879d62SMarkus Armbruster {
1366fa879d62SMarkus Armbruster     assert(bs->dev == dev);
1367fa879d62SMarkus Armbruster     bs->dev = NULL;
13680e49de52SMarkus Armbruster     bs->dev_ops = NULL;
13690e49de52SMarkus Armbruster     bs->dev_opaque = NULL;
137029e05f20SMarkus Armbruster     bs->buffer_alignment = 512;
137118846deeSMarkus Armbruster }
137218846deeSMarkus Armbruster 
1373fa879d62SMarkus Armbruster /* TODO change to return DeviceState * when all users are qdevified */
1374fa879d62SMarkus Armbruster void *bdrv_get_attached_dev(BlockDriverState *bs)
137518846deeSMarkus Armbruster {
1376fa879d62SMarkus Armbruster     return bs->dev;
137718846deeSMarkus Armbruster }
137818846deeSMarkus Armbruster 
13790e49de52SMarkus Armbruster void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
13800e49de52SMarkus Armbruster                       void *opaque)
13810e49de52SMarkus Armbruster {
13820e49de52SMarkus Armbruster     bs->dev_ops = ops;
13830e49de52SMarkus Armbruster     bs->dev_opaque = opaque;
13842c6942faSMarkus Armbruster     if (bdrv_dev_has_removable_media(bs) && bs == bs_snapshots) {
13852c6942faSMarkus Armbruster         bs_snapshots = NULL;
13862c6942faSMarkus Armbruster     }
13870e49de52SMarkus Armbruster }
13880e49de52SMarkus Armbruster 
1389329c0a48SLuiz Capitulino void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
1390329c0a48SLuiz Capitulino                                BlockQMPEventAction action, int is_read)
1391329c0a48SLuiz Capitulino {
1392329c0a48SLuiz Capitulino     QObject *data;
1393329c0a48SLuiz Capitulino     const char *action_str;
1394329c0a48SLuiz Capitulino 
1395329c0a48SLuiz Capitulino     switch (action) {
1396329c0a48SLuiz Capitulino     case BDRV_ACTION_REPORT:
1397329c0a48SLuiz Capitulino         action_str = "report";
1398329c0a48SLuiz Capitulino         break;
1399329c0a48SLuiz Capitulino     case BDRV_ACTION_IGNORE:
1400329c0a48SLuiz Capitulino         action_str = "ignore";
1401329c0a48SLuiz Capitulino         break;
1402329c0a48SLuiz Capitulino     case BDRV_ACTION_STOP:
1403329c0a48SLuiz Capitulino         action_str = "stop";
1404329c0a48SLuiz Capitulino         break;
1405329c0a48SLuiz Capitulino     default:
1406329c0a48SLuiz Capitulino         abort();
1407329c0a48SLuiz Capitulino     }
1408329c0a48SLuiz Capitulino 
1409329c0a48SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1410329c0a48SLuiz Capitulino                               bdrv->device_name,
1411329c0a48SLuiz Capitulino                               action_str,
1412329c0a48SLuiz Capitulino                               is_read ? "read" : "write");
1413329c0a48SLuiz Capitulino     monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1414329c0a48SLuiz Capitulino 
1415329c0a48SLuiz Capitulino     qobject_decref(data);
1416329c0a48SLuiz Capitulino }
1417329c0a48SLuiz Capitulino 
14186f382ed2SLuiz Capitulino static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
14196f382ed2SLuiz Capitulino {
14206f382ed2SLuiz Capitulino     QObject *data;
14216f382ed2SLuiz Capitulino 
14226f382ed2SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
14236f382ed2SLuiz Capitulino                               bdrv_get_device_name(bs), ejected);
14246f382ed2SLuiz Capitulino     monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
14256f382ed2SLuiz Capitulino 
14266f382ed2SLuiz Capitulino     qobject_decref(data);
14276f382ed2SLuiz Capitulino }
14286f382ed2SLuiz Capitulino 
14297d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
14300e49de52SMarkus Armbruster {
1431145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->change_media_cb) {
14326f382ed2SLuiz Capitulino         bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
14337d4b4ba5SMarkus Armbruster         bs->dev_ops->change_media_cb(bs->dev_opaque, load);
14346f382ed2SLuiz Capitulino         if (tray_was_closed) {
14356f382ed2SLuiz Capitulino             /* tray open */
14366f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, true);
14376f382ed2SLuiz Capitulino         }
14386f382ed2SLuiz Capitulino         if (load) {
14396f382ed2SLuiz Capitulino             /* tray close */
14406f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, false);
14416f382ed2SLuiz Capitulino         }
1442145feb17SMarkus Armbruster     }
1443145feb17SMarkus Armbruster }
1444145feb17SMarkus Armbruster 
14452c6942faSMarkus Armbruster bool bdrv_dev_has_removable_media(BlockDriverState *bs)
14462c6942faSMarkus Armbruster {
14472c6942faSMarkus Armbruster     return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
14482c6942faSMarkus Armbruster }
14492c6942faSMarkus Armbruster 
1450025ccaa7SPaolo Bonzini void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
1451025ccaa7SPaolo Bonzini {
1452025ccaa7SPaolo Bonzini     if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
1453025ccaa7SPaolo Bonzini         bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
1454025ccaa7SPaolo Bonzini     }
1455025ccaa7SPaolo Bonzini }
1456025ccaa7SPaolo Bonzini 
1457e4def80bSMarkus Armbruster bool bdrv_dev_is_tray_open(BlockDriverState *bs)
1458e4def80bSMarkus Armbruster {
1459e4def80bSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_tray_open) {
1460e4def80bSMarkus Armbruster         return bs->dev_ops->is_tray_open(bs->dev_opaque);
1461e4def80bSMarkus Armbruster     }
1462e4def80bSMarkus Armbruster     return false;
1463e4def80bSMarkus Armbruster }
1464e4def80bSMarkus Armbruster 
1465145feb17SMarkus Armbruster static void bdrv_dev_resize_cb(BlockDriverState *bs)
1466145feb17SMarkus Armbruster {
1467145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->resize_cb) {
1468145feb17SMarkus Armbruster         bs->dev_ops->resize_cb(bs->dev_opaque);
14690e49de52SMarkus Armbruster     }
14700e49de52SMarkus Armbruster }
14710e49de52SMarkus Armbruster 
1472f107639aSMarkus Armbruster bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
1473f107639aSMarkus Armbruster {
1474f107639aSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
1475f107639aSMarkus Armbruster         return bs->dev_ops->is_medium_locked(bs->dev_opaque);
1476f107639aSMarkus Armbruster     }
1477f107639aSMarkus Armbruster     return false;
1478f107639aSMarkus Armbruster }
1479f107639aSMarkus Armbruster 
1480e97fc193Saliguori /*
1481e97fc193Saliguori  * Run consistency checks on an image
1482e97fc193Saliguori  *
1483e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
1484a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
1485e076f338SKevin Wolf  * check are stored in res.
1486e97fc193Saliguori  */
14874534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
1488e97fc193Saliguori {
1489e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
1490e97fc193Saliguori         return -ENOTSUP;
1491e97fc193Saliguori     }
1492e97fc193Saliguori 
1493e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
14944534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
1495e97fc193Saliguori }
1496e97fc193Saliguori 
14978a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
14988a426614SKevin Wolf 
149933e3963eSbellard /* commit COW file into the raw image */
150033e3963eSbellard int bdrv_commit(BlockDriverState *bs)
150133e3963eSbellard {
150219cb3738Sbellard     BlockDriver *drv = bs->drv;
15038a426614SKevin Wolf     int64_t sector, total_sectors;
15048a426614SKevin Wolf     int n, ro, open_flags;
15050bce597dSJeff Cody     int ret = 0;
15068a426614SKevin Wolf     uint8_t *buf;
15074dca4b63SNaphtali Sprei     char filename[1024];
150833e3963eSbellard 
150919cb3738Sbellard     if (!drv)
151019cb3738Sbellard         return -ENOMEDIUM;
151133e3963eSbellard 
15124dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
15134dca4b63SNaphtali Sprei         return -ENOTSUP;
15144dca4b63SNaphtali Sprei     }
15154dca4b63SNaphtali Sprei 
15162d3735d3SStefan Hajnoczi     if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
15172d3735d3SStefan Hajnoczi         return -EBUSY;
15182d3735d3SStefan Hajnoczi     }
15192d3735d3SStefan Hajnoczi 
15204dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
15214dca4b63SNaphtali Sprei     strncpy(filename, bs->backing_hd->filename, sizeof(filename));
15224dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
15234dca4b63SNaphtali Sprei 
15244dca4b63SNaphtali Sprei     if (ro) {
15250bce597dSJeff Cody         if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
15260bce597dSJeff Cody             return -EACCES;
15274dca4b63SNaphtali Sprei         }
1528ea2384d3Sbellard     }
1529ea2384d3Sbellard 
15306ea44308SJan Kiszka     total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
15317267c094SAnthony Liguori     buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
15328a426614SKevin Wolf 
15338a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
153405c4af54SStefan Hajnoczi         if (bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
15358a426614SKevin Wolf 
15368a426614SKevin Wolf             if (bdrv_read(bs, sector, buf, n) != 0) {
15374dca4b63SNaphtali Sprei                 ret = -EIO;
15384dca4b63SNaphtali Sprei                 goto ro_cleanup;
153933e3963eSbellard             }
154033e3963eSbellard 
15418a426614SKevin Wolf             if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
15424dca4b63SNaphtali Sprei                 ret = -EIO;
15434dca4b63SNaphtali Sprei                 goto ro_cleanup;
154433e3963eSbellard             }
154533e3963eSbellard         }
154633e3963eSbellard     }
154795389c86Sbellard 
15481d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
15491d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
15501d44952fSChristoph Hellwig         bdrv_flush(bs);
15511d44952fSChristoph Hellwig     }
155295389c86Sbellard 
15533f5075aeSChristoph Hellwig     /*
15543f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
15553f5075aeSChristoph Hellwig      * stable on disk.
15563f5075aeSChristoph Hellwig      */
15573f5075aeSChristoph Hellwig     if (bs->backing_hd)
15583f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
15594dca4b63SNaphtali Sprei 
15604dca4b63SNaphtali Sprei ro_cleanup:
15617267c094SAnthony Liguori     g_free(buf);
15624dca4b63SNaphtali Sprei 
15634dca4b63SNaphtali Sprei     if (ro) {
15640bce597dSJeff Cody         /* ignoring error return here */
15650bce597dSJeff Cody         bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
15664dca4b63SNaphtali Sprei     }
15674dca4b63SNaphtali Sprei 
15681d44952fSChristoph Hellwig     return ret;
156933e3963eSbellard }
157033e3963eSbellard 
1571e8877497SStefan Hajnoczi int bdrv_commit_all(void)
15726ab4b5abSMarkus Armbruster {
15736ab4b5abSMarkus Armbruster     BlockDriverState *bs;
15746ab4b5abSMarkus Armbruster 
15756ab4b5abSMarkus Armbruster     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1576e8877497SStefan Hajnoczi         int ret = bdrv_commit(bs);
1577e8877497SStefan Hajnoczi         if (ret < 0) {
1578e8877497SStefan Hajnoczi             return ret;
15796ab4b5abSMarkus Armbruster         }
15806ab4b5abSMarkus Armbruster     }
1581e8877497SStefan Hajnoczi     return 0;
1582e8877497SStefan Hajnoczi }
15836ab4b5abSMarkus Armbruster 
1584dbffbdcfSStefan Hajnoczi struct BdrvTrackedRequest {
1585dbffbdcfSStefan Hajnoczi     BlockDriverState *bs;
1586dbffbdcfSStefan Hajnoczi     int64_t sector_num;
1587dbffbdcfSStefan Hajnoczi     int nb_sectors;
1588dbffbdcfSStefan Hajnoczi     bool is_write;
1589dbffbdcfSStefan Hajnoczi     QLIST_ENTRY(BdrvTrackedRequest) list;
15905f8b6491SStefan Hajnoczi     Coroutine *co; /* owner, used for deadlock detection */
1591f4658285SStefan Hajnoczi     CoQueue wait_queue; /* coroutines blocked on this request */
1592dbffbdcfSStefan Hajnoczi };
1593dbffbdcfSStefan Hajnoczi 
1594dbffbdcfSStefan Hajnoczi /**
1595dbffbdcfSStefan Hajnoczi  * Remove an active request from the tracked requests list
1596dbffbdcfSStefan Hajnoczi  *
1597dbffbdcfSStefan Hajnoczi  * This function should be called when a tracked request is completing.
1598dbffbdcfSStefan Hajnoczi  */
1599dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req)
1600dbffbdcfSStefan Hajnoczi {
1601dbffbdcfSStefan Hajnoczi     QLIST_REMOVE(req, list);
1602f4658285SStefan Hajnoczi     qemu_co_queue_restart_all(&req->wait_queue);
1603dbffbdcfSStefan Hajnoczi }
1604dbffbdcfSStefan Hajnoczi 
1605dbffbdcfSStefan Hajnoczi /**
1606dbffbdcfSStefan Hajnoczi  * Add an active request to the tracked requests list
1607dbffbdcfSStefan Hajnoczi  */
1608dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req,
1609dbffbdcfSStefan Hajnoczi                                   BlockDriverState *bs,
1610dbffbdcfSStefan Hajnoczi                                   int64_t sector_num,
1611dbffbdcfSStefan Hajnoczi                                   int nb_sectors, bool is_write)
1612dbffbdcfSStefan Hajnoczi {
1613dbffbdcfSStefan Hajnoczi     *req = (BdrvTrackedRequest){
1614dbffbdcfSStefan Hajnoczi         .bs = bs,
1615dbffbdcfSStefan Hajnoczi         .sector_num = sector_num,
1616dbffbdcfSStefan Hajnoczi         .nb_sectors = nb_sectors,
1617dbffbdcfSStefan Hajnoczi         .is_write = is_write,
16185f8b6491SStefan Hajnoczi         .co = qemu_coroutine_self(),
1619dbffbdcfSStefan Hajnoczi     };
1620dbffbdcfSStefan Hajnoczi 
1621f4658285SStefan Hajnoczi     qemu_co_queue_init(&req->wait_queue);
1622f4658285SStefan Hajnoczi 
1623dbffbdcfSStefan Hajnoczi     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
1624dbffbdcfSStefan Hajnoczi }
1625dbffbdcfSStefan Hajnoczi 
1626d83947acSStefan Hajnoczi /**
1627d83947acSStefan Hajnoczi  * Round a region to cluster boundaries
1628d83947acSStefan Hajnoczi  */
1629d83947acSStefan Hajnoczi static void round_to_clusters(BlockDriverState *bs,
1630d83947acSStefan Hajnoczi                               int64_t sector_num, int nb_sectors,
1631d83947acSStefan Hajnoczi                               int64_t *cluster_sector_num,
1632d83947acSStefan Hajnoczi                               int *cluster_nb_sectors)
1633d83947acSStefan Hajnoczi {
1634d83947acSStefan Hajnoczi     BlockDriverInfo bdi;
1635d83947acSStefan Hajnoczi 
1636d83947acSStefan Hajnoczi     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
1637d83947acSStefan Hajnoczi         *cluster_sector_num = sector_num;
1638d83947acSStefan Hajnoczi         *cluster_nb_sectors = nb_sectors;
1639d83947acSStefan Hajnoczi     } else {
1640d83947acSStefan Hajnoczi         int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
1641d83947acSStefan Hajnoczi         *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
1642d83947acSStefan Hajnoczi         *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
1643d83947acSStefan Hajnoczi                                             nb_sectors, c);
1644d83947acSStefan Hajnoczi     }
1645d83947acSStefan Hajnoczi }
1646d83947acSStefan Hajnoczi 
1647f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req,
1648f4658285SStefan Hajnoczi                                      int64_t sector_num, int nb_sectors) {
1649d83947acSStefan Hajnoczi     /*        aaaa   bbbb */
1650d83947acSStefan Hajnoczi     if (sector_num >= req->sector_num + req->nb_sectors) {
1651d83947acSStefan Hajnoczi         return false;
1652d83947acSStefan Hajnoczi     }
1653d83947acSStefan Hajnoczi     /* bbbb   aaaa        */
1654d83947acSStefan Hajnoczi     if (req->sector_num >= sector_num + nb_sectors) {
1655d83947acSStefan Hajnoczi         return false;
1656d83947acSStefan Hajnoczi     }
1657d83947acSStefan Hajnoczi     return true;
1658f4658285SStefan Hajnoczi }
1659f4658285SStefan Hajnoczi 
1660f4658285SStefan Hajnoczi static void coroutine_fn wait_for_overlapping_requests(BlockDriverState *bs,
1661f4658285SStefan Hajnoczi         int64_t sector_num, int nb_sectors)
1662f4658285SStefan Hajnoczi {
1663f4658285SStefan Hajnoczi     BdrvTrackedRequest *req;
1664d83947acSStefan Hajnoczi     int64_t cluster_sector_num;
1665d83947acSStefan Hajnoczi     int cluster_nb_sectors;
1666f4658285SStefan Hajnoczi     bool retry;
1667f4658285SStefan Hajnoczi 
1668d83947acSStefan Hajnoczi     /* If we touch the same cluster it counts as an overlap.  This guarantees
1669d83947acSStefan Hajnoczi      * that allocating writes will be serialized and not race with each other
1670d83947acSStefan Hajnoczi      * for the same cluster.  For example, in copy-on-read it ensures that the
1671d83947acSStefan Hajnoczi      * CoR read and write operations are atomic and guest writes cannot
1672d83947acSStefan Hajnoczi      * interleave between them.
1673d83947acSStefan Hajnoczi      */
1674d83947acSStefan Hajnoczi     round_to_clusters(bs, sector_num, nb_sectors,
1675d83947acSStefan Hajnoczi                       &cluster_sector_num, &cluster_nb_sectors);
1676d83947acSStefan Hajnoczi 
1677f4658285SStefan Hajnoczi     do {
1678f4658285SStefan Hajnoczi         retry = false;
1679f4658285SStefan Hajnoczi         QLIST_FOREACH(req, &bs->tracked_requests, list) {
1680d83947acSStefan Hajnoczi             if (tracked_request_overlaps(req, cluster_sector_num,
1681d83947acSStefan Hajnoczi                                          cluster_nb_sectors)) {
16825f8b6491SStefan Hajnoczi                 /* Hitting this means there was a reentrant request, for
16835f8b6491SStefan Hajnoczi                  * example, a block driver issuing nested requests.  This must
16845f8b6491SStefan Hajnoczi                  * never happen since it means deadlock.
16855f8b6491SStefan Hajnoczi                  */
16865f8b6491SStefan Hajnoczi                 assert(qemu_coroutine_self() != req->co);
16875f8b6491SStefan Hajnoczi 
1688f4658285SStefan Hajnoczi                 qemu_co_queue_wait(&req->wait_queue);
1689f4658285SStefan Hajnoczi                 retry = true;
1690f4658285SStefan Hajnoczi                 break;
1691f4658285SStefan Hajnoczi             }
1692f4658285SStefan Hajnoczi         }
1693f4658285SStefan Hajnoczi     } while (retry);
1694f4658285SStefan Hajnoczi }
1695f4658285SStefan Hajnoczi 
1696756e6736SKevin Wolf /*
1697756e6736SKevin Wolf  * Return values:
1698756e6736SKevin Wolf  * 0        - success
1699756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
1700756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
1701756e6736SKevin Wolf  *            image file header
1702756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
1703756e6736SKevin Wolf  */
1704756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
1705756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
1706756e6736SKevin Wolf {
1707756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
1708469ef350SPaolo Bonzini     int ret;
1709756e6736SKevin Wolf 
17105f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
17115f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
17125f377794SPaolo Bonzini         return -EINVAL;
17135f377794SPaolo Bonzini     }
17145f377794SPaolo Bonzini 
1715756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
1716469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
1717756e6736SKevin Wolf     } else {
1718469ef350SPaolo Bonzini         ret = -ENOTSUP;
1719756e6736SKevin Wolf     }
1720469ef350SPaolo Bonzini 
1721469ef350SPaolo Bonzini     if (ret == 0) {
1722469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1723469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1724469ef350SPaolo Bonzini     }
1725469ef350SPaolo Bonzini     return ret;
1726756e6736SKevin Wolf }
1727756e6736SKevin Wolf 
17286ebdcee2SJeff Cody /*
17296ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
17306ebdcee2SJeff Cody  *
17316ebdcee2SJeff Cody  * active is the current topmost image.
17326ebdcee2SJeff Cody  *
17336ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
17346ebdcee2SJeff Cody  * or if active == bs.
17356ebdcee2SJeff Cody  */
17366ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
17376ebdcee2SJeff Cody                                     BlockDriverState *bs)
17386ebdcee2SJeff Cody {
17396ebdcee2SJeff Cody     BlockDriverState *overlay = NULL;
17406ebdcee2SJeff Cody     BlockDriverState *intermediate;
17416ebdcee2SJeff Cody 
17426ebdcee2SJeff Cody     assert(active != NULL);
17436ebdcee2SJeff Cody     assert(bs != NULL);
17446ebdcee2SJeff Cody 
17456ebdcee2SJeff Cody     /* if bs is the same as active, then by definition it has no overlay
17466ebdcee2SJeff Cody      */
17476ebdcee2SJeff Cody     if (active == bs) {
17486ebdcee2SJeff Cody         return NULL;
17496ebdcee2SJeff Cody     }
17506ebdcee2SJeff Cody 
17516ebdcee2SJeff Cody     intermediate = active;
17526ebdcee2SJeff Cody     while (intermediate->backing_hd) {
17536ebdcee2SJeff Cody         if (intermediate->backing_hd == bs) {
17546ebdcee2SJeff Cody             overlay = intermediate;
17556ebdcee2SJeff Cody             break;
17566ebdcee2SJeff Cody         }
17576ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
17586ebdcee2SJeff Cody     }
17596ebdcee2SJeff Cody 
17606ebdcee2SJeff Cody     return overlay;
17616ebdcee2SJeff Cody }
17626ebdcee2SJeff Cody 
17636ebdcee2SJeff Cody typedef struct BlkIntermediateStates {
17646ebdcee2SJeff Cody     BlockDriverState *bs;
17656ebdcee2SJeff Cody     QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
17666ebdcee2SJeff Cody } BlkIntermediateStates;
17676ebdcee2SJeff Cody 
17686ebdcee2SJeff Cody 
17696ebdcee2SJeff Cody /*
17706ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
17716ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
17726ebdcee2SJeff Cody  *
17736ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
17746ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
17756ebdcee2SJeff Cody  *
17766ebdcee2SJeff Cody  * E.g., this will convert the following chain:
17776ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
17786ebdcee2SJeff Cody  *
17796ebdcee2SJeff Cody  * to
17806ebdcee2SJeff Cody  *
17816ebdcee2SJeff Cody  * bottom <- base <- active
17826ebdcee2SJeff Cody  *
17836ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
17846ebdcee2SJeff Cody  *
17856ebdcee2SJeff Cody  * base <- intermediate <- top <- active
17866ebdcee2SJeff Cody  *
17876ebdcee2SJeff Cody  * to
17886ebdcee2SJeff Cody  *
17896ebdcee2SJeff Cody  * base <- active
17906ebdcee2SJeff Cody  *
17916ebdcee2SJeff Cody  * Error conditions:
17926ebdcee2SJeff Cody  *  if active == top, that is considered an error
17936ebdcee2SJeff Cody  *
17946ebdcee2SJeff Cody  */
17956ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
17966ebdcee2SJeff Cody                            BlockDriverState *base)
17976ebdcee2SJeff Cody {
17986ebdcee2SJeff Cody     BlockDriverState *intermediate;
17996ebdcee2SJeff Cody     BlockDriverState *base_bs = NULL;
18006ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
18016ebdcee2SJeff Cody     BlkIntermediateStates *intermediate_state, *next;
18026ebdcee2SJeff Cody     int ret = -EIO;
18036ebdcee2SJeff Cody 
18046ebdcee2SJeff Cody     QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
18056ebdcee2SJeff Cody     QSIMPLEQ_INIT(&states_to_delete);
18066ebdcee2SJeff Cody 
18076ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
18086ebdcee2SJeff Cody         goto exit;
18096ebdcee2SJeff Cody     }
18106ebdcee2SJeff Cody 
18116ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
18126ebdcee2SJeff Cody 
18136ebdcee2SJeff Cody     if (new_top_bs == NULL) {
18146ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
18156ebdcee2SJeff Cody         goto exit;
18166ebdcee2SJeff Cody     }
18176ebdcee2SJeff Cody 
18186ebdcee2SJeff Cody     /* special case of new_top_bs->backing_hd already pointing to base - nothing
18196ebdcee2SJeff Cody      * to do, no intermediate images */
18206ebdcee2SJeff Cody     if (new_top_bs->backing_hd == base) {
18216ebdcee2SJeff Cody         ret = 0;
18226ebdcee2SJeff Cody         goto exit;
18236ebdcee2SJeff Cody     }
18246ebdcee2SJeff Cody 
18256ebdcee2SJeff Cody     intermediate = top;
18266ebdcee2SJeff Cody 
18276ebdcee2SJeff Cody     /* now we will go down through the list, and add each BDS we find
18286ebdcee2SJeff Cody      * into our deletion queue, until we hit the 'base'
18296ebdcee2SJeff Cody      */
18306ebdcee2SJeff Cody     while (intermediate) {
18316ebdcee2SJeff Cody         intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
18326ebdcee2SJeff Cody         intermediate_state->bs = intermediate;
18336ebdcee2SJeff Cody         QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
18346ebdcee2SJeff Cody 
18356ebdcee2SJeff Cody         if (intermediate->backing_hd == base) {
18366ebdcee2SJeff Cody             base_bs = intermediate->backing_hd;
18376ebdcee2SJeff Cody             break;
18386ebdcee2SJeff Cody         }
18396ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
18406ebdcee2SJeff Cody     }
18416ebdcee2SJeff Cody     if (base_bs == NULL) {
18426ebdcee2SJeff Cody         /* something went wrong, we did not end at the base. safely
18436ebdcee2SJeff Cody          * unravel everything, and exit with error */
18446ebdcee2SJeff Cody         goto exit;
18456ebdcee2SJeff Cody     }
18466ebdcee2SJeff Cody 
18476ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
18486ebdcee2SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
18496ebdcee2SJeff Cody                                    base_bs->drv ? base_bs->drv->format_name : "");
18506ebdcee2SJeff Cody     if (ret) {
18516ebdcee2SJeff Cody         goto exit;
18526ebdcee2SJeff Cody     }
18536ebdcee2SJeff Cody     new_top_bs->backing_hd = base_bs;
18546ebdcee2SJeff Cody 
18556ebdcee2SJeff Cody 
18566ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
18576ebdcee2SJeff Cody         /* so that bdrv_close() does not recursively close the chain */
18586ebdcee2SJeff Cody         intermediate_state->bs->backing_hd = NULL;
18596ebdcee2SJeff Cody         bdrv_delete(intermediate_state->bs);
18606ebdcee2SJeff Cody     }
18616ebdcee2SJeff Cody     ret = 0;
18626ebdcee2SJeff Cody 
18636ebdcee2SJeff Cody exit:
18646ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
18656ebdcee2SJeff Cody         g_free(intermediate_state);
18666ebdcee2SJeff Cody     }
18676ebdcee2SJeff Cody     return ret;
18686ebdcee2SJeff Cody }
18696ebdcee2SJeff Cody 
18706ebdcee2SJeff Cody 
187171d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
187271d0770cSaliguori                                    size_t size)
187371d0770cSaliguori {
187471d0770cSaliguori     int64_t len;
187571d0770cSaliguori 
187671d0770cSaliguori     if (!bdrv_is_inserted(bs))
187771d0770cSaliguori         return -ENOMEDIUM;
187871d0770cSaliguori 
187971d0770cSaliguori     if (bs->growable)
188071d0770cSaliguori         return 0;
188171d0770cSaliguori 
188271d0770cSaliguori     len = bdrv_getlength(bs);
188371d0770cSaliguori 
1884fbb7b4e0SKevin Wolf     if (offset < 0)
1885fbb7b4e0SKevin Wolf         return -EIO;
1886fbb7b4e0SKevin Wolf 
1887fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
188871d0770cSaliguori         return -EIO;
188971d0770cSaliguori 
189071d0770cSaliguori     return 0;
189171d0770cSaliguori }
189271d0770cSaliguori 
189371d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
189471d0770cSaliguori                               int nb_sectors)
189571d0770cSaliguori {
1896eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
1897eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
189871d0770cSaliguori }
189971d0770cSaliguori 
19001c9805a3SStefan Hajnoczi typedef struct RwCo {
19011c9805a3SStefan Hajnoczi     BlockDriverState *bs;
19021c9805a3SStefan Hajnoczi     int64_t sector_num;
19031c9805a3SStefan Hajnoczi     int nb_sectors;
19041c9805a3SStefan Hajnoczi     QEMUIOVector *qiov;
19051c9805a3SStefan Hajnoczi     bool is_write;
19061c9805a3SStefan Hajnoczi     int ret;
19071c9805a3SStefan Hajnoczi } RwCo;
19081c9805a3SStefan Hajnoczi 
19091c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque)
1910fc01f7e7Sbellard {
19111c9805a3SStefan Hajnoczi     RwCo *rwco = opaque;
1912fc01f7e7Sbellard 
19131c9805a3SStefan Hajnoczi     if (!rwco->is_write) {
19141c9805a3SStefan Hajnoczi         rwco->ret = bdrv_co_do_readv(rwco->bs, rwco->sector_num,
1915470c0504SStefan Hajnoczi                                      rwco->nb_sectors, rwco->qiov, 0);
19161c9805a3SStefan Hajnoczi     } else {
19171c9805a3SStefan Hajnoczi         rwco->ret = bdrv_co_do_writev(rwco->bs, rwco->sector_num,
1918f08f2ddaSStefan Hajnoczi                                       rwco->nb_sectors, rwco->qiov, 0);
19191c9805a3SStefan Hajnoczi     }
19201c9805a3SStefan Hajnoczi }
1921e7a8a783SKevin Wolf 
19221c9805a3SStefan Hajnoczi /*
19231c9805a3SStefan Hajnoczi  * Process a synchronous request using coroutines
19241c9805a3SStefan Hajnoczi  */
19251c9805a3SStefan Hajnoczi static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
19261c9805a3SStefan Hajnoczi                       int nb_sectors, bool is_write)
19271c9805a3SStefan Hajnoczi {
1928e7a8a783SKevin Wolf     QEMUIOVector qiov;
1929e7a8a783SKevin Wolf     struct iovec iov = {
1930e7a8a783SKevin Wolf         .iov_base = (void *)buf,
1931e7a8a783SKevin Wolf         .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1932e7a8a783SKevin Wolf     };
19331c9805a3SStefan Hajnoczi     Coroutine *co;
19341c9805a3SStefan Hajnoczi     RwCo rwco = {
19351c9805a3SStefan Hajnoczi         .bs = bs,
19361c9805a3SStefan Hajnoczi         .sector_num = sector_num,
19371c9805a3SStefan Hajnoczi         .nb_sectors = nb_sectors,
19381c9805a3SStefan Hajnoczi         .qiov = &qiov,
19391c9805a3SStefan Hajnoczi         .is_write = is_write,
19401c9805a3SStefan Hajnoczi         .ret = NOT_DONE,
19411c9805a3SStefan Hajnoczi     };
1942e7a8a783SKevin Wolf 
1943e7a8a783SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
19441c9805a3SStefan Hajnoczi 
1945498e386cSZhi Yong Wu     /**
1946498e386cSZhi Yong Wu      * In sync call context, when the vcpu is blocked, this throttling timer
1947498e386cSZhi Yong Wu      * will not fire; so the I/O throttling function has to be disabled here
1948498e386cSZhi Yong Wu      * if it has been enabled.
1949498e386cSZhi Yong Wu      */
1950498e386cSZhi Yong Wu     if (bs->io_limits_enabled) {
1951498e386cSZhi Yong Wu         fprintf(stderr, "Disabling I/O throttling on '%s' due "
1952498e386cSZhi Yong Wu                         "to synchronous I/O.\n", bdrv_get_device_name(bs));
1953498e386cSZhi Yong Wu         bdrv_io_limits_disable(bs);
1954498e386cSZhi Yong Wu     }
1955498e386cSZhi Yong Wu 
19561c9805a3SStefan Hajnoczi     if (qemu_in_coroutine()) {
19571c9805a3SStefan Hajnoczi         /* Fast-path if already in coroutine context */
19581c9805a3SStefan Hajnoczi         bdrv_rw_co_entry(&rwco);
19591c9805a3SStefan Hajnoczi     } else {
19601c9805a3SStefan Hajnoczi         co = qemu_coroutine_create(bdrv_rw_co_entry);
19611c9805a3SStefan Hajnoczi         qemu_coroutine_enter(co, &rwco);
19621c9805a3SStefan Hajnoczi         while (rwco.ret == NOT_DONE) {
19631c9805a3SStefan Hajnoczi             qemu_aio_wait();
19641c9805a3SStefan Hajnoczi         }
19651c9805a3SStefan Hajnoczi     }
19661c9805a3SStefan Hajnoczi     return rwco.ret;
1967e7a8a783SKevin Wolf }
1968e7a8a783SKevin Wolf 
19691c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */
19701c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num,
19711c9805a3SStefan Hajnoczi               uint8_t *buf, int nb_sectors)
19721c9805a3SStefan Hajnoczi {
19731c9805a3SStefan Hajnoczi     return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false);
197483f64091Sbellard }
1975fc01f7e7Sbellard 
197607d27a44SMarkus Armbruster /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
197707d27a44SMarkus Armbruster int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
197807d27a44SMarkus Armbruster                           uint8_t *buf, int nb_sectors)
197907d27a44SMarkus Armbruster {
198007d27a44SMarkus Armbruster     bool enabled;
198107d27a44SMarkus Armbruster     int ret;
198207d27a44SMarkus Armbruster 
198307d27a44SMarkus Armbruster     enabled = bs->io_limits_enabled;
198407d27a44SMarkus Armbruster     bs->io_limits_enabled = false;
198507d27a44SMarkus Armbruster     ret = bdrv_read(bs, 0, buf, 1);
198607d27a44SMarkus Armbruster     bs->io_limits_enabled = enabled;
198707d27a44SMarkus Armbruster     return ret;
198807d27a44SMarkus Armbruster }
198907d27a44SMarkus Armbruster 
199071df14fcSPaolo Bonzini #define BITS_PER_LONG  (sizeof(unsigned long) * 8)
199171df14fcSPaolo Bonzini 
19927cd1e32aSlirans@il.ibm.com static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
19937cd1e32aSlirans@il.ibm.com                              int nb_sectors, int dirty)
19947cd1e32aSlirans@il.ibm.com {
19957cd1e32aSlirans@il.ibm.com     int64_t start, end;
1996c6d22830SJan Kiszka     unsigned long val, idx, bit;
1997a55eb92cSJan Kiszka 
19986ea44308SJan Kiszka     start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
1999c6d22830SJan Kiszka     end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
20007cd1e32aSlirans@il.ibm.com 
20017cd1e32aSlirans@il.ibm.com     for (; start <= end; start++) {
200271df14fcSPaolo Bonzini         idx = start / BITS_PER_LONG;
200371df14fcSPaolo Bonzini         bit = start % BITS_PER_LONG;
2004c6d22830SJan Kiszka         val = bs->dirty_bitmap[idx];
2005c6d22830SJan Kiszka         if (dirty) {
20066d59fec1SMarcelo Tosatti             if (!(val & (1UL << bit))) {
2007aaa0eb75SLiran Schour                 bs->dirty_count++;
20086d59fec1SMarcelo Tosatti                 val |= 1UL << bit;
2009aaa0eb75SLiran Schour             }
2010c6d22830SJan Kiszka         } else {
20116d59fec1SMarcelo Tosatti             if (val & (1UL << bit)) {
2012aaa0eb75SLiran Schour                 bs->dirty_count--;
20136d59fec1SMarcelo Tosatti                 val &= ~(1UL << bit);
2014c6d22830SJan Kiszka             }
2015aaa0eb75SLiran Schour         }
2016c6d22830SJan Kiszka         bs->dirty_bitmap[idx] = val;
20177cd1e32aSlirans@il.ibm.com     }
20187cd1e32aSlirans@il.ibm.com }
20197cd1e32aSlirans@il.ibm.com 
202019cb3738Sbellard /* Return < 0 if error. Important errors are:
202119cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
202219cb3738Sbellard   -ENOMEDIUM   No media inserted.
202319cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
202419cb3738Sbellard   -EACCES      Trying to write a read-only device
202519cb3738Sbellard */
2026fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
2027fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
2028fc01f7e7Sbellard {
20291c9805a3SStefan Hajnoczi     return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true);
203083f64091Sbellard }
203183f64091Sbellard 
2032eda578e5Saliguori int bdrv_pread(BlockDriverState *bs, int64_t offset,
2033eda578e5Saliguori                void *buf, int count1)
203483f64091Sbellard {
20356ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
203683f64091Sbellard     int len, nb_sectors, count;
203783f64091Sbellard     int64_t sector_num;
20389a8c4cceSKevin Wolf     int ret;
203983f64091Sbellard 
204083f64091Sbellard     count = count1;
204183f64091Sbellard     /* first read to align to sector start */
20426ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
204383f64091Sbellard     if (len > count)
204483f64091Sbellard         len = count;
20456ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
204683f64091Sbellard     if (len > 0) {
20479a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
20489a8c4cceSKevin Wolf             return ret;
20496ea44308SJan Kiszka         memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
205083f64091Sbellard         count -= len;
205183f64091Sbellard         if (count == 0)
205283f64091Sbellard             return count1;
205383f64091Sbellard         sector_num++;
205483f64091Sbellard         buf += len;
205583f64091Sbellard     }
205683f64091Sbellard 
205783f64091Sbellard     /* read the sectors "in place" */
20586ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
205983f64091Sbellard     if (nb_sectors > 0) {
20609a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
20619a8c4cceSKevin Wolf             return ret;
206283f64091Sbellard         sector_num += nb_sectors;
20636ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
206483f64091Sbellard         buf += len;
206583f64091Sbellard         count -= len;
206683f64091Sbellard     }
206783f64091Sbellard 
206883f64091Sbellard     /* add data from the last sector */
206983f64091Sbellard     if (count > 0) {
20709a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
20719a8c4cceSKevin Wolf             return ret;
207283f64091Sbellard         memcpy(buf, tmp_buf, count);
207383f64091Sbellard     }
207483f64091Sbellard     return count1;
207583f64091Sbellard }
207683f64091Sbellard 
2077eda578e5Saliguori int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
2078eda578e5Saliguori                 const void *buf, int count1)
207983f64091Sbellard {
20806ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
208183f64091Sbellard     int len, nb_sectors, count;
208283f64091Sbellard     int64_t sector_num;
20839a8c4cceSKevin Wolf     int ret;
208483f64091Sbellard 
208583f64091Sbellard     count = count1;
208683f64091Sbellard     /* first write to align to sector start */
20876ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
208883f64091Sbellard     if (len > count)
208983f64091Sbellard         len = count;
20906ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
209183f64091Sbellard     if (len > 0) {
20929a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
20939a8c4cceSKevin Wolf             return ret;
20946ea44308SJan Kiszka         memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
20959a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
20969a8c4cceSKevin Wolf             return ret;
209783f64091Sbellard         count -= len;
209883f64091Sbellard         if (count == 0)
209983f64091Sbellard             return count1;
210083f64091Sbellard         sector_num++;
210183f64091Sbellard         buf += len;
210283f64091Sbellard     }
210383f64091Sbellard 
210483f64091Sbellard     /* write the sectors "in place" */
21056ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
210683f64091Sbellard     if (nb_sectors > 0) {
21079a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
21089a8c4cceSKevin Wolf             return ret;
210983f64091Sbellard         sector_num += nb_sectors;
21106ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
211183f64091Sbellard         buf += len;
211283f64091Sbellard         count -= len;
211383f64091Sbellard     }
211483f64091Sbellard 
211583f64091Sbellard     /* add data from the last sector */
211683f64091Sbellard     if (count > 0) {
21179a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
21189a8c4cceSKevin Wolf             return ret;
211983f64091Sbellard         memcpy(tmp_buf, buf, count);
21209a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
21219a8c4cceSKevin Wolf             return ret;
212283f64091Sbellard     }
212383f64091Sbellard     return count1;
212483f64091Sbellard }
212583f64091Sbellard 
2126f08145feSKevin Wolf /*
2127f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
2128f08145feSKevin Wolf  * request (acts as a barrier)
2129f08145feSKevin Wolf  *
2130f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
2131f08145feSKevin Wolf  */
2132f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2133f08145feSKevin Wolf     const void *buf, int count)
2134f08145feSKevin Wolf {
2135f08145feSKevin Wolf     int ret;
2136f08145feSKevin Wolf 
2137f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
2138f08145feSKevin Wolf     if (ret < 0) {
2139f08145feSKevin Wolf         return ret;
2140f08145feSKevin Wolf     }
2141f08145feSKevin Wolf 
2142f05fa4adSPaolo Bonzini     /* No flush needed for cache modes that already do it */
2143f05fa4adSPaolo Bonzini     if (bs->enable_write_cache) {
2144f08145feSKevin Wolf         bdrv_flush(bs);
2145f08145feSKevin Wolf     }
2146f08145feSKevin Wolf 
2147f08145feSKevin Wolf     return 0;
2148f08145feSKevin Wolf }
2149f08145feSKevin Wolf 
2150470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
2151ab185921SStefan Hajnoczi         int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2152ab185921SStefan Hajnoczi {
2153ab185921SStefan Hajnoczi     /* Perform I/O through a temporary buffer so that users who scribble over
2154ab185921SStefan Hajnoczi      * their read buffer while the operation is in progress do not end up
2155ab185921SStefan Hajnoczi      * modifying the image file.  This is critical for zero-copy guest I/O
2156ab185921SStefan Hajnoczi      * where anything might happen inside guest memory.
2157ab185921SStefan Hajnoczi      */
2158ab185921SStefan Hajnoczi     void *bounce_buffer;
2159ab185921SStefan Hajnoczi 
216079c053bdSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2161ab185921SStefan Hajnoczi     struct iovec iov;
2162ab185921SStefan Hajnoczi     QEMUIOVector bounce_qiov;
2163ab185921SStefan Hajnoczi     int64_t cluster_sector_num;
2164ab185921SStefan Hajnoczi     int cluster_nb_sectors;
2165ab185921SStefan Hajnoczi     size_t skip_bytes;
2166ab185921SStefan Hajnoczi     int ret;
2167ab185921SStefan Hajnoczi 
2168ab185921SStefan Hajnoczi     /* Cover entire cluster so no additional backing file I/O is required when
2169ab185921SStefan Hajnoczi      * allocating cluster in the image file.
2170ab185921SStefan Hajnoczi      */
2171ab185921SStefan Hajnoczi     round_to_clusters(bs, sector_num, nb_sectors,
2172ab185921SStefan Hajnoczi                       &cluster_sector_num, &cluster_nb_sectors);
2173ab185921SStefan Hajnoczi 
2174470c0504SStefan Hajnoczi     trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2175ab185921SStefan Hajnoczi                                    cluster_sector_num, cluster_nb_sectors);
2176ab185921SStefan Hajnoczi 
2177ab185921SStefan Hajnoczi     iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2178ab185921SStefan Hajnoczi     iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
2179ab185921SStefan Hajnoczi     qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2180ab185921SStefan Hajnoczi 
218179c053bdSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2182ab185921SStefan Hajnoczi                              &bounce_qiov);
2183ab185921SStefan Hajnoczi     if (ret < 0) {
2184ab185921SStefan Hajnoczi         goto err;
2185ab185921SStefan Hajnoczi     }
2186ab185921SStefan Hajnoczi 
218779c053bdSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes &&
218879c053bdSStefan Hajnoczi         buffer_is_zero(bounce_buffer, iov.iov_len)) {
2189621f0589SKevin Wolf         ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
219079c053bdSStefan Hajnoczi                                       cluster_nb_sectors);
219179c053bdSStefan Hajnoczi     } else {
2192f05fa4adSPaolo Bonzini         /* This does not change the data on the disk, it is not necessary
2193f05fa4adSPaolo Bonzini          * to flush even in cache=writethrough mode.
2194f05fa4adSPaolo Bonzini          */
219579c053bdSStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
2196ab185921SStefan Hajnoczi                                   &bounce_qiov);
219779c053bdSStefan Hajnoczi     }
219879c053bdSStefan Hajnoczi 
2199ab185921SStefan Hajnoczi     if (ret < 0) {
2200ab185921SStefan Hajnoczi         /* It might be okay to ignore write errors for guest requests.  If this
2201ab185921SStefan Hajnoczi          * is a deliberate copy-on-read then we don't want to ignore the error.
2202ab185921SStefan Hajnoczi          * Simply report it in all cases.
2203ab185921SStefan Hajnoczi          */
2204ab185921SStefan Hajnoczi         goto err;
2205ab185921SStefan Hajnoczi     }
2206ab185921SStefan Hajnoczi 
2207ab185921SStefan Hajnoczi     skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
220803396148SMichael Tokarev     qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
2209ab185921SStefan Hajnoczi                         nb_sectors * BDRV_SECTOR_SIZE);
2210ab185921SStefan Hajnoczi 
2211ab185921SStefan Hajnoczi err:
2212ab185921SStefan Hajnoczi     qemu_vfree(bounce_buffer);
2213ab185921SStefan Hajnoczi     return ret;
2214ab185921SStefan Hajnoczi }
2215ab185921SStefan Hajnoczi 
2216c5fbe571SStefan Hajnoczi /*
2217c5fbe571SStefan Hajnoczi  * Handle a read request in coroutine context
2218c5fbe571SStefan Hajnoczi  */
2219c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
2220470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2221470c0504SStefan Hajnoczi     BdrvRequestFlags flags)
2222da1fa91dSKevin Wolf {
2223da1fa91dSKevin Wolf     BlockDriver *drv = bs->drv;
2224dbffbdcfSStefan Hajnoczi     BdrvTrackedRequest req;
2225dbffbdcfSStefan Hajnoczi     int ret;
2226da1fa91dSKevin Wolf 
2227da1fa91dSKevin Wolf     if (!drv) {
2228da1fa91dSKevin Wolf         return -ENOMEDIUM;
2229da1fa91dSKevin Wolf     }
2230da1fa91dSKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2231da1fa91dSKevin Wolf         return -EIO;
2232da1fa91dSKevin Wolf     }
2233da1fa91dSKevin Wolf 
223498f90dbaSZhi Yong Wu     /* throttling disk read I/O */
223598f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
223698f90dbaSZhi Yong Wu         bdrv_io_limits_intercept(bs, false, nb_sectors);
223798f90dbaSZhi Yong Wu     }
223898f90dbaSZhi Yong Wu 
2239f4658285SStefan Hajnoczi     if (bs->copy_on_read) {
2240470c0504SStefan Hajnoczi         flags |= BDRV_REQ_COPY_ON_READ;
2241470c0504SStefan Hajnoczi     }
2242470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2243470c0504SStefan Hajnoczi         bs->copy_on_read_in_flight++;
2244470c0504SStefan Hajnoczi     }
2245470c0504SStefan Hajnoczi 
2246470c0504SStefan Hajnoczi     if (bs->copy_on_read_in_flight) {
2247f4658285SStefan Hajnoczi         wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2248f4658285SStefan Hajnoczi     }
2249f4658285SStefan Hajnoczi 
2250dbffbdcfSStefan Hajnoczi     tracked_request_begin(&req, bs, sector_num, nb_sectors, false);
2251ab185921SStefan Hajnoczi 
2252470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2253ab185921SStefan Hajnoczi         int pnum;
2254ab185921SStefan Hajnoczi 
2255ab185921SStefan Hajnoczi         ret = bdrv_co_is_allocated(bs, sector_num, nb_sectors, &pnum);
2256ab185921SStefan Hajnoczi         if (ret < 0) {
2257ab185921SStefan Hajnoczi             goto out;
2258ab185921SStefan Hajnoczi         }
2259ab185921SStefan Hajnoczi 
2260ab185921SStefan Hajnoczi         if (!ret || pnum != nb_sectors) {
2261470c0504SStefan Hajnoczi             ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
2262ab185921SStefan Hajnoczi             goto out;
2263ab185921SStefan Hajnoczi         }
2264ab185921SStefan Hajnoczi     }
2265ab185921SStefan Hajnoczi 
2266dbffbdcfSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
2267ab185921SStefan Hajnoczi 
2268ab185921SStefan Hajnoczi out:
2269dbffbdcfSStefan Hajnoczi     tracked_request_end(&req);
2270470c0504SStefan Hajnoczi 
2271470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2272470c0504SStefan Hajnoczi         bs->copy_on_read_in_flight--;
2273470c0504SStefan Hajnoczi     }
2274470c0504SStefan Hajnoczi 
2275dbffbdcfSStefan Hajnoczi     return ret;
2276da1fa91dSKevin Wolf }
2277da1fa91dSKevin Wolf 
2278c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
2279da1fa91dSKevin Wolf     int nb_sectors, QEMUIOVector *qiov)
2280da1fa91dSKevin Wolf {
2281c5fbe571SStefan Hajnoczi     trace_bdrv_co_readv(bs, sector_num, nb_sectors);
2282da1fa91dSKevin Wolf 
2283470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
2284470c0504SStefan Hajnoczi }
2285470c0504SStefan Hajnoczi 
2286470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
2287470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2288470c0504SStefan Hajnoczi {
2289470c0504SStefan Hajnoczi     trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
2290470c0504SStefan Hajnoczi 
2291470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
2292470c0504SStefan Hajnoczi                             BDRV_REQ_COPY_ON_READ);
2293c5fbe571SStefan Hajnoczi }
2294c5fbe571SStefan Hajnoczi 
2295f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
2296f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors)
2297f08f2ddaSStefan Hajnoczi {
2298f08f2ddaSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2299f08f2ddaSStefan Hajnoczi     QEMUIOVector qiov;
2300f08f2ddaSStefan Hajnoczi     struct iovec iov;
2301f08f2ddaSStefan Hajnoczi     int ret;
2302f08f2ddaSStefan Hajnoczi 
2303621f0589SKevin Wolf     /* TODO Emulate only part of misaligned requests instead of letting block
2304621f0589SKevin Wolf      * drivers return -ENOTSUP and emulate everything */
2305621f0589SKevin Wolf 
2306f08f2ddaSStefan Hajnoczi     /* First try the efficient write zeroes operation */
2307f08f2ddaSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes) {
2308621f0589SKevin Wolf         ret = drv->bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2309621f0589SKevin Wolf         if (ret != -ENOTSUP) {
2310621f0589SKevin Wolf             return ret;
2311621f0589SKevin Wolf         }
2312f08f2ddaSStefan Hajnoczi     }
2313f08f2ddaSStefan Hajnoczi 
2314f08f2ddaSStefan Hajnoczi     /* Fall back to bounce buffer if write zeroes is unsupported */
2315f08f2ddaSStefan Hajnoczi     iov.iov_len  = nb_sectors * BDRV_SECTOR_SIZE;
2316f08f2ddaSStefan Hajnoczi     iov.iov_base = qemu_blockalign(bs, iov.iov_len);
2317f08f2ddaSStefan Hajnoczi     memset(iov.iov_base, 0, iov.iov_len);
2318f08f2ddaSStefan Hajnoczi     qemu_iovec_init_external(&qiov, &iov, 1);
2319f08f2ddaSStefan Hajnoczi 
2320f08f2ddaSStefan Hajnoczi     ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
2321f08f2ddaSStefan Hajnoczi 
2322f08f2ddaSStefan Hajnoczi     qemu_vfree(iov.iov_base);
2323f08f2ddaSStefan Hajnoczi     return ret;
2324f08f2ddaSStefan Hajnoczi }
2325f08f2ddaSStefan Hajnoczi 
2326c5fbe571SStefan Hajnoczi /*
2327c5fbe571SStefan Hajnoczi  * Handle a write request in coroutine context
2328c5fbe571SStefan Hajnoczi  */
2329c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
2330f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2331f08f2ddaSStefan Hajnoczi     BdrvRequestFlags flags)
2332c5fbe571SStefan Hajnoczi {
2333c5fbe571SStefan Hajnoczi     BlockDriver *drv = bs->drv;
2334dbffbdcfSStefan Hajnoczi     BdrvTrackedRequest req;
23356b7cb247SStefan Hajnoczi     int ret;
2336da1fa91dSKevin Wolf 
2337da1fa91dSKevin Wolf     if (!bs->drv) {
2338da1fa91dSKevin Wolf         return -ENOMEDIUM;
2339da1fa91dSKevin Wolf     }
2340da1fa91dSKevin Wolf     if (bs->read_only) {
2341da1fa91dSKevin Wolf         return -EACCES;
2342da1fa91dSKevin Wolf     }
2343da1fa91dSKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2344da1fa91dSKevin Wolf         return -EIO;
2345da1fa91dSKevin Wolf     }
2346da1fa91dSKevin Wolf 
234798f90dbaSZhi Yong Wu     /* throttling disk write I/O */
234898f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
234998f90dbaSZhi Yong Wu         bdrv_io_limits_intercept(bs, true, nb_sectors);
235098f90dbaSZhi Yong Wu     }
235198f90dbaSZhi Yong Wu 
2352470c0504SStefan Hajnoczi     if (bs->copy_on_read_in_flight) {
2353f4658285SStefan Hajnoczi         wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2354f4658285SStefan Hajnoczi     }
2355f4658285SStefan Hajnoczi 
2356dbffbdcfSStefan Hajnoczi     tracked_request_begin(&req, bs, sector_num, nb_sectors, true);
2357dbffbdcfSStefan Hajnoczi 
2358f08f2ddaSStefan Hajnoczi     if (flags & BDRV_REQ_ZERO_WRITE) {
2359f08f2ddaSStefan Hajnoczi         ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors);
2360f08f2ddaSStefan Hajnoczi     } else {
23616b7cb247SStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
2362f08f2ddaSStefan Hajnoczi     }
23636b7cb247SStefan Hajnoczi 
2364f05fa4adSPaolo Bonzini     if (ret == 0 && !bs->enable_write_cache) {
2365f05fa4adSPaolo Bonzini         ret = bdrv_co_flush(bs);
2366f05fa4adSPaolo Bonzini     }
2367f05fa4adSPaolo Bonzini 
2368da1fa91dSKevin Wolf     if (bs->dirty_bitmap) {
2369da1fa91dSKevin Wolf         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
2370da1fa91dSKevin Wolf     }
2371da1fa91dSKevin Wolf 
2372da1fa91dSKevin Wolf     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2373da1fa91dSKevin Wolf         bs->wr_highest_sector = sector_num + nb_sectors - 1;
2374da1fa91dSKevin Wolf     }
2375da1fa91dSKevin Wolf 
2376dbffbdcfSStefan Hajnoczi     tracked_request_end(&req);
2377dbffbdcfSStefan Hajnoczi 
23786b7cb247SStefan Hajnoczi     return ret;
2379da1fa91dSKevin Wolf }
2380da1fa91dSKevin Wolf 
2381c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
2382c5fbe571SStefan Hajnoczi     int nb_sectors, QEMUIOVector *qiov)
2383c5fbe571SStefan Hajnoczi {
2384c5fbe571SStefan Hajnoczi     trace_bdrv_co_writev(bs, sector_num, nb_sectors);
2385c5fbe571SStefan Hajnoczi 
2386f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
2387f08f2ddaSStefan Hajnoczi }
2388f08f2ddaSStefan Hajnoczi 
2389f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
2390f08f2ddaSStefan Hajnoczi                                       int64_t sector_num, int nb_sectors)
2391f08f2ddaSStefan Hajnoczi {
2392f08f2ddaSStefan Hajnoczi     trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2393f08f2ddaSStefan Hajnoczi 
2394f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
2395f08f2ddaSStefan Hajnoczi                              BDRV_REQ_ZERO_WRITE);
2396c5fbe571SStefan Hajnoczi }
2397c5fbe571SStefan Hajnoczi 
239883f64091Sbellard /**
239983f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
240083f64091Sbellard  */
240183f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
240283f64091Sbellard {
240383f64091Sbellard     BlockDriver *drv = bs->drv;
240451762288SStefan Hajnoczi     int ret;
240583f64091Sbellard     if (!drv)
240619cb3738Sbellard         return -ENOMEDIUM;
240783f64091Sbellard     if (!drv->bdrv_truncate)
240883f64091Sbellard         return -ENOTSUP;
240959f2689dSNaphtali Sprei     if (bs->read_only)
241059f2689dSNaphtali Sprei         return -EACCES;
24118591675fSMarcelo Tosatti     if (bdrv_in_use(bs))
24128591675fSMarcelo Tosatti         return -EBUSY;
241351762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
241451762288SStefan Hajnoczi     if (ret == 0) {
241551762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2416145feb17SMarkus Armbruster         bdrv_dev_resize_cb(bs);
241751762288SStefan Hajnoczi     }
241851762288SStefan Hajnoczi     return ret;
241983f64091Sbellard }
242083f64091Sbellard 
242183f64091Sbellard /**
24224a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
24234a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
24244a1d5e1fSFam Zheng  */
24254a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
24264a1d5e1fSFam Zheng {
24274a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
24284a1d5e1fSFam Zheng     if (!drv) {
24294a1d5e1fSFam Zheng         return -ENOMEDIUM;
24304a1d5e1fSFam Zheng     }
24314a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
24324a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
24334a1d5e1fSFam Zheng     }
24344a1d5e1fSFam Zheng     if (bs->file) {
24354a1d5e1fSFam Zheng         return bdrv_get_allocated_file_size(bs->file);
24364a1d5e1fSFam Zheng     }
24374a1d5e1fSFam Zheng     return -ENOTSUP;
24384a1d5e1fSFam Zheng }
24394a1d5e1fSFam Zheng 
24404a1d5e1fSFam Zheng /**
244183f64091Sbellard  * Length of a file in bytes. Return < 0 if error or unknown.
244283f64091Sbellard  */
244383f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs)
244483f64091Sbellard {
244583f64091Sbellard     BlockDriver *drv = bs->drv;
244683f64091Sbellard     if (!drv)
244719cb3738Sbellard         return -ENOMEDIUM;
244851762288SStefan Hajnoczi 
24492c6942faSMarkus Armbruster     if (bs->growable || bdrv_dev_has_removable_media(bs)) {
245046a4e4e6SStefan Hajnoczi         if (drv->bdrv_getlength) {
245183f64091Sbellard             return drv->bdrv_getlength(bs);
2452fc01f7e7Sbellard         }
245346a4e4e6SStefan Hajnoczi     }
245446a4e4e6SStefan Hajnoczi     return bs->total_sectors * BDRV_SECTOR_SIZE;
245546a4e4e6SStefan Hajnoczi }
2456fc01f7e7Sbellard 
245719cb3738Sbellard /* return 0 as number of sectors if no device present or error */
245896b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2459fc01f7e7Sbellard {
246019cb3738Sbellard     int64_t length;
246119cb3738Sbellard     length = bdrv_getlength(bs);
246219cb3738Sbellard     if (length < 0)
246319cb3738Sbellard         length = 0;
246419cb3738Sbellard     else
24656ea44308SJan Kiszka         length = length >> BDRV_SECTOR_BITS;
246619cb3738Sbellard     *nb_sectors_ptr = length;
2467fc01f7e7Sbellard }
2468cf98951bSbellard 
24690563e191SZhi Yong Wu /* throttling disk io limits */
24700563e191SZhi Yong Wu void bdrv_set_io_limits(BlockDriverState *bs,
24710563e191SZhi Yong Wu                         BlockIOLimit *io_limits)
24720563e191SZhi Yong Wu {
24730563e191SZhi Yong Wu     bs->io_limits = *io_limits;
24740563e191SZhi Yong Wu     bs->io_limits_enabled = bdrv_io_limits_enabled(bs);
24750563e191SZhi Yong Wu }
24760563e191SZhi Yong Wu 
2477abd7f68dSMarkus Armbruster void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
2478abd7f68dSMarkus Armbruster                        BlockErrorAction on_write_error)
2479abd7f68dSMarkus Armbruster {
2480abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
2481abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
2482abd7f68dSMarkus Armbruster }
2483abd7f68dSMarkus Armbruster 
2484abd7f68dSMarkus Armbruster BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
2485abd7f68dSMarkus Armbruster {
2486abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
2487abd7f68dSMarkus Armbruster }
2488abd7f68dSMarkus Armbruster 
2489b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2490b338082bSbellard {
2491b338082bSbellard     return bs->read_only;
2492b338082bSbellard }
2493b338082bSbellard 
2494985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2495985a03b0Sths {
2496985a03b0Sths     return bs->sg;
2497985a03b0Sths }
2498985a03b0Sths 
2499e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
2500e900a7b7SChristoph Hellwig {
2501e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
2502e900a7b7SChristoph Hellwig }
2503e900a7b7SChristoph Hellwig 
2504425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2505425b0148SPaolo Bonzini {
2506425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
250755b110f2SJeff Cody 
250855b110f2SJeff Cody     /* so a reopen() will preserve wce */
250955b110f2SJeff Cody     if (wce) {
251055b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
251155b110f2SJeff Cody     } else {
251255b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
251355b110f2SJeff Cody     }
2514425b0148SPaolo Bonzini }
2515425b0148SPaolo Bonzini 
2516ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2517ea2384d3Sbellard {
2518ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
2519ea2384d3Sbellard         return 1;
2520ea2384d3Sbellard     return bs->encrypted;
2521ea2384d3Sbellard }
2522ea2384d3Sbellard 
2523c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2524c0f4ce77Saliguori {
2525c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
2526c0f4ce77Saliguori 
2527c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
2528c0f4ce77Saliguori         return 1;
2529c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2530c0f4ce77Saliguori }
2531c0f4ce77Saliguori 
2532ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2533ea2384d3Sbellard {
2534ea2384d3Sbellard     int ret;
2535ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
2536ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
2537ea2384d3Sbellard         if (ret < 0)
2538ea2384d3Sbellard             return ret;
2539ea2384d3Sbellard         if (!bs->encrypted)
2540ea2384d3Sbellard             return 0;
2541ea2384d3Sbellard     }
2542fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2543fd04a2aeSShahar Havivi         return -EINVAL;
2544fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2545fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2546fd04a2aeSShahar Havivi     }
2547c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2548bb5fc20fSaliguori     if (ret < 0) {
2549bb5fc20fSaliguori         bs->valid_key = 0;
2550bb5fc20fSaliguori     } else if (!bs->valid_key) {
2551bb5fc20fSaliguori         bs->valid_key = 1;
2552bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
25537d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
2554bb5fc20fSaliguori     }
2555c0f4ce77Saliguori     return ret;
2556ea2384d3Sbellard }
2557ea2384d3Sbellard 
2558f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
2559ea2384d3Sbellard {
2560f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
2561ea2384d3Sbellard }
2562ea2384d3Sbellard 
2563ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2564ea2384d3Sbellard                          void *opaque)
2565ea2384d3Sbellard {
2566ea2384d3Sbellard     BlockDriver *drv;
2567ea2384d3Sbellard 
25688a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2569ea2384d3Sbellard         it(opaque, drv->format_name);
2570ea2384d3Sbellard     }
2571ea2384d3Sbellard }
2572ea2384d3Sbellard 
2573b338082bSbellard BlockDriverState *bdrv_find(const char *name)
2574b338082bSbellard {
2575b338082bSbellard     BlockDriverState *bs;
2576b338082bSbellard 
25771b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
25781b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
2579b338082bSbellard             return bs;
2580b338082bSbellard         }
25811b7bdbc1SStefan Hajnoczi     }
2582b338082bSbellard     return NULL;
2583b338082bSbellard }
2584b338082bSbellard 
25852f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
25862f399b0aSMarkus Armbruster {
25872f399b0aSMarkus Armbruster     if (!bs) {
25882f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
25892f399b0aSMarkus Armbruster     }
25902f399b0aSMarkus Armbruster     return QTAILQ_NEXT(bs, list);
25912f399b0aSMarkus Armbruster }
25922f399b0aSMarkus Armbruster 
259351de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
259481d0912dSbellard {
259581d0912dSbellard     BlockDriverState *bs;
259681d0912dSbellard 
25971b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
259851de9760Saliguori         it(opaque, bs);
259981d0912dSbellard     }
260081d0912dSbellard }
260181d0912dSbellard 
2602ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
2603ea2384d3Sbellard {
2604ea2384d3Sbellard     return bs->device_name;
2605ea2384d3Sbellard }
2606ea2384d3Sbellard 
2607c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
2608c8433287SMarkus Armbruster {
2609c8433287SMarkus Armbruster     return bs->open_flags;
2610c8433287SMarkus Armbruster }
2611c8433287SMarkus Armbruster 
2612c6ca28d6Saliguori void bdrv_flush_all(void)
2613c6ca28d6Saliguori {
2614c6ca28d6Saliguori     BlockDriverState *bs;
2615c6ca28d6Saliguori 
26161b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
2617c6ca28d6Saliguori         bdrv_flush(bs);
2618c6ca28d6Saliguori     }
26191b7bdbc1SStefan Hajnoczi }
2620c6ca28d6Saliguori 
2621f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
2622f2feebbdSKevin Wolf {
2623f2feebbdSKevin Wolf     assert(bs->drv);
2624f2feebbdSKevin Wolf 
2625336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
2626336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
2627f2feebbdSKevin Wolf     }
2628f2feebbdSKevin Wolf 
2629f2feebbdSKevin Wolf     return 1;
2630f2feebbdSKevin Wolf }
2631f2feebbdSKevin Wolf 
2632376ae3f1SStefan Hajnoczi typedef struct BdrvCoIsAllocatedData {
2633376ae3f1SStefan Hajnoczi     BlockDriverState *bs;
2634376ae3f1SStefan Hajnoczi     int64_t sector_num;
2635376ae3f1SStefan Hajnoczi     int nb_sectors;
2636376ae3f1SStefan Hajnoczi     int *pnum;
2637376ae3f1SStefan Hajnoczi     int ret;
2638376ae3f1SStefan Hajnoczi     bool done;
2639376ae3f1SStefan Hajnoczi } BdrvCoIsAllocatedData;
2640376ae3f1SStefan Hajnoczi 
2641f58c7b35Sths /*
2642f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
2643f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
2644f58c7b35Sths  * hence all their sectors are reported as allocated.
2645f58c7b35Sths  *
2646bd9533e3SStefan Hajnoczi  * If 'sector_num' is beyond the end of the disk image the return value is 0
2647bd9533e3SStefan Hajnoczi  * and 'pnum' is set to 0.
2648bd9533e3SStefan Hajnoczi  *
2649f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
2650f58c7b35Sths  * the specified sector) that are known to be in the same
2651f58c7b35Sths  * allocated/unallocated state.
2652f58c7b35Sths  *
2653bd9533e3SStefan Hajnoczi  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
2654bd9533e3SStefan Hajnoczi  * beyond the end of the disk image it will be clamped.
2655f58c7b35Sths  */
2656060f51c9SStefan Hajnoczi int coroutine_fn bdrv_co_is_allocated(BlockDriverState *bs, int64_t sector_num,
2657060f51c9SStefan Hajnoczi                                       int nb_sectors, int *pnum)
2658f58c7b35Sths {
2659f58c7b35Sths     int64_t n;
2660bd9533e3SStefan Hajnoczi 
26616aebab14SStefan Hajnoczi     if (sector_num >= bs->total_sectors) {
26626aebab14SStefan Hajnoczi         *pnum = 0;
26636aebab14SStefan Hajnoczi         return 0;
26646aebab14SStefan Hajnoczi     }
2665bd9533e3SStefan Hajnoczi 
26666aebab14SStefan Hajnoczi     n = bs->total_sectors - sector_num;
2667bd9533e3SStefan Hajnoczi     if (n < nb_sectors) {
2668bd9533e3SStefan Hajnoczi         nb_sectors = n;
2669bd9533e3SStefan Hajnoczi     }
2670bd9533e3SStefan Hajnoczi 
2671bd9533e3SStefan Hajnoczi     if (!bs->drv->bdrv_co_is_allocated) {
2672bd9533e3SStefan Hajnoczi         *pnum = nb_sectors;
26736aebab14SStefan Hajnoczi         return 1;
26746aebab14SStefan Hajnoczi     }
26756aebab14SStefan Hajnoczi 
2676060f51c9SStefan Hajnoczi     return bs->drv->bdrv_co_is_allocated(bs, sector_num, nb_sectors, pnum);
2677060f51c9SStefan Hajnoczi }
2678060f51c9SStefan Hajnoczi 
2679060f51c9SStefan Hajnoczi /* Coroutine wrapper for bdrv_is_allocated() */
2680060f51c9SStefan Hajnoczi static void coroutine_fn bdrv_is_allocated_co_entry(void *opaque)
2681060f51c9SStefan Hajnoczi {
2682060f51c9SStefan Hajnoczi     BdrvCoIsAllocatedData *data = opaque;
2683060f51c9SStefan Hajnoczi     BlockDriverState *bs = data->bs;
2684060f51c9SStefan Hajnoczi 
2685060f51c9SStefan Hajnoczi     data->ret = bdrv_co_is_allocated(bs, data->sector_num, data->nb_sectors,
2686060f51c9SStefan Hajnoczi                                      data->pnum);
2687060f51c9SStefan Hajnoczi     data->done = true;
2688060f51c9SStefan Hajnoczi }
2689060f51c9SStefan Hajnoczi 
2690060f51c9SStefan Hajnoczi /*
2691060f51c9SStefan Hajnoczi  * Synchronous wrapper around bdrv_co_is_allocated().
2692060f51c9SStefan Hajnoczi  *
2693060f51c9SStefan Hajnoczi  * See bdrv_co_is_allocated() for details.
2694060f51c9SStefan Hajnoczi  */
2695060f51c9SStefan Hajnoczi int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
2696060f51c9SStefan Hajnoczi                       int *pnum)
2697060f51c9SStefan Hajnoczi {
2698376ae3f1SStefan Hajnoczi     Coroutine *co;
2699376ae3f1SStefan Hajnoczi     BdrvCoIsAllocatedData data = {
2700376ae3f1SStefan Hajnoczi         .bs = bs,
2701376ae3f1SStefan Hajnoczi         .sector_num = sector_num,
2702376ae3f1SStefan Hajnoczi         .nb_sectors = nb_sectors,
2703376ae3f1SStefan Hajnoczi         .pnum = pnum,
2704376ae3f1SStefan Hajnoczi         .done = false,
2705376ae3f1SStefan Hajnoczi     };
2706376ae3f1SStefan Hajnoczi 
2707376ae3f1SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_is_allocated_co_entry);
2708376ae3f1SStefan Hajnoczi     qemu_coroutine_enter(co, &data);
2709376ae3f1SStefan Hajnoczi     while (!data.done) {
2710376ae3f1SStefan Hajnoczi         qemu_aio_wait();
2711376ae3f1SStefan Hajnoczi     }
2712376ae3f1SStefan Hajnoczi     return data.ret;
2713376ae3f1SStefan Hajnoczi }
2714f58c7b35Sths 
2715188a7bbfSPaolo Bonzini /*
2716188a7bbfSPaolo Bonzini  * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2717188a7bbfSPaolo Bonzini  *
2718188a7bbfSPaolo Bonzini  * Return true if the given sector is allocated in any image between
2719188a7bbfSPaolo Bonzini  * BASE and TOP (inclusive).  BASE can be NULL to check if the given
2720188a7bbfSPaolo Bonzini  * sector is allocated in any image of the chain.  Return false otherwise.
2721188a7bbfSPaolo Bonzini  *
2722188a7bbfSPaolo Bonzini  * 'pnum' is set to the number of sectors (including and immediately following
2723188a7bbfSPaolo Bonzini  *  the specified sector) that are known to be in the same
2724188a7bbfSPaolo Bonzini  *  allocated/unallocated state.
2725188a7bbfSPaolo Bonzini  *
2726188a7bbfSPaolo Bonzini  */
2727188a7bbfSPaolo Bonzini int coroutine_fn bdrv_co_is_allocated_above(BlockDriverState *top,
2728188a7bbfSPaolo Bonzini                                             BlockDriverState *base,
2729188a7bbfSPaolo Bonzini                                             int64_t sector_num,
2730188a7bbfSPaolo Bonzini                                             int nb_sectors, int *pnum)
2731188a7bbfSPaolo Bonzini {
2732188a7bbfSPaolo Bonzini     BlockDriverState *intermediate;
2733188a7bbfSPaolo Bonzini     int ret, n = nb_sectors;
2734188a7bbfSPaolo Bonzini 
2735188a7bbfSPaolo Bonzini     intermediate = top;
2736188a7bbfSPaolo Bonzini     while (intermediate && intermediate != base) {
2737188a7bbfSPaolo Bonzini         int pnum_inter;
2738188a7bbfSPaolo Bonzini         ret = bdrv_co_is_allocated(intermediate, sector_num, nb_sectors,
2739188a7bbfSPaolo Bonzini                                    &pnum_inter);
2740188a7bbfSPaolo Bonzini         if (ret < 0) {
2741188a7bbfSPaolo Bonzini             return ret;
2742188a7bbfSPaolo Bonzini         } else if (ret) {
2743188a7bbfSPaolo Bonzini             *pnum = pnum_inter;
2744188a7bbfSPaolo Bonzini             return 1;
2745188a7bbfSPaolo Bonzini         }
2746188a7bbfSPaolo Bonzini 
2747188a7bbfSPaolo Bonzini         /*
2748188a7bbfSPaolo Bonzini          * [sector_num, nb_sectors] is unallocated on top but intermediate
2749188a7bbfSPaolo Bonzini          * might have
2750188a7bbfSPaolo Bonzini          *
2751188a7bbfSPaolo Bonzini          * [sector_num+x, nr_sectors] allocated.
2752188a7bbfSPaolo Bonzini          */
2753188a7bbfSPaolo Bonzini         if (n > pnum_inter) {
2754188a7bbfSPaolo Bonzini             n = pnum_inter;
2755188a7bbfSPaolo Bonzini         }
2756188a7bbfSPaolo Bonzini 
2757188a7bbfSPaolo Bonzini         intermediate = intermediate->backing_hd;
2758188a7bbfSPaolo Bonzini     }
2759188a7bbfSPaolo Bonzini 
2760188a7bbfSPaolo Bonzini     *pnum = n;
2761188a7bbfSPaolo Bonzini     return 0;
2762188a7bbfSPaolo Bonzini }
2763188a7bbfSPaolo Bonzini 
2764b2023818SLuiz Capitulino BlockInfoList *qmp_query_block(Error **errp)
2765b338082bSbellard {
2766b2023818SLuiz Capitulino     BlockInfoList *head = NULL, *cur_item = NULL;
2767d15e5465SLuiz Capitulino     BlockDriverState *bs;
2768d15e5465SLuiz Capitulino 
27691b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
2770b2023818SLuiz Capitulino         BlockInfoList *info = g_malloc0(sizeof(*info));
2771d15e5465SLuiz Capitulino 
2772b2023818SLuiz Capitulino         info->value = g_malloc0(sizeof(*info->value));
2773b2023818SLuiz Capitulino         info->value->device = g_strdup(bs->device_name);
2774b2023818SLuiz Capitulino         info->value->type = g_strdup("unknown");
2775b2023818SLuiz Capitulino         info->value->locked = bdrv_dev_is_medium_locked(bs);
2776b2023818SLuiz Capitulino         info->value->removable = bdrv_dev_has_removable_media(bs);
2777d15e5465SLuiz Capitulino 
2778e4def80bSMarkus Armbruster         if (bdrv_dev_has_removable_media(bs)) {
2779b2023818SLuiz Capitulino             info->value->has_tray_open = true;
2780b2023818SLuiz Capitulino             info->value->tray_open = bdrv_dev_is_tray_open(bs);
2781e4def80bSMarkus Armbruster         }
2782f04ef601SLuiz Capitulino 
2783f04ef601SLuiz Capitulino         if (bdrv_iostatus_is_enabled(bs)) {
2784b2023818SLuiz Capitulino             info->value->has_io_status = true;
2785b2023818SLuiz Capitulino             info->value->io_status = bs->iostatus;
2786f04ef601SLuiz Capitulino         }
2787f04ef601SLuiz Capitulino 
2788d15e5465SLuiz Capitulino         if (bs->drv) {
2789b2023818SLuiz Capitulino             info->value->has_inserted = true;
2790b2023818SLuiz Capitulino             info->value->inserted = g_malloc0(sizeof(*info->value->inserted));
2791b2023818SLuiz Capitulino             info->value->inserted->file = g_strdup(bs->filename);
2792b2023818SLuiz Capitulino             info->value->inserted->ro = bs->read_only;
2793b2023818SLuiz Capitulino             info->value->inserted->drv = g_strdup(bs->drv->format_name);
2794b2023818SLuiz Capitulino             info->value->inserted->encrypted = bs->encrypted;
2795c75a1a8aSLuiz Capitulino             info->value->inserted->encryption_key_missing = bdrv_key_required(bs);
2796b2023818SLuiz Capitulino             if (bs->backing_file[0]) {
2797b2023818SLuiz Capitulino                 info->value->inserted->has_backing_file = true;
2798b2023818SLuiz Capitulino                 info->value->inserted->backing_file = g_strdup(bs->backing_file);
2799b2023818SLuiz Capitulino             }
2800727f005eSZhi Yong Wu 
28012e3e3317SBenoît Canet             info->value->inserted->backing_file_depth =
28022e3e3317SBenoît Canet                 bdrv_get_backing_file_depth(bs);
28032e3e3317SBenoît Canet 
2804727f005eSZhi Yong Wu             if (bs->io_limits_enabled) {
2805727f005eSZhi Yong Wu                 info->value->inserted->bps =
2806727f005eSZhi Yong Wu                                bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
2807727f005eSZhi Yong Wu                 info->value->inserted->bps_rd =
2808727f005eSZhi Yong Wu                                bs->io_limits.bps[BLOCK_IO_LIMIT_READ];
2809727f005eSZhi Yong Wu                 info->value->inserted->bps_wr =
2810727f005eSZhi Yong Wu                                bs->io_limits.bps[BLOCK_IO_LIMIT_WRITE];
2811727f005eSZhi Yong Wu                 info->value->inserted->iops =
2812727f005eSZhi Yong Wu                                bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
2813727f005eSZhi Yong Wu                 info->value->inserted->iops_rd =
2814727f005eSZhi Yong Wu                                bs->io_limits.iops[BLOCK_IO_LIMIT_READ];
2815727f005eSZhi Yong Wu                 info->value->inserted->iops_wr =
2816727f005eSZhi Yong Wu                                bs->io_limits.iops[BLOCK_IO_LIMIT_WRITE];
2817727f005eSZhi Yong Wu             }
2818d15e5465SLuiz Capitulino         }
2819d15e5465SLuiz Capitulino 
2820b2023818SLuiz Capitulino         /* XXX: waiting for the qapi to support GSList */
2821b2023818SLuiz Capitulino         if (!cur_item) {
2822b2023818SLuiz Capitulino             head = cur_item = info;
2823b2023818SLuiz Capitulino         } else {
2824b2023818SLuiz Capitulino             cur_item->next = info;
2825b2023818SLuiz Capitulino             cur_item = info;
2826d15e5465SLuiz Capitulino         }
2827d15e5465SLuiz Capitulino     }
2828d15e5465SLuiz Capitulino 
2829b2023818SLuiz Capitulino     return head;
2830b338082bSbellard }
2831a36e69ddSths 
2832f11f57e4SLuiz Capitulino /* Consider exposing this as a full fledged QMP command */
2833f11f57e4SLuiz Capitulino static BlockStats *qmp_query_blockstat(const BlockDriverState *bs, Error **errp)
2834a36e69ddSths {
2835f11f57e4SLuiz Capitulino     BlockStats *s;
2836218a536aSLuiz Capitulino 
2837f11f57e4SLuiz Capitulino     s = g_malloc0(sizeof(*s));
2838218a536aSLuiz Capitulino 
2839f11f57e4SLuiz Capitulino     if (bs->device_name[0]) {
2840f11f57e4SLuiz Capitulino         s->has_device = true;
2841f11f57e4SLuiz Capitulino         s->device = g_strdup(bs->device_name);
2842218a536aSLuiz Capitulino     }
2843218a536aSLuiz Capitulino 
2844f11f57e4SLuiz Capitulino     s->stats = g_malloc0(sizeof(*s->stats));
2845f11f57e4SLuiz Capitulino     s->stats->rd_bytes = bs->nr_bytes[BDRV_ACCT_READ];
2846f11f57e4SLuiz Capitulino     s->stats->wr_bytes = bs->nr_bytes[BDRV_ACCT_WRITE];
2847f11f57e4SLuiz Capitulino     s->stats->rd_operations = bs->nr_ops[BDRV_ACCT_READ];
2848f11f57e4SLuiz Capitulino     s->stats->wr_operations = bs->nr_ops[BDRV_ACCT_WRITE];
2849f11f57e4SLuiz Capitulino     s->stats->wr_highest_offset = bs->wr_highest_sector * BDRV_SECTOR_SIZE;
2850f11f57e4SLuiz Capitulino     s->stats->flush_operations = bs->nr_ops[BDRV_ACCT_FLUSH];
2851f11f57e4SLuiz Capitulino     s->stats->wr_total_time_ns = bs->total_time_ns[BDRV_ACCT_WRITE];
2852f11f57e4SLuiz Capitulino     s->stats->rd_total_time_ns = bs->total_time_ns[BDRV_ACCT_READ];
2853f11f57e4SLuiz Capitulino     s->stats->flush_total_time_ns = bs->total_time_ns[BDRV_ACCT_FLUSH];
2854294cc35fSKevin Wolf 
2855294cc35fSKevin Wolf     if (bs->file) {
2856f11f57e4SLuiz Capitulino         s->has_parent = true;
2857f11f57e4SLuiz Capitulino         s->parent = qmp_query_blockstat(bs->file, NULL);
2858294cc35fSKevin Wolf     }
2859294cc35fSKevin Wolf 
2860f11f57e4SLuiz Capitulino     return s;
2861294cc35fSKevin Wolf }
2862294cc35fSKevin Wolf 
2863f11f57e4SLuiz Capitulino BlockStatsList *qmp_query_blockstats(Error **errp)
2864218a536aSLuiz Capitulino {
2865f11f57e4SLuiz Capitulino     BlockStatsList *head = NULL, *cur_item = NULL;
2866a36e69ddSths     BlockDriverState *bs;
2867a36e69ddSths 
28681b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
2869f11f57e4SLuiz Capitulino         BlockStatsList *info = g_malloc0(sizeof(*info));
2870f11f57e4SLuiz Capitulino         info->value = qmp_query_blockstat(bs, NULL);
2871f11f57e4SLuiz Capitulino 
2872f11f57e4SLuiz Capitulino         /* XXX: waiting for the qapi to support GSList */
2873f11f57e4SLuiz Capitulino         if (!cur_item) {
2874f11f57e4SLuiz Capitulino             head = cur_item = info;
2875f11f57e4SLuiz Capitulino         } else {
2876f11f57e4SLuiz Capitulino             cur_item->next = info;
2877f11f57e4SLuiz Capitulino             cur_item = info;
2878f11f57e4SLuiz Capitulino         }
2879a36e69ddSths     }
2880218a536aSLuiz Capitulino 
2881f11f57e4SLuiz Capitulino     return head;
2882a36e69ddSths }
2883ea2384d3Sbellard 
2884045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2885045df330Saliguori {
2886045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
2887045df330Saliguori         return bs->backing_file;
2888045df330Saliguori     else if (bs->encrypted)
2889045df330Saliguori         return bs->filename;
2890045df330Saliguori     else
2891045df330Saliguori         return NULL;
2892045df330Saliguori }
2893045df330Saliguori 
289483f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
289583f64091Sbellard                                char *filename, int filename_size)
289683f64091Sbellard {
289783f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
289883f64091Sbellard }
289983f64091Sbellard 
2900faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
2901faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
2902faea38e7Sbellard {
2903faea38e7Sbellard     BlockDriver *drv = bs->drv;
2904faea38e7Sbellard     if (!drv)
290519cb3738Sbellard         return -ENOMEDIUM;
2906faea38e7Sbellard     if (!drv->bdrv_write_compressed)
2907faea38e7Sbellard         return -ENOTSUP;
2908fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
2909fbb7b4e0SKevin Wolf         return -EIO;
29107cd1e32aSlirans@il.ibm.com 
2911c6d22830SJan Kiszka     if (bs->dirty_bitmap) {
29127cd1e32aSlirans@il.ibm.com         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
29137cd1e32aSlirans@il.ibm.com     }
29147cd1e32aSlirans@il.ibm.com 
2915faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
2916faea38e7Sbellard }
2917faea38e7Sbellard 
2918faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2919faea38e7Sbellard {
2920faea38e7Sbellard     BlockDriver *drv = bs->drv;
2921faea38e7Sbellard     if (!drv)
292219cb3738Sbellard         return -ENOMEDIUM;
2923faea38e7Sbellard     if (!drv->bdrv_get_info)
2924faea38e7Sbellard         return -ENOTSUP;
2925faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
2926faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
2927faea38e7Sbellard }
2928faea38e7Sbellard 
292945566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
293045566e9cSChristoph Hellwig                       int64_t pos, int size)
2931178e08a5Saliguori {
2932178e08a5Saliguori     BlockDriver *drv = bs->drv;
2933178e08a5Saliguori     if (!drv)
2934178e08a5Saliguori         return -ENOMEDIUM;
29357cdb1f6dSMORITA Kazutaka     if (drv->bdrv_save_vmstate)
293645566e9cSChristoph Hellwig         return drv->bdrv_save_vmstate(bs, buf, pos, size);
29377cdb1f6dSMORITA Kazutaka     if (bs->file)
29387cdb1f6dSMORITA Kazutaka         return bdrv_save_vmstate(bs->file, buf, pos, size);
29397cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2940178e08a5Saliguori }
2941178e08a5Saliguori 
294245566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
294345566e9cSChristoph Hellwig                       int64_t pos, int size)
2944178e08a5Saliguori {
2945178e08a5Saliguori     BlockDriver *drv = bs->drv;
2946178e08a5Saliguori     if (!drv)
2947178e08a5Saliguori         return -ENOMEDIUM;
29487cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
294945566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
29507cdb1f6dSMORITA Kazutaka     if (bs->file)
29517cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
29527cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2953178e08a5Saliguori }
2954178e08a5Saliguori 
29558b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
29568b9b0cc2SKevin Wolf {
29578b9b0cc2SKevin Wolf     BlockDriver *drv = bs->drv;
29588b9b0cc2SKevin Wolf 
29598b9b0cc2SKevin Wolf     if (!drv || !drv->bdrv_debug_event) {
29608b9b0cc2SKevin Wolf         return;
29618b9b0cc2SKevin Wolf     }
29628b9b0cc2SKevin Wolf 
29630ed8b6f6SBlue Swirl     drv->bdrv_debug_event(bs, event);
29648b9b0cc2SKevin Wolf 
29658b9b0cc2SKevin Wolf }
29668b9b0cc2SKevin Wolf 
2967faea38e7Sbellard /**************************************************************/
2968faea38e7Sbellard /* handling of snapshots */
2969faea38e7Sbellard 
2970feeee5acSMiguel Di Ciurcio Filho int bdrv_can_snapshot(BlockDriverState *bs)
2971feeee5acSMiguel Di Ciurcio Filho {
2972feeee5acSMiguel Di Ciurcio Filho     BlockDriver *drv = bs->drv;
297307b70bfbSMarkus Armbruster     if (!drv || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
2974feeee5acSMiguel Di Ciurcio Filho         return 0;
2975feeee5acSMiguel Di Ciurcio Filho     }
2976feeee5acSMiguel Di Ciurcio Filho 
2977feeee5acSMiguel Di Ciurcio Filho     if (!drv->bdrv_snapshot_create) {
2978feeee5acSMiguel Di Ciurcio Filho         if (bs->file != NULL) {
2979feeee5acSMiguel Di Ciurcio Filho             return bdrv_can_snapshot(bs->file);
2980feeee5acSMiguel Di Ciurcio Filho         }
2981feeee5acSMiguel Di Ciurcio Filho         return 0;
2982feeee5acSMiguel Di Ciurcio Filho     }
2983feeee5acSMiguel Di Ciurcio Filho 
2984feeee5acSMiguel Di Ciurcio Filho     return 1;
2985feeee5acSMiguel Di Ciurcio Filho }
2986feeee5acSMiguel Di Ciurcio Filho 
2987199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
2988199630b6SBlue Swirl {
2989199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2990199630b6SBlue Swirl }
2991199630b6SBlue Swirl 
2992f9092b10SMarkus Armbruster BlockDriverState *bdrv_snapshots(void)
2993f9092b10SMarkus Armbruster {
2994f9092b10SMarkus Armbruster     BlockDriverState *bs;
2995f9092b10SMarkus Armbruster 
29963ac906f7SMarkus Armbruster     if (bs_snapshots) {
2997f9092b10SMarkus Armbruster         return bs_snapshots;
29983ac906f7SMarkus Armbruster     }
2999f9092b10SMarkus Armbruster 
3000f9092b10SMarkus Armbruster     bs = NULL;
3001f9092b10SMarkus Armbruster     while ((bs = bdrv_next(bs))) {
3002f9092b10SMarkus Armbruster         if (bdrv_can_snapshot(bs)) {
30033ac906f7SMarkus Armbruster             bs_snapshots = bs;
30043ac906f7SMarkus Armbruster             return bs;
3005f9092b10SMarkus Armbruster         }
3006f9092b10SMarkus Armbruster     }
3007f9092b10SMarkus Armbruster     return NULL;
3008f9092b10SMarkus Armbruster }
3009f9092b10SMarkus Armbruster 
3010faea38e7Sbellard int bdrv_snapshot_create(BlockDriverState *bs,
3011faea38e7Sbellard                          QEMUSnapshotInfo *sn_info)
3012faea38e7Sbellard {
3013faea38e7Sbellard     BlockDriver *drv = bs->drv;
3014faea38e7Sbellard     if (!drv)
301519cb3738Sbellard         return -ENOMEDIUM;
30167cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_create)
3017faea38e7Sbellard         return drv->bdrv_snapshot_create(bs, sn_info);
30187cdb1f6dSMORITA Kazutaka     if (bs->file)
30197cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_create(bs->file, sn_info);
30207cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3021faea38e7Sbellard }
3022faea38e7Sbellard 
3023faea38e7Sbellard int bdrv_snapshot_goto(BlockDriverState *bs,
3024faea38e7Sbellard                        const char *snapshot_id)
3025faea38e7Sbellard {
3026faea38e7Sbellard     BlockDriver *drv = bs->drv;
30277cdb1f6dSMORITA Kazutaka     int ret, open_ret;
30287cdb1f6dSMORITA Kazutaka 
3029faea38e7Sbellard     if (!drv)
303019cb3738Sbellard         return -ENOMEDIUM;
30317cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_goto)
3032faea38e7Sbellard         return drv->bdrv_snapshot_goto(bs, snapshot_id);
30337cdb1f6dSMORITA Kazutaka 
30347cdb1f6dSMORITA Kazutaka     if (bs->file) {
30357cdb1f6dSMORITA Kazutaka         drv->bdrv_close(bs);
30367cdb1f6dSMORITA Kazutaka         ret = bdrv_snapshot_goto(bs->file, snapshot_id);
30377cdb1f6dSMORITA Kazutaka         open_ret = drv->bdrv_open(bs, bs->open_flags);
30387cdb1f6dSMORITA Kazutaka         if (open_ret < 0) {
30397cdb1f6dSMORITA Kazutaka             bdrv_delete(bs->file);
30407cdb1f6dSMORITA Kazutaka             bs->drv = NULL;
30417cdb1f6dSMORITA Kazutaka             return open_ret;
30427cdb1f6dSMORITA Kazutaka         }
30437cdb1f6dSMORITA Kazutaka         return ret;
30447cdb1f6dSMORITA Kazutaka     }
30457cdb1f6dSMORITA Kazutaka 
30467cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3047faea38e7Sbellard }
3048faea38e7Sbellard 
3049faea38e7Sbellard int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
3050faea38e7Sbellard {
3051faea38e7Sbellard     BlockDriver *drv = bs->drv;
3052faea38e7Sbellard     if (!drv)
305319cb3738Sbellard         return -ENOMEDIUM;
30547cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_delete)
3055faea38e7Sbellard         return drv->bdrv_snapshot_delete(bs, snapshot_id);
30567cdb1f6dSMORITA Kazutaka     if (bs->file)
30577cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_delete(bs->file, snapshot_id);
30587cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3059faea38e7Sbellard }
3060faea38e7Sbellard 
3061faea38e7Sbellard int bdrv_snapshot_list(BlockDriverState *bs,
3062faea38e7Sbellard                        QEMUSnapshotInfo **psn_info)
3063faea38e7Sbellard {
3064faea38e7Sbellard     BlockDriver *drv = bs->drv;
3065faea38e7Sbellard     if (!drv)
306619cb3738Sbellard         return -ENOMEDIUM;
30677cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_list)
3068faea38e7Sbellard         return drv->bdrv_snapshot_list(bs, psn_info);
30697cdb1f6dSMORITA Kazutaka     if (bs->file)
30707cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_list(bs->file, psn_info);
30717cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3072faea38e7Sbellard }
3073faea38e7Sbellard 
307451ef6727Sedison int bdrv_snapshot_load_tmp(BlockDriverState *bs,
307551ef6727Sedison         const char *snapshot_name)
307651ef6727Sedison {
307751ef6727Sedison     BlockDriver *drv = bs->drv;
307851ef6727Sedison     if (!drv) {
307951ef6727Sedison         return -ENOMEDIUM;
308051ef6727Sedison     }
308151ef6727Sedison     if (!bs->read_only) {
308251ef6727Sedison         return -EINVAL;
308351ef6727Sedison     }
308451ef6727Sedison     if (drv->bdrv_snapshot_load_tmp) {
308551ef6727Sedison         return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
308651ef6727Sedison     }
308751ef6727Sedison     return -ENOTSUP;
308851ef6727Sedison }
308951ef6727Sedison 
3090e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3091e8a6bb9cSMarcelo Tosatti         const char *backing_file)
3092e8a6bb9cSMarcelo Tosatti {
3093e8a6bb9cSMarcelo Tosatti     if (!bs->drv) {
3094e8a6bb9cSMarcelo Tosatti         return NULL;
3095e8a6bb9cSMarcelo Tosatti     }
3096e8a6bb9cSMarcelo Tosatti 
3097e8a6bb9cSMarcelo Tosatti     if (bs->backing_hd) {
3098e8a6bb9cSMarcelo Tosatti         if (strcmp(bs->backing_file, backing_file) == 0) {
3099e8a6bb9cSMarcelo Tosatti             return bs->backing_hd;
3100e8a6bb9cSMarcelo Tosatti         } else {
3101e8a6bb9cSMarcelo Tosatti             return bdrv_find_backing_image(bs->backing_hd, backing_file);
3102e8a6bb9cSMarcelo Tosatti         }
3103e8a6bb9cSMarcelo Tosatti     }
3104e8a6bb9cSMarcelo Tosatti 
3105e8a6bb9cSMarcelo Tosatti     return NULL;
3106e8a6bb9cSMarcelo Tosatti }
3107e8a6bb9cSMarcelo Tosatti 
3108f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
3109f198fd1cSBenoît Canet {
3110f198fd1cSBenoît Canet     if (!bs->drv) {
3111f198fd1cSBenoît Canet         return 0;
3112f198fd1cSBenoît Canet     }
3113f198fd1cSBenoît Canet 
3114f198fd1cSBenoît Canet     if (!bs->backing_hd) {
3115f198fd1cSBenoît Canet         return 0;
3116f198fd1cSBenoît Canet     }
3117f198fd1cSBenoît Canet 
3118f198fd1cSBenoît Canet     return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
3119f198fd1cSBenoît Canet }
3120f198fd1cSBenoît Canet 
312179fac568SJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
312279fac568SJeff Cody {
312379fac568SJeff Cody     BlockDriverState *curr_bs = NULL;
312479fac568SJeff Cody 
312579fac568SJeff Cody     if (!bs) {
312679fac568SJeff Cody         return NULL;
312779fac568SJeff Cody     }
312879fac568SJeff Cody 
312979fac568SJeff Cody     curr_bs = bs;
313079fac568SJeff Cody 
313179fac568SJeff Cody     while (curr_bs->backing_hd) {
313279fac568SJeff Cody         curr_bs = curr_bs->backing_hd;
313379fac568SJeff Cody     }
313479fac568SJeff Cody     return curr_bs;
313579fac568SJeff Cody }
313679fac568SJeff Cody 
3137faea38e7Sbellard #define NB_SUFFIXES 4
3138faea38e7Sbellard 
3139faea38e7Sbellard char *get_human_readable_size(char *buf, int buf_size, int64_t size)
3140faea38e7Sbellard {
3141faea38e7Sbellard     static const char suffixes[NB_SUFFIXES] = "KMGT";
3142faea38e7Sbellard     int64_t base;
3143faea38e7Sbellard     int i;
3144faea38e7Sbellard 
3145faea38e7Sbellard     if (size <= 999) {
3146faea38e7Sbellard         snprintf(buf, buf_size, "%" PRId64, size);
3147faea38e7Sbellard     } else {
3148faea38e7Sbellard         base = 1024;
3149faea38e7Sbellard         for(i = 0; i < NB_SUFFIXES; i++) {
3150faea38e7Sbellard             if (size < (10 * base)) {
3151faea38e7Sbellard                 snprintf(buf, buf_size, "%0.1f%c",
3152faea38e7Sbellard                          (double)size / base,
3153faea38e7Sbellard                          suffixes[i]);
3154faea38e7Sbellard                 break;
3155faea38e7Sbellard             } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
3156faea38e7Sbellard                 snprintf(buf, buf_size, "%" PRId64 "%c",
3157faea38e7Sbellard                          ((size + (base >> 1)) / base),
3158faea38e7Sbellard                          suffixes[i]);
3159faea38e7Sbellard                 break;
3160faea38e7Sbellard             }
3161faea38e7Sbellard             base = base * 1024;
3162faea38e7Sbellard         }
3163faea38e7Sbellard     }
3164faea38e7Sbellard     return buf;
3165faea38e7Sbellard }
3166faea38e7Sbellard 
3167faea38e7Sbellard char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
3168faea38e7Sbellard {
3169faea38e7Sbellard     char buf1[128], date_buf[128], clock_buf[128];
31703b9f94e1Sbellard #ifdef _WIN32
31713b9f94e1Sbellard     struct tm *ptm;
31723b9f94e1Sbellard #else
3173faea38e7Sbellard     struct tm tm;
31743b9f94e1Sbellard #endif
3175faea38e7Sbellard     time_t ti;
3176faea38e7Sbellard     int64_t secs;
3177faea38e7Sbellard 
3178faea38e7Sbellard     if (!sn) {
3179faea38e7Sbellard         snprintf(buf, buf_size,
3180faea38e7Sbellard                  "%-10s%-20s%7s%20s%15s",
3181faea38e7Sbellard                  "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
3182faea38e7Sbellard     } else {
3183faea38e7Sbellard         ti = sn->date_sec;
31843b9f94e1Sbellard #ifdef _WIN32
31853b9f94e1Sbellard         ptm = localtime(&ti);
31863b9f94e1Sbellard         strftime(date_buf, sizeof(date_buf),
31873b9f94e1Sbellard                  "%Y-%m-%d %H:%M:%S", ptm);
31883b9f94e1Sbellard #else
3189faea38e7Sbellard         localtime_r(&ti, &tm);
3190faea38e7Sbellard         strftime(date_buf, sizeof(date_buf),
3191faea38e7Sbellard                  "%Y-%m-%d %H:%M:%S", &tm);
31923b9f94e1Sbellard #endif
3193faea38e7Sbellard         secs = sn->vm_clock_nsec / 1000000000;
3194faea38e7Sbellard         snprintf(clock_buf, sizeof(clock_buf),
3195faea38e7Sbellard                  "%02d:%02d:%02d.%03d",
3196faea38e7Sbellard                  (int)(secs / 3600),
3197faea38e7Sbellard                  (int)((secs / 60) % 60),
3198faea38e7Sbellard                  (int)(secs % 60),
3199faea38e7Sbellard                  (int)((sn->vm_clock_nsec / 1000000) % 1000));
3200faea38e7Sbellard         snprintf(buf, buf_size,
3201faea38e7Sbellard                  "%-10s%-20s%7s%20s%15s",
3202faea38e7Sbellard                  sn->id_str, sn->name,
3203faea38e7Sbellard                  get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
3204faea38e7Sbellard                  date_buf,
3205faea38e7Sbellard                  clock_buf);
3206faea38e7Sbellard     }
3207faea38e7Sbellard     return buf;
3208faea38e7Sbellard }
3209faea38e7Sbellard 
3210ea2384d3Sbellard /**************************************************************/
321183f64091Sbellard /* async I/Os */
3212ea2384d3Sbellard 
32133b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
3214f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
321583f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
3216ea2384d3Sbellard {
3217bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
3218bbf0a440SStefan Hajnoczi 
3219b2a61371SStefan Hajnoczi     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
32208c5873d6SStefan Hajnoczi                                  cb, opaque, false);
322183f64091Sbellard }
322283f64091Sbellard 
3223f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
3224f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
322583f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
32267674e7bfSbellard {
3227bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
3228bbf0a440SStefan Hajnoczi 
32291a6e115bSStefan Hajnoczi     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
32308c5873d6SStefan Hajnoczi                                  cb, opaque, true);
323183f64091Sbellard }
323283f64091Sbellard 
323340b4f539SKevin Wolf 
323440b4f539SKevin Wolf typedef struct MultiwriteCB {
323540b4f539SKevin Wolf     int error;
323640b4f539SKevin Wolf     int num_requests;
323740b4f539SKevin Wolf     int num_callbacks;
323840b4f539SKevin Wolf     struct {
323940b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
324040b4f539SKevin Wolf         void *opaque;
324140b4f539SKevin Wolf         QEMUIOVector *free_qiov;
324240b4f539SKevin Wolf     } callbacks[];
324340b4f539SKevin Wolf } MultiwriteCB;
324440b4f539SKevin Wolf 
324540b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
324640b4f539SKevin Wolf {
324740b4f539SKevin Wolf     int i;
324840b4f539SKevin Wolf 
324940b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
325040b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
32511e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
32521e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
32531e1ea48dSStefan Hajnoczi         }
32547267c094SAnthony Liguori         g_free(mcb->callbacks[i].free_qiov);
325540b4f539SKevin Wolf     }
325640b4f539SKevin Wolf }
325740b4f539SKevin Wolf 
325840b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
325940b4f539SKevin Wolf {
326040b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
326140b4f539SKevin Wolf 
32626d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
32636d519a5fSStefan Hajnoczi 
3264cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
326540b4f539SKevin Wolf         mcb->error = ret;
326640b4f539SKevin Wolf     }
326740b4f539SKevin Wolf 
326840b4f539SKevin Wolf     mcb->num_requests--;
326940b4f539SKevin Wolf     if (mcb->num_requests == 0) {
327040b4f539SKevin Wolf         multiwrite_user_cb(mcb);
32717267c094SAnthony Liguori         g_free(mcb);
327240b4f539SKevin Wolf     }
327340b4f539SKevin Wolf }
327440b4f539SKevin Wolf 
327540b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
327640b4f539SKevin Wolf {
327777be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
327877be4366SChristoph Hellwig 
327977be4366SChristoph Hellwig     /*
328077be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
328177be4366SChristoph Hellwig      * here as that could overflow the return value.
328277be4366SChristoph Hellwig      */
328377be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
328477be4366SChristoph Hellwig         return 1;
328577be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
328677be4366SChristoph Hellwig         return -1;
328777be4366SChristoph Hellwig     } else {
328877be4366SChristoph Hellwig         return 0;
328977be4366SChristoph Hellwig     }
329040b4f539SKevin Wolf }
329140b4f539SKevin Wolf 
329240b4f539SKevin Wolf /*
329340b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
329440b4f539SKevin Wolf  * requests that remain after merging.
329540b4f539SKevin Wolf  */
329640b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
329740b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
329840b4f539SKevin Wolf {
329940b4f539SKevin Wolf     int i, outidx;
330040b4f539SKevin Wolf 
330140b4f539SKevin Wolf     // Sort requests by start sector
330240b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
330340b4f539SKevin Wolf 
330440b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
330540b4f539SKevin Wolf     // filling up gaps with zero sectors.
330640b4f539SKevin Wolf     outidx = 0;
330740b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
330840b4f539SKevin Wolf         int merge = 0;
330940b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
331040b4f539SKevin Wolf 
3311b6a127a1SPaolo Bonzini         // Handle exactly sequential writes and overlapping writes.
331240b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
331340b4f539SKevin Wolf             merge = 1;
331440b4f539SKevin Wolf         }
331540b4f539SKevin Wolf 
3316e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
3317e2a305fbSChristoph Hellwig             merge = 0;
3318e2a305fbSChristoph Hellwig         }
3319e2a305fbSChristoph Hellwig 
332040b4f539SKevin Wolf         if (merge) {
332140b4f539SKevin Wolf             size_t size;
33227267c094SAnthony Liguori             QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
332340b4f539SKevin Wolf             qemu_iovec_init(qiov,
332440b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
332540b4f539SKevin Wolf 
332640b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
332740b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
332840b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
33291b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
333040b4f539SKevin Wolf 
3331b6a127a1SPaolo Bonzini             // We should need to add any zeros between the two requests
3332b6a127a1SPaolo Bonzini             assert (reqs[i].sector <= oldreq_last);
333340b4f539SKevin Wolf 
333440b4f539SKevin Wolf             // Add the second request
33351b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
333640b4f539SKevin Wolf 
3337cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
333840b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
333940b4f539SKevin Wolf 
334040b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
334140b4f539SKevin Wolf         } else {
334240b4f539SKevin Wolf             outidx++;
334340b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
334440b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
334540b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
334640b4f539SKevin Wolf         }
334740b4f539SKevin Wolf     }
334840b4f539SKevin Wolf 
334940b4f539SKevin Wolf     return outidx + 1;
335040b4f539SKevin Wolf }
335140b4f539SKevin Wolf 
335240b4f539SKevin Wolf /*
335340b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
335440b4f539SKevin Wolf  *
335540b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
335640b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
335740b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
335840b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
335940b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
336040b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
336140b4f539SKevin Wolf  *
336240b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
336340b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
336440b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
336540b4f539SKevin Wolf  */
336640b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
336740b4f539SKevin Wolf {
336840b4f539SKevin Wolf     MultiwriteCB *mcb;
336940b4f539SKevin Wolf     int i;
337040b4f539SKevin Wolf 
3371301db7c2SRyan Harper     /* don't submit writes if we don't have a medium */
3372301db7c2SRyan Harper     if (bs->drv == NULL) {
3373301db7c2SRyan Harper         for (i = 0; i < num_reqs; i++) {
3374301db7c2SRyan Harper             reqs[i].error = -ENOMEDIUM;
3375301db7c2SRyan Harper         }
3376301db7c2SRyan Harper         return -1;
3377301db7c2SRyan Harper     }
3378301db7c2SRyan Harper 
337940b4f539SKevin Wolf     if (num_reqs == 0) {
338040b4f539SKevin Wolf         return 0;
338140b4f539SKevin Wolf     }
338240b4f539SKevin Wolf 
338340b4f539SKevin Wolf     // Create MultiwriteCB structure
33847267c094SAnthony Liguori     mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
338540b4f539SKevin Wolf     mcb->num_requests = 0;
338640b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
338740b4f539SKevin Wolf 
338840b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
338940b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
339040b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
339140b4f539SKevin Wolf     }
339240b4f539SKevin Wolf 
339340b4f539SKevin Wolf     // Check for mergable requests
339440b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
339540b4f539SKevin Wolf 
33966d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
33976d519a5fSStefan Hajnoczi 
3398df9309fbSPaolo Bonzini     /* Run the aio requests. */
3399df9309fbSPaolo Bonzini     mcb->num_requests = num_reqs;
340040b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
3401ad54ae80SPaolo Bonzini         bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
340240b4f539SKevin Wolf             reqs[i].nb_sectors, multiwrite_cb, mcb);
340340b4f539SKevin Wolf     }
340440b4f539SKevin Wolf 
340540b4f539SKevin Wolf     return 0;
340640b4f539SKevin Wolf }
340740b4f539SKevin Wolf 
340883f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
340983f64091Sbellard {
34106bbff9a0Saliguori     acb->pool->cancel(acb);
341183f64091Sbellard }
341283f64091Sbellard 
341398f90dbaSZhi Yong Wu /* block I/O throttling */
341498f90dbaSZhi Yong Wu static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
341598f90dbaSZhi Yong Wu                  bool is_write, double elapsed_time, uint64_t *wait)
341698f90dbaSZhi Yong Wu {
341798f90dbaSZhi Yong Wu     uint64_t bps_limit = 0;
341898f90dbaSZhi Yong Wu     double   bytes_limit, bytes_base, bytes_res;
341998f90dbaSZhi Yong Wu     double   slice_time, wait_time;
342098f90dbaSZhi Yong Wu 
342198f90dbaSZhi Yong Wu     if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
342298f90dbaSZhi Yong Wu         bps_limit = bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
342398f90dbaSZhi Yong Wu     } else if (bs->io_limits.bps[is_write]) {
342498f90dbaSZhi Yong Wu         bps_limit = bs->io_limits.bps[is_write];
342598f90dbaSZhi Yong Wu     } else {
342698f90dbaSZhi Yong Wu         if (wait) {
342798f90dbaSZhi Yong Wu             *wait = 0;
342898f90dbaSZhi Yong Wu         }
342998f90dbaSZhi Yong Wu 
343098f90dbaSZhi Yong Wu         return false;
343198f90dbaSZhi Yong Wu     }
343298f90dbaSZhi Yong Wu 
343398f90dbaSZhi Yong Wu     slice_time = bs->slice_end - bs->slice_start;
343498f90dbaSZhi Yong Wu     slice_time /= (NANOSECONDS_PER_SECOND);
343598f90dbaSZhi Yong Wu     bytes_limit = bps_limit * slice_time;
343698f90dbaSZhi Yong Wu     bytes_base  = bs->nr_bytes[is_write] - bs->io_base.bytes[is_write];
343798f90dbaSZhi Yong Wu     if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
343898f90dbaSZhi Yong Wu         bytes_base += bs->nr_bytes[!is_write] - bs->io_base.bytes[!is_write];
343998f90dbaSZhi Yong Wu     }
344098f90dbaSZhi Yong Wu 
344198f90dbaSZhi Yong Wu     /* bytes_base: the bytes of data which have been read/written; and
344298f90dbaSZhi Yong Wu      *             it is obtained from the history statistic info.
344398f90dbaSZhi Yong Wu      * bytes_res: the remaining bytes of data which need to be read/written.
344498f90dbaSZhi Yong Wu      * (bytes_base + bytes_res) / bps_limit: used to calcuate
344598f90dbaSZhi Yong Wu      *             the total time for completing reading/writting all data.
344698f90dbaSZhi Yong Wu      */
344798f90dbaSZhi Yong Wu     bytes_res   = (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
344898f90dbaSZhi Yong Wu 
344998f90dbaSZhi Yong Wu     if (bytes_base + bytes_res <= bytes_limit) {
345098f90dbaSZhi Yong Wu         if (wait) {
345198f90dbaSZhi Yong Wu             *wait = 0;
345298f90dbaSZhi Yong Wu         }
345398f90dbaSZhi Yong Wu 
345498f90dbaSZhi Yong Wu         return false;
345598f90dbaSZhi Yong Wu     }
345698f90dbaSZhi Yong Wu 
345798f90dbaSZhi Yong Wu     /* Calc approx time to dispatch */
345898f90dbaSZhi Yong Wu     wait_time = (bytes_base + bytes_res) / bps_limit - elapsed_time;
345998f90dbaSZhi Yong Wu 
346098f90dbaSZhi Yong Wu     /* When the I/O rate at runtime exceeds the limits,
346198f90dbaSZhi Yong Wu      * bs->slice_end need to be extended in order that the current statistic
346298f90dbaSZhi Yong Wu      * info can be kept until the timer fire, so it is increased and tuned
346398f90dbaSZhi Yong Wu      * based on the result of experiment.
346498f90dbaSZhi Yong Wu      */
346598f90dbaSZhi Yong Wu     bs->slice_time = wait_time * BLOCK_IO_SLICE_TIME * 10;
346698f90dbaSZhi Yong Wu     bs->slice_end += bs->slice_time - 3 * BLOCK_IO_SLICE_TIME;
346798f90dbaSZhi Yong Wu     if (wait) {
346898f90dbaSZhi Yong Wu         *wait = wait_time * BLOCK_IO_SLICE_TIME * 10;
346998f90dbaSZhi Yong Wu     }
347098f90dbaSZhi Yong Wu 
347198f90dbaSZhi Yong Wu     return true;
347298f90dbaSZhi Yong Wu }
347398f90dbaSZhi Yong Wu 
347498f90dbaSZhi Yong Wu static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
347598f90dbaSZhi Yong Wu                              double elapsed_time, uint64_t *wait)
347698f90dbaSZhi Yong Wu {
347798f90dbaSZhi Yong Wu     uint64_t iops_limit = 0;
347898f90dbaSZhi Yong Wu     double   ios_limit, ios_base;
347998f90dbaSZhi Yong Wu     double   slice_time, wait_time;
348098f90dbaSZhi Yong Wu 
348198f90dbaSZhi Yong Wu     if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
348298f90dbaSZhi Yong Wu         iops_limit = bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
348398f90dbaSZhi Yong Wu     } else if (bs->io_limits.iops[is_write]) {
348498f90dbaSZhi Yong Wu         iops_limit = bs->io_limits.iops[is_write];
348598f90dbaSZhi Yong Wu     } else {
348698f90dbaSZhi Yong Wu         if (wait) {
348798f90dbaSZhi Yong Wu             *wait = 0;
348898f90dbaSZhi Yong Wu         }
348998f90dbaSZhi Yong Wu 
349098f90dbaSZhi Yong Wu         return false;
349198f90dbaSZhi Yong Wu     }
349298f90dbaSZhi Yong Wu 
349398f90dbaSZhi Yong Wu     slice_time = bs->slice_end - bs->slice_start;
349498f90dbaSZhi Yong Wu     slice_time /= (NANOSECONDS_PER_SECOND);
349598f90dbaSZhi Yong Wu     ios_limit  = iops_limit * slice_time;
349698f90dbaSZhi Yong Wu     ios_base   = bs->nr_ops[is_write] - bs->io_base.ios[is_write];
349798f90dbaSZhi Yong Wu     if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
349898f90dbaSZhi Yong Wu         ios_base += bs->nr_ops[!is_write] - bs->io_base.ios[!is_write];
349998f90dbaSZhi Yong Wu     }
350098f90dbaSZhi Yong Wu 
350198f90dbaSZhi Yong Wu     if (ios_base + 1 <= ios_limit) {
350298f90dbaSZhi Yong Wu         if (wait) {
350398f90dbaSZhi Yong Wu             *wait = 0;
350498f90dbaSZhi Yong Wu         }
350598f90dbaSZhi Yong Wu 
350698f90dbaSZhi Yong Wu         return false;
350798f90dbaSZhi Yong Wu     }
350898f90dbaSZhi Yong Wu 
350998f90dbaSZhi Yong Wu     /* Calc approx time to dispatch */
351098f90dbaSZhi Yong Wu     wait_time = (ios_base + 1) / iops_limit;
351198f90dbaSZhi Yong Wu     if (wait_time > elapsed_time) {
351298f90dbaSZhi Yong Wu         wait_time = wait_time - elapsed_time;
351398f90dbaSZhi Yong Wu     } else {
351498f90dbaSZhi Yong Wu         wait_time = 0;
351598f90dbaSZhi Yong Wu     }
351698f90dbaSZhi Yong Wu 
351798f90dbaSZhi Yong Wu     bs->slice_time = wait_time * BLOCK_IO_SLICE_TIME * 10;
351898f90dbaSZhi Yong Wu     bs->slice_end += bs->slice_time - 3 * BLOCK_IO_SLICE_TIME;
351998f90dbaSZhi Yong Wu     if (wait) {
352098f90dbaSZhi Yong Wu         *wait = wait_time * BLOCK_IO_SLICE_TIME * 10;
352198f90dbaSZhi Yong Wu     }
352298f90dbaSZhi Yong Wu 
352398f90dbaSZhi Yong Wu     return true;
352498f90dbaSZhi Yong Wu }
352598f90dbaSZhi Yong Wu 
352698f90dbaSZhi Yong Wu static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
352798f90dbaSZhi Yong Wu                            bool is_write, int64_t *wait)
352898f90dbaSZhi Yong Wu {
352998f90dbaSZhi Yong Wu     int64_t  now, max_wait;
353098f90dbaSZhi Yong Wu     uint64_t bps_wait = 0, iops_wait = 0;
353198f90dbaSZhi Yong Wu     double   elapsed_time;
353298f90dbaSZhi Yong Wu     int      bps_ret, iops_ret;
353398f90dbaSZhi Yong Wu 
353498f90dbaSZhi Yong Wu     now = qemu_get_clock_ns(vm_clock);
353598f90dbaSZhi Yong Wu     if ((bs->slice_start < now)
353698f90dbaSZhi Yong Wu         && (bs->slice_end > now)) {
353798f90dbaSZhi Yong Wu         bs->slice_end = now + bs->slice_time;
353898f90dbaSZhi Yong Wu     } else {
353998f90dbaSZhi Yong Wu         bs->slice_time  =  5 * BLOCK_IO_SLICE_TIME;
354098f90dbaSZhi Yong Wu         bs->slice_start = now;
354198f90dbaSZhi Yong Wu         bs->slice_end   = now + bs->slice_time;
354298f90dbaSZhi Yong Wu 
354398f90dbaSZhi Yong Wu         bs->io_base.bytes[is_write]  = bs->nr_bytes[is_write];
354498f90dbaSZhi Yong Wu         bs->io_base.bytes[!is_write] = bs->nr_bytes[!is_write];
354598f90dbaSZhi Yong Wu 
354698f90dbaSZhi Yong Wu         bs->io_base.ios[is_write]    = bs->nr_ops[is_write];
354798f90dbaSZhi Yong Wu         bs->io_base.ios[!is_write]   = bs->nr_ops[!is_write];
354898f90dbaSZhi Yong Wu     }
354998f90dbaSZhi Yong Wu 
355098f90dbaSZhi Yong Wu     elapsed_time  = now - bs->slice_start;
355198f90dbaSZhi Yong Wu     elapsed_time  /= (NANOSECONDS_PER_SECOND);
355298f90dbaSZhi Yong Wu 
355398f90dbaSZhi Yong Wu     bps_ret  = bdrv_exceed_bps_limits(bs, nb_sectors,
355498f90dbaSZhi Yong Wu                                       is_write, elapsed_time, &bps_wait);
355598f90dbaSZhi Yong Wu     iops_ret = bdrv_exceed_iops_limits(bs, is_write,
355698f90dbaSZhi Yong Wu                                       elapsed_time, &iops_wait);
355798f90dbaSZhi Yong Wu     if (bps_ret || iops_ret) {
355898f90dbaSZhi Yong Wu         max_wait = bps_wait > iops_wait ? bps_wait : iops_wait;
355998f90dbaSZhi Yong Wu         if (wait) {
356098f90dbaSZhi Yong Wu             *wait = max_wait;
356198f90dbaSZhi Yong Wu         }
356298f90dbaSZhi Yong Wu 
356398f90dbaSZhi Yong Wu         now = qemu_get_clock_ns(vm_clock);
356498f90dbaSZhi Yong Wu         if (bs->slice_end < now + max_wait) {
356598f90dbaSZhi Yong Wu             bs->slice_end = now + max_wait;
356698f90dbaSZhi Yong Wu         }
356798f90dbaSZhi Yong Wu 
356898f90dbaSZhi Yong Wu         return true;
356998f90dbaSZhi Yong Wu     }
357098f90dbaSZhi Yong Wu 
357198f90dbaSZhi Yong Wu     if (wait) {
357298f90dbaSZhi Yong Wu         *wait = 0;
357398f90dbaSZhi Yong Wu     }
357498f90dbaSZhi Yong Wu 
357598f90dbaSZhi Yong Wu     return false;
357698f90dbaSZhi Yong Wu }
357783f64091Sbellard 
357883f64091Sbellard /**************************************************************/
357983f64091Sbellard /* async block device emulation */
358083f64091Sbellard 
3581c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
3582c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
3583c16b5a2cSChristoph Hellwig     QEMUBH *bh;
3584c16b5a2cSChristoph Hellwig     int ret;
3585c16b5a2cSChristoph Hellwig     /* vector translation state */
3586c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
3587c16b5a2cSChristoph Hellwig     uint8_t *bounce;
3588c16b5a2cSChristoph Hellwig     int is_write;
3589c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
3590c16b5a2cSChristoph Hellwig 
3591c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
3592c16b5a2cSChristoph Hellwig {
3593b666d239SKevin Wolf     BlockDriverAIOCBSync *acb =
3594b666d239SKevin Wolf         container_of(blockacb, BlockDriverAIOCBSync, common);
35956a7ad299SDor Laor     qemu_bh_delete(acb->bh);
359636afc451SAvi Kivity     acb->bh = NULL;
3597c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
3598c16b5a2cSChristoph Hellwig }
3599c16b5a2cSChristoph Hellwig 
3600c16b5a2cSChristoph Hellwig static AIOPool bdrv_em_aio_pool = {
3601c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
3602c16b5a2cSChristoph Hellwig     .cancel             = bdrv_aio_cancel_em,
3603c16b5a2cSChristoph Hellwig };
3604c16b5a2cSChristoph Hellwig 
360583f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
3606beac80cdSbellard {
3607ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
3608f141eafeSaliguori 
3609f141eafeSaliguori     if (!acb->is_write)
361003396148SMichael Tokarev         qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
3611ceb42de8Saliguori     qemu_vfree(acb->bounce);
3612ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
36136a7ad299SDor Laor     qemu_bh_delete(acb->bh);
361436afc451SAvi Kivity     acb->bh = NULL;
3615ce1a14dcSpbrook     qemu_aio_release(acb);
3616beac80cdSbellard }
3617beac80cdSbellard 
3618f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
3619f141eafeSaliguori                                             int64_t sector_num,
3620f141eafeSaliguori                                             QEMUIOVector *qiov,
3621f141eafeSaliguori                                             int nb_sectors,
3622f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
3623f141eafeSaliguori                                             void *opaque,
3624f141eafeSaliguori                                             int is_write)
3625f141eafeSaliguori 
3626ea2384d3Sbellard {
3627ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
362883f64091Sbellard 
3629c16b5a2cSChristoph Hellwig     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
3630f141eafeSaliguori     acb->is_write = is_write;
3631f141eafeSaliguori     acb->qiov = qiov;
3632e268ca52Saliguori     acb->bounce = qemu_blockalign(bs, qiov->size);
3633ce1a14dcSpbrook     acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
3634f141eafeSaliguori 
3635f141eafeSaliguori     if (is_write) {
3636d5e6b161SMichael Tokarev         qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
36371ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
3638f141eafeSaliguori     } else {
36391ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
3640f141eafeSaliguori     }
3641f141eafeSaliguori 
3642ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
3643f141eafeSaliguori 
3644ce1a14dcSpbrook     return &acb->common;
36457a6cba61Spbrook }
36467a6cba61Spbrook 
3647f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
3648f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
3649ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
365083f64091Sbellard {
3651f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
365283f64091Sbellard }
365383f64091Sbellard 
3654f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
3655f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
3656f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
3657f141eafeSaliguori {
3658f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
3659f141eafeSaliguori }
3660f141eafeSaliguori 
366168485420SKevin Wolf 
366268485420SKevin Wolf typedef struct BlockDriverAIOCBCoroutine {
366368485420SKevin Wolf     BlockDriverAIOCB common;
366468485420SKevin Wolf     BlockRequest req;
366568485420SKevin Wolf     bool is_write;
366668485420SKevin Wolf     QEMUBH* bh;
366768485420SKevin Wolf } BlockDriverAIOCBCoroutine;
366868485420SKevin Wolf 
366968485420SKevin Wolf static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
367068485420SKevin Wolf {
367168485420SKevin Wolf     qemu_aio_flush();
367268485420SKevin Wolf }
367368485420SKevin Wolf 
367468485420SKevin Wolf static AIOPool bdrv_em_co_aio_pool = {
367568485420SKevin Wolf     .aiocb_size         = sizeof(BlockDriverAIOCBCoroutine),
367668485420SKevin Wolf     .cancel             = bdrv_aio_co_cancel_em,
367768485420SKevin Wolf };
367868485420SKevin Wolf 
367935246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque)
368068485420SKevin Wolf {
368168485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb = opaque;
368268485420SKevin Wolf 
368368485420SKevin Wolf     acb->common.cb(acb->common.opaque, acb->req.error);
368468485420SKevin Wolf     qemu_bh_delete(acb->bh);
368568485420SKevin Wolf     qemu_aio_release(acb);
368668485420SKevin Wolf }
368768485420SKevin Wolf 
3688b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
3689b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque)
3690b2a61371SStefan Hajnoczi {
3691b2a61371SStefan Hajnoczi     BlockDriverAIOCBCoroutine *acb = opaque;
3692b2a61371SStefan Hajnoczi     BlockDriverState *bs = acb->common.bs;
3693b2a61371SStefan Hajnoczi 
3694b2a61371SStefan Hajnoczi     if (!acb->is_write) {
3695b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
3696470c0504SStefan Hajnoczi             acb->req.nb_sectors, acb->req.qiov, 0);
3697b2a61371SStefan Hajnoczi     } else {
3698b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
3699f08f2ddaSStefan Hajnoczi             acb->req.nb_sectors, acb->req.qiov, 0);
3700b2a61371SStefan Hajnoczi     }
3701b2a61371SStefan Hajnoczi 
370235246a68SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
3703b2a61371SStefan Hajnoczi     qemu_bh_schedule(acb->bh);
3704b2a61371SStefan Hajnoczi }
3705b2a61371SStefan Hajnoczi 
370668485420SKevin Wolf static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
370768485420SKevin Wolf                                                int64_t sector_num,
370868485420SKevin Wolf                                                QEMUIOVector *qiov,
370968485420SKevin Wolf                                                int nb_sectors,
371068485420SKevin Wolf                                                BlockDriverCompletionFunc *cb,
371168485420SKevin Wolf                                                void *opaque,
37128c5873d6SStefan Hajnoczi                                                bool is_write)
371368485420SKevin Wolf {
371468485420SKevin Wolf     Coroutine *co;
371568485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb;
371668485420SKevin Wolf 
371768485420SKevin Wolf     acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
371868485420SKevin Wolf     acb->req.sector = sector_num;
371968485420SKevin Wolf     acb->req.nb_sectors = nb_sectors;
372068485420SKevin Wolf     acb->req.qiov = qiov;
372168485420SKevin Wolf     acb->is_write = is_write;
372268485420SKevin Wolf 
37238c5873d6SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_co_do_rw);
372468485420SKevin Wolf     qemu_coroutine_enter(co, acb);
372568485420SKevin Wolf 
372668485420SKevin Wolf     return &acb->common;
372768485420SKevin Wolf }
372868485420SKevin Wolf 
372907f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
3730b2e12bc6SChristoph Hellwig {
373107f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
373207f07615SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
3733b2e12bc6SChristoph Hellwig 
373407f07615SPaolo Bonzini     acb->req.error = bdrv_co_flush(bs);
373507f07615SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
3736b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
3737b2e12bc6SChristoph Hellwig }
3738b2e12bc6SChristoph Hellwig 
373907f07615SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
3740016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
3741016f5cf6SAlexander Graf {
374207f07615SPaolo Bonzini     trace_bdrv_aio_flush(bs, opaque);
3743016f5cf6SAlexander Graf 
374407f07615SPaolo Bonzini     Coroutine *co;
374507f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
3746016f5cf6SAlexander Graf 
374707f07615SPaolo Bonzini     acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
374807f07615SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
374907f07615SPaolo Bonzini     qemu_coroutine_enter(co, acb);
3750016f5cf6SAlexander Graf 
3751016f5cf6SAlexander Graf     return &acb->common;
3752016f5cf6SAlexander Graf }
3753016f5cf6SAlexander Graf 
37544265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
37554265d620SPaolo Bonzini {
37564265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
37574265d620SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
37584265d620SPaolo Bonzini 
37594265d620SPaolo Bonzini     acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
37604265d620SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
37614265d620SPaolo Bonzini     qemu_bh_schedule(acb->bh);
37624265d620SPaolo Bonzini }
37634265d620SPaolo Bonzini 
37644265d620SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
37654265d620SPaolo Bonzini         int64_t sector_num, int nb_sectors,
37664265d620SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
37674265d620SPaolo Bonzini {
37684265d620SPaolo Bonzini     Coroutine *co;
37694265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
37704265d620SPaolo Bonzini 
37714265d620SPaolo Bonzini     trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
37724265d620SPaolo Bonzini 
37734265d620SPaolo Bonzini     acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
37744265d620SPaolo Bonzini     acb->req.sector = sector_num;
37754265d620SPaolo Bonzini     acb->req.nb_sectors = nb_sectors;
37764265d620SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
37774265d620SPaolo Bonzini     qemu_coroutine_enter(co, acb);
37784265d620SPaolo Bonzini 
37794265d620SPaolo Bonzini     return &acb->common;
37804265d620SPaolo Bonzini }
37814265d620SPaolo Bonzini 
3782ea2384d3Sbellard void bdrv_init(void)
3783ea2384d3Sbellard {
37845efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
3785ea2384d3Sbellard }
3786ce1a14dcSpbrook 
3787eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
3788eb852011SMarkus Armbruster {
3789eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
3790eb852011SMarkus Armbruster     bdrv_init();
3791eb852011SMarkus Armbruster }
3792eb852011SMarkus Armbruster 
3793c16b5a2cSChristoph Hellwig void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
37946bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
37956bbff9a0Saliguori {
3796ce1a14dcSpbrook     BlockDriverAIOCB *acb;
3797ce1a14dcSpbrook 
37986bbff9a0Saliguori     if (pool->free_aiocb) {
37996bbff9a0Saliguori         acb = pool->free_aiocb;
38006bbff9a0Saliguori         pool->free_aiocb = acb->next;
3801ce1a14dcSpbrook     } else {
38027267c094SAnthony Liguori         acb = g_malloc0(pool->aiocb_size);
38036bbff9a0Saliguori         acb->pool = pool;
3804ce1a14dcSpbrook     }
3805ce1a14dcSpbrook     acb->bs = bs;
3806ce1a14dcSpbrook     acb->cb = cb;
3807ce1a14dcSpbrook     acb->opaque = opaque;
3808ce1a14dcSpbrook     return acb;
3809ce1a14dcSpbrook }
3810ce1a14dcSpbrook 
3811ce1a14dcSpbrook void qemu_aio_release(void *p)
3812ce1a14dcSpbrook {
38136bbff9a0Saliguori     BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
38146bbff9a0Saliguori     AIOPool *pool = acb->pool;
38156bbff9a0Saliguori     acb->next = pool->free_aiocb;
38166bbff9a0Saliguori     pool->free_aiocb = acb;
3817ce1a14dcSpbrook }
381819cb3738Sbellard 
381919cb3738Sbellard /**************************************************************/
3820f9f05dc5SKevin Wolf /* Coroutine block device emulation */
3821f9f05dc5SKevin Wolf 
3822f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion {
3823f9f05dc5SKevin Wolf     Coroutine *coroutine;
3824f9f05dc5SKevin Wolf     int ret;
3825f9f05dc5SKevin Wolf } CoroutineIOCompletion;
3826f9f05dc5SKevin Wolf 
3827f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret)
3828f9f05dc5SKevin Wolf {
3829f9f05dc5SKevin Wolf     CoroutineIOCompletion *co = opaque;
3830f9f05dc5SKevin Wolf 
3831f9f05dc5SKevin Wolf     co->ret = ret;
3832f9f05dc5SKevin Wolf     qemu_coroutine_enter(co->coroutine, NULL);
3833f9f05dc5SKevin Wolf }
3834f9f05dc5SKevin Wolf 
3835f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
3836f9f05dc5SKevin Wolf                                       int nb_sectors, QEMUIOVector *iov,
3837f9f05dc5SKevin Wolf                                       bool is_write)
3838f9f05dc5SKevin Wolf {
3839f9f05dc5SKevin Wolf     CoroutineIOCompletion co = {
3840f9f05dc5SKevin Wolf         .coroutine = qemu_coroutine_self(),
3841f9f05dc5SKevin Wolf     };
3842f9f05dc5SKevin Wolf     BlockDriverAIOCB *acb;
3843f9f05dc5SKevin Wolf 
3844f9f05dc5SKevin Wolf     if (is_write) {
3845a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
3846f9f05dc5SKevin Wolf                                        bdrv_co_io_em_complete, &co);
3847f9f05dc5SKevin Wolf     } else {
3848a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
3849f9f05dc5SKevin Wolf                                       bdrv_co_io_em_complete, &co);
3850f9f05dc5SKevin Wolf     }
3851f9f05dc5SKevin Wolf 
385259370aaaSStefan Hajnoczi     trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
3853f9f05dc5SKevin Wolf     if (!acb) {
3854f9f05dc5SKevin Wolf         return -EIO;
3855f9f05dc5SKevin Wolf     }
3856f9f05dc5SKevin Wolf     qemu_coroutine_yield();
3857f9f05dc5SKevin Wolf 
3858f9f05dc5SKevin Wolf     return co.ret;
3859f9f05dc5SKevin Wolf }
3860f9f05dc5SKevin Wolf 
3861f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
3862f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
3863f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
3864f9f05dc5SKevin Wolf {
3865f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
3866f9f05dc5SKevin Wolf }
3867f9f05dc5SKevin Wolf 
3868f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
3869f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
3870f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
3871f9f05dc5SKevin Wolf {
3872f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
3873f9f05dc5SKevin Wolf }
3874f9f05dc5SKevin Wolf 
387507f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque)
3876e7a8a783SKevin Wolf {
387707f07615SPaolo Bonzini     RwCo *rwco = opaque;
387807f07615SPaolo Bonzini 
387907f07615SPaolo Bonzini     rwco->ret = bdrv_co_flush(rwco->bs);
388007f07615SPaolo Bonzini }
388107f07615SPaolo Bonzini 
388207f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
388307f07615SPaolo Bonzini {
3884eb489bb1SKevin Wolf     int ret;
3885eb489bb1SKevin Wolf 
388629cdb251SPaolo Bonzini     if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
388707f07615SPaolo Bonzini         return 0;
3888eb489bb1SKevin Wolf     }
3889eb489bb1SKevin Wolf 
3890ca716364SKevin Wolf     /* Write back cached data to the OS even with cache=unsafe */
3891eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_os) {
3892eb489bb1SKevin Wolf         ret = bs->drv->bdrv_co_flush_to_os(bs);
3893eb489bb1SKevin Wolf         if (ret < 0) {
3894eb489bb1SKevin Wolf             return ret;
3895eb489bb1SKevin Wolf         }
3896eb489bb1SKevin Wolf     }
3897eb489bb1SKevin Wolf 
3898ca716364SKevin Wolf     /* But don't actually force it to the disk with cache=unsafe */
3899ca716364SKevin Wolf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
3900d4c82329SKevin Wolf         goto flush_parent;
3901ca716364SKevin Wolf     }
3902ca716364SKevin Wolf 
3903eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_disk) {
390429cdb251SPaolo Bonzini         ret = bs->drv->bdrv_co_flush_to_disk(bs);
390507f07615SPaolo Bonzini     } else if (bs->drv->bdrv_aio_flush) {
390607f07615SPaolo Bonzini         BlockDriverAIOCB *acb;
3907e7a8a783SKevin Wolf         CoroutineIOCompletion co = {
3908e7a8a783SKevin Wolf             .coroutine = qemu_coroutine_self(),
3909e7a8a783SKevin Wolf         };
3910e7a8a783SKevin Wolf 
391107f07615SPaolo Bonzini         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
391207f07615SPaolo Bonzini         if (acb == NULL) {
391329cdb251SPaolo Bonzini             ret = -EIO;
391407f07615SPaolo Bonzini         } else {
3915e7a8a783SKevin Wolf             qemu_coroutine_yield();
391629cdb251SPaolo Bonzini             ret = co.ret;
3917e7a8a783SKevin Wolf         }
391807f07615SPaolo Bonzini     } else {
391907f07615SPaolo Bonzini         /*
392007f07615SPaolo Bonzini          * Some block drivers always operate in either writethrough or unsafe
392107f07615SPaolo Bonzini          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
392207f07615SPaolo Bonzini          * know how the server works (because the behaviour is hardcoded or
392307f07615SPaolo Bonzini          * depends on server-side configuration), so we can't ensure that
392407f07615SPaolo Bonzini          * everything is safe on disk. Returning an error doesn't work because
392507f07615SPaolo Bonzini          * that would break guests even if the server operates in writethrough
392607f07615SPaolo Bonzini          * mode.
392707f07615SPaolo Bonzini          *
392807f07615SPaolo Bonzini          * Let's hope the user knows what he's doing.
392907f07615SPaolo Bonzini          */
393029cdb251SPaolo Bonzini         ret = 0;
393107f07615SPaolo Bonzini     }
393229cdb251SPaolo Bonzini     if (ret < 0) {
393329cdb251SPaolo Bonzini         return ret;
393429cdb251SPaolo Bonzini     }
393529cdb251SPaolo Bonzini 
393629cdb251SPaolo Bonzini     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
393729cdb251SPaolo Bonzini      * in the case of cache=unsafe, so there are no useless flushes.
393829cdb251SPaolo Bonzini      */
3939d4c82329SKevin Wolf flush_parent:
394029cdb251SPaolo Bonzini     return bdrv_co_flush(bs->file);
394107f07615SPaolo Bonzini }
394207f07615SPaolo Bonzini 
39430f15423cSAnthony Liguori void bdrv_invalidate_cache(BlockDriverState *bs)
39440f15423cSAnthony Liguori {
39450f15423cSAnthony Liguori     if (bs->drv && bs->drv->bdrv_invalidate_cache) {
39460f15423cSAnthony Liguori         bs->drv->bdrv_invalidate_cache(bs);
39470f15423cSAnthony Liguori     }
39480f15423cSAnthony Liguori }
39490f15423cSAnthony Liguori 
39500f15423cSAnthony Liguori void bdrv_invalidate_cache_all(void)
39510f15423cSAnthony Liguori {
39520f15423cSAnthony Liguori     BlockDriverState *bs;
39530f15423cSAnthony Liguori 
39540f15423cSAnthony Liguori     QTAILQ_FOREACH(bs, &bdrv_states, list) {
39550f15423cSAnthony Liguori         bdrv_invalidate_cache(bs);
39560f15423cSAnthony Liguori     }
39570f15423cSAnthony Liguori }
39580f15423cSAnthony Liguori 
395907789269SBenoît Canet void bdrv_clear_incoming_migration_all(void)
396007789269SBenoît Canet {
396107789269SBenoît Canet     BlockDriverState *bs;
396207789269SBenoît Canet 
396307789269SBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, list) {
396407789269SBenoît Canet         bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
396507789269SBenoît Canet     }
396607789269SBenoît Canet }
396707789269SBenoît Canet 
396807f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs)
396907f07615SPaolo Bonzini {
397007f07615SPaolo Bonzini     Coroutine *co;
397107f07615SPaolo Bonzini     RwCo rwco = {
397207f07615SPaolo Bonzini         .bs = bs,
397307f07615SPaolo Bonzini         .ret = NOT_DONE,
397407f07615SPaolo Bonzini     };
397507f07615SPaolo Bonzini 
397607f07615SPaolo Bonzini     if (qemu_in_coroutine()) {
397707f07615SPaolo Bonzini         /* Fast-path if already in coroutine context */
397807f07615SPaolo Bonzini         bdrv_flush_co_entry(&rwco);
397907f07615SPaolo Bonzini     } else {
398007f07615SPaolo Bonzini         co = qemu_coroutine_create(bdrv_flush_co_entry);
398107f07615SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
398207f07615SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
398307f07615SPaolo Bonzini             qemu_aio_wait();
398407f07615SPaolo Bonzini         }
398507f07615SPaolo Bonzini     }
398607f07615SPaolo Bonzini 
398707f07615SPaolo Bonzini     return rwco.ret;
398807f07615SPaolo Bonzini }
3989e7a8a783SKevin Wolf 
39904265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque)
39914265d620SPaolo Bonzini {
39924265d620SPaolo Bonzini     RwCo *rwco = opaque;
39934265d620SPaolo Bonzini 
39944265d620SPaolo Bonzini     rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
39954265d620SPaolo Bonzini }
39964265d620SPaolo Bonzini 
39974265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
39984265d620SPaolo Bonzini                                  int nb_sectors)
39994265d620SPaolo Bonzini {
40004265d620SPaolo Bonzini     if (!bs->drv) {
40014265d620SPaolo Bonzini         return -ENOMEDIUM;
40024265d620SPaolo Bonzini     } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
40034265d620SPaolo Bonzini         return -EIO;
40044265d620SPaolo Bonzini     } else if (bs->read_only) {
40054265d620SPaolo Bonzini         return -EROFS;
40064265d620SPaolo Bonzini     } else if (bs->drv->bdrv_co_discard) {
40074265d620SPaolo Bonzini         return bs->drv->bdrv_co_discard(bs, sector_num, nb_sectors);
40084265d620SPaolo Bonzini     } else if (bs->drv->bdrv_aio_discard) {
40094265d620SPaolo Bonzini         BlockDriverAIOCB *acb;
40104265d620SPaolo Bonzini         CoroutineIOCompletion co = {
40114265d620SPaolo Bonzini             .coroutine = qemu_coroutine_self(),
40124265d620SPaolo Bonzini         };
40134265d620SPaolo Bonzini 
40144265d620SPaolo Bonzini         acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
40154265d620SPaolo Bonzini                                         bdrv_co_io_em_complete, &co);
40164265d620SPaolo Bonzini         if (acb == NULL) {
40174265d620SPaolo Bonzini             return -EIO;
40184265d620SPaolo Bonzini         } else {
40194265d620SPaolo Bonzini             qemu_coroutine_yield();
40204265d620SPaolo Bonzini             return co.ret;
40214265d620SPaolo Bonzini         }
40224265d620SPaolo Bonzini     } else {
40234265d620SPaolo Bonzini         return 0;
40244265d620SPaolo Bonzini     }
40254265d620SPaolo Bonzini }
40264265d620SPaolo Bonzini 
40274265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
40284265d620SPaolo Bonzini {
40294265d620SPaolo Bonzini     Coroutine *co;
40304265d620SPaolo Bonzini     RwCo rwco = {
40314265d620SPaolo Bonzini         .bs = bs,
40324265d620SPaolo Bonzini         .sector_num = sector_num,
40334265d620SPaolo Bonzini         .nb_sectors = nb_sectors,
40344265d620SPaolo Bonzini         .ret = NOT_DONE,
40354265d620SPaolo Bonzini     };
40364265d620SPaolo Bonzini 
40374265d620SPaolo Bonzini     if (qemu_in_coroutine()) {
40384265d620SPaolo Bonzini         /* Fast-path if already in coroutine context */
40394265d620SPaolo Bonzini         bdrv_discard_co_entry(&rwco);
40404265d620SPaolo Bonzini     } else {
40414265d620SPaolo Bonzini         co = qemu_coroutine_create(bdrv_discard_co_entry);
40424265d620SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
40434265d620SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
40444265d620SPaolo Bonzini             qemu_aio_wait();
40454265d620SPaolo Bonzini         }
40464265d620SPaolo Bonzini     }
40474265d620SPaolo Bonzini 
40484265d620SPaolo Bonzini     return rwco.ret;
40494265d620SPaolo Bonzini }
40504265d620SPaolo Bonzini 
4051f9f05dc5SKevin Wolf /**************************************************************/
405219cb3738Sbellard /* removable device support */
405319cb3738Sbellard 
405419cb3738Sbellard /**
405519cb3738Sbellard  * Return TRUE if the media is present
405619cb3738Sbellard  */
405719cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
405819cb3738Sbellard {
405919cb3738Sbellard     BlockDriver *drv = bs->drv;
4060a1aff5bfSMarkus Armbruster 
406119cb3738Sbellard     if (!drv)
406219cb3738Sbellard         return 0;
406319cb3738Sbellard     if (!drv->bdrv_is_inserted)
4064a1aff5bfSMarkus Armbruster         return 1;
4065a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
406619cb3738Sbellard }
406719cb3738Sbellard 
406819cb3738Sbellard /**
40698e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
40708e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
407119cb3738Sbellard  */
407219cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
407319cb3738Sbellard {
407419cb3738Sbellard     BlockDriver *drv = bs->drv;
407519cb3738Sbellard 
40768e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
40778e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
40788e49ca46SMarkus Armbruster     }
40798e49ca46SMarkus Armbruster     return -ENOTSUP;
408019cb3738Sbellard }
408119cb3738Sbellard 
408219cb3738Sbellard /**
408319cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
408419cb3738Sbellard  */
4085f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
408619cb3738Sbellard {
408719cb3738Sbellard     BlockDriver *drv = bs->drv;
408819cb3738Sbellard 
4089822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
4090822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
409119cb3738Sbellard     }
40926f382ed2SLuiz Capitulino 
40936f382ed2SLuiz Capitulino     if (bs->device_name[0] != '\0') {
40946f382ed2SLuiz Capitulino         bdrv_emit_qmp_eject_event(bs, eject_flag);
40956f382ed2SLuiz Capitulino     }
409619cb3738Sbellard }
409719cb3738Sbellard 
409819cb3738Sbellard /**
409919cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
410019cb3738Sbellard  * to eject it manually).
410119cb3738Sbellard  */
4102025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
410319cb3738Sbellard {
410419cb3738Sbellard     BlockDriver *drv = bs->drv;
410519cb3738Sbellard 
4106025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
4107b8c6d095SStefan Hajnoczi 
4108025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
4109025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
411019cb3738Sbellard     }
411119cb3738Sbellard }
4112985a03b0Sths 
4113985a03b0Sths /* needed for generic scsi interface */
4114985a03b0Sths 
4115985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
4116985a03b0Sths {
4117985a03b0Sths     BlockDriver *drv = bs->drv;
4118985a03b0Sths 
4119985a03b0Sths     if (drv && drv->bdrv_ioctl)
4120985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
4121985a03b0Sths     return -ENOTSUP;
4122985a03b0Sths }
41237d780669Saliguori 
4124221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
4125221f715dSaliguori         unsigned long int req, void *buf,
41267d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
41277d780669Saliguori {
4128221f715dSaliguori     BlockDriver *drv = bs->drv;
41297d780669Saliguori 
4130221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
4131221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
4132221f715dSaliguori     return NULL;
41337d780669Saliguori }
4134e268ca52Saliguori 
41357b6f9300SMarkus Armbruster void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
41367b6f9300SMarkus Armbruster {
41377b6f9300SMarkus Armbruster     bs->buffer_alignment = align;
41387b6f9300SMarkus Armbruster }
41397cd1e32aSlirans@il.ibm.com 
4140e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
4141e268ca52Saliguori {
4142e268ca52Saliguori     return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
4143e268ca52Saliguori }
41447cd1e32aSlirans@il.ibm.com 
41457cd1e32aSlirans@il.ibm.com void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
41467cd1e32aSlirans@il.ibm.com {
41477cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
4148a55eb92cSJan Kiszka 
4149aaa0eb75SLiran Schour     bs->dirty_count = 0;
41507cd1e32aSlirans@il.ibm.com     if (enable) {
4151c6d22830SJan Kiszka         if (!bs->dirty_bitmap) {
4152c6d22830SJan Kiszka             bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
415371df14fcSPaolo Bonzini                     BDRV_SECTORS_PER_DIRTY_CHUNK * BITS_PER_LONG - 1;
415471df14fcSPaolo Bonzini             bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * BITS_PER_LONG;
41557cd1e32aSlirans@il.ibm.com 
415671df14fcSPaolo Bonzini             bs->dirty_bitmap = g_new0(unsigned long, bitmap_size);
41577cd1e32aSlirans@il.ibm.com         }
41587cd1e32aSlirans@il.ibm.com     } else {
4159c6d22830SJan Kiszka         if (bs->dirty_bitmap) {
41607267c094SAnthony Liguori             g_free(bs->dirty_bitmap);
4161c6d22830SJan Kiszka             bs->dirty_bitmap = NULL;
41627cd1e32aSlirans@il.ibm.com         }
41637cd1e32aSlirans@il.ibm.com     }
41647cd1e32aSlirans@il.ibm.com }
41657cd1e32aSlirans@il.ibm.com 
41667cd1e32aSlirans@il.ibm.com int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
41677cd1e32aSlirans@il.ibm.com {
41686ea44308SJan Kiszka     int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
41697cd1e32aSlirans@il.ibm.com 
4170c6d22830SJan Kiszka     if (bs->dirty_bitmap &&
4171c6d22830SJan Kiszka         (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
41726d59fec1SMarcelo Tosatti         return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
41736d59fec1SMarcelo Tosatti             (1UL << (chunk % (sizeof(unsigned long) * 8))));
41747cd1e32aSlirans@il.ibm.com     } else {
41757cd1e32aSlirans@il.ibm.com         return 0;
41767cd1e32aSlirans@il.ibm.com     }
41777cd1e32aSlirans@il.ibm.com }
41787cd1e32aSlirans@il.ibm.com 
41797cd1e32aSlirans@il.ibm.com void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
41807cd1e32aSlirans@il.ibm.com                       int nr_sectors)
41817cd1e32aSlirans@il.ibm.com {
41827cd1e32aSlirans@il.ibm.com     set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
41837cd1e32aSlirans@il.ibm.com }
4184aaa0eb75SLiran Schour 
4185aaa0eb75SLiran Schour int64_t bdrv_get_dirty_count(BlockDriverState *bs)
4186aaa0eb75SLiran Schour {
4187aaa0eb75SLiran Schour     return bs->dirty_count;
4188aaa0eb75SLiran Schour }
4189f88e1a42SJes Sorensen 
4190db593f25SMarcelo Tosatti void bdrv_set_in_use(BlockDriverState *bs, int in_use)
4191db593f25SMarcelo Tosatti {
4192db593f25SMarcelo Tosatti     assert(bs->in_use != in_use);
4193db593f25SMarcelo Tosatti     bs->in_use = in_use;
4194db593f25SMarcelo Tosatti }
4195db593f25SMarcelo Tosatti 
4196db593f25SMarcelo Tosatti int bdrv_in_use(BlockDriverState *bs)
4197db593f25SMarcelo Tosatti {
4198db593f25SMarcelo Tosatti     return bs->in_use;
4199db593f25SMarcelo Tosatti }
4200db593f25SMarcelo Tosatti 
420128a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
420228a7282aSLuiz Capitulino {
4203d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
420458e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
420528a7282aSLuiz Capitulino }
420628a7282aSLuiz Capitulino 
420728a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
420828a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
420928a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
421028a7282aSLuiz Capitulino {
4211d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
421228a7282aSLuiz Capitulino            (bs->on_write_error == BLOCK_ERR_STOP_ENOSPC ||
421328a7282aSLuiz Capitulino             bs->on_write_error == BLOCK_ERR_STOP_ANY    ||
421428a7282aSLuiz Capitulino             bs->on_read_error == BLOCK_ERR_STOP_ANY));
421528a7282aSLuiz Capitulino }
421628a7282aSLuiz Capitulino 
421728a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
421828a7282aSLuiz Capitulino {
4219d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
422028a7282aSLuiz Capitulino }
422128a7282aSLuiz Capitulino 
422228a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
422328a7282aSLuiz Capitulino {
422428a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
422558e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
422628a7282aSLuiz Capitulino     }
422728a7282aSLuiz Capitulino }
422828a7282aSLuiz Capitulino 
422928a7282aSLuiz Capitulino /* XXX: Today this is set by device models because it makes the implementation
423028a7282aSLuiz Capitulino    quite simple. However, the block layer knows about the error, so it's
423128a7282aSLuiz Capitulino    possible to implement this without device models being involved */
423228a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
423328a7282aSLuiz Capitulino {
423458e21ef5SLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs) &&
423558e21ef5SLuiz Capitulino         bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
423628a7282aSLuiz Capitulino         assert(error >= 0);
423758e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
423858e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
423928a7282aSLuiz Capitulino     }
424028a7282aSLuiz Capitulino }
424128a7282aSLuiz Capitulino 
4242a597e79cSChristoph Hellwig void
4243a597e79cSChristoph Hellwig bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
4244a597e79cSChristoph Hellwig         enum BlockAcctType type)
4245a597e79cSChristoph Hellwig {
4246a597e79cSChristoph Hellwig     assert(type < BDRV_MAX_IOTYPE);
4247a597e79cSChristoph Hellwig 
4248a597e79cSChristoph Hellwig     cookie->bytes = bytes;
4249c488c7f6SChristoph Hellwig     cookie->start_time_ns = get_clock();
4250a597e79cSChristoph Hellwig     cookie->type = type;
4251a597e79cSChristoph Hellwig }
4252a597e79cSChristoph Hellwig 
4253a597e79cSChristoph Hellwig void
4254a597e79cSChristoph Hellwig bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
4255a597e79cSChristoph Hellwig {
4256a597e79cSChristoph Hellwig     assert(cookie->type < BDRV_MAX_IOTYPE);
4257a597e79cSChristoph Hellwig 
4258a597e79cSChristoph Hellwig     bs->nr_bytes[cookie->type] += cookie->bytes;
4259a597e79cSChristoph Hellwig     bs->nr_ops[cookie->type]++;
4260c488c7f6SChristoph Hellwig     bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
4261a597e79cSChristoph Hellwig }
4262a597e79cSChristoph Hellwig 
4263f88e1a42SJes Sorensen int bdrv_img_create(const char *filename, const char *fmt,
4264f88e1a42SJes Sorensen                     const char *base_filename, const char *base_fmt,
4265f88e1a42SJes Sorensen                     char *options, uint64_t img_size, int flags)
4266f88e1a42SJes Sorensen {
4267f88e1a42SJes Sorensen     QEMUOptionParameter *param = NULL, *create_options = NULL;
4268d220894eSKevin Wolf     QEMUOptionParameter *backing_fmt, *backing_file, *size;
4269f88e1a42SJes Sorensen     BlockDriverState *bs = NULL;
4270f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
427196df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
4272f88e1a42SJes Sorensen     int ret = 0;
4273f88e1a42SJes Sorensen 
4274f88e1a42SJes Sorensen     /* Find driver and parse its options */
4275f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
4276f88e1a42SJes Sorensen     if (!drv) {
4277f88e1a42SJes Sorensen         error_report("Unknown file format '%s'", fmt);
42784f70f249SJes Sorensen         ret = -EINVAL;
4279f88e1a42SJes Sorensen         goto out;
4280f88e1a42SJes Sorensen     }
4281f88e1a42SJes Sorensen 
4282f88e1a42SJes Sorensen     proto_drv = bdrv_find_protocol(filename);
4283f88e1a42SJes Sorensen     if (!proto_drv) {
4284f88e1a42SJes Sorensen         error_report("Unknown protocol '%s'", filename);
42854f70f249SJes Sorensen         ret = -EINVAL;
4286f88e1a42SJes Sorensen         goto out;
4287f88e1a42SJes Sorensen     }
4288f88e1a42SJes Sorensen 
4289f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
4290f88e1a42SJes Sorensen                                               drv->create_options);
4291f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
4292f88e1a42SJes Sorensen                                               proto_drv->create_options);
4293f88e1a42SJes Sorensen 
4294f88e1a42SJes Sorensen     /* Create parameter list with default values */
4295f88e1a42SJes Sorensen     param = parse_option_parameters("", create_options, param);
4296f88e1a42SJes Sorensen 
4297f88e1a42SJes Sorensen     set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
4298f88e1a42SJes Sorensen 
4299f88e1a42SJes Sorensen     /* Parse -o options */
4300f88e1a42SJes Sorensen     if (options) {
4301f88e1a42SJes Sorensen         param = parse_option_parameters(options, create_options, param);
4302f88e1a42SJes Sorensen         if (param == NULL) {
4303f88e1a42SJes Sorensen             error_report("Invalid options for file format '%s'.", fmt);
43044f70f249SJes Sorensen             ret = -EINVAL;
4305f88e1a42SJes Sorensen             goto out;
4306f88e1a42SJes Sorensen         }
4307f88e1a42SJes Sorensen     }
4308f88e1a42SJes Sorensen 
4309f88e1a42SJes Sorensen     if (base_filename) {
4310f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
4311f88e1a42SJes Sorensen                                  base_filename)) {
4312f88e1a42SJes Sorensen             error_report("Backing file not supported for file format '%s'",
4313f88e1a42SJes Sorensen                          fmt);
43144f70f249SJes Sorensen             ret = -EINVAL;
4315f88e1a42SJes Sorensen             goto out;
4316f88e1a42SJes Sorensen         }
4317f88e1a42SJes Sorensen     }
4318f88e1a42SJes Sorensen 
4319f88e1a42SJes Sorensen     if (base_fmt) {
4320f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
4321f88e1a42SJes Sorensen             error_report("Backing file format not supported for file "
4322f88e1a42SJes Sorensen                          "format '%s'", fmt);
43234f70f249SJes Sorensen             ret = -EINVAL;
4324f88e1a42SJes Sorensen             goto out;
4325f88e1a42SJes Sorensen         }
4326f88e1a42SJes Sorensen     }
4327f88e1a42SJes Sorensen 
4328792da93aSJes Sorensen     backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
4329792da93aSJes Sorensen     if (backing_file && backing_file->value.s) {
4330792da93aSJes Sorensen         if (!strcmp(filename, backing_file->value.s)) {
4331792da93aSJes Sorensen             error_report("Error: Trying to create an image with the "
4332792da93aSJes Sorensen                          "same filename as the backing file");
43334f70f249SJes Sorensen             ret = -EINVAL;
4334792da93aSJes Sorensen             goto out;
4335792da93aSJes Sorensen         }
4336792da93aSJes Sorensen     }
4337792da93aSJes Sorensen 
4338f88e1a42SJes Sorensen     backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
4339f88e1a42SJes Sorensen     if (backing_fmt && backing_fmt->value.s) {
434096df67d1SStefan Hajnoczi         backing_drv = bdrv_find_format(backing_fmt->value.s);
434196df67d1SStefan Hajnoczi         if (!backing_drv) {
4342f88e1a42SJes Sorensen             error_report("Unknown backing file format '%s'",
4343f88e1a42SJes Sorensen                          backing_fmt->value.s);
43444f70f249SJes Sorensen             ret = -EINVAL;
4345f88e1a42SJes Sorensen             goto out;
4346f88e1a42SJes Sorensen         }
4347f88e1a42SJes Sorensen     }
4348f88e1a42SJes Sorensen 
4349f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
4350f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
4351d220894eSKevin Wolf     size = get_option_parameter(param, BLOCK_OPT_SIZE);
4352d220894eSKevin Wolf     if (size && size->value.n == -1) {
4353f88e1a42SJes Sorensen         if (backing_file && backing_file->value.s) {
4354f88e1a42SJes Sorensen             uint64_t size;
4355f88e1a42SJes Sorensen             char buf[32];
435663090dacSPaolo Bonzini             int back_flags;
435763090dacSPaolo Bonzini 
435863090dacSPaolo Bonzini             /* backing files always opened read-only */
435963090dacSPaolo Bonzini             back_flags =
436063090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
4361f88e1a42SJes Sorensen 
4362f88e1a42SJes Sorensen             bs = bdrv_new("");
4363f88e1a42SJes Sorensen 
436463090dacSPaolo Bonzini             ret = bdrv_open(bs, backing_file->value.s, back_flags, backing_drv);
4365f88e1a42SJes Sorensen             if (ret < 0) {
436696df67d1SStefan Hajnoczi                 error_report("Could not open '%s'", backing_file->value.s);
4367f88e1a42SJes Sorensen                 goto out;
4368f88e1a42SJes Sorensen             }
4369f88e1a42SJes Sorensen             bdrv_get_geometry(bs, &size);
4370f88e1a42SJes Sorensen             size *= 512;
4371f88e1a42SJes Sorensen 
4372f88e1a42SJes Sorensen             snprintf(buf, sizeof(buf), "%" PRId64, size);
4373f88e1a42SJes Sorensen             set_option_parameter(param, BLOCK_OPT_SIZE, buf);
4374f88e1a42SJes Sorensen         } else {
4375f88e1a42SJes Sorensen             error_report("Image creation needs a size parameter");
43764f70f249SJes Sorensen             ret = -EINVAL;
4377f88e1a42SJes Sorensen             goto out;
4378f88e1a42SJes Sorensen         }
4379f88e1a42SJes Sorensen     }
4380f88e1a42SJes Sorensen 
4381f88e1a42SJes Sorensen     printf("Formatting '%s', fmt=%s ", filename, fmt);
4382f88e1a42SJes Sorensen     print_option_parameters(param);
4383f88e1a42SJes Sorensen     puts("");
4384f88e1a42SJes Sorensen 
4385f88e1a42SJes Sorensen     ret = bdrv_create(drv, filename, param);
4386f88e1a42SJes Sorensen 
4387f88e1a42SJes Sorensen     if (ret < 0) {
4388f88e1a42SJes Sorensen         if (ret == -ENOTSUP) {
4389f88e1a42SJes Sorensen             error_report("Formatting or formatting option not supported for "
4390f88e1a42SJes Sorensen                          "file format '%s'", fmt);
4391f88e1a42SJes Sorensen         } else if (ret == -EFBIG) {
4392f88e1a42SJes Sorensen             error_report("The image size is too large for file format '%s'",
4393f88e1a42SJes Sorensen                          fmt);
4394f88e1a42SJes Sorensen         } else {
4395f88e1a42SJes Sorensen             error_report("%s: error while creating %s: %s", filename, fmt,
4396f88e1a42SJes Sorensen                          strerror(-ret));
4397f88e1a42SJes Sorensen         }
4398f88e1a42SJes Sorensen     }
4399f88e1a42SJes Sorensen 
4400f88e1a42SJes Sorensen out:
4401f88e1a42SJes Sorensen     free_option_parameters(create_options);
4402f88e1a42SJes Sorensen     free_option_parameters(param);
4403f88e1a42SJes Sorensen 
4404f88e1a42SJes Sorensen     if (bs) {
4405f88e1a42SJes Sorensen         bdrv_delete(bs);
4406f88e1a42SJes Sorensen     }
44074f70f249SJes Sorensen 
44084f70f249SJes Sorensen     return ret;
4409f88e1a42SJes Sorensen }
4410