migration.c 19.9 KB
Newer Older
A
aliguori 已提交
1 2 3 4 5 6 7 8 9 10 11
/*
 * QEMU live migration
 *
 * Copyright IBM, Corp. 2008
 *
 * Authors:
 *  Anthony Liguori   <aliguori@us.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.
A
aliguori 已提交
14 15 16
 */

#include "qemu-common.h"
17
#include "qemu/main-loop.h"
18
#include "migration/migration.h"
19
#include "monitor/monitor.h"
20
#include "migration/qemu-file.h"
21
#include "sysemu/sysemu.h"
22
#include "block/block.h"
23
#include "qemu/sockets.h"
24
#include "migration/block.h"
25
#include "qemu/thread.h"
L
Luiz Capitulino 已提交
26
#include "qmp-commands.h"
27
#include "trace.h"
28 29 30 31

//#define DEBUG_MIGRATION

#ifdef DEBUG_MIGRATION
M
malc 已提交
32
#define DPRINTF(fmt, ...) \
33 34
    do { printf("migration: " fmt, ## __VA_ARGS__); } while (0)
#else
M
malc 已提交
35
#define DPRINTF(fmt, ...) \
36 37
    do { } while (0)
#endif
A
aliguori 已提交
38

39
enum {
40 41
    MIG_STATE_ERROR = -1,
    MIG_STATE_NONE,
42
    MIG_STATE_SETUP,
43
    MIG_STATE_CANCELLING,
44 45 46 47
    MIG_STATE_CANCELLED,
    MIG_STATE_ACTIVE,
    MIG_STATE_COMPLETED,
};
A
aliguori 已提交
48

49
#define MAX_THROTTLE  (32 << 20)      /* Migration speed throttling */
A
aliguori 已提交
50

J
Juan Quintela 已提交
51 52 53 54 55
/* Amount of time to allocate to each "chunk" of bandwidth-throttled
 * data. */
#define BUFFER_DELAY     100
#define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)

56 57 58
/* Migration XBZRLE default cache size */
#define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)

59 60 61
static NotifierList migration_state_notifiers =
    NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);

62 63 64 65
/* When we add fault tolerance, we could have several
   migrations at once.  For now we don't need to add
   dynamic creation of migration */

66
MigrationState *migrate_get_current(void)
67 68
{
    static MigrationState current_migration = {
69
        .state = MIG_STATE_NONE,
70
        .bandwidth_limit = MAX_THROTTLE,
71
        .xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,
72
        .mbps = -1,
73 74 75 76 77
    };

    return &current_migration;
}

78
void qemu_start_incoming_migration(const char *uri, Error **errp)
A
aliguori 已提交
79
{
A
aliguori 已提交
80 81 82
    const char *p;

    if (strstart(uri, "tcp:", &p))
83
        tcp_start_incoming_migration(p, errp);
M
Michael R. Hines 已提交
84
#ifdef CONFIG_RDMA
85
    else if (strstart(uri, "rdma:", &p))
M
Michael R. Hines 已提交
86 87
        rdma_start_incoming_migration(p, errp);
#endif
88 89
#if !defined(WIN32)
    else if (strstart(uri, "exec:", &p))
90
        exec_start_incoming_migration(p, errp);
C
Chris Lalancette 已提交
91
    else if (strstart(uri, "unix:", &p))
92
        unix_start_incoming_migration(p, errp);
P
Paolo Bonzini 已提交
93
    else if (strstart(uri, "fd:", &p))
94
        fd_start_incoming_migration(p, errp);
95
#endif
J
Juan Quintela 已提交
96
    else {
97
        error_setg(errp, "unknown migration protocol: %s", uri);
J
Juan Quintela 已提交
98
    }
A
aliguori 已提交
99 100
}

101
static void process_incoming_migration_co(void *opaque)
102
{
103
    QEMUFile *f = opaque;
104
    Error *local_err = NULL;
105 106 107 108
    int ret;

    ret = qemu_loadvm_state(f);
    qemu_fclose(f);
109
    free_xbzrle_decoded_buf();
110
    if (ret < 0) {
111
        fprintf(stderr, "load of migration failed\n");
112
        exit(EXIT_FAILURE);
113 114 115 116
    }
    qemu_announce_self();
    DPRINTF("successfully loaded vm state\n");

117
    bdrv_clear_incoming_migration_all();
118
    /* Make sure all file formats flush their mutable metadata */
119 120 121 122 123 124
    bdrv_invalidate_cache_all(&local_err);
    if (local_err) {
        qerror_report_err(local_err);
        error_free(local_err);
        exit(EXIT_FAILURE);
    }
125

126
    if (autostart) {
127
        vm_start();
128
    } else {
129
        runstate_set(RUN_STATE_PAUSED);
130
    }
131 132
}

133 134 135 136 137 138
void process_incoming_migration(QEMUFile *f)
{
    Coroutine *co = qemu_coroutine_create(process_incoming_migration_co);
    int fd = qemu_get_fd(f);

    assert(fd != -1);
139
    qemu_set_nonblock(fd);
140 141 142
    qemu_coroutine_enter(co, f);
}

143 144 145 146 147 148 149 150 151 152 153
/* amount of nanoseconds we are willing to wait for migration to be down.
 * the choice of nanoseconds is because it is the maximum resolution that
 * get_clock() can achieve. It is an internal measure. All user-visible
 * units must be in seconds */
static uint64_t max_downtime = 30000000;

uint64_t migrate_max_downtime(void)
{
    return max_downtime;
}

O
Orit Wasserman 已提交
154 155 156 157 158 159 160
MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
{
    MigrationCapabilityStatusList *head = NULL;
    MigrationCapabilityStatusList *caps;
    MigrationState *s = migrate_get_current();
    int i;

161
    caps = NULL; /* silence compiler warning */
O
Orit Wasserman 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
    for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
        if (head == NULL) {
            head = g_malloc0(sizeof(*caps));
            caps = head;
        } else {
            caps->next = g_malloc0(sizeof(*caps));
            caps = caps->next;
        }
        caps->value =
            g_malloc(sizeof(*caps->value));
        caps->value->capability = i;
        caps->value->state = s->enabled_capabilities[i];
    }

    return head;
}

