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