migration.c 21.2 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
enum {
30 31
    MIG_STATE_ERROR = -1,
    MIG_STATE_NONE,
32
    MIG_STATE_SETUP,
33
    MIG_STATE_CANCELLING,
34 35 36 37
    MIG_STATE_CANCELLED,
    MIG_STATE_ACTIVE,
    MIG_STATE_COMPLETED,
};
A
aliguori 已提交
38

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

J
Juan Quintela 已提交
41 42 43 44 45
/* Amount of time to allocate to each "chunk" of bandwidth-throttled
 * data. */
#define BUFFER_DELAY     100
#define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)

46 47 48
/* Migration XBZRLE default cache size */
#define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)

49 50 51
static NotifierList migration_state_notifiers =
    NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);

D
Dr. David Alan Gilbert 已提交
52 53
static bool deferred_incoming;

54 55 56 57
/* When we add fault tolerance, we could have several
   migrations at once.  For now we don't need to add
   dynamic creation of migration */

58
MigrationState *migrate_get_current(void)
59 60
{
    static MigrationState current_migration = {
61
        .state = MIG_STATE_NONE,
62
        .bandwidth_limit = MAX_THROTTLE,
63
        .xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,
64
        .mbps = -1,
65 66 67 68 69
    };

    return &current_migration;
}

D
Dr. David Alan Gilbert 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82
/*
 * Called on -incoming with a defer: uri.
 * The migration can be started later after any parameters have been
 * changed.
 */
static void deferred_incoming_migration(Error **errp)
{
    if (deferred_incoming) {
        error_setg(errp, "Incoming migration already deferred");
    }
    deferred_incoming = true;
}

83
void qemu_start_incoming_migration(const char *uri, Error **errp)
A
aliguori 已提交
84
{
A
aliguori 已提交
85 86
    const char *p;

D
Dr. David Alan Gilbert 已提交
87 88 89
    if (!strcmp(uri, "defer")) {
        deferred_incoming_migration(errp);
    } else if (strstart(uri, "tcp:", &p)) {
90
        tcp_start_incoming_migration(p, errp);
M
Michael R. Hines 已提交
91
#ifdef CONFIG_RDMA
D
Dr. David Alan Gilbert 已提交
92
    } else if (strstart(uri, "rdma:", &p)) {
M
Michael R. Hines 已提交
93 94
        rdma_start_incoming_migration(p, errp);
#endif
95
#if !defined(WIN32)
D
Dr. David Alan Gilbert 已提交
96
    } else if (strstart(uri, "exec:", &p)) {
97
        exec_start_incoming_migration(p, errp);
D
Dr. David Alan Gilbert 已提交
98
    } else if (strstart(uri, "unix:", &p)) {
99
        unix_start_incoming_migration(p, errp);
D
Dr. David Alan Gilbert 已提交
100
    } else if (strstart(uri, "fd:", &p)) {
101
        fd_start_incoming_migration(p, errp);
102
#endif
D
Dr. David Alan Gilbert 已提交
103
    } else {
104
        error_setg(errp, "unknown migration protocol: %s", uri);
J
Juan Quintela 已提交
105
    }
A
aliguori 已提交
106 107
}

108
static void process_incoming_migration_co(void *opaque)
109
{
110
    QEMUFile *f = opaque;
111
    Error *local_err = NULL;
112 113 114 115
    int ret;

    ret = qemu_loadvm_state(f);
    qemu_fclose(f);
116
    free_xbzrle_decoded_buf();
117
    if (ret < 0) {
118
        error_report("load of migration failed: %s", strerror(-ret));
119
        exit(EXIT_FAILURE);
120 121 122
    }
    qemu_announce_self();

123
    /* Make sure all file formats flush their mutable metadata */
124 125 126 127 128 129
    bdrv_invalidate_cache_all(&local_err);
    if (local_err) {
        qerror_report_err(local_err);
        error_free(local_err);
        exit(EXIT_FAILURE);
    }
130

131
    if (autostart) {
132
        vm_start();
133
    } else {
134
        runstate_set(RUN_STATE_PAUSED);
135
    }
136 137
}

138 139 140 141 142 143
void process_incoming_migration(QEMUFile *f)
{
    Coroutine *co = qemu_coroutine_create(process_incoming_migration_co);
    int fd = qemu_get_fd(f);

    assert(fd != -1);
144
    qemu_set_nonblock(fd);
145 146 147
    qemu_coroutine_enter(co, f);
}

