migration.c 23.3 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
#define MAX_THROTTLE  (32 << 20)      /* Migration speed throttling */
A
aliguori 已提交
30

J
Juan Quintela 已提交
31 32 33 34 35
/* Amount of time to allocate to each "chunk" of bandwidth-throttled
 * data. */
#define BUFFER_DELAY     100
#define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)

36 37
/* Default compression thread count */
#define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
38 39 40
/* Default decompression thread count, usually decompression is at
 * least 4 times as fast as compression.*/
#define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
41 42 43
/*0: means nocompress, 1: best speed, ... 9: best compress ratio */
#define DEFAULT_MIGRATE_COMPRESS_LEVEL 1

44 45 46
/* Migration XBZRLE default cache size */
#define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)

47 48 49
static NotifierList migration_state_notifiers =
    NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);

D
Dr. David Alan Gilbert 已提交
50 51
static bool deferred_incoming;

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

56
MigrationState *migrate_get_current(void)
57 58
{
    static MigrationState current_migration = {
59
        .state = MIGRATION_STATUS_NONE,
60
        .bandwidth_limit = MAX_THROTTLE,
61
        .xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,
62
        .mbps = -1,
63 64 65 66 67 68
        .parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] =
                DEFAULT_MIGRATE_COMPRESS_LEVEL,
        .parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] =
                DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT,
        .parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
                DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT,
69 70 71 72 73
    };

    return &current_migration;
}

D
Dr. David Alan Gilbert 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86
/*
 * 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;
}

87
void qemu_start_incoming_migration(const char *uri, Error **errp)
A
aliguori 已提交
88
{
A
aliguori 已提交
89 90
    const char *p;

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

112
static void process_incoming_migration_co(void *opaque)
113
{
114
    QEMUFile *f = opaque;
115
    Error *local_err = NULL;
116 117 118 119
    int ret;

    ret = qemu_loadvm_state(f);
    qemu_fclose(f);
120
    free_xbzrle_decoded_buf();
121
    if (ret < 0) {
122
        error_report("load of migration failed: %s", strerror(-ret));
123
        migrate_decompress_threads_join();
124
        exit(EXIT_FAILURE);
125 126 127
    }
    qemu_announce_self();

128
    /* Make sure all file formats flush their mutable metadata */
129 130
    bdrv_invalidate_cache_all(&local_err);
    if (local_err) {
131
        error_report_err(local_err);
132
        migrate_decompress_threads_join();
133 134
        exit(EXIT_FAILURE);
    }
135

136
    if (autostart) {
137
        vm_start();
138
    } else {
139
        runstate_set(RUN_STATE_PAUSED);
140
    }
141
    migrate_decompress_threads_join();
142 143
}

144 145 146 147 148 149
void process_incoming_migration(QEMUFile *f)
{
    Coroutine *co = qemu_coroutine_create(process_incoming_migration_co);
    int fd = qemu_get_fd(f);

    assert(fd != -1);
150
    migrate_decompress_threads_create();
151
    qemu_set_nonblock(fd);
152 153 154
    qemu_coroutine_enter(co, f);
}

155 156 157 158
/* 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 */
159
static uint64_t max_downtime = 300000000;
160 161 162 163 164 165

uint64_t migrate_max_downtime(void)
{
    return max_downtime;
}

