block.c 28.7 KB
Newer Older
L
lirans@il.ibm.com 已提交
1 2 3 4 5 6 7 8 9 10 11
/*
 * QEMU live block migration
 *
 * Copyright IBM, Corp. 2009
 *
 * Authors:
 *  Liran Schour   <lirans@il.ibm.com>
 *
 * This work is licensed under the terms of the GNU GPL, version 2.  See
 * the COPYING file in the top-level directory.
 *
12 13
 * Contributions after 2012-01-13 are licensed under the terms of the
 * GNU GPL, version 2 or (at your option) any later version.
L
lirans@il.ibm.com 已提交
14 15
 */

P
Peter Maydell 已提交
16
#include "qemu/osdep.h"
17
#include "qapi/error.h"
L
lirans@il.ibm.com 已提交
18
#include "qemu-common.h"
19 20 21
#include "block/block.h"
#include "qemu/error-report.h"
#include "qemu/main-loop.h"
L
lirans@il.ibm.com 已提交
22
#include "hw/hw.h"
23
#include "qemu/cutils.h"
24 25
#include "qemu/queue.h"
#include "qemu/timer.h"
26 27
#include "block.h"
#include "migration/misc.h"
28
#include "migration.h"
29
#include "migration/register.h"
30
#include "sysemu/blockdev.h"
J
Juan Quintela 已提交
31
#include "qemu-file.h"
32
#include "migration/vmstate.h"
33
#include "sysemu/block-backend.h"
L
lirans@il.ibm.com 已提交
34

35 36
#define BLOCK_SIZE                       (1 << 20)
#define BDRV_SECTORS_PER_DIRTY_CHUNK     (BLOCK_SIZE >> BDRV_SECTOR_BITS)
L
lirans@il.ibm.com 已提交
37 38 39

#define BLK_MIG_FLAG_DEVICE_BLOCK       0x01
#define BLK_MIG_FLAG_EOS                0x02
40
#define BLK_MIG_FLAG_PROGRESS           0x04
41
#define BLK_MIG_FLAG_ZERO_BLOCK         0x08
L
lirans@il.ibm.com 已提交
42 43 44

#define MAX_IS_ALLOCATED_SEARCH 65536

45 46
#define MAX_INFLIGHT_IO 512

L
lirans@il.ibm.com 已提交
47 48 49
//#define DEBUG_BLK_MIGRATION

