migration.c 20.4 KB
Newer Older
aliguori's avatar
aliguori committed
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.
aliguori's avatar
aliguori committed
14
15
16
 */

#include "qemu-common.h"
17
#include "migration/migration.h"
18
#include "monitor/monitor.h"
19
#include "migration/qemu-file.h"
20
#include "sysemu/sysemu.h"
21
#include "block/block.h"
22
#include "qemu/sockets.h"
23
#include "migration/block.h"
24
#include "qemu/thread.h"
Luiz Capitulino's avatar
Luiz Capitulino committed
25
#include "qmp-commands.h"
26
27
28
29

//#define DEBUG_MIGRATION

#ifdef DEBUG_MIGRATION
malc's avatar
malc committed
30
#define DPRINTF(fmt, ...) \
31
32
    do { printf("migration: " fmt, ## __VA_ARGS__); } while (0)
#else
malc's avatar
malc committed
33
#define DPRINTF(fmt, ...) \
34
35
    do { } while (0)
#endif
aliguori's avatar
aliguori committed
36

37
38
39
40
41
42
43
enum {
    MIG_STATE_ERROR,
    MIG_STATE_SETUP,
    MIG_STATE_CANCELLED,
    MIG_STATE_ACTIVE,
    MIG_STATE_COMPLETED,
};
aliguori's avatar
aliguori committed
44

45
#define MAX_THROTTLE  (32 << 20)      /* Migration speed throttling */
aliguori's avatar
aliguori committed
46

47
48
49
50
51
/* Amount of time to allocate to each "chunk" of bandwidth-throttled
 * data. */
#define BUFFER_DELAY     100
#define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)

52
53
54
/* Migration XBZRLE default cache size */
#define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)

55
56
57
static NotifierList migration_state_notifiers =
    NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);

58
59
60
61
/* When we add fault tolerance, we could have several
   migrations at once.  For now we don't need to add
   dynamic creation of migration */

62
MigrationState *migrate_get_current(void)
63
64
65
{
    static MigrationState current_migration = {
        .state = MIG_STATE_SETUP,
66
        .bandwidth_limit = MAX_THROTTLE,
67
        .xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,
68
69
70
71
72
    };

    return &current_migration;
}

73
void qemu_start_incoming_migration(const char *uri, Error **errp)
aliguori's avatar
aliguori committed
74
{
75
76
77
    const char *p;

    if (strstart(uri, "tcp:", &p))
78
        tcp_start_incoming_migration(p, errp);
79
80
#if !defined(WIN32)
    else if (strstart(uri, "exec:", &p))
81
        exec_start_incoming_migration(p, errp);
Chris Lalancette's avatar
Chris Lalancette committed
82
    else if (strstart(uri, "unix:", &p))
83
        unix_start_incoming_migration(p, errp);
Paolo Bonzini's avatar
Paolo Bonzini committed
84
    else if (strstart(uri, "fd:", &p))
85
        fd_start_incoming_migration(p, errp);
86
#endif
87
    else {
88
        error_setg(errp, "unknown migration protocol: %s\n", uri);
89
    }
aliguori's avatar
aliguori committed
90
91
}

92
static void process_incoming_migration_co(void *opaque)
93
{
94
    QEMUFile *f = opaque;
95
96
97
    int ret;

    ret = qemu_loadvm_state(f);
98
    qemu_set_fd_handler(qemu_get_fd(f), NULL, NULL, NULL);
99
100
    qemu_fclose(f);
    if (ret < 0) {
101
102
103
104
105
106
        fprintf(stderr, "load of migration failed\n");
        exit(0);
    }
    qemu_announce_self();
    DPRINTF("successfully loaded vm state\n");

107
    bdrv_clear_incoming_migration_all();
108
109
110
    /* Make sure all file formats flush their mutable metadata */
    bdrv_invalidate_cache_all();

111
    if (autostart) {
112
        vm_start();
113
    } else {
114
        runstate_set(RUN_STATE_PAUSED);
115
    }
116
117
}

118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
static void enter_migration_coroutine(void *opaque)
{
    Coroutine *co = opaque;
    qemu_coroutine_enter(co, NULL);
}

void process_incoming_migration(QEMUFile *f)
{
    Coroutine *co = qemu_coroutine_create(process_incoming_migration_co);
    int fd = qemu_get_fd(f);

    assert(fd != -1);
    socket_set_nonblock(fd);
    qemu_set_fd_handler(fd, enter_migration_coroutine, NULL, co);
    qemu_coroutine_enter(co, f);
}

135
136
137
138
139
140
141
142
143
144
145
/* 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;
}

Orit Wasserman's avatar
Orit Wasserman committed
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
{
    MigrationCapabilityStatusList *head = NULL;
    MigrationCapabilityStatusList *caps;
    MigrationState *s = migrate_get_current();
    int i;

    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;
}

Orit Wasserman's avatar
Orit Wasserman committed
170
171
172
173
174
175
176
177
178
179
180
181
182
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();
    }
}

Luiz Capitulino's avatar
Luiz Capitulino committed
183
MigrationInfo *qmp_query_migrate(Error **errp)
aliguori's avatar
aliguori committed
184
{
Luiz Capitulino's avatar
Luiz Capitulino committed
185
    MigrationInfo *info = g_malloc0(sizeof(*info));
186
187
188
189
190
191
192
    MigrationState *s = migrate_get_current();

    switch (s->state) {
    case MIG_STATE_SETUP:
        /* no migration has happened ever */
        break;
    case MIG_STATE_ACTIVE:
Luiz Capitulino's avatar
Luiz Capitulino committed
193
194
        info->has_status = true;
        info->status = g_strdup("active");
195
196
197
        info->has_total_time = true;
        info->total_time = qemu_get_clock_ms(rt_clock)
            - s->total_time;
198
199
        info->has_expected_downtime = true;
        info->expected_downtime = s->expected_downtime;
200

Luiz Capitulino's avatar
Luiz Capitulino committed
201
202
203
204
205
        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();
206
207
208
        info->ram->duplicate = dup_mig_pages_transferred();
        info->ram->normal = norm_mig_pages_transferred();
        info->ram->normal_bytes = norm_mig_bytes_transferred();
209
210
        info->ram->dirty_pages_rate = s->dirty_pages_rate;

211
212

        if (blk_mig_active()) {
Luiz Capitulino's avatar
Luiz Capitulino committed
213
214
215
216
217
            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();
aliguori's avatar
aliguori committed
218
        }
Orit Wasserman's avatar
Orit Wasserman committed
219
220

        get_xbzrle_cache_stats(info);
221
222
        break;
    case MIG_STATE_COMPLETED:
Orit Wasserman's avatar
Orit Wasserman committed
223
224
        get_xbzrle_cache_stats(info);

Luiz Capitulino's avatar
Luiz Capitulino committed
225
226
        info->has_status = true;
        info->status = g_strdup("completed");
227
        info->total_time = s->total_time;
228
229
        info->has_downtime = true;
        info->downtime = s->downtime;
Juan Quintela's avatar
Juan Quintela committed
230
231
232
233
234
235

        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();
236
237
238
        info->ram->duplicate = dup_mig_pages_transferred();
        info->ram->normal = norm_mig_pages_transferred();
        info->ram->normal_bytes = norm_mig_bytes_transferred();
239
240
        break;
    case MIG_STATE_ERROR:
Luiz Capitulino's avatar
Luiz Capitulino committed
241
242
        info->has_status = true;
        info->status = g_strdup("failed");
243
244
        break;
    case MIG_STATE_CANCELLED:
Luiz Capitulino's avatar
Luiz Capitulino committed
245
246
        info->has_status = true;
        info->status = g_strdup("cancelled");
247
        break;
aliguori's avatar
aliguori committed
248
    }
