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