block.c 26.2 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 "migration/block.h"
#include "migration/migration.h"
28
#include "sysemu/blockdev.h"
29
#include "sysemu/block-backend.h"
L
lirans@il.ibm.com 已提交
30

31 32
#define BLOCK_SIZE                       (1 << 20)
#define BDRV_SECTORS_PER_DIRTY_CHUNK     (BLOCK_SIZE >> BDRV_SECTOR_BITS)
L
lirans@il.ibm.com 已提交
33 34 35

#define BLK_MIG_FLAG_DEVICE_BLOCK       0x01
#define BLK_MIG_FLAG_EOS                0x02
36
#define BLK_MIG_FLAG_PROGRESS           0x04
37
#define BLK_MIG_FLAG_ZERO_BLOCK         0x08
L
lirans@il.ibm.com 已提交
38 39 40

#define MAX_IS_ALLOCATED_SEARCH 65536

41 42
#define MAX_INFLIGHT_IO 512

L
lirans@il.ibm.com 已提交
43 44 45
//#define DEBUG_BLK_MIGRATION

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

53
typedef struct BlkMigDevState {
54
    /* Written during setup phase.  Can be read without a lock.  */
55 56 57
    BlockDriverState *bs;
    int shared_base;
    int64_t total_sectors;
58
    QSIMPLEQ_ENTRY(BlkMigDevState) entry;
59
    Error *blocker;
60 61 62 63 64 65

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

66 67 68
    /* Data in the aio_bitmap is protected by block migration lock.
     * Allocation and free happen during setup and cleanup respectively.
     */
69
    unsigned long *aio_bitmap;
70 71

    /* Protected by block migration lock.  */
72
    int64_t completed_sectors;
73 74 75 76

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

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

P
Paolo Bonzini 已提交
90
    /* Protected by block migration lock.  */
L
lirans@il.ibm.com 已提交
91
    int ret;
92
    QSIMPLEQ_ENTRY(BlkMigBlock) entry;
L
lirans@il.ibm.com 已提交
93 94 95
} BlkMigBlock;

typedef struct BlkMigState {
96
    /* Written during setup phase.  Can be read without a lock.  */
L
lirans@il.ibm.com 已提交
97 98
    int blk_enable;
    int shared_base;
99
    QSIMPLEQ_HEAD(bmds_list, BlkMigDevState) bmds_list;
100
    int64_t total_sector_sum;
101
    bool zero_blocks;
102

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

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

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

117
static BlkMigState block_mig_state;
L
lirans@il.ibm.com 已提交
118

P
Paolo Bonzini 已提交
119 120 121 122 123 124 125 126 127 128
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);
}

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

133 134 135
static void blk_send(QEMUFile *f, BlkMigBlock * blk)
{
    int len;
136 137 138 139 140 141
    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;
    }
142 143 144

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

    /* device name */
148
    len = strlen(bdrv_get_device_name(blk->bmds->bs));
149
    qemu_put_byte(f, len);
150
    qemu_put_buffer(f, (uint8_t *)bdrv_get_device_name(blk->bmds->bs), len);
151

152 153 154 155 156 157 158 159
    /* 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;
    }

160 161 162
    qemu_put_buffer(f, blk->buf, BLOCK_SIZE);
}

163 164 165 166 167 168 169 170 171 172
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 已提交
173
    blk_mig_lock();
174 175 176
    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
        sum += bmds->completed_sectors;
    }
P
Paolo Bonzini 已提交
177
    blk_mig_unlock();
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
    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 已提交
197 198 199

/* Called with migration lock held.  */

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

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

P
Paolo Bonzini 已提交
212 213
/* Called with migration lock held.  */

214 215 216 217 218 219 220 221 222 223 224 225 226 227
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) {
228
            val |= 1UL << bit;
229
        } else {
230
            val &= ~(1UL << bit);
231 232 233 234 235 236 237 238 239 240
        }
        bmds->aio_bitmap[idx] = val;
    }
}

static void alloc_aio_bitmap(BlkMigDevState *bmds)
{
    BlockDriverState *bs = bmds->bs;
    int64_t bitmap_size;

241
    bitmap_size = bdrv_nb_sectors(bs) + BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
242 243
    bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;

244
    bmds->aio_bitmap = g_malloc0(bitmap_size);
245 246
}

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

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

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

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

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

