]> Git Repo - qemu.git/blob - migration/migration.c
COLO: Add block replication into colo process
[qemu.git] / migration / migration.c
1 /*
2  * QEMU live migration
3  *
4  * Copyright IBM, Corp. 2008
5  *
6  * Authors:
7  *  Anthony Liguori   <[email protected]>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2.  See
10  * the COPYING file in the top-level directory.
11  *
12  * Contributions after 2012-01-13 are licensed under the terms of the
13  * GNU GPL, version 2 or (at your option) any later version.
14  */
15
16 #include "qemu/osdep.h"
17 #include "qemu/cutils.h"
18 #include "qemu/error-report.h"
19 #include "migration/blocker.h"
20 #include "exec.h"
21 #include "fd.h"
22 #include "socket.h"
23 #include "rdma.h"
24 #include "ram.h"
25 #include "migration/global_state.h"
26 #include "migration/misc.h"
27 #include "migration.h"
28 #include "savevm.h"
29 #include "qemu-file-channel.h"
30 #include "qemu-file.h"
31 #include "migration/vmstate.h"
32 #include "block/block.h"
33 #include "qapi/error.h"
34 #include "qapi/qapi-commands-migration.h"
35 #include "qapi/qapi-events-migration.h"
36 #include "qapi/qmp/qerror.h"
37 #include "qapi/qmp/qnull.h"
38 #include "qemu/rcu.h"
39 #include "block.h"
40 #include "postcopy-ram.h"
41 #include "qemu/thread.h"
42 #include "trace.h"
43 #include "exec/target_page.h"
44 #include "io/channel-buffer.h"
45 #include "migration/colo.h"
46 #include "hw/boards.h"
47 #include "monitor/monitor.h"
48
49 #define MAX_THROTTLE  (32 << 20)      /* Migration transfer speed throttling */
50
51 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
52  * data. */
53 #define BUFFER_DELAY     100
54 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
55
56 /* Time in milliseconds we are allowed to stop the source,
57  * for sending the last part */
58 #define DEFAULT_MIGRATE_SET_DOWNTIME 300
59
60 /* Maximum migrate downtime set to 2000 seconds */
61 #define MAX_MIGRATE_DOWNTIME_SECONDS 2000
62 #define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000)
63
64 /* Default compression thread count */
65 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
66 /* Default decompression thread count, usually decompression is at
67  * least 4 times as fast as compression.*/
68 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
69 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
70 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
71 /* Define default autoconverge cpu throttle migration parameters */
72 #define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
73 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
74 #define DEFAULT_MIGRATE_MAX_CPU_THROTTLE 99
75
76 /* Migration XBZRLE default cache size */
77 #define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024)
78
79 /* The delay time (in ms) between two COLO checkpoints */
80 #define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY (200 * 100)
81 #define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2
82 #define DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT 16
83
84 /* Background transfer rate for postcopy, 0 means unlimited, note
85  * that page requests can still exceed this limit.
86  */
87 #define DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH 0
88
89 static NotifierList migration_state_notifiers =
90     NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
91
92 static bool deferred_incoming;
93
94 /* Messages sent on the return path from destination to source */
95 enum mig_rp_message_type {
96     MIG_RP_MSG_INVALID = 0,  /* Must be 0 */
97     MIG_RP_MSG_SHUT,         /* sibling will not send any more RP messages */
98     MIG_RP_MSG_PONG,         /* Response to a PING; data (seq: be32 ) */
99
100     MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
101     MIG_RP_MSG_REQ_PAGES,    /* data (start: be64, len: be32) */
102     MIG_RP_MSG_RECV_BITMAP,  /* send recved_bitmap back to source */
103     MIG_RP_MSG_RESUME_ACK,   /* tell source that we are ready to resume */
104
105     MIG_RP_MSG_MAX
106 };
107
108 /* When we add fault tolerance, we could have several
109    migrations at once.  For now we don't need to add
110    dynamic creation of migration */
111
112 static MigrationState *current_migration;
113 static MigrationIncomingState *current_incoming;
114
115 static bool migration_object_check(MigrationState *ms, Error **errp);
116 static int migration_maybe_pause(MigrationState *s,
117                                  int *current_active_state,
118                                  int new_state);
119
120 void migration_object_init(void)
121 {
122     MachineState *ms = MACHINE(qdev_get_machine());
123     Error *err = NULL;
124
125     /* This can only be called once. */
126     assert(!current_migration);
127     current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
128
129     /*
130      * Init the migrate incoming object as well no matter whether
131      * we'll use it or not.
132      */
133     assert(!current_incoming);
134     current_incoming = g_new0(MigrationIncomingState, 1);
135     current_incoming->state = MIGRATION_STATUS_NONE;
136     current_incoming->postcopy_remote_fds =
137         g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD));
138     qemu_mutex_init(&current_incoming->rp_mutex);
139     qemu_event_init(&current_incoming->main_thread_load_event, false);
140     qemu_sem_init(&current_incoming->postcopy_pause_sem_dst, 0);
141     qemu_sem_init(&current_incoming->postcopy_pause_sem_fault, 0);
142
143     init_dirty_bitmap_incoming_migration();
144
145     if (!migration_object_check(current_migration, &err)) {
146         error_report_err(err);
147         exit(1);
148     }
149
150     /*
151      * We cannot really do this in migration_instance_init() since at
152      * that time global properties are not yet applied, then this
153      * value will be definitely replaced by something else.
154      */
155     if (ms->enforce_config_section) {
156         current_migration->send_configuration = true;
157     }
158 }
159
160 void migration_object_finalize(void)
161 {
162     object_unref(OBJECT(current_migration));
163 }
164
165 /* For outgoing */
166 MigrationState *migrate_get_current(void)
167 {
168     /* This can only be called after the object created. */
169     assert(current_migration);
170     return current_migration;
171 }
172
173 MigrationIncomingState *migration_incoming_get_current(void)
174 {
175     assert(current_incoming);
176     return current_incoming;
177 }
178
179 void migration_incoming_state_destroy(void)
180 {
181     struct MigrationIncomingState *mis = migration_incoming_get_current();
182
183     if (mis->to_src_file) {
184         /* Tell source that we are done */
185         migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
186         qemu_fclose(mis->to_src_file);
187         mis->to_src_file = NULL;
188     }
189
190     if (mis->from_src_file) {
191         qemu_fclose(mis->from_src_file);
192         mis->from_src_file = NULL;
193     }
194     if (mis->postcopy_remote_fds) {
195         g_array_free(mis->postcopy_remote_fds, TRUE);
196         mis->postcopy_remote_fds = NULL;
197     }
198
199     qemu_event_reset(&mis->main_thread_load_event);
200 }
201
202 static void migrate_generate_event(int new_state)
203 {
204     if (migrate_use_events()) {
205         qapi_event_send_migration(new_state);
206     }
207 }
208
209 static bool migrate_late_block_activate(void)
210 {
211     MigrationState *s;
212
213     s = migrate_get_current();
214
215     return s->enabled_capabilities[
216         MIGRATION_CAPABILITY_LATE_BLOCK_ACTIVATE];
217 }
218
219 /*
220  * Called on -incoming with a defer: uri.
221  * The migration can be started later after any parameters have been
222  * changed.
223  */
224 static void deferred_incoming_migration(Error **errp)
225 {
226     if (deferred_incoming) {
227         error_setg(errp, "Incoming migration already deferred");
228     }
229     deferred_incoming = true;
230 }
231
232 /*
233  * Send a message on the return channel back to the source
234  * of the migration.
235  */
236 static int migrate_send_rp_message(MigrationIncomingState *mis,
237                                    enum mig_rp_message_type message_type,
238                                    uint16_t len, void *data)
239 {
240     int ret = 0;
241
242     trace_migrate_send_rp_message((int)message_type, len);
243     qemu_mutex_lock(&mis->rp_mutex);
244
245     /*
246      * It's possible that the file handle got lost due to network
247      * failures.
248      */
249     if (!mis->to_src_file) {
250         ret = -EIO;
251         goto error;
252     }
253
254     qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
255     qemu_put_be16(mis->to_src_file, len);
256     qemu_put_buffer(mis->to_src_file, data, len);
257     qemu_fflush(mis->to_src_file);
258
259     /* It's possible that qemu file got error during sending */
260     ret = qemu_file_get_error(mis->to_src_file);
261
262 error:
263     qemu_mutex_unlock(&mis->rp_mutex);
264     return ret;
265 }
266
267 /* Request a range of pages from the source VM at the given
268  * start address.
269  *   rbname: Name of the RAMBlock to request the page in, if NULL it's the same
270  *           as the last request (a name must have been given previously)
271  *   Start: Address offset within the RB
272  *   Len: Length in bytes required - must be a multiple of pagesize
273  */
274 int migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
275                               ram_addr_t start, size_t len)
276 {
277     uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
278     size_t msglen = 12; /* start + len */
279     enum mig_rp_message_type msg_type;
280
281     *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
282     *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
283
284     if (rbname) {
285         int rbname_len = strlen(rbname);
286         assert(rbname_len < 256);
287
288         bufc[msglen++] = rbname_len;
289         memcpy(bufc + msglen, rbname, rbname_len);
290         msglen += rbname_len;
291         msg_type = MIG_RP_MSG_REQ_PAGES_ID;
292     } else {
293         msg_type = MIG_RP_MSG_REQ_PAGES;
294     }
295
296     return migrate_send_rp_message(mis, msg_type, msglen, bufc);
297 }
298
299 void qemu_start_incoming_migration(const char *uri, Error **errp)
300 {
301     const char *p;
302
303     qapi_event_send_migration(MIGRATION_STATUS_SETUP);
304     if (!strcmp(uri, "defer")) {
305         deferred_incoming_migration(errp);
306     } else if (strstart(uri, "tcp:", &p)) {
307         tcp_start_incoming_migration(p, errp);
308 #ifdef CONFIG_RDMA
309     } else if (strstart(uri, "rdma:", &p)) {
310         rdma_start_incoming_migration(p, errp);
311 #endif
312     } else if (strstart(uri, "exec:", &p)) {
313         exec_start_incoming_migration(p, errp);
314     } else if (strstart(uri, "unix:", &p)) {
315         unix_start_incoming_migration(p, errp);
316     } else if (strstart(uri, "fd:", &p)) {
317         fd_start_incoming_migration(p, errp);
318     } else {
319         error_setg(errp, "unknown migration protocol: %s", uri);
320     }
321 }
322
323 static void process_incoming_migration_bh(void *opaque)
324 {
325     Error *local_err = NULL;
326     MigrationIncomingState *mis = opaque;
327
328     /* If capability late_block_activate is set:
329      * Only fire up the block code now if we're going to restart the
330      * VM, else 'cont' will do it.
331      * This causes file locking to happen; so we don't want it to happen
332      * unless we really are starting the VM.
333      */
334     if (!migrate_late_block_activate() ||
335          (autostart && (!global_state_received() ||
336             global_state_get_runstate() == RUN_STATE_RUNNING))) {
337         /* Make sure all file formats flush their mutable metadata.
338          * If we get an error here, just don't restart the VM yet. */
339         bdrv_invalidate_cache_all(&local_err);
340         if (local_err) {
341             error_report_err(local_err);
342             local_err = NULL;
343             autostart = false;
344         }
345     }
346
347     /*
348      * This must happen after all error conditions are dealt with and
349      * we're sure the VM is going to be running on this host.
350      */
351     qemu_announce_self();
352
353     if (multifd_load_cleanup(&local_err) != 0) {
354         error_report_err(local_err);
355         autostart = false;
356     }
357     /* If global state section was not received or we are in running
358        state, we need to obey autostart. Any other state is set with
359        runstate_set. */
360
361     dirty_bitmap_mig_before_vm_start();
362
363     if (!global_state_received() ||
364         global_state_get_runstate() == RUN_STATE_RUNNING) {
365         if (autostart) {
366             vm_start();
367         } else {
368             runstate_set(RUN_STATE_PAUSED);
369         }
370     } else {
371         runstate_set(global_state_get_runstate());
372     }
373     /*
374      * This must happen after any state changes since as soon as an external
375      * observer sees this event they might start to prod at the VM assuming
376      * it's ready to use.
377      */
378     migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
379                       MIGRATION_STATUS_COMPLETED);
380     qemu_bh_delete(mis->bh);
381     migration_incoming_state_destroy();
382 }
383
384 static void process_incoming_migration_co(void *opaque)
385 {
386     MigrationIncomingState *mis = migration_incoming_get_current();
387     PostcopyState ps;
388     int ret;
389     Error *local_err = NULL;
390
391     assert(mis->from_src_file);
392     mis->migration_incoming_co = qemu_coroutine_self();
393     mis->largest_page_size = qemu_ram_pagesize_largest();
394     postcopy_state_set(POSTCOPY_INCOMING_NONE);
395     migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
396                       MIGRATION_STATUS_ACTIVE);
397     ret = qemu_loadvm_state(mis->from_src_file);
398
399     ps = postcopy_state_get();
400     trace_process_incoming_migration_co_end(ret, ps);
401     if (ps != POSTCOPY_INCOMING_NONE) {
402         if (ps == POSTCOPY_INCOMING_ADVISE) {
403             /*
404              * Where a migration had postcopy enabled (and thus went to advise)
405              * but managed to complete within the precopy period, we can use
406              * the normal exit.
407              */
408             postcopy_ram_incoming_cleanup(mis);
409         } else if (ret >= 0) {
410             /*
411              * Postcopy was started, cleanup should happen at the end of the
412              * postcopy thread.
413              */
414             trace_process_incoming_migration_co_postcopy_end_main();
415             return;
416         }
417         /* Else if something went wrong then just fall out of the normal exit */
418     }
419
420     /* we get COLO info, and know if we are in COLO mode */
421     if (!ret && migration_incoming_enable_colo()) {
422         /* Make sure all file formats flush their mutable metadata */
423         bdrv_invalidate_cache_all(&local_err);
424         if (local_err) {
425             migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
426                     MIGRATION_STATUS_FAILED);
427             error_report_err(local_err);
428             exit(EXIT_FAILURE);
429         }
430
431         qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
432              colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
433         mis->have_colo_incoming_thread = true;
434         qemu_coroutine_yield();
435
436         /* Wait checkpoint incoming thread exit before free resource */
437         qemu_thread_join(&mis->colo_incoming_thread);
438     }
439
440     if (ret < 0) {
441         Error *local_err = NULL;
442
443         migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
444                           MIGRATION_STATUS_FAILED);
445         error_report("load of migration failed: %s", strerror(-ret));
446         qemu_fclose(mis->from_src_file);
447         if (multifd_load_cleanup(&local_err) != 0) {
448             error_report_err(local_err);
449         }
450         exit(EXIT_FAILURE);
451     }
452     mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
453     qemu_bh_schedule(mis->bh);
454     mis->migration_incoming_co = NULL;
455 }
456
457 static void migration_incoming_setup(QEMUFile *f)
458 {
459     MigrationIncomingState *mis = migration_incoming_get_current();
460
461     if (multifd_load_setup() != 0) {
462         /* We haven't been able to create multifd threads
463            nothing better to do */
464         exit(EXIT_FAILURE);
465     }
466
467     if (!mis->from_src_file) {
468         mis->from_src_file = f;
469     }
470     qemu_file_set_blocking(f, false);
471 }
472
473 void migration_incoming_process(void)
474 {
475     Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
476     qemu_coroutine_enter(co);
477 }
478
479 /* Returns true if recovered from a paused migration, otherwise false */
480 static bool postcopy_try_recover(QEMUFile *f)
481 {
482     MigrationIncomingState *mis = migration_incoming_get_current();
483
484     if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
485         /* Resumed from a paused postcopy migration */
486
487         mis->from_src_file = f;
488         /* Postcopy has standalone thread to do vm load */
489         qemu_file_set_blocking(f, true);
490
491         /* Re-configure the return path */
492         mis->to_src_file = qemu_file_get_return_path(f);
493
494         migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
495                           MIGRATION_STATUS_POSTCOPY_RECOVER);
496
497         /*
498          * Here, we only wake up the main loading thread (while the
499          * fault thread will still be waiting), so that we can receive
500          * commands from source now, and answer it if needed. The
501          * fault thread will be woken up afterwards until we are sure
502          * that source is ready to reply to page requests.
503          */
504         qemu_sem_post(&mis->postcopy_pause_sem_dst);
505         return true;
506     }
507
508     return false;
509 }
510
511 void migration_fd_process_incoming(QEMUFile *f)
512 {
513     if (postcopy_try_recover(f)) {
514         return;
515     }
516
517     migration_incoming_setup(f);
518     migration_incoming_process();
519 }
520
521 void migration_ioc_process_incoming(QIOChannel *ioc)
522 {
523     MigrationIncomingState *mis = migration_incoming_get_current();
524     bool start_migration;
525
526     if (!mis->from_src_file) {
527         /* The first connection (multifd may have multiple) */
528         QEMUFile *f = qemu_fopen_channel_input(ioc);
529
530         /* If it's a recovery, we're done */
531         if (postcopy_try_recover(f)) {
532             return;
533         }
534
535         migration_incoming_setup(f);
536
537         /*
538          * Common migration only needs one channel, so we can start
539          * right now.  Multifd needs more than one channel, we wait.
540          */
541         start_migration = !migrate_use_multifd();
542     } else {
543         /* Multiple connections */
544         assert(migrate_use_multifd());
545         start_migration = multifd_recv_new_channel(ioc);
546     }
547
548     if (start_migration) {
549         migration_incoming_process();
550     }
551 }
552
553 /**
554  * @migration_has_all_channels: We have received all channels that we need
555  *
556  * Returns true when we have got connections to all the channels that
557  * we need for migration.
558  */
559 bool migration_has_all_channels(void)
560 {
561     MigrationIncomingState *mis = migration_incoming_get_current();
562     bool all_channels;
563
564     all_channels = multifd_recv_all_channels_created();
565
566     return all_channels && mis->from_src_file != NULL;
567 }
568
569 /*
570  * Send a 'SHUT' message on the return channel with the given value
571  * to indicate that we've finished with the RP.  Non-0 value indicates
572  * error.
573  */
574 void migrate_send_rp_shut(MigrationIncomingState *mis,
575                           uint32_t value)
576 {
577     uint32_t buf;
578
579     buf = cpu_to_be32(value);
580     migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
581 }
582
583 /*
584  * Send a 'PONG' message on the return channel with the given value
585  * (normally in response to a 'PING')
586  */
587 void migrate_send_rp_pong(MigrationIncomingState *mis,
588                           uint32_t value)
589 {
590     uint32_t buf;
591
592     buf = cpu_to_be32(value);
593     migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
594 }
595
596 void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
597                                  char *block_name)
598 {
599     char buf[512];
600     int len;
601     int64_t res;
602
603     /*
604      * First, we send the header part. It contains only the len of
605      * idstr, and the idstr itself.
606      */
607     len = strlen(block_name);
608     buf[0] = len;
609     memcpy(buf + 1, block_name, len);
610
611     if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
612         error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
613                      __func__);
614         return;
615     }
616
617     migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
618
619     /*
620      * Next, we dump the received bitmap to the stream.
621      *
622      * TODO: currently we are safe since we are the only one that is
623      * using the to_src_file handle (fault thread is still paused),
624      * and it's ok even not taking the mutex. However the best way is
625      * to take the lock before sending the message header, and release
626      * the lock after sending the bitmap.
627      */
628     qemu_mutex_lock(&mis->rp_mutex);
629     res = ramblock_recv_bitmap_send(mis->to_src_file, block_name);
630     qemu_mutex_unlock(&mis->rp_mutex);
631
632     trace_migrate_send_rp_recv_bitmap(block_name, res);
633 }
634
635 void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
636 {
637     uint32_t buf;
638
639     buf = cpu_to_be32(value);
640     migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
641 }
642
643 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
644 {
645     MigrationCapabilityStatusList *head = NULL;
646     MigrationCapabilityStatusList *caps;
647     MigrationState *s = migrate_get_current();
648     int i;
649
650     caps = NULL; /* silence compiler warning */
651     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
652 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
653         if (i == MIGRATION_CAPABILITY_BLOCK) {
654             continue;
655         }
656 #endif
657         if (head == NULL) {
658             head = g_malloc0(sizeof(*caps));
659             caps = head;
660         } else {
661             caps->next = g_malloc0(sizeof(*caps));
662             caps = caps->next;
663         }
664         caps->value =
665             g_malloc(sizeof(*caps->value));
666         caps->value->capability = i;
667         caps->value->state = s->enabled_capabilities[i];
668     }
669
670     return head;
671 }
672
673 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
674 {
675     MigrationParameters *params;
676     MigrationState *s = migrate_get_current();
677
678     /* TODO use QAPI_CLONE() instead of duplicating it inline */
679     params = g_malloc0(sizeof(*params));
680     params->has_compress_level = true;
681     params->compress_level = s->parameters.compress_level;
682     params->has_compress_threads = true;
683     params->compress_threads = s->parameters.compress_threads;
684     params->has_compress_wait_thread = true;
685     params->compress_wait_thread = s->parameters.compress_wait_thread;
686     params->has_decompress_threads = true;
687     params->decompress_threads = s->parameters.decompress_threads;
688     params->has_cpu_throttle_initial = true;
689     params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
690     params->has_cpu_throttle_increment = true;
691     params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
692     params->has_tls_creds = true;
693     params->tls_creds = g_strdup(s->parameters.tls_creds);
694     params->has_tls_hostname = true;
695     params->tls_hostname = g_strdup(s->parameters.tls_hostname);
696     params->has_max_bandwidth = true;
697     params->max_bandwidth = s->parameters.max_bandwidth;
698     params->has_downtime_limit = true;
699     params->downtime_limit = s->parameters.downtime_limit;
700     params->has_x_checkpoint_delay = true;
701     params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
702     params->has_block_incremental = true;
703     params->block_incremental = s->parameters.block_incremental;
704     params->has_x_multifd_channels = true;
705     params->x_multifd_channels = s->parameters.x_multifd_channels;
706     params->has_x_multifd_page_count = true;
707     params->x_multifd_page_count = s->parameters.x_multifd_page_count;
708     params->has_xbzrle_cache_size = true;
709     params->xbzrle_cache_size = s->parameters.xbzrle_cache_size;
710     params->has_max_postcopy_bandwidth = true;
711     params->max_postcopy_bandwidth = s->parameters.max_postcopy_bandwidth;
712     params->has_max_cpu_throttle = true;
713     params->max_cpu_throttle = s->parameters.max_cpu_throttle;
714
715     return params;
716 }
717
718 /*
719  * Return true if we're already in the middle of a migration
720  * (i.e. any of the active or setup states)
721  */
722 static bool migration_is_setup_or_active(int state)
723 {
724     switch (state) {
725     case MIGRATION_STATUS_ACTIVE:
726     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
727     case MIGRATION_STATUS_POSTCOPY_PAUSED:
728     case MIGRATION_STATUS_POSTCOPY_RECOVER:
729     case MIGRATION_STATUS_SETUP:
730     case MIGRATION_STATUS_PRE_SWITCHOVER:
731     case MIGRATION_STATUS_DEVICE:
732         return true;
733
734     default:
735         return false;
736
737     }
738 }
739
740 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
741 {
742     info->has_ram = true;
743     info->ram = g_malloc0(sizeof(*info->ram));
744     info->ram->transferred = ram_counters.transferred;
745     info->ram->total = ram_bytes_total();
746     info->ram->duplicate = ram_counters.duplicate;
747     /* legacy value.  It is not used anymore */
748     info->ram->skipped = 0;
749     info->ram->normal = ram_counters.normal;
750     info->ram->normal_bytes = ram_counters.normal *
751         qemu_target_page_size();
752     info->ram->mbps = s->mbps;
753     info->ram->dirty_sync_count = ram_counters.dirty_sync_count;
754     info->ram->postcopy_requests = ram_counters.postcopy_requests;
755     info->ram->page_size = qemu_target_page_size();
756     info->ram->multifd_bytes = ram_counters.multifd_bytes;
757
758     if (migrate_use_xbzrle()) {
759         info->has_xbzrle_cache = true;
760         info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
761         info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
762         info->xbzrle_cache->bytes = xbzrle_counters.bytes;
763         info->xbzrle_cache->pages = xbzrle_counters.pages;
764         info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
765         info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
766         info->xbzrle_cache->overflow = xbzrle_counters.overflow;
767     }
768
769     if (migrate_use_compression()) {
770         info->has_compression = true;
771         info->compression = g_malloc0(sizeof(*info->compression));
772         info->compression->pages = compression_counters.pages;
773         info->compression->busy = compression_counters.busy;
774         info->compression->busy_rate = compression_counters.busy_rate;
775         info->compression->compressed_size =
776                                     compression_counters.compressed_size;
777         info->compression->compression_rate =
778                                     compression_counters.compression_rate;
779     }
780
781     if (cpu_throttle_active()) {
782         info->has_cpu_throttle_percentage = true;
783         info->cpu_throttle_percentage = cpu_throttle_get_percentage();
784     }
785
786     if (s->state != MIGRATION_STATUS_COMPLETED) {
787         info->ram->remaining = ram_bytes_remaining();
788         info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate;
789     }
790 }
791
792 static void populate_disk_info(MigrationInfo *info)
793 {
794     if (blk_mig_active()) {
795         info->has_disk = true;
796         info->disk = g_malloc0(sizeof(*info->disk));
797         info->disk->transferred = blk_mig_bytes_transferred();
798         info->disk->remaining = blk_mig_bytes_remaining();
799         info->disk->total = blk_mig_bytes_total();
800     }
801 }
802
803 static void fill_source_migration_info(MigrationInfo *info)
804 {
805     MigrationState *s = migrate_get_current();
806
807     switch (s->state) {
808     case MIGRATION_STATUS_NONE:
809         /* no migration has happened ever */
810         /* do not overwrite destination migration status */
811         return;
812         break;
813     case MIGRATION_STATUS_SETUP:
814         info->has_status = true;
815         info->has_total_time = false;
816         break;
817     case MIGRATION_STATUS_ACTIVE:
818     case MIGRATION_STATUS_CANCELLING:
819     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
820     case MIGRATION_STATUS_PRE_SWITCHOVER:
821     case MIGRATION_STATUS_DEVICE:
822     case MIGRATION_STATUS_POSTCOPY_PAUSED:
823     case MIGRATION_STATUS_POSTCOPY_RECOVER:
824          /* TODO add some postcopy stats */
825         info->has_status = true;
826         info->has_total_time = true;
827         info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
828             - s->start_time;
829         info->has_expected_downtime = true;
830         info->expected_downtime = s->expected_downtime;
831         info->has_setup_time = true;
832         info->setup_time = s->setup_time;
833
834         populate_ram_info(info, s);
835         populate_disk_info(info);
836         break;
837     case MIGRATION_STATUS_COLO:
838         info->has_status = true;
839         /* TODO: display COLO specific information (checkpoint info etc.) */
840         break;
841     case MIGRATION_STATUS_COMPLETED:
842         info->has_status = true;
843         info->has_total_time = true;
844         info->total_time = s->total_time;
845         info->has_downtime = true;
846         info->downtime = s->downtime;
847         info->has_setup_time = true;
848         info->setup_time = s->setup_time;
849
850         populate_ram_info(info, s);
851         break;
852     case MIGRATION_STATUS_FAILED:
853         info->has_status = true;
854         if (s->error) {
855             info->has_error_desc = true;
856             info->error_desc = g_strdup(error_get_pretty(s->error));
857         }
858         break;
859     case MIGRATION_STATUS_CANCELLED:
860         info->has_status = true;
861         break;
862     }
863     info->status = s->state;
864 }
865
866 /**
867  * @migration_caps_check - check capability validity
868  *
869  * @cap_list: old capability list, array of bool
870  * @params: new capabilities to be applied soon
871  * @errp: set *errp if the check failed, with reason
872  *
873  * Returns true if check passed, otherwise false.
874  */
875 static bool migrate_caps_check(bool *cap_list,
876                                MigrationCapabilityStatusList *params,
877                                Error **errp)
878 {
879     MigrationCapabilityStatusList *cap;
880     bool old_postcopy_cap;
881     MigrationIncomingState *mis = migration_incoming_get_current();
882
883     old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];
884
885     for (cap = params; cap; cap = cap->next) {
886         cap_list[cap->value->capability] = cap->value->state;
887     }
888
889 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
890     if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {
891         error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
892                    "block migration");
893         error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
894         return false;
895     }
896 #endif
897
898     if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
899         if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) {
900             /* The decompression threads asynchronously write into RAM
901              * rather than use the atomic copies needed to avoid
902              * userfaulting.  It should be possible to fix the decompression
903              * threads for compatibility in future.
904              */
905             error_setg(errp, "Postcopy is not currently compatible "
906                        "with compression");
907             return false;
908         }
909
910         /* This check is reasonably expensive, so only when it's being
911          * set the first time, also it's only the destination that needs
912          * special support.
913          */
914         if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
915             !postcopy_ram_supported_by_host(mis)) {
916             /* postcopy_ram_supported_by_host will have emitted a more
917              * detailed message
918              */
919             error_setg(errp, "Postcopy is not supported");
920             return false;
921         }
922     }
923
924     return true;
925 }
926
927 static void fill_destination_migration_info(MigrationInfo *info)
928 {
929     MigrationIncomingState *mis = migration_incoming_get_current();
930
931     switch (mis->state) {
932     case MIGRATION_STATUS_NONE:
933         return;
934         break;
935     case MIGRATION_STATUS_SETUP:
936     case MIGRATION_STATUS_CANCELLING:
937     case MIGRATION_STATUS_CANCELLED:
938     case MIGRATION_STATUS_ACTIVE:
939     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
940     case MIGRATION_STATUS_POSTCOPY_PAUSED:
941     case MIGRATION_STATUS_POSTCOPY_RECOVER:
942     case MIGRATION_STATUS_FAILED:
943     case MIGRATION_STATUS_COLO:
944         info->has_status = true;
945         break;
946     case MIGRATION_STATUS_COMPLETED:
947         info->has_status = true;
948         fill_destination_postcopy_migration_info(info);
949         break;
950     }
951     info->status = mis->state;
952 }
953
954 MigrationInfo *qmp_query_migrate(Error **errp)
955 {
956     MigrationInfo *info = g_malloc0(sizeof(*info));
957
958     fill_destination_migration_info(info);
959     fill_source_migration_info(info);
960
961     return info;
962 }
963
964 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
965                                   Error **errp)
966 {
967     MigrationState *s = migrate_get_current();
968     MigrationCapabilityStatusList *cap;
969     bool cap_list[MIGRATION_CAPABILITY__MAX];
970
971     if (migration_is_setup_or_active(s->state)) {
972         error_setg(errp, QERR_MIGRATION_ACTIVE);
973         return;
974     }
975
976     memcpy(cap_list, s->enabled_capabilities, sizeof(cap_list));
977     if (!migrate_caps_check(cap_list, params, errp)) {
978         return;
979     }
980
981     for (cap = params; cap; cap = cap->next) {
982         s->enabled_capabilities[cap->value->capability] = cap->value->state;
983     }
984 }
985
986 /*
987  * Check whether the parameters are valid. Error will be put into errp
988  * (if provided). Return true if valid, otherwise false.
989  */
990 static bool migrate_params_check(MigrationParameters *params, Error **errp)
991 {
992     if (params->has_compress_level &&
993         (params->compress_level > 9)) {
994         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
995                    "is invalid, it should be in the range of 0 to 9");
996         return false;
997     }
998
999     if (params->has_compress_threads && (params->compress_threads < 1)) {
1000         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1001                    "compress_threads",
1002                    "is invalid, it should be in the range of 1 to 255");
1003         return false;
1004     }
1005
1006     if (params->has_decompress_threads && (params->decompress_threads < 1)) {
1007         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1008                    "decompress_threads",
1009                    "is invalid, it should be in the range of 1 to 255");
1010         return false;
1011     }
1012
1013     if (params->has_cpu_throttle_initial &&
1014         (params->cpu_throttle_initial < 1 ||
1015          params->cpu_throttle_initial > 99)) {
1016         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1017                    "cpu_throttle_initial",
1018                    "an integer in the range of 1 to 99");
1019         return false;
1020     }
1021
1022     if (params->has_cpu_throttle_increment &&
1023         (params->cpu_throttle_increment < 1 ||
1024          params->cpu_throttle_increment > 99)) {
1025         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1026                    "cpu_throttle_increment",
1027                    "an integer in the range of 1 to 99");
1028         return false;
1029     }
1030
1031     if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) {
1032         error_setg(errp, "Parameter 'max_bandwidth' expects an integer in the"
1033                          " range of 0 to %zu bytes/second", SIZE_MAX);
1034         return false;
1035     }
1036
1037     if (params->has_downtime_limit &&
1038         (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
1039         error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1040                          "the range of 0 to %d milliseconds",
1041                          MAX_MIGRATE_DOWNTIME);
1042         return false;
1043     }
1044
1045     /* x_checkpoint_delay is now always positive */
1046
1047     if (params->has_x_multifd_channels && (params->x_multifd_channels < 1)) {
1048         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1049                    "multifd_channels",
1050                    "is invalid, it should be in the range of 1 to 255");
1051         return false;
1052     }
1053     if (params->has_x_multifd_page_count &&
1054         (params->x_multifd_page_count < 1 ||
1055          params->x_multifd_page_count > 10000)) {
1056         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1057                    "multifd_page_count",
1058                    "is invalid, it should be in the range of 1 to 10000");
1059         return false;
1060     }
1061
1062     if (params->has_xbzrle_cache_size &&
1063         (params->xbzrle_cache_size < qemu_target_page_size() ||
1064          !is_power_of_2(params->xbzrle_cache_size))) {
1065         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1066                    "xbzrle_cache_size",
1067                    "is invalid, it should be bigger than target page size"
1068                    " and a power of two");
1069         return false;
1070     }
1071
1072     if (params->has_max_cpu_throttle &&
1073         (params->max_cpu_throttle < params->cpu_throttle_initial ||
1074          params->max_cpu_throttle > 99)) {
1075         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1076                    "max_cpu_throttle",
1077                    "an integer in the range of cpu_throttle_initial to 99");
1078         return false;
1079     }
1080
1081     return true;
1082 }
1083
1084 static void migrate_params_test_apply(MigrateSetParameters *params,
1085                                       MigrationParameters *dest)
1086 {
1087     *dest = migrate_get_current()->parameters;
1088
1089     /* TODO use QAPI_CLONE() instead of duplicating it inline */
1090
1091     if (params->has_compress_level) {
1092         dest->compress_level = params->compress_level;
1093     }
1094
1095     if (params->has_compress_threads) {
1096         dest->compress_threads = params->compress_threads;
1097     }
1098
1099     if (params->has_compress_wait_thread) {
1100         dest->compress_wait_thread = params->compress_wait_thread;
1101     }
1102
1103     if (params->has_decompress_threads) {
1104         dest->decompress_threads = params->decompress_threads;
1105     }
1106
1107     if (params->has_cpu_throttle_initial) {
1108         dest->cpu_throttle_initial = params->cpu_throttle_initial;
1109     }
1110
1111     if (params->has_cpu_throttle_increment) {
1112         dest->cpu_throttle_increment = params->cpu_throttle_increment;
1113     }
1114
1115     if (params->has_tls_creds) {
1116         assert(params->tls_creds->type == QTYPE_QSTRING);
1117         dest->tls_creds = g_strdup(params->tls_creds->u.s);
1118     }
1119
1120     if (params->has_tls_hostname) {
1121         assert(params->tls_hostname->type == QTYPE_QSTRING);
1122         dest->tls_hostname = g_strdup(params->tls_hostname->u.s);
1123     }
1124
1125     if (params->has_max_bandwidth) {
1126         dest->max_bandwidth = params->max_bandwidth;
1127     }
1128
1129     if (params->has_downtime_limit) {
1130         dest->downtime_limit = params->downtime_limit;
1131     }
1132
1133     if (params->has_x_checkpoint_delay) {
1134         dest->x_checkpoint_delay = params->x_checkpoint_delay;
1135     }
1136
1137     if (params->has_block_incremental) {
1138         dest->block_incremental = params->block_incremental;
1139     }
1140     if (params->has_x_multifd_channels) {
1141         dest->x_multifd_channels = params->x_multifd_channels;
1142     }
1143     if (params->has_x_multifd_page_count) {
1144         dest->x_multifd_page_count = params->x_multifd_page_count;
1145     }
1146     if (params->has_xbzrle_cache_size) {
1147         dest->xbzrle_cache_size = params->xbzrle_cache_size;
1148     }
1149     if (params->has_max_postcopy_bandwidth) {
1150         dest->max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1151     }
1152     if (params->has_max_cpu_throttle) {
1153         dest->max_cpu_throttle = params->max_cpu_throttle;
1154     }
1155 }
1156
1157 static void migrate_params_apply(MigrateSetParameters *params, Error **errp)
1158 {
1159     MigrationState *s = migrate_get_current();
1160
1161     /* TODO use QAPI_CLONE() instead of duplicating it inline */
1162
1163     if (params->has_compress_level) {
1164         s->parameters.compress_level = params->compress_level;
1165     }
1166
1167     if (params->has_compress_threads) {
1168         s->parameters.compress_threads = params->compress_threads;
1169     }
1170
1171     if (params->has_compress_wait_thread) {
1172         s->parameters.compress_wait_thread = params->compress_wait_thread;
1173     }
1174
1175     if (params->has_decompress_threads) {
1176         s->parameters.decompress_threads = params->decompress_threads;
1177     }
1178
1179     if (params->has_cpu_throttle_initial) {
1180         s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
1181     }
1182
1183     if (params->has_cpu_throttle_increment) {
1184         s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
1185     }
1186
1187     if (params->has_tls_creds) {
1188         g_free(s->parameters.tls_creds);
1189         assert(params->tls_creds->type == QTYPE_QSTRING);
1190         s->parameters.tls_creds = g_strdup(params->tls_creds->u.s);
1191     }
1192
1193     if (params->has_tls_hostname) {
1194         g_free(s->parameters.tls_hostname);
1195         assert(params->tls_hostname->type == QTYPE_QSTRING);
1196         s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s);
1197     }
1198
1199     if (params->has_max_bandwidth) {
1200         s->parameters.max_bandwidth = params->max_bandwidth;
1201         if (s->to_dst_file) {
1202             qemu_file_set_rate_limit(s->to_dst_file,
1203                                 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
1204         }
1205     }
1206
1207     if (params->has_downtime_limit) {
1208         s->parameters.downtime_limit = params->downtime_limit;
1209     }
1210
1211     if (params->has_x_checkpoint_delay) {
1212         s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
1213         if (migration_in_colo_state()) {
1214             colo_checkpoint_notify(s);
1215         }
1216     }
1217
1218     if (params->has_block_incremental) {
1219         s->parameters.block_incremental = params->block_incremental;
1220     }
1221     if (params->has_x_multifd_channels) {
1222         s->parameters.x_multifd_channels = params->x_multifd_channels;
1223     }
1224     if (params->has_x_multifd_page_count) {
1225         s->parameters.x_multifd_page_count = params->x_multifd_page_count;
1226     }
1227     if (params->has_xbzrle_cache_size) {
1228         s->parameters.xbzrle_cache_size = params->xbzrle_cache_size;
1229         xbzrle_cache_resize(params->xbzrle_cache_size, errp);
1230     }
1231     if (params->has_max_postcopy_bandwidth) {
1232         s->parameters.max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1233     }
1234     if (params->has_max_cpu_throttle) {
1235         s->parameters.max_cpu_throttle = params->max_cpu_throttle;
1236     }
1237 }
1238
1239 void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp)
1240 {
1241     MigrationParameters tmp;
1242
1243     /* TODO Rewrite "" to null instead */
1244     if (params->has_tls_creds
1245         && params->tls_creds->type == QTYPE_QNULL) {
1246         qobject_unref(params->tls_creds->u.n);
1247         params->tls_creds->type = QTYPE_QSTRING;
1248         params->tls_creds->u.s = strdup("");
1249     }
1250     /* TODO Rewrite "" to null instead */
1251     if (params->has_tls_hostname
1252         && params->tls_hostname->type == QTYPE_QNULL) {
1253         qobject_unref(params->tls_hostname->u.n);
1254         params->tls_hostname->type = QTYPE_QSTRING;
1255         params->tls_hostname->u.s = strdup("");
1256     }
1257
1258     migrate_params_test_apply(params, &tmp);
1259
1260     if (!migrate_params_check(&tmp, errp)) {
1261         /* Invalid parameter */
1262         return;
1263     }
1264
1265     migrate_params_apply(params, errp);
1266 }
1267
1268
1269 void qmp_migrate_start_postcopy(Error **errp)
1270 {
1271     MigrationState *s = migrate_get_current();
1272
1273     if (!migrate_postcopy()) {
1274         error_setg(errp, "Enable postcopy with migrate_set_capability before"
1275                          " the start of migration");
1276         return;
1277     }
1278
1279     if (s->state == MIGRATION_STATUS_NONE) {
1280         error_setg(errp, "Postcopy must be started after migration has been"
1281                          " started");
1282         return;
1283     }
1284     /*
1285      * we don't error if migration has finished since that would be racy
1286      * with issuing this command.
1287      */
1288     atomic_set(&s->start_postcopy, true);
1289 }
1290
1291 /* shared migration helpers */
1292
1293 void migrate_set_state(int *state, int old_state, int new_state)
1294 {
1295     assert(new_state < MIGRATION_STATUS__MAX);
1296     if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
1297         trace_migrate_set_state(MigrationStatus_str(new_state));
1298         migrate_generate_event(new_state);
1299     }
1300 }
1301
1302 static MigrationCapabilityStatusList *migrate_cap_add(
1303     MigrationCapabilityStatusList *list,
1304     MigrationCapability index,
1305     bool state)
1306 {
1307     MigrationCapabilityStatusList *cap;
1308
1309     cap = g_new0(MigrationCapabilityStatusList, 1);
1310     cap->value = g_new0(MigrationCapabilityStatus, 1);
1311     cap->value->capability = index;
1312     cap->value->state = state;
1313     cap->next = list;
1314
1315     return cap;
1316 }
1317
1318 void migrate_set_block_enabled(bool value, Error **errp)
1319 {
1320     MigrationCapabilityStatusList *cap;
1321
1322     cap = migrate_cap_add(NULL, MIGRATION_CAPABILITY_BLOCK, value);
1323     qmp_migrate_set_capabilities(cap, errp);
1324     qapi_free_MigrationCapabilityStatusList(cap);
1325 }
1326
1327 static void migrate_set_block_incremental(MigrationState *s, bool value)
1328 {
1329     s->parameters.block_incremental = value;
1330 }
1331
1332 static void block_cleanup_parameters(MigrationState *s)
1333 {
1334     if (s->must_remove_block_options) {
1335         /* setting to false can never fail */
1336         migrate_set_block_enabled(false, &error_abort);
1337         migrate_set_block_incremental(s, false);
1338         s->must_remove_block_options = false;
1339     }
1340 }
1341
1342 static void migrate_fd_cleanup(void *opaque)
1343 {
1344     MigrationState *s = opaque;
1345
1346     qemu_bh_delete(s->cleanup_bh);
1347     s->cleanup_bh = NULL;
1348
1349     qemu_savevm_state_cleanup();
1350
1351     if (s->to_dst_file) {
1352         Error *local_err = NULL;
1353         QEMUFile *tmp;
1354
1355         trace_migrate_fd_cleanup();
1356         qemu_mutex_unlock_iothread();
1357         if (s->migration_thread_running) {
1358             qemu_thread_join(&s->thread);
1359             s->migration_thread_running = false;
1360         }
1361         qemu_mutex_lock_iothread();
1362
1363         if (multifd_save_cleanup(&local_err) != 0) {
1364             error_report_err(local_err);
1365         }
1366         qemu_mutex_lock(&s->qemu_file_lock);
1367         tmp = s->to_dst_file;
1368         s->to_dst_file = NULL;
1369         qemu_mutex_unlock(&s->qemu_file_lock);
1370         /*
1371          * Close the file handle without the lock to make sure the
1372          * critical section won't block for long.
1373          */
1374         qemu_fclose(tmp);
1375     }
1376
1377     assert((s->state != MIGRATION_STATUS_ACTIVE) &&
1378            (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
1379
1380     if (s->state == MIGRATION_STATUS_CANCELLING) {
1381         migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1382                           MIGRATION_STATUS_CANCELLED);
1383     }
1384
1385     if (s->error) {
1386         /* It is used on info migrate.  We can't free it */
1387         error_report_err(error_copy(s->error));
1388     }
1389     notifier_list_notify(&migration_state_notifiers, s);
1390     block_cleanup_parameters(s);
1391 }
1392
1393 void migrate_set_error(MigrationState *s, const Error *error)
1394 {
1395     qemu_mutex_lock(&s->error_mutex);
1396     if (!s->error) {
1397         s->error = error_copy(error);
1398     }
1399     qemu_mutex_unlock(&s->error_mutex);
1400 }
1401
1402 void migrate_fd_error(MigrationState *s, const Error *error)
1403 {
1404     trace_migrate_fd_error(error_get_pretty(error));
1405     assert(s->to_dst_file == NULL);
1406     migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1407                       MIGRATION_STATUS_FAILED);
1408     migrate_set_error(s, error);
1409 }
1410
1411 static void migrate_fd_cancel(MigrationState *s)
1412 {
1413     int old_state ;
1414     QEMUFile *f = migrate_get_current()->to_dst_file;
1415     trace_migrate_fd_cancel();
1416
1417     if (s->rp_state.from_dst_file) {
1418         /* shutdown the rp socket, so causing the rp thread to shutdown */
1419         qemu_file_shutdown(s->rp_state.from_dst_file);
1420     }
1421
1422     do {
1423         old_state = s->state;
1424         if (!migration_is_setup_or_active(old_state)) {
1425             break;
1426         }
1427         /* If the migration is paused, kick it out of the pause */
1428         if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1429             qemu_sem_post(&s->pause_sem);
1430         }
1431         migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
1432     } while (s->state != MIGRATION_STATUS_CANCELLING);
1433
1434     /*
1435      * If we're unlucky the migration code might be stuck somewhere in a
1436      * send/write while the network has failed and is waiting to timeout;
1437      * if we've got shutdown(2) available then we can force it to quit.
1438      * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1439      * called in a bh, so there is no race against this cancel.
1440      */
1441     if (s->state == MIGRATION_STATUS_CANCELLING && f) {
1442         qemu_file_shutdown(f);
1443     }
1444     if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1445         Error *local_err = NULL;
1446
1447         bdrv_invalidate_cache_all(&local_err);
1448         if (local_err) {
1449             error_report_err(local_err);
1450         } else {
1451             s->block_inactive = false;
1452         }
1453     }
1454 }
1455
1456 void add_migration_state_change_notifier(Notifier *notify)
1457 {
1458     notifier_list_add(&migration_state_notifiers, notify);
1459 }
1460
1461 void remove_migration_state_change_notifier(Notifier *notify)
1462 {
1463     notifier_remove(notify);
1464 }
1465
1466 bool migration_in_setup(MigrationState *s)
1467 {
1468     return s->state == MIGRATION_STATUS_SETUP;
1469 }
1470
1471 bool migration_has_finished(MigrationState *s)
1472 {
1473     return s->state == MIGRATION_STATUS_COMPLETED;
1474 }
1475
1476 bool migration_has_failed(MigrationState *s)
1477 {
1478     return (s->state == MIGRATION_STATUS_CANCELLED ||
1479             s->state == MIGRATION_STATUS_FAILED);
1480 }
1481
1482 bool migration_in_postcopy(void)
1483 {
1484     MigrationState *s = migrate_get_current();
1485
1486     return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1487 }
1488
1489 bool migration_in_postcopy_after_devices(MigrationState *s)
1490 {
1491     return migration_in_postcopy() && s->postcopy_after_devices;
1492 }
1493
1494 bool migration_is_idle(void)
1495 {
1496     MigrationState *s = migrate_get_current();
1497
1498     switch (s->state) {
1499     case MIGRATION_STATUS_NONE:
1500     case MIGRATION_STATUS_CANCELLED:
1501     case MIGRATION_STATUS_COMPLETED:
1502     case MIGRATION_STATUS_FAILED:
1503         return true;
1504     case MIGRATION_STATUS_SETUP:
1505     case MIGRATION_STATUS_CANCELLING:
1506     case MIGRATION_STATUS_ACTIVE:
1507     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1508     case MIGRATION_STATUS_COLO:
1509     case MIGRATION_STATUS_PRE_SWITCHOVER:
1510     case MIGRATION_STATUS_DEVICE:
1511         return false;
1512     case MIGRATION_STATUS__MAX:
1513         g_assert_not_reached();
1514     }
1515
1516     return false;
1517 }
1518
1519 void migrate_init(MigrationState *s)
1520 {
1521     /*
1522      * Reinitialise all migration state, except
1523      * parameters/capabilities that the user set, and
1524      * locks.
1525      */
1526     s->bytes_xfer = 0;
1527     s->xfer_limit = 0;
1528     s->cleanup_bh = 0;
1529     s->to_dst_file = NULL;
1530     s->state = MIGRATION_STATUS_NONE;
1531     s->rp_state.from_dst_file = NULL;
1532     s->rp_state.error = false;
1533     s->mbps = 0.0;
1534     s->downtime = 0;
1535     s->expected_downtime = 0;
1536     s->setup_time = 0;
1537     s->start_postcopy = false;
1538     s->postcopy_after_devices = false;
1539     s->migration_thread_running = false;
1540     error_free(s->error);
1541     s->error = NULL;
1542
1543     migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
1544
1545     s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1546     s->total_time = 0;
1547     s->vm_was_running = false;
1548     s->iteration_initial_bytes = 0;
1549     s->threshold_size = 0;
1550 }
1551
1552 static GSList *migration_blockers;
1553
1554 int migrate_add_blocker(Error *reason, Error **errp)
1555 {
1556     if (migrate_get_current()->only_migratable) {
1557         error_propagate(errp, error_copy(reason));
1558         error_prepend(errp, "disallowing migration blocker "
1559                           "(--only_migratable) for: ");
1560         return -EACCES;
1561     }
1562
1563     if (migration_is_idle()) {
1564         migration_blockers = g_slist_prepend(migration_blockers, reason);
1565         return 0;
1566     }
1567
1568     error_propagate(errp, error_copy(reason));
1569     error_prepend(errp, "disallowing migration blocker (migration in "
1570                       "progress) for: ");
1571     return -EBUSY;
1572 }
1573
1574 void migrate_del_blocker(Error *reason)
1575 {
1576     migration_blockers = g_slist_remove(migration_blockers, reason);
1577 }
1578
1579 void qmp_migrate_incoming(const char *uri, Error **errp)
1580 {
1581     Error *local_err = NULL;
1582     static bool once = true;
1583
1584     if (!deferred_incoming) {
1585         error_setg(errp, "For use with '-incoming defer'");
1586         return;
1587     }
1588     if (!once) {
1589         error_setg(errp, "The incoming migration has already been started");
1590     }
1591
1592     qemu_start_incoming_migration(uri, &local_err);
1593
1594     if (local_err) {
1595         error_propagate(errp, local_err);
1596         return;
1597     }
1598
1599     once = false;
1600 }
1601
1602 void qmp_migrate_recover(const char *uri, Error **errp)
1603 {
1604     MigrationIncomingState *mis = migration_incoming_get_current();
1605
1606     if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1607         error_setg(errp, "Migrate recover can only be run "
1608                    "when postcopy is paused.");
1609         return;
1610     }
1611
1612     if (atomic_cmpxchg(&mis->postcopy_recover_triggered,
1613                        false, true) == true) {
1614         error_setg(errp, "Migrate recovery is triggered already");
1615         return;
1616     }
1617
1618     /*
1619      * Note that this call will never start a real migration; it will
1620      * only re-setup the migration stream and poke existing migration
1621      * to continue using that newly established channel.
1622      */
1623     qemu_start_incoming_migration(uri, errp);
1624 }
1625
1626 void qmp_migrate_pause(Error **errp)
1627 {
1628     MigrationState *ms = migrate_get_current();
1629     MigrationIncomingState *mis = migration_incoming_get_current();
1630     int ret;
1631
1632     if (ms->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1633         /* Source side, during postcopy */
1634         qemu_mutex_lock(&ms->qemu_file_lock);
1635         ret = qemu_file_shutdown(ms->to_dst_file);
1636         qemu_mutex_unlock(&ms->qemu_file_lock);
1637         if (ret) {
1638             error_setg(errp, "Failed to pause source migration");
1639         }
1640         return;
1641     }
1642
1643     if (mis->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1644         ret = qemu_file_shutdown(mis->from_src_file);
1645         if (ret) {
1646             error_setg(errp, "Failed to pause destination migration");
1647         }
1648         return;
1649     }
1650
1651     error_setg(errp, "migrate-pause is currently only supported "
1652                "during postcopy-active state");
1653 }
1654
1655 bool migration_is_blocked(Error **errp)
1656 {
1657     if (qemu_savevm_state_blocked(errp)) {
1658         return true;
1659     }
1660
1661     if (migration_blockers) {
1662         error_propagate(errp, error_copy(migration_blockers->data));
1663         return true;
1664     }
1665
1666     return false;
1667 }
1668
1669 /* Returns true if continue to migrate, or false if error detected */
1670 static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
1671                             bool resume, Error **errp)
1672 {
1673     Error *local_err = NULL;
1674
1675     if (resume) {
1676         if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1677             error_setg(errp, "Cannot resume if there is no "
1678                        "paused migration");
1679             return false;
1680         }
1681
1682         /*
1683          * Postcopy recovery won't work well with release-ram
1684          * capability since release-ram will drop the page buffer as
1685          * long as the page is put into the send buffer.  So if there
1686          * is a network failure happened, any page buffers that have
1687          * not yet reached the destination VM but have already been
1688          * sent from the source VM will be lost forever.  Let's refuse
1689          * the client from resuming such a postcopy migration.
1690          * Luckily release-ram was designed to only be used when src
1691          * and destination VMs are on the same host, so it should be
1692          * fine.
1693          */
1694         if (migrate_release_ram()) {
1695             error_setg(errp, "Postcopy recovery cannot work "
1696                        "when release-ram capability is set");
1697             return false;
1698         }
1699
1700         /* This is a resume, skip init status */
1701         return true;
1702     }
1703
1704     if (migration_is_setup_or_active(s->state) ||
1705         s->state == MIGRATION_STATUS_CANCELLING ||
1706         s->state == MIGRATION_STATUS_COLO) {
1707         error_setg(errp, QERR_MIGRATION_ACTIVE);
1708         return false;
1709     }
1710
1711     if (runstate_check(RUN_STATE_INMIGRATE)) {
1712         error_setg(errp, "Guest is waiting for an incoming migration");
1713         return false;
1714     }
1715
1716     if (migration_is_blocked(errp)) {
1717         return false;
1718     }
1719
1720     if (blk || blk_inc) {
1721         if (migrate_use_block() || migrate_use_block_incremental()) {
1722             error_setg(errp, "Command options are incompatible with "
1723                        "current migration capabilities");
1724             return false;
1725         }
1726         migrate_set_block_enabled(true, &local_err);
1727         if (local_err) {
1728             error_propagate(errp, local_err);
1729             return false;
1730         }
1731         s->must_remove_block_options = true;
1732     }
1733
1734     if (blk_inc) {
1735         migrate_set_block_incremental(s, true);
1736     }
1737
1738     migrate_init(s);
1739
1740     return true;
1741 }
1742
1743 void qmp_migrate(const char *uri, bool has_blk, bool blk,
1744                  bool has_inc, bool inc, bool has_detach, bool detach,
1745                  bool has_resume, bool resume, Error **errp)
1746 {
1747     Error *local_err = NULL;
1748     MigrationState *s = migrate_get_current();
1749     const char *p;
1750
1751     if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
1752                          has_resume && resume, errp)) {
1753         /* Error detected, put into errp */
1754         return;
1755     }
1756
1757     if (strstart(uri, "tcp:", &p)) {
1758         tcp_start_outgoing_migration(s, p, &local_err);
1759 #ifdef CONFIG_RDMA
1760     } else if (strstart(uri, "rdma:", &p)) {
1761         rdma_start_outgoing_migration(s, p, &local_err);
1762 #endif
1763     } else if (strstart(uri, "exec:", &p)) {
1764         exec_start_outgoing_migration(s, p, &local_err);
1765     } else if (strstart(uri, "unix:", &p)) {
1766         unix_start_outgoing_migration(s, p, &local_err);
1767     } else if (strstart(uri, "fd:", &p)) {
1768         fd_start_outgoing_migration(s, p, &local_err);
1769     } else {
1770         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1771                    "a valid migration protocol");
1772         migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1773                           MIGRATION_STATUS_FAILED);
1774         block_cleanup_parameters(s);
1775         return;
1776     }
1777
1778     if (local_err) {
1779         migrate_fd_error(s, local_err);
1780         error_propagate(errp, local_err);
1781         return;
1782     }
1783 }
1784
1785 void qmp_migrate_cancel(Error **errp)
1786 {
1787     migrate_fd_cancel(migrate_get_current());
1788 }
1789
1790 void qmp_migrate_continue(MigrationStatus state, Error **errp)
1791 {
1792     MigrationState *s = migrate_get_current();
1793     if (s->state != state) {
1794         error_setg(errp,  "Migration not in expected state: %s",
1795                    MigrationStatus_str(s->state));
1796         return;
1797     }
1798     qemu_sem_post(&s->pause_sem);
1799 }
1800
1801 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1802 {
1803     MigrateSetParameters p = {
1804         .has_xbzrle_cache_size = true,
1805         .xbzrle_cache_size = value,
1806     };
1807
1808     qmp_migrate_set_parameters(&p, errp);
1809 }
1810
1811 int64_t qmp_query_migrate_cache_size(Error **errp)
1812 {
1813     return migrate_xbzrle_cache_size();
1814 }
1815
1816 void qmp_migrate_set_speed(int64_t value, Error **errp)
1817 {
1818     MigrateSetParameters p = {
1819         .has_max_bandwidth = true,
1820         .max_bandwidth = value,
1821     };
1822
1823     qmp_migrate_set_parameters(&p, errp);
1824 }
1825
1826 void qmp_migrate_set_downtime(double value, Error **errp)
1827 {
1828     if (value < 0 || value > MAX_MIGRATE_DOWNTIME_SECONDS) {
1829         error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1830                          "the range of 0 to %d seconds",
1831                          MAX_MIGRATE_DOWNTIME_SECONDS);
1832         return;
1833     }
1834
1835     value *= 1000; /* Convert to milliseconds */
1836     value = MAX(0, MIN(INT64_MAX, value));
1837
1838     MigrateSetParameters p = {
1839         .has_downtime_limit = true,
1840         .downtime_limit = value,
1841     };
1842
1843     qmp_migrate_set_parameters(&p, errp);
1844 }
1845
1846 bool migrate_release_ram(void)
1847 {
1848     MigrationState *s;
1849
1850     s = migrate_get_current();
1851
1852     return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
1853 }
1854
1855 bool migrate_postcopy_ram(void)
1856 {
1857     MigrationState *s;
1858
1859     s = migrate_get_current();
1860
1861     return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
1862 }
1863
1864 bool migrate_postcopy(void)
1865 {
1866     return migrate_postcopy_ram() || migrate_dirty_bitmaps();
1867 }
1868
1869 bool migrate_auto_converge(void)
1870 {
1871     MigrationState *s;
1872
1873     s = migrate_get_current();
1874
1875     return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1876 }
1877
1878 bool migrate_zero_blocks(void)
1879 {
1880     MigrationState *s;
1881
1882     s = migrate_get_current();
1883
1884     return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1885 }
1886
1887 bool migrate_postcopy_blocktime(void)
1888 {
1889     MigrationState *s;
1890
1891     s = migrate_get_current();
1892
1893     return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME];
1894 }
1895
1896 bool migrate_use_compression(void)
1897 {
1898     MigrationState *s;
1899
1900     s = migrate_get_current();
1901
1902     return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
1903 }
1904
1905 int migrate_compress_level(void)
1906 {
1907     MigrationState *s;
1908
1909     s = migrate_get_current();
1910
1911     return s->parameters.compress_level;
1912 }
1913
1914 int migrate_compress_threads(void)
1915 {
1916     MigrationState *s;
1917
1918     s = migrate_get_current();
1919
1920     return s->parameters.compress_threads;
1921 }
1922
1923 int migrate_compress_wait_thread(void)
1924 {
1925     MigrationState *s;
1926
1927     s = migrate_get_current();
1928
1929     return s->parameters.compress_wait_thread;
1930 }
1931
1932 int migrate_decompress_threads(void)
1933 {
1934     MigrationState *s;
1935
1936     s = migrate_get_current();
1937
1938     return s->parameters.decompress_threads;
1939 }
1940
1941 bool migrate_dirty_bitmaps(void)
1942 {
1943     MigrationState *s;
1944
1945     s = migrate_get_current();
1946
1947     return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS];
1948 }
1949
1950 bool migrate_use_events(void)
1951 {
1952     MigrationState *s;
1953
1954     s = migrate_get_current();
1955
1956     return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1957 }
1958
1959 bool migrate_use_multifd(void)
1960 {
1961     MigrationState *s;
1962
1963     s = migrate_get_current();
1964
1965     return s->enabled_capabilities[MIGRATION_CAPABILITY_X_MULTIFD];
1966 }
1967
1968 bool migrate_pause_before_switchover(void)
1969 {
1970     MigrationState *s;
1971
1972     s = migrate_get_current();
1973
1974     return s->enabled_capabilities[
1975         MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
1976 }
1977
1978 int migrate_multifd_channels(void)
1979 {
1980     MigrationState *s;
1981
1982     s = migrate_get_current();
1983
1984     return s->parameters.x_multifd_channels;
1985 }
1986
1987 int migrate_multifd_page_count(void)
1988 {
1989     MigrationState *s;
1990
1991     s = migrate_get_current();
1992
1993     return s->parameters.x_multifd_page_count;
1994 }
1995
1996 int migrate_use_xbzrle(void)
1997 {
1998     MigrationState *s;
1999
2000     s = migrate_get_current();
2001
2002     return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
2003 }
2004
2005 int64_t migrate_xbzrle_cache_size(void)
2006 {
2007     MigrationState *s;
2008
2009     s = migrate_get_current();
2010
2011     return s->parameters.xbzrle_cache_size;
2012 }
2013
2014 static int64_t migrate_max_postcopy_bandwidth(void)
2015 {
2016     MigrationState *s;
2017
2018     s = migrate_get_current();
2019
2020     return s->parameters.max_postcopy_bandwidth;
2021 }
2022
2023 bool migrate_use_block(void)
2024 {
2025     MigrationState *s;
2026
2027     s = migrate_get_current();
2028
2029     return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
2030 }
2031
2032 bool migrate_use_return_path(void)
2033 {
2034     MigrationState *s;
2035
2036     s = migrate_get_current();
2037
2038     return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
2039 }
2040
2041 bool migrate_use_block_incremental(void)
2042 {
2043     MigrationState *s;
2044
2045     s = migrate_get_current();
2046
2047     return s->parameters.block_incremental;
2048 }
2049
2050 /* migration thread support */
2051 /*
2052  * Something bad happened to the RP stream, mark an error
2053  * The caller shall print or trace something to indicate why
2054  */
2055 static void mark_source_rp_bad(MigrationState *s)
2056 {
2057     s->rp_state.error = true;
2058 }
2059
2060 static struct rp_cmd_args {
2061     ssize_t     len; /* -1 = variable */
2062     const char *name;
2063 } rp_cmd_args[] = {
2064     [MIG_RP_MSG_INVALID]        = { .len = -1, .name = "INVALID" },
2065     [MIG_RP_MSG_SHUT]           = { .len =  4, .name = "SHUT" },
2066     [MIG_RP_MSG_PONG]           = { .len =  4, .name = "PONG" },
2067     [MIG_RP_MSG_REQ_PAGES]      = { .len = 12, .name = "REQ_PAGES" },
2068     [MIG_RP_MSG_REQ_PAGES_ID]   = { .len = -1, .name = "REQ_PAGES_ID" },
2069     [MIG_RP_MSG_RECV_BITMAP]    = { .len = -1, .name = "RECV_BITMAP" },
2070     [MIG_RP_MSG_RESUME_ACK]     = { .len =  4, .name = "RESUME_ACK" },
2071     [MIG_RP_MSG_MAX]            = { .len = -1, .name = "MAX" },
2072 };
2073
2074 /*
2075  * Process a request for pages received on the return path,
2076  * We're allowed to send more than requested (e.g. to round to our page size)
2077  * and we don't need to send pages that have already been sent.
2078  */
2079 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
2080                                        ram_addr_t start, size_t len)
2081 {
2082     long our_host_ps = getpagesize();
2083
2084     trace_migrate_handle_rp_req_pages(rbname, start, len);
2085
2086     /*
2087      * Since we currently insist on matching page sizes, just sanity check
2088      * we're being asked for whole host pages.
2089      */
2090     if (start & (our_host_ps-1) ||
2091        (len & (our_host_ps-1))) {
2092         error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
2093                      " len: %zd", __func__, start, len);
2094         mark_source_rp_bad(ms);
2095         return;
2096     }
2097
2098     if (ram_save_queue_pages(rbname, start, len)) {
2099         mark_source_rp_bad(ms);
2100     }
2101 }
2102
2103 /* Return true to retry, false to quit */
2104 static bool postcopy_pause_return_path_thread(MigrationState *s)
2105 {
2106     trace_postcopy_pause_return_path();
2107
2108     qemu_sem_wait(&s->postcopy_pause_rp_sem);
2109
2110     trace_postcopy_pause_return_path_continued();
2111
2112     return true;
2113 }
2114
2115 static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
2116 {
2117     RAMBlock *block = qemu_ram_block_by_name(block_name);
2118
2119     if (!block) {
2120         error_report("%s: invalid block name '%s'", __func__, block_name);
2121         return -EINVAL;
2122     }
2123
2124     /* Fetch the received bitmap and refresh the dirty bitmap */
2125     return ram_dirty_bitmap_reload(s, block);
2126 }
2127
2128 static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
2129 {
2130     trace_source_return_path_thread_resume_ack(value);
2131
2132     if (value != MIGRATION_RESUME_ACK_VALUE) {
2133         error_report("%s: illegal resume_ack value %"PRIu32,
2134                      __func__, value);
2135         return -1;
2136     }
2137
2138     /* Now both sides are active. */
2139     migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2140                       MIGRATION_STATUS_POSTCOPY_ACTIVE);
2141
2142     /* Notify send thread that time to continue send pages */
2143     qemu_sem_post(&s->rp_state.rp_sem);
2144
2145     return 0;
2146 }
2147
2148 /*
2149  * Handles messages sent on the return path towards the source VM
2150  *
2151  */
2152 static void *source_return_path_thread(void *opaque)
2153 {
2154     MigrationState *ms = opaque;
2155     QEMUFile *rp = ms->rp_state.from_dst_file;
2156     uint16_t header_len, header_type;
2157     uint8_t buf[512];
2158     uint32_t tmp32, sibling_error;
2159     ram_addr_t start = 0; /* =0 to silence warning */
2160     size_t  len = 0, expected_len;
2161     int res;
2162
2163     trace_source_return_path_thread_entry();
2164     rcu_register_thread();
2165
2166 retry:
2167     while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
2168            migration_is_setup_or_active(ms->state)) {
2169         trace_source_return_path_thread_loop_top();
2170         header_type = qemu_get_be16(rp);
2171         header_len = qemu_get_be16(rp);
2172
2173         if (qemu_file_get_error(rp)) {
2174             mark_source_rp_bad(ms);
2175             goto out;
2176         }
2177
2178         if (header_type >= MIG_RP_MSG_MAX ||
2179             header_type == MIG_RP_MSG_INVALID) {
2180             error_report("RP: Received invalid message 0x%04x length 0x%04x",
2181                     header_type, header_len);
2182             mark_source_rp_bad(ms);
2183             goto out;
2184         }
2185
2186         if ((rp_cmd_args[header_type].len != -1 &&
2187             header_len != rp_cmd_args[header_type].len) ||
2188             header_len > sizeof(buf)) {
2189             error_report("RP: Received '%s' message (0x%04x) with"
2190                     "incorrect length %d expecting %zu",
2191                     rp_cmd_args[header_type].name, header_type, header_len,
2192                     (size_t)rp_cmd_args[header_type].len);
2193             mark_source_rp_bad(ms);
2194             goto out;
2195         }
2196
2197         /* We know we've got a valid header by this point */
2198         res = qemu_get_buffer(rp, buf, header_len);
2199         if (res != header_len) {
2200             error_report("RP: Failed reading data for message 0x%04x"
2201                          " read %d expected %d",
2202                          header_type, res, header_len);
2203             mark_source_rp_bad(ms);
2204             goto out;
2205         }
2206
2207         /* OK, we have the message and the data */
2208         switch (header_type) {
2209         case MIG_RP_MSG_SHUT:
2210             sibling_error = ldl_be_p(buf);
2211             trace_source_return_path_thread_shut(sibling_error);
2212             if (sibling_error) {
2213                 error_report("RP: Sibling indicated error %d", sibling_error);
2214                 mark_source_rp_bad(ms);
2215             }
2216             /*
2217              * We'll let the main thread deal with closing the RP
2218              * we could do a shutdown(2) on it, but we're the only user
2219              * anyway, so there's nothing gained.
2220              */
2221             goto out;
2222
2223         case MIG_RP_MSG_PONG:
2224             tmp32 = ldl_be_p(buf);
2225             trace_source_return_path_thread_pong(tmp32);
2226             break;
2227
2228         case MIG_RP_MSG_REQ_PAGES:
2229             start = ldq_be_p(buf);
2230             len = ldl_be_p(buf + 8);
2231             migrate_handle_rp_req_pages(ms, NULL, start, len);
2232             break;
2233
2234         case MIG_RP_MSG_REQ_PAGES_ID:
2235             expected_len = 12 + 1; /* header + termination */
2236
2237             if (header_len >= expected_len) {
2238                 start = ldq_be_p(buf);
2239                 len = ldl_be_p(buf + 8);
2240                 /* Now we expect an idstr */
2241                 tmp32 = buf[12]; /* Length of the following idstr */
2242                 buf[13 + tmp32] = '\0';
2243                 expected_len += tmp32;
2244             }
2245             if (header_len != expected_len) {
2246                 error_report("RP: Req_Page_id with length %d expecting %zd",
2247                         header_len, expected_len);
2248                 mark_source_rp_bad(ms);
2249                 goto out;
2250             }
2251             migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
2252             break;
2253
2254         case MIG_RP_MSG_RECV_BITMAP:
2255             if (header_len < 1) {
2256                 error_report("%s: missing block name", __func__);
2257                 mark_source_rp_bad(ms);
2258                 goto out;
2259             }
2260             /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2261             buf[buf[0] + 1] = '\0';
2262             if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
2263                 mark_source_rp_bad(ms);
2264                 goto out;
2265             }
2266             break;
2267
2268         case MIG_RP_MSG_RESUME_ACK:
2269             tmp32 = ldl_be_p(buf);
2270             if (migrate_handle_rp_resume_ack(ms, tmp32)) {
2271                 mark_source_rp_bad(ms);
2272                 goto out;
2273             }
2274             break;
2275
2276         default:
2277             break;
2278         }
2279     }
2280
2281 out:
2282     res = qemu_file_get_error(rp);
2283     if (res) {
2284         if (res == -EIO) {
2285             /*
2286              * Maybe there is something we can do: it looks like a
2287              * network down issue, and we pause for a recovery.
2288              */
2289             if (postcopy_pause_return_path_thread(ms)) {
2290                 /* Reload rp, reset the rest */
2291                 if (rp != ms->rp_state.from_dst_file) {
2292                     qemu_fclose(rp);
2293                     rp = ms->rp_state.from_dst_file;
2294                 }
2295                 ms->rp_state.error = false;
2296                 goto retry;
2297             }
2298         }
2299
2300         trace_source_return_path_thread_bad_end();
2301         mark_source_rp_bad(ms);
2302     }
2303
2304     trace_source_return_path_thread_end();
2305     ms->rp_state.from_dst_file = NULL;
2306     qemu_fclose(rp);
2307     rcu_unregister_thread();
2308     return NULL;
2309 }
2310
2311 static int open_return_path_on_source(MigrationState *ms,
2312                                       bool create_thread)
2313 {
2314
2315     ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
2316     if (!ms->rp_state.from_dst_file) {
2317         return -1;
2318     }
2319
2320     trace_open_return_path_on_source();
2321
2322     if (!create_thread) {
2323         /* We're done */
2324         return 0;
2325     }
2326
2327     qemu_thread_create(&ms->rp_state.rp_thread, "return path",
2328                        source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
2329
2330     trace_open_return_path_on_source_continue();
2331
2332     return 0;
2333 }
2334
2335 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
2336 static int await_return_path_close_on_source(MigrationState *ms)
2337 {
2338     /*
2339      * If this is a normal exit then the destination will send a SHUT and the
2340      * rp_thread will exit, however if there's an error we need to cause
2341      * it to exit.
2342      */
2343     if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
2344         /*
2345          * shutdown(2), if we have it, will cause it to unblock if it's stuck
2346          * waiting for the destination.
2347          */
2348         qemu_file_shutdown(ms->rp_state.from_dst_file);
2349         mark_source_rp_bad(ms);
2350     }
2351     trace_await_return_path_close_on_source_joining();
2352     qemu_thread_join(&ms->rp_state.rp_thread);
2353     trace_await_return_path_close_on_source_close();
2354     return ms->rp_state.error;
2355 }
2356
2357 /*
2358  * Switch from normal iteration to postcopy
2359  * Returns non-0 on error
2360  */
2361 static int postcopy_start(MigrationState *ms)
2362 {
2363     int ret;
2364     QIOChannelBuffer *bioc;
2365     QEMUFile *fb;
2366     int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2367     int64_t bandwidth = migrate_max_postcopy_bandwidth();
2368     bool restart_block = false;
2369     int cur_state = MIGRATION_STATUS_ACTIVE;
2370     if (!migrate_pause_before_switchover()) {
2371         migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
2372                           MIGRATION_STATUS_POSTCOPY_ACTIVE);
2373     }
2374
2375     trace_postcopy_start();
2376     qemu_mutex_lock_iothread();
2377     trace_postcopy_start_set_run();
2378
2379     qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
2380     global_state_store();
2381     ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2382     if (ret < 0) {
2383         goto fail;
2384     }
2385
2386     ret = migration_maybe_pause(ms, &cur_state,
2387                                 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2388     if (ret < 0) {
2389         goto fail;
2390     }
2391
2392     ret = bdrv_inactivate_all();
2393     if (ret < 0) {
2394         goto fail;
2395     }
2396     restart_block = true;
2397
2398     /*
2399      * Cause any non-postcopiable, but iterative devices to
2400      * send out their final data.
2401      */
2402     qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
2403
2404     /*
2405      * in Finish migrate and with the io-lock held everything should
2406      * be quiet, but we've potentially still got dirty pages and we
2407      * need to tell the destination to throw any pages it's already received
2408      * that are dirty
2409      */
2410     if (migrate_postcopy_ram()) {
2411         if (ram_postcopy_send_discard_bitmap(ms)) {
2412             error_report("postcopy send discard bitmap failed");
2413             goto fail;
2414         }
2415     }
2416
2417     /*
2418      * send rest of state - note things that are doing postcopy
2419      * will notice we're in POSTCOPY_ACTIVE and not actually
2420      * wrap their state up here
2421      */
2422     /* 0 max-postcopy-bandwidth means unlimited */
2423     if (!bandwidth) {
2424         qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
2425     } else {
2426         qemu_file_set_rate_limit(ms->to_dst_file, bandwidth / XFER_LIMIT_RATIO);
2427     }
2428     if (migrate_postcopy_ram()) {
2429         /* Ping just for debugging, helps line traces up */
2430         qemu_savevm_send_ping(ms->to_dst_file, 2);
2431     }
2432
2433     /*
2434      * While loading the device state we may trigger page transfer
2435      * requests and the fd must be free to process those, and thus
2436      * the destination must read the whole device state off the fd before
2437      * it starts processing it.  Unfortunately the ad-hoc migration format
2438      * doesn't allow the destination to know the size to read without fully
2439      * parsing it through each devices load-state code (especially the open
2440      * coded devices that use get/put).
2441      * So we wrap the device state up in a package with a length at the start;
2442      * to do this we use a qemu_buf to hold the whole of the device state.
2443      */
2444     bioc = qio_channel_buffer_new(4096);
2445     qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
2446     fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
2447     object_unref(OBJECT(bioc));
2448
2449     /*
2450      * Make sure the receiver can get incoming pages before we send the rest
2451      * of the state
2452      */
2453     qemu_savevm_send_postcopy_listen(fb);
2454
2455     qemu_savevm_state_complete_precopy(fb, false, false);
2456     if (migrate_postcopy_ram()) {
2457         qemu_savevm_send_ping(fb, 3);
2458     }
2459
2460     qemu_savevm_send_postcopy_run(fb);
2461
2462     /* <><> end of stuff going into the package */
2463
2464     /* Last point of recovery; as soon as we send the package the destination
2465      * can open devices and potentially start running.
2466      * Lets just check again we've not got any errors.
2467      */
2468     ret = qemu_file_get_error(ms->to_dst_file);
2469     if (ret) {
2470         error_report("postcopy_start: Migration stream errored (pre package)");
2471         goto fail_closefb;
2472     }
2473
2474     restart_block = false;
2475
2476     /* Now send that blob */
2477     if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
2478         goto fail_closefb;
2479     }
2480     qemu_fclose(fb);
2481
2482     /* Send a notify to give a chance for anything that needs to happen
2483      * at the transition to postcopy and after the device state; in particular
2484      * spice needs to trigger a transition now
2485      */
2486     ms->postcopy_after_devices = true;
2487     notifier_list_notify(&migration_state_notifiers, ms);
2488
2489     ms->downtime =  qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
2490
2491     qemu_mutex_unlock_iothread();
2492
2493     if (migrate_postcopy_ram()) {
2494         /*
2495          * Although this ping is just for debug, it could potentially be
2496          * used for getting a better measurement of downtime at the source.
2497          */
2498         qemu_savevm_send_ping(ms->to_dst_file, 4);
2499     }
2500
2501     if (migrate_release_ram()) {
2502         ram_postcopy_migrated_memory_release(ms);
2503     }
2504
2505     ret = qemu_file_get_error(ms->to_dst_file);
2506     if (ret) {
2507         error_report("postcopy_start: Migration stream errored");
2508         migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2509                               MIGRATION_STATUS_FAILED);
2510     }
2511
2512     return ret;
2513
2514 fail_closefb:
2515     qemu_fclose(fb);
2516 fail:
2517     migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2518                           MIGRATION_STATUS_FAILED);
2519     if (restart_block) {
2520         /* A failure happened early enough that we know the destination hasn't
2521          * accessed block devices, so we're safe to recover.
2522          */
2523         Error *local_err = NULL;
2524
2525         bdrv_invalidate_cache_all(&local_err);
2526         if (local_err) {
2527             error_report_err(local_err);
2528         }
2529     }
2530     qemu_mutex_unlock_iothread();
2531     return -1;
2532 }
2533
2534 /**
2535  * migration_maybe_pause: Pause if required to by
2536  * migrate_pause_before_switchover called with the iothread locked
2537  * Returns: 0 on success
2538  */
2539 static int migration_maybe_pause(MigrationState *s,
2540                                  int *current_active_state,
2541                                  int new_state)
2542 {
2543     if (!migrate_pause_before_switchover()) {
2544         return 0;
2545     }
2546
2547     /* Since leaving this state is not atomic with posting the semaphore
2548      * it's possible that someone could have issued multiple migrate_continue
2549      * and the semaphore is incorrectly positive at this point;
2550      * the docs say it's undefined to reinit a semaphore that's already
2551      * init'd, so use timedwait to eat up any existing posts.
2552      */
2553     while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2554         /* This block intentionally left blank */
2555     }
2556
2557     qemu_mutex_unlock_iothread();
2558     migrate_set_state(&s->state, *current_active_state,
2559                       MIGRATION_STATUS_PRE_SWITCHOVER);
2560     qemu_sem_wait(&s->pause_sem);
2561     migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
2562                       new_state);
2563     *current_active_state = new_state;
2564     qemu_mutex_lock_iothread();
2565
2566     return s->state == new_state ? 0 : -EINVAL;
2567 }
2568
2569 /**
2570  * migration_completion: Used by migration_thread when there's not much left.
2571  *   The caller 'breaks' the loop when this returns.
2572  *
2573  * @s: Current migration state
2574  */
2575 static void migration_completion(MigrationState *s)
2576 {
2577     int ret;
2578     int current_active_state = s->state;
2579
2580     if (s->state == MIGRATION_STATUS_ACTIVE) {
2581         qemu_mutex_lock_iothread();
2582         s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2583         qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
2584         s->vm_was_running = runstate_is_running();
2585         ret = global_state_store();
2586
2587         if (!ret) {
2588             bool inactivate = !migrate_colo_enabled();
2589             ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2590             if (ret >= 0) {
2591                 ret = migration_maybe_pause(s, &current_active_state,
2592                                             MIGRATION_STATUS_DEVICE);
2593             }
2594             if (ret >= 0) {
2595                 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
2596                 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
2597                                                          inactivate);
2598             }
2599             if (inactivate && ret >= 0) {
2600                 s->block_inactive = true;
2601             }
2602         }
2603         qemu_mutex_unlock_iothread();
2604
2605         if (ret < 0) {
2606             goto fail;
2607         }
2608     } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2609         trace_migration_completion_postcopy_end();
2610
2611         qemu_savevm_state_complete_postcopy(s->to_dst_file);
2612         trace_migration_completion_postcopy_end_after_complete();
2613     }
2614
2615     /*
2616      * If rp was opened we must clean up the thread before
2617      * cleaning everything else up (since if there are no failures
2618      * it will wait for the destination to send it's status in
2619      * a SHUT command).
2620      */
2621     if (s->rp_state.from_dst_file) {
2622         int rp_error;
2623         trace_migration_return_path_end_before();
2624         rp_error = await_return_path_close_on_source(s);
2625         trace_migration_return_path_end_after(rp_error);
2626         if (rp_error) {
2627             goto fail_invalidate;
2628         }
2629     }
2630
2631     if (qemu_file_get_error(s->to_dst_file)) {
2632         trace_migration_completion_file_err();
2633         goto fail_invalidate;
2634     }
2635
2636     if (!migrate_colo_enabled()) {
2637         migrate_set_state(&s->state, current_active_state,
2638                           MIGRATION_STATUS_COMPLETED);
2639     }
2640
2641     return;
2642
2643 fail_invalidate:
2644     /* If not doing postcopy, vm_start() will be called: let's regain
2645      * control on images.
2646      */
2647     if (s->state == MIGRATION_STATUS_ACTIVE ||
2648         s->state == MIGRATION_STATUS_DEVICE) {
2649         Error *local_err = NULL;
2650
2651         qemu_mutex_lock_iothread();
2652         bdrv_invalidate_cache_all(&local_err);
2653         if (local_err) {
2654             error_report_err(local_err);
2655         } else {
2656             s->block_inactive = false;
2657         }
2658         qemu_mutex_unlock_iothread();
2659     }
2660
2661 fail:
2662     migrate_set_state(&s->state, current_active_state,
2663                       MIGRATION_STATUS_FAILED);
2664 }
2665
2666 bool migrate_colo_enabled(void)
2667 {
2668     MigrationState *s = migrate_get_current();
2669     return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
2670 }
2671
2672 typedef enum MigThrError {
2673     /* No error detected */
2674     MIG_THR_ERR_NONE = 0,
2675     /* Detected error, but resumed successfully */
2676     MIG_THR_ERR_RECOVERED = 1,
2677     /* Detected fatal error, need to exit */
2678     MIG_THR_ERR_FATAL = 2,
2679 } MigThrError;
2680
2681 static int postcopy_resume_handshake(MigrationState *s)
2682 {
2683     qemu_savevm_send_postcopy_resume(s->to_dst_file);
2684
2685     while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2686         qemu_sem_wait(&s->rp_state.rp_sem);
2687     }
2688
2689     if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2690         return 0;
2691     }
2692
2693     return -1;
2694 }
2695
2696 /* Return zero if success, or <0 for error */
2697 static int postcopy_do_resume(MigrationState *s)
2698 {
2699     int ret;
2700
2701     /*
2702      * Call all the resume_prepare() hooks, so that modules can be
2703      * ready for the migration resume.
2704      */
2705     ret = qemu_savevm_state_resume_prepare(s);
2706     if (ret) {
2707         error_report("%s: resume_prepare() failure detected: %d",
2708                      __func__, ret);
2709         return ret;
2710     }
2711
2712     /*
2713      * Last handshake with destination on the resume (destination will
2714      * switch to postcopy-active afterwards)
2715      */
2716     ret = postcopy_resume_handshake(s);
2717     if (ret) {
2718         error_report("%s: handshake failed: %d", __func__, ret);
2719         return ret;
2720     }
2721
2722     return 0;
2723 }
2724
2725 /*
2726  * We don't return until we are in a safe state to continue current
2727  * postcopy migration.  Returns MIG_THR_ERR_RECOVERED if recovered, or
2728  * MIG_THR_ERR_FATAL if unrecovery failure happened.
2729  */
2730 static MigThrError postcopy_pause(MigrationState *s)
2731 {
2732     assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2733
2734     while (true) {
2735         QEMUFile *file;
2736
2737         migrate_set_state(&s->state, s->state,
2738                           MIGRATION_STATUS_POSTCOPY_PAUSED);
2739
2740         /* Current channel is possibly broken. Release it. */
2741         assert(s->to_dst_file);
2742         qemu_mutex_lock(&s->qemu_file_lock);
2743         file = s->to_dst_file;
2744         s->to_dst_file = NULL;
2745         qemu_mutex_unlock(&s->qemu_file_lock);
2746
2747         qemu_file_shutdown(file);
2748         qemu_fclose(file);
2749
2750         error_report("Detected IO failure for postcopy. "
2751                      "Migration paused.");
2752
2753         /*
2754          * We wait until things fixed up. Then someone will setup the
2755          * status back for us.
2756          */
2757         while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2758             qemu_sem_wait(&s->postcopy_pause_sem);
2759         }
2760
2761         if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2762             /* Woken up by a recover procedure. Give it a shot */
2763
2764             /*
2765              * Firstly, let's wake up the return path now, with a new
2766              * return path channel.
2767              */
2768             qemu_sem_post(&s->postcopy_pause_rp_sem);
2769
2770             /* Do the resume logic */
2771             if (postcopy_do_resume(s) == 0) {
2772                 /* Let's continue! */
2773                 trace_postcopy_pause_continued();
2774                 return MIG_THR_ERR_RECOVERED;
2775             } else {
2776                 /*
2777                  * Something wrong happened during the recovery, let's
2778                  * pause again. Pause is always better than throwing
2779                  * data away.
2780                  */
2781                 continue;
2782             }
2783         } else {
2784             /* This is not right... Time to quit. */
2785             return MIG_THR_ERR_FATAL;
2786         }
2787     }
2788 }
2789
2790 static MigThrError migration_detect_error(MigrationState *s)
2791 {
2792     int ret;
2793
2794     /* Try to detect any file errors */
2795     ret = qemu_file_get_error(s->to_dst_file);
2796
2797     if (!ret) {
2798         /* Everything is fine */
2799         return MIG_THR_ERR_NONE;
2800     }
2801
2802     if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret == -EIO) {
2803         /*
2804          * For postcopy, we allow the network to be down for a
2805          * while. After that, it can be continued by a
2806          * recovery phase.
2807          */
2808         return postcopy_pause(s);
2809     } else {
2810         /*
2811          * For precopy (or postcopy with error outside IO), we fail
2812          * with no time.
2813          */
2814         migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
2815         trace_migration_thread_file_err();
2816
2817         /* Time to stop the migration, now. */
2818         return MIG_THR_ERR_FATAL;
2819     }
2820 }
2821
2822 /* How many bytes have we transferred since the beggining of the migration */
2823 static uint64_t migration_total_bytes(MigrationState *s)
2824 {
2825     return qemu_ftell(s->to_dst_file) + ram_counters.multifd_bytes;
2826 }
2827
2828 static void migration_calculate_complete(MigrationState *s)
2829 {
2830     uint64_t bytes = migration_total_bytes(s);
2831     int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2832     int64_t transfer_time;
2833
2834     s->total_time = end_time - s->start_time;
2835     if (!s->downtime) {
2836         /*
2837          * It's still not set, so we are precopy migration.  For
2838          * postcopy, downtime is calculated during postcopy_start().
2839          */
2840         s->downtime = end_time - s->downtime_start;
2841     }
2842
2843     transfer_time = s->total_time - s->setup_time;
2844     if (transfer_time) {
2845         s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
2846     }
2847 }
2848
2849 static void migration_update_counters(MigrationState *s,
2850                                       int64_t current_time)
2851 {
2852     uint64_t transferred, time_spent;
2853     uint64_t current_bytes; /* bytes transferred since the beginning */
2854     double bandwidth;
2855
2856     if (current_time < s->iteration_start_time + BUFFER_DELAY) {
2857         return;
2858     }
2859
2860     current_bytes = migration_total_bytes(s);
2861     transferred = current_bytes - s->iteration_initial_bytes;
2862     time_spent = current_time - s->iteration_start_time;
2863     bandwidth = (double)transferred / time_spent;
2864     s->threshold_size = bandwidth * s->parameters.downtime_limit;
2865
2866     s->mbps = (((double) transferred * 8.0) /
2867                ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
2868
2869     /*
2870      * if we haven't sent anything, we don't want to
2871      * recalculate. 10000 is a small enough number for our purposes
2872      */
2873     if (ram_counters.dirty_pages_rate && transferred > 10000) {
2874         s->expected_downtime = ram_counters.remaining / bandwidth;
2875     }
2876
2877     qemu_file_reset_rate_limit(s->to_dst_file);
2878
2879     s->iteration_start_time = current_time;
2880     s->iteration_initial_bytes = current_bytes;
2881
2882     trace_migrate_transferred(transferred, time_spent,
2883                               bandwidth, s->threshold_size);
2884 }
2885
2886 /* Migration thread iteration status */
2887 typedef enum {
2888     MIG_ITERATE_RESUME,         /* Resume current iteration */
2889     MIG_ITERATE_SKIP,           /* Skip current iteration */
2890     MIG_ITERATE_BREAK,          /* Break the loop */
2891 } MigIterateState;
2892
2893 /*
2894  * Return true if continue to the next iteration directly, false
2895  * otherwise.
2896  */
2897 static MigIterateState migration_iteration_run(MigrationState *s)
2898 {
2899     uint64_t pending_size, pend_pre, pend_compat, pend_post;
2900     bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
2901
2902     qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
2903                               &pend_compat, &pend_post);
2904     pending_size = pend_pre + pend_compat + pend_post;
2905
2906     trace_migrate_pending(pending_size, s->threshold_size,
2907                           pend_pre, pend_compat, pend_post);
2908
2909     if (pending_size && pending_size >= s->threshold_size) {
2910         /* Still a significant amount to transfer */
2911         if (migrate_postcopy() && !in_postcopy &&
2912             pend_pre <= s->threshold_size &&
2913             atomic_read(&s->start_postcopy)) {
2914             if (postcopy_start(s)) {
2915                 error_report("%s: postcopy failed to start", __func__);
2916             }
2917             return MIG_ITERATE_SKIP;
2918         }
2919         /* Just another iteration step */
2920         qemu_savevm_state_iterate(s->to_dst_file,
2921             s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2922     } else {
2923         trace_migration_thread_low_pending(pending_size);
2924         migration_completion(s);
2925         return MIG_ITERATE_BREAK;
2926     }
2927
2928     return MIG_ITERATE_RESUME;
2929 }
2930
2931 static void migration_iteration_finish(MigrationState *s)
2932 {
2933     /* If we enabled cpu throttling for auto-converge, turn it off. */
2934     cpu_throttle_stop();
2935
2936     qemu_mutex_lock_iothread();
2937     switch (s->state) {
2938     case MIGRATION_STATUS_COMPLETED:
2939         migration_calculate_complete(s);
2940         runstate_set(RUN_STATE_POSTMIGRATE);
2941         break;
2942
2943     case MIGRATION_STATUS_ACTIVE:
2944         /*
2945          * We should really assert here, but since it's during
2946          * migration, let's try to reduce the usage of assertions.
2947          */
2948         if (!migrate_colo_enabled()) {
2949             error_report("%s: critical error: calling COLO code without "
2950                          "COLO enabled", __func__);
2951         }
2952         migrate_start_colo_process(s);
2953         /*
2954          * Fixme: we will run VM in COLO no matter its old running state.
2955          * After exited COLO, we will keep running.
2956          */
2957         s->vm_was_running = true;
2958         /* Fallthrough */
2959     case MIGRATION_STATUS_FAILED:
2960     case MIGRATION_STATUS_CANCELLED:
2961     case MIGRATION_STATUS_CANCELLING:
2962         if (s->vm_was_running) {
2963             vm_start();
2964         } else {
2965             if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
2966                 runstate_set(RUN_STATE_POSTMIGRATE);
2967             }
2968         }
2969         break;
2970
2971     default:
2972         /* Should not reach here, but if so, forgive the VM. */
2973         error_report("%s: Unknown ending state %d", __func__, s->state);
2974         break;
2975     }
2976     qemu_bh_schedule(s->cleanup_bh);
2977     qemu_mutex_unlock_iothread();
2978 }
2979
2980 void migration_make_urgent_request(void)
2981 {
2982     qemu_sem_post(&migrate_get_current()->rate_limit_sem);
2983 }
2984
2985 void migration_consume_urgent_request(void)
2986 {
2987     qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
2988 }
2989
2990 /*
2991  * Master migration thread on the source VM.
2992  * It drives the migration and pumps the data down the outgoing channel.
2993  */
2994 static void *migration_thread(void *opaque)
2995 {
2996     MigrationState *s = opaque;
2997     int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
2998     MigThrError thr_error;
2999     bool urgent = false;
3000
3001     rcu_register_thread();
3002
3003     s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3004
3005     qemu_savevm_state_header(s->to_dst_file);
3006
3007     /*
3008      * If we opened the return path, we need to make sure dst has it
3009      * opened as well.
3010      */
3011     if (s->rp_state.from_dst_file) {
3012         /* Now tell the dest that it should open its end so it can reply */
3013         qemu_savevm_send_open_return_path(s->to_dst_file);
3014
3015         /* And do a ping that will make stuff easier to debug */
3016         qemu_savevm_send_ping(s->to_dst_file, 1);
3017     }
3018
3019     if (migrate_postcopy()) {
3020         /*
3021          * Tell the destination that we *might* want to do postcopy later;
3022          * if the other end can't do postcopy it should fail now, nice and
3023          * early.
3024          */
3025         qemu_savevm_send_postcopy_advise(s->to_dst_file);
3026     }
3027
3028     qemu_savevm_state_setup(s->to_dst_file);
3029
3030     s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3031     migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3032                       MIGRATION_STATUS_ACTIVE);
3033
3034     trace_migration_thread_setup_complete();
3035
3036     while (s->state == MIGRATION_STATUS_ACTIVE ||
3037            s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3038         int64_t current_time;
3039
3040         if (urgent || !qemu_file_rate_limit(s->to_dst_file)) {
3041             MigIterateState iter_state = migration_iteration_run(s);
3042             if (iter_state == MIG_ITERATE_SKIP) {
3043                 continue;
3044             } else if (iter_state == MIG_ITERATE_BREAK) {
3045                 break;
3046             }
3047         }
3048
3049         /*
3050          * Try to detect any kind of failures, and see whether we
3051          * should stop the migration now.
3052          */
3053         thr_error = migration_detect_error(s);
3054         if (thr_error == MIG_THR_ERR_FATAL) {
3055             /* Stop migration */
3056             break;
3057         } else if (thr_error == MIG_THR_ERR_RECOVERED) {
3058             /*
3059              * Just recovered from a e.g. network failure, reset all
3060              * the local variables. This is important to avoid
3061              * breaking transferred_bytes and bandwidth calculation
3062              */
3063             s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3064             s->iteration_initial_bytes = 0;
3065         }
3066
3067         current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3068
3069         migration_update_counters(s, current_time);
3070
3071         urgent = false;
3072         if (qemu_file_rate_limit(s->to_dst_file)) {
3073             /* Wait for a delay to do rate limiting OR
3074              * something urgent to post the semaphore.
3075              */
3076             int ms = s->iteration_start_time + BUFFER_DELAY - current_time;
3077             trace_migration_thread_ratelimit_pre(ms);
3078             if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
3079                 /* We were worken by one or more urgent things but
3080                  * the timedwait will have consumed one of them.
3081                  * The service routine for the urgent wake will dec
3082                  * the semaphore itself for each item it consumes,
3083                  * so add this one we just eat back.
3084                  */
3085                 qemu_sem_post(&s->rate_limit_sem);
3086                 urgent = true;
3087             }
3088             trace_migration_thread_ratelimit_post(urgent);
3089         }
3090     }
3091
3092     trace_migration_thread_after_loop();
3093     migration_iteration_finish(s);
3094     rcu_unregister_thread();
3095     return NULL;
3096 }
3097
3098 void migrate_fd_connect(MigrationState *s, Error *error_in)
3099 {
3100     int64_t rate_limit;
3101     bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
3102
3103     s->expected_downtime = s->parameters.downtime_limit;
3104     s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
3105     if (error_in) {
3106         migrate_fd_error(s, error_in);
3107         migrate_fd_cleanup(s);
3108         return;
3109     }
3110
3111     if (resume) {
3112         /* This is a resumed migration */
3113         rate_limit = INT64_MAX;
3114     } else {
3115         /* This is a fresh new migration */
3116         rate_limit = s->parameters.max_bandwidth / XFER_LIMIT_RATIO;
3117
3118         /* Notify before starting migration thread */
3119         notifier_list_notify(&migration_state_notifiers, s);
3120     }
3121
3122     qemu_file_set_rate_limit(s->to_dst_file, rate_limit);
3123     qemu_file_set_blocking(s->to_dst_file, true);
3124
3125     /*
3126      * Open the return path. For postcopy, it is used exclusively. For
3127      * precopy, only if user specified "return-path" capability would
3128      * QEMU uses the return path.
3129      */
3130     if (migrate_postcopy_ram() || migrate_use_return_path()) {
3131         if (open_return_path_on_source(s, !resume)) {
3132             error_report("Unable to open return-path for postcopy");
3133             migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
3134             migrate_fd_cleanup(s);
3135             return;
3136         }
3137     }
3138
3139     if (resume) {
3140         /* Wakeup the main migration thread to do the recovery */
3141         migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
3142                           MIGRATION_STATUS_POSTCOPY_RECOVER);
3143         qemu_sem_post(&s->postcopy_pause_sem);
3144         return;
3145     }
3146
3147     if (multifd_save_setup() != 0) {
3148         migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3149                           MIGRATION_STATUS_FAILED);
3150         migrate_fd_cleanup(s);
3151         return;
3152     }
3153     qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
3154                        QEMU_THREAD_JOINABLE);
3155     s->migration_thread_running = true;
3156 }
3157
3158 void migration_global_dump(Monitor *mon)
3159 {
3160     MigrationState *ms = migrate_get_current();
3161
3162     monitor_printf(mon, "globals:\n");
3163     monitor_printf(mon, "store-global-state: %s\n",
3164                    ms->store_global_state ? "on" : "off");
3165     monitor_printf(mon, "only-migratable: %s\n",
3166                    ms->only_migratable ? "on" : "off");
3167     monitor_printf(mon, "send-configuration: %s\n",
3168                    ms->send_configuration ? "on" : "off");
3169     monitor_printf(mon, "send-section-footer: %s\n",
3170                    ms->send_section_footer ? "on" : "off");
3171     monitor_printf(mon, "decompress-error-check: %s\n",
3172                    ms->decompress_error_check ? "on" : "off");
3173 }
3174
3175 #define DEFINE_PROP_MIG_CAP(name, x)             \
3176     DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
3177
3178 static Property migration_properties[] = {
3179     DEFINE_PROP_BOOL("store-global-state", MigrationState,
3180                      store_global_state, true),
3181     DEFINE_PROP_BOOL("only-migratable", MigrationState, only_migratable, false),
3182     DEFINE_PROP_BOOL("send-configuration", MigrationState,
3183                      send_configuration, true),
3184     DEFINE_PROP_BOOL("send-section-footer", MigrationState,
3185                      send_section_footer, true),
3186     DEFINE_PROP_BOOL("decompress-error-check", MigrationState,
3187                       decompress_error_check, true),
3188
3189     /* Migration parameters */
3190     DEFINE_PROP_UINT8("x-compress-level", MigrationState,
3191                       parameters.compress_level,
3192                       DEFAULT_MIGRATE_COMPRESS_LEVEL),
3193     DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
3194                       parameters.compress_threads,
3195                       DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
3196     DEFINE_PROP_BOOL("x-compress-wait-thread", MigrationState,
3197                       parameters.compress_wait_thread, true),
3198     DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
3199                       parameters.decompress_threads,
3200                       DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
3201     DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
3202                       parameters.cpu_throttle_initial,
3203                       DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
3204     DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
3205                       parameters.cpu_throttle_increment,
3206                       DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
3207     DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
3208                       parameters.max_bandwidth, MAX_THROTTLE),
3209     DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
3210                       parameters.downtime_limit,
3211                       DEFAULT_MIGRATE_SET_DOWNTIME),
3212     DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
3213                       parameters.x_checkpoint_delay,
3214                       DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
3215     DEFINE_PROP_UINT8("x-multifd-channels", MigrationState,
3216                       parameters.x_multifd_channels,
3217                       DEFAULT_MIGRATE_MULTIFD_CHANNELS),
3218     DEFINE_PROP_UINT32("x-multifd-page-count", MigrationState,
3219                       parameters.x_multifd_page_count,
3220                       DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT),
3221     DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
3222                       parameters.xbzrle_cache_size,
3223                       DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
3224     DEFINE_PROP_SIZE("max-postcopy-bandwidth", MigrationState,
3225                       parameters.max_postcopy_bandwidth,
3226                       DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH),
3227     DEFINE_PROP_UINT8("max-cpu-throttle", MigrationState,
3228                       parameters.max_cpu_throttle,
3229                       DEFAULT_MIGRATE_MAX_CPU_THROTTLE),
3230
3231     /* Migration capabilities */
3232     DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
3233     DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
3234     DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
3235     DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
3236     DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
3237     DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
3238     DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
3239     DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
3240     DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
3241     DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
3242     DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
3243     DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_X_MULTIFD),
3244
3245     DEFINE_PROP_END_OF_LIST(),
3246 };
3247
3248 static void migration_class_init(ObjectClass *klass, void *data)
3249 {
3250     DeviceClass *dc = DEVICE_CLASS(klass);
3251
3252     dc->user_creatable = false;
3253     dc->props = migration_properties;
3254 }
3255
3256 static void migration_instance_finalize(Object *obj)
3257 {
3258     MigrationState *ms = MIGRATION_OBJ(obj);
3259     MigrationParameters *params = &ms->parameters;
3260
3261     qemu_mutex_destroy(&ms->error_mutex);
3262     qemu_mutex_destroy(&ms->qemu_file_lock);
3263     g_free(params->tls_hostname);
3264     g_free(params->tls_creds);
3265     qemu_sem_destroy(&ms->rate_limit_sem);
3266     qemu_sem_destroy(&ms->pause_sem);
3267     qemu_sem_destroy(&ms->postcopy_pause_sem);
3268     qemu_sem_destroy(&ms->postcopy_pause_rp_sem);
3269     qemu_sem_destroy(&ms->rp_state.rp_sem);
3270     error_free(ms->error);
3271 }
3272
3273 static void migration_instance_init(Object *obj)
3274 {
3275     MigrationState *ms = MIGRATION_OBJ(obj);
3276     MigrationParameters *params = &ms->parameters;
3277
3278     ms->state = MIGRATION_STATUS_NONE;
3279     ms->mbps = -1;
3280     qemu_sem_init(&ms->pause_sem, 0);
3281     qemu_mutex_init(&ms->error_mutex);
3282
3283     params->tls_hostname = g_strdup("");
3284     params->tls_creds = g_strdup("");
3285
3286     /* Set has_* up only for parameter checks */
3287     params->has_compress_level = true;
3288     params->has_compress_threads = true;
3289     params->has_decompress_threads = true;
3290     params->has_cpu_throttle_initial = true;
3291     params->has_cpu_throttle_increment = true;
3292     params->has_max_bandwidth = true;
3293     params->has_downtime_limit = true;
3294     params->has_x_checkpoint_delay = true;
3295     params->has_block_incremental = true;
3296     params->has_x_multifd_channels = true;
3297     params->has_x_multifd_page_count = true;
3298     params->has_xbzrle_cache_size = true;
3299     params->has_max_postcopy_bandwidth = true;
3300     params->has_max_cpu_throttle = true;
3301
3302     qemu_sem_init(&ms->postcopy_pause_sem, 0);
3303     qemu_sem_init(&ms->postcopy_pause_rp_sem, 0);
3304     qemu_sem_init(&ms->rp_state.rp_sem, 0);
3305     qemu_sem_init(&ms->rate_limit_sem, 0);
3306     qemu_mutex_init(&ms->qemu_file_lock);
3307 }
3308
3309 /*
3310  * Return true if check pass, false otherwise. Error will be put
3311  * inside errp if provided.
3312  */
3313 static bool migration_object_check(MigrationState *ms, Error **errp)
3314 {
3315     MigrationCapabilityStatusList *head = NULL;
3316     /* Assuming all off */
3317     bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
3318     int i;
3319
3320     if (!migrate_params_check(&ms->parameters, errp)) {
3321         return false;
3322     }
3323
3324     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3325         if (ms->enabled_capabilities[i]) {
3326             head = migrate_cap_add(head, i, true);
3327         }
3328     }
3329
3330     ret = migrate_caps_check(cap_list, head, errp);
3331
3332     /* It works with head == NULL */
3333     qapi_free_MigrationCapabilityStatusList(head);
3334
3335     return ret;
3336 }
3337
3338 static const TypeInfo migration_type = {
3339     .name = TYPE_MIGRATION,
3340     /*
3341      * NOTE: TYPE_MIGRATION is not really a device, as the object is
3342      * not created using qdev_create(), it is not attached to the qdev
3343      * device tree, and it is never realized.
3344      *
3345      * TODO: Make this TYPE_OBJECT once QOM provides something like
3346      * TYPE_DEVICE's "-global" properties.
3347      */
3348     .parent = TYPE_DEVICE,
3349     .class_init = migration_class_init,
3350     .class_size = sizeof(MigrationClass),
3351     .instance_size = sizeof(MigrationState),
3352     .instance_init = migration_instance_init,
3353     .instance_finalize = migration_instance_finalize,
3354 };
3355
3356 static void register_migration_types(void)
3357 {
3358     type_register_static(&migration_type);
3359 }
3360
3361 type_init(register_migration_types);
This page took 0.214847 seconds and 4 git commands to generate.