qemu/migration/block.c
<<
>>
Prefs
   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/osdep.h"
  17#include "qapi/error.h"
  18#include "qemu/error-report.h"
  19#include "qemu/cutils.h"
  20#include "qemu/queue.h"
  21#include "block.h"
  22#include "migration/misc.h"
  23#include "migration.h"
  24#include "migration/register.h"
  25#include "qemu-file.h"
  26#include "migration/vmstate.h"
  27#include "sysemu/block-backend.h"
  28
  29#define BLOCK_SIZE                       (1 << 20)
  30#define BDRV_SECTORS_PER_DIRTY_CHUNK     (BLOCK_SIZE >> BDRV_SECTOR_BITS)
  31
  32#define BLK_MIG_FLAG_DEVICE_BLOCK       0x01
  33#define BLK_MIG_FLAG_EOS                0x02
  34#define BLK_MIG_FLAG_PROGRESS           0x04
  35#define BLK_MIG_FLAG_ZERO_BLOCK         0x08
  36
  37#define MAX_IS_ALLOCATED_SEARCH (65536 * BDRV_SECTOR_SIZE)
  38
  39#define MAX_INFLIGHT_IO 512
  40
  41//#define DEBUG_BLK_MIGRATION
  42
  43#ifdef DEBUG_BLK_MIGRATION
  44#define DPRINTF(fmt, ...) \
  45    do { printf("blk_migration: " fmt, ## __VA_ARGS__); } while (0)
  46#else
  47#define DPRINTF(fmt, ...) \
  48    do { } while (0)
  49#endif
  50
  51typedef struct BlkMigDevState {
  52    /* Written during setup phase.  Can be read without a lock.  */
  53    BlockBackend *blk;
  54    char *blk_name;
  55    int shared_base;
  56    int64_t total_sectors;
  57    QSIMPLEQ_ENTRY(BlkMigDevState) entry;
  58    Error *blocker;
  59
  60    /* Only used by migration thread.  Does not need a lock.  */
  61    int bulk_completed;
  62    int64_t cur_sector;
  63    int64_t cur_dirty;
  64
  65    /* Data in the aio_bitmap is protected by block migration lock.
  66     * Allocation and free happen during setup and cleanup respectively.
  67     */
  68    unsigned long *aio_bitmap;
  69
  70    /* Protected by block migration lock.  */
  71    int64_t completed_sectors;
  72
  73    /* During migration this is protected by iothread lock / AioContext.
  74     * Allocation and free happen during setup and cleanup respectively.
  75     */
  76    BdrvDirtyBitmap *dirty_bitmap;
  77} BlkMigDevState;
  78
  79typedef struct BlkMigBlock {
  80    /* Only used by migration thread.  */
  81    uint8_t *buf;
  82    BlkMigDevState *bmds;
  83    int64_t sector;
  84    int nr_sectors;
  85    struct iovec iov;
  86    QEMUIOVector qiov;
  87    BlockAIOCB *aiocb;
  88
  89    /* Protected by block migration lock.  */
  90    int ret;
  91    QSIMPLEQ_ENTRY(BlkMigBlock) entry;
  92} BlkMigBlock;
  93
  94typedef struct BlkMigState {
  95    QSIMPLEQ_HEAD(bmds_list, BlkMigDevState) bmds_list;
  96    int64_t total_sector_sum;
  97    bool zero_blocks;
  98
  99    /* Protected by lock.  */
 100    QSIMPLEQ_HEAD(blk_list, BlkMigBlock) blk_list;
 101    int submitted;
 102    int read_done;
 103
 104    /* Only used by migration thread.  Does not need a lock.  */
 105    int transferred;
 106    int prev_progress;
 107    int bulk_completed;
 108
 109    /* Lock must be taken _inside_ the iothread lock and any AioContexts.  */
 110    QemuMutex lock;
 111} BlkMigState;
 112
 113static BlkMigState block_mig_state;
 114
 115static void blk_mig_lock(void)
 116{
 117    qemu_mutex_lock(&block_mig_state.lock);
 118}
 119
 120static void blk_mig_unlock(void)
 121{
 122    qemu_mutex_unlock(&block_mig_state.lock);
 123}
 124
 125/* Must run outside of the iothread lock during the bulk phase,
 126 * or the VM will stall.
 127 */
 128
 129static void blk_send(QEMUFile *f, BlkMigBlock * blk)
 130{
 131    int len;
 132    uint64_t flags = BLK_MIG_FLAG_DEVICE_BLOCK;
 133
 134    if (block_mig_state.zero_blocks &&
 135        buffer_is_zero(blk->buf, BLOCK_SIZE)) {
 136        flags |= BLK_MIG_FLAG_ZERO_BLOCK;
 137    }
 138
 139    /* sector number and flags */
 140    qemu_put_be64(f, (blk->sector << BDRV_SECTOR_BITS)
 141                     | flags);
 142
 143    /* device name */
 144    len = strlen(blk->bmds->blk_name);
 145    qemu_put_byte(f, len);
 146    qemu_put_buffer(f, (uint8_t *) blk->bmds->blk_name, len);
 147
 148    /* if a block is zero we need to flush here since the network
 149     * bandwidth is now a lot higher than the storage device bandwidth.
 150     * thus if we queue zero blocks we slow down the migration */
 151    if (flags & BLK_MIG_FLAG_ZERO_BLOCK) {
 152        qemu_fflush(f);
 153        return;
 154    }
 155
 156    qemu_put_buffer(f, blk->buf, BLOCK_SIZE);
 157}
 158
 159int blk_mig_active(void)
 160{
 161    return !QSIMPLEQ_EMPTY(&block_mig_state.bmds_list);
 162}
 163
 164uint64_t blk_mig_bytes_transferred(void)
 165{
 166    BlkMigDevState *bmds;
 167    uint64_t sum = 0;
 168
 169    blk_mig_lock();
 170    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
 171        sum += bmds->completed_sectors;
 172    }
 173    blk_mig_unlock();
 174    return sum << BDRV_SECTOR_BITS;
 175}
 176
 177uint64_t blk_mig_bytes_remaining(void)
 178{
 179    return blk_mig_bytes_total() - blk_mig_bytes_transferred();
 180}
 181
 182uint64_t blk_mig_bytes_total(void)
 183{
 184    BlkMigDevState *bmds;
 185    uint64_t sum = 0;
 186
 187    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
 188        sum += bmds->total_sectors;
 189    }
 190    return sum << BDRV_SECTOR_BITS;
 191}
 192
 193
 194/* Called with migration lock held.  */
 195
 196static int bmds_aio_inflight(BlkMigDevState *bmds, int64_t sector)
 197{
 198    int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
 199
 200    if (sector < blk_nb_sectors(bmds->blk)) {
 201        return !!(bmds->aio_bitmap[chunk / (sizeof(unsigned long) * 8)] &
 202            (1UL << (chunk % (sizeof(unsigned long) * 8))));
 203    } else {
 204        return 0;
 205    }
 206}
 207
 208/* Called with migration lock held.  */
 209
 210static void bmds_set_aio_inflight(BlkMigDevState *bmds, int64_t sector_num,
 211                             int nb_sectors, int set)
 212{
 213    int64_t start, end;
 214    unsigned long val, idx, bit;
 215
 216    start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
 217    end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
 218
 219    for (; start <= end; start++) {
 220        idx = start / (sizeof(unsigned long) * 8);
 221        bit = start % (sizeof(unsigned long) * 8);
 222        val = bmds->aio_bitmap[idx];
 223        if (set) {
 224            val |= 1UL << bit;
 225        } else {
 226            val &= ~(1UL << bit);
 227        }
 228        bmds->aio_bitmap[idx] = val;
 229    }
 230}
 231
 232static void alloc_aio_bitmap(BlkMigDevState *bmds)
 233{
 234    BlockBackend *bb = bmds->blk;
 235    int64_t bitmap_size;
 236
 237    bitmap_size = blk_nb_sectors(bb) + BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
 238    bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
 239
 240    bmds->aio_bitmap = g_malloc0(bitmap_size);
 241}
 242
 243/* Never hold migration lock when yielding to the main loop!  */
 244
 245static void blk_mig_read_cb(void *opaque, int ret)
 246{
 247    BlkMigBlock *blk = opaque;
 248
 249    blk_mig_lock();
 250    blk->ret = ret;
 251
 252    QSIMPLEQ_INSERT_TAIL(&block_mig_state.blk_list, blk, entry);
 253    bmds_set_aio_inflight(blk->bmds, blk->sector, blk->nr_sectors, 0);
 254
 255    block_mig_state.submitted--;
 256    block_mig_state.read_done++;
 257    assert(block_mig_state.submitted >= 0);
 258    blk_mig_unlock();
 259}
 260
 261/* Called with no lock taken.  */
 262
 263static int mig_save_device_bulk(QEMUFile *f, BlkMigDevState *bmds)
 264{
 265    int64_t total_sectors = bmds->total_sectors;
 266    int64_t cur_sector = bmds->cur_sector;
 267    BlockBackend *bb = bmds->blk;
 268    BlkMigBlock *blk;
 269    int nr_sectors;
 270    int64_t count;
 271
 272    if (bmds->shared_base) {
 273        qemu_mutex_lock_iothread();
 274        aio_context_acquire(blk_get_aio_context(bb));
 275        /* Skip unallocated sectors; intentionally treats failure or
 276         * partial sector as an allocated sector */
 277        while (cur_sector < total_sectors &&
 278               !bdrv_is_allocated(blk_bs(bb), cur_sector * BDRV_SECTOR_SIZE,
 279                                  MAX_IS_ALLOCATED_SEARCH, &count)) {
 280            if (count < BDRV_SECTOR_SIZE) {
 281                break;
 282            }
 283            cur_sector += count >> BDRV_SECTOR_BITS;
 284        }
 285        aio_context_release(blk_get_aio_context(bb));
 286        qemu_mutex_unlock_iothread();
 287    }
 288
 289    if (cur_sector >= total_sectors) {
 290        bmds->cur_sector = bmds->completed_sectors = total_sectors;
 291        return 1;
 292    }
 293
 294    bmds->completed_sectors = cur_sector;
 295
 296    cur_sector &= ~((int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK - 1);
 297
 298    /* we are going to transfer a full block even if it is not allocated */
 299    nr_sectors = BDRV_SECTORS_PER_DIRTY_CHUNK;
 300
 301    if (total_sectors - cur_sector < BDRV_SECTORS_PER_DIRTY_CHUNK) {
 302        nr_sectors = total_sectors - cur_sector;
 303    }
 304
 305    blk = g_new(BlkMigBlock, 1);
 306    blk->buf = g_malloc(BLOCK_SIZE);
 307    blk->bmds = bmds;
 308    blk->sector = cur_sector;
 309    blk->nr_sectors = nr_sectors;
 310
 311    blk->iov.iov_base = blk->buf;
 312    blk->iov.iov_len = nr_sectors * BDRV_SECTOR_SIZE;
 313    qemu_iovec_init_external(&blk->qiov, &blk->iov, 1);
 314
 315    blk_mig_lock();
 316    block_mig_state.submitted++;
 317    blk_mig_unlock();
 318
 319    /* We do not know if bs is under the main thread (and thus does
 320     * not acquire the AioContext when doing AIO) or rather under
 321     * dataplane.  Thus acquire both the iothread mutex and the
 322     * AioContext.
 323     *
 324     * This is ugly and will disappear when we make bdrv_* thread-safe,
 325     * without the need to acquire the AioContext.
 326     */
 327    qemu_mutex_lock_iothread();
 328    aio_context_acquire(blk_get_aio_context(bmds->blk));
 329    blk->aiocb = blk_aio_preadv(bb, cur_sector * BDRV_SECTOR_SIZE, &blk->qiov,
 330                                0, blk_mig_read_cb, blk);
 331
 332    bdrv_reset_dirty_bitmap(bmds->dirty_bitmap, cur_sector, nr_sectors);
 333    aio_context_release(blk_get_aio_context(bmds->blk));
 334    qemu_mutex_unlock_iothread();
 335
 336    bmds->cur_sector = cur_sector + nr_sectors;
 337    return (bmds->cur_sector >= total_sectors);
 338}
 339
 340/* Called with iothread lock taken.  */
 341
 342static int set_dirty_tracking(void)
 343{
 344    BlkMigDevState *bmds;
 345    int ret;
 346
 347    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
 348        bmds->dirty_bitmap = bdrv_create_dirty_bitmap(blk_bs(bmds->blk),
 349                                                      BLOCK_SIZE, NULL, NULL);
 350        if (!bmds->dirty_bitmap) {
 351            ret = -errno;
 352            goto fail;
 353        }
 354    }
 355    return 0;
 356
 357fail:
 358    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
 359        if (bmds->dirty_bitmap) {
 360            bdrv_release_dirty_bitmap(blk_bs(bmds->blk), bmds->dirty_bitmap);
 361        }
 362    }
 363    return ret;
 364}
 365
 366/* Called with iothread lock taken.  */
 367
 368static void unset_dirty_tracking(void)
 369{
 370    BlkMigDevState *bmds;
 371
 372    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
 373        bdrv_release_dirty_bitmap(blk_bs(bmds->blk), bmds->dirty_bitmap);
 374    }
 375}
 376
 377static int init_blk_migration(QEMUFile *f)
 378{
 379    BlockDriverState *bs;
 380    BlkMigDevState *bmds;
 381    int64_t sectors;
 382    BdrvNextIterator it;
 383    int i, num_bs = 0;
 384    struct {
 385        BlkMigDevState *bmds;
 386        BlockDriverState *bs;
 387    } *bmds_bs;
 388    Error *local_err = NULL;
 389    int ret;
 390
 391    block_mig_state.submitted = 0;
 392    block_mig_state.read_done = 0;
 393    block_mig_state.transferred = 0;
 394    block_mig_state.total_sector_sum = 0;
 395    block_mig_state.prev_progress = -1;
 396    block_mig_state.bulk_completed = 0;
 397    block_mig_state.zero_blocks = migrate_zero_blocks();
 398
 399    for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
 400        num_bs++;
 401    }
 402    bmds_bs = g_malloc0(num_bs * sizeof(*bmds_bs));
 403
 404    for (i = 0, bs = bdrv_first(&it); bs; bs = bdrv_next(&it), i++) {
 405        if (bdrv_is_read_only(bs)) {
 406            continue;
 407        }
 408
 409        sectors = bdrv_nb_sectors(bs);
 410        if (sectors <= 0) {
 411            ret = sectors;
 412            goto out;
 413        }
 414
 415        bmds = g_new0(BlkMigDevState, 1);
 416        bmds->blk = blk_new(BLK_PERM_CONSISTENT_READ, BLK_PERM_ALL);
 417        bmds->blk_name = g_strdup(bdrv_get_device_name(bs));
 418        bmds->bulk_completed = 0;
 419        bmds->total_sectors = sectors;
 420        bmds->completed_sectors = 0;
 421        bmds->shared_base = migrate_use_block_incremental();
 422
 423        assert(i < num_bs);
 424        bmds_bs[i].bmds = bmds;
 425        bmds_bs[i].bs = bs;
 426
 427        block_mig_state.total_sector_sum += sectors;
 428
 429        if (bmds->shared_base) {
 430            DPRINTF("Start migration for %s with shared base image\n",
 431                    bdrv_get_device_name(bs));
 432        } else {
 433            DPRINTF("Start full migration for %s\n", bdrv_get_device_name(bs));
 434        }
 435
 436        QSIMPLEQ_INSERT_TAIL(&block_mig_state.bmds_list, bmds, entry);
 437    }
 438
 439    /* Can only insert new BDSes now because doing so while iterating block
 440     * devices may end up in a deadlock (iterating the new BDSes, too). */
 441    for (i = 0; i < num_bs; i++) {
 442        BlkMigDevState *bmds = bmds_bs[i].bmds;
 443        BlockDriverState *bs = bmds_bs[i].bs;
 444
 445        if (bmds) {
 446            ret = blk_insert_bs(bmds->blk, bs, &local_err);
 447            if (ret < 0) {
 448                error_report_err(local_err);
 449                goto out;
 450            }
 451
 452            alloc_aio_bitmap(bmds);
 453            error_setg(&bmds->blocker, "block device is in use by migration");
 454            bdrv_op_block_all(bs, bmds->blocker);
 455        }
 456    }
 457
 458    ret = 0;
 459out:
 460    g_free(bmds_bs);
 461    return ret;
 462}
 463
 464/* Called with no lock taken.  */
 465
 466static int blk_mig_save_bulked_block(QEMUFile *f)
 467{
 468    int64_t completed_sector_sum = 0;
 469    BlkMigDevState *bmds;
 470    int progress;
 471    int ret = 0;
 472
 473    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
 474        if (bmds->bulk_completed == 0) {
 475            if (mig_save_device_bulk(f, bmds) == 1) {
 476                /* completed bulk section for this device */
 477                bmds->bulk_completed = 1;
 478            }
 479            completed_sector_sum += bmds->completed_sectors;
 480            ret = 1;
 481            break;
 482        } else {
 483            completed_sector_sum += bmds->completed_sectors;
 484        }
 485    }
 486
 487    if (block_mig_state.total_sector_sum != 0) {
 488        progress = completed_sector_sum * 100 /
 489                   block_mig_state.total_sector_sum;
 490    } else {
 491        progress = 100;
 492    }
 493    if (progress != block_mig_state.prev_progress) {
 494        block_mig_state.prev_progress = progress;
 495        qemu_put_be64(f, (progress << BDRV_SECTOR_BITS)
 496                         | BLK_MIG_FLAG_PROGRESS);
 497        DPRINTF("Completed %d %%\r", progress);
 498    }
 499
 500    return ret;
 501}
 502
 503static void blk_mig_reset_dirty_cursor(void)
 504{
 505    BlkMigDevState *bmds;
 506
 507    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
 508        bmds->cur_dirty = 0;
 509    }
 510}
 511
 512/* Called with iothread lock and AioContext taken.  */
 513
 514static int mig_save_device_dirty(QEMUFile *f, BlkMigDevState *bmds,
 515                                 int is_async)
 516{
 517    BlkMigBlock *blk;
 518    BlockDriverState *bs = blk_bs(bmds->blk);
 519    int64_t total_sectors = bmds->total_sectors;
 520    int64_t sector;
 521    int nr_sectors;
 522    int ret = -EIO;
 523
 524    for (sector = bmds->cur_dirty; sector < bmds->total_sectors;) {
 525        blk_mig_lock();
 526        if (bmds_aio_inflight(bmds, sector)) {
 527            blk_mig_unlock();
 528            blk_drain(bmds->blk);
 529        } else {
 530            blk_mig_unlock();
 531        }
 532        bdrv_dirty_bitmap_lock(bmds->dirty_bitmap);
 533        if (bdrv_get_dirty_locked(bs, bmds->dirty_bitmap, sector)) {
 534            if (total_sectors - sector < BDRV_SECTORS_PER_DIRTY_CHUNK) {
 535                nr_sectors = total_sectors - sector;
 536            } else {
 537                nr_sectors = BDRV_SECTORS_PER_DIRTY_CHUNK;
 538            }
 539            bdrv_reset_dirty_bitmap_locked(bmds->dirty_bitmap, sector, nr_sectors);
 540            bdrv_dirty_bitmap_unlock(bmds->dirty_bitmap);
 541
 542            blk = g_new(BlkMigBlock, 1);
 543            blk->buf = g_malloc(BLOCK_SIZE);
 544            blk->bmds = bmds;
 545            blk->sector = sector;
 546            blk->nr_sectors = nr_sectors;
 547
 548            if (is_async) {
 549                blk->iov.iov_base = blk->buf;
 550                blk->iov.iov_len = nr_sectors * BDRV_SECTOR_SIZE;
 551                qemu_iovec_init_external(&blk->qiov, &blk->iov, 1);
 552
 553                blk->aiocb = blk_aio_preadv(bmds->blk,
 554                                            sector * BDRV_SECTOR_SIZE,
 555                                            &blk->qiov, 0, blk_mig_read_cb,
 556                                            blk);
 557
 558                blk_mig_lock();
 559                block_mig_state.submitted++;
 560                bmds_set_aio_inflight(bmds, sector, nr_sectors, 1);
 561                blk_mig_unlock();
 562            } else {
 563                ret = blk_pread(bmds->blk, sector * BDRV_SECTOR_SIZE, blk->buf,
 564                                nr_sectors * BDRV_SECTOR_SIZE);
 565                if (ret < 0) {
 566                    goto error;
 567                }
 568                blk_send(f, blk);
 569
 570                g_free(blk->buf);
 571                g_free(blk);
 572            }
 573
 574            sector += nr_sectors;
 575            bmds->cur_dirty = sector;
 576            break;
 577        }
 578
 579        bdrv_dirty_bitmap_unlock(bmds->dirty_bitmap);
 580        sector += BDRV_SECTORS_PER_DIRTY_CHUNK;
 581        bmds->cur_dirty = sector;
 582    }
 583
 584    return (bmds->cur_dirty >= bmds->total_sectors);
 585
 586error:
 587    DPRINTF("Error reading sector %" PRId64 "\n", sector);
 588    g_free(blk->buf);
 589    g_free(blk);
 590    return ret;
 591}
 592
 593/* Called with iothread lock taken.
 594 *
 595 * return value:
 596 * 0: too much data for max_downtime
 597 * 1: few enough data for max_downtime
 598*/
 599static int blk_mig_save_dirty_block(QEMUFile *f, int is_async)
 600{
 601    BlkMigDevState *bmds;
 602    int ret = 1;
 603
 604    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
 605        aio_context_acquire(blk_get_aio_context(bmds->blk));
 606        ret = mig_save_device_dirty(f, bmds, is_async);
 607        aio_context_release(blk_get_aio_context(bmds->blk));
 608        if (ret <= 0) {
 609            break;
 610        }
 611    }
 612
 613    return ret;
 614}
 615
 616/* Called with no locks taken.  */
 617
 618static int flush_blks(QEMUFile *f)
 619{
 620    BlkMigBlock *blk;
 621    int ret = 0;
 622
 623    DPRINTF("%s Enter submitted %d read_done %d transferred %d\n",
 624            __FUNCTION__, block_mig_state.submitted, block_mig_state.read_done,
 625            block_mig_state.transferred);
 626
 627    blk_mig_lock();
 628    while ((blk = QSIMPLEQ_FIRST(&block_mig_state.blk_list)) != NULL) {
 629        if (qemu_file_rate_limit(f)) {
 630            break;
 631        }
 632        if (blk->ret < 0) {
 633            ret = blk->ret;
 634            break;
 635        }
 636
 637        QSIMPLEQ_REMOVE_HEAD(&block_mig_state.blk_list, entry);
 638        blk_mig_unlock();
 639        blk_send(f, blk);
 640        blk_mig_lock();
 641
 642        g_free(blk->buf);
 643        g_free(blk);
 644
 645        block_mig_state.read_done--;
 646        block_mig_state.transferred++;
 647        assert(block_mig_state.read_done >= 0);
 648    }
 649    blk_mig_unlock();
 650
 651    DPRINTF("%s Exit submitted %d read_done %d transferred %d\n", __FUNCTION__,
 652            block_mig_state.submitted, block_mig_state.read_done,
 653            block_mig_state.transferred);
 654    return ret;
 655}
 656
 657/* Called with iothread lock taken.  */
 658
 659static int64_t get_remaining_dirty(void)
 660{
 661    BlkMigDevState *bmds;
 662    int64_t dirty = 0;
 663
 664    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
 665        aio_context_acquire(blk_get_aio_context(bmds->blk));
 666        dirty += bdrv_get_dirty_count(bmds->dirty_bitmap);
 667        aio_context_release(blk_get_aio_context(bmds->blk));
 668    }
 669
 670    return dirty << BDRV_SECTOR_BITS;
 671}
 672
 673
 674
 675/* Called with iothread lock taken.  */
 676static void block_migration_cleanup_bmds(void)
 677{
 678    BlkMigDevState *bmds;
 679    AioContext *ctx;
 680
 681    unset_dirty_tracking();
 682
 683    while ((bmds = QSIMPLEQ_FIRST(&block_mig_state.bmds_list)) != NULL) {
 684        QSIMPLEQ_REMOVE_HEAD(&block_mig_state.bmds_list, entry);
 685        bdrv_op_unblock_all(blk_bs(bmds->blk), bmds->blocker);
 686        error_free(bmds->blocker);
 687
 688        /* Save ctx, because bmds->blk can disappear during blk_unref.  */
 689        ctx = blk_get_aio_context(bmds->blk);
 690        aio_context_acquire(ctx);
 691        blk_unref(bmds->blk);
 692        aio_context_release(ctx);
 693
 694        g_free(bmds->blk_name);
 695        g_free(bmds->aio_bitmap);
 696        g_free(bmds);
 697    }
 698}
 699
 700/* Called with iothread lock taken.  */
 701static void block_migration_cleanup(void *opaque)
 702{
 703    BlkMigBlock *blk;
 704
 705    bdrv_drain_all();
 706
 707    block_migration_cleanup_bmds();
 708
 709    blk_mig_lock();
 710    while ((blk = QSIMPLEQ_FIRST(&block_mig_state.blk_list)) != NULL) {
 711        QSIMPLEQ_REMOVE_HEAD(&block_mig_state.blk_list, entry);
 712        g_free(blk->buf);
 713        g_free(blk);
 714    }
 715    blk_mig_unlock();
 716}
 717
 718static int block_save_setup(QEMUFile *f, void *opaque)
 719{
 720    int ret;
 721
 722    DPRINTF("Enter save live setup submitted %d transferred %d\n",
 723            block_mig_state.submitted, block_mig_state.transferred);
 724
 725    qemu_mutex_lock_iothread();
 726    ret = init_blk_migration(f);
 727    if (ret < 0) {
 728        qemu_mutex_unlock_iothread();
 729        return ret;
 730    }
 731
 732    /* start track dirty blocks */
 733    ret = set_dirty_tracking();
 734
 735    qemu_mutex_unlock_iothread();
 736
 737    if (ret) {
 738        return ret;
 739    }
 740
 741    ret = flush_blks(f);
 742    blk_mig_reset_dirty_cursor();
 743    qemu_put_be64(f, BLK_MIG_FLAG_EOS);
 744
 745    return ret;
 746}
 747
 748static int block_save_iterate(QEMUFile *f, void *opaque)
 749{
 750    int ret;
 751    int64_t last_ftell = qemu_ftell(f);
 752    int64_t delta_ftell;
 753
 754    DPRINTF("Enter save live iterate submitted %d transferred %d\n",
 755            block_mig_state.submitted, block_mig_state.transferred);
 756
 757    ret = flush_blks(f);
 758    if (ret) {
 759        return ret;
 760    }
 761
 762    blk_mig_reset_dirty_cursor();
 763
 764    /* control the rate of transfer */
 765    blk_mig_lock();
 766    while ((block_mig_state.submitted +
 767            block_mig_state.read_done) * BLOCK_SIZE <
 768           qemu_file_get_rate_limit(f) &&
 769           (block_mig_state.submitted +
 770            block_mig_state.read_done) <
 771           MAX_INFLIGHT_IO) {
 772        blk_mig_unlock();
 773        if (block_mig_state.bulk_completed == 0) {
 774            /* first finish the bulk phase */
 775            if (blk_mig_save_bulked_block(f) == 0) {
 776                /* finished saving bulk on all devices */
 777                block_mig_state.bulk_completed = 1;
 778            }
 779            ret = 0;
 780        } else {
 781            /* Always called with iothread lock taken for
 782             * simplicity, block_save_complete also calls it.
 783             */
 784            qemu_mutex_lock_iothread();
 785            ret = blk_mig_save_dirty_block(f, 1);
 786            qemu_mutex_unlock_iothread();
 787        }
 788        if (ret < 0) {
 789            return ret;
 790        }
 791        blk_mig_lock();
 792        if (ret != 0) {
 793            /* no more dirty blocks */
 794            break;
 795        }
 796    }
 797    blk_mig_unlock();
 798
 799    ret = flush_blks(f);
 800    if (ret) {
 801        return ret;
 802    }
 803
 804    qemu_put_be64(f, BLK_MIG_FLAG_EOS);
 805    delta_ftell = qemu_ftell(f) - last_ftell;
 806    if (delta_ftell > 0) {
 807        return 1;
 808    } else if (delta_ftell < 0) {
 809        return -1;
 810    } else {
 811        return 0;
 812    }
 813}
 814
 815/* Called with iothread lock taken.  */
 816
 817static int block_save_complete(QEMUFile *f, void *opaque)
 818{
 819    int ret;
 820
 821    DPRINTF("Enter save live complete submitted %d transferred %d\n",
 822            block_mig_state.submitted, block_mig_state.transferred);
 823
 824    ret = flush_blks(f);
 825    if (ret) {
 826        return ret;
 827    }
 828
 829    blk_mig_reset_dirty_cursor();
 830
 831    /* we know for sure that save bulk is completed and
 832       all async read completed */
 833    blk_mig_lock();
 834    assert(block_mig_state.submitted == 0);
 835    blk_mig_unlock();
 836
 837    do {
 838        ret = blk_mig_save_dirty_block(f, 0);
 839        if (ret < 0) {
 840            return ret;
 841        }
 842    } while (ret == 0);
 843
 844    /* report completion */
 845    qemu_put_be64(f, (100 << BDRV_SECTOR_BITS) | BLK_MIG_FLAG_PROGRESS);
 846
 847    DPRINTF("Block migration completed\n");
 848
 849    qemu_put_be64(f, BLK_MIG_FLAG_EOS);
 850
 851    /* Make sure that our BlockBackends are gone, so that the block driver
 852     * nodes can be inactivated. */
 853    block_migration_cleanup_bmds();
 854
 855    return 0;
 856}
 857
 858static void block_save_pending(QEMUFile *f, void *opaque, uint64_t max_size,
 859                               uint64_t *non_postcopiable_pending,
 860                               uint64_t *postcopiable_pending)
 861{
 862    /* Estimate pending number of bytes to send */
 863    uint64_t pending;
 864
 865    qemu_mutex_lock_iothread();
 866    pending = get_remaining_dirty();
 867    qemu_mutex_unlock_iothread();
 868
 869    blk_mig_lock();
 870    pending += block_mig_state.submitted * BLOCK_SIZE +
 871               block_mig_state.read_done * BLOCK_SIZE;
 872    blk_mig_unlock();
 873
 874    /* Report at least one block pending during bulk phase */
 875    if (pending <= max_size && !block_mig_state.bulk_completed) {
 876        pending = max_size + BLOCK_SIZE;
 877    }
 878
 879    DPRINTF("Enter save live pending  %" PRIu64 "\n", pending);
 880    /* We don't do postcopy */
 881    *non_postcopiable_pending += pending;
 882}
 883
 884static int block_load(QEMUFile *f, void *opaque, int version_id)
 885{
 886    static int banner_printed;
 887    int len, flags;
 888    char device_name[256];
 889    int64_t addr;
 890    BlockBackend *blk, *blk_prev = NULL;;
 891    Error *local_err = NULL;
 892    uint8_t *buf;
 893    int64_t total_sectors = 0;
 894    int nr_sectors;
 895    int ret;
 896    BlockDriverInfo bdi;
 897    int cluster_size = BLOCK_SIZE;
 898
 899    do {
 900        addr = qemu_get_be64(f);
 901
 902        flags = addr & ~BDRV_SECTOR_MASK;
 903        addr >>= BDRV_SECTOR_BITS;
 904
 905        if (flags & BLK_MIG_FLAG_DEVICE_BLOCK) {
 906            /* get device name */
 907            len = qemu_get_byte(f);
 908            qemu_get_buffer(f, (uint8_t *)device_name, len);
 909            device_name[len] = '\0';
 910
 911            blk = blk_by_name(device_name);
 912            if (!blk) {
 913                fprintf(stderr, "Error unknown block device %s\n",
 914                        device_name);
 915                return -EINVAL;
 916            }
 917
 918            if (blk != blk_prev) {
 919                blk_prev = blk;
 920                total_sectors = blk_nb_sectors(blk);
 921                if (total_sectors <= 0) {
 922                    error_report("Error getting length of block device %s",
 923                                 device_name);
 924                    return -EINVAL;
 925                }
 926
 927                blk_invalidate_cache(blk, &local_err);
 928                if (local_err) {
 929                    error_report_err(local_err);
 930                    return -EINVAL;
 931                }
 932
 933                ret = bdrv_get_info(blk_bs(blk), &bdi);
 934                if (ret == 0 && bdi.cluster_size > 0 &&
 935                    bdi.cluster_size <= BLOCK_SIZE &&
 936                    BLOCK_SIZE % bdi.cluster_size == 0) {
 937                    cluster_size = bdi.cluster_size;
 938                } else {
 939                    cluster_size = BLOCK_SIZE;
 940                }
 941            }
 942
 943            if (total_sectors - addr < BDRV_SECTORS_PER_DIRTY_CHUNK) {
 944                nr_sectors = total_sectors - addr;
 945            } else {
 946                nr_sectors = BDRV_SECTORS_PER_DIRTY_CHUNK;
 947            }
 948
 949            if (flags & BLK_MIG_FLAG_ZERO_BLOCK) {
 950                ret = blk_pwrite_zeroes(blk, addr * BDRV_SECTOR_SIZE,
 951                                        nr_sectors * BDRV_SECTOR_SIZE,
 952                                        BDRV_REQ_MAY_UNMAP);
 953            } else {
 954                int i;
 955                int64_t cur_addr;
 956                uint8_t *cur_buf;
 957
 958                buf = g_malloc(BLOCK_SIZE);
 959                qemu_get_buffer(f, buf, BLOCK_SIZE);
 960                for (i = 0; i < BLOCK_SIZE / cluster_size; i++) {
 961                    cur_addr = addr * BDRV_SECTOR_SIZE + i * cluster_size;
 962                    cur_buf = buf + i * cluster_size;
 963
 964                    if ((!block_mig_state.zero_blocks ||
 965                        cluster_size < BLOCK_SIZE) &&
 966                        buffer_is_zero(cur_buf, cluster_size)) {
 967                        ret = blk_pwrite_zeroes(blk, cur_addr,
 968                                                cluster_size,
 969                                                BDRV_REQ_MAY_UNMAP);
 970                    } else {
 971                        ret = blk_pwrite(blk, cur_addr, cur_buf,
 972                                         cluster_size, 0);
 973                    }
 974                    if (ret < 0) {
 975                        break;
 976                    }
 977                }
 978                g_free(buf);
 979            }
 980
 981            if (ret < 0) {
 982                return ret;
 983            }
 984        } else if (flags & BLK_MIG_FLAG_PROGRESS) {
 985            if (!banner_printed) {
 986                printf("Receiving block device images\n");
 987                banner_printed = 1;
 988            }
 989            printf("Completed %d %%%c", (int)addr,
 990                   (addr == 100) ? '\n' : '\r');
 991            fflush(stdout);
 992        } else if (!(flags & BLK_MIG_FLAG_EOS)) {
 993            fprintf(stderr, "Unknown block migration flags: %#x\n", flags);
 994            return -EINVAL;
 995        }
 996        ret = qemu_file_get_error(f);
 997        if (ret != 0) {
 998            return ret;
 999        }
1000    } while (!(flags & BLK_MIG_FLAG_EOS));
1001
1002    return 0;
1003}
1004
1005static bool block_is_active(void *opaque)
1006{
1007    return migrate_use_block();
1008}
1009
1010static SaveVMHandlers savevm_block_handlers = {
1011    .save_setup = block_save_setup,
1012    .save_live_iterate = block_save_iterate,
1013    .save_live_complete_precopy = block_save_complete,
1014    .save_live_pending = block_save_pending,
1015    .load_state = block_load,
1016    .save_cleanup = block_migration_cleanup,
1017    .is_active = block_is_active,
1018};
1019
1020void blk_mig_init(void)
1021{
1022    QSIMPLEQ_INIT(&block_mig_state.bmds_list);
1023    QSIMPLEQ_INIT(&block_mig_state.blk_list);
1024    qemu_mutex_init(&block_mig_state.lock);
1025
1026    register_savevm_live(NULL, "block", 0, 1, &savevm_block_handlers,
1027                         &block_mig_state);
1028}
1029