265 266
/* Called with no lock taken.  */

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

275
    if (bmds->shared_base) {
276
        qemu_mutex_lock_iothread();
277
        aio_context_acquire(bdrv_get_aio_context(bs));
278
        while (cur_sector < total_sectors &&
279 280
               !bdrv_is_allocated(bs, cur_sector, MAX_IS_ALLOCATED_SEARCH,
                                  &nr_sectors)) {
L
lirans@il.ibm.com 已提交
281 282
            cur_sector += nr_sectors;
        }
283
        aio_context_release(bdrv_get_aio_context(bs));
284
        qemu_mutex_unlock_iothread();
L
lirans@il.ibm.com 已提交
285
    }
286 287

    if (cur_sector >= total_sectors) {
288
        bmds->cur_sector = bmds->completed_sectors = total_sectors;
L
lirans@il.ibm.com 已提交
289 290
        return 1;
    }
291

292
    bmds->completed_sectors = cur_sector;
293

294 295
    cur_sector &= ~((int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK - 1);

J
Jan Kiszka 已提交
296 297
    /* 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 已提交
298

J
Jan Kiszka 已提交
299
    if (total_sectors - cur_sector < BDRV_SECTORS_PER_DIRTY_CHUNK) {
300
        nr_sectors = total_sectors - cur_sector;
L
lirans@il.ibm.com 已提交
301
    }
302

303
    blk = g_new(BlkMigBlock, 1);
304
    blk->buf = g_malloc(BLOCK_SIZE);
305 306
    blk->bmds = bmds;
    blk->sector = cur_sector;
307
    blk->nr_sectors = nr_sectors;
308

L
Liran Schour 已提交
309 310 311
    blk->iov.iov_base = blk->buf;
    blk->iov.iov_len = nr_sectors * BDRV_SECTOR_SIZE;
    qemu_iovec_init_external(&blk->qiov, &blk->iov, 1);
312

P
Paolo Bonzini 已提交
313
    blk_mig_lock();
314
    block_mig_state.submitted++;
P
Paolo Bonzini 已提交
315
    blk_mig_unlock();
316

317 318 319 320 321 322 323 324
    /* 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.
     */
325
    qemu_mutex_lock_iothread();
326
    aio_context_acquire(bdrv_get_aio_context(bmds->bs));
L
Liran Schour 已提交
327 328
    blk->aiocb = bdrv_aio_readv(bs, cur_sector, &blk->qiov,
                                nr_sectors, blk_mig_read_cb, blk);
329

330
    bdrv_reset_dirty_bitmap(bmds->dirty_bitmap, cur_sector, nr_sectors);
331
    aio_context_release(bdrv_get_aio_context(bmds->bs));
332
    qemu_mutex_unlock_iothread();
333

334
    bmds->cur_sector = cur_sector + nr_sectors;
335
    return (bmds->cur_sector >= total_sectors);
L
lirans@il.ibm.com 已提交
336 337
}

338 339
/* Called with iothread lock taken.  */

340
static int set_dirty_tracking(void)
L
lirans@il.ibm.com 已提交
341 342
{
    BlkMigDevState *bmds;
343 344 345
    int ret;

    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
346
        aio_context_acquire(bdrv_get_aio_context(bmds->bs));
347
        bmds->dirty_bitmap = bdrv_create_dirty_bitmap(bmds->bs, BLOCK_SIZE,
348
                                                      NULL, NULL);
349
        aio_context_release(bdrv_get_aio_context(bmds->bs));
350 351 352 353 354 355
        if (!bmds->dirty_bitmap) {
            ret = -errno;
            goto fail;
        }
    }
    return 0;
356

357
fail:
358
    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
359
        if (bmds->dirty_bitmap) {
360
            aio_context_acquire(bdrv_get_aio_context(bmds->bs));
361
            bdrv_release_dirty_bitmap(bmds->bs, bmds->dirty_bitmap);
362
            aio_context_release(bdrv_get_aio_context(bmds->bs));
363
        }
F
Fam Zheng 已提交
364
    }
365
    return ret;
F
Fam Zheng 已提交
366 367
}

368 369
/* Called with iothread lock taken.  */