Luiz Capitulino's avatar
Luiz Capitulino committed
249
250

    return info;
aliguori's avatar
aliguori committed
251
252
}

Orit Wasserman's avatar
Orit Wasserman committed
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
                                  Error **errp)
{
    MigrationState *s = migrate_get_current();
    MigrationCapabilityStatusList *cap;

    if (s->state == MIG_STATE_ACTIVE) {
        error_set(errp, QERR_MIGRATION_ACTIVE);
        return;
    }

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

269
270
/* shared migration helpers */

271
static int migrate_fd_cleanup(MigrationState *s)
272
{
273
274
    int ret = 0;

275
    if (s->file) {
malc's avatar
malc committed
276
        DPRINTF("closing file\n");
277
        ret = qemu_fclose(s->file);
278
        s->file = NULL;
279
280
    }

281
    assert(s->fd == -1);
282
    return ret;
283
284
}

285
void migrate_fd_error(MigrationState *s)
286
{
287
288
    DPRINTF("setting error state\n");
    s->state = MIG_STATE_ERROR;
289
    notifier_list_notify(&migration_state_notifiers, s);
290
291
292
    migrate_fd_cleanup(s);
}

293
294
295
296
297
298
299
300
301
static void migrate_fd_completed(MigrationState *s)
{
    DPRINTF("setting completed state\n");
    if (migrate_fd_cleanup(s) < 0) {
        s->state = MIG_STATE_ERROR;
    } else {
        s->state = MIG_STATE_COMPLETED;
        runstate_set(RUN_STATE_POSTMIGRATE);
    }
302
    notifier_list_notify(&migration_state_notifiers, s);
303
304
}

305
306
static ssize_t migrate_fd_put_buffer(MigrationState *s, const void *data,
                                     size_t size)
307
308
309
{
    ssize_t ret;

310
311
312
313
    if (s->state != MIG_STATE_ACTIVE) {
        return -EIO;
    }

314
315
    do {
        ret = s->write(s, data, size);
316
    } while (ret == -1 && ((s->get_error(s)) == EINTR));
317
318
319
320
321
322
323

    if (ret == -1)
        ret = -(s->get_error(s));

    return ret;
}

324
static void migrate_fd_cancel(MigrationState *s)
325
326
327
328
{
    if (s->state != MIG_STATE_ACTIVE)
        return;

malc's avatar
malc committed
329
    DPRINTF("cancelling migration\n");
330
331

    s->state = MIG_STATE_CANCELLED;
332
    notifier_list_notify(&migration_state_notifiers, s);
333
    qemu_savevm_state_cancel(s->file);
334
335
336
337

    migrate_fd_cleanup(s);
}

338
int migrate_fd_close(MigrationState *s)
339
{
340
341
342
343
344
345
    int rc = 0;
    if (s->fd != -1) {
        rc = s->close(s);
        s->fd = -1;
    }
    return rc;
346
}
347
348
349
350
351
352
353
354

void add_migration_state_change_notifier(Notifier *notify)
{
    notifier_list_add(&migration_state_notifiers, notify);
}

void remove_migration_state_change_notifier(Notifier *notify)
{
Paolo Bonzini's avatar
Paolo Bonzini committed
355
    notifier_remove(notify);
356
357
}

358
359
360
361
362
bool migration_is_active(MigrationState *s)
{
    return s->state == MIG_STATE_ACTIVE;
}

363
bool migration_has_finished(MigrationState *s)
364
{
365
    return s->state == MIG_STATE_COMPLETED;
366
}
367

368
369
370
371
372
373
bool migration_has_failed(MigrationState *s)
{
    return (s->state == MIG_STATE_CANCELLED ||
            s->state == MIG_STATE_ERROR);
}

Isaku Yamahata's avatar
Isaku Yamahata committed
374
static MigrationState *migrate_init(const MigrationParams *params)
375
{
376
    MigrationState *s = migrate_get_current();
377
    int64_t bandwidth_limit = s->bandwidth_limit;
Orit Wasserman's avatar
Orit Wasserman committed
378
    bool enabled_capabilities[MIGRATION_CAPABILITY_MAX];
379
    int64_t xbzrle_cache_size = s->xbzrle_cache_size;
Orit Wasserman's avatar
Orit Wasserman committed
380
381
382

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

384
    memset(s, 0, sizeof(*s));
385
    s->bandwidth_limit = bandwidth_limit;
Isaku Yamahata's avatar
Isaku Yamahata committed
386
    s->params = *params;
Orit Wasserman's avatar
Orit Wasserman committed
387
388
    memcpy(s->enabled_capabilities, enabled_capabilities,
           sizeof(enabled_capabilities));
389
    s->xbzrle_cache_size = xbzrle_cache_size;
390

391
    s->bandwidth_limit = bandwidth_limit;
392
    s->state = MIG_STATE_SETUP;
Juan Quintela's avatar
Juan Quintela committed
393
    s->total_time = qemu_get_clock_ms(rt_clock);
394
395
396

    return s;
}
397

398
399
400
401
402
403
404
405
406
407
408
409
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);
}

