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