block: protect tracked_requests and flush_queue with reqs_lock
[qemu.git] / block / io.c
blob91611ffb2aa627c5743e2f66d5da65e4ced73dac
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/blockjob_int.h"
30 #include "block/block_int.h"
31 #include "qemu/cutils.h"
32 #include "qapi/error.h"
33 #include "qemu/error-report.h"
35 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
37 static BlockAIOCB *bdrv_co_aio_prw_vector(BdrvChild *child,
38 int64_t offset,
39 QEMUIOVector *qiov,
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 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 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 static void bdrv_merge_limits(BlockLimits *dst, const BlockLimits *src)
72 dst->opt_transfer = MAX(dst->opt_transfer, src->opt_transfer);
73 dst->max_transfer = MIN_NON_ZERO(dst->max_transfer, src->max_transfer);
74 dst->opt_mem_alignment = MAX(dst->opt_mem_alignment,
75 src->opt_mem_alignment);
76 dst->min_mem_alignment = MAX(dst->min_mem_alignment,
77 src->min_mem_alignment);
78 dst->max_iov = MIN_NON_ZERO(dst->max_iov, src->max_iov);
81 void bdrv_refresh_limits(BlockDriverState *bs, Error **errp)
83 BlockDriver *drv = bs->drv;
84 Error *local_err = NULL;
86 memset(&bs->bl, 0, sizeof(bs->bl));
88 if (!drv) {
89 return;
92 /* Default alignment based on whether driver has byte interface */
93 bs->bl.request_alignment = drv->bdrv_co_preadv ? 1 : 512;
95 /* Take some limits from the children as a default */
96 if (bs->file) {
97 bdrv_refresh_limits(bs->file->bs, &local_err);
98 if (local_err) {
99 error_propagate(errp, local_err);
100 return;
102 bdrv_merge_limits(&bs->bl, &bs->file->bs->bl);
103 } else {
104 bs->bl.min_mem_alignment = 512;
105 bs->bl.opt_mem_alignment = getpagesize();
107 /* Safe default since most protocols use readv()/writev()/etc */
108 bs->bl.max_iov = IOV_MAX;
111 if (bs->backing) {
112 bdrv_refresh_limits(bs->backing->bs, &local_err);
113 if (local_err) {
114 error_propagate(errp, local_err);
115 return;
117 bdrv_merge_limits(&bs->bl, &bs->backing->bs->bl);
120 /* Then let the driver override it */
121 if (drv->bdrv_refresh_limits) {
122 drv->bdrv_refresh_limits(bs, errp);
127 * The copy-on-read flag is actually a reference count so multiple users may
128 * use the feature without worrying about clobbering its previous state.
129 * Copy-on-read stays enabled until all users have called to disable it.
131 void bdrv_enable_copy_on_read(BlockDriverState *bs)
133 atomic_inc(&bs->copy_on_read);
136 void bdrv_disable_copy_on_read(BlockDriverState *bs)
138 int old = atomic_fetch_dec(&bs->copy_on_read);
139 assert(old >= 1);
142 /* Check if any requests are in-flight (including throttled requests) */
143 bool bdrv_requests_pending(BlockDriverState *bs)
145 BdrvChild *child;
147 if (atomic_read(&bs->in_flight)) {
148 return true;
151 QLIST_FOREACH(child, &bs->children, next) {
152 if (bdrv_requests_pending(child->bs)) {
153 return true;
157 return false;
160 static bool bdrv_drain_recurse(BlockDriverState *bs)
162 BdrvChild *child, *tmp;
163 bool waited;
165 waited = BDRV_POLL_WHILE(bs, atomic_read(&bs->in_flight) > 0);
167 if (bs->drv && bs->drv->bdrv_drain) {
168 bs->drv->bdrv_drain(bs);
171 QLIST_FOREACH_SAFE(child, &bs->children, next, tmp) {
172 BlockDriverState *bs = child->bs;
173 bool in_main_loop =
174 qemu_get_current_aio_context() == qemu_get_aio_context();
175 assert(bs->refcnt > 0);
176 if (in_main_loop) {
177 /* In case the recursive bdrv_drain_recurse processes a
178 * block_job_defer_to_main_loop BH and modifies the graph,
179 * let's hold a reference to bs until we are done.
181 * IOThread doesn't have such a BH, and it is not safe to call
182 * bdrv_unref without BQL, so skip doing it there.
184 bdrv_ref(bs);
186 waited |= bdrv_drain_recurse(bs);
187 if (in_main_loop) {
188 bdrv_unref(bs);
192 return waited;
195 typedef struct {
196 Coroutine *co;
197 BlockDriverState *bs;
198 bool done;
199 } BdrvCoDrainData;
201 static void bdrv_co_drain_bh_cb(void *opaque)
203 BdrvCoDrainData *data = opaque;
204 Coroutine *co = data->co;
205 BlockDriverState *bs = data->bs;
207 bdrv_dec_in_flight(bs);
208 bdrv_drained_begin(bs);
209 data->done = true;
210 aio_co_wake(co);
213 static void coroutine_fn bdrv_co_yield_to_drain(BlockDriverState *bs)
215 BdrvCoDrainData data;
217 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
218 * other coroutines run if they were queued from
219 * qemu_co_queue_run_restart(). */
221 assert(qemu_in_coroutine());
222 data = (BdrvCoDrainData) {
223 .co = qemu_coroutine_self(),
224 .bs = bs,
225 .done = false,
227 bdrv_inc_in_flight(bs);
228 aio_bh_schedule_oneshot(bdrv_get_aio_context(bs),
229 bdrv_co_drain_bh_cb, &data);
231 qemu_coroutine_yield();
232 /* If we are resumed from some other event (such as an aio completion or a
233 * timer callback), it is a bug in the caller that should be fixed. */
234 assert(data.done);
237 void bdrv_drained_begin(BlockDriverState *bs)
239 if (qemu_in_coroutine()) {
240 bdrv_co_yield_to_drain(bs);
241 return;
244 if (atomic_fetch_inc(&bs->quiesce_counter) == 0) {
245 aio_disable_external(bdrv_get_aio_context(bs));
246 bdrv_parent_drained_begin(bs);
249 bdrv_drain_recurse(bs);
252 void bdrv_drained_end(BlockDriverState *bs)
254 assert(bs->quiesce_counter > 0);
255 if (atomic_fetch_dec(&bs->quiesce_counter) > 1) {
256 return;
259 bdrv_parent_drained_end(bs);
260 aio_enable_external(bdrv_get_aio_context(bs));
264 * Wait for pending requests to complete on a single BlockDriverState subtree,
265 * and suspend block driver's internal I/O until next request arrives.
267 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
268 * AioContext.
270 * Only this BlockDriverState's AioContext is run, so in-flight requests must
271 * not depend on events in other AioContexts. In that case, use
272 * bdrv_drain_all() instead.
274 void coroutine_fn bdrv_co_drain(BlockDriverState *bs)
276 assert(qemu_in_coroutine());
277 bdrv_drained_begin(bs);
278 bdrv_drained_end(bs);
281 void bdrv_drain(BlockDriverState *bs)
283 bdrv_drained_begin(bs);
284 bdrv_drained_end(bs);
288 * Wait for pending requests to complete across all BlockDriverStates
290 * This function does not flush data to disk, use bdrv_flush_all() for that
291 * after calling this function.
293 * This pauses all block jobs and disables external clients. It must
294 * be paired with bdrv_drain_all_end().
296 * NOTE: no new block jobs or BlockDriverStates can be created between
297 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
299 void bdrv_drain_all_begin(void)
301 /* Always run first iteration so any pending completion BHs run */
302 bool waited = true;
303 BlockDriverState *bs;
304 BdrvNextIterator it;
305 GSList *aio_ctxs = NULL, *ctx;
307 block_job_pause_all();
309 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
310 AioContext *aio_context = bdrv_get_aio_context(bs);
312 aio_context_acquire(aio_context);
313 bdrv_parent_drained_begin(bs);
314 aio_disable_external(aio_context);
315 aio_context_release(aio_context);
317 if (!g_slist_find(aio_ctxs, aio_context)) {
318 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
322 /* Note that completion of an asynchronous I/O operation can trigger any
323 * number of other I/O operations on other devices---for example a
324 * coroutine can submit an I/O request to another device in response to
325 * request completion. Therefore we must keep looping until there was no
326 * more activity rather than simply draining each device independently.
328 while (waited) {
329 waited = false;
331 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
332 AioContext *aio_context = ctx->data;
334 aio_context_acquire(aio_context);
335 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
336 if (aio_context == bdrv_get_aio_context(bs)) {
337 waited |= bdrv_drain_recurse(bs);
340 aio_context_release(aio_context);
344 g_slist_free(aio_ctxs);
347 void bdrv_drain_all_end(void)
349 BlockDriverState *bs;
350 BdrvNextIterator it;
352 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
353 AioContext *aio_context = bdrv_get_aio_context(bs);
355 aio_context_acquire(aio_context);
356 aio_enable_external(aio_context);
357 bdrv_parent_drained_end(bs);
358 aio_context_release(aio_context);
361 block_job_resume_all();
364 void bdrv_drain_all(void)
366 bdrv_drain_all_begin();
367 bdrv_drain_all_end();
371 * Remove an active request from the tracked requests list
373 * This function should be called when a tracked request is completing.
375 static void tracked_request_end(BdrvTrackedRequest *req)
377 if (req->serialising) {
378 atomic_dec(&req->bs->serialising_in_flight);
381 qemu_co_mutex_lock(&req->bs->reqs_lock);
382 QLIST_REMOVE(req, list);
383 qemu_co_queue_restart_all(&req->wait_queue);
384 qemu_co_mutex_unlock(&req->bs->reqs_lock);
388 * Add an active request to the tracked requests list
390 static void tracked_request_begin(BdrvTrackedRequest *req,
391 BlockDriverState *bs,
392 int64_t offset,
393 unsigned int bytes,
394 enum BdrvTrackedRequestType type)
396 *req = (BdrvTrackedRequest){
397 .bs = bs,
398 .offset = offset,
399 .bytes = bytes,
400 .type = type,
401 .co = qemu_coroutine_self(),
402 .serialising = false,
403 .overlap_offset = offset,
404 .overlap_bytes = bytes,
407 qemu_co_queue_init(&req->wait_queue);
409 qemu_co_mutex_lock(&bs->reqs_lock);
410 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
411 qemu_co_mutex_unlock(&bs->reqs_lock);
414 static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
416 int64_t overlap_offset = req->offset & ~(align - 1);
417 unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
418 - overlap_offset;
420 if (!req->serialising) {
421 atomic_inc(&req->bs->serialising_in_flight);
422 req->serialising = true;
425 req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
426 req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
430 * Round a region to cluster boundaries (sector-based)
432 void bdrv_round_sectors_to_clusters(BlockDriverState *bs,
433 int64_t sector_num, int nb_sectors,
434 int64_t *cluster_sector_num,
435 int *cluster_nb_sectors)
437 BlockDriverInfo bdi;
439 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
440 *cluster_sector_num = sector_num;
441 *cluster_nb_sectors = nb_sectors;
442 } else {
443 int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
444 *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
445 *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
446 nb_sectors, c);
451 * Round a region to cluster boundaries
453 void bdrv_round_to_clusters(BlockDriverState *bs,
454 int64_t offset, unsigned int bytes,
455 int64_t *cluster_offset,
456 unsigned int *cluster_bytes)
458 BlockDriverInfo bdi;
460 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
461 *cluster_offset = offset;
462 *cluster_bytes = bytes;
463 } else {
464 int64_t c = bdi.cluster_size;
465 *cluster_offset = QEMU_ALIGN_DOWN(offset, c);
466 *cluster_bytes = QEMU_ALIGN_UP(offset - *cluster_offset + bytes, c);
470 static int bdrv_get_cluster_size(BlockDriverState *bs)
472 BlockDriverInfo bdi;
473 int ret;
475 ret = bdrv_get_info(bs, &bdi);
476 if (ret < 0 || bdi.cluster_size == 0) {
477 return bs->bl.request_alignment;
478 } else {
479 return bdi.cluster_size;
483 static bool tracked_request_overlaps(BdrvTrackedRequest *req,
484 int64_t offset, unsigned int bytes)
486 /* aaaa bbbb */
487 if (offset >= req->overlap_offset + req->overlap_bytes) {
488 return false;
490 /* bbbb aaaa */
491 if (req->overlap_offset >= offset + bytes) {
492 return false;
494 return true;
497 void bdrv_inc_in_flight(BlockDriverState *bs)
499 atomic_inc(&bs->in_flight);
502 static void dummy_bh_cb(void *opaque)
506 void bdrv_wakeup(BlockDriverState *bs)
508 /* The barrier (or an atomic op) is in the caller. */
509 if (atomic_read(&bs->wakeup)) {
510 aio_bh_schedule_oneshot(qemu_get_aio_context(), dummy_bh_cb, NULL);
514 void bdrv_dec_in_flight(BlockDriverState *bs)
516 atomic_dec(&bs->in_flight);
517 bdrv_wakeup(bs);
520 static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
522 BlockDriverState *bs = self->bs;
523 BdrvTrackedRequest *req;
524 bool retry;
525 bool waited = false;
527 if (!atomic_read(&bs->serialising_in_flight)) {
528 return false;
531 do {
532 retry = false;
533 qemu_co_mutex_lock(&bs->reqs_lock);
534 QLIST_FOREACH(req, &bs->tracked_requests, list) {
535 if (req == self || (!req->serialising && !self->serialising)) {
536 continue;
538 if (tracked_request_overlaps(req, self->overlap_offset,
539 self->overlap_bytes))
541 /* Hitting this means there was a reentrant request, for
542 * example, a block driver issuing nested requests. This must
543 * never happen since it means deadlock.
545 assert(qemu_coroutine_self() != req->co);
547 /* If the request is already (indirectly) waiting for us, or
548 * will wait for us as soon as it wakes up, then just go on
549 * (instead of producing a deadlock in the former case). */
550 if (!req->waiting_for) {
551 self->waiting_for = req;
552 qemu_co_queue_wait(&req->wait_queue, &bs->reqs_lock);
553 self->waiting_for = NULL;
554 retry = true;
555 waited = true;
556 break;
560 qemu_co_mutex_unlock(&bs->reqs_lock);
561 } while (retry);
563 return waited;
566 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
567 size_t size)
569 if (size > BDRV_REQUEST_MAX_SECTORS << BDRV_SECTOR_BITS) {
570 return -EIO;
573 if (!bdrv_is_inserted(bs)) {
574 return -ENOMEDIUM;
577 if (offset < 0) {
578 return -EIO;
581 return 0;
584 typedef struct RwCo {
585 BdrvChild *child;
586 int64_t offset;
587 QEMUIOVector *qiov;
588 bool is_write;
589 int ret;
590 BdrvRequestFlags flags;
591 } RwCo;
593 static void coroutine_fn bdrv_rw_co_entry(void *opaque)
595 RwCo *rwco = opaque;
597 if (!rwco->is_write) {
598 rwco->ret = bdrv_co_preadv(rwco->child, rwco->offset,
599 rwco->qiov->size, rwco->qiov,
600 rwco->flags);
601 } else {
602 rwco->ret = bdrv_co_pwritev(rwco->child, rwco->offset,
603 rwco->qiov->size, rwco->qiov,
604 rwco->flags);
609 * Process a vectored synchronous request using coroutines
611 static int bdrv_prwv_co(BdrvChild *child, int64_t offset,
612 QEMUIOVector *qiov, bool is_write,
613 BdrvRequestFlags flags)
615 Coroutine *co;
616 RwCo rwco = {
617 .child = child,
618 .offset = offset,
619 .qiov = qiov,
620 .is_write = is_write,
621 .ret = NOT_DONE,
622 .flags = flags,
625 if (qemu_in_coroutine()) {
626 /* Fast-path if already in coroutine context */
627 bdrv_rw_co_entry(&rwco);
628 } else {
629 co = qemu_coroutine_create(bdrv_rw_co_entry, &rwco);
630 bdrv_coroutine_enter(child->bs, co);
631 BDRV_POLL_WHILE(child->bs, rwco.ret == NOT_DONE);
633 return rwco.ret;
637 * Process a synchronous request using coroutines
639 static int bdrv_rw_co(BdrvChild *child, int64_t sector_num, uint8_t *buf,
640 int nb_sectors, bool is_write, BdrvRequestFlags flags)
642 QEMUIOVector qiov;
643 struct iovec iov = {
644 .iov_base = (void *)buf,
645 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
648 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
649 return -EINVAL;
652 qemu_iovec_init_external(&qiov, &iov, 1);
653 return bdrv_prwv_co(child, sector_num << BDRV_SECTOR_BITS,
654 &qiov, is_write, flags);
657 /* return < 0 if error. See bdrv_write() for the return codes */
658 int bdrv_read(BdrvChild *child, int64_t sector_num,
659 uint8_t *buf, int nb_sectors)
661 return bdrv_rw_co(child, sector_num, buf, nb_sectors, false, 0);
664 /* Return < 0 if error. Important errors are:
665 -EIO generic I/O error (may happen for all errors)
666 -ENOMEDIUM No media inserted.
667 -EINVAL Invalid sector number or nb_sectors
668 -EACCES Trying to write a read-only device
670 int bdrv_write(BdrvChild *child, int64_t sector_num,
671 const uint8_t *buf, int nb_sectors)
673 return bdrv_rw_co(child, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
676 int bdrv_pwrite_zeroes(BdrvChild *child, int64_t offset,
677 int count, BdrvRequestFlags flags)
679 QEMUIOVector qiov;
680 struct iovec iov = {
681 .iov_base = NULL,
682 .iov_len = count,
685 qemu_iovec_init_external(&qiov, &iov, 1);
686 return bdrv_prwv_co(child, offset, &qiov, true,
687 BDRV_REQ_ZERO_WRITE | flags);
691 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
692 * The operation is sped up by checking the block status and only writing
693 * zeroes to the device if they currently do not return zeroes. Optional
694 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
695 * BDRV_REQ_FUA).
697 * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
699 int bdrv_make_zero(BdrvChild *child, BdrvRequestFlags flags)
701 int64_t target_sectors, ret, nb_sectors, sector_num = 0;
702 BlockDriverState *bs = child->bs;
703 BlockDriverState *file;
704 int n;
706 target_sectors = bdrv_nb_sectors(bs);
707 if (target_sectors < 0) {
708 return target_sectors;
711 for (;;) {
712 nb_sectors = MIN(target_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
713 if (nb_sectors <= 0) {
714 return 0;
716 ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n, &file);
717 if (ret < 0) {
718 error_report("error getting block status at sector %" PRId64 ": %s",
719 sector_num, strerror(-ret));
720 return ret;
722 if (ret & BDRV_BLOCK_ZERO) {
723 sector_num += n;
724 continue;
726 ret = bdrv_pwrite_zeroes(child, sector_num << BDRV_SECTOR_BITS,
727 n << BDRV_SECTOR_BITS, flags);
728 if (ret < 0) {
729 error_report("error writing zeroes at sector %" PRId64 ": %s",
730 sector_num, strerror(-ret));
731 return ret;
733 sector_num += n;
737 int bdrv_preadv(BdrvChild *child, int64_t offset, QEMUIOVector *qiov)
739 int ret;
741 ret = bdrv_prwv_co(child, offset, qiov, false, 0);
742 if (ret < 0) {
743 return ret;
746 return qiov->size;
749 int bdrv_pread(BdrvChild *child, int64_t offset, void *buf, int bytes)
751 QEMUIOVector qiov;
752 struct iovec iov = {
753 .iov_base = (void *)buf,
754 .iov_len = bytes,
757 if (bytes < 0) {
758 return -EINVAL;
761 qemu_iovec_init_external(&qiov, &iov, 1);
762 return bdrv_preadv(child, offset, &qiov);
765 int bdrv_pwritev(BdrvChild *child, int64_t offset, QEMUIOVector *qiov)
767 int ret;
769 ret = bdrv_prwv_co(child, offset, qiov, true, 0);
770 if (ret < 0) {
771 return ret;
774 return qiov->size;
777 int bdrv_pwrite(BdrvChild *child, int64_t offset, const void *buf, int bytes)
779 QEMUIOVector qiov;
780 struct iovec iov = {
781 .iov_base = (void *) buf,
782 .iov_len = bytes,
785 if (bytes < 0) {
786 return -EINVAL;
789 qemu_iovec_init_external(&qiov, &iov, 1);
790 return bdrv_pwritev(child, offset, &qiov);
794 * Writes to the file and ensures that no writes are reordered across this
795 * request (acts as a barrier)
797 * Returns 0 on success, -errno in error cases.
799 int bdrv_pwrite_sync(BdrvChild *child, int64_t offset,
800 const void *buf, int count)
802 int ret;
804 ret = bdrv_pwrite(child, offset, buf, count);
805 if (ret < 0) {
806 return ret;
809 ret = bdrv_flush(child->bs);
810 if (ret < 0) {
811 return ret;
814 return 0;
817 typedef struct CoroutineIOCompletion {
818 Coroutine *coroutine;
819 int ret;
820 } CoroutineIOCompletion;
822 static void bdrv_co_io_em_complete(void *opaque, int ret)
824 CoroutineIOCompletion *co = opaque;
826 co->ret = ret;
827 aio_co_wake(co->coroutine);
830 static int coroutine_fn bdrv_driver_preadv(BlockDriverState *bs,
831 uint64_t offset, uint64_t bytes,
832 QEMUIOVector *qiov, int flags)
834 BlockDriver *drv = bs->drv;
835 int64_t sector_num;
836 unsigned int nb_sectors;
838 assert(!(flags & ~BDRV_REQ_MASK));
840 if (drv->bdrv_co_preadv) {
841 return drv->bdrv_co_preadv(bs, offset, bytes, qiov, flags);
844 sector_num = offset >> BDRV_SECTOR_BITS;
845 nb_sectors = bytes >> BDRV_SECTOR_BITS;
847 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
848 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
849 assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);
851 if (drv->bdrv_co_readv) {
852 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
853 } else {
854 BlockAIOCB *acb;
855 CoroutineIOCompletion co = {
856 .coroutine = qemu_coroutine_self(),
859 acb = bs->drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
860 bdrv_co_io_em_complete, &co);
861 if (acb == NULL) {
862 return -EIO;
863 } else {
864 qemu_coroutine_yield();
865 return co.ret;
870 static int coroutine_fn bdrv_driver_pwritev(BlockDriverState *bs,
871 uint64_t offset, uint64_t bytes,
872 QEMUIOVector *qiov, int flags)
874 BlockDriver *drv = bs->drv;
875 int64_t sector_num;
876 unsigned int nb_sectors;
877 int ret;
879 assert(!(flags & ~BDRV_REQ_MASK));
881 if (drv->bdrv_co_pwritev) {
882 ret = drv->bdrv_co_pwritev(bs, offset, bytes, qiov,
883 flags & bs->supported_write_flags);
884 flags &= ~bs->supported_write_flags;
885 goto emulate_flags;
888 sector_num = offset >> BDRV_SECTOR_BITS;
889 nb_sectors = bytes >> BDRV_SECTOR_BITS;
891 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
892 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
893 assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);
895 if (drv->bdrv_co_writev_flags) {
896 ret = drv->bdrv_co_writev_flags(bs, sector_num, nb_sectors, qiov,
897 flags & bs->supported_write_flags);
898 flags &= ~bs->supported_write_flags;
899 } else if (drv->bdrv_co_writev) {
900 assert(!bs->supported_write_flags);
901 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
902 } else {
903 BlockAIOCB *acb;
904 CoroutineIOCompletion co = {
905 .coroutine = qemu_coroutine_self(),
908 acb = bs->drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
909 bdrv_co_io_em_complete, &co);
910 if (acb == NULL) {
911 ret = -EIO;
912 } else {
913 qemu_coroutine_yield();
914 ret = co.ret;
918 emulate_flags:
919 if (ret == 0 && (flags & BDRV_REQ_FUA)) {
920 ret = bdrv_co_flush(bs);
923 return ret;
926 static int coroutine_fn
927 bdrv_driver_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
928 uint64_t bytes, QEMUIOVector *qiov)
930 BlockDriver *drv = bs->drv;
932 if (!drv->bdrv_co_pwritev_compressed) {
933 return -ENOTSUP;
936 return drv->bdrv_co_pwritev_compressed(bs, offset, bytes, qiov);
939 static int coroutine_fn bdrv_co_do_copy_on_readv(BdrvChild *child,
940 int64_t offset, unsigned int bytes, QEMUIOVector *qiov)
942 BlockDriverState *bs = child->bs;
944 /* Perform I/O through a temporary buffer so that users who scribble over
945 * their read buffer while the operation is in progress do not end up
946 * modifying the image file. This is critical for zero-copy guest I/O
947 * where anything might happen inside guest memory.
949 void *bounce_buffer;
951 BlockDriver *drv = bs->drv;
952 struct iovec iov;
953 QEMUIOVector bounce_qiov;
954 int64_t cluster_offset;
955 unsigned int cluster_bytes;
956 size_t skip_bytes;
957 int ret;
959 /* FIXME We cannot require callers to have write permissions when all they
960 * are doing is a read request. If we did things right, write permissions
961 * would be obtained anyway, but internally by the copy-on-read code. As
962 * long as it is implemented here rather than in a separat filter driver,
963 * the copy-on-read code doesn't have its own BdrvChild, however, for which
964 * it could request permissions. Therefore we have to bypass the permission
965 * system for the moment. */
966 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
968 /* Cover entire cluster so no additional backing file I/O is required when
969 * allocating cluster in the image file.
971 bdrv_round_to_clusters(bs, offset, bytes, &cluster_offset, &cluster_bytes);
973 trace_bdrv_co_do_copy_on_readv(bs, offset, bytes,
974 cluster_offset, cluster_bytes);
976 iov.iov_len = cluster_bytes;
977 iov.iov_base = bounce_buffer = qemu_try_blockalign(bs, iov.iov_len);
978 if (bounce_buffer == NULL) {
979 ret = -ENOMEM;
980 goto err;
983 qemu_iovec_init_external(&bounce_qiov, &iov, 1);
985 ret = bdrv_driver_preadv(bs, cluster_offset, cluster_bytes,
986 &bounce_qiov, 0);
987 if (ret < 0) {
988 goto err;
991 if (drv->bdrv_co_pwrite_zeroes &&
992 buffer_is_zero(bounce_buffer, iov.iov_len)) {
993 /* FIXME: Should we (perhaps conditionally) be setting
994 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
995 * that still correctly reads as zero? */
996 ret = bdrv_co_do_pwrite_zeroes(bs, cluster_offset, cluster_bytes, 0);
997 } else {
998 /* This does not change the data on the disk, it is not necessary
999 * to flush even in cache=writethrough mode.
1001 ret = bdrv_driver_pwritev(bs, cluster_offset, cluster_bytes,
1002 &bounce_qiov, 0);
1005 if (ret < 0) {
1006 /* It might be okay to ignore write errors for guest requests. If this
1007 * is a deliberate copy-on-read then we don't want to ignore the error.
1008 * Simply report it in all cases.
1010 goto err;
1013 skip_bytes = offset - cluster_offset;
1014 qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes, bytes);
1016 err:
1017 qemu_vfree(bounce_buffer);
1018 return ret;
1022 * Forwards an already correctly aligned request to the BlockDriver. This
1023 * handles copy on read, zeroing after EOF, and fragmentation of large
1024 * reads; any other features must be implemented by the caller.
1026 static int coroutine_fn bdrv_aligned_preadv(BdrvChild *child,
1027 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
1028 int64_t align, QEMUIOVector *qiov, int flags)
1030 BlockDriverState *bs = child->bs;
1031 int64_t total_bytes, max_bytes;
1032 int ret = 0;
1033 uint64_t bytes_remaining = bytes;
1034 int max_transfer;
1036 assert(is_power_of_2(align));
1037 assert((offset & (align - 1)) == 0);
1038 assert((bytes & (align - 1)) == 0);
1039 assert(!qiov || bytes == qiov->size);
1040 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1041 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1042 align);
1044 /* TODO: We would need a per-BDS .supported_read_flags and
1045 * potential fallback support, if we ever implement any read flags
1046 * to pass through to drivers. For now, there aren't any
1047 * passthrough flags. */
1048 assert(!(flags & ~(BDRV_REQ_NO_SERIALISING | BDRV_REQ_COPY_ON_READ)));
1050 /* Handle Copy on Read and associated serialisation */
1051 if (flags & BDRV_REQ_COPY_ON_READ) {
1052 /* If we touch the same cluster it counts as an overlap. This
1053 * guarantees that allocating writes will be serialized and not race
1054 * with each other for the same cluster. For example, in copy-on-read
1055 * it ensures that the CoR read and write operations are atomic and
1056 * guest writes cannot interleave between them. */
1057 mark_request_serialising(req, bdrv_get_cluster_size(bs));
1060 if (!(flags & BDRV_REQ_NO_SERIALISING)) {
1061 wait_serialising_requests(req);
1064 if (flags & BDRV_REQ_COPY_ON_READ) {
1065 int64_t start_sector = offset >> BDRV_SECTOR_BITS;
1066 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
1067 unsigned int nb_sectors = end_sector - start_sector;
1068 int pnum;
1070 ret = bdrv_is_allocated(bs, start_sector, nb_sectors, &pnum);
1071 if (ret < 0) {
1072 goto out;
1075 if (!ret || pnum != nb_sectors) {
1076 ret = bdrv_co_do_copy_on_readv(child, offset, bytes, qiov);
1077 goto out;
1081 /* Forward the request to the BlockDriver, possibly fragmenting it */
1082 total_bytes = bdrv_getlength(bs);
1083 if (total_bytes < 0) {
1084 ret = total_bytes;
1085 goto out;
1088 max_bytes = ROUND_UP(MAX(0, total_bytes - offset), align);
1089 if (bytes <= max_bytes && bytes <= max_transfer) {
1090 ret = bdrv_driver_preadv(bs, offset, bytes, qiov, 0);
1091 goto out;
1094 while (bytes_remaining) {
1095 int num;
1097 if (max_bytes) {
1098 QEMUIOVector local_qiov;
1100 num = MIN(bytes_remaining, MIN(max_bytes, max_transfer));
1101 assert(num);
1102 qemu_iovec_init(&local_qiov, qiov->niov);
1103 qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num);
1105 ret = bdrv_driver_preadv(bs, offset + bytes - bytes_remaining,
1106 num, &local_qiov, 0);
1107 max_bytes -= num;
1108 qemu_iovec_destroy(&local_qiov);
1109 } else {
1110 num = bytes_remaining;
1111 ret = qemu_iovec_memset(qiov, bytes - bytes_remaining, 0,
1112 bytes_remaining);
1114 if (ret < 0) {
1115 goto out;
1117 bytes_remaining -= num;
1120 out:
1121 return ret < 0 ? ret : 0;
1125 * Handle a read request in coroutine context
1127 int coroutine_fn bdrv_co_preadv(BdrvChild *child,
1128 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1129 BdrvRequestFlags flags)
1131 BlockDriverState *bs = child->bs;
1132 BlockDriver *drv = bs->drv;
1133 BdrvTrackedRequest req;
1135 uint64_t align = bs->bl.request_alignment;
1136 uint8_t *head_buf = NULL;
1137 uint8_t *tail_buf = NULL;
1138 QEMUIOVector local_qiov;
1139 bool use_local_qiov = false;
1140 int ret;
1142 if (!drv) {
1143 return -ENOMEDIUM;
1146 ret = bdrv_check_byte_request(bs, offset, bytes);
1147 if (ret < 0) {
1148 return ret;
1151 bdrv_inc_in_flight(bs);
1153 /* Don't do copy-on-read if we read data before write operation */
1154 if (atomic_read(&bs->copy_on_read) && !(flags & BDRV_REQ_NO_SERIALISING)) {
1155 flags |= BDRV_REQ_COPY_ON_READ;
1158 /* Align read if necessary by padding qiov */
1159 if (offset & (align - 1)) {
1160 head_buf = qemu_blockalign(bs, align);
1161 qemu_iovec_init(&local_qiov, qiov->niov + 2);
1162 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
1163 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1164 use_local_qiov = true;
1166 bytes += offset & (align - 1);
1167 offset = offset & ~(align - 1);
1170 if ((offset + bytes) & (align - 1)) {
1171 if (!use_local_qiov) {
1172 qemu_iovec_init(&local_qiov, qiov->niov + 1);
1173 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1174 use_local_qiov = true;
1176 tail_buf = qemu_blockalign(bs, align);
1177 qemu_iovec_add(&local_qiov, tail_buf,
1178 align - ((offset + bytes) & (align - 1)));
1180 bytes = ROUND_UP(bytes, align);
1183 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_READ);
1184 ret = bdrv_aligned_preadv(child, &req, offset, bytes, align,
1185 use_local_qiov ? &local_qiov : qiov,
1186 flags);
1187 tracked_request_end(&req);
1188 bdrv_dec_in_flight(bs);
1190 if (use_local_qiov) {
1191 qemu_iovec_destroy(&local_qiov);
1192 qemu_vfree(head_buf);
1193 qemu_vfree(tail_buf);
1196 return ret;
1199 static int coroutine_fn bdrv_co_do_readv(BdrvChild *child,
1200 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
1201 BdrvRequestFlags flags)
1203 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
1204 return -EINVAL;
1207 return bdrv_co_preadv(child, sector_num << BDRV_SECTOR_BITS,
1208 nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
1211 int coroutine_fn bdrv_co_readv(BdrvChild *child, int64_t sector_num,
1212 int nb_sectors, QEMUIOVector *qiov)
1214 trace_bdrv_co_readv(child->bs, sector_num, nb_sectors);
1216 return bdrv_co_do_readv(child, sector_num, nb_sectors, qiov, 0);
1219 /* Maximum buffer for write zeroes fallback, in bytes */
1220 #define MAX_WRITE_ZEROES_BOUNCE_BUFFER (32768 << BDRV_SECTOR_BITS)
1222 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
1223 int64_t offset, int count, BdrvRequestFlags flags)
1225 BlockDriver *drv = bs->drv;
1226 QEMUIOVector qiov;
1227 struct iovec iov = {0};
1228 int ret = 0;
1229 bool need_flush = false;
1230 int head = 0;
1231 int tail = 0;
1233 int max_write_zeroes = MIN_NON_ZERO(bs->bl.max_pwrite_zeroes, INT_MAX);
1234 int alignment = MAX(bs->bl.pwrite_zeroes_alignment,
1235 bs->bl.request_alignment);
1236 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer,
1237 MAX_WRITE_ZEROES_BOUNCE_BUFFER);
1239 assert(alignment % bs->bl.request_alignment == 0);
1240 head = offset % alignment;
1241 tail = (offset + count) % alignment;
1242 max_write_zeroes = QEMU_ALIGN_DOWN(max_write_zeroes, alignment);
1243 assert(max_write_zeroes >= bs->bl.request_alignment);
1245 while (count > 0 && !ret) {
1246 int num = count;
1248 /* Align request. Block drivers can expect the "bulk" of the request
1249 * to be aligned, and that unaligned requests do not cross cluster
1250 * boundaries.
1252 if (head) {
1253 /* Make a small request up to the first aligned sector. For
1254 * convenience, limit this request to max_transfer even if
1255 * we don't need to fall back to writes. */
1256 num = MIN(MIN(count, max_transfer), alignment - head);
1257 head = (head + num) % alignment;
1258 assert(num < max_write_zeroes);
1259 } else if (tail && num > alignment) {
1260 /* Shorten the request to the last aligned sector. */
1261 num -= tail;
1264 /* limit request size */
1265 if (num > max_write_zeroes) {
1266 num = max_write_zeroes;
1269 ret = -ENOTSUP;
1270 /* First try the efficient write zeroes operation */
1271 if (drv->bdrv_co_pwrite_zeroes) {
1272 ret = drv->bdrv_co_pwrite_zeroes(bs, offset, num,
1273 flags & bs->supported_zero_flags);
1274 if (ret != -ENOTSUP && (flags & BDRV_REQ_FUA) &&
1275 !(bs->supported_zero_flags & BDRV_REQ_FUA)) {
1276 need_flush = true;
1278 } else {
1279 assert(!bs->supported_zero_flags);
1282 if (ret == -ENOTSUP) {
1283 /* Fall back to bounce buffer if write zeroes is unsupported */
1284 BdrvRequestFlags write_flags = flags & ~BDRV_REQ_ZERO_WRITE;
1286 if ((flags & BDRV_REQ_FUA) &&
1287 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1288 /* No need for bdrv_driver_pwrite() to do a fallback
1289 * flush on each chunk; use just one at the end */
1290 write_flags &= ~BDRV_REQ_FUA;
1291 need_flush = true;
1293 num = MIN(num, max_transfer);
1294 iov.iov_len = num;
1295 if (iov.iov_base == NULL) {
1296 iov.iov_base = qemu_try_blockalign(bs, num);
1297 if (iov.iov_base == NULL) {
1298 ret = -ENOMEM;
1299 goto fail;
1301 memset(iov.iov_base, 0, num);
1303 qemu_iovec_init_external(&qiov, &iov, 1);
1305 ret = bdrv_driver_pwritev(bs, offset, num, &qiov, write_flags);
1307 /* Keep bounce buffer around if it is big enough for all
1308 * all future requests.
1310 if (num < max_transfer) {
1311 qemu_vfree(iov.iov_base);
1312 iov.iov_base = NULL;
1316 offset += num;
1317 count -= num;
1320 fail:
1321 if (ret == 0 && need_flush) {
1322 ret = bdrv_co_flush(bs);
1324 qemu_vfree(iov.iov_base);
1325 return ret;
1329 * Forwards an already correctly aligned write request to the BlockDriver,
1330 * after possibly fragmenting it.
1332 static int coroutine_fn bdrv_aligned_pwritev(BdrvChild *child,
1333 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
1334 int64_t align, QEMUIOVector *qiov, int flags)
1336 BlockDriverState *bs = child->bs;
1337 BlockDriver *drv = bs->drv;
1338 bool waited;
1339 int ret;
1341 int64_t start_sector = offset >> BDRV_SECTOR_BITS;
1342 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
1343 uint64_t bytes_remaining = bytes;
1344 int max_transfer;
1346 assert(is_power_of_2(align));
1347 assert((offset & (align - 1)) == 0);
1348 assert((bytes & (align - 1)) == 0);
1349 assert(!qiov || bytes == qiov->size);
1350 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1351 assert(!(flags & ~BDRV_REQ_MASK));
1352 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1353 align);
1355 waited = wait_serialising_requests(req);
1356 assert(!waited || !req->serialising);
1357 assert(req->overlap_offset <= offset);
1358 assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
1359 assert(child->perm & BLK_PERM_WRITE);
1360 assert(end_sector <= bs->total_sectors || child->perm & BLK_PERM_RESIZE);
1362 ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
1364 if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
1365 !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_pwrite_zeroes &&
1366 qemu_iovec_is_zero(qiov)) {
1367 flags |= BDRV_REQ_ZERO_WRITE;
1368 if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
1369 flags |= BDRV_REQ_MAY_UNMAP;
1373 if (ret < 0) {
1374 /* Do nothing, write notifier decided to fail this request */
1375 } else if (flags & BDRV_REQ_ZERO_WRITE) {
1376 bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO);
1377 ret = bdrv_co_do_pwrite_zeroes(bs, offset, bytes, flags);
1378 } else if (flags & BDRV_REQ_WRITE_COMPRESSED) {
1379 ret = bdrv_driver_pwritev_compressed(bs, offset, bytes, qiov);
1380 } else if (bytes <= max_transfer) {
1381 bdrv_debug_event(bs, BLKDBG_PWRITEV);
1382 ret = bdrv_driver_pwritev(bs, offset, bytes, qiov, flags);
1383 } else {
1384 bdrv_debug_event(bs, BLKDBG_PWRITEV);
1385 while (bytes_remaining) {
1386 int num = MIN(bytes_remaining, max_transfer);
1387 QEMUIOVector local_qiov;
1388 int local_flags = flags;
1390 assert(num);
1391 if (num < bytes_remaining && (flags & BDRV_REQ_FUA) &&
1392 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1393 /* If FUA is going to be emulated by flush, we only
1394 * need to flush on the last iteration */
1395 local_flags &= ~BDRV_REQ_FUA;
1397 qemu_iovec_init(&local_qiov, qiov->niov);
1398 qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num);
1400 ret = bdrv_driver_pwritev(bs, offset + bytes - bytes_remaining,
1401 num, &local_qiov, local_flags);
1402 qemu_iovec_destroy(&local_qiov);
1403 if (ret < 0) {
1404 break;
1406 bytes_remaining -= num;
1409 bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE);
1411 atomic_inc(&bs->write_gen);
1412 bdrv_set_dirty(bs, start_sector, end_sector - start_sector);
1414 stat64_max(&bs->wr_highest_offset, offset + bytes);
1416 if (ret >= 0) {
1417 bs->total_sectors = MAX(bs->total_sectors, end_sector);
1418 ret = 0;
1421 return ret;
1424 static int coroutine_fn bdrv_co_do_zero_pwritev(BdrvChild *child,
1425 int64_t offset,
1426 unsigned int bytes,
1427 BdrvRequestFlags flags,
1428 BdrvTrackedRequest *req)
1430 BlockDriverState *bs = child->bs;
1431 uint8_t *buf = NULL;
1432 QEMUIOVector local_qiov;
1433 struct iovec iov;
1434 uint64_t align = bs->bl.request_alignment;
1435 unsigned int head_padding_bytes, tail_padding_bytes;
1436 int ret = 0;
1438 head_padding_bytes = offset & (align - 1);
1439 tail_padding_bytes = (align - (offset + bytes)) & (align - 1);
1442 assert(flags & BDRV_REQ_ZERO_WRITE);
1443 if (head_padding_bytes || tail_padding_bytes) {
1444 buf = qemu_blockalign(bs, align);
1445 iov = (struct iovec) {
1446 .iov_base = buf,
1447 .iov_len = align,
1449 qemu_iovec_init_external(&local_qiov, &iov, 1);
1451 if (head_padding_bytes) {
1452 uint64_t zero_bytes = MIN(bytes, align - head_padding_bytes);
1454 /* RMW the unaligned part before head. */
1455 mark_request_serialising(req, align);
1456 wait_serialising_requests(req);
1457 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1458 ret = bdrv_aligned_preadv(child, req, offset & ~(align - 1), align,
1459 align, &local_qiov, 0);
1460 if (ret < 0) {
1461 goto fail;
1463 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1465 memset(buf + head_padding_bytes, 0, zero_bytes);
1466 ret = bdrv_aligned_pwritev(child, req, offset & ~(align - 1), align,
1467 align, &local_qiov,
1468 flags & ~BDRV_REQ_ZERO_WRITE);
1469 if (ret < 0) {
1470 goto fail;
1472 offset += zero_bytes;
1473 bytes -= zero_bytes;
1476 assert(!bytes || (offset & (align - 1)) == 0);
1477 if (bytes >= align) {
1478 /* Write the aligned part in the middle. */
1479 uint64_t aligned_bytes = bytes & ~(align - 1);
1480 ret = bdrv_aligned_pwritev(child, req, offset, aligned_bytes, align,
1481 NULL, flags);
1482 if (ret < 0) {
1483 goto fail;
1485 bytes -= aligned_bytes;
1486 offset += aligned_bytes;
1489 assert(!bytes || (offset & (align - 1)) == 0);
1490 if (bytes) {
1491 assert(align == tail_padding_bytes + bytes);
1492 /* RMW the unaligned part after tail. */
1493 mark_request_serialising(req, align);
1494 wait_serialising_requests(req);
1495 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1496 ret = bdrv_aligned_preadv(child, req, offset, align,
1497 align, &local_qiov, 0);
1498 if (ret < 0) {
1499 goto fail;
1501 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1503 memset(buf, 0, bytes);
1504 ret = bdrv_aligned_pwritev(child, req, offset, align, align,
1505 &local_qiov, flags & ~BDRV_REQ_ZERO_WRITE);
1507 fail:
1508 qemu_vfree(buf);
1509 return ret;
1514 * Handle a write request in coroutine context
1516 int coroutine_fn bdrv_co_pwritev(BdrvChild *child,
1517 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1518 BdrvRequestFlags flags)
1520 BlockDriverState *bs = child->bs;
1521 BdrvTrackedRequest req;
1522 uint64_t align = bs->bl.request_alignment;
1523 uint8_t *head_buf = NULL;
1524 uint8_t *tail_buf = NULL;
1525 QEMUIOVector local_qiov;
1526 bool use_local_qiov = false;
1527 int ret;
1529 if (!bs->drv) {
1530 return -ENOMEDIUM;
1532 if (bs->read_only) {
1533 return -EPERM;
1535 assert(!(bs->open_flags & BDRV_O_INACTIVE));
1537 ret = bdrv_check_byte_request(bs, offset, bytes);
1538 if (ret < 0) {
1539 return ret;
1542 bdrv_inc_in_flight(bs);
1544 * Align write if necessary by performing a read-modify-write cycle.
1545 * Pad qiov with the read parts and be sure to have a tracked request not
1546 * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
1548 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);
1550 if (!qiov) {
1551 ret = bdrv_co_do_zero_pwritev(child, offset, bytes, flags, &req);
1552 goto out;
1555 if (offset & (align - 1)) {
1556 QEMUIOVector head_qiov;
1557 struct iovec head_iov;
1559 mark_request_serialising(&req, align);
1560 wait_serialising_requests(&req);
1562 head_buf = qemu_blockalign(bs, align);
1563 head_iov = (struct iovec) {
1564 .iov_base = head_buf,
1565 .iov_len = align,
1567 qemu_iovec_init_external(&head_qiov, &head_iov, 1);
1569 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1570 ret = bdrv_aligned_preadv(child, &req, offset & ~(align - 1), align,
1571 align, &head_qiov, 0);
1572 if (ret < 0) {
1573 goto fail;
1575 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1577 qemu_iovec_init(&local_qiov, qiov->niov + 2);
1578 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
1579 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1580 use_local_qiov = true;
1582 bytes += offset & (align - 1);
1583 offset = offset & ~(align - 1);
1585 /* We have read the tail already if the request is smaller
1586 * than one aligned block.
1588 if (bytes < align) {
1589 qemu_iovec_add(&local_qiov, head_buf + bytes, align - bytes);
1590 bytes = align;
1594 if ((offset + bytes) & (align - 1)) {
1595 QEMUIOVector tail_qiov;
1596 struct iovec tail_iov;
1597 size_t tail_bytes;
1598 bool waited;
1600 mark_request_serialising(&req, align);
1601 waited = wait_serialising_requests(&req);
1602 assert(!waited || !use_local_qiov);
1604 tail_buf = qemu_blockalign(bs, align);
1605 tail_iov = (struct iovec) {
1606 .iov_base = tail_buf,
1607 .iov_len = align,
1609 qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);
1611 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1612 ret = bdrv_aligned_preadv(child, &req, (offset + bytes) & ~(align - 1),
1613 align, align, &tail_qiov, 0);
1614 if (ret < 0) {
1615 goto fail;
1617 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1619 if (!use_local_qiov) {
1620 qemu_iovec_init(&local_qiov, qiov->niov + 1);
1621 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1622 use_local_qiov = true;
1625 tail_bytes = (offset + bytes) & (align - 1);
1626 qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
1628 bytes = ROUND_UP(bytes, align);
1631 ret = bdrv_aligned_pwritev(child, &req, offset, bytes, align,
1632 use_local_qiov ? &local_qiov : qiov,
1633 flags);
1635 fail:
1637 if (use_local_qiov) {
1638 qemu_iovec_destroy(&local_qiov);
1640 qemu_vfree(head_buf);
1641 qemu_vfree(tail_buf);
1642 out:
1643 tracked_request_end(&req);
1644 bdrv_dec_in_flight(bs);
1645 return ret;
1648 static int coroutine_fn bdrv_co_do_writev(BdrvChild *child,
1649 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
1650 BdrvRequestFlags flags)
1652 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
1653 return -EINVAL;
1656 return bdrv_co_pwritev(child, sector_num << BDRV_SECTOR_BITS,
1657 nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
1660 int coroutine_fn bdrv_co_writev(BdrvChild *child, int64_t sector_num,
1661 int nb_sectors, QEMUIOVector *qiov)
1663 trace_bdrv_co_writev(child->bs, sector_num, nb_sectors);
1665 return bdrv_co_do_writev(child, sector_num, nb_sectors, qiov, 0);
1668 int coroutine_fn bdrv_co_pwrite_zeroes(BdrvChild *child, int64_t offset,
1669 int count, BdrvRequestFlags flags)
1671 trace_bdrv_co_pwrite_zeroes(child->bs, offset, count, flags);
1673 if (!(child->bs->open_flags & BDRV_O_UNMAP)) {
1674 flags &= ~BDRV_REQ_MAY_UNMAP;
1677 return bdrv_co_pwritev(child, offset, count, NULL,
1678 BDRV_REQ_ZERO_WRITE | flags);
1682 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
1684 int bdrv_flush_all(void)
1686 BdrvNextIterator it;
1687 BlockDriverState *bs = NULL;
1688 int result = 0;
1690 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
1691 AioContext *aio_context = bdrv_get_aio_context(bs);
1692 int ret;
1694 aio_context_acquire(aio_context);
1695 ret = bdrv_flush(bs);
1696 if (ret < 0 && !result) {
1697 result = ret;
1699 aio_context_release(aio_context);
1702 return result;
1706 typedef struct BdrvCoGetBlockStatusData {
1707 BlockDriverState *bs;
1708 BlockDriverState *base;
1709 BlockDriverState **file;
1710 int64_t sector_num;
1711 int nb_sectors;
1712 int *pnum;
1713 int64_t ret;
1714 bool done;
1715 } BdrvCoGetBlockStatusData;
1718 * Returns the allocation status of the specified sectors.
1719 * Drivers not implementing the functionality are assumed to not support
1720 * backing files, hence all their sectors are reported as allocated.
1722 * If 'sector_num' is beyond the end of the disk image the return value is 0
1723 * and 'pnum' is set to 0.
1725 * 'pnum' is set to the number of sectors (including and immediately following
1726 * the specified sector) that are known to be in the same
1727 * allocated/unallocated state.
1729 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1730 * beyond the end of the disk image it will be clamped.
1732 * If returned value is positive and BDRV_BLOCK_OFFSET_VALID bit is set, 'file'
1733 * points to the BDS which the sector range is allocated in.
1735 static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
1736 int64_t sector_num,
1737 int nb_sectors, int *pnum,
1738 BlockDriverState **file)
1740 int64_t total_sectors;
1741 int64_t n;
1742 int64_t ret, ret2;
1744 total_sectors = bdrv_nb_sectors(bs);
1745 if (total_sectors < 0) {
1746 return total_sectors;
1749 if (sector_num >= total_sectors) {
1750 *pnum = 0;
1751 return 0;
1754 n = total_sectors - sector_num;
1755 if (n < nb_sectors) {
1756 nb_sectors = n;
1759 if (!bs->drv->bdrv_co_get_block_status) {
1760 *pnum = nb_sectors;
1761 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
1762 if (bs->drv->protocol_name) {
1763 ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
1765 return ret;
1768 *file = NULL;
1769 bdrv_inc_in_flight(bs);
1770 ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum,
1771 file);
1772 if (ret < 0) {
1773 *pnum = 0;
1774 goto out;
1777 if (ret & BDRV_BLOCK_RAW) {
1778 assert(ret & BDRV_BLOCK_OFFSET_VALID);
1779 ret = bdrv_co_get_block_status(*file, ret >> BDRV_SECTOR_BITS,
1780 *pnum, pnum, file);
1781 goto out;
1784 if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
1785 ret |= BDRV_BLOCK_ALLOCATED;
1786 } else {
1787 if (bdrv_unallocated_blocks_are_zero(bs)) {
1788 ret |= BDRV_BLOCK_ZERO;
1789 } else if (bs->backing) {
1790 BlockDriverState *bs2 = bs->backing->bs;
1791 int64_t nb_sectors2 = bdrv_nb_sectors(bs2);
1792 if (nb_sectors2 >= 0 && sector_num >= nb_sectors2) {
1793 ret |= BDRV_BLOCK_ZERO;
1798 if (*file && *file != bs &&
1799 (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
1800 (ret & BDRV_BLOCK_OFFSET_VALID)) {
1801 BlockDriverState *file2;
1802 int file_pnum;
1804 ret2 = bdrv_co_get_block_status(*file, ret >> BDRV_SECTOR_BITS,
1805 *pnum, &file_pnum, &file2);
1806 if (ret2 >= 0) {
1807 /* Ignore errors. This is just providing extra information, it
1808 * is useful but not necessary.
1810 if (!file_pnum) {
1811 /* !file_pnum indicates an offset at or beyond the EOF; it is
1812 * perfectly valid for the format block driver to point to such
1813 * offsets, so catch it and mark everything as zero */
1814 ret |= BDRV_BLOCK_ZERO;
1815 } else {
1816 /* Limit request to the range reported by the protocol driver */
1817 *pnum = file_pnum;
1818 ret |= (ret2 & BDRV_BLOCK_ZERO);
1823 out:
1824 bdrv_dec_in_flight(bs);
1825 return ret;
1828 static int64_t coroutine_fn bdrv_co_get_block_status_above(BlockDriverState *bs,
1829 BlockDriverState *base,
1830 int64_t sector_num,
1831 int nb_sectors,
1832 int *pnum,
1833 BlockDriverState **file)
1835 BlockDriverState *p;
1836 int64_t ret = 0;
1838 assert(bs != base);
1839 for (p = bs; p != base; p = backing_bs(p)) {
1840 ret = bdrv_co_get_block_status(p, sector_num, nb_sectors, pnum, file);
1841 if (ret < 0 || ret & BDRV_BLOCK_ALLOCATED) {
1842 break;
1844 /* [sector_num, pnum] unallocated on this layer, which could be only
1845 * the first part of [sector_num, nb_sectors]. */
1846 nb_sectors = MIN(nb_sectors, *pnum);
1848 return ret;
1851 /* Coroutine wrapper for bdrv_get_block_status_above() */
1852 static void coroutine_fn bdrv_get_block_status_above_co_entry(void *opaque)
1854 BdrvCoGetBlockStatusData *data = opaque;
1856 data->ret = bdrv_co_get_block_status_above(data->bs, data->base,
1857 data->sector_num,
1858 data->nb_sectors,
1859 data->pnum,
1860 data->file);
1861 data->done = true;
1865 * Synchronous wrapper around bdrv_co_get_block_status_above().
1867 * See bdrv_co_get_block_status_above() for details.
1869 int64_t bdrv_get_block_status_above(BlockDriverState *bs,
1870 BlockDriverState *base,
1871 int64_t sector_num,
1872 int nb_sectors, int *pnum,
1873 BlockDriverState **file)
1875 Coroutine *co;
1876 BdrvCoGetBlockStatusData data = {
1877 .bs = bs,
1878 .base = base,
1879 .file = file,
1880 .sector_num = sector_num,
1881 .nb_sectors = nb_sectors,
1882 .pnum = pnum,
1883 .done = false,
1886 if (qemu_in_coroutine()) {
1887 /* Fast-path if already in coroutine context */
1888 bdrv_get_block_status_above_co_entry(&data);
1889 } else {
1890 co = qemu_coroutine_create(bdrv_get_block_status_above_co_entry,
1891 &data);
1892 bdrv_coroutine_enter(bs, co);
1893 BDRV_POLL_WHILE(bs, !data.done);
1895 return data.ret;
1898 int64_t bdrv_get_block_status(BlockDriverState *bs,
1899 int64_t sector_num,
1900 int nb_sectors, int *pnum,
1901 BlockDriverState **file)
1903 return bdrv_get_block_status_above(bs, backing_bs(bs),
1904 sector_num, nb_sectors, pnum, file);
1907 int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
1908 int nb_sectors, int *pnum)
1910 BlockDriverState *file;
1911 int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum,
1912 &file);
1913 if (ret < 0) {
1914 return ret;
1916 return !!(ret & BDRV_BLOCK_ALLOCATED);
1920 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
1922 * Return true if the given sector is allocated in any image between
1923 * BASE and TOP (inclusive). BASE can be NULL to check if the given
1924 * sector is allocated in any image of the chain. Return false otherwise.
1926 * 'pnum' is set to the number of sectors (including and immediately following
1927 * the specified sector) that are known to be in the same
1928 * allocated/unallocated state.
1931 int bdrv_is_allocated_above(BlockDriverState *top,
1932 BlockDriverState *base,
1933 int64_t sector_num,
1934 int nb_sectors, int *pnum)
1936 BlockDriverState *intermediate;
1937 int ret, n = nb_sectors;
1939 intermediate = top;
1940 while (intermediate && intermediate != base) {
1941 int pnum_inter;
1942 ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
1943 &pnum_inter);
1944 if (ret < 0) {
1945 return ret;
1946 } else if (ret) {
1947 *pnum = pnum_inter;
1948 return 1;
1952 * [sector_num, nb_sectors] is unallocated on top but intermediate
1953 * might have
1955 * [sector_num+x, nr_sectors] allocated.
1957 if (n > pnum_inter &&
1958 (intermediate == top ||
1959 sector_num + pnum_inter < intermediate->total_sectors)) {
1960 n = pnum_inter;
1963 intermediate = backing_bs(intermediate);
1966 *pnum = n;
1967 return 0;
1970 typedef struct BdrvVmstateCo {
1971 BlockDriverState *bs;
1972 QEMUIOVector *qiov;
1973 int64_t pos;
1974 bool is_read;
1975 int ret;
1976 } BdrvVmstateCo;
1978 static int coroutine_fn
1979 bdrv_co_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos,
1980 bool is_read)
1982 BlockDriver *drv = bs->drv;
1984 if (!drv) {
1985 return -ENOMEDIUM;
1986 } else if (drv->bdrv_load_vmstate) {
1987 return is_read ? drv->bdrv_load_vmstate(bs, qiov, pos)
1988 : drv->bdrv_save_vmstate(bs, qiov, pos);
1989 } else if (bs->file) {
1990 return bdrv_co_rw_vmstate(bs->file->bs, qiov, pos, is_read);
1993 return -ENOTSUP;
1996 static void coroutine_fn bdrv_co_rw_vmstate_entry(void *opaque)
1998 BdrvVmstateCo *co = opaque;
1999 co->ret = bdrv_co_rw_vmstate(co->bs, co->qiov, co->pos, co->is_read);
2002 static inline int
2003 bdrv_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos,
2004 bool is_read)
2006 if (qemu_in_coroutine()) {
2007 return bdrv_co_rw_vmstate(bs, qiov, pos, is_read);
2008 } else {
2009 BdrvVmstateCo data = {
2010 .bs = bs,
2011 .qiov = qiov,
2012 .pos = pos,
2013 .is_read = is_read,
2014 .ret = -EINPROGRESS,
2016 Coroutine *co = qemu_coroutine_create(bdrv_co_rw_vmstate_entry, &data);
2018 bdrv_coroutine_enter(bs, co);
2019 while (data.ret == -EINPROGRESS) {
2020 aio_poll(bdrv_get_aio_context(bs), true);
2022 return data.ret;
2026 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2027 int64_t pos, int size)
2029 QEMUIOVector qiov;
2030 struct iovec iov = {
2031 .iov_base = (void *) buf,
2032 .iov_len = size,
2034 int ret;
2036 qemu_iovec_init_external(&qiov, &iov, 1);
2038 ret = bdrv_writev_vmstate(bs, &qiov, pos);
2039 if (ret < 0) {
2040 return ret;
2043 return size;
2046 int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2048 return bdrv_rw_vmstate(bs, qiov, pos, false);
2051 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2052 int64_t pos, int size)
2054 QEMUIOVector qiov;
2055 struct iovec iov = {
2056 .iov_base = buf,
2057 .iov_len = size,
2059 int ret;
2061 qemu_iovec_init_external(&qiov, &iov, 1);
2062 ret = bdrv_readv_vmstate(bs, &qiov, pos);
2063 if (ret < 0) {
2064 return ret;
2067 return size;
2070 int bdrv_readv_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2072 return bdrv_rw_vmstate(bs, qiov, pos, true);
2075 /**************************************************************/
2076 /* async I/Os */
2078 BlockAIOCB *bdrv_aio_readv(BdrvChild *child, int64_t sector_num,
2079 QEMUIOVector *qiov, int nb_sectors,
2080 BlockCompletionFunc *cb, void *opaque)
2082 trace_bdrv_aio_readv(child->bs, sector_num, nb_sectors, opaque);
2084 assert(nb_sectors << BDRV_SECTOR_BITS == qiov->size);
2085 return bdrv_co_aio_prw_vector(child, sector_num << BDRV_SECTOR_BITS, qiov,
2086 0, cb, opaque, false);
2089 BlockAIOCB *bdrv_aio_writev(BdrvChild *child, int64_t sector_num,
2090 QEMUIOVector *qiov, int nb_sectors,
2091 BlockCompletionFunc *cb, void *opaque)
2093 trace_bdrv_aio_writev(child->bs, sector_num, nb_sectors, opaque);
2095 assert(nb_sectors << BDRV_SECTOR_BITS == qiov->size);
2096 return bdrv_co_aio_prw_vector(child, sector_num << BDRV_SECTOR_BITS, qiov,
2097 0, cb, opaque, true);
2100 void bdrv_aio_cancel(BlockAIOCB *acb)
2102 qemu_aio_ref(acb);
2103 bdrv_aio_cancel_async(acb);
2104 while (acb->refcnt > 1) {
2105 if (acb->aiocb_info->get_aio_context) {
2106 aio_poll(acb->aiocb_info->get_aio_context(acb), true);
2107 } else if (acb->bs) {
2108 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2109 * assert that we're not using an I/O thread. Thread-safe
2110 * code should use bdrv_aio_cancel_async exclusively.
2112 assert(bdrv_get_aio_context(acb->bs) == qemu_get_aio_context());
2113 aio_poll(bdrv_get_aio_context(acb->bs), true);
2114 } else {
2115 abort();
2118 qemu_aio_unref(acb);
2121 /* Async version of aio cancel. The caller is not blocked if the acb implements
2122 * cancel_async, otherwise we do nothing and let the request normally complete.
2123 * In either case the completion callback must be called. */
2124 void bdrv_aio_cancel_async(BlockAIOCB *acb)
2126 if (acb->aiocb_info->cancel_async) {
2127 acb->aiocb_info->cancel_async(acb);
2131 /**************************************************************/
2132 /* async block device emulation */
2134 typedef struct BlockRequest {
2135 union {
2136 /* Used during read, write, trim */
2137 struct {
2138 int64_t offset;
2139 int bytes;
2140 int flags;
2141 QEMUIOVector *qiov;
2143 /* Used during ioctl */
2144 struct {
2145 int req;
2146 void *buf;
2149 BlockCompletionFunc *cb;
2150 void *opaque;
2152 int error;
2153 } BlockRequest;
2155 typedef struct BlockAIOCBCoroutine {
2156 BlockAIOCB common;
2157 BdrvChild *child;
2158 BlockRequest req;
2159 bool is_write;
2160 bool need_bh;
2161 bool *done;
2162 } BlockAIOCBCoroutine;
2164 static const AIOCBInfo bdrv_em_co_aiocb_info = {
2165 .aiocb_size = sizeof(BlockAIOCBCoroutine),
2168 static void bdrv_co_complete(BlockAIOCBCoroutine *acb)
2170 if (!acb->need_bh) {
2171 bdrv_dec_in_flight(acb->common.bs);
2172 acb->common.cb(acb->common.opaque, acb->req.error);
2173 qemu_aio_unref(acb);
2177 static void bdrv_co_em_bh(void *opaque)
2179 BlockAIOCBCoroutine *acb = opaque;
2181 assert(!acb->need_bh);
2182 bdrv_co_complete(acb);
2185 static void bdrv_co_maybe_schedule_bh(BlockAIOCBCoroutine *acb)
2187 acb->need_bh = false;
2188 if (acb->req.error != -EINPROGRESS) {
2189 BlockDriverState *bs = acb->common.bs;
2191 aio_bh_schedule_oneshot(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb);
2195 /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
2196 static void coroutine_fn bdrv_co_do_rw(void *opaque)
2198 BlockAIOCBCoroutine *acb = opaque;
2200 if (!acb->is_write) {
2201 acb->req.error = bdrv_co_preadv(acb->child, acb->req.offset,
2202 acb->req.qiov->size, acb->req.qiov, acb->req.flags);
2203 } else {
2204 acb->req.error = bdrv_co_pwritev(acb->child, acb->req.offset,
2205 acb->req.qiov->size, acb->req.qiov, acb->req.flags);
2208 bdrv_co_complete(acb);
2211 static BlockAIOCB *bdrv_co_aio_prw_vector(BdrvChild *child,
2212 int64_t offset,
2213 QEMUIOVector *qiov,
2214 BdrvRequestFlags flags,
2215 BlockCompletionFunc *cb,
2216 void *opaque,
2217 bool is_write)
2219 Coroutine *co;
2220 BlockAIOCBCoroutine *acb;
2222 /* Matched by bdrv_co_complete's bdrv_dec_in_flight. */
2223 bdrv_inc_in_flight(child->bs);
2225 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, child->bs, cb, opaque);
2226 acb->child = child;
2227 acb->need_bh = true;
2228 acb->req.error = -EINPROGRESS;
2229 acb->req.offset = offset;
2230 acb->req.qiov = qiov;
2231 acb->req.flags = flags;
2232 acb->is_write = is_write;
2234 co = qemu_coroutine_create(bdrv_co_do_rw, acb);
2235 bdrv_coroutine_enter(child->bs, co);
2237 bdrv_co_maybe_schedule_bh(acb);
2238 return &acb->common;
2241 static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
2243 BlockAIOCBCoroutine *acb = opaque;
2244 BlockDriverState *bs = acb->common.bs;
2246 acb->req.error = bdrv_co_flush(bs);
2247 bdrv_co_complete(acb);
2250 BlockAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2251 BlockCompletionFunc *cb, void *opaque)
2253 trace_bdrv_aio_flush(bs, opaque);
2255 Coroutine *co;
2256 BlockAIOCBCoroutine *acb;
2258 /* Matched by bdrv_co_complete's bdrv_dec_in_flight. */
2259 bdrv_inc_in_flight(bs);
2261 acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
2262 acb->need_bh = true;
2263 acb->req.error = -EINPROGRESS;
2265 co = qemu_coroutine_create(bdrv_aio_flush_co_entry, acb);
2266 bdrv_coroutine_enter(bs, co);
2268 bdrv_co_maybe_schedule_bh(acb);
2269 return &acb->common;
2272 /**************************************************************/
2273 /* Coroutine block device emulation */
2275 typedef struct FlushCo {
2276 BlockDriverState *bs;
2277 int ret;
2278 } FlushCo;
2281 static void coroutine_fn bdrv_flush_co_entry(void *opaque)
2283 FlushCo *rwco = opaque;
2285 rwco->ret = bdrv_co_flush(rwco->bs);
2288 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
2290 int current_gen;
2291 int ret = 0;
2293 bdrv_inc_in_flight(bs);
2295 if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||
2296 bdrv_is_sg(bs)) {
2297 goto early_exit;
2300 qemu_co_mutex_lock(&bs->reqs_lock);
2301 current_gen = atomic_read(&bs->write_gen);
2303 /* Wait until any previous flushes are completed */
2304 while (bs->active_flush_req) {
2305 qemu_co_queue_wait(&bs->flush_queue, &bs->reqs_lock);
2308 /* Flushes reach this point in nondecreasing current_gen order. */
2309 bs->active_flush_req = true;
2310 qemu_co_mutex_unlock(&bs->reqs_lock);
2312 /* Write back all layers by calling one driver function */
2313 if (bs->drv->bdrv_co_flush) {
2314 ret = bs->drv->bdrv_co_flush(bs);
2315 goto out;
2318 /* Write back cached data to the OS even with cache=unsafe */
2319 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
2320 if (bs->drv->bdrv_co_flush_to_os) {
2321 ret = bs->drv->bdrv_co_flush_to_os(bs);
2322 if (ret < 0) {
2323 goto out;
2327 /* But don't actually force it to the disk with cache=unsafe */
2328 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2329 goto flush_parent;
2332 /* Check if we really need to flush anything */
2333 if (bs->flushed_gen == current_gen) {
2334 goto flush_parent;
2337 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
2338 if (bs->drv->bdrv_co_flush_to_disk) {
2339 ret = bs->drv->bdrv_co_flush_to_disk(bs);
2340 } else if (bs->drv->bdrv_aio_flush) {
2341 BlockAIOCB *acb;
2342 CoroutineIOCompletion co = {
2343 .coroutine = qemu_coroutine_self(),
2346 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
2347 if (acb == NULL) {
2348 ret = -EIO;
2349 } else {
2350 qemu_coroutine_yield();
2351 ret = co.ret;
2353 } else {
2355 * Some block drivers always operate in either writethrough or unsafe
2356 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2357 * know how the server works (because the behaviour is hardcoded or
2358 * depends on server-side configuration), so we can't ensure that
2359 * everything is safe on disk. Returning an error doesn't work because
2360 * that would break guests even if the server operates in writethrough
2361 * mode.
2363 * Let's hope the user knows what he's doing.
2365 ret = 0;
2368 if (ret < 0) {
2369 goto out;
2372 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2373 * in the case of cache=unsafe, so there are no useless flushes.
2375 flush_parent:
2376 ret = bs->file ? bdrv_co_flush(bs->file->bs) : 0;
2377 out:
2378 /* Notify any pending flushes that we have completed */
2379 if (ret == 0) {
2380 bs->flushed_gen = current_gen;
2383 qemu_co_mutex_lock(&bs->reqs_lock);
2384 bs->active_flush_req = false;
2385 /* Return value is ignored - it's ok if wait queue is empty */
2386 qemu_co_queue_next(&bs->flush_queue);
2387 qemu_co_mutex_unlock(&bs->reqs_lock);
2389 early_exit:
2390 bdrv_dec_in_flight(bs);
2391 return ret;
2394 int bdrv_flush(BlockDriverState *bs)
2396 Coroutine *co;
2397 FlushCo flush_co = {
2398 .bs = bs,
2399 .ret = NOT_DONE,
2402 if (qemu_in_coroutine()) {
2403 /* Fast-path if already in coroutine context */
2404 bdrv_flush_co_entry(&flush_co);
2405 } else {
2406 co = qemu_coroutine_create(bdrv_flush_co_entry, &flush_co);
2407 bdrv_coroutine_enter(bs, co);
2408 BDRV_POLL_WHILE(bs, flush_co.ret == NOT_DONE);
2411 return flush_co.ret;
2414 typedef struct DiscardCo {
2415 BlockDriverState *bs;
2416 int64_t offset;
2417 int count;
2418 int ret;
2419 } DiscardCo;
2420 static void coroutine_fn bdrv_pdiscard_co_entry(void *opaque)
2422 DiscardCo *rwco = opaque;
2424 rwco->ret = bdrv_co_pdiscard(rwco->bs, rwco->offset, rwco->count);
2427 int coroutine_fn bdrv_co_pdiscard(BlockDriverState *bs, int64_t offset,
2428 int count)
2430 BdrvTrackedRequest req;
2431 int max_pdiscard, ret;
2432 int head, tail, align;
2434 if (!bs->drv) {
2435 return -ENOMEDIUM;
2438 ret = bdrv_check_byte_request(bs, offset, count);
2439 if (ret < 0) {
2440 return ret;
2441 } else if (bs->read_only) {
2442 return -EPERM;
2444 assert(!(bs->open_flags & BDRV_O_INACTIVE));
2446 /* Do nothing if disabled. */
2447 if (!(bs->open_flags & BDRV_O_UNMAP)) {
2448 return 0;
2451 if (!bs->drv->bdrv_co_pdiscard && !bs->drv->bdrv_aio_pdiscard) {
2452 return 0;
2455 /* Discard is advisory, but some devices track and coalesce
2456 * unaligned requests, so we must pass everything down rather than
2457 * round here. Still, most devices will just silently ignore
2458 * unaligned requests (by returning -ENOTSUP), so we must fragment
2459 * the request accordingly. */
2460 align = MAX(bs->bl.pdiscard_alignment, bs->bl.request_alignment);
2461 assert(align % bs->bl.request_alignment == 0);
2462 head = offset % align;
2463 tail = (offset + count) % align;
2465 bdrv_inc_in_flight(bs);
2466 tracked_request_begin(&req, bs, offset, count, BDRV_TRACKED_DISCARD);
2468 ret = notifier_with_return_list_notify(&bs->before_write_notifiers, &req);
2469 if (ret < 0) {
2470 goto out;
2473 max_pdiscard = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_pdiscard, INT_MAX),
2474 align);
2475 assert(max_pdiscard >= bs->bl.request_alignment);
2477 while (count > 0) {
2478 int ret;
2479 int num = count;
2481 if (head) {
2482 /* Make small requests to get to alignment boundaries. */
2483 num = MIN(count, align - head);
2484 if (!QEMU_IS_ALIGNED(num, bs->bl.request_alignment)) {
2485 num %= bs->bl.request_alignment;
2487 head = (head + num) % align;
2488 assert(num < max_pdiscard);
2489 } else if (tail) {
2490 if (num > align) {
2491 /* Shorten the request to the last aligned cluster. */
2492 num -= tail;
2493 } else if (!QEMU_IS_ALIGNED(tail, bs->bl.request_alignment) &&
2494 tail > bs->bl.request_alignment) {
2495 tail %= bs->bl.request_alignment;
2496 num -= tail;
2499 /* limit request size */
2500 if (num > max_pdiscard) {
2501 num = max_pdiscard;
2504 if (bs->drv->bdrv_co_pdiscard) {
2505 ret = bs->drv->bdrv_co_pdiscard(bs, offset, num);
2506 } else {
2507 BlockAIOCB *acb;
2508 CoroutineIOCompletion co = {
2509 .coroutine = qemu_coroutine_self(),
2512 acb = bs->drv->bdrv_aio_pdiscard(bs, offset, num,
2513 bdrv_co_io_em_complete, &co);
2514 if (acb == NULL) {
2515 ret = -EIO;
2516 goto out;
2517 } else {
2518 qemu_coroutine_yield();
2519 ret = co.ret;
2522 if (ret && ret != -ENOTSUP) {
2523 goto out;
2526 offset += num;
2527 count -= num;
2529 ret = 0;
2530 out:
2531 atomic_inc(&bs->write_gen);
2532 bdrv_set_dirty(bs, req.offset >> BDRV_SECTOR_BITS,
2533 req.bytes >> BDRV_SECTOR_BITS);
2534 tracked_request_end(&req);
2535 bdrv_dec_in_flight(bs);
2536 return ret;
2539 int bdrv_pdiscard(BlockDriverState *bs, int64_t offset, int count)
2541 Coroutine *co;
2542 DiscardCo rwco = {
2543 .bs = bs,
2544 .offset = offset,
2545 .count = count,
2546 .ret = NOT_DONE,
2549 if (qemu_in_coroutine()) {
2550 /* Fast-path if already in coroutine context */
2551 bdrv_pdiscard_co_entry(&rwco);
2552 } else {
2553 co = qemu_coroutine_create(bdrv_pdiscard_co_entry, &rwco);
2554 bdrv_coroutine_enter(bs, co);
2555 BDRV_POLL_WHILE(bs, rwco.ret == NOT_DONE);
2558 return rwco.ret;
2561 int bdrv_co_ioctl(BlockDriverState *bs, int req, void *buf)
2563 BlockDriver *drv = bs->drv;
2564 CoroutineIOCompletion co = {
2565 .coroutine = qemu_coroutine_self(),
2567 BlockAIOCB *acb;
2569 bdrv_inc_in_flight(bs);
2570 if (!drv || (!drv->bdrv_aio_ioctl && !drv->bdrv_co_ioctl)) {
2571 co.ret = -ENOTSUP;
2572 goto out;
2575 if (drv->bdrv_co_ioctl) {
2576 co.ret = drv->bdrv_co_ioctl(bs, req, buf);
2577 } else {
2578 acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
2579 if (!acb) {
2580 co.ret = -ENOTSUP;
2581 goto out;
2583 qemu_coroutine_yield();
2585 out:
2586 bdrv_dec_in_flight(bs);
2587 return co.ret;
2590 void *qemu_blockalign(BlockDriverState *bs, size_t size)
2592 return qemu_memalign(bdrv_opt_mem_align(bs), size);
2595 void *qemu_blockalign0(BlockDriverState *bs, size_t size)
2597 return memset(qemu_blockalign(bs, size), 0, size);
2600 void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
2602 size_t align = bdrv_opt_mem_align(bs);
2604 /* Ensure that NULL is never returned on success */
2605 assert(align > 0);
2606 if (size == 0) {
2607 size = align;
2610 return qemu_try_memalign(align, size);
2613 void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
2615 void *mem = qemu_try_blockalign(bs, size);
2617 if (mem) {
2618 memset(mem, 0, size);
2621 return mem;
2625 * Check if all memory in this vector is sector aligned.
2627 bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
2629 int i;
2630 size_t alignment = bdrv_min_mem_align(bs);
2632 for (i = 0; i < qiov->niov; i++) {
2633 if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
2634 return false;
2636 if (qiov->iov[i].iov_len % alignment) {
2637 return false;
2641 return true;
2644 void bdrv_add_before_write_notifier(BlockDriverState *bs,
2645 NotifierWithReturn *notifier)
2647 notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
2650 void bdrv_io_plug(BlockDriverState *bs)
2652 BdrvChild *child;
2654 QLIST_FOREACH(child, &bs->children, next) {
2655 bdrv_io_plug(child->bs);
2658 if (atomic_fetch_inc(&bs->io_plugged) == 0) {
2659 BlockDriver *drv = bs->drv;
2660 if (drv && drv->bdrv_io_plug) {
2661 drv->bdrv_io_plug(bs);
2666 void bdrv_io_unplug(BlockDriverState *bs)
2668 BdrvChild *child;
2670 assert(bs->io_plugged);
2671 if (atomic_fetch_dec(&bs->io_plugged) == 1) {
2672 BlockDriver *drv = bs->drv;
2673 if (drv && drv->bdrv_io_unplug) {
2674 drv->bdrv_io_unplug(bs);
2678 QLIST_FOREACH(child, &bs->children, next) {
2679 bdrv_io_unplug(child->bs);