Luiz Capitulino's avatar
Luiz Capitulino committed
410
411
412
void qmp_migrate(const char *uri, bool has_blk, bool blk,
                 bool has_inc, bool inc, bool has_detach, bool detach,
                 Error **errp)
413
{
414
    Error *local_err = NULL;
415
    MigrationState *s = migrate_get_current();
Isaku Yamahata's avatar
Isaku Yamahata committed
416
    MigrationParams params;
417
418
    const char *p;

Isaku Yamahata's avatar
Isaku Yamahata committed
419
420
421
    params.blk = blk;
    params.shared = inc;

422
    if (s->state == MIG_STATE_ACTIVE) {
Luiz Capitulino's avatar
Luiz Capitulino committed
423
424
        error_set(errp, QERR_MIGRATION_ACTIVE);
        return;
425
426
    }

Luiz Capitulino's avatar
Luiz Capitulino committed
427
428
    if (qemu_savevm_state_blocked(errp)) {
        return;
429
430
    }

431
    if (migration_blockers) {
Luiz Capitulino's avatar
Luiz Capitulino committed
432
433
        *errp = error_copy(migration_blockers->data);
        return;
434
435
    }

Isaku Yamahata's avatar
Isaku Yamahata committed
436
    s = migrate_init(&params);
437
438

    if (strstart(uri, "tcp:", &p)) {
439
        tcp_start_outgoing_migration(s, p, &local_err);
440
441
#if !defined(WIN32)
    } else if (strstart(uri, "exec:", &p)) {
442
        exec_start_outgoing_migration(s, p, &local_err);
443
    } else if (strstart(uri, "unix:", &p)) {
444
        unix_start_outgoing_migration(s, p, &local_err);
445
    } else if (strstart(uri, "fd:", &p)) {
446
        fd_start_outgoing_migration(s, p, &local_err);
447
#endif
448
    } else {
Luiz Capitulino's avatar
Luiz Capitulino committed
449
450
        error_set(errp, QERR_INVALID_PARAMETER_VALUE, "uri", "a valid migration protocol");
        return;
451
452
    }

453
    if (local_err) {
454
        migrate_fd_error(s);
455
        error_propagate(errp, local_err);
Luiz Capitulino's avatar
Luiz Capitulino committed
456
        return;
457
    }
458
459
}

