xref: /qemu/block/backup.c (revision d1f3a23b)
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 "qemu/ratelimit.h"
23 
24 #define BACKUP_CLUSTER_BITS 16
25 #define BACKUP_CLUSTER_SIZE (1 << BACKUP_CLUSTER_BITS)
26 #define BACKUP_SECTORS_PER_CLUSTER (BACKUP_CLUSTER_SIZE / BDRV_SECTOR_SIZE)
27 
28 #define SLICE_TIME 100000000ULL /* ns */
29 
30 typedef struct CowRequest {
31     int64_t start;
32     int64_t end;
33     QLIST_ENTRY(CowRequest) list;
34     CoQueue wait_queue; /* coroutines blocked on this request */
35 } CowRequest;
36 
37 typedef struct BackupBlockJob {
38     BlockJob common;
39     BlockDriverState *target;
40     MirrorSyncMode sync_mode;
41     RateLimit limit;
42     BlockdevOnError on_source_error;
43     BlockdevOnError on_target_error;
44     CoRwlock flush_rwlock;
45     uint64_t sectors_read;
46     HBitmap *bitmap;
47     QLIST_HEAD(, CowRequest) inflight_reqs;
48 } BackupBlockJob;
49 
50 /* See if in-flight requests overlap and wait for them to complete */
51 static void coroutine_fn wait_for_overlapping_requests(BackupBlockJob *job,
52                                                        int64_t start,
53                                                        int64_t end)
54 {
55     CowRequest *req;
56     bool retry;
57 
58     do {
59         retry = false;
60         QLIST_FOREACH(req, &job->inflight_reqs, list) {
61             if (end > req->start && start < req->end) {
62                 qemu_co_queue_wait(&req->wait_queue);
63                 retry = true;
64                 break;
65             }
66         }
67     } while (retry);
68 }
69 
70 /* Keep track of an in-flight request */
71 static void cow_request_begin(CowRequest *req, BackupBlockJob *job,
72                                      int64_t start, int64_t end)
73 {
74     req->start = start;
75     req->end = end;
76     qemu_co_queue_init(&req->wait_queue);
77     QLIST_INSERT_HEAD(&job->inflight_reqs, req, list);
78 }
79 
80 /* Forget about a completed request */
81 static void cow_request_end(CowRequest *req)
82 {
83     QLIST_REMOVE(req, list);
84     qemu_co_queue_restart_all(&req->wait_queue);
85 }
86 
87 static int coroutine_fn backup_do_cow(BlockDriverState *bs,
88                                       int64_t sector_num, int nb_sectors,
89                                       bool *error_is_read)
90 {
91     BackupBlockJob *job = (BackupBlockJob *)bs->job;
92     CowRequest cow_request;
93     struct iovec iov;
94     QEMUIOVector bounce_qiov;
95     void *bounce_buffer = NULL;
96     int ret = 0;
97     int64_t start, end;
98     int n;
99 
100     qemu_co_rwlock_rdlock(&job->flush_rwlock);
101 
102     start = sector_num / BACKUP_SECTORS_PER_CLUSTER;
103     end = DIV_ROUND_UP(sector_num + nb_sectors, BACKUP_SECTORS_PER_CLUSTER);
104 
105     trace_backup_do_cow_enter(job, start, sector_num, nb_sectors);
106 
107     wait_for_overlapping_requests(job, start, end);
108     cow_request_begin(&cow_request, job, start, end);
109 
110     for (; start < end; start++) {
111         if (hbitmap_get(job->bitmap, start)) {
112             trace_backup_do_cow_skip(job, start);
113             continue; /* already copied */
114         }
115 
116         trace_backup_do_cow_process(job, start);
117 
118         n = MIN(BACKUP_SECTORS_PER_CLUSTER,
119                 job->common.len / BDRV_SECTOR_SIZE -
120                 start * BACKUP_SECTORS_PER_CLUSTER);
121 
122         if (!bounce_buffer) {
123             bounce_buffer = qemu_blockalign(bs, BACKUP_CLUSTER_SIZE);
124         }
125         iov.iov_base = bounce_buffer;
126         iov.iov_len = n * BDRV_SECTOR_SIZE;
127         qemu_iovec_init_external(&bounce_qiov, &iov, 1);
128 
129         ret = bdrv_co_readv(bs, start * BACKUP_SECTORS_PER_CLUSTER, n,
130                             &bounce_qiov);
131         if (ret < 0) {
132             trace_backup_do_cow_read_fail(job, start, ret);
133             if (error_is_read) {
134                 *error_is_read = true;
135             }
136             goto out;
137         }
138 
139         if (buffer_is_zero(iov.iov_base, iov.iov_len)) {
140             ret = bdrv_co_write_zeroes(job->target,
141                                        start * BACKUP_SECTORS_PER_CLUSTER, n);
142         } else {
143             ret = bdrv_co_writev(job->target,
144                                  start * BACKUP_SECTORS_PER_CLUSTER, n,
145                                  &bounce_qiov);
146         }
147         if (ret < 0) {
148             trace_backup_do_cow_write_fail(job, start, ret);
149             if (error_is_read) {
150                 *error_is_read = false;
151             }
152             goto out;
153         }
154 
155         hbitmap_set(job->bitmap, start, 1);
156 
157         /* Publish progress, guest I/O counts as progress too.  Note that the
158          * offset field is an opaque progress value, it is not a disk offset.
159          */
160         job->sectors_read += n;
161         job->common.offset += n * BDRV_SECTOR_SIZE;
162     }
163 
164 out:
165     if (bounce_buffer) {
166         qemu_vfree(bounce_buffer);
167     }
168 
169     cow_request_end(&cow_request);
170 
171     trace_backup_do_cow_return(job, sector_num, nb_sectors, ret);
172 
173     qemu_co_rwlock_unlock(&job->flush_rwlock);
174 
175     return ret;
176 }
177 
178 static int coroutine_fn backup_before_write_notify(
179         NotifierWithReturn *notifier,
180         void *opaque)
181 {
182     BdrvTrackedRequest *req = opaque;
183 
184     return backup_do_cow(req->bs, req->sector_num, req->nb_sectors, NULL);
185 }
186 
187 static void backup_set_speed(BlockJob *job, int64_t speed, Error **errp)
188 {
189     BackupBlockJob *s = container_of(job, BackupBlockJob, common);
190 
191     if (speed < 0) {
192         error_set(errp, QERR_INVALID_PARAMETER, "speed");
193         return;
194     }
195     ratelimit_set_speed(&s->limit, speed / BDRV_SECTOR_SIZE, SLICE_TIME);
196 }
197 
198 static void backup_iostatus_reset(BlockJob *job)
199 {
200     BackupBlockJob *s = container_of(job, BackupBlockJob, common);
201 
202     bdrv_iostatus_reset(s->target);
203 }
204 
205 static const BlockJobDriver backup_job_driver = {
206     .instance_size  = sizeof(BackupBlockJob),
207     .job_type       = BLOCK_JOB_TYPE_BACKUP,
208     .set_speed      = backup_set_speed,
209     .iostatus_reset = backup_iostatus_reset,
210 };
211 
212 static BlockErrorAction backup_error_action(BackupBlockJob *job,
213                                             bool read, int error)
214 {
215     if (read) {
216         return block_job_error_action(&job->common, job->common.bs,
217                                       job->on_source_error, true, error);
218     } else {
219         return block_job_error_action(&job->common, job->target,
220                                       job->on_target_error, false, error);
221     }
222 }
223 
224 static void coroutine_fn backup_run(void *opaque)
225 {
226     BackupBlockJob *job = opaque;
227     BlockDriverState *bs = job->common.bs;
228     BlockDriverState *target = job->target;
229     BlockdevOnError on_target_error = job->on_target_error;
230     NotifierWithReturn before_write = {
231         .notify = backup_before_write_notify,
232     };
233     int64_t start, end;
234     int ret = 0;
235 
236     QLIST_INIT(&job->inflight_reqs);
237     qemu_co_rwlock_init(&job->flush_rwlock);
238 
239     start = 0;
240     end = DIV_ROUND_UP(job->common.len / BDRV_SECTOR_SIZE,
241                        BACKUP_SECTORS_PER_CLUSTER);
242 
243     job->bitmap = hbitmap_alloc(end, 0);
244 
245     bdrv_set_enable_write_cache(target, true);
246     bdrv_set_on_error(target, on_target_error, on_target_error);
247     bdrv_iostatus_enable(target);
248 
249     bdrv_add_before_write_notifier(bs, &before_write);
250 
251     if (job->sync_mode == MIRROR_SYNC_MODE_NONE) {
252         while (!block_job_is_cancelled(&job->common)) {
253             /* Yield until the job is cancelled.  We just let our before_write
254              * notify callback service CoW requests. */
255             job->common.busy = false;
256             qemu_coroutine_yield();
257             job->common.busy = true;
258         }
259     } else {
260         /* Both FULL and TOP SYNC_MODE's require copying.. */
261         for (; start < end; start++) {
262             bool error_is_read;
263 
264             if (block_job_is_cancelled(&job->common)) {
265                 break;
266             }
267 
268             /* we need to yield so that qemu_aio_flush() returns.
269              * (without, VM does not reboot)
270              */
271             if (job->common.speed) {
272                 uint64_t delay_ns = ratelimit_calculate_delay(
273                         &job->limit, job->sectors_read);
274                 job->sectors_read = 0;
275                 block_job_sleep_ns(&job->common, QEMU_CLOCK_REALTIME, delay_ns);
276             } else {
277                 block_job_sleep_ns(&job->common, QEMU_CLOCK_REALTIME, 0);
278             }
279 
280             if (block_job_is_cancelled(&job->common)) {
281                 break;
282             }
283 
284             if (job->sync_mode == MIRROR_SYNC_MODE_TOP) {
285                 int i, n;
286                 int alloced = 0;
287 
288                 /* Check to see if these blocks are already in the
289                  * backing file. */
290 
291                 for (i = 0; i < BACKUP_SECTORS_PER_CLUSTER;) {
292                     /* bdrv_is_allocated() only returns true/false based
293                      * on the first set of sectors it comes across that
294                      * are are all in the same state.
295                      * For that reason we must verify each sector in the
296                      * backup cluster length.  We end up copying more than
297                      * needed but at some point that is always the case. */
298                     alloced =
299                         bdrv_is_allocated(bs,
300                                 start * BACKUP_SECTORS_PER_CLUSTER + i,
301                                 BACKUP_SECTORS_PER_CLUSTER - i, &n);
302                     i += n;
303 
304                     if (alloced == 1) {
305                         break;
306                     }
307                 }
308 
309                 /* If the above loop never found any sectors that are in
310                  * the topmost image, skip this backup. */
311                 if (alloced == 0) {
312                     continue;
313                 }
314             }
315             /* FULL sync mode we copy the whole drive. */
316             ret = backup_do_cow(bs, start * BACKUP_SECTORS_PER_CLUSTER,
317                     BACKUP_SECTORS_PER_CLUSTER, &error_is_read);
318             if (ret < 0) {
319                 /* Depending on error action, fail now or retry cluster */
320                 BlockErrorAction action =
321                     backup_error_action(job, error_is_read, -ret);
322                 if (action == BDRV_ACTION_REPORT) {
323                     break;
324                 } else {
325                     start--;
326                     continue;
327                 }
328             }
329         }
330     }
331 
332     notifier_with_return_remove(&before_write);
333 
334     /* wait until pending backup_do_cow() calls have completed */
335     qemu_co_rwlock_wrlock(&job->flush_rwlock);
336     qemu_co_rwlock_unlock(&job->flush_rwlock);
337 
338     hbitmap_free(job->bitmap);
339 
340     bdrv_iostatus_disable(target);
341     bdrv_unref(target);
342 
343     block_job_completed(&job->common, ret);
344 }
345 
346 void backup_start(BlockDriverState *bs, BlockDriverState *target,
347                   int64_t speed, MirrorSyncMode sync_mode,
348                   BlockdevOnError on_source_error,
349                   BlockdevOnError on_target_error,
350                   BlockDriverCompletionFunc *cb, void *opaque,
351                   Error **errp)
352 {
353     int64_t len;
354 
355     assert(bs);
356     assert(target);
357     assert(cb);
358 
359     if ((on_source_error == BLOCKDEV_ON_ERROR_STOP ||
360          on_source_error == BLOCKDEV_ON_ERROR_ENOSPC) &&
361         !bdrv_iostatus_is_enabled(bs)) {
362         error_set(errp, QERR_INVALID_PARAMETER, "on-source-error");
363         return;
364     }
365 
366     len = bdrv_getlength(bs);
367     if (len < 0) {
368         error_setg_errno(errp, -len, "unable to get length for '%s'",
369                          bdrv_get_device_name(bs));
370         return;
371     }
372 
373     BackupBlockJob *job = block_job_create(&backup_job_driver, bs, speed,
374                                            cb, opaque, errp);
375     if (!job) {
376         return;
377     }
378 
379     job->on_source_error = on_source_error;
380     job->on_target_error = on_target_error;
381     job->target = target;
382     job->sync_mode = sync_mode;
383     job->common.len = len;
384     job->common.co = qemu_coroutine_create(backup_run);
385     qemu_coroutine_enter(job->common.co, job);
386 }
387