#ifdef DEBUG_BLK_MIGRATION
M
malc 已提交
50
#define DPRINTF(fmt, ...) \
L
lirans@il.ibm.com 已提交
51 52
    do { printf("blk_migration: " fmt, ## __VA_ARGS__); } while (0)
#else
M
malc 已提交
53
#define DPRINTF(fmt, ...) \
L
lirans@il.ibm.com 已提交
54 55 56
    do { } while (0)
#endif

57
typedef struct BlkMigDevState {
58
    /* Written during setup phase.  Can be read without a lock.  */
59 60
    BlockBackend *blk;
    char *blk_name;
61 62
    int shared_base;
    int64_t total_sectors;
63
    QSIMPLEQ_ENTRY(BlkMigDevState) entry;
64
    Error *blocker;
65 66 67 68 69 70

    /* Only used by migration thread.  Does not need a lock.  */
    int bulk_completed;
    int64_t cur_sector;
    int64_t cur_dirty;

71 72 73
    /* Data in the aio_bitmap is protected by block migration lock.
     * Allocation and free happen during setup and cleanup respectively.
     */
74
    unsigned long *aio_bitmap;
75 76

    /* Protected by block migration lock.  */
77
    int64_t completed_sectors;
78 79 80 81

    /* During migration this is protected by iothread lock / AioContext.
     * Allocation and free happen during setup and cleanup respectively.
     */
F
Fam Zheng 已提交
82
    BdrvDirtyBitmap *dirty_bitmap;
83 84
} BlkMigDevState;

L
lirans@il.ibm.com 已提交
85
typedef struct BlkMigBlock {
86
    /* Only used by migration thread.  */
L
lirans@il.ibm.com 已提交
87 88 89
    uint8_t *buf;
    BlkMigDevState *bmds;
    int64_t sector;
90
    int nr_sectors;
L
lirans@il.ibm.com 已提交
91 92
    struct iovec iov;
    QEMUIOVector qiov;
93
    BlockAIOCB *aiocb;
94

P
Paolo Bonzini 已提交
95
    /* Protected by block migration lock.  */
L
lirans@il.ibm.com 已提交
96
    int ret;
97
    QSIMPLEQ_ENTRY(BlkMigBlock) entry;
L
lirans@il.ibm.com 已提交
98 99 100
} BlkMigBlock;

typedef struct BlkMigState {
101
    QSIMPLEQ_HEAD(bmds_list, BlkMigDevState) bmds_list;
102
    int64_t total_sector_sum;
103
    bool zero_blocks;
104

P
Paolo Bonzini 已提交
105
    /* Protected by lock.  */
106
    QSIMPLEQ_HEAD(blk_list, BlkMigBlock) blk_list;
L
lirans@il.ibm.com 已提交
107 108
    int submitted;
    int read_done;
109 110

    /* Only used by migration thread.  Does not need a lock.  */
L
lirans@il.ibm.com 已提交
111
    int transferred;
112
    int prev_progress;
L
Liran Schour 已提交
113
    int bulk_completed;
P
Paolo Bonzini 已提交
114

115
    /* Lock must be taken _inside_ the iothread lock and any AioContexts.  */
P
Paolo Bonzini 已提交
116
    QemuMutex lock;
L
lirans@il.ibm.com 已提交
117 118
} BlkMigState;

119
static BlkMigState block_mig_state;
L
lirans@il.ibm.com 已提交
120

P
Paolo Bonzini 已提交
121 122 123 124 125 126 127 128 129 130
static void blk_mig_lock(void)
{
    qemu_mutex_lock(&block_mig_state.lock);
}

static void blk_mig_unlock(void)
{
    qemu_mutex_unlock(&block_mig_state.lock);
}

131 132 133 134
/* Must run outside of the iothread lock during the bulk phase,
 * or the VM will stall.
 */

135 136 137
static void blk_send(QEMUFile *f, BlkMigBlock * blk)
{
    int len;
138 139 140 141 142 143
    uint64_t flags = BLK_MIG_FLAG_DEVICE_BLOCK;

    if (block_mig_state.zero_blocks &&
        buffer_is_zero(blk->buf, BLOCK_SIZE)) {
        flags |= BLK_MIG_FLAG_ZERO_BLOCK;
    }
144 145 146

    /* sector number and flags */
    qemu_put_be64(f, (blk->sector << BDRV_SECTOR_BITS)
147
                     | flags);
148 149

    /* device name */
150
    len = strlen(blk->bmds->blk_name);
151
    qemu_put_byte(f, len);
152
    qemu_put_buffer(f, (uint8_t *) blk->bmds->blk_name, len);
153

154 155 156 157 158 159 160 161
    /* if a block is zero we need to flush here since the network
     * bandwidth is now a lot higher than the storage device bandwidth.
     * thus if we queue zero blocks we slow down the migration */
    if (flags & BLK_MIG_FLAG_ZERO_BLOCK) {
        qemu_fflush(f);
        return;
    }

162 163 164
    qemu_put_buffer(f, blk->buf, BLOCK_SIZE);
}

165 166 167 168 169 170 171 172 173 174
int blk_mig_active(void)
{
    return !QSIMPLEQ_EMPTY(&block_mig_state.bmds_list);
}

uint64_t blk_mig_bytes_transferred(void)
{
    BlkMigDevState *bmds;
    uint64_t sum = 0;

P
Paolo Bonzini 已提交
175
    blk_mig_lock();
176 177 178
    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
        sum += bmds->completed_sectors;
    }
P
Paolo Bonzini 已提交
179
    blk_mig_unlock();
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
    return sum << BDRV_SECTOR_BITS;
}

uint64_t blk_mig_bytes_remaining(void)
{
    return blk_mig_bytes_total() - blk_mig_bytes_transferred();
}

uint64_t blk_mig_bytes_total(void)
{
    BlkMigDevState *bmds;
    uint64_t sum = 0;

    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
        sum += bmds->total_sectors;
    }
    return sum << BDRV_SECTOR_BITS;
}

P
Paolo Bonzini 已提交
199 200 201

/* Called with migration lock held.  */

202 203 204 205
static int bmds_aio_inflight(BlkMigDevState *bmds, int64_t sector)
{
    int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;

206
    if (sector < blk_nb_sectors(bmds->blk)) {
207 208 209 210 211 212 213
        return !!(bmds->aio_bitmap[chunk / (sizeof(unsigned long) * 8)] &
            (1UL << (chunk % (sizeof(unsigned long) * 8))));
    } else {
        return 0;
    }
}

P
Paolo Bonzini 已提交
214 215
/* Called with migration lock held.  */

216 217 218 219 220 221 222 223 224 225 226 227 228 229
static void bmds_set_aio_inflight(BlkMigDevState *bmds, int64_t sector_num,
                             int nb_sectors, int set)
{
    int64_t start, end;
    unsigned long val, idx, bit;

    start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
    end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;

    for (; start <= end; start++) {
        idx = start / (sizeof(unsigned long) * 8);
        bit = start % (sizeof(unsigned long) * 8);
        val = bmds->aio_bitmap[idx];
        if (set) {
230
            val |= 1UL << bit;
231
        } else {
232
            val &= ~(1UL << bit);
233 234 235 236 237 238 239
        }
        bmds->aio_bitmap[idx] = val;
    }
}

static void alloc_aio_bitmap(BlkMigDevState *bmds)
{
240
    BlockBackend *bb = bmds->blk;
241 242
    int64_t bitmap_size;

243
    bitmap_size = blk_nb_sectors(bb) + BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
244 245
    bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;

246
    bmds->aio_bitmap = g_malloc0(bitmap_size);
247 248
}

P
Paolo Bonzini 已提交
249 250
/* Never hold migration lock when yielding to the main loop!  */