O
Orit Wasserman 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191
static void get_xbzrle_cache_stats(MigrationInfo *info)
{
    if (migrate_use_xbzrle()) {
        info->has_xbzrle_cache = true;
        info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
        info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
        info->xbzrle_cache->bytes = xbzrle_mig_bytes_transferred();
        info->xbzrle_cache->pages = xbzrle_mig_pages_transferred();
        info->xbzrle_cache->cache_miss = xbzrle_mig_pages_cache_miss();
        info->xbzrle_cache->overflow = xbzrle_mig_pages_overflow();
    }
}

L
Luiz Capitulino 已提交
192
MigrationInfo *qmp_query_migrate(Error **errp)
A
aliguori 已提交
193
{
L
Luiz Capitulino 已提交
194
    MigrationInfo *info = g_malloc0(sizeof(*info));
195 196 197
    MigrationState *s = migrate_get_current();

    switch (s->state) {
198
    case MIG_STATE_NONE:
199 200
        /* no migration has happened ever */
        break;
201 202 203
    case MIG_STATE_SETUP:
        info->has_status = true;
        info->status = g_strdup("setup");
204
        info->has_total_time = false;
205
        break;
206
    case MIG_STATE_ACTIVE:
207
    case MIG_STATE_CANCELLING:
L
Luiz Capitulino 已提交
208 209
        info->has_status = true;
        info->status = g_strdup("active");
210
        info->has_total_time = true;
211
        info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
212
            - s->total_time;
213 214
        info->has_expected_downtime = true;
        info->expected_downtime = s->expected_downtime;
215 216
        info->has_setup_time = true;
        info->setup_time = s->setup_time;
217

L
Luiz Capitulino 已提交
218 219 220 221 222
        info->has_ram = true;
        info->ram = g_malloc0(sizeof(*info->ram));
        info->ram->transferred = ram_bytes_transferred();
        info->ram->remaining = ram_bytes_remaining();
        info->ram->total = ram_bytes_total();
223
        info->ram->duplicate = dup_mig_pages_transferred();
224
        info->ram->skipped = skipped_mig_pages_transferred();
225 226
        info->ram->normal = norm_mig_pages_transferred();
        info->ram->normal_bytes = norm_mig_bytes_transferred();
227
        info->ram->dirty_pages_rate = s->dirty_pages_rate;
228
        info->ram->mbps = s->mbps;
229

230
        if (blk_mig_active()) {
L
Luiz Capitulino 已提交
231 232 233 234 235
            info->has_disk = true;
            info->disk = g_malloc0(sizeof(*info->disk));
            info->disk->transferred = blk_mig_bytes_transferred();
            info->disk->remaining = blk_mig_bytes_remaining();
            info->disk->total = blk_mig_bytes_total();
A
aliguori 已提交
236
        }
O
Orit Wasserman 已提交
237 238

        get_xbzrle_cache_stats(info);
239 240
        break;
    case MIG_STATE_COMPLETED:
O
Orit Wasserman 已提交
241 242
        get_xbzrle_cache_stats(info);

L
Luiz Capitulino 已提交
243 244
        info->has_status = true;
        info->status = g_strdup("completed");
245
        info->has_total_time = true;
246
        info->total_time = s->total_time;
247 248
        info->has_downtime = true;
        info->downtime = s->downtime;
249 250
        info->has_setup_time = true;
        info->setup_time = s->setup_time;
J
Juan Quintela 已提交
251 252 253 254 255 256

        info->has_ram = true;
        info->ram = g_malloc0(sizeof(*info->ram));
        info->ram->transferred = ram_bytes_transferred();
        info->ram->remaining = 0;
        info->ram->total = ram_bytes_total();
257
        info->ram->duplicate = dup_mig_pages_transferred();
258
        info->ram->skipped = skipped_mig_pages_transferred();
259 260
        info->ram->normal = norm_mig_pages_transferred();
        info->ram->normal_bytes = norm_mig_bytes_transferred();
261
        info->ram->mbps = s->mbps;
262 263
        break;
    case MIG_STATE_ERROR:
L
Luiz Capitulino 已提交
264 265
        info->has_status = true;
        info->status = g_strdup("failed");
266 267
        break;
    case MIG_STATE_CANCELLED:
L
Luiz Capitulino 已提交
268 269
        info->has_status = true;
        info->status = g_strdup("cancelled");
270
        break;
A
aliguori 已提交
271
    }
L
Luiz Capitulino 已提交
272 273

    return info;
A
aliguori 已提交
274 275
}

