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" 27737e150eSPaolo Bonzini #include "block/block_int.h" 28737e150eSPaolo Bonzini #include "block/blockjob.h" 291de7afc9SPaolo Bonzini #include "qemu/module.h" 307b1b5d19SPaolo Bonzini #include "qapi/qmp/qjson.h" 319c17d615SPaolo Bonzini #include "sysemu/sysemu.h" 321de7afc9SPaolo Bonzini #include "qemu/notify.h" 33737e150eSPaolo Bonzini #include "block/coroutine.h" 34c13163fbSBenoît Canet #include "block/qapi.h" 35b2023818SLuiz Capitulino #include "qmp-commands.h" 361de7afc9SPaolo Bonzini #include "qemu/timer.h" 37a5ee7bd4SWenchao Xia #include "qapi-event.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 60*2a87151fSStefan Hajnoczi #define COROUTINE_POOL_RESERVATION 64 /* number of coroutines to reserve */ 61*2a87151fSStefan Hajnoczi 627d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load); 63f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs, 64f141eafeSaliguori int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, 65c87c0672Saliguori BlockDriverCompletionFunc *cb, void *opaque); 66f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs, 67f141eafeSaliguori int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, 68ce1a14dcSpbrook BlockDriverCompletionFunc *cb, void *opaque); 69f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs, 70f9f05dc5SKevin Wolf int64_t sector_num, int nb_sectors, 71f9f05dc5SKevin Wolf QEMUIOVector *iov); 72f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs, 73f9f05dc5SKevin Wolf int64_t sector_num, int nb_sectors, 74f9f05dc5SKevin Wolf QEMUIOVector *iov); 75775aa8b6SKevin Wolf static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs, 76775aa8b6SKevin Wolf int64_t offset, unsigned int bytes, QEMUIOVector *qiov, 77470c0504SStefan Hajnoczi BdrvRequestFlags flags); 78775aa8b6SKevin Wolf static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs, 79775aa8b6SKevin Wolf int64_t offset, unsigned int bytes, QEMUIOVector *qiov, 80f08f2ddaSStefan Hajnoczi BdrvRequestFlags flags); 81b2a61371SStefan Hajnoczi static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs, 82b2a61371SStefan Hajnoczi int64_t sector_num, 83b2a61371SStefan Hajnoczi QEMUIOVector *qiov, 84b2a61371SStefan Hajnoczi int nb_sectors, 85d20d9b7cSPaolo Bonzini BdrvRequestFlags flags, 86b2a61371SStefan Hajnoczi BlockDriverCompletionFunc *cb, 87b2a61371SStefan Hajnoczi void *opaque, 888c5873d6SStefan Hajnoczi bool is_write); 89b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque); 90621f0589SKevin Wolf static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs, 91aa7bfbffSPeter Lieven int64_t sector_num, int nb_sectors, BdrvRequestFlags flags); 92ec530c81Sbellard 931b7bdbc1SStefan Hajnoczi static QTAILQ_HEAD(, BlockDriverState) bdrv_states = 941b7bdbc1SStefan Hajnoczi QTAILQ_HEAD_INITIALIZER(bdrv_states); 957ee930d0Sblueswir1 96dc364f4cSBenoît Canet static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states = 97dc364f4cSBenoît Canet QTAILQ_HEAD_INITIALIZER(graph_bdrv_states); 98dc364f4cSBenoît Canet 998a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers = 1008a22f02aSStefan Hajnoczi QLIST_HEAD_INITIALIZER(bdrv_drivers); 101ea2384d3Sbellard 102eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */ 103eb852011SMarkus Armbruster static int use_bdrv_whitelist; 104eb852011SMarkus Armbruster 1059e0b22f4SStefan Hajnoczi #ifdef _WIN32 1069e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename) 1079e0b22f4SStefan Hajnoczi { 1089e0b22f4SStefan Hajnoczi return (((filename[0] >= 'a' && filename[0] <= 'z') || 1099e0b22f4SStefan Hajnoczi (filename[0] >= 'A' && filename[0] <= 'Z')) && 1109e0b22f4SStefan Hajnoczi filename[1] == ':'); 1119e0b22f4SStefan Hajnoczi } 1129e0b22f4SStefan Hajnoczi 1139e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename) 1149e0b22f4SStefan Hajnoczi { 1159e0b22f4SStefan Hajnoczi if (is_windows_drive_prefix(filename) && 1169e0b22f4SStefan Hajnoczi filename[2] == '\0') 1179e0b22f4SStefan Hajnoczi return 1; 1189e0b22f4SStefan Hajnoczi if (strstart(filename, "\\\\.\\", NULL) || 1199e0b22f4SStefan Hajnoczi strstart(filename, "//./", NULL)) 1209e0b22f4SStefan Hajnoczi return 1; 1219e0b22f4SStefan Hajnoczi return 0; 1229e0b22f4SStefan Hajnoczi } 1239e0b22f4SStefan Hajnoczi #endif 1249e0b22f4SStefan Hajnoczi 1250563e191SZhi Yong Wu /* throttling disk I/O limits */ 126cc0681c4SBenoît Canet void bdrv_set_io_limits(BlockDriverState *bs, 127cc0681c4SBenoît Canet ThrottleConfig *cfg) 128cc0681c4SBenoît Canet { 129cc0681c4SBenoît Canet int i; 130cc0681c4SBenoît Canet 131cc0681c4SBenoît Canet throttle_config(&bs->throttle_state, cfg); 132cc0681c4SBenoît Canet 133cc0681c4SBenoît Canet for (i = 0; i < 2; i++) { 134cc0681c4SBenoît Canet qemu_co_enter_next(&bs->throttled_reqs[i]); 135cc0681c4SBenoît Canet } 136cc0681c4SBenoît Canet } 137cc0681c4SBenoît Canet 138cc0681c4SBenoît Canet /* this function drain all the throttled IOs */ 139cc0681c4SBenoît Canet static bool bdrv_start_throttled_reqs(BlockDriverState *bs) 140cc0681c4SBenoît Canet { 141cc0681c4SBenoît Canet bool drained = false; 142cc0681c4SBenoît Canet bool enabled = bs->io_limits_enabled; 143cc0681c4SBenoît Canet int i; 144cc0681c4SBenoît Canet 145cc0681c4SBenoît Canet bs->io_limits_enabled = false; 146cc0681c4SBenoît Canet 147cc0681c4SBenoît Canet for (i = 0; i < 2; i++) { 148cc0681c4SBenoît Canet while (qemu_co_enter_next(&bs->throttled_reqs[i])) { 149cc0681c4SBenoît Canet drained = true; 150cc0681c4SBenoît Canet } 151cc0681c4SBenoît Canet } 152cc0681c4SBenoît Canet 153cc0681c4SBenoît Canet bs->io_limits_enabled = enabled; 154cc0681c4SBenoît Canet 155cc0681c4SBenoît Canet return drained; 156cc0681c4SBenoît Canet } 157cc0681c4SBenoît Canet 15898f90dbaSZhi Yong Wu void bdrv_io_limits_disable(BlockDriverState *bs) 15998f90dbaSZhi Yong Wu { 16098f90dbaSZhi Yong Wu bs->io_limits_enabled = false; 16198f90dbaSZhi Yong Wu 162cc0681c4SBenoît Canet bdrv_start_throttled_reqs(bs); 16398f90dbaSZhi Yong Wu 164cc0681c4SBenoît Canet throttle_destroy(&bs->throttle_state); 16598f90dbaSZhi Yong Wu } 16698f90dbaSZhi Yong Wu 167cc0681c4SBenoît Canet static void bdrv_throttle_read_timer_cb(void *opaque) 1680563e191SZhi Yong Wu { 1690563e191SZhi Yong Wu BlockDriverState *bs = opaque; 170cc0681c4SBenoît Canet qemu_co_enter_next(&bs->throttled_reqs[0]); 1710563e191SZhi Yong Wu } 1720563e191SZhi Yong Wu 173cc0681c4SBenoît Canet static void bdrv_throttle_write_timer_cb(void *opaque) 174cc0681c4SBenoît Canet { 175cc0681c4SBenoît Canet BlockDriverState *bs = opaque; 176cc0681c4SBenoît Canet qemu_co_enter_next(&bs->throttled_reqs[1]); 177cc0681c4SBenoît Canet } 178cc0681c4SBenoît Canet 179cc0681c4SBenoît Canet /* should be called before bdrv_set_io_limits if a limit is set */ 1800563e191SZhi Yong Wu void bdrv_io_limits_enable(BlockDriverState *bs) 1810563e191SZhi Yong Wu { 182cc0681c4SBenoît Canet assert(!bs->io_limits_enabled); 183cc0681c4SBenoît Canet throttle_init(&bs->throttle_state, 18413af91ebSStefan Hajnoczi bdrv_get_aio_context(bs), 185cc0681c4SBenoît Canet QEMU_CLOCK_VIRTUAL, 186cc0681c4SBenoît Canet bdrv_throttle_read_timer_cb, 187cc0681c4SBenoît Canet bdrv_throttle_write_timer_cb, 188cc0681c4SBenoît Canet bs); 1890563e191SZhi Yong Wu bs->io_limits_enabled = true; 1900563e191SZhi Yong Wu } 1910563e191SZhi Yong Wu 192cc0681c4SBenoît Canet /* This function makes an IO wait if needed 193cc0681c4SBenoît Canet * 194cc0681c4SBenoît Canet * @nb_sectors: the number of sectors of the IO 195cc0681c4SBenoît Canet * @is_write: is the IO a write 19698f90dbaSZhi Yong Wu */ 197cc0681c4SBenoît Canet static void bdrv_io_limits_intercept(BlockDriverState *bs, 198d5103588SKevin Wolf unsigned int bytes, 199cc0681c4SBenoît Canet bool is_write) 200cc0681c4SBenoît Canet { 201cc0681c4SBenoît Canet /* does this io must wait */ 202cc0681c4SBenoît Canet bool must_wait = throttle_schedule_timer(&bs->throttle_state, is_write); 20398f90dbaSZhi Yong Wu 204cc0681c4SBenoît Canet /* if must wait or any request of this type throttled queue the IO */ 205cc0681c4SBenoît Canet if (must_wait || 206cc0681c4SBenoît Canet !qemu_co_queue_empty(&bs->throttled_reqs[is_write])) { 207cc0681c4SBenoît Canet qemu_co_queue_wait(&bs->throttled_reqs[is_write]); 20898f90dbaSZhi Yong Wu } 20998f90dbaSZhi Yong Wu 210cc0681c4SBenoît Canet /* the IO will be executed, do the accounting */ 211d5103588SKevin Wolf throttle_account(&bs->throttle_state, is_write, bytes); 212d5103588SKevin Wolf 213cc0681c4SBenoît Canet 214cc0681c4SBenoît Canet /* if the next request must wait -> do nothing */ 215cc0681c4SBenoît Canet if (throttle_schedule_timer(&bs->throttle_state, is_write)) { 216cc0681c4SBenoît Canet return; 217cc0681c4SBenoît Canet } 218cc0681c4SBenoît Canet 219cc0681c4SBenoît Canet /* else queue next request for execution */ 220cc0681c4SBenoît Canet qemu_co_queue_next(&bs->throttled_reqs[is_write]); 22198f90dbaSZhi Yong Wu } 22298f90dbaSZhi Yong Wu 223339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs) 224339064d5SKevin Wolf { 225339064d5SKevin Wolf if (!bs || !bs->drv) { 226339064d5SKevin Wolf /* 4k should be on the safe side */ 227339064d5SKevin Wolf return 4096; 228339064d5SKevin Wolf } 229339064d5SKevin Wolf 230339064d5SKevin Wolf return bs->bl.opt_mem_alignment; 231339064d5SKevin Wolf } 232339064d5SKevin Wolf 2339e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */ 2349e0b22f4SStefan Hajnoczi static int path_has_protocol(const char *path) 2359e0b22f4SStefan Hajnoczi { 236947995c0SPaolo Bonzini const char *p; 237947995c0SPaolo Bonzini 2389e0b22f4SStefan Hajnoczi #ifdef _WIN32 2399e0b22f4SStefan Hajnoczi if (is_windows_drive(path) || 2409e0b22f4SStefan Hajnoczi is_windows_drive_prefix(path)) { 2419e0b22f4SStefan Hajnoczi return 0; 2429e0b22f4SStefan Hajnoczi } 243947995c0SPaolo Bonzini p = path + strcspn(path, ":/\\"); 244947995c0SPaolo Bonzini #else 245947995c0SPaolo Bonzini p = path + strcspn(path, ":/"); 2469e0b22f4SStefan Hajnoczi #endif 2479e0b22f4SStefan Hajnoczi 248947995c0SPaolo Bonzini return *p == ':'; 2499e0b22f4SStefan Hajnoczi } 2509e0b22f4SStefan Hajnoczi 25183f64091Sbellard int path_is_absolute(const char *path) 25283f64091Sbellard { 25321664424Sbellard #ifdef _WIN32 25421664424Sbellard /* specific case for names like: "\\.\d:" */ 255f53f4da9SPaolo Bonzini if (is_windows_drive(path) || is_windows_drive_prefix(path)) { 25621664424Sbellard return 1; 257f53f4da9SPaolo Bonzini } 258f53f4da9SPaolo Bonzini return (*path == '/' || *path == '\\'); 2593b9f94e1Sbellard #else 260f53f4da9SPaolo Bonzini return (*path == '/'); 2613b9f94e1Sbellard #endif 26283f64091Sbellard } 26383f64091Sbellard 26483f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a 26583f64091Sbellard path to it by considering it is relative to base_path. URL are 26683f64091Sbellard supported. */ 26783f64091Sbellard void path_combine(char *dest, int dest_size, 26883f64091Sbellard const char *base_path, 26983f64091Sbellard const char *filename) 27083f64091Sbellard { 27183f64091Sbellard const char *p, *p1; 27283f64091Sbellard int len; 27383f64091Sbellard 27483f64091Sbellard if (dest_size <= 0) 27583f64091Sbellard return; 27683f64091Sbellard if (path_is_absolute(filename)) { 27783f64091Sbellard pstrcpy(dest, dest_size, filename); 27883f64091Sbellard } else { 27983f64091Sbellard p = strchr(base_path, ':'); 28083f64091Sbellard if (p) 28183f64091Sbellard p++; 28283f64091Sbellard else 28383f64091Sbellard p = base_path; 2843b9f94e1Sbellard p1 = strrchr(base_path, '/'); 2853b9f94e1Sbellard #ifdef _WIN32 2863b9f94e1Sbellard { 2873b9f94e1Sbellard const char *p2; 2883b9f94e1Sbellard p2 = strrchr(base_path, '\\'); 2893b9f94e1Sbellard if (!p1 || p2 > p1) 2903b9f94e1Sbellard p1 = p2; 2913b9f94e1Sbellard } 2923b9f94e1Sbellard #endif 29383f64091Sbellard if (p1) 29483f64091Sbellard p1++; 29583f64091Sbellard else 29683f64091Sbellard p1 = base_path; 29783f64091Sbellard if (p1 > p) 29883f64091Sbellard p = p1; 29983f64091Sbellard len = p - base_path; 30083f64091Sbellard if (len > dest_size - 1) 30183f64091Sbellard len = dest_size - 1; 30283f64091Sbellard memcpy(dest, base_path, len); 30383f64091Sbellard dest[len] = '\0'; 30483f64091Sbellard pstrcat(dest, dest_size, filename); 30583f64091Sbellard } 30683f64091Sbellard } 30783f64091Sbellard 308dc5a1371SPaolo Bonzini void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz) 309dc5a1371SPaolo Bonzini { 310dc5a1371SPaolo Bonzini if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) { 311dc5a1371SPaolo Bonzini pstrcpy(dest, sz, bs->backing_file); 312dc5a1371SPaolo Bonzini } else { 313dc5a1371SPaolo Bonzini path_combine(dest, sz, bs->filename, bs->backing_file); 314dc5a1371SPaolo Bonzini } 315dc5a1371SPaolo Bonzini } 316dc5a1371SPaolo Bonzini 3175efa9d5aSAnthony Liguori void bdrv_register(BlockDriver *bdrv) 318ea2384d3Sbellard { 3198c5873d6SStefan Hajnoczi /* Block drivers without coroutine functions need emulation */ 3208c5873d6SStefan Hajnoczi if (!bdrv->bdrv_co_readv) { 321f9f05dc5SKevin Wolf bdrv->bdrv_co_readv = bdrv_co_readv_em; 322f9f05dc5SKevin Wolf bdrv->bdrv_co_writev = bdrv_co_writev_em; 323f9f05dc5SKevin Wolf 324f8c35c1dSStefan Hajnoczi /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if 325f8c35c1dSStefan Hajnoczi * the block driver lacks aio we need to emulate that too. 326f8c35c1dSStefan Hajnoczi */ 327f9f05dc5SKevin Wolf if (!bdrv->bdrv_aio_readv) { 32883f64091Sbellard /* add AIO emulation layer */ 329f141eafeSaliguori bdrv->bdrv_aio_readv = bdrv_aio_readv_em; 330f141eafeSaliguori bdrv->bdrv_aio_writev = bdrv_aio_writev_em; 33183f64091Sbellard } 332f9f05dc5SKevin Wolf } 333b2e12bc6SChristoph Hellwig 3348a22f02aSStefan Hajnoczi QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list); 335ea2384d3Sbellard } 336b338082bSbellard 337b338082bSbellard /* create a new block device (by default it is empty) */ 33898522f63SKevin Wolf BlockDriverState *bdrv_new(const char *device_name, Error **errp) 339fc01f7e7Sbellard { 3401b7bdbc1SStefan Hajnoczi BlockDriverState *bs; 341fbe40ff7SFam Zheng int i; 342b338082bSbellard 343f2d953ecSKevin Wolf if (bdrv_find(device_name)) { 344f2d953ecSKevin Wolf error_setg(errp, "Device with id '%s' already exists", 345f2d953ecSKevin Wolf device_name); 346f2d953ecSKevin Wolf return NULL; 347f2d953ecSKevin Wolf } 348f2d953ecSKevin Wolf if (bdrv_find_node(device_name)) { 349f2d953ecSKevin Wolf error_setg(errp, "Device with node-name '%s' already exists", 350f2d953ecSKevin Wolf device_name); 351f2d953ecSKevin Wolf return NULL; 352f2d953ecSKevin Wolf } 353f2d953ecSKevin Wolf 3547267c094SAnthony Liguori bs = g_malloc0(sizeof(BlockDriverState)); 355e4654d2dSFam Zheng QLIST_INIT(&bs->dirty_bitmaps); 356b338082bSbellard pstrcpy(bs->device_name, sizeof(bs->device_name), device_name); 357ea2384d3Sbellard if (device_name[0] != '\0') { 358dc364f4cSBenoît Canet QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list); 359ea2384d3Sbellard } 360fbe40ff7SFam Zheng for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { 361fbe40ff7SFam Zheng QLIST_INIT(&bs->op_blockers[i]); 362fbe40ff7SFam Zheng } 36328a7282aSLuiz Capitulino bdrv_iostatus_disable(bs); 364d7d512f6SPaolo Bonzini notifier_list_init(&bs->close_notifiers); 365d616b224SStefan Hajnoczi notifier_with_return_list_init(&bs->before_write_notifiers); 366cc0681c4SBenoît Canet qemu_co_queue_init(&bs->throttled_reqs[0]); 367cc0681c4SBenoît Canet qemu_co_queue_init(&bs->throttled_reqs[1]); 3689fcb0251SFam Zheng bs->refcnt = 1; 369dcd04228SStefan Hajnoczi bs->aio_context = qemu_get_aio_context(); 370d7d512f6SPaolo Bonzini 371b338082bSbellard return bs; 372b338082bSbellard } 373b338082bSbellard 374d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify) 375d7d512f6SPaolo Bonzini { 376d7d512f6SPaolo Bonzini notifier_list_add(&bs->close_notifiers, notify); 377d7d512f6SPaolo Bonzini } 378d7d512f6SPaolo Bonzini 379ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name) 380ea2384d3Sbellard { 381ea2384d3Sbellard BlockDriver *drv1; 3828a22f02aSStefan Hajnoczi QLIST_FOREACH(drv1, &bdrv_drivers, list) { 3838a22f02aSStefan Hajnoczi if (!strcmp(drv1->format_name, format_name)) { 384ea2384d3Sbellard return drv1; 385ea2384d3Sbellard } 3868a22f02aSStefan Hajnoczi } 387ea2384d3Sbellard return NULL; 388ea2384d3Sbellard } 389ea2384d3Sbellard 390b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only) 391eb852011SMarkus Armbruster { 392b64ec4e4SFam Zheng static const char *whitelist_rw[] = { 393b64ec4e4SFam Zheng CONFIG_BDRV_RW_WHITELIST 394b64ec4e4SFam Zheng }; 395b64ec4e4SFam Zheng static const char *whitelist_ro[] = { 396b64ec4e4SFam Zheng CONFIG_BDRV_RO_WHITELIST 397eb852011SMarkus Armbruster }; 398eb852011SMarkus Armbruster const char **p; 399eb852011SMarkus Armbruster 400b64ec4e4SFam Zheng if (!whitelist_rw[0] && !whitelist_ro[0]) { 401eb852011SMarkus Armbruster return 1; /* no whitelist, anything goes */ 402b64ec4e4SFam Zheng } 403eb852011SMarkus Armbruster 404b64ec4e4SFam Zheng for (p = whitelist_rw; *p; p++) { 405eb852011SMarkus Armbruster if (!strcmp(drv->format_name, *p)) { 406eb852011SMarkus Armbruster return 1; 407eb852011SMarkus Armbruster } 408eb852011SMarkus Armbruster } 409b64ec4e4SFam Zheng if (read_only) { 410b64ec4e4SFam Zheng for (p = whitelist_ro; *p; p++) { 411b64ec4e4SFam Zheng if (!strcmp(drv->format_name, *p)) { 412b64ec4e4SFam Zheng return 1; 413b64ec4e4SFam Zheng } 414b64ec4e4SFam Zheng } 415b64ec4e4SFam Zheng } 416eb852011SMarkus Armbruster return 0; 417eb852011SMarkus Armbruster } 418eb852011SMarkus Armbruster 419b64ec4e4SFam Zheng BlockDriver *bdrv_find_whitelisted_format(const char *format_name, 420b64ec4e4SFam Zheng bool read_only) 421eb852011SMarkus Armbruster { 422eb852011SMarkus Armbruster BlockDriver *drv = bdrv_find_format(format_name); 423b64ec4e4SFam Zheng return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL; 424eb852011SMarkus Armbruster } 425eb852011SMarkus Armbruster 4265b7e1542SZhi Yong Wu typedef struct CreateCo { 4275b7e1542SZhi Yong Wu BlockDriver *drv; 4285b7e1542SZhi Yong Wu char *filename; 42983d0521aSChunyan Liu QemuOpts *opts; 4305b7e1542SZhi Yong Wu int ret; 431cc84d90fSMax Reitz Error *err; 4325b7e1542SZhi Yong Wu } CreateCo; 4335b7e1542SZhi Yong Wu 4345b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque) 4355b7e1542SZhi Yong Wu { 436cc84d90fSMax Reitz Error *local_err = NULL; 437cc84d90fSMax Reitz int ret; 438cc84d90fSMax Reitz 4395b7e1542SZhi Yong Wu CreateCo *cco = opaque; 4405b7e1542SZhi Yong Wu assert(cco->drv); 4415b7e1542SZhi Yong Wu 442c282e1fdSChunyan Liu ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err); 44384d18f06SMarkus Armbruster if (local_err) { 444cc84d90fSMax Reitz error_propagate(&cco->err, local_err); 445cc84d90fSMax Reitz } 446cc84d90fSMax Reitz cco->ret = ret; 4475b7e1542SZhi Yong Wu } 4485b7e1542SZhi Yong Wu 4490e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename, 45083d0521aSChunyan Liu QemuOpts *opts, Error **errp) 451ea2384d3Sbellard { 4525b7e1542SZhi Yong Wu int ret; 4530e7e1989SKevin Wolf 4545b7e1542SZhi Yong Wu Coroutine *co; 4555b7e1542SZhi Yong Wu CreateCo cco = { 4565b7e1542SZhi Yong Wu .drv = drv, 4575b7e1542SZhi Yong Wu .filename = g_strdup(filename), 45883d0521aSChunyan Liu .opts = opts, 4595b7e1542SZhi Yong Wu .ret = NOT_DONE, 460cc84d90fSMax Reitz .err = NULL, 4615b7e1542SZhi Yong Wu }; 4625b7e1542SZhi Yong Wu 463c282e1fdSChunyan Liu if (!drv->bdrv_create) { 464cc84d90fSMax Reitz error_setg(errp, "Driver '%s' does not support image creation", drv->format_name); 46580168bffSLuiz Capitulino ret = -ENOTSUP; 46680168bffSLuiz Capitulino goto out; 4675b7e1542SZhi Yong Wu } 4685b7e1542SZhi Yong Wu 4695b7e1542SZhi Yong Wu if (qemu_in_coroutine()) { 4705b7e1542SZhi Yong Wu /* Fast-path if already in coroutine context */ 4715b7e1542SZhi Yong Wu bdrv_create_co_entry(&cco); 4725b7e1542SZhi Yong Wu } else { 4735b7e1542SZhi Yong Wu co = qemu_coroutine_create(bdrv_create_co_entry); 4745b7e1542SZhi Yong Wu qemu_coroutine_enter(co, &cco); 4755b7e1542SZhi Yong Wu while (cco.ret == NOT_DONE) { 476b47ec2c4SPaolo Bonzini aio_poll(qemu_get_aio_context(), true); 4775b7e1542SZhi Yong Wu } 4785b7e1542SZhi Yong Wu } 4795b7e1542SZhi Yong Wu 4805b7e1542SZhi Yong Wu ret = cco.ret; 481cc84d90fSMax Reitz if (ret < 0) { 48284d18f06SMarkus Armbruster if (cco.err) { 483cc84d90fSMax Reitz error_propagate(errp, cco.err); 484cc84d90fSMax Reitz } else { 485cc84d90fSMax Reitz error_setg_errno(errp, -ret, "Could not create image"); 486cc84d90fSMax Reitz } 487cc84d90fSMax Reitz } 4885b7e1542SZhi Yong Wu 48980168bffSLuiz Capitulino out: 49080168bffSLuiz Capitulino g_free(cco.filename); 4915b7e1542SZhi Yong Wu return ret; 492ea2384d3Sbellard } 493ea2384d3Sbellard 494c282e1fdSChunyan Liu int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp) 49584a12e66SChristoph Hellwig { 49684a12e66SChristoph Hellwig BlockDriver *drv; 497cc84d90fSMax Reitz Error *local_err = NULL; 498cc84d90fSMax Reitz int ret; 49984a12e66SChristoph Hellwig 50098289620SKevin Wolf drv = bdrv_find_protocol(filename, true); 50184a12e66SChristoph Hellwig if (drv == NULL) { 502cc84d90fSMax Reitz error_setg(errp, "Could not find protocol for file '%s'", filename); 50316905d71SStefan Hajnoczi return -ENOENT; 50484a12e66SChristoph Hellwig } 50584a12e66SChristoph Hellwig 506c282e1fdSChunyan Liu ret = bdrv_create(drv, filename, opts, &local_err); 50784d18f06SMarkus Armbruster if (local_err) { 508cc84d90fSMax Reitz error_propagate(errp, local_err); 509cc84d90fSMax Reitz } 510cc84d90fSMax Reitz return ret; 51184a12e66SChristoph Hellwig } 51284a12e66SChristoph Hellwig 5133baca891SKevin Wolf void bdrv_refresh_limits(BlockDriverState *bs, Error **errp) 514d34682cdSKevin Wolf { 515d34682cdSKevin Wolf BlockDriver *drv = bs->drv; 5163baca891SKevin Wolf Error *local_err = NULL; 517d34682cdSKevin Wolf 518d34682cdSKevin Wolf memset(&bs->bl, 0, sizeof(bs->bl)); 519d34682cdSKevin Wolf 520466ad822SKevin Wolf if (!drv) { 5213baca891SKevin Wolf return; 522466ad822SKevin Wolf } 523466ad822SKevin Wolf 524466ad822SKevin Wolf /* Take some limits from the children as a default */ 525466ad822SKevin Wolf if (bs->file) { 5263baca891SKevin Wolf bdrv_refresh_limits(bs->file, &local_err); 5273baca891SKevin Wolf if (local_err) { 5283baca891SKevin Wolf error_propagate(errp, local_err); 5293baca891SKevin Wolf return; 5303baca891SKevin Wolf } 531466ad822SKevin Wolf bs->bl.opt_transfer_length = bs->file->bl.opt_transfer_length; 532339064d5SKevin Wolf bs->bl.opt_mem_alignment = bs->file->bl.opt_mem_alignment; 533339064d5SKevin Wolf } else { 534339064d5SKevin Wolf bs->bl.opt_mem_alignment = 512; 535466ad822SKevin Wolf } 536466ad822SKevin Wolf 537466ad822SKevin Wolf if (bs->backing_hd) { 5383baca891SKevin Wolf bdrv_refresh_limits(bs->backing_hd, &local_err); 5393baca891SKevin Wolf if (local_err) { 5403baca891SKevin Wolf error_propagate(errp, local_err); 5413baca891SKevin Wolf return; 5423baca891SKevin Wolf } 543466ad822SKevin Wolf bs->bl.opt_transfer_length = 544466ad822SKevin Wolf MAX(bs->bl.opt_transfer_length, 545466ad822SKevin Wolf bs->backing_hd->bl.opt_transfer_length); 546339064d5SKevin Wolf bs->bl.opt_mem_alignment = 547339064d5SKevin Wolf MAX(bs->bl.opt_mem_alignment, 548339064d5SKevin Wolf bs->backing_hd->bl.opt_mem_alignment); 549466ad822SKevin Wolf } 550466ad822SKevin Wolf 551466ad822SKevin Wolf /* Then let the driver override it */ 552466ad822SKevin Wolf if (drv->bdrv_refresh_limits) { 5533baca891SKevin Wolf drv->bdrv_refresh_limits(bs, errp); 554d34682cdSKevin Wolf } 555d34682cdSKevin Wolf } 556d34682cdSKevin Wolf 557eba25057SJim Meyering /* 558eba25057SJim Meyering * Create a uniquely-named empty temporary file. 559eba25057SJim Meyering * Return 0 upon success, otherwise a negative errno value. 560eba25057SJim Meyering */ 561eba25057SJim Meyering int get_tmp_filename(char *filename, int size) 562eba25057SJim Meyering { 563d5249393Sbellard #ifdef _WIN32 5643b9f94e1Sbellard char temp_dir[MAX_PATH]; 565eba25057SJim Meyering /* GetTempFileName requires that its output buffer (4th param) 566eba25057SJim Meyering have length MAX_PATH or greater. */ 567eba25057SJim Meyering assert(size >= MAX_PATH); 568eba25057SJim Meyering return (GetTempPath(MAX_PATH, temp_dir) 569eba25057SJim Meyering && GetTempFileName(temp_dir, "qem", 0, filename) 570eba25057SJim Meyering ? 0 : -GetLastError()); 571d5249393Sbellard #else 572ea2384d3Sbellard int fd; 5737ccfb2ebSblueswir1 const char *tmpdir; 5740badc1eeSaurel32 tmpdir = getenv("TMPDIR"); 57569bef793SAmit Shah if (!tmpdir) { 57669bef793SAmit Shah tmpdir = "/var/tmp"; 57769bef793SAmit Shah } 578eba25057SJim Meyering if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) { 579eba25057SJim Meyering return -EOVERFLOW; 580ea2384d3Sbellard } 581eba25057SJim Meyering fd = mkstemp(filename); 582fe235a06SDunrong Huang if (fd < 0) { 583fe235a06SDunrong Huang return -errno; 584fe235a06SDunrong Huang } 585fe235a06SDunrong Huang if (close(fd) != 0) { 586fe235a06SDunrong Huang unlink(filename); 587eba25057SJim Meyering return -errno; 588eba25057SJim Meyering } 589eba25057SJim Meyering return 0; 590d5249393Sbellard #endif 591eba25057SJim Meyering } 592ea2384d3Sbellard 593f3a5d3f8SChristoph Hellwig /* 594f3a5d3f8SChristoph Hellwig * Detect host devices. By convention, /dev/cdrom[N] is always 595f3a5d3f8SChristoph Hellwig * recognized as a host CDROM. 596f3a5d3f8SChristoph Hellwig */ 597f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename) 598f3a5d3f8SChristoph Hellwig { 599508c7cb3SChristoph Hellwig int score_max = 0, score; 600508c7cb3SChristoph Hellwig BlockDriver *drv = NULL, *d; 601f3a5d3f8SChristoph Hellwig 6028a22f02aSStefan Hajnoczi QLIST_FOREACH(d, &bdrv_drivers, list) { 603508c7cb3SChristoph Hellwig if (d->bdrv_probe_device) { 604508c7cb3SChristoph Hellwig score = d->bdrv_probe_device(filename); 605508c7cb3SChristoph Hellwig if (score > score_max) { 606508c7cb3SChristoph Hellwig score_max = score; 607508c7cb3SChristoph Hellwig drv = d; 608f3a5d3f8SChristoph Hellwig } 609508c7cb3SChristoph Hellwig } 610f3a5d3f8SChristoph Hellwig } 611f3a5d3f8SChristoph Hellwig 612508c7cb3SChristoph Hellwig return drv; 613f3a5d3f8SChristoph Hellwig } 614f3a5d3f8SChristoph Hellwig 61598289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename, 61698289620SKevin Wolf bool allow_protocol_prefix) 61784a12e66SChristoph Hellwig { 61884a12e66SChristoph Hellwig BlockDriver *drv1; 61984a12e66SChristoph Hellwig char protocol[128]; 62084a12e66SChristoph Hellwig int len; 62184a12e66SChristoph Hellwig const char *p; 62284a12e66SChristoph Hellwig 62366f82ceeSKevin Wolf /* TODO Drivers without bdrv_file_open must be specified explicitly */ 62466f82ceeSKevin Wolf 62539508e7aSChristoph Hellwig /* 62639508e7aSChristoph Hellwig * XXX(hch): we really should not let host device detection 62739508e7aSChristoph Hellwig * override an explicit protocol specification, but moving this 62839508e7aSChristoph Hellwig * later breaks access to device names with colons in them. 62939508e7aSChristoph Hellwig * Thanks to the brain-dead persistent naming schemes on udev- 63039508e7aSChristoph Hellwig * based Linux systems those actually are quite common. 63139508e7aSChristoph Hellwig */ 63284a12e66SChristoph Hellwig drv1 = find_hdev_driver(filename); 63339508e7aSChristoph Hellwig if (drv1) { 63484a12e66SChristoph Hellwig return drv1; 63584a12e66SChristoph Hellwig } 63639508e7aSChristoph Hellwig 63798289620SKevin Wolf if (!path_has_protocol(filename) || !allow_protocol_prefix) { 63839508e7aSChristoph Hellwig return bdrv_find_format("file"); 63939508e7aSChristoph Hellwig } 64098289620SKevin Wolf 6419e0b22f4SStefan Hajnoczi p = strchr(filename, ':'); 6429e0b22f4SStefan Hajnoczi assert(p != NULL); 64384a12e66SChristoph Hellwig len = p - filename; 64484a12e66SChristoph Hellwig if (len > sizeof(protocol) - 1) 64584a12e66SChristoph Hellwig len = sizeof(protocol) - 1; 64684a12e66SChristoph Hellwig memcpy(protocol, filename, len); 64784a12e66SChristoph Hellwig protocol[len] = '\0'; 64884a12e66SChristoph Hellwig QLIST_FOREACH(drv1, &bdrv_drivers, list) { 64984a12e66SChristoph Hellwig if (drv1->protocol_name && 65084a12e66SChristoph Hellwig !strcmp(drv1->protocol_name, protocol)) { 65184a12e66SChristoph Hellwig return drv1; 65284a12e66SChristoph Hellwig } 65384a12e66SChristoph Hellwig } 65484a12e66SChristoph Hellwig return NULL; 65584a12e66SChristoph Hellwig } 65684a12e66SChristoph Hellwig 657f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename, 65834b5d2c6SMax Reitz BlockDriver **pdrv, Error **errp) 659ea2384d3Sbellard { 660f500a6d3SKevin Wolf int score, score_max; 661ea2384d3Sbellard BlockDriver *drv1, *drv; 66283f64091Sbellard uint8_t buf[2048]; 663f500a6d3SKevin Wolf int ret = 0; 664f8ea0b00SNicholas Bellinger 66508a00559SKevin Wolf /* Return the raw BlockDriver * to scsi-generic devices or empty drives */ 6668e895599SPaolo Bonzini if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) { 667c98ac35dSStefan Weil drv = bdrv_find_format("raw"); 668c98ac35dSStefan Weil if (!drv) { 66934b5d2c6SMax Reitz error_setg(errp, "Could not find raw image format"); 670c98ac35dSStefan Weil ret = -ENOENT; 671c98ac35dSStefan Weil } 672c98ac35dSStefan Weil *pdrv = drv; 673c98ac35dSStefan Weil return ret; 6741a396859SNicholas A. Bellinger } 675f8ea0b00SNicholas Bellinger 67683f64091Sbellard ret = bdrv_pread(bs, 0, buf, sizeof(buf)); 677ea2384d3Sbellard if (ret < 0) { 67834b5d2c6SMax Reitz error_setg_errno(errp, -ret, "Could not read image for determining its " 67934b5d2c6SMax Reitz "format"); 680c98ac35dSStefan Weil *pdrv = NULL; 681c98ac35dSStefan Weil return ret; 682ea2384d3Sbellard } 683ea2384d3Sbellard 684ea2384d3Sbellard score_max = 0; 68584a12e66SChristoph Hellwig drv = NULL; 6868a22f02aSStefan Hajnoczi QLIST_FOREACH(drv1, &bdrv_drivers, list) { 68783f64091Sbellard if (drv1->bdrv_probe) { 688ea2384d3Sbellard score = drv1->bdrv_probe(buf, ret, filename); 689ea2384d3Sbellard if (score > score_max) { 690ea2384d3Sbellard score_max = score; 691ea2384d3Sbellard drv = drv1; 692ea2384d3Sbellard } 693ea2384d3Sbellard } 69483f64091Sbellard } 695c98ac35dSStefan Weil if (!drv) { 69634b5d2c6SMax Reitz error_setg(errp, "Could not determine image format: No compatible " 69734b5d2c6SMax Reitz "driver found"); 698c98ac35dSStefan Weil ret = -ENOENT; 699c98ac35dSStefan Weil } 700c98ac35dSStefan Weil *pdrv = drv; 701c98ac35dSStefan Weil return ret; 702ea2384d3Sbellard } 703ea2384d3Sbellard 70451762288SStefan Hajnoczi /** 70551762288SStefan Hajnoczi * Set the current 'total_sectors' value 70665a9bb25SMarkus Armbruster * Return 0 on success, -errno on error. 70751762288SStefan Hajnoczi */ 70851762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint) 70951762288SStefan Hajnoczi { 71051762288SStefan Hajnoczi BlockDriver *drv = bs->drv; 71151762288SStefan Hajnoczi 712396759adSNicholas Bellinger /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */ 713396759adSNicholas Bellinger if (bs->sg) 714396759adSNicholas Bellinger return 0; 715396759adSNicholas Bellinger 71651762288SStefan Hajnoczi /* query actual device if possible, otherwise just trust the hint */ 71751762288SStefan Hajnoczi if (drv->bdrv_getlength) { 71851762288SStefan Hajnoczi int64_t length = drv->bdrv_getlength(bs); 71951762288SStefan Hajnoczi if (length < 0) { 72051762288SStefan Hajnoczi return length; 72151762288SStefan Hajnoczi } 7227e382003SFam Zheng hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE); 72351762288SStefan Hajnoczi } 72451762288SStefan Hajnoczi 72551762288SStefan Hajnoczi bs->total_sectors = hint; 72651762288SStefan Hajnoczi return 0; 72751762288SStefan Hajnoczi } 72851762288SStefan Hajnoczi 729c3993cdcSStefan Hajnoczi /** 7309e8f1835SPaolo Bonzini * Set open flags for a given discard mode 7319e8f1835SPaolo Bonzini * 7329e8f1835SPaolo Bonzini * Return 0 on success, -1 if the discard mode was invalid. 7339e8f1835SPaolo Bonzini */ 7349e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags) 7359e8f1835SPaolo Bonzini { 7369e8f1835SPaolo Bonzini *flags &= ~BDRV_O_UNMAP; 7379e8f1835SPaolo Bonzini 7389e8f1835SPaolo Bonzini if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) { 7399e8f1835SPaolo Bonzini /* do nothing */ 7409e8f1835SPaolo Bonzini } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) { 7419e8f1835SPaolo Bonzini *flags |= BDRV_O_UNMAP; 7429e8f1835SPaolo Bonzini } else { 7439e8f1835SPaolo Bonzini return -1; 7449e8f1835SPaolo Bonzini } 7459e8f1835SPaolo Bonzini 7469e8f1835SPaolo Bonzini return 0; 7479e8f1835SPaolo Bonzini } 7489e8f1835SPaolo Bonzini 7499e8f1835SPaolo Bonzini /** 750c3993cdcSStefan Hajnoczi * Set open flags for a given cache mode 751c3993cdcSStefan Hajnoczi * 752c3993cdcSStefan Hajnoczi * Return 0 on success, -1 if the cache mode was invalid. 753c3993cdcSStefan Hajnoczi */ 754c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags) 755c3993cdcSStefan Hajnoczi { 756c3993cdcSStefan Hajnoczi *flags &= ~BDRV_O_CACHE_MASK; 757c3993cdcSStefan Hajnoczi 758c3993cdcSStefan Hajnoczi if (!strcmp(mode, "off") || !strcmp(mode, "none")) { 759c3993cdcSStefan Hajnoczi *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB; 76092196b2fSStefan Hajnoczi } else if (!strcmp(mode, "directsync")) { 76192196b2fSStefan Hajnoczi *flags |= BDRV_O_NOCACHE; 762c3993cdcSStefan Hajnoczi } else if (!strcmp(mode, "writeback")) { 763c3993cdcSStefan Hajnoczi *flags |= BDRV_O_CACHE_WB; 764c3993cdcSStefan Hajnoczi } else if (!strcmp(mode, "unsafe")) { 765c3993cdcSStefan Hajnoczi *flags |= BDRV_O_CACHE_WB; 766c3993cdcSStefan Hajnoczi *flags |= BDRV_O_NO_FLUSH; 767c3993cdcSStefan Hajnoczi } else if (!strcmp(mode, "writethrough")) { 768c3993cdcSStefan Hajnoczi /* this is the default */ 769c3993cdcSStefan Hajnoczi } else { 770c3993cdcSStefan Hajnoczi return -1; 771c3993cdcSStefan Hajnoczi } 772c3993cdcSStefan Hajnoczi 773c3993cdcSStefan Hajnoczi return 0; 774c3993cdcSStefan Hajnoczi } 775c3993cdcSStefan Hajnoczi 77653fec9d3SStefan Hajnoczi /** 77753fec9d3SStefan Hajnoczi * The copy-on-read flag is actually a reference count so multiple users may 77853fec9d3SStefan Hajnoczi * use the feature without worrying about clobbering its previous state. 77953fec9d3SStefan Hajnoczi * Copy-on-read stays enabled until all users have called to disable it. 78053fec9d3SStefan Hajnoczi */ 78153fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs) 78253fec9d3SStefan Hajnoczi { 78353fec9d3SStefan Hajnoczi bs->copy_on_read++; 78453fec9d3SStefan Hajnoczi } 78553fec9d3SStefan Hajnoczi 78653fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs) 78753fec9d3SStefan Hajnoczi { 78853fec9d3SStefan Hajnoczi assert(bs->copy_on_read > 0); 78953fec9d3SStefan Hajnoczi bs->copy_on_read--; 79053fec9d3SStefan Hajnoczi } 79153fec9d3SStefan Hajnoczi 7920b50cc88SKevin Wolf /* 793b1e6fc08SKevin Wolf * Returns the flags that a temporary snapshot should get, based on the 794b1e6fc08SKevin Wolf * originally requested flags (the originally requested image will have flags 795b1e6fc08SKevin Wolf * like a backing file) 796b1e6fc08SKevin Wolf */ 797b1e6fc08SKevin Wolf static int bdrv_temp_snapshot_flags(int flags) 798b1e6fc08SKevin Wolf { 799b1e6fc08SKevin Wolf return (flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY; 800b1e6fc08SKevin Wolf } 801b1e6fc08SKevin Wolf 802b1e6fc08SKevin Wolf /* 8030b50cc88SKevin Wolf * Returns the flags that bs->file should get, based on the given flags for 8040b50cc88SKevin Wolf * the parent BDS 8050b50cc88SKevin Wolf */ 8060b50cc88SKevin Wolf static int bdrv_inherited_flags(int flags) 8070b50cc88SKevin Wolf { 8080b50cc88SKevin Wolf /* Enable protocol handling, disable format probing for bs->file */ 8090b50cc88SKevin Wolf flags |= BDRV_O_PROTOCOL; 8100b50cc88SKevin Wolf 8110b50cc88SKevin Wolf /* Our block drivers take care to send flushes and respect unmap policy, 8120b50cc88SKevin Wolf * so we can enable both unconditionally on lower layers. */ 8130b50cc88SKevin Wolf flags |= BDRV_O_CACHE_WB | BDRV_O_UNMAP; 8140b50cc88SKevin Wolf 8150b50cc88SKevin Wolf /* Clear flags that only apply to the top layer */ 8165669b44dSKevin Wolf flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ); 8170b50cc88SKevin Wolf 8180b50cc88SKevin Wolf return flags; 8190b50cc88SKevin Wolf } 8200b50cc88SKevin Wolf 821317fc44eSKevin Wolf /* 822317fc44eSKevin Wolf * Returns the flags that bs->backing_hd should get, based on the given flags 823317fc44eSKevin Wolf * for the parent BDS 824317fc44eSKevin Wolf */ 825317fc44eSKevin Wolf static int bdrv_backing_flags(int flags) 826317fc44eSKevin Wolf { 827317fc44eSKevin Wolf /* backing files always opened read-only */ 828317fc44eSKevin Wolf flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ); 829317fc44eSKevin Wolf 830317fc44eSKevin Wolf /* snapshot=on is handled on the top layer */ 8318bfea15dSKevin Wolf flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY); 832317fc44eSKevin Wolf 833317fc44eSKevin Wolf return flags; 834317fc44eSKevin Wolf } 835317fc44eSKevin Wolf 8367b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags) 8377b272452SKevin Wolf { 8387b272452SKevin Wolf int open_flags = flags | BDRV_O_CACHE_WB; 8397b272452SKevin Wolf 8407b272452SKevin Wolf /* 8417b272452SKevin Wolf * Clear flags that are internal to the block layer before opening the 8427b272452SKevin Wolf * image. 8437b272452SKevin Wolf */ 84420cca275SKevin Wolf open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL); 8457b272452SKevin Wolf 8467b272452SKevin Wolf /* 8477b272452SKevin Wolf * Snapshots should be writable. 8487b272452SKevin Wolf */ 8498bfea15dSKevin Wolf if (flags & BDRV_O_TEMPORARY) { 8507b272452SKevin Wolf open_flags |= BDRV_O_RDWR; 8517b272452SKevin Wolf } 8527b272452SKevin Wolf 8537b272452SKevin Wolf return open_flags; 8547b272452SKevin Wolf } 8557b272452SKevin Wolf 856636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs, 8576913c0c2SBenoît Canet const char *node_name, 8586913c0c2SBenoît Canet Error **errp) 8596913c0c2SBenoît Canet { 8606913c0c2SBenoît Canet if (!node_name) { 861636ea370SKevin Wolf return; 8626913c0c2SBenoît Canet } 8636913c0c2SBenoît Canet 8646913c0c2SBenoît Canet /* empty string node name is invalid */ 8656913c0c2SBenoît Canet if (node_name[0] == '\0') { 8666913c0c2SBenoît Canet error_setg(errp, "Empty node name"); 867636ea370SKevin Wolf return; 8686913c0c2SBenoît Canet } 8696913c0c2SBenoît Canet 8700c5e94eeSBenoît Canet /* takes care of avoiding namespaces collisions */ 8710c5e94eeSBenoît Canet if (bdrv_find(node_name)) { 8720c5e94eeSBenoît Canet error_setg(errp, "node-name=%s is conflicting with a device id", 8730c5e94eeSBenoît Canet node_name); 874636ea370SKevin Wolf return; 8750c5e94eeSBenoît Canet } 8760c5e94eeSBenoît Canet 8776913c0c2SBenoît Canet /* takes care of avoiding duplicates node names */ 8786913c0c2SBenoît Canet if (bdrv_find_node(node_name)) { 8796913c0c2SBenoît Canet error_setg(errp, "Duplicate node name"); 880636ea370SKevin Wolf return; 8816913c0c2SBenoît Canet } 8826913c0c2SBenoît Canet 8836913c0c2SBenoît Canet /* copy node name into the bs and insert it into the graph list */ 8846913c0c2SBenoît Canet pstrcpy(bs->node_name, sizeof(bs->node_name), node_name); 8856913c0c2SBenoît Canet QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list); 8866913c0c2SBenoît Canet } 8876913c0c2SBenoît Canet 888b6ce07aaSKevin Wolf /* 88957915332SKevin Wolf * Common part for opening disk images and files 890b6ad491aSKevin Wolf * 891b6ad491aSKevin Wolf * Removes all processed options from *options. 89257915332SKevin Wolf */ 893f500a6d3SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file, 89434b5d2c6SMax Reitz QDict *options, int flags, BlockDriver *drv, Error **errp) 89557915332SKevin Wolf { 89657915332SKevin Wolf int ret, open_flags; 897035fccdfSKevin Wolf const char *filename; 8986913c0c2SBenoît Canet const char *node_name = NULL; 89934b5d2c6SMax Reitz Error *local_err = NULL; 90057915332SKevin Wolf 90157915332SKevin Wolf assert(drv != NULL); 9026405875cSPaolo Bonzini assert(bs->file == NULL); 903707ff828SKevin Wolf assert(options != NULL && bs->options != options); 90457915332SKevin Wolf 90545673671SKevin Wolf if (file != NULL) { 90645673671SKevin Wolf filename = file->filename; 90745673671SKevin Wolf } else { 90845673671SKevin Wolf filename = qdict_get_try_str(options, "filename"); 90945673671SKevin Wolf } 91045673671SKevin Wolf 911765003dbSKevin Wolf if (drv->bdrv_needs_filename && !filename) { 912765003dbSKevin Wolf error_setg(errp, "The '%s' block driver requires a file name", 913765003dbSKevin Wolf drv->format_name); 914765003dbSKevin Wolf return -EINVAL; 915765003dbSKevin Wolf } 916765003dbSKevin Wolf 91745673671SKevin Wolf trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name); 91828dcee10SStefan Hajnoczi 9196913c0c2SBenoît Canet node_name = qdict_get_try_str(options, "node-name"); 920636ea370SKevin Wolf bdrv_assign_node_name(bs, node_name, &local_err); 9210fb6395cSMarkus Armbruster if (local_err) { 922636ea370SKevin Wolf error_propagate(errp, local_err); 923636ea370SKevin Wolf return -EINVAL; 9246913c0c2SBenoît Canet } 9256913c0c2SBenoît Canet qdict_del(options, "node-name"); 9266913c0c2SBenoît Canet 9275d186eb0SKevin Wolf /* bdrv_open() with directly using a protocol as drv. This layer is already 9285d186eb0SKevin Wolf * opened, so assign it to bs (while file becomes a closed BlockDriverState) 9295d186eb0SKevin Wolf * and return immediately. */ 9305d186eb0SKevin Wolf if (file != NULL && drv->bdrv_file_open) { 9315d186eb0SKevin Wolf bdrv_swap(file, bs); 9325d186eb0SKevin Wolf return 0; 9335d186eb0SKevin Wolf } 9345d186eb0SKevin Wolf 93557915332SKevin Wolf bs->open_flags = flags; 9361b7fd729SPaolo Bonzini bs->guest_block_size = 512; 937c25f53b0SPaolo Bonzini bs->request_alignment = 512; 9380d51b4deSAsias He bs->zero_beyond_eof = true; 939b64ec4e4SFam Zheng open_flags = bdrv_open_flags(bs, flags); 940b64ec4e4SFam Zheng bs->read_only = !(open_flags & BDRV_O_RDWR); 94120cca275SKevin Wolf bs->growable = !!(flags & BDRV_O_PROTOCOL); 942b64ec4e4SFam Zheng 943b64ec4e4SFam Zheng if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) { 9448f94a6e4SKevin Wolf error_setg(errp, 9458f94a6e4SKevin Wolf !bs->read_only && bdrv_is_whitelisted(drv, true) 9468f94a6e4SKevin Wolf ? "Driver '%s' can only be used for read-only devices" 9478f94a6e4SKevin Wolf : "Driver '%s' is not whitelisted", 9488f94a6e4SKevin Wolf drv->format_name); 949b64ec4e4SFam Zheng return -ENOTSUP; 950b64ec4e4SFam Zheng } 95157915332SKevin Wolf 95253fec9d3SStefan Hajnoczi assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */ 9530ebd24e0SKevin Wolf if (flags & BDRV_O_COPY_ON_READ) { 9540ebd24e0SKevin Wolf if (!bs->read_only) { 95553fec9d3SStefan Hajnoczi bdrv_enable_copy_on_read(bs); 9560ebd24e0SKevin Wolf } else { 9570ebd24e0SKevin Wolf error_setg(errp, "Can't use copy-on-read on read-only device"); 9580ebd24e0SKevin Wolf return -EINVAL; 9590ebd24e0SKevin Wolf } 96053fec9d3SStefan Hajnoczi } 96153fec9d3SStefan Hajnoczi 962c2ad1b0cSKevin Wolf if (filename != NULL) { 96357915332SKevin Wolf pstrcpy(bs->filename, sizeof(bs->filename), filename); 964c2ad1b0cSKevin Wolf } else { 965c2ad1b0cSKevin Wolf bs->filename[0] = '\0'; 966c2ad1b0cSKevin Wolf } 96757915332SKevin Wolf 96857915332SKevin Wolf bs->drv = drv; 9697267c094SAnthony Liguori bs->opaque = g_malloc0(drv->instance_size); 97057915332SKevin Wolf 97103f541bdSStefan Hajnoczi bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB); 972e7c63796SStefan Hajnoczi 97366f82ceeSKevin Wolf /* Open the image, either directly or using a protocol */ 97466f82ceeSKevin Wolf if (drv->bdrv_file_open) { 9755d186eb0SKevin Wolf assert(file == NULL); 976030be321SBenoît Canet assert(!drv->bdrv_needs_filename || filename != NULL); 97734b5d2c6SMax Reitz ret = drv->bdrv_file_open(bs, options, open_flags, &local_err); 978f500a6d3SKevin Wolf } else { 9792af5ef70SKevin Wolf if (file == NULL) { 98034b5d2c6SMax Reitz error_setg(errp, "Can't use '%s' as a block driver for the " 98134b5d2c6SMax Reitz "protocol level", drv->format_name); 9822af5ef70SKevin Wolf ret = -EINVAL; 9832af5ef70SKevin Wolf goto free_and_fail; 9842af5ef70SKevin Wolf } 985f500a6d3SKevin Wolf bs->file = file; 98634b5d2c6SMax Reitz ret = drv->bdrv_open(bs, options, open_flags, &local_err); 98766f82ceeSKevin Wolf } 98866f82ceeSKevin Wolf 98957915332SKevin Wolf if (ret < 0) { 99084d18f06SMarkus Armbruster if (local_err) { 99134b5d2c6SMax Reitz error_propagate(errp, local_err); 9922fa9aa59SDunrong Huang } else if (bs->filename[0]) { 9932fa9aa59SDunrong Huang error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename); 99434b5d2c6SMax Reitz } else { 99534b5d2c6SMax Reitz error_setg_errno(errp, -ret, "Could not open image"); 99634b5d2c6SMax Reitz } 99757915332SKevin Wolf goto free_and_fail; 99857915332SKevin Wolf } 99957915332SKevin Wolf 100051762288SStefan Hajnoczi ret = refresh_total_sectors(bs, bs->total_sectors); 100151762288SStefan Hajnoczi if (ret < 0) { 100234b5d2c6SMax Reitz error_setg_errno(errp, -ret, "Could not refresh total sector count"); 100351762288SStefan Hajnoczi goto free_and_fail; 100457915332SKevin Wolf } 100551762288SStefan Hajnoczi 10063baca891SKevin Wolf bdrv_refresh_limits(bs, &local_err); 10073baca891SKevin Wolf if (local_err) { 10083baca891SKevin Wolf error_propagate(errp, local_err); 10093baca891SKevin Wolf ret = -EINVAL; 10103baca891SKevin Wolf goto free_and_fail; 10113baca891SKevin Wolf } 10123baca891SKevin Wolf 1013c25f53b0SPaolo Bonzini assert(bdrv_opt_mem_align(bs) != 0); 101447ea2de2SKevin Wolf assert((bs->request_alignment != 0) || bs->sg); 101557915332SKevin Wolf return 0; 101657915332SKevin Wolf 101757915332SKevin Wolf free_and_fail: 101866f82ceeSKevin Wolf bs->file = NULL; 10197267c094SAnthony Liguori g_free(bs->opaque); 102057915332SKevin Wolf bs->opaque = NULL; 102157915332SKevin Wolf bs->drv = NULL; 102257915332SKevin Wolf return ret; 102357915332SKevin Wolf } 102457915332SKevin Wolf 10255e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp) 10265e5c4f63SKevin Wolf { 10275e5c4f63SKevin Wolf QObject *options_obj; 10285e5c4f63SKevin Wolf QDict *options; 10295e5c4f63SKevin Wolf int ret; 10305e5c4f63SKevin Wolf 10315e5c4f63SKevin Wolf ret = strstart(filename, "json:", &filename); 10325e5c4f63SKevin Wolf assert(ret); 10335e5c4f63SKevin Wolf 10345e5c4f63SKevin Wolf options_obj = qobject_from_json(filename); 10355e5c4f63SKevin Wolf if (!options_obj) { 10365e5c4f63SKevin Wolf error_setg(errp, "Could not parse the JSON options"); 10375e5c4f63SKevin Wolf return NULL; 10385e5c4f63SKevin Wolf } 10395e5c4f63SKevin Wolf 10405e5c4f63SKevin Wolf if (qobject_type(options_obj) != QTYPE_QDICT) { 10415e5c4f63SKevin Wolf qobject_decref(options_obj); 10425e5c4f63SKevin Wolf error_setg(errp, "Invalid JSON object given"); 10435e5c4f63SKevin Wolf return NULL; 10445e5c4f63SKevin Wolf } 10455e5c4f63SKevin Wolf 10465e5c4f63SKevin Wolf options = qobject_to_qdict(options_obj); 10475e5c4f63SKevin Wolf qdict_flatten(options); 10485e5c4f63SKevin Wolf 10495e5c4f63SKevin Wolf return options; 10505e5c4f63SKevin Wolf } 10515e5c4f63SKevin Wolf 105257915332SKevin Wolf /* 1053f54120ffSKevin Wolf * Fills in default options for opening images and converts the legacy 1054f54120ffSKevin Wolf * filename/flags pair to option QDict entries. 1055f54120ffSKevin Wolf */ 10565e5c4f63SKevin Wolf static int bdrv_fill_options(QDict **options, const char **pfilename, int flags, 105717b005f1SKevin Wolf BlockDriver *drv, Error **errp) 1058f54120ffSKevin Wolf { 10595e5c4f63SKevin Wolf const char *filename = *pfilename; 1060f54120ffSKevin Wolf const char *drvname; 1061462f5bcfSKevin Wolf bool protocol = flags & BDRV_O_PROTOCOL; 1062f54120ffSKevin Wolf bool parse_filename = false; 1063f54120ffSKevin Wolf Error *local_err = NULL; 1064f54120ffSKevin Wolf 10655e5c4f63SKevin Wolf /* Parse json: pseudo-protocol */ 10665e5c4f63SKevin Wolf if (filename && g_str_has_prefix(filename, "json:")) { 10675e5c4f63SKevin Wolf QDict *json_options = parse_json_filename(filename, &local_err); 10685e5c4f63SKevin Wolf if (local_err) { 10695e5c4f63SKevin Wolf error_propagate(errp, local_err); 10705e5c4f63SKevin Wolf return -EINVAL; 10715e5c4f63SKevin Wolf } 10725e5c4f63SKevin Wolf 10735e5c4f63SKevin Wolf /* Options given in the filename have lower priority than options 10745e5c4f63SKevin Wolf * specified directly */ 10755e5c4f63SKevin Wolf qdict_join(*options, json_options, false); 10765e5c4f63SKevin Wolf QDECREF(json_options); 10775e5c4f63SKevin Wolf *pfilename = filename = NULL; 10785e5c4f63SKevin Wolf } 10795e5c4f63SKevin Wolf 1080f54120ffSKevin Wolf /* Fetch the file name from the options QDict if necessary */ 108117b005f1SKevin Wolf if (protocol && filename) { 1082f54120ffSKevin Wolf if (!qdict_haskey(*options, "filename")) { 1083f54120ffSKevin Wolf qdict_put(*options, "filename", qstring_from_str(filename)); 1084f54120ffSKevin Wolf parse_filename = true; 1085f54120ffSKevin Wolf } else { 1086f54120ffSKevin Wolf error_setg(errp, "Can't specify 'file' and 'filename' options at " 1087f54120ffSKevin Wolf "the same time"); 1088f54120ffSKevin Wolf return -EINVAL; 1089f54120ffSKevin Wolf } 1090f54120ffSKevin Wolf } 1091f54120ffSKevin Wolf 1092f54120ffSKevin Wolf /* Find the right block driver */ 1093f54120ffSKevin Wolf filename = qdict_get_try_str(*options, "filename"); 1094f54120ffSKevin Wolf drvname = qdict_get_try_str(*options, "driver"); 1095f54120ffSKevin Wolf 109617b005f1SKevin Wolf if (drv) { 109717b005f1SKevin Wolf if (drvname) { 109817b005f1SKevin Wolf error_setg(errp, "Driver specified twice"); 109917b005f1SKevin Wolf return -EINVAL; 110017b005f1SKevin Wolf } 110117b005f1SKevin Wolf drvname = drv->format_name; 110217b005f1SKevin Wolf qdict_put(*options, "driver", qstring_from_str(drvname)); 110317b005f1SKevin Wolf } else { 110417b005f1SKevin Wolf if (!drvname && protocol) { 1105f54120ffSKevin Wolf if (filename) { 1106f54120ffSKevin Wolf drv = bdrv_find_protocol(filename, parse_filename); 1107f54120ffSKevin Wolf if (!drv) { 1108f54120ffSKevin Wolf error_setg(errp, "Unknown protocol"); 1109f54120ffSKevin Wolf return -EINVAL; 1110f54120ffSKevin Wolf } 1111f54120ffSKevin Wolf 1112f54120ffSKevin Wolf drvname = drv->format_name; 1113f54120ffSKevin Wolf qdict_put(*options, "driver", qstring_from_str(drvname)); 1114f54120ffSKevin Wolf } else { 1115f54120ffSKevin Wolf error_setg(errp, "Must specify either driver or file"); 1116f54120ffSKevin Wolf return -EINVAL; 1117f54120ffSKevin Wolf } 111817b005f1SKevin Wolf } else if (drvname) { 1119f54120ffSKevin Wolf drv = bdrv_find_format(drvname); 1120f54120ffSKevin Wolf if (!drv) { 1121f54120ffSKevin Wolf error_setg(errp, "Unknown driver '%s'", drvname); 1122f54120ffSKevin Wolf return -ENOENT; 1123f54120ffSKevin Wolf } 112417b005f1SKevin Wolf } 112517b005f1SKevin Wolf } 112617b005f1SKevin Wolf 112717b005f1SKevin Wolf assert(drv || !protocol); 1128f54120ffSKevin Wolf 1129f54120ffSKevin Wolf /* Driver-specific filename parsing */ 113017b005f1SKevin Wolf if (drv && drv->bdrv_parse_filename && parse_filename) { 1131f54120ffSKevin Wolf drv->bdrv_parse_filename(filename, *options, &local_err); 1132f54120ffSKevin Wolf if (local_err) { 1133f54120ffSKevin Wolf error_propagate(errp, local_err); 1134f54120ffSKevin Wolf return -EINVAL; 1135f54120ffSKevin Wolf } 1136f54120ffSKevin Wolf 1137f54120ffSKevin Wolf if (!drv->bdrv_needs_filename) { 1138f54120ffSKevin Wolf qdict_del(*options, "filename"); 1139f54120ffSKevin Wolf } 1140f54120ffSKevin Wolf } 1141f54120ffSKevin Wolf 1142f54120ffSKevin Wolf return 0; 1143f54120ffSKevin Wolf } 1144f54120ffSKevin Wolf 11458d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd) 11468d24cce1SFam Zheng { 11478d24cce1SFam Zheng 1148826b6ca0SFam Zheng if (bs->backing_hd) { 1149826b6ca0SFam Zheng assert(bs->backing_blocker); 1150826b6ca0SFam Zheng bdrv_op_unblock_all(bs->backing_hd, bs->backing_blocker); 1151826b6ca0SFam Zheng } else if (backing_hd) { 1152826b6ca0SFam Zheng error_setg(&bs->backing_blocker, 1153826b6ca0SFam Zheng "device is used as backing hd of '%s'", 1154826b6ca0SFam Zheng bs->device_name); 1155826b6ca0SFam Zheng } 1156826b6ca0SFam Zheng 11578d24cce1SFam Zheng bs->backing_hd = backing_hd; 11588d24cce1SFam Zheng if (!backing_hd) { 1159826b6ca0SFam Zheng error_free(bs->backing_blocker); 1160826b6ca0SFam Zheng bs->backing_blocker = NULL; 11618d24cce1SFam Zheng goto out; 11628d24cce1SFam Zheng } 11638d24cce1SFam Zheng bs->open_flags &= ~BDRV_O_NO_BACKING; 11648d24cce1SFam Zheng pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename); 11658d24cce1SFam Zheng pstrcpy(bs->backing_format, sizeof(bs->backing_format), 11668d24cce1SFam Zheng backing_hd->drv ? backing_hd->drv->format_name : ""); 1167826b6ca0SFam Zheng 1168826b6ca0SFam Zheng bdrv_op_block_all(bs->backing_hd, bs->backing_blocker); 1169826b6ca0SFam Zheng /* Otherwise we won't be able to commit due to check in bdrv_commit */ 1170826b6ca0SFam Zheng bdrv_op_unblock(bs->backing_hd, BLOCK_OP_TYPE_COMMIT, 1171826b6ca0SFam Zheng bs->backing_blocker); 11728d24cce1SFam Zheng out: 11733baca891SKevin Wolf bdrv_refresh_limits(bs, NULL); 11748d24cce1SFam Zheng } 11758d24cce1SFam Zheng 117631ca6d07SKevin Wolf /* 117731ca6d07SKevin Wolf * Opens the backing file for a BlockDriverState if not yet open 117831ca6d07SKevin Wolf * 117931ca6d07SKevin Wolf * options is a QDict of options to pass to the block drivers, or NULL for an 118031ca6d07SKevin Wolf * empty set of options. The reference to the QDict is transferred to this 118131ca6d07SKevin Wolf * function (even on failure), so if the caller intends to reuse the dictionary, 118231ca6d07SKevin Wolf * it needs to use QINCREF() before calling bdrv_file_open. 118331ca6d07SKevin Wolf */ 118434b5d2c6SMax Reitz int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp) 11859156df12SPaolo Bonzini { 11861ba4b6a5SBenoît Canet char *backing_filename = g_malloc0(PATH_MAX); 1187317fc44eSKevin Wolf int ret = 0; 11889156df12SPaolo Bonzini BlockDriver *back_drv = NULL; 11898d24cce1SFam Zheng BlockDriverState *backing_hd; 119034b5d2c6SMax Reitz Error *local_err = NULL; 11919156df12SPaolo Bonzini 11929156df12SPaolo Bonzini if (bs->backing_hd != NULL) { 119331ca6d07SKevin Wolf QDECREF(options); 11941ba4b6a5SBenoît Canet goto free_exit; 11959156df12SPaolo Bonzini } 11969156df12SPaolo Bonzini 119731ca6d07SKevin Wolf /* NULL means an empty set of options */ 119831ca6d07SKevin Wolf if (options == NULL) { 119931ca6d07SKevin Wolf options = qdict_new(); 120031ca6d07SKevin Wolf } 120131ca6d07SKevin Wolf 12029156df12SPaolo Bonzini bs->open_flags &= ~BDRV_O_NO_BACKING; 12031cb6f506SKevin Wolf if (qdict_haskey(options, "file.filename")) { 12041cb6f506SKevin Wolf backing_filename[0] = '\0'; 12051cb6f506SKevin Wolf } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) { 120631ca6d07SKevin Wolf QDECREF(options); 12071ba4b6a5SBenoît Canet goto free_exit; 1208dbecebddSFam Zheng } else { 12091ba4b6a5SBenoît Canet bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX); 12109156df12SPaolo Bonzini } 12119156df12SPaolo Bonzini 12128ee79e70SKevin Wolf if (!bs->drv || !bs->drv->supports_backing) { 12138ee79e70SKevin Wolf ret = -EINVAL; 12148ee79e70SKevin Wolf error_setg(errp, "Driver doesn't support backing files"); 12158ee79e70SKevin Wolf QDECREF(options); 12168ee79e70SKevin Wolf goto free_exit; 12178ee79e70SKevin Wolf } 12188ee79e70SKevin Wolf 12198d24cce1SFam Zheng backing_hd = bdrv_new("", errp); 12208d24cce1SFam Zheng 12219156df12SPaolo Bonzini if (bs->backing_format[0] != '\0') { 12229156df12SPaolo Bonzini back_drv = bdrv_find_format(bs->backing_format); 12239156df12SPaolo Bonzini } 12249156df12SPaolo Bonzini 1225f67503e5SMax Reitz assert(bs->backing_hd == NULL); 12268d24cce1SFam Zheng ret = bdrv_open(&backing_hd, 1227ddf5636dSMax Reitz *backing_filename ? backing_filename : NULL, NULL, options, 1228317fc44eSKevin Wolf bdrv_backing_flags(bs->open_flags), back_drv, &local_err); 12299156df12SPaolo Bonzini if (ret < 0) { 12308d24cce1SFam Zheng bdrv_unref(backing_hd); 12318d24cce1SFam Zheng backing_hd = NULL; 12329156df12SPaolo Bonzini bs->open_flags |= BDRV_O_NO_BACKING; 1233b04b6b6eSFam Zheng error_setg(errp, "Could not open backing file: %s", 1234b04b6b6eSFam Zheng error_get_pretty(local_err)); 1235b04b6b6eSFam Zheng error_free(local_err); 12361ba4b6a5SBenoît Canet goto free_exit; 12379156df12SPaolo Bonzini } 12388d24cce1SFam Zheng bdrv_set_backing_hd(bs, backing_hd); 1239d80ac658SPeter Feiner 12401ba4b6a5SBenoît Canet free_exit: 12411ba4b6a5SBenoît Canet g_free(backing_filename); 12421ba4b6a5SBenoît Canet return ret; 12439156df12SPaolo Bonzini } 12449156df12SPaolo Bonzini 1245b6ce07aaSKevin Wolf /* 1246da557aacSMax Reitz * Opens a disk image whose options are given as BlockdevRef in another block 1247da557aacSMax Reitz * device's options. 1248da557aacSMax Reitz * 1249da557aacSMax Reitz * If allow_none is true, no image will be opened if filename is false and no 1250da557aacSMax Reitz * BlockdevRef is given. *pbs will remain unchanged and 0 will be returned. 1251da557aacSMax Reitz * 1252da557aacSMax Reitz * bdrev_key specifies the key for the image's BlockdevRef in the options QDict. 1253da557aacSMax Reitz * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict 1254da557aacSMax Reitz * itself, all options starting with "${bdref_key}." are considered part of the 1255da557aacSMax Reitz * BlockdevRef. 1256da557aacSMax Reitz * 1257da557aacSMax Reitz * The BlockdevRef will be removed from the options QDict. 1258f67503e5SMax Reitz * 1259f67503e5SMax Reitz * To conform with the behavior of bdrv_open(), *pbs has to be NULL. 1260da557aacSMax Reitz */ 1261da557aacSMax Reitz int bdrv_open_image(BlockDriverState **pbs, const char *filename, 1262da557aacSMax Reitz QDict *options, const char *bdref_key, int flags, 1263f7d9fd8cSMax Reitz bool allow_none, Error **errp) 1264da557aacSMax Reitz { 1265da557aacSMax Reitz QDict *image_options; 1266da557aacSMax Reitz int ret; 1267da557aacSMax Reitz char *bdref_key_dot; 1268da557aacSMax Reitz const char *reference; 1269da557aacSMax Reitz 1270f67503e5SMax Reitz assert(pbs); 1271f67503e5SMax Reitz assert(*pbs == NULL); 1272f67503e5SMax Reitz 1273da557aacSMax Reitz bdref_key_dot = g_strdup_printf("%s.", bdref_key); 1274da557aacSMax Reitz qdict_extract_subqdict(options, &image_options, bdref_key_dot); 1275da557aacSMax Reitz g_free(bdref_key_dot); 1276da557aacSMax Reitz 1277da557aacSMax Reitz reference = qdict_get_try_str(options, bdref_key); 1278da557aacSMax Reitz if (!filename && !reference && !qdict_size(image_options)) { 1279da557aacSMax Reitz if (allow_none) { 1280da557aacSMax Reitz ret = 0; 1281da557aacSMax Reitz } else { 1282da557aacSMax Reitz error_setg(errp, "A block device must be specified for \"%s\"", 1283da557aacSMax Reitz bdref_key); 1284da557aacSMax Reitz ret = -EINVAL; 1285da557aacSMax Reitz } 1286b20e61e0SMarkus Armbruster QDECREF(image_options); 1287da557aacSMax Reitz goto done; 1288da557aacSMax Reitz } 1289da557aacSMax Reitz 1290f7d9fd8cSMax Reitz ret = bdrv_open(pbs, filename, reference, image_options, flags, NULL, errp); 1291da557aacSMax Reitz 1292da557aacSMax Reitz done: 1293da557aacSMax Reitz qdict_del(options, bdref_key); 1294da557aacSMax Reitz return ret; 1295da557aacSMax Reitz } 1296da557aacSMax Reitz 12976b8aeca5SChen Gang int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp) 1298b998875dSKevin Wolf { 1299b998875dSKevin Wolf /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */ 13001ba4b6a5SBenoît Canet char *tmp_filename = g_malloc0(PATH_MAX + 1); 1301b998875dSKevin Wolf int64_t total_size; 1302b998875dSKevin Wolf BlockDriver *bdrv_qcow2; 130383d0521aSChunyan Liu QemuOpts *opts = NULL; 1304b998875dSKevin Wolf QDict *snapshot_options; 1305b998875dSKevin Wolf BlockDriverState *bs_snapshot; 1306b998875dSKevin Wolf Error *local_err; 1307b998875dSKevin Wolf int ret; 1308b998875dSKevin Wolf 1309b998875dSKevin Wolf /* if snapshot, we create a temporary backing file and open it 1310b998875dSKevin Wolf instead of opening 'filename' directly */ 1311b998875dSKevin Wolf 1312b998875dSKevin Wolf /* Get the required size from the image */ 1313f187743aSKevin Wolf total_size = bdrv_getlength(bs); 1314f187743aSKevin Wolf if (total_size < 0) { 13156b8aeca5SChen Gang ret = total_size; 1316f187743aSKevin Wolf error_setg_errno(errp, -total_size, "Could not get image size"); 13171ba4b6a5SBenoît Canet goto out; 1318f187743aSKevin Wolf } 1319b998875dSKevin Wolf 1320b998875dSKevin Wolf /* Create the temporary image */ 13211ba4b6a5SBenoît Canet ret = get_tmp_filename(tmp_filename, PATH_MAX + 1); 1322b998875dSKevin Wolf if (ret < 0) { 1323b998875dSKevin Wolf error_setg_errno(errp, -ret, "Could not get temporary filename"); 13241ba4b6a5SBenoît Canet goto out; 1325b998875dSKevin Wolf } 1326b998875dSKevin Wolf 1327b998875dSKevin Wolf bdrv_qcow2 = bdrv_find_format("qcow2"); 1328c282e1fdSChunyan Liu opts = qemu_opts_create(bdrv_qcow2->create_opts, NULL, 0, 1329c282e1fdSChunyan Liu &error_abort); 133083d0521aSChunyan Liu qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size); 1331c282e1fdSChunyan Liu ret = bdrv_create(bdrv_qcow2, tmp_filename, opts, &local_err); 133283d0521aSChunyan Liu qemu_opts_del(opts); 1333b998875dSKevin Wolf if (ret < 0) { 1334b998875dSKevin Wolf error_setg_errno(errp, -ret, "Could not create temporary overlay " 1335b998875dSKevin Wolf "'%s': %s", tmp_filename, 1336b998875dSKevin Wolf error_get_pretty(local_err)); 1337b998875dSKevin Wolf error_free(local_err); 13381ba4b6a5SBenoît Canet goto out; 1339b998875dSKevin Wolf } 1340b998875dSKevin Wolf 1341b998875dSKevin Wolf /* Prepare a new options QDict for the temporary file */ 1342b998875dSKevin Wolf snapshot_options = qdict_new(); 1343b998875dSKevin Wolf qdict_put(snapshot_options, "file.driver", 1344b998875dSKevin Wolf qstring_from_str("file")); 1345b998875dSKevin Wolf qdict_put(snapshot_options, "file.filename", 1346b998875dSKevin Wolf qstring_from_str(tmp_filename)); 1347b998875dSKevin Wolf 134898522f63SKevin Wolf bs_snapshot = bdrv_new("", &error_abort); 1349b998875dSKevin Wolf 1350b998875dSKevin Wolf ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options, 1351b1e6fc08SKevin Wolf flags, bdrv_qcow2, &local_err); 1352b998875dSKevin Wolf if (ret < 0) { 1353b998875dSKevin Wolf error_propagate(errp, local_err); 13541ba4b6a5SBenoît Canet goto out; 1355b998875dSKevin Wolf } 1356b998875dSKevin Wolf 1357b998875dSKevin Wolf bdrv_append(bs_snapshot, bs); 13581ba4b6a5SBenoît Canet 13591ba4b6a5SBenoît Canet out: 13601ba4b6a5SBenoît Canet g_free(tmp_filename); 13616b8aeca5SChen Gang return ret; 1362b998875dSKevin Wolf } 1363b998875dSKevin Wolf 1364da557aacSMax Reitz /* 1365b6ce07aaSKevin Wolf * Opens a disk image (raw, qcow2, vmdk, ...) 1366de9c0cecSKevin Wolf * 1367de9c0cecSKevin Wolf * options is a QDict of options to pass to the block drivers, or NULL for an 1368de9c0cecSKevin Wolf * empty set of options. The reference to the QDict belongs to the block layer 1369de9c0cecSKevin Wolf * after the call (even on failure), so if the caller intends to reuse the 1370de9c0cecSKevin Wolf * dictionary, it needs to use QINCREF() before calling bdrv_open. 1371f67503e5SMax Reitz * 1372f67503e5SMax Reitz * If *pbs is NULL, a new BDS will be created with a pointer to it stored there. 1373f67503e5SMax Reitz * If it is not NULL, the referenced BDS will be reused. 1374ddf5636dSMax Reitz * 1375ddf5636dSMax Reitz * The reference parameter may be used to specify an existing block device which 1376ddf5636dSMax Reitz * should be opened. If specified, neither options nor a filename may be given, 1377ddf5636dSMax Reitz * nor can an existing BDS be reused (that is, *pbs has to be NULL). 1378b6ce07aaSKevin Wolf */ 1379ddf5636dSMax Reitz int bdrv_open(BlockDriverState **pbs, const char *filename, 1380ddf5636dSMax Reitz const char *reference, QDict *options, int flags, 1381ddf5636dSMax Reitz BlockDriver *drv, Error **errp) 1382ea2384d3Sbellard { 1383b6ce07aaSKevin Wolf int ret; 1384f67503e5SMax Reitz BlockDriverState *file = NULL, *bs; 138574fe54f2SKevin Wolf const char *drvname; 138634b5d2c6SMax Reitz Error *local_err = NULL; 1387b1e6fc08SKevin Wolf int snapshot_flags = 0; 138833e3963eSbellard 1389f67503e5SMax Reitz assert(pbs); 1390f67503e5SMax Reitz 1391ddf5636dSMax Reitz if (reference) { 1392ddf5636dSMax Reitz bool options_non_empty = options ? qdict_size(options) : false; 1393ddf5636dSMax Reitz QDECREF(options); 1394ddf5636dSMax Reitz 1395ddf5636dSMax Reitz if (*pbs) { 1396ddf5636dSMax Reitz error_setg(errp, "Cannot reuse an existing BDS when referencing " 1397ddf5636dSMax Reitz "another block device"); 1398ddf5636dSMax Reitz return -EINVAL; 1399ddf5636dSMax Reitz } 1400ddf5636dSMax Reitz 1401ddf5636dSMax Reitz if (filename || options_non_empty) { 1402ddf5636dSMax Reitz error_setg(errp, "Cannot reference an existing block device with " 1403ddf5636dSMax Reitz "additional options or a new filename"); 1404ddf5636dSMax Reitz return -EINVAL; 1405ddf5636dSMax Reitz } 1406ddf5636dSMax Reitz 1407ddf5636dSMax Reitz bs = bdrv_lookup_bs(reference, reference, errp); 1408ddf5636dSMax Reitz if (!bs) { 1409ddf5636dSMax Reitz return -ENODEV; 1410ddf5636dSMax Reitz } 1411ddf5636dSMax Reitz bdrv_ref(bs); 1412ddf5636dSMax Reitz *pbs = bs; 1413ddf5636dSMax Reitz return 0; 1414ddf5636dSMax Reitz } 1415ddf5636dSMax Reitz 1416f67503e5SMax Reitz if (*pbs) { 1417f67503e5SMax Reitz bs = *pbs; 1418f67503e5SMax Reitz } else { 141998522f63SKevin Wolf bs = bdrv_new("", &error_abort); 1420f67503e5SMax Reitz } 1421f67503e5SMax Reitz 1422de9c0cecSKevin Wolf /* NULL means an empty set of options */ 1423de9c0cecSKevin Wolf if (options == NULL) { 1424de9c0cecSKevin Wolf options = qdict_new(); 1425de9c0cecSKevin Wolf } 1426de9c0cecSKevin Wolf 142717b005f1SKevin Wolf ret = bdrv_fill_options(&options, &filename, flags, drv, &local_err); 1428462f5bcfSKevin Wolf if (local_err) { 1429462f5bcfSKevin Wolf goto fail; 1430462f5bcfSKevin Wolf } 1431462f5bcfSKevin Wolf 143276c591b0SKevin Wolf /* Find the right image format driver */ 143376c591b0SKevin Wolf drv = NULL; 143476c591b0SKevin Wolf drvname = qdict_get_try_str(options, "driver"); 143576c591b0SKevin Wolf if (drvname) { 143676c591b0SKevin Wolf drv = bdrv_find_format(drvname); 143776c591b0SKevin Wolf qdict_del(options, "driver"); 143876c591b0SKevin Wolf if (!drv) { 143976c591b0SKevin Wolf error_setg(errp, "Unknown driver: '%s'", drvname); 144076c591b0SKevin Wolf ret = -EINVAL; 144176c591b0SKevin Wolf goto fail; 144276c591b0SKevin Wolf } 144376c591b0SKevin Wolf } 144476c591b0SKevin Wolf 144576c591b0SKevin Wolf assert(drvname || !(flags & BDRV_O_PROTOCOL)); 144676c591b0SKevin Wolf if (drv && !drv->bdrv_file_open) { 144776c591b0SKevin Wolf /* If the user explicitly wants a format driver here, we'll need to add 144876c591b0SKevin Wolf * another layer for the protocol in bs->file */ 144976c591b0SKevin Wolf flags &= ~BDRV_O_PROTOCOL; 145076c591b0SKevin Wolf } 145176c591b0SKevin Wolf 1452de9c0cecSKevin Wolf bs->options = options; 1453b6ad491aSKevin Wolf options = qdict_clone_shallow(options); 1454de9c0cecSKevin Wolf 1455f500a6d3SKevin Wolf /* Open image file without format layer */ 1456f4788adcSKevin Wolf if ((flags & BDRV_O_PROTOCOL) == 0) { 1457be028adcSJeff Cody if (flags & BDRV_O_RDWR) { 1458be028adcSJeff Cody flags |= BDRV_O_ALLOW_RDWR; 1459be028adcSJeff Cody } 1460b1e6fc08SKevin Wolf if (flags & BDRV_O_SNAPSHOT) { 1461b1e6fc08SKevin Wolf snapshot_flags = bdrv_temp_snapshot_flags(flags); 1462b1e6fc08SKevin Wolf flags = bdrv_backing_flags(flags); 1463b1e6fc08SKevin Wolf } 1464be028adcSJeff Cody 1465f67503e5SMax Reitz assert(file == NULL); 1466054963f8SMax Reitz ret = bdrv_open_image(&file, filename, options, "file", 14670b50cc88SKevin Wolf bdrv_inherited_flags(flags), 14680b50cc88SKevin Wolf true, &local_err); 1469f500a6d3SKevin Wolf if (ret < 0) { 14708bfea15dSKevin Wolf goto fail; 1471f500a6d3SKevin Wolf } 1472f4788adcSKevin Wolf } 1473f500a6d3SKevin Wolf 147476c591b0SKevin Wolf /* Image format probing */ 147576c591b0SKevin Wolf if (!drv && file) { 147634b5d2c6SMax Reitz ret = find_image_format(file, filename, &drv, &local_err); 147717b005f1SKevin Wolf if (ret < 0) { 147817b005f1SKevin Wolf goto fail; 147917b005f1SKevin Wolf } 148076c591b0SKevin Wolf } else if (!drv) { 14812a05cbe4SMax Reitz error_setg(errp, "Must specify either driver or file"); 14822a05cbe4SMax Reitz ret = -EINVAL; 14838bfea15dSKevin Wolf goto fail; 14842a05cbe4SMax Reitz } 1485f500a6d3SKevin Wolf 1486b6ce07aaSKevin Wolf /* Open the image */ 148734b5d2c6SMax Reitz ret = bdrv_open_common(bs, file, options, flags, drv, &local_err); 1488b6ce07aaSKevin Wolf if (ret < 0) { 14898bfea15dSKevin Wolf goto fail; 14906987307cSChristoph Hellwig } 14916987307cSChristoph Hellwig 14922a05cbe4SMax Reitz if (file && (bs->file != file)) { 14934f6fd349SFam Zheng bdrv_unref(file); 1494f500a6d3SKevin Wolf file = NULL; 1495f500a6d3SKevin Wolf } 1496f500a6d3SKevin Wolf 1497b6ce07aaSKevin Wolf /* If there is a backing file, use it */ 14989156df12SPaolo Bonzini if ((flags & BDRV_O_NO_BACKING) == 0) { 149931ca6d07SKevin Wolf QDict *backing_options; 150031ca6d07SKevin Wolf 15015726d872SBenoît Canet qdict_extract_subqdict(options, &backing_options, "backing."); 150234b5d2c6SMax Reitz ret = bdrv_open_backing_file(bs, backing_options, &local_err); 1503b6ce07aaSKevin Wolf if (ret < 0) { 1504b6ad491aSKevin Wolf goto close_and_fail; 1505b6ce07aaSKevin Wolf } 1506b6ce07aaSKevin Wolf } 1507b6ce07aaSKevin Wolf 1508b998875dSKevin Wolf /* For snapshot=on, create a temporary qcow2 overlay. bs points to the 1509b998875dSKevin Wolf * temporary snapshot afterwards. */ 1510b1e6fc08SKevin Wolf if (snapshot_flags) { 15116b8aeca5SChen Gang ret = bdrv_append_temp_snapshot(bs, snapshot_flags, &local_err); 1512b998875dSKevin Wolf if (local_err) { 1513b998875dSKevin Wolf goto close_and_fail; 1514b998875dSKevin Wolf } 1515b998875dSKevin Wolf } 1516b998875dSKevin Wolf 1517b6ad491aSKevin Wolf /* Check if any unknown options were used */ 15185acd9d81SMax Reitz if (options && (qdict_size(options) != 0)) { 1519b6ad491aSKevin Wolf const QDictEntry *entry = qdict_first(options); 15205acd9d81SMax Reitz if (flags & BDRV_O_PROTOCOL) { 15215acd9d81SMax Reitz error_setg(errp, "Block protocol '%s' doesn't support the option " 15225acd9d81SMax Reitz "'%s'", drv->format_name, entry->key); 15235acd9d81SMax Reitz } else { 152434b5d2c6SMax Reitz error_setg(errp, "Block format '%s' used by device '%s' doesn't " 15255acd9d81SMax Reitz "support the option '%s'", drv->format_name, 15265acd9d81SMax Reitz bs->device_name, entry->key); 15275acd9d81SMax Reitz } 1528b6ad491aSKevin Wolf 1529b6ad491aSKevin Wolf ret = -EINVAL; 1530b6ad491aSKevin Wolf goto close_and_fail; 1531b6ad491aSKevin Wolf } 1532b6ad491aSKevin Wolf 1533b6ce07aaSKevin Wolf if (!bdrv_key_required(bs)) { 15347d4b4ba5SMarkus Armbruster bdrv_dev_change_media_cb(bs, true); 1535c3adb58fSMarkus Armbruster } else if (!runstate_check(RUN_STATE_PRELAUNCH) 1536c3adb58fSMarkus Armbruster && !runstate_check(RUN_STATE_INMIGRATE) 1537c3adb58fSMarkus Armbruster && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */ 1538c3adb58fSMarkus Armbruster error_setg(errp, 1539c3adb58fSMarkus Armbruster "Guest must be stopped for opening of encrypted image"); 1540c3adb58fSMarkus Armbruster ret = -EBUSY; 1541c3adb58fSMarkus Armbruster goto close_and_fail; 1542b6ce07aaSKevin Wolf } 1543b6ce07aaSKevin Wolf 1544c3adb58fSMarkus Armbruster QDECREF(options); 1545f67503e5SMax Reitz *pbs = bs; 1546b6ce07aaSKevin Wolf return 0; 1547b6ce07aaSKevin Wolf 15488bfea15dSKevin Wolf fail: 1549f500a6d3SKevin Wolf if (file != NULL) { 15504f6fd349SFam Zheng bdrv_unref(file); 1551f500a6d3SKevin Wolf } 1552de9c0cecSKevin Wolf QDECREF(bs->options); 1553b6ad491aSKevin Wolf QDECREF(options); 1554de9c0cecSKevin Wolf bs->options = NULL; 1555f67503e5SMax Reitz if (!*pbs) { 1556f67503e5SMax Reitz /* If *pbs is NULL, a new BDS has been created in this function and 1557f67503e5SMax Reitz needs to be freed now. Otherwise, it does not need to be closed, 1558f67503e5SMax Reitz since it has not really been opened yet. */ 1559f67503e5SMax Reitz bdrv_unref(bs); 1560f67503e5SMax Reitz } 156184d18f06SMarkus Armbruster if (local_err) { 156234b5d2c6SMax Reitz error_propagate(errp, local_err); 156334b5d2c6SMax Reitz } 1564b6ad491aSKevin Wolf return ret; 1565de9c0cecSKevin Wolf 1566b6ad491aSKevin Wolf close_and_fail: 1567f67503e5SMax Reitz /* See fail path, but now the BDS has to be always closed */ 1568f67503e5SMax Reitz if (*pbs) { 1569b6ad491aSKevin Wolf bdrv_close(bs); 1570f67503e5SMax Reitz } else { 1571f67503e5SMax Reitz bdrv_unref(bs); 1572f67503e5SMax Reitz } 1573b6ad491aSKevin Wolf QDECREF(options); 157484d18f06SMarkus Armbruster if (local_err) { 157534b5d2c6SMax Reitz error_propagate(errp, local_err); 157634b5d2c6SMax Reitz } 1577b6ce07aaSKevin Wolf return ret; 1578b6ce07aaSKevin Wolf } 1579b6ce07aaSKevin Wolf 1580e971aa12SJeff Cody typedef struct BlockReopenQueueEntry { 1581e971aa12SJeff Cody bool prepared; 1582e971aa12SJeff Cody BDRVReopenState state; 1583e971aa12SJeff Cody QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry; 1584e971aa12SJeff Cody } BlockReopenQueueEntry; 1585e971aa12SJeff Cody 1586e971aa12SJeff Cody /* 1587e971aa12SJeff Cody * Adds a BlockDriverState to a simple queue for an atomic, transactional 1588e971aa12SJeff Cody * reopen of multiple devices. 1589e971aa12SJeff Cody * 1590e971aa12SJeff Cody * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT 1591e971aa12SJeff Cody * already performed, or alternatively may be NULL a new BlockReopenQueue will 1592e971aa12SJeff Cody * be created and initialized. This newly created BlockReopenQueue should be 1593e971aa12SJeff Cody * passed back in for subsequent calls that are intended to be of the same 1594e971aa12SJeff Cody * atomic 'set'. 1595e971aa12SJeff Cody * 1596e971aa12SJeff Cody * bs is the BlockDriverState to add to the reopen queue. 1597e971aa12SJeff Cody * 1598e971aa12SJeff Cody * flags contains the open flags for the associated bs 1599e971aa12SJeff Cody * 1600e971aa12SJeff Cody * returns a pointer to bs_queue, which is either the newly allocated 1601e971aa12SJeff Cody * bs_queue, or the existing bs_queue being used. 1602e971aa12SJeff Cody * 1603e971aa12SJeff Cody */ 1604e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue, 1605e971aa12SJeff Cody BlockDriverState *bs, int flags) 1606e971aa12SJeff Cody { 1607e971aa12SJeff Cody assert(bs != NULL); 1608e971aa12SJeff Cody 1609e971aa12SJeff Cody BlockReopenQueueEntry *bs_entry; 1610e971aa12SJeff Cody if (bs_queue == NULL) { 1611e971aa12SJeff Cody bs_queue = g_new0(BlockReopenQueue, 1); 1612e971aa12SJeff Cody QSIMPLEQ_INIT(bs_queue); 1613e971aa12SJeff Cody } 1614e971aa12SJeff Cody 1615f1f25a2eSKevin Wolf /* bdrv_open() masks this flag out */ 1616f1f25a2eSKevin Wolf flags &= ~BDRV_O_PROTOCOL; 1617f1f25a2eSKevin Wolf 1618e971aa12SJeff Cody if (bs->file) { 1619f1f25a2eSKevin Wolf bdrv_reopen_queue(bs_queue, bs->file, bdrv_inherited_flags(flags)); 1620e971aa12SJeff Cody } 1621e971aa12SJeff Cody 1622e971aa12SJeff Cody bs_entry = g_new0(BlockReopenQueueEntry, 1); 1623e971aa12SJeff Cody QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry); 1624e971aa12SJeff Cody 1625e971aa12SJeff Cody bs_entry->state.bs = bs; 1626e971aa12SJeff Cody bs_entry->state.flags = flags; 1627e971aa12SJeff Cody 1628e971aa12SJeff Cody return bs_queue; 1629e971aa12SJeff Cody } 1630e971aa12SJeff Cody 1631e971aa12SJeff Cody /* 1632e971aa12SJeff Cody * Reopen multiple BlockDriverStates atomically & transactionally. 1633e971aa12SJeff Cody * 1634e971aa12SJeff Cody * The queue passed in (bs_queue) must have been built up previous 1635e971aa12SJeff Cody * via bdrv_reopen_queue(). 1636e971aa12SJeff Cody * 1637e971aa12SJeff Cody * Reopens all BDS specified in the queue, with the appropriate 1638e971aa12SJeff Cody * flags. All devices are prepared for reopen, and failure of any 1639e971aa12SJeff Cody * device will cause all device changes to be abandonded, and intermediate 1640e971aa12SJeff Cody * data cleaned up. 1641e971aa12SJeff Cody * 1642e971aa12SJeff Cody * If all devices prepare successfully, then the changes are committed 1643e971aa12SJeff Cody * to all devices. 1644e971aa12SJeff Cody * 1645e971aa12SJeff Cody */ 1646e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp) 1647e971aa12SJeff Cody { 1648e971aa12SJeff Cody int ret = -1; 1649e971aa12SJeff Cody BlockReopenQueueEntry *bs_entry, *next; 1650e971aa12SJeff Cody Error *local_err = NULL; 1651e971aa12SJeff Cody 1652e971aa12SJeff Cody assert(bs_queue != NULL); 1653e971aa12SJeff Cody 1654e971aa12SJeff Cody bdrv_drain_all(); 1655e971aa12SJeff Cody 1656e971aa12SJeff Cody QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) { 1657e971aa12SJeff Cody if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) { 1658e971aa12SJeff Cody error_propagate(errp, local_err); 1659e971aa12SJeff Cody goto cleanup; 1660e971aa12SJeff Cody } 1661e971aa12SJeff Cody bs_entry->prepared = true; 1662e971aa12SJeff Cody } 1663e971aa12SJeff Cody 1664e971aa12SJeff Cody /* If we reach this point, we have success and just need to apply the 1665e971aa12SJeff Cody * changes 1666e971aa12SJeff Cody */ 1667e971aa12SJeff Cody QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) { 1668e971aa12SJeff Cody bdrv_reopen_commit(&bs_entry->state); 1669e971aa12SJeff Cody } 1670e971aa12SJeff Cody 1671e971aa12SJeff Cody ret = 0; 1672e971aa12SJeff Cody 1673e971aa12SJeff Cody cleanup: 1674e971aa12SJeff Cody QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) { 1675e971aa12SJeff Cody if (ret && bs_entry->prepared) { 1676e971aa12SJeff Cody bdrv_reopen_abort(&bs_entry->state); 1677e971aa12SJeff Cody } 1678e971aa12SJeff Cody g_free(bs_entry); 1679e971aa12SJeff Cody } 1680e971aa12SJeff Cody g_free(bs_queue); 1681e971aa12SJeff Cody return ret; 1682e971aa12SJeff Cody } 1683e971aa12SJeff Cody 1684e971aa12SJeff Cody 1685e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */ 1686e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp) 1687e971aa12SJeff Cody { 1688e971aa12SJeff Cody int ret = -1; 1689e971aa12SJeff Cody Error *local_err = NULL; 1690e971aa12SJeff Cody BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags); 1691e971aa12SJeff Cody 1692e971aa12SJeff Cody ret = bdrv_reopen_multiple(queue, &local_err); 1693e971aa12SJeff Cody if (local_err != NULL) { 1694e971aa12SJeff Cody error_propagate(errp, local_err); 1695e971aa12SJeff Cody } 1696e971aa12SJeff Cody return ret; 1697e971aa12SJeff Cody } 1698e971aa12SJeff Cody 1699e971aa12SJeff Cody 1700e971aa12SJeff Cody /* 1701e971aa12SJeff Cody * Prepares a BlockDriverState for reopen. All changes are staged in the 1702e971aa12SJeff Cody * 'opaque' field of the BDRVReopenState, which is used and allocated by 1703e971aa12SJeff Cody * the block driver layer .bdrv_reopen_prepare() 1704e971aa12SJeff Cody * 1705e971aa12SJeff Cody * bs is the BlockDriverState to reopen 1706e971aa12SJeff Cody * flags are the new open flags 1707e971aa12SJeff Cody * queue is the reopen queue 1708e971aa12SJeff Cody * 1709e971aa12SJeff Cody * Returns 0 on success, non-zero on error. On error errp will be set 1710e971aa12SJeff Cody * as well. 1711e971aa12SJeff Cody * 1712e971aa12SJeff Cody * On failure, bdrv_reopen_abort() will be called to clean up any data. 1713e971aa12SJeff Cody * It is the responsibility of the caller to then call the abort() or 1714e971aa12SJeff Cody * commit() for any other BDS that have been left in a prepare() state 1715e971aa12SJeff Cody * 1716e971aa12SJeff Cody */ 1717e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue, 1718e971aa12SJeff Cody Error **errp) 1719e971aa12SJeff Cody { 1720e971aa12SJeff Cody int ret = -1; 1721e971aa12SJeff Cody Error *local_err = NULL; 1722e971aa12SJeff Cody BlockDriver *drv; 1723e971aa12SJeff Cody 1724e971aa12SJeff Cody assert(reopen_state != NULL); 1725e971aa12SJeff Cody assert(reopen_state->bs->drv != NULL); 1726e971aa12SJeff Cody drv = reopen_state->bs->drv; 1727e971aa12SJeff Cody 1728e971aa12SJeff Cody /* if we are to stay read-only, do not allow permission change 1729e971aa12SJeff Cody * to r/w */ 1730e971aa12SJeff Cody if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) && 1731e971aa12SJeff Cody reopen_state->flags & BDRV_O_RDWR) { 1732e971aa12SJeff Cody error_set(errp, QERR_DEVICE_IS_READ_ONLY, 1733e971aa12SJeff Cody reopen_state->bs->device_name); 1734e971aa12SJeff Cody goto error; 1735e971aa12SJeff Cody } 1736e971aa12SJeff Cody 1737e971aa12SJeff Cody 1738e971aa12SJeff Cody ret = bdrv_flush(reopen_state->bs); 1739e971aa12SJeff Cody if (ret) { 1740e971aa12SJeff Cody error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive", 1741e971aa12SJeff Cody strerror(-ret)); 1742e971aa12SJeff Cody goto error; 1743e971aa12SJeff Cody } 1744e971aa12SJeff Cody 1745e971aa12SJeff Cody if (drv->bdrv_reopen_prepare) { 1746e971aa12SJeff Cody ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err); 1747e971aa12SJeff Cody if (ret) { 1748e971aa12SJeff Cody if (local_err != NULL) { 1749e971aa12SJeff Cody error_propagate(errp, local_err); 1750e971aa12SJeff Cody } else { 1751d8b6895fSLuiz Capitulino error_setg(errp, "failed while preparing to reopen image '%s'", 1752e971aa12SJeff Cody reopen_state->bs->filename); 1753e971aa12SJeff Cody } 1754e971aa12SJeff Cody goto error; 1755e971aa12SJeff Cody } 1756e971aa12SJeff Cody } else { 1757e971aa12SJeff Cody /* It is currently mandatory to have a bdrv_reopen_prepare() 1758e971aa12SJeff Cody * handler for each supported drv. */ 1759e971aa12SJeff Cody error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED, 1760e971aa12SJeff Cody drv->format_name, reopen_state->bs->device_name, 1761e971aa12SJeff Cody "reopening of file"); 1762e971aa12SJeff Cody ret = -1; 1763e971aa12SJeff Cody goto error; 1764e971aa12SJeff Cody } 1765e971aa12SJeff Cody 1766e971aa12SJeff Cody ret = 0; 1767e971aa12SJeff Cody 1768e971aa12SJeff Cody error: 1769e971aa12SJeff Cody return ret; 1770e971aa12SJeff Cody } 1771e971aa12SJeff Cody 1772e971aa12SJeff Cody /* 1773e971aa12SJeff Cody * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and 1774e971aa12SJeff Cody * makes them final by swapping the staging BlockDriverState contents into 1775e971aa12SJeff Cody * the active BlockDriverState contents. 1776e971aa12SJeff Cody */ 1777e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state) 1778e971aa12SJeff Cody { 1779e971aa12SJeff Cody BlockDriver *drv; 1780e971aa12SJeff Cody 1781e971aa12SJeff Cody assert(reopen_state != NULL); 1782e971aa12SJeff Cody drv = reopen_state->bs->drv; 1783e971aa12SJeff Cody assert(drv != NULL); 1784e971aa12SJeff Cody 1785e971aa12SJeff Cody /* If there are any driver level actions to take */ 1786e971aa12SJeff Cody if (drv->bdrv_reopen_commit) { 1787e971aa12SJeff Cody drv->bdrv_reopen_commit(reopen_state); 1788e971aa12SJeff Cody } 1789e971aa12SJeff Cody 1790e971aa12SJeff Cody /* set BDS specific flags now */ 1791e971aa12SJeff Cody reopen_state->bs->open_flags = reopen_state->flags; 1792e971aa12SJeff Cody reopen_state->bs->enable_write_cache = !!(reopen_state->flags & 1793e971aa12SJeff Cody BDRV_O_CACHE_WB); 1794e971aa12SJeff Cody reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR); 1795355ef4acSKevin Wolf 17963baca891SKevin Wolf bdrv_refresh_limits(reopen_state->bs, NULL); 1797e971aa12SJeff Cody } 1798e971aa12SJeff Cody 1799e971aa12SJeff Cody /* 1800e971aa12SJeff Cody * Abort the reopen, and delete and free the staged changes in 1801e971aa12SJeff Cody * reopen_state 1802e971aa12SJeff Cody */ 1803e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state) 1804e971aa12SJeff Cody { 1805e971aa12SJeff Cody BlockDriver *drv; 1806e971aa12SJeff Cody 1807e971aa12SJeff Cody assert(reopen_state != NULL); 1808e971aa12SJeff Cody drv = reopen_state->bs->drv; 1809e971aa12SJeff Cody assert(drv != NULL); 1810e971aa12SJeff Cody 1811e971aa12SJeff Cody if (drv->bdrv_reopen_abort) { 1812e971aa12SJeff Cody drv->bdrv_reopen_abort(reopen_state); 1813e971aa12SJeff Cody } 1814e971aa12SJeff Cody } 1815e971aa12SJeff Cody 1816e971aa12SJeff Cody 1817fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs) 1818fc01f7e7Sbellard { 18193e914655SPaolo Bonzini if (bs->job) { 18203e914655SPaolo Bonzini block_job_cancel_sync(bs->job); 18213e914655SPaolo Bonzini } 182258fda173SStefan Hajnoczi bdrv_drain_all(); /* complete I/O */ 182358fda173SStefan Hajnoczi bdrv_flush(bs); 182458fda173SStefan Hajnoczi bdrv_drain_all(); /* in case flush left pending I/O */ 1825d7d512f6SPaolo Bonzini notifier_list_notify(&bs->close_notifiers, bs); 18267094f12fSKevin Wolf 18273cbc002cSPaolo Bonzini if (bs->drv) { 1828557df6acSStefan Hajnoczi if (bs->backing_hd) { 1829826b6ca0SFam Zheng BlockDriverState *backing_hd = bs->backing_hd; 1830826b6ca0SFam Zheng bdrv_set_backing_hd(bs, NULL); 1831826b6ca0SFam Zheng bdrv_unref(backing_hd); 1832557df6acSStefan Hajnoczi } 1833ea2384d3Sbellard bs->drv->bdrv_close(bs); 18347267c094SAnthony Liguori g_free(bs->opaque); 1835ea2384d3Sbellard bs->opaque = NULL; 1836ea2384d3Sbellard bs->drv = NULL; 183753fec9d3SStefan Hajnoczi bs->copy_on_read = 0; 1838a275fa42SPaolo Bonzini bs->backing_file[0] = '\0'; 1839a275fa42SPaolo Bonzini bs->backing_format[0] = '\0'; 18406405875cSPaolo Bonzini bs->total_sectors = 0; 18416405875cSPaolo Bonzini bs->encrypted = 0; 18426405875cSPaolo Bonzini bs->valid_key = 0; 18436405875cSPaolo Bonzini bs->sg = 0; 18446405875cSPaolo Bonzini bs->growable = 0; 18450d51b4deSAsias He bs->zero_beyond_eof = false; 1846de9c0cecSKevin Wolf QDECREF(bs->options); 1847de9c0cecSKevin Wolf bs->options = NULL; 1848b338082bSbellard 184966f82ceeSKevin Wolf if (bs->file != NULL) { 18504f6fd349SFam Zheng bdrv_unref(bs->file); 18510ac9377dSPaolo Bonzini bs->file = NULL; 185266f82ceeSKevin Wolf } 18539ca11154SPavel Hrdina } 185466f82ceeSKevin Wolf 18557d4b4ba5SMarkus Armbruster bdrv_dev_change_media_cb(bs, false); 185698f90dbaSZhi Yong Wu 185798f90dbaSZhi Yong Wu /*throttling disk I/O limits*/ 185898f90dbaSZhi Yong Wu if (bs->io_limits_enabled) { 185998f90dbaSZhi Yong Wu bdrv_io_limits_disable(bs); 186098f90dbaSZhi Yong Wu } 1861b338082bSbellard } 1862b338082bSbellard 18632bc93fedSMORITA Kazutaka void bdrv_close_all(void) 18642bc93fedSMORITA Kazutaka { 18652bc93fedSMORITA Kazutaka BlockDriverState *bs; 18662bc93fedSMORITA Kazutaka 1867dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 1868ed78cda3SStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 1869ed78cda3SStefan Hajnoczi 1870ed78cda3SStefan Hajnoczi aio_context_acquire(aio_context); 18712bc93fedSMORITA Kazutaka bdrv_close(bs); 1872ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 18732bc93fedSMORITA Kazutaka } 18742bc93fedSMORITA Kazutaka } 18752bc93fedSMORITA Kazutaka 187688266f5aSStefan Hajnoczi /* Check if any requests are in-flight (including throttled requests) */ 187788266f5aSStefan Hajnoczi static bool bdrv_requests_pending(BlockDriverState *bs) 187888266f5aSStefan Hajnoczi { 187988266f5aSStefan Hajnoczi if (!QLIST_EMPTY(&bs->tracked_requests)) { 188088266f5aSStefan Hajnoczi return true; 188188266f5aSStefan Hajnoczi } 1882cc0681c4SBenoît Canet if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) { 1883cc0681c4SBenoît Canet return true; 1884cc0681c4SBenoît Canet } 1885cc0681c4SBenoît Canet if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) { 188688266f5aSStefan Hajnoczi return true; 188788266f5aSStefan Hajnoczi } 188888266f5aSStefan Hajnoczi if (bs->file && bdrv_requests_pending(bs->file)) { 188988266f5aSStefan Hajnoczi return true; 189088266f5aSStefan Hajnoczi } 189188266f5aSStefan Hajnoczi if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) { 189288266f5aSStefan Hajnoczi return true; 189388266f5aSStefan Hajnoczi } 189488266f5aSStefan Hajnoczi return false; 189588266f5aSStefan Hajnoczi } 189688266f5aSStefan Hajnoczi 1897922453bcSStefan Hajnoczi /* 1898922453bcSStefan Hajnoczi * Wait for pending requests to complete across all BlockDriverStates 1899922453bcSStefan Hajnoczi * 1900922453bcSStefan Hajnoczi * This function does not flush data to disk, use bdrv_flush_all() for that 1901922453bcSStefan Hajnoczi * after calling this function. 19024c355d53SZhi Yong Wu * 19034c355d53SZhi Yong Wu * Note that completion of an asynchronous I/O operation can trigger any 19044c355d53SZhi Yong Wu * number of other I/O operations on other devices---for example a coroutine 19054c355d53SZhi Yong Wu * can be arbitrarily complex and a constant flow of I/O can come until the 19064c355d53SZhi Yong Wu * coroutine is complete. Because of this, it is not possible to have a 19074c355d53SZhi Yong Wu * function to drain a single device's I/O queue. 1908922453bcSStefan Hajnoczi */ 1909922453bcSStefan Hajnoczi void bdrv_drain_all(void) 1910922453bcSStefan Hajnoczi { 191188266f5aSStefan Hajnoczi /* Always run first iteration so any pending completion BHs run */ 191288266f5aSStefan Hajnoczi bool busy = true; 1913922453bcSStefan Hajnoczi BlockDriverState *bs; 1914922453bcSStefan Hajnoczi 191588266f5aSStefan Hajnoczi while (busy) { 19169b536adcSStefan Hajnoczi busy = false; 1917922453bcSStefan Hajnoczi 19189b536adcSStefan Hajnoczi QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 19199b536adcSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 19209b536adcSStefan Hajnoczi bool bs_busy; 19219b536adcSStefan Hajnoczi 19229b536adcSStefan Hajnoczi aio_context_acquire(aio_context); 1923448ad91dSMing Lei bdrv_flush_io_queue(bs); 19249b536adcSStefan Hajnoczi bdrv_start_throttled_reqs(bs); 19259b536adcSStefan Hajnoczi bs_busy = bdrv_requests_pending(bs); 19269b536adcSStefan Hajnoczi bs_busy |= aio_poll(aio_context, bs_busy); 19279b536adcSStefan Hajnoczi aio_context_release(aio_context); 19289b536adcSStefan Hajnoczi 19299b536adcSStefan Hajnoczi busy |= bs_busy; 19309b536adcSStefan Hajnoczi } 1931922453bcSStefan Hajnoczi } 1932922453bcSStefan Hajnoczi } 1933922453bcSStefan Hajnoczi 1934dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and 1935dc364f4cSBenoît Canet * graph_bdrv_state list. 1936d22b2f41SRyan Harper Also, NULL terminate the device_name to prevent double remove */ 1937d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs) 1938d22b2f41SRyan Harper { 1939d22b2f41SRyan Harper if (bs->device_name[0] != '\0') { 1940dc364f4cSBenoît Canet QTAILQ_REMOVE(&bdrv_states, bs, device_list); 1941d22b2f41SRyan Harper } 1942d22b2f41SRyan Harper bs->device_name[0] = '\0'; 1943dc364f4cSBenoît Canet if (bs->node_name[0] != '\0') { 1944dc364f4cSBenoît Canet QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list); 1945dc364f4cSBenoît Canet } 1946dc364f4cSBenoît Canet bs->node_name[0] = '\0'; 1947d22b2f41SRyan Harper } 1948d22b2f41SRyan Harper 1949e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs) 1950e023b2e2SPaolo Bonzini { 1951e023b2e2SPaolo Bonzini if (bs->drv && bs->drv->bdrv_rebind) { 1952e023b2e2SPaolo Bonzini bs->drv->bdrv_rebind(bs); 1953e023b2e2SPaolo Bonzini } 1954e023b2e2SPaolo Bonzini } 1955e023b2e2SPaolo Bonzini 19564ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest, 19574ddc07caSPaolo Bonzini BlockDriverState *bs_src) 19584ddc07caSPaolo Bonzini { 19594ddc07caSPaolo Bonzini /* move some fields that need to stay attached to the device */ 19604ddc07caSPaolo Bonzini 19614ddc07caSPaolo Bonzini /* dev info */ 19624ddc07caSPaolo Bonzini bs_dest->dev_ops = bs_src->dev_ops; 19634ddc07caSPaolo Bonzini bs_dest->dev_opaque = bs_src->dev_opaque; 19644ddc07caSPaolo Bonzini bs_dest->dev = bs_src->dev; 19651b7fd729SPaolo Bonzini bs_dest->guest_block_size = bs_src->guest_block_size; 19664ddc07caSPaolo Bonzini bs_dest->copy_on_read = bs_src->copy_on_read; 19674ddc07caSPaolo Bonzini 19684ddc07caSPaolo Bonzini bs_dest->enable_write_cache = bs_src->enable_write_cache; 19694ddc07caSPaolo Bonzini 1970cc0681c4SBenoît Canet /* i/o throttled req */ 1971cc0681c4SBenoît Canet memcpy(&bs_dest->throttle_state, 1972cc0681c4SBenoît Canet &bs_src->throttle_state, 1973cc0681c4SBenoît Canet sizeof(ThrottleState)); 1974cc0681c4SBenoît Canet bs_dest->throttled_reqs[0] = bs_src->throttled_reqs[0]; 1975cc0681c4SBenoît Canet bs_dest->throttled_reqs[1] = bs_src->throttled_reqs[1]; 19764ddc07caSPaolo Bonzini bs_dest->io_limits_enabled = bs_src->io_limits_enabled; 19774ddc07caSPaolo Bonzini 19784ddc07caSPaolo Bonzini /* r/w error */ 19794ddc07caSPaolo Bonzini bs_dest->on_read_error = bs_src->on_read_error; 19804ddc07caSPaolo Bonzini bs_dest->on_write_error = bs_src->on_write_error; 19814ddc07caSPaolo Bonzini 19824ddc07caSPaolo Bonzini /* i/o status */ 19834ddc07caSPaolo Bonzini bs_dest->iostatus_enabled = bs_src->iostatus_enabled; 19844ddc07caSPaolo Bonzini bs_dest->iostatus = bs_src->iostatus; 19854ddc07caSPaolo Bonzini 19864ddc07caSPaolo Bonzini /* dirty bitmap */ 1987e4654d2dSFam Zheng bs_dest->dirty_bitmaps = bs_src->dirty_bitmaps; 19884ddc07caSPaolo Bonzini 19899fcb0251SFam Zheng /* reference count */ 19909fcb0251SFam Zheng bs_dest->refcnt = bs_src->refcnt; 19919fcb0251SFam Zheng 19924ddc07caSPaolo Bonzini /* job */ 19934ddc07caSPaolo Bonzini bs_dest->job = bs_src->job; 19944ddc07caSPaolo Bonzini 19954ddc07caSPaolo Bonzini /* keep the same entry in bdrv_states */ 19964ddc07caSPaolo Bonzini pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name), 19974ddc07caSPaolo Bonzini bs_src->device_name); 1998dc364f4cSBenoît Canet bs_dest->device_list = bs_src->device_list; 1999fbe40ff7SFam Zheng memcpy(bs_dest->op_blockers, bs_src->op_blockers, 2000fbe40ff7SFam Zheng sizeof(bs_dest->op_blockers)); 20014ddc07caSPaolo Bonzini } 20024ddc07caSPaolo Bonzini 20034ddc07caSPaolo Bonzini /* 20044ddc07caSPaolo Bonzini * Swap bs contents for two image chains while they are live, 20054ddc07caSPaolo Bonzini * while keeping required fields on the BlockDriverState that is 20064ddc07caSPaolo Bonzini * actually attached to a device. 20074ddc07caSPaolo Bonzini * 20084ddc07caSPaolo Bonzini * This will modify the BlockDriverState fields, and swap contents 20094ddc07caSPaolo Bonzini * between bs_new and bs_old. Both bs_new and bs_old are modified. 20104ddc07caSPaolo Bonzini * 20114ddc07caSPaolo Bonzini * bs_new is required to be anonymous. 20124ddc07caSPaolo Bonzini * 20134ddc07caSPaolo Bonzini * This function does not create any image files. 20144ddc07caSPaolo Bonzini */ 20154ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old) 20164ddc07caSPaolo Bonzini { 20174ddc07caSPaolo Bonzini BlockDriverState tmp; 20184ddc07caSPaolo Bonzini 201990ce8a06SBenoît Canet /* The code needs to swap the node_name but simply swapping node_list won't 202090ce8a06SBenoît Canet * work so first remove the nodes from the graph list, do the swap then 202190ce8a06SBenoît Canet * insert them back if needed. 202290ce8a06SBenoît Canet */ 202390ce8a06SBenoît Canet if (bs_new->node_name[0] != '\0') { 202490ce8a06SBenoît Canet QTAILQ_REMOVE(&graph_bdrv_states, bs_new, node_list); 202590ce8a06SBenoît Canet } 202690ce8a06SBenoît Canet if (bs_old->node_name[0] != '\0') { 202790ce8a06SBenoît Canet QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list); 202890ce8a06SBenoît Canet } 202990ce8a06SBenoît Canet 20304ddc07caSPaolo Bonzini /* bs_new must be anonymous and shouldn't have anything fancy enabled */ 20314ddc07caSPaolo Bonzini assert(bs_new->device_name[0] == '\0'); 2032e4654d2dSFam Zheng assert(QLIST_EMPTY(&bs_new->dirty_bitmaps)); 20334ddc07caSPaolo Bonzini assert(bs_new->job == NULL); 20344ddc07caSPaolo Bonzini assert(bs_new->dev == NULL); 20354ddc07caSPaolo Bonzini assert(bs_new->io_limits_enabled == false); 2036cc0681c4SBenoît Canet assert(!throttle_have_timer(&bs_new->throttle_state)); 20374ddc07caSPaolo Bonzini 20384ddc07caSPaolo Bonzini tmp = *bs_new; 20394ddc07caSPaolo Bonzini *bs_new = *bs_old; 20404ddc07caSPaolo Bonzini *bs_old = tmp; 20414ddc07caSPaolo Bonzini 20424ddc07caSPaolo Bonzini /* there are some fields that should not be swapped, move them back */ 20434ddc07caSPaolo Bonzini bdrv_move_feature_fields(&tmp, bs_old); 20444ddc07caSPaolo Bonzini bdrv_move_feature_fields(bs_old, bs_new); 20454ddc07caSPaolo Bonzini bdrv_move_feature_fields(bs_new, &tmp); 20464ddc07caSPaolo Bonzini 20474ddc07caSPaolo Bonzini /* bs_new shouldn't be in bdrv_states even after the swap! */ 20484ddc07caSPaolo Bonzini assert(bs_new->device_name[0] == '\0'); 20494ddc07caSPaolo Bonzini 20504ddc07caSPaolo Bonzini /* Check a few fields that should remain attached to the device */ 20514ddc07caSPaolo Bonzini assert(bs_new->dev == NULL); 20524ddc07caSPaolo Bonzini assert(bs_new->job == NULL); 20534ddc07caSPaolo Bonzini assert(bs_new->io_limits_enabled == false); 2054cc0681c4SBenoît Canet assert(!throttle_have_timer(&bs_new->throttle_state)); 20554ddc07caSPaolo Bonzini 205690ce8a06SBenoît Canet /* insert the nodes back into the graph node list if needed */ 205790ce8a06SBenoît Canet if (bs_new->node_name[0] != '\0') { 205890ce8a06SBenoît Canet QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_new, node_list); 205990ce8a06SBenoît Canet } 206090ce8a06SBenoît Canet if (bs_old->node_name[0] != '\0') { 206190ce8a06SBenoît Canet QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_old, node_list); 206290ce8a06SBenoît Canet } 206390ce8a06SBenoît Canet 20644ddc07caSPaolo Bonzini bdrv_rebind(bs_new); 20654ddc07caSPaolo Bonzini bdrv_rebind(bs_old); 20664ddc07caSPaolo Bonzini } 20674ddc07caSPaolo Bonzini 20688802d1fdSJeff Cody /* 20698802d1fdSJeff Cody * Add new bs contents at the top of an image chain while the chain is 20708802d1fdSJeff Cody * live, while keeping required fields on the top layer. 20718802d1fdSJeff Cody * 20728802d1fdSJeff Cody * This will modify the BlockDriverState fields, and swap contents 20738802d1fdSJeff Cody * between bs_new and bs_top. Both bs_new and bs_top are modified. 20748802d1fdSJeff Cody * 2075f6801b83SJeff Cody * bs_new is required to be anonymous. 2076f6801b83SJeff Cody * 20778802d1fdSJeff Cody * This function does not create any image files. 20788802d1fdSJeff Cody */ 20798802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top) 20808802d1fdSJeff Cody { 20814ddc07caSPaolo Bonzini bdrv_swap(bs_new, bs_top); 20828802d1fdSJeff Cody 20838802d1fdSJeff Cody /* The contents of 'tmp' will become bs_top, as we are 20848802d1fdSJeff Cody * swapping bs_new and bs_top contents. */ 20858d24cce1SFam Zheng bdrv_set_backing_hd(bs_top, bs_new); 20868802d1fdSJeff Cody } 20878802d1fdSJeff Cody 20884f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs) 2089b338082bSbellard { 2090fa879d62SMarkus Armbruster assert(!bs->dev); 20913e914655SPaolo Bonzini assert(!bs->job); 20923718d8abSFam Zheng assert(bdrv_op_blocker_is_empty(bs)); 20934f6fd349SFam Zheng assert(!bs->refcnt); 2094e4654d2dSFam Zheng assert(QLIST_EMPTY(&bs->dirty_bitmaps)); 209518846deeSMarkus Armbruster 2096e1b5c52eSStefan Hajnoczi bdrv_close(bs); 2097e1b5c52eSStefan Hajnoczi 20981b7bdbc1SStefan Hajnoczi /* remove from list, if necessary */ 2099d22b2f41SRyan Harper bdrv_make_anon(bs); 210034c6f050Saurel32 21017267c094SAnthony Liguori g_free(bs); 2102fc01f7e7Sbellard } 2103fc01f7e7Sbellard 2104fa879d62SMarkus Armbruster int bdrv_attach_dev(BlockDriverState *bs, void *dev) 2105fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */ 210618846deeSMarkus Armbruster { 2107fa879d62SMarkus Armbruster if (bs->dev) { 210818846deeSMarkus Armbruster return -EBUSY; 210918846deeSMarkus Armbruster } 2110fa879d62SMarkus Armbruster bs->dev = dev; 211128a7282aSLuiz Capitulino bdrv_iostatus_reset(bs); 2112*2a87151fSStefan Hajnoczi 2113*2a87151fSStefan Hajnoczi /* We're expecting I/O from the device so bump up coroutine pool size */ 2114*2a87151fSStefan Hajnoczi qemu_coroutine_adjust_pool_size(COROUTINE_POOL_RESERVATION); 211518846deeSMarkus Armbruster return 0; 211618846deeSMarkus Armbruster } 211718846deeSMarkus Armbruster 2118fa879d62SMarkus Armbruster /* TODO qdevified devices don't use this, remove when devices are qdevified */ 2119fa879d62SMarkus Armbruster void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev) 212018846deeSMarkus Armbruster { 2121fa879d62SMarkus Armbruster if (bdrv_attach_dev(bs, dev) < 0) { 2122fa879d62SMarkus Armbruster abort(); 2123fa879d62SMarkus Armbruster } 2124fa879d62SMarkus Armbruster } 2125fa879d62SMarkus Armbruster 2126fa879d62SMarkus Armbruster void bdrv_detach_dev(BlockDriverState *bs, void *dev) 2127fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */ 2128fa879d62SMarkus Armbruster { 2129fa879d62SMarkus Armbruster assert(bs->dev == dev); 2130fa879d62SMarkus Armbruster bs->dev = NULL; 21310e49de52SMarkus Armbruster bs->dev_ops = NULL; 21320e49de52SMarkus Armbruster bs->dev_opaque = NULL; 21331b7fd729SPaolo Bonzini bs->guest_block_size = 512; 2134*2a87151fSStefan Hajnoczi qemu_coroutine_adjust_pool_size(-COROUTINE_POOL_RESERVATION); 213518846deeSMarkus Armbruster } 213618846deeSMarkus Armbruster 2137fa879d62SMarkus Armbruster /* TODO change to return DeviceState * when all users are qdevified */ 2138fa879d62SMarkus Armbruster void *bdrv_get_attached_dev(BlockDriverState *bs) 213918846deeSMarkus Armbruster { 2140fa879d62SMarkus Armbruster return bs->dev; 214118846deeSMarkus Armbruster } 214218846deeSMarkus Armbruster 21430e49de52SMarkus Armbruster void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops, 21440e49de52SMarkus Armbruster void *opaque) 21450e49de52SMarkus Armbruster { 21460e49de52SMarkus Armbruster bs->dev_ops = ops; 21470e49de52SMarkus Armbruster bs->dev_opaque = opaque; 21480e49de52SMarkus Armbruster } 21490e49de52SMarkus Armbruster 21507d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load) 21510e49de52SMarkus Armbruster { 2152145feb17SMarkus Armbruster if (bs->dev_ops && bs->dev_ops->change_media_cb) { 21536f382ed2SLuiz Capitulino bool tray_was_closed = !bdrv_dev_is_tray_open(bs); 21547d4b4ba5SMarkus Armbruster bs->dev_ops->change_media_cb(bs->dev_opaque, load); 21556f382ed2SLuiz Capitulino if (tray_was_closed) { 21566f382ed2SLuiz Capitulino /* tray open */ 2157a5ee7bd4SWenchao Xia qapi_event_send_device_tray_moved(bdrv_get_device_name(bs), 2158a5ee7bd4SWenchao Xia true, &error_abort); 21596f382ed2SLuiz Capitulino } 21606f382ed2SLuiz Capitulino if (load) { 21616f382ed2SLuiz Capitulino /* tray close */ 2162a5ee7bd4SWenchao Xia qapi_event_send_device_tray_moved(bdrv_get_device_name(bs), 2163a5ee7bd4SWenchao Xia false, &error_abort); 21646f382ed2SLuiz Capitulino } 2165145feb17SMarkus Armbruster } 2166145feb17SMarkus Armbruster } 2167145feb17SMarkus Armbruster 21682c6942faSMarkus Armbruster bool bdrv_dev_has_removable_media(BlockDriverState *bs) 21692c6942faSMarkus Armbruster { 21702c6942faSMarkus Armbruster return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb); 21712c6942faSMarkus Armbruster } 21722c6942faSMarkus Armbruster 2173025ccaa7SPaolo Bonzini void bdrv_dev_eject_request(BlockDriverState *bs, bool force) 2174025ccaa7SPaolo Bonzini { 2175025ccaa7SPaolo Bonzini if (bs->dev_ops && bs->dev_ops->eject_request_cb) { 2176025ccaa7SPaolo Bonzini bs->dev_ops->eject_request_cb(bs->dev_opaque, force); 2177025ccaa7SPaolo Bonzini } 2178025ccaa7SPaolo Bonzini } 2179025ccaa7SPaolo Bonzini 2180e4def80bSMarkus Armbruster bool bdrv_dev_is_tray_open(BlockDriverState *bs) 2181e4def80bSMarkus Armbruster { 2182e4def80bSMarkus Armbruster if (bs->dev_ops && bs->dev_ops->is_tray_open) { 2183e4def80bSMarkus Armbruster return bs->dev_ops->is_tray_open(bs->dev_opaque); 2184e4def80bSMarkus Armbruster } 2185e4def80bSMarkus Armbruster return false; 2186e4def80bSMarkus Armbruster } 2187e4def80bSMarkus Armbruster 2188145feb17SMarkus Armbruster static void bdrv_dev_resize_cb(BlockDriverState *bs) 2189145feb17SMarkus Armbruster { 2190145feb17SMarkus Armbruster if (bs->dev_ops && bs->dev_ops->resize_cb) { 2191145feb17SMarkus Armbruster bs->dev_ops->resize_cb(bs->dev_opaque); 21920e49de52SMarkus Armbruster } 21930e49de52SMarkus Armbruster } 21940e49de52SMarkus Armbruster 2195f107639aSMarkus Armbruster bool bdrv_dev_is_medium_locked(BlockDriverState *bs) 2196f107639aSMarkus Armbruster { 2197f107639aSMarkus Armbruster if (bs->dev_ops && bs->dev_ops->is_medium_locked) { 2198f107639aSMarkus Armbruster return bs->dev_ops->is_medium_locked(bs->dev_opaque); 2199f107639aSMarkus Armbruster } 2200f107639aSMarkus Armbruster return false; 2201f107639aSMarkus Armbruster } 2202f107639aSMarkus Armbruster 2203e97fc193Saliguori /* 2204e97fc193Saliguori * Run consistency checks on an image 2205e97fc193Saliguori * 2206e076f338SKevin Wolf * Returns 0 if the check could be completed (it doesn't mean that the image is 2207a1c7273bSStefan Weil * free of errors) or -errno when an internal error occurred. The results of the 2208e076f338SKevin Wolf * check are stored in res. 2209e97fc193Saliguori */ 22104534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix) 2211e97fc193Saliguori { 2212e97fc193Saliguori if (bs->drv->bdrv_check == NULL) { 2213e97fc193Saliguori return -ENOTSUP; 2214e97fc193Saliguori } 2215e97fc193Saliguori 2216e076f338SKevin Wolf memset(res, 0, sizeof(*res)); 22174534ff54SKevin Wolf return bs->drv->bdrv_check(bs, res, fix); 2218e97fc193Saliguori } 2219e97fc193Saliguori 22208a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048 22218a426614SKevin Wolf 222233e3963eSbellard /* commit COW file into the raw image */ 222333e3963eSbellard int bdrv_commit(BlockDriverState *bs) 222433e3963eSbellard { 222519cb3738Sbellard BlockDriver *drv = bs->drv; 222672706ea4SJeff Cody int64_t sector, total_sectors, length, backing_length; 22278a426614SKevin Wolf int n, ro, open_flags; 22280bce597dSJeff Cody int ret = 0; 222972706ea4SJeff Cody uint8_t *buf = NULL; 2230c2cba3d9SJim Meyering char filename[PATH_MAX]; 223133e3963eSbellard 223219cb3738Sbellard if (!drv) 223319cb3738Sbellard return -ENOMEDIUM; 223433e3963eSbellard 22354dca4b63SNaphtali Sprei if (!bs->backing_hd) { 22364dca4b63SNaphtali Sprei return -ENOTSUP; 22374dca4b63SNaphtali Sprei } 22384dca4b63SNaphtali Sprei 22393718d8abSFam Zheng if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, NULL) || 22403718d8abSFam Zheng bdrv_op_is_blocked(bs->backing_hd, BLOCK_OP_TYPE_COMMIT, NULL)) { 22412d3735d3SStefan Hajnoczi return -EBUSY; 22422d3735d3SStefan Hajnoczi } 22432d3735d3SStefan Hajnoczi 22444dca4b63SNaphtali Sprei ro = bs->backing_hd->read_only; 2245c2cba3d9SJim Meyering /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */ 2246c2cba3d9SJim Meyering pstrcpy(filename, sizeof(filename), bs->backing_hd->filename); 22474dca4b63SNaphtali Sprei open_flags = bs->backing_hd->open_flags; 22484dca4b63SNaphtali Sprei 22494dca4b63SNaphtali Sprei if (ro) { 22500bce597dSJeff Cody if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) { 22510bce597dSJeff Cody return -EACCES; 22524dca4b63SNaphtali Sprei } 2253ea2384d3Sbellard } 2254ea2384d3Sbellard 225572706ea4SJeff Cody length = bdrv_getlength(bs); 225672706ea4SJeff Cody if (length < 0) { 225772706ea4SJeff Cody ret = length; 225872706ea4SJeff Cody goto ro_cleanup; 225972706ea4SJeff Cody } 226072706ea4SJeff Cody 226172706ea4SJeff Cody backing_length = bdrv_getlength(bs->backing_hd); 226272706ea4SJeff Cody if (backing_length < 0) { 226372706ea4SJeff Cody ret = backing_length; 226472706ea4SJeff Cody goto ro_cleanup; 226572706ea4SJeff Cody } 226672706ea4SJeff Cody 226772706ea4SJeff Cody /* If our top snapshot is larger than the backing file image, 226872706ea4SJeff Cody * grow the backing file image if possible. If not possible, 226972706ea4SJeff Cody * we must return an error */ 227072706ea4SJeff Cody if (length > backing_length) { 227172706ea4SJeff Cody ret = bdrv_truncate(bs->backing_hd, length); 227272706ea4SJeff Cody if (ret < 0) { 227372706ea4SJeff Cody goto ro_cleanup; 227472706ea4SJeff Cody } 227572706ea4SJeff Cody } 227672706ea4SJeff Cody 227772706ea4SJeff Cody total_sectors = length >> BDRV_SECTOR_BITS; 22787267c094SAnthony Liguori buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE); 22798a426614SKevin Wolf 22808a426614SKevin Wolf for (sector = 0; sector < total_sectors; sector += n) { 2281d663640cSPaolo Bonzini ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n); 2282d663640cSPaolo Bonzini if (ret < 0) { 2283d663640cSPaolo Bonzini goto ro_cleanup; 2284d663640cSPaolo Bonzini } 2285d663640cSPaolo Bonzini if (ret) { 2286dabfa6ccSKevin Wolf ret = bdrv_read(bs, sector, buf, n); 2287dabfa6ccSKevin Wolf if (ret < 0) { 22884dca4b63SNaphtali Sprei goto ro_cleanup; 228933e3963eSbellard } 229033e3963eSbellard 2291dabfa6ccSKevin Wolf ret = bdrv_write(bs->backing_hd, sector, buf, n); 2292dabfa6ccSKevin Wolf if (ret < 0) { 22934dca4b63SNaphtali Sprei goto ro_cleanup; 229433e3963eSbellard } 229533e3963eSbellard } 229633e3963eSbellard } 229795389c86Sbellard 22981d44952fSChristoph Hellwig if (drv->bdrv_make_empty) { 22991d44952fSChristoph Hellwig ret = drv->bdrv_make_empty(bs); 2300dabfa6ccSKevin Wolf if (ret < 0) { 2301dabfa6ccSKevin Wolf goto ro_cleanup; 2302dabfa6ccSKevin Wolf } 23031d44952fSChristoph Hellwig bdrv_flush(bs); 23041d44952fSChristoph Hellwig } 230595389c86Sbellard 23063f5075aeSChristoph Hellwig /* 23073f5075aeSChristoph Hellwig * Make sure all data we wrote to the backing device is actually 23083f5075aeSChristoph Hellwig * stable on disk. 23093f5075aeSChristoph Hellwig */ 2310dabfa6ccSKevin Wolf if (bs->backing_hd) { 23113f5075aeSChristoph Hellwig bdrv_flush(bs->backing_hd); 2312dabfa6ccSKevin Wolf } 23134dca4b63SNaphtali Sprei 2314dabfa6ccSKevin Wolf ret = 0; 23154dca4b63SNaphtali Sprei ro_cleanup: 23167267c094SAnthony Liguori g_free(buf); 23174dca4b63SNaphtali Sprei 23184dca4b63SNaphtali Sprei if (ro) { 23190bce597dSJeff Cody /* ignoring error return here */ 23200bce597dSJeff Cody bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL); 23214dca4b63SNaphtali Sprei } 23224dca4b63SNaphtali Sprei 23231d44952fSChristoph Hellwig return ret; 232433e3963eSbellard } 232533e3963eSbellard 2326e8877497SStefan Hajnoczi int bdrv_commit_all(void) 23276ab4b5abSMarkus Armbruster { 23286ab4b5abSMarkus Armbruster BlockDriverState *bs; 23296ab4b5abSMarkus Armbruster 2330dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 2331ed78cda3SStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 2332ed78cda3SStefan Hajnoczi 2333ed78cda3SStefan Hajnoczi aio_context_acquire(aio_context); 2334272d2d8eSJeff Cody if (bs->drv && bs->backing_hd) { 2335e8877497SStefan Hajnoczi int ret = bdrv_commit(bs); 2336e8877497SStefan Hajnoczi if (ret < 0) { 2337ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 2338e8877497SStefan Hajnoczi return ret; 23396ab4b5abSMarkus Armbruster } 23406ab4b5abSMarkus Armbruster } 2341ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 2342272d2d8eSJeff Cody } 2343e8877497SStefan Hajnoczi return 0; 2344e8877497SStefan Hajnoczi } 23456ab4b5abSMarkus Armbruster 2346dbffbdcfSStefan Hajnoczi /** 2347dbffbdcfSStefan Hajnoczi * Remove an active request from the tracked requests list 2348dbffbdcfSStefan Hajnoczi * 2349dbffbdcfSStefan Hajnoczi * This function should be called when a tracked request is completing. 2350dbffbdcfSStefan Hajnoczi */ 2351dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req) 2352dbffbdcfSStefan Hajnoczi { 23532dbafdc0SKevin Wolf if (req->serialising) { 23542dbafdc0SKevin Wolf req->bs->serialising_in_flight--; 23552dbafdc0SKevin Wolf } 23562dbafdc0SKevin Wolf 2357dbffbdcfSStefan Hajnoczi QLIST_REMOVE(req, list); 2358f4658285SStefan Hajnoczi qemu_co_queue_restart_all(&req->wait_queue); 2359dbffbdcfSStefan Hajnoczi } 2360dbffbdcfSStefan Hajnoczi 2361dbffbdcfSStefan Hajnoczi /** 2362dbffbdcfSStefan Hajnoczi * Add an active request to the tracked requests list 2363dbffbdcfSStefan Hajnoczi */ 2364dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req, 2365dbffbdcfSStefan Hajnoczi BlockDriverState *bs, 2366793ed47aSKevin Wolf int64_t offset, 2367793ed47aSKevin Wolf unsigned int bytes, bool is_write) 2368dbffbdcfSStefan Hajnoczi { 2369dbffbdcfSStefan Hajnoczi *req = (BdrvTrackedRequest){ 2370dbffbdcfSStefan Hajnoczi .bs = bs, 2371793ed47aSKevin Wolf .offset = offset, 2372793ed47aSKevin Wolf .bytes = bytes, 2373dbffbdcfSStefan Hajnoczi .is_write = is_write, 23745f8b6491SStefan Hajnoczi .co = qemu_coroutine_self(), 23752dbafdc0SKevin Wolf .serialising = false, 23767327145fSKevin Wolf .overlap_offset = offset, 23777327145fSKevin Wolf .overlap_bytes = bytes, 2378dbffbdcfSStefan Hajnoczi }; 2379dbffbdcfSStefan Hajnoczi 2380f4658285SStefan Hajnoczi qemu_co_queue_init(&req->wait_queue); 2381f4658285SStefan Hajnoczi 2382dbffbdcfSStefan Hajnoczi QLIST_INSERT_HEAD(&bs->tracked_requests, req, list); 2383dbffbdcfSStefan Hajnoczi } 2384dbffbdcfSStefan Hajnoczi 2385e96126ffSKevin Wolf static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align) 23862dbafdc0SKevin Wolf { 23877327145fSKevin Wolf int64_t overlap_offset = req->offset & ~(align - 1); 2388e96126ffSKevin Wolf unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align) 23897327145fSKevin Wolf - overlap_offset; 23907327145fSKevin Wolf 23912dbafdc0SKevin Wolf if (!req->serialising) { 23922dbafdc0SKevin Wolf req->bs->serialising_in_flight++; 23932dbafdc0SKevin Wolf req->serialising = true; 23942dbafdc0SKevin Wolf } 23957327145fSKevin Wolf 23967327145fSKevin Wolf req->overlap_offset = MIN(req->overlap_offset, overlap_offset); 23977327145fSKevin Wolf req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes); 23982dbafdc0SKevin Wolf } 23992dbafdc0SKevin Wolf 2400d83947acSStefan Hajnoczi /** 2401d83947acSStefan Hajnoczi * Round a region to cluster boundaries 2402d83947acSStefan Hajnoczi */ 2403343bded4SPaolo Bonzini void bdrv_round_to_clusters(BlockDriverState *bs, 2404d83947acSStefan Hajnoczi int64_t sector_num, int nb_sectors, 2405d83947acSStefan Hajnoczi int64_t *cluster_sector_num, 2406d83947acSStefan Hajnoczi int *cluster_nb_sectors) 2407d83947acSStefan Hajnoczi { 2408d83947acSStefan Hajnoczi BlockDriverInfo bdi; 2409d83947acSStefan Hajnoczi 2410d83947acSStefan Hajnoczi if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) { 2411d83947acSStefan Hajnoczi *cluster_sector_num = sector_num; 2412d83947acSStefan Hajnoczi *cluster_nb_sectors = nb_sectors; 2413d83947acSStefan Hajnoczi } else { 2414d83947acSStefan Hajnoczi int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE; 2415d83947acSStefan Hajnoczi *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c); 2416d83947acSStefan Hajnoczi *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num + 2417d83947acSStefan Hajnoczi nb_sectors, c); 2418d83947acSStefan Hajnoczi } 2419d83947acSStefan Hajnoczi } 2420d83947acSStefan Hajnoczi 24217327145fSKevin Wolf static int bdrv_get_cluster_size(BlockDriverState *bs) 2422793ed47aSKevin Wolf { 2423793ed47aSKevin Wolf BlockDriverInfo bdi; 24247327145fSKevin Wolf int ret; 2425793ed47aSKevin Wolf 24267327145fSKevin Wolf ret = bdrv_get_info(bs, &bdi); 24277327145fSKevin Wolf if (ret < 0 || bdi.cluster_size == 0) { 24287327145fSKevin Wolf return bs->request_alignment; 2429793ed47aSKevin Wolf } else { 24307327145fSKevin Wolf return bdi.cluster_size; 2431793ed47aSKevin Wolf } 2432793ed47aSKevin Wolf } 2433793ed47aSKevin Wolf 2434f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req, 2435793ed47aSKevin Wolf int64_t offset, unsigned int bytes) 2436793ed47aSKevin Wolf { 2437d83947acSStefan Hajnoczi /* aaaa bbbb */ 24387327145fSKevin Wolf if (offset >= req->overlap_offset + req->overlap_bytes) { 2439d83947acSStefan Hajnoczi return false; 2440d83947acSStefan Hajnoczi } 2441d83947acSStefan Hajnoczi /* bbbb aaaa */ 24427327145fSKevin Wolf if (req->overlap_offset >= offset + bytes) { 2443d83947acSStefan Hajnoczi return false; 2444d83947acSStefan Hajnoczi } 2445d83947acSStefan Hajnoczi return true; 2446f4658285SStefan Hajnoczi } 2447f4658285SStefan Hajnoczi 244828de2dcdSKevin Wolf static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self) 2449f4658285SStefan Hajnoczi { 24502dbafdc0SKevin Wolf BlockDriverState *bs = self->bs; 2451f4658285SStefan Hajnoczi BdrvTrackedRequest *req; 2452f4658285SStefan Hajnoczi bool retry; 245328de2dcdSKevin Wolf bool waited = false; 2454f4658285SStefan Hajnoczi 24552dbafdc0SKevin Wolf if (!bs->serialising_in_flight) { 245628de2dcdSKevin Wolf return false; 24572dbafdc0SKevin Wolf } 24582dbafdc0SKevin Wolf 2459f4658285SStefan Hajnoczi do { 2460f4658285SStefan Hajnoczi retry = false; 2461f4658285SStefan Hajnoczi QLIST_FOREACH(req, &bs->tracked_requests, list) { 24622dbafdc0SKevin Wolf if (req == self || (!req->serialising && !self->serialising)) { 246365afd211SKevin Wolf continue; 246465afd211SKevin Wolf } 24657327145fSKevin Wolf if (tracked_request_overlaps(req, self->overlap_offset, 24667327145fSKevin Wolf self->overlap_bytes)) 24677327145fSKevin Wolf { 24685f8b6491SStefan Hajnoczi /* Hitting this means there was a reentrant request, for 24695f8b6491SStefan Hajnoczi * example, a block driver issuing nested requests. This must 24705f8b6491SStefan Hajnoczi * never happen since it means deadlock. 24715f8b6491SStefan Hajnoczi */ 24725f8b6491SStefan Hajnoczi assert(qemu_coroutine_self() != req->co); 24735f8b6491SStefan Hajnoczi 24746460440fSKevin Wolf /* If the request is already (indirectly) waiting for us, or 24756460440fSKevin Wolf * will wait for us as soon as it wakes up, then just go on 24766460440fSKevin Wolf * (instead of producing a deadlock in the former case). */ 24776460440fSKevin Wolf if (!req->waiting_for) { 24786460440fSKevin Wolf self->waiting_for = req; 2479f4658285SStefan Hajnoczi qemu_co_queue_wait(&req->wait_queue); 24806460440fSKevin Wolf self->waiting_for = NULL; 2481f4658285SStefan Hajnoczi retry = true; 248228de2dcdSKevin Wolf waited = true; 2483f4658285SStefan Hajnoczi break; 2484f4658285SStefan Hajnoczi } 2485f4658285SStefan Hajnoczi } 24866460440fSKevin Wolf } 2487f4658285SStefan Hajnoczi } while (retry); 248828de2dcdSKevin Wolf 248928de2dcdSKevin Wolf return waited; 2490f4658285SStefan Hajnoczi } 2491f4658285SStefan Hajnoczi 2492756e6736SKevin Wolf /* 2493756e6736SKevin Wolf * Return values: 2494756e6736SKevin Wolf * 0 - success 2495756e6736SKevin Wolf * -EINVAL - backing format specified, but no file 2496756e6736SKevin Wolf * -ENOSPC - can't update the backing file because no space is left in the 2497756e6736SKevin Wolf * image file header 2498756e6736SKevin Wolf * -ENOTSUP - format driver doesn't support changing the backing file 2499756e6736SKevin Wolf */ 2500756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs, 2501756e6736SKevin Wolf const char *backing_file, const char *backing_fmt) 2502756e6736SKevin Wolf { 2503756e6736SKevin Wolf BlockDriver *drv = bs->drv; 2504469ef350SPaolo Bonzini int ret; 2505756e6736SKevin Wolf 25065f377794SPaolo Bonzini /* Backing file format doesn't make sense without a backing file */ 25075f377794SPaolo Bonzini if (backing_fmt && !backing_file) { 25085f377794SPaolo Bonzini return -EINVAL; 25095f377794SPaolo Bonzini } 25105f377794SPaolo Bonzini 2511756e6736SKevin Wolf if (drv->bdrv_change_backing_file != NULL) { 2512469ef350SPaolo Bonzini ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt); 2513756e6736SKevin Wolf } else { 2514469ef350SPaolo Bonzini ret = -ENOTSUP; 2515756e6736SKevin Wolf } 2516469ef350SPaolo Bonzini 2517469ef350SPaolo Bonzini if (ret == 0) { 2518469ef350SPaolo Bonzini pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: ""); 2519469ef350SPaolo Bonzini pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: ""); 2520469ef350SPaolo Bonzini } 2521469ef350SPaolo Bonzini return ret; 2522756e6736SKevin Wolf } 2523756e6736SKevin Wolf 25246ebdcee2SJeff Cody /* 25256ebdcee2SJeff Cody * Finds the image layer in the chain that has 'bs' as its backing file. 25266ebdcee2SJeff Cody * 25276ebdcee2SJeff Cody * active is the current topmost image. 25286ebdcee2SJeff Cody * 25296ebdcee2SJeff Cody * Returns NULL if bs is not found in active's image chain, 25306ebdcee2SJeff Cody * or if active == bs. 25314caf0fcdSJeff Cody * 25324caf0fcdSJeff Cody * Returns the bottommost base image if bs == NULL. 25336ebdcee2SJeff Cody */ 25346ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active, 25356ebdcee2SJeff Cody BlockDriverState *bs) 25366ebdcee2SJeff Cody { 25374caf0fcdSJeff Cody while (active && bs != active->backing_hd) { 25384caf0fcdSJeff Cody active = active->backing_hd; 25396ebdcee2SJeff Cody } 25406ebdcee2SJeff Cody 25414caf0fcdSJeff Cody return active; 25426ebdcee2SJeff Cody } 25436ebdcee2SJeff Cody 25444caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */ 25454caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs) 25464caf0fcdSJeff Cody { 25474caf0fcdSJeff Cody return bdrv_find_overlay(bs, NULL); 25486ebdcee2SJeff Cody } 25496ebdcee2SJeff Cody 25506ebdcee2SJeff Cody typedef struct BlkIntermediateStates { 25516ebdcee2SJeff Cody BlockDriverState *bs; 25526ebdcee2SJeff Cody QSIMPLEQ_ENTRY(BlkIntermediateStates) entry; 25536ebdcee2SJeff Cody } BlkIntermediateStates; 25546ebdcee2SJeff Cody 25556ebdcee2SJeff Cody 25566ebdcee2SJeff Cody /* 25576ebdcee2SJeff Cody * Drops images above 'base' up to and including 'top', and sets the image 25586ebdcee2SJeff Cody * above 'top' to have base as its backing file. 25596ebdcee2SJeff Cody * 25606ebdcee2SJeff Cody * Requires that the overlay to 'top' is opened r/w, so that the backing file 25616ebdcee2SJeff Cody * information in 'bs' can be properly updated. 25626ebdcee2SJeff Cody * 25636ebdcee2SJeff Cody * E.g., this will convert the following chain: 25646ebdcee2SJeff Cody * bottom <- base <- intermediate <- top <- active 25656ebdcee2SJeff Cody * 25666ebdcee2SJeff Cody * to 25676ebdcee2SJeff Cody * 25686ebdcee2SJeff Cody * bottom <- base <- active 25696ebdcee2SJeff Cody * 25706ebdcee2SJeff Cody * It is allowed for bottom==base, in which case it converts: 25716ebdcee2SJeff Cody * 25726ebdcee2SJeff Cody * base <- intermediate <- top <- active 25736ebdcee2SJeff Cody * 25746ebdcee2SJeff Cody * to 25756ebdcee2SJeff Cody * 25766ebdcee2SJeff Cody * base <- active 25776ebdcee2SJeff Cody * 257854e26900SJeff Cody * If backing_file_str is non-NULL, it will be used when modifying top's 257954e26900SJeff Cody * overlay image metadata. 258054e26900SJeff Cody * 25816ebdcee2SJeff Cody * Error conditions: 25826ebdcee2SJeff Cody * if active == top, that is considered an error 25836ebdcee2SJeff Cody * 25846ebdcee2SJeff Cody */ 25856ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top, 258654e26900SJeff Cody BlockDriverState *base, const char *backing_file_str) 25876ebdcee2SJeff Cody { 25886ebdcee2SJeff Cody BlockDriverState *intermediate; 25896ebdcee2SJeff Cody BlockDriverState *base_bs = NULL; 25906ebdcee2SJeff Cody BlockDriverState *new_top_bs = NULL; 25916ebdcee2SJeff Cody BlkIntermediateStates *intermediate_state, *next; 25926ebdcee2SJeff Cody int ret = -EIO; 25936ebdcee2SJeff Cody 25946ebdcee2SJeff Cody QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete; 25956ebdcee2SJeff Cody QSIMPLEQ_INIT(&states_to_delete); 25966ebdcee2SJeff Cody 25976ebdcee2SJeff Cody if (!top->drv || !base->drv) { 25986ebdcee2SJeff Cody goto exit; 25996ebdcee2SJeff Cody } 26006ebdcee2SJeff Cody 26016ebdcee2SJeff Cody new_top_bs = bdrv_find_overlay(active, top); 26026ebdcee2SJeff Cody 26036ebdcee2SJeff Cody if (new_top_bs == NULL) { 26046ebdcee2SJeff Cody /* we could not find the image above 'top', this is an error */ 26056ebdcee2SJeff Cody goto exit; 26066ebdcee2SJeff Cody } 26076ebdcee2SJeff Cody 26086ebdcee2SJeff Cody /* special case of new_top_bs->backing_hd already pointing to base - nothing 26096ebdcee2SJeff Cody * to do, no intermediate images */ 26106ebdcee2SJeff Cody if (new_top_bs->backing_hd == base) { 26116ebdcee2SJeff Cody ret = 0; 26126ebdcee2SJeff Cody goto exit; 26136ebdcee2SJeff Cody } 26146ebdcee2SJeff Cody 26156ebdcee2SJeff Cody intermediate = top; 26166ebdcee2SJeff Cody 26176ebdcee2SJeff Cody /* now we will go down through the list, and add each BDS we find 26186ebdcee2SJeff Cody * into our deletion queue, until we hit the 'base' 26196ebdcee2SJeff Cody */ 26206ebdcee2SJeff Cody while (intermediate) { 26216ebdcee2SJeff Cody intermediate_state = g_malloc0(sizeof(BlkIntermediateStates)); 26226ebdcee2SJeff Cody intermediate_state->bs = intermediate; 26236ebdcee2SJeff Cody QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry); 26246ebdcee2SJeff Cody 26256ebdcee2SJeff Cody if (intermediate->backing_hd == base) { 26266ebdcee2SJeff Cody base_bs = intermediate->backing_hd; 26276ebdcee2SJeff Cody break; 26286ebdcee2SJeff Cody } 26296ebdcee2SJeff Cody intermediate = intermediate->backing_hd; 26306ebdcee2SJeff Cody } 26316ebdcee2SJeff Cody if (base_bs == NULL) { 26326ebdcee2SJeff Cody /* something went wrong, we did not end at the base. safely 26336ebdcee2SJeff Cody * unravel everything, and exit with error */ 26346ebdcee2SJeff Cody goto exit; 26356ebdcee2SJeff Cody } 26366ebdcee2SJeff Cody 26376ebdcee2SJeff Cody /* success - we can delete the intermediate states, and link top->base */ 263854e26900SJeff Cody backing_file_str = backing_file_str ? backing_file_str : base_bs->filename; 263954e26900SJeff Cody ret = bdrv_change_backing_file(new_top_bs, backing_file_str, 26406ebdcee2SJeff Cody base_bs->drv ? base_bs->drv->format_name : ""); 26416ebdcee2SJeff Cody if (ret) { 26426ebdcee2SJeff Cody goto exit; 26436ebdcee2SJeff Cody } 2644920beae1SFam Zheng bdrv_set_backing_hd(new_top_bs, base_bs); 26456ebdcee2SJeff Cody 26466ebdcee2SJeff Cody QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) { 26476ebdcee2SJeff Cody /* so that bdrv_close() does not recursively close the chain */ 2648920beae1SFam Zheng bdrv_set_backing_hd(intermediate_state->bs, NULL); 26494f6fd349SFam Zheng bdrv_unref(intermediate_state->bs); 26506ebdcee2SJeff Cody } 26516ebdcee2SJeff Cody ret = 0; 26526ebdcee2SJeff Cody 26536ebdcee2SJeff Cody exit: 26546ebdcee2SJeff Cody QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) { 26556ebdcee2SJeff Cody g_free(intermediate_state); 26566ebdcee2SJeff Cody } 26576ebdcee2SJeff Cody return ret; 26586ebdcee2SJeff Cody } 26596ebdcee2SJeff Cody 26606ebdcee2SJeff Cody 266171d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset, 266271d0770cSaliguori size_t size) 266371d0770cSaliguori { 266471d0770cSaliguori int64_t len; 266571d0770cSaliguori 26661dd3a447SKevin Wolf if (size > INT_MAX) { 26671dd3a447SKevin Wolf return -EIO; 26681dd3a447SKevin Wolf } 26691dd3a447SKevin Wolf 267071d0770cSaliguori if (!bdrv_is_inserted(bs)) 267171d0770cSaliguori return -ENOMEDIUM; 267271d0770cSaliguori 267371d0770cSaliguori if (bs->growable) 267471d0770cSaliguori return 0; 267571d0770cSaliguori 267671d0770cSaliguori len = bdrv_getlength(bs); 267771d0770cSaliguori 2678fbb7b4e0SKevin Wolf if (offset < 0) 2679fbb7b4e0SKevin Wolf return -EIO; 2680fbb7b4e0SKevin Wolf 2681fbb7b4e0SKevin Wolf if ((offset > len) || (len - offset < size)) 268271d0770cSaliguori return -EIO; 268371d0770cSaliguori 268471d0770cSaliguori return 0; 268571d0770cSaliguori } 268671d0770cSaliguori 268771d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num, 268871d0770cSaliguori int nb_sectors) 268971d0770cSaliguori { 269054db38a4SKevin Wolf if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) { 26918f4754edSKevin Wolf return -EIO; 26928f4754edSKevin Wolf } 26938f4754edSKevin Wolf 2694eb5a3165SJes Sorensen return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE, 2695eb5a3165SJes Sorensen nb_sectors * BDRV_SECTOR_SIZE); 269671d0770cSaliguori } 269771d0770cSaliguori 26981c9805a3SStefan Hajnoczi typedef struct RwCo { 26991c9805a3SStefan Hajnoczi BlockDriverState *bs; 2700775aa8b6SKevin Wolf int64_t offset; 27011c9805a3SStefan Hajnoczi QEMUIOVector *qiov; 27021c9805a3SStefan Hajnoczi bool is_write; 27031c9805a3SStefan Hajnoczi int ret; 27044105eaaaSPeter Lieven BdrvRequestFlags flags; 27051c9805a3SStefan Hajnoczi } RwCo; 27061c9805a3SStefan Hajnoczi 27071c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque) 2708fc01f7e7Sbellard { 27091c9805a3SStefan Hajnoczi RwCo *rwco = opaque; 2710fc01f7e7Sbellard 27111c9805a3SStefan Hajnoczi if (!rwco->is_write) { 2712775aa8b6SKevin Wolf rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset, 2713775aa8b6SKevin Wolf rwco->qiov->size, rwco->qiov, 27144105eaaaSPeter Lieven rwco->flags); 27151c9805a3SStefan Hajnoczi } else { 2716775aa8b6SKevin Wolf rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset, 2717775aa8b6SKevin Wolf rwco->qiov->size, rwco->qiov, 27184105eaaaSPeter Lieven rwco->flags); 27191c9805a3SStefan Hajnoczi } 27201c9805a3SStefan Hajnoczi } 2721e7a8a783SKevin Wolf 27221c9805a3SStefan Hajnoczi /* 27238d3b1a2dSKevin Wolf * Process a vectored synchronous request using coroutines 27241c9805a3SStefan Hajnoczi */ 2725775aa8b6SKevin Wolf static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset, 27264105eaaaSPeter Lieven QEMUIOVector *qiov, bool is_write, 27274105eaaaSPeter Lieven BdrvRequestFlags flags) 27281c9805a3SStefan Hajnoczi { 27291c9805a3SStefan Hajnoczi Coroutine *co; 27301c9805a3SStefan Hajnoczi RwCo rwco = { 27311c9805a3SStefan Hajnoczi .bs = bs, 2732775aa8b6SKevin Wolf .offset = offset, 27338d3b1a2dSKevin Wolf .qiov = qiov, 27341c9805a3SStefan Hajnoczi .is_write = is_write, 27351c9805a3SStefan Hajnoczi .ret = NOT_DONE, 27364105eaaaSPeter Lieven .flags = flags, 27371c9805a3SStefan Hajnoczi }; 27381c9805a3SStefan Hajnoczi 2739498e386cSZhi Yong Wu /** 2740498e386cSZhi Yong Wu * In sync call context, when the vcpu is blocked, this throttling timer 2741498e386cSZhi Yong Wu * will not fire; so the I/O throttling function has to be disabled here 2742498e386cSZhi Yong Wu * if it has been enabled. 2743498e386cSZhi Yong Wu */ 2744498e386cSZhi Yong Wu if (bs->io_limits_enabled) { 2745498e386cSZhi Yong Wu fprintf(stderr, "Disabling I/O throttling on '%s' due " 2746498e386cSZhi Yong Wu "to synchronous I/O.\n", bdrv_get_device_name(bs)); 2747498e386cSZhi Yong Wu bdrv_io_limits_disable(bs); 2748498e386cSZhi Yong Wu } 2749498e386cSZhi Yong Wu 27501c9805a3SStefan Hajnoczi if (qemu_in_coroutine()) { 27511c9805a3SStefan Hajnoczi /* Fast-path if already in coroutine context */ 27521c9805a3SStefan Hajnoczi bdrv_rw_co_entry(&rwco); 27531c9805a3SStefan Hajnoczi } else { 27542572b37aSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 27552572b37aSStefan Hajnoczi 27561c9805a3SStefan Hajnoczi co = qemu_coroutine_create(bdrv_rw_co_entry); 27571c9805a3SStefan Hajnoczi qemu_coroutine_enter(co, &rwco); 27581c9805a3SStefan Hajnoczi while (rwco.ret == NOT_DONE) { 27592572b37aSStefan Hajnoczi aio_poll(aio_context, true); 27601c9805a3SStefan Hajnoczi } 27611c9805a3SStefan Hajnoczi } 27621c9805a3SStefan Hajnoczi return rwco.ret; 2763e7a8a783SKevin Wolf } 2764e7a8a783SKevin Wolf 27658d3b1a2dSKevin Wolf /* 27668d3b1a2dSKevin Wolf * Process a synchronous request using coroutines 27678d3b1a2dSKevin Wolf */ 27688d3b1a2dSKevin Wolf static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf, 27694105eaaaSPeter Lieven int nb_sectors, bool is_write, BdrvRequestFlags flags) 27708d3b1a2dSKevin Wolf { 27718d3b1a2dSKevin Wolf QEMUIOVector qiov; 27728d3b1a2dSKevin Wolf struct iovec iov = { 27738d3b1a2dSKevin Wolf .iov_base = (void *)buf, 27748d3b1a2dSKevin Wolf .iov_len = nb_sectors * BDRV_SECTOR_SIZE, 27758d3b1a2dSKevin Wolf }; 27768d3b1a2dSKevin Wolf 2777da15ee51SKevin Wolf if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) { 2778da15ee51SKevin Wolf return -EINVAL; 2779da15ee51SKevin Wolf } 2780da15ee51SKevin Wolf 27818d3b1a2dSKevin Wolf qemu_iovec_init_external(&qiov, &iov, 1); 2782775aa8b6SKevin Wolf return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS, 2783775aa8b6SKevin Wolf &qiov, is_write, flags); 27848d3b1a2dSKevin Wolf } 27858d3b1a2dSKevin Wolf 27861c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */ 27871c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num, 27881c9805a3SStefan Hajnoczi uint8_t *buf, int nb_sectors) 27891c9805a3SStefan Hajnoczi { 27904105eaaaSPeter Lieven return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0); 279183f64091Sbellard } 2792fc01f7e7Sbellard 279307d27a44SMarkus Armbruster /* Just like bdrv_read(), but with I/O throttling temporarily disabled */ 279407d27a44SMarkus Armbruster int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num, 279507d27a44SMarkus Armbruster uint8_t *buf, int nb_sectors) 279607d27a44SMarkus Armbruster { 279707d27a44SMarkus Armbruster bool enabled; 279807d27a44SMarkus Armbruster int ret; 279907d27a44SMarkus Armbruster 280007d27a44SMarkus Armbruster enabled = bs->io_limits_enabled; 280107d27a44SMarkus Armbruster bs->io_limits_enabled = false; 28024e7395e8SPeter Lieven ret = bdrv_read(bs, sector_num, buf, nb_sectors); 280307d27a44SMarkus Armbruster bs->io_limits_enabled = enabled; 280407d27a44SMarkus Armbruster return ret; 280507d27a44SMarkus Armbruster } 280607d27a44SMarkus Armbruster 280719cb3738Sbellard /* Return < 0 if error. Important errors are: 280819cb3738Sbellard -EIO generic I/O error (may happen for all errors) 280919cb3738Sbellard -ENOMEDIUM No media inserted. 281019cb3738Sbellard -EINVAL Invalid sector number or nb_sectors 281119cb3738Sbellard -EACCES Trying to write a read-only device 281219cb3738Sbellard */ 2813fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num, 2814fc01f7e7Sbellard const uint8_t *buf, int nb_sectors) 2815fc01f7e7Sbellard { 28164105eaaaSPeter Lieven return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0); 281783f64091Sbellard } 281883f64091Sbellard 2819aa7bfbffSPeter Lieven int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num, 2820aa7bfbffSPeter Lieven int nb_sectors, BdrvRequestFlags flags) 28214105eaaaSPeter Lieven { 28224105eaaaSPeter Lieven return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true, 2823aa7bfbffSPeter Lieven BDRV_REQ_ZERO_WRITE | flags); 28248d3b1a2dSKevin Wolf } 28258d3b1a2dSKevin Wolf 2826d75cbb5eSPeter Lieven /* 2827d75cbb5eSPeter Lieven * Completely zero out a block device with the help of bdrv_write_zeroes. 2828d75cbb5eSPeter Lieven * The operation is sped up by checking the block status and only writing 2829d75cbb5eSPeter Lieven * zeroes to the device if they currently do not return zeroes. Optional 2830d75cbb5eSPeter Lieven * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP). 2831d75cbb5eSPeter Lieven * 2832d75cbb5eSPeter Lieven * Returns < 0 on error, 0 on success. For error codes see bdrv_write(). 2833d75cbb5eSPeter Lieven */ 2834d75cbb5eSPeter Lieven int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags) 2835d75cbb5eSPeter Lieven { 2836d32f7c10SMarkus Armbruster int64_t target_sectors, ret, nb_sectors, sector_num = 0; 2837d75cbb5eSPeter Lieven int n; 2838d75cbb5eSPeter Lieven 2839d32f7c10SMarkus Armbruster target_sectors = bdrv_nb_sectors(bs); 2840d32f7c10SMarkus Armbruster if (target_sectors < 0) { 2841d32f7c10SMarkus Armbruster return target_sectors; 28429ce10c0bSKevin Wolf } 28439ce10c0bSKevin Wolf 2844d75cbb5eSPeter Lieven for (;;) { 2845d32f7c10SMarkus Armbruster nb_sectors = target_sectors - sector_num; 2846d75cbb5eSPeter Lieven if (nb_sectors <= 0) { 2847d75cbb5eSPeter Lieven return 0; 2848d75cbb5eSPeter Lieven } 2849d75cbb5eSPeter Lieven if (nb_sectors > INT_MAX) { 2850d75cbb5eSPeter Lieven nb_sectors = INT_MAX; 2851d75cbb5eSPeter Lieven } 2852d75cbb5eSPeter Lieven ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n); 28533d94ce60SPeter Lieven if (ret < 0) { 28543d94ce60SPeter Lieven error_report("error getting block status at sector %" PRId64 ": %s", 28553d94ce60SPeter Lieven sector_num, strerror(-ret)); 28563d94ce60SPeter Lieven return ret; 28573d94ce60SPeter Lieven } 2858d75cbb5eSPeter Lieven if (ret & BDRV_BLOCK_ZERO) { 2859d75cbb5eSPeter Lieven sector_num += n; 2860d75cbb5eSPeter Lieven continue; 2861d75cbb5eSPeter Lieven } 2862d75cbb5eSPeter Lieven ret = bdrv_write_zeroes(bs, sector_num, n, flags); 2863d75cbb5eSPeter Lieven if (ret < 0) { 2864d75cbb5eSPeter Lieven error_report("error writing zeroes at sector %" PRId64 ": %s", 2865d75cbb5eSPeter Lieven sector_num, strerror(-ret)); 2866d75cbb5eSPeter Lieven return ret; 2867d75cbb5eSPeter Lieven } 2868d75cbb5eSPeter Lieven sector_num += n; 2869d75cbb5eSPeter Lieven } 2870d75cbb5eSPeter Lieven } 2871d75cbb5eSPeter Lieven 2872a3ef6571SKevin Wolf int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes) 287383f64091Sbellard { 2874a3ef6571SKevin Wolf QEMUIOVector qiov; 2875a3ef6571SKevin Wolf struct iovec iov = { 2876a3ef6571SKevin Wolf .iov_base = (void *)buf, 2877a3ef6571SKevin Wolf .iov_len = bytes, 2878a3ef6571SKevin Wolf }; 28799a8c4cceSKevin Wolf int ret; 288083f64091Sbellard 2881a3ef6571SKevin Wolf if (bytes < 0) { 2882a3ef6571SKevin Wolf return -EINVAL; 288383f64091Sbellard } 288483f64091Sbellard 2885a3ef6571SKevin Wolf qemu_iovec_init_external(&qiov, &iov, 1); 2886a3ef6571SKevin Wolf ret = bdrv_prwv_co(bs, offset, &qiov, false, 0); 2887a3ef6571SKevin Wolf if (ret < 0) { 28889a8c4cceSKevin Wolf return ret; 288983f64091Sbellard } 289083f64091Sbellard 2891a3ef6571SKevin Wolf return bytes; 289283f64091Sbellard } 289383f64091Sbellard 28948d3b1a2dSKevin Wolf int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov) 289583f64091Sbellard { 28969a8c4cceSKevin Wolf int ret; 289783f64091Sbellard 28988407d5d7SKevin Wolf ret = bdrv_prwv_co(bs, offset, qiov, true, 0); 28998d3b1a2dSKevin Wolf if (ret < 0) { 29009a8c4cceSKevin Wolf return ret; 29018d3b1a2dSKevin Wolf } 29028d3b1a2dSKevin Wolf 29038d3b1a2dSKevin Wolf return qiov->size; 29048d3b1a2dSKevin Wolf } 29058d3b1a2dSKevin Wolf 29068d3b1a2dSKevin Wolf int bdrv_pwrite(BlockDriverState *bs, int64_t offset, 29078407d5d7SKevin Wolf const void *buf, int bytes) 29088d3b1a2dSKevin Wolf { 29098d3b1a2dSKevin Wolf QEMUIOVector qiov; 29108d3b1a2dSKevin Wolf struct iovec iov = { 29118d3b1a2dSKevin Wolf .iov_base = (void *) buf, 29128407d5d7SKevin Wolf .iov_len = bytes, 29138d3b1a2dSKevin Wolf }; 29148d3b1a2dSKevin Wolf 29158407d5d7SKevin Wolf if (bytes < 0) { 29168407d5d7SKevin Wolf return -EINVAL; 29178407d5d7SKevin Wolf } 29188407d5d7SKevin Wolf 29198d3b1a2dSKevin Wolf qemu_iovec_init_external(&qiov, &iov, 1); 29208d3b1a2dSKevin Wolf return bdrv_pwritev(bs, offset, &qiov); 292183f64091Sbellard } 292283f64091Sbellard 2923f08145feSKevin Wolf /* 2924f08145feSKevin Wolf * Writes to the file and ensures that no writes are reordered across this 2925f08145feSKevin Wolf * request (acts as a barrier) 2926f08145feSKevin Wolf * 2927f08145feSKevin Wolf * Returns 0 on success, -errno in error cases. 2928f08145feSKevin Wolf */ 2929f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset, 2930f08145feSKevin Wolf const void *buf, int count) 2931f08145feSKevin Wolf { 2932f08145feSKevin Wolf int ret; 2933f08145feSKevin Wolf 2934f08145feSKevin Wolf ret = bdrv_pwrite(bs, offset, buf, count); 2935f08145feSKevin Wolf if (ret < 0) { 2936f08145feSKevin Wolf return ret; 2937f08145feSKevin Wolf } 2938f08145feSKevin Wolf 2939f05fa4adSPaolo Bonzini /* No flush needed for cache modes that already do it */ 2940f05fa4adSPaolo Bonzini if (bs->enable_write_cache) { 2941f08145feSKevin Wolf bdrv_flush(bs); 2942f08145feSKevin Wolf } 2943f08145feSKevin Wolf 2944f08145feSKevin Wolf return 0; 2945f08145feSKevin Wolf } 2946f08145feSKevin Wolf 2947470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs, 2948ab185921SStefan Hajnoczi int64_t sector_num, int nb_sectors, QEMUIOVector *qiov) 2949ab185921SStefan Hajnoczi { 2950ab185921SStefan Hajnoczi /* Perform I/O through a temporary buffer so that users who scribble over 2951ab185921SStefan Hajnoczi * their read buffer while the operation is in progress do not end up 2952ab185921SStefan Hajnoczi * modifying the image file. This is critical for zero-copy guest I/O 2953ab185921SStefan Hajnoczi * where anything might happen inside guest memory. 2954ab185921SStefan Hajnoczi */ 2955ab185921SStefan Hajnoczi void *bounce_buffer; 2956ab185921SStefan Hajnoczi 295779c053bdSStefan Hajnoczi BlockDriver *drv = bs->drv; 2958ab185921SStefan Hajnoczi struct iovec iov; 2959ab185921SStefan Hajnoczi QEMUIOVector bounce_qiov; 2960ab185921SStefan Hajnoczi int64_t cluster_sector_num; 2961ab185921SStefan Hajnoczi int cluster_nb_sectors; 2962ab185921SStefan Hajnoczi size_t skip_bytes; 2963ab185921SStefan Hajnoczi int ret; 2964ab185921SStefan Hajnoczi 2965ab185921SStefan Hajnoczi /* Cover entire cluster so no additional backing file I/O is required when 2966ab185921SStefan Hajnoczi * allocating cluster in the image file. 2967ab185921SStefan Hajnoczi */ 2968343bded4SPaolo Bonzini bdrv_round_to_clusters(bs, sector_num, nb_sectors, 2969ab185921SStefan Hajnoczi &cluster_sector_num, &cluster_nb_sectors); 2970ab185921SStefan Hajnoczi 2971470c0504SStefan Hajnoczi trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, 2972ab185921SStefan Hajnoczi cluster_sector_num, cluster_nb_sectors); 2973ab185921SStefan Hajnoczi 2974ab185921SStefan Hajnoczi iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE; 2975ab185921SStefan Hajnoczi iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len); 2976ab185921SStefan Hajnoczi qemu_iovec_init_external(&bounce_qiov, &iov, 1); 2977ab185921SStefan Hajnoczi 297879c053bdSStefan Hajnoczi ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors, 2979ab185921SStefan Hajnoczi &bounce_qiov); 2980ab185921SStefan Hajnoczi if (ret < 0) { 2981ab185921SStefan Hajnoczi goto err; 2982ab185921SStefan Hajnoczi } 2983ab185921SStefan Hajnoczi 298479c053bdSStefan Hajnoczi if (drv->bdrv_co_write_zeroes && 298579c053bdSStefan Hajnoczi buffer_is_zero(bounce_buffer, iov.iov_len)) { 2986621f0589SKevin Wolf ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num, 2987aa7bfbffSPeter Lieven cluster_nb_sectors, 0); 298879c053bdSStefan Hajnoczi } else { 2989f05fa4adSPaolo Bonzini /* This does not change the data on the disk, it is not necessary 2990f05fa4adSPaolo Bonzini * to flush even in cache=writethrough mode. 2991f05fa4adSPaolo Bonzini */ 299279c053bdSStefan Hajnoczi ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors, 2993ab185921SStefan Hajnoczi &bounce_qiov); 299479c053bdSStefan Hajnoczi } 299579c053bdSStefan Hajnoczi 2996ab185921SStefan Hajnoczi if (ret < 0) { 2997ab185921SStefan Hajnoczi /* It might be okay to ignore write errors for guest requests. If this 2998ab185921SStefan Hajnoczi * is a deliberate copy-on-read then we don't want to ignore the error. 2999ab185921SStefan Hajnoczi * Simply report it in all cases. 3000ab185921SStefan Hajnoczi */ 3001ab185921SStefan Hajnoczi goto err; 3002ab185921SStefan Hajnoczi } 3003ab185921SStefan Hajnoczi 3004ab185921SStefan Hajnoczi skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE; 300503396148SMichael Tokarev qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes, 3006ab185921SStefan Hajnoczi nb_sectors * BDRV_SECTOR_SIZE); 3007ab185921SStefan Hajnoczi 3008ab185921SStefan Hajnoczi err: 3009ab185921SStefan Hajnoczi qemu_vfree(bounce_buffer); 3010ab185921SStefan Hajnoczi return ret; 3011ab185921SStefan Hajnoczi } 3012ab185921SStefan Hajnoczi 3013c5fbe571SStefan Hajnoczi /* 3014d0c7f642SKevin Wolf * Forwards an already correctly aligned request to the BlockDriver. This 3015d0c7f642SKevin Wolf * handles copy on read and zeroing after EOF; any other features must be 3016d0c7f642SKevin Wolf * implemented by the caller. 3017c5fbe571SStefan Hajnoczi */ 3018d0c7f642SKevin Wolf static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs, 301965afd211SKevin Wolf BdrvTrackedRequest *req, int64_t offset, unsigned int bytes, 3020ec746e10SKevin Wolf int64_t align, QEMUIOVector *qiov, int flags) 3021da1fa91dSKevin Wolf { 3022da1fa91dSKevin Wolf BlockDriver *drv = bs->drv; 3023dbffbdcfSStefan Hajnoczi int ret; 3024da1fa91dSKevin Wolf 3025d0c7f642SKevin Wolf int64_t sector_num = offset >> BDRV_SECTOR_BITS; 3026d0c7f642SKevin Wolf unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS; 3027da1fa91dSKevin Wolf 3028d0c7f642SKevin Wolf assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0); 3029d0c7f642SKevin Wolf assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0); 30308eb029c2SKevin Wolf assert(!qiov || bytes == qiov->size); 3031d0c7f642SKevin Wolf 3032d0c7f642SKevin Wolf /* Handle Copy on Read and associated serialisation */ 3033470c0504SStefan Hajnoczi if (flags & BDRV_REQ_COPY_ON_READ) { 30347327145fSKevin Wolf /* If we touch the same cluster it counts as an overlap. This 30357327145fSKevin Wolf * guarantees that allocating writes will be serialized and not race 30367327145fSKevin Wolf * with each other for the same cluster. For example, in copy-on-read 30377327145fSKevin Wolf * it ensures that the CoR read and write operations are atomic and 30387327145fSKevin Wolf * guest writes cannot interleave between them. */ 30397327145fSKevin Wolf mark_request_serialising(req, bdrv_get_cluster_size(bs)); 3040470c0504SStefan Hajnoczi } 3041470c0504SStefan Hajnoczi 30422dbafdc0SKevin Wolf wait_serialising_requests(req); 3043f4658285SStefan Hajnoczi 3044470c0504SStefan Hajnoczi if (flags & BDRV_REQ_COPY_ON_READ) { 3045ab185921SStefan Hajnoczi int pnum; 3046ab185921SStefan Hajnoczi 3047bdad13b9SPaolo Bonzini ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum); 3048ab185921SStefan Hajnoczi if (ret < 0) { 3049ab185921SStefan Hajnoczi goto out; 3050ab185921SStefan Hajnoczi } 3051ab185921SStefan Hajnoczi 3052ab185921SStefan Hajnoczi if (!ret || pnum != nb_sectors) { 3053470c0504SStefan Hajnoczi ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov); 3054ab185921SStefan Hajnoczi goto out; 3055ab185921SStefan Hajnoczi } 3056ab185921SStefan Hajnoczi } 3057ab185921SStefan Hajnoczi 3058d0c7f642SKevin Wolf /* Forward the request to the BlockDriver */ 3059893a8f62SMORITA Kazutaka if (!(bs->zero_beyond_eof && bs->growable)) { 3060dbffbdcfSStefan Hajnoczi ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov); 3061893a8f62SMORITA Kazutaka } else { 3062893a8f62SMORITA Kazutaka /* Read zeros after EOF of growable BDSes */ 30634049082cSMarkus Armbruster int64_t total_sectors, max_nb_sectors; 3064893a8f62SMORITA Kazutaka 30654049082cSMarkus Armbruster total_sectors = bdrv_nb_sectors(bs); 30664049082cSMarkus Armbruster if (total_sectors < 0) { 30674049082cSMarkus Armbruster ret = total_sectors; 3068893a8f62SMORITA Kazutaka goto out; 3069893a8f62SMORITA Kazutaka } 3070893a8f62SMORITA Kazutaka 30715f5bcd80SKevin Wolf max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num), 30725f5bcd80SKevin Wolf align >> BDRV_SECTOR_BITS); 3073893a8f62SMORITA Kazutaka if (max_nb_sectors > 0) { 307433f461e0SKevin Wolf QEMUIOVector local_qiov; 307533f461e0SKevin Wolf size_t local_sectors; 307633f461e0SKevin Wolf 307733f461e0SKevin Wolf max_nb_sectors = MIN(max_nb_sectors, SIZE_MAX / BDRV_SECTOR_BITS); 307833f461e0SKevin Wolf local_sectors = MIN(max_nb_sectors, nb_sectors); 307933f461e0SKevin Wolf 308033f461e0SKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov); 308133f461e0SKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, 308233f461e0SKevin Wolf local_sectors * BDRV_SECTOR_SIZE); 308333f461e0SKevin Wolf 308433f461e0SKevin Wolf ret = drv->bdrv_co_readv(bs, sector_num, local_sectors, 308533f461e0SKevin Wolf &local_qiov); 308633f461e0SKevin Wolf 308733f461e0SKevin Wolf qemu_iovec_destroy(&local_qiov); 3088893a8f62SMORITA Kazutaka } else { 3089893a8f62SMORITA Kazutaka ret = 0; 3090893a8f62SMORITA Kazutaka } 3091893a8f62SMORITA Kazutaka 3092893a8f62SMORITA Kazutaka /* Reading beyond end of file is supposed to produce zeroes */ 3093893a8f62SMORITA Kazutaka if (ret == 0 && total_sectors < sector_num + nb_sectors) { 3094893a8f62SMORITA Kazutaka uint64_t offset = MAX(0, total_sectors - sector_num); 3095893a8f62SMORITA Kazutaka uint64_t bytes = (sector_num + nb_sectors - offset) * 3096893a8f62SMORITA Kazutaka BDRV_SECTOR_SIZE; 3097893a8f62SMORITA Kazutaka qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes); 3098893a8f62SMORITA Kazutaka } 3099893a8f62SMORITA Kazutaka } 3100ab185921SStefan Hajnoczi 3101ab185921SStefan Hajnoczi out: 3102dbffbdcfSStefan Hajnoczi return ret; 3103da1fa91dSKevin Wolf } 3104da1fa91dSKevin Wolf 3105d0c7f642SKevin Wolf /* 3106d0c7f642SKevin Wolf * Handle a read request in coroutine context 3107d0c7f642SKevin Wolf */ 31081b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs, 31091b0288aeSKevin Wolf int64_t offset, unsigned int bytes, QEMUIOVector *qiov, 3110d0c7f642SKevin Wolf BdrvRequestFlags flags) 3111d0c7f642SKevin Wolf { 3112d0c7f642SKevin Wolf BlockDriver *drv = bs->drv; 311365afd211SKevin Wolf BdrvTrackedRequest req; 311465afd211SKevin Wolf 31151b0288aeSKevin Wolf /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */ 31161b0288aeSKevin Wolf uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment); 31171b0288aeSKevin Wolf uint8_t *head_buf = NULL; 31181b0288aeSKevin Wolf uint8_t *tail_buf = NULL; 31191b0288aeSKevin Wolf QEMUIOVector local_qiov; 31201b0288aeSKevin Wolf bool use_local_qiov = false; 3121d0c7f642SKevin Wolf int ret; 3122d0c7f642SKevin Wolf 3123d0c7f642SKevin Wolf if (!drv) { 3124d0c7f642SKevin Wolf return -ENOMEDIUM; 3125d0c7f642SKevin Wolf } 31261b0288aeSKevin Wolf if (bdrv_check_byte_request(bs, offset, bytes)) { 3127d0c7f642SKevin Wolf return -EIO; 3128d0c7f642SKevin Wolf } 3129d0c7f642SKevin Wolf 3130d0c7f642SKevin Wolf if (bs->copy_on_read) { 3131d0c7f642SKevin Wolf flags |= BDRV_REQ_COPY_ON_READ; 3132d0c7f642SKevin Wolf } 3133d0c7f642SKevin Wolf 3134d0c7f642SKevin Wolf /* throttling disk I/O */ 3135d0c7f642SKevin Wolf if (bs->io_limits_enabled) { 3136d5103588SKevin Wolf bdrv_io_limits_intercept(bs, bytes, false); 3137d0c7f642SKevin Wolf } 3138d0c7f642SKevin Wolf 31391b0288aeSKevin Wolf /* Align read if necessary by padding qiov */ 31401b0288aeSKevin Wolf if (offset & (align - 1)) { 31411b0288aeSKevin Wolf head_buf = qemu_blockalign(bs, align); 31421b0288aeSKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov + 2); 31431b0288aeSKevin Wolf qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1)); 31441b0288aeSKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 31451b0288aeSKevin Wolf use_local_qiov = true; 31461b0288aeSKevin Wolf 31471b0288aeSKevin Wolf bytes += offset & (align - 1); 31481b0288aeSKevin Wolf offset = offset & ~(align - 1); 31491b0288aeSKevin Wolf } 31501b0288aeSKevin Wolf 31511b0288aeSKevin Wolf if ((offset + bytes) & (align - 1)) { 31521b0288aeSKevin Wolf if (!use_local_qiov) { 31531b0288aeSKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov + 1); 31541b0288aeSKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 31551b0288aeSKevin Wolf use_local_qiov = true; 31561b0288aeSKevin Wolf } 31571b0288aeSKevin Wolf tail_buf = qemu_blockalign(bs, align); 31581b0288aeSKevin Wolf qemu_iovec_add(&local_qiov, tail_buf, 31591b0288aeSKevin Wolf align - ((offset + bytes) & (align - 1))); 31601b0288aeSKevin Wolf 31611b0288aeSKevin Wolf bytes = ROUND_UP(bytes, align); 31621b0288aeSKevin Wolf } 31631b0288aeSKevin Wolf 316465afd211SKevin Wolf tracked_request_begin(&req, bs, offset, bytes, false); 3165ec746e10SKevin Wolf ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align, 31661b0288aeSKevin Wolf use_local_qiov ? &local_qiov : qiov, 31671b0288aeSKevin Wolf flags); 316865afd211SKevin Wolf tracked_request_end(&req); 31691b0288aeSKevin Wolf 31701b0288aeSKevin Wolf if (use_local_qiov) { 31711b0288aeSKevin Wolf qemu_iovec_destroy(&local_qiov); 31721b0288aeSKevin Wolf qemu_vfree(head_buf); 31731b0288aeSKevin Wolf qemu_vfree(tail_buf); 31741b0288aeSKevin Wolf } 31751b0288aeSKevin Wolf 3176d0c7f642SKevin Wolf return ret; 3177d0c7f642SKevin Wolf } 3178d0c7f642SKevin Wolf 31791b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs, 31801b0288aeSKevin Wolf int64_t sector_num, int nb_sectors, QEMUIOVector *qiov, 31811b0288aeSKevin Wolf BdrvRequestFlags flags) 31821b0288aeSKevin Wolf { 31831b0288aeSKevin Wolf if (nb_sectors < 0 || nb_sectors > (UINT_MAX >> BDRV_SECTOR_BITS)) { 31841b0288aeSKevin Wolf return -EINVAL; 31851b0288aeSKevin Wolf } 31861b0288aeSKevin Wolf 31871b0288aeSKevin Wolf return bdrv_co_do_preadv(bs, sector_num << BDRV_SECTOR_BITS, 31881b0288aeSKevin Wolf nb_sectors << BDRV_SECTOR_BITS, qiov, flags); 31891b0288aeSKevin Wolf } 31901b0288aeSKevin Wolf 3191c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num, 3192da1fa91dSKevin Wolf int nb_sectors, QEMUIOVector *qiov) 3193da1fa91dSKevin Wolf { 3194c5fbe571SStefan Hajnoczi trace_bdrv_co_readv(bs, sector_num, nb_sectors); 3195da1fa91dSKevin Wolf 3196470c0504SStefan Hajnoczi return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0); 3197470c0504SStefan Hajnoczi } 3198470c0504SStefan Hajnoczi 3199470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs, 3200470c0504SStefan Hajnoczi int64_t sector_num, int nb_sectors, QEMUIOVector *qiov) 3201470c0504SStefan Hajnoczi { 3202470c0504SStefan Hajnoczi trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors); 3203470c0504SStefan Hajnoczi 3204470c0504SStefan Hajnoczi return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 3205470c0504SStefan Hajnoczi BDRV_REQ_COPY_ON_READ); 3206c5fbe571SStefan Hajnoczi } 3207c5fbe571SStefan Hajnoczi 3208c31cb707SPeter Lieven /* if no limit is specified in the BlockLimits use a default 3209c31cb707SPeter Lieven * of 32768 512-byte sectors (16 MiB) per request. 3210c31cb707SPeter Lieven */ 3211c31cb707SPeter Lieven #define MAX_WRITE_ZEROES_DEFAULT 32768 3212c31cb707SPeter Lieven 3213f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs, 3214aa7bfbffSPeter Lieven int64_t sector_num, int nb_sectors, BdrvRequestFlags flags) 3215f08f2ddaSStefan Hajnoczi { 3216f08f2ddaSStefan Hajnoczi BlockDriver *drv = bs->drv; 3217f08f2ddaSStefan Hajnoczi QEMUIOVector qiov; 3218c31cb707SPeter Lieven struct iovec iov = {0}; 3219c31cb707SPeter Lieven int ret = 0; 3220f08f2ddaSStefan Hajnoczi 3221c31cb707SPeter Lieven int max_write_zeroes = bs->bl.max_write_zeroes ? 3222c31cb707SPeter Lieven bs->bl.max_write_zeroes : MAX_WRITE_ZEROES_DEFAULT; 3223621f0589SKevin Wolf 3224c31cb707SPeter Lieven while (nb_sectors > 0 && !ret) { 3225c31cb707SPeter Lieven int num = nb_sectors; 3226c31cb707SPeter Lieven 3227b8d71c09SPaolo Bonzini /* Align request. Block drivers can expect the "bulk" of the request 3228b8d71c09SPaolo Bonzini * to be aligned. 3229b8d71c09SPaolo Bonzini */ 3230b8d71c09SPaolo Bonzini if (bs->bl.write_zeroes_alignment 3231b8d71c09SPaolo Bonzini && num > bs->bl.write_zeroes_alignment) { 3232b8d71c09SPaolo Bonzini if (sector_num % bs->bl.write_zeroes_alignment != 0) { 3233b8d71c09SPaolo Bonzini /* Make a small request up to the first aligned sector. */ 3234c31cb707SPeter Lieven num = bs->bl.write_zeroes_alignment; 3235c31cb707SPeter Lieven num -= sector_num % bs->bl.write_zeroes_alignment; 3236b8d71c09SPaolo Bonzini } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) { 3237b8d71c09SPaolo Bonzini /* Shorten the request to the last aligned sector. num cannot 3238b8d71c09SPaolo Bonzini * underflow because num > bs->bl.write_zeroes_alignment. 3239b8d71c09SPaolo Bonzini */ 3240b8d71c09SPaolo Bonzini num -= (sector_num + num) % bs->bl.write_zeroes_alignment; 3241b8d71c09SPaolo Bonzini } 3242c31cb707SPeter Lieven } 3243c31cb707SPeter Lieven 3244c31cb707SPeter Lieven /* limit request size */ 3245c31cb707SPeter Lieven if (num > max_write_zeroes) { 3246c31cb707SPeter Lieven num = max_write_zeroes; 3247c31cb707SPeter Lieven } 3248c31cb707SPeter Lieven 3249c31cb707SPeter Lieven ret = -ENOTSUP; 3250f08f2ddaSStefan Hajnoczi /* First try the efficient write zeroes operation */ 3251f08f2ddaSStefan Hajnoczi if (drv->bdrv_co_write_zeroes) { 3252c31cb707SPeter Lieven ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags); 3253f08f2ddaSStefan Hajnoczi } 3254f08f2ddaSStefan Hajnoczi 3255c31cb707SPeter Lieven if (ret == -ENOTSUP) { 3256f08f2ddaSStefan Hajnoczi /* Fall back to bounce buffer if write zeroes is unsupported */ 3257c31cb707SPeter Lieven iov.iov_len = num * BDRV_SECTOR_SIZE; 3258c31cb707SPeter Lieven if (iov.iov_base == NULL) { 3259b8d71c09SPaolo Bonzini iov.iov_base = qemu_blockalign(bs, num * BDRV_SECTOR_SIZE); 3260b8d71c09SPaolo Bonzini memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE); 3261c31cb707SPeter Lieven } 3262f08f2ddaSStefan Hajnoczi qemu_iovec_init_external(&qiov, &iov, 1); 3263f08f2ddaSStefan Hajnoczi 3264c31cb707SPeter Lieven ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov); 3265b8d71c09SPaolo Bonzini 3266b8d71c09SPaolo Bonzini /* Keep bounce buffer around if it is big enough for all 3267b8d71c09SPaolo Bonzini * all future requests. 3268b8d71c09SPaolo Bonzini */ 3269b8d71c09SPaolo Bonzini if (num < max_write_zeroes) { 3270b8d71c09SPaolo Bonzini qemu_vfree(iov.iov_base); 3271b8d71c09SPaolo Bonzini iov.iov_base = NULL; 3272b8d71c09SPaolo Bonzini } 3273c31cb707SPeter Lieven } 3274c31cb707SPeter Lieven 3275c31cb707SPeter Lieven sector_num += num; 3276c31cb707SPeter Lieven nb_sectors -= num; 3277c31cb707SPeter Lieven } 3278f08f2ddaSStefan Hajnoczi 3279f08f2ddaSStefan Hajnoczi qemu_vfree(iov.iov_base); 3280f08f2ddaSStefan Hajnoczi return ret; 3281f08f2ddaSStefan Hajnoczi } 3282f08f2ddaSStefan Hajnoczi 3283c5fbe571SStefan Hajnoczi /* 3284b404f720SKevin Wolf * Forwards an already correctly aligned write request to the BlockDriver. 3285c5fbe571SStefan Hajnoczi */ 3286b404f720SKevin Wolf static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs, 328765afd211SKevin Wolf BdrvTrackedRequest *req, int64_t offset, unsigned int bytes, 328865afd211SKevin Wolf QEMUIOVector *qiov, int flags) 3289c5fbe571SStefan Hajnoczi { 3290c5fbe571SStefan Hajnoczi BlockDriver *drv = bs->drv; 329128de2dcdSKevin Wolf bool waited; 32926b7cb247SStefan Hajnoczi int ret; 3293da1fa91dSKevin Wolf 3294b404f720SKevin Wolf int64_t sector_num = offset >> BDRV_SECTOR_BITS; 3295b404f720SKevin Wolf unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS; 3296da1fa91dSKevin Wolf 3297b404f720SKevin Wolf assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0); 3298b404f720SKevin Wolf assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0); 32998eb029c2SKevin Wolf assert(!qiov || bytes == qiov->size); 3300cc0681c4SBenoît Canet 330128de2dcdSKevin Wolf waited = wait_serialising_requests(req); 330228de2dcdSKevin Wolf assert(!waited || !req->serialising); 3303af91f9a7SKevin Wolf assert(req->overlap_offset <= offset); 3304af91f9a7SKevin Wolf assert(offset + bytes <= req->overlap_offset + req->overlap_bytes); 3305244eadefSKevin Wolf 330665afd211SKevin Wolf ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req); 3307d616b224SStefan Hajnoczi 3308465bee1dSPeter Lieven if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF && 3309465bee1dSPeter Lieven !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_write_zeroes && 3310465bee1dSPeter Lieven qemu_iovec_is_zero(qiov)) { 3311465bee1dSPeter Lieven flags |= BDRV_REQ_ZERO_WRITE; 3312465bee1dSPeter Lieven if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) { 3313465bee1dSPeter Lieven flags |= BDRV_REQ_MAY_UNMAP; 3314465bee1dSPeter Lieven } 3315465bee1dSPeter Lieven } 3316465bee1dSPeter Lieven 3317d616b224SStefan Hajnoczi if (ret < 0) { 3318d616b224SStefan Hajnoczi /* Do nothing, write notifier decided to fail this request */ 3319d616b224SStefan Hajnoczi } else if (flags & BDRV_REQ_ZERO_WRITE) { 33209e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_ZERO); 3321aa7bfbffSPeter Lieven ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags); 3322f08f2ddaSStefan Hajnoczi } else { 33239e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV); 33246b7cb247SStefan Hajnoczi ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov); 3325f08f2ddaSStefan Hajnoczi } 33269e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_DONE); 33276b7cb247SStefan Hajnoczi 3328f05fa4adSPaolo Bonzini if (ret == 0 && !bs->enable_write_cache) { 3329f05fa4adSPaolo Bonzini ret = bdrv_co_flush(bs); 3330f05fa4adSPaolo Bonzini } 3331f05fa4adSPaolo Bonzini 33321755da16SPaolo Bonzini bdrv_set_dirty(bs, sector_num, nb_sectors); 3333da1fa91dSKevin Wolf 3334da1fa91dSKevin Wolf if (bs->wr_highest_sector < sector_num + nb_sectors - 1) { 3335da1fa91dSKevin Wolf bs->wr_highest_sector = sector_num + nb_sectors - 1; 3336da1fa91dSKevin Wolf } 3337df2a6f29SPaolo Bonzini if (bs->growable && ret >= 0) { 3338df2a6f29SPaolo Bonzini bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors); 3339df2a6f29SPaolo Bonzini } 3340da1fa91dSKevin Wolf 33416b7cb247SStefan Hajnoczi return ret; 3342da1fa91dSKevin Wolf } 3343da1fa91dSKevin Wolf 3344b404f720SKevin Wolf /* 3345b404f720SKevin Wolf * Handle a write request in coroutine context 3346b404f720SKevin Wolf */ 33476601553eSKevin Wolf static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs, 33486601553eSKevin Wolf int64_t offset, unsigned int bytes, QEMUIOVector *qiov, 3349b404f720SKevin Wolf BdrvRequestFlags flags) 3350b404f720SKevin Wolf { 335165afd211SKevin Wolf BdrvTrackedRequest req; 33523b8242e0SKevin Wolf /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */ 33533b8242e0SKevin Wolf uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment); 33543b8242e0SKevin Wolf uint8_t *head_buf = NULL; 33553b8242e0SKevin Wolf uint8_t *tail_buf = NULL; 33563b8242e0SKevin Wolf QEMUIOVector local_qiov; 33573b8242e0SKevin Wolf bool use_local_qiov = false; 3358b404f720SKevin Wolf int ret; 3359b404f720SKevin Wolf 3360b404f720SKevin Wolf if (!bs->drv) { 3361b404f720SKevin Wolf return -ENOMEDIUM; 3362b404f720SKevin Wolf } 3363b404f720SKevin Wolf if (bs->read_only) { 3364b404f720SKevin Wolf return -EACCES; 3365b404f720SKevin Wolf } 33666601553eSKevin Wolf if (bdrv_check_byte_request(bs, offset, bytes)) { 3367b404f720SKevin Wolf return -EIO; 3368b404f720SKevin Wolf } 3369b404f720SKevin Wolf 3370b404f720SKevin Wolf /* throttling disk I/O */ 3371b404f720SKevin Wolf if (bs->io_limits_enabled) { 3372d5103588SKevin Wolf bdrv_io_limits_intercept(bs, bytes, true); 3373b404f720SKevin Wolf } 3374b404f720SKevin Wolf 33753b8242e0SKevin Wolf /* 33763b8242e0SKevin Wolf * Align write if necessary by performing a read-modify-write cycle. 33773b8242e0SKevin Wolf * Pad qiov with the read parts and be sure to have a tracked request not 33783b8242e0SKevin Wolf * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle. 33793b8242e0SKevin Wolf */ 338065afd211SKevin Wolf tracked_request_begin(&req, bs, offset, bytes, true); 33813b8242e0SKevin Wolf 33823b8242e0SKevin Wolf if (offset & (align - 1)) { 33833b8242e0SKevin Wolf QEMUIOVector head_qiov; 33843b8242e0SKevin Wolf struct iovec head_iov; 33853b8242e0SKevin Wolf 33863b8242e0SKevin Wolf mark_request_serialising(&req, align); 33873b8242e0SKevin Wolf wait_serialising_requests(&req); 33883b8242e0SKevin Wolf 33893b8242e0SKevin Wolf head_buf = qemu_blockalign(bs, align); 33903b8242e0SKevin Wolf head_iov = (struct iovec) { 33913b8242e0SKevin Wolf .iov_base = head_buf, 33923b8242e0SKevin Wolf .iov_len = align, 33933b8242e0SKevin Wolf }; 33943b8242e0SKevin Wolf qemu_iovec_init_external(&head_qiov, &head_iov, 1); 33953b8242e0SKevin Wolf 33969e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_HEAD); 33973b8242e0SKevin Wolf ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align, 33983b8242e0SKevin Wolf align, &head_qiov, 0); 33993b8242e0SKevin Wolf if (ret < 0) { 34003b8242e0SKevin Wolf goto fail; 34013b8242e0SKevin Wolf } 34029e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD); 34033b8242e0SKevin Wolf 34043b8242e0SKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov + 2); 34053b8242e0SKevin Wolf qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1)); 34063b8242e0SKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 34073b8242e0SKevin Wolf use_local_qiov = true; 34083b8242e0SKevin Wolf 34093b8242e0SKevin Wolf bytes += offset & (align - 1); 34103b8242e0SKevin Wolf offset = offset & ~(align - 1); 34113b8242e0SKevin Wolf } 34123b8242e0SKevin Wolf 34133b8242e0SKevin Wolf if ((offset + bytes) & (align - 1)) { 34143b8242e0SKevin Wolf QEMUIOVector tail_qiov; 34153b8242e0SKevin Wolf struct iovec tail_iov; 34163b8242e0SKevin Wolf size_t tail_bytes; 341728de2dcdSKevin Wolf bool waited; 34183b8242e0SKevin Wolf 34193b8242e0SKevin Wolf mark_request_serialising(&req, align); 342028de2dcdSKevin Wolf waited = wait_serialising_requests(&req); 342128de2dcdSKevin Wolf assert(!waited || !use_local_qiov); 34223b8242e0SKevin Wolf 34233b8242e0SKevin Wolf tail_buf = qemu_blockalign(bs, align); 34243b8242e0SKevin Wolf tail_iov = (struct iovec) { 34253b8242e0SKevin Wolf .iov_base = tail_buf, 34263b8242e0SKevin Wolf .iov_len = align, 34273b8242e0SKevin Wolf }; 34283b8242e0SKevin Wolf qemu_iovec_init_external(&tail_qiov, &tail_iov, 1); 34293b8242e0SKevin Wolf 34309e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_TAIL); 34313b8242e0SKevin Wolf ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align, 34323b8242e0SKevin Wolf align, &tail_qiov, 0); 34333b8242e0SKevin Wolf if (ret < 0) { 34343b8242e0SKevin Wolf goto fail; 34353b8242e0SKevin Wolf } 34369e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL); 34373b8242e0SKevin Wolf 34383b8242e0SKevin Wolf if (!use_local_qiov) { 34393b8242e0SKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov + 1); 34403b8242e0SKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 34413b8242e0SKevin Wolf use_local_qiov = true; 34423b8242e0SKevin Wolf } 34433b8242e0SKevin Wolf 34443b8242e0SKevin Wolf tail_bytes = (offset + bytes) & (align - 1); 34453b8242e0SKevin Wolf qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes); 34463b8242e0SKevin Wolf 34473b8242e0SKevin Wolf bytes = ROUND_UP(bytes, align); 34483b8242e0SKevin Wolf } 34493b8242e0SKevin Wolf 34503b8242e0SKevin Wolf ret = bdrv_aligned_pwritev(bs, &req, offset, bytes, 34513b8242e0SKevin Wolf use_local_qiov ? &local_qiov : qiov, 34523b8242e0SKevin Wolf flags); 34533b8242e0SKevin Wolf 34543b8242e0SKevin Wolf fail: 345565afd211SKevin Wolf tracked_request_end(&req); 3456b404f720SKevin Wolf 34573b8242e0SKevin Wolf if (use_local_qiov) { 34583b8242e0SKevin Wolf qemu_iovec_destroy(&local_qiov); 345999c4a85cSKevin Wolf } 34603b8242e0SKevin Wolf qemu_vfree(head_buf); 34613b8242e0SKevin Wolf qemu_vfree(tail_buf); 34623b8242e0SKevin Wolf 3463b404f720SKevin Wolf return ret; 3464b404f720SKevin Wolf } 3465b404f720SKevin Wolf 34666601553eSKevin Wolf static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs, 34676601553eSKevin Wolf int64_t sector_num, int nb_sectors, QEMUIOVector *qiov, 34686601553eSKevin Wolf BdrvRequestFlags flags) 34696601553eSKevin Wolf { 34706601553eSKevin Wolf if (nb_sectors < 0 || nb_sectors > (INT_MAX >> BDRV_SECTOR_BITS)) { 34716601553eSKevin Wolf return -EINVAL; 34726601553eSKevin Wolf } 34736601553eSKevin Wolf 34746601553eSKevin Wolf return bdrv_co_do_pwritev(bs, sector_num << BDRV_SECTOR_BITS, 34756601553eSKevin Wolf nb_sectors << BDRV_SECTOR_BITS, qiov, flags); 34766601553eSKevin Wolf } 34776601553eSKevin Wolf 3478c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num, 3479c5fbe571SStefan Hajnoczi int nb_sectors, QEMUIOVector *qiov) 3480c5fbe571SStefan Hajnoczi { 3481c5fbe571SStefan Hajnoczi trace_bdrv_co_writev(bs, sector_num, nb_sectors); 3482c5fbe571SStefan Hajnoczi 3483f08f2ddaSStefan Hajnoczi return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0); 3484f08f2ddaSStefan Hajnoczi } 3485f08f2ddaSStefan Hajnoczi 3486f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs, 3487aa7bfbffSPeter Lieven int64_t sector_num, int nb_sectors, 3488aa7bfbffSPeter Lieven BdrvRequestFlags flags) 3489f08f2ddaSStefan Hajnoczi { 349094d6ff21SPaolo Bonzini trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags); 3491f08f2ddaSStefan Hajnoczi 3492d32f35cbSPeter Lieven if (!(bs->open_flags & BDRV_O_UNMAP)) { 3493d32f35cbSPeter Lieven flags &= ~BDRV_REQ_MAY_UNMAP; 3494d32f35cbSPeter Lieven } 3495d32f35cbSPeter Lieven 3496f08f2ddaSStefan Hajnoczi return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL, 3497aa7bfbffSPeter Lieven BDRV_REQ_ZERO_WRITE | flags); 3498c5fbe571SStefan Hajnoczi } 3499c5fbe571SStefan Hajnoczi 350083f64091Sbellard /** 350183f64091Sbellard * Truncate file to 'offset' bytes (needed only for file protocols) 350283f64091Sbellard */ 350383f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset) 350483f64091Sbellard { 350583f64091Sbellard BlockDriver *drv = bs->drv; 350651762288SStefan Hajnoczi int ret; 350783f64091Sbellard if (!drv) 350819cb3738Sbellard return -ENOMEDIUM; 350983f64091Sbellard if (!drv->bdrv_truncate) 351083f64091Sbellard return -ENOTSUP; 351159f2689dSNaphtali Sprei if (bs->read_only) 351259f2689dSNaphtali Sprei return -EACCES; 35139c75e168SJeff Cody 351451762288SStefan Hajnoczi ret = drv->bdrv_truncate(bs, offset); 351551762288SStefan Hajnoczi if (ret == 0) { 351651762288SStefan Hajnoczi ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS); 3517145feb17SMarkus Armbruster bdrv_dev_resize_cb(bs); 351851762288SStefan Hajnoczi } 351951762288SStefan Hajnoczi return ret; 352083f64091Sbellard } 352183f64091Sbellard 352283f64091Sbellard /** 35234a1d5e1fSFam Zheng * Length of a allocated file in bytes. Sparse files are counted by actual 35244a1d5e1fSFam Zheng * allocated space. Return < 0 if error or unknown. 35254a1d5e1fSFam Zheng */ 35264a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs) 35274a1d5e1fSFam Zheng { 35284a1d5e1fSFam Zheng BlockDriver *drv = bs->drv; 35294a1d5e1fSFam Zheng if (!drv) { 35304a1d5e1fSFam Zheng return -ENOMEDIUM; 35314a1d5e1fSFam Zheng } 35324a1d5e1fSFam Zheng if (drv->bdrv_get_allocated_file_size) { 35334a1d5e1fSFam Zheng return drv->bdrv_get_allocated_file_size(bs); 35344a1d5e1fSFam Zheng } 35354a1d5e1fSFam Zheng if (bs->file) { 35364a1d5e1fSFam Zheng return bdrv_get_allocated_file_size(bs->file); 35374a1d5e1fSFam Zheng } 35384a1d5e1fSFam Zheng return -ENOTSUP; 35394a1d5e1fSFam Zheng } 35404a1d5e1fSFam Zheng 35414a1d5e1fSFam Zheng /** 354265a9bb25SMarkus Armbruster * Return number of sectors on success, -errno on error. 354383f64091Sbellard */ 354465a9bb25SMarkus Armbruster int64_t bdrv_nb_sectors(BlockDriverState *bs) 354583f64091Sbellard { 354683f64091Sbellard BlockDriver *drv = bs->drv; 354765a9bb25SMarkus Armbruster 354883f64091Sbellard if (!drv) 354919cb3738Sbellard return -ENOMEDIUM; 355051762288SStefan Hajnoczi 3551b94a2610SKevin Wolf if (drv->has_variable_length) { 3552b94a2610SKevin Wolf int ret = refresh_total_sectors(bs, bs->total_sectors); 3553b94a2610SKevin Wolf if (ret < 0) { 3554b94a2610SKevin Wolf return ret; 3555fc01f7e7Sbellard } 355646a4e4e6SStefan Hajnoczi } 355765a9bb25SMarkus Armbruster return bs->total_sectors; 355865a9bb25SMarkus Armbruster } 355965a9bb25SMarkus Armbruster 356065a9bb25SMarkus Armbruster /** 356165a9bb25SMarkus Armbruster * Return length in bytes on success, -errno on error. 356265a9bb25SMarkus Armbruster * The length is always a multiple of BDRV_SECTOR_SIZE. 356365a9bb25SMarkus Armbruster */ 356465a9bb25SMarkus Armbruster int64_t bdrv_getlength(BlockDriverState *bs) 356565a9bb25SMarkus Armbruster { 356665a9bb25SMarkus Armbruster int64_t ret = bdrv_nb_sectors(bs); 356765a9bb25SMarkus Armbruster 356865a9bb25SMarkus Armbruster return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE; 356946a4e4e6SStefan Hajnoczi } 3570fc01f7e7Sbellard 357119cb3738Sbellard /* return 0 as number of sectors if no device present or error */ 357296b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr) 3573fc01f7e7Sbellard { 357465a9bb25SMarkus Armbruster int64_t nb_sectors = bdrv_nb_sectors(bs); 357565a9bb25SMarkus Armbruster 357665a9bb25SMarkus Armbruster *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors; 3577fc01f7e7Sbellard } 3578cf98951bSbellard 3579ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error, 3580ff06f5f3SPaolo Bonzini BlockdevOnError on_write_error) 3581abd7f68dSMarkus Armbruster { 3582abd7f68dSMarkus Armbruster bs->on_read_error = on_read_error; 3583abd7f68dSMarkus Armbruster bs->on_write_error = on_write_error; 3584abd7f68dSMarkus Armbruster } 3585abd7f68dSMarkus Armbruster 35861ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read) 3587abd7f68dSMarkus Armbruster { 3588abd7f68dSMarkus Armbruster return is_read ? bs->on_read_error : bs->on_write_error; 3589abd7f68dSMarkus Armbruster } 3590abd7f68dSMarkus Armbruster 35913e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error) 35923e1caa5fSPaolo Bonzini { 35933e1caa5fSPaolo Bonzini BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error; 35943e1caa5fSPaolo Bonzini 35953e1caa5fSPaolo Bonzini switch (on_err) { 35963e1caa5fSPaolo Bonzini case BLOCKDEV_ON_ERROR_ENOSPC: 3597a589569fSWenchao Xia return (error == ENOSPC) ? 3598a589569fSWenchao Xia BLOCK_ERROR_ACTION_STOP : BLOCK_ERROR_ACTION_REPORT; 35993e1caa5fSPaolo Bonzini case BLOCKDEV_ON_ERROR_STOP: 3600a589569fSWenchao Xia return BLOCK_ERROR_ACTION_STOP; 36013e1caa5fSPaolo Bonzini case BLOCKDEV_ON_ERROR_REPORT: 3602a589569fSWenchao Xia return BLOCK_ERROR_ACTION_REPORT; 36033e1caa5fSPaolo Bonzini case BLOCKDEV_ON_ERROR_IGNORE: 3604a589569fSWenchao Xia return BLOCK_ERROR_ACTION_IGNORE; 36053e1caa5fSPaolo Bonzini default: 36063e1caa5fSPaolo Bonzini abort(); 36073e1caa5fSPaolo Bonzini } 36083e1caa5fSPaolo Bonzini } 36093e1caa5fSPaolo Bonzini 36103e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows 36113e1caa5fSPaolo Bonzini * about the error, it does not know whether an operation comes from 36123e1caa5fSPaolo Bonzini * the device or the block layer (from a job, for example). 36133e1caa5fSPaolo Bonzini */ 36143e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action, 36153e1caa5fSPaolo Bonzini bool is_read, int error) 36163e1caa5fSPaolo Bonzini { 36173e1caa5fSPaolo Bonzini assert(error >= 0); 36182bd3bce8SPaolo Bonzini 3619a589569fSWenchao Xia if (action == BLOCK_ERROR_ACTION_STOP) { 36202bd3bce8SPaolo Bonzini /* First set the iostatus, so that "info block" returns an iostatus 36212bd3bce8SPaolo Bonzini * that matches the events raised so far (an additional error iostatus 36222bd3bce8SPaolo Bonzini * is fine, but not a lost one). 36232bd3bce8SPaolo Bonzini */ 36243e1caa5fSPaolo Bonzini bdrv_iostatus_set_err(bs, error); 36252bd3bce8SPaolo Bonzini 36262bd3bce8SPaolo Bonzini /* Then raise the request to stop the VM and the event. 36272bd3bce8SPaolo Bonzini * qemu_system_vmstop_request_prepare has two effects. First, 36282bd3bce8SPaolo Bonzini * it ensures that the STOP event always comes after the 36292bd3bce8SPaolo Bonzini * BLOCK_IO_ERROR event. Second, it ensures that even if management 36302bd3bce8SPaolo Bonzini * can observe the STOP event and do a "cont" before the STOP 36312bd3bce8SPaolo Bonzini * event is issued, the VM will not stop. In this case, vm_start() 36322bd3bce8SPaolo Bonzini * also ensures that the STOP/RESUME pair of events is emitted. 36332bd3bce8SPaolo Bonzini */ 36342bd3bce8SPaolo Bonzini qemu_system_vmstop_request_prepare(); 36355a2d2cbdSWenchao Xia qapi_event_send_block_io_error(bdrv_get_device_name(bs), 36365a2d2cbdSWenchao Xia is_read ? IO_OPERATION_TYPE_READ : 36375a2d2cbdSWenchao Xia IO_OPERATION_TYPE_WRITE, 36385a2d2cbdSWenchao Xia action, &error_abort); 36392bd3bce8SPaolo Bonzini qemu_system_vmstop_request(RUN_STATE_IO_ERROR); 36402bd3bce8SPaolo Bonzini } else { 36415a2d2cbdSWenchao Xia qapi_event_send_block_io_error(bdrv_get_device_name(bs), 36425a2d2cbdSWenchao Xia is_read ? IO_OPERATION_TYPE_READ : 36435a2d2cbdSWenchao Xia IO_OPERATION_TYPE_WRITE, 36445a2d2cbdSWenchao Xia action, &error_abort); 36453e1caa5fSPaolo Bonzini } 36463e1caa5fSPaolo Bonzini } 36473e1caa5fSPaolo Bonzini 3648b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs) 3649b338082bSbellard { 3650b338082bSbellard return bs->read_only; 3651b338082bSbellard } 3652b338082bSbellard 3653985a03b0Sths int bdrv_is_sg(BlockDriverState *bs) 3654985a03b0Sths { 3655985a03b0Sths return bs->sg; 3656985a03b0Sths } 3657985a03b0Sths 3658e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs) 3659e900a7b7SChristoph Hellwig { 3660e900a7b7SChristoph Hellwig return bs->enable_write_cache; 3661e900a7b7SChristoph Hellwig } 3662e900a7b7SChristoph Hellwig 3663425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce) 3664425b0148SPaolo Bonzini { 3665425b0148SPaolo Bonzini bs->enable_write_cache = wce; 366655b110f2SJeff Cody 366755b110f2SJeff Cody /* so a reopen() will preserve wce */ 366855b110f2SJeff Cody if (wce) { 366955b110f2SJeff Cody bs->open_flags |= BDRV_O_CACHE_WB; 367055b110f2SJeff Cody } else { 367155b110f2SJeff Cody bs->open_flags &= ~BDRV_O_CACHE_WB; 367255b110f2SJeff Cody } 3673425b0148SPaolo Bonzini } 3674425b0148SPaolo Bonzini 3675ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs) 3676ea2384d3Sbellard { 3677ea2384d3Sbellard if (bs->backing_hd && bs->backing_hd->encrypted) 3678ea2384d3Sbellard return 1; 3679ea2384d3Sbellard return bs->encrypted; 3680ea2384d3Sbellard } 3681ea2384d3Sbellard 3682c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs) 3683c0f4ce77Saliguori { 3684c0f4ce77Saliguori BlockDriverState *backing_hd = bs->backing_hd; 3685c0f4ce77Saliguori 3686c0f4ce77Saliguori if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key) 3687c0f4ce77Saliguori return 1; 3688c0f4ce77Saliguori return (bs->encrypted && !bs->valid_key); 3689c0f4ce77Saliguori } 3690c0f4ce77Saliguori 3691ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key) 3692ea2384d3Sbellard { 3693ea2384d3Sbellard int ret; 3694ea2384d3Sbellard if (bs->backing_hd && bs->backing_hd->encrypted) { 3695ea2384d3Sbellard ret = bdrv_set_key(bs->backing_hd, key); 3696ea2384d3Sbellard if (ret < 0) 3697ea2384d3Sbellard return ret; 3698ea2384d3Sbellard if (!bs->encrypted) 3699ea2384d3Sbellard return 0; 3700ea2384d3Sbellard } 3701fd04a2aeSShahar Havivi if (!bs->encrypted) { 3702fd04a2aeSShahar Havivi return -EINVAL; 3703fd04a2aeSShahar Havivi } else if (!bs->drv || !bs->drv->bdrv_set_key) { 3704fd04a2aeSShahar Havivi return -ENOMEDIUM; 3705fd04a2aeSShahar Havivi } 3706c0f4ce77Saliguori ret = bs->drv->bdrv_set_key(bs, key); 3707bb5fc20fSaliguori if (ret < 0) { 3708bb5fc20fSaliguori bs->valid_key = 0; 3709bb5fc20fSaliguori } else if (!bs->valid_key) { 3710bb5fc20fSaliguori bs->valid_key = 1; 3711bb5fc20fSaliguori /* call the change callback now, we skipped it on open */ 37127d4b4ba5SMarkus Armbruster bdrv_dev_change_media_cb(bs, true); 3713bb5fc20fSaliguori } 3714c0f4ce77Saliguori return ret; 3715ea2384d3Sbellard } 3716ea2384d3Sbellard 3717f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs) 3718ea2384d3Sbellard { 3719f8d6bba1SMarkus Armbruster return bs->drv ? bs->drv->format_name : NULL; 3720ea2384d3Sbellard } 3721ea2384d3Sbellard 3722ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name), 3723ea2384d3Sbellard void *opaque) 3724ea2384d3Sbellard { 3725ea2384d3Sbellard BlockDriver *drv; 3726e855e4fbSJeff Cody int count = 0; 3727e855e4fbSJeff Cody const char **formats = NULL; 3728ea2384d3Sbellard 37298a22f02aSStefan Hajnoczi QLIST_FOREACH(drv, &bdrv_drivers, list) { 3730e855e4fbSJeff Cody if (drv->format_name) { 3731e855e4fbSJeff Cody bool found = false; 3732e855e4fbSJeff Cody int i = count; 3733e855e4fbSJeff Cody while (formats && i && !found) { 3734e855e4fbSJeff Cody found = !strcmp(formats[--i], drv->format_name); 3735e855e4fbSJeff Cody } 3736e855e4fbSJeff Cody 3737e855e4fbSJeff Cody if (!found) { 3738e855e4fbSJeff Cody formats = g_realloc(formats, (count + 1) * sizeof(char *)); 3739e855e4fbSJeff Cody formats[count++] = drv->format_name; 3740ea2384d3Sbellard it(opaque, drv->format_name); 3741ea2384d3Sbellard } 3742ea2384d3Sbellard } 3743e855e4fbSJeff Cody } 3744e855e4fbSJeff Cody g_free(formats); 3745e855e4fbSJeff Cody } 3746ea2384d3Sbellard 3747dc364f4cSBenoît Canet /* This function is to find block backend bs */ 3748b338082bSbellard BlockDriverState *bdrv_find(const char *name) 3749b338082bSbellard { 3750b338082bSbellard BlockDriverState *bs; 3751b338082bSbellard 3752dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 37531b7bdbc1SStefan Hajnoczi if (!strcmp(name, bs->device_name)) { 3754b338082bSbellard return bs; 3755b338082bSbellard } 37561b7bdbc1SStefan Hajnoczi } 3757b338082bSbellard return NULL; 3758b338082bSbellard } 3759b338082bSbellard 3760dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */ 3761dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name) 3762dc364f4cSBenoît Canet { 3763dc364f4cSBenoît Canet BlockDriverState *bs; 3764dc364f4cSBenoît Canet 3765dc364f4cSBenoît Canet assert(node_name); 3766dc364f4cSBenoît Canet 3767dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) { 3768dc364f4cSBenoît Canet if (!strcmp(node_name, bs->node_name)) { 3769dc364f4cSBenoît Canet return bs; 3770dc364f4cSBenoît Canet } 3771dc364f4cSBenoît Canet } 3772dc364f4cSBenoît Canet return NULL; 3773dc364f4cSBenoît Canet } 3774dc364f4cSBenoît Canet 3775c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */ 3776c13163fbSBenoît Canet BlockDeviceInfoList *bdrv_named_nodes_list(void) 3777c13163fbSBenoît Canet { 3778c13163fbSBenoît Canet BlockDeviceInfoList *list, *entry; 3779c13163fbSBenoît Canet BlockDriverState *bs; 3780c13163fbSBenoît Canet 3781c13163fbSBenoît Canet list = NULL; 3782c13163fbSBenoît Canet QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) { 3783c13163fbSBenoît Canet entry = g_malloc0(sizeof(*entry)); 3784c13163fbSBenoît Canet entry->value = bdrv_block_device_info(bs); 3785c13163fbSBenoît Canet entry->next = list; 3786c13163fbSBenoît Canet list = entry; 3787c13163fbSBenoît Canet } 3788c13163fbSBenoît Canet 3789c13163fbSBenoît Canet return list; 3790c13163fbSBenoît Canet } 3791c13163fbSBenoît Canet 379212d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device, 379312d3ba82SBenoît Canet const char *node_name, 379412d3ba82SBenoît Canet Error **errp) 379512d3ba82SBenoît Canet { 379612d3ba82SBenoît Canet BlockDriverState *bs = NULL; 379712d3ba82SBenoît Canet 379812d3ba82SBenoît Canet if (device) { 379912d3ba82SBenoît Canet bs = bdrv_find(device); 380012d3ba82SBenoît Canet 3801dd67fa50SBenoît Canet if (bs) { 380212d3ba82SBenoît Canet return bs; 380312d3ba82SBenoît Canet } 3804dd67fa50SBenoît Canet } 380512d3ba82SBenoît Canet 3806dd67fa50SBenoît Canet if (node_name) { 380712d3ba82SBenoît Canet bs = bdrv_find_node(node_name); 380812d3ba82SBenoît Canet 3809dd67fa50SBenoît Canet if (bs) { 3810dd67fa50SBenoît Canet return bs; 3811dd67fa50SBenoît Canet } 381212d3ba82SBenoît Canet } 381312d3ba82SBenoît Canet 3814dd67fa50SBenoît Canet error_setg(errp, "Cannot find device=%s nor node_name=%s", 3815dd67fa50SBenoît Canet device ? device : "", 3816dd67fa50SBenoît Canet node_name ? node_name : ""); 3817dd67fa50SBenoît Canet return NULL; 381812d3ba82SBenoît Canet } 381912d3ba82SBenoît Canet 38205a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise, 38215a6684d2SJeff Cody * return false. If either argument is NULL, return false. */ 38225a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base) 38235a6684d2SJeff Cody { 38245a6684d2SJeff Cody while (top && top != base) { 38255a6684d2SJeff Cody top = top->backing_hd; 38265a6684d2SJeff Cody } 38275a6684d2SJeff Cody 38285a6684d2SJeff Cody return top != NULL; 38295a6684d2SJeff Cody } 38305a6684d2SJeff Cody 38312f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs) 38322f399b0aSMarkus Armbruster { 38332f399b0aSMarkus Armbruster if (!bs) { 38342f399b0aSMarkus Armbruster return QTAILQ_FIRST(&bdrv_states); 38352f399b0aSMarkus Armbruster } 3836dc364f4cSBenoît Canet return QTAILQ_NEXT(bs, device_list); 38372f399b0aSMarkus Armbruster } 38382f399b0aSMarkus Armbruster 383951de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque) 384081d0912dSbellard { 384181d0912dSbellard BlockDriverState *bs; 384281d0912dSbellard 3843dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 384451de9760Saliguori it(opaque, bs); 384581d0912dSbellard } 384681d0912dSbellard } 384781d0912dSbellard 3848ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs) 3849ea2384d3Sbellard { 3850ea2384d3Sbellard return bs->device_name; 3851ea2384d3Sbellard } 3852ea2384d3Sbellard 3853c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs) 3854c8433287SMarkus Armbruster { 3855c8433287SMarkus Armbruster return bs->open_flags; 3856c8433287SMarkus Armbruster } 3857c8433287SMarkus Armbruster 3858f0f0fdfeSKevin Wolf int bdrv_flush_all(void) 3859c6ca28d6Saliguori { 3860c6ca28d6Saliguori BlockDriverState *bs; 3861f0f0fdfeSKevin Wolf int result = 0; 3862c6ca28d6Saliguori 3863dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 3864ed78cda3SStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 3865ed78cda3SStefan Hajnoczi int ret; 3866ed78cda3SStefan Hajnoczi 3867ed78cda3SStefan Hajnoczi aio_context_acquire(aio_context); 3868ed78cda3SStefan Hajnoczi ret = bdrv_flush(bs); 3869f0f0fdfeSKevin Wolf if (ret < 0 && !result) { 3870f0f0fdfeSKevin Wolf result = ret; 3871c6ca28d6Saliguori } 3872ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 38731b7bdbc1SStefan Hajnoczi } 3874c6ca28d6Saliguori 3875f0f0fdfeSKevin Wolf return result; 3876f0f0fdfeSKevin Wolf } 3877f0f0fdfeSKevin Wolf 38783ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs) 38793ac21627SPeter Lieven { 38803ac21627SPeter Lieven return 1; 38813ac21627SPeter Lieven } 38823ac21627SPeter Lieven 3883f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs) 3884f2feebbdSKevin Wolf { 3885f2feebbdSKevin Wolf assert(bs->drv); 3886f2feebbdSKevin Wolf 388711212d8fSPaolo Bonzini /* If BS is a copy on write image, it is initialized to 388811212d8fSPaolo Bonzini the contents of the base image, which may not be zeroes. */ 388911212d8fSPaolo Bonzini if (bs->backing_hd) { 389011212d8fSPaolo Bonzini return 0; 389111212d8fSPaolo Bonzini } 3892336c1c12SKevin Wolf if (bs->drv->bdrv_has_zero_init) { 3893336c1c12SKevin Wolf return bs->drv->bdrv_has_zero_init(bs); 3894f2feebbdSKevin Wolf } 3895f2feebbdSKevin Wolf 38963ac21627SPeter Lieven /* safe default */ 38973ac21627SPeter Lieven return 0; 3898f2feebbdSKevin Wolf } 3899f2feebbdSKevin Wolf 39004ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs) 39014ce78691SPeter Lieven { 39024ce78691SPeter Lieven BlockDriverInfo bdi; 39034ce78691SPeter Lieven 39044ce78691SPeter Lieven if (bs->backing_hd) { 39054ce78691SPeter Lieven return false; 39064ce78691SPeter Lieven } 39074ce78691SPeter Lieven 39084ce78691SPeter Lieven if (bdrv_get_info(bs, &bdi) == 0) { 39094ce78691SPeter Lieven return bdi.unallocated_blocks_are_zero; 39104ce78691SPeter Lieven } 39114ce78691SPeter Lieven 39124ce78691SPeter Lieven return false; 39134ce78691SPeter Lieven } 39144ce78691SPeter Lieven 39154ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs) 39164ce78691SPeter Lieven { 39174ce78691SPeter Lieven BlockDriverInfo bdi; 39184ce78691SPeter Lieven 39194ce78691SPeter Lieven if (bs->backing_hd || !(bs->open_flags & BDRV_O_UNMAP)) { 39204ce78691SPeter Lieven return false; 39214ce78691SPeter Lieven } 39224ce78691SPeter Lieven 39234ce78691SPeter Lieven if (bdrv_get_info(bs, &bdi) == 0) { 39244ce78691SPeter Lieven return bdi.can_write_zeroes_with_unmap; 39254ce78691SPeter Lieven } 39264ce78691SPeter Lieven 39274ce78691SPeter Lieven return false; 39284ce78691SPeter Lieven } 39294ce78691SPeter Lieven 3930b6b8a333SPaolo Bonzini typedef struct BdrvCoGetBlockStatusData { 3931376ae3f1SStefan Hajnoczi BlockDriverState *bs; 3932b35b2bbaSMiroslav Rezanina BlockDriverState *base; 3933376ae3f1SStefan Hajnoczi int64_t sector_num; 3934376ae3f1SStefan Hajnoczi int nb_sectors; 3935376ae3f1SStefan Hajnoczi int *pnum; 3936b6b8a333SPaolo Bonzini int64_t ret; 3937376ae3f1SStefan Hajnoczi bool done; 3938b6b8a333SPaolo Bonzini } BdrvCoGetBlockStatusData; 3939376ae3f1SStefan Hajnoczi 3940f58c7b35Sths /* 3941f58c7b35Sths * Returns true iff the specified sector is present in the disk image. Drivers 3942f58c7b35Sths * not implementing the functionality are assumed to not support backing files, 3943f58c7b35Sths * hence all their sectors are reported as allocated. 3944f58c7b35Sths * 3945bd9533e3SStefan Hajnoczi * If 'sector_num' is beyond the end of the disk image the return value is 0 3946bd9533e3SStefan Hajnoczi * and 'pnum' is set to 0. 3947bd9533e3SStefan Hajnoczi * 3948f58c7b35Sths * 'pnum' is set to the number of sectors (including and immediately following 3949f58c7b35Sths * the specified sector) that are known to be in the same 3950f58c7b35Sths * allocated/unallocated state. 3951f58c7b35Sths * 3952bd9533e3SStefan Hajnoczi * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes 3953bd9533e3SStefan Hajnoczi * beyond the end of the disk image it will be clamped. 3954f58c7b35Sths */ 3955b6b8a333SPaolo Bonzini static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs, 3956bdad13b9SPaolo Bonzini int64_t sector_num, 3957060f51c9SStefan Hajnoczi int nb_sectors, int *pnum) 3958f58c7b35Sths { 395930a7f2fcSMarkus Armbruster int64_t total_sectors; 3960f58c7b35Sths int64_t n; 39615daa74a6SPaolo Bonzini int64_t ret, ret2; 3962bd9533e3SStefan Hajnoczi 396330a7f2fcSMarkus Armbruster total_sectors = bdrv_nb_sectors(bs); 396430a7f2fcSMarkus Armbruster if (total_sectors < 0) { 396530a7f2fcSMarkus Armbruster return total_sectors; 3966617ccb46SPaolo Bonzini } 3967617ccb46SPaolo Bonzini 396830a7f2fcSMarkus Armbruster if (sector_num >= total_sectors) { 39696aebab14SStefan Hajnoczi *pnum = 0; 39706aebab14SStefan Hajnoczi return 0; 39716aebab14SStefan Hajnoczi } 3972bd9533e3SStefan Hajnoczi 397330a7f2fcSMarkus Armbruster n = total_sectors - sector_num; 3974bd9533e3SStefan Hajnoczi if (n < nb_sectors) { 3975bd9533e3SStefan Hajnoczi nb_sectors = n; 3976bd9533e3SStefan Hajnoczi } 3977bd9533e3SStefan Hajnoczi 3978b6b8a333SPaolo Bonzini if (!bs->drv->bdrv_co_get_block_status) { 3979bd9533e3SStefan Hajnoczi *pnum = nb_sectors; 3980e88ae226SKevin Wolf ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED; 3981918e92d7SPaolo Bonzini if (bs->drv->protocol_name) { 3982918e92d7SPaolo Bonzini ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE); 3983918e92d7SPaolo Bonzini } 3984918e92d7SPaolo Bonzini return ret; 39856aebab14SStefan Hajnoczi } 39866aebab14SStefan Hajnoczi 3987415b5b01SPaolo Bonzini ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum); 3988415b5b01SPaolo Bonzini if (ret < 0) { 39893e0a233dSPeter Lieven *pnum = 0; 3990415b5b01SPaolo Bonzini return ret; 3991415b5b01SPaolo Bonzini } 3992415b5b01SPaolo Bonzini 399392bc50a5SPeter Lieven if (ret & BDRV_BLOCK_RAW) { 399492bc50a5SPeter Lieven assert(ret & BDRV_BLOCK_OFFSET_VALID); 399592bc50a5SPeter Lieven return bdrv_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS, 399692bc50a5SPeter Lieven *pnum, pnum); 399792bc50a5SPeter Lieven } 399892bc50a5SPeter Lieven 3999e88ae226SKevin Wolf if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) { 4000e88ae226SKevin Wolf ret |= BDRV_BLOCK_ALLOCATED; 4001e88ae226SKevin Wolf } 4002e88ae226SKevin Wolf 4003c3d86884SPeter Lieven if (!(ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO)) { 4004c3d86884SPeter Lieven if (bdrv_unallocated_blocks_are_zero(bs)) { 4005415b5b01SPaolo Bonzini ret |= BDRV_BLOCK_ZERO; 40061f9db224SPeter Lieven } else if (bs->backing_hd) { 4007f0ad5712SPaolo Bonzini BlockDriverState *bs2 = bs->backing_hd; 400830a7f2fcSMarkus Armbruster int64_t nb_sectors2 = bdrv_nb_sectors(bs2); 400930a7f2fcSMarkus Armbruster if (nb_sectors2 >= 0 && sector_num >= nb_sectors2) { 4010f0ad5712SPaolo Bonzini ret |= BDRV_BLOCK_ZERO; 4011f0ad5712SPaolo Bonzini } 4012f0ad5712SPaolo Bonzini } 4013415b5b01SPaolo Bonzini } 40145daa74a6SPaolo Bonzini 40155daa74a6SPaolo Bonzini if (bs->file && 40165daa74a6SPaolo Bonzini (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) && 40175daa74a6SPaolo Bonzini (ret & BDRV_BLOCK_OFFSET_VALID)) { 40185daa74a6SPaolo Bonzini ret2 = bdrv_co_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS, 40195daa74a6SPaolo Bonzini *pnum, pnum); 40205daa74a6SPaolo Bonzini if (ret2 >= 0) { 40215daa74a6SPaolo Bonzini /* Ignore errors. This is just providing extra information, it 40225daa74a6SPaolo Bonzini * is useful but not necessary. 40235daa74a6SPaolo Bonzini */ 40245daa74a6SPaolo Bonzini ret |= (ret2 & BDRV_BLOCK_ZERO); 40255daa74a6SPaolo Bonzini } 40265daa74a6SPaolo Bonzini } 40275daa74a6SPaolo Bonzini 4028415b5b01SPaolo Bonzini return ret; 4029060f51c9SStefan Hajnoczi } 4030060f51c9SStefan Hajnoczi 4031b6b8a333SPaolo Bonzini /* Coroutine wrapper for bdrv_get_block_status() */ 4032b6b8a333SPaolo Bonzini static void coroutine_fn bdrv_get_block_status_co_entry(void *opaque) 4033060f51c9SStefan Hajnoczi { 4034b6b8a333SPaolo Bonzini BdrvCoGetBlockStatusData *data = opaque; 4035060f51c9SStefan Hajnoczi BlockDriverState *bs = data->bs; 4036060f51c9SStefan Hajnoczi 4037b6b8a333SPaolo Bonzini data->ret = bdrv_co_get_block_status(bs, data->sector_num, data->nb_sectors, 4038060f51c9SStefan Hajnoczi data->pnum); 4039060f51c9SStefan Hajnoczi data->done = true; 4040060f51c9SStefan Hajnoczi } 4041060f51c9SStefan Hajnoczi 4042060f51c9SStefan Hajnoczi /* 4043b6b8a333SPaolo Bonzini * Synchronous wrapper around bdrv_co_get_block_status(). 4044060f51c9SStefan Hajnoczi * 4045b6b8a333SPaolo Bonzini * See bdrv_co_get_block_status() for details. 4046060f51c9SStefan Hajnoczi */ 4047b6b8a333SPaolo Bonzini int64_t bdrv_get_block_status(BlockDriverState *bs, int64_t sector_num, 4048b6b8a333SPaolo Bonzini int nb_sectors, int *pnum) 4049060f51c9SStefan Hajnoczi { 4050376ae3f1SStefan Hajnoczi Coroutine *co; 4051b6b8a333SPaolo Bonzini BdrvCoGetBlockStatusData data = { 4052376ae3f1SStefan Hajnoczi .bs = bs, 4053376ae3f1SStefan Hajnoczi .sector_num = sector_num, 4054376ae3f1SStefan Hajnoczi .nb_sectors = nb_sectors, 4055376ae3f1SStefan Hajnoczi .pnum = pnum, 4056376ae3f1SStefan Hajnoczi .done = false, 4057376ae3f1SStefan Hajnoczi }; 4058376ae3f1SStefan Hajnoczi 4059bdad13b9SPaolo Bonzini if (qemu_in_coroutine()) { 4060bdad13b9SPaolo Bonzini /* Fast-path if already in coroutine context */ 4061b6b8a333SPaolo Bonzini bdrv_get_block_status_co_entry(&data); 4062bdad13b9SPaolo Bonzini } else { 40632572b37aSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 40642572b37aSStefan Hajnoczi 4065b6b8a333SPaolo Bonzini co = qemu_coroutine_create(bdrv_get_block_status_co_entry); 4066376ae3f1SStefan Hajnoczi qemu_coroutine_enter(co, &data); 4067376ae3f1SStefan Hajnoczi while (!data.done) { 40682572b37aSStefan Hajnoczi aio_poll(aio_context, true); 4069376ae3f1SStefan Hajnoczi } 4070bdad13b9SPaolo Bonzini } 4071376ae3f1SStefan Hajnoczi return data.ret; 4072376ae3f1SStefan Hajnoczi } 4073f58c7b35Sths 4074b6b8a333SPaolo Bonzini int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, 4075b6b8a333SPaolo Bonzini int nb_sectors, int *pnum) 4076b6b8a333SPaolo Bonzini { 40774333bb71SPaolo Bonzini int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum); 40784333bb71SPaolo Bonzini if (ret < 0) { 40794333bb71SPaolo Bonzini return ret; 40804333bb71SPaolo Bonzini } 408101fb2705SKevin Wolf return !!(ret & BDRV_BLOCK_ALLOCATED); 4082b6b8a333SPaolo Bonzini } 4083b6b8a333SPaolo Bonzini 4084188a7bbfSPaolo Bonzini /* 4085188a7bbfSPaolo Bonzini * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP] 4086188a7bbfSPaolo Bonzini * 4087188a7bbfSPaolo Bonzini * Return true if the given sector is allocated in any image between 4088188a7bbfSPaolo Bonzini * BASE and TOP (inclusive). BASE can be NULL to check if the given 4089188a7bbfSPaolo Bonzini * sector is allocated in any image of the chain. Return false otherwise. 4090188a7bbfSPaolo Bonzini * 4091188a7bbfSPaolo Bonzini * 'pnum' is set to the number of sectors (including and immediately following 4092188a7bbfSPaolo Bonzini * the specified sector) that are known to be in the same 4093188a7bbfSPaolo Bonzini * allocated/unallocated state. 4094188a7bbfSPaolo Bonzini * 4095188a7bbfSPaolo Bonzini */ 40964f578637SPaolo Bonzini int bdrv_is_allocated_above(BlockDriverState *top, 4097188a7bbfSPaolo Bonzini BlockDriverState *base, 4098188a7bbfSPaolo Bonzini int64_t sector_num, 4099188a7bbfSPaolo Bonzini int nb_sectors, int *pnum) 4100188a7bbfSPaolo Bonzini { 4101188a7bbfSPaolo Bonzini BlockDriverState *intermediate; 4102188a7bbfSPaolo Bonzini int ret, n = nb_sectors; 4103188a7bbfSPaolo Bonzini 4104188a7bbfSPaolo Bonzini intermediate = top; 4105188a7bbfSPaolo Bonzini while (intermediate && intermediate != base) { 4106188a7bbfSPaolo Bonzini int pnum_inter; 4107bdad13b9SPaolo Bonzini ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors, 4108188a7bbfSPaolo Bonzini &pnum_inter); 4109188a7bbfSPaolo Bonzini if (ret < 0) { 4110188a7bbfSPaolo Bonzini return ret; 4111188a7bbfSPaolo Bonzini } else if (ret) { 4112188a7bbfSPaolo Bonzini *pnum = pnum_inter; 4113188a7bbfSPaolo Bonzini return 1; 4114188a7bbfSPaolo Bonzini } 4115188a7bbfSPaolo Bonzini 4116188a7bbfSPaolo Bonzini /* 4117188a7bbfSPaolo Bonzini * [sector_num, nb_sectors] is unallocated on top but intermediate 4118188a7bbfSPaolo Bonzini * might have 4119188a7bbfSPaolo Bonzini * 4120188a7bbfSPaolo Bonzini * [sector_num+x, nr_sectors] allocated. 4121188a7bbfSPaolo Bonzini */ 412263ba17d3SVishvananda Ishaya if (n > pnum_inter && 412363ba17d3SVishvananda Ishaya (intermediate == top || 412463ba17d3SVishvananda Ishaya sector_num + pnum_inter < intermediate->total_sectors)) { 4125188a7bbfSPaolo Bonzini n = pnum_inter; 4126188a7bbfSPaolo Bonzini } 4127188a7bbfSPaolo Bonzini 4128188a7bbfSPaolo Bonzini intermediate = intermediate->backing_hd; 4129188a7bbfSPaolo Bonzini } 4130188a7bbfSPaolo Bonzini 4131188a7bbfSPaolo Bonzini *pnum = n; 4132188a7bbfSPaolo Bonzini return 0; 4133188a7bbfSPaolo Bonzini } 4134188a7bbfSPaolo Bonzini 4135045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs) 4136045df330Saliguori { 4137045df330Saliguori if (bs->backing_hd && bs->backing_hd->encrypted) 4138045df330Saliguori return bs->backing_file; 4139045df330Saliguori else if (bs->encrypted) 4140045df330Saliguori return bs->filename; 4141045df330Saliguori else 4142045df330Saliguori return NULL; 4143045df330Saliguori } 4144045df330Saliguori 414583f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs, 414683f64091Sbellard char *filename, int filename_size) 414783f64091Sbellard { 414883f64091Sbellard pstrcpy(filename, filename_size, bs->backing_file); 414983f64091Sbellard } 415083f64091Sbellard 4151faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num, 4152faea38e7Sbellard const uint8_t *buf, int nb_sectors) 4153faea38e7Sbellard { 4154faea38e7Sbellard BlockDriver *drv = bs->drv; 4155faea38e7Sbellard if (!drv) 415619cb3738Sbellard return -ENOMEDIUM; 4157faea38e7Sbellard if (!drv->bdrv_write_compressed) 4158faea38e7Sbellard return -ENOTSUP; 4159fbb7b4e0SKevin Wolf if (bdrv_check_request(bs, sector_num, nb_sectors)) 4160fbb7b4e0SKevin Wolf return -EIO; 41617cd1e32aSlirans@il.ibm.com 4162e4654d2dSFam Zheng assert(QLIST_EMPTY(&bs->dirty_bitmaps)); 41637cd1e32aSlirans@il.ibm.com 4164faea38e7Sbellard return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors); 4165faea38e7Sbellard } 4166faea38e7Sbellard 4167faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi) 4168faea38e7Sbellard { 4169faea38e7Sbellard BlockDriver *drv = bs->drv; 4170faea38e7Sbellard if (!drv) 417119cb3738Sbellard return -ENOMEDIUM; 4172faea38e7Sbellard if (!drv->bdrv_get_info) 4173faea38e7Sbellard return -ENOTSUP; 4174faea38e7Sbellard memset(bdi, 0, sizeof(*bdi)); 4175faea38e7Sbellard return drv->bdrv_get_info(bs, bdi); 4176faea38e7Sbellard } 4177faea38e7Sbellard 4178eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs) 4179eae041feSMax Reitz { 4180eae041feSMax Reitz BlockDriver *drv = bs->drv; 4181eae041feSMax Reitz if (drv && drv->bdrv_get_specific_info) { 4182eae041feSMax Reitz return drv->bdrv_get_specific_info(bs); 4183eae041feSMax Reitz } 4184eae041feSMax Reitz return NULL; 4185eae041feSMax Reitz } 4186eae041feSMax Reitz 418745566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf, 418845566e9cSChristoph Hellwig int64_t pos, int size) 4189178e08a5Saliguori { 4190cf8074b3SKevin Wolf QEMUIOVector qiov; 4191cf8074b3SKevin Wolf struct iovec iov = { 4192cf8074b3SKevin Wolf .iov_base = (void *) buf, 4193cf8074b3SKevin Wolf .iov_len = size, 4194cf8074b3SKevin Wolf }; 4195cf8074b3SKevin Wolf 4196cf8074b3SKevin Wolf qemu_iovec_init_external(&qiov, &iov, 1); 4197cf8074b3SKevin Wolf return bdrv_writev_vmstate(bs, &qiov, pos); 4198cf8074b3SKevin Wolf } 4199cf8074b3SKevin Wolf 4200cf8074b3SKevin Wolf int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos) 4201cf8074b3SKevin Wolf { 4202178e08a5Saliguori BlockDriver *drv = bs->drv; 4203cf8074b3SKevin Wolf 4204cf8074b3SKevin Wolf if (!drv) { 4205178e08a5Saliguori return -ENOMEDIUM; 4206cf8074b3SKevin Wolf } else if (drv->bdrv_save_vmstate) { 4207cf8074b3SKevin Wolf return drv->bdrv_save_vmstate(bs, qiov, pos); 4208cf8074b3SKevin Wolf } else if (bs->file) { 4209cf8074b3SKevin Wolf return bdrv_writev_vmstate(bs->file, qiov, pos); 4210cf8074b3SKevin Wolf } 4211cf8074b3SKevin Wolf 42127cdb1f6dSMORITA Kazutaka return -ENOTSUP; 4213178e08a5Saliguori } 4214178e08a5Saliguori 421545566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf, 421645566e9cSChristoph Hellwig int64_t pos, int size) 4217178e08a5Saliguori { 4218178e08a5Saliguori BlockDriver *drv = bs->drv; 4219178e08a5Saliguori if (!drv) 4220178e08a5Saliguori return -ENOMEDIUM; 42217cdb1f6dSMORITA Kazutaka if (drv->bdrv_load_vmstate) 422245566e9cSChristoph Hellwig return drv->bdrv_load_vmstate(bs, buf, pos, size); 42237cdb1f6dSMORITA Kazutaka if (bs->file) 42247cdb1f6dSMORITA Kazutaka return bdrv_load_vmstate(bs->file, buf, pos, size); 42257cdb1f6dSMORITA Kazutaka return -ENOTSUP; 4226178e08a5Saliguori } 4227178e08a5Saliguori 42288b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event) 42298b9b0cc2SKevin Wolf { 4230bf736fe3SKevin Wolf if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) { 42318b9b0cc2SKevin Wolf return; 42328b9b0cc2SKevin Wolf } 42338b9b0cc2SKevin Wolf 4234bf736fe3SKevin Wolf bs->drv->bdrv_debug_event(bs, event); 423541c695c7SKevin Wolf } 42368b9b0cc2SKevin Wolf 423741c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event, 423841c695c7SKevin Wolf const char *tag) 423941c695c7SKevin Wolf { 424041c695c7SKevin Wolf while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) { 424141c695c7SKevin Wolf bs = bs->file; 424241c695c7SKevin Wolf } 424341c695c7SKevin Wolf 424441c695c7SKevin Wolf if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) { 424541c695c7SKevin Wolf return bs->drv->bdrv_debug_breakpoint(bs, event, tag); 424641c695c7SKevin Wolf } 424741c695c7SKevin Wolf 424841c695c7SKevin Wolf return -ENOTSUP; 424941c695c7SKevin Wolf } 425041c695c7SKevin Wolf 42514cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag) 42524cc70e93SFam Zheng { 42534cc70e93SFam Zheng while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) { 42544cc70e93SFam Zheng bs = bs->file; 42554cc70e93SFam Zheng } 42564cc70e93SFam Zheng 42574cc70e93SFam Zheng if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) { 42584cc70e93SFam Zheng return bs->drv->bdrv_debug_remove_breakpoint(bs, tag); 42594cc70e93SFam Zheng } 42604cc70e93SFam Zheng 42614cc70e93SFam Zheng return -ENOTSUP; 42624cc70e93SFam Zheng } 42634cc70e93SFam Zheng 426441c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag) 426541c695c7SKevin Wolf { 4266938789eaSMax Reitz while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) { 426741c695c7SKevin Wolf bs = bs->file; 426841c695c7SKevin Wolf } 426941c695c7SKevin Wolf 427041c695c7SKevin Wolf if (bs && bs->drv && bs->drv->bdrv_debug_resume) { 427141c695c7SKevin Wolf return bs->drv->bdrv_debug_resume(bs, tag); 427241c695c7SKevin Wolf } 427341c695c7SKevin Wolf 427441c695c7SKevin Wolf return -ENOTSUP; 427541c695c7SKevin Wolf } 427641c695c7SKevin Wolf 427741c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag) 427841c695c7SKevin Wolf { 427941c695c7SKevin Wolf while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) { 428041c695c7SKevin Wolf bs = bs->file; 428141c695c7SKevin Wolf } 428241c695c7SKevin Wolf 428341c695c7SKevin Wolf if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) { 428441c695c7SKevin Wolf return bs->drv->bdrv_debug_is_suspended(bs, tag); 428541c695c7SKevin Wolf } 428641c695c7SKevin Wolf 428741c695c7SKevin Wolf return false; 42888b9b0cc2SKevin Wolf } 42898b9b0cc2SKevin Wolf 4290199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs) 4291199630b6SBlue Swirl { 4292199630b6SBlue Swirl return !!(bs->open_flags & BDRV_O_SNAPSHOT); 4293199630b6SBlue Swirl } 4294199630b6SBlue Swirl 4295b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol. If it is 4296b1b1d783SJeff Cody * relative, it must be relative to the chain. So, passing in bs->filename 4297b1b1d783SJeff Cody * from a BDS as backing_file should not be done, as that may be relative to 4298b1b1d783SJeff Cody * the CWD rather than the chain. */ 4299e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs, 4300e8a6bb9cSMarcelo Tosatti const char *backing_file) 4301e8a6bb9cSMarcelo Tosatti { 4302b1b1d783SJeff Cody char *filename_full = NULL; 4303b1b1d783SJeff Cody char *backing_file_full = NULL; 4304b1b1d783SJeff Cody char *filename_tmp = NULL; 4305b1b1d783SJeff Cody int is_protocol = 0; 4306b1b1d783SJeff Cody BlockDriverState *curr_bs = NULL; 4307b1b1d783SJeff Cody BlockDriverState *retval = NULL; 4308b1b1d783SJeff Cody 4309b1b1d783SJeff Cody if (!bs || !bs->drv || !backing_file) { 4310e8a6bb9cSMarcelo Tosatti return NULL; 4311e8a6bb9cSMarcelo Tosatti } 4312e8a6bb9cSMarcelo Tosatti 4313b1b1d783SJeff Cody filename_full = g_malloc(PATH_MAX); 4314b1b1d783SJeff Cody backing_file_full = g_malloc(PATH_MAX); 4315b1b1d783SJeff Cody filename_tmp = g_malloc(PATH_MAX); 4316b1b1d783SJeff Cody 4317b1b1d783SJeff Cody is_protocol = path_has_protocol(backing_file); 4318b1b1d783SJeff Cody 4319b1b1d783SJeff Cody for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) { 4320b1b1d783SJeff Cody 4321b1b1d783SJeff Cody /* If either of the filename paths is actually a protocol, then 4322b1b1d783SJeff Cody * compare unmodified paths; otherwise make paths relative */ 4323b1b1d783SJeff Cody if (is_protocol || path_has_protocol(curr_bs->backing_file)) { 4324b1b1d783SJeff Cody if (strcmp(backing_file, curr_bs->backing_file) == 0) { 4325b1b1d783SJeff Cody retval = curr_bs->backing_hd; 4326b1b1d783SJeff Cody break; 4327b1b1d783SJeff Cody } 4328e8a6bb9cSMarcelo Tosatti } else { 4329b1b1d783SJeff Cody /* If not an absolute filename path, make it relative to the current 4330b1b1d783SJeff Cody * image's filename path */ 4331b1b1d783SJeff Cody path_combine(filename_tmp, PATH_MAX, curr_bs->filename, 4332b1b1d783SJeff Cody backing_file); 4333b1b1d783SJeff Cody 4334b1b1d783SJeff Cody /* We are going to compare absolute pathnames */ 4335b1b1d783SJeff Cody if (!realpath(filename_tmp, filename_full)) { 4336b1b1d783SJeff Cody continue; 4337b1b1d783SJeff Cody } 4338b1b1d783SJeff Cody 4339b1b1d783SJeff Cody /* We need to make sure the backing filename we are comparing against 4340b1b1d783SJeff Cody * is relative to the current image filename (or absolute) */ 4341b1b1d783SJeff Cody path_combine(filename_tmp, PATH_MAX, curr_bs->filename, 4342b1b1d783SJeff Cody curr_bs->backing_file); 4343b1b1d783SJeff Cody 4344b1b1d783SJeff Cody if (!realpath(filename_tmp, backing_file_full)) { 4345b1b1d783SJeff Cody continue; 4346b1b1d783SJeff Cody } 4347b1b1d783SJeff Cody 4348b1b1d783SJeff Cody if (strcmp(backing_file_full, filename_full) == 0) { 4349b1b1d783SJeff Cody retval = curr_bs->backing_hd; 4350b1b1d783SJeff Cody break; 4351b1b1d783SJeff Cody } 4352e8a6bb9cSMarcelo Tosatti } 4353e8a6bb9cSMarcelo Tosatti } 4354e8a6bb9cSMarcelo Tosatti 4355b1b1d783SJeff Cody g_free(filename_full); 4356b1b1d783SJeff Cody g_free(backing_file_full); 4357b1b1d783SJeff Cody g_free(filename_tmp); 4358b1b1d783SJeff Cody return retval; 4359e8a6bb9cSMarcelo Tosatti } 4360e8a6bb9cSMarcelo Tosatti 4361f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs) 4362f198fd1cSBenoît Canet { 4363f198fd1cSBenoît Canet if (!bs->drv) { 4364f198fd1cSBenoît Canet return 0; 4365f198fd1cSBenoît Canet } 4366f198fd1cSBenoît Canet 4367f198fd1cSBenoît Canet if (!bs->backing_hd) { 4368f198fd1cSBenoît Canet return 0; 4369f198fd1cSBenoît Canet } 4370f198fd1cSBenoît Canet 4371f198fd1cSBenoît Canet return 1 + bdrv_get_backing_file_depth(bs->backing_hd); 4372f198fd1cSBenoît Canet } 4373f198fd1cSBenoît Canet 4374ea2384d3Sbellard /**************************************************************/ 437583f64091Sbellard /* async I/Os */ 4376ea2384d3Sbellard 43773b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num, 4378f141eafeSaliguori QEMUIOVector *qiov, int nb_sectors, 437983f64091Sbellard BlockDriverCompletionFunc *cb, void *opaque) 4380ea2384d3Sbellard { 4381bbf0a440SStefan Hajnoczi trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque); 4382bbf0a440SStefan Hajnoczi 4383d20d9b7cSPaolo Bonzini return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0, 43848c5873d6SStefan Hajnoczi cb, opaque, false); 438583f64091Sbellard } 438683f64091Sbellard 4387f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num, 4388f141eafeSaliguori QEMUIOVector *qiov, int nb_sectors, 438983f64091Sbellard BlockDriverCompletionFunc *cb, void *opaque) 43907674e7bfSbellard { 4391bbf0a440SStefan Hajnoczi trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque); 4392bbf0a440SStefan Hajnoczi 4393d20d9b7cSPaolo Bonzini return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0, 43948c5873d6SStefan Hajnoczi cb, opaque, true); 439583f64091Sbellard } 439683f64091Sbellard 4397d5ef94d4SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs, 4398d5ef94d4SPaolo Bonzini int64_t sector_num, int nb_sectors, BdrvRequestFlags flags, 4399d5ef94d4SPaolo Bonzini BlockDriverCompletionFunc *cb, void *opaque) 4400d5ef94d4SPaolo Bonzini { 4401d5ef94d4SPaolo Bonzini trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque); 4402d5ef94d4SPaolo Bonzini 4403d5ef94d4SPaolo Bonzini return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors, 4404d5ef94d4SPaolo Bonzini BDRV_REQ_ZERO_WRITE | flags, 4405d5ef94d4SPaolo Bonzini cb, opaque, true); 4406d5ef94d4SPaolo Bonzini } 4407d5ef94d4SPaolo Bonzini 440840b4f539SKevin Wolf 440940b4f539SKevin Wolf typedef struct MultiwriteCB { 441040b4f539SKevin Wolf int error; 441140b4f539SKevin Wolf int num_requests; 441240b4f539SKevin Wolf int num_callbacks; 441340b4f539SKevin Wolf struct { 441440b4f539SKevin Wolf BlockDriverCompletionFunc *cb; 441540b4f539SKevin Wolf void *opaque; 441640b4f539SKevin Wolf QEMUIOVector *free_qiov; 441740b4f539SKevin Wolf } callbacks[]; 441840b4f539SKevin Wolf } MultiwriteCB; 441940b4f539SKevin Wolf 442040b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb) 442140b4f539SKevin Wolf { 442240b4f539SKevin Wolf int i; 442340b4f539SKevin Wolf 442440b4f539SKevin Wolf for (i = 0; i < mcb->num_callbacks; i++) { 442540b4f539SKevin Wolf mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error); 44261e1ea48dSStefan Hajnoczi if (mcb->callbacks[i].free_qiov) { 44271e1ea48dSStefan Hajnoczi qemu_iovec_destroy(mcb->callbacks[i].free_qiov); 44281e1ea48dSStefan Hajnoczi } 44297267c094SAnthony Liguori g_free(mcb->callbacks[i].free_qiov); 443040b4f539SKevin Wolf } 443140b4f539SKevin Wolf } 443240b4f539SKevin Wolf 443340b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret) 443440b4f539SKevin Wolf { 443540b4f539SKevin Wolf MultiwriteCB *mcb = opaque; 443640b4f539SKevin Wolf 44376d519a5fSStefan Hajnoczi trace_multiwrite_cb(mcb, ret); 44386d519a5fSStefan Hajnoczi 4439cb6d3ca0SKevin Wolf if (ret < 0 && !mcb->error) { 444040b4f539SKevin Wolf mcb->error = ret; 444140b4f539SKevin Wolf } 444240b4f539SKevin Wolf 444340b4f539SKevin Wolf mcb->num_requests--; 444440b4f539SKevin Wolf if (mcb->num_requests == 0) { 444540b4f539SKevin Wolf multiwrite_user_cb(mcb); 44467267c094SAnthony Liguori g_free(mcb); 444740b4f539SKevin Wolf } 444840b4f539SKevin Wolf } 444940b4f539SKevin Wolf 445040b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b) 445140b4f539SKevin Wolf { 445277be4366SChristoph Hellwig const BlockRequest *req1 = a, *req2 = b; 445377be4366SChristoph Hellwig 445477be4366SChristoph Hellwig /* 445577be4366SChristoph Hellwig * Note that we can't simply subtract req2->sector from req1->sector 445677be4366SChristoph Hellwig * here as that could overflow the return value. 445777be4366SChristoph Hellwig */ 445877be4366SChristoph Hellwig if (req1->sector > req2->sector) { 445977be4366SChristoph Hellwig return 1; 446077be4366SChristoph Hellwig } else if (req1->sector < req2->sector) { 446177be4366SChristoph Hellwig return -1; 446277be4366SChristoph Hellwig } else { 446377be4366SChristoph Hellwig return 0; 446477be4366SChristoph Hellwig } 446540b4f539SKevin Wolf } 446640b4f539SKevin Wolf 446740b4f539SKevin Wolf /* 446840b4f539SKevin Wolf * Takes a bunch of requests and tries to merge them. Returns the number of 446940b4f539SKevin Wolf * requests that remain after merging. 447040b4f539SKevin Wolf */ 447140b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs, 447240b4f539SKevin Wolf int num_reqs, MultiwriteCB *mcb) 447340b4f539SKevin Wolf { 447440b4f539SKevin Wolf int i, outidx; 447540b4f539SKevin Wolf 447640b4f539SKevin Wolf // Sort requests by start sector 447740b4f539SKevin Wolf qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare); 447840b4f539SKevin Wolf 447940b4f539SKevin Wolf // Check if adjacent requests touch the same clusters. If so, combine them, 448040b4f539SKevin Wolf // filling up gaps with zero sectors. 448140b4f539SKevin Wolf outidx = 0; 448240b4f539SKevin Wolf for (i = 1; i < num_reqs; i++) { 448340b4f539SKevin Wolf int merge = 0; 448440b4f539SKevin Wolf int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors; 448540b4f539SKevin Wolf 4486b6a127a1SPaolo Bonzini // Handle exactly sequential writes and overlapping writes. 448740b4f539SKevin Wolf if (reqs[i].sector <= oldreq_last) { 448840b4f539SKevin Wolf merge = 1; 448940b4f539SKevin Wolf } 449040b4f539SKevin Wolf 4491e2a305fbSChristoph Hellwig if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) { 4492e2a305fbSChristoph Hellwig merge = 0; 4493e2a305fbSChristoph Hellwig } 4494e2a305fbSChristoph Hellwig 449540b4f539SKevin Wolf if (merge) { 449640b4f539SKevin Wolf size_t size; 44977267c094SAnthony Liguori QEMUIOVector *qiov = g_malloc0(sizeof(*qiov)); 449840b4f539SKevin Wolf qemu_iovec_init(qiov, 449940b4f539SKevin Wolf reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1); 450040b4f539SKevin Wolf 450140b4f539SKevin Wolf // Add the first request to the merged one. If the requests are 450240b4f539SKevin Wolf // overlapping, drop the last sectors of the first request. 450340b4f539SKevin Wolf size = (reqs[i].sector - reqs[outidx].sector) << 9; 45041b093c48SMichael Tokarev qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size); 450540b4f539SKevin Wolf 4506b6a127a1SPaolo Bonzini // We should need to add any zeros between the two requests 4507b6a127a1SPaolo Bonzini assert (reqs[i].sector <= oldreq_last); 450840b4f539SKevin Wolf 450940b4f539SKevin Wolf // Add the second request 45101b093c48SMichael Tokarev qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size); 451140b4f539SKevin Wolf 4512cbf1dff2SKevin Wolf reqs[outidx].nb_sectors = qiov->size >> 9; 451340b4f539SKevin Wolf reqs[outidx].qiov = qiov; 451440b4f539SKevin Wolf 451540b4f539SKevin Wolf mcb->callbacks[i].free_qiov = reqs[outidx].qiov; 451640b4f539SKevin Wolf } else { 451740b4f539SKevin Wolf outidx++; 451840b4f539SKevin Wolf reqs[outidx].sector = reqs[i].sector; 451940b4f539SKevin Wolf reqs[outidx].nb_sectors = reqs[i].nb_sectors; 452040b4f539SKevin Wolf reqs[outidx].qiov = reqs[i].qiov; 452140b4f539SKevin Wolf } 452240b4f539SKevin Wolf } 452340b4f539SKevin Wolf 452440b4f539SKevin Wolf return outidx + 1; 452540b4f539SKevin Wolf } 452640b4f539SKevin Wolf 452740b4f539SKevin Wolf /* 452840b4f539SKevin Wolf * Submit multiple AIO write requests at once. 452940b4f539SKevin Wolf * 453040b4f539SKevin Wolf * On success, the function returns 0 and all requests in the reqs array have 453140b4f539SKevin Wolf * been submitted. In error case this function returns -1, and any of the 453240b4f539SKevin Wolf * requests may or may not be submitted yet. In particular, this means that the 453340b4f539SKevin Wolf * callback will be called for some of the requests, for others it won't. The 453440b4f539SKevin Wolf * caller must check the error field of the BlockRequest to wait for the right 453540b4f539SKevin Wolf * callbacks (if error != 0, no callback will be called). 453640b4f539SKevin Wolf * 453740b4f539SKevin Wolf * The implementation may modify the contents of the reqs array, e.g. to merge 453840b4f539SKevin Wolf * requests. However, the fields opaque and error are left unmodified as they 453940b4f539SKevin Wolf * are used to signal failure for a single request to the caller. 454040b4f539SKevin Wolf */ 454140b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs) 454240b4f539SKevin Wolf { 454340b4f539SKevin Wolf MultiwriteCB *mcb; 454440b4f539SKevin Wolf int i; 454540b4f539SKevin Wolf 4546301db7c2SRyan Harper /* don't submit writes if we don't have a medium */ 4547301db7c2SRyan Harper if (bs->drv == NULL) { 4548301db7c2SRyan Harper for (i = 0; i < num_reqs; i++) { 4549301db7c2SRyan Harper reqs[i].error = -ENOMEDIUM; 4550301db7c2SRyan Harper } 4551301db7c2SRyan Harper return -1; 4552301db7c2SRyan Harper } 4553301db7c2SRyan Harper 455440b4f539SKevin Wolf if (num_reqs == 0) { 455540b4f539SKevin Wolf return 0; 455640b4f539SKevin Wolf } 455740b4f539SKevin Wolf 455840b4f539SKevin Wolf // Create MultiwriteCB structure 45597267c094SAnthony Liguori mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks)); 456040b4f539SKevin Wolf mcb->num_requests = 0; 456140b4f539SKevin Wolf mcb->num_callbacks = num_reqs; 456240b4f539SKevin Wolf 456340b4f539SKevin Wolf for (i = 0; i < num_reqs; i++) { 456440b4f539SKevin Wolf mcb->callbacks[i].cb = reqs[i].cb; 456540b4f539SKevin Wolf mcb->callbacks[i].opaque = reqs[i].opaque; 456640b4f539SKevin Wolf } 456740b4f539SKevin Wolf 456840b4f539SKevin Wolf // Check for mergable requests 456940b4f539SKevin Wolf num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb); 457040b4f539SKevin Wolf 45716d519a5fSStefan Hajnoczi trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs); 45726d519a5fSStefan Hajnoczi 4573df9309fbSPaolo Bonzini /* Run the aio requests. */ 4574df9309fbSPaolo Bonzini mcb->num_requests = num_reqs; 457540b4f539SKevin Wolf for (i = 0; i < num_reqs; i++) { 4576d20d9b7cSPaolo Bonzini bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov, 4577d20d9b7cSPaolo Bonzini reqs[i].nb_sectors, reqs[i].flags, 4578d20d9b7cSPaolo Bonzini multiwrite_cb, mcb, 4579d20d9b7cSPaolo Bonzini true); 458040b4f539SKevin Wolf } 458140b4f539SKevin Wolf 458240b4f539SKevin Wolf return 0; 458340b4f539SKevin Wolf } 458440b4f539SKevin Wolf 458583f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb) 458683f64091Sbellard { 4587d7331bedSStefan Hajnoczi acb->aiocb_info->cancel(acb); 458883f64091Sbellard } 458983f64091Sbellard 459083f64091Sbellard /**************************************************************/ 459183f64091Sbellard /* async block device emulation */ 459283f64091Sbellard 4593c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync { 4594c16b5a2cSChristoph Hellwig BlockDriverAIOCB common; 4595c16b5a2cSChristoph Hellwig QEMUBH *bh; 4596c16b5a2cSChristoph Hellwig int ret; 4597c16b5a2cSChristoph Hellwig /* vector translation state */ 4598c16b5a2cSChristoph Hellwig QEMUIOVector *qiov; 4599c16b5a2cSChristoph Hellwig uint8_t *bounce; 4600c16b5a2cSChristoph Hellwig int is_write; 4601c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync; 4602c16b5a2cSChristoph Hellwig 4603c16b5a2cSChristoph Hellwig static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb) 4604c16b5a2cSChristoph Hellwig { 4605b666d239SKevin Wolf BlockDriverAIOCBSync *acb = 4606b666d239SKevin Wolf container_of(blockacb, BlockDriverAIOCBSync, common); 46076a7ad299SDor Laor qemu_bh_delete(acb->bh); 460836afc451SAvi Kivity acb->bh = NULL; 4609c16b5a2cSChristoph Hellwig qemu_aio_release(acb); 4610c16b5a2cSChristoph Hellwig } 4611c16b5a2cSChristoph Hellwig 4612d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_aiocb_info = { 4613c16b5a2cSChristoph Hellwig .aiocb_size = sizeof(BlockDriverAIOCBSync), 4614c16b5a2cSChristoph Hellwig .cancel = bdrv_aio_cancel_em, 4615c16b5a2cSChristoph Hellwig }; 4616c16b5a2cSChristoph Hellwig 461783f64091Sbellard static void bdrv_aio_bh_cb(void *opaque) 4618beac80cdSbellard { 4619ce1a14dcSpbrook BlockDriverAIOCBSync *acb = opaque; 4620f141eafeSaliguori 4621f141eafeSaliguori if (!acb->is_write) 462203396148SMichael Tokarev qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size); 4623ceb42de8Saliguori qemu_vfree(acb->bounce); 4624ce1a14dcSpbrook acb->common.cb(acb->common.opaque, acb->ret); 46256a7ad299SDor Laor qemu_bh_delete(acb->bh); 462636afc451SAvi Kivity acb->bh = NULL; 4627ce1a14dcSpbrook qemu_aio_release(acb); 4628beac80cdSbellard } 4629beac80cdSbellard 4630f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs, 4631f141eafeSaliguori int64_t sector_num, 4632f141eafeSaliguori QEMUIOVector *qiov, 4633f141eafeSaliguori int nb_sectors, 4634f141eafeSaliguori BlockDriverCompletionFunc *cb, 4635f141eafeSaliguori void *opaque, 4636f141eafeSaliguori int is_write) 4637f141eafeSaliguori 4638ea2384d3Sbellard { 4639ce1a14dcSpbrook BlockDriverAIOCBSync *acb; 464083f64091Sbellard 4641d7331bedSStefan Hajnoczi acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque); 4642f141eafeSaliguori acb->is_write = is_write; 4643f141eafeSaliguori acb->qiov = qiov; 4644e268ca52Saliguori acb->bounce = qemu_blockalign(bs, qiov->size); 46452572b37aSStefan Hajnoczi acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_aio_bh_cb, acb); 4646f141eafeSaliguori 4647f141eafeSaliguori if (is_write) { 4648d5e6b161SMichael Tokarev qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size); 46491ed20acfSStefan Hajnoczi acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors); 4650f141eafeSaliguori } else { 46511ed20acfSStefan Hajnoczi acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors); 4652f141eafeSaliguori } 4653f141eafeSaliguori 4654ce1a14dcSpbrook qemu_bh_schedule(acb->bh); 4655f141eafeSaliguori 4656ce1a14dcSpbrook return &acb->common; 46577a6cba61Spbrook } 46587a6cba61Spbrook 4659f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs, 4660f141eafeSaliguori int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, 4661ce1a14dcSpbrook BlockDriverCompletionFunc *cb, void *opaque) 466283f64091Sbellard { 4663f141eafeSaliguori return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0); 466483f64091Sbellard } 466583f64091Sbellard 4666f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs, 4667f141eafeSaliguori int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, 4668f141eafeSaliguori BlockDriverCompletionFunc *cb, void *opaque) 4669f141eafeSaliguori { 4670f141eafeSaliguori return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1); 4671f141eafeSaliguori } 4672f141eafeSaliguori 467368485420SKevin Wolf 467468485420SKevin Wolf typedef struct BlockDriverAIOCBCoroutine { 467568485420SKevin Wolf BlockDriverAIOCB common; 467668485420SKevin Wolf BlockRequest req; 467768485420SKevin Wolf bool is_write; 4678d318aea9SKevin Wolf bool *done; 467968485420SKevin Wolf QEMUBH* bh; 468068485420SKevin Wolf } BlockDriverAIOCBCoroutine; 468168485420SKevin Wolf 468268485420SKevin Wolf static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb) 468368485420SKevin Wolf { 46842572b37aSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(blockacb->bs); 4685d318aea9SKevin Wolf BlockDriverAIOCBCoroutine *acb = 4686d318aea9SKevin Wolf container_of(blockacb, BlockDriverAIOCBCoroutine, common); 4687d318aea9SKevin Wolf bool done = false; 4688d318aea9SKevin Wolf 4689d318aea9SKevin Wolf acb->done = &done; 4690d318aea9SKevin Wolf while (!done) { 46912572b37aSStefan Hajnoczi aio_poll(aio_context, true); 4692d318aea9SKevin Wolf } 469368485420SKevin Wolf } 469468485420SKevin Wolf 4695d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_co_aiocb_info = { 469668485420SKevin Wolf .aiocb_size = sizeof(BlockDriverAIOCBCoroutine), 469768485420SKevin Wolf .cancel = bdrv_aio_co_cancel_em, 469868485420SKevin Wolf }; 469968485420SKevin Wolf 470035246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque) 470168485420SKevin Wolf { 470268485420SKevin Wolf BlockDriverAIOCBCoroutine *acb = opaque; 470368485420SKevin Wolf 470468485420SKevin Wolf acb->common.cb(acb->common.opaque, acb->req.error); 4705d318aea9SKevin Wolf 4706d318aea9SKevin Wolf if (acb->done) { 4707d318aea9SKevin Wolf *acb->done = true; 4708d318aea9SKevin Wolf } 4709d318aea9SKevin Wolf 471068485420SKevin Wolf qemu_bh_delete(acb->bh); 471168485420SKevin Wolf qemu_aio_release(acb); 471268485420SKevin Wolf } 471368485420SKevin Wolf 4714b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */ 4715b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque) 4716b2a61371SStefan Hajnoczi { 4717b2a61371SStefan Hajnoczi BlockDriverAIOCBCoroutine *acb = opaque; 4718b2a61371SStefan Hajnoczi BlockDriverState *bs = acb->common.bs; 4719b2a61371SStefan Hajnoczi 4720b2a61371SStefan Hajnoczi if (!acb->is_write) { 4721b2a61371SStefan Hajnoczi acb->req.error = bdrv_co_do_readv(bs, acb->req.sector, 4722d20d9b7cSPaolo Bonzini acb->req.nb_sectors, acb->req.qiov, acb->req.flags); 4723b2a61371SStefan Hajnoczi } else { 4724b2a61371SStefan Hajnoczi acb->req.error = bdrv_co_do_writev(bs, acb->req.sector, 4725d20d9b7cSPaolo Bonzini acb->req.nb_sectors, acb->req.qiov, acb->req.flags); 4726b2a61371SStefan Hajnoczi } 4727b2a61371SStefan Hajnoczi 47282572b37aSStefan Hajnoczi acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb); 4729b2a61371SStefan Hajnoczi qemu_bh_schedule(acb->bh); 4730b2a61371SStefan Hajnoczi } 4731b2a61371SStefan Hajnoczi 473268485420SKevin Wolf static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs, 473368485420SKevin Wolf int64_t sector_num, 473468485420SKevin Wolf QEMUIOVector *qiov, 473568485420SKevin Wolf int nb_sectors, 4736d20d9b7cSPaolo Bonzini BdrvRequestFlags flags, 473768485420SKevin Wolf BlockDriverCompletionFunc *cb, 473868485420SKevin Wolf void *opaque, 47398c5873d6SStefan Hajnoczi bool is_write) 474068485420SKevin Wolf { 474168485420SKevin Wolf Coroutine *co; 474268485420SKevin Wolf BlockDriverAIOCBCoroutine *acb; 474368485420SKevin Wolf 4744d7331bedSStefan Hajnoczi acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque); 474568485420SKevin Wolf acb->req.sector = sector_num; 474668485420SKevin Wolf acb->req.nb_sectors = nb_sectors; 474768485420SKevin Wolf acb->req.qiov = qiov; 4748d20d9b7cSPaolo Bonzini acb->req.flags = flags; 474968485420SKevin Wolf acb->is_write = is_write; 4750d318aea9SKevin Wolf acb->done = NULL; 475168485420SKevin Wolf 47528c5873d6SStefan Hajnoczi co = qemu_coroutine_create(bdrv_co_do_rw); 475368485420SKevin Wolf qemu_coroutine_enter(co, acb); 475468485420SKevin Wolf 475568485420SKevin Wolf return &acb->common; 475668485420SKevin Wolf } 475768485420SKevin Wolf 475807f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque) 4759b2e12bc6SChristoph Hellwig { 476007f07615SPaolo Bonzini BlockDriverAIOCBCoroutine *acb = opaque; 476107f07615SPaolo Bonzini BlockDriverState *bs = acb->common.bs; 4762b2e12bc6SChristoph Hellwig 476307f07615SPaolo Bonzini acb->req.error = bdrv_co_flush(bs); 47642572b37aSStefan Hajnoczi acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb); 4765b2e12bc6SChristoph Hellwig qemu_bh_schedule(acb->bh); 4766b2e12bc6SChristoph Hellwig } 4767b2e12bc6SChristoph Hellwig 476807f07615SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs, 4769016f5cf6SAlexander Graf BlockDriverCompletionFunc *cb, void *opaque) 4770016f5cf6SAlexander Graf { 477107f07615SPaolo Bonzini trace_bdrv_aio_flush(bs, opaque); 4772016f5cf6SAlexander Graf 477307f07615SPaolo Bonzini Coroutine *co; 477407f07615SPaolo Bonzini BlockDriverAIOCBCoroutine *acb; 4775016f5cf6SAlexander Graf 4776d7331bedSStefan Hajnoczi acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque); 4777d318aea9SKevin Wolf acb->done = NULL; 4778d318aea9SKevin Wolf 477907f07615SPaolo Bonzini co = qemu_coroutine_create(bdrv_aio_flush_co_entry); 478007f07615SPaolo Bonzini qemu_coroutine_enter(co, acb); 4781016f5cf6SAlexander Graf 4782016f5cf6SAlexander Graf return &acb->common; 4783016f5cf6SAlexander Graf } 4784016f5cf6SAlexander Graf 47854265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque) 47864265d620SPaolo Bonzini { 47874265d620SPaolo Bonzini BlockDriverAIOCBCoroutine *acb = opaque; 47884265d620SPaolo Bonzini BlockDriverState *bs = acb->common.bs; 47894265d620SPaolo Bonzini 47904265d620SPaolo Bonzini acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors); 47912572b37aSStefan Hajnoczi acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb); 47924265d620SPaolo Bonzini qemu_bh_schedule(acb->bh); 47934265d620SPaolo Bonzini } 47944265d620SPaolo Bonzini 47954265d620SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs, 47964265d620SPaolo Bonzini int64_t sector_num, int nb_sectors, 47974265d620SPaolo Bonzini BlockDriverCompletionFunc *cb, void *opaque) 47984265d620SPaolo Bonzini { 47994265d620SPaolo Bonzini Coroutine *co; 48004265d620SPaolo Bonzini BlockDriverAIOCBCoroutine *acb; 48014265d620SPaolo Bonzini 48024265d620SPaolo Bonzini trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque); 48034265d620SPaolo Bonzini 4804d7331bedSStefan Hajnoczi acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque); 48054265d620SPaolo Bonzini acb->req.sector = sector_num; 48064265d620SPaolo Bonzini acb->req.nb_sectors = nb_sectors; 4807d318aea9SKevin Wolf acb->done = NULL; 48084265d620SPaolo Bonzini co = qemu_coroutine_create(bdrv_aio_discard_co_entry); 48094265d620SPaolo Bonzini qemu_coroutine_enter(co, acb); 48104265d620SPaolo Bonzini 48114265d620SPaolo Bonzini return &acb->common; 48124265d620SPaolo Bonzini } 48134265d620SPaolo Bonzini 4814ea2384d3Sbellard void bdrv_init(void) 4815ea2384d3Sbellard { 48165efa9d5aSAnthony Liguori module_call_init(MODULE_INIT_BLOCK); 4817ea2384d3Sbellard } 4818ce1a14dcSpbrook 4819eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void) 4820eb852011SMarkus Armbruster { 4821eb852011SMarkus Armbruster use_bdrv_whitelist = 1; 4822eb852011SMarkus Armbruster bdrv_init(); 4823eb852011SMarkus Armbruster } 4824eb852011SMarkus Armbruster 4825d7331bedSStefan Hajnoczi void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs, 48266bbff9a0Saliguori BlockDriverCompletionFunc *cb, void *opaque) 48276bbff9a0Saliguori { 4828ce1a14dcSpbrook BlockDriverAIOCB *acb; 4829ce1a14dcSpbrook 4830d7331bedSStefan Hajnoczi acb = g_slice_alloc(aiocb_info->aiocb_size); 4831d7331bedSStefan Hajnoczi acb->aiocb_info = aiocb_info; 4832ce1a14dcSpbrook acb->bs = bs; 4833ce1a14dcSpbrook acb->cb = cb; 4834ce1a14dcSpbrook acb->opaque = opaque; 4835ce1a14dcSpbrook return acb; 4836ce1a14dcSpbrook } 4837ce1a14dcSpbrook 4838ce1a14dcSpbrook void qemu_aio_release(void *p) 4839ce1a14dcSpbrook { 4840d37c975fSStefan Hajnoczi BlockDriverAIOCB *acb = p; 4841d7331bedSStefan Hajnoczi g_slice_free1(acb->aiocb_info->aiocb_size, acb); 4842ce1a14dcSpbrook } 484319cb3738Sbellard 484419cb3738Sbellard /**************************************************************/ 4845f9f05dc5SKevin Wolf /* Coroutine block device emulation */ 4846f9f05dc5SKevin Wolf 4847f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion { 4848f9f05dc5SKevin Wolf Coroutine *coroutine; 4849f9f05dc5SKevin Wolf int ret; 4850f9f05dc5SKevin Wolf } CoroutineIOCompletion; 4851f9f05dc5SKevin Wolf 4852f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret) 4853f9f05dc5SKevin Wolf { 4854f9f05dc5SKevin Wolf CoroutineIOCompletion *co = opaque; 4855f9f05dc5SKevin Wolf 4856f9f05dc5SKevin Wolf co->ret = ret; 4857f9f05dc5SKevin Wolf qemu_coroutine_enter(co->coroutine, NULL); 4858f9f05dc5SKevin Wolf } 4859f9f05dc5SKevin Wolf 4860f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num, 4861f9f05dc5SKevin Wolf int nb_sectors, QEMUIOVector *iov, 4862f9f05dc5SKevin Wolf bool is_write) 4863f9f05dc5SKevin Wolf { 4864f9f05dc5SKevin Wolf CoroutineIOCompletion co = { 4865f9f05dc5SKevin Wolf .coroutine = qemu_coroutine_self(), 4866f9f05dc5SKevin Wolf }; 4867f9f05dc5SKevin Wolf BlockDriverAIOCB *acb; 4868f9f05dc5SKevin Wolf 4869f9f05dc5SKevin Wolf if (is_write) { 4870a652d160SStefan Hajnoczi acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors, 4871f9f05dc5SKevin Wolf bdrv_co_io_em_complete, &co); 4872f9f05dc5SKevin Wolf } else { 4873a652d160SStefan Hajnoczi acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors, 4874f9f05dc5SKevin Wolf bdrv_co_io_em_complete, &co); 4875f9f05dc5SKevin Wolf } 4876f9f05dc5SKevin Wolf 487759370aaaSStefan Hajnoczi trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb); 4878f9f05dc5SKevin Wolf if (!acb) { 4879f9f05dc5SKevin Wolf return -EIO; 4880f9f05dc5SKevin Wolf } 4881f9f05dc5SKevin Wolf qemu_coroutine_yield(); 4882f9f05dc5SKevin Wolf 4883f9f05dc5SKevin Wolf return co.ret; 4884f9f05dc5SKevin Wolf } 4885f9f05dc5SKevin Wolf 4886f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs, 4887f9f05dc5SKevin Wolf int64_t sector_num, int nb_sectors, 4888f9f05dc5SKevin Wolf QEMUIOVector *iov) 4889f9f05dc5SKevin Wolf { 4890f9f05dc5SKevin Wolf return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false); 4891f9f05dc5SKevin Wolf } 4892f9f05dc5SKevin Wolf 4893f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs, 4894f9f05dc5SKevin Wolf int64_t sector_num, int nb_sectors, 4895f9f05dc5SKevin Wolf QEMUIOVector *iov) 4896f9f05dc5SKevin Wolf { 4897f9f05dc5SKevin Wolf return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true); 4898f9f05dc5SKevin Wolf } 4899f9f05dc5SKevin Wolf 490007f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque) 4901e7a8a783SKevin Wolf { 490207f07615SPaolo Bonzini RwCo *rwco = opaque; 490307f07615SPaolo Bonzini 490407f07615SPaolo Bonzini rwco->ret = bdrv_co_flush(rwco->bs); 490507f07615SPaolo Bonzini } 490607f07615SPaolo Bonzini 490707f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs) 490807f07615SPaolo Bonzini { 4909eb489bb1SKevin Wolf int ret; 4910eb489bb1SKevin Wolf 491129cdb251SPaolo Bonzini if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) { 491207f07615SPaolo Bonzini return 0; 4913eb489bb1SKevin Wolf } 4914eb489bb1SKevin Wolf 4915ca716364SKevin Wolf /* Write back cached data to the OS even with cache=unsafe */ 4916bf736fe3SKevin Wolf BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS); 4917eb489bb1SKevin Wolf if (bs->drv->bdrv_co_flush_to_os) { 4918eb489bb1SKevin Wolf ret = bs->drv->bdrv_co_flush_to_os(bs); 4919eb489bb1SKevin Wolf if (ret < 0) { 4920eb489bb1SKevin Wolf return ret; 4921eb489bb1SKevin Wolf } 4922eb489bb1SKevin Wolf } 4923eb489bb1SKevin Wolf 4924ca716364SKevin Wolf /* But don't actually force it to the disk with cache=unsafe */ 4925ca716364SKevin Wolf if (bs->open_flags & BDRV_O_NO_FLUSH) { 4926d4c82329SKevin Wolf goto flush_parent; 4927ca716364SKevin Wolf } 4928ca716364SKevin Wolf 4929bf736fe3SKevin Wolf BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK); 4930eb489bb1SKevin Wolf if (bs->drv->bdrv_co_flush_to_disk) { 493129cdb251SPaolo Bonzini ret = bs->drv->bdrv_co_flush_to_disk(bs); 493207f07615SPaolo Bonzini } else if (bs->drv->bdrv_aio_flush) { 493307f07615SPaolo Bonzini BlockDriverAIOCB *acb; 4934e7a8a783SKevin Wolf CoroutineIOCompletion co = { 4935e7a8a783SKevin Wolf .coroutine = qemu_coroutine_self(), 4936e7a8a783SKevin Wolf }; 4937e7a8a783SKevin Wolf 493807f07615SPaolo Bonzini acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co); 493907f07615SPaolo Bonzini if (acb == NULL) { 494029cdb251SPaolo Bonzini ret = -EIO; 494107f07615SPaolo Bonzini } else { 4942e7a8a783SKevin Wolf qemu_coroutine_yield(); 494329cdb251SPaolo Bonzini ret = co.ret; 4944e7a8a783SKevin Wolf } 494507f07615SPaolo Bonzini } else { 494607f07615SPaolo Bonzini /* 494707f07615SPaolo Bonzini * Some block drivers always operate in either writethrough or unsafe 494807f07615SPaolo Bonzini * mode and don't support bdrv_flush therefore. Usually qemu doesn't 494907f07615SPaolo Bonzini * know how the server works (because the behaviour is hardcoded or 495007f07615SPaolo Bonzini * depends on server-side configuration), so we can't ensure that 495107f07615SPaolo Bonzini * everything is safe on disk. Returning an error doesn't work because 495207f07615SPaolo Bonzini * that would break guests even if the server operates in writethrough 495307f07615SPaolo Bonzini * mode. 495407f07615SPaolo Bonzini * 495507f07615SPaolo Bonzini * Let's hope the user knows what he's doing. 495607f07615SPaolo Bonzini */ 495729cdb251SPaolo Bonzini ret = 0; 495807f07615SPaolo Bonzini } 495929cdb251SPaolo Bonzini if (ret < 0) { 496029cdb251SPaolo Bonzini return ret; 496129cdb251SPaolo Bonzini } 496229cdb251SPaolo Bonzini 496329cdb251SPaolo Bonzini /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH 496429cdb251SPaolo Bonzini * in the case of cache=unsafe, so there are no useless flushes. 496529cdb251SPaolo Bonzini */ 4966d4c82329SKevin Wolf flush_parent: 496729cdb251SPaolo Bonzini return bdrv_co_flush(bs->file); 496807f07615SPaolo Bonzini } 496907f07615SPaolo Bonzini 49705a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp) 49710f15423cSAnthony Liguori { 49725a8a30dbSKevin Wolf Error *local_err = NULL; 49735a8a30dbSKevin Wolf int ret; 49745a8a30dbSKevin Wolf 49753456a8d1SKevin Wolf if (!bs->drv) { 49763456a8d1SKevin Wolf return; 49770f15423cSAnthony Liguori } 49783456a8d1SKevin Wolf 49793456a8d1SKevin Wolf if (bs->drv->bdrv_invalidate_cache) { 49805a8a30dbSKevin Wolf bs->drv->bdrv_invalidate_cache(bs, &local_err); 49813456a8d1SKevin Wolf } else if (bs->file) { 49825a8a30dbSKevin Wolf bdrv_invalidate_cache(bs->file, &local_err); 49835a8a30dbSKevin Wolf } 49845a8a30dbSKevin Wolf if (local_err) { 49855a8a30dbSKevin Wolf error_propagate(errp, local_err); 49865a8a30dbSKevin Wolf return; 49873456a8d1SKevin Wolf } 49883456a8d1SKevin Wolf 49895a8a30dbSKevin Wolf ret = refresh_total_sectors(bs, bs->total_sectors); 49905a8a30dbSKevin Wolf if (ret < 0) { 49915a8a30dbSKevin Wolf error_setg_errno(errp, -ret, "Could not refresh total sector count"); 49925a8a30dbSKevin Wolf return; 49935a8a30dbSKevin Wolf } 49940f15423cSAnthony Liguori } 49950f15423cSAnthony Liguori 49965a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp) 49970f15423cSAnthony Liguori { 49980f15423cSAnthony Liguori BlockDriverState *bs; 49995a8a30dbSKevin Wolf Error *local_err = NULL; 50000f15423cSAnthony Liguori 5001dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 5002ed78cda3SStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 5003ed78cda3SStefan Hajnoczi 5004ed78cda3SStefan Hajnoczi aio_context_acquire(aio_context); 50055a8a30dbSKevin Wolf bdrv_invalidate_cache(bs, &local_err); 5006ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 50075a8a30dbSKevin Wolf if (local_err) { 50085a8a30dbSKevin Wolf error_propagate(errp, local_err); 50095a8a30dbSKevin Wolf return; 50105a8a30dbSKevin Wolf } 50110f15423cSAnthony Liguori } 50120f15423cSAnthony Liguori } 50130f15423cSAnthony Liguori 501407789269SBenoît Canet void bdrv_clear_incoming_migration_all(void) 501507789269SBenoît Canet { 501607789269SBenoît Canet BlockDriverState *bs; 501707789269SBenoît Canet 5018dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 5019ed78cda3SStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 5020ed78cda3SStefan Hajnoczi 5021ed78cda3SStefan Hajnoczi aio_context_acquire(aio_context); 502207789269SBenoît Canet bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING); 5023ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 502407789269SBenoît Canet } 502507789269SBenoît Canet } 502607789269SBenoît Canet 502707f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs) 502807f07615SPaolo Bonzini { 502907f07615SPaolo Bonzini Coroutine *co; 503007f07615SPaolo Bonzini RwCo rwco = { 503107f07615SPaolo Bonzini .bs = bs, 503207f07615SPaolo Bonzini .ret = NOT_DONE, 503307f07615SPaolo Bonzini }; 503407f07615SPaolo Bonzini 503507f07615SPaolo Bonzini if (qemu_in_coroutine()) { 503607f07615SPaolo Bonzini /* Fast-path if already in coroutine context */ 503707f07615SPaolo Bonzini bdrv_flush_co_entry(&rwco); 503807f07615SPaolo Bonzini } else { 50392572b37aSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 50402572b37aSStefan Hajnoczi 504107f07615SPaolo Bonzini co = qemu_coroutine_create(bdrv_flush_co_entry); 504207f07615SPaolo Bonzini qemu_coroutine_enter(co, &rwco); 504307f07615SPaolo Bonzini while (rwco.ret == NOT_DONE) { 50442572b37aSStefan Hajnoczi aio_poll(aio_context, true); 504507f07615SPaolo Bonzini } 504607f07615SPaolo Bonzini } 504707f07615SPaolo Bonzini 504807f07615SPaolo Bonzini return rwco.ret; 504907f07615SPaolo Bonzini } 5050e7a8a783SKevin Wolf 5051775aa8b6SKevin Wolf typedef struct DiscardCo { 5052775aa8b6SKevin Wolf BlockDriverState *bs; 5053775aa8b6SKevin Wolf int64_t sector_num; 5054775aa8b6SKevin Wolf int nb_sectors; 5055775aa8b6SKevin Wolf int ret; 5056775aa8b6SKevin Wolf } DiscardCo; 50574265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque) 50584265d620SPaolo Bonzini { 5059775aa8b6SKevin Wolf DiscardCo *rwco = opaque; 50604265d620SPaolo Bonzini 50614265d620SPaolo Bonzini rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors); 50624265d620SPaolo Bonzini } 50634265d620SPaolo Bonzini 50646f14da52SPeter Lieven /* if no limit is specified in the BlockLimits use a default 50656f14da52SPeter Lieven * of 32768 512-byte sectors (16 MiB) per request. 50666f14da52SPeter Lieven */ 50676f14da52SPeter Lieven #define MAX_DISCARD_DEFAULT 32768 50686f14da52SPeter Lieven 50694265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num, 50704265d620SPaolo Bonzini int nb_sectors) 50714265d620SPaolo Bonzini { 5072d51e9fe5SPaolo Bonzini int max_discard; 5073d51e9fe5SPaolo Bonzini 50744265d620SPaolo Bonzini if (!bs->drv) { 50754265d620SPaolo Bonzini return -ENOMEDIUM; 50764265d620SPaolo Bonzini } else if (bdrv_check_request(bs, sector_num, nb_sectors)) { 50774265d620SPaolo Bonzini return -EIO; 50784265d620SPaolo Bonzini } else if (bs->read_only) { 50794265d620SPaolo Bonzini return -EROFS; 5080df702c9bSPaolo Bonzini } 5081df702c9bSPaolo Bonzini 50828f0720ecSPaolo Bonzini bdrv_reset_dirty(bs, sector_num, nb_sectors); 5083df702c9bSPaolo Bonzini 50849e8f1835SPaolo Bonzini /* Do nothing if disabled. */ 50859e8f1835SPaolo Bonzini if (!(bs->open_flags & BDRV_O_UNMAP)) { 50869e8f1835SPaolo Bonzini return 0; 50879e8f1835SPaolo Bonzini } 50889e8f1835SPaolo Bonzini 5089d51e9fe5SPaolo Bonzini if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) { 5090d51e9fe5SPaolo Bonzini return 0; 5091d51e9fe5SPaolo Bonzini } 50926f14da52SPeter Lieven 5093d51e9fe5SPaolo Bonzini max_discard = bs->bl.max_discard ? bs->bl.max_discard : MAX_DISCARD_DEFAULT; 50946f14da52SPeter Lieven while (nb_sectors > 0) { 50956f14da52SPeter Lieven int ret; 50966f14da52SPeter Lieven int num = nb_sectors; 50976f14da52SPeter Lieven 50986f14da52SPeter Lieven /* align request */ 50996f14da52SPeter Lieven if (bs->bl.discard_alignment && 51006f14da52SPeter Lieven num >= bs->bl.discard_alignment && 51016f14da52SPeter Lieven sector_num % bs->bl.discard_alignment) { 51026f14da52SPeter Lieven if (num > bs->bl.discard_alignment) { 51036f14da52SPeter Lieven num = bs->bl.discard_alignment; 51046f14da52SPeter Lieven } 51056f14da52SPeter Lieven num -= sector_num % bs->bl.discard_alignment; 51066f14da52SPeter Lieven } 51076f14da52SPeter Lieven 51086f14da52SPeter Lieven /* limit request size */ 51096f14da52SPeter Lieven if (num > max_discard) { 51106f14da52SPeter Lieven num = max_discard; 51116f14da52SPeter Lieven } 51126f14da52SPeter Lieven 5113d51e9fe5SPaolo Bonzini if (bs->drv->bdrv_co_discard) { 51146f14da52SPeter Lieven ret = bs->drv->bdrv_co_discard(bs, sector_num, num); 5115d51e9fe5SPaolo Bonzini } else { 51164265d620SPaolo Bonzini BlockDriverAIOCB *acb; 51174265d620SPaolo Bonzini CoroutineIOCompletion co = { 51184265d620SPaolo Bonzini .coroutine = qemu_coroutine_self(), 51194265d620SPaolo Bonzini }; 51204265d620SPaolo Bonzini 51214265d620SPaolo Bonzini acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors, 51224265d620SPaolo Bonzini bdrv_co_io_em_complete, &co); 51234265d620SPaolo Bonzini if (acb == NULL) { 51244265d620SPaolo Bonzini return -EIO; 51254265d620SPaolo Bonzini } else { 51264265d620SPaolo Bonzini qemu_coroutine_yield(); 5127d51e9fe5SPaolo Bonzini ret = co.ret; 51284265d620SPaolo Bonzini } 5129d51e9fe5SPaolo Bonzini } 51307ce21016SPaolo Bonzini if (ret && ret != -ENOTSUP) { 5131d51e9fe5SPaolo Bonzini return ret; 5132d51e9fe5SPaolo Bonzini } 5133d51e9fe5SPaolo Bonzini 5134d51e9fe5SPaolo Bonzini sector_num += num; 5135d51e9fe5SPaolo Bonzini nb_sectors -= num; 5136d51e9fe5SPaolo Bonzini } 51374265d620SPaolo Bonzini return 0; 51384265d620SPaolo Bonzini } 51394265d620SPaolo Bonzini 51404265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors) 51414265d620SPaolo Bonzini { 51424265d620SPaolo Bonzini Coroutine *co; 5143775aa8b6SKevin Wolf DiscardCo rwco = { 51444265d620SPaolo Bonzini .bs = bs, 51454265d620SPaolo Bonzini .sector_num = sector_num, 51464265d620SPaolo Bonzini .nb_sectors = nb_sectors, 51474265d620SPaolo Bonzini .ret = NOT_DONE, 51484265d620SPaolo Bonzini }; 51494265d620SPaolo Bonzini 51504265d620SPaolo Bonzini if (qemu_in_coroutine()) { 51514265d620SPaolo Bonzini /* Fast-path if already in coroutine context */ 51524265d620SPaolo Bonzini bdrv_discard_co_entry(&rwco); 51534265d620SPaolo Bonzini } else { 51542572b37aSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 51552572b37aSStefan Hajnoczi 51564265d620SPaolo Bonzini co = qemu_coroutine_create(bdrv_discard_co_entry); 51574265d620SPaolo Bonzini qemu_coroutine_enter(co, &rwco); 51584265d620SPaolo Bonzini while (rwco.ret == NOT_DONE) { 51592572b37aSStefan Hajnoczi aio_poll(aio_context, true); 51604265d620SPaolo Bonzini } 51614265d620SPaolo Bonzini } 51624265d620SPaolo Bonzini 51634265d620SPaolo Bonzini return rwco.ret; 51644265d620SPaolo Bonzini } 51654265d620SPaolo Bonzini 5166f9f05dc5SKevin Wolf /**************************************************************/ 516719cb3738Sbellard /* removable device support */ 516819cb3738Sbellard 516919cb3738Sbellard /** 517019cb3738Sbellard * Return TRUE if the media is present 517119cb3738Sbellard */ 517219cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs) 517319cb3738Sbellard { 517419cb3738Sbellard BlockDriver *drv = bs->drv; 5175a1aff5bfSMarkus Armbruster 517619cb3738Sbellard if (!drv) 517719cb3738Sbellard return 0; 517819cb3738Sbellard if (!drv->bdrv_is_inserted) 5179a1aff5bfSMarkus Armbruster return 1; 5180a1aff5bfSMarkus Armbruster return drv->bdrv_is_inserted(bs); 518119cb3738Sbellard } 518219cb3738Sbellard 518319cb3738Sbellard /** 51848e49ca46SMarkus Armbruster * Return whether the media changed since the last call to this 51858e49ca46SMarkus Armbruster * function, or -ENOTSUP if we don't know. Most drivers don't know. 518619cb3738Sbellard */ 518719cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs) 518819cb3738Sbellard { 518919cb3738Sbellard BlockDriver *drv = bs->drv; 519019cb3738Sbellard 51918e49ca46SMarkus Armbruster if (drv && drv->bdrv_media_changed) { 51928e49ca46SMarkus Armbruster return drv->bdrv_media_changed(bs); 51938e49ca46SMarkus Armbruster } 51948e49ca46SMarkus Armbruster return -ENOTSUP; 519519cb3738Sbellard } 519619cb3738Sbellard 519719cb3738Sbellard /** 519819cb3738Sbellard * If eject_flag is TRUE, eject the media. Otherwise, close the tray 519919cb3738Sbellard */ 5200f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag) 520119cb3738Sbellard { 520219cb3738Sbellard BlockDriver *drv = bs->drv; 520319cb3738Sbellard 5204822e1cd1SMarkus Armbruster if (drv && drv->bdrv_eject) { 5205822e1cd1SMarkus Armbruster drv->bdrv_eject(bs, eject_flag); 520619cb3738Sbellard } 52076f382ed2SLuiz Capitulino 52086f382ed2SLuiz Capitulino if (bs->device_name[0] != '\0') { 5209a5ee7bd4SWenchao Xia qapi_event_send_device_tray_moved(bdrv_get_device_name(bs), 5210a5ee7bd4SWenchao Xia eject_flag, &error_abort); 52116f382ed2SLuiz Capitulino } 521219cb3738Sbellard } 521319cb3738Sbellard 521419cb3738Sbellard /** 521519cb3738Sbellard * Lock or unlock the media (if it is locked, the user won't be able 521619cb3738Sbellard * to eject it manually). 521719cb3738Sbellard */ 5218025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked) 521919cb3738Sbellard { 522019cb3738Sbellard BlockDriver *drv = bs->drv; 522119cb3738Sbellard 5222025e849aSMarkus Armbruster trace_bdrv_lock_medium(bs, locked); 5223b8c6d095SStefan Hajnoczi 5224025e849aSMarkus Armbruster if (drv && drv->bdrv_lock_medium) { 5225025e849aSMarkus Armbruster drv->bdrv_lock_medium(bs, locked); 522619cb3738Sbellard } 522719cb3738Sbellard } 5228985a03b0Sths 5229985a03b0Sths /* needed for generic scsi interface */ 5230985a03b0Sths 5231985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf) 5232985a03b0Sths { 5233985a03b0Sths BlockDriver *drv = bs->drv; 5234985a03b0Sths 5235985a03b0Sths if (drv && drv->bdrv_ioctl) 5236985a03b0Sths return drv->bdrv_ioctl(bs, req, buf); 5237985a03b0Sths return -ENOTSUP; 5238985a03b0Sths } 52397d780669Saliguori 5240221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs, 5241221f715dSaliguori unsigned long int req, void *buf, 52427d780669Saliguori BlockDriverCompletionFunc *cb, void *opaque) 52437d780669Saliguori { 5244221f715dSaliguori BlockDriver *drv = bs->drv; 52457d780669Saliguori 5246221f715dSaliguori if (drv && drv->bdrv_aio_ioctl) 5247221f715dSaliguori return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque); 5248221f715dSaliguori return NULL; 52497d780669Saliguori } 5250e268ca52Saliguori 52511b7fd729SPaolo Bonzini void bdrv_set_guest_block_size(BlockDriverState *bs, int align) 52527b6f9300SMarkus Armbruster { 52531b7fd729SPaolo Bonzini bs->guest_block_size = align; 52547b6f9300SMarkus Armbruster } 52557cd1e32aSlirans@il.ibm.com 5256e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size) 5257e268ca52Saliguori { 5258339064d5SKevin Wolf return qemu_memalign(bdrv_opt_mem_align(bs), size); 5259e268ca52Saliguori } 52607cd1e32aSlirans@il.ibm.com 5261c53b1c51SStefan Hajnoczi /* 5262c53b1c51SStefan Hajnoczi * Check if all memory in this vector is sector aligned. 5263c53b1c51SStefan Hajnoczi */ 5264c53b1c51SStefan Hajnoczi bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov) 5265c53b1c51SStefan Hajnoczi { 5266c53b1c51SStefan Hajnoczi int i; 5267339064d5SKevin Wolf size_t alignment = bdrv_opt_mem_align(bs); 5268c53b1c51SStefan Hajnoczi 5269c53b1c51SStefan Hajnoczi for (i = 0; i < qiov->niov; i++) { 5270339064d5SKevin Wolf if ((uintptr_t) qiov->iov[i].iov_base % alignment) { 5271c53b1c51SStefan Hajnoczi return false; 5272c53b1c51SStefan Hajnoczi } 5273339064d5SKevin Wolf if (qiov->iov[i].iov_len % alignment) { 52741ff735bdSKevin Wolf return false; 52751ff735bdSKevin Wolf } 5276c53b1c51SStefan Hajnoczi } 5277c53b1c51SStefan Hajnoczi 5278c53b1c51SStefan Hajnoczi return true; 5279c53b1c51SStefan Hajnoczi } 5280c53b1c51SStefan Hajnoczi 5281b8afb520SFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs, int granularity, 5282b8afb520SFam Zheng Error **errp) 52837cd1e32aSlirans@il.ibm.com { 52847cd1e32aSlirans@il.ibm.com int64_t bitmap_size; 5285e4654d2dSFam Zheng BdrvDirtyBitmap *bitmap; 5286a55eb92cSJan Kiszka 528750717e94SPaolo Bonzini assert((granularity & (granularity - 1)) == 0); 528850717e94SPaolo Bonzini 528950717e94SPaolo Bonzini granularity >>= BDRV_SECTOR_BITS; 5290e4654d2dSFam Zheng assert(granularity); 529157322b78SMarkus Armbruster bitmap_size = bdrv_nb_sectors(bs); 5292b8afb520SFam Zheng if (bitmap_size < 0) { 5293b8afb520SFam Zheng error_setg_errno(errp, -bitmap_size, "could not get length of device"); 5294b8afb520SFam Zheng errno = -bitmap_size; 5295b8afb520SFam Zheng return NULL; 5296b8afb520SFam Zheng } 5297e4654d2dSFam Zheng bitmap = g_malloc0(sizeof(BdrvDirtyBitmap)); 5298e4654d2dSFam Zheng bitmap->bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1); 5299e4654d2dSFam Zheng QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list); 5300e4654d2dSFam Zheng return bitmap; 5301e4654d2dSFam Zheng } 5302e4654d2dSFam Zheng 5303e4654d2dSFam Zheng void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap) 5304e4654d2dSFam Zheng { 5305e4654d2dSFam Zheng BdrvDirtyBitmap *bm, *next; 5306e4654d2dSFam Zheng QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) { 5307e4654d2dSFam Zheng if (bm == bitmap) { 5308e4654d2dSFam Zheng QLIST_REMOVE(bitmap, list); 5309e4654d2dSFam Zheng hbitmap_free(bitmap->bitmap); 5310e4654d2dSFam Zheng g_free(bitmap); 5311e4654d2dSFam Zheng return; 53127cd1e32aSlirans@il.ibm.com } 53137cd1e32aSlirans@il.ibm.com } 53147cd1e32aSlirans@il.ibm.com } 53157cd1e32aSlirans@il.ibm.com 531621b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs) 531721b56835SFam Zheng { 531821b56835SFam Zheng BdrvDirtyBitmap *bm; 531921b56835SFam Zheng BlockDirtyInfoList *list = NULL; 532021b56835SFam Zheng BlockDirtyInfoList **plist = &list; 532121b56835SFam Zheng 532221b56835SFam Zheng QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) { 532321b56835SFam Zheng BlockDirtyInfo *info = g_malloc0(sizeof(BlockDirtyInfo)); 532421b56835SFam Zheng BlockDirtyInfoList *entry = g_malloc0(sizeof(BlockDirtyInfoList)); 532521b56835SFam Zheng info->count = bdrv_get_dirty_count(bs, bm); 532621b56835SFam Zheng info->granularity = 532721b56835SFam Zheng ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bm->bitmap)); 532821b56835SFam Zheng entry->value = info; 532921b56835SFam Zheng *plist = entry; 533021b56835SFam Zheng plist = &entry->next; 533121b56835SFam Zheng } 533221b56835SFam Zheng 533321b56835SFam Zheng return list; 533421b56835SFam Zheng } 533521b56835SFam Zheng 5336e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector) 53377cd1e32aSlirans@il.ibm.com { 5338e4654d2dSFam Zheng if (bitmap) { 5339e4654d2dSFam Zheng return hbitmap_get(bitmap->bitmap, sector); 53407cd1e32aSlirans@il.ibm.com } else { 53417cd1e32aSlirans@il.ibm.com return 0; 53427cd1e32aSlirans@il.ibm.com } 53437cd1e32aSlirans@il.ibm.com } 53447cd1e32aSlirans@il.ibm.com 5345e4654d2dSFam Zheng void bdrv_dirty_iter_init(BlockDriverState *bs, 5346e4654d2dSFam Zheng BdrvDirtyBitmap *bitmap, HBitmapIter *hbi) 53471755da16SPaolo Bonzini { 5348e4654d2dSFam Zheng hbitmap_iter_init(hbi, bitmap->bitmap, 0); 53491755da16SPaolo Bonzini } 53501755da16SPaolo Bonzini 53511755da16SPaolo Bonzini void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector, 53521755da16SPaolo Bonzini int nr_sectors) 53531755da16SPaolo Bonzini { 5354e4654d2dSFam Zheng BdrvDirtyBitmap *bitmap; 5355e4654d2dSFam Zheng QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) { 5356e4654d2dSFam Zheng hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors); 5357e4654d2dSFam Zheng } 53581755da16SPaolo Bonzini } 53591755da16SPaolo Bonzini 5360e4654d2dSFam Zheng void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors) 53617cd1e32aSlirans@il.ibm.com { 5362e4654d2dSFam Zheng BdrvDirtyBitmap *bitmap; 5363e4654d2dSFam Zheng QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) { 5364e4654d2dSFam Zheng hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors); 5365e4654d2dSFam Zheng } 53667cd1e32aSlirans@il.ibm.com } 5367aaa0eb75SLiran Schour 5368e4654d2dSFam Zheng int64_t bdrv_get_dirty_count(BlockDriverState *bs, BdrvDirtyBitmap *bitmap) 5369aaa0eb75SLiran Schour { 5370e4654d2dSFam Zheng return hbitmap_count(bitmap->bitmap); 5371aaa0eb75SLiran Schour } 5372f88e1a42SJes Sorensen 53739fcb0251SFam Zheng /* Get a reference to bs */ 53749fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs) 53759fcb0251SFam Zheng { 53769fcb0251SFam Zheng bs->refcnt++; 53779fcb0251SFam Zheng } 53789fcb0251SFam Zheng 53799fcb0251SFam Zheng /* Release a previously grabbed reference to bs. 53809fcb0251SFam Zheng * If after releasing, reference count is zero, the BlockDriverState is 53819fcb0251SFam Zheng * deleted. */ 53829fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs) 53839fcb0251SFam Zheng { 53849fcb0251SFam Zheng assert(bs->refcnt > 0); 53859fcb0251SFam Zheng if (--bs->refcnt == 0) { 53869fcb0251SFam Zheng bdrv_delete(bs); 53879fcb0251SFam Zheng } 53889fcb0251SFam Zheng } 53899fcb0251SFam Zheng 5390fbe40ff7SFam Zheng struct BdrvOpBlocker { 5391fbe40ff7SFam Zheng Error *reason; 5392fbe40ff7SFam Zheng QLIST_ENTRY(BdrvOpBlocker) list; 5393fbe40ff7SFam Zheng }; 5394fbe40ff7SFam Zheng 5395fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp) 5396fbe40ff7SFam Zheng { 5397fbe40ff7SFam Zheng BdrvOpBlocker *blocker; 5398fbe40ff7SFam Zheng assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX); 5399fbe40ff7SFam Zheng if (!QLIST_EMPTY(&bs->op_blockers[op])) { 5400fbe40ff7SFam Zheng blocker = QLIST_FIRST(&bs->op_blockers[op]); 5401fbe40ff7SFam Zheng if (errp) { 5402fbe40ff7SFam Zheng error_setg(errp, "Device '%s' is busy: %s", 5403fbe40ff7SFam Zheng bs->device_name, error_get_pretty(blocker->reason)); 5404fbe40ff7SFam Zheng } 5405fbe40ff7SFam Zheng return true; 5406fbe40ff7SFam Zheng } 5407fbe40ff7SFam Zheng return false; 5408fbe40ff7SFam Zheng } 5409fbe40ff7SFam Zheng 5410fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason) 5411fbe40ff7SFam Zheng { 5412fbe40ff7SFam Zheng BdrvOpBlocker *blocker; 5413fbe40ff7SFam Zheng assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX); 5414fbe40ff7SFam Zheng 5415fbe40ff7SFam Zheng blocker = g_malloc0(sizeof(BdrvOpBlocker)); 5416fbe40ff7SFam Zheng blocker->reason = reason; 5417fbe40ff7SFam Zheng QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list); 5418fbe40ff7SFam Zheng } 5419fbe40ff7SFam Zheng 5420fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason) 5421fbe40ff7SFam Zheng { 5422fbe40ff7SFam Zheng BdrvOpBlocker *blocker, *next; 5423fbe40ff7SFam Zheng assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX); 5424fbe40ff7SFam Zheng QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) { 5425fbe40ff7SFam Zheng if (blocker->reason == reason) { 5426fbe40ff7SFam Zheng QLIST_REMOVE(blocker, list); 5427fbe40ff7SFam Zheng g_free(blocker); 5428fbe40ff7SFam Zheng } 5429fbe40ff7SFam Zheng } 5430fbe40ff7SFam Zheng } 5431fbe40ff7SFam Zheng 5432fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason) 5433fbe40ff7SFam Zheng { 5434fbe40ff7SFam Zheng int i; 5435fbe40ff7SFam Zheng for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { 5436fbe40ff7SFam Zheng bdrv_op_block(bs, i, reason); 5437fbe40ff7SFam Zheng } 5438fbe40ff7SFam Zheng } 5439fbe40ff7SFam Zheng 5440fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason) 5441fbe40ff7SFam Zheng { 5442fbe40ff7SFam Zheng int i; 5443fbe40ff7SFam Zheng for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { 5444fbe40ff7SFam Zheng bdrv_op_unblock(bs, i, reason); 5445fbe40ff7SFam Zheng } 5446fbe40ff7SFam Zheng } 5447fbe40ff7SFam Zheng 5448fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs) 5449fbe40ff7SFam Zheng { 5450fbe40ff7SFam Zheng int i; 5451fbe40ff7SFam Zheng 5452fbe40ff7SFam Zheng for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { 5453fbe40ff7SFam Zheng if (!QLIST_EMPTY(&bs->op_blockers[i])) { 5454fbe40ff7SFam Zheng return false; 5455fbe40ff7SFam Zheng } 5456fbe40ff7SFam Zheng } 5457fbe40ff7SFam Zheng return true; 5458fbe40ff7SFam Zheng } 5459fbe40ff7SFam Zheng 546028a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs) 546128a7282aSLuiz Capitulino { 5462d6bf279eSLuiz Capitulino bs->iostatus_enabled = true; 546358e21ef5SLuiz Capitulino bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK; 546428a7282aSLuiz Capitulino } 546528a7282aSLuiz Capitulino 546628a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly 546728a7282aSLuiz Capitulino * enables it _and_ the VM is configured to stop on errors */ 546828a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs) 546928a7282aSLuiz Capitulino { 5470d6bf279eSLuiz Capitulino return (bs->iostatus_enabled && 547192aa5c6dSPaolo Bonzini (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC || 547292aa5c6dSPaolo Bonzini bs->on_write_error == BLOCKDEV_ON_ERROR_STOP || 547392aa5c6dSPaolo Bonzini bs->on_read_error == BLOCKDEV_ON_ERROR_STOP)); 547428a7282aSLuiz Capitulino } 547528a7282aSLuiz Capitulino 547628a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs) 547728a7282aSLuiz Capitulino { 5478d6bf279eSLuiz Capitulino bs->iostatus_enabled = false; 547928a7282aSLuiz Capitulino } 548028a7282aSLuiz Capitulino 548128a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs) 548228a7282aSLuiz Capitulino { 548328a7282aSLuiz Capitulino if (bdrv_iostatus_is_enabled(bs)) { 548458e21ef5SLuiz Capitulino bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK; 54853bd293c3SPaolo Bonzini if (bs->job) { 54863bd293c3SPaolo Bonzini block_job_iostatus_reset(bs->job); 54873bd293c3SPaolo Bonzini } 548828a7282aSLuiz Capitulino } 548928a7282aSLuiz Capitulino } 549028a7282aSLuiz Capitulino 549128a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error) 549228a7282aSLuiz Capitulino { 54933e1caa5fSPaolo Bonzini assert(bdrv_iostatus_is_enabled(bs)); 54943e1caa5fSPaolo Bonzini if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) { 549558e21ef5SLuiz Capitulino bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE : 549658e21ef5SLuiz Capitulino BLOCK_DEVICE_IO_STATUS_FAILED; 549728a7282aSLuiz Capitulino } 549828a7282aSLuiz Capitulino } 549928a7282aSLuiz Capitulino 5500a597e79cSChristoph Hellwig void 5501a597e79cSChristoph Hellwig bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes, 5502a597e79cSChristoph Hellwig enum BlockAcctType type) 5503a597e79cSChristoph Hellwig { 5504a597e79cSChristoph Hellwig assert(type < BDRV_MAX_IOTYPE); 5505a597e79cSChristoph Hellwig 5506a597e79cSChristoph Hellwig cookie->bytes = bytes; 5507c488c7f6SChristoph Hellwig cookie->start_time_ns = get_clock(); 5508a597e79cSChristoph Hellwig cookie->type = type; 5509a597e79cSChristoph Hellwig } 5510a597e79cSChristoph Hellwig 5511a597e79cSChristoph Hellwig void 5512a597e79cSChristoph Hellwig bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie) 5513a597e79cSChristoph Hellwig { 5514a597e79cSChristoph Hellwig assert(cookie->type < BDRV_MAX_IOTYPE); 5515a597e79cSChristoph Hellwig 5516a597e79cSChristoph Hellwig bs->nr_bytes[cookie->type] += cookie->bytes; 5517a597e79cSChristoph Hellwig bs->nr_ops[cookie->type]++; 5518c488c7f6SChristoph Hellwig bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns; 5519a597e79cSChristoph Hellwig } 5520a597e79cSChristoph Hellwig 5521d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt, 5522f88e1a42SJes Sorensen const char *base_filename, const char *base_fmt, 5523f382d43aSMiroslav Rezanina char *options, uint64_t img_size, int flags, 5524f382d43aSMiroslav Rezanina Error **errp, bool quiet) 5525f88e1a42SJes Sorensen { 552683d0521aSChunyan Liu QemuOptsList *create_opts = NULL; 552783d0521aSChunyan Liu QemuOpts *opts = NULL; 552883d0521aSChunyan Liu const char *backing_fmt, *backing_file; 552983d0521aSChunyan Liu int64_t size; 5530f88e1a42SJes Sorensen BlockDriver *drv, *proto_drv; 553196df67d1SStefan Hajnoczi BlockDriver *backing_drv = NULL; 5532cc84d90fSMax Reitz Error *local_err = NULL; 5533f88e1a42SJes Sorensen int ret = 0; 5534f88e1a42SJes Sorensen 5535f88e1a42SJes Sorensen /* Find driver and parse its options */ 5536f88e1a42SJes Sorensen drv = bdrv_find_format(fmt); 5537f88e1a42SJes Sorensen if (!drv) { 553871c79813SLuiz Capitulino error_setg(errp, "Unknown file format '%s'", fmt); 5539d92ada22SLuiz Capitulino return; 5540f88e1a42SJes Sorensen } 5541f88e1a42SJes Sorensen 554298289620SKevin Wolf proto_drv = bdrv_find_protocol(filename, true); 5543f88e1a42SJes Sorensen if (!proto_drv) { 554471c79813SLuiz Capitulino error_setg(errp, "Unknown protocol '%s'", filename); 5545d92ada22SLuiz Capitulino return; 5546f88e1a42SJes Sorensen } 5547f88e1a42SJes Sorensen 5548c282e1fdSChunyan Liu create_opts = qemu_opts_append(create_opts, drv->create_opts); 5549c282e1fdSChunyan Liu create_opts = qemu_opts_append(create_opts, proto_drv->create_opts); 5550f88e1a42SJes Sorensen 5551f88e1a42SJes Sorensen /* Create parameter list with default values */ 555283d0521aSChunyan Liu opts = qemu_opts_create(create_opts, NULL, 0, &error_abort); 555383d0521aSChunyan Liu qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size); 5554f88e1a42SJes Sorensen 5555f88e1a42SJes Sorensen /* Parse -o options */ 5556f88e1a42SJes Sorensen if (options) { 555783d0521aSChunyan Liu if (qemu_opts_do_parse(opts, options, NULL) != 0) { 555883d0521aSChunyan Liu error_setg(errp, "Invalid options for file format '%s'", fmt); 5559f88e1a42SJes Sorensen goto out; 5560f88e1a42SJes Sorensen } 5561f88e1a42SJes Sorensen } 5562f88e1a42SJes Sorensen 5563f88e1a42SJes Sorensen if (base_filename) { 556483d0521aSChunyan Liu if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename)) { 556571c79813SLuiz Capitulino error_setg(errp, "Backing file not supported for file format '%s'", 556671c79813SLuiz Capitulino fmt); 5567f88e1a42SJes Sorensen goto out; 5568f88e1a42SJes Sorensen } 5569f88e1a42SJes Sorensen } 5570f88e1a42SJes Sorensen 5571f88e1a42SJes Sorensen if (base_fmt) { 557283d0521aSChunyan Liu if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt)) { 557371c79813SLuiz Capitulino error_setg(errp, "Backing file format not supported for file " 557471c79813SLuiz Capitulino "format '%s'", fmt); 5575f88e1a42SJes Sorensen goto out; 5576f88e1a42SJes Sorensen } 5577f88e1a42SJes Sorensen } 5578f88e1a42SJes Sorensen 557983d0521aSChunyan Liu backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE); 558083d0521aSChunyan Liu if (backing_file) { 558183d0521aSChunyan Liu if (!strcmp(filename, backing_file)) { 558271c79813SLuiz Capitulino error_setg(errp, "Error: Trying to create an image with the " 558371c79813SLuiz Capitulino "same filename as the backing file"); 5584792da93aSJes Sorensen goto out; 5585792da93aSJes Sorensen } 5586792da93aSJes Sorensen } 5587792da93aSJes Sorensen 558883d0521aSChunyan Liu backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT); 558983d0521aSChunyan Liu if (backing_fmt) { 559083d0521aSChunyan Liu backing_drv = bdrv_find_format(backing_fmt); 559196df67d1SStefan Hajnoczi if (!backing_drv) { 559271c79813SLuiz Capitulino error_setg(errp, "Unknown backing file format '%s'", 559383d0521aSChunyan Liu backing_fmt); 5594f88e1a42SJes Sorensen goto out; 5595f88e1a42SJes Sorensen } 5596f88e1a42SJes Sorensen } 5597f88e1a42SJes Sorensen 5598f88e1a42SJes Sorensen // The size for the image must always be specified, with one exception: 5599f88e1a42SJes Sorensen // If we are using a backing file, we can obtain the size from there 560083d0521aSChunyan Liu size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0); 560183d0521aSChunyan Liu if (size == -1) { 560283d0521aSChunyan Liu if (backing_file) { 560366f6b814SMax Reitz BlockDriverState *bs; 560452bf1e72SMarkus Armbruster int64_t size; 560563090dacSPaolo Bonzini int back_flags; 560663090dacSPaolo Bonzini 560763090dacSPaolo Bonzini /* backing files always opened read-only */ 560863090dacSPaolo Bonzini back_flags = 560963090dacSPaolo Bonzini flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING); 5610f88e1a42SJes Sorensen 5611f67503e5SMax Reitz bs = NULL; 561283d0521aSChunyan Liu ret = bdrv_open(&bs, backing_file, NULL, NULL, back_flags, 5613cc84d90fSMax Reitz backing_drv, &local_err); 5614f88e1a42SJes Sorensen if (ret < 0) { 5615cc84d90fSMax Reitz error_setg_errno(errp, -ret, "Could not open '%s': %s", 561683d0521aSChunyan Liu backing_file, 5617cc84d90fSMax Reitz error_get_pretty(local_err)); 5618cc84d90fSMax Reitz error_free(local_err); 5619cc84d90fSMax Reitz local_err = NULL; 5620f88e1a42SJes Sorensen goto out; 5621f88e1a42SJes Sorensen } 562252bf1e72SMarkus Armbruster size = bdrv_getlength(bs); 562352bf1e72SMarkus Armbruster if (size < 0) { 562452bf1e72SMarkus Armbruster error_setg_errno(errp, -size, "Could not get size of '%s'", 562552bf1e72SMarkus Armbruster backing_file); 562652bf1e72SMarkus Armbruster bdrv_unref(bs); 562752bf1e72SMarkus Armbruster goto out; 562852bf1e72SMarkus Armbruster } 5629f88e1a42SJes Sorensen 563083d0521aSChunyan Liu qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size); 563166f6b814SMax Reitz 563266f6b814SMax Reitz bdrv_unref(bs); 5633f88e1a42SJes Sorensen } else { 563471c79813SLuiz Capitulino error_setg(errp, "Image creation needs a size parameter"); 5635f88e1a42SJes Sorensen goto out; 5636f88e1a42SJes Sorensen } 5637f88e1a42SJes Sorensen } 5638f88e1a42SJes Sorensen 5639f382d43aSMiroslav Rezanina if (!quiet) { 5640f88e1a42SJes Sorensen printf("Formatting '%s', fmt=%s ", filename, fmt); 564183d0521aSChunyan Liu qemu_opts_print(opts); 5642f88e1a42SJes Sorensen puts(""); 5643f382d43aSMiroslav Rezanina } 564483d0521aSChunyan Liu 5645c282e1fdSChunyan Liu ret = bdrv_create(drv, filename, opts, &local_err); 564683d0521aSChunyan Liu 5647cc84d90fSMax Reitz if (ret == -EFBIG) { 5648cc84d90fSMax Reitz /* This is generally a better message than whatever the driver would 5649cc84d90fSMax Reitz * deliver (especially because of the cluster_size_hint), since that 5650cc84d90fSMax Reitz * is most probably not much different from "image too large". */ 5651f3f4d2c0SKevin Wolf const char *cluster_size_hint = ""; 565283d0521aSChunyan Liu if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) { 5653f3f4d2c0SKevin Wolf cluster_size_hint = " (try using a larger cluster size)"; 5654f3f4d2c0SKevin Wolf } 5655cc84d90fSMax Reitz error_setg(errp, "The image size is too large for file format '%s'" 5656cc84d90fSMax Reitz "%s", fmt, cluster_size_hint); 5657cc84d90fSMax Reitz error_free(local_err); 5658cc84d90fSMax Reitz local_err = NULL; 5659f88e1a42SJes Sorensen } 5660f88e1a42SJes Sorensen 5661f88e1a42SJes Sorensen out: 566283d0521aSChunyan Liu qemu_opts_del(opts); 566383d0521aSChunyan Liu qemu_opts_free(create_opts); 566484d18f06SMarkus Armbruster if (local_err) { 5665cc84d90fSMax Reitz error_propagate(errp, local_err); 5666cc84d90fSMax Reitz } 5667f88e1a42SJes Sorensen } 566885d126f3SStefan Hajnoczi 566985d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs) 567085d126f3SStefan Hajnoczi { 5671dcd04228SStefan Hajnoczi return bs->aio_context; 5672dcd04228SStefan Hajnoczi } 5673dcd04228SStefan Hajnoczi 5674dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs) 5675dcd04228SStefan Hajnoczi { 5676dcd04228SStefan Hajnoczi if (!bs->drv) { 5677dcd04228SStefan Hajnoczi return; 5678dcd04228SStefan Hajnoczi } 5679dcd04228SStefan Hajnoczi 568013af91ebSStefan Hajnoczi if (bs->io_limits_enabled) { 568113af91ebSStefan Hajnoczi throttle_detach_aio_context(&bs->throttle_state); 568213af91ebSStefan Hajnoczi } 5683dcd04228SStefan Hajnoczi if (bs->drv->bdrv_detach_aio_context) { 5684dcd04228SStefan Hajnoczi bs->drv->bdrv_detach_aio_context(bs); 5685dcd04228SStefan Hajnoczi } 5686dcd04228SStefan Hajnoczi if (bs->file) { 5687dcd04228SStefan Hajnoczi bdrv_detach_aio_context(bs->file); 5688dcd04228SStefan Hajnoczi } 5689dcd04228SStefan Hajnoczi if (bs->backing_hd) { 5690dcd04228SStefan Hajnoczi bdrv_detach_aio_context(bs->backing_hd); 5691dcd04228SStefan Hajnoczi } 5692dcd04228SStefan Hajnoczi 5693dcd04228SStefan Hajnoczi bs->aio_context = NULL; 5694dcd04228SStefan Hajnoczi } 5695dcd04228SStefan Hajnoczi 5696dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs, 5697dcd04228SStefan Hajnoczi AioContext *new_context) 5698dcd04228SStefan Hajnoczi { 5699dcd04228SStefan Hajnoczi if (!bs->drv) { 5700dcd04228SStefan Hajnoczi return; 5701dcd04228SStefan Hajnoczi } 5702dcd04228SStefan Hajnoczi 5703dcd04228SStefan Hajnoczi bs->aio_context = new_context; 5704dcd04228SStefan Hajnoczi 5705dcd04228SStefan Hajnoczi if (bs->backing_hd) { 5706dcd04228SStefan Hajnoczi bdrv_attach_aio_context(bs->backing_hd, new_context); 5707dcd04228SStefan Hajnoczi } 5708dcd04228SStefan Hajnoczi if (bs->file) { 5709dcd04228SStefan Hajnoczi bdrv_attach_aio_context(bs->file, new_context); 5710dcd04228SStefan Hajnoczi } 5711dcd04228SStefan Hajnoczi if (bs->drv->bdrv_attach_aio_context) { 5712dcd04228SStefan Hajnoczi bs->drv->bdrv_attach_aio_context(bs, new_context); 5713dcd04228SStefan Hajnoczi } 571413af91ebSStefan Hajnoczi if (bs->io_limits_enabled) { 571513af91ebSStefan Hajnoczi throttle_attach_aio_context(&bs->throttle_state, new_context); 571613af91ebSStefan Hajnoczi } 5717dcd04228SStefan Hajnoczi } 5718dcd04228SStefan Hajnoczi 5719dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context) 5720dcd04228SStefan Hajnoczi { 5721dcd04228SStefan Hajnoczi bdrv_drain_all(); /* ensure there are no in-flight requests */ 5722dcd04228SStefan Hajnoczi 5723dcd04228SStefan Hajnoczi bdrv_detach_aio_context(bs); 5724dcd04228SStefan Hajnoczi 5725dcd04228SStefan Hajnoczi /* This function executes in the old AioContext so acquire the new one in 5726dcd04228SStefan Hajnoczi * case it runs in a different thread. 5727dcd04228SStefan Hajnoczi */ 5728dcd04228SStefan Hajnoczi aio_context_acquire(new_context); 5729dcd04228SStefan Hajnoczi bdrv_attach_aio_context(bs, new_context); 5730dcd04228SStefan Hajnoczi aio_context_release(new_context); 573185d126f3SStefan Hajnoczi } 5732d616b224SStefan Hajnoczi 5733d616b224SStefan Hajnoczi void bdrv_add_before_write_notifier(BlockDriverState *bs, 5734d616b224SStefan Hajnoczi NotifierWithReturn *notifier) 5735d616b224SStefan Hajnoczi { 5736d616b224SStefan Hajnoczi notifier_with_return_list_add(&bs->before_write_notifiers, notifier); 5737d616b224SStefan Hajnoczi } 57386f176b48SMax Reitz 5739c282e1fdSChunyan Liu int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts) 57406f176b48SMax Reitz { 5741c282e1fdSChunyan Liu if (!bs->drv->bdrv_amend_options) { 57426f176b48SMax Reitz return -ENOTSUP; 57436f176b48SMax Reitz } 5744c282e1fdSChunyan Liu return bs->drv->bdrv_amend_options(bs, opts); 57456f176b48SMax Reitz } 5746f6186f49SBenoît Canet 5747b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method 5748b5042a36SBenoît Canet * of block filter and by bdrv_is_first_non_filter. 5749b5042a36SBenoît Canet * It is used to test if the given bs is the candidate or recurse more in the 5750b5042a36SBenoît Canet * node graph. 5751212a5a8fSBenoît Canet */ 5752212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs, 5753212a5a8fSBenoît Canet BlockDriverState *candidate) 5754f6186f49SBenoît Canet { 5755b5042a36SBenoît Canet /* return false if basic checks fails */ 5756b5042a36SBenoît Canet if (!bs || !bs->drv) { 5757b5042a36SBenoît Canet return false; 5758b5042a36SBenoît Canet } 5759b5042a36SBenoît Canet 5760b5042a36SBenoît Canet /* the code reached a non block filter driver -> check if the bs is 5761b5042a36SBenoît Canet * the same as the candidate. It's the recursion termination condition. 5762b5042a36SBenoît Canet */ 5763b5042a36SBenoît Canet if (!bs->drv->is_filter) { 5764b5042a36SBenoît Canet return bs == candidate; 5765b5042a36SBenoît Canet } 5766b5042a36SBenoît Canet /* Down this path the driver is a block filter driver */ 5767b5042a36SBenoît Canet 5768b5042a36SBenoît Canet /* If the block filter recursion method is defined use it to recurse down 5769b5042a36SBenoît Canet * the node graph. 5770b5042a36SBenoît Canet */ 5771b5042a36SBenoît Canet if (bs->drv->bdrv_recurse_is_first_non_filter) { 5772212a5a8fSBenoît Canet return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate); 5773212a5a8fSBenoît Canet } 5774212a5a8fSBenoît Canet 5775b5042a36SBenoît Canet /* the driver is a block filter but don't allow to recurse -> return false 5776b5042a36SBenoît Canet */ 5777b5042a36SBenoît Canet return false; 5778212a5a8fSBenoît Canet } 5779212a5a8fSBenoît Canet 5780212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's 5781212a5a8fSBenoît Canet * bs chain. Since we don't have pointers to parents it explore all bs chains 5782212a5a8fSBenoît Canet * from the top. Some filters can choose not to pass down the recursion. 5783212a5a8fSBenoît Canet */ 5784212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate) 5785212a5a8fSBenoît Canet { 5786212a5a8fSBenoît Canet BlockDriverState *bs; 5787212a5a8fSBenoît Canet 5788212a5a8fSBenoît Canet /* walk down the bs forest recursively */ 5789212a5a8fSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 5790212a5a8fSBenoît Canet bool perm; 5791212a5a8fSBenoît Canet 5792b5042a36SBenoît Canet /* try to recurse in this top level bs */ 5793e6dc8a1fSKevin Wolf perm = bdrv_recurse_is_first_non_filter(bs, candidate); 5794212a5a8fSBenoît Canet 5795212a5a8fSBenoît Canet /* candidate is the first non filter */ 5796212a5a8fSBenoît Canet if (perm) { 5797212a5a8fSBenoît Canet return true; 5798212a5a8fSBenoît Canet } 5799212a5a8fSBenoît Canet } 5800212a5a8fSBenoît Canet 5801212a5a8fSBenoît Canet return false; 5802f6186f49SBenoît Canet } 580309158f00SBenoît Canet 580409158f00SBenoît Canet BlockDriverState *check_to_replace_node(const char *node_name, Error **errp) 580509158f00SBenoît Canet { 580609158f00SBenoît Canet BlockDriverState *to_replace_bs = bdrv_find_node(node_name); 580709158f00SBenoît Canet if (!to_replace_bs) { 580809158f00SBenoît Canet error_setg(errp, "Node name '%s' not found", node_name); 580909158f00SBenoît Canet return NULL; 581009158f00SBenoît Canet } 581109158f00SBenoît Canet 581209158f00SBenoît Canet if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) { 581309158f00SBenoît Canet return NULL; 581409158f00SBenoît Canet } 581509158f00SBenoît Canet 581609158f00SBenoît Canet /* We don't want arbitrary node of the BDS chain to be replaced only the top 581709158f00SBenoît Canet * most non filter in order to prevent data corruption. 581809158f00SBenoît Canet * Another benefit is that this tests exclude backing files which are 581909158f00SBenoît Canet * blocked by the backing blockers. 582009158f00SBenoît Canet */ 582109158f00SBenoît Canet if (!bdrv_is_first_non_filter(to_replace_bs)) { 582209158f00SBenoît Canet error_setg(errp, "Only top most non filter can be replaced"); 582309158f00SBenoît Canet return NULL; 582409158f00SBenoît Canet } 582509158f00SBenoît Canet 582609158f00SBenoît Canet return to_replace_bs; 582709158f00SBenoît Canet } 5828448ad91dSMing Lei 5829448ad91dSMing Lei void bdrv_io_plug(BlockDriverState *bs) 5830448ad91dSMing Lei { 5831448ad91dSMing Lei BlockDriver *drv = bs->drv; 5832448ad91dSMing Lei if (drv && drv->bdrv_io_plug) { 5833448ad91dSMing Lei drv->bdrv_io_plug(bs); 5834448ad91dSMing Lei } else if (bs->file) { 5835448ad91dSMing Lei bdrv_io_plug(bs->file); 5836448ad91dSMing Lei } 5837448ad91dSMing Lei } 5838448ad91dSMing Lei 5839448ad91dSMing Lei void bdrv_io_unplug(BlockDriverState *bs) 5840448ad91dSMing Lei { 5841448ad91dSMing Lei BlockDriver *drv = bs->drv; 5842448ad91dSMing Lei if (drv && drv->bdrv_io_unplug) { 5843448ad91dSMing Lei drv->bdrv_io_unplug(bs); 5844448ad91dSMing Lei } else if (bs->file) { 5845448ad91dSMing Lei bdrv_io_unplug(bs->file); 5846448ad91dSMing Lei } 5847448ad91dSMing Lei } 5848448ad91dSMing Lei 5849448ad91dSMing Lei void bdrv_flush_io_queue(BlockDriverState *bs) 5850448ad91dSMing Lei { 5851448ad91dSMing Lei BlockDriver *drv = bs->drv; 5852448ad91dSMing Lei if (drv && drv->bdrv_flush_io_queue) { 5853448ad91dSMing Lei drv->bdrv_flush_io_queue(bs); 5854448ad91dSMing Lei } else if (bs->file) { 5855448ad91dSMing Lei bdrv_flush_io_queue(bs->file); 5856448ad91dSMing Lei } 5857448ad91dSMing Lei } 5858