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
25 #include "qemu/osdep.h"
27 #include "sysemu/block-backend.h"
28 #include "block/blockjob.h"
29 #include "block/block_int.h"
30 #include "block/throttle-groups.h"
31 #include "qemu/cutils.h"
32 #include "qapi/error.h"
33 #include "qemu/error-report.h"
35 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
37 static BlockAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
38 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
39 BlockCompletionFunc *cb, void *opaque);
40 static BlockAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
41 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
42 BlockCompletionFunc *cb, void *opaque);
43 static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
44 int64_t sector_num, int nb_sectors,
46 static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
47 int64_t sector_num, int nb_sectors,
49 static BlockAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
53 BdrvRequestFlags flags,
54 BlockCompletionFunc *cb,
57 static void coroutine_fn bdrv_co_do_rw(void *opaque);
58 static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
59 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags);
61 /* throttling disk I/O limits */
62 void bdrv_set_io_limits(BlockDriverState *bs,
67 throttle_group_config(bs, cfg);
69 for (i = 0; i < 2; i++) {
70 qemu_co_enter_next(&bs->throttled_reqs[i]);
74 static void bdrv_start_throttled_reqs(BlockDriverState *bs)
76 bool enabled = bs->io_limits_enabled;
79 bs->io_limits_enabled = false;
81 for (i = 0; i < 2; i++) {
82 while (qemu_co_enter_next(&bs->throttled_reqs[i])) {
87 bs->io_limits_enabled = enabled;
90 void bdrv_io_limits_disable(BlockDriverState *bs)
92 bs->io_limits_enabled = false;
93 bdrv_start_throttled_reqs(bs);
94 throttle_group_unregister_bs(bs);
97 /* should be called before bdrv_set_io_limits if a limit is set */
98 void bdrv_io_limits_enable(BlockDriverState *bs, const char *group)
100 assert(!bs->io_limits_enabled);
101 throttle_group_register_bs(bs, group);
102 bs->io_limits_enabled = true;
105 void bdrv_io_limits_update_group(BlockDriverState *bs, const char *group)
107 /* this bs is not part of any group */
108 if (!bs->throttle_state) {
112 /* this bs is a part of the same group than the one we want */
113 if (!g_strcmp0(throttle_group_get_name(bs), group)) {
117 /* need to change the group this bs belong to */
118 bdrv_io_limits_disable(bs);
119 bdrv_io_limits_enable(bs, group);
122 void bdrv_setup_io_funcs(BlockDriver *bdrv)
124 /* Block drivers without coroutine functions need emulation */
125 if (!bdrv->bdrv_co_readv) {
126 bdrv->bdrv_co_readv = bdrv_co_readv_em;
127 bdrv->bdrv_co_writev = bdrv_co_writev_em;
129 /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
130 * the block driver lacks aio we need to emulate that too.
132 if (!bdrv->bdrv_aio_readv) {
133 /* add AIO emulation layer */
134 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
135 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
140 void bdrv_refresh_limits(BlockDriverState *bs, Error **errp)
142 BlockDriver *drv = bs->drv;
143 Error *local_err = NULL;
145 memset(&bs->bl, 0, sizeof(bs->bl));
151 /* Take some limits from the children as a default */
153 bdrv_refresh_limits(bs->file->bs, &local_err);
155 error_propagate(errp, local_err);
158 bs->bl.opt_transfer_length = bs->file->bs->bl.opt_transfer_length;
159 bs->bl.max_transfer_length = bs->file->bs->bl.max_transfer_length;
160 bs->bl.min_mem_alignment = bs->file->bs->bl.min_mem_alignment;
161 bs->bl.opt_mem_alignment = bs->file->bs->bl.opt_mem_alignment;
162 bs->bl.max_iov = bs->file->bs->bl.max_iov;
164 bs->bl.min_mem_alignment = 512;
165 bs->bl.opt_mem_alignment = getpagesize();
167 /* Safe default since most protocols use readv()/writev()/etc */
168 bs->bl.max_iov = IOV_MAX;
172 bdrv_refresh_limits(bs->backing->bs, &local_err);
174 error_propagate(errp, local_err);
177 bs->bl.opt_transfer_length =
178 MAX(bs->bl.opt_transfer_length,
179 bs->backing->bs->bl.opt_transfer_length);
180 bs->bl.max_transfer_length =
181 MIN_NON_ZERO(bs->bl.max_transfer_length,
182 bs->backing->bs->bl.max_transfer_length);
183 bs->bl.opt_mem_alignment =
184 MAX(bs->bl.opt_mem_alignment,
185 bs->backing->bs->bl.opt_mem_alignment);
186 bs->bl.min_mem_alignment =
187 MAX(bs->bl.min_mem_alignment,
188 bs->backing->bs->bl.min_mem_alignment);
191 bs->backing->bs->bl.max_iov);
194 /* Then let the driver override it */
195 if (drv->bdrv_refresh_limits) {
196 drv->bdrv_refresh_limits(bs, errp);
201 * The copy-on-read flag is actually a reference count so multiple users may
202 * use the feature without worrying about clobbering its previous state.
203 * Copy-on-read stays enabled until all users have called to disable it.
205 void bdrv_enable_copy_on_read(BlockDriverState *bs)
210 void bdrv_disable_copy_on_read(BlockDriverState *bs)
212 assert(bs->copy_on_read > 0);
216 /* Check if any requests are in-flight (including throttled requests) */
217 bool bdrv_requests_pending(BlockDriverState *bs)
221 if (!QLIST_EMPTY(&bs->tracked_requests)) {
224 if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) {
227 if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) {
231 QLIST_FOREACH(child, &bs->children, next) {
232 if (bdrv_requests_pending(child->bs)) {
240 static void bdrv_drain_recurse(BlockDriverState *bs)
244 if (bs->drv && bs->drv->bdrv_drain) {
245 bs->drv->bdrv_drain(bs);
247 QLIST_FOREACH(child, &bs->children, next) {
248 bdrv_drain_recurse(child->bs);
254 BlockDriverState *bs;
259 static void bdrv_co_drain_bh_cb(void *opaque)
261 BdrvCoDrainData *data = opaque;
262 Coroutine *co = data->co;
264 qemu_bh_delete(data->bh);
265 bdrv_drain(data->bs);
267 qemu_coroutine_enter(co, NULL);
270 void coroutine_fn bdrv_co_drain(BlockDriverState *bs)
272 BdrvCoDrainData data;
274 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
275 * other coroutines run if they were queued from
276 * qemu_co_queue_run_restart(). */
278 assert(qemu_in_coroutine());
279 data = (BdrvCoDrainData) {
280 .co = qemu_coroutine_self(),
283 .bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_drain_bh_cb, &data),
285 qemu_bh_schedule(data.bh);
287 qemu_coroutine_yield();
288 /* If we are resumed from some other event (such as an aio completion or a
289 * timer callback), it is a bug in the caller that should be fixed. */
294 * Wait for pending requests to complete on a single BlockDriverState subtree,
295 * and suspend block driver's internal I/O until next request arrives.
297 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
300 * Only this BlockDriverState's AioContext is run, so in-flight requests must
301 * not depend on events in other AioContexts. In that case, use
302 * bdrv_drain_all() instead.
304 void bdrv_drain(BlockDriverState *bs)
308 bdrv_drain_recurse(bs);
309 if (qemu_in_coroutine()) {
315 bdrv_flush_io_queue(bs);
316 busy = bdrv_requests_pending(bs);
317 busy |= aio_poll(bdrv_get_aio_context(bs), busy);
322 * Wait for pending requests to complete across all BlockDriverStates
324 * This function does not flush data to disk, use bdrv_flush_all() for that
325 * after calling this function.
327 void bdrv_drain_all(void)
329 /* Always run first iteration so any pending completion BHs run */
331 BlockDriverState *bs = NULL;
332 GSList *aio_ctxs = NULL, *ctx;
334 while ((bs = bdrv_next(bs))) {
335 AioContext *aio_context = bdrv_get_aio_context(bs);
337 aio_context_acquire(aio_context);
339 block_job_pause(bs->job);
341 bdrv_drain_recurse(bs);
342 aio_context_release(aio_context);
344 if (!g_slist_find(aio_ctxs, aio_context)) {
345 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
349 /* Note that completion of an asynchronous I/O operation can trigger any
350 * number of other I/O operations on other devices---for example a
351 * coroutine can submit an I/O request to another device in response to
352 * request completion. Therefore we must keep looping until there was no
353 * more activity rather than simply draining each device independently.
358 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
359 AioContext *aio_context = ctx->data;
362 aio_context_acquire(aio_context);
363 while ((bs = bdrv_next(bs))) {
364 if (aio_context == bdrv_get_aio_context(bs)) {
365 bdrv_flush_io_queue(bs);
366 if (bdrv_requests_pending(bs)) {
368 aio_poll(aio_context, busy);
372 busy |= aio_poll(aio_context, false);
373 aio_context_release(aio_context);
378 while ((bs = bdrv_next(bs))) {
379 AioContext *aio_context = bdrv_get_aio_context(bs);
381 aio_context_acquire(aio_context);
383 block_job_resume(bs->job);
385 aio_context_release(aio_context);
387 g_slist_free(aio_ctxs);
391 * Remove an active request from the tracked requests list
393 * This function should be called when a tracked request is completing.
395 static void tracked_request_end(BdrvTrackedRequest *req)
397 if (req->serialising) {
398 req->bs->serialising_in_flight--;
401 QLIST_REMOVE(req, list);
402 qemu_co_queue_restart_all(&req->wait_queue);
406 * Add an active request to the tracked requests list
408 static void tracked_request_begin(BdrvTrackedRequest *req,
409 BlockDriverState *bs,
412 enum BdrvTrackedRequestType type)
414 *req = (BdrvTrackedRequest){
419 .co = qemu_coroutine_self(),
420 .serialising = false,
421 .overlap_offset = offset,
422 .overlap_bytes = bytes,
425 qemu_co_queue_init(&req->wait_queue);
427 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
430 static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
432 int64_t overlap_offset = req->offset & ~(align - 1);
433 unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
436 if (!req->serialising) {
437 req->bs->serialising_in_flight++;
438 req->serialising = true;
441 req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
442 req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
446 * Round a region to cluster boundaries
448 void bdrv_round_to_clusters(BlockDriverState *bs,
449 int64_t sector_num, int nb_sectors,
450 int64_t *cluster_sector_num,
451 int *cluster_nb_sectors)
455 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
456 *cluster_sector_num = sector_num;
457 *cluster_nb_sectors = nb_sectors;
459 int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
460 *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
461 *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
466 static int bdrv_get_cluster_size(BlockDriverState *bs)
471 ret = bdrv_get_info(bs, &bdi);
472 if (ret < 0 || bdi.cluster_size == 0) {
473 return bs->request_alignment;
475 return bdi.cluster_size;
479 static bool tracked_request_overlaps(BdrvTrackedRequest *req,
480 int64_t offset, unsigned int bytes)
483 if (offset >= req->overlap_offset + req->overlap_bytes) {
487 if (req->overlap_offset >= offset + bytes) {
493 static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
495 BlockDriverState *bs = self->bs;
496 BdrvTrackedRequest *req;
500 if (!bs->serialising_in_flight) {
506 QLIST_FOREACH(req, &bs->tracked_requests, list) {
507 if (req == self || (!req->serialising && !self->serialising)) {
510 if (tracked_request_overlaps(req, self->overlap_offset,
511 self->overlap_bytes))
513 /* Hitting this means there was a reentrant request, for
514 * example, a block driver issuing nested requests. This must
515 * never happen since it means deadlock.
517 assert(qemu_coroutine_self() != req->co);
519 /* If the request is already (indirectly) waiting for us, or
520 * will wait for us as soon as it wakes up, then just go on
521 * (instead of producing a deadlock in the former case). */
522 if (!req->waiting_for) {
523 self->waiting_for = req;
524 qemu_co_queue_wait(&req->wait_queue);
525 self->waiting_for = NULL;
537 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
540 if (size > BDRV_REQUEST_MAX_SECTORS << BDRV_SECTOR_BITS) {
544 if (!bdrv_is_inserted(bs)) {
555 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
558 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
562 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
563 nb_sectors * BDRV_SECTOR_SIZE);
566 typedef struct RwCo {
567 BlockDriverState *bs;
572 BdrvRequestFlags flags;
575 static void coroutine_fn bdrv_rw_co_entry(void *opaque)
579 if (!rwco->is_write) {
580 rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset,
581 rwco->qiov->size, rwco->qiov,
584 rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset,
585 rwco->qiov->size, rwco->qiov,
591 * Process a vectored synchronous request using coroutines
593 static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset,
594 QEMUIOVector *qiov, bool is_write,
595 BdrvRequestFlags flags)
602 .is_write = is_write,
607 if (qemu_in_coroutine()) {
608 /* Fast-path if already in coroutine context */
609 bdrv_rw_co_entry(&rwco);
611 AioContext *aio_context = bdrv_get_aio_context(bs);
613 co = qemu_coroutine_create(bdrv_rw_co_entry);
614 qemu_coroutine_enter(co, &rwco);
615 while (rwco.ret == NOT_DONE) {
616 aio_poll(aio_context, true);
623 * Process a synchronous request using coroutines
625 static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
626 int nb_sectors, bool is_write, BdrvRequestFlags flags)
630 .iov_base = (void *)buf,
631 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
634 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
638 qemu_iovec_init_external(&qiov, &iov, 1);
639 return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS,
640 &qiov, is_write, flags);
643 /* return < 0 if error. See bdrv_write() for the return codes */
644 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
645 uint8_t *buf, int nb_sectors)
647 return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
650 /* Return < 0 if error. Important errors are:
651 -EIO generic I/O error (may happen for all errors)
652 -ENOMEDIUM No media inserted.
653 -EINVAL Invalid sector number or nb_sectors
654 -EACCES Trying to write a read-only device
656 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
657 const uint8_t *buf, int nb_sectors)
659 return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
662 int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num,
663 int nb_sectors, BdrvRequestFlags flags)
665 return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,
666 BDRV_REQ_ZERO_WRITE | flags);
670 * Completely zero out a block device with the help of bdrv_write_zeroes.
671 * The operation is sped up by checking the block status and only writing
672 * zeroes to the device if they currently do not return zeroes. Optional
673 * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP).
675 * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
677 int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags)
679 int64_t target_sectors, ret, nb_sectors, sector_num = 0;
680 BlockDriverState *file;
683 target_sectors = bdrv_nb_sectors(bs);
684 if (target_sectors < 0) {
685 return target_sectors;
689 nb_sectors = MIN(target_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
690 if (nb_sectors <= 0) {
693 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n, &file);
695 error_report("error getting block status at sector %" PRId64 ": %s",
696 sector_num, strerror(-ret));
699 if (ret & BDRV_BLOCK_ZERO) {
703 ret = bdrv_write_zeroes(bs, sector_num, n, flags);
705 error_report("error writing zeroes at sector %" PRId64 ": %s",
706 sector_num, strerror(-ret));
713 int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes)
717 .iov_base = (void *)buf,
726 qemu_iovec_init_external(&qiov, &iov, 1);
727 ret = bdrv_prwv_co(bs, offset, &qiov, false, 0);
735 int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
739 ret = bdrv_prwv_co(bs, offset, qiov, true, 0);
747 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
748 const void *buf, int bytes)
752 .iov_base = (void *) buf,
760 qemu_iovec_init_external(&qiov, &iov, 1);
761 return bdrv_pwritev(bs, offset, &qiov);
765 * Writes to the file and ensures that no writes are reordered across this
766 * request (acts as a barrier)
768 * Returns 0 on success, -errno in error cases.
770 int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
771 const void *buf, int count)
775 ret = bdrv_pwrite(bs, offset, buf, count);
780 ret = bdrv_flush(bs);
788 static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
789 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
791 /* Perform I/O through a temporary buffer so that users who scribble over
792 * their read buffer while the operation is in progress do not end up
793 * modifying the image file. This is critical for zero-copy guest I/O
794 * where anything might happen inside guest memory.
798 BlockDriver *drv = bs->drv;
800 QEMUIOVector bounce_qiov;
801 int64_t cluster_sector_num;
802 int cluster_nb_sectors;
806 /* Cover entire cluster so no additional backing file I/O is required when
807 * allocating cluster in the image file.
809 bdrv_round_to_clusters(bs, sector_num, nb_sectors,
810 &cluster_sector_num, &cluster_nb_sectors);
812 trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
813 cluster_sector_num, cluster_nb_sectors);
815 iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
816 iov.iov_base = bounce_buffer = qemu_try_blockalign(bs, iov.iov_len);
817 if (bounce_buffer == NULL) {
822 qemu_iovec_init_external(&bounce_qiov, &iov, 1);
824 ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
830 if (drv->bdrv_co_write_zeroes &&
831 buffer_is_zero(bounce_buffer, iov.iov_len)) {
832 ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
833 cluster_nb_sectors, 0);
835 /* This does not change the data on the disk, it is not necessary
836 * to flush even in cache=writethrough mode.
838 ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
843 /* It might be okay to ignore write errors for guest requests. If this
844 * is a deliberate copy-on-read then we don't want to ignore the error.
845 * Simply report it in all cases.
850 skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
851 qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
852 nb_sectors * BDRV_SECTOR_SIZE);
855 qemu_vfree(bounce_buffer);
860 * Forwards an already correctly aligned request to the BlockDriver. This
861 * handles copy on read and zeroing after EOF; any other features must be
862 * implemented by the caller.
864 static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,
865 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
866 int64_t align, QEMUIOVector *qiov, int flags)
868 BlockDriver *drv = bs->drv;
871 int64_t sector_num = offset >> BDRV_SECTOR_BITS;
872 unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
874 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
875 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
876 assert(!qiov || bytes == qiov->size);
877 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
879 /* Handle Copy on Read and associated serialisation */
880 if (flags & BDRV_REQ_COPY_ON_READ) {
881 /* If we touch the same cluster it counts as an overlap. This
882 * guarantees that allocating writes will be serialized and not race
883 * with each other for the same cluster. For example, in copy-on-read
884 * it ensures that the CoR read and write operations are atomic and
885 * guest writes cannot interleave between them. */
886 mark_request_serialising(req, bdrv_get_cluster_size(bs));
889 if (!(flags & BDRV_REQ_NO_SERIALISING)) {
890 wait_serialising_requests(req);
893 if (flags & BDRV_REQ_COPY_ON_READ) {
896 ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);
901 if (!ret || pnum != nb_sectors) {
902 ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
907 /* Forward the request to the BlockDriver */
908 if (!bs->zero_beyond_eof) {
909 ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
911 /* Read zeros after EOF */
912 int64_t total_sectors, max_nb_sectors;
914 total_sectors = bdrv_nb_sectors(bs);
915 if (total_sectors < 0) {
920 max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num),
921 align >> BDRV_SECTOR_BITS);
922 if (nb_sectors < max_nb_sectors) {
923 ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
924 } else if (max_nb_sectors > 0) {
925 QEMUIOVector local_qiov;
927 qemu_iovec_init(&local_qiov, qiov->niov);
928 qemu_iovec_concat(&local_qiov, qiov, 0,
929 max_nb_sectors * BDRV_SECTOR_SIZE);
931 ret = drv->bdrv_co_readv(bs, sector_num, max_nb_sectors,
934 qemu_iovec_destroy(&local_qiov);
939 /* Reading beyond end of file is supposed to produce zeroes */
940 if (ret == 0 && total_sectors < sector_num + nb_sectors) {
941 uint64_t offset = MAX(0, total_sectors - sector_num);
942 uint64_t bytes = (sector_num + nb_sectors - offset) *
944 qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
953 * Handle a read request in coroutine context
955 int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
956 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
957 BdrvRequestFlags flags)
959 BlockDriver *drv = bs->drv;
960 BdrvTrackedRequest req;
962 /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
963 uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
964 uint8_t *head_buf = NULL;
965 uint8_t *tail_buf = NULL;
966 QEMUIOVector local_qiov;
967 bool use_local_qiov = false;
974 ret = bdrv_check_byte_request(bs, offset, bytes);
979 /* Don't do copy-on-read if we read data before write operation */
980 if (bs->copy_on_read && !(flags & BDRV_REQ_NO_SERIALISING)) {
981 flags |= BDRV_REQ_COPY_ON_READ;
984 /* throttling disk I/O */
985 if (bs->io_limits_enabled) {
986 throttle_group_co_io_limits_intercept(bs, bytes, false);
989 /* Align read if necessary by padding qiov */
990 if (offset & (align - 1)) {
991 head_buf = qemu_blockalign(bs, align);
992 qemu_iovec_init(&local_qiov, qiov->niov + 2);
993 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
994 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
995 use_local_qiov = true;
997 bytes += offset & (align - 1);
998 offset = offset & ~(align - 1);
1001 if ((offset + bytes) & (align - 1)) {
1002 if (!use_local_qiov) {
1003 qemu_iovec_init(&local_qiov, qiov->niov + 1);
1004 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1005 use_local_qiov = true;
1007 tail_buf = qemu_blockalign(bs, align);
1008 qemu_iovec_add(&local_qiov, tail_buf,
1009 align - ((offset + bytes) & (align - 1)));
1011 bytes = ROUND_UP(bytes, align);
1014 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_READ);
1015 ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align,
1016 use_local_qiov ? &local_qiov : qiov,
1018 tracked_request_end(&req);
1020 if (use_local_qiov) {
1021 qemu_iovec_destroy(&local_qiov);
1022 qemu_vfree(head_buf);
1023 qemu_vfree(tail_buf);
1029 static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
1030 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
1031 BdrvRequestFlags flags)
1033 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
1037 return bdrv_co_do_preadv(bs, sector_num << BDRV_SECTOR_BITS,
1038 nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
1041 int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1042 int nb_sectors, QEMUIOVector *qiov)
1044 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1046 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
1049 int coroutine_fn bdrv_co_readv_no_serialising(BlockDriverState *bs,
1050 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
1052 trace_bdrv_co_readv_no_serialising(bs, sector_num, nb_sectors);
1054 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
1055 BDRV_REQ_NO_SERIALISING);
1058 int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
1059 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
1061 trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
1063 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
1064 BDRV_REQ_COPY_ON_READ);
1067 #define MAX_WRITE_ZEROES_BOUNCE_BUFFER 32768
1069 static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
1070 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
1072 BlockDriver *drv = bs->drv;
1074 struct iovec iov = {0};
1077 int max_write_zeroes = MIN_NON_ZERO(bs->bl.max_write_zeroes,
1078 BDRV_REQUEST_MAX_SECTORS);
1080 while (nb_sectors > 0 && !ret) {
1081 int num = nb_sectors;
1083 /* Align request. Block drivers can expect the "bulk" of the request
1086 if (bs->bl.write_zeroes_alignment
1087 && num > bs->bl.write_zeroes_alignment) {
1088 if (sector_num % bs->bl.write_zeroes_alignment != 0) {
1089 /* Make a small request up to the first aligned sector. */
1090 num = bs->bl.write_zeroes_alignment;
1091 num -= sector_num % bs->bl.write_zeroes_alignment;
1092 } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) {
1093 /* Shorten the request to the last aligned sector. num cannot
1094 * underflow because num > bs->bl.write_zeroes_alignment.
1096 num -= (sector_num + num) % bs->bl.write_zeroes_alignment;
1100 /* limit request size */
1101 if (num > max_write_zeroes) {
1102 num = max_write_zeroes;
1106 /* First try the efficient write zeroes operation */
1107 if (drv->bdrv_co_write_zeroes) {
1108 ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags);
1111 if (ret == -ENOTSUP) {
1112 /* Fall back to bounce buffer if write zeroes is unsupported */
1113 int max_xfer_len = MIN_NON_ZERO(bs->bl.max_transfer_length,
1114 MAX_WRITE_ZEROES_BOUNCE_BUFFER);
1115 num = MIN(num, max_xfer_len);
1116 iov.iov_len = num * BDRV_SECTOR_SIZE;
1117 if (iov.iov_base == NULL) {
1118 iov.iov_base = qemu_try_blockalign(bs, num * BDRV_SECTOR_SIZE);
1119 if (iov.iov_base == NULL) {
1123 memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE);
1125 qemu_iovec_init_external(&qiov, &iov, 1);
1127 ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov);
1129 /* Keep bounce buffer around if it is big enough for all
1130 * all future requests.
1132 if (num < max_xfer_len) {
1133 qemu_vfree(iov.iov_base);
1134 iov.iov_base = NULL;
1143 qemu_vfree(iov.iov_base);
1148 * Forwards an already correctly aligned write request to the BlockDriver.
1150 static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,
1151 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
1152 QEMUIOVector *qiov, int flags)
1154 BlockDriver *drv = bs->drv;
1158 int64_t sector_num = offset >> BDRV_SECTOR_BITS;
1159 unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
1161 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1162 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1163 assert(!qiov || bytes == qiov->size);
1164 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1166 waited = wait_serialising_requests(req);
1167 assert(!waited || !req->serialising);
1168 assert(req->overlap_offset <= offset);
1169 assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
1171 ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
1173 if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
1174 !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_write_zeroes &&
1175 qemu_iovec_is_zero(qiov)) {
1176 flags |= BDRV_REQ_ZERO_WRITE;
1177 if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
1178 flags |= BDRV_REQ_MAY_UNMAP;
1183 /* Do nothing, write notifier decided to fail this request */
1184 } else if (flags & BDRV_REQ_ZERO_WRITE) {
1185 bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO);
1186 ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags);
1187 } else if (drv->bdrv_co_writev_flags) {
1188 bdrv_debug_event(bs, BLKDBG_PWRITEV);
1189 ret = drv->bdrv_co_writev_flags(bs, sector_num, nb_sectors, qiov,
1192 assert(drv->supported_write_flags == 0);
1193 bdrv_debug_event(bs, BLKDBG_PWRITEV);
1194 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
1196 bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE);
1198 if (ret == 0 && (flags & BDRV_REQ_FUA) &&
1199 !(drv->supported_write_flags & BDRV_REQ_FUA))
1201 ret = bdrv_co_flush(bs);
1204 bdrv_set_dirty(bs, sector_num, nb_sectors);
1206 if (bs->wr_highest_offset < offset + bytes) {
1207 bs->wr_highest_offset = offset + bytes;
1211 bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);
1217 static int coroutine_fn bdrv_co_do_zero_pwritev(BlockDriverState *bs,
1220 BdrvRequestFlags flags,
1221 BdrvTrackedRequest *req)
1223 uint8_t *buf = NULL;
1224 QEMUIOVector local_qiov;
1226 uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
1227 unsigned int head_padding_bytes, tail_padding_bytes;
1230 head_padding_bytes = offset & (align - 1);
1231 tail_padding_bytes = align - ((offset + bytes) & (align - 1));
1234 assert(flags & BDRV_REQ_ZERO_WRITE);
1235 if (head_padding_bytes || tail_padding_bytes) {
1236 buf = qemu_blockalign(bs, align);
1237 iov = (struct iovec) {
1241 qemu_iovec_init_external(&local_qiov, &iov, 1);
1243 if (head_padding_bytes) {
1244 uint64_t zero_bytes = MIN(bytes, align - head_padding_bytes);
1246 /* RMW the unaligned part before head. */
1247 mark_request_serialising(req, align);
1248 wait_serialising_requests(req);
1249 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1250 ret = bdrv_aligned_preadv(bs, req, offset & ~(align - 1), align,
1251 align, &local_qiov, 0);
1255 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1257 memset(buf + head_padding_bytes, 0, zero_bytes);
1258 ret = bdrv_aligned_pwritev(bs, req, offset & ~(align - 1), align,
1260 flags & ~BDRV_REQ_ZERO_WRITE);
1264 offset += zero_bytes;
1265 bytes -= zero_bytes;
1268 assert(!bytes || (offset & (align - 1)) == 0);
1269 if (bytes >= align) {
1270 /* Write the aligned part in the middle. */
1271 uint64_t aligned_bytes = bytes & ~(align - 1);
1272 ret = bdrv_aligned_pwritev(bs, req, offset, aligned_bytes,
1277 bytes -= aligned_bytes;
1278 offset += aligned_bytes;
1281 assert(!bytes || (offset & (align - 1)) == 0);
1283 assert(align == tail_padding_bytes + bytes);
1284 /* RMW the unaligned part after tail. */
1285 mark_request_serialising(req, align);
1286 wait_serialising_requests(req);
1287 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1288 ret = bdrv_aligned_preadv(bs, req, offset, align,
1289 align, &local_qiov, 0);
1293 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1295 memset(buf, 0, bytes);
1296 ret = bdrv_aligned_pwritev(bs, req, offset, align,
1297 &local_qiov, flags & ~BDRV_REQ_ZERO_WRITE);
1306 * Handle a write request in coroutine context
1308 int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
1309 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1310 BdrvRequestFlags flags)
1312 BdrvTrackedRequest req;
1313 /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
1314 uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
1315 uint8_t *head_buf = NULL;
1316 uint8_t *tail_buf = NULL;
1317 QEMUIOVector local_qiov;
1318 bool use_local_qiov = false;
1324 if (bs->read_only) {
1327 assert(!(bs->open_flags & BDRV_O_INACTIVE));
1329 ret = bdrv_check_byte_request(bs, offset, bytes);
1334 /* throttling disk I/O */
1335 if (bs->io_limits_enabled) {
1336 throttle_group_co_io_limits_intercept(bs, bytes, true);
1340 * Align write if necessary by performing a read-modify-write cycle.
1341 * Pad qiov with the read parts and be sure to have a tracked request not
1342 * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
1344 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);
1347 ret = bdrv_co_do_zero_pwritev(bs, offset, bytes, flags, &req);
1351 if (offset & (align - 1)) {
1352 QEMUIOVector head_qiov;
1353 struct iovec head_iov;
1355 mark_request_serialising(&req, align);
1356 wait_serialising_requests(&req);
1358 head_buf = qemu_blockalign(bs, align);
1359 head_iov = (struct iovec) {
1360 .iov_base = head_buf,
1363 qemu_iovec_init_external(&head_qiov, &head_iov, 1);
1365 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1366 ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align,
1367 align, &head_qiov, 0);
1371 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1373 qemu_iovec_init(&local_qiov, qiov->niov + 2);
1374 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
1375 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1376 use_local_qiov = true;
1378 bytes += offset & (align - 1);
1379 offset = offset & ~(align - 1);
1382 if ((offset + bytes) & (align - 1)) {
1383 QEMUIOVector tail_qiov;
1384 struct iovec tail_iov;
1388 mark_request_serialising(&req, align);
1389 waited = wait_serialising_requests(&req);
1390 assert(!waited || !use_local_qiov);
1392 tail_buf = qemu_blockalign(bs, align);
1393 tail_iov = (struct iovec) {
1394 .iov_base = tail_buf,
1397 qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);
1399 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1400 ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align,
1401 align, &tail_qiov, 0);
1405 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1407 if (!use_local_qiov) {
1408 qemu_iovec_init(&local_qiov, qiov->niov + 1);
1409 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1410 use_local_qiov = true;
1413 tail_bytes = (offset + bytes) & (align - 1);
1414 qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
1416 bytes = ROUND_UP(bytes, align);
1419 ret = bdrv_aligned_pwritev(bs, &req, offset, bytes,
1420 use_local_qiov ? &local_qiov : qiov,
1425 if (use_local_qiov) {
1426 qemu_iovec_destroy(&local_qiov);
1428 qemu_vfree(head_buf);
1429 qemu_vfree(tail_buf);
1431 tracked_request_end(&req);
1435 static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
1436 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
1437 BdrvRequestFlags flags)
1439 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
1443 return bdrv_co_do_pwritev(bs, sector_num << BDRV_SECTOR_BITS,
1444 nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
1447 int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1448 int nb_sectors, QEMUIOVector *qiov)
1450 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1452 return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
1455 int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
1456 int64_t sector_num, int nb_sectors,
1457 BdrvRequestFlags flags)
1459 trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags);
1461 if (!(bs->open_flags & BDRV_O_UNMAP)) {
1462 flags &= ~BDRV_REQ_MAY_UNMAP;
1465 return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
1466 BDRV_REQ_ZERO_WRITE | flags);
1469 typedef struct BdrvCoGetBlockStatusData {
1470 BlockDriverState *bs;
1471 BlockDriverState *base;
1472 BlockDriverState **file;
1478 } BdrvCoGetBlockStatusData;
1481 * Returns the allocation status of the specified sectors.
1482 * Drivers not implementing the functionality are assumed to not support
1483 * backing files, hence all their sectors are reported as allocated.
1485 * If 'sector_num' is beyond the end of the disk image the return value is 0
1486 * and 'pnum' is set to 0.
1488 * 'pnum' is set to the number of sectors (including and immediately following
1489 * the specified sector) that are known to be in the same
1490 * allocated/unallocated state.
1492 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1493 * beyond the end of the disk image it will be clamped.
1495 * If returned value is positive and BDRV_BLOCK_OFFSET_VALID bit is set, 'file'
1496 * points to the BDS which the sector range is allocated in.
1498 static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
1500 int nb_sectors, int *pnum,
1501 BlockDriverState **file)
1503 int64_t total_sectors;
1507 total_sectors = bdrv_nb_sectors(bs);
1508 if (total_sectors < 0) {
1509 return total_sectors;
1512 if (sector_num >= total_sectors) {
1517 n = total_sectors - sector_num;
1518 if (n < nb_sectors) {
1522 if (!bs->drv->bdrv_co_get_block_status) {
1524 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
1525 if (bs->drv->protocol_name) {
1526 ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
1532 ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum,
1539 if (ret & BDRV_BLOCK_RAW) {
1540 assert(ret & BDRV_BLOCK_OFFSET_VALID);
1541 return bdrv_get_block_status(bs->file->bs, ret >> BDRV_SECTOR_BITS,
1545 if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
1546 ret |= BDRV_BLOCK_ALLOCATED;
1548 if (bdrv_unallocated_blocks_are_zero(bs)) {
1549 ret |= BDRV_BLOCK_ZERO;
1550 } else if (bs->backing) {
1551 BlockDriverState *bs2 = bs->backing->bs;
1552 int64_t nb_sectors2 = bdrv_nb_sectors(bs2);
1553 if (nb_sectors2 >= 0 && sector_num >= nb_sectors2) {
1554 ret |= BDRV_BLOCK_ZERO;
1559 if (*file && *file != bs &&
1560 (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
1561 (ret & BDRV_BLOCK_OFFSET_VALID)) {
1562 BlockDriverState *file2;
1565 ret2 = bdrv_co_get_block_status(*file, ret >> BDRV_SECTOR_BITS,
1566 *pnum, &file_pnum, &file2);
1568 /* Ignore errors. This is just providing extra information, it
1569 * is useful but not necessary.
1572 /* !file_pnum indicates an offset at or beyond the EOF; it is
1573 * perfectly valid for the format block driver to point to such
1574 * offsets, so catch it and mark everything as zero */
1575 ret |= BDRV_BLOCK_ZERO;
1577 /* Limit request to the range reported by the protocol driver */
1579 ret |= (ret2 & BDRV_BLOCK_ZERO);
1587 static int64_t coroutine_fn bdrv_co_get_block_status_above(BlockDriverState *bs,
1588 BlockDriverState *base,
1592 BlockDriverState **file)
1594 BlockDriverState *p;
1598 for (p = bs; p != base; p = backing_bs(p)) {
1599 ret = bdrv_co_get_block_status(p, sector_num, nb_sectors, pnum, file);
1600 if (ret < 0 || ret & BDRV_BLOCK_ALLOCATED) {
1603 /* [sector_num, pnum] unallocated on this layer, which could be only
1604 * the first part of [sector_num, nb_sectors]. */
1605 nb_sectors = MIN(nb_sectors, *pnum);
1610 /* Coroutine wrapper for bdrv_get_block_status_above() */
1611 static void coroutine_fn bdrv_get_block_status_above_co_entry(void *opaque)
1613 BdrvCoGetBlockStatusData *data = opaque;
1615 data->ret = bdrv_co_get_block_status_above(data->bs, data->base,
1624 * Synchronous wrapper around bdrv_co_get_block_status_above().
1626 * See bdrv_co_get_block_status_above() for details.
1628 int64_t bdrv_get_block_status_above(BlockDriverState *bs,
1629 BlockDriverState *base,
1631 int nb_sectors, int *pnum,
1632 BlockDriverState **file)
1635 BdrvCoGetBlockStatusData data = {
1639 .sector_num = sector_num,
1640 .nb_sectors = nb_sectors,
1645 if (qemu_in_coroutine()) {
1646 /* Fast-path if already in coroutine context */
1647 bdrv_get_block_status_above_co_entry(&data);
1649 AioContext *aio_context = bdrv_get_aio_context(bs);
1651 co = qemu_coroutine_create(bdrv_get_block_status_above_co_entry);
1652 qemu_coroutine_enter(co, &data);
1653 while (!data.done) {
1654 aio_poll(aio_context, true);
1660 int64_t bdrv_get_block_status(BlockDriverState *bs,
1662 int nb_sectors, int *pnum,
1663 BlockDriverState **file)
1665 return bdrv_get_block_status_above(bs, backing_bs(bs),
1666 sector_num, nb_sectors, pnum, file);
1669 int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
1670 int nb_sectors, int *pnum)
1672 BlockDriverState *file;
1673 int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum,
1678 return !!(ret & BDRV_BLOCK_ALLOCATED);
1682 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
1684 * Return true if the given sector is allocated in any image between
1685 * BASE and TOP (inclusive). BASE can be NULL to check if the given
1686 * sector is allocated in any image of the chain. Return false otherwise.
1688 * 'pnum' is set to the number of sectors (including and immediately following
1689 * the specified sector) that are known to be in the same
1690 * allocated/unallocated state.
1693 int bdrv_is_allocated_above(BlockDriverState *top,
1694 BlockDriverState *base,
1696 int nb_sectors, int *pnum)
1698 BlockDriverState *intermediate;
1699 int ret, n = nb_sectors;
1702 while (intermediate && intermediate != base) {
1704 ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
1714 * [sector_num, nb_sectors] is unallocated on top but intermediate
1717 * [sector_num+x, nr_sectors] allocated.
1719 if (n > pnum_inter &&
1720 (intermediate == top ||
1721 sector_num + pnum_inter < intermediate->total_sectors)) {
1725 intermediate = backing_bs(intermediate);
1732 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1733 const uint8_t *buf, int nb_sectors)
1735 BlockDriver *drv = bs->drv;
1741 if (!drv->bdrv_write_compressed) {
1744 ret = bdrv_check_request(bs, sector_num, nb_sectors);
1749 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
1751 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1754 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1755 int64_t pos, int size)
1758 struct iovec iov = {
1759 .iov_base = (void *) buf,
1763 qemu_iovec_init_external(&qiov, &iov, 1);
1764 return bdrv_writev_vmstate(bs, &qiov, pos);
1767 int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
1769 BlockDriver *drv = bs->drv;
1773 } else if (drv->bdrv_save_vmstate) {
1774 return drv->bdrv_save_vmstate(bs, qiov, pos);
1775 } else if (bs->file) {
1776 return bdrv_writev_vmstate(bs->file->bs, qiov, pos);
1782 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1783 int64_t pos, int size)
1785 BlockDriver *drv = bs->drv;
1788 if (drv->bdrv_load_vmstate)
1789 return drv->bdrv_load_vmstate(bs, buf, pos, size);
1791 return bdrv_load_vmstate(bs->file->bs, buf, pos, size);
1795 /**************************************************************/
1798 BlockAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
1799 QEMUIOVector *qiov, int nb_sectors,
1800 BlockCompletionFunc *cb, void *opaque)
1802 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
1804 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
1808 BlockAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
1809 QEMUIOVector *qiov, int nb_sectors,
1810 BlockCompletionFunc *cb, void *opaque)
1812 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
1814 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
1818 BlockAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs,
1819 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags,
1820 BlockCompletionFunc *cb, void *opaque)
1822 trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque);
1824 return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors,
1825 BDRV_REQ_ZERO_WRITE | flags,
1830 typedef struct MultiwriteCB {
1835 BlockCompletionFunc *cb;
1837 QEMUIOVector *free_qiov;
1841 static void multiwrite_user_cb(MultiwriteCB *mcb)
1845 for (i = 0; i < mcb->num_callbacks; i++) {
1846 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
1847 if (mcb->callbacks[i].free_qiov) {
1848 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
1850 g_free(mcb->callbacks[i].free_qiov);
1854 static void multiwrite_cb(void *opaque, int ret)
1856 MultiwriteCB *mcb = opaque;
1858 trace_multiwrite_cb(mcb, ret);
1860 if (ret < 0 && !mcb->error) {
1864 mcb->num_requests--;
1865 if (mcb->num_requests == 0) {
1866 multiwrite_user_cb(mcb);
1871 static int multiwrite_req_compare(const void *a, const void *b)
1873 const BlockRequest *req1 = a, *req2 = b;
1876 * Note that we can't simply subtract req2->sector from req1->sector
1877 * here as that could overflow the return value.
1879 if (req1->sector > req2->sector) {
1881 } else if (req1->sector < req2->sector) {
1889 * Takes a bunch of requests and tries to merge them. Returns the number of
1890 * requests that remain after merging.
1892 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
1893 int num_reqs, MultiwriteCB *mcb)
1897 // Sort requests by start sector
1898 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
1900 // Check if adjacent requests touch the same clusters. If so, combine them,
1901 // filling up gaps with zero sectors.
1903 for (i = 1; i < num_reqs; i++) {
1905 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
1907 // Handle exactly sequential writes and overlapping writes.
1908 if (reqs[i].sector <= oldreq_last) {
1912 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 >
1917 if (bs->bl.max_transfer_length && reqs[outidx].nb_sectors +
1918 reqs[i].nb_sectors > bs->bl.max_transfer_length) {
1924 QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
1925 qemu_iovec_init(qiov,
1926 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
1928 // Add the first request to the merged one. If the requests are
1929 // overlapping, drop the last sectors of the first request.
1930 size = (reqs[i].sector - reqs[outidx].sector) << 9;
1931 qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
1933 // We should need to add any zeros between the two requests
1934 assert (reqs[i].sector <= oldreq_last);
1936 // Add the second request
1937 qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
1939 // Add tail of first request, if necessary
1940 if (qiov->size < reqs[outidx].qiov->size) {
1941 qemu_iovec_concat(qiov, reqs[outidx].qiov, qiov->size,
1942 reqs[outidx].qiov->size - qiov->size);
1945 reqs[outidx].nb_sectors = qiov->size >> 9;
1946 reqs[outidx].qiov = qiov;
1948 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
1951 reqs[outidx].sector = reqs[i].sector;
1952 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
1953 reqs[outidx].qiov = reqs[i].qiov;
1958 block_acct_merge_done(blk_get_stats(bs->blk), BLOCK_ACCT_WRITE,
1959 num_reqs - outidx - 1);
1966 * Submit multiple AIO write requests at once.
1968 * On success, the function returns 0 and all requests in the reqs array have
1969 * been submitted. In error case this function returns -1, and any of the
1970 * requests may or may not be submitted yet. In particular, this means that the
1971 * callback will be called for some of the requests, for others it won't. The
1972 * caller must check the error field of the BlockRequest to wait for the right
1973 * callbacks (if error != 0, no callback will be called).
1975 * The implementation may modify the contents of the reqs array, e.g. to merge
1976 * requests. However, the fields opaque and error are left unmodified as they
1977 * are used to signal failure for a single request to the caller.
1979 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
1984 /* don't submit writes if we don't have a medium */
1985 if (bs->drv == NULL) {
1986 for (i = 0; i < num_reqs; i++) {
1987 reqs[i].error = -ENOMEDIUM;
1992 if (num_reqs == 0) {
1996 // Create MultiwriteCB structure
1997 mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
1998 mcb->num_requests = 0;
1999 mcb->num_callbacks = num_reqs;
2001 for (i = 0; i < num_reqs; i++) {
2002 mcb->callbacks[i].cb = reqs[i].cb;
2003 mcb->callbacks[i].opaque = reqs[i].opaque;
2006 // Check for mergable requests
2007 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2009 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
2011 /* Run the aio requests. */
2012 mcb->num_requests = num_reqs;
2013 for (i = 0; i < num_reqs; i++) {
2014 bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov,
2015 reqs[i].nb_sectors, reqs[i].flags,
2023 void bdrv_aio_cancel(BlockAIOCB *acb)
2026 bdrv_aio_cancel_async(acb);
2027 while (acb->refcnt > 1) {
2028 if (acb->aiocb_info->get_aio_context) {
2029 aio_poll(acb->aiocb_info->get_aio_context(acb), true);
2030 } else if (acb->bs) {
2031 aio_poll(bdrv_get_aio_context(acb->bs), true);
2036 qemu_aio_unref(acb);
2039 /* Async version of aio cancel. The caller is not blocked if the acb implements
2040 * cancel_async, otherwise we do nothing and let the request normally complete.
2041 * In either case the completion callback must be called. */
2042 void bdrv_aio_cancel_async(BlockAIOCB *acb)
2044 if (acb->aiocb_info->cancel_async) {
2045 acb->aiocb_info->cancel_async(acb);
2049 /**************************************************************/
2050 /* async block device emulation */
2052 typedef struct BlockAIOCBSync {
2056 /* vector translation state */
2062 static const AIOCBInfo bdrv_em_aiocb_info = {
2063 .aiocb_size = sizeof(BlockAIOCBSync),
2066 static void bdrv_aio_bh_cb(void *opaque)
2068 BlockAIOCBSync *acb = opaque;
2070 if (!acb->is_write && acb->ret >= 0) {
2071 qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
2073 qemu_vfree(acb->bounce);
2074 acb->common.cb(acb->common.opaque, acb->ret);
2075 qemu_bh_delete(acb->bh);
2077 qemu_aio_unref(acb);
2080 static BlockAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2084 BlockCompletionFunc *cb,
2089 BlockAIOCBSync *acb;
2091 acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
2092 acb->is_write = is_write;
2094 acb->bounce = qemu_try_blockalign(bs, qiov->size);
2095 acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_aio_bh_cb, acb);
2097 if (acb->bounce == NULL) {
2099 } else if (is_write) {
2100 qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
2101 acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2103 acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2106 qemu_bh_schedule(acb->bh);
2108 return &acb->common;
2111 static BlockAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2112 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2113 BlockCompletionFunc *cb, void *opaque)
2115 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
2118 static BlockAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2119 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2120 BlockCompletionFunc *cb, void *opaque)
2122 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2126 typedef struct BlockAIOCBCoroutine {
2133 } BlockAIOCBCoroutine;
2135 static const AIOCBInfo bdrv_em_co_aiocb_info = {
2136 .aiocb_size = sizeof(BlockAIOCBCoroutine),
2139 static void bdrv_co_complete(BlockAIOCBCoroutine *acb)
2141 if (!acb->need_bh) {
2142 acb->common.cb(acb->common.opaque, acb->req.error);
2143 qemu_aio_unref(acb);
2147 static void bdrv_co_em_bh(void *opaque)
2149 BlockAIOCBCoroutine *acb = opaque;
2151 assert(!acb->need_bh);
2152 qemu_bh_delete(acb->bh);
2153 bdrv_co_complete(acb);
2156 static void bdrv_co_maybe_schedule_bh(BlockAIOCBCoroutine *acb)
2158 acb->need_bh = false;
2159 if (acb->req.error != -EINPROGRESS) {
2160 BlockDriverState *bs = acb->common.bs;
2162 acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb);
2163 qemu_bh_schedule(acb->bh);
2167 /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
2168 static void coroutine_fn bdrv_co_do_rw(void *opaque)
2170 BlockAIOCBCoroutine *acb = opaque;
2171 BlockDriverState *bs = acb->common.bs;
2173 if (!acb->is_write) {
2174 acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
2175 acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
2177 acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
2178 acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
2181 bdrv_co_complete(acb);
2184 static BlockAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
2188 BdrvRequestFlags flags,
2189 BlockCompletionFunc *cb,
2194 BlockAIOCBCoroutine *acb;
2196 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
2197 acb->need_bh = true;
2198 acb->req.error = -EINPROGRESS;
2199 acb->req.sector = sector_num;
2200 acb->req.nb_sectors = nb_sectors;
2201 acb->req.qiov = qiov;
2202 acb->req.flags = flags;
2203 acb->is_write = is_write;
2205 co = qemu_coroutine_create(bdrv_co_do_rw);
2206 qemu_coroutine_enter(co, acb);
2208 bdrv_co_maybe_schedule_bh(acb);
2209 return &acb->common;
2212 static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
2214 BlockAIOCBCoroutine *acb = opaque;
2215 BlockDriverState *bs = acb->common.bs;
2217 acb->req.error = bdrv_co_flush(bs);
2218 bdrv_co_complete(acb);
2221 BlockAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2222 BlockCompletionFunc *cb, void *opaque)
2224 trace_bdrv_aio_flush(bs, opaque);
2227 BlockAIOCBCoroutine *acb;
2229 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
2230 acb->need_bh = true;
2231 acb->req.error = -EINPROGRESS;
2233 co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
2234 qemu_coroutine_enter(co, acb);
2236 bdrv_co_maybe_schedule_bh(acb);
2237 return &acb->common;
2240 static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
2242 BlockAIOCBCoroutine *acb = opaque;
2243 BlockDriverState *bs = acb->common.bs;
2245 acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
2246 bdrv_co_complete(acb);
2249 BlockAIOCB *bdrv_aio_discard(BlockDriverState *bs,
2250 int64_t sector_num, int nb_sectors,
2251 BlockCompletionFunc *cb, void *opaque)
2254 BlockAIOCBCoroutine *acb;
2256 trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
2258 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
2259 acb->need_bh = true;
2260 acb->req.error = -EINPROGRESS;
2261 acb->req.sector = sector_num;
2262 acb->req.nb_sectors = nb_sectors;
2263 co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
2264 qemu_coroutine_enter(co, acb);
2266 bdrv_co_maybe_schedule_bh(acb);
2267 return &acb->common;
2270 void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
2271 BlockCompletionFunc *cb, void *opaque)
2275 acb = g_malloc(aiocb_info->aiocb_size);
2276 acb->aiocb_info = aiocb_info;
2279 acb->opaque = opaque;
2284 void qemu_aio_ref(void *p)
2286 BlockAIOCB *acb = p;
2290 void qemu_aio_unref(void *p)
2292 BlockAIOCB *acb = p;
2293 assert(acb->refcnt > 0);
2294 if (--acb->refcnt == 0) {
2299 /**************************************************************/
2300 /* Coroutine block device emulation */
2302 typedef struct CoroutineIOCompletion {
2303 Coroutine *coroutine;
2305 } CoroutineIOCompletion;
2307 static void bdrv_co_io_em_complete(void *opaque, int ret)
2309 CoroutineIOCompletion *co = opaque;
2312 qemu_coroutine_enter(co->coroutine, NULL);
2315 static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
2316 int nb_sectors, QEMUIOVector *iov,
2319 CoroutineIOCompletion co = {
2320 .coroutine = qemu_coroutine_self(),
2325 acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
2326 bdrv_co_io_em_complete, &co);
2328 acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
2329 bdrv_co_io_em_complete, &co);
2332 trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
2336 qemu_coroutine_yield();
2341 static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
2342 int64_t sector_num, int nb_sectors,
2345 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
2348 static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
2349 int64_t sector_num, int nb_sectors,
2352 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
2355 static void coroutine_fn bdrv_flush_co_entry(void *opaque)
2357 RwCo *rwco = opaque;
2359 rwco->ret = bdrv_co_flush(rwco->bs);
2362 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
2365 BdrvTrackedRequest req;
2367 if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||
2372 tracked_request_begin(&req, bs, 0, 0, BDRV_TRACKED_FLUSH);
2374 /* Write back all layers by calling one driver function */
2375 if (bs->drv->bdrv_co_flush) {
2376 ret = bs->drv->bdrv_co_flush(bs);
2380 /* Write back cached data to the OS even with cache=unsafe */
2381 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
2382 if (bs->drv->bdrv_co_flush_to_os) {
2383 ret = bs->drv->bdrv_co_flush_to_os(bs);
2389 /* But don't actually force it to the disk with cache=unsafe */
2390 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2394 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
2395 if (bs->drv->bdrv_co_flush_to_disk) {
2396 ret = bs->drv->bdrv_co_flush_to_disk(bs);
2397 } else if (bs->drv->bdrv_aio_flush) {
2399 CoroutineIOCompletion co = {
2400 .coroutine = qemu_coroutine_self(),
2403 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
2407 qemu_coroutine_yield();
2412 * Some block drivers always operate in either writethrough or unsafe
2413 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2414 * know how the server works (because the behaviour is hardcoded or
2415 * depends on server-side configuration), so we can't ensure that
2416 * everything is safe on disk. Returning an error doesn't work because
2417 * that would break guests even if the server operates in writethrough
2420 * Let's hope the user knows what he's doing.
2428 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2429 * in the case of cache=unsafe, so there are no useless flushes.
2432 ret = bs->file ? bdrv_co_flush(bs->file->bs) : 0;
2434 tracked_request_end(&req);
2438 int bdrv_flush(BlockDriverState *bs)
2446 if (qemu_in_coroutine()) {
2447 /* Fast-path if already in coroutine context */
2448 bdrv_flush_co_entry(&rwco);
2450 AioContext *aio_context = bdrv_get_aio_context(bs);
2452 co = qemu_coroutine_create(bdrv_flush_co_entry);
2453 qemu_coroutine_enter(co, &rwco);
2454 while (rwco.ret == NOT_DONE) {
2455 aio_poll(aio_context, true);
2462 typedef struct DiscardCo {
2463 BlockDriverState *bs;
2468 static void coroutine_fn bdrv_discard_co_entry(void *opaque)
2470 DiscardCo *rwco = opaque;
2472 rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
2475 int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
2478 BdrvTrackedRequest req;
2479 int max_discard, ret;
2485 ret = bdrv_check_request(bs, sector_num, nb_sectors);
2488 } else if (bs->read_only) {
2491 assert(!(bs->open_flags & BDRV_O_INACTIVE));
2493 /* Do nothing if disabled. */
2494 if (!(bs->open_flags & BDRV_O_UNMAP)) {
2498 if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) {
2502 tracked_request_begin(&req, bs, sector_num, nb_sectors,
2503 BDRV_TRACKED_DISCARD);
2504 bdrv_set_dirty(bs, sector_num, nb_sectors);
2506 max_discard = MIN_NON_ZERO(bs->bl.max_discard, BDRV_REQUEST_MAX_SECTORS);
2507 while (nb_sectors > 0) {
2509 int num = nb_sectors;
2512 if (bs->bl.discard_alignment &&
2513 num >= bs->bl.discard_alignment &&
2514 sector_num % bs->bl.discard_alignment) {
2515 if (num > bs->bl.discard_alignment) {
2516 num = bs->bl.discard_alignment;
2518 num -= sector_num % bs->bl.discard_alignment;
2521 /* limit request size */
2522 if (num > max_discard) {
2526 if (bs->drv->bdrv_co_discard) {
2527 ret = bs->drv->bdrv_co_discard(bs, sector_num, num);
2530 CoroutineIOCompletion co = {
2531 .coroutine = qemu_coroutine_self(),
2534 acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
2535 bdrv_co_io_em_complete, &co);
2540 qemu_coroutine_yield();
2544 if (ret && ret != -ENOTSUP) {
2553 tracked_request_end(&req);
2557 int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
2562 .sector_num = sector_num,
2563 .nb_sectors = nb_sectors,
2567 if (qemu_in_coroutine()) {
2568 /* Fast-path if already in coroutine context */
2569 bdrv_discard_co_entry(&rwco);
2571 AioContext *aio_context = bdrv_get_aio_context(bs);
2573 co = qemu_coroutine_create(bdrv_discard_co_entry);
2574 qemu_coroutine_enter(co, &rwco);
2575 while (rwco.ret == NOT_DONE) {
2576 aio_poll(aio_context, true);
2584 CoroutineIOCompletion *co;
2586 } BdrvIoctlCompletionData;
2588 static void bdrv_ioctl_bh_cb(void *opaque)
2590 BdrvIoctlCompletionData *data = opaque;
2592 bdrv_co_io_em_complete(data->co, -ENOTSUP);
2593 qemu_bh_delete(data->bh);
2596 static int bdrv_co_do_ioctl(BlockDriverState *bs, int req, void *buf)
2598 BlockDriver *drv = bs->drv;
2599 BdrvTrackedRequest tracked_req;
2600 CoroutineIOCompletion co = {
2601 .coroutine = qemu_coroutine_self(),
2605 tracked_request_begin(&tracked_req, bs, 0, 0, BDRV_TRACKED_IOCTL);
2606 if (!drv || !drv->bdrv_aio_ioctl) {
2611 acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
2613 BdrvIoctlCompletionData *data = g_new(BdrvIoctlCompletionData, 1);
2614 data->bh = aio_bh_new(bdrv_get_aio_context(bs),
2615 bdrv_ioctl_bh_cb, data);
2617 qemu_bh_schedule(data->bh);
2619 qemu_coroutine_yield();
2621 tracked_request_end(&tracked_req);
2626 BlockDriverState *bs;
2632 static void coroutine_fn bdrv_co_ioctl_entry(void *opaque)
2634 BdrvIoctlCoData *data = opaque;
2635 data->ret = bdrv_co_do_ioctl(data->bs, data->req, data->buf);
2638 /* needed for generic scsi interface */
2639 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2641 BdrvIoctlCoData data = {
2645 .ret = -EINPROGRESS,
2648 if (qemu_in_coroutine()) {
2649 /* Fast-path if already in coroutine context */
2650 bdrv_co_ioctl_entry(&data);
2652 Coroutine *co = qemu_coroutine_create(bdrv_co_ioctl_entry);
2654 qemu_coroutine_enter(co, &data);
2655 while (data.ret == -EINPROGRESS) {
2656 aio_poll(bdrv_get_aio_context(bs), true);
2662 static void coroutine_fn bdrv_co_aio_ioctl_entry(void *opaque)
2664 BlockAIOCBCoroutine *acb = opaque;
2665 acb->req.error = bdrv_co_do_ioctl(acb->common.bs,
2666 acb->req.req, acb->req.buf);
2667 bdrv_co_complete(acb);
2670 BlockAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
2671 unsigned long int req, void *buf,
2672 BlockCompletionFunc *cb, void *opaque)
2674 BlockAIOCBCoroutine *acb = qemu_aio_get(&bdrv_em_co_aiocb_info,
2678 acb->need_bh = true;
2679 acb->req.error = -EINPROGRESS;
2682 co = qemu_coroutine_create(bdrv_co_aio_ioctl_entry);
2683 qemu_coroutine_enter(co, acb);
2685 bdrv_co_maybe_schedule_bh(acb);
2686 return &acb->common;
2689 void *qemu_blockalign(BlockDriverState *bs, size_t size)
2691 return qemu_memalign(bdrv_opt_mem_align(bs), size);
2694 void *qemu_blockalign0(BlockDriverState *bs, size_t size)
2696 return memset(qemu_blockalign(bs, size), 0, size);
2699 void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
2701 size_t align = bdrv_opt_mem_align(bs);
2703 /* Ensure that NULL is never returned on success */
2709 return qemu_try_memalign(align, size);
2712 void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
2714 void *mem = qemu_try_blockalign(bs, size);
2717 memset(mem, 0, size);
2724 * Check if all memory in this vector is sector aligned.
2726 bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
2729 size_t alignment = bdrv_min_mem_align(bs);
2731 for (i = 0; i < qiov->niov; i++) {
2732 if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
2735 if (qiov->iov[i].iov_len % alignment) {
2743 void bdrv_add_before_write_notifier(BlockDriverState *bs,
2744 NotifierWithReturn *notifier)
2746 notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
2749 void bdrv_io_plug(BlockDriverState *bs)
2751 BlockDriver *drv = bs->drv;
2752 if (drv && drv->bdrv_io_plug) {
2753 drv->bdrv_io_plug(bs);
2754 } else if (bs->file) {
2755 bdrv_io_plug(bs->file->bs);
2759 void bdrv_io_unplug(BlockDriverState *bs)
2761 BlockDriver *drv = bs->drv;
2762 if (drv && drv->bdrv_io_unplug) {
2763 drv->bdrv_io_unplug(bs);
2764 } else if (bs->file) {
2765 bdrv_io_unplug(bs->file->bs);
2769 void bdrv_flush_io_queue(BlockDriverState *bs)
2771 BlockDriver *drv = bs->drv;
2772 if (drv && drv->bdrv_flush_io_queue) {
2773 drv->bdrv_flush_io_queue(bs);
2774 } else if (bs->file) {
2775 bdrv_flush_io_queue(bs->file->bs);
2777 bdrv_start_throttled_reqs(bs);
2780 void bdrv_drained_begin(BlockDriverState *bs)
2782 if (!bs->quiesce_counter++) {
2783 aio_disable_external(bdrv_get_aio_context(bs));
2788 void bdrv_drained_end(BlockDriverState *bs)
2790 assert(bs->quiesce_counter > 0);
2791 if (--bs->quiesce_counter > 0) {
2794 aio_enable_external(bdrv_get_aio_context(bs));