O
Orit Wasserman 已提交
276 277 278 279 280 281
void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
                                  Error **errp)
{
    MigrationState *s = migrate_get_current();
    MigrationCapabilityStatusList *cap;

282
    if (s->state == MIG_STATE_ACTIVE || s->state == MIG_STATE_SETUP) {
O
Orit Wasserman 已提交
283 284 285 286 287 288 289 290 291
        error_set(errp, QERR_MIGRATION_ACTIVE);
        return;
    }

    for (cap = params; cap; cap = cap->next) {
        s->enabled_capabilities[cap->value->capability] = cap->value->state;
    }
}

292 293
/* shared migration helpers */

294 295 296 297 298 299 300
static void migrate_set_state(MigrationState *s, int old_state, int new_state)
{
    if (atomic_cmpxchg(&s->state, old_state, new_state) == new_state) {
        trace_migrate_set_state(new_state);
    }
}

301
static void migrate_fd_cleanup(void *opaque)
302
{
303 304 305 306 307
    MigrationState *s = opaque;

    qemu_bh_delete(s->cleanup_bh);
    s->cleanup_bh = NULL;

308
    if (s->file) {
M
malc 已提交
309
        DPRINTF("closing file\n");
310 311 312 313
        qemu_mutex_unlock_iothread();
        qemu_thread_join(&s->thread);
        qemu_mutex_lock_iothread();

314 315
        qemu_fclose(s->file);
        s->file = NULL;
316 317
    }

318
    assert(s->state != MIG_STATE_ACTIVE);
319

320
    if (s->state != MIG_STATE_COMPLETED) {
321
        qemu_savevm_state_cancel();
322 323 324
        if (s->state == MIG_STATE_CANCELLING) {
            migrate_set_state(s, MIG_STATE_CANCELLING, MIG_STATE_CANCELLED);
        }
325
    }
326 327

    notifier_list_notify(&migration_state_notifiers, s);
328 329
}

330
void migrate_fd_error(MigrationState *s)
331
{
332
    DPRINTF("setting error state\n");
333 334 335 336
    assert(s->file == NULL);
    s->state = MIG_STATE_ERROR;
    trace_migrate_set_state(MIG_STATE_ERROR);
    notifier_list_notify(&migration_state_notifiers, s);
337 338
}

