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 */ 13 14 #ifndef QEMU_MIGRATION_H 15 #define QEMU_MIGRATION_H 16 17 #include "exec/cpu-common.h" 18 #include "hw/qdev-core.h" 19 #include "qapi/qapi-types-migration.h" 20 #include "qapi/qmp/json-writer.h" 21 #include "qemu/thread.h" 22 #include "qemu/coroutine.h" 23 #include "io/channel.h" 24 #include "io/channel-buffer.h" 25 #include "net/announce.h" 26 #include "qom/object.h" 27 #include "postcopy-ram.h" 28 #include "sysemu/runstate.h" 29 #include "migration/misc.h" 30 31 struct PostcopyBlocktimeContext; 32 33 #define MIGRATION_RESUME_ACK_VALUE (1) 34 35 /* 36 * 1<<6=64 pages -> 256K chunk when page size is 4K. This gives us 37 * the benefit that all the chunks are 64 pages aligned then the 38 * bitmaps are always aligned to LONG. 39 */ 40 #define CLEAR_BITMAP_SHIFT_MIN 6 41 /* 42 * 1<<18=256K pages -> 1G chunk when page size is 4K. This is the 43 * default value to use if no one specified. 44 */ 45 #define CLEAR_BITMAP_SHIFT_DEFAULT 18 46 /* 47 * 1<<31=2G pages -> 8T chunk when page size is 4K. This should be 48 * big enough and make sure we won't overflow easily. 49 */ 50 #define CLEAR_BITMAP_SHIFT_MAX 31 51 52 /* This is an abstraction of a "temp huge page" for postcopy's purpose */ 53 typedef struct { 54 /* 55 * This points to a temporary huge page as a buffer for UFFDIO_COPY. It's 56 * mmap()ed and needs to be freed when cleanup. 57 */ 58 void *tmp_huge_page; 59 /* 60 * This points to the host page we're going to install for this temp page. 61 * It tells us after we've received the whole page, where we should put it. 62 */ 63 void *host_addr; 64 /* Number of small pages copied (in size of TARGET_PAGE_SIZE) */ 65 unsigned int target_pages; 66 /* Whether this page contains all zeros */ 67 bool all_zero; 68 } PostcopyTmpPage; 69 70 typedef enum { 71 PREEMPT_THREAD_NONE = 0, 72 PREEMPT_THREAD_CREATED, 73 PREEMPT_THREAD_QUIT, 74 } PreemptThreadStatus; 75 76 /* State for the incoming migration */ 77 struct MigrationIncomingState { 78 QEMUFile *from_src_file; 79 /* Previously received RAM's RAMBlock pointer */ 80 RAMBlock *last_recv_block[RAM_CHANNEL_MAX]; 81 /* A hook to allow cleanup at the end of incoming migration */ 82 void *transport_data; 83 void (*transport_cleanup)(void *data); 84 /* 85 * Used to sync thread creations. Note that we can't create threads in 86 * parallel with this sem. 87 */ 88 QemuSemaphore thread_sync_sem; 89 /* 90 * Free at the start of the main state load, set as the main thread finishes 91 * loading state. 92 */ 93 QemuEvent main_thread_load_event; 94 95 /* For network announces */ 96 AnnounceTimer announce_timer; 97 98 size_t largest_page_size; 99 bool have_fault_thread; 100 QemuThread fault_thread; 101 /* Set this when we want the fault thread to quit */ 102 bool fault_thread_quit; 103 104 bool have_listen_thread; 105 QemuThread listen_thread; 106 107 /* For the kernel to send us notifications */ 108 int userfault_fd; 109 /* To notify the fault_thread to wake, e.g., when need to quit */ 110 int userfault_event_fd; 111 QEMUFile *to_src_file; 112 QemuMutex rp_mutex; /* We send replies from multiple threads */ 113 /* RAMBlock of last request sent to source */ 114 RAMBlock *last_rb; 115 /* 116 * Number of postcopy channels including the default precopy channel, so 117 * vanilla postcopy will only contain one channel which contain both 118 * precopy and postcopy streams. 119 * 120 * This is calculated when the src requests to enable postcopy but before 121 * it starts. Its value can depend on e.g. whether postcopy preemption is 122 * enabled. 123 */ 124 unsigned int postcopy_channels; 125 /* QEMUFile for postcopy only; it'll be handled by a separate thread */ 126 QEMUFile *postcopy_qemufile_dst; 127 /* 128 * When postcopy_qemufile_dst is properly setup, this sem is posted. 129 * One can wait on this semaphore to wait until the preempt channel is 130 * properly setup. 131 */ 132 QemuSemaphore postcopy_qemufile_dst_done; 133 /* Postcopy priority thread is used to receive postcopy requested pages */ 134 QemuThread postcopy_prio_thread; 135 /* 136 * Always set by the main vm load thread only, but can be read by the 137 * postcopy preempt thread. "volatile" makes sure all reads will be 138 * up-to-date across cores. 139 */ 140 volatile PreemptThreadStatus preempt_thread_status; 141 /* 142 * Used to sync between the ram load main thread and the fast ram load 143 * thread. It protects postcopy_qemufile_dst, which is the postcopy 144 * fast channel. 145 * 146 * The ram fast load thread will take it mostly for the whole lifecycle 147 * because it needs to continuously read data from the channel, and 148 * it'll only release this mutex if postcopy is interrupted, so that 149 * the ram load main thread will take this mutex over and properly 150 * release the broken channel. 151 */ 152 QemuMutex postcopy_prio_thread_mutex; 153 /* 154 * An array of temp host huge pages to be used, one for each postcopy 155 * channel. 156 */ 157 PostcopyTmpPage *postcopy_tmp_pages; 158 /* This is shared for all postcopy channels */ 159 void *postcopy_tmp_zero_page; 160 /* PostCopyFD's for external userfaultfds & handlers of shared memory */ 161 GArray *postcopy_remote_fds; 162 163 MigrationStatus state; 164 165 /* 166 * The incoming migration coroutine, non-NULL during qemu_loadvm_state(). 167 * Used to wake the migration incoming coroutine from rdma code. How much is 168 * it safe - it's a question. 169 */ 170 Coroutine *loadvm_co; 171 172 /* The coroutine we should enter (back) after failover */ 173 Coroutine *colo_incoming_co; 174 QemuSemaphore colo_incoming_sem; 175 176 /* 177 * PostcopyBlocktimeContext to keep information for postcopy 178 * live migration, to calculate vCPU block time 179 * */ 180 struct PostcopyBlocktimeContext *blocktime_ctx; 181 182 /* notify PAUSED postcopy incoming migrations to try to continue */ 183 QemuSemaphore postcopy_pause_sem_dst; 184 QemuSemaphore postcopy_pause_sem_fault; 185 /* 186 * This semaphore is used to allow the ram fast load thread (only when 187 * postcopy preempt is enabled) fall into sleep when there's network 188 * interruption detected. When the recovery is done, the main load 189 * thread will kick the fast ram load thread using this semaphore. 190 */ 191 QemuSemaphore postcopy_pause_sem_fast_load; 192 193 /* List of listening socket addresses */ 194 SocketAddressList *socket_address_list; 195 196 /* A tree of pages that we requested to the source VM */ 197 GTree *page_requested; 198 /* 199 * For postcopy only, count the number of requested page faults that 200 * still haven't been resolved. 201 */ 202 int page_requested_count; 203 /* 204 * The mutex helps to maintain the requested pages that we sent to the 205 * source, IOW, to guarantee coherent between the page_requests tree and 206 * the per-ramblock receivedmap. Note! This does not guarantee consistency 207 * of the real page copy procedures (using UFFDIO_[ZERO]COPY). E.g., even 208 * if one bit in receivedmap is cleared, UFFDIO_COPY could have happened 209 * for that page already. This is intended so that the mutex won't 210 * serialize and blocked by slow operations like UFFDIO_* ioctls. However 211 * this should be enough to make sure the page_requested tree always 212 * contains valid information. 213 */ 214 QemuMutex page_request_mutex; 215 /* 216 * If postcopy preempt is enabled, there is a chance that the main 217 * thread finished loading its data before the preempt channel has 218 * finished loading the urgent pages. If that happens, the two threads 219 * will use this condvar to synchronize, so the main thread will always 220 * wait until all pages received. 221 */ 222 QemuCond page_request_cond; 223 224 /* 225 * Number of devices that have yet to approve switchover. When this reaches 226 * zero an ACK that it's OK to do switchover is sent to the source. No lock 227 * is needed as this field is updated serially. 228 */ 229 unsigned int switchover_ack_pending_num; 230 231 /* Do exit on incoming migration failure */ 232 bool exit_on_error; 233 }; 234 235 MigrationIncomingState *migration_incoming_get_current(void); 236 void migration_incoming_state_destroy(void); 237 void migration_incoming_transport_cleanup(MigrationIncomingState *mis); 238 /* 239 * Functions to work with blocktime context 240 */ 241 void fill_destination_postcopy_migration_info(MigrationInfo *info); 242 243 #define TYPE_MIGRATION "migration" 244 245 typedef struct MigrationClass MigrationClass; 246 DECLARE_OBJ_CHECKERS(MigrationState, MigrationClass, 247 MIGRATION_OBJ, TYPE_MIGRATION) 248 249 struct MigrationClass { 250 /*< private >*/ 251 DeviceClass parent_class; 252 }; 253 254 struct MigrationState { 255 /*< private >*/ 256 DeviceState parent_obj; 257 258 /*< public >*/ 259 QemuThread thread; 260 /* Protected by qemu_file_lock */ 261 QEMUFile *to_dst_file; 262 /* Postcopy specific transfer channel */ 263 QEMUFile *postcopy_qemufile_src; 264 /* 265 * It is posted when the preempt channel is established. Note: this is 266 * used for both the start or recover of a postcopy migration. We'll 267 * post to this sem every time a new preempt channel is created in the 268 * main thread, and we keep post() and wait() in pair. 269 */ 270 QemuSemaphore postcopy_qemufile_src_sem; 271 QIOChannelBuffer *bioc; 272 /* 273 * Protects to_dst_file/from_dst_file pointers. We need to make sure we 274 * won't yield or hang during the critical section, since this lock will be 275 * used in OOB command handler. 276 */ 277 QemuMutex qemu_file_lock; 278 279 /* 280 * Used to allow urgent requests to override rate limiting. 281 */ 282 QemuSemaphore rate_limit_sem; 283 284 /* pages already send at the beginning of current iteration */ 285 uint64_t iteration_initial_pages; 286 287 /* pages transferred per second */ 288 double pages_per_second; 289 290 /* bytes already send at the beginning of current iteration */ 291 uint64_t iteration_initial_bytes; 292 /* time at the start of current iteration */ 293 int64_t iteration_start_time; 294 /* 295 * The final stage happens when the remaining data is smaller than 296 * this threshold; it's calculated from the requested downtime and 297 * measured bandwidth, or avail-switchover-bandwidth if specified. 298 */ 299 uint64_t threshold_size; 300 301 /* params from 'migrate-set-parameters' */ 302 MigrationParameters parameters; 303 304 MigrationStatus state; 305 306 /* State related to return path */ 307 struct { 308 /* Protected by qemu_file_lock */ 309 QEMUFile *from_dst_file; 310 QemuThread rp_thread; 311 /* 312 * We can also check non-zero of rp_thread, but there's no "official" 313 * way to do this, so this bool makes it slightly more elegant. 314 * Checking from_dst_file for this is racy because from_dst_file will 315 * be cleared in the rp_thread! 316 */ 317 bool rp_thread_created; 318 /* 319 * Used to synchronize between migration main thread and return 320 * path thread. The migration thread can wait() on this sem, while 321 * other threads (e.g., return path thread) can kick it using a 322 * post(). 323 */ 324 QemuSemaphore rp_sem; 325 /* 326 * We post to this when we got one PONG from dest. So far it's an 327 * easy way to know the main channel has successfully established 328 * on dest QEMU. 329 */ 330 QemuSemaphore rp_pong_acks; 331 } rp_state; 332 333 double mbps; 334 /* Timestamp when recent migration starts (ms) */ 335 int64_t start_time; 336 /* Total time used by latest migration (ms) */ 337 int64_t total_time; 338 /* Timestamp when VM is down (ms) to migrate the last stuff */ 339 int64_t downtime_start; 340 int64_t downtime; 341 int64_t expected_downtime; 342 bool capabilities[MIGRATION_CAPABILITY__MAX]; 343 int64_t setup_time; 344 345 /* 346 * State before stopping the vm by vm_stop_force_state(). 347 * If migration is interrupted by any reason, we need to continue 348 * running the guest on source if it was running or restore its stopped 349 * state. 350 */ 351 RunState vm_old_state; 352 353 /* Flag set once the migration has been asked to enter postcopy */ 354 bool start_postcopy; 355 356 /* Flag set once the migration thread is running (and needs joining) */ 357 bool migration_thread_running; 358 359 /* Flag set once the migration thread called bdrv_inactivate_all */ 360 bool block_inactive; 361 362 /* Migration is waiting for guest to unplug device */ 363 QemuSemaphore wait_unplug_sem; 364 365 /* Migration is paused due to pause-before-switchover */ 366 QemuSemaphore pause_sem; 367 368 /* The semaphore is used to notify COLO thread that failover is finished */ 369 QemuSemaphore colo_exit_sem; 370 371 /* The event is used to notify COLO thread to do checkpoint */ 372 QemuEvent colo_checkpoint_event; 373 int64_t colo_checkpoint_time; 374 QEMUTimer *colo_delay_timer; 375 376 /* The first error that has occurred. 377 We used the mutex to be able to return the 1st error message */ 378 Error *error; 379 /* mutex to protect errp */ 380 QemuMutex error_mutex; 381 382 /* 383 * Global switch on whether we need to store the global state 384 * during migration. 385 */ 386 bool store_global_state; 387 388 /* Whether we send QEMU_VM_CONFIGURATION during migration */ 389 bool send_configuration; 390 /* Whether we send section footer during migration */ 391 bool send_section_footer; 392 393 /* Needed by postcopy-pause state */ 394 QemuSemaphore postcopy_pause_sem; 395 /* 396 * This variable only affects behavior when postcopy preempt mode is 397 * enabled. 398 * 399 * When set: 400 * 401 * - postcopy preempt src QEMU instance will generate an EOS message at 402 * the end of migration to shut the preempt channel on dest side. 403 * 404 * - postcopy preempt channel will be created at the setup phase on src 405 QEMU. 406 * 407 * When clear: 408 * 409 * - postcopy preempt src QEMU instance will _not_ generate an EOS 410 * message at the end of migration, the dest qemu will shutdown the 411 * channel itself. 412 * 413 * - postcopy preempt channel will be created at the switching phase 414 * from precopy -> postcopy (to avoid race condition of misordered 415 * creation of channels). 416 * 417 * NOTE: See message-id <ZBoShWArKDPpX/D7@work-vm> on qemu-devel 418 * mailing list for more information on the possible race. Everyone 419 * should probably just keep this value untouched after set by the 420 * machine type (or the default). 421 */ 422 bool preempt_pre_7_2; 423 424 /* 425 * flush every channel after each section sent. 426 * 427 * This assures that we can't mix pages from one iteration through 428 * ram pages with pages for the following iteration. We really 429 * only need to do this flush after we have go through all the 430 * dirty pages. For historical reasons, we do that after each 431 * section. This is suboptimal (we flush too many times). 432 * Default value is false. (since 8.1) 433 */ 434 bool multifd_flush_after_each_section; 435 /* 436 * This decides the size of guest memory chunk that will be used 437 * to track dirty bitmap clearing. The size of memory chunk will 438 * be GUEST_PAGE_SIZE << N. Say, N=0 means we will clear dirty 439 * bitmap for each page to send (1<<0=1); N=10 means we will clear 440 * dirty bitmap only once for 1<<10=1K continuous guest pages 441 * (which is in 4M chunk). 442 */ 443 uint8_t clear_bitmap_shift; 444 445 /* 446 * This save hostname when out-going migration starts 447 */ 448 char *hostname; 449 450 /* QEMU_VM_VMDESCRIPTION content filled for all non-iterable devices. */ 451 JSONWriter *vmdesc; 452 453 /* 454 * Indicates whether an ACK from the destination that it's OK to do 455 * switchover has been received. 456 */ 457 bool switchover_acked; 458 /* Is this a rdma migration */ 459 bool rdma_migration; 460 }; 461 462 void migrate_set_state(MigrationStatus *state, MigrationStatus old_state, 463 MigrationStatus new_state); 464 465 void migration_fd_process_incoming(QEMUFile *f); 466 void migration_ioc_process_incoming(QIOChannel *ioc, Error **errp); 467 void migration_incoming_process(void); 468 469 bool migration_has_all_channels(void); 470 471 void migrate_set_error(MigrationState *s, const Error *error); 472 bool migrate_has_error(MigrationState *s); 473 474 void migrate_fd_connect(MigrationState *s, Error *error_in); 475 476 int migration_call_notifiers(MigrationState *s, MigrationEventType type, 477 Error **errp); 478 479 int migrate_init(MigrationState *s, Error **errp); 480 bool migration_is_blocked(Error **errp); 481 /* True if outgoing migration has entered postcopy phase */ 482 bool migration_in_postcopy(void); 483 bool migration_postcopy_is_alive(MigrationStatus state); 484 MigrationState *migrate_get_current(void); 485 bool migration_has_failed(MigrationState *); 486 bool migrate_mode_is_cpr(MigrationState *); 487 488 uint64_t ram_get_total_transferred_pages(void); 489 490 /* Sending on the return path - generic and then for each message type */ 491 void migrate_send_rp_shut(MigrationIncomingState *mis, 492 uint32_t value); 493 void migrate_send_rp_pong(MigrationIncomingState *mis, 494 uint32_t value); 495 int migrate_send_rp_req_pages(MigrationIncomingState *mis, RAMBlock *rb, 496 ram_addr_t start, uint64_t haddr); 497 int migrate_send_rp_message_req_pages(MigrationIncomingState *mis, 498 RAMBlock *rb, ram_addr_t start); 499 void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis, 500 char *block_name); 501 void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value); 502 int migrate_send_rp_switchover_ack(MigrationIncomingState *mis); 503 504 void dirty_bitmap_mig_before_vm_start(void); 505 void dirty_bitmap_mig_cancel_outgoing(void); 506 void dirty_bitmap_mig_cancel_incoming(void); 507 bool check_dirty_bitmap_mig_alias_map(const BitmapMigrationNodeAliasList *bbm, 508 Error **errp); 509 510 void migrate_add_address(SocketAddress *address); 511 bool migrate_uri_parse(const char *uri, MigrationChannel **channel, 512 Error **errp); 513 int foreach_not_ignored_block(RAMBlockIterFunc func, void *opaque); 514 515 #define qemu_ram_foreach_block \ 516 #warning "Use foreach_not_ignored_block in migration code" 517 518 void migration_make_urgent_request(void); 519 void migration_consume_urgent_request(void); 520 bool migration_rate_limit(void); 521 void migration_bh_schedule(QEMUBHFunc *cb, void *opaque); 522 void migration_cancel(const Error *error); 523 524 void migration_populate_vfio_info(MigrationInfo *info); 525 void migration_reset_vfio_bytes_transferred(void); 526 void postcopy_temp_page_reset(PostcopyTmpPage *tmp_page); 527 528 /* 529 * Migration thread waiting for return path thread. Return non-zero if an 530 * error is detected. 531 */ 532 int migration_rp_wait(MigrationState *s); 533 /* 534 * Kick the migration thread waiting for return path messages. NOTE: the 535 * name can be slightly confusing (when read as "kick the rp thread"), just 536 * to remember the target is always the migration thread. 537 */ 538 void migration_rp_kick(MigrationState *s); 539 540 #endif 541