F
Fam Zheng 已提交
370 371 372 373 374
static void unset_dirty_tracking(void)
{
    BlkMigDevState *bmds;

    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
375
        aio_context_acquire(bdrv_get_aio_context(bmds->bs));
F
Fam Zheng 已提交
376
        bdrv_release_dirty_bitmap(bmds->bs, bmds->dirty_bitmap);
377
        aio_context_release(bdrv_get_aio_context(bmds->bs));
L
lirans@il.ibm.com 已提交
378 379 380
    }
}

381
static void init_blk_migration(QEMUFile *f)
L
lirans@il.ibm.com 已提交
382
{
383
    BlockDriverState *bs;
384
    BlkMigDevState *bmds;
385
    int64_t sectors;
K
Kevin Wolf 已提交
386
    BdrvNextIterator it;
387

388 389 390 391 392 393 394 395
    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 已提交
396

K
Kevin Wolf 已提交
397
    for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
398 399 400 401
        if (bdrv_is_read_only(bs)) {
            continue;
        }

402
        sectors = bdrv_nb_sectors(bs);
403
        if (sectors <= 0) {
404 405 406
            return;
        }

407
        bmds = g_new0(BlkMigDevState, 1);
408 409 410 411 412
        bmds->bs = bs;
        bmds->bulk_completed = 0;
        bmds->total_sectors = sectors;
        bmds->completed_sectors = 0;
        bmds->shared_base = block_mig_state.shared_base;
413
        alloc_aio_bitmap(bmds);
414 415
        error_setg(&bmds->blocker, "block device is in use by migration");
        bdrv_op_block_all(bs, bmds->blocker);
416
        bdrv_ref(bs);
417 418 419 420

        block_mig_state.total_sector_sum += sectors;

        if (bmds->shared_base) {
421
            DPRINTF("Start migration for %s with shared base image\n",
422
                    bdrv_get_device_name(bs));
423
        } else {
424
            DPRINTF("Start full migration for %s\n", bdrv_get_device_name(bs));
425 426 427 428 429 430
        }

        QSIMPLEQ_INSERT_TAIL(&block_mig_state.bmds_list, bmds, entry);
    }
}

431 432
/* Called with no lock taken.  */

433
static int blk_mig_save_bulked_block(QEMUFile *f)
L
lirans@il.ibm.com 已提交
434
{
435
    int64_t completed_sector_sum = 0;
L
lirans@il.ibm.com 已提交
436
    BlkMigDevState *bmds;
437
    int progress;
438
    int ret = 0;
L
lirans@il.ibm.com 已提交
439

440
    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
441
        if (bmds->bulk_completed == 0) {
442
            if (mig_save_device_bulk(f, bmds) == 1) {
443 444
                /* completed bulk section for this device */
                bmds->bulk_completed = 1;
L
lirans@il.ibm.com 已提交
445
            }
446 447 448 449 450
            completed_sector_sum += bmds->completed_sectors;
            ret = 1;
            break;
        } else {
            completed_sector_sum += bmds->completed_sectors;
L
lirans@il.ibm.com 已提交
451 452
        }
    }
453

454 455 456 457 458 459
    if (block_mig_state.total_sector_sum != 0) {
        progress = completed_sector_sum * 100 /
                   block_mig_state.total_sector_sum;
    } else {
        progress = 100;
    }
460 461 462 463
    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);
464
        DPRINTF("Completed %d %%\r", progress);
465 466 467
    }

    return ret;
L
lirans@il.ibm.com 已提交
468 469
}