339
static void migrate_fd_cancel(MigrationState *s)
340
{
341
    int old_state ;
M
malc 已提交
342
    DPRINTF("cancelling migration\n");
343

344 345 346 347 348
    do {
        old_state = s->state;
        if (old_state != MIG_STATE_SETUP && old_state != MIG_STATE_ACTIVE) {
            break;
        }
349 350
        migrate_set_state(s, old_state, MIG_STATE_CANCELLING);
    } while (s->state != MIG_STATE_CANCELLING);
351 352
}

353 354 355 356 357 358 359
void add_migration_state_change_notifier(Notifier *notify)
{
    notifier_list_add(&migration_state_notifiers, notify);
}

void remove_migration_state_change_notifier(Notifier *notify)
{
P
Paolo Bonzini 已提交
360
    notifier_remove(notify);
361 362
}

S
Stefan Hajnoczi 已提交
363
bool migration_in_setup(MigrationState *s)
364
{
S
Stefan Hajnoczi 已提交
365
    return s->state == MIG_STATE_SETUP;
366 367
}

368
bool migration_has_finished(MigrationState *s)
369
{
370
    return s->state == MIG_STATE_COMPLETED;
371
}
372

373 374 375 376 377 378
bool migration_has_failed(MigrationState *s)
{
    return (s->state == MIG_STATE_CANCELLED ||
            s->state == MIG_STATE_ERROR);
}

I
Isaku Yamahata 已提交
379
static MigrationState *migrate_init(const MigrationParams *params)
380
{
381
    MigrationState *s = migrate_get_current();
382
    int64_t bandwidth_limit = s->bandwidth_limit;
O
Orit Wasserman 已提交
383
    bool enabled_capabilities[MIGRATION_CAPABILITY_MAX];
384
    int64_t xbzrle_cache_size = s->xbzrle_cache_size;
O
Orit Wasserman 已提交
385 386 387

    memcpy(enabled_capabilities, s->enabled_capabilities,
           sizeof(enabled_capabilities));
388

389
    memset(s, 0, sizeof(*s));
I
Isaku Yamahata 已提交
390
    s->params = *params;
O
Orit Wasserman 已提交
391 392
    memcpy(s->enabled_capabilities, enabled_capabilities,
           sizeof(enabled_capabilities));
393
    s->xbzrle_cache_size = xbzrle_cache_size;
394

395
    s->bandwidth_limit = bandwidth_limit;
396
    s->state = MIG_STATE_SETUP;
397
    trace_migrate_set_state(MIG_STATE_SETUP);
398

399
    s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
400 401
    return s;
}
402

A
Anthony Liguori 已提交
403 404 405 406 407 408 409 410 411 412 413 414
static GSList *migration_blockers;

void migrate_add_blocker(Error *reason)
{
    migration_blockers = g_slist_prepend(migration_blockers, reason);
}

void migrate_del_blocker(Error *reason)
{
    migration_blockers = g_slist_remove(migration_blockers, reason);
}

L
Luiz Capitulino 已提交
415 416 417
void qmp_migrate(const char *uri, bool has_blk, bool blk,
                 bool has_inc, bool inc, bool has_detach, bool detach,
                 Error **errp)
418
{
419
    Error *local_err = NULL;
420
    MigrationState *s = migrate_get_current();
I
Isaku Yamahata 已提交
421
    MigrationParams params;
422 423
    const char *p;

424 425
    params.blk = has_blk && blk;
    params.shared = has_inc && inc;
I
Isaku Yamahata 已提交
426

427 428
    if (s->state == MIG_STATE_ACTIVE || s->state == MIG_STATE_SETUP ||
        s->state == MIG_STATE_CANCELLING) {
L
Luiz Capitulino 已提交
429 430
        error_set(errp, QERR_MIGRATION_ACTIVE);
        return;
431 432
    }

L
Luiz Capitulino 已提交
433 434
    if (qemu_savevm_state_blocked(errp)) {
        return;
435 436
    }

A
Anthony Liguori 已提交
437
    if (migration_blockers) {
L
Luiz Capitulino 已提交
438 439
        *errp = error_copy(migration_blockers->data);
        return;
A
Anthony Liguori 已提交
440 441
    }

I
Isaku Yamahata 已提交
442
    s = migrate_init(&params);
443 444

    if (strstart(uri, "tcp:", &p)) {
445
        tcp_start_outgoing_migration(s, p, &local_err);
M
Michael R. Hines 已提交
446
#ifdef CONFIG_RDMA
447
    } else if (strstart(uri, "rdma:", &p)) {
M
Michael R. Hines 已提交
448 449
        rdma_start_outgoing_migration(s, p, &local_err);
#endif
450 451
#if !defined(WIN32)
    } else if (strstart(uri, "exec:", &p)) {
452
        exec_start_outgoing_migration(s, p, &local_err);
453
    } else if (strstart(uri, "unix:", &p)) {
454
        unix_start_outgoing_migration(s, p, &local_err);
455
    } else if (strstart(uri, "fd:", &p)) {
456
        fd_start_outgoing_migration(s, p, &local_err);
457
#endif
458
    } else {
L
Luiz Capitulino 已提交
459
        error_set(errp, QERR_INVALID_PARAMETER_VALUE, "uri", "a valid migration protocol");
460
        s->state = MIG_STATE_ERROR;
L
Luiz Capitulino 已提交
461
        return;
462 463
    }

464
    if (local_err) {
465
        migrate_fd_error(s);
466
        error_propagate(errp, local_err);
L
Luiz Capitulino 已提交
467
        return;
468
    }
469 470
}