L
lirans@il.ibm.com 已提交
251 252 253
static void blk_mig_read_cb(void *opaque, int ret)
{
    BlkMigBlock *blk = opaque;
254

P
Paolo Bonzini 已提交
255
    blk_mig_lock();
L
lirans@il.ibm.com 已提交
256
    blk->ret = ret;
257

258
    QSIMPLEQ_INSERT_TAIL(&block_mig_state.blk_list, blk, entry);
259
    bmds_set_aio_inflight(blk->bmds, blk->sector, blk->nr_sectors, 0);
260

261 262 263
    block_mig_state.submitted--;
    block_mig_state.read_done++;
    assert(block_mig_state.submitted >= 0);
P
Paolo Bonzini 已提交
264
    blk_mig_unlock();
L
lirans@il.ibm.com 已提交
265 266
}

267 268
/* Called with no lock taken.  */

269
static int mig_save_device_bulk(QEMUFile *f, BlkMigDevState *bmds)
270
{
271 272
    int64_t total_sectors = bmds->total_sectors;
    int64_t cur_sector = bmds->cur_sector;
273
    BlockBackend *bb = bmds->blk;
L
lirans@il.ibm.com 已提交
274
    BlkMigBlock *blk;
275
    int nr_sectors;
276

277
    if (bmds->shared_base) {
278
        qemu_mutex_lock_iothread();
279
        aio_context_acquire(blk_get_aio_context(bb));
280 281
        /* Skip unallocated sectors; intentionally treats failure as
         * an allocated sector */
282
        while (cur_sector < total_sectors &&
283 284
               !bdrv_is_allocated(blk_bs(bb), cur_sector,
                                  MAX_IS_ALLOCATED_SEARCH, &nr_sectors)) {
L
lirans@il.ibm.com 已提交
285 286
            cur_sector += nr_sectors;
        }
287
        aio_context_release(blk_get_aio_context(bb));
288
        qemu_mutex_unlock_iothread();
L
lirans@il.ibm.com 已提交
289
    }
290 291

    if (cur_sector >= total_sectors) {
292
        bmds->cur_sector = bmds->completed_sectors = total_sectors;
L
lirans@il.ibm.com 已提交
293 294
        return 1;
    }
295

296
    bmds->completed_sectors = cur_sector;
297

298 299
    cur_sector &= ~((int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK - 1);

J
Jan Kiszka 已提交
300 301
    /* we are going to transfer a full block even if it is not allocated */
    nr_sectors = BDRV_SECTORS_PER_DIRTY_CHUNK;
L
lirans@il.ibm.com 已提交
302

J
Jan Kiszka 已提交
303
    if (total_sectors - cur_sector < BDRV_SECTORS_PER_DIRTY_CHUNK) {
304
        nr_sectors = total_sectors - cur_sector;
L
lirans@il.ibm.com 已提交
305
    }
306

307
    blk = g_new(BlkMigBlock, 1);
308
    blk->buf = g_malloc(BLOCK_SIZE);
309 310
    blk->bmds = bmds;
    blk->sector = cur_sector;
311
    blk->nr_sectors = nr_sectors;
312

L
Liran Schour 已提交
313 314 315
    blk->iov.iov_base = blk->buf;
    blk->iov.iov_len = nr_sectors * BDRV_SECTOR_SIZE;
    qemu_iovec_init_external(&blk->qiov, &blk->iov, 1);
316

P
Paolo Bonzini 已提交
317
    blk_mig_lock();
318
    block_mig_state.submitted++;
P
Paolo Bonzini 已提交
319
    blk_mig_unlock();
320

321 322 323 324 325 326 327 328
    /* We do not know if bs is under the main thread (and thus does
     * not acquire the AioContext when doing AIO) or rather under
     * dataplane.  Thus acquire both the iothread mutex and the
     * AioContext.
     *
     * This is ugly and will disappear when we make bdrv_* thread-safe,
     * without the need to acquire the AioContext.
     */
329
    qemu_mutex_lock_iothread();
330 331 332
    aio_context_acquire(blk_get_aio_context(bmds->blk));
    blk->aiocb = blk_aio_preadv(bb, cur_sector * BDRV_SECTOR_SIZE, &blk->qiov,
                                0, blk_mig_read_cb, blk);
333

334
    bdrv_reset_dirty_bitmap(bmds->dirty_bitmap, cur_sector, nr_sectors);
335
    aio_context_release(blk_get_aio_context(bmds->blk));
336
    qemu_mutex_unlock_iothread();
337

338
    bmds->cur_sector = cur_sector + nr_sectors;
339
    return (bmds->cur_sector >= total_sectors);
L
lirans@il.ibm.com 已提交
340 341
}

342 343
/* Called with iothread lock taken.  */

344
static int set_dirty_tracking(void)
L
lirans@il.ibm.com 已提交
345 346
{
    BlkMigDevState *bmds;
347 348 349
    int ret;

    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
350 351 352 353
        aio_context_acquire(blk_get_aio_context(bmds->blk));
        bmds->dirty_bitmap = bdrv_create_dirty_bitmap(blk_bs(bmds->blk),
                                                      BLOCK_SIZE, NULL, NULL);
        aio_context_release(blk_get_aio_context(bmds->blk));
354 355 356 357 358 359
        if (!bmds->dirty_bitmap) {
            ret = -errno;
            goto fail;
        }
    }
    return 0;
360

361
fail:
362
    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
363
        if (bmds->dirty_bitmap) {
364 365 366
            aio_context_acquire(blk_get_aio_context(bmds->blk));
            bdrv_release_dirty_bitmap(blk_bs(bmds->blk), bmds->dirty_bitmap);
            aio_context_release(blk_get_aio_context(bmds->blk));
367
        }
F
Fam Zheng 已提交
368
    }
