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