L
Luiz Capitulino 已提交
471
void qmp_migrate_cancel(Error **errp)
472
{
473
    migrate_fd_cancel(migrate_get_current());
474 475
}

476 477 478
void qmp_migrate_set_cache_size(int64_t value, Error **errp)
{
    MigrationState *s = migrate_get_current();
479
    int64_t new_size;
480 481 482 483 484 485 486 487

    /* Check for truncation */
    if (value != (size_t)value) {
        error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
                  "exceeding address space");
        return;
    }

488 489 490 491 492 493 494
    /* Cache should not be larger than guest ram size */
    if (value > ram_bytes_total()) {
        error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
                  "exceeds guest ram size ");
        return;
    }

495 496 497 498 499 500 501 502
    new_size = xbzrle_cache_resize(value);
    if (new_size < 0) {
        error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
                  "is smaller than page size");
        return;
    }

    s->xbzrle_cache_size = new_size;
503 504 505 506 507 508 509
}

int64_t qmp_query_migrate_cache_size(Error **errp)
{
    return migrate_xbzrle_cache_size();
}

L
Luiz Capitulino 已提交
510
void qmp_migrate_set_speed(int64_t value, Error **errp)
511 512 513
{
    MigrationState *s;

L
Luiz Capitulino 已提交
514 515
    if (value < 0) {
        value = 0;
516
    }
517 518 519
    if (value > SIZE_MAX) {
        value = SIZE_MAX;
    }
520

521
    s = migrate_get_current();
L
Luiz Capitulino 已提交
522
    s->bandwidth_limit = value;
523 524 525
    if (s->file) {
        qemu_file_set_rate_limit(s->file, s->bandwidth_limit / XFER_LIMIT_RATIO);
    }
526 527
}

528
void qmp_migrate_set_downtime(double value, Error **errp)
529
{
530 531 532
    value *= 1e9;
    value = MAX(0, MIN(UINT64_MAX, value));
    max_downtime = (uint64_t)value;
533
}
534

535 536 537 538 539 540
bool migrate_rdma_pin_all(void)
{
    MigrationState *s;

    s = migrate_get_current();

541
    return s->enabled_capabilities[MIGRATION_CAPABILITY_RDMA_PIN_ALL];
542 543
}

544 545 546 547 548 549 550 551 552
bool migrate_auto_converge(void)
{
    MigrationState *s;

    s = migrate_get_current();

    return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
}

553 554 555 556 557 558 559 560 561
bool migrate_zero_blocks(void)
{
    MigrationState *s;

    s = migrate_get_current();

    return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
}

562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
int migrate_use_xbzrle(void)
{
    MigrationState *s;

    s = migrate_get_current();

    return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
}

int64_t migrate_xbzrle_cache_size(void)
{
    MigrationState *s;

    s = migrate_get_current();

    return s->xbzrle_cache_size;
}
579 580 581

/* migration thread support */

