virtio-9p: convert VMSTATE_VIRTIO_DEVICE
[qemu/ar7.git] / block / io.c
blob57a2eeb512f69ca69b2d216e4c1000e7c7830b1f
1 /*
2 * Block layer I/O functions
4 * Copyright (c) 2003 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
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"
34 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
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);
47 static void bdrv_parent_drained_begin(BlockDriverState *bs)
49 BdrvChild *c;
51 QLIST_FOREACH(c, &bs->parents, next_parent) {
52 if (c->role->drained_begin) {
53 c->role->drained_begin(c);
58 static void bdrv_parent_drained_end(BlockDriverState *bs)
60 BdrvChild *c;
62 QLIST_FOREACH(c, &bs->parents, next_parent) {
63 if (c->role->drained_end) {
64 c->role->drained_end(c);
69 static void bdrv_merge_limits(BlockLimits *dst, const BlockLimits *src)
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);
80 void bdrv_refresh_limits(BlockDriverState *bs, Error **errp)
82 BlockDriver *drv = bs->drv;
83 Error *local_err = NULL;
85 memset(&bs->bl, 0, sizeof(bs->bl));
87 if (!drv) {
88 return;
91 /* Default alignment based on whether driver has byte interface */
92 bs->bl.request_alignment = drv->bdrv_co_preadv ? 1 : 512;
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;
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();
106 /* Safe default since most protocols use readv()/writev()/etc */
107 bs->bl.max_iov = IOV_MAX;
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;
116 bdrv_merge_limits(&bs->bl, &bs->backing->bs->bl);
119 /* Then let the driver override it */
120 if (drv->bdrv_refresh_limits) {
121 drv->bdrv_refresh_limits(bs, errp);
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.
130 void bdrv_enable_copy_on_read(BlockDriverState *bs)
132 bs->copy_on_read++;
135 void bdrv_disable_copy_on_read(BlockDriverState *bs)
137 assert(bs->copy_on_read > 0);
138 bs->copy_on_read--;
141 /* Check if any requests are in-flight (including throttled requests) */
142 bool bdrv_requests_pending(BlockDriverState *bs)
144 BdrvChild *child;
146 if (!QLIST_EMPTY(&bs->tracked_requests)) {
147 return true;
150 QLIST_FOREACH(child, &bs->children, next) {
151 if (bdrv_requests_pending(child->bs)) {
152 return true;
156 return false;
159 static void bdrv_drain_recurse(BlockDriverState *bs)
161 BdrvChild *child;
163 if (bs->drv && bs->drv->bdrv_drain) {
164 bs->drv->bdrv_drain(bs);
166 QLIST_FOREACH(child, &bs->children, next) {
167 bdrv_drain_recurse(child->bs);
171 typedef struct {
172 Coroutine *co;
173 BlockDriverState *bs;
174 QEMUBH *bh;
175 bool done;
176 } BdrvCoDrainData;
178 static void bdrv_drain_poll(BlockDriverState *bs)
180 bool busy = true;
182 while (busy) {
183 /* Keep iterating */
184 busy = bdrv_requests_pending(bs);
185 busy |= aio_poll(bdrv_get_aio_context(bs), busy);
189 static void bdrv_co_drain_bh_cb(void *opaque)
191 BdrvCoDrainData *data = opaque;
192 Coroutine *co = data->co;
194 qemu_bh_delete(data->bh);
195 bdrv_drain_poll(data->bs);
196 data->done = true;
197 qemu_coroutine_enter(co);
200 static void coroutine_fn bdrv_co_yield_to_drain(BlockDriverState *bs)
202 BdrvCoDrainData data;
204 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
205 * other coroutines run if they were queued from
206 * qemu_co_queue_run_restart(). */
208 assert(qemu_in_coroutine());
209 data = (BdrvCoDrainData) {
210 .co = qemu_coroutine_self(),
211 .bs = bs,
212 .done = false,
213 .bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_drain_bh_cb, &data),
215 qemu_bh_schedule(data.bh);
217 qemu_coroutine_yield();
218 /* If we are resumed from some other event (such as an aio completion or a
219 * timer callback), it is a bug in the caller that should be fixed. */
220 assert(data.done);
223 void bdrv_drained_begin(BlockDriverState *bs)
225 if (!bs->quiesce_counter++) {
226 aio_disable_external(bdrv_get_aio_context(bs));
227 bdrv_parent_drained_begin(bs);
230 bdrv_io_unplugged_begin(bs);
231 bdrv_drain_recurse(bs);
232 if (qemu_in_coroutine()) {
233 bdrv_co_yield_to_drain(bs);
234 } else {
235 bdrv_drain_poll(bs);
237 bdrv_io_unplugged_end(bs);
240 void bdrv_drained_end(BlockDriverState *bs)
242 assert(bs->quiesce_counter > 0);
243 if (--bs->quiesce_counter > 0) {
244 return;
247 bdrv_parent_drained_end(bs);
248 aio_enable_external(bdrv_get_aio_context(bs));
252 * Wait for pending requests to complete on a single BlockDriverState subtree,
253 * and suspend block driver's internal I/O until next request arrives.
255 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
256 * AioContext.
258 * Only this BlockDriverState's AioContext is run, so in-flight requests must
259 * not depend on events in other AioContexts. In that case, use
260 * bdrv_drain_all() instead.
262 void coroutine_fn bdrv_co_drain(BlockDriverState *bs)
264 assert(qemu_in_coroutine());
265 bdrv_drained_begin(bs);
266 bdrv_drained_end(bs);
269 void bdrv_drain(BlockDriverState *bs)
271 bdrv_drained_begin(bs);
272 bdrv_drained_end(bs);
276 * Wait for pending requests to complete across all BlockDriverStates
278 * This function does not flush data to disk, use bdrv_flush_all() for that
279 * after calling this function.
281 void bdrv_drain_all(void)
283 /* Always run first iteration so any pending completion BHs run */
284 bool busy = true;
285 BlockDriverState *bs;
286 BdrvNextIterator it;
287 BlockJob *job = NULL;
288 GSList *aio_ctxs = NULL, *ctx;
290 while ((job = block_job_next(job))) {
291 AioContext *aio_context = blk_get_aio_context(job->blk);
293 aio_context_acquire(aio_context);
294 block_job_pause(job);
295 aio_context_release(aio_context);
298 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
299 AioContext *aio_context = bdrv_get_aio_context(bs);
301 aio_context_acquire(aio_context);
302 bdrv_parent_drained_begin(bs);
303 bdrv_io_unplugged_begin(bs);
304 bdrv_drain_recurse(bs);
305 aio_context_release(aio_context);
307 if (!g_slist_find(aio_ctxs, aio_context)) {
308 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
312 /* Note that completion of an asynchronous I/O operation can trigger any
313 * number of other I/O operations on other devices---for example a
314 * coroutine can submit an I/O request to another device in response to
315 * request completion. Therefore we must keep looping until there was no
316 * more activity rather than simply draining each device independently.
318 while (busy) {
319 busy = false;
321 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
322 AioContext *aio_context = ctx->data;
324 aio_context_acquire(aio_context);
325 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
326 if (aio_context == bdrv_get_aio_context(bs)) {
327 if (bdrv_requests_pending(bs)) {
328 busy = true;
329 aio_poll(aio_context, busy);
333 busy |= aio_poll(aio_context, false);
334 aio_context_release(aio_context);
338 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
339 AioContext *aio_context = bdrv_get_aio_context(bs);
341 aio_context_acquire(aio_context);
342 bdrv_io_unplugged_end(bs);
343 bdrv_parent_drained_end(bs);
344 aio_context_release(aio_context);
346 g_slist_free(aio_ctxs);
348 job = NULL;
349 while ((job = block_job_next(job))) {
350 AioContext *aio_context = blk_get_aio_context(job->blk);
352 aio_context_acquire(aio_context);
353 block_job_resume(job);
354 aio_context_release(aio_context);
359 * Remove an active request from the tracked requests list
361 * This function should be called when a tracked request is completing.
363 static void tracked_request_end(BdrvTrackedRequest *req)
365 if (req->serialising) {
366 req->bs->serialising_in_flight--;
369 QLIST_REMOVE(req, list);
370 qemu_co_queue_restart_all(&req->wait_queue);
374 * Add an active request to the tracked requests list
376 static void tracked_request_begin(BdrvTrackedRequest *req,
377 BlockDriverState *bs,
378 int64_t offset,
379 unsigned int bytes,
380 enum BdrvTrackedRequestType type)
382 *req = (BdrvTrackedRequest){
383 .bs = bs,
384 .offset = offset,
385 .bytes = bytes,
386 .type = type,
387 .co = qemu_coroutine_self(),
388 .serialising = false,
389 .overlap_offset = offset,
390 .overlap_bytes = bytes,
393 qemu_co_queue_init(&req->wait_queue);
395 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
398 static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
400 int64_t overlap_offset = req->offset & ~(align - 1);
401 unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
402 - overlap_offset;
404 if (!req->serialising) {
405 req->bs->serialising_in_flight++;
406 req->serialising = true;
409 req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
410 req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
414 * Round a region to cluster boundaries (sector-based)
416 void bdrv_round_sectors_to_clusters(BlockDriverState *bs,
417 int64_t sector_num, int nb_sectors,
418 int64_t *cluster_sector_num,
419 int *cluster_nb_sectors)
421 BlockDriverInfo bdi;
423 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
424 *cluster_sector_num = sector_num;
425 *cluster_nb_sectors = nb_sectors;
426 } else {
427 int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
428 *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
429 *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
430 nb_sectors, c);
435 * Round a region to cluster boundaries
437 void bdrv_round_to_clusters(BlockDriverState *bs,
438 int64_t offset, unsigned int bytes,
439 int64_t *cluster_offset,
440 unsigned int *cluster_bytes)
442 BlockDriverInfo bdi;
444 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
445 *cluster_offset = offset;
446 *cluster_bytes = bytes;
447 } else {
448 int64_t c = bdi.cluster_size;
449 *cluster_offset = QEMU_ALIGN_DOWN(offset, c);
450 *cluster_bytes = QEMU_ALIGN_UP(offset - *cluster_offset + bytes, c);
454 static int bdrv_get_cluster_size(BlockDriverState *bs)
456 BlockDriverInfo bdi;
457 int ret;
459 ret = bdrv_get_info(bs, &bdi);
460 if (ret < 0 || bdi.cluster_size == 0) {
461 return bs->bl.request_alignment;
462 } else {
463 return bdi.cluster_size;
467 static bool tracked_request_overlaps(BdrvTrackedRequest *req,
468 int64_t offset, unsigned int bytes)
470 /* aaaa bbbb */
471 if (offset >= req->overlap_offset + req->overlap_bytes) {
472 return false;
474 /* bbbb aaaa */
475 if (req->overlap_offset >= offset + bytes) {
476 return false;
478 return true;
481 static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
483 BlockDriverState *bs = self->bs;
484 BdrvTrackedRequest *req;
485 bool retry;
486 bool waited = false;
488 if (!bs->serialising_in_flight) {
489 return false;
492 do {
493 retry = false;
494 QLIST_FOREACH(req, &bs->tracked_requests, list) {
495 if (req == self || (!req->serialising && !self->serialising)) {
496 continue;
498 if (tracked_request_overlaps(req, self->overlap_offset,
499 self->overlap_bytes))
501 /* Hitting this means there was a reentrant request, for
502 * example, a block driver issuing nested requests. This must
503 * never happen since it means deadlock.
505 assert(qemu_coroutine_self() != req->co);
507 /* If the request is already (indirectly) waiting for us, or
508 * will wait for us as soon as it wakes up, then just go on
509 * (instead of producing a deadlock in the former case). */
510 if (!req->waiting_for) {
511 self->waiting_for = req;
512 qemu_co_queue_wait(&req->wait_queue);
513 self->waiting_for = NULL;
514 retry = true;
515 waited = true;
516 break;
520 } while (retry);
522 return waited;
525 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
526 size_t size)
528 if (size > BDRV_REQUEST_MAX_SECTORS << BDRV_SECTOR_BITS) {
529 return -EIO;
532 if (!bdrv_is_inserted(bs)) {
533 return -ENOMEDIUM;
536 if (offset < 0) {
537 return -EIO;
540 return 0;
543 typedef struct RwCo {
544 BdrvChild *child;
545 int64_t offset;
546 QEMUIOVector *qiov;
547 bool is_write;
548 int ret;
549 BdrvRequestFlags flags;
550 } RwCo;
552 static void coroutine_fn bdrv_rw_co_entry(void *opaque)
554 RwCo *rwco = opaque;
556 if (!rwco->is_write) {
557 rwco->ret = bdrv_co_preadv(rwco->child, rwco->offset,
558 rwco->qiov->size, rwco->qiov,
559 rwco->flags);
560 } else {
561 rwco->ret = bdrv_co_pwritev(rwco->child, rwco->offset,
562 rwco->qiov->size, rwco->qiov,
563 rwco->flags);
568 * Process a vectored synchronous request using coroutines
570 static int bdrv_prwv_co(BdrvChild *child, int64_t offset,
571 QEMUIOVector *qiov, bool is_write,
572 BdrvRequestFlags flags)
574 Coroutine *co;
575 RwCo rwco = {
576 .child = child,
577 .offset = offset,
578 .qiov = qiov,
579 .is_write = is_write,
580 .ret = NOT_DONE,
581 .flags = flags,
584 if (qemu_in_coroutine()) {
585 /* Fast-path if already in coroutine context */
586 bdrv_rw_co_entry(&rwco);
587 } else {
588 AioContext *aio_context = bdrv_get_aio_context(child->bs);
590 co = qemu_coroutine_create(bdrv_rw_co_entry, &rwco);
591 qemu_coroutine_enter(co);
592 while (rwco.ret == NOT_DONE) {
593 aio_poll(aio_context, true);
596 return rwco.ret;
600 * Process a synchronous request using coroutines
602 static int bdrv_rw_co(BdrvChild *child, int64_t sector_num, uint8_t *buf,
603 int nb_sectors, bool is_write, BdrvRequestFlags flags)
605 QEMUIOVector qiov;
606 struct iovec iov = {
607 .iov_base = (void *)buf,
608 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
611 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
612 return -EINVAL;
615 qemu_iovec_init_external(&qiov, &iov, 1);
616 return bdrv_prwv_co(child, sector_num << BDRV_SECTOR_BITS,
617 &qiov, is_write, flags);
620 /* return < 0 if error. See bdrv_write() for the return codes */
621 int bdrv_read(BdrvChild *child, int64_t sector_num,
622 uint8_t *buf, int nb_sectors)
624 return bdrv_rw_co(child, sector_num, buf, nb_sectors, false, 0);
627 /* Return < 0 if error. Important errors are:
628 -EIO generic I/O error (may happen for all errors)
629 -ENOMEDIUM No media inserted.
630 -EINVAL Invalid sector number or nb_sectors
631 -EACCES Trying to write a read-only device
633 int bdrv_write(BdrvChild *child, int64_t sector_num,
634 const uint8_t *buf, int nb_sectors)
636 return bdrv_rw_co(child, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
639 int bdrv_pwrite_zeroes(BdrvChild *child, int64_t offset,
640 int count, BdrvRequestFlags flags)
642 QEMUIOVector qiov;
643 struct iovec iov = {
644 .iov_base = NULL,
645 .iov_len = count,
648 qemu_iovec_init_external(&qiov, &iov, 1);
649 return bdrv_prwv_co(child, offset, &qiov, true,
650 BDRV_REQ_ZERO_WRITE | flags);
654 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
655 * The operation is sped up by checking the block status and only writing
656 * zeroes to the device if they currently do not return zeroes. Optional
657 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
658 * BDRV_REQ_FUA).
660 * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
662 int bdrv_make_zero(BdrvChild *child, BdrvRequestFlags flags)
664 int64_t target_sectors, ret, nb_sectors, sector_num = 0;
665 BlockDriverState *bs = child->bs;
666 BlockDriverState *file;
667 int n;
669 target_sectors = bdrv_nb_sectors(bs);
670 if (target_sectors < 0) {
671 return target_sectors;
674 for (;;) {
675 nb_sectors = MIN(target_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
676 if (nb_sectors <= 0) {
677 return 0;
679 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n, &file);
680 if (ret < 0) {
681 error_report("error getting block status at sector %" PRId64 ": %s",
682 sector_num, strerror(-ret));
683 return ret;
685 if (ret & BDRV_BLOCK_ZERO) {
686 sector_num += n;
687 continue;
689 ret = bdrv_pwrite_zeroes(child, sector_num << BDRV_SECTOR_BITS,
690 n << BDRV_SECTOR_BITS, flags);
691 if (ret < 0) {
692 error_report("error writing zeroes at sector %" PRId64 ": %s",
693 sector_num, strerror(-ret));
694 return ret;
696 sector_num += n;
700 int bdrv_preadv(BdrvChild *child, int64_t offset, QEMUIOVector *qiov)
702 int ret;
704 ret = bdrv_prwv_co(child, offset, qiov, false, 0);
705 if (ret < 0) {
706 return ret;
709 return qiov->size;
712 int bdrv_pread(BdrvChild *child, int64_t offset, void *buf, int bytes)
714 QEMUIOVector qiov;
715 struct iovec iov = {
716 .iov_base = (void *)buf,
717 .iov_len = bytes,
720 if (bytes < 0) {
721 return -EINVAL;
724 qemu_iovec_init_external(&qiov, &iov, 1);
725 return bdrv_preadv(child, offset, &qiov);
728 int bdrv_pwritev(BdrvChild *child, int64_t offset, QEMUIOVector *qiov)
730 int ret;
732 ret = bdrv_prwv_co(child, offset, qiov, true, 0);
733 if (ret < 0) {
734 return ret;
737 return qiov->size;
740 int bdrv_pwrite(BdrvChild *child, int64_t offset, const void *buf, int bytes)
742 QEMUIOVector qiov;
743 struct iovec iov = {
744 .iov_base = (void *) buf,
745 .iov_len = bytes,
748 if (bytes < 0) {
749 return -EINVAL;
752 qemu_iovec_init_external(&qiov, &iov, 1);
753 return bdrv_pwritev(child, offset, &qiov);
757 * Writes to the file and ensures that no writes are reordered across this
758 * request (acts as a barrier)
760 * Returns 0 on success, -errno in error cases.
762 int bdrv_pwrite_sync(BdrvChild *child, int64_t offset,
763 const void *buf, int count)
765 int ret;
767 ret = bdrv_pwrite(child, offset, buf, count);
768 if (ret < 0) {
769 return ret;
772 ret = bdrv_flush(child->bs);
773 if (ret < 0) {
774 return ret;
777 return 0;
780 typedef struct CoroutineIOCompletion {
781 Coroutine *coroutine;
782 int ret;
783 } CoroutineIOCompletion;
785 static void bdrv_co_io_em_complete(void *opaque, int ret)
787 CoroutineIOCompletion *co = opaque;
789 co->ret = ret;
790 qemu_coroutine_enter(co->coroutine);
793 static int coroutine_fn bdrv_driver_preadv(BlockDriverState *bs,
794 uint64_t offset, uint64_t bytes,
795 QEMUIOVector *qiov, int flags)
797 BlockDriver *drv = bs->drv;
798 int64_t sector_num;
799 unsigned int nb_sectors;
801 assert(!(flags & ~BDRV_REQ_MASK));
803 if (drv->bdrv_co_preadv) {
804 return drv->bdrv_co_preadv(bs, offset, bytes, qiov, flags);
807 sector_num = offset >> BDRV_SECTOR_BITS;
808 nb_sectors = bytes >> BDRV_SECTOR_BITS;
810 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
811 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
812 assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);
814 if (drv->bdrv_co_readv) {
815 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
816 } else {
817 BlockAIOCB *acb;
818 CoroutineIOCompletion co = {
819 .coroutine = qemu_coroutine_self(),
822 acb = bs->drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
823 bdrv_co_io_em_complete, &co);
824 if (acb == NULL) {
825 return -EIO;
826 } else {
827 qemu_coroutine_yield();
828 return co.ret;
833 static int coroutine_fn bdrv_driver_pwritev(BlockDriverState *bs,
834 uint64_t offset, uint64_t bytes,
835 QEMUIOVector *qiov, int flags)
837 BlockDriver *drv = bs->drv;
838 int64_t sector_num;
839 unsigned int nb_sectors;
840 int ret;
842 assert(!(flags & ~BDRV_REQ_MASK));
844 if (drv->bdrv_co_pwritev) {
845 ret = drv->bdrv_co_pwritev(bs, offset, bytes, qiov,
846 flags & bs->supported_write_flags);
847 flags &= ~bs->supported_write_flags;
848 goto emulate_flags;
851 sector_num = offset >> BDRV_SECTOR_BITS;
852 nb_sectors = bytes >> BDRV_SECTOR_BITS;
854 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
855 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
856 assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);
858 if (drv->bdrv_co_writev_flags) {
859 ret = drv->bdrv_co_writev_flags(bs, sector_num, nb_sectors, qiov,
860 flags & bs->supported_write_flags);
861 flags &= ~bs->supported_write_flags;
862 } else if (drv->bdrv_co_writev) {
863 assert(!bs->supported_write_flags);
864 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
865 } else {
866 BlockAIOCB *acb;
867 CoroutineIOCompletion co = {
868 .coroutine = qemu_coroutine_self(),
871 acb = bs->drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
872 bdrv_co_io_em_complete, &co);
873 if (acb == NULL) {
874 ret = -EIO;
875 } else {
876 qemu_coroutine_yield();
877 ret = co.ret;
881 emulate_flags:
882 if (ret == 0 && (flags & BDRV_REQ_FUA)) {
883 ret = bdrv_co_flush(bs);
886 return ret;
889 static int coroutine_fn
890 bdrv_driver_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
891 uint64_t bytes, QEMUIOVector *qiov)
893 BlockDriver *drv = bs->drv;
895 if (!drv->bdrv_co_pwritev_compressed) {
896 return -ENOTSUP;
899 return drv->bdrv_co_pwritev_compressed(bs, offset, bytes, qiov);
902 static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
903 int64_t offset, unsigned int bytes, QEMUIOVector *qiov)
905 /* Perform I/O through a temporary buffer so that users who scribble over
906 * their read buffer while the operation is in progress do not end up
907 * modifying the image file. This is critical for zero-copy guest I/O
908 * where anything might happen inside guest memory.
910 void *bounce_buffer;
912 BlockDriver *drv = bs->drv;
913 struct iovec iov;
914 QEMUIOVector bounce_qiov;
915 int64_t cluster_offset;
916 unsigned int cluster_bytes;
917 size_t skip_bytes;
918 int ret;
920 /* Cover entire cluster so no additional backing file I/O is required when
921 * allocating cluster in the image file.
923 bdrv_round_to_clusters(bs, offset, bytes, &cluster_offset, &cluster_bytes);
925 trace_bdrv_co_do_copy_on_readv(bs, offset, bytes,
926 cluster_offset, cluster_bytes);
928 iov.iov_len = cluster_bytes;
929 iov.iov_base = bounce_buffer = qemu_try_blockalign(bs, iov.iov_len);
930 if (bounce_buffer == NULL) {
931 ret = -ENOMEM;
932 goto err;
935 qemu_iovec_init_external(&bounce_qiov, &iov, 1);
937 ret = bdrv_driver_preadv(bs, cluster_offset, cluster_bytes,
938 &bounce_qiov, 0);
939 if (ret < 0) {
940 goto err;
943 if (drv->bdrv_co_pwrite_zeroes &&
944 buffer_is_zero(bounce_buffer, iov.iov_len)) {
945 /* FIXME: Should we (perhaps conditionally) be setting
946 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
947 * that still correctly reads as zero? */
948 ret = bdrv_co_do_pwrite_zeroes(bs, cluster_offset, cluster_bytes, 0);
949 } else {
950 /* This does not change the data on the disk, it is not necessary
951 * to flush even in cache=writethrough mode.
953 ret = bdrv_driver_pwritev(bs, cluster_offset, cluster_bytes,
954 &bounce_qiov, 0);
957 if (ret < 0) {
958 /* It might be okay to ignore write errors for guest requests. If this
959 * is a deliberate copy-on-read then we don't want to ignore the error.
960 * Simply report it in all cases.
962 goto err;
965 skip_bytes = offset - cluster_offset;
966 qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes, bytes);
968 err:
969 qemu_vfree(bounce_buffer);
970 return ret;
974 * Forwards an already correctly aligned request to the BlockDriver. This
975 * handles copy on read, zeroing after EOF, and fragmentation of large
976 * reads; any other features must be implemented by the caller.
978 static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,
979 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
980 int64_t align, QEMUIOVector *qiov, int flags)
982 int64_t total_bytes, max_bytes;
983 int ret = 0;
984 uint64_t bytes_remaining = bytes;
985 int max_transfer;
987 assert(is_power_of_2(align));
988 assert((offset & (align - 1)) == 0);
989 assert((bytes & (align - 1)) == 0);
990 assert(!qiov || bytes == qiov->size);
991 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
992 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
993 align);
995 /* TODO: We would need a per-BDS .supported_read_flags and
996 * potential fallback support, if we ever implement any read flags
997 * to pass through to drivers. For now, there aren't any
998 * passthrough flags. */
999 assert(!(flags & ~(BDRV_REQ_NO_SERIALISING | BDRV_REQ_COPY_ON_READ)));
1001 /* Handle Copy on Read and associated serialisation */
1002 if (flags & BDRV_REQ_COPY_ON_READ) {
1003 /* If we touch the same cluster it counts as an overlap. This
1004 * guarantees that allocating writes will be serialized and not race
1005 * with each other for the same cluster. For example, in copy-on-read
1006 * it ensures that the CoR read and write operations are atomic and
1007 * guest writes cannot interleave between them. */
1008 mark_request_serialising(req, bdrv_get_cluster_size(bs));
1011 if (!(flags & BDRV_REQ_NO_SERIALISING)) {
1012 wait_serialising_requests(req);
1015 if (flags & BDRV_REQ_COPY_ON_READ) {
1016 int64_t start_sector = offset >> BDRV_SECTOR_BITS;
1017 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
1018 unsigned int nb_sectors = end_sector - start_sector;
1019 int pnum;
1021 ret = bdrv_is_allocated(bs, start_sector, nb_sectors, &pnum);
1022 if (ret < 0) {
1023 goto out;
1026 if (!ret || pnum != nb_sectors) {
1027 ret = bdrv_co_do_copy_on_readv(bs, offset, bytes, qiov);
1028 goto out;
1032 /* Forward the request to the BlockDriver, possibly fragmenting it */
1033 total_bytes = bdrv_getlength(bs);
1034 if (total_bytes < 0) {
1035 ret = total_bytes;
1036 goto out;
1039 max_bytes = ROUND_UP(MAX(0, total_bytes - offset), align);
1040 if (bytes <= max_bytes && bytes <= max_transfer) {
1041 ret = bdrv_driver_preadv(bs, offset, bytes, qiov, 0);
1042 goto out;
1045 while (bytes_remaining) {
1046 int num;
1048 if (max_bytes) {
1049 QEMUIOVector local_qiov;
1051 num = MIN(bytes_remaining, MIN(max_bytes, max_transfer));
1052 assert(num);
1053 qemu_iovec_init(&local_qiov, qiov->niov);
1054 qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num);
1056 ret = bdrv_driver_preadv(bs, offset + bytes - bytes_remaining,
1057 num, &local_qiov, 0);
1058 max_bytes -= num;
1059 qemu_iovec_destroy(&local_qiov);
1060 } else {
1061 num = bytes_remaining;
1062 ret = qemu_iovec_memset(qiov, bytes - bytes_remaining, 0,
1063 bytes_remaining);
1065 if (ret < 0) {
1066 goto out;
1068 bytes_remaining -= num;
1071 out:
1072 return ret < 0 ? ret : 0;
1076 * Handle a read request in coroutine context
1078 int coroutine_fn bdrv_co_preadv(BdrvChild *child,
1079 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1080 BdrvRequestFlags flags)
1082 BlockDriverState *bs = child->bs;
1083 BlockDriver *drv = bs->drv;
1084 BdrvTrackedRequest req;
1086 uint64_t align = bs->bl.request_alignment;
1087 uint8_t *head_buf = NULL;
1088 uint8_t *tail_buf = NULL;
1089 QEMUIOVector local_qiov;
1090 bool use_local_qiov = false;
1091 int ret;
1093 if (!drv) {
1094 return -ENOMEDIUM;
1097 ret = bdrv_check_byte_request(bs, offset, bytes);
1098 if (ret < 0) {
1099 return ret;
1102 /* Don't do copy-on-read if we read data before write operation */
1103 if (bs->copy_on_read && !(flags & BDRV_REQ_NO_SERIALISING)) {
1104 flags |= BDRV_REQ_COPY_ON_READ;
1107 /* Align read if necessary by padding qiov */
1108 if (offset & (align - 1)) {
1109 head_buf = qemu_blockalign(bs, align);
1110 qemu_iovec_init(&local_qiov, qiov->niov + 2);
1111 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
1112 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1113 use_local_qiov = true;
1115 bytes += offset & (align - 1);
1116 offset = offset & ~(align - 1);
1119 if ((offset + bytes) & (align - 1)) {
1120 if (!use_local_qiov) {
1121 qemu_iovec_init(&local_qiov, qiov->niov + 1);
1122 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1123 use_local_qiov = true;
1125 tail_buf = qemu_blockalign(bs, align);
1126 qemu_iovec_add(&local_qiov, tail_buf,
1127 align - ((offset + bytes) & (align - 1)));
1129 bytes = ROUND_UP(bytes, align);
1132 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_READ);
1133 ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align,
1134 use_local_qiov ? &local_qiov : qiov,
1135 flags);
1136 tracked_request_end(&req);
1138 if (use_local_qiov) {
1139 qemu_iovec_destroy(&local_qiov);
1140 qemu_vfree(head_buf);
1141 qemu_vfree(tail_buf);
1144 return ret;
1147 static int coroutine_fn bdrv_co_do_readv(BdrvChild *child,
1148 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
1149 BdrvRequestFlags flags)
1151 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
1152 return -EINVAL;
1155 return bdrv_co_preadv(child, sector_num << BDRV_SECTOR_BITS,
1156 nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
1159 int coroutine_fn bdrv_co_readv(BdrvChild *child, int64_t sector_num,
1160 int nb_sectors, QEMUIOVector *qiov)
1162 trace_bdrv_co_readv(child->bs, sector_num, nb_sectors);
1164 return bdrv_co_do_readv(child, sector_num, nb_sectors, qiov, 0);
1167 /* Maximum buffer for write zeroes fallback, in bytes */
1168 #define MAX_WRITE_ZEROES_BOUNCE_BUFFER (32768 << BDRV_SECTOR_BITS)
1170 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
1171 int64_t offset, int count, BdrvRequestFlags flags)
1173 BlockDriver *drv = bs->drv;
1174 QEMUIOVector qiov;
1175 struct iovec iov = {0};
1176 int ret = 0;
1177 bool need_flush = false;
1178 int head = 0;
1179 int tail = 0;
1181 int max_write_zeroes = MIN_NON_ZERO(bs->bl.max_pwrite_zeroes, INT_MAX);
1182 int alignment = MAX(bs->bl.pwrite_zeroes_alignment,
1183 bs->bl.request_alignment);
1185 assert(alignment % bs->bl.request_alignment == 0);
1186 head = offset % alignment;
1187 tail = (offset + count) % alignment;
1188 max_write_zeroes = QEMU_ALIGN_DOWN(max_write_zeroes, alignment);
1189 assert(max_write_zeroes >= bs->bl.request_alignment);
1191 while (count > 0 && !ret) {
1192 int num = count;
1194 /* Align request. Block drivers can expect the "bulk" of the request
1195 * to be aligned, and that unaligned requests do not cross cluster
1196 * boundaries.
1198 if (head) {
1199 /* Make a small request up to the first aligned sector. */
1200 num = MIN(count, alignment - head);
1201 head = 0;
1202 } else if (tail && num > alignment) {
1203 /* Shorten the request to the last aligned sector. */
1204 num -= tail;
1207 /* limit request size */
1208 if (num > max_write_zeroes) {
1209 num = max_write_zeroes;
1212 ret = -ENOTSUP;
1213 /* First try the efficient write zeroes operation */
1214 if (drv->bdrv_co_pwrite_zeroes) {
1215 ret = drv->bdrv_co_pwrite_zeroes(bs, offset, num,
1216 flags & bs->supported_zero_flags);
1217 if (ret != -ENOTSUP && (flags & BDRV_REQ_FUA) &&
1218 !(bs->supported_zero_flags & BDRV_REQ_FUA)) {
1219 need_flush = true;
1221 } else {
1222 assert(!bs->supported_zero_flags);
1225 if (ret == -ENOTSUP) {
1226 /* Fall back to bounce buffer if write zeroes is unsupported */
1227 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer,
1228 MAX_WRITE_ZEROES_BOUNCE_BUFFER);
1229 BdrvRequestFlags write_flags = flags & ~BDRV_REQ_ZERO_WRITE;
1231 if ((flags & BDRV_REQ_FUA) &&
1232 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1233 /* No need for bdrv_driver_pwrite() to do a fallback
1234 * flush on each chunk; use just one at the end */
1235 write_flags &= ~BDRV_REQ_FUA;
1236 need_flush = true;
1238 num = MIN(num, max_transfer);
1239 iov.iov_len = num;
1240 if (iov.iov_base == NULL) {
1241 iov.iov_base = qemu_try_blockalign(bs, num);
1242 if (iov.iov_base == NULL) {
1243 ret = -ENOMEM;
1244 goto fail;
1246 memset(iov.iov_base, 0, num);
1248 qemu_iovec_init_external(&qiov, &iov, 1);
1250 ret = bdrv_driver_pwritev(bs, offset, num, &qiov, write_flags);
1252 /* Keep bounce buffer around if it is big enough for all
1253 * all future requests.
1255 if (num < max_transfer) {
1256 qemu_vfree(iov.iov_base);
1257 iov.iov_base = NULL;
1261 offset += num;
1262 count -= num;
1265 fail:
1266 if (ret == 0 && need_flush) {
1267 ret = bdrv_co_flush(bs);
1269 qemu_vfree(iov.iov_base);
1270 return ret;
1274 * Forwards an already correctly aligned write request to the BlockDriver,
1275 * after possibly fragmenting it.
1277 static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,
1278 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
1279 int64_t align, QEMUIOVector *qiov, int flags)
1281 BlockDriver *drv = bs->drv;
1282 bool waited;
1283 int ret;
1285 int64_t start_sector = offset >> BDRV_SECTOR_BITS;
1286 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
1287 uint64_t bytes_remaining = bytes;
1288 int max_transfer;
1290 assert(is_power_of_2(align));
1291 assert((offset & (align - 1)) == 0);
1292 assert((bytes & (align - 1)) == 0);
1293 assert(!qiov || bytes == qiov->size);
1294 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1295 assert(!(flags & ~BDRV_REQ_MASK));
1296 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1297 align);
1299 waited = wait_serialising_requests(req);
1300 assert(!waited || !req->serialising);
1301 assert(req->overlap_offset <= offset);
1302 assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
1304 ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
1306 if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
1307 !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_pwrite_zeroes &&
1308 qemu_iovec_is_zero(qiov)) {
1309 flags |= BDRV_REQ_ZERO_WRITE;
1310 if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
1311 flags |= BDRV_REQ_MAY_UNMAP;
1315 if (ret < 0) {
1316 /* Do nothing, write notifier decided to fail this request */
1317 } else if (flags & BDRV_REQ_ZERO_WRITE) {
1318 bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO);
1319 ret = bdrv_co_do_pwrite_zeroes(bs, offset, bytes, flags);
1320 } else if (flags & BDRV_REQ_WRITE_COMPRESSED) {
1321 ret = bdrv_driver_pwritev_compressed(bs, offset, bytes, qiov);
1322 } else if (bytes <= max_transfer) {
1323 bdrv_debug_event(bs, BLKDBG_PWRITEV);
1324 ret = bdrv_driver_pwritev(bs, offset, bytes, qiov, flags);
1325 } else {
1326 bdrv_debug_event(bs, BLKDBG_PWRITEV);
1327 while (bytes_remaining) {
1328 int num = MIN(bytes_remaining, max_transfer);
1329 QEMUIOVector local_qiov;
1330 int local_flags = flags;
1332 assert(num);
1333 if (num < bytes_remaining && (flags & BDRV_REQ_FUA) &&
1334 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1335 /* If FUA is going to be emulated by flush, we only
1336 * need to flush on the last iteration */
1337 local_flags &= ~BDRV_REQ_FUA;
1339 qemu_iovec_init(&local_qiov, qiov->niov);
1340 qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num);
1342 ret = bdrv_driver_pwritev(bs, offset + bytes - bytes_remaining,
1343 num, &local_qiov, local_flags);
1344 qemu_iovec_destroy(&local_qiov);
1345 if (ret < 0) {
1346 break;
1348 bytes_remaining -= num;
1351 bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE);
1353 ++bs->write_gen;
1354 bdrv_set_dirty(bs, start_sector, end_sector - start_sector);
1356 if (bs->wr_highest_offset < offset + bytes) {
1357 bs->wr_highest_offset = offset + bytes;
1360 if (ret >= 0) {
1361 bs->total_sectors = MAX(bs->total_sectors, end_sector);
1362 ret = 0;
1365 return ret;
1368 static int coroutine_fn bdrv_co_do_zero_pwritev(BlockDriverState *bs,
1369 int64_t offset,
1370 unsigned int bytes,
1371 BdrvRequestFlags flags,
1372 BdrvTrackedRequest *req)
1374 uint8_t *buf = NULL;
1375 QEMUIOVector local_qiov;
1376 struct iovec iov;
1377 uint64_t align = bs->bl.request_alignment;
1378 unsigned int head_padding_bytes, tail_padding_bytes;
1379 int ret = 0;
1381 head_padding_bytes = offset & (align - 1);
1382 tail_padding_bytes = align - ((offset + bytes) & (align - 1));
1385 assert(flags & BDRV_REQ_ZERO_WRITE);
1386 if (head_padding_bytes || tail_padding_bytes) {
1387 buf = qemu_blockalign(bs, align);
1388 iov = (struct iovec) {
1389 .iov_base = buf,
1390 .iov_len = align,
1392 qemu_iovec_init_external(&local_qiov, &iov, 1);
1394 if (head_padding_bytes) {
1395 uint64_t zero_bytes = MIN(bytes, align - head_padding_bytes);
1397 /* RMW the unaligned part before head. */
1398 mark_request_serialising(req, align);
1399 wait_serialising_requests(req);
1400 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1401 ret = bdrv_aligned_preadv(bs, req, offset & ~(align - 1), align,
1402 align, &local_qiov, 0);
1403 if (ret < 0) {
1404 goto fail;
1406 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1408 memset(buf + head_padding_bytes, 0, zero_bytes);
1409 ret = bdrv_aligned_pwritev(bs, req, offset & ~(align - 1), align,
1410 align, &local_qiov,
1411 flags & ~BDRV_REQ_ZERO_WRITE);
1412 if (ret < 0) {
1413 goto fail;
1415 offset += zero_bytes;
1416 bytes -= zero_bytes;
1419 assert(!bytes || (offset & (align - 1)) == 0);
1420 if (bytes >= align) {
1421 /* Write the aligned part in the middle. */
1422 uint64_t aligned_bytes = bytes & ~(align - 1);
1423 ret = bdrv_aligned_pwritev(bs, req, offset, aligned_bytes, align,
1424 NULL, flags);
1425 if (ret < 0) {
1426 goto fail;
1428 bytes -= aligned_bytes;
1429 offset += aligned_bytes;
1432 assert(!bytes || (offset & (align - 1)) == 0);
1433 if (bytes) {
1434 assert(align == tail_padding_bytes + bytes);
1435 /* RMW the unaligned part after tail. */
1436 mark_request_serialising(req, align);
1437 wait_serialising_requests(req);
1438 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1439 ret = bdrv_aligned_preadv(bs, req, offset, align,
1440 align, &local_qiov, 0);
1441 if (ret < 0) {
1442 goto fail;
1444 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1446 memset(buf, 0, bytes);
1447 ret = bdrv_aligned_pwritev(bs, req, offset, align, align,
1448 &local_qiov, flags & ~BDRV_REQ_ZERO_WRITE);
1450 fail:
1451 qemu_vfree(buf);
1452 return ret;
1457 * Handle a write request in coroutine context
1459 int coroutine_fn bdrv_co_pwritev(BdrvChild *child,
1460 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1461 BdrvRequestFlags flags)
1463 BlockDriverState *bs = child->bs;
1464 BdrvTrackedRequest req;
1465 uint64_t align = bs->bl.request_alignment;
1466 uint8_t *head_buf = NULL;
1467 uint8_t *tail_buf = NULL;
1468 QEMUIOVector local_qiov;
1469 bool use_local_qiov = false;
1470 int ret;
1472 if (!bs->drv) {
1473 return -ENOMEDIUM;
1475 if (bs->read_only) {
1476 return -EPERM;
1478 assert(!(bs->open_flags & BDRV_O_INACTIVE));
1480 ret = bdrv_check_byte_request(bs, offset, bytes);
1481 if (ret < 0) {
1482 return ret;
1486 * Align write if necessary by performing a read-modify-write cycle.
1487 * Pad qiov with the read parts and be sure to have a tracked request not
1488 * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
1490 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);
1492 if (!qiov) {
1493 ret = bdrv_co_do_zero_pwritev(bs, offset, bytes, flags, &req);
1494 goto out;
1497 if (offset & (align - 1)) {
1498 QEMUIOVector head_qiov;
1499 struct iovec head_iov;
1501 mark_request_serialising(&req, align);
1502 wait_serialising_requests(&req);
1504 head_buf = qemu_blockalign(bs, align);
1505 head_iov = (struct iovec) {
1506 .iov_base = head_buf,
1507 .iov_len = align,
1509 qemu_iovec_init_external(&head_qiov, &head_iov, 1);
1511 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1512 ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align,
1513 align, &head_qiov, 0);
1514 if (ret < 0) {
1515 goto fail;
1517 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1519 qemu_iovec_init(&local_qiov, qiov->niov + 2);
1520 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
1521 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1522 use_local_qiov = true;
1524 bytes += offset & (align - 1);
1525 offset = offset & ~(align - 1);
1527 /* We have read the tail already if the request is smaller
1528 * than one aligned block.
1530 if (bytes < align) {
1531 qemu_iovec_add(&local_qiov, head_buf + bytes, align - bytes);
1532 bytes = align;
1536 if ((offset + bytes) & (align - 1)) {
1537 QEMUIOVector tail_qiov;
1538 struct iovec tail_iov;
1539 size_t tail_bytes;
1540 bool waited;
1542 mark_request_serialising(&req, align);
1543 waited = wait_serialising_requests(&req);
1544 assert(!waited || !use_local_qiov);
1546 tail_buf = qemu_blockalign(bs, align);
1547 tail_iov = (struct iovec) {
1548 .iov_base = tail_buf,
1549 .iov_len = align,
1551 qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);
1553 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1554 ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align,
1555 align, &tail_qiov, 0);
1556 if (ret < 0) {
1557 goto fail;
1559 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1561 if (!use_local_qiov) {
1562 qemu_iovec_init(&local_qiov, qiov->niov + 1);
1563 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1564 use_local_qiov = true;
1567 tail_bytes = (offset + bytes) & (align - 1);
1568 qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
1570 bytes = ROUND_UP(bytes, align);
1573 ret = bdrv_aligned_pwritev(bs, &req, offset, bytes, align,
1574 use_local_qiov ? &local_qiov : qiov,
1575 flags);
1577 fail:
1579 if (use_local_qiov) {
1580 qemu_iovec_destroy(&local_qiov);
1582 qemu_vfree(head_buf);
1583 qemu_vfree(tail_buf);
1584 out:
1585 tracked_request_end(&req);
1586 return ret;
1589 static int coroutine_fn bdrv_co_do_writev(BdrvChild *child,
1590 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
1591 BdrvRequestFlags flags)
1593 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
1594 return -EINVAL;
1597 return bdrv_co_pwritev(child, sector_num << BDRV_SECTOR_BITS,
1598 nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
1601 int coroutine_fn bdrv_co_writev(BdrvChild *child, int64_t sector_num,
1602 int nb_sectors, QEMUIOVector *qiov)
1604 trace_bdrv_co_writev(child->bs, sector_num, nb_sectors);
1606 return bdrv_co_do_writev(child, sector_num, nb_sectors, qiov, 0);
1609 int coroutine_fn bdrv_co_pwrite_zeroes(BdrvChild *child, int64_t offset,
1610 int count, BdrvRequestFlags flags)
1612 trace_bdrv_co_pwrite_zeroes(child->bs, offset, count, flags);
1614 if (!(child->bs->open_flags & BDRV_O_UNMAP)) {
1615 flags &= ~BDRV_REQ_MAY_UNMAP;
1618 return bdrv_co_pwritev(child, offset, count, NULL,
1619 BDRV_REQ_ZERO_WRITE | flags);
1623 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
1625 int bdrv_flush_all(void)
1627 BdrvNextIterator it;
1628 BlockDriverState *bs = NULL;
1629 int result = 0;
1631 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
1632 AioContext *aio_context = bdrv_get_aio_context(bs);
1633 int ret;
1635 aio_context_acquire(aio_context);
1636 ret = bdrv_flush(bs);
1637 if (ret < 0 && !result) {
1638 result = ret;
1640 aio_context_release(aio_context);
1643 return result;
1647 typedef struct BdrvCoGetBlockStatusData {
1648 BlockDriverState *bs;
1649 BlockDriverState *base;
1650 BlockDriverState **file;
1651 int64_t sector_num;
1652 int nb_sectors;
1653 int *pnum;
1654 int64_t ret;
1655 bool done;
1656 } BdrvCoGetBlockStatusData;
1659 * Returns the allocation status of the specified sectors.
1660 * Drivers not implementing the functionality are assumed to not support
1661 * backing files, hence all their sectors are reported as allocated.
1663 * If 'sector_num' is beyond the end of the disk image the return value is 0
1664 * and 'pnum' is set to 0.
1666 * 'pnum' is set to the number of sectors (including and immediately following
1667 * the specified sector) that are known to be in the same
1668 * allocated/unallocated state.
1670 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1671 * beyond the end of the disk image it will be clamped.
1673 * If returned value is positive and BDRV_BLOCK_OFFSET_VALID bit is set, 'file'
1674 * points to the BDS which the sector range is allocated in.
1676 static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
1677 int64_t sector_num,
1678 int nb_sectors, int *pnum,
1679 BlockDriverState **file)
1681 int64_t total_sectors;
1682 int64_t n;
1683 int64_t ret, ret2;
1685 total_sectors = bdrv_nb_sectors(bs);
1686 if (total_sectors < 0) {
1687 return total_sectors;
1690 if (sector_num >= total_sectors) {
1691 *pnum = 0;
1692 return 0;
1695 n = total_sectors - sector_num;
1696 if (n < nb_sectors) {
1697 nb_sectors = n;
1700 if (!bs->drv->bdrv_co_get_block_status) {
1701 *pnum = nb_sectors;
1702 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
1703 if (bs->drv->protocol_name) {
1704 ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
1706 return ret;
1709 *file = NULL;
1710 ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum,
1711 file);
1712 if (ret < 0) {
1713 *pnum = 0;
1714 return ret;
1717 if (ret & BDRV_BLOCK_RAW) {
1718 assert(ret & BDRV_BLOCK_OFFSET_VALID);
1719 return bdrv_get_block_status(bs->file->bs, ret >> BDRV_SECTOR_BITS,
1720 *pnum, pnum, file);
1723 if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
1724 ret |= BDRV_BLOCK_ALLOCATED;
1725 } else {
1726 if (bdrv_unallocated_blocks_are_zero(bs)) {
1727 ret |= BDRV_BLOCK_ZERO;
1728 } else if (bs->backing) {
1729 BlockDriverState *bs2 = bs->backing->bs;
1730 int64_t nb_sectors2 = bdrv_nb_sectors(bs2);
1731 if (nb_sectors2 >= 0 && sector_num >= nb_sectors2) {
1732 ret |= BDRV_BLOCK_ZERO;
1737 if (*file && *file != bs &&
1738 (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
1739 (ret & BDRV_BLOCK_OFFSET_VALID)) {
1740 BlockDriverState *file2;
1741 int file_pnum;
1743 ret2 = bdrv_co_get_block_status(*file, ret >> BDRV_SECTOR_BITS,
1744 *pnum, &file_pnum, &file2);
1745 if (ret2 >= 0) {
1746 /* Ignore errors. This is just providing extra information, it
1747 * is useful but not necessary.
1749 if (!file_pnum) {
1750 /* !file_pnum indicates an offset at or beyond the EOF; it is
1751 * perfectly valid for the format block driver to point to such
1752 * offsets, so catch it and mark everything as zero */
1753 ret |= BDRV_BLOCK_ZERO;
1754 } else {
1755 /* Limit request to the range reported by the protocol driver */
1756 *pnum = file_pnum;
1757 ret |= (ret2 & BDRV_BLOCK_ZERO);
1762 return ret;
1765 static int64_t coroutine_fn bdrv_co_get_block_status_above(BlockDriverState *bs,
1766 BlockDriverState *base,
1767 int64_t sector_num,
1768 int nb_sectors,
1769 int *pnum,
1770 BlockDriverState **file)
1772 BlockDriverState *p;
1773 int64_t ret = 0;
1775 assert(bs != base);
1776 for (p = bs; p != base; p = backing_bs(p)) {
1777 ret = bdrv_co_get_block_status(p, sector_num, nb_sectors, pnum, file);
1778 if (ret < 0 || ret & BDRV_BLOCK_ALLOCATED) {
1779 break;
1781 /* [sector_num, pnum] unallocated on this layer, which could be only
1782 * the first part of [sector_num, nb_sectors]. */
1783 nb_sectors = MIN(nb_sectors, *pnum);
1785 return ret;
1788 /* Coroutine wrapper for bdrv_get_block_status_above() */
1789 static void coroutine_fn bdrv_get_block_status_above_co_entry(void *opaque)
1791 BdrvCoGetBlockStatusData *data = opaque;
1793 data->ret = bdrv_co_get_block_status_above(data->bs, data->base,
1794 data->sector_num,
1795 data->nb_sectors,
1796 data->pnum,
1797 data->file);
1798 data->done = true;
1802 * Synchronous wrapper around bdrv_co_get_block_status_above().
1804 * See bdrv_co_get_block_status_above() for details.
1806 int64_t bdrv_get_block_status_above(BlockDriverState *bs,
1807 BlockDriverState *base,
1808 int64_t sector_num,
1809 int nb_sectors, int *pnum,
1810 BlockDriverState **file)
1812 Coroutine *co;
1813 BdrvCoGetBlockStatusData data = {
1814 .bs = bs,
1815 .base = base,
1816 .file = file,
1817 .sector_num = sector_num,
1818 .nb_sectors = nb_sectors,
1819 .pnum = pnum,
1820 .done = false,
1823 if (qemu_in_coroutine()) {
1824 /* Fast-path if already in coroutine context */
1825 bdrv_get_block_status_above_co_entry(&data);
1826 } else {
1827 AioContext *aio_context = bdrv_get_aio_context(bs);
1829 co = qemu_coroutine_create(bdrv_get_block_status_above_co_entry,
1830 &data);
1831 qemu_coroutine_enter(co);
1832 while (!data.done) {
1833 aio_poll(aio_context, true);
1836 return data.ret;
1839 int64_t bdrv_get_block_status(BlockDriverState *bs,
1840 int64_t sector_num,
1841 int nb_sectors, int *pnum,
1842 BlockDriverState **file)
1844 return bdrv_get_block_status_above(bs, backing_bs(bs),
1845 sector_num, nb_sectors, pnum, file);
1848 int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
1849 int nb_sectors, int *pnum)
1851 BlockDriverState *file;
1852 int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum,
1853 &file);
1854 if (ret < 0) {
1855 return ret;
1857 return !!(ret & BDRV_BLOCK_ALLOCATED);
1861 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
1863 * Return true if the given sector is allocated in any image between
1864 * BASE and TOP (inclusive). BASE can be NULL to check if the given
1865 * sector is allocated in any image of the chain. Return false otherwise.
1867 * 'pnum' is set to the number of sectors (including and immediately following
1868 * the specified sector) that are known to be in the same
1869 * allocated/unallocated state.
1872 int bdrv_is_allocated_above(BlockDriverState *top,
1873 BlockDriverState *base,
1874 int64_t sector_num,
1875 int nb_sectors, int *pnum)
1877 BlockDriverState *intermediate;
1878 int ret, n = nb_sectors;
1880 intermediate = top;
1881 while (intermediate && intermediate != base) {
1882 int pnum_inter;
1883 ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
1884 &pnum_inter);
1885 if (ret < 0) {
1886 return ret;
1887 } else if (ret) {
1888 *pnum = pnum_inter;
1889 return 1;
1893 * [sector_num, nb_sectors] is unallocated on top but intermediate
1894 * might have
1896 * [sector_num+x, nr_sectors] allocated.
1898 if (n > pnum_inter &&
1899 (intermediate == top ||
1900 sector_num + pnum_inter < intermediate->total_sectors)) {
1901 n = pnum_inter;
1904 intermediate = backing_bs(intermediate);
1907 *pnum = n;
1908 return 0;
1911 typedef struct BdrvVmstateCo {
1912 BlockDriverState *bs;
1913 QEMUIOVector *qiov;
1914 int64_t pos;
1915 bool is_read;
1916 int ret;
1917 } BdrvVmstateCo;
1919 static int coroutine_fn
1920 bdrv_co_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos,
1921 bool is_read)
1923 BlockDriver *drv = bs->drv;
1925 if (!drv) {
1926 return -ENOMEDIUM;
1927 } else if (drv->bdrv_load_vmstate) {
1928 return is_read ? drv->bdrv_load_vmstate(bs, qiov, pos)
1929 : drv->bdrv_save_vmstate(bs, qiov, pos);
1930 } else if (bs->file) {
1931 return bdrv_co_rw_vmstate(bs->file->bs, qiov, pos, is_read);
1934 return -ENOTSUP;
1937 static void coroutine_fn bdrv_co_rw_vmstate_entry(void *opaque)
1939 BdrvVmstateCo *co = opaque;
1940 co->ret = bdrv_co_rw_vmstate(co->bs, co->qiov, co->pos, co->is_read);
1943 static inline int
1944 bdrv_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos,
1945 bool is_read)
1947 if (qemu_in_coroutine()) {
1948 return bdrv_co_rw_vmstate(bs, qiov, pos, is_read);
1949 } else {
1950 BdrvVmstateCo data = {
1951 .bs = bs,
1952 .qiov = qiov,
1953 .pos = pos,
1954 .is_read = is_read,
1955 .ret = -EINPROGRESS,
1957 Coroutine *co = qemu_coroutine_create(bdrv_co_rw_vmstate_entry, &data);
1959 qemu_coroutine_enter(co);
1960 while (data.ret == -EINPROGRESS) {
1961 aio_poll(bdrv_get_aio_context(bs), true);
1963 return data.ret;
1967 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1968 int64_t pos, int size)
1970 QEMUIOVector qiov;
1971 struct iovec iov = {
1972 .iov_base = (void *) buf,
1973 .iov_len = size,
1975 int ret;
1977 qemu_iovec_init_external(&qiov, &iov, 1);
1979 ret = bdrv_writev_vmstate(bs, &qiov, pos);
1980 if (ret < 0) {
1981 return ret;
1984 return size;
1987 int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
1989 return bdrv_rw_vmstate(bs, qiov, pos, false);
1992 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1993 int64_t pos, int size)
1995 QEMUIOVector qiov;
1996 struct iovec iov = {
1997 .iov_base = buf,
1998 .iov_len = size,
2000 int ret;
2002 qemu_iovec_init_external(&qiov, &iov, 1);
2003 ret = bdrv_readv_vmstate(bs, &qiov, pos);
2004 if (ret < 0) {
2005 return ret;
2008 return size;
2011 int bdrv_readv_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2013 return bdrv_rw_vmstate(bs, qiov, pos, true);
2016 /**************************************************************/
2017 /* async I/Os */
2019 BlockAIOCB *bdrv_aio_readv(BdrvChild *child, int64_t sector_num,
2020 QEMUIOVector *qiov, int nb_sectors,
2021 BlockCompletionFunc *cb, void *opaque)
2023 trace_bdrv_aio_readv(child->bs, sector_num, nb_sectors, opaque);
2025 assert(nb_sectors << BDRV_SECTOR_BITS == qiov->size);
2026 return bdrv_co_aio_prw_vector(child, sector_num << BDRV_SECTOR_BITS, qiov,
2027 0, cb, opaque, false);
2030 BlockAIOCB *bdrv_aio_writev(BdrvChild *child, int64_t sector_num,
2031 QEMUIOVector *qiov, int nb_sectors,
2032 BlockCompletionFunc *cb, void *opaque)
2034 trace_bdrv_aio_writev(child->bs, sector_num, nb_sectors, opaque);
2036 assert(nb_sectors << BDRV_SECTOR_BITS == qiov->size);
2037 return bdrv_co_aio_prw_vector(child, sector_num << BDRV_SECTOR_BITS, qiov,
2038 0, cb, opaque, true);
2041 void bdrv_aio_cancel(BlockAIOCB *acb)
2043 qemu_aio_ref(acb);
2044 bdrv_aio_cancel_async(acb);
2045 while (acb->refcnt > 1) {
2046 if (acb->aiocb_info->get_aio_context) {
2047 aio_poll(acb->aiocb_info->get_aio_context(acb), true);
2048 } else if (acb->bs) {
2049 aio_poll(bdrv_get_aio_context(acb->bs), true);
2050 } else {
2051 abort();
2054 qemu_aio_unref(acb);
2057 /* Async version of aio cancel. The caller is not blocked if the acb implements
2058 * cancel_async, otherwise we do nothing and let the request normally complete.
2059 * In either case the completion callback must be called. */
2060 void bdrv_aio_cancel_async(BlockAIOCB *acb)
2062 if (acb->aiocb_info->cancel_async) {
2063 acb->aiocb_info->cancel_async(acb);
2067 /**************************************************************/
2068 /* async block device emulation */
2070 typedef struct BlockRequest {
2071 union {
2072 /* Used during read, write, trim */
2073 struct {
2074 int64_t offset;
2075 int bytes;
2076 int flags;
2077 QEMUIOVector *qiov;
2079 /* Used during ioctl */
2080 struct {
2081 int req;
2082 void *buf;
2085 BlockCompletionFunc *cb;
2086 void *opaque;
2088 int error;
2089 } BlockRequest;
2091 typedef struct BlockAIOCBCoroutine {
2092 BlockAIOCB common;
2093 BdrvChild *child;
2094 BlockRequest req;
2095 bool is_write;
2096 bool need_bh;
2097 bool *done;
2098 QEMUBH* bh;
2099 } BlockAIOCBCoroutine;
2101 static const AIOCBInfo bdrv_em_co_aiocb_info = {
2102 .aiocb_size = sizeof(BlockAIOCBCoroutine),
2105 static void bdrv_co_complete(BlockAIOCBCoroutine *acb)
2107 if (!acb->need_bh) {
2108 acb->common.cb(acb->common.opaque, acb->req.error);
2109 qemu_aio_unref(acb);
2113 static void bdrv_co_em_bh(void *opaque)
2115 BlockAIOCBCoroutine *acb = opaque;
2117 assert(!acb->need_bh);
2118 qemu_bh_delete(acb->bh);
2119 bdrv_co_complete(acb);
2122 static void bdrv_co_maybe_schedule_bh(BlockAIOCBCoroutine *acb)
2124 acb->need_bh = false;
2125 if (acb->req.error != -EINPROGRESS) {
2126 BlockDriverState *bs = acb->common.bs;
2128 acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb);
2129 qemu_bh_schedule(acb->bh);
2133 /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
2134 static void coroutine_fn bdrv_co_do_rw(void *opaque)
2136 BlockAIOCBCoroutine *acb = opaque;
2138 if (!acb->is_write) {
2139 acb->req.error = bdrv_co_preadv(acb->child, acb->req.offset,
2140 acb->req.qiov->size, acb->req.qiov, acb->req.flags);
2141 } else {
2142 acb->req.error = bdrv_co_pwritev(acb->child, acb->req.offset,
2143 acb->req.qiov->size, acb->req.qiov, acb->req.flags);
2146 bdrv_co_complete(acb);
2149 static BlockAIOCB *bdrv_co_aio_prw_vector(BdrvChild *child,
2150 int64_t offset,
2151 QEMUIOVector *qiov,
2152 BdrvRequestFlags flags,
2153 BlockCompletionFunc *cb,
2154 void *opaque,
2155 bool is_write)
2157 Coroutine *co;
2158 BlockAIOCBCoroutine *acb;
2160 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, child->bs, cb, opaque);
2161 acb->child = child;
2162 acb->need_bh = true;
2163 acb->req.error = -EINPROGRESS;
2164 acb->req.offset = offset;
2165 acb->req.qiov = qiov;
2166 acb->req.flags = flags;
2167 acb->is_write = is_write;
2169 co = qemu_coroutine_create(bdrv_co_do_rw, acb);
2170 qemu_coroutine_enter(co);
2172 bdrv_co_maybe_schedule_bh(acb);
2173 return &acb->common;
2176 static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
2178 BlockAIOCBCoroutine *acb = opaque;
2179 BlockDriverState *bs = acb->common.bs;
2181 acb->req.error = bdrv_co_flush(bs);
2182 bdrv_co_complete(acb);
2185 BlockAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2186 BlockCompletionFunc *cb, void *opaque)
2188 trace_bdrv_aio_flush(bs, opaque);
2190 Coroutine *co;
2191 BlockAIOCBCoroutine *acb;
2193 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
2194 acb->need_bh = true;
2195 acb->req.error = -EINPROGRESS;
2197 co = qemu_coroutine_create(bdrv_aio_flush_co_entry, acb);
2198 qemu_coroutine_enter(co);
2200 bdrv_co_maybe_schedule_bh(acb);
2201 return &acb->common;
2204 static void coroutine_fn bdrv_aio_pdiscard_co_entry(void *opaque)
2206 BlockAIOCBCoroutine *acb = opaque;
2207 BlockDriverState *bs = acb->common.bs;
2209 acb->req.error = bdrv_co_pdiscard(bs, acb->req.offset, acb->req.bytes);
2210 bdrv_co_complete(acb);
2213 BlockAIOCB *bdrv_aio_pdiscard(BlockDriverState *bs, int64_t offset, int count,
2214 BlockCompletionFunc *cb, void *opaque)
2216 Coroutine *co;
2217 BlockAIOCBCoroutine *acb;
2219 trace_bdrv_aio_pdiscard(bs, offset, count, opaque);
2221 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
2222 acb->need_bh = true;
2223 acb->req.error = -EINPROGRESS;
2224 acb->req.offset = offset;
2225 acb->req.bytes = count;
2226 co = qemu_coroutine_create(bdrv_aio_pdiscard_co_entry, acb);
2227 qemu_coroutine_enter(co);
2229 bdrv_co_maybe_schedule_bh(acb);
2230 return &acb->common;
2233 void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
2234 BlockCompletionFunc *cb, void *opaque)
2236 BlockAIOCB *acb;
2238 acb = g_malloc(aiocb_info->aiocb_size);
2239 acb->aiocb_info = aiocb_info;
2240 acb->bs = bs;
2241 acb->cb = cb;
2242 acb->opaque = opaque;
2243 acb->refcnt = 1;
2244 return acb;
2247 void qemu_aio_ref(void *p)
2249 BlockAIOCB *acb = p;
2250 acb->refcnt++;
2253 void qemu_aio_unref(void *p)
2255 BlockAIOCB *acb = p;
2256 assert(acb->refcnt > 0);
2257 if (--acb->refcnt == 0) {
2258 g_free(acb);
2262 /**************************************************************/
2263 /* Coroutine block device emulation */
2265 typedef struct FlushCo {
2266 BlockDriverState *bs;
2267 int ret;
2268 } FlushCo;
2271 static void coroutine_fn bdrv_flush_co_entry(void *opaque)
2273 FlushCo *rwco = opaque;
2275 rwco->ret = bdrv_co_flush(rwco->bs);
2278 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
2280 int ret;
2281 BdrvTrackedRequest req;
2283 if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||
2284 bdrv_is_sg(bs)) {
2285 return 0;
2288 tracked_request_begin(&req, bs, 0, 0, BDRV_TRACKED_FLUSH);
2290 int current_gen = bs->write_gen;
2292 /* Wait until any previous flushes are completed */
2293 while (bs->active_flush_req != NULL) {
2294 qemu_co_queue_wait(&bs->flush_queue);
2297 bs->active_flush_req = &req;
2299 /* Write back all layers by calling one driver function */
2300 if (bs->drv->bdrv_co_flush) {
2301 ret = bs->drv->bdrv_co_flush(bs);
2302 goto out;
2305 /* Write back cached data to the OS even with cache=unsafe */
2306 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
2307 if (bs->drv->bdrv_co_flush_to_os) {
2308 ret = bs->drv->bdrv_co_flush_to_os(bs);
2309 if (ret < 0) {
2310 goto out;
2314 /* But don't actually force it to the disk with cache=unsafe */
2315 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2316 goto flush_parent;
2319 /* Check if we really need to flush anything */
2320 if (bs->flushed_gen == current_gen) {
2321 goto flush_parent;
2324 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
2325 if (bs->drv->bdrv_co_flush_to_disk) {
2326 ret = bs->drv->bdrv_co_flush_to_disk(bs);
2327 } else if (bs->drv->bdrv_aio_flush) {
2328 BlockAIOCB *acb;
2329 CoroutineIOCompletion co = {
2330 .coroutine = qemu_coroutine_self(),
2333 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
2334 if (acb == NULL) {
2335 ret = -EIO;
2336 } else {
2337 qemu_coroutine_yield();
2338 ret = co.ret;
2340 } else {
2342 * Some block drivers always operate in either writethrough or unsafe
2343 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2344 * know how the server works (because the behaviour is hardcoded or
2345 * depends on server-side configuration), so we can't ensure that
2346 * everything is safe on disk. Returning an error doesn't work because
2347 * that would break guests even if the server operates in writethrough
2348 * mode.
2350 * Let's hope the user knows what he's doing.
2352 ret = 0;
2355 if (ret < 0) {
2356 goto out;
2359 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2360 * in the case of cache=unsafe, so there are no useless flushes.
2362 flush_parent:
2363 ret = bs->file ? bdrv_co_flush(bs->file->bs) : 0;
2364 out:
2365 /* Notify any pending flushes that we have completed */
2366 bs->flushed_gen = current_gen;
2367 bs->active_flush_req = NULL;
2368 /* Return value is ignored - it's ok if wait queue is empty */
2369 qemu_co_queue_next(&bs->flush_queue);
2371 tracked_request_end(&req);
2372 return ret;
2375 int bdrv_flush(BlockDriverState *bs)
2377 Coroutine *co;
2378 FlushCo flush_co = {
2379 .bs = bs,
2380 .ret = NOT_DONE,
2383 if (qemu_in_coroutine()) {
2384 /* Fast-path if already in coroutine context */
2385 bdrv_flush_co_entry(&flush_co);
2386 } else {
2387 AioContext *aio_context = bdrv_get_aio_context(bs);
2389 co = qemu_coroutine_create(bdrv_flush_co_entry, &flush_co);
2390 qemu_coroutine_enter(co);
2391 while (flush_co.ret == NOT_DONE) {
2392 aio_poll(aio_context, true);
2396 return flush_co.ret;
2399 typedef struct DiscardCo {
2400 BlockDriverState *bs;
2401 int64_t offset;
2402 int count;
2403 int ret;
2404 } DiscardCo;
2405 static void coroutine_fn bdrv_pdiscard_co_entry(void *opaque)
2407 DiscardCo *rwco = opaque;
2409 rwco->ret = bdrv_co_pdiscard(rwco->bs, rwco->offset, rwco->count);
2412 int coroutine_fn bdrv_co_pdiscard(BlockDriverState *bs, int64_t offset,
2413 int count)
2415 BdrvTrackedRequest req;
2416 int max_pdiscard, ret;
2417 int head, align;
2419 if (!bs->drv) {
2420 return -ENOMEDIUM;
2423 ret = bdrv_check_byte_request(bs, offset, count);
2424 if (ret < 0) {
2425 return ret;
2426 } else if (bs->read_only) {
2427 return -EPERM;
2429 assert(!(bs->open_flags & BDRV_O_INACTIVE));
2431 /* Do nothing if disabled. */
2432 if (!(bs->open_flags & BDRV_O_UNMAP)) {
2433 return 0;
2436 if (!bs->drv->bdrv_co_pdiscard && !bs->drv->bdrv_aio_pdiscard) {
2437 return 0;
2440 /* Discard is advisory, so ignore any unaligned head or tail */
2441 align = MAX(bs->bl.pdiscard_alignment, bs->bl.request_alignment);
2442 assert(align % bs->bl.request_alignment == 0);
2443 head = offset % align;
2444 if (head) {
2445 head = MIN(count, align - head);
2446 count -= head;
2447 offset += head;
2449 count = QEMU_ALIGN_DOWN(count, align);
2450 if (!count) {
2451 return 0;
2454 tracked_request_begin(&req, bs, offset, count, BDRV_TRACKED_DISCARD);
2456 ret = notifier_with_return_list_notify(&bs->before_write_notifiers, &req);
2457 if (ret < 0) {
2458 goto out;
2461 max_pdiscard = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_pdiscard, INT_MAX),
2462 align);
2463 assert(max_pdiscard);
2465 while (count > 0) {
2466 int ret;
2467 int num = MIN(count, max_pdiscard);
2469 if (bs->drv->bdrv_co_pdiscard) {
2470 ret = bs->drv->bdrv_co_pdiscard(bs, offset, num);
2471 } else {
2472 BlockAIOCB *acb;
2473 CoroutineIOCompletion co = {
2474 .coroutine = qemu_coroutine_self(),
2477 acb = bs->drv->bdrv_aio_pdiscard(bs, offset, num,
2478 bdrv_co_io_em_complete, &co);
2479 if (acb == NULL) {
2480 ret = -EIO;
2481 goto out;
2482 } else {
2483 qemu_coroutine_yield();
2484 ret = co.ret;
2487 if (ret && ret != -ENOTSUP) {
2488 goto out;
2491 offset += num;
2492 count -= num;
2494 ret = 0;
2495 out:
2496 ++bs->write_gen;
2497 bdrv_set_dirty(bs, req.offset >> BDRV_SECTOR_BITS,
2498 req.bytes >> BDRV_SECTOR_BITS);
2499 tracked_request_end(&req);
2500 return ret;
2503 int bdrv_pdiscard(BlockDriverState *bs, int64_t offset, int count)
2505 Coroutine *co;
2506 DiscardCo rwco = {
2507 .bs = bs,
2508 .offset = offset,
2509 .count = count,
2510 .ret = NOT_DONE,
2513 if (qemu_in_coroutine()) {
2514 /* Fast-path if already in coroutine context */
2515 bdrv_pdiscard_co_entry(&rwco);
2516 } else {
2517 AioContext *aio_context = bdrv_get_aio_context(bs);
2519 co = qemu_coroutine_create(bdrv_pdiscard_co_entry, &rwco);
2520 qemu_coroutine_enter(co);
2521 while (rwco.ret == NOT_DONE) {
2522 aio_poll(aio_context, true);
2526 return rwco.ret;
2529 static int bdrv_co_do_ioctl(BlockDriverState *bs, int req, void *buf)
2531 BlockDriver *drv = bs->drv;
2532 BdrvTrackedRequest tracked_req;
2533 CoroutineIOCompletion co = {
2534 .coroutine = qemu_coroutine_self(),
2536 BlockAIOCB *acb;
2538 tracked_request_begin(&tracked_req, bs, 0, 0, BDRV_TRACKED_IOCTL);
2539 if (!drv || !drv->bdrv_aio_ioctl) {
2540 co.ret = -ENOTSUP;
2541 goto out;
2544 acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
2545 if (!acb) {
2546 co.ret = -ENOTSUP;
2547 goto out;
2549 qemu_coroutine_yield();
2550 out:
2551 tracked_request_end(&tracked_req);
2552 return co.ret;
2555 typedef struct {
2556 BlockDriverState *bs;
2557 int req;
2558 void *buf;
2559 int ret;
2560 } BdrvIoctlCoData;
2562 static void coroutine_fn bdrv_co_ioctl_entry(void *opaque)
2564 BdrvIoctlCoData *data = opaque;
2565 data->ret = bdrv_co_do_ioctl(data->bs, data->req, data->buf);
2568 /* needed for generic scsi interface */
2569 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2571 BdrvIoctlCoData data = {
2572 .bs = bs,
2573 .req = req,
2574 .buf = buf,
2575 .ret = -EINPROGRESS,
2578 if (qemu_in_coroutine()) {
2579 /* Fast-path if already in coroutine context */
2580 bdrv_co_ioctl_entry(&data);
2581 } else {
2582 Coroutine *co = qemu_coroutine_create(bdrv_co_ioctl_entry, &data);
2584 qemu_coroutine_enter(co);
2585 while (data.ret == -EINPROGRESS) {
2586 aio_poll(bdrv_get_aio_context(bs), true);
2589 return data.ret;
2592 static void coroutine_fn bdrv_co_aio_ioctl_entry(void *opaque)
2594 BlockAIOCBCoroutine *acb = opaque;
2595 acb->req.error = bdrv_co_do_ioctl(acb->common.bs,
2596 acb->req.req, acb->req.buf);
2597 bdrv_co_complete(acb);
2600 BlockAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
2601 unsigned long int req, void *buf,
2602 BlockCompletionFunc *cb, void *opaque)
2604 BlockAIOCBCoroutine *acb = qemu_aio_get(&bdrv_em_co_aiocb_info,
2605 bs, cb, opaque);
2606 Coroutine *co;
2608 acb->need_bh = true;
2609 acb->req.error = -EINPROGRESS;
2610 acb->req.req = req;
2611 acb->req.buf = buf;
2612 co = qemu_coroutine_create(bdrv_co_aio_ioctl_entry, acb);
2613 qemu_coroutine_enter(co);
2615 bdrv_co_maybe_schedule_bh(acb);
2616 return &acb->common;
2619 void *qemu_blockalign(BlockDriverState *bs, size_t size)
2621 return qemu_memalign(bdrv_opt_mem_align(bs), size);
2624 void *qemu_blockalign0(BlockDriverState *bs, size_t size)
2626 return memset(qemu_blockalign(bs, size), 0, size);
2629 void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
2631 size_t align = bdrv_opt_mem_align(bs);
2633 /* Ensure that NULL is never returned on success */
2634 assert(align > 0);
2635 if (size == 0) {
2636 size = align;
2639 return qemu_try_memalign(align, size);
2642 void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
2644 void *mem = qemu_try_blockalign(bs, size);
2646 if (mem) {
2647 memset(mem, 0, size);
2650 return mem;
2654 * Check if all memory in this vector is sector aligned.
2656 bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
2658 int i;
2659 size_t alignment = bdrv_min_mem_align(bs);
2661 for (i = 0; i < qiov->niov; i++) {
2662 if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
2663 return false;
2665 if (qiov->iov[i].iov_len % alignment) {
2666 return false;
2670 return true;
2673 void bdrv_add_before_write_notifier(BlockDriverState *bs,
2674 NotifierWithReturn *notifier)
2676 notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
2679 void bdrv_io_plug(BlockDriverState *bs)
2681 BdrvChild *child;
2683 QLIST_FOREACH(child, &bs->children, next) {
2684 bdrv_io_plug(child->bs);
2687 if (bs->io_plugged++ == 0 && bs->io_plug_disabled == 0) {
2688 BlockDriver *drv = bs->drv;
2689 if (drv && drv->bdrv_io_plug) {
2690 drv->bdrv_io_plug(bs);
2695 void bdrv_io_unplug(BlockDriverState *bs)
2697 BdrvChild *child;
2699 assert(bs->io_plugged);
2700 if (--bs->io_plugged == 0 && bs->io_plug_disabled == 0) {
2701 BlockDriver *drv = bs->drv;
2702 if (drv && drv->bdrv_io_unplug) {
2703 drv->bdrv_io_unplug(bs);
2707 QLIST_FOREACH(child, &bs->children, next) {
2708 bdrv_io_unplug(child->bs);
2712 void bdrv_io_unplugged_begin(BlockDriverState *bs)
2714 BdrvChild *child;
2716 if (bs->io_plug_disabled++ == 0 && bs->io_plugged > 0) {
2717 BlockDriver *drv = bs->drv;
2718 if (drv && drv->bdrv_io_unplug) {
2719 drv->bdrv_io_unplug(bs);
2723 QLIST_FOREACH(child, &bs->children, next) {
2724 bdrv_io_unplugged_begin(child->bs);
2728 void bdrv_io_unplugged_end(BlockDriverState *bs)
2730 BdrvChild *child;
2732 assert(bs->io_plug_disabled);
2733 QLIST_FOREACH(child, &bs->children, next) {
2734 bdrv_io_unplugged_end(child->bs);
2737 if (--bs->io_plug_disabled == 0 && bs->io_plugged > 0) {
2738 BlockDriver *drv = bs->drv;
2739 if (drv && drv->bdrv_io_plug) {
2740 drv->bdrv_io_plug(bs);