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