369
    return ret;
F
Fam Zheng 已提交
370 371
}

372 373
/* Called with iothread lock taken.  */

F
Fam Zheng 已提交
374 375 376 377 378
static void unset_dirty_tracking(void)
{
    BlkMigDevState *bmds;

    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
379 380 381
        aio_context_acquire(blk_get_aio_context(bmds->blk));
        bdrv_release_dirty_bitmap(blk_bs(bmds->blk), bmds->dirty_bitmap);
        aio_context_release(blk_get_aio_context(bmds->blk));
L
lirans@il.ibm.com 已提交
382 383 384
    }
}

385
static int init_blk_migration(QEMUFile *f)
L
lirans@il.ibm.com 已提交
386
{
387
    BlockDriverState *bs;
388
    BlkMigDevState *bmds;
389
    int64_t sectors;
K
Kevin Wolf 已提交
390
    BdrvNextIterator it;
391 392 393 394 395
    int i, num_bs = 0;
    struct {
        BlkMigDevState *bmds;
        BlockDriverState *bs;
    } *bmds_bs;
396 397
    Error *local_err = NULL;
    int ret;
398

399 400 401 402 403 404 405 406
    block_mig_state.submitted = 0;
    block_mig_state.read_done = 0;
    block_mig_state.transferred = 0;
    block_mig_state.total_sector_sum = 0;
    block_mig_state.prev_progress = -1;
    block_mig_state.bulk_completed = 0;
    block_mig_state.zero_blocks = migrate_zero_blocks();

K
Kevin Wolf 已提交
407
    for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
408 409 410 411 412
        num_bs++;
    }
    bmds_bs = g_malloc0(num_bs * sizeof(*bmds_bs));

    for (i = 0, bs = bdrv_first(&it); bs; bs = bdrv_next(&it), i++) {
413 414 415 416
        if (bdrv_is_read_only(bs)) {
            continue;
        }

417
        sectors = bdrv_nb_sectors(bs);
418
        if (sectors <= 0) {
419
            ret = sectors;
420
            goto out;
421 422
        }

423
        bmds = g_new0(BlkMigDevState, 1);
424
        bmds->blk = blk_new(BLK_PERM_CONSISTENT_READ, BLK_PERM_ALL);
425
        bmds->blk_name = g_strdup(bdrv_get_device_name(bs));
426 427 428
        bmds->bulk_completed = 0;
        bmds->total_sectors = sectors;
        bmds->completed_sectors = 0;
429
        bmds->shared_base = migrate_use_block_incremental();
430 431 432 433

        assert(i < num_bs);
        bmds_bs[i].bmds = bmds;
        bmds_bs[i].bs = bs;
434 435 436 437

        block_mig_state.total_sector_sum += sectors;

        if (bmds->shared_base) {
438
            DPRINTF("Start migration for %s with shared base image\n",
439
                    bdrv_get_device_name(bs));
440
        } else {
441
            DPRINTF("Start full migration for %s\n", bdrv_get_device_name(bs));
442 443 444 445
        }

        QSIMPLEQ_INSERT_TAIL(&block_mig_state.bmds_list, bmds, entry);
    }
446 447 448 449 450 451 452 453

    /* Can only insert new BDSes now because doing so while iterating block
     * devices may end up in a deadlock (iterating the new BDSes, too). */
    for (i = 0; i < num_bs; i++) {
        BlkMigDevState *bmds = bmds_bs[i].bmds;
        BlockDriverState *bs = bmds_bs[i].bs;

        if (bmds) {
454 455 456 457 458
            ret = blk_insert_bs(bmds->blk, bs, &local_err);
            if (ret < 0) {
                error_report_err(local_err);
                goto out;
            }
459 460 461 462 463 464 465

            alloc_aio_bitmap(bmds);
            error_setg(&bmds->blocker, "block device is in use by migration");
            bdrv_op_block_all(bs, bmds->blocker);
        }
    }

466
    ret = 0;
467 468
out:
    g_free(bmds_bs);
469
    return ret;
470 471
}

472 473
/* Called with no lock taken.  */

474
static int blk_mig_save_bulked_block(QEMUFile *f)
L
lirans@il.ibm.com 已提交
475
{
476
    int64_t completed_sector_sum = 0;
L
lirans@il.ibm.com 已提交
477
    BlkMigDevState *bmds;
478
    int progress;
479
    int ret = 0;
L
lirans@il.ibm.com 已提交
480

481
    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
482
        if (bmds->bulk_completed == 0) {
483
            if (mig_save_device_bulk(f, bmds) == 1) {
484 485
                /* completed bulk section for this device */
                bmds->bulk_completed = 1;
L
lirans@il.ibm.com 已提交
486
            }
487 488 489 490 491
            completed_sector_sum += bmds->completed_sectors;
            ret = 1;
            break;
        } else {
            completed_sector_sum += bmds->completed_sectors;
L
lirans@il.ibm.com 已提交
492 493
        }
    }
494

495 496 497 498 499 500
    if (block_mig_state.total_sector_sum != 0) {
        progress = completed_sector_sum * 100 /
                   block_mig_state.total_sector_sum;
    } else {
        progress = 100;
    }
