xref: /openbmc/qemu/block/stream.c (revision 6a094d62)
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 "qapi/qmp/qdict.h"
21 #include "qemu/ratelimit.h"
22 #include "sysemu/block-backend.h"
23 #include "block/copy-on-read.h"
24 
25 enum {
26     /*
27      * Maximum chunk size to feed to copy-on-read.  This should be
28      * large enough to process multiple clusters in a single call, so
29      * that populating contiguous regions of the image is efficient.
30      */
31     STREAM_CHUNK = 512 * 1024, /* in bytes */
32 };
33 
34 typedef struct StreamBlockJob {
35     BlockJob common;
36     BlockBackend *blk;
37     BlockDriverState *base_overlay; /* COW overlay (stream from this) */
38     BlockDriverState *above_base;   /* Node directly above the base */
39     BlockDriverState *cor_filter_bs;
40     BlockDriverState *target_bs;
41     BlockdevOnError on_error;
42     char *backing_file_str;
43     bool bs_read_only;
44 } StreamBlockJob;
45 
46 static int coroutine_fn stream_populate(BlockBackend *blk,
47                                         int64_t offset, uint64_t bytes)
48 {
49     assert(bytes < SIZE_MAX);
50 
51     return blk_co_preadv(blk, offset, bytes, NULL, BDRV_REQ_PREFETCH);
52 }
53 
54 static int stream_prepare(Job *job)
55 {
56     StreamBlockJob *s = container_of(job, StreamBlockJob, common.job);
57     BlockDriverState *unfiltered_bs = bdrv_skip_filters(s->target_bs);
58     BlockDriverState *base;
59     BlockDriverState *unfiltered_base;
60     Error *local_err = NULL;
61     int ret = 0;
62 
63     /* We should drop filter at this point, as filter hold the backing chain */
64     bdrv_cor_filter_drop(s->cor_filter_bs);
65     s->cor_filter_bs = NULL;
66 
67     base = bdrv_filter_or_cow_bs(s->above_base);
68     unfiltered_base = bdrv_skip_filters(base);
69 
70     if (bdrv_cow_child(unfiltered_bs)) {
71         const char *base_id = NULL, *base_fmt = NULL;
72         if (unfiltered_base) {
73             base_id = s->backing_file_str ?: unfiltered_base->filename;
74             if (unfiltered_base->drv) {
75                 base_fmt = unfiltered_base->drv->format_name;
76             }
77         }
78         bdrv_set_backing_hd(unfiltered_bs, base, &local_err);
79         ret = bdrv_change_backing_file(unfiltered_bs, base_id, base_fmt, false);
80         if (local_err) {
81             error_report_err(local_err);
82             return -EPERM;
83         }
84     }
85 
86     return ret;
87 }
88 
89 static void stream_clean(Job *job)
90 {
91     StreamBlockJob *s = container_of(job, StreamBlockJob, common.job);
92 
93     if (s->cor_filter_bs) {
94         bdrv_cor_filter_drop(s->cor_filter_bs);
95         s->cor_filter_bs = NULL;
96     }
97 
98     blk_unref(s->blk);
99     s->blk = NULL;
100 
101     /* Reopen the image back in read-only mode if necessary */
102     if (s->bs_read_only) {
103         /* Give up write permissions before making it read-only */
104         bdrv_reopen_set_read_only(s->target_bs, true, NULL);
105     }
106 
107     g_free(s->backing_file_str);
108 }
109 
110 static int coroutine_fn stream_run(Job *job, Error **errp)
111 {
112     StreamBlockJob *s = container_of(job, StreamBlockJob, common.job);
113     BlockDriverState *unfiltered_bs = bdrv_skip_filters(s->target_bs);
114     int64_t len;
115     int64_t offset = 0;
116     uint64_t delay_ns = 0;
117     int error = 0;
118     int64_t n = 0; /* bytes */
119 
120     if (unfiltered_bs == s->base_overlay) {
121         /* Nothing to stream */
122         return 0;
123     }
124 
125     len = bdrv_getlength(s->target_bs);
126     if (len < 0) {
127         return len;
128     }
129     job_progress_set_remaining(&s->common.job, len);
130 
131     for ( ; offset < len; offset += n) {
132         bool copy;
133         int ret;
134 
135         /* Note that even when no rate limit is applied we need to yield
136          * with no pending I/O here so that bdrv_drain_all() returns.
137          */
138         job_sleep_ns(&s->common.job, delay_ns);
139         if (job_is_cancelled(&s->common.job)) {
140             break;
141         }
142 
143         copy = false;
144 
145         ret = bdrv_is_allocated(unfiltered_bs, offset, STREAM_CHUNK, &n);
146         if (ret == 1) {
147             /* Allocated in the top, no need to copy.  */
148         } else if (ret >= 0) {
149             /* Copy if allocated in the intermediate images.  Limit to the
150              * known-unallocated area [offset, offset+n*BDRV_SECTOR_SIZE).  */
151             ret = bdrv_is_allocated_above(bdrv_cow_bs(unfiltered_bs),
152                                           s->base_overlay, true,
153                                           offset, n, &n);
154             /* Finish early if end of backing file has been reached */
155             if (ret == 0 && n == 0) {
156                 n = len - offset;
157             }
158 
159             copy = (ret > 0);
160         }
161         trace_stream_one_iteration(s, offset, n, ret);
162         if (copy) {
163             ret = stream_populate(s->blk, offset, n);
164         }
165         if (ret < 0) {
166             BlockErrorAction action =
167                 block_job_error_action(&s->common, s->on_error, true, -ret);
168             if (action == BLOCK_ERROR_ACTION_STOP) {
169                 n = 0;
170                 continue;
171             }
172             if (error == 0) {
173                 error = ret;
174             }
175             if (action == BLOCK_ERROR_ACTION_REPORT) {
176                 break;
177             }
178         }
179 
180         /* Publish progress */
181         job_progress_update(&s->common.job, n);
182         if (copy) {
183             delay_ns = block_job_ratelimit_get_delay(&s->common, n);
184         } else {
185             delay_ns = 0;
186         }
187     }
188 
189     /* Do not remove the backing file if an error was there but ignored. */
190     return error;
191 }
192 
193 static const BlockJobDriver stream_job_driver = {
194     .job_driver = {
195         .instance_size = sizeof(StreamBlockJob),
196         .job_type      = JOB_TYPE_STREAM,
197         .free          = block_job_free,
198         .run           = stream_run,
199         .prepare       = stream_prepare,
200         .clean         = stream_clean,
201         .user_resume   = block_job_user_resume,
202     },
203 };
204 
205 void stream_start(const char *job_id, BlockDriverState *bs,
206                   BlockDriverState *base, const char *backing_file_str,
207                   BlockDriverState *bottom,
208                   int creation_flags, int64_t speed,
209                   BlockdevOnError on_error,
210                   const char *filter_node_name,
211                   Error **errp)
212 {
213     StreamBlockJob *s = NULL;
214     BlockDriverState *iter;
215     bool bs_read_only;
216     int basic_flags = BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
217     BlockDriverState *base_overlay;
218     BlockDriverState *cor_filter_bs = NULL;
219     BlockDriverState *above_base;
220     QDict *opts;
221     int ret;
222 
223     assert(!(base && bottom));
224     assert(!(backing_file_str && bottom));
225 
226     if (bottom) {
227         /*
228          * New simple interface. The code is written in terms of old interface
229          * with @base parameter (still, it doesn't freeze link to base, so in
230          * this mean old code is correct for new interface). So, for now, just
231          * emulate base_overlay and above_base. Still, when old interface
232          * finally removed, we should refactor code to use only "bottom", but
233          * not "*base*" things.
234          */
235         assert(!bottom->drv->is_filter);
236         base_overlay = above_base = bottom;
237     } else {
238         base_overlay = bdrv_find_overlay(bs, base);
239         if (!base_overlay) {
240             error_setg(errp, "'%s' is not in the backing chain of '%s'",
241                        base->node_name, bs->node_name);
242             return;
243         }
244 
245         /*
246          * Find the node directly above @base.  @base_overlay is a COW overlay,
247          * so it must have a bdrv_cow_child(), but it is the immediate overlay
248          * of @base, so between the two there can only be filters.
249          */
250         above_base = base_overlay;
251         if (bdrv_cow_bs(above_base) != base) {
252             above_base = bdrv_cow_bs(above_base);
253             while (bdrv_filter_bs(above_base) != base) {
254                 above_base = bdrv_filter_bs(above_base);
255             }
256         }
257     }
258 
259     /* Make sure that the image is opened in read-write mode */
260     bs_read_only = bdrv_is_read_only(bs);
261     if (bs_read_only) {
262         int ret;
263         /* Hold the chain during reopen */
264         if (bdrv_freeze_backing_chain(bs, above_base, errp) < 0) {
265             return;
266         }
267 
268         ret = bdrv_reopen_set_read_only(bs, false, errp);
269 
270         /* failure, or cor-filter will hold the chain */
271         bdrv_unfreeze_backing_chain(bs, above_base);
272 
273         if (ret < 0) {
274             return;
275         }
276     }
277 
278     opts = qdict_new();
279 
280     qdict_put_str(opts, "driver", "copy-on-read");
281     qdict_put_str(opts, "file", bdrv_get_node_name(bs));
282     /* Pass the base_overlay node name as 'bottom' to COR driver */
283     qdict_put_str(opts, "bottom", base_overlay->node_name);
284     if (filter_node_name) {
285         qdict_put_str(opts, "node-name", filter_node_name);
286     }
287 
288     cor_filter_bs = bdrv_insert_node(bs, opts, BDRV_O_RDWR, errp);
289     if (!cor_filter_bs) {
290         goto fail;
291     }
292 
293     if (!filter_node_name) {
294         cor_filter_bs->implicit = true;
295     }
296 
297     s = block_job_create(job_id, &stream_job_driver, NULL, cor_filter_bs,
298                          0, BLK_PERM_ALL,
299                          speed, creation_flags, NULL, NULL, errp);
300     if (!s) {
301         goto fail;
302     }
303 
304     s->blk = blk_new_with_bs(cor_filter_bs, BLK_PERM_CONSISTENT_READ,
305                              basic_flags | BLK_PERM_WRITE, errp);
306     if (!s->blk) {
307         goto fail;
308     }
309     /*
310      * Disable request queuing in the BlockBackend to avoid deadlocks on drain:
311      * The job reports that it's busy until it reaches a pause point.
312      */
313     blk_set_disable_request_queuing(s->blk, true);
314     blk_set_allow_aio_context_change(s->blk, true);
315 
316     /*
317      * Prevent concurrent jobs trying to modify the graph structure here, we
318      * already have our own plans. Also don't allow resize as the image size is
319      * queried only at the job start and then cached.
320      */
321     if (block_job_add_bdrv(&s->common, "active node", bs, 0,
322                            basic_flags | BLK_PERM_WRITE, errp)) {
323         goto fail;
324     }
325 
326     /* Block all intermediate nodes between bs and base, because they will
327      * disappear from the chain after this operation. The streaming job reads
328      * every block only once, assuming that it doesn't change, so forbid writes
329      * and resizes. Reassign the base node pointer because the backing BS of the
330      * bottom node might change after the call to bdrv_reopen_set_read_only()
331      * due to parallel block jobs running.
332      * above_base node might change after the call to
333      * bdrv_reopen_set_read_only() due to parallel block jobs running.
334      */
335     base = bdrv_filter_or_cow_bs(above_base);
336     for (iter = bdrv_filter_or_cow_bs(bs); iter != base;
337          iter = bdrv_filter_or_cow_bs(iter))
338     {
339         ret = block_job_add_bdrv(&s->common, "intermediate node", iter, 0,
340                                  basic_flags, errp);
341         if (ret < 0) {
342             goto fail;
343         }
344     }
345 
346     s->base_overlay = base_overlay;
347     s->above_base = above_base;
348     s->backing_file_str = g_strdup(backing_file_str);
349     s->cor_filter_bs = cor_filter_bs;
350     s->target_bs = bs;
351     s->bs_read_only = bs_read_only;
352 
353     s->on_error = on_error;
354     trace_stream_start(bs, base, s);
355     job_start(&s->common.job);
356     return;
357 
358 fail:
359     if (s) {
360         job_early_fail(&s->common.job);
361     }
362     if (cor_filter_bs) {
363         bdrv_cor_filter_drop(cor_filter_bs);
364     }
365     if (bs_read_only) {
366         bdrv_reopen_set_read_only(bs, true, NULL);
367     }
368 }
369