Luiz Capitulino's avatar
Luiz Capitulino committed
460
void qmp_migrate_cancel(Error **errp)
461
{
462
    migrate_fd_cancel(migrate_get_current());
463
464
}

465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
void qmp_migrate_set_cache_size(int64_t value, Error **errp)
{
    MigrationState *s = migrate_get_current();

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

    s->xbzrle_cache_size = xbzrle_cache_resize(value);
}

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

484
void qmp_migrate_set_speed(int64_t value, Error **errp)
485
486
487
{
    MigrationState *s;

488
489
    if (value < 0) {
        value = 0;
490
    }
491

492
    s = migrate_get_current();
493
    s->bandwidth_limit = value;
494
    qemu_file_set_rate_limit(s->file, s->bandwidth_limit);
495
496
}

497
void qmp_migrate_set_downtime(double value, Error **errp)
498
{
499
500
501
    value *= 1e9;
    value = MAX(0, MIN(UINT64_MAX, value));
    max_downtime = (uint64_t)value;
502
}
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520

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;
}
521
522
523

/* migration thread support */

524
525

static ssize_t buffered_flush(MigrationState *s)
526
527
528
529
530
531
532
533
{
    size_t offset = 0;
    ssize_t ret = 0;

    DPRINTF("flushing %zu byte(s) of data\n", s->buffer_size);

    while (s->bytes_xfer < s->xfer_limit && offset < s->buffer_size) {
        size_t to_send = MIN(s->buffer_size - offset, s->xfer_limit - s->bytes_xfer);
534
        ret = migrate_fd_put_buffer(s, s->buffer + offset, to_send);
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
        if (ret <= 0) {
            DPRINTF("error flushing data, %zd\n", ret);
            break;
        } else {
            DPRINTF("flushed %zd byte(s)\n", ret);
            offset += ret;
            s->bytes_xfer += ret;
        }
    }

    DPRINTF("flushed %zu of %zu byte(s)\n", offset, s->buffer_size);
    memmove(s->buffer, s->buffer + offset, s->buffer_size - offset);
    s->buffer_size -= offset;

    if (ret < 0) {
        return ret;
    }
    return offset;
}

