OSDN Git Service

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