148 149 150 151
/* 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 */
152
static uint64_t max_downtime = 300000000;
153 154 155 156 157 158

uint64_t migrate_max_downtime(void)
{
    return max_downtime;
}

O
Orit Wasserman 已提交
159 160 161 162 163 164 165
MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
{
    MigrationCapabilityStatusList *head = NULL;
    MigrationCapabilityStatusList *caps;
    MigrationState *s = migrate_get_current();
    int i;

166
    caps = NULL; /* silence compiler warning */
O
Orit Wasserman 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    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 已提交
184 185 186 187 188 189 190 191 192
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();
193
        info->xbzrle_cache->cache_miss_rate = xbzrle_mig_cache_miss_rate();
O
Orit Wasserman 已提交
194 195 196 197
        info->xbzrle_cache->overflow = xbzrle_mig_pages_overflow();
    }
}

L
Luiz Capitulino 已提交
198
MigrationInfo *qmp_query_migrate(Error **errp)
A
aliguori 已提交
199
{
L
Luiz Capitulino 已提交
200
    MigrationInfo *info = g_malloc0(sizeof(*info));
201 202 203
    MigrationState *s = migrate_get_current();

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

L
Luiz Capitulino 已提交
224 225 226 227 228
        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();
229
        info->ram->duplicate = dup_mig_pages_transferred();
230
        info->ram->skipped = skipped_mig_pages_transferred();
231 232
        info->ram->normal = norm_mig_pages_transferred();
        info->ram->normal_bytes = norm_mig_bytes_transferred();
233
        info->ram->dirty_pages_rate = s->dirty_pages_rate;
234
        info->ram->mbps = s->mbps;
235
        info->ram->dirty_sync_count = s->dirty_sync_count;
236

237
        if (blk_mig_active()) {
L
Luiz Capitulino 已提交
238 239 240 241 242
            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 已提交
243
        }
O
Orit Wasserman 已提交
244 245

        get_xbzrle_cache_stats(info);
246 247
        break;
    case MIG_STATE_COMPLETED:
O
Orit Wasserman 已提交
248 249
        get_xbzrle_cache_stats(info);

L
Luiz Capitulino 已提交
250 251
        info->has_status = true;
        info->status = g_strdup("completed");
252
        info->has_total_time = true;
253
        info->total_time = s->total_time;
254 255
        info->has_downtime = true;
        info->downtime = s->downtime;
256 257
        info->has_setup_time = true;
        info->setup_time = s->setup_time;
J
Juan Quintela 已提交
258 259 260 261 262 263

        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();
264
        info->ram->duplicate = dup_mig_pages_transferred();
265
        info->ram->skipped = skipped_mig_pages_transferred();
266 267
        info->ram->normal = norm_mig_pages_transferred();
        info->ram->normal_bytes = norm_mig_bytes_transferred();
268
        info->ram->mbps = s->mbps;
269
        info->ram->dirty_sync_count = s->dirty_sync_count;
270 271
        break;
    case MIG_STATE_ERROR:
L
Luiz Capitulino 已提交
272 273
        info->has_status = true;
        info->status = g_strdup("failed");
274 275
        break;
    case MIG_STATE_CANCELLED:
L
Luiz Capitulino 已提交
276 277
        info->has_status = true;
        info->status = g_strdup("cancelled");
278
        break;
A
aliguori 已提交
279
    }
L
Luiz Capitulino 已提交
280 281

    return info;
A
aliguori 已提交
282 283
}

O
Orit Wasserman 已提交
284 285 286 287 288 289
void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
                                  Error **errp)
{
    MigrationState *s = migrate_get_current();
    MigrationCapabilityStatusList *cap;

290
    if (s->state == MIG_STATE_ACTIVE || s->state == MIG_STATE_SETUP) {
O
Orit Wasserman 已提交
291 292 293 294 295 296 297 298 299
        error_set(errp, QERR_MIGRATION_ACTIVE);
        return;
    }

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

300 301
/* shared migration helpers */

302 303 304 305 306 307 308
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);
    }
}

309
static void migrate_fd_cleanup(void *opaque)
310
{
311 312 313 314 315
    MigrationState *s = opaque;

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

316
    if (s->file) {
317
        trace_migrate_fd_cleanup();
318 319 320 321
        qemu_mutex_unlock_iothread();
        qemu_thread_join(&s->thread);
        qemu_mutex_lock_iothread();

322 323
        qemu_fclose(s->file);
        s->file = NULL;
324 325
    }

326
    assert(s->state != MIG_STATE_ACTIVE);
327

328
    if (s->state != MIG_STATE_COMPLETED) {
329
        qemu_savevm_state_cancel();
330 331 332
        if (s->state == MIG_STATE_CANCELLING) {
            migrate_set_state(s, MIG_STATE_CANCELLING, MIG_STATE_CANCELLED);
        }
333
    }
334 335

    notifier_list_notify(&migration_state_notifiers, s);
336 337
}

