]> Git Repo - qemu.git/blob - block/mirror.c
mirror: double performance of the bulk stage if the disc is full
[qemu.git] / block / mirror.c
1 /*
2  * Image mirroring
3  *
4  * Copyright Red Hat, Inc. 2012
5  *
6  * Authors:
7  *  Paolo Bonzini  <[email protected]>
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/blockjob.h"
17 #include "block/block_int.h"
18 #include "sysemu/block-backend.h"
19 #include "qapi/error.h"
20 #include "qapi/qmp/qerror.h"
21 #include "qemu/ratelimit.h"
22 #include "qemu/bitmap.h"
23
24 #define SLICE_TIME    100000000ULL /* ns */
25 #define MAX_IN_FLIGHT 16
26 #define MAX_IO_SECTORS ((1 << 20) >> BDRV_SECTOR_BITS) /* 1 Mb */
27 #define DEFAULT_MIRROR_BUF_SIZE \
28     (MAX_IN_FLIGHT * MAX_IO_SECTORS * BDRV_SECTOR_SIZE)
29
30 /* The mirroring buffer is a list of granularity-sized chunks.
31  * Free chunks are organized in a list.
32  */
33 typedef struct MirrorBuffer {
34     QSIMPLEQ_ENTRY(MirrorBuffer) next;
35 } MirrorBuffer;
36
37 typedef struct MirrorBlockJob {
38     BlockJob common;
39     RateLimit limit;
40     BlockBackend *target;
41     BlockDriverState *base;
42     /* The name of the graph node to replace */
43     char *replaces;
44     /* The BDS to replace */
45     BlockDriverState *to_replace;
46     /* Used to block operations on the drive-mirror-replace target */
47     Error *replace_blocker;
48     bool is_none_mode;
49     BlockMirrorBackingMode backing_mode;
50     BlockdevOnError on_source_error, on_target_error;
51     bool synced;
52     bool should_complete;
53     int64_t granularity;
54     size_t buf_size;
55     int64_t bdev_length;
56     unsigned long *cow_bitmap;
57     BdrvDirtyBitmap *dirty_bitmap;
58     HBitmapIter hbi;
59     uint8_t *buf;
60     QSIMPLEQ_HEAD(, MirrorBuffer) buf_free;
61     int buf_free_count;
62
63     uint64_t last_pause_ns;
64     unsigned long *in_flight_bitmap;
65     int in_flight;
66     int64_t sectors_in_flight;
67     int ret;
68     bool unmap;
69     bool waiting_for_io;
70     int target_cluster_sectors;
71     int max_iov;
72 } MirrorBlockJob;
73
74 typedef struct MirrorOp {
75     MirrorBlockJob *s;
76     QEMUIOVector qiov;
77     int64_t sector_num;
78     int nb_sectors;
79 } MirrorOp;
80
81 static BlockErrorAction mirror_error_action(MirrorBlockJob *s, bool read,
82                                             int error)
83 {
84     s->synced = false;
85     if (read) {
86         return block_job_error_action(&s->common, s->on_source_error,
87                                       true, error);
88     } else {
89         return block_job_error_action(&s->common, s->on_target_error,
90                                       false, error);
91     }
92 }
93
94 static void mirror_iteration_done(MirrorOp *op, int ret)
95 {
96     MirrorBlockJob *s = op->s;
97     struct iovec *iov;
98     int64_t chunk_num;
99     int i, nb_chunks, sectors_per_chunk;
100
101     trace_mirror_iteration_done(s, op->sector_num, op->nb_sectors, ret);
102
103     s->in_flight--;
104     s->sectors_in_flight -= op->nb_sectors;
105     iov = op->qiov.iov;
106     for (i = 0; i < op->qiov.niov; i++) {
107         MirrorBuffer *buf = (MirrorBuffer *) iov[i].iov_base;
108         QSIMPLEQ_INSERT_TAIL(&s->buf_free, buf, next);
109         s->buf_free_count++;
110     }
111
112     sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
113     chunk_num = op->sector_num / sectors_per_chunk;
114     nb_chunks = DIV_ROUND_UP(op->nb_sectors, sectors_per_chunk);
115     bitmap_clear(s->in_flight_bitmap, chunk_num, nb_chunks);
116     if (ret >= 0) {
117         if (s->cow_bitmap) {
118             bitmap_set(s->cow_bitmap, chunk_num, nb_chunks);
119         }
120         s->common.offset += (uint64_t)op->nb_sectors * BDRV_SECTOR_SIZE;
121     }
122
123     qemu_iovec_destroy(&op->qiov);
124     g_free(op);
125
126     if (s->waiting_for_io) {
127         qemu_coroutine_enter(s->common.co);
128     }
129 }
130
131 static void mirror_write_complete(void *opaque, int ret)
132 {
133     MirrorOp *op = opaque;
134     MirrorBlockJob *s = op->s;
135     if (ret < 0) {
136         BlockErrorAction action;
137
138         bdrv_set_dirty_bitmap(s->dirty_bitmap, op->sector_num, op->nb_sectors);
139         action = mirror_error_action(s, false, -ret);
140         if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
141             s->ret = ret;
142         }
143     }
144     mirror_iteration_done(op, ret);
145 }
146
147 static void mirror_read_complete(void *opaque, int ret)
148 {
149     MirrorOp *op = opaque;
150     MirrorBlockJob *s = op->s;
151     if (ret < 0) {
152         BlockErrorAction action;
153
154         bdrv_set_dirty_bitmap(s->dirty_bitmap, op->sector_num, op->nb_sectors);
155         action = mirror_error_action(s, true, -ret);
156         if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
157             s->ret = ret;
158         }
159
160         mirror_iteration_done(op, ret);
161         return;
162     }
163     blk_aio_pwritev(s->target, op->sector_num * BDRV_SECTOR_SIZE, &op->qiov,
164                     0, mirror_write_complete, op);
165 }
166
167 static inline void mirror_clip_sectors(MirrorBlockJob *s,
168                                        int64_t sector_num,
169                                        int *nb_sectors)
170 {
171     *nb_sectors = MIN(*nb_sectors,
172                       s->bdev_length / BDRV_SECTOR_SIZE - sector_num);
173 }
174
175 /* Round sector_num and/or nb_sectors to target cluster if COW is needed, and
176  * return the offset of the adjusted tail sector against original. */
177 static int mirror_cow_align(MirrorBlockJob *s,
178                             int64_t *sector_num,
179                             int *nb_sectors)
180 {
181     bool need_cow;
182     int ret = 0;
183     int chunk_sectors = s->granularity >> BDRV_SECTOR_BITS;
184     int64_t align_sector_num = *sector_num;
185     int align_nb_sectors = *nb_sectors;
186     int max_sectors = chunk_sectors * s->max_iov;
187
188     need_cow = !test_bit(*sector_num / chunk_sectors, s->cow_bitmap);
189     need_cow |= !test_bit((*sector_num + *nb_sectors - 1) / chunk_sectors,
190                           s->cow_bitmap);
191     if (need_cow) {
192         bdrv_round_sectors_to_clusters(blk_bs(s->target), *sector_num,
193                                        *nb_sectors, &align_sector_num,
194                                        &align_nb_sectors);
195     }
196
197     if (align_nb_sectors > max_sectors) {
198         align_nb_sectors = max_sectors;
199         if (need_cow) {
200             align_nb_sectors = QEMU_ALIGN_DOWN(align_nb_sectors,
201                                                s->target_cluster_sectors);
202         }
203     }
204     /* Clipping may result in align_nb_sectors unaligned to chunk boundary, but
205      * that doesn't matter because it's already the end of source image. */
206     mirror_clip_sectors(s, align_sector_num, &align_nb_sectors);
207
208     ret = align_sector_num + align_nb_sectors - (*sector_num + *nb_sectors);
209     *sector_num = align_sector_num;
210     *nb_sectors = align_nb_sectors;
211     assert(ret >= 0);
212     return ret;
213 }
214
215 static inline void mirror_wait_for_io(MirrorBlockJob *s)
216 {
217     assert(!s->waiting_for_io);
218     s->waiting_for_io = true;
219     qemu_coroutine_yield();
220     s->waiting_for_io = false;
221 }
222
223 /* Submit async read while handling COW.
224  * Returns: The number of sectors copied after and including sector_num,
225  *          excluding any sectors copied prior to sector_num due to alignment.
226  *          This will be nb_sectors if no alignment is necessary, or
227  *          (new_end - sector_num) if tail is rounded up or down due to
228  *          alignment or buffer limit.
229  */
230 static int mirror_do_read(MirrorBlockJob *s, int64_t sector_num,
231                           int nb_sectors)
232 {
233     BlockBackend *source = s->common.blk;
234     int sectors_per_chunk, nb_chunks;
235     int ret;
236     MirrorOp *op;
237     int max_sectors;
238
239     sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
240     max_sectors = sectors_per_chunk * s->max_iov;
241
242     /* We can only handle as much as buf_size at a time. */
243     nb_sectors = MIN(s->buf_size >> BDRV_SECTOR_BITS, nb_sectors);
244     nb_sectors = MIN(max_sectors, nb_sectors);
245     assert(nb_sectors);
246     ret = nb_sectors;
247
248     if (s->cow_bitmap) {
249         ret += mirror_cow_align(s, &sector_num, &nb_sectors);
250     }
251     assert(nb_sectors << BDRV_SECTOR_BITS <= s->buf_size);
252     /* The sector range must meet granularity because:
253      * 1) Caller passes in aligned values;
254      * 2) mirror_cow_align is used only when target cluster is larger. */
255     assert(!(sector_num % sectors_per_chunk));
256     nb_chunks = DIV_ROUND_UP(nb_sectors, sectors_per_chunk);
257
258     while (s->buf_free_count < nb_chunks) {
259         trace_mirror_yield_in_flight(s, sector_num, s->in_flight);
260         mirror_wait_for_io(s);
261     }
262
263     /* Allocate a MirrorOp that is used as an AIO callback.  */
264     op = g_new(MirrorOp, 1);
265     op->s = s;
266     op->sector_num = sector_num;
267     op->nb_sectors = nb_sectors;
268
269     /* Now make a QEMUIOVector taking enough granularity-sized chunks
270      * from s->buf_free.
271      */
272     qemu_iovec_init(&op->qiov, nb_chunks);
273     while (nb_chunks-- > 0) {
274         MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);
275         size_t remaining = nb_sectors * BDRV_SECTOR_SIZE - op->qiov.size;
276
277         QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);
278         s->buf_free_count--;
279         qemu_iovec_add(&op->qiov, buf, MIN(s->granularity, remaining));
280     }
281
282     /* Copy the dirty cluster.  */
283     s->in_flight++;
284     s->sectors_in_flight += nb_sectors;
285     trace_mirror_one_iteration(s, sector_num, nb_sectors);
286
287     blk_aio_preadv(source, sector_num * BDRV_SECTOR_SIZE, &op->qiov, 0,
288                    mirror_read_complete, op);
289     return ret;
290 }
291
292 static void mirror_do_zero_or_discard(MirrorBlockJob *s,
293                                       int64_t sector_num,
294                                       int nb_sectors,
295                                       bool is_discard)
296 {
297     MirrorOp *op;
298
299     /* Allocate a MirrorOp that is used as an AIO callback. The qiov is zeroed
300      * so the freeing in mirror_iteration_done is nop. */
301     op = g_new0(MirrorOp, 1);
302     op->s = s;
303     op->sector_num = sector_num;
304     op->nb_sectors = nb_sectors;
305
306     s->in_flight++;
307     s->sectors_in_flight += nb_sectors;
308     if (is_discard) {
309         blk_aio_pdiscard(s->target, sector_num << BDRV_SECTOR_BITS,
310                          op->nb_sectors << BDRV_SECTOR_BITS,
311                          mirror_write_complete, op);
312     } else {
313         blk_aio_pwrite_zeroes(s->target, sector_num * BDRV_SECTOR_SIZE,
314                               op->nb_sectors * BDRV_SECTOR_SIZE,
315                               s->unmap ? BDRV_REQ_MAY_UNMAP : 0,
316                               mirror_write_complete, op);
317     }
318 }
319
320 static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)
321 {
322     BlockDriverState *source = blk_bs(s->common.blk);
323     int64_t sector_num, first_chunk;
324     uint64_t delay_ns = 0;
325     /* At least the first dirty chunk is mirrored in one iteration. */
326     int nb_chunks = 1;
327     int64_t end = s->bdev_length / BDRV_SECTOR_SIZE;
328     int sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
329     bool write_zeroes_ok = bdrv_can_write_zeroes_with_unmap(blk_bs(s->target));
330     int max_io_sectors = MAX((s->buf_size >> BDRV_SECTOR_BITS) / MAX_IN_FLIGHT,
331                              MAX_IO_SECTORS);
332
333     sector_num = hbitmap_iter_next(&s->hbi);
334     if (sector_num < 0) {
335         bdrv_dirty_iter_init(s->dirty_bitmap, &s->hbi);
336         sector_num = hbitmap_iter_next(&s->hbi);
337         trace_mirror_restart_iter(s, bdrv_get_dirty_count(s->dirty_bitmap));
338         assert(sector_num >= 0);
339     }
340
341     first_chunk = sector_num / sectors_per_chunk;
342     while (test_bit(first_chunk, s->in_flight_bitmap)) {
343         trace_mirror_yield_in_flight(s, sector_num, s->in_flight);
344         mirror_wait_for_io(s);
345     }
346
347     block_job_pause_point(&s->common);
348
349     /* Find the number of consective dirty chunks following the first dirty
350      * one, and wait for in flight requests in them. */
351     while (nb_chunks * sectors_per_chunk < (s->buf_size >> BDRV_SECTOR_BITS)) {
352         int64_t hbitmap_next;
353         int64_t next_sector = sector_num + nb_chunks * sectors_per_chunk;
354         int64_t next_chunk = next_sector / sectors_per_chunk;
355         if (next_sector >= end ||
356             !bdrv_get_dirty(source, s->dirty_bitmap, next_sector)) {
357             break;
358         }
359         if (test_bit(next_chunk, s->in_flight_bitmap)) {
360             break;
361         }
362
363         hbitmap_next = hbitmap_iter_next(&s->hbi);
364         if (hbitmap_next > next_sector || hbitmap_next < 0) {
365             /* The bitmap iterator's cache is stale, refresh it */
366             bdrv_set_dirty_iter(&s->hbi, next_sector);
367             hbitmap_next = hbitmap_iter_next(&s->hbi);
368         }
369         assert(hbitmap_next == next_sector);
370         nb_chunks++;
371     }
372
373     /* Clear dirty bits before querying the block status, because
374      * calling bdrv_get_block_status_above could yield - if some blocks are
375      * marked dirty in this window, we need to know.
376      */
377     bdrv_reset_dirty_bitmap(s->dirty_bitmap, sector_num,
378                             nb_chunks * sectors_per_chunk);
379     bitmap_set(s->in_flight_bitmap, sector_num / sectors_per_chunk, nb_chunks);
380     while (nb_chunks > 0 && sector_num < end) {
381         int ret;
382         int io_sectors, io_sectors_acct;
383         BlockDriverState *file;
384         enum MirrorMethod {
385             MIRROR_METHOD_COPY,
386             MIRROR_METHOD_ZERO,
387             MIRROR_METHOD_DISCARD
388         } mirror_method = MIRROR_METHOD_COPY;
389
390         assert(!(sector_num % sectors_per_chunk));
391         ret = bdrv_get_block_status_above(source, NULL, sector_num,
392                                           nb_chunks * sectors_per_chunk,
393                                           &io_sectors, &file);
394         if (ret < 0) {
395             io_sectors = MIN(nb_chunks * sectors_per_chunk, max_io_sectors);
396         } else if (ret & BDRV_BLOCK_DATA) {
397             io_sectors = MIN(io_sectors, max_io_sectors);
398         }
399
400         io_sectors -= io_sectors % sectors_per_chunk;
401         if (io_sectors < sectors_per_chunk) {
402             io_sectors = sectors_per_chunk;
403         } else if (ret >= 0 && !(ret & BDRV_BLOCK_DATA)) {
404             int64_t target_sector_num;
405             int target_nb_sectors;
406             bdrv_round_sectors_to_clusters(blk_bs(s->target), sector_num,
407                                            io_sectors,  &target_sector_num,
408                                            &target_nb_sectors);
409             if (target_sector_num == sector_num &&
410                 target_nb_sectors == io_sectors) {
411                 mirror_method = ret & BDRV_BLOCK_ZERO ?
412                                     MIRROR_METHOD_ZERO :
413                                     MIRROR_METHOD_DISCARD;
414             }
415         }
416
417         while (s->in_flight >= MAX_IN_FLIGHT) {
418             trace_mirror_yield_in_flight(s, sector_num, s->in_flight);
419             mirror_wait_for_io(s);
420         }
421
422         mirror_clip_sectors(s, sector_num, &io_sectors);
423         switch (mirror_method) {
424         case MIRROR_METHOD_COPY:
425             io_sectors = mirror_do_read(s, sector_num, io_sectors);
426             io_sectors_acct = io_sectors;
427             break;
428         case MIRROR_METHOD_ZERO:
429         case MIRROR_METHOD_DISCARD:
430             mirror_do_zero_or_discard(s, sector_num, io_sectors,
431                                       mirror_method == MIRROR_METHOD_DISCARD);
432             if (write_zeroes_ok) {
433                 io_sectors_acct = 0;
434             } else {
435                 io_sectors_acct = io_sectors;
436             }
437             break;
438         default:
439             abort();
440         }
441         assert(io_sectors);
442         sector_num += io_sectors;
443         nb_chunks -= DIV_ROUND_UP(io_sectors, sectors_per_chunk);
444         if (s->common.speed) {
445             delay_ns = ratelimit_calculate_delay(&s->limit, io_sectors_acct);
446         }
447     }
448     return delay_ns;
449 }
450
451 static void mirror_free_init(MirrorBlockJob *s)
452 {
453     int granularity = s->granularity;
454     size_t buf_size = s->buf_size;
455     uint8_t *buf = s->buf;
456
457     assert(s->buf_free_count == 0);
458     QSIMPLEQ_INIT(&s->buf_free);
459     while (buf_size != 0) {
460         MirrorBuffer *cur = (MirrorBuffer *)buf;
461         QSIMPLEQ_INSERT_TAIL(&s->buf_free, cur, next);
462         s->buf_free_count++;
463         buf_size -= granularity;
464         buf += granularity;
465     }
466 }
467
468 static void mirror_drain(MirrorBlockJob *s)
469 {
470     while (s->in_flight > 0) {
471         mirror_wait_for_io(s);
472     }
473 }
474
475 typedef struct {
476     int ret;
477 } MirrorExitData;
478
479 static void mirror_exit(BlockJob *job, void *opaque)
480 {
481     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
482     MirrorExitData *data = opaque;
483     AioContext *replace_aio_context = NULL;
484     BlockDriverState *src = blk_bs(s->common.blk);
485     BlockDriverState *target_bs = blk_bs(s->target);
486
487     /* Make sure that the source BDS doesn't go away before we called
488      * block_job_completed(). */
489     bdrv_ref(src);
490
491     if (s->to_replace) {
492         replace_aio_context = bdrv_get_aio_context(s->to_replace);
493         aio_context_acquire(replace_aio_context);
494     }
495
496     if (s->should_complete && data->ret == 0) {
497         BlockDriverState *to_replace = src;
498         if (s->to_replace) {
499             to_replace = s->to_replace;
500         }
501
502         if (bdrv_get_flags(target_bs) != bdrv_get_flags(to_replace)) {
503             bdrv_reopen(target_bs, bdrv_get_flags(to_replace), NULL);
504         }
505
506         /* The mirror job has no requests in flight any more, but we need to
507          * drain potential other users of the BDS before changing the graph. */
508         bdrv_drained_begin(target_bs);
509         bdrv_replace_in_backing_chain(to_replace, target_bs);
510         bdrv_drained_end(target_bs);
511
512         /* We just changed the BDS the job BB refers to */
513         blk_remove_bs(job->blk);
514         blk_insert_bs(job->blk, src);
515     }
516     if (s->to_replace) {
517         bdrv_op_unblock_all(s->to_replace, s->replace_blocker);
518         error_free(s->replace_blocker);
519         bdrv_unref(s->to_replace);
520     }
521     if (replace_aio_context) {
522         aio_context_release(replace_aio_context);
523     }
524     g_free(s->replaces);
525     bdrv_op_unblock_all(target_bs, s->common.blocker);
526     blk_unref(s->target);
527     block_job_completed(&s->common, data->ret);
528     g_free(data);
529     bdrv_drained_end(src);
530     bdrv_unref(src);
531 }
532
533 static void mirror_throttle(MirrorBlockJob *s)
534 {
535     int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
536
537     if (now - s->last_pause_ns > SLICE_TIME) {
538         s->last_pause_ns = now;
539         block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, 0);
540     } else {
541         block_job_pause_point(&s->common);
542     }
543 }
544
545 static int coroutine_fn mirror_dirty_init(MirrorBlockJob *s)
546 {
547     int64_t sector_num, end;
548     BlockDriverState *base = s->base;
549     BlockDriverState *bs = blk_bs(s->common.blk);
550     BlockDriverState *target_bs = blk_bs(s->target);
551     int ret, n;
552
553     end = s->bdev_length / BDRV_SECTOR_SIZE;
554
555     if (base == NULL && !bdrv_has_zero_init(target_bs)) {
556         if (!bdrv_can_write_zeroes_with_unmap(target_bs)) {
557             bdrv_set_dirty_bitmap(s->dirty_bitmap, 0, end);
558             return 0;
559         }
560
561         for (sector_num = 0; sector_num < end; ) {
562             int nb_sectors = MIN(end - sector_num,
563                 QEMU_ALIGN_DOWN(INT_MAX, s->granularity) >> BDRV_SECTOR_BITS);
564
565             mirror_throttle(s);
566
567             if (block_job_is_cancelled(&s->common)) {
568                 return 0;
569             }
570
571             if (s->in_flight >= MAX_IN_FLIGHT) {
572                 trace_mirror_yield(s, s->in_flight, s->buf_free_count, -1);
573                 mirror_wait_for_io(s);
574                 continue;
575             }
576
577             mirror_do_zero_or_discard(s, sector_num, nb_sectors, false);
578             sector_num += nb_sectors;
579         }
580
581         mirror_drain(s);
582     }
583
584     /* First part, loop on the sectors and initialize the dirty bitmap.  */
585     for (sector_num = 0; sector_num < end; ) {
586         /* Just to make sure we are not exceeding int limit. */
587         int nb_sectors = MIN(INT_MAX >> BDRV_SECTOR_BITS,
588                              end - sector_num);
589
590         mirror_throttle(s);
591
592         if (block_job_is_cancelled(&s->common)) {
593             return 0;
594         }
595
596         ret = bdrv_is_allocated_above(bs, base, sector_num, nb_sectors, &n);
597         if (ret < 0) {
598             return ret;
599         }
600
601         assert(n > 0);
602         if (ret == 1) {
603             bdrv_set_dirty_bitmap(s->dirty_bitmap, sector_num, n);
604         }
605         sector_num += n;
606     }
607     return 0;
608 }
609
610 static void coroutine_fn mirror_run(void *opaque)
611 {
612     MirrorBlockJob *s = opaque;
613     MirrorExitData *data;
614     BlockDriverState *bs = blk_bs(s->common.blk);
615     BlockDriverState *target_bs = blk_bs(s->target);
616     int64_t length;
617     BlockDriverInfo bdi;
618     char backing_filename[2]; /* we only need 2 characters because we are only
619                                  checking for a NULL string */
620     int ret = 0;
621     int target_cluster_size = BDRV_SECTOR_SIZE;
622
623     if (block_job_is_cancelled(&s->common)) {
624         goto immediate_exit;
625     }
626
627     s->bdev_length = bdrv_getlength(bs);
628     if (s->bdev_length < 0) {
629         ret = s->bdev_length;
630         goto immediate_exit;
631     } else if (s->bdev_length == 0) {
632         /* Report BLOCK_JOB_READY and wait for complete. */
633         block_job_event_ready(&s->common);
634         s->synced = true;
635         while (!block_job_is_cancelled(&s->common) && !s->should_complete) {
636             block_job_yield(&s->common);
637         }
638         s->common.cancelled = false;
639         goto immediate_exit;
640     }
641
642     length = DIV_ROUND_UP(s->bdev_length, s->granularity);
643     s->in_flight_bitmap = bitmap_new(length);
644
645     /* If we have no backing file yet in the destination, we cannot let
646      * the destination do COW.  Instead, we copy sectors around the
647      * dirty data if needed.  We need a bitmap to do that.
648      */
649     bdrv_get_backing_filename(target_bs, backing_filename,
650                               sizeof(backing_filename));
651     if (!bdrv_get_info(target_bs, &bdi) && bdi.cluster_size) {
652         target_cluster_size = bdi.cluster_size;
653     }
654     if (backing_filename[0] && !target_bs->backing
655         && s->granularity < target_cluster_size) {
656         s->buf_size = MAX(s->buf_size, target_cluster_size);
657         s->cow_bitmap = bitmap_new(length);
658     }
659     s->target_cluster_sectors = target_cluster_size >> BDRV_SECTOR_BITS;
660     s->max_iov = MIN(bs->bl.max_iov, target_bs->bl.max_iov);
661
662     s->buf = qemu_try_blockalign(bs, s->buf_size);
663     if (s->buf == NULL) {
664         ret = -ENOMEM;
665         goto immediate_exit;
666     }
667
668     mirror_free_init(s);
669
670     s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
671     if (!s->is_none_mode) {
672         ret = mirror_dirty_init(s);
673         if (ret < 0 || block_job_is_cancelled(&s->common)) {
674             goto immediate_exit;
675         }
676     }
677
678     bdrv_dirty_iter_init(s->dirty_bitmap, &s->hbi);
679     for (;;) {
680         uint64_t delay_ns = 0;
681         int64_t cnt, delta;
682         bool should_complete;
683
684         if (s->ret < 0) {
685             ret = s->ret;
686             goto immediate_exit;
687         }
688
689         block_job_pause_point(&s->common);
690
691         cnt = bdrv_get_dirty_count(s->dirty_bitmap);
692         /* s->common.offset contains the number of bytes already processed so
693          * far, cnt is the number of dirty sectors remaining and
694          * s->sectors_in_flight is the number of sectors currently being
695          * processed; together those are the current total operation length */
696         s->common.len = s->common.offset +
697                         (cnt + s->sectors_in_flight) * BDRV_SECTOR_SIZE;
698
699         /* Note that even when no rate limit is applied we need to yield
700          * periodically with no pending I/O so that bdrv_drain_all() returns.
701          * We do so every SLICE_TIME nanoseconds, or when there is an error,
702          * or when the source is clean, whichever comes first.
703          */
704         delta = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->last_pause_ns;
705         if (delta < SLICE_TIME &&
706             s->common.iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
707             if (s->in_flight >= MAX_IN_FLIGHT || s->buf_free_count == 0 ||
708                 (cnt == 0 && s->in_flight > 0)) {
709                 trace_mirror_yield(s, s->in_flight, s->buf_free_count, cnt);
710                 mirror_wait_for_io(s);
711                 continue;
712             } else if (cnt != 0) {
713                 delay_ns = mirror_iteration(s);
714             }
715         }
716
717         should_complete = false;
718         if (s->in_flight == 0 && cnt == 0) {
719             trace_mirror_before_flush(s);
720             ret = blk_flush(s->target);
721             if (ret < 0) {
722                 if (mirror_error_action(s, false, -ret) ==
723                     BLOCK_ERROR_ACTION_REPORT) {
724                     goto immediate_exit;
725                 }
726             } else {
727                 /* We're out of the streaming phase.  From now on, if the job
728                  * is cancelled we will actually complete all pending I/O and
729                  * report completion.  This way, block-job-cancel will leave
730                  * the target in a consistent state.
731                  */
732                 if (!s->synced) {
733                     block_job_event_ready(&s->common);
734                     s->synced = true;
735                 }
736
737                 should_complete = s->should_complete ||
738                     block_job_is_cancelled(&s->common);
739                 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
740             }
741         }
742
743         if (cnt == 0 && should_complete) {
744             /* The dirty bitmap is not updated while operations are pending.
745              * If we're about to exit, wait for pending operations before
746              * calling bdrv_get_dirty_count(bs), or we may exit while the
747              * source has dirty data to copy!
748              *
749              * Note that I/O can be submitted by the guest while
750              * mirror_populate runs.
751              */
752             trace_mirror_before_drain(s, cnt);
753             bdrv_co_drain(bs);
754             cnt = bdrv_get_dirty_count(s->dirty_bitmap);
755         }
756
757         ret = 0;
758         trace_mirror_before_sleep(s, cnt, s->synced, delay_ns);
759         if (!s->synced) {
760             block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);
761             if (block_job_is_cancelled(&s->common)) {
762                 break;
763             }
764         } else if (!should_complete) {
765             delay_ns = (s->in_flight == 0 && cnt == 0 ? SLICE_TIME : 0);
766             block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);
767         } else if (cnt == 0) {
768             /* The two disks are in sync.  Exit and report successful
769              * completion.
770              */
771             assert(QLIST_EMPTY(&bs->tracked_requests));
772             s->common.cancelled = false;
773             break;
774         }
775         s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
776     }
777
778 immediate_exit:
779     if (s->in_flight > 0) {
780         /* We get here only if something went wrong.  Either the job failed,
781          * or it was cancelled prematurely so that we do not guarantee that
782          * the target is a copy of the source.
783          */
784         assert(ret < 0 || (!s->synced && block_job_is_cancelled(&s->common)));
785         mirror_drain(s);
786     }
787
788     assert(s->in_flight == 0);
789     qemu_vfree(s->buf);
790     g_free(s->cow_bitmap);
791     g_free(s->in_flight_bitmap);
792     bdrv_release_dirty_bitmap(bs, s->dirty_bitmap);
793
794     data = g_malloc(sizeof(*data));
795     data->ret = ret;
796     /* Before we switch to target in mirror_exit, make sure data doesn't
797      * change. */
798     bdrv_drained_begin(bs);
799     block_job_defer_to_main_loop(&s->common, mirror_exit, data);
800 }
801
802 static void mirror_set_speed(BlockJob *job, int64_t speed, Error **errp)
803 {
804     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
805
806     if (speed < 0) {
807         error_setg(errp, QERR_INVALID_PARAMETER, "speed");
808         return;
809     }
810     ratelimit_set_speed(&s->limit, speed / BDRV_SECTOR_SIZE, SLICE_TIME);
811 }
812
813 static void mirror_complete(BlockJob *job, Error **errp)
814 {
815     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
816     BlockDriverState *src, *target;
817
818     src = blk_bs(job->blk);
819     target = blk_bs(s->target);
820
821     if (!s->synced) {
822         error_setg(errp, "The active block job '%s' cannot be completed",
823                    job->id);
824         return;
825     }
826
827     if (s->backing_mode == MIRROR_OPEN_BACKING_CHAIN) {
828         int ret;
829
830         assert(!target->backing);
831         ret = bdrv_open_backing_file(target, NULL, "backing", errp);
832         if (ret < 0) {
833             return;
834         }
835     }
836
837     /* block all operations on to_replace bs */
838     if (s->replaces) {
839         AioContext *replace_aio_context;
840
841         s->to_replace = bdrv_find_node(s->replaces);
842         if (!s->to_replace) {
843             error_setg(errp, "Node name '%s' not found", s->replaces);
844             return;
845         }
846
847         replace_aio_context = bdrv_get_aio_context(s->to_replace);
848         aio_context_acquire(replace_aio_context);
849
850         error_setg(&s->replace_blocker,
851                    "block device is in use by block-job-complete");
852         bdrv_op_block_all(s->to_replace, s->replace_blocker);
853         bdrv_ref(s->to_replace);
854
855         aio_context_release(replace_aio_context);
856     }
857
858     if (s->backing_mode == MIRROR_SOURCE_BACKING_CHAIN) {
859         BlockDriverState *backing = s->is_none_mode ? src : s->base;
860         if (backing_bs(target) != backing) {
861             bdrv_set_backing_hd(target, backing);
862         }
863     }
864
865     s->should_complete = true;
866     block_job_enter(&s->common);
867 }
868
869 /* There is no matching mirror_resume() because mirror_run() will begin
870  * iterating again when the job is resumed.
871  */
872 static void coroutine_fn mirror_pause(BlockJob *job)
873 {
874     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
875
876     mirror_drain(s);
877 }
878
879 static void mirror_attached_aio_context(BlockJob *job, AioContext *new_context)
880 {
881     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
882
883     blk_set_aio_context(s->target, new_context);
884 }
885
886 static const BlockJobDriver mirror_job_driver = {
887     .instance_size          = sizeof(MirrorBlockJob),
888     .job_type               = BLOCK_JOB_TYPE_MIRROR,
889     .set_speed              = mirror_set_speed,
890     .complete               = mirror_complete,
891     .pause                  = mirror_pause,
892     .attached_aio_context   = mirror_attached_aio_context,
893 };
894
895 static const BlockJobDriver commit_active_job_driver = {
896     .instance_size          = sizeof(MirrorBlockJob),
897     .job_type               = BLOCK_JOB_TYPE_COMMIT,
898     .set_speed              = mirror_set_speed,
899     .complete               = mirror_complete,
900     .pause                  = mirror_pause,
901     .attached_aio_context   = mirror_attached_aio_context,
902 };
903
904 static void mirror_start_job(const char *job_id, BlockDriverState *bs,
905                              BlockDriverState *target, const char *replaces,
906                              int64_t speed, uint32_t granularity,
907                              int64_t buf_size,
908                              BlockMirrorBackingMode backing_mode,
909                              BlockdevOnError on_source_error,
910                              BlockdevOnError on_target_error,
911                              bool unmap,
912                              BlockCompletionFunc *cb,
913                              void *opaque, Error **errp,
914                              const BlockJobDriver *driver,
915                              bool is_none_mode, BlockDriverState *base)
916 {
917     MirrorBlockJob *s;
918
919     if (granularity == 0) {
920         granularity = bdrv_get_default_bitmap_granularity(target);
921     }
922
923     assert ((granularity & (granularity - 1)) == 0);
924
925     if (buf_size < 0) {
926         error_setg(errp, "Invalid parameter 'buf-size'");
927         return;
928     }
929
930     if (buf_size == 0) {
931         buf_size = DEFAULT_MIRROR_BUF_SIZE;
932     }
933
934     s = block_job_create(job_id, driver, bs, speed, cb, opaque, errp);
935     if (!s) {
936         return;
937     }
938
939     s->target = blk_new();
940     blk_insert_bs(s->target, target);
941
942     s->replaces = g_strdup(replaces);
943     s->on_source_error = on_source_error;
944     s->on_target_error = on_target_error;
945     s->is_none_mode = is_none_mode;
946     s->backing_mode = backing_mode;
947     s->base = base;
948     s->granularity = granularity;
949     s->buf_size = ROUND_UP(buf_size, granularity);
950     s->unmap = unmap;
951
952     s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
953     if (!s->dirty_bitmap) {
954         g_free(s->replaces);
955         blk_unref(s->target);
956         block_job_unref(&s->common);
957         return;
958     }
959
960     bdrv_op_block_all(target, s->common.blocker);
961
962     s->common.co = qemu_coroutine_create(mirror_run, s);
963     trace_mirror_start(bs, s, s->common.co, opaque);
964     qemu_coroutine_enter(s->common.co);
965 }
966
967 void mirror_start(const char *job_id, BlockDriverState *bs,
968                   BlockDriverState *target, const char *replaces,
969                   int64_t speed, uint32_t granularity, int64_t buf_size,
970                   MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
971                   BlockdevOnError on_source_error,
972                   BlockdevOnError on_target_error,
973                   bool unmap,
974                   BlockCompletionFunc *cb,
975                   void *opaque, Error **errp)
976 {
977     bool is_none_mode;
978     BlockDriverState *base;
979
980     if (mode == MIRROR_SYNC_MODE_INCREMENTAL) {
981         error_setg(errp, "Sync mode 'incremental' not supported");
982         return;
983     }
984     is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
985     base = mode == MIRROR_SYNC_MODE_TOP ? backing_bs(bs) : NULL;
986     mirror_start_job(job_id, bs, target, replaces,
987                      speed, granularity, buf_size, backing_mode,
988                      on_source_error, on_target_error, unmap, cb, opaque, errp,
989                      &mirror_job_driver, is_none_mode, base);
990 }
991
992 void commit_active_start(const char *job_id, BlockDriverState *bs,
993                          BlockDriverState *base, int64_t speed,
994                          BlockdevOnError on_error,
995                          BlockCompletionFunc *cb,
996                          void *opaque, Error **errp)
997 {
998     int64_t length, base_length;
999     int orig_base_flags;
1000     int ret;
1001     Error *local_err = NULL;
1002
1003     orig_base_flags = bdrv_get_flags(base);
1004
1005     if (bdrv_reopen(base, bs->open_flags, errp)) {
1006         return;
1007     }
1008
1009     length = bdrv_getlength(bs);
1010     if (length < 0) {
1011         error_setg_errno(errp, -length,
1012                          "Unable to determine length of %s", bs->filename);
1013         goto error_restore_flags;
1014     }
1015
1016     base_length = bdrv_getlength(base);
1017     if (base_length < 0) {
1018         error_setg_errno(errp, -base_length,
1019                          "Unable to determine length of %s", base->filename);
1020         goto error_restore_flags;
1021     }
1022
1023     if (length > base_length) {
1024         ret = bdrv_truncate(base, length);
1025         if (ret < 0) {
1026             error_setg_errno(errp, -ret,
1027                             "Top image %s is larger than base image %s, and "
1028                              "resize of base image failed",
1029                              bs->filename, base->filename);
1030             goto error_restore_flags;
1031         }
1032     }
1033
1034     mirror_start_job(job_id, bs, base, NULL, speed, 0, 0,
1035                      MIRROR_LEAVE_BACKING_CHAIN,
1036                      on_error, on_error, false, cb, opaque, &local_err,
1037                      &commit_active_job_driver, false, base);
1038     if (local_err) {
1039         error_propagate(errp, local_err);
1040         goto error_restore_flags;
1041     }
1042
1043     return;
1044
1045 error_restore_flags:
1046     /* ignore error and errp for bdrv_reopen, because we want to propagate
1047      * the original error */
1048     bdrv_reopen(base, orig_base_flags, NULL);
1049     return;
1050 }
This page took 0.085321 seconds and 4 git commands to generate.