501 502 503 504
    if (progress != block_mig_state.prev_progress) {
        block_mig_state.prev_progress = progress;
        qemu_put_be64(f, (progress << BDRV_SECTOR_BITS)
                         | BLK_MIG_FLAG_PROGRESS);
505
        DPRINTF("Completed %d %%\r", progress);
506 507 508
    }

    return ret;
L
lirans@il.ibm.com 已提交
509 510
}

511
static void blk_mig_reset_dirty_cursor(void)
L
lirans@il.ibm.com 已提交
512 513
{
    BlkMigDevState *bmds;
514 515 516 517 518 519

    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
        bmds->cur_dirty = 0;
    }
}

520
/* Called with iothread lock and AioContext taken.  */
521

522 523
static int mig_save_device_dirty(QEMUFile *f, BlkMigDevState *bmds,
                                 int is_async)
524 525
{
    BlkMigBlock *blk;
526
    BlockDriverState *bs = blk_bs(bmds->blk);
527
    int64_t total_sectors = bmds->total_sectors;
L
lirans@il.ibm.com 已提交
528
    int64_t sector;
529
    int nr_sectors;
530
    int ret = -EIO;
531

532
    for (sector = bmds->cur_dirty; sector < bmds->total_sectors;) {
P
Paolo Bonzini 已提交
533
        blk_mig_lock();
534
        if (bmds_aio_inflight(bmds, sector)) {
P
Paolo Bonzini 已提交
535
            blk_mig_unlock();
536
            blk_drain(bmds->blk);
P
Paolo Bonzini 已提交
537 538
        } else {
            blk_mig_unlock();
539
        }
540
        if (bdrv_get_dirty(bs, bmds->dirty_bitmap, sector)) {
541

542 543 544 545 546
            if (total_sectors - sector < BDRV_SECTORS_PER_DIRTY_CHUNK) {
                nr_sectors = total_sectors - sector;
            } else {
                nr_sectors = BDRV_SECTORS_PER_DIRTY_CHUNK;
            }
547
            blk = g_new(BlkMigBlock, 1);
548
            blk->buf = g_malloc(BLOCK_SIZE);
549 550
            blk->bmds = bmds;
            blk->sector = sector;
551
            blk->nr_sectors = nr_sectors;
552

553
            if (is_async) {
554 555 556 557
                blk->iov.iov_base = blk->buf;
                blk->iov.iov_len = nr_sectors * BDRV_SECTOR_SIZE;
                qemu_iovec_init_external(&blk->qiov, &blk->iov, 1);

558 559 560 561
                blk->aiocb = blk_aio_preadv(bmds->blk,
                                            sector * BDRV_SECTOR_SIZE,
                                            &blk->qiov, 0, blk_mig_read_cb,
                                            blk);
P
Paolo Bonzini 已提交
562 563

                blk_mig_lock();
564
                block_mig_state.submitted++;
565
                bmds_set_aio_inflight(bmds, sector, nr_sectors, 1);
P
Paolo Bonzini 已提交
566
                blk_mig_unlock();
567
            } else {
568 569
                ret = blk_pread(bmds->blk, sector * BDRV_SECTOR_SIZE, blk->buf,
                                nr_sectors * BDRV_SECTOR_SIZE);
570
                if (ret < 0) {
571
                    goto error;
L
lirans@il.ibm.com 已提交
572
                }
573
                blk_send(f, blk);
574

575 576
                g_free(blk->buf);
                g_free(blk);
577
            }
578

579
            bdrv_reset_dirty_bitmap(bmds->dirty_bitmap, sector, nr_sectors);
580 581 582
            sector += nr_sectors;
            bmds->cur_dirty = sector;

583
            break;
L
lirans@il.ibm.com 已提交
584
        }
585 586
        sector += BDRV_SECTORS_PER_DIRTY_CHUNK;
        bmds->cur_dirty = sector;
L
lirans@il.ibm.com 已提交
587
    }
588

589 590
    return (bmds->cur_dirty >= bmds->total_sectors);

591
error:
592
    DPRINTF("Error reading sector %" PRId64 "\n", sector);
593 594
    g_free(blk->buf);
    g_free(blk);
595
    return ret;
596 597
}

598 599 600
/* Called with iothread lock taken.
 *
 * return value:
601 602 603
 * 0: too much data for max_downtime
 * 1: few enough data for max_downtime
*/
604
static int blk_mig_save_dirty_block(QEMUFile *f, int is_async)
605 606
{
    BlkMigDevState *bmds;
607
    int ret = 1;
608 609

    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
610
        aio_context_acquire(blk_get_aio_context(bmds->blk));
611
        ret = mig_save_device_dirty(f, bmds, is_async);
612
        aio_context_release(blk_get_aio_context(bmds->blk));
613
        if (ret <= 0) {
614 615 616 617 618
            break;
        }
    }

    return ret;
L
lirans@il.ibm.com 已提交
619 620
}

621 622
/* Called with no locks taken.  */

