xref: /openbmc/qemu/block/backup.c (revision f1f7e4bf)
1 /*
2  * QEMU backup
3  *
4  * Copyright (C) 2013 Proxmox Server Solutions
5  *
6  * Authors:
7  *  Dietmar Maurer (dietmar@proxmox.com)
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2 or later.
10  * See the COPYING file in the top-level directory.
11  *
12  */
13 
14 #include <stdio.h>
15 #include <errno.h>
16 #include <unistd.h>
17 
18 #include "trace.h"
19 #include "block/block.h"
20 #include "block/block_int.h"
21 #include "block/blockjob.h"
22 #include "qapi/qmp/qerror.h"
23 #include "qemu/ratelimit.h"
24 #include "sysemu/block-backend.h"
25 
26 #define BACKUP_CLUSTER_BITS 16
27 #define BACKUP_CLUSTER_SIZE (1 << BACKUP_CLUSTER_BITS)
28 #define BACKUP_SECTORS_PER_CLUSTER (BACKUP_CLUSTER_SIZE / BDRV_SECTOR_SIZE)
29 
30 #define SLICE_TIME 100000000ULL /* ns */
31 
32 typedef struct CowRequest {
33     int64_t start;
34     int64_t end;
35     QLIST_ENTRY(CowRequest) list;
36     CoQueue wait_queue; /* coroutines blocked on this request */
37 } CowRequest;
38 
39 typedef struct BackupBlockJob {
40     BlockJob common;
41     BlockDriverState *target;
42     /* bitmap for sync=incremental */
43     BdrvDirtyBitmap *sync_bitmap;
44     MirrorSyncMode sync_mode;
45     RateLimit limit;
46     BlockdevOnError on_source_error;
47     BlockdevOnError on_target_error;
48     CoRwlock flush_rwlock;
49     uint64_t sectors_read;
50     HBitmap *bitmap;
51     QLIST_HEAD(, CowRequest) inflight_reqs;
52 } BackupBlockJob;
53 
54 /* See if in-flight requests overlap and wait for them to complete */
55 static void coroutine_fn wait_for_overlapping_requests(BackupBlockJob *job,
56                                                        int64_t start,
57                                                        int64_t end)
58 {
59     CowRequest *req;
60     bool retry;
61 
62     do {
63         retry = false;
64         QLIST_FOREACH(req, &job->inflight_reqs, list) {
65             if (end > req->start && start < req->end) {
66                 qemu_co_queue_wait(&req->wait_queue);
67                 retry = true;
68                 break;
69             }
70         }
71     } while (retry);
72 }
73 
74 /* Keep track of an in-flight request */
75 static void cow_request_begin(CowRequest *req, BackupBlockJob *job,
76                                      int64_t start, int64_t end)
77 {
78     req->start = start;
79     req->end = end;
80     qemu_co_queue_init(&req->wait_queue);
81     QLIST_INSERT_HEAD(&job->inflight_reqs, req, list);
82 }
83 
84 /* Forget about a completed request */
85 static void cow_request_end(CowRequest *req)
86 {
87     QLIST_REMOVE(req, list);
88     qemu_co_queue_restart_all(&req->wait_queue);
89 }
90 
91 static int coroutine_fn backup_do_cow(BlockDriverState *bs,
92                                       int64_t sector_num, int nb_sectors,
93                                       bool *error_is_read,
94                                       bool is_write_notifier)
95 {
96     BackupBlockJob *job = (BackupBlockJob *)bs->job;
97     CowRequest cow_request;
98     struct iovec iov;
99     QEMUIOVector bounce_qiov;
100     void *bounce_buffer = NULL;
101     int ret = 0;
102     int64_t start, end;
103     int n;
104 
105     qemu_co_rwlock_rdlock(&job->flush_rwlock);
106 
107     start = sector_num / BACKUP_SECTORS_PER_CLUSTER;
108     end = DIV_ROUND_UP(sector_num + nb_sectors, BACKUP_SECTORS_PER_CLUSTER);
109 
110     trace_backup_do_cow_enter(job, start, sector_num, nb_sectors);
111 
112     wait_for_overlapping_requests(job, start, end);
113     cow_request_begin(&cow_request, job, start, end);
114 
115     for (; start < end; start++) {
116         if (hbitmap_get(job->bitmap, start)) {
117             trace_backup_do_cow_skip(job, start);
118             continue; /* already copied */
119         }
120 
121         trace_backup_do_cow_process(job, start);
122 
123         n = MIN(BACKUP_SECTORS_PER_CLUSTER,
124                 job->common.len / BDRV_SECTOR_SIZE -
125                 start * BACKUP_SECTORS_PER_CLUSTER);
126 
127         if (!bounce_buffer) {
128             bounce_buffer = qemu_blockalign(bs, BACKUP_CLUSTER_SIZE);
129         }
130         iov.iov_base = bounce_buffer;
131         iov.iov_len = n * BDRV_SECTOR_SIZE;
132         qemu_iovec_init_external(&bounce_qiov, &iov, 1);
133 
134         if (is_write_notifier) {
135             ret = bdrv_co_readv_no_serialising(bs,
136                                            start * BACKUP_SECTORS_PER_CLUSTER,
137                                            n, &bounce_qiov);
138         } else {
139             ret = bdrv_co_readv(bs, start * BACKUP_SECTORS_PER_CLUSTER, n,
140                                 &bounce_qiov);
141         }
142         if (ret < 0) {
143             trace_backup_do_cow_read_fail(job, start, ret);
144             if (error_is_read) {
145                 *error_is_read = true;
146             }
147             goto out;
148         }
149 
150         if (buffer_is_zero(iov.iov_base, iov.iov_len)) {
151             ret = bdrv_co_write_zeroes(job->target,
152                                        start * BACKUP_SECTORS_PER_CLUSTER,
153                                        n, BDRV_REQ_MAY_UNMAP);
154         } else {
155             ret = bdrv_co_writev(job->target,
156                                  start * BACKUP_SECTORS_PER_CLUSTER, n,
157                                  &bounce_qiov);
158         }
159         if (ret < 0) {
160             trace_backup_do_cow_write_fail(job, start, ret);
161             if (error_is_read) {
162                 *error_is_read = false;
163             }
164             goto out;
165         }
166 
167         hbitmap_set(job->bitmap, start, 1);
168 
169         /* Publish progress, guest I/O counts as progress too.  Note that the
170          * offset field is an opaque progress value, it is not a disk offset.
171          */
172         job->sectors_read += n;
173         job->common.offset += n * BDRV_SECTOR_SIZE;
174     }
175 
176 out:
177     if (bounce_buffer) {
178         qemu_vfree(bounce_buffer);
179     }
180 
181     cow_request_end(&cow_request);
182 
183     trace_backup_do_cow_return(job, sector_num, nb_sectors, ret);
184 
185     qemu_co_rwlock_unlock(&job->flush_rwlock);
186 
187     return ret;
188 }
189 
190 static int coroutine_fn backup_before_write_notify(
191         NotifierWithReturn *notifier,
192         void *opaque)
193 {
194     BdrvTrackedRequest *req = opaque;
195     int64_t sector_num = req->offset >> BDRV_SECTOR_BITS;
196     int nb_sectors = req->bytes >> BDRV_SECTOR_BITS;
197 
198     assert((req->offset & (BDRV_SECTOR_SIZE - 1)) == 0);
199     assert((req->bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
200 
201     return backup_do_cow(req->bs, sector_num, nb_sectors, NULL, true);
202 }
203 
204 static void backup_set_speed(BlockJob *job, int64_t speed, Error **errp)
205 {
206     BackupBlockJob *s = container_of(job, BackupBlockJob, common);
207 
208     if (speed < 0) {
209         error_setg(errp, QERR_INVALID_PARAMETER, "speed");
210         return;
211     }
212     ratelimit_set_speed(&s->limit, speed / BDRV_SECTOR_SIZE, SLICE_TIME);
213 }
214 
215 static void backup_iostatus_reset(BlockJob *job)
216 {
217     BackupBlockJob *s = container_of(job, BackupBlockJob, common);
218 
219     if (s->target->blk) {
220         blk_iostatus_reset(s->target->blk);
221     }
222 }
223 
224 static void backup_cleanup_sync_bitmap(BackupBlockJob *job, int ret)
225 {
226     BdrvDirtyBitmap *bm;
227     BlockDriverState *bs = job->common.bs;
228 
229     if (ret < 0 || block_job_is_cancelled(&job->common)) {
230         /* Merge the successor back into the parent, delete nothing. */
231         bm = bdrv_reclaim_dirty_bitmap(bs, job->sync_bitmap, NULL);
232         assert(bm);
233     } else {
234         /* Everything is fine, delete this bitmap and install the backup. */
235         bm = bdrv_dirty_bitmap_abdicate(bs, job->sync_bitmap, NULL);
236         assert(bm);
237     }
238 }
239 
240 static void backup_commit(BlockJob *job)
241 {
242     BackupBlockJob *s = container_of(job, BackupBlockJob, common);
243     if (s->sync_bitmap) {
244         backup_cleanup_sync_bitmap(s, 0);
245     }
246 }
247 
248 static void backup_abort(BlockJob *job)
249 {
250     BackupBlockJob *s = container_of(job, BackupBlockJob, common);
251     if (s->sync_bitmap) {
252         backup_cleanup_sync_bitmap(s, -1);
253     }
254 }
255 
256 static const BlockJobDriver backup_job_driver = {
257     .instance_size  = sizeof(BackupBlockJob),
258     .job_type       = BLOCK_JOB_TYPE_BACKUP,
259     .set_speed      = backup_set_speed,
260     .iostatus_reset = backup_iostatus_reset,
261     .commit         = backup_commit,
262     .abort          = backup_abort,
263 };
264 
265 static BlockErrorAction backup_error_action(BackupBlockJob *job,
266                                             bool read, int error)
267 {
268     if (read) {
269         return block_job_error_action(&job->common, job->common.bs,
270                                       job->on_source_error, true, error);
271     } else {
272         return block_job_error_action(&job->common, job->target,
273                                       job->on_target_error, false, error);
274     }
275 }
276 
277 typedef struct {
278     int ret;
279 } BackupCompleteData;
280 
281 static void backup_complete(BlockJob *job, void *opaque)
282 {
283     BackupBlockJob *s = container_of(job, BackupBlockJob, common);
284     BackupCompleteData *data = opaque;
285 
286     bdrv_unref(s->target);
287 
288     block_job_completed(job, data->ret);
289     g_free(data);
290 }
291 
292 static bool coroutine_fn yield_and_check(BackupBlockJob *job)
293 {
294     if (block_job_is_cancelled(&job->common)) {
295         return true;
296     }
297 
298     /* we need to yield so that bdrv_drain_all() returns.
299      * (without, VM does not reboot)
300      */
301     if (job->common.speed) {
302         uint64_t delay_ns = ratelimit_calculate_delay(&job->limit,
303                                                       job->sectors_read);
304         job->sectors_read = 0;
305         block_job_sleep_ns(&job->common, QEMU_CLOCK_REALTIME, delay_ns);
306     } else {
307         block_job_sleep_ns(&job->common, QEMU_CLOCK_REALTIME, 0);
308     }
309 
310     if (block_job_is_cancelled(&job->common)) {
311         return true;
312     }
313 
314     return false;
315 }
316 
317 static int coroutine_fn backup_run_incremental(BackupBlockJob *job)
318 {
319     bool error_is_read;
320     int ret = 0;
321     int clusters_per_iter;
322     uint32_t granularity;
323     int64_t sector;
324     int64_t cluster;
325     int64_t end;
326     int64_t last_cluster = -1;
327     BlockDriverState *bs = job->common.bs;
328     HBitmapIter hbi;
329 
330     granularity = bdrv_dirty_bitmap_granularity(job->sync_bitmap);
331     clusters_per_iter = MAX((granularity / BACKUP_CLUSTER_SIZE), 1);
332     bdrv_dirty_iter_init(job->sync_bitmap, &hbi);
333 
334     /* Find the next dirty sector(s) */
335     while ((sector = hbitmap_iter_next(&hbi)) != -1) {
336         cluster = sector / BACKUP_SECTORS_PER_CLUSTER;
337 
338         /* Fake progress updates for any clusters we skipped */
339         if (cluster != last_cluster + 1) {
340             job->common.offset += ((cluster - last_cluster - 1) *
341                                    BACKUP_CLUSTER_SIZE);
342         }
343 
344         for (end = cluster + clusters_per_iter; cluster < end; cluster++) {
345             do {
346                 if (yield_and_check(job)) {
347                     return ret;
348                 }
349                 ret = backup_do_cow(bs, cluster * BACKUP_SECTORS_PER_CLUSTER,
350                                     BACKUP_SECTORS_PER_CLUSTER, &error_is_read,
351                                     false);
352                 if ((ret < 0) &&
353                     backup_error_action(job, error_is_read, -ret) ==
354                     BLOCK_ERROR_ACTION_REPORT) {
355                     return ret;
356                 }
357             } while (ret < 0);
358         }
359 
360         /* If the bitmap granularity is smaller than the backup granularity,
361          * we need to advance the iterator pointer to the next cluster. */
362         if (granularity < BACKUP_CLUSTER_SIZE) {
363             bdrv_set_dirty_iter(&hbi, cluster * BACKUP_SECTORS_PER_CLUSTER);
364         }
365 
366         last_cluster = cluster - 1;
367     }
368 
369     /* Play some final catchup with the progress meter */
370     end = DIV_ROUND_UP(job->common.len, BACKUP_CLUSTER_SIZE);
371     if (last_cluster + 1 < end) {
372         job->common.offset += ((end - last_cluster - 1) * BACKUP_CLUSTER_SIZE);
373     }
374 
375     return ret;
376 }
377 
378 static void coroutine_fn backup_run(void *opaque)
379 {
380     BackupBlockJob *job = opaque;
381     BackupCompleteData *data;
382     BlockDriverState *bs = job->common.bs;
383     BlockDriverState *target = job->target;
384     BlockdevOnError on_target_error = job->on_target_error;
385     NotifierWithReturn before_write = {
386         .notify = backup_before_write_notify,
387     };
388     int64_t start, end;
389     int ret = 0;
390 
391     QLIST_INIT(&job->inflight_reqs);
392     qemu_co_rwlock_init(&job->flush_rwlock);
393 
394     start = 0;
395     end = DIV_ROUND_UP(job->common.len, BACKUP_CLUSTER_SIZE);
396 
397     job->bitmap = hbitmap_alloc(end, 0);
398 
399     bdrv_set_enable_write_cache(target, true);
400     if (target->blk) {
401         blk_set_on_error(target->blk, on_target_error, on_target_error);
402         blk_iostatus_enable(target->blk);
403     }
404 
405     bdrv_add_before_write_notifier(bs, &before_write);
406 
407     if (job->sync_mode == MIRROR_SYNC_MODE_NONE) {
408         while (!block_job_is_cancelled(&job->common)) {
409             /* Yield until the job is cancelled.  We just let our before_write
410              * notify callback service CoW requests. */
411             job->common.busy = false;
412             qemu_coroutine_yield();
413             job->common.busy = true;
414         }
415     } else if (job->sync_mode == MIRROR_SYNC_MODE_INCREMENTAL) {
416         ret = backup_run_incremental(job);
417     } else {
418         /* Both FULL and TOP SYNC_MODE's require copying.. */
419         for (; start < end; start++) {
420             bool error_is_read;
421             if (yield_and_check(job)) {
422                 break;
423             }
424 
425             if (job->sync_mode == MIRROR_SYNC_MODE_TOP) {
426                 int i, n;
427                 int alloced = 0;
428 
429                 /* Check to see if these blocks are already in the
430                  * backing file. */
431 
432                 for (i = 0; i < BACKUP_SECTORS_PER_CLUSTER;) {
433                     /* bdrv_is_allocated() only returns true/false based
434                      * on the first set of sectors it comes across that
435                      * are are all in the same state.
436                      * For that reason we must verify each sector in the
437                      * backup cluster length.  We end up copying more than
438                      * needed but at some point that is always the case. */
439                     alloced =
440                         bdrv_is_allocated(bs,
441                                 start * BACKUP_SECTORS_PER_CLUSTER + i,
442                                 BACKUP_SECTORS_PER_CLUSTER - i, &n);
443                     i += n;
444 
445                     if (alloced == 1 || n == 0) {
446                         break;
447                     }
448                 }
449 
450                 /* If the above loop never found any sectors that are in
451                  * the topmost image, skip this backup. */
452                 if (alloced == 0) {
453                     continue;
454                 }
455             }
456             /* FULL sync mode we copy the whole drive. */
457             ret = backup_do_cow(bs, start * BACKUP_SECTORS_PER_CLUSTER,
458                     BACKUP_SECTORS_PER_CLUSTER, &error_is_read, false);
459             if (ret < 0) {
460                 /* Depending on error action, fail now or retry cluster */
461                 BlockErrorAction action =
462                     backup_error_action(job, error_is_read, -ret);
463                 if (action == BLOCK_ERROR_ACTION_REPORT) {
464                     break;
465                 } else {
466                     start--;
467                     continue;
468                 }
469             }
470         }
471     }
472 
473     notifier_with_return_remove(&before_write);
474 
475     /* wait until pending backup_do_cow() calls have completed */
476     qemu_co_rwlock_wrlock(&job->flush_rwlock);
477     qemu_co_rwlock_unlock(&job->flush_rwlock);
478     hbitmap_free(job->bitmap);
479 
480     if (target->blk) {
481         blk_iostatus_disable(target->blk);
482     }
483     bdrv_op_unblock_all(target, job->common.blocker);
484 
485     data = g_malloc(sizeof(*data));
486     data->ret = ret;
487     block_job_defer_to_main_loop(&job->common, backup_complete, data);
488 }
489 
490 void backup_start(BlockDriverState *bs, BlockDriverState *target,
491                   int64_t speed, MirrorSyncMode sync_mode,
492                   BdrvDirtyBitmap *sync_bitmap,
493                   BlockdevOnError on_source_error,
494                   BlockdevOnError on_target_error,
495                   BlockCompletionFunc *cb, void *opaque,
496                   BlockJobTxn *txn, Error **errp)
497 {
498     int64_t len;
499 
500     assert(bs);
501     assert(target);
502     assert(cb);
503 
504     if (bs == target) {
505         error_setg(errp, "Source and target cannot be the same");
506         return;
507     }
508 
509     if ((on_source_error == BLOCKDEV_ON_ERROR_STOP ||
510          on_source_error == BLOCKDEV_ON_ERROR_ENOSPC) &&
511         (!bs->blk || !blk_iostatus_is_enabled(bs->blk))) {
512         error_setg(errp, QERR_INVALID_PARAMETER, "on-source-error");
513         return;
514     }
515 
516     if (!bdrv_is_inserted(bs)) {
517         error_setg(errp, "Device is not inserted: %s",
518                    bdrv_get_device_name(bs));
519         return;
520     }
521 
522     if (!bdrv_is_inserted(target)) {
523         error_setg(errp, "Device is not inserted: %s",
524                    bdrv_get_device_name(target));
525         return;
526     }
527 
528     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
529         return;
530     }
531 
532     if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_BACKUP_TARGET, errp)) {
533         return;
534     }
535 
536     if (sync_mode == MIRROR_SYNC_MODE_INCREMENTAL) {
537         if (!sync_bitmap) {
538             error_setg(errp, "must provide a valid bitmap name for "
539                              "\"incremental\" sync mode");
540             return;
541         }
542 
543         /* Create a new bitmap, and freeze/disable this one. */
544         if (bdrv_dirty_bitmap_create_successor(bs, sync_bitmap, errp) < 0) {
545             return;
546         }
547     } else if (sync_bitmap) {
548         error_setg(errp,
549                    "a sync_bitmap was provided to backup_run, "
550                    "but received an incompatible sync_mode (%s)",
551                    MirrorSyncMode_lookup[sync_mode]);
552         return;
553     }
554 
555     len = bdrv_getlength(bs);
556     if (len < 0) {
557         error_setg_errno(errp, -len, "unable to get length for '%s'",
558                          bdrv_get_device_name(bs));
559         goto error;
560     }
561 
562     BackupBlockJob *job = block_job_create(&backup_job_driver, bs, speed,
563                                            cb, opaque, errp);
564     if (!job) {
565         goto error;
566     }
567 
568     bdrv_op_block_all(target, job->common.blocker);
569 
570     job->on_source_error = on_source_error;
571     job->on_target_error = on_target_error;
572     job->target = target;
573     job->sync_mode = sync_mode;
574     job->sync_bitmap = sync_mode == MIRROR_SYNC_MODE_INCREMENTAL ?
575                        sync_bitmap : NULL;
576     job->common.len = len;
577     job->common.co = qemu_coroutine_create(backup_run);
578     block_job_txn_add_job(txn, &job->common);
579     qemu_coroutine_enter(job->common.co, job);
580     return;
581 
582  error:
583     if (sync_bitmap) {
584         bdrv_reclaim_dirty_bitmap(bs, sync_bitmap, NULL);
585     }
586 }
587