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