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