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