xref: /openbmc/qemu/block.c (revision 6963a30d82413bea36c7545137b090b284cc2b18)
1fc01f7e7Sbellard /*
2fc01f7e7Sbellard  * QEMU System Emulator block driver
3fc01f7e7Sbellard  *
4fc01f7e7Sbellard  * Copyright (c) 2003 Fabrice Bellard
5fc01f7e7Sbellard  *
6fc01f7e7Sbellard  * Permission is hereby granted, free of charge, to any person obtaining a copy
7fc01f7e7Sbellard  * of this software and associated documentation files (the "Software"), to deal
8fc01f7e7Sbellard  * in the Software without restriction, including without limitation the rights
9fc01f7e7Sbellard  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10fc01f7e7Sbellard  * copies of the Software, and to permit persons to whom the Software is
11fc01f7e7Sbellard  * furnished to do so, subject to the following conditions:
12fc01f7e7Sbellard  *
13fc01f7e7Sbellard  * The above copyright notice and this permission notice shall be included in
14fc01f7e7Sbellard  * all copies or substantial portions of the Software.
15fc01f7e7Sbellard  *
16fc01f7e7Sbellard  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17fc01f7e7Sbellard  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18fc01f7e7Sbellard  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19fc01f7e7Sbellard  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20fc01f7e7Sbellard  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21fc01f7e7Sbellard  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22fc01f7e7Sbellard  * THE SOFTWARE.
23fc01f7e7Sbellard  */
243990d09aSblueswir1 #include "config-host.h"
25faf07963Spbrook #include "qemu-common.h"
266d519a5fSStefan Hajnoczi #include "trace.h"
2783c9089eSPaolo Bonzini #include "monitor/monitor.h"
28737e150eSPaolo Bonzini #include "block/block_int.h"
29737e150eSPaolo Bonzini #include "block/blockjob.h"
301de7afc9SPaolo Bonzini #include "qemu/module.h"
317b1b5d19SPaolo Bonzini #include "qapi/qmp/qjson.h"
329c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
331de7afc9SPaolo Bonzini #include "qemu/notify.h"
34737e150eSPaolo Bonzini #include "block/coroutine.h"
35b2023818SLuiz Capitulino #include "qmp-commands.h"
361de7afc9SPaolo Bonzini #include "qemu/timer.h"
37fc01f7e7Sbellard 
3871e72a19SJuan Quintela #ifdef CONFIG_BSD
397674e7bfSbellard #include <sys/types.h>
407674e7bfSbellard #include <sys/stat.h>
417674e7bfSbellard #include <sys/ioctl.h>
4272cf2d4fSBlue Swirl #include <sys/queue.h>
43c5e97233Sblueswir1 #ifndef __DragonFly__
447674e7bfSbellard #include <sys/disk.h>
457674e7bfSbellard #endif
46c5e97233Sblueswir1 #endif
477674e7bfSbellard 
4849dc768dSaliguori #ifdef _WIN32
4949dc768dSaliguori #include <windows.h>
5049dc768dSaliguori #endif
5149dc768dSaliguori 
521c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
531c9805a3SStefan Hajnoczi 
54470c0504SStefan Hajnoczi typedef enum {
55470c0504SStefan Hajnoczi     BDRV_REQ_COPY_ON_READ = 0x1,
56f08f2ddaSStefan Hajnoczi     BDRV_REQ_ZERO_WRITE   = 0x2,
57470c0504SStefan Hajnoczi } BdrvRequestFlags;
58470c0504SStefan Hajnoczi 
597d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
60f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
61f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
62c87c0672Saliguori         BlockDriverCompletionFunc *cb, void *opaque);
63f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
64f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
65ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque);
66f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
67f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
68f9f05dc5SKevin Wolf                                          QEMUIOVector *iov);
69f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
70f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
71f9f05dc5SKevin Wolf                                          QEMUIOVector *iov);
72c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
73470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
74470c0504SStefan Hajnoczi     BdrvRequestFlags flags);
751c9805a3SStefan Hajnoczi static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
76f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
77f08f2ddaSStefan Hajnoczi     BdrvRequestFlags flags);
78b2a61371SStefan Hajnoczi static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
79b2a61371SStefan Hajnoczi                                                int64_t sector_num,
80b2a61371SStefan Hajnoczi                                                QEMUIOVector *qiov,
81b2a61371SStefan Hajnoczi                                                int nb_sectors,
82b2a61371SStefan Hajnoczi                                                BlockDriverCompletionFunc *cb,
83b2a61371SStefan Hajnoczi                                                void *opaque,
848c5873d6SStefan Hajnoczi                                                bool is_write);
85b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque);
86621f0589SKevin Wolf static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
87621f0589SKevin Wolf     int64_t sector_num, int nb_sectors);
88ec530c81Sbellard 
8998f90dbaSZhi Yong Wu static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
9098f90dbaSZhi Yong Wu         bool is_write, double elapsed_time, uint64_t *wait);
9198f90dbaSZhi Yong Wu static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
9298f90dbaSZhi Yong Wu         double elapsed_time, uint64_t *wait);
9398f90dbaSZhi Yong Wu static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
9498f90dbaSZhi Yong Wu         bool is_write, int64_t *wait);
9598f90dbaSZhi Yong Wu 
961b7bdbc1SStefan Hajnoczi static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
971b7bdbc1SStefan Hajnoczi     QTAILQ_HEAD_INITIALIZER(bdrv_states);
987ee930d0Sblueswir1 
998a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
1008a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
101ea2384d3Sbellard 
102f9092b10SMarkus Armbruster /* The device to use for VM snapshots */
103f9092b10SMarkus Armbruster static BlockDriverState *bs_snapshots;
104f9092b10SMarkus Armbruster 
105eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
106eb852011SMarkus Armbruster static int use_bdrv_whitelist;
107eb852011SMarkus Armbruster 
1089e0b22f4SStefan Hajnoczi #ifdef _WIN32
1099e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
1109e0b22f4SStefan Hajnoczi {
1119e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
1129e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
1139e0b22f4SStefan Hajnoczi             filename[1] == ':');
1149e0b22f4SStefan Hajnoczi }
1159e0b22f4SStefan Hajnoczi 
1169e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
1179e0b22f4SStefan Hajnoczi {
1189e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
1199e0b22f4SStefan Hajnoczi         filename[2] == '\0')
1209e0b22f4SStefan Hajnoczi         return 1;
1219e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
1229e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
1239e0b22f4SStefan Hajnoczi         return 1;
1249e0b22f4SStefan Hajnoczi     return 0;
1259e0b22f4SStefan Hajnoczi }
1269e0b22f4SStefan Hajnoczi #endif
1279e0b22f4SStefan Hajnoczi 
1280563e191SZhi Yong Wu /* throttling disk I/O limits */
12998f90dbaSZhi Yong Wu void bdrv_io_limits_disable(BlockDriverState *bs)
13098f90dbaSZhi Yong Wu {
13198f90dbaSZhi Yong Wu     bs->io_limits_enabled = false;
13298f90dbaSZhi Yong Wu 
13398f90dbaSZhi Yong Wu     while (qemu_co_queue_next(&bs->throttled_reqs));
13498f90dbaSZhi Yong Wu 
13598f90dbaSZhi Yong Wu     if (bs->block_timer) {
13698f90dbaSZhi Yong Wu         qemu_del_timer(bs->block_timer);
13798f90dbaSZhi Yong Wu         qemu_free_timer(bs->block_timer);
13898f90dbaSZhi Yong Wu         bs->block_timer = NULL;
13998f90dbaSZhi Yong Wu     }
14098f90dbaSZhi Yong Wu 
14198f90dbaSZhi Yong Wu     bs->slice_start = 0;
14298f90dbaSZhi Yong Wu     bs->slice_end   = 0;
14398f90dbaSZhi Yong Wu     bs->slice_time  = 0;
14498f90dbaSZhi Yong Wu     memset(&bs->io_base, 0, sizeof(bs->io_base));
14598f90dbaSZhi Yong Wu }
14698f90dbaSZhi Yong Wu 
1470563e191SZhi Yong Wu static void bdrv_block_timer(void *opaque)
1480563e191SZhi Yong Wu {
1490563e191SZhi Yong Wu     BlockDriverState *bs = opaque;
1500563e191SZhi Yong Wu 
1510563e191SZhi Yong Wu     qemu_co_queue_next(&bs->throttled_reqs);
1520563e191SZhi Yong Wu }
1530563e191SZhi Yong Wu 
1540563e191SZhi Yong Wu void bdrv_io_limits_enable(BlockDriverState *bs)
1550563e191SZhi Yong Wu {
1560563e191SZhi Yong Wu     qemu_co_queue_init(&bs->throttled_reqs);
1570563e191SZhi Yong Wu     bs->block_timer = qemu_new_timer_ns(vm_clock, bdrv_block_timer, bs);
1580563e191SZhi Yong Wu     bs->io_limits_enabled = true;
1590563e191SZhi Yong Wu }
1600563e191SZhi Yong Wu 
1610563e191SZhi Yong Wu bool bdrv_io_limits_enabled(BlockDriverState *bs)
1620563e191SZhi Yong Wu {
1630563e191SZhi Yong Wu     BlockIOLimit *io_limits = &bs->io_limits;
1640563e191SZhi Yong Wu     return io_limits->bps[BLOCK_IO_LIMIT_READ]
1650563e191SZhi Yong Wu          || io_limits->bps[BLOCK_IO_LIMIT_WRITE]
1660563e191SZhi Yong Wu          || io_limits->bps[BLOCK_IO_LIMIT_TOTAL]
1670563e191SZhi Yong Wu          || io_limits->iops[BLOCK_IO_LIMIT_READ]
1680563e191SZhi Yong Wu          || io_limits->iops[BLOCK_IO_LIMIT_WRITE]
1690563e191SZhi Yong Wu          || io_limits->iops[BLOCK_IO_LIMIT_TOTAL];
1700563e191SZhi Yong Wu }
1710563e191SZhi Yong Wu 
17298f90dbaSZhi Yong Wu static void bdrv_io_limits_intercept(BlockDriverState *bs,
17398f90dbaSZhi Yong Wu                                      bool is_write, int nb_sectors)
17498f90dbaSZhi Yong Wu {
17598f90dbaSZhi Yong Wu     int64_t wait_time = -1;
17698f90dbaSZhi Yong Wu 
17798f90dbaSZhi Yong Wu     if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
17898f90dbaSZhi Yong Wu         qemu_co_queue_wait(&bs->throttled_reqs);
17998f90dbaSZhi Yong Wu     }
18098f90dbaSZhi Yong Wu 
18198f90dbaSZhi Yong Wu     /* In fact, we hope to keep each request's timing, in FIFO mode. The next
18298f90dbaSZhi Yong Wu      * throttled requests will not be dequeued until the current request is
18398f90dbaSZhi Yong Wu      * allowed to be serviced. So if the current request still exceeds the
18498f90dbaSZhi Yong Wu      * limits, it will be inserted to the head. All requests followed it will
18598f90dbaSZhi Yong Wu      * be still in throttled_reqs queue.
18698f90dbaSZhi Yong Wu      */
18798f90dbaSZhi Yong Wu 
18898f90dbaSZhi Yong Wu     while (bdrv_exceed_io_limits(bs, nb_sectors, is_write, &wait_time)) {
18998f90dbaSZhi Yong Wu         qemu_mod_timer(bs->block_timer,
19098f90dbaSZhi Yong Wu                        wait_time + qemu_get_clock_ns(vm_clock));
19198f90dbaSZhi Yong Wu         qemu_co_queue_wait_insert_head(&bs->throttled_reqs);
19298f90dbaSZhi Yong Wu     }
19398f90dbaSZhi Yong Wu 
19498f90dbaSZhi Yong Wu     qemu_co_queue_next(&bs->throttled_reqs);
19598f90dbaSZhi Yong Wu }
19698f90dbaSZhi Yong Wu 
1979e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
1989e0b22f4SStefan Hajnoczi static int path_has_protocol(const char *path)
1999e0b22f4SStefan Hajnoczi {
200947995c0SPaolo Bonzini     const char *p;
201947995c0SPaolo Bonzini 
2029e0b22f4SStefan Hajnoczi #ifdef _WIN32
2039e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
2049e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
2059e0b22f4SStefan Hajnoczi         return 0;
2069e0b22f4SStefan Hajnoczi     }
207947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
208947995c0SPaolo Bonzini #else
209947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
2109e0b22f4SStefan Hajnoczi #endif
2119e0b22f4SStefan Hajnoczi 
212947995c0SPaolo Bonzini     return *p == ':';
2139e0b22f4SStefan Hajnoczi }
2149e0b22f4SStefan Hajnoczi 
21583f64091Sbellard int path_is_absolute(const char *path)
21683f64091Sbellard {
21721664424Sbellard #ifdef _WIN32
21821664424Sbellard     /* specific case for names like: "\\.\d:" */
219f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
22021664424Sbellard         return 1;
221f53f4da9SPaolo Bonzini     }
222f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
2233b9f94e1Sbellard #else
224f53f4da9SPaolo Bonzini     return (*path == '/');
2253b9f94e1Sbellard #endif
22683f64091Sbellard }
22783f64091Sbellard 
22883f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
22983f64091Sbellard    path to it by considering it is relative to base_path. URL are
23083f64091Sbellard    supported. */
23183f64091Sbellard void path_combine(char *dest, int dest_size,
23283f64091Sbellard                   const char *base_path,
23383f64091Sbellard                   const char *filename)
23483f64091Sbellard {
23583f64091Sbellard     const char *p, *p1;
23683f64091Sbellard     int len;
23783f64091Sbellard 
23883f64091Sbellard     if (dest_size <= 0)
23983f64091Sbellard         return;
24083f64091Sbellard     if (path_is_absolute(filename)) {
24183f64091Sbellard         pstrcpy(dest, dest_size, filename);
24283f64091Sbellard     } else {
24383f64091Sbellard         p = strchr(base_path, ':');
24483f64091Sbellard         if (p)
24583f64091Sbellard             p++;
24683f64091Sbellard         else
24783f64091Sbellard             p = base_path;
2483b9f94e1Sbellard         p1 = strrchr(base_path, '/');
2493b9f94e1Sbellard #ifdef _WIN32
2503b9f94e1Sbellard         {
2513b9f94e1Sbellard             const char *p2;
2523b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
2533b9f94e1Sbellard             if (!p1 || p2 > p1)
2543b9f94e1Sbellard                 p1 = p2;
2553b9f94e1Sbellard         }
2563b9f94e1Sbellard #endif
25783f64091Sbellard         if (p1)
25883f64091Sbellard             p1++;
25983f64091Sbellard         else
26083f64091Sbellard             p1 = base_path;
26183f64091Sbellard         if (p1 > p)
26283f64091Sbellard             p = p1;
26383f64091Sbellard         len = p - base_path;
26483f64091Sbellard         if (len > dest_size - 1)
26583f64091Sbellard             len = dest_size - 1;
26683f64091Sbellard         memcpy(dest, base_path, len);
26783f64091Sbellard         dest[len] = '\0';
26883f64091Sbellard         pstrcat(dest, dest_size, filename);
26983f64091Sbellard     }
27083f64091Sbellard }
27183f64091Sbellard 
272dc5a1371SPaolo Bonzini void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
273dc5a1371SPaolo Bonzini {
274dc5a1371SPaolo Bonzini     if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
275dc5a1371SPaolo Bonzini         pstrcpy(dest, sz, bs->backing_file);
276dc5a1371SPaolo Bonzini     } else {
277dc5a1371SPaolo Bonzini         path_combine(dest, sz, bs->filename, bs->backing_file);
278dc5a1371SPaolo Bonzini     }
279dc5a1371SPaolo Bonzini }
280dc5a1371SPaolo Bonzini 
2815efa9d5aSAnthony Liguori void bdrv_register(BlockDriver *bdrv)
282ea2384d3Sbellard {
2838c5873d6SStefan Hajnoczi     /* Block drivers without coroutine functions need emulation */
2848c5873d6SStefan Hajnoczi     if (!bdrv->bdrv_co_readv) {
285f9f05dc5SKevin Wolf         bdrv->bdrv_co_readv = bdrv_co_readv_em;
286f9f05dc5SKevin Wolf         bdrv->bdrv_co_writev = bdrv_co_writev_em;
287f9f05dc5SKevin Wolf 
288f8c35c1dSStefan Hajnoczi         /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
289f8c35c1dSStefan Hajnoczi          * the block driver lacks aio we need to emulate that too.
290f8c35c1dSStefan Hajnoczi          */
291f9f05dc5SKevin Wolf         if (!bdrv->bdrv_aio_readv) {
29283f64091Sbellard             /* add AIO emulation layer */
293f141eafeSaliguori             bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
294f141eafeSaliguori             bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
29583f64091Sbellard         }
296f9f05dc5SKevin Wolf     }
297b2e12bc6SChristoph Hellwig 
2988a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
299ea2384d3Sbellard }
300b338082bSbellard 
301b338082bSbellard /* create a new block device (by default it is empty) */
302b338082bSbellard BlockDriverState *bdrv_new(const char *device_name)
303fc01f7e7Sbellard {
3041b7bdbc1SStefan Hajnoczi     BlockDriverState *bs;
305b338082bSbellard 
3067267c094SAnthony Liguori     bs = g_malloc0(sizeof(BlockDriverState));
307b338082bSbellard     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
308ea2384d3Sbellard     if (device_name[0] != '\0') {
3091b7bdbc1SStefan Hajnoczi         QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
310ea2384d3Sbellard     }
31128a7282aSLuiz Capitulino     bdrv_iostatus_disable(bs);
312d7d512f6SPaolo Bonzini     notifier_list_init(&bs->close_notifiers);
313d7d512f6SPaolo Bonzini 
314b338082bSbellard     return bs;
315b338082bSbellard }
316b338082bSbellard 
317d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
318d7d512f6SPaolo Bonzini {
319d7d512f6SPaolo Bonzini     notifier_list_add(&bs->close_notifiers, notify);
320d7d512f6SPaolo Bonzini }
321d7d512f6SPaolo Bonzini 
322ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
323ea2384d3Sbellard {
324ea2384d3Sbellard     BlockDriver *drv1;
3258a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
3268a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
327ea2384d3Sbellard             return drv1;
328ea2384d3Sbellard         }
3298a22f02aSStefan Hajnoczi     }
330ea2384d3Sbellard     return NULL;
331ea2384d3Sbellard }
332ea2384d3Sbellard 
333eb852011SMarkus Armbruster static int bdrv_is_whitelisted(BlockDriver *drv)
334eb852011SMarkus Armbruster {
335eb852011SMarkus Armbruster     static const char *whitelist[] = {
336eb852011SMarkus Armbruster         CONFIG_BDRV_WHITELIST
337eb852011SMarkus Armbruster     };
338eb852011SMarkus Armbruster     const char **p;
339eb852011SMarkus Armbruster 
340eb852011SMarkus Armbruster     if (!whitelist[0])
341eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
342eb852011SMarkus Armbruster 
343eb852011SMarkus Armbruster     for (p = whitelist; *p; p++) {
344eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
345eb852011SMarkus Armbruster             return 1;
346eb852011SMarkus Armbruster         }
347eb852011SMarkus Armbruster     }
348eb852011SMarkus Armbruster     return 0;
349eb852011SMarkus Armbruster }
350eb852011SMarkus Armbruster 
351eb852011SMarkus Armbruster BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
352eb852011SMarkus Armbruster {
353eb852011SMarkus Armbruster     BlockDriver *drv = bdrv_find_format(format_name);
354eb852011SMarkus Armbruster     return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
355eb852011SMarkus Armbruster }
356eb852011SMarkus Armbruster 
3575b7e1542SZhi Yong Wu typedef struct CreateCo {
3585b7e1542SZhi Yong Wu     BlockDriver *drv;
3595b7e1542SZhi Yong Wu     char *filename;
3605b7e1542SZhi Yong Wu     QEMUOptionParameter *options;
3615b7e1542SZhi Yong Wu     int ret;
3625b7e1542SZhi Yong Wu } CreateCo;
3635b7e1542SZhi Yong Wu 
3645b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
3655b7e1542SZhi Yong Wu {
3665b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
3675b7e1542SZhi Yong Wu     assert(cco->drv);
3685b7e1542SZhi Yong Wu 
3695b7e1542SZhi Yong Wu     cco->ret = cco->drv->bdrv_create(cco->filename, cco->options);
3705b7e1542SZhi Yong Wu }
3715b7e1542SZhi Yong Wu 
3720e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
3730e7e1989SKevin Wolf     QEMUOptionParameter *options)
374ea2384d3Sbellard {
3755b7e1542SZhi Yong Wu     int ret;
3760e7e1989SKevin Wolf 
3775b7e1542SZhi Yong Wu     Coroutine *co;
3785b7e1542SZhi Yong Wu     CreateCo cco = {
3795b7e1542SZhi Yong Wu         .drv = drv,
3805b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
3815b7e1542SZhi Yong Wu         .options = options,
3825b7e1542SZhi Yong Wu         .ret = NOT_DONE,
3835b7e1542SZhi Yong Wu     };
3845b7e1542SZhi Yong Wu 
3855b7e1542SZhi Yong Wu     if (!drv->bdrv_create) {
38680168bffSLuiz Capitulino         ret = -ENOTSUP;
38780168bffSLuiz Capitulino         goto out;
3885b7e1542SZhi Yong Wu     }
3895b7e1542SZhi Yong Wu 
3905b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
3915b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
3925b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
3935b7e1542SZhi Yong Wu     } else {
3945b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
3955b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
3965b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
3975b7e1542SZhi Yong Wu             qemu_aio_wait();
3985b7e1542SZhi Yong Wu         }
3995b7e1542SZhi Yong Wu     }
4005b7e1542SZhi Yong Wu 
4015b7e1542SZhi Yong Wu     ret = cco.ret;
4025b7e1542SZhi Yong Wu 
40380168bffSLuiz Capitulino out:
40480168bffSLuiz Capitulino     g_free(cco.filename);
4055b7e1542SZhi Yong Wu     return ret;
406ea2384d3Sbellard }
407ea2384d3Sbellard 
40884a12e66SChristoph Hellwig int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
40984a12e66SChristoph Hellwig {
41084a12e66SChristoph Hellwig     BlockDriver *drv;
41184a12e66SChristoph Hellwig 
412b50cbabcSMORITA Kazutaka     drv = bdrv_find_protocol(filename);
41384a12e66SChristoph Hellwig     if (drv == NULL) {
41416905d71SStefan Hajnoczi         return -ENOENT;
41584a12e66SChristoph Hellwig     }
41684a12e66SChristoph Hellwig 
41784a12e66SChristoph Hellwig     return bdrv_create(drv, filename, options);
41884a12e66SChristoph Hellwig }
41984a12e66SChristoph Hellwig 
420eba25057SJim Meyering /*
421eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
422eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
423eba25057SJim Meyering  */
424eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
425eba25057SJim Meyering {
426d5249393Sbellard #ifdef _WIN32
4273b9f94e1Sbellard     char temp_dir[MAX_PATH];
428eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
429eba25057SJim Meyering        have length MAX_PATH or greater.  */
430eba25057SJim Meyering     assert(size >= MAX_PATH);
431eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
432eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
433eba25057SJim Meyering             ? 0 : -GetLastError());
434d5249393Sbellard #else
435ea2384d3Sbellard     int fd;
4367ccfb2ebSblueswir1     const char *tmpdir;
4370badc1eeSaurel32     tmpdir = getenv("TMPDIR");
4380badc1eeSaurel32     if (!tmpdir)
4390badc1eeSaurel32         tmpdir = "/tmp";
440eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
441eba25057SJim Meyering         return -EOVERFLOW;
442ea2384d3Sbellard     }
443eba25057SJim Meyering     fd = mkstemp(filename);
444fe235a06SDunrong Huang     if (fd < 0) {
445fe235a06SDunrong Huang         return -errno;
446fe235a06SDunrong Huang     }
447fe235a06SDunrong Huang     if (close(fd) != 0) {
448fe235a06SDunrong Huang         unlink(filename);
449eba25057SJim Meyering         return -errno;
450eba25057SJim Meyering     }
451eba25057SJim Meyering     return 0;
452d5249393Sbellard #endif
453eba25057SJim Meyering }
454ea2384d3Sbellard 
455f3a5d3f8SChristoph Hellwig /*
456f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
457f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
458f3a5d3f8SChristoph Hellwig  */
459f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
460f3a5d3f8SChristoph Hellwig {
461508c7cb3SChristoph Hellwig     int score_max = 0, score;
462508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
463f3a5d3f8SChristoph Hellwig 
4648a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
465508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
466508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
467508c7cb3SChristoph Hellwig             if (score > score_max) {
468508c7cb3SChristoph Hellwig                 score_max = score;
469508c7cb3SChristoph Hellwig                 drv = d;
470f3a5d3f8SChristoph Hellwig             }
471508c7cb3SChristoph Hellwig         }
472f3a5d3f8SChristoph Hellwig     }
473f3a5d3f8SChristoph Hellwig 
474508c7cb3SChristoph Hellwig     return drv;
475f3a5d3f8SChristoph Hellwig }
476f3a5d3f8SChristoph Hellwig 
477b50cbabcSMORITA Kazutaka BlockDriver *bdrv_find_protocol(const char *filename)
47884a12e66SChristoph Hellwig {
47984a12e66SChristoph Hellwig     BlockDriver *drv1;
48084a12e66SChristoph Hellwig     char protocol[128];
48184a12e66SChristoph Hellwig     int len;
48284a12e66SChristoph Hellwig     const char *p;
48384a12e66SChristoph Hellwig 
48466f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
48566f82ceeSKevin Wolf 
48639508e7aSChristoph Hellwig     /*
48739508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
48839508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
48939508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
49039508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
49139508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
49239508e7aSChristoph Hellwig      */
49384a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
49439508e7aSChristoph Hellwig     if (drv1) {
49584a12e66SChristoph Hellwig         return drv1;
49684a12e66SChristoph Hellwig     }
49739508e7aSChristoph Hellwig 
4989e0b22f4SStefan Hajnoczi     if (!path_has_protocol(filename)) {
49939508e7aSChristoph Hellwig         return bdrv_find_format("file");
50039508e7aSChristoph Hellwig     }
5019e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
5029e0b22f4SStefan Hajnoczi     assert(p != NULL);
50384a12e66SChristoph Hellwig     len = p - filename;
50484a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
50584a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
50684a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
50784a12e66SChristoph Hellwig     protocol[len] = '\0';
50884a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
50984a12e66SChristoph Hellwig         if (drv1->protocol_name &&
51084a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
51184a12e66SChristoph Hellwig             return drv1;
51284a12e66SChristoph Hellwig         }
51384a12e66SChristoph Hellwig     }
51484a12e66SChristoph Hellwig     return NULL;
51584a12e66SChristoph Hellwig }
51684a12e66SChristoph Hellwig 
517f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
518f500a6d3SKevin Wolf                              BlockDriver **pdrv)
519ea2384d3Sbellard {
520f500a6d3SKevin Wolf     int score, score_max;
521ea2384d3Sbellard     BlockDriver *drv1, *drv;
52283f64091Sbellard     uint8_t buf[2048];
523f500a6d3SKevin Wolf     int ret = 0;
524f8ea0b00SNicholas Bellinger 
52508a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
5268e895599SPaolo Bonzini     if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
527c98ac35dSStefan Weil         drv = bdrv_find_format("raw");
528c98ac35dSStefan Weil         if (!drv) {
529c98ac35dSStefan Weil             ret = -ENOENT;
530c98ac35dSStefan Weil         }
531c98ac35dSStefan Weil         *pdrv = drv;
532c98ac35dSStefan Weil         return ret;
5331a396859SNicholas A. Bellinger     }
534f8ea0b00SNicholas Bellinger 
53583f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
536ea2384d3Sbellard     if (ret < 0) {
537c98ac35dSStefan Weil         *pdrv = NULL;
538c98ac35dSStefan Weil         return ret;
539ea2384d3Sbellard     }
540ea2384d3Sbellard 
541ea2384d3Sbellard     score_max = 0;
54284a12e66SChristoph Hellwig     drv = NULL;
5438a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
54483f64091Sbellard         if (drv1->bdrv_probe) {
545ea2384d3Sbellard             score = drv1->bdrv_probe(buf, ret, filename);
546ea2384d3Sbellard             if (score > score_max) {
547ea2384d3Sbellard                 score_max = score;
548ea2384d3Sbellard                 drv = drv1;
549ea2384d3Sbellard             }
550ea2384d3Sbellard         }
55183f64091Sbellard     }
552c98ac35dSStefan Weil     if (!drv) {
553c98ac35dSStefan Weil         ret = -ENOENT;
554c98ac35dSStefan Weil     }
555c98ac35dSStefan Weil     *pdrv = drv;
556c98ac35dSStefan Weil     return ret;
557ea2384d3Sbellard }
558ea2384d3Sbellard 
55951762288SStefan Hajnoczi /**
56051762288SStefan Hajnoczi  * Set the current 'total_sectors' value
56151762288SStefan Hajnoczi  */
56251762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
56351762288SStefan Hajnoczi {
56451762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
56551762288SStefan Hajnoczi 
566396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
567396759adSNicholas Bellinger     if (bs->sg)
568396759adSNicholas Bellinger         return 0;
569396759adSNicholas Bellinger 
57051762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
57151762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
57251762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
57351762288SStefan Hajnoczi         if (length < 0) {
57451762288SStefan Hajnoczi             return length;
57551762288SStefan Hajnoczi         }
57651762288SStefan Hajnoczi         hint = length >> BDRV_SECTOR_BITS;
57751762288SStefan Hajnoczi     }
57851762288SStefan Hajnoczi 
57951762288SStefan Hajnoczi     bs->total_sectors = hint;
58051762288SStefan Hajnoczi     return 0;
58151762288SStefan Hajnoczi }
58251762288SStefan Hajnoczi 
583c3993cdcSStefan Hajnoczi /**
5849e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
5859e8f1835SPaolo Bonzini  *
5869e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
5879e8f1835SPaolo Bonzini  */
5889e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
5899e8f1835SPaolo Bonzini {
5909e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
5919e8f1835SPaolo Bonzini 
5929e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
5939e8f1835SPaolo Bonzini         /* do nothing */
5949e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
5959e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
5969e8f1835SPaolo Bonzini     } else {
5979e8f1835SPaolo Bonzini         return -1;
5989e8f1835SPaolo Bonzini     }
5999e8f1835SPaolo Bonzini 
6009e8f1835SPaolo Bonzini     return 0;
6019e8f1835SPaolo Bonzini }
6029e8f1835SPaolo Bonzini 
6039e8f1835SPaolo Bonzini /**
604c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
605c3993cdcSStefan Hajnoczi  *
606c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
607c3993cdcSStefan Hajnoczi  */
608c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
609c3993cdcSStefan Hajnoczi {
610c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
611c3993cdcSStefan Hajnoczi 
612c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
613c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
61492196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
61592196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
616c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
617c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
618c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
619c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
620c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
621c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
622c3993cdcSStefan Hajnoczi         /* this is the default */
623c3993cdcSStefan Hajnoczi     } else {
624c3993cdcSStefan Hajnoczi         return -1;
625c3993cdcSStefan Hajnoczi     }
626c3993cdcSStefan Hajnoczi 
627c3993cdcSStefan Hajnoczi     return 0;
628c3993cdcSStefan Hajnoczi }
629c3993cdcSStefan Hajnoczi 
63053fec9d3SStefan Hajnoczi /**
63153fec9d3SStefan Hajnoczi  * The copy-on-read flag is actually a reference count so multiple users may
63253fec9d3SStefan Hajnoczi  * use the feature without worrying about clobbering its previous state.
63353fec9d3SStefan Hajnoczi  * Copy-on-read stays enabled until all users have called to disable it.
63453fec9d3SStefan Hajnoczi  */
63553fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs)
63653fec9d3SStefan Hajnoczi {
63753fec9d3SStefan Hajnoczi     bs->copy_on_read++;
63853fec9d3SStefan Hajnoczi }
63953fec9d3SStefan Hajnoczi 
64053fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs)
64153fec9d3SStefan Hajnoczi {
64253fec9d3SStefan Hajnoczi     assert(bs->copy_on_read > 0);
64353fec9d3SStefan Hajnoczi     bs->copy_on_read--;
64453fec9d3SStefan Hajnoczi }
64553fec9d3SStefan Hajnoczi 
6467b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
6477b272452SKevin Wolf {
6487b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
6497b272452SKevin Wolf 
6507b272452SKevin Wolf     /*
6517b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
6527b272452SKevin Wolf      * image.
6537b272452SKevin Wolf      */
6547b272452SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
6557b272452SKevin Wolf 
6567b272452SKevin Wolf     /*
6577b272452SKevin Wolf      * Snapshots should be writable.
6587b272452SKevin Wolf      */
6597b272452SKevin Wolf     if (bs->is_temporary) {
6607b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
6617b272452SKevin Wolf     }
6627b272452SKevin Wolf 
6637b272452SKevin Wolf     return open_flags;
6647b272452SKevin Wolf }
6657b272452SKevin Wolf 
666b6ce07aaSKevin Wolf /*
66757915332SKevin Wolf  * Common part for opening disk images and files
668b6ad491aSKevin Wolf  *
669b6ad491aSKevin Wolf  * Removes all processed options from *options.
67057915332SKevin Wolf  */
671f500a6d3SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
672b6ad491aSKevin Wolf     const char *filename, QDict *options,
67357915332SKevin Wolf     int flags, BlockDriver *drv)
67457915332SKevin Wolf {
67557915332SKevin Wolf     int ret, open_flags;
67657915332SKevin Wolf 
67757915332SKevin Wolf     assert(drv != NULL);
6786405875cSPaolo Bonzini     assert(bs->file == NULL);
679707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
68057915332SKevin Wolf 
68128dcee10SStefan Hajnoczi     trace_bdrv_open_common(bs, filename, flags, drv->format_name);
68228dcee10SStefan Hajnoczi 
68357915332SKevin Wolf     bs->open_flags = flags;
68457915332SKevin Wolf     bs->buffer_alignment = 512;
68557915332SKevin Wolf 
68653fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
68753fec9d3SStefan Hajnoczi     if ((flags & BDRV_O_RDWR) && (flags & BDRV_O_COPY_ON_READ)) {
68853fec9d3SStefan Hajnoczi         bdrv_enable_copy_on_read(bs);
68953fec9d3SStefan Hajnoczi     }
69053fec9d3SStefan Hajnoczi 
69157915332SKevin Wolf     pstrcpy(bs->filename, sizeof(bs->filename), filename);
69257915332SKevin Wolf 
69357915332SKevin Wolf     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
69457915332SKevin Wolf         return -ENOTSUP;
69557915332SKevin Wolf     }
69657915332SKevin Wolf 
69757915332SKevin Wolf     bs->drv = drv;
6987267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
69957915332SKevin Wolf 
70003f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
7017b272452SKevin Wolf     open_flags = bdrv_open_flags(bs, flags);
70257915332SKevin Wolf 
703be028adcSJeff Cody     bs->read_only = !(open_flags & BDRV_O_RDWR);
704e7c63796SStefan Hajnoczi 
70566f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
70666f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
707f500a6d3SKevin Wolf         if (file != NULL) {
708f500a6d3SKevin Wolf             bdrv_swap(file, bs);
709f500a6d3SKevin Wolf             ret = 0;
71066f82ceeSKevin Wolf         } else {
711787e4a85SKevin Wolf             ret = drv->bdrv_file_open(bs, filename, options, open_flags);
71266f82ceeSKevin Wolf         }
713f500a6d3SKevin Wolf     } else {
714f500a6d3SKevin Wolf         assert(file != NULL);
715f500a6d3SKevin Wolf         bs->file = file;
716b6ad491aSKevin Wolf         ret = drv->bdrv_open(bs, options, open_flags);
71766f82ceeSKevin Wolf     }
71866f82ceeSKevin Wolf 
71957915332SKevin Wolf     if (ret < 0) {
72057915332SKevin Wolf         goto free_and_fail;
72157915332SKevin Wolf     }
72257915332SKevin Wolf 
72351762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
72451762288SStefan Hajnoczi     if (ret < 0) {
72551762288SStefan Hajnoczi         goto free_and_fail;
72657915332SKevin Wolf     }
72751762288SStefan Hajnoczi 
72857915332SKevin Wolf #ifndef _WIN32
72957915332SKevin Wolf     if (bs->is_temporary) {
73057915332SKevin Wolf         unlink(filename);
73157915332SKevin Wolf     }
73257915332SKevin Wolf #endif
73357915332SKevin Wolf     return 0;
73457915332SKevin Wolf 
73557915332SKevin Wolf free_and_fail:
73666f82ceeSKevin Wolf     bs->file = NULL;
7377267c094SAnthony Liguori     g_free(bs->opaque);
73857915332SKevin Wolf     bs->opaque = NULL;
73957915332SKevin Wolf     bs->drv = NULL;
74057915332SKevin Wolf     return ret;
74157915332SKevin Wolf }
74257915332SKevin Wolf 
74357915332SKevin Wolf /*
744b6ce07aaSKevin Wolf  * Opens a file using a protocol (file, host_device, nbd, ...)
745787e4a85SKevin Wolf  *
746787e4a85SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
747787e4a85SKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
748787e4a85SKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
749787e4a85SKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_file_open.
750b6ce07aaSKevin Wolf  */
751787e4a85SKevin Wolf int bdrv_file_open(BlockDriverState **pbs, const char *filename,
752787e4a85SKevin Wolf                    QDict *options, int flags)
753b338082bSbellard {
75483f64091Sbellard     BlockDriverState *bs;
7556db95603SChristoph Hellwig     BlockDriver *drv;
75683f64091Sbellard     int ret;
7573b0d4f61Sbellard 
758b50cbabcSMORITA Kazutaka     drv = bdrv_find_protocol(filename);
7596db95603SChristoph Hellwig     if (!drv) {
760707ff828SKevin Wolf         QDECREF(options);
7616db95603SChristoph Hellwig         return -ENOENT;
7626db95603SChristoph Hellwig     }
7636db95603SChristoph Hellwig 
764707ff828SKevin Wolf     /* NULL means an empty set of options */
765707ff828SKevin Wolf     if (options == NULL) {
766707ff828SKevin Wolf         options = qdict_new();
7673b0d4f61Sbellard     }
768707ff828SKevin Wolf 
769707ff828SKevin Wolf     bs = bdrv_new("");
770707ff828SKevin Wolf     bs->options = options;
771707ff828SKevin Wolf     options = qdict_clone_shallow(options);
772707ff828SKevin Wolf 
773*6963a30dSKevin Wolf     if (drv->bdrv_parse_filename) {
774*6963a30dSKevin Wolf         Error *local_err = NULL;
775*6963a30dSKevin Wolf         drv->bdrv_parse_filename(filename, options, &local_err);
776*6963a30dSKevin Wolf         if (error_is_set(&local_err)) {
777*6963a30dSKevin Wolf             qerror_report_err(local_err);
778*6963a30dSKevin Wolf             error_free(local_err);
779*6963a30dSKevin Wolf             ret = -EINVAL;
780*6963a30dSKevin Wolf             goto fail;
781*6963a30dSKevin Wolf         }
782*6963a30dSKevin Wolf     }
783*6963a30dSKevin Wolf 
784707ff828SKevin Wolf     ret = bdrv_open_common(bs, NULL, filename, options, flags, drv);
785707ff828SKevin Wolf     if (ret < 0) {
786707ff828SKevin Wolf         goto fail;
787707ff828SKevin Wolf     }
788707ff828SKevin Wolf 
789707ff828SKevin Wolf     /* Check if any unknown options were used */
790707ff828SKevin Wolf     if (qdict_size(options) != 0) {
791707ff828SKevin Wolf         const QDictEntry *entry = qdict_first(options);
792707ff828SKevin Wolf         qerror_report(ERROR_CLASS_GENERIC_ERROR, "Block protocol '%s' doesn't "
793707ff828SKevin Wolf                       "support the option '%s'",
794707ff828SKevin Wolf                       drv->format_name, entry->key);
795707ff828SKevin Wolf         ret = -EINVAL;
796707ff828SKevin Wolf         goto fail;
797707ff828SKevin Wolf     }
798707ff828SKevin Wolf     QDECREF(options);
799707ff828SKevin Wolf 
80071d0770cSaliguori     bs->growable = 1;
80183f64091Sbellard     *pbs = bs;
80283f64091Sbellard     return 0;
803707ff828SKevin Wolf 
804707ff828SKevin Wolf fail:
805707ff828SKevin Wolf     QDECREF(options);
806707ff828SKevin Wolf     if (!bs->drv) {
807707ff828SKevin Wolf         QDECREF(bs->options);
808707ff828SKevin Wolf     }
809707ff828SKevin Wolf     bdrv_delete(bs);
810707ff828SKevin Wolf     return ret;
8113b0d4f61Sbellard }
8123b0d4f61Sbellard 
8139156df12SPaolo Bonzini int bdrv_open_backing_file(BlockDriverState *bs)
8149156df12SPaolo Bonzini {
8159156df12SPaolo Bonzini     char backing_filename[PATH_MAX];
8169156df12SPaolo Bonzini     int back_flags, ret;
8179156df12SPaolo Bonzini     BlockDriver *back_drv = NULL;
8189156df12SPaolo Bonzini 
8199156df12SPaolo Bonzini     if (bs->backing_hd != NULL) {
8209156df12SPaolo Bonzini         return 0;
8219156df12SPaolo Bonzini     }
8229156df12SPaolo Bonzini 
8239156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
8249156df12SPaolo Bonzini     if (bs->backing_file[0] == '\0') {
8259156df12SPaolo Bonzini         return 0;
8269156df12SPaolo Bonzini     }
8279156df12SPaolo Bonzini 
8289156df12SPaolo Bonzini     bs->backing_hd = bdrv_new("");
8299156df12SPaolo Bonzini     bdrv_get_full_backing_filename(bs, backing_filename,
8309156df12SPaolo Bonzini                                    sizeof(backing_filename));
8319156df12SPaolo Bonzini 
8329156df12SPaolo Bonzini     if (bs->backing_format[0] != '\0') {
8339156df12SPaolo Bonzini         back_drv = bdrv_find_format(bs->backing_format);
8349156df12SPaolo Bonzini     }
8359156df12SPaolo Bonzini 
8369156df12SPaolo Bonzini     /* backing files always opened read-only */
8379156df12SPaolo Bonzini     back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT);
8389156df12SPaolo Bonzini 
839de9c0cecSKevin Wolf     ret = bdrv_open(bs->backing_hd, backing_filename, NULL,
840de9c0cecSKevin Wolf                     back_flags, back_drv);
8419156df12SPaolo Bonzini     if (ret < 0) {
8429156df12SPaolo Bonzini         bdrv_delete(bs->backing_hd);
8439156df12SPaolo Bonzini         bs->backing_hd = NULL;
8449156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
8459156df12SPaolo Bonzini         return ret;
8469156df12SPaolo Bonzini     }
8479156df12SPaolo Bonzini     return 0;
8489156df12SPaolo Bonzini }
8499156df12SPaolo Bonzini 
850707ff828SKevin Wolf static void extract_subqdict(QDict *src, QDict **dst, const char *start)
851707ff828SKevin Wolf {
852707ff828SKevin Wolf     const QDictEntry *entry, *next;
853707ff828SKevin Wolf     const char *p;
854707ff828SKevin Wolf 
855707ff828SKevin Wolf     *dst = qdict_new();
856707ff828SKevin Wolf     entry = qdict_first(src);
857707ff828SKevin Wolf 
858707ff828SKevin Wolf     while (entry != NULL) {
859707ff828SKevin Wolf         next = qdict_next(src, entry);
860707ff828SKevin Wolf         if (strstart(entry->key, start, &p)) {
861707ff828SKevin Wolf             qobject_incref(entry->value);
862707ff828SKevin Wolf             qdict_put_obj(*dst, p, entry->value);
863707ff828SKevin Wolf             qdict_del(src, entry->key);
864707ff828SKevin Wolf         }
865707ff828SKevin Wolf         entry = next;
866707ff828SKevin Wolf     }
867707ff828SKevin Wolf }
868707ff828SKevin Wolf 
869b6ce07aaSKevin Wolf /*
870b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
871de9c0cecSKevin Wolf  *
872de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
873de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
874de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
875de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
876b6ce07aaSKevin Wolf  */
877de9c0cecSKevin Wolf int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,
878de9c0cecSKevin Wolf               int flags, BlockDriver *drv)
879ea2384d3Sbellard {
880b6ce07aaSKevin Wolf     int ret;
88189c9bc3dSStefan Weil     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
88289c9bc3dSStefan Weil     char tmp_filename[PATH_MAX + 1];
883f500a6d3SKevin Wolf     BlockDriverState *file = NULL;
884707ff828SKevin Wolf     QDict *file_options = NULL;
88533e3963eSbellard 
886de9c0cecSKevin Wolf     /* NULL means an empty set of options */
887de9c0cecSKevin Wolf     if (options == NULL) {
888de9c0cecSKevin Wolf         options = qdict_new();
889de9c0cecSKevin Wolf     }
890de9c0cecSKevin Wolf 
891de9c0cecSKevin Wolf     bs->options = options;
892b6ad491aSKevin Wolf     options = qdict_clone_shallow(options);
893de9c0cecSKevin Wolf 
894de9c0cecSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay */
89583f64091Sbellard     if (flags & BDRV_O_SNAPSHOT) {
896ea2384d3Sbellard         BlockDriverState *bs1;
897ea2384d3Sbellard         int64_t total_size;
89891a073a9SKevin Wolf         BlockDriver *bdrv_qcow2;
89991a073a9SKevin Wolf         QEMUOptionParameter *options;
900b6ce07aaSKevin Wolf         char backing_filename[PATH_MAX];
90133e3963eSbellard 
902ea2384d3Sbellard         /* if snapshot, we create a temporary backing file and open it
903ea2384d3Sbellard            instead of opening 'filename' directly */
904ea2384d3Sbellard 
905ea2384d3Sbellard         /* if there is a backing file, use it */
906ea2384d3Sbellard         bs1 = bdrv_new("");
907de9c0cecSKevin Wolf         ret = bdrv_open(bs1, filename, NULL, 0, drv);
90851d7c00cSaliguori         if (ret < 0) {
909ea2384d3Sbellard             bdrv_delete(bs1);
910de9c0cecSKevin Wolf             goto fail;
911ea2384d3Sbellard         }
9123e82990bSJes Sorensen         total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
9137c96d46eSaliguori 
914ea2384d3Sbellard         bdrv_delete(bs1);
915ea2384d3Sbellard 
916eba25057SJim Meyering         ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));
917eba25057SJim Meyering         if (ret < 0) {
918de9c0cecSKevin Wolf             goto fail;
919eba25057SJim Meyering         }
9207c96d46eSaliguori 
9217c96d46eSaliguori         /* Real path is meaningless for protocols */
9224d70655bSStefan Hajnoczi         if (path_has_protocol(filename)) {
9237c96d46eSaliguori             snprintf(backing_filename, sizeof(backing_filename),
9247c96d46eSaliguori                      "%s", filename);
925de9c0cecSKevin Wolf         } else if (!realpath(filename, backing_filename)) {
926de9c0cecSKevin Wolf             ret = -errno;
927de9c0cecSKevin Wolf             goto fail;
928de9c0cecSKevin Wolf         }
9297c96d46eSaliguori 
93091a073a9SKevin Wolf         bdrv_qcow2 = bdrv_find_format("qcow2");
93191a073a9SKevin Wolf         options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
93291a073a9SKevin Wolf 
9333e82990bSJes Sorensen         set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
93491a073a9SKevin Wolf         set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
93591a073a9SKevin Wolf         if (drv) {
93691a073a9SKevin Wolf             set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
93791a073a9SKevin Wolf                 drv->format_name);
93891a073a9SKevin Wolf         }
93991a073a9SKevin Wolf 
94091a073a9SKevin Wolf         ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
941d748768cSJan Kiszka         free_option_parameters(options);
94251d7c00cSaliguori         if (ret < 0) {
943de9c0cecSKevin Wolf             goto fail;
944ea2384d3Sbellard         }
94591a073a9SKevin Wolf 
946ea2384d3Sbellard         filename = tmp_filename;
94791a073a9SKevin Wolf         drv = bdrv_qcow2;
948ea2384d3Sbellard         bs->is_temporary = 1;
949ea2384d3Sbellard     }
950ea2384d3Sbellard 
951f500a6d3SKevin Wolf     /* Open image file without format layer */
952be028adcSJeff Cody     if (flags & BDRV_O_RDWR) {
953be028adcSJeff Cody         flags |= BDRV_O_ALLOW_RDWR;
954be028adcSJeff Cody     }
955be028adcSJeff Cody 
956707ff828SKevin Wolf     extract_subqdict(options, &file_options, "file.");
957707ff828SKevin Wolf 
958707ff828SKevin Wolf     ret = bdrv_file_open(&file, filename, file_options,
959707ff828SKevin Wolf                          bdrv_open_flags(bs, flags));
960f500a6d3SKevin Wolf     if (ret < 0) {
961de9c0cecSKevin Wolf         goto fail;
962f500a6d3SKevin Wolf     }
963f500a6d3SKevin Wolf 
964f500a6d3SKevin Wolf     /* Find the right image format driver */
965f500a6d3SKevin Wolf     if (!drv) {
966f500a6d3SKevin Wolf         ret = find_image_format(file, filename, &drv);
967f500a6d3SKevin Wolf     }
968f500a6d3SKevin Wolf 
969f500a6d3SKevin Wolf     if (!drv) {
970f500a6d3SKevin Wolf         goto unlink_and_fail;
971f500a6d3SKevin Wolf     }
972f500a6d3SKevin Wolf 
973b6ce07aaSKevin Wolf     /* Open the image */
974b6ad491aSKevin Wolf     ret = bdrv_open_common(bs, file, filename, options, flags, drv);
975b6ce07aaSKevin Wolf     if (ret < 0) {
9766987307cSChristoph Hellwig         goto unlink_and_fail;
9776987307cSChristoph Hellwig     }
9786987307cSChristoph Hellwig 
979f500a6d3SKevin Wolf     if (bs->file != file) {
980f500a6d3SKevin Wolf         bdrv_delete(file);
981f500a6d3SKevin Wolf         file = NULL;
982f500a6d3SKevin Wolf     }
983f500a6d3SKevin Wolf 
984b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
9859156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
9869156df12SPaolo Bonzini         ret = bdrv_open_backing_file(bs);
987b6ce07aaSKevin Wolf         if (ret < 0) {
988b6ad491aSKevin Wolf             goto close_and_fail;
989b6ce07aaSKevin Wolf         }
990b6ce07aaSKevin Wolf     }
991b6ce07aaSKevin Wolf 
992b6ad491aSKevin Wolf     /* Check if any unknown options were used */
993b6ad491aSKevin Wolf     if (qdict_size(options) != 0) {
994b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
995b6ad491aSKevin Wolf         qerror_report(ERROR_CLASS_GENERIC_ERROR, "Block format '%s' used by "
996b6ad491aSKevin Wolf             "device '%s' doesn't support the option '%s'",
997b6ad491aSKevin Wolf             drv->format_name, bs->device_name, entry->key);
998b6ad491aSKevin Wolf 
999b6ad491aSKevin Wolf         ret = -EINVAL;
1000b6ad491aSKevin Wolf         goto close_and_fail;
1001b6ad491aSKevin Wolf     }
1002b6ad491aSKevin Wolf     QDECREF(options);
1003b6ad491aSKevin Wolf 
1004b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
10057d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
1006b6ce07aaSKevin Wolf     }
1007b6ce07aaSKevin Wolf 
100898f90dbaSZhi Yong Wu     /* throttling disk I/O limits */
100998f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
101098f90dbaSZhi Yong Wu         bdrv_io_limits_enable(bs);
101198f90dbaSZhi Yong Wu     }
101298f90dbaSZhi Yong Wu 
1013b6ce07aaSKevin Wolf     return 0;
1014b6ce07aaSKevin Wolf 
1015b6ce07aaSKevin Wolf unlink_and_fail:
1016f500a6d3SKevin Wolf     if (file != NULL) {
1017f500a6d3SKevin Wolf         bdrv_delete(file);
1018f500a6d3SKevin Wolf     }
1019b6ce07aaSKevin Wolf     if (bs->is_temporary) {
1020b6ce07aaSKevin Wolf         unlink(filename);
1021b6ce07aaSKevin Wolf     }
1022de9c0cecSKevin Wolf fail:
1023de9c0cecSKevin Wolf     QDECREF(bs->options);
1024b6ad491aSKevin Wolf     QDECREF(options);
1025de9c0cecSKevin Wolf     bs->options = NULL;
1026b6ad491aSKevin Wolf     return ret;
1027de9c0cecSKevin Wolf 
1028b6ad491aSKevin Wolf close_and_fail:
1029b6ad491aSKevin Wolf     bdrv_close(bs);
1030b6ad491aSKevin Wolf     QDECREF(options);
1031b6ce07aaSKevin Wolf     return ret;
1032b6ce07aaSKevin Wolf }
1033b6ce07aaSKevin Wolf 
1034e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1035e971aa12SJeff Cody      bool prepared;
1036e971aa12SJeff Cody      BDRVReopenState state;
1037e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1038e971aa12SJeff Cody } BlockReopenQueueEntry;
1039e971aa12SJeff Cody 
1040e971aa12SJeff Cody /*
1041e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1042e971aa12SJeff Cody  * reopen of multiple devices.
1043e971aa12SJeff Cody  *
1044e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1045e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1046e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1047e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1048e971aa12SJeff Cody  * atomic 'set'.
1049e971aa12SJeff Cody  *
1050e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1051e971aa12SJeff Cody  *
1052e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1053e971aa12SJeff Cody  *
1054e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1055e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1056e971aa12SJeff Cody  *
1057e971aa12SJeff Cody  */
1058e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1059e971aa12SJeff Cody                                     BlockDriverState *bs, int flags)
1060e971aa12SJeff Cody {
1061e971aa12SJeff Cody     assert(bs != NULL);
1062e971aa12SJeff Cody 
1063e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
1064e971aa12SJeff Cody     if (bs_queue == NULL) {
1065e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1066e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1067e971aa12SJeff Cody     }
1068e971aa12SJeff Cody 
1069e971aa12SJeff Cody     if (bs->file) {
1070e971aa12SJeff Cody         bdrv_reopen_queue(bs_queue, bs->file, flags);
1071e971aa12SJeff Cody     }
1072e971aa12SJeff Cody 
1073e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1074e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1075e971aa12SJeff Cody 
1076e971aa12SJeff Cody     bs_entry->state.bs = bs;
1077e971aa12SJeff Cody     bs_entry->state.flags = flags;
1078e971aa12SJeff Cody 
1079e971aa12SJeff Cody     return bs_queue;
1080e971aa12SJeff Cody }
1081e971aa12SJeff Cody 
1082e971aa12SJeff Cody /*
1083e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1084e971aa12SJeff Cody  *
1085e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1086e971aa12SJeff Cody  * via bdrv_reopen_queue().
1087e971aa12SJeff Cody  *
1088e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1089e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1090e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1091e971aa12SJeff Cody  * data cleaned up.
1092e971aa12SJeff Cody  *
1093e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1094e971aa12SJeff Cody  * to all devices.
1095e971aa12SJeff Cody  *
1096e971aa12SJeff Cody  */
1097e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1098e971aa12SJeff Cody {
1099e971aa12SJeff Cody     int ret = -1;
1100e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1101e971aa12SJeff Cody     Error *local_err = NULL;
1102e971aa12SJeff Cody 
1103e971aa12SJeff Cody     assert(bs_queue != NULL);
1104e971aa12SJeff Cody 
1105e971aa12SJeff Cody     bdrv_drain_all();
1106e971aa12SJeff Cody 
1107e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1108e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1109e971aa12SJeff Cody             error_propagate(errp, local_err);
1110e971aa12SJeff Cody             goto cleanup;
1111e971aa12SJeff Cody         }
1112e971aa12SJeff Cody         bs_entry->prepared = true;
1113e971aa12SJeff Cody     }
1114e971aa12SJeff Cody 
1115e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1116e971aa12SJeff Cody      * changes
1117e971aa12SJeff Cody      */
1118e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1119e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1120e971aa12SJeff Cody     }
1121e971aa12SJeff Cody 
1122e971aa12SJeff Cody     ret = 0;
1123e971aa12SJeff Cody 
1124e971aa12SJeff Cody cleanup:
1125e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1126e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1127e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1128e971aa12SJeff Cody         }
1129e971aa12SJeff Cody         g_free(bs_entry);
1130e971aa12SJeff Cody     }
1131e971aa12SJeff Cody     g_free(bs_queue);
1132e971aa12SJeff Cody     return ret;
1133e971aa12SJeff Cody }
1134e971aa12SJeff Cody 
1135e971aa12SJeff Cody 
1136e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1137e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1138e971aa12SJeff Cody {
1139e971aa12SJeff Cody     int ret = -1;
1140e971aa12SJeff Cody     Error *local_err = NULL;
1141e971aa12SJeff Cody     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1142e971aa12SJeff Cody 
1143e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1144e971aa12SJeff Cody     if (local_err != NULL) {
1145e971aa12SJeff Cody         error_propagate(errp, local_err);
1146e971aa12SJeff Cody     }
1147e971aa12SJeff Cody     return ret;
1148e971aa12SJeff Cody }
1149e971aa12SJeff Cody 
1150e971aa12SJeff Cody 
1151e971aa12SJeff Cody /*
1152e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1153e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1154e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1155e971aa12SJeff Cody  *
1156e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1157e971aa12SJeff Cody  * flags are the new open flags
1158e971aa12SJeff Cody  * queue is the reopen queue
1159e971aa12SJeff Cody  *
1160e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1161e971aa12SJeff Cody  * as well.
1162e971aa12SJeff Cody  *
1163e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1164e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1165e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1166e971aa12SJeff Cody  *
1167e971aa12SJeff Cody  */
1168e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1169e971aa12SJeff Cody                         Error **errp)
1170e971aa12SJeff Cody {
1171e971aa12SJeff Cody     int ret = -1;
1172e971aa12SJeff Cody     Error *local_err = NULL;
1173e971aa12SJeff Cody     BlockDriver *drv;
1174e971aa12SJeff Cody 
1175e971aa12SJeff Cody     assert(reopen_state != NULL);
1176e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1177e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1178e971aa12SJeff Cody 
1179e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1180e971aa12SJeff Cody      * to r/w */
1181e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1182e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
1183e971aa12SJeff Cody         error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1184e971aa12SJeff Cody                   reopen_state->bs->device_name);
1185e971aa12SJeff Cody         goto error;
1186e971aa12SJeff Cody     }
1187e971aa12SJeff Cody 
1188e971aa12SJeff Cody 
1189e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1190e971aa12SJeff Cody     if (ret) {
1191e971aa12SJeff Cody         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1192e971aa12SJeff Cody                   strerror(-ret));
1193e971aa12SJeff Cody         goto error;
1194e971aa12SJeff Cody     }
1195e971aa12SJeff Cody 
1196e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1197e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1198e971aa12SJeff Cody         if (ret) {
1199e971aa12SJeff Cody             if (local_err != NULL) {
1200e971aa12SJeff Cody                 error_propagate(errp, local_err);
1201e971aa12SJeff Cody             } else {
1202e971aa12SJeff Cody                 error_set(errp, QERR_OPEN_FILE_FAILED,
1203e971aa12SJeff Cody                           reopen_state->bs->filename);
1204e971aa12SJeff Cody             }
1205e971aa12SJeff Cody             goto error;
1206e971aa12SJeff Cody         }
1207e971aa12SJeff Cody     } else {
1208e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1209e971aa12SJeff Cody          * handler for each supported drv. */
1210e971aa12SJeff Cody         error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1211e971aa12SJeff Cody                   drv->format_name, reopen_state->bs->device_name,
1212e971aa12SJeff Cody                  "reopening of file");
1213e971aa12SJeff Cody         ret = -1;
1214e971aa12SJeff Cody         goto error;
1215e971aa12SJeff Cody     }
1216e971aa12SJeff Cody 
1217e971aa12SJeff Cody     ret = 0;
1218e971aa12SJeff Cody 
1219e971aa12SJeff Cody error:
1220e971aa12SJeff Cody     return ret;
1221e971aa12SJeff Cody }
1222e971aa12SJeff Cody 
1223e971aa12SJeff Cody /*
1224e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1225e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1226e971aa12SJeff Cody  * the active BlockDriverState contents.
1227e971aa12SJeff Cody  */
1228e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1229e971aa12SJeff Cody {
1230e971aa12SJeff Cody     BlockDriver *drv;
1231e971aa12SJeff Cody 
1232e971aa12SJeff Cody     assert(reopen_state != NULL);
1233e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1234e971aa12SJeff Cody     assert(drv != NULL);
1235e971aa12SJeff Cody 
1236e971aa12SJeff Cody     /* If there are any driver level actions to take */
1237e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1238e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1239e971aa12SJeff Cody     }
1240e971aa12SJeff Cody 
1241e971aa12SJeff Cody     /* set BDS specific flags now */
1242e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1243e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1244e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1245e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1246e971aa12SJeff Cody }
1247e971aa12SJeff Cody 
1248e971aa12SJeff Cody /*
1249e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1250e971aa12SJeff Cody  * reopen_state
1251e971aa12SJeff Cody  */
1252e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1253e971aa12SJeff Cody {
1254e971aa12SJeff Cody     BlockDriver *drv;
1255e971aa12SJeff Cody 
1256e971aa12SJeff Cody     assert(reopen_state != NULL);
1257e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1258e971aa12SJeff Cody     assert(drv != NULL);
1259e971aa12SJeff Cody 
1260e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1261e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1262e971aa12SJeff Cody     }
1263e971aa12SJeff Cody }
1264e971aa12SJeff Cody 
1265e971aa12SJeff Cody 
1266fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1267fc01f7e7Sbellard {
126880ccf93bSLiu Yuan     bdrv_flush(bs);
12693e914655SPaolo Bonzini     if (bs->job) {
12703e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
12713e914655SPaolo Bonzini     }
12727094f12fSKevin Wolf     bdrv_drain_all();
1273d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
12747094f12fSKevin Wolf 
12753cbc002cSPaolo Bonzini     if (bs->drv) {
1276f9092b10SMarkus Armbruster         if (bs == bs_snapshots) {
1277f9092b10SMarkus Armbruster             bs_snapshots = NULL;
1278f9092b10SMarkus Armbruster         }
1279557df6acSStefan Hajnoczi         if (bs->backing_hd) {
1280ea2384d3Sbellard             bdrv_delete(bs->backing_hd);
1281557df6acSStefan Hajnoczi             bs->backing_hd = NULL;
1282557df6acSStefan Hajnoczi         }
1283ea2384d3Sbellard         bs->drv->bdrv_close(bs);
12847267c094SAnthony Liguori         g_free(bs->opaque);
1285ea2384d3Sbellard #ifdef _WIN32
1286ea2384d3Sbellard         if (bs->is_temporary) {
1287ea2384d3Sbellard             unlink(bs->filename);
1288ea2384d3Sbellard         }
128967b915a5Sbellard #endif
1290ea2384d3Sbellard         bs->opaque = NULL;
1291ea2384d3Sbellard         bs->drv = NULL;
129253fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1293a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1294a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
12956405875cSPaolo Bonzini         bs->total_sectors = 0;
12966405875cSPaolo Bonzini         bs->encrypted = 0;
12976405875cSPaolo Bonzini         bs->valid_key = 0;
12986405875cSPaolo Bonzini         bs->sg = 0;
12996405875cSPaolo Bonzini         bs->growable = 0;
1300de9c0cecSKevin Wolf         QDECREF(bs->options);
1301de9c0cecSKevin Wolf         bs->options = NULL;
1302b338082bSbellard 
130366f82ceeSKevin Wolf         if (bs->file != NULL) {
13040ac9377dSPaolo Bonzini             bdrv_delete(bs->file);
13050ac9377dSPaolo Bonzini             bs->file = NULL;
130666f82ceeSKevin Wolf         }
13079ca11154SPavel Hrdina     }
130866f82ceeSKevin Wolf 
13097d4b4ba5SMarkus Armbruster     bdrv_dev_change_media_cb(bs, false);
131098f90dbaSZhi Yong Wu 
131198f90dbaSZhi Yong Wu     /*throttling disk I/O limits*/
131298f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
131398f90dbaSZhi Yong Wu         bdrv_io_limits_disable(bs);
131498f90dbaSZhi Yong Wu     }
1315b338082bSbellard }
1316b338082bSbellard 
13172bc93fedSMORITA Kazutaka void bdrv_close_all(void)
13182bc93fedSMORITA Kazutaka {
13192bc93fedSMORITA Kazutaka     BlockDriverState *bs;
13202bc93fedSMORITA Kazutaka 
13212bc93fedSMORITA Kazutaka     QTAILQ_FOREACH(bs, &bdrv_states, list) {
13222bc93fedSMORITA Kazutaka         bdrv_close(bs);
13232bc93fedSMORITA Kazutaka     }
13242bc93fedSMORITA Kazutaka }
13252bc93fedSMORITA Kazutaka 
1326922453bcSStefan Hajnoczi /*
1327922453bcSStefan Hajnoczi  * Wait for pending requests to complete across all BlockDriverStates
1328922453bcSStefan Hajnoczi  *
1329922453bcSStefan Hajnoczi  * This function does not flush data to disk, use bdrv_flush_all() for that
1330922453bcSStefan Hajnoczi  * after calling this function.
13314c355d53SZhi Yong Wu  *
13324c355d53SZhi Yong Wu  * Note that completion of an asynchronous I/O operation can trigger any
13334c355d53SZhi Yong Wu  * number of other I/O operations on other devices---for example a coroutine
13344c355d53SZhi Yong Wu  * can be arbitrarily complex and a constant flow of I/O can come until the
13354c355d53SZhi Yong Wu  * coroutine is complete.  Because of this, it is not possible to have a
13364c355d53SZhi Yong Wu  * function to drain a single device's I/O queue.
1337922453bcSStefan Hajnoczi  */
1338922453bcSStefan Hajnoczi void bdrv_drain_all(void)
1339922453bcSStefan Hajnoczi {
1340922453bcSStefan Hajnoczi     BlockDriverState *bs;
13414c355d53SZhi Yong Wu     bool busy;
1342922453bcSStefan Hajnoczi 
13434c355d53SZhi Yong Wu     do {
13444c355d53SZhi Yong Wu         busy = qemu_aio_wait();
13454c355d53SZhi Yong Wu 
13464c355d53SZhi Yong Wu         /* FIXME: We do not have timer support here, so this is effectively
13474c355d53SZhi Yong Wu          * a busy wait.
13484c355d53SZhi Yong Wu          */
13494c355d53SZhi Yong Wu         QTAILQ_FOREACH(bs, &bdrv_states, list) {
13504c355d53SZhi Yong Wu             if (!qemu_co_queue_empty(&bs->throttled_reqs)) {
13514c355d53SZhi Yong Wu                 qemu_co_queue_restart_all(&bs->throttled_reqs);
13524c355d53SZhi Yong Wu                 busy = true;
13534c355d53SZhi Yong Wu             }
13544c355d53SZhi Yong Wu         }
13554c355d53SZhi Yong Wu     } while (busy);
1356922453bcSStefan Hajnoczi 
1357922453bcSStefan Hajnoczi     /* If requests are still pending there is a bug somewhere */
1358922453bcSStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1359922453bcSStefan Hajnoczi         assert(QLIST_EMPTY(&bs->tracked_requests));
1360922453bcSStefan Hajnoczi         assert(qemu_co_queue_empty(&bs->throttled_reqs));
1361922453bcSStefan Hajnoczi     }
1362922453bcSStefan Hajnoczi }
1363922453bcSStefan Hajnoczi 
1364d22b2f41SRyan Harper /* make a BlockDriverState anonymous by removing from bdrv_state list.
1365d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
1366d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
1367d22b2f41SRyan Harper {
1368d22b2f41SRyan Harper     if (bs->device_name[0] != '\0') {
1369d22b2f41SRyan Harper         QTAILQ_REMOVE(&bdrv_states, bs, list);
1370d22b2f41SRyan Harper     }
1371d22b2f41SRyan Harper     bs->device_name[0] = '\0';
1372d22b2f41SRyan Harper }
1373d22b2f41SRyan Harper 
1374e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs)
1375e023b2e2SPaolo Bonzini {
1376e023b2e2SPaolo Bonzini     if (bs->drv && bs->drv->bdrv_rebind) {
1377e023b2e2SPaolo Bonzini         bs->drv->bdrv_rebind(bs);
1378e023b2e2SPaolo Bonzini     }
1379e023b2e2SPaolo Bonzini }
1380e023b2e2SPaolo Bonzini 
13814ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
13824ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
13834ddc07caSPaolo Bonzini {
13844ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
13854ddc07caSPaolo Bonzini     bs_dest->open_flags         = bs_src->open_flags;
13864ddc07caSPaolo Bonzini 
13874ddc07caSPaolo Bonzini     /* dev info */
13884ddc07caSPaolo Bonzini     bs_dest->dev_ops            = bs_src->dev_ops;
13894ddc07caSPaolo Bonzini     bs_dest->dev_opaque         = bs_src->dev_opaque;
13904ddc07caSPaolo Bonzini     bs_dest->dev                = bs_src->dev;
13914ddc07caSPaolo Bonzini     bs_dest->buffer_alignment   = bs_src->buffer_alignment;
13924ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
13934ddc07caSPaolo Bonzini 
13944ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
13954ddc07caSPaolo Bonzini 
13964ddc07caSPaolo Bonzini     /* i/o timing parameters */
13974ddc07caSPaolo Bonzini     bs_dest->slice_time         = bs_src->slice_time;
13984ddc07caSPaolo Bonzini     bs_dest->slice_start        = bs_src->slice_start;
13994ddc07caSPaolo Bonzini     bs_dest->slice_end          = bs_src->slice_end;
14004ddc07caSPaolo Bonzini     bs_dest->io_limits          = bs_src->io_limits;
14014ddc07caSPaolo Bonzini     bs_dest->io_base            = bs_src->io_base;
14024ddc07caSPaolo Bonzini     bs_dest->throttled_reqs     = bs_src->throttled_reqs;
14034ddc07caSPaolo Bonzini     bs_dest->block_timer        = bs_src->block_timer;
14044ddc07caSPaolo Bonzini     bs_dest->io_limits_enabled  = bs_src->io_limits_enabled;
14054ddc07caSPaolo Bonzini 
14064ddc07caSPaolo Bonzini     /* r/w error */
14074ddc07caSPaolo Bonzini     bs_dest->on_read_error      = bs_src->on_read_error;
14084ddc07caSPaolo Bonzini     bs_dest->on_write_error     = bs_src->on_write_error;
14094ddc07caSPaolo Bonzini 
14104ddc07caSPaolo Bonzini     /* i/o status */
14114ddc07caSPaolo Bonzini     bs_dest->iostatus_enabled   = bs_src->iostatus_enabled;
14124ddc07caSPaolo Bonzini     bs_dest->iostatus           = bs_src->iostatus;
14134ddc07caSPaolo Bonzini 
14144ddc07caSPaolo Bonzini     /* dirty bitmap */
14154ddc07caSPaolo Bonzini     bs_dest->dirty_bitmap       = bs_src->dirty_bitmap;
14164ddc07caSPaolo Bonzini 
14174ddc07caSPaolo Bonzini     /* job */
14184ddc07caSPaolo Bonzini     bs_dest->in_use             = bs_src->in_use;
14194ddc07caSPaolo Bonzini     bs_dest->job                = bs_src->job;
14204ddc07caSPaolo Bonzini 
14214ddc07caSPaolo Bonzini     /* keep the same entry in bdrv_states */
14224ddc07caSPaolo Bonzini     pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
14234ddc07caSPaolo Bonzini             bs_src->device_name);
14244ddc07caSPaolo Bonzini     bs_dest->list = bs_src->list;
14254ddc07caSPaolo Bonzini }
14264ddc07caSPaolo Bonzini 
14274ddc07caSPaolo Bonzini /*
14284ddc07caSPaolo Bonzini  * Swap bs contents for two image chains while they are live,
14294ddc07caSPaolo Bonzini  * while keeping required fields on the BlockDriverState that is
14304ddc07caSPaolo Bonzini  * actually attached to a device.
14314ddc07caSPaolo Bonzini  *
14324ddc07caSPaolo Bonzini  * This will modify the BlockDriverState fields, and swap contents
14334ddc07caSPaolo Bonzini  * between bs_new and bs_old. Both bs_new and bs_old are modified.
14344ddc07caSPaolo Bonzini  *
14354ddc07caSPaolo Bonzini  * bs_new is required to be anonymous.
14364ddc07caSPaolo Bonzini  *
14374ddc07caSPaolo Bonzini  * This function does not create any image files.
14384ddc07caSPaolo Bonzini  */
14394ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
14404ddc07caSPaolo Bonzini {
14414ddc07caSPaolo Bonzini     BlockDriverState tmp;
14424ddc07caSPaolo Bonzini 
14434ddc07caSPaolo Bonzini     /* bs_new must be anonymous and shouldn't have anything fancy enabled */
14444ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
14454ddc07caSPaolo Bonzini     assert(bs_new->dirty_bitmap == NULL);
14464ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
14474ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
14484ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
14494ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
14504ddc07caSPaolo Bonzini     assert(bs_new->block_timer == NULL);
14514ddc07caSPaolo Bonzini 
14524ddc07caSPaolo Bonzini     tmp = *bs_new;
14534ddc07caSPaolo Bonzini     *bs_new = *bs_old;
14544ddc07caSPaolo Bonzini     *bs_old = tmp;
14554ddc07caSPaolo Bonzini 
14564ddc07caSPaolo Bonzini     /* there are some fields that should not be swapped, move them back */
14574ddc07caSPaolo Bonzini     bdrv_move_feature_fields(&tmp, bs_old);
14584ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_old, bs_new);
14594ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_new, &tmp);
14604ddc07caSPaolo Bonzini 
14614ddc07caSPaolo Bonzini     /* bs_new shouldn't be in bdrv_states even after the swap!  */
14624ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
14634ddc07caSPaolo Bonzini 
14644ddc07caSPaolo Bonzini     /* Check a few fields that should remain attached to the device */
14654ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
14664ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
14674ddc07caSPaolo Bonzini     assert(bs_new->in_use == 0);
14684ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
14694ddc07caSPaolo Bonzini     assert(bs_new->block_timer == NULL);
14704ddc07caSPaolo Bonzini 
14714ddc07caSPaolo Bonzini     bdrv_rebind(bs_new);
14724ddc07caSPaolo Bonzini     bdrv_rebind(bs_old);
14734ddc07caSPaolo Bonzini }
14744ddc07caSPaolo Bonzini 
14758802d1fdSJeff Cody /*
14768802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
14778802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
14788802d1fdSJeff Cody  *
14798802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
14808802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
14818802d1fdSJeff Cody  *
1482f6801b83SJeff Cody  * bs_new is required to be anonymous.
1483f6801b83SJeff Cody  *
14848802d1fdSJeff Cody  * This function does not create any image files.
14858802d1fdSJeff Cody  */
14868802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
14878802d1fdSJeff Cody {
14884ddc07caSPaolo Bonzini     bdrv_swap(bs_new, bs_top);
14898802d1fdSJeff Cody 
14908802d1fdSJeff Cody     /* The contents of 'tmp' will become bs_top, as we are
14918802d1fdSJeff Cody      * swapping bs_new and bs_top contents. */
14924ddc07caSPaolo Bonzini     bs_top->backing_hd = bs_new;
14934ddc07caSPaolo Bonzini     bs_top->open_flags &= ~BDRV_O_NO_BACKING;
14944ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
14954ddc07caSPaolo Bonzini             bs_new->filename);
14964ddc07caSPaolo Bonzini     pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
14974ddc07caSPaolo Bonzini             bs_new->drv ? bs_new->drv->format_name : "");
14988802d1fdSJeff Cody }
14998802d1fdSJeff Cody 
1500b338082bSbellard void bdrv_delete(BlockDriverState *bs)
1501b338082bSbellard {
1502fa879d62SMarkus Armbruster     assert(!bs->dev);
15033e914655SPaolo Bonzini     assert(!bs->job);
15043e914655SPaolo Bonzini     assert(!bs->in_use);
150518846deeSMarkus Armbruster 
15061b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
1507d22b2f41SRyan Harper     bdrv_make_anon(bs);
150834c6f050Saurel32 
1509b338082bSbellard     bdrv_close(bs);
151066f82ceeSKevin Wolf 
1511f9092b10SMarkus Armbruster     assert(bs != bs_snapshots);
15127267c094SAnthony Liguori     g_free(bs);
1513fc01f7e7Sbellard }
1514fc01f7e7Sbellard 
1515fa879d62SMarkus Armbruster int bdrv_attach_dev(BlockDriverState *bs, void *dev)
1516fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
151718846deeSMarkus Armbruster {
1518fa879d62SMarkus Armbruster     if (bs->dev) {
151918846deeSMarkus Armbruster         return -EBUSY;
152018846deeSMarkus Armbruster     }
1521fa879d62SMarkus Armbruster     bs->dev = dev;
152228a7282aSLuiz Capitulino     bdrv_iostatus_reset(bs);
152318846deeSMarkus Armbruster     return 0;
152418846deeSMarkus Armbruster }
152518846deeSMarkus Armbruster 
1526fa879d62SMarkus Armbruster /* TODO qdevified devices don't use this, remove when devices are qdevified */
1527fa879d62SMarkus Armbruster void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
152818846deeSMarkus Armbruster {
1529fa879d62SMarkus Armbruster     if (bdrv_attach_dev(bs, dev) < 0) {
1530fa879d62SMarkus Armbruster         abort();
1531fa879d62SMarkus Armbruster     }
1532fa879d62SMarkus Armbruster }
1533fa879d62SMarkus Armbruster 
1534fa879d62SMarkus Armbruster void bdrv_detach_dev(BlockDriverState *bs, void *dev)
1535fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
1536fa879d62SMarkus Armbruster {
1537fa879d62SMarkus Armbruster     assert(bs->dev == dev);
1538fa879d62SMarkus Armbruster     bs->dev = NULL;
15390e49de52SMarkus Armbruster     bs->dev_ops = NULL;
15400e49de52SMarkus Armbruster     bs->dev_opaque = NULL;
154129e05f20SMarkus Armbruster     bs->buffer_alignment = 512;
154218846deeSMarkus Armbruster }
154318846deeSMarkus Armbruster 
1544fa879d62SMarkus Armbruster /* TODO change to return DeviceState * when all users are qdevified */
1545fa879d62SMarkus Armbruster void *bdrv_get_attached_dev(BlockDriverState *bs)
154618846deeSMarkus Armbruster {
1547fa879d62SMarkus Armbruster     return bs->dev;
154818846deeSMarkus Armbruster }
154918846deeSMarkus Armbruster 
15500e49de52SMarkus Armbruster void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
15510e49de52SMarkus Armbruster                       void *opaque)
15520e49de52SMarkus Armbruster {
15530e49de52SMarkus Armbruster     bs->dev_ops = ops;
15540e49de52SMarkus Armbruster     bs->dev_opaque = opaque;
15552c6942faSMarkus Armbruster     if (bdrv_dev_has_removable_media(bs) && bs == bs_snapshots) {
15562c6942faSMarkus Armbruster         bs_snapshots = NULL;
15572c6942faSMarkus Armbruster     }
15580e49de52SMarkus Armbruster }
15590e49de52SMarkus Armbruster 
156032c81a4aSPaolo Bonzini void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
156132c81a4aSPaolo Bonzini                                enum MonitorEvent ev,
15621ceee0d5SPaolo Bonzini                                BlockErrorAction action, bool is_read)
1563329c0a48SLuiz Capitulino {
1564329c0a48SLuiz Capitulino     QObject *data;
1565329c0a48SLuiz Capitulino     const char *action_str;
1566329c0a48SLuiz Capitulino 
1567329c0a48SLuiz Capitulino     switch (action) {
1568329c0a48SLuiz Capitulino     case BDRV_ACTION_REPORT:
1569329c0a48SLuiz Capitulino         action_str = "report";
1570329c0a48SLuiz Capitulino         break;
1571329c0a48SLuiz Capitulino     case BDRV_ACTION_IGNORE:
1572329c0a48SLuiz Capitulino         action_str = "ignore";
1573329c0a48SLuiz Capitulino         break;
1574329c0a48SLuiz Capitulino     case BDRV_ACTION_STOP:
1575329c0a48SLuiz Capitulino         action_str = "stop";
1576329c0a48SLuiz Capitulino         break;
1577329c0a48SLuiz Capitulino     default:
1578329c0a48SLuiz Capitulino         abort();
1579329c0a48SLuiz Capitulino     }
1580329c0a48SLuiz Capitulino 
1581329c0a48SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1582329c0a48SLuiz Capitulino                               bdrv->device_name,
1583329c0a48SLuiz Capitulino                               action_str,
1584329c0a48SLuiz Capitulino                               is_read ? "read" : "write");
158532c81a4aSPaolo Bonzini     monitor_protocol_event(ev, data);
1586329c0a48SLuiz Capitulino 
1587329c0a48SLuiz Capitulino     qobject_decref(data);
1588329c0a48SLuiz Capitulino }
1589329c0a48SLuiz Capitulino 
15906f382ed2SLuiz Capitulino static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
15916f382ed2SLuiz Capitulino {
15926f382ed2SLuiz Capitulino     QObject *data;
15936f382ed2SLuiz Capitulino 
15946f382ed2SLuiz Capitulino     data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
15956f382ed2SLuiz Capitulino                               bdrv_get_device_name(bs), ejected);
15966f382ed2SLuiz Capitulino     monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
15976f382ed2SLuiz Capitulino 
15986f382ed2SLuiz Capitulino     qobject_decref(data);
15996f382ed2SLuiz Capitulino }
16006f382ed2SLuiz Capitulino 
16017d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
16020e49de52SMarkus Armbruster {
1603145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->change_media_cb) {
16046f382ed2SLuiz Capitulino         bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
16057d4b4ba5SMarkus Armbruster         bs->dev_ops->change_media_cb(bs->dev_opaque, load);
16066f382ed2SLuiz Capitulino         if (tray_was_closed) {
16076f382ed2SLuiz Capitulino             /* tray open */
16086f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, true);
16096f382ed2SLuiz Capitulino         }
16106f382ed2SLuiz Capitulino         if (load) {
16116f382ed2SLuiz Capitulino             /* tray close */
16126f382ed2SLuiz Capitulino             bdrv_emit_qmp_eject_event(bs, false);
16136f382ed2SLuiz Capitulino         }
1614145feb17SMarkus Armbruster     }
1615145feb17SMarkus Armbruster }
1616145feb17SMarkus Armbruster 
16172c6942faSMarkus Armbruster bool bdrv_dev_has_removable_media(BlockDriverState *bs)
16182c6942faSMarkus Armbruster {
16192c6942faSMarkus Armbruster     return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
16202c6942faSMarkus Armbruster }
16212c6942faSMarkus Armbruster 
1622025ccaa7SPaolo Bonzini void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
1623025ccaa7SPaolo Bonzini {
1624025ccaa7SPaolo Bonzini     if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
1625025ccaa7SPaolo Bonzini         bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
1626025ccaa7SPaolo Bonzini     }
1627025ccaa7SPaolo Bonzini }
1628025ccaa7SPaolo Bonzini 
1629e4def80bSMarkus Armbruster bool bdrv_dev_is_tray_open(BlockDriverState *bs)
1630e4def80bSMarkus Armbruster {
1631e4def80bSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_tray_open) {
1632e4def80bSMarkus Armbruster         return bs->dev_ops->is_tray_open(bs->dev_opaque);
1633e4def80bSMarkus Armbruster     }
1634e4def80bSMarkus Armbruster     return false;
1635e4def80bSMarkus Armbruster }
1636e4def80bSMarkus Armbruster 
1637145feb17SMarkus Armbruster static void bdrv_dev_resize_cb(BlockDriverState *bs)
1638145feb17SMarkus Armbruster {
1639145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->resize_cb) {
1640145feb17SMarkus Armbruster         bs->dev_ops->resize_cb(bs->dev_opaque);
16410e49de52SMarkus Armbruster     }
16420e49de52SMarkus Armbruster }
16430e49de52SMarkus Armbruster 
1644f107639aSMarkus Armbruster bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
1645f107639aSMarkus Armbruster {
1646f107639aSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
1647f107639aSMarkus Armbruster         return bs->dev_ops->is_medium_locked(bs->dev_opaque);
1648f107639aSMarkus Armbruster     }
1649f107639aSMarkus Armbruster     return false;
1650f107639aSMarkus Armbruster }
1651f107639aSMarkus Armbruster 
1652e97fc193Saliguori /*
1653e97fc193Saliguori  * Run consistency checks on an image
1654e97fc193Saliguori  *
1655e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
1656a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
1657e076f338SKevin Wolf  * check are stored in res.
1658e97fc193Saliguori  */
16594534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
1660e97fc193Saliguori {
1661e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
1662e97fc193Saliguori         return -ENOTSUP;
1663e97fc193Saliguori     }
1664e97fc193Saliguori 
1665e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
16664534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
1667e97fc193Saliguori }
1668e97fc193Saliguori 
16698a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
16708a426614SKevin Wolf 
167133e3963eSbellard /* commit COW file into the raw image */
167233e3963eSbellard int bdrv_commit(BlockDriverState *bs)
167333e3963eSbellard {
167419cb3738Sbellard     BlockDriver *drv = bs->drv;
16758a426614SKevin Wolf     int64_t sector, total_sectors;
16768a426614SKevin Wolf     int n, ro, open_flags;
16770bce597dSJeff Cody     int ret = 0;
16788a426614SKevin Wolf     uint8_t *buf;
1679c2cba3d9SJim Meyering     char filename[PATH_MAX];
168033e3963eSbellard 
168119cb3738Sbellard     if (!drv)
168219cb3738Sbellard         return -ENOMEDIUM;
168333e3963eSbellard 
16844dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
16854dca4b63SNaphtali Sprei         return -ENOTSUP;
16864dca4b63SNaphtali Sprei     }
16874dca4b63SNaphtali Sprei 
16882d3735d3SStefan Hajnoczi     if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
16892d3735d3SStefan Hajnoczi         return -EBUSY;
16902d3735d3SStefan Hajnoczi     }
16912d3735d3SStefan Hajnoczi 
16924dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
1693c2cba3d9SJim Meyering     /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
1694c2cba3d9SJim Meyering     pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
16954dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
16964dca4b63SNaphtali Sprei 
16974dca4b63SNaphtali Sprei     if (ro) {
16980bce597dSJeff Cody         if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
16990bce597dSJeff Cody             return -EACCES;
17004dca4b63SNaphtali Sprei         }
1701ea2384d3Sbellard     }
1702ea2384d3Sbellard 
17036ea44308SJan Kiszka     total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
17047267c094SAnthony Liguori     buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
17058a426614SKevin Wolf 
17068a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
170705c4af54SStefan Hajnoczi         if (bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
17088a426614SKevin Wolf 
17098a426614SKevin Wolf             if (bdrv_read(bs, sector, buf, n) != 0) {
17104dca4b63SNaphtali Sprei                 ret = -EIO;
17114dca4b63SNaphtali Sprei                 goto ro_cleanup;
171233e3963eSbellard             }
171333e3963eSbellard 
17148a426614SKevin Wolf             if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
17154dca4b63SNaphtali Sprei                 ret = -EIO;
17164dca4b63SNaphtali Sprei                 goto ro_cleanup;
171733e3963eSbellard             }
171833e3963eSbellard         }
171933e3963eSbellard     }
172095389c86Sbellard 
17211d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
17221d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
17231d44952fSChristoph Hellwig         bdrv_flush(bs);
17241d44952fSChristoph Hellwig     }
172595389c86Sbellard 
17263f5075aeSChristoph Hellwig     /*
17273f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
17283f5075aeSChristoph Hellwig      * stable on disk.
17293f5075aeSChristoph Hellwig      */
17303f5075aeSChristoph Hellwig     if (bs->backing_hd)
17313f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
17324dca4b63SNaphtali Sprei 
17334dca4b63SNaphtali Sprei ro_cleanup:
17347267c094SAnthony Liguori     g_free(buf);
17354dca4b63SNaphtali Sprei 
17364dca4b63SNaphtali Sprei     if (ro) {
17370bce597dSJeff Cody         /* ignoring error return here */
17380bce597dSJeff Cody         bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
17394dca4b63SNaphtali Sprei     }
17404dca4b63SNaphtali Sprei 
17411d44952fSChristoph Hellwig     return ret;
174233e3963eSbellard }
174333e3963eSbellard 
1744e8877497SStefan Hajnoczi int bdrv_commit_all(void)
17456ab4b5abSMarkus Armbruster {
17466ab4b5abSMarkus Armbruster     BlockDriverState *bs;
17476ab4b5abSMarkus Armbruster 
17486ab4b5abSMarkus Armbruster     QTAILQ_FOREACH(bs, &bdrv_states, list) {
1749272d2d8eSJeff Cody         if (bs->drv && bs->backing_hd) {
1750e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
1751e8877497SStefan Hajnoczi             if (ret < 0) {
1752e8877497SStefan Hajnoczi                 return ret;
17536ab4b5abSMarkus Armbruster             }
17546ab4b5abSMarkus Armbruster         }
1755272d2d8eSJeff Cody     }
1756e8877497SStefan Hajnoczi     return 0;
1757e8877497SStefan Hajnoczi }
17586ab4b5abSMarkus Armbruster 
1759dbffbdcfSStefan Hajnoczi struct BdrvTrackedRequest {
1760dbffbdcfSStefan Hajnoczi     BlockDriverState *bs;
1761dbffbdcfSStefan Hajnoczi     int64_t sector_num;
1762dbffbdcfSStefan Hajnoczi     int nb_sectors;
1763dbffbdcfSStefan Hajnoczi     bool is_write;
1764dbffbdcfSStefan Hajnoczi     QLIST_ENTRY(BdrvTrackedRequest) list;
17655f8b6491SStefan Hajnoczi     Coroutine *co; /* owner, used for deadlock detection */
1766f4658285SStefan Hajnoczi     CoQueue wait_queue; /* coroutines blocked on this request */
1767dbffbdcfSStefan Hajnoczi };
1768dbffbdcfSStefan Hajnoczi 
1769dbffbdcfSStefan Hajnoczi /**
1770dbffbdcfSStefan Hajnoczi  * Remove an active request from the tracked requests list
1771dbffbdcfSStefan Hajnoczi  *
1772dbffbdcfSStefan Hajnoczi  * This function should be called when a tracked request is completing.
1773dbffbdcfSStefan Hajnoczi  */
1774dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req)
1775dbffbdcfSStefan Hajnoczi {
1776dbffbdcfSStefan Hajnoczi     QLIST_REMOVE(req, list);
1777f4658285SStefan Hajnoczi     qemu_co_queue_restart_all(&req->wait_queue);
1778dbffbdcfSStefan Hajnoczi }
1779dbffbdcfSStefan Hajnoczi 
1780dbffbdcfSStefan Hajnoczi /**
1781dbffbdcfSStefan Hajnoczi  * Add an active request to the tracked requests list
1782dbffbdcfSStefan Hajnoczi  */
1783dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req,
1784dbffbdcfSStefan Hajnoczi                                   BlockDriverState *bs,
1785dbffbdcfSStefan Hajnoczi                                   int64_t sector_num,
1786dbffbdcfSStefan Hajnoczi                                   int nb_sectors, bool is_write)
1787dbffbdcfSStefan Hajnoczi {
1788dbffbdcfSStefan Hajnoczi     *req = (BdrvTrackedRequest){
1789dbffbdcfSStefan Hajnoczi         .bs = bs,
1790dbffbdcfSStefan Hajnoczi         .sector_num = sector_num,
1791dbffbdcfSStefan Hajnoczi         .nb_sectors = nb_sectors,
1792dbffbdcfSStefan Hajnoczi         .is_write = is_write,
17935f8b6491SStefan Hajnoczi         .co = qemu_coroutine_self(),
1794dbffbdcfSStefan Hajnoczi     };
1795dbffbdcfSStefan Hajnoczi 
1796f4658285SStefan Hajnoczi     qemu_co_queue_init(&req->wait_queue);
1797f4658285SStefan Hajnoczi 
1798dbffbdcfSStefan Hajnoczi     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
1799dbffbdcfSStefan Hajnoczi }
1800dbffbdcfSStefan Hajnoczi 
1801d83947acSStefan Hajnoczi /**
1802d83947acSStefan Hajnoczi  * Round a region to cluster boundaries
1803d83947acSStefan Hajnoczi  */
1804343bded4SPaolo Bonzini void bdrv_round_to_clusters(BlockDriverState *bs,
1805d83947acSStefan Hajnoczi                             int64_t sector_num, int nb_sectors,
1806d83947acSStefan Hajnoczi                             int64_t *cluster_sector_num,
1807d83947acSStefan Hajnoczi                             int *cluster_nb_sectors)
1808d83947acSStefan Hajnoczi {
1809d83947acSStefan Hajnoczi     BlockDriverInfo bdi;
1810d83947acSStefan Hajnoczi 
1811d83947acSStefan Hajnoczi     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
1812d83947acSStefan Hajnoczi         *cluster_sector_num = sector_num;
1813d83947acSStefan Hajnoczi         *cluster_nb_sectors = nb_sectors;
1814d83947acSStefan Hajnoczi     } else {
1815d83947acSStefan Hajnoczi         int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
1816d83947acSStefan Hajnoczi         *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
1817d83947acSStefan Hajnoczi         *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
1818d83947acSStefan Hajnoczi                                             nb_sectors, c);
1819d83947acSStefan Hajnoczi     }
1820d83947acSStefan Hajnoczi }
1821d83947acSStefan Hajnoczi 
1822f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req,
1823f4658285SStefan Hajnoczi                                      int64_t sector_num, int nb_sectors) {
1824d83947acSStefan Hajnoczi     /*        aaaa   bbbb */
1825d83947acSStefan Hajnoczi     if (sector_num >= req->sector_num + req->nb_sectors) {
1826d83947acSStefan Hajnoczi         return false;
1827d83947acSStefan Hajnoczi     }
1828d83947acSStefan Hajnoczi     /* bbbb   aaaa        */
1829d83947acSStefan Hajnoczi     if (req->sector_num >= sector_num + nb_sectors) {
1830d83947acSStefan Hajnoczi         return false;
1831d83947acSStefan Hajnoczi     }
1832d83947acSStefan Hajnoczi     return true;
1833f4658285SStefan Hajnoczi }
1834f4658285SStefan Hajnoczi 
1835f4658285SStefan Hajnoczi static void coroutine_fn wait_for_overlapping_requests(BlockDriverState *bs,
1836f4658285SStefan Hajnoczi         int64_t sector_num, int nb_sectors)
1837f4658285SStefan Hajnoczi {
1838f4658285SStefan Hajnoczi     BdrvTrackedRequest *req;
1839d83947acSStefan Hajnoczi     int64_t cluster_sector_num;
1840d83947acSStefan Hajnoczi     int cluster_nb_sectors;
1841f4658285SStefan Hajnoczi     bool retry;
1842f4658285SStefan Hajnoczi 
1843d83947acSStefan Hajnoczi     /* If we touch the same cluster it counts as an overlap.  This guarantees
1844d83947acSStefan Hajnoczi      * that allocating writes will be serialized and not race with each other
1845d83947acSStefan Hajnoczi      * for the same cluster.  For example, in copy-on-read it ensures that the
1846d83947acSStefan Hajnoczi      * CoR read and write operations are atomic and guest writes cannot
1847d83947acSStefan Hajnoczi      * interleave between them.
1848d83947acSStefan Hajnoczi      */
1849343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
1850d83947acSStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
1851d83947acSStefan Hajnoczi 
1852f4658285SStefan Hajnoczi     do {
1853f4658285SStefan Hajnoczi         retry = false;
1854f4658285SStefan Hajnoczi         QLIST_FOREACH(req, &bs->tracked_requests, list) {
1855d83947acSStefan Hajnoczi             if (tracked_request_overlaps(req, cluster_sector_num,
1856d83947acSStefan Hajnoczi                                          cluster_nb_sectors)) {
18575f8b6491SStefan Hajnoczi                 /* Hitting this means there was a reentrant request, for
18585f8b6491SStefan Hajnoczi                  * example, a block driver issuing nested requests.  This must
18595f8b6491SStefan Hajnoczi                  * never happen since it means deadlock.
18605f8b6491SStefan Hajnoczi                  */
18615f8b6491SStefan Hajnoczi                 assert(qemu_coroutine_self() != req->co);
18625f8b6491SStefan Hajnoczi 
1863f4658285SStefan Hajnoczi                 qemu_co_queue_wait(&req->wait_queue);
1864f4658285SStefan Hajnoczi                 retry = true;
1865f4658285SStefan Hajnoczi                 break;
1866f4658285SStefan Hajnoczi             }
1867f4658285SStefan Hajnoczi         }
1868f4658285SStefan Hajnoczi     } while (retry);
1869f4658285SStefan Hajnoczi }
1870f4658285SStefan Hajnoczi 
1871756e6736SKevin Wolf /*
1872756e6736SKevin Wolf  * Return values:
1873756e6736SKevin Wolf  * 0        - success
1874756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
1875756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
1876756e6736SKevin Wolf  *            image file header
1877756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
1878756e6736SKevin Wolf  */
1879756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
1880756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
1881756e6736SKevin Wolf {
1882756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
1883469ef350SPaolo Bonzini     int ret;
1884756e6736SKevin Wolf 
18855f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
18865f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
18875f377794SPaolo Bonzini         return -EINVAL;
18885f377794SPaolo Bonzini     }
18895f377794SPaolo Bonzini 
1890756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
1891469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
1892756e6736SKevin Wolf     } else {
1893469ef350SPaolo Bonzini         ret = -ENOTSUP;
1894756e6736SKevin Wolf     }
1895469ef350SPaolo Bonzini 
1896469ef350SPaolo Bonzini     if (ret == 0) {
1897469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1898469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1899469ef350SPaolo Bonzini     }
1900469ef350SPaolo Bonzini     return ret;
1901756e6736SKevin Wolf }
1902756e6736SKevin Wolf 
19036ebdcee2SJeff Cody /*
19046ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
19056ebdcee2SJeff Cody  *
19066ebdcee2SJeff Cody  * active is the current topmost image.
19076ebdcee2SJeff Cody  *
19086ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
19096ebdcee2SJeff Cody  * or if active == bs.
19106ebdcee2SJeff Cody  */
19116ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
19126ebdcee2SJeff Cody                                     BlockDriverState *bs)
19136ebdcee2SJeff Cody {
19146ebdcee2SJeff Cody     BlockDriverState *overlay = NULL;
19156ebdcee2SJeff Cody     BlockDriverState *intermediate;
19166ebdcee2SJeff Cody 
19176ebdcee2SJeff Cody     assert(active != NULL);
19186ebdcee2SJeff Cody     assert(bs != NULL);
19196ebdcee2SJeff Cody 
19206ebdcee2SJeff Cody     /* if bs is the same as active, then by definition it has no overlay
19216ebdcee2SJeff Cody      */
19226ebdcee2SJeff Cody     if (active == bs) {
19236ebdcee2SJeff Cody         return NULL;
19246ebdcee2SJeff Cody     }
19256ebdcee2SJeff Cody 
19266ebdcee2SJeff Cody     intermediate = active;
19276ebdcee2SJeff Cody     while (intermediate->backing_hd) {
19286ebdcee2SJeff Cody         if (intermediate->backing_hd == bs) {
19296ebdcee2SJeff Cody             overlay = intermediate;
19306ebdcee2SJeff Cody             break;
19316ebdcee2SJeff Cody         }
19326ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
19336ebdcee2SJeff Cody     }
19346ebdcee2SJeff Cody 
19356ebdcee2SJeff Cody     return overlay;
19366ebdcee2SJeff Cody }
19376ebdcee2SJeff Cody 
19386ebdcee2SJeff Cody typedef struct BlkIntermediateStates {
19396ebdcee2SJeff Cody     BlockDriverState *bs;
19406ebdcee2SJeff Cody     QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
19416ebdcee2SJeff Cody } BlkIntermediateStates;
19426ebdcee2SJeff Cody 
19436ebdcee2SJeff Cody 
19446ebdcee2SJeff Cody /*
19456ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
19466ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
19476ebdcee2SJeff Cody  *
19486ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
19496ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
19506ebdcee2SJeff Cody  *
19516ebdcee2SJeff Cody  * E.g., this will convert the following chain:
19526ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
19536ebdcee2SJeff Cody  *
19546ebdcee2SJeff Cody  * to
19556ebdcee2SJeff Cody  *
19566ebdcee2SJeff Cody  * bottom <- base <- active
19576ebdcee2SJeff Cody  *
19586ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
19596ebdcee2SJeff Cody  *
19606ebdcee2SJeff Cody  * base <- intermediate <- top <- active
19616ebdcee2SJeff Cody  *
19626ebdcee2SJeff Cody  * to
19636ebdcee2SJeff Cody  *
19646ebdcee2SJeff Cody  * base <- active
19656ebdcee2SJeff Cody  *
19666ebdcee2SJeff Cody  * Error conditions:
19676ebdcee2SJeff Cody  *  if active == top, that is considered an error
19686ebdcee2SJeff Cody  *
19696ebdcee2SJeff Cody  */
19706ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
19716ebdcee2SJeff Cody                            BlockDriverState *base)
19726ebdcee2SJeff Cody {
19736ebdcee2SJeff Cody     BlockDriverState *intermediate;
19746ebdcee2SJeff Cody     BlockDriverState *base_bs = NULL;
19756ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
19766ebdcee2SJeff Cody     BlkIntermediateStates *intermediate_state, *next;
19776ebdcee2SJeff Cody     int ret = -EIO;
19786ebdcee2SJeff Cody 
19796ebdcee2SJeff Cody     QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
19806ebdcee2SJeff Cody     QSIMPLEQ_INIT(&states_to_delete);
19816ebdcee2SJeff Cody 
19826ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
19836ebdcee2SJeff Cody         goto exit;
19846ebdcee2SJeff Cody     }
19856ebdcee2SJeff Cody 
19866ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
19876ebdcee2SJeff Cody 
19886ebdcee2SJeff Cody     if (new_top_bs == NULL) {
19896ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
19906ebdcee2SJeff Cody         goto exit;
19916ebdcee2SJeff Cody     }
19926ebdcee2SJeff Cody 
19936ebdcee2SJeff Cody     /* special case of new_top_bs->backing_hd already pointing to base - nothing
19946ebdcee2SJeff Cody      * to do, no intermediate images */
19956ebdcee2SJeff Cody     if (new_top_bs->backing_hd == base) {
19966ebdcee2SJeff Cody         ret = 0;
19976ebdcee2SJeff Cody         goto exit;
19986ebdcee2SJeff Cody     }
19996ebdcee2SJeff Cody 
20006ebdcee2SJeff Cody     intermediate = top;
20016ebdcee2SJeff Cody 
20026ebdcee2SJeff Cody     /* now we will go down through the list, and add each BDS we find
20036ebdcee2SJeff Cody      * into our deletion queue, until we hit the 'base'
20046ebdcee2SJeff Cody      */
20056ebdcee2SJeff Cody     while (intermediate) {
20066ebdcee2SJeff Cody         intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
20076ebdcee2SJeff Cody         intermediate_state->bs = intermediate;
20086ebdcee2SJeff Cody         QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
20096ebdcee2SJeff Cody 
20106ebdcee2SJeff Cody         if (intermediate->backing_hd == base) {
20116ebdcee2SJeff Cody             base_bs = intermediate->backing_hd;
20126ebdcee2SJeff Cody             break;
20136ebdcee2SJeff Cody         }
20146ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
20156ebdcee2SJeff Cody     }
20166ebdcee2SJeff Cody     if (base_bs == NULL) {
20176ebdcee2SJeff Cody         /* something went wrong, we did not end at the base. safely
20186ebdcee2SJeff Cody          * unravel everything, and exit with error */
20196ebdcee2SJeff Cody         goto exit;
20206ebdcee2SJeff Cody     }
20216ebdcee2SJeff Cody 
20226ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
20236ebdcee2SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
20246ebdcee2SJeff Cody                                    base_bs->drv ? base_bs->drv->format_name : "");
20256ebdcee2SJeff Cody     if (ret) {
20266ebdcee2SJeff Cody         goto exit;
20276ebdcee2SJeff Cody     }
20286ebdcee2SJeff Cody     new_top_bs->backing_hd = base_bs;
20296ebdcee2SJeff Cody 
20306ebdcee2SJeff Cody 
20316ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
20326ebdcee2SJeff Cody         /* so that bdrv_close() does not recursively close the chain */
20336ebdcee2SJeff Cody         intermediate_state->bs->backing_hd = NULL;
20346ebdcee2SJeff Cody         bdrv_delete(intermediate_state->bs);
20356ebdcee2SJeff Cody     }
20366ebdcee2SJeff Cody     ret = 0;
20376ebdcee2SJeff Cody 
20386ebdcee2SJeff Cody exit:
20396ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
20406ebdcee2SJeff Cody         g_free(intermediate_state);
20416ebdcee2SJeff Cody     }
20426ebdcee2SJeff Cody     return ret;
20436ebdcee2SJeff Cody }
20446ebdcee2SJeff Cody 
20456ebdcee2SJeff Cody 
204671d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
204771d0770cSaliguori                                    size_t size)
204871d0770cSaliguori {
204971d0770cSaliguori     int64_t len;
205071d0770cSaliguori 
205171d0770cSaliguori     if (!bdrv_is_inserted(bs))
205271d0770cSaliguori         return -ENOMEDIUM;
205371d0770cSaliguori 
205471d0770cSaliguori     if (bs->growable)
205571d0770cSaliguori         return 0;
205671d0770cSaliguori 
205771d0770cSaliguori     len = bdrv_getlength(bs);
205871d0770cSaliguori 
2059fbb7b4e0SKevin Wolf     if (offset < 0)
2060fbb7b4e0SKevin Wolf         return -EIO;
2061fbb7b4e0SKevin Wolf 
2062fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
206371d0770cSaliguori         return -EIO;
206471d0770cSaliguori 
206571d0770cSaliguori     return 0;
206671d0770cSaliguori }
206771d0770cSaliguori 
206871d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
206971d0770cSaliguori                               int nb_sectors)
207071d0770cSaliguori {
2071eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
2072eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
207371d0770cSaliguori }
207471d0770cSaliguori 
20751c9805a3SStefan Hajnoczi typedef struct RwCo {
20761c9805a3SStefan Hajnoczi     BlockDriverState *bs;
20771c9805a3SStefan Hajnoczi     int64_t sector_num;
20781c9805a3SStefan Hajnoczi     int nb_sectors;
20791c9805a3SStefan Hajnoczi     QEMUIOVector *qiov;
20801c9805a3SStefan Hajnoczi     bool is_write;
20811c9805a3SStefan Hajnoczi     int ret;
20821c9805a3SStefan Hajnoczi } RwCo;
20831c9805a3SStefan Hajnoczi 
20841c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque)
2085fc01f7e7Sbellard {
20861c9805a3SStefan Hajnoczi     RwCo *rwco = opaque;
2087fc01f7e7Sbellard 
20881c9805a3SStefan Hajnoczi     if (!rwco->is_write) {
20891c9805a3SStefan Hajnoczi         rwco->ret = bdrv_co_do_readv(rwco->bs, rwco->sector_num,
2090470c0504SStefan Hajnoczi                                      rwco->nb_sectors, rwco->qiov, 0);
20911c9805a3SStefan Hajnoczi     } else {
20921c9805a3SStefan Hajnoczi         rwco->ret = bdrv_co_do_writev(rwco->bs, rwco->sector_num,
2093f08f2ddaSStefan Hajnoczi                                       rwco->nb_sectors, rwco->qiov, 0);
20941c9805a3SStefan Hajnoczi     }
20951c9805a3SStefan Hajnoczi }
2096e7a8a783SKevin Wolf 
20971c9805a3SStefan Hajnoczi /*
20981c9805a3SStefan Hajnoczi  * Process a synchronous request using coroutines
20991c9805a3SStefan Hajnoczi  */
21001c9805a3SStefan Hajnoczi static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
21011c9805a3SStefan Hajnoczi                       int nb_sectors, bool is_write)
21021c9805a3SStefan Hajnoczi {
2103e7a8a783SKevin Wolf     QEMUIOVector qiov;
2104e7a8a783SKevin Wolf     struct iovec iov = {
2105e7a8a783SKevin Wolf         .iov_base = (void *)buf,
2106e7a8a783SKevin Wolf         .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
2107e7a8a783SKevin Wolf     };
21081c9805a3SStefan Hajnoczi     Coroutine *co;
21091c9805a3SStefan Hajnoczi     RwCo rwco = {
21101c9805a3SStefan Hajnoczi         .bs = bs,
21111c9805a3SStefan Hajnoczi         .sector_num = sector_num,
21121c9805a3SStefan Hajnoczi         .nb_sectors = nb_sectors,
21131c9805a3SStefan Hajnoczi         .qiov = &qiov,
21141c9805a3SStefan Hajnoczi         .is_write = is_write,
21151c9805a3SStefan Hajnoczi         .ret = NOT_DONE,
21161c9805a3SStefan Hajnoczi     };
2117e7a8a783SKevin Wolf 
2118e7a8a783SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
21191c9805a3SStefan Hajnoczi 
2120498e386cSZhi Yong Wu     /**
2121498e386cSZhi Yong Wu      * In sync call context, when the vcpu is blocked, this throttling timer
2122498e386cSZhi Yong Wu      * will not fire; so the I/O throttling function has to be disabled here
2123498e386cSZhi Yong Wu      * if it has been enabled.
2124498e386cSZhi Yong Wu      */
2125498e386cSZhi Yong Wu     if (bs->io_limits_enabled) {
2126498e386cSZhi Yong Wu         fprintf(stderr, "Disabling I/O throttling on '%s' due "
2127498e386cSZhi Yong Wu                         "to synchronous I/O.\n", bdrv_get_device_name(bs));
2128498e386cSZhi Yong Wu         bdrv_io_limits_disable(bs);
2129498e386cSZhi Yong Wu     }
2130498e386cSZhi Yong Wu 
21311c9805a3SStefan Hajnoczi     if (qemu_in_coroutine()) {
21321c9805a3SStefan Hajnoczi         /* Fast-path if already in coroutine context */
21331c9805a3SStefan Hajnoczi         bdrv_rw_co_entry(&rwco);
21341c9805a3SStefan Hajnoczi     } else {
21351c9805a3SStefan Hajnoczi         co = qemu_coroutine_create(bdrv_rw_co_entry);
21361c9805a3SStefan Hajnoczi         qemu_coroutine_enter(co, &rwco);
21371c9805a3SStefan Hajnoczi         while (rwco.ret == NOT_DONE) {
21381c9805a3SStefan Hajnoczi             qemu_aio_wait();
21391c9805a3SStefan Hajnoczi         }
21401c9805a3SStefan Hajnoczi     }
21411c9805a3SStefan Hajnoczi     return rwco.ret;
2142e7a8a783SKevin Wolf }
2143e7a8a783SKevin Wolf 
21441c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */
21451c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num,
21461c9805a3SStefan Hajnoczi               uint8_t *buf, int nb_sectors)
21471c9805a3SStefan Hajnoczi {
21481c9805a3SStefan Hajnoczi     return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false);
214983f64091Sbellard }
2150fc01f7e7Sbellard 
215107d27a44SMarkus Armbruster /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
215207d27a44SMarkus Armbruster int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
215307d27a44SMarkus Armbruster                           uint8_t *buf, int nb_sectors)
215407d27a44SMarkus Armbruster {
215507d27a44SMarkus Armbruster     bool enabled;
215607d27a44SMarkus Armbruster     int ret;
215707d27a44SMarkus Armbruster 
215807d27a44SMarkus Armbruster     enabled = bs->io_limits_enabled;
215907d27a44SMarkus Armbruster     bs->io_limits_enabled = false;
216007d27a44SMarkus Armbruster     ret = bdrv_read(bs, 0, buf, 1);
216107d27a44SMarkus Armbruster     bs->io_limits_enabled = enabled;
216207d27a44SMarkus Armbruster     return ret;
216307d27a44SMarkus Armbruster }
216407d27a44SMarkus Armbruster 
216519cb3738Sbellard /* Return < 0 if error. Important errors are:
216619cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
216719cb3738Sbellard   -ENOMEDIUM   No media inserted.
216819cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
216919cb3738Sbellard   -EACCES      Trying to write a read-only device
217019cb3738Sbellard */
2171fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
2172fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
2173fc01f7e7Sbellard {
21741c9805a3SStefan Hajnoczi     return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true);
217583f64091Sbellard }
217683f64091Sbellard 
2177eda578e5Saliguori int bdrv_pread(BlockDriverState *bs, int64_t offset,
2178eda578e5Saliguori                void *buf, int count1)
217983f64091Sbellard {
21806ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
218183f64091Sbellard     int len, nb_sectors, count;
218283f64091Sbellard     int64_t sector_num;
21839a8c4cceSKevin Wolf     int ret;
218483f64091Sbellard 
218583f64091Sbellard     count = count1;
218683f64091Sbellard     /* first read to align to sector start */
21876ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
218883f64091Sbellard     if (len > count)
218983f64091Sbellard         len = count;
21906ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
219183f64091Sbellard     if (len > 0) {
21929a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
21939a8c4cceSKevin Wolf             return ret;
21946ea44308SJan Kiszka         memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
219583f64091Sbellard         count -= len;
219683f64091Sbellard         if (count == 0)
219783f64091Sbellard             return count1;
219883f64091Sbellard         sector_num++;
219983f64091Sbellard         buf += len;
220083f64091Sbellard     }
220183f64091Sbellard 
220283f64091Sbellard     /* read the sectors "in place" */
22036ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
220483f64091Sbellard     if (nb_sectors > 0) {
22059a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
22069a8c4cceSKevin Wolf             return ret;
220783f64091Sbellard         sector_num += nb_sectors;
22086ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
220983f64091Sbellard         buf += len;
221083f64091Sbellard         count -= len;
221183f64091Sbellard     }
221283f64091Sbellard 
221383f64091Sbellard     /* add data from the last sector */
221483f64091Sbellard     if (count > 0) {
22159a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
22169a8c4cceSKevin Wolf             return ret;
221783f64091Sbellard         memcpy(buf, tmp_buf, count);
221883f64091Sbellard     }
221983f64091Sbellard     return count1;
222083f64091Sbellard }
222183f64091Sbellard 
2222eda578e5Saliguori int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
2223eda578e5Saliguori                 const void *buf, int count1)
222483f64091Sbellard {
22256ea44308SJan Kiszka     uint8_t tmp_buf[BDRV_SECTOR_SIZE];
222683f64091Sbellard     int len, nb_sectors, count;
222783f64091Sbellard     int64_t sector_num;
22289a8c4cceSKevin Wolf     int ret;
222983f64091Sbellard 
223083f64091Sbellard     count = count1;
223183f64091Sbellard     /* first write to align to sector start */
22326ea44308SJan Kiszka     len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
223383f64091Sbellard     if (len > count)
223483f64091Sbellard         len = count;
22356ea44308SJan Kiszka     sector_num = offset >> BDRV_SECTOR_BITS;
223683f64091Sbellard     if (len > 0) {
22379a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
22389a8c4cceSKevin Wolf             return ret;
22396ea44308SJan Kiszka         memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
22409a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
22419a8c4cceSKevin Wolf             return ret;
224283f64091Sbellard         count -= len;
224383f64091Sbellard         if (count == 0)
224483f64091Sbellard             return count1;
224583f64091Sbellard         sector_num++;
224683f64091Sbellard         buf += len;
224783f64091Sbellard     }
224883f64091Sbellard 
224983f64091Sbellard     /* write the sectors "in place" */
22506ea44308SJan Kiszka     nb_sectors = count >> BDRV_SECTOR_BITS;
225183f64091Sbellard     if (nb_sectors > 0) {
22529a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
22539a8c4cceSKevin Wolf             return ret;
225483f64091Sbellard         sector_num += nb_sectors;
22556ea44308SJan Kiszka         len = nb_sectors << BDRV_SECTOR_BITS;
225683f64091Sbellard         buf += len;
225783f64091Sbellard         count -= len;
225883f64091Sbellard     }
225983f64091Sbellard 
226083f64091Sbellard     /* add data from the last sector */
226183f64091Sbellard     if (count > 0) {
22629a8c4cceSKevin Wolf         if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
22639a8c4cceSKevin Wolf             return ret;
226483f64091Sbellard         memcpy(tmp_buf, buf, count);
22659a8c4cceSKevin Wolf         if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
22669a8c4cceSKevin Wolf             return ret;
226783f64091Sbellard     }
226883f64091Sbellard     return count1;
226983f64091Sbellard }
227083f64091Sbellard 
2271f08145feSKevin Wolf /*
2272f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
2273f08145feSKevin Wolf  * request (acts as a barrier)
2274f08145feSKevin Wolf  *
2275f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
2276f08145feSKevin Wolf  */
2277f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2278f08145feSKevin Wolf     const void *buf, int count)
2279f08145feSKevin Wolf {
2280f08145feSKevin Wolf     int ret;
2281f08145feSKevin Wolf 
2282f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
2283f08145feSKevin Wolf     if (ret < 0) {
2284f08145feSKevin Wolf         return ret;
2285f08145feSKevin Wolf     }
2286f08145feSKevin Wolf 
2287f05fa4adSPaolo Bonzini     /* No flush needed for cache modes that already do it */
2288f05fa4adSPaolo Bonzini     if (bs->enable_write_cache) {
2289f08145feSKevin Wolf         bdrv_flush(bs);
2290f08145feSKevin Wolf     }
2291f08145feSKevin Wolf 
2292f08145feSKevin Wolf     return 0;
2293f08145feSKevin Wolf }
2294f08145feSKevin Wolf 
2295470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
2296ab185921SStefan Hajnoczi         int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2297ab185921SStefan Hajnoczi {
2298ab185921SStefan Hajnoczi     /* Perform I/O through a temporary buffer so that users who scribble over
2299ab185921SStefan Hajnoczi      * their read buffer while the operation is in progress do not end up
2300ab185921SStefan Hajnoczi      * modifying the image file.  This is critical for zero-copy guest I/O
2301ab185921SStefan Hajnoczi      * where anything might happen inside guest memory.
2302ab185921SStefan Hajnoczi      */
2303ab185921SStefan Hajnoczi     void *bounce_buffer;
2304ab185921SStefan Hajnoczi 
230579c053bdSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2306ab185921SStefan Hajnoczi     struct iovec iov;
2307ab185921SStefan Hajnoczi     QEMUIOVector bounce_qiov;
2308ab185921SStefan Hajnoczi     int64_t cluster_sector_num;
2309ab185921SStefan Hajnoczi     int cluster_nb_sectors;
2310ab185921SStefan Hajnoczi     size_t skip_bytes;
2311ab185921SStefan Hajnoczi     int ret;
2312ab185921SStefan Hajnoczi 
2313ab185921SStefan Hajnoczi     /* Cover entire cluster so no additional backing file I/O is required when
2314ab185921SStefan Hajnoczi      * allocating cluster in the image file.
2315ab185921SStefan Hajnoczi      */
2316343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2317ab185921SStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
2318ab185921SStefan Hajnoczi 
2319470c0504SStefan Hajnoczi     trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2320ab185921SStefan Hajnoczi                                    cluster_sector_num, cluster_nb_sectors);
2321ab185921SStefan Hajnoczi 
2322ab185921SStefan Hajnoczi     iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
2323ab185921SStefan Hajnoczi     iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
2324ab185921SStefan Hajnoczi     qemu_iovec_init_external(&bounce_qiov, &iov, 1);
2325ab185921SStefan Hajnoczi 
232679c053bdSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
2327ab185921SStefan Hajnoczi                              &bounce_qiov);
2328ab185921SStefan Hajnoczi     if (ret < 0) {
2329ab185921SStefan Hajnoczi         goto err;
2330ab185921SStefan Hajnoczi     }
2331ab185921SStefan Hajnoczi 
233279c053bdSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes &&
233379c053bdSStefan Hajnoczi         buffer_is_zero(bounce_buffer, iov.iov_len)) {
2334621f0589SKevin Wolf         ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
233579c053bdSStefan Hajnoczi                                       cluster_nb_sectors);
233679c053bdSStefan Hajnoczi     } else {
2337f05fa4adSPaolo Bonzini         /* This does not change the data on the disk, it is not necessary
2338f05fa4adSPaolo Bonzini          * to flush even in cache=writethrough mode.
2339f05fa4adSPaolo Bonzini          */
234079c053bdSStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
2341ab185921SStefan Hajnoczi                                   &bounce_qiov);
234279c053bdSStefan Hajnoczi     }
234379c053bdSStefan Hajnoczi 
2344ab185921SStefan Hajnoczi     if (ret < 0) {
2345ab185921SStefan Hajnoczi         /* It might be okay to ignore write errors for guest requests.  If this
2346ab185921SStefan Hajnoczi          * is a deliberate copy-on-read then we don't want to ignore the error.
2347ab185921SStefan Hajnoczi          * Simply report it in all cases.
2348ab185921SStefan Hajnoczi          */
2349ab185921SStefan Hajnoczi         goto err;
2350ab185921SStefan Hajnoczi     }
2351ab185921SStefan Hajnoczi 
2352ab185921SStefan Hajnoczi     skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
235303396148SMichael Tokarev     qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
2354ab185921SStefan Hajnoczi                         nb_sectors * BDRV_SECTOR_SIZE);
2355ab185921SStefan Hajnoczi 
2356ab185921SStefan Hajnoczi err:
2357ab185921SStefan Hajnoczi     qemu_vfree(bounce_buffer);
2358ab185921SStefan Hajnoczi     return ret;
2359ab185921SStefan Hajnoczi }
2360ab185921SStefan Hajnoczi 
2361c5fbe571SStefan Hajnoczi /*
2362c5fbe571SStefan Hajnoczi  * Handle a read request in coroutine context
2363c5fbe571SStefan Hajnoczi  */
2364c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
2365470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2366470c0504SStefan Hajnoczi     BdrvRequestFlags flags)
2367da1fa91dSKevin Wolf {
2368da1fa91dSKevin Wolf     BlockDriver *drv = bs->drv;
2369dbffbdcfSStefan Hajnoczi     BdrvTrackedRequest req;
2370dbffbdcfSStefan Hajnoczi     int ret;
2371da1fa91dSKevin Wolf 
2372da1fa91dSKevin Wolf     if (!drv) {
2373da1fa91dSKevin Wolf         return -ENOMEDIUM;
2374da1fa91dSKevin Wolf     }
2375da1fa91dSKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2376da1fa91dSKevin Wolf         return -EIO;
2377da1fa91dSKevin Wolf     }
2378da1fa91dSKevin Wolf 
237998f90dbaSZhi Yong Wu     /* throttling disk read I/O */
238098f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
238198f90dbaSZhi Yong Wu         bdrv_io_limits_intercept(bs, false, nb_sectors);
238298f90dbaSZhi Yong Wu     }
238398f90dbaSZhi Yong Wu 
2384f4658285SStefan Hajnoczi     if (bs->copy_on_read) {
2385470c0504SStefan Hajnoczi         flags |= BDRV_REQ_COPY_ON_READ;
2386470c0504SStefan Hajnoczi     }
2387470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2388470c0504SStefan Hajnoczi         bs->copy_on_read_in_flight++;
2389470c0504SStefan Hajnoczi     }
2390470c0504SStefan Hajnoczi 
2391470c0504SStefan Hajnoczi     if (bs->copy_on_read_in_flight) {
2392f4658285SStefan Hajnoczi         wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2393f4658285SStefan Hajnoczi     }
2394f4658285SStefan Hajnoczi 
2395dbffbdcfSStefan Hajnoczi     tracked_request_begin(&req, bs, sector_num, nb_sectors, false);
2396ab185921SStefan Hajnoczi 
2397470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2398ab185921SStefan Hajnoczi         int pnum;
2399ab185921SStefan Hajnoczi 
2400ab185921SStefan Hajnoczi         ret = bdrv_co_is_allocated(bs, sector_num, nb_sectors, &pnum);
2401ab185921SStefan Hajnoczi         if (ret < 0) {
2402ab185921SStefan Hajnoczi             goto out;
2403ab185921SStefan Hajnoczi         }
2404ab185921SStefan Hajnoczi 
2405ab185921SStefan Hajnoczi         if (!ret || pnum != nb_sectors) {
2406470c0504SStefan Hajnoczi             ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
2407ab185921SStefan Hajnoczi             goto out;
2408ab185921SStefan Hajnoczi         }
2409ab185921SStefan Hajnoczi     }
2410ab185921SStefan Hajnoczi 
2411dbffbdcfSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
2412ab185921SStefan Hajnoczi 
2413ab185921SStefan Hajnoczi out:
2414dbffbdcfSStefan Hajnoczi     tracked_request_end(&req);
2415470c0504SStefan Hajnoczi 
2416470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
2417470c0504SStefan Hajnoczi         bs->copy_on_read_in_flight--;
2418470c0504SStefan Hajnoczi     }
2419470c0504SStefan Hajnoczi 
2420dbffbdcfSStefan Hajnoczi     return ret;
2421da1fa91dSKevin Wolf }
2422da1fa91dSKevin Wolf 
2423c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
2424da1fa91dSKevin Wolf     int nb_sectors, QEMUIOVector *qiov)
2425da1fa91dSKevin Wolf {
2426c5fbe571SStefan Hajnoczi     trace_bdrv_co_readv(bs, sector_num, nb_sectors);
2427da1fa91dSKevin Wolf 
2428470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
2429470c0504SStefan Hajnoczi }
2430470c0504SStefan Hajnoczi 
2431470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
2432470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2433470c0504SStefan Hajnoczi {
2434470c0504SStefan Hajnoczi     trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
2435470c0504SStefan Hajnoczi 
2436470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
2437470c0504SStefan Hajnoczi                             BDRV_REQ_COPY_ON_READ);
2438c5fbe571SStefan Hajnoczi }
2439c5fbe571SStefan Hajnoczi 
2440f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
2441f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors)
2442f08f2ddaSStefan Hajnoczi {
2443f08f2ddaSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2444f08f2ddaSStefan Hajnoczi     QEMUIOVector qiov;
2445f08f2ddaSStefan Hajnoczi     struct iovec iov;
2446f08f2ddaSStefan Hajnoczi     int ret;
2447f08f2ddaSStefan Hajnoczi 
2448621f0589SKevin Wolf     /* TODO Emulate only part of misaligned requests instead of letting block
2449621f0589SKevin Wolf      * drivers return -ENOTSUP and emulate everything */
2450621f0589SKevin Wolf 
2451f08f2ddaSStefan Hajnoczi     /* First try the efficient write zeroes operation */
2452f08f2ddaSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes) {
2453621f0589SKevin Wolf         ret = drv->bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2454621f0589SKevin Wolf         if (ret != -ENOTSUP) {
2455621f0589SKevin Wolf             return ret;
2456621f0589SKevin Wolf         }
2457f08f2ddaSStefan Hajnoczi     }
2458f08f2ddaSStefan Hajnoczi 
2459f08f2ddaSStefan Hajnoczi     /* Fall back to bounce buffer if write zeroes is unsupported */
2460f08f2ddaSStefan Hajnoczi     iov.iov_len  = nb_sectors * BDRV_SECTOR_SIZE;
2461f08f2ddaSStefan Hajnoczi     iov.iov_base = qemu_blockalign(bs, iov.iov_len);
2462f08f2ddaSStefan Hajnoczi     memset(iov.iov_base, 0, iov.iov_len);
2463f08f2ddaSStefan Hajnoczi     qemu_iovec_init_external(&qiov, &iov, 1);
2464f08f2ddaSStefan Hajnoczi 
2465f08f2ddaSStefan Hajnoczi     ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
2466f08f2ddaSStefan Hajnoczi 
2467f08f2ddaSStefan Hajnoczi     qemu_vfree(iov.iov_base);
2468f08f2ddaSStefan Hajnoczi     return ret;
2469f08f2ddaSStefan Hajnoczi }
2470f08f2ddaSStefan Hajnoczi 
2471c5fbe571SStefan Hajnoczi /*
2472c5fbe571SStefan Hajnoczi  * Handle a write request in coroutine context
2473c5fbe571SStefan Hajnoczi  */
2474c5fbe571SStefan Hajnoczi static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
2475f08f2ddaSStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
2476f08f2ddaSStefan Hajnoczi     BdrvRequestFlags flags)
2477c5fbe571SStefan Hajnoczi {
2478c5fbe571SStefan Hajnoczi     BlockDriver *drv = bs->drv;
2479dbffbdcfSStefan Hajnoczi     BdrvTrackedRequest req;
24806b7cb247SStefan Hajnoczi     int ret;
2481da1fa91dSKevin Wolf 
2482da1fa91dSKevin Wolf     if (!bs->drv) {
2483da1fa91dSKevin Wolf         return -ENOMEDIUM;
2484da1fa91dSKevin Wolf     }
2485da1fa91dSKevin Wolf     if (bs->read_only) {
2486da1fa91dSKevin Wolf         return -EACCES;
2487da1fa91dSKevin Wolf     }
2488da1fa91dSKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors)) {
2489da1fa91dSKevin Wolf         return -EIO;
2490da1fa91dSKevin Wolf     }
2491da1fa91dSKevin Wolf 
249298f90dbaSZhi Yong Wu     /* throttling disk write I/O */
249398f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
249498f90dbaSZhi Yong Wu         bdrv_io_limits_intercept(bs, true, nb_sectors);
249598f90dbaSZhi Yong Wu     }
249698f90dbaSZhi Yong Wu 
2497470c0504SStefan Hajnoczi     if (bs->copy_on_read_in_flight) {
2498f4658285SStefan Hajnoczi         wait_for_overlapping_requests(bs, sector_num, nb_sectors);
2499f4658285SStefan Hajnoczi     }
2500f4658285SStefan Hajnoczi 
2501dbffbdcfSStefan Hajnoczi     tracked_request_begin(&req, bs, sector_num, nb_sectors, true);
2502dbffbdcfSStefan Hajnoczi 
2503f08f2ddaSStefan Hajnoczi     if (flags & BDRV_REQ_ZERO_WRITE) {
2504f08f2ddaSStefan Hajnoczi         ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors);
2505f08f2ddaSStefan Hajnoczi     } else {
25066b7cb247SStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
2507f08f2ddaSStefan Hajnoczi     }
25086b7cb247SStefan Hajnoczi 
2509f05fa4adSPaolo Bonzini     if (ret == 0 && !bs->enable_write_cache) {
2510f05fa4adSPaolo Bonzini         ret = bdrv_co_flush(bs);
2511f05fa4adSPaolo Bonzini     }
2512f05fa4adSPaolo Bonzini 
2513da1fa91dSKevin Wolf     if (bs->dirty_bitmap) {
25141755da16SPaolo Bonzini         bdrv_set_dirty(bs, sector_num, nb_sectors);
2515da1fa91dSKevin Wolf     }
2516da1fa91dSKevin Wolf 
2517da1fa91dSKevin Wolf     if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2518da1fa91dSKevin Wolf         bs->wr_highest_sector = sector_num + nb_sectors - 1;
2519da1fa91dSKevin Wolf     }
2520da1fa91dSKevin Wolf 
2521dbffbdcfSStefan Hajnoczi     tracked_request_end(&req);
2522dbffbdcfSStefan Hajnoczi 
25236b7cb247SStefan Hajnoczi     return ret;
2524da1fa91dSKevin Wolf }
2525da1fa91dSKevin Wolf 
2526c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
2527c5fbe571SStefan Hajnoczi     int nb_sectors, QEMUIOVector *qiov)
2528c5fbe571SStefan Hajnoczi {
2529c5fbe571SStefan Hajnoczi     trace_bdrv_co_writev(bs, sector_num, nb_sectors);
2530c5fbe571SStefan Hajnoczi 
2531f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
2532f08f2ddaSStefan Hajnoczi }
2533f08f2ddaSStefan Hajnoczi 
2534f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
2535f08f2ddaSStefan Hajnoczi                                       int64_t sector_num, int nb_sectors)
2536f08f2ddaSStefan Hajnoczi {
2537f08f2ddaSStefan Hajnoczi     trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors);
2538f08f2ddaSStefan Hajnoczi 
2539f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
2540f08f2ddaSStefan Hajnoczi                              BDRV_REQ_ZERO_WRITE);
2541c5fbe571SStefan Hajnoczi }
2542c5fbe571SStefan Hajnoczi 
254383f64091Sbellard /**
254483f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
254583f64091Sbellard  */
254683f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
254783f64091Sbellard {
254883f64091Sbellard     BlockDriver *drv = bs->drv;
254951762288SStefan Hajnoczi     int ret;
255083f64091Sbellard     if (!drv)
255119cb3738Sbellard         return -ENOMEDIUM;
255283f64091Sbellard     if (!drv->bdrv_truncate)
255383f64091Sbellard         return -ENOTSUP;
255459f2689dSNaphtali Sprei     if (bs->read_only)
255559f2689dSNaphtali Sprei         return -EACCES;
25568591675fSMarcelo Tosatti     if (bdrv_in_use(bs))
25578591675fSMarcelo Tosatti         return -EBUSY;
255851762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
255951762288SStefan Hajnoczi     if (ret == 0) {
256051762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2561145feb17SMarkus Armbruster         bdrv_dev_resize_cb(bs);
256251762288SStefan Hajnoczi     }
256351762288SStefan Hajnoczi     return ret;
256483f64091Sbellard }
256583f64091Sbellard 
256683f64091Sbellard /**
25674a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
25684a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
25694a1d5e1fSFam Zheng  */
25704a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
25714a1d5e1fSFam Zheng {
25724a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
25734a1d5e1fSFam Zheng     if (!drv) {
25744a1d5e1fSFam Zheng         return -ENOMEDIUM;
25754a1d5e1fSFam Zheng     }
25764a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
25774a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
25784a1d5e1fSFam Zheng     }
25794a1d5e1fSFam Zheng     if (bs->file) {
25804a1d5e1fSFam Zheng         return bdrv_get_allocated_file_size(bs->file);
25814a1d5e1fSFam Zheng     }
25824a1d5e1fSFam Zheng     return -ENOTSUP;
25834a1d5e1fSFam Zheng }
25844a1d5e1fSFam Zheng 
25854a1d5e1fSFam Zheng /**
258683f64091Sbellard  * Length of a file in bytes. Return < 0 if error or unknown.
258783f64091Sbellard  */
258883f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs)
258983f64091Sbellard {
259083f64091Sbellard     BlockDriver *drv = bs->drv;
259183f64091Sbellard     if (!drv)
259219cb3738Sbellard         return -ENOMEDIUM;
259351762288SStefan Hajnoczi 
25942c6942faSMarkus Armbruster     if (bs->growable || bdrv_dev_has_removable_media(bs)) {
259546a4e4e6SStefan Hajnoczi         if (drv->bdrv_getlength) {
259683f64091Sbellard             return drv->bdrv_getlength(bs);
2597fc01f7e7Sbellard         }
259846a4e4e6SStefan Hajnoczi     }
259946a4e4e6SStefan Hajnoczi     return bs->total_sectors * BDRV_SECTOR_SIZE;
260046a4e4e6SStefan Hajnoczi }
2601fc01f7e7Sbellard 
260219cb3738Sbellard /* return 0 as number of sectors if no device present or error */
260396b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2604fc01f7e7Sbellard {
260519cb3738Sbellard     int64_t length;
260619cb3738Sbellard     length = bdrv_getlength(bs);
260719cb3738Sbellard     if (length < 0)
260819cb3738Sbellard         length = 0;
260919cb3738Sbellard     else
26106ea44308SJan Kiszka         length = length >> BDRV_SECTOR_BITS;
261119cb3738Sbellard     *nb_sectors_ptr = length;
2612fc01f7e7Sbellard }
2613cf98951bSbellard 
26140563e191SZhi Yong Wu /* throttling disk io limits */
26150563e191SZhi Yong Wu void bdrv_set_io_limits(BlockDriverState *bs,
26160563e191SZhi Yong Wu                         BlockIOLimit *io_limits)
26170563e191SZhi Yong Wu {
26180563e191SZhi Yong Wu     bs->io_limits = *io_limits;
26190563e191SZhi Yong Wu     bs->io_limits_enabled = bdrv_io_limits_enabled(bs);
26200563e191SZhi Yong Wu }
26210563e191SZhi Yong Wu 
2622ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
2623ff06f5f3SPaolo Bonzini                        BlockdevOnError on_write_error)
2624abd7f68dSMarkus Armbruster {
2625abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
2626abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
2627abd7f68dSMarkus Armbruster }
2628abd7f68dSMarkus Armbruster 
26291ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
2630abd7f68dSMarkus Armbruster {
2631abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
2632abd7f68dSMarkus Armbruster }
2633abd7f68dSMarkus Armbruster 
26343e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
26353e1caa5fSPaolo Bonzini {
26363e1caa5fSPaolo Bonzini     BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
26373e1caa5fSPaolo Bonzini 
26383e1caa5fSPaolo Bonzini     switch (on_err) {
26393e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_ENOSPC:
26403e1caa5fSPaolo Bonzini         return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT;
26413e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_STOP:
26423e1caa5fSPaolo Bonzini         return BDRV_ACTION_STOP;
26433e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_REPORT:
26443e1caa5fSPaolo Bonzini         return BDRV_ACTION_REPORT;
26453e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_IGNORE:
26463e1caa5fSPaolo Bonzini         return BDRV_ACTION_IGNORE;
26473e1caa5fSPaolo Bonzini     default:
26483e1caa5fSPaolo Bonzini         abort();
26493e1caa5fSPaolo Bonzini     }
26503e1caa5fSPaolo Bonzini }
26513e1caa5fSPaolo Bonzini 
26523e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows
26533e1caa5fSPaolo Bonzini  * about the error, it does not know whether an operation comes from
26543e1caa5fSPaolo Bonzini  * the device or the block layer (from a job, for example).
26553e1caa5fSPaolo Bonzini  */
26563e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
26573e1caa5fSPaolo Bonzini                        bool is_read, int error)
26583e1caa5fSPaolo Bonzini {
26593e1caa5fSPaolo Bonzini     assert(error >= 0);
266032c81a4aSPaolo Bonzini     bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);
26613e1caa5fSPaolo Bonzini     if (action == BDRV_ACTION_STOP) {
26623e1caa5fSPaolo Bonzini         vm_stop(RUN_STATE_IO_ERROR);
26633e1caa5fSPaolo Bonzini         bdrv_iostatus_set_err(bs, error);
26643e1caa5fSPaolo Bonzini     }
26653e1caa5fSPaolo Bonzini }
26663e1caa5fSPaolo Bonzini 
2667b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2668b338082bSbellard {
2669b338082bSbellard     return bs->read_only;
2670b338082bSbellard }
2671b338082bSbellard 
2672985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2673985a03b0Sths {
2674985a03b0Sths     return bs->sg;
2675985a03b0Sths }
2676985a03b0Sths 
2677e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
2678e900a7b7SChristoph Hellwig {
2679e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
2680e900a7b7SChristoph Hellwig }
2681e900a7b7SChristoph Hellwig 
2682425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2683425b0148SPaolo Bonzini {
2684425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
268555b110f2SJeff Cody 
268655b110f2SJeff Cody     /* so a reopen() will preserve wce */
268755b110f2SJeff Cody     if (wce) {
268855b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
268955b110f2SJeff Cody     } else {
269055b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
269155b110f2SJeff Cody     }
2692425b0148SPaolo Bonzini }
2693425b0148SPaolo Bonzini 
2694ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2695ea2384d3Sbellard {
2696ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
2697ea2384d3Sbellard         return 1;
2698ea2384d3Sbellard     return bs->encrypted;
2699ea2384d3Sbellard }
2700ea2384d3Sbellard 
2701c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2702c0f4ce77Saliguori {
2703c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
2704c0f4ce77Saliguori 
2705c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
2706c0f4ce77Saliguori         return 1;
2707c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2708c0f4ce77Saliguori }
2709c0f4ce77Saliguori 
2710ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2711ea2384d3Sbellard {
2712ea2384d3Sbellard     int ret;
2713ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
2714ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
2715ea2384d3Sbellard         if (ret < 0)
2716ea2384d3Sbellard             return ret;
2717ea2384d3Sbellard         if (!bs->encrypted)
2718ea2384d3Sbellard             return 0;
2719ea2384d3Sbellard     }
2720fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2721fd04a2aeSShahar Havivi         return -EINVAL;
2722fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2723fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2724fd04a2aeSShahar Havivi     }
2725c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2726bb5fc20fSaliguori     if (ret < 0) {
2727bb5fc20fSaliguori         bs->valid_key = 0;
2728bb5fc20fSaliguori     } else if (!bs->valid_key) {
2729bb5fc20fSaliguori         bs->valid_key = 1;
2730bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
27317d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
2732bb5fc20fSaliguori     }
2733c0f4ce77Saliguori     return ret;
2734ea2384d3Sbellard }
2735ea2384d3Sbellard 
2736f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
2737ea2384d3Sbellard {
2738f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
2739ea2384d3Sbellard }
2740ea2384d3Sbellard 
2741ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2742ea2384d3Sbellard                          void *opaque)
2743ea2384d3Sbellard {
2744ea2384d3Sbellard     BlockDriver *drv;
2745ea2384d3Sbellard 
27468a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2747ea2384d3Sbellard         it(opaque, drv->format_name);
2748ea2384d3Sbellard     }
2749ea2384d3Sbellard }
2750ea2384d3Sbellard 
2751b338082bSbellard BlockDriverState *bdrv_find(const char *name)
2752b338082bSbellard {
2753b338082bSbellard     BlockDriverState *bs;
2754b338082bSbellard 
27551b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
27561b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
2757b338082bSbellard             return bs;
2758b338082bSbellard         }
27591b7bdbc1SStefan Hajnoczi     }
2760b338082bSbellard     return NULL;
2761b338082bSbellard }
2762b338082bSbellard 
27632f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
27642f399b0aSMarkus Armbruster {
27652f399b0aSMarkus Armbruster     if (!bs) {
27662f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
27672f399b0aSMarkus Armbruster     }
27682f399b0aSMarkus Armbruster     return QTAILQ_NEXT(bs, list);
27692f399b0aSMarkus Armbruster }
27702f399b0aSMarkus Armbruster 
277151de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
277281d0912dSbellard {
277381d0912dSbellard     BlockDriverState *bs;
277481d0912dSbellard 
27751b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
277651de9760Saliguori         it(opaque, bs);
277781d0912dSbellard     }
277881d0912dSbellard }
277981d0912dSbellard 
2780ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
2781ea2384d3Sbellard {
2782ea2384d3Sbellard     return bs->device_name;
2783ea2384d3Sbellard }
2784ea2384d3Sbellard 
2785c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
2786c8433287SMarkus Armbruster {
2787c8433287SMarkus Armbruster     return bs->open_flags;
2788c8433287SMarkus Armbruster }
2789c8433287SMarkus Armbruster 
2790c6ca28d6Saliguori void bdrv_flush_all(void)
2791c6ca28d6Saliguori {
2792c6ca28d6Saliguori     BlockDriverState *bs;
2793c6ca28d6Saliguori 
27941b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
2795c6ca28d6Saliguori         bdrv_flush(bs);
2796c6ca28d6Saliguori     }
27971b7bdbc1SStefan Hajnoczi }
2798c6ca28d6Saliguori 
2799f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
2800f2feebbdSKevin Wolf {
2801f2feebbdSKevin Wolf     assert(bs->drv);
2802f2feebbdSKevin Wolf 
2803336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
2804336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
2805f2feebbdSKevin Wolf     }
2806f2feebbdSKevin Wolf 
2807f2feebbdSKevin Wolf     return 1;
2808f2feebbdSKevin Wolf }
2809f2feebbdSKevin Wolf 
2810376ae3f1SStefan Hajnoczi typedef struct BdrvCoIsAllocatedData {
2811376ae3f1SStefan Hajnoczi     BlockDriverState *bs;
2812b35b2bbaSMiroslav Rezanina     BlockDriverState *base;
2813376ae3f1SStefan Hajnoczi     int64_t sector_num;
2814376ae3f1SStefan Hajnoczi     int nb_sectors;
2815376ae3f1SStefan Hajnoczi     int *pnum;
2816376ae3f1SStefan Hajnoczi     int ret;
2817376ae3f1SStefan Hajnoczi     bool done;
2818376ae3f1SStefan Hajnoczi } BdrvCoIsAllocatedData;
2819376ae3f1SStefan Hajnoczi 
2820f58c7b35Sths /*
2821f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
2822f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
2823f58c7b35Sths  * hence all their sectors are reported as allocated.
2824f58c7b35Sths  *
2825bd9533e3SStefan Hajnoczi  * If 'sector_num' is beyond the end of the disk image the return value is 0
2826bd9533e3SStefan Hajnoczi  * and 'pnum' is set to 0.
2827bd9533e3SStefan Hajnoczi  *
2828f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
2829f58c7b35Sths  * the specified sector) that are known to be in the same
2830f58c7b35Sths  * allocated/unallocated state.
2831f58c7b35Sths  *
2832bd9533e3SStefan Hajnoczi  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
2833bd9533e3SStefan Hajnoczi  * beyond the end of the disk image it will be clamped.
2834f58c7b35Sths  */
2835060f51c9SStefan Hajnoczi int coroutine_fn bdrv_co_is_allocated(BlockDriverState *bs, int64_t sector_num,
2836060f51c9SStefan Hajnoczi                                       int nb_sectors, int *pnum)
2837f58c7b35Sths {
2838f58c7b35Sths     int64_t n;
2839bd9533e3SStefan Hajnoczi 
28406aebab14SStefan Hajnoczi     if (sector_num >= bs->total_sectors) {
28416aebab14SStefan Hajnoczi         *pnum = 0;
28426aebab14SStefan Hajnoczi         return 0;
28436aebab14SStefan Hajnoczi     }
2844bd9533e3SStefan Hajnoczi 
28456aebab14SStefan Hajnoczi     n = bs->total_sectors - sector_num;
2846bd9533e3SStefan Hajnoczi     if (n < nb_sectors) {
2847bd9533e3SStefan Hajnoczi         nb_sectors = n;
2848bd9533e3SStefan Hajnoczi     }
2849bd9533e3SStefan Hajnoczi 
2850bd9533e3SStefan Hajnoczi     if (!bs->drv->bdrv_co_is_allocated) {
2851bd9533e3SStefan Hajnoczi         *pnum = nb_sectors;
28526aebab14SStefan Hajnoczi         return 1;
28536aebab14SStefan Hajnoczi     }
28546aebab14SStefan Hajnoczi 
2855060f51c9SStefan Hajnoczi     return bs->drv->bdrv_co_is_allocated(bs, sector_num, nb_sectors, pnum);
2856060f51c9SStefan Hajnoczi }
2857060f51c9SStefan Hajnoczi 
2858060f51c9SStefan Hajnoczi /* Coroutine wrapper for bdrv_is_allocated() */
2859060f51c9SStefan Hajnoczi static void coroutine_fn bdrv_is_allocated_co_entry(void *opaque)
2860060f51c9SStefan Hajnoczi {
2861060f51c9SStefan Hajnoczi     BdrvCoIsAllocatedData *data = opaque;
2862060f51c9SStefan Hajnoczi     BlockDriverState *bs = data->bs;
2863060f51c9SStefan Hajnoczi 
2864060f51c9SStefan Hajnoczi     data->ret = bdrv_co_is_allocated(bs, data->sector_num, data->nb_sectors,
2865060f51c9SStefan Hajnoczi                                      data->pnum);
2866060f51c9SStefan Hajnoczi     data->done = true;
2867060f51c9SStefan Hajnoczi }
2868060f51c9SStefan Hajnoczi 
2869060f51c9SStefan Hajnoczi /*
2870060f51c9SStefan Hajnoczi  * Synchronous wrapper around bdrv_co_is_allocated().
2871060f51c9SStefan Hajnoczi  *
2872060f51c9SStefan Hajnoczi  * See bdrv_co_is_allocated() for details.
2873060f51c9SStefan Hajnoczi  */
2874060f51c9SStefan Hajnoczi int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
2875060f51c9SStefan Hajnoczi                       int *pnum)
2876060f51c9SStefan Hajnoczi {
2877376ae3f1SStefan Hajnoczi     Coroutine *co;
2878376ae3f1SStefan Hajnoczi     BdrvCoIsAllocatedData data = {
2879376ae3f1SStefan Hajnoczi         .bs = bs,
2880376ae3f1SStefan Hajnoczi         .sector_num = sector_num,
2881376ae3f1SStefan Hajnoczi         .nb_sectors = nb_sectors,
2882376ae3f1SStefan Hajnoczi         .pnum = pnum,
2883376ae3f1SStefan Hajnoczi         .done = false,
2884376ae3f1SStefan Hajnoczi     };
2885376ae3f1SStefan Hajnoczi 
2886376ae3f1SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_is_allocated_co_entry);
2887376ae3f1SStefan Hajnoczi     qemu_coroutine_enter(co, &data);
2888376ae3f1SStefan Hajnoczi     while (!data.done) {
2889376ae3f1SStefan Hajnoczi         qemu_aio_wait();
2890376ae3f1SStefan Hajnoczi     }
2891376ae3f1SStefan Hajnoczi     return data.ret;
2892376ae3f1SStefan Hajnoczi }
2893f58c7b35Sths 
2894188a7bbfSPaolo Bonzini /*
2895188a7bbfSPaolo Bonzini  * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2896188a7bbfSPaolo Bonzini  *
2897188a7bbfSPaolo Bonzini  * Return true if the given sector is allocated in any image between
2898188a7bbfSPaolo Bonzini  * BASE and TOP (inclusive).  BASE can be NULL to check if the given
2899188a7bbfSPaolo Bonzini  * sector is allocated in any image of the chain.  Return false otherwise.
2900188a7bbfSPaolo Bonzini  *
2901188a7bbfSPaolo Bonzini  * 'pnum' is set to the number of sectors (including and immediately following
2902188a7bbfSPaolo Bonzini  *  the specified sector) that are known to be in the same
2903188a7bbfSPaolo Bonzini  *  allocated/unallocated state.
2904188a7bbfSPaolo Bonzini  *
2905188a7bbfSPaolo Bonzini  */
2906188a7bbfSPaolo Bonzini int coroutine_fn bdrv_co_is_allocated_above(BlockDriverState *top,
2907188a7bbfSPaolo Bonzini                                             BlockDriverState *base,
2908188a7bbfSPaolo Bonzini                                             int64_t sector_num,
2909188a7bbfSPaolo Bonzini                                             int nb_sectors, int *pnum)
2910188a7bbfSPaolo Bonzini {
2911188a7bbfSPaolo Bonzini     BlockDriverState *intermediate;
2912188a7bbfSPaolo Bonzini     int ret, n = nb_sectors;
2913188a7bbfSPaolo Bonzini 
2914188a7bbfSPaolo Bonzini     intermediate = top;
2915188a7bbfSPaolo Bonzini     while (intermediate && intermediate != base) {
2916188a7bbfSPaolo Bonzini         int pnum_inter;
2917188a7bbfSPaolo Bonzini         ret = bdrv_co_is_allocated(intermediate, sector_num, nb_sectors,
2918188a7bbfSPaolo Bonzini                                    &pnum_inter);
2919188a7bbfSPaolo Bonzini         if (ret < 0) {
2920188a7bbfSPaolo Bonzini             return ret;
2921188a7bbfSPaolo Bonzini         } else if (ret) {
2922188a7bbfSPaolo Bonzini             *pnum = pnum_inter;
2923188a7bbfSPaolo Bonzini             return 1;
2924188a7bbfSPaolo Bonzini         }
2925188a7bbfSPaolo Bonzini 
2926188a7bbfSPaolo Bonzini         /*
2927188a7bbfSPaolo Bonzini          * [sector_num, nb_sectors] is unallocated on top but intermediate
2928188a7bbfSPaolo Bonzini          * might have
2929188a7bbfSPaolo Bonzini          *
2930188a7bbfSPaolo Bonzini          * [sector_num+x, nr_sectors] allocated.
2931188a7bbfSPaolo Bonzini          */
293263ba17d3SVishvananda Ishaya         if (n > pnum_inter &&
293363ba17d3SVishvananda Ishaya             (intermediate == top ||
293463ba17d3SVishvananda Ishaya              sector_num + pnum_inter < intermediate->total_sectors)) {
2935188a7bbfSPaolo Bonzini             n = pnum_inter;
2936188a7bbfSPaolo Bonzini         }
2937188a7bbfSPaolo Bonzini 
2938188a7bbfSPaolo Bonzini         intermediate = intermediate->backing_hd;
2939188a7bbfSPaolo Bonzini     }
2940188a7bbfSPaolo Bonzini 
2941188a7bbfSPaolo Bonzini     *pnum = n;
2942188a7bbfSPaolo Bonzini     return 0;
2943188a7bbfSPaolo Bonzini }
2944188a7bbfSPaolo Bonzini 
2945b35b2bbaSMiroslav Rezanina /* Coroutine wrapper for bdrv_is_allocated_above() */
2946b35b2bbaSMiroslav Rezanina static void coroutine_fn bdrv_is_allocated_above_co_entry(void *opaque)
2947b35b2bbaSMiroslav Rezanina {
2948b35b2bbaSMiroslav Rezanina     BdrvCoIsAllocatedData *data = opaque;
2949b35b2bbaSMiroslav Rezanina     BlockDriverState *top = data->bs;
2950b35b2bbaSMiroslav Rezanina     BlockDriverState *base = data->base;
2951b35b2bbaSMiroslav Rezanina 
2952b35b2bbaSMiroslav Rezanina     data->ret = bdrv_co_is_allocated_above(top, base, data->sector_num,
2953b35b2bbaSMiroslav Rezanina                                            data->nb_sectors, data->pnum);
2954b35b2bbaSMiroslav Rezanina     data->done = true;
2955b35b2bbaSMiroslav Rezanina }
2956b35b2bbaSMiroslav Rezanina 
2957b35b2bbaSMiroslav Rezanina /*
2958b35b2bbaSMiroslav Rezanina  * Synchronous wrapper around bdrv_co_is_allocated_above().
2959b35b2bbaSMiroslav Rezanina  *
2960b35b2bbaSMiroslav Rezanina  * See bdrv_co_is_allocated_above() for details.
2961b35b2bbaSMiroslav Rezanina  */
2962b35b2bbaSMiroslav Rezanina int bdrv_is_allocated_above(BlockDriverState *top, BlockDriverState *base,
2963b35b2bbaSMiroslav Rezanina                             int64_t sector_num, int nb_sectors, int *pnum)
2964b35b2bbaSMiroslav Rezanina {
2965b35b2bbaSMiroslav Rezanina     Coroutine *co;
2966b35b2bbaSMiroslav Rezanina     BdrvCoIsAllocatedData data = {
2967b35b2bbaSMiroslav Rezanina         .bs = top,
2968b35b2bbaSMiroslav Rezanina         .base = base,
2969b35b2bbaSMiroslav Rezanina         .sector_num = sector_num,
2970b35b2bbaSMiroslav Rezanina         .nb_sectors = nb_sectors,
2971b35b2bbaSMiroslav Rezanina         .pnum = pnum,
2972b35b2bbaSMiroslav Rezanina         .done = false,
2973b35b2bbaSMiroslav Rezanina     };
2974b35b2bbaSMiroslav Rezanina 
2975b35b2bbaSMiroslav Rezanina     co = qemu_coroutine_create(bdrv_is_allocated_above_co_entry);
2976b35b2bbaSMiroslav Rezanina     qemu_coroutine_enter(co, &data);
2977b35b2bbaSMiroslav Rezanina     while (!data.done) {
2978b35b2bbaSMiroslav Rezanina         qemu_aio_wait();
2979b35b2bbaSMiroslav Rezanina     }
2980b35b2bbaSMiroslav Rezanina     return data.ret;
2981b35b2bbaSMiroslav Rezanina }
2982b35b2bbaSMiroslav Rezanina 
2983ac84adacSPaolo Bonzini BlockInfo *bdrv_query_info(BlockDriverState *bs)
2984ac84adacSPaolo Bonzini {
2985ac84adacSPaolo Bonzini     BlockInfo *info = g_malloc0(sizeof(*info));
2986ac84adacSPaolo Bonzini     info->device = g_strdup(bs->device_name);
2987ac84adacSPaolo Bonzini     info->type = g_strdup("unknown");
2988ac84adacSPaolo Bonzini     info->locked = bdrv_dev_is_medium_locked(bs);
2989ac84adacSPaolo Bonzini     info->removable = bdrv_dev_has_removable_media(bs);
2990ac84adacSPaolo Bonzini 
2991ac84adacSPaolo Bonzini     if (bdrv_dev_has_removable_media(bs)) {
2992ac84adacSPaolo Bonzini         info->has_tray_open = true;
2993ac84adacSPaolo Bonzini         info->tray_open = bdrv_dev_is_tray_open(bs);
2994ac84adacSPaolo Bonzini     }
2995ac84adacSPaolo Bonzini 
2996ac84adacSPaolo Bonzini     if (bdrv_iostatus_is_enabled(bs)) {
2997ac84adacSPaolo Bonzini         info->has_io_status = true;
2998ac84adacSPaolo Bonzini         info->io_status = bs->iostatus;
2999ac84adacSPaolo Bonzini     }
3000ac84adacSPaolo Bonzini 
3001b9a9b3a4SPaolo Bonzini     if (bs->dirty_bitmap) {
3002b9a9b3a4SPaolo Bonzini         info->has_dirty = true;
3003b9a9b3a4SPaolo Bonzini         info->dirty = g_malloc0(sizeof(*info->dirty));
3004acc906c6SPaolo Bonzini         info->dirty->count = bdrv_get_dirty_count(bs) * BDRV_SECTOR_SIZE;
300550717e94SPaolo Bonzini         info->dirty->granularity =
300650717e94SPaolo Bonzini             ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bs->dirty_bitmap));
3007b9a9b3a4SPaolo Bonzini     }
3008b9a9b3a4SPaolo Bonzini 
3009ac84adacSPaolo Bonzini     if (bs->drv) {
3010ac84adacSPaolo Bonzini         info->has_inserted = true;
3011ac84adacSPaolo Bonzini         info->inserted = g_malloc0(sizeof(*info->inserted));
3012ac84adacSPaolo Bonzini         info->inserted->file = g_strdup(bs->filename);
3013ac84adacSPaolo Bonzini         info->inserted->ro = bs->read_only;
3014ac84adacSPaolo Bonzini         info->inserted->drv = g_strdup(bs->drv->format_name);
3015ac84adacSPaolo Bonzini         info->inserted->encrypted = bs->encrypted;
3016ac84adacSPaolo Bonzini         info->inserted->encryption_key_missing = bdrv_key_required(bs);
3017ac84adacSPaolo Bonzini 
3018ac84adacSPaolo Bonzini         if (bs->backing_file[0]) {
3019ac84adacSPaolo Bonzini             info->inserted->has_backing_file = true;
3020ac84adacSPaolo Bonzini             info->inserted->backing_file = g_strdup(bs->backing_file);
3021ac84adacSPaolo Bonzini         }
3022ac84adacSPaolo Bonzini 
3023ac84adacSPaolo Bonzini         info->inserted->backing_file_depth = bdrv_get_backing_file_depth(bs);
3024ac84adacSPaolo Bonzini 
3025ac84adacSPaolo Bonzini         if (bs->io_limits_enabled) {
3026ac84adacSPaolo Bonzini             info->inserted->bps =
3027ac84adacSPaolo Bonzini                            bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
3028ac84adacSPaolo Bonzini             info->inserted->bps_rd =
3029ac84adacSPaolo Bonzini                            bs->io_limits.bps[BLOCK_IO_LIMIT_READ];
3030ac84adacSPaolo Bonzini             info->inserted->bps_wr =
3031ac84adacSPaolo Bonzini                            bs->io_limits.bps[BLOCK_IO_LIMIT_WRITE];
3032ac84adacSPaolo Bonzini             info->inserted->iops =
3033ac84adacSPaolo Bonzini                            bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
3034ac84adacSPaolo Bonzini             info->inserted->iops_rd =
3035ac84adacSPaolo Bonzini                            bs->io_limits.iops[BLOCK_IO_LIMIT_READ];
3036ac84adacSPaolo Bonzini             info->inserted->iops_wr =
3037ac84adacSPaolo Bonzini                            bs->io_limits.iops[BLOCK_IO_LIMIT_WRITE];
3038ac84adacSPaolo Bonzini         }
3039ac84adacSPaolo Bonzini     }
3040ac84adacSPaolo Bonzini     return info;
3041ac84adacSPaolo Bonzini }
3042ac84adacSPaolo Bonzini 
3043b2023818SLuiz Capitulino BlockInfoList *qmp_query_block(Error **errp)
3044b338082bSbellard {
3045ac84adacSPaolo Bonzini     BlockInfoList *head = NULL, **p_next = &head;
3046d15e5465SLuiz Capitulino     BlockDriverState *bs;
3047d15e5465SLuiz Capitulino 
30481b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
3049b2023818SLuiz Capitulino         BlockInfoList *info = g_malloc0(sizeof(*info));
3050ac84adacSPaolo Bonzini         info->value = bdrv_query_info(bs);
3051d15e5465SLuiz Capitulino 
3052ac84adacSPaolo Bonzini         *p_next = info;
3053ac84adacSPaolo Bonzini         p_next = &info->next;
3054d15e5465SLuiz Capitulino     }
3055d15e5465SLuiz Capitulino 
3056b2023818SLuiz Capitulino     return head;
3057b338082bSbellard }
3058a36e69ddSths 
30599887b616SPaolo Bonzini BlockStats *bdrv_query_stats(const BlockDriverState *bs)
3060a36e69ddSths {
3061f11f57e4SLuiz Capitulino     BlockStats *s;
3062218a536aSLuiz Capitulino 
3063f11f57e4SLuiz Capitulino     s = g_malloc0(sizeof(*s));
3064218a536aSLuiz Capitulino 
3065f11f57e4SLuiz Capitulino     if (bs->device_name[0]) {
3066f11f57e4SLuiz Capitulino         s->has_device = true;
3067f11f57e4SLuiz Capitulino         s->device = g_strdup(bs->device_name);
3068218a536aSLuiz Capitulino     }
3069218a536aSLuiz Capitulino 
3070f11f57e4SLuiz Capitulino     s->stats = g_malloc0(sizeof(*s->stats));
3071f11f57e4SLuiz Capitulino     s->stats->rd_bytes = bs->nr_bytes[BDRV_ACCT_READ];
3072f11f57e4SLuiz Capitulino     s->stats->wr_bytes = bs->nr_bytes[BDRV_ACCT_WRITE];
3073f11f57e4SLuiz Capitulino     s->stats->rd_operations = bs->nr_ops[BDRV_ACCT_READ];
3074f11f57e4SLuiz Capitulino     s->stats->wr_operations = bs->nr_ops[BDRV_ACCT_WRITE];
3075f11f57e4SLuiz Capitulino     s->stats->wr_highest_offset = bs->wr_highest_sector * BDRV_SECTOR_SIZE;
3076f11f57e4SLuiz Capitulino     s->stats->flush_operations = bs->nr_ops[BDRV_ACCT_FLUSH];
3077f11f57e4SLuiz Capitulino     s->stats->wr_total_time_ns = bs->total_time_ns[BDRV_ACCT_WRITE];
3078f11f57e4SLuiz Capitulino     s->stats->rd_total_time_ns = bs->total_time_ns[BDRV_ACCT_READ];
3079f11f57e4SLuiz Capitulino     s->stats->flush_total_time_ns = bs->total_time_ns[BDRV_ACCT_FLUSH];
3080294cc35fSKevin Wolf 
3081294cc35fSKevin Wolf     if (bs->file) {
3082f11f57e4SLuiz Capitulino         s->has_parent = true;
30839887b616SPaolo Bonzini         s->parent = bdrv_query_stats(bs->file);
3084294cc35fSKevin Wolf     }
3085294cc35fSKevin Wolf 
3086f11f57e4SLuiz Capitulino     return s;
3087294cc35fSKevin Wolf }
3088294cc35fSKevin Wolf 
3089f11f57e4SLuiz Capitulino BlockStatsList *qmp_query_blockstats(Error **errp)
3090218a536aSLuiz Capitulino {
30919887b616SPaolo Bonzini     BlockStatsList *head = NULL, **p_next = &head;
3092a36e69ddSths     BlockDriverState *bs;
3093a36e69ddSths 
30941b7bdbc1SStefan Hajnoczi     QTAILQ_FOREACH(bs, &bdrv_states, list) {
3095f11f57e4SLuiz Capitulino         BlockStatsList *info = g_malloc0(sizeof(*info));
30969887b616SPaolo Bonzini         info->value = bdrv_query_stats(bs);
3097f11f57e4SLuiz Capitulino 
30989887b616SPaolo Bonzini         *p_next = info;
30999887b616SPaolo Bonzini         p_next = &info->next;
3100a36e69ddSths     }
3101218a536aSLuiz Capitulino 
3102f11f57e4SLuiz Capitulino     return head;
3103a36e69ddSths }
3104ea2384d3Sbellard 
3105045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3106045df330Saliguori {
3107045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
3108045df330Saliguori         return bs->backing_file;
3109045df330Saliguori     else if (bs->encrypted)
3110045df330Saliguori         return bs->filename;
3111045df330Saliguori     else
3112045df330Saliguori         return NULL;
3113045df330Saliguori }
3114045df330Saliguori 
311583f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
311683f64091Sbellard                                char *filename, int filename_size)
311783f64091Sbellard {
311883f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
311983f64091Sbellard }
312083f64091Sbellard 
3121faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
3122faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
3123faea38e7Sbellard {
3124faea38e7Sbellard     BlockDriver *drv = bs->drv;
3125faea38e7Sbellard     if (!drv)
312619cb3738Sbellard         return -ENOMEDIUM;
3127faea38e7Sbellard     if (!drv->bdrv_write_compressed)
3128faea38e7Sbellard         return -ENOTSUP;
3129fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
3130fbb7b4e0SKevin Wolf         return -EIO;
31317cd1e32aSlirans@il.ibm.com 
31321755da16SPaolo Bonzini     assert(!bs->dirty_bitmap);
31337cd1e32aSlirans@il.ibm.com 
3134faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
3135faea38e7Sbellard }
3136faea38e7Sbellard 
3137faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3138faea38e7Sbellard {
3139faea38e7Sbellard     BlockDriver *drv = bs->drv;
3140faea38e7Sbellard     if (!drv)
314119cb3738Sbellard         return -ENOMEDIUM;
3142faea38e7Sbellard     if (!drv->bdrv_get_info)
3143faea38e7Sbellard         return -ENOTSUP;
3144faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
3145faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
3146faea38e7Sbellard }
3147faea38e7Sbellard 
314845566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
314945566e9cSChristoph Hellwig                       int64_t pos, int size)
3150178e08a5Saliguori {
3151178e08a5Saliguori     BlockDriver *drv = bs->drv;
3152178e08a5Saliguori     if (!drv)
3153178e08a5Saliguori         return -ENOMEDIUM;
31547cdb1f6dSMORITA Kazutaka     if (drv->bdrv_save_vmstate)
315545566e9cSChristoph Hellwig         return drv->bdrv_save_vmstate(bs, buf, pos, size);
31567cdb1f6dSMORITA Kazutaka     if (bs->file)
31577cdb1f6dSMORITA Kazutaka         return bdrv_save_vmstate(bs->file, buf, pos, size);
31587cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3159178e08a5Saliguori }
3160178e08a5Saliguori 
316145566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
316245566e9cSChristoph Hellwig                       int64_t pos, int size)
3163178e08a5Saliguori {
3164178e08a5Saliguori     BlockDriver *drv = bs->drv;
3165178e08a5Saliguori     if (!drv)
3166178e08a5Saliguori         return -ENOMEDIUM;
31677cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
316845566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
31697cdb1f6dSMORITA Kazutaka     if (bs->file)
31707cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
31717cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3172178e08a5Saliguori }
3173178e08a5Saliguori 
31748b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
31758b9b0cc2SKevin Wolf {
31768b9b0cc2SKevin Wolf     BlockDriver *drv = bs->drv;
31778b9b0cc2SKevin Wolf 
31788b9b0cc2SKevin Wolf     if (!drv || !drv->bdrv_debug_event) {
31798b9b0cc2SKevin Wolf         return;
31808b9b0cc2SKevin Wolf     }
31818b9b0cc2SKevin Wolf 
31820ed8b6f6SBlue Swirl     drv->bdrv_debug_event(bs, event);
318341c695c7SKevin Wolf }
31848b9b0cc2SKevin Wolf 
318541c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
318641c695c7SKevin Wolf                           const char *tag)
318741c695c7SKevin Wolf {
318841c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
318941c695c7SKevin Wolf         bs = bs->file;
319041c695c7SKevin Wolf     }
319141c695c7SKevin Wolf 
319241c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
319341c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
319441c695c7SKevin Wolf     }
319541c695c7SKevin Wolf 
319641c695c7SKevin Wolf     return -ENOTSUP;
319741c695c7SKevin Wolf }
319841c695c7SKevin Wolf 
319941c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
320041c695c7SKevin Wolf {
320141c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_resume) {
320241c695c7SKevin Wolf         bs = bs->file;
320341c695c7SKevin Wolf     }
320441c695c7SKevin Wolf 
320541c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
320641c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
320741c695c7SKevin Wolf     }
320841c695c7SKevin Wolf 
320941c695c7SKevin Wolf     return -ENOTSUP;
321041c695c7SKevin Wolf }
321141c695c7SKevin Wolf 
321241c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
321341c695c7SKevin Wolf {
321441c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
321541c695c7SKevin Wolf         bs = bs->file;
321641c695c7SKevin Wolf     }
321741c695c7SKevin Wolf 
321841c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
321941c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
322041c695c7SKevin Wolf     }
322141c695c7SKevin Wolf 
322241c695c7SKevin Wolf     return false;
32238b9b0cc2SKevin Wolf }
32248b9b0cc2SKevin Wolf 
3225faea38e7Sbellard /**************************************************************/
3226faea38e7Sbellard /* handling of snapshots */
3227faea38e7Sbellard 
3228feeee5acSMiguel Di Ciurcio Filho int bdrv_can_snapshot(BlockDriverState *bs)
3229feeee5acSMiguel Di Ciurcio Filho {
3230feeee5acSMiguel Di Ciurcio Filho     BlockDriver *drv = bs->drv;
323107b70bfbSMarkus Armbruster     if (!drv || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
3232feeee5acSMiguel Di Ciurcio Filho         return 0;
3233feeee5acSMiguel Di Ciurcio Filho     }
3234feeee5acSMiguel Di Ciurcio Filho 
3235feeee5acSMiguel Di Ciurcio Filho     if (!drv->bdrv_snapshot_create) {
3236feeee5acSMiguel Di Ciurcio Filho         if (bs->file != NULL) {
3237feeee5acSMiguel Di Ciurcio Filho             return bdrv_can_snapshot(bs->file);
3238feeee5acSMiguel Di Ciurcio Filho         }
3239feeee5acSMiguel Di Ciurcio Filho         return 0;
3240feeee5acSMiguel Di Ciurcio Filho     }
3241feeee5acSMiguel Di Ciurcio Filho 
3242feeee5acSMiguel Di Ciurcio Filho     return 1;
3243feeee5acSMiguel Di Ciurcio Filho }
3244feeee5acSMiguel Di Ciurcio Filho 
3245199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
3246199630b6SBlue Swirl {
3247199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3248199630b6SBlue Swirl }
3249199630b6SBlue Swirl 
3250f9092b10SMarkus Armbruster BlockDriverState *bdrv_snapshots(void)
3251f9092b10SMarkus Armbruster {
3252f9092b10SMarkus Armbruster     BlockDriverState *bs;
3253f9092b10SMarkus Armbruster 
32543ac906f7SMarkus Armbruster     if (bs_snapshots) {
3255f9092b10SMarkus Armbruster         return bs_snapshots;
32563ac906f7SMarkus Armbruster     }
3257f9092b10SMarkus Armbruster 
3258f9092b10SMarkus Armbruster     bs = NULL;
3259f9092b10SMarkus Armbruster     while ((bs = bdrv_next(bs))) {
3260f9092b10SMarkus Armbruster         if (bdrv_can_snapshot(bs)) {
32613ac906f7SMarkus Armbruster             bs_snapshots = bs;
32623ac906f7SMarkus Armbruster             return bs;
3263f9092b10SMarkus Armbruster         }
3264f9092b10SMarkus Armbruster     }
3265f9092b10SMarkus Armbruster     return NULL;
3266f9092b10SMarkus Armbruster }
3267f9092b10SMarkus Armbruster 
3268faea38e7Sbellard int bdrv_snapshot_create(BlockDriverState *bs,
3269faea38e7Sbellard                          QEMUSnapshotInfo *sn_info)
3270faea38e7Sbellard {
3271faea38e7Sbellard     BlockDriver *drv = bs->drv;
3272faea38e7Sbellard     if (!drv)
327319cb3738Sbellard         return -ENOMEDIUM;
32747cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_create)
3275faea38e7Sbellard         return drv->bdrv_snapshot_create(bs, sn_info);
32767cdb1f6dSMORITA Kazutaka     if (bs->file)
32777cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_create(bs->file, sn_info);
32787cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3279faea38e7Sbellard }
3280faea38e7Sbellard 
3281faea38e7Sbellard int bdrv_snapshot_goto(BlockDriverState *bs,
3282faea38e7Sbellard                        const char *snapshot_id)
3283faea38e7Sbellard {
3284faea38e7Sbellard     BlockDriver *drv = bs->drv;
32857cdb1f6dSMORITA Kazutaka     int ret, open_ret;
32867cdb1f6dSMORITA Kazutaka 
3287faea38e7Sbellard     if (!drv)
328819cb3738Sbellard         return -ENOMEDIUM;
32897cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_goto)
3290faea38e7Sbellard         return drv->bdrv_snapshot_goto(bs, snapshot_id);
32917cdb1f6dSMORITA Kazutaka 
32927cdb1f6dSMORITA Kazutaka     if (bs->file) {
32937cdb1f6dSMORITA Kazutaka         drv->bdrv_close(bs);
32947cdb1f6dSMORITA Kazutaka         ret = bdrv_snapshot_goto(bs->file, snapshot_id);
32951a86938fSKevin Wolf         open_ret = drv->bdrv_open(bs, NULL, bs->open_flags);
32967cdb1f6dSMORITA Kazutaka         if (open_ret < 0) {
32977cdb1f6dSMORITA Kazutaka             bdrv_delete(bs->file);
32987cdb1f6dSMORITA Kazutaka             bs->drv = NULL;
32997cdb1f6dSMORITA Kazutaka             return open_ret;
33007cdb1f6dSMORITA Kazutaka         }
33017cdb1f6dSMORITA Kazutaka         return ret;
33027cdb1f6dSMORITA Kazutaka     }
33037cdb1f6dSMORITA Kazutaka 
33047cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3305faea38e7Sbellard }
3306faea38e7Sbellard 
3307faea38e7Sbellard int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
3308faea38e7Sbellard {
3309faea38e7Sbellard     BlockDriver *drv = bs->drv;
3310faea38e7Sbellard     if (!drv)
331119cb3738Sbellard         return -ENOMEDIUM;
33127cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_delete)
3313faea38e7Sbellard         return drv->bdrv_snapshot_delete(bs, snapshot_id);
33147cdb1f6dSMORITA Kazutaka     if (bs->file)
33157cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_delete(bs->file, snapshot_id);
33167cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3317faea38e7Sbellard }
3318faea38e7Sbellard 
3319faea38e7Sbellard int bdrv_snapshot_list(BlockDriverState *bs,
3320faea38e7Sbellard                        QEMUSnapshotInfo **psn_info)
3321faea38e7Sbellard {
3322faea38e7Sbellard     BlockDriver *drv = bs->drv;
3323faea38e7Sbellard     if (!drv)
332419cb3738Sbellard         return -ENOMEDIUM;
33257cdb1f6dSMORITA Kazutaka     if (drv->bdrv_snapshot_list)
3326faea38e7Sbellard         return drv->bdrv_snapshot_list(bs, psn_info);
33277cdb1f6dSMORITA Kazutaka     if (bs->file)
33287cdb1f6dSMORITA Kazutaka         return bdrv_snapshot_list(bs->file, psn_info);
33297cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
3330faea38e7Sbellard }
3331faea38e7Sbellard 
333251ef6727Sedison int bdrv_snapshot_load_tmp(BlockDriverState *bs,
333351ef6727Sedison         const char *snapshot_name)
333451ef6727Sedison {
333551ef6727Sedison     BlockDriver *drv = bs->drv;
333651ef6727Sedison     if (!drv) {
333751ef6727Sedison         return -ENOMEDIUM;
333851ef6727Sedison     }
333951ef6727Sedison     if (!bs->read_only) {
334051ef6727Sedison         return -EINVAL;
334151ef6727Sedison     }
334251ef6727Sedison     if (drv->bdrv_snapshot_load_tmp) {
334351ef6727Sedison         return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
334451ef6727Sedison     }
334551ef6727Sedison     return -ENOTSUP;
334651ef6727Sedison }
334751ef6727Sedison 
3348b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
3349b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
3350b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
3351b1b1d783SJeff Cody  * the CWD rather than the chain. */
3352e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3353e8a6bb9cSMarcelo Tosatti         const char *backing_file)
3354e8a6bb9cSMarcelo Tosatti {
3355b1b1d783SJeff Cody     char *filename_full = NULL;
3356b1b1d783SJeff Cody     char *backing_file_full = NULL;
3357b1b1d783SJeff Cody     char *filename_tmp = NULL;
3358b1b1d783SJeff Cody     int is_protocol = 0;
3359b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
3360b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
3361b1b1d783SJeff Cody 
3362b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
3363e8a6bb9cSMarcelo Tosatti         return NULL;
3364e8a6bb9cSMarcelo Tosatti     }
3365e8a6bb9cSMarcelo Tosatti 
3366b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
3367b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
3368b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
3369b1b1d783SJeff Cody 
3370b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
3371b1b1d783SJeff Cody 
3372b1b1d783SJeff Cody     for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
3373b1b1d783SJeff Cody 
3374b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
3375b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
3376b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3377b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3378b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
3379b1b1d783SJeff Cody                 break;
3380b1b1d783SJeff Cody             }
3381e8a6bb9cSMarcelo Tosatti         } else {
3382b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
3383b1b1d783SJeff Cody              * image's filename path */
3384b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3385b1b1d783SJeff Cody                          backing_file);
3386b1b1d783SJeff Cody 
3387b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
3388b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
3389b1b1d783SJeff Cody                 continue;
3390b1b1d783SJeff Cody             }
3391b1b1d783SJeff Cody 
3392b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
3393b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
3394b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3395b1b1d783SJeff Cody                          curr_bs->backing_file);
3396b1b1d783SJeff Cody 
3397b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
3398b1b1d783SJeff Cody                 continue;
3399b1b1d783SJeff Cody             }
3400b1b1d783SJeff Cody 
3401b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
3402b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
3403b1b1d783SJeff Cody                 break;
3404b1b1d783SJeff Cody             }
3405e8a6bb9cSMarcelo Tosatti         }
3406e8a6bb9cSMarcelo Tosatti     }
3407e8a6bb9cSMarcelo Tosatti 
3408b1b1d783SJeff Cody     g_free(filename_full);
3409b1b1d783SJeff Cody     g_free(backing_file_full);
3410b1b1d783SJeff Cody     g_free(filename_tmp);
3411b1b1d783SJeff Cody     return retval;
3412e8a6bb9cSMarcelo Tosatti }
3413e8a6bb9cSMarcelo Tosatti 
3414f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
3415f198fd1cSBenoît Canet {
3416f198fd1cSBenoît Canet     if (!bs->drv) {
3417f198fd1cSBenoît Canet         return 0;
3418f198fd1cSBenoît Canet     }
3419f198fd1cSBenoît Canet 
3420f198fd1cSBenoît Canet     if (!bs->backing_hd) {
3421f198fd1cSBenoît Canet         return 0;
3422f198fd1cSBenoît Canet     }
3423f198fd1cSBenoît Canet 
3424f198fd1cSBenoît Canet     return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
3425f198fd1cSBenoît Canet }
3426f198fd1cSBenoît Canet 
342779fac568SJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
342879fac568SJeff Cody {
342979fac568SJeff Cody     BlockDriverState *curr_bs = NULL;
343079fac568SJeff Cody 
343179fac568SJeff Cody     if (!bs) {
343279fac568SJeff Cody         return NULL;
343379fac568SJeff Cody     }
343479fac568SJeff Cody 
343579fac568SJeff Cody     curr_bs = bs;
343679fac568SJeff Cody 
343779fac568SJeff Cody     while (curr_bs->backing_hd) {
343879fac568SJeff Cody         curr_bs = curr_bs->backing_hd;
343979fac568SJeff Cody     }
344079fac568SJeff Cody     return curr_bs;
344179fac568SJeff Cody }
344279fac568SJeff Cody 
3443faea38e7Sbellard #define NB_SUFFIXES 4
3444faea38e7Sbellard 
3445faea38e7Sbellard char *get_human_readable_size(char *buf, int buf_size, int64_t size)
3446faea38e7Sbellard {
3447faea38e7Sbellard     static const char suffixes[NB_SUFFIXES] = "KMGT";
3448faea38e7Sbellard     int64_t base;
3449faea38e7Sbellard     int i;
3450faea38e7Sbellard 
3451faea38e7Sbellard     if (size <= 999) {
3452faea38e7Sbellard         snprintf(buf, buf_size, "%" PRId64, size);
3453faea38e7Sbellard     } else {
3454faea38e7Sbellard         base = 1024;
3455faea38e7Sbellard         for(i = 0; i < NB_SUFFIXES; i++) {
3456faea38e7Sbellard             if (size < (10 * base)) {
3457faea38e7Sbellard                 snprintf(buf, buf_size, "%0.1f%c",
3458faea38e7Sbellard                          (double)size / base,
3459faea38e7Sbellard                          suffixes[i]);
3460faea38e7Sbellard                 break;
3461faea38e7Sbellard             } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
3462faea38e7Sbellard                 snprintf(buf, buf_size, "%" PRId64 "%c",
3463faea38e7Sbellard                          ((size + (base >> 1)) / base),
3464faea38e7Sbellard                          suffixes[i]);
3465faea38e7Sbellard                 break;
3466faea38e7Sbellard             }
3467faea38e7Sbellard             base = base * 1024;
3468faea38e7Sbellard         }
3469faea38e7Sbellard     }
3470faea38e7Sbellard     return buf;
3471faea38e7Sbellard }
3472faea38e7Sbellard 
3473faea38e7Sbellard char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
3474faea38e7Sbellard {
3475faea38e7Sbellard     char buf1[128], date_buf[128], clock_buf[128];
3476faea38e7Sbellard     struct tm tm;
3477faea38e7Sbellard     time_t ti;
3478faea38e7Sbellard     int64_t secs;
3479faea38e7Sbellard 
3480faea38e7Sbellard     if (!sn) {
3481faea38e7Sbellard         snprintf(buf, buf_size,
3482faea38e7Sbellard                  "%-10s%-20s%7s%20s%15s",
3483faea38e7Sbellard                  "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
3484faea38e7Sbellard     } else {
3485faea38e7Sbellard         ti = sn->date_sec;
3486faea38e7Sbellard         localtime_r(&ti, &tm);
3487faea38e7Sbellard         strftime(date_buf, sizeof(date_buf),
3488faea38e7Sbellard                  "%Y-%m-%d %H:%M:%S", &tm);
3489faea38e7Sbellard         secs = sn->vm_clock_nsec / 1000000000;
3490faea38e7Sbellard         snprintf(clock_buf, sizeof(clock_buf),
3491faea38e7Sbellard                  "%02d:%02d:%02d.%03d",
3492faea38e7Sbellard                  (int)(secs / 3600),
3493faea38e7Sbellard                  (int)((secs / 60) % 60),
3494faea38e7Sbellard                  (int)(secs % 60),
3495faea38e7Sbellard                  (int)((sn->vm_clock_nsec / 1000000) % 1000));
3496faea38e7Sbellard         snprintf(buf, buf_size,
3497faea38e7Sbellard                  "%-10s%-20s%7s%20s%15s",
3498faea38e7Sbellard                  sn->id_str, sn->name,
3499faea38e7Sbellard                  get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
3500faea38e7Sbellard                  date_buf,
3501faea38e7Sbellard                  clock_buf);
3502faea38e7Sbellard     }
3503faea38e7Sbellard     return buf;
3504faea38e7Sbellard }
3505faea38e7Sbellard 
3506ea2384d3Sbellard /**************************************************************/
350783f64091Sbellard /* async I/Os */
3508ea2384d3Sbellard 
35093b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
3510f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
351183f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
3512ea2384d3Sbellard {
3513bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
3514bbf0a440SStefan Hajnoczi 
3515b2a61371SStefan Hajnoczi     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
35168c5873d6SStefan Hajnoczi                                  cb, opaque, false);
351783f64091Sbellard }
351883f64091Sbellard 
3519f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
3520f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
352183f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
35227674e7bfSbellard {
3523bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
3524bbf0a440SStefan Hajnoczi 
35251a6e115bSStefan Hajnoczi     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors,
35268c5873d6SStefan Hajnoczi                                  cb, opaque, true);
352783f64091Sbellard }
352883f64091Sbellard 
352940b4f539SKevin Wolf 
353040b4f539SKevin Wolf typedef struct MultiwriteCB {
353140b4f539SKevin Wolf     int error;
353240b4f539SKevin Wolf     int num_requests;
353340b4f539SKevin Wolf     int num_callbacks;
353440b4f539SKevin Wolf     struct {
353540b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
353640b4f539SKevin Wolf         void *opaque;
353740b4f539SKevin Wolf         QEMUIOVector *free_qiov;
353840b4f539SKevin Wolf     } callbacks[];
353940b4f539SKevin Wolf } MultiwriteCB;
354040b4f539SKevin Wolf 
354140b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
354240b4f539SKevin Wolf {
354340b4f539SKevin Wolf     int i;
354440b4f539SKevin Wolf 
354540b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
354640b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
35471e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
35481e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
35491e1ea48dSStefan Hajnoczi         }
35507267c094SAnthony Liguori         g_free(mcb->callbacks[i].free_qiov);
355140b4f539SKevin Wolf     }
355240b4f539SKevin Wolf }
355340b4f539SKevin Wolf 
355440b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
355540b4f539SKevin Wolf {
355640b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
355740b4f539SKevin Wolf 
35586d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
35596d519a5fSStefan Hajnoczi 
3560cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
356140b4f539SKevin Wolf         mcb->error = ret;
356240b4f539SKevin Wolf     }
356340b4f539SKevin Wolf 
356440b4f539SKevin Wolf     mcb->num_requests--;
356540b4f539SKevin Wolf     if (mcb->num_requests == 0) {
356640b4f539SKevin Wolf         multiwrite_user_cb(mcb);
35677267c094SAnthony Liguori         g_free(mcb);
356840b4f539SKevin Wolf     }
356940b4f539SKevin Wolf }
357040b4f539SKevin Wolf 
357140b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
357240b4f539SKevin Wolf {
357377be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
357477be4366SChristoph Hellwig 
357577be4366SChristoph Hellwig     /*
357677be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
357777be4366SChristoph Hellwig      * here as that could overflow the return value.
357877be4366SChristoph Hellwig      */
357977be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
358077be4366SChristoph Hellwig         return 1;
358177be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
358277be4366SChristoph Hellwig         return -1;
358377be4366SChristoph Hellwig     } else {
358477be4366SChristoph Hellwig         return 0;
358577be4366SChristoph Hellwig     }
358640b4f539SKevin Wolf }
358740b4f539SKevin Wolf 
358840b4f539SKevin Wolf /*
358940b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
359040b4f539SKevin Wolf  * requests that remain after merging.
359140b4f539SKevin Wolf  */
359240b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
359340b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
359440b4f539SKevin Wolf {
359540b4f539SKevin Wolf     int i, outidx;
359640b4f539SKevin Wolf 
359740b4f539SKevin Wolf     // Sort requests by start sector
359840b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
359940b4f539SKevin Wolf 
360040b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
360140b4f539SKevin Wolf     // filling up gaps with zero sectors.
360240b4f539SKevin Wolf     outidx = 0;
360340b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
360440b4f539SKevin Wolf         int merge = 0;
360540b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
360640b4f539SKevin Wolf 
3607b6a127a1SPaolo Bonzini         // Handle exactly sequential writes and overlapping writes.
360840b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
360940b4f539SKevin Wolf             merge = 1;
361040b4f539SKevin Wolf         }
361140b4f539SKevin Wolf 
3612e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
3613e2a305fbSChristoph Hellwig             merge = 0;
3614e2a305fbSChristoph Hellwig         }
3615e2a305fbSChristoph Hellwig 
361640b4f539SKevin Wolf         if (merge) {
361740b4f539SKevin Wolf             size_t size;
36187267c094SAnthony Liguori             QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
361940b4f539SKevin Wolf             qemu_iovec_init(qiov,
362040b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
362140b4f539SKevin Wolf 
362240b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
362340b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
362440b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
36251b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
362640b4f539SKevin Wolf 
3627b6a127a1SPaolo Bonzini             // We should need to add any zeros between the two requests
3628b6a127a1SPaolo Bonzini             assert (reqs[i].sector <= oldreq_last);
362940b4f539SKevin Wolf 
363040b4f539SKevin Wolf             // Add the second request
36311b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
363240b4f539SKevin Wolf 
3633cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
363440b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
363540b4f539SKevin Wolf 
363640b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
363740b4f539SKevin Wolf         } else {
363840b4f539SKevin Wolf             outidx++;
363940b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
364040b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
364140b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
364240b4f539SKevin Wolf         }
364340b4f539SKevin Wolf     }
364440b4f539SKevin Wolf 
364540b4f539SKevin Wolf     return outidx + 1;
364640b4f539SKevin Wolf }
364740b4f539SKevin Wolf 
364840b4f539SKevin Wolf /*
364940b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
365040b4f539SKevin Wolf  *
365140b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
365240b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
365340b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
365440b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
365540b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
365640b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
365740b4f539SKevin Wolf  *
365840b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
365940b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
366040b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
366140b4f539SKevin Wolf  */
366240b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
366340b4f539SKevin Wolf {
366440b4f539SKevin Wolf     MultiwriteCB *mcb;
366540b4f539SKevin Wolf     int i;
366640b4f539SKevin Wolf 
3667301db7c2SRyan Harper     /* don't submit writes if we don't have a medium */
3668301db7c2SRyan Harper     if (bs->drv == NULL) {
3669301db7c2SRyan Harper         for (i = 0; i < num_reqs; i++) {
3670301db7c2SRyan Harper             reqs[i].error = -ENOMEDIUM;
3671301db7c2SRyan Harper         }
3672301db7c2SRyan Harper         return -1;
3673301db7c2SRyan Harper     }
3674301db7c2SRyan Harper 
367540b4f539SKevin Wolf     if (num_reqs == 0) {
367640b4f539SKevin Wolf         return 0;
367740b4f539SKevin Wolf     }
367840b4f539SKevin Wolf 
367940b4f539SKevin Wolf     // Create MultiwriteCB structure
36807267c094SAnthony Liguori     mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
368140b4f539SKevin Wolf     mcb->num_requests = 0;
368240b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
368340b4f539SKevin Wolf 
368440b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
368540b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
368640b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
368740b4f539SKevin Wolf     }
368840b4f539SKevin Wolf 
368940b4f539SKevin Wolf     // Check for mergable requests
369040b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
369140b4f539SKevin Wolf 
36926d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
36936d519a5fSStefan Hajnoczi 
3694df9309fbSPaolo Bonzini     /* Run the aio requests. */
3695df9309fbSPaolo Bonzini     mcb->num_requests = num_reqs;
369640b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
3697ad54ae80SPaolo Bonzini         bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
369840b4f539SKevin Wolf             reqs[i].nb_sectors, multiwrite_cb, mcb);
369940b4f539SKevin Wolf     }
370040b4f539SKevin Wolf 
370140b4f539SKevin Wolf     return 0;
370240b4f539SKevin Wolf }
370340b4f539SKevin Wolf 
370483f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
370583f64091Sbellard {
3706d7331bedSStefan Hajnoczi     acb->aiocb_info->cancel(acb);
370783f64091Sbellard }
370883f64091Sbellard 
370998f90dbaSZhi Yong Wu /* block I/O throttling */
371098f90dbaSZhi Yong Wu static bool bdrv_exceed_bps_limits(BlockDriverState *bs, int nb_sectors,
371198f90dbaSZhi Yong Wu                  bool is_write, double elapsed_time, uint64_t *wait)
371298f90dbaSZhi Yong Wu {
371398f90dbaSZhi Yong Wu     uint64_t bps_limit = 0;
371498f90dbaSZhi Yong Wu     double   bytes_limit, bytes_base, bytes_res;
371598f90dbaSZhi Yong Wu     double   slice_time, wait_time;
371698f90dbaSZhi Yong Wu 
371798f90dbaSZhi Yong Wu     if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
371898f90dbaSZhi Yong Wu         bps_limit = bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL];
371998f90dbaSZhi Yong Wu     } else if (bs->io_limits.bps[is_write]) {
372098f90dbaSZhi Yong Wu         bps_limit = bs->io_limits.bps[is_write];
372198f90dbaSZhi Yong Wu     } else {
372298f90dbaSZhi Yong Wu         if (wait) {
372398f90dbaSZhi Yong Wu             *wait = 0;
372498f90dbaSZhi Yong Wu         }
372598f90dbaSZhi Yong Wu 
372698f90dbaSZhi Yong Wu         return false;
372798f90dbaSZhi Yong Wu     }
372898f90dbaSZhi Yong Wu 
372998f90dbaSZhi Yong Wu     slice_time = bs->slice_end - bs->slice_start;
373098f90dbaSZhi Yong Wu     slice_time /= (NANOSECONDS_PER_SECOND);
373198f90dbaSZhi Yong Wu     bytes_limit = bps_limit * slice_time;
373298f90dbaSZhi Yong Wu     bytes_base  = bs->nr_bytes[is_write] - bs->io_base.bytes[is_write];
373398f90dbaSZhi Yong Wu     if (bs->io_limits.bps[BLOCK_IO_LIMIT_TOTAL]) {
373498f90dbaSZhi Yong Wu         bytes_base += bs->nr_bytes[!is_write] - bs->io_base.bytes[!is_write];
373598f90dbaSZhi Yong Wu     }
373698f90dbaSZhi Yong Wu 
373798f90dbaSZhi Yong Wu     /* bytes_base: the bytes of data which have been read/written; and
373898f90dbaSZhi Yong Wu      *             it is obtained from the history statistic info.
373998f90dbaSZhi Yong Wu      * bytes_res: the remaining bytes of data which need to be read/written.
374098f90dbaSZhi Yong Wu      * (bytes_base + bytes_res) / bps_limit: used to calcuate
374198f90dbaSZhi Yong Wu      *             the total time for completing reading/writting all data.
374298f90dbaSZhi Yong Wu      */
374398f90dbaSZhi Yong Wu     bytes_res   = (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
374498f90dbaSZhi Yong Wu 
374598f90dbaSZhi Yong Wu     if (bytes_base + bytes_res <= bytes_limit) {
374698f90dbaSZhi Yong Wu         if (wait) {
374798f90dbaSZhi Yong Wu             *wait = 0;
374898f90dbaSZhi Yong Wu         }
374998f90dbaSZhi Yong Wu 
375098f90dbaSZhi Yong Wu         return false;
375198f90dbaSZhi Yong Wu     }
375298f90dbaSZhi Yong Wu 
375398f90dbaSZhi Yong Wu     /* Calc approx time to dispatch */
375498f90dbaSZhi Yong Wu     wait_time = (bytes_base + bytes_res) / bps_limit - elapsed_time;
375598f90dbaSZhi Yong Wu 
375698f90dbaSZhi Yong Wu     /* When the I/O rate at runtime exceeds the limits,
375798f90dbaSZhi Yong Wu      * bs->slice_end need to be extended in order that the current statistic
375898f90dbaSZhi Yong Wu      * info can be kept until the timer fire, so it is increased and tuned
375998f90dbaSZhi Yong Wu      * based on the result of experiment.
376098f90dbaSZhi Yong Wu      */
376198f90dbaSZhi Yong Wu     bs->slice_time = wait_time * BLOCK_IO_SLICE_TIME * 10;
376298f90dbaSZhi Yong Wu     bs->slice_end += bs->slice_time - 3 * BLOCK_IO_SLICE_TIME;
376398f90dbaSZhi Yong Wu     if (wait) {
376498f90dbaSZhi Yong Wu         *wait = wait_time * BLOCK_IO_SLICE_TIME * 10;
376598f90dbaSZhi Yong Wu     }
376698f90dbaSZhi Yong Wu 
376798f90dbaSZhi Yong Wu     return true;
376898f90dbaSZhi Yong Wu }
376998f90dbaSZhi Yong Wu 
377098f90dbaSZhi Yong Wu static bool bdrv_exceed_iops_limits(BlockDriverState *bs, bool is_write,
377198f90dbaSZhi Yong Wu                              double elapsed_time, uint64_t *wait)
377298f90dbaSZhi Yong Wu {
377398f90dbaSZhi Yong Wu     uint64_t iops_limit = 0;
377498f90dbaSZhi Yong Wu     double   ios_limit, ios_base;
377598f90dbaSZhi Yong Wu     double   slice_time, wait_time;
377698f90dbaSZhi Yong Wu 
377798f90dbaSZhi Yong Wu     if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
377898f90dbaSZhi Yong Wu         iops_limit = bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL];
377998f90dbaSZhi Yong Wu     } else if (bs->io_limits.iops[is_write]) {
378098f90dbaSZhi Yong Wu         iops_limit = bs->io_limits.iops[is_write];
378198f90dbaSZhi Yong Wu     } else {
378298f90dbaSZhi Yong Wu         if (wait) {
378398f90dbaSZhi Yong Wu             *wait = 0;
378498f90dbaSZhi Yong Wu         }
378598f90dbaSZhi Yong Wu 
378698f90dbaSZhi Yong Wu         return false;
378798f90dbaSZhi Yong Wu     }
378898f90dbaSZhi Yong Wu 
378998f90dbaSZhi Yong Wu     slice_time = bs->slice_end - bs->slice_start;
379098f90dbaSZhi Yong Wu     slice_time /= (NANOSECONDS_PER_SECOND);
379198f90dbaSZhi Yong Wu     ios_limit  = iops_limit * slice_time;
379298f90dbaSZhi Yong Wu     ios_base   = bs->nr_ops[is_write] - bs->io_base.ios[is_write];
379398f90dbaSZhi Yong Wu     if (bs->io_limits.iops[BLOCK_IO_LIMIT_TOTAL]) {
379498f90dbaSZhi Yong Wu         ios_base += bs->nr_ops[!is_write] - bs->io_base.ios[!is_write];
379598f90dbaSZhi Yong Wu     }
379698f90dbaSZhi Yong Wu 
379798f90dbaSZhi Yong Wu     if (ios_base + 1 <= ios_limit) {
379898f90dbaSZhi Yong Wu         if (wait) {
379998f90dbaSZhi Yong Wu             *wait = 0;
380098f90dbaSZhi Yong Wu         }
380198f90dbaSZhi Yong Wu 
380298f90dbaSZhi Yong Wu         return false;
380398f90dbaSZhi Yong Wu     }
380498f90dbaSZhi Yong Wu 
380598f90dbaSZhi Yong Wu     /* Calc approx time to dispatch */
380698f90dbaSZhi Yong Wu     wait_time = (ios_base + 1) / iops_limit;
380798f90dbaSZhi Yong Wu     if (wait_time > elapsed_time) {
380898f90dbaSZhi Yong Wu         wait_time = wait_time - elapsed_time;
380998f90dbaSZhi Yong Wu     } else {
381098f90dbaSZhi Yong Wu         wait_time = 0;
381198f90dbaSZhi Yong Wu     }
381298f90dbaSZhi Yong Wu 
381398f90dbaSZhi Yong Wu     bs->slice_time = wait_time * BLOCK_IO_SLICE_TIME * 10;
381498f90dbaSZhi Yong Wu     bs->slice_end += bs->slice_time - 3 * BLOCK_IO_SLICE_TIME;
381598f90dbaSZhi Yong Wu     if (wait) {
381698f90dbaSZhi Yong Wu         *wait = wait_time * BLOCK_IO_SLICE_TIME * 10;
381798f90dbaSZhi Yong Wu     }
381898f90dbaSZhi Yong Wu 
381998f90dbaSZhi Yong Wu     return true;
382098f90dbaSZhi Yong Wu }
382198f90dbaSZhi Yong Wu 
382298f90dbaSZhi Yong Wu static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,
382398f90dbaSZhi Yong Wu                            bool is_write, int64_t *wait)
382498f90dbaSZhi Yong Wu {
382598f90dbaSZhi Yong Wu     int64_t  now, max_wait;
382698f90dbaSZhi Yong Wu     uint64_t bps_wait = 0, iops_wait = 0;
382798f90dbaSZhi Yong Wu     double   elapsed_time;
382898f90dbaSZhi Yong Wu     int      bps_ret, iops_ret;
382998f90dbaSZhi Yong Wu 
383098f90dbaSZhi Yong Wu     now = qemu_get_clock_ns(vm_clock);
383198f90dbaSZhi Yong Wu     if ((bs->slice_start < now)
383298f90dbaSZhi Yong Wu         && (bs->slice_end > now)) {
383398f90dbaSZhi Yong Wu         bs->slice_end = now + bs->slice_time;
383498f90dbaSZhi Yong Wu     } else {
383598f90dbaSZhi Yong Wu         bs->slice_time  =  5 * BLOCK_IO_SLICE_TIME;
383698f90dbaSZhi Yong Wu         bs->slice_start = now;
383798f90dbaSZhi Yong Wu         bs->slice_end   = now + bs->slice_time;
383898f90dbaSZhi Yong Wu 
383998f90dbaSZhi Yong Wu         bs->io_base.bytes[is_write]  = bs->nr_bytes[is_write];
384098f90dbaSZhi Yong Wu         bs->io_base.bytes[!is_write] = bs->nr_bytes[!is_write];
384198f90dbaSZhi Yong Wu 
384298f90dbaSZhi Yong Wu         bs->io_base.ios[is_write]    = bs->nr_ops[is_write];
384398f90dbaSZhi Yong Wu         bs->io_base.ios[!is_write]   = bs->nr_ops[!is_write];
384498f90dbaSZhi Yong Wu     }
384598f90dbaSZhi Yong Wu 
384698f90dbaSZhi Yong Wu     elapsed_time  = now - bs->slice_start;
384798f90dbaSZhi Yong Wu     elapsed_time  /= (NANOSECONDS_PER_SECOND);
384898f90dbaSZhi Yong Wu 
384998f90dbaSZhi Yong Wu     bps_ret  = bdrv_exceed_bps_limits(bs, nb_sectors,
385098f90dbaSZhi Yong Wu                                       is_write, elapsed_time, &bps_wait);
385198f90dbaSZhi Yong Wu     iops_ret = bdrv_exceed_iops_limits(bs, is_write,
385298f90dbaSZhi Yong Wu                                       elapsed_time, &iops_wait);
385398f90dbaSZhi Yong Wu     if (bps_ret || iops_ret) {
385498f90dbaSZhi Yong Wu         max_wait = bps_wait > iops_wait ? bps_wait : iops_wait;
385598f90dbaSZhi Yong Wu         if (wait) {
385698f90dbaSZhi Yong Wu             *wait = max_wait;
385798f90dbaSZhi Yong Wu         }
385898f90dbaSZhi Yong Wu 
385998f90dbaSZhi Yong Wu         now = qemu_get_clock_ns(vm_clock);
386098f90dbaSZhi Yong Wu         if (bs->slice_end < now + max_wait) {
386198f90dbaSZhi Yong Wu             bs->slice_end = now + max_wait;
386298f90dbaSZhi Yong Wu         }
386398f90dbaSZhi Yong Wu 
386498f90dbaSZhi Yong Wu         return true;
386598f90dbaSZhi Yong Wu     }
386698f90dbaSZhi Yong Wu 
386798f90dbaSZhi Yong Wu     if (wait) {
386898f90dbaSZhi Yong Wu         *wait = 0;
386998f90dbaSZhi Yong Wu     }
387098f90dbaSZhi Yong Wu 
387198f90dbaSZhi Yong Wu     return false;
387298f90dbaSZhi Yong Wu }
387383f64091Sbellard 
387483f64091Sbellard /**************************************************************/
387583f64091Sbellard /* async block device emulation */
387683f64091Sbellard 
3877c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
3878c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
3879c16b5a2cSChristoph Hellwig     QEMUBH *bh;
3880c16b5a2cSChristoph Hellwig     int ret;
3881c16b5a2cSChristoph Hellwig     /* vector translation state */
3882c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
3883c16b5a2cSChristoph Hellwig     uint8_t *bounce;
3884c16b5a2cSChristoph Hellwig     int is_write;
3885c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
3886c16b5a2cSChristoph Hellwig 
3887c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
3888c16b5a2cSChristoph Hellwig {
3889b666d239SKevin Wolf     BlockDriverAIOCBSync *acb =
3890b666d239SKevin Wolf         container_of(blockacb, BlockDriverAIOCBSync, common);
38916a7ad299SDor Laor     qemu_bh_delete(acb->bh);
389236afc451SAvi Kivity     acb->bh = NULL;
3893c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
3894c16b5a2cSChristoph Hellwig }
3895c16b5a2cSChristoph Hellwig 
3896d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_aiocb_info = {
3897c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
3898c16b5a2cSChristoph Hellwig     .cancel             = bdrv_aio_cancel_em,
3899c16b5a2cSChristoph Hellwig };
3900c16b5a2cSChristoph Hellwig 
390183f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
3902beac80cdSbellard {
3903ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
3904f141eafeSaliguori 
3905f141eafeSaliguori     if (!acb->is_write)
390603396148SMichael Tokarev         qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
3907ceb42de8Saliguori     qemu_vfree(acb->bounce);
3908ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
39096a7ad299SDor Laor     qemu_bh_delete(acb->bh);
391036afc451SAvi Kivity     acb->bh = NULL;
3911ce1a14dcSpbrook     qemu_aio_release(acb);
3912beac80cdSbellard }
3913beac80cdSbellard 
3914f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
3915f141eafeSaliguori                                             int64_t sector_num,
3916f141eafeSaliguori                                             QEMUIOVector *qiov,
3917f141eafeSaliguori                                             int nb_sectors,
3918f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
3919f141eafeSaliguori                                             void *opaque,
3920f141eafeSaliguori                                             int is_write)
3921f141eafeSaliguori 
3922ea2384d3Sbellard {
3923ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
392483f64091Sbellard 
3925d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
3926f141eafeSaliguori     acb->is_write = is_write;
3927f141eafeSaliguori     acb->qiov = qiov;
3928e268ca52Saliguori     acb->bounce = qemu_blockalign(bs, qiov->size);
3929ce1a14dcSpbrook     acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
3930f141eafeSaliguori 
3931f141eafeSaliguori     if (is_write) {
3932d5e6b161SMichael Tokarev         qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
39331ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
3934f141eafeSaliguori     } else {
39351ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
3936f141eafeSaliguori     }
3937f141eafeSaliguori 
3938ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
3939f141eafeSaliguori 
3940ce1a14dcSpbrook     return &acb->common;
39417a6cba61Spbrook }
39427a6cba61Spbrook 
3943f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
3944f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
3945ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
394683f64091Sbellard {
3947f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
394883f64091Sbellard }
394983f64091Sbellard 
3950f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
3951f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
3952f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
3953f141eafeSaliguori {
3954f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
3955f141eafeSaliguori }
3956f141eafeSaliguori 
395768485420SKevin Wolf 
395868485420SKevin Wolf typedef struct BlockDriverAIOCBCoroutine {
395968485420SKevin Wolf     BlockDriverAIOCB common;
396068485420SKevin Wolf     BlockRequest req;
396168485420SKevin Wolf     bool is_write;
3962d318aea9SKevin Wolf     bool *done;
396368485420SKevin Wolf     QEMUBH* bh;
396468485420SKevin Wolf } BlockDriverAIOCBCoroutine;
396568485420SKevin Wolf 
396668485420SKevin Wolf static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
396768485420SKevin Wolf {
3968d318aea9SKevin Wolf     BlockDriverAIOCBCoroutine *acb =
3969d318aea9SKevin Wolf         container_of(blockacb, BlockDriverAIOCBCoroutine, common);
3970d318aea9SKevin Wolf     bool done = false;
3971d318aea9SKevin Wolf 
3972d318aea9SKevin Wolf     acb->done = &done;
3973d318aea9SKevin Wolf     while (!done) {
3974d318aea9SKevin Wolf         qemu_aio_wait();
3975d318aea9SKevin Wolf     }
397668485420SKevin Wolf }
397768485420SKevin Wolf 
3978d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_co_aiocb_info = {
397968485420SKevin Wolf     .aiocb_size         = sizeof(BlockDriverAIOCBCoroutine),
398068485420SKevin Wolf     .cancel             = bdrv_aio_co_cancel_em,
398168485420SKevin Wolf };
398268485420SKevin Wolf 
398335246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque)
398468485420SKevin Wolf {
398568485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb = opaque;
398668485420SKevin Wolf 
398768485420SKevin Wolf     acb->common.cb(acb->common.opaque, acb->req.error);
3988d318aea9SKevin Wolf 
3989d318aea9SKevin Wolf     if (acb->done) {
3990d318aea9SKevin Wolf         *acb->done = true;
3991d318aea9SKevin Wolf     }
3992d318aea9SKevin Wolf 
399368485420SKevin Wolf     qemu_bh_delete(acb->bh);
399468485420SKevin Wolf     qemu_aio_release(acb);
399568485420SKevin Wolf }
399668485420SKevin Wolf 
3997b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
3998b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque)
3999b2a61371SStefan Hajnoczi {
4000b2a61371SStefan Hajnoczi     BlockDriverAIOCBCoroutine *acb = opaque;
4001b2a61371SStefan Hajnoczi     BlockDriverState *bs = acb->common.bs;
4002b2a61371SStefan Hajnoczi 
4003b2a61371SStefan Hajnoczi     if (!acb->is_write) {
4004b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
4005470c0504SStefan Hajnoczi             acb->req.nb_sectors, acb->req.qiov, 0);
4006b2a61371SStefan Hajnoczi     } else {
4007b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
4008f08f2ddaSStefan Hajnoczi             acb->req.nb_sectors, acb->req.qiov, 0);
4009b2a61371SStefan Hajnoczi     }
4010b2a61371SStefan Hajnoczi 
401135246a68SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4012b2a61371SStefan Hajnoczi     qemu_bh_schedule(acb->bh);
4013b2a61371SStefan Hajnoczi }
4014b2a61371SStefan Hajnoczi 
401568485420SKevin Wolf static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
401668485420SKevin Wolf                                                int64_t sector_num,
401768485420SKevin Wolf                                                QEMUIOVector *qiov,
401868485420SKevin Wolf                                                int nb_sectors,
401968485420SKevin Wolf                                                BlockDriverCompletionFunc *cb,
402068485420SKevin Wolf                                                void *opaque,
40218c5873d6SStefan Hajnoczi                                                bool is_write)
402268485420SKevin Wolf {
402368485420SKevin Wolf     Coroutine *co;
402468485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb;
402568485420SKevin Wolf 
4026d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
402768485420SKevin Wolf     acb->req.sector = sector_num;
402868485420SKevin Wolf     acb->req.nb_sectors = nb_sectors;
402968485420SKevin Wolf     acb->req.qiov = qiov;
403068485420SKevin Wolf     acb->is_write = is_write;
4031d318aea9SKevin Wolf     acb->done = NULL;
403268485420SKevin Wolf 
40338c5873d6SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_co_do_rw);
403468485420SKevin Wolf     qemu_coroutine_enter(co, acb);
403568485420SKevin Wolf 
403668485420SKevin Wolf     return &acb->common;
403768485420SKevin Wolf }
403868485420SKevin Wolf 
403907f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
4040b2e12bc6SChristoph Hellwig {
404107f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
404207f07615SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
4043b2e12bc6SChristoph Hellwig 
404407f07615SPaolo Bonzini     acb->req.error = bdrv_co_flush(bs);
404507f07615SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
4046b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
4047b2e12bc6SChristoph Hellwig }
4048b2e12bc6SChristoph Hellwig 
404907f07615SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
4050016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
4051016f5cf6SAlexander Graf {
405207f07615SPaolo Bonzini     trace_bdrv_aio_flush(bs, opaque);
4053016f5cf6SAlexander Graf 
405407f07615SPaolo Bonzini     Coroutine *co;
405507f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
4056016f5cf6SAlexander Graf 
4057d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4058d318aea9SKevin Wolf     acb->done = NULL;
4059d318aea9SKevin Wolf 
406007f07615SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
406107f07615SPaolo Bonzini     qemu_coroutine_enter(co, acb);
4062016f5cf6SAlexander Graf 
4063016f5cf6SAlexander Graf     return &acb->common;
4064016f5cf6SAlexander Graf }
4065016f5cf6SAlexander Graf 
40664265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
40674265d620SPaolo Bonzini {
40684265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
40694265d620SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
40704265d620SPaolo Bonzini 
40714265d620SPaolo Bonzini     acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
40724265d620SPaolo Bonzini     acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
40734265d620SPaolo Bonzini     qemu_bh_schedule(acb->bh);
40744265d620SPaolo Bonzini }
40754265d620SPaolo Bonzini 
40764265d620SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
40774265d620SPaolo Bonzini         int64_t sector_num, int nb_sectors,
40784265d620SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
40794265d620SPaolo Bonzini {
40804265d620SPaolo Bonzini     Coroutine *co;
40814265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
40824265d620SPaolo Bonzini 
40834265d620SPaolo Bonzini     trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
40844265d620SPaolo Bonzini 
4085d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
40864265d620SPaolo Bonzini     acb->req.sector = sector_num;
40874265d620SPaolo Bonzini     acb->req.nb_sectors = nb_sectors;
4088d318aea9SKevin Wolf     acb->done = NULL;
40894265d620SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
40904265d620SPaolo Bonzini     qemu_coroutine_enter(co, acb);
40914265d620SPaolo Bonzini 
40924265d620SPaolo Bonzini     return &acb->common;
40934265d620SPaolo Bonzini }
40944265d620SPaolo Bonzini 
4095ea2384d3Sbellard void bdrv_init(void)
4096ea2384d3Sbellard {
40975efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
4098ea2384d3Sbellard }
4099ce1a14dcSpbrook 
4100eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
4101eb852011SMarkus Armbruster {
4102eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
4103eb852011SMarkus Armbruster     bdrv_init();
4104eb852011SMarkus Armbruster }
4105eb852011SMarkus Armbruster 
4106d7331bedSStefan Hajnoczi void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
41076bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
41086bbff9a0Saliguori {
4109ce1a14dcSpbrook     BlockDriverAIOCB *acb;
4110ce1a14dcSpbrook 
4111d7331bedSStefan Hajnoczi     acb = g_slice_alloc(aiocb_info->aiocb_size);
4112d7331bedSStefan Hajnoczi     acb->aiocb_info = aiocb_info;
4113ce1a14dcSpbrook     acb->bs = bs;
4114ce1a14dcSpbrook     acb->cb = cb;
4115ce1a14dcSpbrook     acb->opaque = opaque;
4116ce1a14dcSpbrook     return acb;
4117ce1a14dcSpbrook }
4118ce1a14dcSpbrook 
4119ce1a14dcSpbrook void qemu_aio_release(void *p)
4120ce1a14dcSpbrook {
4121d37c975fSStefan Hajnoczi     BlockDriverAIOCB *acb = p;
4122d7331bedSStefan Hajnoczi     g_slice_free1(acb->aiocb_info->aiocb_size, acb);
4123ce1a14dcSpbrook }
412419cb3738Sbellard 
412519cb3738Sbellard /**************************************************************/
4126f9f05dc5SKevin Wolf /* Coroutine block device emulation */
4127f9f05dc5SKevin Wolf 
4128f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion {
4129f9f05dc5SKevin Wolf     Coroutine *coroutine;
4130f9f05dc5SKevin Wolf     int ret;
4131f9f05dc5SKevin Wolf } CoroutineIOCompletion;
4132f9f05dc5SKevin Wolf 
4133f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret)
4134f9f05dc5SKevin Wolf {
4135f9f05dc5SKevin Wolf     CoroutineIOCompletion *co = opaque;
4136f9f05dc5SKevin Wolf 
4137f9f05dc5SKevin Wolf     co->ret = ret;
4138f9f05dc5SKevin Wolf     qemu_coroutine_enter(co->coroutine, NULL);
4139f9f05dc5SKevin Wolf }
4140f9f05dc5SKevin Wolf 
4141f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
4142f9f05dc5SKevin Wolf                                       int nb_sectors, QEMUIOVector *iov,
4143f9f05dc5SKevin Wolf                                       bool is_write)
4144f9f05dc5SKevin Wolf {
4145f9f05dc5SKevin Wolf     CoroutineIOCompletion co = {
4146f9f05dc5SKevin Wolf         .coroutine = qemu_coroutine_self(),
4147f9f05dc5SKevin Wolf     };
4148f9f05dc5SKevin Wolf     BlockDriverAIOCB *acb;
4149f9f05dc5SKevin Wolf 
4150f9f05dc5SKevin Wolf     if (is_write) {
4151a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
4152f9f05dc5SKevin Wolf                                        bdrv_co_io_em_complete, &co);
4153f9f05dc5SKevin Wolf     } else {
4154a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
4155f9f05dc5SKevin Wolf                                       bdrv_co_io_em_complete, &co);
4156f9f05dc5SKevin Wolf     }
4157f9f05dc5SKevin Wolf 
415859370aaaSStefan Hajnoczi     trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
4159f9f05dc5SKevin Wolf     if (!acb) {
4160f9f05dc5SKevin Wolf         return -EIO;
4161f9f05dc5SKevin Wolf     }
4162f9f05dc5SKevin Wolf     qemu_coroutine_yield();
4163f9f05dc5SKevin Wolf 
4164f9f05dc5SKevin Wolf     return co.ret;
4165f9f05dc5SKevin Wolf }
4166f9f05dc5SKevin Wolf 
4167f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
4168f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4169f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4170f9f05dc5SKevin Wolf {
4171f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
4172f9f05dc5SKevin Wolf }
4173f9f05dc5SKevin Wolf 
4174f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
4175f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4176f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4177f9f05dc5SKevin Wolf {
4178f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
4179f9f05dc5SKevin Wolf }
4180f9f05dc5SKevin Wolf 
418107f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque)
4182e7a8a783SKevin Wolf {
418307f07615SPaolo Bonzini     RwCo *rwco = opaque;
418407f07615SPaolo Bonzini 
418507f07615SPaolo Bonzini     rwco->ret = bdrv_co_flush(rwco->bs);
418607f07615SPaolo Bonzini }
418707f07615SPaolo Bonzini 
418807f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
418907f07615SPaolo Bonzini {
4190eb489bb1SKevin Wolf     int ret;
4191eb489bb1SKevin Wolf 
419229cdb251SPaolo Bonzini     if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
419307f07615SPaolo Bonzini         return 0;
4194eb489bb1SKevin Wolf     }
4195eb489bb1SKevin Wolf 
4196ca716364SKevin Wolf     /* Write back cached data to the OS even with cache=unsafe */
4197eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_os) {
4198eb489bb1SKevin Wolf         ret = bs->drv->bdrv_co_flush_to_os(bs);
4199eb489bb1SKevin Wolf         if (ret < 0) {
4200eb489bb1SKevin Wolf             return ret;
4201eb489bb1SKevin Wolf         }
4202eb489bb1SKevin Wolf     }
4203eb489bb1SKevin Wolf 
4204ca716364SKevin Wolf     /* But don't actually force it to the disk with cache=unsafe */
4205ca716364SKevin Wolf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
4206d4c82329SKevin Wolf         goto flush_parent;
4207ca716364SKevin Wolf     }
4208ca716364SKevin Wolf 
4209eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_disk) {
421029cdb251SPaolo Bonzini         ret = bs->drv->bdrv_co_flush_to_disk(bs);
421107f07615SPaolo Bonzini     } else if (bs->drv->bdrv_aio_flush) {
421207f07615SPaolo Bonzini         BlockDriverAIOCB *acb;
4213e7a8a783SKevin Wolf         CoroutineIOCompletion co = {
4214e7a8a783SKevin Wolf             .coroutine = qemu_coroutine_self(),
4215e7a8a783SKevin Wolf         };
4216e7a8a783SKevin Wolf 
421707f07615SPaolo Bonzini         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
421807f07615SPaolo Bonzini         if (acb == NULL) {
421929cdb251SPaolo Bonzini             ret = -EIO;
422007f07615SPaolo Bonzini         } else {
4221e7a8a783SKevin Wolf             qemu_coroutine_yield();
422229cdb251SPaolo Bonzini             ret = co.ret;
4223e7a8a783SKevin Wolf         }
422407f07615SPaolo Bonzini     } else {
422507f07615SPaolo Bonzini         /*
422607f07615SPaolo Bonzini          * Some block drivers always operate in either writethrough or unsafe
422707f07615SPaolo Bonzini          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
422807f07615SPaolo Bonzini          * know how the server works (because the behaviour is hardcoded or
422907f07615SPaolo Bonzini          * depends on server-side configuration), so we can't ensure that
423007f07615SPaolo Bonzini          * everything is safe on disk. Returning an error doesn't work because
423107f07615SPaolo Bonzini          * that would break guests even if the server operates in writethrough
423207f07615SPaolo Bonzini          * mode.
423307f07615SPaolo Bonzini          *
423407f07615SPaolo Bonzini          * Let's hope the user knows what he's doing.
423507f07615SPaolo Bonzini          */
423629cdb251SPaolo Bonzini         ret = 0;
423707f07615SPaolo Bonzini     }
423829cdb251SPaolo Bonzini     if (ret < 0) {
423929cdb251SPaolo Bonzini         return ret;
424029cdb251SPaolo Bonzini     }
424129cdb251SPaolo Bonzini 
424229cdb251SPaolo Bonzini     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
424329cdb251SPaolo Bonzini      * in the case of cache=unsafe, so there are no useless flushes.
424429cdb251SPaolo Bonzini      */
4245d4c82329SKevin Wolf flush_parent:
424629cdb251SPaolo Bonzini     return bdrv_co_flush(bs->file);
424707f07615SPaolo Bonzini }
424807f07615SPaolo Bonzini 
42490f15423cSAnthony Liguori void bdrv_invalidate_cache(BlockDriverState *bs)
42500f15423cSAnthony Liguori {
42510f15423cSAnthony Liguori     if (bs->drv && bs->drv->bdrv_invalidate_cache) {
42520f15423cSAnthony Liguori         bs->drv->bdrv_invalidate_cache(bs);
42530f15423cSAnthony Liguori     }
42540f15423cSAnthony Liguori }
42550f15423cSAnthony Liguori 
42560f15423cSAnthony Liguori void bdrv_invalidate_cache_all(void)
42570f15423cSAnthony Liguori {
42580f15423cSAnthony Liguori     BlockDriverState *bs;
42590f15423cSAnthony Liguori 
42600f15423cSAnthony Liguori     QTAILQ_FOREACH(bs, &bdrv_states, list) {
42610f15423cSAnthony Liguori         bdrv_invalidate_cache(bs);
42620f15423cSAnthony Liguori     }
42630f15423cSAnthony Liguori }
42640f15423cSAnthony Liguori 
426507789269SBenoît Canet void bdrv_clear_incoming_migration_all(void)
426607789269SBenoît Canet {
426707789269SBenoît Canet     BlockDriverState *bs;
426807789269SBenoît Canet 
426907789269SBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, list) {
427007789269SBenoît Canet         bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
427107789269SBenoît Canet     }
427207789269SBenoît Canet }
427307789269SBenoît Canet 
427407f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs)
427507f07615SPaolo Bonzini {
427607f07615SPaolo Bonzini     Coroutine *co;
427707f07615SPaolo Bonzini     RwCo rwco = {
427807f07615SPaolo Bonzini         .bs = bs,
427907f07615SPaolo Bonzini         .ret = NOT_DONE,
428007f07615SPaolo Bonzini     };
428107f07615SPaolo Bonzini 
428207f07615SPaolo Bonzini     if (qemu_in_coroutine()) {
428307f07615SPaolo Bonzini         /* Fast-path if already in coroutine context */
428407f07615SPaolo Bonzini         bdrv_flush_co_entry(&rwco);
428507f07615SPaolo Bonzini     } else {
428607f07615SPaolo Bonzini         co = qemu_coroutine_create(bdrv_flush_co_entry);
428707f07615SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
428807f07615SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
428907f07615SPaolo Bonzini             qemu_aio_wait();
429007f07615SPaolo Bonzini         }
429107f07615SPaolo Bonzini     }
429207f07615SPaolo Bonzini 
429307f07615SPaolo Bonzini     return rwco.ret;
429407f07615SPaolo Bonzini }
4295e7a8a783SKevin Wolf 
42964265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque)
42974265d620SPaolo Bonzini {
42984265d620SPaolo Bonzini     RwCo *rwco = opaque;
42994265d620SPaolo Bonzini 
43004265d620SPaolo Bonzini     rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
43014265d620SPaolo Bonzini }
43024265d620SPaolo Bonzini 
43034265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
43044265d620SPaolo Bonzini                                  int nb_sectors)
43054265d620SPaolo Bonzini {
43064265d620SPaolo Bonzini     if (!bs->drv) {
43074265d620SPaolo Bonzini         return -ENOMEDIUM;
43084265d620SPaolo Bonzini     } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
43094265d620SPaolo Bonzini         return -EIO;
43104265d620SPaolo Bonzini     } else if (bs->read_only) {
43114265d620SPaolo Bonzini         return -EROFS;
4312df702c9bSPaolo Bonzini     }
4313df702c9bSPaolo Bonzini 
4314df702c9bSPaolo Bonzini     if (bs->dirty_bitmap) {
43158f0720ecSPaolo Bonzini         bdrv_reset_dirty(bs, sector_num, nb_sectors);
4316df702c9bSPaolo Bonzini     }
4317df702c9bSPaolo Bonzini 
43189e8f1835SPaolo Bonzini     /* Do nothing if disabled.  */
43199e8f1835SPaolo Bonzini     if (!(bs->open_flags & BDRV_O_UNMAP)) {
43209e8f1835SPaolo Bonzini         return 0;
43219e8f1835SPaolo Bonzini     }
43229e8f1835SPaolo Bonzini 
4323df702c9bSPaolo Bonzini     if (bs->drv->bdrv_co_discard) {
43244265d620SPaolo Bonzini         return bs->drv->bdrv_co_discard(bs, sector_num, nb_sectors);
43254265d620SPaolo Bonzini     } else if (bs->drv->bdrv_aio_discard) {
43264265d620SPaolo Bonzini         BlockDriverAIOCB *acb;
43274265d620SPaolo Bonzini         CoroutineIOCompletion co = {
43284265d620SPaolo Bonzini             .coroutine = qemu_coroutine_self(),
43294265d620SPaolo Bonzini         };
43304265d620SPaolo Bonzini 
43314265d620SPaolo Bonzini         acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
43324265d620SPaolo Bonzini                                         bdrv_co_io_em_complete, &co);
43334265d620SPaolo Bonzini         if (acb == NULL) {
43344265d620SPaolo Bonzini             return -EIO;
43354265d620SPaolo Bonzini         } else {
43364265d620SPaolo Bonzini             qemu_coroutine_yield();
43374265d620SPaolo Bonzini             return co.ret;
43384265d620SPaolo Bonzini         }
43394265d620SPaolo Bonzini     } else {
43404265d620SPaolo Bonzini         return 0;
43414265d620SPaolo Bonzini     }
43424265d620SPaolo Bonzini }
43434265d620SPaolo Bonzini 
43444265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
43454265d620SPaolo Bonzini {
43464265d620SPaolo Bonzini     Coroutine *co;
43474265d620SPaolo Bonzini     RwCo rwco = {
43484265d620SPaolo Bonzini         .bs = bs,
43494265d620SPaolo Bonzini         .sector_num = sector_num,
43504265d620SPaolo Bonzini         .nb_sectors = nb_sectors,
43514265d620SPaolo Bonzini         .ret = NOT_DONE,
43524265d620SPaolo Bonzini     };
43534265d620SPaolo Bonzini 
43544265d620SPaolo Bonzini     if (qemu_in_coroutine()) {
43554265d620SPaolo Bonzini         /* Fast-path if already in coroutine context */
43564265d620SPaolo Bonzini         bdrv_discard_co_entry(&rwco);
43574265d620SPaolo Bonzini     } else {
43584265d620SPaolo Bonzini         co = qemu_coroutine_create(bdrv_discard_co_entry);
43594265d620SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
43604265d620SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
43614265d620SPaolo Bonzini             qemu_aio_wait();
43624265d620SPaolo Bonzini         }
43634265d620SPaolo Bonzini     }
43644265d620SPaolo Bonzini 
43654265d620SPaolo Bonzini     return rwco.ret;
43664265d620SPaolo Bonzini }
43674265d620SPaolo Bonzini 
4368f9f05dc5SKevin Wolf /**************************************************************/
436919cb3738Sbellard /* removable device support */
437019cb3738Sbellard 
437119cb3738Sbellard /**
437219cb3738Sbellard  * Return TRUE if the media is present
437319cb3738Sbellard  */
437419cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
437519cb3738Sbellard {
437619cb3738Sbellard     BlockDriver *drv = bs->drv;
4377a1aff5bfSMarkus Armbruster 
437819cb3738Sbellard     if (!drv)
437919cb3738Sbellard         return 0;
438019cb3738Sbellard     if (!drv->bdrv_is_inserted)
4381a1aff5bfSMarkus Armbruster         return 1;
4382a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
438319cb3738Sbellard }
438419cb3738Sbellard 
438519cb3738Sbellard /**
43868e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
43878e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
438819cb3738Sbellard  */
438919cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
439019cb3738Sbellard {
439119cb3738Sbellard     BlockDriver *drv = bs->drv;
439219cb3738Sbellard 
43938e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
43948e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
43958e49ca46SMarkus Armbruster     }
43968e49ca46SMarkus Armbruster     return -ENOTSUP;
439719cb3738Sbellard }
439819cb3738Sbellard 
439919cb3738Sbellard /**
440019cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
440119cb3738Sbellard  */
4402f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
440319cb3738Sbellard {
440419cb3738Sbellard     BlockDriver *drv = bs->drv;
440519cb3738Sbellard 
4406822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
4407822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
440819cb3738Sbellard     }
44096f382ed2SLuiz Capitulino 
44106f382ed2SLuiz Capitulino     if (bs->device_name[0] != '\0') {
44116f382ed2SLuiz Capitulino         bdrv_emit_qmp_eject_event(bs, eject_flag);
44126f382ed2SLuiz Capitulino     }
441319cb3738Sbellard }
441419cb3738Sbellard 
441519cb3738Sbellard /**
441619cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
441719cb3738Sbellard  * to eject it manually).
441819cb3738Sbellard  */
4419025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
442019cb3738Sbellard {
442119cb3738Sbellard     BlockDriver *drv = bs->drv;
442219cb3738Sbellard 
4423025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
4424b8c6d095SStefan Hajnoczi 
4425025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
4426025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
442719cb3738Sbellard     }
442819cb3738Sbellard }
4429985a03b0Sths 
4430985a03b0Sths /* needed for generic scsi interface */
4431985a03b0Sths 
4432985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
4433985a03b0Sths {
4434985a03b0Sths     BlockDriver *drv = bs->drv;
4435985a03b0Sths 
4436985a03b0Sths     if (drv && drv->bdrv_ioctl)
4437985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
4438985a03b0Sths     return -ENOTSUP;
4439985a03b0Sths }
44407d780669Saliguori 
4441221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
4442221f715dSaliguori         unsigned long int req, void *buf,
44437d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
44447d780669Saliguori {
4445221f715dSaliguori     BlockDriver *drv = bs->drv;
44467d780669Saliguori 
4447221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
4448221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
4449221f715dSaliguori     return NULL;
44507d780669Saliguori }
4451e268ca52Saliguori 
44527b6f9300SMarkus Armbruster void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
44537b6f9300SMarkus Armbruster {
44547b6f9300SMarkus Armbruster     bs->buffer_alignment = align;
44557b6f9300SMarkus Armbruster }
44567cd1e32aSlirans@il.ibm.com 
4457e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
4458e268ca52Saliguori {
4459e268ca52Saliguori     return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
4460e268ca52Saliguori }
44617cd1e32aSlirans@il.ibm.com 
4462c53b1c51SStefan Hajnoczi /*
4463c53b1c51SStefan Hajnoczi  * Check if all memory in this vector is sector aligned.
4464c53b1c51SStefan Hajnoczi  */
4465c53b1c51SStefan Hajnoczi bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
4466c53b1c51SStefan Hajnoczi {
4467c53b1c51SStefan Hajnoczi     int i;
4468c53b1c51SStefan Hajnoczi 
4469c53b1c51SStefan Hajnoczi     for (i = 0; i < qiov->niov; i++) {
4470c53b1c51SStefan Hajnoczi         if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {
4471c53b1c51SStefan Hajnoczi             return false;
4472c53b1c51SStefan Hajnoczi         }
4473c53b1c51SStefan Hajnoczi     }
4474c53b1c51SStefan Hajnoczi 
4475c53b1c51SStefan Hajnoczi     return true;
4476c53b1c51SStefan Hajnoczi }
4477c53b1c51SStefan Hajnoczi 
447850717e94SPaolo Bonzini void bdrv_set_dirty_tracking(BlockDriverState *bs, int granularity)
44797cd1e32aSlirans@il.ibm.com {
44807cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
4481a55eb92cSJan Kiszka 
448250717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
448350717e94SPaolo Bonzini 
448450717e94SPaolo Bonzini     if (granularity) {
448550717e94SPaolo Bonzini         granularity >>= BDRV_SECTOR_BITS;
448650717e94SPaolo Bonzini         assert(!bs->dirty_bitmap);
44878f0720ecSPaolo Bonzini         bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS);
448850717e94SPaolo Bonzini         bs->dirty_bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
44897cd1e32aSlirans@il.ibm.com     } else {
4490c6d22830SJan Kiszka         if (bs->dirty_bitmap) {
44918f0720ecSPaolo Bonzini             hbitmap_free(bs->dirty_bitmap);
4492c6d22830SJan Kiszka             bs->dirty_bitmap = NULL;
44937cd1e32aSlirans@il.ibm.com         }
44947cd1e32aSlirans@il.ibm.com     }
44957cd1e32aSlirans@il.ibm.com }
44967cd1e32aSlirans@il.ibm.com 
44977cd1e32aSlirans@il.ibm.com int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
44987cd1e32aSlirans@il.ibm.com {
44998f0720ecSPaolo Bonzini     if (bs->dirty_bitmap) {
45008f0720ecSPaolo Bonzini         return hbitmap_get(bs->dirty_bitmap, sector);
45017cd1e32aSlirans@il.ibm.com     } else {
45027cd1e32aSlirans@il.ibm.com         return 0;
45037cd1e32aSlirans@il.ibm.com     }
45047cd1e32aSlirans@il.ibm.com }
45057cd1e32aSlirans@il.ibm.com 
45068f0720ecSPaolo Bonzini void bdrv_dirty_iter_init(BlockDriverState *bs, HBitmapIter *hbi)
45071755da16SPaolo Bonzini {
45088f0720ecSPaolo Bonzini     hbitmap_iter_init(hbi, bs->dirty_bitmap, 0);
45091755da16SPaolo Bonzini }
45101755da16SPaolo Bonzini 
45111755da16SPaolo Bonzini void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
45121755da16SPaolo Bonzini                     int nr_sectors)
45131755da16SPaolo Bonzini {
45148f0720ecSPaolo Bonzini     hbitmap_set(bs->dirty_bitmap, cur_sector, nr_sectors);
45151755da16SPaolo Bonzini }
45161755da16SPaolo Bonzini 
45177cd1e32aSlirans@il.ibm.com void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
45187cd1e32aSlirans@il.ibm.com                       int nr_sectors)
45197cd1e32aSlirans@il.ibm.com {
45208f0720ecSPaolo Bonzini     hbitmap_reset(bs->dirty_bitmap, cur_sector, nr_sectors);
45217cd1e32aSlirans@il.ibm.com }
4522aaa0eb75SLiran Schour 
4523aaa0eb75SLiran Schour int64_t bdrv_get_dirty_count(BlockDriverState *bs)
4524aaa0eb75SLiran Schour {
45258f0720ecSPaolo Bonzini     if (bs->dirty_bitmap) {
4526acc906c6SPaolo Bonzini         return hbitmap_count(bs->dirty_bitmap);
45278f0720ecSPaolo Bonzini     } else {
45288f0720ecSPaolo Bonzini         return 0;
45298f0720ecSPaolo Bonzini     }
4530aaa0eb75SLiran Schour }
4531f88e1a42SJes Sorensen 
4532db593f25SMarcelo Tosatti void bdrv_set_in_use(BlockDriverState *bs, int in_use)
4533db593f25SMarcelo Tosatti {
4534db593f25SMarcelo Tosatti     assert(bs->in_use != in_use);
4535db593f25SMarcelo Tosatti     bs->in_use = in_use;
4536db593f25SMarcelo Tosatti }
4537db593f25SMarcelo Tosatti 
4538db593f25SMarcelo Tosatti int bdrv_in_use(BlockDriverState *bs)
4539db593f25SMarcelo Tosatti {
4540db593f25SMarcelo Tosatti     return bs->in_use;
4541db593f25SMarcelo Tosatti }
4542db593f25SMarcelo Tosatti 
454328a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
454428a7282aSLuiz Capitulino {
4545d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
454658e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
454728a7282aSLuiz Capitulino }
454828a7282aSLuiz Capitulino 
454928a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
455028a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
455128a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
455228a7282aSLuiz Capitulino {
4553d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
455492aa5c6dSPaolo Bonzini            (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
455592aa5c6dSPaolo Bonzini             bs->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
455692aa5c6dSPaolo Bonzini             bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
455728a7282aSLuiz Capitulino }
455828a7282aSLuiz Capitulino 
455928a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
456028a7282aSLuiz Capitulino {
4561d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
456228a7282aSLuiz Capitulino }
456328a7282aSLuiz Capitulino 
456428a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
456528a7282aSLuiz Capitulino {
456628a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
456758e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
45683bd293c3SPaolo Bonzini         if (bs->job) {
45693bd293c3SPaolo Bonzini             block_job_iostatus_reset(bs->job);
45703bd293c3SPaolo Bonzini         }
457128a7282aSLuiz Capitulino     }
457228a7282aSLuiz Capitulino }
457328a7282aSLuiz Capitulino 
457428a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
457528a7282aSLuiz Capitulino {
45763e1caa5fSPaolo Bonzini     assert(bdrv_iostatus_is_enabled(bs));
45773e1caa5fSPaolo Bonzini     if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
457858e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
457958e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
458028a7282aSLuiz Capitulino     }
458128a7282aSLuiz Capitulino }
458228a7282aSLuiz Capitulino 
4583a597e79cSChristoph Hellwig void
4584a597e79cSChristoph Hellwig bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
4585a597e79cSChristoph Hellwig         enum BlockAcctType type)
4586a597e79cSChristoph Hellwig {
4587a597e79cSChristoph Hellwig     assert(type < BDRV_MAX_IOTYPE);
4588a597e79cSChristoph Hellwig 
4589a597e79cSChristoph Hellwig     cookie->bytes = bytes;
4590c488c7f6SChristoph Hellwig     cookie->start_time_ns = get_clock();
4591a597e79cSChristoph Hellwig     cookie->type = type;
4592a597e79cSChristoph Hellwig }
4593a597e79cSChristoph Hellwig 
4594a597e79cSChristoph Hellwig void
4595a597e79cSChristoph Hellwig bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
4596a597e79cSChristoph Hellwig {
4597a597e79cSChristoph Hellwig     assert(cookie->type < BDRV_MAX_IOTYPE);
4598a597e79cSChristoph Hellwig 
4599a597e79cSChristoph Hellwig     bs->nr_bytes[cookie->type] += cookie->bytes;
4600a597e79cSChristoph Hellwig     bs->nr_ops[cookie->type]++;
4601c488c7f6SChristoph Hellwig     bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
4602a597e79cSChristoph Hellwig }
4603a597e79cSChristoph Hellwig 
4604d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
4605f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
4606f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
4607f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
4608f88e1a42SJes Sorensen {
4609f88e1a42SJes Sorensen     QEMUOptionParameter *param = NULL, *create_options = NULL;
4610d220894eSKevin Wolf     QEMUOptionParameter *backing_fmt, *backing_file, *size;
4611f88e1a42SJes Sorensen     BlockDriverState *bs = NULL;
4612f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
461396df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
4614f88e1a42SJes Sorensen     int ret = 0;
4615f88e1a42SJes Sorensen 
4616f88e1a42SJes Sorensen     /* Find driver and parse its options */
4617f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
4618f88e1a42SJes Sorensen     if (!drv) {
461971c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
4620d92ada22SLuiz Capitulino         return;
4621f88e1a42SJes Sorensen     }
4622f88e1a42SJes Sorensen 
4623f88e1a42SJes Sorensen     proto_drv = bdrv_find_protocol(filename);
4624f88e1a42SJes Sorensen     if (!proto_drv) {
462571c79813SLuiz Capitulino         error_setg(errp, "Unknown protocol '%s'", filename);
4626d92ada22SLuiz Capitulino         return;
4627f88e1a42SJes Sorensen     }
4628f88e1a42SJes Sorensen 
4629f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
4630f88e1a42SJes Sorensen                                               drv->create_options);
4631f88e1a42SJes Sorensen     create_options = append_option_parameters(create_options,
4632f88e1a42SJes Sorensen                                               proto_drv->create_options);
4633f88e1a42SJes Sorensen 
4634f88e1a42SJes Sorensen     /* Create parameter list with default values */
4635f88e1a42SJes Sorensen     param = parse_option_parameters("", create_options, param);
4636f88e1a42SJes Sorensen 
4637f88e1a42SJes Sorensen     set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
4638f88e1a42SJes Sorensen 
4639f88e1a42SJes Sorensen     /* Parse -o options */
4640f88e1a42SJes Sorensen     if (options) {
4641f88e1a42SJes Sorensen         param = parse_option_parameters(options, create_options, param);
4642f88e1a42SJes Sorensen         if (param == NULL) {
464371c79813SLuiz Capitulino             error_setg(errp, "Invalid options for file format '%s'.", fmt);
4644f88e1a42SJes Sorensen             goto out;
4645f88e1a42SJes Sorensen         }
4646f88e1a42SJes Sorensen     }
4647f88e1a42SJes Sorensen 
4648f88e1a42SJes Sorensen     if (base_filename) {
4649f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
4650f88e1a42SJes Sorensen                                  base_filename)) {
465171c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
465271c79813SLuiz Capitulino                        fmt);
4653f88e1a42SJes Sorensen             goto out;
4654f88e1a42SJes Sorensen         }
4655f88e1a42SJes Sorensen     }
4656f88e1a42SJes Sorensen 
4657f88e1a42SJes Sorensen     if (base_fmt) {
4658f88e1a42SJes Sorensen         if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
465971c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
466071c79813SLuiz Capitulino                              "format '%s'", fmt);
4661f88e1a42SJes Sorensen             goto out;
4662f88e1a42SJes Sorensen         }
4663f88e1a42SJes Sorensen     }
4664f88e1a42SJes Sorensen 
4665792da93aSJes Sorensen     backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
4666792da93aSJes Sorensen     if (backing_file && backing_file->value.s) {
4667792da93aSJes Sorensen         if (!strcmp(filename, backing_file->value.s)) {
466871c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
466971c79813SLuiz Capitulino                              "same filename as the backing file");
4670792da93aSJes Sorensen             goto out;
4671792da93aSJes Sorensen         }
4672792da93aSJes Sorensen     }
4673792da93aSJes Sorensen 
4674f88e1a42SJes Sorensen     backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
4675f88e1a42SJes Sorensen     if (backing_fmt && backing_fmt->value.s) {
467696df67d1SStefan Hajnoczi         backing_drv = bdrv_find_format(backing_fmt->value.s);
467796df67d1SStefan Hajnoczi         if (!backing_drv) {
467871c79813SLuiz Capitulino             error_setg(errp, "Unknown backing file format '%s'",
467971c79813SLuiz Capitulino                        backing_fmt->value.s);
4680f88e1a42SJes Sorensen             goto out;
4681f88e1a42SJes Sorensen         }
4682f88e1a42SJes Sorensen     }
4683f88e1a42SJes Sorensen 
4684f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
4685f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
4686d220894eSKevin Wolf     size = get_option_parameter(param, BLOCK_OPT_SIZE);
4687d220894eSKevin Wolf     if (size && size->value.n == -1) {
4688f88e1a42SJes Sorensen         if (backing_file && backing_file->value.s) {
4689f88e1a42SJes Sorensen             uint64_t size;
4690f88e1a42SJes Sorensen             char buf[32];
469163090dacSPaolo Bonzini             int back_flags;
469263090dacSPaolo Bonzini 
469363090dacSPaolo Bonzini             /* backing files always opened read-only */
469463090dacSPaolo Bonzini             back_flags =
469563090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
4696f88e1a42SJes Sorensen 
4697f88e1a42SJes Sorensen             bs = bdrv_new("");
4698f88e1a42SJes Sorensen 
4699de9c0cecSKevin Wolf             ret = bdrv_open(bs, backing_file->value.s, NULL, back_flags,
4700de9c0cecSKevin Wolf                             backing_drv);
4701f88e1a42SJes Sorensen             if (ret < 0) {
470271c79813SLuiz Capitulino                 error_setg_errno(errp, -ret, "Could not open '%s'",
470371c79813SLuiz Capitulino                                  backing_file->value.s);
4704f88e1a42SJes Sorensen                 goto out;
4705f88e1a42SJes Sorensen             }
4706f88e1a42SJes Sorensen             bdrv_get_geometry(bs, &size);
4707f88e1a42SJes Sorensen             size *= 512;
4708f88e1a42SJes Sorensen 
4709f88e1a42SJes Sorensen             snprintf(buf, sizeof(buf), "%" PRId64, size);
4710f88e1a42SJes Sorensen             set_option_parameter(param, BLOCK_OPT_SIZE, buf);
4711f88e1a42SJes Sorensen         } else {
471271c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
4713f88e1a42SJes Sorensen             goto out;
4714f88e1a42SJes Sorensen         }
4715f88e1a42SJes Sorensen     }
4716f88e1a42SJes Sorensen 
4717f382d43aSMiroslav Rezanina     if (!quiet) {
4718f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
4719f88e1a42SJes Sorensen         print_option_parameters(param);
4720f88e1a42SJes Sorensen         puts("");
4721f382d43aSMiroslav Rezanina     }
4722f88e1a42SJes Sorensen     ret = bdrv_create(drv, filename, param);
4723f88e1a42SJes Sorensen     if (ret < 0) {
4724f88e1a42SJes Sorensen         if (ret == -ENOTSUP) {
472571c79813SLuiz Capitulino             error_setg(errp,"Formatting or formatting option not supported for "
472671c79813SLuiz Capitulino                             "file format '%s'", fmt);
4727f88e1a42SJes Sorensen         } else if (ret == -EFBIG) {
472871c79813SLuiz Capitulino             error_setg(errp, "The image size is too large for file format '%s'",
472971c79813SLuiz Capitulino                        fmt);
4730f88e1a42SJes Sorensen         } else {
473171c79813SLuiz Capitulino             error_setg(errp, "%s: error while creating %s: %s", filename, fmt,
473271c79813SLuiz Capitulino                        strerror(-ret));
4733f88e1a42SJes Sorensen         }
4734f88e1a42SJes Sorensen     }
4735f88e1a42SJes Sorensen 
4736f88e1a42SJes Sorensen out:
4737f88e1a42SJes Sorensen     free_option_parameters(create_options);
4738f88e1a42SJes Sorensen     free_option_parameters(param);
4739f88e1a42SJes Sorensen 
4740f88e1a42SJes Sorensen     if (bs) {
4741f88e1a42SJes Sorensen         bdrv_delete(bs);
4742f88e1a42SJes Sorensen     }
4743f88e1a42SJes Sorensen }
474485d126f3SStefan Hajnoczi 
474585d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
474685d126f3SStefan Hajnoczi {
474785d126f3SStefan Hajnoczi     /* Currently BlockDriverState always uses the main loop AioContext */
474885d126f3SStefan Hajnoczi     return qemu_get_aio_context();
474985d126f3SStefan Hajnoczi }
4750