xref: /openbmc/qemu/block/backup.c (revision 56411125)
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_no_copy_on_readv(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 const BlockJobDriver backup_job_driver = {
225     .instance_size  = sizeof(BackupBlockJob),
226     .job_type       = BLOCK_JOB_TYPE_BACKUP,
227     .set_speed      = backup_set_speed,
228     .iostatus_reset = backup_iostatus_reset,
229 };
230 
231 static BlockErrorAction backup_error_action(BackupBlockJob *job,
232                                             bool read, int error)
233 {
234     if (read) {
235         return block_job_error_action(&job->common, job->common.bs,
236                                       job->on_source_error, true, error);
237     } else {
238         return block_job_error_action(&job->common, job->target,
239                                       job->on_target_error, false, error);
240     }
241 }
242 
243 typedef struct {
244     int ret;
245 } BackupCompleteData;
246 
247 static void backup_complete(BlockJob *job, void *opaque)
248 {
249     BackupBlockJob *s = container_of(job, BackupBlockJob, common);
250     BackupCompleteData *data = opaque;
251 
252     bdrv_unref(s->target);
253 
254     block_job_completed(job, data->ret);
255     g_free(data);
256 }
257 
258 static bool coroutine_fn yield_and_check(BackupBlockJob *job)
259 {
260     if (block_job_is_cancelled(&job->common)) {
261         return true;
262     }
263 
264     /* we need to yield so that bdrv_drain_all() returns.
265      * (without, VM does not reboot)
266      */
267     if (job->common.speed) {
268         uint64_t delay_ns = ratelimit_calculate_delay(&job->limit,
269                                                       job->sectors_read);
270         job->sectors_read = 0;
271         block_job_sleep_ns(&job->common, QEMU_CLOCK_REALTIME, delay_ns);
272     } else {
273         block_job_sleep_ns(&job->common, QEMU_CLOCK_REALTIME, 0);
274     }
275 
276     if (block_job_is_cancelled(&job->common)) {
277         return true;
278     }
279 
280     return false;
281 }
282 
283 static int coroutine_fn backup_run_incremental(BackupBlockJob *job)
284 {
285     bool error_is_read;
286     int ret = 0;
287     int clusters_per_iter;
288     uint32_t granularity;
289     int64_t sector;
290     int64_t cluster;
291     int64_t end;
292     int64_t last_cluster = -1;
293     BlockDriverState *bs = job->common.bs;
294     HBitmapIter hbi;
295 
296     granularity = bdrv_dirty_bitmap_granularity(job->sync_bitmap);
297     clusters_per_iter = MAX((granularity / BACKUP_CLUSTER_SIZE), 1);
298     bdrv_dirty_iter_init(job->sync_bitmap, &hbi);
299 
300     /* Find the next dirty sector(s) */
301     while ((sector = hbitmap_iter_next(&hbi)) != -1) {
302         cluster = sector / BACKUP_SECTORS_PER_CLUSTER;
303 
304         /* Fake progress updates for any clusters we skipped */
305         if (cluster != last_cluster + 1) {
306             job->common.offset += ((cluster - last_cluster - 1) *
307                                    BACKUP_CLUSTER_SIZE);
308         }
309 
310         for (end = cluster + clusters_per_iter; cluster < end; cluster++) {
311             do {
312                 if (yield_and_check(job)) {
313                     return ret;
314                 }
315                 ret = backup_do_cow(bs, cluster * BACKUP_SECTORS_PER_CLUSTER,
316                                     BACKUP_SECTORS_PER_CLUSTER, &error_is_read,
317                                     false);
318                 if ((ret < 0) &&
319                     backup_error_action(job, error_is_read, -ret) ==
320                     BLOCK_ERROR_ACTION_REPORT) {
321                     return ret;
322                 }
323             } while (ret < 0);
324         }
325 
326         /* If the bitmap granularity is smaller than the backup granularity,
327          * we need to advance the iterator pointer to the next cluster. */
328         if (granularity < BACKUP_CLUSTER_SIZE) {
329             bdrv_set_dirty_iter(&hbi, cluster * BACKUP_SECTORS_PER_CLUSTER);
330         }
331 
332         last_cluster = cluster - 1;
333     }
334 
335     /* Play some final catchup with the progress meter */
336     end = DIV_ROUND_UP(job->common.len, BACKUP_CLUSTER_SIZE);
337     if (last_cluster + 1 < end) {
338         job->common.offset += ((end - last_cluster - 1) * BACKUP_CLUSTER_SIZE);
339     }
340 
341     return ret;
342 }
343 
344 static void coroutine_fn backup_run(void *opaque)
345 {
346     BackupBlockJob *job = opaque;
347     BackupCompleteData *data;
348     BlockDriverState *bs = job->common.bs;
349     BlockDriverState *target = job->target;
350     BlockdevOnError on_target_error = job->on_target_error;
351     NotifierWithReturn before_write = {
352         .notify = backup_before_write_notify,
353     };
354     int64_t start, end;
355     int ret = 0;
356 
357     QLIST_INIT(&job->inflight_reqs);
358     qemu_co_rwlock_init(&job->flush_rwlock);
359 
360     start = 0;
361     end = DIV_ROUND_UP(job->common.len, BACKUP_CLUSTER_SIZE);
362 
363     job->bitmap = hbitmap_alloc(end, 0);
364 
365     bdrv_set_enable_write_cache(target, true);
366     if (target->blk) {
367         blk_set_on_error(target->blk, on_target_error, on_target_error);
368         blk_iostatus_enable(target->blk);
369     }
370 
371     bdrv_add_before_write_notifier(bs, &before_write);
372 
373     if (job->sync_mode == MIRROR_SYNC_MODE_NONE) {
374         while (!block_job_is_cancelled(&job->common)) {
375             /* Yield until the job is cancelled.  We just let our before_write
376              * notify callback service CoW requests. */
377             job->common.busy = false;
378             qemu_coroutine_yield();
379             job->common.busy = true;
380         }
381     } else if (job->sync_mode == MIRROR_SYNC_MODE_INCREMENTAL) {
382         ret = backup_run_incremental(job);
383     } else {
384         /* Both FULL and TOP SYNC_MODE's require copying.. */
385         for (; start < end; start++) {
386             bool error_is_read;
387             if (yield_and_check(job)) {
388                 break;
389             }
390 
391             if (job->sync_mode == MIRROR_SYNC_MODE_TOP) {
392                 int i, n;
393                 int alloced = 0;
394 
395                 /* Check to see if these blocks are already in the
396                  * backing file. */
397 
398                 for (i = 0; i < BACKUP_SECTORS_PER_CLUSTER;) {
399                     /* bdrv_is_allocated() only returns true/false based
400                      * on the first set of sectors it comes across that
401                      * are are all in the same state.
402                      * For that reason we must verify each sector in the
403                      * backup cluster length.  We end up copying more than
404                      * needed but at some point that is always the case. */
405                     alloced =
406                         bdrv_is_allocated(bs,
407                                 start * BACKUP_SECTORS_PER_CLUSTER + i,
408                                 BACKUP_SECTORS_PER_CLUSTER - i, &n);
409                     i += n;
410 
411                     if (alloced == 1 || n == 0) {
412                         break;
413                     }
414                 }
415 
416                 /* If the above loop never found any sectors that are in
417                  * the topmost image, skip this backup. */
418                 if (alloced == 0) {
419                     continue;
420                 }
421             }
422             /* FULL sync mode we copy the whole drive. */
423             ret = backup_do_cow(bs, start * BACKUP_SECTORS_PER_CLUSTER,
424                     BACKUP_SECTORS_PER_CLUSTER, &error_is_read, false);
425             if (ret < 0) {
426                 /* Depending on error action, fail now or retry cluster */
427                 BlockErrorAction action =
428                     backup_error_action(job, error_is_read, -ret);
429                 if (action == BLOCK_ERROR_ACTION_REPORT) {
430                     break;
431                 } else {
432                     start--;
433                     continue;
434                 }
435             }
436         }
437     }
438 
439     notifier_with_return_remove(&before_write);
440 
441     /* wait until pending backup_do_cow() calls have completed */
442     qemu_co_rwlock_wrlock(&job->flush_rwlock);
443     qemu_co_rwlock_unlock(&job->flush_rwlock);
444 
445     if (job->sync_bitmap) {
446         BdrvDirtyBitmap *bm;
447         if (ret < 0 || block_job_is_cancelled(&job->common)) {
448             /* Merge the successor back into the parent, delete nothing. */
449             bm = bdrv_reclaim_dirty_bitmap(bs, job->sync_bitmap, NULL);
450             assert(bm);
451         } else {
452             /* Everything is fine, delete this bitmap and install the backup. */
453             bm = bdrv_dirty_bitmap_abdicate(bs, job->sync_bitmap, NULL);
454             assert(bm);
455         }
456     }
457     hbitmap_free(job->bitmap);
458 
459     if (target->blk) {
460         blk_iostatus_disable(target->blk);
461     }
462     bdrv_op_unblock_all(target, job->common.blocker);
463 
464     data = g_malloc(sizeof(*data));
465     data->ret = ret;
466     block_job_defer_to_main_loop(&job->common, backup_complete, data);
467 }
468 
469 void backup_start(BlockDriverState *bs, BlockDriverState *target,
470                   int64_t speed, MirrorSyncMode sync_mode,
471                   BdrvDirtyBitmap *sync_bitmap,
472                   BlockdevOnError on_source_error,
473                   BlockdevOnError on_target_error,
474                   BlockCompletionFunc *cb, void *opaque,
475                   Error **errp)
476 {
477     int64_t len;
478 
479     assert(bs);
480     assert(target);
481     assert(cb);
482 
483     if (bs == target) {
484         error_setg(errp, "Source and target cannot be the same");
485         return;
486     }
487 
488     if ((on_source_error == BLOCKDEV_ON_ERROR_STOP ||
489          on_source_error == BLOCKDEV_ON_ERROR_ENOSPC) &&
490         (!bs->blk || !blk_iostatus_is_enabled(bs->blk))) {
491         error_setg(errp, QERR_INVALID_PARAMETER, "on-source-error");
492         return;
493     }
494 
495     if (!bdrv_is_inserted(bs)) {
496         error_setg(errp, "Device is not inserted: %s",
497                    bdrv_get_device_name(bs));
498         return;
499     }
500 
501     if (!bdrv_is_inserted(target)) {
502         error_setg(errp, "Device is not inserted: %s",
503                    bdrv_get_device_name(target));
504         return;
505     }
506 
507     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
508         return;
509     }
510 
511     if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_BACKUP_TARGET, errp)) {
512         return;
513     }
514 
515     if (sync_mode == MIRROR_SYNC_MODE_INCREMENTAL) {
516         if (!sync_bitmap) {
517             error_setg(errp, "must provide a valid bitmap name for "
518                              "\"incremental\" sync mode");
519             return;
520         }
521 
522         /* Create a new bitmap, and freeze/disable this one. */
523         if (bdrv_dirty_bitmap_create_successor(bs, sync_bitmap, errp) < 0) {
524             return;
525         }
526     } else if (sync_bitmap) {
527         error_setg(errp,
528                    "a sync_bitmap was provided to backup_run, "
529                    "but received an incompatible sync_mode (%s)",
530                    MirrorSyncMode_lookup[sync_mode]);
531         return;
532     }
533 
534     len = bdrv_getlength(bs);
535     if (len < 0) {
536         error_setg_errno(errp, -len, "unable to get length for '%s'",
537                          bdrv_get_device_name(bs));
538         goto error;
539     }
540 
541     BackupBlockJob *job = block_job_create(&backup_job_driver, bs, speed,
542                                            cb, opaque, errp);
543     if (!job) {
544         goto error;
545     }
546 
547     bdrv_op_block_all(target, job->common.blocker);
548 
549     job->on_source_error = on_source_error;
550     job->on_target_error = on_target_error;
551     job->target = target;
552     job->sync_mode = sync_mode;
553     job->sync_bitmap = sync_mode == MIRROR_SYNC_MODE_INCREMENTAL ?
554                        sync_bitmap : NULL;
555     job->common.len = len;
556     job->common.co = qemu_coroutine_create(backup_run);
557     qemu_coroutine_enter(job->common.co, job);
558     return;
559 
560  error:
561     if (sync_bitmap) {
562         bdrv_reclaim_dirty_bitmap(bs, sync_bitmap, NULL);
563     }
564 }
565