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