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