O
Orit Wasserman 已提交
166 167 168 169 170 171 172
MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
{
    MigrationCapabilityStatusList *head = NULL;
    MigrationCapabilityStatusList *caps;
    MigrationState *s = migrate_get_current();
    int i;

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

L
Luiz Capitulino 已提交
205
MigrationInfo *qmp_query_migrate(Error **errp)
A
aliguori 已提交
206
{
L
Luiz Capitulino 已提交
207
    MigrationInfo *info = g_malloc0(sizeof(*info));
208 209 210
    MigrationState *s = migrate_get_current();

    switch (s->state) {
211
    case MIGRATION_STATUS_NONE:
212 213
        /* no migration has happened ever */
        break;
214
    case MIGRATION_STATUS_SETUP:
215
        info->has_status = true;
216
        info->has_total_time = false;
217
        break;
218 219
    case MIGRATION_STATUS_ACTIVE:
    case MIGRATION_STATUS_CANCELLING:
L
Luiz Capitulino 已提交
220
        info->has_status = true;
221
        info->has_total_time = true;
222
        info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
223
            - s->total_time;
224 225
        info->has_expected_downtime = true;
        info->expected_downtime = s->expected_downtime;
226 227
        info->has_setup_time = true;
        info->setup_time = s->setup_time;
228

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

242
        if (blk_mig_active()) {
L
Luiz Capitulino 已提交
243 244 245 246 247
            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 已提交
248
        }
O
Orit Wasserman 已提交
249 250

        get_xbzrle_cache_stats(info);
251
        break;
252
    case MIGRATION_STATUS_COMPLETED:
O
Orit Wasserman 已提交
253 254
        get_xbzrle_cache_stats(info);

L
Luiz Capitulino 已提交
255
        info->has_status = true;
256
        info->has_total_time = true;
257
        info->total_time = s->total_time;
258 259
        info->has_downtime = true;
        info->downtime = s->downtime;
260 261
        info->has_setup_time = true;
        info->setup_time = s->setup_time;
J
Juan Quintela 已提交
262 263 264 265 266 267

        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();
268
        info->ram->duplicate = dup_mig_pages_transferred();
269
        info->ram->skipped = skipped_mig_pages_transferred();
270 271
        info->ram->normal = norm_mig_pages_transferred();
        info->ram->normal_bytes = norm_mig_bytes_transferred();
272
        info->ram->mbps = s->mbps;
273
        info->ram->dirty_sync_count = s->dirty_sync_count;
274
        break;
275
    case MIGRATION_STATUS_FAILED:
L
Luiz Capitulino 已提交
276
        info->has_status = true;
277
        break;
278
    case MIGRATION_STATUS_CANCELLED:
L
Luiz Capitulino 已提交
279
        info->has_status = true;
280
        break;
A
aliguori 已提交
281
    }
282
    info->status = s->state;
L
Luiz Capitulino 已提交
283 284

    return info;
A
aliguori 已提交
285 286
}

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

293 294
    if (s->state == MIGRATION_STATUS_ACTIVE ||
        s->state == MIGRATION_STATUS_SETUP) {
O
Orit Wasserman 已提交
295 296 297 298 299 300 301 302 303
        error_set(errp, QERR_MIGRATION_ACTIVE);
        return;
    }

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

304 305
/* shared migration helpers */

306 307 308 309 310 311 312
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);
    }
}

313
static void migrate_fd_cleanup(void *opaque)
314
{
315 316 317 318 319
    MigrationState *s = opaque;

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

320
    if (s->file) {
321
        trace_migrate_fd_cleanup();
322 323 324 325
        qemu_mutex_unlock_iothread();
        qemu_thread_join(&s->thread);
        qemu_mutex_lock_iothread();

326
        migrate_compress_threads_join();
327 328
        qemu_fclose(s->file);
        s->file = NULL;
329 330
    }

331
    assert(s->state != MIGRATION_STATUS_ACTIVE);
332

333
    if (s->state != MIGRATION_STATUS_COMPLETED) {
334
        qemu_savevm_state_cancel();
335 336 337
        if (s->state == MIGRATION_STATUS_CANCELLING) {
            migrate_set_state(s, MIGRATION_STATUS_CANCELLING,
                              MIGRATION_STATUS_CANCELLED);
338
        }
339
    }
340 341

    notifier_list_notify(&migration_state_notifiers, s);
342 343
}

344
void migrate_fd_error(MigrationState *s)
345
{
346
    trace_migrate_fd_error();
347
    assert(s->file == NULL);
348 349
    s->state = MIGRATION_STATUS_FAILED;
    trace_migrate_set_state(MIGRATION_STATUS_FAILED);
350
    notifier_list_notify(&migration_state_notifiers, s);
351 352
}

353
static void migrate_fd_cancel(MigrationState *s)
354
{
355
    int old_state ;
356
    QEMUFile *f = migrate_get_current()->file;
357
    trace_migrate_fd_cancel();
358

359 360
    do {
        old_state = s->state;
361 362
        if (old_state != MIGRATION_STATUS_SETUP &&
            old_state != MIGRATION_STATUS_ACTIVE) {
363 364
            break;
        }
365 366
        migrate_set_state(s, old_state, MIGRATION_STATUS_CANCELLING);
    } while (s->state != MIGRATION_STATUS_CANCELLING);
367 368 369 370 371 372 373 374

    /*
     * 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.
     */
375
    if (s->state == MIGRATION_STATUS_CANCELLING && f) {
376 377
        qemu_file_shutdown(f);
    }
378 379
}