470
static void blk_mig_reset_dirty_cursor(void)
L
lirans@il.ibm.com 已提交
471 472
{
    BlkMigDevState *bmds;
473 474 475 476 477 478

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

479
/* Called with iothread lock and AioContext taken.  */
480

481 482
static int mig_save_device_dirty(QEMUFile *f, BlkMigDevState *bmds,
                                 int is_async)
483 484 485
{
    BlkMigBlock *blk;
    int64_t total_sectors = bmds->total_sectors;
L
lirans@il.ibm.com 已提交
486
    int64_t sector;
487
    int nr_sectors;
488
    int ret = -EIO;
489

490
    for (sector = bmds->cur_dirty; sector < bmds->total_sectors;) {
P
Paolo Bonzini 已提交
491
        blk_mig_lock();
492
        if (bmds_aio_inflight(bmds, sector)) {
P
Paolo Bonzini 已提交
493
            blk_mig_unlock();
494
            bdrv_drain(bmds->bs);
P
Paolo Bonzini 已提交
495 496
        } else {
            blk_mig_unlock();
497
        }
F
Fam Zheng 已提交
498
        if (bdrv_get_dirty(bmds->bs, bmds->dirty_bitmap, sector)) {
499

500 501 502 503 504
            if (total_sectors - sector < BDRV_SECTORS_PER_DIRTY_CHUNK) {
                nr_sectors = total_sectors - sector;
            } else {
                nr_sectors = BDRV_SECTORS_PER_DIRTY_CHUNK;
            }
505
            blk = g_new(BlkMigBlock, 1);
506
            blk->buf = g_malloc(BLOCK_SIZE);
507 508
            blk->bmds = bmds;
            blk->sector = sector;
509
            blk->nr_sectors = nr_sectors;
510

511
            if (is_async) {
512 513 514 515 516 517
                blk->iov.iov_base = blk->buf;
                blk->iov.iov_len = nr_sectors * BDRV_SECTOR_SIZE;
                qemu_iovec_init_external(&blk->qiov, &blk->iov, 1);

                blk->aiocb = bdrv_aio_readv(bmds->bs, sector, &blk->qiov,
                                            nr_sectors, blk_mig_read_cb, blk);
P
Paolo Bonzini 已提交
518 519

                blk_mig_lock();
520
                block_mig_state.submitted++;
521
                bmds_set_aio_inflight(bmds, sector, nr_sectors, 1);
P
Paolo Bonzini 已提交
522
                blk_mig_unlock();
523
            } else {
524 525
                ret = bdrv_read(bmds->bs, sector, blk->buf, nr_sectors);
                if (ret < 0) {
526
                    goto error;
L
lirans@il.ibm.com 已提交
527
                }
528
                blk_send(f, blk);
529

530 531
                g_free(blk->buf);
                g_free(blk);
532
            }
533

534
            bdrv_reset_dirty_bitmap(bmds->dirty_bitmap, sector, nr_sectors);
535
            break;
L
lirans@il.ibm.com 已提交
536
        }
537 538
        sector += BDRV_SECTORS_PER_DIRTY_CHUNK;
        bmds->cur_dirty = sector;
L
lirans@il.ibm.com 已提交
539
    }
540

541 542
    return (bmds->cur_dirty >= bmds->total_sectors);

543
error:
544
    DPRINTF("Error reading sector %" PRId64 "\n", sector);
545 546
    g_free(blk->buf);
    g_free(blk);
547
    return ret;
548 549
}

550 551 552
/* Called with iothread lock taken.
 *
 * return value:
553 554 555
 * 0: too much data for max_downtime
 * 1: few enough data for max_downtime
*/
556
static int blk_mig_save_dirty_block(QEMUFile *f, int is_async)
557 558
{
    BlkMigDevState *bmds;
559
    int ret = 1;
560 561

    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
562
        aio_context_acquire(bdrv_get_aio_context(bmds->bs));
563
        ret = mig_save_device_dirty(f, bmds, is_async);
564
        aio_context_release(bdrv_get_aio_context(bmds->bs));
565
        if (ret <= 0) {
566 567 568 569 570
            break;
        }
    }

    return ret;
L
lirans@il.ibm.com 已提交
571 572
}

573 574
/* Called with no locks taken.  */

575
static int flush_blks(QEMUFile *f)
L
lirans@il.ibm.com 已提交
576
{
577
    BlkMigBlock *blk;
578
    int ret = 0;
579

M
malc 已提交
580
    DPRINTF("%s Enter submitted %d read_done %d transferred %d\n",
581 582
            __FUNCTION__, block_mig_state.submitted, block_mig_state.read_done,
            block_mig_state.transferred);
583

P
Paolo Bonzini 已提交
584
    blk_mig_lock();
585 586 587 588
    while ((blk = QSIMPLEQ_FIRST(&block_mig_state.blk_list)) != NULL) {
        if (qemu_file_rate_limit(f)) {
            break;
        }
589
        if (blk->ret < 0) {
590
            ret = blk->ret;
591 592
            break;
        }
593

594
        QSIMPLEQ_REMOVE_HEAD(&block_mig_state.blk_list, entry);
P
Paolo Bonzini 已提交
595
        blk_mig_unlock();
596
        blk_send(f, blk);
P
Paolo Bonzini 已提交
597
        blk_mig_lock();
598

599 600
        g_free(blk->buf);
        g_free(blk);
601

602 603 604
        block_mig_state.read_done--;
        block_mig_state.transferred++;
        assert(block_mig_state.read_done >= 0);
L
lirans@il.ibm.com 已提交
605
    }
P
Paolo Bonzini 已提交
606
    blk_mig_unlock();
L
lirans@il.ibm.com 已提交
607

M
malc 已提交
608
    DPRINTF("%s Exit submitted %d read_done %d transferred %d\n", __FUNCTION__,
609 610
            block_mig_state.submitted, block_mig_state.read_done,
            block_mig_state.transferred);
611
    return ret;
L
lirans@il.ibm.com 已提交
612 613
}

