xref: /openbmc/qemu/block.c (revision fa4478d5c8b74a5f0c8b93cc00590ec007be5016)
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"
295efa9d5aSAnthony Liguori #include "module.h"
30f795e743SLuiz Capitulino #include "qjson.h"
3168485420SKevin Wolf #include "qemu-coroutine.h"
32b2023818SLuiz Capitulino #include "qmp-commands.h"
330563e191SZhi Yong Wu #include "qemu-timer.h"
34fc01f7e7Sbellard 
3571e72a19SJuan Quintela #ifdef CONFIG_BSD
367674e7bfSbellard #include <sys/types.h>
377674e7bfSbellard #include <sys/stat.h>
387674e7bfSbellard #include <sys/ioctl.h>
3972cf2d4fSBlue Swirl #include <sys/queue.h>
40c5e97233Sblueswir1 #ifndef __DragonFly__
417674e7bfSbellard #include <sys/disk.h>
427674e7bfSbellard #endif
43c5e97233Sblueswir1 #endif
447674e7bfSbellard 
4549dc768dSaliguori #ifdef _WIN32
4649dc768dSaliguori #include <windows.h>
4749dc768dSaliguori #endif
4849dc768dSaliguori 
491c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
501c9805a3SStefan Hajnoczi 
51470c0504SStefan Hajnoczi typedef enum {
52470c0504SStefan Hajnoczi     BDRV_REQ_COPY_ON_READ = 0x1,
53f08f2ddaSStefan Hajnoczi     BDRV_REQ_ZERO_WRITE   = 0x2,
54470c0504SStefan Hajnoczi } BdrvRequestFlags;
55470c0504SStefan Hajnoczi 
567d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
57f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
58f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
59c87c0672Saliguori         BlockDriverCompletionFunc *cb, void *opaque);
60f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
61f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
62ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque);
63f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
64f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
65f9f05dc5SKevin Wolf                                          QEMUIOVector *iov);
66f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
67f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
68f9f05dc5SKevin Wolf                                          QEMUIOVector *iov);
69c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
70470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
71470c0504SStefan Hajnoczi     BdrvRequestFlags flags);
721c9805a3SStefan Hajnoczi static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
73f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
74f08f2ddaSStefan Hajnoczi     BdrvRequestFlags flags);
75b2a61371SStefan Hajnoczi static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
76b2a61371SStefan Hajnoczi                                                int64_t sector_num,
77b2a61371SStefan Hajnoczi                                                QEMUIOVector *qiov,
78b2a61371SStefan Hajnoczi                                                int nb_sectors,
79b2a61371SStefan Hajnoczi                                                BlockDriverCompletionFunc *cb,
80b2a61371SStefan Hajnoczi                                                void *opaque,
818c5873d6SStefan Hajnoczi                                                bool is_write);
82b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque);
83621f0589SKevin Wolf static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
84621f0589SKevin Wolf     int64_t sector_num, int nb_sectors);
85ec530c81Sbellard 
8698f90dbaSZhi Yong Wu static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
8798f90dbaSZhi Yong Wu         bool is_write, double elapsed_time, uint64_t *wait);
8898f90dbaSZhi Yong Wu static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
8998f90dbaSZhi Yong Wu         double elapsed_time, uint64_t *wait);
9098f90dbaSZhi Yong Wu static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
9198f90dbaSZhi Yong Wu         bool is_write, int64_t *wait);
9298f90dbaSZhi Yong Wu 
931b7bdbc1SStefan Hajnoczi static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
941b7bdbc1SStefan Hajnoczi     QTAILQ_HEAD_INITIALIZER(bdrv_states);
957ee930d0Sblueswir1 
968a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
978a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
98ea2384d3Sbellard 
99f9092b10SMarkus Armbruster /* The device to use for VM snapshots */
100f9092b10SMarkus Armbruster static BlockDriverState *bs_snapshots;
101f9092b10SMarkus Armbruster 
102eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
103eb852011SMarkus Armbruster static int use_bdrv_whitelist;
104eb852011SMarkus Armbruster 
1059e0b22f4SStefan Hajnoczi #ifdef _WIN32
1069e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
1079e0b22f4SStefan Hajnoczi {
1089e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
1099e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
1109e0b22f4SStefan Hajnoczi             filename[1] == ':');
1119e0b22f4SStefan Hajnoczi }
1129e0b22f4SStefan Hajnoczi 
1139e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
1149e0b22f4SStefan Hajnoczi {
1159e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
1169e0b22f4SStefan Hajnoczi         filename[2] == '\0')
1179e0b22f4SStefan Hajnoczi         return 1;
1189e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
1199e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
1209e0b22f4SStefan Hajnoczi         return 1;
1219e0b22f4SStefan Hajnoczi     return 0;
1229e0b22f4SStefan Hajnoczi }
1239e0b22f4SStefan Hajnoczi #endif
1249e0b22f4SStefan Hajnoczi 
1250563e191SZhi Yong Wu /* throttling disk I/O limits */
12698f90dbaSZhi Yong Wu void bdrv_io_limits_disable(BlockDriverState *bs)
12798f90dbaSZhi Yong Wu {
12898f90dbaSZhi Yong Wu     bs->io_limits_enabled = false;
12998f90dbaSZhi Yong Wu 
13098f90dbaSZhi Yong Wu     while (qemu_co_queue_next(&bs->throttled_reqs));
13198f90dbaSZhi Yong Wu 
13298f90dbaSZhi Yong Wu     if (bs->block_timer) {
13398f90dbaSZhi Yong Wu         qemu_del_timer(bs->block_timer);
13498f90dbaSZhi Yong Wu         qemu_free_timer(bs->block_timer);
13598f90dbaSZhi Yong Wu         bs->block_timer = NULL;
13698f90dbaSZhi Yong Wu     }
13798f90dbaSZhi Yong Wu 
13898f90dbaSZhi Yong Wu     bs->slice_start = 0;
13998f90dbaSZhi Yong Wu     bs->slice_end   = 0;
14098f90dbaSZhi Yong Wu     bs->slice_time  = 0;
14198f90dbaSZhi Yong Wu     memset(&bs->io_base, 0, sizeof(bs->io_base));
14298f90dbaSZhi Yong Wu }
14398f90dbaSZhi Yong Wu 
1440563e191SZhi Yong Wu static void bdrv_block_timer(void *opaque)
1450563e191SZhi Yong Wu {
1460563e191SZhi Yong Wu     BlockDriverState *bs = opaque;
1470563e191SZhi Yong Wu 
1480563e191SZhi Yong Wu     qemu_co_queue_next(&bs->throttled_reqs);
1490563e191SZhi Yong Wu }
1500563e191SZhi Yong Wu 
1510563e191SZhi Yong Wu void bdrv_io_limits_enable(BlockDriverState *bs)
1520563e191SZhi Yong Wu {
1530563e191SZhi Yong Wu     qemu_co_queue_init(&bs->throttled_reqs);
1540563e191SZhi Yong Wu     bs->block_timer = qemu_new_timer_ns(vm_clock, bdrv_block_timer, bs);
1550563e191SZhi Yong Wu     bs->slice_time  = 5 * BLOCK_IO_SLICE_TIME;
1560563e191SZhi Yong Wu     bs->slice_start = qemu_get_clock_ns(vm_clock);
1570563e191SZhi Yong Wu     bs->slice_end   = bs->slice_start + bs->slice_time;
1580563e191SZhi Yong Wu     memset(&bs->io_base, 0, sizeof(bs->io_base));
1590563e191SZhi Yong Wu     bs->io_limits_enabled = true;
1600563e191SZhi Yong Wu }
1610563e191SZhi Yong Wu 
1620563e191SZhi Yong Wu bool bdrv_io_limits_enabled(BlockDriverState *bs)
1630563e191SZhi Yong Wu {
1640563e191SZhi Yong Wu     BlockIOLimit *io_limits = &bs->io_limits;
1650563e191SZhi Yong Wu     return io_limits->bps[BLOCK_IO_LIMIT_READ]
1660563e191SZhi Yong Wu          || io_limits->bps[BLOCK_IO_LIMIT_WRITE]
1670563e191SZhi Yong Wu          || io_limits->bps[BLOCK_IO_LIMIT_TOTAL]
1680563e191SZhi Yong Wu          || io_limits->iops[BLOCK_IO_LIMIT_READ]
1690563e191SZhi Yong Wu          || io_limits->iops[BLOCK_IO_LIMIT_WRITE]
1700563e191SZhi Yong Wu          || io_limits->iops[BLOCK_IO_LIMIT_TOTAL];
1710563e191SZhi Yong Wu }
1720563e191SZhi Yong Wu 
17398f90dbaSZhi Yong Wu static void bdrv_io_limits_intercept(BlockDriverState *bs,
17498f90dbaSZhi Yong Wu                                      bool is_write, int nb_sectors)
17598f90dbaSZhi Yong Wu {
17698f90dbaSZhi Yong Wu     int64_t wait_time = -1;
17798f90dbaSZhi Yong Wu 
17898f90dbaSZhi Yong Wu     if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
17998f90dbaSZhi Yong Wu         qemu_co_queue_wait(&bs->throttled_reqs);
18098f90dbaSZhi Yong Wu     }
18198f90dbaSZhi Yong Wu 
18298f90dbaSZhi Yong Wu     /* In fact, we hope to keep each request's timing, in FIFO mode. The next
18398f90dbaSZhi Yong Wu      * throttled requests will not be dequeued until the current request is
18498f90dbaSZhi Yong Wu      * allowed to be serviced. So if the current request still exceeds the
18598f90dbaSZhi Yong Wu      * limits, it will be inserted to the head. All requests followed it will
18698f90dbaSZhi Yong Wu      * be still in throttled_reqs queue.
18798f90dbaSZhi Yong Wu      */
18898f90dbaSZhi Yong Wu 
18998f90dbaSZhi Yong Wu     while (bdrv_exceed_io_limits(bs, nb_sectors, is_write, &wait_time)) {
19098f90dbaSZhi Yong Wu         qemu_mod_timer(bs->block_timer,
19198f90dbaSZhi Yong Wu                        wait_time + qemu_get_clock_ns(vm_clock));
19298f90dbaSZhi Yong Wu         qemu_co_queue_wait_insert_head(&bs->throttled_reqs);
19398f90dbaSZhi Yong Wu     }
19498f90dbaSZhi Yong Wu 
19598f90dbaSZhi Yong Wu     qemu_co_queue_next(&bs->throttled_reqs);
19698f90dbaSZhi Yong Wu }
19798f90dbaSZhi Yong Wu 
1989e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
1999e0b22f4SStefan Hajnoczi static int path_has_protocol(const char *path)
2009e0b22f4SStefan Hajnoczi {
2019e0b22f4SStefan Hajnoczi #ifdef _WIN32
2029e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
2039e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
2049e0b22f4SStefan Hajnoczi         return 0;
2059e0b22f4SStefan Hajnoczi     }
2069e0b22f4SStefan Hajnoczi #endif
2079e0b22f4SStefan Hajnoczi 
2089e0b22f4SStefan Hajnoczi     return strchr(path, ':') != NULL;
2099e0b22f4SStefan Hajnoczi }
2109e0b22f4SStefan Hajnoczi 
21183f64091Sbellard int path_is_absolute(const char *path)
21283f64091Sbellard {
21383f64091Sbellard     const char *p;
21421664424Sbellard #ifdef _WIN32
21521664424Sbellard     /* specific case for names like: "\\.\d:" */
21621664424Sbellard     if (*path == '/' || *path == '\\')
21721664424Sbellard         return 1;
21821664424Sbellard #endif
21983f64091Sbellard     p = strchr(path, ':');
22083f64091Sbellard     if (p)
22183f64091Sbellard         p++;
22283f64091Sbellard     else
22383f64091Sbellard         p = path;
2243b9f94e1Sbellard #ifdef _WIN32
2253b9f94e1Sbellard     return (*p == '/' || *p == '\\');
2263b9f94e1Sbellard #else
2273b9f94e1Sbellard     return (*p == '/');
2283b9f94e1Sbellard #endif
22983f64091Sbellard }
23083f64091Sbellard 
23183f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
23283f64091Sbellard    path to it by considering it is relative to base_path. URL are
23383f64091Sbellard    supported. */
23483f64091Sbellard void path_combine(char *dest, int dest_size,
23583f64091Sbellard                   const char *base_path,
23683f64091Sbellard                   const char *filename)
23783f64091Sbellard {
23883f64091Sbellard     const char *p, *p1;
23983f64091Sbellard     int len;
24083f64091Sbellard 
24183f64091Sbellard     if (dest_size <= 0)
24283f64091Sbellard         return;
24383f64091Sbellard     if (path_is_absolute(filename)) {
24483f64091Sbellard         pstrcpy(dest, dest_size, filename);
24583f64091Sbellard     } else {
24683f64091Sbellard         p = strchr(base_path, ':');
24783f64091Sbellard         if (p)
24883f64091Sbellard             p++;
24983f64091Sbellard         else
25083f64091Sbellard             p = base_path;
2513b9f94e1Sbellard         p1 = strrchr(base_path, '/');
2523b9f94e1Sbellard #ifdef _WIN32
2533b9f94e1Sbellard         {
2543b9f94e1Sbellard             const char *p2;
2553b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
2563b9f94e1Sbellard             if (!p1 || p2 > p1)
2573b9f94e1Sbellard                 p1 = p2;
2583b9f94e1Sbellard         }
2593b9f94e1Sbellard #endif
26083f64091Sbellard         if (p1)
26183f64091Sbellard             p1++;
26283f64091Sbellard         else
26383f64091Sbellard             p1 = base_path;
26483f64091Sbellard         if (p1 > p)
26583f64091Sbellard             p = p1;
26683f64091Sbellard         len = p - base_path;
26783f64091Sbellard         if (len > dest_size - 1)
26883f64091Sbellard             len = dest_size - 1;
26983f64091Sbellard         memcpy(dest, base_path, len);
27083f64091Sbellard         dest[len] = '\0';
27183f64091Sbellard         pstrcat(dest, dest_size, filename);
27283f64091Sbellard     }
27383f64091Sbellard }
27483f64091Sbellard 
2755efa9d5aSAnthony Liguori void bdrv_register(BlockDriver *bdrv)
276ea2384d3Sbellard {
2778c5873d6SStefan Hajnoczi     /* Block drivers without coroutine functions need emulation */
2788c5873d6SStefan Hajnoczi     if (!bdrv->bdrv_co_readv) {
279f9f05dc5SKevin Wolf         bdrv->bdrv_co_readv = bdrv_co_readv_em;
280f9f05dc5SKevin Wolf         bdrv->bdrv_co_writev = bdrv_co_writev_em;
281f9f05dc5SKevin Wolf 
282f8c35c1dSStefan Hajnoczi         /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
283f8c35c1dSStefan Hajnoczi          * the block driver lacks aio we need to emulate that too.
284f8c35c1dSStefan Hajnoczi          */
285f9f05dc5SKevin Wolf         if (!bdrv->bdrv_aio_readv) {
28683f64091Sbellard             /* add AIO emulation layer */
287f141eafeSaliguori             bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
288f141eafeSaliguori             bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
28983f64091Sbellard         }
290f9f05dc5SKevin Wolf     }
291b2e12bc6SChristoph Hellwig 
2928a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
293ea2384d3Sbellard }
294b338082bSbellard 
295b338082bSbellard /* create a new block device (by default it is empty) */
296b338082bSbellard BlockDriverState *bdrv_new(const char *device_name)
297fc01f7e7Sbellard {
2981b7bdbc1SStefan Hajnoczi     BlockDriverState *bs;
299b338082bSbellard 
3007267c094SAnthony Liguori     bs = g_malloc0(sizeof(BlockDriverState));
301b338082bSbellard     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
302ea2384d3Sbellard     if (device_name[0] != '\0') {
3031b7bdbc1SStefan Hajnoczi         QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
304ea2384d3Sbellard     }
30528a7282aSLuiz Capitulino     bdrv_iostatus_disable(bs);
306b338082bSbellard     return bs;
307b338082bSbellard }
308b338082bSbellard 
309ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
310ea2384d3Sbellard {
311ea2384d3Sbellard     BlockDriver *drv1;
3128a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
3138a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
314ea2384d3Sbellard             return drv1;
315ea2384d3Sbellard         }
3168a22f02aSStefan Hajnoczi     }
317ea2384d3Sbellard     return NULL;
318ea2384d3Sbellard }
319ea2384d3Sbellard 
320eb852011SMarkus Armbruster static int bdrv_is_whitelisted(BlockDriver *drv)
321eb852011SMarkus Armbruster {
322eb852011SMarkus Armbruster     static const char *whitelist[] = {
323eb852011SMarkus Armbruster         CONFIG_BDRV_WHITELIST
324eb852011SMarkus Armbruster     };
325eb852011SMarkus Armbruster     const char **p;
326eb852011SMarkus Armbruster 
327eb852011SMarkus Armbruster     if (!whitelist[0])
328eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
329eb852011SMarkus Armbruster 
330eb852011SMarkus Armbruster     for (p = whitelist; *p; p++) {
331eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
332eb852011SMarkus Armbruster             return 1;
333eb852011SMarkus Armbruster         }
334eb852011SMarkus Armbruster     }
335eb852011SMarkus Armbruster     return 0;
336eb852011SMarkus Armbruster }
337eb852011SMarkus Armbruster 
338eb852011SMarkus Armbruster BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
339eb852011SMarkus Armbruster {
340eb852011SMarkus Armbruster     BlockDriver *drv = bdrv_find_format(format_name);
341eb852011SMarkus Armbruster     return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
342eb852011SMarkus Armbruster }
343eb852011SMarkus Armbruster 
3445b7e1542SZhi Yong Wu typedef struct CreateCo {
3455b7e1542SZhi Yong Wu     BlockDriver *drv;
3465b7e1542SZhi Yong Wu     char *filename;
3475b7e1542SZhi Yong Wu     QEMUOptionParameter *options;
3485b7e1542SZhi Yong Wu     int ret;
3495b7e1542SZhi Yong Wu } CreateCo;
3505b7e1542SZhi Yong Wu 
3515b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
3525b7e1542SZhi Yong Wu {
3535b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
3545b7e1542SZhi Yong Wu     assert(cco->drv);
3555b7e1542SZhi Yong Wu 
3565b7e1542SZhi Yong Wu     cco->ret = cco->drv->bdrv_create(cco->filename, cco->options);
3575b7e1542SZhi Yong Wu }
3585b7e1542SZhi Yong Wu 
3590e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
3600e7e1989SKevin Wolf     QEMUOptionParameter *options)
361ea2384d3Sbellard {
3625b7e1542SZhi Yong Wu     int ret;
3630e7e1989SKevin Wolf 
3645b7e1542SZhi Yong Wu     Coroutine *co;
3655b7e1542SZhi Yong Wu     CreateCo cco = {
3665b7e1542SZhi Yong Wu         .drv = drv,
3675b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
3685b7e1542SZhi Yong Wu         .options = options,
3695b7e1542SZhi Yong Wu         .ret = NOT_DONE,
3705b7e1542SZhi Yong Wu     };
3715b7e1542SZhi Yong Wu 
3725b7e1542SZhi Yong Wu     if (!drv->bdrv_create) {
3735b7e1542SZhi Yong Wu         return -ENOTSUP;
3745b7e1542SZhi Yong Wu     }
3755b7e1542SZhi Yong Wu 
3765b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
3775b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
3785b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
3795b7e1542SZhi Yong Wu     } else {
3805b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
3815b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
3825b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
3835b7e1542SZhi Yong Wu             qemu_aio_wait();
3845b7e1542SZhi Yong Wu         }
3855b7e1542SZhi Yong Wu     }
3865b7e1542SZhi Yong Wu 
3875b7e1542SZhi Yong Wu     ret = cco.ret;
3885b7e1542SZhi Yong Wu     g_free(cco.filename);
3895b7e1542SZhi Yong Wu 
3905b7e1542SZhi Yong Wu     return ret;
391ea2384d3Sbellard }
392ea2384d3Sbellard 
39384a12e66SChristoph Hellwig int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
39484a12e66SChristoph Hellwig {
39584a12e66SChristoph Hellwig     BlockDriver *drv;
39684a12e66SChristoph Hellwig 
397b50cbabcSMORITA Kazutaka     drv = bdrv_find_protocol(filename);
39884a12e66SChristoph Hellwig     if (drv == NULL) {
39916905d71SStefan Hajnoczi         return -ENOENT;
40084a12e66SChristoph Hellwig     }
40184a12e66SChristoph Hellwig 
40284a12e66SChristoph Hellwig     return bdrv_create(drv, filename, options);
40384a12e66SChristoph Hellwig }
40484a12e66SChristoph Hellwig 
405d5249393Sbellard #ifdef _WIN32
40695389c86Sbellard void get_tmp_filename(char *filename, int size)
407d5249393Sbellard {
4083b9f94e1Sbellard     char temp_dir[MAX_PATH];
4093b9f94e1Sbellard 
4103b9f94e1Sbellard     GetTempPath(MAX_PATH, temp_dir);
4113b9f94e1Sbellard     GetTempFileName(temp_dir, "qem", 0, filename);
412d5249393Sbellard }
413d5249393Sbellard #else
41495389c86Sbellard void get_tmp_filename(char *filename, int size)
415ea2384d3Sbellard {
416ea2384d3Sbellard     int fd;
4177ccfb2ebSblueswir1     const char *tmpdir;
418d5249393Sbellard     /* XXX: race condition possible */
4190badc1eeSaurel32     tmpdir = getenv("TMPDIR");
4200badc1eeSaurel32     if (!tmpdir)
4210badc1eeSaurel32         tmpdir = "/tmp";
4220badc1eeSaurel32     snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
423ea2384d3Sbellard     fd = mkstemp(filename);
424ea2384d3Sbellard     close(fd);
425ea2384d3Sbellard }
426d5249393Sbellard #endif
427ea2384d3Sbellard 
428f3a5d3f8SChristoph Hellwig /*
429f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
430f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
431f3a5d3f8SChristoph Hellwig  */
432f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
433f3a5d3f8SChristoph Hellwig {
434508c7cb3SChristoph Hellwig     int score_max = 0, score;
435508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
436f3a5d3f8SChristoph Hellwig 
4378a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
438508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
439508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
440508c7cb3SChristoph Hellwig             if (score > score_max) {
441508c7cb3SChristoph Hellwig                 score_max = score;
442508c7cb3SChristoph Hellwig                 drv = d;
443f3a5d3f8SChristoph Hellwig             }
444508c7cb3SChristoph Hellwig         }
445f3a5d3f8SChristoph Hellwig     }
446f3a5d3f8SChristoph Hellwig 
447508c7cb3SChristoph Hellwig     return drv;
448f3a5d3f8SChristoph Hellwig }
449f3a5d3f8SChristoph Hellwig 
450b50cbabcSMORITA Kazutaka BlockDriver *bdrv_find_protocol(const char *filename)
45184a12e66SChristoph Hellwig {
45284a12e66SChristoph Hellwig     BlockDriver *drv1;
45384a12e66SChristoph Hellwig     char protocol[128];
45484a12e66SChristoph Hellwig     int len;
45584a12e66SChristoph Hellwig     const char *p;
45684a12e66SChristoph Hellwig 
45766f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
45866f82ceeSKevin Wolf 
45939508e7aSChristoph Hellwig     /*
46039508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
46139508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
46239508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
46339508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
46439508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
46539508e7aSChristoph Hellwig      */
46684a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
46739508e7aSChristoph Hellwig     if (drv1) {
46884a12e66SChristoph Hellwig         return drv1;
46984a12e66SChristoph Hellwig     }
47039508e7aSChristoph Hellwig 
4719e0b22f4SStefan Hajnoczi     if (!path_has_protocol(filename)) {
47239508e7aSChristoph Hellwig         return bdrv_find_format("file");
47339508e7aSChristoph Hellwig     }
4749e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
4759e0b22f4SStefan Hajnoczi     assert(p != NULL);
47684a12e66SChristoph Hellwig     len = p - filename;
47784a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
47884a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
47984a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
48084a12e66SChristoph Hellwig     protocol[len] = '\0';
48184a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
48284a12e66SChristoph Hellwig         if (drv1->protocol_name &&
48384a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
48484a12e66SChristoph Hellwig             return drv1;
48584a12e66SChristoph Hellwig         }
48684a12e66SChristoph Hellwig     }
48784a12e66SChristoph Hellwig     return NULL;
48884a12e66SChristoph Hellwig }
48984a12e66SChristoph Hellwig 
490c98ac35dSStefan Weil static int find_image_format(const char *filename, BlockDriver **pdrv)
491ea2384d3Sbellard {
49283f64091Sbellard     int ret, score, score_max;
493ea2384d3Sbellard     BlockDriver *drv1, *drv;
49483f64091Sbellard     uint8_t buf[2048];
49583f64091Sbellard     BlockDriverState *bs;
496ea2384d3Sbellard 
497f5edb014SNaphtali Sprei     ret = bdrv_file_open(&bs, filename, 0);
498c98ac35dSStefan Weil     if (ret < 0) {
499c98ac35dSStefan Weil         *pdrv = NULL;
500c98ac35dSStefan Weil         return ret;
501c98ac35dSStefan Weil     }
502f8ea0b00SNicholas Bellinger 
50308a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
50408a00559SKevin Wolf     if (bs->sg || !bdrv_is_inserted(bs)) {
5051a396859SNicholas A. Bellinger         bdrv_delete(bs);
506c98ac35dSStefan Weil         drv = bdrv_find_format("raw");
507c98ac35dSStefan Weil         if (!drv) {
508c98ac35dSStefan Weil             ret = -ENOENT;
509c98ac35dSStefan Weil         }
510c98ac35dSStefan Weil         *pdrv = drv;
511c98ac35dSStefan Weil         return ret;
5121a396859SNicholas A. Bellinger     }
513f8ea0b00SNicholas Bellinger 
51483f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
51583f64091Sbellard     bdrv_delete(bs);
516ea2384d3Sbellard     if (ret < 0) {
517c98ac35dSStefan Weil         *pdrv = NULL;
518c98ac35dSStefan Weil         return ret;
519ea2384d3Sbellard     }
520ea2384d3Sbellard 
521ea2384d3Sbellard     score_max = 0;
52284a12e66SChristoph Hellwig     drv = NULL;
5238a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
52483f64091Sbellard         if (drv1->bdrv_probe) {
525ea2384d3Sbellard             score = drv1->bdrv_probe(buf, ret, filename);
526ea2384d3Sbellard             if (score > score_max) {
527ea2384d3Sbellard                 score_max = score;
528ea2384d3Sbellard                 drv = drv1;
529ea2384d3Sbellard             }
530ea2384d3Sbellard         }
53183f64091Sbellard     }
532c98ac35dSStefan Weil     if (!drv) {
533c98ac35dSStefan Weil         ret = -ENOENT;
534c98ac35dSStefan Weil     }
535c98ac35dSStefan Weil     *pdrv = drv;
536c98ac35dSStefan Weil     return ret;
537ea2384d3Sbellard }
538ea2384d3Sbellard 
53951762288SStefan Hajnoczi /**
54051762288SStefan Hajnoczi  * Set the current 'total_sectors' value
54151762288SStefan Hajnoczi  */
54251762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
54351762288SStefan Hajnoczi {
54451762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
54551762288SStefan Hajnoczi 
546396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
547396759adSNicholas Bellinger     if (bs->sg)
548396759adSNicholas Bellinger         return 0;
549396759adSNicholas Bellinger 
55051762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
55151762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
55251762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
55351762288SStefan Hajnoczi         if (length < 0) {
55451762288SStefan Hajnoczi             return length;
55551762288SStefan Hajnoczi         }
55651762288SStefan Hajnoczi         hint = length >> BDRV_SECTOR_BITS;
55751762288SStefan Hajnoczi     }
55851762288SStefan Hajnoczi 
55951762288SStefan Hajnoczi     bs->total_sectors = hint;
56051762288SStefan Hajnoczi     return 0;
56151762288SStefan Hajnoczi }
56251762288SStefan Hajnoczi 
563c3993cdcSStefan Hajnoczi /**
564c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
565c3993cdcSStefan Hajnoczi  *
566c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
567c3993cdcSStefan Hajnoczi  */
568c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
569c3993cdcSStefan Hajnoczi {
570c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
571c3993cdcSStefan Hajnoczi 
572c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
573c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
57492196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
57592196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
576c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
577c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
578c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
579c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
580c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
581c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
582c3993cdcSStefan Hajnoczi         /* this is the default */
583c3993cdcSStefan Hajnoczi     } else {
584c3993cdcSStefan Hajnoczi         return -1;
585c3993cdcSStefan Hajnoczi     }
586c3993cdcSStefan Hajnoczi 
587c3993cdcSStefan Hajnoczi     return 0;
588c3993cdcSStefan Hajnoczi }
589c3993cdcSStefan Hajnoczi 
59053fec9d3SStefan Hajnoczi /**
59153fec9d3SStefan Hajnoczi  * The copy-on-read flag is actually a reference count so multiple users may
59253fec9d3SStefan Hajnoczi  * use the feature without worrying about clobbering its previous state.
59353fec9d3SStefan Hajnoczi  * Copy-on-read stays enabled until all users have called to disable it.
59453fec9d3SStefan Hajnoczi  */
59553fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs)
59653fec9d3SStefan Hajnoczi {
59753fec9d3SStefan Hajnoczi     bs->copy_on_read++;
59853fec9d3SStefan Hajnoczi }
59953fec9d3SStefan Hajnoczi 
60053fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs)
60153fec9d3SStefan Hajnoczi {
60253fec9d3SStefan Hajnoczi     assert(bs->copy_on_read > 0);
60353fec9d3SStefan Hajnoczi     bs->copy_on_read--;
60453fec9d3SStefan Hajnoczi }
60553fec9d3SStefan Hajnoczi 
606b6ce07aaSKevin Wolf /*
60757915332SKevin Wolf  * Common part for opening disk images and files
60857915332SKevin Wolf  */
60957915332SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, const char *filename,
61057915332SKevin Wolf     int flags, BlockDriver *drv)
61157915332SKevin Wolf {
61257915332SKevin Wolf     int ret, open_flags;
61357915332SKevin Wolf 
61457915332SKevin Wolf     assert(drv != NULL);
61557915332SKevin Wolf 
61628dcee10SStefan Hajnoczi     trace_bdrv_open_common(bs, filename, flags, drv->format_name);
61728dcee10SStefan Hajnoczi 
61866f82ceeSKevin Wolf     bs->file = NULL;
61951762288SStefan Hajnoczi     bs->total_sectors = 0;
62057915332SKevin Wolf     bs->encrypted = 0;
62157915332SKevin Wolf     bs->valid_key = 0;
62203f541bdSStefan Hajnoczi     bs->sg = 0;
62357915332SKevin Wolf     bs->open_flags = flags;
62403f541bdSStefan Hajnoczi     bs->growable = 0;
62557915332SKevin Wolf     bs->buffer_alignment = 512;
62657915332SKevin Wolf 
62753fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
62853fec9d3SStefan Hajnoczi     if ((flags & BDRV_O_RDWR) && (flags & BDRV_O_COPY_ON_READ)) {
62953fec9d3SStefan Hajnoczi         bdrv_enable_copy_on_read(bs);
63053fec9d3SStefan Hajnoczi     }
63153fec9d3SStefan Hajnoczi 
63257915332SKevin Wolf     pstrcpy(bs->filename, sizeof(bs->filename), filename);
63303f541bdSStefan Hajnoczi     bs->backing_file[0] = '\0';
63457915332SKevin Wolf 
63557915332SKevin Wolf     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
63657915332SKevin Wolf         return -ENOTSUP;
63757915332SKevin Wolf     }
63857915332SKevin Wolf 
63957915332SKevin Wolf     bs->drv = drv;
6407267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
64157915332SKevin Wolf 
64203f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
64357915332SKevin Wolf 
64457915332SKevin Wolf     /*
64557915332SKevin Wolf      * Clear flags that are internal to the block layer before opening the
64657915332SKevin Wolf      * image.
64757915332SKevin Wolf      */
64857915332SKevin Wolf     open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
64957915332SKevin Wolf 
65057915332SKevin Wolf     /*
651ebabb67aSStefan Weil      * Snapshots should be writable.
65257915332SKevin Wolf      */
65357915332SKevin Wolf     if (bs->is_temporary) {
65457915332SKevin Wolf         open_flags |= BDRV_O_RDWR;
65557915332SKevin Wolf     }
65657915332SKevin Wolf 
657e7c63796SStefan Hajnoczi     bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
658e7c63796SStefan Hajnoczi 
65966f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
66066f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
66166f82ceeSKevin Wolf         ret = drv->bdrv_file_open(bs, filename, open_flags);
66266f82ceeSKevin Wolf     } else {
66366f82ceeSKevin Wolf         ret = bdrv_file_open(&bs->file, filename, open_flags);
66466f82ceeSKevin Wolf         if (ret >= 0) {
66566f82ceeSKevin Wolf             ret = drv->bdrv_open(bs, open_flags);
66666f82ceeSKevin Wolf         }
66766f82ceeSKevin Wolf     }
66866f82ceeSKevin Wolf 
66957915332SKevin Wolf     if (ret < 0) {
67057915332SKevin Wolf         goto free_and_fail;
67157915332SKevin Wolf     }
67257915332SKevin Wolf 
67351762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
67451762288SStefan Hajnoczi     if (ret < 0) {
67551762288SStefan Hajnoczi         goto free_and_fail;
67657915332SKevin Wolf     }
67751762288SStefan Hajnoczi 
67857915332SKevin Wolf #ifndef _WIN32
67957915332SKevin Wolf     if (bs->is_temporary) {
68057915332SKevin Wolf         unlink(filename);
68157915332SKevin Wolf     }
68257915332SKevin Wolf #endif
68357915332SKevin Wolf     return 0;
68457915332SKevin Wolf 
68557915332SKevin Wolf free_and_fail:
68666f82ceeSKevin Wolf     if (bs->file) {
68766f82ceeSKevin Wolf         bdrv_delete(bs->file);
68866f82ceeSKevin Wolf         bs->file = NULL;
68966f82ceeSKevin Wolf     }
6907267c094SAnthony Liguori     g_free(bs->opaque);
69157915332SKevin Wolf     bs->opaque = NULL;
69257915332SKevin Wolf     bs->drv = NULL;
69357915332SKevin Wolf     return ret;
69457915332SKevin Wolf }
69557915332SKevin Wolf 
69657915332SKevin Wolf /*
697b6ce07aaSKevin Wolf  * Opens a file using a protocol (file, host_device, nbd, ...)
698b6ce07aaSKevin Wolf  */
69983f64091Sbellard int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
700b338082bSbellard {
70183f64091Sbellard     BlockDriverState *bs;
7026db95603SChristoph Hellwig     BlockDriver *drv;
70383f64091Sbellard     int ret;
7043b0d4f61Sbellard 
705b50cbabcSMORITA Kazutaka     drv = bdrv_find_protocol(filename);
7066db95603SChristoph Hellwig     if (!drv) {
7076db95603SChristoph Hellwig         return -ENOENT;
7086db95603SChristoph Hellwig     }
7096db95603SChristoph Hellwig 
71083f64091Sbellard     bs = bdrv_new("");
711b6ce07aaSKevin Wolf     ret = bdrv_open_common(bs, filename, flags, drv);
71283f64091Sbellard     if (ret < 0) {
71383f64091Sbellard         bdrv_delete(bs);
71483f64091Sbellard         return ret;
7153b0d4f61Sbellard     }
71671d0770cSaliguori     bs->growable = 1;
71783f64091Sbellard     *pbs = bs;
71883f64091Sbellard     return 0;
7193b0d4f61Sbellard }
7203b0d4f61Sbellard 
721b6ce07aaSKevin Wolf /*
722b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
723b6ce07aaSKevin Wolf  */
724d6e9098eSKevin Wolf int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
725ea2384d3Sbellard               BlockDriver *drv)
726ea2384d3Sbellard {
727b6ce07aaSKevin Wolf     int ret;
7282b572816SKevin Wolf     char tmp_filename[PATH_MAX];
72933e3963eSbellard 
73083f64091Sbellard     if (flags & BDRV_O_SNAPSHOT) {
731ea2384d3Sbellard         BlockDriverState *bs1;
732ea2384d3Sbellard         int64_t total_size;
7337c96d46eSaliguori         int is_protocol = 0;
73491a073a9SKevin Wolf         BlockDriver *bdrv_qcow2;
73591a073a9SKevin Wolf         QEMUOptionParameter *options;
736b6ce07aaSKevin Wolf         char backing_filename[PATH_MAX];
73733e3963eSbellard 
738ea2384d3Sbellard         /* if snapshot, we create a temporary backing file and open it
739ea2384d3Sbellard            instead of opening 'filename' directly */
740ea2384d3Sbellard 
741ea2384d3Sbellard         /* if there is a backing file, use it */
742ea2384d3Sbellard         bs1 = bdrv_new("");
743d6e9098eSKevin Wolf         ret = bdrv_open(bs1, filename, 0, drv);
74451d7c00cSaliguori         if (ret < 0) {
745ea2384d3Sbellard             bdrv_delete(bs1);
74651d7c00cSaliguori             return ret;
747ea2384d3Sbellard         }
7483e82990bSJes Sorensen         total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
7497c96d46eSaliguori 
7507c96d46eSaliguori         if (bs1->drv && bs1->drv->protocol_name)
7517c96d46eSaliguori             is_protocol = 1;
7527c96d46eSaliguori 
753ea2384d3Sbellard         bdrv_delete(bs1);
754ea2384d3Sbellard 
755ea2384d3Sbellard         get_tmp_filename(tmp_filename, sizeof(tmp_filename));
7567c96d46eSaliguori 
7577c96d46eSaliguori         /* Real path is meaningless for protocols */
7587c96d46eSaliguori         if (is_protocol)
7597c96d46eSaliguori             snprintf(backing_filename, sizeof(backing_filename),
7607c96d46eSaliguori                      "%s", filename);
761114cdfa9SKirill A. Shutemov         else if (!realpath(filename, backing_filename))
762114cdfa9SKirill A. Shutemov             return -errno;
7637c96d46eSaliguori 
76491a073a9SKevin Wolf         bdrv_qcow2 = bdrv_find_format("qcow2");
76591a073a9SKevin Wolf         options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
76691a073a9SKevin Wolf 
7673e82990bSJes Sorensen         set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
76891a073a9SKevin Wolf         set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
76991a073a9SKevin Wolf         if (drv) {
77091a073a9SKevin Wolf             set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
77191a073a9SKevin Wolf                 drv->format_name);
77291a073a9SKevin Wolf         }
77391a073a9SKevin Wolf 
77491a073a9SKevin Wolf         ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
775d748768cSJan Kiszka         free_option_parameters(options);
77651d7c00cSaliguori         if (ret < 0) {
77751d7c00cSaliguori             return ret;
778ea2384d3Sbellard         }
77991a073a9SKevin Wolf 
780ea2384d3Sbellard         filename = tmp_filename;
78191a073a9SKevin Wolf         drv = bdrv_qcow2;
782ea2384d3Sbellard         bs->is_temporary = 1;
783ea2384d3Sbellard     }
784ea2384d3Sbellard 
785b6ce07aaSKevin Wolf     /* Find the right image format driver */
7866db95603SChristoph Hellwig     if (!drv) {
787c98ac35dSStefan Weil         ret = find_image_format(filename, &drv);
788ea2384d3Sbellard     }
7896987307cSChristoph Hellwig 
79051d7c00cSaliguori     if (!drv) {
79151d7c00cSaliguori         goto unlink_and_fail;
79283f64091Sbellard     }
793b6ce07aaSKevin Wolf 
794b6ce07aaSKevin Wolf     /* Open the image */
795b6ce07aaSKevin Wolf     ret = bdrv_open_common(bs, filename, flags, drv);
796b6ce07aaSKevin Wolf     if (ret < 0) {
7976987307cSChristoph Hellwig         goto unlink_and_fail;
7986987307cSChristoph Hellwig     }
7996987307cSChristoph Hellwig 
800b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
801b6ce07aaSKevin Wolf     if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
802b6ce07aaSKevin Wolf         char backing_filename[PATH_MAX];
803b6ce07aaSKevin Wolf         int back_flags;
804b6ce07aaSKevin Wolf         BlockDriver *back_drv = NULL;
805b6ce07aaSKevin Wolf 
806b6ce07aaSKevin Wolf         bs->backing_hd = bdrv_new("");
807df2dbb4aSStefan Hajnoczi 
808df2dbb4aSStefan Hajnoczi         if (path_has_protocol(bs->backing_file)) {
809df2dbb4aSStefan Hajnoczi             pstrcpy(backing_filename, sizeof(backing_filename),
810df2dbb4aSStefan Hajnoczi                     bs->backing_file);
811df2dbb4aSStefan Hajnoczi         } else {
812b6ce07aaSKevin Wolf             path_combine(backing_filename, sizeof(backing_filename),
813b6ce07aaSKevin Wolf                          filename, bs->backing_file);
814df2dbb4aSStefan Hajnoczi         }
815df2dbb4aSStefan Hajnoczi 
816df2dbb4aSStefan Hajnoczi         if (bs->backing_format[0] != '\0') {
817b6ce07aaSKevin Wolf             back_drv = bdrv_find_format(bs->backing_format);
818df2dbb4aSStefan Hajnoczi         }
819b6ce07aaSKevin Wolf 
820b6ce07aaSKevin Wolf         /* backing files always opened read-only */
821b6ce07aaSKevin Wolf         back_flags =
822b6ce07aaSKevin Wolf             flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
823b6ce07aaSKevin Wolf 
824b6ce07aaSKevin Wolf         ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
825b6ce07aaSKevin Wolf         if (ret < 0) {
826b6ce07aaSKevin Wolf             bdrv_close(bs);
827b6ce07aaSKevin Wolf             return ret;
828b6ce07aaSKevin Wolf         }
829b6ce07aaSKevin Wolf         if (bs->is_temporary) {
830b6ce07aaSKevin Wolf             bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
831b6ce07aaSKevin Wolf         } else {
832b6ce07aaSKevin Wolf             /* base image inherits from "parent" */
833b6ce07aaSKevin Wolf             bs->backing_hd->keep_read_only = bs->keep_read_only;
834b6ce07aaSKevin Wolf         }
835b6ce07aaSKevin Wolf     }
836b6ce07aaSKevin Wolf 
837b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
8387d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
839b6ce07aaSKevin Wolf     }
840b6ce07aaSKevin Wolf 
84198f90dbaSZhi Yong Wu     /* throttling disk I/O limits */
84298f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
84398f90dbaSZhi Yong Wu         bdrv_io_limits_enable(bs);
84498f90dbaSZhi Yong Wu     }
84598f90dbaSZhi Yong Wu 
846b6ce07aaSKevin Wolf     return 0;
847b6ce07aaSKevin Wolf 
848b6ce07aaSKevin Wolf unlink_and_fail:
849b6ce07aaSKevin Wolf     if (bs->is_temporary) {
850b6ce07aaSKevin Wolf         unlink(filename);
851b6ce07aaSKevin Wolf     }
852b6ce07aaSKevin Wolf     return ret;
853b6ce07aaSKevin Wolf }
854b6ce07aaSKevin Wolf 
855fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
856fc01f7e7Sbellard {
85780ccf93bSLiu Yuan     bdrv_flush(bs);
85819cb3738Sbellard     if (bs->drv) {
8593e914655SPaolo Bonzini         if (bs->job) {
8603e914655SPaolo Bonzini             block_job_cancel_sync(bs->job);
8613e914655SPaolo Bonzini         }
8627094f12fSKevin Wolf         bdrv_drain_all();
8637094f12fSKevin Wolf 
864f9092b10SMarkus Armbruster         if (bs == bs_snapshots) {
865f9092b10SMarkus Armbruster             bs_snapshots = NULL;
866f9092b10SMarkus Armbruster         }
867557df6acSStefan Hajnoczi         if (bs->backing_hd) {
868ea2384d3Sbellard             bdrv_delete(bs->backing_hd);
869557df6acSStefan Hajnoczi             bs->backing_hd = NULL;
870557df6acSStefan Hajnoczi         }
871ea2384d3Sbellard         bs->drv->bdrv_close(bs);
8727267c094SAnthony Liguori         g_free(bs->opaque);
873ea2384d3Sbellard #ifdef _WIN32
874ea2384d3Sbellard         if (bs->is_temporary) {
875ea2384d3Sbellard             unlink(bs->filename);
876ea2384d3Sbellard         }
87767b915a5Sbellard #endif
878ea2384d3Sbellard         bs->opaque = NULL;
879ea2384d3Sbellard         bs->drv = NULL;
88053fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
881a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
882a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
883b338082bSbellard 
88466f82ceeSKevin Wolf         if (bs->file != NULL) {
8850ac9377dSPaolo Bonzini             bdrv_delete(bs->file);
8860ac9377dSPaolo Bonzini             bs->file = NULL;
88766f82ceeSKevin Wolf         }
88866f82ceeSKevin Wolf 
8897d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, false);
890b338082bSbellard     }
89198f90dbaSZhi Yong Wu 
89298f90dbaSZhi Yong Wu     /*throttling disk I/O limits*/
89398f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
89498f90dbaSZhi Yong Wu         bdrv_io_limits_disable(bs);
89598f90dbaSZhi Yong Wu     }
896b338082bSbellard }
897b338082bSbellard 
8982bc93fedSMORITA Kazutaka void bdrv_close_all(void)
8992bc93fedSMORITA Kazutaka {
9002bc93fedSMORITA Kazutaka     BlockDriverState *bs;
9012bc93fedSMORITA Kazutaka 
9022bc93fedSMORITA Kazutaka     QTAILQ_FOREACH(bs, &bdrv_states, list) {
9032bc93fedSMORITA Kazutaka         bdrv_close(bs);
9042bc93fedSMORITA Kazutaka     }
9052bc93fedSMORITA Kazutaka }
9062bc93fedSMORITA Kazutaka 
907922453bcSStefan Hajnoczi /*
908922453bcSStefan Hajnoczi  * Wait for pending requests to complete across all BlockDriverStates
909922453bcSStefan Hajnoczi  *
910922453bcSStefan Hajnoczi  * This function does not flush data to disk, use bdrv_flush_all() for that
911922453bcSStefan Hajnoczi  * after calling this function.
9124c355d53SZhi Yong Wu  *
9134c355d53SZhi Yong Wu  * Note that completion of an asynchronous I/O operation can trigger any
9144c355d53SZhi Yong Wu  * number of other I/O operations on other devices---for example a coroutine
9154c355d53SZhi Yong Wu  * can be arbitrarily complex and a constant flow of I/O can come until the
9164c355d53SZhi Yong Wu  * coroutine is complete.  Because of this, it is not possible to have a
9174c355d53SZhi Yong Wu  * function to drain a single device's I/O queue.
918922453bcSStefan Hajnoczi  */
919922453bcSStefan Hajnoczi void bdrv_drain_all(void)
920922453bcSStefan Hajnoczi {
921922453bcSStefan Hajnoczi     BlockDriverState *bs;
9224c355d53SZhi Yong Wu     bool busy;
923922453bcSStefan Hajnoczi 
9244c355d53SZhi Yong Wu     do {
9254c355d53SZhi Yong Wu         busy = qemu_aio_wait();
9264c355d53SZhi Yong Wu 
9274c355d53SZhi Yong Wu         /* FIXME: We do not have timer support here, so this is effectively
9284c355d53SZhi Yong Wu          * a busy wait.
9294c355d53SZhi Yong Wu          */
9304c355d53SZhi Yong Wu         QTAILQ_FOREACH(bs, &bdrv_states, list) {
9314c355d53SZhi Yong Wu             if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
9324c355d53SZhi Yong Wu                 qemu_co_queue_restart_all(&bs->throttled_reqs);
9334c355d53SZhi Yong Wu                 busy = true;
9344c355d53SZhi Yong Wu             }
9354c355d53SZhi Yong Wu         }
9364c355d53SZhi Yong Wu     } while (busy);
937922453bcSStefan Hajnoczi 
938922453bcSStefan Hajnoczi     /* If requests are still pending there is a bug somewhere */
939922453bcSStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
940922453bcSStefan Hajnoczi         assert(QLIST_EMPTY(&bs->tracked_requests));
941922453bcSStefan Hajnoczi         assert(qemu_co_queue_empty(&bs->throttled_reqs));
942922453bcSStefan Hajnoczi     }
943922453bcSStefan Hajnoczi }
944922453bcSStefan Hajnoczi 
945d22b2f41SRyan Harper /* make a BlockDriverState anonymous by removing from bdrv_state list.
946d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
947d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
948d22b2f41SRyan Harper {
949d22b2f41SRyan Harper     if (bs->device_name[0] != '\0') {
950d22b2f41SRyan Harper         QTAILQ_REMOVE(&bdrv_states, bs, list);
951d22b2f41SRyan Harper     }
952d22b2f41SRyan Harper     bs->device_name[0] = '\0';
953d22b2f41SRyan Harper }
954d22b2f41SRyan Harper 
955e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs)
956e023b2e2SPaolo Bonzini {
957e023b2e2SPaolo Bonzini     if (bs->drv && bs->drv->bdrv_rebind) {
958e023b2e2SPaolo Bonzini         bs->drv->bdrv_rebind(bs);
959e023b2e2SPaolo Bonzini     }
960e023b2e2SPaolo Bonzini }
961e023b2e2SPaolo Bonzini 
9628802d1fdSJeff Cody /*
9638802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
9648802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
9658802d1fdSJeff Cody  *
9668802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
9678802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
9688802d1fdSJeff Cody  *
969f6801b83SJeff Cody  * bs_new is required to be anonymous.
970f6801b83SJeff Cody  *
9718802d1fdSJeff Cody  * This function does not create any image files.
9728802d1fdSJeff Cody  */
9738802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
9748802d1fdSJeff Cody {
9758802d1fdSJeff Cody     BlockDriverState tmp;
9768802d1fdSJeff Cody 
977f6801b83SJeff Cody     /* bs_new must be anonymous */
978f6801b83SJeff Cody     assert(bs_new->device_name[0] == '\0');
9798802d1fdSJeff Cody 
9808802d1fdSJeff Cody     tmp = *bs_new;
9818802d1fdSJeff Cody 
9828802d1fdSJeff Cody     /* there are some fields that need to stay on the top layer: */
9833a389e79SPaolo Bonzini     tmp.open_flags        = bs_top->open_flags;
9848802d1fdSJeff Cody 
9858802d1fdSJeff Cody     /* dev info */
9868802d1fdSJeff Cody     tmp.dev_ops           = bs_top->dev_ops;
9878802d1fdSJeff Cody     tmp.dev_opaque        = bs_top->dev_opaque;
9888802d1fdSJeff Cody     tmp.dev               = bs_top->dev;
9898802d1fdSJeff Cody     tmp.buffer_alignment  = bs_top->buffer_alignment;
9908802d1fdSJeff Cody     tmp.copy_on_read      = bs_top->copy_on_read;
9918802d1fdSJeff Cody 
9928802d1fdSJeff Cody     /* i/o timing parameters */
9938802d1fdSJeff Cody     tmp.slice_time        = bs_top->slice_time;
9948802d1fdSJeff Cody     tmp.slice_start       = bs_top->slice_start;
9958802d1fdSJeff Cody     tmp.slice_end         = bs_top->slice_end;
9968802d1fdSJeff Cody     tmp.io_limits         = bs_top->io_limits;
9978802d1fdSJeff Cody     tmp.io_base           = bs_top->io_base;
9988802d1fdSJeff Cody     tmp.throttled_reqs    = bs_top->throttled_reqs;
9998802d1fdSJeff Cody     tmp.block_timer       = bs_top->block_timer;
10008802d1fdSJeff Cody     tmp.io_limits_enabled = bs_top->io_limits_enabled;
10018802d1fdSJeff Cody 
10028802d1fdSJeff Cody     /* geometry */
10038802d1fdSJeff Cody     tmp.cyls              = bs_top->cyls;
10048802d1fdSJeff Cody     tmp.heads             = bs_top->heads;
10058802d1fdSJeff Cody     tmp.secs              = bs_top->secs;
10068802d1fdSJeff Cody     tmp.translation       = bs_top->translation;
10078802d1fdSJeff Cody 
10088802d1fdSJeff Cody     /* r/w error */
10098802d1fdSJeff Cody     tmp.on_read_error     = bs_top->on_read_error;
10108802d1fdSJeff Cody     tmp.on_write_error    = bs_top->on_write_error;
10118802d1fdSJeff Cody 
10128802d1fdSJeff Cody     /* i/o status */
10138802d1fdSJeff Cody     tmp.iostatus_enabled  = bs_top->iostatus_enabled;
10148802d1fdSJeff Cody     tmp.iostatus          = bs_top->iostatus;
10158802d1fdSJeff Cody 
10168802d1fdSJeff Cody     /* keep the same entry in bdrv_states */
10178802d1fdSJeff Cody     pstrcpy(tmp.device_name, sizeof(tmp.device_name), bs_top->device_name);
10188802d1fdSJeff Cody     tmp.list = bs_top->list;
10198802d1fdSJeff Cody 
10208802d1fdSJeff Cody     /* The contents of 'tmp' will become bs_top, as we are
10218802d1fdSJeff Cody      * swapping bs_new and bs_top contents. */
10228802d1fdSJeff Cody     tmp.backing_hd = bs_new;
10238802d1fdSJeff Cody     pstrcpy(tmp.backing_file, sizeof(tmp.backing_file), bs_top->filename);
1024f6801b83SJeff Cody     bdrv_get_format(bs_top, tmp.backing_format, sizeof(tmp.backing_format));
10258802d1fdSJeff Cody 
10268802d1fdSJeff Cody     /* swap contents of the fixed new bs and the current top */
10278802d1fdSJeff Cody     *bs_new = *bs_top;
10288802d1fdSJeff Cody     *bs_top = tmp;
10298802d1fdSJeff Cody 
1030f6801b83SJeff Cody     /* device_name[] was carried over from the old bs_top.  bs_new
1031f6801b83SJeff Cody      * shouldn't be in bdrv_states, so we need to make device_name[]
1032f6801b83SJeff Cody      * reflect the anonymity of bs_new
1033f6801b83SJeff Cody      */
1034f6801b83SJeff Cody     bs_new->device_name[0] = '\0';
1035f6801b83SJeff Cody 
10368802d1fdSJeff Cody     /* clear the copied fields in the new backing file */
10378802d1fdSJeff Cody     bdrv_detach_dev(bs_new, bs_new->dev);
10388802d1fdSJeff Cody 
10398802d1fdSJeff Cody     qemu_co_queue_init(&bs_new->throttled_reqs);
10408802d1fdSJeff Cody     memset(&bs_new->io_base,   0, sizeof(bs_new->io_base));
10418802d1fdSJeff Cody     memset(&bs_new->io_limits, 0, sizeof(bs_new->io_limits));
10428802d1fdSJeff Cody     bdrv_iostatus_disable(bs_new);
10438802d1fdSJeff Cody 
10448802d1fdSJeff Cody     /* we don't use bdrv_io_limits_disable() for this, because we don't want
10458802d1fdSJeff Cody      * to affect or delete the block_timer, as it has been moved to bs_top */
10468802d1fdSJeff Cody     bs_new->io_limits_enabled = false;
10478802d1fdSJeff Cody     bs_new->block_timer       = NULL;
10488802d1fdSJeff Cody     bs_new->slice_time        = 0;
10498802d1fdSJeff Cody     bs_new->slice_start       = 0;
10508802d1fdSJeff Cody     bs_new->slice_end         = 0;
1051e023b2e2SPaolo Bonzini 
1052e023b2e2SPaolo Bonzini     bdrv_rebind(bs_new);
1053e023b2e2SPaolo Bonzini     bdrv_rebind(bs_top);
10548802d1fdSJeff Cody }
10558802d1fdSJeff Cody 
1056b338082bSbellard void bdrv_delete(BlockDriverState *bs)
1057b338082bSbellard {
1058fa879d62SMarkus Armbruster     assert(!bs->dev);
10593e914655SPaolo Bonzini     assert(!bs->job);
10603e914655SPaolo Bonzini     assert(!bs->in_use);
106118846deeSMarkus Armbruster 
10621b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
1063d22b2f41SRyan Harper     bdrv_make_anon(bs);
106434c6f050Saurel32 
1065b338082bSbellard     bdrv_close(bs);
106666f82ceeSKevin Wolf 
1067f9092b10SMarkus Armbruster     assert(bs != bs_snapshots);
10687267c094SAnthony Liguori     g_free(bs);
1069fc01f7e7Sbellard }
1070fc01f7e7Sbellard 
1071fa879d62SMarkus Armbruster int bdrv_attach_dev(BlockDriverState *bs, void *dev)
1072fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
107318846deeSMarkus Armbruster {
1074fa879d62SMarkus Armbruster     if (bs->dev) {
107518846deeSMarkus Armbruster         return -EBUSY;
107618846deeSMarkus Armbruster     }
1077fa879d62SMarkus Armbruster     bs->dev = dev;
107828a7282aSLuiz Capitulino     bdrv_iostatus_reset(bs);
107918846deeSMarkus Armbruster     return 0;
108018846deeSMarkus Armbruster }
108118846deeSMarkus Armbruster 
1082fa879d62SMarkus Armbruster /* TODO qdevified devices don't use this, remove when devices are qdevified */
1083fa879d62SMarkus Armbruster void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
108418846deeSMarkus Armbruster {
1085fa879d62SMarkus Armbruster     if (bdrv_attach_dev(bs, dev) < 0) {
1086fa879d62SMarkus Armbruster         abort();
1087fa879d62SMarkus Armbruster     }
1088fa879d62SMarkus Armbruster }
1089fa879d62SMarkus Armbruster 
1090fa879d62SMarkus Armbruster void bdrv_detach_dev(BlockDriverState *bs, void *dev)
1091fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
1092fa879d62SMarkus Armbruster {
1093fa879d62SMarkus Armbruster     assert(bs->dev == dev);
1094fa879d62SMarkus Armbruster     bs->dev = NULL;
10950e49de52SMarkus Armbruster     bs->dev_ops = NULL;
10960e49de52SMarkus Armbruster     bs->dev_opaque = NULL;
109729e05f20SMarkus Armbruster     bs->buffer_alignment = 512;
109818846deeSMarkus Armbruster }
109918846deeSMarkus Armbruster 
1100fa879d62SMarkus Armbruster /* TODO change to return DeviceState * when all users are qdevified */
1101fa879d62SMarkus Armbruster void *bdrv_get_attached_dev(BlockDriverState *bs)
110218846deeSMarkus Armbruster {
1103fa879d62SMarkus Armbruster     return bs->dev;
110418846deeSMarkus Armbruster }
110518846deeSMarkus Armbruster 
11060e49de52SMarkus Armbruster void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
11070e49de52SMarkus Armbruster                       void *opaque)
11080e49de52SMarkus Armbruster {
11090e49de52SMarkus Armbruster     bs->dev_ops = ops;
11100e49de52SMarkus Armbruster     bs->dev_opaque = opaque;
11112c6942faSMarkus Armbruster     if (bdrv_dev_has_removable_media(bs) && bs == bs_snapshots) {
11122c6942faSMarkus Armbruster         bs_snapshots = NULL;
11132c6942faSMarkus Armbruster     }
11140e49de52SMarkus Armbruster }
11150e49de52SMarkus Armbruster 
1116329c0a48SLuiz Capitulino void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
1117329c0a48SLuiz Capitulino                                BlockQMPEventAction action, int is_read)
1118329c0a48SLuiz Capitulino {
1119329c0a48SLuiz Capitulino     QObject *data;
1120329c0a48SLuiz Capitulino     const char *action_str;
1121329c0a48SLuiz Capitulino 
1122329c0a48SLuiz Capitulino     switch (action) {
1123329c0a48SLuiz Capitulino     case BDRV_ACTION_REPORT:
1124329c0a48SLuiz Capitulino         action_str = "report";
1125329c0a48SLuiz Capitulino         break;
1126329c0a48SLuiz Capitulino     case BDRV_ACTION_IGNORE:
1127329c0a48SLuiz Capitulino         action_str = "ignore";
1128329c0a48SLuiz Capitulino         break;
1129329c0a48SLuiz Capitulino     case BDRV_ACTION_STOP:
1130329c0a48SLuiz Capitulino         action_str = "stop";
1131329c0a48SLuiz Capitulino         break;
1132329c0a48SLuiz Capitulino     default:
1133329c0a48SLuiz Capitulino         abort();
1134329c0a48SLuiz Capitulino     }
1135329c0a48SLuiz Capitulino 
1136329c0a48SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1137329c0a48SLuiz Capitulino                               bdrv->device_name,
1138329c0a48SLuiz Capitulino                               action_str,
1139329c0a48SLuiz Capitulino                               is_read ? "read" : "write");
1140329c0a48SLuiz Capitulino     monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1141329c0a48SLuiz Capitulino 
1142329c0a48SLuiz Capitulino     qobject_decref(data);
1143329c0a48SLuiz Capitulino }
1144329c0a48SLuiz Capitulino 
11456f382ed2SLuiz Capitulino static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
11466f382ed2SLuiz Capitulino {
11476f382ed2SLuiz Capitulino     QObject *data;
11486f382ed2SLuiz Capitulino 
11496f382ed2SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
11506f382ed2SLuiz Capitulino                               bdrv_get_device_name(bs), ejected);
11516f382ed2SLuiz Capitulino     monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
11526f382ed2SLuiz Capitulino 
11536f382ed2SLuiz Capitulino     qobject_decref(data);
11546f382ed2SLuiz Capitulino }
11556f382ed2SLuiz Capitulino 
11567d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
11570e49de52SMarkus Armbruster {
1158145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->change_media_cb) {
11596f382ed2SLuiz Capitulino         bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
11607d4b4ba5SMarkus Armbruster         bs->dev_ops->change_media_cb(bs->dev_opaque, load);
11616f382ed2SLuiz Capitulino         if (tray_was_closed) {
11626f382ed2SLuiz Capitulino             /* tray open */
11636f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, true);
11646f382ed2SLuiz Capitulino         }
11656f382ed2SLuiz Capitulino         if (load) {
11666f382ed2SLuiz Capitulino             /* tray close */
11676f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, false);
11686f382ed2SLuiz Capitulino         }
1169145feb17SMarkus Armbruster     }
1170145feb17SMarkus Armbruster }
1171145feb17SMarkus Armbruster 
11722c6942faSMarkus Armbruster bool bdrv_dev_has_removable_media(BlockDriverState *bs)
11732c6942faSMarkus Armbruster {
11742c6942faSMarkus Armbruster     return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
11752c6942faSMarkus Armbruster }
11762c6942faSMarkus Armbruster 
1177025ccaa7SPaolo Bonzini void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
1178025ccaa7SPaolo Bonzini {
1179025ccaa7SPaolo Bonzini     if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
1180025ccaa7SPaolo Bonzini         bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
1181025ccaa7SPaolo Bonzini     }
1182025ccaa7SPaolo Bonzini }
1183025ccaa7SPaolo Bonzini 
1184e4def80bSMarkus Armbruster bool bdrv_dev_is_tray_open(BlockDriverState *bs)
1185e4def80bSMarkus Armbruster {
1186e4def80bSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_tray_open) {
1187e4def80bSMarkus Armbruster         return bs->dev_ops->is_tray_open(bs->dev_opaque);
1188e4def80bSMarkus Armbruster     }
1189e4def80bSMarkus Armbruster     return false;
1190e4def80bSMarkus Armbruster }
1191e4def80bSMarkus Armbruster 
1192145feb17SMarkus Armbruster static void bdrv_dev_resize_cb(BlockDriverState *bs)
1193145feb17SMarkus Armbruster {
1194145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->resize_cb) {
1195145feb17SMarkus Armbruster         bs->dev_ops->resize_cb(bs->dev_opaque);
11960e49de52SMarkus Armbruster     }
11970e49de52SMarkus Armbruster }
11980e49de52SMarkus Armbruster 
1199f107639aSMarkus Armbruster bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
1200f107639aSMarkus Armbruster {
1201f107639aSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
1202f107639aSMarkus Armbruster         return bs->dev_ops->is_medium_locked(bs->dev_opaque);
1203f107639aSMarkus Armbruster     }
1204f107639aSMarkus Armbruster     return false;
1205f107639aSMarkus Armbruster }
1206f107639aSMarkus Armbruster 
1207e97fc193Saliguori /*
1208e97fc193Saliguori  * Run consistency checks on an image
1209e97fc193Saliguori  *
1210e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
1211a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
1212e076f338SKevin Wolf  * check are stored in res.
1213e97fc193Saliguori  */
1214e076f338SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
1215e97fc193Saliguori {
1216e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
1217e97fc193Saliguori         return -ENOTSUP;
1218e97fc193Saliguori     }
1219e97fc193Saliguori 
1220e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
12219ac228e0SKevin Wolf     return bs->drv->bdrv_check(bs, res);
1222e97fc193Saliguori }
1223e97fc193Saliguori 
12248a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
12258a426614SKevin Wolf 
122633e3963eSbellard /* commit COW file into the raw image */
122733e3963eSbellard int bdrv_commit(BlockDriverState *bs)
122833e3963eSbellard {
122919cb3738Sbellard     BlockDriver *drv = bs->drv;
1230ee181196SKevin Wolf     BlockDriver *backing_drv;
12318a426614SKevin Wolf     int64_t sector, total_sectors;
12328a426614SKevin Wolf     int n, ro, open_flags;
12334dca4b63SNaphtali Sprei     int ret = 0, rw_ret = 0;
12348a426614SKevin Wolf     uint8_t *buf;
12354dca4b63SNaphtali Sprei     char filename[1024];
12364dca4b63SNaphtali Sprei     BlockDriverState *bs_rw, *bs_ro;
123733e3963eSbellard 
123819cb3738Sbellard     if (!drv)
123919cb3738Sbellard         return -ENOMEDIUM;
124033e3963eSbellard 
12414dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
12424dca4b63SNaphtali Sprei         return -ENOTSUP;
12434dca4b63SNaphtali Sprei     }
12444dca4b63SNaphtali Sprei 
12454dca4b63SNaphtali Sprei     if (bs->backing_hd->keep_read_only) {
1246ea2384d3Sbellard         return -EACCES;
124733e3963eSbellard     }
124833e3963eSbellard 
12492d3735d3SStefan Hajnoczi     if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
12502d3735d3SStefan Hajnoczi         return -EBUSY;
12512d3735d3SStefan Hajnoczi     }
12522d3735d3SStefan Hajnoczi 
1253ee181196SKevin Wolf     backing_drv = bs->backing_hd->drv;
12544dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
12554dca4b63SNaphtali Sprei     strncpy(filename, bs->backing_hd->filename, sizeof(filename));
12564dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
12574dca4b63SNaphtali Sprei 
12584dca4b63SNaphtali Sprei     if (ro) {
12594dca4b63SNaphtali Sprei         /* re-open as RW */
12604dca4b63SNaphtali Sprei         bdrv_delete(bs->backing_hd);
12614dca4b63SNaphtali Sprei         bs->backing_hd = NULL;
12624dca4b63SNaphtali Sprei         bs_rw = bdrv_new("");
1263ee181196SKevin Wolf         rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
1264ee181196SKevin Wolf             backing_drv);
12654dca4b63SNaphtali Sprei         if (rw_ret < 0) {
12664dca4b63SNaphtali Sprei             bdrv_delete(bs_rw);
12674dca4b63SNaphtali Sprei             /* try to re-open read-only */
12684dca4b63SNaphtali Sprei             bs_ro = bdrv_new("");
1269ee181196SKevin Wolf             ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
1270ee181196SKevin Wolf                 backing_drv);
12714dca4b63SNaphtali Sprei             if (ret < 0) {
12724dca4b63SNaphtali Sprei                 bdrv_delete(bs_ro);
12734dca4b63SNaphtali Sprei                 /* drive not functional anymore */
12744dca4b63SNaphtali Sprei                 bs->drv = NULL;
12754dca4b63SNaphtali Sprei                 return ret;
12764dca4b63SNaphtali Sprei             }
12774dca4b63SNaphtali Sprei             bs->backing_hd = bs_ro;
12784dca4b63SNaphtali Sprei             return rw_ret;
12794dca4b63SNaphtali Sprei         }
12804dca4b63SNaphtali Sprei         bs->backing_hd = bs_rw;
1281ea2384d3Sbellard     }
1282ea2384d3Sbellard 
12836ea44308SJan Kiszka     total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
12847267c094SAnthony Liguori     buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
12858a426614SKevin Wolf 
12868a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
128705c4af54SStefan Hajnoczi         if (bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
12888a426614SKevin Wolf 
12898a426614SKevin Wolf             if (bdrv_read(bs, sector, buf, n) != 0) {
12904dca4b63SNaphtali Sprei                 ret = -EIO;
12914dca4b63SNaphtali Sprei                 goto ro_cleanup;
129233e3963eSbellard             }
129333e3963eSbellard 
12948a426614SKevin Wolf             if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
12954dca4b63SNaphtali Sprei                 ret = -EIO;
12964dca4b63SNaphtali Sprei                 goto ro_cleanup;
129733e3963eSbellard             }
129833e3963eSbellard         }
129933e3963eSbellard     }
130095389c86Sbellard 
13011d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
13021d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
13031d44952fSChristoph Hellwig         bdrv_flush(bs);
13041d44952fSChristoph Hellwig     }
130595389c86Sbellard 
13063f5075aeSChristoph Hellwig     /*
13073f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
13083f5075aeSChristoph Hellwig      * stable on disk.
13093f5075aeSChristoph Hellwig      */
13103f5075aeSChristoph Hellwig     if (bs->backing_hd)
13113f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
13124dca4b63SNaphtali Sprei 
13134dca4b63SNaphtali Sprei ro_cleanup:
13147267c094SAnthony Liguori     g_free(buf);
13154dca4b63SNaphtali Sprei 
13164dca4b63SNaphtali Sprei     if (ro) {
13174dca4b63SNaphtali Sprei         /* re-open as RO */
13184dca4b63SNaphtali Sprei         bdrv_delete(bs->backing_hd);
13194dca4b63SNaphtali Sprei         bs->backing_hd = NULL;
13204dca4b63SNaphtali Sprei         bs_ro = bdrv_new("");
1321ee181196SKevin Wolf         ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
1322ee181196SKevin Wolf             backing_drv);
13234dca4b63SNaphtali Sprei         if (ret < 0) {
13244dca4b63SNaphtali Sprei             bdrv_delete(bs_ro);
13254dca4b63SNaphtali Sprei             /* drive not functional anymore */
13264dca4b63SNaphtali Sprei             bs->drv = NULL;
13274dca4b63SNaphtali Sprei             return ret;
13284dca4b63SNaphtali Sprei         }
13294dca4b63SNaphtali Sprei         bs->backing_hd = bs_ro;
13304dca4b63SNaphtali Sprei         bs->backing_hd->keep_read_only = 0;
13314dca4b63SNaphtali Sprei     }
13324dca4b63SNaphtali Sprei 
13331d44952fSChristoph Hellwig     return ret;
133433e3963eSbellard }
133533e3963eSbellard 
1336e8877497SStefan Hajnoczi int bdrv_commit_all(void)
13376ab4b5abSMarkus Armbruster {
13386ab4b5abSMarkus Armbruster     BlockDriverState *bs;
13396ab4b5abSMarkus Armbruster 
13406ab4b5abSMarkus Armbruster     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1341e8877497SStefan Hajnoczi         int ret = bdrv_commit(bs);
1342e8877497SStefan Hajnoczi         if (ret < 0) {
1343e8877497SStefan Hajnoczi             return ret;
13446ab4b5abSMarkus Armbruster         }
13456ab4b5abSMarkus Armbruster     }
1346e8877497SStefan Hajnoczi     return 0;
1347e8877497SStefan Hajnoczi }
13486ab4b5abSMarkus Armbruster 
1349dbffbdcfSStefan Hajnoczi struct BdrvTrackedRequest {
1350dbffbdcfSStefan Hajnoczi     BlockDriverState *bs;
1351dbffbdcfSStefan Hajnoczi     int64_t sector_num;
1352dbffbdcfSStefan Hajnoczi     int nb_sectors;
1353dbffbdcfSStefan Hajnoczi     bool is_write;
1354dbffbdcfSStefan Hajnoczi     QLIST_ENTRY(BdrvTrackedRequest) list;
13555f8b6491SStefan Hajnoczi     Coroutine *co; /* owner, used for deadlock detection */
1356f4658285SStefan Hajnoczi     CoQueue wait_queue; /* coroutines blocked on this request */
1357dbffbdcfSStefan Hajnoczi };
1358dbffbdcfSStefan Hajnoczi 
1359dbffbdcfSStefan Hajnoczi /**
1360dbffbdcfSStefan Hajnoczi  * Remove an active request from the tracked requests list
1361dbffbdcfSStefan Hajnoczi  *
1362dbffbdcfSStefan Hajnoczi  * This function should be called when a tracked request is completing.
1363dbffbdcfSStefan Hajnoczi  */
1364dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req)
1365dbffbdcfSStefan Hajnoczi {
1366dbffbdcfSStefan Hajnoczi     QLIST_REMOVE(req, list);
1367f4658285SStefan Hajnoczi     qemu_co_queue_restart_all(&req->wait_queue);
1368dbffbdcfSStefan Hajnoczi }
1369dbffbdcfSStefan Hajnoczi 
1370dbffbdcfSStefan Hajnoczi /**
1371dbffbdcfSStefan Hajnoczi  * Add an active request to the tracked requests list
1372dbffbdcfSStefan Hajnoczi  */
1373dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req,
1374dbffbdcfSStefan Hajnoczi                                   BlockDriverState *bs,
1375dbffbdcfSStefan Hajnoczi                                   int64_t sector_num,
1376dbffbdcfSStefan Hajnoczi                                   int nb_sectors, bool is_write)
1377dbffbdcfSStefan Hajnoczi {
1378dbffbdcfSStefan Hajnoczi     *req = (BdrvTrackedRequest){
1379dbffbdcfSStefan Hajnoczi         .bs = bs,
1380dbffbdcfSStefan Hajnoczi         .sector_num = sector_num,
1381dbffbdcfSStefan Hajnoczi         .nb_sectors = nb_sectors,
1382dbffbdcfSStefan Hajnoczi         .is_write = is_write,
13835f8b6491SStefan Hajnoczi         .co = qemu_coroutine_self(),
1384dbffbdcfSStefan Hajnoczi     };
1385dbffbdcfSStefan Hajnoczi 
1386f4658285SStefan Hajnoczi     qemu_co_queue_init(&req->wait_queue);
1387f4658285SStefan Hajnoczi 
1388dbffbdcfSStefan Hajnoczi     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
1389dbffbdcfSStefan Hajnoczi }
1390dbffbdcfSStefan Hajnoczi 
1391d83947acSStefan Hajnoczi /**
1392d83947acSStefan Hajnoczi  * Round a region to cluster boundaries
1393d83947acSStefan Hajnoczi  */
1394d83947acSStefan Hajnoczi static void round_to_clusters(BlockDriverState *bs,
1395d83947acSStefan Hajnoczi                               int64_t sector_num, int nb_sectors,
1396d83947acSStefan Hajnoczi                               int64_t *cluster_sector_num,
1397d83947acSStefan Hajnoczi                               int *cluster_nb_sectors)
1398d83947acSStefan Hajnoczi {
1399d83947acSStefan Hajnoczi     BlockDriverInfo bdi;
1400d83947acSStefan Hajnoczi 
1401d83947acSStefan Hajnoczi     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
1402d83947acSStefan Hajnoczi         *cluster_sector_num = sector_num;
1403d83947acSStefan Hajnoczi         *cluster_nb_sectors = nb_sectors;
1404d83947acSStefan Hajnoczi     } else {
1405d83947acSStefan Hajnoczi         int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
1406d83947acSStefan Hajnoczi         *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
1407d83947acSStefan Hajnoczi         *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
1408d83947acSStefan Hajnoczi                                             nb_sectors, c);
1409d83947acSStefan Hajnoczi     }
1410d83947acSStefan Hajnoczi }
1411d83947acSStefan Hajnoczi 
1412f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req,
1413f4658285SStefan Hajnoczi                                      int64_t sector_num, int nb_sectors) {
1414d83947acSStefan Hajnoczi     /*        aaaa   bbbb */
1415d83947acSStefan Hajnoczi     if (sector_num >= req->sector_num + req->nb_sectors) {
1416d83947acSStefan Hajnoczi         return false;
1417d83947acSStefan Hajnoczi     }
1418d83947acSStefan Hajnoczi     /* bbbb   aaaa        */
1419d83947acSStefan Hajnoczi     if (req->sector_num >= sector_num + nb_sectors) {
1420d83947acSStefan Hajnoczi         return false;
1421d83947acSStefan Hajnoczi     }
1422d83947acSStefan Hajnoczi     return true;
1423f4658285SStefan Hajnoczi }
1424f4658285SStefan Hajnoczi 
1425f4658285SStefan Hajnoczi static void coroutine_fn wait_for_overlapping_requests(BlockDriverState *bs,
1426f4658285SStefan Hajnoczi         int64_t sector_num, int nb_sectors)
1427f4658285SStefan Hajnoczi {
1428f4658285SStefan Hajnoczi     BdrvTrackedRequest *req;
1429d83947acSStefan Hajnoczi     int64_t cluster_sector_num;
1430d83947acSStefan Hajnoczi     int cluster_nb_sectors;
1431f4658285SStefan Hajnoczi     bool retry;
1432f4658285SStefan Hajnoczi 
1433d83947acSStefan Hajnoczi     /* If we touch the same cluster it counts as an overlap.  This guarantees
1434d83947acSStefan Hajnoczi      * that allocating writes will be serialized and not race with each other
1435d83947acSStefan Hajnoczi      * for the same cluster.  For example, in copy-on-read it ensures that the
1436d83947acSStefan Hajnoczi      * CoR read and write operations are atomic and guest writes cannot
1437d83947acSStefan Hajnoczi      * interleave between them.
1438d83947acSStefan Hajnoczi      */
1439d83947acSStefan Hajnoczi     round_to_clusters(bs, sector_num, nb_sectors,
1440d83947acSStefan Hajnoczi                       &cluster_sector_num, &cluster_nb_sectors);
1441d83947acSStefan Hajnoczi 
1442f4658285SStefan Hajnoczi     do {
1443f4658285SStefan Hajnoczi         retry = false;
1444f4658285SStefan Hajnoczi         QLIST_FOREACH(req, &bs->tracked_requests, list) {
1445d83947acSStefan Hajnoczi             if (tracked_request_overlaps(req, cluster_sector_num,
1446d83947acSStefan Hajnoczi                                          cluster_nb_sectors)) {
14475f8b6491SStefan Hajnoczi                 /* Hitting this means there was a reentrant request, for
14485f8b6491SStefan Hajnoczi                  * example, a block driver issuing nested requests.  This must
14495f8b6491SStefan Hajnoczi                  * never happen since it means deadlock.
14505f8b6491SStefan Hajnoczi                  */
14515f8b6491SStefan Hajnoczi                 assert(qemu_coroutine_self() != req->co);
14525f8b6491SStefan Hajnoczi 
1453f4658285SStefan Hajnoczi                 qemu_co_queue_wait(&req->wait_queue);
1454f4658285SStefan Hajnoczi                 retry = true;
1455f4658285SStefan Hajnoczi                 break;
1456f4658285SStefan Hajnoczi             }
1457f4658285SStefan Hajnoczi         }
1458f4658285SStefan Hajnoczi     } while (retry);
1459f4658285SStefan Hajnoczi }
1460f4658285SStefan Hajnoczi 
1461756e6736SKevin Wolf /*
1462756e6736SKevin Wolf  * Return values:
1463756e6736SKevin Wolf  * 0        - success
1464756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
1465756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
1466756e6736SKevin Wolf  *            image file header
1467756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
1468756e6736SKevin Wolf  */
1469756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
1470756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
1471756e6736SKevin Wolf {
1472756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
1473469ef350SPaolo Bonzini     int ret;
1474756e6736SKevin Wolf 
14755f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
14765f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
14775f377794SPaolo Bonzini         return -EINVAL;
14785f377794SPaolo Bonzini     }
14795f377794SPaolo Bonzini 
1480756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
1481469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
1482756e6736SKevin Wolf     } else {
1483469ef350SPaolo Bonzini         ret = -ENOTSUP;
1484756e6736SKevin Wolf     }
1485469ef350SPaolo Bonzini 
1486469ef350SPaolo Bonzini     if (ret == 0) {
1487469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1488469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1489469ef350SPaolo Bonzini     }
1490469ef350SPaolo Bonzini     return ret;
1491756e6736SKevin Wolf }
1492756e6736SKevin Wolf 
149371d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
149471d0770cSaliguori                                    size_t size)
149571d0770cSaliguori {
149671d0770cSaliguori     int64_t len;
149771d0770cSaliguori 
149871d0770cSaliguori     if (!bdrv_is_inserted(bs))
149971d0770cSaliguori         return -ENOMEDIUM;
150071d0770cSaliguori 
150171d0770cSaliguori     if (bs->growable)
150271d0770cSaliguori         return 0;
150371d0770cSaliguori 
150471d0770cSaliguori     len = bdrv_getlength(bs);
150571d0770cSaliguori 
1506fbb7b4e0SKevin Wolf     if (offset < 0)
1507fbb7b4e0SKevin Wolf         return -EIO;
1508fbb7b4e0SKevin Wolf 
1509fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
151071d0770cSaliguori         return -EIO;
151171d0770cSaliguori 
151271d0770cSaliguori     return 0;
151371d0770cSaliguori }
151471d0770cSaliguori 
151571d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
151671d0770cSaliguori                               int nb_sectors)
151771d0770cSaliguori {
1518eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
1519eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
152071d0770cSaliguori }
152171d0770cSaliguori 
15221c9805a3SStefan Hajnoczi typedef struct RwCo {
15231c9805a3SStefan Hajnoczi     BlockDriverState *bs;
15241c9805a3SStefan Hajnoczi     int64_t sector_num;
15251c9805a3SStefan Hajnoczi     int nb_sectors;
15261c9805a3SStefan Hajnoczi     QEMUIOVector *qiov;
15271c9805a3SStefan Hajnoczi     bool is_write;
15281c9805a3SStefan Hajnoczi     int ret;
15291c9805a3SStefan Hajnoczi } RwCo;
15301c9805a3SStefan Hajnoczi 
15311c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque)
1532fc01f7e7Sbellard {
15331c9805a3SStefan Hajnoczi     RwCo *rwco = opaque;
1534fc01f7e7Sbellard 
15351c9805a3SStefan Hajnoczi     if (!rwco->is_write) {
15361c9805a3SStefan Hajnoczi         rwco->ret = bdrv_co_do_readv(rwco->bs, rwco->sector_num,
1537470c0504SStefan Hajnoczi                                      rwco->nb_sectors, rwco->qiov, 0);
15381c9805a3SStefan Hajnoczi     } else {
15391c9805a3SStefan Hajnoczi         rwco->ret = bdrv_co_do_writev(rwco->bs, rwco->sector_num,
1540f08f2ddaSStefan Hajnoczi                                       rwco->nb_sectors, rwco->qiov, 0);
15411c9805a3SStefan Hajnoczi     }
15421c9805a3SStefan Hajnoczi }
1543e7a8a783SKevin Wolf 
15441c9805a3SStefan Hajnoczi /*
15451c9805a3SStefan Hajnoczi  * Process a synchronous request using coroutines
15461c9805a3SStefan Hajnoczi  */
15471c9805a3SStefan Hajnoczi static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
15481c9805a3SStefan Hajnoczi                       int nb_sectors, bool is_write)
15491c9805a3SStefan Hajnoczi {
1550e7a8a783SKevin Wolf     QEMUIOVector qiov;
1551e7a8a783SKevin Wolf     struct iovec iov = {
1552e7a8a783SKevin Wolf         .iov_base = (void *)buf,
1553e7a8a783SKevin Wolf         .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1554e7a8a783SKevin Wolf     };
15551c9805a3SStefan Hajnoczi     Coroutine *co;
15561c9805a3SStefan Hajnoczi     RwCo rwco = {
15571c9805a3SStefan Hajnoczi         .bs = bs,
15581c9805a3SStefan Hajnoczi         .sector_num = sector_num,
15591c9805a3SStefan Hajnoczi         .nb_sectors = nb_sectors,
15601c9805a3SStefan Hajnoczi         .qiov = &qiov,
15611c9805a3SStefan Hajnoczi         .is_write = is_write,
15621c9805a3SStefan Hajnoczi         .ret = NOT_DONE,
15631c9805a3SStefan Hajnoczi     };
1564e7a8a783SKevin Wolf 
1565e7a8a783SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
15661c9805a3SStefan Hajnoczi 
1567498e386cSZhi Yong Wu     /**
1568498e386cSZhi Yong Wu      * In sync call context, when the vcpu is blocked, this throttling timer
1569498e386cSZhi Yong Wu      * will not fire; so the I/O throttling function has to be disabled here
1570498e386cSZhi Yong Wu      * if it has been enabled.
1571498e386cSZhi Yong Wu      */
1572498e386cSZhi Yong Wu     if (bs->io_limits_enabled) {
1573498e386cSZhi Yong Wu         fprintf(stderr, "Disabling I/O throttling on '%s' due "
1574498e386cSZhi Yong Wu                         "to synchronous I/O.\n", bdrv_get_device_name(bs));
1575498e386cSZhi Yong Wu         bdrv_io_limits_disable(bs);
1576498e386cSZhi Yong Wu     }
1577498e386cSZhi Yong Wu 
15781c9805a3SStefan Hajnoczi     if (qemu_in_coroutine()) {
15791c9805a3SStefan Hajnoczi         /* Fast-path if already in coroutine context */
15801c9805a3SStefan Hajnoczi         bdrv_rw_co_entry(&rwco);
15811c9805a3SStefan Hajnoczi     } else {
15821c9805a3SStefan Hajnoczi         co = qemu_coroutine_create(bdrv_rw_co_entry);
15831c9805a3SStefan Hajnoczi         qemu_coroutine_enter(co, &rwco);
15841c9805a3SStefan Hajnoczi         while (rwco.ret == NOT_DONE) {
15851c9805a3SStefan Hajnoczi             qemu_aio_wait();
15861c9805a3SStefan Hajnoczi         }
15871c9805a3SStefan Hajnoczi     }
15881c9805a3SStefan Hajnoczi     return rwco.ret;
1589e7a8a783SKevin Wolf }
1590e7a8a783SKevin Wolf 
15911c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */
15921c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num,
15931c9805a3SStefan Hajnoczi               uint8_t *buf, int nb_sectors)
15941c9805a3SStefan Hajnoczi {
15951c9805a3SStefan Hajnoczi     return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false);
159683f64091Sbellard }
1597fc01f7e7Sbellard 
159871df14fcSPaolo Bonzini #define BITS_PER_LONG  (sizeof(unsigned long) * 8)
159971df14fcSPaolo Bonzini 
16007cd1e32aSlirans@il.ibm.com static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
16017cd1e32aSlirans@il.ibm.com                              int nb_sectors, int dirty)
16027cd1e32aSlirans@il.ibm.com {
16037cd1e32aSlirans@il.ibm.com     int64_t start, end;
1604c6d22830SJan Kiszka     unsigned long val, idx, bit;
1605a55eb92cSJan Kiszka 
16066ea44308SJan Kiszka     start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
1607c6d22830SJan Kiszka     end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
16087cd1e32aSlirans@il.ibm.com 
16097cd1e32aSlirans@il.ibm.com     for (; start <= end; start++) {
161071df14fcSPaolo Bonzini         idx = start / BITS_PER_LONG;
161171df14fcSPaolo Bonzini         bit = start % BITS_PER_LONG;
1612c6d22830SJan Kiszka         val = bs->dirty_bitmap[idx];
1613c6d22830SJan Kiszka         if (dirty) {
16146d59fec1SMarcelo Tosatti             if (!(val & (1UL << bit))) {
1615aaa0eb75SLiran Schour                 bs->dirty_count++;
16166d59fec1SMarcelo Tosatti                 val |= 1UL << bit;
1617aaa0eb75SLiran Schour             }
1618c6d22830SJan Kiszka         } else {
16196d59fec1SMarcelo Tosatti             if (val & (1UL << bit)) {
1620aaa0eb75SLiran Schour                 bs->dirty_count--;
16216d59fec1SMarcelo Tosatti                 val &= ~(1UL << bit);
1622c6d22830SJan Kiszka             }
1623aaa0eb75SLiran Schour         }
1624c6d22830SJan Kiszka         bs->dirty_bitmap[idx] = val;
16257cd1e32aSlirans@il.ibm.com     }
16267cd1e32aSlirans@il.ibm.com }
16277cd1e32aSlirans@il.ibm.com 
162819cb3738Sbellard /* Return < 0 if error. Important errors are:
162919cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
163019cb3738Sbellard   -ENOMEDIUM   No media inserted.
163119cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
163219cb3738Sbellard   -EACCES      Trying to write a read-only device
163319cb3738Sbellard */
1634fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
1635fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
1636fc01f7e7Sbellard {
16371c9805a3SStefan Hajnoczi     return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true);
163883f64091Sbellard }
163983f64091Sbellard 
1640eda578e5Saliguori int bdrv_pread(BlockDriverState *bs, int64_t offset,
1641eda578e5Saliguori                void *buf, int count1)
164283f64091Sbellard {
16436ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
164483f64091Sbellard     int len, nb_sectors, count;
164583f64091Sbellard     int64_t sector_num;
16469a8c4cceSKevin Wolf     int ret;
164783f64091Sbellard 
164883f64091Sbellard     count = count1;
164983f64091Sbellard     /* first read to align to sector start */
16506ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
165183f64091Sbellard     if (len > count)
165283f64091Sbellard         len = count;
16536ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
165483f64091Sbellard     if (len > 0) {
16559a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
16569a8c4cceSKevin Wolf             return ret;
16576ea44308SJan Kiszka         memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
165883f64091Sbellard         count -= len;
165983f64091Sbellard         if (count == 0)
166083f64091Sbellard             return count1;
166183f64091Sbellard         sector_num++;
166283f64091Sbellard         buf += len;
166383f64091Sbellard     }
166483f64091Sbellard 
166583f64091Sbellard     /* read the sectors "in place" */
16666ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
166783f64091Sbellard     if (nb_sectors > 0) {
16689a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
16699a8c4cceSKevin Wolf             return ret;
167083f64091Sbellard         sector_num += nb_sectors;
16716ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
167283f64091Sbellard         buf += len;
167383f64091Sbellard         count -= len;
167483f64091Sbellard     }
167583f64091Sbellard 
167683f64091Sbellard     /* add data from the last sector */
167783f64091Sbellard     if (count > 0) {
16789a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
16799a8c4cceSKevin Wolf             return ret;
168083f64091Sbellard         memcpy(buf, tmp_buf, count);
168183f64091Sbellard     }
168283f64091Sbellard     return count1;
168383f64091Sbellard }
168483f64091Sbellard 
1685eda578e5Saliguori int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1686eda578e5Saliguori                 const void *buf, int count1)
168783f64091Sbellard {
16886ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
168983f64091Sbellard     int len, nb_sectors, count;
169083f64091Sbellard     int64_t sector_num;
16919a8c4cceSKevin Wolf     int ret;
169283f64091Sbellard 
169383f64091Sbellard     count = count1;
169483f64091Sbellard     /* first write to align to sector start */
16956ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
169683f64091Sbellard     if (len > count)
169783f64091Sbellard         len = count;
16986ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
169983f64091Sbellard     if (len > 0) {
17009a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
17019a8c4cceSKevin Wolf             return ret;
17026ea44308SJan Kiszka         memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
17039a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
17049a8c4cceSKevin Wolf             return ret;
170583f64091Sbellard         count -= len;
170683f64091Sbellard         if (count == 0)
170783f64091Sbellard             return count1;
170883f64091Sbellard         sector_num++;
170983f64091Sbellard         buf += len;
171083f64091Sbellard     }
171183f64091Sbellard 
171283f64091Sbellard     /* write the sectors "in place" */
17136ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
171483f64091Sbellard     if (nb_sectors > 0) {
17159a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
17169a8c4cceSKevin Wolf             return ret;
171783f64091Sbellard         sector_num += nb_sectors;
17186ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
171983f64091Sbellard         buf += len;
172083f64091Sbellard         count -= len;
172183f64091Sbellard     }
172283f64091Sbellard 
172383f64091Sbellard     /* add data from the last sector */
172483f64091Sbellard     if (count > 0) {
17259a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
17269a8c4cceSKevin Wolf             return ret;
172783f64091Sbellard         memcpy(tmp_buf, buf, count);
17289a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
17299a8c4cceSKevin Wolf             return ret;
173083f64091Sbellard     }
173183f64091Sbellard     return count1;
173283f64091Sbellard }
173383f64091Sbellard 
1734f08145feSKevin Wolf /*
1735f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
1736f08145feSKevin Wolf  * request (acts as a barrier)
1737f08145feSKevin Wolf  *
1738f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
1739f08145feSKevin Wolf  */
1740f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1741f08145feSKevin Wolf     const void *buf, int count)
1742f08145feSKevin Wolf {
1743f08145feSKevin Wolf     int ret;
1744f08145feSKevin Wolf 
1745f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
1746f08145feSKevin Wolf     if (ret < 0) {
1747f08145feSKevin Wolf         return ret;
1748f08145feSKevin Wolf     }
1749f08145feSKevin Wolf 
175092196b2fSStefan Hajnoczi     /* No flush needed for cache modes that use O_DSYNC */
175192196b2fSStefan Hajnoczi     if ((bs->open_flags & BDRV_O_CACHE_WB) != 0) {
1752f08145feSKevin Wolf         bdrv_flush(bs);
1753f08145feSKevin Wolf     }
1754f08145feSKevin Wolf 
1755f08145feSKevin Wolf     return 0;
1756f08145feSKevin Wolf }
1757f08145feSKevin Wolf 
1758470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
1759ab185921SStefan Hajnoczi         int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
1760ab185921SStefan Hajnoczi {
1761ab185921SStefan Hajnoczi     /* Perform I/O through a temporary buffer so that users who scribble over
1762ab185921SStefan Hajnoczi      * their read buffer while the operation is in progress do not end up
1763ab185921SStefan Hajnoczi      * modifying the image file.  This is critical for zero-copy guest I/O
1764ab185921SStefan Hajnoczi      * where anything might happen inside guest memory.
1765ab185921SStefan Hajnoczi      */
1766ab185921SStefan Hajnoczi     void *bounce_buffer;
1767ab185921SStefan Hajnoczi 
176879c053bdSStefan Hajnoczi     BlockDriver *drv = bs->drv;
1769ab185921SStefan Hajnoczi     struct iovec iov;
1770ab185921SStefan Hajnoczi     QEMUIOVector bounce_qiov;
1771ab185921SStefan Hajnoczi     int64_t cluster_sector_num;
1772ab185921SStefan Hajnoczi     int cluster_nb_sectors;
1773ab185921SStefan Hajnoczi     size_t skip_bytes;
1774ab185921SStefan Hajnoczi     int ret;
1775ab185921SStefan Hajnoczi 
1776ab185921SStefan Hajnoczi     /* Cover entire cluster so no additional backing file I/O is required when
1777ab185921SStefan Hajnoczi      * allocating cluster in the image file.
1778ab185921SStefan Hajnoczi      */
1779ab185921SStefan Hajnoczi     round_to_clusters(bs, sector_num, nb_sectors,
1780ab185921SStefan Hajnoczi                       &cluster_sector_num, &cluster_nb_sectors);
1781ab185921SStefan Hajnoczi 
1782470c0504SStefan Hajnoczi     trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
1783ab185921SStefan Hajnoczi                                    cluster_sector_num, cluster_nb_sectors);
1784ab185921SStefan Hajnoczi 
1785ab185921SStefan Hajnoczi     iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
1786ab185921SStefan Hajnoczi     iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
1787ab185921SStefan Hajnoczi     qemu_iovec_init_external(&bounce_qiov, &iov, 1);
1788ab185921SStefan Hajnoczi 
178979c053bdSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
1790ab185921SStefan Hajnoczi                              &bounce_qiov);
1791ab185921SStefan Hajnoczi     if (ret < 0) {
1792ab185921SStefan Hajnoczi         goto err;
1793ab185921SStefan Hajnoczi     }
1794ab185921SStefan Hajnoczi 
179579c053bdSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes &&
179679c053bdSStefan Hajnoczi         buffer_is_zero(bounce_buffer, iov.iov_len)) {
1797621f0589SKevin Wolf         ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
179879c053bdSStefan Hajnoczi                                       cluster_nb_sectors);
179979c053bdSStefan Hajnoczi     } else {
180079c053bdSStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
1801ab185921SStefan Hajnoczi                                   &bounce_qiov);
180279c053bdSStefan Hajnoczi     }
180379c053bdSStefan Hajnoczi 
1804ab185921SStefan Hajnoczi     if (ret < 0) {
1805ab185921SStefan Hajnoczi         /* It might be okay to ignore write errors for guest requests.  If this
1806ab185921SStefan Hajnoczi          * is a deliberate copy-on-read then we don't want to ignore the error.
1807ab185921SStefan Hajnoczi          * Simply report it in all cases.
1808ab185921SStefan Hajnoczi          */
1809ab185921SStefan Hajnoczi         goto err;
1810ab185921SStefan Hajnoczi     }
1811ab185921SStefan Hajnoczi 
1812ab185921SStefan Hajnoczi     skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
1813ab185921SStefan Hajnoczi     qemu_iovec_from_buffer(qiov, bounce_buffer + skip_bytes,
1814ab185921SStefan Hajnoczi                            nb_sectors * BDRV_SECTOR_SIZE);
1815ab185921SStefan Hajnoczi 
1816ab185921SStefan Hajnoczi err:
1817ab185921SStefan Hajnoczi     qemu_vfree(bounce_buffer);
1818ab185921SStefan Hajnoczi     return ret;
1819ab185921SStefan Hajnoczi }
1820ab185921SStefan Hajnoczi 
1821c5fbe571SStefan Hajnoczi /*
1822c5fbe571SStefan Hajnoczi  * Handle a read request in coroutine context
1823c5fbe571SStefan Hajnoczi  */
1824c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
1825470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
1826470c0504SStefan Hajnoczi     BdrvRequestFlags flags)
1827da1fa91dSKevin Wolf {
1828da1fa91dSKevin Wolf     BlockDriver *drv = bs->drv;
1829dbffbdcfSStefan Hajnoczi     BdrvTrackedRequest req;
1830dbffbdcfSStefan Hajnoczi     int ret;
1831da1fa91dSKevin Wolf 
1832da1fa91dSKevin Wolf     if (!drv) {
1833da1fa91dSKevin Wolf         return -ENOMEDIUM;
1834da1fa91dSKevin Wolf     }
1835da1fa91dSKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1836da1fa91dSKevin Wolf         return -EIO;
1837da1fa91dSKevin Wolf     }
1838da1fa91dSKevin Wolf 
183998f90dbaSZhi Yong Wu     /* throttling disk read I/O */
184098f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
184198f90dbaSZhi Yong Wu         bdrv_io_limits_intercept(bs, false, nb_sectors);
184298f90dbaSZhi Yong Wu     }
184398f90dbaSZhi Yong Wu 
1844f4658285SStefan Hajnoczi     if (bs->copy_on_read) {
1845470c0504SStefan Hajnoczi         flags |= BDRV_REQ_COPY_ON_READ;
1846470c0504SStefan Hajnoczi     }
1847470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
1848470c0504SStefan Hajnoczi         bs->copy_on_read_in_flight++;
1849470c0504SStefan Hajnoczi     }
1850470c0504SStefan Hajnoczi 
1851470c0504SStefan Hajnoczi     if (bs->copy_on_read_in_flight) {
1852f4658285SStefan Hajnoczi         wait_for_overlapping_requests(bs, sector_num, nb_sectors);
1853f4658285SStefan Hajnoczi     }
1854f4658285SStefan Hajnoczi 
1855dbffbdcfSStefan Hajnoczi     tracked_request_begin(&req, bs, sector_num, nb_sectors, false);
1856ab185921SStefan Hajnoczi 
1857470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
1858ab185921SStefan Hajnoczi         int pnum;
1859ab185921SStefan Hajnoczi 
1860ab185921SStefan Hajnoczi         ret = bdrv_co_is_allocated(bs, sector_num, nb_sectors, &pnum);
1861ab185921SStefan Hajnoczi         if (ret < 0) {
1862ab185921SStefan Hajnoczi             goto out;
1863ab185921SStefan Hajnoczi         }
1864ab185921SStefan Hajnoczi 
1865ab185921SStefan Hajnoczi         if (!ret || pnum != nb_sectors) {
1866470c0504SStefan Hajnoczi             ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
1867ab185921SStefan Hajnoczi             goto out;
1868ab185921SStefan Hajnoczi         }
1869ab185921SStefan Hajnoczi     }
1870ab185921SStefan Hajnoczi 
1871dbffbdcfSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1872ab185921SStefan Hajnoczi 
1873ab185921SStefan Hajnoczi out:
1874dbffbdcfSStefan Hajnoczi     tracked_request_end(&req);
1875470c0504SStefan Hajnoczi 
1876470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
1877470c0504SStefan Hajnoczi         bs->copy_on_read_in_flight--;
1878470c0504SStefan Hajnoczi     }
1879470c0504SStefan Hajnoczi 
1880dbffbdcfSStefan Hajnoczi     return ret;
1881da1fa91dSKevin Wolf }
1882da1fa91dSKevin Wolf 
1883c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1884da1fa91dSKevin Wolf     int nb_sectors, QEMUIOVector *qiov)
1885da1fa91dSKevin Wolf {
1886c5fbe571SStefan Hajnoczi     trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1887da1fa91dSKevin Wolf 
1888470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
1889470c0504SStefan Hajnoczi }
1890470c0504SStefan Hajnoczi 
1891470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
1892470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
1893470c0504SStefan Hajnoczi {
1894470c0504SStefan Hajnoczi     trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
1895470c0504SStefan Hajnoczi 
1896470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
1897470c0504SStefan Hajnoczi                             BDRV_REQ_COPY_ON_READ);
1898c5fbe571SStefan Hajnoczi }
1899c5fbe571SStefan Hajnoczi 
1900f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
1901f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors)
1902f08f2ddaSStefan Hajnoczi {
1903f08f2ddaSStefan Hajnoczi     BlockDriver *drv = bs->drv;
1904f08f2ddaSStefan Hajnoczi     QEMUIOVector qiov;
1905f08f2ddaSStefan Hajnoczi     struct iovec iov;
1906f08f2ddaSStefan Hajnoczi     int ret;
1907f08f2ddaSStefan Hajnoczi 
1908621f0589SKevin Wolf     /* TODO Emulate only part of misaligned requests instead of letting block
1909621f0589SKevin Wolf      * drivers return -ENOTSUP and emulate everything */
1910621f0589SKevin Wolf 
1911f08f2ddaSStefan Hajnoczi     /* First try the efficient write zeroes operation */
1912f08f2ddaSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes) {
1913621f0589SKevin Wolf         ret = drv->bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
1914621f0589SKevin Wolf         if (ret != -ENOTSUP) {
1915621f0589SKevin Wolf             return ret;
1916621f0589SKevin Wolf         }
1917f08f2ddaSStefan Hajnoczi     }
1918f08f2ddaSStefan Hajnoczi 
1919f08f2ddaSStefan Hajnoczi     /* Fall back to bounce buffer if write zeroes is unsupported */
1920f08f2ddaSStefan Hajnoczi     iov.iov_len  = nb_sectors * BDRV_SECTOR_SIZE;
1921f08f2ddaSStefan Hajnoczi     iov.iov_base = qemu_blockalign(bs, iov.iov_len);
1922f08f2ddaSStefan Hajnoczi     memset(iov.iov_base, 0, iov.iov_len);
1923f08f2ddaSStefan Hajnoczi     qemu_iovec_init_external(&qiov, &iov, 1);
1924f08f2ddaSStefan Hajnoczi 
1925f08f2ddaSStefan Hajnoczi     ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
1926f08f2ddaSStefan Hajnoczi 
1927f08f2ddaSStefan Hajnoczi     qemu_vfree(iov.iov_base);
1928f08f2ddaSStefan Hajnoczi     return ret;
1929f08f2ddaSStefan Hajnoczi }
1930f08f2ddaSStefan Hajnoczi 
1931c5fbe571SStefan Hajnoczi /*
1932c5fbe571SStefan Hajnoczi  * Handle a write request in coroutine context
1933c5fbe571SStefan Hajnoczi  */
1934c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
1935f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
1936f08f2ddaSStefan Hajnoczi     BdrvRequestFlags flags)
1937c5fbe571SStefan Hajnoczi {
1938c5fbe571SStefan Hajnoczi     BlockDriver *drv = bs->drv;
1939dbffbdcfSStefan Hajnoczi     BdrvTrackedRequest req;
19406b7cb247SStefan Hajnoczi     int ret;
1941da1fa91dSKevin Wolf 
1942da1fa91dSKevin Wolf     if (!bs->drv) {
1943da1fa91dSKevin Wolf         return -ENOMEDIUM;
1944da1fa91dSKevin Wolf     }
1945da1fa91dSKevin Wolf     if (bs->read_only) {
1946da1fa91dSKevin Wolf         return -EACCES;
1947da1fa91dSKevin Wolf     }
1948da1fa91dSKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1949da1fa91dSKevin Wolf         return -EIO;
1950da1fa91dSKevin Wolf     }
1951da1fa91dSKevin Wolf 
195298f90dbaSZhi Yong Wu     /* throttling disk write I/O */
195398f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
195498f90dbaSZhi Yong Wu         bdrv_io_limits_intercept(bs, true, nb_sectors);
195598f90dbaSZhi Yong Wu     }
195698f90dbaSZhi Yong Wu 
1957470c0504SStefan Hajnoczi     if (bs->copy_on_read_in_flight) {
1958f4658285SStefan Hajnoczi         wait_for_overlapping_requests(bs, sector_num, nb_sectors);
1959f4658285SStefan Hajnoczi     }
1960f4658285SStefan Hajnoczi 
1961dbffbdcfSStefan Hajnoczi     tracked_request_begin(&req, bs, sector_num, nb_sectors, true);
1962dbffbdcfSStefan Hajnoczi 
1963f08f2ddaSStefan Hajnoczi     if (flags & BDRV_REQ_ZERO_WRITE) {
1964f08f2ddaSStefan Hajnoczi         ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors);
1965f08f2ddaSStefan Hajnoczi     } else {
19666b7cb247SStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
1967f08f2ddaSStefan Hajnoczi     }
19686b7cb247SStefan Hajnoczi 
1969da1fa91dSKevin Wolf     if (bs->dirty_bitmap) {
1970da1fa91dSKevin Wolf         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1971da1fa91dSKevin Wolf     }
1972da1fa91dSKevin Wolf 
1973da1fa91dSKevin Wolf     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1974da1fa91dSKevin Wolf         bs->wr_highest_sector = sector_num + nb_sectors - 1;
1975da1fa91dSKevin Wolf     }
1976da1fa91dSKevin Wolf 
1977dbffbdcfSStefan Hajnoczi     tracked_request_end(&req);
1978dbffbdcfSStefan Hajnoczi 
19796b7cb247SStefan Hajnoczi     return ret;
1980da1fa91dSKevin Wolf }
1981da1fa91dSKevin Wolf 
1982c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1983c5fbe571SStefan Hajnoczi     int nb_sectors, QEMUIOVector *qiov)
1984c5fbe571SStefan Hajnoczi {
1985c5fbe571SStefan Hajnoczi     trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1986c5fbe571SStefan Hajnoczi 
1987f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
1988f08f2ddaSStefan Hajnoczi }
1989f08f2ddaSStefan Hajnoczi 
1990f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
1991f08f2ddaSStefan Hajnoczi                                       int64_t sector_num, int nb_sectors)
1992f08f2ddaSStefan Hajnoczi {
1993f08f2ddaSStefan Hajnoczi     trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
1994f08f2ddaSStefan Hajnoczi 
1995f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
1996f08f2ddaSStefan Hajnoczi                              BDRV_REQ_ZERO_WRITE);
1997c5fbe571SStefan Hajnoczi }
1998c5fbe571SStefan Hajnoczi 
199983f64091Sbellard /**
200083f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
200183f64091Sbellard  */
200283f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
200383f64091Sbellard {
200483f64091Sbellard     BlockDriver *drv = bs->drv;
200551762288SStefan Hajnoczi     int ret;
200683f64091Sbellard     if (!drv)
200719cb3738Sbellard         return -ENOMEDIUM;
200883f64091Sbellard     if (!drv->bdrv_truncate)
200983f64091Sbellard         return -ENOTSUP;
201059f2689dSNaphtali Sprei     if (bs->read_only)
201159f2689dSNaphtali Sprei         return -EACCES;
20128591675fSMarcelo Tosatti     if (bdrv_in_use(bs))
20138591675fSMarcelo Tosatti         return -EBUSY;
201451762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
201551762288SStefan Hajnoczi     if (ret == 0) {
201651762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2017145feb17SMarkus Armbruster         bdrv_dev_resize_cb(bs);
201851762288SStefan Hajnoczi     }
201951762288SStefan Hajnoczi     return ret;
202083f64091Sbellard }
202183f64091Sbellard 
202283f64091Sbellard /**
20234a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
20244a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
20254a1d5e1fSFam Zheng  */
20264a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
20274a1d5e1fSFam Zheng {
20284a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
20294a1d5e1fSFam Zheng     if (!drv) {
20304a1d5e1fSFam Zheng         return -ENOMEDIUM;
20314a1d5e1fSFam Zheng     }
20324a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
20334a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
20344a1d5e1fSFam Zheng     }
20354a1d5e1fSFam Zheng     if (bs->file) {
20364a1d5e1fSFam Zheng         return bdrv_get_allocated_file_size(bs->file);
20374a1d5e1fSFam Zheng     }
20384a1d5e1fSFam Zheng     return -ENOTSUP;
20394a1d5e1fSFam Zheng }
20404a1d5e1fSFam Zheng 
20414a1d5e1fSFam Zheng /**
204283f64091Sbellard  * Length of a file in bytes. Return < 0 if error or unknown.
204383f64091Sbellard  */
204483f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs)
204583f64091Sbellard {
204683f64091Sbellard     BlockDriver *drv = bs->drv;
204783f64091Sbellard     if (!drv)
204819cb3738Sbellard         return -ENOMEDIUM;
204951762288SStefan Hajnoczi 
20502c6942faSMarkus Armbruster     if (bs->growable || bdrv_dev_has_removable_media(bs)) {
205146a4e4e6SStefan Hajnoczi         if (drv->bdrv_getlength) {
205283f64091Sbellard             return drv->bdrv_getlength(bs);
2053fc01f7e7Sbellard         }
205446a4e4e6SStefan Hajnoczi     }
205546a4e4e6SStefan Hajnoczi     return bs->total_sectors * BDRV_SECTOR_SIZE;
205646a4e4e6SStefan Hajnoczi }
2057fc01f7e7Sbellard 
205819cb3738Sbellard /* return 0 as number of sectors if no device present or error */
205996b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2060fc01f7e7Sbellard {
206119cb3738Sbellard     int64_t length;
206219cb3738Sbellard     length = bdrv_getlength(bs);
206319cb3738Sbellard     if (length < 0)
206419cb3738Sbellard         length = 0;
206519cb3738Sbellard     else
20666ea44308SJan Kiszka         length = length >> BDRV_SECTOR_BITS;
206719cb3738Sbellard     *nb_sectors_ptr = length;
2068fc01f7e7Sbellard }
2069cf98951bSbellard 
2070f3d54fc4Saliguori struct partition {
2071f3d54fc4Saliguori         uint8_t boot_ind;           /* 0x80 - active */
2072f3d54fc4Saliguori         uint8_t head;               /* starting head */
2073f3d54fc4Saliguori         uint8_t sector;             /* starting sector */
2074f3d54fc4Saliguori         uint8_t cyl;                /* starting cylinder */
2075f3d54fc4Saliguori         uint8_t sys_ind;            /* What partition type */
2076f3d54fc4Saliguori         uint8_t end_head;           /* end head */
2077f3d54fc4Saliguori         uint8_t end_sector;         /* end sector */
2078f3d54fc4Saliguori         uint8_t end_cyl;            /* end cylinder */
2079f3d54fc4Saliguori         uint32_t start_sect;        /* starting sector counting from 0 */
2080f3d54fc4Saliguori         uint32_t nr_sects;          /* nr of sectors in partition */
2081541dc0d4SStefan Weil } QEMU_PACKED;
2082f3d54fc4Saliguori 
2083f3d54fc4Saliguori /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
2084f3d54fc4Saliguori static int guess_disk_lchs(BlockDriverState *bs,
2085f3d54fc4Saliguori                            int *pcylinders, int *pheads, int *psectors)
2086f3d54fc4Saliguori {
2087eb5a3165SJes Sorensen     uint8_t buf[BDRV_SECTOR_SIZE];
2088f3d54fc4Saliguori     int ret, i, heads, sectors, cylinders;
2089f3d54fc4Saliguori     struct partition *p;
2090f3d54fc4Saliguori     uint32_t nr_sects;
2091a38131b6Sblueswir1     uint64_t nb_sectors;
2092498e386cSZhi Yong Wu     bool enabled;
2093f3d54fc4Saliguori 
2094f3d54fc4Saliguori     bdrv_get_geometry(bs, &nb_sectors);
2095f3d54fc4Saliguori 
2096498e386cSZhi Yong Wu     /**
2097498e386cSZhi Yong Wu      * The function will be invoked during startup not only in sync I/O mode,
2098498e386cSZhi Yong Wu      * but also in async I/O mode. So the I/O throttling function has to
2099498e386cSZhi Yong Wu      * be disabled temporarily here, not permanently.
2100498e386cSZhi Yong Wu      */
2101498e386cSZhi Yong Wu     enabled = bs->io_limits_enabled;
2102498e386cSZhi Yong Wu     bs->io_limits_enabled = false;
2103f3d54fc4Saliguori     ret = bdrv_read(bs, 0, buf, 1);
2104498e386cSZhi Yong Wu     bs->io_limits_enabled = enabled;
2105f3d54fc4Saliguori     if (ret < 0)
2106f3d54fc4Saliguori         return -1;
2107f3d54fc4Saliguori     /* test msdos magic */
2108f3d54fc4Saliguori     if (buf[510] != 0x55 || buf[511] != 0xaa)
2109f3d54fc4Saliguori         return -1;
2110f3d54fc4Saliguori     for(i = 0; i < 4; i++) {
2111f3d54fc4Saliguori         p = ((struct partition *)(buf + 0x1be)) + i;
2112f3d54fc4Saliguori         nr_sects = le32_to_cpu(p->nr_sects);
2113f3d54fc4Saliguori         if (nr_sects && p->end_head) {
2114f3d54fc4Saliguori             /* We make the assumption that the partition terminates on
2115f3d54fc4Saliguori                a cylinder boundary */
2116f3d54fc4Saliguori             heads = p->end_head + 1;
2117f3d54fc4Saliguori             sectors = p->end_sector & 63;
2118f3d54fc4Saliguori             if (sectors == 0)
2119f3d54fc4Saliguori                 continue;
2120f3d54fc4Saliguori             cylinders = nb_sectors / (heads * sectors);
2121f3d54fc4Saliguori             if (cylinders < 1 || cylinders > 16383)
2122f3d54fc4Saliguori                 continue;
2123f3d54fc4Saliguori             *pheads = heads;
2124f3d54fc4Saliguori             *psectors = sectors;
2125f3d54fc4Saliguori             *pcylinders = cylinders;
2126f3d54fc4Saliguori #if 0
2127f3d54fc4Saliguori             printf("guessed geometry: LCHS=%d %d %d\n",
2128f3d54fc4Saliguori                    cylinders, heads, sectors);
2129f3d54fc4Saliguori #endif
2130f3d54fc4Saliguori             return 0;
2131f3d54fc4Saliguori         }
2132f3d54fc4Saliguori     }
2133f3d54fc4Saliguori     return -1;
2134f3d54fc4Saliguori }
2135f3d54fc4Saliguori 
2136f3d54fc4Saliguori void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
2137f3d54fc4Saliguori {
2138f3d54fc4Saliguori     int translation, lba_detected = 0;
2139f3d54fc4Saliguori     int cylinders, heads, secs;
2140a38131b6Sblueswir1     uint64_t nb_sectors;
2141f3d54fc4Saliguori 
2142f3d54fc4Saliguori     /* if a geometry hint is available, use it */
2143f3d54fc4Saliguori     bdrv_get_geometry(bs, &nb_sectors);
2144f3d54fc4Saliguori     bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
2145f3d54fc4Saliguori     translation = bdrv_get_translation_hint(bs);
2146f3d54fc4Saliguori     if (cylinders != 0) {
2147f3d54fc4Saliguori         *pcyls = cylinders;
2148f3d54fc4Saliguori         *pheads = heads;
2149f3d54fc4Saliguori         *psecs = secs;
2150f3d54fc4Saliguori     } else {
2151f3d54fc4Saliguori         if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
2152f3d54fc4Saliguori             if (heads > 16) {
2153f3d54fc4Saliguori                 /* if heads > 16, it means that a BIOS LBA
2154f3d54fc4Saliguori                    translation was active, so the default
2155f3d54fc4Saliguori                    hardware geometry is OK */
2156f3d54fc4Saliguori                 lba_detected = 1;
2157f3d54fc4Saliguori                 goto default_geometry;
2158f3d54fc4Saliguori             } else {
2159f3d54fc4Saliguori                 *pcyls = cylinders;
2160f3d54fc4Saliguori                 *pheads = heads;
2161f3d54fc4Saliguori                 *psecs = secs;
2162f3d54fc4Saliguori                 /* disable any translation to be in sync with
2163f3d54fc4Saliguori                    the logical geometry */
2164f3d54fc4Saliguori                 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
2165f3d54fc4Saliguori                     bdrv_set_translation_hint(bs,
2166f3d54fc4Saliguori                                               BIOS_ATA_TRANSLATION_NONE);
2167f3d54fc4Saliguori                 }
2168f3d54fc4Saliguori             }
2169f3d54fc4Saliguori         } else {
2170f3d54fc4Saliguori         default_geometry:
2171f3d54fc4Saliguori             /* if no geometry, use a standard physical disk geometry */
2172f3d54fc4Saliguori             cylinders = nb_sectors / (16 * 63);
2173f3d54fc4Saliguori 
2174f3d54fc4Saliguori             if (cylinders > 16383)
2175f3d54fc4Saliguori                 cylinders = 16383;
2176f3d54fc4Saliguori             else if (cylinders < 2)
2177f3d54fc4Saliguori                 cylinders = 2;
2178f3d54fc4Saliguori             *pcyls = cylinders;
2179f3d54fc4Saliguori             *pheads = 16;
2180f3d54fc4Saliguori             *psecs = 63;
2181f3d54fc4Saliguori             if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
2182f3d54fc4Saliguori                 if ((*pcyls * *pheads) <= 131072) {
2183f3d54fc4Saliguori                     bdrv_set_translation_hint(bs,
2184f3d54fc4Saliguori                                               BIOS_ATA_TRANSLATION_LARGE);
2185f3d54fc4Saliguori                 } else {
2186f3d54fc4Saliguori                     bdrv_set_translation_hint(bs,
2187f3d54fc4Saliguori                                               BIOS_ATA_TRANSLATION_LBA);
2188f3d54fc4Saliguori                 }
2189f3d54fc4Saliguori             }
2190f3d54fc4Saliguori         }
2191f3d54fc4Saliguori         bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
2192f3d54fc4Saliguori     }
2193f3d54fc4Saliguori }
2194f3d54fc4Saliguori 
2195b338082bSbellard void bdrv_set_geometry_hint(BlockDriverState *bs,
2196b338082bSbellard                             int cyls, int heads, int secs)
2197b338082bSbellard {
2198b338082bSbellard     bs->cyls = cyls;
2199b338082bSbellard     bs->heads = heads;
2200b338082bSbellard     bs->secs = secs;
2201b338082bSbellard }
2202b338082bSbellard 
220346d4767dSbellard void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
220446d4767dSbellard {
220546d4767dSbellard     bs->translation = translation;
220646d4767dSbellard }
220746d4767dSbellard 
2208b338082bSbellard void bdrv_get_geometry_hint(BlockDriverState *bs,
2209b338082bSbellard                             int *pcyls, int *pheads, int *psecs)
2210b338082bSbellard {
2211b338082bSbellard     *pcyls = bs->cyls;
2212b338082bSbellard     *pheads = bs->heads;
2213b338082bSbellard     *psecs = bs->secs;
2214b338082bSbellard }
2215b338082bSbellard 
22160563e191SZhi Yong Wu /* throttling disk io limits */
22170563e191SZhi Yong Wu void bdrv_set_io_limits(BlockDriverState *bs,
22180563e191SZhi Yong Wu                         BlockIOLimit *io_limits)
22190563e191SZhi Yong Wu {
22200563e191SZhi Yong Wu     bs->io_limits = *io_limits;
22210563e191SZhi Yong Wu     bs->io_limits_enabled = bdrv_io_limits_enabled(bs);
22220563e191SZhi Yong Wu }
22230563e191SZhi Yong Wu 
22245bbdbb46SBlue Swirl /* Recognize floppy formats */
22255bbdbb46SBlue Swirl typedef struct FDFormat {
22265bbdbb46SBlue Swirl     FDriveType drive;
22275bbdbb46SBlue Swirl     uint8_t last_sect;
22285bbdbb46SBlue Swirl     uint8_t max_track;
22295bbdbb46SBlue Swirl     uint8_t max_head;
2230f8d3d128SHervé Poussineau     FDriveRate rate;
22315bbdbb46SBlue Swirl } FDFormat;
22325bbdbb46SBlue Swirl 
22335bbdbb46SBlue Swirl static const FDFormat fd_formats[] = {
22345bbdbb46SBlue Swirl     /* First entry is default format */
22355bbdbb46SBlue Swirl     /* 1.44 MB 3"1/2 floppy disks */
2236f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 18, 80, 1, FDRIVE_RATE_500K, },
2237f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 20, 80, 1, FDRIVE_RATE_500K, },
2238f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 21, 80, 1, FDRIVE_RATE_500K, },
2239f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 21, 82, 1, FDRIVE_RATE_500K, },
2240f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 21, 83, 1, FDRIVE_RATE_500K, },
2241f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 22, 80, 1, FDRIVE_RATE_500K, },
2242f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 23, 80, 1, FDRIVE_RATE_500K, },
2243f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 24, 80, 1, FDRIVE_RATE_500K, },
22445bbdbb46SBlue Swirl     /* 2.88 MB 3"1/2 floppy disks */
2245f8d3d128SHervé Poussineau     { FDRIVE_DRV_288, 36, 80, 1, FDRIVE_RATE_1M, },
2246f8d3d128SHervé Poussineau     { FDRIVE_DRV_288, 39, 80, 1, FDRIVE_RATE_1M, },
2247f8d3d128SHervé Poussineau     { FDRIVE_DRV_288, 40, 80, 1, FDRIVE_RATE_1M, },
2248f8d3d128SHervé Poussineau     { FDRIVE_DRV_288, 44, 80, 1, FDRIVE_RATE_1M, },
2249f8d3d128SHervé Poussineau     { FDRIVE_DRV_288, 48, 80, 1, FDRIVE_RATE_1M, },
22505bbdbb46SBlue Swirl     /* 720 kB 3"1/2 floppy disks */
2251f8d3d128SHervé Poussineau     { FDRIVE_DRV_144,  9, 80, 1, FDRIVE_RATE_250K, },
2252f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 10, 80, 1, FDRIVE_RATE_250K, },
2253f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 10, 82, 1, FDRIVE_RATE_250K, },
2254f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 10, 83, 1, FDRIVE_RATE_250K, },
2255f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 13, 80, 1, FDRIVE_RATE_250K, },
2256f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 14, 80, 1, FDRIVE_RATE_250K, },
22575bbdbb46SBlue Swirl     /* 1.2 MB 5"1/4 floppy disks */
2258f8d3d128SHervé Poussineau     { FDRIVE_DRV_120, 15, 80, 1, FDRIVE_RATE_500K, },
2259f8d3d128SHervé Poussineau     { FDRIVE_DRV_120, 18, 80, 1, FDRIVE_RATE_500K, },
2260f8d3d128SHervé Poussineau     { FDRIVE_DRV_120, 18, 82, 1, FDRIVE_RATE_500K, },
2261f8d3d128SHervé Poussineau     { FDRIVE_DRV_120, 18, 83, 1, FDRIVE_RATE_500K, },
2262f8d3d128SHervé Poussineau     { FDRIVE_DRV_120, 20, 80, 1, FDRIVE_RATE_500K, },
22635bbdbb46SBlue Swirl     /* 720 kB 5"1/4 floppy disks */
2264f8d3d128SHervé Poussineau     { FDRIVE_DRV_120,  9, 80, 1, FDRIVE_RATE_250K, },
2265f8d3d128SHervé Poussineau     { FDRIVE_DRV_120, 11, 80, 1, FDRIVE_RATE_250K, },
22665bbdbb46SBlue Swirl     /* 360 kB 5"1/4 floppy disks */
2267f8d3d128SHervé Poussineau     { FDRIVE_DRV_120,  9, 40, 1, FDRIVE_RATE_300K, },
2268f8d3d128SHervé Poussineau     { FDRIVE_DRV_120,  9, 40, 0, FDRIVE_RATE_300K, },
2269f8d3d128SHervé Poussineau     { FDRIVE_DRV_120, 10, 41, 1, FDRIVE_RATE_300K, },
2270f8d3d128SHervé Poussineau     { FDRIVE_DRV_120, 10, 42, 1, FDRIVE_RATE_300K, },
22715bbdbb46SBlue Swirl     /* 320 kB 5"1/4 floppy disks */
2272f8d3d128SHervé Poussineau     { FDRIVE_DRV_120,  8, 40, 1, FDRIVE_RATE_250K, },
2273f8d3d128SHervé Poussineau     { FDRIVE_DRV_120,  8, 40, 0, FDRIVE_RATE_250K, },
22745bbdbb46SBlue Swirl     /* 360 kB must match 5"1/4 better than 3"1/2... */
2275f8d3d128SHervé Poussineau     { FDRIVE_DRV_144,  9, 80, 0, FDRIVE_RATE_250K, },
22765bbdbb46SBlue Swirl     /* end */
2277f8d3d128SHervé Poussineau     { FDRIVE_DRV_NONE, -1, -1, 0, 0, },
22785bbdbb46SBlue Swirl };
22795bbdbb46SBlue Swirl 
22805bbdbb46SBlue Swirl void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
22815bbdbb46SBlue Swirl                                    int *max_track, int *last_sect,
2282f8d3d128SHervé Poussineau                                    FDriveType drive_in, FDriveType *drive,
2283f8d3d128SHervé Poussineau                                    FDriveRate *rate)
22845bbdbb46SBlue Swirl {
22855bbdbb46SBlue Swirl     const FDFormat *parse;
22865bbdbb46SBlue Swirl     uint64_t nb_sectors, size;
22875bbdbb46SBlue Swirl     int i, first_match, match;
22885bbdbb46SBlue Swirl 
22895bbdbb46SBlue Swirl     bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
22905bbdbb46SBlue Swirl     if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
22915bbdbb46SBlue Swirl         /* User defined disk */
2292f8d3d128SHervé Poussineau         *rate = FDRIVE_RATE_500K;
22935bbdbb46SBlue Swirl     } else {
22945bbdbb46SBlue Swirl         bdrv_get_geometry(bs, &nb_sectors);
22955bbdbb46SBlue Swirl         match = -1;
22965bbdbb46SBlue Swirl         first_match = -1;
22975bbdbb46SBlue Swirl         for (i = 0; ; i++) {
22985bbdbb46SBlue Swirl             parse = &fd_formats[i];
22995bbdbb46SBlue Swirl             if (parse->drive == FDRIVE_DRV_NONE) {
23005bbdbb46SBlue Swirl                 break;
23015bbdbb46SBlue Swirl             }
23025bbdbb46SBlue Swirl             if (drive_in == parse->drive ||
23035bbdbb46SBlue Swirl                 drive_in == FDRIVE_DRV_NONE) {
23045bbdbb46SBlue Swirl                 size = (parse->max_head + 1) * parse->max_track *
23055bbdbb46SBlue Swirl                     parse->last_sect;
23065bbdbb46SBlue Swirl                 if (nb_sectors == size) {
23075bbdbb46SBlue Swirl                     match = i;
23085bbdbb46SBlue Swirl                     break;
23095bbdbb46SBlue Swirl                 }
23105bbdbb46SBlue Swirl                 if (first_match == -1) {
23115bbdbb46SBlue Swirl                     first_match = i;
23125bbdbb46SBlue Swirl                 }
23135bbdbb46SBlue Swirl             }
23145bbdbb46SBlue Swirl         }
23155bbdbb46SBlue Swirl         if (match == -1) {
23165bbdbb46SBlue Swirl             if (first_match == -1) {
23175bbdbb46SBlue Swirl                 match = 1;
23185bbdbb46SBlue Swirl             } else {
23195bbdbb46SBlue Swirl                 match = first_match;
23205bbdbb46SBlue Swirl             }
23215bbdbb46SBlue Swirl             parse = &fd_formats[match];
23225bbdbb46SBlue Swirl         }
23235bbdbb46SBlue Swirl         *nb_heads = parse->max_head + 1;
23245bbdbb46SBlue Swirl         *max_track = parse->max_track;
23255bbdbb46SBlue Swirl         *last_sect = parse->last_sect;
23265bbdbb46SBlue Swirl         *drive = parse->drive;
2327f8d3d128SHervé Poussineau         *rate = parse->rate;
23285bbdbb46SBlue Swirl     }
23295bbdbb46SBlue Swirl }
23305bbdbb46SBlue Swirl 
233146d4767dSbellard int bdrv_get_translation_hint(BlockDriverState *bs)
233246d4767dSbellard {
233346d4767dSbellard     return bs->translation;
233446d4767dSbellard }
233546d4767dSbellard 
2336abd7f68dSMarkus Armbruster void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
2337abd7f68dSMarkus Armbruster                        BlockErrorAction on_write_error)
2338abd7f68dSMarkus Armbruster {
2339abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
2340abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
2341abd7f68dSMarkus Armbruster }
2342abd7f68dSMarkus Armbruster 
2343abd7f68dSMarkus Armbruster BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
2344abd7f68dSMarkus Armbruster {
2345abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
2346abd7f68dSMarkus Armbruster }
2347abd7f68dSMarkus Armbruster 
2348b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2349b338082bSbellard {
2350b338082bSbellard     return bs->read_only;
2351b338082bSbellard }
2352b338082bSbellard 
2353985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2354985a03b0Sths {
2355985a03b0Sths     return bs->sg;
2356985a03b0Sths }
2357985a03b0Sths 
2358e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
2359e900a7b7SChristoph Hellwig {
2360e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
2361e900a7b7SChristoph Hellwig }
2362e900a7b7SChristoph Hellwig 
2363ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2364ea2384d3Sbellard {
2365ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
2366ea2384d3Sbellard         return 1;
2367ea2384d3Sbellard     return bs->encrypted;
2368ea2384d3Sbellard }
2369ea2384d3Sbellard 
2370c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2371c0f4ce77Saliguori {
2372c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
2373c0f4ce77Saliguori 
2374c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
2375c0f4ce77Saliguori         return 1;
2376c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2377c0f4ce77Saliguori }
2378c0f4ce77Saliguori 
2379ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2380ea2384d3Sbellard {
2381ea2384d3Sbellard     int ret;
2382ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
2383ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
2384ea2384d3Sbellard         if (ret < 0)
2385ea2384d3Sbellard             return ret;
2386ea2384d3Sbellard         if (!bs->encrypted)
2387ea2384d3Sbellard             return 0;
2388ea2384d3Sbellard     }
2389fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2390fd04a2aeSShahar Havivi         return -EINVAL;
2391fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2392fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2393fd04a2aeSShahar Havivi     }
2394c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2395bb5fc20fSaliguori     if (ret < 0) {
2396bb5fc20fSaliguori         bs->valid_key = 0;
2397bb5fc20fSaliguori     } else if (!bs->valid_key) {
2398bb5fc20fSaliguori         bs->valid_key = 1;
2399bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
24007d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
2401bb5fc20fSaliguori     }
2402c0f4ce77Saliguori     return ret;
2403ea2384d3Sbellard }
2404ea2384d3Sbellard 
2405ea2384d3Sbellard void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
2406ea2384d3Sbellard {
240719cb3738Sbellard     if (!bs->drv) {
2408ea2384d3Sbellard         buf[0] = '\0';
2409ea2384d3Sbellard     } else {
2410ea2384d3Sbellard         pstrcpy(buf, buf_size, bs->drv->format_name);
2411ea2384d3Sbellard     }
2412ea2384d3Sbellard }
2413ea2384d3Sbellard 
2414ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2415ea2384d3Sbellard                          void *opaque)
2416ea2384d3Sbellard {
2417ea2384d3Sbellard     BlockDriver *drv;
2418ea2384d3Sbellard 
24198a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2420ea2384d3Sbellard         it(opaque, drv->format_name);
2421ea2384d3Sbellard     }
2422ea2384d3Sbellard }
2423ea2384d3Sbellard 
2424b338082bSbellard BlockDriverState *bdrv_find(const char *name)
2425b338082bSbellard {
2426b338082bSbellard     BlockDriverState *bs;
2427b338082bSbellard 
24281b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
24291b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
2430b338082bSbellard             return bs;
2431b338082bSbellard         }
24321b7bdbc1SStefan Hajnoczi     }
2433b338082bSbellard     return NULL;
2434b338082bSbellard }
2435b338082bSbellard 
24362f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
24372f399b0aSMarkus Armbruster {
24382f399b0aSMarkus Armbruster     if (!bs) {
24392f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
24402f399b0aSMarkus Armbruster     }
24412f399b0aSMarkus Armbruster     return QTAILQ_NEXT(bs, list);
24422f399b0aSMarkus Armbruster }
24432f399b0aSMarkus Armbruster 
244451de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
244581d0912dSbellard {
244681d0912dSbellard     BlockDriverState *bs;
244781d0912dSbellard 
24481b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
244951de9760Saliguori         it(opaque, bs);
245081d0912dSbellard     }
245181d0912dSbellard }
245281d0912dSbellard 
2453ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
2454ea2384d3Sbellard {
2455ea2384d3Sbellard     return bs->device_name;
2456ea2384d3Sbellard }
2457ea2384d3Sbellard 
2458c6ca28d6Saliguori void bdrv_flush_all(void)
2459c6ca28d6Saliguori {
2460c6ca28d6Saliguori     BlockDriverState *bs;
2461c6ca28d6Saliguori 
24621b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
2463c6ca28d6Saliguori         bdrv_flush(bs);
2464c6ca28d6Saliguori     }
24651b7bdbc1SStefan Hajnoczi }
2466c6ca28d6Saliguori 
2467f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
2468f2feebbdSKevin Wolf {
2469f2feebbdSKevin Wolf     assert(bs->drv);
2470f2feebbdSKevin Wolf 
2471336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
2472336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
2473f2feebbdSKevin Wolf     }
2474f2feebbdSKevin Wolf 
2475f2feebbdSKevin Wolf     return 1;
2476f2feebbdSKevin Wolf }
2477f2feebbdSKevin Wolf 
2478376ae3f1SStefan Hajnoczi typedef struct BdrvCoIsAllocatedData {
2479376ae3f1SStefan Hajnoczi     BlockDriverState *bs;
2480376ae3f1SStefan Hajnoczi     int64_t sector_num;
2481376ae3f1SStefan Hajnoczi     int nb_sectors;
2482376ae3f1SStefan Hajnoczi     int *pnum;
2483376ae3f1SStefan Hajnoczi     int ret;
2484376ae3f1SStefan Hajnoczi     bool done;
2485376ae3f1SStefan Hajnoczi } BdrvCoIsAllocatedData;
2486376ae3f1SStefan Hajnoczi 
2487f58c7b35Sths /*
2488f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
2489f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
2490f58c7b35Sths  * hence all their sectors are reported as allocated.
2491f58c7b35Sths  *
2492bd9533e3SStefan Hajnoczi  * If 'sector_num' is beyond the end of the disk image the return value is 0
2493bd9533e3SStefan Hajnoczi  * and 'pnum' is set to 0.
2494bd9533e3SStefan Hajnoczi  *
2495f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
2496f58c7b35Sths  * the specified sector) that are known to be in the same
2497f58c7b35Sths  * allocated/unallocated state.
2498f58c7b35Sths  *
2499bd9533e3SStefan Hajnoczi  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
2500bd9533e3SStefan Hajnoczi  * beyond the end of the disk image it will be clamped.
2501f58c7b35Sths  */
2502060f51c9SStefan Hajnoczi int coroutine_fn bdrv_co_is_allocated(BlockDriverState *bs, int64_t sector_num,
2503060f51c9SStefan Hajnoczi                                       int nb_sectors, int *pnum)
2504f58c7b35Sths {
2505f58c7b35Sths     int64_t n;
2506bd9533e3SStefan Hajnoczi 
25076aebab14SStefan Hajnoczi     if (sector_num >= bs->total_sectors) {
25086aebab14SStefan Hajnoczi         *pnum = 0;
25096aebab14SStefan Hajnoczi         return 0;
25106aebab14SStefan Hajnoczi     }
2511bd9533e3SStefan Hajnoczi 
25126aebab14SStefan Hajnoczi     n = bs->total_sectors - sector_num;
2513bd9533e3SStefan Hajnoczi     if (n < nb_sectors) {
2514bd9533e3SStefan Hajnoczi         nb_sectors = n;
2515bd9533e3SStefan Hajnoczi     }
2516bd9533e3SStefan Hajnoczi 
2517bd9533e3SStefan Hajnoczi     if (!bs->drv->bdrv_co_is_allocated) {
2518bd9533e3SStefan Hajnoczi         *pnum = nb_sectors;
25196aebab14SStefan Hajnoczi         return 1;
25206aebab14SStefan Hajnoczi     }
25216aebab14SStefan Hajnoczi 
2522060f51c9SStefan Hajnoczi     return bs->drv->bdrv_co_is_allocated(bs, sector_num, nb_sectors, pnum);
2523060f51c9SStefan Hajnoczi }
2524060f51c9SStefan Hajnoczi 
2525060f51c9SStefan Hajnoczi /* Coroutine wrapper for bdrv_is_allocated() */
2526060f51c9SStefan Hajnoczi static void coroutine_fn bdrv_is_allocated_co_entry(void *opaque)
2527060f51c9SStefan Hajnoczi {
2528060f51c9SStefan Hajnoczi     BdrvCoIsAllocatedData *data = opaque;
2529060f51c9SStefan Hajnoczi     BlockDriverState *bs = data->bs;
2530060f51c9SStefan Hajnoczi 
2531060f51c9SStefan Hajnoczi     data->ret = bdrv_co_is_allocated(bs, data->sector_num, data->nb_sectors,
2532060f51c9SStefan Hajnoczi                                      data->pnum);
2533060f51c9SStefan Hajnoczi     data->done = true;
2534060f51c9SStefan Hajnoczi }
2535060f51c9SStefan Hajnoczi 
2536060f51c9SStefan Hajnoczi /*
2537060f51c9SStefan Hajnoczi  * Synchronous wrapper around bdrv_co_is_allocated().
2538060f51c9SStefan Hajnoczi  *
2539060f51c9SStefan Hajnoczi  * See bdrv_co_is_allocated() for details.
2540060f51c9SStefan Hajnoczi  */
2541060f51c9SStefan Hajnoczi int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
2542060f51c9SStefan Hajnoczi                       int *pnum)
2543060f51c9SStefan Hajnoczi {
2544376ae3f1SStefan Hajnoczi     Coroutine *co;
2545376ae3f1SStefan Hajnoczi     BdrvCoIsAllocatedData data = {
2546376ae3f1SStefan Hajnoczi         .bs = bs,
2547376ae3f1SStefan Hajnoczi         .sector_num = sector_num,
2548376ae3f1SStefan Hajnoczi         .nb_sectors = nb_sectors,
2549376ae3f1SStefan Hajnoczi         .pnum = pnum,
2550376ae3f1SStefan Hajnoczi         .done = false,
2551376ae3f1SStefan Hajnoczi     };
2552376ae3f1SStefan Hajnoczi 
2553376ae3f1SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_is_allocated_co_entry);
2554376ae3f1SStefan Hajnoczi     qemu_coroutine_enter(co, &data);
2555376ae3f1SStefan Hajnoczi     while (!data.done) {
2556376ae3f1SStefan Hajnoczi         qemu_aio_wait();
2557376ae3f1SStefan Hajnoczi     }
2558376ae3f1SStefan Hajnoczi     return data.ret;
2559376ae3f1SStefan Hajnoczi }
2560f58c7b35Sths 
2561b2023818SLuiz Capitulino BlockInfoList *qmp_query_block(Error **errp)
2562b338082bSbellard {
2563b2023818SLuiz Capitulino     BlockInfoList *head = NULL, *cur_item = NULL;
2564d15e5465SLuiz Capitulino     BlockDriverState *bs;
2565d15e5465SLuiz Capitulino 
25661b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
2567b2023818SLuiz Capitulino         BlockInfoList *info = g_malloc0(sizeof(*info));
2568d15e5465SLuiz Capitulino 
2569b2023818SLuiz Capitulino         info->value = g_malloc0(sizeof(*info->value));
2570b2023818SLuiz Capitulino         info->value->device = g_strdup(bs->device_name);
2571b2023818SLuiz Capitulino         info->value->type = g_strdup("unknown");
2572b2023818SLuiz Capitulino         info->value->locked = bdrv_dev_is_medium_locked(bs);
2573b2023818SLuiz Capitulino         info->value->removable = bdrv_dev_has_removable_media(bs);
2574d15e5465SLuiz Capitulino 
2575e4def80bSMarkus Armbruster         if (bdrv_dev_has_removable_media(bs)) {
2576b2023818SLuiz Capitulino             info->value->has_tray_open = true;
2577b2023818SLuiz Capitulino             info->value->tray_open = bdrv_dev_is_tray_open(bs);
2578e4def80bSMarkus Armbruster         }
2579f04ef601SLuiz Capitulino 
2580f04ef601SLuiz Capitulino         if (bdrv_iostatus_is_enabled(bs)) {
2581b2023818SLuiz Capitulino             info->value->has_io_status = true;
2582b2023818SLuiz Capitulino             info->value->io_status = bs->iostatus;
2583f04ef601SLuiz Capitulino         }
2584f04ef601SLuiz Capitulino 
2585d15e5465SLuiz Capitulino         if (bs->drv) {
2586b2023818SLuiz Capitulino             info->value->has_inserted = true;
2587b2023818SLuiz Capitulino             info->value->inserted = g_malloc0(sizeof(*info->value->inserted));
2588b2023818SLuiz Capitulino             info->value->inserted->file = g_strdup(bs->filename);
2589b2023818SLuiz Capitulino             info->value->inserted->ro = bs->read_only;
2590b2023818SLuiz Capitulino             info->value->inserted->drv = g_strdup(bs->drv->format_name);
2591b2023818SLuiz Capitulino             info->value->inserted->encrypted = bs->encrypted;
2592b2023818SLuiz Capitulino             if (bs->backing_file[0]) {
2593b2023818SLuiz Capitulino                 info->value->inserted->has_backing_file = true;
2594b2023818SLuiz Capitulino                 info->value->inserted->backing_file = g_strdup(bs->backing_file);
2595b2023818SLuiz Capitulino             }
2596727f005eSZhi Yong Wu 
2597727f005eSZhi Yong Wu             if (bs->io_limits_enabled) {
2598727f005eSZhi Yong Wu                 info->value->inserted->bps =
2599727f005eSZhi Yong Wu                                bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
2600727f005eSZhi Yong Wu                 info->value->inserted->bps_rd =
2601727f005eSZhi Yong Wu                                bs->io_limits.bps[BLOCK_IO_LIMIT_READ];
2602727f005eSZhi Yong Wu                 info->value->inserted->bps_wr =
2603727f005eSZhi Yong Wu                                bs->io_limits.bps[BLOCK_IO_LIMIT_WRITE];
2604727f005eSZhi Yong Wu                 info->value->inserted->iops =
2605727f005eSZhi Yong Wu                                bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
2606727f005eSZhi Yong Wu                 info->value->inserted->iops_rd =
2607727f005eSZhi Yong Wu                                bs->io_limits.iops[BLOCK_IO_LIMIT_READ];
2608727f005eSZhi Yong Wu                 info->value->inserted->iops_wr =
2609727f005eSZhi Yong Wu                                bs->io_limits.iops[BLOCK_IO_LIMIT_WRITE];
2610727f005eSZhi Yong Wu             }
2611d15e5465SLuiz Capitulino         }
2612d15e5465SLuiz Capitulino 
2613b2023818SLuiz Capitulino         /* XXX: waiting for the qapi to support GSList */
2614b2023818SLuiz Capitulino         if (!cur_item) {
2615b2023818SLuiz Capitulino             head = cur_item = info;
2616b2023818SLuiz Capitulino         } else {
2617b2023818SLuiz Capitulino             cur_item->next = info;
2618b2023818SLuiz Capitulino             cur_item = info;
2619d15e5465SLuiz Capitulino         }
2620d15e5465SLuiz Capitulino     }
2621d15e5465SLuiz Capitulino 
2622b2023818SLuiz Capitulino     return head;
2623b338082bSbellard }
2624a36e69ddSths 
2625f11f57e4SLuiz Capitulino /* Consider exposing this as a full fledged QMP command */
2626f11f57e4SLuiz Capitulino static BlockStats *qmp_query_blockstat(const BlockDriverState *bs, Error **errp)
2627a36e69ddSths {
2628f11f57e4SLuiz Capitulino     BlockStats *s;
2629218a536aSLuiz Capitulino 
2630f11f57e4SLuiz Capitulino     s = g_malloc0(sizeof(*s));
2631218a536aSLuiz Capitulino 
2632f11f57e4SLuiz Capitulino     if (bs->device_name[0]) {
2633f11f57e4SLuiz Capitulino         s->has_device = true;
2634f11f57e4SLuiz Capitulino         s->device = g_strdup(bs->device_name);
2635218a536aSLuiz Capitulino     }
2636218a536aSLuiz Capitulino 
2637f11f57e4SLuiz Capitulino     s->stats = g_malloc0(sizeof(*s->stats));
2638f11f57e4SLuiz Capitulino     s->stats->rd_bytes = bs->nr_bytes[BDRV_ACCT_READ];
2639f11f57e4SLuiz Capitulino     s->stats->wr_bytes = bs->nr_bytes[BDRV_ACCT_WRITE];
2640f11f57e4SLuiz Capitulino     s->stats->rd_operations = bs->nr_ops[BDRV_ACCT_READ];
2641f11f57e4SLuiz Capitulino     s->stats->wr_operations = bs->nr_ops[BDRV_ACCT_WRITE];
2642f11f57e4SLuiz Capitulino     s->stats->wr_highest_offset = bs->wr_highest_sector * BDRV_SECTOR_SIZE;
2643f11f57e4SLuiz Capitulino     s->stats->flush_operations = bs->nr_ops[BDRV_ACCT_FLUSH];
2644f11f57e4SLuiz Capitulino     s->stats->wr_total_time_ns = bs->total_time_ns[BDRV_ACCT_WRITE];
2645f11f57e4SLuiz Capitulino     s->stats->rd_total_time_ns = bs->total_time_ns[BDRV_ACCT_READ];
2646f11f57e4SLuiz Capitulino     s->stats->flush_total_time_ns = bs->total_time_ns[BDRV_ACCT_FLUSH];
2647294cc35fSKevin Wolf 
2648294cc35fSKevin Wolf     if (bs->file) {
2649f11f57e4SLuiz Capitulino         s->has_parent = true;
2650f11f57e4SLuiz Capitulino         s->parent = qmp_query_blockstat(bs->file, NULL);
2651294cc35fSKevin Wolf     }
2652294cc35fSKevin Wolf 
2653f11f57e4SLuiz Capitulino     return s;
2654294cc35fSKevin Wolf }
2655294cc35fSKevin Wolf 
2656f11f57e4SLuiz Capitulino BlockStatsList *qmp_query_blockstats(Error **errp)
2657218a536aSLuiz Capitulino {
2658f11f57e4SLuiz Capitulino     BlockStatsList *head = NULL, *cur_item = NULL;
2659a36e69ddSths     BlockDriverState *bs;
2660a36e69ddSths 
26611b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
2662f11f57e4SLuiz Capitulino         BlockStatsList *info = g_malloc0(sizeof(*info));
2663f11f57e4SLuiz Capitulino         info->value = qmp_query_blockstat(bs, NULL);
2664f11f57e4SLuiz Capitulino 
2665f11f57e4SLuiz Capitulino         /* XXX: waiting for the qapi to support GSList */
2666f11f57e4SLuiz Capitulino         if (!cur_item) {
2667f11f57e4SLuiz Capitulino             head = cur_item = info;
2668f11f57e4SLuiz Capitulino         } else {
2669f11f57e4SLuiz Capitulino             cur_item->next = info;
2670f11f57e4SLuiz Capitulino             cur_item = info;
2671f11f57e4SLuiz Capitulino         }
2672a36e69ddSths     }
2673218a536aSLuiz Capitulino 
2674f11f57e4SLuiz Capitulino     return head;
2675a36e69ddSths }
2676ea2384d3Sbellard 
2677045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2678045df330Saliguori {
2679045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
2680045df330Saliguori         return bs->backing_file;
2681045df330Saliguori     else if (bs->encrypted)
2682045df330Saliguori         return bs->filename;
2683045df330Saliguori     else
2684045df330Saliguori         return NULL;
2685045df330Saliguori }
2686045df330Saliguori 
268783f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
268883f64091Sbellard                                char *filename, int filename_size)
268983f64091Sbellard {
269083f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
269183f64091Sbellard }
269283f64091Sbellard 
2693faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
2694faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
2695faea38e7Sbellard {
2696faea38e7Sbellard     BlockDriver *drv = bs->drv;
2697faea38e7Sbellard     if (!drv)
269819cb3738Sbellard         return -ENOMEDIUM;
2699faea38e7Sbellard     if (!drv->bdrv_write_compressed)
2700faea38e7Sbellard         return -ENOTSUP;
2701fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
2702fbb7b4e0SKevin Wolf         return -EIO;
27037cd1e32aSlirans@il.ibm.com 
2704c6d22830SJan Kiszka     if (bs->dirty_bitmap) {
27057cd1e32aSlirans@il.ibm.com         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
27067cd1e32aSlirans@il.ibm.com     }
27077cd1e32aSlirans@il.ibm.com 
2708faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
2709faea38e7Sbellard }
2710faea38e7Sbellard 
2711faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2712faea38e7Sbellard {
2713faea38e7Sbellard     BlockDriver *drv = bs->drv;
2714faea38e7Sbellard     if (!drv)
271519cb3738Sbellard         return -ENOMEDIUM;
2716faea38e7Sbellard     if (!drv->bdrv_get_info)
2717faea38e7Sbellard         return -ENOTSUP;
2718faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
2719faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
2720faea38e7Sbellard }
2721faea38e7Sbellard 
272245566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
272345566e9cSChristoph Hellwig                       int64_t pos, int size)
2724178e08a5Saliguori {
2725178e08a5Saliguori     BlockDriver *drv = bs->drv;
2726178e08a5Saliguori     if (!drv)
2727178e08a5Saliguori         return -ENOMEDIUM;
27287cdb1f6dSMORITA Kazutaka     if (drv->bdrv_save_vmstate)
272945566e9cSChristoph Hellwig         return drv->bdrv_save_vmstate(bs, buf, pos, size);
27307cdb1f6dSMORITA Kazutaka     if (bs->file)
27317cdb1f6dSMORITA Kazutaka         return bdrv_save_vmstate(bs->file, buf, pos, size);
27327cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2733178e08a5Saliguori }
2734178e08a5Saliguori 
273545566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
273645566e9cSChristoph Hellwig                       int64_t pos, int size)
2737178e08a5Saliguori {
2738178e08a5Saliguori     BlockDriver *drv = bs->drv;
2739178e08a5Saliguori     if (!drv)
2740178e08a5Saliguori         return -ENOMEDIUM;
27417cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
274245566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
27437cdb1f6dSMORITA Kazutaka     if (bs->file)
27447cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
27457cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2746178e08a5Saliguori }
2747178e08a5Saliguori 
27488b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
27498b9b0cc2SKevin Wolf {
27508b9b0cc2SKevin Wolf     BlockDriver *drv = bs->drv;
27518b9b0cc2SKevin Wolf 
27528b9b0cc2SKevin Wolf     if (!drv || !drv->bdrv_debug_event) {
27538b9b0cc2SKevin Wolf         return;
27548b9b0cc2SKevin Wolf     }
27558b9b0cc2SKevin Wolf 
27568b9b0cc2SKevin Wolf     return drv->bdrv_debug_event(bs, event);
27578b9b0cc2SKevin Wolf 
27588b9b0cc2SKevin Wolf }
27598b9b0cc2SKevin Wolf 
2760faea38e7Sbellard /**************************************************************/
2761faea38e7Sbellard /* handling of snapshots */
2762faea38e7Sbellard 
2763feeee5acSMiguel Di Ciurcio Filho int bdrv_can_snapshot(BlockDriverState *bs)
2764feeee5acSMiguel Di Ciurcio Filho {
2765feeee5acSMiguel Di Ciurcio Filho     BlockDriver *drv = bs->drv;
276607b70bfbSMarkus Armbruster     if (!drv || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
2767feeee5acSMiguel Di Ciurcio Filho         return 0;
2768feeee5acSMiguel Di Ciurcio Filho     }
2769feeee5acSMiguel Di Ciurcio Filho 
2770feeee5acSMiguel Di Ciurcio Filho     if (!drv->bdrv_snapshot_create) {
2771feeee5acSMiguel Di Ciurcio Filho         if (bs->file != NULL) {
2772feeee5acSMiguel Di Ciurcio Filho             return bdrv_can_snapshot(bs->file);
2773feeee5acSMiguel Di Ciurcio Filho         }
2774feeee5acSMiguel Di Ciurcio Filho         return 0;
2775feeee5acSMiguel Di Ciurcio Filho     }
2776feeee5acSMiguel Di Ciurcio Filho 
2777feeee5acSMiguel Di Ciurcio Filho     return 1;
2778feeee5acSMiguel Di Ciurcio Filho }
2779feeee5acSMiguel Di Ciurcio Filho 
2780199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
2781199630b6SBlue Swirl {
2782199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2783199630b6SBlue Swirl }
2784199630b6SBlue Swirl 
2785f9092b10SMarkus Armbruster BlockDriverState *bdrv_snapshots(void)
2786f9092b10SMarkus Armbruster {
2787f9092b10SMarkus Armbruster     BlockDriverState *bs;
2788f9092b10SMarkus Armbruster 
27893ac906f7SMarkus Armbruster     if (bs_snapshots) {
2790f9092b10SMarkus Armbruster         return bs_snapshots;
27913ac906f7SMarkus Armbruster     }
2792f9092b10SMarkus Armbruster 
2793f9092b10SMarkus Armbruster     bs = NULL;
2794f9092b10SMarkus Armbruster     while ((bs = bdrv_next(bs))) {
2795f9092b10SMarkus Armbruster         if (bdrv_can_snapshot(bs)) {
27963ac906f7SMarkus Armbruster             bs_snapshots = bs;
27973ac906f7SMarkus Armbruster             return bs;
2798f9092b10SMarkus Armbruster         }
2799f9092b10SMarkus Armbruster     }
2800f9092b10SMarkus Armbruster     return NULL;
2801f9092b10SMarkus Armbruster }
2802f9092b10SMarkus Armbruster 
2803faea38e7Sbellard int bdrv_snapshot_create(BlockDriverState *bs,
2804faea38e7Sbellard                          QEMUSnapshotInfo *sn_info)
2805faea38e7Sbellard {
2806faea38e7Sbellard     BlockDriver *drv = bs->drv;
2807faea38e7Sbellard     if (!drv)
280819cb3738Sbellard         return -ENOMEDIUM;
28097cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_create)
2810faea38e7Sbellard         return drv->bdrv_snapshot_create(bs, sn_info);
28117cdb1f6dSMORITA Kazutaka     if (bs->file)
28127cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_create(bs->file, sn_info);
28137cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2814faea38e7Sbellard }
2815faea38e7Sbellard 
2816faea38e7Sbellard int bdrv_snapshot_goto(BlockDriverState *bs,
2817faea38e7Sbellard                        const char *snapshot_id)
2818faea38e7Sbellard {
2819faea38e7Sbellard     BlockDriver *drv = bs->drv;
28207cdb1f6dSMORITA Kazutaka     int ret, open_ret;
28217cdb1f6dSMORITA Kazutaka 
2822faea38e7Sbellard     if (!drv)
282319cb3738Sbellard         return -ENOMEDIUM;
28247cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_goto)
2825faea38e7Sbellard         return drv->bdrv_snapshot_goto(bs, snapshot_id);
28267cdb1f6dSMORITA Kazutaka 
28277cdb1f6dSMORITA Kazutaka     if (bs->file) {
28287cdb1f6dSMORITA Kazutaka         drv->bdrv_close(bs);
28297cdb1f6dSMORITA Kazutaka         ret = bdrv_snapshot_goto(bs->file, snapshot_id);
28307cdb1f6dSMORITA Kazutaka         open_ret = drv->bdrv_open(bs, bs->open_flags);
28317cdb1f6dSMORITA Kazutaka         if (open_ret < 0) {
28327cdb1f6dSMORITA Kazutaka             bdrv_delete(bs->file);
28337cdb1f6dSMORITA Kazutaka             bs->drv = NULL;
28347cdb1f6dSMORITA Kazutaka             return open_ret;
28357cdb1f6dSMORITA Kazutaka         }
28367cdb1f6dSMORITA Kazutaka         return ret;
28377cdb1f6dSMORITA Kazutaka     }
28387cdb1f6dSMORITA Kazutaka 
28397cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2840faea38e7Sbellard }
2841faea38e7Sbellard 
2842faea38e7Sbellard int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2843faea38e7Sbellard {
2844faea38e7Sbellard     BlockDriver *drv = bs->drv;
2845faea38e7Sbellard     if (!drv)
284619cb3738Sbellard         return -ENOMEDIUM;
28477cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_delete)
2848faea38e7Sbellard         return drv->bdrv_snapshot_delete(bs, snapshot_id);
28497cdb1f6dSMORITA Kazutaka     if (bs->file)
28507cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_delete(bs->file, snapshot_id);
28517cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2852faea38e7Sbellard }
2853faea38e7Sbellard 
2854faea38e7Sbellard int bdrv_snapshot_list(BlockDriverState *bs,
2855faea38e7Sbellard                        QEMUSnapshotInfo **psn_info)
2856faea38e7Sbellard {
2857faea38e7Sbellard     BlockDriver *drv = bs->drv;
2858faea38e7Sbellard     if (!drv)
285919cb3738Sbellard         return -ENOMEDIUM;
28607cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_list)
2861faea38e7Sbellard         return drv->bdrv_snapshot_list(bs, psn_info);
28627cdb1f6dSMORITA Kazutaka     if (bs->file)
28637cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_list(bs->file, psn_info);
28647cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2865faea38e7Sbellard }
2866faea38e7Sbellard 
286751ef6727Sedison int bdrv_snapshot_load_tmp(BlockDriverState *bs,
286851ef6727Sedison         const char *snapshot_name)
286951ef6727Sedison {
287051ef6727Sedison     BlockDriver *drv = bs->drv;
287151ef6727Sedison     if (!drv) {
287251ef6727Sedison         return -ENOMEDIUM;
287351ef6727Sedison     }
287451ef6727Sedison     if (!bs->read_only) {
287551ef6727Sedison         return -EINVAL;
287651ef6727Sedison     }
287751ef6727Sedison     if (drv->bdrv_snapshot_load_tmp) {
287851ef6727Sedison         return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
287951ef6727Sedison     }
288051ef6727Sedison     return -ENOTSUP;
288151ef6727Sedison }
288251ef6727Sedison 
2883e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
2884e8a6bb9cSMarcelo Tosatti         const char *backing_file)
2885e8a6bb9cSMarcelo Tosatti {
2886e8a6bb9cSMarcelo Tosatti     if (!bs->drv) {
2887e8a6bb9cSMarcelo Tosatti         return NULL;
2888e8a6bb9cSMarcelo Tosatti     }
2889e8a6bb9cSMarcelo Tosatti 
2890e8a6bb9cSMarcelo Tosatti     if (bs->backing_hd) {
2891e8a6bb9cSMarcelo Tosatti         if (strcmp(bs->backing_file, backing_file) == 0) {
2892e8a6bb9cSMarcelo Tosatti             return bs->backing_hd;
2893e8a6bb9cSMarcelo Tosatti         } else {
2894e8a6bb9cSMarcelo Tosatti             return bdrv_find_backing_image(bs->backing_hd, backing_file);
2895e8a6bb9cSMarcelo Tosatti         }
2896e8a6bb9cSMarcelo Tosatti     }
2897e8a6bb9cSMarcelo Tosatti 
2898e8a6bb9cSMarcelo Tosatti     return NULL;
2899e8a6bb9cSMarcelo Tosatti }
2900e8a6bb9cSMarcelo Tosatti 
2901faea38e7Sbellard #define NB_SUFFIXES 4
2902faea38e7Sbellard 
2903faea38e7Sbellard char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2904faea38e7Sbellard {
2905faea38e7Sbellard     static const char suffixes[NB_SUFFIXES] = "KMGT";
2906faea38e7Sbellard     int64_t base;
2907faea38e7Sbellard     int i;
2908faea38e7Sbellard 
2909faea38e7Sbellard     if (size <= 999) {
2910faea38e7Sbellard         snprintf(buf, buf_size, "%" PRId64, size);
2911faea38e7Sbellard     } else {
2912faea38e7Sbellard         base = 1024;
2913faea38e7Sbellard         for(i = 0; i < NB_SUFFIXES; i++) {
2914faea38e7Sbellard             if (size < (10 * base)) {
2915faea38e7Sbellard                 snprintf(buf, buf_size, "%0.1f%c",
2916faea38e7Sbellard                          (double)size / base,
2917faea38e7Sbellard                          suffixes[i]);
2918faea38e7Sbellard                 break;
2919faea38e7Sbellard             } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
2920faea38e7Sbellard                 snprintf(buf, buf_size, "%" PRId64 "%c",
2921faea38e7Sbellard                          ((size + (base >> 1)) / base),
2922faea38e7Sbellard                          suffixes[i]);
2923faea38e7Sbellard                 break;
2924faea38e7Sbellard             }
2925faea38e7Sbellard             base = base * 1024;
2926faea38e7Sbellard         }
2927faea38e7Sbellard     }
2928faea38e7Sbellard     return buf;
2929faea38e7Sbellard }
2930faea38e7Sbellard 
2931faea38e7Sbellard char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2932faea38e7Sbellard {
2933faea38e7Sbellard     char buf1[128], date_buf[128], clock_buf[128];
29343b9f94e1Sbellard #ifdef _WIN32
29353b9f94e1Sbellard     struct tm *ptm;
29363b9f94e1Sbellard #else
2937faea38e7Sbellard     struct tm tm;
29383b9f94e1Sbellard #endif
2939faea38e7Sbellard     time_t ti;
2940faea38e7Sbellard     int64_t secs;
2941faea38e7Sbellard 
2942faea38e7Sbellard     if (!sn) {
2943faea38e7Sbellard         snprintf(buf, buf_size,
2944faea38e7Sbellard                  "%-10s%-20s%7s%20s%15s",
2945faea38e7Sbellard                  "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2946faea38e7Sbellard     } else {
2947faea38e7Sbellard         ti = sn->date_sec;
29483b9f94e1Sbellard #ifdef _WIN32
29493b9f94e1Sbellard         ptm = localtime(&ti);
29503b9f94e1Sbellard         strftime(date_buf, sizeof(date_buf),
29513b9f94e1Sbellard                  "%Y-%m-%d %H:%M:%S", ptm);
29523b9f94e1Sbellard #else
2953faea38e7Sbellard         localtime_r(&ti, &tm);
2954faea38e7Sbellard         strftime(date_buf, sizeof(date_buf),
2955faea38e7Sbellard                  "%Y-%m-%d %H:%M:%S", &tm);
29563b9f94e1Sbellard #endif
2957faea38e7Sbellard         secs = sn->vm_clock_nsec / 1000000000;
2958faea38e7Sbellard         snprintf(clock_buf, sizeof(clock_buf),
2959faea38e7Sbellard                  "%02d:%02d:%02d.%03d",
2960faea38e7Sbellard                  (int)(secs / 3600),
2961faea38e7Sbellard                  (int)((secs / 60) % 60),
2962faea38e7Sbellard                  (int)(secs % 60),
2963faea38e7Sbellard                  (int)((sn->vm_clock_nsec / 1000000) % 1000));
2964faea38e7Sbellard         snprintf(buf, buf_size,
2965faea38e7Sbellard                  "%-10s%-20s%7s%20s%15s",
2966faea38e7Sbellard                  sn->id_str, sn->name,
2967faea38e7Sbellard                  get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2968faea38e7Sbellard                  date_buf,
2969faea38e7Sbellard                  clock_buf);
2970faea38e7Sbellard     }
2971faea38e7Sbellard     return buf;
2972faea38e7Sbellard }
2973faea38e7Sbellard 
2974ea2384d3Sbellard /**************************************************************/
297583f64091Sbellard /* async I/Os */
2976ea2384d3Sbellard 
29773b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
2978f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
297983f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
2980ea2384d3Sbellard {
2981bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2982bbf0a440SStefan Hajnoczi 
2983b2a61371SStefan Hajnoczi     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
29848c5873d6SStefan Hajnoczi                                  cb, opaque, false);
298583f64091Sbellard }
298683f64091Sbellard 
2987f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2988f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
298983f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
29907674e7bfSbellard {
2991bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2992bbf0a440SStefan Hajnoczi 
29931a6e115bSStefan Hajnoczi     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
29948c5873d6SStefan Hajnoczi                                  cb, opaque, true);
299583f64091Sbellard }
299683f64091Sbellard 
299740b4f539SKevin Wolf 
299840b4f539SKevin Wolf typedef struct MultiwriteCB {
299940b4f539SKevin Wolf     int error;
300040b4f539SKevin Wolf     int num_requests;
300140b4f539SKevin Wolf     int num_callbacks;
300240b4f539SKevin Wolf     struct {
300340b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
300440b4f539SKevin Wolf         void *opaque;
300540b4f539SKevin Wolf         QEMUIOVector *free_qiov;
300640b4f539SKevin Wolf     } callbacks[];
300740b4f539SKevin Wolf } MultiwriteCB;
300840b4f539SKevin Wolf 
300940b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
301040b4f539SKevin Wolf {
301140b4f539SKevin Wolf     int i;
301240b4f539SKevin Wolf 
301340b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
301440b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
30151e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
30161e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
30171e1ea48dSStefan Hajnoczi         }
30187267c094SAnthony Liguori         g_free(mcb->callbacks[i].free_qiov);
301940b4f539SKevin Wolf     }
302040b4f539SKevin Wolf }
302140b4f539SKevin Wolf 
302240b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
302340b4f539SKevin Wolf {
302440b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
302540b4f539SKevin Wolf 
30266d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
30276d519a5fSStefan Hajnoczi 
3028cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
302940b4f539SKevin Wolf         mcb->error = ret;
303040b4f539SKevin Wolf     }
303140b4f539SKevin Wolf 
303240b4f539SKevin Wolf     mcb->num_requests--;
303340b4f539SKevin Wolf     if (mcb->num_requests == 0) {
303440b4f539SKevin Wolf         multiwrite_user_cb(mcb);
30357267c094SAnthony Liguori         g_free(mcb);
303640b4f539SKevin Wolf     }
303740b4f539SKevin Wolf }
303840b4f539SKevin Wolf 
303940b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
304040b4f539SKevin Wolf {
304177be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
304277be4366SChristoph Hellwig 
304377be4366SChristoph Hellwig     /*
304477be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
304577be4366SChristoph Hellwig      * here as that could overflow the return value.
304677be4366SChristoph Hellwig      */
304777be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
304877be4366SChristoph Hellwig         return 1;
304977be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
305077be4366SChristoph Hellwig         return -1;
305177be4366SChristoph Hellwig     } else {
305277be4366SChristoph Hellwig         return 0;
305377be4366SChristoph Hellwig     }
305440b4f539SKevin Wolf }
305540b4f539SKevin Wolf 
305640b4f539SKevin Wolf /*
305740b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
305840b4f539SKevin Wolf  * requests that remain after merging.
305940b4f539SKevin Wolf  */
306040b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
306140b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
306240b4f539SKevin Wolf {
306340b4f539SKevin Wolf     int i, outidx;
306440b4f539SKevin Wolf 
306540b4f539SKevin Wolf     // Sort requests by start sector
306640b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
306740b4f539SKevin Wolf 
306840b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
306940b4f539SKevin Wolf     // filling up gaps with zero sectors.
307040b4f539SKevin Wolf     outidx = 0;
307140b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
307240b4f539SKevin Wolf         int merge = 0;
307340b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
307440b4f539SKevin Wolf 
3075b6a127a1SPaolo Bonzini         // Handle exactly sequential writes and overlapping writes.
307640b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
307740b4f539SKevin Wolf             merge = 1;
307840b4f539SKevin Wolf         }
307940b4f539SKevin Wolf 
3080e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
3081e2a305fbSChristoph Hellwig             merge = 0;
3082e2a305fbSChristoph Hellwig         }
3083e2a305fbSChristoph Hellwig 
308440b4f539SKevin Wolf         if (merge) {
308540b4f539SKevin Wolf             size_t size;
30867267c094SAnthony Liguori             QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
308740b4f539SKevin Wolf             qemu_iovec_init(qiov,
308840b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
308940b4f539SKevin Wolf 
309040b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
309140b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
309240b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
309340b4f539SKevin Wolf             qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
309440b4f539SKevin Wolf 
3095b6a127a1SPaolo Bonzini             // We should need to add any zeros between the two requests
3096b6a127a1SPaolo Bonzini             assert (reqs[i].sector <= oldreq_last);
309740b4f539SKevin Wolf 
309840b4f539SKevin Wolf             // Add the second request
309940b4f539SKevin Wolf             qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
310040b4f539SKevin Wolf 
3101cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
310240b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
310340b4f539SKevin Wolf 
310440b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
310540b4f539SKevin Wolf         } else {
310640b4f539SKevin Wolf             outidx++;
310740b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
310840b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
310940b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
311040b4f539SKevin Wolf         }
311140b4f539SKevin Wolf     }
311240b4f539SKevin Wolf 
311340b4f539SKevin Wolf     return outidx + 1;
311440b4f539SKevin Wolf }
311540b4f539SKevin Wolf 
311640b4f539SKevin Wolf /*
311740b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
311840b4f539SKevin Wolf  *
311940b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
312040b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
312140b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
312240b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
312340b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
312440b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
312540b4f539SKevin Wolf  *
312640b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
312740b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
312840b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
312940b4f539SKevin Wolf  */
313040b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
313140b4f539SKevin Wolf {
313240b4f539SKevin Wolf     MultiwriteCB *mcb;
313340b4f539SKevin Wolf     int i;
313440b4f539SKevin Wolf 
3135301db7c2SRyan Harper     /* don't submit writes if we don't have a medium */
3136301db7c2SRyan Harper     if (bs->drv == NULL) {
3137301db7c2SRyan Harper         for (i = 0; i < num_reqs; i++) {
3138301db7c2SRyan Harper             reqs[i].error = -ENOMEDIUM;
3139301db7c2SRyan Harper         }
3140301db7c2SRyan Harper         return -1;
3141301db7c2SRyan Harper     }
3142301db7c2SRyan Harper 
314340b4f539SKevin Wolf     if (num_reqs == 0) {
314440b4f539SKevin Wolf         return 0;
314540b4f539SKevin Wolf     }
314640b4f539SKevin Wolf 
314740b4f539SKevin Wolf     // Create MultiwriteCB structure
31487267c094SAnthony Liguori     mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
314940b4f539SKevin Wolf     mcb->num_requests = 0;
315040b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
315140b4f539SKevin Wolf 
315240b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
315340b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
315440b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
315540b4f539SKevin Wolf     }
315640b4f539SKevin Wolf 
315740b4f539SKevin Wolf     // Check for mergable requests
315840b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
315940b4f539SKevin Wolf 
31606d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
31616d519a5fSStefan Hajnoczi 
3162df9309fbSPaolo Bonzini     /* Run the aio requests. */
3163df9309fbSPaolo Bonzini     mcb->num_requests = num_reqs;
316440b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
3165ad54ae80SPaolo Bonzini         bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
316640b4f539SKevin Wolf             reqs[i].nb_sectors, multiwrite_cb, mcb);
316740b4f539SKevin Wolf     }
316840b4f539SKevin Wolf 
316940b4f539SKevin Wolf     return 0;
317040b4f539SKevin Wolf }
317140b4f539SKevin Wolf 
317283f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
317383f64091Sbellard {
31746bbff9a0Saliguori     acb->pool->cancel(acb);
317583f64091Sbellard }
317683f64091Sbellard 
317798f90dbaSZhi Yong Wu /* block I/O throttling */
317898f90dbaSZhi Yong Wu static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
317998f90dbaSZhi Yong Wu                  bool is_write, double elapsed_time, uint64_t *wait)
318098f90dbaSZhi Yong Wu {
318198f90dbaSZhi Yong Wu     uint64_t bps_limit = 0;
318298f90dbaSZhi Yong Wu     double   bytes_limit, bytes_base, bytes_res;
318398f90dbaSZhi Yong Wu     double   slice_time, wait_time;
318498f90dbaSZhi Yong Wu 
318598f90dbaSZhi Yong Wu     if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
318698f90dbaSZhi Yong Wu         bps_limit = bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
318798f90dbaSZhi Yong Wu     } else if (bs->io_limits.bps[is_write]) {
318898f90dbaSZhi Yong Wu         bps_limit = bs->io_limits.bps[is_write];
318998f90dbaSZhi Yong Wu     } else {
319098f90dbaSZhi Yong Wu         if (wait) {
319198f90dbaSZhi Yong Wu             *wait = 0;
319298f90dbaSZhi Yong Wu         }
319398f90dbaSZhi Yong Wu 
319498f90dbaSZhi Yong Wu         return false;
319598f90dbaSZhi Yong Wu     }
319698f90dbaSZhi Yong Wu 
319798f90dbaSZhi Yong Wu     slice_time = bs->slice_end - bs->slice_start;
319898f90dbaSZhi Yong Wu     slice_time /= (NANOSECONDS_PER_SECOND);
319998f90dbaSZhi Yong Wu     bytes_limit = bps_limit * slice_time;
320098f90dbaSZhi Yong Wu     bytes_base  = bs->nr_bytes[is_write] - bs->io_base.bytes[is_write];
320198f90dbaSZhi Yong Wu     if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
320298f90dbaSZhi Yong Wu         bytes_base += bs->nr_bytes[!is_write] - bs->io_base.bytes[!is_write];
320398f90dbaSZhi Yong Wu     }
320498f90dbaSZhi Yong Wu 
320598f90dbaSZhi Yong Wu     /* bytes_base: the bytes of data which have been read/written; and
320698f90dbaSZhi Yong Wu      *             it is obtained from the history statistic info.
320798f90dbaSZhi Yong Wu      * bytes_res: the remaining bytes of data which need to be read/written.
320898f90dbaSZhi Yong Wu      * (bytes_base + bytes_res) / bps_limit: used to calcuate
320998f90dbaSZhi Yong Wu      *             the total time for completing reading/writting all data.
321098f90dbaSZhi Yong Wu      */
321198f90dbaSZhi Yong Wu     bytes_res   = (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
321298f90dbaSZhi Yong Wu 
321398f90dbaSZhi Yong Wu     if (bytes_base + bytes_res <= bytes_limit) {
321498f90dbaSZhi Yong Wu         if (wait) {
321598f90dbaSZhi Yong Wu             *wait = 0;
321698f90dbaSZhi Yong Wu         }
321798f90dbaSZhi Yong Wu 
321898f90dbaSZhi Yong Wu         return false;
321998f90dbaSZhi Yong Wu     }
322098f90dbaSZhi Yong Wu 
322198f90dbaSZhi Yong Wu     /* Calc approx time to dispatch */
322298f90dbaSZhi Yong Wu     wait_time = (bytes_base + bytes_res) / bps_limit - elapsed_time;
322398f90dbaSZhi Yong Wu 
322498f90dbaSZhi Yong Wu     /* When the I/O rate at runtime exceeds the limits,
322598f90dbaSZhi Yong Wu      * bs->slice_end need to be extended in order that the current statistic
322698f90dbaSZhi Yong Wu      * info can be kept until the timer fire, so it is increased and tuned
322798f90dbaSZhi Yong Wu      * based on the result of experiment.
322898f90dbaSZhi Yong Wu      */
322998f90dbaSZhi Yong Wu     bs->slice_time = wait_time * BLOCK_IO_SLICE_TIME * 10;
323098f90dbaSZhi Yong Wu     bs->slice_end += bs->slice_time - 3 * BLOCK_IO_SLICE_TIME;
323198f90dbaSZhi Yong Wu     if (wait) {
323298f90dbaSZhi Yong Wu         *wait = wait_time * BLOCK_IO_SLICE_TIME * 10;
323398f90dbaSZhi Yong Wu     }
323498f90dbaSZhi Yong Wu 
323598f90dbaSZhi Yong Wu     return true;
323698f90dbaSZhi Yong Wu }
323798f90dbaSZhi Yong Wu 
323898f90dbaSZhi Yong Wu static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
323998f90dbaSZhi Yong Wu                              double elapsed_time, uint64_t *wait)
324098f90dbaSZhi Yong Wu {
324198f90dbaSZhi Yong Wu     uint64_t iops_limit = 0;
324298f90dbaSZhi Yong Wu     double   ios_limit, ios_base;
324398f90dbaSZhi Yong Wu     double   slice_time, wait_time;
324498f90dbaSZhi Yong Wu 
324598f90dbaSZhi Yong Wu     if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
324698f90dbaSZhi Yong Wu         iops_limit = bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
324798f90dbaSZhi Yong Wu     } else if (bs->io_limits.iops[is_write]) {
324898f90dbaSZhi Yong Wu         iops_limit = bs->io_limits.iops[is_write];
324998f90dbaSZhi Yong Wu     } else {
325098f90dbaSZhi Yong Wu         if (wait) {
325198f90dbaSZhi Yong Wu             *wait = 0;
325298f90dbaSZhi Yong Wu         }
325398f90dbaSZhi Yong Wu 
325498f90dbaSZhi Yong Wu         return false;
325598f90dbaSZhi Yong Wu     }
325698f90dbaSZhi Yong Wu 
325798f90dbaSZhi Yong Wu     slice_time = bs->slice_end - bs->slice_start;
325898f90dbaSZhi Yong Wu     slice_time /= (NANOSECONDS_PER_SECOND);
325998f90dbaSZhi Yong Wu     ios_limit  = iops_limit * slice_time;
326098f90dbaSZhi Yong Wu     ios_base   = bs->nr_ops[is_write] - bs->io_base.ios[is_write];
326198f90dbaSZhi Yong Wu     if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
326298f90dbaSZhi Yong Wu         ios_base += bs->nr_ops[!is_write] - bs->io_base.ios[!is_write];
326398f90dbaSZhi Yong Wu     }
326498f90dbaSZhi Yong Wu 
326598f90dbaSZhi Yong Wu     if (ios_base + 1 <= ios_limit) {
326698f90dbaSZhi Yong Wu         if (wait) {
326798f90dbaSZhi Yong Wu             *wait = 0;
326898f90dbaSZhi Yong Wu         }
326998f90dbaSZhi Yong Wu 
327098f90dbaSZhi Yong Wu         return false;
327198f90dbaSZhi Yong Wu     }
327298f90dbaSZhi Yong Wu 
327398f90dbaSZhi Yong Wu     /* Calc approx time to dispatch */
327498f90dbaSZhi Yong Wu     wait_time = (ios_base + 1) / iops_limit;
327598f90dbaSZhi Yong Wu     if (wait_time > elapsed_time) {
327698f90dbaSZhi Yong Wu         wait_time = wait_time - elapsed_time;
327798f90dbaSZhi Yong Wu     } else {
327898f90dbaSZhi Yong Wu         wait_time = 0;
327998f90dbaSZhi Yong Wu     }
328098f90dbaSZhi Yong Wu 
328198f90dbaSZhi Yong Wu     bs->slice_time = wait_time * BLOCK_IO_SLICE_TIME * 10;
328298f90dbaSZhi Yong Wu     bs->slice_end += bs->slice_time - 3 * BLOCK_IO_SLICE_TIME;
328398f90dbaSZhi Yong Wu     if (wait) {
328498f90dbaSZhi Yong Wu         *wait = wait_time * BLOCK_IO_SLICE_TIME * 10;
328598f90dbaSZhi Yong Wu     }
328698f90dbaSZhi Yong Wu 
328798f90dbaSZhi Yong Wu     return true;
328898f90dbaSZhi Yong Wu }
328998f90dbaSZhi Yong Wu 
329098f90dbaSZhi Yong Wu static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
329198f90dbaSZhi Yong Wu                            bool is_write, int64_t *wait)
329298f90dbaSZhi Yong Wu {
329398f90dbaSZhi Yong Wu     int64_t  now, max_wait;
329498f90dbaSZhi Yong Wu     uint64_t bps_wait = 0, iops_wait = 0;
329598f90dbaSZhi Yong Wu     double   elapsed_time;
329698f90dbaSZhi Yong Wu     int      bps_ret, iops_ret;
329798f90dbaSZhi Yong Wu 
329898f90dbaSZhi Yong Wu     now = qemu_get_clock_ns(vm_clock);
329998f90dbaSZhi Yong Wu     if ((bs->slice_start < now)
330098f90dbaSZhi Yong Wu         && (bs->slice_end > now)) {
330198f90dbaSZhi Yong Wu         bs->slice_end = now + bs->slice_time;
330298f90dbaSZhi Yong Wu     } else {
330398f90dbaSZhi Yong Wu         bs->slice_time  =  5 * BLOCK_IO_SLICE_TIME;
330498f90dbaSZhi Yong Wu         bs->slice_start = now;
330598f90dbaSZhi Yong Wu         bs->slice_end   = now + bs->slice_time;
330698f90dbaSZhi Yong Wu 
330798f90dbaSZhi Yong Wu         bs->io_base.bytes[is_write]  = bs->nr_bytes[is_write];
330898f90dbaSZhi Yong Wu         bs->io_base.bytes[!is_write] = bs->nr_bytes[!is_write];
330998f90dbaSZhi Yong Wu 
331098f90dbaSZhi Yong Wu         bs->io_base.ios[is_write]    = bs->nr_ops[is_write];
331198f90dbaSZhi Yong Wu         bs->io_base.ios[!is_write]   = bs->nr_ops[!is_write];
331298f90dbaSZhi Yong Wu     }
331398f90dbaSZhi Yong Wu 
331498f90dbaSZhi Yong Wu     elapsed_time  = now - bs->slice_start;
331598f90dbaSZhi Yong Wu     elapsed_time  /= (NANOSECONDS_PER_SECOND);
331698f90dbaSZhi Yong Wu 
331798f90dbaSZhi Yong Wu     bps_ret  = bdrv_exceed_bps_limits(bs, nb_sectors,
331898f90dbaSZhi Yong Wu                                       is_write, elapsed_time, &bps_wait);
331998f90dbaSZhi Yong Wu     iops_ret = bdrv_exceed_iops_limits(bs, is_write,
332098f90dbaSZhi Yong Wu                                       elapsed_time, &iops_wait);
332198f90dbaSZhi Yong Wu     if (bps_ret || iops_ret) {
332298f90dbaSZhi Yong Wu         max_wait = bps_wait > iops_wait ? bps_wait : iops_wait;
332398f90dbaSZhi Yong Wu         if (wait) {
332498f90dbaSZhi Yong Wu             *wait = max_wait;
332598f90dbaSZhi Yong Wu         }
332698f90dbaSZhi Yong Wu 
332798f90dbaSZhi Yong Wu         now = qemu_get_clock_ns(vm_clock);
332898f90dbaSZhi Yong Wu         if (bs->slice_end < now + max_wait) {
332998f90dbaSZhi Yong Wu             bs->slice_end = now + max_wait;
333098f90dbaSZhi Yong Wu         }
333198f90dbaSZhi Yong Wu 
333298f90dbaSZhi Yong Wu         return true;
333398f90dbaSZhi Yong Wu     }
333498f90dbaSZhi Yong Wu 
333598f90dbaSZhi Yong Wu     if (wait) {
333698f90dbaSZhi Yong Wu         *wait = 0;
333798f90dbaSZhi Yong Wu     }
333898f90dbaSZhi Yong Wu 
333998f90dbaSZhi Yong Wu     return false;
334098f90dbaSZhi Yong Wu }
334183f64091Sbellard 
334283f64091Sbellard /**************************************************************/
334383f64091Sbellard /* async block device emulation */
334483f64091Sbellard 
3345c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
3346c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
3347c16b5a2cSChristoph Hellwig     QEMUBH *bh;
3348c16b5a2cSChristoph Hellwig     int ret;
3349c16b5a2cSChristoph Hellwig     /* vector translation state */
3350c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
3351c16b5a2cSChristoph Hellwig     uint8_t *bounce;
3352c16b5a2cSChristoph Hellwig     int is_write;
3353c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
3354c16b5a2cSChristoph Hellwig 
3355c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
3356c16b5a2cSChristoph Hellwig {
3357b666d239SKevin Wolf     BlockDriverAIOCBSync *acb =
3358b666d239SKevin Wolf         container_of(blockacb, BlockDriverAIOCBSync, common);
33596a7ad299SDor Laor     qemu_bh_delete(acb->bh);
336036afc451SAvi Kivity     acb->bh = NULL;
3361c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
3362c16b5a2cSChristoph Hellwig }
3363c16b5a2cSChristoph Hellwig 
3364c16b5a2cSChristoph Hellwig static AIOPool bdrv_em_aio_pool = {
3365c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
3366c16b5a2cSChristoph Hellwig     .cancel             = bdrv_aio_cancel_em,
3367c16b5a2cSChristoph Hellwig };
3368c16b5a2cSChristoph Hellwig 
336983f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
3370beac80cdSbellard {
3371ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
3372f141eafeSaliguori 
3373f141eafeSaliguori     if (!acb->is_write)
3374f141eafeSaliguori         qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
3375ceb42de8Saliguori     qemu_vfree(acb->bounce);
3376ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
33776a7ad299SDor Laor     qemu_bh_delete(acb->bh);
337836afc451SAvi Kivity     acb->bh = NULL;
3379ce1a14dcSpbrook     qemu_aio_release(acb);
3380beac80cdSbellard }
3381beac80cdSbellard 
3382f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
3383f141eafeSaliguori                                             int64_t sector_num,
3384f141eafeSaliguori                                             QEMUIOVector *qiov,
3385f141eafeSaliguori                                             int nb_sectors,
3386f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
3387f141eafeSaliguori                                             void *opaque,
3388f141eafeSaliguori                                             int is_write)
3389f141eafeSaliguori 
3390ea2384d3Sbellard {
3391ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
339283f64091Sbellard 
3393c16b5a2cSChristoph Hellwig     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
3394f141eafeSaliguori     acb->is_write = is_write;
3395f141eafeSaliguori     acb->qiov = qiov;
3396e268ca52Saliguori     acb->bounce = qemu_blockalign(bs, qiov->size);
3397ce1a14dcSpbrook     acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
3398f141eafeSaliguori 
3399f141eafeSaliguori     if (is_write) {
3400f141eafeSaliguori         qemu_iovec_to_buffer(acb->qiov, acb->bounce);
34011ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
3402f141eafeSaliguori     } else {
34031ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
3404f141eafeSaliguori     }
3405f141eafeSaliguori 
3406ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
3407f141eafeSaliguori 
3408ce1a14dcSpbrook     return &acb->common;
34097a6cba61Spbrook }
34107a6cba61Spbrook 
3411f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
3412f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
3413ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
341483f64091Sbellard {
3415f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
341683f64091Sbellard }
341783f64091Sbellard 
3418f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
3419f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
3420f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
3421f141eafeSaliguori {
3422f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
3423f141eafeSaliguori }
3424f141eafeSaliguori 
342568485420SKevin Wolf 
342668485420SKevin Wolf typedef struct BlockDriverAIOCBCoroutine {
342768485420SKevin Wolf     BlockDriverAIOCB common;
342868485420SKevin Wolf     BlockRequest req;
342968485420SKevin Wolf     bool is_write;
343068485420SKevin Wolf     QEMUBH* bh;
343168485420SKevin Wolf } BlockDriverAIOCBCoroutine;
343268485420SKevin Wolf 
343368485420SKevin Wolf static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
343468485420SKevin Wolf {
343568485420SKevin Wolf     qemu_aio_flush();
343668485420SKevin Wolf }
343768485420SKevin Wolf 
343868485420SKevin Wolf static AIOPool bdrv_em_co_aio_pool = {
343968485420SKevin Wolf     .aiocb_size         = sizeof(BlockDriverAIOCBCoroutine),
344068485420SKevin Wolf     .cancel             = bdrv_aio_co_cancel_em,
344168485420SKevin Wolf };
344268485420SKevin Wolf 
344335246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque)
344468485420SKevin Wolf {
344568485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb = opaque;
344668485420SKevin Wolf 
344768485420SKevin Wolf     acb->common.cb(acb->common.opaque, acb->req.error);
344868485420SKevin Wolf     qemu_bh_delete(acb->bh);
344968485420SKevin Wolf     qemu_aio_release(acb);
345068485420SKevin Wolf }
345168485420SKevin Wolf 
3452b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
3453b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque)
3454b2a61371SStefan Hajnoczi {
3455b2a61371SStefan Hajnoczi     BlockDriverAIOCBCoroutine *acb = opaque;
3456b2a61371SStefan Hajnoczi     BlockDriverState *bs = acb->common.bs;
3457b2a61371SStefan Hajnoczi 
3458b2a61371SStefan Hajnoczi     if (!acb->is_write) {
3459b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
3460470c0504SStefan Hajnoczi             acb->req.nb_sectors, acb->req.qiov, 0);
3461b2a61371SStefan Hajnoczi     } else {
3462b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
3463f08f2ddaSStefan Hajnoczi             acb->req.nb_sectors, acb->req.qiov, 0);
3464b2a61371SStefan Hajnoczi     }
3465b2a61371SStefan Hajnoczi 
346635246a68SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
3467b2a61371SStefan Hajnoczi     qemu_bh_schedule(acb->bh);
3468b2a61371SStefan Hajnoczi }
3469b2a61371SStefan Hajnoczi 
347068485420SKevin Wolf static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
347168485420SKevin Wolf                                                int64_t sector_num,
347268485420SKevin Wolf                                                QEMUIOVector *qiov,
347368485420SKevin Wolf                                                int nb_sectors,
347468485420SKevin Wolf                                                BlockDriverCompletionFunc *cb,
347568485420SKevin Wolf                                                void *opaque,
34768c5873d6SStefan Hajnoczi                                                bool is_write)
347768485420SKevin Wolf {
347868485420SKevin Wolf     Coroutine *co;
347968485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb;
348068485420SKevin Wolf 
348168485420SKevin Wolf     acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
348268485420SKevin Wolf     acb->req.sector = sector_num;
348368485420SKevin Wolf     acb->req.nb_sectors = nb_sectors;
348468485420SKevin Wolf     acb->req.qiov = qiov;
348568485420SKevin Wolf     acb->is_write = is_write;
348668485420SKevin Wolf 
34878c5873d6SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_co_do_rw);
348868485420SKevin Wolf     qemu_coroutine_enter(co, acb);
348968485420SKevin Wolf 
349068485420SKevin Wolf     return &acb->common;
349168485420SKevin Wolf }
349268485420SKevin Wolf 
349307f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
3494b2e12bc6SChristoph Hellwig {
349507f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
349607f07615SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
3497b2e12bc6SChristoph Hellwig 
349807f07615SPaolo Bonzini     acb->req.error = bdrv_co_flush(bs);
349907f07615SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
3500b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
3501b2e12bc6SChristoph Hellwig }
3502b2e12bc6SChristoph Hellwig 
350307f07615SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
3504016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
3505016f5cf6SAlexander Graf {
350607f07615SPaolo Bonzini     trace_bdrv_aio_flush(bs, opaque);
3507016f5cf6SAlexander Graf 
350807f07615SPaolo Bonzini     Coroutine *co;
350907f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
3510016f5cf6SAlexander Graf 
351107f07615SPaolo Bonzini     acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
351207f07615SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
351307f07615SPaolo Bonzini     qemu_coroutine_enter(co, acb);
3514016f5cf6SAlexander Graf 
3515016f5cf6SAlexander Graf     return &acb->common;
3516016f5cf6SAlexander Graf }
3517016f5cf6SAlexander Graf 
35184265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
35194265d620SPaolo Bonzini {
35204265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
35214265d620SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
35224265d620SPaolo Bonzini 
35234265d620SPaolo Bonzini     acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
35244265d620SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
35254265d620SPaolo Bonzini     qemu_bh_schedule(acb->bh);
35264265d620SPaolo Bonzini }
35274265d620SPaolo Bonzini 
35284265d620SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
35294265d620SPaolo Bonzini         int64_t sector_num, int nb_sectors,
35304265d620SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
35314265d620SPaolo Bonzini {
35324265d620SPaolo Bonzini     Coroutine *co;
35334265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
35344265d620SPaolo Bonzini 
35354265d620SPaolo Bonzini     trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
35364265d620SPaolo Bonzini 
35374265d620SPaolo Bonzini     acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
35384265d620SPaolo Bonzini     acb->req.sector = sector_num;
35394265d620SPaolo Bonzini     acb->req.nb_sectors = nb_sectors;
35404265d620SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
35414265d620SPaolo Bonzini     qemu_coroutine_enter(co, acb);
35424265d620SPaolo Bonzini 
35434265d620SPaolo Bonzini     return &acb->common;
35444265d620SPaolo Bonzini }
35454265d620SPaolo Bonzini 
3546ea2384d3Sbellard void bdrv_init(void)
3547ea2384d3Sbellard {
35485efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
3549ea2384d3Sbellard }
3550ce1a14dcSpbrook 
3551eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
3552eb852011SMarkus Armbruster {
3553eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
3554eb852011SMarkus Armbruster     bdrv_init();
3555eb852011SMarkus Armbruster }
3556eb852011SMarkus Armbruster 
3557c16b5a2cSChristoph Hellwig void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
35586bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
35596bbff9a0Saliguori {
3560ce1a14dcSpbrook     BlockDriverAIOCB *acb;
3561ce1a14dcSpbrook 
35626bbff9a0Saliguori     if (pool->free_aiocb) {
35636bbff9a0Saliguori         acb = pool->free_aiocb;
35646bbff9a0Saliguori         pool->free_aiocb = acb->next;
3565ce1a14dcSpbrook     } else {
35667267c094SAnthony Liguori         acb = g_malloc0(pool->aiocb_size);
35676bbff9a0Saliguori         acb->pool = pool;
3568ce1a14dcSpbrook     }
3569ce1a14dcSpbrook     acb->bs = bs;
3570ce1a14dcSpbrook     acb->cb = cb;
3571ce1a14dcSpbrook     acb->opaque = opaque;
3572ce1a14dcSpbrook     return acb;
3573ce1a14dcSpbrook }
3574ce1a14dcSpbrook 
3575ce1a14dcSpbrook void qemu_aio_release(void *p)
3576ce1a14dcSpbrook {
35776bbff9a0Saliguori     BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
35786bbff9a0Saliguori     AIOPool *pool = acb->pool;
35796bbff9a0Saliguori     acb->next = pool->free_aiocb;
35806bbff9a0Saliguori     pool->free_aiocb = acb;
3581ce1a14dcSpbrook }
358219cb3738Sbellard 
358319cb3738Sbellard /**************************************************************/
3584f9f05dc5SKevin Wolf /* Coroutine block device emulation */
3585f9f05dc5SKevin Wolf 
3586f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion {
3587f9f05dc5SKevin Wolf     Coroutine *coroutine;
3588f9f05dc5SKevin Wolf     int ret;
3589f9f05dc5SKevin Wolf } CoroutineIOCompletion;
3590f9f05dc5SKevin Wolf 
3591f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret)
3592f9f05dc5SKevin Wolf {
3593f9f05dc5SKevin Wolf     CoroutineIOCompletion *co = opaque;
3594f9f05dc5SKevin Wolf 
3595f9f05dc5SKevin Wolf     co->ret = ret;
3596f9f05dc5SKevin Wolf     qemu_coroutine_enter(co->coroutine, NULL);
3597f9f05dc5SKevin Wolf }
3598f9f05dc5SKevin Wolf 
3599f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
3600f9f05dc5SKevin Wolf                                       int nb_sectors, QEMUIOVector *iov,
3601f9f05dc5SKevin Wolf                                       bool is_write)
3602f9f05dc5SKevin Wolf {
3603f9f05dc5SKevin Wolf     CoroutineIOCompletion co = {
3604f9f05dc5SKevin Wolf         .coroutine = qemu_coroutine_self(),
3605f9f05dc5SKevin Wolf     };
3606f9f05dc5SKevin Wolf     BlockDriverAIOCB *acb;
3607f9f05dc5SKevin Wolf 
3608f9f05dc5SKevin Wolf     if (is_write) {
3609a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
3610f9f05dc5SKevin Wolf                                        bdrv_co_io_em_complete, &co);
3611f9f05dc5SKevin Wolf     } else {
3612a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
3613f9f05dc5SKevin Wolf                                       bdrv_co_io_em_complete, &co);
3614f9f05dc5SKevin Wolf     }
3615f9f05dc5SKevin Wolf 
361659370aaaSStefan Hajnoczi     trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
3617f9f05dc5SKevin Wolf     if (!acb) {
3618f9f05dc5SKevin Wolf         return -EIO;
3619f9f05dc5SKevin Wolf     }
3620f9f05dc5SKevin Wolf     qemu_coroutine_yield();
3621f9f05dc5SKevin Wolf 
3622f9f05dc5SKevin Wolf     return co.ret;
3623f9f05dc5SKevin Wolf }
3624f9f05dc5SKevin Wolf 
3625f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
3626f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
3627f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
3628f9f05dc5SKevin Wolf {
3629f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
3630f9f05dc5SKevin Wolf }
3631f9f05dc5SKevin Wolf 
3632f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
3633f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
3634f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
3635f9f05dc5SKevin Wolf {
3636f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
3637f9f05dc5SKevin Wolf }
3638f9f05dc5SKevin Wolf 
363907f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque)
3640e7a8a783SKevin Wolf {
364107f07615SPaolo Bonzini     RwCo *rwco = opaque;
364207f07615SPaolo Bonzini 
364307f07615SPaolo Bonzini     rwco->ret = bdrv_co_flush(rwco->bs);
364407f07615SPaolo Bonzini }
364507f07615SPaolo Bonzini 
364607f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
364707f07615SPaolo Bonzini {
3648eb489bb1SKevin Wolf     int ret;
3649eb489bb1SKevin Wolf 
365029cdb251SPaolo Bonzini     if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
365107f07615SPaolo Bonzini         return 0;
3652eb489bb1SKevin Wolf     }
3653eb489bb1SKevin Wolf 
3654ca716364SKevin Wolf     /* Write back cached data to the OS even with cache=unsafe */
3655eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_os) {
3656eb489bb1SKevin Wolf         ret = bs->drv->bdrv_co_flush_to_os(bs);
3657eb489bb1SKevin Wolf         if (ret < 0) {
3658eb489bb1SKevin Wolf             return ret;
3659eb489bb1SKevin Wolf         }
3660eb489bb1SKevin Wolf     }
3661eb489bb1SKevin Wolf 
3662ca716364SKevin Wolf     /* But don't actually force it to the disk with cache=unsafe */
3663ca716364SKevin Wolf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
3664ca716364SKevin Wolf         return 0;
3665ca716364SKevin Wolf     }
3666ca716364SKevin Wolf 
3667eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_disk) {
366829cdb251SPaolo Bonzini         ret = bs->drv->bdrv_co_flush_to_disk(bs);
366907f07615SPaolo Bonzini     } else if (bs->drv->bdrv_aio_flush) {
367007f07615SPaolo Bonzini         BlockDriverAIOCB *acb;
3671e7a8a783SKevin Wolf         CoroutineIOCompletion co = {
3672e7a8a783SKevin Wolf             .coroutine = qemu_coroutine_self(),
3673e7a8a783SKevin Wolf         };
3674e7a8a783SKevin Wolf 
367507f07615SPaolo Bonzini         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
367607f07615SPaolo Bonzini         if (acb == NULL) {
367729cdb251SPaolo Bonzini             ret = -EIO;
367807f07615SPaolo Bonzini         } else {
3679e7a8a783SKevin Wolf             qemu_coroutine_yield();
368029cdb251SPaolo Bonzini             ret = co.ret;
3681e7a8a783SKevin Wolf         }
368207f07615SPaolo Bonzini     } else {
368307f07615SPaolo Bonzini         /*
368407f07615SPaolo Bonzini          * Some block drivers always operate in either writethrough or unsafe
368507f07615SPaolo Bonzini          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
368607f07615SPaolo Bonzini          * know how the server works (because the behaviour is hardcoded or
368707f07615SPaolo Bonzini          * depends on server-side configuration), so we can't ensure that
368807f07615SPaolo Bonzini          * everything is safe on disk. Returning an error doesn't work because
368907f07615SPaolo Bonzini          * that would break guests even if the server operates in writethrough
369007f07615SPaolo Bonzini          * mode.
369107f07615SPaolo Bonzini          *
369207f07615SPaolo Bonzini          * Let's hope the user knows what he's doing.
369307f07615SPaolo Bonzini          */
369429cdb251SPaolo Bonzini         ret = 0;
369507f07615SPaolo Bonzini     }
369629cdb251SPaolo Bonzini     if (ret < 0) {
369729cdb251SPaolo Bonzini         return ret;
369829cdb251SPaolo Bonzini     }
369929cdb251SPaolo Bonzini 
370029cdb251SPaolo Bonzini     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
370129cdb251SPaolo Bonzini      * in the case of cache=unsafe, so there are no useless flushes.
370229cdb251SPaolo Bonzini      */
370329cdb251SPaolo Bonzini     return bdrv_co_flush(bs->file);
370407f07615SPaolo Bonzini }
370507f07615SPaolo Bonzini 
37060f15423cSAnthony Liguori void bdrv_invalidate_cache(BlockDriverState *bs)
37070f15423cSAnthony Liguori {
37080f15423cSAnthony Liguori     if (bs->drv && bs->drv->bdrv_invalidate_cache) {
37090f15423cSAnthony Liguori         bs->drv->bdrv_invalidate_cache(bs);
37100f15423cSAnthony Liguori     }
37110f15423cSAnthony Liguori }
37120f15423cSAnthony Liguori 
37130f15423cSAnthony Liguori void bdrv_invalidate_cache_all(void)
37140f15423cSAnthony Liguori {
37150f15423cSAnthony Liguori     BlockDriverState *bs;
37160f15423cSAnthony Liguori 
37170f15423cSAnthony Liguori     QTAILQ_FOREACH(bs, &bdrv_states, list) {
37180f15423cSAnthony Liguori         bdrv_invalidate_cache(bs);
37190f15423cSAnthony Liguori     }
37200f15423cSAnthony Liguori }
37210f15423cSAnthony Liguori 
372207789269SBenoît Canet void bdrv_clear_incoming_migration_all(void)
372307789269SBenoît Canet {
372407789269SBenoît Canet     BlockDriverState *bs;
372507789269SBenoît Canet 
372607789269SBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, list) {
372707789269SBenoît Canet         bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
372807789269SBenoît Canet     }
372907789269SBenoît Canet }
373007789269SBenoît Canet 
373107f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs)
373207f07615SPaolo Bonzini {
373307f07615SPaolo Bonzini     Coroutine *co;
373407f07615SPaolo Bonzini     RwCo rwco = {
373507f07615SPaolo Bonzini         .bs = bs,
373607f07615SPaolo Bonzini         .ret = NOT_DONE,
373707f07615SPaolo Bonzini     };
373807f07615SPaolo Bonzini 
373907f07615SPaolo Bonzini     if (qemu_in_coroutine()) {
374007f07615SPaolo Bonzini         /* Fast-path if already in coroutine context */
374107f07615SPaolo Bonzini         bdrv_flush_co_entry(&rwco);
374207f07615SPaolo Bonzini     } else {
374307f07615SPaolo Bonzini         co = qemu_coroutine_create(bdrv_flush_co_entry);
374407f07615SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
374507f07615SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
374607f07615SPaolo Bonzini             qemu_aio_wait();
374707f07615SPaolo Bonzini         }
374807f07615SPaolo Bonzini     }
374907f07615SPaolo Bonzini 
375007f07615SPaolo Bonzini     return rwco.ret;
375107f07615SPaolo Bonzini }
3752e7a8a783SKevin Wolf 
37534265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque)
37544265d620SPaolo Bonzini {
37554265d620SPaolo Bonzini     RwCo *rwco = opaque;
37564265d620SPaolo Bonzini 
37574265d620SPaolo Bonzini     rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
37584265d620SPaolo Bonzini }
37594265d620SPaolo Bonzini 
37604265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
37614265d620SPaolo Bonzini                                  int nb_sectors)
37624265d620SPaolo Bonzini {
37634265d620SPaolo Bonzini     if (!bs->drv) {
37644265d620SPaolo Bonzini         return -ENOMEDIUM;
37654265d620SPaolo Bonzini     } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
37664265d620SPaolo Bonzini         return -EIO;
37674265d620SPaolo Bonzini     } else if (bs->read_only) {
37684265d620SPaolo Bonzini         return -EROFS;
37694265d620SPaolo Bonzini     } else if (bs->drv->bdrv_co_discard) {
37704265d620SPaolo Bonzini         return bs->drv->bdrv_co_discard(bs, sector_num, nb_sectors);
37714265d620SPaolo Bonzini     } else if (bs->drv->bdrv_aio_discard) {
37724265d620SPaolo Bonzini         BlockDriverAIOCB *acb;
37734265d620SPaolo Bonzini         CoroutineIOCompletion co = {
37744265d620SPaolo Bonzini             .coroutine = qemu_coroutine_self(),
37754265d620SPaolo Bonzini         };
37764265d620SPaolo Bonzini 
37774265d620SPaolo Bonzini         acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
37784265d620SPaolo Bonzini                                         bdrv_co_io_em_complete, &co);
37794265d620SPaolo Bonzini         if (acb == NULL) {
37804265d620SPaolo Bonzini             return -EIO;
37814265d620SPaolo Bonzini         } else {
37824265d620SPaolo Bonzini             qemu_coroutine_yield();
37834265d620SPaolo Bonzini             return co.ret;
37844265d620SPaolo Bonzini         }
37854265d620SPaolo Bonzini     } else {
37864265d620SPaolo Bonzini         return 0;
37874265d620SPaolo Bonzini     }
37884265d620SPaolo Bonzini }
37894265d620SPaolo Bonzini 
37904265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
37914265d620SPaolo Bonzini {
37924265d620SPaolo Bonzini     Coroutine *co;
37934265d620SPaolo Bonzini     RwCo rwco = {
37944265d620SPaolo Bonzini         .bs = bs,
37954265d620SPaolo Bonzini         .sector_num = sector_num,
37964265d620SPaolo Bonzini         .nb_sectors = nb_sectors,
37974265d620SPaolo Bonzini         .ret = NOT_DONE,
37984265d620SPaolo Bonzini     };
37994265d620SPaolo Bonzini 
38004265d620SPaolo Bonzini     if (qemu_in_coroutine()) {
38014265d620SPaolo Bonzini         /* Fast-path if already in coroutine context */
38024265d620SPaolo Bonzini         bdrv_discard_co_entry(&rwco);
38034265d620SPaolo Bonzini     } else {
38044265d620SPaolo Bonzini         co = qemu_coroutine_create(bdrv_discard_co_entry);
38054265d620SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
38064265d620SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
38074265d620SPaolo Bonzini             qemu_aio_wait();
38084265d620SPaolo Bonzini         }
38094265d620SPaolo Bonzini     }
38104265d620SPaolo Bonzini 
38114265d620SPaolo Bonzini     return rwco.ret;
38124265d620SPaolo Bonzini }
38134265d620SPaolo Bonzini 
3814f9f05dc5SKevin Wolf /**************************************************************/
381519cb3738Sbellard /* removable device support */
381619cb3738Sbellard 
381719cb3738Sbellard /**
381819cb3738Sbellard  * Return TRUE if the media is present
381919cb3738Sbellard  */
382019cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
382119cb3738Sbellard {
382219cb3738Sbellard     BlockDriver *drv = bs->drv;
3823a1aff5bfSMarkus Armbruster 
382419cb3738Sbellard     if (!drv)
382519cb3738Sbellard         return 0;
382619cb3738Sbellard     if (!drv->bdrv_is_inserted)
3827a1aff5bfSMarkus Armbruster         return 1;
3828a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
382919cb3738Sbellard }
383019cb3738Sbellard 
383119cb3738Sbellard /**
38328e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
38338e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
383419cb3738Sbellard  */
383519cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
383619cb3738Sbellard {
383719cb3738Sbellard     BlockDriver *drv = bs->drv;
383819cb3738Sbellard 
38398e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
38408e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
38418e49ca46SMarkus Armbruster     }
38428e49ca46SMarkus Armbruster     return -ENOTSUP;
384319cb3738Sbellard }
384419cb3738Sbellard 
384519cb3738Sbellard /**
384619cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
384719cb3738Sbellard  */
3848f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
384919cb3738Sbellard {
385019cb3738Sbellard     BlockDriver *drv = bs->drv;
385119cb3738Sbellard 
3852822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
3853822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
385419cb3738Sbellard     }
38556f382ed2SLuiz Capitulino 
38566f382ed2SLuiz Capitulino     if (bs->device_name[0] != '\0') {
38576f382ed2SLuiz Capitulino         bdrv_emit_qmp_eject_event(bs, eject_flag);
38586f382ed2SLuiz Capitulino     }
385919cb3738Sbellard }
386019cb3738Sbellard 
386119cb3738Sbellard /**
386219cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
386319cb3738Sbellard  * to eject it manually).
386419cb3738Sbellard  */
3865025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
386619cb3738Sbellard {
386719cb3738Sbellard     BlockDriver *drv = bs->drv;
386819cb3738Sbellard 
3869025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
3870b8c6d095SStefan Hajnoczi 
3871025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
3872025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
387319cb3738Sbellard     }
387419cb3738Sbellard }
3875985a03b0Sths 
3876985a03b0Sths /* needed for generic scsi interface */
3877985a03b0Sths 
3878985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3879985a03b0Sths {
3880985a03b0Sths     BlockDriver *drv = bs->drv;
3881985a03b0Sths 
3882985a03b0Sths     if (drv && drv->bdrv_ioctl)
3883985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
3884985a03b0Sths     return -ENOTSUP;
3885985a03b0Sths }
38867d780669Saliguori 
3887221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
3888221f715dSaliguori         unsigned long int req, void *buf,
38897d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
38907d780669Saliguori {
3891221f715dSaliguori     BlockDriver *drv = bs->drv;
38927d780669Saliguori 
3893221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
3894221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
3895221f715dSaliguori     return NULL;
38967d780669Saliguori }
3897e268ca52Saliguori 
38987b6f9300SMarkus Armbruster void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
38997b6f9300SMarkus Armbruster {
39007b6f9300SMarkus Armbruster     bs->buffer_alignment = align;
39017b6f9300SMarkus Armbruster }
39027cd1e32aSlirans@il.ibm.com 
3903e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
3904e268ca52Saliguori {
3905e268ca52Saliguori     return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
3906e268ca52Saliguori }
39077cd1e32aSlirans@il.ibm.com 
39087cd1e32aSlirans@il.ibm.com void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
39097cd1e32aSlirans@il.ibm.com {
39107cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
3911a55eb92cSJan Kiszka 
3912aaa0eb75SLiran Schour     bs->dirty_count = 0;
39137cd1e32aSlirans@il.ibm.com     if (enable) {
3914c6d22830SJan Kiszka         if (!bs->dirty_bitmap) {
3915c6d22830SJan Kiszka             bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
391671df14fcSPaolo Bonzini                     BDRV_SECTORS_PER_DIRTY_CHUNK * BITS_PER_LONG - 1;
391771df14fcSPaolo Bonzini             bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * BITS_PER_LONG;
39187cd1e32aSlirans@il.ibm.com 
391971df14fcSPaolo Bonzini             bs->dirty_bitmap = g_new0(unsigned long, bitmap_size);
39207cd1e32aSlirans@il.ibm.com         }
39217cd1e32aSlirans@il.ibm.com     } else {
3922c6d22830SJan Kiszka         if (bs->dirty_bitmap) {
39237267c094SAnthony Liguori             g_free(bs->dirty_bitmap);
3924c6d22830SJan Kiszka             bs->dirty_bitmap = NULL;
39257cd1e32aSlirans@il.ibm.com         }
39267cd1e32aSlirans@il.ibm.com     }
39277cd1e32aSlirans@il.ibm.com }
39287cd1e32aSlirans@il.ibm.com 
39297cd1e32aSlirans@il.ibm.com int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
39307cd1e32aSlirans@il.ibm.com {
39316ea44308SJan Kiszka     int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
39327cd1e32aSlirans@il.ibm.com 
3933c6d22830SJan Kiszka     if (bs->dirty_bitmap &&
3934c6d22830SJan Kiszka         (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
39356d59fec1SMarcelo Tosatti         return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
39366d59fec1SMarcelo Tosatti             (1UL << (chunk % (sizeof(unsigned long) * 8))));
39377cd1e32aSlirans@il.ibm.com     } else {
39387cd1e32aSlirans@il.ibm.com         return 0;
39397cd1e32aSlirans@il.ibm.com     }
39407cd1e32aSlirans@il.ibm.com }
39417cd1e32aSlirans@il.ibm.com 
39427cd1e32aSlirans@il.ibm.com void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
39437cd1e32aSlirans@il.ibm.com                       int nr_sectors)
39447cd1e32aSlirans@il.ibm.com {
39457cd1e32aSlirans@il.ibm.com     set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
39467cd1e32aSlirans@il.ibm.com }
3947aaa0eb75SLiran Schour 
3948aaa0eb75SLiran Schour int64_t bdrv_get_dirty_count(BlockDriverState *bs)
3949aaa0eb75SLiran Schour {
3950aaa0eb75SLiran Schour     return bs->dirty_count;
3951aaa0eb75SLiran Schour }
3952f88e1a42SJes Sorensen 
3953db593f25SMarcelo Tosatti void bdrv_set_in_use(BlockDriverState *bs, int in_use)
3954db593f25SMarcelo Tosatti {
3955db593f25SMarcelo Tosatti     assert(bs->in_use != in_use);
3956db593f25SMarcelo Tosatti     bs->in_use = in_use;
3957db593f25SMarcelo Tosatti }
3958db593f25SMarcelo Tosatti 
3959db593f25SMarcelo Tosatti int bdrv_in_use(BlockDriverState *bs)
3960db593f25SMarcelo Tosatti {
3961db593f25SMarcelo Tosatti     return bs->in_use;
3962db593f25SMarcelo Tosatti }
3963db593f25SMarcelo Tosatti 
396428a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
396528a7282aSLuiz Capitulino {
3966d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
396758e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
396828a7282aSLuiz Capitulino }
396928a7282aSLuiz Capitulino 
397028a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
397128a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
397228a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
397328a7282aSLuiz Capitulino {
3974d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
397528a7282aSLuiz Capitulino            (bs->on_write_error == BLOCK_ERR_STOP_ENOSPC ||
397628a7282aSLuiz Capitulino             bs->on_write_error == BLOCK_ERR_STOP_ANY    ||
397728a7282aSLuiz Capitulino             bs->on_read_error == BLOCK_ERR_STOP_ANY));
397828a7282aSLuiz Capitulino }
397928a7282aSLuiz Capitulino 
398028a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
398128a7282aSLuiz Capitulino {
3982d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
398328a7282aSLuiz Capitulino }
398428a7282aSLuiz Capitulino 
398528a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
398628a7282aSLuiz Capitulino {
398728a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
398858e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
398928a7282aSLuiz Capitulino     }
399028a7282aSLuiz Capitulino }
399128a7282aSLuiz Capitulino 
399228a7282aSLuiz Capitulino /* XXX: Today this is set by device models because it makes the implementation
399328a7282aSLuiz Capitulino    quite simple. However, the block layer knows about the error, so it's
399428a7282aSLuiz Capitulino    possible to implement this without device models being involved */
399528a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
399628a7282aSLuiz Capitulino {
399758e21ef5SLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs) &&
399858e21ef5SLuiz Capitulino         bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
399928a7282aSLuiz Capitulino         assert(error >= 0);
400058e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
400158e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
400228a7282aSLuiz Capitulino     }
400328a7282aSLuiz Capitulino }
400428a7282aSLuiz Capitulino 
4005a597e79cSChristoph Hellwig void
4006a597e79cSChristoph Hellwig bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
4007a597e79cSChristoph Hellwig         enum BlockAcctType type)
4008a597e79cSChristoph Hellwig {
4009a597e79cSChristoph Hellwig     assert(type < BDRV_MAX_IOTYPE);
4010a597e79cSChristoph Hellwig 
4011a597e79cSChristoph Hellwig     cookie->bytes = bytes;
4012c488c7f6SChristoph Hellwig     cookie->start_time_ns = get_clock();
4013a597e79cSChristoph Hellwig     cookie->type = type;
4014a597e79cSChristoph Hellwig }
4015a597e79cSChristoph Hellwig 
4016a597e79cSChristoph Hellwig void
4017a597e79cSChristoph Hellwig bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
4018a597e79cSChristoph Hellwig {
4019a597e79cSChristoph Hellwig     assert(cookie->type < BDRV_MAX_IOTYPE);
4020a597e79cSChristoph Hellwig 
4021a597e79cSChristoph Hellwig     bs->nr_bytes[cookie->type] += cookie->bytes;
4022a597e79cSChristoph Hellwig     bs->nr_ops[cookie->type]++;
4023c488c7f6SChristoph Hellwig     bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
4024a597e79cSChristoph Hellwig }
4025a597e79cSChristoph Hellwig 
4026f88e1a42SJes Sorensen int bdrv_img_create(const char *filename, const char *fmt,
4027f88e1a42SJes Sorensen                     const char *base_filename, const char *base_fmt,
4028f88e1a42SJes Sorensen                     char *options, uint64_t img_size, int flags)
4029f88e1a42SJes Sorensen {
4030f88e1a42SJes Sorensen     QEMUOptionParameter *param = NULL, *create_options = NULL;
4031d220894eSKevin Wolf     QEMUOptionParameter *backing_fmt, *backing_file, *size;
4032f88e1a42SJes Sorensen     BlockDriverState *bs = NULL;
4033f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
403496df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
4035f88e1a42SJes Sorensen     int ret = 0;
4036f88e1a42SJes Sorensen 
4037f88e1a42SJes Sorensen     /* Find driver and parse its options */
4038f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
4039f88e1a42SJes Sorensen     if (!drv) {
4040f88e1a42SJes Sorensen         error_report("Unknown file format '%s'", fmt);
40414f70f249SJes Sorensen         ret = -EINVAL;
4042f88e1a42SJes Sorensen         goto out;
4043f88e1a42SJes Sorensen     }
4044f88e1a42SJes Sorensen 
4045f88e1a42SJes Sorensen     proto_drv = bdrv_find_protocol(filename);
4046f88e1a42SJes Sorensen     if (!proto_drv) {
4047f88e1a42SJes Sorensen         error_report("Unknown protocol '%s'", filename);
40484f70f249SJes Sorensen         ret = -EINVAL;
4049f88e1a42SJes Sorensen         goto out;
4050f88e1a42SJes Sorensen     }
4051f88e1a42SJes Sorensen 
4052f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
4053f88e1a42SJes Sorensen                                               drv->create_options);
4054f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
4055f88e1a42SJes Sorensen                                               proto_drv->create_options);
4056f88e1a42SJes Sorensen 
4057f88e1a42SJes Sorensen     /* Create parameter list with default values */
4058f88e1a42SJes Sorensen     param = parse_option_parameters("", create_options, param);
4059f88e1a42SJes Sorensen 
4060f88e1a42SJes Sorensen     set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
4061f88e1a42SJes Sorensen 
4062f88e1a42SJes Sorensen     /* Parse -o options */
4063f88e1a42SJes Sorensen     if (options) {
4064f88e1a42SJes Sorensen         param = parse_option_parameters(options, create_options, param);
4065f88e1a42SJes Sorensen         if (param == NULL) {
4066f88e1a42SJes Sorensen             error_report("Invalid options for file format '%s'.", fmt);
40674f70f249SJes Sorensen             ret = -EINVAL;
4068f88e1a42SJes Sorensen             goto out;
4069f88e1a42SJes Sorensen         }
4070f88e1a42SJes Sorensen     }
4071f88e1a42SJes Sorensen 
4072f88e1a42SJes Sorensen     if (base_filename) {
4073f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
4074f88e1a42SJes Sorensen                                  base_filename)) {
4075f88e1a42SJes Sorensen             error_report("Backing file not supported for file format '%s'",
4076f88e1a42SJes Sorensen                          fmt);
40774f70f249SJes Sorensen             ret = -EINVAL;
4078f88e1a42SJes Sorensen             goto out;
4079f88e1a42SJes Sorensen         }
4080f88e1a42SJes Sorensen     }
4081f88e1a42SJes Sorensen 
4082f88e1a42SJes Sorensen     if (base_fmt) {
4083f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
4084f88e1a42SJes Sorensen             error_report("Backing file format not supported for file "
4085f88e1a42SJes Sorensen                          "format '%s'", fmt);
40864f70f249SJes Sorensen             ret = -EINVAL;
4087f88e1a42SJes Sorensen             goto out;
4088f88e1a42SJes Sorensen         }
4089f88e1a42SJes Sorensen     }
4090f88e1a42SJes Sorensen 
4091792da93aSJes Sorensen     backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
4092792da93aSJes Sorensen     if (backing_file && backing_file->value.s) {
4093792da93aSJes Sorensen         if (!strcmp(filename, backing_file->value.s)) {
4094792da93aSJes Sorensen             error_report("Error: Trying to create an image with the "
4095792da93aSJes Sorensen                          "same filename as the backing file");
40964f70f249SJes Sorensen             ret = -EINVAL;
4097792da93aSJes Sorensen             goto out;
4098792da93aSJes Sorensen         }
4099792da93aSJes Sorensen     }
4100792da93aSJes Sorensen 
4101f88e1a42SJes Sorensen     backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
4102f88e1a42SJes Sorensen     if (backing_fmt && backing_fmt->value.s) {
410396df67d1SStefan Hajnoczi         backing_drv = bdrv_find_format(backing_fmt->value.s);
410496df67d1SStefan Hajnoczi         if (!backing_drv) {
4105f88e1a42SJes Sorensen             error_report("Unknown backing file format '%s'",
4106f88e1a42SJes Sorensen                          backing_fmt->value.s);
41074f70f249SJes Sorensen             ret = -EINVAL;
4108f88e1a42SJes Sorensen             goto out;
4109f88e1a42SJes Sorensen         }
4110f88e1a42SJes Sorensen     }
4111f88e1a42SJes Sorensen 
4112f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
4113f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
4114d220894eSKevin Wolf     size = get_option_parameter(param, BLOCK_OPT_SIZE);
4115d220894eSKevin Wolf     if (size && size->value.n == -1) {
4116f88e1a42SJes Sorensen         if (backing_file && backing_file->value.s) {
4117f88e1a42SJes Sorensen             uint64_t size;
4118f88e1a42SJes Sorensen             char buf[32];
411963090dacSPaolo Bonzini             int back_flags;
412063090dacSPaolo Bonzini 
412163090dacSPaolo Bonzini             /* backing files always opened read-only */
412263090dacSPaolo Bonzini             back_flags =
412363090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
4124f88e1a42SJes Sorensen 
4125f88e1a42SJes Sorensen             bs = bdrv_new("");
4126f88e1a42SJes Sorensen 
412763090dacSPaolo Bonzini             ret = bdrv_open(bs, backing_file->value.s, back_flags, backing_drv);
4128f88e1a42SJes Sorensen             if (ret < 0) {
412996df67d1SStefan Hajnoczi                 error_report("Could not open '%s'", backing_file->value.s);
4130f88e1a42SJes Sorensen                 goto out;
4131f88e1a42SJes Sorensen             }
4132f88e1a42SJes Sorensen             bdrv_get_geometry(bs, &size);
4133f88e1a42SJes Sorensen             size *= 512;
4134f88e1a42SJes Sorensen 
4135f88e1a42SJes Sorensen             snprintf(buf, sizeof(buf), "%" PRId64, size);
4136f88e1a42SJes Sorensen             set_option_parameter(param, BLOCK_OPT_SIZE, buf);
4137f88e1a42SJes Sorensen         } else {
4138f88e1a42SJes Sorensen             error_report("Image creation needs a size parameter");
41394f70f249SJes Sorensen             ret = -EINVAL;
4140f88e1a42SJes Sorensen             goto out;
4141f88e1a42SJes Sorensen         }
4142f88e1a42SJes Sorensen     }
4143f88e1a42SJes Sorensen 
4144f88e1a42SJes Sorensen     printf("Formatting '%s', fmt=%s ", filename, fmt);
4145f88e1a42SJes Sorensen     print_option_parameters(param);
4146f88e1a42SJes Sorensen     puts("");
4147f88e1a42SJes Sorensen 
4148f88e1a42SJes Sorensen     ret = bdrv_create(drv, filename, param);
4149f88e1a42SJes Sorensen 
4150f88e1a42SJes Sorensen     if (ret < 0) {
4151f88e1a42SJes Sorensen         if (ret == -ENOTSUP) {
4152f88e1a42SJes Sorensen             error_report("Formatting or formatting option not supported for "
4153f88e1a42SJes Sorensen                          "file format '%s'", fmt);
4154f88e1a42SJes Sorensen         } else if (ret == -EFBIG) {
4155f88e1a42SJes Sorensen             error_report("The image size is too large for file format '%s'",
4156f88e1a42SJes Sorensen                          fmt);
4157f88e1a42SJes Sorensen         } else {
4158f88e1a42SJes Sorensen             error_report("%s: error while creating %s: %s", filename, fmt,
4159f88e1a42SJes Sorensen                          strerror(-ret));
4160f88e1a42SJes Sorensen         }
4161f88e1a42SJes Sorensen     }
4162f88e1a42SJes Sorensen 
4163f88e1a42SJes Sorensen out:
4164f88e1a42SJes Sorensen     free_option_parameters(create_options);
4165f88e1a42SJes Sorensen     free_option_parameters(param);
4166f88e1a42SJes Sorensen 
4167f88e1a42SJes Sorensen     if (bs) {
4168f88e1a42SJes Sorensen         bdrv_delete(bs);
4169f88e1a42SJes Sorensen     }
41704f70f249SJes Sorensen 
41714f70f249SJes Sorensen     return ret;
4172f88e1a42SJes Sorensen }
4173eeec61f2SStefan Hajnoczi 
4174eeec61f2SStefan Hajnoczi void *block_job_create(const BlockJobType *job_type, BlockDriverState *bs,
4175c83c66c3SStefan Hajnoczi                        int64_t speed, BlockDriverCompletionFunc *cb,
4176c83c66c3SStefan Hajnoczi                        void *opaque, Error **errp)
4177eeec61f2SStefan Hajnoczi {
4178eeec61f2SStefan Hajnoczi     BlockJob *job;
4179eeec61f2SStefan Hajnoczi 
4180eeec61f2SStefan Hajnoczi     if (bs->job || bdrv_in_use(bs)) {
4181fd7f8c65SStefan Hajnoczi         error_set(errp, QERR_DEVICE_IN_USE, bdrv_get_device_name(bs));
4182eeec61f2SStefan Hajnoczi         return NULL;
4183eeec61f2SStefan Hajnoczi     }
4184eeec61f2SStefan Hajnoczi     bdrv_set_in_use(bs, 1);
4185eeec61f2SStefan Hajnoczi 
4186eeec61f2SStefan Hajnoczi     job = g_malloc0(job_type->instance_size);
4187eeec61f2SStefan Hajnoczi     job->job_type      = job_type;
4188eeec61f2SStefan Hajnoczi     job->bs            = bs;
4189eeec61f2SStefan Hajnoczi     job->cb            = cb;
4190eeec61f2SStefan Hajnoczi     job->opaque        = opaque;
41914513eafeSPaolo Bonzini     job->busy          = true;
4192eeec61f2SStefan Hajnoczi     bs->job = job;
4193c83c66c3SStefan Hajnoczi 
4194c83c66c3SStefan Hajnoczi     /* Only set speed when necessary to avoid NotSupported error */
4195c83c66c3SStefan Hajnoczi     if (speed != 0) {
4196c83c66c3SStefan Hajnoczi         Error *local_err = NULL;
4197c83c66c3SStefan Hajnoczi 
4198c83c66c3SStefan Hajnoczi         block_job_set_speed(job, speed, &local_err);
4199c83c66c3SStefan Hajnoczi         if (error_is_set(&local_err)) {
4200c83c66c3SStefan Hajnoczi             bs->job = NULL;
4201c83c66c3SStefan Hajnoczi             g_free(job);
4202c83c66c3SStefan Hajnoczi             bdrv_set_in_use(bs, 0);
4203c83c66c3SStefan Hajnoczi             error_propagate(errp, local_err);
4204c83c66c3SStefan Hajnoczi             return NULL;
4205c83c66c3SStefan Hajnoczi         }
4206c83c66c3SStefan Hajnoczi     }
4207eeec61f2SStefan Hajnoczi     return job;
4208eeec61f2SStefan Hajnoczi }
4209eeec61f2SStefan Hajnoczi 
4210eeec61f2SStefan Hajnoczi void block_job_complete(BlockJob *job, int ret)
4211eeec61f2SStefan Hajnoczi {
4212eeec61f2SStefan Hajnoczi     BlockDriverState *bs = job->bs;
4213eeec61f2SStefan Hajnoczi 
4214eeec61f2SStefan Hajnoczi     assert(bs->job == job);
4215eeec61f2SStefan Hajnoczi     job->cb(job->opaque, ret);
4216eeec61f2SStefan Hajnoczi     bs->job = NULL;
4217eeec61f2SStefan Hajnoczi     g_free(job);
4218eeec61f2SStefan Hajnoczi     bdrv_set_in_use(bs, 0);
4219eeec61f2SStefan Hajnoczi }
4220eeec61f2SStefan Hajnoczi 
4221882ec7ceSStefan Hajnoczi void block_job_set_speed(BlockJob *job, int64_t speed, Error **errp)
4222eeec61f2SStefan Hajnoczi {
42239e6636c7SStefan Hajnoczi     Error *local_err = NULL;
42249f25ecccSPaolo Bonzini 
4225eeec61f2SStefan Hajnoczi     if (!job->job_type->set_speed) {
42269e6636c7SStefan Hajnoczi         error_set(errp, QERR_NOT_SUPPORTED);
42279e6636c7SStefan Hajnoczi         return;
4228eeec61f2SStefan Hajnoczi     }
4229882ec7ceSStefan Hajnoczi     job->job_type->set_speed(job, speed, &local_err);
42309e6636c7SStefan Hajnoczi     if (error_is_set(&local_err)) {
42319e6636c7SStefan Hajnoczi         error_propagate(errp, local_err);
42329e6636c7SStefan Hajnoczi         return;
42339e6636c7SStefan Hajnoczi     }
42349e6636c7SStefan Hajnoczi 
4235882ec7ceSStefan Hajnoczi     job->speed = speed;
42369f25ecccSPaolo Bonzini }
4237eeec61f2SStefan Hajnoczi 
4238eeec61f2SStefan Hajnoczi void block_job_cancel(BlockJob *job)
4239eeec61f2SStefan Hajnoczi {
4240eeec61f2SStefan Hajnoczi     job->cancelled = true;
4241*fa4478d5SPaolo Bonzini     if (job->co && !job->busy) {
4242*fa4478d5SPaolo Bonzini         qemu_coroutine_enter(job->co, NULL);
4243*fa4478d5SPaolo Bonzini     }
4244eeec61f2SStefan Hajnoczi }
4245eeec61f2SStefan Hajnoczi 
4246eeec61f2SStefan Hajnoczi bool block_job_is_cancelled(BlockJob *job)
4247eeec61f2SStefan Hajnoczi {
4248eeec61f2SStefan Hajnoczi     return job->cancelled;
4249eeec61f2SStefan Hajnoczi }
42503e914655SPaolo Bonzini 
4251*fa4478d5SPaolo Bonzini struct BlockCancelData {
4252*fa4478d5SPaolo Bonzini     BlockJob *job;
4253*fa4478d5SPaolo Bonzini     BlockDriverCompletionFunc *cb;
4254*fa4478d5SPaolo Bonzini     void *opaque;
4255*fa4478d5SPaolo Bonzini     bool cancelled;
4256*fa4478d5SPaolo Bonzini     int ret;
4257*fa4478d5SPaolo Bonzini };
4258*fa4478d5SPaolo Bonzini 
4259*fa4478d5SPaolo Bonzini static void block_job_cancel_cb(void *opaque, int ret)
42603e914655SPaolo Bonzini {
4261*fa4478d5SPaolo Bonzini     struct BlockCancelData *data = opaque;
4262*fa4478d5SPaolo Bonzini 
4263*fa4478d5SPaolo Bonzini     data->cancelled = block_job_is_cancelled(data->job);
4264*fa4478d5SPaolo Bonzini     data->ret = ret;
4265*fa4478d5SPaolo Bonzini     data->cb(data->opaque, ret);
4266*fa4478d5SPaolo Bonzini }
4267*fa4478d5SPaolo Bonzini 
4268*fa4478d5SPaolo Bonzini int block_job_cancel_sync(BlockJob *job)
4269*fa4478d5SPaolo Bonzini {
4270*fa4478d5SPaolo Bonzini     struct BlockCancelData data;
42713e914655SPaolo Bonzini     BlockDriverState *bs = job->bs;
42723e914655SPaolo Bonzini 
42733e914655SPaolo Bonzini     assert(bs->job == job);
4274*fa4478d5SPaolo Bonzini 
4275*fa4478d5SPaolo Bonzini     /* Set up our own callback to store the result and chain to
4276*fa4478d5SPaolo Bonzini      * the original callback.
4277*fa4478d5SPaolo Bonzini      */
4278*fa4478d5SPaolo Bonzini     data.job = job;
4279*fa4478d5SPaolo Bonzini     data.cb = job->cb;
4280*fa4478d5SPaolo Bonzini     data.opaque = job->opaque;
4281*fa4478d5SPaolo Bonzini     data.ret = -EINPROGRESS;
4282*fa4478d5SPaolo Bonzini     job->cb = block_job_cancel_cb;
4283*fa4478d5SPaolo Bonzini     job->opaque = &data;
42843e914655SPaolo Bonzini     block_job_cancel(job);
4285*fa4478d5SPaolo Bonzini     while (data.ret == -EINPROGRESS) {
42863e914655SPaolo Bonzini         qemu_aio_wait();
42873e914655SPaolo Bonzini     }
4288*fa4478d5SPaolo Bonzini     return (data.cancelled && data.ret == 0) ? -ECANCELED : data.ret;
42893e914655SPaolo Bonzini }
42904513eafeSPaolo Bonzini 
42914513eafeSPaolo Bonzini void block_job_sleep_ns(BlockJob *job, QEMUClock *clock, int64_t ns)
42924513eafeSPaolo Bonzini {
42934513eafeSPaolo Bonzini     /* Check cancellation *before* setting busy = false, too!  */
42944513eafeSPaolo Bonzini     if (!block_job_is_cancelled(job)) {
42954513eafeSPaolo Bonzini         job->busy = false;
42964513eafeSPaolo Bonzini         co_sleep_ns(clock, ns);
42974513eafeSPaolo Bonzini         job->busy = true;
42984513eafeSPaolo Bonzini     }
42994513eafeSPaolo Bonzini }
4300