libcacard: fix wrong array expansion logic
[sdk/emulator/qemu.git] / block-migration.c
1 /*
2  * QEMU live block migration
3  *
4  * Copyright IBM, Corp. 2009
5  *
6  * Authors:
7  *  Liran Schour   <lirans@il.ibm.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2.  See
10  * the COPYING file in the top-level directory.
11  *
12  * Contributions after 2012-01-13 are licensed under the terms of the
13  * GNU GPL, version 2 or (at your option) any later version.
14  */
15
16 #include "qemu-common.h"
17 #include "block/block_int.h"
18 #include "hw/hw.h"
19 #include "qemu/queue.h"
20 #include "qemu/timer.h"
21 #include "migration/block.h"
22 #include "migration/migration.h"
23 #include "sysemu/blockdev.h"
24 #include <assert.h>
25
26 #define BLOCK_SIZE                       (1 << 20)
27 #define BDRV_SECTORS_PER_DIRTY_CHUNK     (BLOCK_SIZE >> BDRV_SECTOR_BITS)
28
29 #define BLK_MIG_FLAG_DEVICE_BLOCK       0x01
30 #define BLK_MIG_FLAG_EOS                0x02
31 #define BLK_MIG_FLAG_PROGRESS           0x04
32 #define BLK_MIG_FLAG_ZERO_BLOCK         0x08
33
34 #define MAX_IS_ALLOCATED_SEARCH 65536
35
36 //#define DEBUG_BLK_MIGRATION
37
38 #ifdef DEBUG_BLK_MIGRATION
39 #define DPRINTF(fmt, ...) \
40     do { printf("blk_migration: " fmt, ## __VA_ARGS__); } while (0)
41 #else
42 #define DPRINTF(fmt, ...) \
43     do { } while (0)
44 #endif
45
46 typedef struct BlkMigDevState {
47     /* Written during setup phase.  Can be read without a lock.  */
48     BlockDriverState *bs;
49     int shared_base;
50     int64_t total_sectors;
51     QSIMPLEQ_ENTRY(BlkMigDevState) entry;
52
53     /* Only used by migration thread.  Does not need a lock.  */
54     int bulk_completed;
55     int64_t cur_sector;
56     int64_t cur_dirty;
57
58     /* Protected by block migration lock.  */
59     unsigned long *aio_bitmap;
60     int64_t completed_sectors;
61     BdrvDirtyBitmap *dirty_bitmap;
62 } BlkMigDevState;
63
64 typedef struct BlkMigBlock {
65     /* Only used by migration thread.  */
66     uint8_t *buf;
67     BlkMigDevState *bmds;
68     int64_t sector;
69     int nr_sectors;
70     struct iovec iov;
71     QEMUIOVector qiov;
72     BlockDriverAIOCB *aiocb;
73
74     /* Protected by block migration lock.  */
75     int ret;
76     QSIMPLEQ_ENTRY(BlkMigBlock) entry;
77 } BlkMigBlock;
78
79 typedef struct BlkMigState {
80     /* Written during setup phase.  Can be read without a lock.  */
81     int blk_enable;
82     int shared_base;
83     QSIMPLEQ_HEAD(bmds_list, BlkMigDevState) bmds_list;
84     int64_t total_sector_sum;
85     bool zero_blocks;
86
87     /* Protected by lock.  */
88     QSIMPLEQ_HEAD(blk_list, BlkMigBlock) blk_list;
89     int submitted;
90     int read_done;
91
92     /* Only used by migration thread.  Does not need a lock.  */
93     int transferred;
94     int prev_progress;
95     int bulk_completed;
96
97     /* Lock must be taken _inside_ the iothread lock.  */
98     QemuMutex lock;
99 } BlkMigState;
100
101 static BlkMigState block_mig_state;
102
103 static void blk_mig_lock(void)
104 {
105     qemu_mutex_lock(&block_mig_state.lock);
106 }
107
108 static void blk_mig_unlock(void)
109 {
110     qemu_mutex_unlock(&block_mig_state.lock);
111 }
112
113 /* Must run outside of the iothread lock during the bulk phase,
114  * or the VM will stall.
115  */
116
117 static void blk_send(QEMUFile *f, BlkMigBlock * blk)
118 {
119     int len;
120     uint64_t flags = BLK_MIG_FLAG_DEVICE_BLOCK;
121
122     if (block_mig_state.zero_blocks &&
123         buffer_is_zero(blk->buf, BLOCK_SIZE)) {
124         flags |= BLK_MIG_FLAG_ZERO_BLOCK;
125     }
126
127     /* sector number and flags */
128     qemu_put_be64(f, (blk->sector << BDRV_SECTOR_BITS)
129                      | flags);
130
131     /* device name */
132     len = strlen(blk->bmds->bs->device_name);
133     qemu_put_byte(f, len);
134     qemu_put_buffer(f, (uint8_t *)blk->bmds->bs->device_name, len);
135
136     /* if a block is zero we need to flush here since the network
137      * bandwidth is now a lot higher than the storage device bandwidth.
138      * thus if we queue zero blocks we slow down the migration */
139     if (flags & BLK_MIG_FLAG_ZERO_BLOCK) {
140         qemu_fflush(f);
141         return;
142     }
143
144     qemu_put_buffer(f, blk->buf, BLOCK_SIZE);
145 }
146
147 int blk_mig_active(void)
148 {
149     return !QSIMPLEQ_EMPTY(&block_mig_state.bmds_list);
150 }
151
152 uint64_t blk_mig_bytes_transferred(void)
153 {
154     BlkMigDevState *bmds;
155     uint64_t sum = 0;
156
157     blk_mig_lock();
158     QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
159         sum += bmds->completed_sectors;
160     }
161     blk_mig_unlock();
162     return sum << BDRV_SECTOR_BITS;
163 }
164
165 uint64_t blk_mig_bytes_remaining(void)
166 {
167     return blk_mig_bytes_total() - blk_mig_bytes_transferred();
168 }
169
170 uint64_t blk_mig_bytes_total(void)
171 {
172     BlkMigDevState *bmds;
173     uint64_t sum = 0;
174
175     QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
176         sum += bmds->total_sectors;
177     }
178     return sum << BDRV_SECTOR_BITS;
179 }
180
181
182 /* Called with migration lock held.  */
183
184 static int bmds_aio_inflight(BlkMigDevState *bmds, int64_t sector)
185 {
186     int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
187
188     if ((sector << BDRV_SECTOR_BITS) < bdrv_getlength(bmds->bs)) {
189         return !!(bmds->aio_bitmap[chunk / (sizeof(unsigned long) * 8)] &
190             (1UL << (chunk % (sizeof(unsigned long) * 8))));
191     } else {
192         return 0;
193     }
194 }
195
196 /* Called with migration lock held.  */
197
198 static void bmds_set_aio_inflight(BlkMigDevState *bmds, int64_t sector_num,
199                              int nb_sectors, int set)
200 {
201     int64_t start, end;
202     unsigned long val, idx, bit;
203
204     start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
205     end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
206
207     for (; start <= end; start++) {
208         idx = start / (sizeof(unsigned long) * 8);
209         bit = start % (sizeof(unsigned long) * 8);
210         val = bmds->aio_bitmap[idx];
211         if (set) {
212             val |= 1UL << bit;
213         } else {
214             val &= ~(1UL << bit);
215         }
216         bmds->aio_bitmap[idx] = val;
217     }
218 }
219
220 static void alloc_aio_bitmap(BlkMigDevState *bmds)
221 {
222     BlockDriverState *bs = bmds->bs;
223     int64_t bitmap_size;
224
225     bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
226             BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
227     bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
228
229     bmds->aio_bitmap = g_malloc0(bitmap_size);
230 }
231
232 /* Never hold migration lock when yielding to the main loop!  */
233
234 static void blk_mig_read_cb(void *opaque, int ret)
235 {
236     BlkMigBlock *blk = opaque;
237
238     blk_mig_lock();
239     blk->ret = ret;
240
241     QSIMPLEQ_INSERT_TAIL(&block_mig_state.blk_list, blk, entry);
242     bmds_set_aio_inflight(blk->bmds, blk->sector, blk->nr_sectors, 0);
243
244     block_mig_state.submitted--;
245     block_mig_state.read_done++;
246     assert(block_mig_state.submitted >= 0);
247     blk_mig_unlock();
248 }
249
250 /* Called with no lock taken.  */
251
252 static int mig_save_device_bulk(QEMUFile *f, BlkMigDevState *bmds)
253 {
254     int64_t total_sectors = bmds->total_sectors;
255     int64_t cur_sector = bmds->cur_sector;
256     BlockDriverState *bs = bmds->bs;
257     BlkMigBlock *blk;
258     int nr_sectors;
259
260     if (bmds->shared_base) {
261         qemu_mutex_lock_iothread();
262         while (cur_sector < total_sectors &&
263                !bdrv_is_allocated(bs, cur_sector, MAX_IS_ALLOCATED_SEARCH,
264                                   &nr_sectors)) {
265             cur_sector += nr_sectors;
266         }
267         qemu_mutex_unlock_iothread();
268     }
269
270     if (cur_sector >= total_sectors) {
271         bmds->cur_sector = bmds->completed_sectors = total_sectors;
272         return 1;
273     }
274
275     bmds->completed_sectors = cur_sector;
276
277     cur_sector &= ~((int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK - 1);
278
279     /* we are going to transfer a full block even if it is not allocated */
280     nr_sectors = BDRV_SECTORS_PER_DIRTY_CHUNK;
281
282     if (total_sectors - cur_sector < BDRV_SECTORS_PER_DIRTY_CHUNK) {
283         nr_sectors = total_sectors - cur_sector;
284     }
285
286     blk = g_malloc(sizeof(BlkMigBlock));
287     blk->buf = g_malloc(BLOCK_SIZE);
288     blk->bmds = bmds;
289     blk->sector = cur_sector;
290     blk->nr_sectors = nr_sectors;
291
292     blk->iov.iov_base = blk->buf;
293     blk->iov.iov_len = nr_sectors * BDRV_SECTOR_SIZE;
294     qemu_iovec_init_external(&blk->qiov, &blk->iov, 1);
295
296     blk_mig_lock();
297     block_mig_state.submitted++;
298     blk_mig_unlock();
299
300     qemu_mutex_lock_iothread();
301     blk->aiocb = bdrv_aio_readv(bs, cur_sector, &blk->qiov,
302                                 nr_sectors, blk_mig_read_cb, blk);
303
304     bdrv_reset_dirty(bs, cur_sector, nr_sectors);
305     qemu_mutex_unlock_iothread();
306
307     bmds->cur_sector = cur_sector + nr_sectors;
308     return (bmds->cur_sector >= total_sectors);
309 }
310
311 /* Called with iothread lock taken.  */
312
313 static int set_dirty_tracking(void)
314 {
315     BlkMigDevState *bmds;
316     int ret;
317
318     QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
319         bmds->dirty_bitmap = bdrv_create_dirty_bitmap(bmds->bs, BLOCK_SIZE,
320                                                       NULL);
321         if (!bmds->dirty_bitmap) {
322             ret = -errno;
323             goto fail;
324         }
325     }
326     return 0;
327
328 fail:
329     QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
330         if (bmds->dirty_bitmap) {
331             bdrv_release_dirty_bitmap(bmds->bs, bmds->dirty_bitmap);
332         }
333     }
334     return ret;
335 }
336
337 static void unset_dirty_tracking(void)
338 {
339     BlkMigDevState *bmds;
340
341     QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
342         bdrv_release_dirty_bitmap(bmds->bs, bmds->dirty_bitmap);
343     }
344 }
345
346 static void init_blk_migration_it(void *opaque, BlockDriverState *bs)
347 {
348     BlkMigDevState *bmds;
349     int64_t sectors;
350
351     if (!bdrv_is_read_only(bs)) {
352         sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
353         if (sectors <= 0) {
354             return;
355         }
356
357         bmds = g_malloc0(sizeof(BlkMigDevState));
358         bmds->bs = bs;
359         bmds->bulk_completed = 0;
360         bmds->total_sectors = sectors;
361         bmds->completed_sectors = 0;
362         bmds->shared_base = block_mig_state.shared_base;
363         alloc_aio_bitmap(bmds);
364         bdrv_set_in_use(bs, 1);
365         bdrv_ref(bs);
366
367         block_mig_state.total_sector_sum += sectors;
368
369         if (bmds->shared_base) {
370             DPRINTF("Start migration for %s with shared base image\n",
371                     bs->device_name);
372         } else {
373             DPRINTF("Start full migration for %s\n", bs->device_name);
374         }
375
376         QSIMPLEQ_INSERT_TAIL(&block_mig_state.bmds_list, bmds, entry);
377     }
378 }
379
380 static void init_blk_migration(QEMUFile *f)
381 {
382     block_mig_state.submitted = 0;
383     block_mig_state.read_done = 0;
384     block_mig_state.transferred = 0;
385     block_mig_state.total_sector_sum = 0;
386     block_mig_state.prev_progress = -1;
387     block_mig_state.bulk_completed = 0;
388     block_mig_state.zero_blocks = migrate_zero_blocks();
389
390     bdrv_iterate(init_blk_migration_it, NULL);
391 }
392
393 /* Called with no lock taken.  */
394
395 static int blk_mig_save_bulked_block(QEMUFile *f)
396 {
397     int64_t completed_sector_sum = 0;
398     BlkMigDevState *bmds;
399     int progress;
400     int ret = 0;
401
402     QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
403         if (bmds->bulk_completed == 0) {
404             if (mig_save_device_bulk(f, bmds) == 1) {
405                 /* completed bulk section for this device */
406                 bmds->bulk_completed = 1;
407             }
408             completed_sector_sum += bmds->completed_sectors;
409             ret = 1;
410             break;
411         } else {
412             completed_sector_sum += bmds->completed_sectors;
413         }
414     }
415
416     if (block_mig_state.total_sector_sum != 0) {
417         progress = completed_sector_sum * 100 /
418                    block_mig_state.total_sector_sum;
419     } else {
420         progress = 100;
421     }
422     if (progress != block_mig_state.prev_progress) {
423         block_mig_state.prev_progress = progress;
424         qemu_put_be64(f, (progress << BDRV_SECTOR_BITS)
425                          | BLK_MIG_FLAG_PROGRESS);
426         DPRINTF("Completed %d %%\r", progress);
427     }
428
429     return ret;
430 }
431
432 static void blk_mig_reset_dirty_cursor(void)
433 {
434     BlkMigDevState *bmds;
435
436     QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
437         bmds->cur_dirty = 0;
438     }
439 }
440
441 /* Called with iothread lock taken.  */
442
443 static int mig_save_device_dirty(QEMUFile *f, BlkMigDevState *bmds,
444                                  int is_async)
445 {
446     BlkMigBlock *blk;
447     int64_t total_sectors = bmds->total_sectors;
448     int64_t sector;
449     int nr_sectors;
450     int ret = -EIO;
451
452     for (sector = bmds->cur_dirty; sector < bmds->total_sectors;) {
453         blk_mig_lock();
454         if (bmds_aio_inflight(bmds, sector)) {
455             blk_mig_unlock();
456             bdrv_drain_all();
457         } else {
458             blk_mig_unlock();
459         }
460         if (bdrv_get_dirty(bmds->bs, bmds->dirty_bitmap, sector)) {
461
462             if (total_sectors - sector < BDRV_SECTORS_PER_DIRTY_CHUNK) {
463                 nr_sectors = total_sectors - sector;
464             } else {
465                 nr_sectors = BDRV_SECTORS_PER_DIRTY_CHUNK;
466             }
467             blk = g_malloc(sizeof(BlkMigBlock));
468             blk->buf = g_malloc(BLOCK_SIZE);
469             blk->bmds = bmds;
470             blk->sector = sector;
471             blk->nr_sectors = nr_sectors;
472
473             if (is_async) {
474                 blk->iov.iov_base = blk->buf;
475                 blk->iov.iov_len = nr_sectors * BDRV_SECTOR_SIZE;
476                 qemu_iovec_init_external(&blk->qiov, &blk->iov, 1);
477
478                 blk->aiocb = bdrv_aio_readv(bmds->bs, sector, &blk->qiov,
479                                             nr_sectors, blk_mig_read_cb, blk);
480
481                 blk_mig_lock();
482                 block_mig_state.submitted++;
483                 bmds_set_aio_inflight(bmds, sector, nr_sectors, 1);
484                 blk_mig_unlock();
485             } else {
486                 ret = bdrv_read(bmds->bs, sector, blk->buf, nr_sectors);
487                 if (ret < 0) {
488                     goto error;
489                 }
490                 blk_send(f, blk);
491
492                 g_free(blk->buf);
493                 g_free(blk);
494             }
495
496             bdrv_reset_dirty(bmds->bs, sector, nr_sectors);
497             break;
498         }
499         sector += BDRV_SECTORS_PER_DIRTY_CHUNK;
500         bmds->cur_dirty = sector;
501     }
502
503     return (bmds->cur_dirty >= bmds->total_sectors);
504
505 error:
506     DPRINTF("Error reading sector %" PRId64 "\n", sector);
507     g_free(blk->buf);
508     g_free(blk);
509     return ret;
510 }
511
512 /* Called with iothread lock taken.
513  *
514  * return value:
515  * 0: too much data for max_downtime
516  * 1: few enough data for max_downtime
517 */
518 static int blk_mig_save_dirty_block(QEMUFile *f, int is_async)
519 {
520     BlkMigDevState *bmds;
521     int ret = 1;
522
523     QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
524         ret = mig_save_device_dirty(f, bmds, is_async);
525         if (ret <= 0) {
526             break;
527         }
528     }
529
530     return ret;
531 }
532
533 /* Called with no locks taken.  */
534
535 static int flush_blks(QEMUFile *f)
536 {
537     BlkMigBlock *blk;
538     int ret = 0;
539
540     DPRINTF("%s Enter submitted %d read_done %d transferred %d\n",
541             __FUNCTION__, block_mig_state.submitted, block_mig_state.read_done,
542             block_mig_state.transferred);
543
544     blk_mig_lock();
545     while ((blk = QSIMPLEQ_FIRST(&block_mig_state.blk_list)) != NULL) {
546         if (qemu_file_rate_limit(f)) {
547             break;
548         }
549         if (blk->ret < 0) {
550             ret = blk->ret;
551             break;
552         }
553
554         QSIMPLEQ_REMOVE_HEAD(&block_mig_state.blk_list, entry);
555         blk_mig_unlock();
556         blk_send(f, blk);
557         blk_mig_lock();
558
559         g_free(blk->buf);
560         g_free(blk);
561
562         block_mig_state.read_done--;
563         block_mig_state.transferred++;
564         assert(block_mig_state.read_done >= 0);
565     }
566     blk_mig_unlock();
567
568     DPRINTF("%s Exit submitted %d read_done %d transferred %d\n", __FUNCTION__,
569             block_mig_state.submitted, block_mig_state.read_done,
570             block_mig_state.transferred);
571     return ret;
572 }
573
574 /* Called with iothread lock taken.  */
575
576 static int64_t get_remaining_dirty(void)
577 {
578     BlkMigDevState *bmds;
579     int64_t dirty = 0;
580
581     QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
582         dirty += bdrv_get_dirty_count(bmds->bs, bmds->dirty_bitmap);
583     }
584
585     return dirty << BDRV_SECTOR_BITS;
586 }
587
588 /* Called with iothread lock taken.  */
589
590 static void blk_mig_cleanup(void)
591 {
592     BlkMigDevState *bmds;
593     BlkMigBlock *blk;
594
595     bdrv_drain_all();
596
597     unset_dirty_tracking();
598
599     blk_mig_lock();
600     while ((bmds = QSIMPLEQ_FIRST(&block_mig_state.bmds_list)) != NULL) {
601         QSIMPLEQ_REMOVE_HEAD(&block_mig_state.bmds_list, entry);
602         bdrv_set_in_use(bmds->bs, 0);
603         bdrv_unref(bmds->bs);
604         g_free(bmds->aio_bitmap);
605         g_free(bmds);
606     }
607
608     while ((blk = QSIMPLEQ_FIRST(&block_mig_state.blk_list)) != NULL) {
609         QSIMPLEQ_REMOVE_HEAD(&block_mig_state.blk_list, entry);
610         g_free(blk->buf);
611         g_free(blk);
612     }
613     blk_mig_unlock();
614 }
615
616 static void block_migration_cancel(void *opaque)
617 {
618     blk_mig_cleanup();
619 }
620
621 static int block_save_setup(QEMUFile *f, void *opaque)
622 {
623     int ret;
624
625     DPRINTF("Enter save live setup submitted %d transferred %d\n",
626             block_mig_state.submitted, block_mig_state.transferred);
627
628     qemu_mutex_lock_iothread();
629
630     /* start track dirty blocks */
631     ret = set_dirty_tracking();
632
633     if (ret) {
634         qemu_mutex_unlock_iothread();
635         return ret;
636     }
637
638     init_blk_migration(f);
639
640     qemu_mutex_unlock_iothread();
641
642     ret = flush_blks(f);
643     blk_mig_reset_dirty_cursor();
644     qemu_put_be64(f, BLK_MIG_FLAG_EOS);
645
646     return ret;
647 }
648
649 static int block_save_iterate(QEMUFile *f, void *opaque)
650 {
651     int ret;
652     int64_t last_ftell = qemu_ftell(f);
653
654     DPRINTF("Enter save live iterate submitted %d transferred %d\n",
655             block_mig_state.submitted, block_mig_state.transferred);
656
657     ret = flush_blks(f);
658     if (ret) {
659         return ret;
660     }
661
662     blk_mig_reset_dirty_cursor();
663
664     /* control the rate of transfer */
665     blk_mig_lock();
666     while ((block_mig_state.submitted +
667             block_mig_state.read_done) * BLOCK_SIZE <
668            qemu_file_get_rate_limit(f)) {
669         blk_mig_unlock();
670         if (block_mig_state.bulk_completed == 0) {
671             /* first finish the bulk phase */
672             if (blk_mig_save_bulked_block(f) == 0) {
673                 /* finished saving bulk on all devices */
674                 block_mig_state.bulk_completed = 1;
675             }
676             ret = 0;
677         } else {
678             /* Always called with iothread lock taken for
679              * simplicity, block_save_complete also calls it.
680              */
681             qemu_mutex_lock_iothread();
682             ret = blk_mig_save_dirty_block(f, 1);
683             qemu_mutex_unlock_iothread();
684         }
685         if (ret < 0) {
686             return ret;
687         }
688         blk_mig_lock();
689         if (ret != 0) {
690             /* no more dirty blocks */
691             break;
692         }
693     }
694     blk_mig_unlock();
695
696     ret = flush_blks(f);
697     if (ret) {
698         return ret;
699     }
700
701     qemu_put_be64(f, BLK_MIG_FLAG_EOS);
702     return qemu_ftell(f) - last_ftell;
703 }
704
705 /* Called with iothread lock taken.  */
706
707 static int block_save_complete(QEMUFile *f, void *opaque)
708 {
709     int ret;
710
711     DPRINTF("Enter save live complete submitted %d transferred %d\n",
712             block_mig_state.submitted, block_mig_state.transferred);
713
714     ret = flush_blks(f);
715     if (ret) {
716         return ret;
717     }
718
719     blk_mig_reset_dirty_cursor();
720
721     /* we know for sure that save bulk is completed and
722        all async read completed */
723     blk_mig_lock();
724     assert(block_mig_state.submitted == 0);
725     blk_mig_unlock();
726
727     do {
728         ret = blk_mig_save_dirty_block(f, 0);
729         if (ret < 0) {
730             return ret;
731         }
732     } while (ret == 0);
733
734     /* report completion */
735     qemu_put_be64(f, (100 << BDRV_SECTOR_BITS) | BLK_MIG_FLAG_PROGRESS);
736
737     DPRINTF("Block migration completed\n");
738
739     qemu_put_be64(f, BLK_MIG_FLAG_EOS);
740
741     blk_mig_cleanup();
742     return 0;
743 }
744
745 static uint64_t block_save_pending(QEMUFile *f, void *opaque, uint64_t max_size)
746 {
747     /* Estimate pending number of bytes to send */
748     uint64_t pending;
749
750     qemu_mutex_lock_iothread();
751     blk_mig_lock();
752     pending = get_remaining_dirty() +
753                        block_mig_state.submitted * BLOCK_SIZE +
754                        block_mig_state.read_done * BLOCK_SIZE;
755
756     /* Report at least one block pending during bulk phase */
757     if (pending == 0 && !block_mig_state.bulk_completed) {
758         pending = BLOCK_SIZE;
759     }
760     blk_mig_unlock();
761     qemu_mutex_unlock_iothread();
762
763     DPRINTF("Enter save live pending  %" PRIu64 "\n", pending);
764     return pending;
765 }
766
767 static int block_load(QEMUFile *f, void *opaque, int version_id)
768 {
769     static int banner_printed;
770     int len, flags;
771     char device_name[256];
772     int64_t addr;
773     BlockDriverState *bs, *bs_prev = NULL;
774     uint8_t *buf;
775     int64_t total_sectors = 0;
776     int nr_sectors;
777     int ret;
778
779     do {
780         addr = qemu_get_be64(f);
781
782         flags = addr & ~BDRV_SECTOR_MASK;
783         addr >>= BDRV_SECTOR_BITS;
784
785         if (flags & BLK_MIG_FLAG_DEVICE_BLOCK) {
786             /* get device name */
787             len = qemu_get_byte(f);
788             qemu_get_buffer(f, (uint8_t *)device_name, len);
789             device_name[len] = '\0';
790
791             bs = bdrv_find(device_name);
792             if (!bs) {
793                 fprintf(stderr, "Error unknown block device %s\n",
794                         device_name);
795                 return -EINVAL;
796             }
797
798             if (bs != bs_prev) {
799                 bs_prev = bs;
800                 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
801                 if (total_sectors <= 0) {
802                     error_report("Error getting length of block device %s",
803                                  device_name);
804                     return -EINVAL;
805                 }
806             }
807
808             if (total_sectors - addr < BDRV_SECTORS_PER_DIRTY_CHUNK) {
809                 nr_sectors = total_sectors - addr;
810             } else {
811                 nr_sectors = BDRV_SECTORS_PER_DIRTY_CHUNK;
812             }
813
814             if (flags & BLK_MIG_FLAG_ZERO_BLOCK) {
815                 ret = bdrv_write_zeroes(bs, addr, nr_sectors,
816                                         BDRV_REQ_MAY_UNMAP);
817             } else {
818                 buf = g_malloc(BLOCK_SIZE);
819                 qemu_get_buffer(f, buf, BLOCK_SIZE);
820                 ret = bdrv_write(bs, addr, buf, nr_sectors);
821                 g_free(buf);
822             }
823
824             if (ret < 0) {
825                 return ret;
826             }
827         } else if (flags & BLK_MIG_FLAG_PROGRESS) {
828             if (!banner_printed) {
829                 printf("Receiving block device images\n");
830                 banner_printed = 1;
831             }
832             printf("Completed %d %%%c", (int)addr,
833                    (addr == 100) ? '\n' : '\r');
834             fflush(stdout);
835         } else if (!(flags & BLK_MIG_FLAG_EOS)) {
836             fprintf(stderr, "Unknown block migration flags: %#x\n", flags);
837             return -EINVAL;
838         }
839         ret = qemu_file_get_error(f);
840         if (ret != 0) {
841             return ret;
842         }
843     } while (!(flags & BLK_MIG_FLAG_EOS));
844
845     return 0;
846 }
847
848 static void block_set_params(const MigrationParams *params, void *opaque)
849 {
850     block_mig_state.blk_enable = params->blk;
851     block_mig_state.shared_base = params->shared;
852
853     /* shared base means that blk_enable = 1 */
854     block_mig_state.blk_enable |= params->shared;
855 }
856
857 static bool block_is_active(void *opaque)
858 {
859     return block_mig_state.blk_enable == 1;
860 }
861
862 SaveVMHandlers savevm_block_handlers = {
863     .set_params = block_set_params,
864     .save_live_setup = block_save_setup,
865     .save_live_iterate = block_save_iterate,
866     .save_live_complete = block_save_complete,
867     .save_live_pending = block_save_pending,
868     .load_state = block_load,
869     .cancel = block_migration_cancel,
870     .is_active = block_is_active,
871 };
872
873 void blk_mig_init(void)
874 {
875     QSIMPLEQ_INIT(&block_mig_state.bmds_list);
876     QSIMPLEQ_INIT(&block_mig_state.blk_list);
877     qemu_mutex_init(&block_mig_state.lock);
878
879     register_savevm_live(NULL, "block", 0, 1, &savevm_block_handlers,
880                          &block_mig_state);
881 }