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