J
Juan Quintela 已提交
582
static void *migration_thread(void *opaque)
583
{
584
    MigrationState *s = opaque;
585 586
    int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
    int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
587
    int64_t initial_bytes = 0;
588
    int64_t max_size = 0;
589 590
    int64_t start_time = initial_time;
    bool old_vm_running = false;
591 592

    DPRINTF("beginning savevm\n");
593
    qemu_savevm_state_begin(s->file, &s->params);
594

595
    s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
596 597
    migrate_set_state(s, MIG_STATE_SETUP, MIG_STATE_ACTIVE);

598 599
    DPRINTF("setup complete\n");

600
    while (s->state == MIG_STATE_ACTIVE) {
601
        int64_t current_time;
602
        uint64_t pending_size;
603

604
        if (!qemu_file_rate_limit(s->file)) {
605 606
            DPRINTF("iterate\n");
            pending_size = qemu_savevm_state_pending(s->file, max_size);
607 608
            DPRINTF("pending size %" PRIu64 " max %" PRIu64 "\n",
                    pending_size, max_size);
609
            if (pending_size && pending_size >= max_size) {
610
                qemu_savevm_state_iterate(s->file);
611
            } else {
612 613
                int ret;

614
                DPRINTF("done iterating\n");
615
                qemu_mutex_lock_iothread();
616
                start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
617
                qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
618
                old_vm_running = runstate_is_running();
619 620 621

                ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
                if (ret >= 0) {
M
Matthew Garrett 已提交
622
                    qemu_file_set_rate_limit(s->file, INT64_MAX);
623 624
                    qemu_savevm_state_complete(s->file);
                }
625
                qemu_mutex_unlock_iothread();
626 627

                if (ret < 0) {
628
                    migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_ERROR);
629 630 631
                    break;
                }

P
Paolo Bonzini 已提交
632
                if (!qemu_file_get_error(s->file)) {
633
                    migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_COMPLETED);
P
Paolo Bonzini 已提交
634 635
                    break;
                }
636 637
            }
        }
638

639
        if (qemu_file_get_error(s->file)) {
640
            migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_ERROR);
641 642
            break;
        }
643
        current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
644
        if (current_time >= initial_time + BUFFER_DELAY) {
645
            uint64_t transferred_bytes = qemu_ftell(s->file) - initial_bytes;
646
            uint64_t time_spent = current_time - initial_time;
647 648 649
            double bandwidth = transferred_bytes / time_spent;
            max_size = bandwidth * migrate_max_downtime() / 1000000;

650 651 652
            s->mbps = time_spent ? (((double) transferred_bytes * 8.0) /
                    ((double) time_spent / 1000.0)) / 1000.0 / 1000.0 : -1;

653 654 655
            DPRINTF("transferred %" PRIu64 " time_spent %" PRIu64
                    " bandwidth %g max_size %" PRId64 "\n",
                    transferred_bytes, time_spent, bandwidth, max_size);
656 657 658 659 660
            /* if we haven't sent anything, we don't want to recalculate
               10000 is a small enough number for our purposes */
            if (s->dirty_bytes_rate && transferred_bytes > 10000) {
                s->expected_downtime = s->dirty_bytes_rate / bandwidth;
            }
661

662
            qemu_file_reset_rate_limit(s->file);
663
            initial_time = current_time;
664
            initial_bytes = qemu_ftell(s->file);
665
        }
666
        if (qemu_file_rate_limit(s->file)) {
667 668 669
            /* usleep expects microseconds */
            g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
        }
670 671
    }

672
    qemu_mutex_lock_iothread();
673
    if (s->state == MIG_STATE_COMPLETED) {
674
        int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
675 676 677 678 679 680
        s->total_time = end_time - s->total_time;
        s->downtime = end_time - start_time;
        runstate_set(RUN_STATE_POSTMIGRATE);
    } else {
        if (old_vm_running) {
            vm_start();
681
        }
682
    }
683
    qemu_bh_schedule(s->cleanup_bh);
684
    qemu_mutex_unlock_iothread();
685

686 687 688
    return NULL;
}

689
void migrate_fd_connect(MigrationState *s)
690
{
691 692
    s->state = MIG_STATE_SETUP;
    trace_migrate_set_state(MIG_STATE_SETUP);
693

694 695
    /* This is a best 1st approximation. ns to ms */
    s->expected_downtime = max_downtime/1000000;
696
    s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
697

698 699 700
    qemu_file_set_rate_limit(s->file,
                             s->bandwidth_limit / XFER_LIMIT_RATIO);

701 702 703
    /* Notify before starting migration thread */
    notifier_list_notify(&migration_state_notifiers, s);

704
    qemu_thread_create(&s->thread, "migration", migration_thread, s,
705
                       QEMU_THREAD_JOINABLE);
706
}