xref: /openbmc/qemu/block.c (revision fd7f8c65377ee918479e43b38d44f54f13aa6548)
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 
3440e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
3450e7e1989SKevin Wolf     QEMUOptionParameter *options)
346ea2384d3Sbellard {
347ea2384d3Sbellard     if (!drv->bdrv_create)
348ea2384d3Sbellard         return -ENOTSUP;
3490e7e1989SKevin Wolf 
3500e7e1989SKevin Wolf     return drv->bdrv_create(filename, options);
351ea2384d3Sbellard }
352ea2384d3Sbellard 
35384a12e66SChristoph Hellwig int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
35484a12e66SChristoph Hellwig {
35584a12e66SChristoph Hellwig     BlockDriver *drv;
35684a12e66SChristoph Hellwig 
357b50cbabcSMORITA Kazutaka     drv = bdrv_find_protocol(filename);
35884a12e66SChristoph Hellwig     if (drv == NULL) {
35916905d71SStefan Hajnoczi         return -ENOENT;
36084a12e66SChristoph Hellwig     }
36184a12e66SChristoph Hellwig 
36284a12e66SChristoph Hellwig     return bdrv_create(drv, filename, options);
36384a12e66SChristoph Hellwig }
36484a12e66SChristoph Hellwig 
365d5249393Sbellard #ifdef _WIN32
36695389c86Sbellard void get_tmp_filename(char *filename, int size)
367d5249393Sbellard {
3683b9f94e1Sbellard     char temp_dir[MAX_PATH];
3693b9f94e1Sbellard 
3703b9f94e1Sbellard     GetTempPath(MAX_PATH, temp_dir);
3713b9f94e1Sbellard     GetTempFileName(temp_dir, "qem", 0, filename);
372d5249393Sbellard }
373d5249393Sbellard #else
37495389c86Sbellard void get_tmp_filename(char *filename, int size)
375ea2384d3Sbellard {
376ea2384d3Sbellard     int fd;
3777ccfb2ebSblueswir1     const char *tmpdir;
378d5249393Sbellard     /* XXX: race condition possible */
3790badc1eeSaurel32     tmpdir = getenv("TMPDIR");
3800badc1eeSaurel32     if (!tmpdir)
3810badc1eeSaurel32         tmpdir = "/tmp";
3820badc1eeSaurel32     snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
383ea2384d3Sbellard     fd = mkstemp(filename);
384ea2384d3Sbellard     close(fd);
385ea2384d3Sbellard }
386d5249393Sbellard #endif
387ea2384d3Sbellard 
388f3a5d3f8SChristoph Hellwig /*
389f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
390f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
391f3a5d3f8SChristoph Hellwig  */
392f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
393f3a5d3f8SChristoph Hellwig {
394508c7cb3SChristoph Hellwig     int score_max = 0, score;
395508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
396f3a5d3f8SChristoph Hellwig 
3978a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
398508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
399508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
400508c7cb3SChristoph Hellwig             if (score > score_max) {
401508c7cb3SChristoph Hellwig                 score_max = score;
402508c7cb3SChristoph Hellwig                 drv = d;
403f3a5d3f8SChristoph Hellwig             }
404508c7cb3SChristoph Hellwig         }
405f3a5d3f8SChristoph Hellwig     }
406f3a5d3f8SChristoph Hellwig 
407508c7cb3SChristoph Hellwig     return drv;
408f3a5d3f8SChristoph Hellwig }
409f3a5d3f8SChristoph Hellwig 
410b50cbabcSMORITA Kazutaka BlockDriver *bdrv_find_protocol(const char *filename)
41184a12e66SChristoph Hellwig {
41284a12e66SChristoph Hellwig     BlockDriver *drv1;
41384a12e66SChristoph Hellwig     char protocol[128];
41484a12e66SChristoph Hellwig     int len;
41584a12e66SChristoph Hellwig     const char *p;
41684a12e66SChristoph Hellwig 
41766f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
41866f82ceeSKevin Wolf 
41939508e7aSChristoph Hellwig     /*
42039508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
42139508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
42239508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
42339508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
42439508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
42539508e7aSChristoph Hellwig      */
42684a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
42739508e7aSChristoph Hellwig     if (drv1) {
42884a12e66SChristoph Hellwig         return drv1;
42984a12e66SChristoph Hellwig     }
43039508e7aSChristoph Hellwig 
4319e0b22f4SStefan Hajnoczi     if (!path_has_protocol(filename)) {
43239508e7aSChristoph Hellwig         return bdrv_find_format("file");
43339508e7aSChristoph Hellwig     }
4349e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
4359e0b22f4SStefan Hajnoczi     assert(p != NULL);
43684a12e66SChristoph Hellwig     len = p - filename;
43784a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
43884a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
43984a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
44084a12e66SChristoph Hellwig     protocol[len] = '\0';
44184a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
44284a12e66SChristoph Hellwig         if (drv1->protocol_name &&
44384a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
44484a12e66SChristoph Hellwig             return drv1;
44584a12e66SChristoph Hellwig         }
44684a12e66SChristoph Hellwig     }
44784a12e66SChristoph Hellwig     return NULL;
44884a12e66SChristoph Hellwig }
44984a12e66SChristoph Hellwig 
450c98ac35dSStefan Weil static int find_image_format(const char *filename, BlockDriver **pdrv)
451ea2384d3Sbellard {
45283f64091Sbellard     int ret, score, score_max;
453ea2384d3Sbellard     BlockDriver *drv1, *drv;
45483f64091Sbellard     uint8_t buf[2048];
45583f64091Sbellard     BlockDriverState *bs;
456ea2384d3Sbellard 
457f5edb014SNaphtali Sprei     ret = bdrv_file_open(&bs, filename, 0);
458c98ac35dSStefan Weil     if (ret < 0) {
459c98ac35dSStefan Weil         *pdrv = NULL;
460c98ac35dSStefan Weil         return ret;
461c98ac35dSStefan Weil     }
462f8ea0b00SNicholas Bellinger 
46308a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
46408a00559SKevin Wolf     if (bs->sg || !bdrv_is_inserted(bs)) {
4651a396859SNicholas A. Bellinger         bdrv_delete(bs);
466c98ac35dSStefan Weil         drv = bdrv_find_format("raw");
467c98ac35dSStefan Weil         if (!drv) {
468c98ac35dSStefan Weil             ret = -ENOENT;
469c98ac35dSStefan Weil         }
470c98ac35dSStefan Weil         *pdrv = drv;
471c98ac35dSStefan Weil         return ret;
4721a396859SNicholas A. Bellinger     }
473f8ea0b00SNicholas Bellinger 
47483f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
47583f64091Sbellard     bdrv_delete(bs);
476ea2384d3Sbellard     if (ret < 0) {
477c98ac35dSStefan Weil         *pdrv = NULL;
478c98ac35dSStefan Weil         return ret;
479ea2384d3Sbellard     }
480ea2384d3Sbellard 
481ea2384d3Sbellard     score_max = 0;
48284a12e66SChristoph Hellwig     drv = NULL;
4838a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
48483f64091Sbellard         if (drv1->bdrv_probe) {
485ea2384d3Sbellard             score = drv1->bdrv_probe(buf, ret, filename);
486ea2384d3Sbellard             if (score > score_max) {
487ea2384d3Sbellard                 score_max = score;
488ea2384d3Sbellard                 drv = drv1;
489ea2384d3Sbellard             }
490ea2384d3Sbellard         }
49183f64091Sbellard     }
492c98ac35dSStefan Weil     if (!drv) {
493c98ac35dSStefan Weil         ret = -ENOENT;
494c98ac35dSStefan Weil     }
495c98ac35dSStefan Weil     *pdrv = drv;
496c98ac35dSStefan Weil     return ret;
497ea2384d3Sbellard }
498ea2384d3Sbellard 
49951762288SStefan Hajnoczi /**
50051762288SStefan Hajnoczi  * Set the current 'total_sectors' value
50151762288SStefan Hajnoczi  */
50251762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
50351762288SStefan Hajnoczi {
50451762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
50551762288SStefan Hajnoczi 
506396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
507396759adSNicholas Bellinger     if (bs->sg)
508396759adSNicholas Bellinger         return 0;
509396759adSNicholas Bellinger 
51051762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
51151762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
51251762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
51351762288SStefan Hajnoczi         if (length < 0) {
51451762288SStefan Hajnoczi             return length;
51551762288SStefan Hajnoczi         }
51651762288SStefan Hajnoczi         hint = length >> BDRV_SECTOR_BITS;
51751762288SStefan Hajnoczi     }
51851762288SStefan Hajnoczi 
51951762288SStefan Hajnoczi     bs->total_sectors = hint;
52051762288SStefan Hajnoczi     return 0;
52151762288SStefan Hajnoczi }
52251762288SStefan Hajnoczi 
523c3993cdcSStefan Hajnoczi /**
524c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
525c3993cdcSStefan Hajnoczi  *
526c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
527c3993cdcSStefan Hajnoczi  */
528c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
529c3993cdcSStefan Hajnoczi {
530c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
531c3993cdcSStefan Hajnoczi 
532c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
533c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
53492196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
53592196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
536c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
537c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
538c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
539c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
540c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
541c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
542c3993cdcSStefan Hajnoczi         /* this is the default */
543c3993cdcSStefan Hajnoczi     } else {
544c3993cdcSStefan Hajnoczi         return -1;
545c3993cdcSStefan Hajnoczi     }
546c3993cdcSStefan Hajnoczi 
547c3993cdcSStefan Hajnoczi     return 0;
548c3993cdcSStefan Hajnoczi }
549c3993cdcSStefan Hajnoczi 
55053fec9d3SStefan Hajnoczi /**
55153fec9d3SStefan Hajnoczi  * The copy-on-read flag is actually a reference count so multiple users may
55253fec9d3SStefan Hajnoczi  * use the feature without worrying about clobbering its previous state.
55353fec9d3SStefan Hajnoczi  * Copy-on-read stays enabled until all users have called to disable it.
55453fec9d3SStefan Hajnoczi  */
55553fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs)
55653fec9d3SStefan Hajnoczi {
55753fec9d3SStefan Hajnoczi     bs->copy_on_read++;
55853fec9d3SStefan Hajnoczi }
55953fec9d3SStefan Hajnoczi 
56053fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs)
56153fec9d3SStefan Hajnoczi {
56253fec9d3SStefan Hajnoczi     assert(bs->copy_on_read > 0);
56353fec9d3SStefan Hajnoczi     bs->copy_on_read--;
56453fec9d3SStefan Hajnoczi }
56553fec9d3SStefan Hajnoczi 
566b6ce07aaSKevin Wolf /*
56757915332SKevin Wolf  * Common part for opening disk images and files
56857915332SKevin Wolf  */
56957915332SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, const char *filename,
57057915332SKevin Wolf     int flags, BlockDriver *drv)
57157915332SKevin Wolf {
57257915332SKevin Wolf     int ret, open_flags;
57357915332SKevin Wolf 
57457915332SKevin Wolf     assert(drv != NULL);
57557915332SKevin Wolf 
57628dcee10SStefan Hajnoczi     trace_bdrv_open_common(bs, filename, flags, drv->format_name);
57728dcee10SStefan Hajnoczi 
57866f82ceeSKevin Wolf     bs->file = NULL;
57951762288SStefan Hajnoczi     bs->total_sectors = 0;
58057915332SKevin Wolf     bs->encrypted = 0;
58157915332SKevin Wolf     bs->valid_key = 0;
58203f541bdSStefan Hajnoczi     bs->sg = 0;
58357915332SKevin Wolf     bs->open_flags = flags;
58403f541bdSStefan Hajnoczi     bs->growable = 0;
58557915332SKevin Wolf     bs->buffer_alignment = 512;
58657915332SKevin Wolf 
58753fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
58853fec9d3SStefan Hajnoczi     if ((flags & BDRV_O_RDWR) && (flags & BDRV_O_COPY_ON_READ)) {
58953fec9d3SStefan Hajnoczi         bdrv_enable_copy_on_read(bs);
59053fec9d3SStefan Hajnoczi     }
59153fec9d3SStefan Hajnoczi 
59257915332SKevin Wolf     pstrcpy(bs->filename, sizeof(bs->filename), filename);
59303f541bdSStefan Hajnoczi     bs->backing_file[0] = '\0';
59457915332SKevin Wolf 
59557915332SKevin Wolf     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
59657915332SKevin Wolf         return -ENOTSUP;
59757915332SKevin Wolf     }
59857915332SKevin Wolf 
59957915332SKevin Wolf     bs->drv = drv;
6007267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
60157915332SKevin Wolf 
60203f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
60357915332SKevin Wolf 
60457915332SKevin Wolf     /*
60557915332SKevin Wolf      * Clear flags that are internal to the block layer before opening the
60657915332SKevin Wolf      * image.
60757915332SKevin Wolf      */
60857915332SKevin Wolf     open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
60957915332SKevin Wolf 
61057915332SKevin Wolf     /*
611ebabb67aSStefan Weil      * Snapshots should be writable.
61257915332SKevin Wolf      */
61357915332SKevin Wolf     if (bs->is_temporary) {
61457915332SKevin Wolf         open_flags |= BDRV_O_RDWR;
61557915332SKevin Wolf     }
61657915332SKevin Wolf 
617e7c63796SStefan Hajnoczi     bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
618e7c63796SStefan Hajnoczi 
61966f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
62066f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
62166f82ceeSKevin Wolf         ret = drv->bdrv_file_open(bs, filename, open_flags);
62266f82ceeSKevin Wolf     } else {
62366f82ceeSKevin Wolf         ret = bdrv_file_open(&bs->file, filename, open_flags);
62466f82ceeSKevin Wolf         if (ret >= 0) {
62566f82ceeSKevin Wolf             ret = drv->bdrv_open(bs, open_flags);
62666f82ceeSKevin Wolf         }
62766f82ceeSKevin Wolf     }
62866f82ceeSKevin Wolf 
62957915332SKevin Wolf     if (ret < 0) {
63057915332SKevin Wolf         goto free_and_fail;
63157915332SKevin Wolf     }
63257915332SKevin Wolf 
63351762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
63451762288SStefan Hajnoczi     if (ret < 0) {
63551762288SStefan Hajnoczi         goto free_and_fail;
63657915332SKevin Wolf     }
63751762288SStefan Hajnoczi 
63857915332SKevin Wolf #ifndef _WIN32
63957915332SKevin Wolf     if (bs->is_temporary) {
64057915332SKevin Wolf         unlink(filename);
64157915332SKevin Wolf     }
64257915332SKevin Wolf #endif
64357915332SKevin Wolf     return 0;
64457915332SKevin Wolf 
64557915332SKevin Wolf free_and_fail:
64666f82ceeSKevin Wolf     if (bs->file) {
64766f82ceeSKevin Wolf         bdrv_delete(bs->file);
64866f82ceeSKevin Wolf         bs->file = NULL;
64966f82ceeSKevin Wolf     }
6507267c094SAnthony Liguori     g_free(bs->opaque);
65157915332SKevin Wolf     bs->opaque = NULL;
65257915332SKevin Wolf     bs->drv = NULL;
65357915332SKevin Wolf     return ret;
65457915332SKevin Wolf }
65557915332SKevin Wolf 
65657915332SKevin Wolf /*
657b6ce07aaSKevin Wolf  * Opens a file using a protocol (file, host_device, nbd, ...)
658b6ce07aaSKevin Wolf  */
65983f64091Sbellard int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
660b338082bSbellard {
66183f64091Sbellard     BlockDriverState *bs;
6626db95603SChristoph Hellwig     BlockDriver *drv;
66383f64091Sbellard     int ret;
6643b0d4f61Sbellard 
665b50cbabcSMORITA Kazutaka     drv = bdrv_find_protocol(filename);
6666db95603SChristoph Hellwig     if (!drv) {
6676db95603SChristoph Hellwig         return -ENOENT;
6686db95603SChristoph Hellwig     }
6696db95603SChristoph Hellwig 
67083f64091Sbellard     bs = bdrv_new("");
671b6ce07aaSKevin Wolf     ret = bdrv_open_common(bs, filename, flags, drv);
67283f64091Sbellard     if (ret < 0) {
67383f64091Sbellard         bdrv_delete(bs);
67483f64091Sbellard         return ret;
6753b0d4f61Sbellard     }
67671d0770cSaliguori     bs->growable = 1;
67783f64091Sbellard     *pbs = bs;
67883f64091Sbellard     return 0;
6793b0d4f61Sbellard }
6803b0d4f61Sbellard 
681b6ce07aaSKevin Wolf /*
682b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
683b6ce07aaSKevin Wolf  */
684d6e9098eSKevin Wolf int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
685ea2384d3Sbellard               BlockDriver *drv)
686ea2384d3Sbellard {
687b6ce07aaSKevin Wolf     int ret;
6882b572816SKevin Wolf     char tmp_filename[PATH_MAX];
68933e3963eSbellard 
69083f64091Sbellard     if (flags & BDRV_O_SNAPSHOT) {
691ea2384d3Sbellard         BlockDriverState *bs1;
692ea2384d3Sbellard         int64_t total_size;
6937c96d46eSaliguori         int is_protocol = 0;
69491a073a9SKevin Wolf         BlockDriver *bdrv_qcow2;
69591a073a9SKevin Wolf         QEMUOptionParameter *options;
696b6ce07aaSKevin Wolf         char backing_filename[PATH_MAX];
69733e3963eSbellard 
698ea2384d3Sbellard         /* if snapshot, we create a temporary backing file and open it
699ea2384d3Sbellard            instead of opening 'filename' directly */
700ea2384d3Sbellard 
701ea2384d3Sbellard         /* if there is a backing file, use it */
702ea2384d3Sbellard         bs1 = bdrv_new("");
703d6e9098eSKevin Wolf         ret = bdrv_open(bs1, filename, 0, drv);
70451d7c00cSaliguori         if (ret < 0) {
705ea2384d3Sbellard             bdrv_delete(bs1);
70651d7c00cSaliguori             return ret;
707ea2384d3Sbellard         }
7083e82990bSJes Sorensen         total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
7097c96d46eSaliguori 
7107c96d46eSaliguori         if (bs1->drv && bs1->drv->protocol_name)
7117c96d46eSaliguori             is_protocol = 1;
7127c96d46eSaliguori 
713ea2384d3Sbellard         bdrv_delete(bs1);
714ea2384d3Sbellard 
715ea2384d3Sbellard         get_tmp_filename(tmp_filename, sizeof(tmp_filename));
7167c96d46eSaliguori 
7177c96d46eSaliguori         /* Real path is meaningless for protocols */
7187c96d46eSaliguori         if (is_protocol)
7197c96d46eSaliguori             snprintf(backing_filename, sizeof(backing_filename),
7207c96d46eSaliguori                      "%s", filename);
721114cdfa9SKirill A. Shutemov         else if (!realpath(filename, backing_filename))
722114cdfa9SKirill A. Shutemov             return -errno;
7237c96d46eSaliguori 
72491a073a9SKevin Wolf         bdrv_qcow2 = bdrv_find_format("qcow2");
72591a073a9SKevin Wolf         options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
72691a073a9SKevin Wolf 
7273e82990bSJes Sorensen         set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
72891a073a9SKevin Wolf         set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
72991a073a9SKevin Wolf         if (drv) {
73091a073a9SKevin Wolf             set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
73191a073a9SKevin Wolf                 drv->format_name);
73291a073a9SKevin Wolf         }
73391a073a9SKevin Wolf 
73491a073a9SKevin Wolf         ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
735d748768cSJan Kiszka         free_option_parameters(options);
73651d7c00cSaliguori         if (ret < 0) {
73751d7c00cSaliguori             return ret;
738ea2384d3Sbellard         }
73991a073a9SKevin Wolf 
740ea2384d3Sbellard         filename = tmp_filename;
74191a073a9SKevin Wolf         drv = bdrv_qcow2;
742ea2384d3Sbellard         bs->is_temporary = 1;
743ea2384d3Sbellard     }
744ea2384d3Sbellard 
745b6ce07aaSKevin Wolf     /* Find the right image format driver */
7466db95603SChristoph Hellwig     if (!drv) {
747c98ac35dSStefan Weil         ret = find_image_format(filename, &drv);
748ea2384d3Sbellard     }
7496987307cSChristoph Hellwig 
75051d7c00cSaliguori     if (!drv) {
75151d7c00cSaliguori         goto unlink_and_fail;
75283f64091Sbellard     }
753b6ce07aaSKevin Wolf 
754b6ce07aaSKevin Wolf     /* Open the image */
755b6ce07aaSKevin Wolf     ret = bdrv_open_common(bs, filename, flags, drv);
756b6ce07aaSKevin Wolf     if (ret < 0) {
7576987307cSChristoph Hellwig         goto unlink_and_fail;
7586987307cSChristoph Hellwig     }
7596987307cSChristoph Hellwig 
760b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
761b6ce07aaSKevin Wolf     if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
762b6ce07aaSKevin Wolf         char backing_filename[PATH_MAX];
763b6ce07aaSKevin Wolf         int back_flags;
764b6ce07aaSKevin Wolf         BlockDriver *back_drv = NULL;
765b6ce07aaSKevin Wolf 
766b6ce07aaSKevin Wolf         bs->backing_hd = bdrv_new("");
767df2dbb4aSStefan Hajnoczi 
768df2dbb4aSStefan Hajnoczi         if (path_has_protocol(bs->backing_file)) {
769df2dbb4aSStefan Hajnoczi             pstrcpy(backing_filename, sizeof(backing_filename),
770df2dbb4aSStefan Hajnoczi                     bs->backing_file);
771df2dbb4aSStefan Hajnoczi         } else {
772b6ce07aaSKevin Wolf             path_combine(backing_filename, sizeof(backing_filename),
773b6ce07aaSKevin Wolf                          filename, bs->backing_file);
774df2dbb4aSStefan Hajnoczi         }
775df2dbb4aSStefan Hajnoczi 
776df2dbb4aSStefan Hajnoczi         if (bs->backing_format[0] != '\0') {
777b6ce07aaSKevin Wolf             back_drv = bdrv_find_format(bs->backing_format);
778df2dbb4aSStefan Hajnoczi         }
779b6ce07aaSKevin Wolf 
780b6ce07aaSKevin Wolf         /* backing files always opened read-only */
781b6ce07aaSKevin Wolf         back_flags =
782b6ce07aaSKevin Wolf             flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
783b6ce07aaSKevin Wolf 
784b6ce07aaSKevin Wolf         ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
785b6ce07aaSKevin Wolf         if (ret < 0) {
786b6ce07aaSKevin Wolf             bdrv_close(bs);
787b6ce07aaSKevin Wolf             return ret;
788b6ce07aaSKevin Wolf         }
789b6ce07aaSKevin Wolf         if (bs->is_temporary) {
790b6ce07aaSKevin Wolf             bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
791b6ce07aaSKevin Wolf         } else {
792b6ce07aaSKevin Wolf             /* base image inherits from "parent" */
793b6ce07aaSKevin Wolf             bs->backing_hd->keep_read_only = bs->keep_read_only;
794b6ce07aaSKevin Wolf         }
795b6ce07aaSKevin Wolf     }
796b6ce07aaSKevin Wolf 
797b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
7987d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
799b6ce07aaSKevin Wolf     }
800b6ce07aaSKevin Wolf 
80198f90dbaSZhi Yong Wu     /* throttling disk I/O limits */
80298f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
80398f90dbaSZhi Yong Wu         bdrv_io_limits_enable(bs);
80498f90dbaSZhi Yong Wu     }
80598f90dbaSZhi Yong Wu 
806b6ce07aaSKevin Wolf     return 0;
807b6ce07aaSKevin Wolf 
808b6ce07aaSKevin Wolf unlink_and_fail:
809b6ce07aaSKevin Wolf     if (bs->is_temporary) {
810b6ce07aaSKevin Wolf         unlink(filename);
811b6ce07aaSKevin Wolf     }
812b6ce07aaSKevin Wolf     return ret;
813b6ce07aaSKevin Wolf }
814b6ce07aaSKevin Wolf 
815fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
816fc01f7e7Sbellard {
81780ccf93bSLiu Yuan     bdrv_flush(bs);
81819cb3738Sbellard     if (bs->drv) {
8193e914655SPaolo Bonzini         if (bs->job) {
8203e914655SPaolo Bonzini             block_job_cancel_sync(bs->job);
8213e914655SPaolo Bonzini         }
8227094f12fSKevin Wolf         bdrv_drain_all();
8237094f12fSKevin Wolf 
824f9092b10SMarkus Armbruster         if (bs == bs_snapshots) {
825f9092b10SMarkus Armbruster             bs_snapshots = NULL;
826f9092b10SMarkus Armbruster         }
827557df6acSStefan Hajnoczi         if (bs->backing_hd) {
828ea2384d3Sbellard             bdrv_delete(bs->backing_hd);
829557df6acSStefan Hajnoczi             bs->backing_hd = NULL;
830557df6acSStefan Hajnoczi         }
831ea2384d3Sbellard         bs->drv->bdrv_close(bs);
8327267c094SAnthony Liguori         g_free(bs->opaque);
833ea2384d3Sbellard #ifdef _WIN32
834ea2384d3Sbellard         if (bs->is_temporary) {
835ea2384d3Sbellard             unlink(bs->filename);
836ea2384d3Sbellard         }
83767b915a5Sbellard #endif
838ea2384d3Sbellard         bs->opaque = NULL;
839ea2384d3Sbellard         bs->drv = NULL;
84053fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
841b338082bSbellard 
84266f82ceeSKevin Wolf         if (bs->file != NULL) {
84366f82ceeSKevin Wolf             bdrv_close(bs->file);
84466f82ceeSKevin Wolf         }
84566f82ceeSKevin Wolf 
8467d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, false);
847b338082bSbellard     }
84898f90dbaSZhi Yong Wu 
84998f90dbaSZhi Yong Wu     /*throttling disk I/O limits*/
85098f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
85198f90dbaSZhi Yong Wu         bdrv_io_limits_disable(bs);
85298f90dbaSZhi Yong Wu     }
853b338082bSbellard }
854b338082bSbellard 
8552bc93fedSMORITA Kazutaka void bdrv_close_all(void)
8562bc93fedSMORITA Kazutaka {
8572bc93fedSMORITA Kazutaka     BlockDriverState *bs;
8582bc93fedSMORITA Kazutaka 
8592bc93fedSMORITA Kazutaka     QTAILQ_FOREACH(bs, &bdrv_states, list) {
8602bc93fedSMORITA Kazutaka         bdrv_close(bs);
8612bc93fedSMORITA Kazutaka     }
8622bc93fedSMORITA Kazutaka }
8632bc93fedSMORITA Kazutaka 
864922453bcSStefan Hajnoczi /*
865922453bcSStefan Hajnoczi  * Wait for pending requests to complete across all BlockDriverStates
866922453bcSStefan Hajnoczi  *
867922453bcSStefan Hajnoczi  * This function does not flush data to disk, use bdrv_flush_all() for that
868922453bcSStefan Hajnoczi  * after calling this function.
869922453bcSStefan Hajnoczi  */
870922453bcSStefan Hajnoczi void bdrv_drain_all(void)
871922453bcSStefan Hajnoczi {
872922453bcSStefan Hajnoczi     BlockDriverState *bs;
873922453bcSStefan Hajnoczi 
874922453bcSStefan Hajnoczi     qemu_aio_flush();
875922453bcSStefan Hajnoczi 
876922453bcSStefan Hajnoczi     /* If requests are still pending there is a bug somewhere */
877922453bcSStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
878922453bcSStefan Hajnoczi         assert(QLIST_EMPTY(&bs->tracked_requests));
879922453bcSStefan Hajnoczi         assert(qemu_co_queue_empty(&bs->throttled_reqs));
880922453bcSStefan Hajnoczi     }
881922453bcSStefan Hajnoczi }
882922453bcSStefan Hajnoczi 
883d22b2f41SRyan Harper /* make a BlockDriverState anonymous by removing from bdrv_state list.
884d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
885d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
886d22b2f41SRyan Harper {
887d22b2f41SRyan Harper     if (bs->device_name[0] != '\0') {
888d22b2f41SRyan Harper         QTAILQ_REMOVE(&bdrv_states, bs, list);
889d22b2f41SRyan Harper     }
890d22b2f41SRyan Harper     bs->device_name[0] = '\0';
891d22b2f41SRyan Harper }
892d22b2f41SRyan Harper 
8938802d1fdSJeff Cody /*
8948802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
8958802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
8968802d1fdSJeff Cody  *
8978802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
8988802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
8998802d1fdSJeff Cody  *
900f6801b83SJeff Cody  * bs_new is required to be anonymous.
901f6801b83SJeff Cody  *
9028802d1fdSJeff Cody  * This function does not create any image files.
9038802d1fdSJeff Cody  */
9048802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
9058802d1fdSJeff Cody {
9068802d1fdSJeff Cody     BlockDriverState tmp;
9078802d1fdSJeff Cody 
908f6801b83SJeff Cody     /* bs_new must be anonymous */
909f6801b83SJeff Cody     assert(bs_new->device_name[0] == '\0');
9108802d1fdSJeff Cody 
9118802d1fdSJeff Cody     tmp = *bs_new;
9128802d1fdSJeff Cody 
9138802d1fdSJeff Cody     /* there are some fields that need to stay on the top layer: */
9148802d1fdSJeff Cody 
9158802d1fdSJeff Cody     /* dev info */
9168802d1fdSJeff Cody     tmp.dev_ops           = bs_top->dev_ops;
9178802d1fdSJeff Cody     tmp.dev_opaque        = bs_top->dev_opaque;
9188802d1fdSJeff Cody     tmp.dev               = bs_top->dev;
9198802d1fdSJeff Cody     tmp.buffer_alignment  = bs_top->buffer_alignment;
9208802d1fdSJeff Cody     tmp.copy_on_read      = bs_top->copy_on_read;
9218802d1fdSJeff Cody 
9228802d1fdSJeff Cody     /* i/o timing parameters */
9238802d1fdSJeff Cody     tmp.slice_time        = bs_top->slice_time;
9248802d1fdSJeff Cody     tmp.slice_start       = bs_top->slice_start;
9258802d1fdSJeff Cody     tmp.slice_end         = bs_top->slice_end;
9268802d1fdSJeff Cody     tmp.io_limits         = bs_top->io_limits;
9278802d1fdSJeff Cody     tmp.io_base           = bs_top->io_base;
9288802d1fdSJeff Cody     tmp.throttled_reqs    = bs_top->throttled_reqs;
9298802d1fdSJeff Cody     tmp.block_timer       = bs_top->block_timer;
9308802d1fdSJeff Cody     tmp.io_limits_enabled = bs_top->io_limits_enabled;
9318802d1fdSJeff Cody 
9328802d1fdSJeff Cody     /* geometry */
9338802d1fdSJeff Cody     tmp.cyls              = bs_top->cyls;
9348802d1fdSJeff Cody     tmp.heads             = bs_top->heads;
9358802d1fdSJeff Cody     tmp.secs              = bs_top->secs;
9368802d1fdSJeff Cody     tmp.translation       = bs_top->translation;
9378802d1fdSJeff Cody 
9388802d1fdSJeff Cody     /* r/w error */
9398802d1fdSJeff Cody     tmp.on_read_error     = bs_top->on_read_error;
9408802d1fdSJeff Cody     tmp.on_write_error    = bs_top->on_write_error;
9418802d1fdSJeff Cody 
9428802d1fdSJeff Cody     /* i/o status */
9438802d1fdSJeff Cody     tmp.iostatus_enabled  = bs_top->iostatus_enabled;
9448802d1fdSJeff Cody     tmp.iostatus          = bs_top->iostatus;
9458802d1fdSJeff Cody 
9468802d1fdSJeff Cody     /* keep the same entry in bdrv_states */
9478802d1fdSJeff Cody     pstrcpy(tmp.device_name, sizeof(tmp.device_name), bs_top->device_name);
9488802d1fdSJeff Cody     tmp.list = bs_top->list;
9498802d1fdSJeff Cody 
9508802d1fdSJeff Cody     /* The contents of 'tmp' will become bs_top, as we are
9518802d1fdSJeff Cody      * swapping bs_new and bs_top contents. */
9528802d1fdSJeff Cody     tmp.backing_hd = bs_new;
9538802d1fdSJeff Cody     pstrcpy(tmp.backing_file, sizeof(tmp.backing_file), bs_top->filename);
954f6801b83SJeff Cody     bdrv_get_format(bs_top, tmp.backing_format, sizeof(tmp.backing_format));
9558802d1fdSJeff Cody 
9568802d1fdSJeff Cody     /* swap contents of the fixed new bs and the current top */
9578802d1fdSJeff Cody     *bs_new = *bs_top;
9588802d1fdSJeff Cody     *bs_top = tmp;
9598802d1fdSJeff Cody 
960f6801b83SJeff Cody     /* device_name[] was carried over from the old bs_top.  bs_new
961f6801b83SJeff Cody      * shouldn't be in bdrv_states, so we need to make device_name[]
962f6801b83SJeff Cody      * reflect the anonymity of bs_new
963f6801b83SJeff Cody      */
964f6801b83SJeff Cody     bs_new->device_name[0] = '\0';
965f6801b83SJeff Cody 
9668802d1fdSJeff Cody     /* clear the copied fields in the new backing file */
9678802d1fdSJeff Cody     bdrv_detach_dev(bs_new, bs_new->dev);
9688802d1fdSJeff Cody 
9698802d1fdSJeff Cody     qemu_co_queue_init(&bs_new->throttled_reqs);
9708802d1fdSJeff Cody     memset(&bs_new->io_base,   0, sizeof(bs_new->io_base));
9718802d1fdSJeff Cody     memset(&bs_new->io_limits, 0, sizeof(bs_new->io_limits));
9728802d1fdSJeff Cody     bdrv_iostatus_disable(bs_new);
9738802d1fdSJeff Cody 
9748802d1fdSJeff Cody     /* we don't use bdrv_io_limits_disable() for this, because we don't want
9758802d1fdSJeff Cody      * to affect or delete the block_timer, as it has been moved to bs_top */
9768802d1fdSJeff Cody     bs_new->io_limits_enabled = false;
9778802d1fdSJeff Cody     bs_new->block_timer       = NULL;
9788802d1fdSJeff Cody     bs_new->slice_time        = 0;
9798802d1fdSJeff Cody     bs_new->slice_start       = 0;
9808802d1fdSJeff Cody     bs_new->slice_end         = 0;
9818802d1fdSJeff Cody }
9828802d1fdSJeff Cody 
983b338082bSbellard void bdrv_delete(BlockDriverState *bs)
984b338082bSbellard {
985fa879d62SMarkus Armbruster     assert(!bs->dev);
9863e914655SPaolo Bonzini     assert(!bs->job);
9873e914655SPaolo Bonzini     assert(!bs->in_use);
98818846deeSMarkus Armbruster 
9891b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
990d22b2f41SRyan Harper     bdrv_make_anon(bs);
99134c6f050Saurel32 
992b338082bSbellard     bdrv_close(bs);
99366f82ceeSKevin Wolf     if (bs->file != NULL) {
99466f82ceeSKevin Wolf         bdrv_delete(bs->file);
99566f82ceeSKevin Wolf     }
99666f82ceeSKevin Wolf 
997f9092b10SMarkus Armbruster     assert(bs != bs_snapshots);
9987267c094SAnthony Liguori     g_free(bs);
999fc01f7e7Sbellard }
1000fc01f7e7Sbellard 
1001fa879d62SMarkus Armbruster int bdrv_attach_dev(BlockDriverState *bs, void *dev)
1002fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
100318846deeSMarkus Armbruster {
1004fa879d62SMarkus Armbruster     if (bs->dev) {
100518846deeSMarkus Armbruster         return -EBUSY;
100618846deeSMarkus Armbruster     }
1007fa879d62SMarkus Armbruster     bs->dev = dev;
100828a7282aSLuiz Capitulino     bdrv_iostatus_reset(bs);
100918846deeSMarkus Armbruster     return 0;
101018846deeSMarkus Armbruster }
101118846deeSMarkus Armbruster 
1012fa879d62SMarkus Armbruster /* TODO qdevified devices don't use this, remove when devices are qdevified */
1013fa879d62SMarkus Armbruster void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
101418846deeSMarkus Armbruster {
1015fa879d62SMarkus Armbruster     if (bdrv_attach_dev(bs, dev) < 0) {
1016fa879d62SMarkus Armbruster         abort();
1017fa879d62SMarkus Armbruster     }
1018fa879d62SMarkus Armbruster }
1019fa879d62SMarkus Armbruster 
1020fa879d62SMarkus Armbruster void bdrv_detach_dev(BlockDriverState *bs, void *dev)
1021fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
1022fa879d62SMarkus Armbruster {
1023fa879d62SMarkus Armbruster     assert(bs->dev == dev);
1024fa879d62SMarkus Armbruster     bs->dev = NULL;
10250e49de52SMarkus Armbruster     bs->dev_ops = NULL;
10260e49de52SMarkus Armbruster     bs->dev_opaque = NULL;
102729e05f20SMarkus Armbruster     bs->buffer_alignment = 512;
102818846deeSMarkus Armbruster }
102918846deeSMarkus Armbruster 
1030fa879d62SMarkus Armbruster /* TODO change to return DeviceState * when all users are qdevified */
1031fa879d62SMarkus Armbruster void *bdrv_get_attached_dev(BlockDriverState *bs)
103218846deeSMarkus Armbruster {
1033fa879d62SMarkus Armbruster     return bs->dev;
103418846deeSMarkus Armbruster }
103518846deeSMarkus Armbruster 
10360e49de52SMarkus Armbruster void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
10370e49de52SMarkus Armbruster                       void *opaque)
10380e49de52SMarkus Armbruster {
10390e49de52SMarkus Armbruster     bs->dev_ops = ops;
10400e49de52SMarkus Armbruster     bs->dev_opaque = opaque;
10412c6942faSMarkus Armbruster     if (bdrv_dev_has_removable_media(bs) && bs == bs_snapshots) {
10422c6942faSMarkus Armbruster         bs_snapshots = NULL;
10432c6942faSMarkus Armbruster     }
10440e49de52SMarkus Armbruster }
10450e49de52SMarkus Armbruster 
1046329c0a48SLuiz Capitulino void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
1047329c0a48SLuiz Capitulino                                BlockQMPEventAction action, int is_read)
1048329c0a48SLuiz Capitulino {
1049329c0a48SLuiz Capitulino     QObject *data;
1050329c0a48SLuiz Capitulino     const char *action_str;
1051329c0a48SLuiz Capitulino 
1052329c0a48SLuiz Capitulino     switch (action) {
1053329c0a48SLuiz Capitulino     case BDRV_ACTION_REPORT:
1054329c0a48SLuiz Capitulino         action_str = "report";
1055329c0a48SLuiz Capitulino         break;
1056329c0a48SLuiz Capitulino     case BDRV_ACTION_IGNORE:
1057329c0a48SLuiz Capitulino         action_str = "ignore";
1058329c0a48SLuiz Capitulino         break;
1059329c0a48SLuiz Capitulino     case BDRV_ACTION_STOP:
1060329c0a48SLuiz Capitulino         action_str = "stop";
1061329c0a48SLuiz Capitulino         break;
1062329c0a48SLuiz Capitulino     default:
1063329c0a48SLuiz Capitulino         abort();
1064329c0a48SLuiz Capitulino     }
1065329c0a48SLuiz Capitulino 
1066329c0a48SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1067329c0a48SLuiz Capitulino                               bdrv->device_name,
1068329c0a48SLuiz Capitulino                               action_str,
1069329c0a48SLuiz Capitulino                               is_read ? "read" : "write");
1070329c0a48SLuiz Capitulino     monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1071329c0a48SLuiz Capitulino 
1072329c0a48SLuiz Capitulino     qobject_decref(data);
1073329c0a48SLuiz Capitulino }
1074329c0a48SLuiz Capitulino 
10756f382ed2SLuiz Capitulino static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
10766f382ed2SLuiz Capitulino {
10776f382ed2SLuiz Capitulino     QObject *data;
10786f382ed2SLuiz Capitulino 
10796f382ed2SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
10806f382ed2SLuiz Capitulino                               bdrv_get_device_name(bs), ejected);
10816f382ed2SLuiz Capitulino     monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
10826f382ed2SLuiz Capitulino 
10836f382ed2SLuiz Capitulino     qobject_decref(data);
10846f382ed2SLuiz Capitulino }
10856f382ed2SLuiz Capitulino 
10867d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
10870e49de52SMarkus Armbruster {
1088145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->change_media_cb) {
10896f382ed2SLuiz Capitulino         bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
10907d4b4ba5SMarkus Armbruster         bs->dev_ops->change_media_cb(bs->dev_opaque, load);
10916f382ed2SLuiz Capitulino         if (tray_was_closed) {
10926f382ed2SLuiz Capitulino             /* tray open */
10936f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, true);
10946f382ed2SLuiz Capitulino         }
10956f382ed2SLuiz Capitulino         if (load) {
10966f382ed2SLuiz Capitulino             /* tray close */
10976f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, false);
10986f382ed2SLuiz Capitulino         }
1099145feb17SMarkus Armbruster     }
1100145feb17SMarkus Armbruster }
1101145feb17SMarkus Armbruster 
11022c6942faSMarkus Armbruster bool bdrv_dev_has_removable_media(BlockDriverState *bs)
11032c6942faSMarkus Armbruster {
11042c6942faSMarkus Armbruster     return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
11052c6942faSMarkus Armbruster }
11062c6942faSMarkus Armbruster 
1107025ccaa7SPaolo Bonzini void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
1108025ccaa7SPaolo Bonzini {
1109025ccaa7SPaolo Bonzini     if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
1110025ccaa7SPaolo Bonzini         bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
1111025ccaa7SPaolo Bonzini     }
1112025ccaa7SPaolo Bonzini }
1113025ccaa7SPaolo Bonzini 
1114e4def80bSMarkus Armbruster bool bdrv_dev_is_tray_open(BlockDriverState *bs)
1115e4def80bSMarkus Armbruster {
1116e4def80bSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_tray_open) {
1117e4def80bSMarkus Armbruster         return bs->dev_ops->is_tray_open(bs->dev_opaque);
1118e4def80bSMarkus Armbruster     }
1119e4def80bSMarkus Armbruster     return false;
1120e4def80bSMarkus Armbruster }
1121e4def80bSMarkus Armbruster 
1122145feb17SMarkus Armbruster static void bdrv_dev_resize_cb(BlockDriverState *bs)
1123145feb17SMarkus Armbruster {
1124145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->resize_cb) {
1125145feb17SMarkus Armbruster         bs->dev_ops->resize_cb(bs->dev_opaque);
11260e49de52SMarkus Armbruster     }
11270e49de52SMarkus Armbruster }
11280e49de52SMarkus Armbruster 
1129f107639aSMarkus Armbruster bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
1130f107639aSMarkus Armbruster {
1131f107639aSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
1132f107639aSMarkus Armbruster         return bs->dev_ops->is_medium_locked(bs->dev_opaque);
1133f107639aSMarkus Armbruster     }
1134f107639aSMarkus Armbruster     return false;
1135f107639aSMarkus Armbruster }
1136f107639aSMarkus Armbruster 
1137e97fc193Saliguori /*
1138e97fc193Saliguori  * Run consistency checks on an image
1139e97fc193Saliguori  *
1140e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
1141a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
1142e076f338SKevin Wolf  * check are stored in res.
1143e97fc193Saliguori  */
1144e076f338SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
1145e97fc193Saliguori {
1146e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
1147e97fc193Saliguori         return -ENOTSUP;
1148e97fc193Saliguori     }
1149e97fc193Saliguori 
1150e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
11519ac228e0SKevin Wolf     return bs->drv->bdrv_check(bs, res);
1152e97fc193Saliguori }
1153e97fc193Saliguori 
11548a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
11558a426614SKevin Wolf 
115633e3963eSbellard /* commit COW file into the raw image */
115733e3963eSbellard int bdrv_commit(BlockDriverState *bs)
115833e3963eSbellard {
115919cb3738Sbellard     BlockDriver *drv = bs->drv;
1160ee181196SKevin Wolf     BlockDriver *backing_drv;
11618a426614SKevin Wolf     int64_t sector, total_sectors;
11628a426614SKevin Wolf     int n, ro, open_flags;
11634dca4b63SNaphtali Sprei     int ret = 0, rw_ret = 0;
11648a426614SKevin Wolf     uint8_t *buf;
11654dca4b63SNaphtali Sprei     char filename[1024];
11664dca4b63SNaphtali Sprei     BlockDriverState *bs_rw, *bs_ro;
116733e3963eSbellard 
116819cb3738Sbellard     if (!drv)
116919cb3738Sbellard         return -ENOMEDIUM;
117033e3963eSbellard 
11714dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
11724dca4b63SNaphtali Sprei         return -ENOTSUP;
11734dca4b63SNaphtali Sprei     }
11744dca4b63SNaphtali Sprei 
11754dca4b63SNaphtali Sprei     if (bs->backing_hd->keep_read_only) {
1176ea2384d3Sbellard         return -EACCES;
117733e3963eSbellard     }
117833e3963eSbellard 
11792d3735d3SStefan Hajnoczi     if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
11802d3735d3SStefan Hajnoczi         return -EBUSY;
11812d3735d3SStefan Hajnoczi     }
11822d3735d3SStefan Hajnoczi 
1183ee181196SKevin Wolf     backing_drv = bs->backing_hd->drv;
11844dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
11854dca4b63SNaphtali Sprei     strncpy(filename, bs->backing_hd->filename, sizeof(filename));
11864dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
11874dca4b63SNaphtali Sprei 
11884dca4b63SNaphtali Sprei     if (ro) {
11894dca4b63SNaphtali Sprei         /* re-open as RW */
11904dca4b63SNaphtali Sprei         bdrv_delete(bs->backing_hd);
11914dca4b63SNaphtali Sprei         bs->backing_hd = NULL;
11924dca4b63SNaphtali Sprei         bs_rw = bdrv_new("");
1193ee181196SKevin Wolf         rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
1194ee181196SKevin Wolf             backing_drv);
11954dca4b63SNaphtali Sprei         if (rw_ret < 0) {
11964dca4b63SNaphtali Sprei             bdrv_delete(bs_rw);
11974dca4b63SNaphtali Sprei             /* try to re-open read-only */
11984dca4b63SNaphtali Sprei             bs_ro = bdrv_new("");
1199ee181196SKevin Wolf             ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
1200ee181196SKevin Wolf                 backing_drv);
12014dca4b63SNaphtali Sprei             if (ret < 0) {
12024dca4b63SNaphtali Sprei                 bdrv_delete(bs_ro);
12034dca4b63SNaphtali Sprei                 /* drive not functional anymore */
12044dca4b63SNaphtali Sprei                 bs->drv = NULL;
12054dca4b63SNaphtali Sprei                 return ret;
12064dca4b63SNaphtali Sprei             }
12074dca4b63SNaphtali Sprei             bs->backing_hd = bs_ro;
12084dca4b63SNaphtali Sprei             return rw_ret;
12094dca4b63SNaphtali Sprei         }
12104dca4b63SNaphtali Sprei         bs->backing_hd = bs_rw;
1211ea2384d3Sbellard     }
1212ea2384d3Sbellard 
12136ea44308SJan Kiszka     total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
12147267c094SAnthony Liguori     buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
12158a426614SKevin Wolf 
12168a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
121705c4af54SStefan Hajnoczi         if (bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
12188a426614SKevin Wolf 
12198a426614SKevin Wolf             if (bdrv_read(bs, sector, buf, n) != 0) {
12204dca4b63SNaphtali Sprei                 ret = -EIO;
12214dca4b63SNaphtali Sprei                 goto ro_cleanup;
122233e3963eSbellard             }
122333e3963eSbellard 
12248a426614SKevin Wolf             if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
12254dca4b63SNaphtali Sprei                 ret = -EIO;
12264dca4b63SNaphtali Sprei                 goto ro_cleanup;
122733e3963eSbellard             }
122833e3963eSbellard         }
122933e3963eSbellard     }
123095389c86Sbellard 
12311d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
12321d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
12331d44952fSChristoph Hellwig         bdrv_flush(bs);
12341d44952fSChristoph Hellwig     }
123595389c86Sbellard 
12363f5075aeSChristoph Hellwig     /*
12373f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
12383f5075aeSChristoph Hellwig      * stable on disk.
12393f5075aeSChristoph Hellwig      */
12403f5075aeSChristoph Hellwig     if (bs->backing_hd)
12413f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
12424dca4b63SNaphtali Sprei 
12434dca4b63SNaphtali Sprei ro_cleanup:
12447267c094SAnthony Liguori     g_free(buf);
12454dca4b63SNaphtali Sprei 
12464dca4b63SNaphtali Sprei     if (ro) {
12474dca4b63SNaphtali Sprei         /* re-open as RO */
12484dca4b63SNaphtali Sprei         bdrv_delete(bs->backing_hd);
12494dca4b63SNaphtali Sprei         bs->backing_hd = NULL;
12504dca4b63SNaphtali Sprei         bs_ro = bdrv_new("");
1251ee181196SKevin Wolf         ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
1252ee181196SKevin Wolf             backing_drv);
12534dca4b63SNaphtali Sprei         if (ret < 0) {
12544dca4b63SNaphtali Sprei             bdrv_delete(bs_ro);
12554dca4b63SNaphtali Sprei             /* drive not functional anymore */
12564dca4b63SNaphtali Sprei             bs->drv = NULL;
12574dca4b63SNaphtali Sprei             return ret;
12584dca4b63SNaphtali Sprei         }
12594dca4b63SNaphtali Sprei         bs->backing_hd = bs_ro;
12604dca4b63SNaphtali Sprei         bs->backing_hd->keep_read_only = 0;
12614dca4b63SNaphtali Sprei     }
12624dca4b63SNaphtali Sprei 
12631d44952fSChristoph Hellwig     return ret;
126433e3963eSbellard }
126533e3963eSbellard 
1266e8877497SStefan Hajnoczi int bdrv_commit_all(void)
12676ab4b5abSMarkus Armbruster {
12686ab4b5abSMarkus Armbruster     BlockDriverState *bs;
12696ab4b5abSMarkus Armbruster 
12706ab4b5abSMarkus Armbruster     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1271e8877497SStefan Hajnoczi         int ret = bdrv_commit(bs);
1272e8877497SStefan Hajnoczi         if (ret < 0) {
1273e8877497SStefan Hajnoczi             return ret;
12746ab4b5abSMarkus Armbruster         }
12756ab4b5abSMarkus Armbruster     }
1276e8877497SStefan Hajnoczi     return 0;
1277e8877497SStefan Hajnoczi }
12786ab4b5abSMarkus Armbruster 
1279dbffbdcfSStefan Hajnoczi struct BdrvTrackedRequest {
1280dbffbdcfSStefan Hajnoczi     BlockDriverState *bs;
1281dbffbdcfSStefan Hajnoczi     int64_t sector_num;
1282dbffbdcfSStefan Hajnoczi     int nb_sectors;
1283dbffbdcfSStefan Hajnoczi     bool is_write;
1284dbffbdcfSStefan Hajnoczi     QLIST_ENTRY(BdrvTrackedRequest) list;
12855f8b6491SStefan Hajnoczi     Coroutine *co; /* owner, used for deadlock detection */
1286f4658285SStefan Hajnoczi     CoQueue wait_queue; /* coroutines blocked on this request */
1287dbffbdcfSStefan Hajnoczi };
1288dbffbdcfSStefan Hajnoczi 
1289dbffbdcfSStefan Hajnoczi /**
1290dbffbdcfSStefan Hajnoczi  * Remove an active request from the tracked requests list
1291dbffbdcfSStefan Hajnoczi  *
1292dbffbdcfSStefan Hajnoczi  * This function should be called when a tracked request is completing.
1293dbffbdcfSStefan Hajnoczi  */
1294dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req)
1295dbffbdcfSStefan Hajnoczi {
1296dbffbdcfSStefan Hajnoczi     QLIST_REMOVE(req, list);
1297f4658285SStefan Hajnoczi     qemu_co_queue_restart_all(&req->wait_queue);
1298dbffbdcfSStefan Hajnoczi }
1299dbffbdcfSStefan Hajnoczi 
1300dbffbdcfSStefan Hajnoczi /**
1301dbffbdcfSStefan Hajnoczi  * Add an active request to the tracked requests list
1302dbffbdcfSStefan Hajnoczi  */
1303dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req,
1304dbffbdcfSStefan Hajnoczi                                   BlockDriverState *bs,
1305dbffbdcfSStefan Hajnoczi                                   int64_t sector_num,
1306dbffbdcfSStefan Hajnoczi                                   int nb_sectors, bool is_write)
1307dbffbdcfSStefan Hajnoczi {
1308dbffbdcfSStefan Hajnoczi     *req = (BdrvTrackedRequest){
1309dbffbdcfSStefan Hajnoczi         .bs = bs,
1310dbffbdcfSStefan Hajnoczi         .sector_num = sector_num,
1311dbffbdcfSStefan Hajnoczi         .nb_sectors = nb_sectors,
1312dbffbdcfSStefan Hajnoczi         .is_write = is_write,
13135f8b6491SStefan Hajnoczi         .co = qemu_coroutine_self(),
1314dbffbdcfSStefan Hajnoczi     };
1315dbffbdcfSStefan Hajnoczi 
1316f4658285SStefan Hajnoczi     qemu_co_queue_init(&req->wait_queue);
1317f4658285SStefan Hajnoczi 
1318dbffbdcfSStefan Hajnoczi     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
1319dbffbdcfSStefan Hajnoczi }
1320dbffbdcfSStefan Hajnoczi 
1321d83947acSStefan Hajnoczi /**
1322d83947acSStefan Hajnoczi  * Round a region to cluster boundaries
1323d83947acSStefan Hajnoczi  */
1324d83947acSStefan Hajnoczi static void round_to_clusters(BlockDriverState *bs,
1325d83947acSStefan Hajnoczi                               int64_t sector_num, int nb_sectors,
1326d83947acSStefan Hajnoczi                               int64_t *cluster_sector_num,
1327d83947acSStefan Hajnoczi                               int *cluster_nb_sectors)
1328d83947acSStefan Hajnoczi {
1329d83947acSStefan Hajnoczi     BlockDriverInfo bdi;
1330d83947acSStefan Hajnoczi 
1331d83947acSStefan Hajnoczi     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
1332d83947acSStefan Hajnoczi         *cluster_sector_num = sector_num;
1333d83947acSStefan Hajnoczi         *cluster_nb_sectors = nb_sectors;
1334d83947acSStefan Hajnoczi     } else {
1335d83947acSStefan Hajnoczi         int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
1336d83947acSStefan Hajnoczi         *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
1337d83947acSStefan Hajnoczi         *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
1338d83947acSStefan Hajnoczi                                             nb_sectors, c);
1339d83947acSStefan Hajnoczi     }
1340d83947acSStefan Hajnoczi }
1341d83947acSStefan Hajnoczi 
1342f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req,
1343f4658285SStefan Hajnoczi                                      int64_t sector_num, int nb_sectors) {
1344d83947acSStefan Hajnoczi     /*        aaaa   bbbb */
1345d83947acSStefan Hajnoczi     if (sector_num >= req->sector_num + req->nb_sectors) {
1346d83947acSStefan Hajnoczi         return false;
1347d83947acSStefan Hajnoczi     }
1348d83947acSStefan Hajnoczi     /* bbbb   aaaa        */
1349d83947acSStefan Hajnoczi     if (req->sector_num >= sector_num + nb_sectors) {
1350d83947acSStefan Hajnoczi         return false;
1351d83947acSStefan Hajnoczi     }
1352d83947acSStefan Hajnoczi     return true;
1353f4658285SStefan Hajnoczi }
1354f4658285SStefan Hajnoczi 
1355f4658285SStefan Hajnoczi static void coroutine_fn wait_for_overlapping_requests(BlockDriverState *bs,
1356f4658285SStefan Hajnoczi         int64_t sector_num, int nb_sectors)
1357f4658285SStefan Hajnoczi {
1358f4658285SStefan Hajnoczi     BdrvTrackedRequest *req;
1359d83947acSStefan Hajnoczi     int64_t cluster_sector_num;
1360d83947acSStefan Hajnoczi     int cluster_nb_sectors;
1361f4658285SStefan Hajnoczi     bool retry;
1362f4658285SStefan Hajnoczi 
1363d83947acSStefan Hajnoczi     /* If we touch the same cluster it counts as an overlap.  This guarantees
1364d83947acSStefan Hajnoczi      * that allocating writes will be serialized and not race with each other
1365d83947acSStefan Hajnoczi      * for the same cluster.  For example, in copy-on-read it ensures that the
1366d83947acSStefan Hajnoczi      * CoR read and write operations are atomic and guest writes cannot
1367d83947acSStefan Hajnoczi      * interleave between them.
1368d83947acSStefan Hajnoczi      */
1369d83947acSStefan Hajnoczi     round_to_clusters(bs, sector_num, nb_sectors,
1370d83947acSStefan Hajnoczi                       &cluster_sector_num, &cluster_nb_sectors);
1371d83947acSStefan Hajnoczi 
1372f4658285SStefan Hajnoczi     do {
1373f4658285SStefan Hajnoczi         retry = false;
1374f4658285SStefan Hajnoczi         QLIST_FOREACH(req, &bs->tracked_requests, list) {
1375d83947acSStefan Hajnoczi             if (tracked_request_overlaps(req, cluster_sector_num,
1376d83947acSStefan Hajnoczi                                          cluster_nb_sectors)) {
13775f8b6491SStefan Hajnoczi                 /* Hitting this means there was a reentrant request, for
13785f8b6491SStefan Hajnoczi                  * example, a block driver issuing nested requests.  This must
13795f8b6491SStefan Hajnoczi                  * never happen since it means deadlock.
13805f8b6491SStefan Hajnoczi                  */
13815f8b6491SStefan Hajnoczi                 assert(qemu_coroutine_self() != req->co);
13825f8b6491SStefan Hajnoczi 
1383f4658285SStefan Hajnoczi                 qemu_co_queue_wait(&req->wait_queue);
1384f4658285SStefan Hajnoczi                 retry = true;
1385f4658285SStefan Hajnoczi                 break;
1386f4658285SStefan Hajnoczi             }
1387f4658285SStefan Hajnoczi         }
1388f4658285SStefan Hajnoczi     } while (retry);
1389f4658285SStefan Hajnoczi }
1390f4658285SStefan Hajnoczi 
1391756e6736SKevin Wolf /*
1392756e6736SKevin Wolf  * Return values:
1393756e6736SKevin Wolf  * 0        - success
1394756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
1395756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
1396756e6736SKevin Wolf  *            image file header
1397756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
1398756e6736SKevin Wolf  */
1399756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
1400756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
1401756e6736SKevin Wolf {
1402756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
1403756e6736SKevin Wolf 
1404756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
1405756e6736SKevin Wolf         return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
1406756e6736SKevin Wolf     } else {
1407756e6736SKevin Wolf         return -ENOTSUP;
1408756e6736SKevin Wolf     }
1409756e6736SKevin Wolf }
1410756e6736SKevin Wolf 
141171d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
141271d0770cSaliguori                                    size_t size)
141371d0770cSaliguori {
141471d0770cSaliguori     int64_t len;
141571d0770cSaliguori 
141671d0770cSaliguori     if (!bdrv_is_inserted(bs))
141771d0770cSaliguori         return -ENOMEDIUM;
141871d0770cSaliguori 
141971d0770cSaliguori     if (bs->growable)
142071d0770cSaliguori         return 0;
142171d0770cSaliguori 
142271d0770cSaliguori     len = bdrv_getlength(bs);
142371d0770cSaliguori 
1424fbb7b4e0SKevin Wolf     if (offset < 0)
1425fbb7b4e0SKevin Wolf         return -EIO;
1426fbb7b4e0SKevin Wolf 
1427fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
142871d0770cSaliguori         return -EIO;
142971d0770cSaliguori 
143071d0770cSaliguori     return 0;
143171d0770cSaliguori }
143271d0770cSaliguori 
143371d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
143471d0770cSaliguori                               int nb_sectors)
143571d0770cSaliguori {
1436eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
1437eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
143871d0770cSaliguori }
143971d0770cSaliguori 
14401c9805a3SStefan Hajnoczi typedef struct RwCo {
14411c9805a3SStefan Hajnoczi     BlockDriverState *bs;
14421c9805a3SStefan Hajnoczi     int64_t sector_num;
14431c9805a3SStefan Hajnoczi     int nb_sectors;
14441c9805a3SStefan Hajnoczi     QEMUIOVector *qiov;
14451c9805a3SStefan Hajnoczi     bool is_write;
14461c9805a3SStefan Hajnoczi     int ret;
14471c9805a3SStefan Hajnoczi } RwCo;
14481c9805a3SStefan Hajnoczi 
14491c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque)
1450fc01f7e7Sbellard {
14511c9805a3SStefan Hajnoczi     RwCo *rwco = opaque;
1452fc01f7e7Sbellard 
14531c9805a3SStefan Hajnoczi     if (!rwco->is_write) {
14541c9805a3SStefan Hajnoczi         rwco->ret = bdrv_co_do_readv(rwco->bs, rwco->sector_num,
1455470c0504SStefan Hajnoczi                                      rwco->nb_sectors, rwco->qiov, 0);
14561c9805a3SStefan Hajnoczi     } else {
14571c9805a3SStefan Hajnoczi         rwco->ret = bdrv_co_do_writev(rwco->bs, rwco->sector_num,
1458f08f2ddaSStefan Hajnoczi                                       rwco->nb_sectors, rwco->qiov, 0);
14591c9805a3SStefan Hajnoczi     }
14601c9805a3SStefan Hajnoczi }
1461e7a8a783SKevin Wolf 
14621c9805a3SStefan Hajnoczi /*
14631c9805a3SStefan Hajnoczi  * Process a synchronous request using coroutines
14641c9805a3SStefan Hajnoczi  */
14651c9805a3SStefan Hajnoczi static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
14661c9805a3SStefan Hajnoczi                       int nb_sectors, bool is_write)
14671c9805a3SStefan Hajnoczi {
1468e7a8a783SKevin Wolf     QEMUIOVector qiov;
1469e7a8a783SKevin Wolf     struct iovec iov = {
1470e7a8a783SKevin Wolf         .iov_base = (void *)buf,
1471e7a8a783SKevin Wolf         .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1472e7a8a783SKevin Wolf     };
14731c9805a3SStefan Hajnoczi     Coroutine *co;
14741c9805a3SStefan Hajnoczi     RwCo rwco = {
14751c9805a3SStefan Hajnoczi         .bs = bs,
14761c9805a3SStefan Hajnoczi         .sector_num = sector_num,
14771c9805a3SStefan Hajnoczi         .nb_sectors = nb_sectors,
14781c9805a3SStefan Hajnoczi         .qiov = &qiov,
14791c9805a3SStefan Hajnoczi         .is_write = is_write,
14801c9805a3SStefan Hajnoczi         .ret = NOT_DONE,
14811c9805a3SStefan Hajnoczi     };
1482e7a8a783SKevin Wolf 
1483e7a8a783SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
14841c9805a3SStefan Hajnoczi 
1485498e386cSZhi Yong Wu     /**
1486498e386cSZhi Yong Wu      * In sync call context, when the vcpu is blocked, this throttling timer
1487498e386cSZhi Yong Wu      * will not fire; so the I/O throttling function has to be disabled here
1488498e386cSZhi Yong Wu      * if it has been enabled.
1489498e386cSZhi Yong Wu      */
1490498e386cSZhi Yong Wu     if (bs->io_limits_enabled) {
1491498e386cSZhi Yong Wu         fprintf(stderr, "Disabling I/O throttling on '%s' due "
1492498e386cSZhi Yong Wu                         "to synchronous I/O.\n", bdrv_get_device_name(bs));
1493498e386cSZhi Yong Wu         bdrv_io_limits_disable(bs);
1494498e386cSZhi Yong Wu     }
1495498e386cSZhi Yong Wu 
14961c9805a3SStefan Hajnoczi     if (qemu_in_coroutine()) {
14971c9805a3SStefan Hajnoczi         /* Fast-path if already in coroutine context */
14981c9805a3SStefan Hajnoczi         bdrv_rw_co_entry(&rwco);
14991c9805a3SStefan Hajnoczi     } else {
15001c9805a3SStefan Hajnoczi         co = qemu_coroutine_create(bdrv_rw_co_entry);
15011c9805a3SStefan Hajnoczi         qemu_coroutine_enter(co, &rwco);
15021c9805a3SStefan Hajnoczi         while (rwco.ret == NOT_DONE) {
15031c9805a3SStefan Hajnoczi             qemu_aio_wait();
15041c9805a3SStefan Hajnoczi         }
15051c9805a3SStefan Hajnoczi     }
15061c9805a3SStefan Hajnoczi     return rwco.ret;
1507e7a8a783SKevin Wolf }
1508e7a8a783SKevin Wolf 
15091c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */
15101c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num,
15111c9805a3SStefan Hajnoczi               uint8_t *buf, int nb_sectors)
15121c9805a3SStefan Hajnoczi {
15131c9805a3SStefan Hajnoczi     return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false);
151483f64091Sbellard }
1515fc01f7e7Sbellard 
15167cd1e32aSlirans@il.ibm.com static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
15177cd1e32aSlirans@il.ibm.com                              int nb_sectors, int dirty)
15187cd1e32aSlirans@il.ibm.com {
15197cd1e32aSlirans@il.ibm.com     int64_t start, end;
1520c6d22830SJan Kiszka     unsigned long val, idx, bit;
1521a55eb92cSJan Kiszka 
15226ea44308SJan Kiszka     start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
1523c6d22830SJan Kiszka     end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
15247cd1e32aSlirans@il.ibm.com 
15257cd1e32aSlirans@il.ibm.com     for (; start <= end; start++) {
1526c6d22830SJan Kiszka         idx = start / (sizeof(unsigned long) * 8);
1527c6d22830SJan Kiszka         bit = start % (sizeof(unsigned long) * 8);
1528c6d22830SJan Kiszka         val = bs->dirty_bitmap[idx];
1529c6d22830SJan Kiszka         if (dirty) {
15306d59fec1SMarcelo Tosatti             if (!(val & (1UL << bit))) {
1531aaa0eb75SLiran Schour                 bs->dirty_count++;
15326d59fec1SMarcelo Tosatti                 val |= 1UL << bit;
1533aaa0eb75SLiran Schour             }
1534c6d22830SJan Kiszka         } else {
15356d59fec1SMarcelo Tosatti             if (val & (1UL << bit)) {
1536aaa0eb75SLiran Schour                 bs->dirty_count--;
15376d59fec1SMarcelo Tosatti                 val &= ~(1UL << bit);
1538c6d22830SJan Kiszka             }
1539aaa0eb75SLiran Schour         }
1540c6d22830SJan Kiszka         bs->dirty_bitmap[idx] = val;
15417cd1e32aSlirans@il.ibm.com     }
15427cd1e32aSlirans@il.ibm.com }
15437cd1e32aSlirans@il.ibm.com 
154419cb3738Sbellard /* Return < 0 if error. Important errors are:
154519cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
154619cb3738Sbellard   -ENOMEDIUM   No media inserted.
154719cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
154819cb3738Sbellard   -EACCES      Trying to write a read-only device
154919cb3738Sbellard */
1550fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
1551fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
1552fc01f7e7Sbellard {
15531c9805a3SStefan Hajnoczi     return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true);
155483f64091Sbellard }
155583f64091Sbellard 
1556eda578e5Saliguori int bdrv_pread(BlockDriverState *bs, int64_t offset,
1557eda578e5Saliguori                void *buf, int count1)
155883f64091Sbellard {
15596ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
156083f64091Sbellard     int len, nb_sectors, count;
156183f64091Sbellard     int64_t sector_num;
15629a8c4cceSKevin Wolf     int ret;
156383f64091Sbellard 
156483f64091Sbellard     count = count1;
156583f64091Sbellard     /* first read to align to sector start */
15666ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
156783f64091Sbellard     if (len > count)
156883f64091Sbellard         len = count;
15696ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
157083f64091Sbellard     if (len > 0) {
15719a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
15729a8c4cceSKevin Wolf             return ret;
15736ea44308SJan Kiszka         memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
157483f64091Sbellard         count -= len;
157583f64091Sbellard         if (count == 0)
157683f64091Sbellard             return count1;
157783f64091Sbellard         sector_num++;
157883f64091Sbellard         buf += len;
157983f64091Sbellard     }
158083f64091Sbellard 
158183f64091Sbellard     /* read the sectors "in place" */
15826ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
158383f64091Sbellard     if (nb_sectors > 0) {
15849a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
15859a8c4cceSKevin Wolf             return ret;
158683f64091Sbellard         sector_num += nb_sectors;
15876ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
158883f64091Sbellard         buf += len;
158983f64091Sbellard         count -= len;
159083f64091Sbellard     }
159183f64091Sbellard 
159283f64091Sbellard     /* add data from the last sector */
159383f64091Sbellard     if (count > 0) {
15949a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
15959a8c4cceSKevin Wolf             return ret;
159683f64091Sbellard         memcpy(buf, tmp_buf, count);
159783f64091Sbellard     }
159883f64091Sbellard     return count1;
159983f64091Sbellard }
160083f64091Sbellard 
1601eda578e5Saliguori int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1602eda578e5Saliguori                 const void *buf, int count1)
160383f64091Sbellard {
16046ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
160583f64091Sbellard     int len, nb_sectors, count;
160683f64091Sbellard     int64_t sector_num;
16079a8c4cceSKevin Wolf     int ret;
160883f64091Sbellard 
160983f64091Sbellard     count = count1;
161083f64091Sbellard     /* first write to align to sector start */
16116ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
161283f64091Sbellard     if (len > count)
161383f64091Sbellard         len = count;
16146ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
161583f64091Sbellard     if (len > 0) {
16169a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
16179a8c4cceSKevin Wolf             return ret;
16186ea44308SJan Kiszka         memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
16199a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
16209a8c4cceSKevin Wolf             return ret;
162183f64091Sbellard         count -= len;
162283f64091Sbellard         if (count == 0)
162383f64091Sbellard             return count1;
162483f64091Sbellard         sector_num++;
162583f64091Sbellard         buf += len;
162683f64091Sbellard     }
162783f64091Sbellard 
162883f64091Sbellard     /* write the sectors "in place" */
16296ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
163083f64091Sbellard     if (nb_sectors > 0) {
16319a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
16329a8c4cceSKevin Wolf             return ret;
163383f64091Sbellard         sector_num += nb_sectors;
16346ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
163583f64091Sbellard         buf += len;
163683f64091Sbellard         count -= len;
163783f64091Sbellard     }
163883f64091Sbellard 
163983f64091Sbellard     /* add data from the last sector */
164083f64091Sbellard     if (count > 0) {
16419a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
16429a8c4cceSKevin Wolf             return ret;
164383f64091Sbellard         memcpy(tmp_buf, buf, count);
16449a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
16459a8c4cceSKevin Wolf             return ret;
164683f64091Sbellard     }
164783f64091Sbellard     return count1;
164883f64091Sbellard }
164983f64091Sbellard 
1650f08145feSKevin Wolf /*
1651f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
1652f08145feSKevin Wolf  * request (acts as a barrier)
1653f08145feSKevin Wolf  *
1654f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
1655f08145feSKevin Wolf  */
1656f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1657f08145feSKevin Wolf     const void *buf, int count)
1658f08145feSKevin Wolf {
1659f08145feSKevin Wolf     int ret;
1660f08145feSKevin Wolf 
1661f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
1662f08145feSKevin Wolf     if (ret < 0) {
1663f08145feSKevin Wolf         return ret;
1664f08145feSKevin Wolf     }
1665f08145feSKevin Wolf 
166692196b2fSStefan Hajnoczi     /* No flush needed for cache modes that use O_DSYNC */
166792196b2fSStefan Hajnoczi     if ((bs->open_flags & BDRV_O_CACHE_WB) != 0) {
1668f08145feSKevin Wolf         bdrv_flush(bs);
1669f08145feSKevin Wolf     }
1670f08145feSKevin Wolf 
1671f08145feSKevin Wolf     return 0;
1672f08145feSKevin Wolf }
1673f08145feSKevin Wolf 
1674470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
1675ab185921SStefan Hajnoczi         int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
1676ab185921SStefan Hajnoczi {
1677ab185921SStefan Hajnoczi     /* Perform I/O through a temporary buffer so that users who scribble over
1678ab185921SStefan Hajnoczi      * their read buffer while the operation is in progress do not end up
1679ab185921SStefan Hajnoczi      * modifying the image file.  This is critical for zero-copy guest I/O
1680ab185921SStefan Hajnoczi      * where anything might happen inside guest memory.
1681ab185921SStefan Hajnoczi      */
1682ab185921SStefan Hajnoczi     void *bounce_buffer;
1683ab185921SStefan Hajnoczi 
168479c053bdSStefan Hajnoczi     BlockDriver *drv = bs->drv;
1685ab185921SStefan Hajnoczi     struct iovec iov;
1686ab185921SStefan Hajnoczi     QEMUIOVector bounce_qiov;
1687ab185921SStefan Hajnoczi     int64_t cluster_sector_num;
1688ab185921SStefan Hajnoczi     int cluster_nb_sectors;
1689ab185921SStefan Hajnoczi     size_t skip_bytes;
1690ab185921SStefan Hajnoczi     int ret;
1691ab185921SStefan Hajnoczi 
1692ab185921SStefan Hajnoczi     /* Cover entire cluster so no additional backing file I/O is required when
1693ab185921SStefan Hajnoczi      * allocating cluster in the image file.
1694ab185921SStefan Hajnoczi      */
1695ab185921SStefan Hajnoczi     round_to_clusters(bs, sector_num, nb_sectors,
1696ab185921SStefan Hajnoczi                       &cluster_sector_num, &cluster_nb_sectors);
1697ab185921SStefan Hajnoczi 
1698470c0504SStefan Hajnoczi     trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
1699ab185921SStefan Hajnoczi                                    cluster_sector_num, cluster_nb_sectors);
1700ab185921SStefan Hajnoczi 
1701ab185921SStefan Hajnoczi     iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
1702ab185921SStefan Hajnoczi     iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
1703ab185921SStefan Hajnoczi     qemu_iovec_init_external(&bounce_qiov, &iov, 1);
1704ab185921SStefan Hajnoczi 
170579c053bdSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
1706ab185921SStefan Hajnoczi                              &bounce_qiov);
1707ab185921SStefan Hajnoczi     if (ret < 0) {
1708ab185921SStefan Hajnoczi         goto err;
1709ab185921SStefan Hajnoczi     }
1710ab185921SStefan Hajnoczi 
171179c053bdSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes &&
171279c053bdSStefan Hajnoczi         buffer_is_zero(bounce_buffer, iov.iov_len)) {
1713621f0589SKevin Wolf         ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
171479c053bdSStefan Hajnoczi                                       cluster_nb_sectors);
171579c053bdSStefan Hajnoczi     } else {
171679c053bdSStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
1717ab185921SStefan Hajnoczi                                   &bounce_qiov);
171879c053bdSStefan Hajnoczi     }
171979c053bdSStefan Hajnoczi 
1720ab185921SStefan Hajnoczi     if (ret < 0) {
1721ab185921SStefan Hajnoczi         /* It might be okay to ignore write errors for guest requests.  If this
1722ab185921SStefan Hajnoczi          * is a deliberate copy-on-read then we don't want to ignore the error.
1723ab185921SStefan Hajnoczi          * Simply report it in all cases.
1724ab185921SStefan Hajnoczi          */
1725ab185921SStefan Hajnoczi         goto err;
1726ab185921SStefan Hajnoczi     }
1727ab185921SStefan Hajnoczi 
1728ab185921SStefan Hajnoczi     skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
1729ab185921SStefan Hajnoczi     qemu_iovec_from_buffer(qiov, bounce_buffer + skip_bytes,
1730ab185921SStefan Hajnoczi                            nb_sectors * BDRV_SECTOR_SIZE);
1731ab185921SStefan Hajnoczi 
1732ab185921SStefan Hajnoczi err:
1733ab185921SStefan Hajnoczi     qemu_vfree(bounce_buffer);
1734ab185921SStefan Hajnoczi     return ret;
1735ab185921SStefan Hajnoczi }
1736ab185921SStefan Hajnoczi 
1737c5fbe571SStefan Hajnoczi /*
1738c5fbe571SStefan Hajnoczi  * Handle a read request in coroutine context
1739c5fbe571SStefan Hajnoczi  */
1740c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
1741470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
1742470c0504SStefan Hajnoczi     BdrvRequestFlags flags)
1743da1fa91dSKevin Wolf {
1744da1fa91dSKevin Wolf     BlockDriver *drv = bs->drv;
1745dbffbdcfSStefan Hajnoczi     BdrvTrackedRequest req;
1746dbffbdcfSStefan Hajnoczi     int ret;
1747da1fa91dSKevin Wolf 
1748da1fa91dSKevin Wolf     if (!drv) {
1749da1fa91dSKevin Wolf         return -ENOMEDIUM;
1750da1fa91dSKevin Wolf     }
1751da1fa91dSKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1752da1fa91dSKevin Wolf         return -EIO;
1753da1fa91dSKevin Wolf     }
1754da1fa91dSKevin Wolf 
175598f90dbaSZhi Yong Wu     /* throttling disk read I/O */
175698f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
175798f90dbaSZhi Yong Wu         bdrv_io_limits_intercept(bs, false, nb_sectors);
175898f90dbaSZhi Yong Wu     }
175998f90dbaSZhi Yong Wu 
1760f4658285SStefan Hajnoczi     if (bs->copy_on_read) {
1761470c0504SStefan Hajnoczi         flags |= BDRV_REQ_COPY_ON_READ;
1762470c0504SStefan Hajnoczi     }
1763470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
1764470c0504SStefan Hajnoczi         bs->copy_on_read_in_flight++;
1765470c0504SStefan Hajnoczi     }
1766470c0504SStefan Hajnoczi 
1767470c0504SStefan Hajnoczi     if (bs->copy_on_read_in_flight) {
1768f4658285SStefan Hajnoczi         wait_for_overlapping_requests(bs, sector_num, nb_sectors);
1769f4658285SStefan Hajnoczi     }
1770f4658285SStefan Hajnoczi 
1771dbffbdcfSStefan Hajnoczi     tracked_request_begin(&req, bs, sector_num, nb_sectors, false);
1772ab185921SStefan Hajnoczi 
1773470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
1774ab185921SStefan Hajnoczi         int pnum;
1775ab185921SStefan Hajnoczi 
1776ab185921SStefan Hajnoczi         ret = bdrv_co_is_allocated(bs, sector_num, nb_sectors, &pnum);
1777ab185921SStefan Hajnoczi         if (ret < 0) {
1778ab185921SStefan Hajnoczi             goto out;
1779ab185921SStefan Hajnoczi         }
1780ab185921SStefan Hajnoczi 
1781ab185921SStefan Hajnoczi         if (!ret || pnum != nb_sectors) {
1782470c0504SStefan Hajnoczi             ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
1783ab185921SStefan Hajnoczi             goto out;
1784ab185921SStefan Hajnoczi         }
1785ab185921SStefan Hajnoczi     }
1786ab185921SStefan Hajnoczi 
1787dbffbdcfSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1788ab185921SStefan Hajnoczi 
1789ab185921SStefan Hajnoczi out:
1790dbffbdcfSStefan Hajnoczi     tracked_request_end(&req);
1791470c0504SStefan Hajnoczi 
1792470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
1793470c0504SStefan Hajnoczi         bs->copy_on_read_in_flight--;
1794470c0504SStefan Hajnoczi     }
1795470c0504SStefan Hajnoczi 
1796dbffbdcfSStefan Hajnoczi     return ret;
1797da1fa91dSKevin Wolf }
1798da1fa91dSKevin Wolf 
1799c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1800da1fa91dSKevin Wolf     int nb_sectors, QEMUIOVector *qiov)
1801da1fa91dSKevin Wolf {
1802c5fbe571SStefan Hajnoczi     trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1803da1fa91dSKevin Wolf 
1804470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
1805470c0504SStefan Hajnoczi }
1806470c0504SStefan Hajnoczi 
1807470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
1808470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
1809470c0504SStefan Hajnoczi {
1810470c0504SStefan Hajnoczi     trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
1811470c0504SStefan Hajnoczi 
1812470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
1813470c0504SStefan Hajnoczi                             BDRV_REQ_COPY_ON_READ);
1814c5fbe571SStefan Hajnoczi }
1815c5fbe571SStefan Hajnoczi 
1816f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
1817f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors)
1818f08f2ddaSStefan Hajnoczi {
1819f08f2ddaSStefan Hajnoczi     BlockDriver *drv = bs->drv;
1820f08f2ddaSStefan Hajnoczi     QEMUIOVector qiov;
1821f08f2ddaSStefan Hajnoczi     struct iovec iov;
1822f08f2ddaSStefan Hajnoczi     int ret;
1823f08f2ddaSStefan Hajnoczi 
1824621f0589SKevin Wolf     /* TODO Emulate only part of misaligned requests instead of letting block
1825621f0589SKevin Wolf      * drivers return -ENOTSUP and emulate everything */
1826621f0589SKevin Wolf 
1827f08f2ddaSStefan Hajnoczi     /* First try the efficient write zeroes operation */
1828f08f2ddaSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes) {
1829621f0589SKevin Wolf         ret = drv->bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
1830621f0589SKevin Wolf         if (ret != -ENOTSUP) {
1831621f0589SKevin Wolf             return ret;
1832621f0589SKevin Wolf         }
1833f08f2ddaSStefan Hajnoczi     }
1834f08f2ddaSStefan Hajnoczi 
1835f08f2ddaSStefan Hajnoczi     /* Fall back to bounce buffer if write zeroes is unsupported */
1836f08f2ddaSStefan Hajnoczi     iov.iov_len  = nb_sectors * BDRV_SECTOR_SIZE;
1837f08f2ddaSStefan Hajnoczi     iov.iov_base = qemu_blockalign(bs, iov.iov_len);
1838f08f2ddaSStefan Hajnoczi     memset(iov.iov_base, 0, iov.iov_len);
1839f08f2ddaSStefan Hajnoczi     qemu_iovec_init_external(&qiov, &iov, 1);
1840f08f2ddaSStefan Hajnoczi 
1841f08f2ddaSStefan Hajnoczi     ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
1842f08f2ddaSStefan Hajnoczi 
1843f08f2ddaSStefan Hajnoczi     qemu_vfree(iov.iov_base);
1844f08f2ddaSStefan Hajnoczi     return ret;
1845f08f2ddaSStefan Hajnoczi }
1846f08f2ddaSStefan Hajnoczi 
1847c5fbe571SStefan Hajnoczi /*
1848c5fbe571SStefan Hajnoczi  * Handle a write request in coroutine context
1849c5fbe571SStefan Hajnoczi  */
1850c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
1851f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
1852f08f2ddaSStefan Hajnoczi     BdrvRequestFlags flags)
1853c5fbe571SStefan Hajnoczi {
1854c5fbe571SStefan Hajnoczi     BlockDriver *drv = bs->drv;
1855dbffbdcfSStefan Hajnoczi     BdrvTrackedRequest req;
18566b7cb247SStefan Hajnoczi     int ret;
1857da1fa91dSKevin Wolf 
1858da1fa91dSKevin Wolf     if (!bs->drv) {
1859da1fa91dSKevin Wolf         return -ENOMEDIUM;
1860da1fa91dSKevin Wolf     }
1861da1fa91dSKevin Wolf     if (bs->read_only) {
1862da1fa91dSKevin Wolf         return -EACCES;
1863da1fa91dSKevin Wolf     }
1864da1fa91dSKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1865da1fa91dSKevin Wolf         return -EIO;
1866da1fa91dSKevin Wolf     }
1867da1fa91dSKevin Wolf 
186898f90dbaSZhi Yong Wu     /* throttling disk write I/O */
186998f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
187098f90dbaSZhi Yong Wu         bdrv_io_limits_intercept(bs, true, nb_sectors);
187198f90dbaSZhi Yong Wu     }
187298f90dbaSZhi Yong Wu 
1873470c0504SStefan Hajnoczi     if (bs->copy_on_read_in_flight) {
1874f4658285SStefan Hajnoczi         wait_for_overlapping_requests(bs, sector_num, nb_sectors);
1875f4658285SStefan Hajnoczi     }
1876f4658285SStefan Hajnoczi 
1877dbffbdcfSStefan Hajnoczi     tracked_request_begin(&req, bs, sector_num, nb_sectors, true);
1878dbffbdcfSStefan Hajnoczi 
1879f08f2ddaSStefan Hajnoczi     if (flags & BDRV_REQ_ZERO_WRITE) {
1880f08f2ddaSStefan Hajnoczi         ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors);
1881f08f2ddaSStefan Hajnoczi     } else {
18826b7cb247SStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
1883f08f2ddaSStefan Hajnoczi     }
18846b7cb247SStefan Hajnoczi 
1885da1fa91dSKevin Wolf     if (bs->dirty_bitmap) {
1886da1fa91dSKevin Wolf         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1887da1fa91dSKevin Wolf     }
1888da1fa91dSKevin Wolf 
1889da1fa91dSKevin Wolf     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1890da1fa91dSKevin Wolf         bs->wr_highest_sector = sector_num + nb_sectors - 1;
1891da1fa91dSKevin Wolf     }
1892da1fa91dSKevin Wolf 
1893dbffbdcfSStefan Hajnoczi     tracked_request_end(&req);
1894dbffbdcfSStefan Hajnoczi 
18956b7cb247SStefan Hajnoczi     return ret;
1896da1fa91dSKevin Wolf }
1897da1fa91dSKevin Wolf 
1898c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1899c5fbe571SStefan Hajnoczi     int nb_sectors, QEMUIOVector *qiov)
1900c5fbe571SStefan Hajnoczi {
1901c5fbe571SStefan Hajnoczi     trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1902c5fbe571SStefan Hajnoczi 
1903f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
1904f08f2ddaSStefan Hajnoczi }
1905f08f2ddaSStefan Hajnoczi 
1906f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
1907f08f2ddaSStefan Hajnoczi                                       int64_t sector_num, int nb_sectors)
1908f08f2ddaSStefan Hajnoczi {
1909f08f2ddaSStefan Hajnoczi     trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
1910f08f2ddaSStefan Hajnoczi 
1911f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
1912f08f2ddaSStefan Hajnoczi                              BDRV_REQ_ZERO_WRITE);
1913c5fbe571SStefan Hajnoczi }
1914c5fbe571SStefan Hajnoczi 
191583f64091Sbellard /**
191683f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
191783f64091Sbellard  */
191883f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
191983f64091Sbellard {
192083f64091Sbellard     BlockDriver *drv = bs->drv;
192151762288SStefan Hajnoczi     int ret;
192283f64091Sbellard     if (!drv)
192319cb3738Sbellard         return -ENOMEDIUM;
192483f64091Sbellard     if (!drv->bdrv_truncate)
192583f64091Sbellard         return -ENOTSUP;
192659f2689dSNaphtali Sprei     if (bs->read_only)
192759f2689dSNaphtali Sprei         return -EACCES;
19288591675fSMarcelo Tosatti     if (bdrv_in_use(bs))
19298591675fSMarcelo Tosatti         return -EBUSY;
193051762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
193151762288SStefan Hajnoczi     if (ret == 0) {
193251762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
1933145feb17SMarkus Armbruster         bdrv_dev_resize_cb(bs);
193451762288SStefan Hajnoczi     }
193551762288SStefan Hajnoczi     return ret;
193683f64091Sbellard }
193783f64091Sbellard 
193883f64091Sbellard /**
19394a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
19404a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
19414a1d5e1fSFam Zheng  */
19424a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
19434a1d5e1fSFam Zheng {
19444a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
19454a1d5e1fSFam Zheng     if (!drv) {
19464a1d5e1fSFam Zheng         return -ENOMEDIUM;
19474a1d5e1fSFam Zheng     }
19484a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
19494a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
19504a1d5e1fSFam Zheng     }
19514a1d5e1fSFam Zheng     if (bs->file) {
19524a1d5e1fSFam Zheng         return bdrv_get_allocated_file_size(bs->file);
19534a1d5e1fSFam Zheng     }
19544a1d5e1fSFam Zheng     return -ENOTSUP;
19554a1d5e1fSFam Zheng }
19564a1d5e1fSFam Zheng 
19574a1d5e1fSFam Zheng /**
195883f64091Sbellard  * Length of a file in bytes. Return < 0 if error or unknown.
195983f64091Sbellard  */
196083f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs)
196183f64091Sbellard {
196283f64091Sbellard     BlockDriver *drv = bs->drv;
196383f64091Sbellard     if (!drv)
196419cb3738Sbellard         return -ENOMEDIUM;
196551762288SStefan Hajnoczi 
19662c6942faSMarkus Armbruster     if (bs->growable || bdrv_dev_has_removable_media(bs)) {
196746a4e4e6SStefan Hajnoczi         if (drv->bdrv_getlength) {
196883f64091Sbellard             return drv->bdrv_getlength(bs);
1969fc01f7e7Sbellard         }
197046a4e4e6SStefan Hajnoczi     }
197146a4e4e6SStefan Hajnoczi     return bs->total_sectors * BDRV_SECTOR_SIZE;
197246a4e4e6SStefan Hajnoczi }
1973fc01f7e7Sbellard 
197419cb3738Sbellard /* return 0 as number of sectors if no device present or error */
197596b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
1976fc01f7e7Sbellard {
197719cb3738Sbellard     int64_t length;
197819cb3738Sbellard     length = bdrv_getlength(bs);
197919cb3738Sbellard     if (length < 0)
198019cb3738Sbellard         length = 0;
198119cb3738Sbellard     else
19826ea44308SJan Kiszka         length = length >> BDRV_SECTOR_BITS;
198319cb3738Sbellard     *nb_sectors_ptr = length;
1984fc01f7e7Sbellard }
1985cf98951bSbellard 
1986f3d54fc4Saliguori struct partition {
1987f3d54fc4Saliguori         uint8_t boot_ind;           /* 0x80 - active */
1988f3d54fc4Saliguori         uint8_t head;               /* starting head */
1989f3d54fc4Saliguori         uint8_t sector;             /* starting sector */
1990f3d54fc4Saliguori         uint8_t cyl;                /* starting cylinder */
1991f3d54fc4Saliguori         uint8_t sys_ind;            /* What partition type */
1992f3d54fc4Saliguori         uint8_t end_head;           /* end head */
1993f3d54fc4Saliguori         uint8_t end_sector;         /* end sector */
1994f3d54fc4Saliguori         uint8_t end_cyl;            /* end cylinder */
1995f3d54fc4Saliguori         uint32_t start_sect;        /* starting sector counting from 0 */
1996f3d54fc4Saliguori         uint32_t nr_sects;          /* nr of sectors in partition */
1997541dc0d4SStefan Weil } QEMU_PACKED;
1998f3d54fc4Saliguori 
1999f3d54fc4Saliguori /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
2000f3d54fc4Saliguori static int guess_disk_lchs(BlockDriverState *bs,
2001f3d54fc4Saliguori                            int *pcylinders, int *pheads, int *psectors)
2002f3d54fc4Saliguori {
2003eb5a3165SJes Sorensen     uint8_t buf[BDRV_SECTOR_SIZE];
2004f3d54fc4Saliguori     int ret, i, heads, sectors, cylinders;
2005f3d54fc4Saliguori     struct partition *p;
2006f3d54fc4Saliguori     uint32_t nr_sects;
2007a38131b6Sblueswir1     uint64_t nb_sectors;
2008498e386cSZhi Yong Wu     bool enabled;
2009f3d54fc4Saliguori 
2010f3d54fc4Saliguori     bdrv_get_geometry(bs, &nb_sectors);
2011f3d54fc4Saliguori 
2012498e386cSZhi Yong Wu     /**
2013498e386cSZhi Yong Wu      * The function will be invoked during startup not only in sync I/O mode,
2014498e386cSZhi Yong Wu      * but also in async I/O mode. So the I/O throttling function has to
2015498e386cSZhi Yong Wu      * be disabled temporarily here, not permanently.
2016498e386cSZhi Yong Wu      */
2017498e386cSZhi Yong Wu     enabled = bs->io_limits_enabled;
2018498e386cSZhi Yong Wu     bs->io_limits_enabled = false;
2019f3d54fc4Saliguori     ret = bdrv_read(bs, 0, buf, 1);
2020498e386cSZhi Yong Wu     bs->io_limits_enabled = enabled;
2021f3d54fc4Saliguori     if (ret < 0)
2022f3d54fc4Saliguori         return -1;
2023f3d54fc4Saliguori     /* test msdos magic */
2024f3d54fc4Saliguori     if (buf[510] != 0x55 || buf[511] != 0xaa)
2025f3d54fc4Saliguori         return -1;
2026f3d54fc4Saliguori     for(i = 0; i < 4; i++) {
2027f3d54fc4Saliguori         p = ((struct partition *)(buf + 0x1be)) + i;
2028f3d54fc4Saliguori         nr_sects = le32_to_cpu(p->nr_sects);
2029f3d54fc4Saliguori         if (nr_sects && p->end_head) {
2030f3d54fc4Saliguori             /* We make the assumption that the partition terminates on
2031f3d54fc4Saliguori                a cylinder boundary */
2032f3d54fc4Saliguori             heads = p->end_head + 1;
2033f3d54fc4Saliguori             sectors = p->end_sector & 63;
2034f3d54fc4Saliguori             if (sectors == 0)
2035f3d54fc4Saliguori                 continue;
2036f3d54fc4Saliguori             cylinders = nb_sectors / (heads * sectors);
2037f3d54fc4Saliguori             if (cylinders < 1 || cylinders > 16383)
2038f3d54fc4Saliguori                 continue;
2039f3d54fc4Saliguori             *pheads = heads;
2040f3d54fc4Saliguori             *psectors = sectors;
2041f3d54fc4Saliguori             *pcylinders = cylinders;
2042f3d54fc4Saliguori #if 0
2043f3d54fc4Saliguori             printf("guessed geometry: LCHS=%d %d %d\n",
2044f3d54fc4Saliguori                    cylinders, heads, sectors);
2045f3d54fc4Saliguori #endif
2046f3d54fc4Saliguori             return 0;
2047f3d54fc4Saliguori         }
2048f3d54fc4Saliguori     }
2049f3d54fc4Saliguori     return -1;
2050f3d54fc4Saliguori }
2051f3d54fc4Saliguori 
2052f3d54fc4Saliguori void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
2053f3d54fc4Saliguori {
2054f3d54fc4Saliguori     int translation, lba_detected = 0;
2055f3d54fc4Saliguori     int cylinders, heads, secs;
2056a38131b6Sblueswir1     uint64_t nb_sectors;
2057f3d54fc4Saliguori 
2058f3d54fc4Saliguori     /* if a geometry hint is available, use it */
2059f3d54fc4Saliguori     bdrv_get_geometry(bs, &nb_sectors);
2060f3d54fc4Saliguori     bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
2061f3d54fc4Saliguori     translation = bdrv_get_translation_hint(bs);
2062f3d54fc4Saliguori     if (cylinders != 0) {
2063f3d54fc4Saliguori         *pcyls = cylinders;
2064f3d54fc4Saliguori         *pheads = heads;
2065f3d54fc4Saliguori         *psecs = secs;
2066f3d54fc4Saliguori     } else {
2067f3d54fc4Saliguori         if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
2068f3d54fc4Saliguori             if (heads > 16) {
2069f3d54fc4Saliguori                 /* if heads > 16, it means that a BIOS LBA
2070f3d54fc4Saliguori                    translation was active, so the default
2071f3d54fc4Saliguori                    hardware geometry is OK */
2072f3d54fc4Saliguori                 lba_detected = 1;
2073f3d54fc4Saliguori                 goto default_geometry;
2074f3d54fc4Saliguori             } else {
2075f3d54fc4Saliguori                 *pcyls = cylinders;
2076f3d54fc4Saliguori                 *pheads = heads;
2077f3d54fc4Saliguori                 *psecs = secs;
2078f3d54fc4Saliguori                 /* disable any translation to be in sync with
2079f3d54fc4Saliguori                    the logical geometry */
2080f3d54fc4Saliguori                 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
2081f3d54fc4Saliguori                     bdrv_set_translation_hint(bs,
2082f3d54fc4Saliguori                                               BIOS_ATA_TRANSLATION_NONE);
2083f3d54fc4Saliguori                 }
2084f3d54fc4Saliguori             }
2085f3d54fc4Saliguori         } else {
2086f3d54fc4Saliguori         default_geometry:
2087f3d54fc4Saliguori             /* if no geometry, use a standard physical disk geometry */
2088f3d54fc4Saliguori             cylinders = nb_sectors / (16 * 63);
2089f3d54fc4Saliguori 
2090f3d54fc4Saliguori             if (cylinders > 16383)
2091f3d54fc4Saliguori                 cylinders = 16383;
2092f3d54fc4Saliguori             else if (cylinders < 2)
2093f3d54fc4Saliguori                 cylinders = 2;
2094f3d54fc4Saliguori             *pcyls = cylinders;
2095f3d54fc4Saliguori             *pheads = 16;
2096f3d54fc4Saliguori             *psecs = 63;
2097f3d54fc4Saliguori             if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
2098f3d54fc4Saliguori                 if ((*pcyls * *pheads) <= 131072) {
2099f3d54fc4Saliguori                     bdrv_set_translation_hint(bs,
2100f3d54fc4Saliguori                                               BIOS_ATA_TRANSLATION_LARGE);
2101f3d54fc4Saliguori                 } else {
2102f3d54fc4Saliguori                     bdrv_set_translation_hint(bs,
2103f3d54fc4Saliguori                                               BIOS_ATA_TRANSLATION_LBA);
2104f3d54fc4Saliguori                 }
2105f3d54fc4Saliguori             }
2106f3d54fc4Saliguori         }
2107f3d54fc4Saliguori         bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
2108f3d54fc4Saliguori     }
2109f3d54fc4Saliguori }
2110f3d54fc4Saliguori 
2111b338082bSbellard void bdrv_set_geometry_hint(BlockDriverState *bs,
2112b338082bSbellard                             int cyls, int heads, int secs)
2113b338082bSbellard {
2114b338082bSbellard     bs->cyls = cyls;
2115b338082bSbellard     bs->heads = heads;
2116b338082bSbellard     bs->secs = secs;
2117b338082bSbellard }
2118b338082bSbellard 
211946d4767dSbellard void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
212046d4767dSbellard {
212146d4767dSbellard     bs->translation = translation;
212246d4767dSbellard }
212346d4767dSbellard 
2124b338082bSbellard void bdrv_get_geometry_hint(BlockDriverState *bs,
2125b338082bSbellard                             int *pcyls, int *pheads, int *psecs)
2126b338082bSbellard {
2127b338082bSbellard     *pcyls = bs->cyls;
2128b338082bSbellard     *pheads = bs->heads;
2129b338082bSbellard     *psecs = bs->secs;
2130b338082bSbellard }
2131b338082bSbellard 
21320563e191SZhi Yong Wu /* throttling disk io limits */
21330563e191SZhi Yong Wu void bdrv_set_io_limits(BlockDriverState *bs,
21340563e191SZhi Yong Wu                         BlockIOLimit *io_limits)
21350563e191SZhi Yong Wu {
21360563e191SZhi Yong Wu     bs->io_limits = *io_limits;
21370563e191SZhi Yong Wu     bs->io_limits_enabled = bdrv_io_limits_enabled(bs);
21380563e191SZhi Yong Wu }
21390563e191SZhi Yong Wu 
21405bbdbb46SBlue Swirl /* Recognize floppy formats */
21415bbdbb46SBlue Swirl typedef struct FDFormat {
21425bbdbb46SBlue Swirl     FDriveType drive;
21435bbdbb46SBlue Swirl     uint8_t last_sect;
21445bbdbb46SBlue Swirl     uint8_t max_track;
21455bbdbb46SBlue Swirl     uint8_t max_head;
2146f8d3d128SHervé Poussineau     FDriveRate rate;
21475bbdbb46SBlue Swirl } FDFormat;
21485bbdbb46SBlue Swirl 
21495bbdbb46SBlue Swirl static const FDFormat fd_formats[] = {
21505bbdbb46SBlue Swirl     /* First entry is default format */
21515bbdbb46SBlue Swirl     /* 1.44 MB 3"1/2 floppy disks */
2152f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 18, 80, 1, FDRIVE_RATE_500K, },
2153f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 20, 80, 1, FDRIVE_RATE_500K, },
2154f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 21, 80, 1, FDRIVE_RATE_500K, },
2155f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 21, 82, 1, FDRIVE_RATE_500K, },
2156f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 21, 83, 1, FDRIVE_RATE_500K, },
2157f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 22, 80, 1, FDRIVE_RATE_500K, },
2158f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 23, 80, 1, FDRIVE_RATE_500K, },
2159f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 24, 80, 1, FDRIVE_RATE_500K, },
21605bbdbb46SBlue Swirl     /* 2.88 MB 3"1/2 floppy disks */
2161f8d3d128SHervé Poussineau     { FDRIVE_DRV_288, 36, 80, 1, FDRIVE_RATE_1M, },
2162f8d3d128SHervé Poussineau     { FDRIVE_DRV_288, 39, 80, 1, FDRIVE_RATE_1M, },
2163f8d3d128SHervé Poussineau     { FDRIVE_DRV_288, 40, 80, 1, FDRIVE_RATE_1M, },
2164f8d3d128SHervé Poussineau     { FDRIVE_DRV_288, 44, 80, 1, FDRIVE_RATE_1M, },
2165f8d3d128SHervé Poussineau     { FDRIVE_DRV_288, 48, 80, 1, FDRIVE_RATE_1M, },
21665bbdbb46SBlue Swirl     /* 720 kB 3"1/2 floppy disks */
2167f8d3d128SHervé Poussineau     { FDRIVE_DRV_144,  9, 80, 1, FDRIVE_RATE_250K, },
2168f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 10, 80, 1, FDRIVE_RATE_250K, },
2169f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 10, 82, 1, FDRIVE_RATE_250K, },
2170f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 10, 83, 1, FDRIVE_RATE_250K, },
2171f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 13, 80, 1, FDRIVE_RATE_250K, },
2172f8d3d128SHervé Poussineau     { FDRIVE_DRV_144, 14, 80, 1, FDRIVE_RATE_250K, },
21735bbdbb46SBlue Swirl     /* 1.2 MB 5"1/4 floppy disks */
2174f8d3d128SHervé Poussineau     { FDRIVE_DRV_120, 15, 80, 1, FDRIVE_RATE_500K, },
2175f8d3d128SHervé Poussineau     { FDRIVE_DRV_120, 18, 80, 1, FDRIVE_RATE_500K, },
2176f8d3d128SHervé Poussineau     { FDRIVE_DRV_120, 18, 82, 1, FDRIVE_RATE_500K, },
2177f8d3d128SHervé Poussineau     { FDRIVE_DRV_120, 18, 83, 1, FDRIVE_RATE_500K, },
2178f8d3d128SHervé Poussineau     { FDRIVE_DRV_120, 20, 80, 1, FDRIVE_RATE_500K, },
21795bbdbb46SBlue Swirl     /* 720 kB 5"1/4 floppy disks */
2180f8d3d128SHervé Poussineau     { FDRIVE_DRV_120,  9, 80, 1, FDRIVE_RATE_250K, },
2181f8d3d128SHervé Poussineau     { FDRIVE_DRV_120, 11, 80, 1, FDRIVE_RATE_250K, },
21825bbdbb46SBlue Swirl     /* 360 kB 5"1/4 floppy disks */
2183f8d3d128SHervé Poussineau     { FDRIVE_DRV_120,  9, 40, 1, FDRIVE_RATE_300K, },
2184f8d3d128SHervé Poussineau     { FDRIVE_DRV_120,  9, 40, 0, FDRIVE_RATE_300K, },
2185f8d3d128SHervé Poussineau     { FDRIVE_DRV_120, 10, 41, 1, FDRIVE_RATE_300K, },
2186f8d3d128SHervé Poussineau     { FDRIVE_DRV_120, 10, 42, 1, FDRIVE_RATE_300K, },
21875bbdbb46SBlue Swirl     /* 320 kB 5"1/4 floppy disks */
2188f8d3d128SHervé Poussineau     { FDRIVE_DRV_120,  8, 40, 1, FDRIVE_RATE_250K, },
2189f8d3d128SHervé Poussineau     { FDRIVE_DRV_120,  8, 40, 0, FDRIVE_RATE_250K, },
21905bbdbb46SBlue Swirl     /* 360 kB must match 5"1/4 better than 3"1/2... */
2191f8d3d128SHervé Poussineau     { FDRIVE_DRV_144,  9, 80, 0, FDRIVE_RATE_250K, },
21925bbdbb46SBlue Swirl     /* end */
2193f8d3d128SHervé Poussineau     { FDRIVE_DRV_NONE, -1, -1, 0, 0, },
21945bbdbb46SBlue Swirl };
21955bbdbb46SBlue Swirl 
21965bbdbb46SBlue Swirl void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
21975bbdbb46SBlue Swirl                                    int *max_track, int *last_sect,
2198f8d3d128SHervé Poussineau                                    FDriveType drive_in, FDriveType *drive,
2199f8d3d128SHervé Poussineau                                    FDriveRate *rate)
22005bbdbb46SBlue Swirl {
22015bbdbb46SBlue Swirl     const FDFormat *parse;
22025bbdbb46SBlue Swirl     uint64_t nb_sectors, size;
22035bbdbb46SBlue Swirl     int i, first_match, match;
22045bbdbb46SBlue Swirl 
22055bbdbb46SBlue Swirl     bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
22065bbdbb46SBlue Swirl     if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
22075bbdbb46SBlue Swirl         /* User defined disk */
2208f8d3d128SHervé Poussineau         *rate = FDRIVE_RATE_500K;
22095bbdbb46SBlue Swirl     } else {
22105bbdbb46SBlue Swirl         bdrv_get_geometry(bs, &nb_sectors);
22115bbdbb46SBlue Swirl         match = -1;
22125bbdbb46SBlue Swirl         first_match = -1;
22135bbdbb46SBlue Swirl         for (i = 0; ; i++) {
22145bbdbb46SBlue Swirl             parse = &fd_formats[i];
22155bbdbb46SBlue Swirl             if (parse->drive == FDRIVE_DRV_NONE) {
22165bbdbb46SBlue Swirl                 break;
22175bbdbb46SBlue Swirl             }
22185bbdbb46SBlue Swirl             if (drive_in == parse->drive ||
22195bbdbb46SBlue Swirl                 drive_in == FDRIVE_DRV_NONE) {
22205bbdbb46SBlue Swirl                 size = (parse->max_head + 1) * parse->max_track *
22215bbdbb46SBlue Swirl                     parse->last_sect;
22225bbdbb46SBlue Swirl                 if (nb_sectors == size) {
22235bbdbb46SBlue Swirl                     match = i;
22245bbdbb46SBlue Swirl                     break;
22255bbdbb46SBlue Swirl                 }
22265bbdbb46SBlue Swirl                 if (first_match == -1) {
22275bbdbb46SBlue Swirl                     first_match = i;
22285bbdbb46SBlue Swirl                 }
22295bbdbb46SBlue Swirl             }
22305bbdbb46SBlue Swirl         }
22315bbdbb46SBlue Swirl         if (match == -1) {
22325bbdbb46SBlue Swirl             if (first_match == -1) {
22335bbdbb46SBlue Swirl                 match = 1;
22345bbdbb46SBlue Swirl             } else {
22355bbdbb46SBlue Swirl                 match = first_match;
22365bbdbb46SBlue Swirl             }
22375bbdbb46SBlue Swirl             parse = &fd_formats[match];
22385bbdbb46SBlue Swirl         }
22395bbdbb46SBlue Swirl         *nb_heads = parse->max_head + 1;
22405bbdbb46SBlue Swirl         *max_track = parse->max_track;
22415bbdbb46SBlue Swirl         *last_sect = parse->last_sect;
22425bbdbb46SBlue Swirl         *drive = parse->drive;
2243f8d3d128SHervé Poussineau         *rate = parse->rate;
22445bbdbb46SBlue Swirl     }
22455bbdbb46SBlue Swirl }
22465bbdbb46SBlue Swirl 
224746d4767dSbellard int bdrv_get_translation_hint(BlockDriverState *bs)
224846d4767dSbellard {
224946d4767dSbellard     return bs->translation;
225046d4767dSbellard }
225146d4767dSbellard 
2252abd7f68dSMarkus Armbruster void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
2253abd7f68dSMarkus Armbruster                        BlockErrorAction on_write_error)
2254abd7f68dSMarkus Armbruster {
2255abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
2256abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
2257abd7f68dSMarkus Armbruster }
2258abd7f68dSMarkus Armbruster 
2259abd7f68dSMarkus Armbruster BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
2260abd7f68dSMarkus Armbruster {
2261abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
2262abd7f68dSMarkus Armbruster }
2263abd7f68dSMarkus Armbruster 
2264b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2265b338082bSbellard {
2266b338082bSbellard     return bs->read_only;
2267b338082bSbellard }
2268b338082bSbellard 
2269985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2270985a03b0Sths {
2271985a03b0Sths     return bs->sg;
2272985a03b0Sths }
2273985a03b0Sths 
2274e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
2275e900a7b7SChristoph Hellwig {
2276e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
2277e900a7b7SChristoph Hellwig }
2278e900a7b7SChristoph Hellwig 
2279ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2280ea2384d3Sbellard {
2281ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
2282ea2384d3Sbellard         return 1;
2283ea2384d3Sbellard     return bs->encrypted;
2284ea2384d3Sbellard }
2285ea2384d3Sbellard 
2286c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2287c0f4ce77Saliguori {
2288c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
2289c0f4ce77Saliguori 
2290c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
2291c0f4ce77Saliguori         return 1;
2292c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2293c0f4ce77Saliguori }
2294c0f4ce77Saliguori 
2295ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2296ea2384d3Sbellard {
2297ea2384d3Sbellard     int ret;
2298ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
2299ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
2300ea2384d3Sbellard         if (ret < 0)
2301ea2384d3Sbellard             return ret;
2302ea2384d3Sbellard         if (!bs->encrypted)
2303ea2384d3Sbellard             return 0;
2304ea2384d3Sbellard     }
2305fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2306fd04a2aeSShahar Havivi         return -EINVAL;
2307fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2308fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2309fd04a2aeSShahar Havivi     }
2310c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2311bb5fc20fSaliguori     if (ret < 0) {
2312bb5fc20fSaliguori         bs->valid_key = 0;
2313bb5fc20fSaliguori     } else if (!bs->valid_key) {
2314bb5fc20fSaliguori         bs->valid_key = 1;
2315bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
23167d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
2317bb5fc20fSaliguori     }
2318c0f4ce77Saliguori     return ret;
2319ea2384d3Sbellard }
2320ea2384d3Sbellard 
2321ea2384d3Sbellard void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
2322ea2384d3Sbellard {
232319cb3738Sbellard     if (!bs->drv) {
2324ea2384d3Sbellard         buf[0] = '\0';
2325ea2384d3Sbellard     } else {
2326ea2384d3Sbellard         pstrcpy(buf, buf_size, bs->drv->format_name);
2327ea2384d3Sbellard     }
2328ea2384d3Sbellard }
2329ea2384d3Sbellard 
2330ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2331ea2384d3Sbellard                          void *opaque)
2332ea2384d3Sbellard {
2333ea2384d3Sbellard     BlockDriver *drv;
2334ea2384d3Sbellard 
23358a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2336ea2384d3Sbellard         it(opaque, drv->format_name);
2337ea2384d3Sbellard     }
2338ea2384d3Sbellard }
2339ea2384d3Sbellard 
2340b338082bSbellard BlockDriverState *bdrv_find(const char *name)
2341b338082bSbellard {
2342b338082bSbellard     BlockDriverState *bs;
2343b338082bSbellard 
23441b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
23451b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
2346b338082bSbellard             return bs;
2347b338082bSbellard         }
23481b7bdbc1SStefan Hajnoczi     }
2349b338082bSbellard     return NULL;
2350b338082bSbellard }
2351b338082bSbellard 
23522f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
23532f399b0aSMarkus Armbruster {
23542f399b0aSMarkus Armbruster     if (!bs) {
23552f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
23562f399b0aSMarkus Armbruster     }
23572f399b0aSMarkus Armbruster     return QTAILQ_NEXT(bs, list);
23582f399b0aSMarkus Armbruster }
23592f399b0aSMarkus Armbruster 
236051de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
236181d0912dSbellard {
236281d0912dSbellard     BlockDriverState *bs;
236381d0912dSbellard 
23641b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
236551de9760Saliguori         it(opaque, bs);
236681d0912dSbellard     }
236781d0912dSbellard }
236881d0912dSbellard 
2369ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
2370ea2384d3Sbellard {
2371ea2384d3Sbellard     return bs->device_name;
2372ea2384d3Sbellard }
2373ea2384d3Sbellard 
2374c6ca28d6Saliguori void bdrv_flush_all(void)
2375c6ca28d6Saliguori {
2376c6ca28d6Saliguori     BlockDriverState *bs;
2377c6ca28d6Saliguori 
23781b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
2379c6ca28d6Saliguori         bdrv_flush(bs);
2380c6ca28d6Saliguori     }
23811b7bdbc1SStefan Hajnoczi }
2382c6ca28d6Saliguori 
2383f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
2384f2feebbdSKevin Wolf {
2385f2feebbdSKevin Wolf     assert(bs->drv);
2386f2feebbdSKevin Wolf 
2387336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
2388336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
2389f2feebbdSKevin Wolf     }
2390f2feebbdSKevin Wolf 
2391f2feebbdSKevin Wolf     return 1;
2392f2feebbdSKevin Wolf }
2393f2feebbdSKevin Wolf 
2394376ae3f1SStefan Hajnoczi typedef struct BdrvCoIsAllocatedData {
2395376ae3f1SStefan Hajnoczi     BlockDriverState *bs;
2396376ae3f1SStefan Hajnoczi     int64_t sector_num;
2397376ae3f1SStefan Hajnoczi     int nb_sectors;
2398376ae3f1SStefan Hajnoczi     int *pnum;
2399376ae3f1SStefan Hajnoczi     int ret;
2400376ae3f1SStefan Hajnoczi     bool done;
2401376ae3f1SStefan Hajnoczi } BdrvCoIsAllocatedData;
2402376ae3f1SStefan Hajnoczi 
2403f58c7b35Sths /*
2404f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
2405f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
2406f58c7b35Sths  * hence all their sectors are reported as allocated.
2407f58c7b35Sths  *
2408bd9533e3SStefan Hajnoczi  * If 'sector_num' is beyond the end of the disk image the return value is 0
2409bd9533e3SStefan Hajnoczi  * and 'pnum' is set to 0.
2410bd9533e3SStefan Hajnoczi  *
2411f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
2412f58c7b35Sths  * the specified sector) that are known to be in the same
2413f58c7b35Sths  * allocated/unallocated state.
2414f58c7b35Sths  *
2415bd9533e3SStefan Hajnoczi  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
2416bd9533e3SStefan Hajnoczi  * beyond the end of the disk image it will be clamped.
2417f58c7b35Sths  */
2418060f51c9SStefan Hajnoczi int coroutine_fn bdrv_co_is_allocated(BlockDriverState *bs, int64_t sector_num,
2419060f51c9SStefan Hajnoczi                                       int nb_sectors, int *pnum)
2420f58c7b35Sths {
2421f58c7b35Sths     int64_t n;
2422bd9533e3SStefan Hajnoczi 
24236aebab14SStefan Hajnoczi     if (sector_num >= bs->total_sectors) {
24246aebab14SStefan Hajnoczi         *pnum = 0;
24256aebab14SStefan Hajnoczi         return 0;
24266aebab14SStefan Hajnoczi     }
2427bd9533e3SStefan Hajnoczi 
24286aebab14SStefan Hajnoczi     n = bs->total_sectors - sector_num;
2429bd9533e3SStefan Hajnoczi     if (n < nb_sectors) {
2430bd9533e3SStefan Hajnoczi         nb_sectors = n;
2431bd9533e3SStefan Hajnoczi     }
2432bd9533e3SStefan Hajnoczi 
2433bd9533e3SStefan Hajnoczi     if (!bs->drv->bdrv_co_is_allocated) {
2434bd9533e3SStefan Hajnoczi         *pnum = nb_sectors;
24356aebab14SStefan Hajnoczi         return 1;
24366aebab14SStefan Hajnoczi     }
24376aebab14SStefan Hajnoczi 
2438060f51c9SStefan Hajnoczi     return bs->drv->bdrv_co_is_allocated(bs, sector_num, nb_sectors, pnum);
2439060f51c9SStefan Hajnoczi }
2440060f51c9SStefan Hajnoczi 
2441060f51c9SStefan Hajnoczi /* Coroutine wrapper for bdrv_is_allocated() */
2442060f51c9SStefan Hajnoczi static void coroutine_fn bdrv_is_allocated_co_entry(void *opaque)
2443060f51c9SStefan Hajnoczi {
2444060f51c9SStefan Hajnoczi     BdrvCoIsAllocatedData *data = opaque;
2445060f51c9SStefan Hajnoczi     BlockDriverState *bs = data->bs;
2446060f51c9SStefan Hajnoczi 
2447060f51c9SStefan Hajnoczi     data->ret = bdrv_co_is_allocated(bs, data->sector_num, data->nb_sectors,
2448060f51c9SStefan Hajnoczi                                      data->pnum);
2449060f51c9SStefan Hajnoczi     data->done = true;
2450060f51c9SStefan Hajnoczi }
2451060f51c9SStefan Hajnoczi 
2452060f51c9SStefan Hajnoczi /*
2453060f51c9SStefan Hajnoczi  * Synchronous wrapper around bdrv_co_is_allocated().
2454060f51c9SStefan Hajnoczi  *
2455060f51c9SStefan Hajnoczi  * See bdrv_co_is_allocated() for details.
2456060f51c9SStefan Hajnoczi  */
2457060f51c9SStefan Hajnoczi int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
2458060f51c9SStefan Hajnoczi                       int *pnum)
2459060f51c9SStefan Hajnoczi {
2460376ae3f1SStefan Hajnoczi     Coroutine *co;
2461376ae3f1SStefan Hajnoczi     BdrvCoIsAllocatedData data = {
2462376ae3f1SStefan Hajnoczi         .bs = bs,
2463376ae3f1SStefan Hajnoczi         .sector_num = sector_num,
2464376ae3f1SStefan Hajnoczi         .nb_sectors = nb_sectors,
2465376ae3f1SStefan Hajnoczi         .pnum = pnum,
2466376ae3f1SStefan Hajnoczi         .done = false,
2467376ae3f1SStefan Hajnoczi     };
2468376ae3f1SStefan Hajnoczi 
2469376ae3f1SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_is_allocated_co_entry);
2470376ae3f1SStefan Hajnoczi     qemu_coroutine_enter(co, &data);
2471376ae3f1SStefan Hajnoczi     while (!data.done) {
2472376ae3f1SStefan Hajnoczi         qemu_aio_wait();
2473376ae3f1SStefan Hajnoczi     }
2474376ae3f1SStefan Hajnoczi     return data.ret;
2475376ae3f1SStefan Hajnoczi }
2476f58c7b35Sths 
2477b2023818SLuiz Capitulino BlockInfoList *qmp_query_block(Error **errp)
2478b338082bSbellard {
2479b2023818SLuiz Capitulino     BlockInfoList *head = NULL, *cur_item = NULL;
2480d15e5465SLuiz Capitulino     BlockDriverState *bs;
2481d15e5465SLuiz Capitulino 
24821b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
2483b2023818SLuiz Capitulino         BlockInfoList *info = g_malloc0(sizeof(*info));
2484d15e5465SLuiz Capitulino 
2485b2023818SLuiz Capitulino         info->value = g_malloc0(sizeof(*info->value));
2486b2023818SLuiz Capitulino         info->value->device = g_strdup(bs->device_name);
2487b2023818SLuiz Capitulino         info->value->type = g_strdup("unknown");
2488b2023818SLuiz Capitulino         info->value->locked = bdrv_dev_is_medium_locked(bs);
2489b2023818SLuiz Capitulino         info->value->removable = bdrv_dev_has_removable_media(bs);
2490d15e5465SLuiz Capitulino 
2491e4def80bSMarkus Armbruster         if (bdrv_dev_has_removable_media(bs)) {
2492b2023818SLuiz Capitulino             info->value->has_tray_open = true;
2493b2023818SLuiz Capitulino             info->value->tray_open = bdrv_dev_is_tray_open(bs);
2494e4def80bSMarkus Armbruster         }
2495f04ef601SLuiz Capitulino 
2496f04ef601SLuiz Capitulino         if (bdrv_iostatus_is_enabled(bs)) {
2497b2023818SLuiz Capitulino             info->value->has_io_status = true;
2498b2023818SLuiz Capitulino             info->value->io_status = bs->iostatus;
2499f04ef601SLuiz Capitulino         }
2500f04ef601SLuiz Capitulino 
2501d15e5465SLuiz Capitulino         if (bs->drv) {
2502b2023818SLuiz Capitulino             info->value->has_inserted = true;
2503b2023818SLuiz Capitulino             info->value->inserted = g_malloc0(sizeof(*info->value->inserted));
2504b2023818SLuiz Capitulino             info->value->inserted->file = g_strdup(bs->filename);
2505b2023818SLuiz Capitulino             info->value->inserted->ro = bs->read_only;
2506b2023818SLuiz Capitulino             info->value->inserted->drv = g_strdup(bs->drv->format_name);
2507b2023818SLuiz Capitulino             info->value->inserted->encrypted = bs->encrypted;
2508b2023818SLuiz Capitulino             if (bs->backing_file[0]) {
2509b2023818SLuiz Capitulino                 info->value->inserted->has_backing_file = true;
2510b2023818SLuiz Capitulino                 info->value->inserted->backing_file = g_strdup(bs->backing_file);
2511b2023818SLuiz Capitulino             }
2512727f005eSZhi Yong Wu 
2513727f005eSZhi Yong Wu             if (bs->io_limits_enabled) {
2514727f005eSZhi Yong Wu                 info->value->inserted->bps =
2515727f005eSZhi Yong Wu                                bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
2516727f005eSZhi Yong Wu                 info->value->inserted->bps_rd =
2517727f005eSZhi Yong Wu                                bs->io_limits.bps[BLOCK_IO_LIMIT_READ];
2518727f005eSZhi Yong Wu                 info->value->inserted->bps_wr =
2519727f005eSZhi Yong Wu                                bs->io_limits.bps[BLOCK_IO_LIMIT_WRITE];
2520727f005eSZhi Yong Wu                 info->value->inserted->iops =
2521727f005eSZhi Yong Wu                                bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
2522727f005eSZhi Yong Wu                 info->value->inserted->iops_rd =
2523727f005eSZhi Yong Wu                                bs->io_limits.iops[BLOCK_IO_LIMIT_READ];
2524727f005eSZhi Yong Wu                 info->value->inserted->iops_wr =
2525727f005eSZhi Yong Wu                                bs->io_limits.iops[BLOCK_IO_LIMIT_WRITE];
2526727f005eSZhi Yong Wu             }
2527d15e5465SLuiz Capitulino         }
2528d15e5465SLuiz Capitulino 
2529b2023818SLuiz Capitulino         /* XXX: waiting for the qapi to support GSList */
2530b2023818SLuiz Capitulino         if (!cur_item) {
2531b2023818SLuiz Capitulino             head = cur_item = info;
2532b2023818SLuiz Capitulino         } else {
2533b2023818SLuiz Capitulino             cur_item->next = info;
2534b2023818SLuiz Capitulino             cur_item = info;
2535d15e5465SLuiz Capitulino         }
2536d15e5465SLuiz Capitulino     }
2537d15e5465SLuiz Capitulino 
2538b2023818SLuiz Capitulino     return head;
2539b338082bSbellard }
2540a36e69ddSths 
2541f11f57e4SLuiz Capitulino /* Consider exposing this as a full fledged QMP command */
2542f11f57e4SLuiz Capitulino static BlockStats *qmp_query_blockstat(const BlockDriverState *bs, Error **errp)
2543a36e69ddSths {
2544f11f57e4SLuiz Capitulino     BlockStats *s;
2545218a536aSLuiz Capitulino 
2546f11f57e4SLuiz Capitulino     s = g_malloc0(sizeof(*s));
2547218a536aSLuiz Capitulino 
2548f11f57e4SLuiz Capitulino     if (bs->device_name[0]) {
2549f11f57e4SLuiz Capitulino         s->has_device = true;
2550f11f57e4SLuiz Capitulino         s->device = g_strdup(bs->device_name);
2551218a536aSLuiz Capitulino     }
2552218a536aSLuiz Capitulino 
2553f11f57e4SLuiz Capitulino     s->stats = g_malloc0(sizeof(*s->stats));
2554f11f57e4SLuiz Capitulino     s->stats->rd_bytes = bs->nr_bytes[BDRV_ACCT_READ];
2555f11f57e4SLuiz Capitulino     s->stats->wr_bytes = bs->nr_bytes[BDRV_ACCT_WRITE];
2556f11f57e4SLuiz Capitulino     s->stats->rd_operations = bs->nr_ops[BDRV_ACCT_READ];
2557f11f57e4SLuiz Capitulino     s->stats->wr_operations = bs->nr_ops[BDRV_ACCT_WRITE];
2558f11f57e4SLuiz Capitulino     s->stats->wr_highest_offset = bs->wr_highest_sector * BDRV_SECTOR_SIZE;
2559f11f57e4SLuiz Capitulino     s->stats->flush_operations = bs->nr_ops[BDRV_ACCT_FLUSH];
2560f11f57e4SLuiz Capitulino     s->stats->wr_total_time_ns = bs->total_time_ns[BDRV_ACCT_WRITE];
2561f11f57e4SLuiz Capitulino     s->stats->rd_total_time_ns = bs->total_time_ns[BDRV_ACCT_READ];
2562f11f57e4SLuiz Capitulino     s->stats->flush_total_time_ns = bs->total_time_ns[BDRV_ACCT_FLUSH];
2563294cc35fSKevin Wolf 
2564294cc35fSKevin Wolf     if (bs->file) {
2565f11f57e4SLuiz Capitulino         s->has_parent = true;
2566f11f57e4SLuiz Capitulino         s->parent = qmp_query_blockstat(bs->file, NULL);
2567294cc35fSKevin Wolf     }
2568294cc35fSKevin Wolf 
2569f11f57e4SLuiz Capitulino     return s;
2570294cc35fSKevin Wolf }
2571294cc35fSKevin Wolf 
2572f11f57e4SLuiz Capitulino BlockStatsList *qmp_query_blockstats(Error **errp)
2573218a536aSLuiz Capitulino {
2574f11f57e4SLuiz Capitulino     BlockStatsList *head = NULL, *cur_item = NULL;
2575a36e69ddSths     BlockDriverState *bs;
2576a36e69ddSths 
25771b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
2578f11f57e4SLuiz Capitulino         BlockStatsList *info = g_malloc0(sizeof(*info));
2579f11f57e4SLuiz Capitulino         info->value = qmp_query_blockstat(bs, NULL);
2580f11f57e4SLuiz Capitulino 
2581f11f57e4SLuiz Capitulino         /* XXX: waiting for the qapi to support GSList */
2582f11f57e4SLuiz Capitulino         if (!cur_item) {
2583f11f57e4SLuiz Capitulino             head = cur_item = info;
2584f11f57e4SLuiz Capitulino         } else {
2585f11f57e4SLuiz Capitulino             cur_item->next = info;
2586f11f57e4SLuiz Capitulino             cur_item = info;
2587f11f57e4SLuiz Capitulino         }
2588a36e69ddSths     }
2589218a536aSLuiz Capitulino 
2590f11f57e4SLuiz Capitulino     return head;
2591a36e69ddSths }
2592ea2384d3Sbellard 
2593045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2594045df330Saliguori {
2595045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
2596045df330Saliguori         return bs->backing_file;
2597045df330Saliguori     else if (bs->encrypted)
2598045df330Saliguori         return bs->filename;
2599045df330Saliguori     else
2600045df330Saliguori         return NULL;
2601045df330Saliguori }
2602045df330Saliguori 
260383f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
260483f64091Sbellard                                char *filename, int filename_size)
260583f64091Sbellard {
260683f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
260783f64091Sbellard }
260883f64091Sbellard 
2609faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
2610faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
2611faea38e7Sbellard {
2612faea38e7Sbellard     BlockDriver *drv = bs->drv;
2613faea38e7Sbellard     if (!drv)
261419cb3738Sbellard         return -ENOMEDIUM;
2615faea38e7Sbellard     if (!drv->bdrv_write_compressed)
2616faea38e7Sbellard         return -ENOTSUP;
2617fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
2618fbb7b4e0SKevin Wolf         return -EIO;
26197cd1e32aSlirans@il.ibm.com 
2620c6d22830SJan Kiszka     if (bs->dirty_bitmap) {
26217cd1e32aSlirans@il.ibm.com         set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
26227cd1e32aSlirans@il.ibm.com     }
26237cd1e32aSlirans@il.ibm.com 
2624faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
2625faea38e7Sbellard }
2626faea38e7Sbellard 
2627faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2628faea38e7Sbellard {
2629faea38e7Sbellard     BlockDriver *drv = bs->drv;
2630faea38e7Sbellard     if (!drv)
263119cb3738Sbellard         return -ENOMEDIUM;
2632faea38e7Sbellard     if (!drv->bdrv_get_info)
2633faea38e7Sbellard         return -ENOTSUP;
2634faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
2635faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
2636faea38e7Sbellard }
2637faea38e7Sbellard 
263845566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
263945566e9cSChristoph Hellwig                       int64_t pos, int size)
2640178e08a5Saliguori {
2641178e08a5Saliguori     BlockDriver *drv = bs->drv;
2642178e08a5Saliguori     if (!drv)
2643178e08a5Saliguori         return -ENOMEDIUM;
26447cdb1f6dSMORITA Kazutaka     if (drv->bdrv_save_vmstate)
264545566e9cSChristoph Hellwig         return drv->bdrv_save_vmstate(bs, buf, pos, size);
26467cdb1f6dSMORITA Kazutaka     if (bs->file)
26477cdb1f6dSMORITA Kazutaka         return bdrv_save_vmstate(bs->file, buf, pos, size);
26487cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2649178e08a5Saliguori }
2650178e08a5Saliguori 
265145566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
265245566e9cSChristoph Hellwig                       int64_t pos, int size)
2653178e08a5Saliguori {
2654178e08a5Saliguori     BlockDriver *drv = bs->drv;
2655178e08a5Saliguori     if (!drv)
2656178e08a5Saliguori         return -ENOMEDIUM;
26577cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
265845566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
26597cdb1f6dSMORITA Kazutaka     if (bs->file)
26607cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
26617cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2662178e08a5Saliguori }
2663178e08a5Saliguori 
26648b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
26658b9b0cc2SKevin Wolf {
26668b9b0cc2SKevin Wolf     BlockDriver *drv = bs->drv;
26678b9b0cc2SKevin Wolf 
26688b9b0cc2SKevin Wolf     if (!drv || !drv->bdrv_debug_event) {
26698b9b0cc2SKevin Wolf         return;
26708b9b0cc2SKevin Wolf     }
26718b9b0cc2SKevin Wolf 
26728b9b0cc2SKevin Wolf     return drv->bdrv_debug_event(bs, event);
26738b9b0cc2SKevin Wolf 
26748b9b0cc2SKevin Wolf }
26758b9b0cc2SKevin Wolf 
2676faea38e7Sbellard /**************************************************************/
2677faea38e7Sbellard /* handling of snapshots */
2678faea38e7Sbellard 
2679feeee5acSMiguel Di Ciurcio Filho int bdrv_can_snapshot(BlockDriverState *bs)
2680feeee5acSMiguel Di Ciurcio Filho {
2681feeee5acSMiguel Di Ciurcio Filho     BlockDriver *drv = bs->drv;
268207b70bfbSMarkus Armbruster     if (!drv || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
2683feeee5acSMiguel Di Ciurcio Filho         return 0;
2684feeee5acSMiguel Di Ciurcio Filho     }
2685feeee5acSMiguel Di Ciurcio Filho 
2686feeee5acSMiguel Di Ciurcio Filho     if (!drv->bdrv_snapshot_create) {
2687feeee5acSMiguel Di Ciurcio Filho         if (bs->file != NULL) {
2688feeee5acSMiguel Di Ciurcio Filho             return bdrv_can_snapshot(bs->file);
2689feeee5acSMiguel Di Ciurcio Filho         }
2690feeee5acSMiguel Di Ciurcio Filho         return 0;
2691feeee5acSMiguel Di Ciurcio Filho     }
2692feeee5acSMiguel Di Ciurcio Filho 
2693feeee5acSMiguel Di Ciurcio Filho     return 1;
2694feeee5acSMiguel Di Ciurcio Filho }
2695feeee5acSMiguel Di Ciurcio Filho 
2696199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
2697199630b6SBlue Swirl {
2698199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2699199630b6SBlue Swirl }
2700199630b6SBlue Swirl 
2701f9092b10SMarkus Armbruster BlockDriverState *bdrv_snapshots(void)
2702f9092b10SMarkus Armbruster {
2703f9092b10SMarkus Armbruster     BlockDriverState *bs;
2704f9092b10SMarkus Armbruster 
27053ac906f7SMarkus Armbruster     if (bs_snapshots) {
2706f9092b10SMarkus Armbruster         return bs_snapshots;
27073ac906f7SMarkus Armbruster     }
2708f9092b10SMarkus Armbruster 
2709f9092b10SMarkus Armbruster     bs = NULL;
2710f9092b10SMarkus Armbruster     while ((bs = bdrv_next(bs))) {
2711f9092b10SMarkus Armbruster         if (bdrv_can_snapshot(bs)) {
27123ac906f7SMarkus Armbruster             bs_snapshots = bs;
27133ac906f7SMarkus Armbruster             return bs;
2714f9092b10SMarkus Armbruster         }
2715f9092b10SMarkus Armbruster     }
2716f9092b10SMarkus Armbruster     return NULL;
2717f9092b10SMarkus Armbruster }
2718f9092b10SMarkus Armbruster 
2719faea38e7Sbellard int bdrv_snapshot_create(BlockDriverState *bs,
2720faea38e7Sbellard                          QEMUSnapshotInfo *sn_info)
2721faea38e7Sbellard {
2722faea38e7Sbellard     BlockDriver *drv = bs->drv;
2723faea38e7Sbellard     if (!drv)
272419cb3738Sbellard         return -ENOMEDIUM;
27257cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_create)
2726faea38e7Sbellard         return drv->bdrv_snapshot_create(bs, sn_info);
27277cdb1f6dSMORITA Kazutaka     if (bs->file)
27287cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_create(bs->file, sn_info);
27297cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2730faea38e7Sbellard }
2731faea38e7Sbellard 
2732faea38e7Sbellard int bdrv_snapshot_goto(BlockDriverState *bs,
2733faea38e7Sbellard                        const char *snapshot_id)
2734faea38e7Sbellard {
2735faea38e7Sbellard     BlockDriver *drv = bs->drv;
27367cdb1f6dSMORITA Kazutaka     int ret, open_ret;
27377cdb1f6dSMORITA Kazutaka 
2738faea38e7Sbellard     if (!drv)
273919cb3738Sbellard         return -ENOMEDIUM;
27407cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_goto)
2741faea38e7Sbellard         return drv->bdrv_snapshot_goto(bs, snapshot_id);
27427cdb1f6dSMORITA Kazutaka 
27437cdb1f6dSMORITA Kazutaka     if (bs->file) {
27447cdb1f6dSMORITA Kazutaka         drv->bdrv_close(bs);
27457cdb1f6dSMORITA Kazutaka         ret = bdrv_snapshot_goto(bs->file, snapshot_id);
27467cdb1f6dSMORITA Kazutaka         open_ret = drv->bdrv_open(bs, bs->open_flags);
27477cdb1f6dSMORITA Kazutaka         if (open_ret < 0) {
27487cdb1f6dSMORITA Kazutaka             bdrv_delete(bs->file);
27497cdb1f6dSMORITA Kazutaka             bs->drv = NULL;
27507cdb1f6dSMORITA Kazutaka             return open_ret;
27517cdb1f6dSMORITA Kazutaka         }
27527cdb1f6dSMORITA Kazutaka         return ret;
27537cdb1f6dSMORITA Kazutaka     }
27547cdb1f6dSMORITA Kazutaka 
27557cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2756faea38e7Sbellard }
2757faea38e7Sbellard 
2758faea38e7Sbellard int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2759faea38e7Sbellard {
2760faea38e7Sbellard     BlockDriver *drv = bs->drv;
2761faea38e7Sbellard     if (!drv)
276219cb3738Sbellard         return -ENOMEDIUM;
27637cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_delete)
2764faea38e7Sbellard         return drv->bdrv_snapshot_delete(bs, snapshot_id);
27657cdb1f6dSMORITA Kazutaka     if (bs->file)
27667cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_delete(bs->file, snapshot_id);
27677cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2768faea38e7Sbellard }
2769faea38e7Sbellard 
2770faea38e7Sbellard int bdrv_snapshot_list(BlockDriverState *bs,
2771faea38e7Sbellard                        QEMUSnapshotInfo **psn_info)
2772faea38e7Sbellard {
2773faea38e7Sbellard     BlockDriver *drv = bs->drv;
2774faea38e7Sbellard     if (!drv)
277519cb3738Sbellard         return -ENOMEDIUM;
27767cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_list)
2777faea38e7Sbellard         return drv->bdrv_snapshot_list(bs, psn_info);
27787cdb1f6dSMORITA Kazutaka     if (bs->file)
27797cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_list(bs->file, psn_info);
27807cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
2781faea38e7Sbellard }
2782faea38e7Sbellard 
278351ef6727Sedison int bdrv_snapshot_load_tmp(BlockDriverState *bs,
278451ef6727Sedison         const char *snapshot_name)
278551ef6727Sedison {
278651ef6727Sedison     BlockDriver *drv = bs->drv;
278751ef6727Sedison     if (!drv) {
278851ef6727Sedison         return -ENOMEDIUM;
278951ef6727Sedison     }
279051ef6727Sedison     if (!bs->read_only) {
279151ef6727Sedison         return -EINVAL;
279251ef6727Sedison     }
279351ef6727Sedison     if (drv->bdrv_snapshot_load_tmp) {
279451ef6727Sedison         return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
279551ef6727Sedison     }
279651ef6727Sedison     return -ENOTSUP;
279751ef6727Sedison }
279851ef6727Sedison 
2799e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
2800e8a6bb9cSMarcelo Tosatti         const char *backing_file)
2801e8a6bb9cSMarcelo Tosatti {
2802e8a6bb9cSMarcelo Tosatti     if (!bs->drv) {
2803e8a6bb9cSMarcelo Tosatti         return NULL;
2804e8a6bb9cSMarcelo Tosatti     }
2805e8a6bb9cSMarcelo Tosatti 
2806e8a6bb9cSMarcelo Tosatti     if (bs->backing_hd) {
2807e8a6bb9cSMarcelo Tosatti         if (strcmp(bs->backing_file, backing_file) == 0) {
2808e8a6bb9cSMarcelo Tosatti             return bs->backing_hd;
2809e8a6bb9cSMarcelo Tosatti         } else {
2810e8a6bb9cSMarcelo Tosatti             return bdrv_find_backing_image(bs->backing_hd, backing_file);
2811e8a6bb9cSMarcelo Tosatti         }
2812e8a6bb9cSMarcelo Tosatti     }
2813e8a6bb9cSMarcelo Tosatti 
2814e8a6bb9cSMarcelo Tosatti     return NULL;
2815e8a6bb9cSMarcelo Tosatti }
2816e8a6bb9cSMarcelo Tosatti 
2817faea38e7Sbellard #define NB_SUFFIXES 4
2818faea38e7Sbellard 
2819faea38e7Sbellard char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2820faea38e7Sbellard {
2821faea38e7Sbellard     static const char suffixes[NB_SUFFIXES] = "KMGT";
2822faea38e7Sbellard     int64_t base;
2823faea38e7Sbellard     int i;
2824faea38e7Sbellard 
2825faea38e7Sbellard     if (size <= 999) {
2826faea38e7Sbellard         snprintf(buf, buf_size, "%" PRId64, size);
2827faea38e7Sbellard     } else {
2828faea38e7Sbellard         base = 1024;
2829faea38e7Sbellard         for(i = 0; i < NB_SUFFIXES; i++) {
2830faea38e7Sbellard             if (size < (10 * base)) {
2831faea38e7Sbellard                 snprintf(buf, buf_size, "%0.1f%c",
2832faea38e7Sbellard                          (double)size / base,
2833faea38e7Sbellard                          suffixes[i]);
2834faea38e7Sbellard                 break;
2835faea38e7Sbellard             } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
2836faea38e7Sbellard                 snprintf(buf, buf_size, "%" PRId64 "%c",
2837faea38e7Sbellard                          ((size + (base >> 1)) / base),
2838faea38e7Sbellard                          suffixes[i]);
2839faea38e7Sbellard                 break;
2840faea38e7Sbellard             }
2841faea38e7Sbellard             base = base * 1024;
2842faea38e7Sbellard         }
2843faea38e7Sbellard     }
2844faea38e7Sbellard     return buf;
2845faea38e7Sbellard }
2846faea38e7Sbellard 
2847faea38e7Sbellard char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2848faea38e7Sbellard {
2849faea38e7Sbellard     char buf1[128], date_buf[128], clock_buf[128];
28503b9f94e1Sbellard #ifdef _WIN32
28513b9f94e1Sbellard     struct tm *ptm;
28523b9f94e1Sbellard #else
2853faea38e7Sbellard     struct tm tm;
28543b9f94e1Sbellard #endif
2855faea38e7Sbellard     time_t ti;
2856faea38e7Sbellard     int64_t secs;
2857faea38e7Sbellard 
2858faea38e7Sbellard     if (!sn) {
2859faea38e7Sbellard         snprintf(buf, buf_size,
2860faea38e7Sbellard                  "%-10s%-20s%7s%20s%15s",
2861faea38e7Sbellard                  "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2862faea38e7Sbellard     } else {
2863faea38e7Sbellard         ti = sn->date_sec;
28643b9f94e1Sbellard #ifdef _WIN32
28653b9f94e1Sbellard         ptm = localtime(&ti);
28663b9f94e1Sbellard         strftime(date_buf, sizeof(date_buf),
28673b9f94e1Sbellard                  "%Y-%m-%d %H:%M:%S", ptm);
28683b9f94e1Sbellard #else
2869faea38e7Sbellard         localtime_r(&ti, &tm);
2870faea38e7Sbellard         strftime(date_buf, sizeof(date_buf),
2871faea38e7Sbellard                  "%Y-%m-%d %H:%M:%S", &tm);
28723b9f94e1Sbellard #endif
2873faea38e7Sbellard         secs = sn->vm_clock_nsec / 1000000000;
2874faea38e7Sbellard         snprintf(clock_buf, sizeof(clock_buf),
2875faea38e7Sbellard                  "%02d:%02d:%02d.%03d",
2876faea38e7Sbellard                  (int)(secs / 3600),
2877faea38e7Sbellard                  (int)((secs / 60) % 60),
2878faea38e7Sbellard                  (int)(secs % 60),
2879faea38e7Sbellard                  (int)((sn->vm_clock_nsec / 1000000) % 1000));
2880faea38e7Sbellard         snprintf(buf, buf_size,
2881faea38e7Sbellard                  "%-10s%-20s%7s%20s%15s",
2882faea38e7Sbellard                  sn->id_str, sn->name,
2883faea38e7Sbellard                  get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2884faea38e7Sbellard                  date_buf,
2885faea38e7Sbellard                  clock_buf);
2886faea38e7Sbellard     }
2887faea38e7Sbellard     return buf;
2888faea38e7Sbellard }
2889faea38e7Sbellard 
2890ea2384d3Sbellard /**************************************************************/
289183f64091Sbellard /* async I/Os */
2892ea2384d3Sbellard 
28933b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
2894f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
289583f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
2896ea2384d3Sbellard {
2897bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2898bbf0a440SStefan Hajnoczi 
2899b2a61371SStefan Hajnoczi     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
29008c5873d6SStefan Hajnoczi                                  cb, opaque, false);
290183f64091Sbellard }
290283f64091Sbellard 
2903f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2904f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
290583f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
29067674e7bfSbellard {
2907bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2908bbf0a440SStefan Hajnoczi 
29091a6e115bSStefan Hajnoczi     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
29108c5873d6SStefan Hajnoczi                                  cb, opaque, true);
291183f64091Sbellard }
291283f64091Sbellard 
291340b4f539SKevin Wolf 
291440b4f539SKevin Wolf typedef struct MultiwriteCB {
291540b4f539SKevin Wolf     int error;
291640b4f539SKevin Wolf     int num_requests;
291740b4f539SKevin Wolf     int num_callbacks;
291840b4f539SKevin Wolf     struct {
291940b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
292040b4f539SKevin Wolf         void *opaque;
292140b4f539SKevin Wolf         QEMUIOVector *free_qiov;
292240b4f539SKevin Wolf     } callbacks[];
292340b4f539SKevin Wolf } MultiwriteCB;
292440b4f539SKevin Wolf 
292540b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
292640b4f539SKevin Wolf {
292740b4f539SKevin Wolf     int i;
292840b4f539SKevin Wolf 
292940b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
293040b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
29311e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
29321e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
29331e1ea48dSStefan Hajnoczi         }
29347267c094SAnthony Liguori         g_free(mcb->callbacks[i].free_qiov);
293540b4f539SKevin Wolf     }
293640b4f539SKevin Wolf }
293740b4f539SKevin Wolf 
293840b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
293940b4f539SKevin Wolf {
294040b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
294140b4f539SKevin Wolf 
29426d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
29436d519a5fSStefan Hajnoczi 
2944cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
294540b4f539SKevin Wolf         mcb->error = ret;
294640b4f539SKevin Wolf     }
294740b4f539SKevin Wolf 
294840b4f539SKevin Wolf     mcb->num_requests--;
294940b4f539SKevin Wolf     if (mcb->num_requests == 0) {
295040b4f539SKevin Wolf         multiwrite_user_cb(mcb);
29517267c094SAnthony Liguori         g_free(mcb);
295240b4f539SKevin Wolf     }
295340b4f539SKevin Wolf }
295440b4f539SKevin Wolf 
295540b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
295640b4f539SKevin Wolf {
295777be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
295877be4366SChristoph Hellwig 
295977be4366SChristoph Hellwig     /*
296077be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
296177be4366SChristoph Hellwig      * here as that could overflow the return value.
296277be4366SChristoph Hellwig      */
296377be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
296477be4366SChristoph Hellwig         return 1;
296577be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
296677be4366SChristoph Hellwig         return -1;
296777be4366SChristoph Hellwig     } else {
296877be4366SChristoph Hellwig         return 0;
296977be4366SChristoph Hellwig     }
297040b4f539SKevin Wolf }
297140b4f539SKevin Wolf 
297240b4f539SKevin Wolf /*
297340b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
297440b4f539SKevin Wolf  * requests that remain after merging.
297540b4f539SKevin Wolf  */
297640b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
297740b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
297840b4f539SKevin Wolf {
297940b4f539SKevin Wolf     int i, outidx;
298040b4f539SKevin Wolf 
298140b4f539SKevin Wolf     // Sort requests by start sector
298240b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
298340b4f539SKevin Wolf 
298440b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
298540b4f539SKevin Wolf     // filling up gaps with zero sectors.
298640b4f539SKevin Wolf     outidx = 0;
298740b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
298840b4f539SKevin Wolf         int merge = 0;
298940b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
299040b4f539SKevin Wolf 
2991b6a127a1SPaolo Bonzini         // Handle exactly sequential writes and overlapping writes.
299240b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
299340b4f539SKevin Wolf             merge = 1;
299440b4f539SKevin Wolf         }
299540b4f539SKevin Wolf 
2996e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2997e2a305fbSChristoph Hellwig             merge = 0;
2998e2a305fbSChristoph Hellwig         }
2999e2a305fbSChristoph Hellwig 
300040b4f539SKevin Wolf         if (merge) {
300140b4f539SKevin Wolf             size_t size;
30027267c094SAnthony Liguori             QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
300340b4f539SKevin Wolf             qemu_iovec_init(qiov,
300440b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
300540b4f539SKevin Wolf 
300640b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
300740b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
300840b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
300940b4f539SKevin Wolf             qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
301040b4f539SKevin Wolf 
3011b6a127a1SPaolo Bonzini             // We should need to add any zeros between the two requests
3012b6a127a1SPaolo Bonzini             assert (reqs[i].sector <= oldreq_last);
301340b4f539SKevin Wolf 
301440b4f539SKevin Wolf             // Add the second request
301540b4f539SKevin Wolf             qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
301640b4f539SKevin Wolf 
3017cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
301840b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
301940b4f539SKevin Wolf 
302040b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
302140b4f539SKevin Wolf         } else {
302240b4f539SKevin Wolf             outidx++;
302340b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
302440b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
302540b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
302640b4f539SKevin Wolf         }
302740b4f539SKevin Wolf     }
302840b4f539SKevin Wolf 
302940b4f539SKevin Wolf     return outidx + 1;
303040b4f539SKevin Wolf }
303140b4f539SKevin Wolf 
303240b4f539SKevin Wolf /*
303340b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
303440b4f539SKevin Wolf  *
303540b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
303640b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
303740b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
303840b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
303940b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
304040b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
304140b4f539SKevin Wolf  *
304240b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
304340b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
304440b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
304540b4f539SKevin Wolf  */
304640b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
304740b4f539SKevin Wolf {
304840b4f539SKevin Wolf     MultiwriteCB *mcb;
304940b4f539SKevin Wolf     int i;
305040b4f539SKevin Wolf 
3051301db7c2SRyan Harper     /* don't submit writes if we don't have a medium */
3052301db7c2SRyan Harper     if (bs->drv == NULL) {
3053301db7c2SRyan Harper         for (i = 0; i < num_reqs; i++) {
3054301db7c2SRyan Harper             reqs[i].error = -ENOMEDIUM;
3055301db7c2SRyan Harper         }
3056301db7c2SRyan Harper         return -1;
3057301db7c2SRyan Harper     }
3058301db7c2SRyan Harper 
305940b4f539SKevin Wolf     if (num_reqs == 0) {
306040b4f539SKevin Wolf         return 0;
306140b4f539SKevin Wolf     }
306240b4f539SKevin Wolf 
306340b4f539SKevin Wolf     // Create MultiwriteCB structure
30647267c094SAnthony Liguori     mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
306540b4f539SKevin Wolf     mcb->num_requests = 0;
306640b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
306740b4f539SKevin Wolf 
306840b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
306940b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
307040b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
307140b4f539SKevin Wolf     }
307240b4f539SKevin Wolf 
307340b4f539SKevin Wolf     // Check for mergable requests
307440b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
307540b4f539SKevin Wolf 
30766d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
30776d519a5fSStefan Hajnoczi 
3078df9309fbSPaolo Bonzini     /* Run the aio requests. */
3079df9309fbSPaolo Bonzini     mcb->num_requests = num_reqs;
308040b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
3081ad54ae80SPaolo Bonzini         bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
308240b4f539SKevin Wolf             reqs[i].nb_sectors, multiwrite_cb, mcb);
308340b4f539SKevin Wolf     }
308440b4f539SKevin Wolf 
308540b4f539SKevin Wolf     return 0;
308640b4f539SKevin Wolf }
308740b4f539SKevin Wolf 
308883f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
308983f64091Sbellard {
30906bbff9a0Saliguori     acb->pool->cancel(acb);
309183f64091Sbellard }
309283f64091Sbellard 
309398f90dbaSZhi Yong Wu /* block I/O throttling */
309498f90dbaSZhi Yong Wu static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
309598f90dbaSZhi Yong Wu                  bool is_write, double elapsed_time, uint64_t *wait)
309698f90dbaSZhi Yong Wu {
309798f90dbaSZhi Yong Wu     uint64_t bps_limit = 0;
309898f90dbaSZhi Yong Wu     double   bytes_limit, bytes_base, bytes_res;
309998f90dbaSZhi Yong Wu     double   slice_time, wait_time;
310098f90dbaSZhi Yong Wu 
310198f90dbaSZhi Yong Wu     if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
310298f90dbaSZhi Yong Wu         bps_limit = bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
310398f90dbaSZhi Yong Wu     } else if (bs->io_limits.bps[is_write]) {
310498f90dbaSZhi Yong Wu         bps_limit = bs->io_limits.bps[is_write];
310598f90dbaSZhi Yong Wu     } else {
310698f90dbaSZhi Yong Wu         if (wait) {
310798f90dbaSZhi Yong Wu             *wait = 0;
310898f90dbaSZhi Yong Wu         }
310998f90dbaSZhi Yong Wu 
311098f90dbaSZhi Yong Wu         return false;
311198f90dbaSZhi Yong Wu     }
311298f90dbaSZhi Yong Wu 
311398f90dbaSZhi Yong Wu     slice_time = bs->slice_end - bs->slice_start;
311498f90dbaSZhi Yong Wu     slice_time /= (NANOSECONDS_PER_SECOND);
311598f90dbaSZhi Yong Wu     bytes_limit = bps_limit * slice_time;
311698f90dbaSZhi Yong Wu     bytes_base  = bs->nr_bytes[is_write] - bs->io_base.bytes[is_write];
311798f90dbaSZhi Yong Wu     if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
311898f90dbaSZhi Yong Wu         bytes_base += bs->nr_bytes[!is_write] - bs->io_base.bytes[!is_write];
311998f90dbaSZhi Yong Wu     }
312098f90dbaSZhi Yong Wu 
312198f90dbaSZhi Yong Wu     /* bytes_base: the bytes of data which have been read/written; and
312298f90dbaSZhi Yong Wu      *             it is obtained from the history statistic info.
312398f90dbaSZhi Yong Wu      * bytes_res: the remaining bytes of data which need to be read/written.
312498f90dbaSZhi Yong Wu      * (bytes_base + bytes_res) / bps_limit: used to calcuate
312598f90dbaSZhi Yong Wu      *             the total time for completing reading/writting all data.
312698f90dbaSZhi Yong Wu      */
312798f90dbaSZhi Yong Wu     bytes_res   = (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
312898f90dbaSZhi Yong Wu 
312998f90dbaSZhi Yong Wu     if (bytes_base + bytes_res <= bytes_limit) {
313098f90dbaSZhi Yong Wu         if (wait) {
313198f90dbaSZhi Yong Wu             *wait = 0;
313298f90dbaSZhi Yong Wu         }
313398f90dbaSZhi Yong Wu 
313498f90dbaSZhi Yong Wu         return false;
313598f90dbaSZhi Yong Wu     }
313698f90dbaSZhi Yong Wu 
313798f90dbaSZhi Yong Wu     /* Calc approx time to dispatch */
313898f90dbaSZhi Yong Wu     wait_time = (bytes_base + bytes_res) / bps_limit - elapsed_time;
313998f90dbaSZhi Yong Wu 
314098f90dbaSZhi Yong Wu     /* When the I/O rate at runtime exceeds the limits,
314198f90dbaSZhi Yong Wu      * bs->slice_end need to be extended in order that the current statistic
314298f90dbaSZhi Yong Wu      * info can be kept until the timer fire, so it is increased and tuned
314398f90dbaSZhi Yong Wu      * based on the result of experiment.
314498f90dbaSZhi Yong Wu      */
314598f90dbaSZhi Yong Wu     bs->slice_time = wait_time * BLOCK_IO_SLICE_TIME * 10;
314698f90dbaSZhi Yong Wu     bs->slice_end += bs->slice_time - 3 * BLOCK_IO_SLICE_TIME;
314798f90dbaSZhi Yong Wu     if (wait) {
314898f90dbaSZhi Yong Wu         *wait = wait_time * BLOCK_IO_SLICE_TIME * 10;
314998f90dbaSZhi Yong Wu     }
315098f90dbaSZhi Yong Wu 
315198f90dbaSZhi Yong Wu     return true;
315298f90dbaSZhi Yong Wu }
315398f90dbaSZhi Yong Wu 
315498f90dbaSZhi Yong Wu static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
315598f90dbaSZhi Yong Wu                              double elapsed_time, uint64_t *wait)
315698f90dbaSZhi Yong Wu {
315798f90dbaSZhi Yong Wu     uint64_t iops_limit = 0;
315898f90dbaSZhi Yong Wu     double   ios_limit, ios_base;
315998f90dbaSZhi Yong Wu     double   slice_time, wait_time;
316098f90dbaSZhi Yong Wu 
316198f90dbaSZhi Yong Wu     if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
316298f90dbaSZhi Yong Wu         iops_limit = bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
316398f90dbaSZhi Yong Wu     } else if (bs->io_limits.iops[is_write]) {
316498f90dbaSZhi Yong Wu         iops_limit = bs->io_limits.iops[is_write];
316598f90dbaSZhi Yong Wu     } else {
316698f90dbaSZhi Yong Wu         if (wait) {
316798f90dbaSZhi Yong Wu             *wait = 0;
316898f90dbaSZhi Yong Wu         }
316998f90dbaSZhi Yong Wu 
317098f90dbaSZhi Yong Wu         return false;
317198f90dbaSZhi Yong Wu     }
317298f90dbaSZhi Yong Wu 
317398f90dbaSZhi Yong Wu     slice_time = bs->slice_end - bs->slice_start;
317498f90dbaSZhi Yong Wu     slice_time /= (NANOSECONDS_PER_SECOND);
317598f90dbaSZhi Yong Wu     ios_limit  = iops_limit * slice_time;
317698f90dbaSZhi Yong Wu     ios_base   = bs->nr_ops[is_write] - bs->io_base.ios[is_write];
317798f90dbaSZhi Yong Wu     if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
317898f90dbaSZhi Yong Wu         ios_base += bs->nr_ops[!is_write] - bs->io_base.ios[!is_write];
317998f90dbaSZhi Yong Wu     }
318098f90dbaSZhi Yong Wu 
318198f90dbaSZhi Yong Wu     if (ios_base + 1 <= ios_limit) {
318298f90dbaSZhi Yong Wu         if (wait) {
318398f90dbaSZhi Yong Wu             *wait = 0;
318498f90dbaSZhi Yong Wu         }
318598f90dbaSZhi Yong Wu 
318698f90dbaSZhi Yong Wu         return false;
318798f90dbaSZhi Yong Wu     }
318898f90dbaSZhi Yong Wu 
318998f90dbaSZhi Yong Wu     /* Calc approx time to dispatch */
319098f90dbaSZhi Yong Wu     wait_time = (ios_base + 1) / iops_limit;
319198f90dbaSZhi Yong Wu     if (wait_time > elapsed_time) {
319298f90dbaSZhi Yong Wu         wait_time = wait_time - elapsed_time;
319398f90dbaSZhi Yong Wu     } else {
319498f90dbaSZhi Yong Wu         wait_time = 0;
319598f90dbaSZhi Yong Wu     }
319698f90dbaSZhi Yong Wu 
319798f90dbaSZhi Yong Wu     bs->slice_time = wait_time * BLOCK_IO_SLICE_TIME * 10;
319898f90dbaSZhi Yong Wu     bs->slice_end += bs->slice_time - 3 * BLOCK_IO_SLICE_TIME;
319998f90dbaSZhi Yong Wu     if (wait) {
320098f90dbaSZhi Yong Wu         *wait = wait_time * BLOCK_IO_SLICE_TIME * 10;
320198f90dbaSZhi Yong Wu     }
320298f90dbaSZhi Yong Wu 
320398f90dbaSZhi Yong Wu     return true;
320498f90dbaSZhi Yong Wu }
320598f90dbaSZhi Yong Wu 
320698f90dbaSZhi Yong Wu static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
320798f90dbaSZhi Yong Wu                            bool is_write, int64_t *wait)
320898f90dbaSZhi Yong Wu {
320998f90dbaSZhi Yong Wu     int64_t  now, max_wait;
321098f90dbaSZhi Yong Wu     uint64_t bps_wait = 0, iops_wait = 0;
321198f90dbaSZhi Yong Wu     double   elapsed_time;
321298f90dbaSZhi Yong Wu     int      bps_ret, iops_ret;
321398f90dbaSZhi Yong Wu 
321498f90dbaSZhi Yong Wu     now = qemu_get_clock_ns(vm_clock);
321598f90dbaSZhi Yong Wu     if ((bs->slice_start < now)
321698f90dbaSZhi Yong Wu         && (bs->slice_end > now)) {
321798f90dbaSZhi Yong Wu         bs->slice_end = now + bs->slice_time;
321898f90dbaSZhi Yong Wu     } else {
321998f90dbaSZhi Yong Wu         bs->slice_time  =  5 * BLOCK_IO_SLICE_TIME;
322098f90dbaSZhi Yong Wu         bs->slice_start = now;
322198f90dbaSZhi Yong Wu         bs->slice_end   = now + bs->slice_time;
322298f90dbaSZhi Yong Wu 
322398f90dbaSZhi Yong Wu         bs->io_base.bytes[is_write]  = bs->nr_bytes[is_write];
322498f90dbaSZhi Yong Wu         bs->io_base.bytes[!is_write] = bs->nr_bytes[!is_write];
322598f90dbaSZhi Yong Wu 
322698f90dbaSZhi Yong Wu         bs->io_base.ios[is_write]    = bs->nr_ops[is_write];
322798f90dbaSZhi Yong Wu         bs->io_base.ios[!is_write]   = bs->nr_ops[!is_write];
322898f90dbaSZhi Yong Wu     }
322998f90dbaSZhi Yong Wu 
323098f90dbaSZhi Yong Wu     elapsed_time  = now - bs->slice_start;
323198f90dbaSZhi Yong Wu     elapsed_time  /= (NANOSECONDS_PER_SECOND);
323298f90dbaSZhi Yong Wu 
323398f90dbaSZhi Yong Wu     bps_ret  = bdrv_exceed_bps_limits(bs, nb_sectors,
323498f90dbaSZhi Yong Wu                                       is_write, elapsed_time, &bps_wait);
323598f90dbaSZhi Yong Wu     iops_ret = bdrv_exceed_iops_limits(bs, is_write,
323698f90dbaSZhi Yong Wu                                       elapsed_time, &iops_wait);
323798f90dbaSZhi Yong Wu     if (bps_ret || iops_ret) {
323898f90dbaSZhi Yong Wu         max_wait = bps_wait > iops_wait ? bps_wait : iops_wait;
323998f90dbaSZhi Yong Wu         if (wait) {
324098f90dbaSZhi Yong Wu             *wait = max_wait;
324198f90dbaSZhi Yong Wu         }
324298f90dbaSZhi Yong Wu 
324398f90dbaSZhi Yong Wu         now = qemu_get_clock_ns(vm_clock);
324498f90dbaSZhi Yong Wu         if (bs->slice_end < now + max_wait) {
324598f90dbaSZhi Yong Wu             bs->slice_end = now + max_wait;
324698f90dbaSZhi Yong Wu         }
324798f90dbaSZhi Yong Wu 
324898f90dbaSZhi Yong Wu         return true;
324998f90dbaSZhi Yong Wu     }
325098f90dbaSZhi Yong Wu 
325198f90dbaSZhi Yong Wu     if (wait) {
325298f90dbaSZhi Yong Wu         *wait = 0;
325398f90dbaSZhi Yong Wu     }
325498f90dbaSZhi Yong Wu 
325598f90dbaSZhi Yong Wu     return false;
325698f90dbaSZhi Yong Wu }
325783f64091Sbellard 
325883f64091Sbellard /**************************************************************/
325983f64091Sbellard /* async block device emulation */
326083f64091Sbellard 
3261c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
3262c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
3263c16b5a2cSChristoph Hellwig     QEMUBH *bh;
3264c16b5a2cSChristoph Hellwig     int ret;
3265c16b5a2cSChristoph Hellwig     /* vector translation state */
3266c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
3267c16b5a2cSChristoph Hellwig     uint8_t *bounce;
3268c16b5a2cSChristoph Hellwig     int is_write;
3269c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
3270c16b5a2cSChristoph Hellwig 
3271c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
3272c16b5a2cSChristoph Hellwig {
3273b666d239SKevin Wolf     BlockDriverAIOCBSync *acb =
3274b666d239SKevin Wolf         container_of(blockacb, BlockDriverAIOCBSync, common);
32756a7ad299SDor Laor     qemu_bh_delete(acb->bh);
327636afc451SAvi Kivity     acb->bh = NULL;
3277c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
3278c16b5a2cSChristoph Hellwig }
3279c16b5a2cSChristoph Hellwig 
3280c16b5a2cSChristoph Hellwig static AIOPool bdrv_em_aio_pool = {
3281c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
3282c16b5a2cSChristoph Hellwig     .cancel             = bdrv_aio_cancel_em,
3283c16b5a2cSChristoph Hellwig };
3284c16b5a2cSChristoph Hellwig 
328583f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
3286beac80cdSbellard {
3287ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
3288f141eafeSaliguori 
3289f141eafeSaliguori     if (!acb->is_write)
3290f141eafeSaliguori         qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
3291ceb42de8Saliguori     qemu_vfree(acb->bounce);
3292ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
32936a7ad299SDor Laor     qemu_bh_delete(acb->bh);
329436afc451SAvi Kivity     acb->bh = NULL;
3295ce1a14dcSpbrook     qemu_aio_release(acb);
3296beac80cdSbellard }
3297beac80cdSbellard 
3298f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
3299f141eafeSaliguori                                             int64_t sector_num,
3300f141eafeSaliguori                                             QEMUIOVector *qiov,
3301f141eafeSaliguori                                             int nb_sectors,
3302f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
3303f141eafeSaliguori                                             void *opaque,
3304f141eafeSaliguori                                             int is_write)
3305f141eafeSaliguori 
3306ea2384d3Sbellard {
3307ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
330883f64091Sbellard 
3309c16b5a2cSChristoph Hellwig     acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
3310f141eafeSaliguori     acb->is_write = is_write;
3311f141eafeSaliguori     acb->qiov = qiov;
3312e268ca52Saliguori     acb->bounce = qemu_blockalign(bs, qiov->size);
3313ce1a14dcSpbrook     acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
3314f141eafeSaliguori 
3315f141eafeSaliguori     if (is_write) {
3316f141eafeSaliguori         qemu_iovec_to_buffer(acb->qiov, acb->bounce);
33171ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
3318f141eafeSaliguori     } else {
33191ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
3320f141eafeSaliguori     }
3321f141eafeSaliguori 
3322ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
3323f141eafeSaliguori 
3324ce1a14dcSpbrook     return &acb->common;
33257a6cba61Spbrook }
33267a6cba61Spbrook 
3327f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
3328f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
3329ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
333083f64091Sbellard {
3331f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
333283f64091Sbellard }
333383f64091Sbellard 
3334f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
3335f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
3336f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
3337f141eafeSaliguori {
3338f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
3339f141eafeSaliguori }
3340f141eafeSaliguori 
334168485420SKevin Wolf 
334268485420SKevin Wolf typedef struct BlockDriverAIOCBCoroutine {
334368485420SKevin Wolf     BlockDriverAIOCB common;
334468485420SKevin Wolf     BlockRequest req;
334568485420SKevin Wolf     bool is_write;
334668485420SKevin Wolf     QEMUBH* bh;
334768485420SKevin Wolf } BlockDriverAIOCBCoroutine;
334868485420SKevin Wolf 
334968485420SKevin Wolf static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
335068485420SKevin Wolf {
335168485420SKevin Wolf     qemu_aio_flush();
335268485420SKevin Wolf }
335368485420SKevin Wolf 
335468485420SKevin Wolf static AIOPool bdrv_em_co_aio_pool = {
335568485420SKevin Wolf     .aiocb_size         = sizeof(BlockDriverAIOCBCoroutine),
335668485420SKevin Wolf     .cancel             = bdrv_aio_co_cancel_em,
335768485420SKevin Wolf };
335868485420SKevin Wolf 
335935246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque)
336068485420SKevin Wolf {
336168485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb = opaque;
336268485420SKevin Wolf 
336368485420SKevin Wolf     acb->common.cb(acb->common.opaque, acb->req.error);
336468485420SKevin Wolf     qemu_bh_delete(acb->bh);
336568485420SKevin Wolf     qemu_aio_release(acb);
336668485420SKevin Wolf }
336768485420SKevin Wolf 
3368b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
3369b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque)
3370b2a61371SStefan Hajnoczi {
3371b2a61371SStefan Hajnoczi     BlockDriverAIOCBCoroutine *acb = opaque;
3372b2a61371SStefan Hajnoczi     BlockDriverState *bs = acb->common.bs;
3373b2a61371SStefan Hajnoczi 
3374b2a61371SStefan Hajnoczi     if (!acb->is_write) {
3375b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
3376470c0504SStefan Hajnoczi             acb->req.nb_sectors, acb->req.qiov, 0);
3377b2a61371SStefan Hajnoczi     } else {
3378b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
3379f08f2ddaSStefan Hajnoczi             acb->req.nb_sectors, acb->req.qiov, 0);
3380b2a61371SStefan Hajnoczi     }
3381b2a61371SStefan Hajnoczi 
338235246a68SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
3383b2a61371SStefan Hajnoczi     qemu_bh_schedule(acb->bh);
3384b2a61371SStefan Hajnoczi }
3385b2a61371SStefan Hajnoczi 
338668485420SKevin Wolf static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
338768485420SKevin Wolf                                                int64_t sector_num,
338868485420SKevin Wolf                                                QEMUIOVector *qiov,
338968485420SKevin Wolf                                                int nb_sectors,
339068485420SKevin Wolf                                                BlockDriverCompletionFunc *cb,
339168485420SKevin Wolf                                                void *opaque,
33928c5873d6SStefan Hajnoczi                                                bool is_write)
339368485420SKevin Wolf {
339468485420SKevin Wolf     Coroutine *co;
339568485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb;
339668485420SKevin Wolf 
339768485420SKevin Wolf     acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
339868485420SKevin Wolf     acb->req.sector = sector_num;
339968485420SKevin Wolf     acb->req.nb_sectors = nb_sectors;
340068485420SKevin Wolf     acb->req.qiov = qiov;
340168485420SKevin Wolf     acb->is_write = is_write;
340268485420SKevin Wolf 
34038c5873d6SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_co_do_rw);
340468485420SKevin Wolf     qemu_coroutine_enter(co, acb);
340568485420SKevin Wolf 
340668485420SKevin Wolf     return &acb->common;
340768485420SKevin Wolf }
340868485420SKevin Wolf 
340907f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
3410b2e12bc6SChristoph Hellwig {
341107f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
341207f07615SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
3413b2e12bc6SChristoph Hellwig 
341407f07615SPaolo Bonzini     acb->req.error = bdrv_co_flush(bs);
341507f07615SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
3416b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
3417b2e12bc6SChristoph Hellwig }
3418b2e12bc6SChristoph Hellwig 
341907f07615SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
3420016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
3421016f5cf6SAlexander Graf {
342207f07615SPaolo Bonzini     trace_bdrv_aio_flush(bs, opaque);
3423016f5cf6SAlexander Graf 
342407f07615SPaolo Bonzini     Coroutine *co;
342507f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
3426016f5cf6SAlexander Graf 
342707f07615SPaolo Bonzini     acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
342807f07615SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
342907f07615SPaolo Bonzini     qemu_coroutine_enter(co, acb);
3430016f5cf6SAlexander Graf 
3431016f5cf6SAlexander Graf     return &acb->common;
3432016f5cf6SAlexander Graf }
3433016f5cf6SAlexander Graf 
34344265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
34354265d620SPaolo Bonzini {
34364265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
34374265d620SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
34384265d620SPaolo Bonzini 
34394265d620SPaolo Bonzini     acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
34404265d620SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
34414265d620SPaolo Bonzini     qemu_bh_schedule(acb->bh);
34424265d620SPaolo Bonzini }
34434265d620SPaolo Bonzini 
34444265d620SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
34454265d620SPaolo Bonzini         int64_t sector_num, int nb_sectors,
34464265d620SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
34474265d620SPaolo Bonzini {
34484265d620SPaolo Bonzini     Coroutine *co;
34494265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
34504265d620SPaolo Bonzini 
34514265d620SPaolo Bonzini     trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
34524265d620SPaolo Bonzini 
34534265d620SPaolo Bonzini     acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
34544265d620SPaolo Bonzini     acb->req.sector = sector_num;
34554265d620SPaolo Bonzini     acb->req.nb_sectors = nb_sectors;
34564265d620SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
34574265d620SPaolo Bonzini     qemu_coroutine_enter(co, acb);
34584265d620SPaolo Bonzini 
34594265d620SPaolo Bonzini     return &acb->common;
34604265d620SPaolo Bonzini }
34614265d620SPaolo Bonzini 
3462ea2384d3Sbellard void bdrv_init(void)
3463ea2384d3Sbellard {
34645efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
3465ea2384d3Sbellard }
3466ce1a14dcSpbrook 
3467eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
3468eb852011SMarkus Armbruster {
3469eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
3470eb852011SMarkus Armbruster     bdrv_init();
3471eb852011SMarkus Armbruster }
3472eb852011SMarkus Armbruster 
3473c16b5a2cSChristoph Hellwig void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
34746bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
34756bbff9a0Saliguori {
3476ce1a14dcSpbrook     BlockDriverAIOCB *acb;
3477ce1a14dcSpbrook 
34786bbff9a0Saliguori     if (pool->free_aiocb) {
34796bbff9a0Saliguori         acb = pool->free_aiocb;
34806bbff9a0Saliguori         pool->free_aiocb = acb->next;
3481ce1a14dcSpbrook     } else {
34827267c094SAnthony Liguori         acb = g_malloc0(pool->aiocb_size);
34836bbff9a0Saliguori         acb->pool = pool;
3484ce1a14dcSpbrook     }
3485ce1a14dcSpbrook     acb->bs = bs;
3486ce1a14dcSpbrook     acb->cb = cb;
3487ce1a14dcSpbrook     acb->opaque = opaque;
3488ce1a14dcSpbrook     return acb;
3489ce1a14dcSpbrook }
3490ce1a14dcSpbrook 
3491ce1a14dcSpbrook void qemu_aio_release(void *p)
3492ce1a14dcSpbrook {
34936bbff9a0Saliguori     BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
34946bbff9a0Saliguori     AIOPool *pool = acb->pool;
34956bbff9a0Saliguori     acb->next = pool->free_aiocb;
34966bbff9a0Saliguori     pool->free_aiocb = acb;
3497ce1a14dcSpbrook }
349819cb3738Sbellard 
349919cb3738Sbellard /**************************************************************/
3500f9f05dc5SKevin Wolf /* Coroutine block device emulation */
3501f9f05dc5SKevin Wolf 
3502f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion {
3503f9f05dc5SKevin Wolf     Coroutine *coroutine;
3504f9f05dc5SKevin Wolf     int ret;
3505f9f05dc5SKevin Wolf } CoroutineIOCompletion;
3506f9f05dc5SKevin Wolf 
3507f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret)
3508f9f05dc5SKevin Wolf {
3509f9f05dc5SKevin Wolf     CoroutineIOCompletion *co = opaque;
3510f9f05dc5SKevin Wolf 
3511f9f05dc5SKevin Wolf     co->ret = ret;
3512f9f05dc5SKevin Wolf     qemu_coroutine_enter(co->coroutine, NULL);
3513f9f05dc5SKevin Wolf }
3514f9f05dc5SKevin Wolf 
3515f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
3516f9f05dc5SKevin Wolf                                       int nb_sectors, QEMUIOVector *iov,
3517f9f05dc5SKevin Wolf                                       bool is_write)
3518f9f05dc5SKevin Wolf {
3519f9f05dc5SKevin Wolf     CoroutineIOCompletion co = {
3520f9f05dc5SKevin Wolf         .coroutine = qemu_coroutine_self(),
3521f9f05dc5SKevin Wolf     };
3522f9f05dc5SKevin Wolf     BlockDriverAIOCB *acb;
3523f9f05dc5SKevin Wolf 
3524f9f05dc5SKevin Wolf     if (is_write) {
3525a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
3526f9f05dc5SKevin Wolf                                        bdrv_co_io_em_complete, &co);
3527f9f05dc5SKevin Wolf     } else {
3528a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
3529f9f05dc5SKevin Wolf                                       bdrv_co_io_em_complete, &co);
3530f9f05dc5SKevin Wolf     }
3531f9f05dc5SKevin Wolf 
353259370aaaSStefan Hajnoczi     trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
3533f9f05dc5SKevin Wolf     if (!acb) {
3534f9f05dc5SKevin Wolf         return -EIO;
3535f9f05dc5SKevin Wolf     }
3536f9f05dc5SKevin Wolf     qemu_coroutine_yield();
3537f9f05dc5SKevin Wolf 
3538f9f05dc5SKevin Wolf     return co.ret;
3539f9f05dc5SKevin Wolf }
3540f9f05dc5SKevin Wolf 
3541f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
3542f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
3543f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
3544f9f05dc5SKevin Wolf {
3545f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
3546f9f05dc5SKevin Wolf }
3547f9f05dc5SKevin Wolf 
3548f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
3549f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
3550f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
3551f9f05dc5SKevin Wolf {
3552f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
3553f9f05dc5SKevin Wolf }
3554f9f05dc5SKevin Wolf 
355507f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque)
3556e7a8a783SKevin Wolf {
355707f07615SPaolo Bonzini     RwCo *rwco = opaque;
355807f07615SPaolo Bonzini 
355907f07615SPaolo Bonzini     rwco->ret = bdrv_co_flush(rwco->bs);
356007f07615SPaolo Bonzini }
356107f07615SPaolo Bonzini 
356207f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
356307f07615SPaolo Bonzini {
3564eb489bb1SKevin Wolf     int ret;
3565eb489bb1SKevin Wolf 
356629cdb251SPaolo Bonzini     if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
356707f07615SPaolo Bonzini         return 0;
3568eb489bb1SKevin Wolf     }
3569eb489bb1SKevin Wolf 
3570ca716364SKevin Wolf     /* Write back cached data to the OS even with cache=unsafe */
3571eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_os) {
3572eb489bb1SKevin Wolf         ret = bs->drv->bdrv_co_flush_to_os(bs);
3573eb489bb1SKevin Wolf         if (ret < 0) {
3574eb489bb1SKevin Wolf             return ret;
3575eb489bb1SKevin Wolf         }
3576eb489bb1SKevin Wolf     }
3577eb489bb1SKevin Wolf 
3578ca716364SKevin Wolf     /* But don't actually force it to the disk with cache=unsafe */
3579ca716364SKevin Wolf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
3580ca716364SKevin Wolf         return 0;
3581ca716364SKevin Wolf     }
3582ca716364SKevin Wolf 
3583eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_disk) {
358429cdb251SPaolo Bonzini         ret = bs->drv->bdrv_co_flush_to_disk(bs);
358507f07615SPaolo Bonzini     } else if (bs->drv->bdrv_aio_flush) {
358607f07615SPaolo Bonzini         BlockDriverAIOCB *acb;
3587e7a8a783SKevin Wolf         CoroutineIOCompletion co = {
3588e7a8a783SKevin Wolf             .coroutine = qemu_coroutine_self(),
3589e7a8a783SKevin Wolf         };
3590e7a8a783SKevin Wolf 
359107f07615SPaolo Bonzini         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
359207f07615SPaolo Bonzini         if (acb == NULL) {
359329cdb251SPaolo Bonzini             ret = -EIO;
359407f07615SPaolo Bonzini         } else {
3595e7a8a783SKevin Wolf             qemu_coroutine_yield();
359629cdb251SPaolo Bonzini             ret = co.ret;
3597e7a8a783SKevin Wolf         }
359807f07615SPaolo Bonzini     } else {
359907f07615SPaolo Bonzini         /*
360007f07615SPaolo Bonzini          * Some block drivers always operate in either writethrough or unsafe
360107f07615SPaolo Bonzini          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
360207f07615SPaolo Bonzini          * know how the server works (because the behaviour is hardcoded or
360307f07615SPaolo Bonzini          * depends on server-side configuration), so we can't ensure that
360407f07615SPaolo Bonzini          * everything is safe on disk. Returning an error doesn't work because
360507f07615SPaolo Bonzini          * that would break guests even if the server operates in writethrough
360607f07615SPaolo Bonzini          * mode.
360707f07615SPaolo Bonzini          *
360807f07615SPaolo Bonzini          * Let's hope the user knows what he's doing.
360907f07615SPaolo Bonzini          */
361029cdb251SPaolo Bonzini         ret = 0;
361107f07615SPaolo Bonzini     }
361229cdb251SPaolo Bonzini     if (ret < 0) {
361329cdb251SPaolo Bonzini         return ret;
361429cdb251SPaolo Bonzini     }
361529cdb251SPaolo Bonzini 
361629cdb251SPaolo Bonzini     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
361729cdb251SPaolo Bonzini      * in the case of cache=unsafe, so there are no useless flushes.
361829cdb251SPaolo Bonzini      */
361929cdb251SPaolo Bonzini     return bdrv_co_flush(bs->file);
362007f07615SPaolo Bonzini }
362107f07615SPaolo Bonzini 
36220f15423cSAnthony Liguori void bdrv_invalidate_cache(BlockDriverState *bs)
36230f15423cSAnthony Liguori {
36240f15423cSAnthony Liguori     if (bs->drv && bs->drv->bdrv_invalidate_cache) {
36250f15423cSAnthony Liguori         bs->drv->bdrv_invalidate_cache(bs);
36260f15423cSAnthony Liguori     }
36270f15423cSAnthony Liguori }
36280f15423cSAnthony Liguori 
36290f15423cSAnthony Liguori void bdrv_invalidate_cache_all(void)
36300f15423cSAnthony Liguori {
36310f15423cSAnthony Liguori     BlockDriverState *bs;
36320f15423cSAnthony Liguori 
36330f15423cSAnthony Liguori     QTAILQ_FOREACH(bs, &bdrv_states, list) {
36340f15423cSAnthony Liguori         bdrv_invalidate_cache(bs);
36350f15423cSAnthony Liguori     }
36360f15423cSAnthony Liguori }
36370f15423cSAnthony Liguori 
363807789269SBenoît Canet void bdrv_clear_incoming_migration_all(void)
363907789269SBenoît Canet {
364007789269SBenoît Canet     BlockDriverState *bs;
364107789269SBenoît Canet 
364207789269SBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, list) {
364307789269SBenoît Canet         bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
364407789269SBenoît Canet     }
364507789269SBenoît Canet }
364607789269SBenoît Canet 
364707f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs)
364807f07615SPaolo Bonzini {
364907f07615SPaolo Bonzini     Coroutine *co;
365007f07615SPaolo Bonzini     RwCo rwco = {
365107f07615SPaolo Bonzini         .bs = bs,
365207f07615SPaolo Bonzini         .ret = NOT_DONE,
365307f07615SPaolo Bonzini     };
365407f07615SPaolo Bonzini 
365507f07615SPaolo Bonzini     if (qemu_in_coroutine()) {
365607f07615SPaolo Bonzini         /* Fast-path if already in coroutine context */
365707f07615SPaolo Bonzini         bdrv_flush_co_entry(&rwco);
365807f07615SPaolo Bonzini     } else {
365907f07615SPaolo Bonzini         co = qemu_coroutine_create(bdrv_flush_co_entry);
366007f07615SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
366107f07615SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
366207f07615SPaolo Bonzini             qemu_aio_wait();
366307f07615SPaolo Bonzini         }
366407f07615SPaolo Bonzini     }
366507f07615SPaolo Bonzini 
366607f07615SPaolo Bonzini     return rwco.ret;
366707f07615SPaolo Bonzini }
3668e7a8a783SKevin Wolf 
36694265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque)
36704265d620SPaolo Bonzini {
36714265d620SPaolo Bonzini     RwCo *rwco = opaque;
36724265d620SPaolo Bonzini 
36734265d620SPaolo Bonzini     rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
36744265d620SPaolo Bonzini }
36754265d620SPaolo Bonzini 
36764265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
36774265d620SPaolo Bonzini                                  int nb_sectors)
36784265d620SPaolo Bonzini {
36794265d620SPaolo Bonzini     if (!bs->drv) {
36804265d620SPaolo Bonzini         return -ENOMEDIUM;
36814265d620SPaolo Bonzini     } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
36824265d620SPaolo Bonzini         return -EIO;
36834265d620SPaolo Bonzini     } else if (bs->read_only) {
36844265d620SPaolo Bonzini         return -EROFS;
36854265d620SPaolo Bonzini     } else if (bs->drv->bdrv_co_discard) {
36864265d620SPaolo Bonzini         return bs->drv->bdrv_co_discard(bs, sector_num, nb_sectors);
36874265d620SPaolo Bonzini     } else if (bs->drv->bdrv_aio_discard) {
36884265d620SPaolo Bonzini         BlockDriverAIOCB *acb;
36894265d620SPaolo Bonzini         CoroutineIOCompletion co = {
36904265d620SPaolo Bonzini             .coroutine = qemu_coroutine_self(),
36914265d620SPaolo Bonzini         };
36924265d620SPaolo Bonzini 
36934265d620SPaolo Bonzini         acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
36944265d620SPaolo Bonzini                                         bdrv_co_io_em_complete, &co);
36954265d620SPaolo Bonzini         if (acb == NULL) {
36964265d620SPaolo Bonzini             return -EIO;
36974265d620SPaolo Bonzini         } else {
36984265d620SPaolo Bonzini             qemu_coroutine_yield();
36994265d620SPaolo Bonzini             return co.ret;
37004265d620SPaolo Bonzini         }
37014265d620SPaolo Bonzini     } else {
37024265d620SPaolo Bonzini         return 0;
37034265d620SPaolo Bonzini     }
37044265d620SPaolo Bonzini }
37054265d620SPaolo Bonzini 
37064265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
37074265d620SPaolo Bonzini {
37084265d620SPaolo Bonzini     Coroutine *co;
37094265d620SPaolo Bonzini     RwCo rwco = {
37104265d620SPaolo Bonzini         .bs = bs,
37114265d620SPaolo Bonzini         .sector_num = sector_num,
37124265d620SPaolo Bonzini         .nb_sectors = nb_sectors,
37134265d620SPaolo Bonzini         .ret = NOT_DONE,
37144265d620SPaolo Bonzini     };
37154265d620SPaolo Bonzini 
37164265d620SPaolo Bonzini     if (qemu_in_coroutine()) {
37174265d620SPaolo Bonzini         /* Fast-path if already in coroutine context */
37184265d620SPaolo Bonzini         bdrv_discard_co_entry(&rwco);
37194265d620SPaolo Bonzini     } else {
37204265d620SPaolo Bonzini         co = qemu_coroutine_create(bdrv_discard_co_entry);
37214265d620SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
37224265d620SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
37234265d620SPaolo Bonzini             qemu_aio_wait();
37244265d620SPaolo Bonzini         }
37254265d620SPaolo Bonzini     }
37264265d620SPaolo Bonzini 
37274265d620SPaolo Bonzini     return rwco.ret;
37284265d620SPaolo Bonzini }
37294265d620SPaolo Bonzini 
3730f9f05dc5SKevin Wolf /**************************************************************/
373119cb3738Sbellard /* removable device support */
373219cb3738Sbellard 
373319cb3738Sbellard /**
373419cb3738Sbellard  * Return TRUE if the media is present
373519cb3738Sbellard  */
373619cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
373719cb3738Sbellard {
373819cb3738Sbellard     BlockDriver *drv = bs->drv;
3739a1aff5bfSMarkus Armbruster 
374019cb3738Sbellard     if (!drv)
374119cb3738Sbellard         return 0;
374219cb3738Sbellard     if (!drv->bdrv_is_inserted)
3743a1aff5bfSMarkus Armbruster         return 1;
3744a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
374519cb3738Sbellard }
374619cb3738Sbellard 
374719cb3738Sbellard /**
37488e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
37498e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
375019cb3738Sbellard  */
375119cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
375219cb3738Sbellard {
375319cb3738Sbellard     BlockDriver *drv = bs->drv;
375419cb3738Sbellard 
37558e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
37568e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
37578e49ca46SMarkus Armbruster     }
37588e49ca46SMarkus Armbruster     return -ENOTSUP;
375919cb3738Sbellard }
376019cb3738Sbellard 
376119cb3738Sbellard /**
376219cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
376319cb3738Sbellard  */
3764f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
376519cb3738Sbellard {
376619cb3738Sbellard     BlockDriver *drv = bs->drv;
376719cb3738Sbellard 
3768822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
3769822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
377019cb3738Sbellard     }
37716f382ed2SLuiz Capitulino 
37726f382ed2SLuiz Capitulino     if (bs->device_name[0] != '\0') {
37736f382ed2SLuiz Capitulino         bdrv_emit_qmp_eject_event(bs, eject_flag);
37746f382ed2SLuiz Capitulino     }
377519cb3738Sbellard }
377619cb3738Sbellard 
377719cb3738Sbellard /**
377819cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
377919cb3738Sbellard  * to eject it manually).
378019cb3738Sbellard  */
3781025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
378219cb3738Sbellard {
378319cb3738Sbellard     BlockDriver *drv = bs->drv;
378419cb3738Sbellard 
3785025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
3786b8c6d095SStefan Hajnoczi 
3787025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
3788025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
378919cb3738Sbellard     }
379019cb3738Sbellard }
3791985a03b0Sths 
3792985a03b0Sths /* needed for generic scsi interface */
3793985a03b0Sths 
3794985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3795985a03b0Sths {
3796985a03b0Sths     BlockDriver *drv = bs->drv;
3797985a03b0Sths 
3798985a03b0Sths     if (drv && drv->bdrv_ioctl)
3799985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
3800985a03b0Sths     return -ENOTSUP;
3801985a03b0Sths }
38027d780669Saliguori 
3803221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
3804221f715dSaliguori         unsigned long int req, void *buf,
38057d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
38067d780669Saliguori {
3807221f715dSaliguori     BlockDriver *drv = bs->drv;
38087d780669Saliguori 
3809221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
3810221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
3811221f715dSaliguori     return NULL;
38127d780669Saliguori }
3813e268ca52Saliguori 
38147b6f9300SMarkus Armbruster void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
38157b6f9300SMarkus Armbruster {
38167b6f9300SMarkus Armbruster     bs->buffer_alignment = align;
38177b6f9300SMarkus Armbruster }
38187cd1e32aSlirans@il.ibm.com 
3819e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
3820e268ca52Saliguori {
3821e268ca52Saliguori     return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
3822e268ca52Saliguori }
38237cd1e32aSlirans@il.ibm.com 
38247cd1e32aSlirans@il.ibm.com void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
38257cd1e32aSlirans@il.ibm.com {
38267cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
3827a55eb92cSJan Kiszka 
3828aaa0eb75SLiran Schour     bs->dirty_count = 0;
38297cd1e32aSlirans@il.ibm.com     if (enable) {
3830c6d22830SJan Kiszka         if (!bs->dirty_bitmap) {
3831c6d22830SJan Kiszka             bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
3832c6d22830SJan Kiszka                     BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
3833c6d22830SJan Kiszka             bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
38347cd1e32aSlirans@il.ibm.com 
38357267c094SAnthony Liguori             bs->dirty_bitmap = g_malloc0(bitmap_size);
38367cd1e32aSlirans@il.ibm.com         }
38377cd1e32aSlirans@il.ibm.com     } else {
3838c6d22830SJan Kiszka         if (bs->dirty_bitmap) {
38397267c094SAnthony Liguori             g_free(bs->dirty_bitmap);
3840c6d22830SJan Kiszka             bs->dirty_bitmap = NULL;
38417cd1e32aSlirans@il.ibm.com         }
38427cd1e32aSlirans@il.ibm.com     }
38437cd1e32aSlirans@il.ibm.com }
38447cd1e32aSlirans@il.ibm.com 
38457cd1e32aSlirans@il.ibm.com int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
38467cd1e32aSlirans@il.ibm.com {
38476ea44308SJan Kiszka     int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
38487cd1e32aSlirans@il.ibm.com 
3849c6d22830SJan Kiszka     if (bs->dirty_bitmap &&
3850c6d22830SJan Kiszka         (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
38516d59fec1SMarcelo Tosatti         return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
38526d59fec1SMarcelo Tosatti             (1UL << (chunk % (sizeof(unsigned long) * 8))));
38537cd1e32aSlirans@il.ibm.com     } else {
38547cd1e32aSlirans@il.ibm.com         return 0;
38557cd1e32aSlirans@il.ibm.com     }
38567cd1e32aSlirans@il.ibm.com }
38577cd1e32aSlirans@il.ibm.com 
38587cd1e32aSlirans@il.ibm.com void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
38597cd1e32aSlirans@il.ibm.com                       int nr_sectors)
38607cd1e32aSlirans@il.ibm.com {
38617cd1e32aSlirans@il.ibm.com     set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
38627cd1e32aSlirans@il.ibm.com }
3863aaa0eb75SLiran Schour 
3864aaa0eb75SLiran Schour int64_t bdrv_get_dirty_count(BlockDriverState *bs)
3865aaa0eb75SLiran Schour {
3866aaa0eb75SLiran Schour     return bs->dirty_count;
3867aaa0eb75SLiran Schour }
3868f88e1a42SJes Sorensen 
3869db593f25SMarcelo Tosatti void bdrv_set_in_use(BlockDriverState *bs, int in_use)
3870db593f25SMarcelo Tosatti {
3871db593f25SMarcelo Tosatti     assert(bs->in_use != in_use);
3872db593f25SMarcelo Tosatti     bs->in_use = in_use;
3873db593f25SMarcelo Tosatti }
3874db593f25SMarcelo Tosatti 
3875db593f25SMarcelo Tosatti int bdrv_in_use(BlockDriverState *bs)
3876db593f25SMarcelo Tosatti {
3877db593f25SMarcelo Tosatti     return bs->in_use;
3878db593f25SMarcelo Tosatti }
3879db593f25SMarcelo Tosatti 
388028a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
388128a7282aSLuiz Capitulino {
3882d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
388358e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
388428a7282aSLuiz Capitulino }
388528a7282aSLuiz Capitulino 
388628a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
388728a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
388828a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
388928a7282aSLuiz Capitulino {
3890d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
389128a7282aSLuiz Capitulino            (bs->on_write_error == BLOCK_ERR_STOP_ENOSPC ||
389228a7282aSLuiz Capitulino             bs->on_write_error == BLOCK_ERR_STOP_ANY    ||
389328a7282aSLuiz Capitulino             bs->on_read_error == BLOCK_ERR_STOP_ANY));
389428a7282aSLuiz Capitulino }
389528a7282aSLuiz Capitulino 
389628a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
389728a7282aSLuiz Capitulino {
3898d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
389928a7282aSLuiz Capitulino }
390028a7282aSLuiz Capitulino 
390128a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
390228a7282aSLuiz Capitulino {
390328a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
390458e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
390528a7282aSLuiz Capitulino     }
390628a7282aSLuiz Capitulino }
390728a7282aSLuiz Capitulino 
390828a7282aSLuiz Capitulino /* XXX: Today this is set by device models because it makes the implementation
390928a7282aSLuiz Capitulino    quite simple. However, the block layer knows about the error, so it's
391028a7282aSLuiz Capitulino    possible to implement this without device models being involved */
391128a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
391228a7282aSLuiz Capitulino {
391358e21ef5SLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs) &&
391458e21ef5SLuiz Capitulino         bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
391528a7282aSLuiz Capitulino         assert(error >= 0);
391658e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
391758e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
391828a7282aSLuiz Capitulino     }
391928a7282aSLuiz Capitulino }
392028a7282aSLuiz Capitulino 
3921a597e79cSChristoph Hellwig void
3922a597e79cSChristoph Hellwig bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
3923a597e79cSChristoph Hellwig         enum BlockAcctType type)
3924a597e79cSChristoph Hellwig {
3925a597e79cSChristoph Hellwig     assert(type < BDRV_MAX_IOTYPE);
3926a597e79cSChristoph Hellwig 
3927a597e79cSChristoph Hellwig     cookie->bytes = bytes;
3928c488c7f6SChristoph Hellwig     cookie->start_time_ns = get_clock();
3929a597e79cSChristoph Hellwig     cookie->type = type;
3930a597e79cSChristoph Hellwig }
3931a597e79cSChristoph Hellwig 
3932a597e79cSChristoph Hellwig void
3933a597e79cSChristoph Hellwig bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
3934a597e79cSChristoph Hellwig {
3935a597e79cSChristoph Hellwig     assert(cookie->type < BDRV_MAX_IOTYPE);
3936a597e79cSChristoph Hellwig 
3937a597e79cSChristoph Hellwig     bs->nr_bytes[cookie->type] += cookie->bytes;
3938a597e79cSChristoph Hellwig     bs->nr_ops[cookie->type]++;
3939c488c7f6SChristoph Hellwig     bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
3940a597e79cSChristoph Hellwig }
3941a597e79cSChristoph Hellwig 
3942f88e1a42SJes Sorensen int bdrv_img_create(const char *filename, const char *fmt,
3943f88e1a42SJes Sorensen                     const char *base_filename, const char *base_fmt,
3944f88e1a42SJes Sorensen                     char *options, uint64_t img_size, int flags)
3945f88e1a42SJes Sorensen {
3946f88e1a42SJes Sorensen     QEMUOptionParameter *param = NULL, *create_options = NULL;
3947d220894eSKevin Wolf     QEMUOptionParameter *backing_fmt, *backing_file, *size;
3948f88e1a42SJes Sorensen     BlockDriverState *bs = NULL;
3949f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
395096df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
3951f88e1a42SJes Sorensen     int ret = 0;
3952f88e1a42SJes Sorensen 
3953f88e1a42SJes Sorensen     /* Find driver and parse its options */
3954f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
3955f88e1a42SJes Sorensen     if (!drv) {
3956f88e1a42SJes Sorensen         error_report("Unknown file format '%s'", fmt);
39574f70f249SJes Sorensen         ret = -EINVAL;
3958f88e1a42SJes Sorensen         goto out;
3959f88e1a42SJes Sorensen     }
3960f88e1a42SJes Sorensen 
3961f88e1a42SJes Sorensen     proto_drv = bdrv_find_protocol(filename);
3962f88e1a42SJes Sorensen     if (!proto_drv) {
3963f88e1a42SJes Sorensen         error_report("Unknown protocol '%s'", filename);
39644f70f249SJes Sorensen         ret = -EINVAL;
3965f88e1a42SJes Sorensen         goto out;
3966f88e1a42SJes Sorensen     }
3967f88e1a42SJes Sorensen 
3968f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
3969f88e1a42SJes Sorensen                                               drv->create_options);
3970f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
3971f88e1a42SJes Sorensen                                               proto_drv->create_options);
3972f88e1a42SJes Sorensen 
3973f88e1a42SJes Sorensen     /* Create parameter list with default values */
3974f88e1a42SJes Sorensen     param = parse_option_parameters("", create_options, param);
3975f88e1a42SJes Sorensen 
3976f88e1a42SJes Sorensen     set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
3977f88e1a42SJes Sorensen 
3978f88e1a42SJes Sorensen     /* Parse -o options */
3979f88e1a42SJes Sorensen     if (options) {
3980f88e1a42SJes Sorensen         param = parse_option_parameters(options, create_options, param);
3981f88e1a42SJes Sorensen         if (param == NULL) {
3982f88e1a42SJes Sorensen             error_report("Invalid options for file format '%s'.", fmt);
39834f70f249SJes Sorensen             ret = -EINVAL;
3984f88e1a42SJes Sorensen             goto out;
3985f88e1a42SJes Sorensen         }
3986f88e1a42SJes Sorensen     }
3987f88e1a42SJes Sorensen 
3988f88e1a42SJes Sorensen     if (base_filename) {
3989f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
3990f88e1a42SJes Sorensen                                  base_filename)) {
3991f88e1a42SJes Sorensen             error_report("Backing file not supported for file format '%s'",
3992f88e1a42SJes Sorensen                          fmt);
39934f70f249SJes Sorensen             ret = -EINVAL;
3994f88e1a42SJes Sorensen             goto out;
3995f88e1a42SJes Sorensen         }
3996f88e1a42SJes Sorensen     }
3997f88e1a42SJes Sorensen 
3998f88e1a42SJes Sorensen     if (base_fmt) {
3999f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
4000f88e1a42SJes Sorensen             error_report("Backing file format not supported for file "
4001f88e1a42SJes Sorensen                          "format '%s'", fmt);
40024f70f249SJes Sorensen             ret = -EINVAL;
4003f88e1a42SJes Sorensen             goto out;
4004f88e1a42SJes Sorensen         }
4005f88e1a42SJes Sorensen     }
4006f88e1a42SJes Sorensen 
4007792da93aSJes Sorensen     backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
4008792da93aSJes Sorensen     if (backing_file && backing_file->value.s) {
4009792da93aSJes Sorensen         if (!strcmp(filename, backing_file->value.s)) {
4010792da93aSJes Sorensen             error_report("Error: Trying to create an image with the "
4011792da93aSJes Sorensen                          "same filename as the backing file");
40124f70f249SJes Sorensen             ret = -EINVAL;
4013792da93aSJes Sorensen             goto out;
4014792da93aSJes Sorensen         }
4015792da93aSJes Sorensen     }
4016792da93aSJes Sorensen 
4017f88e1a42SJes Sorensen     backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
4018f88e1a42SJes Sorensen     if (backing_fmt && backing_fmt->value.s) {
401996df67d1SStefan Hajnoczi         backing_drv = bdrv_find_format(backing_fmt->value.s);
402096df67d1SStefan Hajnoczi         if (!backing_drv) {
4021f88e1a42SJes Sorensen             error_report("Unknown backing file format '%s'",
4022f88e1a42SJes Sorensen                          backing_fmt->value.s);
40234f70f249SJes Sorensen             ret = -EINVAL;
4024f88e1a42SJes Sorensen             goto out;
4025f88e1a42SJes Sorensen         }
4026f88e1a42SJes Sorensen     }
4027f88e1a42SJes Sorensen 
4028f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
4029f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
4030d220894eSKevin Wolf     size = get_option_parameter(param, BLOCK_OPT_SIZE);
4031d220894eSKevin Wolf     if (size && size->value.n == -1) {
4032f88e1a42SJes Sorensen         if (backing_file && backing_file->value.s) {
4033f88e1a42SJes Sorensen             uint64_t size;
4034f88e1a42SJes Sorensen             char buf[32];
4035f88e1a42SJes Sorensen 
4036f88e1a42SJes Sorensen             bs = bdrv_new("");
4037f88e1a42SJes Sorensen 
403896df67d1SStefan Hajnoczi             ret = bdrv_open(bs, backing_file->value.s, flags, backing_drv);
4039f88e1a42SJes Sorensen             if (ret < 0) {
404096df67d1SStefan Hajnoczi                 error_report("Could not open '%s'", backing_file->value.s);
4041f88e1a42SJes Sorensen                 goto out;
4042f88e1a42SJes Sorensen             }
4043f88e1a42SJes Sorensen             bdrv_get_geometry(bs, &size);
4044f88e1a42SJes Sorensen             size *= 512;
4045f88e1a42SJes Sorensen 
4046f88e1a42SJes Sorensen             snprintf(buf, sizeof(buf), "%" PRId64, size);
4047f88e1a42SJes Sorensen             set_option_parameter(param, BLOCK_OPT_SIZE, buf);
4048f88e1a42SJes Sorensen         } else {
4049f88e1a42SJes Sorensen             error_report("Image creation needs a size parameter");
40504f70f249SJes Sorensen             ret = -EINVAL;
4051f88e1a42SJes Sorensen             goto out;
4052f88e1a42SJes Sorensen         }
4053f88e1a42SJes Sorensen     }
4054f88e1a42SJes Sorensen 
4055f88e1a42SJes Sorensen     printf("Formatting '%s', fmt=%s ", filename, fmt);
4056f88e1a42SJes Sorensen     print_option_parameters(param);
4057f88e1a42SJes Sorensen     puts("");
4058f88e1a42SJes Sorensen 
4059f88e1a42SJes Sorensen     ret = bdrv_create(drv, filename, param);
4060f88e1a42SJes Sorensen 
4061f88e1a42SJes Sorensen     if (ret < 0) {
4062f88e1a42SJes Sorensen         if (ret == -ENOTSUP) {
4063f88e1a42SJes Sorensen             error_report("Formatting or formatting option not supported for "
4064f88e1a42SJes Sorensen                          "file format '%s'", fmt);
4065f88e1a42SJes Sorensen         } else if (ret == -EFBIG) {
4066f88e1a42SJes Sorensen             error_report("The image size is too large for file format '%s'",
4067f88e1a42SJes Sorensen                          fmt);
4068f88e1a42SJes Sorensen         } else {
4069f88e1a42SJes Sorensen             error_report("%s: error while creating %s: %s", filename, fmt,
4070f88e1a42SJes Sorensen                          strerror(-ret));
4071f88e1a42SJes Sorensen         }
4072f88e1a42SJes Sorensen     }
4073f88e1a42SJes Sorensen 
4074f88e1a42SJes Sorensen out:
4075f88e1a42SJes Sorensen     free_option_parameters(create_options);
4076f88e1a42SJes Sorensen     free_option_parameters(param);
4077f88e1a42SJes Sorensen 
4078f88e1a42SJes Sorensen     if (bs) {
4079f88e1a42SJes Sorensen         bdrv_delete(bs);
4080f88e1a42SJes Sorensen     }
40814f70f249SJes Sorensen 
40824f70f249SJes Sorensen     return ret;
4083f88e1a42SJes Sorensen }
4084eeec61f2SStefan Hajnoczi 
4085eeec61f2SStefan Hajnoczi void *block_job_create(const BlockJobType *job_type, BlockDriverState *bs,
4086*fd7f8c65SStefan Hajnoczi                        BlockDriverCompletionFunc *cb, void *opaque,
4087*fd7f8c65SStefan Hajnoczi                        Error **errp)
4088eeec61f2SStefan Hajnoczi {
4089eeec61f2SStefan Hajnoczi     BlockJob *job;
4090eeec61f2SStefan Hajnoczi 
4091eeec61f2SStefan Hajnoczi     if (bs->job || bdrv_in_use(bs)) {
4092*fd7f8c65SStefan Hajnoczi         error_set(errp, QERR_DEVICE_IN_USE, bdrv_get_device_name(bs));
4093eeec61f2SStefan Hajnoczi         return NULL;
4094eeec61f2SStefan Hajnoczi     }
4095eeec61f2SStefan Hajnoczi     bdrv_set_in_use(bs, 1);
4096eeec61f2SStefan Hajnoczi 
4097eeec61f2SStefan Hajnoczi     job = g_malloc0(job_type->instance_size);
4098eeec61f2SStefan Hajnoczi     job->job_type      = job_type;
4099eeec61f2SStefan Hajnoczi     job->bs            = bs;
4100eeec61f2SStefan Hajnoczi     job->cb            = cb;
4101eeec61f2SStefan Hajnoczi     job->opaque        = opaque;
4102eeec61f2SStefan Hajnoczi     bs->job = job;
4103eeec61f2SStefan Hajnoczi     return job;
4104eeec61f2SStefan Hajnoczi }
4105eeec61f2SStefan Hajnoczi 
4106eeec61f2SStefan Hajnoczi void block_job_complete(BlockJob *job, int ret)
4107eeec61f2SStefan Hajnoczi {
4108eeec61f2SStefan Hajnoczi     BlockDriverState *bs = job->bs;
4109eeec61f2SStefan Hajnoczi 
4110eeec61f2SStefan Hajnoczi     assert(bs->job == job);
4111eeec61f2SStefan Hajnoczi     job->cb(job->opaque, ret);
4112eeec61f2SStefan Hajnoczi     bs->job = NULL;
4113eeec61f2SStefan Hajnoczi     g_free(job);
4114eeec61f2SStefan Hajnoczi     bdrv_set_in_use(bs, 0);
4115eeec61f2SStefan Hajnoczi }
4116eeec61f2SStefan Hajnoczi 
4117eeec61f2SStefan Hajnoczi int block_job_set_speed(BlockJob *job, int64_t value)
4118eeec61f2SStefan Hajnoczi {
41199f25ecccSPaolo Bonzini     int rc;
41209f25ecccSPaolo Bonzini 
4121eeec61f2SStefan Hajnoczi     if (!job->job_type->set_speed) {
4122eeec61f2SStefan Hajnoczi         return -ENOTSUP;
4123eeec61f2SStefan Hajnoczi     }
41249f25ecccSPaolo Bonzini     rc = job->job_type->set_speed(job, value);
41259f25ecccSPaolo Bonzini     if (rc == 0) {
41269f25ecccSPaolo Bonzini         job->speed = value;
41279f25ecccSPaolo Bonzini     }
41289f25ecccSPaolo Bonzini     return rc;
4129eeec61f2SStefan Hajnoczi }
4130eeec61f2SStefan Hajnoczi 
4131eeec61f2SStefan Hajnoczi void block_job_cancel(BlockJob *job)
4132eeec61f2SStefan Hajnoczi {
4133eeec61f2SStefan Hajnoczi     job->cancelled = true;
4134eeec61f2SStefan Hajnoczi }
4135eeec61f2SStefan Hajnoczi 
4136eeec61f2SStefan Hajnoczi bool block_job_is_cancelled(BlockJob *job)
4137eeec61f2SStefan Hajnoczi {
4138eeec61f2SStefan Hajnoczi     return job->cancelled;
4139eeec61f2SStefan Hajnoczi }
41403e914655SPaolo Bonzini 
41413e914655SPaolo Bonzini void block_job_cancel_sync(BlockJob *job)
41423e914655SPaolo Bonzini {
41433e914655SPaolo Bonzini     BlockDriverState *bs = job->bs;
41443e914655SPaolo Bonzini 
41453e914655SPaolo Bonzini     assert(bs->job == job);
41463e914655SPaolo Bonzini     block_job_cancel(job);
41473e914655SPaolo Bonzini     while (bs->job != NULL && bs->job->busy) {
41483e914655SPaolo Bonzini         qemu_aio_wait();
41493e914655SPaolo Bonzini     }
41503e914655SPaolo Bonzini }
4151