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