338
void migrate_fd_error(MigrationState *s)
339
{
340
    trace_migrate_fd_error();
341 342 343 344
    assert(s->file == NULL);
    s->state = MIG_STATE_ERROR;
    trace_migrate_set_state(MIG_STATE_ERROR);
    notifier_list_notify(&migration_state_notifiers, s);
345 346
}

347
static void migrate_fd_cancel(MigrationState *s)
348
{
349
    int old_state ;
350
    QEMUFile *f = migrate_get_current()->file;
351
    trace_migrate_fd_cancel();
352

353 354 355 356 357
    do {
        old_state = s->state;
        if (old_state != MIG_STATE_SETUP && old_state != MIG_STATE_ACTIVE) {
            break;
        }
358 359
        migrate_set_state(s, old_state, MIG_STATE_CANCELLING);
    } while (s->state != MIG_STATE_CANCELLING);
360 361 362 363 364 365 366 367 368 369 370

    /*
     * If we're unlucky the migration code might be stuck somewhere in a
     * send/write while the network has failed and is waiting to timeout;
     * if we've got shutdown(2) available then we can force it to quit.
     * The outgoing qemu file gets closed in migrate_fd_cleanup that is
     * called in a bh, so there is no race against this cancel.
     */
    if (s->state == MIG_STATE_CANCELLING && f) {
        qemu_file_shutdown(f);
    }
371 372
}

373 374 375 376 377 378 379
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 已提交
380
    notifier_remove(notify);
381 382
}

S
Stefan Hajnoczi 已提交
383
bool migration_in_setup(MigrationState *s)
384
{
S
Stefan Hajnoczi 已提交
385
    return s->state == MIG_STATE_SETUP;
386 387
}

388
bool migration_has_finished(MigrationState *s)
389
{
390
    return s->state == MIG_STATE_COMPLETED;
391
}
392

393 394 395 396 397 398
bool migration_has_failed(MigrationState *s)
{
    return (s->state == MIG_STATE_CANCELLED ||
            s->state == MIG_STATE_ERROR);
}

I
Isaku Yamahata 已提交
399
static MigrationState *migrate_init(const MigrationParams *params)
400
{
401
    MigrationState *s = migrate_get_current();
402
    int64_t bandwidth_limit = s->bandwidth_limit;
O
Orit Wasserman 已提交
403
    bool enabled_capabilities[MIGRATION_CAPABILITY_MAX];
404
    int64_t xbzrle_cache_size = s->xbzrle_cache_size;
O
Orit Wasserman 已提交
405 406 407

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

409
    memset(s, 0, sizeof(*s));
I
Isaku Yamahata 已提交
410
    s->params = *params;
O
Orit Wasserman 已提交
411 412
    memcpy(s->enabled_capabilities, enabled_capabilities,
           sizeof(enabled_capabilities));
413
    s->xbzrle_cache_size = xbzrle_cache_size;
414

415
    s->bandwidth_limit = bandwidth_limit;
416
    s->state = MIG_STATE_SETUP;
417
    trace_migrate_set_state(MIG_STATE_SETUP);
418

419
    s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
420 421
    return s;
}
422

A
Anthony Liguori 已提交
423 424 425 426 427 428 429 430 431 432 433 434
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);
}

D
Dr. David Alan Gilbert 已提交
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
void qmp_migrate_incoming(const char *uri, Error **errp)
{
    Error *local_err = NULL;

    if (!deferred_incoming) {
        error_setg(errp, "'-incoming defer' is required for migrate_incoming");
        return;
    }

    qemu_start_incoming_migration(uri, &local_err);

    if (local_err) {
        error_propagate(errp, local_err);
        return;
    }

    deferred_incoming = false;
}

L
Luiz Capitulino 已提交
454 455 456
void qmp_migrate(const char *uri, bool has_blk, bool blk,
                 bool has_inc, bool inc, bool has_detach, bool detach,
                 Error **errp)
