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