380 381 382 383 384 385 386
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 已提交
387
    notifier_remove(notify);
388 389
}

S
Stefan Hajnoczi 已提交
390
bool migration_in_setup(MigrationState *s)
391
{
392
    return s->state == MIGRATION_STATUS_SETUP;
393 394
}

395
bool migration_has_finished(MigrationState *s)
396
{
397
    return s->state == MIGRATION_STATUS_COMPLETED;
398
}
399

400 401
bool migration_has_failed(MigrationState *s)
{
402 403
    return (s->state == MIGRATION_STATUS_CANCELLED ||
            s->state == MIGRATION_STATUS_FAILED);
404 405
}

I
Isaku Yamahata 已提交
406
static MigrationState *migrate_init(const MigrationParams *params)
407
{
408
    MigrationState *s = migrate_get_current();
409
    int64_t bandwidth_limit = s->bandwidth_limit;
O
Orit Wasserman 已提交
410
    bool enabled_capabilities[MIGRATION_CAPABILITY_MAX];
411
    int64_t xbzrle_cache_size = s->xbzrle_cache_size;
412 413 414 415 416
    int compress_level = s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
    int compress_thread_count =
            s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
    int decompress_thread_count =
            s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
O
Orit Wasserman 已提交
417 418 419

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

421
    memset(s, 0, sizeof(*s));
I
Isaku Yamahata 已提交
422
    s->params = *params;
O
Orit Wasserman 已提交
423 424
    memcpy(s->enabled_capabilities, enabled_capabilities,
           sizeof(enabled_capabilities));
425
    s->xbzrle_cache_size = xbzrle_cache_size;
426

427 428 429 430 431
    s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] = compress_level;
    s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] =
               compress_thread_count;
    s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
               decompress_thread_count;
432
    s->bandwidth_limit = bandwidth_limit;
433 434
    s->state = MIGRATION_STATUS_SETUP;
    trace_migrate_set_state(MIGRATION_STATUS_SETUP);
435

436
    s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
437 438
    return s;
}
439

A
Anthony Liguori 已提交
440 441 442 443 444 445 446 447 448 449 450 451
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 已提交
452 453 454
void qmp_migrate_incoming(const char *uri, Error **errp)
{
    Error *local_err = NULL;
455
    static bool once = true;
D
Dr. David Alan Gilbert 已提交
456 457

    if (!deferred_incoming) {
458
        error_setg(errp, "For use with '-incoming defer'");
D
Dr. David Alan Gilbert 已提交
459 460
        return;
    }
461 462 463
    if (!once) {
        error_setg(errp, "The incoming migration has already been started");
    }
D
Dr. David Alan Gilbert 已提交
464 465 466 467 468 469 470 471

    qemu_start_incoming_migration(uri, &local_err);

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

472
    once = false;
D
Dr. David Alan Gilbert 已提交
473 474
}

L
Luiz Capitulino 已提交
475 476 477
void qmp_migrate(const char *uri, bool has_blk, bool blk,
                 bool has_inc, bool inc, bool has_detach, bool detach,
                 Error **errp)