623
static int flush_blks(QEMUFile *f)
L
lirans@il.ibm.com 已提交
624
{
625
    BlkMigBlock *blk;
626
    int ret = 0;
627

M
malc 已提交
628
    DPRINTF("%s Enter submitted %d read_done %d transferred %d\n",
629 630
            __FUNCTION__, block_mig_state.submitted, block_mig_state.read_done,
            block_mig_state.transferred);
631

P
Paolo Bonzini 已提交
632
    blk_mig_lock();
633 634 635 636
    while ((blk = QSIMPLEQ_FIRST(&block_mig_state.blk_list)) != NULL) {
        if (qemu_file_rate_limit(f)) {
            break;
        }
637
        if (blk->ret < 0) {
638
            ret = blk->ret;
639 640
            break;
        }
641

642
        QSIMPLEQ_REMOVE_HEAD(&block_mig_state.blk_list, entry);
P
Paolo Bonzini 已提交
643
        blk_mig_unlock();
644
        blk_send(f, blk);
P
Paolo Bonzini 已提交
645
        blk_mig_lock();
646

647 648
        g_free(blk->buf);
        g_free(blk);
649

650 651 652
        block_mig_state.read_done--;
        block_mig_state.transferred++;
        assert(block_mig_state.read_done >= 0);
L
lirans@il.ibm.com 已提交
653
    }
P
Paolo Bonzini 已提交
654
    blk_mig_unlock();
L
lirans@il.ibm.com 已提交
655

M
malc 已提交
656
    DPRINTF("%s Exit submitted %d read_done %d transferred %d\n", __FUNCTION__,
657 658
            block_mig_state.submitted, block_mig_state.read_done,
            block_mig_state.transferred);
659
    return ret;
L
lirans@il.ibm.com 已提交
660 661
}

662 663
/* Called with iothread lock taken.  */

664 665 666 667 668 669
static int64_t get_remaining_dirty(void)
{
    BlkMigDevState *bmds;
    int64_t dirty = 0;

    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
670
        aio_context_acquire(blk_get_aio_context(bmds->blk));
671
        dirty += bdrv_get_dirty_count(bmds->dirty_bitmap);
672
        aio_context_release(blk_get_aio_context(bmds->blk));
673 674
    }

675
    return dirty << BDRV_SECTOR_BITS;
676 677
}

678

679 680 681

/* Called with iothread lock taken.  */
static void block_migration_cleanup_bmds(void)
682
{
683
    BlkMigDevState *bmds;
684
    AioContext *ctx;
685

F
Fam Zheng 已提交
686
    unset_dirty_tracking();
687

688 689
    while ((bmds = QSIMPLEQ_FIRST(&block_mig_state.bmds_list)) != NULL) {
        QSIMPLEQ_REMOVE_HEAD(&block_mig_state.bmds_list, entry);
690
        bdrv_op_unblock_all(blk_bs(bmds->blk), bmds->blocker);
691
        error_free(bmds->blocker);
692

693 694
        /* Save ctx, because bmds->blk can disappear during blk_unref.  */
        ctx = blk_get_aio_context(bmds->blk);
695
        aio_context_acquire(ctx);
696
        blk_unref(bmds->blk);
697 698
        aio_context_release(ctx);

699
        g_free(bmds->blk_name);
700 701
        g_free(bmds->aio_bitmap);
        g_free(bmds);
702
    }
703 704 705 706 707 708 709 710 711 712
}

/* Called with iothread lock taken.  */
static void block_migration_cleanup(void *opaque)
{
    BlkMigBlock *blk;

    bdrv_drain_all();

    block_migration_cleanup_bmds();
713

714
    blk_mig_lock();
715 716
    while ((blk = QSIMPLEQ_FIRST(&block_mig_state.blk_list)) != NULL) {
        QSIMPLEQ_REMOVE_HEAD(&block_mig_state.blk_list, entry);
717 718
        g_free(blk->buf);
        g_free(blk);
719
    }
P
Paolo Bonzini 已提交
720
    blk_mig_unlock();
721 722
}

723
static int block_save_setup(QEMUFile *f, void *opaque)
L
lirans@il.ibm.com 已提交
724
{
725 726
    int ret;

727 728
    DPRINTF("Enter save live setup submitted %d transferred %d\n",
            block_mig_state.submitted, block_mig_state.transferred);
729

730
    qemu_mutex_lock_iothread();
731 732 733 734 735
    ret = init_blk_migration(f);
    if (ret < 0) {
        qemu_mutex_unlock_iothread();
        return ret;
    }
736 737

    /* start track dirty blocks */
738 739
    ret = set_dirty_tracking();

740 741
    qemu_mutex_unlock_iothread();

742 743 744 745
    if (ret) {
        return ret;
    }

746
    ret = flush_blks(f);
747 748 749
    blk_mig_reset_dirty_cursor();
    qemu_put_be64(f, BLK_MIG_FLAG_EOS);

750
    return ret;
751 752
}

