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