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