block: Tighter assertions on bdrv_aligned_pwritev()
[qemu/ar7.git] / block / io.c
blobb95e856cf9a3af82e6a8cbc37d69395b6a1d98a2
1 /*
2 * Block layer I/O functions
4 * Copyright (c) 2003 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 #include "qemu/osdep.h"
26 #include "trace.h"
27 #include "sysemu/block-backend.h"
28 #include "block/blockjob.h"
29 #include "block/block_int.h"
30 #include "qemu/cutils.h"
31 #include "qapi/error.h"
32 #include "qemu/error-report.h"
34 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
36 static BlockAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
37 int64_t sector_num,
38 QEMUIOVector *qiov,
39 int nb_sectors,
40 BdrvRequestFlags flags,
41 BlockCompletionFunc *cb,
42 void *opaque,
43 bool is_write);
44 static void coroutine_fn bdrv_co_do_rw(void *opaque);
45 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
46 int64_t offset, int count, BdrvRequestFlags flags);
48 static void bdrv_parent_drained_begin(BlockDriverState *bs)
50 BdrvChild *c;
52 QLIST_FOREACH(c, &bs->parents, next_parent) {
53 if (c->role->drained_begin) {
54 c->role->drained_begin(c);
59 static void bdrv_parent_drained_end(BlockDriverState *bs)
61 BdrvChild *c;
63 QLIST_FOREACH(c, &bs->parents, next_parent) {
64 if (c->role->drained_end) {
65 c->role->drained_end(c);
70 void bdrv_refresh_limits(BlockDriverState *bs, Error **errp)
72 BlockDriver *drv = bs->drv;
73 Error *local_err = NULL;
75 memset(&bs->bl, 0, sizeof(bs->bl));
77 if (!drv) {
78 return;
81 /* Take some limits from the children as a default */
82 if (bs->file) {
83 bdrv_refresh_limits(bs->file->bs, &local_err);
84 if (local_err) {
85 error_propagate(errp, local_err);
86 return;
88 bs->bl.opt_transfer_length = bs->file->bs->bl.opt_transfer_length;
89 bs->bl.max_transfer_length = bs->file->bs->bl.max_transfer_length;
90 bs->bl.min_mem_alignment = bs->file->bs->bl.min_mem_alignment;
91 bs->bl.opt_mem_alignment = bs->file->bs->bl.opt_mem_alignment;
92 bs->bl.max_iov = bs->file->bs->bl.max_iov;
93 } else {
94 bs->bl.min_mem_alignment = 512;
95 bs->bl.opt_mem_alignment = getpagesize();
97 /* Safe default since most protocols use readv()/writev()/etc */
98 bs->bl.max_iov = IOV_MAX;
101 if (bs->backing) {
102 bdrv_refresh_limits(bs->backing->bs, &local_err);
103 if (local_err) {
104 error_propagate(errp, local_err);
105 return;
107 bs->bl.opt_transfer_length =
108 MAX(bs->bl.opt_transfer_length,
109 bs->backing->bs->bl.opt_transfer_length);
110 bs->bl.max_transfer_length =
111 MIN_NON_ZERO(bs->bl.max_transfer_length,
112 bs->backing->bs->bl.max_transfer_length);
113 bs->bl.opt_mem_alignment =
114 MAX(bs->bl.opt_mem_alignment,
115 bs->backing->bs->bl.opt_mem_alignment);
116 bs->bl.min_mem_alignment =
117 MAX(bs->bl.min_mem_alignment,
118 bs->backing->bs->bl.min_mem_alignment);
119 bs->bl.max_iov =
120 MIN(bs->bl.max_iov,
121 bs->backing->bs->bl.max_iov);
124 /* Then let the driver override it */
125 if (drv->bdrv_refresh_limits) {
126 drv->bdrv_refresh_limits(bs, errp);
131 * The copy-on-read flag is actually a reference count so multiple users may
132 * use the feature without worrying about clobbering its previous state.
133 * Copy-on-read stays enabled until all users have called to disable it.
135 void bdrv_enable_copy_on_read(BlockDriverState *bs)
137 bs->copy_on_read++;
140 void bdrv_disable_copy_on_read(BlockDriverState *bs)
142 assert(bs->copy_on_read > 0);
143 bs->copy_on_read--;
146 /* Check if any requests are in-flight (including throttled requests) */
147 bool bdrv_requests_pending(BlockDriverState *bs)
149 BdrvChild *child;
151 if (!QLIST_EMPTY(&bs->tracked_requests)) {
152 return true;
155 QLIST_FOREACH(child, &bs->children, next) {
156 if (bdrv_requests_pending(child->bs)) {
157 return true;
161 return false;
164 static void bdrv_drain_recurse(BlockDriverState *bs)
166 BdrvChild *child;
168 if (bs->drv && bs->drv->bdrv_drain) {
169 bs->drv->bdrv_drain(bs);
171 QLIST_FOREACH(child, &bs->children, next) {
172 bdrv_drain_recurse(child->bs);
176 typedef struct {
177 Coroutine *co;
178 BlockDriverState *bs;
179 QEMUBH *bh;
180 bool done;
181 } BdrvCoDrainData;
183 static void bdrv_drain_poll(BlockDriverState *bs)
185 bool busy = true;
187 while (busy) {
188 /* Keep iterating */
189 busy = bdrv_requests_pending(bs);
190 busy |= aio_poll(bdrv_get_aio_context(bs), busy);
194 static void bdrv_co_drain_bh_cb(void *opaque)
196 BdrvCoDrainData *data = opaque;
197 Coroutine *co = data->co;
199 qemu_bh_delete(data->bh);
200 bdrv_drain_poll(data->bs);
201 data->done = true;
202 qemu_coroutine_enter(co, NULL);
205 static void coroutine_fn bdrv_co_yield_to_drain(BlockDriverState *bs)
207 BdrvCoDrainData data;
209 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
210 * other coroutines run if they were queued from
211 * qemu_co_queue_run_restart(). */
213 assert(qemu_in_coroutine());
214 data = (BdrvCoDrainData) {
215 .co = qemu_coroutine_self(),
216 .bs = bs,
217 .done = false,
218 .bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_drain_bh_cb, &data),
220 qemu_bh_schedule(data.bh);
222 qemu_coroutine_yield();
223 /* If we are resumed from some other event (such as an aio completion or a
224 * timer callback), it is a bug in the caller that should be fixed. */
225 assert(data.done);
228 void bdrv_drained_begin(BlockDriverState *bs)
230 if (!bs->quiesce_counter++) {
231 aio_disable_external(bdrv_get_aio_context(bs));
232 bdrv_parent_drained_begin(bs);
235 bdrv_io_unplugged_begin(bs);
236 bdrv_drain_recurse(bs);
237 if (qemu_in_coroutine()) {
238 bdrv_co_yield_to_drain(bs);
239 } else {
240 bdrv_drain_poll(bs);
242 bdrv_io_unplugged_end(bs);
245 void bdrv_drained_end(BlockDriverState *bs)
247 assert(bs->quiesce_counter > 0);
248 if (--bs->quiesce_counter > 0) {
249 return;
252 bdrv_parent_drained_end(bs);
253 aio_enable_external(bdrv_get_aio_context(bs));
257 * Wait for pending requests to complete on a single BlockDriverState subtree,
258 * and suspend block driver's internal I/O until next request arrives.
260 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
261 * AioContext.
263 * Only this BlockDriverState's AioContext is run, so in-flight requests must
264 * not depend on events in other AioContexts. In that case, use
265 * bdrv_drain_all() instead.
267 void coroutine_fn bdrv_co_drain(BlockDriverState *bs)
269 assert(qemu_in_coroutine());
270 bdrv_drained_begin(bs);
271 bdrv_drained_end(bs);
274 void bdrv_drain(BlockDriverState *bs)
276 bdrv_drained_begin(bs);
277 bdrv_drained_end(bs);
281 * Wait for pending requests to complete across all BlockDriverStates
283 * This function does not flush data to disk, use bdrv_flush_all() for that
284 * after calling this function.
286 void bdrv_drain_all(void)
288 /* Always run first iteration so any pending completion BHs run */
289 bool busy = true;
290 BlockDriverState *bs;
291 BdrvNextIterator it;
292 BlockJob *job = NULL;
293 GSList *aio_ctxs = NULL, *ctx;
295 while ((job = block_job_next(job))) {
296 AioContext *aio_context = blk_get_aio_context(job->blk);
298 aio_context_acquire(aio_context);
299 block_job_pause(job);
300 aio_context_release(aio_context);
303 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
304 AioContext *aio_context = bdrv_get_aio_context(bs);
306 aio_context_acquire(aio_context);
307 bdrv_parent_drained_begin(bs);
308 bdrv_io_unplugged_begin(bs);
309 bdrv_drain_recurse(bs);
310 aio_context_release(aio_context);
312 if (!g_slist_find(aio_ctxs, aio_context)) {
313 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
317 /* Note that completion of an asynchronous I/O operation can trigger any
318 * number of other I/O operations on other devices---for example a
319 * coroutine can submit an I/O request to another device in response to
320 * request completion. Therefore we must keep looping until there was no
321 * more activity rather than simply draining each device independently.
323 while (busy) {
324 busy = false;
326 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
327 AioContext *aio_context = ctx->data;
329 aio_context_acquire(aio_context);
330 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
331 if (aio_context == bdrv_get_aio_context(bs)) {
332 if (bdrv_requests_pending(bs)) {
333 busy = true;
334 aio_poll(aio_context, busy);
338 busy |= aio_poll(aio_context, false);
339 aio_context_release(aio_context);
343 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
344 AioContext *aio_context = bdrv_get_aio_context(bs);
346 aio_context_acquire(aio_context);
347 bdrv_io_unplugged_end(bs);
348 bdrv_parent_drained_end(bs);
349 aio_context_release(aio_context);
351 g_slist_free(aio_ctxs);
353 job = NULL;
354 while ((job = block_job_next(job))) {
355 AioContext *aio_context = blk_get_aio_context(job->blk);
357 aio_context_acquire(aio_context);
358 block_job_resume(job);
359 aio_context_release(aio_context);
364 * Remove an active request from the tracked requests list
366 * This function should be called when a tracked request is completing.
368 static void tracked_request_end(BdrvTrackedRequest *req)
370 if (req->serialising) {
371 req->bs->serialising_in_flight--;
374 QLIST_REMOVE(req, list);
375 qemu_co_queue_restart_all(&req->wait_queue);
379 * Add an active request to the tracked requests list
381 static void tracked_request_begin(BdrvTrackedRequest *req,
382 BlockDriverState *bs,
383 int64_t offset,
384 unsigned int bytes,
385 enum BdrvTrackedRequestType type)
387 *req = (BdrvTrackedRequest){
388 .bs = bs,
389 .offset = offset,
390 .bytes = bytes,
391 .type = type,
392 .co = qemu_coroutine_self(),
393 .serialising = false,
394 .overlap_offset = offset,
395 .overlap_bytes = bytes,
398 qemu_co_queue_init(&req->wait_queue);
400 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
403 static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
405 int64_t overlap_offset = req->offset & ~(align - 1);
406 unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
407 - overlap_offset;
409 if (!req->serialising) {
410 req->bs->serialising_in_flight++;
411 req->serialising = true;
414 req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
415 req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
419 * Round a region to cluster boundaries (sector-based)
421 void bdrv_round_sectors_to_clusters(BlockDriverState *bs,
422 int64_t sector_num, int nb_sectors,
423 int64_t *cluster_sector_num,
424 int *cluster_nb_sectors)
426 BlockDriverInfo bdi;
428 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
429 *cluster_sector_num = sector_num;
430 *cluster_nb_sectors = nb_sectors;
431 } else {
432 int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
433 *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
434 *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
435 nb_sectors, c);
440 * Round a region to cluster boundaries
442 void bdrv_round_to_clusters(BlockDriverState *bs,
443 int64_t offset, unsigned int bytes,
444 int64_t *cluster_offset,
445 unsigned int *cluster_bytes)
447 BlockDriverInfo bdi;
449 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
450 *cluster_offset = offset;
451 *cluster_bytes = bytes;
452 } else {
453 int64_t c = bdi.cluster_size;
454 *cluster_offset = QEMU_ALIGN_DOWN(offset, c);
455 *cluster_bytes = QEMU_ALIGN_UP(offset - *cluster_offset + bytes, c);
459 static int bdrv_get_cluster_size(BlockDriverState *bs)
461 BlockDriverInfo bdi;
462 int ret;
464 ret = bdrv_get_info(bs, &bdi);
465 if (ret < 0 || bdi.cluster_size == 0) {
466 return bs->request_alignment;
467 } else {
468 return bdi.cluster_size;
472 static bool tracked_request_overlaps(BdrvTrackedRequest *req,
473 int64_t offset, unsigned int bytes)
475 /* aaaa bbbb */
476 if (offset >= req->overlap_offset + req->overlap_bytes) {
477 return false;
479 /* bbbb aaaa */
480 if (req->overlap_offset >= offset + bytes) {
481 return false;
483 return true;
486 static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
488 BlockDriverState *bs = self->bs;
489 BdrvTrackedRequest *req;
490 bool retry;
491 bool waited = false;
493 if (!bs->serialising_in_flight) {
494 return false;
497 do {
498 retry = false;
499 QLIST_FOREACH(req, &bs->tracked_requests, list) {
500 if (req == self || (!req->serialising && !self->serialising)) {
501 continue;
503 if (tracked_request_overlaps(req, self->overlap_offset,
504 self->overlap_bytes))
506 /* Hitting this means there was a reentrant request, for
507 * example, a block driver issuing nested requests. This must
508 * never happen since it means deadlock.
510 assert(qemu_coroutine_self() != req->co);
512 /* If the request is already (indirectly) waiting for us, or
513 * will wait for us as soon as it wakes up, then just go on
514 * (instead of producing a deadlock in the former case). */
515 if (!req->waiting_for) {
516 self->waiting_for = req;
517 qemu_co_queue_wait(&req->wait_queue);
518 self->waiting_for = NULL;
519 retry = true;
520 waited = true;
521 break;
525 } while (retry);
527 return waited;
530 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
531 size_t size)
533 if (size > BDRV_REQUEST_MAX_SECTORS << BDRV_SECTOR_BITS) {
534 return -EIO;
537 if (!bdrv_is_inserted(bs)) {
538 return -ENOMEDIUM;
541 if (offset < 0) {
542 return -EIO;
545 return 0;
548 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
549 int nb_sectors)
551 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
552 return -EIO;
555 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
556 nb_sectors * BDRV_SECTOR_SIZE);
559 typedef struct RwCo {
560 BlockDriverState *bs;
561 int64_t offset;
562 QEMUIOVector *qiov;
563 bool is_write;
564 int ret;
565 BdrvRequestFlags flags;
566 } RwCo;
568 static void coroutine_fn bdrv_rw_co_entry(void *opaque)
570 RwCo *rwco = opaque;
572 if (!rwco->is_write) {
573 rwco->ret = bdrv_co_preadv(rwco->bs, rwco->offset,
574 rwco->qiov->size, rwco->qiov,
575 rwco->flags);
576 } else {
577 rwco->ret = bdrv_co_pwritev(rwco->bs, rwco->offset,
578 rwco->qiov->size, rwco->qiov,
579 rwco->flags);
584 * Process a vectored synchronous request using coroutines
586 static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset,
587 QEMUIOVector *qiov, bool is_write,
588 BdrvRequestFlags flags)
590 Coroutine *co;
591 RwCo rwco = {
592 .bs = bs,
593 .offset = offset,
594 .qiov = qiov,
595 .is_write = is_write,
596 .ret = NOT_DONE,
597 .flags = flags,
600 if (qemu_in_coroutine()) {
601 /* Fast-path if already in coroutine context */
602 bdrv_rw_co_entry(&rwco);
603 } else {
604 AioContext *aio_context = bdrv_get_aio_context(bs);
606 co = qemu_coroutine_create(bdrv_rw_co_entry);
607 qemu_coroutine_enter(co, &rwco);
608 while (rwco.ret == NOT_DONE) {
609 aio_poll(aio_context, true);
612 return rwco.ret;
616 * Process a synchronous request using coroutines
618 static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
619 int nb_sectors, bool is_write, BdrvRequestFlags flags)
621 QEMUIOVector qiov;
622 struct iovec iov = {
623 .iov_base = (void *)buf,
624 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
627 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
628 return -EINVAL;
631 qemu_iovec_init_external(&qiov, &iov, 1);
632 return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS,
633 &qiov, is_write, flags);
636 /* return < 0 if error. See bdrv_write() for the return codes */
637 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
638 uint8_t *buf, int nb_sectors)
640 return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
643 /* Return < 0 if error. Important errors are:
644 -EIO generic I/O error (may happen for all errors)
645 -ENOMEDIUM No media inserted.
646 -EINVAL Invalid sector number or nb_sectors
647 -EACCES Trying to write a read-only device
649 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
650 const uint8_t *buf, int nb_sectors)
652 return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
655 int bdrv_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
656 int count, BdrvRequestFlags flags)
658 QEMUIOVector qiov;
659 struct iovec iov = {
660 .iov_base = NULL,
661 .iov_len = count,
664 qemu_iovec_init_external(&qiov, &iov, 1);
665 return bdrv_prwv_co(bs, offset, &qiov, true,
666 BDRV_REQ_ZERO_WRITE | flags);
670 * Completely zero out a block device with the help of bdrv_pwrite_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_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
674 * BDRV_REQ_FUA).
676 * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
678 int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags)
680 int64_t target_sectors, ret, nb_sectors, sector_num = 0;
681 BlockDriverState *file;
682 int n;
684 target_sectors = bdrv_nb_sectors(bs);
685 if (target_sectors < 0) {
686 return target_sectors;
689 for (;;) {
690 nb_sectors = MIN(target_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
691 if (nb_sectors <= 0) {
692 return 0;
694 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n, &file);
695 if (ret < 0) {
696 error_report("error getting block status at sector %" PRId64 ": %s",
697 sector_num, strerror(-ret));
698 return ret;
700 if (ret & BDRV_BLOCK_ZERO) {
701 sector_num += n;
702 continue;
704 ret = bdrv_pwrite_zeroes(bs, sector_num << BDRV_SECTOR_BITS,
705 n << BDRV_SECTOR_BITS, flags);
706 if (ret < 0) {
707 error_report("error writing zeroes at sector %" PRId64 ": %s",
708 sector_num, strerror(-ret));
709 return ret;
711 sector_num += n;
715 int bdrv_preadv(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
717 int ret;
719 ret = bdrv_prwv_co(bs, offset, qiov, false, 0);
720 if (ret < 0) {
721 return ret;
724 return qiov->size;
727 int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes)
729 QEMUIOVector qiov;
730 struct iovec iov = {
731 .iov_base = (void *)buf,
732 .iov_len = bytes,
735 if (bytes < 0) {
736 return -EINVAL;
739 qemu_iovec_init_external(&qiov, &iov, 1);
740 return bdrv_preadv(bs, offset, &qiov);
743 int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
745 int ret;
747 ret = bdrv_prwv_co(bs, offset, qiov, true, 0);
748 if (ret < 0) {
749 return ret;
752 return qiov->size;
755 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
756 const void *buf, int bytes)
758 QEMUIOVector qiov;
759 struct iovec iov = {
760 .iov_base = (void *) buf,
761 .iov_len = bytes,
764 if (bytes < 0) {
765 return -EINVAL;
768 qemu_iovec_init_external(&qiov, &iov, 1);
769 return bdrv_pwritev(bs, offset, &qiov);
773 * Writes to the file and ensures that no writes are reordered across this
774 * request (acts as a barrier)
776 * Returns 0 on success, -errno in error cases.
778 int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
779 const void *buf, int count)
781 int ret;
783 ret = bdrv_pwrite(bs, offset, buf, count);
784 if (ret < 0) {
785 return ret;
788 ret = bdrv_flush(bs);
789 if (ret < 0) {
790 return ret;
793 return 0;
796 typedef struct CoroutineIOCompletion {
797 Coroutine *coroutine;
798 int ret;
799 } CoroutineIOCompletion;
801 static void bdrv_co_io_em_complete(void *opaque, int ret)
803 CoroutineIOCompletion *co = opaque;
805 co->ret = ret;
806 qemu_coroutine_enter(co->coroutine, NULL);
809 static int coroutine_fn bdrv_driver_preadv(BlockDriverState *bs,
810 uint64_t offset, uint64_t bytes,
811 QEMUIOVector *qiov, int flags)
813 BlockDriver *drv = bs->drv;
814 int64_t sector_num;
815 unsigned int nb_sectors;
817 assert(!(flags & ~BDRV_REQ_MASK));
819 if (drv->bdrv_co_preadv) {
820 return drv->bdrv_co_preadv(bs, offset, bytes, qiov, flags);
823 sector_num = offset >> BDRV_SECTOR_BITS;
824 nb_sectors = bytes >> BDRV_SECTOR_BITS;
826 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
827 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
828 assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);
830 if (drv->bdrv_co_readv) {
831 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
832 } else {
833 BlockAIOCB *acb;
834 CoroutineIOCompletion co = {
835 .coroutine = qemu_coroutine_self(),
838 acb = bs->drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
839 bdrv_co_io_em_complete, &co);
840 if (acb == NULL) {
841 return -EIO;
842 } else {
843 qemu_coroutine_yield();
844 return co.ret;
849 static int coroutine_fn bdrv_driver_pwritev(BlockDriverState *bs,
850 uint64_t offset, uint64_t bytes,
851 QEMUIOVector *qiov, int flags)
853 BlockDriver *drv = bs->drv;
854 int64_t sector_num;
855 unsigned int nb_sectors;
856 int ret;
858 assert(!(flags & ~BDRV_REQ_MASK));
860 if (drv->bdrv_co_pwritev) {
861 ret = drv->bdrv_co_pwritev(bs, offset, bytes, qiov,
862 flags & bs->supported_write_flags);
863 flags &= ~bs->supported_write_flags;
864 goto emulate_flags;
867 sector_num = offset >> BDRV_SECTOR_BITS;
868 nb_sectors = bytes >> BDRV_SECTOR_BITS;
870 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
871 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
872 assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);
874 if (drv->bdrv_co_writev_flags) {
875 ret = drv->bdrv_co_writev_flags(bs, sector_num, nb_sectors, qiov,
876 flags & bs->supported_write_flags);
877 flags &= ~bs->supported_write_flags;
878 } else if (drv->bdrv_co_writev) {
879 assert(!bs->supported_write_flags);
880 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
881 } else {
882 BlockAIOCB *acb;
883 CoroutineIOCompletion co = {
884 .coroutine = qemu_coroutine_self(),
887 acb = bs->drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
888 bdrv_co_io_em_complete, &co);
889 if (acb == NULL) {
890 ret = -EIO;
891 } else {
892 qemu_coroutine_yield();
893 ret = co.ret;
897 emulate_flags:
898 if (ret == 0 && (flags & BDRV_REQ_FUA)) {
899 ret = bdrv_co_flush(bs);
902 return ret;
905 static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
906 int64_t offset, unsigned int bytes, QEMUIOVector *qiov)
908 /* Perform I/O through a temporary buffer so that users who scribble over
909 * their read buffer while the operation is in progress do not end up
910 * modifying the image file. This is critical for zero-copy guest I/O
911 * where anything might happen inside guest memory.
913 void *bounce_buffer;
915 BlockDriver *drv = bs->drv;
916 struct iovec iov;
917 QEMUIOVector bounce_qiov;
918 int64_t cluster_offset;
919 unsigned int cluster_bytes;
920 size_t skip_bytes;
921 int ret;
923 /* Cover entire cluster so no additional backing file I/O is required when
924 * allocating cluster in the image file.
926 bdrv_round_to_clusters(bs, offset, bytes, &cluster_offset, &cluster_bytes);
928 trace_bdrv_co_do_copy_on_readv(bs, offset, bytes,
929 cluster_offset, cluster_bytes);
931 iov.iov_len = cluster_bytes;
932 iov.iov_base = bounce_buffer = qemu_try_blockalign(bs, iov.iov_len);
933 if (bounce_buffer == NULL) {
934 ret = -ENOMEM;
935 goto err;
938 qemu_iovec_init_external(&bounce_qiov, &iov, 1);
940 ret = bdrv_driver_preadv(bs, cluster_offset, cluster_bytes,
941 &bounce_qiov, 0);
942 if (ret < 0) {
943 goto err;
946 if (drv->bdrv_co_pwrite_zeroes &&
947 buffer_is_zero(bounce_buffer, iov.iov_len)) {
948 ret = bdrv_co_do_pwrite_zeroes(bs, cluster_offset, cluster_bytes, 0);
949 } else {
950 /* This does not change the data on the disk, it is not necessary
951 * to flush even in cache=writethrough mode.
953 ret = bdrv_driver_pwritev(bs, cluster_offset, cluster_bytes,
954 &bounce_qiov, 0);
957 if (ret < 0) {
958 /* It might be okay to ignore write errors for guest requests. If this
959 * is a deliberate copy-on-read then we don't want to ignore the error.
960 * Simply report it in all cases.
962 goto err;
965 skip_bytes = offset - cluster_offset;
966 qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes, bytes);
968 err:
969 qemu_vfree(bounce_buffer);
970 return ret;
974 * Forwards an already correctly aligned request to the BlockDriver. This
975 * handles copy on read and zeroing after EOF; any other features must be
976 * implemented by the caller.
978 static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,
979 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
980 int64_t align, QEMUIOVector *qiov, int flags)
982 int64_t total_bytes, max_bytes;
983 int ret;
985 assert(is_power_of_2(align));
986 assert((offset & (align - 1)) == 0);
987 assert((bytes & (align - 1)) == 0);
988 assert(!qiov || bytes == qiov->size);
989 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
990 assert(!(flags & ~BDRV_REQ_MASK));
992 /* Handle Copy on Read and associated serialisation */
993 if (flags & BDRV_REQ_COPY_ON_READ) {
994 /* If we touch the same cluster it counts as an overlap. This
995 * guarantees that allocating writes will be serialized and not race
996 * with each other for the same cluster. For example, in copy-on-read
997 * it ensures that the CoR read and write operations are atomic and
998 * guest writes cannot interleave between them. */
999 mark_request_serialising(req, bdrv_get_cluster_size(bs));
1002 if (!(flags & BDRV_REQ_NO_SERIALISING)) {
1003 wait_serialising_requests(req);
1006 if (flags & BDRV_REQ_COPY_ON_READ) {
1007 int64_t start_sector = offset >> BDRV_SECTOR_BITS;
1008 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
1009 unsigned int nb_sectors = end_sector - start_sector;
1010 int pnum;
1012 ret = bdrv_is_allocated(bs, start_sector, nb_sectors, &pnum);
1013 if (ret < 0) {
1014 goto out;
1017 if (!ret || pnum != nb_sectors) {
1018 ret = bdrv_co_do_copy_on_readv(bs, offset, bytes, qiov);
1019 goto out;
1023 /* Forward the request to the BlockDriver */
1024 total_bytes = bdrv_getlength(bs);
1025 if (total_bytes < 0) {
1026 ret = total_bytes;
1027 goto out;
1030 max_bytes = ROUND_UP(MAX(0, total_bytes - offset), align);
1031 if (bytes < max_bytes) {
1032 ret = bdrv_driver_preadv(bs, offset, bytes, qiov, 0);
1033 } else if (max_bytes > 0) {
1034 QEMUIOVector local_qiov;
1036 qemu_iovec_init(&local_qiov, qiov->niov);
1037 qemu_iovec_concat(&local_qiov, qiov, 0, max_bytes);
1039 ret = bdrv_driver_preadv(bs, offset, max_bytes, &local_qiov, 0);
1041 qemu_iovec_destroy(&local_qiov);
1042 } else {
1043 ret = 0;
1046 /* Reading beyond end of file is supposed to produce zeroes */
1047 if (ret == 0 && total_bytes < offset + bytes) {
1048 uint64_t zero_offset = MAX(0, total_bytes - offset);
1049 uint64_t zero_bytes = offset + bytes - zero_offset;
1050 qemu_iovec_memset(qiov, zero_offset, 0, zero_bytes);
1053 out:
1054 return ret;
1058 * Handle a read request in coroutine context
1060 int coroutine_fn bdrv_co_preadv(BlockDriverState *bs,
1061 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1062 BdrvRequestFlags flags)
1064 BlockDriver *drv = bs->drv;
1065 BdrvTrackedRequest req;
1067 uint64_t align = bs->request_alignment;
1068 uint8_t *head_buf = NULL;
1069 uint8_t *tail_buf = NULL;
1070 QEMUIOVector local_qiov;
1071 bool use_local_qiov = false;
1072 int ret;
1074 if (!drv) {
1075 return -ENOMEDIUM;
1078 ret = bdrv_check_byte_request(bs, offset, bytes);
1079 if (ret < 0) {
1080 return ret;
1083 /* Don't do copy-on-read if we read data before write operation */
1084 if (bs->copy_on_read && !(flags & BDRV_REQ_NO_SERIALISING)) {
1085 flags |= BDRV_REQ_COPY_ON_READ;
1088 /* Align read if necessary by padding qiov */
1089 if (offset & (align - 1)) {
1090 head_buf = qemu_blockalign(bs, align);
1091 qemu_iovec_init(&local_qiov, qiov->niov + 2);
1092 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
1093 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1094 use_local_qiov = true;
1096 bytes += offset & (align - 1);
1097 offset = offset & ~(align - 1);
1100 if ((offset + bytes) & (align - 1)) {
1101 if (!use_local_qiov) {
1102 qemu_iovec_init(&local_qiov, qiov->niov + 1);
1103 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1104 use_local_qiov = true;
1106 tail_buf = qemu_blockalign(bs, align);
1107 qemu_iovec_add(&local_qiov, tail_buf,
1108 align - ((offset + bytes) & (align - 1)));
1110 bytes = ROUND_UP(bytes, align);
1113 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_READ);
1114 ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align,
1115 use_local_qiov ? &local_qiov : qiov,
1116 flags);
1117 tracked_request_end(&req);
1119 if (use_local_qiov) {
1120 qemu_iovec_destroy(&local_qiov);
1121 qemu_vfree(head_buf);
1122 qemu_vfree(tail_buf);
1125 return ret;
1128 static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
1129 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
1130 BdrvRequestFlags flags)
1132 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
1133 return -EINVAL;
1136 return bdrv_co_preadv(bs, sector_num << BDRV_SECTOR_BITS,
1137 nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
1140 int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1141 int nb_sectors, QEMUIOVector *qiov)
1143 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1145 return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
1148 #define MAX_WRITE_ZEROES_BOUNCE_BUFFER 32768
1150 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
1151 int64_t offset, int count, BdrvRequestFlags flags)
1153 BlockDriver *drv = bs->drv;
1154 QEMUIOVector qiov;
1155 struct iovec iov = {0};
1156 int ret = 0;
1157 bool need_flush = false;
1158 int head = 0;
1159 int tail = 0;
1161 int max_write_zeroes = MIN_NON_ZERO(bs->bl.max_pwrite_zeroes, INT_MAX);
1162 int alignment = MAX(bs->bl.pwrite_zeroes_alignment ?: 1,
1163 bs->request_alignment);
1165 assert(is_power_of_2(alignment));
1166 head = offset & (alignment - 1);
1167 tail = (offset + count) & (alignment - 1);
1168 max_write_zeroes &= ~(alignment - 1);
1170 while (count > 0 && !ret) {
1171 int num = count;
1173 /* Align request. Block drivers can expect the "bulk" of the request
1174 * to be aligned, and that unaligned requests do not cross cluster
1175 * boundaries.
1177 if (head) {
1178 /* Make a small request up to the first aligned sector. */
1179 num = MIN(count, alignment - head);
1180 head = 0;
1181 } else if (tail && num > alignment) {
1182 /* Shorten the request to the last aligned sector. */
1183 num -= tail;
1186 /* limit request size */
1187 if (num > max_write_zeroes) {
1188 num = max_write_zeroes;
1191 ret = -ENOTSUP;
1192 /* First try the efficient write zeroes operation */
1193 if (drv->bdrv_co_pwrite_zeroes) {
1194 ret = drv->bdrv_co_pwrite_zeroes(bs, offset, num,
1195 flags & bs->supported_zero_flags);
1196 if (ret != -ENOTSUP && (flags & BDRV_REQ_FUA) &&
1197 !(bs->supported_zero_flags & BDRV_REQ_FUA)) {
1198 need_flush = true;
1200 } else {
1201 assert(!bs->supported_zero_flags);
1204 if (ret == -ENOTSUP) {
1205 /* Fall back to bounce buffer if write zeroes is unsupported */
1206 int max_xfer_len = MIN_NON_ZERO(bs->bl.max_transfer_length,
1207 MAX_WRITE_ZEROES_BOUNCE_BUFFER);
1208 BdrvRequestFlags write_flags = flags & ~BDRV_REQ_ZERO_WRITE;
1210 if ((flags & BDRV_REQ_FUA) &&
1211 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1212 /* No need for bdrv_driver_pwrite() to do a fallback
1213 * flush on each chunk; use just one at the end */
1214 write_flags &= ~BDRV_REQ_FUA;
1215 need_flush = true;
1217 num = MIN(num, max_xfer_len << BDRV_SECTOR_BITS);
1218 iov.iov_len = num;
1219 if (iov.iov_base == NULL) {
1220 iov.iov_base = qemu_try_blockalign(bs, num);
1221 if (iov.iov_base == NULL) {
1222 ret = -ENOMEM;
1223 goto fail;
1225 memset(iov.iov_base, 0, num);
1227 qemu_iovec_init_external(&qiov, &iov, 1);
1229 ret = bdrv_driver_pwritev(bs, offset, num, &qiov, write_flags);
1231 /* Keep bounce buffer around if it is big enough for all
1232 * all future requests.
1234 if (num < max_xfer_len << BDRV_SECTOR_BITS) {
1235 qemu_vfree(iov.iov_base);
1236 iov.iov_base = NULL;
1240 offset += num;
1241 count -= num;
1244 fail:
1245 if (ret == 0 && need_flush) {
1246 ret = bdrv_co_flush(bs);
1248 qemu_vfree(iov.iov_base);
1249 return ret;
1253 * Forwards an already correctly aligned write request to the BlockDriver.
1255 static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,
1256 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
1257 int64_t align, QEMUIOVector *qiov, int flags)
1259 BlockDriver *drv = bs->drv;
1260 bool waited;
1261 int ret;
1263 int64_t start_sector = offset >> BDRV_SECTOR_BITS;
1264 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
1266 assert(is_power_of_2(align));
1267 assert((offset & (align - 1)) == 0);
1268 assert((bytes & (align - 1)) == 0);
1269 assert(!qiov || bytes == qiov->size);
1270 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1271 assert(!(flags & ~BDRV_REQ_MASK));
1273 waited = wait_serialising_requests(req);
1274 assert(!waited || !req->serialising);
1275 assert(req->overlap_offset <= offset);
1276 assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
1278 ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
1280 if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
1281 !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_pwrite_zeroes &&
1282 qemu_iovec_is_zero(qiov)) {
1283 flags |= BDRV_REQ_ZERO_WRITE;
1284 if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
1285 flags |= BDRV_REQ_MAY_UNMAP;
1289 if (ret < 0) {
1290 /* Do nothing, write notifier decided to fail this request */
1291 } else if (flags & BDRV_REQ_ZERO_WRITE) {
1292 bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO);
1293 ret = bdrv_co_do_pwrite_zeroes(bs, offset, bytes, flags);
1294 } else {
1295 bdrv_debug_event(bs, BLKDBG_PWRITEV);
1296 ret = bdrv_driver_pwritev(bs, offset, bytes, qiov, flags);
1298 bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE);
1300 bdrv_set_dirty(bs, start_sector, end_sector - start_sector);
1302 if (bs->wr_highest_offset < offset + bytes) {
1303 bs->wr_highest_offset = offset + bytes;
1306 if (ret >= 0) {
1307 bs->total_sectors = MAX(bs->total_sectors, end_sector);
1310 return ret;
1313 static int coroutine_fn bdrv_co_do_zero_pwritev(BlockDriverState *bs,
1314 int64_t offset,
1315 unsigned int bytes,
1316 BdrvRequestFlags flags,
1317 BdrvTrackedRequest *req)
1319 uint8_t *buf = NULL;
1320 QEMUIOVector local_qiov;
1321 struct iovec iov;
1322 uint64_t align = bs->request_alignment;
1323 unsigned int head_padding_bytes, tail_padding_bytes;
1324 int ret = 0;
1326 head_padding_bytes = offset & (align - 1);
1327 tail_padding_bytes = align - ((offset + bytes) & (align - 1));
1330 assert(flags & BDRV_REQ_ZERO_WRITE);
1331 if (head_padding_bytes || tail_padding_bytes) {
1332 buf = qemu_blockalign(bs, align);
1333 iov = (struct iovec) {
1334 .iov_base = buf,
1335 .iov_len = align,
1337 qemu_iovec_init_external(&local_qiov, &iov, 1);
1339 if (head_padding_bytes) {
1340 uint64_t zero_bytes = MIN(bytes, align - head_padding_bytes);
1342 /* RMW the unaligned part before head. */
1343 mark_request_serialising(req, align);
1344 wait_serialising_requests(req);
1345 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1346 ret = bdrv_aligned_preadv(bs, req, offset & ~(align - 1), align,
1347 align, &local_qiov, 0);
1348 if (ret < 0) {
1349 goto fail;
1351 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1353 memset(buf + head_padding_bytes, 0, zero_bytes);
1354 ret = bdrv_aligned_pwritev(bs, req, offset & ~(align - 1), align,
1355 align, &local_qiov,
1356 flags & ~BDRV_REQ_ZERO_WRITE);
1357 if (ret < 0) {
1358 goto fail;
1360 offset += zero_bytes;
1361 bytes -= zero_bytes;
1364 assert(!bytes || (offset & (align - 1)) == 0);
1365 if (bytes >= align) {
1366 /* Write the aligned part in the middle. */
1367 uint64_t aligned_bytes = bytes & ~(align - 1);
1368 ret = bdrv_aligned_pwritev(bs, req, offset, aligned_bytes, align,
1369 NULL, flags);
1370 if (ret < 0) {
1371 goto fail;
1373 bytes -= aligned_bytes;
1374 offset += aligned_bytes;
1377 assert(!bytes || (offset & (align - 1)) == 0);
1378 if (bytes) {
1379 assert(align == tail_padding_bytes + bytes);
1380 /* RMW the unaligned part after tail. */
1381 mark_request_serialising(req, align);
1382 wait_serialising_requests(req);
1383 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1384 ret = bdrv_aligned_preadv(bs, req, offset, align,
1385 align, &local_qiov, 0);
1386 if (ret < 0) {
1387 goto fail;
1389 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1391 memset(buf, 0, bytes);
1392 ret = bdrv_aligned_pwritev(bs, req, offset, align, align,
1393 &local_qiov, flags & ~BDRV_REQ_ZERO_WRITE);
1395 fail:
1396 qemu_vfree(buf);
1397 return ret;
1402 * Handle a write request in coroutine context
1404 int coroutine_fn bdrv_co_pwritev(BlockDriverState *bs,
1405 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1406 BdrvRequestFlags flags)
1408 BdrvTrackedRequest req;
1409 uint64_t align = bs->request_alignment;
1410 uint8_t *head_buf = NULL;
1411 uint8_t *tail_buf = NULL;
1412 QEMUIOVector local_qiov;
1413 bool use_local_qiov = false;
1414 int ret;
1416 if (!bs->drv) {
1417 return -ENOMEDIUM;
1419 if (bs->read_only) {
1420 return -EPERM;
1422 assert(!(bs->open_flags & BDRV_O_INACTIVE));
1424 ret = bdrv_check_byte_request(bs, offset, bytes);
1425 if (ret < 0) {
1426 return ret;
1430 * Align write if necessary by performing a read-modify-write cycle.
1431 * Pad qiov with the read parts and be sure to have a tracked request not
1432 * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
1434 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);
1436 if (!qiov) {
1437 ret = bdrv_co_do_zero_pwritev(bs, offset, bytes, flags, &req);
1438 goto out;
1441 if (offset & (align - 1)) {
1442 QEMUIOVector head_qiov;
1443 struct iovec head_iov;
1445 mark_request_serialising(&req, align);
1446 wait_serialising_requests(&req);
1448 head_buf = qemu_blockalign(bs, align);
1449 head_iov = (struct iovec) {
1450 .iov_base = head_buf,
1451 .iov_len = align,
1453 qemu_iovec_init_external(&head_qiov, &head_iov, 1);
1455 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1456 ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align,
1457 align, &head_qiov, 0);
1458 if (ret < 0) {
1459 goto fail;
1461 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1463 qemu_iovec_init(&local_qiov, qiov->niov + 2);
1464 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
1465 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1466 use_local_qiov = true;
1468 bytes += offset & (align - 1);
1469 offset = offset & ~(align - 1);
1471 /* We have read the tail already if the request is smaller
1472 * than one aligned block.
1474 if (bytes < align) {
1475 qemu_iovec_add(&local_qiov, head_buf + bytes, align - bytes);
1476 bytes = align;
1480 if ((offset + bytes) & (align - 1)) {
1481 QEMUIOVector tail_qiov;
1482 struct iovec tail_iov;
1483 size_t tail_bytes;
1484 bool waited;
1486 mark_request_serialising(&req, align);
1487 waited = wait_serialising_requests(&req);
1488 assert(!waited || !use_local_qiov);
1490 tail_buf = qemu_blockalign(bs, align);
1491 tail_iov = (struct iovec) {
1492 .iov_base = tail_buf,
1493 .iov_len = align,
1495 qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);
1497 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1498 ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align,
1499 align, &tail_qiov, 0);
1500 if (ret < 0) {
1501 goto fail;
1503 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1505 if (!use_local_qiov) {
1506 qemu_iovec_init(&local_qiov, qiov->niov + 1);
1507 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1508 use_local_qiov = true;
1511 tail_bytes = (offset + bytes) & (align - 1);
1512 qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
1514 bytes = ROUND_UP(bytes, align);
1517 ret = bdrv_aligned_pwritev(bs, &req, offset, bytes, align,
1518 use_local_qiov ? &local_qiov : qiov,
1519 flags);
1521 fail:
1523 if (use_local_qiov) {
1524 qemu_iovec_destroy(&local_qiov);
1526 qemu_vfree(head_buf);
1527 qemu_vfree(tail_buf);
1528 out:
1529 tracked_request_end(&req);
1530 return ret;
1533 static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
1534 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
1535 BdrvRequestFlags flags)
1537 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
1538 return -EINVAL;
1541 return bdrv_co_pwritev(bs, sector_num << BDRV_SECTOR_BITS,
1542 nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
1545 int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1546 int nb_sectors, QEMUIOVector *qiov)
1548 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1550 return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
1553 int coroutine_fn bdrv_co_pwrite_zeroes(BlockDriverState *bs,
1554 int64_t offset, int count,
1555 BdrvRequestFlags flags)
1557 trace_bdrv_co_pwrite_zeroes(bs, offset, count, flags);
1559 if (!(bs->open_flags & BDRV_O_UNMAP)) {
1560 flags &= ~BDRV_REQ_MAY_UNMAP;
1563 return bdrv_co_pwritev(bs, offset, count, NULL,
1564 BDRV_REQ_ZERO_WRITE | flags);
1567 typedef struct BdrvCoGetBlockStatusData {
1568 BlockDriverState *bs;
1569 BlockDriverState *base;
1570 BlockDriverState **file;
1571 int64_t sector_num;
1572 int nb_sectors;
1573 int *pnum;
1574 int64_t ret;
1575 bool done;
1576 } BdrvCoGetBlockStatusData;
1579 * Returns the allocation status of the specified sectors.
1580 * Drivers not implementing the functionality are assumed to not support
1581 * backing files, hence all their sectors are reported as allocated.
1583 * If 'sector_num' is beyond the end of the disk image the return value is 0
1584 * and 'pnum' is set to 0.
1586 * 'pnum' is set to the number of sectors (including and immediately following
1587 * the specified sector) that are known to be in the same
1588 * allocated/unallocated state.
1590 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1591 * beyond the end of the disk image it will be clamped.
1593 * If returned value is positive and BDRV_BLOCK_OFFSET_VALID bit is set, 'file'
1594 * points to the BDS which the sector range is allocated in.
1596 static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
1597 int64_t sector_num,
1598 int nb_sectors, int *pnum,
1599 BlockDriverState **file)
1601 int64_t total_sectors;
1602 int64_t n;
1603 int64_t ret, ret2;
1605 total_sectors = bdrv_nb_sectors(bs);
1606 if (total_sectors < 0) {
1607 return total_sectors;
1610 if (sector_num >= total_sectors) {
1611 *pnum = 0;
1612 return 0;
1615 n = total_sectors - sector_num;
1616 if (n < nb_sectors) {
1617 nb_sectors = n;
1620 if (!bs->drv->bdrv_co_get_block_status) {
1621 *pnum = nb_sectors;
1622 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
1623 if (bs->drv->protocol_name) {
1624 ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
1626 return ret;
1629 *file = NULL;
1630 ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum,
1631 file);
1632 if (ret < 0) {
1633 *pnum = 0;
1634 return ret;
1637 if (ret & BDRV_BLOCK_RAW) {
1638 assert(ret & BDRV_BLOCK_OFFSET_VALID);
1639 return bdrv_get_block_status(bs->file->bs, ret >> BDRV_SECTOR_BITS,
1640 *pnum, pnum, file);
1643 if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
1644 ret |= BDRV_BLOCK_ALLOCATED;
1645 } else {
1646 if (bdrv_unallocated_blocks_are_zero(bs)) {
1647 ret |= BDRV_BLOCK_ZERO;
1648 } else if (bs->backing) {
1649 BlockDriverState *bs2 = bs->backing->bs;
1650 int64_t nb_sectors2 = bdrv_nb_sectors(bs2);
1651 if (nb_sectors2 >= 0 && sector_num >= nb_sectors2) {
1652 ret |= BDRV_BLOCK_ZERO;
1657 if (*file && *file != bs &&
1658 (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
1659 (ret & BDRV_BLOCK_OFFSET_VALID)) {
1660 BlockDriverState *file2;
1661 int file_pnum;
1663 ret2 = bdrv_co_get_block_status(*file, ret >> BDRV_SECTOR_BITS,
1664 *pnum, &file_pnum, &file2);
1665 if (ret2 >= 0) {
1666 /* Ignore errors. This is just providing extra information, it
1667 * is useful but not necessary.
1669 if (!file_pnum) {
1670 /* !file_pnum indicates an offset at or beyond the EOF; it is
1671 * perfectly valid for the format block driver to point to such
1672 * offsets, so catch it and mark everything as zero */
1673 ret |= BDRV_BLOCK_ZERO;
1674 } else {
1675 /* Limit request to the range reported by the protocol driver */
1676 *pnum = file_pnum;
1677 ret |= (ret2 & BDRV_BLOCK_ZERO);
1682 return ret;
1685 static int64_t coroutine_fn bdrv_co_get_block_status_above(BlockDriverState *bs,
1686 BlockDriverState *base,
1687 int64_t sector_num,
1688 int nb_sectors,
1689 int *pnum,
1690 BlockDriverState **file)
1692 BlockDriverState *p;
1693 int64_t ret = 0;
1695 assert(bs != base);
1696 for (p = bs; p != base; p = backing_bs(p)) {
1697 ret = bdrv_co_get_block_status(p, sector_num, nb_sectors, pnum, file);
1698 if (ret < 0 || ret & BDRV_BLOCK_ALLOCATED) {
1699 break;
1701 /* [sector_num, pnum] unallocated on this layer, which could be only
1702 * the first part of [sector_num, nb_sectors]. */
1703 nb_sectors = MIN(nb_sectors, *pnum);
1705 return ret;
1708 /* Coroutine wrapper for bdrv_get_block_status_above() */
1709 static void coroutine_fn bdrv_get_block_status_above_co_entry(void *opaque)
1711 BdrvCoGetBlockStatusData *data = opaque;
1713 data->ret = bdrv_co_get_block_status_above(data->bs, data->base,
1714 data->sector_num,
1715 data->nb_sectors,
1716 data->pnum,
1717 data->file);
1718 data->done = true;
1722 * Synchronous wrapper around bdrv_co_get_block_status_above().
1724 * See bdrv_co_get_block_status_above() for details.
1726 int64_t bdrv_get_block_status_above(BlockDriverState *bs,
1727 BlockDriverState *base,
1728 int64_t sector_num,
1729 int nb_sectors, int *pnum,
1730 BlockDriverState **file)
1732 Coroutine *co;
1733 BdrvCoGetBlockStatusData data = {
1734 .bs = bs,
1735 .base = base,
1736 .file = file,
1737 .sector_num = sector_num,
1738 .nb_sectors = nb_sectors,
1739 .pnum = pnum,
1740 .done = false,
1743 if (qemu_in_coroutine()) {
1744 /* Fast-path if already in coroutine context */
1745 bdrv_get_block_status_above_co_entry(&data);
1746 } else {
1747 AioContext *aio_context = bdrv_get_aio_context(bs);
1749 co = qemu_coroutine_create(bdrv_get_block_status_above_co_entry);
1750 qemu_coroutine_enter(co, &data);
1751 while (!data.done) {
1752 aio_poll(aio_context, true);
1755 return data.ret;
1758 int64_t bdrv_get_block_status(BlockDriverState *bs,
1759 int64_t sector_num,
1760 int nb_sectors, int *pnum,
1761 BlockDriverState **file)
1763 return bdrv_get_block_status_above(bs, backing_bs(bs),
1764 sector_num, nb_sectors, pnum, file);
1767 int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
1768 int nb_sectors, int *pnum)
1770 BlockDriverState *file;
1771 int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum,
1772 &file);
1773 if (ret < 0) {
1774 return ret;
1776 return !!(ret & BDRV_BLOCK_ALLOCATED);
1780 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
1782 * Return true if the given sector is allocated in any image between
1783 * BASE and TOP (inclusive). BASE can be NULL to check if the given
1784 * sector is allocated in any image of the chain. Return false otherwise.
1786 * 'pnum' is set to the number of sectors (including and immediately following
1787 * the specified sector) that are known to be in the same
1788 * allocated/unallocated state.
1791 int bdrv_is_allocated_above(BlockDriverState *top,
1792 BlockDriverState *base,
1793 int64_t sector_num,
1794 int nb_sectors, int *pnum)
1796 BlockDriverState *intermediate;
1797 int ret, n = nb_sectors;
1799 intermediate = top;
1800 while (intermediate && intermediate != base) {
1801 int pnum_inter;
1802 ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
1803 &pnum_inter);
1804 if (ret < 0) {
1805 return ret;
1806 } else if (ret) {
1807 *pnum = pnum_inter;
1808 return 1;
1812 * [sector_num, nb_sectors] is unallocated on top but intermediate
1813 * might have
1815 * [sector_num+x, nr_sectors] allocated.
1817 if (n > pnum_inter &&
1818 (intermediate == top ||
1819 sector_num + pnum_inter < intermediate->total_sectors)) {
1820 n = pnum_inter;
1823 intermediate = backing_bs(intermediate);
1826 *pnum = n;
1827 return 0;
1830 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1831 const uint8_t *buf, int nb_sectors)
1833 BlockDriver *drv = bs->drv;
1834 int ret;
1836 if (!drv) {
1837 return -ENOMEDIUM;
1839 if (!drv->bdrv_write_compressed) {
1840 return -ENOTSUP;
1842 ret = bdrv_check_request(bs, sector_num, nb_sectors);
1843 if (ret < 0) {
1844 return ret;
1847 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
1849 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1852 typedef struct BdrvVmstateCo {
1853 BlockDriverState *bs;
1854 QEMUIOVector *qiov;
1855 int64_t pos;
1856 bool is_read;
1857 int ret;
1858 } BdrvVmstateCo;
1860 static int coroutine_fn
1861 bdrv_co_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos,
1862 bool is_read)
1864 BlockDriver *drv = bs->drv;
1866 if (!drv) {
1867 return -ENOMEDIUM;
1868 } else if (drv->bdrv_load_vmstate) {
1869 return is_read ? drv->bdrv_load_vmstate(bs, qiov, pos)
1870 : drv->bdrv_save_vmstate(bs, qiov, pos);
1871 } else if (bs->file) {
1872 return bdrv_co_rw_vmstate(bs->file->bs, qiov, pos, is_read);
1875 return -ENOTSUP;
1878 static void coroutine_fn bdrv_co_rw_vmstate_entry(void *opaque)
1880 BdrvVmstateCo *co = opaque;
1881 co->ret = bdrv_co_rw_vmstate(co->bs, co->qiov, co->pos, co->is_read);
1884 static inline int
1885 bdrv_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos,
1886 bool is_read)
1888 if (qemu_in_coroutine()) {
1889 return bdrv_co_rw_vmstate(bs, qiov, pos, is_read);
1890 } else {
1891 BdrvVmstateCo data = {
1892 .bs = bs,
1893 .qiov = qiov,
1894 .pos = pos,
1895 .is_read = is_read,
1896 .ret = -EINPROGRESS,
1898 Coroutine *co = qemu_coroutine_create(bdrv_co_rw_vmstate_entry);
1900 qemu_coroutine_enter(co, &data);
1901 while (data.ret == -EINPROGRESS) {
1902 aio_poll(bdrv_get_aio_context(bs), true);
1904 return data.ret;
1908 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1909 int64_t pos, int size)
1911 QEMUIOVector qiov;
1912 struct iovec iov = {
1913 .iov_base = (void *) buf,
1914 .iov_len = size,
1916 int ret;
1918 qemu_iovec_init_external(&qiov, &iov, 1);
1920 ret = bdrv_writev_vmstate(bs, &qiov, pos);
1921 if (ret < 0) {
1922 return ret;
1925 return size;
1928 int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
1930 return bdrv_rw_vmstate(bs, qiov, pos, false);
1933 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1934 int64_t pos, int size)
1936 QEMUIOVector qiov;
1937 struct iovec iov = {
1938 .iov_base = buf,
1939 .iov_len = size,
1941 int ret;
1943 qemu_iovec_init_external(&qiov, &iov, 1);
1944 ret = bdrv_readv_vmstate(bs, &qiov, pos);
1945 if (ret < 0) {
1946 return ret;
1949 return size;
1952 int bdrv_readv_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
1954 return bdrv_rw_vmstate(bs, qiov, pos, true);
1957 /**************************************************************/
1958 /* async I/Os */
1960 BlockAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
1961 QEMUIOVector *qiov, int nb_sectors,
1962 BlockCompletionFunc *cb, void *opaque)
1964 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
1966 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
1967 cb, opaque, false);
1970 BlockAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
1971 QEMUIOVector *qiov, int nb_sectors,
1972 BlockCompletionFunc *cb, void *opaque)
1974 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
1976 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
1977 cb, opaque, true);
1980 void bdrv_aio_cancel(BlockAIOCB *acb)
1982 qemu_aio_ref(acb);
1983 bdrv_aio_cancel_async(acb);
1984 while (acb->refcnt > 1) {
1985 if (acb->aiocb_info->get_aio_context) {
1986 aio_poll(acb->aiocb_info->get_aio_context(acb), true);
1987 } else if (acb->bs) {
1988 aio_poll(bdrv_get_aio_context(acb->bs), true);
1989 } else {
1990 abort();
1993 qemu_aio_unref(acb);
1996 /* Async version of aio cancel. The caller is not blocked if the acb implements
1997 * cancel_async, otherwise we do nothing and let the request normally complete.
1998 * In either case the completion callback must be called. */
1999 void bdrv_aio_cancel_async(BlockAIOCB *acb)
2001 if (acb->aiocb_info->cancel_async) {
2002 acb->aiocb_info->cancel_async(acb);
2006 /**************************************************************/
2007 /* async block device emulation */
2009 typedef struct BlockRequest {
2010 union {
2011 /* Used during read, write, trim */
2012 struct {
2013 int64_t sector;
2014 int nb_sectors;
2015 int flags;
2016 QEMUIOVector *qiov;
2018 /* Used during ioctl */
2019 struct {
2020 int req;
2021 void *buf;
2024 BlockCompletionFunc *cb;
2025 void *opaque;
2027 int error;
2028 } BlockRequest;
2030 typedef struct BlockAIOCBCoroutine {
2031 BlockAIOCB common;
2032 BlockRequest req;
2033 bool is_write;
2034 bool need_bh;
2035 bool *done;
2036 QEMUBH* bh;
2037 } BlockAIOCBCoroutine;
2039 static const AIOCBInfo bdrv_em_co_aiocb_info = {
2040 .aiocb_size = sizeof(BlockAIOCBCoroutine),
2043 static void bdrv_co_complete(BlockAIOCBCoroutine *acb)
2045 if (!acb->need_bh) {
2046 acb->common.cb(acb->common.opaque, acb->req.error);
2047 qemu_aio_unref(acb);
2051 static void bdrv_co_em_bh(void *opaque)
2053 BlockAIOCBCoroutine *acb = opaque;
2055 assert(!acb->need_bh);
2056 qemu_bh_delete(acb->bh);
2057 bdrv_co_complete(acb);
2060 static void bdrv_co_maybe_schedule_bh(BlockAIOCBCoroutine *acb)
2062 acb->need_bh = false;
2063 if (acb->req.error != -EINPROGRESS) {
2064 BlockDriverState *bs = acb->common.bs;
2066 acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb);
2067 qemu_bh_schedule(acb->bh);
2071 /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
2072 static void coroutine_fn bdrv_co_do_rw(void *opaque)
2074 BlockAIOCBCoroutine *acb = opaque;
2075 BlockDriverState *bs = acb->common.bs;
2077 if (!acb->is_write) {
2078 acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
2079 acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
2080 } else {
2081 acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
2082 acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
2085 bdrv_co_complete(acb);
2088 static BlockAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
2089 int64_t sector_num,
2090 QEMUIOVector *qiov,
2091 int nb_sectors,
2092 BdrvRequestFlags flags,
2093 BlockCompletionFunc *cb,
2094 void *opaque,
2095 bool is_write)
2097 Coroutine *co;
2098 BlockAIOCBCoroutine *acb;
2100 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
2101 acb->need_bh = true;
2102 acb->req.error = -EINPROGRESS;
2103 acb->req.sector = sector_num;
2104 acb->req.nb_sectors = nb_sectors;
2105 acb->req.qiov = qiov;
2106 acb->req.flags = flags;
2107 acb->is_write = is_write;
2109 co = qemu_coroutine_create(bdrv_co_do_rw);
2110 qemu_coroutine_enter(co, acb);
2112 bdrv_co_maybe_schedule_bh(acb);
2113 return &acb->common;
2116 static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
2118 BlockAIOCBCoroutine *acb = opaque;
2119 BlockDriverState *bs = acb->common.bs;
2121 acb->req.error = bdrv_co_flush(bs);
2122 bdrv_co_complete(acb);
2125 BlockAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2126 BlockCompletionFunc *cb, void *opaque)
2128 trace_bdrv_aio_flush(bs, opaque);
2130 Coroutine *co;
2131 BlockAIOCBCoroutine *acb;
2133 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
2134 acb->need_bh = true;
2135 acb->req.error = -EINPROGRESS;
2137 co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
2138 qemu_coroutine_enter(co, acb);
2140 bdrv_co_maybe_schedule_bh(acb);
2141 return &acb->common;
2144 static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
2146 BlockAIOCBCoroutine *acb = opaque;
2147 BlockDriverState *bs = acb->common.bs;
2149 acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
2150 bdrv_co_complete(acb);
2153 BlockAIOCB *bdrv_aio_discard(BlockDriverState *bs,
2154 int64_t sector_num, int nb_sectors,
2155 BlockCompletionFunc *cb, void *opaque)
2157 Coroutine *co;
2158 BlockAIOCBCoroutine *acb;
2160 trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
2162 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
2163 acb->need_bh = true;
2164 acb->req.error = -EINPROGRESS;
2165 acb->req.sector = sector_num;
2166 acb->req.nb_sectors = nb_sectors;
2167 co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
2168 qemu_coroutine_enter(co, acb);
2170 bdrv_co_maybe_schedule_bh(acb);
2171 return &acb->common;
2174 void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
2175 BlockCompletionFunc *cb, void *opaque)
2177 BlockAIOCB *acb;
2179 acb = g_malloc(aiocb_info->aiocb_size);
2180 acb->aiocb_info = aiocb_info;
2181 acb->bs = bs;
2182 acb->cb = cb;
2183 acb->opaque = opaque;
2184 acb->refcnt = 1;
2185 return acb;
2188 void qemu_aio_ref(void *p)
2190 BlockAIOCB *acb = p;
2191 acb->refcnt++;
2194 void qemu_aio_unref(void *p)
2196 BlockAIOCB *acb = p;
2197 assert(acb->refcnt > 0);
2198 if (--acb->refcnt == 0) {
2199 g_free(acb);
2203 /**************************************************************/
2204 /* Coroutine block device emulation */
2206 static void coroutine_fn bdrv_flush_co_entry(void *opaque)
2208 RwCo *rwco = opaque;
2210 rwco->ret = bdrv_co_flush(rwco->bs);
2213 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
2215 int ret;
2216 BdrvTrackedRequest req;
2218 if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||
2219 bdrv_is_sg(bs)) {
2220 return 0;
2223 tracked_request_begin(&req, bs, 0, 0, BDRV_TRACKED_FLUSH);
2225 /* Write back all layers by calling one driver function */
2226 if (bs->drv->bdrv_co_flush) {
2227 ret = bs->drv->bdrv_co_flush(bs);
2228 goto out;
2231 /* Write back cached data to the OS even with cache=unsafe */
2232 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
2233 if (bs->drv->bdrv_co_flush_to_os) {
2234 ret = bs->drv->bdrv_co_flush_to_os(bs);
2235 if (ret < 0) {
2236 goto out;
2240 /* But don't actually force it to the disk with cache=unsafe */
2241 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2242 goto flush_parent;
2245 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
2246 if (bs->drv->bdrv_co_flush_to_disk) {
2247 ret = bs->drv->bdrv_co_flush_to_disk(bs);
2248 } else if (bs->drv->bdrv_aio_flush) {
2249 BlockAIOCB *acb;
2250 CoroutineIOCompletion co = {
2251 .coroutine = qemu_coroutine_self(),
2254 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
2255 if (acb == NULL) {
2256 ret = -EIO;
2257 } else {
2258 qemu_coroutine_yield();
2259 ret = co.ret;
2261 } else {
2263 * Some block drivers always operate in either writethrough or unsafe
2264 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2265 * know how the server works (because the behaviour is hardcoded or
2266 * depends on server-side configuration), so we can't ensure that
2267 * everything is safe on disk. Returning an error doesn't work because
2268 * that would break guests even if the server operates in writethrough
2269 * mode.
2271 * Let's hope the user knows what he's doing.
2273 ret = 0;
2275 if (ret < 0) {
2276 goto out;
2279 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2280 * in the case of cache=unsafe, so there are no useless flushes.
2282 flush_parent:
2283 ret = bs->file ? bdrv_co_flush(bs->file->bs) : 0;
2284 out:
2285 tracked_request_end(&req);
2286 return ret;
2289 int bdrv_flush(BlockDriverState *bs)
2291 Coroutine *co;
2292 RwCo rwco = {
2293 .bs = bs,
2294 .ret = NOT_DONE,
2297 if (qemu_in_coroutine()) {
2298 /* Fast-path if already in coroutine context */
2299 bdrv_flush_co_entry(&rwco);
2300 } else {
2301 AioContext *aio_context = bdrv_get_aio_context(bs);
2303 co = qemu_coroutine_create(bdrv_flush_co_entry);
2304 qemu_coroutine_enter(co, &rwco);
2305 while (rwco.ret == NOT_DONE) {
2306 aio_poll(aio_context, true);
2310 return rwco.ret;
2313 typedef struct DiscardCo {
2314 BlockDriverState *bs;
2315 int64_t sector_num;
2316 int nb_sectors;
2317 int ret;
2318 } DiscardCo;
2319 static void coroutine_fn bdrv_discard_co_entry(void *opaque)
2321 DiscardCo *rwco = opaque;
2323 rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
2326 int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
2327 int nb_sectors)
2329 BdrvTrackedRequest req;
2330 int max_discard, ret;
2332 if (!bs->drv) {
2333 return -ENOMEDIUM;
2336 ret = bdrv_check_request(bs, sector_num, nb_sectors);
2337 if (ret < 0) {
2338 return ret;
2339 } else if (bs->read_only) {
2340 return -EPERM;
2342 assert(!(bs->open_flags & BDRV_O_INACTIVE));
2344 /* Do nothing if disabled. */
2345 if (!(bs->open_flags & BDRV_O_UNMAP)) {
2346 return 0;
2349 if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) {
2350 return 0;
2353 tracked_request_begin(&req, bs, sector_num << BDRV_SECTOR_BITS,
2354 nb_sectors << BDRV_SECTOR_BITS, BDRV_TRACKED_DISCARD);
2356 ret = notifier_with_return_list_notify(&bs->before_write_notifiers, &req);
2357 if (ret < 0) {
2358 goto out;
2361 max_discard = MIN_NON_ZERO(bs->bl.max_discard, BDRV_REQUEST_MAX_SECTORS);
2362 while (nb_sectors > 0) {
2363 int ret;
2364 int num = nb_sectors;
2366 /* align request */
2367 if (bs->bl.discard_alignment &&
2368 num >= bs->bl.discard_alignment &&
2369 sector_num % bs->bl.discard_alignment) {
2370 if (num > bs->bl.discard_alignment) {
2371 num = bs->bl.discard_alignment;
2373 num -= sector_num % bs->bl.discard_alignment;
2376 /* limit request size */
2377 if (num > max_discard) {
2378 num = max_discard;
2381 if (bs->drv->bdrv_co_discard) {
2382 ret = bs->drv->bdrv_co_discard(bs, sector_num, num);
2383 } else {
2384 BlockAIOCB *acb;
2385 CoroutineIOCompletion co = {
2386 .coroutine = qemu_coroutine_self(),
2389 acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
2390 bdrv_co_io_em_complete, &co);
2391 if (acb == NULL) {
2392 ret = -EIO;
2393 goto out;
2394 } else {
2395 qemu_coroutine_yield();
2396 ret = co.ret;
2399 if (ret && ret != -ENOTSUP) {
2400 goto out;
2403 sector_num += num;
2404 nb_sectors -= num;
2406 ret = 0;
2407 out:
2408 bdrv_set_dirty(bs, req.offset >> BDRV_SECTOR_BITS,
2409 req.bytes >> BDRV_SECTOR_BITS);
2410 tracked_request_end(&req);
2411 return ret;
2414 int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
2416 Coroutine *co;
2417 DiscardCo rwco = {
2418 .bs = bs,
2419 .sector_num = sector_num,
2420 .nb_sectors = nb_sectors,
2421 .ret = NOT_DONE,
2424 if (qemu_in_coroutine()) {
2425 /* Fast-path if already in coroutine context */
2426 bdrv_discard_co_entry(&rwco);
2427 } else {
2428 AioContext *aio_context = bdrv_get_aio_context(bs);
2430 co = qemu_coroutine_create(bdrv_discard_co_entry);
2431 qemu_coroutine_enter(co, &rwco);
2432 while (rwco.ret == NOT_DONE) {
2433 aio_poll(aio_context, true);
2437 return rwco.ret;
2440 static int bdrv_co_do_ioctl(BlockDriverState *bs, int req, void *buf)
2442 BlockDriver *drv = bs->drv;
2443 BdrvTrackedRequest tracked_req;
2444 CoroutineIOCompletion co = {
2445 .coroutine = qemu_coroutine_self(),
2447 BlockAIOCB *acb;
2449 tracked_request_begin(&tracked_req, bs, 0, 0, BDRV_TRACKED_IOCTL);
2450 if (!drv || !drv->bdrv_aio_ioctl) {
2451 co.ret = -ENOTSUP;
2452 goto out;
2455 acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
2456 if (!acb) {
2457 co.ret = -ENOTSUP;
2458 goto out;
2460 qemu_coroutine_yield();
2461 out:
2462 tracked_request_end(&tracked_req);
2463 return co.ret;
2466 typedef struct {
2467 BlockDriverState *bs;
2468 int req;
2469 void *buf;
2470 int ret;
2471 } BdrvIoctlCoData;
2473 static void coroutine_fn bdrv_co_ioctl_entry(void *opaque)
2475 BdrvIoctlCoData *data = opaque;
2476 data->ret = bdrv_co_do_ioctl(data->bs, data->req, data->buf);
2479 /* needed for generic scsi interface */
2480 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2482 BdrvIoctlCoData data = {
2483 .bs = bs,
2484 .req = req,
2485 .buf = buf,
2486 .ret = -EINPROGRESS,
2489 if (qemu_in_coroutine()) {
2490 /* Fast-path if already in coroutine context */
2491 bdrv_co_ioctl_entry(&data);
2492 } else {
2493 Coroutine *co = qemu_coroutine_create(bdrv_co_ioctl_entry);
2495 qemu_coroutine_enter(co, &data);
2496 while (data.ret == -EINPROGRESS) {
2497 aio_poll(bdrv_get_aio_context(bs), true);
2500 return data.ret;
2503 static void coroutine_fn bdrv_co_aio_ioctl_entry(void *opaque)
2505 BlockAIOCBCoroutine *acb = opaque;
2506 acb->req.error = bdrv_co_do_ioctl(acb->common.bs,
2507 acb->req.req, acb->req.buf);
2508 bdrv_co_complete(acb);
2511 BlockAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
2512 unsigned long int req, void *buf,
2513 BlockCompletionFunc *cb, void *opaque)
2515 BlockAIOCBCoroutine *acb = qemu_aio_get(&bdrv_em_co_aiocb_info,
2516 bs, cb, opaque);
2517 Coroutine *co;
2519 acb->need_bh = true;
2520 acb->req.error = -EINPROGRESS;
2521 acb->req.req = req;
2522 acb->req.buf = buf;
2523 co = qemu_coroutine_create(bdrv_co_aio_ioctl_entry);
2524 qemu_coroutine_enter(co, acb);
2526 bdrv_co_maybe_schedule_bh(acb);
2527 return &acb->common;
2530 void *qemu_blockalign(BlockDriverState *bs, size_t size)
2532 return qemu_memalign(bdrv_opt_mem_align(bs), size);
2535 void *qemu_blockalign0(BlockDriverState *bs, size_t size)
2537 return memset(qemu_blockalign(bs, size), 0, size);
2540 void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
2542 size_t align = bdrv_opt_mem_align(bs);
2544 /* Ensure that NULL is never returned on success */
2545 assert(align > 0);
2546 if (size == 0) {
2547 size = align;
2550 return qemu_try_memalign(align, size);
2553 void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
2555 void *mem = qemu_try_blockalign(bs, size);
2557 if (mem) {
2558 memset(mem, 0, size);
2561 return mem;
2565 * Check if all memory in this vector is sector aligned.
2567 bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
2569 int i;
2570 size_t alignment = bdrv_min_mem_align(bs);
2572 for (i = 0; i < qiov->niov; i++) {
2573 if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
2574 return false;
2576 if (qiov->iov[i].iov_len % alignment) {
2577 return false;
2581 return true;
2584 void bdrv_add_before_write_notifier(BlockDriverState *bs,
2585 NotifierWithReturn *notifier)
2587 notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
2590 void bdrv_io_plug(BlockDriverState *bs)
2592 BdrvChild *child;
2594 QLIST_FOREACH(child, &bs->children, next) {
2595 bdrv_io_plug(child->bs);
2598 if (bs->io_plugged++ == 0 && bs->io_plug_disabled == 0) {
2599 BlockDriver *drv = bs->drv;
2600 if (drv && drv->bdrv_io_plug) {
2601 drv->bdrv_io_plug(bs);
2606 void bdrv_io_unplug(BlockDriverState *bs)
2608 BdrvChild *child;
2610 assert(bs->io_plugged);
2611 if (--bs->io_plugged == 0 && bs->io_plug_disabled == 0) {
2612 BlockDriver *drv = bs->drv;
2613 if (drv && drv->bdrv_io_unplug) {
2614 drv->bdrv_io_unplug(bs);
2618 QLIST_FOREACH(child, &bs->children, next) {
2619 bdrv_io_unplug(child->bs);
2623 void bdrv_io_unplugged_begin(BlockDriverState *bs)
2625 BdrvChild *child;
2627 if (bs->io_plug_disabled++ == 0 && bs->io_plugged > 0) {
2628 BlockDriver *drv = bs->drv;
2629 if (drv && drv->bdrv_io_unplug) {
2630 drv->bdrv_io_unplug(bs);
2634 QLIST_FOREACH(child, &bs->children, next) {
2635 bdrv_io_unplugged_begin(child->bs);
2639 void bdrv_io_unplugged_end(BlockDriverState *bs)
2641 BdrvChild *child;
2643 assert(bs->io_plug_disabled);
2644 QLIST_FOREACH(child, &bs->children, next) {
2645 bdrv_io_unplugged_end(child->bs);
2648 if (--bs->io_plug_disabled == 0 && bs->io_plugged > 0) {
2649 BlockDriver *drv = bs->drv;
2650 if (drv && drv->bdrv_io_plug) {
2651 drv->bdrv_io_plug(bs);