614 615
/* Called with iothread lock taken.  */

616 617 618 619 620 621
static int64_t get_remaining_dirty(void)
{
    BlkMigDevState *bmds;
    int64_t dirty = 0;

    QSIMPLEQ_FOREACH(bmds, &block_mig_state.bmds_list, entry) {
622
        aio_context_acquire(bdrv_get_aio_context(bmds->bs));
623
        dirty += bdrv_get_dirty_count(bmds->dirty_bitmap);
624
        aio_context_release(bdrv_get_aio_context(bmds->bs));
625 626
    }

627
    return dirty << BDRV_SECTOR_BITS;
628 629
}

630 631
/* Called with iothread lock taken.  */

L
Liang Li 已提交
632
static void block_migration_cleanup(void *opaque)
633
{
634 635
    BlkMigDevState *bmds;
    BlkMigBlock *blk;
636
    AioContext *ctx;
637

638 639
    bdrv_drain_all();

F
Fam Zheng 已提交
640
    unset_dirty_tracking();
641

642 643
    while ((bmds = QSIMPLEQ_FIRST(&block_mig_state.bmds_list)) != NULL) {
        QSIMPLEQ_REMOVE_HEAD(&block_mig_state.bmds_list, entry);
644 645
        bdrv_op_unblock_all(bmds->bs, bmds->blocker);
        error_free(bmds->blocker);
646 647 648 649

        /* Save ctx, because bmds->bs can disappear during bdrv_unref.  */
        ctx = bdrv_get_aio_context(bmds->bs);
        aio_context_acquire(ctx);
650
        bdrv_unref(bmds->bs);
651 652
        aio_context_release(ctx);

653 654
        g_free(bmds->aio_bitmap);
        g_free(bmds);
655 656
    }

657
    blk_mig_lock();
658 659
    while ((blk = QSIMPLEQ_FIRST(&block_mig_state.blk_list)) != NULL) {
        QSIMPLEQ_REMOVE_HEAD(&block_mig_state.blk_list, entry);
660 661
        g_free(blk->buf);
        g_free(blk);
662
    }
P
Paolo Bonzini 已提交
663
    blk_mig_unlock();
664 665
}

666
static int block_save_setup(QEMUFile *f, void *opaque)
L
lirans@il.ibm.com 已提交
667
{
668 669
    int ret;

670 671
    DPRINTF("Enter save live setup submitted %d transferred %d\n",
            block_mig_state.submitted, block_mig_state.transferred);
672

673
    qemu_mutex_lock_iothread();
674
    init_blk_migration(f);
675 676

    /* start track dirty blocks */
677 678
    ret = set_dirty_tracking();

679 680
    qemu_mutex_unlock_iothread();

681 682 683 684
    if (ret) {
        return ret;
    }

685
    ret = flush_blks(f);
686 687 688
    blk_mig_reset_dirty_cursor();
    qemu_put_be64(f, BLK_MIG_FLAG_EOS);

689
    return ret;
690 691
}