static int buffered_put_buffer(void *opaque, const uint8_t *buf,
                               int64_t pos, int size)
{
558
    MigrationState *s = opaque;
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
    ssize_t error;

    DPRINTF("putting %d bytes at %" PRId64 "\n", size, pos);

    error = qemu_file_get_error(s->file);
    if (error) {
        DPRINTF("flush when error, bailing: %s\n", strerror(-error));
        return error;
    }

    if (size <= 0) {
        return size;
    }

    if (size > (s->buffer_capacity - s->buffer_size)) {
        DPRINTF("increasing buffer capacity from %zu by %zu\n",
                s->buffer_capacity, size + 1024);

        s->buffer_capacity += size + 1024;

        s->buffer = g_realloc(s->buffer, s->buffer_capacity);
    }

    memcpy(s->buffer + s->buffer_size, buf, size);
    s->buffer_size += size;

    return size;
}

static int buffered_close(void *opaque)
{
590
    MigrationState *s = opaque;
591
592
593
594
595
596
597
598
599
600
601
602
603
    ssize_t ret = 0;
    int ret2;

    DPRINTF("closing\n");

    s->xfer_limit = INT_MAX;
    while (!qemu_file_get_error(s->file) && s->buffer_size) {
        ret = buffered_flush(s);
        if (ret < 0) {
            break;
        }
    }

604
    ret2 = migrate_fd_close(s);
605
606
607
    if (ret >= 0) {
        ret = ret2;
    }
608
    s->complete = true;
609
610
611
612
613
    return ret;
}

static int buffered_get_fd(void *opaque)
{
614
    MigrationState *s = opaque;
615

616
    return s->fd;
617
618
619
620
621
622
623
624
625
626
}

/*
 * The meaning of the return values is:
 *   0: We can continue sending
 *   1: Time to stop
 *   negative: There has been an error
 */
static int buffered_rate_limit(void *opaque)
{
627
    MigrationState *s = opaque;
628
629
630
631
632
633
634
    int ret;

    ret = qemu_file_get_error(s->file);
    if (ret) {
        return ret;
    }

635
    if (s->bytes_xfer >= s->xfer_limit) {
636
637
638
639
640
641
642
643
        return 1;
    }

    return 0;
}

static int64_t buffered_set_rate_limit(void *opaque, int64_t new_rate)
{
644
    MigrationState *s = opaque;
645
646
647
648
649
650
651
    if (qemu_file_get_error(s->file)) {
        goto out;
    }
    if (new_rate > SIZE_MAX) {
        new_rate = SIZE_MAX;
    }

652
    s->xfer_limit = new_rate / XFER_LIMIT_RATIO;
653
654
655
656
657
658
659

out:
    return s->xfer_limit;
}

static int64_t buffered_get_rate_limit(void *opaque)
{
660
    MigrationState *s = opaque;
661
662
663
664

    return s->xfer_limit;
}