478
{
479
    Error *local_err = NULL;
480
    MigrationState *s = migrate_get_current();
I
Isaku Yamahata 已提交
481
    MigrationParams params;
482 483
    const char *p;

484 485
    params.blk = has_blk && blk;
    params.shared = has_inc && inc;
I
Isaku Yamahata 已提交
486

487 488 489
    if (s->state == MIGRATION_STATUS_ACTIVE ||
        s->state == MIGRATION_STATUS_SETUP ||
        s->state == MIGRATION_STATUS_CANCELLING) {
L
Luiz Capitulino 已提交
490 491
        error_set(errp, QERR_MIGRATION_ACTIVE);
        return;
492 493
    }

494 495 496 497 498
    if (runstate_check(RUN_STATE_INMIGRATE)) {
        error_setg(errp, "Guest is waiting for an incoming migration");
        return;
    }

L
Luiz Capitulino 已提交
499 500
    if (qemu_savevm_state_blocked(errp)) {
        return;
501 502
    }

A
Anthony Liguori 已提交
503
    if (migration_blockers) {
L
Luiz Capitulino 已提交
504 505
        *errp = error_copy(migration_blockers->data);
        return;
A
Anthony Liguori 已提交
506 507
    }

I
Isaku Yamahata 已提交
508
    s = migrate_init(&params);
509 510

    if (strstart(uri, "tcp:", &p)) {
511
        tcp_start_outgoing_migration(s, p, &local_err);
M
Michael R. Hines 已提交
512
#ifdef CONFIG_RDMA
513
    } else if (strstart(uri, "rdma:", &p)) {
M
Michael R. Hines 已提交
514 515
        rdma_start_outgoing_migration(s, p, &local_err);
#endif
516 517
#if !defined(WIN32)
    } else if (strstart(uri, "exec:", &p)) {
518
        exec_start_outgoing_migration(s, p, &local_err);
519
    } else if (strstart(uri, "unix:", &p)) {
520
        unix_start_outgoing_migration(s, p, &local_err);
521
    } else if (strstart(uri, "fd:", &p)) {
522
        fd_start_outgoing_migration(s, p, &local_err);
523
#endif
524
    } else {
L
Luiz Capitulino 已提交
525
        error_set(errp, QERR_INVALID_PARAMETER_VALUE, "uri", "a valid migration protocol");
526
        s->state = MIGRATION_STATUS_FAILED;
L
Luiz Capitulino 已提交
527
        return;
528 529
    }

530
    if (local_err) {
531
        migrate_fd_error(s);
532
        error_propagate(errp, local_err);
L
Luiz Capitulino 已提交
533
        return;
534
    }
535 536
}

L
Luiz Capitulino 已提交
537
void qmp_migrate_cancel(Error **errp)
538
{
539
    migrate_fd_cancel(migrate_get_current());
540 541
}

