OSDN Git Service

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