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