xref: /openbmc/qemu/block/stream.c (revision 61f3c91a)
1 /*
2  * Image streaming
3  *
4  * Copyright IBM, Corp. 2011
5  *
6  * Authors:
7  *  Stefan Hajnoczi   <stefanha@linux.vnet.ibm.com>
8  *
9  * This work is licensed under the terms of the GNU LGPL, version 2 or later.
10  * See the COPYING.LIB file in the top-level directory.
11  *
12  */
13 
14 #include "qemu/osdep.h"
15 #include "trace.h"
16 #include "block/block_int.h"
17 #include "block/blockjob_int.h"
18 #include "qapi/error.h"
19 #include "qapi/qmp/qerror.h"
20 #include "qemu/ratelimit.h"
21 #include "sysemu/block-backend.h"
22 
23 enum {
24     /*
25      * Maximum chunk size to feed to copy-on-read.  This should be
26      * large enough to process multiple clusters in a single call, so
27      * that populating contiguous regions of the image is efficient.
28      */
29     STREAM_CHUNK = 512 * 1024, /* in bytes */
30 };
31 
32 typedef struct StreamBlockJob {
33     BlockJob common;
34     BlockDriverState *base_overlay; /* COW overlay (stream from this) */
35     BlockDriverState *above_base;   /* Node directly above the base */
36     BlockdevOnError on_error;
37     char *backing_file_str;
38     bool bs_read_only;
39     bool chain_frozen;
40 } StreamBlockJob;
41 
42 static int coroutine_fn stream_populate(BlockBackend *blk,
43                                         int64_t offset, uint64_t bytes)
44 {
45     assert(bytes < SIZE_MAX);
46 
47     return blk_co_preadv(blk, offset, bytes, NULL,
48                          BDRV_REQ_COPY_ON_READ | BDRV_REQ_PREFETCH);
49 }
50 
51 static void stream_abort(Job *job)
52 {
53     StreamBlockJob *s = container_of(job, StreamBlockJob, common.job);
54 
55     if (s->chain_frozen) {
56         BlockJob *bjob = &s->common;
57         bdrv_unfreeze_backing_chain(blk_bs(bjob->blk), s->above_base);
58     }
59 }
60 
61 static int stream_prepare(Job *job)
62 {
63     StreamBlockJob *s = container_of(job, StreamBlockJob, common.job);
64     BlockJob *bjob = &s->common;
65     BlockDriverState *bs = blk_bs(bjob->blk);
66     BlockDriverState *unfiltered_bs = bdrv_skip_filters(bs);
67     BlockDriverState *base = bdrv_filter_or_cow_bs(s->above_base);
68     Error *local_err = NULL;
69     int ret = 0;
70 
71     bdrv_unfreeze_backing_chain(bs, s->above_base);
72     s->chain_frozen = false;
73 
74     if (bdrv_cow_child(unfiltered_bs)) {
75         const char *base_id = NULL, *base_fmt = NULL;
76         if (base) {
77             base_id = s->backing_file_str;
78             if (base->drv) {
79                 base_fmt = base->drv->format_name;
80             }
81         }
82         bdrv_set_backing_hd(unfiltered_bs, base, &local_err);
83         ret = bdrv_change_backing_file(unfiltered_bs, base_id, base_fmt, false);
84         if (local_err) {
85             error_report_err(local_err);
86             return -EPERM;
87         }
88     }
89 
90     return ret;
91 }
92 
93 static void stream_clean(Job *job)
94 {
95     StreamBlockJob *s = container_of(job, StreamBlockJob, common.job);
96     BlockJob *bjob = &s->common;
97     BlockDriverState *bs = blk_bs(bjob->blk);
98 
99     /* Reopen the image back in read-only mode if necessary */
100     if (s->bs_read_only) {
101         /* Give up write permissions before making it read-only */
102         blk_set_perm(bjob->blk, 0, BLK_PERM_ALL, &error_abort);
103         bdrv_reopen_set_read_only(bs, true, NULL);
104     }
105 
106     g_free(s->backing_file_str);
107 }
108 
109 static int coroutine_fn stream_run(Job *job, Error **errp)
110 {
111     StreamBlockJob *s = container_of(job, StreamBlockJob, common.job);
112     BlockBackend *blk = s->common.blk;
113     BlockDriverState *bs = blk_bs(blk);
114     BlockDriverState *unfiltered_bs = bdrv_skip_filters(bs);
115     bool enable_cor = !bdrv_cow_child(s->base_overlay);
116     int64_t len;
117     int64_t offset = 0;
118     uint64_t delay_ns = 0;
119     int error = 0;
120     int64_t n = 0; /* bytes */
121 
122     if (unfiltered_bs == s->base_overlay) {
123         /* Nothing to stream */
124         return 0;
125     }
126 
127     len = bdrv_getlength(bs);
128     if (len < 0) {
129         return len;
130     }
131     job_progress_set_remaining(&s->common.job, len);
132 
133     /* Turn on copy-on-read for the whole block device so that guest read
134      * requests help us make progress.  Only do this when copying the entire
135      * backing chain since the copy-on-read operation does not take base into
136      * account.
137      */
138     if (enable_cor) {
139         bdrv_enable_copy_on_read(bs);
140     }
141 
142     for ( ; offset < len; offset += n) {
143         bool copy;
144         int ret;
145 
146         /* Note that even when no rate limit is applied we need to yield
147          * with no pending I/O here so that bdrv_drain_all() returns.
148          */
149         job_sleep_ns(&s->common.job, delay_ns);
150         if (job_is_cancelled(&s->common.job)) {
151             break;
152         }
153 
154         copy = false;
155 
156         ret = bdrv_is_allocated(unfiltered_bs, offset, STREAM_CHUNK, &n);
157         if (ret == 1) {
158             /* Allocated in the top, no need to copy.  */
159         } else if (ret >= 0) {
160             /* Copy if allocated in the intermediate images.  Limit to the
161              * known-unallocated area [offset, offset+n*BDRV_SECTOR_SIZE).  */
162             ret = bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs),
163                                           s->base_overlay, true,
164                                           offset, n, &n);
165             /* Finish early if end of backing file has been reached */
166             if (ret == 0 && n == 0) {
167                 n = len - offset;
168             }
169 
170             copy = (ret > 0);
171         }
172         trace_stream_one_iteration(s, offset, n, ret);
173         if (copy) {
174             ret = stream_populate(blk, offset, n);
175         }
176         if (ret < 0) {
177             BlockErrorAction action =
178                 block_job_error_action(&s->common, s->on_error, true, -ret);
179             if (action == BLOCK_ERROR_ACTION_STOP) {
180                 n = 0;
181                 continue;
182             }
183             if (error == 0) {
184                 error = ret;
185             }
186             if (action == BLOCK_ERROR_ACTION_REPORT) {
187                 break;
188             }
189         }
190 
191         /* Publish progress */
192         job_progress_update(&s->common.job, n);
193         if (copy) {
194             delay_ns = block_job_ratelimit_get_delay(&s->common, n);
195         } else {
196             delay_ns = 0;
197         }
198     }
199 
200     if (enable_cor) {
201         bdrv_disable_copy_on_read(bs);
202     }
203 
204     /* Do not remove the backing file if an error was there but ignored. */
205     return error;
206 }
207 
208 static const BlockJobDriver stream_job_driver = {
209     .job_driver = {
210         .instance_size = sizeof(StreamBlockJob),
211         .job_type      = JOB_TYPE_STREAM,
212         .free          = block_job_free,
213         .run           = stream_run,
214         .prepare       = stream_prepare,
215         .abort         = stream_abort,
216         .clean         = stream_clean,
217         .user_resume   = block_job_user_resume,
218     },
219 };
220 
221 void stream_start(const char *job_id, BlockDriverState *bs,
222                   BlockDriverState *base, const char *backing_file_str,
223                   int creation_flags, int64_t speed,
224                   BlockdevOnError on_error, Error **errp)
225 {
226     StreamBlockJob *s;
227     BlockDriverState *iter;
228     bool bs_read_only;
229     int basic_flags = BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
230     BlockDriverState *base_overlay = bdrv_find_overlay(bs, base);
231     BlockDriverState *above_base;
232 
233     if (!base_overlay) {
234         error_setg(errp, "'%s' is not in the backing chain of '%s'",
235                    base->node_name, bs->node_name);
236         return;
237     }
238 
239     /*
240      * Find the node directly above @base.  @base_overlay is a COW overlay, so
241      * it must have a bdrv_cow_child(), but it is the immediate overlay of
242      * @base, so between the two there can only be filters.
243      */
244     above_base = base_overlay;
245     if (bdrv_cow_bs(above_base) != base) {
246         above_base = bdrv_cow_bs(above_base);
247         while (bdrv_filter_bs(above_base) != base) {
248             above_base = bdrv_filter_bs(above_base);
249         }
250     }
251 
252     if (bdrv_freeze_backing_chain(bs, above_base, errp) < 0) {
253         return;
254     }
255 
256     /* Make sure that the image is opened in read-write mode */
257     bs_read_only = bdrv_is_read_only(bs);
258     if (bs_read_only) {
259         if (bdrv_reopen_set_read_only(bs, false, errp) != 0) {
260             bs_read_only = false;
261             goto fail;
262         }
263     }
264 
265     /* Prevent concurrent jobs trying to modify the graph structure here, we
266      * already have our own plans. Also don't allow resize as the image size is
267      * queried only at the job start and then cached. */
268     s = block_job_create(job_id, &stream_job_driver, NULL, bs,
269                          basic_flags | BLK_PERM_GRAPH_MOD,
270                          basic_flags | BLK_PERM_WRITE,
271                          speed, creation_flags, NULL, NULL, errp);
272     if (!s) {
273         goto fail;
274     }
275 
276     /* Block all intermediate nodes between bs and base, because they will
277      * disappear from the chain after this operation. The streaming job reads
278      * every block only once, assuming that it doesn't change, so forbid writes
279      * and resizes. Reassign the base node pointer because the backing BS of the
280      * bottom node might change after the call to bdrv_reopen_set_read_only()
281      * due to parallel block jobs running.
282      * above_base node might change after the call to
283      * bdrv_reopen_set_read_only() due to parallel block jobs running.
284      */
285     base = bdrv_filter_or_cow_bs(above_base);
286     for (iter = bdrv_filter_or_cow_bs(bs); iter != base;
287          iter = bdrv_filter_or_cow_bs(iter))
288     {
289         block_job_add_bdrv(&s->common, "intermediate node", iter, 0,
290                            basic_flags, &error_abort);
291     }
292 
293     s->base_overlay = base_overlay;
294     s->above_base = above_base;
295     s->backing_file_str = g_strdup(backing_file_str);
296     s->bs_read_only = bs_read_only;
297     s->chain_frozen = true;
298 
299     s->on_error = on_error;
300     trace_stream_start(bs, base, s);
301     job_start(&s->common.job);
302     return;
303 
304 fail:
305     if (bs_read_only) {
306         bdrv_reopen_set_read_only(bs, true, NULL);
307     }
308     bdrv_unfreeze_backing_chain(bs, above_base);
309 }
310