block.c 26.1 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;
386

387 388 389 390 391 392 393 394 395 396 397 398 399
    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();

    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {
        if (bdrv_is_read_only(bs)) {
            continue;
        }

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

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

        block_mig_state.total_sector_sum += sectors;

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

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

429 430
/* Called with no lock taken.  */

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

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

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

    return ret;
L
lirans@il.ibm.com 已提交
466 467
}

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

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

477
/* Called with iothread lock and AioContext taken.  */
478

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

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

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

509
            if (is_async) {
510 511 512 513 514 515
                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 已提交
516 517

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

528 529
                g_free(blk->buf);
                g_free(blk);
530
            }
531

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

539 540
    return (bmds->cur_dirty >= bmds->total_sectors);

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

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

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

    return ret;
L
lirans@il.ibm.com 已提交
569 570
}

571 572
/* Called with no locks taken.  */

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

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

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

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

597 598
        g_free(blk->buf);
        g_free(blk);
599

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

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

612 613
/* Called with iothread lock taken.  */

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

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

625
    return dirty << BDRV_SECTOR_BITS;
626 627
}

628 629
/* Called with iothread lock taken.  */

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

636 637
    bdrv_drain_all();

F
Fam Zheng 已提交
638
    unset_dirty_tracking();
639

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

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

651 652
        g_free(bmds->aio_bitmap);
        g_free(bmds);
653 654
    }

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

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

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

671
    qemu_mutex_lock_iothread();
672
    init_blk_migration(f);
673 674

    /* start track dirty blocks */
675 676
    ret = set_dirty_tracking();

677 678
    qemu_mutex_unlock_iothread();

679 680 681 682
    if (ret) {
        return ret;
    }

683
    ret = flush_blks(f);
684 685 686
    blk_mig_reset_dirty_cursor();
    qemu_put_be64(f, BLK_MIG_FLAG_EOS);

687
    return ret;
688 689
}

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

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

699
    ret = flush_blks(f);
700 701
    if (ret) {
        return ret;
702 703
    }

704 705
    blk_mig_reset_dirty_cursor();

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

741
    ret = flush_blks(f);
742 743
    if (ret) {
        return ret;
744 745
    }

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

757 758
/* Called with iothread lock taken.  */

759 760 761 762 763 764 765
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);

766
    ret = flush_blks(f);
767 768 769
    if (ret) {
        return ret;
    }
770

771
    blk_mig_reset_dirty_cursor();
772

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

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

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

789 790
    DPRINTF("Block migration completed\n");

791 792
    qemu_put_be64(f, BLK_MIG_FLAG_EOS);

793
    return 0;
L
lirans@il.ibm.com 已提交
794 795
}

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

803
    qemu_mutex_lock_iothread();
804 805 806
    pending = get_remaining_dirty();
    qemu_mutex_unlock_iothread();

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

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

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

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

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

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

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

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

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

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

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

883
            if (flags & BLK_MIG_FLAG_ZERO_BLOCK) {
884 885
                ret = bdrv_write_zeroes(bs, addr, nr_sectors,
                                        BDRV_REQ_MAY_UNMAP);
886 887 888 889 890 891
            } else {
                buf = g_malloc(BLOCK_SIZE);
                qemu_get_buffer(f, buf, BLOCK_SIZE);
                ret = bdrv_write(bs, addr, buf, nr_sectors);
                g_free(buf);
            }
892

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

L
lirans@il.ibm.com 已提交
914 915 916
    return 0;
}

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

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

926 927 928 929 930
static bool block_is_active(void *opaque)
{
    return block_mig_state.blk_enable == 1;
}

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

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

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