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" 31bfb197e0SMarkus Armbruster #include "sysemu/block-backend.h" 329c17d615SPaolo Bonzini #include "sysemu/sysemu.h" 331de7afc9SPaolo Bonzini #include "qemu/notify.h" 34737e150eSPaolo Bonzini #include "block/coroutine.h" 35c13163fbSBenoît Canet #include "block/qapi.h" 36b2023818SLuiz Capitulino #include "qmp-commands.h" 371de7afc9SPaolo Bonzini #include "qemu/timer.h" 38a5ee7bd4SWenchao Xia #include "qapi-event.h" 39fc01f7e7Sbellard 4071e72a19SJuan Quintela #ifdef CONFIG_BSD 417674e7bfSbellard #include <sys/types.h> 427674e7bfSbellard #include <sys/stat.h> 437674e7bfSbellard #include <sys/ioctl.h> 4472cf2d4fSBlue Swirl #include <sys/queue.h> 45c5e97233Sblueswir1 #ifndef __DragonFly__ 467674e7bfSbellard #include <sys/disk.h> 477674e7bfSbellard #endif 48c5e97233Sblueswir1 #endif 497674e7bfSbellard 5049dc768dSaliguori #ifdef _WIN32 5149dc768dSaliguori #include <windows.h> 5249dc768dSaliguori #endif 5349dc768dSaliguori 54e4654d2dSFam Zheng struct BdrvDirtyBitmap { 55e4654d2dSFam Zheng HBitmap *bitmap; 56e4654d2dSFam Zheng QLIST_ENTRY(BdrvDirtyBitmap) list; 57e4654d2dSFam Zheng }; 58e4654d2dSFam Zheng 591c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */ 601c9805a3SStefan Hajnoczi 617c84b1b8SMarkus Armbruster static BlockAIOCB *bdrv_aio_readv_em(BlockDriverState *bs, 62f141eafeSaliguori int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, 63097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque); 647c84b1b8SMarkus Armbruster static BlockAIOCB *bdrv_aio_writev_em(BlockDriverState *bs, 65f141eafeSaliguori int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, 66097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque); 67f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs, 68f9f05dc5SKevin Wolf int64_t sector_num, int nb_sectors, 69f9f05dc5SKevin Wolf QEMUIOVector *iov); 70f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs, 71f9f05dc5SKevin Wolf int64_t sector_num, int nb_sectors, 72f9f05dc5SKevin Wolf QEMUIOVector *iov); 73775aa8b6SKevin Wolf static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs, 74775aa8b6SKevin Wolf int64_t offset, unsigned int bytes, QEMUIOVector *qiov, 75470c0504SStefan Hajnoczi BdrvRequestFlags flags); 76775aa8b6SKevin Wolf static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs, 77775aa8b6SKevin Wolf int64_t offset, unsigned int bytes, QEMUIOVector *qiov, 78f08f2ddaSStefan Hajnoczi BdrvRequestFlags flags); 797c84b1b8SMarkus Armbruster static BlockAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs, 80b2a61371SStefan Hajnoczi int64_t sector_num, 81b2a61371SStefan Hajnoczi QEMUIOVector *qiov, 82b2a61371SStefan Hajnoczi int nb_sectors, 83d20d9b7cSPaolo Bonzini BdrvRequestFlags flags, 84097310b5SMarkus Armbruster BlockCompletionFunc *cb, 85b2a61371SStefan Hajnoczi void *opaque, 868c5873d6SStefan Hajnoczi bool is_write); 87b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque); 88621f0589SKevin Wolf static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs, 89aa7bfbffSPeter Lieven int64_t sector_num, int nb_sectors, BdrvRequestFlags flags); 90ec530c81Sbellard 911b7bdbc1SStefan Hajnoczi static QTAILQ_HEAD(, BlockDriverState) bdrv_states = 921b7bdbc1SStefan Hajnoczi QTAILQ_HEAD_INITIALIZER(bdrv_states); 937ee930d0Sblueswir1 94dc364f4cSBenoît Canet static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states = 95dc364f4cSBenoît Canet QTAILQ_HEAD_INITIALIZER(graph_bdrv_states); 96dc364f4cSBenoît Canet 978a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers = 988a22f02aSStefan Hajnoczi QLIST_HEAD_INITIALIZER(bdrv_drivers); 99ea2384d3Sbellard 100c4237dfaSVladimir Sementsov-Ogievskiy static void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector, 101c4237dfaSVladimir Sementsov-Ogievskiy int nr_sectors); 102c4237dfaSVladimir Sementsov-Ogievskiy static void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, 103c4237dfaSVladimir Sementsov-Ogievskiy int nr_sectors); 104eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */ 105eb852011SMarkus Armbruster static int use_bdrv_whitelist; 106eb852011SMarkus Armbruster 1079e0b22f4SStefan Hajnoczi #ifdef _WIN32 1089e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename) 1099e0b22f4SStefan Hajnoczi { 1109e0b22f4SStefan Hajnoczi return (((filename[0] >= 'a' && filename[0] <= 'z') || 1119e0b22f4SStefan Hajnoczi (filename[0] >= 'A' && filename[0] <= 'Z')) && 1129e0b22f4SStefan Hajnoczi filename[1] == ':'); 1139e0b22f4SStefan Hajnoczi } 1149e0b22f4SStefan Hajnoczi 1159e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename) 1169e0b22f4SStefan Hajnoczi { 1179e0b22f4SStefan Hajnoczi if (is_windows_drive_prefix(filename) && 1189e0b22f4SStefan Hajnoczi filename[2] == '\0') 1199e0b22f4SStefan Hajnoczi return 1; 1209e0b22f4SStefan Hajnoczi if (strstart(filename, "\\\\.\\", NULL) || 1219e0b22f4SStefan Hajnoczi strstart(filename, "//./", NULL)) 1229e0b22f4SStefan Hajnoczi return 1; 1239e0b22f4SStefan Hajnoczi return 0; 1249e0b22f4SStefan Hajnoczi } 1259e0b22f4SStefan Hajnoczi #endif 1269e0b22f4SStefan Hajnoczi 1270563e191SZhi Yong Wu /* throttling disk I/O limits */ 128cc0681c4SBenoît Canet void bdrv_set_io_limits(BlockDriverState *bs, 129cc0681c4SBenoît Canet ThrottleConfig *cfg) 130cc0681c4SBenoît Canet { 131cc0681c4SBenoît Canet int i; 132cc0681c4SBenoît Canet 133cc0681c4SBenoît Canet throttle_config(&bs->throttle_state, cfg); 134cc0681c4SBenoît Canet 135cc0681c4SBenoît Canet for (i = 0; i < 2; i++) { 136cc0681c4SBenoît Canet qemu_co_enter_next(&bs->throttled_reqs[i]); 137cc0681c4SBenoît Canet } 138cc0681c4SBenoît Canet } 139cc0681c4SBenoît Canet 140cc0681c4SBenoît Canet /* this function drain all the throttled IOs */ 141cc0681c4SBenoît Canet static bool bdrv_start_throttled_reqs(BlockDriverState *bs) 142cc0681c4SBenoît Canet { 143cc0681c4SBenoît Canet bool drained = false; 144cc0681c4SBenoît Canet bool enabled = bs->io_limits_enabled; 145cc0681c4SBenoît Canet int i; 146cc0681c4SBenoît Canet 147cc0681c4SBenoît Canet bs->io_limits_enabled = false; 148cc0681c4SBenoît Canet 149cc0681c4SBenoît Canet for (i = 0; i < 2; i++) { 150cc0681c4SBenoît Canet while (qemu_co_enter_next(&bs->throttled_reqs[i])) { 151cc0681c4SBenoît Canet drained = true; 152cc0681c4SBenoît Canet } 153cc0681c4SBenoît Canet } 154cc0681c4SBenoît Canet 155cc0681c4SBenoît Canet bs->io_limits_enabled = enabled; 156cc0681c4SBenoît Canet 157cc0681c4SBenoît Canet return drained; 158cc0681c4SBenoît Canet } 159cc0681c4SBenoît Canet 16098f90dbaSZhi Yong Wu void bdrv_io_limits_disable(BlockDriverState *bs) 16198f90dbaSZhi Yong Wu { 16298f90dbaSZhi Yong Wu bs->io_limits_enabled = false; 16398f90dbaSZhi Yong Wu 164cc0681c4SBenoît Canet bdrv_start_throttled_reqs(bs); 16598f90dbaSZhi Yong Wu 166cc0681c4SBenoît Canet throttle_destroy(&bs->throttle_state); 16798f90dbaSZhi Yong Wu } 16898f90dbaSZhi Yong Wu 169cc0681c4SBenoît Canet static void bdrv_throttle_read_timer_cb(void *opaque) 1700563e191SZhi Yong Wu { 1710563e191SZhi Yong Wu BlockDriverState *bs = opaque; 172cc0681c4SBenoît Canet qemu_co_enter_next(&bs->throttled_reqs[0]); 1730563e191SZhi Yong Wu } 1740563e191SZhi Yong Wu 175cc0681c4SBenoît Canet static void bdrv_throttle_write_timer_cb(void *opaque) 176cc0681c4SBenoît Canet { 177cc0681c4SBenoît Canet BlockDriverState *bs = opaque; 178cc0681c4SBenoît Canet qemu_co_enter_next(&bs->throttled_reqs[1]); 179cc0681c4SBenoît Canet } 180cc0681c4SBenoît Canet 181cc0681c4SBenoît Canet /* should be called before bdrv_set_io_limits if a limit is set */ 1820563e191SZhi Yong Wu void bdrv_io_limits_enable(BlockDriverState *bs) 1830563e191SZhi Yong Wu { 184cc0681c4SBenoît Canet assert(!bs->io_limits_enabled); 185cc0681c4SBenoît Canet throttle_init(&bs->throttle_state, 18613af91ebSStefan Hajnoczi bdrv_get_aio_context(bs), 187cc0681c4SBenoît Canet QEMU_CLOCK_VIRTUAL, 188cc0681c4SBenoît Canet bdrv_throttle_read_timer_cb, 189cc0681c4SBenoît Canet bdrv_throttle_write_timer_cb, 190cc0681c4SBenoît Canet bs); 1910563e191SZhi Yong Wu bs->io_limits_enabled = true; 1920563e191SZhi Yong Wu } 1930563e191SZhi Yong Wu 194cc0681c4SBenoît Canet /* This function makes an IO wait if needed 195cc0681c4SBenoît Canet * 196cc0681c4SBenoît Canet * @nb_sectors: the number of sectors of the IO 197cc0681c4SBenoît Canet * @is_write: is the IO a write 19898f90dbaSZhi Yong Wu */ 199cc0681c4SBenoît Canet static void bdrv_io_limits_intercept(BlockDriverState *bs, 200d5103588SKevin Wolf unsigned int bytes, 201cc0681c4SBenoît Canet bool is_write) 202cc0681c4SBenoît Canet { 203cc0681c4SBenoît Canet /* does this io must wait */ 204cc0681c4SBenoît Canet bool must_wait = throttle_schedule_timer(&bs->throttle_state, is_write); 20598f90dbaSZhi Yong Wu 206cc0681c4SBenoît Canet /* if must wait or any request of this type throttled queue the IO */ 207cc0681c4SBenoît Canet if (must_wait || 208cc0681c4SBenoît Canet !qemu_co_queue_empty(&bs->throttled_reqs[is_write])) { 209cc0681c4SBenoît Canet qemu_co_queue_wait(&bs->throttled_reqs[is_write]); 21098f90dbaSZhi Yong Wu } 21198f90dbaSZhi Yong Wu 212cc0681c4SBenoît Canet /* the IO will be executed, do the accounting */ 213d5103588SKevin Wolf throttle_account(&bs->throttle_state, is_write, bytes); 214d5103588SKevin Wolf 215cc0681c4SBenoît Canet 216cc0681c4SBenoît Canet /* if the next request must wait -> do nothing */ 217cc0681c4SBenoît Canet if (throttle_schedule_timer(&bs->throttle_state, is_write)) { 218cc0681c4SBenoît Canet return; 219cc0681c4SBenoît Canet } 220cc0681c4SBenoît Canet 221cc0681c4SBenoît Canet /* else queue next request for execution */ 222cc0681c4SBenoît Canet qemu_co_queue_next(&bs->throttled_reqs[is_write]); 22398f90dbaSZhi Yong Wu } 22498f90dbaSZhi Yong Wu 225339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs) 226339064d5SKevin Wolf { 227339064d5SKevin Wolf if (!bs || !bs->drv) { 228339064d5SKevin Wolf /* 4k should be on the safe side */ 229339064d5SKevin Wolf return 4096; 230339064d5SKevin Wolf } 231339064d5SKevin Wolf 232339064d5SKevin Wolf return bs->bl.opt_mem_alignment; 233339064d5SKevin Wolf } 234339064d5SKevin Wolf 2359e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */ 2365c98415bSMax Reitz int path_has_protocol(const char *path) 2379e0b22f4SStefan Hajnoczi { 238947995c0SPaolo Bonzini const char *p; 239947995c0SPaolo Bonzini 2409e0b22f4SStefan Hajnoczi #ifdef _WIN32 2419e0b22f4SStefan Hajnoczi if (is_windows_drive(path) || 2429e0b22f4SStefan Hajnoczi is_windows_drive_prefix(path)) { 2439e0b22f4SStefan Hajnoczi return 0; 2449e0b22f4SStefan Hajnoczi } 245947995c0SPaolo Bonzini p = path + strcspn(path, ":/\\"); 246947995c0SPaolo Bonzini #else 247947995c0SPaolo Bonzini p = path + strcspn(path, ":/"); 2489e0b22f4SStefan Hajnoczi #endif 2499e0b22f4SStefan Hajnoczi 250947995c0SPaolo Bonzini return *p == ':'; 2519e0b22f4SStefan Hajnoczi } 2529e0b22f4SStefan Hajnoczi 25383f64091Sbellard int path_is_absolute(const char *path) 25483f64091Sbellard { 25521664424Sbellard #ifdef _WIN32 25621664424Sbellard /* specific case for names like: "\\.\d:" */ 257f53f4da9SPaolo Bonzini if (is_windows_drive(path) || is_windows_drive_prefix(path)) { 25821664424Sbellard return 1; 259f53f4da9SPaolo Bonzini } 260f53f4da9SPaolo Bonzini return (*path == '/' || *path == '\\'); 2613b9f94e1Sbellard #else 262f53f4da9SPaolo Bonzini return (*path == '/'); 2633b9f94e1Sbellard #endif 26483f64091Sbellard } 26583f64091Sbellard 26683f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a 26783f64091Sbellard path to it by considering it is relative to base_path. URL are 26883f64091Sbellard supported. */ 26983f64091Sbellard void path_combine(char *dest, int dest_size, 27083f64091Sbellard const char *base_path, 27183f64091Sbellard const char *filename) 27283f64091Sbellard { 27383f64091Sbellard const char *p, *p1; 27483f64091Sbellard int len; 27583f64091Sbellard 27683f64091Sbellard if (dest_size <= 0) 27783f64091Sbellard return; 27883f64091Sbellard if (path_is_absolute(filename)) { 27983f64091Sbellard pstrcpy(dest, dest_size, filename); 28083f64091Sbellard } else { 28183f64091Sbellard p = strchr(base_path, ':'); 28283f64091Sbellard if (p) 28383f64091Sbellard p++; 28483f64091Sbellard else 28583f64091Sbellard p = base_path; 2863b9f94e1Sbellard p1 = strrchr(base_path, '/'); 2873b9f94e1Sbellard #ifdef _WIN32 2883b9f94e1Sbellard { 2893b9f94e1Sbellard const char *p2; 2903b9f94e1Sbellard p2 = strrchr(base_path, '\\'); 2913b9f94e1Sbellard if (!p1 || p2 > p1) 2923b9f94e1Sbellard p1 = p2; 2933b9f94e1Sbellard } 2943b9f94e1Sbellard #endif 29583f64091Sbellard if (p1) 29683f64091Sbellard p1++; 29783f64091Sbellard else 29883f64091Sbellard p1 = base_path; 29983f64091Sbellard if (p1 > p) 30083f64091Sbellard p = p1; 30183f64091Sbellard len = p - base_path; 30283f64091Sbellard if (len > dest_size - 1) 30383f64091Sbellard len = dest_size - 1; 30483f64091Sbellard memcpy(dest, base_path, len); 30583f64091Sbellard dest[len] = '\0'; 30683f64091Sbellard pstrcat(dest, dest_size, filename); 30783f64091Sbellard } 30883f64091Sbellard } 30983f64091Sbellard 3100a82855aSMax Reitz void bdrv_get_full_backing_filename_from_filename(const char *backed, 3110a82855aSMax Reitz const char *backing, 3129f07429eSMax Reitz char *dest, size_t sz, 3139f07429eSMax Reitz Error **errp) 3140a82855aSMax Reitz { 3159f07429eSMax Reitz if (backing[0] == '\0' || path_has_protocol(backing) || 3169f07429eSMax Reitz path_is_absolute(backing)) 3179f07429eSMax Reitz { 3180a82855aSMax Reitz pstrcpy(dest, sz, backing); 3199f07429eSMax Reitz } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) { 3209f07429eSMax Reitz error_setg(errp, "Cannot use relative backing file names for '%s'", 3219f07429eSMax Reitz backed); 3220a82855aSMax Reitz } else { 3230a82855aSMax Reitz path_combine(dest, sz, backed, backing); 3240a82855aSMax Reitz } 3250a82855aSMax Reitz } 3260a82855aSMax Reitz 3279f07429eSMax Reitz void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz, 3289f07429eSMax Reitz Error **errp) 329dc5a1371SPaolo Bonzini { 3309f07429eSMax Reitz char *backed = bs->exact_filename[0] ? bs->exact_filename : bs->filename; 3319f07429eSMax Reitz 3329f07429eSMax Reitz bdrv_get_full_backing_filename_from_filename(backed, bs->backing_file, 3339f07429eSMax Reitz dest, sz, errp); 334dc5a1371SPaolo Bonzini } 335dc5a1371SPaolo Bonzini 3365efa9d5aSAnthony Liguori void bdrv_register(BlockDriver *bdrv) 337ea2384d3Sbellard { 3388c5873d6SStefan Hajnoczi /* Block drivers without coroutine functions need emulation */ 3398c5873d6SStefan Hajnoczi if (!bdrv->bdrv_co_readv) { 340f9f05dc5SKevin Wolf bdrv->bdrv_co_readv = bdrv_co_readv_em; 341f9f05dc5SKevin Wolf bdrv->bdrv_co_writev = bdrv_co_writev_em; 342f9f05dc5SKevin Wolf 343f8c35c1dSStefan Hajnoczi /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if 344f8c35c1dSStefan Hajnoczi * the block driver lacks aio we need to emulate that too. 345f8c35c1dSStefan Hajnoczi */ 346f9f05dc5SKevin Wolf if (!bdrv->bdrv_aio_readv) { 34783f64091Sbellard /* add AIO emulation layer */ 348f141eafeSaliguori bdrv->bdrv_aio_readv = bdrv_aio_readv_em; 349f141eafeSaliguori bdrv->bdrv_aio_writev = bdrv_aio_writev_em; 35083f64091Sbellard } 351f9f05dc5SKevin Wolf } 352b2e12bc6SChristoph Hellwig 3538a22f02aSStefan Hajnoczi QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list); 354ea2384d3Sbellard } 355b338082bSbellard 3567f06d47eSMarkus Armbruster BlockDriverState *bdrv_new_root(void) 357fc01f7e7Sbellard { 3587f06d47eSMarkus Armbruster BlockDriverState *bs = bdrv_new(); 359e4e9986bSMarkus Armbruster 360e4e9986bSMarkus Armbruster QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list); 361e4e9986bSMarkus Armbruster return bs; 362e4e9986bSMarkus Armbruster } 363e4e9986bSMarkus Armbruster 364e4e9986bSMarkus Armbruster BlockDriverState *bdrv_new(void) 365e4e9986bSMarkus Armbruster { 366e4e9986bSMarkus Armbruster BlockDriverState *bs; 367e4e9986bSMarkus Armbruster int i; 368e4e9986bSMarkus Armbruster 3695839e53bSMarkus Armbruster bs = g_new0(BlockDriverState, 1); 370e4654d2dSFam Zheng QLIST_INIT(&bs->dirty_bitmaps); 371fbe40ff7SFam Zheng for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { 372fbe40ff7SFam Zheng QLIST_INIT(&bs->op_blockers[i]); 373fbe40ff7SFam Zheng } 37428a7282aSLuiz Capitulino bdrv_iostatus_disable(bs); 375d7d512f6SPaolo Bonzini notifier_list_init(&bs->close_notifiers); 376d616b224SStefan Hajnoczi notifier_with_return_list_init(&bs->before_write_notifiers); 377cc0681c4SBenoît Canet qemu_co_queue_init(&bs->throttled_reqs[0]); 378cc0681c4SBenoît Canet qemu_co_queue_init(&bs->throttled_reqs[1]); 3799fcb0251SFam Zheng bs->refcnt = 1; 380dcd04228SStefan Hajnoczi bs->aio_context = qemu_get_aio_context(); 381d7d512f6SPaolo Bonzini 382b338082bSbellard return bs; 383b338082bSbellard } 384b338082bSbellard 385d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify) 386d7d512f6SPaolo Bonzini { 387d7d512f6SPaolo Bonzini notifier_list_add(&bs->close_notifiers, notify); 388d7d512f6SPaolo Bonzini } 389d7d512f6SPaolo Bonzini 390ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name) 391ea2384d3Sbellard { 392ea2384d3Sbellard BlockDriver *drv1; 3938a22f02aSStefan Hajnoczi QLIST_FOREACH(drv1, &bdrv_drivers, list) { 3948a22f02aSStefan Hajnoczi if (!strcmp(drv1->format_name, format_name)) { 395ea2384d3Sbellard return drv1; 396ea2384d3Sbellard } 3978a22f02aSStefan Hajnoczi } 398ea2384d3Sbellard return NULL; 399ea2384d3Sbellard } 400ea2384d3Sbellard 401b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only) 402eb852011SMarkus Armbruster { 403b64ec4e4SFam Zheng static const char *whitelist_rw[] = { 404b64ec4e4SFam Zheng CONFIG_BDRV_RW_WHITELIST 405b64ec4e4SFam Zheng }; 406b64ec4e4SFam Zheng static const char *whitelist_ro[] = { 407b64ec4e4SFam Zheng CONFIG_BDRV_RO_WHITELIST 408eb852011SMarkus Armbruster }; 409eb852011SMarkus Armbruster const char **p; 410eb852011SMarkus Armbruster 411b64ec4e4SFam Zheng if (!whitelist_rw[0] && !whitelist_ro[0]) { 412eb852011SMarkus Armbruster return 1; /* no whitelist, anything goes */ 413b64ec4e4SFam Zheng } 414eb852011SMarkus Armbruster 415b64ec4e4SFam Zheng for (p = whitelist_rw; *p; p++) { 416eb852011SMarkus Armbruster if (!strcmp(drv->format_name, *p)) { 417eb852011SMarkus Armbruster return 1; 418eb852011SMarkus Armbruster } 419eb852011SMarkus Armbruster } 420b64ec4e4SFam Zheng if (read_only) { 421b64ec4e4SFam Zheng for (p = whitelist_ro; *p; p++) { 422b64ec4e4SFam Zheng if (!strcmp(drv->format_name, *p)) { 423b64ec4e4SFam Zheng return 1; 424b64ec4e4SFam Zheng } 425b64ec4e4SFam Zheng } 426b64ec4e4SFam Zheng } 427eb852011SMarkus Armbruster return 0; 428eb852011SMarkus Armbruster } 429eb852011SMarkus Armbruster 430b64ec4e4SFam Zheng BlockDriver *bdrv_find_whitelisted_format(const char *format_name, 431b64ec4e4SFam Zheng bool read_only) 432eb852011SMarkus Armbruster { 433eb852011SMarkus Armbruster BlockDriver *drv = bdrv_find_format(format_name); 434b64ec4e4SFam Zheng return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL; 435eb852011SMarkus Armbruster } 436eb852011SMarkus Armbruster 4375b7e1542SZhi Yong Wu typedef struct CreateCo { 4385b7e1542SZhi Yong Wu BlockDriver *drv; 4395b7e1542SZhi Yong Wu char *filename; 44083d0521aSChunyan Liu QemuOpts *opts; 4415b7e1542SZhi Yong Wu int ret; 442cc84d90fSMax Reitz Error *err; 4435b7e1542SZhi Yong Wu } CreateCo; 4445b7e1542SZhi Yong Wu 4455b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque) 4465b7e1542SZhi Yong Wu { 447cc84d90fSMax Reitz Error *local_err = NULL; 448cc84d90fSMax Reitz int ret; 449cc84d90fSMax Reitz 4505b7e1542SZhi Yong Wu CreateCo *cco = opaque; 4515b7e1542SZhi Yong Wu assert(cco->drv); 4525b7e1542SZhi Yong Wu 453c282e1fdSChunyan Liu ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err); 45484d18f06SMarkus Armbruster if (local_err) { 455cc84d90fSMax Reitz error_propagate(&cco->err, local_err); 456cc84d90fSMax Reitz } 457cc84d90fSMax Reitz cco->ret = ret; 4585b7e1542SZhi Yong Wu } 4595b7e1542SZhi Yong Wu 4600e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename, 46183d0521aSChunyan Liu QemuOpts *opts, Error **errp) 462ea2384d3Sbellard { 4635b7e1542SZhi Yong Wu int ret; 4640e7e1989SKevin Wolf 4655b7e1542SZhi Yong Wu Coroutine *co; 4665b7e1542SZhi Yong Wu CreateCo cco = { 4675b7e1542SZhi Yong Wu .drv = drv, 4685b7e1542SZhi Yong Wu .filename = g_strdup(filename), 46983d0521aSChunyan Liu .opts = opts, 4705b7e1542SZhi Yong Wu .ret = NOT_DONE, 471cc84d90fSMax Reitz .err = NULL, 4725b7e1542SZhi Yong Wu }; 4735b7e1542SZhi Yong Wu 474c282e1fdSChunyan Liu if (!drv->bdrv_create) { 475cc84d90fSMax Reitz error_setg(errp, "Driver '%s' does not support image creation", drv->format_name); 47680168bffSLuiz Capitulino ret = -ENOTSUP; 47780168bffSLuiz Capitulino goto out; 4785b7e1542SZhi Yong Wu } 4795b7e1542SZhi Yong Wu 4805b7e1542SZhi Yong Wu if (qemu_in_coroutine()) { 4815b7e1542SZhi Yong Wu /* Fast-path if already in coroutine context */ 4825b7e1542SZhi Yong Wu bdrv_create_co_entry(&cco); 4835b7e1542SZhi Yong Wu } else { 4845b7e1542SZhi Yong Wu co = qemu_coroutine_create(bdrv_create_co_entry); 4855b7e1542SZhi Yong Wu qemu_coroutine_enter(co, &cco); 4865b7e1542SZhi Yong Wu while (cco.ret == NOT_DONE) { 487b47ec2c4SPaolo Bonzini aio_poll(qemu_get_aio_context(), true); 4885b7e1542SZhi Yong Wu } 4895b7e1542SZhi Yong Wu } 4905b7e1542SZhi Yong Wu 4915b7e1542SZhi Yong Wu ret = cco.ret; 492cc84d90fSMax Reitz if (ret < 0) { 49384d18f06SMarkus Armbruster if (cco.err) { 494cc84d90fSMax Reitz error_propagate(errp, cco.err); 495cc84d90fSMax Reitz } else { 496cc84d90fSMax Reitz error_setg_errno(errp, -ret, "Could not create image"); 497cc84d90fSMax Reitz } 498cc84d90fSMax Reitz } 4995b7e1542SZhi Yong Wu 50080168bffSLuiz Capitulino out: 50180168bffSLuiz Capitulino g_free(cco.filename); 5025b7e1542SZhi Yong Wu return ret; 503ea2384d3Sbellard } 504ea2384d3Sbellard 505c282e1fdSChunyan Liu int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp) 50684a12e66SChristoph Hellwig { 50784a12e66SChristoph Hellwig BlockDriver *drv; 508cc84d90fSMax Reitz Error *local_err = NULL; 509cc84d90fSMax Reitz int ret; 51084a12e66SChristoph Hellwig 51198289620SKevin Wolf drv = bdrv_find_protocol(filename, true); 51284a12e66SChristoph Hellwig if (drv == NULL) { 513cc84d90fSMax Reitz error_setg(errp, "Could not find protocol for file '%s'", filename); 51416905d71SStefan Hajnoczi return -ENOENT; 51584a12e66SChristoph Hellwig } 51684a12e66SChristoph Hellwig 517c282e1fdSChunyan Liu ret = bdrv_create(drv, filename, opts, &local_err); 51884d18f06SMarkus Armbruster if (local_err) { 519cc84d90fSMax Reitz error_propagate(errp, local_err); 520cc84d90fSMax Reitz } 521cc84d90fSMax Reitz return ret; 52284a12e66SChristoph Hellwig } 52384a12e66SChristoph Hellwig 5243baca891SKevin Wolf void bdrv_refresh_limits(BlockDriverState *bs, Error **errp) 525d34682cdSKevin Wolf { 526d34682cdSKevin Wolf BlockDriver *drv = bs->drv; 5273baca891SKevin Wolf Error *local_err = NULL; 528d34682cdSKevin Wolf 529d34682cdSKevin Wolf memset(&bs->bl, 0, sizeof(bs->bl)); 530d34682cdSKevin Wolf 531466ad822SKevin Wolf if (!drv) { 5323baca891SKevin Wolf return; 533466ad822SKevin Wolf } 534466ad822SKevin Wolf 535466ad822SKevin Wolf /* Take some limits from the children as a default */ 536466ad822SKevin Wolf if (bs->file) { 5373baca891SKevin Wolf bdrv_refresh_limits(bs->file, &local_err); 5383baca891SKevin Wolf if (local_err) { 5393baca891SKevin Wolf error_propagate(errp, local_err); 5403baca891SKevin Wolf return; 5413baca891SKevin Wolf } 542466ad822SKevin Wolf bs->bl.opt_transfer_length = bs->file->bl.opt_transfer_length; 5432647fab5SPeter Lieven bs->bl.max_transfer_length = bs->file->bl.max_transfer_length; 544339064d5SKevin Wolf bs->bl.opt_mem_alignment = bs->file->bl.opt_mem_alignment; 545339064d5SKevin Wolf } else { 546339064d5SKevin Wolf bs->bl.opt_mem_alignment = 512; 547466ad822SKevin Wolf } 548466ad822SKevin Wolf 549466ad822SKevin Wolf if (bs->backing_hd) { 5503baca891SKevin Wolf bdrv_refresh_limits(bs->backing_hd, &local_err); 5513baca891SKevin Wolf if (local_err) { 5523baca891SKevin Wolf error_propagate(errp, local_err); 5533baca891SKevin Wolf return; 5543baca891SKevin Wolf } 555466ad822SKevin Wolf bs->bl.opt_transfer_length = 556466ad822SKevin Wolf MAX(bs->bl.opt_transfer_length, 557466ad822SKevin Wolf bs->backing_hd->bl.opt_transfer_length); 5582647fab5SPeter Lieven bs->bl.max_transfer_length = 5592647fab5SPeter Lieven MIN_NON_ZERO(bs->bl.max_transfer_length, 5602647fab5SPeter Lieven bs->backing_hd->bl.max_transfer_length); 561339064d5SKevin Wolf bs->bl.opt_mem_alignment = 562339064d5SKevin Wolf MAX(bs->bl.opt_mem_alignment, 563339064d5SKevin Wolf bs->backing_hd->bl.opt_mem_alignment); 564466ad822SKevin Wolf } 565466ad822SKevin Wolf 566466ad822SKevin Wolf /* Then let the driver override it */ 567466ad822SKevin Wolf if (drv->bdrv_refresh_limits) { 5683baca891SKevin Wolf drv->bdrv_refresh_limits(bs, errp); 569d34682cdSKevin Wolf } 570d34682cdSKevin Wolf } 571d34682cdSKevin Wolf 572eba25057SJim Meyering /* 573eba25057SJim Meyering * Create a uniquely-named empty temporary file. 574eba25057SJim Meyering * Return 0 upon success, otherwise a negative errno value. 575eba25057SJim Meyering */ 576eba25057SJim Meyering int get_tmp_filename(char *filename, int size) 577eba25057SJim Meyering { 578d5249393Sbellard #ifdef _WIN32 5793b9f94e1Sbellard char temp_dir[MAX_PATH]; 580eba25057SJim Meyering /* GetTempFileName requires that its output buffer (4th param) 581eba25057SJim Meyering have length MAX_PATH or greater. */ 582eba25057SJim Meyering assert(size >= MAX_PATH); 583eba25057SJim Meyering return (GetTempPath(MAX_PATH, temp_dir) 584eba25057SJim Meyering && GetTempFileName(temp_dir, "qem", 0, filename) 585eba25057SJim Meyering ? 0 : -GetLastError()); 586d5249393Sbellard #else 587ea2384d3Sbellard int fd; 5887ccfb2ebSblueswir1 const char *tmpdir; 5890badc1eeSaurel32 tmpdir = getenv("TMPDIR"); 59069bef793SAmit Shah if (!tmpdir) { 59169bef793SAmit Shah tmpdir = "/var/tmp"; 59269bef793SAmit Shah } 593eba25057SJim Meyering if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) { 594eba25057SJim Meyering return -EOVERFLOW; 595ea2384d3Sbellard } 596eba25057SJim Meyering fd = mkstemp(filename); 597fe235a06SDunrong Huang if (fd < 0) { 598fe235a06SDunrong Huang return -errno; 599fe235a06SDunrong Huang } 600fe235a06SDunrong Huang if (close(fd) != 0) { 601fe235a06SDunrong Huang unlink(filename); 602eba25057SJim Meyering return -errno; 603eba25057SJim Meyering } 604eba25057SJim Meyering return 0; 605d5249393Sbellard #endif 606eba25057SJim Meyering } 607ea2384d3Sbellard 608f3a5d3f8SChristoph Hellwig /* 609f3a5d3f8SChristoph Hellwig * Detect host devices. By convention, /dev/cdrom[N] is always 610f3a5d3f8SChristoph Hellwig * recognized as a host CDROM. 611f3a5d3f8SChristoph Hellwig */ 612f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename) 613f3a5d3f8SChristoph Hellwig { 614508c7cb3SChristoph Hellwig int score_max = 0, score; 615508c7cb3SChristoph Hellwig BlockDriver *drv = NULL, *d; 616f3a5d3f8SChristoph Hellwig 6178a22f02aSStefan Hajnoczi QLIST_FOREACH(d, &bdrv_drivers, list) { 618508c7cb3SChristoph Hellwig if (d->bdrv_probe_device) { 619508c7cb3SChristoph Hellwig score = d->bdrv_probe_device(filename); 620508c7cb3SChristoph Hellwig if (score > score_max) { 621508c7cb3SChristoph Hellwig score_max = score; 622508c7cb3SChristoph Hellwig drv = d; 623f3a5d3f8SChristoph Hellwig } 624508c7cb3SChristoph Hellwig } 625f3a5d3f8SChristoph Hellwig } 626f3a5d3f8SChristoph Hellwig 627508c7cb3SChristoph Hellwig return drv; 628f3a5d3f8SChristoph Hellwig } 629f3a5d3f8SChristoph Hellwig 63098289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename, 63198289620SKevin Wolf bool allow_protocol_prefix) 63284a12e66SChristoph Hellwig { 63384a12e66SChristoph Hellwig BlockDriver *drv1; 63484a12e66SChristoph Hellwig char protocol[128]; 63584a12e66SChristoph Hellwig int len; 63684a12e66SChristoph Hellwig const char *p; 63784a12e66SChristoph Hellwig 63866f82ceeSKevin Wolf /* TODO Drivers without bdrv_file_open must be specified explicitly */ 63966f82ceeSKevin Wolf 64039508e7aSChristoph Hellwig /* 64139508e7aSChristoph Hellwig * XXX(hch): we really should not let host device detection 64239508e7aSChristoph Hellwig * override an explicit protocol specification, but moving this 64339508e7aSChristoph Hellwig * later breaks access to device names with colons in them. 64439508e7aSChristoph Hellwig * Thanks to the brain-dead persistent naming schemes on udev- 64539508e7aSChristoph Hellwig * based Linux systems those actually are quite common. 64639508e7aSChristoph Hellwig */ 64784a12e66SChristoph Hellwig drv1 = find_hdev_driver(filename); 64839508e7aSChristoph Hellwig if (drv1) { 64984a12e66SChristoph Hellwig return drv1; 65084a12e66SChristoph Hellwig } 65139508e7aSChristoph Hellwig 65298289620SKevin Wolf if (!path_has_protocol(filename) || !allow_protocol_prefix) { 653ef810437SMax Reitz return &bdrv_file; 65439508e7aSChristoph Hellwig } 65598289620SKevin Wolf 6569e0b22f4SStefan Hajnoczi p = strchr(filename, ':'); 6579e0b22f4SStefan Hajnoczi assert(p != NULL); 65884a12e66SChristoph Hellwig len = p - filename; 65984a12e66SChristoph Hellwig if (len > sizeof(protocol) - 1) 66084a12e66SChristoph Hellwig len = sizeof(protocol) - 1; 66184a12e66SChristoph Hellwig memcpy(protocol, filename, len); 66284a12e66SChristoph Hellwig protocol[len] = '\0'; 66384a12e66SChristoph Hellwig QLIST_FOREACH(drv1, &bdrv_drivers, list) { 66484a12e66SChristoph Hellwig if (drv1->protocol_name && 66584a12e66SChristoph Hellwig !strcmp(drv1->protocol_name, protocol)) { 66684a12e66SChristoph Hellwig return drv1; 66784a12e66SChristoph Hellwig } 66884a12e66SChristoph Hellwig } 66984a12e66SChristoph Hellwig return NULL; 67084a12e66SChristoph Hellwig } 67184a12e66SChristoph Hellwig 672c6684249SMarkus Armbruster /* 673c6684249SMarkus Armbruster * Guess image format by probing its contents. 674c6684249SMarkus Armbruster * This is not a good idea when your image is raw (CVE-2008-2004), but 675c6684249SMarkus Armbruster * we do it anyway for backward compatibility. 676c6684249SMarkus Armbruster * 677c6684249SMarkus Armbruster * @buf contains the image's first @buf_size bytes. 6787cddd372SKevin Wolf * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE, 6797cddd372SKevin Wolf * but can be smaller if the image file is smaller) 680c6684249SMarkus Armbruster * @filename is its filename. 681c6684249SMarkus Armbruster * 682c6684249SMarkus Armbruster * For all block drivers, call the bdrv_probe() method to get its 683c6684249SMarkus Armbruster * probing score. 684c6684249SMarkus Armbruster * Return the first block driver with the highest probing score. 685c6684249SMarkus Armbruster */ 68638f3ef57SKevin Wolf BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size, 687c6684249SMarkus Armbruster const char *filename) 688c6684249SMarkus Armbruster { 689c6684249SMarkus Armbruster int score_max = 0, score; 690c6684249SMarkus Armbruster BlockDriver *drv = NULL, *d; 691c6684249SMarkus Armbruster 692c6684249SMarkus Armbruster QLIST_FOREACH(d, &bdrv_drivers, list) { 693c6684249SMarkus Armbruster if (d->bdrv_probe) { 694c6684249SMarkus Armbruster score = d->bdrv_probe(buf, buf_size, filename); 695c6684249SMarkus Armbruster if (score > score_max) { 696c6684249SMarkus Armbruster score_max = score; 697c6684249SMarkus Armbruster drv = d; 698c6684249SMarkus Armbruster } 699c6684249SMarkus Armbruster } 700c6684249SMarkus Armbruster } 701c6684249SMarkus Armbruster 702c6684249SMarkus Armbruster return drv; 703c6684249SMarkus Armbruster } 704c6684249SMarkus Armbruster 705f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename, 70634b5d2c6SMax Reitz BlockDriver **pdrv, Error **errp) 707ea2384d3Sbellard { 708c6684249SMarkus Armbruster BlockDriver *drv; 7097cddd372SKevin Wolf uint8_t buf[BLOCK_PROBE_BUF_SIZE]; 710f500a6d3SKevin Wolf int ret = 0; 711f8ea0b00SNicholas Bellinger 71208a00559SKevin Wolf /* Return the raw BlockDriver * to scsi-generic devices or empty drives */ 7138e895599SPaolo Bonzini if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) { 714ef810437SMax Reitz *pdrv = &bdrv_raw; 715c98ac35dSStefan Weil return ret; 7161a396859SNicholas A. Bellinger } 717f8ea0b00SNicholas Bellinger 71883f64091Sbellard ret = bdrv_pread(bs, 0, buf, sizeof(buf)); 719ea2384d3Sbellard if (ret < 0) { 72034b5d2c6SMax Reitz error_setg_errno(errp, -ret, "Could not read image for determining its " 72134b5d2c6SMax Reitz "format"); 722c98ac35dSStefan Weil *pdrv = NULL; 723c98ac35dSStefan Weil return ret; 724ea2384d3Sbellard } 725ea2384d3Sbellard 726c6684249SMarkus Armbruster drv = bdrv_probe_all(buf, ret, filename); 727c98ac35dSStefan Weil if (!drv) { 72834b5d2c6SMax Reitz error_setg(errp, "Could not determine image format: No compatible " 72934b5d2c6SMax Reitz "driver found"); 730c98ac35dSStefan Weil ret = -ENOENT; 731c98ac35dSStefan Weil } 732c98ac35dSStefan Weil *pdrv = drv; 733c98ac35dSStefan Weil return ret; 734ea2384d3Sbellard } 735ea2384d3Sbellard 73651762288SStefan Hajnoczi /** 73751762288SStefan Hajnoczi * Set the current 'total_sectors' value 73865a9bb25SMarkus Armbruster * Return 0 on success, -errno on error. 73951762288SStefan Hajnoczi */ 74051762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint) 74151762288SStefan Hajnoczi { 74251762288SStefan Hajnoczi BlockDriver *drv = bs->drv; 74351762288SStefan Hajnoczi 744396759adSNicholas Bellinger /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */ 745396759adSNicholas Bellinger if (bs->sg) 746396759adSNicholas Bellinger return 0; 747396759adSNicholas Bellinger 74851762288SStefan Hajnoczi /* query actual device if possible, otherwise just trust the hint */ 74951762288SStefan Hajnoczi if (drv->bdrv_getlength) { 75051762288SStefan Hajnoczi int64_t length = drv->bdrv_getlength(bs); 75151762288SStefan Hajnoczi if (length < 0) { 75251762288SStefan Hajnoczi return length; 75351762288SStefan Hajnoczi } 7547e382003SFam Zheng hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE); 75551762288SStefan Hajnoczi } 75651762288SStefan Hajnoczi 75751762288SStefan Hajnoczi bs->total_sectors = hint; 75851762288SStefan Hajnoczi return 0; 75951762288SStefan Hajnoczi } 76051762288SStefan Hajnoczi 761c3993cdcSStefan Hajnoczi /** 7629e8f1835SPaolo Bonzini * Set open flags for a given discard mode 7639e8f1835SPaolo Bonzini * 7649e8f1835SPaolo Bonzini * Return 0 on success, -1 if the discard mode was invalid. 7659e8f1835SPaolo Bonzini */ 7669e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags) 7679e8f1835SPaolo Bonzini { 7689e8f1835SPaolo Bonzini *flags &= ~BDRV_O_UNMAP; 7699e8f1835SPaolo Bonzini 7709e8f1835SPaolo Bonzini if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) { 7719e8f1835SPaolo Bonzini /* do nothing */ 7729e8f1835SPaolo Bonzini } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) { 7739e8f1835SPaolo Bonzini *flags |= BDRV_O_UNMAP; 7749e8f1835SPaolo Bonzini } else { 7759e8f1835SPaolo Bonzini return -1; 7769e8f1835SPaolo Bonzini } 7779e8f1835SPaolo Bonzini 7789e8f1835SPaolo Bonzini return 0; 7799e8f1835SPaolo Bonzini } 7809e8f1835SPaolo Bonzini 7819e8f1835SPaolo Bonzini /** 782c3993cdcSStefan Hajnoczi * Set open flags for a given cache mode 783c3993cdcSStefan Hajnoczi * 784c3993cdcSStefan Hajnoczi * Return 0 on success, -1 if the cache mode was invalid. 785c3993cdcSStefan Hajnoczi */ 786c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags) 787c3993cdcSStefan Hajnoczi { 788c3993cdcSStefan Hajnoczi *flags &= ~BDRV_O_CACHE_MASK; 789c3993cdcSStefan Hajnoczi 790c3993cdcSStefan Hajnoczi if (!strcmp(mode, "off") || !strcmp(mode, "none")) { 791c3993cdcSStefan Hajnoczi *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB; 79292196b2fSStefan Hajnoczi } else if (!strcmp(mode, "directsync")) { 79392196b2fSStefan Hajnoczi *flags |= BDRV_O_NOCACHE; 794c3993cdcSStefan Hajnoczi } else if (!strcmp(mode, "writeback")) { 795c3993cdcSStefan Hajnoczi *flags |= BDRV_O_CACHE_WB; 796c3993cdcSStefan Hajnoczi } else if (!strcmp(mode, "unsafe")) { 797c3993cdcSStefan Hajnoczi *flags |= BDRV_O_CACHE_WB; 798c3993cdcSStefan Hajnoczi *flags |= BDRV_O_NO_FLUSH; 799c3993cdcSStefan Hajnoczi } else if (!strcmp(mode, "writethrough")) { 800c3993cdcSStefan Hajnoczi /* this is the default */ 801c3993cdcSStefan Hajnoczi } else { 802c3993cdcSStefan Hajnoczi return -1; 803c3993cdcSStefan Hajnoczi } 804c3993cdcSStefan Hajnoczi 805c3993cdcSStefan Hajnoczi return 0; 806c3993cdcSStefan Hajnoczi } 807c3993cdcSStefan Hajnoczi 80853fec9d3SStefan Hajnoczi /** 80953fec9d3SStefan Hajnoczi * The copy-on-read flag is actually a reference count so multiple users may 81053fec9d3SStefan Hajnoczi * use the feature without worrying about clobbering its previous state. 81153fec9d3SStefan Hajnoczi * Copy-on-read stays enabled until all users have called to disable it. 81253fec9d3SStefan Hajnoczi */ 81353fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs) 81453fec9d3SStefan Hajnoczi { 81553fec9d3SStefan Hajnoczi bs->copy_on_read++; 81653fec9d3SStefan Hajnoczi } 81753fec9d3SStefan Hajnoczi 81853fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs) 81953fec9d3SStefan Hajnoczi { 82053fec9d3SStefan Hajnoczi assert(bs->copy_on_read > 0); 82153fec9d3SStefan Hajnoczi bs->copy_on_read--; 82253fec9d3SStefan Hajnoczi } 82353fec9d3SStefan Hajnoczi 8240b50cc88SKevin Wolf /* 825b1e6fc08SKevin Wolf * Returns the flags that a temporary snapshot should get, based on the 826b1e6fc08SKevin Wolf * originally requested flags (the originally requested image will have flags 827b1e6fc08SKevin Wolf * like a backing file) 828b1e6fc08SKevin Wolf */ 829b1e6fc08SKevin Wolf static int bdrv_temp_snapshot_flags(int flags) 830b1e6fc08SKevin Wolf { 831b1e6fc08SKevin Wolf return (flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY; 832b1e6fc08SKevin Wolf } 833b1e6fc08SKevin Wolf 834b1e6fc08SKevin Wolf /* 8350b50cc88SKevin Wolf * Returns the flags that bs->file should get, based on the given flags for 8360b50cc88SKevin Wolf * the parent BDS 8370b50cc88SKevin Wolf */ 8380b50cc88SKevin Wolf static int bdrv_inherited_flags(int flags) 8390b50cc88SKevin Wolf { 8400b50cc88SKevin Wolf /* Enable protocol handling, disable format probing for bs->file */ 8410b50cc88SKevin Wolf flags |= BDRV_O_PROTOCOL; 8420b50cc88SKevin Wolf 8430b50cc88SKevin Wolf /* Our block drivers take care to send flushes and respect unmap policy, 8440b50cc88SKevin Wolf * so we can enable both unconditionally on lower layers. */ 8450b50cc88SKevin Wolf flags |= BDRV_O_CACHE_WB | BDRV_O_UNMAP; 8460b50cc88SKevin Wolf 8470b50cc88SKevin Wolf /* Clear flags that only apply to the top layer */ 8485669b44dSKevin Wolf flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ); 8490b50cc88SKevin Wolf 8500b50cc88SKevin Wolf return flags; 8510b50cc88SKevin Wolf } 8520b50cc88SKevin Wolf 853317fc44eSKevin Wolf /* 854317fc44eSKevin Wolf * Returns the flags that bs->backing_hd should get, based on the given flags 855317fc44eSKevin Wolf * for the parent BDS 856317fc44eSKevin Wolf */ 857317fc44eSKevin Wolf static int bdrv_backing_flags(int flags) 858317fc44eSKevin Wolf { 859317fc44eSKevin Wolf /* backing files always opened read-only */ 860317fc44eSKevin Wolf flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ); 861317fc44eSKevin Wolf 862317fc44eSKevin Wolf /* snapshot=on is handled on the top layer */ 8638bfea15dSKevin Wolf flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY); 864317fc44eSKevin Wolf 865317fc44eSKevin Wolf return flags; 866317fc44eSKevin Wolf } 867317fc44eSKevin Wolf 8687b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags) 8697b272452SKevin Wolf { 8707b272452SKevin Wolf int open_flags = flags | BDRV_O_CACHE_WB; 8717b272452SKevin Wolf 8727b272452SKevin Wolf /* 8737b272452SKevin Wolf * Clear flags that are internal to the block layer before opening the 8747b272452SKevin Wolf * image. 8757b272452SKevin Wolf */ 87620cca275SKevin Wolf open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL); 8777b272452SKevin Wolf 8787b272452SKevin Wolf /* 8797b272452SKevin Wolf * Snapshots should be writable. 8807b272452SKevin Wolf */ 8818bfea15dSKevin Wolf if (flags & BDRV_O_TEMPORARY) { 8827b272452SKevin Wolf open_flags |= BDRV_O_RDWR; 8837b272452SKevin Wolf } 8847b272452SKevin Wolf 8857b272452SKevin Wolf return open_flags; 8867b272452SKevin Wolf } 8877b272452SKevin Wolf 888636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs, 8896913c0c2SBenoît Canet const char *node_name, 8906913c0c2SBenoît Canet Error **errp) 8916913c0c2SBenoît Canet { 8926913c0c2SBenoît Canet if (!node_name) { 893636ea370SKevin Wolf return; 8946913c0c2SBenoît Canet } 8956913c0c2SBenoît Canet 8969aebf3b8SKevin Wolf /* Check for empty string or invalid characters */ 897f5bebbbbSMarkus Armbruster if (!id_wellformed(node_name)) { 8989aebf3b8SKevin Wolf error_setg(errp, "Invalid node name"); 899636ea370SKevin Wolf return; 9006913c0c2SBenoît Canet } 9016913c0c2SBenoît Canet 9020c5e94eeSBenoît Canet /* takes care of avoiding namespaces collisions */ 9037f06d47eSMarkus Armbruster if (blk_by_name(node_name)) { 9040c5e94eeSBenoît Canet error_setg(errp, "node-name=%s is conflicting with a device id", 9050c5e94eeSBenoît Canet node_name); 906636ea370SKevin Wolf return; 9070c5e94eeSBenoît Canet } 9080c5e94eeSBenoît Canet 9096913c0c2SBenoît Canet /* takes care of avoiding duplicates node names */ 9106913c0c2SBenoît Canet if (bdrv_find_node(node_name)) { 9116913c0c2SBenoît Canet error_setg(errp, "Duplicate node name"); 912636ea370SKevin Wolf return; 9136913c0c2SBenoît Canet } 9146913c0c2SBenoît Canet 9156913c0c2SBenoît Canet /* copy node name into the bs and insert it into the graph list */ 9166913c0c2SBenoît Canet pstrcpy(bs->node_name, sizeof(bs->node_name), node_name); 9176913c0c2SBenoît Canet QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list); 9186913c0c2SBenoît Canet } 9196913c0c2SBenoît Canet 920b6ce07aaSKevin Wolf /* 92157915332SKevin Wolf * Common part for opening disk images and files 922b6ad491aSKevin Wolf * 923b6ad491aSKevin Wolf * Removes all processed options from *options. 92457915332SKevin Wolf */ 925f500a6d3SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file, 92634b5d2c6SMax Reitz QDict *options, int flags, BlockDriver *drv, Error **errp) 92757915332SKevin Wolf { 92857915332SKevin Wolf int ret, open_flags; 929035fccdfSKevin Wolf const char *filename; 9306913c0c2SBenoît Canet const char *node_name = NULL; 93134b5d2c6SMax Reitz Error *local_err = NULL; 93257915332SKevin Wolf 93357915332SKevin Wolf assert(drv != NULL); 9346405875cSPaolo Bonzini assert(bs->file == NULL); 935707ff828SKevin Wolf assert(options != NULL && bs->options != options); 93657915332SKevin Wolf 93745673671SKevin Wolf if (file != NULL) { 93845673671SKevin Wolf filename = file->filename; 93945673671SKevin Wolf } else { 94045673671SKevin Wolf filename = qdict_get_try_str(options, "filename"); 94145673671SKevin Wolf } 94245673671SKevin Wolf 943765003dbSKevin Wolf if (drv->bdrv_needs_filename && !filename) { 944765003dbSKevin Wolf error_setg(errp, "The '%s' block driver requires a file name", 945765003dbSKevin Wolf drv->format_name); 946765003dbSKevin Wolf return -EINVAL; 947765003dbSKevin Wolf } 948765003dbSKevin Wolf 94945673671SKevin Wolf trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name); 95028dcee10SStefan Hajnoczi 9516913c0c2SBenoît Canet node_name = qdict_get_try_str(options, "node-name"); 952636ea370SKevin Wolf bdrv_assign_node_name(bs, node_name, &local_err); 9530fb6395cSMarkus Armbruster if (local_err) { 954636ea370SKevin Wolf error_propagate(errp, local_err); 955636ea370SKevin Wolf return -EINVAL; 9566913c0c2SBenoît Canet } 9576913c0c2SBenoît Canet qdict_del(options, "node-name"); 9586913c0c2SBenoît Canet 9595d186eb0SKevin Wolf /* bdrv_open() with directly using a protocol as drv. This layer is already 9605d186eb0SKevin Wolf * opened, so assign it to bs (while file becomes a closed BlockDriverState) 9615d186eb0SKevin Wolf * and return immediately. */ 9625d186eb0SKevin Wolf if (file != NULL && drv->bdrv_file_open) { 9635d186eb0SKevin Wolf bdrv_swap(file, bs); 9645d186eb0SKevin Wolf return 0; 9655d186eb0SKevin Wolf } 9665d186eb0SKevin Wolf 96757915332SKevin Wolf bs->open_flags = flags; 9681b7fd729SPaolo Bonzini bs->guest_block_size = 512; 969c25f53b0SPaolo Bonzini bs->request_alignment = 512; 9700d51b4deSAsias He bs->zero_beyond_eof = true; 971b64ec4e4SFam Zheng open_flags = bdrv_open_flags(bs, flags); 972b64ec4e4SFam Zheng bs->read_only = !(open_flags & BDRV_O_RDWR); 97320cca275SKevin Wolf bs->growable = !!(flags & BDRV_O_PROTOCOL); 974b64ec4e4SFam Zheng 975b64ec4e4SFam Zheng if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) { 9768f94a6e4SKevin Wolf error_setg(errp, 9778f94a6e4SKevin Wolf !bs->read_only && bdrv_is_whitelisted(drv, true) 9788f94a6e4SKevin Wolf ? "Driver '%s' can only be used for read-only devices" 9798f94a6e4SKevin Wolf : "Driver '%s' is not whitelisted", 9808f94a6e4SKevin Wolf drv->format_name); 981b64ec4e4SFam Zheng return -ENOTSUP; 982b64ec4e4SFam Zheng } 98357915332SKevin Wolf 98453fec9d3SStefan Hajnoczi assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */ 9850ebd24e0SKevin Wolf if (flags & BDRV_O_COPY_ON_READ) { 9860ebd24e0SKevin Wolf if (!bs->read_only) { 98753fec9d3SStefan Hajnoczi bdrv_enable_copy_on_read(bs); 9880ebd24e0SKevin Wolf } else { 9890ebd24e0SKevin Wolf error_setg(errp, "Can't use copy-on-read on read-only device"); 9900ebd24e0SKevin Wolf return -EINVAL; 9910ebd24e0SKevin Wolf } 99253fec9d3SStefan Hajnoczi } 99353fec9d3SStefan Hajnoczi 994c2ad1b0cSKevin Wolf if (filename != NULL) { 99557915332SKevin Wolf pstrcpy(bs->filename, sizeof(bs->filename), filename); 996c2ad1b0cSKevin Wolf } else { 997c2ad1b0cSKevin Wolf bs->filename[0] = '\0'; 998c2ad1b0cSKevin Wolf } 99991af7014SMax Reitz pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename); 100057915332SKevin Wolf 100157915332SKevin Wolf bs->drv = drv; 10027267c094SAnthony Liguori bs->opaque = g_malloc0(drv->instance_size); 100357915332SKevin Wolf 100403f541bdSStefan Hajnoczi bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB); 1005e7c63796SStefan Hajnoczi 100666f82ceeSKevin Wolf /* Open the image, either directly or using a protocol */ 100766f82ceeSKevin Wolf if (drv->bdrv_file_open) { 10085d186eb0SKevin Wolf assert(file == NULL); 1009030be321SBenoît Canet assert(!drv->bdrv_needs_filename || filename != NULL); 101034b5d2c6SMax Reitz ret = drv->bdrv_file_open(bs, options, open_flags, &local_err); 1011f500a6d3SKevin Wolf } else { 10122af5ef70SKevin Wolf if (file == NULL) { 101334b5d2c6SMax Reitz error_setg(errp, "Can't use '%s' as a block driver for the " 101434b5d2c6SMax Reitz "protocol level", drv->format_name); 10152af5ef70SKevin Wolf ret = -EINVAL; 10162af5ef70SKevin Wolf goto free_and_fail; 10172af5ef70SKevin Wolf } 1018f500a6d3SKevin Wolf bs->file = file; 101934b5d2c6SMax Reitz ret = drv->bdrv_open(bs, options, open_flags, &local_err); 102066f82ceeSKevin Wolf } 102166f82ceeSKevin Wolf 102257915332SKevin Wolf if (ret < 0) { 102384d18f06SMarkus Armbruster if (local_err) { 102434b5d2c6SMax Reitz error_propagate(errp, local_err); 10252fa9aa59SDunrong Huang } else if (bs->filename[0]) { 10262fa9aa59SDunrong Huang error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename); 102734b5d2c6SMax Reitz } else { 102834b5d2c6SMax Reitz error_setg_errno(errp, -ret, "Could not open image"); 102934b5d2c6SMax Reitz } 103057915332SKevin Wolf goto free_and_fail; 103157915332SKevin Wolf } 103257915332SKevin Wolf 103351762288SStefan Hajnoczi ret = refresh_total_sectors(bs, bs->total_sectors); 103451762288SStefan Hajnoczi if (ret < 0) { 103534b5d2c6SMax Reitz error_setg_errno(errp, -ret, "Could not refresh total sector count"); 103651762288SStefan Hajnoczi goto free_and_fail; 103757915332SKevin Wolf } 103851762288SStefan Hajnoczi 10393baca891SKevin Wolf bdrv_refresh_limits(bs, &local_err); 10403baca891SKevin Wolf if (local_err) { 10413baca891SKevin Wolf error_propagate(errp, local_err); 10423baca891SKevin Wolf ret = -EINVAL; 10433baca891SKevin Wolf goto free_and_fail; 10443baca891SKevin Wolf } 10453baca891SKevin Wolf 1046c25f53b0SPaolo Bonzini assert(bdrv_opt_mem_align(bs) != 0); 104747ea2de2SKevin Wolf assert((bs->request_alignment != 0) || bs->sg); 104857915332SKevin Wolf return 0; 104957915332SKevin Wolf 105057915332SKevin Wolf free_and_fail: 105166f82ceeSKevin Wolf bs->file = NULL; 10527267c094SAnthony Liguori g_free(bs->opaque); 105357915332SKevin Wolf bs->opaque = NULL; 105457915332SKevin Wolf bs->drv = NULL; 105557915332SKevin Wolf return ret; 105657915332SKevin Wolf } 105757915332SKevin Wolf 10585e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp) 10595e5c4f63SKevin Wolf { 10605e5c4f63SKevin Wolf QObject *options_obj; 10615e5c4f63SKevin Wolf QDict *options; 10625e5c4f63SKevin Wolf int ret; 10635e5c4f63SKevin Wolf 10645e5c4f63SKevin Wolf ret = strstart(filename, "json:", &filename); 10655e5c4f63SKevin Wolf assert(ret); 10665e5c4f63SKevin Wolf 10675e5c4f63SKevin Wolf options_obj = qobject_from_json(filename); 10685e5c4f63SKevin Wolf if (!options_obj) { 10695e5c4f63SKevin Wolf error_setg(errp, "Could not parse the JSON options"); 10705e5c4f63SKevin Wolf return NULL; 10715e5c4f63SKevin Wolf } 10725e5c4f63SKevin Wolf 10735e5c4f63SKevin Wolf if (qobject_type(options_obj) != QTYPE_QDICT) { 10745e5c4f63SKevin Wolf qobject_decref(options_obj); 10755e5c4f63SKevin Wolf error_setg(errp, "Invalid JSON object given"); 10765e5c4f63SKevin Wolf return NULL; 10775e5c4f63SKevin Wolf } 10785e5c4f63SKevin Wolf 10795e5c4f63SKevin Wolf options = qobject_to_qdict(options_obj); 10805e5c4f63SKevin Wolf qdict_flatten(options); 10815e5c4f63SKevin Wolf 10825e5c4f63SKevin Wolf return options; 10835e5c4f63SKevin Wolf } 10845e5c4f63SKevin Wolf 108557915332SKevin Wolf /* 1086f54120ffSKevin Wolf * Fills in default options for opening images and converts the legacy 1087f54120ffSKevin Wolf * filename/flags pair to option QDict entries. 1088f54120ffSKevin Wolf */ 10895e5c4f63SKevin Wolf static int bdrv_fill_options(QDict **options, const char **pfilename, int flags, 109017b005f1SKevin Wolf BlockDriver *drv, Error **errp) 1091f54120ffSKevin Wolf { 10925e5c4f63SKevin Wolf const char *filename = *pfilename; 1093f54120ffSKevin Wolf const char *drvname; 1094462f5bcfSKevin Wolf bool protocol = flags & BDRV_O_PROTOCOL; 1095f54120ffSKevin Wolf bool parse_filename = false; 1096f54120ffSKevin Wolf Error *local_err = NULL; 1097f54120ffSKevin Wolf 10985e5c4f63SKevin Wolf /* Parse json: pseudo-protocol */ 10995e5c4f63SKevin Wolf if (filename && g_str_has_prefix(filename, "json:")) { 11005e5c4f63SKevin Wolf QDict *json_options = parse_json_filename(filename, &local_err); 11015e5c4f63SKevin Wolf if (local_err) { 11025e5c4f63SKevin Wolf error_propagate(errp, local_err); 11035e5c4f63SKevin Wolf return -EINVAL; 11045e5c4f63SKevin Wolf } 11055e5c4f63SKevin Wolf 11065e5c4f63SKevin Wolf /* Options given in the filename have lower priority than options 11075e5c4f63SKevin Wolf * specified directly */ 11085e5c4f63SKevin Wolf qdict_join(*options, json_options, false); 11095e5c4f63SKevin Wolf QDECREF(json_options); 11105e5c4f63SKevin Wolf *pfilename = filename = NULL; 11115e5c4f63SKevin Wolf } 11125e5c4f63SKevin Wolf 1113f54120ffSKevin Wolf /* Fetch the file name from the options QDict if necessary */ 111417b005f1SKevin Wolf if (protocol && filename) { 1115f54120ffSKevin Wolf if (!qdict_haskey(*options, "filename")) { 1116f54120ffSKevin Wolf qdict_put(*options, "filename", qstring_from_str(filename)); 1117f54120ffSKevin Wolf parse_filename = true; 1118f54120ffSKevin Wolf } else { 1119f54120ffSKevin Wolf error_setg(errp, "Can't specify 'file' and 'filename' options at " 1120f54120ffSKevin Wolf "the same time"); 1121f54120ffSKevin Wolf return -EINVAL; 1122f54120ffSKevin Wolf } 1123f54120ffSKevin Wolf } 1124f54120ffSKevin Wolf 1125f54120ffSKevin Wolf /* Find the right block driver */ 1126f54120ffSKevin Wolf filename = qdict_get_try_str(*options, "filename"); 1127f54120ffSKevin Wolf drvname = qdict_get_try_str(*options, "driver"); 1128f54120ffSKevin Wolf 112917b005f1SKevin Wolf if (drv) { 113017b005f1SKevin Wolf if (drvname) { 113117b005f1SKevin Wolf error_setg(errp, "Driver specified twice"); 113217b005f1SKevin Wolf return -EINVAL; 113317b005f1SKevin Wolf } 113417b005f1SKevin Wolf drvname = drv->format_name; 113517b005f1SKevin Wolf qdict_put(*options, "driver", qstring_from_str(drvname)); 113617b005f1SKevin Wolf } else { 113717b005f1SKevin Wolf if (!drvname && protocol) { 1138f54120ffSKevin Wolf if (filename) { 1139f54120ffSKevin Wolf drv = bdrv_find_protocol(filename, parse_filename); 1140f54120ffSKevin Wolf if (!drv) { 1141f54120ffSKevin Wolf error_setg(errp, "Unknown protocol"); 1142f54120ffSKevin Wolf return -EINVAL; 1143f54120ffSKevin Wolf } 1144f54120ffSKevin Wolf 1145f54120ffSKevin Wolf drvname = drv->format_name; 1146f54120ffSKevin Wolf qdict_put(*options, "driver", qstring_from_str(drvname)); 1147f54120ffSKevin Wolf } else { 1148f54120ffSKevin Wolf error_setg(errp, "Must specify either driver or file"); 1149f54120ffSKevin Wolf return -EINVAL; 1150f54120ffSKevin Wolf } 115117b005f1SKevin Wolf } else if (drvname) { 1152f54120ffSKevin Wolf drv = bdrv_find_format(drvname); 1153f54120ffSKevin Wolf if (!drv) { 1154f54120ffSKevin Wolf error_setg(errp, "Unknown driver '%s'", drvname); 1155f54120ffSKevin Wolf return -ENOENT; 1156f54120ffSKevin Wolf } 115717b005f1SKevin Wolf } 115817b005f1SKevin Wolf } 115917b005f1SKevin Wolf 116017b005f1SKevin Wolf assert(drv || !protocol); 1161f54120ffSKevin Wolf 1162f54120ffSKevin Wolf /* Driver-specific filename parsing */ 116317b005f1SKevin Wolf if (drv && drv->bdrv_parse_filename && parse_filename) { 1164f54120ffSKevin Wolf drv->bdrv_parse_filename(filename, *options, &local_err); 1165f54120ffSKevin Wolf if (local_err) { 1166f54120ffSKevin Wolf error_propagate(errp, local_err); 1167f54120ffSKevin Wolf return -EINVAL; 1168f54120ffSKevin Wolf } 1169f54120ffSKevin Wolf 1170f54120ffSKevin Wolf if (!drv->bdrv_needs_filename) { 1171f54120ffSKevin Wolf qdict_del(*options, "filename"); 1172f54120ffSKevin Wolf } 1173f54120ffSKevin Wolf } 1174f54120ffSKevin Wolf 1175f54120ffSKevin Wolf return 0; 1176f54120ffSKevin Wolf } 1177f54120ffSKevin Wolf 11788d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd) 11798d24cce1SFam Zheng { 11808d24cce1SFam Zheng 1181826b6ca0SFam Zheng if (bs->backing_hd) { 1182826b6ca0SFam Zheng assert(bs->backing_blocker); 1183826b6ca0SFam Zheng bdrv_op_unblock_all(bs->backing_hd, bs->backing_blocker); 1184826b6ca0SFam Zheng } else if (backing_hd) { 1185826b6ca0SFam Zheng error_setg(&bs->backing_blocker, 1186826b6ca0SFam Zheng "device is used as backing hd of '%s'", 1187bfb197e0SMarkus Armbruster bdrv_get_device_name(bs)); 1188826b6ca0SFam Zheng } 1189826b6ca0SFam Zheng 11908d24cce1SFam Zheng bs->backing_hd = backing_hd; 11918d24cce1SFam Zheng if (!backing_hd) { 1192826b6ca0SFam Zheng error_free(bs->backing_blocker); 1193826b6ca0SFam Zheng bs->backing_blocker = NULL; 11948d24cce1SFam Zheng goto out; 11958d24cce1SFam Zheng } 11968d24cce1SFam Zheng bs->open_flags &= ~BDRV_O_NO_BACKING; 11978d24cce1SFam Zheng pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename); 11988d24cce1SFam Zheng pstrcpy(bs->backing_format, sizeof(bs->backing_format), 11998d24cce1SFam Zheng backing_hd->drv ? backing_hd->drv->format_name : ""); 1200826b6ca0SFam Zheng 1201826b6ca0SFam Zheng bdrv_op_block_all(bs->backing_hd, bs->backing_blocker); 1202826b6ca0SFam Zheng /* Otherwise we won't be able to commit due to check in bdrv_commit */ 1203826b6ca0SFam Zheng bdrv_op_unblock(bs->backing_hd, BLOCK_OP_TYPE_COMMIT, 1204826b6ca0SFam Zheng bs->backing_blocker); 12058d24cce1SFam Zheng out: 12063baca891SKevin Wolf bdrv_refresh_limits(bs, NULL); 12078d24cce1SFam Zheng } 12088d24cce1SFam Zheng 120931ca6d07SKevin Wolf /* 121031ca6d07SKevin Wolf * Opens the backing file for a BlockDriverState if not yet open 121131ca6d07SKevin Wolf * 121231ca6d07SKevin Wolf * options is a QDict of options to pass to the block drivers, or NULL for an 121331ca6d07SKevin Wolf * empty set of options. The reference to the QDict is transferred to this 121431ca6d07SKevin Wolf * function (even on failure), so if the caller intends to reuse the dictionary, 121531ca6d07SKevin Wolf * it needs to use QINCREF() before calling bdrv_file_open. 121631ca6d07SKevin Wolf */ 121734b5d2c6SMax Reitz int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp) 12189156df12SPaolo Bonzini { 12191ba4b6a5SBenoît Canet char *backing_filename = g_malloc0(PATH_MAX); 1220317fc44eSKevin Wolf int ret = 0; 12218d24cce1SFam Zheng BlockDriverState *backing_hd; 122234b5d2c6SMax Reitz Error *local_err = NULL; 12239156df12SPaolo Bonzini 12249156df12SPaolo Bonzini if (bs->backing_hd != NULL) { 122531ca6d07SKevin Wolf QDECREF(options); 12261ba4b6a5SBenoît Canet goto free_exit; 12279156df12SPaolo Bonzini } 12289156df12SPaolo Bonzini 122931ca6d07SKevin Wolf /* NULL means an empty set of options */ 123031ca6d07SKevin Wolf if (options == NULL) { 123131ca6d07SKevin Wolf options = qdict_new(); 123231ca6d07SKevin Wolf } 123331ca6d07SKevin Wolf 12349156df12SPaolo Bonzini bs->open_flags &= ~BDRV_O_NO_BACKING; 12351cb6f506SKevin Wolf if (qdict_haskey(options, "file.filename")) { 12361cb6f506SKevin Wolf backing_filename[0] = '\0'; 12371cb6f506SKevin Wolf } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) { 123831ca6d07SKevin Wolf QDECREF(options); 12391ba4b6a5SBenoît Canet goto free_exit; 1240dbecebddSFam Zheng } else { 12419f07429eSMax Reitz bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX, 12429f07429eSMax Reitz &local_err); 12439f07429eSMax Reitz if (local_err) { 12449f07429eSMax Reitz ret = -EINVAL; 12459f07429eSMax Reitz error_propagate(errp, local_err); 12469f07429eSMax Reitz QDECREF(options); 12479f07429eSMax Reitz goto free_exit; 12489f07429eSMax Reitz } 12499156df12SPaolo Bonzini } 12509156df12SPaolo Bonzini 12518ee79e70SKevin Wolf if (!bs->drv || !bs->drv->supports_backing) { 12528ee79e70SKevin Wolf ret = -EINVAL; 12538ee79e70SKevin Wolf error_setg(errp, "Driver doesn't support backing files"); 12548ee79e70SKevin Wolf QDECREF(options); 12558ee79e70SKevin Wolf goto free_exit; 12568ee79e70SKevin Wolf } 12578ee79e70SKevin Wolf 1258e4e9986bSMarkus Armbruster backing_hd = bdrv_new(); 12598d24cce1SFam Zheng 1260c5f6e493SKevin Wolf if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) { 1261c5f6e493SKevin Wolf qdict_put(options, "driver", qstring_from_str(bs->backing_format)); 12629156df12SPaolo Bonzini } 12639156df12SPaolo Bonzini 1264f67503e5SMax Reitz assert(bs->backing_hd == NULL); 12658d24cce1SFam Zheng ret = bdrv_open(&backing_hd, 1266ddf5636dSMax Reitz *backing_filename ? backing_filename : NULL, NULL, options, 1267c5f6e493SKevin Wolf bdrv_backing_flags(bs->open_flags), NULL, &local_err); 12689156df12SPaolo Bonzini if (ret < 0) { 12698d24cce1SFam Zheng bdrv_unref(backing_hd); 12708d24cce1SFam Zheng backing_hd = NULL; 12719156df12SPaolo Bonzini bs->open_flags |= BDRV_O_NO_BACKING; 1272b04b6b6eSFam Zheng error_setg(errp, "Could not open backing file: %s", 1273b04b6b6eSFam Zheng error_get_pretty(local_err)); 1274b04b6b6eSFam Zheng error_free(local_err); 12751ba4b6a5SBenoît Canet goto free_exit; 12769156df12SPaolo Bonzini } 12778d24cce1SFam Zheng bdrv_set_backing_hd(bs, backing_hd); 1278d80ac658SPeter Feiner 12791ba4b6a5SBenoît Canet free_exit: 12801ba4b6a5SBenoît Canet g_free(backing_filename); 12811ba4b6a5SBenoît Canet return ret; 12829156df12SPaolo Bonzini } 12839156df12SPaolo Bonzini 1284b6ce07aaSKevin Wolf /* 1285da557aacSMax Reitz * Opens a disk image whose options are given as BlockdevRef in another block 1286da557aacSMax Reitz * device's options. 1287da557aacSMax Reitz * 1288da557aacSMax Reitz * If allow_none is true, no image will be opened if filename is false and no 1289da557aacSMax Reitz * BlockdevRef is given. *pbs will remain unchanged and 0 will be returned. 1290da557aacSMax Reitz * 1291da557aacSMax Reitz * bdrev_key specifies the key for the image's BlockdevRef in the options QDict. 1292da557aacSMax Reitz * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict 1293da557aacSMax Reitz * itself, all options starting with "${bdref_key}." are considered part of the 1294da557aacSMax Reitz * BlockdevRef. 1295da557aacSMax Reitz * 1296da557aacSMax Reitz * The BlockdevRef will be removed from the options QDict. 1297f67503e5SMax Reitz * 1298f67503e5SMax Reitz * To conform with the behavior of bdrv_open(), *pbs has to be NULL. 1299da557aacSMax Reitz */ 1300da557aacSMax Reitz int bdrv_open_image(BlockDriverState **pbs, const char *filename, 1301da557aacSMax Reitz QDict *options, const char *bdref_key, int flags, 1302f7d9fd8cSMax Reitz bool allow_none, Error **errp) 1303da557aacSMax Reitz { 1304da557aacSMax Reitz QDict *image_options; 1305da557aacSMax Reitz int ret; 1306da557aacSMax Reitz char *bdref_key_dot; 1307da557aacSMax Reitz const char *reference; 1308da557aacSMax Reitz 1309f67503e5SMax Reitz assert(pbs); 1310f67503e5SMax Reitz assert(*pbs == NULL); 1311f67503e5SMax Reitz 1312da557aacSMax Reitz bdref_key_dot = g_strdup_printf("%s.", bdref_key); 1313da557aacSMax Reitz qdict_extract_subqdict(options, &image_options, bdref_key_dot); 1314da557aacSMax Reitz g_free(bdref_key_dot); 1315da557aacSMax Reitz 1316da557aacSMax Reitz reference = qdict_get_try_str(options, bdref_key); 1317da557aacSMax Reitz if (!filename && !reference && !qdict_size(image_options)) { 1318da557aacSMax Reitz if (allow_none) { 1319da557aacSMax Reitz ret = 0; 1320da557aacSMax Reitz } else { 1321da557aacSMax Reitz error_setg(errp, "A block device must be specified for \"%s\"", 1322da557aacSMax Reitz bdref_key); 1323da557aacSMax Reitz ret = -EINVAL; 1324da557aacSMax Reitz } 1325b20e61e0SMarkus Armbruster QDECREF(image_options); 1326da557aacSMax Reitz goto done; 1327da557aacSMax Reitz } 1328da557aacSMax Reitz 1329f7d9fd8cSMax Reitz ret = bdrv_open(pbs, filename, reference, image_options, flags, NULL, errp); 1330da557aacSMax Reitz 1331da557aacSMax Reitz done: 1332da557aacSMax Reitz qdict_del(options, bdref_key); 1333da557aacSMax Reitz return ret; 1334da557aacSMax Reitz } 1335da557aacSMax Reitz 13366b8aeca5SChen Gang int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp) 1337b998875dSKevin Wolf { 1338b998875dSKevin Wolf /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */ 13391ba4b6a5SBenoît Canet char *tmp_filename = g_malloc0(PATH_MAX + 1); 1340b998875dSKevin Wolf int64_t total_size; 134183d0521aSChunyan Liu QemuOpts *opts = NULL; 1342b998875dSKevin Wolf QDict *snapshot_options; 1343b998875dSKevin Wolf BlockDriverState *bs_snapshot; 1344b998875dSKevin Wolf Error *local_err; 1345b998875dSKevin Wolf int ret; 1346b998875dSKevin Wolf 1347b998875dSKevin Wolf /* if snapshot, we create a temporary backing file and open it 1348b998875dSKevin Wolf instead of opening 'filename' directly */ 1349b998875dSKevin Wolf 1350b998875dSKevin Wolf /* Get the required size from the image */ 1351f187743aSKevin Wolf total_size = bdrv_getlength(bs); 1352f187743aSKevin Wolf if (total_size < 0) { 13536b8aeca5SChen Gang ret = total_size; 1354f187743aSKevin Wolf error_setg_errno(errp, -total_size, "Could not get image size"); 13551ba4b6a5SBenoît Canet goto out; 1356f187743aSKevin Wolf } 1357b998875dSKevin Wolf 1358b998875dSKevin Wolf /* Create the temporary image */ 13591ba4b6a5SBenoît Canet ret = get_tmp_filename(tmp_filename, PATH_MAX + 1); 1360b998875dSKevin Wolf if (ret < 0) { 1361b998875dSKevin Wolf error_setg_errno(errp, -ret, "Could not get temporary filename"); 13621ba4b6a5SBenoît Canet goto out; 1363b998875dSKevin Wolf } 1364b998875dSKevin Wolf 1365ef810437SMax Reitz opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0, 1366c282e1fdSChunyan Liu &error_abort); 136783d0521aSChunyan Liu qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size); 1368ef810437SMax Reitz ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, &local_err); 136983d0521aSChunyan Liu qemu_opts_del(opts); 1370b998875dSKevin Wolf if (ret < 0) { 1371b998875dSKevin Wolf error_setg_errno(errp, -ret, "Could not create temporary overlay " 1372b998875dSKevin Wolf "'%s': %s", tmp_filename, 1373b998875dSKevin Wolf error_get_pretty(local_err)); 1374b998875dSKevin Wolf error_free(local_err); 13751ba4b6a5SBenoît Canet goto out; 1376b998875dSKevin Wolf } 1377b998875dSKevin Wolf 1378b998875dSKevin Wolf /* Prepare a new options QDict for the temporary file */ 1379b998875dSKevin Wolf snapshot_options = qdict_new(); 1380b998875dSKevin Wolf qdict_put(snapshot_options, "file.driver", 1381b998875dSKevin Wolf qstring_from_str("file")); 1382b998875dSKevin Wolf qdict_put(snapshot_options, "file.filename", 1383b998875dSKevin Wolf qstring_from_str(tmp_filename)); 1384b998875dSKevin Wolf 1385e4e9986bSMarkus Armbruster bs_snapshot = bdrv_new(); 1386b998875dSKevin Wolf 1387b998875dSKevin Wolf ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options, 1388ef810437SMax Reitz flags, &bdrv_qcow2, &local_err); 1389b998875dSKevin Wolf if (ret < 0) { 1390b998875dSKevin Wolf error_propagate(errp, local_err); 13911ba4b6a5SBenoît Canet goto out; 1392b998875dSKevin Wolf } 1393b998875dSKevin Wolf 1394b998875dSKevin Wolf bdrv_append(bs_snapshot, bs); 13951ba4b6a5SBenoît Canet 13961ba4b6a5SBenoît Canet out: 13971ba4b6a5SBenoît Canet g_free(tmp_filename); 13986b8aeca5SChen Gang return ret; 1399b998875dSKevin Wolf } 1400b998875dSKevin Wolf 1401da557aacSMax Reitz /* 1402b6ce07aaSKevin Wolf * Opens a disk image (raw, qcow2, vmdk, ...) 1403de9c0cecSKevin Wolf * 1404de9c0cecSKevin Wolf * options is a QDict of options to pass to the block drivers, or NULL for an 1405de9c0cecSKevin Wolf * empty set of options. The reference to the QDict belongs to the block layer 1406de9c0cecSKevin Wolf * after the call (even on failure), so if the caller intends to reuse the 1407de9c0cecSKevin Wolf * dictionary, it needs to use QINCREF() before calling bdrv_open. 1408f67503e5SMax Reitz * 1409f67503e5SMax Reitz * If *pbs is NULL, a new BDS will be created with a pointer to it stored there. 1410f67503e5SMax Reitz * If it is not NULL, the referenced BDS will be reused. 1411ddf5636dSMax Reitz * 1412ddf5636dSMax Reitz * The reference parameter may be used to specify an existing block device which 1413ddf5636dSMax Reitz * should be opened. If specified, neither options nor a filename may be given, 1414ddf5636dSMax Reitz * nor can an existing BDS be reused (that is, *pbs has to be NULL). 1415b6ce07aaSKevin Wolf */ 1416ddf5636dSMax Reitz int bdrv_open(BlockDriverState **pbs, const char *filename, 1417ddf5636dSMax Reitz const char *reference, QDict *options, int flags, 1418ddf5636dSMax Reitz BlockDriver *drv, Error **errp) 1419ea2384d3Sbellard { 1420b6ce07aaSKevin Wolf int ret; 1421f67503e5SMax Reitz BlockDriverState *file = NULL, *bs; 142274fe54f2SKevin Wolf const char *drvname; 142334b5d2c6SMax Reitz Error *local_err = NULL; 1424b1e6fc08SKevin Wolf int snapshot_flags = 0; 142533e3963eSbellard 1426f67503e5SMax Reitz assert(pbs); 1427f67503e5SMax Reitz 1428ddf5636dSMax Reitz if (reference) { 1429ddf5636dSMax Reitz bool options_non_empty = options ? qdict_size(options) : false; 1430ddf5636dSMax Reitz QDECREF(options); 1431ddf5636dSMax Reitz 1432ddf5636dSMax Reitz if (*pbs) { 1433ddf5636dSMax Reitz error_setg(errp, "Cannot reuse an existing BDS when referencing " 1434ddf5636dSMax Reitz "another block device"); 1435ddf5636dSMax Reitz return -EINVAL; 1436ddf5636dSMax Reitz } 1437ddf5636dSMax Reitz 1438ddf5636dSMax Reitz if (filename || options_non_empty) { 1439ddf5636dSMax Reitz error_setg(errp, "Cannot reference an existing block device with " 1440ddf5636dSMax Reitz "additional options or a new filename"); 1441ddf5636dSMax Reitz return -EINVAL; 1442ddf5636dSMax Reitz } 1443ddf5636dSMax Reitz 1444ddf5636dSMax Reitz bs = bdrv_lookup_bs(reference, reference, errp); 1445ddf5636dSMax Reitz if (!bs) { 1446ddf5636dSMax Reitz return -ENODEV; 1447ddf5636dSMax Reitz } 1448ddf5636dSMax Reitz bdrv_ref(bs); 1449ddf5636dSMax Reitz *pbs = bs; 1450ddf5636dSMax Reitz return 0; 1451ddf5636dSMax Reitz } 1452ddf5636dSMax Reitz 1453f67503e5SMax Reitz if (*pbs) { 1454f67503e5SMax Reitz bs = *pbs; 1455f67503e5SMax Reitz } else { 1456e4e9986bSMarkus Armbruster bs = bdrv_new(); 1457f67503e5SMax Reitz } 1458f67503e5SMax Reitz 1459de9c0cecSKevin Wolf /* NULL means an empty set of options */ 1460de9c0cecSKevin Wolf if (options == NULL) { 1461de9c0cecSKevin Wolf options = qdict_new(); 1462de9c0cecSKevin Wolf } 1463de9c0cecSKevin Wolf 146417b005f1SKevin Wolf ret = bdrv_fill_options(&options, &filename, flags, drv, &local_err); 1465462f5bcfSKevin Wolf if (local_err) { 1466462f5bcfSKevin Wolf goto fail; 1467462f5bcfSKevin Wolf } 1468462f5bcfSKevin Wolf 146976c591b0SKevin Wolf /* Find the right image format driver */ 147076c591b0SKevin Wolf drv = NULL; 147176c591b0SKevin Wolf drvname = qdict_get_try_str(options, "driver"); 147276c591b0SKevin Wolf if (drvname) { 147376c591b0SKevin Wolf drv = bdrv_find_format(drvname); 147476c591b0SKevin Wolf qdict_del(options, "driver"); 147576c591b0SKevin Wolf if (!drv) { 147676c591b0SKevin Wolf error_setg(errp, "Unknown driver: '%s'", drvname); 147776c591b0SKevin Wolf ret = -EINVAL; 147876c591b0SKevin Wolf goto fail; 147976c591b0SKevin Wolf } 148076c591b0SKevin Wolf } 148176c591b0SKevin Wolf 148276c591b0SKevin Wolf assert(drvname || !(flags & BDRV_O_PROTOCOL)); 148376c591b0SKevin Wolf if (drv && !drv->bdrv_file_open) { 148476c591b0SKevin Wolf /* If the user explicitly wants a format driver here, we'll need to add 148576c591b0SKevin Wolf * another layer for the protocol in bs->file */ 148676c591b0SKevin Wolf flags &= ~BDRV_O_PROTOCOL; 148776c591b0SKevin Wolf } 148876c591b0SKevin Wolf 1489de9c0cecSKevin Wolf bs->options = options; 1490b6ad491aSKevin Wolf options = qdict_clone_shallow(options); 1491de9c0cecSKevin Wolf 1492f500a6d3SKevin Wolf /* Open image file without format layer */ 1493f4788adcSKevin Wolf if ((flags & BDRV_O_PROTOCOL) == 0) { 1494be028adcSJeff Cody if (flags & BDRV_O_RDWR) { 1495be028adcSJeff Cody flags |= BDRV_O_ALLOW_RDWR; 1496be028adcSJeff Cody } 1497b1e6fc08SKevin Wolf if (flags & BDRV_O_SNAPSHOT) { 1498b1e6fc08SKevin Wolf snapshot_flags = bdrv_temp_snapshot_flags(flags); 1499b1e6fc08SKevin Wolf flags = bdrv_backing_flags(flags); 1500b1e6fc08SKevin Wolf } 1501be028adcSJeff Cody 1502f67503e5SMax Reitz assert(file == NULL); 1503054963f8SMax Reitz ret = bdrv_open_image(&file, filename, options, "file", 15040b50cc88SKevin Wolf bdrv_inherited_flags(flags), 15050b50cc88SKevin Wolf true, &local_err); 1506f500a6d3SKevin Wolf if (ret < 0) { 15078bfea15dSKevin Wolf goto fail; 1508f500a6d3SKevin Wolf } 1509f4788adcSKevin Wolf } 1510f500a6d3SKevin Wolf 151176c591b0SKevin Wolf /* Image format probing */ 151238f3ef57SKevin Wolf bs->probed = !drv; 151376c591b0SKevin Wolf if (!drv && file) { 151434b5d2c6SMax Reitz ret = find_image_format(file, filename, &drv, &local_err); 151517b005f1SKevin Wolf if (ret < 0) { 151617b005f1SKevin Wolf goto fail; 151717b005f1SKevin Wolf } 151876c591b0SKevin Wolf } else if (!drv) { 15192a05cbe4SMax Reitz error_setg(errp, "Must specify either driver or file"); 15202a05cbe4SMax Reitz ret = -EINVAL; 15218bfea15dSKevin Wolf goto fail; 15222a05cbe4SMax Reitz } 1523f500a6d3SKevin Wolf 1524b6ce07aaSKevin Wolf /* Open the image */ 152534b5d2c6SMax Reitz ret = bdrv_open_common(bs, file, options, flags, drv, &local_err); 1526b6ce07aaSKevin Wolf if (ret < 0) { 15278bfea15dSKevin Wolf goto fail; 15286987307cSChristoph Hellwig } 15296987307cSChristoph Hellwig 15302a05cbe4SMax Reitz if (file && (bs->file != file)) { 15314f6fd349SFam Zheng bdrv_unref(file); 1532f500a6d3SKevin Wolf file = NULL; 1533f500a6d3SKevin Wolf } 1534f500a6d3SKevin Wolf 1535b6ce07aaSKevin Wolf /* If there is a backing file, use it */ 15369156df12SPaolo Bonzini if ((flags & BDRV_O_NO_BACKING) == 0) { 153731ca6d07SKevin Wolf QDict *backing_options; 153831ca6d07SKevin Wolf 15395726d872SBenoît Canet qdict_extract_subqdict(options, &backing_options, "backing."); 154034b5d2c6SMax Reitz ret = bdrv_open_backing_file(bs, backing_options, &local_err); 1541b6ce07aaSKevin Wolf if (ret < 0) { 1542b6ad491aSKevin Wolf goto close_and_fail; 1543b6ce07aaSKevin Wolf } 1544b6ce07aaSKevin Wolf } 1545b6ce07aaSKevin Wolf 154691af7014SMax Reitz bdrv_refresh_filename(bs); 154791af7014SMax Reitz 1548b998875dSKevin Wolf /* For snapshot=on, create a temporary qcow2 overlay. bs points to the 1549b998875dSKevin Wolf * temporary snapshot afterwards. */ 1550b1e6fc08SKevin Wolf if (snapshot_flags) { 15516b8aeca5SChen Gang ret = bdrv_append_temp_snapshot(bs, snapshot_flags, &local_err); 1552b998875dSKevin Wolf if (local_err) { 1553b998875dSKevin Wolf goto close_and_fail; 1554b998875dSKevin Wolf } 1555b998875dSKevin Wolf } 1556b998875dSKevin Wolf 1557b6ad491aSKevin Wolf /* Check if any unknown options were used */ 15585acd9d81SMax Reitz if (options && (qdict_size(options) != 0)) { 1559b6ad491aSKevin Wolf const QDictEntry *entry = qdict_first(options); 15605acd9d81SMax Reitz if (flags & BDRV_O_PROTOCOL) { 15615acd9d81SMax Reitz error_setg(errp, "Block protocol '%s' doesn't support the option " 15625acd9d81SMax Reitz "'%s'", drv->format_name, entry->key); 15635acd9d81SMax Reitz } else { 156434b5d2c6SMax Reitz error_setg(errp, "Block format '%s' used by device '%s' doesn't " 15655acd9d81SMax Reitz "support the option '%s'", drv->format_name, 1566bfb197e0SMarkus Armbruster bdrv_get_device_name(bs), entry->key); 15675acd9d81SMax Reitz } 1568b6ad491aSKevin Wolf 1569b6ad491aSKevin Wolf ret = -EINVAL; 1570b6ad491aSKevin Wolf goto close_and_fail; 1571b6ad491aSKevin Wolf } 1572b6ad491aSKevin Wolf 1573b6ce07aaSKevin Wolf if (!bdrv_key_required(bs)) { 1574a7f53e26SMarkus Armbruster if (bs->blk) { 1575a7f53e26SMarkus Armbruster blk_dev_change_media_cb(bs->blk, true); 1576a7f53e26SMarkus Armbruster } 1577c3adb58fSMarkus Armbruster } else if (!runstate_check(RUN_STATE_PRELAUNCH) 1578c3adb58fSMarkus Armbruster && !runstate_check(RUN_STATE_INMIGRATE) 1579c3adb58fSMarkus Armbruster && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */ 1580c3adb58fSMarkus Armbruster error_setg(errp, 1581c3adb58fSMarkus Armbruster "Guest must be stopped for opening of encrypted image"); 1582c3adb58fSMarkus Armbruster ret = -EBUSY; 1583c3adb58fSMarkus Armbruster goto close_and_fail; 1584b6ce07aaSKevin Wolf } 1585b6ce07aaSKevin Wolf 1586c3adb58fSMarkus Armbruster QDECREF(options); 1587f67503e5SMax Reitz *pbs = bs; 1588b6ce07aaSKevin Wolf return 0; 1589b6ce07aaSKevin Wolf 15908bfea15dSKevin Wolf fail: 1591f500a6d3SKevin Wolf if (file != NULL) { 15924f6fd349SFam Zheng bdrv_unref(file); 1593f500a6d3SKevin Wolf } 1594de9c0cecSKevin Wolf QDECREF(bs->options); 1595b6ad491aSKevin Wolf QDECREF(options); 1596de9c0cecSKevin Wolf bs->options = NULL; 1597f67503e5SMax Reitz if (!*pbs) { 1598f67503e5SMax Reitz /* If *pbs is NULL, a new BDS has been created in this function and 1599f67503e5SMax Reitz needs to be freed now. Otherwise, it does not need to be closed, 1600f67503e5SMax Reitz since it has not really been opened yet. */ 1601f67503e5SMax Reitz bdrv_unref(bs); 1602f67503e5SMax Reitz } 160384d18f06SMarkus Armbruster if (local_err) { 160434b5d2c6SMax Reitz error_propagate(errp, local_err); 160534b5d2c6SMax Reitz } 1606b6ad491aSKevin Wolf return ret; 1607de9c0cecSKevin Wolf 1608b6ad491aSKevin Wolf close_and_fail: 1609f67503e5SMax Reitz /* See fail path, but now the BDS has to be always closed */ 1610f67503e5SMax Reitz if (*pbs) { 1611b6ad491aSKevin Wolf bdrv_close(bs); 1612f67503e5SMax Reitz } else { 1613f67503e5SMax Reitz bdrv_unref(bs); 1614f67503e5SMax Reitz } 1615b6ad491aSKevin Wolf QDECREF(options); 161684d18f06SMarkus Armbruster if (local_err) { 161734b5d2c6SMax Reitz error_propagate(errp, local_err); 161834b5d2c6SMax Reitz } 1619b6ce07aaSKevin Wolf return ret; 1620b6ce07aaSKevin Wolf } 1621b6ce07aaSKevin Wolf 1622e971aa12SJeff Cody typedef struct BlockReopenQueueEntry { 1623e971aa12SJeff Cody bool prepared; 1624e971aa12SJeff Cody BDRVReopenState state; 1625e971aa12SJeff Cody QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry; 1626e971aa12SJeff Cody } BlockReopenQueueEntry; 1627e971aa12SJeff Cody 1628e971aa12SJeff Cody /* 1629e971aa12SJeff Cody * Adds a BlockDriverState to a simple queue for an atomic, transactional 1630e971aa12SJeff Cody * reopen of multiple devices. 1631e971aa12SJeff Cody * 1632e971aa12SJeff Cody * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT 1633e971aa12SJeff Cody * already performed, or alternatively may be NULL a new BlockReopenQueue will 1634e971aa12SJeff Cody * be created and initialized. This newly created BlockReopenQueue should be 1635e971aa12SJeff Cody * passed back in for subsequent calls that are intended to be of the same 1636e971aa12SJeff Cody * atomic 'set'. 1637e971aa12SJeff Cody * 1638e971aa12SJeff Cody * bs is the BlockDriverState to add to the reopen queue. 1639e971aa12SJeff Cody * 1640e971aa12SJeff Cody * flags contains the open flags for the associated bs 1641e971aa12SJeff Cody * 1642e971aa12SJeff Cody * returns a pointer to bs_queue, which is either the newly allocated 1643e971aa12SJeff Cody * bs_queue, or the existing bs_queue being used. 1644e971aa12SJeff Cody * 1645e971aa12SJeff Cody */ 1646e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue, 1647e971aa12SJeff Cody BlockDriverState *bs, int flags) 1648e971aa12SJeff Cody { 1649e971aa12SJeff Cody assert(bs != NULL); 1650e971aa12SJeff Cody 1651e971aa12SJeff Cody BlockReopenQueueEntry *bs_entry; 1652e971aa12SJeff Cody if (bs_queue == NULL) { 1653e971aa12SJeff Cody bs_queue = g_new0(BlockReopenQueue, 1); 1654e971aa12SJeff Cody QSIMPLEQ_INIT(bs_queue); 1655e971aa12SJeff Cody } 1656e971aa12SJeff Cody 1657f1f25a2eSKevin Wolf /* bdrv_open() masks this flag out */ 1658f1f25a2eSKevin Wolf flags &= ~BDRV_O_PROTOCOL; 1659f1f25a2eSKevin Wolf 1660e971aa12SJeff Cody if (bs->file) { 1661f1f25a2eSKevin Wolf bdrv_reopen_queue(bs_queue, bs->file, bdrv_inherited_flags(flags)); 1662e971aa12SJeff Cody } 1663e971aa12SJeff Cody 1664e971aa12SJeff Cody bs_entry = g_new0(BlockReopenQueueEntry, 1); 1665e971aa12SJeff Cody QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry); 1666e971aa12SJeff Cody 1667e971aa12SJeff Cody bs_entry->state.bs = bs; 1668e971aa12SJeff Cody bs_entry->state.flags = flags; 1669e971aa12SJeff Cody 1670e971aa12SJeff Cody return bs_queue; 1671e971aa12SJeff Cody } 1672e971aa12SJeff Cody 1673e971aa12SJeff Cody /* 1674e971aa12SJeff Cody * Reopen multiple BlockDriverStates atomically & transactionally. 1675e971aa12SJeff Cody * 1676e971aa12SJeff Cody * The queue passed in (bs_queue) must have been built up previous 1677e971aa12SJeff Cody * via bdrv_reopen_queue(). 1678e971aa12SJeff Cody * 1679e971aa12SJeff Cody * Reopens all BDS specified in the queue, with the appropriate 1680e971aa12SJeff Cody * flags. All devices are prepared for reopen, and failure of any 1681e971aa12SJeff Cody * device will cause all device changes to be abandonded, and intermediate 1682e971aa12SJeff Cody * data cleaned up. 1683e971aa12SJeff Cody * 1684e971aa12SJeff Cody * If all devices prepare successfully, then the changes are committed 1685e971aa12SJeff Cody * to all devices. 1686e971aa12SJeff Cody * 1687e971aa12SJeff Cody */ 1688e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp) 1689e971aa12SJeff Cody { 1690e971aa12SJeff Cody int ret = -1; 1691e971aa12SJeff Cody BlockReopenQueueEntry *bs_entry, *next; 1692e971aa12SJeff Cody Error *local_err = NULL; 1693e971aa12SJeff Cody 1694e971aa12SJeff Cody assert(bs_queue != NULL); 1695e971aa12SJeff Cody 1696e971aa12SJeff Cody bdrv_drain_all(); 1697e971aa12SJeff Cody 1698e971aa12SJeff Cody QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) { 1699e971aa12SJeff Cody if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) { 1700e971aa12SJeff Cody error_propagate(errp, local_err); 1701e971aa12SJeff Cody goto cleanup; 1702e971aa12SJeff Cody } 1703e971aa12SJeff Cody bs_entry->prepared = true; 1704e971aa12SJeff Cody } 1705e971aa12SJeff Cody 1706e971aa12SJeff Cody /* If we reach this point, we have success and just need to apply the 1707e971aa12SJeff Cody * changes 1708e971aa12SJeff Cody */ 1709e971aa12SJeff Cody QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) { 1710e971aa12SJeff Cody bdrv_reopen_commit(&bs_entry->state); 1711e971aa12SJeff Cody } 1712e971aa12SJeff Cody 1713e971aa12SJeff Cody ret = 0; 1714e971aa12SJeff Cody 1715e971aa12SJeff Cody cleanup: 1716e971aa12SJeff Cody QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) { 1717e971aa12SJeff Cody if (ret && bs_entry->prepared) { 1718e971aa12SJeff Cody bdrv_reopen_abort(&bs_entry->state); 1719e971aa12SJeff Cody } 1720e971aa12SJeff Cody g_free(bs_entry); 1721e971aa12SJeff Cody } 1722e971aa12SJeff Cody g_free(bs_queue); 1723e971aa12SJeff Cody return ret; 1724e971aa12SJeff Cody } 1725e971aa12SJeff Cody 1726e971aa12SJeff Cody 1727e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */ 1728e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp) 1729e971aa12SJeff Cody { 1730e971aa12SJeff Cody int ret = -1; 1731e971aa12SJeff Cody Error *local_err = NULL; 1732e971aa12SJeff Cody BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags); 1733e971aa12SJeff Cody 1734e971aa12SJeff Cody ret = bdrv_reopen_multiple(queue, &local_err); 1735e971aa12SJeff Cody if (local_err != NULL) { 1736e971aa12SJeff Cody error_propagate(errp, local_err); 1737e971aa12SJeff Cody } 1738e971aa12SJeff Cody return ret; 1739e971aa12SJeff Cody } 1740e971aa12SJeff Cody 1741e971aa12SJeff Cody 1742e971aa12SJeff Cody /* 1743e971aa12SJeff Cody * Prepares a BlockDriverState for reopen. All changes are staged in the 1744e971aa12SJeff Cody * 'opaque' field of the BDRVReopenState, which is used and allocated by 1745e971aa12SJeff Cody * the block driver layer .bdrv_reopen_prepare() 1746e971aa12SJeff Cody * 1747e971aa12SJeff Cody * bs is the BlockDriverState to reopen 1748e971aa12SJeff Cody * flags are the new open flags 1749e971aa12SJeff Cody * queue is the reopen queue 1750e971aa12SJeff Cody * 1751e971aa12SJeff Cody * Returns 0 on success, non-zero on error. On error errp will be set 1752e971aa12SJeff Cody * as well. 1753e971aa12SJeff Cody * 1754e971aa12SJeff Cody * On failure, bdrv_reopen_abort() will be called to clean up any data. 1755e971aa12SJeff Cody * It is the responsibility of the caller to then call the abort() or 1756e971aa12SJeff Cody * commit() for any other BDS that have been left in a prepare() state 1757e971aa12SJeff Cody * 1758e971aa12SJeff Cody */ 1759e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue, 1760e971aa12SJeff Cody Error **errp) 1761e971aa12SJeff Cody { 1762e971aa12SJeff Cody int ret = -1; 1763e971aa12SJeff Cody Error *local_err = NULL; 1764e971aa12SJeff Cody BlockDriver *drv; 1765e971aa12SJeff Cody 1766e971aa12SJeff Cody assert(reopen_state != NULL); 1767e971aa12SJeff Cody assert(reopen_state->bs->drv != NULL); 1768e971aa12SJeff Cody drv = reopen_state->bs->drv; 1769e971aa12SJeff Cody 1770e971aa12SJeff Cody /* if we are to stay read-only, do not allow permission change 1771e971aa12SJeff Cody * to r/w */ 1772e971aa12SJeff Cody if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) && 1773e971aa12SJeff Cody reopen_state->flags & BDRV_O_RDWR) { 1774e971aa12SJeff Cody error_set(errp, QERR_DEVICE_IS_READ_ONLY, 1775bfb197e0SMarkus Armbruster bdrv_get_device_name(reopen_state->bs)); 1776e971aa12SJeff Cody goto error; 1777e971aa12SJeff Cody } 1778e971aa12SJeff Cody 1779e971aa12SJeff Cody 1780e971aa12SJeff Cody ret = bdrv_flush(reopen_state->bs); 1781e971aa12SJeff Cody if (ret) { 1782e971aa12SJeff Cody error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive", 1783e971aa12SJeff Cody strerror(-ret)); 1784e971aa12SJeff Cody goto error; 1785e971aa12SJeff Cody } 1786e971aa12SJeff Cody 1787e971aa12SJeff Cody if (drv->bdrv_reopen_prepare) { 1788e971aa12SJeff Cody ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err); 1789e971aa12SJeff Cody if (ret) { 1790e971aa12SJeff Cody if (local_err != NULL) { 1791e971aa12SJeff Cody error_propagate(errp, local_err); 1792e971aa12SJeff Cody } else { 1793d8b6895fSLuiz Capitulino error_setg(errp, "failed while preparing to reopen image '%s'", 1794e971aa12SJeff Cody reopen_state->bs->filename); 1795e971aa12SJeff Cody } 1796e971aa12SJeff Cody goto error; 1797e971aa12SJeff Cody } 1798e971aa12SJeff Cody } else { 1799e971aa12SJeff Cody /* It is currently mandatory to have a bdrv_reopen_prepare() 1800e971aa12SJeff Cody * handler for each supported drv. */ 1801e971aa12SJeff Cody error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED, 1802bfb197e0SMarkus Armbruster drv->format_name, bdrv_get_device_name(reopen_state->bs), 1803e971aa12SJeff Cody "reopening of file"); 1804e971aa12SJeff Cody ret = -1; 1805e971aa12SJeff Cody goto error; 1806e971aa12SJeff Cody } 1807e971aa12SJeff Cody 1808e971aa12SJeff Cody ret = 0; 1809e971aa12SJeff Cody 1810e971aa12SJeff Cody error: 1811e971aa12SJeff Cody return ret; 1812e971aa12SJeff Cody } 1813e971aa12SJeff Cody 1814e971aa12SJeff Cody /* 1815e971aa12SJeff Cody * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and 1816e971aa12SJeff Cody * makes them final by swapping the staging BlockDriverState contents into 1817e971aa12SJeff Cody * the active BlockDriverState contents. 1818e971aa12SJeff Cody */ 1819e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state) 1820e971aa12SJeff Cody { 1821e971aa12SJeff Cody BlockDriver *drv; 1822e971aa12SJeff Cody 1823e971aa12SJeff Cody assert(reopen_state != NULL); 1824e971aa12SJeff Cody drv = reopen_state->bs->drv; 1825e971aa12SJeff Cody assert(drv != NULL); 1826e971aa12SJeff Cody 1827e971aa12SJeff Cody /* If there are any driver level actions to take */ 1828e971aa12SJeff Cody if (drv->bdrv_reopen_commit) { 1829e971aa12SJeff Cody drv->bdrv_reopen_commit(reopen_state); 1830e971aa12SJeff Cody } 1831e971aa12SJeff Cody 1832e971aa12SJeff Cody /* set BDS specific flags now */ 1833e971aa12SJeff Cody reopen_state->bs->open_flags = reopen_state->flags; 1834e971aa12SJeff Cody reopen_state->bs->enable_write_cache = !!(reopen_state->flags & 1835e971aa12SJeff Cody BDRV_O_CACHE_WB); 1836e971aa12SJeff Cody reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR); 1837355ef4acSKevin Wolf 18383baca891SKevin Wolf bdrv_refresh_limits(reopen_state->bs, NULL); 1839e971aa12SJeff Cody } 1840e971aa12SJeff Cody 1841e971aa12SJeff Cody /* 1842e971aa12SJeff Cody * Abort the reopen, and delete and free the staged changes in 1843e971aa12SJeff Cody * reopen_state 1844e971aa12SJeff Cody */ 1845e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state) 1846e971aa12SJeff Cody { 1847e971aa12SJeff Cody BlockDriver *drv; 1848e971aa12SJeff Cody 1849e971aa12SJeff Cody assert(reopen_state != NULL); 1850e971aa12SJeff Cody drv = reopen_state->bs->drv; 1851e971aa12SJeff Cody assert(drv != NULL); 1852e971aa12SJeff Cody 1853e971aa12SJeff Cody if (drv->bdrv_reopen_abort) { 1854e971aa12SJeff Cody drv->bdrv_reopen_abort(reopen_state); 1855e971aa12SJeff Cody } 1856e971aa12SJeff Cody } 1857e971aa12SJeff Cody 1858e971aa12SJeff Cody 1859fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs) 1860fc01f7e7Sbellard { 186133384421SMax Reitz BdrvAioNotifier *ban, *ban_next; 186233384421SMax Reitz 18633e914655SPaolo Bonzini if (bs->job) { 18643e914655SPaolo Bonzini block_job_cancel_sync(bs->job); 18653e914655SPaolo Bonzini } 186658fda173SStefan Hajnoczi bdrv_drain_all(); /* complete I/O */ 186758fda173SStefan Hajnoczi bdrv_flush(bs); 186858fda173SStefan Hajnoczi bdrv_drain_all(); /* in case flush left pending I/O */ 1869d7d512f6SPaolo Bonzini notifier_list_notify(&bs->close_notifiers, bs); 18707094f12fSKevin Wolf 18713cbc002cSPaolo Bonzini if (bs->drv) { 1872557df6acSStefan Hajnoczi if (bs->backing_hd) { 1873826b6ca0SFam Zheng BlockDriverState *backing_hd = bs->backing_hd; 1874826b6ca0SFam Zheng bdrv_set_backing_hd(bs, NULL); 1875826b6ca0SFam Zheng bdrv_unref(backing_hd); 1876557df6acSStefan Hajnoczi } 1877ea2384d3Sbellard bs->drv->bdrv_close(bs); 18787267c094SAnthony Liguori g_free(bs->opaque); 1879ea2384d3Sbellard bs->opaque = NULL; 1880ea2384d3Sbellard bs->drv = NULL; 188153fec9d3SStefan Hajnoczi bs->copy_on_read = 0; 1882a275fa42SPaolo Bonzini bs->backing_file[0] = '\0'; 1883a275fa42SPaolo Bonzini bs->backing_format[0] = '\0'; 18846405875cSPaolo Bonzini bs->total_sectors = 0; 18856405875cSPaolo Bonzini bs->encrypted = 0; 18866405875cSPaolo Bonzini bs->valid_key = 0; 18876405875cSPaolo Bonzini bs->sg = 0; 18886405875cSPaolo Bonzini bs->growable = 0; 18890d51b4deSAsias He bs->zero_beyond_eof = false; 1890de9c0cecSKevin Wolf QDECREF(bs->options); 1891de9c0cecSKevin Wolf bs->options = NULL; 189291af7014SMax Reitz QDECREF(bs->full_open_options); 189391af7014SMax Reitz bs->full_open_options = NULL; 1894b338082bSbellard 189566f82ceeSKevin Wolf if (bs->file != NULL) { 18964f6fd349SFam Zheng bdrv_unref(bs->file); 18970ac9377dSPaolo Bonzini bs->file = NULL; 189866f82ceeSKevin Wolf } 18999ca11154SPavel Hrdina } 190066f82ceeSKevin Wolf 1901a7f53e26SMarkus Armbruster if (bs->blk) { 1902a7f53e26SMarkus Armbruster blk_dev_change_media_cb(bs->blk, false); 1903a7f53e26SMarkus Armbruster } 190498f90dbaSZhi Yong Wu 190598f90dbaSZhi Yong Wu /*throttling disk I/O limits*/ 190698f90dbaSZhi Yong Wu if (bs->io_limits_enabled) { 190798f90dbaSZhi Yong Wu bdrv_io_limits_disable(bs); 190898f90dbaSZhi Yong Wu } 190933384421SMax Reitz 191033384421SMax Reitz QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) { 191133384421SMax Reitz g_free(ban); 191233384421SMax Reitz } 191333384421SMax Reitz QLIST_INIT(&bs->aio_notifiers); 1914b338082bSbellard } 1915b338082bSbellard 19162bc93fedSMORITA Kazutaka void bdrv_close_all(void) 19172bc93fedSMORITA Kazutaka { 19182bc93fedSMORITA Kazutaka BlockDriverState *bs; 19192bc93fedSMORITA Kazutaka 1920dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 1921ed78cda3SStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 1922ed78cda3SStefan Hajnoczi 1923ed78cda3SStefan Hajnoczi aio_context_acquire(aio_context); 19242bc93fedSMORITA Kazutaka bdrv_close(bs); 1925ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 19262bc93fedSMORITA Kazutaka } 19272bc93fedSMORITA Kazutaka } 19282bc93fedSMORITA Kazutaka 192988266f5aSStefan Hajnoczi /* Check if any requests are in-flight (including throttled requests) */ 193088266f5aSStefan Hajnoczi static bool bdrv_requests_pending(BlockDriverState *bs) 193188266f5aSStefan Hajnoczi { 193288266f5aSStefan Hajnoczi if (!QLIST_EMPTY(&bs->tracked_requests)) { 193388266f5aSStefan Hajnoczi return true; 193488266f5aSStefan Hajnoczi } 1935cc0681c4SBenoît Canet if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) { 1936cc0681c4SBenoît Canet return true; 1937cc0681c4SBenoît Canet } 1938cc0681c4SBenoît Canet if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) { 193988266f5aSStefan Hajnoczi return true; 194088266f5aSStefan Hajnoczi } 194188266f5aSStefan Hajnoczi if (bs->file && bdrv_requests_pending(bs->file)) { 194288266f5aSStefan Hajnoczi return true; 194388266f5aSStefan Hajnoczi } 194488266f5aSStefan Hajnoczi if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) { 194588266f5aSStefan Hajnoczi return true; 194688266f5aSStefan Hajnoczi } 194788266f5aSStefan Hajnoczi return false; 194888266f5aSStefan Hajnoczi } 194988266f5aSStefan Hajnoczi 19505b98db0aSStefan Hajnoczi static bool bdrv_drain_one(BlockDriverState *bs) 19515b98db0aSStefan Hajnoczi { 19525b98db0aSStefan Hajnoczi bool bs_busy; 19535b98db0aSStefan Hajnoczi 19545b98db0aSStefan Hajnoczi bdrv_flush_io_queue(bs); 19555b98db0aSStefan Hajnoczi bdrv_start_throttled_reqs(bs); 19565b98db0aSStefan Hajnoczi bs_busy = bdrv_requests_pending(bs); 19575b98db0aSStefan Hajnoczi bs_busy |= aio_poll(bdrv_get_aio_context(bs), bs_busy); 19585b98db0aSStefan Hajnoczi return bs_busy; 19595b98db0aSStefan Hajnoczi } 19605b98db0aSStefan Hajnoczi 19615b98db0aSStefan Hajnoczi /* 19625b98db0aSStefan Hajnoczi * Wait for pending requests to complete on a single BlockDriverState subtree 19635b98db0aSStefan Hajnoczi * 19645b98db0aSStefan Hajnoczi * See the warning in bdrv_drain_all(). This function can only be called if 19655b98db0aSStefan Hajnoczi * you are sure nothing can generate I/O because you have op blockers 19665b98db0aSStefan Hajnoczi * installed. 19675b98db0aSStefan Hajnoczi * 19685b98db0aSStefan Hajnoczi * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState 19695b98db0aSStefan Hajnoczi * AioContext. 19705b98db0aSStefan Hajnoczi */ 19715b98db0aSStefan Hajnoczi void bdrv_drain(BlockDriverState *bs) 19725b98db0aSStefan Hajnoczi { 19735b98db0aSStefan Hajnoczi while (bdrv_drain_one(bs)) { 19745b98db0aSStefan Hajnoczi /* Keep iterating */ 19755b98db0aSStefan Hajnoczi } 19765b98db0aSStefan Hajnoczi } 19775b98db0aSStefan Hajnoczi 1978922453bcSStefan Hajnoczi /* 1979922453bcSStefan Hajnoczi * Wait for pending requests to complete across all BlockDriverStates 1980922453bcSStefan Hajnoczi * 1981922453bcSStefan Hajnoczi * This function does not flush data to disk, use bdrv_flush_all() for that 1982922453bcSStefan Hajnoczi * after calling this function. 19834c355d53SZhi Yong Wu * 19844c355d53SZhi Yong Wu * Note that completion of an asynchronous I/O operation can trigger any 19854c355d53SZhi Yong Wu * number of other I/O operations on other devices---for example a coroutine 19864c355d53SZhi Yong Wu * can be arbitrarily complex and a constant flow of I/O can come until the 19874c355d53SZhi Yong Wu * coroutine is complete. Because of this, it is not possible to have a 19884c355d53SZhi Yong Wu * function to drain a single device's I/O queue. 1989922453bcSStefan Hajnoczi */ 1990922453bcSStefan Hajnoczi void bdrv_drain_all(void) 1991922453bcSStefan Hajnoczi { 199288266f5aSStefan Hajnoczi /* Always run first iteration so any pending completion BHs run */ 199388266f5aSStefan Hajnoczi bool busy = true; 1994922453bcSStefan Hajnoczi BlockDriverState *bs; 1995922453bcSStefan Hajnoczi 199688266f5aSStefan Hajnoczi while (busy) { 19979b536adcSStefan Hajnoczi busy = false; 1998922453bcSStefan Hajnoczi 19999b536adcSStefan Hajnoczi QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 20009b536adcSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 20019b536adcSStefan Hajnoczi 20029b536adcSStefan Hajnoczi aio_context_acquire(aio_context); 20035b98db0aSStefan Hajnoczi busy |= bdrv_drain_one(bs); 20049b536adcSStefan Hajnoczi aio_context_release(aio_context); 20059b536adcSStefan Hajnoczi } 2006922453bcSStefan Hajnoczi } 2007922453bcSStefan Hajnoczi } 2008922453bcSStefan Hajnoczi 2009dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and 2010dc364f4cSBenoît Canet * graph_bdrv_state list. 2011d22b2f41SRyan Harper Also, NULL terminate the device_name to prevent double remove */ 2012d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs) 2013d22b2f41SRyan Harper { 2014bfb197e0SMarkus Armbruster /* 2015bfb197e0SMarkus Armbruster * Take care to remove bs from bdrv_states only when it's actually 2016bfb197e0SMarkus Armbruster * in it. Note that bs->device_list.tqe_prev is initially null, 2017bfb197e0SMarkus Armbruster * and gets set to non-null by QTAILQ_INSERT_TAIL(). Establish 2018bfb197e0SMarkus Armbruster * the useful invariant "bs in bdrv_states iff bs->tqe_prev" by 2019bfb197e0SMarkus Armbruster * resetting it to null on remove. 2020bfb197e0SMarkus Armbruster */ 2021bfb197e0SMarkus Armbruster if (bs->device_list.tqe_prev) { 2022dc364f4cSBenoît Canet QTAILQ_REMOVE(&bdrv_states, bs, device_list); 2023bfb197e0SMarkus Armbruster bs->device_list.tqe_prev = NULL; 2024d22b2f41SRyan Harper } 2025dc364f4cSBenoît Canet if (bs->node_name[0] != '\0') { 2026dc364f4cSBenoît Canet QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list); 2027dc364f4cSBenoît Canet } 2028dc364f4cSBenoît Canet bs->node_name[0] = '\0'; 2029d22b2f41SRyan Harper } 2030d22b2f41SRyan Harper 2031e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs) 2032e023b2e2SPaolo Bonzini { 2033e023b2e2SPaolo Bonzini if (bs->drv && bs->drv->bdrv_rebind) { 2034e023b2e2SPaolo Bonzini bs->drv->bdrv_rebind(bs); 2035e023b2e2SPaolo Bonzini } 2036e023b2e2SPaolo Bonzini } 2037e023b2e2SPaolo Bonzini 20384ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest, 20394ddc07caSPaolo Bonzini BlockDriverState *bs_src) 20404ddc07caSPaolo Bonzini { 20414ddc07caSPaolo Bonzini /* move some fields that need to stay attached to the device */ 20424ddc07caSPaolo Bonzini 20434ddc07caSPaolo Bonzini /* dev info */ 20441b7fd729SPaolo Bonzini bs_dest->guest_block_size = bs_src->guest_block_size; 20454ddc07caSPaolo Bonzini bs_dest->copy_on_read = bs_src->copy_on_read; 20464ddc07caSPaolo Bonzini 20474ddc07caSPaolo Bonzini bs_dest->enable_write_cache = bs_src->enable_write_cache; 20484ddc07caSPaolo Bonzini 2049cc0681c4SBenoît Canet /* i/o throttled req */ 2050cc0681c4SBenoît Canet memcpy(&bs_dest->throttle_state, 2051cc0681c4SBenoît Canet &bs_src->throttle_state, 2052cc0681c4SBenoît Canet sizeof(ThrottleState)); 2053cc0681c4SBenoît Canet bs_dest->throttled_reqs[0] = bs_src->throttled_reqs[0]; 2054cc0681c4SBenoît Canet bs_dest->throttled_reqs[1] = bs_src->throttled_reqs[1]; 20554ddc07caSPaolo Bonzini bs_dest->io_limits_enabled = bs_src->io_limits_enabled; 20564ddc07caSPaolo Bonzini 20574ddc07caSPaolo Bonzini /* r/w error */ 20584ddc07caSPaolo Bonzini bs_dest->on_read_error = bs_src->on_read_error; 20594ddc07caSPaolo Bonzini bs_dest->on_write_error = bs_src->on_write_error; 20604ddc07caSPaolo Bonzini 20614ddc07caSPaolo Bonzini /* i/o status */ 20624ddc07caSPaolo Bonzini bs_dest->iostatus_enabled = bs_src->iostatus_enabled; 20634ddc07caSPaolo Bonzini bs_dest->iostatus = bs_src->iostatus; 20644ddc07caSPaolo Bonzini 20654ddc07caSPaolo Bonzini /* dirty bitmap */ 2066e4654d2dSFam Zheng bs_dest->dirty_bitmaps = bs_src->dirty_bitmaps; 20674ddc07caSPaolo Bonzini 20689fcb0251SFam Zheng /* reference count */ 20699fcb0251SFam Zheng bs_dest->refcnt = bs_src->refcnt; 20709fcb0251SFam Zheng 20714ddc07caSPaolo Bonzini /* job */ 20724ddc07caSPaolo Bonzini bs_dest->job = bs_src->job; 20734ddc07caSPaolo Bonzini 20744ddc07caSPaolo Bonzini /* keep the same entry in bdrv_states */ 2075dc364f4cSBenoît Canet bs_dest->device_list = bs_src->device_list; 20767e7d56d9SMarkus Armbruster bs_dest->blk = bs_src->blk; 20777e7d56d9SMarkus Armbruster 2078fbe40ff7SFam Zheng memcpy(bs_dest->op_blockers, bs_src->op_blockers, 2079fbe40ff7SFam Zheng sizeof(bs_dest->op_blockers)); 20804ddc07caSPaolo Bonzini } 20814ddc07caSPaolo Bonzini 20824ddc07caSPaolo Bonzini /* 20834ddc07caSPaolo Bonzini * Swap bs contents for two image chains while they are live, 20844ddc07caSPaolo Bonzini * while keeping required fields on the BlockDriverState that is 20854ddc07caSPaolo Bonzini * actually attached to a device. 20864ddc07caSPaolo Bonzini * 20874ddc07caSPaolo Bonzini * This will modify the BlockDriverState fields, and swap contents 20884ddc07caSPaolo Bonzini * between bs_new and bs_old. Both bs_new and bs_old are modified. 20894ddc07caSPaolo Bonzini * 2090bfb197e0SMarkus Armbruster * bs_new must not be attached to a BlockBackend. 20914ddc07caSPaolo Bonzini * 20924ddc07caSPaolo Bonzini * This function does not create any image files. 20934ddc07caSPaolo Bonzini */ 20944ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old) 20954ddc07caSPaolo Bonzini { 20964ddc07caSPaolo Bonzini BlockDriverState tmp; 20974ddc07caSPaolo Bonzini 209890ce8a06SBenoît Canet /* The code needs to swap the node_name but simply swapping node_list won't 209990ce8a06SBenoît Canet * work so first remove the nodes from the graph list, do the swap then 210090ce8a06SBenoît Canet * insert them back if needed. 210190ce8a06SBenoît Canet */ 210290ce8a06SBenoît Canet if (bs_new->node_name[0] != '\0') { 210390ce8a06SBenoît Canet QTAILQ_REMOVE(&graph_bdrv_states, bs_new, node_list); 210490ce8a06SBenoît Canet } 210590ce8a06SBenoît Canet if (bs_old->node_name[0] != '\0') { 210690ce8a06SBenoît Canet QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list); 210790ce8a06SBenoît Canet } 210890ce8a06SBenoît Canet 2109bfb197e0SMarkus Armbruster /* bs_new must be unattached and shouldn't have anything fancy enabled */ 21107e7d56d9SMarkus Armbruster assert(!bs_new->blk); 2111e4654d2dSFam Zheng assert(QLIST_EMPTY(&bs_new->dirty_bitmaps)); 21124ddc07caSPaolo Bonzini assert(bs_new->job == NULL); 21134ddc07caSPaolo Bonzini assert(bs_new->io_limits_enabled == false); 2114cc0681c4SBenoît Canet assert(!throttle_have_timer(&bs_new->throttle_state)); 21154ddc07caSPaolo Bonzini 21164ddc07caSPaolo Bonzini tmp = *bs_new; 21174ddc07caSPaolo Bonzini *bs_new = *bs_old; 21184ddc07caSPaolo Bonzini *bs_old = tmp; 21194ddc07caSPaolo Bonzini 21204ddc07caSPaolo Bonzini /* there are some fields that should not be swapped, move them back */ 21214ddc07caSPaolo Bonzini bdrv_move_feature_fields(&tmp, bs_old); 21224ddc07caSPaolo Bonzini bdrv_move_feature_fields(bs_old, bs_new); 21234ddc07caSPaolo Bonzini bdrv_move_feature_fields(bs_new, &tmp); 21244ddc07caSPaolo Bonzini 2125bfb197e0SMarkus Armbruster /* bs_new must remain unattached */ 21267e7d56d9SMarkus Armbruster assert(!bs_new->blk); 21274ddc07caSPaolo Bonzini 21284ddc07caSPaolo Bonzini /* Check a few fields that should remain attached to the device */ 21294ddc07caSPaolo Bonzini assert(bs_new->job == NULL); 21304ddc07caSPaolo Bonzini assert(bs_new->io_limits_enabled == false); 2131cc0681c4SBenoît Canet assert(!throttle_have_timer(&bs_new->throttle_state)); 21324ddc07caSPaolo Bonzini 213390ce8a06SBenoît Canet /* insert the nodes back into the graph node list if needed */ 213490ce8a06SBenoît Canet if (bs_new->node_name[0] != '\0') { 213590ce8a06SBenoît Canet QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_new, node_list); 213690ce8a06SBenoît Canet } 213790ce8a06SBenoît Canet if (bs_old->node_name[0] != '\0') { 213890ce8a06SBenoît Canet QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_old, node_list); 213990ce8a06SBenoît Canet } 214090ce8a06SBenoît Canet 21414ddc07caSPaolo Bonzini bdrv_rebind(bs_new); 21424ddc07caSPaolo Bonzini bdrv_rebind(bs_old); 21434ddc07caSPaolo Bonzini } 21444ddc07caSPaolo Bonzini 21458802d1fdSJeff Cody /* 21468802d1fdSJeff Cody * Add new bs contents at the top of an image chain while the chain is 21478802d1fdSJeff Cody * live, while keeping required fields on the top layer. 21488802d1fdSJeff Cody * 21498802d1fdSJeff Cody * This will modify the BlockDriverState fields, and swap contents 21508802d1fdSJeff Cody * between bs_new and bs_top. Both bs_new and bs_top are modified. 21518802d1fdSJeff Cody * 2152bfb197e0SMarkus Armbruster * bs_new must not be attached to a BlockBackend. 2153f6801b83SJeff Cody * 21548802d1fdSJeff Cody * This function does not create any image files. 21558802d1fdSJeff Cody */ 21568802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top) 21578802d1fdSJeff Cody { 21584ddc07caSPaolo Bonzini bdrv_swap(bs_new, bs_top); 21598802d1fdSJeff Cody 21608802d1fdSJeff Cody /* The contents of 'tmp' will become bs_top, as we are 21618802d1fdSJeff Cody * swapping bs_new and bs_top contents. */ 21628d24cce1SFam Zheng bdrv_set_backing_hd(bs_top, bs_new); 21638802d1fdSJeff Cody } 21648802d1fdSJeff Cody 21654f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs) 2166b338082bSbellard { 21673e914655SPaolo Bonzini assert(!bs->job); 21683718d8abSFam Zheng assert(bdrv_op_blocker_is_empty(bs)); 21694f6fd349SFam Zheng assert(!bs->refcnt); 2170e4654d2dSFam Zheng assert(QLIST_EMPTY(&bs->dirty_bitmaps)); 217118846deeSMarkus Armbruster 2172e1b5c52eSStefan Hajnoczi bdrv_close(bs); 2173e1b5c52eSStefan Hajnoczi 21741b7bdbc1SStefan Hajnoczi /* remove from list, if necessary */ 2175d22b2f41SRyan Harper bdrv_make_anon(bs); 217634c6f050Saurel32 21777267c094SAnthony Liguori g_free(bs); 2178fc01f7e7Sbellard } 2179fc01f7e7Sbellard 2180e97fc193Saliguori /* 2181e97fc193Saliguori * Run consistency checks on an image 2182e97fc193Saliguori * 2183e076f338SKevin Wolf * Returns 0 if the check could be completed (it doesn't mean that the image is 2184a1c7273bSStefan Weil * free of errors) or -errno when an internal error occurred. The results of the 2185e076f338SKevin Wolf * check are stored in res. 2186e97fc193Saliguori */ 21874534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix) 2188e97fc193Saliguori { 2189908bcd54SMax Reitz if (bs->drv == NULL) { 2190908bcd54SMax Reitz return -ENOMEDIUM; 2191908bcd54SMax Reitz } 2192e97fc193Saliguori if (bs->drv->bdrv_check == NULL) { 2193e97fc193Saliguori return -ENOTSUP; 2194e97fc193Saliguori } 2195e97fc193Saliguori 2196e076f338SKevin Wolf memset(res, 0, sizeof(*res)); 21974534ff54SKevin Wolf return bs->drv->bdrv_check(bs, res, fix); 2198e97fc193Saliguori } 2199e97fc193Saliguori 22008a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048 22018a426614SKevin Wolf 220233e3963eSbellard /* commit COW file into the raw image */ 220333e3963eSbellard int bdrv_commit(BlockDriverState *bs) 220433e3963eSbellard { 220519cb3738Sbellard BlockDriver *drv = bs->drv; 220672706ea4SJeff Cody int64_t sector, total_sectors, length, backing_length; 22078a426614SKevin Wolf int n, ro, open_flags; 22080bce597dSJeff Cody int ret = 0; 220972706ea4SJeff Cody uint8_t *buf = NULL; 2210c2cba3d9SJim Meyering char filename[PATH_MAX]; 221133e3963eSbellard 221219cb3738Sbellard if (!drv) 221319cb3738Sbellard return -ENOMEDIUM; 221433e3963eSbellard 22154dca4b63SNaphtali Sprei if (!bs->backing_hd) { 22164dca4b63SNaphtali Sprei return -ENOTSUP; 22174dca4b63SNaphtali Sprei } 22184dca4b63SNaphtali Sprei 22193718d8abSFam Zheng if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, NULL) || 22203718d8abSFam Zheng bdrv_op_is_blocked(bs->backing_hd, BLOCK_OP_TYPE_COMMIT, NULL)) { 22212d3735d3SStefan Hajnoczi return -EBUSY; 22222d3735d3SStefan Hajnoczi } 22232d3735d3SStefan Hajnoczi 22244dca4b63SNaphtali Sprei ro = bs->backing_hd->read_only; 2225c2cba3d9SJim Meyering /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */ 2226c2cba3d9SJim Meyering pstrcpy(filename, sizeof(filename), bs->backing_hd->filename); 22274dca4b63SNaphtali Sprei open_flags = bs->backing_hd->open_flags; 22284dca4b63SNaphtali Sprei 22294dca4b63SNaphtali Sprei if (ro) { 22300bce597dSJeff Cody if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) { 22310bce597dSJeff Cody return -EACCES; 22324dca4b63SNaphtali Sprei } 2233ea2384d3Sbellard } 2234ea2384d3Sbellard 223572706ea4SJeff Cody length = bdrv_getlength(bs); 223672706ea4SJeff Cody if (length < 0) { 223772706ea4SJeff Cody ret = length; 223872706ea4SJeff Cody goto ro_cleanup; 223972706ea4SJeff Cody } 224072706ea4SJeff Cody 224172706ea4SJeff Cody backing_length = bdrv_getlength(bs->backing_hd); 224272706ea4SJeff Cody if (backing_length < 0) { 224372706ea4SJeff Cody ret = backing_length; 224472706ea4SJeff Cody goto ro_cleanup; 224572706ea4SJeff Cody } 224672706ea4SJeff Cody 224772706ea4SJeff Cody /* If our top snapshot is larger than the backing file image, 224872706ea4SJeff Cody * grow the backing file image if possible. If not possible, 224972706ea4SJeff Cody * we must return an error */ 225072706ea4SJeff Cody if (length > backing_length) { 225172706ea4SJeff Cody ret = bdrv_truncate(bs->backing_hd, length); 225272706ea4SJeff Cody if (ret < 0) { 225372706ea4SJeff Cody goto ro_cleanup; 225472706ea4SJeff Cody } 225572706ea4SJeff Cody } 225672706ea4SJeff Cody 225772706ea4SJeff Cody total_sectors = length >> BDRV_SECTOR_BITS; 2258857d4f46SKevin Wolf 2259857d4f46SKevin Wolf /* qemu_try_blockalign() for bs will choose an alignment that works for 2260857d4f46SKevin Wolf * bs->backing_hd as well, so no need to compare the alignment manually. */ 2261857d4f46SKevin Wolf buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE); 2262857d4f46SKevin Wolf if (buf == NULL) { 2263857d4f46SKevin Wolf ret = -ENOMEM; 2264857d4f46SKevin Wolf goto ro_cleanup; 2265857d4f46SKevin Wolf } 22668a426614SKevin Wolf 22678a426614SKevin Wolf for (sector = 0; sector < total_sectors; sector += n) { 2268d663640cSPaolo Bonzini ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n); 2269d663640cSPaolo Bonzini if (ret < 0) { 2270d663640cSPaolo Bonzini goto ro_cleanup; 2271d663640cSPaolo Bonzini } 2272d663640cSPaolo Bonzini if (ret) { 2273dabfa6ccSKevin Wolf ret = bdrv_read(bs, sector, buf, n); 2274dabfa6ccSKevin Wolf if (ret < 0) { 22754dca4b63SNaphtali Sprei goto ro_cleanup; 227633e3963eSbellard } 227733e3963eSbellard 2278dabfa6ccSKevin Wolf ret = bdrv_write(bs->backing_hd, sector, buf, n); 2279dabfa6ccSKevin Wolf if (ret < 0) { 22804dca4b63SNaphtali Sprei goto ro_cleanup; 228133e3963eSbellard } 228233e3963eSbellard } 228333e3963eSbellard } 228495389c86Sbellard 22851d44952fSChristoph Hellwig if (drv->bdrv_make_empty) { 22861d44952fSChristoph Hellwig ret = drv->bdrv_make_empty(bs); 2287dabfa6ccSKevin Wolf if (ret < 0) { 2288dabfa6ccSKevin Wolf goto ro_cleanup; 2289dabfa6ccSKevin Wolf } 22901d44952fSChristoph Hellwig bdrv_flush(bs); 22911d44952fSChristoph Hellwig } 229295389c86Sbellard 22933f5075aeSChristoph Hellwig /* 22943f5075aeSChristoph Hellwig * Make sure all data we wrote to the backing device is actually 22953f5075aeSChristoph Hellwig * stable on disk. 22963f5075aeSChristoph Hellwig */ 2297dabfa6ccSKevin Wolf if (bs->backing_hd) { 22983f5075aeSChristoph Hellwig bdrv_flush(bs->backing_hd); 2299dabfa6ccSKevin Wolf } 23004dca4b63SNaphtali Sprei 2301dabfa6ccSKevin Wolf ret = 0; 23024dca4b63SNaphtali Sprei ro_cleanup: 2303857d4f46SKevin Wolf qemu_vfree(buf); 23044dca4b63SNaphtali Sprei 23054dca4b63SNaphtali Sprei if (ro) { 23060bce597dSJeff Cody /* ignoring error return here */ 23070bce597dSJeff Cody bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL); 23084dca4b63SNaphtali Sprei } 23094dca4b63SNaphtali Sprei 23101d44952fSChristoph Hellwig return ret; 231133e3963eSbellard } 231233e3963eSbellard 2313e8877497SStefan Hajnoczi int bdrv_commit_all(void) 23146ab4b5abSMarkus Armbruster { 23156ab4b5abSMarkus Armbruster BlockDriverState *bs; 23166ab4b5abSMarkus Armbruster 2317dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 2318ed78cda3SStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 2319ed78cda3SStefan Hajnoczi 2320ed78cda3SStefan Hajnoczi aio_context_acquire(aio_context); 2321272d2d8eSJeff Cody if (bs->drv && bs->backing_hd) { 2322e8877497SStefan Hajnoczi int ret = bdrv_commit(bs); 2323e8877497SStefan Hajnoczi if (ret < 0) { 2324ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 2325e8877497SStefan Hajnoczi return ret; 23266ab4b5abSMarkus Armbruster } 23276ab4b5abSMarkus Armbruster } 2328ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 2329272d2d8eSJeff Cody } 2330e8877497SStefan Hajnoczi return 0; 2331e8877497SStefan Hajnoczi } 23326ab4b5abSMarkus Armbruster 2333dbffbdcfSStefan Hajnoczi /** 2334dbffbdcfSStefan Hajnoczi * Remove an active request from the tracked requests list 2335dbffbdcfSStefan Hajnoczi * 2336dbffbdcfSStefan Hajnoczi * This function should be called when a tracked request is completing. 2337dbffbdcfSStefan Hajnoczi */ 2338dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req) 2339dbffbdcfSStefan Hajnoczi { 23402dbafdc0SKevin Wolf if (req->serialising) { 23412dbafdc0SKevin Wolf req->bs->serialising_in_flight--; 23422dbafdc0SKevin Wolf } 23432dbafdc0SKevin Wolf 2344dbffbdcfSStefan Hajnoczi QLIST_REMOVE(req, list); 2345f4658285SStefan Hajnoczi qemu_co_queue_restart_all(&req->wait_queue); 2346dbffbdcfSStefan Hajnoczi } 2347dbffbdcfSStefan Hajnoczi 2348dbffbdcfSStefan Hajnoczi /** 2349dbffbdcfSStefan Hajnoczi * Add an active request to the tracked requests list 2350dbffbdcfSStefan Hajnoczi */ 2351dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req, 2352dbffbdcfSStefan Hajnoczi BlockDriverState *bs, 2353793ed47aSKevin Wolf int64_t offset, 2354793ed47aSKevin Wolf unsigned int bytes, bool is_write) 2355dbffbdcfSStefan Hajnoczi { 2356dbffbdcfSStefan Hajnoczi *req = (BdrvTrackedRequest){ 2357dbffbdcfSStefan Hajnoczi .bs = bs, 2358793ed47aSKevin Wolf .offset = offset, 2359793ed47aSKevin Wolf .bytes = bytes, 2360dbffbdcfSStefan Hajnoczi .is_write = is_write, 23615f8b6491SStefan Hajnoczi .co = qemu_coroutine_self(), 23622dbafdc0SKevin Wolf .serialising = false, 23637327145fSKevin Wolf .overlap_offset = offset, 23647327145fSKevin Wolf .overlap_bytes = bytes, 2365dbffbdcfSStefan Hajnoczi }; 2366dbffbdcfSStefan Hajnoczi 2367f4658285SStefan Hajnoczi qemu_co_queue_init(&req->wait_queue); 2368f4658285SStefan Hajnoczi 2369dbffbdcfSStefan Hajnoczi QLIST_INSERT_HEAD(&bs->tracked_requests, req, list); 2370dbffbdcfSStefan Hajnoczi } 2371dbffbdcfSStefan Hajnoczi 2372e96126ffSKevin Wolf static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align) 23732dbafdc0SKevin Wolf { 23747327145fSKevin Wolf int64_t overlap_offset = req->offset & ~(align - 1); 2375e96126ffSKevin Wolf unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align) 23767327145fSKevin Wolf - overlap_offset; 23777327145fSKevin Wolf 23782dbafdc0SKevin Wolf if (!req->serialising) { 23792dbafdc0SKevin Wolf req->bs->serialising_in_flight++; 23802dbafdc0SKevin Wolf req->serialising = true; 23812dbafdc0SKevin Wolf } 23827327145fSKevin Wolf 23837327145fSKevin Wolf req->overlap_offset = MIN(req->overlap_offset, overlap_offset); 23847327145fSKevin Wolf req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes); 23852dbafdc0SKevin Wolf } 23862dbafdc0SKevin Wolf 2387d83947acSStefan Hajnoczi /** 2388d83947acSStefan Hajnoczi * Round a region to cluster boundaries 2389d83947acSStefan Hajnoczi */ 2390343bded4SPaolo Bonzini void bdrv_round_to_clusters(BlockDriverState *bs, 2391d83947acSStefan Hajnoczi int64_t sector_num, int nb_sectors, 2392d83947acSStefan Hajnoczi int64_t *cluster_sector_num, 2393d83947acSStefan Hajnoczi int *cluster_nb_sectors) 2394d83947acSStefan Hajnoczi { 2395d83947acSStefan Hajnoczi BlockDriverInfo bdi; 2396d83947acSStefan Hajnoczi 2397d83947acSStefan Hajnoczi if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) { 2398d83947acSStefan Hajnoczi *cluster_sector_num = sector_num; 2399d83947acSStefan Hajnoczi *cluster_nb_sectors = nb_sectors; 2400d83947acSStefan Hajnoczi } else { 2401d83947acSStefan Hajnoczi int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE; 2402d83947acSStefan Hajnoczi *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c); 2403d83947acSStefan Hajnoczi *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num + 2404d83947acSStefan Hajnoczi nb_sectors, c); 2405d83947acSStefan Hajnoczi } 2406d83947acSStefan Hajnoczi } 2407d83947acSStefan Hajnoczi 24087327145fSKevin Wolf static int bdrv_get_cluster_size(BlockDriverState *bs) 2409793ed47aSKevin Wolf { 2410793ed47aSKevin Wolf BlockDriverInfo bdi; 24117327145fSKevin Wolf int ret; 2412793ed47aSKevin Wolf 24137327145fSKevin Wolf ret = bdrv_get_info(bs, &bdi); 24147327145fSKevin Wolf if (ret < 0 || bdi.cluster_size == 0) { 24157327145fSKevin Wolf return bs->request_alignment; 2416793ed47aSKevin Wolf } else { 24177327145fSKevin Wolf return bdi.cluster_size; 2418793ed47aSKevin Wolf } 2419793ed47aSKevin Wolf } 2420793ed47aSKevin Wolf 2421f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req, 2422793ed47aSKevin Wolf int64_t offset, unsigned int bytes) 2423793ed47aSKevin Wolf { 2424d83947acSStefan Hajnoczi /* aaaa bbbb */ 24257327145fSKevin Wolf if (offset >= req->overlap_offset + req->overlap_bytes) { 2426d83947acSStefan Hajnoczi return false; 2427d83947acSStefan Hajnoczi } 2428d83947acSStefan Hajnoczi /* bbbb aaaa */ 24297327145fSKevin Wolf if (req->overlap_offset >= offset + bytes) { 2430d83947acSStefan Hajnoczi return false; 2431d83947acSStefan Hajnoczi } 2432d83947acSStefan Hajnoczi return true; 2433f4658285SStefan Hajnoczi } 2434f4658285SStefan Hajnoczi 243528de2dcdSKevin Wolf static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self) 2436f4658285SStefan Hajnoczi { 24372dbafdc0SKevin Wolf BlockDriverState *bs = self->bs; 2438f4658285SStefan Hajnoczi BdrvTrackedRequest *req; 2439f4658285SStefan Hajnoczi bool retry; 244028de2dcdSKevin Wolf bool waited = false; 2441f4658285SStefan Hajnoczi 24422dbafdc0SKevin Wolf if (!bs->serialising_in_flight) { 244328de2dcdSKevin Wolf return false; 24442dbafdc0SKevin Wolf } 24452dbafdc0SKevin Wolf 2446f4658285SStefan Hajnoczi do { 2447f4658285SStefan Hajnoczi retry = false; 2448f4658285SStefan Hajnoczi QLIST_FOREACH(req, &bs->tracked_requests, list) { 24492dbafdc0SKevin Wolf if (req == self || (!req->serialising && !self->serialising)) { 245065afd211SKevin Wolf continue; 245165afd211SKevin Wolf } 24527327145fSKevin Wolf if (tracked_request_overlaps(req, self->overlap_offset, 24537327145fSKevin Wolf self->overlap_bytes)) 24547327145fSKevin Wolf { 24555f8b6491SStefan Hajnoczi /* Hitting this means there was a reentrant request, for 24565f8b6491SStefan Hajnoczi * example, a block driver issuing nested requests. This must 24575f8b6491SStefan Hajnoczi * never happen since it means deadlock. 24585f8b6491SStefan Hajnoczi */ 24595f8b6491SStefan Hajnoczi assert(qemu_coroutine_self() != req->co); 24605f8b6491SStefan Hajnoczi 24616460440fSKevin Wolf /* If the request is already (indirectly) waiting for us, or 24626460440fSKevin Wolf * will wait for us as soon as it wakes up, then just go on 24636460440fSKevin Wolf * (instead of producing a deadlock in the former case). */ 24646460440fSKevin Wolf if (!req->waiting_for) { 24656460440fSKevin Wolf self->waiting_for = req; 2466f4658285SStefan Hajnoczi qemu_co_queue_wait(&req->wait_queue); 24676460440fSKevin Wolf self->waiting_for = NULL; 2468f4658285SStefan Hajnoczi retry = true; 246928de2dcdSKevin Wolf waited = true; 2470f4658285SStefan Hajnoczi break; 2471f4658285SStefan Hajnoczi } 2472f4658285SStefan Hajnoczi } 24736460440fSKevin Wolf } 2474f4658285SStefan Hajnoczi } while (retry); 247528de2dcdSKevin Wolf 247628de2dcdSKevin Wolf return waited; 2477f4658285SStefan Hajnoczi } 2478f4658285SStefan Hajnoczi 2479756e6736SKevin Wolf /* 2480756e6736SKevin Wolf * Return values: 2481756e6736SKevin Wolf * 0 - success 2482756e6736SKevin Wolf * -EINVAL - backing format specified, but no file 2483756e6736SKevin Wolf * -ENOSPC - can't update the backing file because no space is left in the 2484756e6736SKevin Wolf * image file header 2485756e6736SKevin Wolf * -ENOTSUP - format driver doesn't support changing the backing file 2486756e6736SKevin Wolf */ 2487756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs, 2488756e6736SKevin Wolf const char *backing_file, const char *backing_fmt) 2489756e6736SKevin Wolf { 2490756e6736SKevin Wolf BlockDriver *drv = bs->drv; 2491469ef350SPaolo Bonzini int ret; 2492756e6736SKevin Wolf 24935f377794SPaolo Bonzini /* Backing file format doesn't make sense without a backing file */ 24945f377794SPaolo Bonzini if (backing_fmt && !backing_file) { 24955f377794SPaolo Bonzini return -EINVAL; 24965f377794SPaolo Bonzini } 24975f377794SPaolo Bonzini 2498756e6736SKevin Wolf if (drv->bdrv_change_backing_file != NULL) { 2499469ef350SPaolo Bonzini ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt); 2500756e6736SKevin Wolf } else { 2501469ef350SPaolo Bonzini ret = -ENOTSUP; 2502756e6736SKevin Wolf } 2503469ef350SPaolo Bonzini 2504469ef350SPaolo Bonzini if (ret == 0) { 2505469ef350SPaolo Bonzini pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: ""); 2506469ef350SPaolo Bonzini pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: ""); 2507469ef350SPaolo Bonzini } 2508469ef350SPaolo Bonzini return ret; 2509756e6736SKevin Wolf } 2510756e6736SKevin Wolf 25116ebdcee2SJeff Cody /* 25126ebdcee2SJeff Cody * Finds the image layer in the chain that has 'bs' as its backing file. 25136ebdcee2SJeff Cody * 25146ebdcee2SJeff Cody * active is the current topmost image. 25156ebdcee2SJeff Cody * 25166ebdcee2SJeff Cody * Returns NULL if bs is not found in active's image chain, 25176ebdcee2SJeff Cody * or if active == bs. 25184caf0fcdSJeff Cody * 25194caf0fcdSJeff Cody * Returns the bottommost base image if bs == NULL. 25206ebdcee2SJeff Cody */ 25216ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active, 25226ebdcee2SJeff Cody BlockDriverState *bs) 25236ebdcee2SJeff Cody { 25244caf0fcdSJeff Cody while (active && bs != active->backing_hd) { 25254caf0fcdSJeff Cody active = active->backing_hd; 25266ebdcee2SJeff Cody } 25276ebdcee2SJeff Cody 25284caf0fcdSJeff Cody return active; 25296ebdcee2SJeff Cody } 25306ebdcee2SJeff Cody 25314caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */ 25324caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs) 25334caf0fcdSJeff Cody { 25344caf0fcdSJeff Cody return bdrv_find_overlay(bs, NULL); 25356ebdcee2SJeff Cody } 25366ebdcee2SJeff Cody 25376ebdcee2SJeff Cody typedef struct BlkIntermediateStates { 25386ebdcee2SJeff Cody BlockDriverState *bs; 25396ebdcee2SJeff Cody QSIMPLEQ_ENTRY(BlkIntermediateStates) entry; 25406ebdcee2SJeff Cody } BlkIntermediateStates; 25416ebdcee2SJeff Cody 25426ebdcee2SJeff Cody 25436ebdcee2SJeff Cody /* 25446ebdcee2SJeff Cody * Drops images above 'base' up to and including 'top', and sets the image 25456ebdcee2SJeff Cody * above 'top' to have base as its backing file. 25466ebdcee2SJeff Cody * 25476ebdcee2SJeff Cody * Requires that the overlay to 'top' is opened r/w, so that the backing file 25486ebdcee2SJeff Cody * information in 'bs' can be properly updated. 25496ebdcee2SJeff Cody * 25506ebdcee2SJeff Cody * E.g., this will convert the following chain: 25516ebdcee2SJeff Cody * bottom <- base <- intermediate <- top <- active 25526ebdcee2SJeff Cody * 25536ebdcee2SJeff Cody * to 25546ebdcee2SJeff Cody * 25556ebdcee2SJeff Cody * bottom <- base <- active 25566ebdcee2SJeff Cody * 25576ebdcee2SJeff Cody * It is allowed for bottom==base, in which case it converts: 25586ebdcee2SJeff Cody * 25596ebdcee2SJeff Cody * base <- intermediate <- top <- active 25606ebdcee2SJeff Cody * 25616ebdcee2SJeff Cody * to 25626ebdcee2SJeff Cody * 25636ebdcee2SJeff Cody * base <- active 25646ebdcee2SJeff Cody * 256554e26900SJeff Cody * If backing_file_str is non-NULL, it will be used when modifying top's 256654e26900SJeff Cody * overlay image metadata. 256754e26900SJeff Cody * 25686ebdcee2SJeff Cody * Error conditions: 25696ebdcee2SJeff Cody * if active == top, that is considered an error 25706ebdcee2SJeff Cody * 25716ebdcee2SJeff Cody */ 25726ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top, 257354e26900SJeff Cody BlockDriverState *base, const char *backing_file_str) 25746ebdcee2SJeff Cody { 25756ebdcee2SJeff Cody BlockDriverState *intermediate; 25766ebdcee2SJeff Cody BlockDriverState *base_bs = NULL; 25776ebdcee2SJeff Cody BlockDriverState *new_top_bs = NULL; 25786ebdcee2SJeff Cody BlkIntermediateStates *intermediate_state, *next; 25796ebdcee2SJeff Cody int ret = -EIO; 25806ebdcee2SJeff Cody 25816ebdcee2SJeff Cody QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete; 25826ebdcee2SJeff Cody QSIMPLEQ_INIT(&states_to_delete); 25836ebdcee2SJeff Cody 25846ebdcee2SJeff Cody if (!top->drv || !base->drv) { 25856ebdcee2SJeff Cody goto exit; 25866ebdcee2SJeff Cody } 25876ebdcee2SJeff Cody 25886ebdcee2SJeff Cody new_top_bs = bdrv_find_overlay(active, top); 25896ebdcee2SJeff Cody 25906ebdcee2SJeff Cody if (new_top_bs == NULL) { 25916ebdcee2SJeff Cody /* we could not find the image above 'top', this is an error */ 25926ebdcee2SJeff Cody goto exit; 25936ebdcee2SJeff Cody } 25946ebdcee2SJeff Cody 25956ebdcee2SJeff Cody /* special case of new_top_bs->backing_hd already pointing to base - nothing 25966ebdcee2SJeff Cody * to do, no intermediate images */ 25976ebdcee2SJeff Cody if (new_top_bs->backing_hd == base) { 25986ebdcee2SJeff Cody ret = 0; 25996ebdcee2SJeff Cody goto exit; 26006ebdcee2SJeff Cody } 26016ebdcee2SJeff Cody 26026ebdcee2SJeff Cody intermediate = top; 26036ebdcee2SJeff Cody 26046ebdcee2SJeff Cody /* now we will go down through the list, and add each BDS we find 26056ebdcee2SJeff Cody * into our deletion queue, until we hit the 'base' 26066ebdcee2SJeff Cody */ 26076ebdcee2SJeff Cody while (intermediate) { 26085839e53bSMarkus Armbruster intermediate_state = g_new0(BlkIntermediateStates, 1); 26096ebdcee2SJeff Cody intermediate_state->bs = intermediate; 26106ebdcee2SJeff Cody QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry); 26116ebdcee2SJeff Cody 26126ebdcee2SJeff Cody if (intermediate->backing_hd == base) { 26136ebdcee2SJeff Cody base_bs = intermediate->backing_hd; 26146ebdcee2SJeff Cody break; 26156ebdcee2SJeff Cody } 26166ebdcee2SJeff Cody intermediate = intermediate->backing_hd; 26176ebdcee2SJeff Cody } 26186ebdcee2SJeff Cody if (base_bs == NULL) { 26196ebdcee2SJeff Cody /* something went wrong, we did not end at the base. safely 26206ebdcee2SJeff Cody * unravel everything, and exit with error */ 26216ebdcee2SJeff Cody goto exit; 26226ebdcee2SJeff Cody } 26236ebdcee2SJeff Cody 26246ebdcee2SJeff Cody /* success - we can delete the intermediate states, and link top->base */ 262554e26900SJeff Cody backing_file_str = backing_file_str ? backing_file_str : base_bs->filename; 262654e26900SJeff Cody ret = bdrv_change_backing_file(new_top_bs, backing_file_str, 26276ebdcee2SJeff Cody base_bs->drv ? base_bs->drv->format_name : ""); 26286ebdcee2SJeff Cody if (ret) { 26296ebdcee2SJeff Cody goto exit; 26306ebdcee2SJeff Cody } 2631920beae1SFam Zheng bdrv_set_backing_hd(new_top_bs, base_bs); 26326ebdcee2SJeff Cody 26336ebdcee2SJeff Cody QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) { 26346ebdcee2SJeff Cody /* so that bdrv_close() does not recursively close the chain */ 2635920beae1SFam Zheng bdrv_set_backing_hd(intermediate_state->bs, NULL); 26364f6fd349SFam Zheng bdrv_unref(intermediate_state->bs); 26376ebdcee2SJeff Cody } 26386ebdcee2SJeff Cody ret = 0; 26396ebdcee2SJeff Cody 26406ebdcee2SJeff Cody exit: 26416ebdcee2SJeff Cody QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) { 26426ebdcee2SJeff Cody g_free(intermediate_state); 26436ebdcee2SJeff Cody } 26446ebdcee2SJeff Cody return ret; 26456ebdcee2SJeff Cody } 26466ebdcee2SJeff Cody 26476ebdcee2SJeff Cody 264871d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset, 264971d0770cSaliguori size_t size) 265071d0770cSaliguori { 265171d0770cSaliguori int64_t len; 265271d0770cSaliguori 26531dd3a447SKevin Wolf if (size > INT_MAX) { 26541dd3a447SKevin Wolf return -EIO; 26551dd3a447SKevin Wolf } 26561dd3a447SKevin Wolf 265771d0770cSaliguori if (!bdrv_is_inserted(bs)) 265871d0770cSaliguori return -ENOMEDIUM; 265971d0770cSaliguori 266071d0770cSaliguori if (bs->growable) 266171d0770cSaliguori return 0; 266271d0770cSaliguori 266371d0770cSaliguori len = bdrv_getlength(bs); 266471d0770cSaliguori 2665fbb7b4e0SKevin Wolf if (offset < 0) 2666fbb7b4e0SKevin Wolf return -EIO; 2667fbb7b4e0SKevin Wolf 2668fbb7b4e0SKevin Wolf if ((offset > len) || (len - offset < size)) 266971d0770cSaliguori return -EIO; 267071d0770cSaliguori 267171d0770cSaliguori return 0; 267271d0770cSaliguori } 267371d0770cSaliguori 267471d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num, 267571d0770cSaliguori int nb_sectors) 267671d0770cSaliguori { 267754db38a4SKevin Wolf if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) { 26788f4754edSKevin Wolf return -EIO; 26798f4754edSKevin Wolf } 26808f4754edSKevin Wolf 2681eb5a3165SJes Sorensen return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE, 2682eb5a3165SJes Sorensen nb_sectors * BDRV_SECTOR_SIZE); 268371d0770cSaliguori } 268471d0770cSaliguori 26851c9805a3SStefan Hajnoczi typedef struct RwCo { 26861c9805a3SStefan Hajnoczi BlockDriverState *bs; 2687775aa8b6SKevin Wolf int64_t offset; 26881c9805a3SStefan Hajnoczi QEMUIOVector *qiov; 26891c9805a3SStefan Hajnoczi bool is_write; 26901c9805a3SStefan Hajnoczi int ret; 26914105eaaaSPeter Lieven BdrvRequestFlags flags; 26921c9805a3SStefan Hajnoczi } RwCo; 26931c9805a3SStefan Hajnoczi 26941c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque) 2695fc01f7e7Sbellard { 26961c9805a3SStefan Hajnoczi RwCo *rwco = opaque; 2697fc01f7e7Sbellard 26981c9805a3SStefan Hajnoczi if (!rwco->is_write) { 2699775aa8b6SKevin Wolf rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset, 2700775aa8b6SKevin Wolf rwco->qiov->size, rwco->qiov, 27014105eaaaSPeter Lieven rwco->flags); 27021c9805a3SStefan Hajnoczi } else { 2703775aa8b6SKevin Wolf rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset, 2704775aa8b6SKevin Wolf rwco->qiov->size, rwco->qiov, 27054105eaaaSPeter Lieven rwco->flags); 27061c9805a3SStefan Hajnoczi } 27071c9805a3SStefan Hajnoczi } 2708e7a8a783SKevin Wolf 27091c9805a3SStefan Hajnoczi /* 27108d3b1a2dSKevin Wolf * Process a vectored synchronous request using coroutines 27111c9805a3SStefan Hajnoczi */ 2712775aa8b6SKevin Wolf static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset, 27134105eaaaSPeter Lieven QEMUIOVector *qiov, bool is_write, 27144105eaaaSPeter Lieven BdrvRequestFlags flags) 27151c9805a3SStefan Hajnoczi { 27161c9805a3SStefan Hajnoczi Coroutine *co; 27171c9805a3SStefan Hajnoczi RwCo rwco = { 27181c9805a3SStefan Hajnoczi .bs = bs, 2719775aa8b6SKevin Wolf .offset = offset, 27208d3b1a2dSKevin Wolf .qiov = qiov, 27211c9805a3SStefan Hajnoczi .is_write = is_write, 27221c9805a3SStefan Hajnoczi .ret = NOT_DONE, 27234105eaaaSPeter Lieven .flags = flags, 27241c9805a3SStefan Hajnoczi }; 27251c9805a3SStefan Hajnoczi 2726498e386cSZhi Yong Wu /** 2727498e386cSZhi Yong Wu * In sync call context, when the vcpu is blocked, this throttling timer 2728498e386cSZhi Yong Wu * will not fire; so the I/O throttling function has to be disabled here 2729498e386cSZhi Yong Wu * if it has been enabled. 2730498e386cSZhi Yong Wu */ 2731498e386cSZhi Yong Wu if (bs->io_limits_enabled) { 2732498e386cSZhi Yong Wu fprintf(stderr, "Disabling I/O throttling on '%s' due " 2733498e386cSZhi Yong Wu "to synchronous I/O.\n", bdrv_get_device_name(bs)); 2734498e386cSZhi Yong Wu bdrv_io_limits_disable(bs); 2735498e386cSZhi Yong Wu } 2736498e386cSZhi Yong Wu 27371c9805a3SStefan Hajnoczi if (qemu_in_coroutine()) { 27381c9805a3SStefan Hajnoczi /* Fast-path if already in coroutine context */ 27391c9805a3SStefan Hajnoczi bdrv_rw_co_entry(&rwco); 27401c9805a3SStefan Hajnoczi } else { 27412572b37aSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 27422572b37aSStefan Hajnoczi 27431c9805a3SStefan Hajnoczi co = qemu_coroutine_create(bdrv_rw_co_entry); 27441c9805a3SStefan Hajnoczi qemu_coroutine_enter(co, &rwco); 27451c9805a3SStefan Hajnoczi while (rwco.ret == NOT_DONE) { 27462572b37aSStefan Hajnoczi aio_poll(aio_context, true); 27471c9805a3SStefan Hajnoczi } 27481c9805a3SStefan Hajnoczi } 27491c9805a3SStefan Hajnoczi return rwco.ret; 2750e7a8a783SKevin Wolf } 2751e7a8a783SKevin Wolf 27528d3b1a2dSKevin Wolf /* 27538d3b1a2dSKevin Wolf * Process a synchronous request using coroutines 27548d3b1a2dSKevin Wolf */ 27558d3b1a2dSKevin Wolf static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf, 27564105eaaaSPeter Lieven int nb_sectors, bool is_write, BdrvRequestFlags flags) 27578d3b1a2dSKevin Wolf { 27588d3b1a2dSKevin Wolf QEMUIOVector qiov; 27598d3b1a2dSKevin Wolf struct iovec iov = { 27608d3b1a2dSKevin Wolf .iov_base = (void *)buf, 27618d3b1a2dSKevin Wolf .iov_len = nb_sectors * BDRV_SECTOR_SIZE, 27628d3b1a2dSKevin Wolf }; 27638d3b1a2dSKevin Wolf 2764da15ee51SKevin Wolf if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) { 2765da15ee51SKevin Wolf return -EINVAL; 2766da15ee51SKevin Wolf } 2767da15ee51SKevin Wolf 27688d3b1a2dSKevin Wolf qemu_iovec_init_external(&qiov, &iov, 1); 2769775aa8b6SKevin Wolf return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS, 2770775aa8b6SKevin Wolf &qiov, is_write, flags); 27718d3b1a2dSKevin Wolf } 27728d3b1a2dSKevin Wolf 27731c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */ 27741c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num, 27751c9805a3SStefan Hajnoczi uint8_t *buf, int nb_sectors) 27761c9805a3SStefan Hajnoczi { 27774105eaaaSPeter Lieven return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0); 277883f64091Sbellard } 2779fc01f7e7Sbellard 278007d27a44SMarkus Armbruster /* Just like bdrv_read(), but with I/O throttling temporarily disabled */ 278107d27a44SMarkus Armbruster int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num, 278207d27a44SMarkus Armbruster uint8_t *buf, int nb_sectors) 278307d27a44SMarkus Armbruster { 278407d27a44SMarkus Armbruster bool enabled; 278507d27a44SMarkus Armbruster int ret; 278607d27a44SMarkus Armbruster 278707d27a44SMarkus Armbruster enabled = bs->io_limits_enabled; 278807d27a44SMarkus Armbruster bs->io_limits_enabled = false; 27894e7395e8SPeter Lieven ret = bdrv_read(bs, sector_num, buf, nb_sectors); 279007d27a44SMarkus Armbruster bs->io_limits_enabled = enabled; 279107d27a44SMarkus Armbruster return ret; 279207d27a44SMarkus Armbruster } 279307d27a44SMarkus Armbruster 279419cb3738Sbellard /* Return < 0 if error. Important errors are: 279519cb3738Sbellard -EIO generic I/O error (may happen for all errors) 279619cb3738Sbellard -ENOMEDIUM No media inserted. 279719cb3738Sbellard -EINVAL Invalid sector number or nb_sectors 279819cb3738Sbellard -EACCES Trying to write a read-only device 279919cb3738Sbellard */ 2800fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num, 2801fc01f7e7Sbellard const uint8_t *buf, int nb_sectors) 2802fc01f7e7Sbellard { 28034105eaaaSPeter Lieven return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0); 280483f64091Sbellard } 280583f64091Sbellard 2806aa7bfbffSPeter Lieven int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num, 2807aa7bfbffSPeter Lieven int nb_sectors, BdrvRequestFlags flags) 28084105eaaaSPeter Lieven { 28094105eaaaSPeter Lieven return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true, 2810aa7bfbffSPeter Lieven BDRV_REQ_ZERO_WRITE | flags); 28118d3b1a2dSKevin Wolf } 28128d3b1a2dSKevin Wolf 2813d75cbb5eSPeter Lieven /* 2814d75cbb5eSPeter Lieven * Completely zero out a block device with the help of bdrv_write_zeroes. 2815d75cbb5eSPeter Lieven * The operation is sped up by checking the block status and only writing 2816d75cbb5eSPeter Lieven * zeroes to the device if they currently do not return zeroes. Optional 2817d75cbb5eSPeter Lieven * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP). 2818d75cbb5eSPeter Lieven * 2819d75cbb5eSPeter Lieven * Returns < 0 on error, 0 on success. For error codes see bdrv_write(). 2820d75cbb5eSPeter Lieven */ 2821d75cbb5eSPeter Lieven int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags) 2822d75cbb5eSPeter Lieven { 2823d32f7c10SMarkus Armbruster int64_t target_sectors, ret, nb_sectors, sector_num = 0; 2824d75cbb5eSPeter Lieven int n; 2825d75cbb5eSPeter Lieven 2826d32f7c10SMarkus Armbruster target_sectors = bdrv_nb_sectors(bs); 2827d32f7c10SMarkus Armbruster if (target_sectors < 0) { 2828d32f7c10SMarkus Armbruster return target_sectors; 28299ce10c0bSKevin Wolf } 28309ce10c0bSKevin Wolf 2831d75cbb5eSPeter Lieven for (;;) { 2832d32f7c10SMarkus Armbruster nb_sectors = target_sectors - sector_num; 2833d75cbb5eSPeter Lieven if (nb_sectors <= 0) { 2834d75cbb5eSPeter Lieven return 0; 2835d75cbb5eSPeter Lieven } 2836f3a9cfddSFam Zheng if (nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) { 2837f3a9cfddSFam Zheng nb_sectors = INT_MAX / BDRV_SECTOR_SIZE; 2838d75cbb5eSPeter Lieven } 2839d75cbb5eSPeter Lieven ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n); 28403d94ce60SPeter Lieven if (ret < 0) { 28413d94ce60SPeter Lieven error_report("error getting block status at sector %" PRId64 ": %s", 28423d94ce60SPeter Lieven sector_num, strerror(-ret)); 28433d94ce60SPeter Lieven return ret; 28443d94ce60SPeter Lieven } 2845d75cbb5eSPeter Lieven if (ret & BDRV_BLOCK_ZERO) { 2846d75cbb5eSPeter Lieven sector_num += n; 2847d75cbb5eSPeter Lieven continue; 2848d75cbb5eSPeter Lieven } 2849d75cbb5eSPeter Lieven ret = bdrv_write_zeroes(bs, sector_num, n, flags); 2850d75cbb5eSPeter Lieven if (ret < 0) { 2851d75cbb5eSPeter Lieven error_report("error writing zeroes at sector %" PRId64 ": %s", 2852d75cbb5eSPeter Lieven sector_num, strerror(-ret)); 2853d75cbb5eSPeter Lieven return ret; 2854d75cbb5eSPeter Lieven } 2855d75cbb5eSPeter Lieven sector_num += n; 2856d75cbb5eSPeter Lieven } 2857d75cbb5eSPeter Lieven } 2858d75cbb5eSPeter Lieven 2859a3ef6571SKevin Wolf int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes) 286083f64091Sbellard { 2861a3ef6571SKevin Wolf QEMUIOVector qiov; 2862a3ef6571SKevin Wolf struct iovec iov = { 2863a3ef6571SKevin Wolf .iov_base = (void *)buf, 2864a3ef6571SKevin Wolf .iov_len = bytes, 2865a3ef6571SKevin Wolf }; 28669a8c4cceSKevin Wolf int ret; 286783f64091Sbellard 2868a3ef6571SKevin Wolf if (bytes < 0) { 2869a3ef6571SKevin Wolf return -EINVAL; 287083f64091Sbellard } 287183f64091Sbellard 2872a3ef6571SKevin Wolf qemu_iovec_init_external(&qiov, &iov, 1); 2873a3ef6571SKevin Wolf ret = bdrv_prwv_co(bs, offset, &qiov, false, 0); 2874a3ef6571SKevin Wolf if (ret < 0) { 28759a8c4cceSKevin Wolf return ret; 287683f64091Sbellard } 287783f64091Sbellard 2878a3ef6571SKevin Wolf return bytes; 287983f64091Sbellard } 288083f64091Sbellard 28818d3b1a2dSKevin Wolf int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov) 288283f64091Sbellard { 28839a8c4cceSKevin Wolf int ret; 288483f64091Sbellard 28858407d5d7SKevin Wolf ret = bdrv_prwv_co(bs, offset, qiov, true, 0); 28868d3b1a2dSKevin Wolf if (ret < 0) { 28879a8c4cceSKevin Wolf return ret; 28888d3b1a2dSKevin Wolf } 28898d3b1a2dSKevin Wolf 28908d3b1a2dSKevin Wolf return qiov->size; 28918d3b1a2dSKevin Wolf } 28928d3b1a2dSKevin Wolf 28938d3b1a2dSKevin Wolf int bdrv_pwrite(BlockDriverState *bs, int64_t offset, 28948407d5d7SKevin Wolf const void *buf, int bytes) 28958d3b1a2dSKevin Wolf { 28968d3b1a2dSKevin Wolf QEMUIOVector qiov; 28978d3b1a2dSKevin Wolf struct iovec iov = { 28988d3b1a2dSKevin Wolf .iov_base = (void *) buf, 28998407d5d7SKevin Wolf .iov_len = bytes, 29008d3b1a2dSKevin Wolf }; 29018d3b1a2dSKevin Wolf 29028407d5d7SKevin Wolf if (bytes < 0) { 29038407d5d7SKevin Wolf return -EINVAL; 29048407d5d7SKevin Wolf } 29058407d5d7SKevin Wolf 29068d3b1a2dSKevin Wolf qemu_iovec_init_external(&qiov, &iov, 1); 29078d3b1a2dSKevin Wolf return bdrv_pwritev(bs, offset, &qiov); 290883f64091Sbellard } 290983f64091Sbellard 2910f08145feSKevin Wolf /* 2911f08145feSKevin Wolf * Writes to the file and ensures that no writes are reordered across this 2912f08145feSKevin Wolf * request (acts as a barrier) 2913f08145feSKevin Wolf * 2914f08145feSKevin Wolf * Returns 0 on success, -errno in error cases. 2915f08145feSKevin Wolf */ 2916f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset, 2917f08145feSKevin Wolf const void *buf, int count) 2918f08145feSKevin Wolf { 2919f08145feSKevin Wolf int ret; 2920f08145feSKevin Wolf 2921f08145feSKevin Wolf ret = bdrv_pwrite(bs, offset, buf, count); 2922f08145feSKevin Wolf if (ret < 0) { 2923f08145feSKevin Wolf return ret; 2924f08145feSKevin Wolf } 2925f08145feSKevin Wolf 2926f05fa4adSPaolo Bonzini /* No flush needed for cache modes that already do it */ 2927f05fa4adSPaolo Bonzini if (bs->enable_write_cache) { 2928f08145feSKevin Wolf bdrv_flush(bs); 2929f08145feSKevin Wolf } 2930f08145feSKevin Wolf 2931f08145feSKevin Wolf return 0; 2932f08145feSKevin Wolf } 2933f08145feSKevin Wolf 2934470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs, 2935ab185921SStefan Hajnoczi int64_t sector_num, int nb_sectors, QEMUIOVector *qiov) 2936ab185921SStefan Hajnoczi { 2937ab185921SStefan Hajnoczi /* Perform I/O through a temporary buffer so that users who scribble over 2938ab185921SStefan Hajnoczi * their read buffer while the operation is in progress do not end up 2939ab185921SStefan Hajnoczi * modifying the image file. This is critical for zero-copy guest I/O 2940ab185921SStefan Hajnoczi * where anything might happen inside guest memory. 2941ab185921SStefan Hajnoczi */ 2942ab185921SStefan Hajnoczi void *bounce_buffer; 2943ab185921SStefan Hajnoczi 294479c053bdSStefan Hajnoczi BlockDriver *drv = bs->drv; 2945ab185921SStefan Hajnoczi struct iovec iov; 2946ab185921SStefan Hajnoczi QEMUIOVector bounce_qiov; 2947ab185921SStefan Hajnoczi int64_t cluster_sector_num; 2948ab185921SStefan Hajnoczi int cluster_nb_sectors; 2949ab185921SStefan Hajnoczi size_t skip_bytes; 2950ab185921SStefan Hajnoczi int ret; 2951ab185921SStefan Hajnoczi 2952ab185921SStefan Hajnoczi /* Cover entire cluster so no additional backing file I/O is required when 2953ab185921SStefan Hajnoczi * allocating cluster in the image file. 2954ab185921SStefan Hajnoczi */ 2955343bded4SPaolo Bonzini bdrv_round_to_clusters(bs, sector_num, nb_sectors, 2956ab185921SStefan Hajnoczi &cluster_sector_num, &cluster_nb_sectors); 2957ab185921SStefan Hajnoczi 2958470c0504SStefan Hajnoczi trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, 2959ab185921SStefan Hajnoczi cluster_sector_num, cluster_nb_sectors); 2960ab185921SStefan Hajnoczi 2961ab185921SStefan Hajnoczi iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE; 2962857d4f46SKevin Wolf iov.iov_base = bounce_buffer = qemu_try_blockalign(bs, iov.iov_len); 2963857d4f46SKevin Wolf if (bounce_buffer == NULL) { 2964857d4f46SKevin Wolf ret = -ENOMEM; 2965857d4f46SKevin Wolf goto err; 2966857d4f46SKevin Wolf } 2967857d4f46SKevin Wolf 2968ab185921SStefan Hajnoczi qemu_iovec_init_external(&bounce_qiov, &iov, 1); 2969ab185921SStefan Hajnoczi 297079c053bdSStefan Hajnoczi ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors, 2971ab185921SStefan Hajnoczi &bounce_qiov); 2972ab185921SStefan Hajnoczi if (ret < 0) { 2973ab185921SStefan Hajnoczi goto err; 2974ab185921SStefan Hajnoczi } 2975ab185921SStefan Hajnoczi 297679c053bdSStefan Hajnoczi if (drv->bdrv_co_write_zeroes && 297779c053bdSStefan Hajnoczi buffer_is_zero(bounce_buffer, iov.iov_len)) { 2978621f0589SKevin Wolf ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num, 2979aa7bfbffSPeter Lieven cluster_nb_sectors, 0); 298079c053bdSStefan Hajnoczi } else { 2981f05fa4adSPaolo Bonzini /* This does not change the data on the disk, it is not necessary 2982f05fa4adSPaolo Bonzini * to flush even in cache=writethrough mode. 2983f05fa4adSPaolo Bonzini */ 298479c053bdSStefan Hajnoczi ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors, 2985ab185921SStefan Hajnoczi &bounce_qiov); 298679c053bdSStefan Hajnoczi } 298779c053bdSStefan Hajnoczi 2988ab185921SStefan Hajnoczi if (ret < 0) { 2989ab185921SStefan Hajnoczi /* It might be okay to ignore write errors for guest requests. If this 2990ab185921SStefan Hajnoczi * is a deliberate copy-on-read then we don't want to ignore the error. 2991ab185921SStefan Hajnoczi * Simply report it in all cases. 2992ab185921SStefan Hajnoczi */ 2993ab185921SStefan Hajnoczi goto err; 2994ab185921SStefan Hajnoczi } 2995ab185921SStefan Hajnoczi 2996ab185921SStefan Hajnoczi skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE; 299703396148SMichael Tokarev qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes, 2998ab185921SStefan Hajnoczi nb_sectors * BDRV_SECTOR_SIZE); 2999ab185921SStefan Hajnoczi 3000ab185921SStefan Hajnoczi err: 3001ab185921SStefan Hajnoczi qemu_vfree(bounce_buffer); 3002ab185921SStefan Hajnoczi return ret; 3003ab185921SStefan Hajnoczi } 3004ab185921SStefan Hajnoczi 3005c5fbe571SStefan Hajnoczi /* 3006d0c7f642SKevin Wolf * Forwards an already correctly aligned request to the BlockDriver. This 3007d0c7f642SKevin Wolf * handles copy on read and zeroing after EOF; any other features must be 3008d0c7f642SKevin Wolf * implemented by the caller. 3009c5fbe571SStefan Hajnoczi */ 3010d0c7f642SKevin Wolf static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs, 301165afd211SKevin Wolf BdrvTrackedRequest *req, int64_t offset, unsigned int bytes, 3012ec746e10SKevin Wolf int64_t align, QEMUIOVector *qiov, int flags) 3013da1fa91dSKevin Wolf { 3014da1fa91dSKevin Wolf BlockDriver *drv = bs->drv; 3015dbffbdcfSStefan Hajnoczi int ret; 3016da1fa91dSKevin Wolf 3017d0c7f642SKevin Wolf int64_t sector_num = offset >> BDRV_SECTOR_BITS; 3018d0c7f642SKevin Wolf unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS; 3019da1fa91dSKevin Wolf 3020d0c7f642SKevin Wolf assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0); 3021d0c7f642SKevin Wolf assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0); 30228eb029c2SKevin Wolf assert(!qiov || bytes == qiov->size); 3023d0c7f642SKevin Wolf 3024d0c7f642SKevin Wolf /* Handle Copy on Read and associated serialisation */ 3025470c0504SStefan Hajnoczi if (flags & BDRV_REQ_COPY_ON_READ) { 30267327145fSKevin Wolf /* If we touch the same cluster it counts as an overlap. This 30277327145fSKevin Wolf * guarantees that allocating writes will be serialized and not race 30287327145fSKevin Wolf * with each other for the same cluster. For example, in copy-on-read 30297327145fSKevin Wolf * it ensures that the CoR read and write operations are atomic and 30307327145fSKevin Wolf * guest writes cannot interleave between them. */ 30317327145fSKevin Wolf mark_request_serialising(req, bdrv_get_cluster_size(bs)); 3032470c0504SStefan Hajnoczi } 3033470c0504SStefan Hajnoczi 30342dbafdc0SKevin Wolf wait_serialising_requests(req); 3035f4658285SStefan Hajnoczi 3036470c0504SStefan Hajnoczi if (flags & BDRV_REQ_COPY_ON_READ) { 3037ab185921SStefan Hajnoczi int pnum; 3038ab185921SStefan Hajnoczi 3039bdad13b9SPaolo Bonzini ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum); 3040ab185921SStefan Hajnoczi if (ret < 0) { 3041ab185921SStefan Hajnoczi goto out; 3042ab185921SStefan Hajnoczi } 3043ab185921SStefan Hajnoczi 3044ab185921SStefan Hajnoczi if (!ret || pnum != nb_sectors) { 3045470c0504SStefan Hajnoczi ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov); 3046ab185921SStefan Hajnoczi goto out; 3047ab185921SStefan Hajnoczi } 3048ab185921SStefan Hajnoczi } 3049ab185921SStefan Hajnoczi 3050d0c7f642SKevin Wolf /* Forward the request to the BlockDriver */ 3051893a8f62SMORITA Kazutaka if (!(bs->zero_beyond_eof && bs->growable)) { 3052dbffbdcfSStefan Hajnoczi ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov); 3053893a8f62SMORITA Kazutaka } else { 3054893a8f62SMORITA Kazutaka /* Read zeros after EOF of growable BDSes */ 30554049082cSMarkus Armbruster int64_t total_sectors, max_nb_sectors; 3056893a8f62SMORITA Kazutaka 30574049082cSMarkus Armbruster total_sectors = bdrv_nb_sectors(bs); 30584049082cSMarkus Armbruster if (total_sectors < 0) { 30594049082cSMarkus Armbruster ret = total_sectors; 3060893a8f62SMORITA Kazutaka goto out; 3061893a8f62SMORITA Kazutaka } 3062893a8f62SMORITA Kazutaka 30635f5bcd80SKevin Wolf max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num), 30645f5bcd80SKevin Wolf align >> BDRV_SECTOR_BITS); 3065e012b78cSPaolo Bonzini if (nb_sectors < max_nb_sectors) { 3066e012b78cSPaolo Bonzini ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov); 3067e012b78cSPaolo Bonzini } else if (max_nb_sectors > 0) { 306833f461e0SKevin Wolf QEMUIOVector local_qiov; 306933f461e0SKevin Wolf 307033f461e0SKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov); 307133f461e0SKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, 3072e012b78cSPaolo Bonzini max_nb_sectors * BDRV_SECTOR_SIZE); 307333f461e0SKevin Wolf 3074e012b78cSPaolo Bonzini ret = drv->bdrv_co_readv(bs, sector_num, max_nb_sectors, 307533f461e0SKevin Wolf &local_qiov); 307633f461e0SKevin Wolf 307733f461e0SKevin Wolf qemu_iovec_destroy(&local_qiov); 3078893a8f62SMORITA Kazutaka } else { 3079893a8f62SMORITA Kazutaka ret = 0; 3080893a8f62SMORITA Kazutaka } 3081893a8f62SMORITA Kazutaka 3082893a8f62SMORITA Kazutaka /* Reading beyond end of file is supposed to produce zeroes */ 3083893a8f62SMORITA Kazutaka if (ret == 0 && total_sectors < sector_num + nb_sectors) { 3084893a8f62SMORITA Kazutaka uint64_t offset = MAX(0, total_sectors - sector_num); 3085893a8f62SMORITA Kazutaka uint64_t bytes = (sector_num + nb_sectors - offset) * 3086893a8f62SMORITA Kazutaka BDRV_SECTOR_SIZE; 3087893a8f62SMORITA Kazutaka qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes); 3088893a8f62SMORITA Kazutaka } 3089893a8f62SMORITA Kazutaka } 3090ab185921SStefan Hajnoczi 3091ab185921SStefan Hajnoczi out: 3092dbffbdcfSStefan Hajnoczi return ret; 3093da1fa91dSKevin Wolf } 3094da1fa91dSKevin Wolf 3095d0c7f642SKevin Wolf /* 3096d0c7f642SKevin Wolf * Handle a read request in coroutine context 3097d0c7f642SKevin Wolf */ 30981b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs, 30991b0288aeSKevin Wolf int64_t offset, unsigned int bytes, QEMUIOVector *qiov, 3100d0c7f642SKevin Wolf BdrvRequestFlags flags) 3101d0c7f642SKevin Wolf { 3102d0c7f642SKevin Wolf BlockDriver *drv = bs->drv; 310365afd211SKevin Wolf BdrvTrackedRequest req; 310465afd211SKevin Wolf 31051b0288aeSKevin Wolf /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */ 31061b0288aeSKevin Wolf uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment); 31071b0288aeSKevin Wolf uint8_t *head_buf = NULL; 31081b0288aeSKevin Wolf uint8_t *tail_buf = NULL; 31091b0288aeSKevin Wolf QEMUIOVector local_qiov; 31101b0288aeSKevin Wolf bool use_local_qiov = false; 3111d0c7f642SKevin Wolf int ret; 3112d0c7f642SKevin Wolf 3113d0c7f642SKevin Wolf if (!drv) { 3114d0c7f642SKevin Wolf return -ENOMEDIUM; 3115d0c7f642SKevin Wolf } 31161b0288aeSKevin Wolf if (bdrv_check_byte_request(bs, offset, bytes)) { 3117d0c7f642SKevin Wolf return -EIO; 3118d0c7f642SKevin Wolf } 3119d0c7f642SKevin Wolf 3120d0c7f642SKevin Wolf if (bs->copy_on_read) { 3121d0c7f642SKevin Wolf flags |= BDRV_REQ_COPY_ON_READ; 3122d0c7f642SKevin Wolf } 3123d0c7f642SKevin Wolf 3124d0c7f642SKevin Wolf /* throttling disk I/O */ 3125d0c7f642SKevin Wolf if (bs->io_limits_enabled) { 3126d5103588SKevin Wolf bdrv_io_limits_intercept(bs, bytes, false); 3127d0c7f642SKevin Wolf } 3128d0c7f642SKevin Wolf 31291b0288aeSKevin Wolf /* Align read if necessary by padding qiov */ 31301b0288aeSKevin Wolf if (offset & (align - 1)) { 31311b0288aeSKevin Wolf head_buf = qemu_blockalign(bs, align); 31321b0288aeSKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov + 2); 31331b0288aeSKevin Wolf qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1)); 31341b0288aeSKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 31351b0288aeSKevin Wolf use_local_qiov = true; 31361b0288aeSKevin Wolf 31371b0288aeSKevin Wolf bytes += offset & (align - 1); 31381b0288aeSKevin Wolf offset = offset & ~(align - 1); 31391b0288aeSKevin Wolf } 31401b0288aeSKevin Wolf 31411b0288aeSKevin Wolf if ((offset + bytes) & (align - 1)) { 31421b0288aeSKevin Wolf if (!use_local_qiov) { 31431b0288aeSKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov + 1); 31441b0288aeSKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 31451b0288aeSKevin Wolf use_local_qiov = true; 31461b0288aeSKevin Wolf } 31471b0288aeSKevin Wolf tail_buf = qemu_blockalign(bs, align); 31481b0288aeSKevin Wolf qemu_iovec_add(&local_qiov, tail_buf, 31491b0288aeSKevin Wolf align - ((offset + bytes) & (align - 1))); 31501b0288aeSKevin Wolf 31511b0288aeSKevin Wolf bytes = ROUND_UP(bytes, align); 31521b0288aeSKevin Wolf } 31531b0288aeSKevin Wolf 315465afd211SKevin Wolf tracked_request_begin(&req, bs, offset, bytes, false); 3155ec746e10SKevin Wolf ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align, 31561b0288aeSKevin Wolf use_local_qiov ? &local_qiov : qiov, 31571b0288aeSKevin Wolf flags); 315865afd211SKevin Wolf tracked_request_end(&req); 31591b0288aeSKevin Wolf 31601b0288aeSKevin Wolf if (use_local_qiov) { 31611b0288aeSKevin Wolf qemu_iovec_destroy(&local_qiov); 31621b0288aeSKevin Wolf qemu_vfree(head_buf); 31631b0288aeSKevin Wolf qemu_vfree(tail_buf); 31641b0288aeSKevin Wolf } 31651b0288aeSKevin Wolf 3166d0c7f642SKevin Wolf return ret; 3167d0c7f642SKevin Wolf } 3168d0c7f642SKevin Wolf 31691b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs, 31701b0288aeSKevin Wolf int64_t sector_num, int nb_sectors, QEMUIOVector *qiov, 31711b0288aeSKevin Wolf BdrvRequestFlags flags) 31721b0288aeSKevin Wolf { 31731b0288aeSKevin Wolf if (nb_sectors < 0 || nb_sectors > (UINT_MAX >> BDRV_SECTOR_BITS)) { 31741b0288aeSKevin Wolf return -EINVAL; 31751b0288aeSKevin Wolf } 31761b0288aeSKevin Wolf 31771b0288aeSKevin Wolf return bdrv_co_do_preadv(bs, sector_num << BDRV_SECTOR_BITS, 31781b0288aeSKevin Wolf nb_sectors << BDRV_SECTOR_BITS, qiov, flags); 31791b0288aeSKevin Wolf } 31801b0288aeSKevin Wolf 3181c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num, 3182da1fa91dSKevin Wolf int nb_sectors, QEMUIOVector *qiov) 3183da1fa91dSKevin Wolf { 3184c5fbe571SStefan Hajnoczi trace_bdrv_co_readv(bs, sector_num, nb_sectors); 3185da1fa91dSKevin Wolf 3186470c0504SStefan Hajnoczi return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0); 3187470c0504SStefan Hajnoczi } 3188470c0504SStefan Hajnoczi 3189470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs, 3190470c0504SStefan Hajnoczi int64_t sector_num, int nb_sectors, QEMUIOVector *qiov) 3191470c0504SStefan Hajnoczi { 3192470c0504SStefan Hajnoczi trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors); 3193470c0504SStefan Hajnoczi 3194470c0504SStefan Hajnoczi return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 3195470c0504SStefan Hajnoczi BDRV_REQ_COPY_ON_READ); 3196c5fbe571SStefan Hajnoczi } 3197c5fbe571SStefan Hajnoczi 3198c31cb707SPeter Lieven /* if no limit is specified in the BlockLimits use a default 3199c31cb707SPeter Lieven * of 32768 512-byte sectors (16 MiB) per request. 3200c31cb707SPeter Lieven */ 3201c31cb707SPeter Lieven #define MAX_WRITE_ZEROES_DEFAULT 32768 3202c31cb707SPeter Lieven 3203f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs, 3204aa7bfbffSPeter Lieven int64_t sector_num, int nb_sectors, BdrvRequestFlags flags) 3205f08f2ddaSStefan Hajnoczi { 3206f08f2ddaSStefan Hajnoczi BlockDriver *drv = bs->drv; 3207f08f2ddaSStefan Hajnoczi QEMUIOVector qiov; 3208c31cb707SPeter Lieven struct iovec iov = {0}; 3209c31cb707SPeter Lieven int ret = 0; 3210f08f2ddaSStefan Hajnoczi 3211c31cb707SPeter Lieven int max_write_zeroes = bs->bl.max_write_zeroes ? 3212c31cb707SPeter Lieven bs->bl.max_write_zeroes : MAX_WRITE_ZEROES_DEFAULT; 3213621f0589SKevin Wolf 3214c31cb707SPeter Lieven while (nb_sectors > 0 && !ret) { 3215c31cb707SPeter Lieven int num = nb_sectors; 3216c31cb707SPeter Lieven 3217b8d71c09SPaolo Bonzini /* Align request. Block drivers can expect the "bulk" of the request 3218b8d71c09SPaolo Bonzini * to be aligned. 3219b8d71c09SPaolo Bonzini */ 3220b8d71c09SPaolo Bonzini if (bs->bl.write_zeroes_alignment 3221b8d71c09SPaolo Bonzini && num > bs->bl.write_zeroes_alignment) { 3222b8d71c09SPaolo Bonzini if (sector_num % bs->bl.write_zeroes_alignment != 0) { 3223b8d71c09SPaolo Bonzini /* Make a small request up to the first aligned sector. */ 3224c31cb707SPeter Lieven num = bs->bl.write_zeroes_alignment; 3225c31cb707SPeter Lieven num -= sector_num % bs->bl.write_zeroes_alignment; 3226b8d71c09SPaolo Bonzini } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) { 3227b8d71c09SPaolo Bonzini /* Shorten the request to the last aligned sector. num cannot 3228b8d71c09SPaolo Bonzini * underflow because num > bs->bl.write_zeroes_alignment. 3229b8d71c09SPaolo Bonzini */ 3230b8d71c09SPaolo Bonzini num -= (sector_num + num) % bs->bl.write_zeroes_alignment; 3231b8d71c09SPaolo Bonzini } 3232c31cb707SPeter Lieven } 3233c31cb707SPeter Lieven 3234c31cb707SPeter Lieven /* limit request size */ 3235c31cb707SPeter Lieven if (num > max_write_zeroes) { 3236c31cb707SPeter Lieven num = max_write_zeroes; 3237c31cb707SPeter Lieven } 3238c31cb707SPeter Lieven 3239c31cb707SPeter Lieven ret = -ENOTSUP; 3240f08f2ddaSStefan Hajnoczi /* First try the efficient write zeroes operation */ 3241f08f2ddaSStefan Hajnoczi if (drv->bdrv_co_write_zeroes) { 3242c31cb707SPeter Lieven ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags); 3243f08f2ddaSStefan Hajnoczi } 3244f08f2ddaSStefan Hajnoczi 3245c31cb707SPeter Lieven if (ret == -ENOTSUP) { 3246f08f2ddaSStefan Hajnoczi /* Fall back to bounce buffer if write zeroes is unsupported */ 3247*095e4fa4SPeter Lieven int max_xfer_len = MIN_NON_ZERO(bs->bl.max_transfer_length, 3248*095e4fa4SPeter Lieven MAX_WRITE_ZEROES_DEFAULT); 3249*095e4fa4SPeter Lieven num = MIN(num, max_xfer_len); 3250c31cb707SPeter Lieven iov.iov_len = num * BDRV_SECTOR_SIZE; 3251c31cb707SPeter Lieven if (iov.iov_base == NULL) { 3252857d4f46SKevin Wolf iov.iov_base = qemu_try_blockalign(bs, num * BDRV_SECTOR_SIZE); 3253857d4f46SKevin Wolf if (iov.iov_base == NULL) { 3254857d4f46SKevin Wolf ret = -ENOMEM; 3255857d4f46SKevin Wolf goto fail; 3256857d4f46SKevin Wolf } 3257b8d71c09SPaolo Bonzini memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE); 3258c31cb707SPeter Lieven } 3259f08f2ddaSStefan Hajnoczi qemu_iovec_init_external(&qiov, &iov, 1); 3260f08f2ddaSStefan Hajnoczi 3261c31cb707SPeter Lieven ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov); 3262b8d71c09SPaolo Bonzini 3263b8d71c09SPaolo Bonzini /* Keep bounce buffer around if it is big enough for all 3264b8d71c09SPaolo Bonzini * all future requests. 3265b8d71c09SPaolo Bonzini */ 3266*095e4fa4SPeter Lieven if (num < max_xfer_len) { 3267b8d71c09SPaolo Bonzini qemu_vfree(iov.iov_base); 3268b8d71c09SPaolo Bonzini iov.iov_base = NULL; 3269b8d71c09SPaolo Bonzini } 3270c31cb707SPeter Lieven } 3271c31cb707SPeter Lieven 3272c31cb707SPeter Lieven sector_num += num; 3273c31cb707SPeter Lieven nb_sectors -= num; 3274c31cb707SPeter Lieven } 3275f08f2ddaSStefan Hajnoczi 3276857d4f46SKevin Wolf fail: 3277f08f2ddaSStefan Hajnoczi qemu_vfree(iov.iov_base); 3278f08f2ddaSStefan Hajnoczi return ret; 3279f08f2ddaSStefan Hajnoczi } 3280f08f2ddaSStefan Hajnoczi 3281c5fbe571SStefan Hajnoczi /* 3282b404f720SKevin Wolf * Forwards an already correctly aligned write request to the BlockDriver. 3283c5fbe571SStefan Hajnoczi */ 3284b404f720SKevin Wolf static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs, 328565afd211SKevin Wolf BdrvTrackedRequest *req, int64_t offset, unsigned int bytes, 328665afd211SKevin Wolf QEMUIOVector *qiov, int flags) 3287c5fbe571SStefan Hajnoczi { 3288c5fbe571SStefan Hajnoczi BlockDriver *drv = bs->drv; 328928de2dcdSKevin Wolf bool waited; 32906b7cb247SStefan Hajnoczi int ret; 3291da1fa91dSKevin Wolf 3292b404f720SKevin Wolf int64_t sector_num = offset >> BDRV_SECTOR_BITS; 3293b404f720SKevin Wolf unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS; 3294da1fa91dSKevin Wolf 3295b404f720SKevin Wolf assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0); 3296b404f720SKevin Wolf assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0); 32978eb029c2SKevin Wolf assert(!qiov || bytes == qiov->size); 3298cc0681c4SBenoît Canet 329928de2dcdSKevin Wolf waited = wait_serialising_requests(req); 330028de2dcdSKevin Wolf assert(!waited || !req->serialising); 3301af91f9a7SKevin Wolf assert(req->overlap_offset <= offset); 3302af91f9a7SKevin Wolf assert(offset + bytes <= req->overlap_offset + req->overlap_bytes); 3303244eadefSKevin Wolf 330465afd211SKevin Wolf ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req); 3305d616b224SStefan Hajnoczi 3306465bee1dSPeter Lieven if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF && 3307465bee1dSPeter Lieven !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_write_zeroes && 3308465bee1dSPeter Lieven qemu_iovec_is_zero(qiov)) { 3309465bee1dSPeter Lieven flags |= BDRV_REQ_ZERO_WRITE; 3310465bee1dSPeter Lieven if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) { 3311465bee1dSPeter Lieven flags |= BDRV_REQ_MAY_UNMAP; 3312465bee1dSPeter Lieven } 3313465bee1dSPeter Lieven } 3314465bee1dSPeter Lieven 3315d616b224SStefan Hajnoczi if (ret < 0) { 3316d616b224SStefan Hajnoczi /* Do nothing, write notifier decided to fail this request */ 3317d616b224SStefan Hajnoczi } else if (flags & BDRV_REQ_ZERO_WRITE) { 33189e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_ZERO); 3319aa7bfbffSPeter Lieven ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags); 3320f08f2ddaSStefan Hajnoczi } else { 33219e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV); 33226b7cb247SStefan Hajnoczi ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov); 3323f08f2ddaSStefan Hajnoczi } 33249e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_DONE); 33256b7cb247SStefan Hajnoczi 3326f05fa4adSPaolo Bonzini if (ret == 0 && !bs->enable_write_cache) { 3327f05fa4adSPaolo Bonzini ret = bdrv_co_flush(bs); 3328f05fa4adSPaolo Bonzini } 3329f05fa4adSPaolo Bonzini 33301755da16SPaolo Bonzini bdrv_set_dirty(bs, sector_num, nb_sectors); 3331da1fa91dSKevin Wolf 33325366d0c8SBenoît Canet block_acct_highest_sector(&bs->stats, sector_num, nb_sectors); 33335e5a94b6SBenoît Canet 3334df2a6f29SPaolo Bonzini if (bs->growable && ret >= 0) { 3335df2a6f29SPaolo Bonzini bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors); 3336df2a6f29SPaolo Bonzini } 3337da1fa91dSKevin Wolf 33386b7cb247SStefan Hajnoczi return ret; 3339da1fa91dSKevin Wolf } 3340da1fa91dSKevin Wolf 3341b404f720SKevin Wolf /* 3342b404f720SKevin Wolf * Handle a write request in coroutine context 3343b404f720SKevin Wolf */ 33446601553eSKevin Wolf static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs, 33456601553eSKevin Wolf int64_t offset, unsigned int bytes, QEMUIOVector *qiov, 3346b404f720SKevin Wolf BdrvRequestFlags flags) 3347b404f720SKevin Wolf { 334865afd211SKevin Wolf BdrvTrackedRequest req; 33493b8242e0SKevin Wolf /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */ 33503b8242e0SKevin Wolf uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment); 33513b8242e0SKevin Wolf uint8_t *head_buf = NULL; 33523b8242e0SKevin Wolf uint8_t *tail_buf = NULL; 33533b8242e0SKevin Wolf QEMUIOVector local_qiov; 33543b8242e0SKevin Wolf bool use_local_qiov = false; 3355b404f720SKevin Wolf int ret; 3356b404f720SKevin Wolf 3357b404f720SKevin Wolf if (!bs->drv) { 3358b404f720SKevin Wolf return -ENOMEDIUM; 3359b404f720SKevin Wolf } 3360b404f720SKevin Wolf if (bs->read_only) { 3361b404f720SKevin Wolf return -EACCES; 3362b404f720SKevin Wolf } 33636601553eSKevin Wolf if (bdrv_check_byte_request(bs, offset, bytes)) { 3364b404f720SKevin Wolf return -EIO; 3365b404f720SKevin Wolf } 3366b404f720SKevin Wolf 3367b404f720SKevin Wolf /* throttling disk I/O */ 3368b404f720SKevin Wolf if (bs->io_limits_enabled) { 3369d5103588SKevin Wolf bdrv_io_limits_intercept(bs, bytes, true); 3370b404f720SKevin Wolf } 3371b404f720SKevin Wolf 33723b8242e0SKevin Wolf /* 33733b8242e0SKevin Wolf * Align write if necessary by performing a read-modify-write cycle. 33743b8242e0SKevin Wolf * Pad qiov with the read parts and be sure to have a tracked request not 33753b8242e0SKevin Wolf * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle. 33763b8242e0SKevin Wolf */ 337765afd211SKevin Wolf tracked_request_begin(&req, bs, offset, bytes, true); 33783b8242e0SKevin Wolf 33793b8242e0SKevin Wolf if (offset & (align - 1)) { 33803b8242e0SKevin Wolf QEMUIOVector head_qiov; 33813b8242e0SKevin Wolf struct iovec head_iov; 33823b8242e0SKevin Wolf 33833b8242e0SKevin Wolf mark_request_serialising(&req, align); 33843b8242e0SKevin Wolf wait_serialising_requests(&req); 33853b8242e0SKevin Wolf 33863b8242e0SKevin Wolf head_buf = qemu_blockalign(bs, align); 33873b8242e0SKevin Wolf head_iov = (struct iovec) { 33883b8242e0SKevin Wolf .iov_base = head_buf, 33893b8242e0SKevin Wolf .iov_len = align, 33903b8242e0SKevin Wolf }; 33913b8242e0SKevin Wolf qemu_iovec_init_external(&head_qiov, &head_iov, 1); 33923b8242e0SKevin Wolf 33939e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_HEAD); 33943b8242e0SKevin Wolf ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align, 33953b8242e0SKevin Wolf align, &head_qiov, 0); 33963b8242e0SKevin Wolf if (ret < 0) { 33973b8242e0SKevin Wolf goto fail; 33983b8242e0SKevin Wolf } 33999e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD); 34003b8242e0SKevin Wolf 34013b8242e0SKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov + 2); 34023b8242e0SKevin Wolf qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1)); 34033b8242e0SKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 34043b8242e0SKevin Wolf use_local_qiov = true; 34053b8242e0SKevin Wolf 34063b8242e0SKevin Wolf bytes += offset & (align - 1); 34073b8242e0SKevin Wolf offset = offset & ~(align - 1); 34083b8242e0SKevin Wolf } 34093b8242e0SKevin Wolf 34103b8242e0SKevin Wolf if ((offset + bytes) & (align - 1)) { 34113b8242e0SKevin Wolf QEMUIOVector tail_qiov; 34123b8242e0SKevin Wolf struct iovec tail_iov; 34133b8242e0SKevin Wolf size_t tail_bytes; 341428de2dcdSKevin Wolf bool waited; 34153b8242e0SKevin Wolf 34163b8242e0SKevin Wolf mark_request_serialising(&req, align); 341728de2dcdSKevin Wolf waited = wait_serialising_requests(&req); 341828de2dcdSKevin Wolf assert(!waited || !use_local_qiov); 34193b8242e0SKevin Wolf 34203b8242e0SKevin Wolf tail_buf = qemu_blockalign(bs, align); 34213b8242e0SKevin Wolf tail_iov = (struct iovec) { 34223b8242e0SKevin Wolf .iov_base = tail_buf, 34233b8242e0SKevin Wolf .iov_len = align, 34243b8242e0SKevin Wolf }; 34253b8242e0SKevin Wolf qemu_iovec_init_external(&tail_qiov, &tail_iov, 1); 34263b8242e0SKevin Wolf 34279e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_TAIL); 34283b8242e0SKevin Wolf ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align, 34293b8242e0SKevin Wolf align, &tail_qiov, 0); 34303b8242e0SKevin Wolf if (ret < 0) { 34313b8242e0SKevin Wolf goto fail; 34323b8242e0SKevin Wolf } 34339e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL); 34343b8242e0SKevin Wolf 34353b8242e0SKevin Wolf if (!use_local_qiov) { 34363b8242e0SKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov + 1); 34373b8242e0SKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 34383b8242e0SKevin Wolf use_local_qiov = true; 34393b8242e0SKevin Wolf } 34403b8242e0SKevin Wolf 34413b8242e0SKevin Wolf tail_bytes = (offset + bytes) & (align - 1); 34423b8242e0SKevin Wolf qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes); 34433b8242e0SKevin Wolf 34443b8242e0SKevin Wolf bytes = ROUND_UP(bytes, align); 34453b8242e0SKevin Wolf } 34463b8242e0SKevin Wolf 34473b8242e0SKevin Wolf ret = bdrv_aligned_pwritev(bs, &req, offset, bytes, 34483b8242e0SKevin Wolf use_local_qiov ? &local_qiov : qiov, 34493b8242e0SKevin Wolf flags); 34503b8242e0SKevin Wolf 34513b8242e0SKevin Wolf fail: 345265afd211SKevin Wolf tracked_request_end(&req); 3453b404f720SKevin Wolf 34543b8242e0SKevin Wolf if (use_local_qiov) { 34553b8242e0SKevin Wolf qemu_iovec_destroy(&local_qiov); 345699c4a85cSKevin Wolf } 34573b8242e0SKevin Wolf qemu_vfree(head_buf); 34583b8242e0SKevin Wolf qemu_vfree(tail_buf); 34593b8242e0SKevin Wolf 3460b404f720SKevin Wolf return ret; 3461b404f720SKevin Wolf } 3462b404f720SKevin Wolf 34636601553eSKevin Wolf static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs, 34646601553eSKevin Wolf int64_t sector_num, int nb_sectors, QEMUIOVector *qiov, 34656601553eSKevin Wolf BdrvRequestFlags flags) 34666601553eSKevin Wolf { 34676601553eSKevin Wolf if (nb_sectors < 0 || nb_sectors > (INT_MAX >> BDRV_SECTOR_BITS)) { 34686601553eSKevin Wolf return -EINVAL; 34696601553eSKevin Wolf } 34706601553eSKevin Wolf 34716601553eSKevin Wolf return bdrv_co_do_pwritev(bs, sector_num << BDRV_SECTOR_BITS, 34726601553eSKevin Wolf nb_sectors << BDRV_SECTOR_BITS, qiov, flags); 34736601553eSKevin Wolf } 34746601553eSKevin Wolf 3475c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num, 3476c5fbe571SStefan Hajnoczi int nb_sectors, QEMUIOVector *qiov) 3477c5fbe571SStefan Hajnoczi { 3478c5fbe571SStefan Hajnoczi trace_bdrv_co_writev(bs, sector_num, nb_sectors); 3479c5fbe571SStefan Hajnoczi 3480f08f2ddaSStefan Hajnoczi return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0); 3481f08f2ddaSStefan Hajnoczi } 3482f08f2ddaSStefan Hajnoczi 3483f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs, 3484aa7bfbffSPeter Lieven int64_t sector_num, int nb_sectors, 3485aa7bfbffSPeter Lieven BdrvRequestFlags flags) 3486f08f2ddaSStefan Hajnoczi { 348794d6ff21SPaolo Bonzini trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags); 3488f08f2ddaSStefan Hajnoczi 3489d32f35cbSPeter Lieven if (!(bs->open_flags & BDRV_O_UNMAP)) { 3490d32f35cbSPeter Lieven flags &= ~BDRV_REQ_MAY_UNMAP; 3491d32f35cbSPeter Lieven } 3492d32f35cbSPeter Lieven 3493f08f2ddaSStefan Hajnoczi return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL, 3494aa7bfbffSPeter Lieven BDRV_REQ_ZERO_WRITE | flags); 3495c5fbe571SStefan Hajnoczi } 3496c5fbe571SStefan Hajnoczi 349783f64091Sbellard /** 349883f64091Sbellard * Truncate file to 'offset' bytes (needed only for file protocols) 349983f64091Sbellard */ 350083f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset) 350183f64091Sbellard { 350283f64091Sbellard BlockDriver *drv = bs->drv; 350351762288SStefan Hajnoczi int ret; 350483f64091Sbellard if (!drv) 350519cb3738Sbellard return -ENOMEDIUM; 350683f64091Sbellard if (!drv->bdrv_truncate) 350783f64091Sbellard return -ENOTSUP; 350859f2689dSNaphtali Sprei if (bs->read_only) 350959f2689dSNaphtali Sprei return -EACCES; 35109c75e168SJeff Cody 351151762288SStefan Hajnoczi ret = drv->bdrv_truncate(bs, offset); 351251762288SStefan Hajnoczi if (ret == 0) { 351351762288SStefan Hajnoczi ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS); 3514a7f53e26SMarkus Armbruster if (bs->blk) { 3515a7f53e26SMarkus Armbruster blk_dev_resize_cb(bs->blk); 3516a7f53e26SMarkus Armbruster } 351751762288SStefan Hajnoczi } 351851762288SStefan Hajnoczi return ret; 351983f64091Sbellard } 352083f64091Sbellard 352183f64091Sbellard /** 35224a1d5e1fSFam Zheng * Length of a allocated file in bytes. Sparse files are counted by actual 35234a1d5e1fSFam Zheng * allocated space. Return < 0 if error or unknown. 35244a1d5e1fSFam Zheng */ 35254a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs) 35264a1d5e1fSFam Zheng { 35274a1d5e1fSFam Zheng BlockDriver *drv = bs->drv; 35284a1d5e1fSFam Zheng if (!drv) { 35294a1d5e1fSFam Zheng return -ENOMEDIUM; 35304a1d5e1fSFam Zheng } 35314a1d5e1fSFam Zheng if (drv->bdrv_get_allocated_file_size) { 35324a1d5e1fSFam Zheng return drv->bdrv_get_allocated_file_size(bs); 35334a1d5e1fSFam Zheng } 35344a1d5e1fSFam Zheng if (bs->file) { 35354a1d5e1fSFam Zheng return bdrv_get_allocated_file_size(bs->file); 35364a1d5e1fSFam Zheng } 35374a1d5e1fSFam Zheng return -ENOTSUP; 35384a1d5e1fSFam Zheng } 35394a1d5e1fSFam Zheng 35404a1d5e1fSFam Zheng /** 354165a9bb25SMarkus Armbruster * Return number of sectors on success, -errno on error. 354283f64091Sbellard */ 354365a9bb25SMarkus Armbruster int64_t bdrv_nb_sectors(BlockDriverState *bs) 354483f64091Sbellard { 354583f64091Sbellard BlockDriver *drv = bs->drv; 354665a9bb25SMarkus Armbruster 354783f64091Sbellard if (!drv) 354819cb3738Sbellard return -ENOMEDIUM; 354951762288SStefan Hajnoczi 3550b94a2610SKevin Wolf if (drv->has_variable_length) { 3551b94a2610SKevin Wolf int ret = refresh_total_sectors(bs, bs->total_sectors); 3552b94a2610SKevin Wolf if (ret < 0) { 3553b94a2610SKevin Wolf return ret; 3554fc01f7e7Sbellard } 355546a4e4e6SStefan Hajnoczi } 355665a9bb25SMarkus Armbruster return bs->total_sectors; 355765a9bb25SMarkus Armbruster } 355865a9bb25SMarkus Armbruster 355965a9bb25SMarkus Armbruster /** 356065a9bb25SMarkus Armbruster * Return length in bytes on success, -errno on error. 356165a9bb25SMarkus Armbruster * The length is always a multiple of BDRV_SECTOR_SIZE. 356265a9bb25SMarkus Armbruster */ 356365a9bb25SMarkus Armbruster int64_t bdrv_getlength(BlockDriverState *bs) 356465a9bb25SMarkus Armbruster { 356565a9bb25SMarkus Armbruster int64_t ret = bdrv_nb_sectors(bs); 356665a9bb25SMarkus Armbruster 356765a9bb25SMarkus Armbruster return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE; 356846a4e4e6SStefan Hajnoczi } 3569fc01f7e7Sbellard 357019cb3738Sbellard /* return 0 as number of sectors if no device present or error */ 357196b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr) 3572fc01f7e7Sbellard { 357365a9bb25SMarkus Armbruster int64_t nb_sectors = bdrv_nb_sectors(bs); 357465a9bb25SMarkus Armbruster 357565a9bb25SMarkus Armbruster *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors; 3576fc01f7e7Sbellard } 3577cf98951bSbellard 3578ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error, 3579ff06f5f3SPaolo Bonzini BlockdevOnError on_write_error) 3580abd7f68dSMarkus Armbruster { 3581abd7f68dSMarkus Armbruster bs->on_read_error = on_read_error; 3582abd7f68dSMarkus Armbruster bs->on_write_error = on_write_error; 3583abd7f68dSMarkus Armbruster } 3584abd7f68dSMarkus Armbruster 35851ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read) 3586abd7f68dSMarkus Armbruster { 3587abd7f68dSMarkus Armbruster return is_read ? bs->on_read_error : bs->on_write_error; 3588abd7f68dSMarkus Armbruster } 3589abd7f68dSMarkus Armbruster 35903e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error) 35913e1caa5fSPaolo Bonzini { 35923e1caa5fSPaolo Bonzini BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error; 35933e1caa5fSPaolo Bonzini 35943e1caa5fSPaolo Bonzini switch (on_err) { 35953e1caa5fSPaolo Bonzini case BLOCKDEV_ON_ERROR_ENOSPC: 3596a589569fSWenchao Xia return (error == ENOSPC) ? 3597a589569fSWenchao Xia BLOCK_ERROR_ACTION_STOP : BLOCK_ERROR_ACTION_REPORT; 35983e1caa5fSPaolo Bonzini case BLOCKDEV_ON_ERROR_STOP: 3599a589569fSWenchao Xia return BLOCK_ERROR_ACTION_STOP; 36003e1caa5fSPaolo Bonzini case BLOCKDEV_ON_ERROR_REPORT: 3601a589569fSWenchao Xia return BLOCK_ERROR_ACTION_REPORT; 36023e1caa5fSPaolo Bonzini case BLOCKDEV_ON_ERROR_IGNORE: 3603a589569fSWenchao Xia return BLOCK_ERROR_ACTION_IGNORE; 36043e1caa5fSPaolo Bonzini default: 36053e1caa5fSPaolo Bonzini abort(); 36063e1caa5fSPaolo Bonzini } 36073e1caa5fSPaolo Bonzini } 36083e1caa5fSPaolo Bonzini 3609c7c2ff0cSLuiz Capitulino static void send_qmp_error_event(BlockDriverState *bs, 3610c7c2ff0cSLuiz Capitulino BlockErrorAction action, 3611c7c2ff0cSLuiz Capitulino bool is_read, int error) 3612c7c2ff0cSLuiz Capitulino { 3613573742a5SPeter Maydell IoOperationType optype; 3614c7c2ff0cSLuiz Capitulino 3615573742a5SPeter Maydell optype = is_read ? IO_OPERATION_TYPE_READ : IO_OPERATION_TYPE_WRITE; 3616573742a5SPeter Maydell qapi_event_send_block_io_error(bdrv_get_device_name(bs), optype, action, 3617c7c2ff0cSLuiz Capitulino bdrv_iostatus_is_enabled(bs), 3618624ff573SLuiz Capitulino error == ENOSPC, strerror(error), 3619624ff573SLuiz Capitulino &error_abort); 3620c7c2ff0cSLuiz Capitulino } 3621c7c2ff0cSLuiz Capitulino 36223e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows 36233e1caa5fSPaolo Bonzini * about the error, it does not know whether an operation comes from 36243e1caa5fSPaolo Bonzini * the device or the block layer (from a job, for example). 36253e1caa5fSPaolo Bonzini */ 36263e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action, 36273e1caa5fSPaolo Bonzini bool is_read, int error) 36283e1caa5fSPaolo Bonzini { 36293e1caa5fSPaolo Bonzini assert(error >= 0); 36302bd3bce8SPaolo Bonzini 3631a589569fSWenchao Xia if (action == BLOCK_ERROR_ACTION_STOP) { 36322bd3bce8SPaolo Bonzini /* First set the iostatus, so that "info block" returns an iostatus 36332bd3bce8SPaolo Bonzini * that matches the events raised so far (an additional error iostatus 36342bd3bce8SPaolo Bonzini * is fine, but not a lost one). 36352bd3bce8SPaolo Bonzini */ 36363e1caa5fSPaolo Bonzini bdrv_iostatus_set_err(bs, error); 36372bd3bce8SPaolo Bonzini 36382bd3bce8SPaolo Bonzini /* Then raise the request to stop the VM and the event. 36392bd3bce8SPaolo Bonzini * qemu_system_vmstop_request_prepare has two effects. First, 36402bd3bce8SPaolo Bonzini * it ensures that the STOP event always comes after the 36412bd3bce8SPaolo Bonzini * BLOCK_IO_ERROR event. Second, it ensures that even if management 36422bd3bce8SPaolo Bonzini * can observe the STOP event and do a "cont" before the STOP 36432bd3bce8SPaolo Bonzini * event is issued, the VM will not stop. In this case, vm_start() 36442bd3bce8SPaolo Bonzini * also ensures that the STOP/RESUME pair of events is emitted. 36452bd3bce8SPaolo Bonzini */ 36462bd3bce8SPaolo Bonzini qemu_system_vmstop_request_prepare(); 3647c7c2ff0cSLuiz Capitulino send_qmp_error_event(bs, action, is_read, error); 36482bd3bce8SPaolo Bonzini qemu_system_vmstop_request(RUN_STATE_IO_ERROR); 36492bd3bce8SPaolo Bonzini } else { 3650c7c2ff0cSLuiz Capitulino send_qmp_error_event(bs, action, is_read, error); 36513e1caa5fSPaolo Bonzini } 36523e1caa5fSPaolo Bonzini } 36533e1caa5fSPaolo Bonzini 3654b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs) 3655b338082bSbellard { 3656b338082bSbellard return bs->read_only; 3657b338082bSbellard } 3658b338082bSbellard 3659985a03b0Sths int bdrv_is_sg(BlockDriverState *bs) 3660985a03b0Sths { 3661985a03b0Sths return bs->sg; 3662985a03b0Sths } 3663985a03b0Sths 3664e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs) 3665e900a7b7SChristoph Hellwig { 3666e900a7b7SChristoph Hellwig return bs->enable_write_cache; 3667e900a7b7SChristoph Hellwig } 3668e900a7b7SChristoph Hellwig 3669425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce) 3670425b0148SPaolo Bonzini { 3671425b0148SPaolo Bonzini bs->enable_write_cache = wce; 367255b110f2SJeff Cody 367355b110f2SJeff Cody /* so a reopen() will preserve wce */ 367455b110f2SJeff Cody if (wce) { 367555b110f2SJeff Cody bs->open_flags |= BDRV_O_CACHE_WB; 367655b110f2SJeff Cody } else { 367755b110f2SJeff Cody bs->open_flags &= ~BDRV_O_CACHE_WB; 367855b110f2SJeff Cody } 3679425b0148SPaolo Bonzini } 3680425b0148SPaolo Bonzini 3681ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs) 3682ea2384d3Sbellard { 3683ea2384d3Sbellard if (bs->backing_hd && bs->backing_hd->encrypted) 3684ea2384d3Sbellard return 1; 3685ea2384d3Sbellard return bs->encrypted; 3686ea2384d3Sbellard } 3687ea2384d3Sbellard 3688c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs) 3689c0f4ce77Saliguori { 3690c0f4ce77Saliguori BlockDriverState *backing_hd = bs->backing_hd; 3691c0f4ce77Saliguori 3692c0f4ce77Saliguori if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key) 3693c0f4ce77Saliguori return 1; 3694c0f4ce77Saliguori return (bs->encrypted && !bs->valid_key); 3695c0f4ce77Saliguori } 3696c0f4ce77Saliguori 3697ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key) 3698ea2384d3Sbellard { 3699ea2384d3Sbellard int ret; 3700ea2384d3Sbellard if (bs->backing_hd && bs->backing_hd->encrypted) { 3701ea2384d3Sbellard ret = bdrv_set_key(bs->backing_hd, key); 3702ea2384d3Sbellard if (ret < 0) 3703ea2384d3Sbellard return ret; 3704ea2384d3Sbellard if (!bs->encrypted) 3705ea2384d3Sbellard return 0; 3706ea2384d3Sbellard } 3707fd04a2aeSShahar Havivi if (!bs->encrypted) { 3708fd04a2aeSShahar Havivi return -EINVAL; 3709fd04a2aeSShahar Havivi } else if (!bs->drv || !bs->drv->bdrv_set_key) { 3710fd04a2aeSShahar Havivi return -ENOMEDIUM; 3711fd04a2aeSShahar Havivi } 3712c0f4ce77Saliguori ret = bs->drv->bdrv_set_key(bs, key); 3713bb5fc20fSaliguori if (ret < 0) { 3714bb5fc20fSaliguori bs->valid_key = 0; 3715bb5fc20fSaliguori } else if (!bs->valid_key) { 3716bb5fc20fSaliguori bs->valid_key = 1; 3717a7f53e26SMarkus Armbruster if (bs->blk) { 3718bb5fc20fSaliguori /* call the change callback now, we skipped it on open */ 3719a7f53e26SMarkus Armbruster blk_dev_change_media_cb(bs->blk, true); 3720a7f53e26SMarkus Armbruster } 3721bb5fc20fSaliguori } 3722c0f4ce77Saliguori return ret; 3723ea2384d3Sbellard } 3724ea2384d3Sbellard 3725f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs) 3726ea2384d3Sbellard { 3727f8d6bba1SMarkus Armbruster return bs->drv ? bs->drv->format_name : NULL; 3728ea2384d3Sbellard } 3729ea2384d3Sbellard 3730ada42401SStefan Hajnoczi static int qsort_strcmp(const void *a, const void *b) 3731ada42401SStefan Hajnoczi { 3732ada42401SStefan Hajnoczi return strcmp(a, b); 3733ada42401SStefan Hajnoczi } 3734ada42401SStefan Hajnoczi 3735ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name), 3736ea2384d3Sbellard void *opaque) 3737ea2384d3Sbellard { 3738ea2384d3Sbellard BlockDriver *drv; 3739e855e4fbSJeff Cody int count = 0; 3740ada42401SStefan Hajnoczi int i; 3741e855e4fbSJeff Cody const char **formats = NULL; 3742ea2384d3Sbellard 37438a22f02aSStefan Hajnoczi QLIST_FOREACH(drv, &bdrv_drivers, list) { 3744e855e4fbSJeff Cody if (drv->format_name) { 3745e855e4fbSJeff Cody bool found = false; 3746e855e4fbSJeff Cody int i = count; 3747e855e4fbSJeff Cody while (formats && i && !found) { 3748e855e4fbSJeff Cody found = !strcmp(formats[--i], drv->format_name); 3749e855e4fbSJeff Cody } 3750e855e4fbSJeff Cody 3751e855e4fbSJeff Cody if (!found) { 37525839e53bSMarkus Armbruster formats = g_renew(const char *, formats, count + 1); 3753e855e4fbSJeff Cody formats[count++] = drv->format_name; 3754ea2384d3Sbellard } 3755ea2384d3Sbellard } 3756e855e4fbSJeff Cody } 3757ada42401SStefan Hajnoczi 3758ada42401SStefan Hajnoczi qsort(formats, count, sizeof(formats[0]), qsort_strcmp); 3759ada42401SStefan Hajnoczi 3760ada42401SStefan Hajnoczi for (i = 0; i < count; i++) { 3761ada42401SStefan Hajnoczi it(opaque, formats[i]); 3762ada42401SStefan Hajnoczi } 3763ada42401SStefan Hajnoczi 3764e855e4fbSJeff Cody g_free(formats); 3765e855e4fbSJeff Cody } 3766ea2384d3Sbellard 3767dc364f4cSBenoît Canet /* This function is to find block backend bs */ 37687f06d47eSMarkus Armbruster /* TODO convert callers to blk_by_name(), then remove */ 3769b338082bSbellard BlockDriverState *bdrv_find(const char *name) 3770b338082bSbellard { 37717f06d47eSMarkus Armbruster BlockBackend *blk = blk_by_name(name); 3772b338082bSbellard 37737f06d47eSMarkus Armbruster return blk ? blk_bs(blk) : NULL; 3774b338082bSbellard } 3775b338082bSbellard 3776dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */ 3777dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name) 3778dc364f4cSBenoît Canet { 3779dc364f4cSBenoît Canet BlockDriverState *bs; 3780dc364f4cSBenoît Canet 3781dc364f4cSBenoît Canet assert(node_name); 3782dc364f4cSBenoît Canet 3783dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) { 3784dc364f4cSBenoît Canet if (!strcmp(node_name, bs->node_name)) { 3785dc364f4cSBenoît Canet return bs; 3786dc364f4cSBenoît Canet } 3787dc364f4cSBenoît Canet } 3788dc364f4cSBenoît Canet return NULL; 3789dc364f4cSBenoît Canet } 3790dc364f4cSBenoît Canet 3791c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */ 3792c13163fbSBenoît Canet BlockDeviceInfoList *bdrv_named_nodes_list(void) 3793c13163fbSBenoît Canet { 3794c13163fbSBenoît Canet BlockDeviceInfoList *list, *entry; 3795c13163fbSBenoît Canet BlockDriverState *bs; 3796c13163fbSBenoît Canet 3797c13163fbSBenoît Canet list = NULL; 3798c13163fbSBenoît Canet QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) { 3799c13163fbSBenoît Canet entry = g_malloc0(sizeof(*entry)); 3800c13163fbSBenoît Canet entry->value = bdrv_block_device_info(bs); 3801c13163fbSBenoît Canet entry->next = list; 3802c13163fbSBenoît Canet list = entry; 3803c13163fbSBenoît Canet } 3804c13163fbSBenoît Canet 3805c13163fbSBenoît Canet return list; 3806c13163fbSBenoît Canet } 3807c13163fbSBenoît Canet 380812d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device, 380912d3ba82SBenoît Canet const char *node_name, 381012d3ba82SBenoît Canet Error **errp) 381112d3ba82SBenoît Canet { 38127f06d47eSMarkus Armbruster BlockBackend *blk; 38137f06d47eSMarkus Armbruster BlockDriverState *bs; 381412d3ba82SBenoît Canet 381512d3ba82SBenoît Canet if (device) { 38167f06d47eSMarkus Armbruster blk = blk_by_name(device); 381712d3ba82SBenoît Canet 38187f06d47eSMarkus Armbruster if (blk) { 38197f06d47eSMarkus Armbruster return blk_bs(blk); 382012d3ba82SBenoît Canet } 3821dd67fa50SBenoît Canet } 382212d3ba82SBenoît Canet 3823dd67fa50SBenoît Canet if (node_name) { 382412d3ba82SBenoît Canet bs = bdrv_find_node(node_name); 382512d3ba82SBenoît Canet 3826dd67fa50SBenoît Canet if (bs) { 3827dd67fa50SBenoît Canet return bs; 3828dd67fa50SBenoît Canet } 382912d3ba82SBenoît Canet } 383012d3ba82SBenoît Canet 3831dd67fa50SBenoît Canet error_setg(errp, "Cannot find device=%s nor node_name=%s", 3832dd67fa50SBenoît Canet device ? device : "", 3833dd67fa50SBenoît Canet node_name ? node_name : ""); 3834dd67fa50SBenoît Canet return NULL; 383512d3ba82SBenoît Canet } 383612d3ba82SBenoît Canet 38375a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise, 38385a6684d2SJeff Cody * return false. If either argument is NULL, return false. */ 38395a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base) 38405a6684d2SJeff Cody { 38415a6684d2SJeff Cody while (top && top != base) { 38425a6684d2SJeff Cody top = top->backing_hd; 38435a6684d2SJeff Cody } 38445a6684d2SJeff Cody 38455a6684d2SJeff Cody return top != NULL; 38465a6684d2SJeff Cody } 38475a6684d2SJeff Cody 384804df765aSFam Zheng BlockDriverState *bdrv_next_node(BlockDriverState *bs) 384904df765aSFam Zheng { 385004df765aSFam Zheng if (!bs) { 385104df765aSFam Zheng return QTAILQ_FIRST(&graph_bdrv_states); 385204df765aSFam Zheng } 385304df765aSFam Zheng return QTAILQ_NEXT(bs, node_list); 385404df765aSFam Zheng } 385504df765aSFam Zheng 38562f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs) 38572f399b0aSMarkus Armbruster { 38582f399b0aSMarkus Armbruster if (!bs) { 38592f399b0aSMarkus Armbruster return QTAILQ_FIRST(&bdrv_states); 38602f399b0aSMarkus Armbruster } 3861dc364f4cSBenoît Canet return QTAILQ_NEXT(bs, device_list); 38622f399b0aSMarkus Armbruster } 38632f399b0aSMarkus Armbruster 386420a9e77dSFam Zheng const char *bdrv_get_node_name(const BlockDriverState *bs) 386520a9e77dSFam Zheng { 386620a9e77dSFam Zheng return bs->node_name; 386720a9e77dSFam Zheng } 386820a9e77dSFam Zheng 38697f06d47eSMarkus Armbruster /* TODO check what callers really want: bs->node_name or blk_name() */ 3870bfb197e0SMarkus Armbruster const char *bdrv_get_device_name(const BlockDriverState *bs) 3871ea2384d3Sbellard { 3872bfb197e0SMarkus Armbruster return bs->blk ? blk_name(bs->blk) : ""; 3873ea2384d3Sbellard } 3874ea2384d3Sbellard 3875c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs) 3876c8433287SMarkus Armbruster { 3877c8433287SMarkus Armbruster return bs->open_flags; 3878c8433287SMarkus Armbruster } 3879c8433287SMarkus Armbruster 3880f0f0fdfeSKevin Wolf int bdrv_flush_all(void) 3881c6ca28d6Saliguori { 3882c6ca28d6Saliguori BlockDriverState *bs; 3883f0f0fdfeSKevin Wolf int result = 0; 3884c6ca28d6Saliguori 3885dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 3886ed78cda3SStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 3887ed78cda3SStefan Hajnoczi int ret; 3888ed78cda3SStefan Hajnoczi 3889ed78cda3SStefan Hajnoczi aio_context_acquire(aio_context); 3890ed78cda3SStefan Hajnoczi ret = bdrv_flush(bs); 3891f0f0fdfeSKevin Wolf if (ret < 0 && !result) { 3892f0f0fdfeSKevin Wolf result = ret; 3893c6ca28d6Saliguori } 3894ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 38951b7bdbc1SStefan Hajnoczi } 3896c6ca28d6Saliguori 3897f0f0fdfeSKevin Wolf return result; 3898f0f0fdfeSKevin Wolf } 3899f0f0fdfeSKevin Wolf 39003ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs) 39013ac21627SPeter Lieven { 39023ac21627SPeter Lieven return 1; 39033ac21627SPeter Lieven } 39043ac21627SPeter Lieven 3905f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs) 3906f2feebbdSKevin Wolf { 3907f2feebbdSKevin Wolf assert(bs->drv); 3908f2feebbdSKevin Wolf 390911212d8fSPaolo Bonzini /* If BS is a copy on write image, it is initialized to 391011212d8fSPaolo Bonzini the contents of the base image, which may not be zeroes. */ 391111212d8fSPaolo Bonzini if (bs->backing_hd) { 391211212d8fSPaolo Bonzini return 0; 391311212d8fSPaolo Bonzini } 3914336c1c12SKevin Wolf if (bs->drv->bdrv_has_zero_init) { 3915336c1c12SKevin Wolf return bs->drv->bdrv_has_zero_init(bs); 3916f2feebbdSKevin Wolf } 3917f2feebbdSKevin Wolf 39183ac21627SPeter Lieven /* safe default */ 39193ac21627SPeter Lieven return 0; 3920f2feebbdSKevin Wolf } 3921f2feebbdSKevin Wolf 39224ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs) 39234ce78691SPeter Lieven { 39244ce78691SPeter Lieven BlockDriverInfo bdi; 39254ce78691SPeter Lieven 39264ce78691SPeter Lieven if (bs->backing_hd) { 39274ce78691SPeter Lieven return false; 39284ce78691SPeter Lieven } 39294ce78691SPeter Lieven 39304ce78691SPeter Lieven if (bdrv_get_info(bs, &bdi) == 0) { 39314ce78691SPeter Lieven return bdi.unallocated_blocks_are_zero; 39324ce78691SPeter Lieven } 39334ce78691SPeter Lieven 39344ce78691SPeter Lieven return false; 39354ce78691SPeter Lieven } 39364ce78691SPeter Lieven 39374ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs) 39384ce78691SPeter Lieven { 39394ce78691SPeter Lieven BlockDriverInfo bdi; 39404ce78691SPeter Lieven 39414ce78691SPeter Lieven if (bs->backing_hd || !(bs->open_flags & BDRV_O_UNMAP)) { 39424ce78691SPeter Lieven return false; 39434ce78691SPeter Lieven } 39444ce78691SPeter Lieven 39454ce78691SPeter Lieven if (bdrv_get_info(bs, &bdi) == 0) { 39464ce78691SPeter Lieven return bdi.can_write_zeroes_with_unmap; 39474ce78691SPeter Lieven } 39484ce78691SPeter Lieven 39494ce78691SPeter Lieven return false; 39504ce78691SPeter Lieven } 39514ce78691SPeter Lieven 3952b6b8a333SPaolo Bonzini typedef struct BdrvCoGetBlockStatusData { 3953376ae3f1SStefan Hajnoczi BlockDriverState *bs; 3954b35b2bbaSMiroslav Rezanina BlockDriverState *base; 3955376ae3f1SStefan Hajnoczi int64_t sector_num; 3956376ae3f1SStefan Hajnoczi int nb_sectors; 3957376ae3f1SStefan Hajnoczi int *pnum; 3958b6b8a333SPaolo Bonzini int64_t ret; 3959376ae3f1SStefan Hajnoczi bool done; 3960b6b8a333SPaolo Bonzini } BdrvCoGetBlockStatusData; 3961376ae3f1SStefan Hajnoczi 3962f58c7b35Sths /* 3963705be728SFam Zheng * Returns the allocation status of the specified sectors. 3964705be728SFam Zheng * Drivers not implementing the functionality are assumed to not support 3965705be728SFam Zheng * backing files, hence all their sectors are reported as allocated. 3966f58c7b35Sths * 3967bd9533e3SStefan Hajnoczi * If 'sector_num' is beyond the end of the disk image the return value is 0 3968bd9533e3SStefan Hajnoczi * and 'pnum' is set to 0. 3969bd9533e3SStefan Hajnoczi * 3970f58c7b35Sths * 'pnum' is set to the number of sectors (including and immediately following 3971f58c7b35Sths * the specified sector) that are known to be in the same 3972f58c7b35Sths * allocated/unallocated state. 3973f58c7b35Sths * 3974bd9533e3SStefan Hajnoczi * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes 3975bd9533e3SStefan Hajnoczi * beyond the end of the disk image it will be clamped. 3976f58c7b35Sths */ 3977b6b8a333SPaolo Bonzini static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs, 3978bdad13b9SPaolo Bonzini int64_t sector_num, 3979060f51c9SStefan Hajnoczi int nb_sectors, int *pnum) 3980f58c7b35Sths { 398130a7f2fcSMarkus Armbruster int64_t total_sectors; 3982f58c7b35Sths int64_t n; 39835daa74a6SPaolo Bonzini int64_t ret, ret2; 3984bd9533e3SStefan Hajnoczi 398530a7f2fcSMarkus Armbruster total_sectors = bdrv_nb_sectors(bs); 398630a7f2fcSMarkus Armbruster if (total_sectors < 0) { 398730a7f2fcSMarkus Armbruster return total_sectors; 3988617ccb46SPaolo Bonzini } 3989617ccb46SPaolo Bonzini 399030a7f2fcSMarkus Armbruster if (sector_num >= total_sectors) { 39916aebab14SStefan Hajnoczi *pnum = 0; 39926aebab14SStefan Hajnoczi return 0; 39936aebab14SStefan Hajnoczi } 3994bd9533e3SStefan Hajnoczi 399530a7f2fcSMarkus Armbruster n = total_sectors - sector_num; 3996bd9533e3SStefan Hajnoczi if (n < nb_sectors) { 3997bd9533e3SStefan Hajnoczi nb_sectors = n; 3998bd9533e3SStefan Hajnoczi } 3999bd9533e3SStefan Hajnoczi 4000b6b8a333SPaolo Bonzini if (!bs->drv->bdrv_co_get_block_status) { 4001bd9533e3SStefan Hajnoczi *pnum = nb_sectors; 4002e88ae226SKevin Wolf ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED; 4003918e92d7SPaolo Bonzini if (bs->drv->protocol_name) { 4004918e92d7SPaolo Bonzini ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE); 4005918e92d7SPaolo Bonzini } 4006918e92d7SPaolo Bonzini return ret; 40076aebab14SStefan Hajnoczi } 40086aebab14SStefan Hajnoczi 4009415b5b01SPaolo Bonzini ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum); 4010415b5b01SPaolo Bonzini if (ret < 0) { 40113e0a233dSPeter Lieven *pnum = 0; 4012415b5b01SPaolo Bonzini return ret; 4013415b5b01SPaolo Bonzini } 4014415b5b01SPaolo Bonzini 401592bc50a5SPeter Lieven if (ret & BDRV_BLOCK_RAW) { 401692bc50a5SPeter Lieven assert(ret & BDRV_BLOCK_OFFSET_VALID); 401792bc50a5SPeter Lieven return bdrv_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS, 401892bc50a5SPeter Lieven *pnum, pnum); 401992bc50a5SPeter Lieven } 402092bc50a5SPeter Lieven 4021e88ae226SKevin Wolf if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) { 4022e88ae226SKevin Wolf ret |= BDRV_BLOCK_ALLOCATED; 4023e88ae226SKevin Wolf } 4024e88ae226SKevin Wolf 4025c3d86884SPeter Lieven if (!(ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO)) { 4026c3d86884SPeter Lieven if (bdrv_unallocated_blocks_are_zero(bs)) { 4027415b5b01SPaolo Bonzini ret |= BDRV_BLOCK_ZERO; 40281f9db224SPeter Lieven } else if (bs->backing_hd) { 4029f0ad5712SPaolo Bonzini BlockDriverState *bs2 = bs->backing_hd; 403030a7f2fcSMarkus Armbruster int64_t nb_sectors2 = bdrv_nb_sectors(bs2); 403130a7f2fcSMarkus Armbruster if (nb_sectors2 >= 0 && sector_num >= nb_sectors2) { 4032f0ad5712SPaolo Bonzini ret |= BDRV_BLOCK_ZERO; 4033f0ad5712SPaolo Bonzini } 4034f0ad5712SPaolo Bonzini } 4035415b5b01SPaolo Bonzini } 40365daa74a6SPaolo Bonzini 40375daa74a6SPaolo Bonzini if (bs->file && 40385daa74a6SPaolo Bonzini (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) && 40395daa74a6SPaolo Bonzini (ret & BDRV_BLOCK_OFFSET_VALID)) { 404059c9a95fSMax Reitz int file_pnum; 404159c9a95fSMax Reitz 40425daa74a6SPaolo Bonzini ret2 = bdrv_co_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS, 404359c9a95fSMax Reitz *pnum, &file_pnum); 40445daa74a6SPaolo Bonzini if (ret2 >= 0) { 40455daa74a6SPaolo Bonzini /* Ignore errors. This is just providing extra information, it 40465daa74a6SPaolo Bonzini * is useful but not necessary. 40475daa74a6SPaolo Bonzini */ 404859c9a95fSMax Reitz if (!file_pnum) { 404959c9a95fSMax Reitz /* !file_pnum indicates an offset at or beyond the EOF; it is 405059c9a95fSMax Reitz * perfectly valid for the format block driver to point to such 405159c9a95fSMax Reitz * offsets, so catch it and mark everything as zero */ 405259c9a95fSMax Reitz ret |= BDRV_BLOCK_ZERO; 405359c9a95fSMax Reitz } else { 405459c9a95fSMax Reitz /* Limit request to the range reported by the protocol driver */ 405559c9a95fSMax Reitz *pnum = file_pnum; 40565daa74a6SPaolo Bonzini ret |= (ret2 & BDRV_BLOCK_ZERO); 40575daa74a6SPaolo Bonzini } 40585daa74a6SPaolo Bonzini } 405959c9a95fSMax Reitz } 40605daa74a6SPaolo Bonzini 4061415b5b01SPaolo Bonzini return ret; 4062060f51c9SStefan Hajnoczi } 4063060f51c9SStefan Hajnoczi 4064b6b8a333SPaolo Bonzini /* Coroutine wrapper for bdrv_get_block_status() */ 4065b6b8a333SPaolo Bonzini static void coroutine_fn bdrv_get_block_status_co_entry(void *opaque) 4066060f51c9SStefan Hajnoczi { 4067b6b8a333SPaolo Bonzini BdrvCoGetBlockStatusData *data = opaque; 4068060f51c9SStefan Hajnoczi BlockDriverState *bs = data->bs; 4069060f51c9SStefan Hajnoczi 4070b6b8a333SPaolo Bonzini data->ret = bdrv_co_get_block_status(bs, data->sector_num, data->nb_sectors, 4071060f51c9SStefan Hajnoczi data->pnum); 4072060f51c9SStefan Hajnoczi data->done = true; 4073060f51c9SStefan Hajnoczi } 4074060f51c9SStefan Hajnoczi 4075060f51c9SStefan Hajnoczi /* 4076b6b8a333SPaolo Bonzini * Synchronous wrapper around bdrv_co_get_block_status(). 4077060f51c9SStefan Hajnoczi * 4078b6b8a333SPaolo Bonzini * See bdrv_co_get_block_status() for details. 4079060f51c9SStefan Hajnoczi */ 4080b6b8a333SPaolo Bonzini int64_t bdrv_get_block_status(BlockDriverState *bs, int64_t sector_num, 4081b6b8a333SPaolo Bonzini int nb_sectors, int *pnum) 4082060f51c9SStefan Hajnoczi { 4083376ae3f1SStefan Hajnoczi Coroutine *co; 4084b6b8a333SPaolo Bonzini BdrvCoGetBlockStatusData data = { 4085376ae3f1SStefan Hajnoczi .bs = bs, 4086376ae3f1SStefan Hajnoczi .sector_num = sector_num, 4087376ae3f1SStefan Hajnoczi .nb_sectors = nb_sectors, 4088376ae3f1SStefan Hajnoczi .pnum = pnum, 4089376ae3f1SStefan Hajnoczi .done = false, 4090376ae3f1SStefan Hajnoczi }; 4091376ae3f1SStefan Hajnoczi 4092bdad13b9SPaolo Bonzini if (qemu_in_coroutine()) { 4093bdad13b9SPaolo Bonzini /* Fast-path if already in coroutine context */ 4094b6b8a333SPaolo Bonzini bdrv_get_block_status_co_entry(&data); 4095bdad13b9SPaolo Bonzini } else { 40962572b37aSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 40972572b37aSStefan Hajnoczi 4098b6b8a333SPaolo Bonzini co = qemu_coroutine_create(bdrv_get_block_status_co_entry); 4099376ae3f1SStefan Hajnoczi qemu_coroutine_enter(co, &data); 4100376ae3f1SStefan Hajnoczi while (!data.done) { 41012572b37aSStefan Hajnoczi aio_poll(aio_context, true); 4102376ae3f1SStefan Hajnoczi } 4103bdad13b9SPaolo Bonzini } 4104376ae3f1SStefan Hajnoczi return data.ret; 4105376ae3f1SStefan Hajnoczi } 4106f58c7b35Sths 4107b6b8a333SPaolo Bonzini int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, 4108b6b8a333SPaolo Bonzini int nb_sectors, int *pnum) 4109b6b8a333SPaolo Bonzini { 41104333bb71SPaolo Bonzini int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum); 41114333bb71SPaolo Bonzini if (ret < 0) { 41124333bb71SPaolo Bonzini return ret; 41134333bb71SPaolo Bonzini } 411401fb2705SKevin Wolf return !!(ret & BDRV_BLOCK_ALLOCATED); 4115b6b8a333SPaolo Bonzini } 4116b6b8a333SPaolo Bonzini 4117188a7bbfSPaolo Bonzini /* 4118188a7bbfSPaolo Bonzini * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP] 4119188a7bbfSPaolo Bonzini * 4120188a7bbfSPaolo Bonzini * Return true if the given sector is allocated in any image between 4121188a7bbfSPaolo Bonzini * BASE and TOP (inclusive). BASE can be NULL to check if the given 4122188a7bbfSPaolo Bonzini * sector is allocated in any image of the chain. Return false otherwise. 4123188a7bbfSPaolo Bonzini * 4124188a7bbfSPaolo Bonzini * 'pnum' is set to the number of sectors (including and immediately following 4125188a7bbfSPaolo Bonzini * the specified sector) that are known to be in the same 4126188a7bbfSPaolo Bonzini * allocated/unallocated state. 4127188a7bbfSPaolo Bonzini * 4128188a7bbfSPaolo Bonzini */ 41294f578637SPaolo Bonzini int bdrv_is_allocated_above(BlockDriverState *top, 4130188a7bbfSPaolo Bonzini BlockDriverState *base, 4131188a7bbfSPaolo Bonzini int64_t sector_num, 4132188a7bbfSPaolo Bonzini int nb_sectors, int *pnum) 4133188a7bbfSPaolo Bonzini { 4134188a7bbfSPaolo Bonzini BlockDriverState *intermediate; 4135188a7bbfSPaolo Bonzini int ret, n = nb_sectors; 4136188a7bbfSPaolo Bonzini 4137188a7bbfSPaolo Bonzini intermediate = top; 4138188a7bbfSPaolo Bonzini while (intermediate && intermediate != base) { 4139188a7bbfSPaolo Bonzini int pnum_inter; 4140bdad13b9SPaolo Bonzini ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors, 4141188a7bbfSPaolo Bonzini &pnum_inter); 4142188a7bbfSPaolo Bonzini if (ret < 0) { 4143188a7bbfSPaolo Bonzini return ret; 4144188a7bbfSPaolo Bonzini } else if (ret) { 4145188a7bbfSPaolo Bonzini *pnum = pnum_inter; 4146188a7bbfSPaolo Bonzini return 1; 4147188a7bbfSPaolo Bonzini } 4148188a7bbfSPaolo Bonzini 4149188a7bbfSPaolo Bonzini /* 4150188a7bbfSPaolo Bonzini * [sector_num, nb_sectors] is unallocated on top but intermediate 4151188a7bbfSPaolo Bonzini * might have 4152188a7bbfSPaolo Bonzini * 4153188a7bbfSPaolo Bonzini * [sector_num+x, nr_sectors] allocated. 4154188a7bbfSPaolo Bonzini */ 415563ba17d3SVishvananda Ishaya if (n > pnum_inter && 415663ba17d3SVishvananda Ishaya (intermediate == top || 415763ba17d3SVishvananda Ishaya sector_num + pnum_inter < intermediate->total_sectors)) { 4158188a7bbfSPaolo Bonzini n = pnum_inter; 4159188a7bbfSPaolo Bonzini } 4160188a7bbfSPaolo Bonzini 4161188a7bbfSPaolo Bonzini intermediate = intermediate->backing_hd; 4162188a7bbfSPaolo Bonzini } 4163188a7bbfSPaolo Bonzini 4164188a7bbfSPaolo Bonzini *pnum = n; 4165188a7bbfSPaolo Bonzini return 0; 4166188a7bbfSPaolo Bonzini } 4167188a7bbfSPaolo Bonzini 4168045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs) 4169045df330Saliguori { 4170045df330Saliguori if (bs->backing_hd && bs->backing_hd->encrypted) 4171045df330Saliguori return bs->backing_file; 4172045df330Saliguori else if (bs->encrypted) 4173045df330Saliguori return bs->filename; 4174045df330Saliguori else 4175045df330Saliguori return NULL; 4176045df330Saliguori } 4177045df330Saliguori 417883f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs, 417983f64091Sbellard char *filename, int filename_size) 418083f64091Sbellard { 418183f64091Sbellard pstrcpy(filename, filename_size, bs->backing_file); 418283f64091Sbellard } 418383f64091Sbellard 4184faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num, 4185faea38e7Sbellard const uint8_t *buf, int nb_sectors) 4186faea38e7Sbellard { 4187faea38e7Sbellard BlockDriver *drv = bs->drv; 4188faea38e7Sbellard if (!drv) 418919cb3738Sbellard return -ENOMEDIUM; 4190faea38e7Sbellard if (!drv->bdrv_write_compressed) 4191faea38e7Sbellard return -ENOTSUP; 4192fbb7b4e0SKevin Wolf if (bdrv_check_request(bs, sector_num, nb_sectors)) 4193fbb7b4e0SKevin Wolf return -EIO; 41947cd1e32aSlirans@il.ibm.com 4195e4654d2dSFam Zheng assert(QLIST_EMPTY(&bs->dirty_bitmaps)); 41967cd1e32aSlirans@il.ibm.com 4197faea38e7Sbellard return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors); 4198faea38e7Sbellard } 4199faea38e7Sbellard 4200faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi) 4201faea38e7Sbellard { 4202faea38e7Sbellard BlockDriver *drv = bs->drv; 4203faea38e7Sbellard if (!drv) 420419cb3738Sbellard return -ENOMEDIUM; 4205faea38e7Sbellard if (!drv->bdrv_get_info) 4206faea38e7Sbellard return -ENOTSUP; 4207faea38e7Sbellard memset(bdi, 0, sizeof(*bdi)); 4208faea38e7Sbellard return drv->bdrv_get_info(bs, bdi); 4209faea38e7Sbellard } 4210faea38e7Sbellard 4211eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs) 4212eae041feSMax Reitz { 4213eae041feSMax Reitz BlockDriver *drv = bs->drv; 4214eae041feSMax Reitz if (drv && drv->bdrv_get_specific_info) { 4215eae041feSMax Reitz return drv->bdrv_get_specific_info(bs); 4216eae041feSMax Reitz } 4217eae041feSMax Reitz return NULL; 4218eae041feSMax Reitz } 4219eae041feSMax Reitz 422045566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf, 422145566e9cSChristoph Hellwig int64_t pos, int size) 4222178e08a5Saliguori { 4223cf8074b3SKevin Wolf QEMUIOVector qiov; 4224cf8074b3SKevin Wolf struct iovec iov = { 4225cf8074b3SKevin Wolf .iov_base = (void *) buf, 4226cf8074b3SKevin Wolf .iov_len = size, 4227cf8074b3SKevin Wolf }; 4228cf8074b3SKevin Wolf 4229cf8074b3SKevin Wolf qemu_iovec_init_external(&qiov, &iov, 1); 4230cf8074b3SKevin Wolf return bdrv_writev_vmstate(bs, &qiov, pos); 4231cf8074b3SKevin Wolf } 4232cf8074b3SKevin Wolf 4233cf8074b3SKevin Wolf int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos) 4234cf8074b3SKevin Wolf { 4235178e08a5Saliguori BlockDriver *drv = bs->drv; 4236cf8074b3SKevin Wolf 4237cf8074b3SKevin Wolf if (!drv) { 4238178e08a5Saliguori return -ENOMEDIUM; 4239cf8074b3SKevin Wolf } else if (drv->bdrv_save_vmstate) { 4240cf8074b3SKevin Wolf return drv->bdrv_save_vmstate(bs, qiov, pos); 4241cf8074b3SKevin Wolf } else if (bs->file) { 4242cf8074b3SKevin Wolf return bdrv_writev_vmstate(bs->file, qiov, pos); 4243cf8074b3SKevin Wolf } 4244cf8074b3SKevin Wolf 42457cdb1f6dSMORITA Kazutaka return -ENOTSUP; 4246178e08a5Saliguori } 4247178e08a5Saliguori 424845566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf, 424945566e9cSChristoph Hellwig int64_t pos, int size) 4250178e08a5Saliguori { 4251178e08a5Saliguori BlockDriver *drv = bs->drv; 4252178e08a5Saliguori if (!drv) 4253178e08a5Saliguori return -ENOMEDIUM; 42547cdb1f6dSMORITA Kazutaka if (drv->bdrv_load_vmstate) 425545566e9cSChristoph Hellwig return drv->bdrv_load_vmstate(bs, buf, pos, size); 42567cdb1f6dSMORITA Kazutaka if (bs->file) 42577cdb1f6dSMORITA Kazutaka return bdrv_load_vmstate(bs->file, buf, pos, size); 42587cdb1f6dSMORITA Kazutaka return -ENOTSUP; 4259178e08a5Saliguori } 4260178e08a5Saliguori 42618b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event) 42628b9b0cc2SKevin Wolf { 4263bf736fe3SKevin Wolf if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) { 42648b9b0cc2SKevin Wolf return; 42658b9b0cc2SKevin Wolf } 42668b9b0cc2SKevin Wolf 4267bf736fe3SKevin Wolf bs->drv->bdrv_debug_event(bs, event); 426841c695c7SKevin Wolf } 42698b9b0cc2SKevin Wolf 427041c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event, 427141c695c7SKevin Wolf const char *tag) 427241c695c7SKevin Wolf { 427341c695c7SKevin Wolf while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) { 427441c695c7SKevin Wolf bs = bs->file; 427541c695c7SKevin Wolf } 427641c695c7SKevin Wolf 427741c695c7SKevin Wolf if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) { 427841c695c7SKevin Wolf return bs->drv->bdrv_debug_breakpoint(bs, event, tag); 427941c695c7SKevin Wolf } 428041c695c7SKevin Wolf 428141c695c7SKevin Wolf return -ENOTSUP; 428241c695c7SKevin Wolf } 428341c695c7SKevin Wolf 42844cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag) 42854cc70e93SFam Zheng { 42864cc70e93SFam Zheng while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) { 42874cc70e93SFam Zheng bs = bs->file; 42884cc70e93SFam Zheng } 42894cc70e93SFam Zheng 42904cc70e93SFam Zheng if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) { 42914cc70e93SFam Zheng return bs->drv->bdrv_debug_remove_breakpoint(bs, tag); 42924cc70e93SFam Zheng } 42934cc70e93SFam Zheng 42944cc70e93SFam Zheng return -ENOTSUP; 42954cc70e93SFam Zheng } 42964cc70e93SFam Zheng 429741c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag) 429841c695c7SKevin Wolf { 4299938789eaSMax Reitz while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) { 430041c695c7SKevin Wolf bs = bs->file; 430141c695c7SKevin Wolf } 430241c695c7SKevin Wolf 430341c695c7SKevin Wolf if (bs && bs->drv && bs->drv->bdrv_debug_resume) { 430441c695c7SKevin Wolf return bs->drv->bdrv_debug_resume(bs, tag); 430541c695c7SKevin Wolf } 430641c695c7SKevin Wolf 430741c695c7SKevin Wolf return -ENOTSUP; 430841c695c7SKevin Wolf } 430941c695c7SKevin Wolf 431041c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag) 431141c695c7SKevin Wolf { 431241c695c7SKevin Wolf while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) { 431341c695c7SKevin Wolf bs = bs->file; 431441c695c7SKevin Wolf } 431541c695c7SKevin Wolf 431641c695c7SKevin Wolf if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) { 431741c695c7SKevin Wolf return bs->drv->bdrv_debug_is_suspended(bs, tag); 431841c695c7SKevin Wolf } 431941c695c7SKevin Wolf 432041c695c7SKevin Wolf return false; 43218b9b0cc2SKevin Wolf } 43228b9b0cc2SKevin Wolf 4323199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs) 4324199630b6SBlue Swirl { 4325199630b6SBlue Swirl return !!(bs->open_flags & BDRV_O_SNAPSHOT); 4326199630b6SBlue Swirl } 4327199630b6SBlue Swirl 4328b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol. If it is 4329b1b1d783SJeff Cody * relative, it must be relative to the chain. So, passing in bs->filename 4330b1b1d783SJeff Cody * from a BDS as backing_file should not be done, as that may be relative to 4331b1b1d783SJeff Cody * the CWD rather than the chain. */ 4332e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs, 4333e8a6bb9cSMarcelo Tosatti const char *backing_file) 4334e8a6bb9cSMarcelo Tosatti { 4335b1b1d783SJeff Cody char *filename_full = NULL; 4336b1b1d783SJeff Cody char *backing_file_full = NULL; 4337b1b1d783SJeff Cody char *filename_tmp = NULL; 4338b1b1d783SJeff Cody int is_protocol = 0; 4339b1b1d783SJeff Cody BlockDriverState *curr_bs = NULL; 4340b1b1d783SJeff Cody BlockDriverState *retval = NULL; 4341b1b1d783SJeff Cody 4342b1b1d783SJeff Cody if (!bs || !bs->drv || !backing_file) { 4343e8a6bb9cSMarcelo Tosatti return NULL; 4344e8a6bb9cSMarcelo Tosatti } 4345e8a6bb9cSMarcelo Tosatti 4346b1b1d783SJeff Cody filename_full = g_malloc(PATH_MAX); 4347b1b1d783SJeff Cody backing_file_full = g_malloc(PATH_MAX); 4348b1b1d783SJeff Cody filename_tmp = g_malloc(PATH_MAX); 4349b1b1d783SJeff Cody 4350b1b1d783SJeff Cody is_protocol = path_has_protocol(backing_file); 4351b1b1d783SJeff Cody 4352b1b1d783SJeff Cody for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) { 4353b1b1d783SJeff Cody 4354b1b1d783SJeff Cody /* If either of the filename paths is actually a protocol, then 4355b1b1d783SJeff Cody * compare unmodified paths; otherwise make paths relative */ 4356b1b1d783SJeff Cody if (is_protocol || path_has_protocol(curr_bs->backing_file)) { 4357b1b1d783SJeff Cody if (strcmp(backing_file, curr_bs->backing_file) == 0) { 4358b1b1d783SJeff Cody retval = curr_bs->backing_hd; 4359b1b1d783SJeff Cody break; 4360b1b1d783SJeff Cody } 4361e8a6bb9cSMarcelo Tosatti } else { 4362b1b1d783SJeff Cody /* If not an absolute filename path, make it relative to the current 4363b1b1d783SJeff Cody * image's filename path */ 4364b1b1d783SJeff Cody path_combine(filename_tmp, PATH_MAX, curr_bs->filename, 4365b1b1d783SJeff Cody backing_file); 4366b1b1d783SJeff Cody 4367b1b1d783SJeff Cody /* We are going to compare absolute pathnames */ 4368b1b1d783SJeff Cody if (!realpath(filename_tmp, filename_full)) { 4369b1b1d783SJeff Cody continue; 4370b1b1d783SJeff Cody } 4371b1b1d783SJeff Cody 4372b1b1d783SJeff Cody /* We need to make sure the backing filename we are comparing against 4373b1b1d783SJeff Cody * is relative to the current image filename (or absolute) */ 4374b1b1d783SJeff Cody path_combine(filename_tmp, PATH_MAX, curr_bs->filename, 4375b1b1d783SJeff Cody curr_bs->backing_file); 4376b1b1d783SJeff Cody 4377b1b1d783SJeff Cody if (!realpath(filename_tmp, backing_file_full)) { 4378b1b1d783SJeff Cody continue; 4379b1b1d783SJeff Cody } 4380b1b1d783SJeff Cody 4381b1b1d783SJeff Cody if (strcmp(backing_file_full, filename_full) == 0) { 4382b1b1d783SJeff Cody retval = curr_bs->backing_hd; 4383b1b1d783SJeff Cody break; 4384b1b1d783SJeff Cody } 4385e8a6bb9cSMarcelo Tosatti } 4386e8a6bb9cSMarcelo Tosatti } 4387e8a6bb9cSMarcelo Tosatti 4388b1b1d783SJeff Cody g_free(filename_full); 4389b1b1d783SJeff Cody g_free(backing_file_full); 4390b1b1d783SJeff Cody g_free(filename_tmp); 4391b1b1d783SJeff Cody return retval; 4392e8a6bb9cSMarcelo Tosatti } 4393e8a6bb9cSMarcelo Tosatti 4394f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs) 4395f198fd1cSBenoît Canet { 4396f198fd1cSBenoît Canet if (!bs->drv) { 4397f198fd1cSBenoît Canet return 0; 4398f198fd1cSBenoît Canet } 4399f198fd1cSBenoît Canet 4400f198fd1cSBenoît Canet if (!bs->backing_hd) { 4401f198fd1cSBenoît Canet return 0; 4402f198fd1cSBenoît Canet } 4403f198fd1cSBenoît Canet 4404f198fd1cSBenoît Canet return 1 + bdrv_get_backing_file_depth(bs->backing_hd); 4405f198fd1cSBenoît Canet } 4406f198fd1cSBenoît Canet 4407ea2384d3Sbellard /**************************************************************/ 440883f64091Sbellard /* async I/Os */ 4409ea2384d3Sbellard 44107c84b1b8SMarkus Armbruster BlockAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num, 4411f141eafeSaliguori QEMUIOVector *qiov, int nb_sectors, 4412097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque) 4413ea2384d3Sbellard { 4414bbf0a440SStefan Hajnoczi trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque); 4415bbf0a440SStefan Hajnoczi 4416d20d9b7cSPaolo Bonzini return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0, 44178c5873d6SStefan Hajnoczi cb, opaque, false); 441883f64091Sbellard } 441983f64091Sbellard 44207c84b1b8SMarkus Armbruster BlockAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num, 4421f141eafeSaliguori QEMUIOVector *qiov, int nb_sectors, 4422097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque) 44237674e7bfSbellard { 4424bbf0a440SStefan Hajnoczi trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque); 4425bbf0a440SStefan Hajnoczi 4426d20d9b7cSPaolo Bonzini return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0, 44278c5873d6SStefan Hajnoczi cb, opaque, true); 442883f64091Sbellard } 442983f64091Sbellard 44307c84b1b8SMarkus Armbruster BlockAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs, 4431d5ef94d4SPaolo Bonzini int64_t sector_num, int nb_sectors, BdrvRequestFlags flags, 4432097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque) 4433d5ef94d4SPaolo Bonzini { 4434d5ef94d4SPaolo Bonzini trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque); 4435d5ef94d4SPaolo Bonzini 4436d5ef94d4SPaolo Bonzini return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors, 4437d5ef94d4SPaolo Bonzini BDRV_REQ_ZERO_WRITE | flags, 4438d5ef94d4SPaolo Bonzini cb, opaque, true); 4439d5ef94d4SPaolo Bonzini } 4440d5ef94d4SPaolo Bonzini 444140b4f539SKevin Wolf 444240b4f539SKevin Wolf typedef struct MultiwriteCB { 444340b4f539SKevin Wolf int error; 444440b4f539SKevin Wolf int num_requests; 444540b4f539SKevin Wolf int num_callbacks; 444640b4f539SKevin Wolf struct { 4447097310b5SMarkus Armbruster BlockCompletionFunc *cb; 444840b4f539SKevin Wolf void *opaque; 444940b4f539SKevin Wolf QEMUIOVector *free_qiov; 445040b4f539SKevin Wolf } callbacks[]; 445140b4f539SKevin Wolf } MultiwriteCB; 445240b4f539SKevin Wolf 445340b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb) 445440b4f539SKevin Wolf { 445540b4f539SKevin Wolf int i; 445640b4f539SKevin Wolf 445740b4f539SKevin Wolf for (i = 0; i < mcb->num_callbacks; i++) { 445840b4f539SKevin Wolf mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error); 44591e1ea48dSStefan Hajnoczi if (mcb->callbacks[i].free_qiov) { 44601e1ea48dSStefan Hajnoczi qemu_iovec_destroy(mcb->callbacks[i].free_qiov); 44611e1ea48dSStefan Hajnoczi } 44627267c094SAnthony Liguori g_free(mcb->callbacks[i].free_qiov); 446340b4f539SKevin Wolf } 446440b4f539SKevin Wolf } 446540b4f539SKevin Wolf 446640b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret) 446740b4f539SKevin Wolf { 446840b4f539SKevin Wolf MultiwriteCB *mcb = opaque; 446940b4f539SKevin Wolf 44706d519a5fSStefan Hajnoczi trace_multiwrite_cb(mcb, ret); 44716d519a5fSStefan Hajnoczi 4472cb6d3ca0SKevin Wolf if (ret < 0 && !mcb->error) { 447340b4f539SKevin Wolf mcb->error = ret; 447440b4f539SKevin Wolf } 447540b4f539SKevin Wolf 447640b4f539SKevin Wolf mcb->num_requests--; 447740b4f539SKevin Wolf if (mcb->num_requests == 0) { 447840b4f539SKevin Wolf multiwrite_user_cb(mcb); 44797267c094SAnthony Liguori g_free(mcb); 448040b4f539SKevin Wolf } 448140b4f539SKevin Wolf } 448240b4f539SKevin Wolf 448340b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b) 448440b4f539SKevin Wolf { 448577be4366SChristoph Hellwig const BlockRequest *req1 = a, *req2 = b; 448677be4366SChristoph Hellwig 448777be4366SChristoph Hellwig /* 448877be4366SChristoph Hellwig * Note that we can't simply subtract req2->sector from req1->sector 448977be4366SChristoph Hellwig * here as that could overflow the return value. 449077be4366SChristoph Hellwig */ 449177be4366SChristoph Hellwig if (req1->sector > req2->sector) { 449277be4366SChristoph Hellwig return 1; 449377be4366SChristoph Hellwig } else if (req1->sector < req2->sector) { 449477be4366SChristoph Hellwig return -1; 449577be4366SChristoph Hellwig } else { 449677be4366SChristoph Hellwig return 0; 449777be4366SChristoph Hellwig } 449840b4f539SKevin Wolf } 449940b4f539SKevin Wolf 450040b4f539SKevin Wolf /* 450140b4f539SKevin Wolf * Takes a bunch of requests and tries to merge them. Returns the number of 450240b4f539SKevin Wolf * requests that remain after merging. 450340b4f539SKevin Wolf */ 450440b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs, 450540b4f539SKevin Wolf int num_reqs, MultiwriteCB *mcb) 450640b4f539SKevin Wolf { 450740b4f539SKevin Wolf int i, outidx; 450840b4f539SKevin Wolf 450940b4f539SKevin Wolf // Sort requests by start sector 451040b4f539SKevin Wolf qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare); 451140b4f539SKevin Wolf 451240b4f539SKevin Wolf // Check if adjacent requests touch the same clusters. If so, combine them, 451340b4f539SKevin Wolf // filling up gaps with zero sectors. 451440b4f539SKevin Wolf outidx = 0; 451540b4f539SKevin Wolf for (i = 1; i < num_reqs; i++) { 451640b4f539SKevin Wolf int merge = 0; 451740b4f539SKevin Wolf int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors; 451840b4f539SKevin Wolf 4519b6a127a1SPaolo Bonzini // Handle exactly sequential writes and overlapping writes. 452040b4f539SKevin Wolf if (reqs[i].sector <= oldreq_last) { 452140b4f539SKevin Wolf merge = 1; 452240b4f539SKevin Wolf } 452340b4f539SKevin Wolf 4524e2a305fbSChristoph Hellwig if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) { 4525e2a305fbSChristoph Hellwig merge = 0; 4526e2a305fbSChristoph Hellwig } 4527e2a305fbSChristoph Hellwig 45286c5a42acSPeter Lieven if (bs->bl.max_transfer_length && reqs[outidx].nb_sectors + 45296c5a42acSPeter Lieven reqs[i].nb_sectors > bs->bl.max_transfer_length) { 45306c5a42acSPeter Lieven merge = 0; 45316c5a42acSPeter Lieven } 45326c5a42acSPeter Lieven 453340b4f539SKevin Wolf if (merge) { 453440b4f539SKevin Wolf size_t size; 45357267c094SAnthony Liguori QEMUIOVector *qiov = g_malloc0(sizeof(*qiov)); 453640b4f539SKevin Wolf qemu_iovec_init(qiov, 453740b4f539SKevin Wolf reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1); 453840b4f539SKevin Wolf 453940b4f539SKevin Wolf // Add the first request to the merged one. If the requests are 454040b4f539SKevin Wolf // overlapping, drop the last sectors of the first request. 454140b4f539SKevin Wolf size = (reqs[i].sector - reqs[outidx].sector) << 9; 45421b093c48SMichael Tokarev qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size); 454340b4f539SKevin Wolf 4544b6a127a1SPaolo Bonzini // We should need to add any zeros between the two requests 4545b6a127a1SPaolo Bonzini assert (reqs[i].sector <= oldreq_last); 454640b4f539SKevin Wolf 454740b4f539SKevin Wolf // Add the second request 45481b093c48SMichael Tokarev qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size); 454940b4f539SKevin Wolf 4550391827ebSStefan Hajnoczi // Add tail of first request, if necessary 4551391827ebSStefan Hajnoczi if (qiov->size < reqs[outidx].qiov->size) { 4552391827ebSStefan Hajnoczi qemu_iovec_concat(qiov, reqs[outidx].qiov, qiov->size, 4553391827ebSStefan Hajnoczi reqs[outidx].qiov->size - qiov->size); 4554391827ebSStefan Hajnoczi } 4555391827ebSStefan Hajnoczi 4556cbf1dff2SKevin Wolf reqs[outidx].nb_sectors = qiov->size >> 9; 455740b4f539SKevin Wolf reqs[outidx].qiov = qiov; 455840b4f539SKevin Wolf 455940b4f539SKevin Wolf mcb->callbacks[i].free_qiov = reqs[outidx].qiov; 456040b4f539SKevin Wolf } else { 456140b4f539SKevin Wolf outidx++; 456240b4f539SKevin Wolf reqs[outidx].sector = reqs[i].sector; 456340b4f539SKevin Wolf reqs[outidx].nb_sectors = reqs[i].nb_sectors; 456440b4f539SKevin Wolf reqs[outidx].qiov = reqs[i].qiov; 456540b4f539SKevin Wolf } 456640b4f539SKevin Wolf } 456740b4f539SKevin Wolf 456840b4f539SKevin Wolf return outidx + 1; 456940b4f539SKevin Wolf } 457040b4f539SKevin Wolf 457140b4f539SKevin Wolf /* 457240b4f539SKevin Wolf * Submit multiple AIO write requests at once. 457340b4f539SKevin Wolf * 457440b4f539SKevin Wolf * On success, the function returns 0 and all requests in the reqs array have 457540b4f539SKevin Wolf * been submitted. In error case this function returns -1, and any of the 457640b4f539SKevin Wolf * requests may or may not be submitted yet. In particular, this means that the 457740b4f539SKevin Wolf * callback will be called for some of the requests, for others it won't. The 457840b4f539SKevin Wolf * caller must check the error field of the BlockRequest to wait for the right 457940b4f539SKevin Wolf * callbacks (if error != 0, no callback will be called). 458040b4f539SKevin Wolf * 458140b4f539SKevin Wolf * The implementation may modify the contents of the reqs array, e.g. to merge 458240b4f539SKevin Wolf * requests. However, the fields opaque and error are left unmodified as they 458340b4f539SKevin Wolf * are used to signal failure for a single request to the caller. 458440b4f539SKevin Wolf */ 458540b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs) 458640b4f539SKevin Wolf { 458740b4f539SKevin Wolf MultiwriteCB *mcb; 458840b4f539SKevin Wolf int i; 458940b4f539SKevin Wolf 4590301db7c2SRyan Harper /* don't submit writes if we don't have a medium */ 4591301db7c2SRyan Harper if (bs->drv == NULL) { 4592301db7c2SRyan Harper for (i = 0; i < num_reqs; i++) { 4593301db7c2SRyan Harper reqs[i].error = -ENOMEDIUM; 4594301db7c2SRyan Harper } 4595301db7c2SRyan Harper return -1; 4596301db7c2SRyan Harper } 4597301db7c2SRyan Harper 459840b4f539SKevin Wolf if (num_reqs == 0) { 459940b4f539SKevin Wolf return 0; 460040b4f539SKevin Wolf } 460140b4f539SKevin Wolf 460240b4f539SKevin Wolf // Create MultiwriteCB structure 46037267c094SAnthony Liguori mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks)); 460440b4f539SKevin Wolf mcb->num_requests = 0; 460540b4f539SKevin Wolf mcb->num_callbacks = num_reqs; 460640b4f539SKevin Wolf 460740b4f539SKevin Wolf for (i = 0; i < num_reqs; i++) { 460840b4f539SKevin Wolf mcb->callbacks[i].cb = reqs[i].cb; 460940b4f539SKevin Wolf mcb->callbacks[i].opaque = reqs[i].opaque; 461040b4f539SKevin Wolf } 461140b4f539SKevin Wolf 461240b4f539SKevin Wolf // Check for mergable requests 461340b4f539SKevin Wolf num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb); 461440b4f539SKevin Wolf 46156d519a5fSStefan Hajnoczi trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs); 46166d519a5fSStefan Hajnoczi 4617df9309fbSPaolo Bonzini /* Run the aio requests. */ 4618df9309fbSPaolo Bonzini mcb->num_requests = num_reqs; 461940b4f539SKevin Wolf for (i = 0; i < num_reqs; i++) { 4620d20d9b7cSPaolo Bonzini bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov, 4621d20d9b7cSPaolo Bonzini reqs[i].nb_sectors, reqs[i].flags, 4622d20d9b7cSPaolo Bonzini multiwrite_cb, mcb, 4623d20d9b7cSPaolo Bonzini true); 462440b4f539SKevin Wolf } 462540b4f539SKevin Wolf 462640b4f539SKevin Wolf return 0; 462740b4f539SKevin Wolf } 462840b4f539SKevin Wolf 46297c84b1b8SMarkus Armbruster void bdrv_aio_cancel(BlockAIOCB *acb) 463083f64091Sbellard { 463102c50efeSFam Zheng qemu_aio_ref(acb); 463202c50efeSFam Zheng bdrv_aio_cancel_async(acb); 463302c50efeSFam Zheng while (acb->refcnt > 1) { 463402c50efeSFam Zheng if (acb->aiocb_info->get_aio_context) { 463502c50efeSFam Zheng aio_poll(acb->aiocb_info->get_aio_context(acb), true); 463602c50efeSFam Zheng } else if (acb->bs) { 463702c50efeSFam Zheng aio_poll(bdrv_get_aio_context(acb->bs), true); 463802c50efeSFam Zheng } else { 463902c50efeSFam Zheng abort(); 464002c50efeSFam Zheng } 464102c50efeSFam Zheng } 46428007429aSFam Zheng qemu_aio_unref(acb); 464302c50efeSFam Zheng } 464402c50efeSFam Zheng 464502c50efeSFam Zheng /* Async version of aio cancel. The caller is not blocked if the acb implements 464602c50efeSFam Zheng * cancel_async, otherwise we do nothing and let the request normally complete. 464702c50efeSFam Zheng * In either case the completion callback must be called. */ 46487c84b1b8SMarkus Armbruster void bdrv_aio_cancel_async(BlockAIOCB *acb) 464902c50efeSFam Zheng { 465002c50efeSFam Zheng if (acb->aiocb_info->cancel_async) { 465102c50efeSFam Zheng acb->aiocb_info->cancel_async(acb); 465202c50efeSFam Zheng } 465383f64091Sbellard } 465483f64091Sbellard 465583f64091Sbellard /**************************************************************/ 465683f64091Sbellard /* async block device emulation */ 465783f64091Sbellard 46587c84b1b8SMarkus Armbruster typedef struct BlockAIOCBSync { 46597c84b1b8SMarkus Armbruster BlockAIOCB common; 4660c16b5a2cSChristoph Hellwig QEMUBH *bh; 4661c16b5a2cSChristoph Hellwig int ret; 4662c16b5a2cSChristoph Hellwig /* vector translation state */ 4663c16b5a2cSChristoph Hellwig QEMUIOVector *qiov; 4664c16b5a2cSChristoph Hellwig uint8_t *bounce; 4665c16b5a2cSChristoph Hellwig int is_write; 46667c84b1b8SMarkus Armbruster } BlockAIOCBSync; 4667c16b5a2cSChristoph Hellwig 4668d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_aiocb_info = { 46697c84b1b8SMarkus Armbruster .aiocb_size = sizeof(BlockAIOCBSync), 4670c16b5a2cSChristoph Hellwig }; 4671c16b5a2cSChristoph Hellwig 467283f64091Sbellard static void bdrv_aio_bh_cb(void *opaque) 4673beac80cdSbellard { 46747c84b1b8SMarkus Armbruster BlockAIOCBSync *acb = opaque; 4675f141eafeSaliguori 4676857d4f46SKevin Wolf if (!acb->is_write && acb->ret >= 0) { 467703396148SMichael Tokarev qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size); 4678857d4f46SKevin Wolf } 4679ceb42de8Saliguori qemu_vfree(acb->bounce); 4680ce1a14dcSpbrook acb->common.cb(acb->common.opaque, acb->ret); 46816a7ad299SDor Laor qemu_bh_delete(acb->bh); 468236afc451SAvi Kivity acb->bh = NULL; 46838007429aSFam Zheng qemu_aio_unref(acb); 4684beac80cdSbellard } 4685beac80cdSbellard 46867c84b1b8SMarkus Armbruster static BlockAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs, 4687f141eafeSaliguori int64_t sector_num, 4688f141eafeSaliguori QEMUIOVector *qiov, 4689f141eafeSaliguori int nb_sectors, 4690097310b5SMarkus Armbruster BlockCompletionFunc *cb, 4691f141eafeSaliguori void *opaque, 4692f141eafeSaliguori int is_write) 4693f141eafeSaliguori 4694ea2384d3Sbellard { 46957c84b1b8SMarkus Armbruster BlockAIOCBSync *acb; 469683f64091Sbellard 4697d7331bedSStefan Hajnoczi acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque); 4698f141eafeSaliguori acb->is_write = is_write; 4699f141eafeSaliguori acb->qiov = qiov; 4700857d4f46SKevin Wolf acb->bounce = qemu_try_blockalign(bs, qiov->size); 47012572b37aSStefan Hajnoczi acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_aio_bh_cb, acb); 4702f141eafeSaliguori 4703857d4f46SKevin Wolf if (acb->bounce == NULL) { 4704857d4f46SKevin Wolf acb->ret = -ENOMEM; 4705857d4f46SKevin Wolf } else if (is_write) { 4706d5e6b161SMichael Tokarev qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size); 47071ed20acfSStefan Hajnoczi acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors); 4708f141eafeSaliguori } else { 47091ed20acfSStefan Hajnoczi acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors); 4710f141eafeSaliguori } 4711f141eafeSaliguori 4712ce1a14dcSpbrook qemu_bh_schedule(acb->bh); 4713f141eafeSaliguori 4714ce1a14dcSpbrook return &acb->common; 47157a6cba61Spbrook } 47167a6cba61Spbrook 47177c84b1b8SMarkus Armbruster static BlockAIOCB *bdrv_aio_readv_em(BlockDriverState *bs, 4718f141eafeSaliguori int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, 4719097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque) 472083f64091Sbellard { 4721f141eafeSaliguori return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0); 472283f64091Sbellard } 472383f64091Sbellard 47247c84b1b8SMarkus Armbruster static BlockAIOCB *bdrv_aio_writev_em(BlockDriverState *bs, 4725f141eafeSaliguori int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, 4726097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque) 4727f141eafeSaliguori { 4728f141eafeSaliguori return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1); 4729f141eafeSaliguori } 4730f141eafeSaliguori 473168485420SKevin Wolf 47327c84b1b8SMarkus Armbruster typedef struct BlockAIOCBCoroutine { 47337c84b1b8SMarkus Armbruster BlockAIOCB common; 473468485420SKevin Wolf BlockRequest req; 473568485420SKevin Wolf bool is_write; 4736d318aea9SKevin Wolf bool *done; 473768485420SKevin Wolf QEMUBH* bh; 47387c84b1b8SMarkus Armbruster } BlockAIOCBCoroutine; 473968485420SKevin Wolf 4740d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_co_aiocb_info = { 47417c84b1b8SMarkus Armbruster .aiocb_size = sizeof(BlockAIOCBCoroutine), 474268485420SKevin Wolf }; 474368485420SKevin Wolf 474435246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque) 474568485420SKevin Wolf { 47467c84b1b8SMarkus Armbruster BlockAIOCBCoroutine *acb = opaque; 474768485420SKevin Wolf 474868485420SKevin Wolf acb->common.cb(acb->common.opaque, acb->req.error); 4749d318aea9SKevin Wolf 475068485420SKevin Wolf qemu_bh_delete(acb->bh); 47518007429aSFam Zheng qemu_aio_unref(acb); 475268485420SKevin Wolf } 475368485420SKevin Wolf 4754b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */ 4755b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque) 4756b2a61371SStefan Hajnoczi { 47577c84b1b8SMarkus Armbruster BlockAIOCBCoroutine *acb = opaque; 4758b2a61371SStefan Hajnoczi BlockDriverState *bs = acb->common.bs; 4759b2a61371SStefan Hajnoczi 4760b2a61371SStefan Hajnoczi if (!acb->is_write) { 4761b2a61371SStefan Hajnoczi acb->req.error = bdrv_co_do_readv(bs, acb->req.sector, 4762d20d9b7cSPaolo Bonzini acb->req.nb_sectors, acb->req.qiov, acb->req.flags); 4763b2a61371SStefan Hajnoczi } else { 4764b2a61371SStefan Hajnoczi acb->req.error = bdrv_co_do_writev(bs, acb->req.sector, 4765d20d9b7cSPaolo Bonzini acb->req.nb_sectors, acb->req.qiov, acb->req.flags); 4766b2a61371SStefan Hajnoczi } 4767b2a61371SStefan Hajnoczi 47682572b37aSStefan Hajnoczi acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb); 4769b2a61371SStefan Hajnoczi qemu_bh_schedule(acb->bh); 4770b2a61371SStefan Hajnoczi } 4771b2a61371SStefan Hajnoczi 47727c84b1b8SMarkus Armbruster static BlockAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs, 477368485420SKevin Wolf int64_t sector_num, 477468485420SKevin Wolf QEMUIOVector *qiov, 477568485420SKevin Wolf int nb_sectors, 4776d20d9b7cSPaolo Bonzini BdrvRequestFlags flags, 4777097310b5SMarkus Armbruster BlockCompletionFunc *cb, 477868485420SKevin Wolf void *opaque, 47798c5873d6SStefan Hajnoczi bool is_write) 478068485420SKevin Wolf { 478168485420SKevin Wolf Coroutine *co; 47827c84b1b8SMarkus Armbruster BlockAIOCBCoroutine *acb; 478368485420SKevin Wolf 4784d7331bedSStefan Hajnoczi acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque); 478568485420SKevin Wolf acb->req.sector = sector_num; 478668485420SKevin Wolf acb->req.nb_sectors = nb_sectors; 478768485420SKevin Wolf acb->req.qiov = qiov; 4788d20d9b7cSPaolo Bonzini acb->req.flags = flags; 478968485420SKevin Wolf acb->is_write = is_write; 479068485420SKevin Wolf 47918c5873d6SStefan Hajnoczi co = qemu_coroutine_create(bdrv_co_do_rw); 479268485420SKevin Wolf qemu_coroutine_enter(co, acb); 479368485420SKevin Wolf 479468485420SKevin Wolf return &acb->common; 479568485420SKevin Wolf } 479668485420SKevin Wolf 479707f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque) 4798b2e12bc6SChristoph Hellwig { 47997c84b1b8SMarkus Armbruster BlockAIOCBCoroutine *acb = opaque; 480007f07615SPaolo Bonzini BlockDriverState *bs = acb->common.bs; 4801b2e12bc6SChristoph Hellwig 480207f07615SPaolo Bonzini acb->req.error = bdrv_co_flush(bs); 48032572b37aSStefan Hajnoczi acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb); 4804b2e12bc6SChristoph Hellwig qemu_bh_schedule(acb->bh); 4805b2e12bc6SChristoph Hellwig } 4806b2e12bc6SChristoph Hellwig 48077c84b1b8SMarkus Armbruster BlockAIOCB *bdrv_aio_flush(BlockDriverState *bs, 4808097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque) 4809016f5cf6SAlexander Graf { 481007f07615SPaolo Bonzini trace_bdrv_aio_flush(bs, opaque); 4811016f5cf6SAlexander Graf 481207f07615SPaolo Bonzini Coroutine *co; 48137c84b1b8SMarkus Armbruster BlockAIOCBCoroutine *acb; 4814016f5cf6SAlexander Graf 4815d7331bedSStefan Hajnoczi acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque); 4816d318aea9SKevin Wolf 481707f07615SPaolo Bonzini co = qemu_coroutine_create(bdrv_aio_flush_co_entry); 481807f07615SPaolo Bonzini qemu_coroutine_enter(co, acb); 4819016f5cf6SAlexander Graf 4820016f5cf6SAlexander Graf return &acb->common; 4821016f5cf6SAlexander Graf } 4822016f5cf6SAlexander Graf 48234265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque) 48244265d620SPaolo Bonzini { 48257c84b1b8SMarkus Armbruster BlockAIOCBCoroutine *acb = opaque; 48264265d620SPaolo Bonzini BlockDriverState *bs = acb->common.bs; 48274265d620SPaolo Bonzini 48284265d620SPaolo Bonzini acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors); 48292572b37aSStefan Hajnoczi acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb); 48304265d620SPaolo Bonzini qemu_bh_schedule(acb->bh); 48314265d620SPaolo Bonzini } 48324265d620SPaolo Bonzini 48337c84b1b8SMarkus Armbruster BlockAIOCB *bdrv_aio_discard(BlockDriverState *bs, 48344265d620SPaolo Bonzini int64_t sector_num, int nb_sectors, 4835097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque) 48364265d620SPaolo Bonzini { 48374265d620SPaolo Bonzini Coroutine *co; 48387c84b1b8SMarkus Armbruster BlockAIOCBCoroutine *acb; 48394265d620SPaolo Bonzini 48404265d620SPaolo Bonzini trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque); 48414265d620SPaolo Bonzini 4842d7331bedSStefan Hajnoczi acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque); 48434265d620SPaolo Bonzini acb->req.sector = sector_num; 48444265d620SPaolo Bonzini acb->req.nb_sectors = nb_sectors; 48454265d620SPaolo Bonzini co = qemu_coroutine_create(bdrv_aio_discard_co_entry); 48464265d620SPaolo Bonzini qemu_coroutine_enter(co, acb); 48474265d620SPaolo Bonzini 48484265d620SPaolo Bonzini return &acb->common; 48494265d620SPaolo Bonzini } 48504265d620SPaolo Bonzini 4851ea2384d3Sbellard void bdrv_init(void) 4852ea2384d3Sbellard { 48535efa9d5aSAnthony Liguori module_call_init(MODULE_INIT_BLOCK); 4854ea2384d3Sbellard } 4855ce1a14dcSpbrook 4856eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void) 4857eb852011SMarkus Armbruster { 4858eb852011SMarkus Armbruster use_bdrv_whitelist = 1; 4859eb852011SMarkus Armbruster bdrv_init(); 4860eb852011SMarkus Armbruster } 4861eb852011SMarkus Armbruster 4862d7331bedSStefan Hajnoczi void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs, 4863097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque) 48646bbff9a0Saliguori { 48657c84b1b8SMarkus Armbruster BlockAIOCB *acb; 4866ce1a14dcSpbrook 4867d7331bedSStefan Hajnoczi acb = g_slice_alloc(aiocb_info->aiocb_size); 4868d7331bedSStefan Hajnoczi acb->aiocb_info = aiocb_info; 4869ce1a14dcSpbrook acb->bs = bs; 4870ce1a14dcSpbrook acb->cb = cb; 4871ce1a14dcSpbrook acb->opaque = opaque; 4872f197fe2bSFam Zheng acb->refcnt = 1; 4873ce1a14dcSpbrook return acb; 4874ce1a14dcSpbrook } 4875ce1a14dcSpbrook 4876f197fe2bSFam Zheng void qemu_aio_ref(void *p) 4877f197fe2bSFam Zheng { 48787c84b1b8SMarkus Armbruster BlockAIOCB *acb = p; 4879f197fe2bSFam Zheng acb->refcnt++; 4880f197fe2bSFam Zheng } 4881f197fe2bSFam Zheng 48828007429aSFam Zheng void qemu_aio_unref(void *p) 4883ce1a14dcSpbrook { 48847c84b1b8SMarkus Armbruster BlockAIOCB *acb = p; 4885f197fe2bSFam Zheng assert(acb->refcnt > 0); 4886f197fe2bSFam Zheng if (--acb->refcnt == 0) { 4887d7331bedSStefan Hajnoczi g_slice_free1(acb->aiocb_info->aiocb_size, acb); 4888ce1a14dcSpbrook } 4889f197fe2bSFam Zheng } 489019cb3738Sbellard 489119cb3738Sbellard /**************************************************************/ 4892f9f05dc5SKevin Wolf /* Coroutine block device emulation */ 4893f9f05dc5SKevin Wolf 4894f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion { 4895f9f05dc5SKevin Wolf Coroutine *coroutine; 4896f9f05dc5SKevin Wolf int ret; 4897f9f05dc5SKevin Wolf } CoroutineIOCompletion; 4898f9f05dc5SKevin Wolf 4899f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret) 4900f9f05dc5SKevin Wolf { 4901f9f05dc5SKevin Wolf CoroutineIOCompletion *co = opaque; 4902f9f05dc5SKevin Wolf 4903f9f05dc5SKevin Wolf co->ret = ret; 4904f9f05dc5SKevin Wolf qemu_coroutine_enter(co->coroutine, NULL); 4905f9f05dc5SKevin Wolf } 4906f9f05dc5SKevin Wolf 4907f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num, 4908f9f05dc5SKevin Wolf int nb_sectors, QEMUIOVector *iov, 4909f9f05dc5SKevin Wolf bool is_write) 4910f9f05dc5SKevin Wolf { 4911f9f05dc5SKevin Wolf CoroutineIOCompletion co = { 4912f9f05dc5SKevin Wolf .coroutine = qemu_coroutine_self(), 4913f9f05dc5SKevin Wolf }; 49147c84b1b8SMarkus Armbruster BlockAIOCB *acb; 4915f9f05dc5SKevin Wolf 4916f9f05dc5SKevin Wolf if (is_write) { 4917a652d160SStefan Hajnoczi acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors, 4918f9f05dc5SKevin Wolf bdrv_co_io_em_complete, &co); 4919f9f05dc5SKevin Wolf } else { 4920a652d160SStefan Hajnoczi acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors, 4921f9f05dc5SKevin Wolf bdrv_co_io_em_complete, &co); 4922f9f05dc5SKevin Wolf } 4923f9f05dc5SKevin Wolf 492459370aaaSStefan Hajnoczi trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb); 4925f9f05dc5SKevin Wolf if (!acb) { 4926f9f05dc5SKevin Wolf return -EIO; 4927f9f05dc5SKevin Wolf } 4928f9f05dc5SKevin Wolf qemu_coroutine_yield(); 4929f9f05dc5SKevin Wolf 4930f9f05dc5SKevin Wolf return co.ret; 4931f9f05dc5SKevin Wolf } 4932f9f05dc5SKevin Wolf 4933f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs, 4934f9f05dc5SKevin Wolf int64_t sector_num, int nb_sectors, 4935f9f05dc5SKevin Wolf QEMUIOVector *iov) 4936f9f05dc5SKevin Wolf { 4937f9f05dc5SKevin Wolf return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false); 4938f9f05dc5SKevin Wolf } 4939f9f05dc5SKevin Wolf 4940f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs, 4941f9f05dc5SKevin Wolf int64_t sector_num, int nb_sectors, 4942f9f05dc5SKevin Wolf QEMUIOVector *iov) 4943f9f05dc5SKevin Wolf { 4944f9f05dc5SKevin Wolf return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true); 4945f9f05dc5SKevin Wolf } 4946f9f05dc5SKevin Wolf 494707f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque) 4948e7a8a783SKevin Wolf { 494907f07615SPaolo Bonzini RwCo *rwco = opaque; 495007f07615SPaolo Bonzini 495107f07615SPaolo Bonzini rwco->ret = bdrv_co_flush(rwco->bs); 495207f07615SPaolo Bonzini } 495307f07615SPaolo Bonzini 495407f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs) 495507f07615SPaolo Bonzini { 4956eb489bb1SKevin Wolf int ret; 4957eb489bb1SKevin Wolf 495829cdb251SPaolo Bonzini if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) { 495907f07615SPaolo Bonzini return 0; 4960eb489bb1SKevin Wolf } 4961eb489bb1SKevin Wolf 4962ca716364SKevin Wolf /* Write back cached data to the OS even with cache=unsafe */ 4963bf736fe3SKevin Wolf BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS); 4964eb489bb1SKevin Wolf if (bs->drv->bdrv_co_flush_to_os) { 4965eb489bb1SKevin Wolf ret = bs->drv->bdrv_co_flush_to_os(bs); 4966eb489bb1SKevin Wolf if (ret < 0) { 4967eb489bb1SKevin Wolf return ret; 4968eb489bb1SKevin Wolf } 4969eb489bb1SKevin Wolf } 4970eb489bb1SKevin Wolf 4971ca716364SKevin Wolf /* But don't actually force it to the disk with cache=unsafe */ 4972ca716364SKevin Wolf if (bs->open_flags & BDRV_O_NO_FLUSH) { 4973d4c82329SKevin Wolf goto flush_parent; 4974ca716364SKevin Wolf } 4975ca716364SKevin Wolf 4976bf736fe3SKevin Wolf BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK); 4977eb489bb1SKevin Wolf if (bs->drv->bdrv_co_flush_to_disk) { 497829cdb251SPaolo Bonzini ret = bs->drv->bdrv_co_flush_to_disk(bs); 497907f07615SPaolo Bonzini } else if (bs->drv->bdrv_aio_flush) { 49807c84b1b8SMarkus Armbruster BlockAIOCB *acb; 4981e7a8a783SKevin Wolf CoroutineIOCompletion co = { 4982e7a8a783SKevin Wolf .coroutine = qemu_coroutine_self(), 4983e7a8a783SKevin Wolf }; 4984e7a8a783SKevin Wolf 498507f07615SPaolo Bonzini acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co); 498607f07615SPaolo Bonzini if (acb == NULL) { 498729cdb251SPaolo Bonzini ret = -EIO; 498807f07615SPaolo Bonzini } else { 4989e7a8a783SKevin Wolf qemu_coroutine_yield(); 499029cdb251SPaolo Bonzini ret = co.ret; 4991e7a8a783SKevin Wolf } 499207f07615SPaolo Bonzini } else { 499307f07615SPaolo Bonzini /* 499407f07615SPaolo Bonzini * Some block drivers always operate in either writethrough or unsafe 499507f07615SPaolo Bonzini * mode and don't support bdrv_flush therefore. Usually qemu doesn't 499607f07615SPaolo Bonzini * know how the server works (because the behaviour is hardcoded or 499707f07615SPaolo Bonzini * depends on server-side configuration), so we can't ensure that 499807f07615SPaolo Bonzini * everything is safe on disk. Returning an error doesn't work because 499907f07615SPaolo Bonzini * that would break guests even if the server operates in writethrough 500007f07615SPaolo Bonzini * mode. 500107f07615SPaolo Bonzini * 500207f07615SPaolo Bonzini * Let's hope the user knows what he's doing. 500307f07615SPaolo Bonzini */ 500429cdb251SPaolo Bonzini ret = 0; 500507f07615SPaolo Bonzini } 500629cdb251SPaolo Bonzini if (ret < 0) { 500729cdb251SPaolo Bonzini return ret; 500829cdb251SPaolo Bonzini } 500929cdb251SPaolo Bonzini 501029cdb251SPaolo Bonzini /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH 501129cdb251SPaolo Bonzini * in the case of cache=unsafe, so there are no useless flushes. 501229cdb251SPaolo Bonzini */ 5013d4c82329SKevin Wolf flush_parent: 501429cdb251SPaolo Bonzini return bdrv_co_flush(bs->file); 501507f07615SPaolo Bonzini } 501607f07615SPaolo Bonzini 50175a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp) 50180f15423cSAnthony Liguori { 50195a8a30dbSKevin Wolf Error *local_err = NULL; 50205a8a30dbSKevin Wolf int ret; 50215a8a30dbSKevin Wolf 50223456a8d1SKevin Wolf if (!bs->drv) { 50233456a8d1SKevin Wolf return; 50240f15423cSAnthony Liguori } 50253456a8d1SKevin Wolf 50267ea2d269SAlexey Kardashevskiy if (!(bs->open_flags & BDRV_O_INCOMING)) { 50277ea2d269SAlexey Kardashevskiy return; 50287ea2d269SAlexey Kardashevskiy } 50297ea2d269SAlexey Kardashevskiy bs->open_flags &= ~BDRV_O_INCOMING; 50307ea2d269SAlexey Kardashevskiy 50313456a8d1SKevin Wolf if (bs->drv->bdrv_invalidate_cache) { 50325a8a30dbSKevin Wolf bs->drv->bdrv_invalidate_cache(bs, &local_err); 50333456a8d1SKevin Wolf } else if (bs->file) { 50345a8a30dbSKevin Wolf bdrv_invalidate_cache(bs->file, &local_err); 50355a8a30dbSKevin Wolf } 50365a8a30dbSKevin Wolf if (local_err) { 50375a8a30dbSKevin Wolf error_propagate(errp, local_err); 50385a8a30dbSKevin Wolf return; 50393456a8d1SKevin Wolf } 50403456a8d1SKevin Wolf 50415a8a30dbSKevin Wolf ret = refresh_total_sectors(bs, bs->total_sectors); 50425a8a30dbSKevin Wolf if (ret < 0) { 50435a8a30dbSKevin Wolf error_setg_errno(errp, -ret, "Could not refresh total sector count"); 50445a8a30dbSKevin Wolf return; 50455a8a30dbSKevin Wolf } 50460f15423cSAnthony Liguori } 50470f15423cSAnthony Liguori 50485a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp) 50490f15423cSAnthony Liguori { 50500f15423cSAnthony Liguori BlockDriverState *bs; 50515a8a30dbSKevin Wolf Error *local_err = NULL; 50520f15423cSAnthony Liguori 5053dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 5054ed78cda3SStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 5055ed78cda3SStefan Hajnoczi 5056ed78cda3SStefan Hajnoczi aio_context_acquire(aio_context); 50575a8a30dbSKevin Wolf bdrv_invalidate_cache(bs, &local_err); 5058ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 50595a8a30dbSKevin Wolf if (local_err) { 50605a8a30dbSKevin Wolf error_propagate(errp, local_err); 50615a8a30dbSKevin Wolf return; 50625a8a30dbSKevin Wolf } 50630f15423cSAnthony Liguori } 50640f15423cSAnthony Liguori } 50650f15423cSAnthony Liguori 506607f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs) 506707f07615SPaolo Bonzini { 506807f07615SPaolo Bonzini Coroutine *co; 506907f07615SPaolo Bonzini RwCo rwco = { 507007f07615SPaolo Bonzini .bs = bs, 507107f07615SPaolo Bonzini .ret = NOT_DONE, 507207f07615SPaolo Bonzini }; 507307f07615SPaolo Bonzini 507407f07615SPaolo Bonzini if (qemu_in_coroutine()) { 507507f07615SPaolo Bonzini /* Fast-path if already in coroutine context */ 507607f07615SPaolo Bonzini bdrv_flush_co_entry(&rwco); 507707f07615SPaolo Bonzini } else { 50782572b37aSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 50792572b37aSStefan Hajnoczi 508007f07615SPaolo Bonzini co = qemu_coroutine_create(bdrv_flush_co_entry); 508107f07615SPaolo Bonzini qemu_coroutine_enter(co, &rwco); 508207f07615SPaolo Bonzini while (rwco.ret == NOT_DONE) { 50832572b37aSStefan Hajnoczi aio_poll(aio_context, true); 508407f07615SPaolo Bonzini } 508507f07615SPaolo Bonzini } 508607f07615SPaolo Bonzini 508707f07615SPaolo Bonzini return rwco.ret; 508807f07615SPaolo Bonzini } 5089e7a8a783SKevin Wolf 5090775aa8b6SKevin Wolf typedef struct DiscardCo { 5091775aa8b6SKevin Wolf BlockDriverState *bs; 5092775aa8b6SKevin Wolf int64_t sector_num; 5093775aa8b6SKevin Wolf int nb_sectors; 5094775aa8b6SKevin Wolf int ret; 5095775aa8b6SKevin Wolf } DiscardCo; 50964265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque) 50974265d620SPaolo Bonzini { 5098775aa8b6SKevin Wolf DiscardCo *rwco = opaque; 50994265d620SPaolo Bonzini 51004265d620SPaolo Bonzini rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors); 51014265d620SPaolo Bonzini } 51024265d620SPaolo Bonzini 51036f14da52SPeter Lieven /* if no limit is specified in the BlockLimits use a default 51046f14da52SPeter Lieven * of 32768 512-byte sectors (16 MiB) per request. 51056f14da52SPeter Lieven */ 51066f14da52SPeter Lieven #define MAX_DISCARD_DEFAULT 32768 51076f14da52SPeter Lieven 51084265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num, 51094265d620SPaolo Bonzini int nb_sectors) 51104265d620SPaolo Bonzini { 5111d51e9fe5SPaolo Bonzini int max_discard; 5112d51e9fe5SPaolo Bonzini 51134265d620SPaolo Bonzini if (!bs->drv) { 51144265d620SPaolo Bonzini return -ENOMEDIUM; 51154265d620SPaolo Bonzini } else if (bdrv_check_request(bs, sector_num, nb_sectors)) { 51164265d620SPaolo Bonzini return -EIO; 51174265d620SPaolo Bonzini } else if (bs->read_only) { 51184265d620SPaolo Bonzini return -EROFS; 5119df702c9bSPaolo Bonzini } 5120df702c9bSPaolo Bonzini 51218f0720ecSPaolo Bonzini bdrv_reset_dirty(bs, sector_num, nb_sectors); 5122df702c9bSPaolo Bonzini 51239e8f1835SPaolo Bonzini /* Do nothing if disabled. */ 51249e8f1835SPaolo Bonzini if (!(bs->open_flags & BDRV_O_UNMAP)) { 51259e8f1835SPaolo Bonzini return 0; 51269e8f1835SPaolo Bonzini } 51279e8f1835SPaolo Bonzini 5128d51e9fe5SPaolo Bonzini if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) { 5129d51e9fe5SPaolo Bonzini return 0; 5130d51e9fe5SPaolo Bonzini } 51316f14da52SPeter Lieven 5132d51e9fe5SPaolo Bonzini max_discard = bs->bl.max_discard ? bs->bl.max_discard : MAX_DISCARD_DEFAULT; 51336f14da52SPeter Lieven while (nb_sectors > 0) { 51346f14da52SPeter Lieven int ret; 51356f14da52SPeter Lieven int num = nb_sectors; 51366f14da52SPeter Lieven 51376f14da52SPeter Lieven /* align request */ 51386f14da52SPeter Lieven if (bs->bl.discard_alignment && 51396f14da52SPeter Lieven num >= bs->bl.discard_alignment && 51406f14da52SPeter Lieven sector_num % bs->bl.discard_alignment) { 51416f14da52SPeter Lieven if (num > bs->bl.discard_alignment) { 51426f14da52SPeter Lieven num = bs->bl.discard_alignment; 51436f14da52SPeter Lieven } 51446f14da52SPeter Lieven num -= sector_num % bs->bl.discard_alignment; 51456f14da52SPeter Lieven } 51466f14da52SPeter Lieven 51476f14da52SPeter Lieven /* limit request size */ 51486f14da52SPeter Lieven if (num > max_discard) { 51496f14da52SPeter Lieven num = max_discard; 51506f14da52SPeter Lieven } 51516f14da52SPeter Lieven 5152d51e9fe5SPaolo Bonzini if (bs->drv->bdrv_co_discard) { 51536f14da52SPeter Lieven ret = bs->drv->bdrv_co_discard(bs, sector_num, num); 5154d51e9fe5SPaolo Bonzini } else { 51557c84b1b8SMarkus Armbruster BlockAIOCB *acb; 51564265d620SPaolo Bonzini CoroutineIOCompletion co = { 51574265d620SPaolo Bonzini .coroutine = qemu_coroutine_self(), 51584265d620SPaolo Bonzini }; 51594265d620SPaolo Bonzini 51604265d620SPaolo Bonzini acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors, 51614265d620SPaolo Bonzini bdrv_co_io_em_complete, &co); 51624265d620SPaolo Bonzini if (acb == NULL) { 51634265d620SPaolo Bonzini return -EIO; 51644265d620SPaolo Bonzini } else { 51654265d620SPaolo Bonzini qemu_coroutine_yield(); 5166d51e9fe5SPaolo Bonzini ret = co.ret; 51674265d620SPaolo Bonzini } 5168d51e9fe5SPaolo Bonzini } 51697ce21016SPaolo Bonzini if (ret && ret != -ENOTSUP) { 5170d51e9fe5SPaolo Bonzini return ret; 5171d51e9fe5SPaolo Bonzini } 5172d51e9fe5SPaolo Bonzini 5173d51e9fe5SPaolo Bonzini sector_num += num; 5174d51e9fe5SPaolo Bonzini nb_sectors -= num; 5175d51e9fe5SPaolo Bonzini } 51764265d620SPaolo Bonzini return 0; 51774265d620SPaolo Bonzini } 51784265d620SPaolo Bonzini 51794265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors) 51804265d620SPaolo Bonzini { 51814265d620SPaolo Bonzini Coroutine *co; 5182775aa8b6SKevin Wolf DiscardCo rwco = { 51834265d620SPaolo Bonzini .bs = bs, 51844265d620SPaolo Bonzini .sector_num = sector_num, 51854265d620SPaolo Bonzini .nb_sectors = nb_sectors, 51864265d620SPaolo Bonzini .ret = NOT_DONE, 51874265d620SPaolo Bonzini }; 51884265d620SPaolo Bonzini 51894265d620SPaolo Bonzini if (qemu_in_coroutine()) { 51904265d620SPaolo Bonzini /* Fast-path if already in coroutine context */ 51914265d620SPaolo Bonzini bdrv_discard_co_entry(&rwco); 51924265d620SPaolo Bonzini } else { 51932572b37aSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 51942572b37aSStefan Hajnoczi 51954265d620SPaolo Bonzini co = qemu_coroutine_create(bdrv_discard_co_entry); 51964265d620SPaolo Bonzini qemu_coroutine_enter(co, &rwco); 51974265d620SPaolo Bonzini while (rwco.ret == NOT_DONE) { 51982572b37aSStefan Hajnoczi aio_poll(aio_context, true); 51994265d620SPaolo Bonzini } 52004265d620SPaolo Bonzini } 52014265d620SPaolo Bonzini 52024265d620SPaolo Bonzini return rwco.ret; 52034265d620SPaolo Bonzini } 52044265d620SPaolo Bonzini 5205f9f05dc5SKevin Wolf /**************************************************************/ 520619cb3738Sbellard /* removable device support */ 520719cb3738Sbellard 520819cb3738Sbellard /** 520919cb3738Sbellard * Return TRUE if the media is present 521019cb3738Sbellard */ 521119cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs) 521219cb3738Sbellard { 521319cb3738Sbellard BlockDriver *drv = bs->drv; 5214a1aff5bfSMarkus Armbruster 521519cb3738Sbellard if (!drv) 521619cb3738Sbellard return 0; 521719cb3738Sbellard if (!drv->bdrv_is_inserted) 5218a1aff5bfSMarkus Armbruster return 1; 5219a1aff5bfSMarkus Armbruster return drv->bdrv_is_inserted(bs); 522019cb3738Sbellard } 522119cb3738Sbellard 522219cb3738Sbellard /** 52238e49ca46SMarkus Armbruster * Return whether the media changed since the last call to this 52248e49ca46SMarkus Armbruster * function, or -ENOTSUP if we don't know. Most drivers don't know. 522519cb3738Sbellard */ 522619cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs) 522719cb3738Sbellard { 522819cb3738Sbellard BlockDriver *drv = bs->drv; 522919cb3738Sbellard 52308e49ca46SMarkus Armbruster if (drv && drv->bdrv_media_changed) { 52318e49ca46SMarkus Armbruster return drv->bdrv_media_changed(bs); 52328e49ca46SMarkus Armbruster } 52338e49ca46SMarkus Armbruster return -ENOTSUP; 523419cb3738Sbellard } 523519cb3738Sbellard 523619cb3738Sbellard /** 523719cb3738Sbellard * If eject_flag is TRUE, eject the media. Otherwise, close the tray 523819cb3738Sbellard */ 5239f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag) 524019cb3738Sbellard { 524119cb3738Sbellard BlockDriver *drv = bs->drv; 5242bfb197e0SMarkus Armbruster const char *device_name; 524319cb3738Sbellard 5244822e1cd1SMarkus Armbruster if (drv && drv->bdrv_eject) { 5245822e1cd1SMarkus Armbruster drv->bdrv_eject(bs, eject_flag); 524619cb3738Sbellard } 52476f382ed2SLuiz Capitulino 5248bfb197e0SMarkus Armbruster device_name = bdrv_get_device_name(bs); 5249bfb197e0SMarkus Armbruster if (device_name[0] != '\0') { 5250bfb197e0SMarkus Armbruster qapi_event_send_device_tray_moved(device_name, 5251a5ee7bd4SWenchao Xia eject_flag, &error_abort); 52526f382ed2SLuiz Capitulino } 525319cb3738Sbellard } 525419cb3738Sbellard 525519cb3738Sbellard /** 525619cb3738Sbellard * Lock or unlock the media (if it is locked, the user won't be able 525719cb3738Sbellard * to eject it manually). 525819cb3738Sbellard */ 5259025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked) 526019cb3738Sbellard { 526119cb3738Sbellard BlockDriver *drv = bs->drv; 526219cb3738Sbellard 5263025e849aSMarkus Armbruster trace_bdrv_lock_medium(bs, locked); 5264b8c6d095SStefan Hajnoczi 5265025e849aSMarkus Armbruster if (drv && drv->bdrv_lock_medium) { 5266025e849aSMarkus Armbruster drv->bdrv_lock_medium(bs, locked); 526719cb3738Sbellard } 526819cb3738Sbellard } 5269985a03b0Sths 5270985a03b0Sths /* needed for generic scsi interface */ 5271985a03b0Sths 5272985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf) 5273985a03b0Sths { 5274985a03b0Sths BlockDriver *drv = bs->drv; 5275985a03b0Sths 5276985a03b0Sths if (drv && drv->bdrv_ioctl) 5277985a03b0Sths return drv->bdrv_ioctl(bs, req, buf); 5278985a03b0Sths return -ENOTSUP; 5279985a03b0Sths } 52807d780669Saliguori 52817c84b1b8SMarkus Armbruster BlockAIOCB *bdrv_aio_ioctl(BlockDriverState *bs, 5282221f715dSaliguori unsigned long int req, void *buf, 5283097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque) 52847d780669Saliguori { 5285221f715dSaliguori BlockDriver *drv = bs->drv; 52867d780669Saliguori 5287221f715dSaliguori if (drv && drv->bdrv_aio_ioctl) 5288221f715dSaliguori return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque); 5289221f715dSaliguori return NULL; 52907d780669Saliguori } 5291e268ca52Saliguori 52921b7fd729SPaolo Bonzini void bdrv_set_guest_block_size(BlockDriverState *bs, int align) 52937b6f9300SMarkus Armbruster { 52941b7fd729SPaolo Bonzini bs->guest_block_size = align; 52957b6f9300SMarkus Armbruster } 52967cd1e32aSlirans@il.ibm.com 5297e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size) 5298e268ca52Saliguori { 5299339064d5SKevin Wolf return qemu_memalign(bdrv_opt_mem_align(bs), size); 5300e268ca52Saliguori } 53017cd1e32aSlirans@il.ibm.com 53029ebd8448SMax Reitz void *qemu_blockalign0(BlockDriverState *bs, size_t size) 53039ebd8448SMax Reitz { 53049ebd8448SMax Reitz return memset(qemu_blockalign(bs, size), 0, size); 53059ebd8448SMax Reitz } 53069ebd8448SMax Reitz 53077d2a35ccSKevin Wolf void *qemu_try_blockalign(BlockDriverState *bs, size_t size) 53087d2a35ccSKevin Wolf { 53097d2a35ccSKevin Wolf size_t align = bdrv_opt_mem_align(bs); 53107d2a35ccSKevin Wolf 53117d2a35ccSKevin Wolf /* Ensure that NULL is never returned on success */ 53127d2a35ccSKevin Wolf assert(align > 0); 53137d2a35ccSKevin Wolf if (size == 0) { 53147d2a35ccSKevin Wolf size = align; 53157d2a35ccSKevin Wolf } 53167d2a35ccSKevin Wolf 53177d2a35ccSKevin Wolf return qemu_try_memalign(align, size); 53187d2a35ccSKevin Wolf } 53197d2a35ccSKevin Wolf 53209ebd8448SMax Reitz void *qemu_try_blockalign0(BlockDriverState *bs, size_t size) 53219ebd8448SMax Reitz { 53229ebd8448SMax Reitz void *mem = qemu_try_blockalign(bs, size); 53239ebd8448SMax Reitz 53249ebd8448SMax Reitz if (mem) { 53259ebd8448SMax Reitz memset(mem, 0, size); 53269ebd8448SMax Reitz } 53279ebd8448SMax Reitz 53289ebd8448SMax Reitz return mem; 53299ebd8448SMax Reitz } 53309ebd8448SMax Reitz 5331c53b1c51SStefan Hajnoczi /* 5332c53b1c51SStefan Hajnoczi * Check if all memory in this vector is sector aligned. 5333c53b1c51SStefan Hajnoczi */ 5334c53b1c51SStefan Hajnoczi bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov) 5335c53b1c51SStefan Hajnoczi { 5336c53b1c51SStefan Hajnoczi int i; 5337339064d5SKevin Wolf size_t alignment = bdrv_opt_mem_align(bs); 5338c53b1c51SStefan Hajnoczi 5339c53b1c51SStefan Hajnoczi for (i = 0; i < qiov->niov; i++) { 5340339064d5SKevin Wolf if ((uintptr_t) qiov->iov[i].iov_base % alignment) { 5341c53b1c51SStefan Hajnoczi return false; 5342c53b1c51SStefan Hajnoczi } 5343339064d5SKevin Wolf if (qiov->iov[i].iov_len % alignment) { 53441ff735bdSKevin Wolf return false; 53451ff735bdSKevin Wolf } 5346c53b1c51SStefan Hajnoczi } 5347c53b1c51SStefan Hajnoczi 5348c53b1c51SStefan Hajnoczi return true; 5349c53b1c51SStefan Hajnoczi } 5350c53b1c51SStefan Hajnoczi 5351b8afb520SFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs, int granularity, 5352b8afb520SFam Zheng Error **errp) 53537cd1e32aSlirans@il.ibm.com { 53547cd1e32aSlirans@il.ibm.com int64_t bitmap_size; 5355e4654d2dSFam Zheng BdrvDirtyBitmap *bitmap; 5356a55eb92cSJan Kiszka 535750717e94SPaolo Bonzini assert((granularity & (granularity - 1)) == 0); 535850717e94SPaolo Bonzini 535950717e94SPaolo Bonzini granularity >>= BDRV_SECTOR_BITS; 5360e4654d2dSFam Zheng assert(granularity); 536157322b78SMarkus Armbruster bitmap_size = bdrv_nb_sectors(bs); 5362b8afb520SFam Zheng if (bitmap_size < 0) { 5363b8afb520SFam Zheng error_setg_errno(errp, -bitmap_size, "could not get length of device"); 5364b8afb520SFam Zheng errno = -bitmap_size; 5365b8afb520SFam Zheng return NULL; 5366b8afb520SFam Zheng } 53675839e53bSMarkus Armbruster bitmap = g_new0(BdrvDirtyBitmap, 1); 5368e4654d2dSFam Zheng bitmap->bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1); 5369e4654d2dSFam Zheng QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list); 5370e4654d2dSFam Zheng return bitmap; 5371e4654d2dSFam Zheng } 5372e4654d2dSFam Zheng 5373e4654d2dSFam Zheng void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap) 5374e4654d2dSFam Zheng { 5375e4654d2dSFam Zheng BdrvDirtyBitmap *bm, *next; 5376e4654d2dSFam Zheng QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) { 5377e4654d2dSFam Zheng if (bm == bitmap) { 5378e4654d2dSFam Zheng QLIST_REMOVE(bitmap, list); 5379e4654d2dSFam Zheng hbitmap_free(bitmap->bitmap); 5380e4654d2dSFam Zheng g_free(bitmap); 5381e4654d2dSFam Zheng return; 53827cd1e32aSlirans@il.ibm.com } 53837cd1e32aSlirans@il.ibm.com } 53847cd1e32aSlirans@il.ibm.com } 53857cd1e32aSlirans@il.ibm.com 538621b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs) 538721b56835SFam Zheng { 538821b56835SFam Zheng BdrvDirtyBitmap *bm; 538921b56835SFam Zheng BlockDirtyInfoList *list = NULL; 539021b56835SFam Zheng BlockDirtyInfoList **plist = &list; 539121b56835SFam Zheng 539221b56835SFam Zheng QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) { 53935839e53bSMarkus Armbruster BlockDirtyInfo *info = g_new0(BlockDirtyInfo, 1); 53945839e53bSMarkus Armbruster BlockDirtyInfoList *entry = g_new0(BlockDirtyInfoList, 1); 539521b56835SFam Zheng info->count = bdrv_get_dirty_count(bs, bm); 539621b56835SFam Zheng info->granularity = 539721b56835SFam Zheng ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bm->bitmap)); 539821b56835SFam Zheng entry->value = info; 539921b56835SFam Zheng *plist = entry; 540021b56835SFam Zheng plist = &entry->next; 540121b56835SFam Zheng } 540221b56835SFam Zheng 540321b56835SFam Zheng return list; 540421b56835SFam Zheng } 540521b56835SFam Zheng 5406e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector) 54077cd1e32aSlirans@il.ibm.com { 5408e4654d2dSFam Zheng if (bitmap) { 5409e4654d2dSFam Zheng return hbitmap_get(bitmap->bitmap, sector); 54107cd1e32aSlirans@il.ibm.com } else { 54117cd1e32aSlirans@il.ibm.com return 0; 54127cd1e32aSlirans@il.ibm.com } 54137cd1e32aSlirans@il.ibm.com } 54147cd1e32aSlirans@il.ibm.com 5415e4654d2dSFam Zheng void bdrv_dirty_iter_init(BlockDriverState *bs, 5416e4654d2dSFam Zheng BdrvDirtyBitmap *bitmap, HBitmapIter *hbi) 54171755da16SPaolo Bonzini { 5418e4654d2dSFam Zheng hbitmap_iter_init(hbi, bitmap->bitmap, 0); 54191755da16SPaolo Bonzini } 54201755da16SPaolo Bonzini 5421c4237dfaSVladimir Sementsov-Ogievskiy void bdrv_set_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, 5422c4237dfaSVladimir Sementsov-Ogievskiy int64_t cur_sector, int nr_sectors) 5423c4237dfaSVladimir Sementsov-Ogievskiy { 5424c4237dfaSVladimir Sementsov-Ogievskiy hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors); 5425c4237dfaSVladimir Sementsov-Ogievskiy } 5426c4237dfaSVladimir Sementsov-Ogievskiy 5427c4237dfaSVladimir Sementsov-Ogievskiy void bdrv_reset_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, 5428c4237dfaSVladimir Sementsov-Ogievskiy int64_t cur_sector, int nr_sectors) 5429c4237dfaSVladimir Sementsov-Ogievskiy { 5430c4237dfaSVladimir Sementsov-Ogievskiy hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors); 5431c4237dfaSVladimir Sementsov-Ogievskiy } 5432c4237dfaSVladimir Sementsov-Ogievskiy 5433c4237dfaSVladimir Sementsov-Ogievskiy static void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector, 54341755da16SPaolo Bonzini int nr_sectors) 54351755da16SPaolo Bonzini { 5436e4654d2dSFam Zheng BdrvDirtyBitmap *bitmap; 5437e4654d2dSFam Zheng QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) { 5438e4654d2dSFam Zheng hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors); 5439e4654d2dSFam Zheng } 54401755da16SPaolo Bonzini } 54411755da16SPaolo Bonzini 5442c4237dfaSVladimir Sementsov-Ogievskiy static void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, 5443c4237dfaSVladimir Sementsov-Ogievskiy int nr_sectors) 54447cd1e32aSlirans@il.ibm.com { 5445e4654d2dSFam Zheng BdrvDirtyBitmap *bitmap; 5446e4654d2dSFam Zheng QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) { 5447e4654d2dSFam Zheng hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors); 5448e4654d2dSFam Zheng } 54497cd1e32aSlirans@il.ibm.com } 5450aaa0eb75SLiran Schour 5451e4654d2dSFam Zheng int64_t bdrv_get_dirty_count(BlockDriverState *bs, BdrvDirtyBitmap *bitmap) 5452aaa0eb75SLiran Schour { 5453e4654d2dSFam Zheng return hbitmap_count(bitmap->bitmap); 5454aaa0eb75SLiran Schour } 5455f88e1a42SJes Sorensen 54569fcb0251SFam Zheng /* Get a reference to bs */ 54579fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs) 54589fcb0251SFam Zheng { 54599fcb0251SFam Zheng bs->refcnt++; 54609fcb0251SFam Zheng } 54619fcb0251SFam Zheng 54629fcb0251SFam Zheng /* Release a previously grabbed reference to bs. 54639fcb0251SFam Zheng * If after releasing, reference count is zero, the BlockDriverState is 54649fcb0251SFam Zheng * deleted. */ 54659fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs) 54669fcb0251SFam Zheng { 54679a4d5ca6SJeff Cody if (!bs) { 54689a4d5ca6SJeff Cody return; 54699a4d5ca6SJeff Cody } 54709fcb0251SFam Zheng assert(bs->refcnt > 0); 54719fcb0251SFam Zheng if (--bs->refcnt == 0) { 54729fcb0251SFam Zheng bdrv_delete(bs); 54739fcb0251SFam Zheng } 54749fcb0251SFam Zheng } 54759fcb0251SFam Zheng 5476fbe40ff7SFam Zheng struct BdrvOpBlocker { 5477fbe40ff7SFam Zheng Error *reason; 5478fbe40ff7SFam Zheng QLIST_ENTRY(BdrvOpBlocker) list; 5479fbe40ff7SFam Zheng }; 5480fbe40ff7SFam Zheng 5481fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp) 5482fbe40ff7SFam Zheng { 5483fbe40ff7SFam Zheng BdrvOpBlocker *blocker; 5484fbe40ff7SFam Zheng assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX); 5485fbe40ff7SFam Zheng if (!QLIST_EMPTY(&bs->op_blockers[op])) { 5486fbe40ff7SFam Zheng blocker = QLIST_FIRST(&bs->op_blockers[op]); 5487fbe40ff7SFam Zheng if (errp) { 5488fbe40ff7SFam Zheng error_setg(errp, "Device '%s' is busy: %s", 5489bfb197e0SMarkus Armbruster bdrv_get_device_name(bs), 5490bfb197e0SMarkus Armbruster error_get_pretty(blocker->reason)); 5491fbe40ff7SFam Zheng } 5492fbe40ff7SFam Zheng return true; 5493fbe40ff7SFam Zheng } 5494fbe40ff7SFam Zheng return false; 5495fbe40ff7SFam Zheng } 5496fbe40ff7SFam Zheng 5497fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason) 5498fbe40ff7SFam Zheng { 5499fbe40ff7SFam Zheng BdrvOpBlocker *blocker; 5500fbe40ff7SFam Zheng assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX); 5501fbe40ff7SFam Zheng 55025839e53bSMarkus Armbruster blocker = g_new0(BdrvOpBlocker, 1); 5503fbe40ff7SFam Zheng blocker->reason = reason; 5504fbe40ff7SFam Zheng QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list); 5505fbe40ff7SFam Zheng } 5506fbe40ff7SFam Zheng 5507fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason) 5508fbe40ff7SFam Zheng { 5509fbe40ff7SFam Zheng BdrvOpBlocker *blocker, *next; 5510fbe40ff7SFam Zheng assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX); 5511fbe40ff7SFam Zheng QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) { 5512fbe40ff7SFam Zheng if (blocker->reason == reason) { 5513fbe40ff7SFam Zheng QLIST_REMOVE(blocker, list); 5514fbe40ff7SFam Zheng g_free(blocker); 5515fbe40ff7SFam Zheng } 5516fbe40ff7SFam Zheng } 5517fbe40ff7SFam Zheng } 5518fbe40ff7SFam Zheng 5519fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason) 5520fbe40ff7SFam Zheng { 5521fbe40ff7SFam Zheng int i; 5522fbe40ff7SFam Zheng for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { 5523fbe40ff7SFam Zheng bdrv_op_block(bs, i, reason); 5524fbe40ff7SFam Zheng } 5525fbe40ff7SFam Zheng } 5526fbe40ff7SFam Zheng 5527fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason) 5528fbe40ff7SFam Zheng { 5529fbe40ff7SFam Zheng int i; 5530fbe40ff7SFam Zheng for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { 5531fbe40ff7SFam Zheng bdrv_op_unblock(bs, i, reason); 5532fbe40ff7SFam Zheng } 5533fbe40ff7SFam Zheng } 5534fbe40ff7SFam Zheng 5535fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs) 5536fbe40ff7SFam Zheng { 5537fbe40ff7SFam Zheng int i; 5538fbe40ff7SFam Zheng 5539fbe40ff7SFam Zheng for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { 5540fbe40ff7SFam Zheng if (!QLIST_EMPTY(&bs->op_blockers[i])) { 5541fbe40ff7SFam Zheng return false; 5542fbe40ff7SFam Zheng } 5543fbe40ff7SFam Zheng } 5544fbe40ff7SFam Zheng return true; 5545fbe40ff7SFam Zheng } 5546fbe40ff7SFam Zheng 554728a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs) 554828a7282aSLuiz Capitulino { 5549d6bf279eSLuiz Capitulino bs->iostatus_enabled = true; 555058e21ef5SLuiz Capitulino bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK; 555128a7282aSLuiz Capitulino } 555228a7282aSLuiz Capitulino 555328a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly 555428a7282aSLuiz Capitulino * enables it _and_ the VM is configured to stop on errors */ 555528a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs) 555628a7282aSLuiz Capitulino { 5557d6bf279eSLuiz Capitulino return (bs->iostatus_enabled && 555892aa5c6dSPaolo Bonzini (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC || 555992aa5c6dSPaolo Bonzini bs->on_write_error == BLOCKDEV_ON_ERROR_STOP || 556092aa5c6dSPaolo Bonzini bs->on_read_error == BLOCKDEV_ON_ERROR_STOP)); 556128a7282aSLuiz Capitulino } 556228a7282aSLuiz Capitulino 556328a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs) 556428a7282aSLuiz Capitulino { 5565d6bf279eSLuiz Capitulino bs->iostatus_enabled = false; 556628a7282aSLuiz Capitulino } 556728a7282aSLuiz Capitulino 556828a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs) 556928a7282aSLuiz Capitulino { 557028a7282aSLuiz Capitulino if (bdrv_iostatus_is_enabled(bs)) { 557158e21ef5SLuiz Capitulino bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK; 55723bd293c3SPaolo Bonzini if (bs->job) { 55733bd293c3SPaolo Bonzini block_job_iostatus_reset(bs->job); 55743bd293c3SPaolo Bonzini } 557528a7282aSLuiz Capitulino } 557628a7282aSLuiz Capitulino } 557728a7282aSLuiz Capitulino 557828a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error) 557928a7282aSLuiz Capitulino { 55803e1caa5fSPaolo Bonzini assert(bdrv_iostatus_is_enabled(bs)); 55813e1caa5fSPaolo Bonzini if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) { 558258e21ef5SLuiz Capitulino bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE : 558358e21ef5SLuiz Capitulino BLOCK_DEVICE_IO_STATUS_FAILED; 558428a7282aSLuiz Capitulino } 558528a7282aSLuiz Capitulino } 558628a7282aSLuiz Capitulino 5587d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt, 5588f88e1a42SJes Sorensen const char *base_filename, const char *base_fmt, 5589f382d43aSMiroslav Rezanina char *options, uint64_t img_size, int flags, 5590f382d43aSMiroslav Rezanina Error **errp, bool quiet) 5591f88e1a42SJes Sorensen { 559283d0521aSChunyan Liu QemuOptsList *create_opts = NULL; 559383d0521aSChunyan Liu QemuOpts *opts = NULL; 559483d0521aSChunyan Liu const char *backing_fmt, *backing_file; 559583d0521aSChunyan Liu int64_t size; 5596f88e1a42SJes Sorensen BlockDriver *drv, *proto_drv; 559796df67d1SStefan Hajnoczi BlockDriver *backing_drv = NULL; 5598cc84d90fSMax Reitz Error *local_err = NULL; 5599f88e1a42SJes Sorensen int ret = 0; 5600f88e1a42SJes Sorensen 5601f88e1a42SJes Sorensen /* Find driver and parse its options */ 5602f88e1a42SJes Sorensen drv = bdrv_find_format(fmt); 5603f88e1a42SJes Sorensen if (!drv) { 560471c79813SLuiz Capitulino error_setg(errp, "Unknown file format '%s'", fmt); 5605d92ada22SLuiz Capitulino return; 5606f88e1a42SJes Sorensen } 5607f88e1a42SJes Sorensen 560898289620SKevin Wolf proto_drv = bdrv_find_protocol(filename, true); 5609f88e1a42SJes Sorensen if (!proto_drv) { 561071c79813SLuiz Capitulino error_setg(errp, "Unknown protocol '%s'", filename); 5611d92ada22SLuiz Capitulino return; 5612f88e1a42SJes Sorensen } 5613f88e1a42SJes Sorensen 5614c6149724SMax Reitz if (!drv->create_opts) { 5615c6149724SMax Reitz error_setg(errp, "Format driver '%s' does not support image creation", 5616c6149724SMax Reitz drv->format_name); 5617c6149724SMax Reitz return; 5618c6149724SMax Reitz } 5619c6149724SMax Reitz 5620c6149724SMax Reitz if (!proto_drv->create_opts) { 5621c6149724SMax Reitz error_setg(errp, "Protocol driver '%s' does not support image creation", 5622c6149724SMax Reitz proto_drv->format_name); 5623c6149724SMax Reitz return; 5624c6149724SMax Reitz } 5625c6149724SMax Reitz 5626c282e1fdSChunyan Liu create_opts = qemu_opts_append(create_opts, drv->create_opts); 5627c282e1fdSChunyan Liu create_opts = qemu_opts_append(create_opts, proto_drv->create_opts); 5628f88e1a42SJes Sorensen 5629f88e1a42SJes Sorensen /* Create parameter list with default values */ 563083d0521aSChunyan Liu opts = qemu_opts_create(create_opts, NULL, 0, &error_abort); 563183d0521aSChunyan Liu qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size); 5632f88e1a42SJes Sorensen 5633f88e1a42SJes Sorensen /* Parse -o options */ 5634f88e1a42SJes Sorensen if (options) { 563583d0521aSChunyan Liu if (qemu_opts_do_parse(opts, options, NULL) != 0) { 563683d0521aSChunyan Liu error_setg(errp, "Invalid options for file format '%s'", fmt); 5637f88e1a42SJes Sorensen goto out; 5638f88e1a42SJes Sorensen } 5639f88e1a42SJes Sorensen } 5640f88e1a42SJes Sorensen 5641f88e1a42SJes Sorensen if (base_filename) { 564283d0521aSChunyan Liu if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename)) { 564371c79813SLuiz Capitulino error_setg(errp, "Backing file not supported for file format '%s'", 564471c79813SLuiz Capitulino fmt); 5645f88e1a42SJes Sorensen goto out; 5646f88e1a42SJes Sorensen } 5647f88e1a42SJes Sorensen } 5648f88e1a42SJes Sorensen 5649f88e1a42SJes Sorensen if (base_fmt) { 565083d0521aSChunyan Liu if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt)) { 565171c79813SLuiz Capitulino error_setg(errp, "Backing file format not supported for file " 565271c79813SLuiz Capitulino "format '%s'", fmt); 5653f88e1a42SJes Sorensen goto out; 5654f88e1a42SJes Sorensen } 5655f88e1a42SJes Sorensen } 5656f88e1a42SJes Sorensen 565783d0521aSChunyan Liu backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE); 565883d0521aSChunyan Liu if (backing_file) { 565983d0521aSChunyan Liu if (!strcmp(filename, backing_file)) { 566071c79813SLuiz Capitulino error_setg(errp, "Error: Trying to create an image with the " 566171c79813SLuiz Capitulino "same filename as the backing file"); 5662792da93aSJes Sorensen goto out; 5663792da93aSJes Sorensen } 5664792da93aSJes Sorensen } 5665792da93aSJes Sorensen 566683d0521aSChunyan Liu backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT); 566783d0521aSChunyan Liu if (backing_fmt) { 566883d0521aSChunyan Liu backing_drv = bdrv_find_format(backing_fmt); 566996df67d1SStefan Hajnoczi if (!backing_drv) { 567071c79813SLuiz Capitulino error_setg(errp, "Unknown backing file format '%s'", 567183d0521aSChunyan Liu backing_fmt); 5672f88e1a42SJes Sorensen goto out; 5673f88e1a42SJes Sorensen } 5674f88e1a42SJes Sorensen } 5675f88e1a42SJes Sorensen 5676f88e1a42SJes Sorensen // The size for the image must always be specified, with one exception: 5677f88e1a42SJes Sorensen // If we are using a backing file, we can obtain the size from there 567883d0521aSChunyan Liu size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0); 567983d0521aSChunyan Liu if (size == -1) { 568083d0521aSChunyan Liu if (backing_file) { 568166f6b814SMax Reitz BlockDriverState *bs; 568229168018SMax Reitz char *full_backing = g_new0(char, PATH_MAX); 568352bf1e72SMarkus Armbruster int64_t size; 568463090dacSPaolo Bonzini int back_flags; 568563090dacSPaolo Bonzini 568629168018SMax Reitz bdrv_get_full_backing_filename_from_filename(filename, backing_file, 568729168018SMax Reitz full_backing, PATH_MAX, 568829168018SMax Reitz &local_err); 568929168018SMax Reitz if (local_err) { 569029168018SMax Reitz g_free(full_backing); 569129168018SMax Reitz goto out; 569229168018SMax Reitz } 569329168018SMax Reitz 569463090dacSPaolo Bonzini /* backing files always opened read-only */ 569563090dacSPaolo Bonzini back_flags = 569663090dacSPaolo Bonzini flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING); 5697f88e1a42SJes Sorensen 5698f67503e5SMax Reitz bs = NULL; 569929168018SMax Reitz ret = bdrv_open(&bs, full_backing, NULL, NULL, back_flags, 5700cc84d90fSMax Reitz backing_drv, &local_err); 570129168018SMax Reitz g_free(full_backing); 5702f88e1a42SJes Sorensen if (ret < 0) { 5703f88e1a42SJes Sorensen goto out; 5704f88e1a42SJes Sorensen } 570552bf1e72SMarkus Armbruster size = bdrv_getlength(bs); 570652bf1e72SMarkus Armbruster if (size < 0) { 570752bf1e72SMarkus Armbruster error_setg_errno(errp, -size, "Could not get size of '%s'", 570852bf1e72SMarkus Armbruster backing_file); 570952bf1e72SMarkus Armbruster bdrv_unref(bs); 571052bf1e72SMarkus Armbruster goto out; 571152bf1e72SMarkus Armbruster } 5712f88e1a42SJes Sorensen 571383d0521aSChunyan Liu qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size); 571466f6b814SMax Reitz 571566f6b814SMax Reitz bdrv_unref(bs); 5716f88e1a42SJes Sorensen } else { 571771c79813SLuiz Capitulino error_setg(errp, "Image creation needs a size parameter"); 5718f88e1a42SJes Sorensen goto out; 5719f88e1a42SJes Sorensen } 5720f88e1a42SJes Sorensen } 5721f88e1a42SJes Sorensen 5722f382d43aSMiroslav Rezanina if (!quiet) { 5723f88e1a42SJes Sorensen printf("Formatting '%s', fmt=%s", filename, fmt); 572443c5d8f8SFam Zheng qemu_opts_print(opts, " "); 5725f88e1a42SJes Sorensen puts(""); 5726f382d43aSMiroslav Rezanina } 572783d0521aSChunyan Liu 5728c282e1fdSChunyan Liu ret = bdrv_create(drv, filename, opts, &local_err); 572983d0521aSChunyan Liu 5730cc84d90fSMax Reitz if (ret == -EFBIG) { 5731cc84d90fSMax Reitz /* This is generally a better message than whatever the driver would 5732cc84d90fSMax Reitz * deliver (especially because of the cluster_size_hint), since that 5733cc84d90fSMax Reitz * is most probably not much different from "image too large". */ 5734f3f4d2c0SKevin Wolf const char *cluster_size_hint = ""; 573583d0521aSChunyan Liu if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) { 5736f3f4d2c0SKevin Wolf cluster_size_hint = " (try using a larger cluster size)"; 5737f3f4d2c0SKevin Wolf } 5738cc84d90fSMax Reitz error_setg(errp, "The image size is too large for file format '%s'" 5739cc84d90fSMax Reitz "%s", fmt, cluster_size_hint); 5740cc84d90fSMax Reitz error_free(local_err); 5741cc84d90fSMax Reitz local_err = NULL; 5742f88e1a42SJes Sorensen } 5743f88e1a42SJes Sorensen 5744f88e1a42SJes Sorensen out: 574583d0521aSChunyan Liu qemu_opts_del(opts); 574683d0521aSChunyan Liu qemu_opts_free(create_opts); 574784d18f06SMarkus Armbruster if (local_err) { 5748cc84d90fSMax Reitz error_propagate(errp, local_err); 5749cc84d90fSMax Reitz } 5750f88e1a42SJes Sorensen } 575185d126f3SStefan Hajnoczi 575285d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs) 575385d126f3SStefan Hajnoczi { 5754dcd04228SStefan Hajnoczi return bs->aio_context; 5755dcd04228SStefan Hajnoczi } 5756dcd04228SStefan Hajnoczi 5757dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs) 5758dcd04228SStefan Hajnoczi { 575933384421SMax Reitz BdrvAioNotifier *baf; 576033384421SMax Reitz 5761dcd04228SStefan Hajnoczi if (!bs->drv) { 5762dcd04228SStefan Hajnoczi return; 5763dcd04228SStefan Hajnoczi } 5764dcd04228SStefan Hajnoczi 576533384421SMax Reitz QLIST_FOREACH(baf, &bs->aio_notifiers, list) { 576633384421SMax Reitz baf->detach_aio_context(baf->opaque); 576733384421SMax Reitz } 576833384421SMax Reitz 576913af91ebSStefan Hajnoczi if (bs->io_limits_enabled) { 577013af91ebSStefan Hajnoczi throttle_detach_aio_context(&bs->throttle_state); 577113af91ebSStefan Hajnoczi } 5772dcd04228SStefan Hajnoczi if (bs->drv->bdrv_detach_aio_context) { 5773dcd04228SStefan Hajnoczi bs->drv->bdrv_detach_aio_context(bs); 5774dcd04228SStefan Hajnoczi } 5775dcd04228SStefan Hajnoczi if (bs->file) { 5776dcd04228SStefan Hajnoczi bdrv_detach_aio_context(bs->file); 5777dcd04228SStefan Hajnoczi } 5778dcd04228SStefan Hajnoczi if (bs->backing_hd) { 5779dcd04228SStefan Hajnoczi bdrv_detach_aio_context(bs->backing_hd); 5780dcd04228SStefan Hajnoczi } 5781dcd04228SStefan Hajnoczi 5782dcd04228SStefan Hajnoczi bs->aio_context = NULL; 5783dcd04228SStefan Hajnoczi } 5784dcd04228SStefan Hajnoczi 5785dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs, 5786dcd04228SStefan Hajnoczi AioContext *new_context) 5787dcd04228SStefan Hajnoczi { 578833384421SMax Reitz BdrvAioNotifier *ban; 578933384421SMax Reitz 5790dcd04228SStefan Hajnoczi if (!bs->drv) { 5791dcd04228SStefan Hajnoczi return; 5792dcd04228SStefan Hajnoczi } 5793dcd04228SStefan Hajnoczi 5794dcd04228SStefan Hajnoczi bs->aio_context = new_context; 5795dcd04228SStefan Hajnoczi 5796dcd04228SStefan Hajnoczi if (bs->backing_hd) { 5797dcd04228SStefan Hajnoczi bdrv_attach_aio_context(bs->backing_hd, new_context); 5798dcd04228SStefan Hajnoczi } 5799dcd04228SStefan Hajnoczi if (bs->file) { 5800dcd04228SStefan Hajnoczi bdrv_attach_aio_context(bs->file, new_context); 5801dcd04228SStefan Hajnoczi } 5802dcd04228SStefan Hajnoczi if (bs->drv->bdrv_attach_aio_context) { 5803dcd04228SStefan Hajnoczi bs->drv->bdrv_attach_aio_context(bs, new_context); 5804dcd04228SStefan Hajnoczi } 580513af91ebSStefan Hajnoczi if (bs->io_limits_enabled) { 580613af91ebSStefan Hajnoczi throttle_attach_aio_context(&bs->throttle_state, new_context); 580713af91ebSStefan Hajnoczi } 580833384421SMax Reitz 580933384421SMax Reitz QLIST_FOREACH(ban, &bs->aio_notifiers, list) { 581033384421SMax Reitz ban->attached_aio_context(new_context, ban->opaque); 581133384421SMax Reitz } 5812dcd04228SStefan Hajnoczi } 5813dcd04228SStefan Hajnoczi 5814dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context) 5815dcd04228SStefan Hajnoczi { 5816dcd04228SStefan Hajnoczi bdrv_drain_all(); /* ensure there are no in-flight requests */ 5817dcd04228SStefan Hajnoczi 5818dcd04228SStefan Hajnoczi bdrv_detach_aio_context(bs); 5819dcd04228SStefan Hajnoczi 5820dcd04228SStefan Hajnoczi /* This function executes in the old AioContext so acquire the new one in 5821dcd04228SStefan Hajnoczi * case it runs in a different thread. 5822dcd04228SStefan Hajnoczi */ 5823dcd04228SStefan Hajnoczi aio_context_acquire(new_context); 5824dcd04228SStefan Hajnoczi bdrv_attach_aio_context(bs, new_context); 5825dcd04228SStefan Hajnoczi aio_context_release(new_context); 582685d126f3SStefan Hajnoczi } 5827d616b224SStefan Hajnoczi 582833384421SMax Reitz void bdrv_add_aio_context_notifier(BlockDriverState *bs, 582933384421SMax Reitz void (*attached_aio_context)(AioContext *new_context, void *opaque), 583033384421SMax Reitz void (*detach_aio_context)(void *opaque), void *opaque) 583133384421SMax Reitz { 583233384421SMax Reitz BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1); 583333384421SMax Reitz *ban = (BdrvAioNotifier){ 583433384421SMax Reitz .attached_aio_context = attached_aio_context, 583533384421SMax Reitz .detach_aio_context = detach_aio_context, 583633384421SMax Reitz .opaque = opaque 583733384421SMax Reitz }; 583833384421SMax Reitz 583933384421SMax Reitz QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list); 584033384421SMax Reitz } 584133384421SMax Reitz 584233384421SMax Reitz void bdrv_remove_aio_context_notifier(BlockDriverState *bs, 584333384421SMax Reitz void (*attached_aio_context)(AioContext *, 584433384421SMax Reitz void *), 584533384421SMax Reitz void (*detach_aio_context)(void *), 584633384421SMax Reitz void *opaque) 584733384421SMax Reitz { 584833384421SMax Reitz BdrvAioNotifier *ban, *ban_next; 584933384421SMax Reitz 585033384421SMax Reitz QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) { 585133384421SMax Reitz if (ban->attached_aio_context == attached_aio_context && 585233384421SMax Reitz ban->detach_aio_context == detach_aio_context && 585333384421SMax Reitz ban->opaque == opaque) 585433384421SMax Reitz { 585533384421SMax Reitz QLIST_REMOVE(ban, list); 585633384421SMax Reitz g_free(ban); 585733384421SMax Reitz 585833384421SMax Reitz return; 585933384421SMax Reitz } 586033384421SMax Reitz } 586133384421SMax Reitz 586233384421SMax Reitz abort(); 586333384421SMax Reitz } 586433384421SMax Reitz 5865d616b224SStefan Hajnoczi void bdrv_add_before_write_notifier(BlockDriverState *bs, 5866d616b224SStefan Hajnoczi NotifierWithReturn *notifier) 5867d616b224SStefan Hajnoczi { 5868d616b224SStefan Hajnoczi notifier_with_return_list_add(&bs->before_write_notifiers, notifier); 5869d616b224SStefan Hajnoczi } 58706f176b48SMax Reitz 587177485434SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts, 587277485434SMax Reitz BlockDriverAmendStatusCB *status_cb) 58736f176b48SMax Reitz { 5874c282e1fdSChunyan Liu if (!bs->drv->bdrv_amend_options) { 58756f176b48SMax Reitz return -ENOTSUP; 58766f176b48SMax Reitz } 587777485434SMax Reitz return bs->drv->bdrv_amend_options(bs, opts, status_cb); 58786f176b48SMax Reitz } 5879f6186f49SBenoît Canet 5880b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method 5881b5042a36SBenoît Canet * of block filter and by bdrv_is_first_non_filter. 5882b5042a36SBenoît Canet * It is used to test if the given bs is the candidate or recurse more in the 5883b5042a36SBenoît Canet * node graph. 5884212a5a8fSBenoît Canet */ 5885212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs, 5886212a5a8fSBenoît Canet BlockDriverState *candidate) 5887f6186f49SBenoît Canet { 5888b5042a36SBenoît Canet /* return false if basic checks fails */ 5889b5042a36SBenoît Canet if (!bs || !bs->drv) { 5890b5042a36SBenoît Canet return false; 5891b5042a36SBenoît Canet } 5892b5042a36SBenoît Canet 5893b5042a36SBenoît Canet /* the code reached a non block filter driver -> check if the bs is 5894b5042a36SBenoît Canet * the same as the candidate. It's the recursion termination condition. 5895b5042a36SBenoît Canet */ 5896b5042a36SBenoît Canet if (!bs->drv->is_filter) { 5897b5042a36SBenoît Canet return bs == candidate; 5898b5042a36SBenoît Canet } 5899b5042a36SBenoît Canet /* Down this path the driver is a block filter driver */ 5900b5042a36SBenoît Canet 5901b5042a36SBenoît Canet /* If the block filter recursion method is defined use it to recurse down 5902b5042a36SBenoît Canet * the node graph. 5903b5042a36SBenoît Canet */ 5904b5042a36SBenoît Canet if (bs->drv->bdrv_recurse_is_first_non_filter) { 5905212a5a8fSBenoît Canet return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate); 5906212a5a8fSBenoît Canet } 5907212a5a8fSBenoît Canet 5908b5042a36SBenoît Canet /* the driver is a block filter but don't allow to recurse -> return false 5909b5042a36SBenoît Canet */ 5910b5042a36SBenoît Canet return false; 5911212a5a8fSBenoît Canet } 5912212a5a8fSBenoît Canet 5913212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's 5914212a5a8fSBenoît Canet * bs chain. Since we don't have pointers to parents it explore all bs chains 5915212a5a8fSBenoît Canet * from the top. Some filters can choose not to pass down the recursion. 5916212a5a8fSBenoît Canet */ 5917212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate) 5918212a5a8fSBenoît Canet { 5919212a5a8fSBenoît Canet BlockDriverState *bs; 5920212a5a8fSBenoît Canet 5921212a5a8fSBenoît Canet /* walk down the bs forest recursively */ 5922212a5a8fSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 5923212a5a8fSBenoît Canet bool perm; 5924212a5a8fSBenoît Canet 5925b5042a36SBenoît Canet /* try to recurse in this top level bs */ 5926e6dc8a1fSKevin Wolf perm = bdrv_recurse_is_first_non_filter(bs, candidate); 5927212a5a8fSBenoît Canet 5928212a5a8fSBenoît Canet /* candidate is the first non filter */ 5929212a5a8fSBenoît Canet if (perm) { 5930212a5a8fSBenoît Canet return true; 5931212a5a8fSBenoît Canet } 5932212a5a8fSBenoît Canet } 5933212a5a8fSBenoît Canet 5934212a5a8fSBenoît Canet return false; 5935f6186f49SBenoît Canet } 593609158f00SBenoît Canet 593709158f00SBenoît Canet BlockDriverState *check_to_replace_node(const char *node_name, Error **errp) 593809158f00SBenoît Canet { 593909158f00SBenoît Canet BlockDriverState *to_replace_bs = bdrv_find_node(node_name); 59405a7e7a0bSStefan Hajnoczi AioContext *aio_context; 59415a7e7a0bSStefan Hajnoczi 594209158f00SBenoît Canet if (!to_replace_bs) { 594309158f00SBenoît Canet error_setg(errp, "Node name '%s' not found", node_name); 594409158f00SBenoît Canet return NULL; 594509158f00SBenoît Canet } 594609158f00SBenoît Canet 59475a7e7a0bSStefan Hajnoczi aio_context = bdrv_get_aio_context(to_replace_bs); 59485a7e7a0bSStefan Hajnoczi aio_context_acquire(aio_context); 59495a7e7a0bSStefan Hajnoczi 595009158f00SBenoît Canet if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) { 59515a7e7a0bSStefan Hajnoczi to_replace_bs = NULL; 59525a7e7a0bSStefan Hajnoczi goto out; 595309158f00SBenoît Canet } 595409158f00SBenoît Canet 595509158f00SBenoît Canet /* We don't want arbitrary node of the BDS chain to be replaced only the top 595609158f00SBenoît Canet * most non filter in order to prevent data corruption. 595709158f00SBenoît Canet * Another benefit is that this tests exclude backing files which are 595809158f00SBenoît Canet * blocked by the backing blockers. 595909158f00SBenoît Canet */ 596009158f00SBenoît Canet if (!bdrv_is_first_non_filter(to_replace_bs)) { 596109158f00SBenoît Canet error_setg(errp, "Only top most non filter can be replaced"); 59625a7e7a0bSStefan Hajnoczi to_replace_bs = NULL; 59635a7e7a0bSStefan Hajnoczi goto out; 596409158f00SBenoît Canet } 596509158f00SBenoît Canet 59665a7e7a0bSStefan Hajnoczi out: 59675a7e7a0bSStefan Hajnoczi aio_context_release(aio_context); 596809158f00SBenoît Canet return to_replace_bs; 596909158f00SBenoît Canet } 5970448ad91dSMing Lei 5971448ad91dSMing Lei void bdrv_io_plug(BlockDriverState *bs) 5972448ad91dSMing Lei { 5973448ad91dSMing Lei BlockDriver *drv = bs->drv; 5974448ad91dSMing Lei if (drv && drv->bdrv_io_plug) { 5975448ad91dSMing Lei drv->bdrv_io_plug(bs); 5976448ad91dSMing Lei } else if (bs->file) { 5977448ad91dSMing Lei bdrv_io_plug(bs->file); 5978448ad91dSMing Lei } 5979448ad91dSMing Lei } 5980448ad91dSMing Lei 5981448ad91dSMing Lei void bdrv_io_unplug(BlockDriverState *bs) 5982448ad91dSMing Lei { 5983448ad91dSMing Lei BlockDriver *drv = bs->drv; 5984448ad91dSMing Lei if (drv && drv->bdrv_io_unplug) { 5985448ad91dSMing Lei drv->bdrv_io_unplug(bs); 5986448ad91dSMing Lei } else if (bs->file) { 5987448ad91dSMing Lei bdrv_io_unplug(bs->file); 5988448ad91dSMing Lei } 5989448ad91dSMing Lei } 5990448ad91dSMing Lei 5991448ad91dSMing Lei void bdrv_flush_io_queue(BlockDriverState *bs) 5992448ad91dSMing Lei { 5993448ad91dSMing Lei BlockDriver *drv = bs->drv; 5994448ad91dSMing Lei if (drv && drv->bdrv_flush_io_queue) { 5995448ad91dSMing Lei drv->bdrv_flush_io_queue(bs); 5996448ad91dSMing Lei } else if (bs->file) { 5997448ad91dSMing Lei bdrv_flush_io_queue(bs->file); 5998448ad91dSMing Lei } 5999448ad91dSMing Lei } 600091af7014SMax Reitz 600191af7014SMax Reitz static bool append_open_options(QDict *d, BlockDriverState *bs) 600291af7014SMax Reitz { 600391af7014SMax Reitz const QDictEntry *entry; 600491af7014SMax Reitz bool found_any = false; 600591af7014SMax Reitz 600691af7014SMax Reitz for (entry = qdict_first(bs->options); entry; 600791af7014SMax Reitz entry = qdict_next(bs->options, entry)) 600891af7014SMax Reitz { 600991af7014SMax Reitz /* Only take options for this level and exclude all non-driver-specific 601091af7014SMax Reitz * options */ 601191af7014SMax Reitz if (!strchr(qdict_entry_key(entry), '.') && 601291af7014SMax Reitz strcmp(qdict_entry_key(entry), "node-name")) 601391af7014SMax Reitz { 601491af7014SMax Reitz qobject_incref(qdict_entry_value(entry)); 601591af7014SMax Reitz qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry)); 601691af7014SMax Reitz found_any = true; 601791af7014SMax Reitz } 601891af7014SMax Reitz } 601991af7014SMax Reitz 602091af7014SMax Reitz return found_any; 602191af7014SMax Reitz } 602291af7014SMax Reitz 602391af7014SMax Reitz /* Updates the following BDS fields: 602491af7014SMax Reitz * - exact_filename: A filename which may be used for opening a block device 602591af7014SMax Reitz * which (mostly) equals the given BDS (even without any 602691af7014SMax Reitz * other options; so reading and writing must return the same 602791af7014SMax Reitz * results, but caching etc. may be different) 602891af7014SMax Reitz * - full_open_options: Options which, when given when opening a block device 602991af7014SMax Reitz * (without a filename), result in a BDS (mostly) 603091af7014SMax Reitz * equalling the given one 603191af7014SMax Reitz * - filename: If exact_filename is set, it is copied here. Otherwise, 603291af7014SMax Reitz * full_open_options is converted to a JSON object, prefixed with 603391af7014SMax Reitz * "json:" (for use through the JSON pseudo protocol) and put here. 603491af7014SMax Reitz */ 603591af7014SMax Reitz void bdrv_refresh_filename(BlockDriverState *bs) 603691af7014SMax Reitz { 603791af7014SMax Reitz BlockDriver *drv = bs->drv; 603891af7014SMax Reitz QDict *opts; 603991af7014SMax Reitz 604091af7014SMax Reitz if (!drv) { 604191af7014SMax Reitz return; 604291af7014SMax Reitz } 604391af7014SMax Reitz 604491af7014SMax Reitz /* This BDS's file name will most probably depend on its file's name, so 604591af7014SMax Reitz * refresh that first */ 604691af7014SMax Reitz if (bs->file) { 604791af7014SMax Reitz bdrv_refresh_filename(bs->file); 604891af7014SMax Reitz } 604991af7014SMax Reitz 605091af7014SMax Reitz if (drv->bdrv_refresh_filename) { 605191af7014SMax Reitz /* Obsolete information is of no use here, so drop the old file name 605291af7014SMax Reitz * information before refreshing it */ 605391af7014SMax Reitz bs->exact_filename[0] = '\0'; 605491af7014SMax Reitz if (bs->full_open_options) { 605591af7014SMax Reitz QDECREF(bs->full_open_options); 605691af7014SMax Reitz bs->full_open_options = NULL; 605791af7014SMax Reitz } 605891af7014SMax Reitz 605991af7014SMax Reitz drv->bdrv_refresh_filename(bs); 606091af7014SMax Reitz } else if (bs->file) { 606191af7014SMax Reitz /* Try to reconstruct valid information from the underlying file */ 606291af7014SMax Reitz bool has_open_options; 606391af7014SMax Reitz 606491af7014SMax Reitz bs->exact_filename[0] = '\0'; 606591af7014SMax Reitz if (bs->full_open_options) { 606691af7014SMax Reitz QDECREF(bs->full_open_options); 606791af7014SMax Reitz bs->full_open_options = NULL; 606891af7014SMax Reitz } 606991af7014SMax Reitz 607091af7014SMax Reitz opts = qdict_new(); 607191af7014SMax Reitz has_open_options = append_open_options(opts, bs); 607291af7014SMax Reitz 607391af7014SMax Reitz /* If no specific options have been given for this BDS, the filename of 607491af7014SMax Reitz * the underlying file should suffice for this one as well */ 607591af7014SMax Reitz if (bs->file->exact_filename[0] && !has_open_options) { 607691af7014SMax Reitz strcpy(bs->exact_filename, bs->file->exact_filename); 607791af7014SMax Reitz } 607891af7014SMax Reitz /* Reconstructing the full options QDict is simple for most format block 607991af7014SMax Reitz * drivers, as long as the full options are known for the underlying 608091af7014SMax Reitz * file BDS. The full options QDict of that file BDS should somehow 608191af7014SMax Reitz * contain a representation of the filename, therefore the following 608291af7014SMax Reitz * suffices without querying the (exact_)filename of this BDS. */ 608391af7014SMax Reitz if (bs->file->full_open_options) { 608491af7014SMax Reitz qdict_put_obj(opts, "driver", 608591af7014SMax Reitz QOBJECT(qstring_from_str(drv->format_name))); 608691af7014SMax Reitz QINCREF(bs->file->full_open_options); 608791af7014SMax Reitz qdict_put_obj(opts, "file", QOBJECT(bs->file->full_open_options)); 608891af7014SMax Reitz 608991af7014SMax Reitz bs->full_open_options = opts; 609091af7014SMax Reitz } else { 609191af7014SMax Reitz QDECREF(opts); 609291af7014SMax Reitz } 609391af7014SMax Reitz } else if (!bs->full_open_options && qdict_size(bs->options)) { 609491af7014SMax Reitz /* There is no underlying file BDS (at least referenced by BDS.file), 609591af7014SMax Reitz * so the full options QDict should be equal to the options given 609691af7014SMax Reitz * specifically for this block device when it was opened (plus the 609791af7014SMax Reitz * driver specification). 609891af7014SMax Reitz * Because those options don't change, there is no need to update 609991af7014SMax Reitz * full_open_options when it's already set. */ 610091af7014SMax Reitz 610191af7014SMax Reitz opts = qdict_new(); 610291af7014SMax Reitz append_open_options(opts, bs); 610391af7014SMax Reitz qdict_put_obj(opts, "driver", 610491af7014SMax Reitz QOBJECT(qstring_from_str(drv->format_name))); 610591af7014SMax Reitz 610691af7014SMax Reitz if (bs->exact_filename[0]) { 610791af7014SMax Reitz /* This may not work for all block protocol drivers (some may 610891af7014SMax Reitz * require this filename to be parsed), but we have to find some 610991af7014SMax Reitz * default solution here, so just include it. If some block driver 611091af7014SMax Reitz * does not support pure options without any filename at all or 611191af7014SMax Reitz * needs some special format of the options QDict, it needs to 611291af7014SMax Reitz * implement the driver-specific bdrv_refresh_filename() function. 611391af7014SMax Reitz */ 611491af7014SMax Reitz qdict_put_obj(opts, "filename", 611591af7014SMax Reitz QOBJECT(qstring_from_str(bs->exact_filename))); 611691af7014SMax Reitz } 611791af7014SMax Reitz 611891af7014SMax Reitz bs->full_open_options = opts; 611991af7014SMax Reitz } 612091af7014SMax Reitz 612191af7014SMax Reitz if (bs->exact_filename[0]) { 612291af7014SMax Reitz pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename); 612391af7014SMax Reitz } else if (bs->full_open_options) { 612491af7014SMax Reitz QString *json = qobject_to_json(QOBJECT(bs->full_open_options)); 612591af7014SMax Reitz snprintf(bs->filename, sizeof(bs->filename), "json:%s", 612691af7014SMax Reitz qstring_get_str(json)); 612791af7014SMax Reitz QDECREF(json); 612891af7014SMax Reitz } 612991af7014SMax Reitz } 61305366d0c8SBenoît Canet 61315366d0c8SBenoît Canet /* This accessor function purpose is to allow the device models to access the 61325366d0c8SBenoît Canet * BlockAcctStats structure embedded inside a BlockDriverState without being 61335366d0c8SBenoît Canet * aware of the BlockDriverState structure layout. 61345366d0c8SBenoît Canet * It will go away when the BlockAcctStats structure will be moved inside 61355366d0c8SBenoît Canet * the device models. 61365366d0c8SBenoît Canet */ 61375366d0c8SBenoît Canet BlockAcctStats *bdrv_get_stats(BlockDriverState *bs) 61385366d0c8SBenoît Canet { 61395366d0c8SBenoît Canet return &bs->stats; 61405366d0c8SBenoît Canet } 6141