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" 35c13163fbSBenoît Canet #include "block/qapi.h" 36b2023818SLuiz Capitulino #include "qmp-commands.h" 371de7afc9SPaolo Bonzini #include "qemu/timer.h" 38fc01f7e7Sbellard 3971e72a19SJuan Quintela #ifdef CONFIG_BSD 407674e7bfSbellard #include <sys/types.h> 417674e7bfSbellard #include <sys/stat.h> 427674e7bfSbellard #include <sys/ioctl.h> 4372cf2d4fSBlue Swirl #include <sys/queue.h> 44c5e97233Sblueswir1 #ifndef __DragonFly__ 457674e7bfSbellard #include <sys/disk.h> 467674e7bfSbellard #endif 47c5e97233Sblueswir1 #endif 487674e7bfSbellard 4949dc768dSaliguori #ifdef _WIN32 5049dc768dSaliguori #include <windows.h> 5149dc768dSaliguori #endif 5249dc768dSaliguori 53e4654d2dSFam Zheng struct BdrvDirtyBitmap { 54e4654d2dSFam Zheng HBitmap *bitmap; 55e4654d2dSFam Zheng QLIST_ENTRY(BdrvDirtyBitmap) list; 56e4654d2dSFam Zheng }; 57e4654d2dSFam Zheng 581c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */ 591c9805a3SStefan Hajnoczi 607d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load); 61f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs, 62f141eafeSaliguori int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, 63c87c0672Saliguori BlockDriverCompletionFunc *cb, void *opaque); 64f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs, 65f141eafeSaliguori int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, 66ce1a14dcSpbrook BlockDriverCompletionFunc *cb, void *opaque); 67f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs, 68f9f05dc5SKevin Wolf int64_t sector_num, int nb_sectors, 69f9f05dc5SKevin Wolf QEMUIOVector *iov); 70f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs, 71f9f05dc5SKevin Wolf int64_t sector_num, int nb_sectors, 72f9f05dc5SKevin Wolf QEMUIOVector *iov); 73775aa8b6SKevin Wolf static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs, 74775aa8b6SKevin Wolf int64_t offset, unsigned int bytes, QEMUIOVector *qiov, 75470c0504SStefan Hajnoczi BdrvRequestFlags flags); 76775aa8b6SKevin Wolf static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs, 77775aa8b6SKevin Wolf int64_t offset, unsigned int bytes, QEMUIOVector *qiov, 78f08f2ddaSStefan Hajnoczi BdrvRequestFlags flags); 79b2a61371SStefan Hajnoczi static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs, 80b2a61371SStefan Hajnoczi int64_t sector_num, 81b2a61371SStefan Hajnoczi QEMUIOVector *qiov, 82b2a61371SStefan Hajnoczi int nb_sectors, 83d20d9b7cSPaolo Bonzini BdrvRequestFlags flags, 84b2a61371SStefan Hajnoczi BlockDriverCompletionFunc *cb, 85b2a61371SStefan Hajnoczi void *opaque, 868c5873d6SStefan Hajnoczi bool is_write); 87b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque); 88621f0589SKevin Wolf static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs, 89aa7bfbffSPeter Lieven int64_t sector_num, int nb_sectors, BdrvRequestFlags flags); 90ec530c81Sbellard 911b7bdbc1SStefan Hajnoczi static QTAILQ_HEAD(, BlockDriverState) bdrv_states = 921b7bdbc1SStefan Hajnoczi QTAILQ_HEAD_INITIALIZER(bdrv_states); 937ee930d0Sblueswir1 94dc364f4cSBenoît Canet static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states = 95dc364f4cSBenoît Canet QTAILQ_HEAD_INITIALIZER(graph_bdrv_states); 96dc364f4cSBenoît Canet 978a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers = 988a22f02aSStefan Hajnoczi QLIST_HEAD_INITIALIZER(bdrv_drivers); 99ea2384d3Sbellard 100eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */ 101eb852011SMarkus Armbruster static int use_bdrv_whitelist; 102eb852011SMarkus Armbruster 1039e0b22f4SStefan Hajnoczi #ifdef _WIN32 1049e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename) 1059e0b22f4SStefan Hajnoczi { 1069e0b22f4SStefan Hajnoczi return (((filename[0] >= 'a' && filename[0] <= 'z') || 1079e0b22f4SStefan Hajnoczi (filename[0] >= 'A' && filename[0] <= 'Z')) && 1089e0b22f4SStefan Hajnoczi filename[1] == ':'); 1099e0b22f4SStefan Hajnoczi } 1109e0b22f4SStefan Hajnoczi 1119e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename) 1129e0b22f4SStefan Hajnoczi { 1139e0b22f4SStefan Hajnoczi if (is_windows_drive_prefix(filename) && 1149e0b22f4SStefan Hajnoczi filename[2] == '\0') 1159e0b22f4SStefan Hajnoczi return 1; 1169e0b22f4SStefan Hajnoczi if (strstart(filename, "\\\\.\\", NULL) || 1179e0b22f4SStefan Hajnoczi strstart(filename, "//./", NULL)) 1189e0b22f4SStefan Hajnoczi return 1; 1199e0b22f4SStefan Hajnoczi return 0; 1209e0b22f4SStefan Hajnoczi } 1219e0b22f4SStefan Hajnoczi #endif 1229e0b22f4SStefan Hajnoczi 1230563e191SZhi Yong Wu /* throttling disk I/O limits */ 124cc0681c4SBenoît Canet void bdrv_set_io_limits(BlockDriverState *bs, 125cc0681c4SBenoît Canet ThrottleConfig *cfg) 126cc0681c4SBenoît Canet { 127cc0681c4SBenoît Canet int i; 128cc0681c4SBenoît Canet 129cc0681c4SBenoît Canet throttle_config(&bs->throttle_state, cfg); 130cc0681c4SBenoît Canet 131cc0681c4SBenoît Canet for (i = 0; i < 2; i++) { 132cc0681c4SBenoît Canet qemu_co_enter_next(&bs->throttled_reqs[i]); 133cc0681c4SBenoît Canet } 134cc0681c4SBenoît Canet } 135cc0681c4SBenoît Canet 136cc0681c4SBenoît Canet /* this function drain all the throttled IOs */ 137cc0681c4SBenoît Canet static bool bdrv_start_throttled_reqs(BlockDriverState *bs) 138cc0681c4SBenoît Canet { 139cc0681c4SBenoît Canet bool drained = false; 140cc0681c4SBenoît Canet bool enabled = bs->io_limits_enabled; 141cc0681c4SBenoît Canet int i; 142cc0681c4SBenoît Canet 143cc0681c4SBenoît Canet bs->io_limits_enabled = false; 144cc0681c4SBenoît Canet 145cc0681c4SBenoît Canet for (i = 0; i < 2; i++) { 146cc0681c4SBenoît Canet while (qemu_co_enter_next(&bs->throttled_reqs[i])) { 147cc0681c4SBenoît Canet drained = true; 148cc0681c4SBenoît Canet } 149cc0681c4SBenoît Canet } 150cc0681c4SBenoît Canet 151cc0681c4SBenoît Canet bs->io_limits_enabled = enabled; 152cc0681c4SBenoît Canet 153cc0681c4SBenoît Canet return drained; 154cc0681c4SBenoît Canet } 155cc0681c4SBenoît Canet 15698f90dbaSZhi Yong Wu void bdrv_io_limits_disable(BlockDriverState *bs) 15798f90dbaSZhi Yong Wu { 15898f90dbaSZhi Yong Wu bs->io_limits_enabled = false; 15998f90dbaSZhi Yong Wu 160cc0681c4SBenoît Canet bdrv_start_throttled_reqs(bs); 16198f90dbaSZhi Yong Wu 162cc0681c4SBenoît Canet throttle_destroy(&bs->throttle_state); 16398f90dbaSZhi Yong Wu } 16498f90dbaSZhi Yong Wu 165cc0681c4SBenoît Canet static void bdrv_throttle_read_timer_cb(void *opaque) 1660563e191SZhi Yong Wu { 1670563e191SZhi Yong Wu BlockDriverState *bs = opaque; 168cc0681c4SBenoît Canet qemu_co_enter_next(&bs->throttled_reqs[0]); 1690563e191SZhi Yong Wu } 1700563e191SZhi Yong Wu 171cc0681c4SBenoît Canet static void bdrv_throttle_write_timer_cb(void *opaque) 172cc0681c4SBenoît Canet { 173cc0681c4SBenoît Canet BlockDriverState *bs = opaque; 174cc0681c4SBenoît Canet qemu_co_enter_next(&bs->throttled_reqs[1]); 175cc0681c4SBenoît Canet } 176cc0681c4SBenoît Canet 177cc0681c4SBenoît Canet /* should be called before bdrv_set_io_limits if a limit is set */ 1780563e191SZhi Yong Wu void bdrv_io_limits_enable(BlockDriverState *bs) 1790563e191SZhi Yong Wu { 180cc0681c4SBenoît Canet assert(!bs->io_limits_enabled); 181cc0681c4SBenoît Canet throttle_init(&bs->throttle_state, 18213af91ebSStefan Hajnoczi bdrv_get_aio_context(bs), 183cc0681c4SBenoît Canet QEMU_CLOCK_VIRTUAL, 184cc0681c4SBenoît Canet bdrv_throttle_read_timer_cb, 185cc0681c4SBenoît Canet bdrv_throttle_write_timer_cb, 186cc0681c4SBenoît Canet bs); 1870563e191SZhi Yong Wu bs->io_limits_enabled = true; 1880563e191SZhi Yong Wu } 1890563e191SZhi Yong Wu 190cc0681c4SBenoît Canet /* This function makes an IO wait if needed 191cc0681c4SBenoît Canet * 192cc0681c4SBenoît Canet * @nb_sectors: the number of sectors of the IO 193cc0681c4SBenoît Canet * @is_write: is the IO a write 19498f90dbaSZhi Yong Wu */ 195cc0681c4SBenoît Canet static void bdrv_io_limits_intercept(BlockDriverState *bs, 196d5103588SKevin Wolf unsigned int bytes, 197cc0681c4SBenoît Canet bool is_write) 198cc0681c4SBenoît Canet { 199cc0681c4SBenoît Canet /* does this io must wait */ 200cc0681c4SBenoît Canet bool must_wait = throttle_schedule_timer(&bs->throttle_state, is_write); 20198f90dbaSZhi Yong Wu 202cc0681c4SBenoît Canet /* if must wait or any request of this type throttled queue the IO */ 203cc0681c4SBenoît Canet if (must_wait || 204cc0681c4SBenoît Canet !qemu_co_queue_empty(&bs->throttled_reqs[is_write])) { 205cc0681c4SBenoît Canet qemu_co_queue_wait(&bs->throttled_reqs[is_write]); 20698f90dbaSZhi Yong Wu } 20798f90dbaSZhi Yong Wu 208cc0681c4SBenoît Canet /* the IO will be executed, do the accounting */ 209d5103588SKevin Wolf throttle_account(&bs->throttle_state, is_write, bytes); 210d5103588SKevin Wolf 211cc0681c4SBenoît Canet 212cc0681c4SBenoît Canet /* if the next request must wait -> do nothing */ 213cc0681c4SBenoît Canet if (throttle_schedule_timer(&bs->throttle_state, is_write)) { 214cc0681c4SBenoît Canet return; 215cc0681c4SBenoît Canet } 216cc0681c4SBenoît Canet 217cc0681c4SBenoît Canet /* else queue next request for execution */ 218cc0681c4SBenoît Canet qemu_co_queue_next(&bs->throttled_reqs[is_write]); 21998f90dbaSZhi Yong Wu } 22098f90dbaSZhi Yong Wu 221339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs) 222339064d5SKevin Wolf { 223339064d5SKevin Wolf if (!bs || !bs->drv) { 224339064d5SKevin Wolf /* 4k should be on the safe side */ 225339064d5SKevin Wolf return 4096; 226339064d5SKevin Wolf } 227339064d5SKevin Wolf 228339064d5SKevin Wolf return bs->bl.opt_mem_alignment; 229339064d5SKevin Wolf } 230339064d5SKevin Wolf 2319e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */ 2329e0b22f4SStefan Hajnoczi static int path_has_protocol(const char *path) 2339e0b22f4SStefan Hajnoczi { 234947995c0SPaolo Bonzini const char *p; 235947995c0SPaolo Bonzini 2369e0b22f4SStefan Hajnoczi #ifdef _WIN32 2379e0b22f4SStefan Hajnoczi if (is_windows_drive(path) || 2389e0b22f4SStefan Hajnoczi is_windows_drive_prefix(path)) { 2399e0b22f4SStefan Hajnoczi return 0; 2409e0b22f4SStefan Hajnoczi } 241947995c0SPaolo Bonzini p = path + strcspn(path, ":/\\"); 242947995c0SPaolo Bonzini #else 243947995c0SPaolo Bonzini p = path + strcspn(path, ":/"); 2449e0b22f4SStefan Hajnoczi #endif 2459e0b22f4SStefan Hajnoczi 246947995c0SPaolo Bonzini return *p == ':'; 2479e0b22f4SStefan Hajnoczi } 2489e0b22f4SStefan Hajnoczi 24983f64091Sbellard int path_is_absolute(const char *path) 25083f64091Sbellard { 25121664424Sbellard #ifdef _WIN32 25221664424Sbellard /* specific case for names like: "\\.\d:" */ 253f53f4da9SPaolo Bonzini if (is_windows_drive(path) || is_windows_drive_prefix(path)) { 25421664424Sbellard return 1; 255f53f4da9SPaolo Bonzini } 256f53f4da9SPaolo Bonzini return (*path == '/' || *path == '\\'); 2573b9f94e1Sbellard #else 258f53f4da9SPaolo Bonzini return (*path == '/'); 2593b9f94e1Sbellard #endif 26083f64091Sbellard } 26183f64091Sbellard 26283f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a 26383f64091Sbellard path to it by considering it is relative to base_path. URL are 26483f64091Sbellard supported. */ 26583f64091Sbellard void path_combine(char *dest, int dest_size, 26683f64091Sbellard const char *base_path, 26783f64091Sbellard const char *filename) 26883f64091Sbellard { 26983f64091Sbellard const char *p, *p1; 27083f64091Sbellard int len; 27183f64091Sbellard 27283f64091Sbellard if (dest_size <= 0) 27383f64091Sbellard return; 27483f64091Sbellard if (path_is_absolute(filename)) { 27583f64091Sbellard pstrcpy(dest, dest_size, filename); 27683f64091Sbellard } else { 27783f64091Sbellard p = strchr(base_path, ':'); 27883f64091Sbellard if (p) 27983f64091Sbellard p++; 28083f64091Sbellard else 28183f64091Sbellard p = base_path; 2823b9f94e1Sbellard p1 = strrchr(base_path, '/'); 2833b9f94e1Sbellard #ifdef _WIN32 2843b9f94e1Sbellard { 2853b9f94e1Sbellard const char *p2; 2863b9f94e1Sbellard p2 = strrchr(base_path, '\\'); 2873b9f94e1Sbellard if (!p1 || p2 > p1) 2883b9f94e1Sbellard p1 = p2; 2893b9f94e1Sbellard } 2903b9f94e1Sbellard #endif 29183f64091Sbellard if (p1) 29283f64091Sbellard p1++; 29383f64091Sbellard else 29483f64091Sbellard p1 = base_path; 29583f64091Sbellard if (p1 > p) 29683f64091Sbellard p = p1; 29783f64091Sbellard len = p - base_path; 29883f64091Sbellard if (len > dest_size - 1) 29983f64091Sbellard len = dest_size - 1; 30083f64091Sbellard memcpy(dest, base_path, len); 30183f64091Sbellard dest[len] = '\0'; 30283f64091Sbellard pstrcat(dest, dest_size, filename); 30383f64091Sbellard } 30483f64091Sbellard } 30583f64091Sbellard 306dc5a1371SPaolo Bonzini void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz) 307dc5a1371SPaolo Bonzini { 308dc5a1371SPaolo Bonzini if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) { 309dc5a1371SPaolo Bonzini pstrcpy(dest, sz, bs->backing_file); 310dc5a1371SPaolo Bonzini } else { 311dc5a1371SPaolo Bonzini path_combine(dest, sz, bs->filename, bs->backing_file); 312dc5a1371SPaolo Bonzini } 313dc5a1371SPaolo Bonzini } 314dc5a1371SPaolo Bonzini 3155efa9d5aSAnthony Liguori void bdrv_register(BlockDriver *bdrv) 316ea2384d3Sbellard { 3178c5873d6SStefan Hajnoczi /* Block drivers without coroutine functions need emulation */ 3188c5873d6SStefan Hajnoczi if (!bdrv->bdrv_co_readv) { 319f9f05dc5SKevin Wolf bdrv->bdrv_co_readv = bdrv_co_readv_em; 320f9f05dc5SKevin Wolf bdrv->bdrv_co_writev = bdrv_co_writev_em; 321f9f05dc5SKevin Wolf 322f8c35c1dSStefan Hajnoczi /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if 323f8c35c1dSStefan Hajnoczi * the block driver lacks aio we need to emulate that too. 324f8c35c1dSStefan Hajnoczi */ 325f9f05dc5SKevin Wolf if (!bdrv->bdrv_aio_readv) { 32683f64091Sbellard /* add AIO emulation layer */ 327f141eafeSaliguori bdrv->bdrv_aio_readv = bdrv_aio_readv_em; 328f141eafeSaliguori bdrv->bdrv_aio_writev = bdrv_aio_writev_em; 32983f64091Sbellard } 330f9f05dc5SKevin Wolf } 331b2e12bc6SChristoph Hellwig 332*83d0521aSChunyan Liu if (bdrv->bdrv_create) { 333*83d0521aSChunyan Liu assert(!bdrv->bdrv_create2 && !bdrv->create_opts); 334*83d0521aSChunyan Liu assert(!bdrv->bdrv_amend_options2); 335*83d0521aSChunyan Liu } else if (bdrv->bdrv_create2) { 336*83d0521aSChunyan Liu assert(!bdrv->bdrv_create && !bdrv->create_options); 337*83d0521aSChunyan Liu assert(!bdrv->bdrv_amend_options); 338*83d0521aSChunyan Liu } 3398a22f02aSStefan Hajnoczi QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list); 340ea2384d3Sbellard } 341b338082bSbellard 342b338082bSbellard /* create a new block device (by default it is empty) */ 34398522f63SKevin Wolf BlockDriverState *bdrv_new(const char *device_name, Error **errp) 344fc01f7e7Sbellard { 3451b7bdbc1SStefan Hajnoczi BlockDriverState *bs; 346fbe40ff7SFam Zheng int i; 347b338082bSbellard 348f2d953ecSKevin Wolf if (bdrv_find(device_name)) { 349f2d953ecSKevin Wolf error_setg(errp, "Device with id '%s' already exists", 350f2d953ecSKevin Wolf device_name); 351f2d953ecSKevin Wolf return NULL; 352f2d953ecSKevin Wolf } 353f2d953ecSKevin Wolf if (bdrv_find_node(device_name)) { 354f2d953ecSKevin Wolf error_setg(errp, "Device with node-name '%s' already exists", 355f2d953ecSKevin Wolf device_name); 356f2d953ecSKevin Wolf return NULL; 357f2d953ecSKevin Wolf } 358f2d953ecSKevin Wolf 3597267c094SAnthony Liguori bs = g_malloc0(sizeof(BlockDriverState)); 360e4654d2dSFam Zheng QLIST_INIT(&bs->dirty_bitmaps); 361b338082bSbellard pstrcpy(bs->device_name, sizeof(bs->device_name), device_name); 362ea2384d3Sbellard if (device_name[0] != '\0') { 363dc364f4cSBenoît Canet QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list); 364ea2384d3Sbellard } 365fbe40ff7SFam Zheng for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { 366fbe40ff7SFam Zheng QLIST_INIT(&bs->op_blockers[i]); 367fbe40ff7SFam Zheng } 36828a7282aSLuiz Capitulino bdrv_iostatus_disable(bs); 369d7d512f6SPaolo Bonzini notifier_list_init(&bs->close_notifiers); 370d616b224SStefan Hajnoczi notifier_with_return_list_init(&bs->before_write_notifiers); 371cc0681c4SBenoît Canet qemu_co_queue_init(&bs->throttled_reqs[0]); 372cc0681c4SBenoît Canet qemu_co_queue_init(&bs->throttled_reqs[1]); 3739fcb0251SFam Zheng bs->refcnt = 1; 374dcd04228SStefan Hajnoczi bs->aio_context = qemu_get_aio_context(); 375d7d512f6SPaolo Bonzini 376b338082bSbellard return bs; 377b338082bSbellard } 378b338082bSbellard 379d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify) 380d7d512f6SPaolo Bonzini { 381d7d512f6SPaolo Bonzini notifier_list_add(&bs->close_notifiers, notify); 382d7d512f6SPaolo Bonzini } 383d7d512f6SPaolo Bonzini 384ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name) 385ea2384d3Sbellard { 386ea2384d3Sbellard BlockDriver *drv1; 3878a22f02aSStefan Hajnoczi QLIST_FOREACH(drv1, &bdrv_drivers, list) { 3888a22f02aSStefan Hajnoczi if (!strcmp(drv1->format_name, format_name)) { 389ea2384d3Sbellard return drv1; 390ea2384d3Sbellard } 3918a22f02aSStefan Hajnoczi } 392ea2384d3Sbellard return NULL; 393ea2384d3Sbellard } 394ea2384d3Sbellard 395b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only) 396eb852011SMarkus Armbruster { 397b64ec4e4SFam Zheng static const char *whitelist_rw[] = { 398b64ec4e4SFam Zheng CONFIG_BDRV_RW_WHITELIST 399b64ec4e4SFam Zheng }; 400b64ec4e4SFam Zheng static const char *whitelist_ro[] = { 401b64ec4e4SFam Zheng CONFIG_BDRV_RO_WHITELIST 402eb852011SMarkus Armbruster }; 403eb852011SMarkus Armbruster const char **p; 404eb852011SMarkus Armbruster 405b64ec4e4SFam Zheng if (!whitelist_rw[0] && !whitelist_ro[0]) { 406eb852011SMarkus Armbruster return 1; /* no whitelist, anything goes */ 407b64ec4e4SFam Zheng } 408eb852011SMarkus Armbruster 409b64ec4e4SFam Zheng for (p = whitelist_rw; *p; p++) { 410eb852011SMarkus Armbruster if (!strcmp(drv->format_name, *p)) { 411eb852011SMarkus Armbruster return 1; 412eb852011SMarkus Armbruster } 413eb852011SMarkus Armbruster } 414b64ec4e4SFam Zheng if (read_only) { 415b64ec4e4SFam Zheng for (p = whitelist_ro; *p; p++) { 416b64ec4e4SFam Zheng if (!strcmp(drv->format_name, *p)) { 417b64ec4e4SFam Zheng return 1; 418b64ec4e4SFam Zheng } 419b64ec4e4SFam Zheng } 420b64ec4e4SFam Zheng } 421eb852011SMarkus Armbruster return 0; 422eb852011SMarkus Armbruster } 423eb852011SMarkus Armbruster 424b64ec4e4SFam Zheng BlockDriver *bdrv_find_whitelisted_format(const char *format_name, 425b64ec4e4SFam Zheng bool read_only) 426eb852011SMarkus Armbruster { 427eb852011SMarkus Armbruster BlockDriver *drv = bdrv_find_format(format_name); 428b64ec4e4SFam Zheng return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL; 429eb852011SMarkus Armbruster } 430eb852011SMarkus Armbruster 4315b7e1542SZhi Yong Wu typedef struct CreateCo { 4325b7e1542SZhi Yong Wu BlockDriver *drv; 4335b7e1542SZhi Yong Wu char *filename; 4345b7e1542SZhi Yong Wu QEMUOptionParameter *options; 435*83d0521aSChunyan Liu QemuOpts *opts; 4365b7e1542SZhi Yong Wu int ret; 437cc84d90fSMax Reitz Error *err; 4385b7e1542SZhi Yong Wu } CreateCo; 4395b7e1542SZhi Yong Wu 4405b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque) 4415b7e1542SZhi Yong Wu { 442cc84d90fSMax Reitz Error *local_err = NULL; 443cc84d90fSMax Reitz int ret; 444cc84d90fSMax Reitz 4455b7e1542SZhi Yong Wu CreateCo *cco = opaque; 4465b7e1542SZhi Yong Wu assert(cco->drv); 447*83d0521aSChunyan Liu assert(!(cco->options && cco->opts)); 4485b7e1542SZhi Yong Wu 449*83d0521aSChunyan Liu if (cco->drv->bdrv_create2) { 450*83d0521aSChunyan Liu QemuOptsList *opts_list = NULL; 451*83d0521aSChunyan Liu if (cco->options) { 452*83d0521aSChunyan Liu opts_list = params_to_opts(cco->options); 453*83d0521aSChunyan Liu cco->opts = qemu_opts_create(opts_list, NULL, 0, &error_abort); 454*83d0521aSChunyan Liu } 455*83d0521aSChunyan Liu ret = cco->drv->bdrv_create2(cco->filename, cco->opts, &local_err); 456*83d0521aSChunyan Liu if (cco->options) { 457*83d0521aSChunyan Liu qemu_opts_del(cco->opts); 458*83d0521aSChunyan Liu qemu_opts_free(opts_list); 459*83d0521aSChunyan Liu } 460*83d0521aSChunyan Liu } else { 461*83d0521aSChunyan Liu if (cco->opts) { 462*83d0521aSChunyan Liu cco->options = opts_to_params(cco->opts); 463*83d0521aSChunyan Liu } 464cc84d90fSMax Reitz ret = cco->drv->bdrv_create(cco->filename, cco->options, &local_err); 465*83d0521aSChunyan Liu if (cco->opts) { 466*83d0521aSChunyan Liu free_option_parameters(cco->options); 467*83d0521aSChunyan Liu } 468*83d0521aSChunyan Liu } 46984d18f06SMarkus Armbruster if (local_err) { 470cc84d90fSMax Reitz error_propagate(&cco->err, local_err); 471cc84d90fSMax Reitz } 472cc84d90fSMax Reitz cco->ret = ret; 4735b7e1542SZhi Yong Wu } 4745b7e1542SZhi Yong Wu 4750e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename, 476*83d0521aSChunyan Liu QEMUOptionParameter *options, 477*83d0521aSChunyan Liu QemuOpts *opts, Error **errp) 478ea2384d3Sbellard { 4795b7e1542SZhi Yong Wu int ret; 4800e7e1989SKevin Wolf 4815b7e1542SZhi Yong Wu Coroutine *co; 4825b7e1542SZhi Yong Wu CreateCo cco = { 4835b7e1542SZhi Yong Wu .drv = drv, 4845b7e1542SZhi Yong Wu .filename = g_strdup(filename), 4855b7e1542SZhi Yong Wu .options = options, 486*83d0521aSChunyan Liu .opts = opts, 4875b7e1542SZhi Yong Wu .ret = NOT_DONE, 488cc84d90fSMax Reitz .err = NULL, 4895b7e1542SZhi Yong Wu }; 4905b7e1542SZhi Yong Wu 491*83d0521aSChunyan Liu if (!drv->bdrv_create && !drv->bdrv_create2) { 492cc84d90fSMax Reitz error_setg(errp, "Driver '%s' does not support image creation", drv->format_name); 49380168bffSLuiz Capitulino ret = -ENOTSUP; 49480168bffSLuiz Capitulino goto out; 4955b7e1542SZhi Yong Wu } 4965b7e1542SZhi Yong Wu 4975b7e1542SZhi Yong Wu if (qemu_in_coroutine()) { 4985b7e1542SZhi Yong Wu /* Fast-path if already in coroutine context */ 4995b7e1542SZhi Yong Wu bdrv_create_co_entry(&cco); 5005b7e1542SZhi Yong Wu } else { 5015b7e1542SZhi Yong Wu co = qemu_coroutine_create(bdrv_create_co_entry); 5025b7e1542SZhi Yong Wu qemu_coroutine_enter(co, &cco); 5035b7e1542SZhi Yong Wu while (cco.ret == NOT_DONE) { 5045b7e1542SZhi Yong Wu qemu_aio_wait(); 5055b7e1542SZhi Yong Wu } 5065b7e1542SZhi Yong Wu } 5075b7e1542SZhi Yong Wu 5085b7e1542SZhi Yong Wu ret = cco.ret; 509cc84d90fSMax Reitz if (ret < 0) { 51084d18f06SMarkus Armbruster if (cco.err) { 511cc84d90fSMax Reitz error_propagate(errp, cco.err); 512cc84d90fSMax Reitz } else { 513cc84d90fSMax Reitz error_setg_errno(errp, -ret, "Could not create image"); 514cc84d90fSMax Reitz } 515cc84d90fSMax Reitz } 5165b7e1542SZhi Yong Wu 51780168bffSLuiz Capitulino out: 51880168bffSLuiz Capitulino g_free(cco.filename); 5195b7e1542SZhi Yong Wu return ret; 520ea2384d3Sbellard } 521ea2384d3Sbellard 522cc84d90fSMax Reitz int bdrv_create_file(const char* filename, QEMUOptionParameter *options, 523*83d0521aSChunyan Liu QemuOpts *opts, Error **errp) 52484a12e66SChristoph Hellwig { 52584a12e66SChristoph Hellwig BlockDriver *drv; 526cc84d90fSMax Reitz Error *local_err = NULL; 527cc84d90fSMax Reitz int ret; 52884a12e66SChristoph Hellwig 52998289620SKevin Wolf drv = bdrv_find_protocol(filename, true); 53084a12e66SChristoph Hellwig if (drv == NULL) { 531cc84d90fSMax Reitz error_setg(errp, "Could not find protocol for file '%s'", filename); 53216905d71SStefan Hajnoczi return -ENOENT; 53384a12e66SChristoph Hellwig } 53484a12e66SChristoph Hellwig 535*83d0521aSChunyan Liu ret = bdrv_create(drv, filename, options, opts, &local_err); 53684d18f06SMarkus Armbruster if (local_err) { 537cc84d90fSMax Reitz error_propagate(errp, local_err); 538cc84d90fSMax Reitz } 539cc84d90fSMax Reitz return ret; 54084a12e66SChristoph Hellwig } 54184a12e66SChristoph Hellwig 542355ef4acSKevin Wolf int bdrv_refresh_limits(BlockDriverState *bs) 543d34682cdSKevin Wolf { 544d34682cdSKevin Wolf BlockDriver *drv = bs->drv; 545d34682cdSKevin Wolf 546d34682cdSKevin Wolf memset(&bs->bl, 0, sizeof(bs->bl)); 547d34682cdSKevin Wolf 548466ad822SKevin Wolf if (!drv) { 549466ad822SKevin Wolf return 0; 550466ad822SKevin Wolf } 551466ad822SKevin Wolf 552466ad822SKevin Wolf /* Take some limits from the children as a default */ 553466ad822SKevin Wolf if (bs->file) { 554466ad822SKevin Wolf bdrv_refresh_limits(bs->file); 555466ad822SKevin Wolf bs->bl.opt_transfer_length = bs->file->bl.opt_transfer_length; 556339064d5SKevin Wolf bs->bl.opt_mem_alignment = bs->file->bl.opt_mem_alignment; 557339064d5SKevin Wolf } else { 558339064d5SKevin Wolf bs->bl.opt_mem_alignment = 512; 559466ad822SKevin Wolf } 560466ad822SKevin Wolf 561466ad822SKevin Wolf if (bs->backing_hd) { 562466ad822SKevin Wolf bdrv_refresh_limits(bs->backing_hd); 563466ad822SKevin Wolf bs->bl.opt_transfer_length = 564466ad822SKevin Wolf MAX(bs->bl.opt_transfer_length, 565466ad822SKevin Wolf bs->backing_hd->bl.opt_transfer_length); 566339064d5SKevin Wolf bs->bl.opt_mem_alignment = 567339064d5SKevin Wolf MAX(bs->bl.opt_mem_alignment, 568339064d5SKevin Wolf bs->backing_hd->bl.opt_mem_alignment); 569466ad822SKevin Wolf } 570466ad822SKevin Wolf 571466ad822SKevin Wolf /* Then let the driver override it */ 572466ad822SKevin Wolf if (drv->bdrv_refresh_limits) { 573d34682cdSKevin Wolf return drv->bdrv_refresh_limits(bs); 574d34682cdSKevin Wolf } 575d34682cdSKevin Wolf 576d34682cdSKevin Wolf return 0; 577d34682cdSKevin Wolf } 578d34682cdSKevin Wolf 579eba25057SJim Meyering /* 580eba25057SJim Meyering * Create a uniquely-named empty temporary file. 581eba25057SJim Meyering * Return 0 upon success, otherwise a negative errno value. 582eba25057SJim Meyering */ 583eba25057SJim Meyering int get_tmp_filename(char *filename, int size) 584eba25057SJim Meyering { 585d5249393Sbellard #ifdef _WIN32 5863b9f94e1Sbellard char temp_dir[MAX_PATH]; 587eba25057SJim Meyering /* GetTempFileName requires that its output buffer (4th param) 588eba25057SJim Meyering have length MAX_PATH or greater. */ 589eba25057SJim Meyering assert(size >= MAX_PATH); 590eba25057SJim Meyering return (GetTempPath(MAX_PATH, temp_dir) 591eba25057SJim Meyering && GetTempFileName(temp_dir, "qem", 0, filename) 592eba25057SJim Meyering ? 0 : -GetLastError()); 593d5249393Sbellard #else 594ea2384d3Sbellard int fd; 5957ccfb2ebSblueswir1 const char *tmpdir; 5960badc1eeSaurel32 tmpdir = getenv("TMPDIR"); 59769bef793SAmit Shah if (!tmpdir) { 59869bef793SAmit Shah tmpdir = "/var/tmp"; 59969bef793SAmit Shah } 600eba25057SJim Meyering if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) { 601eba25057SJim Meyering return -EOVERFLOW; 602ea2384d3Sbellard } 603eba25057SJim Meyering fd = mkstemp(filename); 604fe235a06SDunrong Huang if (fd < 0) { 605fe235a06SDunrong Huang return -errno; 606fe235a06SDunrong Huang } 607fe235a06SDunrong Huang if (close(fd) != 0) { 608fe235a06SDunrong Huang unlink(filename); 609eba25057SJim Meyering return -errno; 610eba25057SJim Meyering } 611eba25057SJim Meyering return 0; 612d5249393Sbellard #endif 613eba25057SJim Meyering } 614ea2384d3Sbellard 615f3a5d3f8SChristoph Hellwig /* 616f3a5d3f8SChristoph Hellwig * Detect host devices. By convention, /dev/cdrom[N] is always 617f3a5d3f8SChristoph Hellwig * recognized as a host CDROM. 618f3a5d3f8SChristoph Hellwig */ 619f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename) 620f3a5d3f8SChristoph Hellwig { 621508c7cb3SChristoph Hellwig int score_max = 0, score; 622508c7cb3SChristoph Hellwig BlockDriver *drv = NULL, *d; 623f3a5d3f8SChristoph Hellwig 6248a22f02aSStefan Hajnoczi QLIST_FOREACH(d, &bdrv_drivers, list) { 625508c7cb3SChristoph Hellwig if (d->bdrv_probe_device) { 626508c7cb3SChristoph Hellwig score = d->bdrv_probe_device(filename); 627508c7cb3SChristoph Hellwig if (score > score_max) { 628508c7cb3SChristoph Hellwig score_max = score; 629508c7cb3SChristoph Hellwig drv = d; 630f3a5d3f8SChristoph Hellwig } 631508c7cb3SChristoph Hellwig } 632f3a5d3f8SChristoph Hellwig } 633f3a5d3f8SChristoph Hellwig 634508c7cb3SChristoph Hellwig return drv; 635f3a5d3f8SChristoph Hellwig } 636f3a5d3f8SChristoph Hellwig 63798289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename, 63898289620SKevin Wolf bool allow_protocol_prefix) 63984a12e66SChristoph Hellwig { 64084a12e66SChristoph Hellwig BlockDriver *drv1; 64184a12e66SChristoph Hellwig char protocol[128]; 64284a12e66SChristoph Hellwig int len; 64384a12e66SChristoph Hellwig const char *p; 64484a12e66SChristoph Hellwig 64566f82ceeSKevin Wolf /* TODO Drivers without bdrv_file_open must be specified explicitly */ 64666f82ceeSKevin Wolf 64739508e7aSChristoph Hellwig /* 64839508e7aSChristoph Hellwig * XXX(hch): we really should not let host device detection 64939508e7aSChristoph Hellwig * override an explicit protocol specification, but moving this 65039508e7aSChristoph Hellwig * later breaks access to device names with colons in them. 65139508e7aSChristoph Hellwig * Thanks to the brain-dead persistent naming schemes on udev- 65239508e7aSChristoph Hellwig * based Linux systems those actually are quite common. 65339508e7aSChristoph Hellwig */ 65484a12e66SChristoph Hellwig drv1 = find_hdev_driver(filename); 65539508e7aSChristoph Hellwig if (drv1) { 65684a12e66SChristoph Hellwig return drv1; 65784a12e66SChristoph Hellwig } 65839508e7aSChristoph Hellwig 65998289620SKevin Wolf if (!path_has_protocol(filename) || !allow_protocol_prefix) { 66039508e7aSChristoph Hellwig return bdrv_find_format("file"); 66139508e7aSChristoph Hellwig } 66298289620SKevin Wolf 6639e0b22f4SStefan Hajnoczi p = strchr(filename, ':'); 6649e0b22f4SStefan Hajnoczi assert(p != NULL); 66584a12e66SChristoph Hellwig len = p - filename; 66684a12e66SChristoph Hellwig if (len > sizeof(protocol) - 1) 66784a12e66SChristoph Hellwig len = sizeof(protocol) - 1; 66884a12e66SChristoph Hellwig memcpy(protocol, filename, len); 66984a12e66SChristoph Hellwig protocol[len] = '\0'; 67084a12e66SChristoph Hellwig QLIST_FOREACH(drv1, &bdrv_drivers, list) { 67184a12e66SChristoph Hellwig if (drv1->protocol_name && 67284a12e66SChristoph Hellwig !strcmp(drv1->protocol_name, protocol)) { 67384a12e66SChristoph Hellwig return drv1; 67484a12e66SChristoph Hellwig } 67584a12e66SChristoph Hellwig } 67684a12e66SChristoph Hellwig return NULL; 67784a12e66SChristoph Hellwig } 67884a12e66SChristoph Hellwig 679f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename, 68034b5d2c6SMax Reitz BlockDriver **pdrv, Error **errp) 681ea2384d3Sbellard { 682f500a6d3SKevin Wolf int score, score_max; 683ea2384d3Sbellard BlockDriver *drv1, *drv; 68483f64091Sbellard uint8_t buf[2048]; 685f500a6d3SKevin Wolf int ret = 0; 686f8ea0b00SNicholas Bellinger 68708a00559SKevin Wolf /* Return the raw BlockDriver * to scsi-generic devices or empty drives */ 6888e895599SPaolo Bonzini if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) { 689c98ac35dSStefan Weil drv = bdrv_find_format("raw"); 690c98ac35dSStefan Weil if (!drv) { 69134b5d2c6SMax Reitz error_setg(errp, "Could not find raw image format"); 692c98ac35dSStefan Weil ret = -ENOENT; 693c98ac35dSStefan Weil } 694c98ac35dSStefan Weil *pdrv = drv; 695c98ac35dSStefan Weil return ret; 6961a396859SNicholas A. Bellinger } 697f8ea0b00SNicholas Bellinger 69883f64091Sbellard ret = bdrv_pread(bs, 0, buf, sizeof(buf)); 699ea2384d3Sbellard if (ret < 0) { 70034b5d2c6SMax Reitz error_setg_errno(errp, -ret, "Could not read image for determining its " 70134b5d2c6SMax Reitz "format"); 702c98ac35dSStefan Weil *pdrv = NULL; 703c98ac35dSStefan Weil return ret; 704ea2384d3Sbellard } 705ea2384d3Sbellard 706ea2384d3Sbellard score_max = 0; 70784a12e66SChristoph Hellwig drv = NULL; 7088a22f02aSStefan Hajnoczi QLIST_FOREACH(drv1, &bdrv_drivers, list) { 70983f64091Sbellard if (drv1->bdrv_probe) { 710ea2384d3Sbellard score = drv1->bdrv_probe(buf, ret, filename); 711ea2384d3Sbellard if (score > score_max) { 712ea2384d3Sbellard score_max = score; 713ea2384d3Sbellard drv = drv1; 714ea2384d3Sbellard } 715ea2384d3Sbellard } 71683f64091Sbellard } 717c98ac35dSStefan Weil if (!drv) { 71834b5d2c6SMax Reitz error_setg(errp, "Could not determine image format: No compatible " 71934b5d2c6SMax Reitz "driver found"); 720c98ac35dSStefan Weil ret = -ENOENT; 721c98ac35dSStefan Weil } 722c98ac35dSStefan Weil *pdrv = drv; 723c98ac35dSStefan Weil return ret; 724ea2384d3Sbellard } 725ea2384d3Sbellard 72651762288SStefan Hajnoczi /** 72751762288SStefan Hajnoczi * Set the current 'total_sectors' value 72851762288SStefan Hajnoczi */ 72951762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint) 73051762288SStefan Hajnoczi { 73151762288SStefan Hajnoczi BlockDriver *drv = bs->drv; 73251762288SStefan Hajnoczi 733396759adSNicholas Bellinger /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */ 734396759adSNicholas Bellinger if (bs->sg) 735396759adSNicholas Bellinger return 0; 736396759adSNicholas Bellinger 73751762288SStefan Hajnoczi /* query actual device if possible, otherwise just trust the hint */ 73851762288SStefan Hajnoczi if (drv->bdrv_getlength) { 73951762288SStefan Hajnoczi int64_t length = drv->bdrv_getlength(bs); 74051762288SStefan Hajnoczi if (length < 0) { 74151762288SStefan Hajnoczi return length; 74251762288SStefan Hajnoczi } 7437e382003SFam Zheng hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE); 74451762288SStefan Hajnoczi } 74551762288SStefan Hajnoczi 74651762288SStefan Hajnoczi bs->total_sectors = hint; 74751762288SStefan Hajnoczi return 0; 74851762288SStefan Hajnoczi } 74951762288SStefan Hajnoczi 750c3993cdcSStefan Hajnoczi /** 7519e8f1835SPaolo Bonzini * Set open flags for a given discard mode 7529e8f1835SPaolo Bonzini * 7539e8f1835SPaolo Bonzini * Return 0 on success, -1 if the discard mode was invalid. 7549e8f1835SPaolo Bonzini */ 7559e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags) 7569e8f1835SPaolo Bonzini { 7579e8f1835SPaolo Bonzini *flags &= ~BDRV_O_UNMAP; 7589e8f1835SPaolo Bonzini 7599e8f1835SPaolo Bonzini if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) { 7609e8f1835SPaolo Bonzini /* do nothing */ 7619e8f1835SPaolo Bonzini } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) { 7629e8f1835SPaolo Bonzini *flags |= BDRV_O_UNMAP; 7639e8f1835SPaolo Bonzini } else { 7649e8f1835SPaolo Bonzini return -1; 7659e8f1835SPaolo Bonzini } 7669e8f1835SPaolo Bonzini 7679e8f1835SPaolo Bonzini return 0; 7689e8f1835SPaolo Bonzini } 7699e8f1835SPaolo Bonzini 7709e8f1835SPaolo Bonzini /** 771c3993cdcSStefan Hajnoczi * Set open flags for a given cache mode 772c3993cdcSStefan Hajnoczi * 773c3993cdcSStefan Hajnoczi * Return 0 on success, -1 if the cache mode was invalid. 774c3993cdcSStefan Hajnoczi */ 775c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags) 776c3993cdcSStefan Hajnoczi { 777c3993cdcSStefan Hajnoczi *flags &= ~BDRV_O_CACHE_MASK; 778c3993cdcSStefan Hajnoczi 779c3993cdcSStefan Hajnoczi if (!strcmp(mode, "off") || !strcmp(mode, "none")) { 780c3993cdcSStefan Hajnoczi *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB; 78192196b2fSStefan Hajnoczi } else if (!strcmp(mode, "directsync")) { 78292196b2fSStefan Hajnoczi *flags |= BDRV_O_NOCACHE; 783c3993cdcSStefan Hajnoczi } else if (!strcmp(mode, "writeback")) { 784c3993cdcSStefan Hajnoczi *flags |= BDRV_O_CACHE_WB; 785c3993cdcSStefan Hajnoczi } else if (!strcmp(mode, "unsafe")) { 786c3993cdcSStefan Hajnoczi *flags |= BDRV_O_CACHE_WB; 787c3993cdcSStefan Hajnoczi *flags |= BDRV_O_NO_FLUSH; 788c3993cdcSStefan Hajnoczi } else if (!strcmp(mode, "writethrough")) { 789c3993cdcSStefan Hajnoczi /* this is the default */ 790c3993cdcSStefan Hajnoczi } else { 791c3993cdcSStefan Hajnoczi return -1; 792c3993cdcSStefan Hajnoczi } 793c3993cdcSStefan Hajnoczi 794c3993cdcSStefan Hajnoczi return 0; 795c3993cdcSStefan Hajnoczi } 796c3993cdcSStefan Hajnoczi 79753fec9d3SStefan Hajnoczi /** 79853fec9d3SStefan Hajnoczi * The copy-on-read flag is actually a reference count so multiple users may 79953fec9d3SStefan Hajnoczi * use the feature without worrying about clobbering its previous state. 80053fec9d3SStefan Hajnoczi * Copy-on-read stays enabled until all users have called to disable it. 80153fec9d3SStefan Hajnoczi */ 80253fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs) 80353fec9d3SStefan Hajnoczi { 80453fec9d3SStefan Hajnoczi bs->copy_on_read++; 80553fec9d3SStefan Hajnoczi } 80653fec9d3SStefan Hajnoczi 80753fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs) 80853fec9d3SStefan Hajnoczi { 80953fec9d3SStefan Hajnoczi assert(bs->copy_on_read > 0); 81053fec9d3SStefan Hajnoczi bs->copy_on_read--; 81153fec9d3SStefan Hajnoczi } 81253fec9d3SStefan Hajnoczi 8130b50cc88SKevin Wolf /* 814b1e6fc08SKevin Wolf * Returns the flags that a temporary snapshot should get, based on the 815b1e6fc08SKevin Wolf * originally requested flags (the originally requested image will have flags 816b1e6fc08SKevin Wolf * like a backing file) 817b1e6fc08SKevin Wolf */ 818b1e6fc08SKevin Wolf static int bdrv_temp_snapshot_flags(int flags) 819b1e6fc08SKevin Wolf { 820b1e6fc08SKevin Wolf return (flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY; 821b1e6fc08SKevin Wolf } 822b1e6fc08SKevin Wolf 823b1e6fc08SKevin Wolf /* 8240b50cc88SKevin Wolf * Returns the flags that bs->file should get, based on the given flags for 8250b50cc88SKevin Wolf * the parent BDS 8260b50cc88SKevin Wolf */ 8270b50cc88SKevin Wolf static int bdrv_inherited_flags(int flags) 8280b50cc88SKevin Wolf { 8290b50cc88SKevin Wolf /* Enable protocol handling, disable format probing for bs->file */ 8300b50cc88SKevin Wolf flags |= BDRV_O_PROTOCOL; 8310b50cc88SKevin Wolf 8320b50cc88SKevin Wolf /* Our block drivers take care to send flushes and respect unmap policy, 8330b50cc88SKevin Wolf * so we can enable both unconditionally on lower layers. */ 8340b50cc88SKevin Wolf flags |= BDRV_O_CACHE_WB | BDRV_O_UNMAP; 8350b50cc88SKevin Wolf 8360b50cc88SKevin Wolf /* Clear flags that only apply to the top layer */ 8375669b44dSKevin Wolf flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ); 8380b50cc88SKevin Wolf 8390b50cc88SKevin Wolf return flags; 8400b50cc88SKevin Wolf } 8410b50cc88SKevin Wolf 842317fc44eSKevin Wolf /* 843317fc44eSKevin Wolf * Returns the flags that bs->backing_hd should get, based on the given flags 844317fc44eSKevin Wolf * for the parent BDS 845317fc44eSKevin Wolf */ 846317fc44eSKevin Wolf static int bdrv_backing_flags(int flags) 847317fc44eSKevin Wolf { 848317fc44eSKevin Wolf /* backing files always opened read-only */ 849317fc44eSKevin Wolf flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ); 850317fc44eSKevin Wolf 851317fc44eSKevin Wolf /* snapshot=on is handled on the top layer */ 8528bfea15dSKevin Wolf flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY); 853317fc44eSKevin Wolf 854317fc44eSKevin Wolf return flags; 855317fc44eSKevin Wolf } 856317fc44eSKevin Wolf 8577b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags) 8587b272452SKevin Wolf { 8597b272452SKevin Wolf int open_flags = flags | BDRV_O_CACHE_WB; 8607b272452SKevin Wolf 8617b272452SKevin Wolf /* 8627b272452SKevin Wolf * Clear flags that are internal to the block layer before opening the 8637b272452SKevin Wolf * image. 8647b272452SKevin Wolf */ 8657b272452SKevin Wolf open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING); 8667b272452SKevin Wolf 8677b272452SKevin Wolf /* 8687b272452SKevin Wolf * Snapshots should be writable. 8697b272452SKevin Wolf */ 8708bfea15dSKevin Wolf if (flags & BDRV_O_TEMPORARY) { 8717b272452SKevin Wolf open_flags |= BDRV_O_RDWR; 8727b272452SKevin Wolf } 8737b272452SKevin Wolf 8747b272452SKevin Wolf return open_flags; 8757b272452SKevin Wolf } 8767b272452SKevin Wolf 877636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs, 8786913c0c2SBenoît Canet const char *node_name, 8796913c0c2SBenoît Canet Error **errp) 8806913c0c2SBenoît Canet { 8816913c0c2SBenoît Canet if (!node_name) { 882636ea370SKevin Wolf return; 8836913c0c2SBenoît Canet } 8846913c0c2SBenoît Canet 8856913c0c2SBenoît Canet /* empty string node name is invalid */ 8866913c0c2SBenoît Canet if (node_name[0] == '\0') { 8876913c0c2SBenoît Canet error_setg(errp, "Empty node name"); 888636ea370SKevin Wolf return; 8896913c0c2SBenoît Canet } 8906913c0c2SBenoît Canet 8910c5e94eeSBenoît Canet /* takes care of avoiding namespaces collisions */ 8920c5e94eeSBenoît Canet if (bdrv_find(node_name)) { 8930c5e94eeSBenoît Canet error_setg(errp, "node-name=%s is conflicting with a device id", 8940c5e94eeSBenoît Canet node_name); 895636ea370SKevin Wolf return; 8960c5e94eeSBenoît Canet } 8970c5e94eeSBenoît Canet 8986913c0c2SBenoît Canet /* takes care of avoiding duplicates node names */ 8996913c0c2SBenoît Canet if (bdrv_find_node(node_name)) { 9006913c0c2SBenoît Canet error_setg(errp, "Duplicate node name"); 901636ea370SKevin Wolf return; 9026913c0c2SBenoît Canet } 9036913c0c2SBenoît Canet 9046913c0c2SBenoît Canet /* copy node name into the bs and insert it into the graph list */ 9056913c0c2SBenoît Canet pstrcpy(bs->node_name, sizeof(bs->node_name), node_name); 9066913c0c2SBenoît Canet QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list); 9076913c0c2SBenoît Canet } 9086913c0c2SBenoît Canet 909b6ce07aaSKevin Wolf /* 91057915332SKevin Wolf * Common part for opening disk images and files 911b6ad491aSKevin Wolf * 912b6ad491aSKevin Wolf * Removes all processed options from *options. 91357915332SKevin Wolf */ 914f500a6d3SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file, 91534b5d2c6SMax Reitz QDict *options, int flags, BlockDriver *drv, Error **errp) 91657915332SKevin Wolf { 91757915332SKevin Wolf int ret, open_flags; 918035fccdfSKevin Wolf const char *filename; 9196913c0c2SBenoît Canet const char *node_name = NULL; 92034b5d2c6SMax Reitz Error *local_err = NULL; 92157915332SKevin Wolf 92257915332SKevin Wolf assert(drv != NULL); 9236405875cSPaolo Bonzini assert(bs->file == NULL); 924707ff828SKevin Wolf assert(options != NULL && bs->options != options); 92557915332SKevin Wolf 92645673671SKevin Wolf if (file != NULL) { 92745673671SKevin Wolf filename = file->filename; 92845673671SKevin Wolf } else { 92945673671SKevin Wolf filename = qdict_get_try_str(options, "filename"); 93045673671SKevin Wolf } 93145673671SKevin Wolf 932765003dbSKevin Wolf if (drv->bdrv_needs_filename && !filename) { 933765003dbSKevin Wolf error_setg(errp, "The '%s' block driver requires a file name", 934765003dbSKevin Wolf drv->format_name); 935765003dbSKevin Wolf return -EINVAL; 936765003dbSKevin Wolf } 937765003dbSKevin Wolf 93845673671SKevin Wolf trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name); 93928dcee10SStefan Hajnoczi 9406913c0c2SBenoît Canet node_name = qdict_get_try_str(options, "node-name"); 941636ea370SKevin Wolf bdrv_assign_node_name(bs, node_name, &local_err); 9420fb6395cSMarkus Armbruster if (local_err) { 943636ea370SKevin Wolf error_propagate(errp, local_err); 944636ea370SKevin Wolf return -EINVAL; 9456913c0c2SBenoît Canet } 9466913c0c2SBenoît Canet qdict_del(options, "node-name"); 9476913c0c2SBenoît Canet 9485d186eb0SKevin Wolf /* bdrv_open() with directly using a protocol as drv. This layer is already 9495d186eb0SKevin Wolf * opened, so assign it to bs (while file becomes a closed BlockDriverState) 9505d186eb0SKevin Wolf * and return immediately. */ 9515d186eb0SKevin Wolf if (file != NULL && drv->bdrv_file_open) { 9525d186eb0SKevin Wolf bdrv_swap(file, bs); 9535d186eb0SKevin Wolf return 0; 9545d186eb0SKevin Wolf } 9555d186eb0SKevin Wolf 95657915332SKevin Wolf bs->open_flags = flags; 9571b7fd729SPaolo Bonzini bs->guest_block_size = 512; 958c25f53b0SPaolo Bonzini bs->request_alignment = 512; 9590d51b4deSAsias He bs->zero_beyond_eof = true; 960b64ec4e4SFam Zheng open_flags = bdrv_open_flags(bs, flags); 961b64ec4e4SFam Zheng bs->read_only = !(open_flags & BDRV_O_RDWR); 962b64ec4e4SFam Zheng 963b64ec4e4SFam Zheng if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) { 9648f94a6e4SKevin Wolf error_setg(errp, 9658f94a6e4SKevin Wolf !bs->read_only && bdrv_is_whitelisted(drv, true) 9668f94a6e4SKevin Wolf ? "Driver '%s' can only be used for read-only devices" 9678f94a6e4SKevin Wolf : "Driver '%s' is not whitelisted", 9688f94a6e4SKevin Wolf drv->format_name); 969b64ec4e4SFam Zheng return -ENOTSUP; 970b64ec4e4SFam Zheng } 97157915332SKevin Wolf 97253fec9d3SStefan Hajnoczi assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */ 9730ebd24e0SKevin Wolf if (flags & BDRV_O_COPY_ON_READ) { 9740ebd24e0SKevin Wolf if (!bs->read_only) { 97553fec9d3SStefan Hajnoczi bdrv_enable_copy_on_read(bs); 9760ebd24e0SKevin Wolf } else { 9770ebd24e0SKevin Wolf error_setg(errp, "Can't use copy-on-read on read-only device"); 9780ebd24e0SKevin Wolf return -EINVAL; 9790ebd24e0SKevin Wolf } 98053fec9d3SStefan Hajnoczi } 98153fec9d3SStefan Hajnoczi 982c2ad1b0cSKevin Wolf if (filename != NULL) { 98357915332SKevin Wolf pstrcpy(bs->filename, sizeof(bs->filename), filename); 984c2ad1b0cSKevin Wolf } else { 985c2ad1b0cSKevin Wolf bs->filename[0] = '\0'; 986c2ad1b0cSKevin Wolf } 98757915332SKevin Wolf 98857915332SKevin Wolf bs->drv = drv; 9897267c094SAnthony Liguori bs->opaque = g_malloc0(drv->instance_size); 99057915332SKevin Wolf 99103f541bdSStefan Hajnoczi bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB); 992e7c63796SStefan Hajnoczi 99366f82ceeSKevin Wolf /* Open the image, either directly or using a protocol */ 99466f82ceeSKevin Wolf if (drv->bdrv_file_open) { 9955d186eb0SKevin Wolf assert(file == NULL); 996030be321SBenoît Canet assert(!drv->bdrv_needs_filename || filename != NULL); 99734b5d2c6SMax Reitz ret = drv->bdrv_file_open(bs, options, open_flags, &local_err); 998f500a6d3SKevin Wolf } else { 9992af5ef70SKevin Wolf if (file == NULL) { 100034b5d2c6SMax Reitz error_setg(errp, "Can't use '%s' as a block driver for the " 100134b5d2c6SMax Reitz "protocol level", drv->format_name); 10022af5ef70SKevin Wolf ret = -EINVAL; 10032af5ef70SKevin Wolf goto free_and_fail; 10042af5ef70SKevin Wolf } 1005f500a6d3SKevin Wolf bs->file = file; 100634b5d2c6SMax Reitz ret = drv->bdrv_open(bs, options, open_flags, &local_err); 100766f82ceeSKevin Wolf } 100866f82ceeSKevin Wolf 100957915332SKevin Wolf if (ret < 0) { 101084d18f06SMarkus Armbruster if (local_err) { 101134b5d2c6SMax Reitz error_propagate(errp, local_err); 10122fa9aa59SDunrong Huang } else if (bs->filename[0]) { 10132fa9aa59SDunrong Huang error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename); 101434b5d2c6SMax Reitz } else { 101534b5d2c6SMax Reitz error_setg_errno(errp, -ret, "Could not open image"); 101634b5d2c6SMax Reitz } 101757915332SKevin Wolf goto free_and_fail; 101857915332SKevin Wolf } 101957915332SKevin Wolf 102051762288SStefan Hajnoczi ret = refresh_total_sectors(bs, bs->total_sectors); 102151762288SStefan Hajnoczi if (ret < 0) { 102234b5d2c6SMax Reitz error_setg_errno(errp, -ret, "Could not refresh total sector count"); 102351762288SStefan Hajnoczi goto free_and_fail; 102457915332SKevin Wolf } 102551762288SStefan Hajnoczi 1026d34682cdSKevin Wolf bdrv_refresh_limits(bs); 1027c25f53b0SPaolo Bonzini assert(bdrv_opt_mem_align(bs) != 0); 102847ea2de2SKevin Wolf assert((bs->request_alignment != 0) || bs->sg); 102957915332SKevin Wolf return 0; 103057915332SKevin Wolf 103157915332SKevin Wolf free_and_fail: 103266f82ceeSKevin Wolf bs->file = NULL; 10337267c094SAnthony Liguori g_free(bs->opaque); 103457915332SKevin Wolf bs->opaque = NULL; 103557915332SKevin Wolf bs->drv = NULL; 103657915332SKevin Wolf return ret; 103757915332SKevin Wolf } 103857915332SKevin Wolf 103957915332SKevin Wolf /* 1040b6ce07aaSKevin Wolf * Opens a file using a protocol (file, host_device, nbd, ...) 1041787e4a85SKevin Wolf * 10425acd9d81SMax Reitz * options is an indirect pointer to a QDict of options to pass to the block 10435acd9d81SMax Reitz * drivers, or pointer to NULL for an empty set of options. If this function 10445acd9d81SMax Reitz * takes ownership of the QDict reference, it will set *options to NULL; 10455acd9d81SMax Reitz * otherwise, it will contain unused/unrecognized options after this function 10465acd9d81SMax Reitz * returns. Then, the caller is responsible for freeing it. If it intends to 10475acd9d81SMax Reitz * reuse the QDict, QINCREF() should be called beforehand. 1048b6ce07aaSKevin Wolf */ 1049d4446eaeSMax Reitz static int bdrv_file_open(BlockDriverState *bs, const char *filename, 10505acd9d81SMax Reitz QDict **options, int flags, Error **errp) 1051b338082bSbellard { 10526db95603SChristoph Hellwig BlockDriver *drv; 1053c2ad1b0cSKevin Wolf const char *drvname; 1054e3fa4bfaSKevin Wolf bool parse_filename = false; 105534b5d2c6SMax Reitz Error *local_err = NULL; 105683f64091Sbellard int ret; 10573b0d4f61Sbellard 1058035fccdfSKevin Wolf /* Fetch the file name from the options QDict if necessary */ 1059035fccdfSKevin Wolf if (!filename) { 10605acd9d81SMax Reitz filename = qdict_get_try_str(*options, "filename"); 10615acd9d81SMax Reitz } else if (filename && !qdict_haskey(*options, "filename")) { 10625acd9d81SMax Reitz qdict_put(*options, "filename", qstring_from_str(filename)); 1063e3fa4bfaSKevin Wolf parse_filename = true; 1064035fccdfSKevin Wolf } else { 106534b5d2c6SMax Reitz error_setg(errp, "Can't specify 'file' and 'filename' options at the " 106634b5d2c6SMax Reitz "same time"); 1067035fccdfSKevin Wolf ret = -EINVAL; 1068035fccdfSKevin Wolf goto fail; 1069035fccdfSKevin Wolf } 1070035fccdfSKevin Wolf 1071c2ad1b0cSKevin Wolf /* Find the right block driver */ 10725acd9d81SMax Reitz drvname = qdict_get_try_str(*options, "driver"); 1073c2ad1b0cSKevin Wolf if (drvname) { 10748f94a6e4SKevin Wolf drv = bdrv_find_format(drvname); 107534b5d2c6SMax Reitz if (!drv) { 107634b5d2c6SMax Reitz error_setg(errp, "Unknown driver '%s'", drvname); 107734b5d2c6SMax Reitz } 10785acd9d81SMax Reitz qdict_del(*options, "driver"); 1079c2ad1b0cSKevin Wolf } else if (filename) { 1080e3fa4bfaSKevin Wolf drv = bdrv_find_protocol(filename, parse_filename); 108198289620SKevin Wolf if (!drv) { 108234b5d2c6SMax Reitz error_setg(errp, "Unknown protocol"); 108398289620SKevin Wolf } 1084c2ad1b0cSKevin Wolf } else { 108534b5d2c6SMax Reitz error_setg(errp, "Must specify either driver or file"); 1086c2ad1b0cSKevin Wolf drv = NULL; 1087c2ad1b0cSKevin Wolf } 1088c2ad1b0cSKevin Wolf 1089c2ad1b0cSKevin Wolf if (!drv) { 109034b5d2c6SMax Reitz /* errp has been set already */ 1091c2ad1b0cSKevin Wolf ret = -ENOENT; 1092c2ad1b0cSKevin Wolf goto fail; 1093c2ad1b0cSKevin Wolf } 1094c2ad1b0cSKevin Wolf 1095c2ad1b0cSKevin Wolf /* Parse the filename and open it */ 1096e3fa4bfaSKevin Wolf if (drv->bdrv_parse_filename && parse_filename) { 10975acd9d81SMax Reitz drv->bdrv_parse_filename(filename, *options, &local_err); 109884d18f06SMarkus Armbruster if (local_err) { 109934b5d2c6SMax Reitz error_propagate(errp, local_err); 11006963a30dSKevin Wolf ret = -EINVAL; 11016963a30dSKevin Wolf goto fail; 11026963a30dSKevin Wolf } 1103cd5d031eSMax Reitz 1104cd5d031eSMax Reitz if (!drv->bdrv_needs_filename) { 11055acd9d81SMax Reitz qdict_del(*options, "filename"); 1106cd5d031eSMax Reitz } else { 1107cd5d031eSMax Reitz filename = qdict_get_str(*options, "filename"); 1108cd5d031eSMax Reitz } 11096963a30dSKevin Wolf } 11106963a30dSKevin Wolf 1111505d7583SMax Reitz if (!drv->bdrv_file_open) { 11125acd9d81SMax Reitz ret = bdrv_open(&bs, filename, NULL, *options, flags, drv, &local_err); 11135acd9d81SMax Reitz *options = NULL; 1114505d7583SMax Reitz } else { 11155acd9d81SMax Reitz ret = bdrv_open_common(bs, NULL, *options, flags, drv, &local_err); 1116505d7583SMax Reitz } 1117707ff828SKevin Wolf if (ret < 0) { 111834b5d2c6SMax Reitz error_propagate(errp, local_err); 1119707ff828SKevin Wolf goto fail; 1120707ff828SKevin Wolf } 1121707ff828SKevin Wolf 112271d0770cSaliguori bs->growable = 1; 112383f64091Sbellard return 0; 1124707ff828SKevin Wolf 1125707ff828SKevin Wolf fail: 1126707ff828SKevin Wolf return ret; 11273b0d4f61Sbellard } 11283b0d4f61Sbellard 11298d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd) 11308d24cce1SFam Zheng { 11318d24cce1SFam Zheng 1132826b6ca0SFam Zheng if (bs->backing_hd) { 1133826b6ca0SFam Zheng assert(bs->backing_blocker); 1134826b6ca0SFam Zheng bdrv_op_unblock_all(bs->backing_hd, bs->backing_blocker); 1135826b6ca0SFam Zheng } else if (backing_hd) { 1136826b6ca0SFam Zheng error_setg(&bs->backing_blocker, 1137826b6ca0SFam Zheng "device is used as backing hd of '%s'", 1138826b6ca0SFam Zheng bs->device_name); 1139826b6ca0SFam Zheng } 1140826b6ca0SFam Zheng 11418d24cce1SFam Zheng bs->backing_hd = backing_hd; 11428d24cce1SFam Zheng if (!backing_hd) { 1143826b6ca0SFam Zheng error_free(bs->backing_blocker); 1144826b6ca0SFam Zheng bs->backing_blocker = NULL; 11458d24cce1SFam Zheng goto out; 11468d24cce1SFam Zheng } 11478d24cce1SFam Zheng bs->open_flags &= ~BDRV_O_NO_BACKING; 11488d24cce1SFam Zheng pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename); 11498d24cce1SFam Zheng pstrcpy(bs->backing_format, sizeof(bs->backing_format), 11508d24cce1SFam Zheng backing_hd->drv ? backing_hd->drv->format_name : ""); 1151826b6ca0SFam Zheng 1152826b6ca0SFam Zheng bdrv_op_block_all(bs->backing_hd, bs->backing_blocker); 1153826b6ca0SFam Zheng /* Otherwise we won't be able to commit due to check in bdrv_commit */ 1154826b6ca0SFam Zheng bdrv_op_unblock(bs->backing_hd, BLOCK_OP_TYPE_COMMIT, 1155826b6ca0SFam Zheng bs->backing_blocker); 11568d24cce1SFam Zheng out: 11578d24cce1SFam Zheng bdrv_refresh_limits(bs); 11588d24cce1SFam Zheng } 11598d24cce1SFam Zheng 116031ca6d07SKevin Wolf /* 116131ca6d07SKevin Wolf * Opens the backing file for a BlockDriverState if not yet open 116231ca6d07SKevin Wolf * 116331ca6d07SKevin Wolf * options is a QDict of options to pass to the block drivers, or NULL for an 116431ca6d07SKevin Wolf * empty set of options. The reference to the QDict is transferred to this 116531ca6d07SKevin Wolf * function (even on failure), so if the caller intends to reuse the dictionary, 116631ca6d07SKevin Wolf * it needs to use QINCREF() before calling bdrv_file_open. 116731ca6d07SKevin Wolf */ 116834b5d2c6SMax Reitz int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp) 11699156df12SPaolo Bonzini { 11701ba4b6a5SBenoît Canet char *backing_filename = g_malloc0(PATH_MAX); 1171317fc44eSKevin Wolf int ret = 0; 11729156df12SPaolo Bonzini BlockDriver *back_drv = NULL; 11738d24cce1SFam Zheng BlockDriverState *backing_hd; 117434b5d2c6SMax Reitz Error *local_err = NULL; 11759156df12SPaolo Bonzini 11769156df12SPaolo Bonzini if (bs->backing_hd != NULL) { 117731ca6d07SKevin Wolf QDECREF(options); 11781ba4b6a5SBenoît Canet goto free_exit; 11799156df12SPaolo Bonzini } 11809156df12SPaolo Bonzini 118131ca6d07SKevin Wolf /* NULL means an empty set of options */ 118231ca6d07SKevin Wolf if (options == NULL) { 118331ca6d07SKevin Wolf options = qdict_new(); 118431ca6d07SKevin Wolf } 118531ca6d07SKevin Wolf 11869156df12SPaolo Bonzini bs->open_flags &= ~BDRV_O_NO_BACKING; 11871cb6f506SKevin Wolf if (qdict_haskey(options, "file.filename")) { 11881cb6f506SKevin Wolf backing_filename[0] = '\0'; 11891cb6f506SKevin Wolf } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) { 119031ca6d07SKevin Wolf QDECREF(options); 11911ba4b6a5SBenoît Canet goto free_exit; 1192dbecebddSFam Zheng } else { 11931ba4b6a5SBenoît Canet bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX); 11949156df12SPaolo Bonzini } 11959156df12SPaolo Bonzini 11968d24cce1SFam Zheng backing_hd = bdrv_new("", errp); 11978d24cce1SFam Zheng 11989156df12SPaolo Bonzini if (bs->backing_format[0] != '\0') { 11999156df12SPaolo Bonzini back_drv = bdrv_find_format(bs->backing_format); 12009156df12SPaolo Bonzini } 12019156df12SPaolo Bonzini 1202f67503e5SMax Reitz assert(bs->backing_hd == NULL); 12038d24cce1SFam Zheng ret = bdrv_open(&backing_hd, 1204ddf5636dSMax Reitz *backing_filename ? backing_filename : NULL, NULL, options, 1205317fc44eSKevin Wolf bdrv_backing_flags(bs->open_flags), back_drv, &local_err); 12069156df12SPaolo Bonzini if (ret < 0) { 12078d24cce1SFam Zheng bdrv_unref(backing_hd); 12088d24cce1SFam Zheng backing_hd = NULL; 12099156df12SPaolo Bonzini bs->open_flags |= BDRV_O_NO_BACKING; 1210b04b6b6eSFam Zheng error_setg(errp, "Could not open backing file: %s", 1211b04b6b6eSFam Zheng error_get_pretty(local_err)); 1212b04b6b6eSFam Zheng error_free(local_err); 12131ba4b6a5SBenoît Canet goto free_exit; 12149156df12SPaolo Bonzini } 12158d24cce1SFam Zheng bdrv_set_backing_hd(bs, backing_hd); 1216d80ac658SPeter Feiner 12171ba4b6a5SBenoît Canet free_exit: 12181ba4b6a5SBenoît Canet g_free(backing_filename); 12191ba4b6a5SBenoît Canet return ret; 12209156df12SPaolo Bonzini } 12219156df12SPaolo Bonzini 1222b6ce07aaSKevin Wolf /* 1223da557aacSMax Reitz * Opens a disk image whose options are given as BlockdevRef in another block 1224da557aacSMax Reitz * device's options. 1225da557aacSMax Reitz * 1226da557aacSMax Reitz * If allow_none is true, no image will be opened if filename is false and no 1227da557aacSMax Reitz * BlockdevRef is given. *pbs will remain unchanged and 0 will be returned. 1228da557aacSMax Reitz * 1229da557aacSMax Reitz * bdrev_key specifies the key for the image's BlockdevRef in the options QDict. 1230da557aacSMax Reitz * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict 1231da557aacSMax Reitz * itself, all options starting with "${bdref_key}." are considered part of the 1232da557aacSMax Reitz * BlockdevRef. 1233da557aacSMax Reitz * 1234da557aacSMax Reitz * The BlockdevRef will be removed from the options QDict. 1235f67503e5SMax Reitz * 1236f67503e5SMax Reitz * To conform with the behavior of bdrv_open(), *pbs has to be NULL. 1237da557aacSMax Reitz */ 1238da557aacSMax Reitz int bdrv_open_image(BlockDriverState **pbs, const char *filename, 1239da557aacSMax Reitz QDict *options, const char *bdref_key, int flags, 1240f7d9fd8cSMax Reitz bool allow_none, Error **errp) 1241da557aacSMax Reitz { 1242da557aacSMax Reitz QDict *image_options; 1243da557aacSMax Reitz int ret; 1244da557aacSMax Reitz char *bdref_key_dot; 1245da557aacSMax Reitz const char *reference; 1246da557aacSMax Reitz 1247f67503e5SMax Reitz assert(pbs); 1248f67503e5SMax Reitz assert(*pbs == NULL); 1249f67503e5SMax Reitz 1250da557aacSMax Reitz bdref_key_dot = g_strdup_printf("%s.", bdref_key); 1251da557aacSMax Reitz qdict_extract_subqdict(options, &image_options, bdref_key_dot); 1252da557aacSMax Reitz g_free(bdref_key_dot); 1253da557aacSMax Reitz 1254da557aacSMax Reitz reference = qdict_get_try_str(options, bdref_key); 1255da557aacSMax Reitz if (!filename && !reference && !qdict_size(image_options)) { 1256da557aacSMax Reitz if (allow_none) { 1257da557aacSMax Reitz ret = 0; 1258da557aacSMax Reitz } else { 1259da557aacSMax Reitz error_setg(errp, "A block device must be specified for \"%s\"", 1260da557aacSMax Reitz bdref_key); 1261da557aacSMax Reitz ret = -EINVAL; 1262da557aacSMax Reitz } 1263b20e61e0SMarkus Armbruster QDECREF(image_options); 1264da557aacSMax Reitz goto done; 1265da557aacSMax Reitz } 1266da557aacSMax Reitz 1267f7d9fd8cSMax Reitz ret = bdrv_open(pbs, filename, reference, image_options, flags, NULL, errp); 1268da557aacSMax Reitz 1269da557aacSMax Reitz done: 1270da557aacSMax Reitz qdict_del(options, bdref_key); 1271da557aacSMax Reitz return ret; 1272da557aacSMax Reitz } 1273da557aacSMax Reitz 1274b1e6fc08SKevin Wolf void bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp) 1275b998875dSKevin Wolf { 1276b998875dSKevin Wolf /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */ 12771ba4b6a5SBenoît Canet char *tmp_filename = g_malloc0(PATH_MAX + 1); 1278b998875dSKevin Wolf int64_t total_size; 1279b998875dSKevin Wolf BlockDriver *bdrv_qcow2; 1280*83d0521aSChunyan Liu QemuOptsList *create_opts = NULL; 1281*83d0521aSChunyan Liu QemuOpts *opts = NULL; 1282b998875dSKevin Wolf QDict *snapshot_options; 1283b998875dSKevin Wolf BlockDriverState *bs_snapshot; 1284b998875dSKevin Wolf Error *local_err; 1285b998875dSKevin Wolf int ret; 1286b998875dSKevin Wolf 1287b998875dSKevin Wolf /* if snapshot, we create a temporary backing file and open it 1288b998875dSKevin Wolf instead of opening 'filename' directly */ 1289b998875dSKevin Wolf 1290b998875dSKevin Wolf /* Get the required size from the image */ 1291f187743aSKevin Wolf total_size = bdrv_getlength(bs); 1292f187743aSKevin Wolf if (total_size < 0) { 1293f187743aSKevin Wolf error_setg_errno(errp, -total_size, "Could not get image size"); 12941ba4b6a5SBenoît Canet goto out; 1295f187743aSKevin Wolf } 1296f187743aSKevin Wolf total_size &= BDRV_SECTOR_MASK; 1297b998875dSKevin Wolf 1298b998875dSKevin Wolf /* Create the temporary image */ 12991ba4b6a5SBenoît Canet ret = get_tmp_filename(tmp_filename, PATH_MAX + 1); 1300b998875dSKevin Wolf if (ret < 0) { 1301b998875dSKevin Wolf error_setg_errno(errp, -ret, "Could not get temporary filename"); 13021ba4b6a5SBenoît Canet goto out; 1303b998875dSKevin Wolf } 1304b998875dSKevin Wolf 1305b998875dSKevin Wolf bdrv_qcow2 = bdrv_find_format("qcow2"); 1306b998875dSKevin Wolf 1307*83d0521aSChunyan Liu assert(!(bdrv_qcow2->create_options && bdrv_qcow2->create_opts)); 1308*83d0521aSChunyan Liu if (bdrv_qcow2->create_options) { 1309*83d0521aSChunyan Liu create_opts = params_to_opts(bdrv_qcow2->create_options); 1310*83d0521aSChunyan Liu } else { 1311*83d0521aSChunyan Liu create_opts = bdrv_qcow2->create_opts; 1312*83d0521aSChunyan Liu } 1313*83d0521aSChunyan Liu opts = qemu_opts_create(create_opts, NULL, 0, &error_abort); 1314*83d0521aSChunyan Liu qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size); 1315*83d0521aSChunyan Liu ret = bdrv_create(bdrv_qcow2, tmp_filename, NULL, opts, &local_err); 1316*83d0521aSChunyan Liu qemu_opts_del(opts); 1317*83d0521aSChunyan Liu if (bdrv_qcow2->create_options) { 1318*83d0521aSChunyan Liu qemu_opts_free(create_opts); 1319*83d0521aSChunyan Liu } 1320b998875dSKevin Wolf if (ret < 0) { 1321b998875dSKevin Wolf error_setg_errno(errp, -ret, "Could not create temporary overlay " 1322b998875dSKevin Wolf "'%s': %s", tmp_filename, 1323b998875dSKevin Wolf error_get_pretty(local_err)); 1324b998875dSKevin Wolf error_free(local_err); 13251ba4b6a5SBenoît Canet goto out; 1326b998875dSKevin Wolf } 1327b998875dSKevin Wolf 1328b998875dSKevin Wolf /* Prepare a new options QDict for the temporary file */ 1329b998875dSKevin Wolf snapshot_options = qdict_new(); 1330b998875dSKevin Wolf qdict_put(snapshot_options, "file.driver", 1331b998875dSKevin Wolf qstring_from_str("file")); 1332b998875dSKevin Wolf qdict_put(snapshot_options, "file.filename", 1333b998875dSKevin Wolf qstring_from_str(tmp_filename)); 1334b998875dSKevin Wolf 133598522f63SKevin Wolf bs_snapshot = bdrv_new("", &error_abort); 1336b998875dSKevin Wolf 1337b998875dSKevin Wolf ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options, 1338b1e6fc08SKevin Wolf flags, bdrv_qcow2, &local_err); 1339b998875dSKevin Wolf if (ret < 0) { 1340b998875dSKevin Wolf error_propagate(errp, local_err); 13411ba4b6a5SBenoît Canet goto out; 1342b998875dSKevin Wolf } 1343b998875dSKevin Wolf 1344b998875dSKevin Wolf bdrv_append(bs_snapshot, bs); 13451ba4b6a5SBenoît Canet 13461ba4b6a5SBenoît Canet out: 13471ba4b6a5SBenoît Canet g_free(tmp_filename); 1348b998875dSKevin Wolf } 1349b998875dSKevin Wolf 13504993f7eaSMax Reitz static QDict *parse_json_filename(const char *filename, Error **errp) 13514993f7eaSMax Reitz { 13524993f7eaSMax Reitz QObject *options_obj; 13534993f7eaSMax Reitz QDict *options; 13544993f7eaSMax Reitz int ret; 13554993f7eaSMax Reitz 13564993f7eaSMax Reitz ret = strstart(filename, "json:", &filename); 13574993f7eaSMax Reitz assert(ret); 13584993f7eaSMax Reitz 13594993f7eaSMax Reitz options_obj = qobject_from_json(filename); 13604993f7eaSMax Reitz if (!options_obj) { 13614993f7eaSMax Reitz error_setg(errp, "Could not parse the JSON options"); 13624993f7eaSMax Reitz return NULL; 13634993f7eaSMax Reitz } 13644993f7eaSMax Reitz 13654993f7eaSMax Reitz if (qobject_type(options_obj) != QTYPE_QDICT) { 13664993f7eaSMax Reitz qobject_decref(options_obj); 13674993f7eaSMax Reitz error_setg(errp, "Invalid JSON object given"); 13684993f7eaSMax Reitz return NULL; 13694993f7eaSMax Reitz } 13704993f7eaSMax Reitz 13714993f7eaSMax Reitz options = qobject_to_qdict(options_obj); 13724993f7eaSMax Reitz qdict_flatten(options); 13734993f7eaSMax Reitz 13744993f7eaSMax Reitz return options; 13754993f7eaSMax Reitz } 13764993f7eaSMax Reitz 1377da557aacSMax Reitz /* 1378b6ce07aaSKevin Wolf * Opens a disk image (raw, qcow2, vmdk, ...) 1379de9c0cecSKevin Wolf * 1380de9c0cecSKevin Wolf * options is a QDict of options to pass to the block drivers, or NULL for an 1381de9c0cecSKevin Wolf * empty set of options. The reference to the QDict belongs to the block layer 1382de9c0cecSKevin Wolf * after the call (even on failure), so if the caller intends to reuse the 1383de9c0cecSKevin Wolf * dictionary, it needs to use QINCREF() before calling bdrv_open. 1384f67503e5SMax Reitz * 1385f67503e5SMax Reitz * If *pbs is NULL, a new BDS will be created with a pointer to it stored there. 1386f67503e5SMax Reitz * If it is not NULL, the referenced BDS will be reused. 1387ddf5636dSMax Reitz * 1388ddf5636dSMax Reitz * The reference parameter may be used to specify an existing block device which 1389ddf5636dSMax Reitz * should be opened. If specified, neither options nor a filename may be given, 1390ddf5636dSMax Reitz * nor can an existing BDS be reused (that is, *pbs has to be NULL). 1391b6ce07aaSKevin Wolf */ 1392ddf5636dSMax Reitz int bdrv_open(BlockDriverState **pbs, const char *filename, 1393ddf5636dSMax Reitz const char *reference, QDict *options, int flags, 1394ddf5636dSMax Reitz BlockDriver *drv, Error **errp) 1395ea2384d3Sbellard { 1396b6ce07aaSKevin Wolf int ret; 1397f67503e5SMax Reitz BlockDriverState *file = NULL, *bs; 139874fe54f2SKevin Wolf const char *drvname; 139934b5d2c6SMax Reitz Error *local_err = NULL; 1400b1e6fc08SKevin Wolf int snapshot_flags = 0; 140133e3963eSbellard 1402f67503e5SMax Reitz assert(pbs); 1403f67503e5SMax Reitz 1404ddf5636dSMax Reitz if (reference) { 1405ddf5636dSMax Reitz bool options_non_empty = options ? qdict_size(options) : false; 1406ddf5636dSMax Reitz QDECREF(options); 1407ddf5636dSMax Reitz 1408ddf5636dSMax Reitz if (*pbs) { 1409ddf5636dSMax Reitz error_setg(errp, "Cannot reuse an existing BDS when referencing " 1410ddf5636dSMax Reitz "another block device"); 1411ddf5636dSMax Reitz return -EINVAL; 1412ddf5636dSMax Reitz } 1413ddf5636dSMax Reitz 1414ddf5636dSMax Reitz if (filename || options_non_empty) { 1415ddf5636dSMax Reitz error_setg(errp, "Cannot reference an existing block device with " 1416ddf5636dSMax Reitz "additional options or a new filename"); 1417ddf5636dSMax Reitz return -EINVAL; 1418ddf5636dSMax Reitz } 1419ddf5636dSMax Reitz 1420ddf5636dSMax Reitz bs = bdrv_lookup_bs(reference, reference, errp); 1421ddf5636dSMax Reitz if (!bs) { 1422ddf5636dSMax Reitz return -ENODEV; 1423ddf5636dSMax Reitz } 1424ddf5636dSMax Reitz bdrv_ref(bs); 1425ddf5636dSMax Reitz *pbs = bs; 1426ddf5636dSMax Reitz return 0; 1427ddf5636dSMax Reitz } 1428ddf5636dSMax Reitz 1429f67503e5SMax Reitz if (*pbs) { 1430f67503e5SMax Reitz bs = *pbs; 1431f67503e5SMax Reitz } else { 143298522f63SKevin Wolf bs = bdrv_new("", &error_abort); 1433f67503e5SMax Reitz } 1434f67503e5SMax Reitz 1435de9c0cecSKevin Wolf /* NULL means an empty set of options */ 1436de9c0cecSKevin Wolf if (options == NULL) { 1437de9c0cecSKevin Wolf options = qdict_new(); 1438de9c0cecSKevin Wolf } 1439de9c0cecSKevin Wolf 14404993f7eaSMax Reitz if (filename && g_str_has_prefix(filename, "json:")) { 14414993f7eaSMax Reitz QDict *json_options = parse_json_filename(filename, &local_err); 14424993f7eaSMax Reitz if (local_err) { 14434993f7eaSMax Reitz ret = -EINVAL; 14444993f7eaSMax Reitz goto fail; 14454993f7eaSMax Reitz } 14464993f7eaSMax Reitz 14474993f7eaSMax Reitz /* Options given in the filename have lower priority than options 14484993f7eaSMax Reitz * specified directly */ 14494993f7eaSMax Reitz qdict_join(options, json_options, false); 14504993f7eaSMax Reitz QDECREF(json_options); 14514993f7eaSMax Reitz filename = NULL; 14524993f7eaSMax Reitz } 14534993f7eaSMax Reitz 1454de9c0cecSKevin Wolf bs->options = options; 1455b6ad491aSKevin Wolf options = qdict_clone_shallow(options); 1456de9c0cecSKevin Wolf 14575469a2a6SMax Reitz if (flags & BDRV_O_PROTOCOL) { 14585469a2a6SMax Reitz assert(!drv); 14595acd9d81SMax Reitz ret = bdrv_file_open(bs, filename, &options, flags & ~BDRV_O_PROTOCOL, 14605469a2a6SMax Reitz &local_err); 14615469a2a6SMax Reitz if (!ret) { 1462eb909c7fSKevin Wolf drv = bs->drv; 14635acd9d81SMax Reitz goto done; 14645469a2a6SMax Reitz } else if (bs->drv) { 14655469a2a6SMax Reitz goto close_and_fail; 14665469a2a6SMax Reitz } else { 14675469a2a6SMax Reitz goto fail; 14685469a2a6SMax Reitz } 14695469a2a6SMax Reitz } 14705469a2a6SMax Reitz 1471f500a6d3SKevin Wolf /* Open image file without format layer */ 1472be028adcSJeff Cody if (flags & BDRV_O_RDWR) { 1473be028adcSJeff Cody flags |= BDRV_O_ALLOW_RDWR; 1474be028adcSJeff Cody } 1475b1e6fc08SKevin Wolf if (flags & BDRV_O_SNAPSHOT) { 1476b1e6fc08SKevin Wolf snapshot_flags = bdrv_temp_snapshot_flags(flags); 1477b1e6fc08SKevin Wolf flags = bdrv_backing_flags(flags); 1478b1e6fc08SKevin Wolf } 1479be028adcSJeff Cody 1480f67503e5SMax Reitz assert(file == NULL); 1481054963f8SMax Reitz ret = bdrv_open_image(&file, filename, options, "file", 14820b50cc88SKevin Wolf bdrv_inherited_flags(flags), 14830b50cc88SKevin Wolf true, &local_err); 1484f500a6d3SKevin Wolf if (ret < 0) { 14858bfea15dSKevin Wolf goto fail; 1486f500a6d3SKevin Wolf } 1487f500a6d3SKevin Wolf 1488f500a6d3SKevin Wolf /* Find the right image format driver */ 148974fe54f2SKevin Wolf drvname = qdict_get_try_str(options, "driver"); 149074fe54f2SKevin Wolf if (drvname) { 14918f94a6e4SKevin Wolf drv = bdrv_find_format(drvname); 149274fe54f2SKevin Wolf qdict_del(options, "driver"); 149306d22aa3SKevin Wolf if (!drv) { 149406d22aa3SKevin Wolf error_setg(errp, "Invalid driver: '%s'", drvname); 149506d22aa3SKevin Wolf ret = -EINVAL; 14968bfea15dSKevin Wolf goto fail; 149706d22aa3SKevin Wolf } 149874fe54f2SKevin Wolf } 149974fe54f2SKevin Wolf 1500f500a6d3SKevin Wolf if (!drv) { 15012a05cbe4SMax Reitz if (file) { 150234b5d2c6SMax Reitz ret = find_image_format(file, filename, &drv, &local_err); 15032a05cbe4SMax Reitz } else { 15042a05cbe4SMax Reitz error_setg(errp, "Must specify either driver or file"); 15052a05cbe4SMax Reitz ret = -EINVAL; 15068bfea15dSKevin Wolf goto fail; 15072a05cbe4SMax Reitz } 1508f500a6d3SKevin Wolf } 1509f500a6d3SKevin Wolf 1510f500a6d3SKevin Wolf if (!drv) { 15118bfea15dSKevin Wolf goto fail; 1512f500a6d3SKevin Wolf } 1513f500a6d3SKevin Wolf 1514b6ce07aaSKevin Wolf /* Open the image */ 151534b5d2c6SMax Reitz ret = bdrv_open_common(bs, file, options, flags, drv, &local_err); 1516b6ce07aaSKevin Wolf if (ret < 0) { 15178bfea15dSKevin Wolf goto fail; 15186987307cSChristoph Hellwig } 15196987307cSChristoph Hellwig 15202a05cbe4SMax Reitz if (file && (bs->file != file)) { 15214f6fd349SFam Zheng bdrv_unref(file); 1522f500a6d3SKevin Wolf file = NULL; 1523f500a6d3SKevin Wolf } 1524f500a6d3SKevin Wolf 1525b6ce07aaSKevin Wolf /* If there is a backing file, use it */ 15269156df12SPaolo Bonzini if ((flags & BDRV_O_NO_BACKING) == 0) { 152731ca6d07SKevin Wolf QDict *backing_options; 152831ca6d07SKevin Wolf 15295726d872SBenoît Canet qdict_extract_subqdict(options, &backing_options, "backing."); 153034b5d2c6SMax Reitz ret = bdrv_open_backing_file(bs, backing_options, &local_err); 1531b6ce07aaSKevin Wolf if (ret < 0) { 1532b6ad491aSKevin Wolf goto close_and_fail; 1533b6ce07aaSKevin Wolf } 1534b6ce07aaSKevin Wolf } 1535b6ce07aaSKevin Wolf 1536b998875dSKevin Wolf /* For snapshot=on, create a temporary qcow2 overlay. bs points to the 1537b998875dSKevin Wolf * temporary snapshot afterwards. */ 1538b1e6fc08SKevin Wolf if (snapshot_flags) { 1539b1e6fc08SKevin Wolf bdrv_append_temp_snapshot(bs, snapshot_flags, &local_err); 1540b998875dSKevin Wolf if (local_err) { 1541b998875dSKevin Wolf error_propagate(errp, local_err); 1542b998875dSKevin Wolf goto close_and_fail; 1543b998875dSKevin Wolf } 1544b998875dSKevin Wolf } 1545b998875dSKevin Wolf 1546b998875dSKevin Wolf 15475acd9d81SMax Reitz done: 1548b6ad491aSKevin Wolf /* Check if any unknown options were used */ 15495acd9d81SMax Reitz if (options && (qdict_size(options) != 0)) { 1550b6ad491aSKevin Wolf const QDictEntry *entry = qdict_first(options); 15515acd9d81SMax Reitz if (flags & BDRV_O_PROTOCOL) { 15525acd9d81SMax Reitz error_setg(errp, "Block protocol '%s' doesn't support the option " 15535acd9d81SMax Reitz "'%s'", drv->format_name, entry->key); 15545acd9d81SMax Reitz } else { 155534b5d2c6SMax Reitz error_setg(errp, "Block format '%s' used by device '%s' doesn't " 15565acd9d81SMax Reitz "support the option '%s'", drv->format_name, 15575acd9d81SMax Reitz bs->device_name, entry->key); 15585acd9d81SMax Reitz } 1559b6ad491aSKevin Wolf 1560b6ad491aSKevin Wolf ret = -EINVAL; 1561b6ad491aSKevin Wolf goto close_and_fail; 1562b6ad491aSKevin Wolf } 1563b6ad491aSKevin Wolf 1564b6ce07aaSKevin Wolf if (!bdrv_key_required(bs)) { 15657d4b4ba5SMarkus Armbruster bdrv_dev_change_media_cb(bs, true); 1566c3adb58fSMarkus Armbruster } else if (!runstate_check(RUN_STATE_PRELAUNCH) 1567c3adb58fSMarkus Armbruster && !runstate_check(RUN_STATE_INMIGRATE) 1568c3adb58fSMarkus Armbruster && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */ 1569c3adb58fSMarkus Armbruster error_setg(errp, 1570c3adb58fSMarkus Armbruster "Guest must be stopped for opening of encrypted image"); 1571c3adb58fSMarkus Armbruster ret = -EBUSY; 1572c3adb58fSMarkus Armbruster goto close_and_fail; 1573b6ce07aaSKevin Wolf } 1574b6ce07aaSKevin Wolf 1575c3adb58fSMarkus Armbruster QDECREF(options); 1576f67503e5SMax Reitz *pbs = bs; 1577b6ce07aaSKevin Wolf return 0; 1578b6ce07aaSKevin Wolf 15798bfea15dSKevin Wolf fail: 1580f500a6d3SKevin Wolf if (file != NULL) { 15814f6fd349SFam Zheng bdrv_unref(file); 1582f500a6d3SKevin Wolf } 1583de9c0cecSKevin Wolf QDECREF(bs->options); 1584b6ad491aSKevin Wolf QDECREF(options); 1585de9c0cecSKevin Wolf bs->options = NULL; 1586f67503e5SMax Reitz if (!*pbs) { 1587f67503e5SMax Reitz /* If *pbs is NULL, a new BDS has been created in this function and 1588f67503e5SMax Reitz needs to be freed now. Otherwise, it does not need to be closed, 1589f67503e5SMax Reitz since it has not really been opened yet. */ 1590f67503e5SMax Reitz bdrv_unref(bs); 1591f67503e5SMax Reitz } 159284d18f06SMarkus Armbruster if (local_err) { 159334b5d2c6SMax Reitz error_propagate(errp, local_err); 159434b5d2c6SMax Reitz } 1595b6ad491aSKevin Wolf return ret; 1596de9c0cecSKevin Wolf 1597b6ad491aSKevin Wolf close_and_fail: 1598f67503e5SMax Reitz /* See fail path, but now the BDS has to be always closed */ 1599f67503e5SMax Reitz if (*pbs) { 1600b6ad491aSKevin Wolf bdrv_close(bs); 1601f67503e5SMax Reitz } else { 1602f67503e5SMax Reitz bdrv_unref(bs); 1603f67503e5SMax Reitz } 1604b6ad491aSKevin Wolf QDECREF(options); 160584d18f06SMarkus Armbruster if (local_err) { 160634b5d2c6SMax Reitz error_propagate(errp, local_err); 160734b5d2c6SMax Reitz } 1608b6ce07aaSKevin Wolf return ret; 1609b6ce07aaSKevin Wolf } 1610b6ce07aaSKevin Wolf 1611e971aa12SJeff Cody typedef struct BlockReopenQueueEntry { 1612e971aa12SJeff Cody bool prepared; 1613e971aa12SJeff Cody BDRVReopenState state; 1614e971aa12SJeff Cody QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry; 1615e971aa12SJeff Cody } BlockReopenQueueEntry; 1616e971aa12SJeff Cody 1617e971aa12SJeff Cody /* 1618e971aa12SJeff Cody * Adds a BlockDriverState to a simple queue for an atomic, transactional 1619e971aa12SJeff Cody * reopen of multiple devices. 1620e971aa12SJeff Cody * 1621e971aa12SJeff Cody * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT 1622e971aa12SJeff Cody * already performed, or alternatively may be NULL a new BlockReopenQueue will 1623e971aa12SJeff Cody * be created and initialized. This newly created BlockReopenQueue should be 1624e971aa12SJeff Cody * passed back in for subsequent calls that are intended to be of the same 1625e971aa12SJeff Cody * atomic 'set'. 1626e971aa12SJeff Cody * 1627e971aa12SJeff Cody * bs is the BlockDriverState to add to the reopen queue. 1628e971aa12SJeff Cody * 1629e971aa12SJeff Cody * flags contains the open flags for the associated bs 1630e971aa12SJeff Cody * 1631e971aa12SJeff Cody * returns a pointer to bs_queue, which is either the newly allocated 1632e971aa12SJeff Cody * bs_queue, or the existing bs_queue being used. 1633e971aa12SJeff Cody * 1634e971aa12SJeff Cody */ 1635e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue, 1636e971aa12SJeff Cody BlockDriverState *bs, int flags) 1637e971aa12SJeff Cody { 1638e971aa12SJeff Cody assert(bs != NULL); 1639e971aa12SJeff Cody 1640e971aa12SJeff Cody BlockReopenQueueEntry *bs_entry; 1641e971aa12SJeff Cody if (bs_queue == NULL) { 1642e971aa12SJeff Cody bs_queue = g_new0(BlockReopenQueue, 1); 1643e971aa12SJeff Cody QSIMPLEQ_INIT(bs_queue); 1644e971aa12SJeff Cody } 1645e971aa12SJeff Cody 1646f1f25a2eSKevin Wolf /* bdrv_open() masks this flag out */ 1647f1f25a2eSKevin Wolf flags &= ~BDRV_O_PROTOCOL; 1648f1f25a2eSKevin Wolf 1649e971aa12SJeff Cody if (bs->file) { 1650f1f25a2eSKevin Wolf bdrv_reopen_queue(bs_queue, bs->file, bdrv_inherited_flags(flags)); 1651e971aa12SJeff Cody } 1652e971aa12SJeff Cody 1653e971aa12SJeff Cody bs_entry = g_new0(BlockReopenQueueEntry, 1); 1654e971aa12SJeff Cody QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry); 1655e971aa12SJeff Cody 1656e971aa12SJeff Cody bs_entry->state.bs = bs; 1657e971aa12SJeff Cody bs_entry->state.flags = flags; 1658e971aa12SJeff Cody 1659e971aa12SJeff Cody return bs_queue; 1660e971aa12SJeff Cody } 1661e971aa12SJeff Cody 1662e971aa12SJeff Cody /* 1663e971aa12SJeff Cody * Reopen multiple BlockDriverStates atomically & transactionally. 1664e971aa12SJeff Cody * 1665e971aa12SJeff Cody * The queue passed in (bs_queue) must have been built up previous 1666e971aa12SJeff Cody * via bdrv_reopen_queue(). 1667e971aa12SJeff Cody * 1668e971aa12SJeff Cody * Reopens all BDS specified in the queue, with the appropriate 1669e971aa12SJeff Cody * flags. All devices are prepared for reopen, and failure of any 1670e971aa12SJeff Cody * device will cause all device changes to be abandonded, and intermediate 1671e971aa12SJeff Cody * data cleaned up. 1672e971aa12SJeff Cody * 1673e971aa12SJeff Cody * If all devices prepare successfully, then the changes are committed 1674e971aa12SJeff Cody * to all devices. 1675e971aa12SJeff Cody * 1676e971aa12SJeff Cody */ 1677e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp) 1678e971aa12SJeff Cody { 1679e971aa12SJeff Cody int ret = -1; 1680e971aa12SJeff Cody BlockReopenQueueEntry *bs_entry, *next; 1681e971aa12SJeff Cody Error *local_err = NULL; 1682e971aa12SJeff Cody 1683e971aa12SJeff Cody assert(bs_queue != NULL); 1684e971aa12SJeff Cody 1685e971aa12SJeff Cody bdrv_drain_all(); 1686e971aa12SJeff Cody 1687e971aa12SJeff Cody QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) { 1688e971aa12SJeff Cody if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) { 1689e971aa12SJeff Cody error_propagate(errp, local_err); 1690e971aa12SJeff Cody goto cleanup; 1691e971aa12SJeff Cody } 1692e971aa12SJeff Cody bs_entry->prepared = true; 1693e971aa12SJeff Cody } 1694e971aa12SJeff Cody 1695e971aa12SJeff Cody /* If we reach this point, we have success and just need to apply the 1696e971aa12SJeff Cody * changes 1697e971aa12SJeff Cody */ 1698e971aa12SJeff Cody QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) { 1699e971aa12SJeff Cody bdrv_reopen_commit(&bs_entry->state); 1700e971aa12SJeff Cody } 1701e971aa12SJeff Cody 1702e971aa12SJeff Cody ret = 0; 1703e971aa12SJeff Cody 1704e971aa12SJeff Cody cleanup: 1705e971aa12SJeff Cody QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) { 1706e971aa12SJeff Cody if (ret && bs_entry->prepared) { 1707e971aa12SJeff Cody bdrv_reopen_abort(&bs_entry->state); 1708e971aa12SJeff Cody } 1709e971aa12SJeff Cody g_free(bs_entry); 1710e971aa12SJeff Cody } 1711e971aa12SJeff Cody g_free(bs_queue); 1712e971aa12SJeff Cody return ret; 1713e971aa12SJeff Cody } 1714e971aa12SJeff Cody 1715e971aa12SJeff Cody 1716e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */ 1717e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp) 1718e971aa12SJeff Cody { 1719e971aa12SJeff Cody int ret = -1; 1720e971aa12SJeff Cody Error *local_err = NULL; 1721e971aa12SJeff Cody BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags); 1722e971aa12SJeff Cody 1723e971aa12SJeff Cody ret = bdrv_reopen_multiple(queue, &local_err); 1724e971aa12SJeff Cody if (local_err != NULL) { 1725e971aa12SJeff Cody error_propagate(errp, local_err); 1726e971aa12SJeff Cody } 1727e971aa12SJeff Cody return ret; 1728e971aa12SJeff Cody } 1729e971aa12SJeff Cody 1730e971aa12SJeff Cody 1731e971aa12SJeff Cody /* 1732e971aa12SJeff Cody * Prepares a BlockDriverState for reopen. All changes are staged in the 1733e971aa12SJeff Cody * 'opaque' field of the BDRVReopenState, which is used and allocated by 1734e971aa12SJeff Cody * the block driver layer .bdrv_reopen_prepare() 1735e971aa12SJeff Cody * 1736e971aa12SJeff Cody * bs is the BlockDriverState to reopen 1737e971aa12SJeff Cody * flags are the new open flags 1738e971aa12SJeff Cody * queue is the reopen queue 1739e971aa12SJeff Cody * 1740e971aa12SJeff Cody * Returns 0 on success, non-zero on error. On error errp will be set 1741e971aa12SJeff Cody * as well. 1742e971aa12SJeff Cody * 1743e971aa12SJeff Cody * On failure, bdrv_reopen_abort() will be called to clean up any data. 1744e971aa12SJeff Cody * It is the responsibility of the caller to then call the abort() or 1745e971aa12SJeff Cody * commit() for any other BDS that have been left in a prepare() state 1746e971aa12SJeff Cody * 1747e971aa12SJeff Cody */ 1748e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue, 1749e971aa12SJeff Cody Error **errp) 1750e971aa12SJeff Cody { 1751e971aa12SJeff Cody int ret = -1; 1752e971aa12SJeff Cody Error *local_err = NULL; 1753e971aa12SJeff Cody BlockDriver *drv; 1754e971aa12SJeff Cody 1755e971aa12SJeff Cody assert(reopen_state != NULL); 1756e971aa12SJeff Cody assert(reopen_state->bs->drv != NULL); 1757e971aa12SJeff Cody drv = reopen_state->bs->drv; 1758e971aa12SJeff Cody 1759e971aa12SJeff Cody /* if we are to stay read-only, do not allow permission change 1760e971aa12SJeff Cody * to r/w */ 1761e971aa12SJeff Cody if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) && 1762e971aa12SJeff Cody reopen_state->flags & BDRV_O_RDWR) { 1763e971aa12SJeff Cody error_set(errp, QERR_DEVICE_IS_READ_ONLY, 1764e971aa12SJeff Cody reopen_state->bs->device_name); 1765e971aa12SJeff Cody goto error; 1766e971aa12SJeff Cody } 1767e971aa12SJeff Cody 1768e971aa12SJeff Cody 1769e971aa12SJeff Cody ret = bdrv_flush(reopen_state->bs); 1770e971aa12SJeff Cody if (ret) { 1771e971aa12SJeff Cody error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive", 1772e971aa12SJeff Cody strerror(-ret)); 1773e971aa12SJeff Cody goto error; 1774e971aa12SJeff Cody } 1775e971aa12SJeff Cody 1776e971aa12SJeff Cody if (drv->bdrv_reopen_prepare) { 1777e971aa12SJeff Cody ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err); 1778e971aa12SJeff Cody if (ret) { 1779e971aa12SJeff Cody if (local_err != NULL) { 1780e971aa12SJeff Cody error_propagate(errp, local_err); 1781e971aa12SJeff Cody } else { 1782d8b6895fSLuiz Capitulino error_setg(errp, "failed while preparing to reopen image '%s'", 1783e971aa12SJeff Cody reopen_state->bs->filename); 1784e971aa12SJeff Cody } 1785e971aa12SJeff Cody goto error; 1786e971aa12SJeff Cody } 1787e971aa12SJeff Cody } else { 1788e971aa12SJeff Cody /* It is currently mandatory to have a bdrv_reopen_prepare() 1789e971aa12SJeff Cody * handler for each supported drv. */ 1790e971aa12SJeff Cody error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED, 1791e971aa12SJeff Cody drv->format_name, reopen_state->bs->device_name, 1792e971aa12SJeff Cody "reopening of file"); 1793e971aa12SJeff Cody ret = -1; 1794e971aa12SJeff Cody goto error; 1795e971aa12SJeff Cody } 1796e971aa12SJeff Cody 1797e971aa12SJeff Cody ret = 0; 1798e971aa12SJeff Cody 1799e971aa12SJeff Cody error: 1800e971aa12SJeff Cody return ret; 1801e971aa12SJeff Cody } 1802e971aa12SJeff Cody 1803e971aa12SJeff Cody /* 1804e971aa12SJeff Cody * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and 1805e971aa12SJeff Cody * makes them final by swapping the staging BlockDriverState contents into 1806e971aa12SJeff Cody * the active BlockDriverState contents. 1807e971aa12SJeff Cody */ 1808e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state) 1809e971aa12SJeff Cody { 1810e971aa12SJeff Cody BlockDriver *drv; 1811e971aa12SJeff Cody 1812e971aa12SJeff Cody assert(reopen_state != NULL); 1813e971aa12SJeff Cody drv = reopen_state->bs->drv; 1814e971aa12SJeff Cody assert(drv != NULL); 1815e971aa12SJeff Cody 1816e971aa12SJeff Cody /* If there are any driver level actions to take */ 1817e971aa12SJeff Cody if (drv->bdrv_reopen_commit) { 1818e971aa12SJeff Cody drv->bdrv_reopen_commit(reopen_state); 1819e971aa12SJeff Cody } 1820e971aa12SJeff Cody 1821e971aa12SJeff Cody /* set BDS specific flags now */ 1822e971aa12SJeff Cody reopen_state->bs->open_flags = reopen_state->flags; 1823e971aa12SJeff Cody reopen_state->bs->enable_write_cache = !!(reopen_state->flags & 1824e971aa12SJeff Cody BDRV_O_CACHE_WB); 1825e971aa12SJeff Cody reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR); 1826355ef4acSKevin Wolf 1827355ef4acSKevin Wolf bdrv_refresh_limits(reopen_state->bs); 1828e971aa12SJeff Cody } 1829e971aa12SJeff Cody 1830e971aa12SJeff Cody /* 1831e971aa12SJeff Cody * Abort the reopen, and delete and free the staged changes in 1832e971aa12SJeff Cody * reopen_state 1833e971aa12SJeff Cody */ 1834e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state) 1835e971aa12SJeff Cody { 1836e971aa12SJeff Cody BlockDriver *drv; 1837e971aa12SJeff Cody 1838e971aa12SJeff Cody assert(reopen_state != NULL); 1839e971aa12SJeff Cody drv = reopen_state->bs->drv; 1840e971aa12SJeff Cody assert(drv != NULL); 1841e971aa12SJeff Cody 1842e971aa12SJeff Cody if (drv->bdrv_reopen_abort) { 1843e971aa12SJeff Cody drv->bdrv_reopen_abort(reopen_state); 1844e971aa12SJeff Cody } 1845e971aa12SJeff Cody } 1846e971aa12SJeff Cody 1847e971aa12SJeff Cody 1848fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs) 1849fc01f7e7Sbellard { 18503e914655SPaolo Bonzini if (bs->job) { 18513e914655SPaolo Bonzini block_job_cancel_sync(bs->job); 18523e914655SPaolo Bonzini } 185358fda173SStefan Hajnoczi bdrv_drain_all(); /* complete I/O */ 185458fda173SStefan Hajnoczi bdrv_flush(bs); 185558fda173SStefan Hajnoczi bdrv_drain_all(); /* in case flush left pending I/O */ 1856d7d512f6SPaolo Bonzini notifier_list_notify(&bs->close_notifiers, bs); 18577094f12fSKevin Wolf 18583cbc002cSPaolo Bonzini if (bs->drv) { 1859557df6acSStefan Hajnoczi if (bs->backing_hd) { 1860826b6ca0SFam Zheng BlockDriverState *backing_hd = bs->backing_hd; 1861826b6ca0SFam Zheng bdrv_set_backing_hd(bs, NULL); 1862826b6ca0SFam Zheng bdrv_unref(backing_hd); 1863557df6acSStefan Hajnoczi } 1864ea2384d3Sbellard bs->drv->bdrv_close(bs); 18657267c094SAnthony Liguori g_free(bs->opaque); 1866ea2384d3Sbellard bs->opaque = NULL; 1867ea2384d3Sbellard bs->drv = NULL; 186853fec9d3SStefan Hajnoczi bs->copy_on_read = 0; 1869a275fa42SPaolo Bonzini bs->backing_file[0] = '\0'; 1870a275fa42SPaolo Bonzini bs->backing_format[0] = '\0'; 18716405875cSPaolo Bonzini bs->total_sectors = 0; 18726405875cSPaolo Bonzini bs->encrypted = 0; 18736405875cSPaolo Bonzini bs->valid_key = 0; 18746405875cSPaolo Bonzini bs->sg = 0; 18756405875cSPaolo Bonzini bs->growable = 0; 18760d51b4deSAsias He bs->zero_beyond_eof = false; 1877de9c0cecSKevin Wolf QDECREF(bs->options); 1878de9c0cecSKevin Wolf bs->options = NULL; 1879b338082bSbellard 188066f82ceeSKevin Wolf if (bs->file != NULL) { 18814f6fd349SFam Zheng bdrv_unref(bs->file); 18820ac9377dSPaolo Bonzini bs->file = NULL; 188366f82ceeSKevin Wolf } 18849ca11154SPavel Hrdina } 188566f82ceeSKevin Wolf 18867d4b4ba5SMarkus Armbruster bdrv_dev_change_media_cb(bs, false); 188798f90dbaSZhi Yong Wu 188898f90dbaSZhi Yong Wu /*throttling disk I/O limits*/ 188998f90dbaSZhi Yong Wu if (bs->io_limits_enabled) { 189098f90dbaSZhi Yong Wu bdrv_io_limits_disable(bs); 189198f90dbaSZhi Yong Wu } 1892b338082bSbellard } 1893b338082bSbellard 18942bc93fedSMORITA Kazutaka void bdrv_close_all(void) 18952bc93fedSMORITA Kazutaka { 18962bc93fedSMORITA Kazutaka BlockDriverState *bs; 18972bc93fedSMORITA Kazutaka 1898dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 1899ed78cda3SStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 1900ed78cda3SStefan Hajnoczi 1901ed78cda3SStefan Hajnoczi aio_context_acquire(aio_context); 19022bc93fedSMORITA Kazutaka bdrv_close(bs); 1903ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 19042bc93fedSMORITA Kazutaka } 19052bc93fedSMORITA Kazutaka } 19062bc93fedSMORITA Kazutaka 190788266f5aSStefan Hajnoczi /* Check if any requests are in-flight (including throttled requests) */ 190888266f5aSStefan Hajnoczi static bool bdrv_requests_pending(BlockDriverState *bs) 190988266f5aSStefan Hajnoczi { 191088266f5aSStefan Hajnoczi if (!QLIST_EMPTY(&bs->tracked_requests)) { 191188266f5aSStefan Hajnoczi return true; 191288266f5aSStefan Hajnoczi } 1913cc0681c4SBenoît Canet if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) { 1914cc0681c4SBenoît Canet return true; 1915cc0681c4SBenoît Canet } 1916cc0681c4SBenoît Canet if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) { 191788266f5aSStefan Hajnoczi return true; 191888266f5aSStefan Hajnoczi } 191988266f5aSStefan Hajnoczi if (bs->file && bdrv_requests_pending(bs->file)) { 192088266f5aSStefan Hajnoczi return true; 192188266f5aSStefan Hajnoczi } 192288266f5aSStefan Hajnoczi if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) { 192388266f5aSStefan Hajnoczi return true; 192488266f5aSStefan Hajnoczi } 192588266f5aSStefan Hajnoczi return false; 192688266f5aSStefan Hajnoczi } 192788266f5aSStefan Hajnoczi 1928922453bcSStefan Hajnoczi /* 1929922453bcSStefan Hajnoczi * Wait for pending requests to complete across all BlockDriverStates 1930922453bcSStefan Hajnoczi * 1931922453bcSStefan Hajnoczi * This function does not flush data to disk, use bdrv_flush_all() for that 1932922453bcSStefan Hajnoczi * after calling this function. 19334c355d53SZhi Yong Wu * 19344c355d53SZhi Yong Wu * Note that completion of an asynchronous I/O operation can trigger any 19354c355d53SZhi Yong Wu * number of other I/O operations on other devices---for example a coroutine 19364c355d53SZhi Yong Wu * can be arbitrarily complex and a constant flow of I/O can come until the 19374c355d53SZhi Yong Wu * coroutine is complete. Because of this, it is not possible to have a 19384c355d53SZhi Yong Wu * function to drain a single device's I/O queue. 1939922453bcSStefan Hajnoczi */ 1940922453bcSStefan Hajnoczi void bdrv_drain_all(void) 1941922453bcSStefan Hajnoczi { 194288266f5aSStefan Hajnoczi /* Always run first iteration so any pending completion BHs run */ 194388266f5aSStefan Hajnoczi bool busy = true; 1944922453bcSStefan Hajnoczi BlockDriverState *bs; 1945922453bcSStefan Hajnoczi 194688266f5aSStefan Hajnoczi while (busy) { 19479b536adcSStefan Hajnoczi busy = false; 1948922453bcSStefan Hajnoczi 19499b536adcSStefan Hajnoczi QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 19509b536adcSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 19519b536adcSStefan Hajnoczi bool bs_busy; 19529b536adcSStefan Hajnoczi 19539b536adcSStefan Hajnoczi aio_context_acquire(aio_context); 19549b536adcSStefan Hajnoczi bdrv_start_throttled_reqs(bs); 19559b536adcSStefan Hajnoczi bs_busy = bdrv_requests_pending(bs); 19569b536adcSStefan Hajnoczi bs_busy |= aio_poll(aio_context, bs_busy); 19579b536adcSStefan Hajnoczi aio_context_release(aio_context); 19589b536adcSStefan Hajnoczi 19599b536adcSStefan Hajnoczi busy |= bs_busy; 19609b536adcSStefan Hajnoczi } 1961922453bcSStefan Hajnoczi } 1962922453bcSStefan Hajnoczi } 1963922453bcSStefan Hajnoczi 1964dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and 1965dc364f4cSBenoît Canet * graph_bdrv_state list. 1966d22b2f41SRyan Harper Also, NULL terminate the device_name to prevent double remove */ 1967d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs) 1968d22b2f41SRyan Harper { 1969d22b2f41SRyan Harper if (bs->device_name[0] != '\0') { 1970dc364f4cSBenoît Canet QTAILQ_REMOVE(&bdrv_states, bs, device_list); 1971d22b2f41SRyan Harper } 1972d22b2f41SRyan Harper bs->device_name[0] = '\0'; 1973dc364f4cSBenoît Canet if (bs->node_name[0] != '\0') { 1974dc364f4cSBenoît Canet QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list); 1975dc364f4cSBenoît Canet } 1976dc364f4cSBenoît Canet bs->node_name[0] = '\0'; 1977d22b2f41SRyan Harper } 1978d22b2f41SRyan Harper 1979e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs) 1980e023b2e2SPaolo Bonzini { 1981e023b2e2SPaolo Bonzini if (bs->drv && bs->drv->bdrv_rebind) { 1982e023b2e2SPaolo Bonzini bs->drv->bdrv_rebind(bs); 1983e023b2e2SPaolo Bonzini } 1984e023b2e2SPaolo Bonzini } 1985e023b2e2SPaolo Bonzini 19864ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest, 19874ddc07caSPaolo Bonzini BlockDriverState *bs_src) 19884ddc07caSPaolo Bonzini { 19894ddc07caSPaolo Bonzini /* move some fields that need to stay attached to the device */ 19904ddc07caSPaolo Bonzini 19914ddc07caSPaolo Bonzini /* dev info */ 19924ddc07caSPaolo Bonzini bs_dest->dev_ops = bs_src->dev_ops; 19934ddc07caSPaolo Bonzini bs_dest->dev_opaque = bs_src->dev_opaque; 19944ddc07caSPaolo Bonzini bs_dest->dev = bs_src->dev; 19951b7fd729SPaolo Bonzini bs_dest->guest_block_size = bs_src->guest_block_size; 19964ddc07caSPaolo Bonzini bs_dest->copy_on_read = bs_src->copy_on_read; 19974ddc07caSPaolo Bonzini 19984ddc07caSPaolo Bonzini bs_dest->enable_write_cache = bs_src->enable_write_cache; 19994ddc07caSPaolo Bonzini 2000cc0681c4SBenoît Canet /* i/o throttled req */ 2001cc0681c4SBenoît Canet memcpy(&bs_dest->throttle_state, 2002cc0681c4SBenoît Canet &bs_src->throttle_state, 2003cc0681c4SBenoît Canet sizeof(ThrottleState)); 2004cc0681c4SBenoît Canet bs_dest->throttled_reqs[0] = bs_src->throttled_reqs[0]; 2005cc0681c4SBenoît Canet bs_dest->throttled_reqs[1] = bs_src->throttled_reqs[1]; 20064ddc07caSPaolo Bonzini bs_dest->io_limits_enabled = bs_src->io_limits_enabled; 20074ddc07caSPaolo Bonzini 20084ddc07caSPaolo Bonzini /* r/w error */ 20094ddc07caSPaolo Bonzini bs_dest->on_read_error = bs_src->on_read_error; 20104ddc07caSPaolo Bonzini bs_dest->on_write_error = bs_src->on_write_error; 20114ddc07caSPaolo Bonzini 20124ddc07caSPaolo Bonzini /* i/o status */ 20134ddc07caSPaolo Bonzini bs_dest->iostatus_enabled = bs_src->iostatus_enabled; 20144ddc07caSPaolo Bonzini bs_dest->iostatus = bs_src->iostatus; 20154ddc07caSPaolo Bonzini 20164ddc07caSPaolo Bonzini /* dirty bitmap */ 2017e4654d2dSFam Zheng bs_dest->dirty_bitmaps = bs_src->dirty_bitmaps; 20184ddc07caSPaolo Bonzini 20199fcb0251SFam Zheng /* reference count */ 20209fcb0251SFam Zheng bs_dest->refcnt = bs_src->refcnt; 20219fcb0251SFam Zheng 20224ddc07caSPaolo Bonzini /* job */ 20234ddc07caSPaolo Bonzini bs_dest->job = bs_src->job; 20244ddc07caSPaolo Bonzini 20254ddc07caSPaolo Bonzini /* keep the same entry in bdrv_states */ 20264ddc07caSPaolo Bonzini pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name), 20274ddc07caSPaolo Bonzini bs_src->device_name); 2028dc364f4cSBenoît Canet bs_dest->device_list = bs_src->device_list; 2029fbe40ff7SFam Zheng memcpy(bs_dest->op_blockers, bs_src->op_blockers, 2030fbe40ff7SFam Zheng sizeof(bs_dest->op_blockers)); 20314ddc07caSPaolo Bonzini } 20324ddc07caSPaolo Bonzini 20334ddc07caSPaolo Bonzini /* 20344ddc07caSPaolo Bonzini * Swap bs contents for two image chains while they are live, 20354ddc07caSPaolo Bonzini * while keeping required fields on the BlockDriverState that is 20364ddc07caSPaolo Bonzini * actually attached to a device. 20374ddc07caSPaolo Bonzini * 20384ddc07caSPaolo Bonzini * This will modify the BlockDriverState fields, and swap contents 20394ddc07caSPaolo Bonzini * between bs_new and bs_old. Both bs_new and bs_old are modified. 20404ddc07caSPaolo Bonzini * 20414ddc07caSPaolo Bonzini * bs_new is required to be anonymous. 20424ddc07caSPaolo Bonzini * 20434ddc07caSPaolo Bonzini * This function does not create any image files. 20444ddc07caSPaolo Bonzini */ 20454ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old) 20464ddc07caSPaolo Bonzini { 20474ddc07caSPaolo Bonzini BlockDriverState tmp; 20484ddc07caSPaolo Bonzini 204990ce8a06SBenoît Canet /* The code needs to swap the node_name but simply swapping node_list won't 205090ce8a06SBenoît Canet * work so first remove the nodes from the graph list, do the swap then 205190ce8a06SBenoît Canet * insert them back if needed. 205290ce8a06SBenoît Canet */ 205390ce8a06SBenoît Canet if (bs_new->node_name[0] != '\0') { 205490ce8a06SBenoît Canet QTAILQ_REMOVE(&graph_bdrv_states, bs_new, node_list); 205590ce8a06SBenoît Canet } 205690ce8a06SBenoît Canet if (bs_old->node_name[0] != '\0') { 205790ce8a06SBenoît Canet QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list); 205890ce8a06SBenoît Canet } 205990ce8a06SBenoît Canet 20604ddc07caSPaolo Bonzini /* bs_new must be anonymous and shouldn't have anything fancy enabled */ 20614ddc07caSPaolo Bonzini assert(bs_new->device_name[0] == '\0'); 2062e4654d2dSFam Zheng assert(QLIST_EMPTY(&bs_new->dirty_bitmaps)); 20634ddc07caSPaolo Bonzini assert(bs_new->job == NULL); 20644ddc07caSPaolo Bonzini assert(bs_new->dev == NULL); 20654ddc07caSPaolo Bonzini assert(bs_new->io_limits_enabled == false); 2066cc0681c4SBenoît Canet assert(!throttle_have_timer(&bs_new->throttle_state)); 20674ddc07caSPaolo Bonzini 20684ddc07caSPaolo Bonzini tmp = *bs_new; 20694ddc07caSPaolo Bonzini *bs_new = *bs_old; 20704ddc07caSPaolo Bonzini *bs_old = tmp; 20714ddc07caSPaolo Bonzini 20724ddc07caSPaolo Bonzini /* there are some fields that should not be swapped, move them back */ 20734ddc07caSPaolo Bonzini bdrv_move_feature_fields(&tmp, bs_old); 20744ddc07caSPaolo Bonzini bdrv_move_feature_fields(bs_old, bs_new); 20754ddc07caSPaolo Bonzini bdrv_move_feature_fields(bs_new, &tmp); 20764ddc07caSPaolo Bonzini 20774ddc07caSPaolo Bonzini /* bs_new shouldn't be in bdrv_states even after the swap! */ 20784ddc07caSPaolo Bonzini assert(bs_new->device_name[0] == '\0'); 20794ddc07caSPaolo Bonzini 20804ddc07caSPaolo Bonzini /* Check a few fields that should remain attached to the device */ 20814ddc07caSPaolo Bonzini assert(bs_new->dev == NULL); 20824ddc07caSPaolo Bonzini assert(bs_new->job == NULL); 20834ddc07caSPaolo Bonzini assert(bs_new->io_limits_enabled == false); 2084cc0681c4SBenoît Canet assert(!throttle_have_timer(&bs_new->throttle_state)); 20854ddc07caSPaolo Bonzini 208690ce8a06SBenoît Canet /* insert the nodes back into the graph node list if needed */ 208790ce8a06SBenoît Canet if (bs_new->node_name[0] != '\0') { 208890ce8a06SBenoît Canet QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_new, node_list); 208990ce8a06SBenoît Canet } 209090ce8a06SBenoît Canet if (bs_old->node_name[0] != '\0') { 209190ce8a06SBenoît Canet QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_old, node_list); 209290ce8a06SBenoît Canet } 209390ce8a06SBenoît Canet 20944ddc07caSPaolo Bonzini bdrv_rebind(bs_new); 20954ddc07caSPaolo Bonzini bdrv_rebind(bs_old); 20964ddc07caSPaolo Bonzini } 20974ddc07caSPaolo Bonzini 20988802d1fdSJeff Cody /* 20998802d1fdSJeff Cody * Add new bs contents at the top of an image chain while the chain is 21008802d1fdSJeff Cody * live, while keeping required fields on the top layer. 21018802d1fdSJeff Cody * 21028802d1fdSJeff Cody * This will modify the BlockDriverState fields, and swap contents 21038802d1fdSJeff Cody * between bs_new and bs_top. Both bs_new and bs_top are modified. 21048802d1fdSJeff Cody * 2105f6801b83SJeff Cody * bs_new is required to be anonymous. 2106f6801b83SJeff Cody * 21078802d1fdSJeff Cody * This function does not create any image files. 21088802d1fdSJeff Cody */ 21098802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top) 21108802d1fdSJeff Cody { 21114ddc07caSPaolo Bonzini bdrv_swap(bs_new, bs_top); 21128802d1fdSJeff Cody 21138802d1fdSJeff Cody /* The contents of 'tmp' will become bs_top, as we are 21148802d1fdSJeff Cody * swapping bs_new and bs_top contents. */ 21158d24cce1SFam Zheng bdrv_set_backing_hd(bs_top, bs_new); 21168802d1fdSJeff Cody } 21178802d1fdSJeff Cody 21184f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs) 2119b338082bSbellard { 2120fa879d62SMarkus Armbruster assert(!bs->dev); 21213e914655SPaolo Bonzini assert(!bs->job); 21223718d8abSFam Zheng assert(bdrv_op_blocker_is_empty(bs)); 21234f6fd349SFam Zheng assert(!bs->refcnt); 2124e4654d2dSFam Zheng assert(QLIST_EMPTY(&bs->dirty_bitmaps)); 212518846deeSMarkus Armbruster 2126e1b5c52eSStefan Hajnoczi bdrv_close(bs); 2127e1b5c52eSStefan Hajnoczi 21281b7bdbc1SStefan Hajnoczi /* remove from list, if necessary */ 2129d22b2f41SRyan Harper bdrv_make_anon(bs); 213034c6f050Saurel32 21317267c094SAnthony Liguori g_free(bs); 2132fc01f7e7Sbellard } 2133fc01f7e7Sbellard 2134fa879d62SMarkus Armbruster int bdrv_attach_dev(BlockDriverState *bs, void *dev) 2135fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */ 213618846deeSMarkus Armbruster { 2137fa879d62SMarkus Armbruster if (bs->dev) { 213818846deeSMarkus Armbruster return -EBUSY; 213918846deeSMarkus Armbruster } 2140fa879d62SMarkus Armbruster bs->dev = dev; 214128a7282aSLuiz Capitulino bdrv_iostatus_reset(bs); 214218846deeSMarkus Armbruster return 0; 214318846deeSMarkus Armbruster } 214418846deeSMarkus Armbruster 2145fa879d62SMarkus Armbruster /* TODO qdevified devices don't use this, remove when devices are qdevified */ 2146fa879d62SMarkus Armbruster void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev) 214718846deeSMarkus Armbruster { 2148fa879d62SMarkus Armbruster if (bdrv_attach_dev(bs, dev) < 0) { 2149fa879d62SMarkus Armbruster abort(); 2150fa879d62SMarkus Armbruster } 2151fa879d62SMarkus Armbruster } 2152fa879d62SMarkus Armbruster 2153fa879d62SMarkus Armbruster void bdrv_detach_dev(BlockDriverState *bs, void *dev) 2154fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */ 2155fa879d62SMarkus Armbruster { 2156fa879d62SMarkus Armbruster assert(bs->dev == dev); 2157fa879d62SMarkus Armbruster bs->dev = NULL; 21580e49de52SMarkus Armbruster bs->dev_ops = NULL; 21590e49de52SMarkus Armbruster bs->dev_opaque = NULL; 21601b7fd729SPaolo Bonzini bs->guest_block_size = 512; 216118846deeSMarkus Armbruster } 216218846deeSMarkus Armbruster 2163fa879d62SMarkus Armbruster /* TODO change to return DeviceState * when all users are qdevified */ 2164fa879d62SMarkus Armbruster void *bdrv_get_attached_dev(BlockDriverState *bs) 216518846deeSMarkus Armbruster { 2166fa879d62SMarkus Armbruster return bs->dev; 216718846deeSMarkus Armbruster } 216818846deeSMarkus Armbruster 21690e49de52SMarkus Armbruster void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops, 21700e49de52SMarkus Armbruster void *opaque) 21710e49de52SMarkus Armbruster { 21720e49de52SMarkus Armbruster bs->dev_ops = ops; 21730e49de52SMarkus Armbruster bs->dev_opaque = opaque; 21740e49de52SMarkus Armbruster } 21750e49de52SMarkus Armbruster 217632c81a4aSPaolo Bonzini void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv, 217732c81a4aSPaolo Bonzini enum MonitorEvent ev, 21781ceee0d5SPaolo Bonzini BlockErrorAction action, bool is_read) 2179329c0a48SLuiz Capitulino { 2180329c0a48SLuiz Capitulino QObject *data; 2181329c0a48SLuiz Capitulino const char *action_str; 2182329c0a48SLuiz Capitulino 2183329c0a48SLuiz Capitulino switch (action) { 2184329c0a48SLuiz Capitulino case BDRV_ACTION_REPORT: 2185329c0a48SLuiz Capitulino action_str = "report"; 2186329c0a48SLuiz Capitulino break; 2187329c0a48SLuiz Capitulino case BDRV_ACTION_IGNORE: 2188329c0a48SLuiz Capitulino action_str = "ignore"; 2189329c0a48SLuiz Capitulino break; 2190329c0a48SLuiz Capitulino case BDRV_ACTION_STOP: 2191329c0a48SLuiz Capitulino action_str = "stop"; 2192329c0a48SLuiz Capitulino break; 2193329c0a48SLuiz Capitulino default: 2194329c0a48SLuiz Capitulino abort(); 2195329c0a48SLuiz Capitulino } 2196329c0a48SLuiz Capitulino 2197329c0a48SLuiz Capitulino data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }", 2198329c0a48SLuiz Capitulino bdrv->device_name, 2199329c0a48SLuiz Capitulino action_str, 2200329c0a48SLuiz Capitulino is_read ? "read" : "write"); 220132c81a4aSPaolo Bonzini monitor_protocol_event(ev, data); 2202329c0a48SLuiz Capitulino 2203329c0a48SLuiz Capitulino qobject_decref(data); 2204329c0a48SLuiz Capitulino } 2205329c0a48SLuiz Capitulino 22066f382ed2SLuiz Capitulino static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected) 22076f382ed2SLuiz Capitulino { 22086f382ed2SLuiz Capitulino QObject *data; 22096f382ed2SLuiz Capitulino 22106f382ed2SLuiz Capitulino data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }", 22116f382ed2SLuiz Capitulino bdrv_get_device_name(bs), ejected); 22126f382ed2SLuiz Capitulino monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data); 22136f382ed2SLuiz Capitulino 22146f382ed2SLuiz Capitulino qobject_decref(data); 22156f382ed2SLuiz Capitulino } 22166f382ed2SLuiz Capitulino 22177d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load) 22180e49de52SMarkus Armbruster { 2219145feb17SMarkus Armbruster if (bs->dev_ops && bs->dev_ops->change_media_cb) { 22206f382ed2SLuiz Capitulino bool tray_was_closed = !bdrv_dev_is_tray_open(bs); 22217d4b4ba5SMarkus Armbruster bs->dev_ops->change_media_cb(bs->dev_opaque, load); 22226f382ed2SLuiz Capitulino if (tray_was_closed) { 22236f382ed2SLuiz Capitulino /* tray open */ 22246f382ed2SLuiz Capitulino bdrv_emit_qmp_eject_event(bs, true); 22256f382ed2SLuiz Capitulino } 22266f382ed2SLuiz Capitulino if (load) { 22276f382ed2SLuiz Capitulino /* tray close */ 22286f382ed2SLuiz Capitulino bdrv_emit_qmp_eject_event(bs, false); 22296f382ed2SLuiz Capitulino } 2230145feb17SMarkus Armbruster } 2231145feb17SMarkus Armbruster } 2232145feb17SMarkus Armbruster 22332c6942faSMarkus Armbruster bool bdrv_dev_has_removable_media(BlockDriverState *bs) 22342c6942faSMarkus Armbruster { 22352c6942faSMarkus Armbruster return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb); 22362c6942faSMarkus Armbruster } 22372c6942faSMarkus Armbruster 2238025ccaa7SPaolo Bonzini void bdrv_dev_eject_request(BlockDriverState *bs, bool force) 2239025ccaa7SPaolo Bonzini { 2240025ccaa7SPaolo Bonzini if (bs->dev_ops && bs->dev_ops->eject_request_cb) { 2241025ccaa7SPaolo Bonzini bs->dev_ops->eject_request_cb(bs->dev_opaque, force); 2242025ccaa7SPaolo Bonzini } 2243025ccaa7SPaolo Bonzini } 2244025ccaa7SPaolo Bonzini 2245e4def80bSMarkus Armbruster bool bdrv_dev_is_tray_open(BlockDriverState *bs) 2246e4def80bSMarkus Armbruster { 2247e4def80bSMarkus Armbruster if (bs->dev_ops && bs->dev_ops->is_tray_open) { 2248e4def80bSMarkus Armbruster return bs->dev_ops->is_tray_open(bs->dev_opaque); 2249e4def80bSMarkus Armbruster } 2250e4def80bSMarkus Armbruster return false; 2251e4def80bSMarkus Armbruster } 2252e4def80bSMarkus Armbruster 2253145feb17SMarkus Armbruster static void bdrv_dev_resize_cb(BlockDriverState *bs) 2254145feb17SMarkus Armbruster { 2255145feb17SMarkus Armbruster if (bs->dev_ops && bs->dev_ops->resize_cb) { 2256145feb17SMarkus Armbruster bs->dev_ops->resize_cb(bs->dev_opaque); 22570e49de52SMarkus Armbruster } 22580e49de52SMarkus Armbruster } 22590e49de52SMarkus Armbruster 2260f107639aSMarkus Armbruster bool bdrv_dev_is_medium_locked(BlockDriverState *bs) 2261f107639aSMarkus Armbruster { 2262f107639aSMarkus Armbruster if (bs->dev_ops && bs->dev_ops->is_medium_locked) { 2263f107639aSMarkus Armbruster return bs->dev_ops->is_medium_locked(bs->dev_opaque); 2264f107639aSMarkus Armbruster } 2265f107639aSMarkus Armbruster return false; 2266f107639aSMarkus Armbruster } 2267f107639aSMarkus Armbruster 2268e97fc193Saliguori /* 2269e97fc193Saliguori * Run consistency checks on an image 2270e97fc193Saliguori * 2271e076f338SKevin Wolf * Returns 0 if the check could be completed (it doesn't mean that the image is 2272a1c7273bSStefan Weil * free of errors) or -errno when an internal error occurred. The results of the 2273e076f338SKevin Wolf * check are stored in res. 2274e97fc193Saliguori */ 22754534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix) 2276e97fc193Saliguori { 2277e97fc193Saliguori if (bs->drv->bdrv_check == NULL) { 2278e97fc193Saliguori return -ENOTSUP; 2279e97fc193Saliguori } 2280e97fc193Saliguori 2281e076f338SKevin Wolf memset(res, 0, sizeof(*res)); 22824534ff54SKevin Wolf return bs->drv->bdrv_check(bs, res, fix); 2283e97fc193Saliguori } 2284e97fc193Saliguori 22858a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048 22868a426614SKevin Wolf 228733e3963eSbellard /* commit COW file into the raw image */ 228833e3963eSbellard int bdrv_commit(BlockDriverState *bs) 228933e3963eSbellard { 229019cb3738Sbellard BlockDriver *drv = bs->drv; 229172706ea4SJeff Cody int64_t sector, total_sectors, length, backing_length; 22928a426614SKevin Wolf int n, ro, open_flags; 22930bce597dSJeff Cody int ret = 0; 229472706ea4SJeff Cody uint8_t *buf = NULL; 2295c2cba3d9SJim Meyering char filename[PATH_MAX]; 229633e3963eSbellard 229719cb3738Sbellard if (!drv) 229819cb3738Sbellard return -ENOMEDIUM; 229933e3963eSbellard 23004dca4b63SNaphtali Sprei if (!bs->backing_hd) { 23014dca4b63SNaphtali Sprei return -ENOTSUP; 23024dca4b63SNaphtali Sprei } 23034dca4b63SNaphtali Sprei 23043718d8abSFam Zheng if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, NULL) || 23053718d8abSFam Zheng bdrv_op_is_blocked(bs->backing_hd, BLOCK_OP_TYPE_COMMIT, NULL)) { 23062d3735d3SStefan Hajnoczi return -EBUSY; 23072d3735d3SStefan Hajnoczi } 23082d3735d3SStefan Hajnoczi 23094dca4b63SNaphtali Sprei ro = bs->backing_hd->read_only; 2310c2cba3d9SJim Meyering /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */ 2311c2cba3d9SJim Meyering pstrcpy(filename, sizeof(filename), bs->backing_hd->filename); 23124dca4b63SNaphtali Sprei open_flags = bs->backing_hd->open_flags; 23134dca4b63SNaphtali Sprei 23144dca4b63SNaphtali Sprei if (ro) { 23150bce597dSJeff Cody if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) { 23160bce597dSJeff Cody return -EACCES; 23174dca4b63SNaphtali Sprei } 2318ea2384d3Sbellard } 2319ea2384d3Sbellard 232072706ea4SJeff Cody length = bdrv_getlength(bs); 232172706ea4SJeff Cody if (length < 0) { 232272706ea4SJeff Cody ret = length; 232372706ea4SJeff Cody goto ro_cleanup; 232472706ea4SJeff Cody } 232572706ea4SJeff Cody 232672706ea4SJeff Cody backing_length = bdrv_getlength(bs->backing_hd); 232772706ea4SJeff Cody if (backing_length < 0) { 232872706ea4SJeff Cody ret = backing_length; 232972706ea4SJeff Cody goto ro_cleanup; 233072706ea4SJeff Cody } 233172706ea4SJeff Cody 233272706ea4SJeff Cody /* If our top snapshot is larger than the backing file image, 233372706ea4SJeff Cody * grow the backing file image if possible. If not possible, 233472706ea4SJeff Cody * we must return an error */ 233572706ea4SJeff Cody if (length > backing_length) { 233672706ea4SJeff Cody ret = bdrv_truncate(bs->backing_hd, length); 233772706ea4SJeff Cody if (ret < 0) { 233872706ea4SJeff Cody goto ro_cleanup; 233972706ea4SJeff Cody } 234072706ea4SJeff Cody } 234172706ea4SJeff Cody 234272706ea4SJeff Cody total_sectors = length >> BDRV_SECTOR_BITS; 23437267c094SAnthony Liguori buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE); 23448a426614SKevin Wolf 23458a426614SKevin Wolf for (sector = 0; sector < total_sectors; sector += n) { 2346d663640cSPaolo Bonzini ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n); 2347d663640cSPaolo Bonzini if (ret < 0) { 2348d663640cSPaolo Bonzini goto ro_cleanup; 2349d663640cSPaolo Bonzini } 2350d663640cSPaolo Bonzini if (ret) { 2351dabfa6ccSKevin Wolf ret = bdrv_read(bs, sector, buf, n); 2352dabfa6ccSKevin Wolf if (ret < 0) { 23534dca4b63SNaphtali Sprei goto ro_cleanup; 235433e3963eSbellard } 235533e3963eSbellard 2356dabfa6ccSKevin Wolf ret = bdrv_write(bs->backing_hd, sector, buf, n); 2357dabfa6ccSKevin Wolf if (ret < 0) { 23584dca4b63SNaphtali Sprei goto ro_cleanup; 235933e3963eSbellard } 236033e3963eSbellard } 236133e3963eSbellard } 236295389c86Sbellard 23631d44952fSChristoph Hellwig if (drv->bdrv_make_empty) { 23641d44952fSChristoph Hellwig ret = drv->bdrv_make_empty(bs); 2365dabfa6ccSKevin Wolf if (ret < 0) { 2366dabfa6ccSKevin Wolf goto ro_cleanup; 2367dabfa6ccSKevin Wolf } 23681d44952fSChristoph Hellwig bdrv_flush(bs); 23691d44952fSChristoph Hellwig } 237095389c86Sbellard 23713f5075aeSChristoph Hellwig /* 23723f5075aeSChristoph Hellwig * Make sure all data we wrote to the backing device is actually 23733f5075aeSChristoph Hellwig * stable on disk. 23743f5075aeSChristoph Hellwig */ 2375dabfa6ccSKevin Wolf if (bs->backing_hd) { 23763f5075aeSChristoph Hellwig bdrv_flush(bs->backing_hd); 2377dabfa6ccSKevin Wolf } 23784dca4b63SNaphtali Sprei 2379dabfa6ccSKevin Wolf ret = 0; 23804dca4b63SNaphtali Sprei ro_cleanup: 23817267c094SAnthony Liguori g_free(buf); 23824dca4b63SNaphtali Sprei 23834dca4b63SNaphtali Sprei if (ro) { 23840bce597dSJeff Cody /* ignoring error return here */ 23850bce597dSJeff Cody bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL); 23864dca4b63SNaphtali Sprei } 23874dca4b63SNaphtali Sprei 23881d44952fSChristoph Hellwig return ret; 238933e3963eSbellard } 239033e3963eSbellard 2391e8877497SStefan Hajnoczi int bdrv_commit_all(void) 23926ab4b5abSMarkus Armbruster { 23936ab4b5abSMarkus Armbruster BlockDriverState *bs; 23946ab4b5abSMarkus Armbruster 2395dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 2396ed78cda3SStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 2397ed78cda3SStefan Hajnoczi 2398ed78cda3SStefan Hajnoczi aio_context_acquire(aio_context); 2399272d2d8eSJeff Cody if (bs->drv && bs->backing_hd) { 2400e8877497SStefan Hajnoczi int ret = bdrv_commit(bs); 2401e8877497SStefan Hajnoczi if (ret < 0) { 2402ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 2403e8877497SStefan Hajnoczi return ret; 24046ab4b5abSMarkus Armbruster } 24056ab4b5abSMarkus Armbruster } 2406ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 2407272d2d8eSJeff Cody } 2408e8877497SStefan Hajnoczi return 0; 2409e8877497SStefan Hajnoczi } 24106ab4b5abSMarkus Armbruster 2411dbffbdcfSStefan Hajnoczi /** 2412dbffbdcfSStefan Hajnoczi * Remove an active request from the tracked requests list 2413dbffbdcfSStefan Hajnoczi * 2414dbffbdcfSStefan Hajnoczi * This function should be called when a tracked request is completing. 2415dbffbdcfSStefan Hajnoczi */ 2416dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req) 2417dbffbdcfSStefan Hajnoczi { 24182dbafdc0SKevin Wolf if (req->serialising) { 24192dbafdc0SKevin Wolf req->bs->serialising_in_flight--; 24202dbafdc0SKevin Wolf } 24212dbafdc0SKevin Wolf 2422dbffbdcfSStefan Hajnoczi QLIST_REMOVE(req, list); 2423f4658285SStefan Hajnoczi qemu_co_queue_restart_all(&req->wait_queue); 2424dbffbdcfSStefan Hajnoczi } 2425dbffbdcfSStefan Hajnoczi 2426dbffbdcfSStefan Hajnoczi /** 2427dbffbdcfSStefan Hajnoczi * Add an active request to the tracked requests list 2428dbffbdcfSStefan Hajnoczi */ 2429dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req, 2430dbffbdcfSStefan Hajnoczi BlockDriverState *bs, 2431793ed47aSKevin Wolf int64_t offset, 2432793ed47aSKevin Wolf unsigned int bytes, bool is_write) 2433dbffbdcfSStefan Hajnoczi { 2434dbffbdcfSStefan Hajnoczi *req = (BdrvTrackedRequest){ 2435dbffbdcfSStefan Hajnoczi .bs = bs, 2436793ed47aSKevin Wolf .offset = offset, 2437793ed47aSKevin Wolf .bytes = bytes, 2438dbffbdcfSStefan Hajnoczi .is_write = is_write, 24395f8b6491SStefan Hajnoczi .co = qemu_coroutine_self(), 24402dbafdc0SKevin Wolf .serialising = false, 24417327145fSKevin Wolf .overlap_offset = offset, 24427327145fSKevin Wolf .overlap_bytes = bytes, 2443dbffbdcfSStefan Hajnoczi }; 2444dbffbdcfSStefan Hajnoczi 2445f4658285SStefan Hajnoczi qemu_co_queue_init(&req->wait_queue); 2446f4658285SStefan Hajnoczi 2447dbffbdcfSStefan Hajnoczi QLIST_INSERT_HEAD(&bs->tracked_requests, req, list); 2448dbffbdcfSStefan Hajnoczi } 2449dbffbdcfSStefan Hajnoczi 2450e96126ffSKevin Wolf static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align) 24512dbafdc0SKevin Wolf { 24527327145fSKevin Wolf int64_t overlap_offset = req->offset & ~(align - 1); 2453e96126ffSKevin Wolf unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align) 24547327145fSKevin Wolf - overlap_offset; 24557327145fSKevin Wolf 24562dbafdc0SKevin Wolf if (!req->serialising) { 24572dbafdc0SKevin Wolf req->bs->serialising_in_flight++; 24582dbafdc0SKevin Wolf req->serialising = true; 24592dbafdc0SKevin Wolf } 24607327145fSKevin Wolf 24617327145fSKevin Wolf req->overlap_offset = MIN(req->overlap_offset, overlap_offset); 24627327145fSKevin Wolf req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes); 24632dbafdc0SKevin Wolf } 24642dbafdc0SKevin Wolf 2465d83947acSStefan Hajnoczi /** 2466d83947acSStefan Hajnoczi * Round a region to cluster boundaries 2467d83947acSStefan Hajnoczi */ 2468343bded4SPaolo Bonzini void bdrv_round_to_clusters(BlockDriverState *bs, 2469d83947acSStefan Hajnoczi int64_t sector_num, int nb_sectors, 2470d83947acSStefan Hajnoczi int64_t *cluster_sector_num, 2471d83947acSStefan Hajnoczi int *cluster_nb_sectors) 2472d83947acSStefan Hajnoczi { 2473d83947acSStefan Hajnoczi BlockDriverInfo bdi; 2474d83947acSStefan Hajnoczi 2475d83947acSStefan Hajnoczi if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) { 2476d83947acSStefan Hajnoczi *cluster_sector_num = sector_num; 2477d83947acSStefan Hajnoczi *cluster_nb_sectors = nb_sectors; 2478d83947acSStefan Hajnoczi } else { 2479d83947acSStefan Hajnoczi int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE; 2480d83947acSStefan Hajnoczi *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c); 2481d83947acSStefan Hajnoczi *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num + 2482d83947acSStefan Hajnoczi nb_sectors, c); 2483d83947acSStefan Hajnoczi } 2484d83947acSStefan Hajnoczi } 2485d83947acSStefan Hajnoczi 24867327145fSKevin Wolf static int bdrv_get_cluster_size(BlockDriverState *bs) 2487793ed47aSKevin Wolf { 2488793ed47aSKevin Wolf BlockDriverInfo bdi; 24897327145fSKevin Wolf int ret; 2490793ed47aSKevin Wolf 24917327145fSKevin Wolf ret = bdrv_get_info(bs, &bdi); 24927327145fSKevin Wolf if (ret < 0 || bdi.cluster_size == 0) { 24937327145fSKevin Wolf return bs->request_alignment; 2494793ed47aSKevin Wolf } else { 24957327145fSKevin Wolf return bdi.cluster_size; 2496793ed47aSKevin Wolf } 2497793ed47aSKevin Wolf } 2498793ed47aSKevin Wolf 2499f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req, 2500793ed47aSKevin Wolf int64_t offset, unsigned int bytes) 2501793ed47aSKevin Wolf { 2502d83947acSStefan Hajnoczi /* aaaa bbbb */ 25037327145fSKevin Wolf if (offset >= req->overlap_offset + req->overlap_bytes) { 2504d83947acSStefan Hajnoczi return false; 2505d83947acSStefan Hajnoczi } 2506d83947acSStefan Hajnoczi /* bbbb aaaa */ 25077327145fSKevin Wolf if (req->overlap_offset >= offset + bytes) { 2508d83947acSStefan Hajnoczi return false; 2509d83947acSStefan Hajnoczi } 2510d83947acSStefan Hajnoczi return true; 2511f4658285SStefan Hajnoczi } 2512f4658285SStefan Hajnoczi 251328de2dcdSKevin Wolf static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self) 2514f4658285SStefan Hajnoczi { 25152dbafdc0SKevin Wolf BlockDriverState *bs = self->bs; 2516f4658285SStefan Hajnoczi BdrvTrackedRequest *req; 2517f4658285SStefan Hajnoczi bool retry; 251828de2dcdSKevin Wolf bool waited = false; 2519f4658285SStefan Hajnoczi 25202dbafdc0SKevin Wolf if (!bs->serialising_in_flight) { 252128de2dcdSKevin Wolf return false; 25222dbafdc0SKevin Wolf } 25232dbafdc0SKevin Wolf 2524f4658285SStefan Hajnoczi do { 2525f4658285SStefan Hajnoczi retry = false; 2526f4658285SStefan Hajnoczi QLIST_FOREACH(req, &bs->tracked_requests, list) { 25272dbafdc0SKevin Wolf if (req == self || (!req->serialising && !self->serialising)) { 252865afd211SKevin Wolf continue; 252965afd211SKevin Wolf } 25307327145fSKevin Wolf if (tracked_request_overlaps(req, self->overlap_offset, 25317327145fSKevin Wolf self->overlap_bytes)) 25327327145fSKevin Wolf { 25335f8b6491SStefan Hajnoczi /* Hitting this means there was a reentrant request, for 25345f8b6491SStefan Hajnoczi * example, a block driver issuing nested requests. This must 25355f8b6491SStefan Hajnoczi * never happen since it means deadlock. 25365f8b6491SStefan Hajnoczi */ 25375f8b6491SStefan Hajnoczi assert(qemu_coroutine_self() != req->co); 25385f8b6491SStefan Hajnoczi 25396460440fSKevin Wolf /* If the request is already (indirectly) waiting for us, or 25406460440fSKevin Wolf * will wait for us as soon as it wakes up, then just go on 25416460440fSKevin Wolf * (instead of producing a deadlock in the former case). */ 25426460440fSKevin Wolf if (!req->waiting_for) { 25436460440fSKevin Wolf self->waiting_for = req; 2544f4658285SStefan Hajnoczi qemu_co_queue_wait(&req->wait_queue); 25456460440fSKevin Wolf self->waiting_for = NULL; 2546f4658285SStefan Hajnoczi retry = true; 254728de2dcdSKevin Wolf waited = true; 2548f4658285SStefan Hajnoczi break; 2549f4658285SStefan Hajnoczi } 2550f4658285SStefan Hajnoczi } 25516460440fSKevin Wolf } 2552f4658285SStefan Hajnoczi } while (retry); 255328de2dcdSKevin Wolf 255428de2dcdSKevin Wolf return waited; 2555f4658285SStefan Hajnoczi } 2556f4658285SStefan Hajnoczi 2557756e6736SKevin Wolf /* 2558756e6736SKevin Wolf * Return values: 2559756e6736SKevin Wolf * 0 - success 2560756e6736SKevin Wolf * -EINVAL - backing format specified, but no file 2561756e6736SKevin Wolf * -ENOSPC - can't update the backing file because no space is left in the 2562756e6736SKevin Wolf * image file header 2563756e6736SKevin Wolf * -ENOTSUP - format driver doesn't support changing the backing file 2564756e6736SKevin Wolf */ 2565756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs, 2566756e6736SKevin Wolf const char *backing_file, const char *backing_fmt) 2567756e6736SKevin Wolf { 2568756e6736SKevin Wolf BlockDriver *drv = bs->drv; 2569469ef350SPaolo Bonzini int ret; 2570756e6736SKevin Wolf 25715f377794SPaolo Bonzini /* Backing file format doesn't make sense without a backing file */ 25725f377794SPaolo Bonzini if (backing_fmt && !backing_file) { 25735f377794SPaolo Bonzini return -EINVAL; 25745f377794SPaolo Bonzini } 25755f377794SPaolo Bonzini 2576756e6736SKevin Wolf if (drv->bdrv_change_backing_file != NULL) { 2577469ef350SPaolo Bonzini ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt); 2578756e6736SKevin Wolf } else { 2579469ef350SPaolo Bonzini ret = -ENOTSUP; 2580756e6736SKevin Wolf } 2581469ef350SPaolo Bonzini 2582469ef350SPaolo Bonzini if (ret == 0) { 2583469ef350SPaolo Bonzini pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: ""); 2584469ef350SPaolo Bonzini pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: ""); 2585469ef350SPaolo Bonzini } 2586469ef350SPaolo Bonzini return ret; 2587756e6736SKevin Wolf } 2588756e6736SKevin Wolf 25896ebdcee2SJeff Cody /* 25906ebdcee2SJeff Cody * Finds the image layer in the chain that has 'bs' as its backing file. 25916ebdcee2SJeff Cody * 25926ebdcee2SJeff Cody * active is the current topmost image. 25936ebdcee2SJeff Cody * 25946ebdcee2SJeff Cody * Returns NULL if bs is not found in active's image chain, 25956ebdcee2SJeff Cody * or if active == bs. 25966ebdcee2SJeff Cody */ 25976ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active, 25986ebdcee2SJeff Cody BlockDriverState *bs) 25996ebdcee2SJeff Cody { 26006ebdcee2SJeff Cody BlockDriverState *overlay = NULL; 26016ebdcee2SJeff Cody BlockDriverState *intermediate; 26026ebdcee2SJeff Cody 26036ebdcee2SJeff Cody assert(active != NULL); 26046ebdcee2SJeff Cody assert(bs != NULL); 26056ebdcee2SJeff Cody 26066ebdcee2SJeff Cody /* if bs is the same as active, then by definition it has no overlay 26076ebdcee2SJeff Cody */ 26086ebdcee2SJeff Cody if (active == bs) { 26096ebdcee2SJeff Cody return NULL; 26106ebdcee2SJeff Cody } 26116ebdcee2SJeff Cody 26126ebdcee2SJeff Cody intermediate = active; 26136ebdcee2SJeff Cody while (intermediate->backing_hd) { 26146ebdcee2SJeff Cody if (intermediate->backing_hd == bs) { 26156ebdcee2SJeff Cody overlay = intermediate; 26166ebdcee2SJeff Cody break; 26176ebdcee2SJeff Cody } 26186ebdcee2SJeff Cody intermediate = intermediate->backing_hd; 26196ebdcee2SJeff Cody } 26206ebdcee2SJeff Cody 26216ebdcee2SJeff Cody return overlay; 26226ebdcee2SJeff Cody } 26236ebdcee2SJeff Cody 26246ebdcee2SJeff Cody typedef struct BlkIntermediateStates { 26256ebdcee2SJeff Cody BlockDriverState *bs; 26266ebdcee2SJeff Cody QSIMPLEQ_ENTRY(BlkIntermediateStates) entry; 26276ebdcee2SJeff Cody } BlkIntermediateStates; 26286ebdcee2SJeff Cody 26296ebdcee2SJeff Cody 26306ebdcee2SJeff Cody /* 26316ebdcee2SJeff Cody * Drops images above 'base' up to and including 'top', and sets the image 26326ebdcee2SJeff Cody * above 'top' to have base as its backing file. 26336ebdcee2SJeff Cody * 26346ebdcee2SJeff Cody * Requires that the overlay to 'top' is opened r/w, so that the backing file 26356ebdcee2SJeff Cody * information in 'bs' can be properly updated. 26366ebdcee2SJeff Cody * 26376ebdcee2SJeff Cody * E.g., this will convert the following chain: 26386ebdcee2SJeff Cody * bottom <- base <- intermediate <- top <- active 26396ebdcee2SJeff Cody * 26406ebdcee2SJeff Cody * to 26416ebdcee2SJeff Cody * 26426ebdcee2SJeff Cody * bottom <- base <- active 26436ebdcee2SJeff Cody * 26446ebdcee2SJeff Cody * It is allowed for bottom==base, in which case it converts: 26456ebdcee2SJeff Cody * 26466ebdcee2SJeff Cody * base <- intermediate <- top <- active 26476ebdcee2SJeff Cody * 26486ebdcee2SJeff Cody * to 26496ebdcee2SJeff Cody * 26506ebdcee2SJeff Cody * base <- active 26516ebdcee2SJeff Cody * 26526ebdcee2SJeff Cody * Error conditions: 26536ebdcee2SJeff Cody * if active == top, that is considered an error 26546ebdcee2SJeff Cody * 26556ebdcee2SJeff Cody */ 26566ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top, 26576ebdcee2SJeff Cody BlockDriverState *base) 26586ebdcee2SJeff Cody { 26596ebdcee2SJeff Cody BlockDriverState *intermediate; 26606ebdcee2SJeff Cody BlockDriverState *base_bs = NULL; 26616ebdcee2SJeff Cody BlockDriverState *new_top_bs = NULL; 26626ebdcee2SJeff Cody BlkIntermediateStates *intermediate_state, *next; 26636ebdcee2SJeff Cody int ret = -EIO; 26646ebdcee2SJeff Cody 26656ebdcee2SJeff Cody QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete; 26666ebdcee2SJeff Cody QSIMPLEQ_INIT(&states_to_delete); 26676ebdcee2SJeff Cody 26686ebdcee2SJeff Cody if (!top->drv || !base->drv) { 26696ebdcee2SJeff Cody goto exit; 26706ebdcee2SJeff Cody } 26716ebdcee2SJeff Cody 26726ebdcee2SJeff Cody new_top_bs = bdrv_find_overlay(active, top); 26736ebdcee2SJeff Cody 26746ebdcee2SJeff Cody if (new_top_bs == NULL) { 26756ebdcee2SJeff Cody /* we could not find the image above 'top', this is an error */ 26766ebdcee2SJeff Cody goto exit; 26776ebdcee2SJeff Cody } 26786ebdcee2SJeff Cody 26796ebdcee2SJeff Cody /* special case of new_top_bs->backing_hd already pointing to base - nothing 26806ebdcee2SJeff Cody * to do, no intermediate images */ 26816ebdcee2SJeff Cody if (new_top_bs->backing_hd == base) { 26826ebdcee2SJeff Cody ret = 0; 26836ebdcee2SJeff Cody goto exit; 26846ebdcee2SJeff Cody } 26856ebdcee2SJeff Cody 26866ebdcee2SJeff Cody intermediate = top; 26876ebdcee2SJeff Cody 26886ebdcee2SJeff Cody /* now we will go down through the list, and add each BDS we find 26896ebdcee2SJeff Cody * into our deletion queue, until we hit the 'base' 26906ebdcee2SJeff Cody */ 26916ebdcee2SJeff Cody while (intermediate) { 26926ebdcee2SJeff Cody intermediate_state = g_malloc0(sizeof(BlkIntermediateStates)); 26936ebdcee2SJeff Cody intermediate_state->bs = intermediate; 26946ebdcee2SJeff Cody QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry); 26956ebdcee2SJeff Cody 26966ebdcee2SJeff Cody if (intermediate->backing_hd == base) { 26976ebdcee2SJeff Cody base_bs = intermediate->backing_hd; 26986ebdcee2SJeff Cody break; 26996ebdcee2SJeff Cody } 27006ebdcee2SJeff Cody intermediate = intermediate->backing_hd; 27016ebdcee2SJeff Cody } 27026ebdcee2SJeff Cody if (base_bs == NULL) { 27036ebdcee2SJeff Cody /* something went wrong, we did not end at the base. safely 27046ebdcee2SJeff Cody * unravel everything, and exit with error */ 27056ebdcee2SJeff Cody goto exit; 27066ebdcee2SJeff Cody } 27076ebdcee2SJeff Cody 27086ebdcee2SJeff Cody /* success - we can delete the intermediate states, and link top->base */ 27096ebdcee2SJeff Cody ret = bdrv_change_backing_file(new_top_bs, base_bs->filename, 27106ebdcee2SJeff Cody base_bs->drv ? base_bs->drv->format_name : ""); 27116ebdcee2SJeff Cody if (ret) { 27126ebdcee2SJeff Cody goto exit; 27136ebdcee2SJeff Cody } 2714920beae1SFam Zheng bdrv_set_backing_hd(new_top_bs, base_bs); 27156ebdcee2SJeff Cody 27166ebdcee2SJeff Cody QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) { 27176ebdcee2SJeff Cody /* so that bdrv_close() does not recursively close the chain */ 2718920beae1SFam Zheng bdrv_set_backing_hd(intermediate_state->bs, NULL); 27194f6fd349SFam Zheng bdrv_unref(intermediate_state->bs); 27206ebdcee2SJeff Cody } 27216ebdcee2SJeff Cody ret = 0; 27226ebdcee2SJeff Cody 27236ebdcee2SJeff Cody exit: 27246ebdcee2SJeff Cody QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) { 27256ebdcee2SJeff Cody g_free(intermediate_state); 27266ebdcee2SJeff Cody } 27276ebdcee2SJeff Cody return ret; 27286ebdcee2SJeff Cody } 27296ebdcee2SJeff Cody 27306ebdcee2SJeff Cody 273171d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset, 273271d0770cSaliguori size_t size) 273371d0770cSaliguori { 273471d0770cSaliguori int64_t len; 273571d0770cSaliguori 27361dd3a447SKevin Wolf if (size > INT_MAX) { 27371dd3a447SKevin Wolf return -EIO; 27381dd3a447SKevin Wolf } 27391dd3a447SKevin Wolf 274071d0770cSaliguori if (!bdrv_is_inserted(bs)) 274171d0770cSaliguori return -ENOMEDIUM; 274271d0770cSaliguori 274371d0770cSaliguori if (bs->growable) 274471d0770cSaliguori return 0; 274571d0770cSaliguori 274671d0770cSaliguori len = bdrv_getlength(bs); 274771d0770cSaliguori 2748fbb7b4e0SKevin Wolf if (offset < 0) 2749fbb7b4e0SKevin Wolf return -EIO; 2750fbb7b4e0SKevin Wolf 2751fbb7b4e0SKevin Wolf if ((offset > len) || (len - offset < size)) 275271d0770cSaliguori return -EIO; 275371d0770cSaliguori 275471d0770cSaliguori return 0; 275571d0770cSaliguori } 275671d0770cSaliguori 275771d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num, 275871d0770cSaliguori int nb_sectors) 275971d0770cSaliguori { 276054db38a4SKevin Wolf if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) { 27618f4754edSKevin Wolf return -EIO; 27628f4754edSKevin Wolf } 27638f4754edSKevin Wolf 2764eb5a3165SJes Sorensen return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE, 2765eb5a3165SJes Sorensen nb_sectors * BDRV_SECTOR_SIZE); 276671d0770cSaliguori } 276771d0770cSaliguori 27681c9805a3SStefan Hajnoczi typedef struct RwCo { 27691c9805a3SStefan Hajnoczi BlockDriverState *bs; 2770775aa8b6SKevin Wolf int64_t offset; 27711c9805a3SStefan Hajnoczi QEMUIOVector *qiov; 27721c9805a3SStefan Hajnoczi bool is_write; 27731c9805a3SStefan Hajnoczi int ret; 27744105eaaaSPeter Lieven BdrvRequestFlags flags; 27751c9805a3SStefan Hajnoczi } RwCo; 27761c9805a3SStefan Hajnoczi 27771c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque) 2778fc01f7e7Sbellard { 27791c9805a3SStefan Hajnoczi RwCo *rwco = opaque; 2780fc01f7e7Sbellard 27811c9805a3SStefan Hajnoczi if (!rwco->is_write) { 2782775aa8b6SKevin Wolf rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset, 2783775aa8b6SKevin Wolf rwco->qiov->size, rwco->qiov, 27844105eaaaSPeter Lieven rwco->flags); 27851c9805a3SStefan Hajnoczi } else { 2786775aa8b6SKevin Wolf rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset, 2787775aa8b6SKevin Wolf rwco->qiov->size, rwco->qiov, 27884105eaaaSPeter Lieven rwco->flags); 27891c9805a3SStefan Hajnoczi } 27901c9805a3SStefan Hajnoczi } 2791e7a8a783SKevin Wolf 27921c9805a3SStefan Hajnoczi /* 27938d3b1a2dSKevin Wolf * Process a vectored synchronous request using coroutines 27941c9805a3SStefan Hajnoczi */ 2795775aa8b6SKevin Wolf static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset, 27964105eaaaSPeter Lieven QEMUIOVector *qiov, bool is_write, 27974105eaaaSPeter Lieven BdrvRequestFlags flags) 27981c9805a3SStefan Hajnoczi { 27991c9805a3SStefan Hajnoczi Coroutine *co; 28001c9805a3SStefan Hajnoczi RwCo rwco = { 28011c9805a3SStefan Hajnoczi .bs = bs, 2802775aa8b6SKevin Wolf .offset = offset, 28038d3b1a2dSKevin Wolf .qiov = qiov, 28041c9805a3SStefan Hajnoczi .is_write = is_write, 28051c9805a3SStefan Hajnoczi .ret = NOT_DONE, 28064105eaaaSPeter Lieven .flags = flags, 28071c9805a3SStefan Hajnoczi }; 28081c9805a3SStefan Hajnoczi 2809498e386cSZhi Yong Wu /** 2810498e386cSZhi Yong Wu * In sync call context, when the vcpu is blocked, this throttling timer 2811498e386cSZhi Yong Wu * will not fire; so the I/O throttling function has to be disabled here 2812498e386cSZhi Yong Wu * if it has been enabled. 2813498e386cSZhi Yong Wu */ 2814498e386cSZhi Yong Wu if (bs->io_limits_enabled) { 2815498e386cSZhi Yong Wu fprintf(stderr, "Disabling I/O throttling on '%s' due " 2816498e386cSZhi Yong Wu "to synchronous I/O.\n", bdrv_get_device_name(bs)); 2817498e386cSZhi Yong Wu bdrv_io_limits_disable(bs); 2818498e386cSZhi Yong Wu } 2819498e386cSZhi Yong Wu 28201c9805a3SStefan Hajnoczi if (qemu_in_coroutine()) { 28211c9805a3SStefan Hajnoczi /* Fast-path if already in coroutine context */ 28221c9805a3SStefan Hajnoczi bdrv_rw_co_entry(&rwco); 28231c9805a3SStefan Hajnoczi } else { 28242572b37aSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 28252572b37aSStefan Hajnoczi 28261c9805a3SStefan Hajnoczi co = qemu_coroutine_create(bdrv_rw_co_entry); 28271c9805a3SStefan Hajnoczi qemu_coroutine_enter(co, &rwco); 28281c9805a3SStefan Hajnoczi while (rwco.ret == NOT_DONE) { 28292572b37aSStefan Hajnoczi aio_poll(aio_context, true); 28301c9805a3SStefan Hajnoczi } 28311c9805a3SStefan Hajnoczi } 28321c9805a3SStefan Hajnoczi return rwco.ret; 2833e7a8a783SKevin Wolf } 2834e7a8a783SKevin Wolf 28358d3b1a2dSKevin Wolf /* 28368d3b1a2dSKevin Wolf * Process a synchronous request using coroutines 28378d3b1a2dSKevin Wolf */ 28388d3b1a2dSKevin Wolf static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf, 28394105eaaaSPeter Lieven int nb_sectors, bool is_write, BdrvRequestFlags flags) 28408d3b1a2dSKevin Wolf { 28418d3b1a2dSKevin Wolf QEMUIOVector qiov; 28428d3b1a2dSKevin Wolf struct iovec iov = { 28438d3b1a2dSKevin Wolf .iov_base = (void *)buf, 28448d3b1a2dSKevin Wolf .iov_len = nb_sectors * BDRV_SECTOR_SIZE, 28458d3b1a2dSKevin Wolf }; 28468d3b1a2dSKevin Wolf 2847da15ee51SKevin Wolf if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) { 2848da15ee51SKevin Wolf return -EINVAL; 2849da15ee51SKevin Wolf } 2850da15ee51SKevin Wolf 28518d3b1a2dSKevin Wolf qemu_iovec_init_external(&qiov, &iov, 1); 2852775aa8b6SKevin Wolf return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS, 2853775aa8b6SKevin Wolf &qiov, is_write, flags); 28548d3b1a2dSKevin Wolf } 28558d3b1a2dSKevin Wolf 28561c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */ 28571c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num, 28581c9805a3SStefan Hajnoczi uint8_t *buf, int nb_sectors) 28591c9805a3SStefan Hajnoczi { 28604105eaaaSPeter Lieven return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0); 286183f64091Sbellard } 2862fc01f7e7Sbellard 286307d27a44SMarkus Armbruster /* Just like bdrv_read(), but with I/O throttling temporarily disabled */ 286407d27a44SMarkus Armbruster int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num, 286507d27a44SMarkus Armbruster uint8_t *buf, int nb_sectors) 286607d27a44SMarkus Armbruster { 286707d27a44SMarkus Armbruster bool enabled; 286807d27a44SMarkus Armbruster int ret; 286907d27a44SMarkus Armbruster 287007d27a44SMarkus Armbruster enabled = bs->io_limits_enabled; 287107d27a44SMarkus Armbruster bs->io_limits_enabled = false; 28724e7395e8SPeter Lieven ret = bdrv_read(bs, sector_num, buf, nb_sectors); 287307d27a44SMarkus Armbruster bs->io_limits_enabled = enabled; 287407d27a44SMarkus Armbruster return ret; 287507d27a44SMarkus Armbruster } 287607d27a44SMarkus Armbruster 287719cb3738Sbellard /* Return < 0 if error. Important errors are: 287819cb3738Sbellard -EIO generic I/O error (may happen for all errors) 287919cb3738Sbellard -ENOMEDIUM No media inserted. 288019cb3738Sbellard -EINVAL Invalid sector number or nb_sectors 288119cb3738Sbellard -EACCES Trying to write a read-only device 288219cb3738Sbellard */ 2883fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num, 2884fc01f7e7Sbellard const uint8_t *buf, int nb_sectors) 2885fc01f7e7Sbellard { 28864105eaaaSPeter Lieven return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0); 288783f64091Sbellard } 288883f64091Sbellard 2889aa7bfbffSPeter Lieven int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num, 2890aa7bfbffSPeter Lieven int nb_sectors, BdrvRequestFlags flags) 28914105eaaaSPeter Lieven { 28924105eaaaSPeter Lieven return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true, 2893aa7bfbffSPeter Lieven BDRV_REQ_ZERO_WRITE | flags); 28948d3b1a2dSKevin Wolf } 28958d3b1a2dSKevin Wolf 2896d75cbb5eSPeter Lieven /* 2897d75cbb5eSPeter Lieven * Completely zero out a block device with the help of bdrv_write_zeroes. 2898d75cbb5eSPeter Lieven * The operation is sped up by checking the block status and only writing 2899d75cbb5eSPeter Lieven * zeroes to the device if they currently do not return zeroes. Optional 2900d75cbb5eSPeter Lieven * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP). 2901d75cbb5eSPeter Lieven * 2902d75cbb5eSPeter Lieven * Returns < 0 on error, 0 on success. For error codes see bdrv_write(). 2903d75cbb5eSPeter Lieven */ 2904d75cbb5eSPeter Lieven int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags) 2905d75cbb5eSPeter Lieven { 29069ce10c0bSKevin Wolf int64_t target_size; 2907d75cbb5eSPeter Lieven int64_t ret, nb_sectors, sector_num = 0; 2908d75cbb5eSPeter Lieven int n; 2909d75cbb5eSPeter Lieven 29109ce10c0bSKevin Wolf target_size = bdrv_getlength(bs); 29119ce10c0bSKevin Wolf if (target_size < 0) { 29129ce10c0bSKevin Wolf return target_size; 29139ce10c0bSKevin Wolf } 29149ce10c0bSKevin Wolf target_size /= BDRV_SECTOR_SIZE; 29159ce10c0bSKevin Wolf 2916d75cbb5eSPeter Lieven for (;;) { 2917d75cbb5eSPeter Lieven nb_sectors = target_size - sector_num; 2918d75cbb5eSPeter Lieven if (nb_sectors <= 0) { 2919d75cbb5eSPeter Lieven return 0; 2920d75cbb5eSPeter Lieven } 2921d75cbb5eSPeter Lieven if (nb_sectors > INT_MAX) { 2922d75cbb5eSPeter Lieven nb_sectors = INT_MAX; 2923d75cbb5eSPeter Lieven } 2924d75cbb5eSPeter Lieven ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n); 29253d94ce60SPeter Lieven if (ret < 0) { 29263d94ce60SPeter Lieven error_report("error getting block status at sector %" PRId64 ": %s", 29273d94ce60SPeter Lieven sector_num, strerror(-ret)); 29283d94ce60SPeter Lieven return ret; 29293d94ce60SPeter Lieven } 2930d75cbb5eSPeter Lieven if (ret & BDRV_BLOCK_ZERO) { 2931d75cbb5eSPeter Lieven sector_num += n; 2932d75cbb5eSPeter Lieven continue; 2933d75cbb5eSPeter Lieven } 2934d75cbb5eSPeter Lieven ret = bdrv_write_zeroes(bs, sector_num, n, flags); 2935d75cbb5eSPeter Lieven if (ret < 0) { 2936d75cbb5eSPeter Lieven error_report("error writing zeroes at sector %" PRId64 ": %s", 2937d75cbb5eSPeter Lieven sector_num, strerror(-ret)); 2938d75cbb5eSPeter Lieven return ret; 2939d75cbb5eSPeter Lieven } 2940d75cbb5eSPeter Lieven sector_num += n; 2941d75cbb5eSPeter Lieven } 2942d75cbb5eSPeter Lieven } 2943d75cbb5eSPeter Lieven 2944a3ef6571SKevin Wolf int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes) 294583f64091Sbellard { 2946a3ef6571SKevin Wolf QEMUIOVector qiov; 2947a3ef6571SKevin Wolf struct iovec iov = { 2948a3ef6571SKevin Wolf .iov_base = (void *)buf, 2949a3ef6571SKevin Wolf .iov_len = bytes, 2950a3ef6571SKevin Wolf }; 29519a8c4cceSKevin Wolf int ret; 295283f64091Sbellard 2953a3ef6571SKevin Wolf if (bytes < 0) { 2954a3ef6571SKevin Wolf return -EINVAL; 295583f64091Sbellard } 295683f64091Sbellard 2957a3ef6571SKevin Wolf qemu_iovec_init_external(&qiov, &iov, 1); 2958a3ef6571SKevin Wolf ret = bdrv_prwv_co(bs, offset, &qiov, false, 0); 2959a3ef6571SKevin Wolf if (ret < 0) { 29609a8c4cceSKevin Wolf return ret; 296183f64091Sbellard } 296283f64091Sbellard 2963a3ef6571SKevin Wolf return bytes; 296483f64091Sbellard } 296583f64091Sbellard 29668d3b1a2dSKevin Wolf int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov) 296783f64091Sbellard { 29689a8c4cceSKevin Wolf int ret; 296983f64091Sbellard 29708407d5d7SKevin Wolf ret = bdrv_prwv_co(bs, offset, qiov, true, 0); 29718d3b1a2dSKevin Wolf if (ret < 0) { 29729a8c4cceSKevin Wolf return ret; 29738d3b1a2dSKevin Wolf } 29748d3b1a2dSKevin Wolf 29758d3b1a2dSKevin Wolf return qiov->size; 29768d3b1a2dSKevin Wolf } 29778d3b1a2dSKevin Wolf 29788d3b1a2dSKevin Wolf int bdrv_pwrite(BlockDriverState *bs, int64_t offset, 29798407d5d7SKevin Wolf const void *buf, int bytes) 29808d3b1a2dSKevin Wolf { 29818d3b1a2dSKevin Wolf QEMUIOVector qiov; 29828d3b1a2dSKevin Wolf struct iovec iov = { 29838d3b1a2dSKevin Wolf .iov_base = (void *) buf, 29848407d5d7SKevin Wolf .iov_len = bytes, 29858d3b1a2dSKevin Wolf }; 29868d3b1a2dSKevin Wolf 29878407d5d7SKevin Wolf if (bytes < 0) { 29888407d5d7SKevin Wolf return -EINVAL; 29898407d5d7SKevin Wolf } 29908407d5d7SKevin Wolf 29918d3b1a2dSKevin Wolf qemu_iovec_init_external(&qiov, &iov, 1); 29928d3b1a2dSKevin Wolf return bdrv_pwritev(bs, offset, &qiov); 299383f64091Sbellard } 299483f64091Sbellard 2995f08145feSKevin Wolf /* 2996f08145feSKevin Wolf * Writes to the file and ensures that no writes are reordered across this 2997f08145feSKevin Wolf * request (acts as a barrier) 2998f08145feSKevin Wolf * 2999f08145feSKevin Wolf * Returns 0 on success, -errno in error cases. 3000f08145feSKevin Wolf */ 3001f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset, 3002f08145feSKevin Wolf const void *buf, int count) 3003f08145feSKevin Wolf { 3004f08145feSKevin Wolf int ret; 3005f08145feSKevin Wolf 3006f08145feSKevin Wolf ret = bdrv_pwrite(bs, offset, buf, count); 3007f08145feSKevin Wolf if (ret < 0) { 3008f08145feSKevin Wolf return ret; 3009f08145feSKevin Wolf } 3010f08145feSKevin Wolf 3011f05fa4adSPaolo Bonzini /* No flush needed for cache modes that already do it */ 3012f05fa4adSPaolo Bonzini if (bs->enable_write_cache) { 3013f08145feSKevin Wolf bdrv_flush(bs); 3014f08145feSKevin Wolf } 3015f08145feSKevin Wolf 3016f08145feSKevin Wolf return 0; 3017f08145feSKevin Wolf } 3018f08145feSKevin Wolf 3019470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs, 3020ab185921SStefan Hajnoczi int64_t sector_num, int nb_sectors, QEMUIOVector *qiov) 3021ab185921SStefan Hajnoczi { 3022ab185921SStefan Hajnoczi /* Perform I/O through a temporary buffer so that users who scribble over 3023ab185921SStefan Hajnoczi * their read buffer while the operation is in progress do not end up 3024ab185921SStefan Hajnoczi * modifying the image file. This is critical for zero-copy guest I/O 3025ab185921SStefan Hajnoczi * where anything might happen inside guest memory. 3026ab185921SStefan Hajnoczi */ 3027ab185921SStefan Hajnoczi void *bounce_buffer; 3028ab185921SStefan Hajnoczi 302979c053bdSStefan Hajnoczi BlockDriver *drv = bs->drv; 3030ab185921SStefan Hajnoczi struct iovec iov; 3031ab185921SStefan Hajnoczi QEMUIOVector bounce_qiov; 3032ab185921SStefan Hajnoczi int64_t cluster_sector_num; 3033ab185921SStefan Hajnoczi int cluster_nb_sectors; 3034ab185921SStefan Hajnoczi size_t skip_bytes; 3035ab185921SStefan Hajnoczi int ret; 3036ab185921SStefan Hajnoczi 3037ab185921SStefan Hajnoczi /* Cover entire cluster so no additional backing file I/O is required when 3038ab185921SStefan Hajnoczi * allocating cluster in the image file. 3039ab185921SStefan Hajnoczi */ 3040343bded4SPaolo Bonzini bdrv_round_to_clusters(bs, sector_num, nb_sectors, 3041ab185921SStefan Hajnoczi &cluster_sector_num, &cluster_nb_sectors); 3042ab185921SStefan Hajnoczi 3043470c0504SStefan Hajnoczi trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, 3044ab185921SStefan Hajnoczi cluster_sector_num, cluster_nb_sectors); 3045ab185921SStefan Hajnoczi 3046ab185921SStefan Hajnoczi iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE; 3047ab185921SStefan Hajnoczi iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len); 3048ab185921SStefan Hajnoczi qemu_iovec_init_external(&bounce_qiov, &iov, 1); 3049ab185921SStefan Hajnoczi 305079c053bdSStefan Hajnoczi ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors, 3051ab185921SStefan Hajnoczi &bounce_qiov); 3052ab185921SStefan Hajnoczi if (ret < 0) { 3053ab185921SStefan Hajnoczi goto err; 3054ab185921SStefan Hajnoczi } 3055ab185921SStefan Hajnoczi 305679c053bdSStefan Hajnoczi if (drv->bdrv_co_write_zeroes && 305779c053bdSStefan Hajnoczi buffer_is_zero(bounce_buffer, iov.iov_len)) { 3058621f0589SKevin Wolf ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num, 3059aa7bfbffSPeter Lieven cluster_nb_sectors, 0); 306079c053bdSStefan Hajnoczi } else { 3061f05fa4adSPaolo Bonzini /* This does not change the data on the disk, it is not necessary 3062f05fa4adSPaolo Bonzini * to flush even in cache=writethrough mode. 3063f05fa4adSPaolo Bonzini */ 306479c053bdSStefan Hajnoczi ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors, 3065ab185921SStefan Hajnoczi &bounce_qiov); 306679c053bdSStefan Hajnoczi } 306779c053bdSStefan Hajnoczi 3068ab185921SStefan Hajnoczi if (ret < 0) { 3069ab185921SStefan Hajnoczi /* It might be okay to ignore write errors for guest requests. If this 3070ab185921SStefan Hajnoczi * is a deliberate copy-on-read then we don't want to ignore the error. 3071ab185921SStefan Hajnoczi * Simply report it in all cases. 3072ab185921SStefan Hajnoczi */ 3073ab185921SStefan Hajnoczi goto err; 3074ab185921SStefan Hajnoczi } 3075ab185921SStefan Hajnoczi 3076ab185921SStefan Hajnoczi skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE; 307703396148SMichael Tokarev qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes, 3078ab185921SStefan Hajnoczi nb_sectors * BDRV_SECTOR_SIZE); 3079ab185921SStefan Hajnoczi 3080ab185921SStefan Hajnoczi err: 3081ab185921SStefan Hajnoczi qemu_vfree(bounce_buffer); 3082ab185921SStefan Hajnoczi return ret; 3083ab185921SStefan Hajnoczi } 3084ab185921SStefan Hajnoczi 3085c5fbe571SStefan Hajnoczi /* 3086d0c7f642SKevin Wolf * Forwards an already correctly aligned request to the BlockDriver. This 3087d0c7f642SKevin Wolf * handles copy on read and zeroing after EOF; any other features must be 3088d0c7f642SKevin Wolf * implemented by the caller. 3089c5fbe571SStefan Hajnoczi */ 3090d0c7f642SKevin Wolf static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs, 309165afd211SKevin Wolf BdrvTrackedRequest *req, int64_t offset, unsigned int bytes, 3092ec746e10SKevin Wolf int64_t align, QEMUIOVector *qiov, int flags) 3093da1fa91dSKevin Wolf { 3094da1fa91dSKevin Wolf BlockDriver *drv = bs->drv; 3095dbffbdcfSStefan Hajnoczi int ret; 3096da1fa91dSKevin Wolf 3097d0c7f642SKevin Wolf int64_t sector_num = offset >> BDRV_SECTOR_BITS; 3098d0c7f642SKevin Wolf unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS; 3099da1fa91dSKevin Wolf 3100d0c7f642SKevin Wolf assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0); 3101d0c7f642SKevin Wolf assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0); 3102d0c7f642SKevin Wolf 3103d0c7f642SKevin Wolf /* Handle Copy on Read and associated serialisation */ 3104470c0504SStefan Hajnoczi if (flags & BDRV_REQ_COPY_ON_READ) { 31057327145fSKevin Wolf /* If we touch the same cluster it counts as an overlap. This 31067327145fSKevin Wolf * guarantees that allocating writes will be serialized and not race 31077327145fSKevin Wolf * with each other for the same cluster. For example, in copy-on-read 31087327145fSKevin Wolf * it ensures that the CoR read and write operations are atomic and 31097327145fSKevin Wolf * guest writes cannot interleave between them. */ 31107327145fSKevin Wolf mark_request_serialising(req, bdrv_get_cluster_size(bs)); 3111470c0504SStefan Hajnoczi } 3112470c0504SStefan Hajnoczi 31132dbafdc0SKevin Wolf wait_serialising_requests(req); 3114f4658285SStefan Hajnoczi 3115470c0504SStefan Hajnoczi if (flags & BDRV_REQ_COPY_ON_READ) { 3116ab185921SStefan Hajnoczi int pnum; 3117ab185921SStefan Hajnoczi 3118bdad13b9SPaolo Bonzini ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum); 3119ab185921SStefan Hajnoczi if (ret < 0) { 3120ab185921SStefan Hajnoczi goto out; 3121ab185921SStefan Hajnoczi } 3122ab185921SStefan Hajnoczi 3123ab185921SStefan Hajnoczi if (!ret || pnum != nb_sectors) { 3124470c0504SStefan Hajnoczi ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov); 3125ab185921SStefan Hajnoczi goto out; 3126ab185921SStefan Hajnoczi } 3127ab185921SStefan Hajnoczi } 3128ab185921SStefan Hajnoczi 3129d0c7f642SKevin Wolf /* Forward the request to the BlockDriver */ 3130893a8f62SMORITA Kazutaka if (!(bs->zero_beyond_eof && bs->growable)) { 3131dbffbdcfSStefan Hajnoczi ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov); 3132893a8f62SMORITA Kazutaka } else { 3133893a8f62SMORITA Kazutaka /* Read zeros after EOF of growable BDSes */ 3134893a8f62SMORITA Kazutaka int64_t len, total_sectors, max_nb_sectors; 3135893a8f62SMORITA Kazutaka 3136893a8f62SMORITA Kazutaka len = bdrv_getlength(bs); 3137893a8f62SMORITA Kazutaka if (len < 0) { 3138893a8f62SMORITA Kazutaka ret = len; 3139893a8f62SMORITA Kazutaka goto out; 3140893a8f62SMORITA Kazutaka } 3141893a8f62SMORITA Kazutaka 3142d055a1feSFam Zheng total_sectors = DIV_ROUND_UP(len, BDRV_SECTOR_SIZE); 31435f5bcd80SKevin Wolf max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num), 31445f5bcd80SKevin Wolf align >> BDRV_SECTOR_BITS); 3145893a8f62SMORITA Kazutaka if (max_nb_sectors > 0) { 3146893a8f62SMORITA Kazutaka ret = drv->bdrv_co_readv(bs, sector_num, 3147893a8f62SMORITA Kazutaka MIN(nb_sectors, max_nb_sectors), qiov); 3148893a8f62SMORITA Kazutaka } else { 3149893a8f62SMORITA Kazutaka ret = 0; 3150893a8f62SMORITA Kazutaka } 3151893a8f62SMORITA Kazutaka 3152893a8f62SMORITA Kazutaka /* Reading beyond end of file is supposed to produce zeroes */ 3153893a8f62SMORITA Kazutaka if (ret == 0 && total_sectors < sector_num + nb_sectors) { 3154893a8f62SMORITA Kazutaka uint64_t offset = MAX(0, total_sectors - sector_num); 3155893a8f62SMORITA Kazutaka uint64_t bytes = (sector_num + nb_sectors - offset) * 3156893a8f62SMORITA Kazutaka BDRV_SECTOR_SIZE; 3157893a8f62SMORITA Kazutaka qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes); 3158893a8f62SMORITA Kazutaka } 3159893a8f62SMORITA Kazutaka } 3160ab185921SStefan Hajnoczi 3161ab185921SStefan Hajnoczi out: 3162dbffbdcfSStefan Hajnoczi return ret; 3163da1fa91dSKevin Wolf } 3164da1fa91dSKevin Wolf 3165d0c7f642SKevin Wolf /* 3166d0c7f642SKevin Wolf * Handle a read request in coroutine context 3167d0c7f642SKevin Wolf */ 31681b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs, 31691b0288aeSKevin Wolf int64_t offset, unsigned int bytes, QEMUIOVector *qiov, 3170d0c7f642SKevin Wolf BdrvRequestFlags flags) 3171d0c7f642SKevin Wolf { 3172d0c7f642SKevin Wolf BlockDriver *drv = bs->drv; 317365afd211SKevin Wolf BdrvTrackedRequest req; 317465afd211SKevin Wolf 31751b0288aeSKevin Wolf /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */ 31761b0288aeSKevin Wolf uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment); 31771b0288aeSKevin Wolf uint8_t *head_buf = NULL; 31781b0288aeSKevin Wolf uint8_t *tail_buf = NULL; 31791b0288aeSKevin Wolf QEMUIOVector local_qiov; 31801b0288aeSKevin Wolf bool use_local_qiov = false; 3181d0c7f642SKevin Wolf int ret; 3182d0c7f642SKevin Wolf 3183d0c7f642SKevin Wolf if (!drv) { 3184d0c7f642SKevin Wolf return -ENOMEDIUM; 3185d0c7f642SKevin Wolf } 31861b0288aeSKevin Wolf if (bdrv_check_byte_request(bs, offset, bytes)) { 3187d0c7f642SKevin Wolf return -EIO; 3188d0c7f642SKevin Wolf } 3189d0c7f642SKevin Wolf 3190d0c7f642SKevin Wolf if (bs->copy_on_read) { 3191d0c7f642SKevin Wolf flags |= BDRV_REQ_COPY_ON_READ; 3192d0c7f642SKevin Wolf } 3193d0c7f642SKevin Wolf 3194d0c7f642SKevin Wolf /* throttling disk I/O */ 3195d0c7f642SKevin Wolf if (bs->io_limits_enabled) { 3196d5103588SKevin Wolf bdrv_io_limits_intercept(bs, bytes, false); 3197d0c7f642SKevin Wolf } 3198d0c7f642SKevin Wolf 31991b0288aeSKevin Wolf /* Align read if necessary by padding qiov */ 32001b0288aeSKevin Wolf if (offset & (align - 1)) { 32011b0288aeSKevin Wolf head_buf = qemu_blockalign(bs, align); 32021b0288aeSKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov + 2); 32031b0288aeSKevin Wolf qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1)); 32041b0288aeSKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 32051b0288aeSKevin Wolf use_local_qiov = true; 32061b0288aeSKevin Wolf 32071b0288aeSKevin Wolf bytes += offset & (align - 1); 32081b0288aeSKevin Wolf offset = offset & ~(align - 1); 32091b0288aeSKevin Wolf } 32101b0288aeSKevin Wolf 32111b0288aeSKevin Wolf if ((offset + bytes) & (align - 1)) { 32121b0288aeSKevin Wolf if (!use_local_qiov) { 32131b0288aeSKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov + 1); 32141b0288aeSKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 32151b0288aeSKevin Wolf use_local_qiov = true; 32161b0288aeSKevin Wolf } 32171b0288aeSKevin Wolf tail_buf = qemu_blockalign(bs, align); 32181b0288aeSKevin Wolf qemu_iovec_add(&local_qiov, tail_buf, 32191b0288aeSKevin Wolf align - ((offset + bytes) & (align - 1))); 32201b0288aeSKevin Wolf 32211b0288aeSKevin Wolf bytes = ROUND_UP(bytes, align); 32221b0288aeSKevin Wolf } 32231b0288aeSKevin Wolf 322465afd211SKevin Wolf tracked_request_begin(&req, bs, offset, bytes, false); 3225ec746e10SKevin Wolf ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align, 32261b0288aeSKevin Wolf use_local_qiov ? &local_qiov : qiov, 32271b0288aeSKevin Wolf flags); 322865afd211SKevin Wolf tracked_request_end(&req); 32291b0288aeSKevin Wolf 32301b0288aeSKevin Wolf if (use_local_qiov) { 32311b0288aeSKevin Wolf qemu_iovec_destroy(&local_qiov); 32321b0288aeSKevin Wolf qemu_vfree(head_buf); 32331b0288aeSKevin Wolf qemu_vfree(tail_buf); 32341b0288aeSKevin Wolf } 32351b0288aeSKevin Wolf 3236d0c7f642SKevin Wolf return ret; 3237d0c7f642SKevin Wolf } 3238d0c7f642SKevin Wolf 32391b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs, 32401b0288aeSKevin Wolf int64_t sector_num, int nb_sectors, QEMUIOVector *qiov, 32411b0288aeSKevin Wolf BdrvRequestFlags flags) 32421b0288aeSKevin Wolf { 32431b0288aeSKevin Wolf if (nb_sectors < 0 || nb_sectors > (UINT_MAX >> BDRV_SECTOR_BITS)) { 32441b0288aeSKevin Wolf return -EINVAL; 32451b0288aeSKevin Wolf } 32461b0288aeSKevin Wolf 32471b0288aeSKevin Wolf return bdrv_co_do_preadv(bs, sector_num << BDRV_SECTOR_BITS, 32481b0288aeSKevin Wolf nb_sectors << BDRV_SECTOR_BITS, qiov, flags); 32491b0288aeSKevin Wolf } 32501b0288aeSKevin Wolf 3251c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num, 3252da1fa91dSKevin Wolf int nb_sectors, QEMUIOVector *qiov) 3253da1fa91dSKevin Wolf { 3254c5fbe571SStefan Hajnoczi trace_bdrv_co_readv(bs, sector_num, nb_sectors); 3255da1fa91dSKevin Wolf 3256470c0504SStefan Hajnoczi return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0); 3257470c0504SStefan Hajnoczi } 3258470c0504SStefan Hajnoczi 3259470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs, 3260470c0504SStefan Hajnoczi int64_t sector_num, int nb_sectors, QEMUIOVector *qiov) 3261470c0504SStefan Hajnoczi { 3262470c0504SStefan Hajnoczi trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors); 3263470c0504SStefan Hajnoczi 3264470c0504SStefan Hajnoczi return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 3265470c0504SStefan Hajnoczi BDRV_REQ_COPY_ON_READ); 3266c5fbe571SStefan Hajnoczi } 3267c5fbe571SStefan Hajnoczi 3268c31cb707SPeter Lieven /* if no limit is specified in the BlockLimits use a default 3269c31cb707SPeter Lieven * of 32768 512-byte sectors (16 MiB) per request. 3270c31cb707SPeter Lieven */ 3271c31cb707SPeter Lieven #define MAX_WRITE_ZEROES_DEFAULT 32768 3272c31cb707SPeter Lieven 3273f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs, 3274aa7bfbffSPeter Lieven int64_t sector_num, int nb_sectors, BdrvRequestFlags flags) 3275f08f2ddaSStefan Hajnoczi { 3276f08f2ddaSStefan Hajnoczi BlockDriver *drv = bs->drv; 3277f08f2ddaSStefan Hajnoczi QEMUIOVector qiov; 3278c31cb707SPeter Lieven struct iovec iov = {0}; 3279c31cb707SPeter Lieven int ret = 0; 3280f08f2ddaSStefan Hajnoczi 3281c31cb707SPeter Lieven int max_write_zeroes = bs->bl.max_write_zeroes ? 3282c31cb707SPeter Lieven bs->bl.max_write_zeroes : MAX_WRITE_ZEROES_DEFAULT; 3283621f0589SKevin Wolf 3284c31cb707SPeter Lieven while (nb_sectors > 0 && !ret) { 3285c31cb707SPeter Lieven int num = nb_sectors; 3286c31cb707SPeter Lieven 3287b8d71c09SPaolo Bonzini /* Align request. Block drivers can expect the "bulk" of the request 3288b8d71c09SPaolo Bonzini * to be aligned. 3289b8d71c09SPaolo Bonzini */ 3290b8d71c09SPaolo Bonzini if (bs->bl.write_zeroes_alignment 3291b8d71c09SPaolo Bonzini && num > bs->bl.write_zeroes_alignment) { 3292b8d71c09SPaolo Bonzini if (sector_num % bs->bl.write_zeroes_alignment != 0) { 3293b8d71c09SPaolo Bonzini /* Make a small request up to the first aligned sector. */ 3294c31cb707SPeter Lieven num = bs->bl.write_zeroes_alignment; 3295c31cb707SPeter Lieven num -= sector_num % bs->bl.write_zeroes_alignment; 3296b8d71c09SPaolo Bonzini } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) { 3297b8d71c09SPaolo Bonzini /* Shorten the request to the last aligned sector. num cannot 3298b8d71c09SPaolo Bonzini * underflow because num > bs->bl.write_zeroes_alignment. 3299b8d71c09SPaolo Bonzini */ 3300b8d71c09SPaolo Bonzini num -= (sector_num + num) % bs->bl.write_zeroes_alignment; 3301b8d71c09SPaolo Bonzini } 3302c31cb707SPeter Lieven } 3303c31cb707SPeter Lieven 3304c31cb707SPeter Lieven /* limit request size */ 3305c31cb707SPeter Lieven if (num > max_write_zeroes) { 3306c31cb707SPeter Lieven num = max_write_zeroes; 3307c31cb707SPeter Lieven } 3308c31cb707SPeter Lieven 3309c31cb707SPeter Lieven ret = -ENOTSUP; 3310f08f2ddaSStefan Hajnoczi /* First try the efficient write zeroes operation */ 3311f08f2ddaSStefan Hajnoczi if (drv->bdrv_co_write_zeroes) { 3312c31cb707SPeter Lieven ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags); 3313f08f2ddaSStefan Hajnoczi } 3314f08f2ddaSStefan Hajnoczi 3315c31cb707SPeter Lieven if (ret == -ENOTSUP) { 3316f08f2ddaSStefan Hajnoczi /* Fall back to bounce buffer if write zeroes is unsupported */ 3317c31cb707SPeter Lieven iov.iov_len = num * BDRV_SECTOR_SIZE; 3318c31cb707SPeter Lieven if (iov.iov_base == NULL) { 3319b8d71c09SPaolo Bonzini iov.iov_base = qemu_blockalign(bs, num * BDRV_SECTOR_SIZE); 3320b8d71c09SPaolo Bonzini memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE); 3321c31cb707SPeter Lieven } 3322f08f2ddaSStefan Hajnoczi qemu_iovec_init_external(&qiov, &iov, 1); 3323f08f2ddaSStefan Hajnoczi 3324c31cb707SPeter Lieven ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov); 3325b8d71c09SPaolo Bonzini 3326b8d71c09SPaolo Bonzini /* Keep bounce buffer around if it is big enough for all 3327b8d71c09SPaolo Bonzini * all future requests. 3328b8d71c09SPaolo Bonzini */ 3329b8d71c09SPaolo Bonzini if (num < max_write_zeroes) { 3330b8d71c09SPaolo Bonzini qemu_vfree(iov.iov_base); 3331b8d71c09SPaolo Bonzini iov.iov_base = NULL; 3332b8d71c09SPaolo Bonzini } 3333c31cb707SPeter Lieven } 3334c31cb707SPeter Lieven 3335c31cb707SPeter Lieven sector_num += num; 3336c31cb707SPeter Lieven nb_sectors -= num; 3337c31cb707SPeter Lieven } 3338f08f2ddaSStefan Hajnoczi 3339f08f2ddaSStefan Hajnoczi qemu_vfree(iov.iov_base); 3340f08f2ddaSStefan Hajnoczi return ret; 3341f08f2ddaSStefan Hajnoczi } 3342f08f2ddaSStefan Hajnoczi 3343c5fbe571SStefan Hajnoczi /* 3344b404f720SKevin Wolf * Forwards an already correctly aligned write request to the BlockDriver. 3345c5fbe571SStefan Hajnoczi */ 3346b404f720SKevin Wolf static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs, 334765afd211SKevin Wolf BdrvTrackedRequest *req, int64_t offset, unsigned int bytes, 334865afd211SKevin Wolf QEMUIOVector *qiov, int flags) 3349c5fbe571SStefan Hajnoczi { 3350c5fbe571SStefan Hajnoczi BlockDriver *drv = bs->drv; 335128de2dcdSKevin Wolf bool waited; 33526b7cb247SStefan Hajnoczi int ret; 3353da1fa91dSKevin Wolf 3354b404f720SKevin Wolf int64_t sector_num = offset >> BDRV_SECTOR_BITS; 3355b404f720SKevin Wolf unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS; 3356da1fa91dSKevin Wolf 3357b404f720SKevin Wolf assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0); 3358b404f720SKevin Wolf assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0); 3359cc0681c4SBenoît Canet 336028de2dcdSKevin Wolf waited = wait_serialising_requests(req); 336128de2dcdSKevin Wolf assert(!waited || !req->serialising); 3362af91f9a7SKevin Wolf assert(req->overlap_offset <= offset); 3363af91f9a7SKevin Wolf assert(offset + bytes <= req->overlap_offset + req->overlap_bytes); 3364244eadefSKevin Wolf 336565afd211SKevin Wolf ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req); 3366d616b224SStefan Hajnoczi 3367465bee1dSPeter Lieven if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF && 3368465bee1dSPeter Lieven !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_write_zeroes && 3369465bee1dSPeter Lieven qemu_iovec_is_zero(qiov)) { 3370465bee1dSPeter Lieven flags |= BDRV_REQ_ZERO_WRITE; 3371465bee1dSPeter Lieven if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) { 3372465bee1dSPeter Lieven flags |= BDRV_REQ_MAY_UNMAP; 3373465bee1dSPeter Lieven } 3374465bee1dSPeter Lieven } 3375465bee1dSPeter Lieven 3376d616b224SStefan Hajnoczi if (ret < 0) { 3377d616b224SStefan Hajnoczi /* Do nothing, write notifier decided to fail this request */ 3378d616b224SStefan Hajnoczi } else if (flags & BDRV_REQ_ZERO_WRITE) { 33799e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_ZERO); 3380aa7bfbffSPeter Lieven ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags); 3381f08f2ddaSStefan Hajnoczi } else { 33829e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV); 33836b7cb247SStefan Hajnoczi ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov); 3384f08f2ddaSStefan Hajnoczi } 33859e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_DONE); 33866b7cb247SStefan Hajnoczi 3387f05fa4adSPaolo Bonzini if (ret == 0 && !bs->enable_write_cache) { 3388f05fa4adSPaolo Bonzini ret = bdrv_co_flush(bs); 3389f05fa4adSPaolo Bonzini } 3390f05fa4adSPaolo Bonzini 33911755da16SPaolo Bonzini bdrv_set_dirty(bs, sector_num, nb_sectors); 3392da1fa91dSKevin Wolf 3393da1fa91dSKevin Wolf if (bs->wr_highest_sector < sector_num + nb_sectors - 1) { 3394da1fa91dSKevin Wolf bs->wr_highest_sector = sector_num + nb_sectors - 1; 3395da1fa91dSKevin Wolf } 3396df2a6f29SPaolo Bonzini if (bs->growable && ret >= 0) { 3397df2a6f29SPaolo Bonzini bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors); 3398df2a6f29SPaolo Bonzini } 3399da1fa91dSKevin Wolf 34006b7cb247SStefan Hajnoczi return ret; 3401da1fa91dSKevin Wolf } 3402da1fa91dSKevin Wolf 3403b404f720SKevin Wolf /* 3404b404f720SKevin Wolf * Handle a write request in coroutine context 3405b404f720SKevin Wolf */ 34066601553eSKevin Wolf static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs, 34076601553eSKevin Wolf int64_t offset, unsigned int bytes, QEMUIOVector *qiov, 3408b404f720SKevin Wolf BdrvRequestFlags flags) 3409b404f720SKevin Wolf { 341065afd211SKevin Wolf BdrvTrackedRequest req; 34113b8242e0SKevin Wolf /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */ 34123b8242e0SKevin Wolf uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment); 34133b8242e0SKevin Wolf uint8_t *head_buf = NULL; 34143b8242e0SKevin Wolf uint8_t *tail_buf = NULL; 34153b8242e0SKevin Wolf QEMUIOVector local_qiov; 34163b8242e0SKevin Wolf bool use_local_qiov = false; 3417b404f720SKevin Wolf int ret; 3418b404f720SKevin Wolf 3419b404f720SKevin Wolf if (!bs->drv) { 3420b404f720SKevin Wolf return -ENOMEDIUM; 3421b404f720SKevin Wolf } 3422b404f720SKevin Wolf if (bs->read_only) { 3423b404f720SKevin Wolf return -EACCES; 3424b404f720SKevin Wolf } 34256601553eSKevin Wolf if (bdrv_check_byte_request(bs, offset, bytes)) { 3426b404f720SKevin Wolf return -EIO; 3427b404f720SKevin Wolf } 3428b404f720SKevin Wolf 3429b404f720SKevin Wolf /* throttling disk I/O */ 3430b404f720SKevin Wolf if (bs->io_limits_enabled) { 3431d5103588SKevin Wolf bdrv_io_limits_intercept(bs, bytes, true); 3432b404f720SKevin Wolf } 3433b404f720SKevin Wolf 34343b8242e0SKevin Wolf /* 34353b8242e0SKevin Wolf * Align write if necessary by performing a read-modify-write cycle. 34363b8242e0SKevin Wolf * Pad qiov with the read parts and be sure to have a tracked request not 34373b8242e0SKevin Wolf * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle. 34383b8242e0SKevin Wolf */ 343965afd211SKevin Wolf tracked_request_begin(&req, bs, offset, bytes, true); 34403b8242e0SKevin Wolf 34413b8242e0SKevin Wolf if (offset & (align - 1)) { 34423b8242e0SKevin Wolf QEMUIOVector head_qiov; 34433b8242e0SKevin Wolf struct iovec head_iov; 34443b8242e0SKevin Wolf 34453b8242e0SKevin Wolf mark_request_serialising(&req, align); 34463b8242e0SKevin Wolf wait_serialising_requests(&req); 34473b8242e0SKevin Wolf 34483b8242e0SKevin Wolf head_buf = qemu_blockalign(bs, align); 34493b8242e0SKevin Wolf head_iov = (struct iovec) { 34503b8242e0SKevin Wolf .iov_base = head_buf, 34513b8242e0SKevin Wolf .iov_len = align, 34523b8242e0SKevin Wolf }; 34533b8242e0SKevin Wolf qemu_iovec_init_external(&head_qiov, &head_iov, 1); 34543b8242e0SKevin Wolf 34559e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_HEAD); 34563b8242e0SKevin Wolf ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align, 34573b8242e0SKevin Wolf align, &head_qiov, 0); 34583b8242e0SKevin Wolf if (ret < 0) { 34593b8242e0SKevin Wolf goto fail; 34603b8242e0SKevin Wolf } 34619e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD); 34623b8242e0SKevin Wolf 34633b8242e0SKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov + 2); 34643b8242e0SKevin Wolf qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1)); 34653b8242e0SKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 34663b8242e0SKevin Wolf use_local_qiov = true; 34673b8242e0SKevin Wolf 34683b8242e0SKevin Wolf bytes += offset & (align - 1); 34693b8242e0SKevin Wolf offset = offset & ~(align - 1); 34703b8242e0SKevin Wolf } 34713b8242e0SKevin Wolf 34723b8242e0SKevin Wolf if ((offset + bytes) & (align - 1)) { 34733b8242e0SKevin Wolf QEMUIOVector tail_qiov; 34743b8242e0SKevin Wolf struct iovec tail_iov; 34753b8242e0SKevin Wolf size_t tail_bytes; 347628de2dcdSKevin Wolf bool waited; 34773b8242e0SKevin Wolf 34783b8242e0SKevin Wolf mark_request_serialising(&req, align); 347928de2dcdSKevin Wolf waited = wait_serialising_requests(&req); 348028de2dcdSKevin Wolf assert(!waited || !use_local_qiov); 34813b8242e0SKevin Wolf 34823b8242e0SKevin Wolf tail_buf = qemu_blockalign(bs, align); 34833b8242e0SKevin Wolf tail_iov = (struct iovec) { 34843b8242e0SKevin Wolf .iov_base = tail_buf, 34853b8242e0SKevin Wolf .iov_len = align, 34863b8242e0SKevin Wolf }; 34873b8242e0SKevin Wolf qemu_iovec_init_external(&tail_qiov, &tail_iov, 1); 34883b8242e0SKevin Wolf 34899e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_TAIL); 34903b8242e0SKevin Wolf ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align, 34913b8242e0SKevin Wolf align, &tail_qiov, 0); 34923b8242e0SKevin Wolf if (ret < 0) { 34933b8242e0SKevin Wolf goto fail; 34943b8242e0SKevin Wolf } 34959e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL); 34963b8242e0SKevin Wolf 34973b8242e0SKevin Wolf if (!use_local_qiov) { 34983b8242e0SKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov + 1); 34993b8242e0SKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 35003b8242e0SKevin Wolf use_local_qiov = true; 35013b8242e0SKevin Wolf } 35023b8242e0SKevin Wolf 35033b8242e0SKevin Wolf tail_bytes = (offset + bytes) & (align - 1); 35043b8242e0SKevin Wolf qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes); 35053b8242e0SKevin Wolf 35063b8242e0SKevin Wolf bytes = ROUND_UP(bytes, align); 35073b8242e0SKevin Wolf } 35083b8242e0SKevin Wolf 35093b8242e0SKevin Wolf ret = bdrv_aligned_pwritev(bs, &req, offset, bytes, 35103b8242e0SKevin Wolf use_local_qiov ? &local_qiov : qiov, 35113b8242e0SKevin Wolf flags); 35123b8242e0SKevin Wolf 35133b8242e0SKevin Wolf fail: 351465afd211SKevin Wolf tracked_request_end(&req); 3515b404f720SKevin Wolf 35163b8242e0SKevin Wolf if (use_local_qiov) { 35173b8242e0SKevin Wolf qemu_iovec_destroy(&local_qiov); 351899c4a85cSKevin Wolf } 35193b8242e0SKevin Wolf qemu_vfree(head_buf); 35203b8242e0SKevin Wolf qemu_vfree(tail_buf); 35213b8242e0SKevin Wolf 3522b404f720SKevin Wolf return ret; 3523b404f720SKevin Wolf } 3524b404f720SKevin Wolf 35256601553eSKevin Wolf static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs, 35266601553eSKevin Wolf int64_t sector_num, int nb_sectors, QEMUIOVector *qiov, 35276601553eSKevin Wolf BdrvRequestFlags flags) 35286601553eSKevin Wolf { 35296601553eSKevin Wolf if (nb_sectors < 0 || nb_sectors > (INT_MAX >> BDRV_SECTOR_BITS)) { 35306601553eSKevin Wolf return -EINVAL; 35316601553eSKevin Wolf } 35326601553eSKevin Wolf 35336601553eSKevin Wolf return bdrv_co_do_pwritev(bs, sector_num << BDRV_SECTOR_BITS, 35346601553eSKevin Wolf nb_sectors << BDRV_SECTOR_BITS, qiov, flags); 35356601553eSKevin Wolf } 35366601553eSKevin Wolf 3537c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num, 3538c5fbe571SStefan Hajnoczi int nb_sectors, QEMUIOVector *qiov) 3539c5fbe571SStefan Hajnoczi { 3540c5fbe571SStefan Hajnoczi trace_bdrv_co_writev(bs, sector_num, nb_sectors); 3541c5fbe571SStefan Hajnoczi 3542f08f2ddaSStefan Hajnoczi return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0); 3543f08f2ddaSStefan Hajnoczi } 3544f08f2ddaSStefan Hajnoczi 3545f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs, 3546aa7bfbffSPeter Lieven int64_t sector_num, int nb_sectors, 3547aa7bfbffSPeter Lieven BdrvRequestFlags flags) 3548f08f2ddaSStefan Hajnoczi { 354994d6ff21SPaolo Bonzini trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags); 3550f08f2ddaSStefan Hajnoczi 3551d32f35cbSPeter Lieven if (!(bs->open_flags & BDRV_O_UNMAP)) { 3552d32f35cbSPeter Lieven flags &= ~BDRV_REQ_MAY_UNMAP; 3553d32f35cbSPeter Lieven } 3554d32f35cbSPeter Lieven 3555f08f2ddaSStefan Hajnoczi return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL, 3556aa7bfbffSPeter Lieven BDRV_REQ_ZERO_WRITE | flags); 3557c5fbe571SStefan Hajnoczi } 3558c5fbe571SStefan Hajnoczi 355983f64091Sbellard /** 356083f64091Sbellard * Truncate file to 'offset' bytes (needed only for file protocols) 356183f64091Sbellard */ 356283f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset) 356383f64091Sbellard { 356483f64091Sbellard BlockDriver *drv = bs->drv; 356551762288SStefan Hajnoczi int ret; 356683f64091Sbellard if (!drv) 356719cb3738Sbellard return -ENOMEDIUM; 356883f64091Sbellard if (!drv->bdrv_truncate) 356983f64091Sbellard return -ENOTSUP; 357059f2689dSNaphtali Sprei if (bs->read_only) 357159f2689dSNaphtali Sprei return -EACCES; 35723718d8abSFam Zheng if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) { 35738591675fSMarcelo Tosatti return -EBUSY; 35743718d8abSFam Zheng } 357551762288SStefan Hajnoczi ret = drv->bdrv_truncate(bs, offset); 357651762288SStefan Hajnoczi if (ret == 0) { 357751762288SStefan Hajnoczi ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS); 3578145feb17SMarkus Armbruster bdrv_dev_resize_cb(bs); 357951762288SStefan Hajnoczi } 358051762288SStefan Hajnoczi return ret; 358183f64091Sbellard } 358283f64091Sbellard 358383f64091Sbellard /** 35844a1d5e1fSFam Zheng * Length of a allocated file in bytes. Sparse files are counted by actual 35854a1d5e1fSFam Zheng * allocated space. Return < 0 if error or unknown. 35864a1d5e1fSFam Zheng */ 35874a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs) 35884a1d5e1fSFam Zheng { 35894a1d5e1fSFam Zheng BlockDriver *drv = bs->drv; 35904a1d5e1fSFam Zheng if (!drv) { 35914a1d5e1fSFam Zheng return -ENOMEDIUM; 35924a1d5e1fSFam Zheng } 35934a1d5e1fSFam Zheng if (drv->bdrv_get_allocated_file_size) { 35944a1d5e1fSFam Zheng return drv->bdrv_get_allocated_file_size(bs); 35954a1d5e1fSFam Zheng } 35964a1d5e1fSFam Zheng if (bs->file) { 35974a1d5e1fSFam Zheng return bdrv_get_allocated_file_size(bs->file); 35984a1d5e1fSFam Zheng } 35994a1d5e1fSFam Zheng return -ENOTSUP; 36004a1d5e1fSFam Zheng } 36014a1d5e1fSFam Zheng 36024a1d5e1fSFam Zheng /** 360383f64091Sbellard * Length of a file in bytes. Return < 0 if error or unknown. 360483f64091Sbellard */ 360583f64091Sbellard int64_t bdrv_getlength(BlockDriverState *bs) 360683f64091Sbellard { 360783f64091Sbellard BlockDriver *drv = bs->drv; 360883f64091Sbellard if (!drv) 360919cb3738Sbellard return -ENOMEDIUM; 361051762288SStefan Hajnoczi 3611b94a2610SKevin Wolf if (drv->has_variable_length) { 3612b94a2610SKevin Wolf int ret = refresh_total_sectors(bs, bs->total_sectors); 3613b94a2610SKevin Wolf if (ret < 0) { 3614b94a2610SKevin Wolf return ret; 3615fc01f7e7Sbellard } 361646a4e4e6SStefan Hajnoczi } 361746a4e4e6SStefan Hajnoczi return bs->total_sectors * BDRV_SECTOR_SIZE; 361846a4e4e6SStefan Hajnoczi } 3619fc01f7e7Sbellard 362019cb3738Sbellard /* return 0 as number of sectors if no device present or error */ 362196b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr) 3622fc01f7e7Sbellard { 362319cb3738Sbellard int64_t length; 362419cb3738Sbellard length = bdrv_getlength(bs); 362519cb3738Sbellard if (length < 0) 362619cb3738Sbellard length = 0; 362719cb3738Sbellard else 36286ea44308SJan Kiszka length = length >> BDRV_SECTOR_BITS; 362919cb3738Sbellard *nb_sectors_ptr = length; 3630fc01f7e7Sbellard } 3631cf98951bSbellard 3632ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error, 3633ff06f5f3SPaolo Bonzini BlockdevOnError on_write_error) 3634abd7f68dSMarkus Armbruster { 3635abd7f68dSMarkus Armbruster bs->on_read_error = on_read_error; 3636abd7f68dSMarkus Armbruster bs->on_write_error = on_write_error; 3637abd7f68dSMarkus Armbruster } 3638abd7f68dSMarkus Armbruster 36391ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read) 3640abd7f68dSMarkus Armbruster { 3641abd7f68dSMarkus Armbruster return is_read ? bs->on_read_error : bs->on_write_error; 3642abd7f68dSMarkus Armbruster } 3643abd7f68dSMarkus Armbruster 36443e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error) 36453e1caa5fSPaolo Bonzini { 36463e1caa5fSPaolo Bonzini BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error; 36473e1caa5fSPaolo Bonzini 36483e1caa5fSPaolo Bonzini switch (on_err) { 36493e1caa5fSPaolo Bonzini case BLOCKDEV_ON_ERROR_ENOSPC: 36503e1caa5fSPaolo Bonzini return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT; 36513e1caa5fSPaolo Bonzini case BLOCKDEV_ON_ERROR_STOP: 36523e1caa5fSPaolo Bonzini return BDRV_ACTION_STOP; 36533e1caa5fSPaolo Bonzini case BLOCKDEV_ON_ERROR_REPORT: 36543e1caa5fSPaolo Bonzini return BDRV_ACTION_REPORT; 36553e1caa5fSPaolo Bonzini case BLOCKDEV_ON_ERROR_IGNORE: 36563e1caa5fSPaolo Bonzini return BDRV_ACTION_IGNORE; 36573e1caa5fSPaolo Bonzini default: 36583e1caa5fSPaolo Bonzini abort(); 36593e1caa5fSPaolo Bonzini } 36603e1caa5fSPaolo Bonzini } 36613e1caa5fSPaolo Bonzini 36623e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows 36633e1caa5fSPaolo Bonzini * about the error, it does not know whether an operation comes from 36643e1caa5fSPaolo Bonzini * the device or the block layer (from a job, for example). 36653e1caa5fSPaolo Bonzini */ 36663e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action, 36673e1caa5fSPaolo Bonzini bool is_read, int error) 36683e1caa5fSPaolo Bonzini { 36693e1caa5fSPaolo Bonzini assert(error >= 0); 367032c81a4aSPaolo Bonzini bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read); 36713e1caa5fSPaolo Bonzini if (action == BDRV_ACTION_STOP) { 36723e1caa5fSPaolo Bonzini vm_stop(RUN_STATE_IO_ERROR); 36733e1caa5fSPaolo Bonzini bdrv_iostatus_set_err(bs, error); 36743e1caa5fSPaolo Bonzini } 36753e1caa5fSPaolo Bonzini } 36763e1caa5fSPaolo Bonzini 3677b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs) 3678b338082bSbellard { 3679b338082bSbellard return bs->read_only; 3680b338082bSbellard } 3681b338082bSbellard 3682985a03b0Sths int bdrv_is_sg(BlockDriverState *bs) 3683985a03b0Sths { 3684985a03b0Sths return bs->sg; 3685985a03b0Sths } 3686985a03b0Sths 3687e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs) 3688e900a7b7SChristoph Hellwig { 3689e900a7b7SChristoph Hellwig return bs->enable_write_cache; 3690e900a7b7SChristoph Hellwig } 3691e900a7b7SChristoph Hellwig 3692425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce) 3693425b0148SPaolo Bonzini { 3694425b0148SPaolo Bonzini bs->enable_write_cache = wce; 369555b110f2SJeff Cody 369655b110f2SJeff Cody /* so a reopen() will preserve wce */ 369755b110f2SJeff Cody if (wce) { 369855b110f2SJeff Cody bs->open_flags |= BDRV_O_CACHE_WB; 369955b110f2SJeff Cody } else { 370055b110f2SJeff Cody bs->open_flags &= ~BDRV_O_CACHE_WB; 370155b110f2SJeff Cody } 3702425b0148SPaolo Bonzini } 3703425b0148SPaolo Bonzini 3704ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs) 3705ea2384d3Sbellard { 3706ea2384d3Sbellard if (bs->backing_hd && bs->backing_hd->encrypted) 3707ea2384d3Sbellard return 1; 3708ea2384d3Sbellard return bs->encrypted; 3709ea2384d3Sbellard } 3710ea2384d3Sbellard 3711c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs) 3712c0f4ce77Saliguori { 3713c0f4ce77Saliguori BlockDriverState *backing_hd = bs->backing_hd; 3714c0f4ce77Saliguori 3715c0f4ce77Saliguori if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key) 3716c0f4ce77Saliguori return 1; 3717c0f4ce77Saliguori return (bs->encrypted && !bs->valid_key); 3718c0f4ce77Saliguori } 3719c0f4ce77Saliguori 3720ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key) 3721ea2384d3Sbellard { 3722ea2384d3Sbellard int ret; 3723ea2384d3Sbellard if (bs->backing_hd && bs->backing_hd->encrypted) { 3724ea2384d3Sbellard ret = bdrv_set_key(bs->backing_hd, key); 3725ea2384d3Sbellard if (ret < 0) 3726ea2384d3Sbellard return ret; 3727ea2384d3Sbellard if (!bs->encrypted) 3728ea2384d3Sbellard return 0; 3729ea2384d3Sbellard } 3730fd04a2aeSShahar Havivi if (!bs->encrypted) { 3731fd04a2aeSShahar Havivi return -EINVAL; 3732fd04a2aeSShahar Havivi } else if (!bs->drv || !bs->drv->bdrv_set_key) { 3733fd04a2aeSShahar Havivi return -ENOMEDIUM; 3734fd04a2aeSShahar Havivi } 3735c0f4ce77Saliguori ret = bs->drv->bdrv_set_key(bs, key); 3736bb5fc20fSaliguori if (ret < 0) { 3737bb5fc20fSaliguori bs->valid_key = 0; 3738bb5fc20fSaliguori } else if (!bs->valid_key) { 3739bb5fc20fSaliguori bs->valid_key = 1; 3740bb5fc20fSaliguori /* call the change callback now, we skipped it on open */ 37417d4b4ba5SMarkus Armbruster bdrv_dev_change_media_cb(bs, true); 3742bb5fc20fSaliguori } 3743c0f4ce77Saliguori return ret; 3744ea2384d3Sbellard } 3745ea2384d3Sbellard 3746f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs) 3747ea2384d3Sbellard { 3748f8d6bba1SMarkus Armbruster return bs->drv ? bs->drv->format_name : NULL; 3749ea2384d3Sbellard } 3750ea2384d3Sbellard 3751ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name), 3752ea2384d3Sbellard void *opaque) 3753ea2384d3Sbellard { 3754ea2384d3Sbellard BlockDriver *drv; 3755e855e4fbSJeff Cody int count = 0; 3756e855e4fbSJeff Cody const char **formats = NULL; 3757ea2384d3Sbellard 37588a22f02aSStefan Hajnoczi QLIST_FOREACH(drv, &bdrv_drivers, list) { 3759e855e4fbSJeff Cody if (drv->format_name) { 3760e855e4fbSJeff Cody bool found = false; 3761e855e4fbSJeff Cody int i = count; 3762e855e4fbSJeff Cody while (formats && i && !found) { 3763e855e4fbSJeff Cody found = !strcmp(formats[--i], drv->format_name); 3764e855e4fbSJeff Cody } 3765e855e4fbSJeff Cody 3766e855e4fbSJeff Cody if (!found) { 3767e855e4fbSJeff Cody formats = g_realloc(formats, (count + 1) * sizeof(char *)); 3768e855e4fbSJeff Cody formats[count++] = drv->format_name; 3769ea2384d3Sbellard it(opaque, drv->format_name); 3770ea2384d3Sbellard } 3771ea2384d3Sbellard } 3772e855e4fbSJeff Cody } 3773e855e4fbSJeff Cody g_free(formats); 3774e855e4fbSJeff Cody } 3775ea2384d3Sbellard 3776dc364f4cSBenoît Canet /* This function is to find block backend bs */ 3777b338082bSbellard BlockDriverState *bdrv_find(const char *name) 3778b338082bSbellard { 3779b338082bSbellard BlockDriverState *bs; 3780b338082bSbellard 3781dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 37821b7bdbc1SStefan Hajnoczi if (!strcmp(name, bs->device_name)) { 3783b338082bSbellard return bs; 3784b338082bSbellard } 37851b7bdbc1SStefan Hajnoczi } 3786b338082bSbellard return NULL; 3787b338082bSbellard } 3788b338082bSbellard 3789dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */ 3790dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name) 3791dc364f4cSBenoît Canet { 3792dc364f4cSBenoît Canet BlockDriverState *bs; 3793dc364f4cSBenoît Canet 3794dc364f4cSBenoît Canet assert(node_name); 3795dc364f4cSBenoît Canet 3796dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) { 3797dc364f4cSBenoît Canet if (!strcmp(node_name, bs->node_name)) { 3798dc364f4cSBenoît Canet return bs; 3799dc364f4cSBenoît Canet } 3800dc364f4cSBenoît Canet } 3801dc364f4cSBenoît Canet return NULL; 3802dc364f4cSBenoît Canet } 3803dc364f4cSBenoît Canet 3804c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */ 3805c13163fbSBenoît Canet BlockDeviceInfoList *bdrv_named_nodes_list(void) 3806c13163fbSBenoît Canet { 3807c13163fbSBenoît Canet BlockDeviceInfoList *list, *entry; 3808c13163fbSBenoît Canet BlockDriverState *bs; 3809c13163fbSBenoît Canet 3810c13163fbSBenoît Canet list = NULL; 3811c13163fbSBenoît Canet QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) { 3812c13163fbSBenoît Canet entry = g_malloc0(sizeof(*entry)); 3813c13163fbSBenoît Canet entry->value = bdrv_block_device_info(bs); 3814c13163fbSBenoît Canet entry->next = list; 3815c13163fbSBenoît Canet list = entry; 3816c13163fbSBenoît Canet } 3817c13163fbSBenoît Canet 3818c13163fbSBenoît Canet return list; 3819c13163fbSBenoît Canet } 3820c13163fbSBenoît Canet 382112d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device, 382212d3ba82SBenoît Canet const char *node_name, 382312d3ba82SBenoît Canet Error **errp) 382412d3ba82SBenoît Canet { 382512d3ba82SBenoît Canet BlockDriverState *bs = NULL; 382612d3ba82SBenoît Canet 382712d3ba82SBenoît Canet if (device) { 382812d3ba82SBenoît Canet bs = bdrv_find(device); 382912d3ba82SBenoît Canet 3830dd67fa50SBenoît Canet if (bs) { 383112d3ba82SBenoît Canet return bs; 383212d3ba82SBenoît Canet } 3833dd67fa50SBenoît Canet } 383412d3ba82SBenoît Canet 3835dd67fa50SBenoît Canet if (node_name) { 383612d3ba82SBenoît Canet bs = bdrv_find_node(node_name); 383712d3ba82SBenoît Canet 3838dd67fa50SBenoît Canet if (bs) { 3839dd67fa50SBenoît Canet return bs; 3840dd67fa50SBenoît Canet } 384112d3ba82SBenoît Canet } 384212d3ba82SBenoît Canet 3843dd67fa50SBenoît Canet error_setg(errp, "Cannot find device=%s nor node_name=%s", 3844dd67fa50SBenoît Canet device ? device : "", 3845dd67fa50SBenoît Canet node_name ? node_name : ""); 3846dd67fa50SBenoît Canet return NULL; 384712d3ba82SBenoît Canet } 384812d3ba82SBenoît Canet 38492f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs) 38502f399b0aSMarkus Armbruster { 38512f399b0aSMarkus Armbruster if (!bs) { 38522f399b0aSMarkus Armbruster return QTAILQ_FIRST(&bdrv_states); 38532f399b0aSMarkus Armbruster } 3854dc364f4cSBenoît Canet return QTAILQ_NEXT(bs, device_list); 38552f399b0aSMarkus Armbruster } 38562f399b0aSMarkus Armbruster 385751de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque) 385881d0912dSbellard { 385981d0912dSbellard BlockDriverState *bs; 386081d0912dSbellard 3861dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 386251de9760Saliguori it(opaque, bs); 386381d0912dSbellard } 386481d0912dSbellard } 386581d0912dSbellard 3866ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs) 3867ea2384d3Sbellard { 3868ea2384d3Sbellard return bs->device_name; 3869ea2384d3Sbellard } 3870ea2384d3Sbellard 3871c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs) 3872c8433287SMarkus Armbruster { 3873c8433287SMarkus Armbruster return bs->open_flags; 3874c8433287SMarkus Armbruster } 3875c8433287SMarkus Armbruster 3876f0f0fdfeSKevin Wolf int bdrv_flush_all(void) 3877c6ca28d6Saliguori { 3878c6ca28d6Saliguori BlockDriverState *bs; 3879f0f0fdfeSKevin Wolf int result = 0; 3880c6ca28d6Saliguori 3881dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 3882ed78cda3SStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 3883ed78cda3SStefan Hajnoczi int ret; 3884ed78cda3SStefan Hajnoczi 3885ed78cda3SStefan Hajnoczi aio_context_acquire(aio_context); 3886ed78cda3SStefan Hajnoczi ret = bdrv_flush(bs); 3887f0f0fdfeSKevin Wolf if (ret < 0 && !result) { 3888f0f0fdfeSKevin Wolf result = ret; 3889c6ca28d6Saliguori } 3890ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 38911b7bdbc1SStefan Hajnoczi } 3892c6ca28d6Saliguori 3893f0f0fdfeSKevin Wolf return result; 3894f0f0fdfeSKevin Wolf } 3895f0f0fdfeSKevin Wolf 38963ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs) 38973ac21627SPeter Lieven { 38983ac21627SPeter Lieven return 1; 38993ac21627SPeter Lieven } 39003ac21627SPeter Lieven 3901f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs) 3902f2feebbdSKevin Wolf { 3903f2feebbdSKevin Wolf assert(bs->drv); 3904f2feebbdSKevin Wolf 390511212d8fSPaolo Bonzini /* If BS is a copy on write image, it is initialized to 390611212d8fSPaolo Bonzini the contents of the base image, which may not be zeroes. */ 390711212d8fSPaolo Bonzini if (bs->backing_hd) { 390811212d8fSPaolo Bonzini return 0; 390911212d8fSPaolo Bonzini } 3910336c1c12SKevin Wolf if (bs->drv->bdrv_has_zero_init) { 3911336c1c12SKevin Wolf return bs->drv->bdrv_has_zero_init(bs); 3912f2feebbdSKevin Wolf } 3913f2feebbdSKevin Wolf 39143ac21627SPeter Lieven /* safe default */ 39153ac21627SPeter Lieven return 0; 3916f2feebbdSKevin Wolf } 3917f2feebbdSKevin Wolf 39184ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs) 39194ce78691SPeter Lieven { 39204ce78691SPeter Lieven BlockDriverInfo bdi; 39214ce78691SPeter Lieven 39224ce78691SPeter Lieven if (bs->backing_hd) { 39234ce78691SPeter Lieven return false; 39244ce78691SPeter Lieven } 39254ce78691SPeter Lieven 39264ce78691SPeter Lieven if (bdrv_get_info(bs, &bdi) == 0) { 39274ce78691SPeter Lieven return bdi.unallocated_blocks_are_zero; 39284ce78691SPeter Lieven } 39294ce78691SPeter Lieven 39304ce78691SPeter Lieven return false; 39314ce78691SPeter Lieven } 39324ce78691SPeter Lieven 39334ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs) 39344ce78691SPeter Lieven { 39354ce78691SPeter Lieven BlockDriverInfo bdi; 39364ce78691SPeter Lieven 39374ce78691SPeter Lieven if (bs->backing_hd || !(bs->open_flags & BDRV_O_UNMAP)) { 39384ce78691SPeter Lieven return false; 39394ce78691SPeter Lieven } 39404ce78691SPeter Lieven 39414ce78691SPeter Lieven if (bdrv_get_info(bs, &bdi) == 0) { 39424ce78691SPeter Lieven return bdi.can_write_zeroes_with_unmap; 39434ce78691SPeter Lieven } 39444ce78691SPeter Lieven 39454ce78691SPeter Lieven return false; 39464ce78691SPeter Lieven } 39474ce78691SPeter Lieven 3948b6b8a333SPaolo Bonzini typedef struct BdrvCoGetBlockStatusData { 3949376ae3f1SStefan Hajnoczi BlockDriverState *bs; 3950b35b2bbaSMiroslav Rezanina BlockDriverState *base; 3951376ae3f1SStefan Hajnoczi int64_t sector_num; 3952376ae3f1SStefan Hajnoczi int nb_sectors; 3953376ae3f1SStefan Hajnoczi int *pnum; 3954b6b8a333SPaolo Bonzini int64_t ret; 3955376ae3f1SStefan Hajnoczi bool done; 3956b6b8a333SPaolo Bonzini } BdrvCoGetBlockStatusData; 3957376ae3f1SStefan Hajnoczi 3958f58c7b35Sths /* 3959f58c7b35Sths * Returns true iff the specified sector is present in the disk image. Drivers 3960f58c7b35Sths * not implementing the functionality are assumed to not support backing files, 3961f58c7b35Sths * hence all their sectors are reported as allocated. 3962f58c7b35Sths * 3963bd9533e3SStefan Hajnoczi * If 'sector_num' is beyond the end of the disk image the return value is 0 3964bd9533e3SStefan Hajnoczi * and 'pnum' is set to 0. 3965bd9533e3SStefan Hajnoczi * 3966f58c7b35Sths * 'pnum' is set to the number of sectors (including and immediately following 3967f58c7b35Sths * the specified sector) that are known to be in the same 3968f58c7b35Sths * allocated/unallocated state. 3969f58c7b35Sths * 3970bd9533e3SStefan Hajnoczi * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes 3971bd9533e3SStefan Hajnoczi * beyond the end of the disk image it will be clamped. 3972f58c7b35Sths */ 3973b6b8a333SPaolo Bonzini static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs, 3974bdad13b9SPaolo Bonzini int64_t sector_num, 3975060f51c9SStefan Hajnoczi int nb_sectors, int *pnum) 3976f58c7b35Sths { 3977617ccb46SPaolo Bonzini int64_t length; 3978f58c7b35Sths int64_t n; 39795daa74a6SPaolo Bonzini int64_t ret, ret2; 3980bd9533e3SStefan Hajnoczi 3981617ccb46SPaolo Bonzini length = bdrv_getlength(bs); 3982617ccb46SPaolo Bonzini if (length < 0) { 3983617ccb46SPaolo Bonzini return length; 3984617ccb46SPaolo Bonzini } 3985617ccb46SPaolo Bonzini 3986617ccb46SPaolo Bonzini if (sector_num >= (length >> BDRV_SECTOR_BITS)) { 39876aebab14SStefan Hajnoczi *pnum = 0; 39886aebab14SStefan Hajnoczi return 0; 39896aebab14SStefan Hajnoczi } 3990bd9533e3SStefan Hajnoczi 39916aebab14SStefan Hajnoczi n = bs->total_sectors - sector_num; 3992bd9533e3SStefan Hajnoczi if (n < nb_sectors) { 3993bd9533e3SStefan Hajnoczi nb_sectors = n; 3994bd9533e3SStefan Hajnoczi } 3995bd9533e3SStefan Hajnoczi 3996b6b8a333SPaolo Bonzini if (!bs->drv->bdrv_co_get_block_status) { 3997bd9533e3SStefan Hajnoczi *pnum = nb_sectors; 3998e88ae226SKevin Wolf ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED; 3999918e92d7SPaolo Bonzini if (bs->drv->protocol_name) { 4000918e92d7SPaolo Bonzini ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE); 4001918e92d7SPaolo Bonzini } 4002918e92d7SPaolo Bonzini return ret; 40036aebab14SStefan Hajnoczi } 40046aebab14SStefan Hajnoczi 4005415b5b01SPaolo Bonzini ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum); 4006415b5b01SPaolo Bonzini if (ret < 0) { 40073e0a233dSPeter Lieven *pnum = 0; 4008415b5b01SPaolo Bonzini return ret; 4009415b5b01SPaolo Bonzini } 4010415b5b01SPaolo Bonzini 401192bc50a5SPeter Lieven if (ret & BDRV_BLOCK_RAW) { 401292bc50a5SPeter Lieven assert(ret & BDRV_BLOCK_OFFSET_VALID); 401392bc50a5SPeter Lieven return bdrv_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS, 401492bc50a5SPeter Lieven *pnum, pnum); 401592bc50a5SPeter Lieven } 401692bc50a5SPeter Lieven 4017e88ae226SKevin Wolf if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) { 4018e88ae226SKevin Wolf ret |= BDRV_BLOCK_ALLOCATED; 4019e88ae226SKevin Wolf } 4020e88ae226SKevin Wolf 4021c3d86884SPeter Lieven if (!(ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO)) { 4022c3d86884SPeter Lieven if (bdrv_unallocated_blocks_are_zero(bs)) { 4023415b5b01SPaolo Bonzini ret |= BDRV_BLOCK_ZERO; 40241f9db224SPeter Lieven } else if (bs->backing_hd) { 4025f0ad5712SPaolo Bonzini BlockDriverState *bs2 = bs->backing_hd; 4026f0ad5712SPaolo Bonzini int64_t length2 = bdrv_getlength(bs2); 4027f0ad5712SPaolo Bonzini if (length2 >= 0 && sector_num >= (length2 >> BDRV_SECTOR_BITS)) { 4028f0ad5712SPaolo Bonzini ret |= BDRV_BLOCK_ZERO; 4029f0ad5712SPaolo Bonzini } 4030f0ad5712SPaolo Bonzini } 4031415b5b01SPaolo Bonzini } 40325daa74a6SPaolo Bonzini 40335daa74a6SPaolo Bonzini if (bs->file && 40345daa74a6SPaolo Bonzini (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) && 40355daa74a6SPaolo Bonzini (ret & BDRV_BLOCK_OFFSET_VALID)) { 40365daa74a6SPaolo Bonzini ret2 = bdrv_co_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS, 40375daa74a6SPaolo Bonzini *pnum, pnum); 40385daa74a6SPaolo Bonzini if (ret2 >= 0) { 40395daa74a6SPaolo Bonzini /* Ignore errors. This is just providing extra information, it 40405daa74a6SPaolo Bonzini * is useful but not necessary. 40415daa74a6SPaolo Bonzini */ 40425daa74a6SPaolo Bonzini ret |= (ret2 & BDRV_BLOCK_ZERO); 40435daa74a6SPaolo Bonzini } 40445daa74a6SPaolo Bonzini } 40455daa74a6SPaolo Bonzini 4046415b5b01SPaolo Bonzini return ret; 4047060f51c9SStefan Hajnoczi } 4048060f51c9SStefan Hajnoczi 4049b6b8a333SPaolo Bonzini /* Coroutine wrapper for bdrv_get_block_status() */ 4050b6b8a333SPaolo Bonzini static void coroutine_fn bdrv_get_block_status_co_entry(void *opaque) 4051060f51c9SStefan Hajnoczi { 4052b6b8a333SPaolo Bonzini BdrvCoGetBlockStatusData *data = opaque; 4053060f51c9SStefan Hajnoczi BlockDriverState *bs = data->bs; 4054060f51c9SStefan Hajnoczi 4055b6b8a333SPaolo Bonzini data->ret = bdrv_co_get_block_status(bs, data->sector_num, data->nb_sectors, 4056060f51c9SStefan Hajnoczi data->pnum); 4057060f51c9SStefan Hajnoczi data->done = true; 4058060f51c9SStefan Hajnoczi } 4059060f51c9SStefan Hajnoczi 4060060f51c9SStefan Hajnoczi /* 4061b6b8a333SPaolo Bonzini * Synchronous wrapper around bdrv_co_get_block_status(). 4062060f51c9SStefan Hajnoczi * 4063b6b8a333SPaolo Bonzini * See bdrv_co_get_block_status() for details. 4064060f51c9SStefan Hajnoczi */ 4065b6b8a333SPaolo Bonzini int64_t bdrv_get_block_status(BlockDriverState *bs, int64_t sector_num, 4066b6b8a333SPaolo Bonzini int nb_sectors, int *pnum) 4067060f51c9SStefan Hajnoczi { 4068376ae3f1SStefan Hajnoczi Coroutine *co; 4069b6b8a333SPaolo Bonzini BdrvCoGetBlockStatusData data = { 4070376ae3f1SStefan Hajnoczi .bs = bs, 4071376ae3f1SStefan Hajnoczi .sector_num = sector_num, 4072376ae3f1SStefan Hajnoczi .nb_sectors = nb_sectors, 4073376ae3f1SStefan Hajnoczi .pnum = pnum, 4074376ae3f1SStefan Hajnoczi .done = false, 4075376ae3f1SStefan Hajnoczi }; 4076376ae3f1SStefan Hajnoczi 4077bdad13b9SPaolo Bonzini if (qemu_in_coroutine()) { 4078bdad13b9SPaolo Bonzini /* Fast-path if already in coroutine context */ 4079b6b8a333SPaolo Bonzini bdrv_get_block_status_co_entry(&data); 4080bdad13b9SPaolo Bonzini } else { 40812572b37aSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 40822572b37aSStefan Hajnoczi 4083b6b8a333SPaolo Bonzini co = qemu_coroutine_create(bdrv_get_block_status_co_entry); 4084376ae3f1SStefan Hajnoczi qemu_coroutine_enter(co, &data); 4085376ae3f1SStefan Hajnoczi while (!data.done) { 40862572b37aSStefan Hajnoczi aio_poll(aio_context, true); 4087376ae3f1SStefan Hajnoczi } 4088bdad13b9SPaolo Bonzini } 4089376ae3f1SStefan Hajnoczi return data.ret; 4090376ae3f1SStefan Hajnoczi } 4091f58c7b35Sths 4092b6b8a333SPaolo Bonzini int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, 4093b6b8a333SPaolo Bonzini int nb_sectors, int *pnum) 4094b6b8a333SPaolo Bonzini { 40954333bb71SPaolo Bonzini int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum); 40964333bb71SPaolo Bonzini if (ret < 0) { 40974333bb71SPaolo Bonzini return ret; 40984333bb71SPaolo Bonzini } 4099e88ae226SKevin Wolf return (ret & BDRV_BLOCK_ALLOCATED); 4100b6b8a333SPaolo Bonzini } 4101b6b8a333SPaolo Bonzini 4102188a7bbfSPaolo Bonzini /* 4103188a7bbfSPaolo Bonzini * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP] 4104188a7bbfSPaolo Bonzini * 4105188a7bbfSPaolo Bonzini * Return true if the given sector is allocated in any image between 4106188a7bbfSPaolo Bonzini * BASE and TOP (inclusive). BASE can be NULL to check if the given 4107188a7bbfSPaolo Bonzini * sector is allocated in any image of the chain. Return false otherwise. 4108188a7bbfSPaolo Bonzini * 4109188a7bbfSPaolo Bonzini * 'pnum' is set to the number of sectors (including and immediately following 4110188a7bbfSPaolo Bonzini * the specified sector) that are known to be in the same 4111188a7bbfSPaolo Bonzini * allocated/unallocated state. 4112188a7bbfSPaolo Bonzini * 4113188a7bbfSPaolo Bonzini */ 41144f578637SPaolo Bonzini int bdrv_is_allocated_above(BlockDriverState *top, 4115188a7bbfSPaolo Bonzini BlockDriverState *base, 4116188a7bbfSPaolo Bonzini int64_t sector_num, 4117188a7bbfSPaolo Bonzini int nb_sectors, int *pnum) 4118188a7bbfSPaolo Bonzini { 4119188a7bbfSPaolo Bonzini BlockDriverState *intermediate; 4120188a7bbfSPaolo Bonzini int ret, n = nb_sectors; 4121188a7bbfSPaolo Bonzini 4122188a7bbfSPaolo Bonzini intermediate = top; 4123188a7bbfSPaolo Bonzini while (intermediate && intermediate != base) { 4124188a7bbfSPaolo Bonzini int pnum_inter; 4125bdad13b9SPaolo Bonzini ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors, 4126188a7bbfSPaolo Bonzini &pnum_inter); 4127188a7bbfSPaolo Bonzini if (ret < 0) { 4128188a7bbfSPaolo Bonzini return ret; 4129188a7bbfSPaolo Bonzini } else if (ret) { 4130188a7bbfSPaolo Bonzini *pnum = pnum_inter; 4131188a7bbfSPaolo Bonzini return 1; 4132188a7bbfSPaolo Bonzini } 4133188a7bbfSPaolo Bonzini 4134188a7bbfSPaolo Bonzini /* 4135188a7bbfSPaolo Bonzini * [sector_num, nb_sectors] is unallocated on top but intermediate 4136188a7bbfSPaolo Bonzini * might have 4137188a7bbfSPaolo Bonzini * 4138188a7bbfSPaolo Bonzini * [sector_num+x, nr_sectors] allocated. 4139188a7bbfSPaolo Bonzini */ 414063ba17d3SVishvananda Ishaya if (n > pnum_inter && 414163ba17d3SVishvananda Ishaya (intermediate == top || 414263ba17d3SVishvananda Ishaya sector_num + pnum_inter < intermediate->total_sectors)) { 4143188a7bbfSPaolo Bonzini n = pnum_inter; 4144188a7bbfSPaolo Bonzini } 4145188a7bbfSPaolo Bonzini 4146188a7bbfSPaolo Bonzini intermediate = intermediate->backing_hd; 4147188a7bbfSPaolo Bonzini } 4148188a7bbfSPaolo Bonzini 4149188a7bbfSPaolo Bonzini *pnum = n; 4150188a7bbfSPaolo Bonzini return 0; 4151188a7bbfSPaolo Bonzini } 4152188a7bbfSPaolo Bonzini 4153045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs) 4154045df330Saliguori { 4155045df330Saliguori if (bs->backing_hd && bs->backing_hd->encrypted) 4156045df330Saliguori return bs->backing_file; 4157045df330Saliguori else if (bs->encrypted) 4158045df330Saliguori return bs->filename; 4159045df330Saliguori else 4160045df330Saliguori return NULL; 4161045df330Saliguori } 4162045df330Saliguori 416383f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs, 416483f64091Sbellard char *filename, int filename_size) 416583f64091Sbellard { 416683f64091Sbellard pstrcpy(filename, filename_size, bs->backing_file); 416783f64091Sbellard } 416883f64091Sbellard 4169faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num, 4170faea38e7Sbellard const uint8_t *buf, int nb_sectors) 4171faea38e7Sbellard { 4172faea38e7Sbellard BlockDriver *drv = bs->drv; 4173faea38e7Sbellard if (!drv) 417419cb3738Sbellard return -ENOMEDIUM; 4175faea38e7Sbellard if (!drv->bdrv_write_compressed) 4176faea38e7Sbellard return -ENOTSUP; 4177fbb7b4e0SKevin Wolf if (bdrv_check_request(bs, sector_num, nb_sectors)) 4178fbb7b4e0SKevin Wolf return -EIO; 41797cd1e32aSlirans@il.ibm.com 4180e4654d2dSFam Zheng assert(QLIST_EMPTY(&bs->dirty_bitmaps)); 41817cd1e32aSlirans@il.ibm.com 4182faea38e7Sbellard return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors); 4183faea38e7Sbellard } 4184faea38e7Sbellard 4185faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi) 4186faea38e7Sbellard { 4187faea38e7Sbellard BlockDriver *drv = bs->drv; 4188faea38e7Sbellard if (!drv) 418919cb3738Sbellard return -ENOMEDIUM; 4190faea38e7Sbellard if (!drv->bdrv_get_info) 4191faea38e7Sbellard return -ENOTSUP; 4192faea38e7Sbellard memset(bdi, 0, sizeof(*bdi)); 4193faea38e7Sbellard return drv->bdrv_get_info(bs, bdi); 4194faea38e7Sbellard } 4195faea38e7Sbellard 4196eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs) 4197eae041feSMax Reitz { 4198eae041feSMax Reitz BlockDriver *drv = bs->drv; 4199eae041feSMax Reitz if (drv && drv->bdrv_get_specific_info) { 4200eae041feSMax Reitz return drv->bdrv_get_specific_info(bs); 4201eae041feSMax Reitz } 4202eae041feSMax Reitz return NULL; 4203eae041feSMax Reitz } 4204eae041feSMax Reitz 420545566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf, 420645566e9cSChristoph Hellwig int64_t pos, int size) 4207178e08a5Saliguori { 4208cf8074b3SKevin Wolf QEMUIOVector qiov; 4209cf8074b3SKevin Wolf struct iovec iov = { 4210cf8074b3SKevin Wolf .iov_base = (void *) buf, 4211cf8074b3SKevin Wolf .iov_len = size, 4212cf8074b3SKevin Wolf }; 4213cf8074b3SKevin Wolf 4214cf8074b3SKevin Wolf qemu_iovec_init_external(&qiov, &iov, 1); 4215cf8074b3SKevin Wolf return bdrv_writev_vmstate(bs, &qiov, pos); 4216cf8074b3SKevin Wolf } 4217cf8074b3SKevin Wolf 4218cf8074b3SKevin Wolf int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos) 4219cf8074b3SKevin Wolf { 4220178e08a5Saliguori BlockDriver *drv = bs->drv; 4221cf8074b3SKevin Wolf 4222cf8074b3SKevin Wolf if (!drv) { 4223178e08a5Saliguori return -ENOMEDIUM; 4224cf8074b3SKevin Wolf } else if (drv->bdrv_save_vmstate) { 4225cf8074b3SKevin Wolf return drv->bdrv_save_vmstate(bs, qiov, pos); 4226cf8074b3SKevin Wolf } else if (bs->file) { 4227cf8074b3SKevin Wolf return bdrv_writev_vmstate(bs->file, qiov, pos); 4228cf8074b3SKevin Wolf } 4229cf8074b3SKevin Wolf 42307cdb1f6dSMORITA Kazutaka return -ENOTSUP; 4231178e08a5Saliguori } 4232178e08a5Saliguori 423345566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf, 423445566e9cSChristoph Hellwig int64_t pos, int size) 4235178e08a5Saliguori { 4236178e08a5Saliguori BlockDriver *drv = bs->drv; 4237178e08a5Saliguori if (!drv) 4238178e08a5Saliguori return -ENOMEDIUM; 42397cdb1f6dSMORITA Kazutaka if (drv->bdrv_load_vmstate) 424045566e9cSChristoph Hellwig return drv->bdrv_load_vmstate(bs, buf, pos, size); 42417cdb1f6dSMORITA Kazutaka if (bs->file) 42427cdb1f6dSMORITA Kazutaka return bdrv_load_vmstate(bs->file, buf, pos, size); 42437cdb1f6dSMORITA Kazutaka return -ENOTSUP; 4244178e08a5Saliguori } 4245178e08a5Saliguori 42468b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event) 42478b9b0cc2SKevin Wolf { 4248bf736fe3SKevin Wolf if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) { 42498b9b0cc2SKevin Wolf return; 42508b9b0cc2SKevin Wolf } 42518b9b0cc2SKevin Wolf 4252bf736fe3SKevin Wolf bs->drv->bdrv_debug_event(bs, event); 425341c695c7SKevin Wolf } 42548b9b0cc2SKevin Wolf 425541c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event, 425641c695c7SKevin Wolf const char *tag) 425741c695c7SKevin Wolf { 425841c695c7SKevin Wolf while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) { 425941c695c7SKevin Wolf bs = bs->file; 426041c695c7SKevin Wolf } 426141c695c7SKevin Wolf 426241c695c7SKevin Wolf if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) { 426341c695c7SKevin Wolf return bs->drv->bdrv_debug_breakpoint(bs, event, tag); 426441c695c7SKevin Wolf } 426541c695c7SKevin Wolf 426641c695c7SKevin Wolf return -ENOTSUP; 426741c695c7SKevin Wolf } 426841c695c7SKevin Wolf 42694cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag) 42704cc70e93SFam Zheng { 42714cc70e93SFam Zheng while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) { 42724cc70e93SFam Zheng bs = bs->file; 42734cc70e93SFam Zheng } 42744cc70e93SFam Zheng 42754cc70e93SFam Zheng if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) { 42764cc70e93SFam Zheng return bs->drv->bdrv_debug_remove_breakpoint(bs, tag); 42774cc70e93SFam Zheng } 42784cc70e93SFam Zheng 42794cc70e93SFam Zheng return -ENOTSUP; 42804cc70e93SFam Zheng } 42814cc70e93SFam Zheng 428241c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag) 428341c695c7SKevin Wolf { 4284938789eaSMax Reitz while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) { 428541c695c7SKevin Wolf bs = bs->file; 428641c695c7SKevin Wolf } 428741c695c7SKevin Wolf 428841c695c7SKevin Wolf if (bs && bs->drv && bs->drv->bdrv_debug_resume) { 428941c695c7SKevin Wolf return bs->drv->bdrv_debug_resume(bs, tag); 429041c695c7SKevin Wolf } 429141c695c7SKevin Wolf 429241c695c7SKevin Wolf return -ENOTSUP; 429341c695c7SKevin Wolf } 429441c695c7SKevin Wolf 429541c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag) 429641c695c7SKevin Wolf { 429741c695c7SKevin Wolf while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) { 429841c695c7SKevin Wolf bs = bs->file; 429941c695c7SKevin Wolf } 430041c695c7SKevin Wolf 430141c695c7SKevin Wolf if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) { 430241c695c7SKevin Wolf return bs->drv->bdrv_debug_is_suspended(bs, tag); 430341c695c7SKevin Wolf } 430441c695c7SKevin Wolf 430541c695c7SKevin Wolf return false; 43068b9b0cc2SKevin Wolf } 43078b9b0cc2SKevin Wolf 4308199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs) 4309199630b6SBlue Swirl { 4310199630b6SBlue Swirl return !!(bs->open_flags & BDRV_O_SNAPSHOT); 4311199630b6SBlue Swirl } 4312199630b6SBlue Swirl 4313b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol. If it is 4314b1b1d783SJeff Cody * relative, it must be relative to the chain. So, passing in bs->filename 4315b1b1d783SJeff Cody * from a BDS as backing_file should not be done, as that may be relative to 4316b1b1d783SJeff Cody * the CWD rather than the chain. */ 4317e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs, 4318e8a6bb9cSMarcelo Tosatti const char *backing_file) 4319e8a6bb9cSMarcelo Tosatti { 4320b1b1d783SJeff Cody char *filename_full = NULL; 4321b1b1d783SJeff Cody char *backing_file_full = NULL; 4322b1b1d783SJeff Cody char *filename_tmp = NULL; 4323b1b1d783SJeff Cody int is_protocol = 0; 4324b1b1d783SJeff Cody BlockDriverState *curr_bs = NULL; 4325b1b1d783SJeff Cody BlockDriverState *retval = NULL; 4326b1b1d783SJeff Cody 4327b1b1d783SJeff Cody if (!bs || !bs->drv || !backing_file) { 4328e8a6bb9cSMarcelo Tosatti return NULL; 4329e8a6bb9cSMarcelo Tosatti } 4330e8a6bb9cSMarcelo Tosatti 4331b1b1d783SJeff Cody filename_full = g_malloc(PATH_MAX); 4332b1b1d783SJeff Cody backing_file_full = g_malloc(PATH_MAX); 4333b1b1d783SJeff Cody filename_tmp = g_malloc(PATH_MAX); 4334b1b1d783SJeff Cody 4335b1b1d783SJeff Cody is_protocol = path_has_protocol(backing_file); 4336b1b1d783SJeff Cody 4337b1b1d783SJeff Cody for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) { 4338b1b1d783SJeff Cody 4339b1b1d783SJeff Cody /* If either of the filename paths is actually a protocol, then 4340b1b1d783SJeff Cody * compare unmodified paths; otherwise make paths relative */ 4341b1b1d783SJeff Cody if (is_protocol || path_has_protocol(curr_bs->backing_file)) { 4342b1b1d783SJeff Cody if (strcmp(backing_file, curr_bs->backing_file) == 0) { 4343b1b1d783SJeff Cody retval = curr_bs->backing_hd; 4344b1b1d783SJeff Cody break; 4345b1b1d783SJeff Cody } 4346e8a6bb9cSMarcelo Tosatti } else { 4347b1b1d783SJeff Cody /* If not an absolute filename path, make it relative to the current 4348b1b1d783SJeff Cody * image's filename path */ 4349b1b1d783SJeff Cody path_combine(filename_tmp, PATH_MAX, curr_bs->filename, 4350b1b1d783SJeff Cody backing_file); 4351b1b1d783SJeff Cody 4352b1b1d783SJeff Cody /* We are going to compare absolute pathnames */ 4353b1b1d783SJeff Cody if (!realpath(filename_tmp, filename_full)) { 4354b1b1d783SJeff Cody continue; 4355b1b1d783SJeff Cody } 4356b1b1d783SJeff Cody 4357b1b1d783SJeff Cody /* We need to make sure the backing filename we are comparing against 4358b1b1d783SJeff Cody * is relative to the current image filename (or absolute) */ 4359b1b1d783SJeff Cody path_combine(filename_tmp, PATH_MAX, curr_bs->filename, 4360b1b1d783SJeff Cody curr_bs->backing_file); 4361b1b1d783SJeff Cody 4362b1b1d783SJeff Cody if (!realpath(filename_tmp, backing_file_full)) { 4363b1b1d783SJeff Cody continue; 4364b1b1d783SJeff Cody } 4365b1b1d783SJeff Cody 4366b1b1d783SJeff Cody if (strcmp(backing_file_full, filename_full) == 0) { 4367b1b1d783SJeff Cody retval = curr_bs->backing_hd; 4368b1b1d783SJeff Cody break; 4369b1b1d783SJeff Cody } 4370e8a6bb9cSMarcelo Tosatti } 4371e8a6bb9cSMarcelo Tosatti } 4372e8a6bb9cSMarcelo Tosatti 4373b1b1d783SJeff Cody g_free(filename_full); 4374b1b1d783SJeff Cody g_free(backing_file_full); 4375b1b1d783SJeff Cody g_free(filename_tmp); 4376b1b1d783SJeff Cody return retval; 4377e8a6bb9cSMarcelo Tosatti } 4378e8a6bb9cSMarcelo Tosatti 4379f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs) 4380f198fd1cSBenoît Canet { 4381f198fd1cSBenoît Canet if (!bs->drv) { 4382f198fd1cSBenoît Canet return 0; 4383f198fd1cSBenoît Canet } 4384f198fd1cSBenoît Canet 4385f198fd1cSBenoît Canet if (!bs->backing_hd) { 4386f198fd1cSBenoît Canet return 0; 4387f198fd1cSBenoît Canet } 4388f198fd1cSBenoît Canet 4389f198fd1cSBenoît Canet return 1 + bdrv_get_backing_file_depth(bs->backing_hd); 4390f198fd1cSBenoît Canet } 4391f198fd1cSBenoît Canet 439279fac568SJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs) 439379fac568SJeff Cody { 439479fac568SJeff Cody BlockDriverState *curr_bs = NULL; 439579fac568SJeff Cody 439679fac568SJeff Cody if (!bs) { 439779fac568SJeff Cody return NULL; 439879fac568SJeff Cody } 439979fac568SJeff Cody 440079fac568SJeff Cody curr_bs = bs; 440179fac568SJeff Cody 440279fac568SJeff Cody while (curr_bs->backing_hd) { 440379fac568SJeff Cody curr_bs = curr_bs->backing_hd; 440479fac568SJeff Cody } 440579fac568SJeff Cody return curr_bs; 440679fac568SJeff Cody } 440779fac568SJeff Cody 4408ea2384d3Sbellard /**************************************************************/ 440983f64091Sbellard /* async I/Os */ 4410ea2384d3Sbellard 44113b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num, 4412f141eafeSaliguori QEMUIOVector *qiov, int nb_sectors, 441383f64091Sbellard BlockDriverCompletionFunc *cb, void *opaque) 4414ea2384d3Sbellard { 4415bbf0a440SStefan Hajnoczi trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque); 4416bbf0a440SStefan Hajnoczi 4417d20d9b7cSPaolo Bonzini return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0, 44188c5873d6SStefan Hajnoczi cb, opaque, false); 441983f64091Sbellard } 442083f64091Sbellard 4421f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num, 4422f141eafeSaliguori QEMUIOVector *qiov, int nb_sectors, 442383f64091Sbellard BlockDriverCompletionFunc *cb, void *opaque) 44247674e7bfSbellard { 4425bbf0a440SStefan Hajnoczi trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque); 4426bbf0a440SStefan Hajnoczi 4427d20d9b7cSPaolo Bonzini return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0, 44288c5873d6SStefan Hajnoczi cb, opaque, true); 442983f64091Sbellard } 443083f64091Sbellard 4431d5ef94d4SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs, 4432d5ef94d4SPaolo Bonzini int64_t sector_num, int nb_sectors, BdrvRequestFlags flags, 4433d5ef94d4SPaolo Bonzini BlockDriverCompletionFunc *cb, void *opaque) 4434d5ef94d4SPaolo Bonzini { 4435d5ef94d4SPaolo Bonzini trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque); 4436d5ef94d4SPaolo Bonzini 4437d5ef94d4SPaolo Bonzini return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors, 4438d5ef94d4SPaolo Bonzini BDRV_REQ_ZERO_WRITE | flags, 4439d5ef94d4SPaolo Bonzini cb, opaque, true); 4440d5ef94d4SPaolo Bonzini } 4441d5ef94d4SPaolo Bonzini 444240b4f539SKevin Wolf 444340b4f539SKevin Wolf typedef struct MultiwriteCB { 444440b4f539SKevin Wolf int error; 444540b4f539SKevin Wolf int num_requests; 444640b4f539SKevin Wolf int num_callbacks; 444740b4f539SKevin Wolf struct { 444840b4f539SKevin Wolf BlockDriverCompletionFunc *cb; 444940b4f539SKevin Wolf void *opaque; 445040b4f539SKevin Wolf QEMUIOVector *free_qiov; 445140b4f539SKevin Wolf } callbacks[]; 445240b4f539SKevin Wolf } MultiwriteCB; 445340b4f539SKevin Wolf 445440b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb) 445540b4f539SKevin Wolf { 445640b4f539SKevin Wolf int i; 445740b4f539SKevin Wolf 445840b4f539SKevin Wolf for (i = 0; i < mcb->num_callbacks; i++) { 445940b4f539SKevin Wolf mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error); 44601e1ea48dSStefan Hajnoczi if (mcb->callbacks[i].free_qiov) { 44611e1ea48dSStefan Hajnoczi qemu_iovec_destroy(mcb->callbacks[i].free_qiov); 44621e1ea48dSStefan Hajnoczi } 44637267c094SAnthony Liguori g_free(mcb->callbacks[i].free_qiov); 446440b4f539SKevin Wolf } 446540b4f539SKevin Wolf } 446640b4f539SKevin Wolf 446740b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret) 446840b4f539SKevin Wolf { 446940b4f539SKevin Wolf MultiwriteCB *mcb = opaque; 447040b4f539SKevin Wolf 44716d519a5fSStefan Hajnoczi trace_multiwrite_cb(mcb, ret); 44726d519a5fSStefan Hajnoczi 4473cb6d3ca0SKevin Wolf if (ret < 0 && !mcb->error) { 447440b4f539SKevin Wolf mcb->error = ret; 447540b4f539SKevin Wolf } 447640b4f539SKevin Wolf 447740b4f539SKevin Wolf mcb->num_requests--; 447840b4f539SKevin Wolf if (mcb->num_requests == 0) { 447940b4f539SKevin Wolf multiwrite_user_cb(mcb); 44807267c094SAnthony Liguori g_free(mcb); 448140b4f539SKevin Wolf } 448240b4f539SKevin Wolf } 448340b4f539SKevin Wolf 448440b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b) 448540b4f539SKevin Wolf { 448677be4366SChristoph Hellwig const BlockRequest *req1 = a, *req2 = b; 448777be4366SChristoph Hellwig 448877be4366SChristoph Hellwig /* 448977be4366SChristoph Hellwig * Note that we can't simply subtract req2->sector from req1->sector 449077be4366SChristoph Hellwig * here as that could overflow the return value. 449177be4366SChristoph Hellwig */ 449277be4366SChristoph Hellwig if (req1->sector > req2->sector) { 449377be4366SChristoph Hellwig return 1; 449477be4366SChristoph Hellwig } else if (req1->sector < req2->sector) { 449577be4366SChristoph Hellwig return -1; 449677be4366SChristoph Hellwig } else { 449777be4366SChristoph Hellwig return 0; 449877be4366SChristoph Hellwig } 449940b4f539SKevin Wolf } 450040b4f539SKevin Wolf 450140b4f539SKevin Wolf /* 450240b4f539SKevin Wolf * Takes a bunch of requests and tries to merge them. Returns the number of 450340b4f539SKevin Wolf * requests that remain after merging. 450440b4f539SKevin Wolf */ 450540b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs, 450640b4f539SKevin Wolf int num_reqs, MultiwriteCB *mcb) 450740b4f539SKevin Wolf { 450840b4f539SKevin Wolf int i, outidx; 450940b4f539SKevin Wolf 451040b4f539SKevin Wolf // Sort requests by start sector 451140b4f539SKevin Wolf qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare); 451240b4f539SKevin Wolf 451340b4f539SKevin Wolf // Check if adjacent requests touch the same clusters. If so, combine them, 451440b4f539SKevin Wolf // filling up gaps with zero sectors. 451540b4f539SKevin Wolf outidx = 0; 451640b4f539SKevin Wolf for (i = 1; i < num_reqs; i++) { 451740b4f539SKevin Wolf int merge = 0; 451840b4f539SKevin Wolf int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors; 451940b4f539SKevin Wolf 4520b6a127a1SPaolo Bonzini // Handle exactly sequential writes and overlapping writes. 452140b4f539SKevin Wolf if (reqs[i].sector <= oldreq_last) { 452240b4f539SKevin Wolf merge = 1; 452340b4f539SKevin Wolf } 452440b4f539SKevin Wolf 4525e2a305fbSChristoph Hellwig if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) { 4526e2a305fbSChristoph Hellwig merge = 0; 4527e2a305fbSChristoph Hellwig } 4528e2a305fbSChristoph Hellwig 452940b4f539SKevin Wolf if (merge) { 453040b4f539SKevin Wolf size_t size; 45317267c094SAnthony Liguori QEMUIOVector *qiov = g_malloc0(sizeof(*qiov)); 453240b4f539SKevin Wolf qemu_iovec_init(qiov, 453340b4f539SKevin Wolf reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1); 453440b4f539SKevin Wolf 453540b4f539SKevin Wolf // Add the first request to the merged one. If the requests are 453640b4f539SKevin Wolf // overlapping, drop the last sectors of the first request. 453740b4f539SKevin Wolf size = (reqs[i].sector - reqs[outidx].sector) << 9; 45381b093c48SMichael Tokarev qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size); 453940b4f539SKevin Wolf 4540b6a127a1SPaolo Bonzini // We should need to add any zeros between the two requests 4541b6a127a1SPaolo Bonzini assert (reqs[i].sector <= oldreq_last); 454240b4f539SKevin Wolf 454340b4f539SKevin Wolf // Add the second request 45441b093c48SMichael Tokarev qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size); 454540b4f539SKevin Wolf 4546cbf1dff2SKevin Wolf reqs[outidx].nb_sectors = qiov->size >> 9; 454740b4f539SKevin Wolf reqs[outidx].qiov = qiov; 454840b4f539SKevin Wolf 454940b4f539SKevin Wolf mcb->callbacks[i].free_qiov = reqs[outidx].qiov; 455040b4f539SKevin Wolf } else { 455140b4f539SKevin Wolf outidx++; 455240b4f539SKevin Wolf reqs[outidx].sector = reqs[i].sector; 455340b4f539SKevin Wolf reqs[outidx].nb_sectors = reqs[i].nb_sectors; 455440b4f539SKevin Wolf reqs[outidx].qiov = reqs[i].qiov; 455540b4f539SKevin Wolf } 455640b4f539SKevin Wolf } 455740b4f539SKevin Wolf 455840b4f539SKevin Wolf return outidx + 1; 455940b4f539SKevin Wolf } 456040b4f539SKevin Wolf 456140b4f539SKevin Wolf /* 456240b4f539SKevin Wolf * Submit multiple AIO write requests at once. 456340b4f539SKevin Wolf * 456440b4f539SKevin Wolf * On success, the function returns 0 and all requests in the reqs array have 456540b4f539SKevin Wolf * been submitted. In error case this function returns -1, and any of the 456640b4f539SKevin Wolf * requests may or may not be submitted yet. In particular, this means that the 456740b4f539SKevin Wolf * callback will be called for some of the requests, for others it won't. The 456840b4f539SKevin Wolf * caller must check the error field of the BlockRequest to wait for the right 456940b4f539SKevin Wolf * callbacks (if error != 0, no callback will be called). 457040b4f539SKevin Wolf * 457140b4f539SKevin Wolf * The implementation may modify the contents of the reqs array, e.g. to merge 457240b4f539SKevin Wolf * requests. However, the fields opaque and error are left unmodified as they 457340b4f539SKevin Wolf * are used to signal failure for a single request to the caller. 457440b4f539SKevin Wolf */ 457540b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs) 457640b4f539SKevin Wolf { 457740b4f539SKevin Wolf MultiwriteCB *mcb; 457840b4f539SKevin Wolf int i; 457940b4f539SKevin Wolf 4580301db7c2SRyan Harper /* don't submit writes if we don't have a medium */ 4581301db7c2SRyan Harper if (bs->drv == NULL) { 4582301db7c2SRyan Harper for (i = 0; i < num_reqs; i++) { 4583301db7c2SRyan Harper reqs[i].error = -ENOMEDIUM; 4584301db7c2SRyan Harper } 4585301db7c2SRyan Harper return -1; 4586301db7c2SRyan Harper } 4587301db7c2SRyan Harper 458840b4f539SKevin Wolf if (num_reqs == 0) { 458940b4f539SKevin Wolf return 0; 459040b4f539SKevin Wolf } 459140b4f539SKevin Wolf 459240b4f539SKevin Wolf // Create MultiwriteCB structure 45937267c094SAnthony Liguori mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks)); 459440b4f539SKevin Wolf mcb->num_requests = 0; 459540b4f539SKevin Wolf mcb->num_callbacks = num_reqs; 459640b4f539SKevin Wolf 459740b4f539SKevin Wolf for (i = 0; i < num_reqs; i++) { 459840b4f539SKevin Wolf mcb->callbacks[i].cb = reqs[i].cb; 459940b4f539SKevin Wolf mcb->callbacks[i].opaque = reqs[i].opaque; 460040b4f539SKevin Wolf } 460140b4f539SKevin Wolf 460240b4f539SKevin Wolf // Check for mergable requests 460340b4f539SKevin Wolf num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb); 460440b4f539SKevin Wolf 46056d519a5fSStefan Hajnoczi trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs); 46066d519a5fSStefan Hajnoczi 4607df9309fbSPaolo Bonzini /* Run the aio requests. */ 4608df9309fbSPaolo Bonzini mcb->num_requests = num_reqs; 460940b4f539SKevin Wolf for (i = 0; i < num_reqs; i++) { 4610d20d9b7cSPaolo Bonzini bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov, 4611d20d9b7cSPaolo Bonzini reqs[i].nb_sectors, reqs[i].flags, 4612d20d9b7cSPaolo Bonzini multiwrite_cb, mcb, 4613d20d9b7cSPaolo Bonzini true); 461440b4f539SKevin Wolf } 461540b4f539SKevin Wolf 461640b4f539SKevin Wolf return 0; 461740b4f539SKevin Wolf } 461840b4f539SKevin Wolf 461983f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb) 462083f64091Sbellard { 4621d7331bedSStefan Hajnoczi acb->aiocb_info->cancel(acb); 462283f64091Sbellard } 462383f64091Sbellard 462483f64091Sbellard /**************************************************************/ 462583f64091Sbellard /* async block device emulation */ 462683f64091Sbellard 4627c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync { 4628c16b5a2cSChristoph Hellwig BlockDriverAIOCB common; 4629c16b5a2cSChristoph Hellwig QEMUBH *bh; 4630c16b5a2cSChristoph Hellwig int ret; 4631c16b5a2cSChristoph Hellwig /* vector translation state */ 4632c16b5a2cSChristoph Hellwig QEMUIOVector *qiov; 4633c16b5a2cSChristoph Hellwig uint8_t *bounce; 4634c16b5a2cSChristoph Hellwig int is_write; 4635c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync; 4636c16b5a2cSChristoph Hellwig 4637c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb) 4638c16b5a2cSChristoph Hellwig { 4639b666d239SKevin Wolf BlockDriverAIOCBSync *acb = 4640b666d239SKevin Wolf container_of(blockacb, BlockDriverAIOCBSync, common); 46416a7ad299SDor Laor qemu_bh_delete(acb->bh); 464236afc451SAvi Kivity acb->bh = NULL; 4643c16b5a2cSChristoph Hellwig qemu_aio_release(acb); 4644c16b5a2cSChristoph Hellwig } 4645c16b5a2cSChristoph Hellwig 4646d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_aiocb_info = { 4647c16b5a2cSChristoph Hellwig .aiocb_size = sizeof(BlockDriverAIOCBSync), 4648c16b5a2cSChristoph Hellwig .cancel = bdrv_aio_cancel_em, 4649c16b5a2cSChristoph Hellwig }; 4650c16b5a2cSChristoph Hellwig 465183f64091Sbellard static void bdrv_aio_bh_cb(void *opaque) 4652beac80cdSbellard { 4653ce1a14dcSpbrook BlockDriverAIOCBSync *acb = opaque; 4654f141eafeSaliguori 4655f141eafeSaliguori if (!acb->is_write) 465603396148SMichael Tokarev qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size); 4657ceb42de8Saliguori qemu_vfree(acb->bounce); 4658ce1a14dcSpbrook acb->common.cb(acb->common.opaque, acb->ret); 46596a7ad299SDor Laor qemu_bh_delete(acb->bh); 466036afc451SAvi Kivity acb->bh = NULL; 4661ce1a14dcSpbrook qemu_aio_release(acb); 4662beac80cdSbellard } 4663beac80cdSbellard 4664f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs, 4665f141eafeSaliguori int64_t sector_num, 4666f141eafeSaliguori QEMUIOVector *qiov, 4667f141eafeSaliguori int nb_sectors, 4668f141eafeSaliguori BlockDriverCompletionFunc *cb, 4669f141eafeSaliguori void *opaque, 4670f141eafeSaliguori int is_write) 4671f141eafeSaliguori 4672ea2384d3Sbellard { 4673ce1a14dcSpbrook BlockDriverAIOCBSync *acb; 467483f64091Sbellard 4675d7331bedSStefan Hajnoczi acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque); 4676f141eafeSaliguori acb->is_write = is_write; 4677f141eafeSaliguori acb->qiov = qiov; 4678e268ca52Saliguori acb->bounce = qemu_blockalign(bs, qiov->size); 46792572b37aSStefan Hajnoczi acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_aio_bh_cb, acb); 4680f141eafeSaliguori 4681f141eafeSaliguori if (is_write) { 4682d5e6b161SMichael Tokarev qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size); 46831ed20acfSStefan Hajnoczi acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors); 4684f141eafeSaliguori } else { 46851ed20acfSStefan Hajnoczi acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors); 4686f141eafeSaliguori } 4687f141eafeSaliguori 4688ce1a14dcSpbrook qemu_bh_schedule(acb->bh); 4689f141eafeSaliguori 4690ce1a14dcSpbrook return &acb->common; 46917a6cba61Spbrook } 46927a6cba61Spbrook 4693f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs, 4694f141eafeSaliguori int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, 4695ce1a14dcSpbrook BlockDriverCompletionFunc *cb, void *opaque) 469683f64091Sbellard { 4697f141eafeSaliguori return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0); 469883f64091Sbellard } 469983f64091Sbellard 4700f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs, 4701f141eafeSaliguori int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, 4702f141eafeSaliguori BlockDriverCompletionFunc *cb, void *opaque) 4703f141eafeSaliguori { 4704f141eafeSaliguori return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1); 4705f141eafeSaliguori } 4706f141eafeSaliguori 470768485420SKevin Wolf 470868485420SKevin Wolf typedef struct BlockDriverAIOCBCoroutine { 470968485420SKevin Wolf BlockDriverAIOCB common; 471068485420SKevin Wolf BlockRequest req; 471168485420SKevin Wolf bool is_write; 4712d318aea9SKevin Wolf bool *done; 471368485420SKevin Wolf QEMUBH* bh; 471468485420SKevin Wolf } BlockDriverAIOCBCoroutine; 471568485420SKevin Wolf 471668485420SKevin Wolf static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb) 471768485420SKevin Wolf { 47182572b37aSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(blockacb->bs); 4719d318aea9SKevin Wolf BlockDriverAIOCBCoroutine *acb = 4720d318aea9SKevin Wolf container_of(blockacb, BlockDriverAIOCBCoroutine, common); 4721d318aea9SKevin Wolf bool done = false; 4722d318aea9SKevin Wolf 4723d318aea9SKevin Wolf acb->done = &done; 4724d318aea9SKevin Wolf while (!done) { 47252572b37aSStefan Hajnoczi aio_poll(aio_context, true); 4726d318aea9SKevin Wolf } 472768485420SKevin Wolf } 472868485420SKevin Wolf 4729d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_co_aiocb_info = { 473068485420SKevin Wolf .aiocb_size = sizeof(BlockDriverAIOCBCoroutine), 473168485420SKevin Wolf .cancel = bdrv_aio_co_cancel_em, 473268485420SKevin Wolf }; 473368485420SKevin Wolf 473435246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque) 473568485420SKevin Wolf { 473668485420SKevin Wolf BlockDriverAIOCBCoroutine *acb = opaque; 473768485420SKevin Wolf 473868485420SKevin Wolf acb->common.cb(acb->common.opaque, acb->req.error); 4739d318aea9SKevin Wolf 4740d318aea9SKevin Wolf if (acb->done) { 4741d318aea9SKevin Wolf *acb->done = true; 4742d318aea9SKevin Wolf } 4743d318aea9SKevin Wolf 474468485420SKevin Wolf qemu_bh_delete(acb->bh); 474568485420SKevin Wolf qemu_aio_release(acb); 474668485420SKevin Wolf } 474768485420SKevin Wolf 4748b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */ 4749b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque) 4750b2a61371SStefan Hajnoczi { 4751b2a61371SStefan Hajnoczi BlockDriverAIOCBCoroutine *acb = opaque; 4752b2a61371SStefan Hajnoczi BlockDriverState *bs = acb->common.bs; 4753b2a61371SStefan Hajnoczi 4754b2a61371SStefan Hajnoczi if (!acb->is_write) { 4755b2a61371SStefan Hajnoczi acb->req.error = bdrv_co_do_readv(bs, acb->req.sector, 4756d20d9b7cSPaolo Bonzini acb->req.nb_sectors, acb->req.qiov, acb->req.flags); 4757b2a61371SStefan Hajnoczi } else { 4758b2a61371SStefan Hajnoczi acb->req.error = bdrv_co_do_writev(bs, acb->req.sector, 4759d20d9b7cSPaolo Bonzini acb->req.nb_sectors, acb->req.qiov, acb->req.flags); 4760b2a61371SStefan Hajnoczi } 4761b2a61371SStefan Hajnoczi 47622572b37aSStefan Hajnoczi acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb); 4763b2a61371SStefan Hajnoczi qemu_bh_schedule(acb->bh); 4764b2a61371SStefan Hajnoczi } 4765b2a61371SStefan Hajnoczi 476668485420SKevin Wolf static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs, 476768485420SKevin Wolf int64_t sector_num, 476868485420SKevin Wolf QEMUIOVector *qiov, 476968485420SKevin Wolf int nb_sectors, 4770d20d9b7cSPaolo Bonzini BdrvRequestFlags flags, 477168485420SKevin Wolf BlockDriverCompletionFunc *cb, 477268485420SKevin Wolf void *opaque, 47738c5873d6SStefan Hajnoczi bool is_write) 477468485420SKevin Wolf { 477568485420SKevin Wolf Coroutine *co; 477668485420SKevin Wolf BlockDriverAIOCBCoroutine *acb; 477768485420SKevin Wolf 4778d7331bedSStefan Hajnoczi acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque); 477968485420SKevin Wolf acb->req.sector = sector_num; 478068485420SKevin Wolf acb->req.nb_sectors = nb_sectors; 478168485420SKevin Wolf acb->req.qiov = qiov; 4782d20d9b7cSPaolo Bonzini acb->req.flags = flags; 478368485420SKevin Wolf acb->is_write = is_write; 4784d318aea9SKevin Wolf acb->done = NULL; 478568485420SKevin Wolf 47868c5873d6SStefan Hajnoczi co = qemu_coroutine_create(bdrv_co_do_rw); 478768485420SKevin Wolf qemu_coroutine_enter(co, acb); 478868485420SKevin Wolf 478968485420SKevin Wolf return &acb->common; 479068485420SKevin Wolf } 479168485420SKevin Wolf 479207f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque) 4793b2e12bc6SChristoph Hellwig { 479407f07615SPaolo Bonzini BlockDriverAIOCBCoroutine *acb = opaque; 479507f07615SPaolo Bonzini BlockDriverState *bs = acb->common.bs; 4796b2e12bc6SChristoph Hellwig 479707f07615SPaolo Bonzini acb->req.error = bdrv_co_flush(bs); 47982572b37aSStefan Hajnoczi acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb); 4799b2e12bc6SChristoph Hellwig qemu_bh_schedule(acb->bh); 4800b2e12bc6SChristoph Hellwig } 4801b2e12bc6SChristoph Hellwig 480207f07615SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs, 4803016f5cf6SAlexander Graf BlockDriverCompletionFunc *cb, void *opaque) 4804016f5cf6SAlexander Graf { 480507f07615SPaolo Bonzini trace_bdrv_aio_flush(bs, opaque); 4806016f5cf6SAlexander Graf 480707f07615SPaolo Bonzini Coroutine *co; 480807f07615SPaolo Bonzini BlockDriverAIOCBCoroutine *acb; 4809016f5cf6SAlexander Graf 4810d7331bedSStefan Hajnoczi acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque); 4811d318aea9SKevin Wolf acb->done = NULL; 4812d318aea9SKevin Wolf 481307f07615SPaolo Bonzini co = qemu_coroutine_create(bdrv_aio_flush_co_entry); 481407f07615SPaolo Bonzini qemu_coroutine_enter(co, acb); 4815016f5cf6SAlexander Graf 4816016f5cf6SAlexander Graf return &acb->common; 4817016f5cf6SAlexander Graf } 4818016f5cf6SAlexander Graf 48194265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque) 48204265d620SPaolo Bonzini { 48214265d620SPaolo Bonzini BlockDriverAIOCBCoroutine *acb = opaque; 48224265d620SPaolo Bonzini BlockDriverState *bs = acb->common.bs; 48234265d620SPaolo Bonzini 48244265d620SPaolo Bonzini acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors); 48252572b37aSStefan Hajnoczi acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb); 48264265d620SPaolo Bonzini qemu_bh_schedule(acb->bh); 48274265d620SPaolo Bonzini } 48284265d620SPaolo Bonzini 48294265d620SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs, 48304265d620SPaolo Bonzini int64_t sector_num, int nb_sectors, 48314265d620SPaolo Bonzini BlockDriverCompletionFunc *cb, void *opaque) 48324265d620SPaolo Bonzini { 48334265d620SPaolo Bonzini Coroutine *co; 48344265d620SPaolo Bonzini BlockDriverAIOCBCoroutine *acb; 48354265d620SPaolo Bonzini 48364265d620SPaolo Bonzini trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque); 48374265d620SPaolo Bonzini 4838d7331bedSStefan Hajnoczi acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque); 48394265d620SPaolo Bonzini acb->req.sector = sector_num; 48404265d620SPaolo Bonzini acb->req.nb_sectors = nb_sectors; 4841d318aea9SKevin Wolf acb->done = NULL; 48424265d620SPaolo Bonzini co = qemu_coroutine_create(bdrv_aio_discard_co_entry); 48434265d620SPaolo Bonzini qemu_coroutine_enter(co, acb); 48444265d620SPaolo Bonzini 48454265d620SPaolo Bonzini return &acb->common; 48464265d620SPaolo Bonzini } 48474265d620SPaolo Bonzini 4848ea2384d3Sbellard void bdrv_init(void) 4849ea2384d3Sbellard { 48505efa9d5aSAnthony Liguori module_call_init(MODULE_INIT_BLOCK); 4851ea2384d3Sbellard } 4852ce1a14dcSpbrook 4853eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void) 4854eb852011SMarkus Armbruster { 4855eb852011SMarkus Armbruster use_bdrv_whitelist = 1; 4856eb852011SMarkus Armbruster bdrv_init(); 4857eb852011SMarkus Armbruster } 4858eb852011SMarkus Armbruster 4859d7331bedSStefan Hajnoczi void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs, 48606bbff9a0Saliguori BlockDriverCompletionFunc *cb, void *opaque) 48616bbff9a0Saliguori { 4862ce1a14dcSpbrook BlockDriverAIOCB *acb; 4863ce1a14dcSpbrook 4864d7331bedSStefan Hajnoczi acb = g_slice_alloc(aiocb_info->aiocb_size); 4865d7331bedSStefan Hajnoczi acb->aiocb_info = aiocb_info; 4866ce1a14dcSpbrook acb->bs = bs; 4867ce1a14dcSpbrook acb->cb = cb; 4868ce1a14dcSpbrook acb->opaque = opaque; 4869ce1a14dcSpbrook return acb; 4870ce1a14dcSpbrook } 4871ce1a14dcSpbrook 4872ce1a14dcSpbrook void qemu_aio_release(void *p) 4873ce1a14dcSpbrook { 4874d37c975fSStefan Hajnoczi BlockDriverAIOCB *acb = p; 4875d7331bedSStefan Hajnoczi g_slice_free1(acb->aiocb_info->aiocb_size, acb); 4876ce1a14dcSpbrook } 487719cb3738Sbellard 487819cb3738Sbellard /**************************************************************/ 4879f9f05dc5SKevin Wolf /* Coroutine block device emulation */ 4880f9f05dc5SKevin Wolf 4881f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion { 4882f9f05dc5SKevin Wolf Coroutine *coroutine; 4883f9f05dc5SKevin Wolf int ret; 4884f9f05dc5SKevin Wolf } CoroutineIOCompletion; 4885f9f05dc5SKevin Wolf 4886f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret) 4887f9f05dc5SKevin Wolf { 4888f9f05dc5SKevin Wolf CoroutineIOCompletion *co = opaque; 4889f9f05dc5SKevin Wolf 4890f9f05dc5SKevin Wolf co->ret = ret; 4891f9f05dc5SKevin Wolf qemu_coroutine_enter(co->coroutine, NULL); 4892f9f05dc5SKevin Wolf } 4893f9f05dc5SKevin Wolf 4894f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num, 4895f9f05dc5SKevin Wolf int nb_sectors, QEMUIOVector *iov, 4896f9f05dc5SKevin Wolf bool is_write) 4897f9f05dc5SKevin Wolf { 4898f9f05dc5SKevin Wolf CoroutineIOCompletion co = { 4899f9f05dc5SKevin Wolf .coroutine = qemu_coroutine_self(), 4900f9f05dc5SKevin Wolf }; 4901f9f05dc5SKevin Wolf BlockDriverAIOCB *acb; 4902f9f05dc5SKevin Wolf 4903f9f05dc5SKevin Wolf if (is_write) { 4904a652d160SStefan Hajnoczi acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors, 4905f9f05dc5SKevin Wolf bdrv_co_io_em_complete, &co); 4906f9f05dc5SKevin Wolf } else { 4907a652d160SStefan Hajnoczi acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors, 4908f9f05dc5SKevin Wolf bdrv_co_io_em_complete, &co); 4909f9f05dc5SKevin Wolf } 4910f9f05dc5SKevin Wolf 491159370aaaSStefan Hajnoczi trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb); 4912f9f05dc5SKevin Wolf if (!acb) { 4913f9f05dc5SKevin Wolf return -EIO; 4914f9f05dc5SKevin Wolf } 4915f9f05dc5SKevin Wolf qemu_coroutine_yield(); 4916f9f05dc5SKevin Wolf 4917f9f05dc5SKevin Wolf return co.ret; 4918f9f05dc5SKevin Wolf } 4919f9f05dc5SKevin Wolf 4920f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs, 4921f9f05dc5SKevin Wolf int64_t sector_num, int nb_sectors, 4922f9f05dc5SKevin Wolf QEMUIOVector *iov) 4923f9f05dc5SKevin Wolf { 4924f9f05dc5SKevin Wolf return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false); 4925f9f05dc5SKevin Wolf } 4926f9f05dc5SKevin Wolf 4927f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs, 4928f9f05dc5SKevin Wolf int64_t sector_num, int nb_sectors, 4929f9f05dc5SKevin Wolf QEMUIOVector *iov) 4930f9f05dc5SKevin Wolf { 4931f9f05dc5SKevin Wolf return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true); 4932f9f05dc5SKevin Wolf } 4933f9f05dc5SKevin Wolf 493407f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque) 4935e7a8a783SKevin Wolf { 493607f07615SPaolo Bonzini RwCo *rwco = opaque; 493707f07615SPaolo Bonzini 493807f07615SPaolo Bonzini rwco->ret = bdrv_co_flush(rwco->bs); 493907f07615SPaolo Bonzini } 494007f07615SPaolo Bonzini 494107f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs) 494207f07615SPaolo Bonzini { 4943eb489bb1SKevin Wolf int ret; 4944eb489bb1SKevin Wolf 494529cdb251SPaolo Bonzini if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) { 494607f07615SPaolo Bonzini return 0; 4947eb489bb1SKevin Wolf } 4948eb489bb1SKevin Wolf 4949ca716364SKevin Wolf /* Write back cached data to the OS even with cache=unsafe */ 4950bf736fe3SKevin Wolf BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS); 4951eb489bb1SKevin Wolf if (bs->drv->bdrv_co_flush_to_os) { 4952eb489bb1SKevin Wolf ret = bs->drv->bdrv_co_flush_to_os(bs); 4953eb489bb1SKevin Wolf if (ret < 0) { 4954eb489bb1SKevin Wolf return ret; 4955eb489bb1SKevin Wolf } 4956eb489bb1SKevin Wolf } 4957eb489bb1SKevin Wolf 4958ca716364SKevin Wolf /* But don't actually force it to the disk with cache=unsafe */ 4959ca716364SKevin Wolf if (bs->open_flags & BDRV_O_NO_FLUSH) { 4960d4c82329SKevin Wolf goto flush_parent; 4961ca716364SKevin Wolf } 4962ca716364SKevin Wolf 4963bf736fe3SKevin Wolf BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK); 4964eb489bb1SKevin Wolf if (bs->drv->bdrv_co_flush_to_disk) { 496529cdb251SPaolo Bonzini ret = bs->drv->bdrv_co_flush_to_disk(bs); 496607f07615SPaolo Bonzini } else if (bs->drv->bdrv_aio_flush) { 496707f07615SPaolo Bonzini BlockDriverAIOCB *acb; 4968e7a8a783SKevin Wolf CoroutineIOCompletion co = { 4969e7a8a783SKevin Wolf .coroutine = qemu_coroutine_self(), 4970e7a8a783SKevin Wolf }; 4971e7a8a783SKevin Wolf 497207f07615SPaolo Bonzini acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co); 497307f07615SPaolo Bonzini if (acb == NULL) { 497429cdb251SPaolo Bonzini ret = -EIO; 497507f07615SPaolo Bonzini } else { 4976e7a8a783SKevin Wolf qemu_coroutine_yield(); 497729cdb251SPaolo Bonzini ret = co.ret; 4978e7a8a783SKevin Wolf } 497907f07615SPaolo Bonzini } else { 498007f07615SPaolo Bonzini /* 498107f07615SPaolo Bonzini * Some block drivers always operate in either writethrough or unsafe 498207f07615SPaolo Bonzini * mode and don't support bdrv_flush therefore. Usually qemu doesn't 498307f07615SPaolo Bonzini * know how the server works (because the behaviour is hardcoded or 498407f07615SPaolo Bonzini * depends on server-side configuration), so we can't ensure that 498507f07615SPaolo Bonzini * everything is safe on disk. Returning an error doesn't work because 498607f07615SPaolo Bonzini * that would break guests even if the server operates in writethrough 498707f07615SPaolo Bonzini * mode. 498807f07615SPaolo Bonzini * 498907f07615SPaolo Bonzini * Let's hope the user knows what he's doing. 499007f07615SPaolo Bonzini */ 499129cdb251SPaolo Bonzini ret = 0; 499207f07615SPaolo Bonzini } 499329cdb251SPaolo Bonzini if (ret < 0) { 499429cdb251SPaolo Bonzini return ret; 499529cdb251SPaolo Bonzini } 499629cdb251SPaolo Bonzini 499729cdb251SPaolo Bonzini /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH 499829cdb251SPaolo Bonzini * in the case of cache=unsafe, so there are no useless flushes. 499929cdb251SPaolo Bonzini */ 5000d4c82329SKevin Wolf flush_parent: 500129cdb251SPaolo Bonzini return bdrv_co_flush(bs->file); 500207f07615SPaolo Bonzini } 500307f07615SPaolo Bonzini 50045a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp) 50050f15423cSAnthony Liguori { 50065a8a30dbSKevin Wolf Error *local_err = NULL; 50075a8a30dbSKevin Wolf int ret; 50085a8a30dbSKevin Wolf 50093456a8d1SKevin Wolf if (!bs->drv) { 50103456a8d1SKevin Wolf return; 50110f15423cSAnthony Liguori } 50123456a8d1SKevin Wolf 50133456a8d1SKevin Wolf if (bs->drv->bdrv_invalidate_cache) { 50145a8a30dbSKevin Wolf bs->drv->bdrv_invalidate_cache(bs, &local_err); 50153456a8d1SKevin Wolf } else if (bs->file) { 50165a8a30dbSKevin Wolf bdrv_invalidate_cache(bs->file, &local_err); 50175a8a30dbSKevin Wolf } 50185a8a30dbSKevin Wolf if (local_err) { 50195a8a30dbSKevin Wolf error_propagate(errp, local_err); 50205a8a30dbSKevin Wolf return; 50213456a8d1SKevin Wolf } 50223456a8d1SKevin Wolf 50235a8a30dbSKevin Wolf ret = refresh_total_sectors(bs, bs->total_sectors); 50245a8a30dbSKevin Wolf if (ret < 0) { 50255a8a30dbSKevin Wolf error_setg_errno(errp, -ret, "Could not refresh total sector count"); 50265a8a30dbSKevin Wolf return; 50275a8a30dbSKevin Wolf } 50280f15423cSAnthony Liguori } 50290f15423cSAnthony Liguori 50305a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp) 50310f15423cSAnthony Liguori { 50320f15423cSAnthony Liguori BlockDriverState *bs; 50335a8a30dbSKevin Wolf Error *local_err = NULL; 50340f15423cSAnthony Liguori 5035dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 5036ed78cda3SStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 5037ed78cda3SStefan Hajnoczi 5038ed78cda3SStefan Hajnoczi aio_context_acquire(aio_context); 50395a8a30dbSKevin Wolf bdrv_invalidate_cache(bs, &local_err); 5040ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 50415a8a30dbSKevin Wolf if (local_err) { 50425a8a30dbSKevin Wolf error_propagate(errp, local_err); 50435a8a30dbSKevin Wolf return; 50445a8a30dbSKevin Wolf } 50450f15423cSAnthony Liguori } 50460f15423cSAnthony Liguori } 50470f15423cSAnthony Liguori 504807789269SBenoît Canet void bdrv_clear_incoming_migration_all(void) 504907789269SBenoît Canet { 505007789269SBenoît Canet BlockDriverState *bs; 505107789269SBenoît Canet 5052dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 5053ed78cda3SStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 5054ed78cda3SStefan Hajnoczi 5055ed78cda3SStefan Hajnoczi aio_context_acquire(aio_context); 505607789269SBenoît Canet bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING); 5057ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 505807789269SBenoît Canet } 505907789269SBenoît Canet } 506007789269SBenoît Canet 506107f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs) 506207f07615SPaolo Bonzini { 506307f07615SPaolo Bonzini Coroutine *co; 506407f07615SPaolo Bonzini RwCo rwco = { 506507f07615SPaolo Bonzini .bs = bs, 506607f07615SPaolo Bonzini .ret = NOT_DONE, 506707f07615SPaolo Bonzini }; 506807f07615SPaolo Bonzini 506907f07615SPaolo Bonzini if (qemu_in_coroutine()) { 507007f07615SPaolo Bonzini /* Fast-path if already in coroutine context */ 507107f07615SPaolo Bonzini bdrv_flush_co_entry(&rwco); 507207f07615SPaolo Bonzini } else { 50732572b37aSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 50742572b37aSStefan Hajnoczi 507507f07615SPaolo Bonzini co = qemu_coroutine_create(bdrv_flush_co_entry); 507607f07615SPaolo Bonzini qemu_coroutine_enter(co, &rwco); 507707f07615SPaolo Bonzini while (rwco.ret == NOT_DONE) { 50782572b37aSStefan Hajnoczi aio_poll(aio_context, true); 507907f07615SPaolo Bonzini } 508007f07615SPaolo Bonzini } 508107f07615SPaolo Bonzini 508207f07615SPaolo Bonzini return rwco.ret; 508307f07615SPaolo Bonzini } 5084e7a8a783SKevin Wolf 5085775aa8b6SKevin Wolf typedef struct DiscardCo { 5086775aa8b6SKevin Wolf BlockDriverState *bs; 5087775aa8b6SKevin Wolf int64_t sector_num; 5088775aa8b6SKevin Wolf int nb_sectors; 5089775aa8b6SKevin Wolf int ret; 5090775aa8b6SKevin Wolf } DiscardCo; 50914265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque) 50924265d620SPaolo Bonzini { 5093775aa8b6SKevin Wolf DiscardCo *rwco = opaque; 50944265d620SPaolo Bonzini 50954265d620SPaolo Bonzini rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors); 50964265d620SPaolo Bonzini } 50974265d620SPaolo Bonzini 50986f14da52SPeter Lieven /* if no limit is specified in the BlockLimits use a default 50996f14da52SPeter Lieven * of 32768 512-byte sectors (16 MiB) per request. 51006f14da52SPeter Lieven */ 51016f14da52SPeter Lieven #define MAX_DISCARD_DEFAULT 32768 51026f14da52SPeter Lieven 51034265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num, 51044265d620SPaolo Bonzini int nb_sectors) 51054265d620SPaolo Bonzini { 5106d51e9fe5SPaolo Bonzini int max_discard; 5107d51e9fe5SPaolo Bonzini 51084265d620SPaolo Bonzini if (!bs->drv) { 51094265d620SPaolo Bonzini return -ENOMEDIUM; 51104265d620SPaolo Bonzini } else if (bdrv_check_request(bs, sector_num, nb_sectors)) { 51114265d620SPaolo Bonzini return -EIO; 51124265d620SPaolo Bonzini } else if (bs->read_only) { 51134265d620SPaolo Bonzini return -EROFS; 5114df702c9bSPaolo Bonzini } 5115df702c9bSPaolo Bonzini 51168f0720ecSPaolo Bonzini bdrv_reset_dirty(bs, sector_num, nb_sectors); 5117df702c9bSPaolo Bonzini 51189e8f1835SPaolo Bonzini /* Do nothing if disabled. */ 51199e8f1835SPaolo Bonzini if (!(bs->open_flags & BDRV_O_UNMAP)) { 51209e8f1835SPaolo Bonzini return 0; 51219e8f1835SPaolo Bonzini } 51229e8f1835SPaolo Bonzini 5123d51e9fe5SPaolo Bonzini if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) { 5124d51e9fe5SPaolo Bonzini return 0; 5125d51e9fe5SPaolo Bonzini } 51266f14da52SPeter Lieven 5127d51e9fe5SPaolo Bonzini max_discard = bs->bl.max_discard ? bs->bl.max_discard : MAX_DISCARD_DEFAULT; 51286f14da52SPeter Lieven while (nb_sectors > 0) { 51296f14da52SPeter Lieven int ret; 51306f14da52SPeter Lieven int num = nb_sectors; 51316f14da52SPeter Lieven 51326f14da52SPeter Lieven /* align request */ 51336f14da52SPeter Lieven if (bs->bl.discard_alignment && 51346f14da52SPeter Lieven num >= bs->bl.discard_alignment && 51356f14da52SPeter Lieven sector_num % bs->bl.discard_alignment) { 51366f14da52SPeter Lieven if (num > bs->bl.discard_alignment) { 51376f14da52SPeter Lieven num = bs->bl.discard_alignment; 51386f14da52SPeter Lieven } 51396f14da52SPeter Lieven num -= sector_num % bs->bl.discard_alignment; 51406f14da52SPeter Lieven } 51416f14da52SPeter Lieven 51426f14da52SPeter Lieven /* limit request size */ 51436f14da52SPeter Lieven if (num > max_discard) { 51446f14da52SPeter Lieven num = max_discard; 51456f14da52SPeter Lieven } 51466f14da52SPeter Lieven 5147d51e9fe5SPaolo Bonzini if (bs->drv->bdrv_co_discard) { 51486f14da52SPeter Lieven ret = bs->drv->bdrv_co_discard(bs, sector_num, num); 5149d51e9fe5SPaolo Bonzini } else { 51504265d620SPaolo Bonzini BlockDriverAIOCB *acb; 51514265d620SPaolo Bonzini CoroutineIOCompletion co = { 51524265d620SPaolo Bonzini .coroutine = qemu_coroutine_self(), 51534265d620SPaolo Bonzini }; 51544265d620SPaolo Bonzini 51554265d620SPaolo Bonzini acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors, 51564265d620SPaolo Bonzini bdrv_co_io_em_complete, &co); 51574265d620SPaolo Bonzini if (acb == NULL) { 51584265d620SPaolo Bonzini return -EIO; 51594265d620SPaolo Bonzini } else { 51604265d620SPaolo Bonzini qemu_coroutine_yield(); 5161d51e9fe5SPaolo Bonzini ret = co.ret; 51624265d620SPaolo Bonzini } 5163d51e9fe5SPaolo Bonzini } 51647ce21016SPaolo Bonzini if (ret && ret != -ENOTSUP) { 5165d51e9fe5SPaolo Bonzini return ret; 5166d51e9fe5SPaolo Bonzini } 5167d51e9fe5SPaolo Bonzini 5168d51e9fe5SPaolo Bonzini sector_num += num; 5169d51e9fe5SPaolo Bonzini nb_sectors -= num; 5170d51e9fe5SPaolo Bonzini } 51714265d620SPaolo Bonzini return 0; 51724265d620SPaolo Bonzini } 51734265d620SPaolo Bonzini 51744265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors) 51754265d620SPaolo Bonzini { 51764265d620SPaolo Bonzini Coroutine *co; 5177775aa8b6SKevin Wolf DiscardCo rwco = { 51784265d620SPaolo Bonzini .bs = bs, 51794265d620SPaolo Bonzini .sector_num = sector_num, 51804265d620SPaolo Bonzini .nb_sectors = nb_sectors, 51814265d620SPaolo Bonzini .ret = NOT_DONE, 51824265d620SPaolo Bonzini }; 51834265d620SPaolo Bonzini 51844265d620SPaolo Bonzini if (qemu_in_coroutine()) { 51854265d620SPaolo Bonzini /* Fast-path if already in coroutine context */ 51864265d620SPaolo Bonzini bdrv_discard_co_entry(&rwco); 51874265d620SPaolo Bonzini } else { 51882572b37aSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 51892572b37aSStefan Hajnoczi 51904265d620SPaolo Bonzini co = qemu_coroutine_create(bdrv_discard_co_entry); 51914265d620SPaolo Bonzini qemu_coroutine_enter(co, &rwco); 51924265d620SPaolo Bonzini while (rwco.ret == NOT_DONE) { 51932572b37aSStefan Hajnoczi aio_poll(aio_context, true); 51944265d620SPaolo Bonzini } 51954265d620SPaolo Bonzini } 51964265d620SPaolo Bonzini 51974265d620SPaolo Bonzini return rwco.ret; 51984265d620SPaolo Bonzini } 51994265d620SPaolo Bonzini 5200f9f05dc5SKevin Wolf /**************************************************************/ 520119cb3738Sbellard /* removable device support */ 520219cb3738Sbellard 520319cb3738Sbellard /** 520419cb3738Sbellard * Return TRUE if the media is present 520519cb3738Sbellard */ 520619cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs) 520719cb3738Sbellard { 520819cb3738Sbellard BlockDriver *drv = bs->drv; 5209a1aff5bfSMarkus Armbruster 521019cb3738Sbellard if (!drv) 521119cb3738Sbellard return 0; 521219cb3738Sbellard if (!drv->bdrv_is_inserted) 5213a1aff5bfSMarkus Armbruster return 1; 5214a1aff5bfSMarkus Armbruster return drv->bdrv_is_inserted(bs); 521519cb3738Sbellard } 521619cb3738Sbellard 521719cb3738Sbellard /** 52188e49ca46SMarkus Armbruster * Return whether the media changed since the last call to this 52198e49ca46SMarkus Armbruster * function, or -ENOTSUP if we don't know. Most drivers don't know. 522019cb3738Sbellard */ 522119cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs) 522219cb3738Sbellard { 522319cb3738Sbellard BlockDriver *drv = bs->drv; 522419cb3738Sbellard 52258e49ca46SMarkus Armbruster if (drv && drv->bdrv_media_changed) { 52268e49ca46SMarkus Armbruster return drv->bdrv_media_changed(bs); 52278e49ca46SMarkus Armbruster } 52288e49ca46SMarkus Armbruster return -ENOTSUP; 522919cb3738Sbellard } 523019cb3738Sbellard 523119cb3738Sbellard /** 523219cb3738Sbellard * If eject_flag is TRUE, eject the media. Otherwise, close the tray 523319cb3738Sbellard */ 5234f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag) 523519cb3738Sbellard { 523619cb3738Sbellard BlockDriver *drv = bs->drv; 523719cb3738Sbellard 5238822e1cd1SMarkus Armbruster if (drv && drv->bdrv_eject) { 5239822e1cd1SMarkus Armbruster drv->bdrv_eject(bs, eject_flag); 524019cb3738Sbellard } 52416f382ed2SLuiz Capitulino 52426f382ed2SLuiz Capitulino if (bs->device_name[0] != '\0') { 52436f382ed2SLuiz Capitulino bdrv_emit_qmp_eject_event(bs, eject_flag); 52446f382ed2SLuiz Capitulino } 524519cb3738Sbellard } 524619cb3738Sbellard 524719cb3738Sbellard /** 524819cb3738Sbellard * Lock or unlock the media (if it is locked, the user won't be able 524919cb3738Sbellard * to eject it manually). 525019cb3738Sbellard */ 5251025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked) 525219cb3738Sbellard { 525319cb3738Sbellard BlockDriver *drv = bs->drv; 525419cb3738Sbellard 5255025e849aSMarkus Armbruster trace_bdrv_lock_medium(bs, locked); 5256b8c6d095SStefan Hajnoczi 5257025e849aSMarkus Armbruster if (drv && drv->bdrv_lock_medium) { 5258025e849aSMarkus Armbruster drv->bdrv_lock_medium(bs, locked); 525919cb3738Sbellard } 526019cb3738Sbellard } 5261985a03b0Sths 5262985a03b0Sths /* needed for generic scsi interface */ 5263985a03b0Sths 5264985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf) 5265985a03b0Sths { 5266985a03b0Sths BlockDriver *drv = bs->drv; 5267985a03b0Sths 5268985a03b0Sths if (drv && drv->bdrv_ioctl) 5269985a03b0Sths return drv->bdrv_ioctl(bs, req, buf); 5270985a03b0Sths return -ENOTSUP; 5271985a03b0Sths } 52727d780669Saliguori 5273221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs, 5274221f715dSaliguori unsigned long int req, void *buf, 52757d780669Saliguori BlockDriverCompletionFunc *cb, void *opaque) 52767d780669Saliguori { 5277221f715dSaliguori BlockDriver *drv = bs->drv; 52787d780669Saliguori 5279221f715dSaliguori if (drv && drv->bdrv_aio_ioctl) 5280221f715dSaliguori return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque); 5281221f715dSaliguori return NULL; 52827d780669Saliguori } 5283e268ca52Saliguori 52841b7fd729SPaolo Bonzini void bdrv_set_guest_block_size(BlockDriverState *bs, int align) 52857b6f9300SMarkus Armbruster { 52861b7fd729SPaolo Bonzini bs->guest_block_size = align; 52877b6f9300SMarkus Armbruster } 52887cd1e32aSlirans@il.ibm.com 5289e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size) 5290e268ca52Saliguori { 5291339064d5SKevin Wolf return qemu_memalign(bdrv_opt_mem_align(bs), size); 5292e268ca52Saliguori } 52937cd1e32aSlirans@il.ibm.com 5294c53b1c51SStefan Hajnoczi /* 5295c53b1c51SStefan Hajnoczi * Check if all memory in this vector is sector aligned. 5296c53b1c51SStefan Hajnoczi */ 5297c53b1c51SStefan Hajnoczi bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov) 5298c53b1c51SStefan Hajnoczi { 5299c53b1c51SStefan Hajnoczi int i; 5300339064d5SKevin Wolf size_t alignment = bdrv_opt_mem_align(bs); 5301c53b1c51SStefan Hajnoczi 5302c53b1c51SStefan Hajnoczi for (i = 0; i < qiov->niov; i++) { 5303339064d5SKevin Wolf if ((uintptr_t) qiov->iov[i].iov_base % alignment) { 5304c53b1c51SStefan Hajnoczi return false; 5305c53b1c51SStefan Hajnoczi } 5306339064d5SKevin Wolf if (qiov->iov[i].iov_len % alignment) { 53071ff735bdSKevin Wolf return false; 53081ff735bdSKevin Wolf } 5309c53b1c51SStefan Hajnoczi } 5310c53b1c51SStefan Hajnoczi 5311c53b1c51SStefan Hajnoczi return true; 5312c53b1c51SStefan Hajnoczi } 5313c53b1c51SStefan Hajnoczi 5314b8afb520SFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs, int granularity, 5315b8afb520SFam Zheng Error **errp) 53167cd1e32aSlirans@il.ibm.com { 53177cd1e32aSlirans@il.ibm.com int64_t bitmap_size; 5318e4654d2dSFam Zheng BdrvDirtyBitmap *bitmap; 5319a55eb92cSJan Kiszka 532050717e94SPaolo Bonzini assert((granularity & (granularity - 1)) == 0); 532150717e94SPaolo Bonzini 532250717e94SPaolo Bonzini granularity >>= BDRV_SECTOR_BITS; 5323e4654d2dSFam Zheng assert(granularity); 5324b8afb520SFam Zheng bitmap_size = bdrv_getlength(bs); 5325b8afb520SFam Zheng if (bitmap_size < 0) { 5326b8afb520SFam Zheng error_setg_errno(errp, -bitmap_size, "could not get length of device"); 5327b8afb520SFam Zheng errno = -bitmap_size; 5328b8afb520SFam Zheng return NULL; 5329b8afb520SFam Zheng } 5330b8afb520SFam Zheng bitmap_size >>= BDRV_SECTOR_BITS; 5331e4654d2dSFam Zheng bitmap = g_malloc0(sizeof(BdrvDirtyBitmap)); 5332e4654d2dSFam Zheng bitmap->bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1); 5333e4654d2dSFam Zheng QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list); 5334e4654d2dSFam Zheng return bitmap; 5335e4654d2dSFam Zheng } 5336e4654d2dSFam Zheng 5337e4654d2dSFam Zheng void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap) 5338e4654d2dSFam Zheng { 5339e4654d2dSFam Zheng BdrvDirtyBitmap *bm, *next; 5340e4654d2dSFam Zheng QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) { 5341e4654d2dSFam Zheng if (bm == bitmap) { 5342e4654d2dSFam Zheng QLIST_REMOVE(bitmap, list); 5343e4654d2dSFam Zheng hbitmap_free(bitmap->bitmap); 5344e4654d2dSFam Zheng g_free(bitmap); 5345e4654d2dSFam Zheng return; 53467cd1e32aSlirans@il.ibm.com } 53477cd1e32aSlirans@il.ibm.com } 53487cd1e32aSlirans@il.ibm.com } 53497cd1e32aSlirans@il.ibm.com 535021b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs) 535121b56835SFam Zheng { 535221b56835SFam Zheng BdrvDirtyBitmap *bm; 535321b56835SFam Zheng BlockDirtyInfoList *list = NULL; 535421b56835SFam Zheng BlockDirtyInfoList **plist = &list; 535521b56835SFam Zheng 535621b56835SFam Zheng QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) { 535721b56835SFam Zheng BlockDirtyInfo *info = g_malloc0(sizeof(BlockDirtyInfo)); 535821b56835SFam Zheng BlockDirtyInfoList *entry = g_malloc0(sizeof(BlockDirtyInfoList)); 535921b56835SFam Zheng info->count = bdrv_get_dirty_count(bs, bm); 536021b56835SFam Zheng info->granularity = 536121b56835SFam Zheng ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bm->bitmap)); 536221b56835SFam Zheng entry->value = info; 536321b56835SFam Zheng *plist = entry; 536421b56835SFam Zheng plist = &entry->next; 536521b56835SFam Zheng } 536621b56835SFam Zheng 536721b56835SFam Zheng return list; 536821b56835SFam Zheng } 536921b56835SFam Zheng 5370e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector) 53717cd1e32aSlirans@il.ibm.com { 5372e4654d2dSFam Zheng if (bitmap) { 5373e4654d2dSFam Zheng return hbitmap_get(bitmap->bitmap, sector); 53747cd1e32aSlirans@il.ibm.com } else { 53757cd1e32aSlirans@il.ibm.com return 0; 53767cd1e32aSlirans@il.ibm.com } 53777cd1e32aSlirans@il.ibm.com } 53787cd1e32aSlirans@il.ibm.com 5379e4654d2dSFam Zheng void bdrv_dirty_iter_init(BlockDriverState *bs, 5380e4654d2dSFam Zheng BdrvDirtyBitmap *bitmap, HBitmapIter *hbi) 53811755da16SPaolo Bonzini { 5382e4654d2dSFam Zheng hbitmap_iter_init(hbi, bitmap->bitmap, 0); 53831755da16SPaolo Bonzini } 53841755da16SPaolo Bonzini 53851755da16SPaolo Bonzini void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector, 53861755da16SPaolo Bonzini int nr_sectors) 53871755da16SPaolo Bonzini { 5388e4654d2dSFam Zheng BdrvDirtyBitmap *bitmap; 5389e4654d2dSFam Zheng QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) { 5390e4654d2dSFam Zheng hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors); 5391e4654d2dSFam Zheng } 53921755da16SPaolo Bonzini } 53931755da16SPaolo Bonzini 5394e4654d2dSFam Zheng void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors) 53957cd1e32aSlirans@il.ibm.com { 5396e4654d2dSFam Zheng BdrvDirtyBitmap *bitmap; 5397e4654d2dSFam Zheng QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) { 5398e4654d2dSFam Zheng hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors); 5399e4654d2dSFam Zheng } 54007cd1e32aSlirans@il.ibm.com } 5401aaa0eb75SLiran Schour 5402e4654d2dSFam Zheng int64_t bdrv_get_dirty_count(BlockDriverState *bs, BdrvDirtyBitmap *bitmap) 5403aaa0eb75SLiran Schour { 5404e4654d2dSFam Zheng return hbitmap_count(bitmap->bitmap); 5405aaa0eb75SLiran Schour } 5406f88e1a42SJes Sorensen 54079fcb0251SFam Zheng /* Get a reference to bs */ 54089fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs) 54099fcb0251SFam Zheng { 54109fcb0251SFam Zheng bs->refcnt++; 54119fcb0251SFam Zheng } 54129fcb0251SFam Zheng 54139fcb0251SFam Zheng /* Release a previously grabbed reference to bs. 54149fcb0251SFam Zheng * If after releasing, reference count is zero, the BlockDriverState is 54159fcb0251SFam Zheng * deleted. */ 54169fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs) 54179fcb0251SFam Zheng { 54189fcb0251SFam Zheng assert(bs->refcnt > 0); 54199fcb0251SFam Zheng if (--bs->refcnt == 0) { 54209fcb0251SFam Zheng bdrv_delete(bs); 54219fcb0251SFam Zheng } 54229fcb0251SFam Zheng } 54239fcb0251SFam Zheng 5424fbe40ff7SFam Zheng struct BdrvOpBlocker { 5425fbe40ff7SFam Zheng Error *reason; 5426fbe40ff7SFam Zheng QLIST_ENTRY(BdrvOpBlocker) list; 5427fbe40ff7SFam Zheng }; 5428fbe40ff7SFam Zheng 5429fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp) 5430fbe40ff7SFam Zheng { 5431fbe40ff7SFam Zheng BdrvOpBlocker *blocker; 5432fbe40ff7SFam Zheng assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX); 5433fbe40ff7SFam Zheng if (!QLIST_EMPTY(&bs->op_blockers[op])) { 5434fbe40ff7SFam Zheng blocker = QLIST_FIRST(&bs->op_blockers[op]); 5435fbe40ff7SFam Zheng if (errp) { 5436fbe40ff7SFam Zheng error_setg(errp, "Device '%s' is busy: %s", 5437fbe40ff7SFam Zheng bs->device_name, error_get_pretty(blocker->reason)); 5438fbe40ff7SFam Zheng } 5439fbe40ff7SFam Zheng return true; 5440fbe40ff7SFam Zheng } 5441fbe40ff7SFam Zheng return false; 5442fbe40ff7SFam Zheng } 5443fbe40ff7SFam Zheng 5444fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason) 5445fbe40ff7SFam Zheng { 5446fbe40ff7SFam Zheng BdrvOpBlocker *blocker; 5447fbe40ff7SFam Zheng assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX); 5448fbe40ff7SFam Zheng 5449fbe40ff7SFam Zheng blocker = g_malloc0(sizeof(BdrvOpBlocker)); 5450fbe40ff7SFam Zheng blocker->reason = reason; 5451fbe40ff7SFam Zheng QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list); 5452fbe40ff7SFam Zheng } 5453fbe40ff7SFam Zheng 5454fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason) 5455fbe40ff7SFam Zheng { 5456fbe40ff7SFam Zheng BdrvOpBlocker *blocker, *next; 5457fbe40ff7SFam Zheng assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX); 5458fbe40ff7SFam Zheng QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) { 5459fbe40ff7SFam Zheng if (blocker->reason == reason) { 5460fbe40ff7SFam Zheng QLIST_REMOVE(blocker, list); 5461fbe40ff7SFam Zheng g_free(blocker); 5462fbe40ff7SFam Zheng } 5463fbe40ff7SFam Zheng } 5464fbe40ff7SFam Zheng } 5465fbe40ff7SFam Zheng 5466fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason) 5467fbe40ff7SFam Zheng { 5468fbe40ff7SFam Zheng int i; 5469fbe40ff7SFam Zheng for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { 5470fbe40ff7SFam Zheng bdrv_op_block(bs, i, reason); 5471fbe40ff7SFam Zheng } 5472fbe40ff7SFam Zheng } 5473fbe40ff7SFam Zheng 5474fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason) 5475fbe40ff7SFam Zheng { 5476fbe40ff7SFam Zheng int i; 5477fbe40ff7SFam Zheng for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { 5478fbe40ff7SFam Zheng bdrv_op_unblock(bs, i, reason); 5479fbe40ff7SFam Zheng } 5480fbe40ff7SFam Zheng } 5481fbe40ff7SFam Zheng 5482fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs) 5483fbe40ff7SFam Zheng { 5484fbe40ff7SFam Zheng int i; 5485fbe40ff7SFam Zheng 5486fbe40ff7SFam Zheng for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { 5487fbe40ff7SFam Zheng if (!QLIST_EMPTY(&bs->op_blockers[i])) { 5488fbe40ff7SFam Zheng return false; 5489fbe40ff7SFam Zheng } 5490fbe40ff7SFam Zheng } 5491fbe40ff7SFam Zheng return true; 5492fbe40ff7SFam Zheng } 5493fbe40ff7SFam Zheng 549428a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs) 549528a7282aSLuiz Capitulino { 5496d6bf279eSLuiz Capitulino bs->iostatus_enabled = true; 549758e21ef5SLuiz Capitulino bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK; 549828a7282aSLuiz Capitulino } 549928a7282aSLuiz Capitulino 550028a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly 550128a7282aSLuiz Capitulino * enables it _and_ the VM is configured to stop on errors */ 550228a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs) 550328a7282aSLuiz Capitulino { 5504d6bf279eSLuiz Capitulino return (bs->iostatus_enabled && 550592aa5c6dSPaolo Bonzini (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC || 550692aa5c6dSPaolo Bonzini bs->on_write_error == BLOCKDEV_ON_ERROR_STOP || 550792aa5c6dSPaolo Bonzini bs->on_read_error == BLOCKDEV_ON_ERROR_STOP)); 550828a7282aSLuiz Capitulino } 550928a7282aSLuiz Capitulino 551028a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs) 551128a7282aSLuiz Capitulino { 5512d6bf279eSLuiz Capitulino bs->iostatus_enabled = false; 551328a7282aSLuiz Capitulino } 551428a7282aSLuiz Capitulino 551528a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs) 551628a7282aSLuiz Capitulino { 551728a7282aSLuiz Capitulino if (bdrv_iostatus_is_enabled(bs)) { 551858e21ef5SLuiz Capitulino bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK; 55193bd293c3SPaolo Bonzini if (bs->job) { 55203bd293c3SPaolo Bonzini block_job_iostatus_reset(bs->job); 55213bd293c3SPaolo Bonzini } 552228a7282aSLuiz Capitulino } 552328a7282aSLuiz Capitulino } 552428a7282aSLuiz Capitulino 552528a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error) 552628a7282aSLuiz Capitulino { 55273e1caa5fSPaolo Bonzini assert(bdrv_iostatus_is_enabled(bs)); 55283e1caa5fSPaolo Bonzini if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) { 552958e21ef5SLuiz Capitulino bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE : 553058e21ef5SLuiz Capitulino BLOCK_DEVICE_IO_STATUS_FAILED; 553128a7282aSLuiz Capitulino } 553228a7282aSLuiz Capitulino } 553328a7282aSLuiz Capitulino 5534a597e79cSChristoph Hellwig void 5535a597e79cSChristoph Hellwig bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes, 5536a597e79cSChristoph Hellwig enum BlockAcctType type) 5537a597e79cSChristoph Hellwig { 5538a597e79cSChristoph Hellwig assert(type < BDRV_MAX_IOTYPE); 5539a597e79cSChristoph Hellwig 5540a597e79cSChristoph Hellwig cookie->bytes = bytes; 5541c488c7f6SChristoph Hellwig cookie->start_time_ns = get_clock(); 5542a597e79cSChristoph Hellwig cookie->type = type; 5543a597e79cSChristoph Hellwig } 5544a597e79cSChristoph Hellwig 5545a597e79cSChristoph Hellwig void 5546a597e79cSChristoph Hellwig bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie) 5547a597e79cSChristoph Hellwig { 5548a597e79cSChristoph Hellwig assert(cookie->type < BDRV_MAX_IOTYPE); 5549a597e79cSChristoph Hellwig 5550a597e79cSChristoph Hellwig bs->nr_bytes[cookie->type] += cookie->bytes; 5551a597e79cSChristoph Hellwig bs->nr_ops[cookie->type]++; 5552c488c7f6SChristoph Hellwig bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns; 5553a597e79cSChristoph Hellwig } 5554a597e79cSChristoph Hellwig 5555d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt, 5556f88e1a42SJes Sorensen const char *base_filename, const char *base_fmt, 5557f382d43aSMiroslav Rezanina char *options, uint64_t img_size, int flags, 5558f382d43aSMiroslav Rezanina Error **errp, bool quiet) 5559f88e1a42SJes Sorensen { 5560*83d0521aSChunyan Liu QemuOptsList *create_opts = NULL; 5561*83d0521aSChunyan Liu QemuOpts *opts = NULL; 5562*83d0521aSChunyan Liu const char *backing_fmt, *backing_file; 5563*83d0521aSChunyan Liu int64_t size; 5564f88e1a42SJes Sorensen BlockDriver *drv, *proto_drv; 556596df67d1SStefan Hajnoczi BlockDriver *backing_drv = NULL; 5566cc84d90fSMax Reitz Error *local_err = NULL; 5567f88e1a42SJes Sorensen int ret = 0; 5568f88e1a42SJes Sorensen 5569f88e1a42SJes Sorensen /* Find driver and parse its options */ 5570f88e1a42SJes Sorensen drv = bdrv_find_format(fmt); 5571f88e1a42SJes Sorensen if (!drv) { 557271c79813SLuiz Capitulino error_setg(errp, "Unknown file format '%s'", fmt); 5573d92ada22SLuiz Capitulino return; 5574f88e1a42SJes Sorensen } 5575f88e1a42SJes Sorensen 557698289620SKevin Wolf proto_drv = bdrv_find_protocol(filename, true); 5577f88e1a42SJes Sorensen if (!proto_drv) { 557871c79813SLuiz Capitulino error_setg(errp, "Unknown protocol '%s'", filename); 5579d92ada22SLuiz Capitulino return; 5580f88e1a42SJes Sorensen } 5581f88e1a42SJes Sorensen 5582*83d0521aSChunyan Liu create_opts = qemu_opts_append(create_opts, drv->create_opts, 5583f88e1a42SJes Sorensen drv->create_options); 5584*83d0521aSChunyan Liu create_opts = qemu_opts_append(create_opts, proto_drv->create_opts, 5585f88e1a42SJes Sorensen proto_drv->create_options); 5586f88e1a42SJes Sorensen 5587f88e1a42SJes Sorensen /* Create parameter list with default values */ 5588*83d0521aSChunyan Liu opts = qemu_opts_create(create_opts, NULL, 0, &error_abort); 5589*83d0521aSChunyan Liu qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size); 5590f88e1a42SJes Sorensen 5591f88e1a42SJes Sorensen /* Parse -o options */ 5592f88e1a42SJes Sorensen if (options) { 5593*83d0521aSChunyan Liu if (qemu_opts_do_parse(opts, options, NULL) != 0) { 5594*83d0521aSChunyan Liu error_setg(errp, "Invalid options for file format '%s'", fmt); 5595f88e1a42SJes Sorensen goto out; 5596f88e1a42SJes Sorensen } 5597f88e1a42SJes Sorensen } 5598f88e1a42SJes Sorensen 5599f88e1a42SJes Sorensen if (base_filename) { 5600*83d0521aSChunyan Liu if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename)) { 560171c79813SLuiz Capitulino error_setg(errp, "Backing file not supported for file format '%s'", 560271c79813SLuiz Capitulino fmt); 5603f88e1a42SJes Sorensen goto out; 5604f88e1a42SJes Sorensen } 5605f88e1a42SJes Sorensen } 5606f88e1a42SJes Sorensen 5607f88e1a42SJes Sorensen if (base_fmt) { 5608*83d0521aSChunyan Liu if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt)) { 560971c79813SLuiz Capitulino error_setg(errp, "Backing file format not supported for file " 561071c79813SLuiz Capitulino "format '%s'", fmt); 5611f88e1a42SJes Sorensen goto out; 5612f88e1a42SJes Sorensen } 5613f88e1a42SJes Sorensen } 5614f88e1a42SJes Sorensen 5615*83d0521aSChunyan Liu backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE); 5616*83d0521aSChunyan Liu if (backing_file) { 5617*83d0521aSChunyan Liu if (!strcmp(filename, backing_file)) { 561871c79813SLuiz Capitulino error_setg(errp, "Error: Trying to create an image with the " 561971c79813SLuiz Capitulino "same filename as the backing file"); 5620792da93aSJes Sorensen goto out; 5621792da93aSJes Sorensen } 5622792da93aSJes Sorensen } 5623792da93aSJes Sorensen 5624*83d0521aSChunyan Liu backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT); 5625*83d0521aSChunyan Liu if (backing_fmt) { 5626*83d0521aSChunyan Liu backing_drv = bdrv_find_format(backing_fmt); 562796df67d1SStefan Hajnoczi if (!backing_drv) { 562871c79813SLuiz Capitulino error_setg(errp, "Unknown backing file format '%s'", 5629*83d0521aSChunyan Liu backing_fmt); 5630f88e1a42SJes Sorensen goto out; 5631f88e1a42SJes Sorensen } 5632f88e1a42SJes Sorensen } 5633f88e1a42SJes Sorensen 5634f88e1a42SJes Sorensen // The size for the image must always be specified, with one exception: 5635f88e1a42SJes Sorensen // If we are using a backing file, we can obtain the size from there 5636*83d0521aSChunyan Liu size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0); 5637*83d0521aSChunyan Liu if (size == -1) { 5638*83d0521aSChunyan Liu if (backing_file) { 563966f6b814SMax Reitz BlockDriverState *bs; 5640f88e1a42SJes Sorensen uint64_t size; 5641f88e1a42SJes Sorensen char buf[32]; 564263090dacSPaolo Bonzini int back_flags; 564363090dacSPaolo Bonzini 564463090dacSPaolo Bonzini /* backing files always opened read-only */ 564563090dacSPaolo Bonzini back_flags = 564663090dacSPaolo Bonzini flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING); 5647f88e1a42SJes Sorensen 5648f67503e5SMax Reitz bs = NULL; 5649*83d0521aSChunyan Liu ret = bdrv_open(&bs, backing_file, NULL, NULL, back_flags, 5650cc84d90fSMax Reitz backing_drv, &local_err); 5651f88e1a42SJes Sorensen if (ret < 0) { 5652cc84d90fSMax Reitz error_setg_errno(errp, -ret, "Could not open '%s': %s", 5653*83d0521aSChunyan Liu backing_file, 5654cc84d90fSMax Reitz error_get_pretty(local_err)); 5655cc84d90fSMax Reitz error_free(local_err); 5656cc84d90fSMax Reitz local_err = NULL; 5657f88e1a42SJes Sorensen goto out; 5658f88e1a42SJes Sorensen } 5659f88e1a42SJes Sorensen bdrv_get_geometry(bs, &size); 5660f88e1a42SJes Sorensen size *= 512; 5661f88e1a42SJes Sorensen 5662f88e1a42SJes Sorensen snprintf(buf, sizeof(buf), "%" PRId64, size); 5663*83d0521aSChunyan Liu qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size); 566466f6b814SMax Reitz 566566f6b814SMax Reitz bdrv_unref(bs); 5666f88e1a42SJes Sorensen } else { 566771c79813SLuiz Capitulino error_setg(errp, "Image creation needs a size parameter"); 5668f88e1a42SJes Sorensen goto out; 5669f88e1a42SJes Sorensen } 5670f88e1a42SJes Sorensen } 5671f88e1a42SJes Sorensen 5672f382d43aSMiroslav Rezanina if (!quiet) { 5673f88e1a42SJes Sorensen printf("Formatting '%s', fmt=%s ", filename, fmt); 5674*83d0521aSChunyan Liu qemu_opts_print(opts); 5675f88e1a42SJes Sorensen puts(""); 5676f382d43aSMiroslav Rezanina } 5677*83d0521aSChunyan Liu 5678*83d0521aSChunyan Liu ret = bdrv_create(drv, filename, NULL, opts, &local_err); 5679*83d0521aSChunyan Liu 5680cc84d90fSMax Reitz if (ret == -EFBIG) { 5681cc84d90fSMax Reitz /* This is generally a better message than whatever the driver would 5682cc84d90fSMax Reitz * deliver (especially because of the cluster_size_hint), since that 5683cc84d90fSMax Reitz * is most probably not much different from "image too large". */ 5684f3f4d2c0SKevin Wolf const char *cluster_size_hint = ""; 5685*83d0521aSChunyan Liu if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) { 5686f3f4d2c0SKevin Wolf cluster_size_hint = " (try using a larger cluster size)"; 5687f3f4d2c0SKevin Wolf } 5688cc84d90fSMax Reitz error_setg(errp, "The image size is too large for file format '%s'" 5689cc84d90fSMax Reitz "%s", fmt, cluster_size_hint); 5690cc84d90fSMax Reitz error_free(local_err); 5691cc84d90fSMax Reitz local_err = NULL; 5692f88e1a42SJes Sorensen } 5693f88e1a42SJes Sorensen 5694f88e1a42SJes Sorensen out: 5695*83d0521aSChunyan Liu qemu_opts_del(opts); 5696*83d0521aSChunyan Liu qemu_opts_free(create_opts); 569784d18f06SMarkus Armbruster if (local_err) { 5698cc84d90fSMax Reitz error_propagate(errp, local_err); 5699cc84d90fSMax Reitz } 5700f88e1a42SJes Sorensen } 570185d126f3SStefan Hajnoczi 570285d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs) 570385d126f3SStefan Hajnoczi { 5704dcd04228SStefan Hajnoczi return bs->aio_context; 5705dcd04228SStefan Hajnoczi } 5706dcd04228SStefan Hajnoczi 5707dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs) 5708dcd04228SStefan Hajnoczi { 5709dcd04228SStefan Hajnoczi if (!bs->drv) { 5710dcd04228SStefan Hajnoczi return; 5711dcd04228SStefan Hajnoczi } 5712dcd04228SStefan Hajnoczi 571313af91ebSStefan Hajnoczi if (bs->io_limits_enabled) { 571413af91ebSStefan Hajnoczi throttle_detach_aio_context(&bs->throttle_state); 571513af91ebSStefan Hajnoczi } 5716dcd04228SStefan Hajnoczi if (bs->drv->bdrv_detach_aio_context) { 5717dcd04228SStefan Hajnoczi bs->drv->bdrv_detach_aio_context(bs); 5718dcd04228SStefan Hajnoczi } 5719dcd04228SStefan Hajnoczi if (bs->file) { 5720dcd04228SStefan Hajnoczi bdrv_detach_aio_context(bs->file); 5721dcd04228SStefan Hajnoczi } 5722dcd04228SStefan Hajnoczi if (bs->backing_hd) { 5723dcd04228SStefan Hajnoczi bdrv_detach_aio_context(bs->backing_hd); 5724dcd04228SStefan Hajnoczi } 5725dcd04228SStefan Hajnoczi 5726dcd04228SStefan Hajnoczi bs->aio_context = NULL; 5727dcd04228SStefan Hajnoczi } 5728dcd04228SStefan Hajnoczi 5729dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs, 5730dcd04228SStefan Hajnoczi AioContext *new_context) 5731dcd04228SStefan Hajnoczi { 5732dcd04228SStefan Hajnoczi if (!bs->drv) { 5733dcd04228SStefan Hajnoczi return; 5734dcd04228SStefan Hajnoczi } 5735dcd04228SStefan Hajnoczi 5736dcd04228SStefan Hajnoczi bs->aio_context = new_context; 5737dcd04228SStefan Hajnoczi 5738dcd04228SStefan Hajnoczi if (bs->backing_hd) { 5739dcd04228SStefan Hajnoczi bdrv_attach_aio_context(bs->backing_hd, new_context); 5740dcd04228SStefan Hajnoczi } 5741dcd04228SStefan Hajnoczi if (bs->file) { 5742dcd04228SStefan Hajnoczi bdrv_attach_aio_context(bs->file, new_context); 5743dcd04228SStefan Hajnoczi } 5744dcd04228SStefan Hajnoczi if (bs->drv->bdrv_attach_aio_context) { 5745dcd04228SStefan Hajnoczi bs->drv->bdrv_attach_aio_context(bs, new_context); 5746dcd04228SStefan Hajnoczi } 574713af91ebSStefan Hajnoczi if (bs->io_limits_enabled) { 574813af91ebSStefan Hajnoczi throttle_attach_aio_context(&bs->throttle_state, new_context); 574913af91ebSStefan Hajnoczi } 5750dcd04228SStefan Hajnoczi } 5751dcd04228SStefan Hajnoczi 5752dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context) 5753dcd04228SStefan Hajnoczi { 5754dcd04228SStefan Hajnoczi bdrv_drain_all(); /* ensure there are no in-flight requests */ 5755dcd04228SStefan Hajnoczi 5756dcd04228SStefan Hajnoczi bdrv_detach_aio_context(bs); 5757dcd04228SStefan Hajnoczi 5758dcd04228SStefan Hajnoczi /* This function executes in the old AioContext so acquire the new one in 5759dcd04228SStefan Hajnoczi * case it runs in a different thread. 5760dcd04228SStefan Hajnoczi */ 5761dcd04228SStefan Hajnoczi aio_context_acquire(new_context); 5762dcd04228SStefan Hajnoczi bdrv_attach_aio_context(bs, new_context); 5763dcd04228SStefan Hajnoczi aio_context_release(new_context); 576485d126f3SStefan Hajnoczi } 5765d616b224SStefan Hajnoczi 5766d616b224SStefan Hajnoczi void bdrv_add_before_write_notifier(BlockDriverState *bs, 5767d616b224SStefan Hajnoczi NotifierWithReturn *notifier) 5768d616b224SStefan Hajnoczi { 5769d616b224SStefan Hajnoczi notifier_with_return_list_add(&bs->before_write_notifiers, notifier); 5770d616b224SStefan Hajnoczi } 57716f176b48SMax Reitz 5772*83d0521aSChunyan Liu int bdrv_amend_options(BlockDriverState *bs, QEMUOptionParameter *options, 5773*83d0521aSChunyan Liu QemuOpts *opts) 57746f176b48SMax Reitz { 5775*83d0521aSChunyan Liu int ret; 5776*83d0521aSChunyan Liu assert(!(options && opts)); 5777*83d0521aSChunyan Liu 5778*83d0521aSChunyan Liu if (!bs->drv->bdrv_amend_options && !bs->drv->bdrv_amend_options2) { 57796f176b48SMax Reitz return -ENOTSUP; 57806f176b48SMax Reitz } 5781*83d0521aSChunyan Liu if (bs->drv->bdrv_amend_options2) { 5782*83d0521aSChunyan Liu QemuOptsList *opts_list = NULL; 5783*83d0521aSChunyan Liu if (options) { 5784*83d0521aSChunyan Liu opts_list = params_to_opts(options); 5785*83d0521aSChunyan Liu opts = qemu_opts_create(opts_list, NULL, 0, &error_abort); 5786*83d0521aSChunyan Liu } 5787*83d0521aSChunyan Liu ret = bs->drv->bdrv_amend_options2(bs, opts); 5788*83d0521aSChunyan Liu if (options) { 5789*83d0521aSChunyan Liu qemu_opts_del(opts); 5790*83d0521aSChunyan Liu qemu_opts_free(opts_list); 5791*83d0521aSChunyan Liu } 5792*83d0521aSChunyan Liu } else { 5793*83d0521aSChunyan Liu if (opts) { 5794*83d0521aSChunyan Liu options = opts_to_params(opts); 5795*83d0521aSChunyan Liu } 5796*83d0521aSChunyan Liu ret = bs->drv->bdrv_amend_options(bs, options); 5797*83d0521aSChunyan Liu if (opts) { 5798*83d0521aSChunyan Liu free_option_parameters(options); 5799*83d0521aSChunyan Liu } 5800*83d0521aSChunyan Liu } 5801*83d0521aSChunyan Liu return ret; 58026f176b48SMax Reitz } 5803f6186f49SBenoît Canet 5804b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method 5805b5042a36SBenoît Canet * of block filter and by bdrv_is_first_non_filter. 5806b5042a36SBenoît Canet * It is used to test if the given bs is the candidate or recurse more in the 5807b5042a36SBenoît Canet * node graph. 5808212a5a8fSBenoît Canet */ 5809212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs, 5810212a5a8fSBenoît Canet BlockDriverState *candidate) 5811f6186f49SBenoît Canet { 5812b5042a36SBenoît Canet /* return false if basic checks fails */ 5813b5042a36SBenoît Canet if (!bs || !bs->drv) { 5814b5042a36SBenoît Canet return false; 5815b5042a36SBenoît Canet } 5816b5042a36SBenoît Canet 5817b5042a36SBenoît Canet /* the code reached a non block filter driver -> check if the bs is 5818b5042a36SBenoît Canet * the same as the candidate. It's the recursion termination condition. 5819b5042a36SBenoît Canet */ 5820b5042a36SBenoît Canet if (!bs->drv->is_filter) { 5821b5042a36SBenoît Canet return bs == candidate; 5822b5042a36SBenoît Canet } 5823b5042a36SBenoît Canet /* Down this path the driver is a block filter driver */ 5824b5042a36SBenoît Canet 5825b5042a36SBenoît Canet /* If the block filter recursion method is defined use it to recurse down 5826b5042a36SBenoît Canet * the node graph. 5827b5042a36SBenoît Canet */ 5828b5042a36SBenoît Canet if (bs->drv->bdrv_recurse_is_first_non_filter) { 5829212a5a8fSBenoît Canet return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate); 5830212a5a8fSBenoît Canet } 5831212a5a8fSBenoît Canet 5832b5042a36SBenoît Canet /* the driver is a block filter but don't allow to recurse -> return false 5833b5042a36SBenoît Canet */ 5834b5042a36SBenoît Canet return false; 5835212a5a8fSBenoît Canet } 5836212a5a8fSBenoît Canet 5837212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's 5838212a5a8fSBenoît Canet * bs chain. Since we don't have pointers to parents it explore all bs chains 5839212a5a8fSBenoît Canet * from the top. Some filters can choose not to pass down the recursion. 5840212a5a8fSBenoît Canet */ 5841212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate) 5842212a5a8fSBenoît Canet { 5843212a5a8fSBenoît Canet BlockDriverState *bs; 5844212a5a8fSBenoît Canet 5845212a5a8fSBenoît Canet /* walk down the bs forest recursively */ 5846212a5a8fSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 5847212a5a8fSBenoît Canet bool perm; 5848212a5a8fSBenoît Canet 5849b5042a36SBenoît Canet /* try to recurse in this top level bs */ 5850e6dc8a1fSKevin Wolf perm = bdrv_recurse_is_first_non_filter(bs, candidate); 5851212a5a8fSBenoît Canet 5852212a5a8fSBenoît Canet /* candidate is the first non filter */ 5853212a5a8fSBenoît Canet if (perm) { 5854212a5a8fSBenoît Canet return true; 5855212a5a8fSBenoît Canet } 5856212a5a8fSBenoît Canet } 5857212a5a8fSBenoît Canet 5858212a5a8fSBenoît Canet return false; 5859f6186f49SBenoît Canet } 5860