]> git.proxmox.com Git - mirror_qemu.git/blame - block/block-copy.c
include/block: Untangle inclusion loops
[mirror_qemu.git] / block / block-copy.c
CommitLineData
beb5f545
VSO
1/*
2 * block_copy API
3 *
4 * Copyright (C) 2013 Proxmox Server Solutions
5 * Copyright (c) 2019 Virtuozzo International GmbH.
6 *
7 * Authors:
8 * Dietmar Maurer (dietmar@proxmox.com)
9 * Vladimir Sementsov-Ogievskiy <vsementsov@virtuozzo.com>
10 *
11 * This work is licensed under the terms of the GNU GPL, version 2 or later.
12 * See the COPYING file in the top-level directory.
13 */
14
15#include "qemu/osdep.h"
16
17#include "trace.h"
18#include "qapi/error.h"
19#include "block/block-copy.h"
e2c1c34f
MA
20#include "block/block_int-io.h"
21#include "block/dirty-bitmap.h"
d088e6a4 22#include "block/reqlist.h"
beb5f545 23#include "sysemu/block-backend.h"
b3b7036a 24#include "qemu/units.h"
e2c1c34f 25#include "qemu/co-shared-resource.h"
4ce5dd3e 26#include "qemu/coroutine.h"
e2c1c34f 27#include "qemu/ratelimit.h"
4ce5dd3e 28#include "block/aio_task.h"
b518e9e9 29#include "qemu/error-report.h"
5df022cf 30#include "qemu/memalign.h"
b3b7036a
VSO
31
32#define BLOCK_COPY_MAX_COPY_RANGE (16 * MiB)
0e240245 33#define BLOCK_COPY_MAX_BUFFER (1 * MiB)
7f739d0e 34#define BLOCK_COPY_MAX_MEM (128 * MiB)
4ce5dd3e 35#define BLOCK_COPY_MAX_WORKERS 64
7e032df0 36#define BLOCK_COPY_SLICE_TIME 100000000ULL /* ns */
b518e9e9 37#define BLOCK_COPY_CLUSTER_SIZE_DEFAULT (1 << 16)
4ce5dd3e 38
05d5e12b
PB
39typedef enum {
40 COPY_READ_WRITE_CLUSTER,
41 COPY_READ_WRITE,
42 COPY_WRITE_ZEROES,
43 COPY_RANGE_SMALL,
44 COPY_RANGE_FULL
45} BlockCopyMethod;
46
4ce5dd3e
VSO
47static coroutine_fn int block_copy_task_entry(AioTask *task);
48
49typedef struct BlockCopyCallState {
d0c389d2 50 /* Fields initialized in block_copy_async() and never changed. */
3b8c2329
VSO
51 BlockCopyState *s;
52 int64_t offset;
53 int64_t bytes;
26be9d62
VSO
54 int max_workers;
55 int64_t max_chunk;
7e032df0 56 bool ignore_ratelimit;
de4641b4
VSO
57 BlockCopyAsyncCallbackFunc cb;
58 void *cb_opaque;
de4641b4
VSO
59 /* Coroutine where async block-copy is running */
60 Coroutine *co;
3b8c2329 61
d0c389d2 62 /* Fields whose state changes throughout the execution */
149009be 63 bool finished; /* atomic */
d0c389d2 64 QemuCoSleep sleep; /* TODO: protect API with a lock */
149009be 65 bool cancelled; /* atomic */
d0c389d2
EGE
66 /* To reference all call states from BlockCopyState */
67 QLIST_ENTRY(BlockCopyCallState) list;
3b8c2329 68
d0c389d2
EGE
69 /*
70 * Fields that report information about return values and erros.
71 * Protected by lock in BlockCopyState.
72 */
4ce5dd3e 73 bool error_is_read;
d0c389d2
EGE
74 /*
75 * @ret is set concurrently by tasks under mutex. Only set once by first
76 * failed task (and untouched if no task failed).
77 * After finishing (call_state->finished is true), it is not modified
78 * anymore and may be safely read without mutex.
79 */
80 int ret;
4ce5dd3e 81} BlockCopyCallState;
beb5f545 82
e9407785 83typedef struct BlockCopyTask {
4ce5dd3e
VSO
84 AioTask task;
85
d0c389d2
EGE
86 /*
87 * Fields initialized in block_copy_task_create()
88 * and never changed.
89 */
1348a657 90 BlockCopyState *s;
4ce5dd3e 91 BlockCopyCallState *call_state;
d0c389d2
EGE
92 /*
93 * @method can also be set again in the while loop of
94 * block_copy_dirty_clusters(), but it is never accessed concurrently
95 * because the only other function that reads it is
96 * block_copy_task_entry() and it is invoked afterwards in the same
97 * iteration.
98 */
05d5e12b 99 BlockCopyMethod method;
d0c389d2
EGE
100
101 /*
d088e6a4
VSO
102 * Generally, req is protected by lock in BlockCopyState, Still req.offset
103 * is only set on task creation, so may be read concurrently after creation.
104 * req.bytes is changed at most once, and need only protecting the case of
105 * parallel read while updating @bytes value in block_copy_task_shrink().
d0c389d2 106 */
d088e6a4 107 BlockReq req;
e9407785 108} BlockCopyTask;
397f4e9d 109
42ac2144
VSO
110static int64_t task_end(BlockCopyTask *task)
111{
d088e6a4 112 return task->req.offset + task->req.bytes;
42ac2144
VSO
113}
114
397f4e9d
VSO
115typedef struct BlockCopyState {
116 /*
117 * BdrvChild objects are not owned or managed by block-copy. They are
118 * provided by block-copy user and user is responsible for appropriate
119 * permissions on these children.
120 */
121 BdrvChild *source;
122 BdrvChild *target;
d0c389d2
EGE
123
124 /*
125 * Fields initialized in block_copy_state_new()
126 * and never changed.
127 */
397f4e9d 128 int64_t cluster_size;
05d5e12b 129 int64_t max_transfer;
397f4e9d 130 uint64_t len;
397f4e9d
VSO
131 BdrvRequestFlags write_flags;
132
d0c389d2
EGE
133 /*
134 * Fields whose state changes throughout the execution
135 * Protected by lock.
136 */
137 CoMutex lock;
138 int64_t in_flight_bytes;
139 BlockCopyMethod method;
d088e6a4 140 BlockReqList reqs;
d0c389d2 141 QLIST_HEAD(, BlockCopyCallState) calls;
397f4e9d
VSO
142 /*
143 * skip_unallocated:
144 *
145 * Used by sync=top jobs, which first scan the source node for unallocated
146 * areas and clear them in the copy_bitmap. During this process, the bitmap
147 * is thus not fully initialized: It may still have bits set for areas that
148 * are unallocated and should actually not be copied.
149 *
150 * This is indicated by skip_unallocated.
151 *
152 * In this case, block_copy() will query the source’s allocation status,
153 * skip unallocated regions, clear them in the copy_bitmap, and invoke
154 * block_copy_reset_unallocated() every time it does.
155 */
d0c389d2
EGE
156 bool skip_unallocated; /* atomic */
157 /* State fields that use a thread-safe API */
158 BdrvDirtyBitmap *copy_bitmap;
397f4e9d 159 ProgressMeter *progress;
397f4e9d 160 SharedResource *mem;
7e032df0 161 RateLimit rate_limit;
397f4e9d
VSO
162} BlockCopyState;
163
d0c389d2 164/* Called with lock held */
05d5e12b
PB
165static int64_t block_copy_chunk_size(BlockCopyState *s)
166{
167 switch (s->method) {
168 case COPY_READ_WRITE_CLUSTER:
169 return s->cluster_size;
170 case COPY_READ_WRITE:
171 case COPY_RANGE_SMALL:
172 return MIN(MAX(s->cluster_size, BLOCK_COPY_MAX_BUFFER),
173 s->max_transfer);
174 case COPY_RANGE_FULL:
175 return MIN(MAX(s->cluster_size, BLOCK_COPY_MAX_COPY_RANGE),
176 s->max_transfer);
177 default:
178 /* Cannot have COPY_WRITE_ZEROES here. */
179 abort();
180 }
181}
182
42ac2144
VSO
183/*
184 * Search for the first dirty area in offset/bytes range and create task at
185 * the beginning of it.
186 */
d0c389d2
EGE
187static coroutine_fn BlockCopyTask *
188block_copy_task_create(BlockCopyState *s, BlockCopyCallState *call_state,
189 int64_t offset, int64_t bytes)
a6ffe199 190{
42ac2144 191 BlockCopyTask *task;
05d5e12b 192 int64_t max_chunk;
f13e60a9 193
d0c389d2 194 QEMU_LOCK_GUARD(&s->lock);
05d5e12b 195 max_chunk = MIN_NON_ZERO(block_copy_chunk_size(s), call_state->max_chunk);
42ac2144
VSO
196 if (!bdrv_dirty_bitmap_next_dirty_area(s->copy_bitmap,
197 offset, offset + bytes,
26be9d62 198 max_chunk, &offset, &bytes))
42ac2144
VSO
199 {
200 return NULL;
201 }
202
7661a886
SR
203 assert(QEMU_IS_ALIGNED(offset, s->cluster_size));
204 bytes = QEMU_ALIGN_UP(bytes, s->cluster_size);
205
42ac2144 206 /* region is dirty, so no existent tasks possible in it */
d088e6a4 207 assert(!reqlist_find_conflict(&s->reqs, offset, bytes));
5332e5d2
VSO
208
209 bdrv_reset_dirty_bitmap(s->copy_bitmap, offset, bytes);
210 s->in_flight_bytes += bytes;
211
42ac2144 212 task = g_new(BlockCopyTask, 1);
1348a657 213 *task = (BlockCopyTask) {
4ce5dd3e 214 .task.func = block_copy_task_entry,
1348a657 215 .s = s,
4ce5dd3e 216 .call_state = call_state,
05d5e12b 217 .method = s->method,
1348a657 218 };
d088e6a4 219 reqlist_init_req(&s->reqs, &task->req, offset, bytes);
f13e60a9
VSO
220
221 return task;
a6ffe199
VSO
222}
223
5332e5d2 224/*
e9407785 225 * block_copy_task_shrink
5332e5d2 226 *
e9407785
VSO
227 * Drop the tail of the task to be handled later. Set dirty bits back and
228 * wake up all tasks waiting for us (may be some of them are not intersecting
229 * with shrunk task)
5332e5d2 230 */
1348a657 231static void coroutine_fn block_copy_task_shrink(BlockCopyTask *task,
e9407785 232 int64_t new_bytes)
a6ffe199 233{
d0c389d2 234 QEMU_LOCK_GUARD(&task->s->lock);
d088e6a4 235 if (new_bytes == task->req.bytes) {
5332e5d2
VSO
236 return;
237 }
238
d088e6a4 239 assert(new_bytes > 0 && new_bytes < task->req.bytes);
5332e5d2 240
d088e6a4 241 task->s->in_flight_bytes -= task->req.bytes - new_bytes;
1348a657 242 bdrv_set_dirty_bitmap(task->s->copy_bitmap,
d088e6a4
VSO
243 task->req.offset + new_bytes,
244 task->req.bytes - new_bytes);
5332e5d2 245
d088e6a4 246 reqlist_shrink_req(&task->req, new_bytes);
5332e5d2
VSO
247}
248
1348a657 249static void coroutine_fn block_copy_task_end(BlockCopyTask *task, int ret)
5332e5d2 250{
d0c389d2 251 QEMU_LOCK_GUARD(&task->s->lock);
d088e6a4 252 task->s->in_flight_bytes -= task->req.bytes;
5332e5d2 253 if (ret < 0) {
d088e6a4
VSO
254 bdrv_set_dirty_bitmap(task->s->copy_bitmap, task->req.offset,
255 task->req.bytes);
5332e5d2 256 }
201b4bb6
VSO
257 if (task->s->progress) {
258 progress_set_remaining(task->s->progress,
259 bdrv_get_dirty_count(task->s->copy_bitmap) +
260 task->s->in_flight_bytes);
261 }
d088e6a4 262 reqlist_remove_req(&task->req);
a6ffe199
VSO
263}
264
beb5f545
VSO
265void block_copy_state_free(BlockCopyState *s)
266{
267 if (!s) {
268 return;
269 }
270
4951967d 271 ratelimit_destroy(&s->rate_limit);
5deb6cbd 272 bdrv_release_dirty_bitmap(s->copy_bitmap);
7f739d0e 273 shres_destroy(s->mem);
beb5f545
VSO
274 g_free(s);
275}
276
9d31bc53
VSO
277static uint32_t block_copy_max_transfer(BdrvChild *source, BdrvChild *target)
278{
279 return MIN_NON_ZERO(INT_MAX,
280 MIN_NON_ZERO(source->bs->bl.max_transfer,
281 target->bs->bl.max_transfer));
282}
283
f8b9504b
VSO
284void block_copy_set_copy_opts(BlockCopyState *s, bool use_copy_range,
285 bool compress)
286{
287 /* Keep BDRV_REQ_SERIALISING set (or not set) in block_copy_state_new() */
288 s->write_flags = (s->write_flags & BDRV_REQ_SERIALISING) |
289 (compress ? BDRV_REQ_WRITE_COMPRESSED : 0);
290
291 if (s->max_transfer < s->cluster_size) {
292 /*
293 * copy_range does not respect max_transfer. We don't want to bother
294 * with requests smaller than block-copy cluster size, so fallback to
295 * buffered copying (read and write respect max_transfer on their
296 * behalf).
297 */
298 s->method = COPY_READ_WRITE_CLUSTER;
299 } else if (compress) {
300 /* Compression supports only cluster-size writes and no copy-range. */
301 s->method = COPY_READ_WRITE_CLUSTER;
302 } else {
303 /*
304 * If copy range enabled, start with COPY_RANGE_SMALL, until first
305 * successful copy_range (look at block_copy_do_copy).
306 */
307 s->method = use_copy_range ? COPY_RANGE_SMALL : COPY_READ_WRITE;
308 }
309}
310
b518e9e9
VSO
311static int64_t block_copy_calculate_cluster_size(BlockDriverState *target,
312 Error **errp)
313{
314 int ret;
315 BlockDriverInfo bdi;
316 bool target_does_cow = bdrv_backing_chain_next(target);
317
318 /*
319 * If there is no backing file on the target, we cannot rely on COW if our
320 * backup cluster size is smaller than the target cluster size. Even for
321 * targets with a backing file, try to avoid COW if possible.
322 */
323 ret = bdrv_get_info(target, &bdi);
324 if (ret == -ENOTSUP && !target_does_cow) {
325 /* Cluster size is not defined */
326 warn_report("The target block device doesn't provide "
327 "information about the block size and it doesn't have a "
328 "backing file. The default block size of %u bytes is "
329 "used. If the actual block size of the target exceeds "
330 "this default, the backup may be unusable",
331 BLOCK_COPY_CLUSTER_SIZE_DEFAULT);
332 return BLOCK_COPY_CLUSTER_SIZE_DEFAULT;
333 } else if (ret < 0 && !target_does_cow) {
334 error_setg_errno(errp, -ret,
335 "Couldn't determine the cluster size of the target image, "
336 "which has no backing file");
337 error_append_hint(errp,
338 "Aborting, since this may create an unusable destination image\n");
339 return ret;
340 } else if (ret < 0 && target_does_cow) {
341 /* Not fatal; just trudge on ahead. */
342 return BLOCK_COPY_CLUSTER_SIZE_DEFAULT;
343 }
344
345 return MAX(BLOCK_COPY_CLUSTER_SIZE_DEFAULT, bdi.cluster_size);
346}
347
00e30f05 348BlockCopyState *block_copy_state_new(BdrvChild *source, BdrvChild *target,
1f7252e8 349 const BdrvDirtyBitmap *bitmap,
abde8ac2 350 Error **errp)
beb5f545 351{
1f7252e8 352 ERRP_GUARD();
beb5f545 353 BlockCopyState *s;
b518e9e9 354 int64_t cluster_size;
beb5f545 355 BdrvDirtyBitmap *copy_bitmap;
49577723 356 bool is_fleecing;
beb5f545 357
b518e9e9
VSO
358 cluster_size = block_copy_calculate_cluster_size(target->bs, errp);
359 if (cluster_size < 0) {
360 return NULL;
361 }
362
00e30f05
VSO
363 copy_bitmap = bdrv_create_dirty_bitmap(source->bs, cluster_size, NULL,
364 errp);
beb5f545
VSO
365 if (!copy_bitmap) {
366 return NULL;
367 }
368 bdrv_disable_dirty_bitmap(copy_bitmap);
1f7252e8
VSO
369 if (bitmap) {
370 if (!bdrv_merge_dirty_bitmap(copy_bitmap, bitmap, NULL, errp)) {
371 error_prepend(errp, "Failed to merge bitmap '%s' to internal "
372 "copy-bitmap: ", bdrv_dirty_bitmap_name(bitmap));
373 bdrv_release_dirty_bitmap(copy_bitmap);
374 return NULL;
375 }
376 } else {
377 bdrv_set_dirty_bitmap(copy_bitmap, 0,
378 bdrv_dirty_bitmap_size(copy_bitmap));
379 }
beb5f545 380
49577723
VSO
381 /*
382 * If source is in backing chain of target assume that target is going to be
383 * used for "image fleecing", i.e. it should represent a kind of snapshot of
384 * source at backup-start point in time. And target is going to be read by
385 * somebody (for example, used as NBD export) during backup job.
386 *
387 * In this case, we need to add BDRV_REQ_SERIALISING write flag to avoid
388 * intersection of backup writes and third party reads from target,
389 * otherwise reading from target we may occasionally read already updated by
390 * guest data.
391 *
392 * For more information see commit f8d59dfb40bb and test
393 * tests/qemu-iotests/222
394 */
395 is_fleecing = bdrv_chain_contains(target->bs, source->bs);
396
beb5f545
VSO
397 s = g_new(BlockCopyState, 1);
398 *s = (BlockCopyState) {
00e30f05
VSO
399 .source = source,
400 .target = target,
beb5f545
VSO
401 .copy_bitmap = copy_bitmap,
402 .cluster_size = cluster_size,
403 .len = bdrv_dirty_bitmap_size(copy_bitmap),
f8b9504b 404 .write_flags = (is_fleecing ? BDRV_REQ_SERIALISING : 0),
7f739d0e 405 .mem = shres_create(BLOCK_COPY_MAX_MEM),
05d5e12b
PB
406 .max_transfer = QEMU_ALIGN_DOWN(
407 block_copy_max_transfer(source, target),
408 cluster_size),
beb5f545
VSO
409 };
410
abde8ac2 411 block_copy_set_copy_opts(s, false, false);
beb5f545 412
4951967d 413 ratelimit_init(&s->rate_limit);
d0c389d2 414 qemu_co_mutex_init(&s->lock);
d088e6a4 415 QLIST_INIT(&s->reqs);
2e099a9d 416 QLIST_INIT(&s->calls);
a6ffe199 417
beb5f545 418 return s;
beb5f545
VSO
419}
420
d0c389d2 421/* Only set before running the job, no need for locking. */
d0ebeca1
VSO
422void block_copy_set_progress_meter(BlockCopyState *s, ProgressMeter *pm)
423{
424 s->progress = pm;
425}
426
4ce5dd3e
VSO
427/*
428 * Takes ownership of @task
429 *
430 * If pool is NULL directly run the task, otherwise schedule it into the pool.
431 *
432 * Returns: task.func return code if pool is NULL
433 * otherwise -ECANCELED if pool status is bad
434 * otherwise 0 (successfully scheduled)
435 */
436static coroutine_fn int block_copy_task_run(AioTaskPool *pool,
437 BlockCopyTask *task)
438{
439 if (!pool) {
440 int ret = task->task.func(&task->task);
441
442 g_free(task);
443 return ret;
444 }
445
446 aio_task_pool_wait_slot(pool);
447 if (aio_task_pool_status(pool) < 0) {
d088e6a4 448 co_put_to_shres(task->s->mem, task->req.bytes);
4ce5dd3e
VSO
449 block_copy_task_end(task, -ECANCELED);
450 g_free(task);
451 return -ECANCELED;
452 }
453
454 aio_task_pool_start_task(pool, &task->task);
455
456 return 0;
457}
458
beb5f545 459/*
e332a726
VSO
460 * block_copy_do_copy
461 *
dafaf135
VSO
462 * Do copy of cluster-aligned chunk. Requested region is allowed to exceed
463 * s->len only to cover last cluster when s->len is not aligned to clusters.
e332a726
VSO
464 *
465 * No sync here: nor bitmap neighter intersecting requests handling, only copy.
466 *
05d5e12b
PB
467 * @method is an in-out argument, so that copy_range can be either extended to
468 * a full-size buffer or disabled if the copy_range attempt fails. The output
469 * value of @method should be used for subsequent tasks.
e332a726 470 * Returns 0 on success.
beb5f545 471 */
e332a726 472static int coroutine_fn block_copy_do_copy(BlockCopyState *s,
8719091f 473 int64_t offset, int64_t bytes,
05d5e12b 474 BlockCopyMethod *method,
bed95234 475 bool *error_is_read)
beb5f545
VSO
476{
477 int ret;
8719091f 478 int64_t nbytes = MIN(offset + bytes, s->len) - offset;
e332a726 479 void *bounce_buffer = NULL;
beb5f545 480
8719091f
VSO
481 assert(offset >= 0 && bytes > 0 && INT64_MAX - offset >= bytes);
482 assert(QEMU_IS_ALIGNED(offset, s->cluster_size));
dafaf135 483 assert(QEMU_IS_ALIGNED(bytes, s->cluster_size));
8719091f
VSO
484 assert(offset < s->len);
485 assert(offset + bytes <= s->len ||
486 offset + bytes == QEMU_ALIGN_UP(s->len, s->cluster_size));
dafaf135 487 assert(nbytes < INT_MAX);
e332a726 488
05d5e12b
PB
489 switch (*method) {
490 case COPY_WRITE_ZEROES:
8719091f 491 ret = bdrv_co_pwrite_zeroes(s->target, offset, nbytes, s->write_flags &
2d57511a
VSO
492 ~BDRV_REQ_WRITE_COMPRESSED);
493 if (ret < 0) {
8719091f 494 trace_block_copy_write_zeroes_fail(s, offset, ret);
d7eca542 495 *error_is_read = false;
2d57511a
VSO
496 }
497 return ret;
2d57511a 498
05d5e12b
PB
499 case COPY_RANGE_SMALL:
500 case COPY_RANGE_FULL:
8719091f 501 ret = bdrv_co_copy_range(s->source, offset, s->target, offset, nbytes,
e332a726 502 0, s->write_flags);
05d5e12b
PB
503 if (ret >= 0) {
504 /* Successful copy-range, increase chunk size. */
505 *method = COPY_RANGE_FULL;
bed95234 506 return 0;
e332a726 507 }
e332a726 508
05d5e12b
PB
509 trace_block_copy_copy_range_fail(s, offset, ret);
510 *method = COPY_READ_WRITE;
511 /* Fall through to read+write with allocated buffer */
0e240245 512
05d5e12b
PB
513 case COPY_READ_WRITE_CLUSTER:
514 case COPY_READ_WRITE:
515 /*
516 * In case of failed copy_range request above, we may proceed with
517 * buffered request larger than BLOCK_COPY_MAX_BUFFER.
518 * Still, further requests will be properly limited, so don't care too
519 * much. Moreover the most likely case (copy_range is unsupported for
520 * the configuration, so the very first copy_range request fails)
521 * is handled by setting large copy_size only after first successful
522 * copy_range.
523 */
beb5f545 524
05d5e12b 525 bounce_buffer = qemu_blockalign(s->source->bs, nbytes);
beb5f545 526
05d5e12b
PB
527 ret = bdrv_co_pread(s->source, offset, nbytes, bounce_buffer, 0);
528 if (ret < 0) {
529 trace_block_copy_read_fail(s, offset, ret);
530 *error_is_read = true;
531 goto out;
532 }
beb5f545 533
05d5e12b
PB
534 ret = bdrv_co_pwrite(s->target, offset, nbytes, bounce_buffer,
535 s->write_flags);
536 if (ret < 0) {
537 trace_block_copy_write_fail(s, offset, ret);
538 *error_is_read = false;
539 goto out;
540 }
3816edd2 541
05d5e12b
PB
542 out:
543 qemu_vfree(bounce_buffer);
544 break;
beb5f545 545
05d5e12b
PB
546 default:
547 abort();
bed95234
VSO
548 }
549
05d5e12b 550 return ret;
bed95234
VSO
551}
552
4ce5dd3e
VSO
553static coroutine_fn int block_copy_task_entry(AioTask *task)
554{
555 BlockCopyTask *t = container_of(task, BlockCopyTask, task);
c6a3e3df 556 BlockCopyState *s = t->s;
c78dd00e 557 bool error_is_read = false;
05d5e12b 558 BlockCopyMethod method = t->method;
4ce5dd3e
VSO
559 int ret;
560
d088e6a4
VSO
561 ret = block_copy_do_copy(s, t->req.offset, t->req.bytes, &method,
562 &error_is_read);
d0c389d2
EGE
563
564 WITH_QEMU_LOCK_GUARD(&s->lock) {
565 if (s->method == t->method) {
566 s->method = method;
567 }
568
569 if (ret < 0) {
570 if (!t->call_state->ret) {
571 t->call_state->ret = ret;
572 t->call_state->error_is_read = error_is_read;
573 }
201b4bb6 574 } else if (s->progress) {
d088e6a4 575 progress_work_done(s->progress, t->req.bytes);
8146b357 576 }
4ce5dd3e 577 }
d088e6a4 578 co_put_to_shres(s->mem, t->req.bytes);
4ce5dd3e
VSO
579 block_copy_task_end(t, ret);
580
581 return ret;
582}
583
43a0d4f0
EGE
584static coroutine_fn int block_copy_block_status(BlockCopyState *s,
585 int64_t offset,
586 int64_t bytes, int64_t *pnum)
2d57511a
VSO
587{
588 int64_t num;
589 BlockDriverState *base;
590 int ret;
591
d0c389d2 592 if (qatomic_read(&s->skip_unallocated)) {
c6f6d846 593 base = bdrv_backing_chain_next(s->source->bs);
2d57511a
VSO
594 } else {
595 base = NULL;
596 }
597
43a0d4f0
EGE
598 ret = bdrv_co_block_status_above(s->source->bs, base, offset, bytes, &num,
599 NULL, NULL);
2d57511a
VSO
600 if (ret < 0 || num < s->cluster_size) {
601 /*
602 * On error or if failed to obtain large enough chunk just fallback to
603 * copy one cluster.
604 */
605 num = s->cluster_size;
606 ret = BDRV_BLOCK_ALLOCATED | BDRV_BLOCK_DATA;
607 } else if (offset + num == s->len) {
608 num = QEMU_ALIGN_UP(num, s->cluster_size);
609 } else {
610 num = QEMU_ALIGN_DOWN(num, s->cluster_size);
611 }
612
613 *pnum = num;
614 return ret;
615}
616
beb5f545
VSO
617/*
618 * Check if the cluster starting at offset is allocated or not.
619 * return via pnum the number of contiguous clusters sharing this allocation.
620 */
43a0d4f0
EGE
621static int coroutine_fn block_copy_is_cluster_allocated(BlockCopyState *s,
622 int64_t offset,
623 int64_t *pnum)
beb5f545 624{
00e30f05 625 BlockDriverState *bs = s->source->bs;
beb5f545
VSO
626 int64_t count, total_count = 0;
627 int64_t bytes = s->len - offset;
628 int ret;
629
630 assert(QEMU_IS_ALIGNED(offset, s->cluster_size));
631
632 while (true) {
43a0d4f0 633 ret = bdrv_co_is_allocated(bs, offset, bytes, &count);
beb5f545
VSO
634 if (ret < 0) {
635 return ret;
636 }
637
638 total_count += count;
639
640 if (ret || count == 0) {
641 /*
642 * ret: partial segment(s) are considered allocated.
643 * otherwise: unallocated tail is treated as an entire segment.
644 */
645 *pnum = DIV_ROUND_UP(total_count, s->cluster_size);
646 return ret;
647 }
648
649 /* Unallocated segment(s) with uncertain following segment(s) */
650 if (total_count >= s->cluster_size) {
651 *pnum = total_count / s->cluster_size;
652 return 0;
653 }
654
655 offset += count;
656 bytes -= count;
657 }
658}
659
177541e6
VSO
660void block_copy_reset(BlockCopyState *s, int64_t offset, int64_t bytes)
661{
662 QEMU_LOCK_GUARD(&s->lock);
663
664 bdrv_reset_dirty_bitmap(s->copy_bitmap, offset, bytes);
665 if (s->progress) {
666 progress_set_remaining(s->progress,
667 bdrv_get_dirty_count(s->copy_bitmap) +
668 s->in_flight_bytes);
669 }
670}
671
beb5f545
VSO
672/*
673 * Reset bits in copy_bitmap starting at offset if they represent unallocated
674 * data in the image. May reset subsequent contiguous bits.
675 * @return 0 when the cluster at @offset was unallocated,
676 * 1 otherwise, and -ret on error.
677 */
43a0d4f0
EGE
678int64_t coroutine_fn block_copy_reset_unallocated(BlockCopyState *s,
679 int64_t offset,
680 int64_t *count)
beb5f545
VSO
681{
682 int ret;
683 int64_t clusters, bytes;
684
685 ret = block_copy_is_cluster_allocated(s, offset, &clusters);
686 if (ret < 0) {
687 return ret;
688 }
689
690 bytes = clusters * s->cluster_size;
691
692 if (!ret) {
177541e6 693 block_copy_reset(s, offset, bytes);
beb5f545
VSO
694 }
695
696 *count = bytes;
697 return ret;
698}
699
5332e5d2
VSO
700/*
701 * block_copy_dirty_clusters
702 *
703 * Copy dirty clusters in @offset/@bytes range.
704 * Returns 1 if dirty clusters found and successfully copied, 0 if no dirty
705 * clusters found and -errno on failure.
706 */
3b8c2329
VSO
707static int coroutine_fn
708block_copy_dirty_clusters(BlockCopyCallState *call_state)
beb5f545 709{
3b8c2329
VSO
710 BlockCopyState *s = call_state->s;
711 int64_t offset = call_state->offset;
712 int64_t bytes = call_state->bytes;
713
beb5f545 714 int ret = 0;
5332e5d2 715 bool found_dirty = false;
42ac2144 716 int64_t end = offset + bytes;
4ce5dd3e 717 AioTaskPool *aio = NULL;
beb5f545
VSO
718
719 /*
720 * block_copy() user is responsible for keeping source and target in same
721 * aio context
722 */
00e30f05
VSO
723 assert(bdrv_get_aio_context(s->source->bs) ==
724 bdrv_get_aio_context(s->target->bs));
beb5f545 725
8719091f 726 assert(QEMU_IS_ALIGNED(offset, s->cluster_size));
dafaf135 727 assert(QEMU_IS_ALIGNED(bytes, s->cluster_size));
beb5f545 728
149009be
EGE
729 while (bytes && aio_task_pool_status(aio) == 0 &&
730 !qatomic_read(&call_state->cancelled)) {
4ce5dd3e 731 BlockCopyTask *task;
42ac2144 732 int64_t status_bytes;
beb5f545 733
3b8c2329 734 task = block_copy_task_create(s, call_state, offset, bytes);
42ac2144
VSO
735 if (!task) {
736 /* No more dirty bits in the bitmap */
737 trace_block_copy_skip_range(s, offset, bytes);
738 break;
739 }
d088e6a4
VSO
740 if (task->req.offset > offset) {
741 trace_block_copy_skip_range(s, offset, task->req.offset - offset);
beb5f545
VSO
742 }
743
5332e5d2
VSO
744 found_dirty = true;
745
d088e6a4 746 ret = block_copy_block_status(s, task->req.offset, task->req.bytes,
42ac2144 747 &status_bytes);
5332e5d2 748 assert(ret >= 0); /* never fail */
d088e6a4 749 if (status_bytes < task->req.bytes) {
42ac2144
VSO
750 block_copy_task_shrink(task, status_bytes);
751 }
d0c389d2
EGE
752 if (qatomic_read(&s->skip_unallocated) &&
753 !(ret & BDRV_BLOCK_ALLOCATED)) {
1348a657 754 block_copy_task_end(task, 0);
d088e6a4 755 trace_block_copy_skip_range(s, task->req.offset, task->req.bytes);
42ac2144
VSO
756 offset = task_end(task);
757 bytes = end - offset;
fc9aefc8 758 g_free(task);
2d57511a 759 continue;
beb5f545 760 }
bed95234 761 if (ret & BDRV_BLOCK_ZERO) {
05d5e12b 762 task->method = COPY_WRITE_ZEROES;
bed95234 763 }
beb5f545 764
ca657c99
PB
765 if (!call_state->ignore_ratelimit) {
766 uint64_t ns = ratelimit_calculate_delay(&s->rate_limit, 0);
767 if (ns > 0) {
768 block_copy_task_end(task, -EAGAIN);
769 g_free(task);
770 qemu_co_sleep_ns_wakeable(&call_state->sleep,
771 QEMU_CLOCK_REALTIME, ns);
772 continue;
7e032df0 773 }
7e032df0
VSO
774 }
775
d088e6a4 776 ratelimit_calculate_delay(&s->rate_limit, task->req.bytes);
ca657c99 777
d088e6a4 778 trace_block_copy_process(s, task->req.offset);
beb5f545 779
d088e6a4 780 co_get_from_shres(s->mem, task->req.bytes);
beb5f545 781
42ac2144
VSO
782 offset = task_end(task);
783 bytes = end - offset;
4ce5dd3e
VSO
784
785 if (!aio && bytes) {
26be9d62 786 aio = aio_task_pool_new(call_state->max_workers);
4ce5dd3e
VSO
787 }
788
789 ret = block_copy_task_run(aio, task);
790 if (ret < 0) {
791 goto out;
792 }
793 }
794
795out:
796 if (aio) {
797 aio_task_pool_wait_all(aio);
798
799 /*
800 * We are not really interested in -ECANCELED returned from
801 * block_copy_task_run. If it fails, it means some task already failed
802 * for real reason, let's return first failure.
803 * Still, assert that we don't rewrite failure by success.
e8de7ba9
VSO
804 *
805 * Note: ret may be positive here because of block-status result.
4ce5dd3e 806 */
e8de7ba9 807 assert(ret >= 0 || aio_task_pool_status(aio) < 0);
4ce5dd3e
VSO
808 ret = aio_task_pool_status(aio);
809
810 aio_task_pool_free(aio);
811 }
beb5f545 812
4ce5dd3e 813 return ret < 0 ? ret : found_dirty;
5332e5d2
VSO
814}
815
7e032df0
VSO
816void block_copy_kick(BlockCopyCallState *call_state)
817{
29a6ea24 818 qemu_co_sleep_wake(&call_state->sleep);
7e032df0
VSO
819}
820
5332e5d2 821/*
3b8c2329 822 * block_copy_common
5332e5d2
VSO
823 *
824 * Copy requested region, accordingly to dirty bitmap.
825 * Collaborate with parallel block_copy requests: if they succeed it will help
826 * us. If they fail, we will retry not-copied regions. So, if we return error,
827 * it means that some I/O operation failed in context of _this_ block_copy call,
828 * not some parallel operation.
829 */
3b8c2329 830static int coroutine_fn block_copy_common(BlockCopyCallState *call_state)
5332e5d2
VSO
831{
832 int ret;
c6a3e3df 833 BlockCopyState *s = call_state->s;
5332e5d2 834
d0c389d2 835 qemu_co_mutex_lock(&s->lock);
c6a3e3df 836 QLIST_INSERT_HEAD(&s->calls, call_state, list);
d0c389d2 837 qemu_co_mutex_unlock(&s->lock);
2e099a9d 838
5332e5d2 839 do {
3b8c2329 840 ret = block_copy_dirty_clusters(call_state);
5332e5d2 841
149009be 842 if (ret == 0 && !qatomic_read(&call_state->cancelled)) {
d0c389d2
EGE
843 WITH_QEMU_LOCK_GUARD(&s->lock) {
844 /*
845 * Check that there is no task we still need to
846 * wait to complete
847 */
d088e6a4
VSO
848 ret = reqlist_wait_one(&s->reqs, call_state->offset,
849 call_state->bytes, &s->lock);
d0c389d2
EGE
850 if (ret == 0) {
851 /*
852 * No pending tasks, but check again the bitmap in this
853 * same critical section, since a task might have failed
854 * between this and the critical section in
855 * block_copy_dirty_clusters().
856 *
d088e6a4 857 * reqlist_wait_one return value 0 also means that it
d0c389d2
EGE
858 * didn't release the lock. So, we are still in the same
859 * critical section, not interrupted by any concurrent
860 * access to state.
861 */
862 ret = bdrv_dirty_bitmap_next_dirty(s->copy_bitmap,
863 call_state->offset,
864 call_state->bytes) >= 0;
865 }
866 }
5332e5d2
VSO
867 }
868
869 /*
870 * We retry in two cases:
871 * 1. Some progress done
872 * Something was copied, which means that there were yield points
873 * and some new dirty bits may have appeared (due to failed parallel
874 * block-copy requests).
875 * 2. We have waited for some intersecting block-copy request
876 * It may have failed and produced new dirty bits.
877 */
149009be 878 } while (ret > 0 && !qatomic_read(&call_state->cancelled));
a6ffe199 879
149009be 880 qatomic_store_release(&call_state->finished, true);
de4641b4
VSO
881
882 if (call_state->cb) {
883 call_state->cb(call_state->cb_opaque);
884 }
885
d0c389d2 886 qemu_co_mutex_lock(&s->lock);
2e099a9d 887 QLIST_REMOVE(call_state, list);
d0c389d2 888 qemu_co_mutex_unlock(&s->lock);
2e099a9d 889
beb5f545
VSO
890 return ret;
891}
397f4e9d 892
15df6e69
VSO
893static void coroutine_fn block_copy_async_co_entry(void *opaque)
894{
895 block_copy_common(opaque);
896}
897
3b8c2329 898int coroutine_fn block_copy(BlockCopyState *s, int64_t start, int64_t bytes,
15df6e69
VSO
899 bool ignore_ratelimit, uint64_t timeout_ns,
900 BlockCopyAsyncCallbackFunc cb,
901 void *cb_opaque)
3b8c2329 902{
15df6e69
VSO
903 int ret;
904 BlockCopyCallState *call_state = g_new(BlockCopyCallState, 1);
905
906 *call_state = (BlockCopyCallState) {
3b8c2329
VSO
907 .s = s,
908 .offset = start,
909 .bytes = bytes,
7e032df0 910 .ignore_ratelimit = ignore_ratelimit,
26be9d62 911 .max_workers = BLOCK_COPY_MAX_WORKERS,
15df6e69
VSO
912 .cb = cb,
913 .cb_opaque = cb_opaque,
3b8c2329
VSO
914 };
915
15df6e69
VSO
916 ret = qemu_co_timeout(block_copy_async_co_entry, call_state, timeout_ns,
917 g_free);
918 if (ret < 0) {
919 assert(ret == -ETIMEDOUT);
920 block_copy_call_cancel(call_state);
921 /* call_state will be freed by running coroutine. */
922 return ret;
923 }
3b8c2329 924
15df6e69
VSO
925 ret = call_state->ret;
926 g_free(call_state);
927
928 return ret;
de4641b4
VSO
929}
930
931BlockCopyCallState *block_copy_async(BlockCopyState *s,
932 int64_t offset, int64_t bytes,
26be9d62 933 int max_workers, int64_t max_chunk,
de4641b4
VSO
934 BlockCopyAsyncCallbackFunc cb,
935 void *cb_opaque)
936{
937 BlockCopyCallState *call_state = g_new(BlockCopyCallState, 1);
938
939 *call_state = (BlockCopyCallState) {
940 .s = s,
941 .offset = offset,
942 .bytes = bytes,
26be9d62
VSO
943 .max_workers = max_workers,
944 .max_chunk = max_chunk,
de4641b4
VSO
945 .cb = cb,
946 .cb_opaque = cb_opaque,
947
948 .co = qemu_coroutine_create(block_copy_async_co_entry, call_state),
949 };
950
951 qemu_coroutine_enter(call_state->co);
952
953 return call_state;
954}
955
956void block_copy_call_free(BlockCopyCallState *call_state)
957{
958 if (!call_state) {
959 return;
960 }
961
149009be 962 assert(qatomic_read(&call_state->finished));
de4641b4
VSO
963 g_free(call_state);
964}
965
966bool block_copy_call_finished(BlockCopyCallState *call_state)
967{
149009be 968 return qatomic_read(&call_state->finished);
de4641b4
VSO
969}
970
971bool block_copy_call_succeeded(BlockCopyCallState *call_state)
972{
149009be
EGE
973 return qatomic_load_acquire(&call_state->finished) &&
974 !qatomic_read(&call_state->cancelled) &&
975 call_state->ret == 0;
de4641b4
VSO
976}
977
978bool block_copy_call_failed(BlockCopyCallState *call_state)
979{
149009be
EGE
980 return qatomic_load_acquire(&call_state->finished) &&
981 !qatomic_read(&call_state->cancelled) &&
982 call_state->ret < 0;
a6d23d56
VSO
983}
984
985bool block_copy_call_cancelled(BlockCopyCallState *call_state)
986{
149009be 987 return qatomic_read(&call_state->cancelled);
de4641b4
VSO
988}
989
990int block_copy_call_status(BlockCopyCallState *call_state, bool *error_is_read)
991{
149009be 992 assert(qatomic_load_acquire(&call_state->finished));
de4641b4
VSO
993 if (error_is_read) {
994 *error_is_read = call_state->error_is_read;
995 }
996 return call_state->ret;
997}
998
149009be
EGE
999/*
1000 * Note that cancelling and finishing are racy.
1001 * User can cancel a block-copy that is already finished.
1002 */
a6d23d56
VSO
1003void block_copy_call_cancel(BlockCopyCallState *call_state)
1004{
149009be 1005 qatomic_set(&call_state->cancelled, true);
a6d23d56
VSO
1006 block_copy_kick(call_state);
1007}
1008
397f4e9d
VSO
1009BdrvDirtyBitmap *block_copy_dirty_bitmap(BlockCopyState *s)
1010{
1011 return s->copy_bitmap;
1012}
1013
b518e9e9
VSO
1014int64_t block_copy_cluster_size(BlockCopyState *s)
1015{
1016 return s->cluster_size;
1017}
1018
397f4e9d
VSO
1019void block_copy_set_skip_unallocated(BlockCopyState *s, bool skip)
1020{
d0c389d2 1021 qatomic_set(&s->skip_unallocated, skip);
397f4e9d 1022}
7e032df0
VSO
1023
1024void block_copy_set_speed(BlockCopyState *s, uint64_t speed)
1025{
ca657c99 1026 ratelimit_set_speed(&s->rate_limit, speed, BLOCK_COPY_SLICE_TIME);
7e032df0
VSO
1027
1028 /*
1029 * Note: it's good to kick all call states from here, but it should be done
1030 * only from a coroutine, to not crash if s->calls list changed while
1031 * entering one call. So for now, the only user of this function kicks its
1032 * only one call_state by hand.
1033 */
1034}