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 100eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */ 101eb852011SMarkus Armbruster static int use_bdrv_whitelist; 102eb852011SMarkus Armbruster 1039e0b22f4SStefan Hajnoczi #ifdef _WIN32 1049e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename) 1059e0b22f4SStefan Hajnoczi { 1069e0b22f4SStefan Hajnoczi return (((filename[0] >= 'a' && filename[0] <= 'z') || 1079e0b22f4SStefan Hajnoczi (filename[0] >= 'A' && filename[0] <= 'Z')) && 1089e0b22f4SStefan Hajnoczi filename[1] == ':'); 1099e0b22f4SStefan Hajnoczi } 1109e0b22f4SStefan Hajnoczi 1119e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename) 1129e0b22f4SStefan Hajnoczi { 1139e0b22f4SStefan Hajnoczi if (is_windows_drive_prefix(filename) && 1149e0b22f4SStefan Hajnoczi filename[2] == '\0') 1159e0b22f4SStefan Hajnoczi return 1; 1169e0b22f4SStefan Hajnoczi if (strstart(filename, "\\\\.\\", NULL) || 1179e0b22f4SStefan Hajnoczi strstart(filename, "//./", NULL)) 1189e0b22f4SStefan Hajnoczi return 1; 1199e0b22f4SStefan Hajnoczi return 0; 1209e0b22f4SStefan Hajnoczi } 1219e0b22f4SStefan Hajnoczi #endif 1229e0b22f4SStefan Hajnoczi 1230563e191SZhi Yong Wu /* throttling disk I/O limits */ 124cc0681c4SBenoît Canet void bdrv_set_io_limits(BlockDriverState *bs, 125cc0681c4SBenoît Canet ThrottleConfig *cfg) 126cc0681c4SBenoît Canet { 127cc0681c4SBenoît Canet int i; 128cc0681c4SBenoît Canet 129cc0681c4SBenoît Canet throttle_config(&bs->throttle_state, cfg); 130cc0681c4SBenoît Canet 131cc0681c4SBenoît Canet for (i = 0; i < 2; i++) { 132cc0681c4SBenoît Canet qemu_co_enter_next(&bs->throttled_reqs[i]); 133cc0681c4SBenoît Canet } 134cc0681c4SBenoît Canet } 135cc0681c4SBenoît Canet 136cc0681c4SBenoît Canet /* this function drain all the throttled IOs */ 137cc0681c4SBenoît Canet static bool bdrv_start_throttled_reqs(BlockDriverState *bs) 138cc0681c4SBenoît Canet { 139cc0681c4SBenoît Canet bool drained = false; 140cc0681c4SBenoît Canet bool enabled = bs->io_limits_enabled; 141cc0681c4SBenoît Canet int i; 142cc0681c4SBenoît Canet 143cc0681c4SBenoît Canet bs->io_limits_enabled = false; 144cc0681c4SBenoît Canet 145cc0681c4SBenoît Canet for (i = 0; i < 2; i++) { 146cc0681c4SBenoît Canet while (qemu_co_enter_next(&bs->throttled_reqs[i])) { 147cc0681c4SBenoît Canet drained = true; 148cc0681c4SBenoît Canet } 149cc0681c4SBenoît Canet } 150cc0681c4SBenoît Canet 151cc0681c4SBenoît Canet bs->io_limits_enabled = enabled; 152cc0681c4SBenoît Canet 153cc0681c4SBenoît Canet return drained; 154cc0681c4SBenoît Canet } 155cc0681c4SBenoît Canet 15698f90dbaSZhi Yong Wu void bdrv_io_limits_disable(BlockDriverState *bs) 15798f90dbaSZhi Yong Wu { 15898f90dbaSZhi Yong Wu bs->io_limits_enabled = false; 15998f90dbaSZhi Yong Wu 160cc0681c4SBenoît Canet bdrv_start_throttled_reqs(bs); 16198f90dbaSZhi Yong Wu 162cc0681c4SBenoît Canet throttle_destroy(&bs->throttle_state); 16398f90dbaSZhi Yong Wu } 16498f90dbaSZhi Yong Wu 165cc0681c4SBenoît Canet static void bdrv_throttle_read_timer_cb(void *opaque) 1660563e191SZhi Yong Wu { 1670563e191SZhi Yong Wu BlockDriverState *bs = opaque; 168cc0681c4SBenoît Canet qemu_co_enter_next(&bs->throttled_reqs[0]); 1690563e191SZhi Yong Wu } 1700563e191SZhi Yong Wu 171cc0681c4SBenoît Canet static void bdrv_throttle_write_timer_cb(void *opaque) 172cc0681c4SBenoît Canet { 173cc0681c4SBenoît Canet BlockDriverState *bs = opaque; 174cc0681c4SBenoît Canet qemu_co_enter_next(&bs->throttled_reqs[1]); 175cc0681c4SBenoît Canet } 176cc0681c4SBenoît Canet 177cc0681c4SBenoît Canet /* should be called before bdrv_set_io_limits if a limit is set */ 1780563e191SZhi Yong Wu void bdrv_io_limits_enable(BlockDriverState *bs) 1790563e191SZhi Yong Wu { 180cc0681c4SBenoît Canet assert(!bs->io_limits_enabled); 181cc0681c4SBenoît Canet throttle_init(&bs->throttle_state, 18213af91ebSStefan Hajnoczi bdrv_get_aio_context(bs), 183cc0681c4SBenoît Canet QEMU_CLOCK_VIRTUAL, 184cc0681c4SBenoît Canet bdrv_throttle_read_timer_cb, 185cc0681c4SBenoît Canet bdrv_throttle_write_timer_cb, 186cc0681c4SBenoît Canet bs); 1870563e191SZhi Yong Wu bs->io_limits_enabled = true; 1880563e191SZhi Yong Wu } 1890563e191SZhi Yong Wu 190cc0681c4SBenoît Canet /* This function makes an IO wait if needed 191cc0681c4SBenoît Canet * 192cc0681c4SBenoît Canet * @nb_sectors: the number of sectors of the IO 193cc0681c4SBenoît Canet * @is_write: is the IO a write 19498f90dbaSZhi Yong Wu */ 195cc0681c4SBenoît Canet static void bdrv_io_limits_intercept(BlockDriverState *bs, 196d5103588SKevin Wolf unsigned int bytes, 197cc0681c4SBenoît Canet bool is_write) 198cc0681c4SBenoît Canet { 199cc0681c4SBenoît Canet /* does this io must wait */ 200cc0681c4SBenoît Canet bool must_wait = throttle_schedule_timer(&bs->throttle_state, is_write); 20198f90dbaSZhi Yong Wu 202cc0681c4SBenoît Canet /* if must wait or any request of this type throttled queue the IO */ 203cc0681c4SBenoît Canet if (must_wait || 204cc0681c4SBenoît Canet !qemu_co_queue_empty(&bs->throttled_reqs[is_write])) { 205cc0681c4SBenoît Canet qemu_co_queue_wait(&bs->throttled_reqs[is_write]); 20698f90dbaSZhi Yong Wu } 20798f90dbaSZhi Yong Wu 208cc0681c4SBenoît Canet /* the IO will be executed, do the accounting */ 209d5103588SKevin Wolf throttle_account(&bs->throttle_state, is_write, bytes); 210d5103588SKevin Wolf 211cc0681c4SBenoît Canet 212cc0681c4SBenoît Canet /* if the next request must wait -> do nothing */ 213cc0681c4SBenoît Canet if (throttle_schedule_timer(&bs->throttle_state, is_write)) { 214cc0681c4SBenoît Canet return; 215cc0681c4SBenoît Canet } 216cc0681c4SBenoît Canet 217cc0681c4SBenoît Canet /* else queue next request for execution */ 218cc0681c4SBenoît Canet qemu_co_queue_next(&bs->throttled_reqs[is_write]); 21998f90dbaSZhi Yong Wu } 22098f90dbaSZhi Yong Wu 221339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs) 222339064d5SKevin Wolf { 223339064d5SKevin Wolf if (!bs || !bs->drv) { 224339064d5SKevin Wolf /* 4k should be on the safe side */ 225339064d5SKevin Wolf return 4096; 226339064d5SKevin Wolf } 227339064d5SKevin Wolf 228339064d5SKevin Wolf return bs->bl.opt_mem_alignment; 229339064d5SKevin Wolf } 230339064d5SKevin Wolf 2319e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */ 2329e0b22f4SStefan Hajnoczi static int path_has_protocol(const char *path) 2339e0b22f4SStefan Hajnoczi { 234947995c0SPaolo Bonzini const char *p; 235947995c0SPaolo Bonzini 2369e0b22f4SStefan Hajnoczi #ifdef _WIN32 2379e0b22f4SStefan Hajnoczi if (is_windows_drive(path) || 2389e0b22f4SStefan Hajnoczi is_windows_drive_prefix(path)) { 2399e0b22f4SStefan Hajnoczi return 0; 2409e0b22f4SStefan Hajnoczi } 241947995c0SPaolo Bonzini p = path + strcspn(path, ":/\\"); 242947995c0SPaolo Bonzini #else 243947995c0SPaolo Bonzini p = path + strcspn(path, ":/"); 2449e0b22f4SStefan Hajnoczi #endif 2459e0b22f4SStefan Hajnoczi 246947995c0SPaolo Bonzini return *p == ':'; 2479e0b22f4SStefan Hajnoczi } 2489e0b22f4SStefan Hajnoczi 24983f64091Sbellard int path_is_absolute(const char *path) 25083f64091Sbellard { 25121664424Sbellard #ifdef _WIN32 25221664424Sbellard /* specific case for names like: "\\.\d:" */ 253f53f4da9SPaolo Bonzini if (is_windows_drive(path) || is_windows_drive_prefix(path)) { 25421664424Sbellard return 1; 255f53f4da9SPaolo Bonzini } 256f53f4da9SPaolo Bonzini return (*path == '/' || *path == '\\'); 2573b9f94e1Sbellard #else 258f53f4da9SPaolo Bonzini return (*path == '/'); 2593b9f94e1Sbellard #endif 26083f64091Sbellard } 26183f64091Sbellard 26283f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a 26383f64091Sbellard path to it by considering it is relative to base_path. URL are 26483f64091Sbellard supported. */ 26583f64091Sbellard void path_combine(char *dest, int dest_size, 26683f64091Sbellard const char *base_path, 26783f64091Sbellard const char *filename) 26883f64091Sbellard { 26983f64091Sbellard const char *p, *p1; 27083f64091Sbellard int len; 27183f64091Sbellard 27283f64091Sbellard if (dest_size <= 0) 27383f64091Sbellard return; 27483f64091Sbellard if (path_is_absolute(filename)) { 27583f64091Sbellard pstrcpy(dest, dest_size, filename); 27683f64091Sbellard } else { 27783f64091Sbellard p = strchr(base_path, ':'); 27883f64091Sbellard if (p) 27983f64091Sbellard p++; 28083f64091Sbellard else 28183f64091Sbellard p = base_path; 2823b9f94e1Sbellard p1 = strrchr(base_path, '/'); 2833b9f94e1Sbellard #ifdef _WIN32 2843b9f94e1Sbellard { 2853b9f94e1Sbellard const char *p2; 2863b9f94e1Sbellard p2 = strrchr(base_path, '\\'); 2873b9f94e1Sbellard if (!p1 || p2 > p1) 2883b9f94e1Sbellard p1 = p2; 2893b9f94e1Sbellard } 2903b9f94e1Sbellard #endif 29183f64091Sbellard if (p1) 29283f64091Sbellard p1++; 29383f64091Sbellard else 29483f64091Sbellard p1 = base_path; 29583f64091Sbellard if (p1 > p) 29683f64091Sbellard p = p1; 29783f64091Sbellard len = p - base_path; 29883f64091Sbellard if (len > dest_size - 1) 29983f64091Sbellard len = dest_size - 1; 30083f64091Sbellard memcpy(dest, base_path, len); 30183f64091Sbellard dest[len] = '\0'; 30283f64091Sbellard pstrcat(dest, dest_size, filename); 30383f64091Sbellard } 30483f64091Sbellard } 30583f64091Sbellard 306dc5a1371SPaolo Bonzini void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz) 307dc5a1371SPaolo Bonzini { 308dc5a1371SPaolo Bonzini if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) { 309dc5a1371SPaolo Bonzini pstrcpy(dest, sz, bs->backing_file); 310dc5a1371SPaolo Bonzini } else { 311dc5a1371SPaolo Bonzini path_combine(dest, sz, bs->filename, bs->backing_file); 312dc5a1371SPaolo Bonzini } 313dc5a1371SPaolo Bonzini } 314dc5a1371SPaolo Bonzini 3155efa9d5aSAnthony Liguori void bdrv_register(BlockDriver *bdrv) 316ea2384d3Sbellard { 3178c5873d6SStefan Hajnoczi /* Block drivers without coroutine functions need emulation */ 3188c5873d6SStefan Hajnoczi if (!bdrv->bdrv_co_readv) { 319f9f05dc5SKevin Wolf bdrv->bdrv_co_readv = bdrv_co_readv_em; 320f9f05dc5SKevin Wolf bdrv->bdrv_co_writev = bdrv_co_writev_em; 321f9f05dc5SKevin Wolf 322f8c35c1dSStefan Hajnoczi /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if 323f8c35c1dSStefan Hajnoczi * the block driver lacks aio we need to emulate that too. 324f8c35c1dSStefan Hajnoczi */ 325f9f05dc5SKevin Wolf if (!bdrv->bdrv_aio_readv) { 32683f64091Sbellard /* add AIO emulation layer */ 327f141eafeSaliguori bdrv->bdrv_aio_readv = bdrv_aio_readv_em; 328f141eafeSaliguori bdrv->bdrv_aio_writev = bdrv_aio_writev_em; 32983f64091Sbellard } 330f9f05dc5SKevin Wolf } 331b2e12bc6SChristoph Hellwig 3328a22f02aSStefan Hajnoczi QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list); 333ea2384d3Sbellard } 334b338082bSbellard 3357f06d47eSMarkus Armbruster BlockDriverState *bdrv_new_root(void) 336fc01f7e7Sbellard { 3377f06d47eSMarkus Armbruster BlockDriverState *bs = bdrv_new(); 338e4e9986bSMarkus Armbruster 339e4e9986bSMarkus Armbruster QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list); 340e4e9986bSMarkus Armbruster return bs; 341e4e9986bSMarkus Armbruster } 342e4e9986bSMarkus Armbruster 343e4e9986bSMarkus Armbruster BlockDriverState *bdrv_new(void) 344e4e9986bSMarkus Armbruster { 345e4e9986bSMarkus Armbruster BlockDriverState *bs; 346e4e9986bSMarkus Armbruster int i; 347e4e9986bSMarkus Armbruster 3485839e53bSMarkus Armbruster bs = g_new0(BlockDriverState, 1); 349e4654d2dSFam Zheng QLIST_INIT(&bs->dirty_bitmaps); 350fbe40ff7SFam Zheng for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { 351fbe40ff7SFam Zheng QLIST_INIT(&bs->op_blockers[i]); 352fbe40ff7SFam Zheng } 35328a7282aSLuiz Capitulino bdrv_iostatus_disable(bs); 354d7d512f6SPaolo Bonzini notifier_list_init(&bs->close_notifiers); 355d616b224SStefan Hajnoczi notifier_with_return_list_init(&bs->before_write_notifiers); 356cc0681c4SBenoît Canet qemu_co_queue_init(&bs->throttled_reqs[0]); 357cc0681c4SBenoît Canet qemu_co_queue_init(&bs->throttled_reqs[1]); 3589fcb0251SFam Zheng bs->refcnt = 1; 359dcd04228SStefan Hajnoczi bs->aio_context = qemu_get_aio_context(); 360d7d512f6SPaolo Bonzini 361b338082bSbellard return bs; 362b338082bSbellard } 363b338082bSbellard 364d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify) 365d7d512f6SPaolo Bonzini { 366d7d512f6SPaolo Bonzini notifier_list_add(&bs->close_notifiers, notify); 367d7d512f6SPaolo Bonzini } 368d7d512f6SPaolo Bonzini 369ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name) 370ea2384d3Sbellard { 371ea2384d3Sbellard BlockDriver *drv1; 3728a22f02aSStefan Hajnoczi QLIST_FOREACH(drv1, &bdrv_drivers, list) { 3738a22f02aSStefan Hajnoczi if (!strcmp(drv1->format_name, format_name)) { 374ea2384d3Sbellard return drv1; 375ea2384d3Sbellard } 3768a22f02aSStefan Hajnoczi } 377ea2384d3Sbellard return NULL; 378ea2384d3Sbellard } 379ea2384d3Sbellard 380b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only) 381eb852011SMarkus Armbruster { 382b64ec4e4SFam Zheng static const char *whitelist_rw[] = { 383b64ec4e4SFam Zheng CONFIG_BDRV_RW_WHITELIST 384b64ec4e4SFam Zheng }; 385b64ec4e4SFam Zheng static const char *whitelist_ro[] = { 386b64ec4e4SFam Zheng CONFIG_BDRV_RO_WHITELIST 387eb852011SMarkus Armbruster }; 388eb852011SMarkus Armbruster const char **p; 389eb852011SMarkus Armbruster 390b64ec4e4SFam Zheng if (!whitelist_rw[0] && !whitelist_ro[0]) { 391eb852011SMarkus Armbruster return 1; /* no whitelist, anything goes */ 392b64ec4e4SFam Zheng } 393eb852011SMarkus Armbruster 394b64ec4e4SFam Zheng for (p = whitelist_rw; *p; p++) { 395eb852011SMarkus Armbruster if (!strcmp(drv->format_name, *p)) { 396eb852011SMarkus Armbruster return 1; 397eb852011SMarkus Armbruster } 398eb852011SMarkus Armbruster } 399b64ec4e4SFam Zheng if (read_only) { 400b64ec4e4SFam Zheng for (p = whitelist_ro; *p; p++) { 401b64ec4e4SFam Zheng if (!strcmp(drv->format_name, *p)) { 402b64ec4e4SFam Zheng return 1; 403b64ec4e4SFam Zheng } 404b64ec4e4SFam Zheng } 405b64ec4e4SFam Zheng } 406eb852011SMarkus Armbruster return 0; 407eb852011SMarkus Armbruster } 408eb852011SMarkus Armbruster 409b64ec4e4SFam Zheng BlockDriver *bdrv_find_whitelisted_format(const char *format_name, 410b64ec4e4SFam Zheng bool read_only) 411eb852011SMarkus Armbruster { 412eb852011SMarkus Armbruster BlockDriver *drv = bdrv_find_format(format_name); 413b64ec4e4SFam Zheng return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL; 414eb852011SMarkus Armbruster } 415eb852011SMarkus Armbruster 4165b7e1542SZhi Yong Wu typedef struct CreateCo { 4175b7e1542SZhi Yong Wu BlockDriver *drv; 4185b7e1542SZhi Yong Wu char *filename; 41983d0521aSChunyan Liu QemuOpts *opts; 4205b7e1542SZhi Yong Wu int ret; 421cc84d90fSMax Reitz Error *err; 4225b7e1542SZhi Yong Wu } CreateCo; 4235b7e1542SZhi Yong Wu 4245b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque) 4255b7e1542SZhi Yong Wu { 426cc84d90fSMax Reitz Error *local_err = NULL; 427cc84d90fSMax Reitz int ret; 428cc84d90fSMax Reitz 4295b7e1542SZhi Yong Wu CreateCo *cco = opaque; 4305b7e1542SZhi Yong Wu assert(cco->drv); 4315b7e1542SZhi Yong Wu 432c282e1fdSChunyan Liu ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err); 43384d18f06SMarkus Armbruster if (local_err) { 434cc84d90fSMax Reitz error_propagate(&cco->err, local_err); 435cc84d90fSMax Reitz } 436cc84d90fSMax Reitz cco->ret = ret; 4375b7e1542SZhi Yong Wu } 4385b7e1542SZhi Yong Wu 4390e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename, 44083d0521aSChunyan Liu QemuOpts *opts, Error **errp) 441ea2384d3Sbellard { 4425b7e1542SZhi Yong Wu int ret; 4430e7e1989SKevin Wolf 4445b7e1542SZhi Yong Wu Coroutine *co; 4455b7e1542SZhi Yong Wu CreateCo cco = { 4465b7e1542SZhi Yong Wu .drv = drv, 4475b7e1542SZhi Yong Wu .filename = g_strdup(filename), 44883d0521aSChunyan Liu .opts = opts, 4495b7e1542SZhi Yong Wu .ret = NOT_DONE, 450cc84d90fSMax Reitz .err = NULL, 4515b7e1542SZhi Yong Wu }; 4525b7e1542SZhi Yong Wu 453c282e1fdSChunyan Liu if (!drv->bdrv_create) { 454cc84d90fSMax Reitz error_setg(errp, "Driver '%s' does not support image creation", drv->format_name); 45580168bffSLuiz Capitulino ret = -ENOTSUP; 45680168bffSLuiz Capitulino goto out; 4575b7e1542SZhi Yong Wu } 4585b7e1542SZhi Yong Wu 4595b7e1542SZhi Yong Wu if (qemu_in_coroutine()) { 4605b7e1542SZhi Yong Wu /* Fast-path if already in coroutine context */ 4615b7e1542SZhi Yong Wu bdrv_create_co_entry(&cco); 4625b7e1542SZhi Yong Wu } else { 4635b7e1542SZhi Yong Wu co = qemu_coroutine_create(bdrv_create_co_entry); 4645b7e1542SZhi Yong Wu qemu_coroutine_enter(co, &cco); 4655b7e1542SZhi Yong Wu while (cco.ret == NOT_DONE) { 466b47ec2c4SPaolo Bonzini aio_poll(qemu_get_aio_context(), true); 4675b7e1542SZhi Yong Wu } 4685b7e1542SZhi Yong Wu } 4695b7e1542SZhi Yong Wu 4705b7e1542SZhi Yong Wu ret = cco.ret; 471cc84d90fSMax Reitz if (ret < 0) { 47284d18f06SMarkus Armbruster if (cco.err) { 473cc84d90fSMax Reitz error_propagate(errp, cco.err); 474cc84d90fSMax Reitz } else { 475cc84d90fSMax Reitz error_setg_errno(errp, -ret, "Could not create image"); 476cc84d90fSMax Reitz } 477cc84d90fSMax Reitz } 4785b7e1542SZhi Yong Wu 47980168bffSLuiz Capitulino out: 48080168bffSLuiz Capitulino g_free(cco.filename); 4815b7e1542SZhi Yong Wu return ret; 482ea2384d3Sbellard } 483ea2384d3Sbellard 484c282e1fdSChunyan Liu int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp) 48584a12e66SChristoph Hellwig { 48684a12e66SChristoph Hellwig BlockDriver *drv; 487cc84d90fSMax Reitz Error *local_err = NULL; 488cc84d90fSMax Reitz int ret; 48984a12e66SChristoph Hellwig 49098289620SKevin Wolf drv = bdrv_find_protocol(filename, true); 49184a12e66SChristoph Hellwig if (drv == NULL) { 492cc84d90fSMax Reitz error_setg(errp, "Could not find protocol for file '%s'", filename); 49316905d71SStefan Hajnoczi return -ENOENT; 49484a12e66SChristoph Hellwig } 49584a12e66SChristoph Hellwig 496c282e1fdSChunyan Liu ret = bdrv_create(drv, filename, opts, &local_err); 49784d18f06SMarkus Armbruster if (local_err) { 498cc84d90fSMax Reitz error_propagate(errp, local_err); 499cc84d90fSMax Reitz } 500cc84d90fSMax Reitz return ret; 50184a12e66SChristoph Hellwig } 50284a12e66SChristoph Hellwig 5033baca891SKevin Wolf void bdrv_refresh_limits(BlockDriverState *bs, Error **errp) 504d34682cdSKevin Wolf { 505d34682cdSKevin Wolf BlockDriver *drv = bs->drv; 5063baca891SKevin Wolf Error *local_err = NULL; 507d34682cdSKevin Wolf 508d34682cdSKevin Wolf memset(&bs->bl, 0, sizeof(bs->bl)); 509d34682cdSKevin Wolf 510466ad822SKevin Wolf if (!drv) { 5113baca891SKevin Wolf return; 512466ad822SKevin Wolf } 513466ad822SKevin Wolf 514466ad822SKevin Wolf /* Take some limits from the children as a default */ 515466ad822SKevin Wolf if (bs->file) { 5163baca891SKevin Wolf bdrv_refresh_limits(bs->file, &local_err); 5173baca891SKevin Wolf if (local_err) { 5183baca891SKevin Wolf error_propagate(errp, local_err); 5193baca891SKevin Wolf return; 5203baca891SKevin Wolf } 521466ad822SKevin Wolf bs->bl.opt_transfer_length = bs->file->bl.opt_transfer_length; 5222647fab5SPeter Lieven bs->bl.max_transfer_length = bs->file->bl.max_transfer_length; 523339064d5SKevin Wolf bs->bl.opt_mem_alignment = bs->file->bl.opt_mem_alignment; 524339064d5SKevin Wolf } else { 525339064d5SKevin Wolf bs->bl.opt_mem_alignment = 512; 526466ad822SKevin Wolf } 527466ad822SKevin Wolf 528466ad822SKevin Wolf if (bs->backing_hd) { 5293baca891SKevin Wolf bdrv_refresh_limits(bs->backing_hd, &local_err); 5303baca891SKevin Wolf if (local_err) { 5313baca891SKevin Wolf error_propagate(errp, local_err); 5323baca891SKevin Wolf return; 5333baca891SKevin Wolf } 534466ad822SKevin Wolf bs->bl.opt_transfer_length = 535466ad822SKevin Wolf MAX(bs->bl.opt_transfer_length, 536466ad822SKevin Wolf bs->backing_hd->bl.opt_transfer_length); 5372647fab5SPeter Lieven bs->bl.max_transfer_length = 5382647fab5SPeter Lieven MIN_NON_ZERO(bs->bl.max_transfer_length, 5392647fab5SPeter Lieven bs->backing_hd->bl.max_transfer_length); 540339064d5SKevin Wolf bs->bl.opt_mem_alignment = 541339064d5SKevin Wolf MAX(bs->bl.opt_mem_alignment, 542339064d5SKevin Wolf bs->backing_hd->bl.opt_mem_alignment); 543466ad822SKevin Wolf } 544466ad822SKevin Wolf 545466ad822SKevin Wolf /* Then let the driver override it */ 546466ad822SKevin Wolf if (drv->bdrv_refresh_limits) { 5473baca891SKevin Wolf drv->bdrv_refresh_limits(bs, errp); 548d34682cdSKevin Wolf } 549d34682cdSKevin Wolf } 550d34682cdSKevin Wolf 551eba25057SJim Meyering /* 552eba25057SJim Meyering * Create a uniquely-named empty temporary file. 553eba25057SJim Meyering * Return 0 upon success, otherwise a negative errno value. 554eba25057SJim Meyering */ 555eba25057SJim Meyering int get_tmp_filename(char *filename, int size) 556eba25057SJim Meyering { 557d5249393Sbellard #ifdef _WIN32 5583b9f94e1Sbellard char temp_dir[MAX_PATH]; 559eba25057SJim Meyering /* GetTempFileName requires that its output buffer (4th param) 560eba25057SJim Meyering have length MAX_PATH or greater. */ 561eba25057SJim Meyering assert(size >= MAX_PATH); 562eba25057SJim Meyering return (GetTempPath(MAX_PATH, temp_dir) 563eba25057SJim Meyering && GetTempFileName(temp_dir, "qem", 0, filename) 564eba25057SJim Meyering ? 0 : -GetLastError()); 565d5249393Sbellard #else 566ea2384d3Sbellard int fd; 5677ccfb2ebSblueswir1 const char *tmpdir; 5680badc1eeSaurel32 tmpdir = getenv("TMPDIR"); 56969bef793SAmit Shah if (!tmpdir) { 57069bef793SAmit Shah tmpdir = "/var/tmp"; 57169bef793SAmit Shah } 572eba25057SJim Meyering if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) { 573eba25057SJim Meyering return -EOVERFLOW; 574ea2384d3Sbellard } 575eba25057SJim Meyering fd = mkstemp(filename); 576fe235a06SDunrong Huang if (fd < 0) { 577fe235a06SDunrong Huang return -errno; 578fe235a06SDunrong Huang } 579fe235a06SDunrong Huang if (close(fd) != 0) { 580fe235a06SDunrong Huang unlink(filename); 581eba25057SJim Meyering return -errno; 582eba25057SJim Meyering } 583eba25057SJim Meyering return 0; 584d5249393Sbellard #endif 585eba25057SJim Meyering } 586ea2384d3Sbellard 587f3a5d3f8SChristoph Hellwig /* 588f3a5d3f8SChristoph Hellwig * Detect host devices. By convention, /dev/cdrom[N] is always 589f3a5d3f8SChristoph Hellwig * recognized as a host CDROM. 590f3a5d3f8SChristoph Hellwig */ 591f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename) 592f3a5d3f8SChristoph Hellwig { 593508c7cb3SChristoph Hellwig int score_max = 0, score; 594508c7cb3SChristoph Hellwig BlockDriver *drv = NULL, *d; 595f3a5d3f8SChristoph Hellwig 5968a22f02aSStefan Hajnoczi QLIST_FOREACH(d, &bdrv_drivers, list) { 597508c7cb3SChristoph Hellwig if (d->bdrv_probe_device) { 598508c7cb3SChristoph Hellwig score = d->bdrv_probe_device(filename); 599508c7cb3SChristoph Hellwig if (score > score_max) { 600508c7cb3SChristoph Hellwig score_max = score; 601508c7cb3SChristoph Hellwig drv = d; 602f3a5d3f8SChristoph Hellwig } 603508c7cb3SChristoph Hellwig } 604f3a5d3f8SChristoph Hellwig } 605f3a5d3f8SChristoph Hellwig 606508c7cb3SChristoph Hellwig return drv; 607f3a5d3f8SChristoph Hellwig } 608f3a5d3f8SChristoph Hellwig 60998289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename, 61098289620SKevin Wolf bool allow_protocol_prefix) 61184a12e66SChristoph Hellwig { 61284a12e66SChristoph Hellwig BlockDriver *drv1; 61384a12e66SChristoph Hellwig char protocol[128]; 61484a12e66SChristoph Hellwig int len; 61584a12e66SChristoph Hellwig const char *p; 61684a12e66SChristoph Hellwig 61766f82ceeSKevin Wolf /* TODO Drivers without bdrv_file_open must be specified explicitly */ 61866f82ceeSKevin Wolf 61939508e7aSChristoph Hellwig /* 62039508e7aSChristoph Hellwig * XXX(hch): we really should not let host device detection 62139508e7aSChristoph Hellwig * override an explicit protocol specification, but moving this 62239508e7aSChristoph Hellwig * later breaks access to device names with colons in them. 62339508e7aSChristoph Hellwig * Thanks to the brain-dead persistent naming schemes on udev- 62439508e7aSChristoph Hellwig * based Linux systems those actually are quite common. 62539508e7aSChristoph Hellwig */ 62684a12e66SChristoph Hellwig drv1 = find_hdev_driver(filename); 62739508e7aSChristoph Hellwig if (drv1) { 62884a12e66SChristoph Hellwig return drv1; 62984a12e66SChristoph Hellwig } 63039508e7aSChristoph Hellwig 63198289620SKevin Wolf if (!path_has_protocol(filename) || !allow_protocol_prefix) { 63239508e7aSChristoph Hellwig return bdrv_find_format("file"); 63339508e7aSChristoph Hellwig } 63498289620SKevin Wolf 6359e0b22f4SStefan Hajnoczi p = strchr(filename, ':'); 6369e0b22f4SStefan Hajnoczi assert(p != NULL); 63784a12e66SChristoph Hellwig len = p - filename; 63884a12e66SChristoph Hellwig if (len > sizeof(protocol) - 1) 63984a12e66SChristoph Hellwig len = sizeof(protocol) - 1; 64084a12e66SChristoph Hellwig memcpy(protocol, filename, len); 64184a12e66SChristoph Hellwig protocol[len] = '\0'; 64284a12e66SChristoph Hellwig QLIST_FOREACH(drv1, &bdrv_drivers, list) { 64384a12e66SChristoph Hellwig if (drv1->protocol_name && 64484a12e66SChristoph Hellwig !strcmp(drv1->protocol_name, protocol)) { 64584a12e66SChristoph Hellwig return drv1; 64684a12e66SChristoph Hellwig } 64784a12e66SChristoph Hellwig } 64884a12e66SChristoph Hellwig return NULL; 64984a12e66SChristoph Hellwig } 65084a12e66SChristoph Hellwig 651c6684249SMarkus Armbruster /* 652c6684249SMarkus Armbruster * Guess image format by probing its contents. 653c6684249SMarkus Armbruster * This is not a good idea when your image is raw (CVE-2008-2004), but 654c6684249SMarkus Armbruster * we do it anyway for backward compatibility. 655c6684249SMarkus Armbruster * 656c6684249SMarkus Armbruster * @buf contains the image's first @buf_size bytes. 657*7cddd372SKevin Wolf * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE, 658*7cddd372SKevin Wolf * but can be smaller if the image file is smaller) 659c6684249SMarkus Armbruster * @filename is its filename. 660c6684249SMarkus Armbruster * 661c6684249SMarkus Armbruster * For all block drivers, call the bdrv_probe() method to get its 662c6684249SMarkus Armbruster * probing score. 663c6684249SMarkus Armbruster * Return the first block driver with the highest probing score. 664c6684249SMarkus Armbruster */ 665c6684249SMarkus Armbruster static BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size, 666c6684249SMarkus Armbruster const char *filename) 667c6684249SMarkus Armbruster { 668c6684249SMarkus Armbruster int score_max = 0, score; 669c6684249SMarkus Armbruster BlockDriver *drv = NULL, *d; 670c6684249SMarkus Armbruster 671c6684249SMarkus Armbruster QLIST_FOREACH(d, &bdrv_drivers, list) { 672c6684249SMarkus Armbruster if (d->bdrv_probe) { 673c6684249SMarkus Armbruster score = d->bdrv_probe(buf, buf_size, filename); 674c6684249SMarkus Armbruster if (score > score_max) { 675c6684249SMarkus Armbruster score_max = score; 676c6684249SMarkus Armbruster drv = d; 677c6684249SMarkus Armbruster } 678c6684249SMarkus Armbruster } 679c6684249SMarkus Armbruster } 680c6684249SMarkus Armbruster 681c6684249SMarkus Armbruster return drv; 682c6684249SMarkus Armbruster } 683c6684249SMarkus Armbruster 684f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename, 68534b5d2c6SMax Reitz BlockDriver **pdrv, Error **errp) 686ea2384d3Sbellard { 687c6684249SMarkus Armbruster BlockDriver *drv; 688*7cddd372SKevin Wolf uint8_t buf[BLOCK_PROBE_BUF_SIZE]; 689f500a6d3SKevin Wolf int ret = 0; 690f8ea0b00SNicholas Bellinger 69108a00559SKevin Wolf /* Return the raw BlockDriver * to scsi-generic devices or empty drives */ 6928e895599SPaolo Bonzini if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) { 693c98ac35dSStefan Weil drv = bdrv_find_format("raw"); 694c98ac35dSStefan Weil if (!drv) { 69534b5d2c6SMax Reitz error_setg(errp, "Could not find raw image format"); 696c98ac35dSStefan Weil ret = -ENOENT; 697c98ac35dSStefan Weil } 698c98ac35dSStefan Weil *pdrv = drv; 699c98ac35dSStefan Weil return ret; 7001a396859SNicholas A. Bellinger } 701f8ea0b00SNicholas Bellinger 70283f64091Sbellard ret = bdrv_pread(bs, 0, buf, sizeof(buf)); 703ea2384d3Sbellard if (ret < 0) { 70434b5d2c6SMax Reitz error_setg_errno(errp, -ret, "Could not read image for determining its " 70534b5d2c6SMax Reitz "format"); 706c98ac35dSStefan Weil *pdrv = NULL; 707c98ac35dSStefan Weil return ret; 708ea2384d3Sbellard } 709ea2384d3Sbellard 710c6684249SMarkus Armbruster drv = bdrv_probe_all(buf, ret, filename); 711c98ac35dSStefan Weil if (!drv) { 71234b5d2c6SMax Reitz error_setg(errp, "Could not determine image format: No compatible " 71334b5d2c6SMax Reitz "driver found"); 714c98ac35dSStefan Weil ret = -ENOENT; 715c98ac35dSStefan Weil } 716c98ac35dSStefan Weil *pdrv = drv; 717c98ac35dSStefan Weil return ret; 718ea2384d3Sbellard } 719ea2384d3Sbellard 72051762288SStefan Hajnoczi /** 72151762288SStefan Hajnoczi * Set the current 'total_sectors' value 72265a9bb25SMarkus Armbruster * Return 0 on success, -errno on error. 72351762288SStefan Hajnoczi */ 72451762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint) 72551762288SStefan Hajnoczi { 72651762288SStefan Hajnoczi BlockDriver *drv = bs->drv; 72751762288SStefan Hajnoczi 728396759adSNicholas Bellinger /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */ 729396759adSNicholas Bellinger if (bs->sg) 730396759adSNicholas Bellinger return 0; 731396759adSNicholas Bellinger 73251762288SStefan Hajnoczi /* query actual device if possible, otherwise just trust the hint */ 73351762288SStefan Hajnoczi if (drv->bdrv_getlength) { 73451762288SStefan Hajnoczi int64_t length = drv->bdrv_getlength(bs); 73551762288SStefan Hajnoczi if (length < 0) { 73651762288SStefan Hajnoczi return length; 73751762288SStefan Hajnoczi } 7387e382003SFam Zheng hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE); 73951762288SStefan Hajnoczi } 74051762288SStefan Hajnoczi 74151762288SStefan Hajnoczi bs->total_sectors = hint; 74251762288SStefan Hajnoczi return 0; 74351762288SStefan Hajnoczi } 74451762288SStefan Hajnoczi 745c3993cdcSStefan Hajnoczi /** 7469e8f1835SPaolo Bonzini * Set open flags for a given discard mode 7479e8f1835SPaolo Bonzini * 7489e8f1835SPaolo Bonzini * Return 0 on success, -1 if the discard mode was invalid. 7499e8f1835SPaolo Bonzini */ 7509e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags) 7519e8f1835SPaolo Bonzini { 7529e8f1835SPaolo Bonzini *flags &= ~BDRV_O_UNMAP; 7539e8f1835SPaolo Bonzini 7549e8f1835SPaolo Bonzini if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) { 7559e8f1835SPaolo Bonzini /* do nothing */ 7569e8f1835SPaolo Bonzini } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) { 7579e8f1835SPaolo Bonzini *flags |= BDRV_O_UNMAP; 7589e8f1835SPaolo Bonzini } else { 7599e8f1835SPaolo Bonzini return -1; 7609e8f1835SPaolo Bonzini } 7619e8f1835SPaolo Bonzini 7629e8f1835SPaolo Bonzini return 0; 7639e8f1835SPaolo Bonzini } 7649e8f1835SPaolo Bonzini 7659e8f1835SPaolo Bonzini /** 766c3993cdcSStefan Hajnoczi * Set open flags for a given cache mode 767c3993cdcSStefan Hajnoczi * 768c3993cdcSStefan Hajnoczi * Return 0 on success, -1 if the cache mode was invalid. 769c3993cdcSStefan Hajnoczi */ 770c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags) 771c3993cdcSStefan Hajnoczi { 772c3993cdcSStefan Hajnoczi *flags &= ~BDRV_O_CACHE_MASK; 773c3993cdcSStefan Hajnoczi 774c3993cdcSStefan Hajnoczi if (!strcmp(mode, "off") || !strcmp(mode, "none")) { 775c3993cdcSStefan Hajnoczi *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB; 77692196b2fSStefan Hajnoczi } else if (!strcmp(mode, "directsync")) { 77792196b2fSStefan Hajnoczi *flags |= BDRV_O_NOCACHE; 778c3993cdcSStefan Hajnoczi } else if (!strcmp(mode, "writeback")) { 779c3993cdcSStefan Hajnoczi *flags |= BDRV_O_CACHE_WB; 780c3993cdcSStefan Hajnoczi } else if (!strcmp(mode, "unsafe")) { 781c3993cdcSStefan Hajnoczi *flags |= BDRV_O_CACHE_WB; 782c3993cdcSStefan Hajnoczi *flags |= BDRV_O_NO_FLUSH; 783c3993cdcSStefan Hajnoczi } else if (!strcmp(mode, "writethrough")) { 784c3993cdcSStefan Hajnoczi /* this is the default */ 785c3993cdcSStefan Hajnoczi } else { 786c3993cdcSStefan Hajnoczi return -1; 787c3993cdcSStefan Hajnoczi } 788c3993cdcSStefan Hajnoczi 789c3993cdcSStefan Hajnoczi return 0; 790c3993cdcSStefan Hajnoczi } 791c3993cdcSStefan Hajnoczi 79253fec9d3SStefan Hajnoczi /** 79353fec9d3SStefan Hajnoczi * The copy-on-read flag is actually a reference count so multiple users may 79453fec9d3SStefan Hajnoczi * use the feature without worrying about clobbering its previous state. 79553fec9d3SStefan Hajnoczi * Copy-on-read stays enabled until all users have called to disable it. 79653fec9d3SStefan Hajnoczi */ 79753fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs) 79853fec9d3SStefan Hajnoczi { 79953fec9d3SStefan Hajnoczi bs->copy_on_read++; 80053fec9d3SStefan Hajnoczi } 80153fec9d3SStefan Hajnoczi 80253fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs) 80353fec9d3SStefan Hajnoczi { 80453fec9d3SStefan Hajnoczi assert(bs->copy_on_read > 0); 80553fec9d3SStefan Hajnoczi bs->copy_on_read--; 80653fec9d3SStefan Hajnoczi } 80753fec9d3SStefan Hajnoczi 8080b50cc88SKevin Wolf /* 809b1e6fc08SKevin Wolf * Returns the flags that a temporary snapshot should get, based on the 810b1e6fc08SKevin Wolf * originally requested flags (the originally requested image will have flags 811b1e6fc08SKevin Wolf * like a backing file) 812b1e6fc08SKevin Wolf */ 813b1e6fc08SKevin Wolf static int bdrv_temp_snapshot_flags(int flags) 814b1e6fc08SKevin Wolf { 815b1e6fc08SKevin Wolf return (flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY; 816b1e6fc08SKevin Wolf } 817b1e6fc08SKevin Wolf 818b1e6fc08SKevin Wolf /* 8190b50cc88SKevin Wolf * Returns the flags that bs->file should get, based on the given flags for 8200b50cc88SKevin Wolf * the parent BDS 8210b50cc88SKevin Wolf */ 8220b50cc88SKevin Wolf static int bdrv_inherited_flags(int flags) 8230b50cc88SKevin Wolf { 8240b50cc88SKevin Wolf /* Enable protocol handling, disable format probing for bs->file */ 8250b50cc88SKevin Wolf flags |= BDRV_O_PROTOCOL; 8260b50cc88SKevin Wolf 8270b50cc88SKevin Wolf /* Our block drivers take care to send flushes and respect unmap policy, 8280b50cc88SKevin Wolf * so we can enable both unconditionally on lower layers. */ 8290b50cc88SKevin Wolf flags |= BDRV_O_CACHE_WB | BDRV_O_UNMAP; 8300b50cc88SKevin Wolf 8310b50cc88SKevin Wolf /* Clear flags that only apply to the top layer */ 8325669b44dSKevin Wolf flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ); 8330b50cc88SKevin Wolf 8340b50cc88SKevin Wolf return flags; 8350b50cc88SKevin Wolf } 8360b50cc88SKevin Wolf 837317fc44eSKevin Wolf /* 838317fc44eSKevin Wolf * Returns the flags that bs->backing_hd should get, based on the given flags 839317fc44eSKevin Wolf * for the parent BDS 840317fc44eSKevin Wolf */ 841317fc44eSKevin Wolf static int bdrv_backing_flags(int flags) 842317fc44eSKevin Wolf { 843317fc44eSKevin Wolf /* backing files always opened read-only */ 844317fc44eSKevin Wolf flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ); 845317fc44eSKevin Wolf 846317fc44eSKevin Wolf /* snapshot=on is handled on the top layer */ 8478bfea15dSKevin Wolf flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY); 848317fc44eSKevin Wolf 849317fc44eSKevin Wolf return flags; 850317fc44eSKevin Wolf } 851317fc44eSKevin Wolf 8527b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags) 8537b272452SKevin Wolf { 8547b272452SKevin Wolf int open_flags = flags | BDRV_O_CACHE_WB; 8557b272452SKevin Wolf 8567b272452SKevin Wolf /* 8577b272452SKevin Wolf * Clear flags that are internal to the block layer before opening the 8587b272452SKevin Wolf * image. 8597b272452SKevin Wolf */ 86020cca275SKevin Wolf open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL); 8617b272452SKevin Wolf 8627b272452SKevin Wolf /* 8637b272452SKevin Wolf * Snapshots should be writable. 8647b272452SKevin Wolf */ 8658bfea15dSKevin Wolf if (flags & BDRV_O_TEMPORARY) { 8667b272452SKevin Wolf open_flags |= BDRV_O_RDWR; 8677b272452SKevin Wolf } 8687b272452SKevin Wolf 8697b272452SKevin Wolf return open_flags; 8707b272452SKevin Wolf } 8717b272452SKevin Wolf 872636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs, 8736913c0c2SBenoît Canet const char *node_name, 8746913c0c2SBenoît Canet Error **errp) 8756913c0c2SBenoît Canet { 8766913c0c2SBenoît Canet if (!node_name) { 877636ea370SKevin Wolf return; 8786913c0c2SBenoît Canet } 8796913c0c2SBenoît Canet 8809aebf3b8SKevin Wolf /* Check for empty string or invalid characters */ 881f5bebbbbSMarkus Armbruster if (!id_wellformed(node_name)) { 8829aebf3b8SKevin Wolf error_setg(errp, "Invalid node name"); 883636ea370SKevin Wolf return; 8846913c0c2SBenoît Canet } 8856913c0c2SBenoît Canet 8860c5e94eeSBenoît Canet /* takes care of avoiding namespaces collisions */ 8877f06d47eSMarkus Armbruster if (blk_by_name(node_name)) { 8880c5e94eeSBenoît Canet error_setg(errp, "node-name=%s is conflicting with a device id", 8890c5e94eeSBenoît Canet node_name); 890636ea370SKevin Wolf return; 8910c5e94eeSBenoît Canet } 8920c5e94eeSBenoît Canet 8936913c0c2SBenoît Canet /* takes care of avoiding duplicates node names */ 8946913c0c2SBenoît Canet if (bdrv_find_node(node_name)) { 8956913c0c2SBenoît Canet error_setg(errp, "Duplicate node name"); 896636ea370SKevin Wolf return; 8976913c0c2SBenoît Canet } 8986913c0c2SBenoît Canet 8996913c0c2SBenoît Canet /* copy node name into the bs and insert it into the graph list */ 9006913c0c2SBenoît Canet pstrcpy(bs->node_name, sizeof(bs->node_name), node_name); 9016913c0c2SBenoît Canet QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list); 9026913c0c2SBenoît Canet } 9036913c0c2SBenoît Canet 904b6ce07aaSKevin Wolf /* 90557915332SKevin Wolf * Common part for opening disk images and files 906b6ad491aSKevin Wolf * 907b6ad491aSKevin Wolf * Removes all processed options from *options. 90857915332SKevin Wolf */ 909f500a6d3SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file, 91034b5d2c6SMax Reitz QDict *options, int flags, BlockDriver *drv, Error **errp) 91157915332SKevin Wolf { 91257915332SKevin Wolf int ret, open_flags; 913035fccdfSKevin Wolf const char *filename; 9146913c0c2SBenoît Canet const char *node_name = NULL; 91534b5d2c6SMax Reitz Error *local_err = NULL; 91657915332SKevin Wolf 91757915332SKevin Wolf assert(drv != NULL); 9186405875cSPaolo Bonzini assert(bs->file == NULL); 919707ff828SKevin Wolf assert(options != NULL && bs->options != options); 92057915332SKevin Wolf 92145673671SKevin Wolf if (file != NULL) { 92245673671SKevin Wolf filename = file->filename; 92345673671SKevin Wolf } else { 92445673671SKevin Wolf filename = qdict_get_try_str(options, "filename"); 92545673671SKevin Wolf } 92645673671SKevin Wolf 927765003dbSKevin Wolf if (drv->bdrv_needs_filename && !filename) { 928765003dbSKevin Wolf error_setg(errp, "The '%s' block driver requires a file name", 929765003dbSKevin Wolf drv->format_name); 930765003dbSKevin Wolf return -EINVAL; 931765003dbSKevin Wolf } 932765003dbSKevin Wolf 93345673671SKevin Wolf trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name); 93428dcee10SStefan Hajnoczi 9356913c0c2SBenoît Canet node_name = qdict_get_try_str(options, "node-name"); 936636ea370SKevin Wolf bdrv_assign_node_name(bs, node_name, &local_err); 9370fb6395cSMarkus Armbruster if (local_err) { 938636ea370SKevin Wolf error_propagate(errp, local_err); 939636ea370SKevin Wolf return -EINVAL; 9406913c0c2SBenoît Canet } 9416913c0c2SBenoît Canet qdict_del(options, "node-name"); 9426913c0c2SBenoît Canet 9435d186eb0SKevin Wolf /* bdrv_open() with directly using a protocol as drv. This layer is already 9445d186eb0SKevin Wolf * opened, so assign it to bs (while file becomes a closed BlockDriverState) 9455d186eb0SKevin Wolf * and return immediately. */ 9465d186eb0SKevin Wolf if (file != NULL && drv->bdrv_file_open) { 9475d186eb0SKevin Wolf bdrv_swap(file, bs); 9485d186eb0SKevin Wolf return 0; 9495d186eb0SKevin Wolf } 9505d186eb0SKevin Wolf 95157915332SKevin Wolf bs->open_flags = flags; 9521b7fd729SPaolo Bonzini bs->guest_block_size = 512; 953c25f53b0SPaolo Bonzini bs->request_alignment = 512; 9540d51b4deSAsias He bs->zero_beyond_eof = true; 955b64ec4e4SFam Zheng open_flags = bdrv_open_flags(bs, flags); 956b64ec4e4SFam Zheng bs->read_only = !(open_flags & BDRV_O_RDWR); 95720cca275SKevin Wolf bs->growable = !!(flags & BDRV_O_PROTOCOL); 958b64ec4e4SFam Zheng 959b64ec4e4SFam Zheng if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) { 9608f94a6e4SKevin Wolf error_setg(errp, 9618f94a6e4SKevin Wolf !bs->read_only && bdrv_is_whitelisted(drv, true) 9628f94a6e4SKevin Wolf ? "Driver '%s' can only be used for read-only devices" 9638f94a6e4SKevin Wolf : "Driver '%s' is not whitelisted", 9648f94a6e4SKevin Wolf drv->format_name); 965b64ec4e4SFam Zheng return -ENOTSUP; 966b64ec4e4SFam Zheng } 96757915332SKevin Wolf 96853fec9d3SStefan Hajnoczi assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */ 9690ebd24e0SKevin Wolf if (flags & BDRV_O_COPY_ON_READ) { 9700ebd24e0SKevin Wolf if (!bs->read_only) { 97153fec9d3SStefan Hajnoczi bdrv_enable_copy_on_read(bs); 9720ebd24e0SKevin Wolf } else { 9730ebd24e0SKevin Wolf error_setg(errp, "Can't use copy-on-read on read-only device"); 9740ebd24e0SKevin Wolf return -EINVAL; 9750ebd24e0SKevin Wolf } 97653fec9d3SStefan Hajnoczi } 97753fec9d3SStefan Hajnoczi 978c2ad1b0cSKevin Wolf if (filename != NULL) { 97957915332SKevin Wolf pstrcpy(bs->filename, sizeof(bs->filename), filename); 980c2ad1b0cSKevin Wolf } else { 981c2ad1b0cSKevin Wolf bs->filename[0] = '\0'; 982c2ad1b0cSKevin Wolf } 98391af7014SMax Reitz pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename); 98457915332SKevin Wolf 98557915332SKevin Wolf bs->drv = drv; 9867267c094SAnthony Liguori bs->opaque = g_malloc0(drv->instance_size); 98757915332SKevin Wolf 98803f541bdSStefan Hajnoczi bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB); 989e7c63796SStefan Hajnoczi 99066f82ceeSKevin Wolf /* Open the image, either directly or using a protocol */ 99166f82ceeSKevin Wolf if (drv->bdrv_file_open) { 9925d186eb0SKevin Wolf assert(file == NULL); 993030be321SBenoît Canet assert(!drv->bdrv_needs_filename || filename != NULL); 99434b5d2c6SMax Reitz ret = drv->bdrv_file_open(bs, options, open_flags, &local_err); 995f500a6d3SKevin Wolf } else { 9962af5ef70SKevin Wolf if (file == NULL) { 99734b5d2c6SMax Reitz error_setg(errp, "Can't use '%s' as a block driver for the " 99834b5d2c6SMax Reitz "protocol level", drv->format_name); 9992af5ef70SKevin Wolf ret = -EINVAL; 10002af5ef70SKevin Wolf goto free_and_fail; 10012af5ef70SKevin Wolf } 1002f500a6d3SKevin Wolf bs->file = file; 100334b5d2c6SMax Reitz ret = drv->bdrv_open(bs, options, open_flags, &local_err); 100466f82ceeSKevin Wolf } 100566f82ceeSKevin Wolf 100657915332SKevin Wolf if (ret < 0) { 100784d18f06SMarkus Armbruster if (local_err) { 100834b5d2c6SMax Reitz error_propagate(errp, local_err); 10092fa9aa59SDunrong Huang } else if (bs->filename[0]) { 10102fa9aa59SDunrong Huang error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename); 101134b5d2c6SMax Reitz } else { 101234b5d2c6SMax Reitz error_setg_errno(errp, -ret, "Could not open image"); 101334b5d2c6SMax Reitz } 101457915332SKevin Wolf goto free_and_fail; 101557915332SKevin Wolf } 101657915332SKevin Wolf 101751762288SStefan Hajnoczi ret = refresh_total_sectors(bs, bs->total_sectors); 101851762288SStefan Hajnoczi if (ret < 0) { 101934b5d2c6SMax Reitz error_setg_errno(errp, -ret, "Could not refresh total sector count"); 102051762288SStefan Hajnoczi goto free_and_fail; 102157915332SKevin Wolf } 102251762288SStefan Hajnoczi 10233baca891SKevin Wolf bdrv_refresh_limits(bs, &local_err); 10243baca891SKevin Wolf if (local_err) { 10253baca891SKevin Wolf error_propagate(errp, local_err); 10263baca891SKevin Wolf ret = -EINVAL; 10273baca891SKevin Wolf goto free_and_fail; 10283baca891SKevin Wolf } 10293baca891SKevin Wolf 1030c25f53b0SPaolo Bonzini assert(bdrv_opt_mem_align(bs) != 0); 103147ea2de2SKevin Wolf assert((bs->request_alignment != 0) || bs->sg); 103257915332SKevin Wolf return 0; 103357915332SKevin Wolf 103457915332SKevin Wolf free_and_fail: 103566f82ceeSKevin Wolf bs->file = NULL; 10367267c094SAnthony Liguori g_free(bs->opaque); 103757915332SKevin Wolf bs->opaque = NULL; 103857915332SKevin Wolf bs->drv = NULL; 103957915332SKevin Wolf return ret; 104057915332SKevin Wolf } 104157915332SKevin Wolf 10425e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp) 10435e5c4f63SKevin Wolf { 10445e5c4f63SKevin Wolf QObject *options_obj; 10455e5c4f63SKevin Wolf QDict *options; 10465e5c4f63SKevin Wolf int ret; 10475e5c4f63SKevin Wolf 10485e5c4f63SKevin Wolf ret = strstart(filename, "json:", &filename); 10495e5c4f63SKevin Wolf assert(ret); 10505e5c4f63SKevin Wolf 10515e5c4f63SKevin Wolf options_obj = qobject_from_json(filename); 10525e5c4f63SKevin Wolf if (!options_obj) { 10535e5c4f63SKevin Wolf error_setg(errp, "Could not parse the JSON options"); 10545e5c4f63SKevin Wolf return NULL; 10555e5c4f63SKevin Wolf } 10565e5c4f63SKevin Wolf 10575e5c4f63SKevin Wolf if (qobject_type(options_obj) != QTYPE_QDICT) { 10585e5c4f63SKevin Wolf qobject_decref(options_obj); 10595e5c4f63SKevin Wolf error_setg(errp, "Invalid JSON object given"); 10605e5c4f63SKevin Wolf return NULL; 10615e5c4f63SKevin Wolf } 10625e5c4f63SKevin Wolf 10635e5c4f63SKevin Wolf options = qobject_to_qdict(options_obj); 10645e5c4f63SKevin Wolf qdict_flatten(options); 10655e5c4f63SKevin Wolf 10665e5c4f63SKevin Wolf return options; 10675e5c4f63SKevin Wolf } 10685e5c4f63SKevin Wolf 106957915332SKevin Wolf /* 1070f54120ffSKevin Wolf * Fills in default options for opening images and converts the legacy 1071f54120ffSKevin Wolf * filename/flags pair to option QDict entries. 1072f54120ffSKevin Wolf */ 10735e5c4f63SKevin Wolf static int bdrv_fill_options(QDict **options, const char **pfilename, int flags, 107417b005f1SKevin Wolf BlockDriver *drv, Error **errp) 1075f54120ffSKevin Wolf { 10765e5c4f63SKevin Wolf const char *filename = *pfilename; 1077f54120ffSKevin Wolf const char *drvname; 1078462f5bcfSKevin Wolf bool protocol = flags & BDRV_O_PROTOCOL; 1079f54120ffSKevin Wolf bool parse_filename = false; 1080f54120ffSKevin Wolf Error *local_err = NULL; 1081f54120ffSKevin Wolf 10825e5c4f63SKevin Wolf /* Parse json: pseudo-protocol */ 10835e5c4f63SKevin Wolf if (filename && g_str_has_prefix(filename, "json:")) { 10845e5c4f63SKevin Wolf QDict *json_options = parse_json_filename(filename, &local_err); 10855e5c4f63SKevin Wolf if (local_err) { 10865e5c4f63SKevin Wolf error_propagate(errp, local_err); 10875e5c4f63SKevin Wolf return -EINVAL; 10885e5c4f63SKevin Wolf } 10895e5c4f63SKevin Wolf 10905e5c4f63SKevin Wolf /* Options given in the filename have lower priority than options 10915e5c4f63SKevin Wolf * specified directly */ 10925e5c4f63SKevin Wolf qdict_join(*options, json_options, false); 10935e5c4f63SKevin Wolf QDECREF(json_options); 10945e5c4f63SKevin Wolf *pfilename = filename = NULL; 10955e5c4f63SKevin Wolf } 10965e5c4f63SKevin Wolf 1097f54120ffSKevin Wolf /* Fetch the file name from the options QDict if necessary */ 109817b005f1SKevin Wolf if (protocol && filename) { 1099f54120ffSKevin Wolf if (!qdict_haskey(*options, "filename")) { 1100f54120ffSKevin Wolf qdict_put(*options, "filename", qstring_from_str(filename)); 1101f54120ffSKevin Wolf parse_filename = true; 1102f54120ffSKevin Wolf } else { 1103f54120ffSKevin Wolf error_setg(errp, "Can't specify 'file' and 'filename' options at " 1104f54120ffSKevin Wolf "the same time"); 1105f54120ffSKevin Wolf return -EINVAL; 1106f54120ffSKevin Wolf } 1107f54120ffSKevin Wolf } 1108f54120ffSKevin Wolf 1109f54120ffSKevin Wolf /* Find the right block driver */ 1110f54120ffSKevin Wolf filename = qdict_get_try_str(*options, "filename"); 1111f54120ffSKevin Wolf drvname = qdict_get_try_str(*options, "driver"); 1112f54120ffSKevin Wolf 111317b005f1SKevin Wolf if (drv) { 111417b005f1SKevin Wolf if (drvname) { 111517b005f1SKevin Wolf error_setg(errp, "Driver specified twice"); 111617b005f1SKevin Wolf return -EINVAL; 111717b005f1SKevin Wolf } 111817b005f1SKevin Wolf drvname = drv->format_name; 111917b005f1SKevin Wolf qdict_put(*options, "driver", qstring_from_str(drvname)); 112017b005f1SKevin Wolf } else { 112117b005f1SKevin Wolf if (!drvname && protocol) { 1122f54120ffSKevin Wolf if (filename) { 1123f54120ffSKevin Wolf drv = bdrv_find_protocol(filename, parse_filename); 1124f54120ffSKevin Wolf if (!drv) { 1125f54120ffSKevin Wolf error_setg(errp, "Unknown protocol"); 1126f54120ffSKevin Wolf return -EINVAL; 1127f54120ffSKevin Wolf } 1128f54120ffSKevin Wolf 1129f54120ffSKevin Wolf drvname = drv->format_name; 1130f54120ffSKevin Wolf qdict_put(*options, "driver", qstring_from_str(drvname)); 1131f54120ffSKevin Wolf } else { 1132f54120ffSKevin Wolf error_setg(errp, "Must specify either driver or file"); 1133f54120ffSKevin Wolf return -EINVAL; 1134f54120ffSKevin Wolf } 113517b005f1SKevin Wolf } else if (drvname) { 1136f54120ffSKevin Wolf drv = bdrv_find_format(drvname); 1137f54120ffSKevin Wolf if (!drv) { 1138f54120ffSKevin Wolf error_setg(errp, "Unknown driver '%s'", drvname); 1139f54120ffSKevin Wolf return -ENOENT; 1140f54120ffSKevin Wolf } 114117b005f1SKevin Wolf } 114217b005f1SKevin Wolf } 114317b005f1SKevin Wolf 114417b005f1SKevin Wolf assert(drv || !protocol); 1145f54120ffSKevin Wolf 1146f54120ffSKevin Wolf /* Driver-specific filename parsing */ 114717b005f1SKevin Wolf if (drv && drv->bdrv_parse_filename && parse_filename) { 1148f54120ffSKevin Wolf drv->bdrv_parse_filename(filename, *options, &local_err); 1149f54120ffSKevin Wolf if (local_err) { 1150f54120ffSKevin Wolf error_propagate(errp, local_err); 1151f54120ffSKevin Wolf return -EINVAL; 1152f54120ffSKevin Wolf } 1153f54120ffSKevin Wolf 1154f54120ffSKevin Wolf if (!drv->bdrv_needs_filename) { 1155f54120ffSKevin Wolf qdict_del(*options, "filename"); 1156f54120ffSKevin Wolf } 1157f54120ffSKevin Wolf } 1158f54120ffSKevin Wolf 1159f54120ffSKevin Wolf return 0; 1160f54120ffSKevin Wolf } 1161f54120ffSKevin Wolf 11628d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd) 11638d24cce1SFam Zheng { 11648d24cce1SFam Zheng 1165826b6ca0SFam Zheng if (bs->backing_hd) { 1166826b6ca0SFam Zheng assert(bs->backing_blocker); 1167826b6ca0SFam Zheng bdrv_op_unblock_all(bs->backing_hd, bs->backing_blocker); 1168826b6ca0SFam Zheng } else if (backing_hd) { 1169826b6ca0SFam Zheng error_setg(&bs->backing_blocker, 1170826b6ca0SFam Zheng "device is used as backing hd of '%s'", 1171bfb197e0SMarkus Armbruster bdrv_get_device_name(bs)); 1172826b6ca0SFam Zheng } 1173826b6ca0SFam Zheng 11748d24cce1SFam Zheng bs->backing_hd = backing_hd; 11758d24cce1SFam Zheng if (!backing_hd) { 1176826b6ca0SFam Zheng error_free(bs->backing_blocker); 1177826b6ca0SFam Zheng bs->backing_blocker = NULL; 11788d24cce1SFam Zheng goto out; 11798d24cce1SFam Zheng } 11808d24cce1SFam Zheng bs->open_flags &= ~BDRV_O_NO_BACKING; 11818d24cce1SFam Zheng pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename); 11828d24cce1SFam Zheng pstrcpy(bs->backing_format, sizeof(bs->backing_format), 11838d24cce1SFam Zheng backing_hd->drv ? backing_hd->drv->format_name : ""); 1184826b6ca0SFam Zheng 1185826b6ca0SFam Zheng bdrv_op_block_all(bs->backing_hd, bs->backing_blocker); 1186826b6ca0SFam Zheng /* Otherwise we won't be able to commit due to check in bdrv_commit */ 1187826b6ca0SFam Zheng bdrv_op_unblock(bs->backing_hd, BLOCK_OP_TYPE_COMMIT, 1188826b6ca0SFam Zheng bs->backing_blocker); 11898d24cce1SFam Zheng out: 11903baca891SKevin Wolf bdrv_refresh_limits(bs, NULL); 11918d24cce1SFam Zheng } 11928d24cce1SFam Zheng 119331ca6d07SKevin Wolf /* 119431ca6d07SKevin Wolf * Opens the backing file for a BlockDriverState if not yet open 119531ca6d07SKevin Wolf * 119631ca6d07SKevin Wolf * options is a QDict of options to pass to the block drivers, or NULL for an 119731ca6d07SKevin Wolf * empty set of options. The reference to the QDict is transferred to this 119831ca6d07SKevin Wolf * function (even on failure), so if the caller intends to reuse the dictionary, 119931ca6d07SKevin Wolf * it needs to use QINCREF() before calling bdrv_file_open. 120031ca6d07SKevin Wolf */ 120134b5d2c6SMax Reitz int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp) 12029156df12SPaolo Bonzini { 12031ba4b6a5SBenoît Canet char *backing_filename = g_malloc0(PATH_MAX); 1204317fc44eSKevin Wolf int ret = 0; 12059156df12SPaolo Bonzini BlockDriver *back_drv = NULL; 12068d24cce1SFam Zheng BlockDriverState *backing_hd; 120734b5d2c6SMax Reitz Error *local_err = NULL; 12089156df12SPaolo Bonzini 12099156df12SPaolo Bonzini if (bs->backing_hd != NULL) { 121031ca6d07SKevin Wolf QDECREF(options); 12111ba4b6a5SBenoît Canet goto free_exit; 12129156df12SPaolo Bonzini } 12139156df12SPaolo Bonzini 121431ca6d07SKevin Wolf /* NULL means an empty set of options */ 121531ca6d07SKevin Wolf if (options == NULL) { 121631ca6d07SKevin Wolf options = qdict_new(); 121731ca6d07SKevin Wolf } 121831ca6d07SKevin Wolf 12199156df12SPaolo Bonzini bs->open_flags &= ~BDRV_O_NO_BACKING; 12201cb6f506SKevin Wolf if (qdict_haskey(options, "file.filename")) { 12211cb6f506SKevin Wolf backing_filename[0] = '\0'; 12221cb6f506SKevin Wolf } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) { 122331ca6d07SKevin Wolf QDECREF(options); 12241ba4b6a5SBenoît Canet goto free_exit; 1225dbecebddSFam Zheng } else { 12261ba4b6a5SBenoît Canet bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX); 12279156df12SPaolo Bonzini } 12289156df12SPaolo Bonzini 12298ee79e70SKevin Wolf if (!bs->drv || !bs->drv->supports_backing) { 12308ee79e70SKevin Wolf ret = -EINVAL; 12318ee79e70SKevin Wolf error_setg(errp, "Driver doesn't support backing files"); 12328ee79e70SKevin Wolf QDECREF(options); 12338ee79e70SKevin Wolf goto free_exit; 12348ee79e70SKevin Wolf } 12358ee79e70SKevin Wolf 1236e4e9986bSMarkus Armbruster backing_hd = bdrv_new(); 12378d24cce1SFam Zheng 12389156df12SPaolo Bonzini if (bs->backing_format[0] != '\0') { 12399156df12SPaolo Bonzini back_drv = bdrv_find_format(bs->backing_format); 12409156df12SPaolo Bonzini } 12419156df12SPaolo Bonzini 1242f67503e5SMax Reitz assert(bs->backing_hd == NULL); 12438d24cce1SFam Zheng ret = bdrv_open(&backing_hd, 1244ddf5636dSMax Reitz *backing_filename ? backing_filename : NULL, NULL, options, 1245317fc44eSKevin Wolf bdrv_backing_flags(bs->open_flags), back_drv, &local_err); 12469156df12SPaolo Bonzini if (ret < 0) { 12478d24cce1SFam Zheng bdrv_unref(backing_hd); 12488d24cce1SFam Zheng backing_hd = NULL; 12499156df12SPaolo Bonzini bs->open_flags |= BDRV_O_NO_BACKING; 1250b04b6b6eSFam Zheng error_setg(errp, "Could not open backing file: %s", 1251b04b6b6eSFam Zheng error_get_pretty(local_err)); 1252b04b6b6eSFam Zheng error_free(local_err); 12531ba4b6a5SBenoît Canet goto free_exit; 12549156df12SPaolo Bonzini } 12558d24cce1SFam Zheng bdrv_set_backing_hd(bs, backing_hd); 1256d80ac658SPeter Feiner 12571ba4b6a5SBenoît Canet free_exit: 12581ba4b6a5SBenoît Canet g_free(backing_filename); 12591ba4b6a5SBenoît Canet return ret; 12609156df12SPaolo Bonzini } 12619156df12SPaolo Bonzini 1262b6ce07aaSKevin Wolf /* 1263da557aacSMax Reitz * Opens a disk image whose options are given as BlockdevRef in another block 1264da557aacSMax Reitz * device's options. 1265da557aacSMax Reitz * 1266da557aacSMax Reitz * If allow_none is true, no image will be opened if filename is false and no 1267da557aacSMax Reitz * BlockdevRef is given. *pbs will remain unchanged and 0 will be returned. 1268da557aacSMax Reitz * 1269da557aacSMax Reitz * bdrev_key specifies the key for the image's BlockdevRef in the options QDict. 1270da557aacSMax Reitz * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict 1271da557aacSMax Reitz * itself, all options starting with "${bdref_key}." are considered part of the 1272da557aacSMax Reitz * BlockdevRef. 1273da557aacSMax Reitz * 1274da557aacSMax Reitz * The BlockdevRef will be removed from the options QDict. 1275f67503e5SMax Reitz * 1276f67503e5SMax Reitz * To conform with the behavior of bdrv_open(), *pbs has to be NULL. 1277da557aacSMax Reitz */ 1278da557aacSMax Reitz int bdrv_open_image(BlockDriverState **pbs, const char *filename, 1279da557aacSMax Reitz QDict *options, const char *bdref_key, int flags, 1280f7d9fd8cSMax Reitz bool allow_none, Error **errp) 1281da557aacSMax Reitz { 1282da557aacSMax Reitz QDict *image_options; 1283da557aacSMax Reitz int ret; 1284da557aacSMax Reitz char *bdref_key_dot; 1285da557aacSMax Reitz const char *reference; 1286da557aacSMax Reitz 1287f67503e5SMax Reitz assert(pbs); 1288f67503e5SMax Reitz assert(*pbs == NULL); 1289f67503e5SMax Reitz 1290da557aacSMax Reitz bdref_key_dot = g_strdup_printf("%s.", bdref_key); 1291da557aacSMax Reitz qdict_extract_subqdict(options, &image_options, bdref_key_dot); 1292da557aacSMax Reitz g_free(bdref_key_dot); 1293da557aacSMax Reitz 1294da557aacSMax Reitz reference = qdict_get_try_str(options, bdref_key); 1295da557aacSMax Reitz if (!filename && !reference && !qdict_size(image_options)) { 1296da557aacSMax Reitz if (allow_none) { 1297da557aacSMax Reitz ret = 0; 1298da557aacSMax Reitz } else { 1299da557aacSMax Reitz error_setg(errp, "A block device must be specified for \"%s\"", 1300da557aacSMax Reitz bdref_key); 1301da557aacSMax Reitz ret = -EINVAL; 1302da557aacSMax Reitz } 1303b20e61e0SMarkus Armbruster QDECREF(image_options); 1304da557aacSMax Reitz goto done; 1305da557aacSMax Reitz } 1306da557aacSMax Reitz 1307f7d9fd8cSMax Reitz ret = bdrv_open(pbs, filename, reference, image_options, flags, NULL, errp); 1308da557aacSMax Reitz 1309da557aacSMax Reitz done: 1310da557aacSMax Reitz qdict_del(options, bdref_key); 1311da557aacSMax Reitz return ret; 1312da557aacSMax Reitz } 1313da557aacSMax Reitz 13146b8aeca5SChen Gang int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp) 1315b998875dSKevin Wolf { 1316b998875dSKevin Wolf /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */ 13171ba4b6a5SBenoît Canet char *tmp_filename = g_malloc0(PATH_MAX + 1); 1318b998875dSKevin Wolf int64_t total_size; 1319b998875dSKevin Wolf BlockDriver *bdrv_qcow2; 132083d0521aSChunyan Liu QemuOpts *opts = NULL; 1321b998875dSKevin Wolf QDict *snapshot_options; 1322b998875dSKevin Wolf BlockDriverState *bs_snapshot; 1323b998875dSKevin Wolf Error *local_err; 1324b998875dSKevin Wolf int ret; 1325b998875dSKevin Wolf 1326b998875dSKevin Wolf /* if snapshot, we create a temporary backing file and open it 1327b998875dSKevin Wolf instead of opening 'filename' directly */ 1328b998875dSKevin Wolf 1329b998875dSKevin Wolf /* Get the required size from the image */ 1330f187743aSKevin Wolf total_size = bdrv_getlength(bs); 1331f187743aSKevin Wolf if (total_size < 0) { 13326b8aeca5SChen Gang ret = total_size; 1333f187743aSKevin Wolf error_setg_errno(errp, -total_size, "Could not get image size"); 13341ba4b6a5SBenoît Canet goto out; 1335f187743aSKevin Wolf } 1336b998875dSKevin Wolf 1337b998875dSKevin Wolf /* Create the temporary image */ 13381ba4b6a5SBenoît Canet ret = get_tmp_filename(tmp_filename, PATH_MAX + 1); 1339b998875dSKevin Wolf if (ret < 0) { 1340b998875dSKevin Wolf error_setg_errno(errp, -ret, "Could not get temporary filename"); 13411ba4b6a5SBenoît Canet goto out; 1342b998875dSKevin Wolf } 1343b998875dSKevin Wolf 1344b998875dSKevin Wolf bdrv_qcow2 = bdrv_find_format("qcow2"); 1345c282e1fdSChunyan Liu opts = qemu_opts_create(bdrv_qcow2->create_opts, NULL, 0, 1346c282e1fdSChunyan Liu &error_abort); 134783d0521aSChunyan Liu qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size); 1348c282e1fdSChunyan Liu ret = bdrv_create(bdrv_qcow2, tmp_filename, opts, &local_err); 134983d0521aSChunyan Liu qemu_opts_del(opts); 1350b998875dSKevin Wolf if (ret < 0) { 1351b998875dSKevin Wolf error_setg_errno(errp, -ret, "Could not create temporary overlay " 1352b998875dSKevin Wolf "'%s': %s", tmp_filename, 1353b998875dSKevin Wolf error_get_pretty(local_err)); 1354b998875dSKevin Wolf error_free(local_err); 13551ba4b6a5SBenoît Canet goto out; 1356b998875dSKevin Wolf } 1357b998875dSKevin Wolf 1358b998875dSKevin Wolf /* Prepare a new options QDict for the temporary file */ 1359b998875dSKevin Wolf snapshot_options = qdict_new(); 1360b998875dSKevin Wolf qdict_put(snapshot_options, "file.driver", 1361b998875dSKevin Wolf qstring_from_str("file")); 1362b998875dSKevin Wolf qdict_put(snapshot_options, "file.filename", 1363b998875dSKevin Wolf qstring_from_str(tmp_filename)); 1364b998875dSKevin Wolf 1365e4e9986bSMarkus Armbruster bs_snapshot = bdrv_new(); 1366b998875dSKevin Wolf 1367b998875dSKevin Wolf ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options, 1368b1e6fc08SKevin Wolf flags, bdrv_qcow2, &local_err); 1369b998875dSKevin Wolf if (ret < 0) { 1370b998875dSKevin Wolf error_propagate(errp, local_err); 13711ba4b6a5SBenoît Canet goto out; 1372b998875dSKevin Wolf } 1373b998875dSKevin Wolf 1374b998875dSKevin Wolf bdrv_append(bs_snapshot, bs); 13751ba4b6a5SBenoît Canet 13761ba4b6a5SBenoît Canet out: 13771ba4b6a5SBenoît Canet g_free(tmp_filename); 13786b8aeca5SChen Gang return ret; 1379b998875dSKevin Wolf } 1380b998875dSKevin Wolf 1381da557aacSMax Reitz /* 1382b6ce07aaSKevin Wolf * Opens a disk image (raw, qcow2, vmdk, ...) 1383de9c0cecSKevin Wolf * 1384de9c0cecSKevin Wolf * options is a QDict of options to pass to the block drivers, or NULL for an 1385de9c0cecSKevin Wolf * empty set of options. The reference to the QDict belongs to the block layer 1386de9c0cecSKevin Wolf * after the call (even on failure), so if the caller intends to reuse the 1387de9c0cecSKevin Wolf * dictionary, it needs to use QINCREF() before calling bdrv_open. 1388f67503e5SMax Reitz * 1389f67503e5SMax Reitz * If *pbs is NULL, a new BDS will be created with a pointer to it stored there. 1390f67503e5SMax Reitz * If it is not NULL, the referenced BDS will be reused. 1391ddf5636dSMax Reitz * 1392ddf5636dSMax Reitz * The reference parameter may be used to specify an existing block device which 1393ddf5636dSMax Reitz * should be opened. If specified, neither options nor a filename may be given, 1394ddf5636dSMax Reitz * nor can an existing BDS be reused (that is, *pbs has to be NULL). 1395b6ce07aaSKevin Wolf */ 1396ddf5636dSMax Reitz int bdrv_open(BlockDriverState **pbs, const char *filename, 1397ddf5636dSMax Reitz const char *reference, QDict *options, int flags, 1398ddf5636dSMax Reitz BlockDriver *drv, Error **errp) 1399ea2384d3Sbellard { 1400b6ce07aaSKevin Wolf int ret; 1401f67503e5SMax Reitz BlockDriverState *file = NULL, *bs; 140274fe54f2SKevin Wolf const char *drvname; 140334b5d2c6SMax Reitz Error *local_err = NULL; 1404b1e6fc08SKevin Wolf int snapshot_flags = 0; 140533e3963eSbellard 1406f67503e5SMax Reitz assert(pbs); 1407f67503e5SMax Reitz 1408ddf5636dSMax Reitz if (reference) { 1409ddf5636dSMax Reitz bool options_non_empty = options ? qdict_size(options) : false; 1410ddf5636dSMax Reitz QDECREF(options); 1411ddf5636dSMax Reitz 1412ddf5636dSMax Reitz if (*pbs) { 1413ddf5636dSMax Reitz error_setg(errp, "Cannot reuse an existing BDS when referencing " 1414ddf5636dSMax Reitz "another block device"); 1415ddf5636dSMax Reitz return -EINVAL; 1416ddf5636dSMax Reitz } 1417ddf5636dSMax Reitz 1418ddf5636dSMax Reitz if (filename || options_non_empty) { 1419ddf5636dSMax Reitz error_setg(errp, "Cannot reference an existing block device with " 1420ddf5636dSMax Reitz "additional options or a new filename"); 1421ddf5636dSMax Reitz return -EINVAL; 1422ddf5636dSMax Reitz } 1423ddf5636dSMax Reitz 1424ddf5636dSMax Reitz bs = bdrv_lookup_bs(reference, reference, errp); 1425ddf5636dSMax Reitz if (!bs) { 1426ddf5636dSMax Reitz return -ENODEV; 1427ddf5636dSMax Reitz } 1428ddf5636dSMax Reitz bdrv_ref(bs); 1429ddf5636dSMax Reitz *pbs = bs; 1430ddf5636dSMax Reitz return 0; 1431ddf5636dSMax Reitz } 1432ddf5636dSMax Reitz 1433f67503e5SMax Reitz if (*pbs) { 1434f67503e5SMax Reitz bs = *pbs; 1435f67503e5SMax Reitz } else { 1436e4e9986bSMarkus Armbruster bs = bdrv_new(); 1437f67503e5SMax Reitz } 1438f67503e5SMax Reitz 1439de9c0cecSKevin Wolf /* NULL means an empty set of options */ 1440de9c0cecSKevin Wolf if (options == NULL) { 1441de9c0cecSKevin Wolf options = qdict_new(); 1442de9c0cecSKevin Wolf } 1443de9c0cecSKevin Wolf 144417b005f1SKevin Wolf ret = bdrv_fill_options(&options, &filename, flags, drv, &local_err); 1445462f5bcfSKevin Wolf if (local_err) { 1446462f5bcfSKevin Wolf goto fail; 1447462f5bcfSKevin Wolf } 1448462f5bcfSKevin Wolf 144976c591b0SKevin Wolf /* Find the right image format driver */ 145076c591b0SKevin Wolf drv = NULL; 145176c591b0SKevin Wolf drvname = qdict_get_try_str(options, "driver"); 145276c591b0SKevin Wolf if (drvname) { 145376c591b0SKevin Wolf drv = bdrv_find_format(drvname); 145476c591b0SKevin Wolf qdict_del(options, "driver"); 145576c591b0SKevin Wolf if (!drv) { 145676c591b0SKevin Wolf error_setg(errp, "Unknown driver: '%s'", drvname); 145776c591b0SKevin Wolf ret = -EINVAL; 145876c591b0SKevin Wolf goto fail; 145976c591b0SKevin Wolf } 146076c591b0SKevin Wolf } 146176c591b0SKevin Wolf 146276c591b0SKevin Wolf assert(drvname || !(flags & BDRV_O_PROTOCOL)); 146376c591b0SKevin Wolf if (drv && !drv->bdrv_file_open) { 146476c591b0SKevin Wolf /* If the user explicitly wants a format driver here, we'll need to add 146576c591b0SKevin Wolf * another layer for the protocol in bs->file */ 146676c591b0SKevin Wolf flags &= ~BDRV_O_PROTOCOL; 146776c591b0SKevin Wolf } 146876c591b0SKevin Wolf 1469de9c0cecSKevin Wolf bs->options = options; 1470b6ad491aSKevin Wolf options = qdict_clone_shallow(options); 1471de9c0cecSKevin Wolf 1472f500a6d3SKevin Wolf /* Open image file without format layer */ 1473f4788adcSKevin Wolf if ((flags & BDRV_O_PROTOCOL) == 0) { 1474be028adcSJeff Cody if (flags & BDRV_O_RDWR) { 1475be028adcSJeff Cody flags |= BDRV_O_ALLOW_RDWR; 1476be028adcSJeff Cody } 1477b1e6fc08SKevin Wolf if (flags & BDRV_O_SNAPSHOT) { 1478b1e6fc08SKevin Wolf snapshot_flags = bdrv_temp_snapshot_flags(flags); 1479b1e6fc08SKevin Wolf flags = bdrv_backing_flags(flags); 1480b1e6fc08SKevin Wolf } 1481be028adcSJeff Cody 1482f67503e5SMax Reitz assert(file == NULL); 1483054963f8SMax Reitz ret = bdrv_open_image(&file, filename, options, "file", 14840b50cc88SKevin Wolf bdrv_inherited_flags(flags), 14850b50cc88SKevin Wolf true, &local_err); 1486f500a6d3SKevin Wolf if (ret < 0) { 14878bfea15dSKevin Wolf goto fail; 1488f500a6d3SKevin Wolf } 1489f4788adcSKevin Wolf } 1490f500a6d3SKevin Wolf 149176c591b0SKevin Wolf /* Image format probing */ 149276c591b0SKevin Wolf if (!drv && file) { 149334b5d2c6SMax Reitz ret = find_image_format(file, filename, &drv, &local_err); 149417b005f1SKevin Wolf if (ret < 0) { 149517b005f1SKevin Wolf goto fail; 149617b005f1SKevin Wolf } 149776c591b0SKevin Wolf } else if (!drv) { 14982a05cbe4SMax Reitz error_setg(errp, "Must specify either driver or file"); 14992a05cbe4SMax Reitz ret = -EINVAL; 15008bfea15dSKevin Wolf goto fail; 15012a05cbe4SMax Reitz } 1502f500a6d3SKevin Wolf 1503b6ce07aaSKevin Wolf /* Open the image */ 150434b5d2c6SMax Reitz ret = bdrv_open_common(bs, file, options, flags, drv, &local_err); 1505b6ce07aaSKevin Wolf if (ret < 0) { 15068bfea15dSKevin Wolf goto fail; 15076987307cSChristoph Hellwig } 15086987307cSChristoph Hellwig 15092a05cbe4SMax Reitz if (file && (bs->file != file)) { 15104f6fd349SFam Zheng bdrv_unref(file); 1511f500a6d3SKevin Wolf file = NULL; 1512f500a6d3SKevin Wolf } 1513f500a6d3SKevin Wolf 1514b6ce07aaSKevin Wolf /* If there is a backing file, use it */ 15159156df12SPaolo Bonzini if ((flags & BDRV_O_NO_BACKING) == 0) { 151631ca6d07SKevin Wolf QDict *backing_options; 151731ca6d07SKevin Wolf 15185726d872SBenoît Canet qdict_extract_subqdict(options, &backing_options, "backing."); 151934b5d2c6SMax Reitz ret = bdrv_open_backing_file(bs, backing_options, &local_err); 1520b6ce07aaSKevin Wolf if (ret < 0) { 1521b6ad491aSKevin Wolf goto close_and_fail; 1522b6ce07aaSKevin Wolf } 1523b6ce07aaSKevin Wolf } 1524b6ce07aaSKevin Wolf 152591af7014SMax Reitz bdrv_refresh_filename(bs); 152691af7014SMax Reitz 1527b998875dSKevin Wolf /* For snapshot=on, create a temporary qcow2 overlay. bs points to the 1528b998875dSKevin Wolf * temporary snapshot afterwards. */ 1529b1e6fc08SKevin Wolf if (snapshot_flags) { 15306b8aeca5SChen Gang ret = bdrv_append_temp_snapshot(bs, snapshot_flags, &local_err); 1531b998875dSKevin Wolf if (local_err) { 1532b998875dSKevin Wolf goto close_and_fail; 1533b998875dSKevin Wolf } 1534b998875dSKevin Wolf } 1535b998875dSKevin Wolf 1536b6ad491aSKevin Wolf /* Check if any unknown options were used */ 15375acd9d81SMax Reitz if (options && (qdict_size(options) != 0)) { 1538b6ad491aSKevin Wolf const QDictEntry *entry = qdict_first(options); 15395acd9d81SMax Reitz if (flags & BDRV_O_PROTOCOL) { 15405acd9d81SMax Reitz error_setg(errp, "Block protocol '%s' doesn't support the option " 15415acd9d81SMax Reitz "'%s'", drv->format_name, entry->key); 15425acd9d81SMax Reitz } else { 154334b5d2c6SMax Reitz error_setg(errp, "Block format '%s' used by device '%s' doesn't " 15445acd9d81SMax Reitz "support the option '%s'", drv->format_name, 1545bfb197e0SMarkus Armbruster bdrv_get_device_name(bs), entry->key); 15465acd9d81SMax Reitz } 1547b6ad491aSKevin Wolf 1548b6ad491aSKevin Wolf ret = -EINVAL; 1549b6ad491aSKevin Wolf goto close_and_fail; 1550b6ad491aSKevin Wolf } 1551b6ad491aSKevin Wolf 1552b6ce07aaSKevin Wolf if (!bdrv_key_required(bs)) { 1553a7f53e26SMarkus Armbruster if (bs->blk) { 1554a7f53e26SMarkus Armbruster blk_dev_change_media_cb(bs->blk, true); 1555a7f53e26SMarkus Armbruster } 1556c3adb58fSMarkus Armbruster } else if (!runstate_check(RUN_STATE_PRELAUNCH) 1557c3adb58fSMarkus Armbruster && !runstate_check(RUN_STATE_INMIGRATE) 1558c3adb58fSMarkus Armbruster && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */ 1559c3adb58fSMarkus Armbruster error_setg(errp, 1560c3adb58fSMarkus Armbruster "Guest must be stopped for opening of encrypted image"); 1561c3adb58fSMarkus Armbruster ret = -EBUSY; 1562c3adb58fSMarkus Armbruster goto close_and_fail; 1563b6ce07aaSKevin Wolf } 1564b6ce07aaSKevin Wolf 1565c3adb58fSMarkus Armbruster QDECREF(options); 1566f67503e5SMax Reitz *pbs = bs; 1567b6ce07aaSKevin Wolf return 0; 1568b6ce07aaSKevin Wolf 15698bfea15dSKevin Wolf fail: 1570f500a6d3SKevin Wolf if (file != NULL) { 15714f6fd349SFam Zheng bdrv_unref(file); 1572f500a6d3SKevin Wolf } 1573de9c0cecSKevin Wolf QDECREF(bs->options); 1574b6ad491aSKevin Wolf QDECREF(options); 1575de9c0cecSKevin Wolf bs->options = NULL; 1576f67503e5SMax Reitz if (!*pbs) { 1577f67503e5SMax Reitz /* If *pbs is NULL, a new BDS has been created in this function and 1578f67503e5SMax Reitz needs to be freed now. Otherwise, it does not need to be closed, 1579f67503e5SMax Reitz since it has not really been opened yet. */ 1580f67503e5SMax Reitz bdrv_unref(bs); 1581f67503e5SMax Reitz } 158284d18f06SMarkus Armbruster if (local_err) { 158334b5d2c6SMax Reitz error_propagate(errp, local_err); 158434b5d2c6SMax Reitz } 1585b6ad491aSKevin Wolf return ret; 1586de9c0cecSKevin Wolf 1587b6ad491aSKevin Wolf close_and_fail: 1588f67503e5SMax Reitz /* See fail path, but now the BDS has to be always closed */ 1589f67503e5SMax Reitz if (*pbs) { 1590b6ad491aSKevin Wolf bdrv_close(bs); 1591f67503e5SMax Reitz } else { 1592f67503e5SMax Reitz bdrv_unref(bs); 1593f67503e5SMax Reitz } 1594b6ad491aSKevin Wolf QDECREF(options); 159584d18f06SMarkus Armbruster if (local_err) { 159634b5d2c6SMax Reitz error_propagate(errp, local_err); 159734b5d2c6SMax Reitz } 1598b6ce07aaSKevin Wolf return ret; 1599b6ce07aaSKevin Wolf } 1600b6ce07aaSKevin Wolf 1601e971aa12SJeff Cody typedef struct BlockReopenQueueEntry { 1602e971aa12SJeff Cody bool prepared; 1603e971aa12SJeff Cody BDRVReopenState state; 1604e971aa12SJeff Cody QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry; 1605e971aa12SJeff Cody } BlockReopenQueueEntry; 1606e971aa12SJeff Cody 1607e971aa12SJeff Cody /* 1608e971aa12SJeff Cody * Adds a BlockDriverState to a simple queue for an atomic, transactional 1609e971aa12SJeff Cody * reopen of multiple devices. 1610e971aa12SJeff Cody * 1611e971aa12SJeff Cody * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT 1612e971aa12SJeff Cody * already performed, or alternatively may be NULL a new BlockReopenQueue will 1613e971aa12SJeff Cody * be created and initialized. This newly created BlockReopenQueue should be 1614e971aa12SJeff Cody * passed back in for subsequent calls that are intended to be of the same 1615e971aa12SJeff Cody * atomic 'set'. 1616e971aa12SJeff Cody * 1617e971aa12SJeff Cody * bs is the BlockDriverState to add to the reopen queue. 1618e971aa12SJeff Cody * 1619e971aa12SJeff Cody * flags contains the open flags for the associated bs 1620e971aa12SJeff Cody * 1621e971aa12SJeff Cody * returns a pointer to bs_queue, which is either the newly allocated 1622e971aa12SJeff Cody * bs_queue, or the existing bs_queue being used. 1623e971aa12SJeff Cody * 1624e971aa12SJeff Cody */ 1625e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue, 1626e971aa12SJeff Cody BlockDriverState *bs, int flags) 1627e971aa12SJeff Cody { 1628e971aa12SJeff Cody assert(bs != NULL); 1629e971aa12SJeff Cody 1630e971aa12SJeff Cody BlockReopenQueueEntry *bs_entry; 1631e971aa12SJeff Cody if (bs_queue == NULL) { 1632e971aa12SJeff Cody bs_queue = g_new0(BlockReopenQueue, 1); 1633e971aa12SJeff Cody QSIMPLEQ_INIT(bs_queue); 1634e971aa12SJeff Cody } 1635e971aa12SJeff Cody 1636f1f25a2eSKevin Wolf /* bdrv_open() masks this flag out */ 1637f1f25a2eSKevin Wolf flags &= ~BDRV_O_PROTOCOL; 1638f1f25a2eSKevin Wolf 1639e971aa12SJeff Cody if (bs->file) { 1640f1f25a2eSKevin Wolf bdrv_reopen_queue(bs_queue, bs->file, bdrv_inherited_flags(flags)); 1641e971aa12SJeff Cody } 1642e971aa12SJeff Cody 1643e971aa12SJeff Cody bs_entry = g_new0(BlockReopenQueueEntry, 1); 1644e971aa12SJeff Cody QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry); 1645e971aa12SJeff Cody 1646e971aa12SJeff Cody bs_entry->state.bs = bs; 1647e971aa12SJeff Cody bs_entry->state.flags = flags; 1648e971aa12SJeff Cody 1649e971aa12SJeff Cody return bs_queue; 1650e971aa12SJeff Cody } 1651e971aa12SJeff Cody 1652e971aa12SJeff Cody /* 1653e971aa12SJeff Cody * Reopen multiple BlockDriverStates atomically & transactionally. 1654e971aa12SJeff Cody * 1655e971aa12SJeff Cody * The queue passed in (bs_queue) must have been built up previous 1656e971aa12SJeff Cody * via bdrv_reopen_queue(). 1657e971aa12SJeff Cody * 1658e971aa12SJeff Cody * Reopens all BDS specified in the queue, with the appropriate 1659e971aa12SJeff Cody * flags. All devices are prepared for reopen, and failure of any 1660e971aa12SJeff Cody * device will cause all device changes to be abandonded, and intermediate 1661e971aa12SJeff Cody * data cleaned up. 1662e971aa12SJeff Cody * 1663e971aa12SJeff Cody * If all devices prepare successfully, then the changes are committed 1664e971aa12SJeff Cody * to all devices. 1665e971aa12SJeff Cody * 1666e971aa12SJeff Cody */ 1667e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp) 1668e971aa12SJeff Cody { 1669e971aa12SJeff Cody int ret = -1; 1670e971aa12SJeff Cody BlockReopenQueueEntry *bs_entry, *next; 1671e971aa12SJeff Cody Error *local_err = NULL; 1672e971aa12SJeff Cody 1673e971aa12SJeff Cody assert(bs_queue != NULL); 1674e971aa12SJeff Cody 1675e971aa12SJeff Cody bdrv_drain_all(); 1676e971aa12SJeff Cody 1677e971aa12SJeff Cody QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) { 1678e971aa12SJeff Cody if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) { 1679e971aa12SJeff Cody error_propagate(errp, local_err); 1680e971aa12SJeff Cody goto cleanup; 1681e971aa12SJeff Cody } 1682e971aa12SJeff Cody bs_entry->prepared = true; 1683e971aa12SJeff Cody } 1684e971aa12SJeff Cody 1685e971aa12SJeff Cody /* If we reach this point, we have success and just need to apply the 1686e971aa12SJeff Cody * changes 1687e971aa12SJeff Cody */ 1688e971aa12SJeff Cody QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) { 1689e971aa12SJeff Cody bdrv_reopen_commit(&bs_entry->state); 1690e971aa12SJeff Cody } 1691e971aa12SJeff Cody 1692e971aa12SJeff Cody ret = 0; 1693e971aa12SJeff Cody 1694e971aa12SJeff Cody cleanup: 1695e971aa12SJeff Cody QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) { 1696e971aa12SJeff Cody if (ret && bs_entry->prepared) { 1697e971aa12SJeff Cody bdrv_reopen_abort(&bs_entry->state); 1698e971aa12SJeff Cody } 1699e971aa12SJeff Cody g_free(bs_entry); 1700e971aa12SJeff Cody } 1701e971aa12SJeff Cody g_free(bs_queue); 1702e971aa12SJeff Cody return ret; 1703e971aa12SJeff Cody } 1704e971aa12SJeff Cody 1705e971aa12SJeff Cody 1706e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */ 1707e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp) 1708e971aa12SJeff Cody { 1709e971aa12SJeff Cody int ret = -1; 1710e971aa12SJeff Cody Error *local_err = NULL; 1711e971aa12SJeff Cody BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags); 1712e971aa12SJeff Cody 1713e971aa12SJeff Cody ret = bdrv_reopen_multiple(queue, &local_err); 1714e971aa12SJeff Cody if (local_err != NULL) { 1715e971aa12SJeff Cody error_propagate(errp, local_err); 1716e971aa12SJeff Cody } 1717e971aa12SJeff Cody return ret; 1718e971aa12SJeff Cody } 1719e971aa12SJeff Cody 1720e971aa12SJeff Cody 1721e971aa12SJeff Cody /* 1722e971aa12SJeff Cody * Prepares a BlockDriverState for reopen. All changes are staged in the 1723e971aa12SJeff Cody * 'opaque' field of the BDRVReopenState, which is used and allocated by 1724e971aa12SJeff Cody * the block driver layer .bdrv_reopen_prepare() 1725e971aa12SJeff Cody * 1726e971aa12SJeff Cody * bs is the BlockDriverState to reopen 1727e971aa12SJeff Cody * flags are the new open flags 1728e971aa12SJeff Cody * queue is the reopen queue 1729e971aa12SJeff Cody * 1730e971aa12SJeff Cody * Returns 0 on success, non-zero on error. On error errp will be set 1731e971aa12SJeff Cody * as well. 1732e971aa12SJeff Cody * 1733e971aa12SJeff Cody * On failure, bdrv_reopen_abort() will be called to clean up any data. 1734e971aa12SJeff Cody * It is the responsibility of the caller to then call the abort() or 1735e971aa12SJeff Cody * commit() for any other BDS that have been left in a prepare() state 1736e971aa12SJeff Cody * 1737e971aa12SJeff Cody */ 1738e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue, 1739e971aa12SJeff Cody Error **errp) 1740e971aa12SJeff Cody { 1741e971aa12SJeff Cody int ret = -1; 1742e971aa12SJeff Cody Error *local_err = NULL; 1743e971aa12SJeff Cody BlockDriver *drv; 1744e971aa12SJeff Cody 1745e971aa12SJeff Cody assert(reopen_state != NULL); 1746e971aa12SJeff Cody assert(reopen_state->bs->drv != NULL); 1747e971aa12SJeff Cody drv = reopen_state->bs->drv; 1748e971aa12SJeff Cody 1749e971aa12SJeff Cody /* if we are to stay read-only, do not allow permission change 1750e971aa12SJeff Cody * to r/w */ 1751e971aa12SJeff Cody if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) && 1752e971aa12SJeff Cody reopen_state->flags & BDRV_O_RDWR) { 1753e971aa12SJeff Cody error_set(errp, QERR_DEVICE_IS_READ_ONLY, 1754bfb197e0SMarkus Armbruster bdrv_get_device_name(reopen_state->bs)); 1755e971aa12SJeff Cody goto error; 1756e971aa12SJeff Cody } 1757e971aa12SJeff Cody 1758e971aa12SJeff Cody 1759e971aa12SJeff Cody ret = bdrv_flush(reopen_state->bs); 1760e971aa12SJeff Cody if (ret) { 1761e971aa12SJeff Cody error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive", 1762e971aa12SJeff Cody strerror(-ret)); 1763e971aa12SJeff Cody goto error; 1764e971aa12SJeff Cody } 1765e971aa12SJeff Cody 1766e971aa12SJeff Cody if (drv->bdrv_reopen_prepare) { 1767e971aa12SJeff Cody ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err); 1768e971aa12SJeff Cody if (ret) { 1769e971aa12SJeff Cody if (local_err != NULL) { 1770e971aa12SJeff Cody error_propagate(errp, local_err); 1771e971aa12SJeff Cody } else { 1772d8b6895fSLuiz Capitulino error_setg(errp, "failed while preparing to reopen image '%s'", 1773e971aa12SJeff Cody reopen_state->bs->filename); 1774e971aa12SJeff Cody } 1775e971aa12SJeff Cody goto error; 1776e971aa12SJeff Cody } 1777e971aa12SJeff Cody } else { 1778e971aa12SJeff Cody /* It is currently mandatory to have a bdrv_reopen_prepare() 1779e971aa12SJeff Cody * handler for each supported drv. */ 1780e971aa12SJeff Cody error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED, 1781bfb197e0SMarkus Armbruster drv->format_name, bdrv_get_device_name(reopen_state->bs), 1782e971aa12SJeff Cody "reopening of file"); 1783e971aa12SJeff Cody ret = -1; 1784e971aa12SJeff Cody goto error; 1785e971aa12SJeff Cody } 1786e971aa12SJeff Cody 1787e971aa12SJeff Cody ret = 0; 1788e971aa12SJeff Cody 1789e971aa12SJeff Cody error: 1790e971aa12SJeff Cody return ret; 1791e971aa12SJeff Cody } 1792e971aa12SJeff Cody 1793e971aa12SJeff Cody /* 1794e971aa12SJeff Cody * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and 1795e971aa12SJeff Cody * makes them final by swapping the staging BlockDriverState contents into 1796e971aa12SJeff Cody * the active BlockDriverState contents. 1797e971aa12SJeff Cody */ 1798e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state) 1799e971aa12SJeff Cody { 1800e971aa12SJeff Cody BlockDriver *drv; 1801e971aa12SJeff Cody 1802e971aa12SJeff Cody assert(reopen_state != NULL); 1803e971aa12SJeff Cody drv = reopen_state->bs->drv; 1804e971aa12SJeff Cody assert(drv != NULL); 1805e971aa12SJeff Cody 1806e971aa12SJeff Cody /* If there are any driver level actions to take */ 1807e971aa12SJeff Cody if (drv->bdrv_reopen_commit) { 1808e971aa12SJeff Cody drv->bdrv_reopen_commit(reopen_state); 1809e971aa12SJeff Cody } 1810e971aa12SJeff Cody 1811e971aa12SJeff Cody /* set BDS specific flags now */ 1812e971aa12SJeff Cody reopen_state->bs->open_flags = reopen_state->flags; 1813e971aa12SJeff Cody reopen_state->bs->enable_write_cache = !!(reopen_state->flags & 1814e971aa12SJeff Cody BDRV_O_CACHE_WB); 1815e971aa12SJeff Cody reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR); 1816355ef4acSKevin Wolf 18173baca891SKevin Wolf bdrv_refresh_limits(reopen_state->bs, NULL); 1818e971aa12SJeff Cody } 1819e971aa12SJeff Cody 1820e971aa12SJeff Cody /* 1821e971aa12SJeff Cody * Abort the reopen, and delete and free the staged changes in 1822e971aa12SJeff Cody * reopen_state 1823e971aa12SJeff Cody */ 1824e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state) 1825e971aa12SJeff Cody { 1826e971aa12SJeff Cody BlockDriver *drv; 1827e971aa12SJeff Cody 1828e971aa12SJeff Cody assert(reopen_state != NULL); 1829e971aa12SJeff Cody drv = reopen_state->bs->drv; 1830e971aa12SJeff Cody assert(drv != NULL); 1831e971aa12SJeff Cody 1832e971aa12SJeff Cody if (drv->bdrv_reopen_abort) { 1833e971aa12SJeff Cody drv->bdrv_reopen_abort(reopen_state); 1834e971aa12SJeff Cody } 1835e971aa12SJeff Cody } 1836e971aa12SJeff Cody 1837e971aa12SJeff Cody 1838fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs) 1839fc01f7e7Sbellard { 184033384421SMax Reitz BdrvAioNotifier *ban, *ban_next; 184133384421SMax Reitz 18423e914655SPaolo Bonzini if (bs->job) { 18433e914655SPaolo Bonzini block_job_cancel_sync(bs->job); 18443e914655SPaolo Bonzini } 184558fda173SStefan Hajnoczi bdrv_drain_all(); /* complete I/O */ 184658fda173SStefan Hajnoczi bdrv_flush(bs); 184758fda173SStefan Hajnoczi bdrv_drain_all(); /* in case flush left pending I/O */ 1848d7d512f6SPaolo Bonzini notifier_list_notify(&bs->close_notifiers, bs); 18497094f12fSKevin Wolf 18503cbc002cSPaolo Bonzini if (bs->drv) { 1851557df6acSStefan Hajnoczi if (bs->backing_hd) { 1852826b6ca0SFam Zheng BlockDriverState *backing_hd = bs->backing_hd; 1853826b6ca0SFam Zheng bdrv_set_backing_hd(bs, NULL); 1854826b6ca0SFam Zheng bdrv_unref(backing_hd); 1855557df6acSStefan Hajnoczi } 1856ea2384d3Sbellard bs->drv->bdrv_close(bs); 18577267c094SAnthony Liguori g_free(bs->opaque); 1858ea2384d3Sbellard bs->opaque = NULL; 1859ea2384d3Sbellard bs->drv = NULL; 186053fec9d3SStefan Hajnoczi bs->copy_on_read = 0; 1861a275fa42SPaolo Bonzini bs->backing_file[0] = '\0'; 1862a275fa42SPaolo Bonzini bs->backing_format[0] = '\0'; 18636405875cSPaolo Bonzini bs->total_sectors = 0; 18646405875cSPaolo Bonzini bs->encrypted = 0; 18656405875cSPaolo Bonzini bs->valid_key = 0; 18666405875cSPaolo Bonzini bs->sg = 0; 18676405875cSPaolo Bonzini bs->growable = 0; 18680d51b4deSAsias He bs->zero_beyond_eof = false; 1869de9c0cecSKevin Wolf QDECREF(bs->options); 1870de9c0cecSKevin Wolf bs->options = NULL; 187191af7014SMax Reitz QDECREF(bs->full_open_options); 187291af7014SMax Reitz bs->full_open_options = NULL; 1873b338082bSbellard 187466f82ceeSKevin Wolf if (bs->file != NULL) { 18754f6fd349SFam Zheng bdrv_unref(bs->file); 18760ac9377dSPaolo Bonzini bs->file = NULL; 187766f82ceeSKevin Wolf } 18789ca11154SPavel Hrdina } 187966f82ceeSKevin Wolf 1880a7f53e26SMarkus Armbruster if (bs->blk) { 1881a7f53e26SMarkus Armbruster blk_dev_change_media_cb(bs->blk, false); 1882a7f53e26SMarkus Armbruster } 188398f90dbaSZhi Yong Wu 188498f90dbaSZhi Yong Wu /*throttling disk I/O limits*/ 188598f90dbaSZhi Yong Wu if (bs->io_limits_enabled) { 188698f90dbaSZhi Yong Wu bdrv_io_limits_disable(bs); 188798f90dbaSZhi Yong Wu } 188833384421SMax Reitz 188933384421SMax Reitz QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) { 189033384421SMax Reitz g_free(ban); 189133384421SMax Reitz } 189233384421SMax Reitz QLIST_INIT(&bs->aio_notifiers); 1893b338082bSbellard } 1894b338082bSbellard 18952bc93fedSMORITA Kazutaka void bdrv_close_all(void) 18962bc93fedSMORITA Kazutaka { 18972bc93fedSMORITA Kazutaka BlockDriverState *bs; 18982bc93fedSMORITA Kazutaka 1899dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 1900ed78cda3SStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 1901ed78cda3SStefan Hajnoczi 1902ed78cda3SStefan Hajnoczi aio_context_acquire(aio_context); 19032bc93fedSMORITA Kazutaka bdrv_close(bs); 1904ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 19052bc93fedSMORITA Kazutaka } 19062bc93fedSMORITA Kazutaka } 19072bc93fedSMORITA Kazutaka 190888266f5aSStefan Hajnoczi /* Check if any requests are in-flight (including throttled requests) */ 190988266f5aSStefan Hajnoczi static bool bdrv_requests_pending(BlockDriverState *bs) 191088266f5aSStefan Hajnoczi { 191188266f5aSStefan Hajnoczi if (!QLIST_EMPTY(&bs->tracked_requests)) { 191288266f5aSStefan Hajnoczi return true; 191388266f5aSStefan Hajnoczi } 1914cc0681c4SBenoît Canet if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) { 1915cc0681c4SBenoît Canet return true; 1916cc0681c4SBenoît Canet } 1917cc0681c4SBenoît Canet if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) { 191888266f5aSStefan Hajnoczi return true; 191988266f5aSStefan Hajnoczi } 192088266f5aSStefan Hajnoczi if (bs->file && bdrv_requests_pending(bs->file)) { 192188266f5aSStefan Hajnoczi return true; 192288266f5aSStefan Hajnoczi } 192388266f5aSStefan Hajnoczi if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) { 192488266f5aSStefan Hajnoczi return true; 192588266f5aSStefan Hajnoczi } 192688266f5aSStefan Hajnoczi return false; 192788266f5aSStefan Hajnoczi } 192888266f5aSStefan Hajnoczi 19295b98db0aSStefan Hajnoczi static bool bdrv_drain_one(BlockDriverState *bs) 19305b98db0aSStefan Hajnoczi { 19315b98db0aSStefan Hajnoczi bool bs_busy; 19325b98db0aSStefan Hajnoczi 19335b98db0aSStefan Hajnoczi bdrv_flush_io_queue(bs); 19345b98db0aSStefan Hajnoczi bdrv_start_throttled_reqs(bs); 19355b98db0aSStefan Hajnoczi bs_busy = bdrv_requests_pending(bs); 19365b98db0aSStefan Hajnoczi bs_busy |= aio_poll(bdrv_get_aio_context(bs), bs_busy); 19375b98db0aSStefan Hajnoczi return bs_busy; 19385b98db0aSStefan Hajnoczi } 19395b98db0aSStefan Hajnoczi 19405b98db0aSStefan Hajnoczi /* 19415b98db0aSStefan Hajnoczi * Wait for pending requests to complete on a single BlockDriverState subtree 19425b98db0aSStefan Hajnoczi * 19435b98db0aSStefan Hajnoczi * See the warning in bdrv_drain_all(). This function can only be called if 19445b98db0aSStefan Hajnoczi * you are sure nothing can generate I/O because you have op blockers 19455b98db0aSStefan Hajnoczi * installed. 19465b98db0aSStefan Hajnoczi * 19475b98db0aSStefan Hajnoczi * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState 19485b98db0aSStefan Hajnoczi * AioContext. 19495b98db0aSStefan Hajnoczi */ 19505b98db0aSStefan Hajnoczi void bdrv_drain(BlockDriverState *bs) 19515b98db0aSStefan Hajnoczi { 19525b98db0aSStefan Hajnoczi while (bdrv_drain_one(bs)) { 19535b98db0aSStefan Hajnoczi /* Keep iterating */ 19545b98db0aSStefan Hajnoczi } 19555b98db0aSStefan Hajnoczi } 19565b98db0aSStefan Hajnoczi 1957922453bcSStefan Hajnoczi /* 1958922453bcSStefan Hajnoczi * Wait for pending requests to complete across all BlockDriverStates 1959922453bcSStefan Hajnoczi * 1960922453bcSStefan Hajnoczi * This function does not flush data to disk, use bdrv_flush_all() for that 1961922453bcSStefan Hajnoczi * after calling this function. 19624c355d53SZhi Yong Wu * 19634c355d53SZhi Yong Wu * Note that completion of an asynchronous I/O operation can trigger any 19644c355d53SZhi Yong Wu * number of other I/O operations on other devices---for example a coroutine 19654c355d53SZhi Yong Wu * can be arbitrarily complex and a constant flow of I/O can come until the 19664c355d53SZhi Yong Wu * coroutine is complete. Because of this, it is not possible to have a 19674c355d53SZhi Yong Wu * function to drain a single device's I/O queue. 1968922453bcSStefan Hajnoczi */ 1969922453bcSStefan Hajnoczi void bdrv_drain_all(void) 1970922453bcSStefan Hajnoczi { 197188266f5aSStefan Hajnoczi /* Always run first iteration so any pending completion BHs run */ 197288266f5aSStefan Hajnoczi bool busy = true; 1973922453bcSStefan Hajnoczi BlockDriverState *bs; 1974922453bcSStefan Hajnoczi 197588266f5aSStefan Hajnoczi while (busy) { 19769b536adcSStefan Hajnoczi busy = false; 1977922453bcSStefan Hajnoczi 19789b536adcSStefan Hajnoczi QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 19799b536adcSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 19809b536adcSStefan Hajnoczi 19819b536adcSStefan Hajnoczi aio_context_acquire(aio_context); 19825b98db0aSStefan Hajnoczi busy |= bdrv_drain_one(bs); 19839b536adcSStefan Hajnoczi aio_context_release(aio_context); 19849b536adcSStefan Hajnoczi } 1985922453bcSStefan Hajnoczi } 1986922453bcSStefan Hajnoczi } 1987922453bcSStefan Hajnoczi 1988dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and 1989dc364f4cSBenoît Canet * graph_bdrv_state list. 1990d22b2f41SRyan Harper Also, NULL terminate the device_name to prevent double remove */ 1991d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs) 1992d22b2f41SRyan Harper { 1993bfb197e0SMarkus Armbruster /* 1994bfb197e0SMarkus Armbruster * Take care to remove bs from bdrv_states only when it's actually 1995bfb197e0SMarkus Armbruster * in it. Note that bs->device_list.tqe_prev is initially null, 1996bfb197e0SMarkus Armbruster * and gets set to non-null by QTAILQ_INSERT_TAIL(). Establish 1997bfb197e0SMarkus Armbruster * the useful invariant "bs in bdrv_states iff bs->tqe_prev" by 1998bfb197e0SMarkus Armbruster * resetting it to null on remove. 1999bfb197e0SMarkus Armbruster */ 2000bfb197e0SMarkus Armbruster if (bs->device_list.tqe_prev) { 2001dc364f4cSBenoît Canet QTAILQ_REMOVE(&bdrv_states, bs, device_list); 2002bfb197e0SMarkus Armbruster bs->device_list.tqe_prev = NULL; 2003d22b2f41SRyan Harper } 2004dc364f4cSBenoît Canet if (bs->node_name[0] != '\0') { 2005dc364f4cSBenoît Canet QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list); 2006dc364f4cSBenoît Canet } 2007dc364f4cSBenoît Canet bs->node_name[0] = '\0'; 2008d22b2f41SRyan Harper } 2009d22b2f41SRyan Harper 2010e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs) 2011e023b2e2SPaolo Bonzini { 2012e023b2e2SPaolo Bonzini if (bs->drv && bs->drv->bdrv_rebind) { 2013e023b2e2SPaolo Bonzini bs->drv->bdrv_rebind(bs); 2014e023b2e2SPaolo Bonzini } 2015e023b2e2SPaolo Bonzini } 2016e023b2e2SPaolo Bonzini 20174ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest, 20184ddc07caSPaolo Bonzini BlockDriverState *bs_src) 20194ddc07caSPaolo Bonzini { 20204ddc07caSPaolo Bonzini /* move some fields that need to stay attached to the device */ 20214ddc07caSPaolo Bonzini 20224ddc07caSPaolo Bonzini /* dev info */ 20231b7fd729SPaolo Bonzini bs_dest->guest_block_size = bs_src->guest_block_size; 20244ddc07caSPaolo Bonzini bs_dest->copy_on_read = bs_src->copy_on_read; 20254ddc07caSPaolo Bonzini 20264ddc07caSPaolo Bonzini bs_dest->enable_write_cache = bs_src->enable_write_cache; 20274ddc07caSPaolo Bonzini 2028cc0681c4SBenoît Canet /* i/o throttled req */ 2029cc0681c4SBenoît Canet memcpy(&bs_dest->throttle_state, 2030cc0681c4SBenoît Canet &bs_src->throttle_state, 2031cc0681c4SBenoît Canet sizeof(ThrottleState)); 2032cc0681c4SBenoît Canet bs_dest->throttled_reqs[0] = bs_src->throttled_reqs[0]; 2033cc0681c4SBenoît Canet bs_dest->throttled_reqs[1] = bs_src->throttled_reqs[1]; 20344ddc07caSPaolo Bonzini bs_dest->io_limits_enabled = bs_src->io_limits_enabled; 20354ddc07caSPaolo Bonzini 20364ddc07caSPaolo Bonzini /* r/w error */ 20374ddc07caSPaolo Bonzini bs_dest->on_read_error = bs_src->on_read_error; 20384ddc07caSPaolo Bonzini bs_dest->on_write_error = bs_src->on_write_error; 20394ddc07caSPaolo Bonzini 20404ddc07caSPaolo Bonzini /* i/o status */ 20414ddc07caSPaolo Bonzini bs_dest->iostatus_enabled = bs_src->iostatus_enabled; 20424ddc07caSPaolo Bonzini bs_dest->iostatus = bs_src->iostatus; 20434ddc07caSPaolo Bonzini 20444ddc07caSPaolo Bonzini /* dirty bitmap */ 2045e4654d2dSFam Zheng bs_dest->dirty_bitmaps = bs_src->dirty_bitmaps; 20464ddc07caSPaolo Bonzini 20479fcb0251SFam Zheng /* reference count */ 20489fcb0251SFam Zheng bs_dest->refcnt = bs_src->refcnt; 20499fcb0251SFam Zheng 20504ddc07caSPaolo Bonzini /* job */ 20514ddc07caSPaolo Bonzini bs_dest->job = bs_src->job; 20524ddc07caSPaolo Bonzini 20534ddc07caSPaolo Bonzini /* keep the same entry in bdrv_states */ 2054dc364f4cSBenoît Canet bs_dest->device_list = bs_src->device_list; 20557e7d56d9SMarkus Armbruster bs_dest->blk = bs_src->blk; 20567e7d56d9SMarkus Armbruster 2057fbe40ff7SFam Zheng memcpy(bs_dest->op_blockers, bs_src->op_blockers, 2058fbe40ff7SFam Zheng sizeof(bs_dest->op_blockers)); 20594ddc07caSPaolo Bonzini } 20604ddc07caSPaolo Bonzini 20614ddc07caSPaolo Bonzini /* 20624ddc07caSPaolo Bonzini * Swap bs contents for two image chains while they are live, 20634ddc07caSPaolo Bonzini * while keeping required fields on the BlockDriverState that is 20644ddc07caSPaolo Bonzini * actually attached to a device. 20654ddc07caSPaolo Bonzini * 20664ddc07caSPaolo Bonzini * This will modify the BlockDriverState fields, and swap contents 20674ddc07caSPaolo Bonzini * between bs_new and bs_old. Both bs_new and bs_old are modified. 20684ddc07caSPaolo Bonzini * 2069bfb197e0SMarkus Armbruster * bs_new must not be attached to a BlockBackend. 20704ddc07caSPaolo Bonzini * 20714ddc07caSPaolo Bonzini * This function does not create any image files. 20724ddc07caSPaolo Bonzini */ 20734ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old) 20744ddc07caSPaolo Bonzini { 20754ddc07caSPaolo Bonzini BlockDriverState tmp; 20764ddc07caSPaolo Bonzini 207790ce8a06SBenoît Canet /* The code needs to swap the node_name but simply swapping node_list won't 207890ce8a06SBenoît Canet * work so first remove the nodes from the graph list, do the swap then 207990ce8a06SBenoît Canet * insert them back if needed. 208090ce8a06SBenoît Canet */ 208190ce8a06SBenoît Canet if (bs_new->node_name[0] != '\0') { 208290ce8a06SBenoît Canet QTAILQ_REMOVE(&graph_bdrv_states, bs_new, node_list); 208390ce8a06SBenoît Canet } 208490ce8a06SBenoît Canet if (bs_old->node_name[0] != '\0') { 208590ce8a06SBenoît Canet QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list); 208690ce8a06SBenoît Canet } 208790ce8a06SBenoît Canet 2088bfb197e0SMarkus Armbruster /* bs_new must be unattached and shouldn't have anything fancy enabled */ 20897e7d56d9SMarkus Armbruster assert(!bs_new->blk); 2090e4654d2dSFam Zheng assert(QLIST_EMPTY(&bs_new->dirty_bitmaps)); 20914ddc07caSPaolo Bonzini assert(bs_new->job == NULL); 20924ddc07caSPaolo Bonzini assert(bs_new->io_limits_enabled == false); 2093cc0681c4SBenoît Canet assert(!throttle_have_timer(&bs_new->throttle_state)); 20944ddc07caSPaolo Bonzini 20954ddc07caSPaolo Bonzini tmp = *bs_new; 20964ddc07caSPaolo Bonzini *bs_new = *bs_old; 20974ddc07caSPaolo Bonzini *bs_old = tmp; 20984ddc07caSPaolo Bonzini 20994ddc07caSPaolo Bonzini /* there are some fields that should not be swapped, move them back */ 21004ddc07caSPaolo Bonzini bdrv_move_feature_fields(&tmp, bs_old); 21014ddc07caSPaolo Bonzini bdrv_move_feature_fields(bs_old, bs_new); 21024ddc07caSPaolo Bonzini bdrv_move_feature_fields(bs_new, &tmp); 21034ddc07caSPaolo Bonzini 2104bfb197e0SMarkus Armbruster /* bs_new must remain unattached */ 21057e7d56d9SMarkus Armbruster assert(!bs_new->blk); 21064ddc07caSPaolo Bonzini 21074ddc07caSPaolo Bonzini /* Check a few fields that should remain attached to the device */ 21084ddc07caSPaolo Bonzini assert(bs_new->job == NULL); 21094ddc07caSPaolo Bonzini assert(bs_new->io_limits_enabled == false); 2110cc0681c4SBenoît Canet assert(!throttle_have_timer(&bs_new->throttle_state)); 21114ddc07caSPaolo Bonzini 211290ce8a06SBenoît Canet /* insert the nodes back into the graph node list if needed */ 211390ce8a06SBenoît Canet if (bs_new->node_name[0] != '\0') { 211490ce8a06SBenoît Canet QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_new, node_list); 211590ce8a06SBenoît Canet } 211690ce8a06SBenoît Canet if (bs_old->node_name[0] != '\0') { 211790ce8a06SBenoît Canet QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_old, node_list); 211890ce8a06SBenoît Canet } 211990ce8a06SBenoît Canet 21204ddc07caSPaolo Bonzini bdrv_rebind(bs_new); 21214ddc07caSPaolo Bonzini bdrv_rebind(bs_old); 21224ddc07caSPaolo Bonzini } 21234ddc07caSPaolo Bonzini 21248802d1fdSJeff Cody /* 21258802d1fdSJeff Cody * Add new bs contents at the top of an image chain while the chain is 21268802d1fdSJeff Cody * live, while keeping required fields on the top layer. 21278802d1fdSJeff Cody * 21288802d1fdSJeff Cody * This will modify the BlockDriverState fields, and swap contents 21298802d1fdSJeff Cody * between bs_new and bs_top. Both bs_new and bs_top are modified. 21308802d1fdSJeff Cody * 2131bfb197e0SMarkus Armbruster * bs_new must not be attached to a BlockBackend. 2132f6801b83SJeff Cody * 21338802d1fdSJeff Cody * This function does not create any image files. 21348802d1fdSJeff Cody */ 21358802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top) 21368802d1fdSJeff Cody { 21374ddc07caSPaolo Bonzini bdrv_swap(bs_new, bs_top); 21388802d1fdSJeff Cody 21398802d1fdSJeff Cody /* The contents of 'tmp' will become bs_top, as we are 21408802d1fdSJeff Cody * swapping bs_new and bs_top contents. */ 21418d24cce1SFam Zheng bdrv_set_backing_hd(bs_top, bs_new); 21428802d1fdSJeff Cody } 21438802d1fdSJeff Cody 21444f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs) 2145b338082bSbellard { 21463e914655SPaolo Bonzini assert(!bs->job); 21473718d8abSFam Zheng assert(bdrv_op_blocker_is_empty(bs)); 21484f6fd349SFam Zheng assert(!bs->refcnt); 2149e4654d2dSFam Zheng assert(QLIST_EMPTY(&bs->dirty_bitmaps)); 215018846deeSMarkus Armbruster 2151e1b5c52eSStefan Hajnoczi bdrv_close(bs); 2152e1b5c52eSStefan Hajnoczi 21531b7bdbc1SStefan Hajnoczi /* remove from list, if necessary */ 2154d22b2f41SRyan Harper bdrv_make_anon(bs); 215534c6f050Saurel32 21567267c094SAnthony Liguori g_free(bs); 2157fc01f7e7Sbellard } 2158fc01f7e7Sbellard 2159e97fc193Saliguori /* 2160e97fc193Saliguori * Run consistency checks on an image 2161e97fc193Saliguori * 2162e076f338SKevin Wolf * Returns 0 if the check could be completed (it doesn't mean that the image is 2163a1c7273bSStefan Weil * free of errors) or -errno when an internal error occurred. The results of the 2164e076f338SKevin Wolf * check are stored in res. 2165e97fc193Saliguori */ 21664534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix) 2167e97fc193Saliguori { 2168908bcd54SMax Reitz if (bs->drv == NULL) { 2169908bcd54SMax Reitz return -ENOMEDIUM; 2170908bcd54SMax Reitz } 2171e97fc193Saliguori if (bs->drv->bdrv_check == NULL) { 2172e97fc193Saliguori return -ENOTSUP; 2173e97fc193Saliguori } 2174e97fc193Saliguori 2175e076f338SKevin Wolf memset(res, 0, sizeof(*res)); 21764534ff54SKevin Wolf return bs->drv->bdrv_check(bs, res, fix); 2177e97fc193Saliguori } 2178e97fc193Saliguori 21798a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048 21808a426614SKevin Wolf 218133e3963eSbellard /* commit COW file into the raw image */ 218233e3963eSbellard int bdrv_commit(BlockDriverState *bs) 218333e3963eSbellard { 218419cb3738Sbellard BlockDriver *drv = bs->drv; 218572706ea4SJeff Cody int64_t sector, total_sectors, length, backing_length; 21868a426614SKevin Wolf int n, ro, open_flags; 21870bce597dSJeff Cody int ret = 0; 218872706ea4SJeff Cody uint8_t *buf = NULL; 2189c2cba3d9SJim Meyering char filename[PATH_MAX]; 219033e3963eSbellard 219119cb3738Sbellard if (!drv) 219219cb3738Sbellard return -ENOMEDIUM; 219333e3963eSbellard 21944dca4b63SNaphtali Sprei if (!bs->backing_hd) { 21954dca4b63SNaphtali Sprei return -ENOTSUP; 21964dca4b63SNaphtali Sprei } 21974dca4b63SNaphtali Sprei 21983718d8abSFam Zheng if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, NULL) || 21993718d8abSFam Zheng bdrv_op_is_blocked(bs->backing_hd, BLOCK_OP_TYPE_COMMIT, NULL)) { 22002d3735d3SStefan Hajnoczi return -EBUSY; 22012d3735d3SStefan Hajnoczi } 22022d3735d3SStefan Hajnoczi 22034dca4b63SNaphtali Sprei ro = bs->backing_hd->read_only; 2204c2cba3d9SJim Meyering /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */ 2205c2cba3d9SJim Meyering pstrcpy(filename, sizeof(filename), bs->backing_hd->filename); 22064dca4b63SNaphtali Sprei open_flags = bs->backing_hd->open_flags; 22074dca4b63SNaphtali Sprei 22084dca4b63SNaphtali Sprei if (ro) { 22090bce597dSJeff Cody if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) { 22100bce597dSJeff Cody return -EACCES; 22114dca4b63SNaphtali Sprei } 2212ea2384d3Sbellard } 2213ea2384d3Sbellard 221472706ea4SJeff Cody length = bdrv_getlength(bs); 221572706ea4SJeff Cody if (length < 0) { 221672706ea4SJeff Cody ret = length; 221772706ea4SJeff Cody goto ro_cleanup; 221872706ea4SJeff Cody } 221972706ea4SJeff Cody 222072706ea4SJeff Cody backing_length = bdrv_getlength(bs->backing_hd); 222172706ea4SJeff Cody if (backing_length < 0) { 222272706ea4SJeff Cody ret = backing_length; 222372706ea4SJeff Cody goto ro_cleanup; 222472706ea4SJeff Cody } 222572706ea4SJeff Cody 222672706ea4SJeff Cody /* If our top snapshot is larger than the backing file image, 222772706ea4SJeff Cody * grow the backing file image if possible. If not possible, 222872706ea4SJeff Cody * we must return an error */ 222972706ea4SJeff Cody if (length > backing_length) { 223072706ea4SJeff Cody ret = bdrv_truncate(bs->backing_hd, length); 223172706ea4SJeff Cody if (ret < 0) { 223272706ea4SJeff Cody goto ro_cleanup; 223372706ea4SJeff Cody } 223472706ea4SJeff Cody } 223572706ea4SJeff Cody 223672706ea4SJeff Cody total_sectors = length >> BDRV_SECTOR_BITS; 2237857d4f46SKevin Wolf 2238857d4f46SKevin Wolf /* qemu_try_blockalign() for bs will choose an alignment that works for 2239857d4f46SKevin Wolf * bs->backing_hd as well, so no need to compare the alignment manually. */ 2240857d4f46SKevin Wolf buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE); 2241857d4f46SKevin Wolf if (buf == NULL) { 2242857d4f46SKevin Wolf ret = -ENOMEM; 2243857d4f46SKevin Wolf goto ro_cleanup; 2244857d4f46SKevin Wolf } 22458a426614SKevin Wolf 22468a426614SKevin Wolf for (sector = 0; sector < total_sectors; sector += n) { 2247d663640cSPaolo Bonzini ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n); 2248d663640cSPaolo Bonzini if (ret < 0) { 2249d663640cSPaolo Bonzini goto ro_cleanup; 2250d663640cSPaolo Bonzini } 2251d663640cSPaolo Bonzini if (ret) { 2252dabfa6ccSKevin Wolf ret = bdrv_read(bs, sector, buf, n); 2253dabfa6ccSKevin Wolf if (ret < 0) { 22544dca4b63SNaphtali Sprei goto ro_cleanup; 225533e3963eSbellard } 225633e3963eSbellard 2257dabfa6ccSKevin Wolf ret = bdrv_write(bs->backing_hd, sector, buf, n); 2258dabfa6ccSKevin Wolf if (ret < 0) { 22594dca4b63SNaphtali Sprei goto ro_cleanup; 226033e3963eSbellard } 226133e3963eSbellard } 226233e3963eSbellard } 226395389c86Sbellard 22641d44952fSChristoph Hellwig if (drv->bdrv_make_empty) { 22651d44952fSChristoph Hellwig ret = drv->bdrv_make_empty(bs); 2266dabfa6ccSKevin Wolf if (ret < 0) { 2267dabfa6ccSKevin Wolf goto ro_cleanup; 2268dabfa6ccSKevin Wolf } 22691d44952fSChristoph Hellwig bdrv_flush(bs); 22701d44952fSChristoph Hellwig } 227195389c86Sbellard 22723f5075aeSChristoph Hellwig /* 22733f5075aeSChristoph Hellwig * Make sure all data we wrote to the backing device is actually 22743f5075aeSChristoph Hellwig * stable on disk. 22753f5075aeSChristoph Hellwig */ 2276dabfa6ccSKevin Wolf if (bs->backing_hd) { 22773f5075aeSChristoph Hellwig bdrv_flush(bs->backing_hd); 2278dabfa6ccSKevin Wolf } 22794dca4b63SNaphtali Sprei 2280dabfa6ccSKevin Wolf ret = 0; 22814dca4b63SNaphtali Sprei ro_cleanup: 2282857d4f46SKevin Wolf qemu_vfree(buf); 22834dca4b63SNaphtali Sprei 22844dca4b63SNaphtali Sprei if (ro) { 22850bce597dSJeff Cody /* ignoring error return here */ 22860bce597dSJeff Cody bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL); 22874dca4b63SNaphtali Sprei } 22884dca4b63SNaphtali Sprei 22891d44952fSChristoph Hellwig return ret; 229033e3963eSbellard } 229133e3963eSbellard 2292e8877497SStefan Hajnoczi int bdrv_commit_all(void) 22936ab4b5abSMarkus Armbruster { 22946ab4b5abSMarkus Armbruster BlockDriverState *bs; 22956ab4b5abSMarkus Armbruster 2296dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 2297ed78cda3SStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 2298ed78cda3SStefan Hajnoczi 2299ed78cda3SStefan Hajnoczi aio_context_acquire(aio_context); 2300272d2d8eSJeff Cody if (bs->drv && bs->backing_hd) { 2301e8877497SStefan Hajnoczi int ret = bdrv_commit(bs); 2302e8877497SStefan Hajnoczi if (ret < 0) { 2303ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 2304e8877497SStefan Hajnoczi return ret; 23056ab4b5abSMarkus Armbruster } 23066ab4b5abSMarkus Armbruster } 2307ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 2308272d2d8eSJeff Cody } 2309e8877497SStefan Hajnoczi return 0; 2310e8877497SStefan Hajnoczi } 23116ab4b5abSMarkus Armbruster 2312dbffbdcfSStefan Hajnoczi /** 2313dbffbdcfSStefan Hajnoczi * Remove an active request from the tracked requests list 2314dbffbdcfSStefan Hajnoczi * 2315dbffbdcfSStefan Hajnoczi * This function should be called when a tracked request is completing. 2316dbffbdcfSStefan Hajnoczi */ 2317dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req) 2318dbffbdcfSStefan Hajnoczi { 23192dbafdc0SKevin Wolf if (req->serialising) { 23202dbafdc0SKevin Wolf req->bs->serialising_in_flight--; 23212dbafdc0SKevin Wolf } 23222dbafdc0SKevin Wolf 2323dbffbdcfSStefan Hajnoczi QLIST_REMOVE(req, list); 2324f4658285SStefan Hajnoczi qemu_co_queue_restart_all(&req->wait_queue); 2325dbffbdcfSStefan Hajnoczi } 2326dbffbdcfSStefan Hajnoczi 2327dbffbdcfSStefan Hajnoczi /** 2328dbffbdcfSStefan Hajnoczi * Add an active request to the tracked requests list 2329dbffbdcfSStefan Hajnoczi */ 2330dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req, 2331dbffbdcfSStefan Hajnoczi BlockDriverState *bs, 2332793ed47aSKevin Wolf int64_t offset, 2333793ed47aSKevin Wolf unsigned int bytes, bool is_write) 2334dbffbdcfSStefan Hajnoczi { 2335dbffbdcfSStefan Hajnoczi *req = (BdrvTrackedRequest){ 2336dbffbdcfSStefan Hajnoczi .bs = bs, 2337793ed47aSKevin Wolf .offset = offset, 2338793ed47aSKevin Wolf .bytes = bytes, 2339dbffbdcfSStefan Hajnoczi .is_write = is_write, 23405f8b6491SStefan Hajnoczi .co = qemu_coroutine_self(), 23412dbafdc0SKevin Wolf .serialising = false, 23427327145fSKevin Wolf .overlap_offset = offset, 23437327145fSKevin Wolf .overlap_bytes = bytes, 2344dbffbdcfSStefan Hajnoczi }; 2345dbffbdcfSStefan Hajnoczi 2346f4658285SStefan Hajnoczi qemu_co_queue_init(&req->wait_queue); 2347f4658285SStefan Hajnoczi 2348dbffbdcfSStefan Hajnoczi QLIST_INSERT_HEAD(&bs->tracked_requests, req, list); 2349dbffbdcfSStefan Hajnoczi } 2350dbffbdcfSStefan Hajnoczi 2351e96126ffSKevin Wolf static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align) 23522dbafdc0SKevin Wolf { 23537327145fSKevin Wolf int64_t overlap_offset = req->offset & ~(align - 1); 2354e96126ffSKevin Wolf unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align) 23557327145fSKevin Wolf - overlap_offset; 23567327145fSKevin Wolf 23572dbafdc0SKevin Wolf if (!req->serialising) { 23582dbafdc0SKevin Wolf req->bs->serialising_in_flight++; 23592dbafdc0SKevin Wolf req->serialising = true; 23602dbafdc0SKevin Wolf } 23617327145fSKevin Wolf 23627327145fSKevin Wolf req->overlap_offset = MIN(req->overlap_offset, overlap_offset); 23637327145fSKevin Wolf req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes); 23642dbafdc0SKevin Wolf } 23652dbafdc0SKevin Wolf 2366d83947acSStefan Hajnoczi /** 2367d83947acSStefan Hajnoczi * Round a region to cluster boundaries 2368d83947acSStefan Hajnoczi */ 2369343bded4SPaolo Bonzini void bdrv_round_to_clusters(BlockDriverState *bs, 2370d83947acSStefan Hajnoczi int64_t sector_num, int nb_sectors, 2371d83947acSStefan Hajnoczi int64_t *cluster_sector_num, 2372d83947acSStefan Hajnoczi int *cluster_nb_sectors) 2373d83947acSStefan Hajnoczi { 2374d83947acSStefan Hajnoczi BlockDriverInfo bdi; 2375d83947acSStefan Hajnoczi 2376d83947acSStefan Hajnoczi if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) { 2377d83947acSStefan Hajnoczi *cluster_sector_num = sector_num; 2378d83947acSStefan Hajnoczi *cluster_nb_sectors = nb_sectors; 2379d83947acSStefan Hajnoczi } else { 2380d83947acSStefan Hajnoczi int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE; 2381d83947acSStefan Hajnoczi *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c); 2382d83947acSStefan Hajnoczi *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num + 2383d83947acSStefan Hajnoczi nb_sectors, c); 2384d83947acSStefan Hajnoczi } 2385d83947acSStefan Hajnoczi } 2386d83947acSStefan Hajnoczi 23877327145fSKevin Wolf static int bdrv_get_cluster_size(BlockDriverState *bs) 2388793ed47aSKevin Wolf { 2389793ed47aSKevin Wolf BlockDriverInfo bdi; 23907327145fSKevin Wolf int ret; 2391793ed47aSKevin Wolf 23927327145fSKevin Wolf ret = bdrv_get_info(bs, &bdi); 23937327145fSKevin Wolf if (ret < 0 || bdi.cluster_size == 0) { 23947327145fSKevin Wolf return bs->request_alignment; 2395793ed47aSKevin Wolf } else { 23967327145fSKevin Wolf return bdi.cluster_size; 2397793ed47aSKevin Wolf } 2398793ed47aSKevin Wolf } 2399793ed47aSKevin Wolf 2400f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req, 2401793ed47aSKevin Wolf int64_t offset, unsigned int bytes) 2402793ed47aSKevin Wolf { 2403d83947acSStefan Hajnoczi /* aaaa bbbb */ 24047327145fSKevin Wolf if (offset >= req->overlap_offset + req->overlap_bytes) { 2405d83947acSStefan Hajnoczi return false; 2406d83947acSStefan Hajnoczi } 2407d83947acSStefan Hajnoczi /* bbbb aaaa */ 24087327145fSKevin Wolf if (req->overlap_offset >= offset + bytes) { 2409d83947acSStefan Hajnoczi return false; 2410d83947acSStefan Hajnoczi } 2411d83947acSStefan Hajnoczi return true; 2412f4658285SStefan Hajnoczi } 2413f4658285SStefan Hajnoczi 241428de2dcdSKevin Wolf static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self) 2415f4658285SStefan Hajnoczi { 24162dbafdc0SKevin Wolf BlockDriverState *bs = self->bs; 2417f4658285SStefan Hajnoczi BdrvTrackedRequest *req; 2418f4658285SStefan Hajnoczi bool retry; 241928de2dcdSKevin Wolf bool waited = false; 2420f4658285SStefan Hajnoczi 24212dbafdc0SKevin Wolf if (!bs->serialising_in_flight) { 242228de2dcdSKevin Wolf return false; 24232dbafdc0SKevin Wolf } 24242dbafdc0SKevin Wolf 2425f4658285SStefan Hajnoczi do { 2426f4658285SStefan Hajnoczi retry = false; 2427f4658285SStefan Hajnoczi QLIST_FOREACH(req, &bs->tracked_requests, list) { 24282dbafdc0SKevin Wolf if (req == self || (!req->serialising && !self->serialising)) { 242965afd211SKevin Wolf continue; 243065afd211SKevin Wolf } 24317327145fSKevin Wolf if (tracked_request_overlaps(req, self->overlap_offset, 24327327145fSKevin Wolf self->overlap_bytes)) 24337327145fSKevin Wolf { 24345f8b6491SStefan Hajnoczi /* Hitting this means there was a reentrant request, for 24355f8b6491SStefan Hajnoczi * example, a block driver issuing nested requests. This must 24365f8b6491SStefan Hajnoczi * never happen since it means deadlock. 24375f8b6491SStefan Hajnoczi */ 24385f8b6491SStefan Hajnoczi assert(qemu_coroutine_self() != req->co); 24395f8b6491SStefan Hajnoczi 24406460440fSKevin Wolf /* If the request is already (indirectly) waiting for us, or 24416460440fSKevin Wolf * will wait for us as soon as it wakes up, then just go on 24426460440fSKevin Wolf * (instead of producing a deadlock in the former case). */ 24436460440fSKevin Wolf if (!req->waiting_for) { 24446460440fSKevin Wolf self->waiting_for = req; 2445f4658285SStefan Hajnoczi qemu_co_queue_wait(&req->wait_queue); 24466460440fSKevin Wolf self->waiting_for = NULL; 2447f4658285SStefan Hajnoczi retry = true; 244828de2dcdSKevin Wolf waited = true; 2449f4658285SStefan Hajnoczi break; 2450f4658285SStefan Hajnoczi } 2451f4658285SStefan Hajnoczi } 24526460440fSKevin Wolf } 2453f4658285SStefan Hajnoczi } while (retry); 245428de2dcdSKevin Wolf 245528de2dcdSKevin Wolf return waited; 2456f4658285SStefan Hajnoczi } 2457f4658285SStefan Hajnoczi 2458756e6736SKevin Wolf /* 2459756e6736SKevin Wolf * Return values: 2460756e6736SKevin Wolf * 0 - success 2461756e6736SKevin Wolf * -EINVAL - backing format specified, but no file 2462756e6736SKevin Wolf * -ENOSPC - can't update the backing file because no space is left in the 2463756e6736SKevin Wolf * image file header 2464756e6736SKevin Wolf * -ENOTSUP - format driver doesn't support changing the backing file 2465756e6736SKevin Wolf */ 2466756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs, 2467756e6736SKevin Wolf const char *backing_file, const char *backing_fmt) 2468756e6736SKevin Wolf { 2469756e6736SKevin Wolf BlockDriver *drv = bs->drv; 2470469ef350SPaolo Bonzini int ret; 2471756e6736SKevin Wolf 24725f377794SPaolo Bonzini /* Backing file format doesn't make sense without a backing file */ 24735f377794SPaolo Bonzini if (backing_fmt && !backing_file) { 24745f377794SPaolo Bonzini return -EINVAL; 24755f377794SPaolo Bonzini } 24765f377794SPaolo Bonzini 2477756e6736SKevin Wolf if (drv->bdrv_change_backing_file != NULL) { 2478469ef350SPaolo Bonzini ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt); 2479756e6736SKevin Wolf } else { 2480469ef350SPaolo Bonzini ret = -ENOTSUP; 2481756e6736SKevin Wolf } 2482469ef350SPaolo Bonzini 2483469ef350SPaolo Bonzini if (ret == 0) { 2484469ef350SPaolo Bonzini pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: ""); 2485469ef350SPaolo Bonzini pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: ""); 2486469ef350SPaolo Bonzini } 2487469ef350SPaolo Bonzini return ret; 2488756e6736SKevin Wolf } 2489756e6736SKevin Wolf 24906ebdcee2SJeff Cody /* 24916ebdcee2SJeff Cody * Finds the image layer in the chain that has 'bs' as its backing file. 24926ebdcee2SJeff Cody * 24936ebdcee2SJeff Cody * active is the current topmost image. 24946ebdcee2SJeff Cody * 24956ebdcee2SJeff Cody * Returns NULL if bs is not found in active's image chain, 24966ebdcee2SJeff Cody * or if active == bs. 24974caf0fcdSJeff Cody * 24984caf0fcdSJeff Cody * Returns the bottommost base image if bs == NULL. 24996ebdcee2SJeff Cody */ 25006ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active, 25016ebdcee2SJeff Cody BlockDriverState *bs) 25026ebdcee2SJeff Cody { 25034caf0fcdSJeff Cody while (active && bs != active->backing_hd) { 25044caf0fcdSJeff Cody active = active->backing_hd; 25056ebdcee2SJeff Cody } 25066ebdcee2SJeff Cody 25074caf0fcdSJeff Cody return active; 25086ebdcee2SJeff Cody } 25096ebdcee2SJeff Cody 25104caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */ 25114caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs) 25124caf0fcdSJeff Cody { 25134caf0fcdSJeff Cody return bdrv_find_overlay(bs, NULL); 25146ebdcee2SJeff Cody } 25156ebdcee2SJeff Cody 25166ebdcee2SJeff Cody typedef struct BlkIntermediateStates { 25176ebdcee2SJeff Cody BlockDriverState *bs; 25186ebdcee2SJeff Cody QSIMPLEQ_ENTRY(BlkIntermediateStates) entry; 25196ebdcee2SJeff Cody } BlkIntermediateStates; 25206ebdcee2SJeff Cody 25216ebdcee2SJeff Cody 25226ebdcee2SJeff Cody /* 25236ebdcee2SJeff Cody * Drops images above 'base' up to and including 'top', and sets the image 25246ebdcee2SJeff Cody * above 'top' to have base as its backing file. 25256ebdcee2SJeff Cody * 25266ebdcee2SJeff Cody * Requires that the overlay to 'top' is opened r/w, so that the backing file 25276ebdcee2SJeff Cody * information in 'bs' can be properly updated. 25286ebdcee2SJeff Cody * 25296ebdcee2SJeff Cody * E.g., this will convert the following chain: 25306ebdcee2SJeff Cody * bottom <- base <- intermediate <- top <- active 25316ebdcee2SJeff Cody * 25326ebdcee2SJeff Cody * to 25336ebdcee2SJeff Cody * 25346ebdcee2SJeff Cody * bottom <- base <- active 25356ebdcee2SJeff Cody * 25366ebdcee2SJeff Cody * It is allowed for bottom==base, in which case it converts: 25376ebdcee2SJeff Cody * 25386ebdcee2SJeff Cody * base <- intermediate <- top <- active 25396ebdcee2SJeff Cody * 25406ebdcee2SJeff Cody * to 25416ebdcee2SJeff Cody * 25426ebdcee2SJeff Cody * base <- active 25436ebdcee2SJeff Cody * 254454e26900SJeff Cody * If backing_file_str is non-NULL, it will be used when modifying top's 254554e26900SJeff Cody * overlay image metadata. 254654e26900SJeff Cody * 25476ebdcee2SJeff Cody * Error conditions: 25486ebdcee2SJeff Cody * if active == top, that is considered an error 25496ebdcee2SJeff Cody * 25506ebdcee2SJeff Cody */ 25516ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top, 255254e26900SJeff Cody BlockDriverState *base, const char *backing_file_str) 25536ebdcee2SJeff Cody { 25546ebdcee2SJeff Cody BlockDriverState *intermediate; 25556ebdcee2SJeff Cody BlockDriverState *base_bs = NULL; 25566ebdcee2SJeff Cody BlockDriverState *new_top_bs = NULL; 25576ebdcee2SJeff Cody BlkIntermediateStates *intermediate_state, *next; 25586ebdcee2SJeff Cody int ret = -EIO; 25596ebdcee2SJeff Cody 25606ebdcee2SJeff Cody QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete; 25616ebdcee2SJeff Cody QSIMPLEQ_INIT(&states_to_delete); 25626ebdcee2SJeff Cody 25636ebdcee2SJeff Cody if (!top->drv || !base->drv) { 25646ebdcee2SJeff Cody goto exit; 25656ebdcee2SJeff Cody } 25666ebdcee2SJeff Cody 25676ebdcee2SJeff Cody new_top_bs = bdrv_find_overlay(active, top); 25686ebdcee2SJeff Cody 25696ebdcee2SJeff Cody if (new_top_bs == NULL) { 25706ebdcee2SJeff Cody /* we could not find the image above 'top', this is an error */ 25716ebdcee2SJeff Cody goto exit; 25726ebdcee2SJeff Cody } 25736ebdcee2SJeff Cody 25746ebdcee2SJeff Cody /* special case of new_top_bs->backing_hd already pointing to base - nothing 25756ebdcee2SJeff Cody * to do, no intermediate images */ 25766ebdcee2SJeff Cody if (new_top_bs->backing_hd == base) { 25776ebdcee2SJeff Cody ret = 0; 25786ebdcee2SJeff Cody goto exit; 25796ebdcee2SJeff Cody } 25806ebdcee2SJeff Cody 25816ebdcee2SJeff Cody intermediate = top; 25826ebdcee2SJeff Cody 25836ebdcee2SJeff Cody /* now we will go down through the list, and add each BDS we find 25846ebdcee2SJeff Cody * into our deletion queue, until we hit the 'base' 25856ebdcee2SJeff Cody */ 25866ebdcee2SJeff Cody while (intermediate) { 25875839e53bSMarkus Armbruster intermediate_state = g_new0(BlkIntermediateStates, 1); 25886ebdcee2SJeff Cody intermediate_state->bs = intermediate; 25896ebdcee2SJeff Cody QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry); 25906ebdcee2SJeff Cody 25916ebdcee2SJeff Cody if (intermediate->backing_hd == base) { 25926ebdcee2SJeff Cody base_bs = intermediate->backing_hd; 25936ebdcee2SJeff Cody break; 25946ebdcee2SJeff Cody } 25956ebdcee2SJeff Cody intermediate = intermediate->backing_hd; 25966ebdcee2SJeff Cody } 25976ebdcee2SJeff Cody if (base_bs == NULL) { 25986ebdcee2SJeff Cody /* something went wrong, we did not end at the base. safely 25996ebdcee2SJeff Cody * unravel everything, and exit with error */ 26006ebdcee2SJeff Cody goto exit; 26016ebdcee2SJeff Cody } 26026ebdcee2SJeff Cody 26036ebdcee2SJeff Cody /* success - we can delete the intermediate states, and link top->base */ 260454e26900SJeff Cody backing_file_str = backing_file_str ? backing_file_str : base_bs->filename; 260554e26900SJeff Cody ret = bdrv_change_backing_file(new_top_bs, backing_file_str, 26066ebdcee2SJeff Cody base_bs->drv ? base_bs->drv->format_name : ""); 26076ebdcee2SJeff Cody if (ret) { 26086ebdcee2SJeff Cody goto exit; 26096ebdcee2SJeff Cody } 2610920beae1SFam Zheng bdrv_set_backing_hd(new_top_bs, base_bs); 26116ebdcee2SJeff Cody 26126ebdcee2SJeff Cody QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) { 26136ebdcee2SJeff Cody /* so that bdrv_close() does not recursively close the chain */ 2614920beae1SFam Zheng bdrv_set_backing_hd(intermediate_state->bs, NULL); 26154f6fd349SFam Zheng bdrv_unref(intermediate_state->bs); 26166ebdcee2SJeff Cody } 26176ebdcee2SJeff Cody ret = 0; 26186ebdcee2SJeff Cody 26196ebdcee2SJeff Cody exit: 26206ebdcee2SJeff Cody QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) { 26216ebdcee2SJeff Cody g_free(intermediate_state); 26226ebdcee2SJeff Cody } 26236ebdcee2SJeff Cody return ret; 26246ebdcee2SJeff Cody } 26256ebdcee2SJeff Cody 26266ebdcee2SJeff Cody 262771d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset, 262871d0770cSaliguori size_t size) 262971d0770cSaliguori { 263071d0770cSaliguori int64_t len; 263171d0770cSaliguori 26321dd3a447SKevin Wolf if (size > INT_MAX) { 26331dd3a447SKevin Wolf return -EIO; 26341dd3a447SKevin Wolf } 26351dd3a447SKevin Wolf 263671d0770cSaliguori if (!bdrv_is_inserted(bs)) 263771d0770cSaliguori return -ENOMEDIUM; 263871d0770cSaliguori 263971d0770cSaliguori if (bs->growable) 264071d0770cSaliguori return 0; 264171d0770cSaliguori 264271d0770cSaliguori len = bdrv_getlength(bs); 264371d0770cSaliguori 2644fbb7b4e0SKevin Wolf if (offset < 0) 2645fbb7b4e0SKevin Wolf return -EIO; 2646fbb7b4e0SKevin Wolf 2647fbb7b4e0SKevin Wolf if ((offset > len) || (len - offset < size)) 264871d0770cSaliguori return -EIO; 264971d0770cSaliguori 265071d0770cSaliguori return 0; 265171d0770cSaliguori } 265271d0770cSaliguori 265371d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num, 265471d0770cSaliguori int nb_sectors) 265571d0770cSaliguori { 265654db38a4SKevin Wolf if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) { 26578f4754edSKevin Wolf return -EIO; 26588f4754edSKevin Wolf } 26598f4754edSKevin Wolf 2660eb5a3165SJes Sorensen return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE, 2661eb5a3165SJes Sorensen nb_sectors * BDRV_SECTOR_SIZE); 266271d0770cSaliguori } 266371d0770cSaliguori 26641c9805a3SStefan Hajnoczi typedef struct RwCo { 26651c9805a3SStefan Hajnoczi BlockDriverState *bs; 2666775aa8b6SKevin Wolf int64_t offset; 26671c9805a3SStefan Hajnoczi QEMUIOVector *qiov; 26681c9805a3SStefan Hajnoczi bool is_write; 26691c9805a3SStefan Hajnoczi int ret; 26704105eaaaSPeter Lieven BdrvRequestFlags flags; 26711c9805a3SStefan Hajnoczi } RwCo; 26721c9805a3SStefan Hajnoczi 26731c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque) 2674fc01f7e7Sbellard { 26751c9805a3SStefan Hajnoczi RwCo *rwco = opaque; 2676fc01f7e7Sbellard 26771c9805a3SStefan Hajnoczi if (!rwco->is_write) { 2678775aa8b6SKevin Wolf rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset, 2679775aa8b6SKevin Wolf rwco->qiov->size, rwco->qiov, 26804105eaaaSPeter Lieven rwco->flags); 26811c9805a3SStefan Hajnoczi } else { 2682775aa8b6SKevin Wolf rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset, 2683775aa8b6SKevin Wolf rwco->qiov->size, rwco->qiov, 26844105eaaaSPeter Lieven rwco->flags); 26851c9805a3SStefan Hajnoczi } 26861c9805a3SStefan Hajnoczi } 2687e7a8a783SKevin Wolf 26881c9805a3SStefan Hajnoczi /* 26898d3b1a2dSKevin Wolf * Process a vectored synchronous request using coroutines 26901c9805a3SStefan Hajnoczi */ 2691775aa8b6SKevin Wolf static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset, 26924105eaaaSPeter Lieven QEMUIOVector *qiov, bool is_write, 26934105eaaaSPeter Lieven BdrvRequestFlags flags) 26941c9805a3SStefan Hajnoczi { 26951c9805a3SStefan Hajnoczi Coroutine *co; 26961c9805a3SStefan Hajnoczi RwCo rwco = { 26971c9805a3SStefan Hajnoczi .bs = bs, 2698775aa8b6SKevin Wolf .offset = offset, 26998d3b1a2dSKevin Wolf .qiov = qiov, 27001c9805a3SStefan Hajnoczi .is_write = is_write, 27011c9805a3SStefan Hajnoczi .ret = NOT_DONE, 27024105eaaaSPeter Lieven .flags = flags, 27031c9805a3SStefan Hajnoczi }; 27041c9805a3SStefan Hajnoczi 2705498e386cSZhi Yong Wu /** 2706498e386cSZhi Yong Wu * In sync call context, when the vcpu is blocked, this throttling timer 2707498e386cSZhi Yong Wu * will not fire; so the I/O throttling function has to be disabled here 2708498e386cSZhi Yong Wu * if it has been enabled. 2709498e386cSZhi Yong Wu */ 2710498e386cSZhi Yong Wu if (bs->io_limits_enabled) { 2711498e386cSZhi Yong Wu fprintf(stderr, "Disabling I/O throttling on '%s' due " 2712498e386cSZhi Yong Wu "to synchronous I/O.\n", bdrv_get_device_name(bs)); 2713498e386cSZhi Yong Wu bdrv_io_limits_disable(bs); 2714498e386cSZhi Yong Wu } 2715498e386cSZhi Yong Wu 27161c9805a3SStefan Hajnoczi if (qemu_in_coroutine()) { 27171c9805a3SStefan Hajnoczi /* Fast-path if already in coroutine context */ 27181c9805a3SStefan Hajnoczi bdrv_rw_co_entry(&rwco); 27191c9805a3SStefan Hajnoczi } else { 27202572b37aSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 27212572b37aSStefan Hajnoczi 27221c9805a3SStefan Hajnoczi co = qemu_coroutine_create(bdrv_rw_co_entry); 27231c9805a3SStefan Hajnoczi qemu_coroutine_enter(co, &rwco); 27241c9805a3SStefan Hajnoczi while (rwco.ret == NOT_DONE) { 27252572b37aSStefan Hajnoczi aio_poll(aio_context, true); 27261c9805a3SStefan Hajnoczi } 27271c9805a3SStefan Hajnoczi } 27281c9805a3SStefan Hajnoczi return rwco.ret; 2729e7a8a783SKevin Wolf } 2730e7a8a783SKevin Wolf 27318d3b1a2dSKevin Wolf /* 27328d3b1a2dSKevin Wolf * Process a synchronous request using coroutines 27338d3b1a2dSKevin Wolf */ 27348d3b1a2dSKevin Wolf static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf, 27354105eaaaSPeter Lieven int nb_sectors, bool is_write, BdrvRequestFlags flags) 27368d3b1a2dSKevin Wolf { 27378d3b1a2dSKevin Wolf QEMUIOVector qiov; 27388d3b1a2dSKevin Wolf struct iovec iov = { 27398d3b1a2dSKevin Wolf .iov_base = (void *)buf, 27408d3b1a2dSKevin Wolf .iov_len = nb_sectors * BDRV_SECTOR_SIZE, 27418d3b1a2dSKevin Wolf }; 27428d3b1a2dSKevin Wolf 2743da15ee51SKevin Wolf if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) { 2744da15ee51SKevin Wolf return -EINVAL; 2745da15ee51SKevin Wolf } 2746da15ee51SKevin Wolf 27478d3b1a2dSKevin Wolf qemu_iovec_init_external(&qiov, &iov, 1); 2748775aa8b6SKevin Wolf return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS, 2749775aa8b6SKevin Wolf &qiov, is_write, flags); 27508d3b1a2dSKevin Wolf } 27518d3b1a2dSKevin Wolf 27521c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */ 27531c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num, 27541c9805a3SStefan Hajnoczi uint8_t *buf, int nb_sectors) 27551c9805a3SStefan Hajnoczi { 27564105eaaaSPeter Lieven return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0); 275783f64091Sbellard } 2758fc01f7e7Sbellard 275907d27a44SMarkus Armbruster /* Just like bdrv_read(), but with I/O throttling temporarily disabled */ 276007d27a44SMarkus Armbruster int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num, 276107d27a44SMarkus Armbruster uint8_t *buf, int nb_sectors) 276207d27a44SMarkus Armbruster { 276307d27a44SMarkus Armbruster bool enabled; 276407d27a44SMarkus Armbruster int ret; 276507d27a44SMarkus Armbruster 276607d27a44SMarkus Armbruster enabled = bs->io_limits_enabled; 276707d27a44SMarkus Armbruster bs->io_limits_enabled = false; 27684e7395e8SPeter Lieven ret = bdrv_read(bs, sector_num, buf, nb_sectors); 276907d27a44SMarkus Armbruster bs->io_limits_enabled = enabled; 277007d27a44SMarkus Armbruster return ret; 277107d27a44SMarkus Armbruster } 277207d27a44SMarkus Armbruster 277319cb3738Sbellard /* Return < 0 if error. Important errors are: 277419cb3738Sbellard -EIO generic I/O error (may happen for all errors) 277519cb3738Sbellard -ENOMEDIUM No media inserted. 277619cb3738Sbellard -EINVAL Invalid sector number or nb_sectors 277719cb3738Sbellard -EACCES Trying to write a read-only device 277819cb3738Sbellard */ 2779fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num, 2780fc01f7e7Sbellard const uint8_t *buf, int nb_sectors) 2781fc01f7e7Sbellard { 27824105eaaaSPeter Lieven return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0); 278383f64091Sbellard } 278483f64091Sbellard 2785aa7bfbffSPeter Lieven int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num, 2786aa7bfbffSPeter Lieven int nb_sectors, BdrvRequestFlags flags) 27874105eaaaSPeter Lieven { 27884105eaaaSPeter Lieven return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true, 2789aa7bfbffSPeter Lieven BDRV_REQ_ZERO_WRITE | flags); 27908d3b1a2dSKevin Wolf } 27918d3b1a2dSKevin Wolf 2792d75cbb5eSPeter Lieven /* 2793d75cbb5eSPeter Lieven * Completely zero out a block device with the help of bdrv_write_zeroes. 2794d75cbb5eSPeter Lieven * The operation is sped up by checking the block status and only writing 2795d75cbb5eSPeter Lieven * zeroes to the device if they currently do not return zeroes. Optional 2796d75cbb5eSPeter Lieven * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP). 2797d75cbb5eSPeter Lieven * 2798d75cbb5eSPeter Lieven * Returns < 0 on error, 0 on success. For error codes see bdrv_write(). 2799d75cbb5eSPeter Lieven */ 2800d75cbb5eSPeter Lieven int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags) 2801d75cbb5eSPeter Lieven { 2802d32f7c10SMarkus Armbruster int64_t target_sectors, ret, nb_sectors, sector_num = 0; 2803d75cbb5eSPeter Lieven int n; 2804d75cbb5eSPeter Lieven 2805d32f7c10SMarkus Armbruster target_sectors = bdrv_nb_sectors(bs); 2806d32f7c10SMarkus Armbruster if (target_sectors < 0) { 2807d32f7c10SMarkus Armbruster return target_sectors; 28089ce10c0bSKevin Wolf } 28099ce10c0bSKevin Wolf 2810d75cbb5eSPeter Lieven for (;;) { 2811d32f7c10SMarkus Armbruster nb_sectors = target_sectors - sector_num; 2812d75cbb5eSPeter Lieven if (nb_sectors <= 0) { 2813d75cbb5eSPeter Lieven return 0; 2814d75cbb5eSPeter Lieven } 2815f3a9cfddSFam Zheng if (nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) { 2816f3a9cfddSFam Zheng nb_sectors = INT_MAX / BDRV_SECTOR_SIZE; 2817d75cbb5eSPeter Lieven } 2818d75cbb5eSPeter Lieven ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n); 28193d94ce60SPeter Lieven if (ret < 0) { 28203d94ce60SPeter Lieven error_report("error getting block status at sector %" PRId64 ": %s", 28213d94ce60SPeter Lieven sector_num, strerror(-ret)); 28223d94ce60SPeter Lieven return ret; 28233d94ce60SPeter Lieven } 2824d75cbb5eSPeter Lieven if (ret & BDRV_BLOCK_ZERO) { 2825d75cbb5eSPeter Lieven sector_num += n; 2826d75cbb5eSPeter Lieven continue; 2827d75cbb5eSPeter Lieven } 2828d75cbb5eSPeter Lieven ret = bdrv_write_zeroes(bs, sector_num, n, flags); 2829d75cbb5eSPeter Lieven if (ret < 0) { 2830d75cbb5eSPeter Lieven error_report("error writing zeroes at sector %" PRId64 ": %s", 2831d75cbb5eSPeter Lieven sector_num, strerror(-ret)); 2832d75cbb5eSPeter Lieven return ret; 2833d75cbb5eSPeter Lieven } 2834d75cbb5eSPeter Lieven sector_num += n; 2835d75cbb5eSPeter Lieven } 2836d75cbb5eSPeter Lieven } 2837d75cbb5eSPeter Lieven 2838a3ef6571SKevin Wolf int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes) 283983f64091Sbellard { 2840a3ef6571SKevin Wolf QEMUIOVector qiov; 2841a3ef6571SKevin Wolf struct iovec iov = { 2842a3ef6571SKevin Wolf .iov_base = (void *)buf, 2843a3ef6571SKevin Wolf .iov_len = bytes, 2844a3ef6571SKevin Wolf }; 28459a8c4cceSKevin Wolf int ret; 284683f64091Sbellard 2847a3ef6571SKevin Wolf if (bytes < 0) { 2848a3ef6571SKevin Wolf return -EINVAL; 284983f64091Sbellard } 285083f64091Sbellard 2851a3ef6571SKevin Wolf qemu_iovec_init_external(&qiov, &iov, 1); 2852a3ef6571SKevin Wolf ret = bdrv_prwv_co(bs, offset, &qiov, false, 0); 2853a3ef6571SKevin Wolf if (ret < 0) { 28549a8c4cceSKevin Wolf return ret; 285583f64091Sbellard } 285683f64091Sbellard 2857a3ef6571SKevin Wolf return bytes; 285883f64091Sbellard } 285983f64091Sbellard 28608d3b1a2dSKevin Wolf int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov) 286183f64091Sbellard { 28629a8c4cceSKevin Wolf int ret; 286383f64091Sbellard 28648407d5d7SKevin Wolf ret = bdrv_prwv_co(bs, offset, qiov, true, 0); 28658d3b1a2dSKevin Wolf if (ret < 0) { 28669a8c4cceSKevin Wolf return ret; 28678d3b1a2dSKevin Wolf } 28688d3b1a2dSKevin Wolf 28698d3b1a2dSKevin Wolf return qiov->size; 28708d3b1a2dSKevin Wolf } 28718d3b1a2dSKevin Wolf 28728d3b1a2dSKevin Wolf int bdrv_pwrite(BlockDriverState *bs, int64_t offset, 28738407d5d7SKevin Wolf const void *buf, int bytes) 28748d3b1a2dSKevin Wolf { 28758d3b1a2dSKevin Wolf QEMUIOVector qiov; 28768d3b1a2dSKevin Wolf struct iovec iov = { 28778d3b1a2dSKevin Wolf .iov_base = (void *) buf, 28788407d5d7SKevin Wolf .iov_len = bytes, 28798d3b1a2dSKevin Wolf }; 28808d3b1a2dSKevin Wolf 28818407d5d7SKevin Wolf if (bytes < 0) { 28828407d5d7SKevin Wolf return -EINVAL; 28838407d5d7SKevin Wolf } 28848407d5d7SKevin Wolf 28858d3b1a2dSKevin Wolf qemu_iovec_init_external(&qiov, &iov, 1); 28868d3b1a2dSKevin Wolf return bdrv_pwritev(bs, offset, &qiov); 288783f64091Sbellard } 288883f64091Sbellard 2889f08145feSKevin Wolf /* 2890f08145feSKevin Wolf * Writes to the file and ensures that no writes are reordered across this 2891f08145feSKevin Wolf * request (acts as a barrier) 2892f08145feSKevin Wolf * 2893f08145feSKevin Wolf * Returns 0 on success, -errno in error cases. 2894f08145feSKevin Wolf */ 2895f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset, 2896f08145feSKevin Wolf const void *buf, int count) 2897f08145feSKevin Wolf { 2898f08145feSKevin Wolf int ret; 2899f08145feSKevin Wolf 2900f08145feSKevin Wolf ret = bdrv_pwrite(bs, offset, buf, count); 2901f08145feSKevin Wolf if (ret < 0) { 2902f08145feSKevin Wolf return ret; 2903f08145feSKevin Wolf } 2904f08145feSKevin Wolf 2905f05fa4adSPaolo Bonzini /* No flush needed for cache modes that already do it */ 2906f05fa4adSPaolo Bonzini if (bs->enable_write_cache) { 2907f08145feSKevin Wolf bdrv_flush(bs); 2908f08145feSKevin Wolf } 2909f08145feSKevin Wolf 2910f08145feSKevin Wolf return 0; 2911f08145feSKevin Wolf } 2912f08145feSKevin Wolf 2913470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs, 2914ab185921SStefan Hajnoczi int64_t sector_num, int nb_sectors, QEMUIOVector *qiov) 2915ab185921SStefan Hajnoczi { 2916ab185921SStefan Hajnoczi /* Perform I/O through a temporary buffer so that users who scribble over 2917ab185921SStefan Hajnoczi * their read buffer while the operation is in progress do not end up 2918ab185921SStefan Hajnoczi * modifying the image file. This is critical for zero-copy guest I/O 2919ab185921SStefan Hajnoczi * where anything might happen inside guest memory. 2920ab185921SStefan Hajnoczi */ 2921ab185921SStefan Hajnoczi void *bounce_buffer; 2922ab185921SStefan Hajnoczi 292379c053bdSStefan Hajnoczi BlockDriver *drv = bs->drv; 2924ab185921SStefan Hajnoczi struct iovec iov; 2925ab185921SStefan Hajnoczi QEMUIOVector bounce_qiov; 2926ab185921SStefan Hajnoczi int64_t cluster_sector_num; 2927ab185921SStefan Hajnoczi int cluster_nb_sectors; 2928ab185921SStefan Hajnoczi size_t skip_bytes; 2929ab185921SStefan Hajnoczi int ret; 2930ab185921SStefan Hajnoczi 2931ab185921SStefan Hajnoczi /* Cover entire cluster so no additional backing file I/O is required when 2932ab185921SStefan Hajnoczi * allocating cluster in the image file. 2933ab185921SStefan Hajnoczi */ 2934343bded4SPaolo Bonzini bdrv_round_to_clusters(bs, sector_num, nb_sectors, 2935ab185921SStefan Hajnoczi &cluster_sector_num, &cluster_nb_sectors); 2936ab185921SStefan Hajnoczi 2937470c0504SStefan Hajnoczi trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, 2938ab185921SStefan Hajnoczi cluster_sector_num, cluster_nb_sectors); 2939ab185921SStefan Hajnoczi 2940ab185921SStefan Hajnoczi iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE; 2941857d4f46SKevin Wolf iov.iov_base = bounce_buffer = qemu_try_blockalign(bs, iov.iov_len); 2942857d4f46SKevin Wolf if (bounce_buffer == NULL) { 2943857d4f46SKevin Wolf ret = -ENOMEM; 2944857d4f46SKevin Wolf goto err; 2945857d4f46SKevin Wolf } 2946857d4f46SKevin Wolf 2947ab185921SStefan Hajnoczi qemu_iovec_init_external(&bounce_qiov, &iov, 1); 2948ab185921SStefan Hajnoczi 294979c053bdSStefan Hajnoczi ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors, 2950ab185921SStefan Hajnoczi &bounce_qiov); 2951ab185921SStefan Hajnoczi if (ret < 0) { 2952ab185921SStefan Hajnoczi goto err; 2953ab185921SStefan Hajnoczi } 2954ab185921SStefan Hajnoczi 295579c053bdSStefan Hajnoczi if (drv->bdrv_co_write_zeroes && 295679c053bdSStefan Hajnoczi buffer_is_zero(bounce_buffer, iov.iov_len)) { 2957621f0589SKevin Wolf ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num, 2958aa7bfbffSPeter Lieven cluster_nb_sectors, 0); 295979c053bdSStefan Hajnoczi } else { 2960f05fa4adSPaolo Bonzini /* This does not change the data on the disk, it is not necessary 2961f05fa4adSPaolo Bonzini * to flush even in cache=writethrough mode. 2962f05fa4adSPaolo Bonzini */ 296379c053bdSStefan Hajnoczi ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors, 2964ab185921SStefan Hajnoczi &bounce_qiov); 296579c053bdSStefan Hajnoczi } 296679c053bdSStefan Hajnoczi 2967ab185921SStefan Hajnoczi if (ret < 0) { 2968ab185921SStefan Hajnoczi /* It might be okay to ignore write errors for guest requests. If this 2969ab185921SStefan Hajnoczi * is a deliberate copy-on-read then we don't want to ignore the error. 2970ab185921SStefan Hajnoczi * Simply report it in all cases. 2971ab185921SStefan Hajnoczi */ 2972ab185921SStefan Hajnoczi goto err; 2973ab185921SStefan Hajnoczi } 2974ab185921SStefan Hajnoczi 2975ab185921SStefan Hajnoczi skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE; 297603396148SMichael Tokarev qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes, 2977ab185921SStefan Hajnoczi nb_sectors * BDRV_SECTOR_SIZE); 2978ab185921SStefan Hajnoczi 2979ab185921SStefan Hajnoczi err: 2980ab185921SStefan Hajnoczi qemu_vfree(bounce_buffer); 2981ab185921SStefan Hajnoczi return ret; 2982ab185921SStefan Hajnoczi } 2983ab185921SStefan Hajnoczi 2984c5fbe571SStefan Hajnoczi /* 2985d0c7f642SKevin Wolf * Forwards an already correctly aligned request to the BlockDriver. This 2986d0c7f642SKevin Wolf * handles copy on read and zeroing after EOF; any other features must be 2987d0c7f642SKevin Wolf * implemented by the caller. 2988c5fbe571SStefan Hajnoczi */ 2989d0c7f642SKevin Wolf static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs, 299065afd211SKevin Wolf BdrvTrackedRequest *req, int64_t offset, unsigned int bytes, 2991ec746e10SKevin Wolf int64_t align, QEMUIOVector *qiov, int flags) 2992da1fa91dSKevin Wolf { 2993da1fa91dSKevin Wolf BlockDriver *drv = bs->drv; 2994dbffbdcfSStefan Hajnoczi int ret; 2995da1fa91dSKevin Wolf 2996d0c7f642SKevin Wolf int64_t sector_num = offset >> BDRV_SECTOR_BITS; 2997d0c7f642SKevin Wolf unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS; 2998da1fa91dSKevin Wolf 2999d0c7f642SKevin Wolf assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0); 3000d0c7f642SKevin Wolf assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0); 30018eb029c2SKevin Wolf assert(!qiov || bytes == qiov->size); 3002d0c7f642SKevin Wolf 3003d0c7f642SKevin Wolf /* Handle Copy on Read and associated serialisation */ 3004470c0504SStefan Hajnoczi if (flags & BDRV_REQ_COPY_ON_READ) { 30057327145fSKevin Wolf /* If we touch the same cluster it counts as an overlap. This 30067327145fSKevin Wolf * guarantees that allocating writes will be serialized and not race 30077327145fSKevin Wolf * with each other for the same cluster. For example, in copy-on-read 30087327145fSKevin Wolf * it ensures that the CoR read and write operations are atomic and 30097327145fSKevin Wolf * guest writes cannot interleave between them. */ 30107327145fSKevin Wolf mark_request_serialising(req, bdrv_get_cluster_size(bs)); 3011470c0504SStefan Hajnoczi } 3012470c0504SStefan Hajnoczi 30132dbafdc0SKevin Wolf wait_serialising_requests(req); 3014f4658285SStefan Hajnoczi 3015470c0504SStefan Hajnoczi if (flags & BDRV_REQ_COPY_ON_READ) { 3016ab185921SStefan Hajnoczi int pnum; 3017ab185921SStefan Hajnoczi 3018bdad13b9SPaolo Bonzini ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum); 3019ab185921SStefan Hajnoczi if (ret < 0) { 3020ab185921SStefan Hajnoczi goto out; 3021ab185921SStefan Hajnoczi } 3022ab185921SStefan Hajnoczi 3023ab185921SStefan Hajnoczi if (!ret || pnum != nb_sectors) { 3024470c0504SStefan Hajnoczi ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov); 3025ab185921SStefan Hajnoczi goto out; 3026ab185921SStefan Hajnoczi } 3027ab185921SStefan Hajnoczi } 3028ab185921SStefan Hajnoczi 3029d0c7f642SKevin Wolf /* Forward the request to the BlockDriver */ 3030893a8f62SMORITA Kazutaka if (!(bs->zero_beyond_eof && bs->growable)) { 3031dbffbdcfSStefan Hajnoczi ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov); 3032893a8f62SMORITA Kazutaka } else { 3033893a8f62SMORITA Kazutaka /* Read zeros after EOF of growable BDSes */ 30344049082cSMarkus Armbruster int64_t total_sectors, max_nb_sectors; 3035893a8f62SMORITA Kazutaka 30364049082cSMarkus Armbruster total_sectors = bdrv_nb_sectors(bs); 30374049082cSMarkus Armbruster if (total_sectors < 0) { 30384049082cSMarkus Armbruster ret = total_sectors; 3039893a8f62SMORITA Kazutaka goto out; 3040893a8f62SMORITA Kazutaka } 3041893a8f62SMORITA Kazutaka 30425f5bcd80SKevin Wolf max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num), 30435f5bcd80SKevin Wolf align >> BDRV_SECTOR_BITS); 3044893a8f62SMORITA Kazutaka if (max_nb_sectors > 0) { 304533f461e0SKevin Wolf QEMUIOVector local_qiov; 304633f461e0SKevin Wolf size_t local_sectors; 304733f461e0SKevin Wolf 304833f461e0SKevin Wolf max_nb_sectors = MIN(max_nb_sectors, SIZE_MAX / BDRV_SECTOR_BITS); 304933f461e0SKevin Wolf local_sectors = MIN(max_nb_sectors, nb_sectors); 305033f461e0SKevin Wolf 305133f461e0SKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov); 305233f461e0SKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, 305333f461e0SKevin Wolf local_sectors * BDRV_SECTOR_SIZE); 305433f461e0SKevin Wolf 305533f461e0SKevin Wolf ret = drv->bdrv_co_readv(bs, sector_num, local_sectors, 305633f461e0SKevin Wolf &local_qiov); 305733f461e0SKevin Wolf 305833f461e0SKevin Wolf qemu_iovec_destroy(&local_qiov); 3059893a8f62SMORITA Kazutaka } else { 3060893a8f62SMORITA Kazutaka ret = 0; 3061893a8f62SMORITA Kazutaka } 3062893a8f62SMORITA Kazutaka 3063893a8f62SMORITA Kazutaka /* Reading beyond end of file is supposed to produce zeroes */ 3064893a8f62SMORITA Kazutaka if (ret == 0 && total_sectors < sector_num + nb_sectors) { 3065893a8f62SMORITA Kazutaka uint64_t offset = MAX(0, total_sectors - sector_num); 3066893a8f62SMORITA Kazutaka uint64_t bytes = (sector_num + nb_sectors - offset) * 3067893a8f62SMORITA Kazutaka BDRV_SECTOR_SIZE; 3068893a8f62SMORITA Kazutaka qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes); 3069893a8f62SMORITA Kazutaka } 3070893a8f62SMORITA Kazutaka } 3071ab185921SStefan Hajnoczi 3072ab185921SStefan Hajnoczi out: 3073dbffbdcfSStefan Hajnoczi return ret; 3074da1fa91dSKevin Wolf } 3075da1fa91dSKevin Wolf 3076d0c7f642SKevin Wolf /* 3077d0c7f642SKevin Wolf * Handle a read request in coroutine context 3078d0c7f642SKevin Wolf */ 30791b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs, 30801b0288aeSKevin Wolf int64_t offset, unsigned int bytes, QEMUIOVector *qiov, 3081d0c7f642SKevin Wolf BdrvRequestFlags flags) 3082d0c7f642SKevin Wolf { 3083d0c7f642SKevin Wolf BlockDriver *drv = bs->drv; 308465afd211SKevin Wolf BdrvTrackedRequest req; 308565afd211SKevin Wolf 30861b0288aeSKevin Wolf /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */ 30871b0288aeSKevin Wolf uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment); 30881b0288aeSKevin Wolf uint8_t *head_buf = NULL; 30891b0288aeSKevin Wolf uint8_t *tail_buf = NULL; 30901b0288aeSKevin Wolf QEMUIOVector local_qiov; 30911b0288aeSKevin Wolf bool use_local_qiov = false; 3092d0c7f642SKevin Wolf int ret; 3093d0c7f642SKevin Wolf 3094d0c7f642SKevin Wolf if (!drv) { 3095d0c7f642SKevin Wolf return -ENOMEDIUM; 3096d0c7f642SKevin Wolf } 30971b0288aeSKevin Wolf if (bdrv_check_byte_request(bs, offset, bytes)) { 3098d0c7f642SKevin Wolf return -EIO; 3099d0c7f642SKevin Wolf } 3100d0c7f642SKevin Wolf 3101d0c7f642SKevin Wolf if (bs->copy_on_read) { 3102d0c7f642SKevin Wolf flags |= BDRV_REQ_COPY_ON_READ; 3103d0c7f642SKevin Wolf } 3104d0c7f642SKevin Wolf 3105d0c7f642SKevin Wolf /* throttling disk I/O */ 3106d0c7f642SKevin Wolf if (bs->io_limits_enabled) { 3107d5103588SKevin Wolf bdrv_io_limits_intercept(bs, bytes, false); 3108d0c7f642SKevin Wolf } 3109d0c7f642SKevin Wolf 31101b0288aeSKevin Wolf /* Align read if necessary by padding qiov */ 31111b0288aeSKevin Wolf if (offset & (align - 1)) { 31121b0288aeSKevin Wolf head_buf = qemu_blockalign(bs, align); 31131b0288aeSKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov + 2); 31141b0288aeSKevin Wolf qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1)); 31151b0288aeSKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 31161b0288aeSKevin Wolf use_local_qiov = true; 31171b0288aeSKevin Wolf 31181b0288aeSKevin Wolf bytes += offset & (align - 1); 31191b0288aeSKevin Wolf offset = offset & ~(align - 1); 31201b0288aeSKevin Wolf } 31211b0288aeSKevin Wolf 31221b0288aeSKevin Wolf if ((offset + bytes) & (align - 1)) { 31231b0288aeSKevin Wolf if (!use_local_qiov) { 31241b0288aeSKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov + 1); 31251b0288aeSKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 31261b0288aeSKevin Wolf use_local_qiov = true; 31271b0288aeSKevin Wolf } 31281b0288aeSKevin Wolf tail_buf = qemu_blockalign(bs, align); 31291b0288aeSKevin Wolf qemu_iovec_add(&local_qiov, tail_buf, 31301b0288aeSKevin Wolf align - ((offset + bytes) & (align - 1))); 31311b0288aeSKevin Wolf 31321b0288aeSKevin Wolf bytes = ROUND_UP(bytes, align); 31331b0288aeSKevin Wolf } 31341b0288aeSKevin Wolf 313565afd211SKevin Wolf tracked_request_begin(&req, bs, offset, bytes, false); 3136ec746e10SKevin Wolf ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align, 31371b0288aeSKevin Wolf use_local_qiov ? &local_qiov : qiov, 31381b0288aeSKevin Wolf flags); 313965afd211SKevin Wolf tracked_request_end(&req); 31401b0288aeSKevin Wolf 31411b0288aeSKevin Wolf if (use_local_qiov) { 31421b0288aeSKevin Wolf qemu_iovec_destroy(&local_qiov); 31431b0288aeSKevin Wolf qemu_vfree(head_buf); 31441b0288aeSKevin Wolf qemu_vfree(tail_buf); 31451b0288aeSKevin Wolf } 31461b0288aeSKevin Wolf 3147d0c7f642SKevin Wolf return ret; 3148d0c7f642SKevin Wolf } 3149d0c7f642SKevin Wolf 31501b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs, 31511b0288aeSKevin Wolf int64_t sector_num, int nb_sectors, QEMUIOVector *qiov, 31521b0288aeSKevin Wolf BdrvRequestFlags flags) 31531b0288aeSKevin Wolf { 31541b0288aeSKevin Wolf if (nb_sectors < 0 || nb_sectors > (UINT_MAX >> BDRV_SECTOR_BITS)) { 31551b0288aeSKevin Wolf return -EINVAL; 31561b0288aeSKevin Wolf } 31571b0288aeSKevin Wolf 31581b0288aeSKevin Wolf return bdrv_co_do_preadv(bs, sector_num << BDRV_SECTOR_BITS, 31591b0288aeSKevin Wolf nb_sectors << BDRV_SECTOR_BITS, qiov, flags); 31601b0288aeSKevin Wolf } 31611b0288aeSKevin Wolf 3162c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num, 3163da1fa91dSKevin Wolf int nb_sectors, QEMUIOVector *qiov) 3164da1fa91dSKevin Wolf { 3165c5fbe571SStefan Hajnoczi trace_bdrv_co_readv(bs, sector_num, nb_sectors); 3166da1fa91dSKevin Wolf 3167470c0504SStefan Hajnoczi return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0); 3168470c0504SStefan Hajnoczi } 3169470c0504SStefan Hajnoczi 3170470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs, 3171470c0504SStefan Hajnoczi int64_t sector_num, int nb_sectors, QEMUIOVector *qiov) 3172470c0504SStefan Hajnoczi { 3173470c0504SStefan Hajnoczi trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors); 3174470c0504SStefan Hajnoczi 3175470c0504SStefan Hajnoczi return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 3176470c0504SStefan Hajnoczi BDRV_REQ_COPY_ON_READ); 3177c5fbe571SStefan Hajnoczi } 3178c5fbe571SStefan Hajnoczi 3179c31cb707SPeter Lieven /* if no limit is specified in the BlockLimits use a default 3180c31cb707SPeter Lieven * of 32768 512-byte sectors (16 MiB) per request. 3181c31cb707SPeter Lieven */ 3182c31cb707SPeter Lieven #define MAX_WRITE_ZEROES_DEFAULT 32768 3183c31cb707SPeter Lieven 3184f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs, 3185aa7bfbffSPeter Lieven int64_t sector_num, int nb_sectors, BdrvRequestFlags flags) 3186f08f2ddaSStefan Hajnoczi { 3187f08f2ddaSStefan Hajnoczi BlockDriver *drv = bs->drv; 3188f08f2ddaSStefan Hajnoczi QEMUIOVector qiov; 3189c31cb707SPeter Lieven struct iovec iov = {0}; 3190c31cb707SPeter Lieven int ret = 0; 3191f08f2ddaSStefan Hajnoczi 3192c31cb707SPeter Lieven int max_write_zeroes = bs->bl.max_write_zeroes ? 3193c31cb707SPeter Lieven bs->bl.max_write_zeroes : MAX_WRITE_ZEROES_DEFAULT; 3194621f0589SKevin Wolf 3195c31cb707SPeter Lieven while (nb_sectors > 0 && !ret) { 3196c31cb707SPeter Lieven int num = nb_sectors; 3197c31cb707SPeter Lieven 3198b8d71c09SPaolo Bonzini /* Align request. Block drivers can expect the "bulk" of the request 3199b8d71c09SPaolo Bonzini * to be aligned. 3200b8d71c09SPaolo Bonzini */ 3201b8d71c09SPaolo Bonzini if (bs->bl.write_zeroes_alignment 3202b8d71c09SPaolo Bonzini && num > bs->bl.write_zeroes_alignment) { 3203b8d71c09SPaolo Bonzini if (sector_num % bs->bl.write_zeroes_alignment != 0) { 3204b8d71c09SPaolo Bonzini /* Make a small request up to the first aligned sector. */ 3205c31cb707SPeter Lieven num = bs->bl.write_zeroes_alignment; 3206c31cb707SPeter Lieven num -= sector_num % bs->bl.write_zeroes_alignment; 3207b8d71c09SPaolo Bonzini } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) { 3208b8d71c09SPaolo Bonzini /* Shorten the request to the last aligned sector. num cannot 3209b8d71c09SPaolo Bonzini * underflow because num > bs->bl.write_zeroes_alignment. 3210b8d71c09SPaolo Bonzini */ 3211b8d71c09SPaolo Bonzini num -= (sector_num + num) % bs->bl.write_zeroes_alignment; 3212b8d71c09SPaolo Bonzini } 3213c31cb707SPeter Lieven } 3214c31cb707SPeter Lieven 3215c31cb707SPeter Lieven /* limit request size */ 3216c31cb707SPeter Lieven if (num > max_write_zeroes) { 3217c31cb707SPeter Lieven num = max_write_zeroes; 3218c31cb707SPeter Lieven } 3219c31cb707SPeter Lieven 3220c31cb707SPeter Lieven ret = -ENOTSUP; 3221f08f2ddaSStefan Hajnoczi /* First try the efficient write zeroes operation */ 3222f08f2ddaSStefan Hajnoczi if (drv->bdrv_co_write_zeroes) { 3223c31cb707SPeter Lieven ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags); 3224f08f2ddaSStefan Hajnoczi } 3225f08f2ddaSStefan Hajnoczi 3226c31cb707SPeter Lieven if (ret == -ENOTSUP) { 3227f08f2ddaSStefan Hajnoczi /* Fall back to bounce buffer if write zeroes is unsupported */ 3228c31cb707SPeter Lieven iov.iov_len = num * BDRV_SECTOR_SIZE; 3229c31cb707SPeter Lieven if (iov.iov_base == NULL) { 3230857d4f46SKevin Wolf iov.iov_base = qemu_try_blockalign(bs, num * BDRV_SECTOR_SIZE); 3231857d4f46SKevin Wolf if (iov.iov_base == NULL) { 3232857d4f46SKevin Wolf ret = -ENOMEM; 3233857d4f46SKevin Wolf goto fail; 3234857d4f46SKevin Wolf } 3235b8d71c09SPaolo Bonzini memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE); 3236c31cb707SPeter Lieven } 3237f08f2ddaSStefan Hajnoczi qemu_iovec_init_external(&qiov, &iov, 1); 3238f08f2ddaSStefan Hajnoczi 3239c31cb707SPeter Lieven ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov); 3240b8d71c09SPaolo Bonzini 3241b8d71c09SPaolo Bonzini /* Keep bounce buffer around if it is big enough for all 3242b8d71c09SPaolo Bonzini * all future requests. 3243b8d71c09SPaolo Bonzini */ 3244b8d71c09SPaolo Bonzini if (num < max_write_zeroes) { 3245b8d71c09SPaolo Bonzini qemu_vfree(iov.iov_base); 3246b8d71c09SPaolo Bonzini iov.iov_base = NULL; 3247b8d71c09SPaolo Bonzini } 3248c31cb707SPeter Lieven } 3249c31cb707SPeter Lieven 3250c31cb707SPeter Lieven sector_num += num; 3251c31cb707SPeter Lieven nb_sectors -= num; 3252c31cb707SPeter Lieven } 3253f08f2ddaSStefan Hajnoczi 3254857d4f46SKevin Wolf fail: 3255f08f2ddaSStefan Hajnoczi qemu_vfree(iov.iov_base); 3256f08f2ddaSStefan Hajnoczi return ret; 3257f08f2ddaSStefan Hajnoczi } 3258f08f2ddaSStefan Hajnoczi 3259c5fbe571SStefan Hajnoczi /* 3260b404f720SKevin Wolf * Forwards an already correctly aligned write request to the BlockDriver. 3261c5fbe571SStefan Hajnoczi */ 3262b404f720SKevin Wolf static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs, 326365afd211SKevin Wolf BdrvTrackedRequest *req, int64_t offset, unsigned int bytes, 326465afd211SKevin Wolf QEMUIOVector *qiov, int flags) 3265c5fbe571SStefan Hajnoczi { 3266c5fbe571SStefan Hajnoczi BlockDriver *drv = bs->drv; 326728de2dcdSKevin Wolf bool waited; 32686b7cb247SStefan Hajnoczi int ret; 3269da1fa91dSKevin Wolf 3270b404f720SKevin Wolf int64_t sector_num = offset >> BDRV_SECTOR_BITS; 3271b404f720SKevin Wolf unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS; 3272da1fa91dSKevin Wolf 3273b404f720SKevin Wolf assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0); 3274b404f720SKevin Wolf assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0); 32758eb029c2SKevin Wolf assert(!qiov || bytes == qiov->size); 3276cc0681c4SBenoît Canet 327728de2dcdSKevin Wolf waited = wait_serialising_requests(req); 327828de2dcdSKevin Wolf assert(!waited || !req->serialising); 3279af91f9a7SKevin Wolf assert(req->overlap_offset <= offset); 3280af91f9a7SKevin Wolf assert(offset + bytes <= req->overlap_offset + req->overlap_bytes); 3281244eadefSKevin Wolf 328265afd211SKevin Wolf ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req); 3283d616b224SStefan Hajnoczi 3284465bee1dSPeter Lieven if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF && 3285465bee1dSPeter Lieven !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_write_zeroes && 3286465bee1dSPeter Lieven qemu_iovec_is_zero(qiov)) { 3287465bee1dSPeter Lieven flags |= BDRV_REQ_ZERO_WRITE; 3288465bee1dSPeter Lieven if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) { 3289465bee1dSPeter Lieven flags |= BDRV_REQ_MAY_UNMAP; 3290465bee1dSPeter Lieven } 3291465bee1dSPeter Lieven } 3292465bee1dSPeter Lieven 3293d616b224SStefan Hajnoczi if (ret < 0) { 3294d616b224SStefan Hajnoczi /* Do nothing, write notifier decided to fail this request */ 3295d616b224SStefan Hajnoczi } else if (flags & BDRV_REQ_ZERO_WRITE) { 32969e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_ZERO); 3297aa7bfbffSPeter Lieven ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags); 3298f08f2ddaSStefan Hajnoczi } else { 32999e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV); 33006b7cb247SStefan Hajnoczi ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov); 3301f08f2ddaSStefan Hajnoczi } 33029e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_DONE); 33036b7cb247SStefan Hajnoczi 3304f05fa4adSPaolo Bonzini if (ret == 0 && !bs->enable_write_cache) { 3305f05fa4adSPaolo Bonzini ret = bdrv_co_flush(bs); 3306f05fa4adSPaolo Bonzini } 3307f05fa4adSPaolo Bonzini 33081755da16SPaolo Bonzini bdrv_set_dirty(bs, sector_num, nb_sectors); 3309da1fa91dSKevin Wolf 33105366d0c8SBenoît Canet block_acct_highest_sector(&bs->stats, sector_num, nb_sectors); 33115e5a94b6SBenoît Canet 3312df2a6f29SPaolo Bonzini if (bs->growable && ret >= 0) { 3313df2a6f29SPaolo Bonzini bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors); 3314df2a6f29SPaolo Bonzini } 3315da1fa91dSKevin Wolf 33166b7cb247SStefan Hajnoczi return ret; 3317da1fa91dSKevin Wolf } 3318da1fa91dSKevin Wolf 3319b404f720SKevin Wolf /* 3320b404f720SKevin Wolf * Handle a write request in coroutine context 3321b404f720SKevin Wolf */ 33226601553eSKevin Wolf static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs, 33236601553eSKevin Wolf int64_t offset, unsigned int bytes, QEMUIOVector *qiov, 3324b404f720SKevin Wolf BdrvRequestFlags flags) 3325b404f720SKevin Wolf { 332665afd211SKevin Wolf BdrvTrackedRequest req; 33273b8242e0SKevin Wolf /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */ 33283b8242e0SKevin Wolf uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment); 33293b8242e0SKevin Wolf uint8_t *head_buf = NULL; 33303b8242e0SKevin Wolf uint8_t *tail_buf = NULL; 33313b8242e0SKevin Wolf QEMUIOVector local_qiov; 33323b8242e0SKevin Wolf bool use_local_qiov = false; 3333b404f720SKevin Wolf int ret; 3334b404f720SKevin Wolf 3335b404f720SKevin Wolf if (!bs->drv) { 3336b404f720SKevin Wolf return -ENOMEDIUM; 3337b404f720SKevin Wolf } 3338b404f720SKevin Wolf if (bs->read_only) { 3339b404f720SKevin Wolf return -EACCES; 3340b404f720SKevin Wolf } 33416601553eSKevin Wolf if (bdrv_check_byte_request(bs, offset, bytes)) { 3342b404f720SKevin Wolf return -EIO; 3343b404f720SKevin Wolf } 3344b404f720SKevin Wolf 3345b404f720SKevin Wolf /* throttling disk I/O */ 3346b404f720SKevin Wolf if (bs->io_limits_enabled) { 3347d5103588SKevin Wolf bdrv_io_limits_intercept(bs, bytes, true); 3348b404f720SKevin Wolf } 3349b404f720SKevin Wolf 33503b8242e0SKevin Wolf /* 33513b8242e0SKevin Wolf * Align write if necessary by performing a read-modify-write cycle. 33523b8242e0SKevin Wolf * Pad qiov with the read parts and be sure to have a tracked request not 33533b8242e0SKevin Wolf * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle. 33543b8242e0SKevin Wolf */ 335565afd211SKevin Wolf tracked_request_begin(&req, bs, offset, bytes, true); 33563b8242e0SKevin Wolf 33573b8242e0SKevin Wolf if (offset & (align - 1)) { 33583b8242e0SKevin Wolf QEMUIOVector head_qiov; 33593b8242e0SKevin Wolf struct iovec head_iov; 33603b8242e0SKevin Wolf 33613b8242e0SKevin Wolf mark_request_serialising(&req, align); 33623b8242e0SKevin Wolf wait_serialising_requests(&req); 33633b8242e0SKevin Wolf 33643b8242e0SKevin Wolf head_buf = qemu_blockalign(bs, align); 33653b8242e0SKevin Wolf head_iov = (struct iovec) { 33663b8242e0SKevin Wolf .iov_base = head_buf, 33673b8242e0SKevin Wolf .iov_len = align, 33683b8242e0SKevin Wolf }; 33693b8242e0SKevin Wolf qemu_iovec_init_external(&head_qiov, &head_iov, 1); 33703b8242e0SKevin Wolf 33719e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_HEAD); 33723b8242e0SKevin Wolf ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align, 33733b8242e0SKevin Wolf align, &head_qiov, 0); 33743b8242e0SKevin Wolf if (ret < 0) { 33753b8242e0SKevin Wolf goto fail; 33763b8242e0SKevin Wolf } 33779e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD); 33783b8242e0SKevin Wolf 33793b8242e0SKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov + 2); 33803b8242e0SKevin Wolf qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1)); 33813b8242e0SKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 33823b8242e0SKevin Wolf use_local_qiov = true; 33833b8242e0SKevin Wolf 33843b8242e0SKevin Wolf bytes += offset & (align - 1); 33853b8242e0SKevin Wolf offset = offset & ~(align - 1); 33863b8242e0SKevin Wolf } 33873b8242e0SKevin Wolf 33883b8242e0SKevin Wolf if ((offset + bytes) & (align - 1)) { 33893b8242e0SKevin Wolf QEMUIOVector tail_qiov; 33903b8242e0SKevin Wolf struct iovec tail_iov; 33913b8242e0SKevin Wolf size_t tail_bytes; 339228de2dcdSKevin Wolf bool waited; 33933b8242e0SKevin Wolf 33943b8242e0SKevin Wolf mark_request_serialising(&req, align); 339528de2dcdSKevin Wolf waited = wait_serialising_requests(&req); 339628de2dcdSKevin Wolf assert(!waited || !use_local_qiov); 33973b8242e0SKevin Wolf 33983b8242e0SKevin Wolf tail_buf = qemu_blockalign(bs, align); 33993b8242e0SKevin Wolf tail_iov = (struct iovec) { 34003b8242e0SKevin Wolf .iov_base = tail_buf, 34013b8242e0SKevin Wolf .iov_len = align, 34023b8242e0SKevin Wolf }; 34033b8242e0SKevin Wolf qemu_iovec_init_external(&tail_qiov, &tail_iov, 1); 34043b8242e0SKevin Wolf 34059e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_TAIL); 34063b8242e0SKevin Wolf ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align, 34073b8242e0SKevin Wolf align, &tail_qiov, 0); 34083b8242e0SKevin Wolf if (ret < 0) { 34093b8242e0SKevin Wolf goto fail; 34103b8242e0SKevin Wolf } 34119e1cb96dSKevin Wolf BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL); 34123b8242e0SKevin Wolf 34133b8242e0SKevin Wolf if (!use_local_qiov) { 34143b8242e0SKevin Wolf qemu_iovec_init(&local_qiov, qiov->niov + 1); 34153b8242e0SKevin Wolf qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 34163b8242e0SKevin Wolf use_local_qiov = true; 34173b8242e0SKevin Wolf } 34183b8242e0SKevin Wolf 34193b8242e0SKevin Wolf tail_bytes = (offset + bytes) & (align - 1); 34203b8242e0SKevin Wolf qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes); 34213b8242e0SKevin Wolf 34223b8242e0SKevin Wolf bytes = ROUND_UP(bytes, align); 34233b8242e0SKevin Wolf } 34243b8242e0SKevin Wolf 34253b8242e0SKevin Wolf ret = bdrv_aligned_pwritev(bs, &req, offset, bytes, 34263b8242e0SKevin Wolf use_local_qiov ? &local_qiov : qiov, 34273b8242e0SKevin Wolf flags); 34283b8242e0SKevin Wolf 34293b8242e0SKevin Wolf fail: 343065afd211SKevin Wolf tracked_request_end(&req); 3431b404f720SKevin Wolf 34323b8242e0SKevin Wolf if (use_local_qiov) { 34333b8242e0SKevin Wolf qemu_iovec_destroy(&local_qiov); 343499c4a85cSKevin Wolf } 34353b8242e0SKevin Wolf qemu_vfree(head_buf); 34363b8242e0SKevin Wolf qemu_vfree(tail_buf); 34373b8242e0SKevin Wolf 3438b404f720SKevin Wolf return ret; 3439b404f720SKevin Wolf } 3440b404f720SKevin Wolf 34416601553eSKevin Wolf static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs, 34426601553eSKevin Wolf int64_t sector_num, int nb_sectors, QEMUIOVector *qiov, 34436601553eSKevin Wolf BdrvRequestFlags flags) 34446601553eSKevin Wolf { 34456601553eSKevin Wolf if (nb_sectors < 0 || nb_sectors > (INT_MAX >> BDRV_SECTOR_BITS)) { 34466601553eSKevin Wolf return -EINVAL; 34476601553eSKevin Wolf } 34486601553eSKevin Wolf 34496601553eSKevin Wolf return bdrv_co_do_pwritev(bs, sector_num << BDRV_SECTOR_BITS, 34506601553eSKevin Wolf nb_sectors << BDRV_SECTOR_BITS, qiov, flags); 34516601553eSKevin Wolf } 34526601553eSKevin Wolf 3453c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num, 3454c5fbe571SStefan Hajnoczi int nb_sectors, QEMUIOVector *qiov) 3455c5fbe571SStefan Hajnoczi { 3456c5fbe571SStefan Hajnoczi trace_bdrv_co_writev(bs, sector_num, nb_sectors); 3457c5fbe571SStefan Hajnoczi 3458f08f2ddaSStefan Hajnoczi return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0); 3459f08f2ddaSStefan Hajnoczi } 3460f08f2ddaSStefan Hajnoczi 3461f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs, 3462aa7bfbffSPeter Lieven int64_t sector_num, int nb_sectors, 3463aa7bfbffSPeter Lieven BdrvRequestFlags flags) 3464f08f2ddaSStefan Hajnoczi { 346594d6ff21SPaolo Bonzini trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags); 3466f08f2ddaSStefan Hajnoczi 3467d32f35cbSPeter Lieven if (!(bs->open_flags & BDRV_O_UNMAP)) { 3468d32f35cbSPeter Lieven flags &= ~BDRV_REQ_MAY_UNMAP; 3469d32f35cbSPeter Lieven } 3470d32f35cbSPeter Lieven 3471f08f2ddaSStefan Hajnoczi return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL, 3472aa7bfbffSPeter Lieven BDRV_REQ_ZERO_WRITE | flags); 3473c5fbe571SStefan Hajnoczi } 3474c5fbe571SStefan Hajnoczi 347583f64091Sbellard /** 347683f64091Sbellard * Truncate file to 'offset' bytes (needed only for file protocols) 347783f64091Sbellard */ 347883f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset) 347983f64091Sbellard { 348083f64091Sbellard BlockDriver *drv = bs->drv; 348151762288SStefan Hajnoczi int ret; 348283f64091Sbellard if (!drv) 348319cb3738Sbellard return -ENOMEDIUM; 348483f64091Sbellard if (!drv->bdrv_truncate) 348583f64091Sbellard return -ENOTSUP; 348659f2689dSNaphtali Sprei if (bs->read_only) 348759f2689dSNaphtali Sprei return -EACCES; 34889c75e168SJeff Cody 348951762288SStefan Hajnoczi ret = drv->bdrv_truncate(bs, offset); 349051762288SStefan Hajnoczi if (ret == 0) { 349151762288SStefan Hajnoczi ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS); 3492a7f53e26SMarkus Armbruster if (bs->blk) { 3493a7f53e26SMarkus Armbruster blk_dev_resize_cb(bs->blk); 3494a7f53e26SMarkus Armbruster } 349551762288SStefan Hajnoczi } 349651762288SStefan Hajnoczi return ret; 349783f64091Sbellard } 349883f64091Sbellard 349983f64091Sbellard /** 35004a1d5e1fSFam Zheng * Length of a allocated file in bytes. Sparse files are counted by actual 35014a1d5e1fSFam Zheng * allocated space. Return < 0 if error or unknown. 35024a1d5e1fSFam Zheng */ 35034a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs) 35044a1d5e1fSFam Zheng { 35054a1d5e1fSFam Zheng BlockDriver *drv = bs->drv; 35064a1d5e1fSFam Zheng if (!drv) { 35074a1d5e1fSFam Zheng return -ENOMEDIUM; 35084a1d5e1fSFam Zheng } 35094a1d5e1fSFam Zheng if (drv->bdrv_get_allocated_file_size) { 35104a1d5e1fSFam Zheng return drv->bdrv_get_allocated_file_size(bs); 35114a1d5e1fSFam Zheng } 35124a1d5e1fSFam Zheng if (bs->file) { 35134a1d5e1fSFam Zheng return bdrv_get_allocated_file_size(bs->file); 35144a1d5e1fSFam Zheng } 35154a1d5e1fSFam Zheng return -ENOTSUP; 35164a1d5e1fSFam Zheng } 35174a1d5e1fSFam Zheng 35184a1d5e1fSFam Zheng /** 351965a9bb25SMarkus Armbruster * Return number of sectors on success, -errno on error. 352083f64091Sbellard */ 352165a9bb25SMarkus Armbruster int64_t bdrv_nb_sectors(BlockDriverState *bs) 352283f64091Sbellard { 352383f64091Sbellard BlockDriver *drv = bs->drv; 352465a9bb25SMarkus Armbruster 352583f64091Sbellard if (!drv) 352619cb3738Sbellard return -ENOMEDIUM; 352751762288SStefan Hajnoczi 3528b94a2610SKevin Wolf if (drv->has_variable_length) { 3529b94a2610SKevin Wolf int ret = refresh_total_sectors(bs, bs->total_sectors); 3530b94a2610SKevin Wolf if (ret < 0) { 3531b94a2610SKevin Wolf return ret; 3532fc01f7e7Sbellard } 353346a4e4e6SStefan Hajnoczi } 353465a9bb25SMarkus Armbruster return bs->total_sectors; 353565a9bb25SMarkus Armbruster } 353665a9bb25SMarkus Armbruster 353765a9bb25SMarkus Armbruster /** 353865a9bb25SMarkus Armbruster * Return length in bytes on success, -errno on error. 353965a9bb25SMarkus Armbruster * The length is always a multiple of BDRV_SECTOR_SIZE. 354065a9bb25SMarkus Armbruster */ 354165a9bb25SMarkus Armbruster int64_t bdrv_getlength(BlockDriverState *bs) 354265a9bb25SMarkus Armbruster { 354365a9bb25SMarkus Armbruster int64_t ret = bdrv_nb_sectors(bs); 354465a9bb25SMarkus Armbruster 354565a9bb25SMarkus Armbruster return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE; 354646a4e4e6SStefan Hajnoczi } 3547fc01f7e7Sbellard 354819cb3738Sbellard /* return 0 as number of sectors if no device present or error */ 354996b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr) 3550fc01f7e7Sbellard { 355165a9bb25SMarkus Armbruster int64_t nb_sectors = bdrv_nb_sectors(bs); 355265a9bb25SMarkus Armbruster 355365a9bb25SMarkus Armbruster *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors; 3554fc01f7e7Sbellard } 3555cf98951bSbellard 3556ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error, 3557ff06f5f3SPaolo Bonzini BlockdevOnError on_write_error) 3558abd7f68dSMarkus Armbruster { 3559abd7f68dSMarkus Armbruster bs->on_read_error = on_read_error; 3560abd7f68dSMarkus Armbruster bs->on_write_error = on_write_error; 3561abd7f68dSMarkus Armbruster } 3562abd7f68dSMarkus Armbruster 35631ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read) 3564abd7f68dSMarkus Armbruster { 3565abd7f68dSMarkus Armbruster return is_read ? bs->on_read_error : bs->on_write_error; 3566abd7f68dSMarkus Armbruster } 3567abd7f68dSMarkus Armbruster 35683e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error) 35693e1caa5fSPaolo Bonzini { 35703e1caa5fSPaolo Bonzini BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error; 35713e1caa5fSPaolo Bonzini 35723e1caa5fSPaolo Bonzini switch (on_err) { 35733e1caa5fSPaolo Bonzini case BLOCKDEV_ON_ERROR_ENOSPC: 3574a589569fSWenchao Xia return (error == ENOSPC) ? 3575a589569fSWenchao Xia BLOCK_ERROR_ACTION_STOP : BLOCK_ERROR_ACTION_REPORT; 35763e1caa5fSPaolo Bonzini case BLOCKDEV_ON_ERROR_STOP: 3577a589569fSWenchao Xia return BLOCK_ERROR_ACTION_STOP; 35783e1caa5fSPaolo Bonzini case BLOCKDEV_ON_ERROR_REPORT: 3579a589569fSWenchao Xia return BLOCK_ERROR_ACTION_REPORT; 35803e1caa5fSPaolo Bonzini case BLOCKDEV_ON_ERROR_IGNORE: 3581a589569fSWenchao Xia return BLOCK_ERROR_ACTION_IGNORE; 35823e1caa5fSPaolo Bonzini default: 35833e1caa5fSPaolo Bonzini abort(); 35843e1caa5fSPaolo Bonzini } 35853e1caa5fSPaolo Bonzini } 35863e1caa5fSPaolo Bonzini 3587c7c2ff0cSLuiz Capitulino static void send_qmp_error_event(BlockDriverState *bs, 3588c7c2ff0cSLuiz Capitulino BlockErrorAction action, 3589c7c2ff0cSLuiz Capitulino bool is_read, int error) 3590c7c2ff0cSLuiz Capitulino { 3591573742a5SPeter Maydell IoOperationType optype; 3592c7c2ff0cSLuiz Capitulino 3593573742a5SPeter Maydell optype = is_read ? IO_OPERATION_TYPE_READ : IO_OPERATION_TYPE_WRITE; 3594573742a5SPeter Maydell qapi_event_send_block_io_error(bdrv_get_device_name(bs), optype, action, 3595c7c2ff0cSLuiz Capitulino bdrv_iostatus_is_enabled(bs), 3596624ff573SLuiz Capitulino error == ENOSPC, strerror(error), 3597624ff573SLuiz Capitulino &error_abort); 3598c7c2ff0cSLuiz Capitulino } 3599c7c2ff0cSLuiz Capitulino 36003e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows 36013e1caa5fSPaolo Bonzini * about the error, it does not know whether an operation comes from 36023e1caa5fSPaolo Bonzini * the device or the block layer (from a job, for example). 36033e1caa5fSPaolo Bonzini */ 36043e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action, 36053e1caa5fSPaolo Bonzini bool is_read, int error) 36063e1caa5fSPaolo Bonzini { 36073e1caa5fSPaolo Bonzini assert(error >= 0); 36082bd3bce8SPaolo Bonzini 3609a589569fSWenchao Xia if (action == BLOCK_ERROR_ACTION_STOP) { 36102bd3bce8SPaolo Bonzini /* First set the iostatus, so that "info block" returns an iostatus 36112bd3bce8SPaolo Bonzini * that matches the events raised so far (an additional error iostatus 36122bd3bce8SPaolo Bonzini * is fine, but not a lost one). 36132bd3bce8SPaolo Bonzini */ 36143e1caa5fSPaolo Bonzini bdrv_iostatus_set_err(bs, error); 36152bd3bce8SPaolo Bonzini 36162bd3bce8SPaolo Bonzini /* Then raise the request to stop the VM and the event. 36172bd3bce8SPaolo Bonzini * qemu_system_vmstop_request_prepare has two effects. First, 36182bd3bce8SPaolo Bonzini * it ensures that the STOP event always comes after the 36192bd3bce8SPaolo Bonzini * BLOCK_IO_ERROR event. Second, it ensures that even if management 36202bd3bce8SPaolo Bonzini * can observe the STOP event and do a "cont" before the STOP 36212bd3bce8SPaolo Bonzini * event is issued, the VM will not stop. In this case, vm_start() 36222bd3bce8SPaolo Bonzini * also ensures that the STOP/RESUME pair of events is emitted. 36232bd3bce8SPaolo Bonzini */ 36242bd3bce8SPaolo Bonzini qemu_system_vmstop_request_prepare(); 3625c7c2ff0cSLuiz Capitulino send_qmp_error_event(bs, action, is_read, error); 36262bd3bce8SPaolo Bonzini qemu_system_vmstop_request(RUN_STATE_IO_ERROR); 36272bd3bce8SPaolo Bonzini } else { 3628c7c2ff0cSLuiz Capitulino send_qmp_error_event(bs, action, is_read, error); 36293e1caa5fSPaolo Bonzini } 36303e1caa5fSPaolo Bonzini } 36313e1caa5fSPaolo Bonzini 3632b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs) 3633b338082bSbellard { 3634b338082bSbellard return bs->read_only; 3635b338082bSbellard } 3636b338082bSbellard 3637985a03b0Sths int bdrv_is_sg(BlockDriverState *bs) 3638985a03b0Sths { 3639985a03b0Sths return bs->sg; 3640985a03b0Sths } 3641985a03b0Sths 3642e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs) 3643e900a7b7SChristoph Hellwig { 3644e900a7b7SChristoph Hellwig return bs->enable_write_cache; 3645e900a7b7SChristoph Hellwig } 3646e900a7b7SChristoph Hellwig 3647425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce) 3648425b0148SPaolo Bonzini { 3649425b0148SPaolo Bonzini bs->enable_write_cache = wce; 365055b110f2SJeff Cody 365155b110f2SJeff Cody /* so a reopen() will preserve wce */ 365255b110f2SJeff Cody if (wce) { 365355b110f2SJeff Cody bs->open_flags |= BDRV_O_CACHE_WB; 365455b110f2SJeff Cody } else { 365555b110f2SJeff Cody bs->open_flags &= ~BDRV_O_CACHE_WB; 365655b110f2SJeff Cody } 3657425b0148SPaolo Bonzini } 3658425b0148SPaolo Bonzini 3659ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs) 3660ea2384d3Sbellard { 3661ea2384d3Sbellard if (bs->backing_hd && bs->backing_hd->encrypted) 3662ea2384d3Sbellard return 1; 3663ea2384d3Sbellard return bs->encrypted; 3664ea2384d3Sbellard } 3665ea2384d3Sbellard 3666c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs) 3667c0f4ce77Saliguori { 3668c0f4ce77Saliguori BlockDriverState *backing_hd = bs->backing_hd; 3669c0f4ce77Saliguori 3670c0f4ce77Saliguori if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key) 3671c0f4ce77Saliguori return 1; 3672c0f4ce77Saliguori return (bs->encrypted && !bs->valid_key); 3673c0f4ce77Saliguori } 3674c0f4ce77Saliguori 3675ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key) 3676ea2384d3Sbellard { 3677ea2384d3Sbellard int ret; 3678ea2384d3Sbellard if (bs->backing_hd && bs->backing_hd->encrypted) { 3679ea2384d3Sbellard ret = bdrv_set_key(bs->backing_hd, key); 3680ea2384d3Sbellard if (ret < 0) 3681ea2384d3Sbellard return ret; 3682ea2384d3Sbellard if (!bs->encrypted) 3683ea2384d3Sbellard return 0; 3684ea2384d3Sbellard } 3685fd04a2aeSShahar Havivi if (!bs->encrypted) { 3686fd04a2aeSShahar Havivi return -EINVAL; 3687fd04a2aeSShahar Havivi } else if (!bs->drv || !bs->drv->bdrv_set_key) { 3688fd04a2aeSShahar Havivi return -ENOMEDIUM; 3689fd04a2aeSShahar Havivi } 3690c0f4ce77Saliguori ret = bs->drv->bdrv_set_key(bs, key); 3691bb5fc20fSaliguori if (ret < 0) { 3692bb5fc20fSaliguori bs->valid_key = 0; 3693bb5fc20fSaliguori } else if (!bs->valid_key) { 3694bb5fc20fSaliguori bs->valid_key = 1; 3695a7f53e26SMarkus Armbruster if (bs->blk) { 3696bb5fc20fSaliguori /* call the change callback now, we skipped it on open */ 3697a7f53e26SMarkus Armbruster blk_dev_change_media_cb(bs->blk, true); 3698a7f53e26SMarkus Armbruster } 3699bb5fc20fSaliguori } 3700c0f4ce77Saliguori return ret; 3701ea2384d3Sbellard } 3702ea2384d3Sbellard 3703f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs) 3704ea2384d3Sbellard { 3705f8d6bba1SMarkus Armbruster return bs->drv ? bs->drv->format_name : NULL; 3706ea2384d3Sbellard } 3707ea2384d3Sbellard 3708ada42401SStefan Hajnoczi static int qsort_strcmp(const void *a, const void *b) 3709ada42401SStefan Hajnoczi { 3710ada42401SStefan Hajnoczi return strcmp(a, b); 3711ada42401SStefan Hajnoczi } 3712ada42401SStefan Hajnoczi 3713ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name), 3714ea2384d3Sbellard void *opaque) 3715ea2384d3Sbellard { 3716ea2384d3Sbellard BlockDriver *drv; 3717e855e4fbSJeff Cody int count = 0; 3718ada42401SStefan Hajnoczi int i; 3719e855e4fbSJeff Cody const char **formats = NULL; 3720ea2384d3Sbellard 37218a22f02aSStefan Hajnoczi QLIST_FOREACH(drv, &bdrv_drivers, list) { 3722e855e4fbSJeff Cody if (drv->format_name) { 3723e855e4fbSJeff Cody bool found = false; 3724e855e4fbSJeff Cody int i = count; 3725e855e4fbSJeff Cody while (formats && i && !found) { 3726e855e4fbSJeff Cody found = !strcmp(formats[--i], drv->format_name); 3727e855e4fbSJeff Cody } 3728e855e4fbSJeff Cody 3729e855e4fbSJeff Cody if (!found) { 37305839e53bSMarkus Armbruster formats = g_renew(const char *, formats, count + 1); 3731e855e4fbSJeff Cody formats[count++] = drv->format_name; 3732ea2384d3Sbellard } 3733ea2384d3Sbellard } 3734e855e4fbSJeff Cody } 3735ada42401SStefan Hajnoczi 3736ada42401SStefan Hajnoczi qsort(formats, count, sizeof(formats[0]), qsort_strcmp); 3737ada42401SStefan Hajnoczi 3738ada42401SStefan Hajnoczi for (i = 0; i < count; i++) { 3739ada42401SStefan Hajnoczi it(opaque, formats[i]); 3740ada42401SStefan Hajnoczi } 3741ada42401SStefan Hajnoczi 3742e855e4fbSJeff Cody g_free(formats); 3743e855e4fbSJeff Cody } 3744ea2384d3Sbellard 3745dc364f4cSBenoît Canet /* This function is to find block backend bs */ 37467f06d47eSMarkus Armbruster /* TODO convert callers to blk_by_name(), then remove */ 3747b338082bSbellard BlockDriverState *bdrv_find(const char *name) 3748b338082bSbellard { 37497f06d47eSMarkus Armbruster BlockBackend *blk = blk_by_name(name); 3750b338082bSbellard 37517f06d47eSMarkus Armbruster return blk ? blk_bs(blk) : NULL; 3752b338082bSbellard } 3753b338082bSbellard 3754dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */ 3755dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name) 3756dc364f4cSBenoît Canet { 3757dc364f4cSBenoît Canet BlockDriverState *bs; 3758dc364f4cSBenoît Canet 3759dc364f4cSBenoît Canet assert(node_name); 3760dc364f4cSBenoît Canet 3761dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) { 3762dc364f4cSBenoît Canet if (!strcmp(node_name, bs->node_name)) { 3763dc364f4cSBenoît Canet return bs; 3764dc364f4cSBenoît Canet } 3765dc364f4cSBenoît Canet } 3766dc364f4cSBenoît Canet return NULL; 3767dc364f4cSBenoît Canet } 3768dc364f4cSBenoît Canet 3769c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */ 3770c13163fbSBenoît Canet BlockDeviceInfoList *bdrv_named_nodes_list(void) 3771c13163fbSBenoît Canet { 3772c13163fbSBenoît Canet BlockDeviceInfoList *list, *entry; 3773c13163fbSBenoît Canet BlockDriverState *bs; 3774c13163fbSBenoît Canet 3775c13163fbSBenoît Canet list = NULL; 3776c13163fbSBenoît Canet QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) { 3777c13163fbSBenoît Canet entry = g_malloc0(sizeof(*entry)); 3778c13163fbSBenoît Canet entry->value = bdrv_block_device_info(bs); 3779c13163fbSBenoît Canet entry->next = list; 3780c13163fbSBenoît Canet list = entry; 3781c13163fbSBenoît Canet } 3782c13163fbSBenoît Canet 3783c13163fbSBenoît Canet return list; 3784c13163fbSBenoît Canet } 3785c13163fbSBenoît Canet 378612d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device, 378712d3ba82SBenoît Canet const char *node_name, 378812d3ba82SBenoît Canet Error **errp) 378912d3ba82SBenoît Canet { 37907f06d47eSMarkus Armbruster BlockBackend *blk; 37917f06d47eSMarkus Armbruster BlockDriverState *bs; 379212d3ba82SBenoît Canet 379312d3ba82SBenoît Canet if (device) { 37947f06d47eSMarkus Armbruster blk = blk_by_name(device); 379512d3ba82SBenoît Canet 37967f06d47eSMarkus Armbruster if (blk) { 37977f06d47eSMarkus Armbruster return blk_bs(blk); 379812d3ba82SBenoît Canet } 3799dd67fa50SBenoît Canet } 380012d3ba82SBenoît Canet 3801dd67fa50SBenoît Canet if (node_name) { 380212d3ba82SBenoît Canet bs = bdrv_find_node(node_name); 380312d3ba82SBenoît Canet 3804dd67fa50SBenoît Canet if (bs) { 3805dd67fa50SBenoît Canet return bs; 3806dd67fa50SBenoît Canet } 380712d3ba82SBenoît Canet } 380812d3ba82SBenoît Canet 3809dd67fa50SBenoît Canet error_setg(errp, "Cannot find device=%s nor node_name=%s", 3810dd67fa50SBenoît Canet device ? device : "", 3811dd67fa50SBenoît Canet node_name ? node_name : ""); 3812dd67fa50SBenoît Canet return NULL; 381312d3ba82SBenoît Canet } 381412d3ba82SBenoît Canet 38155a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise, 38165a6684d2SJeff Cody * return false. If either argument is NULL, return false. */ 38175a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base) 38185a6684d2SJeff Cody { 38195a6684d2SJeff Cody while (top && top != base) { 38205a6684d2SJeff Cody top = top->backing_hd; 38215a6684d2SJeff Cody } 38225a6684d2SJeff Cody 38235a6684d2SJeff Cody return top != NULL; 38245a6684d2SJeff Cody } 38255a6684d2SJeff Cody 382604df765aSFam Zheng BlockDriverState *bdrv_next_node(BlockDriverState *bs) 382704df765aSFam Zheng { 382804df765aSFam Zheng if (!bs) { 382904df765aSFam Zheng return QTAILQ_FIRST(&graph_bdrv_states); 383004df765aSFam Zheng } 383104df765aSFam Zheng return QTAILQ_NEXT(bs, node_list); 383204df765aSFam Zheng } 383304df765aSFam Zheng 38342f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs) 38352f399b0aSMarkus Armbruster { 38362f399b0aSMarkus Armbruster if (!bs) { 38372f399b0aSMarkus Armbruster return QTAILQ_FIRST(&bdrv_states); 38382f399b0aSMarkus Armbruster } 3839dc364f4cSBenoît Canet return QTAILQ_NEXT(bs, device_list); 38402f399b0aSMarkus Armbruster } 38412f399b0aSMarkus Armbruster 384220a9e77dSFam Zheng const char *bdrv_get_node_name(const BlockDriverState *bs) 384320a9e77dSFam Zheng { 384420a9e77dSFam Zheng return bs->node_name; 384520a9e77dSFam Zheng } 384620a9e77dSFam Zheng 38477f06d47eSMarkus Armbruster /* TODO check what callers really want: bs->node_name or blk_name() */ 3848bfb197e0SMarkus Armbruster const char *bdrv_get_device_name(const BlockDriverState *bs) 3849ea2384d3Sbellard { 3850bfb197e0SMarkus Armbruster return bs->blk ? blk_name(bs->blk) : ""; 3851ea2384d3Sbellard } 3852ea2384d3Sbellard 3853c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs) 3854c8433287SMarkus Armbruster { 3855c8433287SMarkus Armbruster return bs->open_flags; 3856c8433287SMarkus Armbruster } 3857c8433287SMarkus Armbruster 3858f0f0fdfeSKevin Wolf int bdrv_flush_all(void) 3859c6ca28d6Saliguori { 3860c6ca28d6Saliguori BlockDriverState *bs; 3861f0f0fdfeSKevin Wolf int result = 0; 3862c6ca28d6Saliguori 3863dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 3864ed78cda3SStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 3865ed78cda3SStefan Hajnoczi int ret; 3866ed78cda3SStefan Hajnoczi 3867ed78cda3SStefan Hajnoczi aio_context_acquire(aio_context); 3868ed78cda3SStefan Hajnoczi ret = bdrv_flush(bs); 3869f0f0fdfeSKevin Wolf if (ret < 0 && !result) { 3870f0f0fdfeSKevin Wolf result = ret; 3871c6ca28d6Saliguori } 3872ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 38731b7bdbc1SStefan Hajnoczi } 3874c6ca28d6Saliguori 3875f0f0fdfeSKevin Wolf return result; 3876f0f0fdfeSKevin Wolf } 3877f0f0fdfeSKevin Wolf 38783ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs) 38793ac21627SPeter Lieven { 38803ac21627SPeter Lieven return 1; 38813ac21627SPeter Lieven } 38823ac21627SPeter Lieven 3883f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs) 3884f2feebbdSKevin Wolf { 3885f2feebbdSKevin Wolf assert(bs->drv); 3886f2feebbdSKevin Wolf 388711212d8fSPaolo Bonzini /* If BS is a copy on write image, it is initialized to 388811212d8fSPaolo Bonzini the contents of the base image, which may not be zeroes. */ 388911212d8fSPaolo Bonzini if (bs->backing_hd) { 389011212d8fSPaolo Bonzini return 0; 389111212d8fSPaolo Bonzini } 3892336c1c12SKevin Wolf if (bs->drv->bdrv_has_zero_init) { 3893336c1c12SKevin Wolf return bs->drv->bdrv_has_zero_init(bs); 3894f2feebbdSKevin Wolf } 3895f2feebbdSKevin Wolf 38963ac21627SPeter Lieven /* safe default */ 38973ac21627SPeter Lieven return 0; 3898f2feebbdSKevin Wolf } 3899f2feebbdSKevin Wolf 39004ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs) 39014ce78691SPeter Lieven { 39024ce78691SPeter Lieven BlockDriverInfo bdi; 39034ce78691SPeter Lieven 39044ce78691SPeter Lieven if (bs->backing_hd) { 39054ce78691SPeter Lieven return false; 39064ce78691SPeter Lieven } 39074ce78691SPeter Lieven 39084ce78691SPeter Lieven if (bdrv_get_info(bs, &bdi) == 0) { 39094ce78691SPeter Lieven return bdi.unallocated_blocks_are_zero; 39104ce78691SPeter Lieven } 39114ce78691SPeter Lieven 39124ce78691SPeter Lieven return false; 39134ce78691SPeter Lieven } 39144ce78691SPeter Lieven 39154ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs) 39164ce78691SPeter Lieven { 39174ce78691SPeter Lieven BlockDriverInfo bdi; 39184ce78691SPeter Lieven 39194ce78691SPeter Lieven if (bs->backing_hd || !(bs->open_flags & BDRV_O_UNMAP)) { 39204ce78691SPeter Lieven return false; 39214ce78691SPeter Lieven } 39224ce78691SPeter Lieven 39234ce78691SPeter Lieven if (bdrv_get_info(bs, &bdi) == 0) { 39244ce78691SPeter Lieven return bdi.can_write_zeroes_with_unmap; 39254ce78691SPeter Lieven } 39264ce78691SPeter Lieven 39274ce78691SPeter Lieven return false; 39284ce78691SPeter Lieven } 39294ce78691SPeter Lieven 3930b6b8a333SPaolo Bonzini typedef struct BdrvCoGetBlockStatusData { 3931376ae3f1SStefan Hajnoczi BlockDriverState *bs; 3932b35b2bbaSMiroslav Rezanina BlockDriverState *base; 3933376ae3f1SStefan Hajnoczi int64_t sector_num; 3934376ae3f1SStefan Hajnoczi int nb_sectors; 3935376ae3f1SStefan Hajnoczi int *pnum; 3936b6b8a333SPaolo Bonzini int64_t ret; 3937376ae3f1SStefan Hajnoczi bool done; 3938b6b8a333SPaolo Bonzini } BdrvCoGetBlockStatusData; 3939376ae3f1SStefan Hajnoczi 3940f58c7b35Sths /* 3941705be728SFam Zheng * Returns the allocation status of the specified sectors. 3942705be728SFam Zheng * Drivers not implementing the functionality are assumed to not support 3943705be728SFam Zheng * backing files, hence all their sectors are reported as allocated. 3944f58c7b35Sths * 3945bd9533e3SStefan Hajnoczi * If 'sector_num' is beyond the end of the disk image the return value is 0 3946bd9533e3SStefan Hajnoczi * and 'pnum' is set to 0. 3947bd9533e3SStefan Hajnoczi * 3948f58c7b35Sths * 'pnum' is set to the number of sectors (including and immediately following 3949f58c7b35Sths * the specified sector) that are known to be in the same 3950f58c7b35Sths * allocated/unallocated state. 3951f58c7b35Sths * 3952bd9533e3SStefan Hajnoczi * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes 3953bd9533e3SStefan Hajnoczi * beyond the end of the disk image it will be clamped. 3954f58c7b35Sths */ 3955b6b8a333SPaolo Bonzini static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs, 3956bdad13b9SPaolo Bonzini int64_t sector_num, 3957060f51c9SStefan Hajnoczi int nb_sectors, int *pnum) 3958f58c7b35Sths { 395930a7f2fcSMarkus Armbruster int64_t total_sectors; 3960f58c7b35Sths int64_t n; 39615daa74a6SPaolo Bonzini int64_t ret, ret2; 3962bd9533e3SStefan Hajnoczi 396330a7f2fcSMarkus Armbruster total_sectors = bdrv_nb_sectors(bs); 396430a7f2fcSMarkus Armbruster if (total_sectors < 0) { 396530a7f2fcSMarkus Armbruster return total_sectors; 3966617ccb46SPaolo Bonzini } 3967617ccb46SPaolo Bonzini 396830a7f2fcSMarkus Armbruster if (sector_num >= total_sectors) { 39696aebab14SStefan Hajnoczi *pnum = 0; 39706aebab14SStefan Hajnoczi return 0; 39716aebab14SStefan Hajnoczi } 3972bd9533e3SStefan Hajnoczi 397330a7f2fcSMarkus Armbruster n = total_sectors - sector_num; 3974bd9533e3SStefan Hajnoczi if (n < nb_sectors) { 3975bd9533e3SStefan Hajnoczi nb_sectors = n; 3976bd9533e3SStefan Hajnoczi } 3977bd9533e3SStefan Hajnoczi 3978b6b8a333SPaolo Bonzini if (!bs->drv->bdrv_co_get_block_status) { 3979bd9533e3SStefan Hajnoczi *pnum = nb_sectors; 3980e88ae226SKevin Wolf ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED; 3981918e92d7SPaolo Bonzini if (bs->drv->protocol_name) { 3982918e92d7SPaolo Bonzini ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE); 3983918e92d7SPaolo Bonzini } 3984918e92d7SPaolo Bonzini return ret; 39856aebab14SStefan Hajnoczi } 39866aebab14SStefan Hajnoczi 3987415b5b01SPaolo Bonzini ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum); 3988415b5b01SPaolo Bonzini if (ret < 0) { 39893e0a233dSPeter Lieven *pnum = 0; 3990415b5b01SPaolo Bonzini return ret; 3991415b5b01SPaolo Bonzini } 3992415b5b01SPaolo Bonzini 399392bc50a5SPeter Lieven if (ret & BDRV_BLOCK_RAW) { 399492bc50a5SPeter Lieven assert(ret & BDRV_BLOCK_OFFSET_VALID); 399592bc50a5SPeter Lieven return bdrv_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS, 399692bc50a5SPeter Lieven *pnum, pnum); 399792bc50a5SPeter Lieven } 399892bc50a5SPeter Lieven 3999e88ae226SKevin Wolf if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) { 4000e88ae226SKevin Wolf ret |= BDRV_BLOCK_ALLOCATED; 4001e88ae226SKevin Wolf } 4002e88ae226SKevin Wolf 4003c3d86884SPeter Lieven if (!(ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO)) { 4004c3d86884SPeter Lieven if (bdrv_unallocated_blocks_are_zero(bs)) { 4005415b5b01SPaolo Bonzini ret |= BDRV_BLOCK_ZERO; 40061f9db224SPeter Lieven } else if (bs->backing_hd) { 4007f0ad5712SPaolo Bonzini BlockDriverState *bs2 = bs->backing_hd; 400830a7f2fcSMarkus Armbruster int64_t nb_sectors2 = bdrv_nb_sectors(bs2); 400930a7f2fcSMarkus Armbruster if (nb_sectors2 >= 0 && sector_num >= nb_sectors2) { 4010f0ad5712SPaolo Bonzini ret |= BDRV_BLOCK_ZERO; 4011f0ad5712SPaolo Bonzini } 4012f0ad5712SPaolo Bonzini } 4013415b5b01SPaolo Bonzini } 40145daa74a6SPaolo Bonzini 40155daa74a6SPaolo Bonzini if (bs->file && 40165daa74a6SPaolo Bonzini (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) && 40175daa74a6SPaolo Bonzini (ret & BDRV_BLOCK_OFFSET_VALID)) { 401859c9a95fSMax Reitz int file_pnum; 401959c9a95fSMax Reitz 40205daa74a6SPaolo Bonzini ret2 = bdrv_co_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS, 402159c9a95fSMax Reitz *pnum, &file_pnum); 40225daa74a6SPaolo Bonzini if (ret2 >= 0) { 40235daa74a6SPaolo Bonzini /* Ignore errors. This is just providing extra information, it 40245daa74a6SPaolo Bonzini * is useful but not necessary. 40255daa74a6SPaolo Bonzini */ 402659c9a95fSMax Reitz if (!file_pnum) { 402759c9a95fSMax Reitz /* !file_pnum indicates an offset at or beyond the EOF; it is 402859c9a95fSMax Reitz * perfectly valid for the format block driver to point to such 402959c9a95fSMax Reitz * offsets, so catch it and mark everything as zero */ 403059c9a95fSMax Reitz ret |= BDRV_BLOCK_ZERO; 403159c9a95fSMax Reitz } else { 403259c9a95fSMax Reitz /* Limit request to the range reported by the protocol driver */ 403359c9a95fSMax Reitz *pnum = file_pnum; 40345daa74a6SPaolo Bonzini ret |= (ret2 & BDRV_BLOCK_ZERO); 40355daa74a6SPaolo Bonzini } 40365daa74a6SPaolo Bonzini } 403759c9a95fSMax Reitz } 40385daa74a6SPaolo Bonzini 4039415b5b01SPaolo Bonzini return ret; 4040060f51c9SStefan Hajnoczi } 4041060f51c9SStefan Hajnoczi 4042b6b8a333SPaolo Bonzini /* Coroutine wrapper for bdrv_get_block_status() */ 4043b6b8a333SPaolo Bonzini static void coroutine_fn bdrv_get_block_status_co_entry(void *opaque) 4044060f51c9SStefan Hajnoczi { 4045b6b8a333SPaolo Bonzini BdrvCoGetBlockStatusData *data = opaque; 4046060f51c9SStefan Hajnoczi BlockDriverState *bs = data->bs; 4047060f51c9SStefan Hajnoczi 4048b6b8a333SPaolo Bonzini data->ret = bdrv_co_get_block_status(bs, data->sector_num, data->nb_sectors, 4049060f51c9SStefan Hajnoczi data->pnum); 4050060f51c9SStefan Hajnoczi data->done = true; 4051060f51c9SStefan Hajnoczi } 4052060f51c9SStefan Hajnoczi 4053060f51c9SStefan Hajnoczi /* 4054b6b8a333SPaolo Bonzini * Synchronous wrapper around bdrv_co_get_block_status(). 4055060f51c9SStefan Hajnoczi * 4056b6b8a333SPaolo Bonzini * See bdrv_co_get_block_status() for details. 4057060f51c9SStefan Hajnoczi */ 4058b6b8a333SPaolo Bonzini int64_t bdrv_get_block_status(BlockDriverState *bs, int64_t sector_num, 4059b6b8a333SPaolo Bonzini int nb_sectors, int *pnum) 4060060f51c9SStefan Hajnoczi { 4061376ae3f1SStefan Hajnoczi Coroutine *co; 4062b6b8a333SPaolo Bonzini BdrvCoGetBlockStatusData data = { 4063376ae3f1SStefan Hajnoczi .bs = bs, 4064376ae3f1SStefan Hajnoczi .sector_num = sector_num, 4065376ae3f1SStefan Hajnoczi .nb_sectors = nb_sectors, 4066376ae3f1SStefan Hajnoczi .pnum = pnum, 4067376ae3f1SStefan Hajnoczi .done = false, 4068376ae3f1SStefan Hajnoczi }; 4069376ae3f1SStefan Hajnoczi 4070bdad13b9SPaolo Bonzini if (qemu_in_coroutine()) { 4071bdad13b9SPaolo Bonzini /* Fast-path if already in coroutine context */ 4072b6b8a333SPaolo Bonzini bdrv_get_block_status_co_entry(&data); 4073bdad13b9SPaolo Bonzini } else { 40742572b37aSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 40752572b37aSStefan Hajnoczi 4076b6b8a333SPaolo Bonzini co = qemu_coroutine_create(bdrv_get_block_status_co_entry); 4077376ae3f1SStefan Hajnoczi qemu_coroutine_enter(co, &data); 4078376ae3f1SStefan Hajnoczi while (!data.done) { 40792572b37aSStefan Hajnoczi aio_poll(aio_context, true); 4080376ae3f1SStefan Hajnoczi } 4081bdad13b9SPaolo Bonzini } 4082376ae3f1SStefan Hajnoczi return data.ret; 4083376ae3f1SStefan Hajnoczi } 4084f58c7b35Sths 4085b6b8a333SPaolo Bonzini int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, 4086b6b8a333SPaolo Bonzini int nb_sectors, int *pnum) 4087b6b8a333SPaolo Bonzini { 40884333bb71SPaolo Bonzini int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum); 40894333bb71SPaolo Bonzini if (ret < 0) { 40904333bb71SPaolo Bonzini return ret; 40914333bb71SPaolo Bonzini } 409201fb2705SKevin Wolf return !!(ret & BDRV_BLOCK_ALLOCATED); 4093b6b8a333SPaolo Bonzini } 4094b6b8a333SPaolo Bonzini 4095188a7bbfSPaolo Bonzini /* 4096188a7bbfSPaolo Bonzini * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP] 4097188a7bbfSPaolo Bonzini * 4098188a7bbfSPaolo Bonzini * Return true if the given sector is allocated in any image between 4099188a7bbfSPaolo Bonzini * BASE and TOP (inclusive). BASE can be NULL to check if the given 4100188a7bbfSPaolo Bonzini * sector is allocated in any image of the chain. Return false otherwise. 4101188a7bbfSPaolo Bonzini * 4102188a7bbfSPaolo Bonzini * 'pnum' is set to the number of sectors (including and immediately following 4103188a7bbfSPaolo Bonzini * the specified sector) that are known to be in the same 4104188a7bbfSPaolo Bonzini * allocated/unallocated state. 4105188a7bbfSPaolo Bonzini * 4106188a7bbfSPaolo Bonzini */ 41074f578637SPaolo Bonzini int bdrv_is_allocated_above(BlockDriverState *top, 4108188a7bbfSPaolo Bonzini BlockDriverState *base, 4109188a7bbfSPaolo Bonzini int64_t sector_num, 4110188a7bbfSPaolo Bonzini int nb_sectors, int *pnum) 4111188a7bbfSPaolo Bonzini { 4112188a7bbfSPaolo Bonzini BlockDriverState *intermediate; 4113188a7bbfSPaolo Bonzini int ret, n = nb_sectors; 4114188a7bbfSPaolo Bonzini 4115188a7bbfSPaolo Bonzini intermediate = top; 4116188a7bbfSPaolo Bonzini while (intermediate && intermediate != base) { 4117188a7bbfSPaolo Bonzini int pnum_inter; 4118bdad13b9SPaolo Bonzini ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors, 4119188a7bbfSPaolo Bonzini &pnum_inter); 4120188a7bbfSPaolo Bonzini if (ret < 0) { 4121188a7bbfSPaolo Bonzini return ret; 4122188a7bbfSPaolo Bonzini } else if (ret) { 4123188a7bbfSPaolo Bonzini *pnum = pnum_inter; 4124188a7bbfSPaolo Bonzini return 1; 4125188a7bbfSPaolo Bonzini } 4126188a7bbfSPaolo Bonzini 4127188a7bbfSPaolo Bonzini /* 4128188a7bbfSPaolo Bonzini * [sector_num, nb_sectors] is unallocated on top but intermediate 4129188a7bbfSPaolo Bonzini * might have 4130188a7bbfSPaolo Bonzini * 4131188a7bbfSPaolo Bonzini * [sector_num+x, nr_sectors] allocated. 4132188a7bbfSPaolo Bonzini */ 413363ba17d3SVishvananda Ishaya if (n > pnum_inter && 413463ba17d3SVishvananda Ishaya (intermediate == top || 413563ba17d3SVishvananda Ishaya sector_num + pnum_inter < intermediate->total_sectors)) { 4136188a7bbfSPaolo Bonzini n = pnum_inter; 4137188a7bbfSPaolo Bonzini } 4138188a7bbfSPaolo Bonzini 4139188a7bbfSPaolo Bonzini intermediate = intermediate->backing_hd; 4140188a7bbfSPaolo Bonzini } 4141188a7bbfSPaolo Bonzini 4142188a7bbfSPaolo Bonzini *pnum = n; 4143188a7bbfSPaolo Bonzini return 0; 4144188a7bbfSPaolo Bonzini } 4145188a7bbfSPaolo Bonzini 4146045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs) 4147045df330Saliguori { 4148045df330Saliguori if (bs->backing_hd && bs->backing_hd->encrypted) 4149045df330Saliguori return bs->backing_file; 4150045df330Saliguori else if (bs->encrypted) 4151045df330Saliguori return bs->filename; 4152045df330Saliguori else 4153045df330Saliguori return NULL; 4154045df330Saliguori } 4155045df330Saliguori 415683f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs, 415783f64091Sbellard char *filename, int filename_size) 415883f64091Sbellard { 415983f64091Sbellard pstrcpy(filename, filename_size, bs->backing_file); 416083f64091Sbellard } 416183f64091Sbellard 4162faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num, 4163faea38e7Sbellard const uint8_t *buf, int nb_sectors) 4164faea38e7Sbellard { 4165faea38e7Sbellard BlockDriver *drv = bs->drv; 4166faea38e7Sbellard if (!drv) 416719cb3738Sbellard return -ENOMEDIUM; 4168faea38e7Sbellard if (!drv->bdrv_write_compressed) 4169faea38e7Sbellard return -ENOTSUP; 4170fbb7b4e0SKevin Wolf if (bdrv_check_request(bs, sector_num, nb_sectors)) 4171fbb7b4e0SKevin Wolf return -EIO; 41727cd1e32aSlirans@il.ibm.com 4173e4654d2dSFam Zheng assert(QLIST_EMPTY(&bs->dirty_bitmaps)); 41747cd1e32aSlirans@il.ibm.com 4175faea38e7Sbellard return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors); 4176faea38e7Sbellard } 4177faea38e7Sbellard 4178faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi) 4179faea38e7Sbellard { 4180faea38e7Sbellard BlockDriver *drv = bs->drv; 4181faea38e7Sbellard if (!drv) 418219cb3738Sbellard return -ENOMEDIUM; 4183faea38e7Sbellard if (!drv->bdrv_get_info) 4184faea38e7Sbellard return -ENOTSUP; 4185faea38e7Sbellard memset(bdi, 0, sizeof(*bdi)); 4186faea38e7Sbellard return drv->bdrv_get_info(bs, bdi); 4187faea38e7Sbellard } 4188faea38e7Sbellard 4189eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs) 4190eae041feSMax Reitz { 4191eae041feSMax Reitz BlockDriver *drv = bs->drv; 4192eae041feSMax Reitz if (drv && drv->bdrv_get_specific_info) { 4193eae041feSMax Reitz return drv->bdrv_get_specific_info(bs); 4194eae041feSMax Reitz } 4195eae041feSMax Reitz return NULL; 4196eae041feSMax Reitz } 4197eae041feSMax Reitz 419845566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf, 419945566e9cSChristoph Hellwig int64_t pos, int size) 4200178e08a5Saliguori { 4201cf8074b3SKevin Wolf QEMUIOVector qiov; 4202cf8074b3SKevin Wolf struct iovec iov = { 4203cf8074b3SKevin Wolf .iov_base = (void *) buf, 4204cf8074b3SKevin Wolf .iov_len = size, 4205cf8074b3SKevin Wolf }; 4206cf8074b3SKevin Wolf 4207cf8074b3SKevin Wolf qemu_iovec_init_external(&qiov, &iov, 1); 4208cf8074b3SKevin Wolf return bdrv_writev_vmstate(bs, &qiov, pos); 4209cf8074b3SKevin Wolf } 4210cf8074b3SKevin Wolf 4211cf8074b3SKevin Wolf int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos) 4212cf8074b3SKevin Wolf { 4213178e08a5Saliguori BlockDriver *drv = bs->drv; 4214cf8074b3SKevin Wolf 4215cf8074b3SKevin Wolf if (!drv) { 4216178e08a5Saliguori return -ENOMEDIUM; 4217cf8074b3SKevin Wolf } else if (drv->bdrv_save_vmstate) { 4218cf8074b3SKevin Wolf return drv->bdrv_save_vmstate(bs, qiov, pos); 4219cf8074b3SKevin Wolf } else if (bs->file) { 4220cf8074b3SKevin Wolf return bdrv_writev_vmstate(bs->file, qiov, pos); 4221cf8074b3SKevin Wolf } 4222cf8074b3SKevin Wolf 42237cdb1f6dSMORITA Kazutaka return -ENOTSUP; 4224178e08a5Saliguori } 4225178e08a5Saliguori 422645566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf, 422745566e9cSChristoph Hellwig int64_t pos, int size) 4228178e08a5Saliguori { 4229178e08a5Saliguori BlockDriver *drv = bs->drv; 4230178e08a5Saliguori if (!drv) 4231178e08a5Saliguori return -ENOMEDIUM; 42327cdb1f6dSMORITA Kazutaka if (drv->bdrv_load_vmstate) 423345566e9cSChristoph Hellwig return drv->bdrv_load_vmstate(bs, buf, pos, size); 42347cdb1f6dSMORITA Kazutaka if (bs->file) 42357cdb1f6dSMORITA Kazutaka return bdrv_load_vmstate(bs->file, buf, pos, size); 42367cdb1f6dSMORITA Kazutaka return -ENOTSUP; 4237178e08a5Saliguori } 4238178e08a5Saliguori 42398b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event) 42408b9b0cc2SKevin Wolf { 4241bf736fe3SKevin Wolf if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) { 42428b9b0cc2SKevin Wolf return; 42438b9b0cc2SKevin Wolf } 42448b9b0cc2SKevin Wolf 4245bf736fe3SKevin Wolf bs->drv->bdrv_debug_event(bs, event); 424641c695c7SKevin Wolf } 42478b9b0cc2SKevin Wolf 424841c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event, 424941c695c7SKevin Wolf const char *tag) 425041c695c7SKevin Wolf { 425141c695c7SKevin Wolf while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) { 425241c695c7SKevin Wolf bs = bs->file; 425341c695c7SKevin Wolf } 425441c695c7SKevin Wolf 425541c695c7SKevin Wolf if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) { 425641c695c7SKevin Wolf return bs->drv->bdrv_debug_breakpoint(bs, event, tag); 425741c695c7SKevin Wolf } 425841c695c7SKevin Wolf 425941c695c7SKevin Wolf return -ENOTSUP; 426041c695c7SKevin Wolf } 426141c695c7SKevin Wolf 42624cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag) 42634cc70e93SFam Zheng { 42644cc70e93SFam Zheng while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) { 42654cc70e93SFam Zheng bs = bs->file; 42664cc70e93SFam Zheng } 42674cc70e93SFam Zheng 42684cc70e93SFam Zheng if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) { 42694cc70e93SFam Zheng return bs->drv->bdrv_debug_remove_breakpoint(bs, tag); 42704cc70e93SFam Zheng } 42714cc70e93SFam Zheng 42724cc70e93SFam Zheng return -ENOTSUP; 42734cc70e93SFam Zheng } 42744cc70e93SFam Zheng 427541c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag) 427641c695c7SKevin Wolf { 4277938789eaSMax Reitz while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) { 427841c695c7SKevin Wolf bs = bs->file; 427941c695c7SKevin Wolf } 428041c695c7SKevin Wolf 428141c695c7SKevin Wolf if (bs && bs->drv && bs->drv->bdrv_debug_resume) { 428241c695c7SKevin Wolf return bs->drv->bdrv_debug_resume(bs, tag); 428341c695c7SKevin Wolf } 428441c695c7SKevin Wolf 428541c695c7SKevin Wolf return -ENOTSUP; 428641c695c7SKevin Wolf } 428741c695c7SKevin Wolf 428841c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag) 428941c695c7SKevin Wolf { 429041c695c7SKevin Wolf while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) { 429141c695c7SKevin Wolf bs = bs->file; 429241c695c7SKevin Wolf } 429341c695c7SKevin Wolf 429441c695c7SKevin Wolf if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) { 429541c695c7SKevin Wolf return bs->drv->bdrv_debug_is_suspended(bs, tag); 429641c695c7SKevin Wolf } 429741c695c7SKevin Wolf 429841c695c7SKevin Wolf return false; 42998b9b0cc2SKevin Wolf } 43008b9b0cc2SKevin Wolf 4301199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs) 4302199630b6SBlue Swirl { 4303199630b6SBlue Swirl return !!(bs->open_flags & BDRV_O_SNAPSHOT); 4304199630b6SBlue Swirl } 4305199630b6SBlue Swirl 4306b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol. If it is 4307b1b1d783SJeff Cody * relative, it must be relative to the chain. So, passing in bs->filename 4308b1b1d783SJeff Cody * from a BDS as backing_file should not be done, as that may be relative to 4309b1b1d783SJeff Cody * the CWD rather than the chain. */ 4310e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs, 4311e8a6bb9cSMarcelo Tosatti const char *backing_file) 4312e8a6bb9cSMarcelo Tosatti { 4313b1b1d783SJeff Cody char *filename_full = NULL; 4314b1b1d783SJeff Cody char *backing_file_full = NULL; 4315b1b1d783SJeff Cody char *filename_tmp = NULL; 4316b1b1d783SJeff Cody int is_protocol = 0; 4317b1b1d783SJeff Cody BlockDriverState *curr_bs = NULL; 4318b1b1d783SJeff Cody BlockDriverState *retval = NULL; 4319b1b1d783SJeff Cody 4320b1b1d783SJeff Cody if (!bs || !bs->drv || !backing_file) { 4321e8a6bb9cSMarcelo Tosatti return NULL; 4322e8a6bb9cSMarcelo Tosatti } 4323e8a6bb9cSMarcelo Tosatti 4324b1b1d783SJeff Cody filename_full = g_malloc(PATH_MAX); 4325b1b1d783SJeff Cody backing_file_full = g_malloc(PATH_MAX); 4326b1b1d783SJeff Cody filename_tmp = g_malloc(PATH_MAX); 4327b1b1d783SJeff Cody 4328b1b1d783SJeff Cody is_protocol = path_has_protocol(backing_file); 4329b1b1d783SJeff Cody 4330b1b1d783SJeff Cody for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) { 4331b1b1d783SJeff Cody 4332b1b1d783SJeff Cody /* If either of the filename paths is actually a protocol, then 4333b1b1d783SJeff Cody * compare unmodified paths; otherwise make paths relative */ 4334b1b1d783SJeff Cody if (is_protocol || path_has_protocol(curr_bs->backing_file)) { 4335b1b1d783SJeff Cody if (strcmp(backing_file, curr_bs->backing_file) == 0) { 4336b1b1d783SJeff Cody retval = curr_bs->backing_hd; 4337b1b1d783SJeff Cody break; 4338b1b1d783SJeff Cody } 4339e8a6bb9cSMarcelo Tosatti } else { 4340b1b1d783SJeff Cody /* If not an absolute filename path, make it relative to the current 4341b1b1d783SJeff Cody * image's filename path */ 4342b1b1d783SJeff Cody path_combine(filename_tmp, PATH_MAX, curr_bs->filename, 4343b1b1d783SJeff Cody backing_file); 4344b1b1d783SJeff Cody 4345b1b1d783SJeff Cody /* We are going to compare absolute pathnames */ 4346b1b1d783SJeff Cody if (!realpath(filename_tmp, filename_full)) { 4347b1b1d783SJeff Cody continue; 4348b1b1d783SJeff Cody } 4349b1b1d783SJeff Cody 4350b1b1d783SJeff Cody /* We need to make sure the backing filename we are comparing against 4351b1b1d783SJeff Cody * is relative to the current image filename (or absolute) */ 4352b1b1d783SJeff Cody path_combine(filename_tmp, PATH_MAX, curr_bs->filename, 4353b1b1d783SJeff Cody curr_bs->backing_file); 4354b1b1d783SJeff Cody 4355b1b1d783SJeff Cody if (!realpath(filename_tmp, backing_file_full)) { 4356b1b1d783SJeff Cody continue; 4357b1b1d783SJeff Cody } 4358b1b1d783SJeff Cody 4359b1b1d783SJeff Cody if (strcmp(backing_file_full, filename_full) == 0) { 4360b1b1d783SJeff Cody retval = curr_bs->backing_hd; 4361b1b1d783SJeff Cody break; 4362b1b1d783SJeff Cody } 4363e8a6bb9cSMarcelo Tosatti } 4364e8a6bb9cSMarcelo Tosatti } 4365e8a6bb9cSMarcelo Tosatti 4366b1b1d783SJeff Cody g_free(filename_full); 4367b1b1d783SJeff Cody g_free(backing_file_full); 4368b1b1d783SJeff Cody g_free(filename_tmp); 4369b1b1d783SJeff Cody return retval; 4370e8a6bb9cSMarcelo Tosatti } 4371e8a6bb9cSMarcelo Tosatti 4372f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs) 4373f198fd1cSBenoît Canet { 4374f198fd1cSBenoît Canet if (!bs->drv) { 4375f198fd1cSBenoît Canet return 0; 4376f198fd1cSBenoît Canet } 4377f198fd1cSBenoît Canet 4378f198fd1cSBenoît Canet if (!bs->backing_hd) { 4379f198fd1cSBenoît Canet return 0; 4380f198fd1cSBenoît Canet } 4381f198fd1cSBenoît Canet 4382f198fd1cSBenoît Canet return 1 + bdrv_get_backing_file_depth(bs->backing_hd); 4383f198fd1cSBenoît Canet } 4384f198fd1cSBenoît Canet 4385ea2384d3Sbellard /**************************************************************/ 438683f64091Sbellard /* async I/Os */ 4387ea2384d3Sbellard 43887c84b1b8SMarkus Armbruster BlockAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num, 4389f141eafeSaliguori QEMUIOVector *qiov, int nb_sectors, 4390097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque) 4391ea2384d3Sbellard { 4392bbf0a440SStefan Hajnoczi trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque); 4393bbf0a440SStefan Hajnoczi 4394d20d9b7cSPaolo Bonzini return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0, 43958c5873d6SStefan Hajnoczi cb, opaque, false); 439683f64091Sbellard } 439783f64091Sbellard 43987c84b1b8SMarkus Armbruster BlockAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num, 4399f141eafeSaliguori QEMUIOVector *qiov, int nb_sectors, 4400097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque) 44017674e7bfSbellard { 4402bbf0a440SStefan Hajnoczi trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque); 4403bbf0a440SStefan Hajnoczi 4404d20d9b7cSPaolo Bonzini return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0, 44058c5873d6SStefan Hajnoczi cb, opaque, true); 440683f64091Sbellard } 440783f64091Sbellard 44087c84b1b8SMarkus Armbruster BlockAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs, 4409d5ef94d4SPaolo Bonzini int64_t sector_num, int nb_sectors, BdrvRequestFlags flags, 4410097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque) 4411d5ef94d4SPaolo Bonzini { 4412d5ef94d4SPaolo Bonzini trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque); 4413d5ef94d4SPaolo Bonzini 4414d5ef94d4SPaolo Bonzini return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors, 4415d5ef94d4SPaolo Bonzini BDRV_REQ_ZERO_WRITE | flags, 4416d5ef94d4SPaolo Bonzini cb, opaque, true); 4417d5ef94d4SPaolo Bonzini } 4418d5ef94d4SPaolo Bonzini 441940b4f539SKevin Wolf 442040b4f539SKevin Wolf typedef struct MultiwriteCB { 442140b4f539SKevin Wolf int error; 442240b4f539SKevin Wolf int num_requests; 442340b4f539SKevin Wolf int num_callbacks; 442440b4f539SKevin Wolf struct { 4425097310b5SMarkus Armbruster BlockCompletionFunc *cb; 442640b4f539SKevin Wolf void *opaque; 442740b4f539SKevin Wolf QEMUIOVector *free_qiov; 442840b4f539SKevin Wolf } callbacks[]; 442940b4f539SKevin Wolf } MultiwriteCB; 443040b4f539SKevin Wolf 443140b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb) 443240b4f539SKevin Wolf { 443340b4f539SKevin Wolf int i; 443440b4f539SKevin Wolf 443540b4f539SKevin Wolf for (i = 0; i < mcb->num_callbacks; i++) { 443640b4f539SKevin Wolf mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error); 44371e1ea48dSStefan Hajnoczi if (mcb->callbacks[i].free_qiov) { 44381e1ea48dSStefan Hajnoczi qemu_iovec_destroy(mcb->callbacks[i].free_qiov); 44391e1ea48dSStefan Hajnoczi } 44407267c094SAnthony Liguori g_free(mcb->callbacks[i].free_qiov); 444140b4f539SKevin Wolf } 444240b4f539SKevin Wolf } 444340b4f539SKevin Wolf 444440b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret) 444540b4f539SKevin Wolf { 444640b4f539SKevin Wolf MultiwriteCB *mcb = opaque; 444740b4f539SKevin Wolf 44486d519a5fSStefan Hajnoczi trace_multiwrite_cb(mcb, ret); 44496d519a5fSStefan Hajnoczi 4450cb6d3ca0SKevin Wolf if (ret < 0 && !mcb->error) { 445140b4f539SKevin Wolf mcb->error = ret; 445240b4f539SKevin Wolf } 445340b4f539SKevin Wolf 445440b4f539SKevin Wolf mcb->num_requests--; 445540b4f539SKevin Wolf if (mcb->num_requests == 0) { 445640b4f539SKevin Wolf multiwrite_user_cb(mcb); 44577267c094SAnthony Liguori g_free(mcb); 445840b4f539SKevin Wolf } 445940b4f539SKevin Wolf } 446040b4f539SKevin Wolf 446140b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b) 446240b4f539SKevin Wolf { 446377be4366SChristoph Hellwig const BlockRequest *req1 = a, *req2 = b; 446477be4366SChristoph Hellwig 446577be4366SChristoph Hellwig /* 446677be4366SChristoph Hellwig * Note that we can't simply subtract req2->sector from req1->sector 446777be4366SChristoph Hellwig * here as that could overflow the return value. 446877be4366SChristoph Hellwig */ 446977be4366SChristoph Hellwig if (req1->sector > req2->sector) { 447077be4366SChristoph Hellwig return 1; 447177be4366SChristoph Hellwig } else if (req1->sector < req2->sector) { 447277be4366SChristoph Hellwig return -1; 447377be4366SChristoph Hellwig } else { 447477be4366SChristoph Hellwig return 0; 447577be4366SChristoph Hellwig } 447640b4f539SKevin Wolf } 447740b4f539SKevin Wolf 447840b4f539SKevin Wolf /* 447940b4f539SKevin Wolf * Takes a bunch of requests and tries to merge them. Returns the number of 448040b4f539SKevin Wolf * requests that remain after merging. 448140b4f539SKevin Wolf */ 448240b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs, 448340b4f539SKevin Wolf int num_reqs, MultiwriteCB *mcb) 448440b4f539SKevin Wolf { 448540b4f539SKevin Wolf int i, outidx; 448640b4f539SKevin Wolf 448740b4f539SKevin Wolf // Sort requests by start sector 448840b4f539SKevin Wolf qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare); 448940b4f539SKevin Wolf 449040b4f539SKevin Wolf // Check if adjacent requests touch the same clusters. If so, combine them, 449140b4f539SKevin Wolf // filling up gaps with zero sectors. 449240b4f539SKevin Wolf outidx = 0; 449340b4f539SKevin Wolf for (i = 1; i < num_reqs; i++) { 449440b4f539SKevin Wolf int merge = 0; 449540b4f539SKevin Wolf int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors; 449640b4f539SKevin Wolf 4497b6a127a1SPaolo Bonzini // Handle exactly sequential writes and overlapping writes. 449840b4f539SKevin Wolf if (reqs[i].sector <= oldreq_last) { 449940b4f539SKevin Wolf merge = 1; 450040b4f539SKevin Wolf } 450140b4f539SKevin Wolf 4502e2a305fbSChristoph Hellwig if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) { 4503e2a305fbSChristoph Hellwig merge = 0; 4504e2a305fbSChristoph Hellwig } 4505e2a305fbSChristoph Hellwig 45066c5a42acSPeter Lieven if (bs->bl.max_transfer_length && reqs[outidx].nb_sectors + 45076c5a42acSPeter Lieven reqs[i].nb_sectors > bs->bl.max_transfer_length) { 45086c5a42acSPeter Lieven merge = 0; 45096c5a42acSPeter Lieven } 45106c5a42acSPeter Lieven 451140b4f539SKevin Wolf if (merge) { 451240b4f539SKevin Wolf size_t size; 45137267c094SAnthony Liguori QEMUIOVector *qiov = g_malloc0(sizeof(*qiov)); 451440b4f539SKevin Wolf qemu_iovec_init(qiov, 451540b4f539SKevin Wolf reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1); 451640b4f539SKevin Wolf 451740b4f539SKevin Wolf // Add the first request to the merged one. If the requests are 451840b4f539SKevin Wolf // overlapping, drop the last sectors of the first request. 451940b4f539SKevin Wolf size = (reqs[i].sector - reqs[outidx].sector) << 9; 45201b093c48SMichael Tokarev qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size); 452140b4f539SKevin Wolf 4522b6a127a1SPaolo Bonzini // We should need to add any zeros between the two requests 4523b6a127a1SPaolo Bonzini assert (reqs[i].sector <= oldreq_last); 452440b4f539SKevin Wolf 452540b4f539SKevin Wolf // Add the second request 45261b093c48SMichael Tokarev qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size); 452740b4f539SKevin Wolf 4528391827ebSStefan Hajnoczi // Add tail of first request, if necessary 4529391827ebSStefan Hajnoczi if (qiov->size < reqs[outidx].qiov->size) { 4530391827ebSStefan Hajnoczi qemu_iovec_concat(qiov, reqs[outidx].qiov, qiov->size, 4531391827ebSStefan Hajnoczi reqs[outidx].qiov->size - qiov->size); 4532391827ebSStefan Hajnoczi } 4533391827ebSStefan Hajnoczi 4534cbf1dff2SKevin Wolf reqs[outidx].nb_sectors = qiov->size >> 9; 453540b4f539SKevin Wolf reqs[outidx].qiov = qiov; 453640b4f539SKevin Wolf 453740b4f539SKevin Wolf mcb->callbacks[i].free_qiov = reqs[outidx].qiov; 453840b4f539SKevin Wolf } else { 453940b4f539SKevin Wolf outidx++; 454040b4f539SKevin Wolf reqs[outidx].sector = reqs[i].sector; 454140b4f539SKevin Wolf reqs[outidx].nb_sectors = reqs[i].nb_sectors; 454240b4f539SKevin Wolf reqs[outidx].qiov = reqs[i].qiov; 454340b4f539SKevin Wolf } 454440b4f539SKevin Wolf } 454540b4f539SKevin Wolf 454640b4f539SKevin Wolf return outidx + 1; 454740b4f539SKevin Wolf } 454840b4f539SKevin Wolf 454940b4f539SKevin Wolf /* 455040b4f539SKevin Wolf * Submit multiple AIO write requests at once. 455140b4f539SKevin Wolf * 455240b4f539SKevin Wolf * On success, the function returns 0 and all requests in the reqs array have 455340b4f539SKevin Wolf * been submitted. In error case this function returns -1, and any of the 455440b4f539SKevin Wolf * requests may or may not be submitted yet. In particular, this means that the 455540b4f539SKevin Wolf * callback will be called for some of the requests, for others it won't. The 455640b4f539SKevin Wolf * caller must check the error field of the BlockRequest to wait for the right 455740b4f539SKevin Wolf * callbacks (if error != 0, no callback will be called). 455840b4f539SKevin Wolf * 455940b4f539SKevin Wolf * The implementation may modify the contents of the reqs array, e.g. to merge 456040b4f539SKevin Wolf * requests. However, the fields opaque and error are left unmodified as they 456140b4f539SKevin Wolf * are used to signal failure for a single request to the caller. 456240b4f539SKevin Wolf */ 456340b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs) 456440b4f539SKevin Wolf { 456540b4f539SKevin Wolf MultiwriteCB *mcb; 456640b4f539SKevin Wolf int i; 456740b4f539SKevin Wolf 4568301db7c2SRyan Harper /* don't submit writes if we don't have a medium */ 4569301db7c2SRyan Harper if (bs->drv == NULL) { 4570301db7c2SRyan Harper for (i = 0; i < num_reqs; i++) { 4571301db7c2SRyan Harper reqs[i].error = -ENOMEDIUM; 4572301db7c2SRyan Harper } 4573301db7c2SRyan Harper return -1; 4574301db7c2SRyan Harper } 4575301db7c2SRyan Harper 457640b4f539SKevin Wolf if (num_reqs == 0) { 457740b4f539SKevin Wolf return 0; 457840b4f539SKevin Wolf } 457940b4f539SKevin Wolf 458040b4f539SKevin Wolf // Create MultiwriteCB structure 45817267c094SAnthony Liguori mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks)); 458240b4f539SKevin Wolf mcb->num_requests = 0; 458340b4f539SKevin Wolf mcb->num_callbacks = num_reqs; 458440b4f539SKevin Wolf 458540b4f539SKevin Wolf for (i = 0; i < num_reqs; i++) { 458640b4f539SKevin Wolf mcb->callbacks[i].cb = reqs[i].cb; 458740b4f539SKevin Wolf mcb->callbacks[i].opaque = reqs[i].opaque; 458840b4f539SKevin Wolf } 458940b4f539SKevin Wolf 459040b4f539SKevin Wolf // Check for mergable requests 459140b4f539SKevin Wolf num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb); 459240b4f539SKevin Wolf 45936d519a5fSStefan Hajnoczi trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs); 45946d519a5fSStefan Hajnoczi 4595df9309fbSPaolo Bonzini /* Run the aio requests. */ 4596df9309fbSPaolo Bonzini mcb->num_requests = num_reqs; 459740b4f539SKevin Wolf for (i = 0; i < num_reqs; i++) { 4598d20d9b7cSPaolo Bonzini bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov, 4599d20d9b7cSPaolo Bonzini reqs[i].nb_sectors, reqs[i].flags, 4600d20d9b7cSPaolo Bonzini multiwrite_cb, mcb, 4601d20d9b7cSPaolo Bonzini true); 460240b4f539SKevin Wolf } 460340b4f539SKevin Wolf 460440b4f539SKevin Wolf return 0; 460540b4f539SKevin Wolf } 460640b4f539SKevin Wolf 46077c84b1b8SMarkus Armbruster void bdrv_aio_cancel(BlockAIOCB *acb) 460883f64091Sbellard { 460902c50efeSFam Zheng qemu_aio_ref(acb); 461002c50efeSFam Zheng bdrv_aio_cancel_async(acb); 461102c50efeSFam Zheng while (acb->refcnt > 1) { 461202c50efeSFam Zheng if (acb->aiocb_info->get_aio_context) { 461302c50efeSFam Zheng aio_poll(acb->aiocb_info->get_aio_context(acb), true); 461402c50efeSFam Zheng } else if (acb->bs) { 461502c50efeSFam Zheng aio_poll(bdrv_get_aio_context(acb->bs), true); 461602c50efeSFam Zheng } else { 461702c50efeSFam Zheng abort(); 461802c50efeSFam Zheng } 461902c50efeSFam Zheng } 46208007429aSFam Zheng qemu_aio_unref(acb); 462102c50efeSFam Zheng } 462202c50efeSFam Zheng 462302c50efeSFam Zheng /* Async version of aio cancel. The caller is not blocked if the acb implements 462402c50efeSFam Zheng * cancel_async, otherwise we do nothing and let the request normally complete. 462502c50efeSFam Zheng * In either case the completion callback must be called. */ 46267c84b1b8SMarkus Armbruster void bdrv_aio_cancel_async(BlockAIOCB *acb) 462702c50efeSFam Zheng { 462802c50efeSFam Zheng if (acb->aiocb_info->cancel_async) { 462902c50efeSFam Zheng acb->aiocb_info->cancel_async(acb); 463002c50efeSFam Zheng } 463183f64091Sbellard } 463283f64091Sbellard 463383f64091Sbellard /**************************************************************/ 463483f64091Sbellard /* async block device emulation */ 463583f64091Sbellard 46367c84b1b8SMarkus Armbruster typedef struct BlockAIOCBSync { 46377c84b1b8SMarkus Armbruster BlockAIOCB common; 4638c16b5a2cSChristoph Hellwig QEMUBH *bh; 4639c16b5a2cSChristoph Hellwig int ret; 4640c16b5a2cSChristoph Hellwig /* vector translation state */ 4641c16b5a2cSChristoph Hellwig QEMUIOVector *qiov; 4642c16b5a2cSChristoph Hellwig uint8_t *bounce; 4643c16b5a2cSChristoph Hellwig int is_write; 46447c84b1b8SMarkus Armbruster } BlockAIOCBSync; 4645c16b5a2cSChristoph Hellwig 4646d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_aiocb_info = { 46477c84b1b8SMarkus Armbruster .aiocb_size = sizeof(BlockAIOCBSync), 4648c16b5a2cSChristoph Hellwig }; 4649c16b5a2cSChristoph Hellwig 465083f64091Sbellard static void bdrv_aio_bh_cb(void *opaque) 4651beac80cdSbellard { 46527c84b1b8SMarkus Armbruster BlockAIOCBSync *acb = opaque; 4653f141eafeSaliguori 4654857d4f46SKevin Wolf if (!acb->is_write && acb->ret >= 0) { 465503396148SMichael Tokarev qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size); 4656857d4f46SKevin Wolf } 4657ceb42de8Saliguori qemu_vfree(acb->bounce); 4658ce1a14dcSpbrook acb->common.cb(acb->common.opaque, acb->ret); 46596a7ad299SDor Laor qemu_bh_delete(acb->bh); 466036afc451SAvi Kivity acb->bh = NULL; 46618007429aSFam Zheng qemu_aio_unref(acb); 4662beac80cdSbellard } 4663beac80cdSbellard 46647c84b1b8SMarkus Armbruster static BlockAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs, 4665f141eafeSaliguori int64_t sector_num, 4666f141eafeSaliguori QEMUIOVector *qiov, 4667f141eafeSaliguori int nb_sectors, 4668097310b5SMarkus Armbruster BlockCompletionFunc *cb, 4669f141eafeSaliguori void *opaque, 4670f141eafeSaliguori int is_write) 4671f141eafeSaliguori 4672ea2384d3Sbellard { 46737c84b1b8SMarkus Armbruster BlockAIOCBSync *acb; 467483f64091Sbellard 4675d7331bedSStefan Hajnoczi acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque); 4676f141eafeSaliguori acb->is_write = is_write; 4677f141eafeSaliguori acb->qiov = qiov; 4678857d4f46SKevin Wolf acb->bounce = qemu_try_blockalign(bs, qiov->size); 46792572b37aSStefan Hajnoczi acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_aio_bh_cb, acb); 4680f141eafeSaliguori 4681857d4f46SKevin Wolf if (acb->bounce == NULL) { 4682857d4f46SKevin Wolf acb->ret = -ENOMEM; 4683857d4f46SKevin Wolf } else if (is_write) { 4684d5e6b161SMichael Tokarev qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size); 46851ed20acfSStefan Hajnoczi acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors); 4686f141eafeSaliguori } else { 46871ed20acfSStefan Hajnoczi acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors); 4688f141eafeSaliguori } 4689f141eafeSaliguori 4690ce1a14dcSpbrook qemu_bh_schedule(acb->bh); 4691f141eafeSaliguori 4692ce1a14dcSpbrook return &acb->common; 46937a6cba61Spbrook } 46947a6cba61Spbrook 46957c84b1b8SMarkus Armbruster static BlockAIOCB *bdrv_aio_readv_em(BlockDriverState *bs, 4696f141eafeSaliguori int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, 4697097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque) 469883f64091Sbellard { 4699f141eafeSaliguori return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0); 470083f64091Sbellard } 470183f64091Sbellard 47027c84b1b8SMarkus Armbruster static BlockAIOCB *bdrv_aio_writev_em(BlockDriverState *bs, 4703f141eafeSaliguori int64_t sector_num, QEMUIOVector *qiov, int nb_sectors, 4704097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque) 4705f141eafeSaliguori { 4706f141eafeSaliguori return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1); 4707f141eafeSaliguori } 4708f141eafeSaliguori 470968485420SKevin Wolf 47107c84b1b8SMarkus Armbruster typedef struct BlockAIOCBCoroutine { 47117c84b1b8SMarkus Armbruster BlockAIOCB common; 471268485420SKevin Wolf BlockRequest req; 471368485420SKevin Wolf bool is_write; 4714d318aea9SKevin Wolf bool *done; 471568485420SKevin Wolf QEMUBH* bh; 47167c84b1b8SMarkus Armbruster } BlockAIOCBCoroutine; 471768485420SKevin Wolf 4718d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_co_aiocb_info = { 47197c84b1b8SMarkus Armbruster .aiocb_size = sizeof(BlockAIOCBCoroutine), 472068485420SKevin Wolf }; 472168485420SKevin Wolf 472235246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque) 472368485420SKevin Wolf { 47247c84b1b8SMarkus Armbruster BlockAIOCBCoroutine *acb = opaque; 472568485420SKevin Wolf 472668485420SKevin Wolf acb->common.cb(acb->common.opaque, acb->req.error); 4727d318aea9SKevin Wolf 472868485420SKevin Wolf qemu_bh_delete(acb->bh); 47298007429aSFam Zheng qemu_aio_unref(acb); 473068485420SKevin Wolf } 473168485420SKevin Wolf 4732b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */ 4733b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque) 4734b2a61371SStefan Hajnoczi { 47357c84b1b8SMarkus Armbruster BlockAIOCBCoroutine *acb = opaque; 4736b2a61371SStefan Hajnoczi BlockDriverState *bs = acb->common.bs; 4737b2a61371SStefan Hajnoczi 4738b2a61371SStefan Hajnoczi if (!acb->is_write) { 4739b2a61371SStefan Hajnoczi acb->req.error = bdrv_co_do_readv(bs, acb->req.sector, 4740d20d9b7cSPaolo Bonzini acb->req.nb_sectors, acb->req.qiov, acb->req.flags); 4741b2a61371SStefan Hajnoczi } else { 4742b2a61371SStefan Hajnoczi acb->req.error = bdrv_co_do_writev(bs, acb->req.sector, 4743d20d9b7cSPaolo Bonzini acb->req.nb_sectors, acb->req.qiov, acb->req.flags); 4744b2a61371SStefan Hajnoczi } 4745b2a61371SStefan Hajnoczi 47462572b37aSStefan Hajnoczi acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb); 4747b2a61371SStefan Hajnoczi qemu_bh_schedule(acb->bh); 4748b2a61371SStefan Hajnoczi } 4749b2a61371SStefan Hajnoczi 47507c84b1b8SMarkus Armbruster static BlockAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs, 475168485420SKevin Wolf int64_t sector_num, 475268485420SKevin Wolf QEMUIOVector *qiov, 475368485420SKevin Wolf int nb_sectors, 4754d20d9b7cSPaolo Bonzini BdrvRequestFlags flags, 4755097310b5SMarkus Armbruster BlockCompletionFunc *cb, 475668485420SKevin Wolf void *opaque, 47578c5873d6SStefan Hajnoczi bool is_write) 475868485420SKevin Wolf { 475968485420SKevin Wolf Coroutine *co; 47607c84b1b8SMarkus Armbruster BlockAIOCBCoroutine *acb; 476168485420SKevin Wolf 4762d7331bedSStefan Hajnoczi acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque); 476368485420SKevin Wolf acb->req.sector = sector_num; 476468485420SKevin Wolf acb->req.nb_sectors = nb_sectors; 476568485420SKevin Wolf acb->req.qiov = qiov; 4766d20d9b7cSPaolo Bonzini acb->req.flags = flags; 476768485420SKevin Wolf acb->is_write = is_write; 476868485420SKevin Wolf 47698c5873d6SStefan Hajnoczi co = qemu_coroutine_create(bdrv_co_do_rw); 477068485420SKevin Wolf qemu_coroutine_enter(co, acb); 477168485420SKevin Wolf 477268485420SKevin Wolf return &acb->common; 477368485420SKevin Wolf } 477468485420SKevin Wolf 477507f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque) 4776b2e12bc6SChristoph Hellwig { 47777c84b1b8SMarkus Armbruster BlockAIOCBCoroutine *acb = opaque; 477807f07615SPaolo Bonzini BlockDriverState *bs = acb->common.bs; 4779b2e12bc6SChristoph Hellwig 478007f07615SPaolo Bonzini acb->req.error = bdrv_co_flush(bs); 47812572b37aSStefan Hajnoczi acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb); 4782b2e12bc6SChristoph Hellwig qemu_bh_schedule(acb->bh); 4783b2e12bc6SChristoph Hellwig } 4784b2e12bc6SChristoph Hellwig 47857c84b1b8SMarkus Armbruster BlockAIOCB *bdrv_aio_flush(BlockDriverState *bs, 4786097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque) 4787016f5cf6SAlexander Graf { 478807f07615SPaolo Bonzini trace_bdrv_aio_flush(bs, opaque); 4789016f5cf6SAlexander Graf 479007f07615SPaolo Bonzini Coroutine *co; 47917c84b1b8SMarkus Armbruster BlockAIOCBCoroutine *acb; 4792016f5cf6SAlexander Graf 4793d7331bedSStefan Hajnoczi acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque); 4794d318aea9SKevin Wolf 479507f07615SPaolo Bonzini co = qemu_coroutine_create(bdrv_aio_flush_co_entry); 479607f07615SPaolo Bonzini qemu_coroutine_enter(co, acb); 4797016f5cf6SAlexander Graf 4798016f5cf6SAlexander Graf return &acb->common; 4799016f5cf6SAlexander Graf } 4800016f5cf6SAlexander Graf 48014265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque) 48024265d620SPaolo Bonzini { 48037c84b1b8SMarkus Armbruster BlockAIOCBCoroutine *acb = opaque; 48044265d620SPaolo Bonzini BlockDriverState *bs = acb->common.bs; 48054265d620SPaolo Bonzini 48064265d620SPaolo Bonzini acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors); 48072572b37aSStefan Hajnoczi acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb); 48084265d620SPaolo Bonzini qemu_bh_schedule(acb->bh); 48094265d620SPaolo Bonzini } 48104265d620SPaolo Bonzini 48117c84b1b8SMarkus Armbruster BlockAIOCB *bdrv_aio_discard(BlockDriverState *bs, 48124265d620SPaolo Bonzini int64_t sector_num, int nb_sectors, 4813097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque) 48144265d620SPaolo Bonzini { 48154265d620SPaolo Bonzini Coroutine *co; 48167c84b1b8SMarkus Armbruster BlockAIOCBCoroutine *acb; 48174265d620SPaolo Bonzini 48184265d620SPaolo Bonzini trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque); 48194265d620SPaolo Bonzini 4820d7331bedSStefan Hajnoczi acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque); 48214265d620SPaolo Bonzini acb->req.sector = sector_num; 48224265d620SPaolo Bonzini acb->req.nb_sectors = nb_sectors; 48234265d620SPaolo Bonzini co = qemu_coroutine_create(bdrv_aio_discard_co_entry); 48244265d620SPaolo Bonzini qemu_coroutine_enter(co, acb); 48254265d620SPaolo Bonzini 48264265d620SPaolo Bonzini return &acb->common; 48274265d620SPaolo Bonzini } 48284265d620SPaolo Bonzini 4829ea2384d3Sbellard void bdrv_init(void) 4830ea2384d3Sbellard { 48315efa9d5aSAnthony Liguori module_call_init(MODULE_INIT_BLOCK); 4832ea2384d3Sbellard } 4833ce1a14dcSpbrook 4834eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void) 4835eb852011SMarkus Armbruster { 4836eb852011SMarkus Armbruster use_bdrv_whitelist = 1; 4837eb852011SMarkus Armbruster bdrv_init(); 4838eb852011SMarkus Armbruster } 4839eb852011SMarkus Armbruster 4840d7331bedSStefan Hajnoczi void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs, 4841097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque) 48426bbff9a0Saliguori { 48437c84b1b8SMarkus Armbruster BlockAIOCB *acb; 4844ce1a14dcSpbrook 4845d7331bedSStefan Hajnoczi acb = g_slice_alloc(aiocb_info->aiocb_size); 4846d7331bedSStefan Hajnoczi acb->aiocb_info = aiocb_info; 4847ce1a14dcSpbrook acb->bs = bs; 4848ce1a14dcSpbrook acb->cb = cb; 4849ce1a14dcSpbrook acb->opaque = opaque; 4850f197fe2bSFam Zheng acb->refcnt = 1; 4851ce1a14dcSpbrook return acb; 4852ce1a14dcSpbrook } 4853ce1a14dcSpbrook 4854f197fe2bSFam Zheng void qemu_aio_ref(void *p) 4855f197fe2bSFam Zheng { 48567c84b1b8SMarkus Armbruster BlockAIOCB *acb = p; 4857f197fe2bSFam Zheng acb->refcnt++; 4858f197fe2bSFam Zheng } 4859f197fe2bSFam Zheng 48608007429aSFam Zheng void qemu_aio_unref(void *p) 4861ce1a14dcSpbrook { 48627c84b1b8SMarkus Armbruster BlockAIOCB *acb = p; 4863f197fe2bSFam Zheng assert(acb->refcnt > 0); 4864f197fe2bSFam Zheng if (--acb->refcnt == 0) { 4865d7331bedSStefan Hajnoczi g_slice_free1(acb->aiocb_info->aiocb_size, acb); 4866ce1a14dcSpbrook } 4867f197fe2bSFam Zheng } 486819cb3738Sbellard 486919cb3738Sbellard /**************************************************************/ 4870f9f05dc5SKevin Wolf /* Coroutine block device emulation */ 4871f9f05dc5SKevin Wolf 4872f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion { 4873f9f05dc5SKevin Wolf Coroutine *coroutine; 4874f9f05dc5SKevin Wolf int ret; 4875f9f05dc5SKevin Wolf } CoroutineIOCompletion; 4876f9f05dc5SKevin Wolf 4877f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret) 4878f9f05dc5SKevin Wolf { 4879f9f05dc5SKevin Wolf CoroutineIOCompletion *co = opaque; 4880f9f05dc5SKevin Wolf 4881f9f05dc5SKevin Wolf co->ret = ret; 4882f9f05dc5SKevin Wolf qemu_coroutine_enter(co->coroutine, NULL); 4883f9f05dc5SKevin Wolf } 4884f9f05dc5SKevin Wolf 4885f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num, 4886f9f05dc5SKevin Wolf int nb_sectors, QEMUIOVector *iov, 4887f9f05dc5SKevin Wolf bool is_write) 4888f9f05dc5SKevin Wolf { 4889f9f05dc5SKevin Wolf CoroutineIOCompletion co = { 4890f9f05dc5SKevin Wolf .coroutine = qemu_coroutine_self(), 4891f9f05dc5SKevin Wolf }; 48927c84b1b8SMarkus Armbruster BlockAIOCB *acb; 4893f9f05dc5SKevin Wolf 4894f9f05dc5SKevin Wolf if (is_write) { 4895a652d160SStefan Hajnoczi acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors, 4896f9f05dc5SKevin Wolf bdrv_co_io_em_complete, &co); 4897f9f05dc5SKevin Wolf } else { 4898a652d160SStefan Hajnoczi acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors, 4899f9f05dc5SKevin Wolf bdrv_co_io_em_complete, &co); 4900f9f05dc5SKevin Wolf } 4901f9f05dc5SKevin Wolf 490259370aaaSStefan Hajnoczi trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb); 4903f9f05dc5SKevin Wolf if (!acb) { 4904f9f05dc5SKevin Wolf return -EIO; 4905f9f05dc5SKevin Wolf } 4906f9f05dc5SKevin Wolf qemu_coroutine_yield(); 4907f9f05dc5SKevin Wolf 4908f9f05dc5SKevin Wolf return co.ret; 4909f9f05dc5SKevin Wolf } 4910f9f05dc5SKevin Wolf 4911f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs, 4912f9f05dc5SKevin Wolf int64_t sector_num, int nb_sectors, 4913f9f05dc5SKevin Wolf QEMUIOVector *iov) 4914f9f05dc5SKevin Wolf { 4915f9f05dc5SKevin Wolf return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false); 4916f9f05dc5SKevin Wolf } 4917f9f05dc5SKevin Wolf 4918f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs, 4919f9f05dc5SKevin Wolf int64_t sector_num, int nb_sectors, 4920f9f05dc5SKevin Wolf QEMUIOVector *iov) 4921f9f05dc5SKevin Wolf { 4922f9f05dc5SKevin Wolf return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true); 4923f9f05dc5SKevin Wolf } 4924f9f05dc5SKevin Wolf 492507f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque) 4926e7a8a783SKevin Wolf { 492707f07615SPaolo Bonzini RwCo *rwco = opaque; 492807f07615SPaolo Bonzini 492907f07615SPaolo Bonzini rwco->ret = bdrv_co_flush(rwco->bs); 493007f07615SPaolo Bonzini } 493107f07615SPaolo Bonzini 493207f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs) 493307f07615SPaolo Bonzini { 4934eb489bb1SKevin Wolf int ret; 4935eb489bb1SKevin Wolf 493629cdb251SPaolo Bonzini if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) { 493707f07615SPaolo Bonzini return 0; 4938eb489bb1SKevin Wolf } 4939eb489bb1SKevin Wolf 4940ca716364SKevin Wolf /* Write back cached data to the OS even with cache=unsafe */ 4941bf736fe3SKevin Wolf BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS); 4942eb489bb1SKevin Wolf if (bs->drv->bdrv_co_flush_to_os) { 4943eb489bb1SKevin Wolf ret = bs->drv->bdrv_co_flush_to_os(bs); 4944eb489bb1SKevin Wolf if (ret < 0) { 4945eb489bb1SKevin Wolf return ret; 4946eb489bb1SKevin Wolf } 4947eb489bb1SKevin Wolf } 4948eb489bb1SKevin Wolf 4949ca716364SKevin Wolf /* But don't actually force it to the disk with cache=unsafe */ 4950ca716364SKevin Wolf if (bs->open_flags & BDRV_O_NO_FLUSH) { 4951d4c82329SKevin Wolf goto flush_parent; 4952ca716364SKevin Wolf } 4953ca716364SKevin Wolf 4954bf736fe3SKevin Wolf BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK); 4955eb489bb1SKevin Wolf if (bs->drv->bdrv_co_flush_to_disk) { 495629cdb251SPaolo Bonzini ret = bs->drv->bdrv_co_flush_to_disk(bs); 495707f07615SPaolo Bonzini } else if (bs->drv->bdrv_aio_flush) { 49587c84b1b8SMarkus Armbruster BlockAIOCB *acb; 4959e7a8a783SKevin Wolf CoroutineIOCompletion co = { 4960e7a8a783SKevin Wolf .coroutine = qemu_coroutine_self(), 4961e7a8a783SKevin Wolf }; 4962e7a8a783SKevin Wolf 496307f07615SPaolo Bonzini acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co); 496407f07615SPaolo Bonzini if (acb == NULL) { 496529cdb251SPaolo Bonzini ret = -EIO; 496607f07615SPaolo Bonzini } else { 4967e7a8a783SKevin Wolf qemu_coroutine_yield(); 496829cdb251SPaolo Bonzini ret = co.ret; 4969e7a8a783SKevin Wolf } 497007f07615SPaolo Bonzini } else { 497107f07615SPaolo Bonzini /* 497207f07615SPaolo Bonzini * Some block drivers always operate in either writethrough or unsafe 497307f07615SPaolo Bonzini * mode and don't support bdrv_flush therefore. Usually qemu doesn't 497407f07615SPaolo Bonzini * know how the server works (because the behaviour is hardcoded or 497507f07615SPaolo Bonzini * depends on server-side configuration), so we can't ensure that 497607f07615SPaolo Bonzini * everything is safe on disk. Returning an error doesn't work because 497707f07615SPaolo Bonzini * that would break guests even if the server operates in writethrough 497807f07615SPaolo Bonzini * mode. 497907f07615SPaolo Bonzini * 498007f07615SPaolo Bonzini * Let's hope the user knows what he's doing. 498107f07615SPaolo Bonzini */ 498229cdb251SPaolo Bonzini ret = 0; 498307f07615SPaolo Bonzini } 498429cdb251SPaolo Bonzini if (ret < 0) { 498529cdb251SPaolo Bonzini return ret; 498629cdb251SPaolo Bonzini } 498729cdb251SPaolo Bonzini 498829cdb251SPaolo Bonzini /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH 498929cdb251SPaolo Bonzini * in the case of cache=unsafe, so there are no useless flushes. 499029cdb251SPaolo Bonzini */ 4991d4c82329SKevin Wolf flush_parent: 499229cdb251SPaolo Bonzini return bdrv_co_flush(bs->file); 499307f07615SPaolo Bonzini } 499407f07615SPaolo Bonzini 49955a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp) 49960f15423cSAnthony Liguori { 49975a8a30dbSKevin Wolf Error *local_err = NULL; 49985a8a30dbSKevin Wolf int ret; 49995a8a30dbSKevin Wolf 50003456a8d1SKevin Wolf if (!bs->drv) { 50013456a8d1SKevin Wolf return; 50020f15423cSAnthony Liguori } 50033456a8d1SKevin Wolf 50047ea2d269SAlexey Kardashevskiy if (!(bs->open_flags & BDRV_O_INCOMING)) { 50057ea2d269SAlexey Kardashevskiy return; 50067ea2d269SAlexey Kardashevskiy } 50077ea2d269SAlexey Kardashevskiy bs->open_flags &= ~BDRV_O_INCOMING; 50087ea2d269SAlexey Kardashevskiy 50093456a8d1SKevin Wolf if (bs->drv->bdrv_invalidate_cache) { 50105a8a30dbSKevin Wolf bs->drv->bdrv_invalidate_cache(bs, &local_err); 50113456a8d1SKevin Wolf } else if (bs->file) { 50125a8a30dbSKevin Wolf bdrv_invalidate_cache(bs->file, &local_err); 50135a8a30dbSKevin Wolf } 50145a8a30dbSKevin Wolf if (local_err) { 50155a8a30dbSKevin Wolf error_propagate(errp, local_err); 50165a8a30dbSKevin Wolf return; 50173456a8d1SKevin Wolf } 50183456a8d1SKevin Wolf 50195a8a30dbSKevin Wolf ret = refresh_total_sectors(bs, bs->total_sectors); 50205a8a30dbSKevin Wolf if (ret < 0) { 50215a8a30dbSKevin Wolf error_setg_errno(errp, -ret, "Could not refresh total sector count"); 50225a8a30dbSKevin Wolf return; 50235a8a30dbSKevin Wolf } 50240f15423cSAnthony Liguori } 50250f15423cSAnthony Liguori 50265a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp) 50270f15423cSAnthony Liguori { 50280f15423cSAnthony Liguori BlockDriverState *bs; 50295a8a30dbSKevin Wolf Error *local_err = NULL; 50300f15423cSAnthony Liguori 5031dc364f4cSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 5032ed78cda3SStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 5033ed78cda3SStefan Hajnoczi 5034ed78cda3SStefan Hajnoczi aio_context_acquire(aio_context); 50355a8a30dbSKevin Wolf bdrv_invalidate_cache(bs, &local_err); 5036ed78cda3SStefan Hajnoczi aio_context_release(aio_context); 50375a8a30dbSKevin Wolf if (local_err) { 50385a8a30dbSKevin Wolf error_propagate(errp, local_err); 50395a8a30dbSKevin Wolf return; 50405a8a30dbSKevin Wolf } 50410f15423cSAnthony Liguori } 50420f15423cSAnthony Liguori } 50430f15423cSAnthony Liguori 504407f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs) 504507f07615SPaolo Bonzini { 504607f07615SPaolo Bonzini Coroutine *co; 504707f07615SPaolo Bonzini RwCo rwco = { 504807f07615SPaolo Bonzini .bs = bs, 504907f07615SPaolo Bonzini .ret = NOT_DONE, 505007f07615SPaolo Bonzini }; 505107f07615SPaolo Bonzini 505207f07615SPaolo Bonzini if (qemu_in_coroutine()) { 505307f07615SPaolo Bonzini /* Fast-path if already in coroutine context */ 505407f07615SPaolo Bonzini bdrv_flush_co_entry(&rwco); 505507f07615SPaolo Bonzini } else { 50562572b37aSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 50572572b37aSStefan Hajnoczi 505807f07615SPaolo Bonzini co = qemu_coroutine_create(bdrv_flush_co_entry); 505907f07615SPaolo Bonzini qemu_coroutine_enter(co, &rwco); 506007f07615SPaolo Bonzini while (rwco.ret == NOT_DONE) { 50612572b37aSStefan Hajnoczi aio_poll(aio_context, true); 506207f07615SPaolo Bonzini } 506307f07615SPaolo Bonzini } 506407f07615SPaolo Bonzini 506507f07615SPaolo Bonzini return rwco.ret; 506607f07615SPaolo Bonzini } 5067e7a8a783SKevin Wolf 5068775aa8b6SKevin Wolf typedef struct DiscardCo { 5069775aa8b6SKevin Wolf BlockDriverState *bs; 5070775aa8b6SKevin Wolf int64_t sector_num; 5071775aa8b6SKevin Wolf int nb_sectors; 5072775aa8b6SKevin Wolf int ret; 5073775aa8b6SKevin Wolf } DiscardCo; 50744265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque) 50754265d620SPaolo Bonzini { 5076775aa8b6SKevin Wolf DiscardCo *rwco = opaque; 50774265d620SPaolo Bonzini 50784265d620SPaolo Bonzini rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors); 50794265d620SPaolo Bonzini } 50804265d620SPaolo Bonzini 50816f14da52SPeter Lieven /* if no limit is specified in the BlockLimits use a default 50826f14da52SPeter Lieven * of 32768 512-byte sectors (16 MiB) per request. 50836f14da52SPeter Lieven */ 50846f14da52SPeter Lieven #define MAX_DISCARD_DEFAULT 32768 50856f14da52SPeter Lieven 50864265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num, 50874265d620SPaolo Bonzini int nb_sectors) 50884265d620SPaolo Bonzini { 5089d51e9fe5SPaolo Bonzini int max_discard; 5090d51e9fe5SPaolo Bonzini 50914265d620SPaolo Bonzini if (!bs->drv) { 50924265d620SPaolo Bonzini return -ENOMEDIUM; 50934265d620SPaolo Bonzini } else if (bdrv_check_request(bs, sector_num, nb_sectors)) { 50944265d620SPaolo Bonzini return -EIO; 50954265d620SPaolo Bonzini } else if (bs->read_only) { 50964265d620SPaolo Bonzini return -EROFS; 5097df702c9bSPaolo Bonzini } 5098df702c9bSPaolo Bonzini 50998f0720ecSPaolo Bonzini bdrv_reset_dirty(bs, sector_num, nb_sectors); 5100df702c9bSPaolo Bonzini 51019e8f1835SPaolo Bonzini /* Do nothing if disabled. */ 51029e8f1835SPaolo Bonzini if (!(bs->open_flags & BDRV_O_UNMAP)) { 51039e8f1835SPaolo Bonzini return 0; 51049e8f1835SPaolo Bonzini } 51059e8f1835SPaolo Bonzini 5106d51e9fe5SPaolo Bonzini if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) { 5107d51e9fe5SPaolo Bonzini return 0; 5108d51e9fe5SPaolo Bonzini } 51096f14da52SPeter Lieven 5110d51e9fe5SPaolo Bonzini max_discard = bs->bl.max_discard ? bs->bl.max_discard : MAX_DISCARD_DEFAULT; 51116f14da52SPeter Lieven while (nb_sectors > 0) { 51126f14da52SPeter Lieven int ret; 51136f14da52SPeter Lieven int num = nb_sectors; 51146f14da52SPeter Lieven 51156f14da52SPeter Lieven /* align request */ 51166f14da52SPeter Lieven if (bs->bl.discard_alignment && 51176f14da52SPeter Lieven num >= bs->bl.discard_alignment && 51186f14da52SPeter Lieven sector_num % bs->bl.discard_alignment) { 51196f14da52SPeter Lieven if (num > bs->bl.discard_alignment) { 51206f14da52SPeter Lieven num = bs->bl.discard_alignment; 51216f14da52SPeter Lieven } 51226f14da52SPeter Lieven num -= sector_num % bs->bl.discard_alignment; 51236f14da52SPeter Lieven } 51246f14da52SPeter Lieven 51256f14da52SPeter Lieven /* limit request size */ 51266f14da52SPeter Lieven if (num > max_discard) { 51276f14da52SPeter Lieven num = max_discard; 51286f14da52SPeter Lieven } 51296f14da52SPeter Lieven 5130d51e9fe5SPaolo Bonzini if (bs->drv->bdrv_co_discard) { 51316f14da52SPeter Lieven ret = bs->drv->bdrv_co_discard(bs, sector_num, num); 5132d51e9fe5SPaolo Bonzini } else { 51337c84b1b8SMarkus Armbruster BlockAIOCB *acb; 51344265d620SPaolo Bonzini CoroutineIOCompletion co = { 51354265d620SPaolo Bonzini .coroutine = qemu_coroutine_self(), 51364265d620SPaolo Bonzini }; 51374265d620SPaolo Bonzini 51384265d620SPaolo Bonzini acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors, 51394265d620SPaolo Bonzini bdrv_co_io_em_complete, &co); 51404265d620SPaolo Bonzini if (acb == NULL) { 51414265d620SPaolo Bonzini return -EIO; 51424265d620SPaolo Bonzini } else { 51434265d620SPaolo Bonzini qemu_coroutine_yield(); 5144d51e9fe5SPaolo Bonzini ret = co.ret; 51454265d620SPaolo Bonzini } 5146d51e9fe5SPaolo Bonzini } 51477ce21016SPaolo Bonzini if (ret && ret != -ENOTSUP) { 5148d51e9fe5SPaolo Bonzini return ret; 5149d51e9fe5SPaolo Bonzini } 5150d51e9fe5SPaolo Bonzini 5151d51e9fe5SPaolo Bonzini sector_num += num; 5152d51e9fe5SPaolo Bonzini nb_sectors -= num; 5153d51e9fe5SPaolo Bonzini } 51544265d620SPaolo Bonzini return 0; 51554265d620SPaolo Bonzini } 51564265d620SPaolo Bonzini 51574265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors) 51584265d620SPaolo Bonzini { 51594265d620SPaolo Bonzini Coroutine *co; 5160775aa8b6SKevin Wolf DiscardCo rwco = { 51614265d620SPaolo Bonzini .bs = bs, 51624265d620SPaolo Bonzini .sector_num = sector_num, 51634265d620SPaolo Bonzini .nb_sectors = nb_sectors, 51644265d620SPaolo Bonzini .ret = NOT_DONE, 51654265d620SPaolo Bonzini }; 51664265d620SPaolo Bonzini 51674265d620SPaolo Bonzini if (qemu_in_coroutine()) { 51684265d620SPaolo Bonzini /* Fast-path if already in coroutine context */ 51694265d620SPaolo Bonzini bdrv_discard_co_entry(&rwco); 51704265d620SPaolo Bonzini } else { 51712572b37aSStefan Hajnoczi AioContext *aio_context = bdrv_get_aio_context(bs); 51722572b37aSStefan Hajnoczi 51734265d620SPaolo Bonzini co = qemu_coroutine_create(bdrv_discard_co_entry); 51744265d620SPaolo Bonzini qemu_coroutine_enter(co, &rwco); 51754265d620SPaolo Bonzini while (rwco.ret == NOT_DONE) { 51762572b37aSStefan Hajnoczi aio_poll(aio_context, true); 51774265d620SPaolo Bonzini } 51784265d620SPaolo Bonzini } 51794265d620SPaolo Bonzini 51804265d620SPaolo Bonzini return rwco.ret; 51814265d620SPaolo Bonzini } 51824265d620SPaolo Bonzini 5183f9f05dc5SKevin Wolf /**************************************************************/ 518419cb3738Sbellard /* removable device support */ 518519cb3738Sbellard 518619cb3738Sbellard /** 518719cb3738Sbellard * Return TRUE if the media is present 518819cb3738Sbellard */ 518919cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs) 519019cb3738Sbellard { 519119cb3738Sbellard BlockDriver *drv = bs->drv; 5192a1aff5bfSMarkus Armbruster 519319cb3738Sbellard if (!drv) 519419cb3738Sbellard return 0; 519519cb3738Sbellard if (!drv->bdrv_is_inserted) 5196a1aff5bfSMarkus Armbruster return 1; 5197a1aff5bfSMarkus Armbruster return drv->bdrv_is_inserted(bs); 519819cb3738Sbellard } 519919cb3738Sbellard 520019cb3738Sbellard /** 52018e49ca46SMarkus Armbruster * Return whether the media changed since the last call to this 52028e49ca46SMarkus Armbruster * function, or -ENOTSUP if we don't know. Most drivers don't know. 520319cb3738Sbellard */ 520419cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs) 520519cb3738Sbellard { 520619cb3738Sbellard BlockDriver *drv = bs->drv; 520719cb3738Sbellard 52088e49ca46SMarkus Armbruster if (drv && drv->bdrv_media_changed) { 52098e49ca46SMarkus Armbruster return drv->bdrv_media_changed(bs); 52108e49ca46SMarkus Armbruster } 52118e49ca46SMarkus Armbruster return -ENOTSUP; 521219cb3738Sbellard } 521319cb3738Sbellard 521419cb3738Sbellard /** 521519cb3738Sbellard * If eject_flag is TRUE, eject the media. Otherwise, close the tray 521619cb3738Sbellard */ 5217f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag) 521819cb3738Sbellard { 521919cb3738Sbellard BlockDriver *drv = bs->drv; 5220bfb197e0SMarkus Armbruster const char *device_name; 522119cb3738Sbellard 5222822e1cd1SMarkus Armbruster if (drv && drv->bdrv_eject) { 5223822e1cd1SMarkus Armbruster drv->bdrv_eject(bs, eject_flag); 522419cb3738Sbellard } 52256f382ed2SLuiz Capitulino 5226bfb197e0SMarkus Armbruster device_name = bdrv_get_device_name(bs); 5227bfb197e0SMarkus Armbruster if (device_name[0] != '\0') { 5228bfb197e0SMarkus Armbruster qapi_event_send_device_tray_moved(device_name, 5229a5ee7bd4SWenchao Xia eject_flag, &error_abort); 52306f382ed2SLuiz Capitulino } 523119cb3738Sbellard } 523219cb3738Sbellard 523319cb3738Sbellard /** 523419cb3738Sbellard * Lock or unlock the media (if it is locked, the user won't be able 523519cb3738Sbellard * to eject it manually). 523619cb3738Sbellard */ 5237025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked) 523819cb3738Sbellard { 523919cb3738Sbellard BlockDriver *drv = bs->drv; 524019cb3738Sbellard 5241025e849aSMarkus Armbruster trace_bdrv_lock_medium(bs, locked); 5242b8c6d095SStefan Hajnoczi 5243025e849aSMarkus Armbruster if (drv && drv->bdrv_lock_medium) { 5244025e849aSMarkus Armbruster drv->bdrv_lock_medium(bs, locked); 524519cb3738Sbellard } 524619cb3738Sbellard } 5247985a03b0Sths 5248985a03b0Sths /* needed for generic scsi interface */ 5249985a03b0Sths 5250985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf) 5251985a03b0Sths { 5252985a03b0Sths BlockDriver *drv = bs->drv; 5253985a03b0Sths 5254985a03b0Sths if (drv && drv->bdrv_ioctl) 5255985a03b0Sths return drv->bdrv_ioctl(bs, req, buf); 5256985a03b0Sths return -ENOTSUP; 5257985a03b0Sths } 52587d780669Saliguori 52597c84b1b8SMarkus Armbruster BlockAIOCB *bdrv_aio_ioctl(BlockDriverState *bs, 5260221f715dSaliguori unsigned long int req, void *buf, 5261097310b5SMarkus Armbruster BlockCompletionFunc *cb, void *opaque) 52627d780669Saliguori { 5263221f715dSaliguori BlockDriver *drv = bs->drv; 52647d780669Saliguori 5265221f715dSaliguori if (drv && drv->bdrv_aio_ioctl) 5266221f715dSaliguori return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque); 5267221f715dSaliguori return NULL; 52687d780669Saliguori } 5269e268ca52Saliguori 52701b7fd729SPaolo Bonzini void bdrv_set_guest_block_size(BlockDriverState *bs, int align) 52717b6f9300SMarkus Armbruster { 52721b7fd729SPaolo Bonzini bs->guest_block_size = align; 52737b6f9300SMarkus Armbruster } 52747cd1e32aSlirans@il.ibm.com 5275e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size) 5276e268ca52Saliguori { 5277339064d5SKevin Wolf return qemu_memalign(bdrv_opt_mem_align(bs), size); 5278e268ca52Saliguori } 52797cd1e32aSlirans@il.ibm.com 52809ebd8448SMax Reitz void *qemu_blockalign0(BlockDriverState *bs, size_t size) 52819ebd8448SMax Reitz { 52829ebd8448SMax Reitz return memset(qemu_blockalign(bs, size), 0, size); 52839ebd8448SMax Reitz } 52849ebd8448SMax Reitz 52857d2a35ccSKevin Wolf void *qemu_try_blockalign(BlockDriverState *bs, size_t size) 52867d2a35ccSKevin Wolf { 52877d2a35ccSKevin Wolf size_t align = bdrv_opt_mem_align(bs); 52887d2a35ccSKevin Wolf 52897d2a35ccSKevin Wolf /* Ensure that NULL is never returned on success */ 52907d2a35ccSKevin Wolf assert(align > 0); 52917d2a35ccSKevin Wolf if (size == 0) { 52927d2a35ccSKevin Wolf size = align; 52937d2a35ccSKevin Wolf } 52947d2a35ccSKevin Wolf 52957d2a35ccSKevin Wolf return qemu_try_memalign(align, size); 52967d2a35ccSKevin Wolf } 52977d2a35ccSKevin Wolf 52989ebd8448SMax Reitz void *qemu_try_blockalign0(BlockDriverState *bs, size_t size) 52999ebd8448SMax Reitz { 53009ebd8448SMax Reitz void *mem = qemu_try_blockalign(bs, size); 53019ebd8448SMax Reitz 53029ebd8448SMax Reitz if (mem) { 53039ebd8448SMax Reitz memset(mem, 0, size); 53049ebd8448SMax Reitz } 53059ebd8448SMax Reitz 53069ebd8448SMax Reitz return mem; 53079ebd8448SMax Reitz } 53089ebd8448SMax Reitz 5309c53b1c51SStefan Hajnoczi /* 5310c53b1c51SStefan Hajnoczi * Check if all memory in this vector is sector aligned. 5311c53b1c51SStefan Hajnoczi */ 5312c53b1c51SStefan Hajnoczi bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov) 5313c53b1c51SStefan Hajnoczi { 5314c53b1c51SStefan Hajnoczi int i; 5315339064d5SKevin Wolf size_t alignment = bdrv_opt_mem_align(bs); 5316c53b1c51SStefan Hajnoczi 5317c53b1c51SStefan Hajnoczi for (i = 0; i < qiov->niov; i++) { 5318339064d5SKevin Wolf if ((uintptr_t) qiov->iov[i].iov_base % alignment) { 5319c53b1c51SStefan Hajnoczi return false; 5320c53b1c51SStefan Hajnoczi } 5321339064d5SKevin Wolf if (qiov->iov[i].iov_len % alignment) { 53221ff735bdSKevin Wolf return false; 53231ff735bdSKevin Wolf } 5324c53b1c51SStefan Hajnoczi } 5325c53b1c51SStefan Hajnoczi 5326c53b1c51SStefan Hajnoczi return true; 5327c53b1c51SStefan Hajnoczi } 5328c53b1c51SStefan Hajnoczi 5329b8afb520SFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs, int granularity, 5330b8afb520SFam Zheng Error **errp) 53317cd1e32aSlirans@il.ibm.com { 53327cd1e32aSlirans@il.ibm.com int64_t bitmap_size; 5333e4654d2dSFam Zheng BdrvDirtyBitmap *bitmap; 5334a55eb92cSJan Kiszka 533550717e94SPaolo Bonzini assert((granularity & (granularity - 1)) == 0); 533650717e94SPaolo Bonzini 533750717e94SPaolo Bonzini granularity >>= BDRV_SECTOR_BITS; 5338e4654d2dSFam Zheng assert(granularity); 533957322b78SMarkus Armbruster bitmap_size = bdrv_nb_sectors(bs); 5340b8afb520SFam Zheng if (bitmap_size < 0) { 5341b8afb520SFam Zheng error_setg_errno(errp, -bitmap_size, "could not get length of device"); 5342b8afb520SFam Zheng errno = -bitmap_size; 5343b8afb520SFam Zheng return NULL; 5344b8afb520SFam Zheng } 53455839e53bSMarkus Armbruster bitmap = g_new0(BdrvDirtyBitmap, 1); 5346e4654d2dSFam Zheng bitmap->bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1); 5347e4654d2dSFam Zheng QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list); 5348e4654d2dSFam Zheng return bitmap; 5349e4654d2dSFam Zheng } 5350e4654d2dSFam Zheng 5351e4654d2dSFam Zheng void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap) 5352e4654d2dSFam Zheng { 5353e4654d2dSFam Zheng BdrvDirtyBitmap *bm, *next; 5354e4654d2dSFam Zheng QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) { 5355e4654d2dSFam Zheng if (bm == bitmap) { 5356e4654d2dSFam Zheng QLIST_REMOVE(bitmap, list); 5357e4654d2dSFam Zheng hbitmap_free(bitmap->bitmap); 5358e4654d2dSFam Zheng g_free(bitmap); 5359e4654d2dSFam Zheng return; 53607cd1e32aSlirans@il.ibm.com } 53617cd1e32aSlirans@il.ibm.com } 53627cd1e32aSlirans@il.ibm.com } 53637cd1e32aSlirans@il.ibm.com 536421b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs) 536521b56835SFam Zheng { 536621b56835SFam Zheng BdrvDirtyBitmap *bm; 536721b56835SFam Zheng BlockDirtyInfoList *list = NULL; 536821b56835SFam Zheng BlockDirtyInfoList **plist = &list; 536921b56835SFam Zheng 537021b56835SFam Zheng QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) { 53715839e53bSMarkus Armbruster BlockDirtyInfo *info = g_new0(BlockDirtyInfo, 1); 53725839e53bSMarkus Armbruster BlockDirtyInfoList *entry = g_new0(BlockDirtyInfoList, 1); 537321b56835SFam Zheng info->count = bdrv_get_dirty_count(bs, bm); 537421b56835SFam Zheng info->granularity = 537521b56835SFam Zheng ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bm->bitmap)); 537621b56835SFam Zheng entry->value = info; 537721b56835SFam Zheng *plist = entry; 537821b56835SFam Zheng plist = &entry->next; 537921b56835SFam Zheng } 538021b56835SFam Zheng 538121b56835SFam Zheng return list; 538221b56835SFam Zheng } 538321b56835SFam Zheng 5384e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector) 53857cd1e32aSlirans@il.ibm.com { 5386e4654d2dSFam Zheng if (bitmap) { 5387e4654d2dSFam Zheng return hbitmap_get(bitmap->bitmap, sector); 53887cd1e32aSlirans@il.ibm.com } else { 53897cd1e32aSlirans@il.ibm.com return 0; 53907cd1e32aSlirans@il.ibm.com } 53917cd1e32aSlirans@il.ibm.com } 53927cd1e32aSlirans@il.ibm.com 5393e4654d2dSFam Zheng void bdrv_dirty_iter_init(BlockDriverState *bs, 5394e4654d2dSFam Zheng BdrvDirtyBitmap *bitmap, HBitmapIter *hbi) 53951755da16SPaolo Bonzini { 5396e4654d2dSFam Zheng hbitmap_iter_init(hbi, bitmap->bitmap, 0); 53971755da16SPaolo Bonzini } 53981755da16SPaolo Bonzini 53991755da16SPaolo Bonzini void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector, 54001755da16SPaolo Bonzini int nr_sectors) 54011755da16SPaolo Bonzini { 5402e4654d2dSFam Zheng BdrvDirtyBitmap *bitmap; 5403e4654d2dSFam Zheng QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) { 5404e4654d2dSFam Zheng hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors); 5405e4654d2dSFam Zheng } 54061755da16SPaolo Bonzini } 54071755da16SPaolo Bonzini 5408e4654d2dSFam Zheng void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors) 54097cd1e32aSlirans@il.ibm.com { 5410e4654d2dSFam Zheng BdrvDirtyBitmap *bitmap; 5411e4654d2dSFam Zheng QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) { 5412e4654d2dSFam Zheng hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors); 5413e4654d2dSFam Zheng } 54147cd1e32aSlirans@il.ibm.com } 5415aaa0eb75SLiran Schour 5416e4654d2dSFam Zheng int64_t bdrv_get_dirty_count(BlockDriverState *bs, BdrvDirtyBitmap *bitmap) 5417aaa0eb75SLiran Schour { 5418e4654d2dSFam Zheng return hbitmap_count(bitmap->bitmap); 5419aaa0eb75SLiran Schour } 5420f88e1a42SJes Sorensen 54219fcb0251SFam Zheng /* Get a reference to bs */ 54229fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs) 54239fcb0251SFam Zheng { 54249fcb0251SFam Zheng bs->refcnt++; 54259fcb0251SFam Zheng } 54269fcb0251SFam Zheng 54279fcb0251SFam Zheng /* Release a previously grabbed reference to bs. 54289fcb0251SFam Zheng * If after releasing, reference count is zero, the BlockDriverState is 54299fcb0251SFam Zheng * deleted. */ 54309fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs) 54319fcb0251SFam Zheng { 54329a4d5ca6SJeff Cody if (!bs) { 54339a4d5ca6SJeff Cody return; 54349a4d5ca6SJeff Cody } 54359fcb0251SFam Zheng assert(bs->refcnt > 0); 54369fcb0251SFam Zheng if (--bs->refcnt == 0) { 54379fcb0251SFam Zheng bdrv_delete(bs); 54389fcb0251SFam Zheng } 54399fcb0251SFam Zheng } 54409fcb0251SFam Zheng 5441fbe40ff7SFam Zheng struct BdrvOpBlocker { 5442fbe40ff7SFam Zheng Error *reason; 5443fbe40ff7SFam Zheng QLIST_ENTRY(BdrvOpBlocker) list; 5444fbe40ff7SFam Zheng }; 5445fbe40ff7SFam Zheng 5446fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp) 5447fbe40ff7SFam Zheng { 5448fbe40ff7SFam Zheng BdrvOpBlocker *blocker; 5449fbe40ff7SFam Zheng assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX); 5450fbe40ff7SFam Zheng if (!QLIST_EMPTY(&bs->op_blockers[op])) { 5451fbe40ff7SFam Zheng blocker = QLIST_FIRST(&bs->op_blockers[op]); 5452fbe40ff7SFam Zheng if (errp) { 5453fbe40ff7SFam Zheng error_setg(errp, "Device '%s' is busy: %s", 5454bfb197e0SMarkus Armbruster bdrv_get_device_name(bs), 5455bfb197e0SMarkus Armbruster error_get_pretty(blocker->reason)); 5456fbe40ff7SFam Zheng } 5457fbe40ff7SFam Zheng return true; 5458fbe40ff7SFam Zheng } 5459fbe40ff7SFam Zheng return false; 5460fbe40ff7SFam Zheng } 5461fbe40ff7SFam Zheng 5462fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason) 5463fbe40ff7SFam Zheng { 5464fbe40ff7SFam Zheng BdrvOpBlocker *blocker; 5465fbe40ff7SFam Zheng assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX); 5466fbe40ff7SFam Zheng 54675839e53bSMarkus Armbruster blocker = g_new0(BdrvOpBlocker, 1); 5468fbe40ff7SFam Zheng blocker->reason = reason; 5469fbe40ff7SFam Zheng QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list); 5470fbe40ff7SFam Zheng } 5471fbe40ff7SFam Zheng 5472fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason) 5473fbe40ff7SFam Zheng { 5474fbe40ff7SFam Zheng BdrvOpBlocker *blocker, *next; 5475fbe40ff7SFam Zheng assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX); 5476fbe40ff7SFam Zheng QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) { 5477fbe40ff7SFam Zheng if (blocker->reason == reason) { 5478fbe40ff7SFam Zheng QLIST_REMOVE(blocker, list); 5479fbe40ff7SFam Zheng g_free(blocker); 5480fbe40ff7SFam Zheng } 5481fbe40ff7SFam Zheng } 5482fbe40ff7SFam Zheng } 5483fbe40ff7SFam Zheng 5484fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason) 5485fbe40ff7SFam Zheng { 5486fbe40ff7SFam Zheng int i; 5487fbe40ff7SFam Zheng for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { 5488fbe40ff7SFam Zheng bdrv_op_block(bs, i, reason); 5489fbe40ff7SFam Zheng } 5490fbe40ff7SFam Zheng } 5491fbe40ff7SFam Zheng 5492fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason) 5493fbe40ff7SFam Zheng { 5494fbe40ff7SFam Zheng int i; 5495fbe40ff7SFam Zheng for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { 5496fbe40ff7SFam Zheng bdrv_op_unblock(bs, i, reason); 5497fbe40ff7SFam Zheng } 5498fbe40ff7SFam Zheng } 5499fbe40ff7SFam Zheng 5500fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs) 5501fbe40ff7SFam Zheng { 5502fbe40ff7SFam Zheng int i; 5503fbe40ff7SFam Zheng 5504fbe40ff7SFam Zheng for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) { 5505fbe40ff7SFam Zheng if (!QLIST_EMPTY(&bs->op_blockers[i])) { 5506fbe40ff7SFam Zheng return false; 5507fbe40ff7SFam Zheng } 5508fbe40ff7SFam Zheng } 5509fbe40ff7SFam Zheng return true; 5510fbe40ff7SFam Zheng } 5511fbe40ff7SFam Zheng 551228a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs) 551328a7282aSLuiz Capitulino { 5514d6bf279eSLuiz Capitulino bs->iostatus_enabled = true; 551558e21ef5SLuiz Capitulino bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK; 551628a7282aSLuiz Capitulino } 551728a7282aSLuiz Capitulino 551828a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly 551928a7282aSLuiz Capitulino * enables it _and_ the VM is configured to stop on errors */ 552028a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs) 552128a7282aSLuiz Capitulino { 5522d6bf279eSLuiz Capitulino return (bs->iostatus_enabled && 552392aa5c6dSPaolo Bonzini (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC || 552492aa5c6dSPaolo Bonzini bs->on_write_error == BLOCKDEV_ON_ERROR_STOP || 552592aa5c6dSPaolo Bonzini bs->on_read_error == BLOCKDEV_ON_ERROR_STOP)); 552628a7282aSLuiz Capitulino } 552728a7282aSLuiz Capitulino 552828a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs) 552928a7282aSLuiz Capitulino { 5530d6bf279eSLuiz Capitulino bs->iostatus_enabled = false; 553128a7282aSLuiz Capitulino } 553228a7282aSLuiz Capitulino 553328a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs) 553428a7282aSLuiz Capitulino { 553528a7282aSLuiz Capitulino if (bdrv_iostatus_is_enabled(bs)) { 553658e21ef5SLuiz Capitulino bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK; 55373bd293c3SPaolo Bonzini if (bs->job) { 55383bd293c3SPaolo Bonzini block_job_iostatus_reset(bs->job); 55393bd293c3SPaolo Bonzini } 554028a7282aSLuiz Capitulino } 554128a7282aSLuiz Capitulino } 554228a7282aSLuiz Capitulino 554328a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error) 554428a7282aSLuiz Capitulino { 55453e1caa5fSPaolo Bonzini assert(bdrv_iostatus_is_enabled(bs)); 55463e1caa5fSPaolo Bonzini if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) { 554758e21ef5SLuiz Capitulino bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE : 554858e21ef5SLuiz Capitulino BLOCK_DEVICE_IO_STATUS_FAILED; 554928a7282aSLuiz Capitulino } 555028a7282aSLuiz Capitulino } 555128a7282aSLuiz Capitulino 5552d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt, 5553f88e1a42SJes Sorensen const char *base_filename, const char *base_fmt, 5554f382d43aSMiroslav Rezanina char *options, uint64_t img_size, int flags, 5555f382d43aSMiroslav Rezanina Error **errp, bool quiet) 5556f88e1a42SJes Sorensen { 555783d0521aSChunyan Liu QemuOptsList *create_opts = NULL; 555883d0521aSChunyan Liu QemuOpts *opts = NULL; 555983d0521aSChunyan Liu const char *backing_fmt, *backing_file; 556083d0521aSChunyan Liu int64_t size; 5561f88e1a42SJes Sorensen BlockDriver *drv, *proto_drv; 556296df67d1SStefan Hajnoczi BlockDriver *backing_drv = NULL; 5563cc84d90fSMax Reitz Error *local_err = NULL; 5564f88e1a42SJes Sorensen int ret = 0; 5565f88e1a42SJes Sorensen 5566f88e1a42SJes Sorensen /* Find driver and parse its options */ 5567f88e1a42SJes Sorensen drv = bdrv_find_format(fmt); 5568f88e1a42SJes Sorensen if (!drv) { 556971c79813SLuiz Capitulino error_setg(errp, "Unknown file format '%s'", fmt); 5570d92ada22SLuiz Capitulino return; 5571f88e1a42SJes Sorensen } 5572f88e1a42SJes Sorensen 557398289620SKevin Wolf proto_drv = bdrv_find_protocol(filename, true); 5574f88e1a42SJes Sorensen if (!proto_drv) { 557571c79813SLuiz Capitulino error_setg(errp, "Unknown protocol '%s'", filename); 5576d92ada22SLuiz Capitulino return; 5577f88e1a42SJes Sorensen } 5578f88e1a42SJes Sorensen 5579c282e1fdSChunyan Liu create_opts = qemu_opts_append(create_opts, drv->create_opts); 5580c282e1fdSChunyan Liu create_opts = qemu_opts_append(create_opts, proto_drv->create_opts); 5581f88e1a42SJes Sorensen 5582f88e1a42SJes Sorensen /* Create parameter list with default values */ 558383d0521aSChunyan Liu opts = qemu_opts_create(create_opts, NULL, 0, &error_abort); 558483d0521aSChunyan Liu qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size); 5585f88e1a42SJes Sorensen 5586f88e1a42SJes Sorensen /* Parse -o options */ 5587f88e1a42SJes Sorensen if (options) { 558883d0521aSChunyan Liu if (qemu_opts_do_parse(opts, options, NULL) != 0) { 558983d0521aSChunyan Liu error_setg(errp, "Invalid options for file format '%s'", fmt); 5590f88e1a42SJes Sorensen goto out; 5591f88e1a42SJes Sorensen } 5592f88e1a42SJes Sorensen } 5593f88e1a42SJes Sorensen 5594f88e1a42SJes Sorensen if (base_filename) { 559583d0521aSChunyan Liu if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename)) { 559671c79813SLuiz Capitulino error_setg(errp, "Backing file not supported for file format '%s'", 559771c79813SLuiz Capitulino fmt); 5598f88e1a42SJes Sorensen goto out; 5599f88e1a42SJes Sorensen } 5600f88e1a42SJes Sorensen } 5601f88e1a42SJes Sorensen 5602f88e1a42SJes Sorensen if (base_fmt) { 560383d0521aSChunyan Liu if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt)) { 560471c79813SLuiz Capitulino error_setg(errp, "Backing file format not supported for file " 560571c79813SLuiz Capitulino "format '%s'", fmt); 5606f88e1a42SJes Sorensen goto out; 5607f88e1a42SJes Sorensen } 5608f88e1a42SJes Sorensen } 5609f88e1a42SJes Sorensen 561083d0521aSChunyan Liu backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE); 561183d0521aSChunyan Liu if (backing_file) { 561283d0521aSChunyan Liu if (!strcmp(filename, backing_file)) { 561371c79813SLuiz Capitulino error_setg(errp, "Error: Trying to create an image with the " 561471c79813SLuiz Capitulino "same filename as the backing file"); 5615792da93aSJes Sorensen goto out; 5616792da93aSJes Sorensen } 5617792da93aSJes Sorensen } 5618792da93aSJes Sorensen 561983d0521aSChunyan Liu backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT); 562083d0521aSChunyan Liu if (backing_fmt) { 562183d0521aSChunyan Liu backing_drv = bdrv_find_format(backing_fmt); 562296df67d1SStefan Hajnoczi if (!backing_drv) { 562371c79813SLuiz Capitulino error_setg(errp, "Unknown backing file format '%s'", 562483d0521aSChunyan Liu backing_fmt); 5625f88e1a42SJes Sorensen goto out; 5626f88e1a42SJes Sorensen } 5627f88e1a42SJes Sorensen } 5628f88e1a42SJes Sorensen 5629f88e1a42SJes Sorensen // The size for the image must always be specified, with one exception: 5630f88e1a42SJes Sorensen // If we are using a backing file, we can obtain the size from there 563183d0521aSChunyan Liu size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0); 563283d0521aSChunyan Liu if (size == -1) { 563383d0521aSChunyan Liu if (backing_file) { 563466f6b814SMax Reitz BlockDriverState *bs; 563552bf1e72SMarkus Armbruster int64_t size; 563663090dacSPaolo Bonzini int back_flags; 563763090dacSPaolo Bonzini 563863090dacSPaolo Bonzini /* backing files always opened read-only */ 563963090dacSPaolo Bonzini back_flags = 564063090dacSPaolo Bonzini flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING); 5641f88e1a42SJes Sorensen 5642f67503e5SMax Reitz bs = NULL; 564383d0521aSChunyan Liu ret = bdrv_open(&bs, backing_file, NULL, NULL, back_flags, 5644cc84d90fSMax Reitz backing_drv, &local_err); 5645f88e1a42SJes Sorensen if (ret < 0) { 5646f88e1a42SJes Sorensen goto out; 5647f88e1a42SJes Sorensen } 564852bf1e72SMarkus Armbruster size = bdrv_getlength(bs); 564952bf1e72SMarkus Armbruster if (size < 0) { 565052bf1e72SMarkus Armbruster error_setg_errno(errp, -size, "Could not get size of '%s'", 565152bf1e72SMarkus Armbruster backing_file); 565252bf1e72SMarkus Armbruster bdrv_unref(bs); 565352bf1e72SMarkus Armbruster goto out; 565452bf1e72SMarkus Armbruster } 5655f88e1a42SJes Sorensen 565683d0521aSChunyan Liu qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size); 565766f6b814SMax Reitz 565866f6b814SMax Reitz bdrv_unref(bs); 5659f88e1a42SJes Sorensen } else { 566071c79813SLuiz Capitulino error_setg(errp, "Image creation needs a size parameter"); 5661f88e1a42SJes Sorensen goto out; 5662f88e1a42SJes Sorensen } 5663f88e1a42SJes Sorensen } 5664f88e1a42SJes Sorensen 5665f382d43aSMiroslav Rezanina if (!quiet) { 5666f88e1a42SJes Sorensen printf("Formatting '%s', fmt=%s ", filename, fmt); 566783d0521aSChunyan Liu qemu_opts_print(opts); 5668f88e1a42SJes Sorensen puts(""); 5669f382d43aSMiroslav Rezanina } 567083d0521aSChunyan Liu 5671c282e1fdSChunyan Liu ret = bdrv_create(drv, filename, opts, &local_err); 567283d0521aSChunyan Liu 5673cc84d90fSMax Reitz if (ret == -EFBIG) { 5674cc84d90fSMax Reitz /* This is generally a better message than whatever the driver would 5675cc84d90fSMax Reitz * deliver (especially because of the cluster_size_hint), since that 5676cc84d90fSMax Reitz * is most probably not much different from "image too large". */ 5677f3f4d2c0SKevin Wolf const char *cluster_size_hint = ""; 567883d0521aSChunyan Liu if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) { 5679f3f4d2c0SKevin Wolf cluster_size_hint = " (try using a larger cluster size)"; 5680f3f4d2c0SKevin Wolf } 5681cc84d90fSMax Reitz error_setg(errp, "The image size is too large for file format '%s'" 5682cc84d90fSMax Reitz "%s", fmt, cluster_size_hint); 5683cc84d90fSMax Reitz error_free(local_err); 5684cc84d90fSMax Reitz local_err = NULL; 5685f88e1a42SJes Sorensen } 5686f88e1a42SJes Sorensen 5687f88e1a42SJes Sorensen out: 568883d0521aSChunyan Liu qemu_opts_del(opts); 568983d0521aSChunyan Liu qemu_opts_free(create_opts); 569084d18f06SMarkus Armbruster if (local_err) { 5691cc84d90fSMax Reitz error_propagate(errp, local_err); 5692cc84d90fSMax Reitz } 5693f88e1a42SJes Sorensen } 569485d126f3SStefan Hajnoczi 569585d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs) 569685d126f3SStefan Hajnoczi { 5697dcd04228SStefan Hajnoczi return bs->aio_context; 5698dcd04228SStefan Hajnoczi } 5699dcd04228SStefan Hajnoczi 5700dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs) 5701dcd04228SStefan Hajnoczi { 570233384421SMax Reitz BdrvAioNotifier *baf; 570333384421SMax Reitz 5704dcd04228SStefan Hajnoczi if (!bs->drv) { 5705dcd04228SStefan Hajnoczi return; 5706dcd04228SStefan Hajnoczi } 5707dcd04228SStefan Hajnoczi 570833384421SMax Reitz QLIST_FOREACH(baf, &bs->aio_notifiers, list) { 570933384421SMax Reitz baf->detach_aio_context(baf->opaque); 571033384421SMax Reitz } 571133384421SMax Reitz 571213af91ebSStefan Hajnoczi if (bs->io_limits_enabled) { 571313af91ebSStefan Hajnoczi throttle_detach_aio_context(&bs->throttle_state); 571413af91ebSStefan Hajnoczi } 5715dcd04228SStefan Hajnoczi if (bs->drv->bdrv_detach_aio_context) { 5716dcd04228SStefan Hajnoczi bs->drv->bdrv_detach_aio_context(bs); 5717dcd04228SStefan Hajnoczi } 5718dcd04228SStefan Hajnoczi if (bs->file) { 5719dcd04228SStefan Hajnoczi bdrv_detach_aio_context(bs->file); 5720dcd04228SStefan Hajnoczi } 5721dcd04228SStefan Hajnoczi if (bs->backing_hd) { 5722dcd04228SStefan Hajnoczi bdrv_detach_aio_context(bs->backing_hd); 5723dcd04228SStefan Hajnoczi } 5724dcd04228SStefan Hajnoczi 5725dcd04228SStefan Hajnoczi bs->aio_context = NULL; 5726dcd04228SStefan Hajnoczi } 5727dcd04228SStefan Hajnoczi 5728dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs, 5729dcd04228SStefan Hajnoczi AioContext *new_context) 5730dcd04228SStefan Hajnoczi { 573133384421SMax Reitz BdrvAioNotifier *ban; 573233384421SMax Reitz 5733dcd04228SStefan Hajnoczi if (!bs->drv) { 5734dcd04228SStefan Hajnoczi return; 5735dcd04228SStefan Hajnoczi } 5736dcd04228SStefan Hajnoczi 5737dcd04228SStefan Hajnoczi bs->aio_context = new_context; 5738dcd04228SStefan Hajnoczi 5739dcd04228SStefan Hajnoczi if (bs->backing_hd) { 5740dcd04228SStefan Hajnoczi bdrv_attach_aio_context(bs->backing_hd, new_context); 5741dcd04228SStefan Hajnoczi } 5742dcd04228SStefan Hajnoczi if (bs->file) { 5743dcd04228SStefan Hajnoczi bdrv_attach_aio_context(bs->file, new_context); 5744dcd04228SStefan Hajnoczi } 5745dcd04228SStefan Hajnoczi if (bs->drv->bdrv_attach_aio_context) { 5746dcd04228SStefan Hajnoczi bs->drv->bdrv_attach_aio_context(bs, new_context); 5747dcd04228SStefan Hajnoczi } 574813af91ebSStefan Hajnoczi if (bs->io_limits_enabled) { 574913af91ebSStefan Hajnoczi throttle_attach_aio_context(&bs->throttle_state, new_context); 575013af91ebSStefan Hajnoczi } 575133384421SMax Reitz 575233384421SMax Reitz QLIST_FOREACH(ban, &bs->aio_notifiers, list) { 575333384421SMax Reitz ban->attached_aio_context(new_context, ban->opaque); 575433384421SMax Reitz } 5755dcd04228SStefan Hajnoczi } 5756dcd04228SStefan Hajnoczi 5757dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context) 5758dcd04228SStefan Hajnoczi { 5759dcd04228SStefan Hajnoczi bdrv_drain_all(); /* ensure there are no in-flight requests */ 5760dcd04228SStefan Hajnoczi 5761dcd04228SStefan Hajnoczi bdrv_detach_aio_context(bs); 5762dcd04228SStefan Hajnoczi 5763dcd04228SStefan Hajnoczi /* This function executes in the old AioContext so acquire the new one in 5764dcd04228SStefan Hajnoczi * case it runs in a different thread. 5765dcd04228SStefan Hajnoczi */ 5766dcd04228SStefan Hajnoczi aio_context_acquire(new_context); 5767dcd04228SStefan Hajnoczi bdrv_attach_aio_context(bs, new_context); 5768dcd04228SStefan Hajnoczi aio_context_release(new_context); 576985d126f3SStefan Hajnoczi } 5770d616b224SStefan Hajnoczi 577133384421SMax Reitz void bdrv_add_aio_context_notifier(BlockDriverState *bs, 577233384421SMax Reitz void (*attached_aio_context)(AioContext *new_context, void *opaque), 577333384421SMax Reitz void (*detach_aio_context)(void *opaque), void *opaque) 577433384421SMax Reitz { 577533384421SMax Reitz BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1); 577633384421SMax Reitz *ban = (BdrvAioNotifier){ 577733384421SMax Reitz .attached_aio_context = attached_aio_context, 577833384421SMax Reitz .detach_aio_context = detach_aio_context, 577933384421SMax Reitz .opaque = opaque 578033384421SMax Reitz }; 578133384421SMax Reitz 578233384421SMax Reitz QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list); 578333384421SMax Reitz } 578433384421SMax Reitz 578533384421SMax Reitz void bdrv_remove_aio_context_notifier(BlockDriverState *bs, 578633384421SMax Reitz void (*attached_aio_context)(AioContext *, 578733384421SMax Reitz void *), 578833384421SMax Reitz void (*detach_aio_context)(void *), 578933384421SMax Reitz void *opaque) 579033384421SMax Reitz { 579133384421SMax Reitz BdrvAioNotifier *ban, *ban_next; 579233384421SMax Reitz 579333384421SMax Reitz QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) { 579433384421SMax Reitz if (ban->attached_aio_context == attached_aio_context && 579533384421SMax Reitz ban->detach_aio_context == detach_aio_context && 579633384421SMax Reitz ban->opaque == opaque) 579733384421SMax Reitz { 579833384421SMax Reitz QLIST_REMOVE(ban, list); 579933384421SMax Reitz g_free(ban); 580033384421SMax Reitz 580133384421SMax Reitz return; 580233384421SMax Reitz } 580333384421SMax Reitz } 580433384421SMax Reitz 580533384421SMax Reitz abort(); 580633384421SMax Reitz } 580733384421SMax Reitz 5808d616b224SStefan Hajnoczi void bdrv_add_before_write_notifier(BlockDriverState *bs, 5809d616b224SStefan Hajnoczi NotifierWithReturn *notifier) 5810d616b224SStefan Hajnoczi { 5811d616b224SStefan Hajnoczi notifier_with_return_list_add(&bs->before_write_notifiers, notifier); 5812d616b224SStefan Hajnoczi } 58136f176b48SMax Reitz 581477485434SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts, 581577485434SMax Reitz BlockDriverAmendStatusCB *status_cb) 58166f176b48SMax Reitz { 5817c282e1fdSChunyan Liu if (!bs->drv->bdrv_amend_options) { 58186f176b48SMax Reitz return -ENOTSUP; 58196f176b48SMax Reitz } 582077485434SMax Reitz return bs->drv->bdrv_amend_options(bs, opts, status_cb); 58216f176b48SMax Reitz } 5822f6186f49SBenoît Canet 5823b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method 5824b5042a36SBenoît Canet * of block filter and by bdrv_is_first_non_filter. 5825b5042a36SBenoît Canet * It is used to test if the given bs is the candidate or recurse more in the 5826b5042a36SBenoît Canet * node graph. 5827212a5a8fSBenoît Canet */ 5828212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs, 5829212a5a8fSBenoît Canet BlockDriverState *candidate) 5830f6186f49SBenoît Canet { 5831b5042a36SBenoît Canet /* return false if basic checks fails */ 5832b5042a36SBenoît Canet if (!bs || !bs->drv) { 5833b5042a36SBenoît Canet return false; 5834b5042a36SBenoît Canet } 5835b5042a36SBenoît Canet 5836b5042a36SBenoît Canet /* the code reached a non block filter driver -> check if the bs is 5837b5042a36SBenoît Canet * the same as the candidate. It's the recursion termination condition. 5838b5042a36SBenoît Canet */ 5839b5042a36SBenoît Canet if (!bs->drv->is_filter) { 5840b5042a36SBenoît Canet return bs == candidate; 5841b5042a36SBenoît Canet } 5842b5042a36SBenoît Canet /* Down this path the driver is a block filter driver */ 5843b5042a36SBenoît Canet 5844b5042a36SBenoît Canet /* If the block filter recursion method is defined use it to recurse down 5845b5042a36SBenoît Canet * the node graph. 5846b5042a36SBenoît Canet */ 5847b5042a36SBenoît Canet if (bs->drv->bdrv_recurse_is_first_non_filter) { 5848212a5a8fSBenoît Canet return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate); 5849212a5a8fSBenoît Canet } 5850212a5a8fSBenoît Canet 5851b5042a36SBenoît Canet /* the driver is a block filter but don't allow to recurse -> return false 5852b5042a36SBenoît Canet */ 5853b5042a36SBenoît Canet return false; 5854212a5a8fSBenoît Canet } 5855212a5a8fSBenoît Canet 5856212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's 5857212a5a8fSBenoît Canet * bs chain. Since we don't have pointers to parents it explore all bs chains 5858212a5a8fSBenoît Canet * from the top. Some filters can choose not to pass down the recursion. 5859212a5a8fSBenoît Canet */ 5860212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate) 5861212a5a8fSBenoît Canet { 5862212a5a8fSBenoît Canet BlockDriverState *bs; 5863212a5a8fSBenoît Canet 5864212a5a8fSBenoît Canet /* walk down the bs forest recursively */ 5865212a5a8fSBenoît Canet QTAILQ_FOREACH(bs, &bdrv_states, device_list) { 5866212a5a8fSBenoît Canet bool perm; 5867212a5a8fSBenoît Canet 5868b5042a36SBenoît Canet /* try to recurse in this top level bs */ 5869e6dc8a1fSKevin Wolf perm = bdrv_recurse_is_first_non_filter(bs, candidate); 5870212a5a8fSBenoît Canet 5871212a5a8fSBenoît Canet /* candidate is the first non filter */ 5872212a5a8fSBenoît Canet if (perm) { 5873212a5a8fSBenoît Canet return true; 5874212a5a8fSBenoît Canet } 5875212a5a8fSBenoît Canet } 5876212a5a8fSBenoît Canet 5877212a5a8fSBenoît Canet return false; 5878f6186f49SBenoît Canet } 587909158f00SBenoît Canet 588009158f00SBenoît Canet BlockDriverState *check_to_replace_node(const char *node_name, Error **errp) 588109158f00SBenoît Canet { 588209158f00SBenoît Canet BlockDriverState *to_replace_bs = bdrv_find_node(node_name); 58835a7e7a0bSStefan Hajnoczi AioContext *aio_context; 58845a7e7a0bSStefan Hajnoczi 588509158f00SBenoît Canet if (!to_replace_bs) { 588609158f00SBenoît Canet error_setg(errp, "Node name '%s' not found", node_name); 588709158f00SBenoît Canet return NULL; 588809158f00SBenoît Canet } 588909158f00SBenoît Canet 58905a7e7a0bSStefan Hajnoczi aio_context = bdrv_get_aio_context(to_replace_bs); 58915a7e7a0bSStefan Hajnoczi aio_context_acquire(aio_context); 58925a7e7a0bSStefan Hajnoczi 589309158f00SBenoît Canet if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) { 58945a7e7a0bSStefan Hajnoczi to_replace_bs = NULL; 58955a7e7a0bSStefan Hajnoczi goto out; 589609158f00SBenoît Canet } 589709158f00SBenoît Canet 589809158f00SBenoît Canet /* We don't want arbitrary node of the BDS chain to be replaced only the top 589909158f00SBenoît Canet * most non filter in order to prevent data corruption. 590009158f00SBenoît Canet * Another benefit is that this tests exclude backing files which are 590109158f00SBenoît Canet * blocked by the backing blockers. 590209158f00SBenoît Canet */ 590309158f00SBenoît Canet if (!bdrv_is_first_non_filter(to_replace_bs)) { 590409158f00SBenoît Canet error_setg(errp, "Only top most non filter can be replaced"); 59055a7e7a0bSStefan Hajnoczi to_replace_bs = NULL; 59065a7e7a0bSStefan Hajnoczi goto out; 590709158f00SBenoît Canet } 590809158f00SBenoît Canet 59095a7e7a0bSStefan Hajnoczi out: 59105a7e7a0bSStefan Hajnoczi aio_context_release(aio_context); 591109158f00SBenoît Canet return to_replace_bs; 591209158f00SBenoît Canet } 5913448ad91dSMing Lei 5914448ad91dSMing Lei void bdrv_io_plug(BlockDriverState *bs) 5915448ad91dSMing Lei { 5916448ad91dSMing Lei BlockDriver *drv = bs->drv; 5917448ad91dSMing Lei if (drv && drv->bdrv_io_plug) { 5918448ad91dSMing Lei drv->bdrv_io_plug(bs); 5919448ad91dSMing Lei } else if (bs->file) { 5920448ad91dSMing Lei bdrv_io_plug(bs->file); 5921448ad91dSMing Lei } 5922448ad91dSMing Lei } 5923448ad91dSMing Lei 5924448ad91dSMing Lei void bdrv_io_unplug(BlockDriverState *bs) 5925448ad91dSMing Lei { 5926448ad91dSMing Lei BlockDriver *drv = bs->drv; 5927448ad91dSMing Lei if (drv && drv->bdrv_io_unplug) { 5928448ad91dSMing Lei drv->bdrv_io_unplug(bs); 5929448ad91dSMing Lei } else if (bs->file) { 5930448ad91dSMing Lei bdrv_io_unplug(bs->file); 5931448ad91dSMing Lei } 5932448ad91dSMing Lei } 5933448ad91dSMing Lei 5934448ad91dSMing Lei void bdrv_flush_io_queue(BlockDriverState *bs) 5935448ad91dSMing Lei { 5936448ad91dSMing Lei BlockDriver *drv = bs->drv; 5937448ad91dSMing Lei if (drv && drv->bdrv_flush_io_queue) { 5938448ad91dSMing Lei drv->bdrv_flush_io_queue(bs); 5939448ad91dSMing Lei } else if (bs->file) { 5940448ad91dSMing Lei bdrv_flush_io_queue(bs->file); 5941448ad91dSMing Lei } 5942448ad91dSMing Lei } 594391af7014SMax Reitz 594491af7014SMax Reitz static bool append_open_options(QDict *d, BlockDriverState *bs) 594591af7014SMax Reitz { 594691af7014SMax Reitz const QDictEntry *entry; 594791af7014SMax Reitz bool found_any = false; 594891af7014SMax Reitz 594991af7014SMax Reitz for (entry = qdict_first(bs->options); entry; 595091af7014SMax Reitz entry = qdict_next(bs->options, entry)) 595191af7014SMax Reitz { 595291af7014SMax Reitz /* Only take options for this level and exclude all non-driver-specific 595391af7014SMax Reitz * options */ 595491af7014SMax Reitz if (!strchr(qdict_entry_key(entry), '.') && 595591af7014SMax Reitz strcmp(qdict_entry_key(entry), "node-name")) 595691af7014SMax Reitz { 595791af7014SMax Reitz qobject_incref(qdict_entry_value(entry)); 595891af7014SMax Reitz qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry)); 595991af7014SMax Reitz found_any = true; 596091af7014SMax Reitz } 596191af7014SMax Reitz } 596291af7014SMax Reitz 596391af7014SMax Reitz return found_any; 596491af7014SMax Reitz } 596591af7014SMax Reitz 596691af7014SMax Reitz /* Updates the following BDS fields: 596791af7014SMax Reitz * - exact_filename: A filename which may be used for opening a block device 596891af7014SMax Reitz * which (mostly) equals the given BDS (even without any 596991af7014SMax Reitz * other options; so reading and writing must return the same 597091af7014SMax Reitz * results, but caching etc. may be different) 597191af7014SMax Reitz * - full_open_options: Options which, when given when opening a block device 597291af7014SMax Reitz * (without a filename), result in a BDS (mostly) 597391af7014SMax Reitz * equalling the given one 597491af7014SMax Reitz * - filename: If exact_filename is set, it is copied here. Otherwise, 597591af7014SMax Reitz * full_open_options is converted to a JSON object, prefixed with 597691af7014SMax Reitz * "json:" (for use through the JSON pseudo protocol) and put here. 597791af7014SMax Reitz */ 597891af7014SMax Reitz void bdrv_refresh_filename(BlockDriverState *bs) 597991af7014SMax Reitz { 598091af7014SMax Reitz BlockDriver *drv = bs->drv; 598191af7014SMax Reitz QDict *opts; 598291af7014SMax Reitz 598391af7014SMax Reitz if (!drv) { 598491af7014SMax Reitz return; 598591af7014SMax Reitz } 598691af7014SMax Reitz 598791af7014SMax Reitz /* This BDS's file name will most probably depend on its file's name, so 598891af7014SMax Reitz * refresh that first */ 598991af7014SMax Reitz if (bs->file) { 599091af7014SMax Reitz bdrv_refresh_filename(bs->file); 599191af7014SMax Reitz } 599291af7014SMax Reitz 599391af7014SMax Reitz if (drv->bdrv_refresh_filename) { 599491af7014SMax Reitz /* Obsolete information is of no use here, so drop the old file name 599591af7014SMax Reitz * information before refreshing it */ 599691af7014SMax Reitz bs->exact_filename[0] = '\0'; 599791af7014SMax Reitz if (bs->full_open_options) { 599891af7014SMax Reitz QDECREF(bs->full_open_options); 599991af7014SMax Reitz bs->full_open_options = NULL; 600091af7014SMax Reitz } 600191af7014SMax Reitz 600291af7014SMax Reitz drv->bdrv_refresh_filename(bs); 600391af7014SMax Reitz } else if (bs->file) { 600491af7014SMax Reitz /* Try to reconstruct valid information from the underlying file */ 600591af7014SMax Reitz bool has_open_options; 600691af7014SMax Reitz 600791af7014SMax Reitz bs->exact_filename[0] = '\0'; 600891af7014SMax Reitz if (bs->full_open_options) { 600991af7014SMax Reitz QDECREF(bs->full_open_options); 601091af7014SMax Reitz bs->full_open_options = NULL; 601191af7014SMax Reitz } 601291af7014SMax Reitz 601391af7014SMax Reitz opts = qdict_new(); 601491af7014SMax Reitz has_open_options = append_open_options(opts, bs); 601591af7014SMax Reitz 601691af7014SMax Reitz /* If no specific options have been given for this BDS, the filename of 601791af7014SMax Reitz * the underlying file should suffice for this one as well */ 601891af7014SMax Reitz if (bs->file->exact_filename[0] && !has_open_options) { 601991af7014SMax Reitz strcpy(bs->exact_filename, bs->file->exact_filename); 602091af7014SMax Reitz } 602191af7014SMax Reitz /* Reconstructing the full options QDict is simple for most format block 602291af7014SMax Reitz * drivers, as long as the full options are known for the underlying 602391af7014SMax Reitz * file BDS. The full options QDict of that file BDS should somehow 602491af7014SMax Reitz * contain a representation of the filename, therefore the following 602591af7014SMax Reitz * suffices without querying the (exact_)filename of this BDS. */ 602691af7014SMax Reitz if (bs->file->full_open_options) { 602791af7014SMax Reitz qdict_put_obj(opts, "driver", 602891af7014SMax Reitz QOBJECT(qstring_from_str(drv->format_name))); 602991af7014SMax Reitz QINCREF(bs->file->full_open_options); 603091af7014SMax Reitz qdict_put_obj(opts, "file", QOBJECT(bs->file->full_open_options)); 603191af7014SMax Reitz 603291af7014SMax Reitz bs->full_open_options = opts; 603391af7014SMax Reitz } else { 603491af7014SMax Reitz QDECREF(opts); 603591af7014SMax Reitz } 603691af7014SMax Reitz } else if (!bs->full_open_options && qdict_size(bs->options)) { 603791af7014SMax Reitz /* There is no underlying file BDS (at least referenced by BDS.file), 603891af7014SMax Reitz * so the full options QDict should be equal to the options given 603991af7014SMax Reitz * specifically for this block device when it was opened (plus the 604091af7014SMax Reitz * driver specification). 604191af7014SMax Reitz * Because those options don't change, there is no need to update 604291af7014SMax Reitz * full_open_options when it's already set. */ 604391af7014SMax Reitz 604491af7014SMax Reitz opts = qdict_new(); 604591af7014SMax Reitz append_open_options(opts, bs); 604691af7014SMax Reitz qdict_put_obj(opts, "driver", 604791af7014SMax Reitz QOBJECT(qstring_from_str(drv->format_name))); 604891af7014SMax Reitz 604991af7014SMax Reitz if (bs->exact_filename[0]) { 605091af7014SMax Reitz /* This may not work for all block protocol drivers (some may 605191af7014SMax Reitz * require this filename to be parsed), but we have to find some 605291af7014SMax Reitz * default solution here, so just include it. If some block driver 605391af7014SMax Reitz * does not support pure options without any filename at all or 605491af7014SMax Reitz * needs some special format of the options QDict, it needs to 605591af7014SMax Reitz * implement the driver-specific bdrv_refresh_filename() function. 605691af7014SMax Reitz */ 605791af7014SMax Reitz qdict_put_obj(opts, "filename", 605891af7014SMax Reitz QOBJECT(qstring_from_str(bs->exact_filename))); 605991af7014SMax Reitz } 606091af7014SMax Reitz 606191af7014SMax Reitz bs->full_open_options = opts; 606291af7014SMax Reitz } 606391af7014SMax Reitz 606491af7014SMax Reitz if (bs->exact_filename[0]) { 606591af7014SMax Reitz pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename); 606691af7014SMax Reitz } else if (bs->full_open_options) { 606791af7014SMax Reitz QString *json = qobject_to_json(QOBJECT(bs->full_open_options)); 606891af7014SMax Reitz snprintf(bs->filename, sizeof(bs->filename), "json:%s", 606991af7014SMax Reitz qstring_get_str(json)); 607091af7014SMax Reitz QDECREF(json); 607191af7014SMax Reitz } 607291af7014SMax Reitz } 60735366d0c8SBenoît Canet 60745366d0c8SBenoît Canet /* This accessor function purpose is to allow the device models to access the 60755366d0c8SBenoît Canet * BlockAcctStats structure embedded inside a BlockDriverState without being 60765366d0c8SBenoît Canet * aware of the BlockDriverState structure layout. 60775366d0c8SBenoît Canet * It will go away when the BlockAcctStats structure will be moved inside 60785366d0c8SBenoît Canet * the device models. 60795366d0c8SBenoît Canet */ 60805366d0c8SBenoît Canet BlockAcctStats *bdrv_get_stats(BlockDriverState *bs) 60815366d0c8SBenoît Canet { 60825366d0c8SBenoît Canet return &bs->stats; 60835366d0c8SBenoît Canet } 6084