753
static int block_save_iterate(QEMUFile *f, void *opaque)
754 755
{
    int ret;
756
    int64_t last_ftell = qemu_ftell(f);
G
Gary R Hook 已提交
757
    int64_t delta_ftell;
758

759 760
    DPRINTF("Enter save live iterate submitted %d transferred %d\n",
            block_mig_state.submitted, block_mig_state.transferred);
761

762
    ret = flush_blks(f);
763 764
    if (ret) {
        return ret;
765 766
    }

767 768
    blk_mig_reset_dirty_cursor();

769
    /* control the rate of transfer */
P
Paolo Bonzini 已提交
770
    blk_mig_lock();
771 772
    while ((block_mig_state.submitted +
            block_mig_state.read_done) * BLOCK_SIZE <
773 774 775 776
           qemu_file_get_rate_limit(f) &&
           (block_mig_state.submitted +
            block_mig_state.read_done) <
           MAX_INFLIGHT_IO) {
P
Paolo Bonzini 已提交
777
        blk_mig_unlock();
778 779 780 781 782 783
        if (block_mig_state.bulk_completed == 0) {
            /* first finish the bulk phase */
            if (blk_mig_save_bulked_block(f) == 0) {
                /* finished saving bulk on all devices */
                block_mig_state.bulk_completed = 1;
            }
784
            ret = 0;
785
        } else {
786 787 788 789
            /* Always called with iothread lock taken for
             * simplicity, block_save_complete also calls it.
             */
            qemu_mutex_lock_iothread();
790
            ret = blk_mig_save_dirty_block(f, 1);
791
            qemu_mutex_unlock_iothread();
792 793 794 795
        }
        if (ret < 0) {
            return ret;
        }
P
Paolo Bonzini 已提交
796
        blk_mig_lock();
797 798 799
        if (ret != 0) {
            /* no more dirty blocks */
            break;
800
        }
801
    }
P
Paolo Bonzini 已提交
802
    blk_mig_unlock();
803

804
    ret = flush_blks(f);
805 806
    if (ret) {
        return ret;
807 808
    }

809
    qemu_put_be64(f, BLK_MIG_FLAG_EOS);
G
Gary R Hook 已提交
810 811 812 813 814 815 816 817
    delta_ftell = qemu_ftell(f) - last_ftell;
    if (delta_ftell > 0) {
        return 1;
    } else if (delta_ftell < 0) {
        return -1;
    } else {
        return 0;
    }
818 819
}

820 821
/* Called with iothread lock taken.  */

822 823 824 825 826 827 828
static int block_save_complete(QEMUFile *f, void *opaque)
{
    int ret;

    DPRINTF("Enter save live complete submitted %d transferred %d\n",
            block_mig_state.submitted, block_mig_state.transferred);

829
    ret = flush_blks(f);
830 831 832
    if (ret) {
        return ret;
    }
833

834
    blk_mig_reset_dirty_cursor();
835

836 837
    /* we know for sure that save bulk is completed and
       all async read completed */
P
Paolo Bonzini 已提交
838
    blk_mig_lock();
839
    assert(block_mig_state.submitted == 0);
P
Paolo Bonzini 已提交
840
    blk_mig_unlock();
841

842 843
    do {
        ret = blk_mig_save_dirty_block(f, 0);
844 845 846
        if (ret < 0) {
            return ret;
        }
847
    } while (ret == 0);
848

849 850
    /* report completion */
    qemu_put_be64(f, (100 << BDRV_SECTOR_BITS) | BLK_MIG_FLAG_PROGRESS);
851

852 853
    DPRINTF("Block migration completed\n");

854 855
    qemu_put_be64(f, BLK_MIG_FLAG_EOS);

856 857 858 859
    /* Make sure that our BlockBackends are gone, so that the block driver
     * nodes can be inactivated. */
    block_migration_cleanup_bmds();

860
    return 0;
L
lirans@il.ibm.com 已提交
861 862
}

863 864 865
static void block_save_pending(QEMUFile *f, void *opaque, uint64_t max_size,
                               uint64_t *non_postcopiable_pending,
                               uint64_t *postcopiable_pending)
866
{
867
    /* Estimate pending number of bytes to send */
868 869
    uint64_t pending;

870
    qemu_mutex_lock_iothread();
871 872 873
    pending = get_remaining_dirty();
    qemu_mutex_unlock_iothread();

P
Paolo Bonzini 已提交
874
    blk_mig_lock();
875 876 877
    pending += block_mig_state.submitted * BLOCK_SIZE +
               block_mig_state.read_done * BLOCK_SIZE;
    blk_mig_unlock();
878 879

    /* Report at least one block pending during bulk phase */
880 881
    if (pending <= max_size && !block_mig_state.bulk_completed) {
        pending = max_size + BLOCK_SIZE;
882
    }
883

884
    DPRINTF("Enter save live pending  %" PRIu64 "\n", pending);
885 886
    /* We don't do postcopy */
    *non_postcopiable_pending += pending;
887 888
}