457
{
458
    Error *local_err = NULL;
459
    MigrationState *s = migrate_get_current();
I
Isaku Yamahata 已提交
460
    MigrationParams params;
461 462
    const char *p;

463 464
    params.blk = has_blk && blk;
    params.shared = has_inc && inc;
I
Isaku Yamahata 已提交
465

466 467
    if (s->state == MIG_STATE_ACTIVE || s->state == MIG_STATE_SETUP ||
        s->state == MIG_STATE_CANCELLING) {
L
Luiz Capitulino 已提交
468 469
        error_set(errp, QERR_MIGRATION_ACTIVE);
        return;
470 471
    }

472 473 474 475 476
    if (runstate_check(RUN_STATE_INMIGRATE)) {
        error_setg(errp, "Guest is waiting for an incoming migration");
        return;
    }

L
Luiz Capitulino 已提交
477 478
    if (qemu_savevm_state_blocked(errp)) {
        return;
479 480
    }

A
Anthony Liguori 已提交
481
    if (migration_blockers) {
L
Luiz Capitulino 已提交
482 483
        *errp = error_copy(migration_blockers->data);
        return;
A
Anthony Liguori 已提交
484 485
    }

I
Isaku Yamahata 已提交
486
    s = migrate_init(&params);
487 488

    if (strstart(uri, "tcp:", &p)) {
489
        tcp_start_outgoing_migration(s, p, &local_err);
M
Michael R. Hines 已提交
490
#ifdef CONFIG_RDMA
491
    } else if (strstart(uri, "rdma:", &p)) {
M
Michael R. Hines 已提交
492 493
        rdma_start_outgoing_migration(s, p, &local_err);
#endif
494 495
#if !defined(WIN32)
    } else if (strstart(uri, "exec:", &p)) {
496
        exec_start_outgoing_migration(s, p, &local_err);
497
    } else if (strstart(uri, "unix:", &p)) {
498
        unix_start_outgoing_migration(s, p, &local_err);
499
    } else if (strstart(uri, "fd:", &p)) {
500
        fd_start_outgoing_migration(s, p, &local_err);
501
#endif
502
    } else {
L
Luiz Capitulino 已提交
503
        error_set(errp, QERR_INVALID_PARAMETER_VALUE, "uri", "a valid migration protocol");
504
        s->state = MIG_STATE_ERROR;
L
Luiz Capitulino 已提交
505
        return;
506 507
    }

508
    if (local_err) {
509
        migrate_fd_error(s);
510
        error_propagate(errp, local_err);
L
Luiz Capitulino 已提交
511
        return;
512
    }
513 514
}

L
Luiz Capitulino 已提交
515
void qmp_migrate_cancel(Error **errp)
516
{
517
    migrate_fd_cancel(migrate_get_current());
518 519
}

