1 /* 2 * Block layer I/O functions 3 * 4 * Copyright (c) 2003 Fabrice Bellard 5 * 6 * Permission is hereby granted, free of charge, to any person obtaining a copy 7 * of this software and associated documentation files (the "Software"), to deal 8 * in the Software without restriction, including without limitation the rights 9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 * copies of the Software, and to permit persons to whom the Software is 11 * furnished to do so, subject to the following conditions: 12 * 13 * The above copyright notice and this permission notice shall be included in 14 * all copies or substantial portions of the Software. 15 * 16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 * THE SOFTWARE. 23 */ 24 25 #include "qemu/osdep.h" 26 #include "trace.h" 27 #include "sysemu/block-backend.h" 28 #include "block/blockjob.h" 29 #include "block/block_int.h" 30 #include "qemu/cutils.h" 31 #include "qapi/error.h" 32 #include "qemu/error-report.h" 33 34 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */ 35 36 static BlockAIOCB *bdrv_co_aio_prw_vector(BdrvChild *child, 37 int64_t offset, 38 QEMUIOVector *qiov, 39 BdrvRequestFlags flags, 40 BlockCompletionFunc *cb, 41 void *opaque, 42 bool is_write); 43 static void coroutine_fn bdrv_co_do_rw(void *opaque); 44 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs, 45 int64_t offset, int count, BdrvRequestFlags flags); 46 47 static void bdrv_parent_drained_begin(BlockDriverState *bs) 48 { 49 BdrvChild *c; 50 51 QLIST_FOREACH(c, &bs->parents, next_parent) { 52 if (c->role->drained_begin) { 53 c->role->drained_begin(c); 54 } 55 } 56 } 57 58 static void bdrv_parent_drained_end(BlockDriverState *bs) 59 { 60 BdrvChild *c; 61 62 QLIST_FOREACH(c, &bs->parents, next_parent) { 63 if (c->role->drained_end) { 64 c->role->drained_end(c); 65 } 66 } 67 } 68 69 static void bdrv_merge_limits(BlockLimits *dst, const BlockLimits *src) 70 { 71 dst->opt_transfer = MAX(dst->opt_transfer, src->opt_transfer); 72 dst->max_transfer = MIN_NON_ZERO(dst->max_transfer, src->max_transfer); 73 dst->opt_mem_alignment = MAX(dst->opt_mem_alignment, 74 src->opt_mem_alignment); 75 dst->min_mem_alignment = MAX(dst->min_mem_alignment, 76 src->min_mem_alignment); 77 dst->max_iov = MIN_NON_ZERO(dst->max_iov, src->max_iov); 78 } 79 80 void bdrv_refresh_limits(BlockDriverState *bs, Error **errp) 81 { 82 BlockDriver *drv = bs->drv; 83 Error *local_err = NULL; 84 85 memset(&bs->bl, 0, sizeof(bs->bl)); 86 87 if (!drv) { 88 return; 89 } 90 91 /* Default alignment based on whether driver has byte interface */ 92 bs->bl.request_alignment = drv->bdrv_co_preadv ? 1 : 512; 93 94 /* Take some limits from the children as a default */ 95 if (bs->file) { 96 bdrv_refresh_limits(bs->file->bs, &local_err); 97 if (local_err) { 98 error_propagate(errp, local_err); 99 return; 100 } 101 bdrv_merge_limits(&bs->bl, &bs->file->bs->bl); 102 } else { 103 bs->bl.min_mem_alignment = 512; 104 bs->bl.opt_mem_alignment = getpagesize(); 105 106 /* Safe default since most protocols use readv()/writev()/etc */ 107 bs->bl.max_iov = IOV_MAX; 108 } 109 110 if (bs->backing) { 111 bdrv_refresh_limits(bs->backing->bs, &local_err); 112 if (local_err) { 113 error_propagate(errp, local_err); 114 return; 115 } 116 bdrv_merge_limits(&bs->bl, &bs->backing->bs->bl); 117 } 118 119 /* Then let the driver override it */ 120 if (drv->bdrv_refresh_limits) { 121 drv->bdrv_refresh_limits(bs, errp); 122 } 123 } 124 125 /** 126 * The copy-on-read flag is actually a reference count so multiple users may 127 * use the feature without worrying about clobbering its previous state. 128 * Copy-on-read stays enabled until all users have called to disable it. 129 */ 130 void bdrv_enable_copy_on_read(BlockDriverState *bs) 131 { 132 bs->copy_on_read++; 133 } 134 135 void bdrv_disable_copy_on_read(BlockDriverState *bs) 136 { 137 assert(bs->copy_on_read > 0); 138 bs->copy_on_read--; 139 } 140 141 /* Check if any requests are in-flight (including throttled requests) */ 142 bool bdrv_requests_pending(BlockDriverState *bs) 143 { 144 BdrvChild *child; 145 146 if (atomic_read(&bs->in_flight)) { 147 return true; 148 } 149 150 QLIST_FOREACH(child, &bs->children, next) { 151 if (bdrv_requests_pending(child->bs)) { 152 return true; 153 } 154 } 155 156 return false; 157 } 158 159 static bool bdrv_drain_recurse(BlockDriverState *bs) 160 { 161 BdrvChild *child; 162 bool waited; 163 164 waited = BDRV_POLL_WHILE(bs, atomic_read(&bs->in_flight) > 0); 165 166 if (bs->drv && bs->drv->bdrv_drain) { 167 bs->drv->bdrv_drain(bs); 168 } 169 170 QLIST_FOREACH(child, &bs->children, next) { 171 waited |= bdrv_drain_recurse(child->bs); 172 } 173 174 return waited; 175 } 176 177 typedef struct { 178 Coroutine *co; 179 BlockDriverState *bs; 180 bool done; 181 } BdrvCoDrainData; 182 183 static void bdrv_co_drain_bh_cb(void *opaque) 184 { 185 BdrvCoDrainData *data = opaque; 186 Coroutine *co = data->co; 187 BlockDriverState *bs = data->bs; 188 189 bdrv_dec_in_flight(bs); 190 bdrv_drained_begin(bs); 191 data->done = true; 192 qemu_coroutine_enter(co); 193 } 194 195 static void coroutine_fn bdrv_co_yield_to_drain(BlockDriverState *bs) 196 { 197 BdrvCoDrainData data; 198 199 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and 200 * other coroutines run if they were queued from 201 * qemu_co_queue_run_restart(). */ 202 203 assert(qemu_in_coroutine()); 204 data = (BdrvCoDrainData) { 205 .co = qemu_coroutine_self(), 206 .bs = bs, 207 .done = false, 208 }; 209 bdrv_inc_in_flight(bs); 210 aio_bh_schedule_oneshot(bdrv_get_aio_context(bs), 211 bdrv_co_drain_bh_cb, &data); 212 213 qemu_coroutine_yield(); 214 /* If we are resumed from some other event (such as an aio completion or a 215 * timer callback), it is a bug in the caller that should be fixed. */ 216 assert(data.done); 217 } 218 219 void bdrv_drained_begin(BlockDriverState *bs) 220 { 221 if (qemu_in_coroutine()) { 222 bdrv_co_yield_to_drain(bs); 223 return; 224 } 225 226 if (!bs->quiesce_counter++) { 227 aio_disable_external(bdrv_get_aio_context(bs)); 228 bdrv_parent_drained_begin(bs); 229 } 230 231 bdrv_io_unplugged_begin(bs); 232 bdrv_drain_recurse(bs); 233 bdrv_io_unplugged_end(bs); 234 } 235 236 void bdrv_drained_end(BlockDriverState *bs) 237 { 238 assert(bs->quiesce_counter > 0); 239 if (--bs->quiesce_counter > 0) { 240 return; 241 } 242 243 bdrv_parent_drained_end(bs); 244 aio_enable_external(bdrv_get_aio_context(bs)); 245 } 246 247 /* 248 * Wait for pending requests to complete on a single BlockDriverState subtree, 249 * and suspend block driver's internal I/O until next request arrives. 250 * 251 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState 252 * AioContext. 253 * 254 * Only this BlockDriverState's AioContext is run, so in-flight requests must 255 * not depend on events in other AioContexts. In that case, use 256 * bdrv_drain_all() instead. 257 */ 258 void coroutine_fn bdrv_co_drain(BlockDriverState *bs) 259 { 260 assert(qemu_in_coroutine()); 261 bdrv_drained_begin(bs); 262 bdrv_drained_end(bs); 263 } 264 265 void bdrv_drain(BlockDriverState *bs) 266 { 267 bdrv_drained_begin(bs); 268 bdrv_drained_end(bs); 269 } 270 271 /* 272 * Wait for pending requests to complete across all BlockDriverStates 273 * 274 * This function does not flush data to disk, use bdrv_flush_all() for that 275 * after calling this function. 276 * 277 * This pauses all block jobs and disables external clients. It must 278 * be paired with bdrv_drain_all_end(). 279 * 280 * NOTE: no new block jobs or BlockDriverStates can be created between 281 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls. 282 */ 283 void bdrv_drain_all_begin(void) 284 { 285 /* Always run first iteration so any pending completion BHs run */ 286 bool waited = true; 287 BlockDriverState *bs; 288 BdrvNextIterator it; 289 BlockJob *job = NULL; 290 GSList *aio_ctxs = NULL, *ctx; 291 292 while ((job = block_job_next(job))) { 293 AioContext *aio_context = blk_get_aio_context(job->blk); 294 295 aio_context_acquire(aio_context); 296 block_job_pause(job); 297 aio_context_release(aio_context); 298 } 299 300 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) { 301 AioContext *aio_context = bdrv_get_aio_context(bs); 302 303 aio_context_acquire(aio_context); 304 bdrv_parent_drained_begin(bs); 305 bdrv_io_unplugged_begin(bs); 306 aio_disable_external(aio_context); 307 aio_context_release(aio_context); 308 309 if (!g_slist_find(aio_ctxs, aio_context)) { 310 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context); 311 } 312 } 313 314 /* Note that completion of an asynchronous I/O operation can trigger any 315 * number of other I/O operations on other devices---for example a 316 * coroutine can submit an I/O request to another device in response to 317 * request completion. Therefore we must keep looping until there was no 318 * more activity rather than simply draining each device independently. 319 */ 320 while (waited) { 321 waited = false; 322 323 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) { 324 AioContext *aio_context = ctx->data; 325 326 aio_context_acquire(aio_context); 327 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) { 328 if (aio_context == bdrv_get_aio_context(bs)) { 329 waited |= bdrv_drain_recurse(bs); 330 } 331 } 332 aio_context_release(aio_context); 333 } 334 } 335 336 g_slist_free(aio_ctxs); 337 } 338 339 void bdrv_drain_all_end(void) 340 { 341 BlockDriverState *bs; 342 BdrvNextIterator it; 343 BlockJob *job = NULL; 344 345 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) { 346 AioContext *aio_context = bdrv_get_aio_context(bs); 347 348 aio_context_acquire(aio_context); 349 aio_enable_external(aio_context); 350 bdrv_io_unplugged_end(bs); 351 bdrv_parent_drained_end(bs); 352 aio_context_release(aio_context); 353 } 354 355 while ((job = block_job_next(job))) { 356 AioContext *aio_context = blk_get_aio_context(job->blk); 357 358 aio_context_acquire(aio_context); 359 block_job_resume(job); 360 aio_context_release(aio_context); 361 } 362 } 363 364 void bdrv_drain_all(void) 365 { 366 bdrv_drain_all_begin(); 367 bdrv_drain_all_end(); 368 } 369 370 /** 371 * Remove an active request from the tracked requests list 372 * 373 * This function should be called when a tracked request is completing. 374 */ 375 static void tracked_request_end(BdrvTrackedRequest *req) 376 { 377 if (req->serialising) { 378 req->bs->serialising_in_flight--; 379 } 380 381 QLIST_REMOVE(req, list); 382 qemu_co_queue_restart_all(&req->wait_queue); 383 } 384 385 /** 386 * Add an active request to the tracked requests list 387 */ 388 static void tracked_request_begin(BdrvTrackedRequest *req, 389 BlockDriverState *bs, 390 int64_t offset, 391 unsigned int bytes, 392 enum BdrvTrackedRequestType type) 393 { 394 *req = (BdrvTrackedRequest){ 395 .bs = bs, 396 .offset = offset, 397 .bytes = bytes, 398 .type = type, 399 .co = qemu_coroutine_self(), 400 .serialising = false, 401 .overlap_offset = offset, 402 .overlap_bytes = bytes, 403 }; 404 405 qemu_co_queue_init(&req->wait_queue); 406 407 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list); 408 } 409 410 static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align) 411 { 412 int64_t overlap_offset = req->offset & ~(align - 1); 413 unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align) 414 - overlap_offset; 415 416 if (!req->serialising) { 417 req->bs->serialising_in_flight++; 418 req->serialising = true; 419 } 420 421 req->overlap_offset = MIN(req->overlap_offset, overlap_offset); 422 req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes); 423 } 424 425 /** 426 * Round a region to cluster boundaries (sector-based) 427 */ 428 void bdrv_round_sectors_to_clusters(BlockDriverState *bs, 429 int64_t sector_num, int nb_sectors, 430 int64_t *cluster_sector_num, 431 int *cluster_nb_sectors) 432 { 433 BlockDriverInfo bdi; 434 435 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) { 436 *cluster_sector_num = sector_num; 437 *cluster_nb_sectors = nb_sectors; 438 } else { 439 int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE; 440 *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c); 441 *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num + 442 nb_sectors, c); 443 } 444 } 445 446 /** 447 * Round a region to cluster boundaries 448 */ 449 void bdrv_round_to_clusters(BlockDriverState *bs, 450 int64_t offset, unsigned int bytes, 451 int64_t *cluster_offset, 452 unsigned int *cluster_bytes) 453 { 454 BlockDriverInfo bdi; 455 456 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) { 457 *cluster_offset = offset; 458 *cluster_bytes = bytes; 459 } else { 460 int64_t c = bdi.cluster_size; 461 *cluster_offset = QEMU_ALIGN_DOWN(offset, c); 462 *cluster_bytes = QEMU_ALIGN_UP(offset - *cluster_offset + bytes, c); 463 } 464 } 465 466 static int bdrv_get_cluster_size(BlockDriverState *bs) 467 { 468 BlockDriverInfo bdi; 469 int ret; 470 471 ret = bdrv_get_info(bs, &bdi); 472 if (ret < 0 || bdi.cluster_size == 0) { 473 return bs->bl.request_alignment; 474 } else { 475 return bdi.cluster_size; 476 } 477 } 478 479 static bool tracked_request_overlaps(BdrvTrackedRequest *req, 480 int64_t offset, unsigned int bytes) 481 { 482 /* aaaa bbbb */ 483 if (offset >= req->overlap_offset + req->overlap_bytes) { 484 return false; 485 } 486 /* bbbb aaaa */ 487 if (req->overlap_offset >= offset + bytes) { 488 return false; 489 } 490 return true; 491 } 492 493 void bdrv_inc_in_flight(BlockDriverState *bs) 494 { 495 atomic_inc(&bs->in_flight); 496 } 497 498 static void dummy_bh_cb(void *opaque) 499 { 500 } 501 502 void bdrv_wakeup(BlockDriverState *bs) 503 { 504 if (bs->wakeup) { 505 aio_bh_schedule_oneshot(qemu_get_aio_context(), dummy_bh_cb, NULL); 506 } 507 } 508 509 void bdrv_dec_in_flight(BlockDriverState *bs) 510 { 511 atomic_dec(&bs->in_flight); 512 bdrv_wakeup(bs); 513 } 514 515 static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self) 516 { 517 BlockDriverState *bs = self->bs; 518 BdrvTrackedRequest *req; 519 bool retry; 520 bool waited = false; 521 522 if (!bs->serialising_in_flight) { 523 return false; 524 } 525 526 do { 527 retry = false; 528 QLIST_FOREACH(req, &bs->tracked_requests, list) { 529 if (req == self || (!req->serialising && !self->serialising)) { 530 continue; 531 } 532 if (tracked_request_overlaps(req, self->overlap_offset, 533 self->overlap_bytes)) 534 { 535 /* Hitting this means there was a reentrant request, for 536 * example, a block driver issuing nested requests. This must 537 * never happen since it means deadlock. 538 */ 539 assert(qemu_coroutine_self() != req->co); 540 541 /* If the request is already (indirectly) waiting for us, or 542 * will wait for us as soon as it wakes up, then just go on 543 * (instead of producing a deadlock in the former case). */ 544 if (!req->waiting_for) { 545 self->waiting_for = req; 546 qemu_co_queue_wait(&req->wait_queue); 547 self->waiting_for = NULL; 548 retry = true; 549 waited = true; 550 break; 551 } 552 } 553 } 554 } while (retry); 555 556 return waited; 557 } 558 559 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset, 560 size_t size) 561 { 562 if (size > BDRV_REQUEST_MAX_SECTORS << BDRV_SECTOR_BITS) { 563 return -EIO; 564 } 565 566 if (!bdrv_is_inserted(bs)) { 567 return -ENOMEDIUM; 568 } 569 570 if (offset < 0) { 571 return -EIO; 572 } 573 574 return 0; 575 } 576 577 typedef struct RwCo { 578 BdrvChild *child; 579 int64_t offset; 580 QEMUIOVector *qiov; 581 bool is_write; 582 int ret; 583 BdrvRequestFlags flags; 584 } RwCo; 585 586 static void coroutine_fn bdrv_rw_co_entry(void *opaque) 587 { 588 RwCo *rwco = opaque; 589 590 if (!rwco->is_write) { 591 rwco->ret = bdrv_co_preadv(rwco->child, rwco->offset, 592 rwco->qiov->size, rwco->qiov, 593 rwco->flags); 594 } else { 595 rwco->ret = bdrv_co_pwritev(rwco->child, rwco->offset, 596 rwco->qiov->size, rwco->qiov, 597 rwco->flags); 598 } 599 } 600 601 /* 602 * Process a vectored synchronous request using coroutines 603 */ 604 static int bdrv_prwv_co(BdrvChild *child, int64_t offset, 605 QEMUIOVector *qiov, bool is_write, 606 BdrvRequestFlags flags) 607 { 608 Coroutine *co; 609 RwCo rwco = { 610 .child = child, 611 .offset = offset, 612 .qiov = qiov, 613 .is_write = is_write, 614 .ret = NOT_DONE, 615 .flags = flags, 616 }; 617 618 if (qemu_in_coroutine()) { 619 /* Fast-path if already in coroutine context */ 620 bdrv_rw_co_entry(&rwco); 621 } else { 622 co = qemu_coroutine_create(bdrv_rw_co_entry, &rwco); 623 qemu_coroutine_enter(co); 624 BDRV_POLL_WHILE(child->bs, rwco.ret == NOT_DONE); 625 } 626 return rwco.ret; 627 } 628 629 /* 630 * Process a synchronous request using coroutines 631 */ 632 static int bdrv_rw_co(BdrvChild *child, int64_t sector_num, uint8_t *buf, 633 int nb_sectors, bool is_write, BdrvRequestFlags flags) 634 { 635 QEMUIOVector qiov; 636 struct iovec iov = { 637 .iov_base = (void *)buf, 638 .iov_len = nb_sectors * BDRV_SECTOR_SIZE, 639 }; 640 641 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) { 642 return -EINVAL; 643 } 644 645 qemu_iovec_init_external(&qiov, &iov, 1); 646 return bdrv_prwv_co(child, sector_num << BDRV_SECTOR_BITS, 647 &qiov, is_write, flags); 648 } 649 650 /* return < 0 if error. See bdrv_write() for the return codes */ 651 int bdrv_read(BdrvChild *child, int64_t sector_num, 652 uint8_t *buf, int nb_sectors) 653 { 654 return bdrv_rw_co(child, sector_num, buf, nb_sectors, false, 0); 655 } 656 657 /* Return < 0 if error. Important errors are: 658 -EIO generic I/O error (may happen for all errors) 659 -ENOMEDIUM No media inserted. 660 -EINVAL Invalid sector number or nb_sectors 661 -EACCES Trying to write a read-only device 662 */ 663 int bdrv_write(BdrvChild *child, int64_t sector_num, 664 const uint8_t *buf, int nb_sectors) 665 { 666 return bdrv_rw_co(child, sector_num, (uint8_t *)buf, nb_sectors, true, 0); 667 } 668 669 int bdrv_pwrite_zeroes(BdrvChild *child, int64_t offset, 670 int count, BdrvRequestFlags flags) 671 { 672 QEMUIOVector qiov; 673 struct iovec iov = { 674 .iov_base = NULL, 675 .iov_len = count, 676 }; 677 678 qemu_iovec_init_external(&qiov, &iov, 1); 679 return bdrv_prwv_co(child, offset, &qiov, true, 680 BDRV_REQ_ZERO_WRITE | flags); 681 } 682 683 /* 684 * Completely zero out a block device with the help of bdrv_pwrite_zeroes. 685 * The operation is sped up by checking the block status and only writing 686 * zeroes to the device if they currently do not return zeroes. Optional 687 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP, 688 * BDRV_REQ_FUA). 689 * 690 * Returns < 0 on error, 0 on success. For error codes see bdrv_write(). 691 */ 692 int bdrv_make_zero(BdrvChild *child, BdrvRequestFlags flags) 693 { 694 int64_t target_sectors, ret, nb_sectors, sector_num = 0; 695 BlockDriverState *bs = child->bs; 696 BlockDriverState *file; 697 int n; 698 699 target_sectors = bdrv_nb_sectors(bs); 700 if (target_sectors < 0) { 701 return target_sectors; 702 } 703 704 for (;;) { 705 nb_sectors = MIN(target_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS); 706 if (nb_sectors <= 0) { 707 return 0; 708 } 709 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n, &file); 710 if (ret < 0) { 711 error_report("error getting block status at sector %" PRId64 ": %s", 712 sector_num, strerror(-ret)); 713 return ret; 714 } 715 if (ret & BDRV_BLOCK_ZERO) { 716 sector_num += n; 717 continue; 718 } 719 ret = bdrv_pwrite_zeroes(child, sector_num << BDRV_SECTOR_BITS, 720 n << BDRV_SECTOR_BITS, flags); 721 if (ret < 0) { 722 error_report("error writing zeroes at sector %" PRId64 ": %s", 723 sector_num, strerror(-ret)); 724 return ret; 725 } 726 sector_num += n; 727 } 728 } 729 730 int bdrv_preadv(BdrvChild *child, int64_t offset, QEMUIOVector *qiov) 731 { 732 int ret; 733 734 ret = bdrv_prwv_co(child, offset, qiov, false, 0); 735 if (ret < 0) { 736 return ret; 737 } 738 739 return qiov->size; 740 } 741 742 int bdrv_pread(BdrvChild *child, int64_t offset, void *buf, int bytes) 743 { 744 QEMUIOVector qiov; 745 struct iovec iov = { 746 .iov_base = (void *)buf, 747 .iov_len = bytes, 748 }; 749 750 if (bytes < 0) { 751 return -EINVAL; 752 } 753 754 qemu_iovec_init_external(&qiov, &iov, 1); 755 return bdrv_preadv(child, offset, &qiov); 756 } 757 758 int bdrv_pwritev(BdrvChild *child, int64_t offset, QEMUIOVector *qiov) 759 { 760 int ret; 761 762 ret = bdrv_prwv_co(child, offset, qiov, true, 0); 763 if (ret < 0) { 764 return ret; 765 } 766 767 return qiov->size; 768 } 769 770 int bdrv_pwrite(BdrvChild *child, int64_t offset, const void *buf, int bytes) 771 { 772 QEMUIOVector qiov; 773 struct iovec iov = { 774 .iov_base = (void *) buf, 775 .iov_len = bytes, 776 }; 777 778 if (bytes < 0) { 779 return -EINVAL; 780 } 781 782 qemu_iovec_init_external(&qiov, &iov, 1); 783 return bdrv_pwritev(child, offset, &qiov); 784 } 785 786 /* 787 * Writes to the file and ensures that no writes are reordered across this 788 * request (acts as a barrier) 789 * 790 * Returns 0 on success, -errno in error cases. 791 */ 792 int bdrv_pwrite_sync(BdrvChild *child, int64_t offset, 793 const void *buf, int count) 794 { 795 int ret; 796 797 ret = bdrv_pwrite(child, offset, buf, count); 798 if (ret < 0) { 799 return ret; 800 } 801 802 ret = bdrv_flush(child->bs); 803 if (ret < 0) { 804 return ret; 805 } 806 807 return 0; 808 } 809 810 typedef struct CoroutineIOCompletion { 811 Coroutine *coroutine; 812 int ret; 813 } CoroutineIOCompletion; 814 815 static void bdrv_co_io_em_complete(void *opaque, int ret) 816 { 817 CoroutineIOCompletion *co = opaque; 818 819 co->ret = ret; 820 qemu_coroutine_enter(co->coroutine); 821 } 822 823 static int coroutine_fn bdrv_driver_preadv(BlockDriverState *bs, 824 uint64_t offset, uint64_t bytes, 825 QEMUIOVector *qiov, int flags) 826 { 827 BlockDriver *drv = bs->drv; 828 int64_t sector_num; 829 unsigned int nb_sectors; 830 831 assert(!(flags & ~BDRV_REQ_MASK)); 832 833 if (drv->bdrv_co_preadv) { 834 return drv->bdrv_co_preadv(bs, offset, bytes, qiov, flags); 835 } 836 837 sector_num = offset >> BDRV_SECTOR_BITS; 838 nb_sectors = bytes >> BDRV_SECTOR_BITS; 839 840 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0); 841 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0); 842 assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS); 843 844 if (drv->bdrv_co_readv) { 845 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov); 846 } else { 847 BlockAIOCB *acb; 848 CoroutineIOCompletion co = { 849 .coroutine = qemu_coroutine_self(), 850 }; 851 852 acb = bs->drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors, 853 bdrv_co_io_em_complete, &co); 854 if (acb == NULL) { 855 return -EIO; 856 } else { 857 qemu_coroutine_yield(); 858 return co.ret; 859 } 860 } 861 } 862 863 static int coroutine_fn bdrv_driver_pwritev(BlockDriverState *bs, 864 uint64_t offset, uint64_t bytes, 865 QEMUIOVector *qiov, int flags) 866 { 867 BlockDriver *drv = bs->drv; 868 int64_t sector_num; 869 unsigned int nb_sectors; 870 int ret; 871 872 assert(!(flags & ~BDRV_REQ_MASK)); 873 874 if (drv->bdrv_co_pwritev) { 875 ret = drv->bdrv_co_pwritev(bs, offset, bytes, qiov, 876 flags & bs->supported_write_flags); 877 flags &= ~bs->supported_write_flags; 878 goto emulate_flags; 879 } 880 881 sector_num = offset >> BDRV_SECTOR_BITS; 882 nb_sectors = bytes >> BDRV_SECTOR_BITS; 883 884 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0); 885 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0); 886 assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS); 887 888 if (drv->bdrv_co_writev_flags) { 889 ret = drv->bdrv_co_writev_flags(bs, sector_num, nb_sectors, qiov, 890 flags & bs->supported_write_flags); 891 flags &= ~bs->supported_write_flags; 892 } else if (drv->bdrv_co_writev) { 893 assert(!bs->supported_write_flags); 894 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov); 895 } else { 896 BlockAIOCB *acb; 897 CoroutineIOCompletion co = { 898 .coroutine = qemu_coroutine_self(), 899 }; 900 901 acb = bs->drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors, 902 bdrv_co_io_em_complete, &co); 903 if (acb == NULL) { 904 ret = -EIO; 905 } else { 906 qemu_coroutine_yield(); 907 ret = co.ret; 908 } 909 } 910 911 emulate_flags: 912 if (ret == 0 && (flags & BDRV_REQ_FUA)) { 913 ret = bdrv_co_flush(bs); 914 } 915 916 return ret; 917 } 918 919 static int coroutine_fn 920 bdrv_driver_pwritev_compressed(BlockDriverState *bs, uint64_t offset, 921 uint64_t bytes, QEMUIOVector *qiov) 922 { 923 BlockDriver *drv = bs->drv; 924 925 if (!drv->bdrv_co_pwritev_compressed) { 926 return -ENOTSUP; 927 } 928 929 return drv->bdrv_co_pwritev_compressed(bs, offset, bytes, qiov); 930 } 931 932 static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs, 933 int64_t offset, unsigned int bytes, QEMUIOVector *qiov) 934 { 935 /* Perform I/O through a temporary buffer so that users who scribble over 936 * their read buffer while the operation is in progress do not end up 937 * modifying the image file. This is critical for zero-copy guest I/O 938 * where anything might happen inside guest memory. 939 */ 940 void *bounce_buffer; 941 942 BlockDriver *drv = bs->drv; 943 struct iovec iov; 944 QEMUIOVector bounce_qiov; 945 int64_t cluster_offset; 946 unsigned int cluster_bytes; 947 size_t skip_bytes; 948 int ret; 949 950 /* Cover entire cluster so no additional backing file I/O is required when 951 * allocating cluster in the image file. 952 */ 953 bdrv_round_to_clusters(bs, offset, bytes, &cluster_offset, &cluster_bytes); 954 955 trace_bdrv_co_do_copy_on_readv(bs, offset, bytes, 956 cluster_offset, cluster_bytes); 957 958 iov.iov_len = cluster_bytes; 959 iov.iov_base = bounce_buffer = qemu_try_blockalign(bs, iov.iov_len); 960 if (bounce_buffer == NULL) { 961 ret = -ENOMEM; 962 goto err; 963 } 964 965 qemu_iovec_init_external(&bounce_qiov, &iov, 1); 966 967 ret = bdrv_driver_preadv(bs, cluster_offset, cluster_bytes, 968 &bounce_qiov, 0); 969 if (ret < 0) { 970 goto err; 971 } 972 973 if (drv->bdrv_co_pwrite_zeroes && 974 buffer_is_zero(bounce_buffer, iov.iov_len)) { 975 /* FIXME: Should we (perhaps conditionally) be setting 976 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy 977 * that still correctly reads as zero? */ 978 ret = bdrv_co_do_pwrite_zeroes(bs, cluster_offset, cluster_bytes, 0); 979 } else { 980 /* This does not change the data on the disk, it is not necessary 981 * to flush even in cache=writethrough mode. 982 */ 983 ret = bdrv_driver_pwritev(bs, cluster_offset, cluster_bytes, 984 &bounce_qiov, 0); 985 } 986 987 if (ret < 0) { 988 /* It might be okay to ignore write errors for guest requests. If this 989 * is a deliberate copy-on-read then we don't want to ignore the error. 990 * Simply report it in all cases. 991 */ 992 goto err; 993 } 994 995 skip_bytes = offset - cluster_offset; 996 qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes, bytes); 997 998 err: 999 qemu_vfree(bounce_buffer); 1000 return ret; 1001 } 1002 1003 /* 1004 * Forwards an already correctly aligned request to the BlockDriver. This 1005 * handles copy on read, zeroing after EOF, and fragmentation of large 1006 * reads; any other features must be implemented by the caller. 1007 */ 1008 static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs, 1009 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes, 1010 int64_t align, QEMUIOVector *qiov, int flags) 1011 { 1012 int64_t total_bytes, max_bytes; 1013 int ret = 0; 1014 uint64_t bytes_remaining = bytes; 1015 int max_transfer; 1016 1017 assert(is_power_of_2(align)); 1018 assert((offset & (align - 1)) == 0); 1019 assert((bytes & (align - 1)) == 0); 1020 assert(!qiov || bytes == qiov->size); 1021 assert((bs->open_flags & BDRV_O_NO_IO) == 0); 1022 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX), 1023 align); 1024 1025 /* TODO: We would need a per-BDS .supported_read_flags and 1026 * potential fallback support, if we ever implement any read flags 1027 * to pass through to drivers. For now, there aren't any 1028 * passthrough flags. */ 1029 assert(!(flags & ~(BDRV_REQ_NO_SERIALISING | BDRV_REQ_COPY_ON_READ))); 1030 1031 /* Handle Copy on Read and associated serialisation */ 1032 if (flags & BDRV_REQ_COPY_ON_READ) { 1033 /* If we touch the same cluster it counts as an overlap. This 1034 * guarantees that allocating writes will be serialized and not race 1035 * with each other for the same cluster. For example, in copy-on-read 1036 * it ensures that the CoR read and write operations are atomic and 1037 * guest writes cannot interleave between them. */ 1038 mark_request_serialising(req, bdrv_get_cluster_size(bs)); 1039 } 1040 1041 if (!(flags & BDRV_REQ_NO_SERIALISING)) { 1042 wait_serialising_requests(req); 1043 } 1044 1045 if (flags & BDRV_REQ_COPY_ON_READ) { 1046 int64_t start_sector = offset >> BDRV_SECTOR_BITS; 1047 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE); 1048 unsigned int nb_sectors = end_sector - start_sector; 1049 int pnum; 1050 1051 ret = bdrv_is_allocated(bs, start_sector, nb_sectors, &pnum); 1052 if (ret < 0) { 1053 goto out; 1054 } 1055 1056 if (!ret || pnum != nb_sectors) { 1057 ret = bdrv_co_do_copy_on_readv(bs, offset, bytes, qiov); 1058 goto out; 1059 } 1060 } 1061 1062 /* Forward the request to the BlockDriver, possibly fragmenting it */ 1063 total_bytes = bdrv_getlength(bs); 1064 if (total_bytes < 0) { 1065 ret = total_bytes; 1066 goto out; 1067 } 1068 1069 max_bytes = ROUND_UP(MAX(0, total_bytes - offset), align); 1070 if (bytes <= max_bytes && bytes <= max_transfer) { 1071 ret = bdrv_driver_preadv(bs, offset, bytes, qiov, 0); 1072 goto out; 1073 } 1074 1075 while (bytes_remaining) { 1076 int num; 1077 1078 if (max_bytes) { 1079 QEMUIOVector local_qiov; 1080 1081 num = MIN(bytes_remaining, MIN(max_bytes, max_transfer)); 1082 assert(num); 1083 qemu_iovec_init(&local_qiov, qiov->niov); 1084 qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num); 1085 1086 ret = bdrv_driver_preadv(bs, offset + bytes - bytes_remaining, 1087 num, &local_qiov, 0); 1088 max_bytes -= num; 1089 qemu_iovec_destroy(&local_qiov); 1090 } else { 1091 num = bytes_remaining; 1092 ret = qemu_iovec_memset(qiov, bytes - bytes_remaining, 0, 1093 bytes_remaining); 1094 } 1095 if (ret < 0) { 1096 goto out; 1097 } 1098 bytes_remaining -= num; 1099 } 1100 1101 out: 1102 return ret < 0 ? ret : 0; 1103 } 1104 1105 /* 1106 * Handle a read request in coroutine context 1107 */ 1108 int coroutine_fn bdrv_co_preadv(BdrvChild *child, 1109 int64_t offset, unsigned int bytes, QEMUIOVector *qiov, 1110 BdrvRequestFlags flags) 1111 { 1112 BlockDriverState *bs = child->bs; 1113 BlockDriver *drv = bs->drv; 1114 BdrvTrackedRequest req; 1115 1116 uint64_t align = bs->bl.request_alignment; 1117 uint8_t *head_buf = NULL; 1118 uint8_t *tail_buf = NULL; 1119 QEMUIOVector local_qiov; 1120 bool use_local_qiov = false; 1121 int ret; 1122 1123 if (!drv) { 1124 return -ENOMEDIUM; 1125 } 1126 1127 ret = bdrv_check_byte_request(bs, offset, bytes); 1128 if (ret < 0) { 1129 return ret; 1130 } 1131 1132 bdrv_inc_in_flight(bs); 1133 1134 /* Don't do copy-on-read if we read data before write operation */ 1135 if (bs->copy_on_read && !(flags & BDRV_REQ_NO_SERIALISING)) { 1136 flags |= BDRV_REQ_COPY_ON_READ; 1137 } 1138 1139 /* Align read if necessary by padding qiov */ 1140 if (offset & (align - 1)) { 1141 head_buf = qemu_blockalign(bs, align); 1142 qemu_iovec_init(&local_qiov, qiov->niov + 2); 1143 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1)); 1144 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 1145 use_local_qiov = true; 1146 1147 bytes += offset & (align - 1); 1148 offset = offset & ~(align - 1); 1149 } 1150 1151 if ((offset + bytes) & (align - 1)) { 1152 if (!use_local_qiov) { 1153 qemu_iovec_init(&local_qiov, qiov->niov + 1); 1154 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 1155 use_local_qiov = true; 1156 } 1157 tail_buf = qemu_blockalign(bs, align); 1158 qemu_iovec_add(&local_qiov, tail_buf, 1159 align - ((offset + bytes) & (align - 1))); 1160 1161 bytes = ROUND_UP(bytes, align); 1162 } 1163 1164 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_READ); 1165 ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align, 1166 use_local_qiov ? &local_qiov : qiov, 1167 flags); 1168 tracked_request_end(&req); 1169 bdrv_dec_in_flight(bs); 1170 1171 if (use_local_qiov) { 1172 qemu_iovec_destroy(&local_qiov); 1173 qemu_vfree(head_buf); 1174 qemu_vfree(tail_buf); 1175 } 1176 1177 return ret; 1178 } 1179 1180 static int coroutine_fn bdrv_co_do_readv(BdrvChild *child, 1181 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov, 1182 BdrvRequestFlags flags) 1183 { 1184 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) { 1185 return -EINVAL; 1186 } 1187 1188 return bdrv_co_preadv(child, sector_num << BDRV_SECTOR_BITS, 1189 nb_sectors << BDRV_SECTOR_BITS, qiov, flags); 1190 } 1191 1192 int coroutine_fn bdrv_co_readv(BdrvChild *child, int64_t sector_num, 1193 int nb_sectors, QEMUIOVector *qiov) 1194 { 1195 trace_bdrv_co_readv(child->bs, sector_num, nb_sectors); 1196 1197 return bdrv_co_do_readv(child, sector_num, nb_sectors, qiov, 0); 1198 } 1199 1200 /* Maximum buffer for write zeroes fallback, in bytes */ 1201 #define MAX_WRITE_ZEROES_BOUNCE_BUFFER (32768 << BDRV_SECTOR_BITS) 1202 1203 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs, 1204 int64_t offset, int count, BdrvRequestFlags flags) 1205 { 1206 BlockDriver *drv = bs->drv; 1207 QEMUIOVector qiov; 1208 struct iovec iov = {0}; 1209 int ret = 0; 1210 bool need_flush = false; 1211 int head = 0; 1212 int tail = 0; 1213 1214 int max_write_zeroes = MIN_NON_ZERO(bs->bl.max_pwrite_zeroes, INT_MAX); 1215 int alignment = MAX(bs->bl.pwrite_zeroes_alignment, 1216 bs->bl.request_alignment); 1217 1218 assert(alignment % bs->bl.request_alignment == 0); 1219 head = offset % alignment; 1220 tail = (offset + count) % alignment; 1221 max_write_zeroes = QEMU_ALIGN_DOWN(max_write_zeroes, alignment); 1222 assert(max_write_zeroes >= bs->bl.request_alignment); 1223 1224 while (count > 0 && !ret) { 1225 int num = count; 1226 1227 /* Align request. Block drivers can expect the "bulk" of the request 1228 * to be aligned, and that unaligned requests do not cross cluster 1229 * boundaries. 1230 */ 1231 if (head) { 1232 /* Make a small request up to the first aligned sector. */ 1233 num = MIN(count, alignment - head); 1234 head = 0; 1235 } else if (tail && num > alignment) { 1236 /* Shorten the request to the last aligned sector. */ 1237 num -= tail; 1238 } 1239 1240 /* limit request size */ 1241 if (num > max_write_zeroes) { 1242 num = max_write_zeroes; 1243 } 1244 1245 ret = -ENOTSUP; 1246 /* First try the efficient write zeroes operation */ 1247 if (drv->bdrv_co_pwrite_zeroes) { 1248 ret = drv->bdrv_co_pwrite_zeroes(bs, offset, num, 1249 flags & bs->supported_zero_flags); 1250 if (ret != -ENOTSUP && (flags & BDRV_REQ_FUA) && 1251 !(bs->supported_zero_flags & BDRV_REQ_FUA)) { 1252 need_flush = true; 1253 } 1254 } else { 1255 assert(!bs->supported_zero_flags); 1256 } 1257 1258 if (ret == -ENOTSUP) { 1259 /* Fall back to bounce buffer if write zeroes is unsupported */ 1260 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer, 1261 MAX_WRITE_ZEROES_BOUNCE_BUFFER); 1262 BdrvRequestFlags write_flags = flags & ~BDRV_REQ_ZERO_WRITE; 1263 1264 if ((flags & BDRV_REQ_FUA) && 1265 !(bs->supported_write_flags & BDRV_REQ_FUA)) { 1266 /* No need for bdrv_driver_pwrite() to do a fallback 1267 * flush on each chunk; use just one at the end */ 1268 write_flags &= ~BDRV_REQ_FUA; 1269 need_flush = true; 1270 } 1271 num = MIN(num, max_transfer); 1272 iov.iov_len = num; 1273 if (iov.iov_base == NULL) { 1274 iov.iov_base = qemu_try_blockalign(bs, num); 1275 if (iov.iov_base == NULL) { 1276 ret = -ENOMEM; 1277 goto fail; 1278 } 1279 memset(iov.iov_base, 0, num); 1280 } 1281 qemu_iovec_init_external(&qiov, &iov, 1); 1282 1283 ret = bdrv_driver_pwritev(bs, offset, num, &qiov, write_flags); 1284 1285 /* Keep bounce buffer around if it is big enough for all 1286 * all future requests. 1287 */ 1288 if (num < max_transfer) { 1289 qemu_vfree(iov.iov_base); 1290 iov.iov_base = NULL; 1291 } 1292 } 1293 1294 offset += num; 1295 count -= num; 1296 } 1297 1298 fail: 1299 if (ret == 0 && need_flush) { 1300 ret = bdrv_co_flush(bs); 1301 } 1302 qemu_vfree(iov.iov_base); 1303 return ret; 1304 } 1305 1306 /* 1307 * Forwards an already correctly aligned write request to the BlockDriver, 1308 * after possibly fragmenting it. 1309 */ 1310 static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs, 1311 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes, 1312 int64_t align, QEMUIOVector *qiov, int flags) 1313 { 1314 BlockDriver *drv = bs->drv; 1315 bool waited; 1316 int ret; 1317 1318 int64_t start_sector = offset >> BDRV_SECTOR_BITS; 1319 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE); 1320 uint64_t bytes_remaining = bytes; 1321 int max_transfer; 1322 1323 assert(is_power_of_2(align)); 1324 assert((offset & (align - 1)) == 0); 1325 assert((bytes & (align - 1)) == 0); 1326 assert(!qiov || bytes == qiov->size); 1327 assert((bs->open_flags & BDRV_O_NO_IO) == 0); 1328 assert(!(flags & ~BDRV_REQ_MASK)); 1329 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX), 1330 align); 1331 1332 waited = wait_serialising_requests(req); 1333 assert(!waited || !req->serialising); 1334 assert(req->overlap_offset <= offset); 1335 assert(offset + bytes <= req->overlap_offset + req->overlap_bytes); 1336 1337 ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req); 1338 1339 if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF && 1340 !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_pwrite_zeroes && 1341 qemu_iovec_is_zero(qiov)) { 1342 flags |= BDRV_REQ_ZERO_WRITE; 1343 if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) { 1344 flags |= BDRV_REQ_MAY_UNMAP; 1345 } 1346 } 1347 1348 if (ret < 0) { 1349 /* Do nothing, write notifier decided to fail this request */ 1350 } else if (flags & BDRV_REQ_ZERO_WRITE) { 1351 bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO); 1352 ret = bdrv_co_do_pwrite_zeroes(bs, offset, bytes, flags); 1353 } else if (flags & BDRV_REQ_WRITE_COMPRESSED) { 1354 ret = bdrv_driver_pwritev_compressed(bs, offset, bytes, qiov); 1355 } else if (bytes <= max_transfer) { 1356 bdrv_debug_event(bs, BLKDBG_PWRITEV); 1357 ret = bdrv_driver_pwritev(bs, offset, bytes, qiov, flags); 1358 } else { 1359 bdrv_debug_event(bs, BLKDBG_PWRITEV); 1360 while (bytes_remaining) { 1361 int num = MIN(bytes_remaining, max_transfer); 1362 QEMUIOVector local_qiov; 1363 int local_flags = flags; 1364 1365 assert(num); 1366 if (num < bytes_remaining && (flags & BDRV_REQ_FUA) && 1367 !(bs->supported_write_flags & BDRV_REQ_FUA)) { 1368 /* If FUA is going to be emulated by flush, we only 1369 * need to flush on the last iteration */ 1370 local_flags &= ~BDRV_REQ_FUA; 1371 } 1372 qemu_iovec_init(&local_qiov, qiov->niov); 1373 qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num); 1374 1375 ret = bdrv_driver_pwritev(bs, offset + bytes - bytes_remaining, 1376 num, &local_qiov, local_flags); 1377 qemu_iovec_destroy(&local_qiov); 1378 if (ret < 0) { 1379 break; 1380 } 1381 bytes_remaining -= num; 1382 } 1383 } 1384 bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE); 1385 1386 ++bs->write_gen; 1387 bdrv_set_dirty(bs, start_sector, end_sector - start_sector); 1388 1389 if (bs->wr_highest_offset < offset + bytes) { 1390 bs->wr_highest_offset = offset + bytes; 1391 } 1392 1393 if (ret >= 0) { 1394 bs->total_sectors = MAX(bs->total_sectors, end_sector); 1395 ret = 0; 1396 } 1397 1398 return ret; 1399 } 1400 1401 static int coroutine_fn bdrv_co_do_zero_pwritev(BlockDriverState *bs, 1402 int64_t offset, 1403 unsigned int bytes, 1404 BdrvRequestFlags flags, 1405 BdrvTrackedRequest *req) 1406 { 1407 uint8_t *buf = NULL; 1408 QEMUIOVector local_qiov; 1409 struct iovec iov; 1410 uint64_t align = bs->bl.request_alignment; 1411 unsigned int head_padding_bytes, tail_padding_bytes; 1412 int ret = 0; 1413 1414 head_padding_bytes = offset & (align - 1); 1415 tail_padding_bytes = align - ((offset + bytes) & (align - 1)); 1416 1417 1418 assert(flags & BDRV_REQ_ZERO_WRITE); 1419 if (head_padding_bytes || tail_padding_bytes) { 1420 buf = qemu_blockalign(bs, align); 1421 iov = (struct iovec) { 1422 .iov_base = buf, 1423 .iov_len = align, 1424 }; 1425 qemu_iovec_init_external(&local_qiov, &iov, 1); 1426 } 1427 if (head_padding_bytes) { 1428 uint64_t zero_bytes = MIN(bytes, align - head_padding_bytes); 1429 1430 /* RMW the unaligned part before head. */ 1431 mark_request_serialising(req, align); 1432 wait_serialising_requests(req); 1433 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD); 1434 ret = bdrv_aligned_preadv(bs, req, offset & ~(align - 1), align, 1435 align, &local_qiov, 0); 1436 if (ret < 0) { 1437 goto fail; 1438 } 1439 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD); 1440 1441 memset(buf + head_padding_bytes, 0, zero_bytes); 1442 ret = bdrv_aligned_pwritev(bs, req, offset & ~(align - 1), align, 1443 align, &local_qiov, 1444 flags & ~BDRV_REQ_ZERO_WRITE); 1445 if (ret < 0) { 1446 goto fail; 1447 } 1448 offset += zero_bytes; 1449 bytes -= zero_bytes; 1450 } 1451 1452 assert(!bytes || (offset & (align - 1)) == 0); 1453 if (bytes >= align) { 1454 /* Write the aligned part in the middle. */ 1455 uint64_t aligned_bytes = bytes & ~(align - 1); 1456 ret = bdrv_aligned_pwritev(bs, req, offset, aligned_bytes, align, 1457 NULL, flags); 1458 if (ret < 0) { 1459 goto fail; 1460 } 1461 bytes -= aligned_bytes; 1462 offset += aligned_bytes; 1463 } 1464 1465 assert(!bytes || (offset & (align - 1)) == 0); 1466 if (bytes) { 1467 assert(align == tail_padding_bytes + bytes); 1468 /* RMW the unaligned part after tail. */ 1469 mark_request_serialising(req, align); 1470 wait_serialising_requests(req); 1471 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL); 1472 ret = bdrv_aligned_preadv(bs, req, offset, align, 1473 align, &local_qiov, 0); 1474 if (ret < 0) { 1475 goto fail; 1476 } 1477 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL); 1478 1479 memset(buf, 0, bytes); 1480 ret = bdrv_aligned_pwritev(bs, req, offset, align, align, 1481 &local_qiov, flags & ~BDRV_REQ_ZERO_WRITE); 1482 } 1483 fail: 1484 qemu_vfree(buf); 1485 return ret; 1486 1487 } 1488 1489 /* 1490 * Handle a write request in coroutine context 1491 */ 1492 int coroutine_fn bdrv_co_pwritev(BdrvChild *child, 1493 int64_t offset, unsigned int bytes, QEMUIOVector *qiov, 1494 BdrvRequestFlags flags) 1495 { 1496 BlockDriverState *bs = child->bs; 1497 BdrvTrackedRequest req; 1498 uint64_t align = bs->bl.request_alignment; 1499 uint8_t *head_buf = NULL; 1500 uint8_t *tail_buf = NULL; 1501 QEMUIOVector local_qiov; 1502 bool use_local_qiov = false; 1503 int ret; 1504 1505 if (!bs->drv) { 1506 return -ENOMEDIUM; 1507 } 1508 if (bs->read_only) { 1509 return -EPERM; 1510 } 1511 assert(!(bs->open_flags & BDRV_O_INACTIVE)); 1512 1513 ret = bdrv_check_byte_request(bs, offset, bytes); 1514 if (ret < 0) { 1515 return ret; 1516 } 1517 1518 bdrv_inc_in_flight(bs); 1519 /* 1520 * Align write if necessary by performing a read-modify-write cycle. 1521 * Pad qiov with the read parts and be sure to have a tracked request not 1522 * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle. 1523 */ 1524 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE); 1525 1526 if (!qiov) { 1527 ret = bdrv_co_do_zero_pwritev(bs, offset, bytes, flags, &req); 1528 goto out; 1529 } 1530 1531 if (offset & (align - 1)) { 1532 QEMUIOVector head_qiov; 1533 struct iovec head_iov; 1534 1535 mark_request_serialising(&req, align); 1536 wait_serialising_requests(&req); 1537 1538 head_buf = qemu_blockalign(bs, align); 1539 head_iov = (struct iovec) { 1540 .iov_base = head_buf, 1541 .iov_len = align, 1542 }; 1543 qemu_iovec_init_external(&head_qiov, &head_iov, 1); 1544 1545 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD); 1546 ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align, 1547 align, &head_qiov, 0); 1548 if (ret < 0) { 1549 goto fail; 1550 } 1551 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD); 1552 1553 qemu_iovec_init(&local_qiov, qiov->niov + 2); 1554 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1)); 1555 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 1556 use_local_qiov = true; 1557 1558 bytes += offset & (align - 1); 1559 offset = offset & ~(align - 1); 1560 1561 /* We have read the tail already if the request is smaller 1562 * than one aligned block. 1563 */ 1564 if (bytes < align) { 1565 qemu_iovec_add(&local_qiov, head_buf + bytes, align - bytes); 1566 bytes = align; 1567 } 1568 } 1569 1570 if ((offset + bytes) & (align - 1)) { 1571 QEMUIOVector tail_qiov; 1572 struct iovec tail_iov; 1573 size_t tail_bytes; 1574 bool waited; 1575 1576 mark_request_serialising(&req, align); 1577 waited = wait_serialising_requests(&req); 1578 assert(!waited || !use_local_qiov); 1579 1580 tail_buf = qemu_blockalign(bs, align); 1581 tail_iov = (struct iovec) { 1582 .iov_base = tail_buf, 1583 .iov_len = align, 1584 }; 1585 qemu_iovec_init_external(&tail_qiov, &tail_iov, 1); 1586 1587 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL); 1588 ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align, 1589 align, &tail_qiov, 0); 1590 if (ret < 0) { 1591 goto fail; 1592 } 1593 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL); 1594 1595 if (!use_local_qiov) { 1596 qemu_iovec_init(&local_qiov, qiov->niov + 1); 1597 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size); 1598 use_local_qiov = true; 1599 } 1600 1601 tail_bytes = (offset + bytes) & (align - 1); 1602 qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes); 1603 1604 bytes = ROUND_UP(bytes, align); 1605 } 1606 1607 ret = bdrv_aligned_pwritev(bs, &req, offset, bytes, align, 1608 use_local_qiov ? &local_qiov : qiov, 1609 flags); 1610 1611 fail: 1612 1613 if (use_local_qiov) { 1614 qemu_iovec_destroy(&local_qiov); 1615 } 1616 qemu_vfree(head_buf); 1617 qemu_vfree(tail_buf); 1618 out: 1619 tracked_request_end(&req); 1620 bdrv_dec_in_flight(bs); 1621 return ret; 1622 } 1623 1624 static int coroutine_fn bdrv_co_do_writev(BdrvChild *child, 1625 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov, 1626 BdrvRequestFlags flags) 1627 { 1628 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) { 1629 return -EINVAL; 1630 } 1631 1632 return bdrv_co_pwritev(child, sector_num << BDRV_SECTOR_BITS, 1633 nb_sectors << BDRV_SECTOR_BITS, qiov, flags); 1634 } 1635 1636 int coroutine_fn bdrv_co_writev(BdrvChild *child, int64_t sector_num, 1637 int nb_sectors, QEMUIOVector *qiov) 1638 { 1639 trace_bdrv_co_writev(child->bs, sector_num, nb_sectors); 1640 1641 return bdrv_co_do_writev(child, sector_num, nb_sectors, qiov, 0); 1642 } 1643 1644 int coroutine_fn bdrv_co_pwrite_zeroes(BdrvChild *child, int64_t offset, 1645 int count, BdrvRequestFlags flags) 1646 { 1647 trace_bdrv_co_pwrite_zeroes(child->bs, offset, count, flags); 1648 1649 if (!(child->bs->open_flags & BDRV_O_UNMAP)) { 1650 flags &= ~BDRV_REQ_MAY_UNMAP; 1651 } 1652 1653 return bdrv_co_pwritev(child, offset, count, NULL, 1654 BDRV_REQ_ZERO_WRITE | flags); 1655 } 1656 1657 /* 1658 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not. 1659 */ 1660 int bdrv_flush_all(void) 1661 { 1662 BdrvNextIterator it; 1663 BlockDriverState *bs = NULL; 1664 int result = 0; 1665 1666 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) { 1667 AioContext *aio_context = bdrv_get_aio_context(bs); 1668 int ret; 1669 1670 aio_context_acquire(aio_context); 1671 ret = bdrv_flush(bs); 1672 if (ret < 0 && !result) { 1673 result = ret; 1674 } 1675 aio_context_release(aio_context); 1676 } 1677 1678 return result; 1679 } 1680 1681 1682 typedef struct BdrvCoGetBlockStatusData { 1683 BlockDriverState *bs; 1684 BlockDriverState *base; 1685 BlockDriverState **file; 1686 int64_t sector_num; 1687 int nb_sectors; 1688 int *pnum; 1689 int64_t ret; 1690 bool done; 1691 } BdrvCoGetBlockStatusData; 1692 1693 /* 1694 * Returns the allocation status of the specified sectors. 1695 * Drivers not implementing the functionality are assumed to not support 1696 * backing files, hence all their sectors are reported as allocated. 1697 * 1698 * If 'sector_num' is beyond the end of the disk image the return value is 0 1699 * and 'pnum' is set to 0. 1700 * 1701 * 'pnum' is set to the number of sectors (including and immediately following 1702 * the specified sector) that are known to be in the same 1703 * allocated/unallocated state. 1704 * 1705 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes 1706 * beyond the end of the disk image it will be clamped. 1707 * 1708 * If returned value is positive and BDRV_BLOCK_OFFSET_VALID bit is set, 'file' 1709 * points to the BDS which the sector range is allocated in. 1710 */ 1711 static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs, 1712 int64_t sector_num, 1713 int nb_sectors, int *pnum, 1714 BlockDriverState **file) 1715 { 1716 int64_t total_sectors; 1717 int64_t n; 1718 int64_t ret, ret2; 1719 1720 total_sectors = bdrv_nb_sectors(bs); 1721 if (total_sectors < 0) { 1722 return total_sectors; 1723 } 1724 1725 if (sector_num >= total_sectors) { 1726 *pnum = 0; 1727 return 0; 1728 } 1729 1730 n = total_sectors - sector_num; 1731 if (n < nb_sectors) { 1732 nb_sectors = n; 1733 } 1734 1735 if (!bs->drv->bdrv_co_get_block_status) { 1736 *pnum = nb_sectors; 1737 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED; 1738 if (bs->drv->protocol_name) { 1739 ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE); 1740 } 1741 return ret; 1742 } 1743 1744 *file = NULL; 1745 bdrv_inc_in_flight(bs); 1746 ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum, 1747 file); 1748 if (ret < 0) { 1749 *pnum = 0; 1750 goto out; 1751 } 1752 1753 if (ret & BDRV_BLOCK_RAW) { 1754 assert(ret & BDRV_BLOCK_OFFSET_VALID); 1755 ret = bdrv_get_block_status(bs->file->bs, ret >> BDRV_SECTOR_BITS, 1756 *pnum, pnum, file); 1757 goto out; 1758 } 1759 1760 if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) { 1761 ret |= BDRV_BLOCK_ALLOCATED; 1762 } else { 1763 if (bdrv_unallocated_blocks_are_zero(bs)) { 1764 ret |= BDRV_BLOCK_ZERO; 1765 } else if (bs->backing) { 1766 BlockDriverState *bs2 = bs->backing->bs; 1767 int64_t nb_sectors2 = bdrv_nb_sectors(bs2); 1768 if (nb_sectors2 >= 0 && sector_num >= nb_sectors2) { 1769 ret |= BDRV_BLOCK_ZERO; 1770 } 1771 } 1772 } 1773 1774 if (*file && *file != bs && 1775 (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) && 1776 (ret & BDRV_BLOCK_OFFSET_VALID)) { 1777 BlockDriverState *file2; 1778 int file_pnum; 1779 1780 ret2 = bdrv_co_get_block_status(*file, ret >> BDRV_SECTOR_BITS, 1781 *pnum, &file_pnum, &file2); 1782 if (ret2 >= 0) { 1783 /* Ignore errors. This is just providing extra information, it 1784 * is useful but not necessary. 1785 */ 1786 if (!file_pnum) { 1787 /* !file_pnum indicates an offset at or beyond the EOF; it is 1788 * perfectly valid for the format block driver to point to such 1789 * offsets, so catch it and mark everything as zero */ 1790 ret |= BDRV_BLOCK_ZERO; 1791 } else { 1792 /* Limit request to the range reported by the protocol driver */ 1793 *pnum = file_pnum; 1794 ret |= (ret2 & BDRV_BLOCK_ZERO); 1795 } 1796 } 1797 } 1798 1799 out: 1800 bdrv_dec_in_flight(bs); 1801 return ret; 1802 } 1803 1804 static int64_t coroutine_fn bdrv_co_get_block_status_above(BlockDriverState *bs, 1805 BlockDriverState *base, 1806 int64_t sector_num, 1807 int nb_sectors, 1808 int *pnum, 1809 BlockDriverState **file) 1810 { 1811 BlockDriverState *p; 1812 int64_t ret = 0; 1813 1814 assert(bs != base); 1815 for (p = bs; p != base; p = backing_bs(p)) { 1816 ret = bdrv_co_get_block_status(p, sector_num, nb_sectors, pnum, file); 1817 if (ret < 0 || ret & BDRV_BLOCK_ALLOCATED) { 1818 break; 1819 } 1820 /* [sector_num, pnum] unallocated on this layer, which could be only 1821 * the first part of [sector_num, nb_sectors]. */ 1822 nb_sectors = MIN(nb_sectors, *pnum); 1823 } 1824 return ret; 1825 } 1826 1827 /* Coroutine wrapper for bdrv_get_block_status_above() */ 1828 static void coroutine_fn bdrv_get_block_status_above_co_entry(void *opaque) 1829 { 1830 BdrvCoGetBlockStatusData *data = opaque; 1831 1832 data->ret = bdrv_co_get_block_status_above(data->bs, data->base, 1833 data->sector_num, 1834 data->nb_sectors, 1835 data->pnum, 1836 data->file); 1837 data->done = true; 1838 } 1839 1840 /* 1841 * Synchronous wrapper around bdrv_co_get_block_status_above(). 1842 * 1843 * See bdrv_co_get_block_status_above() for details. 1844 */ 1845 int64_t bdrv_get_block_status_above(BlockDriverState *bs, 1846 BlockDriverState *base, 1847 int64_t sector_num, 1848 int nb_sectors, int *pnum, 1849 BlockDriverState **file) 1850 { 1851 Coroutine *co; 1852 BdrvCoGetBlockStatusData data = { 1853 .bs = bs, 1854 .base = base, 1855 .file = file, 1856 .sector_num = sector_num, 1857 .nb_sectors = nb_sectors, 1858 .pnum = pnum, 1859 .done = false, 1860 }; 1861 1862 if (qemu_in_coroutine()) { 1863 /* Fast-path if already in coroutine context */ 1864 bdrv_get_block_status_above_co_entry(&data); 1865 } else { 1866 co = qemu_coroutine_create(bdrv_get_block_status_above_co_entry, 1867 &data); 1868 qemu_coroutine_enter(co); 1869 BDRV_POLL_WHILE(bs, !data.done); 1870 } 1871 return data.ret; 1872 } 1873 1874 int64_t bdrv_get_block_status(BlockDriverState *bs, 1875 int64_t sector_num, 1876 int nb_sectors, int *pnum, 1877 BlockDriverState **file) 1878 { 1879 return bdrv_get_block_status_above(bs, backing_bs(bs), 1880 sector_num, nb_sectors, pnum, file); 1881 } 1882 1883 int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, 1884 int nb_sectors, int *pnum) 1885 { 1886 BlockDriverState *file; 1887 int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum, 1888 &file); 1889 if (ret < 0) { 1890 return ret; 1891 } 1892 return !!(ret & BDRV_BLOCK_ALLOCATED); 1893 } 1894 1895 /* 1896 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP] 1897 * 1898 * Return true if the given sector is allocated in any image between 1899 * BASE and TOP (inclusive). BASE can be NULL to check if the given 1900 * sector is allocated in any image of the chain. Return false otherwise. 1901 * 1902 * 'pnum' is set to the number of sectors (including and immediately following 1903 * the specified sector) that are known to be in the same 1904 * allocated/unallocated state. 1905 * 1906 */ 1907 int bdrv_is_allocated_above(BlockDriverState *top, 1908 BlockDriverState *base, 1909 int64_t sector_num, 1910 int nb_sectors, int *pnum) 1911 { 1912 BlockDriverState *intermediate; 1913 int ret, n = nb_sectors; 1914 1915 intermediate = top; 1916 while (intermediate && intermediate != base) { 1917 int pnum_inter; 1918 ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors, 1919 &pnum_inter); 1920 if (ret < 0) { 1921 return ret; 1922 } else if (ret) { 1923 *pnum = pnum_inter; 1924 return 1; 1925 } 1926 1927 /* 1928 * [sector_num, nb_sectors] is unallocated on top but intermediate 1929 * might have 1930 * 1931 * [sector_num+x, nr_sectors] allocated. 1932 */ 1933 if (n > pnum_inter && 1934 (intermediate == top || 1935 sector_num + pnum_inter < intermediate->total_sectors)) { 1936 n = pnum_inter; 1937 } 1938 1939 intermediate = backing_bs(intermediate); 1940 } 1941 1942 *pnum = n; 1943 return 0; 1944 } 1945 1946 typedef struct BdrvVmstateCo { 1947 BlockDriverState *bs; 1948 QEMUIOVector *qiov; 1949 int64_t pos; 1950 bool is_read; 1951 int ret; 1952 } BdrvVmstateCo; 1953 1954 static int coroutine_fn 1955 bdrv_co_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos, 1956 bool is_read) 1957 { 1958 BlockDriver *drv = bs->drv; 1959 1960 if (!drv) { 1961 return -ENOMEDIUM; 1962 } else if (drv->bdrv_load_vmstate) { 1963 return is_read ? drv->bdrv_load_vmstate(bs, qiov, pos) 1964 : drv->bdrv_save_vmstate(bs, qiov, pos); 1965 } else if (bs->file) { 1966 return bdrv_co_rw_vmstate(bs->file->bs, qiov, pos, is_read); 1967 } 1968 1969 return -ENOTSUP; 1970 } 1971 1972 static void coroutine_fn bdrv_co_rw_vmstate_entry(void *opaque) 1973 { 1974 BdrvVmstateCo *co = opaque; 1975 co->ret = bdrv_co_rw_vmstate(co->bs, co->qiov, co->pos, co->is_read); 1976 } 1977 1978 static inline int 1979 bdrv_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos, 1980 bool is_read) 1981 { 1982 if (qemu_in_coroutine()) { 1983 return bdrv_co_rw_vmstate(bs, qiov, pos, is_read); 1984 } else { 1985 BdrvVmstateCo data = { 1986 .bs = bs, 1987 .qiov = qiov, 1988 .pos = pos, 1989 .is_read = is_read, 1990 .ret = -EINPROGRESS, 1991 }; 1992 Coroutine *co = qemu_coroutine_create(bdrv_co_rw_vmstate_entry, &data); 1993 1994 qemu_coroutine_enter(co); 1995 while (data.ret == -EINPROGRESS) { 1996 aio_poll(bdrv_get_aio_context(bs), true); 1997 } 1998 return data.ret; 1999 } 2000 } 2001 2002 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf, 2003 int64_t pos, int size) 2004 { 2005 QEMUIOVector qiov; 2006 struct iovec iov = { 2007 .iov_base = (void *) buf, 2008 .iov_len = size, 2009 }; 2010 int ret; 2011 2012 qemu_iovec_init_external(&qiov, &iov, 1); 2013 2014 ret = bdrv_writev_vmstate(bs, &qiov, pos); 2015 if (ret < 0) { 2016 return ret; 2017 } 2018 2019 return size; 2020 } 2021 2022 int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos) 2023 { 2024 return bdrv_rw_vmstate(bs, qiov, pos, false); 2025 } 2026 2027 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf, 2028 int64_t pos, int size) 2029 { 2030 QEMUIOVector qiov; 2031 struct iovec iov = { 2032 .iov_base = buf, 2033 .iov_len = size, 2034 }; 2035 int ret; 2036 2037 qemu_iovec_init_external(&qiov, &iov, 1); 2038 ret = bdrv_readv_vmstate(bs, &qiov, pos); 2039 if (ret < 0) { 2040 return ret; 2041 } 2042 2043 return size; 2044 } 2045 2046 int bdrv_readv_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos) 2047 { 2048 return bdrv_rw_vmstate(bs, qiov, pos, true); 2049 } 2050 2051 /**************************************************************/ 2052 /* async I/Os */ 2053 2054 BlockAIOCB *bdrv_aio_readv(BdrvChild *child, int64_t sector_num, 2055 QEMUIOVector *qiov, int nb_sectors, 2056 BlockCompletionFunc *cb, void *opaque) 2057 { 2058 trace_bdrv_aio_readv(child->bs, sector_num, nb_sectors, opaque); 2059 2060 assert(nb_sectors << BDRV_SECTOR_BITS == qiov->size); 2061 return bdrv_co_aio_prw_vector(child, sector_num << BDRV_SECTOR_BITS, qiov, 2062 0, cb, opaque, false); 2063 } 2064 2065 BlockAIOCB *bdrv_aio_writev(BdrvChild *child, int64_t sector_num, 2066 QEMUIOVector *qiov, int nb_sectors, 2067 BlockCompletionFunc *cb, void *opaque) 2068 { 2069 trace_bdrv_aio_writev(child->bs, sector_num, nb_sectors, opaque); 2070 2071 assert(nb_sectors << BDRV_SECTOR_BITS == qiov->size); 2072 return bdrv_co_aio_prw_vector(child, sector_num << BDRV_SECTOR_BITS, qiov, 2073 0, cb, opaque, true); 2074 } 2075 2076 void bdrv_aio_cancel(BlockAIOCB *acb) 2077 { 2078 qemu_aio_ref(acb); 2079 bdrv_aio_cancel_async(acb); 2080 while (acb->refcnt > 1) { 2081 if (acb->aiocb_info->get_aio_context) { 2082 aio_poll(acb->aiocb_info->get_aio_context(acb), true); 2083 } else if (acb->bs) { 2084 aio_poll(bdrv_get_aio_context(acb->bs), true); 2085 } else { 2086 abort(); 2087 } 2088 } 2089 qemu_aio_unref(acb); 2090 } 2091 2092 /* Async version of aio cancel. The caller is not blocked if the acb implements 2093 * cancel_async, otherwise we do nothing and let the request normally complete. 2094 * In either case the completion callback must be called. */ 2095 void bdrv_aio_cancel_async(BlockAIOCB *acb) 2096 { 2097 if (acb->aiocb_info->cancel_async) { 2098 acb->aiocb_info->cancel_async(acb); 2099 } 2100 } 2101 2102 /**************************************************************/ 2103 /* async block device emulation */ 2104 2105 typedef struct BlockRequest { 2106 union { 2107 /* Used during read, write, trim */ 2108 struct { 2109 int64_t offset; 2110 int bytes; 2111 int flags; 2112 QEMUIOVector *qiov; 2113 }; 2114 /* Used during ioctl */ 2115 struct { 2116 int req; 2117 void *buf; 2118 }; 2119 }; 2120 BlockCompletionFunc *cb; 2121 void *opaque; 2122 2123 int error; 2124 } BlockRequest; 2125 2126 typedef struct BlockAIOCBCoroutine { 2127 BlockAIOCB common; 2128 BdrvChild *child; 2129 BlockRequest req; 2130 bool is_write; 2131 bool need_bh; 2132 bool *done; 2133 } BlockAIOCBCoroutine; 2134 2135 static const AIOCBInfo bdrv_em_co_aiocb_info = { 2136 .aiocb_size = sizeof(BlockAIOCBCoroutine), 2137 }; 2138 2139 static void bdrv_co_complete(BlockAIOCBCoroutine *acb) 2140 { 2141 if (!acb->need_bh) { 2142 bdrv_dec_in_flight(acb->common.bs); 2143 acb->common.cb(acb->common.opaque, acb->req.error); 2144 qemu_aio_unref(acb); 2145 } 2146 } 2147 2148 static void bdrv_co_em_bh(void *opaque) 2149 { 2150 BlockAIOCBCoroutine *acb = opaque; 2151 2152 assert(!acb->need_bh); 2153 bdrv_co_complete(acb); 2154 } 2155 2156 static void bdrv_co_maybe_schedule_bh(BlockAIOCBCoroutine *acb) 2157 { 2158 acb->need_bh = false; 2159 if (acb->req.error != -EINPROGRESS) { 2160 BlockDriverState *bs = acb->common.bs; 2161 2162 aio_bh_schedule_oneshot(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb); 2163 } 2164 } 2165 2166 /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */ 2167 static void coroutine_fn bdrv_co_do_rw(void *opaque) 2168 { 2169 BlockAIOCBCoroutine *acb = opaque; 2170 2171 if (!acb->is_write) { 2172 acb->req.error = bdrv_co_preadv(acb->child, acb->req.offset, 2173 acb->req.qiov->size, acb->req.qiov, acb->req.flags); 2174 } else { 2175 acb->req.error = bdrv_co_pwritev(acb->child, acb->req.offset, 2176 acb->req.qiov->size, acb->req.qiov, acb->req.flags); 2177 } 2178 2179 bdrv_co_complete(acb); 2180 } 2181 2182 static BlockAIOCB *bdrv_co_aio_prw_vector(BdrvChild *child, 2183 int64_t offset, 2184 QEMUIOVector *qiov, 2185 BdrvRequestFlags flags, 2186 BlockCompletionFunc *cb, 2187 void *opaque, 2188 bool is_write) 2189 { 2190 Coroutine *co; 2191 BlockAIOCBCoroutine *acb; 2192 2193 /* Matched by bdrv_co_complete's bdrv_dec_in_flight. */ 2194 bdrv_inc_in_flight(child->bs); 2195 2196 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, child->bs, cb, opaque); 2197 acb->child = child; 2198 acb->need_bh = true; 2199 acb->req.error = -EINPROGRESS; 2200 acb->req.offset = offset; 2201 acb->req.qiov = qiov; 2202 acb->req.flags = flags; 2203 acb->is_write = is_write; 2204 2205 co = qemu_coroutine_create(bdrv_co_do_rw, acb); 2206 qemu_coroutine_enter(co); 2207 2208 bdrv_co_maybe_schedule_bh(acb); 2209 return &acb->common; 2210 } 2211 2212 static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque) 2213 { 2214 BlockAIOCBCoroutine *acb = opaque; 2215 BlockDriverState *bs = acb->common.bs; 2216 2217 acb->req.error = bdrv_co_flush(bs); 2218 bdrv_co_complete(acb); 2219 } 2220 2221 BlockAIOCB *bdrv_aio_flush(BlockDriverState *bs, 2222 BlockCompletionFunc *cb, void *opaque) 2223 { 2224 trace_bdrv_aio_flush(bs, opaque); 2225 2226 Coroutine *co; 2227 BlockAIOCBCoroutine *acb; 2228 2229 /* Matched by bdrv_co_complete's bdrv_dec_in_flight. */ 2230 bdrv_inc_in_flight(bs); 2231 2232 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque); 2233 acb->need_bh = true; 2234 acb->req.error = -EINPROGRESS; 2235 2236 co = qemu_coroutine_create(bdrv_aio_flush_co_entry, acb); 2237 qemu_coroutine_enter(co); 2238 2239 bdrv_co_maybe_schedule_bh(acb); 2240 return &acb->common; 2241 } 2242 2243 void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs, 2244 BlockCompletionFunc *cb, void *opaque) 2245 { 2246 BlockAIOCB *acb; 2247 2248 acb = g_malloc(aiocb_info->aiocb_size); 2249 acb->aiocb_info = aiocb_info; 2250 acb->bs = bs; 2251 acb->cb = cb; 2252 acb->opaque = opaque; 2253 acb->refcnt = 1; 2254 return acb; 2255 } 2256 2257 void qemu_aio_ref(void *p) 2258 { 2259 BlockAIOCB *acb = p; 2260 acb->refcnt++; 2261 } 2262 2263 void qemu_aio_unref(void *p) 2264 { 2265 BlockAIOCB *acb = p; 2266 assert(acb->refcnt > 0); 2267 if (--acb->refcnt == 0) { 2268 g_free(acb); 2269 } 2270 } 2271 2272 /**************************************************************/ 2273 /* Coroutine block device emulation */ 2274 2275 typedef struct FlushCo { 2276 BlockDriverState *bs; 2277 int ret; 2278 } FlushCo; 2279 2280 2281 static void coroutine_fn bdrv_flush_co_entry(void *opaque) 2282 { 2283 FlushCo *rwco = opaque; 2284 2285 rwco->ret = bdrv_co_flush(rwco->bs); 2286 } 2287 2288 int coroutine_fn bdrv_co_flush(BlockDriverState *bs) 2289 { 2290 int ret; 2291 2292 if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs) || 2293 bdrv_is_sg(bs)) { 2294 return 0; 2295 } 2296 2297 bdrv_inc_in_flight(bs); 2298 2299 int current_gen = bs->write_gen; 2300 2301 /* Wait until any previous flushes are completed */ 2302 while (bs->active_flush_req) { 2303 qemu_co_queue_wait(&bs->flush_queue); 2304 } 2305 2306 bs->active_flush_req = true; 2307 2308 /* Write back all layers by calling one driver function */ 2309 if (bs->drv->bdrv_co_flush) { 2310 ret = bs->drv->bdrv_co_flush(bs); 2311 goto out; 2312 } 2313 2314 /* Write back cached data to the OS even with cache=unsafe */ 2315 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS); 2316 if (bs->drv->bdrv_co_flush_to_os) { 2317 ret = bs->drv->bdrv_co_flush_to_os(bs); 2318 if (ret < 0) { 2319 goto out; 2320 } 2321 } 2322 2323 /* But don't actually force it to the disk with cache=unsafe */ 2324 if (bs->open_flags & BDRV_O_NO_FLUSH) { 2325 goto flush_parent; 2326 } 2327 2328 /* Check if we really need to flush anything */ 2329 if (bs->flushed_gen == current_gen) { 2330 goto flush_parent; 2331 } 2332 2333 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK); 2334 if (bs->drv->bdrv_co_flush_to_disk) { 2335 ret = bs->drv->bdrv_co_flush_to_disk(bs); 2336 } else if (bs->drv->bdrv_aio_flush) { 2337 BlockAIOCB *acb; 2338 CoroutineIOCompletion co = { 2339 .coroutine = qemu_coroutine_self(), 2340 }; 2341 2342 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co); 2343 if (acb == NULL) { 2344 ret = -EIO; 2345 } else { 2346 qemu_coroutine_yield(); 2347 ret = co.ret; 2348 } 2349 } else { 2350 /* 2351 * Some block drivers always operate in either writethrough or unsafe 2352 * mode and don't support bdrv_flush therefore. Usually qemu doesn't 2353 * know how the server works (because the behaviour is hardcoded or 2354 * depends on server-side configuration), so we can't ensure that 2355 * everything is safe on disk. Returning an error doesn't work because 2356 * that would break guests even if the server operates in writethrough 2357 * mode. 2358 * 2359 * Let's hope the user knows what he's doing. 2360 */ 2361 ret = 0; 2362 } 2363 2364 if (ret < 0) { 2365 goto out; 2366 } 2367 2368 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH 2369 * in the case of cache=unsafe, so there are no useless flushes. 2370 */ 2371 flush_parent: 2372 ret = bs->file ? bdrv_co_flush(bs->file->bs) : 0; 2373 out: 2374 /* Notify any pending flushes that we have completed */ 2375 bs->flushed_gen = current_gen; 2376 bs->active_flush_req = false; 2377 /* Return value is ignored - it's ok if wait queue is empty */ 2378 qemu_co_queue_next(&bs->flush_queue); 2379 2380 bdrv_dec_in_flight(bs); 2381 return ret; 2382 } 2383 2384 int bdrv_flush(BlockDriverState *bs) 2385 { 2386 Coroutine *co; 2387 FlushCo flush_co = { 2388 .bs = bs, 2389 .ret = NOT_DONE, 2390 }; 2391 2392 if (qemu_in_coroutine()) { 2393 /* Fast-path if already in coroutine context */ 2394 bdrv_flush_co_entry(&flush_co); 2395 } else { 2396 co = qemu_coroutine_create(bdrv_flush_co_entry, &flush_co); 2397 qemu_coroutine_enter(co); 2398 BDRV_POLL_WHILE(bs, flush_co.ret == NOT_DONE); 2399 } 2400 2401 return flush_co.ret; 2402 } 2403 2404 typedef struct DiscardCo { 2405 BlockDriverState *bs; 2406 int64_t offset; 2407 int count; 2408 int ret; 2409 } DiscardCo; 2410 static void coroutine_fn bdrv_pdiscard_co_entry(void *opaque) 2411 { 2412 DiscardCo *rwco = opaque; 2413 2414 rwco->ret = bdrv_co_pdiscard(rwco->bs, rwco->offset, rwco->count); 2415 } 2416 2417 int coroutine_fn bdrv_co_pdiscard(BlockDriverState *bs, int64_t offset, 2418 int count) 2419 { 2420 BdrvTrackedRequest req; 2421 int max_pdiscard, ret; 2422 int head, align; 2423 2424 if (!bs->drv) { 2425 return -ENOMEDIUM; 2426 } 2427 2428 ret = bdrv_check_byte_request(bs, offset, count); 2429 if (ret < 0) { 2430 return ret; 2431 } else if (bs->read_only) { 2432 return -EPERM; 2433 } 2434 assert(!(bs->open_flags & BDRV_O_INACTIVE)); 2435 2436 /* Do nothing if disabled. */ 2437 if (!(bs->open_flags & BDRV_O_UNMAP)) { 2438 return 0; 2439 } 2440 2441 if (!bs->drv->bdrv_co_pdiscard && !bs->drv->bdrv_aio_pdiscard) { 2442 return 0; 2443 } 2444 2445 /* Discard is advisory, so ignore any unaligned head or tail */ 2446 align = MAX(bs->bl.pdiscard_alignment, bs->bl.request_alignment); 2447 assert(align % bs->bl.request_alignment == 0); 2448 head = offset % align; 2449 if (head) { 2450 head = MIN(count, align - head); 2451 count -= head; 2452 offset += head; 2453 } 2454 count = QEMU_ALIGN_DOWN(count, align); 2455 if (!count) { 2456 return 0; 2457 } 2458 2459 bdrv_inc_in_flight(bs); 2460 tracked_request_begin(&req, bs, offset, count, BDRV_TRACKED_DISCARD); 2461 2462 ret = notifier_with_return_list_notify(&bs->before_write_notifiers, &req); 2463 if (ret < 0) { 2464 goto out; 2465 } 2466 2467 max_pdiscard = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_pdiscard, INT_MAX), 2468 align); 2469 assert(max_pdiscard); 2470 2471 while (count > 0) { 2472 int ret; 2473 int num = MIN(count, max_pdiscard); 2474 2475 if (bs->drv->bdrv_co_pdiscard) { 2476 ret = bs->drv->bdrv_co_pdiscard(bs, offset, num); 2477 } else { 2478 BlockAIOCB *acb; 2479 CoroutineIOCompletion co = { 2480 .coroutine = qemu_coroutine_self(), 2481 }; 2482 2483 acb = bs->drv->bdrv_aio_pdiscard(bs, offset, num, 2484 bdrv_co_io_em_complete, &co); 2485 if (acb == NULL) { 2486 ret = -EIO; 2487 goto out; 2488 } else { 2489 qemu_coroutine_yield(); 2490 ret = co.ret; 2491 } 2492 } 2493 if (ret && ret != -ENOTSUP) { 2494 goto out; 2495 } 2496 2497 offset += num; 2498 count -= num; 2499 } 2500 ret = 0; 2501 out: 2502 ++bs->write_gen; 2503 bdrv_set_dirty(bs, req.offset >> BDRV_SECTOR_BITS, 2504 req.bytes >> BDRV_SECTOR_BITS); 2505 tracked_request_end(&req); 2506 bdrv_dec_in_flight(bs); 2507 return ret; 2508 } 2509 2510 int bdrv_pdiscard(BlockDriverState *bs, int64_t offset, int count) 2511 { 2512 Coroutine *co; 2513 DiscardCo rwco = { 2514 .bs = bs, 2515 .offset = offset, 2516 .count = count, 2517 .ret = NOT_DONE, 2518 }; 2519 2520 if (qemu_in_coroutine()) { 2521 /* Fast-path if already in coroutine context */ 2522 bdrv_pdiscard_co_entry(&rwco); 2523 } else { 2524 co = qemu_coroutine_create(bdrv_pdiscard_co_entry, &rwco); 2525 qemu_coroutine_enter(co); 2526 BDRV_POLL_WHILE(bs, rwco.ret == NOT_DONE); 2527 } 2528 2529 return rwco.ret; 2530 } 2531 2532 int bdrv_co_ioctl(BlockDriverState *bs, int req, void *buf) 2533 { 2534 BlockDriver *drv = bs->drv; 2535 CoroutineIOCompletion co = { 2536 .coroutine = qemu_coroutine_self(), 2537 }; 2538 BlockAIOCB *acb; 2539 2540 bdrv_inc_in_flight(bs); 2541 if (!drv || (!drv->bdrv_aio_ioctl && !drv->bdrv_co_ioctl)) { 2542 co.ret = -ENOTSUP; 2543 goto out; 2544 } 2545 2546 if (drv->bdrv_co_ioctl) { 2547 co.ret = drv->bdrv_co_ioctl(bs, req, buf); 2548 } else { 2549 acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co); 2550 if (!acb) { 2551 co.ret = -ENOTSUP; 2552 goto out; 2553 } 2554 qemu_coroutine_yield(); 2555 } 2556 out: 2557 bdrv_dec_in_flight(bs); 2558 return co.ret; 2559 } 2560 2561 void *qemu_blockalign(BlockDriverState *bs, size_t size) 2562 { 2563 return qemu_memalign(bdrv_opt_mem_align(bs), size); 2564 } 2565 2566 void *qemu_blockalign0(BlockDriverState *bs, size_t size) 2567 { 2568 return memset(qemu_blockalign(bs, size), 0, size); 2569 } 2570 2571 void *qemu_try_blockalign(BlockDriverState *bs, size_t size) 2572 { 2573 size_t align = bdrv_opt_mem_align(bs); 2574 2575 /* Ensure that NULL is never returned on success */ 2576 assert(align > 0); 2577 if (size == 0) { 2578 size = align; 2579 } 2580 2581 return qemu_try_memalign(align, size); 2582 } 2583 2584 void *qemu_try_blockalign0(BlockDriverState *bs, size_t size) 2585 { 2586 void *mem = qemu_try_blockalign(bs, size); 2587 2588 if (mem) { 2589 memset(mem, 0, size); 2590 } 2591 2592 return mem; 2593 } 2594 2595 /* 2596 * Check if all memory in this vector is sector aligned. 2597 */ 2598 bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov) 2599 { 2600 int i; 2601 size_t alignment = bdrv_min_mem_align(bs); 2602 2603 for (i = 0; i < qiov->niov; i++) { 2604 if ((uintptr_t) qiov->iov[i].iov_base % alignment) { 2605 return false; 2606 } 2607 if (qiov->iov[i].iov_len % alignment) { 2608 return false; 2609 } 2610 } 2611 2612 return true; 2613 } 2614 2615 void bdrv_add_before_write_notifier(BlockDriverState *bs, 2616 NotifierWithReturn *notifier) 2617 { 2618 notifier_with_return_list_add(&bs->before_write_notifiers, notifier); 2619 } 2620 2621 void bdrv_io_plug(BlockDriverState *bs) 2622 { 2623 BdrvChild *child; 2624 2625 QLIST_FOREACH(child, &bs->children, next) { 2626 bdrv_io_plug(child->bs); 2627 } 2628 2629 if (bs->io_plugged++ == 0 && bs->io_plug_disabled == 0) { 2630 BlockDriver *drv = bs->drv; 2631 if (drv && drv->bdrv_io_plug) { 2632 drv->bdrv_io_plug(bs); 2633 } 2634 } 2635 } 2636 2637 void bdrv_io_unplug(BlockDriverState *bs) 2638 { 2639 BdrvChild *child; 2640 2641 assert(bs->io_plugged); 2642 if (--bs->io_plugged == 0 && bs->io_plug_disabled == 0) { 2643 BlockDriver *drv = bs->drv; 2644 if (drv && drv->bdrv_io_unplug) { 2645 drv->bdrv_io_unplug(bs); 2646 } 2647 } 2648 2649 QLIST_FOREACH(child, &bs->children, next) { 2650 bdrv_io_unplug(child->bs); 2651 } 2652 } 2653 2654 void bdrv_io_unplugged_begin(BlockDriverState *bs) 2655 { 2656 BdrvChild *child; 2657 2658 if (bs->io_plug_disabled++ == 0 && bs->io_plugged > 0) { 2659 BlockDriver *drv = bs->drv; 2660 if (drv && drv->bdrv_io_unplug) { 2661 drv->bdrv_io_unplug(bs); 2662 } 2663 } 2664 2665 QLIST_FOREACH(child, &bs->children, next) { 2666 bdrv_io_unplugged_begin(child->bs); 2667 } 2668 } 2669 2670 void bdrv_io_unplugged_end(BlockDriverState *bs) 2671 { 2672 BdrvChild *child; 2673 2674 assert(bs->io_plug_disabled); 2675 QLIST_FOREACH(child, &bs->children, next) { 2676 bdrv_io_unplugged_end(child->bs); 2677 } 2678 2679 if (--bs->io_plug_disabled == 0 && bs->io_plugged > 0) { 2680 BlockDriver *drv = bs->drv; 2681 if (drv && drv->bdrv_io_plug) { 2682 drv->bdrv_io_plug(bs); 2683 } 2684 } 2685 } 2686