block-copy.c 33 KB

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