692
static int block_save_iterate(QEMUFile *f, void *opaque)
693 694
{
    int ret;
695
    int64_t last_ftell = qemu_ftell(f);
G
Gary R Hook 已提交
696
    int64_t delta_ftell;
697

698 699
    DPRINTF("Enter save live iterate submitted %d transferred %d\n",
            block_mig_state.submitted, block_mig_state.transferred);
700

701
    ret = flush_blks(f);
702 703
    if (ret) {
        return ret;
704 705
    }

706 707
    blk_mig_reset_dirty_cursor();

708
    /* control the rate of transfer */
P
Paolo Bonzini 已提交
709
    blk_mig_lock();
710 711
    while ((block_mig_state.submitted +
            block_mig_state.read_done) * BLOCK_SIZE <
712 713 714 715
           qemu_file_get_rate_limit(f) &&
           (block_mig_state.submitted +
            block_mig_state.read_done) <
           MAX_INFLIGHT_IO) {
P
Paolo Bonzini 已提交
716
        blk_mig_unlock();
717 718 719 720 721 722
        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;
            }
723
            ret = 0;
724
        } else {
725 726 727 728
            /* Always called with iothread lock taken for
             * simplicity, block_save_complete also calls it.
             */
            qemu_mutex_lock_iothread();
729
            ret = blk_mig_save_dirty_block(f, 1);
730
            qemu_mutex_unlock_iothread();
731 732 733 734
        }
        if (ret < 0) {
            return ret;
        }
P
Paolo Bonzini 已提交
735
        blk_mig_lock();
736 737 738
        if (ret != 0) {
            /* no more dirty blocks */
            break;
739
        }
740
    }
P
Paolo Bonzini 已提交
741
    blk_mig_unlock();
742

743
    ret = flush_blks(f);
744 745
    if (ret) {
        return ret;
746 747
    }

748
    qemu_put_be64(f, BLK_MIG_FLAG_EOS);
G
Gary R Hook 已提交
749 750 751 752 753 754 755 756
    delta_ftell = qemu_ftell(f) - last_ftell;
    if (delta_ftell > 0) {
        return 1;
    } else if (delta_ftell < 0) {
        return -1;
    } else {
        return 0;
    }
757 758
}

759 760
/* Called with iothread lock taken.  */

761 762 763 764 765 766 767
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);

768
    ret = flush_blks(f);
769 770 771
    if (ret) {
        return ret;
    }
772

773
    blk_mig_reset_dirty_cursor();
774

775 776
    /* we know for sure that save bulk is completed and
       all async read completed */
P
Paolo Bonzini 已提交
777
    blk_mig_lock();
778
    assert(block_mig_state.submitted == 0);
P
Paolo Bonzini 已提交
779
    blk_mig_unlock();
780

781 782
    do {
        ret = blk_mig_save_dirty_block(f, 0);
783 784 785
        if (ret < 0) {
            return ret;
        }
786
    } while (ret == 0);
787

788 789
    /* report completion */
    qemu_put_be64(f, (100 << BDRV_SECTOR_BITS) | BLK_MIG_FLAG_PROGRESS);
790

791 792
    DPRINTF("Block migration completed\n");

793 794
    qemu_put_be64(f, BLK_MIG_FLAG_EOS);

795
    return 0;
L
lirans@il.ibm.com 已提交
796 797
}

798 799 800
static void block_save_pending(QEMUFile *f, void *opaque, uint64_t max_size,
                               uint64_t *non_postcopiable_pending,
                               uint64_t *postcopiable_pending)
801
{
802
    /* Estimate pending number of bytes to send */
803 804
    uint64_t pending;

805
    qemu_mutex_lock_iothread();
806 807 808
    pending = get_remaining_dirty();
    qemu_mutex_unlock_iothread();

P
Paolo Bonzini 已提交
809
    blk_mig_lock();
810 811 812
    pending += block_mig_state.submitted * BLOCK_SIZE +
               block_mig_state.read_done * BLOCK_SIZE;
    blk_mig_unlock();
813 814

    /* Report at least one block pending during bulk phase */
815 816
    if (pending <= max_size && !block_mig_state.bulk_completed) {
        pending = max_size + BLOCK_SIZE;
817
    }
818

819
    DPRINTF("Enter save live pending  %" PRIu64 "\n", pending);
820 821
    /* We don't do postcopy */
    *non_postcopiable_pending += pending;
822 823
}