L
lirans@il.ibm.com 已提交
889 890
static int block_load(QEMUFile *f, void *opaque, int version_id)
{
891
    static int banner_printed;
L
lirans@il.ibm.com 已提交
892 893 894
    int len, flags;
    char device_name[256];
    int64_t addr;
895
    BlockBackend *blk, *blk_prev = NULL;;
896
    Error *local_err = NULL;
L
lirans@il.ibm.com 已提交
897
    uint8_t *buf;
898 899
    int64_t total_sectors = 0;
    int nr_sectors;
900
    int ret;
901 902
    BlockDriverInfo bdi;
    int cluster_size = BLOCK_SIZE;
903

L
lirans@il.ibm.com 已提交
904 905
    do {
        addr = qemu_get_be64(f);
906

J
Jan Kiszka 已提交
907 908
        flags = addr & ~BDRV_SECTOR_MASK;
        addr >>= BDRV_SECTOR_BITS;
909 910

        if (flags & BLK_MIG_FLAG_DEVICE_BLOCK) {
L
lirans@il.ibm.com 已提交
911 912 913 914
            /* get device name */
            len = qemu_get_byte(f);
            qemu_get_buffer(f, (uint8_t *)device_name, len);
            device_name[len] = '\0';
915

916 917
            blk = blk_by_name(device_name);
            if (!blk) {
918 919 920 921
                fprintf(stderr, "Error unknown block device %s\n",
                        device_name);
                return -EINVAL;
            }
922

923 924 925
            if (blk != blk_prev) {
                blk_prev = blk;
                total_sectors = blk_nb_sectors(blk);
926
                if (total_sectors <= 0) {
927
                    error_report("Error getting length of block device %s",
928 929 930
                                 device_name);
                    return -EINVAL;
                }
931

932
                blk_invalidate_cache(blk, &local_err);
933 934 935 936
                if (local_err) {
                    error_report_err(local_err);
                    return -EINVAL;
                }
937 938 939 940 941 942 943 944 945

                ret = bdrv_get_info(blk_bs(blk), &bdi);
                if (ret == 0 && bdi.cluster_size > 0 &&
                    bdi.cluster_size <= BLOCK_SIZE &&
                    BLOCK_SIZE % bdi.cluster_size == 0) {
                    cluster_size = bdi.cluster_size;
                } else {
                    cluster_size = BLOCK_SIZE;
                }
946 947 948 949 950 951 952 953
            }

            if (total_sectors - addr < BDRV_SECTORS_PER_DIRTY_CHUNK) {
                nr_sectors = total_sectors - addr;
            } else {
                nr_sectors = BDRV_SECTORS_PER_DIRTY_CHUNK;
            }

954
            if (flags & BLK_MIG_FLAG_ZERO_BLOCK) {
955 956 957
                ret = blk_pwrite_zeroes(blk, addr * BDRV_SECTOR_SIZE,
                                        nr_sectors * BDRV_SECTOR_SIZE,
                                        BDRV_REQ_MAY_UNMAP);
958
            } else {
959 960 961 962
                int i;
                int64_t cur_addr;
                uint8_t *cur_buf;

963 964
                buf = g_malloc(BLOCK_SIZE);
                qemu_get_buffer(f, buf, BLOCK_SIZE);
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
                for (i = 0; i < BLOCK_SIZE / cluster_size; i++) {
                    cur_addr = addr * BDRV_SECTOR_SIZE + i * cluster_size;
                    cur_buf = buf + i * cluster_size;

                    if ((!block_mig_state.zero_blocks ||
                        cluster_size < BLOCK_SIZE) &&
                        buffer_is_zero(cur_buf, cluster_size)) {
                        ret = blk_pwrite_zeroes(blk, cur_addr,
                                                cluster_size,
                                                BDRV_REQ_MAY_UNMAP);
                    } else {
                        ret = blk_pwrite(blk, cur_addr, cur_buf,
                                         cluster_size, 0);
                    }
                    if (ret < 0) {
                        break;
                    }
                }
983 984
                g_free(buf);
            }
985

986 987 988
            if (ret < 0) {
                return ret;
            }
989 990 991 992 993 994 995 996
        } else if (flags & BLK_MIG_FLAG_PROGRESS) {
            if (!banner_printed) {
                printf("Receiving block device images\n");
                banner_printed = 1;
            }
            printf("Completed %d %%%c", (int)addr,
                   (addr == 100) ? '\n' : '\r');
            fflush(stdout);
997
        } else if (!(flags & BLK_MIG_FLAG_EOS)) {
998
            fprintf(stderr, "Unknown block migration flags: %#x\n", flags);
999 1000
            return -EINVAL;
        }
1001 1002 1003
        ret = qemu_file_get_error(f);
        if (ret != 0) {
            return ret;
L
lirans@il.ibm.com 已提交
1004
        }
1005 1006
    } while (!(flags & BLK_MIG_FLAG_EOS));

L
lirans@il.ibm.com 已提交
1007 1008 1009
    return 0;
}

1010 1011
static bool block_is_active(void *opaque)
{
1012
    return migrate_use_block();
1013 1014
}

1015
static SaveVMHandlers savevm_block_handlers = {
1016
    .save_live_setup = block_save_setup,
1017
    .save_live_iterate = block_save_iterate,
1018
    .save_live_complete_precopy = block_save_complete,
1019
    .save_live_pending = block_save_pending,
1020
    .load_state = block_load,
L
Liang Li 已提交
1021
    .cleanup = block_migration_cleanup,
1022
    .is_active = block_is_active,
1023 1024
};

L
lirans@il.ibm.com 已提交
1025
void blk_mig_init(void)
1026
{
1027 1028
    QSIMPLEQ_INIT(&block_mig_state.bmds_list);
    QSIMPLEQ_INIT(&block_mig_state.blk_list);
P
Paolo Bonzini 已提交
1029
    qemu_mutex_init(&block_mig_state.lock);
1030

1031 1032
    register_savevm_live(NULL, "block", 0, 1, &savevm_block_handlers,
                         &block_mig_state);
L
lirans@il.ibm.com 已提交
1033
}