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