665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
static bool migrate_fd_put_ready(MigrationState *s, uint64_t max_size)
{
    int ret;
    uint64_t pending_size;
    bool last_round = false;

    qemu_mutex_lock_iothread();
    if (s->state != MIG_STATE_ACTIVE) {
        DPRINTF("put_ready returning because of non-active state\n");
        qemu_mutex_unlock_iothread();
        return false;
    }

    DPRINTF("iterate\n");
    pending_size = qemu_savevm_state_pending(s->file, max_size);
    DPRINTF("pending size %lu max %lu\n", pending_size, max_size);
    if (pending_size >= max_size) {
        ret = qemu_savevm_state_iterate(s->file);
        if (ret < 0) {
            migrate_fd_error(s);
        }
    } else {
        int old_vm_running = runstate_is_running();
        int64_t start_time, end_time;

        DPRINTF("done iterating\n");
        start_time = qemu_get_clock_ms(rt_clock);
        qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
        if (old_vm_running) {
            vm_stop(RUN_STATE_FINISH_MIGRATE);
        } else {
            vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
        }

        if (qemu_savevm_state_complete(s->file) < 0) {
            migrate_fd_error(s);
        } else {
            migrate_fd_completed(s);
        }
        end_time = qemu_get_clock_ms(rt_clock);
        s->total_time = end_time - s->total_time;
        s->downtime = end_time - start_time;
        if (s->state != MIG_STATE_COMPLETED) {
            if (old_vm_running) {
                vm_start();
            }
        }
        last_round = true;
    }
    qemu_mutex_unlock_iothread();

    return last_round;
}

719
720
static void *buffered_file_thread(void *opaque)
{
721
    MigrationState *s = opaque;
722
723
724
    int64_t initial_time = qemu_get_clock_ms(rt_clock);
    int64_t max_size = 0;
    bool last_round = false;
725
726
727
728
729
730
731
732
733
734
735
    int ret;

    qemu_mutex_lock_iothread();
    DPRINTF("beginning savevm\n");
    ret = qemu_savevm_state_begin(s->file, &s->params);
    if (ret < 0) {
        DPRINTF("failed, %d\n", ret);
        qemu_mutex_unlock_iothread();
        goto out;
    }
    qemu_mutex_unlock_iothread();
736
737
738
739

    while (true) {
        int64_t current_time = qemu_get_clock_ms(rt_clock);

740
        if (s->complete) {
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
            break;
        }
        if (current_time >= initial_time + BUFFER_DELAY) {
            uint64_t transferred_bytes = s->bytes_xfer;
            uint64_t time_spent = current_time - initial_time;
            double bandwidth = transferred_bytes / time_spent;
            max_size = bandwidth * migrate_max_downtime() / 1000000;

            DPRINTF("transferred %" PRIu64 " time_spent %" PRIu64
                    " bandwidth %g max_size %" PRId64 "\n",
                    transferred_bytes, time_spent, bandwidth, max_size);

            s->bytes_xfer = 0;
            initial_time = current_time;
        }
        if (!last_round && (s->bytes_xfer >= s->xfer_limit)) {
            /* usleep expects microseconds */
            g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
        }
        if (buffered_flush(s) < 0) {
            break;
        }

        DPRINTF("file is ready\n");
        if (s->bytes_xfer < s->xfer_limit) {
            DPRINTF("notifying client\n");
767
            last_round = migrate_fd_put_ready(s, max_size);
768
769
770
        }
    }

771
772
773
774
out:
    if (ret < 0) {
        migrate_fd_error(s);
    }
775
776
777
778
779
780
781
782
783
784
785
786
787
    g_free(s->buffer);
    return NULL;
}

static const QEMUFileOps buffered_file_ops = {
    .get_fd =         buffered_get_fd,
    .put_buffer =     buffered_put_buffer,
    .close =          buffered_close,
    .rate_limit =     buffered_rate_limit,
    .get_rate_limit = buffered_get_rate_limit,
    .set_rate_limit = buffered_set_rate_limit,
};

788
void migrate_fd_connect(MigrationState *s)
789
{
790
791
792
793
794
    s->state = MIG_STATE_ACTIVE;
    s->bytes_xfer = 0;
    s->buffer = NULL;
    s->buffer_size = 0;
    s->buffer_capacity = 0;
795

796
797
    s->xfer_limit = s->bandwidth_limit / XFER_LIMIT_RATIO;
    s->complete = false;
798
799
800
801
802

    s->file = qemu_fopen_ops(s, &buffered_file_ops);

    qemu_thread_create(&s->thread, buffered_file_thread, s,
                       QEMU_THREAD_DETACHED);
803
    notifier_list_notify(&migration_state_notifiers, s);
804
}