block: Use blk_co_preadv() for blk_read()
[qemu/ar7.git] / block / io.c
blobc7084e4932c7f5219ccd9791a0b7babc40923dc3
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 "block/throttle-groups.h"
31 #include "qemu/error-report.h"
33 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
35 static BlockAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
36 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
37 BlockCompletionFunc *cb, void *opaque);
38 static BlockAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
39 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
40 BlockCompletionFunc *cb, void *opaque);
41 static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
42 int64_t sector_num, int nb_sectors,
43 QEMUIOVector *iov);
44 static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
45 int64_t sector_num, int nb_sectors,
46 QEMUIOVector *iov);
47 static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
48 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
49 BdrvRequestFlags flags);
50 static BlockAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
51 int64_t sector_num,
52 QEMUIOVector *qiov,
53 int nb_sectors,
54 BdrvRequestFlags flags,
55 BlockCompletionFunc *cb,
56 void *opaque,
57 bool is_write);
58 static void coroutine_fn bdrv_co_do_rw(void *opaque);
59 static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
60 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags);
62 /* throttling disk I/O limits */
63 void bdrv_set_io_limits(BlockDriverState *bs,
64 ThrottleConfig *cfg)
66 int i;
68 throttle_group_config(bs, cfg);
70 for (i = 0; i < 2; i++) {
71 qemu_co_enter_next(&bs->throttled_reqs[i]);
75 /* this function drain all the throttled IOs */
76 static bool bdrv_start_throttled_reqs(BlockDriverState *bs)
78 bool drained = false;
79 bool enabled = bs->io_limits_enabled;
80 int i;
82 bs->io_limits_enabled = false;
84 for (i = 0; i < 2; i++) {
85 while (qemu_co_enter_next(&bs->throttled_reqs[i])) {
86 drained = true;
90 bs->io_limits_enabled = enabled;
92 return drained;
95 void bdrv_io_limits_disable(BlockDriverState *bs)
97 bs->io_limits_enabled = false;
98 bdrv_start_throttled_reqs(bs);
99 throttle_group_unregister_bs(bs);
102 /* should be called before bdrv_set_io_limits if a limit is set */
103 void bdrv_io_limits_enable(BlockDriverState *bs, const char *group)
105 assert(!bs->io_limits_enabled);
106 throttle_group_register_bs(bs, group);
107 bs->io_limits_enabled = true;
110 void bdrv_io_limits_update_group(BlockDriverState *bs, const char *group)
112 /* this bs is not part of any group */
113 if (!bs->throttle_state) {
114 return;
117 /* this bs is a part of the same group than the one we want */
118 if (!g_strcmp0(throttle_group_get_name(bs), group)) {
119 return;
122 /* need to change the group this bs belong to */
123 bdrv_io_limits_disable(bs);
124 bdrv_io_limits_enable(bs, group);
127 void bdrv_setup_io_funcs(BlockDriver *bdrv)
129 /* Block drivers without coroutine functions need emulation */
130 if (!bdrv->bdrv_co_readv) {
131 bdrv->bdrv_co_readv = bdrv_co_readv_em;
132 bdrv->bdrv_co_writev = bdrv_co_writev_em;
134 /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
135 * the block driver lacks aio we need to emulate that too.
137 if (!bdrv->bdrv_aio_readv) {
138 /* add AIO emulation layer */
139 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
140 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
145 void bdrv_refresh_limits(BlockDriverState *bs, Error **errp)
147 BlockDriver *drv = bs->drv;
148 Error *local_err = NULL;
150 memset(&bs->bl, 0, sizeof(bs->bl));
152 if (!drv) {
153 return;
156 /* Take some limits from the children as a default */
157 if (bs->file) {
158 bdrv_refresh_limits(bs->file->bs, &local_err);
159 if (local_err) {
160 error_propagate(errp, local_err);
161 return;
163 bs->bl.opt_transfer_length = bs->file->bs->bl.opt_transfer_length;
164 bs->bl.max_transfer_length = bs->file->bs->bl.max_transfer_length;
165 bs->bl.min_mem_alignment = bs->file->bs->bl.min_mem_alignment;
166 bs->bl.opt_mem_alignment = bs->file->bs->bl.opt_mem_alignment;
167 bs->bl.max_iov = bs->file->bs->bl.max_iov;
168 } else {
169 bs->bl.min_mem_alignment = 512;
170 bs->bl.opt_mem_alignment = getpagesize();
172 /* Safe default since most protocols use readv()/writev()/etc */
173 bs->bl.max_iov = IOV_MAX;
176 if (bs->backing) {
177 bdrv_refresh_limits(bs->backing->bs, &local_err);
178 if (local_err) {
179 error_propagate(errp, local_err);
180 return;
182 bs->bl.opt_transfer_length =
183 MAX(bs->bl.opt_transfer_length,
184 bs->backing->bs->bl.opt_transfer_length);
185 bs->bl.max_transfer_length =
186 MIN_NON_ZERO(bs->bl.max_transfer_length,
187 bs->backing->bs->bl.max_transfer_length);
188 bs->bl.opt_mem_alignment =
189 MAX(bs->bl.opt_mem_alignment,
190 bs->backing->bs->bl.opt_mem_alignment);
191 bs->bl.min_mem_alignment =
192 MAX(bs->bl.min_mem_alignment,
193 bs->backing->bs->bl.min_mem_alignment);
194 bs->bl.max_iov =
195 MIN(bs->bl.max_iov,
196 bs->backing->bs->bl.max_iov);
199 /* Then let the driver override it */
200 if (drv->bdrv_refresh_limits) {
201 drv->bdrv_refresh_limits(bs, errp);
206 * The copy-on-read flag is actually a reference count so multiple users may
207 * use the feature without worrying about clobbering its previous state.
208 * Copy-on-read stays enabled until all users have called to disable it.
210 void bdrv_enable_copy_on_read(BlockDriverState *bs)
212 bs->copy_on_read++;
215 void bdrv_disable_copy_on_read(BlockDriverState *bs)
217 assert(bs->copy_on_read > 0);
218 bs->copy_on_read--;
221 /* Check if any requests are in-flight (including throttled requests) */
222 bool bdrv_requests_pending(BlockDriverState *bs)
224 BdrvChild *child;
226 if (!QLIST_EMPTY(&bs->tracked_requests)) {
227 return true;
229 if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) {
230 return true;
232 if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) {
233 return true;
236 QLIST_FOREACH(child, &bs->children, next) {
237 if (bdrv_requests_pending(child->bs)) {
238 return true;
242 return false;
245 static void bdrv_drain_recurse(BlockDriverState *bs)
247 BdrvChild *child;
249 if (bs->drv && bs->drv->bdrv_drain) {
250 bs->drv->bdrv_drain(bs);
252 QLIST_FOREACH(child, &bs->children, next) {
253 bdrv_drain_recurse(child->bs);
258 * Wait for pending requests to complete on a single BlockDriverState subtree,
259 * and suspend block driver's internal I/O until next request arrives.
261 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
262 * AioContext.
264 * Only this BlockDriverState's AioContext is run, so in-flight requests must
265 * not depend on events in other AioContexts. In that case, use
266 * bdrv_drain_all() instead.
268 void bdrv_drain(BlockDriverState *bs)
270 bool busy = true;
272 bdrv_drain_recurse(bs);
273 while (busy) {
274 /* Keep iterating */
275 bdrv_flush_io_queue(bs);
276 busy = bdrv_requests_pending(bs);
277 busy |= aio_poll(bdrv_get_aio_context(bs), busy);
282 * Wait for pending requests to complete across all BlockDriverStates
284 * This function does not flush data to disk, use bdrv_flush_all() for that
285 * after calling this function.
287 void bdrv_drain_all(void)
289 /* Always run first iteration so any pending completion BHs run */
290 bool busy = true;
291 BlockDriverState *bs = NULL;
292 GSList *aio_ctxs = NULL, *ctx;
294 while ((bs = bdrv_next(bs))) {
295 AioContext *aio_context = bdrv_get_aio_context(bs);
297 aio_context_acquire(aio_context);
298 if (bs->job) {
299 block_job_pause(bs->job);
301 bdrv_drain_recurse(bs);
302 aio_context_release(aio_context);
304 if (!g_slist_find(aio_ctxs, aio_context)) {
305 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
309 /* Note that completion of an asynchronous I/O operation can trigger any
310 * number of other I/O operations on other devices---for example a
311 * coroutine can submit an I/O request to another device in response to
312 * request completion. Therefore we must keep looping until there was no
313 * more activity rather than simply draining each device independently.
315 while (busy) {
316 busy = false;
318 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
319 AioContext *aio_context = ctx->data;
320 bs = NULL;
322 aio_context_acquire(aio_context);
323 while ((bs = bdrv_next(bs))) {
324 if (aio_context == bdrv_get_aio_context(bs)) {
325 bdrv_flush_io_queue(bs);
326 if (bdrv_requests_pending(bs)) {
327 busy = true;
328 aio_poll(aio_context, busy);
332 busy |= aio_poll(aio_context, false);
333 aio_context_release(aio_context);
337 bs = NULL;
338 while ((bs = bdrv_next(bs))) {
339 AioContext *aio_context = bdrv_get_aio_context(bs);
341 aio_context_acquire(aio_context);
342 if (bs->job) {
343 block_job_resume(bs->job);
345 aio_context_release(aio_context);
347 g_slist_free(aio_ctxs);
351 * Remove an active request from the tracked requests list
353 * This function should be called when a tracked request is completing.
355 static void tracked_request_end(BdrvTrackedRequest *req)
357 if (req->serialising) {
358 req->bs->serialising_in_flight--;
361 QLIST_REMOVE(req, list);
362 qemu_co_queue_restart_all(&req->wait_queue);
366 * Add an active request to the tracked requests list
368 static void tracked_request_begin(BdrvTrackedRequest *req,
369 BlockDriverState *bs,
370 int64_t offset,
371 unsigned int bytes,
372 enum BdrvTrackedRequestType type)
374 *req = (BdrvTrackedRequest){
375 .bs = bs,
376 .offset = offset,
377 .bytes = bytes,
378 .type = type,
379 .co = qemu_coroutine_self(),
380 .serialising = false,
381 .overlap_offset = offset,
382 .overlap_bytes = bytes,
385 qemu_co_queue_init(&req->wait_queue);
387 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
390 static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
392 int64_t overlap_offset = req->offset & ~(align - 1);
393 unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
394 - overlap_offset;
396 if (!req->serialising) {
397 req->bs->serialising_in_flight++;
398 req->serialising = true;
401 req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
402 req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
406 * Round a region to cluster boundaries
408 void bdrv_round_to_clusters(BlockDriverState *bs,
409 int64_t sector_num, int nb_sectors,
410 int64_t *cluster_sector_num,
411 int *cluster_nb_sectors)
413 BlockDriverInfo bdi;
415 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
416 *cluster_sector_num = sector_num;
417 *cluster_nb_sectors = nb_sectors;
418 } else {
419 int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
420 *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
421 *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
422 nb_sectors, c);
426 static int bdrv_get_cluster_size(BlockDriverState *bs)
428 BlockDriverInfo bdi;
429 int ret;
431 ret = bdrv_get_info(bs, &bdi);
432 if (ret < 0 || bdi.cluster_size == 0) {
433 return bs->request_alignment;
434 } else {
435 return bdi.cluster_size;
439 static bool tracked_request_overlaps(BdrvTrackedRequest *req,
440 int64_t offset, unsigned int bytes)
442 /* aaaa bbbb */
443 if (offset >= req->overlap_offset + req->overlap_bytes) {
444 return false;
446 /* bbbb aaaa */
447 if (req->overlap_offset >= offset + bytes) {
448 return false;
450 return true;
453 static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
455 BlockDriverState *bs = self->bs;
456 BdrvTrackedRequest *req;
457 bool retry;
458 bool waited = false;
460 if (!bs->serialising_in_flight) {
461 return false;
464 do {
465 retry = false;
466 QLIST_FOREACH(req, &bs->tracked_requests, list) {
467 if (req == self || (!req->serialising && !self->serialising)) {
468 continue;
470 if (tracked_request_overlaps(req, self->overlap_offset,
471 self->overlap_bytes))
473 /* Hitting this means there was a reentrant request, for
474 * example, a block driver issuing nested requests. This must
475 * never happen since it means deadlock.
477 assert(qemu_coroutine_self() != req->co);
479 /* If the request is already (indirectly) waiting for us, or
480 * will wait for us as soon as it wakes up, then just go on
481 * (instead of producing a deadlock in the former case). */
482 if (!req->waiting_for) {
483 self->waiting_for = req;
484 qemu_co_queue_wait(&req->wait_queue);
485 self->waiting_for = NULL;
486 retry = true;
487 waited = true;
488 break;
492 } while (retry);
494 return waited;
497 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
498 size_t size)
500 if (size > BDRV_REQUEST_MAX_SECTORS << BDRV_SECTOR_BITS) {
501 return -EIO;
504 if (!bdrv_is_inserted(bs)) {
505 return -ENOMEDIUM;
508 if (offset < 0) {
509 return -EIO;
512 return 0;
515 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
516 int nb_sectors)
518 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
519 return -EIO;
522 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
523 nb_sectors * BDRV_SECTOR_SIZE);
526 typedef struct RwCo {
527 BlockDriverState *bs;
528 int64_t offset;
529 QEMUIOVector *qiov;
530 bool is_write;
531 int ret;
532 BdrvRequestFlags flags;
533 } RwCo;
535 static void coroutine_fn bdrv_rw_co_entry(void *opaque)
537 RwCo *rwco = opaque;
539 if (!rwco->is_write) {
540 rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset,
541 rwco->qiov->size, rwco->qiov,
542 rwco->flags);
543 } else {
544 rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset,
545 rwco->qiov->size, rwco->qiov,
546 rwco->flags);
551 * Process a vectored synchronous request using coroutines
553 static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset,
554 QEMUIOVector *qiov, bool is_write,
555 BdrvRequestFlags flags)
557 Coroutine *co;
558 RwCo rwco = {
559 .bs = bs,
560 .offset = offset,
561 .qiov = qiov,
562 .is_write = is_write,
563 .ret = NOT_DONE,
564 .flags = flags,
568 * In sync call context, when the vcpu is blocked, this throttling timer
569 * will not fire; so the I/O throttling function has to be disabled here
570 * if it has been enabled.
572 if (bs->io_limits_enabled) {
573 fprintf(stderr, "Disabling I/O throttling on '%s' due "
574 "to synchronous I/O.\n", bdrv_get_device_name(bs));
575 bdrv_io_limits_disable(bs);
578 if (qemu_in_coroutine()) {
579 /* Fast-path if already in coroutine context */
580 bdrv_rw_co_entry(&rwco);
581 } else {
582 AioContext *aio_context = bdrv_get_aio_context(bs);
584 co = qemu_coroutine_create(bdrv_rw_co_entry);
585 qemu_coroutine_enter(co, &rwco);
586 while (rwco.ret == NOT_DONE) {
587 aio_poll(aio_context, true);
590 return rwco.ret;
594 * Process a synchronous request using coroutines
596 static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
597 int nb_sectors, bool is_write, BdrvRequestFlags flags)
599 QEMUIOVector qiov;
600 struct iovec iov = {
601 .iov_base = (void *)buf,
602 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
605 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
606 return -EINVAL;
609 qemu_iovec_init_external(&qiov, &iov, 1);
610 return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS,
611 &qiov, is_write, flags);
614 /* return < 0 if error. See bdrv_write() for the return codes */
615 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
616 uint8_t *buf, int nb_sectors)
618 return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
621 /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
622 int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
623 uint8_t *buf, int nb_sectors)
625 bool enabled;
626 int ret;
628 enabled = bs->io_limits_enabled;
629 bs->io_limits_enabled = false;
630 ret = bdrv_read(bs, sector_num, buf, nb_sectors);
631 bs->io_limits_enabled = enabled;
632 return ret;
635 /* Return < 0 if error. Important errors are:
636 -EIO generic I/O error (may happen for all errors)
637 -ENOMEDIUM No media inserted.
638 -EINVAL Invalid sector number or nb_sectors
639 -EACCES Trying to write a read-only device
641 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
642 const uint8_t *buf, int nb_sectors)
644 return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
647 int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num,
648 int nb_sectors, BdrvRequestFlags flags)
650 return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,
651 BDRV_REQ_ZERO_WRITE | flags);
655 * Completely zero out a block device with the help of bdrv_write_zeroes.
656 * The operation is sped up by checking the block status and only writing
657 * zeroes to the device if they currently do not return zeroes. Optional
658 * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP).
660 * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
662 int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags)
664 int64_t target_sectors, ret, nb_sectors, sector_num = 0;
665 BlockDriverState *file;
666 int n;
668 target_sectors = bdrv_nb_sectors(bs);
669 if (target_sectors < 0) {
670 return target_sectors;
673 for (;;) {
674 nb_sectors = MIN(target_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
675 if (nb_sectors <= 0) {
676 return 0;
678 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n, &file);
679 if (ret < 0) {
680 error_report("error getting block status at sector %" PRId64 ": %s",
681 sector_num, strerror(-ret));
682 return ret;
684 if (ret & BDRV_BLOCK_ZERO) {
685 sector_num += n;
686 continue;
688 ret = bdrv_write_zeroes(bs, sector_num, n, flags);
689 if (ret < 0) {
690 error_report("error writing zeroes at sector %" PRId64 ": %s",
691 sector_num, strerror(-ret));
692 return ret;
694 sector_num += n;
698 int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes)
700 QEMUIOVector qiov;
701 struct iovec iov = {
702 .iov_base = (void *)buf,
703 .iov_len = bytes,
705 int ret;
707 if (bytes < 0) {
708 return -EINVAL;
711 qemu_iovec_init_external(&qiov, &iov, 1);
712 ret = bdrv_prwv_co(bs, offset, &qiov, false, 0);
713 if (ret < 0) {
714 return ret;
717 return bytes;
720 int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
722 int ret;
724 ret = bdrv_prwv_co(bs, offset, qiov, true, 0);
725 if (ret < 0) {
726 return ret;
729 return qiov->size;
732 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
733 const void *buf, int bytes)
735 QEMUIOVector qiov;
736 struct iovec iov = {
737 .iov_base = (void *) buf,
738 .iov_len = bytes,
741 if (bytes < 0) {
742 return -EINVAL;
745 qemu_iovec_init_external(&qiov, &iov, 1);
746 return bdrv_pwritev(bs, offset, &qiov);
750 * Writes to the file and ensures that no writes are reordered across this
751 * request (acts as a barrier)
753 * Returns 0 on success, -errno in error cases.
755 int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
756 const void *buf, int count)
758 int ret;
760 ret = bdrv_pwrite(bs, offset, buf, count);
761 if (ret < 0) {
762 return ret;
765 /* No flush needed for cache modes that already do it */
766 if (bs->enable_write_cache) {
767 bdrv_flush(bs);
770 return 0;
773 static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
774 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
776 /* Perform I/O through a temporary buffer so that users who scribble over
777 * their read buffer while the operation is in progress do not end up
778 * modifying the image file. This is critical for zero-copy guest I/O
779 * where anything might happen inside guest memory.
781 void *bounce_buffer;
783 BlockDriver *drv = bs->drv;
784 struct iovec iov;
785 QEMUIOVector bounce_qiov;
786 int64_t cluster_sector_num;
787 int cluster_nb_sectors;
788 size_t skip_bytes;
789 int ret;
791 /* Cover entire cluster so no additional backing file I/O is required when
792 * allocating cluster in the image file.
794 bdrv_round_to_clusters(bs, sector_num, nb_sectors,
795 &cluster_sector_num, &cluster_nb_sectors);
797 trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
798 cluster_sector_num, cluster_nb_sectors);
800 iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
801 iov.iov_base = bounce_buffer = qemu_try_blockalign(bs, iov.iov_len);
802 if (bounce_buffer == NULL) {
803 ret = -ENOMEM;
804 goto err;
807 qemu_iovec_init_external(&bounce_qiov, &iov, 1);
809 ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
810 &bounce_qiov);
811 if (ret < 0) {
812 goto err;
815 if (drv->bdrv_co_write_zeroes &&
816 buffer_is_zero(bounce_buffer, iov.iov_len)) {
817 ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
818 cluster_nb_sectors, 0);
819 } else {
820 /* This does not change the data on the disk, it is not necessary
821 * to flush even in cache=writethrough mode.
823 ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
824 &bounce_qiov);
827 if (ret < 0) {
828 /* It might be okay to ignore write errors for guest requests. If this
829 * is a deliberate copy-on-read then we don't want to ignore the error.
830 * Simply report it in all cases.
832 goto err;
835 skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
836 qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
837 nb_sectors * BDRV_SECTOR_SIZE);
839 err:
840 qemu_vfree(bounce_buffer);
841 return ret;
845 * Forwards an already correctly aligned request to the BlockDriver. This
846 * handles copy on read and zeroing after EOF; any other features must be
847 * implemented by the caller.
849 static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,
850 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
851 int64_t align, QEMUIOVector *qiov, int flags)
853 BlockDriver *drv = bs->drv;
854 int ret;
856 int64_t sector_num = offset >> BDRV_SECTOR_BITS;
857 unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
859 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
860 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
861 assert(!qiov || bytes == qiov->size);
863 /* Handle Copy on Read and associated serialisation */
864 if (flags & BDRV_REQ_COPY_ON_READ) {
865 /* If we touch the same cluster it counts as an overlap. This
866 * guarantees that allocating writes will be serialized and not race
867 * with each other for the same cluster. For example, in copy-on-read
868 * it ensures that the CoR read and write operations are atomic and
869 * guest writes cannot interleave between them. */
870 mark_request_serialising(req, bdrv_get_cluster_size(bs));
873 if (!(flags & BDRV_REQ_NO_SERIALISING)) {
874 wait_serialising_requests(req);
877 if (flags & BDRV_REQ_COPY_ON_READ) {
878 int pnum;
880 ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);
881 if (ret < 0) {
882 goto out;
885 if (!ret || pnum != nb_sectors) {
886 ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
887 goto out;
891 /* Forward the request to the BlockDriver */
892 if (!bs->zero_beyond_eof) {
893 ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
894 } else {
895 /* Read zeros after EOF */
896 int64_t total_sectors, max_nb_sectors;
898 total_sectors = bdrv_nb_sectors(bs);
899 if (total_sectors < 0) {
900 ret = total_sectors;
901 goto out;
904 max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num),
905 align >> BDRV_SECTOR_BITS);
906 if (nb_sectors < max_nb_sectors) {
907 ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
908 } else if (max_nb_sectors > 0) {
909 QEMUIOVector local_qiov;
911 qemu_iovec_init(&local_qiov, qiov->niov);
912 qemu_iovec_concat(&local_qiov, qiov, 0,
913 max_nb_sectors * BDRV_SECTOR_SIZE);
915 ret = drv->bdrv_co_readv(bs, sector_num, max_nb_sectors,
916 &local_qiov);
918 qemu_iovec_destroy(&local_qiov);
919 } else {
920 ret = 0;
923 /* Reading beyond end of file is supposed to produce zeroes */
924 if (ret == 0 && total_sectors < sector_num + nb_sectors) {
925 uint64_t offset = MAX(0, total_sectors - sector_num);
926 uint64_t bytes = (sector_num + nb_sectors - offset) *
927 BDRV_SECTOR_SIZE;
928 qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
932 out:
933 return ret;
937 * Handle a read request in coroutine context
939 int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
940 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
941 BdrvRequestFlags flags)
943 BlockDriver *drv = bs->drv;
944 BdrvTrackedRequest req;
946 /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
947 uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
948 uint8_t *head_buf = NULL;
949 uint8_t *tail_buf = NULL;
950 QEMUIOVector local_qiov;
951 bool use_local_qiov = false;
952 int ret;
954 if (!drv) {
955 return -ENOMEDIUM;
958 ret = bdrv_check_byte_request(bs, offset, bytes);
959 if (ret < 0) {
960 return ret;
963 /* Don't do copy-on-read if we read data before write operation */
964 if (bs->copy_on_read && !(flags & BDRV_REQ_NO_SERIALISING)) {
965 flags |= BDRV_REQ_COPY_ON_READ;
968 /* throttling disk I/O */
969 if (bs->io_limits_enabled) {
970 throttle_group_co_io_limits_intercept(bs, bytes, false);
973 /* Align read if necessary by padding qiov */
974 if (offset & (align - 1)) {
975 head_buf = qemu_blockalign(bs, align);
976 qemu_iovec_init(&local_qiov, qiov->niov + 2);
977 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
978 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
979 use_local_qiov = true;
981 bytes += offset & (align - 1);
982 offset = offset & ~(align - 1);
985 if ((offset + bytes) & (align - 1)) {
986 if (!use_local_qiov) {
987 qemu_iovec_init(&local_qiov, qiov->niov + 1);
988 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
989 use_local_qiov = true;
991 tail_buf = qemu_blockalign(bs, align);
992 qemu_iovec_add(&local_qiov, tail_buf,
993 align - ((offset + bytes) & (align - 1)));
995 bytes = ROUND_UP(bytes, align);
998 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_READ);
999 ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align,
1000 use_local_qiov ? &local_qiov : qiov,
1001 flags);
1002 tracked_request_end(&req);
1004 if (use_local_qiov) {
1005 qemu_iovec_destroy(&local_qiov);
1006 qemu_vfree(head_buf);
1007 qemu_vfree(tail_buf);
1010 return ret;
1013 static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
1014 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
1015 BdrvRequestFlags flags)
1017 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
1018 return -EINVAL;
1021 return bdrv_co_do_preadv(bs, sector_num << BDRV_SECTOR_BITS,
1022 nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
1025 int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1026 int nb_sectors, QEMUIOVector *qiov)
1028 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1030 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
1033 int coroutine_fn bdrv_co_readv_no_serialising(BlockDriverState *bs,
1034 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
1036 trace_bdrv_co_readv_no_serialising(bs, sector_num, nb_sectors);
1038 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
1039 BDRV_REQ_NO_SERIALISING);
1042 int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
1043 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
1045 trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
1047 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
1048 BDRV_REQ_COPY_ON_READ);
1051 #define MAX_WRITE_ZEROES_BOUNCE_BUFFER 32768
1053 static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
1054 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
1056 BlockDriver *drv = bs->drv;
1057 QEMUIOVector qiov;
1058 struct iovec iov = {0};
1059 int ret = 0;
1061 int max_write_zeroes = MIN_NON_ZERO(bs->bl.max_write_zeroes,
1062 BDRV_REQUEST_MAX_SECTORS);
1064 while (nb_sectors > 0 && !ret) {
1065 int num = nb_sectors;
1067 /* Align request. Block drivers can expect the "bulk" of the request
1068 * to be aligned.
1070 if (bs->bl.write_zeroes_alignment
1071 && num > bs->bl.write_zeroes_alignment) {
1072 if (sector_num % bs->bl.write_zeroes_alignment != 0) {
1073 /* Make a small request up to the first aligned sector. */
1074 num = bs->bl.write_zeroes_alignment;
1075 num -= sector_num % bs->bl.write_zeroes_alignment;
1076 } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) {
1077 /* Shorten the request to the last aligned sector. num cannot
1078 * underflow because num > bs->bl.write_zeroes_alignment.
1080 num -= (sector_num + num) % bs->bl.write_zeroes_alignment;
1084 /* limit request size */
1085 if (num > max_write_zeroes) {
1086 num = max_write_zeroes;
1089 ret = -ENOTSUP;
1090 /* First try the efficient write zeroes operation */
1091 if (drv->bdrv_co_write_zeroes) {
1092 ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags);
1095 if (ret == -ENOTSUP) {
1096 /* Fall back to bounce buffer if write zeroes is unsupported */
1097 int max_xfer_len = MIN_NON_ZERO(bs->bl.max_transfer_length,
1098 MAX_WRITE_ZEROES_BOUNCE_BUFFER);
1099 num = MIN(num, max_xfer_len);
1100 iov.iov_len = num * BDRV_SECTOR_SIZE;
1101 if (iov.iov_base == NULL) {
1102 iov.iov_base = qemu_try_blockalign(bs, num * BDRV_SECTOR_SIZE);
1103 if (iov.iov_base == NULL) {
1104 ret = -ENOMEM;
1105 goto fail;
1107 memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE);
1109 qemu_iovec_init_external(&qiov, &iov, 1);
1111 ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov);
1113 /* Keep bounce buffer around if it is big enough for all
1114 * all future requests.
1116 if (num < max_xfer_len) {
1117 qemu_vfree(iov.iov_base);
1118 iov.iov_base = NULL;
1122 sector_num += num;
1123 nb_sectors -= num;
1126 fail:
1127 qemu_vfree(iov.iov_base);
1128 return ret;
1132 * Forwards an already correctly aligned write request to the BlockDriver.
1134 static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,
1135 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
1136 QEMUIOVector *qiov, int flags)
1138 BlockDriver *drv = bs->drv;
1139 bool waited;
1140 int ret;
1142 int64_t sector_num = offset >> BDRV_SECTOR_BITS;
1143 unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
1145 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1146 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1147 assert(!qiov || bytes == qiov->size);
1149 waited = wait_serialising_requests(req);
1150 assert(!waited || !req->serialising);
1151 assert(req->overlap_offset <= offset);
1152 assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
1154 ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
1156 if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
1157 !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_write_zeroes &&
1158 qemu_iovec_is_zero(qiov)) {
1159 flags |= BDRV_REQ_ZERO_WRITE;
1160 if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
1161 flags |= BDRV_REQ_MAY_UNMAP;
1165 if (ret < 0) {
1166 /* Do nothing, write notifier decided to fail this request */
1167 } else if (flags & BDRV_REQ_ZERO_WRITE) {
1168 bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO);
1169 ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags);
1170 } else {
1171 bdrv_debug_event(bs, BLKDBG_PWRITEV);
1172 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
1174 bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE);
1176 if (ret == 0 && !bs->enable_write_cache) {
1177 ret = bdrv_co_flush(bs);
1180 bdrv_set_dirty(bs, sector_num, nb_sectors);
1182 if (bs->wr_highest_offset < offset + bytes) {
1183 bs->wr_highest_offset = offset + bytes;
1186 if (ret >= 0) {
1187 bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);
1190 return ret;
1193 static int coroutine_fn bdrv_co_do_zero_pwritev(BlockDriverState *bs,
1194 int64_t offset,
1195 unsigned int bytes,
1196 BdrvRequestFlags flags,
1197 BdrvTrackedRequest *req)
1199 uint8_t *buf = NULL;
1200 QEMUIOVector local_qiov;
1201 struct iovec iov;
1202 uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
1203 unsigned int head_padding_bytes, tail_padding_bytes;
1204 int ret = 0;
1206 head_padding_bytes = offset & (align - 1);
1207 tail_padding_bytes = align - ((offset + bytes) & (align - 1));
1210 assert(flags & BDRV_REQ_ZERO_WRITE);
1211 if (head_padding_bytes || tail_padding_bytes) {
1212 buf = qemu_blockalign(bs, align);
1213 iov = (struct iovec) {
1214 .iov_base = buf,
1215 .iov_len = align,
1217 qemu_iovec_init_external(&local_qiov, &iov, 1);
1219 if (head_padding_bytes) {
1220 uint64_t zero_bytes = MIN(bytes, align - head_padding_bytes);
1222 /* RMW the unaligned part before head. */
1223 mark_request_serialising(req, align);
1224 wait_serialising_requests(req);
1225 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1226 ret = bdrv_aligned_preadv(bs, req, offset & ~(align - 1), align,
1227 align, &local_qiov, 0);
1228 if (ret < 0) {
1229 goto fail;
1231 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1233 memset(buf + head_padding_bytes, 0, zero_bytes);
1234 ret = bdrv_aligned_pwritev(bs, req, offset & ~(align - 1), align,
1235 &local_qiov,
1236 flags & ~BDRV_REQ_ZERO_WRITE);
1237 if (ret < 0) {
1238 goto fail;
1240 offset += zero_bytes;
1241 bytes -= zero_bytes;
1244 assert(!bytes || (offset & (align - 1)) == 0);
1245 if (bytes >= align) {
1246 /* Write the aligned part in the middle. */
1247 uint64_t aligned_bytes = bytes & ~(align - 1);
1248 ret = bdrv_aligned_pwritev(bs, req, offset, aligned_bytes,
1249 NULL, flags);
1250 if (ret < 0) {
1251 goto fail;
1253 bytes -= aligned_bytes;
1254 offset += aligned_bytes;
1257 assert(!bytes || (offset & (align - 1)) == 0);
1258 if (bytes) {
1259 assert(align == tail_padding_bytes + bytes);
1260 /* RMW the unaligned part after tail. */
1261 mark_request_serialising(req, align);
1262 wait_serialising_requests(req);
1263 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1264 ret = bdrv_aligned_preadv(bs, req, offset, align,
1265 align, &local_qiov, 0);
1266 if (ret < 0) {
1267 goto fail;
1269 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1271 memset(buf, 0, bytes);
1272 ret = bdrv_aligned_pwritev(bs, req, offset, align,
1273 &local_qiov, flags & ~BDRV_REQ_ZERO_WRITE);
1275 fail:
1276 qemu_vfree(buf);
1277 return ret;
1282 * Handle a write request in coroutine context
1284 static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
1285 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1286 BdrvRequestFlags flags)
1288 BdrvTrackedRequest req;
1289 /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
1290 uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
1291 uint8_t *head_buf = NULL;
1292 uint8_t *tail_buf = NULL;
1293 QEMUIOVector local_qiov;
1294 bool use_local_qiov = false;
1295 int ret;
1297 if (!bs->drv) {
1298 return -ENOMEDIUM;
1300 if (bs->read_only) {
1301 return -EPERM;
1303 assert(!(bs->open_flags & BDRV_O_INACTIVE));
1305 ret = bdrv_check_byte_request(bs, offset, bytes);
1306 if (ret < 0) {
1307 return ret;
1310 /* throttling disk I/O */
1311 if (bs->io_limits_enabled) {
1312 throttle_group_co_io_limits_intercept(bs, bytes, true);
1316 * Align write if necessary by performing a read-modify-write cycle.
1317 * Pad qiov with the read parts and be sure to have a tracked request not
1318 * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
1320 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);
1322 if (!qiov) {
1323 ret = bdrv_co_do_zero_pwritev(bs, offset, bytes, flags, &req);
1324 goto out;
1327 if (offset & (align - 1)) {
1328 QEMUIOVector head_qiov;
1329 struct iovec head_iov;
1331 mark_request_serialising(&req, align);
1332 wait_serialising_requests(&req);
1334 head_buf = qemu_blockalign(bs, align);
1335 head_iov = (struct iovec) {
1336 .iov_base = head_buf,
1337 .iov_len = align,
1339 qemu_iovec_init_external(&head_qiov, &head_iov, 1);
1341 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1342 ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align,
1343 align, &head_qiov, 0);
1344 if (ret < 0) {
1345 goto fail;
1347 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1349 qemu_iovec_init(&local_qiov, qiov->niov + 2);
1350 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
1351 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1352 use_local_qiov = true;
1354 bytes += offset & (align - 1);
1355 offset = offset & ~(align - 1);
1358 if ((offset + bytes) & (align - 1)) {
1359 QEMUIOVector tail_qiov;
1360 struct iovec tail_iov;
1361 size_t tail_bytes;
1362 bool waited;
1364 mark_request_serialising(&req, align);
1365 waited = wait_serialising_requests(&req);
1366 assert(!waited || !use_local_qiov);
1368 tail_buf = qemu_blockalign(bs, align);
1369 tail_iov = (struct iovec) {
1370 .iov_base = tail_buf,
1371 .iov_len = align,
1373 qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);
1375 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1376 ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align,
1377 align, &tail_qiov, 0);
1378 if (ret < 0) {
1379 goto fail;
1381 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1383 if (!use_local_qiov) {
1384 qemu_iovec_init(&local_qiov, qiov->niov + 1);
1385 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1386 use_local_qiov = true;
1389 tail_bytes = (offset + bytes) & (align - 1);
1390 qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
1392 bytes = ROUND_UP(bytes, align);
1395 ret = bdrv_aligned_pwritev(bs, &req, offset, bytes,
1396 use_local_qiov ? &local_qiov : qiov,
1397 flags);
1399 fail:
1401 if (use_local_qiov) {
1402 qemu_iovec_destroy(&local_qiov);
1404 qemu_vfree(head_buf);
1405 qemu_vfree(tail_buf);
1406 out:
1407 tracked_request_end(&req);
1408 return ret;
1411 static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
1412 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
1413 BdrvRequestFlags flags)
1415 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
1416 return -EINVAL;
1419 return bdrv_co_do_pwritev(bs, sector_num << BDRV_SECTOR_BITS,
1420 nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
1423 int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1424 int nb_sectors, QEMUIOVector *qiov)
1426 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1428 return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
1431 int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
1432 int64_t sector_num, int nb_sectors,
1433 BdrvRequestFlags flags)
1435 trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags);
1437 if (!(bs->open_flags & BDRV_O_UNMAP)) {
1438 flags &= ~BDRV_REQ_MAY_UNMAP;
1441 return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
1442 BDRV_REQ_ZERO_WRITE | flags);
1445 typedef struct BdrvCoGetBlockStatusData {
1446 BlockDriverState *bs;
1447 BlockDriverState *base;
1448 BlockDriverState **file;
1449 int64_t sector_num;
1450 int nb_sectors;
1451 int *pnum;
1452 int64_t ret;
1453 bool done;
1454 } BdrvCoGetBlockStatusData;
1457 * Returns the allocation status of the specified sectors.
1458 * Drivers not implementing the functionality are assumed to not support
1459 * backing files, hence all their sectors are reported as allocated.
1461 * If 'sector_num' is beyond the end of the disk image the return value is 0
1462 * and 'pnum' is set to 0.
1464 * 'pnum' is set to the number of sectors (including and immediately following
1465 * the specified sector) that are known to be in the same
1466 * allocated/unallocated state.
1468 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1469 * beyond the end of the disk image it will be clamped.
1471 * If returned value is positive and BDRV_BLOCK_OFFSET_VALID bit is set, 'file'
1472 * points to the BDS which the sector range is allocated in.
1474 static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
1475 int64_t sector_num,
1476 int nb_sectors, int *pnum,
1477 BlockDriverState **file)
1479 int64_t total_sectors;
1480 int64_t n;
1481 int64_t ret, ret2;
1483 total_sectors = bdrv_nb_sectors(bs);
1484 if (total_sectors < 0) {
1485 return total_sectors;
1488 if (sector_num >= total_sectors) {
1489 *pnum = 0;
1490 return 0;
1493 n = total_sectors - sector_num;
1494 if (n < nb_sectors) {
1495 nb_sectors = n;
1498 if (!bs->drv->bdrv_co_get_block_status) {
1499 *pnum = nb_sectors;
1500 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
1501 if (bs->drv->protocol_name) {
1502 ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
1504 return ret;
1507 *file = NULL;
1508 ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum,
1509 file);
1510 if (ret < 0) {
1511 *pnum = 0;
1512 return ret;
1515 if (ret & BDRV_BLOCK_RAW) {
1516 assert(ret & BDRV_BLOCK_OFFSET_VALID);
1517 return bdrv_get_block_status(bs->file->bs, ret >> BDRV_SECTOR_BITS,
1518 *pnum, pnum, file);
1521 if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
1522 ret |= BDRV_BLOCK_ALLOCATED;
1523 } else {
1524 if (bdrv_unallocated_blocks_are_zero(bs)) {
1525 ret |= BDRV_BLOCK_ZERO;
1526 } else if (bs->backing) {
1527 BlockDriverState *bs2 = bs->backing->bs;
1528 int64_t nb_sectors2 = bdrv_nb_sectors(bs2);
1529 if (nb_sectors2 >= 0 && sector_num >= nb_sectors2) {
1530 ret |= BDRV_BLOCK_ZERO;
1535 if (*file && *file != bs &&
1536 (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
1537 (ret & BDRV_BLOCK_OFFSET_VALID)) {
1538 BlockDriverState *file2;
1539 int file_pnum;
1541 ret2 = bdrv_co_get_block_status(*file, ret >> BDRV_SECTOR_BITS,
1542 *pnum, &file_pnum, &file2);
1543 if (ret2 >= 0) {
1544 /* Ignore errors. This is just providing extra information, it
1545 * is useful but not necessary.
1547 if (!file_pnum) {
1548 /* !file_pnum indicates an offset at or beyond the EOF; it is
1549 * perfectly valid for the format block driver to point to such
1550 * offsets, so catch it and mark everything as zero */
1551 ret |= BDRV_BLOCK_ZERO;
1552 } else {
1553 /* Limit request to the range reported by the protocol driver */
1554 *pnum = file_pnum;
1555 ret |= (ret2 & BDRV_BLOCK_ZERO);
1560 return ret;
1563 static int64_t coroutine_fn bdrv_co_get_block_status_above(BlockDriverState *bs,
1564 BlockDriverState *base,
1565 int64_t sector_num,
1566 int nb_sectors,
1567 int *pnum,
1568 BlockDriverState **file)
1570 BlockDriverState *p;
1571 int64_t ret = 0;
1573 assert(bs != base);
1574 for (p = bs; p != base; p = backing_bs(p)) {
1575 ret = bdrv_co_get_block_status(p, sector_num, nb_sectors, pnum, file);
1576 if (ret < 0 || ret & BDRV_BLOCK_ALLOCATED) {
1577 break;
1579 /* [sector_num, pnum] unallocated on this layer, which could be only
1580 * the first part of [sector_num, nb_sectors]. */
1581 nb_sectors = MIN(nb_sectors, *pnum);
1583 return ret;
1586 /* Coroutine wrapper for bdrv_get_block_status_above() */
1587 static void coroutine_fn bdrv_get_block_status_above_co_entry(void *opaque)
1589 BdrvCoGetBlockStatusData *data = opaque;
1591 data->ret = bdrv_co_get_block_status_above(data->bs, data->base,
1592 data->sector_num,
1593 data->nb_sectors,
1594 data->pnum,
1595 data->file);
1596 data->done = true;
1600 * Synchronous wrapper around bdrv_co_get_block_status_above().
1602 * See bdrv_co_get_block_status_above() for details.
1604 int64_t bdrv_get_block_status_above(BlockDriverState *bs,
1605 BlockDriverState *base,
1606 int64_t sector_num,
1607 int nb_sectors, int *pnum,
1608 BlockDriverState **file)
1610 Coroutine *co;
1611 BdrvCoGetBlockStatusData data = {
1612 .bs = bs,
1613 .base = base,
1614 .file = file,
1615 .sector_num = sector_num,
1616 .nb_sectors = nb_sectors,
1617 .pnum = pnum,
1618 .done = false,
1621 if (qemu_in_coroutine()) {
1622 /* Fast-path if already in coroutine context */
1623 bdrv_get_block_status_above_co_entry(&data);
1624 } else {
1625 AioContext *aio_context = bdrv_get_aio_context(bs);
1627 co = qemu_coroutine_create(bdrv_get_block_status_above_co_entry);
1628 qemu_coroutine_enter(co, &data);
1629 while (!data.done) {
1630 aio_poll(aio_context, true);
1633 return data.ret;
1636 int64_t bdrv_get_block_status(BlockDriverState *bs,
1637 int64_t sector_num,
1638 int nb_sectors, int *pnum,
1639 BlockDriverState **file)
1641 return bdrv_get_block_status_above(bs, backing_bs(bs),
1642 sector_num, nb_sectors, pnum, file);
1645 int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
1646 int nb_sectors, int *pnum)
1648 BlockDriverState *file;
1649 int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum,
1650 &file);
1651 if (ret < 0) {
1652 return ret;
1654 return !!(ret & BDRV_BLOCK_ALLOCATED);
1658 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
1660 * Return true if the given sector is allocated in any image between
1661 * BASE and TOP (inclusive). BASE can be NULL to check if the given
1662 * sector is allocated in any image of the chain. Return false otherwise.
1664 * 'pnum' is set to the number of sectors (including and immediately following
1665 * the specified sector) that are known to be in the same
1666 * allocated/unallocated state.
1669 int bdrv_is_allocated_above(BlockDriverState *top,
1670 BlockDriverState *base,
1671 int64_t sector_num,
1672 int nb_sectors, int *pnum)
1674 BlockDriverState *intermediate;
1675 int ret, n = nb_sectors;
1677 intermediate = top;
1678 while (intermediate && intermediate != base) {
1679 int pnum_inter;
1680 ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
1681 &pnum_inter);
1682 if (ret < 0) {
1683 return ret;
1684 } else if (ret) {
1685 *pnum = pnum_inter;
1686 return 1;
1690 * [sector_num, nb_sectors] is unallocated on top but intermediate
1691 * might have
1693 * [sector_num+x, nr_sectors] allocated.
1695 if (n > pnum_inter &&
1696 (intermediate == top ||
1697 sector_num + pnum_inter < intermediate->total_sectors)) {
1698 n = pnum_inter;
1701 intermediate = backing_bs(intermediate);
1704 *pnum = n;
1705 return 0;
1708 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1709 const uint8_t *buf, int nb_sectors)
1711 BlockDriver *drv = bs->drv;
1712 int ret;
1714 if (!drv) {
1715 return -ENOMEDIUM;
1717 if (!drv->bdrv_write_compressed) {
1718 return -ENOTSUP;
1720 ret = bdrv_check_request(bs, sector_num, nb_sectors);
1721 if (ret < 0) {
1722 return ret;
1725 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
1727 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1730 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1731 int64_t pos, int size)
1733 QEMUIOVector qiov;
1734 struct iovec iov = {
1735 .iov_base = (void *) buf,
1736 .iov_len = size,
1739 qemu_iovec_init_external(&qiov, &iov, 1);
1740 return bdrv_writev_vmstate(bs, &qiov, pos);
1743 int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
1745 BlockDriver *drv = bs->drv;
1747 if (!drv) {
1748 return -ENOMEDIUM;
1749 } else if (drv->bdrv_save_vmstate) {
1750 return drv->bdrv_save_vmstate(bs, qiov, pos);
1751 } else if (bs->file) {
1752 return bdrv_writev_vmstate(bs->file->bs, qiov, pos);
1755 return -ENOTSUP;
1758 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1759 int64_t pos, int size)
1761 BlockDriver *drv = bs->drv;
1762 if (!drv)
1763 return -ENOMEDIUM;
1764 if (drv->bdrv_load_vmstate)
1765 return drv->bdrv_load_vmstate(bs, buf, pos, size);
1766 if (bs->file)
1767 return bdrv_load_vmstate(bs->file->bs, buf, pos, size);
1768 return -ENOTSUP;
1771 /**************************************************************/
1772 /* async I/Os */
1774 BlockAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
1775 QEMUIOVector *qiov, int nb_sectors,
1776 BlockCompletionFunc *cb, void *opaque)
1778 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
1780 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
1781 cb, opaque, false);
1784 BlockAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
1785 QEMUIOVector *qiov, int nb_sectors,
1786 BlockCompletionFunc *cb, void *opaque)
1788 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
1790 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
1791 cb, opaque, true);
1794 BlockAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs,
1795 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags,
1796 BlockCompletionFunc *cb, void *opaque)
1798 trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque);
1800 return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors,
1801 BDRV_REQ_ZERO_WRITE | flags,
1802 cb, opaque, true);
1806 typedef struct MultiwriteCB {
1807 int error;
1808 int num_requests;
1809 int num_callbacks;
1810 struct {
1811 BlockCompletionFunc *cb;
1812 void *opaque;
1813 QEMUIOVector *free_qiov;
1814 } callbacks[];
1815 } MultiwriteCB;
1817 static void multiwrite_user_cb(MultiwriteCB *mcb)
1819 int i;
1821 for (i = 0; i < mcb->num_callbacks; i++) {
1822 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
1823 if (mcb->callbacks[i].free_qiov) {
1824 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
1826 g_free(mcb->callbacks[i].free_qiov);
1830 static void multiwrite_cb(void *opaque, int ret)
1832 MultiwriteCB *mcb = opaque;
1834 trace_multiwrite_cb(mcb, ret);
1836 if (ret < 0 && !mcb->error) {
1837 mcb->error = ret;
1840 mcb->num_requests--;
1841 if (mcb->num_requests == 0) {
1842 multiwrite_user_cb(mcb);
1843 g_free(mcb);
1847 static int multiwrite_req_compare(const void *a, const void *b)
1849 const BlockRequest *req1 = a, *req2 = b;
1852 * Note that we can't simply subtract req2->sector from req1->sector
1853 * here as that could overflow the return value.
1855 if (req1->sector > req2->sector) {
1856 return 1;
1857 } else if (req1->sector < req2->sector) {
1858 return -1;
1859 } else {
1860 return 0;
1865 * Takes a bunch of requests and tries to merge them. Returns the number of
1866 * requests that remain after merging.
1868 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
1869 int num_reqs, MultiwriteCB *mcb)
1871 int i, outidx;
1873 // Sort requests by start sector
1874 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
1876 // Check if adjacent requests touch the same clusters. If so, combine them,
1877 // filling up gaps with zero sectors.
1878 outidx = 0;
1879 for (i = 1; i < num_reqs; i++) {
1880 int merge = 0;
1881 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
1883 // Handle exactly sequential writes and overlapping writes.
1884 if (reqs[i].sector <= oldreq_last) {
1885 merge = 1;
1888 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 >
1889 bs->bl.max_iov) {
1890 merge = 0;
1893 if (bs->bl.max_transfer_length && reqs[outidx].nb_sectors +
1894 reqs[i].nb_sectors > bs->bl.max_transfer_length) {
1895 merge = 0;
1898 if (merge) {
1899 size_t size;
1900 QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
1901 qemu_iovec_init(qiov,
1902 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
1904 // Add the first request to the merged one. If the requests are
1905 // overlapping, drop the last sectors of the first request.
1906 size = (reqs[i].sector - reqs[outidx].sector) << 9;
1907 qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
1909 // We should need to add any zeros between the two requests
1910 assert (reqs[i].sector <= oldreq_last);
1912 // Add the second request
1913 qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
1915 // Add tail of first request, if necessary
1916 if (qiov->size < reqs[outidx].qiov->size) {
1917 qemu_iovec_concat(qiov, reqs[outidx].qiov, qiov->size,
1918 reqs[outidx].qiov->size - qiov->size);
1921 reqs[outidx].nb_sectors = qiov->size >> 9;
1922 reqs[outidx].qiov = qiov;
1924 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
1925 } else {
1926 outidx++;
1927 reqs[outidx].sector = reqs[i].sector;
1928 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
1929 reqs[outidx].qiov = reqs[i].qiov;
1933 if (bs->blk) {
1934 block_acct_merge_done(blk_get_stats(bs->blk), BLOCK_ACCT_WRITE,
1935 num_reqs - outidx - 1);
1938 return outidx + 1;
1942 * Submit multiple AIO write requests at once.
1944 * On success, the function returns 0 and all requests in the reqs array have
1945 * been submitted. In error case this function returns -1, and any of the
1946 * requests may or may not be submitted yet. In particular, this means that the
1947 * callback will be called for some of the requests, for others it won't. The
1948 * caller must check the error field of the BlockRequest to wait for the right
1949 * callbacks (if error != 0, no callback will be called).
1951 * The implementation may modify the contents of the reqs array, e.g. to merge
1952 * requests. However, the fields opaque and error are left unmodified as they
1953 * are used to signal failure for a single request to the caller.
1955 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
1957 MultiwriteCB *mcb;
1958 int i;
1960 /* don't submit writes if we don't have a medium */
1961 if (bs->drv == NULL) {
1962 for (i = 0; i < num_reqs; i++) {
1963 reqs[i].error = -ENOMEDIUM;
1965 return -1;
1968 if (num_reqs == 0) {
1969 return 0;
1972 // Create MultiwriteCB structure
1973 mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
1974 mcb->num_requests = 0;
1975 mcb->num_callbacks = num_reqs;
1977 for (i = 0; i < num_reqs; i++) {
1978 mcb->callbacks[i].cb = reqs[i].cb;
1979 mcb->callbacks[i].opaque = reqs[i].opaque;
1982 // Check for mergable requests
1983 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
1985 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
1987 /* Run the aio requests. */
1988 mcb->num_requests = num_reqs;
1989 for (i = 0; i < num_reqs; i++) {
1990 bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov,
1991 reqs[i].nb_sectors, reqs[i].flags,
1992 multiwrite_cb, mcb,
1993 true);
1996 return 0;
1999 void bdrv_aio_cancel(BlockAIOCB *acb)
2001 qemu_aio_ref(acb);
2002 bdrv_aio_cancel_async(acb);
2003 while (acb->refcnt > 1) {
2004 if (acb->aiocb_info->get_aio_context) {
2005 aio_poll(acb->aiocb_info->get_aio_context(acb), true);
2006 } else if (acb->bs) {
2007 aio_poll(bdrv_get_aio_context(acb->bs), true);
2008 } else {
2009 abort();
2012 qemu_aio_unref(acb);
2015 /* Async version of aio cancel. The caller is not blocked if the acb implements
2016 * cancel_async, otherwise we do nothing and let the request normally complete.
2017 * In either case the completion callback must be called. */
2018 void bdrv_aio_cancel_async(BlockAIOCB *acb)
2020 if (acb->aiocb_info->cancel_async) {
2021 acb->aiocb_info->cancel_async(acb);
2025 /**************************************************************/
2026 /* async block device emulation */
2028 typedef struct BlockAIOCBSync {
2029 BlockAIOCB common;
2030 QEMUBH *bh;
2031 int ret;
2032 /* vector translation state */
2033 QEMUIOVector *qiov;
2034 uint8_t *bounce;
2035 int is_write;
2036 } BlockAIOCBSync;
2038 static const AIOCBInfo bdrv_em_aiocb_info = {
2039 .aiocb_size = sizeof(BlockAIOCBSync),
2042 static void bdrv_aio_bh_cb(void *opaque)
2044 BlockAIOCBSync *acb = opaque;
2046 if (!acb->is_write && acb->ret >= 0) {
2047 qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
2049 qemu_vfree(acb->bounce);
2050 acb->common.cb(acb->common.opaque, acb->ret);
2051 qemu_bh_delete(acb->bh);
2052 acb->bh = NULL;
2053 qemu_aio_unref(acb);
2056 static BlockAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2057 int64_t sector_num,
2058 QEMUIOVector *qiov,
2059 int nb_sectors,
2060 BlockCompletionFunc *cb,
2061 void *opaque,
2062 int is_write)
2065 BlockAIOCBSync *acb;
2067 acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
2068 acb->is_write = is_write;
2069 acb->qiov = qiov;
2070 acb->bounce = qemu_try_blockalign(bs, qiov->size);
2071 acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_aio_bh_cb, acb);
2073 if (acb->bounce == NULL) {
2074 acb->ret = -ENOMEM;
2075 } else if (is_write) {
2076 qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
2077 acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2078 } else {
2079 acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2082 qemu_bh_schedule(acb->bh);
2084 return &acb->common;
2087 static BlockAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2088 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2089 BlockCompletionFunc *cb, void *opaque)
2091 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
2094 static BlockAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2095 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2096 BlockCompletionFunc *cb, void *opaque)
2098 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2102 typedef struct BlockAIOCBCoroutine {
2103 BlockAIOCB common;
2104 BlockRequest req;
2105 bool is_write;
2106 bool need_bh;
2107 bool *done;
2108 QEMUBH* bh;
2109 } BlockAIOCBCoroutine;
2111 static const AIOCBInfo bdrv_em_co_aiocb_info = {
2112 .aiocb_size = sizeof(BlockAIOCBCoroutine),
2115 static void bdrv_co_complete(BlockAIOCBCoroutine *acb)
2117 if (!acb->need_bh) {
2118 acb->common.cb(acb->common.opaque, acb->req.error);
2119 qemu_aio_unref(acb);
2123 static void bdrv_co_em_bh(void *opaque)
2125 BlockAIOCBCoroutine *acb = opaque;
2127 assert(!acb->need_bh);
2128 qemu_bh_delete(acb->bh);
2129 bdrv_co_complete(acb);
2132 static void bdrv_co_maybe_schedule_bh(BlockAIOCBCoroutine *acb)
2134 acb->need_bh = false;
2135 if (acb->req.error != -EINPROGRESS) {
2136 BlockDriverState *bs = acb->common.bs;
2138 acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb);
2139 qemu_bh_schedule(acb->bh);
2143 /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
2144 static void coroutine_fn bdrv_co_do_rw(void *opaque)
2146 BlockAIOCBCoroutine *acb = opaque;
2147 BlockDriverState *bs = acb->common.bs;
2149 if (!acb->is_write) {
2150 acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
2151 acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
2152 } else {
2153 acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
2154 acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
2157 bdrv_co_complete(acb);
2160 static BlockAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
2161 int64_t sector_num,
2162 QEMUIOVector *qiov,
2163 int nb_sectors,
2164 BdrvRequestFlags flags,
2165 BlockCompletionFunc *cb,
2166 void *opaque,
2167 bool is_write)
2169 Coroutine *co;
2170 BlockAIOCBCoroutine *acb;
2172 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
2173 acb->need_bh = true;
2174 acb->req.error = -EINPROGRESS;
2175 acb->req.sector = sector_num;
2176 acb->req.nb_sectors = nb_sectors;
2177 acb->req.qiov = qiov;
2178 acb->req.flags = flags;
2179 acb->is_write = is_write;
2181 co = qemu_coroutine_create(bdrv_co_do_rw);
2182 qemu_coroutine_enter(co, acb);
2184 bdrv_co_maybe_schedule_bh(acb);
2185 return &acb->common;
2188 static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
2190 BlockAIOCBCoroutine *acb = opaque;
2191 BlockDriverState *bs = acb->common.bs;
2193 acb->req.error = bdrv_co_flush(bs);
2194 bdrv_co_complete(acb);
2197 BlockAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2198 BlockCompletionFunc *cb, void *opaque)
2200 trace_bdrv_aio_flush(bs, opaque);
2202 Coroutine *co;
2203 BlockAIOCBCoroutine *acb;
2205 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
2206 acb->need_bh = true;
2207 acb->req.error = -EINPROGRESS;
2209 co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
2210 qemu_coroutine_enter(co, acb);
2212 bdrv_co_maybe_schedule_bh(acb);
2213 return &acb->common;
2216 static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
2218 BlockAIOCBCoroutine *acb = opaque;
2219 BlockDriverState *bs = acb->common.bs;
2221 acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
2222 bdrv_co_complete(acb);
2225 BlockAIOCB *bdrv_aio_discard(BlockDriverState *bs,
2226 int64_t sector_num, int nb_sectors,
2227 BlockCompletionFunc *cb, void *opaque)
2229 Coroutine *co;
2230 BlockAIOCBCoroutine *acb;
2232 trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
2234 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
2235 acb->need_bh = true;
2236 acb->req.error = -EINPROGRESS;
2237 acb->req.sector = sector_num;
2238 acb->req.nb_sectors = nb_sectors;
2239 co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
2240 qemu_coroutine_enter(co, acb);
2242 bdrv_co_maybe_schedule_bh(acb);
2243 return &acb->common;
2246 void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
2247 BlockCompletionFunc *cb, void *opaque)
2249 BlockAIOCB *acb;
2251 acb = g_malloc(aiocb_info->aiocb_size);
2252 acb->aiocb_info = aiocb_info;
2253 acb->bs = bs;
2254 acb->cb = cb;
2255 acb->opaque = opaque;
2256 acb->refcnt = 1;
2257 return acb;
2260 void qemu_aio_ref(void *p)
2262 BlockAIOCB *acb = p;
2263 acb->refcnt++;
2266 void qemu_aio_unref(void *p)
2268 BlockAIOCB *acb = p;
2269 assert(acb->refcnt > 0);
2270 if (--acb->refcnt == 0) {
2271 g_free(acb);
2275 /**************************************************************/
2276 /* Coroutine block device emulation */
2278 typedef struct CoroutineIOCompletion {
2279 Coroutine *coroutine;
2280 int ret;
2281 } CoroutineIOCompletion;
2283 static void bdrv_co_io_em_complete(void *opaque, int ret)
2285 CoroutineIOCompletion *co = opaque;
2287 co->ret = ret;
2288 qemu_coroutine_enter(co->coroutine, NULL);
2291 static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
2292 int nb_sectors, QEMUIOVector *iov,
2293 bool is_write)
2295 CoroutineIOCompletion co = {
2296 .coroutine = qemu_coroutine_self(),
2298 BlockAIOCB *acb;
2300 if (is_write) {
2301 acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
2302 bdrv_co_io_em_complete, &co);
2303 } else {
2304 acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
2305 bdrv_co_io_em_complete, &co);
2308 trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
2309 if (!acb) {
2310 return -EIO;
2312 qemu_coroutine_yield();
2314 return co.ret;
2317 static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
2318 int64_t sector_num, int nb_sectors,
2319 QEMUIOVector *iov)
2321 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
2324 static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
2325 int64_t sector_num, int nb_sectors,
2326 QEMUIOVector *iov)
2328 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
2331 static void coroutine_fn bdrv_flush_co_entry(void *opaque)
2333 RwCo *rwco = opaque;
2335 rwco->ret = bdrv_co_flush(rwco->bs);
2338 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
2340 int ret;
2341 BdrvTrackedRequest req;
2343 if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||
2344 bdrv_is_sg(bs)) {
2345 return 0;
2348 tracked_request_begin(&req, bs, 0, 0, BDRV_TRACKED_FLUSH);
2349 /* Write back cached data to the OS even with cache=unsafe */
2350 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
2351 if (bs->drv->bdrv_co_flush_to_os) {
2352 ret = bs->drv->bdrv_co_flush_to_os(bs);
2353 if (ret < 0) {
2354 goto out;
2358 /* But don't actually force it to the disk with cache=unsafe */
2359 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2360 goto flush_parent;
2363 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
2364 if (bs->drv->bdrv_co_flush_to_disk) {
2365 ret = bs->drv->bdrv_co_flush_to_disk(bs);
2366 } else if (bs->drv->bdrv_aio_flush) {
2367 BlockAIOCB *acb;
2368 CoroutineIOCompletion co = {
2369 .coroutine = qemu_coroutine_self(),
2372 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
2373 if (acb == NULL) {
2374 ret = -EIO;
2375 } else {
2376 qemu_coroutine_yield();
2377 ret = co.ret;
2379 } else {
2381 * Some block drivers always operate in either writethrough or unsafe
2382 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2383 * know how the server works (because the behaviour is hardcoded or
2384 * depends on server-side configuration), so we can't ensure that
2385 * everything is safe on disk. Returning an error doesn't work because
2386 * that would break guests even if the server operates in writethrough
2387 * mode.
2389 * Let's hope the user knows what he's doing.
2391 ret = 0;
2393 if (ret < 0) {
2394 goto out;
2397 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2398 * in the case of cache=unsafe, so there are no useless flushes.
2400 flush_parent:
2401 ret = bs->file ? bdrv_co_flush(bs->file->bs) : 0;
2402 out:
2403 tracked_request_end(&req);
2404 return ret;
2407 int bdrv_flush(BlockDriverState *bs)
2409 Coroutine *co;
2410 RwCo rwco = {
2411 .bs = bs,
2412 .ret = NOT_DONE,
2415 if (qemu_in_coroutine()) {
2416 /* Fast-path if already in coroutine context */
2417 bdrv_flush_co_entry(&rwco);
2418 } else {
2419 AioContext *aio_context = bdrv_get_aio_context(bs);
2421 co = qemu_coroutine_create(bdrv_flush_co_entry);
2422 qemu_coroutine_enter(co, &rwco);
2423 while (rwco.ret == NOT_DONE) {
2424 aio_poll(aio_context, true);
2428 return rwco.ret;
2431 typedef struct DiscardCo {
2432 BlockDriverState *bs;
2433 int64_t sector_num;
2434 int nb_sectors;
2435 int ret;
2436 } DiscardCo;
2437 static void coroutine_fn bdrv_discard_co_entry(void *opaque)
2439 DiscardCo *rwco = opaque;
2441 rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
2444 int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
2445 int nb_sectors)
2447 BdrvTrackedRequest req;
2448 int max_discard, ret;
2450 if (!bs->drv) {
2451 return -ENOMEDIUM;
2454 ret = bdrv_check_request(bs, sector_num, nb_sectors);
2455 if (ret < 0) {
2456 return ret;
2457 } else if (bs->read_only) {
2458 return -EPERM;
2460 assert(!(bs->open_flags & BDRV_O_INACTIVE));
2462 /* Do nothing if disabled. */
2463 if (!(bs->open_flags & BDRV_O_UNMAP)) {
2464 return 0;
2467 if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) {
2468 return 0;
2471 tracked_request_begin(&req, bs, sector_num, nb_sectors,
2472 BDRV_TRACKED_DISCARD);
2473 bdrv_set_dirty(bs, sector_num, nb_sectors);
2475 max_discard = MIN_NON_ZERO(bs->bl.max_discard, BDRV_REQUEST_MAX_SECTORS);
2476 while (nb_sectors > 0) {
2477 int ret;
2478 int num = nb_sectors;
2480 /* align request */
2481 if (bs->bl.discard_alignment &&
2482 num >= bs->bl.discard_alignment &&
2483 sector_num % bs->bl.discard_alignment) {
2484 if (num > bs->bl.discard_alignment) {
2485 num = bs->bl.discard_alignment;
2487 num -= sector_num % bs->bl.discard_alignment;
2490 /* limit request size */
2491 if (num > max_discard) {
2492 num = max_discard;
2495 if (bs->drv->bdrv_co_discard) {
2496 ret = bs->drv->bdrv_co_discard(bs, sector_num, num);
2497 } else {
2498 BlockAIOCB *acb;
2499 CoroutineIOCompletion co = {
2500 .coroutine = qemu_coroutine_self(),
2503 acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
2504 bdrv_co_io_em_complete, &co);
2505 if (acb == NULL) {
2506 ret = -EIO;
2507 goto out;
2508 } else {
2509 qemu_coroutine_yield();
2510 ret = co.ret;
2513 if (ret && ret != -ENOTSUP) {
2514 goto out;
2517 sector_num += num;
2518 nb_sectors -= num;
2520 ret = 0;
2521 out:
2522 tracked_request_end(&req);
2523 return ret;
2526 int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
2528 Coroutine *co;
2529 DiscardCo rwco = {
2530 .bs = bs,
2531 .sector_num = sector_num,
2532 .nb_sectors = nb_sectors,
2533 .ret = NOT_DONE,
2536 if (qemu_in_coroutine()) {
2537 /* Fast-path if already in coroutine context */
2538 bdrv_discard_co_entry(&rwco);
2539 } else {
2540 AioContext *aio_context = bdrv_get_aio_context(bs);
2542 co = qemu_coroutine_create(bdrv_discard_co_entry);
2543 qemu_coroutine_enter(co, &rwco);
2544 while (rwco.ret == NOT_DONE) {
2545 aio_poll(aio_context, true);
2549 return rwco.ret;
2552 typedef struct {
2553 CoroutineIOCompletion *co;
2554 QEMUBH *bh;
2555 } BdrvIoctlCompletionData;
2557 static void bdrv_ioctl_bh_cb(void *opaque)
2559 BdrvIoctlCompletionData *data = opaque;
2561 bdrv_co_io_em_complete(data->co, -ENOTSUP);
2562 qemu_bh_delete(data->bh);
2565 static int bdrv_co_do_ioctl(BlockDriverState *bs, int req, void *buf)
2567 BlockDriver *drv = bs->drv;
2568 BdrvTrackedRequest tracked_req;
2569 CoroutineIOCompletion co = {
2570 .coroutine = qemu_coroutine_self(),
2572 BlockAIOCB *acb;
2574 tracked_request_begin(&tracked_req, bs, 0, 0, BDRV_TRACKED_IOCTL);
2575 if (!drv || !drv->bdrv_aio_ioctl) {
2576 co.ret = -ENOTSUP;
2577 goto out;
2580 acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
2581 if (!acb) {
2582 BdrvIoctlCompletionData *data = g_new(BdrvIoctlCompletionData, 1);
2583 data->bh = aio_bh_new(bdrv_get_aio_context(bs),
2584 bdrv_ioctl_bh_cb, data);
2585 data->co = &co;
2586 qemu_bh_schedule(data->bh);
2588 qemu_coroutine_yield();
2589 out:
2590 tracked_request_end(&tracked_req);
2591 return co.ret;
2594 typedef struct {
2595 BlockDriverState *bs;
2596 int req;
2597 void *buf;
2598 int ret;
2599 } BdrvIoctlCoData;
2601 static void coroutine_fn bdrv_co_ioctl_entry(void *opaque)
2603 BdrvIoctlCoData *data = opaque;
2604 data->ret = bdrv_co_do_ioctl(data->bs, data->req, data->buf);
2607 /* needed for generic scsi interface */
2608 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2610 BdrvIoctlCoData data = {
2611 .bs = bs,
2612 .req = req,
2613 .buf = buf,
2614 .ret = -EINPROGRESS,
2617 if (qemu_in_coroutine()) {
2618 /* Fast-path if already in coroutine context */
2619 bdrv_co_ioctl_entry(&data);
2620 } else {
2621 Coroutine *co = qemu_coroutine_create(bdrv_co_ioctl_entry);
2623 qemu_coroutine_enter(co, &data);
2624 while (data.ret == -EINPROGRESS) {
2625 aio_poll(bdrv_get_aio_context(bs), true);
2628 return data.ret;
2631 static void coroutine_fn bdrv_co_aio_ioctl_entry(void *opaque)
2633 BlockAIOCBCoroutine *acb = opaque;
2634 acb->req.error = bdrv_co_do_ioctl(acb->common.bs,
2635 acb->req.req, acb->req.buf);
2636 bdrv_co_complete(acb);
2639 BlockAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
2640 unsigned long int req, void *buf,
2641 BlockCompletionFunc *cb, void *opaque)
2643 BlockAIOCBCoroutine *acb = qemu_aio_get(&bdrv_em_co_aiocb_info,
2644 bs, cb, opaque);
2645 Coroutine *co;
2647 acb->need_bh = true;
2648 acb->req.error = -EINPROGRESS;
2649 acb->req.req = req;
2650 acb->req.buf = buf;
2651 co = qemu_coroutine_create(bdrv_co_aio_ioctl_entry);
2652 qemu_coroutine_enter(co, acb);
2654 bdrv_co_maybe_schedule_bh(acb);
2655 return &acb->common;
2658 void *qemu_blockalign(BlockDriverState *bs, size_t size)
2660 return qemu_memalign(bdrv_opt_mem_align(bs), size);
2663 void *qemu_blockalign0(BlockDriverState *bs, size_t size)
2665 return memset(qemu_blockalign(bs, size), 0, size);
2668 void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
2670 size_t align = bdrv_opt_mem_align(bs);
2672 /* Ensure that NULL is never returned on success */
2673 assert(align > 0);
2674 if (size == 0) {
2675 size = align;
2678 return qemu_try_memalign(align, size);
2681 void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
2683 void *mem = qemu_try_blockalign(bs, size);
2685 if (mem) {
2686 memset(mem, 0, size);
2689 return mem;
2693 * Check if all memory in this vector is sector aligned.
2695 bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
2697 int i;
2698 size_t alignment = bdrv_min_mem_align(bs);
2700 for (i = 0; i < qiov->niov; i++) {
2701 if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
2702 return false;
2704 if (qiov->iov[i].iov_len % alignment) {
2705 return false;
2709 return true;
2712 void bdrv_add_before_write_notifier(BlockDriverState *bs,
2713 NotifierWithReturn *notifier)
2715 notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
2718 void bdrv_io_plug(BlockDriverState *bs)
2720 BlockDriver *drv = bs->drv;
2721 if (drv && drv->bdrv_io_plug) {
2722 drv->bdrv_io_plug(bs);
2723 } else if (bs->file) {
2724 bdrv_io_plug(bs->file->bs);
2728 void bdrv_io_unplug(BlockDriverState *bs)
2730 BlockDriver *drv = bs->drv;
2731 if (drv && drv->bdrv_io_unplug) {
2732 drv->bdrv_io_unplug(bs);
2733 } else if (bs->file) {
2734 bdrv_io_unplug(bs->file->bs);
2738 void bdrv_flush_io_queue(BlockDriverState *bs)
2740 BlockDriver *drv = bs->drv;
2741 if (drv && drv->bdrv_flush_io_queue) {
2742 drv->bdrv_flush_io_queue(bs);
2743 } else if (bs->file) {
2744 bdrv_flush_io_queue(bs->file->bs);
2746 bdrv_start_throttled_reqs(bs);
2749 void bdrv_drained_begin(BlockDriverState *bs)
2751 if (!bs->quiesce_counter++) {
2752 aio_disable_external(bdrv_get_aio_context(bs));
2754 bdrv_drain(bs);
2757 void bdrv_drained_end(BlockDriverState *bs)
2759 assert(bs->quiesce_counter > 0);
2760 if (--bs->quiesce_counter > 0) {
2761 return;
2763 aio_enable_external(bdrv_get_aio_context(bs));