xref: /openbmc/qemu/block.c (revision 893a8f6220368a9ebff9a74bd48359928545cf6a)
1fc01f7e7Sbellard /*
2fc01f7e7Sbellard  * QEMU System Emulator block driver
3fc01f7e7Sbellard  *
4fc01f7e7Sbellard  * Copyright (c) 2003 Fabrice Bellard
5fc01f7e7Sbellard  *
6fc01f7e7Sbellard  * Permission is hereby granted, free of charge, to any person obtaining a copy
7fc01f7e7Sbellard  * of this software and associated documentation files (the "Software"), to deal
8fc01f7e7Sbellard  * in the Software without restriction, including without limitation the rights
9fc01f7e7Sbellard  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10fc01f7e7Sbellard  * copies of the Software, and to permit persons to whom the Software is
11fc01f7e7Sbellard  * furnished to do so, subject to the following conditions:
12fc01f7e7Sbellard  *
13fc01f7e7Sbellard  * The above copyright notice and this permission notice shall be included in
14fc01f7e7Sbellard  * all copies or substantial portions of the Software.
15fc01f7e7Sbellard  *
16fc01f7e7Sbellard  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17fc01f7e7Sbellard  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18fc01f7e7Sbellard  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19fc01f7e7Sbellard  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20fc01f7e7Sbellard  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21fc01f7e7Sbellard  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22fc01f7e7Sbellard  * THE SOFTWARE.
23fc01f7e7Sbellard  */
243990d09aSblueswir1 #include "config-host.h"
25faf07963Spbrook #include "qemu-common.h"
266d519a5fSStefan Hajnoczi #include "trace.h"
2783c9089eSPaolo Bonzini #include "monitor/monitor.h"
28737e150eSPaolo Bonzini #include "block/block_int.h"
29737e150eSPaolo Bonzini #include "block/blockjob.h"
301de7afc9SPaolo Bonzini #include "qemu/module.h"
317b1b5d19SPaolo Bonzini #include "qapi/qmp/qjson.h"
329c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
331de7afc9SPaolo Bonzini #include "qemu/notify.h"
34737e150eSPaolo Bonzini #include "block/coroutine.h"
35b2023818SLuiz Capitulino #include "qmp-commands.h"
361de7afc9SPaolo Bonzini #include "qemu/timer.h"
37fc01f7e7Sbellard 
3871e72a19SJuan Quintela #ifdef CONFIG_BSD
397674e7bfSbellard #include <sys/types.h>
407674e7bfSbellard #include <sys/stat.h>
417674e7bfSbellard #include <sys/ioctl.h>
4272cf2d4fSBlue Swirl #include <sys/queue.h>
43c5e97233Sblueswir1 #ifndef __DragonFly__
447674e7bfSbellard #include <sys/disk.h>
457674e7bfSbellard #endif
46c5e97233Sblueswir1 #endif
477674e7bfSbellard 
4849dc768dSaliguori #ifdef _WIN32
4949dc768dSaliguori #include <windows.h>
5049dc768dSaliguori #endif
5149dc768dSaliguori 
521c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
531c9805a3SStefan Hajnoczi 
54470c0504SStefan Hajnoczi typedef enum {
55470c0504SStefan Hajnoczi     BDRV_REQ_COPY_ON_READ = 0x1,
56f08f2ddaSStefan Hajnoczi     BDRV_REQ_ZERO_WRITE   = 0x2,
57470c0504SStefan Hajnoczi } BdrvRequestFlags;
58470c0504SStefan Hajnoczi 
597d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
60f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
61f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
62c87c0672Saliguori         BlockDriverCompletionFunc *cb, void *opaque);
63f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
64f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
65ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque);
66f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
67f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
68f9f05dc5SKevin Wolf                                          QEMUIOVector *iov);
69f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
70f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
71f9f05dc5SKevin Wolf                                          QEMUIOVector *iov);
72c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
73470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
74470c0504SStefan Hajnoczi     BdrvRequestFlags flags);
751c9805a3SStefan Hajnoczi static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
76f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
77f08f2ddaSStefan Hajnoczi     BdrvRequestFlags flags);
78b2a61371SStefan Hajnoczi static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
79b2a61371SStefan Hajnoczi                                                int64_t sector_num,
80b2a61371SStefan Hajnoczi                                                QEMUIOVector *qiov,
81b2a61371SStefan Hajnoczi                                                int nb_sectors,
82b2a61371SStefan Hajnoczi                                                BlockDriverCompletionFunc *cb,
83b2a61371SStefan Hajnoczi                                                void *opaque,
848c5873d6SStefan Hajnoczi                                                bool is_write);
85b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque);
86621f0589SKevin Wolf static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
87621f0589SKevin Wolf     int64_t sector_num, int nb_sectors);
88ec530c81Sbellard 
8998f90dbaSZhi Yong Wu static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
9098f90dbaSZhi Yong Wu         bool is_write, double elapsed_time, uint64_t *wait);
9198f90dbaSZhi Yong Wu static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
9298f90dbaSZhi Yong Wu         double elapsed_time, uint64_t *wait);
9398f90dbaSZhi Yong Wu static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
9498f90dbaSZhi Yong Wu         bool is_write, int64_t *wait);
9598f90dbaSZhi Yong Wu 
961b7bdbc1SStefan Hajnoczi static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
971b7bdbc1SStefan Hajnoczi     QTAILQ_HEAD_INITIALIZER(bdrv_states);
987ee930d0Sblueswir1 
998a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
1008a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
101ea2384d3Sbellard 
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 
130b681a1c7SBenoît Canet     do {} while (qemu_co_enter_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 }
14198f90dbaSZhi Yong Wu 
1420563e191SZhi Yong Wu static void bdrv_block_timer(void *opaque)
1430563e191SZhi Yong Wu {
1440563e191SZhi Yong Wu     BlockDriverState *bs = opaque;
1450563e191SZhi Yong Wu 
146b681a1c7SBenoît Canet     qemu_co_enter_next(&bs->throttled_reqs);
1470563e191SZhi Yong Wu }
1480563e191SZhi Yong Wu 
1490563e191SZhi Yong Wu void bdrv_io_limits_enable(BlockDriverState *bs)
1500563e191SZhi Yong Wu {
1510563e191SZhi Yong Wu     bs->block_timer = qemu_new_timer_ns(vm_clock, bdrv_block_timer, bs);
1520563e191SZhi Yong Wu     bs->io_limits_enabled = true;
1530563e191SZhi Yong Wu }
1540563e191SZhi Yong Wu 
1550563e191SZhi Yong Wu bool bdrv_io_limits_enabled(BlockDriverState *bs)
1560563e191SZhi Yong Wu {
1570563e191SZhi Yong Wu     BlockIOLimit *io_limits = &bs->io_limits;
1580563e191SZhi Yong Wu     return io_limits->bps[BLOCK_IO_LIMIT_READ]
1590563e191SZhi Yong Wu          || io_limits->bps[BLOCK_IO_LIMIT_WRITE]
1600563e191SZhi Yong Wu          || io_limits->bps[BLOCK_IO_LIMIT_TOTAL]
1610563e191SZhi Yong Wu          || io_limits->iops[BLOCK_IO_LIMIT_READ]
1620563e191SZhi Yong Wu          || io_limits->iops[BLOCK_IO_LIMIT_WRITE]
1630563e191SZhi Yong Wu          || io_limits->iops[BLOCK_IO_LIMIT_TOTAL];
1640563e191SZhi Yong Wu }
1650563e191SZhi Yong Wu 
16698f90dbaSZhi Yong Wu static void bdrv_io_limits_intercept(BlockDriverState *bs,
16798f90dbaSZhi Yong Wu                                      bool is_write, int nb_sectors)
16898f90dbaSZhi Yong Wu {
16998f90dbaSZhi Yong Wu     int64_t wait_time = -1;
17098f90dbaSZhi Yong Wu 
17198f90dbaSZhi Yong Wu     if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
17298f90dbaSZhi Yong Wu         qemu_co_queue_wait(&bs->throttled_reqs);
17398f90dbaSZhi Yong Wu     }
17498f90dbaSZhi Yong Wu 
17598f90dbaSZhi Yong Wu     /* In fact, we hope to keep each request's timing, in FIFO mode. The next
17698f90dbaSZhi Yong Wu      * throttled requests will not be dequeued until the current request is
17798f90dbaSZhi Yong Wu      * allowed to be serviced. So if the current request still exceeds the
17898f90dbaSZhi Yong Wu      * limits, it will be inserted to the head. All requests followed it will
17998f90dbaSZhi Yong Wu      * be still in throttled_reqs queue.
18098f90dbaSZhi Yong Wu      */
18198f90dbaSZhi Yong Wu 
18298f90dbaSZhi Yong Wu     while (bdrv_exceed_io_limits(bs, nb_sectors, is_write, &wait_time)) {
18398f90dbaSZhi Yong Wu         qemu_mod_timer(bs->block_timer,
18498f90dbaSZhi Yong Wu                        wait_time + qemu_get_clock_ns(vm_clock));
18598f90dbaSZhi Yong Wu         qemu_co_queue_wait_insert_head(&bs->throttled_reqs);
18698f90dbaSZhi Yong Wu     }
18798f90dbaSZhi Yong Wu 
18898f90dbaSZhi Yong Wu     qemu_co_queue_next(&bs->throttled_reqs);
18998f90dbaSZhi Yong Wu }
19098f90dbaSZhi Yong Wu 
1919e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
1929e0b22f4SStefan Hajnoczi static int path_has_protocol(const char *path)
1939e0b22f4SStefan Hajnoczi {
194947995c0SPaolo Bonzini     const char *p;
195947995c0SPaolo Bonzini 
1969e0b22f4SStefan Hajnoczi #ifdef _WIN32
1979e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
1989e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
1999e0b22f4SStefan Hajnoczi         return 0;
2009e0b22f4SStefan Hajnoczi     }
201947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
202947995c0SPaolo Bonzini #else
203947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
2049e0b22f4SStefan Hajnoczi #endif
2059e0b22f4SStefan Hajnoczi 
206947995c0SPaolo Bonzini     return *p == ':';
2079e0b22f4SStefan Hajnoczi }
2089e0b22f4SStefan Hajnoczi 
20983f64091Sbellard int path_is_absolute(const char *path)
21083f64091Sbellard {
21121664424Sbellard #ifdef _WIN32
21221664424Sbellard     /* specific case for names like: "\\.\d:" */
213f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
21421664424Sbellard         return 1;
215f53f4da9SPaolo Bonzini     }
216f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
2173b9f94e1Sbellard #else
218f53f4da9SPaolo Bonzini     return (*path == '/');
2193b9f94e1Sbellard #endif
22083f64091Sbellard }
22183f64091Sbellard 
22283f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
22383f64091Sbellard    path to it by considering it is relative to base_path. URL are
22483f64091Sbellard    supported. */
22583f64091Sbellard void path_combine(char *dest, int dest_size,
22683f64091Sbellard                   const char *base_path,
22783f64091Sbellard                   const char *filename)
22883f64091Sbellard {
22983f64091Sbellard     const char *p, *p1;
23083f64091Sbellard     int len;
23183f64091Sbellard 
23283f64091Sbellard     if (dest_size <= 0)
23383f64091Sbellard         return;
23483f64091Sbellard     if (path_is_absolute(filename)) {
23583f64091Sbellard         pstrcpy(dest, dest_size, filename);
23683f64091Sbellard     } else {
23783f64091Sbellard         p = strchr(base_path, ':');
23883f64091Sbellard         if (p)
23983f64091Sbellard             p++;
24083f64091Sbellard         else
24183f64091Sbellard             p = base_path;
2423b9f94e1Sbellard         p1 = strrchr(base_path, '/');
2433b9f94e1Sbellard #ifdef _WIN32
2443b9f94e1Sbellard         {
2453b9f94e1Sbellard             const char *p2;
2463b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
2473b9f94e1Sbellard             if (!p1 || p2 > p1)
2483b9f94e1Sbellard                 p1 = p2;
2493b9f94e1Sbellard         }
2503b9f94e1Sbellard #endif
25183f64091Sbellard         if (p1)
25283f64091Sbellard             p1++;
25383f64091Sbellard         else
25483f64091Sbellard             p1 = base_path;
25583f64091Sbellard         if (p1 > p)
25683f64091Sbellard             p = p1;
25783f64091Sbellard         len = p - base_path;
25883f64091Sbellard         if (len > dest_size - 1)
25983f64091Sbellard             len = dest_size - 1;
26083f64091Sbellard         memcpy(dest, base_path, len);
26183f64091Sbellard         dest[len] = '\0';
26283f64091Sbellard         pstrcat(dest, dest_size, filename);
26383f64091Sbellard     }
26483f64091Sbellard }
26583f64091Sbellard 
266dc5a1371SPaolo Bonzini void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
267dc5a1371SPaolo Bonzini {
268dc5a1371SPaolo Bonzini     if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
269dc5a1371SPaolo Bonzini         pstrcpy(dest, sz, bs->backing_file);
270dc5a1371SPaolo Bonzini     } else {
271dc5a1371SPaolo Bonzini         path_combine(dest, sz, bs->filename, bs->backing_file);
272dc5a1371SPaolo Bonzini     }
273dc5a1371SPaolo Bonzini }
274dc5a1371SPaolo Bonzini 
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);
306d7d512f6SPaolo Bonzini     notifier_list_init(&bs->close_notifiers);
307d616b224SStefan Hajnoczi     notifier_with_return_list_init(&bs->before_write_notifiers);
30888266f5aSStefan Hajnoczi     qemu_co_queue_init(&bs->throttled_reqs);
309d7d512f6SPaolo Bonzini 
310b338082bSbellard     return bs;
311b338082bSbellard }
312b338082bSbellard 
313d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
314d7d512f6SPaolo Bonzini {
315d7d512f6SPaolo Bonzini     notifier_list_add(&bs->close_notifiers, notify);
316d7d512f6SPaolo Bonzini }
317d7d512f6SPaolo Bonzini 
318ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
319ea2384d3Sbellard {
320ea2384d3Sbellard     BlockDriver *drv1;
3218a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
3228a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
323ea2384d3Sbellard             return drv1;
324ea2384d3Sbellard         }
3258a22f02aSStefan Hajnoczi     }
326ea2384d3Sbellard     return NULL;
327ea2384d3Sbellard }
328ea2384d3Sbellard 
329b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
330eb852011SMarkus Armbruster {
331b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
332b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
333b64ec4e4SFam Zheng     };
334b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
335b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
336eb852011SMarkus Armbruster     };
337eb852011SMarkus Armbruster     const char **p;
338eb852011SMarkus Armbruster 
339b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
340eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
341b64ec4e4SFam Zheng     }
342eb852011SMarkus Armbruster 
343b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
344eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
345eb852011SMarkus Armbruster             return 1;
346eb852011SMarkus Armbruster         }
347eb852011SMarkus Armbruster     }
348b64ec4e4SFam Zheng     if (read_only) {
349b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
350b64ec4e4SFam Zheng             if (!strcmp(drv->format_name, *p)) {
351b64ec4e4SFam Zheng                 return 1;
352b64ec4e4SFam Zheng             }
353b64ec4e4SFam Zheng         }
354b64ec4e4SFam Zheng     }
355eb852011SMarkus Armbruster     return 0;
356eb852011SMarkus Armbruster }
357eb852011SMarkus Armbruster 
358b64ec4e4SFam Zheng BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
359b64ec4e4SFam Zheng                                           bool read_only)
360eb852011SMarkus Armbruster {
361eb852011SMarkus Armbruster     BlockDriver *drv = bdrv_find_format(format_name);
362b64ec4e4SFam Zheng     return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL;
363eb852011SMarkus Armbruster }
364eb852011SMarkus Armbruster 
3655b7e1542SZhi Yong Wu typedef struct CreateCo {
3665b7e1542SZhi Yong Wu     BlockDriver *drv;
3675b7e1542SZhi Yong Wu     char *filename;
3685b7e1542SZhi Yong Wu     QEMUOptionParameter *options;
3695b7e1542SZhi Yong Wu     int ret;
3705b7e1542SZhi Yong Wu } CreateCo;
3715b7e1542SZhi Yong Wu 
3725b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
3735b7e1542SZhi Yong Wu {
3745b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
3755b7e1542SZhi Yong Wu     assert(cco->drv);
3765b7e1542SZhi Yong Wu 
3775b7e1542SZhi Yong Wu     cco->ret = cco->drv->bdrv_create(cco->filename, cco->options);
3785b7e1542SZhi Yong Wu }
3795b7e1542SZhi Yong Wu 
3800e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
3810e7e1989SKevin Wolf     QEMUOptionParameter *options)
382ea2384d3Sbellard {
3835b7e1542SZhi Yong Wu     int ret;
3840e7e1989SKevin Wolf 
3855b7e1542SZhi Yong Wu     Coroutine *co;
3865b7e1542SZhi Yong Wu     CreateCo cco = {
3875b7e1542SZhi Yong Wu         .drv = drv,
3885b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
3895b7e1542SZhi Yong Wu         .options = options,
3905b7e1542SZhi Yong Wu         .ret = NOT_DONE,
3915b7e1542SZhi Yong Wu     };
3925b7e1542SZhi Yong Wu 
3935b7e1542SZhi Yong Wu     if (!drv->bdrv_create) {
39480168bffSLuiz Capitulino         ret = -ENOTSUP;
39580168bffSLuiz Capitulino         goto out;
3965b7e1542SZhi Yong Wu     }
3975b7e1542SZhi Yong Wu 
3985b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
3995b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
4005b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
4015b7e1542SZhi Yong Wu     } else {
4025b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
4035b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
4045b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
4055b7e1542SZhi Yong Wu             qemu_aio_wait();
4065b7e1542SZhi Yong Wu         }
4075b7e1542SZhi Yong Wu     }
4085b7e1542SZhi Yong Wu 
4095b7e1542SZhi Yong Wu     ret = cco.ret;
4105b7e1542SZhi Yong Wu 
41180168bffSLuiz Capitulino out:
41280168bffSLuiz Capitulino     g_free(cco.filename);
4135b7e1542SZhi Yong Wu     return ret;
414ea2384d3Sbellard }
415ea2384d3Sbellard 
41684a12e66SChristoph Hellwig int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
41784a12e66SChristoph Hellwig {
41884a12e66SChristoph Hellwig     BlockDriver *drv;
41984a12e66SChristoph Hellwig 
42098289620SKevin Wolf     drv = bdrv_find_protocol(filename, true);
42184a12e66SChristoph Hellwig     if (drv == NULL) {
42216905d71SStefan Hajnoczi         return -ENOENT;
42384a12e66SChristoph Hellwig     }
42484a12e66SChristoph Hellwig 
42584a12e66SChristoph Hellwig     return bdrv_create(drv, filename, options);
42684a12e66SChristoph Hellwig }
42784a12e66SChristoph Hellwig 
428eba25057SJim Meyering /*
429eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
430eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
431eba25057SJim Meyering  */
432eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
433eba25057SJim Meyering {
434d5249393Sbellard #ifdef _WIN32
4353b9f94e1Sbellard     char temp_dir[MAX_PATH];
436eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
437eba25057SJim Meyering        have length MAX_PATH or greater.  */
438eba25057SJim Meyering     assert(size >= MAX_PATH);
439eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
440eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
441eba25057SJim Meyering             ? 0 : -GetLastError());
442d5249393Sbellard #else
443ea2384d3Sbellard     int fd;
4447ccfb2ebSblueswir1     const char *tmpdir;
4450badc1eeSaurel32     tmpdir = getenv("TMPDIR");
4460badc1eeSaurel32     if (!tmpdir)
4470badc1eeSaurel32         tmpdir = "/tmp";
448eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
449eba25057SJim Meyering         return -EOVERFLOW;
450ea2384d3Sbellard     }
451eba25057SJim Meyering     fd = mkstemp(filename);
452fe235a06SDunrong Huang     if (fd < 0) {
453fe235a06SDunrong Huang         return -errno;
454fe235a06SDunrong Huang     }
455fe235a06SDunrong Huang     if (close(fd) != 0) {
456fe235a06SDunrong Huang         unlink(filename);
457eba25057SJim Meyering         return -errno;
458eba25057SJim Meyering     }
459eba25057SJim Meyering     return 0;
460d5249393Sbellard #endif
461eba25057SJim Meyering }
462ea2384d3Sbellard 
463f3a5d3f8SChristoph Hellwig /*
464f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
465f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
466f3a5d3f8SChristoph Hellwig  */
467f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
468f3a5d3f8SChristoph Hellwig {
469508c7cb3SChristoph Hellwig     int score_max = 0, score;
470508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
471f3a5d3f8SChristoph Hellwig 
4728a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
473508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
474508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
475508c7cb3SChristoph Hellwig             if (score > score_max) {
476508c7cb3SChristoph Hellwig                 score_max = score;
477508c7cb3SChristoph Hellwig                 drv = d;
478f3a5d3f8SChristoph Hellwig             }
479508c7cb3SChristoph Hellwig         }
480f3a5d3f8SChristoph Hellwig     }
481f3a5d3f8SChristoph Hellwig 
482508c7cb3SChristoph Hellwig     return drv;
483f3a5d3f8SChristoph Hellwig }
484f3a5d3f8SChristoph Hellwig 
48598289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
48698289620SKevin Wolf                                 bool allow_protocol_prefix)
48784a12e66SChristoph Hellwig {
48884a12e66SChristoph Hellwig     BlockDriver *drv1;
48984a12e66SChristoph Hellwig     char protocol[128];
49084a12e66SChristoph Hellwig     int len;
49184a12e66SChristoph Hellwig     const char *p;
49284a12e66SChristoph Hellwig 
49366f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
49466f82ceeSKevin Wolf 
49539508e7aSChristoph Hellwig     /*
49639508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
49739508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
49839508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
49939508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
50039508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
50139508e7aSChristoph Hellwig      */
50284a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
50339508e7aSChristoph Hellwig     if (drv1) {
50484a12e66SChristoph Hellwig         return drv1;
50584a12e66SChristoph Hellwig     }
50639508e7aSChristoph Hellwig 
50798289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
50839508e7aSChristoph Hellwig         return bdrv_find_format("file");
50939508e7aSChristoph Hellwig     }
51098289620SKevin Wolf 
5119e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
5129e0b22f4SStefan Hajnoczi     assert(p != NULL);
51384a12e66SChristoph Hellwig     len = p - filename;
51484a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
51584a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
51684a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
51784a12e66SChristoph Hellwig     protocol[len] = '\0';
51884a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
51984a12e66SChristoph Hellwig         if (drv1->protocol_name &&
52084a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
52184a12e66SChristoph Hellwig             return drv1;
52284a12e66SChristoph Hellwig         }
52384a12e66SChristoph Hellwig     }
52484a12e66SChristoph Hellwig     return NULL;
52584a12e66SChristoph Hellwig }
52684a12e66SChristoph Hellwig 
527f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
528f500a6d3SKevin Wolf                              BlockDriver **pdrv)
529ea2384d3Sbellard {
530f500a6d3SKevin Wolf     int score, score_max;
531ea2384d3Sbellard     BlockDriver *drv1, *drv;
53283f64091Sbellard     uint8_t buf[2048];
533f500a6d3SKevin Wolf     int ret = 0;
534f8ea0b00SNicholas Bellinger 
53508a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
5368e895599SPaolo Bonzini     if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
537c98ac35dSStefan Weil         drv = bdrv_find_format("raw");
538c98ac35dSStefan Weil         if (!drv) {
539c98ac35dSStefan Weil             ret = -ENOENT;
540c98ac35dSStefan Weil         }
541c98ac35dSStefan Weil         *pdrv = drv;
542c98ac35dSStefan Weil         return ret;
5431a396859SNicholas A. Bellinger     }
544f8ea0b00SNicholas Bellinger 
54583f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
546ea2384d3Sbellard     if (ret < 0) {
547c98ac35dSStefan Weil         *pdrv = NULL;
548c98ac35dSStefan Weil         return ret;
549ea2384d3Sbellard     }
550ea2384d3Sbellard 
551ea2384d3Sbellard     score_max = 0;
55284a12e66SChristoph Hellwig     drv = NULL;
5538a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
55483f64091Sbellard         if (drv1->bdrv_probe) {
555ea2384d3Sbellard             score = drv1->bdrv_probe(buf, ret, filename);
556ea2384d3Sbellard             if (score > score_max) {
557ea2384d3Sbellard                 score_max = score;
558ea2384d3Sbellard                 drv = drv1;
559ea2384d3Sbellard             }
560ea2384d3Sbellard         }
56183f64091Sbellard     }
562c98ac35dSStefan Weil     if (!drv) {
563c98ac35dSStefan Weil         ret = -ENOENT;
564c98ac35dSStefan Weil     }
565c98ac35dSStefan Weil     *pdrv = drv;
566c98ac35dSStefan Weil     return ret;
567ea2384d3Sbellard }
568ea2384d3Sbellard 
56951762288SStefan Hajnoczi /**
57051762288SStefan Hajnoczi  * Set the current 'total_sectors' value
57151762288SStefan Hajnoczi  */
57251762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
57351762288SStefan Hajnoczi {
57451762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
57551762288SStefan Hajnoczi 
576396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
577396759adSNicholas Bellinger     if (bs->sg)
578396759adSNicholas Bellinger         return 0;
579396759adSNicholas Bellinger 
58051762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
58151762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
58251762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
58351762288SStefan Hajnoczi         if (length < 0) {
58451762288SStefan Hajnoczi             return length;
58551762288SStefan Hajnoczi         }
58651762288SStefan Hajnoczi         hint = length >> BDRV_SECTOR_BITS;
58751762288SStefan Hajnoczi     }
58851762288SStefan Hajnoczi 
58951762288SStefan Hajnoczi     bs->total_sectors = hint;
59051762288SStefan Hajnoczi     return 0;
59151762288SStefan Hajnoczi }
59251762288SStefan Hajnoczi 
593c3993cdcSStefan Hajnoczi /**
5949e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
5959e8f1835SPaolo Bonzini  *
5969e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
5979e8f1835SPaolo Bonzini  */
5989e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
5999e8f1835SPaolo Bonzini {
6009e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
6019e8f1835SPaolo Bonzini 
6029e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
6039e8f1835SPaolo Bonzini         /* do nothing */
6049e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
6059e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
6069e8f1835SPaolo Bonzini     } else {
6079e8f1835SPaolo Bonzini         return -1;
6089e8f1835SPaolo Bonzini     }
6099e8f1835SPaolo Bonzini 
6109e8f1835SPaolo Bonzini     return 0;
6119e8f1835SPaolo Bonzini }
6129e8f1835SPaolo Bonzini 
6139e8f1835SPaolo Bonzini /**
614c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
615c3993cdcSStefan Hajnoczi  *
616c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
617c3993cdcSStefan Hajnoczi  */
618c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
619c3993cdcSStefan Hajnoczi {
620c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
621c3993cdcSStefan Hajnoczi 
622c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
623c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
62492196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
62592196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
626c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
627c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
628c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
629c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
630c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
631c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
632c3993cdcSStefan Hajnoczi         /* this is the default */
633c3993cdcSStefan Hajnoczi     } else {
634c3993cdcSStefan Hajnoczi         return -1;
635c3993cdcSStefan Hajnoczi     }
636c3993cdcSStefan Hajnoczi 
637c3993cdcSStefan Hajnoczi     return 0;
638c3993cdcSStefan Hajnoczi }
639c3993cdcSStefan Hajnoczi 
64053fec9d3SStefan Hajnoczi /**
64153fec9d3SStefan Hajnoczi  * The copy-on-read flag is actually a reference count so multiple users may
64253fec9d3SStefan Hajnoczi  * use the feature without worrying about clobbering its previous state.
64353fec9d3SStefan Hajnoczi  * Copy-on-read stays enabled until all users have called to disable it.
64453fec9d3SStefan Hajnoczi  */
64553fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs)
64653fec9d3SStefan Hajnoczi {
64753fec9d3SStefan Hajnoczi     bs->copy_on_read++;
64853fec9d3SStefan Hajnoczi }
64953fec9d3SStefan Hajnoczi 
65053fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs)
65153fec9d3SStefan Hajnoczi {
65253fec9d3SStefan Hajnoczi     assert(bs->copy_on_read > 0);
65353fec9d3SStefan Hajnoczi     bs->copy_on_read--;
65453fec9d3SStefan Hajnoczi }
65553fec9d3SStefan Hajnoczi 
6567b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
6577b272452SKevin Wolf {
6587b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
6597b272452SKevin Wolf 
6607b272452SKevin Wolf     /*
6617b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
6627b272452SKevin Wolf      * image.
6637b272452SKevin Wolf      */
6647b272452SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
6657b272452SKevin Wolf 
6667b272452SKevin Wolf     /*
6677b272452SKevin Wolf      * Snapshots should be writable.
6687b272452SKevin Wolf      */
6697b272452SKevin Wolf     if (bs->is_temporary) {
6707b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
6717b272452SKevin Wolf     }
6727b272452SKevin Wolf 
6737b272452SKevin Wolf     return open_flags;
6747b272452SKevin Wolf }
6757b272452SKevin Wolf 
676b6ce07aaSKevin Wolf /*
67757915332SKevin Wolf  * Common part for opening disk images and files
678b6ad491aSKevin Wolf  *
679b6ad491aSKevin Wolf  * Removes all processed options from *options.
68057915332SKevin Wolf  */
681f500a6d3SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
682035fccdfSKevin Wolf     QDict *options, int flags, BlockDriver *drv)
68357915332SKevin Wolf {
68457915332SKevin Wolf     int ret, open_flags;
685035fccdfSKevin Wolf     const char *filename;
68657915332SKevin Wolf 
68757915332SKevin Wolf     assert(drv != NULL);
6886405875cSPaolo Bonzini     assert(bs->file == NULL);
689707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
69057915332SKevin Wolf 
69145673671SKevin Wolf     if (file != NULL) {
69245673671SKevin Wolf         filename = file->filename;
69345673671SKevin Wolf     } else {
69445673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
69545673671SKevin Wolf     }
69645673671SKevin Wolf 
69745673671SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
69828dcee10SStefan Hajnoczi 
6995d186eb0SKevin Wolf     /* bdrv_open() with directly using a protocol as drv. This layer is already
7005d186eb0SKevin Wolf      * opened, so assign it to bs (while file becomes a closed BlockDriverState)
7015d186eb0SKevin Wolf      * and return immediately. */
7025d186eb0SKevin Wolf     if (file != NULL && drv->bdrv_file_open) {
7035d186eb0SKevin Wolf         bdrv_swap(file, bs);
7045d186eb0SKevin Wolf         return 0;
7055d186eb0SKevin Wolf     }
7065d186eb0SKevin Wolf 
70757915332SKevin Wolf     bs->open_flags = flags;
70857915332SKevin Wolf     bs->buffer_alignment = 512;
7090d51b4deSAsias He     bs->zero_beyond_eof = true;
710b64ec4e4SFam Zheng     open_flags = bdrv_open_flags(bs, flags);
711b64ec4e4SFam Zheng     bs->read_only = !(open_flags & BDRV_O_RDWR);
712b64ec4e4SFam Zheng 
713b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
714b64ec4e4SFam Zheng         return -ENOTSUP;
715b64ec4e4SFam Zheng     }
71657915332SKevin Wolf 
71753fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
718b64ec4e4SFam Zheng     if (!bs->read_only && (flags & BDRV_O_COPY_ON_READ)) {
71953fec9d3SStefan Hajnoczi         bdrv_enable_copy_on_read(bs);
72053fec9d3SStefan Hajnoczi     }
72153fec9d3SStefan Hajnoczi 
722c2ad1b0cSKevin Wolf     if (filename != NULL) {
72357915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
724c2ad1b0cSKevin Wolf     } else {
725c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
726c2ad1b0cSKevin Wolf     }
72757915332SKevin Wolf 
72857915332SKevin Wolf     bs->drv = drv;
7297267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
73057915332SKevin Wolf 
73103f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
732e7c63796SStefan Hajnoczi 
73366f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
73466f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
7355d186eb0SKevin Wolf         assert(file == NULL);
736c2ad1b0cSKevin Wolf         assert(drv->bdrv_parse_filename || filename != NULL);
73756d1b4d2SKevin Wolf         ret = drv->bdrv_file_open(bs, options, open_flags);
738f500a6d3SKevin Wolf     } else {
7392af5ef70SKevin Wolf         if (file == NULL) {
7402af5ef70SKevin Wolf             qerror_report(ERROR_CLASS_GENERIC_ERROR, "Can't use '%s' as a "
7412af5ef70SKevin Wolf                           "block driver for the protocol level",
7422af5ef70SKevin Wolf                           drv->format_name);
7432af5ef70SKevin Wolf             ret = -EINVAL;
7442af5ef70SKevin Wolf             goto free_and_fail;
7452af5ef70SKevin Wolf         }
746f500a6d3SKevin Wolf         assert(file != NULL);
747f500a6d3SKevin Wolf         bs->file = file;
748b6ad491aSKevin Wolf         ret = drv->bdrv_open(bs, options, open_flags);
74966f82ceeSKevin Wolf     }
75066f82ceeSKevin Wolf 
75157915332SKevin Wolf     if (ret < 0) {
75257915332SKevin Wolf         goto free_and_fail;
75357915332SKevin Wolf     }
75457915332SKevin Wolf 
75551762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
75651762288SStefan Hajnoczi     if (ret < 0) {
75751762288SStefan Hajnoczi         goto free_and_fail;
75857915332SKevin Wolf     }
75951762288SStefan Hajnoczi 
76057915332SKevin Wolf #ifndef _WIN32
76157915332SKevin Wolf     if (bs->is_temporary) {
762c2ad1b0cSKevin Wolf         assert(filename != NULL);
76357915332SKevin Wolf         unlink(filename);
76457915332SKevin Wolf     }
76557915332SKevin Wolf #endif
76657915332SKevin Wolf     return 0;
76757915332SKevin Wolf 
76857915332SKevin Wolf free_and_fail:
76966f82ceeSKevin Wolf     bs->file = NULL;
7707267c094SAnthony Liguori     g_free(bs->opaque);
77157915332SKevin Wolf     bs->opaque = NULL;
77257915332SKevin Wolf     bs->drv = NULL;
77357915332SKevin Wolf     return ret;
77457915332SKevin Wolf }
77557915332SKevin Wolf 
77657915332SKevin Wolf /*
777b6ce07aaSKevin Wolf  * Opens a file using a protocol (file, host_device, nbd, ...)
778787e4a85SKevin Wolf  *
779787e4a85SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
780787e4a85SKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
781787e4a85SKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
782787e4a85SKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_file_open.
783b6ce07aaSKevin Wolf  */
784787e4a85SKevin Wolf int bdrv_file_open(BlockDriverState **pbs, const char *filename,
785787e4a85SKevin Wolf                    QDict *options, int flags)
786b338082bSbellard {
78783f64091Sbellard     BlockDriverState *bs;
7886db95603SChristoph Hellwig     BlockDriver *drv;
789c2ad1b0cSKevin Wolf     const char *drvname;
79098289620SKevin Wolf     bool allow_protocol_prefix = false;
79183f64091Sbellard     int ret;
7923b0d4f61Sbellard 
793707ff828SKevin Wolf     /* NULL means an empty set of options */
794707ff828SKevin Wolf     if (options == NULL) {
795707ff828SKevin Wolf         options = qdict_new();
7963b0d4f61Sbellard     }
797707ff828SKevin Wolf 
798707ff828SKevin Wolf     bs = bdrv_new("");
799707ff828SKevin Wolf     bs->options = options;
800707ff828SKevin Wolf     options = qdict_clone_shallow(options);
801707ff828SKevin Wolf 
802035fccdfSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
803035fccdfSKevin Wolf     if (!filename) {
804035fccdfSKevin Wolf         filename = qdict_get_try_str(options, "filename");
805035fccdfSKevin Wolf     } else if (filename && !qdict_haskey(options, "filename")) {
806035fccdfSKevin Wolf         qdict_put(options, "filename", qstring_from_str(filename));
80798289620SKevin Wolf         allow_protocol_prefix = true;
808035fccdfSKevin Wolf     } else {
809035fccdfSKevin Wolf         qerror_report(ERROR_CLASS_GENERIC_ERROR, "Can't specify 'file' and "
810035fccdfSKevin Wolf                       "'filename' options at the same time");
811035fccdfSKevin Wolf         ret = -EINVAL;
812035fccdfSKevin Wolf         goto fail;
813035fccdfSKevin Wolf     }
814035fccdfSKevin Wolf 
815c2ad1b0cSKevin Wolf     /* Find the right block driver */
816c2ad1b0cSKevin Wolf     drvname = qdict_get_try_str(options, "driver");
817c2ad1b0cSKevin Wolf     if (drvname) {
818b64ec4e4SFam Zheng         drv = bdrv_find_whitelisted_format(drvname, !(flags & BDRV_O_RDWR));
819c2ad1b0cSKevin Wolf         qdict_del(options, "driver");
820c2ad1b0cSKevin Wolf     } else if (filename) {
82198289620SKevin Wolf         drv = bdrv_find_protocol(filename, allow_protocol_prefix);
82298289620SKevin Wolf         if (!drv) {
82398289620SKevin Wolf             qerror_report(ERROR_CLASS_GENERIC_ERROR, "Unknown protocol");
82498289620SKevin Wolf         }
825c2ad1b0cSKevin Wolf     } else {
826c2ad1b0cSKevin Wolf         qerror_report(ERROR_CLASS_GENERIC_ERROR,
827c2ad1b0cSKevin Wolf                       "Must specify either driver or file");
828c2ad1b0cSKevin Wolf         drv = NULL;
829c2ad1b0cSKevin Wolf     }
830c2ad1b0cSKevin Wolf 
831c2ad1b0cSKevin Wolf     if (!drv) {
832c2ad1b0cSKevin Wolf         ret = -ENOENT;
833c2ad1b0cSKevin Wolf         goto fail;
834c2ad1b0cSKevin Wolf     }
835c2ad1b0cSKevin Wolf 
836c2ad1b0cSKevin Wolf     /* Parse the filename and open it */
837c2ad1b0cSKevin Wolf     if (drv->bdrv_parse_filename && filename) {
8386963a30dSKevin Wolf         Error *local_err = NULL;
8396963a30dSKevin Wolf         drv->bdrv_parse_filename(filename, options, &local_err);
8406963a30dSKevin Wolf         if (error_is_set(&local_err)) {
8416963a30dSKevin Wolf             qerror_report_err(local_err);
8426963a30dSKevin Wolf             error_free(local_err);
8436963a30dSKevin Wolf             ret = -EINVAL;
8446963a30dSKevin Wolf             goto fail;
8456963a30dSKevin Wolf         }
84656d1b4d2SKevin Wolf         qdict_del(options, "filename");
847c2ad1b0cSKevin Wolf     } else if (!drv->bdrv_parse_filename && !filename) {
848c2ad1b0cSKevin Wolf         qerror_report(ERROR_CLASS_GENERIC_ERROR,
849c2ad1b0cSKevin Wolf                       "The '%s' block driver requires a file name",
850c2ad1b0cSKevin Wolf                       drv->format_name);
851c2ad1b0cSKevin Wolf         ret = -EINVAL;
852c2ad1b0cSKevin Wolf         goto fail;
8536963a30dSKevin Wolf     }
8546963a30dSKevin Wolf 
855035fccdfSKevin Wolf     ret = bdrv_open_common(bs, NULL, options, flags, drv);
856707ff828SKevin Wolf     if (ret < 0) {
857707ff828SKevin Wolf         goto fail;
858707ff828SKevin Wolf     }
859707ff828SKevin Wolf 
860707ff828SKevin Wolf     /* Check if any unknown options were used */
861707ff828SKevin Wolf     if (qdict_size(options) != 0) {
862707ff828SKevin Wolf         const QDictEntry *entry = qdict_first(options);
863707ff828SKevin Wolf         qerror_report(ERROR_CLASS_GENERIC_ERROR, "Block protocol '%s' doesn't "
864707ff828SKevin Wolf                       "support the option '%s'",
865707ff828SKevin Wolf                       drv->format_name, entry->key);
866707ff828SKevin Wolf         ret = -EINVAL;
867707ff828SKevin Wolf         goto fail;
868707ff828SKevin Wolf     }
869707ff828SKevin Wolf     QDECREF(options);
870707ff828SKevin Wolf 
87171d0770cSaliguori     bs->growable = 1;
87283f64091Sbellard     *pbs = bs;
87383f64091Sbellard     return 0;
874707ff828SKevin Wolf 
875707ff828SKevin Wolf fail:
876707ff828SKevin Wolf     QDECREF(options);
877707ff828SKevin Wolf     if (!bs->drv) {
878707ff828SKevin Wolf         QDECREF(bs->options);
879707ff828SKevin Wolf     }
880707ff828SKevin Wolf     bdrv_delete(bs);
881707ff828SKevin Wolf     return ret;
8823b0d4f61Sbellard }
8833b0d4f61Sbellard 
88431ca6d07SKevin Wolf /*
88531ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
88631ca6d07SKevin Wolf  *
88731ca6d07SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
88831ca6d07SKevin Wolf  * empty set of options. The reference to the QDict is transferred to this
88931ca6d07SKevin Wolf  * function (even on failure), so if the caller intends to reuse the dictionary,
89031ca6d07SKevin Wolf  * it needs to use QINCREF() before calling bdrv_file_open.
89131ca6d07SKevin Wolf  */
89231ca6d07SKevin Wolf int bdrv_open_backing_file(BlockDriverState *bs, QDict *options)
8939156df12SPaolo Bonzini {
8949156df12SPaolo Bonzini     char backing_filename[PATH_MAX];
8959156df12SPaolo Bonzini     int back_flags, ret;
8969156df12SPaolo Bonzini     BlockDriver *back_drv = NULL;
8979156df12SPaolo Bonzini 
8989156df12SPaolo Bonzini     if (bs->backing_hd != NULL) {
89931ca6d07SKevin Wolf         QDECREF(options);
9009156df12SPaolo Bonzini         return 0;
9019156df12SPaolo Bonzini     }
9029156df12SPaolo Bonzini 
90331ca6d07SKevin Wolf     /* NULL means an empty set of options */
90431ca6d07SKevin Wolf     if (options == NULL) {
90531ca6d07SKevin Wolf         options = qdict_new();
90631ca6d07SKevin Wolf     }
90731ca6d07SKevin Wolf 
9089156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
9091cb6f506SKevin Wolf     if (qdict_haskey(options, "file.filename")) {
9101cb6f506SKevin Wolf         backing_filename[0] = '\0';
9111cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
91231ca6d07SKevin Wolf         QDECREF(options);
9139156df12SPaolo Bonzini         return 0;
9149156df12SPaolo Bonzini     }
9159156df12SPaolo Bonzini 
9169156df12SPaolo Bonzini     bs->backing_hd = bdrv_new("");
9179156df12SPaolo Bonzini     bdrv_get_full_backing_filename(bs, backing_filename,
9189156df12SPaolo Bonzini                                    sizeof(backing_filename));
9199156df12SPaolo Bonzini 
9209156df12SPaolo Bonzini     if (bs->backing_format[0] != '\0') {
9219156df12SPaolo Bonzini         back_drv = bdrv_find_format(bs->backing_format);
9229156df12SPaolo Bonzini     }
9239156df12SPaolo Bonzini 
9249156df12SPaolo Bonzini     /* backing files always opened read-only */
9259156df12SPaolo Bonzini     back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT);
9269156df12SPaolo Bonzini 
92731ca6d07SKevin Wolf     ret = bdrv_open(bs->backing_hd,
92831ca6d07SKevin Wolf                     *backing_filename ? backing_filename : NULL, options,
929de9c0cecSKevin Wolf                     back_flags, back_drv);
9309156df12SPaolo Bonzini     if (ret < 0) {
9319156df12SPaolo Bonzini         bdrv_delete(bs->backing_hd);
9329156df12SPaolo Bonzini         bs->backing_hd = NULL;
9339156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
9349156df12SPaolo Bonzini         return ret;
9359156df12SPaolo Bonzini     }
9369156df12SPaolo Bonzini     return 0;
9379156df12SPaolo Bonzini }
9389156df12SPaolo Bonzini 
939707ff828SKevin Wolf static void extract_subqdict(QDict *src, QDict **dst, const char *start)
940707ff828SKevin Wolf {
941707ff828SKevin Wolf     const QDictEntry *entry, *next;
942707ff828SKevin Wolf     const char *p;
943707ff828SKevin Wolf 
944707ff828SKevin Wolf     *dst = qdict_new();
945707ff828SKevin Wolf     entry = qdict_first(src);
946707ff828SKevin Wolf 
947707ff828SKevin Wolf     while (entry != NULL) {
948707ff828SKevin Wolf         next = qdict_next(src, entry);
949707ff828SKevin Wolf         if (strstart(entry->key, start, &p)) {
950707ff828SKevin Wolf             qobject_incref(entry->value);
951707ff828SKevin Wolf             qdict_put_obj(*dst, p, entry->value);
952707ff828SKevin Wolf             qdict_del(src, entry->key);
953707ff828SKevin Wolf         }
954707ff828SKevin Wolf         entry = next;
955707ff828SKevin Wolf     }
956707ff828SKevin Wolf }
957707ff828SKevin Wolf 
958b6ce07aaSKevin Wolf /*
959b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
960de9c0cecSKevin Wolf  *
961de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
962de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
963de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
964de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
965b6ce07aaSKevin Wolf  */
966de9c0cecSKevin Wolf int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,
967de9c0cecSKevin Wolf               int flags, BlockDriver *drv)
968ea2384d3Sbellard {
969b6ce07aaSKevin Wolf     int ret;
97089c9bc3dSStefan Weil     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
97189c9bc3dSStefan Weil     char tmp_filename[PATH_MAX + 1];
972f500a6d3SKevin Wolf     BlockDriverState *file = NULL;
973707ff828SKevin Wolf     QDict *file_options = NULL;
97474fe54f2SKevin Wolf     const char *drvname;
97533e3963eSbellard 
976de9c0cecSKevin Wolf     /* NULL means an empty set of options */
977de9c0cecSKevin Wolf     if (options == NULL) {
978de9c0cecSKevin Wolf         options = qdict_new();
979de9c0cecSKevin Wolf     }
980de9c0cecSKevin Wolf 
981de9c0cecSKevin Wolf     bs->options = options;
982b6ad491aSKevin Wolf     options = qdict_clone_shallow(options);
983de9c0cecSKevin Wolf 
984de9c0cecSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay */
98583f64091Sbellard     if (flags & BDRV_O_SNAPSHOT) {
986ea2384d3Sbellard         BlockDriverState *bs1;
987ea2384d3Sbellard         int64_t total_size;
98891a073a9SKevin Wolf         BlockDriver *bdrv_qcow2;
98908b392e1SKevin Wolf         QEMUOptionParameter *create_options;
990b6ce07aaSKevin Wolf         char backing_filename[PATH_MAX];
99133e3963eSbellard 
992c2ad1b0cSKevin Wolf         if (qdict_size(options) != 0) {
993c2ad1b0cSKevin Wolf             error_report("Can't use snapshot=on with driver-specific options");
994c2ad1b0cSKevin Wolf             ret = -EINVAL;
995c2ad1b0cSKevin Wolf             goto fail;
996c2ad1b0cSKevin Wolf         }
997c2ad1b0cSKevin Wolf         assert(filename != NULL);
998c2ad1b0cSKevin Wolf 
999ea2384d3Sbellard         /* if snapshot, we create a temporary backing file and open it
1000ea2384d3Sbellard            instead of opening 'filename' directly */
1001ea2384d3Sbellard 
1002ea2384d3Sbellard         /* if there is a backing file, use it */
1003ea2384d3Sbellard         bs1 = bdrv_new("");
1004de9c0cecSKevin Wolf         ret = bdrv_open(bs1, filename, NULL, 0, drv);
100551d7c00cSaliguori         if (ret < 0) {
1006ea2384d3Sbellard             bdrv_delete(bs1);
1007de9c0cecSKevin Wolf             goto fail;
1008ea2384d3Sbellard         }
10093e82990bSJes Sorensen         total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
10107c96d46eSaliguori 
1011ea2384d3Sbellard         bdrv_delete(bs1);
1012ea2384d3Sbellard 
1013eba25057SJim Meyering         ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
1014eba25057SJim Meyering         if (ret < 0) {
1015de9c0cecSKevin Wolf             goto fail;
1016eba25057SJim Meyering         }
10177c96d46eSaliguori 
10187c96d46eSaliguori         /* Real path is meaningless for protocols */
10194d70655bSStefan Hajnoczi         if (path_has_protocol(filename)) {
10207c96d46eSaliguori             snprintf(backing_filename, sizeof(backing_filename),
10217c96d46eSaliguori                      "%s", filename);
1022de9c0cecSKevin Wolf         } else if (!realpath(filename, backing_filename)) {
1023de9c0cecSKevin Wolf             ret = -errno;
1024de9c0cecSKevin Wolf             goto fail;
1025de9c0cecSKevin Wolf         }
10267c96d46eSaliguori 
102791a073a9SKevin Wolf         bdrv_qcow2 = bdrv_find_format("qcow2");
102808b392e1SKevin Wolf         create_options = parse_option_parameters("", bdrv_qcow2->create_options,
102908b392e1SKevin Wolf                                                  NULL);
103091a073a9SKevin Wolf 
103108b392e1SKevin Wolf         set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);
103208b392e1SKevin Wolf         set_option_parameter(create_options, BLOCK_OPT_BACKING_FILE,
103308b392e1SKevin Wolf                              backing_filename);
103491a073a9SKevin Wolf         if (drv) {
103508b392e1SKevin Wolf             set_option_parameter(create_options, BLOCK_OPT_BACKING_FMT,
103691a073a9SKevin Wolf                 drv->format_name);
103791a073a9SKevin Wolf         }
103891a073a9SKevin Wolf 
103908b392e1SKevin Wolf         ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options);
104008b392e1SKevin Wolf         free_option_parameters(create_options);
104151d7c00cSaliguori         if (ret < 0) {
1042de9c0cecSKevin Wolf             goto fail;
1043ea2384d3Sbellard         }
104491a073a9SKevin Wolf 
1045ea2384d3Sbellard         filename = tmp_filename;
104691a073a9SKevin Wolf         drv = bdrv_qcow2;
1047ea2384d3Sbellard         bs->is_temporary = 1;
1048ea2384d3Sbellard     }
1049ea2384d3Sbellard 
1050f500a6d3SKevin Wolf     /* Open image file without format layer */
1051be028adcSJeff Cody     if (flags & BDRV_O_RDWR) {
1052be028adcSJeff Cody         flags |= BDRV_O_ALLOW_RDWR;
1053be028adcSJeff Cody     }
1054be028adcSJeff Cody 
1055707ff828SKevin Wolf     extract_subqdict(options, &file_options, "file.");
1056707ff828SKevin Wolf 
1057707ff828SKevin Wolf     ret = bdrv_file_open(&file, filename, file_options,
105850b05b6fSKevin Wolf                          bdrv_open_flags(bs, flags | BDRV_O_UNMAP));
1059f500a6d3SKevin Wolf     if (ret < 0) {
1060de9c0cecSKevin Wolf         goto fail;
1061f500a6d3SKevin Wolf     }
1062f500a6d3SKevin Wolf 
1063f500a6d3SKevin Wolf     /* Find the right image format driver */
106474fe54f2SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
106574fe54f2SKevin Wolf     if (drvname) {
106674fe54f2SKevin Wolf         drv = bdrv_find_whitelisted_format(drvname, !(flags & BDRV_O_RDWR));
106774fe54f2SKevin Wolf         qdict_del(options, "driver");
106874fe54f2SKevin Wolf     }
106974fe54f2SKevin Wolf 
1070f500a6d3SKevin Wolf     if (!drv) {
1071f500a6d3SKevin Wolf         ret = find_image_format(file, filename, &drv);
1072f500a6d3SKevin Wolf     }
1073f500a6d3SKevin Wolf 
1074f500a6d3SKevin Wolf     if (!drv) {
1075f500a6d3SKevin Wolf         goto unlink_and_fail;
1076f500a6d3SKevin Wolf     }
1077f500a6d3SKevin Wolf 
1078b6ce07aaSKevin Wolf     /* Open the image */
1079035fccdfSKevin Wolf     ret = bdrv_open_common(bs, file, options, flags, drv);
1080b6ce07aaSKevin Wolf     if (ret < 0) {
10816987307cSChristoph Hellwig         goto unlink_and_fail;
10826987307cSChristoph Hellwig     }
10836987307cSChristoph Hellwig 
1084f500a6d3SKevin Wolf     if (bs->file != file) {
1085f500a6d3SKevin Wolf         bdrv_delete(file);
1086f500a6d3SKevin Wolf         file = NULL;
1087f500a6d3SKevin Wolf     }
1088f500a6d3SKevin Wolf 
1089b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
10909156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
109131ca6d07SKevin Wolf         QDict *backing_options;
109231ca6d07SKevin Wolf 
109331ca6d07SKevin Wolf         extract_subqdict(options, &backing_options, "backing.");
109431ca6d07SKevin Wolf         ret = bdrv_open_backing_file(bs, backing_options);
1095b6ce07aaSKevin Wolf         if (ret < 0) {
1096b6ad491aSKevin Wolf             goto close_and_fail;
1097b6ce07aaSKevin Wolf         }
1098b6ce07aaSKevin Wolf     }
1099b6ce07aaSKevin Wolf 
1100b6ad491aSKevin Wolf     /* Check if any unknown options were used */
1101b6ad491aSKevin Wolf     if (qdict_size(options) != 0) {
1102b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
1103b6ad491aSKevin Wolf         qerror_report(ERROR_CLASS_GENERIC_ERROR, "Block format '%s' used by "
1104b6ad491aSKevin Wolf             "device '%s' doesn't support the option '%s'",
1105b6ad491aSKevin Wolf             drv->format_name, bs->device_name, entry->key);
1106b6ad491aSKevin Wolf 
1107b6ad491aSKevin Wolf         ret = -EINVAL;
1108b6ad491aSKevin Wolf         goto close_and_fail;
1109b6ad491aSKevin Wolf     }
1110b6ad491aSKevin Wolf     QDECREF(options);
1111b6ad491aSKevin Wolf 
1112b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
11137d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
1114b6ce07aaSKevin Wolf     }
1115b6ce07aaSKevin Wolf 
111698f90dbaSZhi Yong Wu     /* throttling disk I/O limits */
111798f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
111898f90dbaSZhi Yong Wu         bdrv_io_limits_enable(bs);
111998f90dbaSZhi Yong Wu     }
112098f90dbaSZhi Yong Wu 
1121b6ce07aaSKevin Wolf     return 0;
1122b6ce07aaSKevin Wolf 
1123b6ce07aaSKevin Wolf unlink_and_fail:
1124f500a6d3SKevin Wolf     if (file != NULL) {
1125f500a6d3SKevin Wolf         bdrv_delete(file);
1126f500a6d3SKevin Wolf     }
1127b6ce07aaSKevin Wolf     if (bs->is_temporary) {
1128b6ce07aaSKevin Wolf         unlink(filename);
1129b6ce07aaSKevin Wolf     }
1130de9c0cecSKevin Wolf fail:
1131de9c0cecSKevin Wolf     QDECREF(bs->options);
1132b6ad491aSKevin Wolf     QDECREF(options);
1133de9c0cecSKevin Wolf     bs->options = NULL;
1134b6ad491aSKevin Wolf     return ret;
1135de9c0cecSKevin Wolf 
1136b6ad491aSKevin Wolf close_and_fail:
1137b6ad491aSKevin Wolf     bdrv_close(bs);
1138b6ad491aSKevin Wolf     QDECREF(options);
1139b6ce07aaSKevin Wolf     return ret;
1140b6ce07aaSKevin Wolf }
1141b6ce07aaSKevin Wolf 
1142e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1143e971aa12SJeff Cody      bool prepared;
1144e971aa12SJeff Cody      BDRVReopenState state;
1145e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1146e971aa12SJeff Cody } BlockReopenQueueEntry;
1147e971aa12SJeff Cody 
1148e971aa12SJeff Cody /*
1149e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1150e971aa12SJeff Cody  * reopen of multiple devices.
1151e971aa12SJeff Cody  *
1152e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1153e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1154e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1155e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1156e971aa12SJeff Cody  * atomic 'set'.
1157e971aa12SJeff Cody  *
1158e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1159e971aa12SJeff Cody  *
1160e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1161e971aa12SJeff Cody  *
1162e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1163e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1164e971aa12SJeff Cody  *
1165e971aa12SJeff Cody  */
1166e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1167e971aa12SJeff Cody                                     BlockDriverState *bs, int flags)
1168e971aa12SJeff Cody {
1169e971aa12SJeff Cody     assert(bs != NULL);
1170e971aa12SJeff Cody 
1171e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
1172e971aa12SJeff Cody     if (bs_queue == NULL) {
1173e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1174e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1175e971aa12SJeff Cody     }
1176e971aa12SJeff Cody 
1177e971aa12SJeff Cody     if (bs->file) {
1178e971aa12SJeff Cody         bdrv_reopen_queue(bs_queue, bs->file, flags);
1179e971aa12SJeff Cody     }
1180e971aa12SJeff Cody 
1181e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1182e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1183e971aa12SJeff Cody 
1184e971aa12SJeff Cody     bs_entry->state.bs = bs;
1185e971aa12SJeff Cody     bs_entry->state.flags = flags;
1186e971aa12SJeff Cody 
1187e971aa12SJeff Cody     return bs_queue;
1188e971aa12SJeff Cody }
1189e971aa12SJeff Cody 
1190e971aa12SJeff Cody /*
1191e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1192e971aa12SJeff Cody  *
1193e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1194e971aa12SJeff Cody  * via bdrv_reopen_queue().
1195e971aa12SJeff Cody  *
1196e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1197e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1198e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1199e971aa12SJeff Cody  * data cleaned up.
1200e971aa12SJeff Cody  *
1201e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1202e971aa12SJeff Cody  * to all devices.
1203e971aa12SJeff Cody  *
1204e971aa12SJeff Cody  */
1205e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1206e971aa12SJeff Cody {
1207e971aa12SJeff Cody     int ret = -1;
1208e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1209e971aa12SJeff Cody     Error *local_err = NULL;
1210e971aa12SJeff Cody 
1211e971aa12SJeff Cody     assert(bs_queue != NULL);
1212e971aa12SJeff Cody 
1213e971aa12SJeff Cody     bdrv_drain_all();
1214e971aa12SJeff Cody 
1215e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1216e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1217e971aa12SJeff Cody             error_propagate(errp, local_err);
1218e971aa12SJeff Cody             goto cleanup;
1219e971aa12SJeff Cody         }
1220e971aa12SJeff Cody         bs_entry->prepared = true;
1221e971aa12SJeff Cody     }
1222e971aa12SJeff Cody 
1223e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1224e971aa12SJeff Cody      * changes
1225e971aa12SJeff Cody      */
1226e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1227e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1228e971aa12SJeff Cody     }
1229e971aa12SJeff Cody 
1230e971aa12SJeff Cody     ret = 0;
1231e971aa12SJeff Cody 
1232e971aa12SJeff Cody cleanup:
1233e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1234e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1235e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1236e971aa12SJeff Cody         }
1237e971aa12SJeff Cody         g_free(bs_entry);
1238e971aa12SJeff Cody     }
1239e971aa12SJeff Cody     g_free(bs_queue);
1240e971aa12SJeff Cody     return ret;
1241e971aa12SJeff Cody }
1242e971aa12SJeff Cody 
1243e971aa12SJeff Cody 
1244e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1245e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1246e971aa12SJeff Cody {
1247e971aa12SJeff Cody     int ret = -1;
1248e971aa12SJeff Cody     Error *local_err = NULL;
1249e971aa12SJeff Cody     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1250e971aa12SJeff Cody 
1251e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1252e971aa12SJeff Cody     if (local_err != NULL) {
1253e971aa12SJeff Cody         error_propagate(errp, local_err);
1254e971aa12SJeff Cody     }
1255e971aa12SJeff Cody     return ret;
1256e971aa12SJeff Cody }
1257e971aa12SJeff Cody 
1258e971aa12SJeff Cody 
1259e971aa12SJeff Cody /*
1260e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1261e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1262e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1263e971aa12SJeff Cody  *
1264e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1265e971aa12SJeff Cody  * flags are the new open flags
1266e971aa12SJeff Cody  * queue is the reopen queue
1267e971aa12SJeff Cody  *
1268e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1269e971aa12SJeff Cody  * as well.
1270e971aa12SJeff Cody  *
1271e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1272e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1273e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1274e971aa12SJeff Cody  *
1275e971aa12SJeff Cody  */
1276e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1277e971aa12SJeff Cody                         Error **errp)
1278e971aa12SJeff Cody {
1279e971aa12SJeff Cody     int ret = -1;
1280e971aa12SJeff Cody     Error *local_err = NULL;
1281e971aa12SJeff Cody     BlockDriver *drv;
1282e971aa12SJeff Cody 
1283e971aa12SJeff Cody     assert(reopen_state != NULL);
1284e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1285e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1286e971aa12SJeff Cody 
1287e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1288e971aa12SJeff Cody      * to r/w */
1289e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1290e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
1291e971aa12SJeff Cody         error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1292e971aa12SJeff Cody                   reopen_state->bs->device_name);
1293e971aa12SJeff Cody         goto error;
1294e971aa12SJeff Cody     }
1295e971aa12SJeff Cody 
1296e971aa12SJeff Cody 
1297e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1298e971aa12SJeff Cody     if (ret) {
1299e971aa12SJeff Cody         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1300e971aa12SJeff Cody                   strerror(-ret));
1301e971aa12SJeff Cody         goto error;
1302e971aa12SJeff Cody     }
1303e971aa12SJeff Cody 
1304e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1305e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1306e971aa12SJeff Cody         if (ret) {
1307e971aa12SJeff Cody             if (local_err != NULL) {
1308e971aa12SJeff Cody                 error_propagate(errp, local_err);
1309e971aa12SJeff Cody             } else {
1310d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
1311e971aa12SJeff Cody                            reopen_state->bs->filename);
1312e971aa12SJeff Cody             }
1313e971aa12SJeff Cody             goto error;
1314e971aa12SJeff Cody         }
1315e971aa12SJeff Cody     } else {
1316e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1317e971aa12SJeff Cody          * handler for each supported drv. */
1318e971aa12SJeff Cody         error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1319e971aa12SJeff Cody                   drv->format_name, reopen_state->bs->device_name,
1320e971aa12SJeff Cody                  "reopening of file");
1321e971aa12SJeff Cody         ret = -1;
1322e971aa12SJeff Cody         goto error;
1323e971aa12SJeff Cody     }
1324e971aa12SJeff Cody 
1325e971aa12SJeff Cody     ret = 0;
1326e971aa12SJeff Cody 
1327e971aa12SJeff Cody error:
1328e971aa12SJeff Cody     return ret;
1329e971aa12SJeff Cody }
1330e971aa12SJeff Cody 
1331e971aa12SJeff Cody /*
1332e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1333e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1334e971aa12SJeff Cody  * the active BlockDriverState contents.
1335e971aa12SJeff Cody  */
1336e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1337e971aa12SJeff Cody {
1338e971aa12SJeff Cody     BlockDriver *drv;
1339e971aa12SJeff Cody 
1340e971aa12SJeff Cody     assert(reopen_state != NULL);
1341e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1342e971aa12SJeff Cody     assert(drv != NULL);
1343e971aa12SJeff Cody 
1344e971aa12SJeff Cody     /* If there are any driver level actions to take */
1345e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1346e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1347e971aa12SJeff Cody     }
1348e971aa12SJeff Cody 
1349e971aa12SJeff Cody     /* set BDS specific flags now */
1350e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1351e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1352e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1353e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1354e971aa12SJeff Cody }
1355e971aa12SJeff Cody 
1356e971aa12SJeff Cody /*
1357e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1358e971aa12SJeff Cody  * reopen_state
1359e971aa12SJeff Cody  */
1360e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1361e971aa12SJeff Cody {
1362e971aa12SJeff Cody     BlockDriver *drv;
1363e971aa12SJeff Cody 
1364e971aa12SJeff Cody     assert(reopen_state != NULL);
1365e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1366e971aa12SJeff Cody     assert(drv != NULL);
1367e971aa12SJeff Cody 
1368e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1369e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1370e971aa12SJeff Cody     }
1371e971aa12SJeff Cody }
1372e971aa12SJeff Cody 
1373e971aa12SJeff Cody 
1374fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1375fc01f7e7Sbellard {
13763e914655SPaolo Bonzini     if (bs->job) {
13773e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
13783e914655SPaolo Bonzini     }
137958fda173SStefan Hajnoczi     bdrv_drain_all(); /* complete I/O */
138058fda173SStefan Hajnoczi     bdrv_flush(bs);
138158fda173SStefan Hajnoczi     bdrv_drain_all(); /* in case flush left pending I/O */
1382d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
13837094f12fSKevin Wolf 
13843cbc002cSPaolo Bonzini     if (bs->drv) {
1385557df6acSStefan Hajnoczi         if (bs->backing_hd) {
1386ea2384d3Sbellard             bdrv_delete(bs->backing_hd);
1387557df6acSStefan Hajnoczi             bs->backing_hd = NULL;
1388557df6acSStefan Hajnoczi         }
1389ea2384d3Sbellard         bs->drv->bdrv_close(bs);
13907267c094SAnthony Liguori         g_free(bs->opaque);
1391ea2384d3Sbellard #ifdef _WIN32
1392ea2384d3Sbellard         if (bs->is_temporary) {
1393ea2384d3Sbellard             unlink(bs->filename);
1394ea2384d3Sbellard         }
139567b915a5Sbellard #endif
1396ea2384d3Sbellard         bs->opaque = NULL;
1397ea2384d3Sbellard         bs->drv = NULL;
139853fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1399a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1400a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
14016405875cSPaolo Bonzini         bs->total_sectors = 0;
14026405875cSPaolo Bonzini         bs->encrypted = 0;
14036405875cSPaolo Bonzini         bs->valid_key = 0;
14046405875cSPaolo Bonzini         bs->sg = 0;
14056405875cSPaolo Bonzini         bs->growable = 0;
14060d51b4deSAsias He         bs->zero_beyond_eof = false;
1407de9c0cecSKevin Wolf         QDECREF(bs->options);
1408de9c0cecSKevin Wolf         bs->options = NULL;
1409b338082bSbellard 
141066f82ceeSKevin Wolf         if (bs->file != NULL) {
14110ac9377dSPaolo Bonzini             bdrv_delete(bs->file);
14120ac9377dSPaolo Bonzini             bs->file = NULL;
141366f82ceeSKevin Wolf         }
14149ca11154SPavel Hrdina     }
141566f82ceeSKevin Wolf 
14167d4b4ba5SMarkus Armbruster     bdrv_dev_change_media_cb(bs, false);
141798f90dbaSZhi Yong Wu 
141898f90dbaSZhi Yong Wu     /*throttling disk I/O limits*/
141998f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
142098f90dbaSZhi Yong Wu         bdrv_io_limits_disable(bs);
142198f90dbaSZhi Yong Wu     }
1422b338082bSbellard }
1423b338082bSbellard 
14242bc93fedSMORITA Kazutaka void bdrv_close_all(void)
14252bc93fedSMORITA Kazutaka {
14262bc93fedSMORITA Kazutaka     BlockDriverState *bs;
14272bc93fedSMORITA Kazutaka 
14282bc93fedSMORITA Kazutaka     QTAILQ_FOREACH(bs, &bdrv_states, list) {
14292bc93fedSMORITA Kazutaka         bdrv_close(bs);
14302bc93fedSMORITA Kazutaka     }
14312bc93fedSMORITA Kazutaka }
14322bc93fedSMORITA Kazutaka 
143388266f5aSStefan Hajnoczi /* Check if any requests are in-flight (including throttled requests) */
143488266f5aSStefan Hajnoczi static bool bdrv_requests_pending(BlockDriverState *bs)
143588266f5aSStefan Hajnoczi {
143688266f5aSStefan Hajnoczi     if (!QLIST_EMPTY(&bs->tracked_requests)) {
143788266f5aSStefan Hajnoczi         return true;
143888266f5aSStefan Hajnoczi     }
143988266f5aSStefan Hajnoczi     if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
144088266f5aSStefan Hajnoczi         return true;
144188266f5aSStefan Hajnoczi     }
144288266f5aSStefan Hajnoczi     if (bs->file && bdrv_requests_pending(bs->file)) {
144388266f5aSStefan Hajnoczi         return true;
144488266f5aSStefan Hajnoczi     }
144588266f5aSStefan Hajnoczi     if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) {
144688266f5aSStefan Hajnoczi         return true;
144788266f5aSStefan Hajnoczi     }
144888266f5aSStefan Hajnoczi     return false;
144988266f5aSStefan Hajnoczi }
145088266f5aSStefan Hajnoczi 
145188266f5aSStefan Hajnoczi static bool bdrv_requests_pending_all(void)
145288266f5aSStefan Hajnoczi {
145388266f5aSStefan Hajnoczi     BlockDriverState *bs;
145488266f5aSStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
145588266f5aSStefan Hajnoczi         if (bdrv_requests_pending(bs)) {
145688266f5aSStefan Hajnoczi             return true;
145788266f5aSStefan Hajnoczi         }
145888266f5aSStefan Hajnoczi     }
145988266f5aSStefan Hajnoczi     return false;
146088266f5aSStefan Hajnoczi }
146188266f5aSStefan Hajnoczi 
1462922453bcSStefan Hajnoczi /*
1463922453bcSStefan Hajnoczi  * Wait for pending requests to complete across all BlockDriverStates
1464922453bcSStefan Hajnoczi  *
1465922453bcSStefan Hajnoczi  * This function does not flush data to disk, use bdrv_flush_all() for that
1466922453bcSStefan Hajnoczi  * after calling this function.
14674c355d53SZhi Yong Wu  *
14684c355d53SZhi Yong Wu  * Note that completion of an asynchronous I/O operation can trigger any
14694c355d53SZhi Yong Wu  * number of other I/O operations on other devices---for example a coroutine
14704c355d53SZhi Yong Wu  * can be arbitrarily complex and a constant flow of I/O can come until the
14714c355d53SZhi Yong Wu  * coroutine is complete.  Because of this, it is not possible to have a
14724c355d53SZhi Yong Wu  * function to drain a single device's I/O queue.
1473922453bcSStefan Hajnoczi  */
1474922453bcSStefan Hajnoczi void bdrv_drain_all(void)
1475922453bcSStefan Hajnoczi {
147688266f5aSStefan Hajnoczi     /* Always run first iteration so any pending completion BHs run */
147788266f5aSStefan Hajnoczi     bool busy = true;
1478922453bcSStefan Hajnoczi     BlockDriverState *bs;
1479922453bcSStefan Hajnoczi 
148088266f5aSStefan Hajnoczi     while (busy) {
14814c355d53SZhi Yong Wu         /* FIXME: We do not have timer support here, so this is effectively
14824c355d53SZhi Yong Wu          * a busy wait.
14834c355d53SZhi Yong Wu          */
14844c355d53SZhi Yong Wu         QTAILQ_FOREACH(bs, &bdrv_states, list) {
1485b681a1c7SBenoît Canet             while (qemu_co_enter_next(&bs->throttled_reqs)) {
14864c355d53SZhi Yong Wu                 busy = true;
14874c355d53SZhi Yong Wu             }
14884c355d53SZhi Yong Wu         }
1489922453bcSStefan Hajnoczi 
149088266f5aSStefan Hajnoczi         busy = bdrv_requests_pending_all();
149188266f5aSStefan Hajnoczi         busy |= aio_poll(qemu_get_aio_context(), busy);
1492922453bcSStefan Hajnoczi     }
1493922453bcSStefan Hajnoczi }
1494922453bcSStefan Hajnoczi 
1495d22b2f41SRyan Harper /* make a BlockDriverState anonymous by removing from bdrv_state list.
1496d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
1497d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
1498d22b2f41SRyan Harper {
1499d22b2f41SRyan Harper     if (bs->device_name[0] != '\0') {
1500d22b2f41SRyan Harper         QTAILQ_REMOVE(&bdrv_states, bs, list);
1501d22b2f41SRyan Harper     }
1502d22b2f41SRyan Harper     bs->device_name[0] = '\0';
1503d22b2f41SRyan Harper }
1504d22b2f41SRyan Harper 
1505e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs)
1506e023b2e2SPaolo Bonzini {
1507e023b2e2SPaolo Bonzini     if (bs->drv && bs->drv->bdrv_rebind) {
1508e023b2e2SPaolo Bonzini         bs->drv->bdrv_rebind(bs);
1509e023b2e2SPaolo Bonzini     }
1510e023b2e2SPaolo Bonzini }
1511e023b2e2SPaolo Bonzini 
15124ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
15134ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
15144ddc07caSPaolo Bonzini {
15154ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
15164ddc07caSPaolo Bonzini     bs_dest->open_flags         = bs_src->open_flags;
15174ddc07caSPaolo Bonzini 
15184ddc07caSPaolo Bonzini     /* dev info */
15194ddc07caSPaolo Bonzini     bs_dest->dev_ops            = bs_src->dev_ops;
15204ddc07caSPaolo Bonzini     bs_dest->dev_opaque         = bs_src->dev_opaque;
15214ddc07caSPaolo Bonzini     bs_dest->dev                = bs_src->dev;
15224ddc07caSPaolo Bonzini     bs_dest->buffer_alignment   = bs_src->buffer_alignment;
15234ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
15244ddc07caSPaolo Bonzini 
15254ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
15264ddc07caSPaolo Bonzini 
15274ddc07caSPaolo Bonzini     /* i/o timing parameters */
15284ddc07caSPaolo Bonzini     bs_dest->slice_start        = bs_src->slice_start;
15294ddc07caSPaolo Bonzini     bs_dest->slice_end          = bs_src->slice_end;
15305905fbc9SStefan Hajnoczi     bs_dest->slice_submitted    = bs_src->slice_submitted;
15314ddc07caSPaolo Bonzini     bs_dest->io_limits          = bs_src->io_limits;
15324ddc07caSPaolo Bonzini     bs_dest->throttled_reqs     = bs_src->throttled_reqs;
15334ddc07caSPaolo Bonzini     bs_dest->block_timer        = bs_src->block_timer;
15344ddc07caSPaolo Bonzini     bs_dest->io_limits_enabled  = bs_src->io_limits_enabled;
15354ddc07caSPaolo Bonzini 
15364ddc07caSPaolo Bonzini     /* r/w error */
15374ddc07caSPaolo Bonzini     bs_dest->on_read_error      = bs_src->on_read_error;
15384ddc07caSPaolo Bonzini     bs_dest->on_write_error     = bs_src->on_write_error;
15394ddc07caSPaolo Bonzini 
15404ddc07caSPaolo Bonzini     /* i/o status */
15414ddc07caSPaolo Bonzini     bs_dest->iostatus_enabled   = bs_src->iostatus_enabled;
15424ddc07caSPaolo Bonzini     bs_dest->iostatus           = bs_src->iostatus;
15434ddc07caSPaolo Bonzini 
15444ddc07caSPaolo Bonzini     /* dirty bitmap */
15454ddc07caSPaolo Bonzini     bs_dest->dirty_bitmap       = bs_src->dirty_bitmap;
15464ddc07caSPaolo Bonzini 
15474ddc07caSPaolo Bonzini     /* job */
15484ddc07caSPaolo Bonzini     bs_dest->in_use             = bs_src->in_use;
15494ddc07caSPaolo Bonzini     bs_dest->job                = bs_src->job;
15504ddc07caSPaolo Bonzini 
15514ddc07caSPaolo Bonzini     /* keep the same entry in bdrv_states */
15524ddc07caSPaolo Bonzini     pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
15534ddc07caSPaolo Bonzini             bs_src->device_name);
15544ddc07caSPaolo Bonzini     bs_dest->list = bs_src->list;
15554ddc07caSPaolo Bonzini }
15564ddc07caSPaolo Bonzini 
15574ddc07caSPaolo Bonzini /*
15584ddc07caSPaolo Bonzini  * Swap bs contents for two image chains while they are live,
15594ddc07caSPaolo Bonzini  * while keeping required fields on the BlockDriverState that is
15604ddc07caSPaolo Bonzini  * actually attached to a device.
15614ddc07caSPaolo Bonzini  *
15624ddc07caSPaolo Bonzini  * This will modify the BlockDriverState fields, and swap contents
15634ddc07caSPaolo Bonzini  * between bs_new and bs_old. Both bs_new and bs_old are modified.
15644ddc07caSPaolo Bonzini  *
15654ddc07caSPaolo Bonzini  * bs_new is required to be anonymous.
15664ddc07caSPaolo Bonzini  *
15674ddc07caSPaolo Bonzini  * This function does not create any image files.
15684ddc07caSPaolo Bonzini  */
15694ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
15704ddc07caSPaolo Bonzini {
15714ddc07caSPaolo Bonzini     BlockDriverState tmp;
15724ddc07caSPaolo Bonzini 
15734ddc07caSPaolo Bonzini     /* bs_new must be anonymous and shouldn't have anything fancy enabled */
15744ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
15754ddc07caSPaolo Bonzini     assert(bs_new->dirty_bitmap == NULL);
15764ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
15774ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
15784ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
15794ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
15804ddc07caSPaolo Bonzini     assert(bs_new->block_timer == NULL);
15814ddc07caSPaolo Bonzini 
15824ddc07caSPaolo Bonzini     tmp = *bs_new;
15834ddc07caSPaolo Bonzini     *bs_new = *bs_old;
15844ddc07caSPaolo Bonzini     *bs_old = tmp;
15854ddc07caSPaolo Bonzini 
15864ddc07caSPaolo Bonzini     /* there are some fields that should not be swapped, move them back */
15874ddc07caSPaolo Bonzini     bdrv_move_feature_fields(&tmp, bs_old);
15884ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_old, bs_new);
15894ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_new, &tmp);
15904ddc07caSPaolo Bonzini 
15914ddc07caSPaolo Bonzini     /* bs_new shouldn't be in bdrv_states even after the swap!  */
15924ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
15934ddc07caSPaolo Bonzini 
15944ddc07caSPaolo Bonzini     /* Check a few fields that should remain attached to the device */
15954ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
15964ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
15974ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
15984ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
15994ddc07caSPaolo Bonzini     assert(bs_new->block_timer == NULL);
16004ddc07caSPaolo Bonzini 
16014ddc07caSPaolo Bonzini     bdrv_rebind(bs_new);
16024ddc07caSPaolo Bonzini     bdrv_rebind(bs_old);
16034ddc07caSPaolo Bonzini }
16044ddc07caSPaolo Bonzini 
16058802d1fdSJeff Cody /*
16068802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
16078802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
16088802d1fdSJeff Cody  *
16098802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
16108802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
16118802d1fdSJeff Cody  *
1612f6801b83SJeff Cody  * bs_new is required to be anonymous.
1613f6801b83SJeff Cody  *
16148802d1fdSJeff Cody  * This function does not create any image files.
16158802d1fdSJeff Cody  */
16168802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
16178802d1fdSJeff Cody {
16184ddc07caSPaolo Bonzini     bdrv_swap(bs_new, bs_top);
16198802d1fdSJeff Cody 
16208802d1fdSJeff Cody     /* The contents of 'tmp' will become bs_top, as we are
16218802d1fdSJeff Cody      * swapping bs_new and bs_top contents. */
16224ddc07caSPaolo Bonzini     bs_top->backing_hd = bs_new;
16234ddc07caSPaolo Bonzini     bs_top->open_flags &= ~BDRV_O_NO_BACKING;
16244ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
16254ddc07caSPaolo Bonzini             bs_new->filename);
16264ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
16274ddc07caSPaolo Bonzini             bs_new->drv ? bs_new->drv->format_name : "");
16288802d1fdSJeff Cody }
16298802d1fdSJeff Cody 
1630b338082bSbellard void bdrv_delete(BlockDriverState *bs)
1631b338082bSbellard {
1632fa879d62SMarkus Armbruster     assert(!bs->dev);
16333e914655SPaolo Bonzini     assert(!bs->job);
16343e914655SPaolo Bonzini     assert(!bs->in_use);
163518846deeSMarkus Armbruster 
1636e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
1637e1b5c52eSStefan Hajnoczi 
16381b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
1639d22b2f41SRyan Harper     bdrv_make_anon(bs);
164034c6f050Saurel32 
16417267c094SAnthony Liguori     g_free(bs);
1642fc01f7e7Sbellard }
1643fc01f7e7Sbellard 
1644fa879d62SMarkus Armbruster int bdrv_attach_dev(BlockDriverState *bs, void *dev)
1645fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
164618846deeSMarkus Armbruster {
1647fa879d62SMarkus Armbruster     if (bs->dev) {
164818846deeSMarkus Armbruster         return -EBUSY;
164918846deeSMarkus Armbruster     }
1650fa879d62SMarkus Armbruster     bs->dev = dev;
165128a7282aSLuiz Capitulino     bdrv_iostatus_reset(bs);
165218846deeSMarkus Armbruster     return 0;
165318846deeSMarkus Armbruster }
165418846deeSMarkus Armbruster 
1655fa879d62SMarkus Armbruster /* TODO qdevified devices don't use this, remove when devices are qdevified */
1656fa879d62SMarkus Armbruster void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
165718846deeSMarkus Armbruster {
1658fa879d62SMarkus Armbruster     if (bdrv_attach_dev(bs, dev) < 0) {
1659fa879d62SMarkus Armbruster         abort();
1660fa879d62SMarkus Armbruster     }
1661fa879d62SMarkus Armbruster }
1662fa879d62SMarkus Armbruster 
1663fa879d62SMarkus Armbruster void bdrv_detach_dev(BlockDriverState *bs, void *dev)
1664fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
1665fa879d62SMarkus Armbruster {
1666fa879d62SMarkus Armbruster     assert(bs->dev == dev);
1667fa879d62SMarkus Armbruster     bs->dev = NULL;
16680e49de52SMarkus Armbruster     bs->dev_ops = NULL;
16690e49de52SMarkus Armbruster     bs->dev_opaque = NULL;
167029e05f20SMarkus Armbruster     bs->buffer_alignment = 512;
167118846deeSMarkus Armbruster }
167218846deeSMarkus Armbruster 
1673fa879d62SMarkus Armbruster /* TODO change to return DeviceState * when all users are qdevified */
1674fa879d62SMarkus Armbruster void *bdrv_get_attached_dev(BlockDriverState *bs)
167518846deeSMarkus Armbruster {
1676fa879d62SMarkus Armbruster     return bs->dev;
167718846deeSMarkus Armbruster }
167818846deeSMarkus Armbruster 
16790e49de52SMarkus Armbruster void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
16800e49de52SMarkus Armbruster                       void *opaque)
16810e49de52SMarkus Armbruster {
16820e49de52SMarkus Armbruster     bs->dev_ops = ops;
16830e49de52SMarkus Armbruster     bs->dev_opaque = opaque;
16840e49de52SMarkus Armbruster }
16850e49de52SMarkus Armbruster 
168632c81a4aSPaolo Bonzini void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
168732c81a4aSPaolo Bonzini                                enum MonitorEvent ev,
16881ceee0d5SPaolo Bonzini                                BlockErrorAction action, bool is_read)
1689329c0a48SLuiz Capitulino {
1690329c0a48SLuiz Capitulino     QObject *data;
1691329c0a48SLuiz Capitulino     const char *action_str;
1692329c0a48SLuiz Capitulino 
1693329c0a48SLuiz Capitulino     switch (action) {
1694329c0a48SLuiz Capitulino     case BDRV_ACTION_REPORT:
1695329c0a48SLuiz Capitulino         action_str = "report";
1696329c0a48SLuiz Capitulino         break;
1697329c0a48SLuiz Capitulino     case BDRV_ACTION_IGNORE:
1698329c0a48SLuiz Capitulino         action_str = "ignore";
1699329c0a48SLuiz Capitulino         break;
1700329c0a48SLuiz Capitulino     case BDRV_ACTION_STOP:
1701329c0a48SLuiz Capitulino         action_str = "stop";
1702329c0a48SLuiz Capitulino         break;
1703329c0a48SLuiz Capitulino     default:
1704329c0a48SLuiz Capitulino         abort();
1705329c0a48SLuiz Capitulino     }
1706329c0a48SLuiz Capitulino 
1707329c0a48SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1708329c0a48SLuiz Capitulino                               bdrv->device_name,
1709329c0a48SLuiz Capitulino                               action_str,
1710329c0a48SLuiz Capitulino                               is_read ? "read" : "write");
171132c81a4aSPaolo Bonzini     monitor_protocol_event(ev, data);
1712329c0a48SLuiz Capitulino 
1713329c0a48SLuiz Capitulino     qobject_decref(data);
1714329c0a48SLuiz Capitulino }
1715329c0a48SLuiz Capitulino 
17166f382ed2SLuiz Capitulino static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
17176f382ed2SLuiz Capitulino {
17186f382ed2SLuiz Capitulino     QObject *data;
17196f382ed2SLuiz Capitulino 
17206f382ed2SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
17216f382ed2SLuiz Capitulino                               bdrv_get_device_name(bs), ejected);
17226f382ed2SLuiz Capitulino     monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
17236f382ed2SLuiz Capitulino 
17246f382ed2SLuiz Capitulino     qobject_decref(data);
17256f382ed2SLuiz Capitulino }
17266f382ed2SLuiz Capitulino 
17277d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
17280e49de52SMarkus Armbruster {
1729145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->change_media_cb) {
17306f382ed2SLuiz Capitulino         bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
17317d4b4ba5SMarkus Armbruster         bs->dev_ops->change_media_cb(bs->dev_opaque, load);
17326f382ed2SLuiz Capitulino         if (tray_was_closed) {
17336f382ed2SLuiz Capitulino             /* tray open */
17346f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, true);
17356f382ed2SLuiz Capitulino         }
17366f382ed2SLuiz Capitulino         if (load) {
17376f382ed2SLuiz Capitulino             /* tray close */
17386f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, false);
17396f382ed2SLuiz Capitulino         }
1740145feb17SMarkus Armbruster     }
1741145feb17SMarkus Armbruster }
1742145feb17SMarkus Armbruster 
17432c6942faSMarkus Armbruster bool bdrv_dev_has_removable_media(BlockDriverState *bs)
17442c6942faSMarkus Armbruster {
17452c6942faSMarkus Armbruster     return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
17462c6942faSMarkus Armbruster }
17472c6942faSMarkus Armbruster 
1748025ccaa7SPaolo Bonzini void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
1749025ccaa7SPaolo Bonzini {
1750025ccaa7SPaolo Bonzini     if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
1751025ccaa7SPaolo Bonzini         bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
1752025ccaa7SPaolo Bonzini     }
1753025ccaa7SPaolo Bonzini }
1754025ccaa7SPaolo Bonzini 
1755e4def80bSMarkus Armbruster bool bdrv_dev_is_tray_open(BlockDriverState *bs)
1756e4def80bSMarkus Armbruster {
1757e4def80bSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_tray_open) {
1758e4def80bSMarkus Armbruster         return bs->dev_ops->is_tray_open(bs->dev_opaque);
1759e4def80bSMarkus Armbruster     }
1760e4def80bSMarkus Armbruster     return false;
1761e4def80bSMarkus Armbruster }
1762e4def80bSMarkus Armbruster 
1763145feb17SMarkus Armbruster static void bdrv_dev_resize_cb(BlockDriverState *bs)
1764145feb17SMarkus Armbruster {
1765145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->resize_cb) {
1766145feb17SMarkus Armbruster         bs->dev_ops->resize_cb(bs->dev_opaque);
17670e49de52SMarkus Armbruster     }
17680e49de52SMarkus Armbruster }
17690e49de52SMarkus Armbruster 
1770f107639aSMarkus Armbruster bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
1771f107639aSMarkus Armbruster {
1772f107639aSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
1773f107639aSMarkus Armbruster         return bs->dev_ops->is_medium_locked(bs->dev_opaque);
1774f107639aSMarkus Armbruster     }
1775f107639aSMarkus Armbruster     return false;
1776f107639aSMarkus Armbruster }
1777f107639aSMarkus Armbruster 
1778e97fc193Saliguori /*
1779e97fc193Saliguori  * Run consistency checks on an image
1780e97fc193Saliguori  *
1781e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
1782a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
1783e076f338SKevin Wolf  * check are stored in res.
1784e97fc193Saliguori  */
17854534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
1786e97fc193Saliguori {
1787e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
1788e97fc193Saliguori         return -ENOTSUP;
1789e97fc193Saliguori     }
1790e97fc193Saliguori 
1791e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
17924534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
1793e97fc193Saliguori }
1794e97fc193Saliguori 
17958a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
17968a426614SKevin Wolf 
179733e3963eSbellard /* commit COW file into the raw image */
179833e3963eSbellard int bdrv_commit(BlockDriverState *bs)
179933e3963eSbellard {
180019cb3738Sbellard     BlockDriver *drv = bs->drv;
18018a426614SKevin Wolf     int64_t sector, total_sectors;
18028a426614SKevin Wolf     int n, ro, open_flags;
18030bce597dSJeff Cody     int ret = 0;
18048a426614SKevin Wolf     uint8_t *buf;
1805c2cba3d9SJim Meyering     char filename[PATH_MAX];
180633e3963eSbellard 
180719cb3738Sbellard     if (!drv)
180819cb3738Sbellard         return -ENOMEDIUM;
180933e3963eSbellard 
18104dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
18114dca4b63SNaphtali Sprei         return -ENOTSUP;
18124dca4b63SNaphtali Sprei     }
18134dca4b63SNaphtali Sprei 
18142d3735d3SStefan Hajnoczi     if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
18152d3735d3SStefan Hajnoczi         return -EBUSY;
18162d3735d3SStefan Hajnoczi     }
18172d3735d3SStefan Hajnoczi 
18184dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
1819c2cba3d9SJim Meyering     /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
1820c2cba3d9SJim Meyering     pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
18214dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
18224dca4b63SNaphtali Sprei 
18234dca4b63SNaphtali Sprei     if (ro) {
18240bce597dSJeff Cody         if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
18250bce597dSJeff Cody             return -EACCES;
18264dca4b63SNaphtali Sprei         }
1827ea2384d3Sbellard     }
1828ea2384d3Sbellard 
18296ea44308SJan Kiszka     total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
18307267c094SAnthony Liguori     buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
18318a426614SKevin Wolf 
18328a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
183305c4af54SStefan Hajnoczi         if (bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
18348a426614SKevin Wolf 
18358a426614SKevin Wolf             if (bdrv_read(bs, sector, buf, n) != 0) {
18364dca4b63SNaphtali Sprei                 ret = -EIO;
18374dca4b63SNaphtali Sprei                 goto ro_cleanup;
183833e3963eSbellard             }
183933e3963eSbellard 
18408a426614SKevin Wolf             if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
18414dca4b63SNaphtali Sprei                 ret = -EIO;
18424dca4b63SNaphtali Sprei                 goto ro_cleanup;
184333e3963eSbellard             }
184433e3963eSbellard         }
184533e3963eSbellard     }
184695389c86Sbellard 
18471d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
18481d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
18491d44952fSChristoph Hellwig         bdrv_flush(bs);
18501d44952fSChristoph Hellwig     }
185195389c86Sbellard 
18523f5075aeSChristoph Hellwig     /*
18533f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
18543f5075aeSChristoph Hellwig      * stable on disk.
18553f5075aeSChristoph Hellwig      */
18563f5075aeSChristoph Hellwig     if (bs->backing_hd)
18573f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
18584dca4b63SNaphtali Sprei 
18594dca4b63SNaphtali Sprei ro_cleanup:
18607267c094SAnthony Liguori     g_free(buf);
18614dca4b63SNaphtali Sprei 
18624dca4b63SNaphtali Sprei     if (ro) {
18630bce597dSJeff Cody         /* ignoring error return here */
18640bce597dSJeff Cody         bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
18654dca4b63SNaphtali Sprei     }
18664dca4b63SNaphtali Sprei 
18671d44952fSChristoph Hellwig     return ret;
186833e3963eSbellard }
186933e3963eSbellard 
1870e8877497SStefan Hajnoczi int bdrv_commit_all(void)
18716ab4b5abSMarkus Armbruster {
18726ab4b5abSMarkus Armbruster     BlockDriverState *bs;
18736ab4b5abSMarkus Armbruster 
18746ab4b5abSMarkus Armbruster     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1875272d2d8eSJeff Cody         if (bs->drv && bs->backing_hd) {
1876e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
1877e8877497SStefan Hajnoczi             if (ret < 0) {
1878e8877497SStefan Hajnoczi                 return ret;
18796ab4b5abSMarkus Armbruster             }
18806ab4b5abSMarkus Armbruster         }
1881272d2d8eSJeff Cody     }
1882e8877497SStefan Hajnoczi     return 0;
1883e8877497SStefan Hajnoczi }
18846ab4b5abSMarkus Armbruster 
1885dbffbdcfSStefan Hajnoczi /**
1886dbffbdcfSStefan Hajnoczi  * Remove an active request from the tracked requests list
1887dbffbdcfSStefan Hajnoczi  *
1888dbffbdcfSStefan Hajnoczi  * This function should be called when a tracked request is completing.
1889dbffbdcfSStefan Hajnoczi  */
1890dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req)
1891dbffbdcfSStefan Hajnoczi {
1892dbffbdcfSStefan Hajnoczi     QLIST_REMOVE(req, list);
1893f4658285SStefan Hajnoczi     qemu_co_queue_restart_all(&req->wait_queue);
1894dbffbdcfSStefan Hajnoczi }
1895dbffbdcfSStefan Hajnoczi 
1896dbffbdcfSStefan Hajnoczi /**
1897dbffbdcfSStefan Hajnoczi  * Add an active request to the tracked requests list
1898dbffbdcfSStefan Hajnoczi  */
1899dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req,
1900dbffbdcfSStefan Hajnoczi                                   BlockDriverState *bs,
1901dbffbdcfSStefan Hajnoczi                                   int64_t sector_num,
1902dbffbdcfSStefan Hajnoczi                                   int nb_sectors, bool is_write)
1903dbffbdcfSStefan Hajnoczi {
1904dbffbdcfSStefan Hajnoczi     *req = (BdrvTrackedRequest){
1905dbffbdcfSStefan Hajnoczi         .bs = bs,
1906dbffbdcfSStefan Hajnoczi         .sector_num = sector_num,
1907dbffbdcfSStefan Hajnoczi         .nb_sectors = nb_sectors,
1908dbffbdcfSStefan Hajnoczi         .is_write = is_write,
19095f8b6491SStefan Hajnoczi         .co = qemu_coroutine_self(),
1910dbffbdcfSStefan Hajnoczi     };
1911dbffbdcfSStefan Hajnoczi 
1912f4658285SStefan Hajnoczi     qemu_co_queue_init(&req->wait_queue);
1913f4658285SStefan Hajnoczi 
1914dbffbdcfSStefan Hajnoczi     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
1915dbffbdcfSStefan Hajnoczi }
1916dbffbdcfSStefan Hajnoczi 
1917d83947acSStefan Hajnoczi /**
1918d83947acSStefan Hajnoczi  * Round a region to cluster boundaries
1919d83947acSStefan Hajnoczi  */
1920343bded4SPaolo Bonzini void bdrv_round_to_clusters(BlockDriverState *bs,
1921d83947acSStefan Hajnoczi                             int64_t sector_num, int nb_sectors,
1922d83947acSStefan Hajnoczi                             int64_t *cluster_sector_num,
1923d83947acSStefan Hajnoczi                             int *cluster_nb_sectors)
1924d83947acSStefan Hajnoczi {
1925d83947acSStefan Hajnoczi     BlockDriverInfo bdi;
1926d83947acSStefan Hajnoczi 
1927d83947acSStefan Hajnoczi     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
1928d83947acSStefan Hajnoczi         *cluster_sector_num = sector_num;
1929d83947acSStefan Hajnoczi         *cluster_nb_sectors = nb_sectors;
1930d83947acSStefan Hajnoczi     } else {
1931d83947acSStefan Hajnoczi         int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
1932d83947acSStefan Hajnoczi         *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
1933d83947acSStefan Hajnoczi         *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
1934d83947acSStefan Hajnoczi                                             nb_sectors, c);
1935d83947acSStefan Hajnoczi     }
1936d83947acSStefan Hajnoczi }
1937d83947acSStefan Hajnoczi 
1938f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req,
1939f4658285SStefan Hajnoczi                                      int64_t sector_num, int nb_sectors) {
1940d83947acSStefan Hajnoczi     /*        aaaa   bbbb */
1941d83947acSStefan Hajnoczi     if (sector_num >= req->sector_num + req->nb_sectors) {
1942d83947acSStefan Hajnoczi         return false;
1943d83947acSStefan Hajnoczi     }
1944d83947acSStefan Hajnoczi     /* bbbb   aaaa        */
1945d83947acSStefan Hajnoczi     if (req->sector_num >= sector_num + nb_sectors) {
1946d83947acSStefan Hajnoczi         return false;
1947d83947acSStefan Hajnoczi     }
1948d83947acSStefan Hajnoczi     return true;
1949f4658285SStefan Hajnoczi }
1950f4658285SStefan Hajnoczi 
1951f4658285SStefan Hajnoczi static void coroutine_fn wait_for_overlapping_requests(BlockDriverState *bs,
1952f4658285SStefan Hajnoczi         int64_t sector_num, int nb_sectors)
1953f4658285SStefan Hajnoczi {
1954f4658285SStefan Hajnoczi     BdrvTrackedRequest *req;
1955d83947acSStefan Hajnoczi     int64_t cluster_sector_num;
1956d83947acSStefan Hajnoczi     int cluster_nb_sectors;
1957f4658285SStefan Hajnoczi     bool retry;
1958f4658285SStefan Hajnoczi 
1959d83947acSStefan Hajnoczi     /* If we touch the same cluster it counts as an overlap.  This guarantees
1960d83947acSStefan Hajnoczi      * that allocating writes will be serialized and not race with each other
1961d83947acSStefan Hajnoczi      * for the same cluster.  For example, in copy-on-read it ensures that the
1962d83947acSStefan Hajnoczi      * CoR read and write operations are atomic and guest writes cannot
1963d83947acSStefan Hajnoczi      * interleave between them.
1964d83947acSStefan Hajnoczi      */
1965343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
1966d83947acSStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
1967d83947acSStefan Hajnoczi 
1968f4658285SStefan Hajnoczi     do {
1969f4658285SStefan Hajnoczi         retry = false;
1970f4658285SStefan Hajnoczi         QLIST_FOREACH(req, &bs->tracked_requests, list) {
1971d83947acSStefan Hajnoczi             if (tracked_request_overlaps(req, cluster_sector_num,
1972d83947acSStefan Hajnoczi                                          cluster_nb_sectors)) {
19735f8b6491SStefan Hajnoczi                 /* Hitting this means there was a reentrant request, for
19745f8b6491SStefan Hajnoczi                  * example, a block driver issuing nested requests.  This must
19755f8b6491SStefan Hajnoczi                  * never happen since it means deadlock.
19765f8b6491SStefan Hajnoczi                  */
19775f8b6491SStefan Hajnoczi                 assert(qemu_coroutine_self() != req->co);
19785f8b6491SStefan Hajnoczi 
1979f4658285SStefan Hajnoczi                 qemu_co_queue_wait(&req->wait_queue);
1980f4658285SStefan Hajnoczi                 retry = true;
1981f4658285SStefan Hajnoczi                 break;
1982f4658285SStefan Hajnoczi             }
1983f4658285SStefan Hajnoczi         }
1984f4658285SStefan Hajnoczi     } while (retry);
1985f4658285SStefan Hajnoczi }
1986f4658285SStefan Hajnoczi 
1987756e6736SKevin Wolf /*
1988756e6736SKevin Wolf  * Return values:
1989756e6736SKevin Wolf  * 0        - success
1990756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
1991756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
1992756e6736SKevin Wolf  *            image file header
1993756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
1994756e6736SKevin Wolf  */
1995756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
1996756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
1997756e6736SKevin Wolf {
1998756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
1999469ef350SPaolo Bonzini     int ret;
2000756e6736SKevin Wolf 
20015f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
20025f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
20035f377794SPaolo Bonzini         return -EINVAL;
20045f377794SPaolo Bonzini     }
20055f377794SPaolo Bonzini 
2006756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2007469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2008756e6736SKevin Wolf     } else {
2009469ef350SPaolo Bonzini         ret = -ENOTSUP;
2010756e6736SKevin Wolf     }
2011469ef350SPaolo Bonzini 
2012469ef350SPaolo Bonzini     if (ret == 0) {
2013469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2014469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2015469ef350SPaolo Bonzini     }
2016469ef350SPaolo Bonzini     return ret;
2017756e6736SKevin Wolf }
2018756e6736SKevin Wolf 
20196ebdcee2SJeff Cody /*
20206ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
20216ebdcee2SJeff Cody  *
20226ebdcee2SJeff Cody  * active is the current topmost image.
20236ebdcee2SJeff Cody  *
20246ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
20256ebdcee2SJeff Cody  * or if active == bs.
20266ebdcee2SJeff Cody  */
20276ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
20286ebdcee2SJeff Cody                                     BlockDriverState *bs)
20296ebdcee2SJeff Cody {
20306ebdcee2SJeff Cody     BlockDriverState *overlay = NULL;
20316ebdcee2SJeff Cody     BlockDriverState *intermediate;
20326ebdcee2SJeff Cody 
20336ebdcee2SJeff Cody     assert(active != NULL);
20346ebdcee2SJeff Cody     assert(bs != NULL);
20356ebdcee2SJeff Cody 
20366ebdcee2SJeff Cody     /* if bs is the same as active, then by definition it has no overlay
20376ebdcee2SJeff Cody      */
20386ebdcee2SJeff Cody     if (active == bs) {
20396ebdcee2SJeff Cody         return NULL;
20406ebdcee2SJeff Cody     }
20416ebdcee2SJeff Cody 
20426ebdcee2SJeff Cody     intermediate = active;
20436ebdcee2SJeff Cody     while (intermediate->backing_hd) {
20446ebdcee2SJeff Cody         if (intermediate->backing_hd == bs) {
20456ebdcee2SJeff Cody             overlay = intermediate;
20466ebdcee2SJeff Cody             break;
20476ebdcee2SJeff Cody         }
20486ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
20496ebdcee2SJeff Cody     }
20506ebdcee2SJeff Cody 
20516ebdcee2SJeff Cody     return overlay;
20526ebdcee2SJeff Cody }
20536ebdcee2SJeff Cody 
20546ebdcee2SJeff Cody typedef struct BlkIntermediateStates {
20556ebdcee2SJeff Cody     BlockDriverState *bs;
20566ebdcee2SJeff Cody     QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
20576ebdcee2SJeff Cody } BlkIntermediateStates;
20586ebdcee2SJeff Cody 
20596ebdcee2SJeff Cody 
20606ebdcee2SJeff Cody /*
20616ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
20626ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
20636ebdcee2SJeff Cody  *
20646ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
20656ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
20666ebdcee2SJeff Cody  *
20676ebdcee2SJeff Cody  * E.g., this will convert the following chain:
20686ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
20696ebdcee2SJeff Cody  *
20706ebdcee2SJeff Cody  * to
20716ebdcee2SJeff Cody  *
20726ebdcee2SJeff Cody  * bottom <- base <- active
20736ebdcee2SJeff Cody  *
20746ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
20756ebdcee2SJeff Cody  *
20766ebdcee2SJeff Cody  * base <- intermediate <- top <- active
20776ebdcee2SJeff Cody  *
20786ebdcee2SJeff Cody  * to
20796ebdcee2SJeff Cody  *
20806ebdcee2SJeff Cody  * base <- active
20816ebdcee2SJeff Cody  *
20826ebdcee2SJeff Cody  * Error conditions:
20836ebdcee2SJeff Cody  *  if active == top, that is considered an error
20846ebdcee2SJeff Cody  *
20856ebdcee2SJeff Cody  */
20866ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
20876ebdcee2SJeff Cody                            BlockDriverState *base)
20886ebdcee2SJeff Cody {
20896ebdcee2SJeff Cody     BlockDriverState *intermediate;
20906ebdcee2SJeff Cody     BlockDriverState *base_bs = NULL;
20916ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
20926ebdcee2SJeff Cody     BlkIntermediateStates *intermediate_state, *next;
20936ebdcee2SJeff Cody     int ret = -EIO;
20946ebdcee2SJeff Cody 
20956ebdcee2SJeff Cody     QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
20966ebdcee2SJeff Cody     QSIMPLEQ_INIT(&states_to_delete);
20976ebdcee2SJeff Cody 
20986ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
20996ebdcee2SJeff Cody         goto exit;
21006ebdcee2SJeff Cody     }
21016ebdcee2SJeff Cody 
21026ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
21036ebdcee2SJeff Cody 
21046ebdcee2SJeff Cody     if (new_top_bs == NULL) {
21056ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
21066ebdcee2SJeff Cody         goto exit;
21076ebdcee2SJeff Cody     }
21086ebdcee2SJeff Cody 
21096ebdcee2SJeff Cody     /* special case of new_top_bs->backing_hd already pointing to base - nothing
21106ebdcee2SJeff Cody      * to do, no intermediate images */
21116ebdcee2SJeff Cody     if (new_top_bs->backing_hd == base) {
21126ebdcee2SJeff Cody         ret = 0;
21136ebdcee2SJeff Cody         goto exit;
21146ebdcee2SJeff Cody     }
21156ebdcee2SJeff Cody 
21166ebdcee2SJeff Cody     intermediate = top;
21176ebdcee2SJeff Cody 
21186ebdcee2SJeff Cody     /* now we will go down through the list, and add each BDS we find
21196ebdcee2SJeff Cody      * into our deletion queue, until we hit the 'base'
21206ebdcee2SJeff Cody      */
21216ebdcee2SJeff Cody     while (intermediate) {
21226ebdcee2SJeff Cody         intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
21236ebdcee2SJeff Cody         intermediate_state->bs = intermediate;
21246ebdcee2SJeff Cody         QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
21256ebdcee2SJeff Cody 
21266ebdcee2SJeff Cody         if (intermediate->backing_hd == base) {
21276ebdcee2SJeff Cody             base_bs = intermediate->backing_hd;
21286ebdcee2SJeff Cody             break;
21296ebdcee2SJeff Cody         }
21306ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
21316ebdcee2SJeff Cody     }
21326ebdcee2SJeff Cody     if (base_bs == NULL) {
21336ebdcee2SJeff Cody         /* something went wrong, we did not end at the base. safely
21346ebdcee2SJeff Cody          * unravel everything, and exit with error */
21356ebdcee2SJeff Cody         goto exit;
21366ebdcee2SJeff Cody     }
21376ebdcee2SJeff Cody 
21386ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
21396ebdcee2SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
21406ebdcee2SJeff Cody                                    base_bs->drv ? base_bs->drv->format_name : "");
21416ebdcee2SJeff Cody     if (ret) {
21426ebdcee2SJeff Cody         goto exit;
21436ebdcee2SJeff Cody     }
21446ebdcee2SJeff Cody     new_top_bs->backing_hd = base_bs;
21456ebdcee2SJeff Cody 
21466ebdcee2SJeff Cody 
21476ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
21486ebdcee2SJeff Cody         /* so that bdrv_close() does not recursively close the chain */
21496ebdcee2SJeff Cody         intermediate_state->bs->backing_hd = NULL;
21506ebdcee2SJeff Cody         bdrv_delete(intermediate_state->bs);
21516ebdcee2SJeff Cody     }
21526ebdcee2SJeff Cody     ret = 0;
21536ebdcee2SJeff Cody 
21546ebdcee2SJeff Cody exit:
21556ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
21566ebdcee2SJeff Cody         g_free(intermediate_state);
21576ebdcee2SJeff Cody     }
21586ebdcee2SJeff Cody     return ret;
21596ebdcee2SJeff Cody }
21606ebdcee2SJeff Cody 
21616ebdcee2SJeff Cody 
216271d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
216371d0770cSaliguori                                    size_t size)
216471d0770cSaliguori {
216571d0770cSaliguori     int64_t len;
216671d0770cSaliguori 
216771d0770cSaliguori     if (!bdrv_is_inserted(bs))
216871d0770cSaliguori         return -ENOMEDIUM;
216971d0770cSaliguori 
217071d0770cSaliguori     if (bs->growable)
217171d0770cSaliguori         return 0;
217271d0770cSaliguori 
217371d0770cSaliguori     len = bdrv_getlength(bs);
217471d0770cSaliguori 
2175fbb7b4e0SKevin Wolf     if (offset < 0)
2176fbb7b4e0SKevin Wolf         return -EIO;
2177fbb7b4e0SKevin Wolf 
2178fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
217971d0770cSaliguori         return -EIO;
218071d0770cSaliguori 
218171d0770cSaliguori     return 0;
218271d0770cSaliguori }
218371d0770cSaliguori 
218471d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
218571d0770cSaliguori                               int nb_sectors)
218671d0770cSaliguori {
2187eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
2188eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
218971d0770cSaliguori }
219071d0770cSaliguori 
21911c9805a3SStefan Hajnoczi typedef struct RwCo {
21921c9805a3SStefan Hajnoczi     BlockDriverState *bs;
21931c9805a3SStefan Hajnoczi     int64_t sector_num;
21941c9805a3SStefan Hajnoczi     int nb_sectors;
21951c9805a3SStefan Hajnoczi     QEMUIOVector *qiov;
21961c9805a3SStefan Hajnoczi     bool is_write;
21971c9805a3SStefan Hajnoczi     int ret;
21984105eaaaSPeter Lieven     BdrvRequestFlags flags;
21991c9805a3SStefan Hajnoczi } RwCo;
22001c9805a3SStefan Hajnoczi 
22011c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque)
2202fc01f7e7Sbellard {
22031c9805a3SStefan Hajnoczi     RwCo *rwco = opaque;
2204fc01f7e7Sbellard 
22051c9805a3SStefan Hajnoczi     if (!rwco->is_write) {
22061c9805a3SStefan Hajnoczi         rwco->ret = bdrv_co_do_readv(rwco->bs, rwco->sector_num,
22074105eaaaSPeter Lieven                                      rwco->nb_sectors, rwco->qiov,
22084105eaaaSPeter Lieven                                      rwco->flags);
22091c9805a3SStefan Hajnoczi     } else {
22101c9805a3SStefan Hajnoczi         rwco->ret = bdrv_co_do_writev(rwco->bs, rwco->sector_num,
22114105eaaaSPeter Lieven                                       rwco->nb_sectors, rwco->qiov,
22124105eaaaSPeter Lieven                                       rwco->flags);
22131c9805a3SStefan Hajnoczi     }
22141c9805a3SStefan Hajnoczi }
2215e7a8a783SKevin Wolf 
22161c9805a3SStefan Hajnoczi /*
22178d3b1a2dSKevin Wolf  * Process a vectored synchronous request using coroutines
22181c9805a3SStefan Hajnoczi  */
22198d3b1a2dSKevin Wolf static int bdrv_rwv_co(BlockDriverState *bs, int64_t sector_num,
22204105eaaaSPeter Lieven                        QEMUIOVector *qiov, bool is_write,
22214105eaaaSPeter Lieven                        BdrvRequestFlags flags)
22221c9805a3SStefan Hajnoczi {
22231c9805a3SStefan Hajnoczi     Coroutine *co;
22241c9805a3SStefan Hajnoczi     RwCo rwco = {
22251c9805a3SStefan Hajnoczi         .bs = bs,
22261c9805a3SStefan Hajnoczi         .sector_num = sector_num,
22278d3b1a2dSKevin Wolf         .nb_sectors = qiov->size >> BDRV_SECTOR_BITS,
22288d3b1a2dSKevin Wolf         .qiov = qiov,
22291c9805a3SStefan Hajnoczi         .is_write = is_write,
22301c9805a3SStefan Hajnoczi         .ret = NOT_DONE,
22314105eaaaSPeter Lieven         .flags = flags,
22321c9805a3SStefan Hajnoczi     };
22338d3b1a2dSKevin Wolf     assert((qiov->size & (BDRV_SECTOR_SIZE - 1)) == 0);
22341c9805a3SStefan Hajnoczi 
2235498e386cSZhi Yong Wu     /**
2236498e386cSZhi Yong Wu      * In sync call context, when the vcpu is blocked, this throttling timer
2237498e386cSZhi Yong Wu      * will not fire; so the I/O throttling function has to be disabled here
2238498e386cSZhi Yong Wu      * if it has been enabled.
2239498e386cSZhi Yong Wu      */
2240498e386cSZhi Yong Wu     if (bs->io_limits_enabled) {
2241498e386cSZhi Yong Wu         fprintf(stderr, "Disabling I/O throttling on '%s' due "
2242498e386cSZhi Yong Wu                         "to synchronous I/O.\n", bdrv_get_device_name(bs));
2243498e386cSZhi Yong Wu         bdrv_io_limits_disable(bs);
2244498e386cSZhi Yong Wu     }
2245498e386cSZhi Yong Wu 
22461c9805a3SStefan Hajnoczi     if (qemu_in_coroutine()) {
22471c9805a3SStefan Hajnoczi         /* Fast-path if already in coroutine context */
22481c9805a3SStefan Hajnoczi         bdrv_rw_co_entry(&rwco);
22491c9805a3SStefan Hajnoczi     } else {
22501c9805a3SStefan Hajnoczi         co = qemu_coroutine_create(bdrv_rw_co_entry);
22511c9805a3SStefan Hajnoczi         qemu_coroutine_enter(co, &rwco);
22521c9805a3SStefan Hajnoczi         while (rwco.ret == NOT_DONE) {
22531c9805a3SStefan Hajnoczi             qemu_aio_wait();
22541c9805a3SStefan Hajnoczi         }
22551c9805a3SStefan Hajnoczi     }
22561c9805a3SStefan Hajnoczi     return rwco.ret;
2257e7a8a783SKevin Wolf }
2258e7a8a783SKevin Wolf 
22598d3b1a2dSKevin Wolf /*
22608d3b1a2dSKevin Wolf  * Process a synchronous request using coroutines
22618d3b1a2dSKevin Wolf  */
22628d3b1a2dSKevin Wolf static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
22634105eaaaSPeter Lieven                       int nb_sectors, bool is_write, BdrvRequestFlags flags)
22648d3b1a2dSKevin Wolf {
22658d3b1a2dSKevin Wolf     QEMUIOVector qiov;
22668d3b1a2dSKevin Wolf     struct iovec iov = {
22678d3b1a2dSKevin Wolf         .iov_base = (void *)buf,
22688d3b1a2dSKevin Wolf         .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
22698d3b1a2dSKevin Wolf     };
22708d3b1a2dSKevin Wolf 
22718d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
22724105eaaaSPeter Lieven     return bdrv_rwv_co(bs, sector_num, &qiov, is_write, flags);
22738d3b1a2dSKevin Wolf }
22748d3b1a2dSKevin Wolf 
22751c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */
22761c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num,
22771c9805a3SStefan Hajnoczi               uint8_t *buf, int nb_sectors)
22781c9805a3SStefan Hajnoczi {
22794105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
228083f64091Sbellard }
2281fc01f7e7Sbellard 
228207d27a44SMarkus Armbruster /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
228307d27a44SMarkus Armbruster int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
228407d27a44SMarkus Armbruster                           uint8_t *buf, int nb_sectors)
228507d27a44SMarkus Armbruster {
228607d27a44SMarkus Armbruster     bool enabled;
228707d27a44SMarkus Armbruster     int ret;
228807d27a44SMarkus Armbruster 
228907d27a44SMarkus Armbruster     enabled = bs->io_limits_enabled;
229007d27a44SMarkus Armbruster     bs->io_limits_enabled = false;
22914e7395e8SPeter Lieven     ret = bdrv_read(bs, sector_num, buf, nb_sectors);
229207d27a44SMarkus Armbruster     bs->io_limits_enabled = enabled;
229307d27a44SMarkus Armbruster     return ret;
229407d27a44SMarkus Armbruster }
229507d27a44SMarkus Armbruster 
229619cb3738Sbellard /* Return < 0 if error. Important errors are:
229719cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
229819cb3738Sbellard   -ENOMEDIUM   No media inserted.
229919cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
230019cb3738Sbellard   -EACCES      Trying to write a read-only device
230119cb3738Sbellard */
2302fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
2303fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
2304fc01f7e7Sbellard {
23054105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
230683f64091Sbellard }
230783f64091Sbellard 
23088d3b1a2dSKevin Wolf int bdrv_writev(BlockDriverState *bs, int64_t sector_num, QEMUIOVector *qiov)
23098d3b1a2dSKevin Wolf {
23104105eaaaSPeter Lieven     return bdrv_rwv_co(bs, sector_num, qiov, true, 0);
23114105eaaaSPeter Lieven }
23124105eaaaSPeter Lieven 
23134105eaaaSPeter Lieven int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
23144105eaaaSPeter Lieven {
23154105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,
23164105eaaaSPeter Lieven                       BDRV_REQ_ZERO_WRITE);
23178d3b1a2dSKevin Wolf }
23188d3b1a2dSKevin Wolf 
2319eda578e5Saliguori int bdrv_pread(BlockDriverState *bs, int64_t offset,
2320eda578e5Saliguori                void *buf, int count1)
232183f64091Sbellard {
23226ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
232383f64091Sbellard     int len, nb_sectors, count;
232483f64091Sbellard     int64_t sector_num;
23259a8c4cceSKevin Wolf     int ret;
232683f64091Sbellard 
232783f64091Sbellard     count = count1;
232883f64091Sbellard     /* first read to align to sector start */
23296ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
233083f64091Sbellard     if (len > count)
233183f64091Sbellard         len = count;
23326ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
233383f64091Sbellard     if (len > 0) {
23349a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
23359a8c4cceSKevin Wolf             return ret;
23366ea44308SJan Kiszka         memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
233783f64091Sbellard         count -= len;
233883f64091Sbellard         if (count == 0)
233983f64091Sbellard             return count1;
234083f64091Sbellard         sector_num++;
234183f64091Sbellard         buf += len;
234283f64091Sbellard     }
234383f64091Sbellard 
234483f64091Sbellard     /* read the sectors "in place" */
23456ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
234683f64091Sbellard     if (nb_sectors > 0) {
23479a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
23489a8c4cceSKevin Wolf             return ret;
234983f64091Sbellard         sector_num += nb_sectors;
23506ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
235183f64091Sbellard         buf += len;
235283f64091Sbellard         count -= len;
235383f64091Sbellard     }
235483f64091Sbellard 
235583f64091Sbellard     /* add data from the last sector */
235683f64091Sbellard     if (count > 0) {
23579a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
23589a8c4cceSKevin Wolf             return ret;
235983f64091Sbellard         memcpy(buf, tmp_buf, count);
236083f64091Sbellard     }
236183f64091Sbellard     return count1;
236283f64091Sbellard }
236383f64091Sbellard 
23648d3b1a2dSKevin Wolf int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
236583f64091Sbellard {
23666ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
236783f64091Sbellard     int len, nb_sectors, count;
236883f64091Sbellard     int64_t sector_num;
23699a8c4cceSKevin Wolf     int ret;
237083f64091Sbellard 
23718d3b1a2dSKevin Wolf     count = qiov->size;
23728d3b1a2dSKevin Wolf 
237383f64091Sbellard     /* first write to align to sector start */
23746ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
237583f64091Sbellard     if (len > count)
237683f64091Sbellard         len = count;
23776ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
237883f64091Sbellard     if (len > 0) {
23799a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
23809a8c4cceSKevin Wolf             return ret;
23818d3b1a2dSKevin Wolf         qemu_iovec_to_buf(qiov, 0, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)),
23828d3b1a2dSKevin Wolf                           len);
23839a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
23849a8c4cceSKevin Wolf             return ret;
238583f64091Sbellard         count -= len;
238683f64091Sbellard         if (count == 0)
23878d3b1a2dSKevin Wolf             return qiov->size;
238883f64091Sbellard         sector_num++;
238983f64091Sbellard     }
239083f64091Sbellard 
239183f64091Sbellard     /* write the sectors "in place" */
23926ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
239383f64091Sbellard     if (nb_sectors > 0) {
23948d3b1a2dSKevin Wolf         QEMUIOVector qiov_inplace;
23958d3b1a2dSKevin Wolf 
23968d3b1a2dSKevin Wolf         qemu_iovec_init(&qiov_inplace, qiov->niov);
23978d3b1a2dSKevin Wolf         qemu_iovec_concat(&qiov_inplace, qiov, len,
23988d3b1a2dSKevin Wolf                           nb_sectors << BDRV_SECTOR_BITS);
23998d3b1a2dSKevin Wolf         ret = bdrv_writev(bs, sector_num, &qiov_inplace);
24008d3b1a2dSKevin Wolf         qemu_iovec_destroy(&qiov_inplace);
24018d3b1a2dSKevin Wolf         if (ret < 0) {
24029a8c4cceSKevin Wolf             return ret;
24038d3b1a2dSKevin Wolf         }
24048d3b1a2dSKevin Wolf 
240583f64091Sbellard         sector_num += nb_sectors;
24066ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
240783f64091Sbellard         count -= len;
240883f64091Sbellard     }
240983f64091Sbellard 
241083f64091Sbellard     /* add data from the last sector */
241183f64091Sbellard     if (count > 0) {
24129a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
24139a8c4cceSKevin Wolf             return ret;
24148d3b1a2dSKevin Wolf         qemu_iovec_to_buf(qiov, qiov->size - count, tmp_buf, count);
24159a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
24169a8c4cceSKevin Wolf             return ret;
241783f64091Sbellard     }
24188d3b1a2dSKevin Wolf     return qiov->size;
24198d3b1a2dSKevin Wolf }
24208d3b1a2dSKevin Wolf 
24218d3b1a2dSKevin Wolf int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
24228d3b1a2dSKevin Wolf                 const void *buf, int count1)
24238d3b1a2dSKevin Wolf {
24248d3b1a2dSKevin Wolf     QEMUIOVector qiov;
24258d3b1a2dSKevin Wolf     struct iovec iov = {
24268d3b1a2dSKevin Wolf         .iov_base   = (void *) buf,
24278d3b1a2dSKevin Wolf         .iov_len    = count1,
24288d3b1a2dSKevin Wolf     };
24298d3b1a2dSKevin Wolf 
24308d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
24318d3b1a2dSKevin Wolf     return bdrv_pwritev(bs, offset, &qiov);
243283f64091Sbellard }
243383f64091Sbellard 
2434f08145feSKevin Wolf /*
2435f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
2436f08145feSKevin Wolf  * request (acts as a barrier)
2437f08145feSKevin Wolf  *
2438f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
2439f08145feSKevin Wolf  */
2440f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2441f08145feSKevin Wolf     const void *buf, int count)
2442f08145feSKevin Wolf {
2443f08145feSKevin Wolf     int ret;
2444f08145feSKevin Wolf 
2445f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
2446f08145feSKevin Wolf     if (ret < 0) {
2447f08145feSKevin Wolf         return ret;
2448f08145feSKevin Wolf     }
2449f08145feSKevin Wolf 
2450f05fa4adSPaolo Bonzini     /* No flush needed for cache modes that already do it */
2451f05fa4adSPaolo Bonzini     if (bs->enable_write_cache) {
2452f08145feSKevin Wolf         bdrv_flush(bs);
2453f08145feSKevin Wolf     }
2454f08145feSKevin Wolf 
2455f08145feSKevin Wolf     return 0;
2456f08145feSKevin Wolf }
2457f08145feSKevin Wolf 
2458470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
2459ab185921SStefan Hajnoczi         int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2460ab185921SStefan Hajnoczi {
2461ab185921SStefan Hajnoczi     /* Perform I/O through a temporary buffer so that users who scribble over
2462ab185921SStefan Hajnoczi      * their read buffer while the operation is in progress do not end up
2463ab185921SStefan Hajnoczi      * modifying the image file.  This is critical for zero-copy guest I/O
2464ab185921SStefan Hajnoczi      * where anything might happen inside guest memory.
2465ab185921SStefan Hajnoczi      */
2466ab185921SStefan Hajnoczi     void *bounce_buffer;
2467ab185921SStefan Hajnoczi 
246879c053bdSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2469ab185921SStefan Hajnoczi     struct iovec iov;
2470ab185921SStefan Hajnoczi     QEMUIOVector bounce_qiov;
2471ab185921SStefan Hajnoczi     int64_t cluster_sector_num;
2472ab185921SStefan Hajnoczi     int cluster_nb_sectors;
2473ab185921SStefan Hajnoczi     size_t skip_bytes;
2474ab185921SStefan Hajnoczi     int ret;
2475ab185921SStefan Hajnoczi 
2476ab185921SStefan Hajnoczi     /* Cover entire cluster so no additional backing file I/O is required when
2477ab185921SStefan Hajnoczi      * allocating cluster in the image file.
2478ab185921SStefan Hajnoczi      */
2479343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2480ab185921SStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
2481ab185921SStefan Hajnoczi 
2482470c0504SStefan Hajnoczi     trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2483ab185921SStefan Hajnoczi                                    cluster_sector_num, cluster_nb_sectors);
2484ab185921SStefan Hajnoczi 
2485ab185921SStefan Hajnoczi     iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2486ab185921SStefan Hajnoczi     iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
2487ab185921SStefan Hajnoczi     qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2488ab185921SStefan Hajnoczi 
248979c053bdSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2490ab185921SStefan Hajnoczi                              &bounce_qiov);
2491ab185921SStefan Hajnoczi     if (ret < 0) {
2492ab185921SStefan Hajnoczi         goto err;
2493ab185921SStefan Hajnoczi     }
2494ab185921SStefan Hajnoczi 
249579c053bdSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes &&
249679c053bdSStefan Hajnoczi         buffer_is_zero(bounce_buffer, iov.iov_len)) {
2497621f0589SKevin Wolf         ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
249879c053bdSStefan Hajnoczi                                       cluster_nb_sectors);
249979c053bdSStefan Hajnoczi     } else {
2500f05fa4adSPaolo Bonzini         /* This does not change the data on the disk, it is not necessary
2501f05fa4adSPaolo Bonzini          * to flush even in cache=writethrough mode.
2502f05fa4adSPaolo Bonzini          */
250379c053bdSStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
2504ab185921SStefan Hajnoczi                                   &bounce_qiov);
250579c053bdSStefan Hajnoczi     }
250679c053bdSStefan Hajnoczi 
2507ab185921SStefan Hajnoczi     if (ret < 0) {
2508ab185921SStefan Hajnoczi         /* It might be okay to ignore write errors for guest requests.  If this
2509ab185921SStefan Hajnoczi          * is a deliberate copy-on-read then we don't want to ignore the error.
2510ab185921SStefan Hajnoczi          * Simply report it in all cases.
2511ab185921SStefan Hajnoczi          */
2512ab185921SStefan Hajnoczi         goto err;
2513ab185921SStefan Hajnoczi     }
2514ab185921SStefan Hajnoczi 
2515ab185921SStefan Hajnoczi     skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
251603396148SMichael Tokarev     qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
2517ab185921SStefan Hajnoczi                         nb_sectors * BDRV_SECTOR_SIZE);
2518ab185921SStefan Hajnoczi 
2519ab185921SStefan Hajnoczi err:
2520ab185921SStefan Hajnoczi     qemu_vfree(bounce_buffer);
2521ab185921SStefan Hajnoczi     return ret;
2522ab185921SStefan Hajnoczi }
2523ab185921SStefan Hajnoczi 
2524c5fbe571SStefan Hajnoczi /*
2525c5fbe571SStefan Hajnoczi  * Handle a read request in coroutine context
2526c5fbe571SStefan Hajnoczi  */
2527c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
2528470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2529470c0504SStefan Hajnoczi     BdrvRequestFlags flags)
2530da1fa91dSKevin Wolf {
2531da1fa91dSKevin Wolf     BlockDriver *drv = bs->drv;
2532dbffbdcfSStefan Hajnoczi     BdrvTrackedRequest req;
2533dbffbdcfSStefan Hajnoczi     int ret;
2534da1fa91dSKevin Wolf 
2535da1fa91dSKevin Wolf     if (!drv) {
2536da1fa91dSKevin Wolf         return -ENOMEDIUM;
2537da1fa91dSKevin Wolf     }
2538da1fa91dSKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2539da1fa91dSKevin Wolf         return -EIO;
2540da1fa91dSKevin Wolf     }
2541da1fa91dSKevin Wolf 
254298f90dbaSZhi Yong Wu     /* throttling disk read I/O */
254398f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
254498f90dbaSZhi Yong Wu         bdrv_io_limits_intercept(bs, false, nb_sectors);
254598f90dbaSZhi Yong Wu     }
254698f90dbaSZhi Yong Wu 
2547f4658285SStefan Hajnoczi     if (bs->copy_on_read) {
2548470c0504SStefan Hajnoczi         flags |= BDRV_REQ_COPY_ON_READ;
2549470c0504SStefan Hajnoczi     }
2550470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2551470c0504SStefan Hajnoczi         bs->copy_on_read_in_flight++;
2552470c0504SStefan Hajnoczi     }
2553470c0504SStefan Hajnoczi 
2554470c0504SStefan Hajnoczi     if (bs->copy_on_read_in_flight) {
2555f4658285SStefan Hajnoczi         wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2556f4658285SStefan Hajnoczi     }
2557f4658285SStefan Hajnoczi 
2558dbffbdcfSStefan Hajnoczi     tracked_request_begin(&req, bs, sector_num, nb_sectors, false);
2559ab185921SStefan Hajnoczi 
2560470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2561ab185921SStefan Hajnoczi         int pnum;
2562ab185921SStefan Hajnoczi 
2563ab185921SStefan Hajnoczi         ret = bdrv_co_is_allocated(bs, sector_num, nb_sectors, &pnum);
2564ab185921SStefan Hajnoczi         if (ret < 0) {
2565ab185921SStefan Hajnoczi             goto out;
2566ab185921SStefan Hajnoczi         }
2567ab185921SStefan Hajnoczi 
2568ab185921SStefan Hajnoczi         if (!ret || pnum != nb_sectors) {
2569470c0504SStefan Hajnoczi             ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
2570ab185921SStefan Hajnoczi             goto out;
2571ab185921SStefan Hajnoczi         }
2572ab185921SStefan Hajnoczi     }
2573ab185921SStefan Hajnoczi 
2574*893a8f62SMORITA Kazutaka     if (!(bs->zero_beyond_eof && bs->growable)) {
2575dbffbdcfSStefan Hajnoczi         ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
2576*893a8f62SMORITA Kazutaka     } else {
2577*893a8f62SMORITA Kazutaka         /* Read zeros after EOF of growable BDSes */
2578*893a8f62SMORITA Kazutaka         int64_t len, total_sectors, max_nb_sectors;
2579*893a8f62SMORITA Kazutaka 
2580*893a8f62SMORITA Kazutaka         len = bdrv_getlength(bs);
2581*893a8f62SMORITA Kazutaka         if (len < 0) {
2582*893a8f62SMORITA Kazutaka             ret = len;
2583*893a8f62SMORITA Kazutaka             goto out;
2584*893a8f62SMORITA Kazutaka         }
2585*893a8f62SMORITA Kazutaka 
2586*893a8f62SMORITA Kazutaka         total_sectors = len >> BDRV_SECTOR_BITS;
2587*893a8f62SMORITA Kazutaka         max_nb_sectors = MAX(0, total_sectors - sector_num);
2588*893a8f62SMORITA Kazutaka         if (max_nb_sectors > 0) {
2589*893a8f62SMORITA Kazutaka             ret = drv->bdrv_co_readv(bs, sector_num,
2590*893a8f62SMORITA Kazutaka                                      MIN(nb_sectors, max_nb_sectors), qiov);
2591*893a8f62SMORITA Kazutaka         } else {
2592*893a8f62SMORITA Kazutaka             ret = 0;
2593*893a8f62SMORITA Kazutaka         }
2594*893a8f62SMORITA Kazutaka 
2595*893a8f62SMORITA Kazutaka         /* Reading beyond end of file is supposed to produce zeroes */
2596*893a8f62SMORITA Kazutaka         if (ret == 0 && total_sectors < sector_num + nb_sectors) {
2597*893a8f62SMORITA Kazutaka             uint64_t offset = MAX(0, total_sectors - sector_num);
2598*893a8f62SMORITA Kazutaka             uint64_t bytes = (sector_num + nb_sectors - offset) *
2599*893a8f62SMORITA Kazutaka                               BDRV_SECTOR_SIZE;
2600*893a8f62SMORITA Kazutaka             qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
2601*893a8f62SMORITA Kazutaka         }
2602*893a8f62SMORITA Kazutaka     }
2603ab185921SStefan Hajnoczi 
2604ab185921SStefan Hajnoczi out:
2605dbffbdcfSStefan Hajnoczi     tracked_request_end(&req);
2606470c0504SStefan Hajnoczi 
2607470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2608470c0504SStefan Hajnoczi         bs->copy_on_read_in_flight--;
2609470c0504SStefan Hajnoczi     }
2610470c0504SStefan Hajnoczi 
2611dbffbdcfSStefan Hajnoczi     return ret;
2612da1fa91dSKevin Wolf }
2613da1fa91dSKevin Wolf 
2614c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
2615da1fa91dSKevin Wolf     int nb_sectors, QEMUIOVector *qiov)
2616da1fa91dSKevin Wolf {
2617c5fbe571SStefan Hajnoczi     trace_bdrv_co_readv(bs, sector_num, nb_sectors);
2618da1fa91dSKevin Wolf 
2619470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
2620470c0504SStefan Hajnoczi }
2621470c0504SStefan Hajnoczi 
2622470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
2623470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2624470c0504SStefan Hajnoczi {
2625470c0504SStefan Hajnoczi     trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
2626470c0504SStefan Hajnoczi 
2627470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
2628470c0504SStefan Hajnoczi                             BDRV_REQ_COPY_ON_READ);
2629c5fbe571SStefan Hajnoczi }
2630c5fbe571SStefan Hajnoczi 
2631f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
2632f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors)
2633f08f2ddaSStefan Hajnoczi {
2634f08f2ddaSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2635f08f2ddaSStefan Hajnoczi     QEMUIOVector qiov;
2636f08f2ddaSStefan Hajnoczi     struct iovec iov;
2637f08f2ddaSStefan Hajnoczi     int ret;
2638f08f2ddaSStefan Hajnoczi 
2639621f0589SKevin Wolf     /* TODO Emulate only part of misaligned requests instead of letting block
2640621f0589SKevin Wolf      * drivers return -ENOTSUP and emulate everything */
2641621f0589SKevin Wolf 
2642f08f2ddaSStefan Hajnoczi     /* First try the efficient write zeroes operation */
2643f08f2ddaSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes) {
2644621f0589SKevin Wolf         ret = drv->bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2645621f0589SKevin Wolf         if (ret != -ENOTSUP) {
2646621f0589SKevin Wolf             return ret;
2647621f0589SKevin Wolf         }
2648f08f2ddaSStefan Hajnoczi     }
2649f08f2ddaSStefan Hajnoczi 
2650f08f2ddaSStefan Hajnoczi     /* Fall back to bounce buffer if write zeroes is unsupported */
2651f08f2ddaSStefan Hajnoczi     iov.iov_len  = nb_sectors * BDRV_SECTOR_SIZE;
2652f08f2ddaSStefan Hajnoczi     iov.iov_base = qemu_blockalign(bs, iov.iov_len);
2653f08f2ddaSStefan Hajnoczi     memset(iov.iov_base, 0, iov.iov_len);
2654f08f2ddaSStefan Hajnoczi     qemu_iovec_init_external(&qiov, &iov, 1);
2655f08f2ddaSStefan Hajnoczi 
2656f08f2ddaSStefan Hajnoczi     ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
2657f08f2ddaSStefan Hajnoczi 
2658f08f2ddaSStefan Hajnoczi     qemu_vfree(iov.iov_base);
2659f08f2ddaSStefan Hajnoczi     return ret;
2660f08f2ddaSStefan Hajnoczi }
2661f08f2ddaSStefan Hajnoczi 
2662c5fbe571SStefan Hajnoczi /*
2663c5fbe571SStefan Hajnoczi  * Handle a write request in coroutine context
2664c5fbe571SStefan Hajnoczi  */
2665c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
2666f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2667f08f2ddaSStefan Hajnoczi     BdrvRequestFlags flags)
2668c5fbe571SStefan Hajnoczi {
2669c5fbe571SStefan Hajnoczi     BlockDriver *drv = bs->drv;
2670dbffbdcfSStefan Hajnoczi     BdrvTrackedRequest req;
26716b7cb247SStefan Hajnoczi     int ret;
2672da1fa91dSKevin Wolf 
2673da1fa91dSKevin Wolf     if (!bs->drv) {
2674da1fa91dSKevin Wolf         return -ENOMEDIUM;
2675da1fa91dSKevin Wolf     }
2676da1fa91dSKevin Wolf     if (bs->read_only) {
2677da1fa91dSKevin Wolf         return -EACCES;
2678da1fa91dSKevin Wolf     }
2679da1fa91dSKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2680da1fa91dSKevin Wolf         return -EIO;
2681da1fa91dSKevin Wolf     }
2682da1fa91dSKevin Wolf 
268398f90dbaSZhi Yong Wu     /* throttling disk write I/O */
268498f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
268598f90dbaSZhi Yong Wu         bdrv_io_limits_intercept(bs, true, nb_sectors);
268698f90dbaSZhi Yong Wu     }
268798f90dbaSZhi Yong Wu 
2688470c0504SStefan Hajnoczi     if (bs->copy_on_read_in_flight) {
2689f4658285SStefan Hajnoczi         wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2690f4658285SStefan Hajnoczi     }
2691f4658285SStefan Hajnoczi 
2692dbffbdcfSStefan Hajnoczi     tracked_request_begin(&req, bs, sector_num, nb_sectors, true);
2693dbffbdcfSStefan Hajnoczi 
2694d616b224SStefan Hajnoczi     ret = notifier_with_return_list_notify(&bs->before_write_notifiers, &req);
2695d616b224SStefan Hajnoczi 
2696d616b224SStefan Hajnoczi     if (ret < 0) {
2697d616b224SStefan Hajnoczi         /* Do nothing, write notifier decided to fail this request */
2698d616b224SStefan Hajnoczi     } else if (flags & BDRV_REQ_ZERO_WRITE) {
2699f08f2ddaSStefan Hajnoczi         ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors);
2700f08f2ddaSStefan Hajnoczi     } else {
27016b7cb247SStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
2702f08f2ddaSStefan Hajnoczi     }
27036b7cb247SStefan Hajnoczi 
2704f05fa4adSPaolo Bonzini     if (ret == 0 && !bs->enable_write_cache) {
2705f05fa4adSPaolo Bonzini         ret = bdrv_co_flush(bs);
2706f05fa4adSPaolo Bonzini     }
2707f05fa4adSPaolo Bonzini 
2708da1fa91dSKevin Wolf     if (bs->dirty_bitmap) {
27091755da16SPaolo Bonzini         bdrv_set_dirty(bs, sector_num, nb_sectors);
2710da1fa91dSKevin Wolf     }
2711da1fa91dSKevin Wolf 
2712da1fa91dSKevin Wolf     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2713da1fa91dSKevin Wolf         bs->wr_highest_sector = sector_num + nb_sectors - 1;
2714da1fa91dSKevin Wolf     }
2715da1fa91dSKevin Wolf 
2716dbffbdcfSStefan Hajnoczi     tracked_request_end(&req);
2717dbffbdcfSStefan Hajnoczi 
27186b7cb247SStefan Hajnoczi     return ret;
2719da1fa91dSKevin Wolf }
2720da1fa91dSKevin Wolf 
2721c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
2722c5fbe571SStefan Hajnoczi     int nb_sectors, QEMUIOVector *qiov)
2723c5fbe571SStefan Hajnoczi {
2724c5fbe571SStefan Hajnoczi     trace_bdrv_co_writev(bs, sector_num, nb_sectors);
2725c5fbe571SStefan Hajnoczi 
2726f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
2727f08f2ddaSStefan Hajnoczi }
2728f08f2ddaSStefan Hajnoczi 
2729f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
2730f08f2ddaSStefan Hajnoczi                                       int64_t sector_num, int nb_sectors)
2731f08f2ddaSStefan Hajnoczi {
2732f08f2ddaSStefan Hajnoczi     trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2733f08f2ddaSStefan Hajnoczi 
2734f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
2735f08f2ddaSStefan Hajnoczi                              BDRV_REQ_ZERO_WRITE);
2736c5fbe571SStefan Hajnoczi }
2737c5fbe571SStefan Hajnoczi 
273883f64091Sbellard /**
273983f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
274083f64091Sbellard  */
274183f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
274283f64091Sbellard {
274383f64091Sbellard     BlockDriver *drv = bs->drv;
274451762288SStefan Hajnoczi     int ret;
274583f64091Sbellard     if (!drv)
274619cb3738Sbellard         return -ENOMEDIUM;
274783f64091Sbellard     if (!drv->bdrv_truncate)
274883f64091Sbellard         return -ENOTSUP;
274959f2689dSNaphtali Sprei     if (bs->read_only)
275059f2689dSNaphtali Sprei         return -EACCES;
27518591675fSMarcelo Tosatti     if (bdrv_in_use(bs))
27528591675fSMarcelo Tosatti         return -EBUSY;
275351762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
275451762288SStefan Hajnoczi     if (ret == 0) {
275551762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2756145feb17SMarkus Armbruster         bdrv_dev_resize_cb(bs);
275751762288SStefan Hajnoczi     }
275851762288SStefan Hajnoczi     return ret;
275983f64091Sbellard }
276083f64091Sbellard 
276183f64091Sbellard /**
27624a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
27634a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
27644a1d5e1fSFam Zheng  */
27654a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
27664a1d5e1fSFam Zheng {
27674a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
27684a1d5e1fSFam Zheng     if (!drv) {
27694a1d5e1fSFam Zheng         return -ENOMEDIUM;
27704a1d5e1fSFam Zheng     }
27714a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
27724a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
27734a1d5e1fSFam Zheng     }
27744a1d5e1fSFam Zheng     if (bs->file) {
27754a1d5e1fSFam Zheng         return bdrv_get_allocated_file_size(bs->file);
27764a1d5e1fSFam Zheng     }
27774a1d5e1fSFam Zheng     return -ENOTSUP;
27784a1d5e1fSFam Zheng }
27794a1d5e1fSFam Zheng 
27804a1d5e1fSFam Zheng /**
278183f64091Sbellard  * Length of a file in bytes. Return < 0 if error or unknown.
278283f64091Sbellard  */
278383f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs)
278483f64091Sbellard {
278583f64091Sbellard     BlockDriver *drv = bs->drv;
278683f64091Sbellard     if (!drv)
278719cb3738Sbellard         return -ENOMEDIUM;
278851762288SStefan Hajnoczi 
27892c6942faSMarkus Armbruster     if (bs->growable || bdrv_dev_has_removable_media(bs)) {
279046a4e4e6SStefan Hajnoczi         if (drv->bdrv_getlength) {
279183f64091Sbellard             return drv->bdrv_getlength(bs);
2792fc01f7e7Sbellard         }
279346a4e4e6SStefan Hajnoczi     }
279446a4e4e6SStefan Hajnoczi     return bs->total_sectors * BDRV_SECTOR_SIZE;
279546a4e4e6SStefan Hajnoczi }
2796fc01f7e7Sbellard 
279719cb3738Sbellard /* return 0 as number of sectors if no device present or error */
279896b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2799fc01f7e7Sbellard {
280019cb3738Sbellard     int64_t length;
280119cb3738Sbellard     length = bdrv_getlength(bs);
280219cb3738Sbellard     if (length < 0)
280319cb3738Sbellard         length = 0;
280419cb3738Sbellard     else
28056ea44308SJan Kiszka         length = length >> BDRV_SECTOR_BITS;
280619cb3738Sbellard     *nb_sectors_ptr = length;
2807fc01f7e7Sbellard }
2808cf98951bSbellard 
28090563e191SZhi Yong Wu /* throttling disk io limits */
28100563e191SZhi Yong Wu void bdrv_set_io_limits(BlockDriverState *bs,
28110563e191SZhi Yong Wu                         BlockIOLimit *io_limits)
28120563e191SZhi Yong Wu {
28130563e191SZhi Yong Wu     bs->io_limits = *io_limits;
28140563e191SZhi Yong Wu     bs->io_limits_enabled = bdrv_io_limits_enabled(bs);
28150563e191SZhi Yong Wu }
28160563e191SZhi Yong Wu 
2817ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
2818ff06f5f3SPaolo Bonzini                        BlockdevOnError on_write_error)
2819abd7f68dSMarkus Armbruster {
2820abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
2821abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
2822abd7f68dSMarkus Armbruster }
2823abd7f68dSMarkus Armbruster 
28241ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
2825abd7f68dSMarkus Armbruster {
2826abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
2827abd7f68dSMarkus Armbruster }
2828abd7f68dSMarkus Armbruster 
28293e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
28303e1caa5fSPaolo Bonzini {
28313e1caa5fSPaolo Bonzini     BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
28323e1caa5fSPaolo Bonzini 
28333e1caa5fSPaolo Bonzini     switch (on_err) {
28343e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_ENOSPC:
28353e1caa5fSPaolo Bonzini         return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT;
28363e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_STOP:
28373e1caa5fSPaolo Bonzini         return BDRV_ACTION_STOP;
28383e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_REPORT:
28393e1caa5fSPaolo Bonzini         return BDRV_ACTION_REPORT;
28403e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_IGNORE:
28413e1caa5fSPaolo Bonzini         return BDRV_ACTION_IGNORE;
28423e1caa5fSPaolo Bonzini     default:
28433e1caa5fSPaolo Bonzini         abort();
28443e1caa5fSPaolo Bonzini     }
28453e1caa5fSPaolo Bonzini }
28463e1caa5fSPaolo Bonzini 
28473e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows
28483e1caa5fSPaolo Bonzini  * about the error, it does not know whether an operation comes from
28493e1caa5fSPaolo Bonzini  * the device or the block layer (from a job, for example).
28503e1caa5fSPaolo Bonzini  */
28513e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
28523e1caa5fSPaolo Bonzini                        bool is_read, int error)
28533e1caa5fSPaolo Bonzini {
28543e1caa5fSPaolo Bonzini     assert(error >= 0);
285532c81a4aSPaolo Bonzini     bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);
28563e1caa5fSPaolo Bonzini     if (action == BDRV_ACTION_STOP) {
28573e1caa5fSPaolo Bonzini         vm_stop(RUN_STATE_IO_ERROR);
28583e1caa5fSPaolo Bonzini         bdrv_iostatus_set_err(bs, error);
28593e1caa5fSPaolo Bonzini     }
28603e1caa5fSPaolo Bonzini }
28613e1caa5fSPaolo Bonzini 
2862b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2863b338082bSbellard {
2864b338082bSbellard     return bs->read_only;
2865b338082bSbellard }
2866b338082bSbellard 
2867985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2868985a03b0Sths {
2869985a03b0Sths     return bs->sg;
2870985a03b0Sths }
2871985a03b0Sths 
2872e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
2873e900a7b7SChristoph Hellwig {
2874e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
2875e900a7b7SChristoph Hellwig }
2876e900a7b7SChristoph Hellwig 
2877425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2878425b0148SPaolo Bonzini {
2879425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
288055b110f2SJeff Cody 
288155b110f2SJeff Cody     /* so a reopen() will preserve wce */
288255b110f2SJeff Cody     if (wce) {
288355b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
288455b110f2SJeff Cody     } else {
288555b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
288655b110f2SJeff Cody     }
2887425b0148SPaolo Bonzini }
2888425b0148SPaolo Bonzini 
2889ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2890ea2384d3Sbellard {
2891ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
2892ea2384d3Sbellard         return 1;
2893ea2384d3Sbellard     return bs->encrypted;
2894ea2384d3Sbellard }
2895ea2384d3Sbellard 
2896c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2897c0f4ce77Saliguori {
2898c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
2899c0f4ce77Saliguori 
2900c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
2901c0f4ce77Saliguori         return 1;
2902c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2903c0f4ce77Saliguori }
2904c0f4ce77Saliguori 
2905ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2906ea2384d3Sbellard {
2907ea2384d3Sbellard     int ret;
2908ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
2909ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
2910ea2384d3Sbellard         if (ret < 0)
2911ea2384d3Sbellard             return ret;
2912ea2384d3Sbellard         if (!bs->encrypted)
2913ea2384d3Sbellard             return 0;
2914ea2384d3Sbellard     }
2915fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2916fd04a2aeSShahar Havivi         return -EINVAL;
2917fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2918fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2919fd04a2aeSShahar Havivi     }
2920c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2921bb5fc20fSaliguori     if (ret < 0) {
2922bb5fc20fSaliguori         bs->valid_key = 0;
2923bb5fc20fSaliguori     } else if (!bs->valid_key) {
2924bb5fc20fSaliguori         bs->valid_key = 1;
2925bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
29267d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
2927bb5fc20fSaliguori     }
2928c0f4ce77Saliguori     return ret;
2929ea2384d3Sbellard }
2930ea2384d3Sbellard 
2931f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
2932ea2384d3Sbellard {
2933f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
2934ea2384d3Sbellard }
2935ea2384d3Sbellard 
2936ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2937ea2384d3Sbellard                          void *opaque)
2938ea2384d3Sbellard {
2939ea2384d3Sbellard     BlockDriver *drv;
2940ea2384d3Sbellard 
29418a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2942ea2384d3Sbellard         it(opaque, drv->format_name);
2943ea2384d3Sbellard     }
2944ea2384d3Sbellard }
2945ea2384d3Sbellard 
2946b338082bSbellard BlockDriverState *bdrv_find(const char *name)
2947b338082bSbellard {
2948b338082bSbellard     BlockDriverState *bs;
2949b338082bSbellard 
29501b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
29511b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
2952b338082bSbellard             return bs;
2953b338082bSbellard         }
29541b7bdbc1SStefan Hajnoczi     }
2955b338082bSbellard     return NULL;
2956b338082bSbellard }
2957b338082bSbellard 
29582f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
29592f399b0aSMarkus Armbruster {
29602f399b0aSMarkus Armbruster     if (!bs) {
29612f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
29622f399b0aSMarkus Armbruster     }
29632f399b0aSMarkus Armbruster     return QTAILQ_NEXT(bs, list);
29642f399b0aSMarkus Armbruster }
29652f399b0aSMarkus Armbruster 
296651de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
296781d0912dSbellard {
296881d0912dSbellard     BlockDriverState *bs;
296981d0912dSbellard 
29701b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
297151de9760Saliguori         it(opaque, bs);
297281d0912dSbellard     }
297381d0912dSbellard }
297481d0912dSbellard 
2975ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
2976ea2384d3Sbellard {
2977ea2384d3Sbellard     return bs->device_name;
2978ea2384d3Sbellard }
2979ea2384d3Sbellard 
2980c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
2981c8433287SMarkus Armbruster {
2982c8433287SMarkus Armbruster     return bs->open_flags;
2983c8433287SMarkus Armbruster }
2984c8433287SMarkus Armbruster 
2985f0f0fdfeSKevin Wolf int bdrv_flush_all(void)
2986c6ca28d6Saliguori {
2987c6ca28d6Saliguori     BlockDriverState *bs;
2988f0f0fdfeSKevin Wolf     int result = 0;
2989c6ca28d6Saliguori 
29901b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
2991f0f0fdfeSKevin Wolf         int ret = bdrv_flush(bs);
2992f0f0fdfeSKevin Wolf         if (ret < 0 && !result) {
2993f0f0fdfeSKevin Wolf             result = ret;
2994c6ca28d6Saliguori         }
29951b7bdbc1SStefan Hajnoczi     }
2996c6ca28d6Saliguori 
2997f0f0fdfeSKevin Wolf     return result;
2998f0f0fdfeSKevin Wolf }
2999f0f0fdfeSKevin Wolf 
30003ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
30013ac21627SPeter Lieven {
30023ac21627SPeter Lieven     return 1;
30033ac21627SPeter Lieven }
30043ac21627SPeter Lieven 
3005f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
3006f2feebbdSKevin Wolf {
3007f2feebbdSKevin Wolf     assert(bs->drv);
3008f2feebbdSKevin Wolf 
3009336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
3010336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
3011f2feebbdSKevin Wolf     }
3012f2feebbdSKevin Wolf 
30133ac21627SPeter Lieven     /* safe default */
30143ac21627SPeter Lieven     return 0;
3015f2feebbdSKevin Wolf }
3016f2feebbdSKevin Wolf 
3017376ae3f1SStefan Hajnoczi typedef struct BdrvCoIsAllocatedData {
3018376ae3f1SStefan Hajnoczi     BlockDriverState *bs;
3019b35b2bbaSMiroslav Rezanina     BlockDriverState *base;
3020376ae3f1SStefan Hajnoczi     int64_t sector_num;
3021376ae3f1SStefan Hajnoczi     int nb_sectors;
3022376ae3f1SStefan Hajnoczi     int *pnum;
3023376ae3f1SStefan Hajnoczi     int ret;
3024376ae3f1SStefan Hajnoczi     bool done;
3025376ae3f1SStefan Hajnoczi } BdrvCoIsAllocatedData;
3026376ae3f1SStefan Hajnoczi 
3027f58c7b35Sths /*
3028f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
3029f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
3030f58c7b35Sths  * hence all their sectors are reported as allocated.
3031f58c7b35Sths  *
3032bd9533e3SStefan Hajnoczi  * If 'sector_num' is beyond the end of the disk image the return value is 0
3033bd9533e3SStefan Hajnoczi  * and 'pnum' is set to 0.
3034bd9533e3SStefan Hajnoczi  *
3035f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
3036f58c7b35Sths  * the specified sector) that are known to be in the same
3037f58c7b35Sths  * allocated/unallocated state.
3038f58c7b35Sths  *
3039bd9533e3SStefan Hajnoczi  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
3040bd9533e3SStefan Hajnoczi  * beyond the end of the disk image it will be clamped.
3041f58c7b35Sths  */
3042060f51c9SStefan Hajnoczi int coroutine_fn bdrv_co_is_allocated(BlockDriverState *bs, int64_t sector_num,
3043060f51c9SStefan Hajnoczi                                       int nb_sectors, int *pnum)
3044f58c7b35Sths {
3045f58c7b35Sths     int64_t n;
3046bd9533e3SStefan Hajnoczi 
30476aebab14SStefan Hajnoczi     if (sector_num >= bs->total_sectors) {
30486aebab14SStefan Hajnoczi         *pnum = 0;
30496aebab14SStefan Hajnoczi         return 0;
30506aebab14SStefan Hajnoczi     }
3051bd9533e3SStefan Hajnoczi 
30526aebab14SStefan Hajnoczi     n = bs->total_sectors - sector_num;
3053bd9533e3SStefan Hajnoczi     if (n < nb_sectors) {
3054bd9533e3SStefan Hajnoczi         nb_sectors = n;
3055bd9533e3SStefan Hajnoczi     }
3056bd9533e3SStefan Hajnoczi 
3057bd9533e3SStefan Hajnoczi     if (!bs->drv->bdrv_co_is_allocated) {
3058bd9533e3SStefan Hajnoczi         *pnum = nb_sectors;
30596aebab14SStefan Hajnoczi         return 1;
30606aebab14SStefan Hajnoczi     }
30616aebab14SStefan Hajnoczi 
3062060f51c9SStefan Hajnoczi     return bs->drv->bdrv_co_is_allocated(bs, sector_num, nb_sectors, pnum);
3063060f51c9SStefan Hajnoczi }
3064060f51c9SStefan Hajnoczi 
3065060f51c9SStefan Hajnoczi /* Coroutine wrapper for bdrv_is_allocated() */
3066060f51c9SStefan Hajnoczi static void coroutine_fn bdrv_is_allocated_co_entry(void *opaque)
3067060f51c9SStefan Hajnoczi {
3068060f51c9SStefan Hajnoczi     BdrvCoIsAllocatedData *data = opaque;
3069060f51c9SStefan Hajnoczi     BlockDriverState *bs = data->bs;
3070060f51c9SStefan Hajnoczi 
3071060f51c9SStefan Hajnoczi     data->ret = bdrv_co_is_allocated(bs, data->sector_num, data->nb_sectors,
3072060f51c9SStefan Hajnoczi                                      data->pnum);
3073060f51c9SStefan Hajnoczi     data->done = true;
3074060f51c9SStefan Hajnoczi }
3075060f51c9SStefan Hajnoczi 
3076060f51c9SStefan Hajnoczi /*
3077060f51c9SStefan Hajnoczi  * Synchronous wrapper around bdrv_co_is_allocated().
3078060f51c9SStefan Hajnoczi  *
3079060f51c9SStefan Hajnoczi  * See bdrv_co_is_allocated() for details.
3080060f51c9SStefan Hajnoczi  */
3081060f51c9SStefan Hajnoczi int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
3082060f51c9SStefan Hajnoczi                       int *pnum)
3083060f51c9SStefan Hajnoczi {
3084376ae3f1SStefan Hajnoczi     Coroutine *co;
3085376ae3f1SStefan Hajnoczi     BdrvCoIsAllocatedData data = {
3086376ae3f1SStefan Hajnoczi         .bs = bs,
3087376ae3f1SStefan Hajnoczi         .sector_num = sector_num,
3088376ae3f1SStefan Hajnoczi         .nb_sectors = nb_sectors,
3089376ae3f1SStefan Hajnoczi         .pnum = pnum,
3090376ae3f1SStefan Hajnoczi         .done = false,
3091376ae3f1SStefan Hajnoczi     };
3092376ae3f1SStefan Hajnoczi 
3093376ae3f1SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_is_allocated_co_entry);
3094376ae3f1SStefan Hajnoczi     qemu_coroutine_enter(co, &data);
3095376ae3f1SStefan Hajnoczi     while (!data.done) {
3096376ae3f1SStefan Hajnoczi         qemu_aio_wait();
3097376ae3f1SStefan Hajnoczi     }
3098376ae3f1SStefan Hajnoczi     return data.ret;
3099376ae3f1SStefan Hajnoczi }
3100f58c7b35Sths 
3101188a7bbfSPaolo Bonzini /*
3102188a7bbfSPaolo Bonzini  * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
3103188a7bbfSPaolo Bonzini  *
3104188a7bbfSPaolo Bonzini  * Return true if the given sector is allocated in any image between
3105188a7bbfSPaolo Bonzini  * BASE and TOP (inclusive).  BASE can be NULL to check if the given
3106188a7bbfSPaolo Bonzini  * sector is allocated in any image of the chain.  Return false otherwise.
3107188a7bbfSPaolo Bonzini  *
3108188a7bbfSPaolo Bonzini  * 'pnum' is set to the number of sectors (including and immediately following
3109188a7bbfSPaolo Bonzini  *  the specified sector) that are known to be in the same
3110188a7bbfSPaolo Bonzini  *  allocated/unallocated state.
3111188a7bbfSPaolo Bonzini  *
3112188a7bbfSPaolo Bonzini  */
3113188a7bbfSPaolo Bonzini int coroutine_fn bdrv_co_is_allocated_above(BlockDriverState *top,
3114188a7bbfSPaolo Bonzini                                             BlockDriverState *base,
3115188a7bbfSPaolo Bonzini                                             int64_t sector_num,
3116188a7bbfSPaolo Bonzini                                             int nb_sectors, int *pnum)
3117188a7bbfSPaolo Bonzini {
3118188a7bbfSPaolo Bonzini     BlockDriverState *intermediate;
3119188a7bbfSPaolo Bonzini     int ret, n = nb_sectors;
3120188a7bbfSPaolo Bonzini 
3121188a7bbfSPaolo Bonzini     intermediate = top;
3122188a7bbfSPaolo Bonzini     while (intermediate && intermediate != base) {
3123188a7bbfSPaolo Bonzini         int pnum_inter;
3124188a7bbfSPaolo Bonzini         ret = bdrv_co_is_allocated(intermediate, sector_num, nb_sectors,
3125188a7bbfSPaolo Bonzini                                    &pnum_inter);
3126188a7bbfSPaolo Bonzini         if (ret < 0) {
3127188a7bbfSPaolo Bonzini             return ret;
3128188a7bbfSPaolo Bonzini         } else if (ret) {
3129188a7bbfSPaolo Bonzini             *pnum = pnum_inter;
3130188a7bbfSPaolo Bonzini             return 1;
3131188a7bbfSPaolo Bonzini         }
3132188a7bbfSPaolo Bonzini 
3133188a7bbfSPaolo Bonzini         /*
3134188a7bbfSPaolo Bonzini          * [sector_num, nb_sectors] is unallocated on top but intermediate
3135188a7bbfSPaolo Bonzini          * might have
3136188a7bbfSPaolo Bonzini          *
3137188a7bbfSPaolo Bonzini          * [sector_num+x, nr_sectors] allocated.
3138188a7bbfSPaolo Bonzini          */
313963ba17d3SVishvananda Ishaya         if (n > pnum_inter &&
314063ba17d3SVishvananda Ishaya             (intermediate == top ||
314163ba17d3SVishvananda Ishaya              sector_num + pnum_inter < intermediate->total_sectors)) {
3142188a7bbfSPaolo Bonzini             n = pnum_inter;
3143188a7bbfSPaolo Bonzini         }
3144188a7bbfSPaolo Bonzini 
3145188a7bbfSPaolo Bonzini         intermediate = intermediate->backing_hd;
3146188a7bbfSPaolo Bonzini     }
3147188a7bbfSPaolo Bonzini 
3148188a7bbfSPaolo Bonzini     *pnum = n;
3149188a7bbfSPaolo Bonzini     return 0;
3150188a7bbfSPaolo Bonzini }
3151188a7bbfSPaolo Bonzini 
3152b35b2bbaSMiroslav Rezanina /* Coroutine wrapper for bdrv_is_allocated_above() */
3153b35b2bbaSMiroslav Rezanina static void coroutine_fn bdrv_is_allocated_above_co_entry(void *opaque)
3154b35b2bbaSMiroslav Rezanina {
3155b35b2bbaSMiroslav Rezanina     BdrvCoIsAllocatedData *data = opaque;
3156b35b2bbaSMiroslav Rezanina     BlockDriverState *top = data->bs;
3157b35b2bbaSMiroslav Rezanina     BlockDriverState *base = data->base;
3158b35b2bbaSMiroslav Rezanina 
3159b35b2bbaSMiroslav Rezanina     data->ret = bdrv_co_is_allocated_above(top, base, data->sector_num,
3160b35b2bbaSMiroslav Rezanina                                            data->nb_sectors, data->pnum);
3161b35b2bbaSMiroslav Rezanina     data->done = true;
3162b35b2bbaSMiroslav Rezanina }
3163b35b2bbaSMiroslav Rezanina 
3164b35b2bbaSMiroslav Rezanina /*
3165b35b2bbaSMiroslav Rezanina  * Synchronous wrapper around bdrv_co_is_allocated_above().
3166b35b2bbaSMiroslav Rezanina  *
3167b35b2bbaSMiroslav Rezanina  * See bdrv_co_is_allocated_above() for details.
3168b35b2bbaSMiroslav Rezanina  */
3169b35b2bbaSMiroslav Rezanina int bdrv_is_allocated_above(BlockDriverState *top, BlockDriverState *base,
3170b35b2bbaSMiroslav Rezanina                             int64_t sector_num, int nb_sectors, int *pnum)
3171b35b2bbaSMiroslav Rezanina {
3172b35b2bbaSMiroslav Rezanina     Coroutine *co;
3173b35b2bbaSMiroslav Rezanina     BdrvCoIsAllocatedData data = {
3174b35b2bbaSMiroslav Rezanina         .bs = top,
3175b35b2bbaSMiroslav Rezanina         .base = base,
3176b35b2bbaSMiroslav Rezanina         .sector_num = sector_num,
3177b35b2bbaSMiroslav Rezanina         .nb_sectors = nb_sectors,
3178b35b2bbaSMiroslav Rezanina         .pnum = pnum,
3179b35b2bbaSMiroslav Rezanina         .done = false,
3180b35b2bbaSMiroslav Rezanina     };
3181b35b2bbaSMiroslav Rezanina 
3182b35b2bbaSMiroslav Rezanina     co = qemu_coroutine_create(bdrv_is_allocated_above_co_entry);
3183b35b2bbaSMiroslav Rezanina     qemu_coroutine_enter(co, &data);
3184b35b2bbaSMiroslav Rezanina     while (!data.done) {
3185b35b2bbaSMiroslav Rezanina         qemu_aio_wait();
3186b35b2bbaSMiroslav Rezanina     }
3187b35b2bbaSMiroslav Rezanina     return data.ret;
3188b35b2bbaSMiroslav Rezanina }
3189b35b2bbaSMiroslav Rezanina 
3190045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3191045df330Saliguori {
3192045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
3193045df330Saliguori         return bs->backing_file;
3194045df330Saliguori     else if (bs->encrypted)
3195045df330Saliguori         return bs->filename;
3196045df330Saliguori     else
3197045df330Saliguori         return NULL;
3198045df330Saliguori }
3199045df330Saliguori 
320083f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
320183f64091Sbellard                                char *filename, int filename_size)
320283f64091Sbellard {
320383f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
320483f64091Sbellard }
320583f64091Sbellard 
3206faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
3207faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
3208faea38e7Sbellard {
3209faea38e7Sbellard     BlockDriver *drv = bs->drv;
3210faea38e7Sbellard     if (!drv)
321119cb3738Sbellard         return -ENOMEDIUM;
3212faea38e7Sbellard     if (!drv->bdrv_write_compressed)
3213faea38e7Sbellard         return -ENOTSUP;
3214fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
3215fbb7b4e0SKevin Wolf         return -EIO;
32167cd1e32aSlirans@il.ibm.com 
32171755da16SPaolo Bonzini     assert(!bs->dirty_bitmap);
32187cd1e32aSlirans@il.ibm.com 
3219faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
3220faea38e7Sbellard }
3221faea38e7Sbellard 
3222faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3223faea38e7Sbellard {
3224faea38e7Sbellard     BlockDriver *drv = bs->drv;
3225faea38e7Sbellard     if (!drv)
322619cb3738Sbellard         return -ENOMEDIUM;
3227faea38e7Sbellard     if (!drv->bdrv_get_info)
3228faea38e7Sbellard         return -ENOTSUP;
3229faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
3230faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
3231faea38e7Sbellard }
3232faea38e7Sbellard 
323345566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
323445566e9cSChristoph Hellwig                       int64_t pos, int size)
3235178e08a5Saliguori {
3236cf8074b3SKevin Wolf     QEMUIOVector qiov;
3237cf8074b3SKevin Wolf     struct iovec iov = {
3238cf8074b3SKevin Wolf         .iov_base   = (void *) buf,
3239cf8074b3SKevin Wolf         .iov_len    = size,
3240cf8074b3SKevin Wolf     };
3241cf8074b3SKevin Wolf 
3242cf8074b3SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
3243cf8074b3SKevin Wolf     return bdrv_writev_vmstate(bs, &qiov, pos);
3244cf8074b3SKevin Wolf }
3245cf8074b3SKevin Wolf 
3246cf8074b3SKevin Wolf int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
3247cf8074b3SKevin Wolf {
3248178e08a5Saliguori     BlockDriver *drv = bs->drv;
3249cf8074b3SKevin Wolf 
3250cf8074b3SKevin Wolf     if (!drv) {
3251178e08a5Saliguori         return -ENOMEDIUM;
3252cf8074b3SKevin Wolf     } else if (drv->bdrv_save_vmstate) {
3253cf8074b3SKevin Wolf         return drv->bdrv_save_vmstate(bs, qiov, pos);
3254cf8074b3SKevin Wolf     } else if (bs->file) {
3255cf8074b3SKevin Wolf         return bdrv_writev_vmstate(bs->file, qiov, pos);
3256cf8074b3SKevin Wolf     }
3257cf8074b3SKevin Wolf 
32587cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3259178e08a5Saliguori }
3260178e08a5Saliguori 
326145566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
326245566e9cSChristoph Hellwig                       int64_t pos, int size)
3263178e08a5Saliguori {
3264178e08a5Saliguori     BlockDriver *drv = bs->drv;
3265178e08a5Saliguori     if (!drv)
3266178e08a5Saliguori         return -ENOMEDIUM;
32677cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
326845566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
32697cdb1f6dSMORITA Kazutaka     if (bs->file)
32707cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
32717cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3272178e08a5Saliguori }
3273178e08a5Saliguori 
32748b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
32758b9b0cc2SKevin Wolf {
3276bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
32778b9b0cc2SKevin Wolf         return;
32788b9b0cc2SKevin Wolf     }
32798b9b0cc2SKevin Wolf 
3280bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
328141c695c7SKevin Wolf }
32828b9b0cc2SKevin Wolf 
328341c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
328441c695c7SKevin Wolf                           const char *tag)
328541c695c7SKevin Wolf {
328641c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
328741c695c7SKevin Wolf         bs = bs->file;
328841c695c7SKevin Wolf     }
328941c695c7SKevin Wolf 
329041c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
329141c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
329241c695c7SKevin Wolf     }
329341c695c7SKevin Wolf 
329441c695c7SKevin Wolf     return -ENOTSUP;
329541c695c7SKevin Wolf }
329641c695c7SKevin Wolf 
329741c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
329841c695c7SKevin Wolf {
329941c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_resume) {
330041c695c7SKevin Wolf         bs = bs->file;
330141c695c7SKevin Wolf     }
330241c695c7SKevin Wolf 
330341c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
330441c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
330541c695c7SKevin Wolf     }
330641c695c7SKevin Wolf 
330741c695c7SKevin Wolf     return -ENOTSUP;
330841c695c7SKevin Wolf }
330941c695c7SKevin Wolf 
331041c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
331141c695c7SKevin Wolf {
331241c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
331341c695c7SKevin Wolf         bs = bs->file;
331441c695c7SKevin Wolf     }
331541c695c7SKevin Wolf 
331641c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
331741c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
331841c695c7SKevin Wolf     }
331941c695c7SKevin Wolf 
332041c695c7SKevin Wolf     return false;
33218b9b0cc2SKevin Wolf }
33228b9b0cc2SKevin Wolf 
3323199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
3324199630b6SBlue Swirl {
3325199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3326199630b6SBlue Swirl }
3327199630b6SBlue Swirl 
3328b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
3329b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
3330b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
3331b1b1d783SJeff Cody  * the CWD rather than the chain. */
3332e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3333e8a6bb9cSMarcelo Tosatti         const char *backing_file)
3334e8a6bb9cSMarcelo Tosatti {
3335b1b1d783SJeff Cody     char *filename_full = NULL;
3336b1b1d783SJeff Cody     char *backing_file_full = NULL;
3337b1b1d783SJeff Cody     char *filename_tmp = NULL;
3338b1b1d783SJeff Cody     int is_protocol = 0;
3339b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
3340b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
3341b1b1d783SJeff Cody 
3342b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
3343e8a6bb9cSMarcelo Tosatti         return NULL;
3344e8a6bb9cSMarcelo Tosatti     }
3345e8a6bb9cSMarcelo Tosatti 
3346b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
3347b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
3348b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
3349b1b1d783SJeff Cody 
3350b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
3351b1b1d783SJeff Cody 
3352b1b1d783SJeff Cody     for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
3353b1b1d783SJeff Cody 
3354b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
3355b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
3356b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3357b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3358b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
3359b1b1d783SJeff Cody                 break;
3360b1b1d783SJeff Cody             }
3361e8a6bb9cSMarcelo Tosatti         } else {
3362b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
3363b1b1d783SJeff Cody              * image's filename path */
3364b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3365b1b1d783SJeff Cody                          backing_file);
3366b1b1d783SJeff Cody 
3367b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
3368b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
3369b1b1d783SJeff Cody                 continue;
3370b1b1d783SJeff Cody             }
3371b1b1d783SJeff Cody 
3372b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
3373b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
3374b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3375b1b1d783SJeff Cody                          curr_bs->backing_file);
3376b1b1d783SJeff Cody 
3377b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
3378b1b1d783SJeff Cody                 continue;
3379b1b1d783SJeff Cody             }
3380b1b1d783SJeff Cody 
3381b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
3382b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
3383b1b1d783SJeff Cody                 break;
3384b1b1d783SJeff Cody             }
3385e8a6bb9cSMarcelo Tosatti         }
3386e8a6bb9cSMarcelo Tosatti     }
3387e8a6bb9cSMarcelo Tosatti 
3388b1b1d783SJeff Cody     g_free(filename_full);
3389b1b1d783SJeff Cody     g_free(backing_file_full);
3390b1b1d783SJeff Cody     g_free(filename_tmp);
3391b1b1d783SJeff Cody     return retval;
3392e8a6bb9cSMarcelo Tosatti }
3393e8a6bb9cSMarcelo Tosatti 
3394f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
3395f198fd1cSBenoît Canet {
3396f198fd1cSBenoît Canet     if (!bs->drv) {
3397f198fd1cSBenoît Canet         return 0;
3398f198fd1cSBenoît Canet     }
3399f198fd1cSBenoît Canet 
3400f198fd1cSBenoît Canet     if (!bs->backing_hd) {
3401f198fd1cSBenoît Canet         return 0;
3402f198fd1cSBenoît Canet     }
3403f198fd1cSBenoît Canet 
3404f198fd1cSBenoît Canet     return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
3405f198fd1cSBenoît Canet }
3406f198fd1cSBenoît Canet 
340779fac568SJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
340879fac568SJeff Cody {
340979fac568SJeff Cody     BlockDriverState *curr_bs = NULL;
341079fac568SJeff Cody 
341179fac568SJeff Cody     if (!bs) {
341279fac568SJeff Cody         return NULL;
341379fac568SJeff Cody     }
341479fac568SJeff Cody 
341579fac568SJeff Cody     curr_bs = bs;
341679fac568SJeff Cody 
341779fac568SJeff Cody     while (curr_bs->backing_hd) {
341879fac568SJeff Cody         curr_bs = curr_bs->backing_hd;
341979fac568SJeff Cody     }
342079fac568SJeff Cody     return curr_bs;
342179fac568SJeff Cody }
342279fac568SJeff Cody 
3423ea2384d3Sbellard /**************************************************************/
342483f64091Sbellard /* async I/Os */
3425ea2384d3Sbellard 
34263b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
3427f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
342883f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
3429ea2384d3Sbellard {
3430bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
3431bbf0a440SStefan Hajnoczi 
3432b2a61371SStefan Hajnoczi     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
34338c5873d6SStefan Hajnoczi                                  cb, opaque, false);
343483f64091Sbellard }
343583f64091Sbellard 
3436f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
3437f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
343883f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
34397674e7bfSbellard {
3440bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
3441bbf0a440SStefan Hajnoczi 
34421a6e115bSStefan Hajnoczi     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
34438c5873d6SStefan Hajnoczi                                  cb, opaque, true);
344483f64091Sbellard }
344583f64091Sbellard 
344640b4f539SKevin Wolf 
344740b4f539SKevin Wolf typedef struct MultiwriteCB {
344840b4f539SKevin Wolf     int error;
344940b4f539SKevin Wolf     int num_requests;
345040b4f539SKevin Wolf     int num_callbacks;
345140b4f539SKevin Wolf     struct {
345240b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
345340b4f539SKevin Wolf         void *opaque;
345440b4f539SKevin Wolf         QEMUIOVector *free_qiov;
345540b4f539SKevin Wolf     } callbacks[];
345640b4f539SKevin Wolf } MultiwriteCB;
345740b4f539SKevin Wolf 
345840b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
345940b4f539SKevin Wolf {
346040b4f539SKevin Wolf     int i;
346140b4f539SKevin Wolf 
346240b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
346340b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
34641e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
34651e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
34661e1ea48dSStefan Hajnoczi         }
34677267c094SAnthony Liguori         g_free(mcb->callbacks[i].free_qiov);
346840b4f539SKevin Wolf     }
346940b4f539SKevin Wolf }
347040b4f539SKevin Wolf 
347140b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
347240b4f539SKevin Wolf {
347340b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
347440b4f539SKevin Wolf 
34756d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
34766d519a5fSStefan Hajnoczi 
3477cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
347840b4f539SKevin Wolf         mcb->error = ret;
347940b4f539SKevin Wolf     }
348040b4f539SKevin Wolf 
348140b4f539SKevin Wolf     mcb->num_requests--;
348240b4f539SKevin Wolf     if (mcb->num_requests == 0) {
348340b4f539SKevin Wolf         multiwrite_user_cb(mcb);
34847267c094SAnthony Liguori         g_free(mcb);
348540b4f539SKevin Wolf     }
348640b4f539SKevin Wolf }
348740b4f539SKevin Wolf 
348840b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
348940b4f539SKevin Wolf {
349077be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
349177be4366SChristoph Hellwig 
349277be4366SChristoph Hellwig     /*
349377be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
349477be4366SChristoph Hellwig      * here as that could overflow the return value.
349577be4366SChristoph Hellwig      */
349677be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
349777be4366SChristoph Hellwig         return 1;
349877be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
349977be4366SChristoph Hellwig         return -1;
350077be4366SChristoph Hellwig     } else {
350177be4366SChristoph Hellwig         return 0;
350277be4366SChristoph Hellwig     }
350340b4f539SKevin Wolf }
350440b4f539SKevin Wolf 
350540b4f539SKevin Wolf /*
350640b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
350740b4f539SKevin Wolf  * requests that remain after merging.
350840b4f539SKevin Wolf  */
350940b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
351040b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
351140b4f539SKevin Wolf {
351240b4f539SKevin Wolf     int i, outidx;
351340b4f539SKevin Wolf 
351440b4f539SKevin Wolf     // Sort requests by start sector
351540b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
351640b4f539SKevin Wolf 
351740b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
351840b4f539SKevin Wolf     // filling up gaps with zero sectors.
351940b4f539SKevin Wolf     outidx = 0;
352040b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
352140b4f539SKevin Wolf         int merge = 0;
352240b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
352340b4f539SKevin Wolf 
3524b6a127a1SPaolo Bonzini         // Handle exactly sequential writes and overlapping writes.
352540b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
352640b4f539SKevin Wolf             merge = 1;
352740b4f539SKevin Wolf         }
352840b4f539SKevin Wolf 
3529e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
3530e2a305fbSChristoph Hellwig             merge = 0;
3531e2a305fbSChristoph Hellwig         }
3532e2a305fbSChristoph Hellwig 
353340b4f539SKevin Wolf         if (merge) {
353440b4f539SKevin Wolf             size_t size;
35357267c094SAnthony Liguori             QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
353640b4f539SKevin Wolf             qemu_iovec_init(qiov,
353740b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
353840b4f539SKevin Wolf 
353940b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
354040b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
354140b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
35421b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
354340b4f539SKevin Wolf 
3544b6a127a1SPaolo Bonzini             // We should need to add any zeros between the two requests
3545b6a127a1SPaolo Bonzini             assert (reqs[i].sector <= oldreq_last);
354640b4f539SKevin Wolf 
354740b4f539SKevin Wolf             // Add the second request
35481b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
354940b4f539SKevin Wolf 
3550cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
355140b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
355240b4f539SKevin Wolf 
355340b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
355440b4f539SKevin Wolf         } else {
355540b4f539SKevin Wolf             outidx++;
355640b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
355740b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
355840b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
355940b4f539SKevin Wolf         }
356040b4f539SKevin Wolf     }
356140b4f539SKevin Wolf 
356240b4f539SKevin Wolf     return outidx + 1;
356340b4f539SKevin Wolf }
356440b4f539SKevin Wolf 
356540b4f539SKevin Wolf /*
356640b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
356740b4f539SKevin Wolf  *
356840b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
356940b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
357040b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
357140b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
357240b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
357340b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
357440b4f539SKevin Wolf  *
357540b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
357640b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
357740b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
357840b4f539SKevin Wolf  */
357940b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
358040b4f539SKevin Wolf {
358140b4f539SKevin Wolf     MultiwriteCB *mcb;
358240b4f539SKevin Wolf     int i;
358340b4f539SKevin Wolf 
3584301db7c2SRyan Harper     /* don't submit writes if we don't have a medium */
3585301db7c2SRyan Harper     if (bs->drv == NULL) {
3586301db7c2SRyan Harper         for (i = 0; i < num_reqs; i++) {
3587301db7c2SRyan Harper             reqs[i].error = -ENOMEDIUM;
3588301db7c2SRyan Harper         }
3589301db7c2SRyan Harper         return -1;
3590301db7c2SRyan Harper     }
3591301db7c2SRyan Harper 
359240b4f539SKevin Wolf     if (num_reqs == 0) {
359340b4f539SKevin Wolf         return 0;
359440b4f539SKevin Wolf     }
359540b4f539SKevin Wolf 
359640b4f539SKevin Wolf     // Create MultiwriteCB structure
35977267c094SAnthony Liguori     mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
359840b4f539SKevin Wolf     mcb->num_requests = 0;
359940b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
360040b4f539SKevin Wolf 
360140b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
360240b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
360340b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
360440b4f539SKevin Wolf     }
360540b4f539SKevin Wolf 
360640b4f539SKevin Wolf     // Check for mergable requests
360740b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
360840b4f539SKevin Wolf 
36096d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
36106d519a5fSStefan Hajnoczi 
3611df9309fbSPaolo Bonzini     /* Run the aio requests. */
3612df9309fbSPaolo Bonzini     mcb->num_requests = num_reqs;
361340b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
3614ad54ae80SPaolo Bonzini         bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
361540b4f539SKevin Wolf             reqs[i].nb_sectors, multiwrite_cb, mcb);
361640b4f539SKevin Wolf     }
361740b4f539SKevin Wolf 
361840b4f539SKevin Wolf     return 0;
361940b4f539SKevin Wolf }
362040b4f539SKevin Wolf 
362183f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
362283f64091Sbellard {
3623d7331bedSStefan Hajnoczi     acb->aiocb_info->cancel(acb);
362483f64091Sbellard }
362583f64091Sbellard 
362698f90dbaSZhi Yong Wu /* block I/O throttling */
362798f90dbaSZhi Yong Wu static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
362898f90dbaSZhi Yong Wu                  bool is_write, double elapsed_time, uint64_t *wait)
362998f90dbaSZhi Yong Wu {
363098f90dbaSZhi Yong Wu     uint64_t bps_limit = 0;
3631ae29d6c6SStefan Hajnoczi     uint64_t extension;
363298f90dbaSZhi Yong Wu     double   bytes_limit, bytes_base, bytes_res;
363398f90dbaSZhi Yong Wu     double   slice_time, wait_time;
363498f90dbaSZhi Yong Wu 
363598f90dbaSZhi Yong Wu     if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
363698f90dbaSZhi Yong Wu         bps_limit = bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
363798f90dbaSZhi Yong Wu     } else if (bs->io_limits.bps[is_write]) {
363898f90dbaSZhi Yong Wu         bps_limit = bs->io_limits.bps[is_write];
363998f90dbaSZhi Yong Wu     } else {
364098f90dbaSZhi Yong Wu         if (wait) {
364198f90dbaSZhi Yong Wu             *wait = 0;
364298f90dbaSZhi Yong Wu         }
364398f90dbaSZhi Yong Wu 
364498f90dbaSZhi Yong Wu         return false;
364598f90dbaSZhi Yong Wu     }
364698f90dbaSZhi Yong Wu 
364798f90dbaSZhi Yong Wu     slice_time = bs->slice_end - bs->slice_start;
364898f90dbaSZhi Yong Wu     slice_time /= (NANOSECONDS_PER_SECOND);
364998f90dbaSZhi Yong Wu     bytes_limit = bps_limit * slice_time;
36505905fbc9SStefan Hajnoczi     bytes_base  = bs->slice_submitted.bytes[is_write];
365198f90dbaSZhi Yong Wu     if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
36525905fbc9SStefan Hajnoczi         bytes_base += bs->slice_submitted.bytes[!is_write];
365398f90dbaSZhi Yong Wu     }
365498f90dbaSZhi Yong Wu 
365598f90dbaSZhi Yong Wu     /* bytes_base: the bytes of data which have been read/written; and
365698f90dbaSZhi Yong Wu      *             it is obtained from the history statistic info.
365798f90dbaSZhi Yong Wu      * bytes_res: the remaining bytes of data which need to be read/written.
365898f90dbaSZhi Yong Wu      * (bytes_base + bytes_res) / bps_limit: used to calcuate
365998f90dbaSZhi Yong Wu      *             the total time for completing reading/writting all data.
366098f90dbaSZhi Yong Wu      */
366198f90dbaSZhi Yong Wu     bytes_res   = (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
366298f90dbaSZhi Yong Wu 
366398f90dbaSZhi Yong Wu     if (bytes_base + bytes_res <= bytes_limit) {
366498f90dbaSZhi Yong Wu         if (wait) {
366598f90dbaSZhi Yong Wu             *wait = 0;
366698f90dbaSZhi Yong Wu         }
366798f90dbaSZhi Yong Wu 
366898f90dbaSZhi Yong Wu         return false;
366998f90dbaSZhi Yong Wu     }
367098f90dbaSZhi Yong Wu 
367198f90dbaSZhi Yong Wu     /* Calc approx time to dispatch */
367298f90dbaSZhi Yong Wu     wait_time = (bytes_base + bytes_res) / bps_limit - elapsed_time;
367398f90dbaSZhi Yong Wu 
367498f90dbaSZhi Yong Wu     /* When the I/O rate at runtime exceeds the limits,
367598f90dbaSZhi Yong Wu      * bs->slice_end need to be extended in order that the current statistic
367698f90dbaSZhi Yong Wu      * info can be kept until the timer fire, so it is increased and tuned
367798f90dbaSZhi Yong Wu      * based on the result of experiment.
367898f90dbaSZhi Yong Wu      */
3679ae29d6c6SStefan Hajnoczi     extension = wait_time * NANOSECONDS_PER_SECOND;
3680ae29d6c6SStefan Hajnoczi     extension = DIV_ROUND_UP(extension, BLOCK_IO_SLICE_TIME) *
3681ae29d6c6SStefan Hajnoczi                 BLOCK_IO_SLICE_TIME;
3682ae29d6c6SStefan Hajnoczi     bs->slice_end += extension;
368398f90dbaSZhi Yong Wu     if (wait) {
36840775437fSStefan Hajnoczi         *wait = wait_time * NANOSECONDS_PER_SECOND;
368598f90dbaSZhi Yong Wu     }
368698f90dbaSZhi Yong Wu 
368798f90dbaSZhi Yong Wu     return true;
368898f90dbaSZhi Yong Wu }
368998f90dbaSZhi Yong Wu 
369098f90dbaSZhi Yong Wu static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
369198f90dbaSZhi Yong Wu                              double elapsed_time, uint64_t *wait)
369298f90dbaSZhi Yong Wu {
369398f90dbaSZhi Yong Wu     uint64_t iops_limit = 0;
369498f90dbaSZhi Yong Wu     double   ios_limit, ios_base;
369598f90dbaSZhi Yong Wu     double   slice_time, wait_time;
369698f90dbaSZhi Yong Wu 
369798f90dbaSZhi Yong Wu     if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
369898f90dbaSZhi Yong Wu         iops_limit = bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
369998f90dbaSZhi Yong Wu     } else if (bs->io_limits.iops[is_write]) {
370098f90dbaSZhi Yong Wu         iops_limit = bs->io_limits.iops[is_write];
370198f90dbaSZhi Yong Wu     } else {
370298f90dbaSZhi Yong Wu         if (wait) {
370398f90dbaSZhi Yong Wu             *wait = 0;
370498f90dbaSZhi Yong Wu         }
370598f90dbaSZhi Yong Wu 
370698f90dbaSZhi Yong Wu         return false;
370798f90dbaSZhi Yong Wu     }
370898f90dbaSZhi Yong Wu 
370998f90dbaSZhi Yong Wu     slice_time = bs->slice_end - bs->slice_start;
371098f90dbaSZhi Yong Wu     slice_time /= (NANOSECONDS_PER_SECOND);
371198f90dbaSZhi Yong Wu     ios_limit  = iops_limit * slice_time;
37125905fbc9SStefan Hajnoczi     ios_base   = bs->slice_submitted.ios[is_write];
371398f90dbaSZhi Yong Wu     if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
37145905fbc9SStefan Hajnoczi         ios_base += bs->slice_submitted.ios[!is_write];
371598f90dbaSZhi Yong Wu     }
371698f90dbaSZhi Yong Wu 
371798f90dbaSZhi Yong Wu     if (ios_base + 1 <= ios_limit) {
371898f90dbaSZhi Yong Wu         if (wait) {
371998f90dbaSZhi Yong Wu             *wait = 0;
372098f90dbaSZhi Yong Wu         }
372198f90dbaSZhi Yong Wu 
372298f90dbaSZhi Yong Wu         return false;
372398f90dbaSZhi Yong Wu     }
372498f90dbaSZhi Yong Wu 
37250775437fSStefan Hajnoczi     /* Calc approx time to dispatch, in seconds */
372698f90dbaSZhi Yong Wu     wait_time = (ios_base + 1) / iops_limit;
372798f90dbaSZhi Yong Wu     if (wait_time > elapsed_time) {
372898f90dbaSZhi Yong Wu         wait_time = wait_time - elapsed_time;
372998f90dbaSZhi Yong Wu     } else {
373098f90dbaSZhi Yong Wu         wait_time = 0;
373198f90dbaSZhi Yong Wu     }
373298f90dbaSZhi Yong Wu 
3733ae29d6c6SStefan Hajnoczi     /* Exceeded current slice, extend it by another slice time */
3734ae29d6c6SStefan Hajnoczi     bs->slice_end += BLOCK_IO_SLICE_TIME;
373598f90dbaSZhi Yong Wu     if (wait) {
37360775437fSStefan Hajnoczi         *wait = wait_time * NANOSECONDS_PER_SECOND;
373798f90dbaSZhi Yong Wu     }
373898f90dbaSZhi Yong Wu 
373998f90dbaSZhi Yong Wu     return true;
374098f90dbaSZhi Yong Wu }
374198f90dbaSZhi Yong Wu 
374298f90dbaSZhi Yong Wu static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
374398f90dbaSZhi Yong Wu                            bool is_write, int64_t *wait)
374498f90dbaSZhi Yong Wu {
374598f90dbaSZhi Yong Wu     int64_t  now, max_wait;
374698f90dbaSZhi Yong Wu     uint64_t bps_wait = 0, iops_wait = 0;
374798f90dbaSZhi Yong Wu     double   elapsed_time;
374898f90dbaSZhi Yong Wu     int      bps_ret, iops_ret;
374998f90dbaSZhi Yong Wu 
375098f90dbaSZhi Yong Wu     now = qemu_get_clock_ns(vm_clock);
3751e660fb8bSStefan Hajnoczi     if (now > bs->slice_end) {
375298f90dbaSZhi Yong Wu         bs->slice_start = now;
3753ae29d6c6SStefan Hajnoczi         bs->slice_end   = now + BLOCK_IO_SLICE_TIME;
37545905fbc9SStefan Hajnoczi         memset(&bs->slice_submitted, 0, sizeof(bs->slice_submitted));
375598f90dbaSZhi Yong Wu     }
375698f90dbaSZhi Yong Wu 
375798f90dbaSZhi Yong Wu     elapsed_time  = now - bs->slice_start;
375898f90dbaSZhi Yong Wu     elapsed_time  /= (NANOSECONDS_PER_SECOND);
375998f90dbaSZhi Yong Wu 
376098f90dbaSZhi Yong Wu     bps_ret  = bdrv_exceed_bps_limits(bs, nb_sectors,
376198f90dbaSZhi Yong Wu                                       is_write, elapsed_time, &bps_wait);
376298f90dbaSZhi Yong Wu     iops_ret = bdrv_exceed_iops_limits(bs, is_write,
376398f90dbaSZhi Yong Wu                                       elapsed_time, &iops_wait);
376498f90dbaSZhi Yong Wu     if (bps_ret || iops_ret) {
376598f90dbaSZhi Yong Wu         max_wait = bps_wait > iops_wait ? bps_wait : iops_wait;
376698f90dbaSZhi Yong Wu         if (wait) {
376798f90dbaSZhi Yong Wu             *wait = max_wait;
376898f90dbaSZhi Yong Wu         }
376998f90dbaSZhi Yong Wu 
377098f90dbaSZhi Yong Wu         now = qemu_get_clock_ns(vm_clock);
377198f90dbaSZhi Yong Wu         if (bs->slice_end < now + max_wait) {
377298f90dbaSZhi Yong Wu             bs->slice_end = now + max_wait;
377398f90dbaSZhi Yong Wu         }
377498f90dbaSZhi Yong Wu 
377598f90dbaSZhi Yong Wu         return true;
377698f90dbaSZhi Yong Wu     }
377798f90dbaSZhi Yong Wu 
377898f90dbaSZhi Yong Wu     if (wait) {
377998f90dbaSZhi Yong Wu         *wait = 0;
378098f90dbaSZhi Yong Wu     }
378198f90dbaSZhi Yong Wu 
37825905fbc9SStefan Hajnoczi     bs->slice_submitted.bytes[is_write] += (int64_t)nb_sectors *
37835905fbc9SStefan Hajnoczi                                            BDRV_SECTOR_SIZE;
37845905fbc9SStefan Hajnoczi     bs->slice_submitted.ios[is_write]++;
37855905fbc9SStefan Hajnoczi 
378698f90dbaSZhi Yong Wu     return false;
378798f90dbaSZhi Yong Wu }
378883f64091Sbellard 
378983f64091Sbellard /**************************************************************/
379083f64091Sbellard /* async block device emulation */
379183f64091Sbellard 
3792c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
3793c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
3794c16b5a2cSChristoph Hellwig     QEMUBH *bh;
3795c16b5a2cSChristoph Hellwig     int ret;
3796c16b5a2cSChristoph Hellwig     /* vector translation state */
3797c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
3798c16b5a2cSChristoph Hellwig     uint8_t *bounce;
3799c16b5a2cSChristoph Hellwig     int is_write;
3800c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
3801c16b5a2cSChristoph Hellwig 
3802c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
3803c16b5a2cSChristoph Hellwig {
3804b666d239SKevin Wolf     BlockDriverAIOCBSync *acb =
3805b666d239SKevin Wolf         container_of(blockacb, BlockDriverAIOCBSync, common);
38066a7ad299SDor Laor     qemu_bh_delete(acb->bh);
380736afc451SAvi Kivity     acb->bh = NULL;
3808c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
3809c16b5a2cSChristoph Hellwig }
3810c16b5a2cSChristoph Hellwig 
3811d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_aiocb_info = {
3812c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
3813c16b5a2cSChristoph Hellwig     .cancel             = bdrv_aio_cancel_em,
3814c16b5a2cSChristoph Hellwig };
3815c16b5a2cSChristoph Hellwig 
381683f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
3817beac80cdSbellard {
3818ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
3819f141eafeSaliguori 
3820f141eafeSaliguori     if (!acb->is_write)
382103396148SMichael Tokarev         qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
3822ceb42de8Saliguori     qemu_vfree(acb->bounce);
3823ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
38246a7ad299SDor Laor     qemu_bh_delete(acb->bh);
382536afc451SAvi Kivity     acb->bh = NULL;
3826ce1a14dcSpbrook     qemu_aio_release(acb);
3827beac80cdSbellard }
3828beac80cdSbellard 
3829f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
3830f141eafeSaliguori                                             int64_t sector_num,
3831f141eafeSaliguori                                             QEMUIOVector *qiov,
3832f141eafeSaliguori                                             int nb_sectors,
3833f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
3834f141eafeSaliguori                                             void *opaque,
3835f141eafeSaliguori                                             int is_write)
3836f141eafeSaliguori 
3837ea2384d3Sbellard {
3838ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
383983f64091Sbellard 
3840d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
3841f141eafeSaliguori     acb->is_write = is_write;
3842f141eafeSaliguori     acb->qiov = qiov;
3843e268ca52Saliguori     acb->bounce = qemu_blockalign(bs, qiov->size);
3844ce1a14dcSpbrook     acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
3845f141eafeSaliguori 
3846f141eafeSaliguori     if (is_write) {
3847d5e6b161SMichael Tokarev         qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
38481ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
3849f141eafeSaliguori     } else {
38501ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
3851f141eafeSaliguori     }
3852f141eafeSaliguori 
3853ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
3854f141eafeSaliguori 
3855ce1a14dcSpbrook     return &acb->common;
38567a6cba61Spbrook }
38577a6cba61Spbrook 
3858f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
3859f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
3860ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
386183f64091Sbellard {
3862f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
386383f64091Sbellard }
386483f64091Sbellard 
3865f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
3866f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
3867f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
3868f141eafeSaliguori {
3869f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
3870f141eafeSaliguori }
3871f141eafeSaliguori 
387268485420SKevin Wolf 
387368485420SKevin Wolf typedef struct BlockDriverAIOCBCoroutine {
387468485420SKevin Wolf     BlockDriverAIOCB common;
387568485420SKevin Wolf     BlockRequest req;
387668485420SKevin Wolf     bool is_write;
3877d318aea9SKevin Wolf     bool *done;
387868485420SKevin Wolf     QEMUBH* bh;
387968485420SKevin Wolf } BlockDriverAIOCBCoroutine;
388068485420SKevin Wolf 
388168485420SKevin Wolf static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
388268485420SKevin Wolf {
3883d318aea9SKevin Wolf     BlockDriverAIOCBCoroutine *acb =
3884d318aea9SKevin Wolf         container_of(blockacb, BlockDriverAIOCBCoroutine, common);
3885d318aea9SKevin Wolf     bool done = false;
3886d318aea9SKevin Wolf 
3887d318aea9SKevin Wolf     acb->done = &done;
3888d318aea9SKevin Wolf     while (!done) {
3889d318aea9SKevin Wolf         qemu_aio_wait();
3890d318aea9SKevin Wolf     }
389168485420SKevin Wolf }
389268485420SKevin Wolf 
3893d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_co_aiocb_info = {
389468485420SKevin Wolf     .aiocb_size         = sizeof(BlockDriverAIOCBCoroutine),
389568485420SKevin Wolf     .cancel             = bdrv_aio_co_cancel_em,
389668485420SKevin Wolf };
389768485420SKevin Wolf 
389835246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque)
389968485420SKevin Wolf {
390068485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb = opaque;
390168485420SKevin Wolf 
390268485420SKevin Wolf     acb->common.cb(acb->common.opaque, acb->req.error);
3903d318aea9SKevin Wolf 
3904d318aea9SKevin Wolf     if (acb->done) {
3905d318aea9SKevin Wolf         *acb->done = true;
3906d318aea9SKevin Wolf     }
3907d318aea9SKevin Wolf 
390868485420SKevin Wolf     qemu_bh_delete(acb->bh);
390968485420SKevin Wolf     qemu_aio_release(acb);
391068485420SKevin Wolf }
391168485420SKevin Wolf 
3912b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
3913b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque)
3914b2a61371SStefan Hajnoczi {
3915b2a61371SStefan Hajnoczi     BlockDriverAIOCBCoroutine *acb = opaque;
3916b2a61371SStefan Hajnoczi     BlockDriverState *bs = acb->common.bs;
3917b2a61371SStefan Hajnoczi 
3918b2a61371SStefan Hajnoczi     if (!acb->is_write) {
3919b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
3920470c0504SStefan Hajnoczi             acb->req.nb_sectors, acb->req.qiov, 0);
3921b2a61371SStefan Hajnoczi     } else {
3922b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
3923f08f2ddaSStefan Hajnoczi             acb->req.nb_sectors, acb->req.qiov, 0);
3924b2a61371SStefan Hajnoczi     }
3925b2a61371SStefan Hajnoczi 
392635246a68SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
3927b2a61371SStefan Hajnoczi     qemu_bh_schedule(acb->bh);
3928b2a61371SStefan Hajnoczi }
3929b2a61371SStefan Hajnoczi 
393068485420SKevin Wolf static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
393168485420SKevin Wolf                                                int64_t sector_num,
393268485420SKevin Wolf                                                QEMUIOVector *qiov,
393368485420SKevin Wolf                                                int nb_sectors,
393468485420SKevin Wolf                                                BlockDriverCompletionFunc *cb,
393568485420SKevin Wolf                                                void *opaque,
39368c5873d6SStefan Hajnoczi                                                bool is_write)
393768485420SKevin Wolf {
393868485420SKevin Wolf     Coroutine *co;
393968485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb;
394068485420SKevin Wolf 
3941d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
394268485420SKevin Wolf     acb->req.sector = sector_num;
394368485420SKevin Wolf     acb->req.nb_sectors = nb_sectors;
394468485420SKevin Wolf     acb->req.qiov = qiov;
394568485420SKevin Wolf     acb->is_write = is_write;
3946d318aea9SKevin Wolf     acb->done = NULL;
394768485420SKevin Wolf 
39488c5873d6SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_co_do_rw);
394968485420SKevin Wolf     qemu_coroutine_enter(co, acb);
395068485420SKevin Wolf 
395168485420SKevin Wolf     return &acb->common;
395268485420SKevin Wolf }
395368485420SKevin Wolf 
395407f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
3955b2e12bc6SChristoph Hellwig {
395607f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
395707f07615SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
3958b2e12bc6SChristoph Hellwig 
395907f07615SPaolo Bonzini     acb->req.error = bdrv_co_flush(bs);
396007f07615SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
3961b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
3962b2e12bc6SChristoph Hellwig }
3963b2e12bc6SChristoph Hellwig 
396407f07615SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
3965016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
3966016f5cf6SAlexander Graf {
396707f07615SPaolo Bonzini     trace_bdrv_aio_flush(bs, opaque);
3968016f5cf6SAlexander Graf 
396907f07615SPaolo Bonzini     Coroutine *co;
397007f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
3971016f5cf6SAlexander Graf 
3972d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
3973d318aea9SKevin Wolf     acb->done = NULL;
3974d318aea9SKevin Wolf 
397507f07615SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
397607f07615SPaolo Bonzini     qemu_coroutine_enter(co, acb);
3977016f5cf6SAlexander Graf 
3978016f5cf6SAlexander Graf     return &acb->common;
3979016f5cf6SAlexander Graf }
3980016f5cf6SAlexander Graf 
39814265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
39824265d620SPaolo Bonzini {
39834265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
39844265d620SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
39854265d620SPaolo Bonzini 
39864265d620SPaolo Bonzini     acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
39874265d620SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
39884265d620SPaolo Bonzini     qemu_bh_schedule(acb->bh);
39894265d620SPaolo Bonzini }
39904265d620SPaolo Bonzini 
39914265d620SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
39924265d620SPaolo Bonzini         int64_t sector_num, int nb_sectors,
39934265d620SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
39944265d620SPaolo Bonzini {
39954265d620SPaolo Bonzini     Coroutine *co;
39964265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
39974265d620SPaolo Bonzini 
39984265d620SPaolo Bonzini     trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
39994265d620SPaolo Bonzini 
4000d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
40014265d620SPaolo Bonzini     acb->req.sector = sector_num;
40024265d620SPaolo Bonzini     acb->req.nb_sectors = nb_sectors;
4003d318aea9SKevin Wolf     acb->done = NULL;
40044265d620SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
40054265d620SPaolo Bonzini     qemu_coroutine_enter(co, acb);
40064265d620SPaolo Bonzini 
40074265d620SPaolo Bonzini     return &acb->common;
40084265d620SPaolo Bonzini }
40094265d620SPaolo Bonzini 
4010ea2384d3Sbellard void bdrv_init(void)
4011ea2384d3Sbellard {
40125efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
4013ea2384d3Sbellard }
4014ce1a14dcSpbrook 
4015eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
4016eb852011SMarkus Armbruster {
4017eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
4018eb852011SMarkus Armbruster     bdrv_init();
4019eb852011SMarkus Armbruster }
4020eb852011SMarkus Armbruster 
4021d7331bedSStefan Hajnoczi void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
40226bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
40236bbff9a0Saliguori {
4024ce1a14dcSpbrook     BlockDriverAIOCB *acb;
4025ce1a14dcSpbrook 
4026d7331bedSStefan Hajnoczi     acb = g_slice_alloc(aiocb_info->aiocb_size);
4027d7331bedSStefan Hajnoczi     acb->aiocb_info = aiocb_info;
4028ce1a14dcSpbrook     acb->bs = bs;
4029ce1a14dcSpbrook     acb->cb = cb;
4030ce1a14dcSpbrook     acb->opaque = opaque;
4031ce1a14dcSpbrook     return acb;
4032ce1a14dcSpbrook }
4033ce1a14dcSpbrook 
4034ce1a14dcSpbrook void qemu_aio_release(void *p)
4035ce1a14dcSpbrook {
4036d37c975fSStefan Hajnoczi     BlockDriverAIOCB *acb = p;
4037d7331bedSStefan Hajnoczi     g_slice_free1(acb->aiocb_info->aiocb_size, acb);
4038ce1a14dcSpbrook }
403919cb3738Sbellard 
404019cb3738Sbellard /**************************************************************/
4041f9f05dc5SKevin Wolf /* Coroutine block device emulation */
4042f9f05dc5SKevin Wolf 
4043f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion {
4044f9f05dc5SKevin Wolf     Coroutine *coroutine;
4045f9f05dc5SKevin Wolf     int ret;
4046f9f05dc5SKevin Wolf } CoroutineIOCompletion;
4047f9f05dc5SKevin Wolf 
4048f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret)
4049f9f05dc5SKevin Wolf {
4050f9f05dc5SKevin Wolf     CoroutineIOCompletion *co = opaque;
4051f9f05dc5SKevin Wolf 
4052f9f05dc5SKevin Wolf     co->ret = ret;
4053f9f05dc5SKevin Wolf     qemu_coroutine_enter(co->coroutine, NULL);
4054f9f05dc5SKevin Wolf }
4055f9f05dc5SKevin Wolf 
4056f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
4057f9f05dc5SKevin Wolf                                       int nb_sectors, QEMUIOVector *iov,
4058f9f05dc5SKevin Wolf                                       bool is_write)
4059f9f05dc5SKevin Wolf {
4060f9f05dc5SKevin Wolf     CoroutineIOCompletion co = {
4061f9f05dc5SKevin Wolf         .coroutine = qemu_coroutine_self(),
4062f9f05dc5SKevin Wolf     };
4063f9f05dc5SKevin Wolf     BlockDriverAIOCB *acb;
4064f9f05dc5SKevin Wolf 
4065f9f05dc5SKevin Wolf     if (is_write) {
4066a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
4067f9f05dc5SKevin Wolf                                        bdrv_co_io_em_complete, &co);
4068f9f05dc5SKevin Wolf     } else {
4069a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
4070f9f05dc5SKevin Wolf                                       bdrv_co_io_em_complete, &co);
4071f9f05dc5SKevin Wolf     }
4072f9f05dc5SKevin Wolf 
407359370aaaSStefan Hajnoczi     trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
4074f9f05dc5SKevin Wolf     if (!acb) {
4075f9f05dc5SKevin Wolf         return -EIO;
4076f9f05dc5SKevin Wolf     }
4077f9f05dc5SKevin Wolf     qemu_coroutine_yield();
4078f9f05dc5SKevin Wolf 
4079f9f05dc5SKevin Wolf     return co.ret;
4080f9f05dc5SKevin Wolf }
4081f9f05dc5SKevin Wolf 
4082f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
4083f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4084f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4085f9f05dc5SKevin Wolf {
4086f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
4087f9f05dc5SKevin Wolf }
4088f9f05dc5SKevin Wolf 
4089f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
4090f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4091f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4092f9f05dc5SKevin Wolf {
4093f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
4094f9f05dc5SKevin Wolf }
4095f9f05dc5SKevin Wolf 
409607f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque)
4097e7a8a783SKevin Wolf {
409807f07615SPaolo Bonzini     RwCo *rwco = opaque;
409907f07615SPaolo Bonzini 
410007f07615SPaolo Bonzini     rwco->ret = bdrv_co_flush(rwco->bs);
410107f07615SPaolo Bonzini }
410207f07615SPaolo Bonzini 
410307f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
410407f07615SPaolo Bonzini {
4105eb489bb1SKevin Wolf     int ret;
4106eb489bb1SKevin Wolf 
410729cdb251SPaolo Bonzini     if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
410807f07615SPaolo Bonzini         return 0;
4109eb489bb1SKevin Wolf     }
4110eb489bb1SKevin Wolf 
4111ca716364SKevin Wolf     /* Write back cached data to the OS even with cache=unsafe */
4112bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
4113eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_os) {
4114eb489bb1SKevin Wolf         ret = bs->drv->bdrv_co_flush_to_os(bs);
4115eb489bb1SKevin Wolf         if (ret < 0) {
4116eb489bb1SKevin Wolf             return ret;
4117eb489bb1SKevin Wolf         }
4118eb489bb1SKevin Wolf     }
4119eb489bb1SKevin Wolf 
4120ca716364SKevin Wolf     /* But don't actually force it to the disk with cache=unsafe */
4121ca716364SKevin Wolf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
4122d4c82329SKevin Wolf         goto flush_parent;
4123ca716364SKevin Wolf     }
4124ca716364SKevin Wolf 
4125bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
4126eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_disk) {
412729cdb251SPaolo Bonzini         ret = bs->drv->bdrv_co_flush_to_disk(bs);
412807f07615SPaolo Bonzini     } else if (bs->drv->bdrv_aio_flush) {
412907f07615SPaolo Bonzini         BlockDriverAIOCB *acb;
4130e7a8a783SKevin Wolf         CoroutineIOCompletion co = {
4131e7a8a783SKevin Wolf             .coroutine = qemu_coroutine_self(),
4132e7a8a783SKevin Wolf         };
4133e7a8a783SKevin Wolf 
413407f07615SPaolo Bonzini         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
413507f07615SPaolo Bonzini         if (acb == NULL) {
413629cdb251SPaolo Bonzini             ret = -EIO;
413707f07615SPaolo Bonzini         } else {
4138e7a8a783SKevin Wolf             qemu_coroutine_yield();
413929cdb251SPaolo Bonzini             ret = co.ret;
4140e7a8a783SKevin Wolf         }
414107f07615SPaolo Bonzini     } else {
414207f07615SPaolo Bonzini         /*
414307f07615SPaolo Bonzini          * Some block drivers always operate in either writethrough or unsafe
414407f07615SPaolo Bonzini          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
414507f07615SPaolo Bonzini          * know how the server works (because the behaviour is hardcoded or
414607f07615SPaolo Bonzini          * depends on server-side configuration), so we can't ensure that
414707f07615SPaolo Bonzini          * everything is safe on disk. Returning an error doesn't work because
414807f07615SPaolo Bonzini          * that would break guests even if the server operates in writethrough
414907f07615SPaolo Bonzini          * mode.
415007f07615SPaolo Bonzini          *
415107f07615SPaolo Bonzini          * Let's hope the user knows what he's doing.
415207f07615SPaolo Bonzini          */
415329cdb251SPaolo Bonzini         ret = 0;
415407f07615SPaolo Bonzini     }
415529cdb251SPaolo Bonzini     if (ret < 0) {
415629cdb251SPaolo Bonzini         return ret;
415729cdb251SPaolo Bonzini     }
415829cdb251SPaolo Bonzini 
415929cdb251SPaolo Bonzini     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
416029cdb251SPaolo Bonzini      * in the case of cache=unsafe, so there are no useless flushes.
416129cdb251SPaolo Bonzini      */
4162d4c82329SKevin Wolf flush_parent:
416329cdb251SPaolo Bonzini     return bdrv_co_flush(bs->file);
416407f07615SPaolo Bonzini }
416507f07615SPaolo Bonzini 
41660f15423cSAnthony Liguori void bdrv_invalidate_cache(BlockDriverState *bs)
41670f15423cSAnthony Liguori {
41680f15423cSAnthony Liguori     if (bs->drv && bs->drv->bdrv_invalidate_cache) {
41690f15423cSAnthony Liguori         bs->drv->bdrv_invalidate_cache(bs);
41700f15423cSAnthony Liguori     }
41710f15423cSAnthony Liguori }
41720f15423cSAnthony Liguori 
41730f15423cSAnthony Liguori void bdrv_invalidate_cache_all(void)
41740f15423cSAnthony Liguori {
41750f15423cSAnthony Liguori     BlockDriverState *bs;
41760f15423cSAnthony Liguori 
41770f15423cSAnthony Liguori     QTAILQ_FOREACH(bs, &bdrv_states, list) {
41780f15423cSAnthony Liguori         bdrv_invalidate_cache(bs);
41790f15423cSAnthony Liguori     }
41800f15423cSAnthony Liguori }
41810f15423cSAnthony Liguori 
418207789269SBenoît Canet void bdrv_clear_incoming_migration_all(void)
418307789269SBenoît Canet {
418407789269SBenoît Canet     BlockDriverState *bs;
418507789269SBenoît Canet 
418607789269SBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, list) {
418707789269SBenoît Canet         bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
418807789269SBenoît Canet     }
418907789269SBenoît Canet }
419007789269SBenoît Canet 
419107f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs)
419207f07615SPaolo Bonzini {
419307f07615SPaolo Bonzini     Coroutine *co;
419407f07615SPaolo Bonzini     RwCo rwco = {
419507f07615SPaolo Bonzini         .bs = bs,
419607f07615SPaolo Bonzini         .ret = NOT_DONE,
419707f07615SPaolo Bonzini     };
419807f07615SPaolo Bonzini 
419907f07615SPaolo Bonzini     if (qemu_in_coroutine()) {
420007f07615SPaolo Bonzini         /* Fast-path if already in coroutine context */
420107f07615SPaolo Bonzini         bdrv_flush_co_entry(&rwco);
420207f07615SPaolo Bonzini     } else {
420307f07615SPaolo Bonzini         co = qemu_coroutine_create(bdrv_flush_co_entry);
420407f07615SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
420507f07615SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
420607f07615SPaolo Bonzini             qemu_aio_wait();
420707f07615SPaolo Bonzini         }
420807f07615SPaolo Bonzini     }
420907f07615SPaolo Bonzini 
421007f07615SPaolo Bonzini     return rwco.ret;
421107f07615SPaolo Bonzini }
4212e7a8a783SKevin Wolf 
42134265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque)
42144265d620SPaolo Bonzini {
42154265d620SPaolo Bonzini     RwCo *rwco = opaque;
42164265d620SPaolo Bonzini 
42174265d620SPaolo Bonzini     rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
42184265d620SPaolo Bonzini }
42194265d620SPaolo Bonzini 
42204265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
42214265d620SPaolo Bonzini                                  int nb_sectors)
42224265d620SPaolo Bonzini {
42234265d620SPaolo Bonzini     if (!bs->drv) {
42244265d620SPaolo Bonzini         return -ENOMEDIUM;
42254265d620SPaolo Bonzini     } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
42264265d620SPaolo Bonzini         return -EIO;
42274265d620SPaolo Bonzini     } else if (bs->read_only) {
42284265d620SPaolo Bonzini         return -EROFS;
4229df702c9bSPaolo Bonzini     }
4230df702c9bSPaolo Bonzini 
4231df702c9bSPaolo Bonzini     if (bs->dirty_bitmap) {
42328f0720ecSPaolo Bonzini         bdrv_reset_dirty(bs, sector_num, nb_sectors);
4233df702c9bSPaolo Bonzini     }
4234df702c9bSPaolo Bonzini 
42359e8f1835SPaolo Bonzini     /* Do nothing if disabled.  */
42369e8f1835SPaolo Bonzini     if (!(bs->open_flags & BDRV_O_UNMAP)) {
42379e8f1835SPaolo Bonzini         return 0;
42389e8f1835SPaolo Bonzini     }
42399e8f1835SPaolo Bonzini 
4240df702c9bSPaolo Bonzini     if (bs->drv->bdrv_co_discard) {
42414265d620SPaolo Bonzini         return bs->drv->bdrv_co_discard(bs, sector_num, nb_sectors);
42424265d620SPaolo Bonzini     } else if (bs->drv->bdrv_aio_discard) {
42434265d620SPaolo Bonzini         BlockDriverAIOCB *acb;
42444265d620SPaolo Bonzini         CoroutineIOCompletion co = {
42454265d620SPaolo Bonzini             .coroutine = qemu_coroutine_self(),
42464265d620SPaolo Bonzini         };
42474265d620SPaolo Bonzini 
42484265d620SPaolo Bonzini         acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
42494265d620SPaolo Bonzini                                         bdrv_co_io_em_complete, &co);
42504265d620SPaolo Bonzini         if (acb == NULL) {
42514265d620SPaolo Bonzini             return -EIO;
42524265d620SPaolo Bonzini         } else {
42534265d620SPaolo Bonzini             qemu_coroutine_yield();
42544265d620SPaolo Bonzini             return co.ret;
42554265d620SPaolo Bonzini         }
42564265d620SPaolo Bonzini     } else {
42574265d620SPaolo Bonzini         return 0;
42584265d620SPaolo Bonzini     }
42594265d620SPaolo Bonzini }
42604265d620SPaolo Bonzini 
42614265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
42624265d620SPaolo Bonzini {
42634265d620SPaolo Bonzini     Coroutine *co;
42644265d620SPaolo Bonzini     RwCo rwco = {
42654265d620SPaolo Bonzini         .bs = bs,
42664265d620SPaolo Bonzini         .sector_num = sector_num,
42674265d620SPaolo Bonzini         .nb_sectors = nb_sectors,
42684265d620SPaolo Bonzini         .ret = NOT_DONE,
42694265d620SPaolo Bonzini     };
42704265d620SPaolo Bonzini 
42714265d620SPaolo Bonzini     if (qemu_in_coroutine()) {
42724265d620SPaolo Bonzini         /* Fast-path if already in coroutine context */
42734265d620SPaolo Bonzini         bdrv_discard_co_entry(&rwco);
42744265d620SPaolo Bonzini     } else {
42754265d620SPaolo Bonzini         co = qemu_coroutine_create(bdrv_discard_co_entry);
42764265d620SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
42774265d620SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
42784265d620SPaolo Bonzini             qemu_aio_wait();
42794265d620SPaolo Bonzini         }
42804265d620SPaolo Bonzini     }
42814265d620SPaolo Bonzini 
42824265d620SPaolo Bonzini     return rwco.ret;
42834265d620SPaolo Bonzini }
42844265d620SPaolo Bonzini 
4285f9f05dc5SKevin Wolf /**************************************************************/
428619cb3738Sbellard /* removable device support */
428719cb3738Sbellard 
428819cb3738Sbellard /**
428919cb3738Sbellard  * Return TRUE if the media is present
429019cb3738Sbellard  */
429119cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
429219cb3738Sbellard {
429319cb3738Sbellard     BlockDriver *drv = bs->drv;
4294a1aff5bfSMarkus Armbruster 
429519cb3738Sbellard     if (!drv)
429619cb3738Sbellard         return 0;
429719cb3738Sbellard     if (!drv->bdrv_is_inserted)
4298a1aff5bfSMarkus Armbruster         return 1;
4299a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
430019cb3738Sbellard }
430119cb3738Sbellard 
430219cb3738Sbellard /**
43038e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
43048e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
430519cb3738Sbellard  */
430619cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
430719cb3738Sbellard {
430819cb3738Sbellard     BlockDriver *drv = bs->drv;
430919cb3738Sbellard 
43108e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
43118e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
43128e49ca46SMarkus Armbruster     }
43138e49ca46SMarkus Armbruster     return -ENOTSUP;
431419cb3738Sbellard }
431519cb3738Sbellard 
431619cb3738Sbellard /**
431719cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
431819cb3738Sbellard  */
4319f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
432019cb3738Sbellard {
432119cb3738Sbellard     BlockDriver *drv = bs->drv;
432219cb3738Sbellard 
4323822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
4324822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
432519cb3738Sbellard     }
43266f382ed2SLuiz Capitulino 
43276f382ed2SLuiz Capitulino     if (bs->device_name[0] != '\0') {
43286f382ed2SLuiz Capitulino         bdrv_emit_qmp_eject_event(bs, eject_flag);
43296f382ed2SLuiz Capitulino     }
433019cb3738Sbellard }
433119cb3738Sbellard 
433219cb3738Sbellard /**
433319cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
433419cb3738Sbellard  * to eject it manually).
433519cb3738Sbellard  */
4336025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
433719cb3738Sbellard {
433819cb3738Sbellard     BlockDriver *drv = bs->drv;
433919cb3738Sbellard 
4340025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
4341b8c6d095SStefan Hajnoczi 
4342025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
4343025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
434419cb3738Sbellard     }
434519cb3738Sbellard }
4346985a03b0Sths 
4347985a03b0Sths /* needed for generic scsi interface */
4348985a03b0Sths 
4349985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
4350985a03b0Sths {
4351985a03b0Sths     BlockDriver *drv = bs->drv;
4352985a03b0Sths 
4353985a03b0Sths     if (drv && drv->bdrv_ioctl)
4354985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
4355985a03b0Sths     return -ENOTSUP;
4356985a03b0Sths }
43577d780669Saliguori 
4358221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
4359221f715dSaliguori         unsigned long int req, void *buf,
43607d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
43617d780669Saliguori {
4362221f715dSaliguori     BlockDriver *drv = bs->drv;
43637d780669Saliguori 
4364221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
4365221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
4366221f715dSaliguori     return NULL;
43677d780669Saliguori }
4368e268ca52Saliguori 
43697b6f9300SMarkus Armbruster void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
43707b6f9300SMarkus Armbruster {
43717b6f9300SMarkus Armbruster     bs->buffer_alignment = align;
43727b6f9300SMarkus Armbruster }
43737cd1e32aSlirans@il.ibm.com 
4374e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
4375e268ca52Saliguori {
4376e268ca52Saliguori     return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
4377e268ca52Saliguori }
43787cd1e32aSlirans@il.ibm.com 
4379c53b1c51SStefan Hajnoczi /*
4380c53b1c51SStefan Hajnoczi  * Check if all memory in this vector is sector aligned.
4381c53b1c51SStefan Hajnoczi  */
4382c53b1c51SStefan Hajnoczi bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
4383c53b1c51SStefan Hajnoczi {
4384c53b1c51SStefan Hajnoczi     int i;
4385c53b1c51SStefan Hajnoczi 
4386c53b1c51SStefan Hajnoczi     for (i = 0; i < qiov->niov; i++) {
4387c53b1c51SStefan Hajnoczi         if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {
4388c53b1c51SStefan Hajnoczi             return false;
4389c53b1c51SStefan Hajnoczi         }
4390c53b1c51SStefan Hajnoczi     }
4391c53b1c51SStefan Hajnoczi 
4392c53b1c51SStefan Hajnoczi     return true;
4393c53b1c51SStefan Hajnoczi }
4394c53b1c51SStefan Hajnoczi 
439550717e94SPaolo Bonzini void bdrv_set_dirty_tracking(BlockDriverState *bs, int granularity)
43967cd1e32aSlirans@il.ibm.com {
43977cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
4398a55eb92cSJan Kiszka 
439950717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
440050717e94SPaolo Bonzini 
440150717e94SPaolo Bonzini     if (granularity) {
440250717e94SPaolo Bonzini         granularity >>= BDRV_SECTOR_BITS;
440350717e94SPaolo Bonzini         assert(!bs->dirty_bitmap);
44048f0720ecSPaolo Bonzini         bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS);
440550717e94SPaolo Bonzini         bs->dirty_bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
44067cd1e32aSlirans@il.ibm.com     } else {
4407c6d22830SJan Kiszka         if (bs->dirty_bitmap) {
44088f0720ecSPaolo Bonzini             hbitmap_free(bs->dirty_bitmap);
4409c6d22830SJan Kiszka             bs->dirty_bitmap = NULL;
44107cd1e32aSlirans@il.ibm.com         }
44117cd1e32aSlirans@il.ibm.com     }
44127cd1e32aSlirans@il.ibm.com }
44137cd1e32aSlirans@il.ibm.com 
44147cd1e32aSlirans@il.ibm.com int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
44157cd1e32aSlirans@il.ibm.com {
44168f0720ecSPaolo Bonzini     if (bs->dirty_bitmap) {
44178f0720ecSPaolo Bonzini         return hbitmap_get(bs->dirty_bitmap, sector);
44187cd1e32aSlirans@il.ibm.com     } else {
44197cd1e32aSlirans@il.ibm.com         return 0;
44207cd1e32aSlirans@il.ibm.com     }
44217cd1e32aSlirans@il.ibm.com }
44227cd1e32aSlirans@il.ibm.com 
44238f0720ecSPaolo Bonzini void bdrv_dirty_iter_init(BlockDriverState *bs, HBitmapIter *hbi)
44241755da16SPaolo Bonzini {
44258f0720ecSPaolo Bonzini     hbitmap_iter_init(hbi, bs->dirty_bitmap, 0);
44261755da16SPaolo Bonzini }
44271755da16SPaolo Bonzini 
44281755da16SPaolo Bonzini void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
44291755da16SPaolo Bonzini                     int nr_sectors)
44301755da16SPaolo Bonzini {
44318f0720ecSPaolo Bonzini     hbitmap_set(bs->dirty_bitmap, cur_sector, nr_sectors);
44321755da16SPaolo Bonzini }
44331755da16SPaolo Bonzini 
44347cd1e32aSlirans@il.ibm.com void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
44357cd1e32aSlirans@il.ibm.com                       int nr_sectors)
44367cd1e32aSlirans@il.ibm.com {
44378f0720ecSPaolo Bonzini     hbitmap_reset(bs->dirty_bitmap, cur_sector, nr_sectors);
44387cd1e32aSlirans@il.ibm.com }
4439aaa0eb75SLiran Schour 
4440aaa0eb75SLiran Schour int64_t bdrv_get_dirty_count(BlockDriverState *bs)
4441aaa0eb75SLiran Schour {
44428f0720ecSPaolo Bonzini     if (bs->dirty_bitmap) {
4443acc906c6SPaolo Bonzini         return hbitmap_count(bs->dirty_bitmap);
44448f0720ecSPaolo Bonzini     } else {
44458f0720ecSPaolo Bonzini         return 0;
44468f0720ecSPaolo Bonzini     }
4447aaa0eb75SLiran Schour }
4448f88e1a42SJes Sorensen 
4449db593f25SMarcelo Tosatti void bdrv_set_in_use(BlockDriverState *bs, int in_use)
4450db593f25SMarcelo Tosatti {
4451db593f25SMarcelo Tosatti     assert(bs->in_use != in_use);
4452db593f25SMarcelo Tosatti     bs->in_use = in_use;
4453db593f25SMarcelo Tosatti }
4454db593f25SMarcelo Tosatti 
4455db593f25SMarcelo Tosatti int bdrv_in_use(BlockDriverState *bs)
4456db593f25SMarcelo Tosatti {
4457db593f25SMarcelo Tosatti     return bs->in_use;
4458db593f25SMarcelo Tosatti }
4459db593f25SMarcelo Tosatti 
446028a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
446128a7282aSLuiz Capitulino {
4462d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
446358e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
446428a7282aSLuiz Capitulino }
446528a7282aSLuiz Capitulino 
446628a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
446728a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
446828a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
446928a7282aSLuiz Capitulino {
4470d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
447192aa5c6dSPaolo Bonzini            (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
447292aa5c6dSPaolo Bonzini             bs->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
447392aa5c6dSPaolo Bonzini             bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
447428a7282aSLuiz Capitulino }
447528a7282aSLuiz Capitulino 
447628a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
447728a7282aSLuiz Capitulino {
4478d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
447928a7282aSLuiz Capitulino }
448028a7282aSLuiz Capitulino 
448128a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
448228a7282aSLuiz Capitulino {
448328a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
448458e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
44853bd293c3SPaolo Bonzini         if (bs->job) {
44863bd293c3SPaolo Bonzini             block_job_iostatus_reset(bs->job);
44873bd293c3SPaolo Bonzini         }
448828a7282aSLuiz Capitulino     }
448928a7282aSLuiz Capitulino }
449028a7282aSLuiz Capitulino 
449128a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
449228a7282aSLuiz Capitulino {
44933e1caa5fSPaolo Bonzini     assert(bdrv_iostatus_is_enabled(bs));
44943e1caa5fSPaolo Bonzini     if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
449558e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
449658e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
449728a7282aSLuiz Capitulino     }
449828a7282aSLuiz Capitulino }
449928a7282aSLuiz Capitulino 
4500a597e79cSChristoph Hellwig void
4501a597e79cSChristoph Hellwig bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
4502a597e79cSChristoph Hellwig         enum BlockAcctType type)
4503a597e79cSChristoph Hellwig {
4504a597e79cSChristoph Hellwig     assert(type < BDRV_MAX_IOTYPE);
4505a597e79cSChristoph Hellwig 
4506a597e79cSChristoph Hellwig     cookie->bytes = bytes;
4507c488c7f6SChristoph Hellwig     cookie->start_time_ns = get_clock();
4508a597e79cSChristoph Hellwig     cookie->type = type;
4509a597e79cSChristoph Hellwig }
4510a597e79cSChristoph Hellwig 
4511a597e79cSChristoph Hellwig void
4512a597e79cSChristoph Hellwig bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
4513a597e79cSChristoph Hellwig {
4514a597e79cSChristoph Hellwig     assert(cookie->type < BDRV_MAX_IOTYPE);
4515a597e79cSChristoph Hellwig 
4516a597e79cSChristoph Hellwig     bs->nr_bytes[cookie->type] += cookie->bytes;
4517a597e79cSChristoph Hellwig     bs->nr_ops[cookie->type]++;
4518c488c7f6SChristoph Hellwig     bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
4519a597e79cSChristoph Hellwig }
4520a597e79cSChristoph Hellwig 
4521d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
4522f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
4523f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
4524f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
4525f88e1a42SJes Sorensen {
4526f88e1a42SJes Sorensen     QEMUOptionParameter *param = NULL, *create_options = NULL;
4527d220894eSKevin Wolf     QEMUOptionParameter *backing_fmt, *backing_file, *size;
4528f88e1a42SJes Sorensen     BlockDriverState *bs = NULL;
4529f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
453096df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
4531f88e1a42SJes Sorensen     int ret = 0;
4532f88e1a42SJes Sorensen 
4533f88e1a42SJes Sorensen     /* Find driver and parse its options */
4534f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
4535f88e1a42SJes Sorensen     if (!drv) {
453671c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
4537d92ada22SLuiz Capitulino         return;
4538f88e1a42SJes Sorensen     }
4539f88e1a42SJes Sorensen 
454098289620SKevin Wolf     proto_drv = bdrv_find_protocol(filename, true);
4541f88e1a42SJes Sorensen     if (!proto_drv) {
454271c79813SLuiz Capitulino         error_setg(errp, "Unknown protocol '%s'", filename);
4543d92ada22SLuiz Capitulino         return;
4544f88e1a42SJes Sorensen     }
4545f88e1a42SJes Sorensen 
4546f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
4547f88e1a42SJes Sorensen                                               drv->create_options);
4548f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
4549f88e1a42SJes Sorensen                                               proto_drv->create_options);
4550f88e1a42SJes Sorensen 
4551f88e1a42SJes Sorensen     /* Create parameter list with default values */
4552f88e1a42SJes Sorensen     param = parse_option_parameters("", create_options, param);
4553f88e1a42SJes Sorensen 
4554f88e1a42SJes Sorensen     set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
4555f88e1a42SJes Sorensen 
4556f88e1a42SJes Sorensen     /* Parse -o options */
4557f88e1a42SJes Sorensen     if (options) {
4558f88e1a42SJes Sorensen         param = parse_option_parameters(options, create_options, param);
4559f88e1a42SJes Sorensen         if (param == NULL) {
456071c79813SLuiz Capitulino             error_setg(errp, "Invalid options for file format '%s'.", fmt);
4561f88e1a42SJes Sorensen             goto out;
4562f88e1a42SJes Sorensen         }
4563f88e1a42SJes Sorensen     }
4564f88e1a42SJes Sorensen 
4565f88e1a42SJes Sorensen     if (base_filename) {
4566f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
4567f88e1a42SJes Sorensen                                  base_filename)) {
456871c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
456971c79813SLuiz Capitulino                        fmt);
4570f88e1a42SJes Sorensen             goto out;
4571f88e1a42SJes Sorensen         }
4572f88e1a42SJes Sorensen     }
4573f88e1a42SJes Sorensen 
4574f88e1a42SJes Sorensen     if (base_fmt) {
4575f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
457671c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
457771c79813SLuiz Capitulino                              "format '%s'", fmt);
4578f88e1a42SJes Sorensen             goto out;
4579f88e1a42SJes Sorensen         }
4580f88e1a42SJes Sorensen     }
4581f88e1a42SJes Sorensen 
4582792da93aSJes Sorensen     backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
4583792da93aSJes Sorensen     if (backing_file && backing_file->value.s) {
4584792da93aSJes Sorensen         if (!strcmp(filename, backing_file->value.s)) {
458571c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
458671c79813SLuiz Capitulino                              "same filename as the backing file");
4587792da93aSJes Sorensen             goto out;
4588792da93aSJes Sorensen         }
4589792da93aSJes Sorensen     }
4590792da93aSJes Sorensen 
4591f88e1a42SJes Sorensen     backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
4592f88e1a42SJes Sorensen     if (backing_fmt && backing_fmt->value.s) {
459396df67d1SStefan Hajnoczi         backing_drv = bdrv_find_format(backing_fmt->value.s);
459496df67d1SStefan Hajnoczi         if (!backing_drv) {
459571c79813SLuiz Capitulino             error_setg(errp, "Unknown backing file format '%s'",
459671c79813SLuiz Capitulino                        backing_fmt->value.s);
4597f88e1a42SJes Sorensen             goto out;
4598f88e1a42SJes Sorensen         }
4599f88e1a42SJes Sorensen     }
4600f88e1a42SJes Sorensen 
4601f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
4602f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
4603d220894eSKevin Wolf     size = get_option_parameter(param, BLOCK_OPT_SIZE);
4604d220894eSKevin Wolf     if (size && size->value.n == -1) {
4605f88e1a42SJes Sorensen         if (backing_file && backing_file->value.s) {
4606f88e1a42SJes Sorensen             uint64_t size;
4607f88e1a42SJes Sorensen             char buf[32];
460863090dacSPaolo Bonzini             int back_flags;
460963090dacSPaolo Bonzini 
461063090dacSPaolo Bonzini             /* backing files always opened read-only */
461163090dacSPaolo Bonzini             back_flags =
461263090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
4613f88e1a42SJes Sorensen 
4614f88e1a42SJes Sorensen             bs = bdrv_new("");
4615f88e1a42SJes Sorensen 
4616de9c0cecSKevin Wolf             ret = bdrv_open(bs, backing_file->value.s, NULL, back_flags,
4617de9c0cecSKevin Wolf                             backing_drv);
4618f88e1a42SJes Sorensen             if (ret < 0) {
461971c79813SLuiz Capitulino                 error_setg_errno(errp, -ret, "Could not open '%s'",
462071c79813SLuiz Capitulino                                  backing_file->value.s);
4621f88e1a42SJes Sorensen                 goto out;
4622f88e1a42SJes Sorensen             }
4623f88e1a42SJes Sorensen             bdrv_get_geometry(bs, &size);
4624f88e1a42SJes Sorensen             size *= 512;
4625f88e1a42SJes Sorensen 
4626f88e1a42SJes Sorensen             snprintf(buf, sizeof(buf), "%" PRId64, size);
4627f88e1a42SJes Sorensen             set_option_parameter(param, BLOCK_OPT_SIZE, buf);
4628f88e1a42SJes Sorensen         } else {
462971c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
4630f88e1a42SJes Sorensen             goto out;
4631f88e1a42SJes Sorensen         }
4632f88e1a42SJes Sorensen     }
4633f88e1a42SJes Sorensen 
4634f382d43aSMiroslav Rezanina     if (!quiet) {
4635f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
4636f88e1a42SJes Sorensen         print_option_parameters(param);
4637f88e1a42SJes Sorensen         puts("");
4638f382d43aSMiroslav Rezanina     }
4639f88e1a42SJes Sorensen     ret = bdrv_create(drv, filename, param);
4640f88e1a42SJes Sorensen     if (ret < 0) {
4641f88e1a42SJes Sorensen         if (ret == -ENOTSUP) {
464271c79813SLuiz Capitulino             error_setg(errp,"Formatting or formatting option not supported for "
464371c79813SLuiz Capitulino                             "file format '%s'", fmt);
4644f88e1a42SJes Sorensen         } else if (ret == -EFBIG) {
4645f3f4d2c0SKevin Wolf             const char *cluster_size_hint = "";
4646f3f4d2c0SKevin Wolf             if (get_option_parameter(create_options, BLOCK_OPT_CLUSTER_SIZE)) {
4647f3f4d2c0SKevin Wolf                 cluster_size_hint = " (try using a larger cluster size)";
4648f3f4d2c0SKevin Wolf             }
4649f3f4d2c0SKevin Wolf             error_setg(errp, "The image size is too large for file format '%s'%s",
4650f3f4d2c0SKevin Wolf                        fmt, cluster_size_hint);
4651f88e1a42SJes Sorensen         } else {
465271c79813SLuiz Capitulino             error_setg(errp, "%s: error while creating %s: %s", filename, fmt,
465371c79813SLuiz Capitulino                        strerror(-ret));
4654f88e1a42SJes Sorensen         }
4655f88e1a42SJes Sorensen     }
4656f88e1a42SJes Sorensen 
4657f88e1a42SJes Sorensen out:
4658f88e1a42SJes Sorensen     free_option_parameters(create_options);
4659f88e1a42SJes Sorensen     free_option_parameters(param);
4660f88e1a42SJes Sorensen 
4661f88e1a42SJes Sorensen     if (bs) {
4662f88e1a42SJes Sorensen         bdrv_delete(bs);
4663f88e1a42SJes Sorensen     }
4664f88e1a42SJes Sorensen }
466585d126f3SStefan Hajnoczi 
466685d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
466785d126f3SStefan Hajnoczi {
466885d126f3SStefan Hajnoczi     /* Currently BlockDriverState always uses the main loop AioContext */
466985d126f3SStefan Hajnoczi     return qemu_get_aio_context();
467085d126f3SStefan Hajnoczi }
4671d616b224SStefan Hajnoczi 
4672d616b224SStefan Hajnoczi void bdrv_add_before_write_notifier(BlockDriverState *bs,
4673d616b224SStefan Hajnoczi                                     NotifierWithReturn *notifier)
4674d616b224SStefan Hajnoczi {
4675d616b224SStefan Hajnoczi     notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
4676d616b224SStefan Hajnoczi }
4677