L
lirans@il.ibm.com 已提交
824 825
static int block_load(QEMUFile *f, void *opaque, int version_id)
{
826
    static int banner_printed;
L
lirans@il.ibm.com 已提交
827 828 829
    int len, flags;
    char device_name[256];
    int64_t addr;
830
    BlockDriverState *bs, *bs_prev = NULL;
831
    BlockBackend *blk;
832
    Error *local_err = NULL;
L
lirans@il.ibm.com 已提交
833
    uint8_t *buf;
834 835
    int64_t total_sectors = 0;
    int nr_sectors;
836
    int ret;
837

L
lirans@il.ibm.com 已提交
838 839
    do {
        addr = qemu_get_be64(f);
840

J
Jan Kiszka 已提交
841 842
        flags = addr & ~BDRV_SECTOR_MASK;
        addr >>= BDRV_SECTOR_BITS;
843 844

        if (flags & BLK_MIG_FLAG_DEVICE_BLOCK) {
L
lirans@il.ibm.com 已提交
845 846 847 848
            /* get device name */
            len = qemu_get_byte(f);
            qemu_get_buffer(f, (uint8_t *)device_name, len);
            device_name[len] = '\0';
849

850 851
            blk = blk_by_name(device_name);
            if (!blk) {
852 853 854 855
                fprintf(stderr, "Error unknown block device %s\n",
                        device_name);
                return -EINVAL;
            }
856
            bs = blk_bs(blk);
M
Max Reitz 已提交
857 858 859 860 861
            if (!bs) {
                fprintf(stderr, "Block device %s has no medium\n",
                        device_name);
                return -EINVAL;
            }
862

863 864
            if (bs != bs_prev) {
                bs_prev = bs;
865
                total_sectors = bdrv_nb_sectors(bs);
866
                if (total_sectors <= 0) {
867
                    error_report("Error getting length of block device %s",
868 869 870
                                 device_name);
                    return -EINVAL;
                }
871 872 873 874 875 876

                bdrv_invalidate_cache(bs, &local_err);
                if (local_err) {
                    error_report_err(local_err);
                    return -EINVAL;
                }
877 878 879 880 881 882 883 884
            }

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

885
            if (flags & BLK_MIG_FLAG_ZERO_BLOCK) {
886 887 888
                ret = bdrv_pwrite_zeroes(bs, addr << BDRV_SECTOR_BITS,
                                         nr_sectors << BDRV_SECTOR_BITS,
                                         BDRV_REQ_MAY_UNMAP);
889 890 891 892 893 894
            } else {
                buf = g_malloc(BLOCK_SIZE);
                qemu_get_buffer(f, buf, BLOCK_SIZE);
                ret = bdrv_write(bs, addr, buf, nr_sectors);
                g_free(buf);
            }
895

896 897 898
            if (ret < 0) {
                return ret;
            }
899 900 901 902 903 904 905 906
        } 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);
907
        } else if (!(flags & BLK_MIG_FLAG_EOS)) {
908
            fprintf(stderr, "Unknown block migration flags: %#x\n", flags);
909 910
            return -EINVAL;
        }
911 912 913
        ret = qemu_file_get_error(f);
        if (ret != 0) {
            return ret;
L
lirans@il.ibm.com 已提交
914
        }
915 916
    } while (!(flags & BLK_MIG_FLAG_EOS));

L
lirans@il.ibm.com 已提交
917 918 919
    return 0;
}

I
Isaku Yamahata 已提交
920
static void block_set_params(const MigrationParams *params, void *opaque)
L
lirans@il.ibm.com 已提交
921
{
I
Isaku Yamahata 已提交
922 923
    block_mig_state.blk_enable = params->blk;
    block_mig_state.shared_base = params->shared;
924

L
lirans@il.ibm.com 已提交
925
    /* shared base means that blk_enable = 1 */
I
Isaku Yamahata 已提交
926
    block_mig_state.blk_enable |= params->shared;
L
lirans@il.ibm.com 已提交
927 928
}

929 930 931 932 933
static bool block_is_active(void *opaque)
{
    return block_mig_state.blk_enable == 1;
}

934
static SaveVMHandlers savevm_block_handlers = {
935
    .set_params = block_set_params,
936
    .save_live_setup = block_save_setup,
937
    .save_live_iterate = block_save_iterate,
938
    .save_live_complete_precopy = block_save_complete,
939
    .save_live_pending = block_save_pending,
940
    .load_state = block_load,
L
Liang Li 已提交
941
    .cleanup = block_migration_cleanup,
942
    .is_active = block_is_active,
943 944
};

L
lirans@il.ibm.com 已提交
945
void blk_mig_init(void)
946
{
947 948
    QSIMPLEQ_INIT(&block_mig_state.bmds_list);
    QSIMPLEQ_INIT(&block_mig_state.blk_list);
P
Paolo Bonzini 已提交
949
    qemu_mutex_init(&block_mig_state.lock);
950

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