520 521 522
void qmp_migrate_set_cache_size(int64_t value, Error **errp)
{
    MigrationState *s = migrate_get_current();
523
    int64_t new_size;
524 525 526 527 528 529 530 531

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

532 533 534 535 536 537 538
    /* 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;
    }

539 540 541 542 543 544 545 546
    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;
547 548 549 550 551 552 553
}

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

L
Luiz Capitulino 已提交
554
void qmp_migrate_set_speed(int64_t value, Error **errp)
555 556 557
{
    MigrationState *s;

L
Luiz Capitulino 已提交
558 559
    if (value < 0) {
        value = 0;
560
    }
561 562 563
    if (value > SIZE_MAX) {
        value = SIZE_MAX;
    }
564

565
    s = migrate_get_current();
L
Luiz Capitulino 已提交
566
    s->bandwidth_limit = value;
567 568 569
    if (s->file) {
        qemu_file_set_rate_limit(s->file, s->bandwidth_limit / XFER_LIMIT_RATIO);
    }
570 571
}

572
void qmp_migrate_set_downtime(double value, Error **errp)
573
{
574 575 576
    value *= 1e9;
    value = MAX(0, MIN(UINT64_MAX, value));
    max_downtime = (uint64_t)value;
577
}
578

579 580 581 582 583 584
bool migrate_rdma_pin_all(void)
{
    MigrationState *s;

    s = migrate_get_current();

585
    return s->enabled_capabilities[MIGRATION_CAPABILITY_RDMA_PIN_ALL];
586 587
}

588 589 590 591 592 593 594 595 596
bool migrate_auto_converge(void)
{
    MigrationState *s;

    s = migrate_get_current();

    return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
}

597 598 599 600 601 602 603 604 605
bool migrate_zero_blocks(void)
{
    MigrationState *s;

    s = migrate_get_current();

    return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
}

606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
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;
}
623 624 625

/* migration thread support */

J
Juan Quintela 已提交
626
static void *migration_thread(void *opaque)
627
{
628
    MigrationState *s = opaque;
629 630
    int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
    int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
631
    int64_t initial_bytes = 0;
632
    int64_t max_size = 0;
633 634
    int64_t start_time = initial_time;
    bool old_vm_running = false;
635

636
    qemu_savevm_state_begin(s->file, &s->params);
637

638
    s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
639 640
    migrate_set_state(s, MIG_STATE_SETUP, MIG_STATE_ACTIVE);

641
    while (s->state == MIG_STATE_ACTIVE) {
642
        int64_t current_time;
643
        uint64_t pending_size;
644

645
        if (!qemu_file_rate_limit(s->file)) {
646
            pending_size = qemu_savevm_state_pending(s->file, max_size);
647
            trace_migrate_pending(pending_size, max_size);
648
            if (pending_size && pending_size >= max_size) {
649
                qemu_savevm_state_iterate(s->file);
650
            } else {
651 652
                int ret;

653
                qemu_mutex_lock_iothread();
654
                start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
655
                qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
656
                old_vm_running = runstate_is_running();
657 658 659

                ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
                if (ret >= 0) {
M
Matthew Garrett 已提交
660
                    qemu_file_set_rate_limit(s->file, INT64_MAX);
661 662
                    qemu_savevm_state_complete(s->file);
                }
663
                qemu_mutex_unlock_iothread();
664 665

                if (ret < 0) {
666
                    migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_ERROR);
667 668 669
                    break;
                }

P
Paolo Bonzini 已提交
670
                if (!qemu_file_get_error(s->file)) {
671
                    migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_COMPLETED);
P
Paolo Bonzini 已提交
672 673
                    break;
                }
674 675
            }
        }
676

677
        if (qemu_file_get_error(s->file)) {
678
            migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_ERROR);
679 680
            break;
        }
681
        current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
682
        if (current_time >= initial_time + BUFFER_DELAY) {
683
            uint64_t transferred_bytes = qemu_ftell(s->file) - initial_bytes;
684
            uint64_t time_spent = current_time - initial_time;
685 686 687
            double bandwidth = transferred_bytes / time_spent;
            max_size = bandwidth * migrate_max_downtime() / 1000000;

688 689 690
            s->mbps = time_spent ? (((double) transferred_bytes * 8.0) /
                    ((double) time_spent / 1000.0)) / 1000.0 / 1000.0 : -1;

691 692
            trace_migrate_transferred(transferred_bytes, time_spent,
                                      bandwidth, max_size);
693 694 695 696 697
            /* 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;
            }
698

699
            qemu_file_reset_rate_limit(s->file);
700
            initial_time = current_time;
701
            initial_bytes = qemu_ftell(s->file);
702
        }
703
        if (qemu_file_rate_limit(s->file)) {
704 705 706
            /* usleep expects microseconds */
            g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
        }
707 708
    }

709
    qemu_mutex_lock_iothread();
710
    if (s->state == MIG_STATE_COMPLETED) {
711
        int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
712
        uint64_t transferred_bytes = qemu_ftell(s->file);
713 714
        s->total_time = end_time - s->total_time;
        s->downtime = end_time - start_time;
715 716 717 718
        if (s->total_time) {
            s->mbps = (((double) transferred_bytes * 8.0) /
                       ((double) s->total_time)) / 1000;
        }
719 720 721 722
        runstate_set(RUN_STATE_POSTMIGRATE);
    } else {
        if (old_vm_running) {
            vm_start();
723
        }
724
    }
725
    qemu_bh_schedule(s->cleanup_bh);
726
    qemu_mutex_unlock_iothread();
727

728 729 730
    return NULL;
}

731
void migrate_fd_connect(MigrationState *s)
732
{
733 734
    s->state = MIG_STATE_SETUP;
    trace_migrate_set_state(MIG_STATE_SETUP);
735

736 737
    /* This is a best 1st approximation. ns to ms */
    s->expected_downtime = max_downtime/1000000;
738
    s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
739

740 741 742
    qemu_file_set_rate_limit(s->file,
                             s->bandwidth_limit / XFER_LIMIT_RATIO);

743 744 745
    /* Notify before starting migration thread */
    notifier_list_notify(&migration_state_notifiers, s);

746
    qemu_thread_create(&s->thread, "migration", migration_thread, s,
747
                       QEMU_THREAD_JOINABLE);
748
}