xref: /openbmc/qemu/block/io.c (revision 6350b2a09b8a330cbfaea462a34bbb1b8c63d7b1)
1 /*
2  * Block layer I/O functions
3  *
4  * Copyright (c) 2003 Fabrice Bellard
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  */
24 
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"
34 
35 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
36 
37 /* Maximum bounce buffer for copy-on-read and write zeroes, in bytes */
38 #define MAX_BOUNCE_BUFFER (32768 << BDRV_SECTOR_BITS)
39 
40 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
41     int64_t offset, int bytes, BdrvRequestFlags flags);
42 
43 void bdrv_parent_drained_begin(BlockDriverState *bs)
44 {
45     BdrvChild *c;
46 
47     QLIST_FOREACH(c, &bs->parents, next_parent) {
48         if (c->role->drained_begin) {
49             c->role->drained_begin(c);
50         }
51     }
52 }
53 
54 void bdrv_parent_drained_end(BlockDriverState *bs)
55 {
56     BdrvChild *c;
57 
58     QLIST_FOREACH(c, &bs->parents, next_parent) {
59         if (c->role->drained_end) {
60             c->role->drained_end(c);
61         }
62     }
63 }
64 
65 static void bdrv_merge_limits(BlockLimits *dst, const BlockLimits *src)
66 {
67     dst->opt_transfer = MAX(dst->opt_transfer, src->opt_transfer);
68     dst->max_transfer = MIN_NON_ZERO(dst->max_transfer, src->max_transfer);
69     dst->opt_mem_alignment = MAX(dst->opt_mem_alignment,
70                                  src->opt_mem_alignment);
71     dst->min_mem_alignment = MAX(dst->min_mem_alignment,
72                                  src->min_mem_alignment);
73     dst->max_iov = MIN_NON_ZERO(dst->max_iov, src->max_iov);
74 }
75 
76 void bdrv_refresh_limits(BlockDriverState *bs, Error **errp)
77 {
78     BlockDriver *drv = bs->drv;
79     Error *local_err = NULL;
80 
81     memset(&bs->bl, 0, sizeof(bs->bl));
82 
83     if (!drv) {
84         return;
85     }
86 
87     /* Default alignment based on whether driver has byte interface */
88     bs->bl.request_alignment = drv->bdrv_co_preadv ? 1 : 512;
89 
90     /* Take some limits from the children as a default */
91     if (bs->file) {
92         bdrv_refresh_limits(bs->file->bs, &local_err);
93         if (local_err) {
94             error_propagate(errp, local_err);
95             return;
96         }
97         bdrv_merge_limits(&bs->bl, &bs->file->bs->bl);
98     } else {
99         bs->bl.min_mem_alignment = 512;
100         bs->bl.opt_mem_alignment = getpagesize();
101 
102         /* Safe default since most protocols use readv()/writev()/etc */
103         bs->bl.max_iov = IOV_MAX;
104     }
105 
106     if (bs->backing) {
107         bdrv_refresh_limits(bs->backing->bs, &local_err);
108         if (local_err) {
109             error_propagate(errp, local_err);
110             return;
111         }
112         bdrv_merge_limits(&bs->bl, &bs->backing->bs->bl);
113     }
114 
115     /* Then let the driver override it */
116     if (drv->bdrv_refresh_limits) {
117         drv->bdrv_refresh_limits(bs, errp);
118     }
119 }
120 
121 /**
122  * The copy-on-read flag is actually a reference count so multiple users may
123  * use the feature without worrying about clobbering its previous state.
124  * Copy-on-read stays enabled until all users have called to disable it.
125  */
126 void bdrv_enable_copy_on_read(BlockDriverState *bs)
127 {
128     atomic_inc(&bs->copy_on_read);
129 }
130 
131 void bdrv_disable_copy_on_read(BlockDriverState *bs)
132 {
133     int old = atomic_fetch_dec(&bs->copy_on_read);
134     assert(old >= 1);
135 }
136 
137 /* Check if any requests are in-flight (including throttled requests) */
138 bool bdrv_requests_pending(BlockDriverState *bs)
139 {
140     BdrvChild *child;
141 
142     if (atomic_read(&bs->in_flight)) {
143         return true;
144     }
145 
146     QLIST_FOREACH(child, &bs->children, next) {
147         if (bdrv_requests_pending(child->bs)) {
148             return true;
149         }
150     }
151 
152     return false;
153 }
154 
155 typedef struct {
156     Coroutine *co;
157     BlockDriverState *bs;
158     bool done;
159     bool begin;
160 } BdrvCoDrainData;
161 
162 static void coroutine_fn bdrv_drain_invoke_entry(void *opaque)
163 {
164     BdrvCoDrainData *data = opaque;
165     BlockDriverState *bs = data->bs;
166 
167     if (data->begin) {
168         bs->drv->bdrv_co_drain_begin(bs);
169     } else {
170         bs->drv->bdrv_co_drain_end(bs);
171     }
172 
173     /* Set data->done before reading bs->wakeup.  */
174     atomic_mb_set(&data->done, true);
175     bdrv_wakeup(bs);
176 }
177 
178 static void bdrv_drain_invoke(BlockDriverState *bs, bool begin)
179 {
180     BdrvCoDrainData data = { .bs = bs, .done = false, .begin = begin};
181 
182     if (!bs->drv || (begin && !bs->drv->bdrv_co_drain_begin) ||
183             (!begin && !bs->drv->bdrv_co_drain_end)) {
184         return;
185     }
186 
187     data.co = qemu_coroutine_create(bdrv_drain_invoke_entry, &data);
188     bdrv_coroutine_enter(bs, data.co);
189     BDRV_POLL_WHILE(bs, !data.done);
190 }
191 
192 static bool bdrv_drain_recurse(BlockDriverState *bs, bool begin)
193 {
194     BdrvChild *child, *tmp;
195     bool waited;
196 
197     /* Ensure any pending metadata writes are submitted to bs->file.  */
198     bdrv_drain_invoke(bs, begin);
199 
200     /* Wait for drained requests to finish */
201     waited = BDRV_POLL_WHILE(bs, atomic_read(&bs->in_flight) > 0);
202 
203     QLIST_FOREACH_SAFE(child, &bs->children, next, tmp) {
204         BlockDriverState *bs = child->bs;
205         bool in_main_loop =
206             qemu_get_current_aio_context() == qemu_get_aio_context();
207         assert(bs->refcnt > 0);
208         if (in_main_loop) {
209             /* In case the recursive bdrv_drain_recurse processes a
210              * block_job_defer_to_main_loop BH and modifies the graph,
211              * let's hold a reference to bs until we are done.
212              *
213              * IOThread doesn't have such a BH, and it is not safe to call
214              * bdrv_unref without BQL, so skip doing it there.
215              */
216             bdrv_ref(bs);
217         }
218         waited |= bdrv_drain_recurse(bs, begin);
219         if (in_main_loop) {
220             bdrv_unref(bs);
221         }
222     }
223 
224     return waited;
225 }
226 
227 static void bdrv_co_drain_bh_cb(void *opaque)
228 {
229     BdrvCoDrainData *data = opaque;
230     Coroutine *co = data->co;
231     BlockDriverState *bs = data->bs;
232 
233     bdrv_dec_in_flight(bs);
234     if (data->begin) {
235         bdrv_drained_begin(bs);
236     } else {
237         bdrv_drained_end(bs);
238     }
239 
240     data->done = true;
241     aio_co_wake(co);
242 }
243 
244 static void coroutine_fn bdrv_co_yield_to_drain(BlockDriverState *bs,
245                                                 bool begin)
246 {
247     BdrvCoDrainData data;
248 
249     /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
250      * other coroutines run if they were queued from
251      * qemu_co_queue_run_restart(). */
252 
253     assert(qemu_in_coroutine());
254     data = (BdrvCoDrainData) {
255         .co = qemu_coroutine_self(),
256         .bs = bs,
257         .done = false,
258         .begin = begin,
259     };
260     bdrv_inc_in_flight(bs);
261     aio_bh_schedule_oneshot(bdrv_get_aio_context(bs),
262                             bdrv_co_drain_bh_cb, &data);
263 
264     qemu_coroutine_yield();
265     /* If we are resumed from some other event (such as an aio completion or a
266      * timer callback), it is a bug in the caller that should be fixed. */
267     assert(data.done);
268 }
269 
270 void bdrv_drained_begin(BlockDriverState *bs)
271 {
272     if (qemu_in_coroutine()) {
273         bdrv_co_yield_to_drain(bs, true);
274         return;
275     }
276 
277     if (atomic_fetch_inc(&bs->quiesce_counter) == 0) {
278         aio_disable_external(bdrv_get_aio_context(bs));
279         bdrv_parent_drained_begin(bs);
280     }
281 
282     bdrv_drain_recurse(bs, true);
283 }
284 
285 void bdrv_drained_end(BlockDriverState *bs)
286 {
287     if (qemu_in_coroutine()) {
288         bdrv_co_yield_to_drain(bs, false);
289         return;
290     }
291     assert(bs->quiesce_counter > 0);
292     if (atomic_fetch_dec(&bs->quiesce_counter) > 1) {
293         return;
294     }
295 
296     bdrv_parent_drained_end(bs);
297     bdrv_drain_recurse(bs, false);
298     aio_enable_external(bdrv_get_aio_context(bs));
299 }
300 
301 /*
302  * Wait for pending requests to complete on a single BlockDriverState subtree,
303  * and suspend block driver's internal I/O until next request arrives.
304  *
305  * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
306  * AioContext.
307  *
308  * Only this BlockDriverState's AioContext is run, so in-flight requests must
309  * not depend on events in other AioContexts.  In that case, use
310  * bdrv_drain_all() instead.
311  */
312 void coroutine_fn bdrv_co_drain(BlockDriverState *bs)
313 {
314     assert(qemu_in_coroutine());
315     bdrv_drained_begin(bs);
316     bdrv_drained_end(bs);
317 }
318 
319 void bdrv_drain(BlockDriverState *bs)
320 {
321     bdrv_drained_begin(bs);
322     bdrv_drained_end(bs);
323 }
324 
325 /*
326  * Wait for pending requests to complete across all BlockDriverStates
327  *
328  * This function does not flush data to disk, use bdrv_flush_all() for that
329  * after calling this function.
330  *
331  * This pauses all block jobs and disables external clients. It must
332  * be paired with bdrv_drain_all_end().
333  *
334  * NOTE: no new block jobs or BlockDriverStates can be created between
335  * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
336  */
337 void bdrv_drain_all_begin(void)
338 {
339     /* Always run first iteration so any pending completion BHs run */
340     bool waited = true;
341     BlockDriverState *bs;
342     BdrvNextIterator it;
343     GSList *aio_ctxs = NULL, *ctx;
344 
345     block_job_pause_all();
346 
347     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
348         AioContext *aio_context = bdrv_get_aio_context(bs);
349 
350         aio_context_acquire(aio_context);
351         bdrv_parent_drained_begin(bs);
352         aio_disable_external(aio_context);
353         aio_context_release(aio_context);
354 
355         if (!g_slist_find(aio_ctxs, aio_context)) {
356             aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
357         }
358     }
359 
360     /* Note that completion of an asynchronous I/O operation can trigger any
361      * number of other I/O operations on other devices---for example a
362      * coroutine can submit an I/O request to another device in response to
363      * request completion.  Therefore we must keep looping until there was no
364      * more activity rather than simply draining each device independently.
365      */
366     while (waited) {
367         waited = false;
368 
369         for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
370             AioContext *aio_context = ctx->data;
371 
372             aio_context_acquire(aio_context);
373             for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
374                 if (aio_context == bdrv_get_aio_context(bs)) {
375                     waited |= bdrv_drain_recurse(bs, true);
376                 }
377             }
378             aio_context_release(aio_context);
379         }
380     }
381 
382     g_slist_free(aio_ctxs);
383 }
384 
385 void bdrv_drain_all_end(void)
386 {
387     BlockDriverState *bs;
388     BdrvNextIterator it;
389 
390     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
391         AioContext *aio_context = bdrv_get_aio_context(bs);
392 
393         aio_context_acquire(aio_context);
394         aio_enable_external(aio_context);
395         bdrv_parent_drained_end(bs);
396         bdrv_drain_recurse(bs, false);
397         aio_context_release(aio_context);
398     }
399 
400     block_job_resume_all();
401 }
402 
403 void bdrv_drain_all(void)
404 {
405     bdrv_drain_all_begin();
406     bdrv_drain_all_end();
407 }
408 
409 /**
410  * Remove an active request from the tracked requests list
411  *
412  * This function should be called when a tracked request is completing.
413  */
414 static void tracked_request_end(BdrvTrackedRequest *req)
415 {
416     if (req->serialising) {
417         atomic_dec(&req->bs->serialising_in_flight);
418     }
419 
420     qemu_co_mutex_lock(&req->bs->reqs_lock);
421     QLIST_REMOVE(req, list);
422     qemu_co_queue_restart_all(&req->wait_queue);
423     qemu_co_mutex_unlock(&req->bs->reqs_lock);
424 }
425 
426 /**
427  * Add an active request to the tracked requests list
428  */
429 static void tracked_request_begin(BdrvTrackedRequest *req,
430                                   BlockDriverState *bs,
431                                   int64_t offset,
432                                   unsigned int bytes,
433                                   enum BdrvTrackedRequestType type)
434 {
435     *req = (BdrvTrackedRequest){
436         .bs = bs,
437         .offset         = offset,
438         .bytes          = bytes,
439         .type           = type,
440         .co             = qemu_coroutine_self(),
441         .serialising    = false,
442         .overlap_offset = offset,
443         .overlap_bytes  = bytes,
444     };
445 
446     qemu_co_queue_init(&req->wait_queue);
447 
448     qemu_co_mutex_lock(&bs->reqs_lock);
449     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
450     qemu_co_mutex_unlock(&bs->reqs_lock);
451 }
452 
453 static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
454 {
455     int64_t overlap_offset = req->offset & ~(align - 1);
456     unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
457                                - overlap_offset;
458 
459     if (!req->serialising) {
460         atomic_inc(&req->bs->serialising_in_flight);
461         req->serialising = true;
462     }
463 
464     req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
465     req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
466 }
467 
468 /**
469  * Round a region to cluster boundaries
470  */
471 void bdrv_round_to_clusters(BlockDriverState *bs,
472                             int64_t offset, int64_t bytes,
473                             int64_t *cluster_offset,
474                             int64_t *cluster_bytes)
475 {
476     BlockDriverInfo bdi;
477 
478     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
479         *cluster_offset = offset;
480         *cluster_bytes = bytes;
481     } else {
482         int64_t c = bdi.cluster_size;
483         *cluster_offset = QEMU_ALIGN_DOWN(offset, c);
484         *cluster_bytes = QEMU_ALIGN_UP(offset - *cluster_offset + bytes, c);
485     }
486 }
487 
488 static int bdrv_get_cluster_size(BlockDriverState *bs)
489 {
490     BlockDriverInfo bdi;
491     int ret;
492 
493     ret = bdrv_get_info(bs, &bdi);
494     if (ret < 0 || bdi.cluster_size == 0) {
495         return bs->bl.request_alignment;
496     } else {
497         return bdi.cluster_size;
498     }
499 }
500 
501 static bool tracked_request_overlaps(BdrvTrackedRequest *req,
502                                      int64_t offset, unsigned int bytes)
503 {
504     /*        aaaa   bbbb */
505     if (offset >= req->overlap_offset + req->overlap_bytes) {
506         return false;
507     }
508     /* bbbb   aaaa        */
509     if (req->overlap_offset >= offset + bytes) {
510         return false;
511     }
512     return true;
513 }
514 
515 void bdrv_inc_in_flight(BlockDriverState *bs)
516 {
517     atomic_inc(&bs->in_flight);
518 }
519 
520 static void dummy_bh_cb(void *opaque)
521 {
522 }
523 
524 void bdrv_wakeup(BlockDriverState *bs)
525 {
526     /* The barrier (or an atomic op) is in the caller.  */
527     if (atomic_read(&bs->wakeup)) {
528         aio_bh_schedule_oneshot(qemu_get_aio_context(), dummy_bh_cb, NULL);
529     }
530 }
531 
532 void bdrv_dec_in_flight(BlockDriverState *bs)
533 {
534     atomic_dec(&bs->in_flight);
535     bdrv_wakeup(bs);
536 }
537 
538 static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
539 {
540     BlockDriverState *bs = self->bs;
541     BdrvTrackedRequest *req;
542     bool retry;
543     bool waited = false;
544 
545     if (!atomic_read(&bs->serialising_in_flight)) {
546         return false;
547     }
548 
549     do {
550         retry = false;
551         qemu_co_mutex_lock(&bs->reqs_lock);
552         QLIST_FOREACH(req, &bs->tracked_requests, list) {
553             if (req == self || (!req->serialising && !self->serialising)) {
554                 continue;
555             }
556             if (tracked_request_overlaps(req, self->overlap_offset,
557                                          self->overlap_bytes))
558             {
559                 /* Hitting this means there was a reentrant request, for
560                  * example, a block driver issuing nested requests.  This must
561                  * never happen since it means deadlock.
562                  */
563                 assert(qemu_coroutine_self() != req->co);
564 
565                 /* If the request is already (indirectly) waiting for us, or
566                  * will wait for us as soon as it wakes up, then just go on
567                  * (instead of producing a deadlock in the former case). */
568                 if (!req->waiting_for) {
569                     self->waiting_for = req;
570                     qemu_co_queue_wait(&req->wait_queue, &bs->reqs_lock);
571                     self->waiting_for = NULL;
572                     retry = true;
573                     waited = true;
574                     break;
575                 }
576             }
577         }
578         qemu_co_mutex_unlock(&bs->reqs_lock);
579     } while (retry);
580 
581     return waited;
582 }
583 
584 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
585                                    size_t size)
586 {
587     if (size > BDRV_REQUEST_MAX_SECTORS << BDRV_SECTOR_BITS) {
588         return -EIO;
589     }
590 
591     if (!bdrv_is_inserted(bs)) {
592         return -ENOMEDIUM;
593     }
594 
595     if (offset < 0) {
596         return -EIO;
597     }
598 
599     return 0;
600 }
601 
602 typedef struct RwCo {
603     BdrvChild *child;
604     int64_t offset;
605     QEMUIOVector *qiov;
606     bool is_write;
607     int ret;
608     BdrvRequestFlags flags;
609 } RwCo;
610 
611 static void coroutine_fn bdrv_rw_co_entry(void *opaque)
612 {
613     RwCo *rwco = opaque;
614 
615     if (!rwco->is_write) {
616         rwco->ret = bdrv_co_preadv(rwco->child, rwco->offset,
617                                    rwco->qiov->size, rwco->qiov,
618                                    rwco->flags);
619     } else {
620         rwco->ret = bdrv_co_pwritev(rwco->child, rwco->offset,
621                                     rwco->qiov->size, rwco->qiov,
622                                     rwco->flags);
623     }
624 }
625 
626 /*
627  * Process a vectored synchronous request using coroutines
628  */
629 static int bdrv_prwv_co(BdrvChild *child, int64_t offset,
630                         QEMUIOVector *qiov, bool is_write,
631                         BdrvRequestFlags flags)
632 {
633     Coroutine *co;
634     RwCo rwco = {
635         .child = child,
636         .offset = offset,
637         .qiov = qiov,
638         .is_write = is_write,
639         .ret = NOT_DONE,
640         .flags = flags,
641     };
642 
643     if (qemu_in_coroutine()) {
644         /* Fast-path if already in coroutine context */
645         bdrv_rw_co_entry(&rwco);
646     } else {
647         co = qemu_coroutine_create(bdrv_rw_co_entry, &rwco);
648         bdrv_coroutine_enter(child->bs, co);
649         BDRV_POLL_WHILE(child->bs, rwco.ret == NOT_DONE);
650     }
651     return rwco.ret;
652 }
653 
654 /*
655  * Process a synchronous request using coroutines
656  */
657 static int bdrv_rw_co(BdrvChild *child, int64_t sector_num, uint8_t *buf,
658                       int nb_sectors, bool is_write, BdrvRequestFlags flags)
659 {
660     QEMUIOVector qiov;
661     struct iovec iov = {
662         .iov_base = (void *)buf,
663         .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
664     };
665 
666     if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
667         return -EINVAL;
668     }
669 
670     qemu_iovec_init_external(&qiov, &iov, 1);
671     return bdrv_prwv_co(child, sector_num << BDRV_SECTOR_BITS,
672                         &qiov, is_write, flags);
673 }
674 
675 /* return < 0 if error. See bdrv_write() for the return codes */
676 int bdrv_read(BdrvChild *child, int64_t sector_num,
677               uint8_t *buf, int nb_sectors)
678 {
679     return bdrv_rw_co(child, sector_num, buf, nb_sectors, false, 0);
680 }
681 
682 /* Return < 0 if error. Important errors are:
683   -EIO         generic I/O error (may happen for all errors)
684   -ENOMEDIUM   No media inserted.
685   -EINVAL      Invalid sector number or nb_sectors
686   -EACCES      Trying to write a read-only device
687 */
688 int bdrv_write(BdrvChild *child, int64_t sector_num,
689                const uint8_t *buf, int nb_sectors)
690 {
691     return bdrv_rw_co(child, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
692 }
693 
694 int bdrv_pwrite_zeroes(BdrvChild *child, int64_t offset,
695                        int bytes, BdrvRequestFlags flags)
696 {
697     QEMUIOVector qiov;
698     struct iovec iov = {
699         .iov_base = NULL,
700         .iov_len = bytes,
701     };
702 
703     qemu_iovec_init_external(&qiov, &iov, 1);
704     return bdrv_prwv_co(child, offset, &qiov, true,
705                         BDRV_REQ_ZERO_WRITE | flags);
706 }
707 
708 /*
709  * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
710  * The operation is sped up by checking the block status and only writing
711  * zeroes to the device if they currently do not return zeroes. Optional
712  * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
713  * BDRV_REQ_FUA).
714  *
715  * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
716  */
717 int bdrv_make_zero(BdrvChild *child, BdrvRequestFlags flags)
718 {
719     int ret;
720     int64_t target_size, bytes, offset = 0;
721     BlockDriverState *bs = child->bs;
722 
723     target_size = bdrv_getlength(bs);
724     if (target_size < 0) {
725         return target_size;
726     }
727 
728     for (;;) {
729         bytes = MIN(target_size - offset, BDRV_REQUEST_MAX_BYTES);
730         if (bytes <= 0) {
731             return 0;
732         }
733         ret = bdrv_block_status(bs, offset, bytes, &bytes, NULL, NULL);
734         if (ret < 0) {
735             error_report("error getting block status at offset %" PRId64 ": %s",
736                          offset, strerror(-ret));
737             return ret;
738         }
739         if (ret & BDRV_BLOCK_ZERO) {
740             offset += bytes;
741             continue;
742         }
743         ret = bdrv_pwrite_zeroes(child, offset, bytes, flags);
744         if (ret < 0) {
745             error_report("error writing zeroes at offset %" PRId64 ": %s",
746                          offset, strerror(-ret));
747             return ret;
748         }
749         offset += bytes;
750     }
751 }
752 
753 int bdrv_preadv(BdrvChild *child, int64_t offset, QEMUIOVector *qiov)
754 {
755     int ret;
756 
757     ret = bdrv_prwv_co(child, offset, qiov, false, 0);
758     if (ret < 0) {
759         return ret;
760     }
761 
762     return qiov->size;
763 }
764 
765 int bdrv_pread(BdrvChild *child, int64_t offset, void *buf, int bytes)
766 {
767     QEMUIOVector qiov;
768     struct iovec iov = {
769         .iov_base = (void *)buf,
770         .iov_len = bytes,
771     };
772 
773     if (bytes < 0) {
774         return -EINVAL;
775     }
776 
777     qemu_iovec_init_external(&qiov, &iov, 1);
778     return bdrv_preadv(child, offset, &qiov);
779 }
780 
781 int bdrv_pwritev(BdrvChild *child, int64_t offset, QEMUIOVector *qiov)
782 {
783     int ret;
784 
785     ret = bdrv_prwv_co(child, offset, qiov, true, 0);
786     if (ret < 0) {
787         return ret;
788     }
789 
790     return qiov->size;
791 }
792 
793 int bdrv_pwrite(BdrvChild *child, int64_t offset, const void *buf, int bytes)
794 {
795     QEMUIOVector qiov;
796     struct iovec iov = {
797         .iov_base   = (void *) buf,
798         .iov_len    = bytes,
799     };
800 
801     if (bytes < 0) {
802         return -EINVAL;
803     }
804 
805     qemu_iovec_init_external(&qiov, &iov, 1);
806     return bdrv_pwritev(child, offset, &qiov);
807 }
808 
809 /*
810  * Writes to the file and ensures that no writes are reordered across this
811  * request (acts as a barrier)
812  *
813  * Returns 0 on success, -errno in error cases.
814  */
815 int bdrv_pwrite_sync(BdrvChild *child, int64_t offset,
816                      const void *buf, int count)
817 {
818     int ret;
819 
820     ret = bdrv_pwrite(child, offset, buf, count);
821     if (ret < 0) {
822         return ret;
823     }
824 
825     ret = bdrv_flush(child->bs);
826     if (ret < 0) {
827         return ret;
828     }
829 
830     return 0;
831 }
832 
833 typedef struct CoroutineIOCompletion {
834     Coroutine *coroutine;
835     int ret;
836 } CoroutineIOCompletion;
837 
838 static void bdrv_co_io_em_complete(void *opaque, int ret)
839 {
840     CoroutineIOCompletion *co = opaque;
841 
842     co->ret = ret;
843     aio_co_wake(co->coroutine);
844 }
845 
846 static int coroutine_fn bdrv_driver_preadv(BlockDriverState *bs,
847                                            uint64_t offset, uint64_t bytes,
848                                            QEMUIOVector *qiov, int flags)
849 {
850     BlockDriver *drv = bs->drv;
851     int64_t sector_num;
852     unsigned int nb_sectors;
853 
854     assert(!(flags & ~BDRV_REQ_MASK));
855 
856     if (drv->bdrv_co_preadv) {
857         return drv->bdrv_co_preadv(bs, offset, bytes, qiov, flags);
858     }
859 
860     sector_num = offset >> BDRV_SECTOR_BITS;
861     nb_sectors = bytes >> BDRV_SECTOR_BITS;
862 
863     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
864     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
865     assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);
866 
867     if (drv->bdrv_co_readv) {
868         return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
869     } else {
870         BlockAIOCB *acb;
871         CoroutineIOCompletion co = {
872             .coroutine = qemu_coroutine_self(),
873         };
874 
875         acb = bs->drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
876                                       bdrv_co_io_em_complete, &co);
877         if (acb == NULL) {
878             return -EIO;
879         } else {
880             qemu_coroutine_yield();
881             return co.ret;
882         }
883     }
884 }
885 
886 static int coroutine_fn bdrv_driver_pwritev(BlockDriverState *bs,
887                                             uint64_t offset, uint64_t bytes,
888                                             QEMUIOVector *qiov, int flags)
889 {
890     BlockDriver *drv = bs->drv;
891     int64_t sector_num;
892     unsigned int nb_sectors;
893     int ret;
894 
895     assert(!(flags & ~BDRV_REQ_MASK));
896 
897     if (drv->bdrv_co_pwritev) {
898         ret = drv->bdrv_co_pwritev(bs, offset, bytes, qiov,
899                                    flags & bs->supported_write_flags);
900         flags &= ~bs->supported_write_flags;
901         goto emulate_flags;
902     }
903 
904     sector_num = offset >> BDRV_SECTOR_BITS;
905     nb_sectors = bytes >> BDRV_SECTOR_BITS;
906 
907     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
908     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
909     assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);
910 
911     if (drv->bdrv_co_writev_flags) {
912         ret = drv->bdrv_co_writev_flags(bs, sector_num, nb_sectors, qiov,
913                                         flags & bs->supported_write_flags);
914         flags &= ~bs->supported_write_flags;
915     } else if (drv->bdrv_co_writev) {
916         assert(!bs->supported_write_flags);
917         ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
918     } else {
919         BlockAIOCB *acb;
920         CoroutineIOCompletion co = {
921             .coroutine = qemu_coroutine_self(),
922         };
923 
924         acb = bs->drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
925                                        bdrv_co_io_em_complete, &co);
926         if (acb == NULL) {
927             ret = -EIO;
928         } else {
929             qemu_coroutine_yield();
930             ret = co.ret;
931         }
932     }
933 
934 emulate_flags:
935     if (ret == 0 && (flags & BDRV_REQ_FUA)) {
936         ret = bdrv_co_flush(bs);
937     }
938 
939     return ret;
940 }
941 
942 static int coroutine_fn
943 bdrv_driver_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
944                                uint64_t bytes, QEMUIOVector *qiov)
945 {
946     BlockDriver *drv = bs->drv;
947 
948     if (!drv->bdrv_co_pwritev_compressed) {
949         return -ENOTSUP;
950     }
951 
952     return drv->bdrv_co_pwritev_compressed(bs, offset, bytes, qiov);
953 }
954 
955 static int coroutine_fn bdrv_co_do_copy_on_readv(BdrvChild *child,
956         int64_t offset, unsigned int bytes, QEMUIOVector *qiov)
957 {
958     BlockDriverState *bs = child->bs;
959 
960     /* Perform I/O through a temporary buffer so that users who scribble over
961      * their read buffer while the operation is in progress do not end up
962      * modifying the image file.  This is critical for zero-copy guest I/O
963      * where anything might happen inside guest memory.
964      */
965     void *bounce_buffer;
966 
967     BlockDriver *drv = bs->drv;
968     struct iovec iov;
969     QEMUIOVector local_qiov;
970     int64_t cluster_offset;
971     int64_t cluster_bytes;
972     size_t skip_bytes;
973     int ret;
974     int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer,
975                                     BDRV_REQUEST_MAX_BYTES);
976     unsigned int progress = 0;
977 
978     /* FIXME We cannot require callers to have write permissions when all they
979      * are doing is a read request. If we did things right, write permissions
980      * would be obtained anyway, but internally by the copy-on-read code. As
981      * long as it is implemented here rather than in a separate filter driver,
982      * the copy-on-read code doesn't have its own BdrvChild, however, for which
983      * it could request permissions. Therefore we have to bypass the permission
984      * system for the moment. */
985     // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
986 
987     /* Cover entire cluster so no additional backing file I/O is required when
988      * allocating cluster in the image file.  Note that this value may exceed
989      * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
990      * is one reason we loop rather than doing it all at once.
991      */
992     bdrv_round_to_clusters(bs, offset, bytes, &cluster_offset, &cluster_bytes);
993     skip_bytes = offset - cluster_offset;
994 
995     trace_bdrv_co_do_copy_on_readv(bs, offset, bytes,
996                                    cluster_offset, cluster_bytes);
997 
998     bounce_buffer = qemu_try_blockalign(bs,
999                                         MIN(MIN(max_transfer, cluster_bytes),
1000                                             MAX_BOUNCE_BUFFER));
1001     if (bounce_buffer == NULL) {
1002         ret = -ENOMEM;
1003         goto err;
1004     }
1005 
1006     while (cluster_bytes) {
1007         int64_t pnum;
1008 
1009         ret = bdrv_is_allocated(bs, cluster_offset,
1010                                 MIN(cluster_bytes, max_transfer), &pnum);
1011         if (ret < 0) {
1012             /* Safe to treat errors in querying allocation as if
1013              * unallocated; we'll probably fail again soon on the
1014              * read, but at least that will set a decent errno.
1015              */
1016             pnum = MIN(cluster_bytes, max_transfer);
1017         }
1018 
1019         assert(skip_bytes < pnum);
1020 
1021         if (ret <= 0) {
1022             /* Must copy-on-read; use the bounce buffer */
1023             iov.iov_base = bounce_buffer;
1024             iov.iov_len = pnum = MIN(pnum, MAX_BOUNCE_BUFFER);
1025             qemu_iovec_init_external(&local_qiov, &iov, 1);
1026 
1027             ret = bdrv_driver_preadv(bs, cluster_offset, pnum,
1028                                      &local_qiov, 0);
1029             if (ret < 0) {
1030                 goto err;
1031             }
1032 
1033             bdrv_debug_event(bs, BLKDBG_COR_WRITE);
1034             if (drv->bdrv_co_pwrite_zeroes &&
1035                 buffer_is_zero(bounce_buffer, pnum)) {
1036                 /* FIXME: Should we (perhaps conditionally) be setting
1037                  * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1038                  * that still correctly reads as zero? */
1039                 ret = bdrv_co_do_pwrite_zeroes(bs, cluster_offset, pnum, 0);
1040             } else {
1041                 /* This does not change the data on the disk, it is not
1042                  * necessary to flush even in cache=writethrough mode.
1043                  */
1044                 ret = bdrv_driver_pwritev(bs, cluster_offset, pnum,
1045                                           &local_qiov, 0);
1046             }
1047 
1048             if (ret < 0) {
1049                 /* It might be okay to ignore write errors for guest
1050                  * requests.  If this is a deliberate copy-on-read
1051                  * then we don't want to ignore the error.  Simply
1052                  * report it in all cases.
1053                  */
1054                 goto err;
1055             }
1056 
1057             qemu_iovec_from_buf(qiov, progress, bounce_buffer + skip_bytes,
1058                                 pnum - skip_bytes);
1059         } else {
1060             /* Read directly into the destination */
1061             qemu_iovec_init(&local_qiov, qiov->niov);
1062             qemu_iovec_concat(&local_qiov, qiov, progress, pnum - skip_bytes);
1063             ret = bdrv_driver_preadv(bs, offset + progress, local_qiov.size,
1064                                      &local_qiov, 0);
1065             qemu_iovec_destroy(&local_qiov);
1066             if (ret < 0) {
1067                 goto err;
1068             }
1069         }
1070 
1071         cluster_offset += pnum;
1072         cluster_bytes -= pnum;
1073         progress += pnum - skip_bytes;
1074         skip_bytes = 0;
1075     }
1076     ret = 0;
1077 
1078 err:
1079     qemu_vfree(bounce_buffer);
1080     return ret;
1081 }
1082 
1083 /*
1084  * Forwards an already correctly aligned request to the BlockDriver. This
1085  * handles copy on read, zeroing after EOF, and fragmentation of large
1086  * reads; any other features must be implemented by the caller.
1087  */
1088 static int coroutine_fn bdrv_aligned_preadv(BdrvChild *child,
1089     BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
1090     int64_t align, QEMUIOVector *qiov, int flags)
1091 {
1092     BlockDriverState *bs = child->bs;
1093     int64_t total_bytes, max_bytes;
1094     int ret = 0;
1095     uint64_t bytes_remaining = bytes;
1096     int max_transfer;
1097 
1098     assert(is_power_of_2(align));
1099     assert((offset & (align - 1)) == 0);
1100     assert((bytes & (align - 1)) == 0);
1101     assert(!qiov || bytes == qiov->size);
1102     assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1103     max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1104                                    align);
1105 
1106     /* TODO: We would need a per-BDS .supported_read_flags and
1107      * potential fallback support, if we ever implement any read flags
1108      * to pass through to drivers.  For now, there aren't any
1109      * passthrough flags.  */
1110     assert(!(flags & ~(BDRV_REQ_NO_SERIALISING | BDRV_REQ_COPY_ON_READ)));
1111 
1112     /* Handle Copy on Read and associated serialisation */
1113     if (flags & BDRV_REQ_COPY_ON_READ) {
1114         /* If we touch the same cluster it counts as an overlap.  This
1115          * guarantees that allocating writes will be serialized and not race
1116          * with each other for the same cluster.  For example, in copy-on-read
1117          * it ensures that the CoR read and write operations are atomic and
1118          * guest writes cannot interleave between them. */
1119         mark_request_serialising(req, bdrv_get_cluster_size(bs));
1120     }
1121 
1122     if (!(flags & BDRV_REQ_NO_SERIALISING)) {
1123         wait_serialising_requests(req);
1124     }
1125 
1126     if (flags & BDRV_REQ_COPY_ON_READ) {
1127         int64_t pnum;
1128 
1129         ret = bdrv_is_allocated(bs, offset, bytes, &pnum);
1130         if (ret < 0) {
1131             goto out;
1132         }
1133 
1134         if (!ret || pnum != bytes) {
1135             ret = bdrv_co_do_copy_on_readv(child, offset, bytes, qiov);
1136             goto out;
1137         }
1138     }
1139 
1140     /* Forward the request to the BlockDriver, possibly fragmenting it */
1141     total_bytes = bdrv_getlength(bs);
1142     if (total_bytes < 0) {
1143         ret = total_bytes;
1144         goto out;
1145     }
1146 
1147     max_bytes = ROUND_UP(MAX(0, total_bytes - offset), align);
1148     if (bytes <= max_bytes && bytes <= max_transfer) {
1149         ret = bdrv_driver_preadv(bs, offset, bytes, qiov, 0);
1150         goto out;
1151     }
1152 
1153     while (bytes_remaining) {
1154         int num;
1155 
1156         if (max_bytes) {
1157             QEMUIOVector local_qiov;
1158 
1159             num = MIN(bytes_remaining, MIN(max_bytes, max_transfer));
1160             assert(num);
1161             qemu_iovec_init(&local_qiov, qiov->niov);
1162             qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num);
1163 
1164             ret = bdrv_driver_preadv(bs, offset + bytes - bytes_remaining,
1165                                      num, &local_qiov, 0);
1166             max_bytes -= num;
1167             qemu_iovec_destroy(&local_qiov);
1168         } else {
1169             num = bytes_remaining;
1170             ret = qemu_iovec_memset(qiov, bytes - bytes_remaining, 0,
1171                                     bytes_remaining);
1172         }
1173         if (ret < 0) {
1174             goto out;
1175         }
1176         bytes_remaining -= num;
1177     }
1178 
1179 out:
1180     return ret < 0 ? ret : 0;
1181 }
1182 
1183 /*
1184  * Handle a read request in coroutine context
1185  */
1186 int coroutine_fn bdrv_co_preadv(BdrvChild *child,
1187     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1188     BdrvRequestFlags flags)
1189 {
1190     BlockDriverState *bs = child->bs;
1191     BlockDriver *drv = bs->drv;
1192     BdrvTrackedRequest req;
1193 
1194     uint64_t align = bs->bl.request_alignment;
1195     uint8_t *head_buf = NULL;
1196     uint8_t *tail_buf = NULL;
1197     QEMUIOVector local_qiov;
1198     bool use_local_qiov = false;
1199     int ret;
1200 
1201     trace_bdrv_co_preadv(child->bs, offset, bytes, flags);
1202 
1203     if (!drv) {
1204         return -ENOMEDIUM;
1205     }
1206 
1207     ret = bdrv_check_byte_request(bs, offset, bytes);
1208     if (ret < 0) {
1209         return ret;
1210     }
1211 
1212     bdrv_inc_in_flight(bs);
1213 
1214     /* Don't do copy-on-read if we read data before write operation */
1215     if (atomic_read(&bs->copy_on_read) && !(flags & BDRV_REQ_NO_SERIALISING)) {
1216         flags |= BDRV_REQ_COPY_ON_READ;
1217     }
1218 
1219     /* Align read if necessary by padding qiov */
1220     if (offset & (align - 1)) {
1221         head_buf = qemu_blockalign(bs, align);
1222         qemu_iovec_init(&local_qiov, qiov->niov + 2);
1223         qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
1224         qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1225         use_local_qiov = true;
1226 
1227         bytes += offset & (align - 1);
1228         offset = offset & ~(align - 1);
1229     }
1230 
1231     if ((offset + bytes) & (align - 1)) {
1232         if (!use_local_qiov) {
1233             qemu_iovec_init(&local_qiov, qiov->niov + 1);
1234             qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1235             use_local_qiov = true;
1236         }
1237         tail_buf = qemu_blockalign(bs, align);
1238         qemu_iovec_add(&local_qiov, tail_buf,
1239                        align - ((offset + bytes) & (align - 1)));
1240 
1241         bytes = ROUND_UP(bytes, align);
1242     }
1243 
1244     tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_READ);
1245     ret = bdrv_aligned_preadv(child, &req, offset, bytes, align,
1246                               use_local_qiov ? &local_qiov : qiov,
1247                               flags);
1248     tracked_request_end(&req);
1249     bdrv_dec_in_flight(bs);
1250 
1251     if (use_local_qiov) {
1252         qemu_iovec_destroy(&local_qiov);
1253         qemu_vfree(head_buf);
1254         qemu_vfree(tail_buf);
1255     }
1256 
1257     return ret;
1258 }
1259 
1260 static int coroutine_fn bdrv_co_do_readv(BdrvChild *child,
1261     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
1262     BdrvRequestFlags flags)
1263 {
1264     if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
1265         return -EINVAL;
1266     }
1267 
1268     return bdrv_co_preadv(child, sector_num << BDRV_SECTOR_BITS,
1269                           nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
1270 }
1271 
1272 int coroutine_fn bdrv_co_readv(BdrvChild *child, int64_t sector_num,
1273                                int nb_sectors, QEMUIOVector *qiov)
1274 {
1275     return bdrv_co_do_readv(child, sector_num, nb_sectors, qiov, 0);
1276 }
1277 
1278 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
1279     int64_t offset, int bytes, BdrvRequestFlags flags)
1280 {
1281     BlockDriver *drv = bs->drv;
1282     QEMUIOVector qiov;
1283     struct iovec iov = {0};
1284     int ret = 0;
1285     bool need_flush = false;
1286     int head = 0;
1287     int tail = 0;
1288 
1289     int max_write_zeroes = MIN_NON_ZERO(bs->bl.max_pwrite_zeroes, INT_MAX);
1290     int alignment = MAX(bs->bl.pwrite_zeroes_alignment,
1291                         bs->bl.request_alignment);
1292     int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer, MAX_BOUNCE_BUFFER);
1293 
1294     assert(alignment % bs->bl.request_alignment == 0);
1295     head = offset % alignment;
1296     tail = (offset + bytes) % alignment;
1297     max_write_zeroes = QEMU_ALIGN_DOWN(max_write_zeroes, alignment);
1298     assert(max_write_zeroes >= bs->bl.request_alignment);
1299 
1300     while (bytes > 0 && !ret) {
1301         int num = bytes;
1302 
1303         /* Align request.  Block drivers can expect the "bulk" of the request
1304          * to be aligned, and that unaligned requests do not cross cluster
1305          * boundaries.
1306          */
1307         if (head) {
1308             /* Make a small request up to the first aligned sector. For
1309              * convenience, limit this request to max_transfer even if
1310              * we don't need to fall back to writes.  */
1311             num = MIN(MIN(bytes, max_transfer), alignment - head);
1312             head = (head + num) % alignment;
1313             assert(num < max_write_zeroes);
1314         } else if (tail && num > alignment) {
1315             /* Shorten the request to the last aligned sector.  */
1316             num -= tail;
1317         }
1318 
1319         /* limit request size */
1320         if (num > max_write_zeroes) {
1321             num = max_write_zeroes;
1322         }
1323 
1324         ret = -ENOTSUP;
1325         /* First try the efficient write zeroes operation */
1326         if (drv->bdrv_co_pwrite_zeroes) {
1327             ret = drv->bdrv_co_pwrite_zeroes(bs, offset, num,
1328                                              flags & bs->supported_zero_flags);
1329             if (ret != -ENOTSUP && (flags & BDRV_REQ_FUA) &&
1330                 !(bs->supported_zero_flags & BDRV_REQ_FUA)) {
1331                 need_flush = true;
1332             }
1333         } else {
1334             assert(!bs->supported_zero_flags);
1335         }
1336 
1337         if (ret == -ENOTSUP) {
1338             /* Fall back to bounce buffer if write zeroes is unsupported */
1339             BdrvRequestFlags write_flags = flags & ~BDRV_REQ_ZERO_WRITE;
1340 
1341             if ((flags & BDRV_REQ_FUA) &&
1342                 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1343                 /* No need for bdrv_driver_pwrite() to do a fallback
1344                  * flush on each chunk; use just one at the end */
1345                 write_flags &= ~BDRV_REQ_FUA;
1346                 need_flush = true;
1347             }
1348             num = MIN(num, max_transfer);
1349             iov.iov_len = num;
1350             if (iov.iov_base == NULL) {
1351                 iov.iov_base = qemu_try_blockalign(bs, num);
1352                 if (iov.iov_base == NULL) {
1353                     ret = -ENOMEM;
1354                     goto fail;
1355                 }
1356                 memset(iov.iov_base, 0, num);
1357             }
1358             qemu_iovec_init_external(&qiov, &iov, 1);
1359 
1360             ret = bdrv_driver_pwritev(bs, offset, num, &qiov, write_flags);
1361 
1362             /* Keep bounce buffer around if it is big enough for all
1363              * all future requests.
1364              */
1365             if (num < max_transfer) {
1366                 qemu_vfree(iov.iov_base);
1367                 iov.iov_base = NULL;
1368             }
1369         }
1370 
1371         offset += num;
1372         bytes -= num;
1373     }
1374 
1375 fail:
1376     if (ret == 0 && need_flush) {
1377         ret = bdrv_co_flush(bs);
1378     }
1379     qemu_vfree(iov.iov_base);
1380     return ret;
1381 }
1382 
1383 /*
1384  * Forwards an already correctly aligned write request to the BlockDriver,
1385  * after possibly fragmenting it.
1386  */
1387 static int coroutine_fn bdrv_aligned_pwritev(BdrvChild *child,
1388     BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
1389     int64_t align, QEMUIOVector *qiov, int flags)
1390 {
1391     BlockDriverState *bs = child->bs;
1392     BlockDriver *drv = bs->drv;
1393     bool waited;
1394     int ret;
1395 
1396     int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
1397     uint64_t bytes_remaining = bytes;
1398     int max_transfer;
1399 
1400     if (bdrv_has_readonly_bitmaps(bs)) {
1401         return -EPERM;
1402     }
1403 
1404     assert(is_power_of_2(align));
1405     assert((offset & (align - 1)) == 0);
1406     assert((bytes & (align - 1)) == 0);
1407     assert(!qiov || bytes == qiov->size);
1408     assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1409     assert(!(flags & ~BDRV_REQ_MASK));
1410     max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1411                                    align);
1412 
1413     waited = wait_serialising_requests(req);
1414     assert(!waited || !req->serialising);
1415     assert(req->overlap_offset <= offset);
1416     assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
1417     assert(child->perm & BLK_PERM_WRITE);
1418     assert(end_sector <= bs->total_sectors || child->perm & BLK_PERM_RESIZE);
1419 
1420     ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
1421 
1422     if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
1423         !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_pwrite_zeroes &&
1424         qemu_iovec_is_zero(qiov)) {
1425         flags |= BDRV_REQ_ZERO_WRITE;
1426         if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
1427             flags |= BDRV_REQ_MAY_UNMAP;
1428         }
1429     }
1430 
1431     if (ret < 0) {
1432         /* Do nothing, write notifier decided to fail this request */
1433     } else if (flags & BDRV_REQ_ZERO_WRITE) {
1434         bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO);
1435         ret = bdrv_co_do_pwrite_zeroes(bs, offset, bytes, flags);
1436     } else if (flags & BDRV_REQ_WRITE_COMPRESSED) {
1437         ret = bdrv_driver_pwritev_compressed(bs, offset, bytes, qiov);
1438     } else if (bytes <= max_transfer) {
1439         bdrv_debug_event(bs, BLKDBG_PWRITEV);
1440         ret = bdrv_driver_pwritev(bs, offset, bytes, qiov, flags);
1441     } else {
1442         bdrv_debug_event(bs, BLKDBG_PWRITEV);
1443         while (bytes_remaining) {
1444             int num = MIN(bytes_remaining, max_transfer);
1445             QEMUIOVector local_qiov;
1446             int local_flags = flags;
1447 
1448             assert(num);
1449             if (num < bytes_remaining && (flags & BDRV_REQ_FUA) &&
1450                 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1451                 /* If FUA is going to be emulated by flush, we only
1452                  * need to flush on the last iteration */
1453                 local_flags &= ~BDRV_REQ_FUA;
1454             }
1455             qemu_iovec_init(&local_qiov, qiov->niov);
1456             qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num);
1457 
1458             ret = bdrv_driver_pwritev(bs, offset + bytes - bytes_remaining,
1459                                       num, &local_qiov, local_flags);
1460             qemu_iovec_destroy(&local_qiov);
1461             if (ret < 0) {
1462                 break;
1463             }
1464             bytes_remaining -= num;
1465         }
1466     }
1467     bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE);
1468 
1469     atomic_inc(&bs->write_gen);
1470     bdrv_set_dirty(bs, offset, bytes);
1471 
1472     stat64_max(&bs->wr_highest_offset, offset + bytes);
1473 
1474     if (ret >= 0) {
1475         bs->total_sectors = MAX(bs->total_sectors, end_sector);
1476         ret = 0;
1477     }
1478 
1479     return ret;
1480 }
1481 
1482 static int coroutine_fn bdrv_co_do_zero_pwritev(BdrvChild *child,
1483                                                 int64_t offset,
1484                                                 unsigned int bytes,
1485                                                 BdrvRequestFlags flags,
1486                                                 BdrvTrackedRequest *req)
1487 {
1488     BlockDriverState *bs = child->bs;
1489     uint8_t *buf = NULL;
1490     QEMUIOVector local_qiov;
1491     struct iovec iov;
1492     uint64_t align = bs->bl.request_alignment;
1493     unsigned int head_padding_bytes, tail_padding_bytes;
1494     int ret = 0;
1495 
1496     head_padding_bytes = offset & (align - 1);
1497     tail_padding_bytes = (align - (offset + bytes)) & (align - 1);
1498 
1499 
1500     assert(flags & BDRV_REQ_ZERO_WRITE);
1501     if (head_padding_bytes || tail_padding_bytes) {
1502         buf = qemu_blockalign(bs, align);
1503         iov = (struct iovec) {
1504             .iov_base   = buf,
1505             .iov_len    = align,
1506         };
1507         qemu_iovec_init_external(&local_qiov, &iov, 1);
1508     }
1509     if (head_padding_bytes) {
1510         uint64_t zero_bytes = MIN(bytes, align - head_padding_bytes);
1511 
1512         /* RMW the unaligned part before head. */
1513         mark_request_serialising(req, align);
1514         wait_serialising_requests(req);
1515         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1516         ret = bdrv_aligned_preadv(child, req, offset & ~(align - 1), align,
1517                                   align, &local_qiov, 0);
1518         if (ret < 0) {
1519             goto fail;
1520         }
1521         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1522 
1523         memset(buf + head_padding_bytes, 0, zero_bytes);
1524         ret = bdrv_aligned_pwritev(child, req, offset & ~(align - 1), align,
1525                                    align, &local_qiov,
1526                                    flags & ~BDRV_REQ_ZERO_WRITE);
1527         if (ret < 0) {
1528             goto fail;
1529         }
1530         offset += zero_bytes;
1531         bytes -= zero_bytes;
1532     }
1533 
1534     assert(!bytes || (offset & (align - 1)) == 0);
1535     if (bytes >= align) {
1536         /* Write the aligned part in the middle. */
1537         uint64_t aligned_bytes = bytes & ~(align - 1);
1538         ret = bdrv_aligned_pwritev(child, req, offset, aligned_bytes, align,
1539                                    NULL, flags);
1540         if (ret < 0) {
1541             goto fail;
1542         }
1543         bytes -= aligned_bytes;
1544         offset += aligned_bytes;
1545     }
1546 
1547     assert(!bytes || (offset & (align - 1)) == 0);
1548     if (bytes) {
1549         assert(align == tail_padding_bytes + bytes);
1550         /* RMW the unaligned part after tail. */
1551         mark_request_serialising(req, align);
1552         wait_serialising_requests(req);
1553         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1554         ret = bdrv_aligned_preadv(child, req, offset, align,
1555                                   align, &local_qiov, 0);
1556         if (ret < 0) {
1557             goto fail;
1558         }
1559         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1560 
1561         memset(buf, 0, bytes);
1562         ret = bdrv_aligned_pwritev(child, req, offset, align, align,
1563                                    &local_qiov, flags & ~BDRV_REQ_ZERO_WRITE);
1564     }
1565 fail:
1566     qemu_vfree(buf);
1567     return ret;
1568 
1569 }
1570 
1571 /*
1572  * Handle a write request in coroutine context
1573  */
1574 int coroutine_fn bdrv_co_pwritev(BdrvChild *child,
1575     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1576     BdrvRequestFlags flags)
1577 {
1578     BlockDriverState *bs = child->bs;
1579     BdrvTrackedRequest req;
1580     uint64_t align = bs->bl.request_alignment;
1581     uint8_t *head_buf = NULL;
1582     uint8_t *tail_buf = NULL;
1583     QEMUIOVector local_qiov;
1584     bool use_local_qiov = false;
1585     int ret;
1586 
1587     trace_bdrv_co_pwritev(child->bs, offset, bytes, flags);
1588 
1589     if (!bs->drv) {
1590         return -ENOMEDIUM;
1591     }
1592     if (bs->read_only) {
1593         return -EPERM;
1594     }
1595     assert(!(bs->open_flags & BDRV_O_INACTIVE));
1596 
1597     ret = bdrv_check_byte_request(bs, offset, bytes);
1598     if (ret < 0) {
1599         return ret;
1600     }
1601 
1602     bdrv_inc_in_flight(bs);
1603     /*
1604      * Align write if necessary by performing a read-modify-write cycle.
1605      * Pad qiov with the read parts and be sure to have a tracked request not
1606      * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
1607      */
1608     tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);
1609 
1610     if (!qiov) {
1611         ret = bdrv_co_do_zero_pwritev(child, offset, bytes, flags, &req);
1612         goto out;
1613     }
1614 
1615     if (offset & (align - 1)) {
1616         QEMUIOVector head_qiov;
1617         struct iovec head_iov;
1618 
1619         mark_request_serialising(&req, align);
1620         wait_serialising_requests(&req);
1621 
1622         head_buf = qemu_blockalign(bs, align);
1623         head_iov = (struct iovec) {
1624             .iov_base   = head_buf,
1625             .iov_len    = align,
1626         };
1627         qemu_iovec_init_external(&head_qiov, &head_iov, 1);
1628 
1629         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1630         ret = bdrv_aligned_preadv(child, &req, offset & ~(align - 1), align,
1631                                   align, &head_qiov, 0);
1632         if (ret < 0) {
1633             goto fail;
1634         }
1635         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1636 
1637         qemu_iovec_init(&local_qiov, qiov->niov + 2);
1638         qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
1639         qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1640         use_local_qiov = true;
1641 
1642         bytes += offset & (align - 1);
1643         offset = offset & ~(align - 1);
1644 
1645         /* We have read the tail already if the request is smaller
1646          * than one aligned block.
1647          */
1648         if (bytes < align) {
1649             qemu_iovec_add(&local_qiov, head_buf + bytes, align - bytes);
1650             bytes = align;
1651         }
1652     }
1653 
1654     if ((offset + bytes) & (align - 1)) {
1655         QEMUIOVector tail_qiov;
1656         struct iovec tail_iov;
1657         size_t tail_bytes;
1658         bool waited;
1659 
1660         mark_request_serialising(&req, align);
1661         waited = wait_serialising_requests(&req);
1662         assert(!waited || !use_local_qiov);
1663 
1664         tail_buf = qemu_blockalign(bs, align);
1665         tail_iov = (struct iovec) {
1666             .iov_base   = tail_buf,
1667             .iov_len    = align,
1668         };
1669         qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);
1670 
1671         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1672         ret = bdrv_aligned_preadv(child, &req, (offset + bytes) & ~(align - 1),
1673                                   align, align, &tail_qiov, 0);
1674         if (ret < 0) {
1675             goto fail;
1676         }
1677         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1678 
1679         if (!use_local_qiov) {
1680             qemu_iovec_init(&local_qiov, qiov->niov + 1);
1681             qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1682             use_local_qiov = true;
1683         }
1684 
1685         tail_bytes = (offset + bytes) & (align - 1);
1686         qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
1687 
1688         bytes = ROUND_UP(bytes, align);
1689     }
1690 
1691     ret = bdrv_aligned_pwritev(child, &req, offset, bytes, align,
1692                                use_local_qiov ? &local_qiov : qiov,
1693                                flags);
1694 
1695 fail:
1696 
1697     if (use_local_qiov) {
1698         qemu_iovec_destroy(&local_qiov);
1699     }
1700     qemu_vfree(head_buf);
1701     qemu_vfree(tail_buf);
1702 out:
1703     tracked_request_end(&req);
1704     bdrv_dec_in_flight(bs);
1705     return ret;
1706 }
1707 
1708 static int coroutine_fn bdrv_co_do_writev(BdrvChild *child,
1709     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
1710     BdrvRequestFlags flags)
1711 {
1712     if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
1713         return -EINVAL;
1714     }
1715 
1716     return bdrv_co_pwritev(child, sector_num << BDRV_SECTOR_BITS,
1717                            nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
1718 }
1719 
1720 int coroutine_fn bdrv_co_writev(BdrvChild *child, int64_t sector_num,
1721     int nb_sectors, QEMUIOVector *qiov)
1722 {
1723     return bdrv_co_do_writev(child, sector_num, nb_sectors, qiov, 0);
1724 }
1725 
1726 int coroutine_fn bdrv_co_pwrite_zeroes(BdrvChild *child, int64_t offset,
1727                                        int bytes, BdrvRequestFlags flags)
1728 {
1729     trace_bdrv_co_pwrite_zeroes(child->bs, offset, bytes, flags);
1730 
1731     if (!(child->bs->open_flags & BDRV_O_UNMAP)) {
1732         flags &= ~BDRV_REQ_MAY_UNMAP;
1733     }
1734 
1735     return bdrv_co_pwritev(child, offset, bytes, NULL,
1736                            BDRV_REQ_ZERO_WRITE | flags);
1737 }
1738 
1739 /*
1740  * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
1741  */
1742 int bdrv_flush_all(void)
1743 {
1744     BdrvNextIterator it;
1745     BlockDriverState *bs = NULL;
1746     int result = 0;
1747 
1748     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
1749         AioContext *aio_context = bdrv_get_aio_context(bs);
1750         int ret;
1751 
1752         aio_context_acquire(aio_context);
1753         ret = bdrv_flush(bs);
1754         if (ret < 0 && !result) {
1755             result = ret;
1756         }
1757         aio_context_release(aio_context);
1758     }
1759 
1760     return result;
1761 }
1762 
1763 
1764 typedef struct BdrvCoBlockStatusData {
1765     BlockDriverState *bs;
1766     BlockDriverState *base;
1767     bool want_zero;
1768     int64_t offset;
1769     int64_t bytes;
1770     int64_t *pnum;
1771     int64_t *map;
1772     BlockDriverState **file;
1773     int ret;
1774     bool done;
1775 } BdrvCoBlockStatusData;
1776 
1777 int64_t coroutine_fn bdrv_co_get_block_status_from_file(BlockDriverState *bs,
1778                                                         int64_t sector_num,
1779                                                         int nb_sectors,
1780                                                         int *pnum,
1781                                                         BlockDriverState **file)
1782 {
1783     assert(bs->file && bs->file->bs);
1784     *pnum = nb_sectors;
1785     *file = bs->file->bs;
1786     return BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID |
1787            (sector_num << BDRV_SECTOR_BITS);
1788 }
1789 
1790 int64_t coroutine_fn bdrv_co_get_block_status_from_backing(BlockDriverState *bs,
1791                                                            int64_t sector_num,
1792                                                            int nb_sectors,
1793                                                            int *pnum,
1794                                                            BlockDriverState **file)
1795 {
1796     assert(bs->backing && bs->backing->bs);
1797     *pnum = nb_sectors;
1798     *file = bs->backing->bs;
1799     return BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID |
1800            (sector_num << BDRV_SECTOR_BITS);
1801 }
1802 
1803 /*
1804  * Returns the allocation status of the specified sectors.
1805  * Drivers not implementing the functionality are assumed to not support
1806  * backing files, hence all their sectors are reported as allocated.
1807  *
1808  * If 'want_zero' is true, the caller is querying for mapping purposes,
1809  * and the result should include BDRV_BLOCK_OFFSET_VALID and
1810  * BDRV_BLOCK_ZERO where possible; otherwise, the result may omit those
1811  * bits particularly if it allows for a larger value in 'pnum'.
1812  *
1813  * If 'offset' is beyond the end of the disk image the return value is
1814  * BDRV_BLOCK_EOF and 'pnum' is set to 0.
1815  *
1816  * 'bytes' is the max value 'pnum' should be set to.  If bytes goes
1817  * beyond the end of the disk image it will be clamped; if 'pnum' is set to
1818  * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
1819  *
1820  * 'pnum' is set to the number of bytes (including and immediately
1821  * following the specified offset) that are easily known to be in the
1822  * same allocated/unallocated state.  Note that a second call starting
1823  * at the original offset plus returned pnum may have the same status.
1824  * The returned value is non-zero on success except at end-of-file.
1825  *
1826  * Returns negative errno on failure.  Otherwise, if the
1827  * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
1828  * set to the host mapping and BDS corresponding to the guest offset.
1829  */
1830 static int coroutine_fn bdrv_co_block_status(BlockDriverState *bs,
1831                                              bool want_zero,
1832                                              int64_t offset, int64_t bytes,
1833                                              int64_t *pnum, int64_t *map,
1834                                              BlockDriverState **file)
1835 {
1836     int64_t total_size;
1837     int64_t n; /* bytes */
1838     int ret;
1839     int64_t local_map = 0;
1840     BlockDriverState *local_file = NULL;
1841     int64_t aligned_offset, aligned_bytes;
1842     uint32_t align;
1843 
1844     assert(pnum);
1845     *pnum = 0;
1846     total_size = bdrv_getlength(bs);
1847     if (total_size < 0) {
1848         ret = total_size;
1849         goto early_out;
1850     }
1851 
1852     if (offset >= total_size) {
1853         ret = BDRV_BLOCK_EOF;
1854         goto early_out;
1855     }
1856     if (!bytes) {
1857         ret = 0;
1858         goto early_out;
1859     }
1860 
1861     n = total_size - offset;
1862     if (n < bytes) {
1863         bytes = n;
1864     }
1865 
1866     if (!bs->drv->bdrv_co_get_block_status) {
1867         *pnum = bytes;
1868         ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
1869         if (offset + bytes == total_size) {
1870             ret |= BDRV_BLOCK_EOF;
1871         }
1872         if (bs->drv->protocol_name) {
1873             ret |= BDRV_BLOCK_OFFSET_VALID;
1874             local_map = offset;
1875             local_file = bs;
1876         }
1877         goto early_out;
1878     }
1879 
1880     bdrv_inc_in_flight(bs);
1881 
1882     /* Round out to request_alignment boundaries */
1883     /* TODO: until we have a byte-based driver callback, we also have to
1884      * round out to sectors, even if that is bigger than request_alignment */
1885     align = MAX(bs->bl.request_alignment, BDRV_SECTOR_SIZE);
1886     aligned_offset = QEMU_ALIGN_DOWN(offset, align);
1887     aligned_bytes = ROUND_UP(offset + bytes, align) - aligned_offset;
1888 
1889     {
1890         int count; /* sectors */
1891         int64_t longret;
1892 
1893         assert(QEMU_IS_ALIGNED(aligned_offset | aligned_bytes,
1894                                BDRV_SECTOR_SIZE));
1895         /*
1896          * The contract allows us to return pnum smaller than bytes, even
1897          * if the next query would see the same status; we truncate the
1898          * request to avoid overflowing the driver's 32-bit interface.
1899          */
1900         longret = bs->drv->bdrv_co_get_block_status(
1901             bs, aligned_offset >> BDRV_SECTOR_BITS,
1902             MIN(INT_MAX, aligned_bytes) >> BDRV_SECTOR_BITS, &count,
1903             &local_file);
1904         if (longret < 0) {
1905             assert(INT_MIN <= longret);
1906             ret = longret;
1907             goto out;
1908         }
1909         if (longret & BDRV_BLOCK_OFFSET_VALID) {
1910             local_map = longret & BDRV_BLOCK_OFFSET_MASK;
1911         }
1912         ret = longret & ~BDRV_BLOCK_OFFSET_MASK;
1913         *pnum = count * BDRV_SECTOR_SIZE;
1914     }
1915 
1916     /*
1917      * The driver's result must be a multiple of request_alignment.
1918      * Clamp pnum and adjust map to original request.
1919      */
1920     assert(QEMU_IS_ALIGNED(*pnum, align) && align > offset - aligned_offset);
1921     *pnum -= offset - aligned_offset;
1922     if (*pnum > bytes) {
1923         *pnum = bytes;
1924     }
1925     if (ret & BDRV_BLOCK_OFFSET_VALID) {
1926         local_map += offset - aligned_offset;
1927     }
1928 
1929     if (ret & BDRV_BLOCK_RAW) {
1930         assert(ret & BDRV_BLOCK_OFFSET_VALID && local_file);
1931         ret = bdrv_co_block_status(local_file, want_zero, local_map,
1932                                    *pnum, pnum, &local_map, &local_file);
1933         goto out;
1934     }
1935 
1936     if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
1937         ret |= BDRV_BLOCK_ALLOCATED;
1938     } else if (want_zero) {
1939         if (bdrv_unallocated_blocks_are_zero(bs)) {
1940             ret |= BDRV_BLOCK_ZERO;
1941         } else if (bs->backing) {
1942             BlockDriverState *bs2 = bs->backing->bs;
1943             int64_t size2 = bdrv_getlength(bs2);
1944 
1945             if (size2 >= 0 && offset >= size2) {
1946                 ret |= BDRV_BLOCK_ZERO;
1947             }
1948         }
1949     }
1950 
1951     if (want_zero && local_file && local_file != bs &&
1952         (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
1953         (ret & BDRV_BLOCK_OFFSET_VALID)) {
1954         int64_t file_pnum;
1955         int ret2;
1956 
1957         ret2 = bdrv_co_block_status(local_file, want_zero, local_map,
1958                                     *pnum, &file_pnum, NULL, NULL);
1959         if (ret2 >= 0) {
1960             /* Ignore errors.  This is just providing extra information, it
1961              * is useful but not necessary.
1962              */
1963             if (ret2 & BDRV_BLOCK_EOF &&
1964                 (!file_pnum || ret2 & BDRV_BLOCK_ZERO)) {
1965                 /*
1966                  * It is valid for the format block driver to read
1967                  * beyond the end of the underlying file's current
1968                  * size; such areas read as zero.
1969                  */
1970                 ret |= BDRV_BLOCK_ZERO;
1971             } else {
1972                 /* Limit request to the range reported by the protocol driver */
1973                 *pnum = file_pnum;
1974                 ret |= (ret2 & BDRV_BLOCK_ZERO);
1975             }
1976         }
1977     }
1978 
1979 out:
1980     bdrv_dec_in_flight(bs);
1981     if (ret >= 0 && offset + *pnum == total_size) {
1982         ret |= BDRV_BLOCK_EOF;
1983     }
1984 early_out:
1985     if (file) {
1986         *file = local_file;
1987     }
1988     if (map) {
1989         *map = local_map;
1990     }
1991     return ret;
1992 }
1993 
1994 static int coroutine_fn bdrv_co_block_status_above(BlockDriverState *bs,
1995                                                    BlockDriverState *base,
1996                                                    bool want_zero,
1997                                                    int64_t offset,
1998                                                    int64_t bytes,
1999                                                    int64_t *pnum,
2000                                                    int64_t *map,
2001                                                    BlockDriverState **file)
2002 {
2003     BlockDriverState *p;
2004     int ret = 0;
2005     bool first = true;
2006 
2007     assert(bs != base);
2008     for (p = bs; p != base; p = backing_bs(p)) {
2009         ret = bdrv_co_block_status(p, want_zero, offset, bytes, pnum, map,
2010                                    file);
2011         if (ret < 0) {
2012             break;
2013         }
2014         if (ret & BDRV_BLOCK_ZERO && ret & BDRV_BLOCK_EOF && !first) {
2015             /*
2016              * Reading beyond the end of the file continues to read
2017              * zeroes, but we can only widen the result to the
2018              * unallocated length we learned from an earlier
2019              * iteration.
2020              */
2021             *pnum = bytes;
2022         }
2023         if (ret & (BDRV_BLOCK_ZERO | BDRV_BLOCK_DATA)) {
2024             break;
2025         }
2026         /* [offset, pnum] unallocated on this layer, which could be only
2027          * the first part of [offset, bytes].  */
2028         bytes = MIN(bytes, *pnum);
2029         first = false;
2030     }
2031     return ret;
2032 }
2033 
2034 /* Coroutine wrapper for bdrv_block_status_above() */
2035 static void coroutine_fn bdrv_block_status_above_co_entry(void *opaque)
2036 {
2037     BdrvCoBlockStatusData *data = opaque;
2038 
2039     data->ret = bdrv_co_block_status_above(data->bs, data->base,
2040                                            data->want_zero,
2041                                            data->offset, data->bytes,
2042                                            data->pnum, data->map, data->file);
2043     data->done = true;
2044 }
2045 
2046 /*
2047  * Synchronous wrapper around bdrv_co_block_status_above().
2048  *
2049  * See bdrv_co_block_status_above() for details.
2050  */
2051 static int bdrv_common_block_status_above(BlockDriverState *bs,
2052                                           BlockDriverState *base,
2053                                           bool want_zero, int64_t offset,
2054                                           int64_t bytes, int64_t *pnum,
2055                                           int64_t *map,
2056                                           BlockDriverState **file)
2057 {
2058     Coroutine *co;
2059     BdrvCoBlockStatusData data = {
2060         .bs = bs,
2061         .base = base,
2062         .want_zero = want_zero,
2063         .offset = offset,
2064         .bytes = bytes,
2065         .pnum = pnum,
2066         .map = map,
2067         .file = file,
2068         .done = false,
2069     };
2070 
2071     if (qemu_in_coroutine()) {
2072         /* Fast-path if already in coroutine context */
2073         bdrv_block_status_above_co_entry(&data);
2074     } else {
2075         co = qemu_coroutine_create(bdrv_block_status_above_co_entry, &data);
2076         bdrv_coroutine_enter(bs, co);
2077         BDRV_POLL_WHILE(bs, !data.done);
2078     }
2079     return data.ret;
2080 }
2081 
2082 int bdrv_block_status_above(BlockDriverState *bs, BlockDriverState *base,
2083                             int64_t offset, int64_t bytes, int64_t *pnum,
2084                             int64_t *map, BlockDriverState **file)
2085 {
2086     return bdrv_common_block_status_above(bs, base, true, offset, bytes,
2087                                           pnum, map, file);
2088 }
2089 
2090 int bdrv_block_status(BlockDriverState *bs, int64_t offset, int64_t bytes,
2091                       int64_t *pnum, int64_t *map, BlockDriverState **file)
2092 {
2093     return bdrv_block_status_above(bs, backing_bs(bs),
2094                                    offset, bytes, pnum, map, file);
2095 }
2096 
2097 int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t offset,
2098                                    int64_t bytes, int64_t *pnum)
2099 {
2100     int ret;
2101     int64_t dummy;
2102 
2103     ret = bdrv_common_block_status_above(bs, backing_bs(bs), false, offset,
2104                                          bytes, pnum ? pnum : &dummy, NULL,
2105                                          NULL);
2106     if (ret < 0) {
2107         return ret;
2108     }
2109     return !!(ret & BDRV_BLOCK_ALLOCATED);
2110 }
2111 
2112 /*
2113  * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2114  *
2115  * Return true if (a prefix of) the given range is allocated in any image
2116  * between BASE and TOP (inclusive).  BASE can be NULL to check if the given
2117  * offset is allocated in any image of the chain.  Return false otherwise,
2118  * or negative errno on failure.
2119  *
2120  * 'pnum' is set to the number of bytes (including and immediately
2121  * following the specified offset) that are known to be in the same
2122  * allocated/unallocated state.  Note that a subsequent call starting
2123  * at 'offset + *pnum' may return the same allocation status (in other
2124  * words, the result is not necessarily the maximum possible range);
2125  * but 'pnum' will only be 0 when end of file is reached.
2126  *
2127  */
2128 int bdrv_is_allocated_above(BlockDriverState *top,
2129                             BlockDriverState *base,
2130                             int64_t offset, int64_t bytes, int64_t *pnum)
2131 {
2132     BlockDriverState *intermediate;
2133     int ret;
2134     int64_t n = bytes;
2135 
2136     intermediate = top;
2137     while (intermediate && intermediate != base) {
2138         int64_t pnum_inter;
2139         int64_t size_inter;
2140 
2141         ret = bdrv_is_allocated(intermediate, offset, bytes, &pnum_inter);
2142         if (ret < 0) {
2143             return ret;
2144         }
2145         if (ret) {
2146             *pnum = pnum_inter;
2147             return 1;
2148         }
2149 
2150         size_inter = bdrv_getlength(intermediate);
2151         if (size_inter < 0) {
2152             return size_inter;
2153         }
2154         if (n > pnum_inter &&
2155             (intermediate == top || offset + pnum_inter < size_inter)) {
2156             n = pnum_inter;
2157         }
2158 
2159         intermediate = backing_bs(intermediate);
2160     }
2161 
2162     *pnum = n;
2163     return 0;
2164 }
2165 
2166 typedef struct BdrvVmstateCo {
2167     BlockDriverState    *bs;
2168     QEMUIOVector        *qiov;
2169     int64_t             pos;
2170     bool                is_read;
2171     int                 ret;
2172 } BdrvVmstateCo;
2173 
2174 static int coroutine_fn
2175 bdrv_co_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos,
2176                    bool is_read)
2177 {
2178     BlockDriver *drv = bs->drv;
2179     int ret = -ENOTSUP;
2180 
2181     bdrv_inc_in_flight(bs);
2182 
2183     if (!drv) {
2184         ret = -ENOMEDIUM;
2185     } else if (drv->bdrv_load_vmstate) {
2186         if (is_read) {
2187             ret = drv->bdrv_load_vmstate(bs, qiov, pos);
2188         } else {
2189             ret = drv->bdrv_save_vmstate(bs, qiov, pos);
2190         }
2191     } else if (bs->file) {
2192         ret = bdrv_co_rw_vmstate(bs->file->bs, qiov, pos, is_read);
2193     }
2194 
2195     bdrv_dec_in_flight(bs);
2196     return ret;
2197 }
2198 
2199 static void coroutine_fn bdrv_co_rw_vmstate_entry(void *opaque)
2200 {
2201     BdrvVmstateCo *co = opaque;
2202     co->ret = bdrv_co_rw_vmstate(co->bs, co->qiov, co->pos, co->is_read);
2203 }
2204 
2205 static inline int
2206 bdrv_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos,
2207                 bool is_read)
2208 {
2209     if (qemu_in_coroutine()) {
2210         return bdrv_co_rw_vmstate(bs, qiov, pos, is_read);
2211     } else {
2212         BdrvVmstateCo data = {
2213             .bs         = bs,
2214             .qiov       = qiov,
2215             .pos        = pos,
2216             .is_read    = is_read,
2217             .ret        = -EINPROGRESS,
2218         };
2219         Coroutine *co = qemu_coroutine_create(bdrv_co_rw_vmstate_entry, &data);
2220 
2221         bdrv_coroutine_enter(bs, co);
2222         BDRV_POLL_WHILE(bs, data.ret == -EINPROGRESS);
2223         return data.ret;
2224     }
2225 }
2226 
2227 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2228                       int64_t pos, int size)
2229 {
2230     QEMUIOVector qiov;
2231     struct iovec iov = {
2232         .iov_base   = (void *) buf,
2233         .iov_len    = size,
2234     };
2235     int ret;
2236 
2237     qemu_iovec_init_external(&qiov, &iov, 1);
2238 
2239     ret = bdrv_writev_vmstate(bs, &qiov, pos);
2240     if (ret < 0) {
2241         return ret;
2242     }
2243 
2244     return size;
2245 }
2246 
2247 int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2248 {
2249     return bdrv_rw_vmstate(bs, qiov, pos, false);
2250 }
2251 
2252 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2253                       int64_t pos, int size)
2254 {
2255     QEMUIOVector qiov;
2256     struct iovec iov = {
2257         .iov_base   = buf,
2258         .iov_len    = size,
2259     };
2260     int ret;
2261 
2262     qemu_iovec_init_external(&qiov, &iov, 1);
2263     ret = bdrv_readv_vmstate(bs, &qiov, pos);
2264     if (ret < 0) {
2265         return ret;
2266     }
2267 
2268     return size;
2269 }
2270 
2271 int bdrv_readv_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2272 {
2273     return bdrv_rw_vmstate(bs, qiov, pos, true);
2274 }
2275 
2276 /**************************************************************/
2277 /* async I/Os */
2278 
2279 void bdrv_aio_cancel(BlockAIOCB *acb)
2280 {
2281     qemu_aio_ref(acb);
2282     bdrv_aio_cancel_async(acb);
2283     while (acb->refcnt > 1) {
2284         if (acb->aiocb_info->get_aio_context) {
2285             aio_poll(acb->aiocb_info->get_aio_context(acb), true);
2286         } else if (acb->bs) {
2287             /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2288              * assert that we're not using an I/O thread.  Thread-safe
2289              * code should use bdrv_aio_cancel_async exclusively.
2290              */
2291             assert(bdrv_get_aio_context(acb->bs) == qemu_get_aio_context());
2292             aio_poll(bdrv_get_aio_context(acb->bs), true);
2293         } else {
2294             abort();
2295         }
2296     }
2297     qemu_aio_unref(acb);
2298 }
2299 
2300 /* Async version of aio cancel. The caller is not blocked if the acb implements
2301  * cancel_async, otherwise we do nothing and let the request normally complete.
2302  * In either case the completion callback must be called. */
2303 void bdrv_aio_cancel_async(BlockAIOCB *acb)
2304 {
2305     if (acb->aiocb_info->cancel_async) {
2306         acb->aiocb_info->cancel_async(acb);
2307     }
2308 }
2309 
2310 /**************************************************************/
2311 /* Coroutine block device emulation */
2312 
2313 typedef struct FlushCo {
2314     BlockDriverState *bs;
2315     int ret;
2316 } FlushCo;
2317 
2318 
2319 static void coroutine_fn bdrv_flush_co_entry(void *opaque)
2320 {
2321     FlushCo *rwco = opaque;
2322 
2323     rwco->ret = bdrv_co_flush(rwco->bs);
2324 }
2325 
2326 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
2327 {
2328     int current_gen;
2329     int ret = 0;
2330 
2331     bdrv_inc_in_flight(bs);
2332 
2333     if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||
2334         bdrv_is_sg(bs)) {
2335         goto early_exit;
2336     }
2337 
2338     qemu_co_mutex_lock(&bs->reqs_lock);
2339     current_gen = atomic_read(&bs->write_gen);
2340 
2341     /* Wait until any previous flushes are completed */
2342     while (bs->active_flush_req) {
2343         qemu_co_queue_wait(&bs->flush_queue, &bs->reqs_lock);
2344     }
2345 
2346     /* Flushes reach this point in nondecreasing current_gen order.  */
2347     bs->active_flush_req = true;
2348     qemu_co_mutex_unlock(&bs->reqs_lock);
2349 
2350     /* Write back all layers by calling one driver function */
2351     if (bs->drv->bdrv_co_flush) {
2352         ret = bs->drv->bdrv_co_flush(bs);
2353         goto out;
2354     }
2355 
2356     /* Write back cached data to the OS even with cache=unsafe */
2357     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
2358     if (bs->drv->bdrv_co_flush_to_os) {
2359         ret = bs->drv->bdrv_co_flush_to_os(bs);
2360         if (ret < 0) {
2361             goto out;
2362         }
2363     }
2364 
2365     /* But don't actually force it to the disk with cache=unsafe */
2366     if (bs->open_flags & BDRV_O_NO_FLUSH) {
2367         goto flush_parent;
2368     }
2369 
2370     /* Check if we really need to flush anything */
2371     if (bs->flushed_gen == current_gen) {
2372         goto flush_parent;
2373     }
2374 
2375     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
2376     if (bs->drv->bdrv_co_flush_to_disk) {
2377         ret = bs->drv->bdrv_co_flush_to_disk(bs);
2378     } else if (bs->drv->bdrv_aio_flush) {
2379         BlockAIOCB *acb;
2380         CoroutineIOCompletion co = {
2381             .coroutine = qemu_coroutine_self(),
2382         };
2383 
2384         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
2385         if (acb == NULL) {
2386             ret = -EIO;
2387         } else {
2388             qemu_coroutine_yield();
2389             ret = co.ret;
2390         }
2391     } else {
2392         /*
2393          * Some block drivers always operate in either writethrough or unsafe
2394          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2395          * know how the server works (because the behaviour is hardcoded or
2396          * depends on server-side configuration), so we can't ensure that
2397          * everything is safe on disk. Returning an error doesn't work because
2398          * that would break guests even if the server operates in writethrough
2399          * mode.
2400          *
2401          * Let's hope the user knows what he's doing.
2402          */
2403         ret = 0;
2404     }
2405 
2406     if (ret < 0) {
2407         goto out;
2408     }
2409 
2410     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
2411      * in the case of cache=unsafe, so there are no useless flushes.
2412      */
2413 flush_parent:
2414     ret = bs->file ? bdrv_co_flush(bs->file->bs) : 0;
2415 out:
2416     /* Notify any pending flushes that we have completed */
2417     if (ret == 0) {
2418         bs->flushed_gen = current_gen;
2419     }
2420 
2421     qemu_co_mutex_lock(&bs->reqs_lock);
2422     bs->active_flush_req = false;
2423     /* Return value is ignored - it's ok if wait queue is empty */
2424     qemu_co_queue_next(&bs->flush_queue);
2425     qemu_co_mutex_unlock(&bs->reqs_lock);
2426 
2427 early_exit:
2428     bdrv_dec_in_flight(bs);
2429     return ret;
2430 }
2431 
2432 int bdrv_flush(BlockDriverState *bs)
2433 {
2434     Coroutine *co;
2435     FlushCo flush_co = {
2436         .bs = bs,
2437         .ret = NOT_DONE,
2438     };
2439 
2440     if (qemu_in_coroutine()) {
2441         /* Fast-path if already in coroutine context */
2442         bdrv_flush_co_entry(&flush_co);
2443     } else {
2444         co = qemu_coroutine_create(bdrv_flush_co_entry, &flush_co);
2445         bdrv_coroutine_enter(bs, co);
2446         BDRV_POLL_WHILE(bs, flush_co.ret == NOT_DONE);
2447     }
2448 
2449     return flush_co.ret;
2450 }
2451 
2452 typedef struct DiscardCo {
2453     BlockDriverState *bs;
2454     int64_t offset;
2455     int bytes;
2456     int ret;
2457 } DiscardCo;
2458 static void coroutine_fn bdrv_pdiscard_co_entry(void *opaque)
2459 {
2460     DiscardCo *rwco = opaque;
2461 
2462     rwco->ret = bdrv_co_pdiscard(rwco->bs, rwco->offset, rwco->bytes);
2463 }
2464 
2465 int coroutine_fn bdrv_co_pdiscard(BlockDriverState *bs, int64_t offset,
2466                                   int bytes)
2467 {
2468     BdrvTrackedRequest req;
2469     int max_pdiscard, ret;
2470     int head, tail, align;
2471 
2472     if (!bs->drv) {
2473         return -ENOMEDIUM;
2474     }
2475 
2476     if (bdrv_has_readonly_bitmaps(bs)) {
2477         return -EPERM;
2478     }
2479 
2480     ret = bdrv_check_byte_request(bs, offset, bytes);
2481     if (ret < 0) {
2482         return ret;
2483     } else if (bs->read_only) {
2484         return -EPERM;
2485     }
2486     assert(!(bs->open_flags & BDRV_O_INACTIVE));
2487 
2488     /* Do nothing if disabled.  */
2489     if (!(bs->open_flags & BDRV_O_UNMAP)) {
2490         return 0;
2491     }
2492 
2493     if (!bs->drv->bdrv_co_pdiscard && !bs->drv->bdrv_aio_pdiscard) {
2494         return 0;
2495     }
2496 
2497     /* Discard is advisory, but some devices track and coalesce
2498      * unaligned requests, so we must pass everything down rather than
2499      * round here.  Still, most devices will just silently ignore
2500      * unaligned requests (by returning -ENOTSUP), so we must fragment
2501      * the request accordingly.  */
2502     align = MAX(bs->bl.pdiscard_alignment, bs->bl.request_alignment);
2503     assert(align % bs->bl.request_alignment == 0);
2504     head = offset % align;
2505     tail = (offset + bytes) % align;
2506 
2507     bdrv_inc_in_flight(bs);
2508     tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_DISCARD);
2509 
2510     ret = notifier_with_return_list_notify(&bs->before_write_notifiers, &req);
2511     if (ret < 0) {
2512         goto out;
2513     }
2514 
2515     max_pdiscard = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_pdiscard, INT_MAX),
2516                                    align);
2517     assert(max_pdiscard >= bs->bl.request_alignment);
2518 
2519     while (bytes > 0) {
2520         int num = bytes;
2521 
2522         if (head) {
2523             /* Make small requests to get to alignment boundaries. */
2524             num = MIN(bytes, align - head);
2525             if (!QEMU_IS_ALIGNED(num, bs->bl.request_alignment)) {
2526                 num %= bs->bl.request_alignment;
2527             }
2528             head = (head + num) % align;
2529             assert(num < max_pdiscard);
2530         } else if (tail) {
2531             if (num > align) {
2532                 /* Shorten the request to the last aligned cluster.  */
2533                 num -= tail;
2534             } else if (!QEMU_IS_ALIGNED(tail, bs->bl.request_alignment) &&
2535                        tail > bs->bl.request_alignment) {
2536                 tail %= bs->bl.request_alignment;
2537                 num -= tail;
2538             }
2539         }
2540         /* limit request size */
2541         if (num > max_pdiscard) {
2542             num = max_pdiscard;
2543         }
2544 
2545         if (bs->drv->bdrv_co_pdiscard) {
2546             ret = bs->drv->bdrv_co_pdiscard(bs, offset, num);
2547         } else {
2548             BlockAIOCB *acb;
2549             CoroutineIOCompletion co = {
2550                 .coroutine = qemu_coroutine_self(),
2551             };
2552 
2553             acb = bs->drv->bdrv_aio_pdiscard(bs, offset, num,
2554                                              bdrv_co_io_em_complete, &co);
2555             if (acb == NULL) {
2556                 ret = -EIO;
2557                 goto out;
2558             } else {
2559                 qemu_coroutine_yield();
2560                 ret = co.ret;
2561             }
2562         }
2563         if (ret && ret != -ENOTSUP) {
2564             goto out;
2565         }
2566 
2567         offset += num;
2568         bytes -= num;
2569     }
2570     ret = 0;
2571 out:
2572     atomic_inc(&bs->write_gen);
2573     bdrv_set_dirty(bs, req.offset, req.bytes);
2574     tracked_request_end(&req);
2575     bdrv_dec_in_flight(bs);
2576     return ret;
2577 }
2578 
2579 int bdrv_pdiscard(BlockDriverState *bs, int64_t offset, int bytes)
2580 {
2581     Coroutine *co;
2582     DiscardCo rwco = {
2583         .bs = bs,
2584         .offset = offset,
2585         .bytes = bytes,
2586         .ret = NOT_DONE,
2587     };
2588 
2589     if (qemu_in_coroutine()) {
2590         /* Fast-path if already in coroutine context */
2591         bdrv_pdiscard_co_entry(&rwco);
2592     } else {
2593         co = qemu_coroutine_create(bdrv_pdiscard_co_entry, &rwco);
2594         bdrv_coroutine_enter(bs, co);
2595         BDRV_POLL_WHILE(bs, rwco.ret == NOT_DONE);
2596     }
2597 
2598     return rwco.ret;
2599 }
2600 
2601 int bdrv_co_ioctl(BlockDriverState *bs, int req, void *buf)
2602 {
2603     BlockDriver *drv = bs->drv;
2604     CoroutineIOCompletion co = {
2605         .coroutine = qemu_coroutine_self(),
2606     };
2607     BlockAIOCB *acb;
2608 
2609     bdrv_inc_in_flight(bs);
2610     if (!drv || (!drv->bdrv_aio_ioctl && !drv->bdrv_co_ioctl)) {
2611         co.ret = -ENOTSUP;
2612         goto out;
2613     }
2614 
2615     if (drv->bdrv_co_ioctl) {
2616         co.ret = drv->bdrv_co_ioctl(bs, req, buf);
2617     } else {
2618         acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
2619         if (!acb) {
2620             co.ret = -ENOTSUP;
2621             goto out;
2622         }
2623         qemu_coroutine_yield();
2624     }
2625 out:
2626     bdrv_dec_in_flight(bs);
2627     return co.ret;
2628 }
2629 
2630 void *qemu_blockalign(BlockDriverState *bs, size_t size)
2631 {
2632     return qemu_memalign(bdrv_opt_mem_align(bs), size);
2633 }
2634 
2635 void *qemu_blockalign0(BlockDriverState *bs, size_t size)
2636 {
2637     return memset(qemu_blockalign(bs, size), 0, size);
2638 }
2639 
2640 void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
2641 {
2642     size_t align = bdrv_opt_mem_align(bs);
2643 
2644     /* Ensure that NULL is never returned on success */
2645     assert(align > 0);
2646     if (size == 0) {
2647         size = align;
2648     }
2649 
2650     return qemu_try_memalign(align, size);
2651 }
2652 
2653 void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
2654 {
2655     void *mem = qemu_try_blockalign(bs, size);
2656 
2657     if (mem) {
2658         memset(mem, 0, size);
2659     }
2660 
2661     return mem;
2662 }
2663 
2664 /*
2665  * Check if all memory in this vector is sector aligned.
2666  */
2667 bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
2668 {
2669     int i;
2670     size_t alignment = bdrv_min_mem_align(bs);
2671 
2672     for (i = 0; i < qiov->niov; i++) {
2673         if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
2674             return false;
2675         }
2676         if (qiov->iov[i].iov_len % alignment) {
2677             return false;
2678         }
2679     }
2680 
2681     return true;
2682 }
2683 
2684 void bdrv_add_before_write_notifier(BlockDriverState *bs,
2685                                     NotifierWithReturn *notifier)
2686 {
2687     notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
2688 }
2689 
2690 void bdrv_io_plug(BlockDriverState *bs)
2691 {
2692     BdrvChild *child;
2693 
2694     QLIST_FOREACH(child, &bs->children, next) {
2695         bdrv_io_plug(child->bs);
2696     }
2697 
2698     if (atomic_fetch_inc(&bs->io_plugged) == 0) {
2699         BlockDriver *drv = bs->drv;
2700         if (drv && drv->bdrv_io_plug) {
2701             drv->bdrv_io_plug(bs);
2702         }
2703     }
2704 }
2705 
2706 void bdrv_io_unplug(BlockDriverState *bs)
2707 {
2708     BdrvChild *child;
2709 
2710     assert(bs->io_plugged);
2711     if (atomic_fetch_dec(&bs->io_plugged) == 1) {
2712         BlockDriver *drv = bs->drv;
2713         if (drv && drv->bdrv_io_unplug) {
2714             drv->bdrv_io_unplug(bs);
2715         }
2716     }
2717 
2718     QLIST_FOREACH(child, &bs->children, next) {
2719         bdrv_io_unplug(child->bs);
2720     }
2721 }
2722