542 543 544
void qmp_migrate_set_cache_size(int64_t value, Error **errp)
{
    MigrationState *s = migrate_get_current();
545
    int64_t new_size;
546 547 548 549 550 551 552 553

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

554 555 556 557 558 559 560
    /* 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;
    }

561 562 563 564 565 566 567 568
    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;
569 570 571 572 573 574 575
}

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

L
Luiz Capitulino 已提交
576
void qmp_migrate_set_speed(int64_t value, Error **errp)
577 578 579
{
    MigrationState *s;

L
Luiz Capitulino 已提交
580 581
    if (value < 0) {
        value = 0;
582
    }
583 584 585
    if (value > SIZE_MAX) {
        value = SIZE_MAX;
    }
586

587
    s = migrate_get_current();
L
Luiz Capitulino 已提交
588
    s->bandwidth_limit = value;
589 590 591
    if (s->file) {
        qemu_file_set_rate_limit(s->file, s->bandwidth_limit / XFER_LIMIT_RATIO);
    }
592 593
}

594
void qmp_migrate_set_downtime(double value, Error **errp)
595
{
596 597 598
    value *= 1e9;
    value = MAX(0, MIN(UINT64_MAX, value));
    max_downtime = (uint64_t)value;
599
}
600

601 602 603 604 605 606 607 608 609
bool migrate_auto_converge(void)
{
    MigrationState *s;

    s = migrate_get_current();

    return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
}

610 611 612 613 614 615 616 617 618
bool migrate_zero_blocks(void)
{
    MigrationState *s;

    s = migrate_get_current();

    return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
}

619 620
bool migrate_use_compression(void)
{
621 622 623 624 625
    MigrationState *s;

    s = migrate_get_current();

    return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
626 627 628 629 630 631 632 633
}

int migrate_compress_level(void)
{
    MigrationState *s;

    s = migrate_get_current();

634
    return s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
635 636 637 638 639 640 641 642
}

int migrate_compress_threads(void)
{
    MigrationState *s;

    s = migrate_get_current();

643
    return s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
644 645
}

646 647 648 649 650 651
int migrate_decompress_threads(void)
{
    MigrationState *s;

    s = migrate_get_current();

652
    return s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
653 654
}

655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
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;
}
672 673 674

/* migration thread support */

J
Juan Quintela 已提交
675
static void *migration_thread(void *opaque)
676
{
677
    MigrationState *s = opaque;
678 679
    int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
    int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
680
    int64_t initial_bytes = 0;
681
    int64_t max_size = 0;
682 683
    int64_t start_time = initial_time;
    bool old_vm_running = false;
684

685
    qemu_savevm_state_begin(s->file, &s->params);
686

687
    s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
688
    migrate_set_state(s, MIGRATION_STATUS_SETUP, MIGRATION_STATUS_ACTIVE);
689

690
    while (s->state == MIGRATION_STATUS_ACTIVE) {
691
        int64_t current_time;
692
        uint64_t pending_size;
693

694
        if (!qemu_file_rate_limit(s->file)) {
695
            pending_size = qemu_savevm_state_pending(s->file, max_size);
696
            trace_migrate_pending(pending_size, max_size);
697
            if (pending_size && pending_size >= max_size) {
698
                qemu_savevm_state_iterate(s->file);
699
            } else {
700 701
                int ret;

702
                qemu_mutex_lock_iothread();
703
                start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
704
                qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
705
                old_vm_running = runstate_is_running();
706 707 708

                ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
                if (ret >= 0) {
M
Matthew Garrett 已提交
709
                    qemu_file_set_rate_limit(s->file, INT64_MAX);
710 711
                    qemu_savevm_state_complete(s->file);
                }
712
                qemu_mutex_unlock_iothread();
713 714

                if (ret < 0) {
715 716
                    migrate_set_state(s, MIGRATION_STATUS_ACTIVE,
                                      MIGRATION_STATUS_FAILED);
717 718 719
                    break;
                }

P
Paolo Bonzini 已提交
720
                if (!qemu_file_get_error(s->file)) {
721 722
                    migrate_set_state(s, MIGRATION_STATUS_ACTIVE,
                                      MIGRATION_STATUS_COMPLETED);
P
Paolo Bonzini 已提交
723 724
                    break;
                }
725 726
            }
        }
727

728
        if (qemu_file_get_error(s->file)) {
729 730
            migrate_set_state(s, MIGRATION_STATUS_ACTIVE,
                              MIGRATION_STATUS_FAILED);
731 732
            break;
        }
733
        current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
734
        if (current_time >= initial_time + BUFFER_DELAY) {
735
            uint64_t transferred_bytes = qemu_ftell(s->file) - initial_bytes;
736
            uint64_t time_spent = current_time - initial_time;
737 738 739
            double bandwidth = transferred_bytes / time_spent;
            max_size = bandwidth * migrate_max_downtime() / 1000000;

740 741 742
            s->mbps = time_spent ? (((double) transferred_bytes * 8.0) /
                    ((double) time_spent / 1000.0)) / 1000.0 / 1000.0 : -1;

743 744
            trace_migrate_transferred(transferred_bytes, time_spent,
                                      bandwidth, max_size);
745 746 747 748 749
            /* 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;
            }
750

751
            qemu_file_reset_rate_limit(s->file);
752
            initial_time = current_time;
753
            initial_bytes = qemu_ftell(s->file);
754
        }
755
        if (qemu_file_rate_limit(s->file)) {
756 757 758
            /* usleep expects microseconds */
            g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
        }
759 760
    }

761
    qemu_mutex_lock_iothread();
762
    if (s->state == MIGRATION_STATUS_COMPLETED) {
763
        int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
764
        uint64_t transferred_bytes = qemu_ftell(s->file);
765 766
        s->total_time = end_time - s->total_time;
        s->downtime = end_time - start_time;
767 768 769 770
        if (s->total_time) {
            s->mbps = (((double) transferred_bytes * 8.0) /
                       ((double) s->total_time)) / 1000;
        }
771 772 773 774
        runstate_set(RUN_STATE_POSTMIGRATE);
    } else {
        if (old_vm_running) {
            vm_start();
775
        }
776
    }
777
    qemu_bh_schedule(s->cleanup_bh);
778
    qemu_mutex_unlock_iothread();
779

780 781 782
    return NULL;
}

783
void migrate_fd_connect(MigrationState *s)
784
{
785 786
    s->state = MIGRATION_STATUS_SETUP;
    trace_migrate_set_state(MIGRATION_STATUS_SETUP);
787

788 789
    /* This is a best 1st approximation. ns to ms */
    s->expected_downtime = max_downtime/1000000;
790
    s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
791

792 793 794
    qemu_file_set_rate_limit(s->file,
                             s->bandwidth_limit / XFER_LIMIT_RATIO);

795 796 797
    /* Notify before starting migration thread */
    notifier_list_notify(&migration_state_notifiers, s);

798
    migrate_compress_threads_create();
799
    qemu_thread_create(&s->thread, "migration", migration_thread, s,
800
                       QEMU_THREAD_JOINABLE);
801
}