1 /* 2 * Postcopy migration for RAM 3 * 4 * Copyright 2013-2015 Red Hat, Inc. and/or its affiliates 5 * 6 * Authors: 7 * Dave Gilbert <dgilbert@redhat.com> 8 * 9 * This work is licensed under the terms of the GNU GPL, version 2 or later. 10 * See the COPYING file in the top-level directory. 11 * 12 */ 13 14 /* 15 * Postcopy is a migration technique where the execution flips from the 16 * source to the destination before all the data has been copied. 17 */ 18 19 #include "qemu/osdep.h" 20 #include "qemu/rcu.h" 21 #include "exec/target_page.h" 22 #include "migration.h" 23 #include "qemu-file.h" 24 #include "savevm.h" 25 #include "postcopy-ram.h" 26 #include "ram.h" 27 #include "qapi/error.h" 28 #include "qemu/notify.h" 29 #include "qemu/rcu.h" 30 #include "sysemu/sysemu.h" 31 #include "qemu/error-report.h" 32 #include "trace.h" 33 #include "hw/boards.h" 34 #include "exec/ramblock.h" 35 36 /* Arbitrary limit on size of each discard command, 37 * keeps them around ~200 bytes 38 */ 39 #define MAX_DISCARDS_PER_COMMAND 12 40 41 struct PostcopyDiscardState { 42 const char *ramblock_name; 43 uint16_t cur_entry; 44 /* 45 * Start and length of a discard range (bytes) 46 */ 47 uint64_t start_list[MAX_DISCARDS_PER_COMMAND]; 48 uint64_t length_list[MAX_DISCARDS_PER_COMMAND]; 49 unsigned int nsentwords; 50 unsigned int nsentcmds; 51 }; 52 53 static NotifierWithReturnList postcopy_notifier_list; 54 55 void postcopy_infrastructure_init(void) 56 { 57 notifier_with_return_list_init(&postcopy_notifier_list); 58 } 59 60 void postcopy_add_notifier(NotifierWithReturn *nn) 61 { 62 notifier_with_return_list_add(&postcopy_notifier_list, nn); 63 } 64 65 void postcopy_remove_notifier(NotifierWithReturn *n) 66 { 67 notifier_with_return_remove(n); 68 } 69 70 int postcopy_notify(enum PostcopyNotifyReason reason, Error **errp) 71 { 72 struct PostcopyNotifyData pnd; 73 pnd.reason = reason; 74 pnd.errp = errp; 75 76 return notifier_with_return_list_notify(&postcopy_notifier_list, 77 &pnd); 78 } 79 80 /* Postcopy needs to detect accesses to pages that haven't yet been copied 81 * across, and efficiently map new pages in, the techniques for doing this 82 * are target OS specific. 83 */ 84 #if defined(__linux__) 85 86 #include <poll.h> 87 #include <sys/ioctl.h> 88 #include <sys/syscall.h> 89 #include <asm/types.h> /* for __u64 */ 90 #endif 91 92 #if defined(__linux__) && defined(__NR_userfaultfd) && defined(CONFIG_EVENTFD) 93 #include <sys/eventfd.h> 94 #include <linux/userfaultfd.h> 95 96 typedef struct PostcopyBlocktimeContext { 97 /* time when page fault initiated per vCPU */ 98 uint32_t *page_fault_vcpu_time; 99 /* page address per vCPU */ 100 uintptr_t *vcpu_addr; 101 uint32_t total_blocktime; 102 /* blocktime per vCPU */ 103 uint32_t *vcpu_blocktime; 104 /* point in time when last page fault was initiated */ 105 uint32_t last_begin; 106 /* number of vCPU are suspended */ 107 int smp_cpus_down; 108 uint64_t start_time; 109 110 /* 111 * Handler for exit event, necessary for 112 * releasing whole blocktime_ctx 113 */ 114 Notifier exit_notifier; 115 } PostcopyBlocktimeContext; 116 117 static void destroy_blocktime_context(struct PostcopyBlocktimeContext *ctx) 118 { 119 g_free(ctx->page_fault_vcpu_time); 120 g_free(ctx->vcpu_addr); 121 g_free(ctx->vcpu_blocktime); 122 g_free(ctx); 123 } 124 125 static void migration_exit_cb(Notifier *n, void *data) 126 { 127 PostcopyBlocktimeContext *ctx = container_of(n, PostcopyBlocktimeContext, 128 exit_notifier); 129 destroy_blocktime_context(ctx); 130 } 131 132 static struct PostcopyBlocktimeContext *blocktime_context_new(void) 133 { 134 MachineState *ms = MACHINE(qdev_get_machine()); 135 unsigned int smp_cpus = ms->smp.cpus; 136 PostcopyBlocktimeContext *ctx = g_new0(PostcopyBlocktimeContext, 1); 137 ctx->page_fault_vcpu_time = g_new0(uint32_t, smp_cpus); 138 ctx->vcpu_addr = g_new0(uintptr_t, smp_cpus); 139 ctx->vcpu_blocktime = g_new0(uint32_t, smp_cpus); 140 141 ctx->exit_notifier.notify = migration_exit_cb; 142 ctx->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 143 qemu_add_exit_notifier(&ctx->exit_notifier); 144 return ctx; 145 } 146 147 static uint32List *get_vcpu_blocktime_list(PostcopyBlocktimeContext *ctx) 148 { 149 MachineState *ms = MACHINE(qdev_get_machine()); 150 uint32List *list = NULL; 151 int i; 152 153 for (i = ms->smp.cpus - 1; i >= 0; i--) { 154 QAPI_LIST_PREPEND(list, ctx->vcpu_blocktime[i]); 155 } 156 157 return list; 158 } 159 160 /* 161 * This function just populates MigrationInfo from postcopy's 162 * blocktime context. It will not populate MigrationInfo, 163 * unless postcopy-blocktime capability was set. 164 * 165 * @info: pointer to MigrationInfo to populate 166 */ 167 void fill_destination_postcopy_migration_info(MigrationInfo *info) 168 { 169 MigrationIncomingState *mis = migration_incoming_get_current(); 170 PostcopyBlocktimeContext *bc = mis->blocktime_ctx; 171 172 if (!bc) { 173 return; 174 } 175 176 info->has_postcopy_blocktime = true; 177 info->postcopy_blocktime = bc->total_blocktime; 178 info->has_postcopy_vcpu_blocktime = true; 179 info->postcopy_vcpu_blocktime = get_vcpu_blocktime_list(bc); 180 } 181 182 static uint32_t get_postcopy_total_blocktime(void) 183 { 184 MigrationIncomingState *mis = migration_incoming_get_current(); 185 PostcopyBlocktimeContext *bc = mis->blocktime_ctx; 186 187 if (!bc) { 188 return 0; 189 } 190 191 return bc->total_blocktime; 192 } 193 194 /** 195 * receive_ufd_features: check userfault fd features, to request only supported 196 * features in the future. 197 * 198 * Returns: true on success 199 * 200 * __NR_userfaultfd - should be checked before 201 * @features: out parameter will contain uffdio_api.features provided by kernel 202 * in case of success 203 */ 204 static bool receive_ufd_features(uint64_t *features) 205 { 206 struct uffdio_api api_struct = {0}; 207 int ufd; 208 bool ret = true; 209 210 /* if we are here __NR_userfaultfd should exists */ 211 ufd = syscall(__NR_userfaultfd, O_CLOEXEC); 212 if (ufd == -1) { 213 error_report("%s: syscall __NR_userfaultfd failed: %s", __func__, 214 strerror(errno)); 215 return false; 216 } 217 218 /* ask features */ 219 api_struct.api = UFFD_API; 220 api_struct.features = 0; 221 if (ioctl(ufd, UFFDIO_API, &api_struct)) { 222 error_report("%s: UFFDIO_API failed: %s", __func__, 223 strerror(errno)); 224 ret = false; 225 goto release_ufd; 226 } 227 228 *features = api_struct.features; 229 230 release_ufd: 231 close(ufd); 232 return ret; 233 } 234 235 /** 236 * request_ufd_features: this function should be called only once on a newly 237 * opened ufd, subsequent calls will lead to error. 238 * 239 * Returns: true on success 240 * 241 * @ufd: fd obtained from userfaultfd syscall 242 * @features: bit mask see UFFD_API_FEATURES 243 */ 244 static bool request_ufd_features(int ufd, uint64_t features) 245 { 246 struct uffdio_api api_struct = {0}; 247 uint64_t ioctl_mask; 248 249 api_struct.api = UFFD_API; 250 api_struct.features = features; 251 if (ioctl(ufd, UFFDIO_API, &api_struct)) { 252 error_report("%s failed: UFFDIO_API failed: %s", __func__, 253 strerror(errno)); 254 return false; 255 } 256 257 ioctl_mask = (__u64)1 << _UFFDIO_REGISTER | 258 (__u64)1 << _UFFDIO_UNREGISTER; 259 if ((api_struct.ioctls & ioctl_mask) != ioctl_mask) { 260 error_report("Missing userfault features: %" PRIx64, 261 (uint64_t)(~api_struct.ioctls & ioctl_mask)); 262 return false; 263 } 264 265 return true; 266 } 267 268 static bool ufd_check_and_apply(int ufd, MigrationIncomingState *mis) 269 { 270 uint64_t asked_features = 0; 271 static uint64_t supported_features; 272 273 /* 274 * it's not possible to 275 * request UFFD_API twice per one fd 276 * userfault fd features is persistent 277 */ 278 if (!supported_features) { 279 if (!receive_ufd_features(&supported_features)) { 280 error_report("%s failed", __func__); 281 return false; 282 } 283 } 284 285 #ifdef UFFD_FEATURE_THREAD_ID 286 if (UFFD_FEATURE_THREAD_ID & supported_features) { 287 asked_features |= UFFD_FEATURE_THREAD_ID; 288 if (migrate_postcopy_blocktime()) { 289 if (!mis->blocktime_ctx) { 290 mis->blocktime_ctx = blocktime_context_new(); 291 } 292 } 293 } 294 #endif 295 296 /* 297 * request features, even if asked_features is 0, due to 298 * kernel expects UFFD_API before UFFDIO_REGISTER, per 299 * userfault file descriptor 300 */ 301 if (!request_ufd_features(ufd, asked_features)) { 302 error_report("%s failed: features %" PRIu64, __func__, 303 asked_features); 304 return false; 305 } 306 307 if (qemu_real_host_page_size != ram_pagesize_summary()) { 308 bool have_hp = false; 309 /* We've got a huge page */ 310 #ifdef UFFD_FEATURE_MISSING_HUGETLBFS 311 have_hp = supported_features & UFFD_FEATURE_MISSING_HUGETLBFS; 312 #endif 313 if (!have_hp) { 314 error_report("Userfault on this host does not support huge pages"); 315 return false; 316 } 317 } 318 return true; 319 } 320 321 /* Callback from postcopy_ram_supported_by_host block iterator. 322 */ 323 static int test_ramblock_postcopiable(RAMBlock *rb, void *opaque) 324 { 325 const char *block_name = qemu_ram_get_idstr(rb); 326 ram_addr_t length = qemu_ram_get_used_length(rb); 327 size_t pagesize = qemu_ram_pagesize(rb); 328 329 if (length % pagesize) { 330 error_report("Postcopy requires RAM blocks to be a page size multiple," 331 " block %s is 0x" RAM_ADDR_FMT " bytes with a " 332 "page size of 0x%zx", block_name, length, pagesize); 333 return 1; 334 } 335 return 0; 336 } 337 338 /* 339 * Note: This has the side effect of munlock'ing all of RAM, that's 340 * normally fine since if the postcopy succeeds it gets turned back on at the 341 * end. 342 */ 343 bool postcopy_ram_supported_by_host(MigrationIncomingState *mis) 344 { 345 long pagesize = qemu_real_host_page_size; 346 int ufd = -1; 347 bool ret = false; /* Error unless we change it */ 348 void *testarea = NULL; 349 struct uffdio_register reg_struct; 350 struct uffdio_range range_struct; 351 uint64_t feature_mask; 352 Error *local_err = NULL; 353 354 if (qemu_target_page_size() > pagesize) { 355 error_report("Target page size bigger than host page size"); 356 goto out; 357 } 358 359 ufd = syscall(__NR_userfaultfd, O_CLOEXEC); 360 if (ufd == -1) { 361 error_report("%s: userfaultfd not available: %s", __func__, 362 strerror(errno)); 363 goto out; 364 } 365 366 /* Give devices a chance to object */ 367 if (postcopy_notify(POSTCOPY_NOTIFY_PROBE, &local_err)) { 368 error_report_err(local_err); 369 goto out; 370 } 371 372 /* Version and features check */ 373 if (!ufd_check_and_apply(ufd, mis)) { 374 goto out; 375 } 376 377 /* We don't support postcopy with shared RAM yet */ 378 if (foreach_not_ignored_block(test_ramblock_postcopiable, NULL)) { 379 goto out; 380 } 381 382 /* 383 * userfault and mlock don't go together; we'll put it back later if 384 * it was enabled. 385 */ 386 if (munlockall()) { 387 error_report("%s: munlockall: %s", __func__, strerror(errno)); 388 goto out; 389 } 390 391 /* 392 * We need to check that the ops we need are supported on anon memory 393 * To do that we need to register a chunk and see the flags that 394 * are returned. 395 */ 396 testarea = mmap(NULL, pagesize, PROT_READ | PROT_WRITE, MAP_PRIVATE | 397 MAP_ANONYMOUS, -1, 0); 398 if (testarea == MAP_FAILED) { 399 error_report("%s: Failed to map test area: %s", __func__, 400 strerror(errno)); 401 goto out; 402 } 403 g_assert(QEMU_PTR_IS_ALIGNED(testarea, pagesize)); 404 405 reg_struct.range.start = (uintptr_t)testarea; 406 reg_struct.range.len = pagesize; 407 reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING; 408 409 if (ioctl(ufd, UFFDIO_REGISTER, ®_struct)) { 410 error_report("%s userfault register: %s", __func__, strerror(errno)); 411 goto out; 412 } 413 414 range_struct.start = (uintptr_t)testarea; 415 range_struct.len = pagesize; 416 if (ioctl(ufd, UFFDIO_UNREGISTER, &range_struct)) { 417 error_report("%s userfault unregister: %s", __func__, strerror(errno)); 418 goto out; 419 } 420 421 feature_mask = (__u64)1 << _UFFDIO_WAKE | 422 (__u64)1 << _UFFDIO_COPY | 423 (__u64)1 << _UFFDIO_ZEROPAGE; 424 if ((reg_struct.ioctls & feature_mask) != feature_mask) { 425 error_report("Missing userfault map features: %" PRIx64, 426 (uint64_t)(~reg_struct.ioctls & feature_mask)); 427 goto out; 428 } 429 430 /* Success! */ 431 ret = true; 432 out: 433 if (testarea) { 434 munmap(testarea, pagesize); 435 } 436 if (ufd != -1) { 437 close(ufd); 438 } 439 return ret; 440 } 441 442 /* 443 * Setup an area of RAM so that it *can* be used for postcopy later; this 444 * must be done right at the start prior to pre-copy. 445 * opaque should be the MIS. 446 */ 447 static int init_range(RAMBlock *rb, void *opaque) 448 { 449 const char *block_name = qemu_ram_get_idstr(rb); 450 void *host_addr = qemu_ram_get_host_addr(rb); 451 ram_addr_t offset = qemu_ram_get_offset(rb); 452 ram_addr_t length = qemu_ram_get_used_length(rb); 453 trace_postcopy_init_range(block_name, host_addr, offset, length); 454 455 /* 456 * Save the used_length before running the guest. In case we have to 457 * resize RAM blocks when syncing RAM block sizes from the source during 458 * precopy, we'll update it manually via the ram block notifier. 459 */ 460 rb->postcopy_length = length; 461 462 /* 463 * We need the whole of RAM to be truly empty for postcopy, so things 464 * like ROMs and any data tables built during init must be zero'd 465 * - we're going to get the copy from the source anyway. 466 * (Precopy will just overwrite this data, so doesn't need the discard) 467 */ 468 if (ram_discard_range(block_name, 0, length)) { 469 return -1; 470 } 471 472 return 0; 473 } 474 475 /* 476 * At the end of migration, undo the effects of init_range 477 * opaque should be the MIS. 478 */ 479 static int cleanup_range(RAMBlock *rb, void *opaque) 480 { 481 const char *block_name = qemu_ram_get_idstr(rb); 482 void *host_addr = qemu_ram_get_host_addr(rb); 483 ram_addr_t offset = qemu_ram_get_offset(rb); 484 ram_addr_t length = rb->postcopy_length; 485 MigrationIncomingState *mis = opaque; 486 struct uffdio_range range_struct; 487 trace_postcopy_cleanup_range(block_name, host_addr, offset, length); 488 489 /* 490 * We turned off hugepage for the precopy stage with postcopy enabled 491 * we can turn it back on now. 492 */ 493 qemu_madvise(host_addr, length, QEMU_MADV_HUGEPAGE); 494 495 /* 496 * We can also turn off userfault now since we should have all the 497 * pages. It can be useful to leave it on to debug postcopy 498 * if you're not sure it's always getting every page. 499 */ 500 range_struct.start = (uintptr_t)host_addr; 501 range_struct.len = length; 502 503 if (ioctl(mis->userfault_fd, UFFDIO_UNREGISTER, &range_struct)) { 504 error_report("%s: userfault unregister %s", __func__, strerror(errno)); 505 506 return -1; 507 } 508 509 return 0; 510 } 511 512 /* 513 * Initialise postcopy-ram, setting the RAM to a state where we can go into 514 * postcopy later; must be called prior to any precopy. 515 * called from arch_init's similarly named ram_postcopy_incoming_init 516 */ 517 int postcopy_ram_incoming_init(MigrationIncomingState *mis) 518 { 519 if (foreach_not_ignored_block(init_range, NULL)) { 520 return -1; 521 } 522 523 return 0; 524 } 525 526 static void postcopy_temp_pages_cleanup(MigrationIncomingState *mis) 527 { 528 if (mis->postcopy_tmp_page) { 529 munmap(mis->postcopy_tmp_page, mis->largest_page_size); 530 mis->postcopy_tmp_page = NULL; 531 } 532 533 if (mis->postcopy_tmp_zero_page) { 534 munmap(mis->postcopy_tmp_zero_page, mis->largest_page_size); 535 mis->postcopy_tmp_zero_page = NULL; 536 } 537 } 538 539 /* 540 * At the end of a migration where postcopy_ram_incoming_init was called. 541 */ 542 int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis) 543 { 544 trace_postcopy_ram_incoming_cleanup_entry(); 545 546 if (mis->have_fault_thread) { 547 Error *local_err = NULL; 548 549 /* Let the fault thread quit */ 550 qatomic_set(&mis->fault_thread_quit, 1); 551 postcopy_fault_thread_notify(mis); 552 trace_postcopy_ram_incoming_cleanup_join(); 553 qemu_thread_join(&mis->fault_thread); 554 555 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_END, &local_err)) { 556 error_report_err(local_err); 557 return -1; 558 } 559 560 if (foreach_not_ignored_block(cleanup_range, mis)) { 561 return -1; 562 } 563 564 trace_postcopy_ram_incoming_cleanup_closeuf(); 565 close(mis->userfault_fd); 566 close(mis->userfault_event_fd); 567 mis->have_fault_thread = false; 568 } 569 570 if (enable_mlock) { 571 if (os_mlock() < 0) { 572 error_report("mlock: %s", strerror(errno)); 573 /* 574 * It doesn't feel right to fail at this point, we have a valid 575 * VM state. 576 */ 577 } 578 } 579 580 postcopy_temp_pages_cleanup(mis); 581 582 trace_postcopy_ram_incoming_cleanup_blocktime( 583 get_postcopy_total_blocktime()); 584 585 trace_postcopy_ram_incoming_cleanup_exit(); 586 return 0; 587 } 588 589 /* 590 * Disable huge pages on an area 591 */ 592 static int nhp_range(RAMBlock *rb, void *opaque) 593 { 594 const char *block_name = qemu_ram_get_idstr(rb); 595 void *host_addr = qemu_ram_get_host_addr(rb); 596 ram_addr_t offset = qemu_ram_get_offset(rb); 597 ram_addr_t length = rb->postcopy_length; 598 trace_postcopy_nhp_range(block_name, host_addr, offset, length); 599 600 /* 601 * Before we do discards we need to ensure those discards really 602 * do delete areas of the page, even if THP thinks a hugepage would 603 * be a good idea, so force hugepages off. 604 */ 605 qemu_madvise(host_addr, length, QEMU_MADV_NOHUGEPAGE); 606 607 return 0; 608 } 609 610 /* 611 * Userfault requires us to mark RAM as NOHUGEPAGE prior to discard 612 * however leaving it until after precopy means that most of the precopy 613 * data is still THPd 614 */ 615 int postcopy_ram_prepare_discard(MigrationIncomingState *mis) 616 { 617 if (foreach_not_ignored_block(nhp_range, mis)) { 618 return -1; 619 } 620 621 postcopy_state_set(POSTCOPY_INCOMING_DISCARD); 622 623 return 0; 624 } 625 626 /* 627 * Mark the given area of RAM as requiring notification to unwritten areas 628 * Used as a callback on foreach_not_ignored_block. 629 * host_addr: Base of area to mark 630 * offset: Offset in the whole ram arena 631 * length: Length of the section 632 * opaque: MigrationIncomingState pointer 633 * Returns 0 on success 634 */ 635 static int ram_block_enable_notify(RAMBlock *rb, void *opaque) 636 { 637 MigrationIncomingState *mis = opaque; 638 struct uffdio_register reg_struct; 639 640 reg_struct.range.start = (uintptr_t)qemu_ram_get_host_addr(rb); 641 reg_struct.range.len = rb->postcopy_length; 642 reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING; 643 644 /* Now tell our userfault_fd that it's responsible for this area */ 645 if (ioctl(mis->userfault_fd, UFFDIO_REGISTER, ®_struct)) { 646 error_report("%s userfault register: %s", __func__, strerror(errno)); 647 return -1; 648 } 649 if (!(reg_struct.ioctls & ((__u64)1 << _UFFDIO_COPY))) { 650 error_report("%s userfault: Region doesn't support COPY", __func__); 651 return -1; 652 } 653 if (reg_struct.ioctls & ((__u64)1 << _UFFDIO_ZEROPAGE)) { 654 qemu_ram_set_uf_zeroable(rb); 655 } 656 657 return 0; 658 } 659 660 int postcopy_wake_shared(struct PostCopyFD *pcfd, 661 uint64_t client_addr, 662 RAMBlock *rb) 663 { 664 size_t pagesize = qemu_ram_pagesize(rb); 665 struct uffdio_range range; 666 int ret; 667 trace_postcopy_wake_shared(client_addr, qemu_ram_get_idstr(rb)); 668 range.start = ROUND_DOWN(client_addr, pagesize); 669 range.len = pagesize; 670 ret = ioctl(pcfd->fd, UFFDIO_WAKE, &range); 671 if (ret) { 672 error_report("%s: Failed to wake: %zx in %s (%s)", 673 __func__, (size_t)client_addr, qemu_ram_get_idstr(rb), 674 strerror(errno)); 675 } 676 return ret; 677 } 678 679 static int postcopy_request_page(MigrationIncomingState *mis, RAMBlock *rb, 680 ram_addr_t start, uint64_t haddr) 681 { 682 void *aligned = (void *)(uintptr_t)ROUND_DOWN(haddr, qemu_ram_pagesize(rb)); 683 684 /* 685 * Discarded pages (via RamDiscardManager) are never migrated. On unlikely 686 * access, place a zeropage, which will also set the relevant bits in the 687 * recv_bitmap accordingly, so we won't try placing a zeropage twice. 688 * 689 * Checking a single bit is sufficient to handle pagesize > TPS as either 690 * all relevant bits are set or not. 691 */ 692 assert(QEMU_IS_ALIGNED(start, qemu_ram_pagesize(rb))); 693 if (ramblock_page_is_discarded(rb, start)) { 694 bool received = ramblock_recv_bitmap_test_byte_offset(rb, start); 695 696 return received ? 0 : postcopy_place_page_zero(mis, aligned, rb); 697 } 698 699 return migrate_send_rp_req_pages(mis, rb, start, haddr); 700 } 701 702 /* 703 * Callback from shared fault handlers to ask for a page, 704 * the page must be specified by a RAMBlock and an offset in that rb 705 * Note: Only for use by shared fault handlers (in fault thread) 706 */ 707 int postcopy_request_shared_page(struct PostCopyFD *pcfd, RAMBlock *rb, 708 uint64_t client_addr, uint64_t rb_offset) 709 { 710 uint64_t aligned_rbo = ROUND_DOWN(rb_offset, qemu_ram_pagesize(rb)); 711 MigrationIncomingState *mis = migration_incoming_get_current(); 712 713 trace_postcopy_request_shared_page(pcfd->idstr, qemu_ram_get_idstr(rb), 714 rb_offset); 715 if (ramblock_recv_bitmap_test_byte_offset(rb, aligned_rbo)) { 716 trace_postcopy_request_shared_page_present(pcfd->idstr, 717 qemu_ram_get_idstr(rb), rb_offset); 718 return postcopy_wake_shared(pcfd, client_addr, rb); 719 } 720 postcopy_request_page(mis, rb, aligned_rbo, client_addr); 721 return 0; 722 } 723 724 static int get_mem_fault_cpu_index(uint32_t pid) 725 { 726 CPUState *cpu_iter; 727 728 CPU_FOREACH(cpu_iter) { 729 if (cpu_iter->thread_id == pid) { 730 trace_get_mem_fault_cpu_index(cpu_iter->cpu_index, pid); 731 return cpu_iter->cpu_index; 732 } 733 } 734 trace_get_mem_fault_cpu_index(-1, pid); 735 return -1; 736 } 737 738 static uint32_t get_low_time_offset(PostcopyBlocktimeContext *dc) 739 { 740 int64_t start_time_offset = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - 741 dc->start_time; 742 return start_time_offset < 1 ? 1 : start_time_offset & UINT32_MAX; 743 } 744 745 /* 746 * This function is being called when pagefault occurs. It 747 * tracks down vCPU blocking time. 748 * 749 * @addr: faulted host virtual address 750 * @ptid: faulted process thread id 751 * @rb: ramblock appropriate to addr 752 */ 753 static void mark_postcopy_blocktime_begin(uintptr_t addr, uint32_t ptid, 754 RAMBlock *rb) 755 { 756 int cpu, already_received; 757 MigrationIncomingState *mis = migration_incoming_get_current(); 758 PostcopyBlocktimeContext *dc = mis->blocktime_ctx; 759 uint32_t low_time_offset; 760 761 if (!dc || ptid == 0) { 762 return; 763 } 764 cpu = get_mem_fault_cpu_index(ptid); 765 if (cpu < 0) { 766 return; 767 } 768 769 low_time_offset = get_low_time_offset(dc); 770 if (dc->vcpu_addr[cpu] == 0) { 771 qatomic_inc(&dc->smp_cpus_down); 772 } 773 774 qatomic_xchg(&dc->last_begin, low_time_offset); 775 qatomic_xchg(&dc->page_fault_vcpu_time[cpu], low_time_offset); 776 qatomic_xchg(&dc->vcpu_addr[cpu], addr); 777 778 /* 779 * check it here, not at the beginning of the function, 780 * due to, check could occur early than bitmap_set in 781 * qemu_ufd_copy_ioctl 782 */ 783 already_received = ramblock_recv_bitmap_test(rb, (void *)addr); 784 if (already_received) { 785 qatomic_xchg(&dc->vcpu_addr[cpu], 0); 786 qatomic_xchg(&dc->page_fault_vcpu_time[cpu], 0); 787 qatomic_dec(&dc->smp_cpus_down); 788 } 789 trace_mark_postcopy_blocktime_begin(addr, dc, dc->page_fault_vcpu_time[cpu], 790 cpu, already_received); 791 } 792 793 /* 794 * This function just provide calculated blocktime per cpu and trace it. 795 * Total blocktime is calculated in mark_postcopy_blocktime_end. 796 * 797 * 798 * Assume we have 3 CPU 799 * 800 * S1 E1 S1 E1 801 * -----***********------------xxx***************------------------------> CPU1 802 * 803 * S2 E2 804 * ------------****************xxx---------------------------------------> CPU2 805 * 806 * S3 E3 807 * ------------------------****xxx********-------------------------------> CPU3 808 * 809 * We have sequence S1,S2,E1,S3,S1,E2,E3,E1 810 * S2,E1 - doesn't match condition due to sequence S1,S2,E1 doesn't include CPU3 811 * S3,S1,E2 - sequence includes all CPUs, in this case overlap will be S1,E2 - 812 * it's a part of total blocktime. 813 * S1 - here is last_begin 814 * Legend of the picture is following: 815 * * - means blocktime per vCPU 816 * x - means overlapped blocktime (total blocktime) 817 * 818 * @addr: host virtual address 819 */ 820 static void mark_postcopy_blocktime_end(uintptr_t addr) 821 { 822 MigrationIncomingState *mis = migration_incoming_get_current(); 823 PostcopyBlocktimeContext *dc = mis->blocktime_ctx; 824 MachineState *ms = MACHINE(qdev_get_machine()); 825 unsigned int smp_cpus = ms->smp.cpus; 826 int i, affected_cpu = 0; 827 bool vcpu_total_blocktime = false; 828 uint32_t read_vcpu_time, low_time_offset; 829 830 if (!dc) { 831 return; 832 } 833 834 low_time_offset = get_low_time_offset(dc); 835 /* lookup cpu, to clear it, 836 * that algorithm looks straightforward, but it's not 837 * optimal, more optimal algorithm is keeping tree or hash 838 * where key is address value is a list of */ 839 for (i = 0; i < smp_cpus; i++) { 840 uint32_t vcpu_blocktime = 0; 841 842 read_vcpu_time = qatomic_fetch_add(&dc->page_fault_vcpu_time[i], 0); 843 if (qatomic_fetch_add(&dc->vcpu_addr[i], 0) != addr || 844 read_vcpu_time == 0) { 845 continue; 846 } 847 qatomic_xchg(&dc->vcpu_addr[i], 0); 848 vcpu_blocktime = low_time_offset - read_vcpu_time; 849 affected_cpu += 1; 850 /* we need to know is that mark_postcopy_end was due to 851 * faulted page, another possible case it's prefetched 852 * page and in that case we shouldn't be here */ 853 if (!vcpu_total_blocktime && 854 qatomic_fetch_add(&dc->smp_cpus_down, 0) == smp_cpus) { 855 vcpu_total_blocktime = true; 856 } 857 /* continue cycle, due to one page could affect several vCPUs */ 858 dc->vcpu_blocktime[i] += vcpu_blocktime; 859 } 860 861 qatomic_sub(&dc->smp_cpus_down, affected_cpu); 862 if (vcpu_total_blocktime) { 863 dc->total_blocktime += low_time_offset - qatomic_fetch_add( 864 &dc->last_begin, 0); 865 } 866 trace_mark_postcopy_blocktime_end(addr, dc, dc->total_blocktime, 867 affected_cpu); 868 } 869 870 static bool postcopy_pause_fault_thread(MigrationIncomingState *mis) 871 { 872 trace_postcopy_pause_fault_thread(); 873 874 qemu_sem_wait(&mis->postcopy_pause_sem_fault); 875 876 trace_postcopy_pause_fault_thread_continued(); 877 878 return true; 879 } 880 881 /* 882 * Handle faults detected by the USERFAULT markings 883 */ 884 static void *postcopy_ram_fault_thread(void *opaque) 885 { 886 MigrationIncomingState *mis = opaque; 887 struct uffd_msg msg; 888 int ret; 889 size_t index; 890 RAMBlock *rb = NULL; 891 892 trace_postcopy_ram_fault_thread_entry(); 893 rcu_register_thread(); 894 mis->last_rb = NULL; /* last RAMBlock we sent part of */ 895 qemu_sem_post(&mis->fault_thread_sem); 896 897 struct pollfd *pfd; 898 size_t pfd_len = 2 + mis->postcopy_remote_fds->len; 899 900 pfd = g_new0(struct pollfd, pfd_len); 901 902 pfd[0].fd = mis->userfault_fd; 903 pfd[0].events = POLLIN; 904 pfd[1].fd = mis->userfault_event_fd; 905 pfd[1].events = POLLIN; /* Waiting for eventfd to go positive */ 906 trace_postcopy_ram_fault_thread_fds_core(pfd[0].fd, pfd[1].fd); 907 for (index = 0; index < mis->postcopy_remote_fds->len; index++) { 908 struct PostCopyFD *pcfd = &g_array_index(mis->postcopy_remote_fds, 909 struct PostCopyFD, index); 910 pfd[2 + index].fd = pcfd->fd; 911 pfd[2 + index].events = POLLIN; 912 trace_postcopy_ram_fault_thread_fds_extra(2 + index, pcfd->idstr, 913 pcfd->fd); 914 } 915 916 while (true) { 917 ram_addr_t rb_offset; 918 int poll_result; 919 920 /* 921 * We're mainly waiting for the kernel to give us a faulting HVA, 922 * however we can be told to quit via userfault_quit_fd which is 923 * an eventfd 924 */ 925 926 poll_result = poll(pfd, pfd_len, -1 /* Wait forever */); 927 if (poll_result == -1) { 928 error_report("%s: userfault poll: %s", __func__, strerror(errno)); 929 break; 930 } 931 932 if (!mis->to_src_file) { 933 /* 934 * Possibly someone tells us that the return path is 935 * broken already using the event. We should hold until 936 * the channel is rebuilt. 937 */ 938 if (postcopy_pause_fault_thread(mis)) { 939 /* Continue to read the userfaultfd */ 940 } else { 941 error_report("%s: paused but don't allow to continue", 942 __func__); 943 break; 944 } 945 } 946 947 if (pfd[1].revents) { 948 uint64_t tmp64 = 0; 949 950 /* Consume the signal */ 951 if (read(mis->userfault_event_fd, &tmp64, 8) != 8) { 952 /* Nothing obviously nicer than posting this error. */ 953 error_report("%s: read() failed", __func__); 954 } 955 956 if (qatomic_read(&mis->fault_thread_quit)) { 957 trace_postcopy_ram_fault_thread_quit(); 958 break; 959 } 960 } 961 962 if (pfd[0].revents) { 963 poll_result--; 964 ret = read(mis->userfault_fd, &msg, sizeof(msg)); 965 if (ret != sizeof(msg)) { 966 if (errno == EAGAIN) { 967 /* 968 * if a wake up happens on the other thread just after 969 * the poll, there is nothing to read. 970 */ 971 continue; 972 } 973 if (ret < 0) { 974 error_report("%s: Failed to read full userfault " 975 "message: %s", 976 __func__, strerror(errno)); 977 break; 978 } else { 979 error_report("%s: Read %d bytes from userfaultfd " 980 "expected %zd", 981 __func__, ret, sizeof(msg)); 982 break; /* Lost alignment, don't know what we'd read next */ 983 } 984 } 985 if (msg.event != UFFD_EVENT_PAGEFAULT) { 986 error_report("%s: Read unexpected event %ud from userfaultfd", 987 __func__, msg.event); 988 continue; /* It's not a page fault, shouldn't happen */ 989 } 990 991 rb = qemu_ram_block_from_host( 992 (void *)(uintptr_t)msg.arg.pagefault.address, 993 true, &rb_offset); 994 if (!rb) { 995 error_report("postcopy_ram_fault_thread: Fault outside guest: %" 996 PRIx64, (uint64_t)msg.arg.pagefault.address); 997 break; 998 } 999 1000 rb_offset = ROUND_DOWN(rb_offset, qemu_ram_pagesize(rb)); 1001 trace_postcopy_ram_fault_thread_request(msg.arg.pagefault.address, 1002 qemu_ram_get_idstr(rb), 1003 rb_offset, 1004 msg.arg.pagefault.feat.ptid); 1005 mark_postcopy_blocktime_begin( 1006 (uintptr_t)(msg.arg.pagefault.address), 1007 msg.arg.pagefault.feat.ptid, rb); 1008 1009 retry: 1010 /* 1011 * Send the request to the source - we want to request one 1012 * of our host page sizes (which is >= TPS) 1013 */ 1014 ret = postcopy_request_page(mis, rb, rb_offset, 1015 msg.arg.pagefault.address); 1016 if (ret) { 1017 /* May be network failure, try to wait for recovery */ 1018 if (ret == -EIO && postcopy_pause_fault_thread(mis)) { 1019 /* We got reconnected somehow, try to continue */ 1020 goto retry; 1021 } else { 1022 /* This is a unavoidable fault */ 1023 error_report("%s: postcopy_request_page() get %d", 1024 __func__, ret); 1025 break; 1026 } 1027 } 1028 } 1029 1030 /* Now handle any requests from external processes on shared memory */ 1031 /* TODO: May need to handle devices deregistering during postcopy */ 1032 for (index = 2; index < pfd_len && poll_result; index++) { 1033 if (pfd[index].revents) { 1034 struct PostCopyFD *pcfd = 1035 &g_array_index(mis->postcopy_remote_fds, 1036 struct PostCopyFD, index - 2); 1037 1038 poll_result--; 1039 if (pfd[index].revents & POLLERR) { 1040 error_report("%s: POLLERR on poll %zd fd=%d", 1041 __func__, index, pcfd->fd); 1042 pfd[index].events = 0; 1043 continue; 1044 } 1045 1046 ret = read(pcfd->fd, &msg, sizeof(msg)); 1047 if (ret != sizeof(msg)) { 1048 if (errno == EAGAIN) { 1049 /* 1050 * if a wake up happens on the other thread just after 1051 * the poll, there is nothing to read. 1052 */ 1053 continue; 1054 } 1055 if (ret < 0) { 1056 error_report("%s: Failed to read full userfault " 1057 "message: %s (shared) revents=%d", 1058 __func__, strerror(errno), 1059 pfd[index].revents); 1060 /*TODO: Could just disable this sharer */ 1061 break; 1062 } else { 1063 error_report("%s: Read %d bytes from userfaultfd " 1064 "expected %zd (shared)", 1065 __func__, ret, sizeof(msg)); 1066 /*TODO: Could just disable this sharer */ 1067 break; /*Lost alignment,don't know what we'd read next*/ 1068 } 1069 } 1070 if (msg.event != UFFD_EVENT_PAGEFAULT) { 1071 error_report("%s: Read unexpected event %ud " 1072 "from userfaultfd (shared)", 1073 __func__, msg.event); 1074 continue; /* It's not a page fault, shouldn't happen */ 1075 } 1076 /* Call the device handler registered with us */ 1077 ret = pcfd->handler(pcfd, &msg); 1078 if (ret) { 1079 error_report("%s: Failed to resolve shared fault on %zd/%s", 1080 __func__, index, pcfd->idstr); 1081 /* TODO: Fail? Disable this sharer? */ 1082 } 1083 } 1084 } 1085 } 1086 rcu_unregister_thread(); 1087 trace_postcopy_ram_fault_thread_exit(); 1088 g_free(pfd); 1089 return NULL; 1090 } 1091 1092 static int postcopy_temp_pages_setup(MigrationIncomingState *mis) 1093 { 1094 int err; 1095 1096 mis->postcopy_tmp_page = mmap(NULL, mis->largest_page_size, 1097 PROT_READ | PROT_WRITE, 1098 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); 1099 if (mis->postcopy_tmp_page == MAP_FAILED) { 1100 err = errno; 1101 mis->postcopy_tmp_page = NULL; 1102 error_report("%s: Failed to map postcopy_tmp_page %s", 1103 __func__, strerror(err)); 1104 return -err; 1105 } 1106 1107 /* 1108 * Map large zero page when kernel can't use UFFDIO_ZEROPAGE for hugepages 1109 */ 1110 mis->postcopy_tmp_zero_page = mmap(NULL, mis->largest_page_size, 1111 PROT_READ | PROT_WRITE, 1112 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); 1113 if (mis->postcopy_tmp_zero_page == MAP_FAILED) { 1114 err = errno; 1115 mis->postcopy_tmp_zero_page = NULL; 1116 error_report("%s: Failed to map large zero page %s", 1117 __func__, strerror(err)); 1118 return -err; 1119 } 1120 1121 memset(mis->postcopy_tmp_zero_page, '\0', mis->largest_page_size); 1122 1123 return 0; 1124 } 1125 1126 int postcopy_ram_incoming_setup(MigrationIncomingState *mis) 1127 { 1128 /* Open the fd for the kernel to give us userfaults */ 1129 mis->userfault_fd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK); 1130 if (mis->userfault_fd == -1) { 1131 error_report("%s: Failed to open userfault fd: %s", __func__, 1132 strerror(errno)); 1133 return -1; 1134 } 1135 1136 /* 1137 * Although the host check already tested the API, we need to 1138 * do the check again as an ABI handshake on the new fd. 1139 */ 1140 if (!ufd_check_and_apply(mis->userfault_fd, mis)) { 1141 return -1; 1142 } 1143 1144 /* Now an eventfd we use to tell the fault-thread to quit */ 1145 mis->userfault_event_fd = eventfd(0, EFD_CLOEXEC); 1146 if (mis->userfault_event_fd == -1) { 1147 error_report("%s: Opening userfault_event_fd: %s", __func__, 1148 strerror(errno)); 1149 close(mis->userfault_fd); 1150 return -1; 1151 } 1152 1153 qemu_sem_init(&mis->fault_thread_sem, 0); 1154 qemu_thread_create(&mis->fault_thread, "postcopy/fault", 1155 postcopy_ram_fault_thread, mis, QEMU_THREAD_JOINABLE); 1156 qemu_sem_wait(&mis->fault_thread_sem); 1157 qemu_sem_destroy(&mis->fault_thread_sem); 1158 mis->have_fault_thread = true; 1159 1160 /* Mark so that we get notified of accesses to unwritten areas */ 1161 if (foreach_not_ignored_block(ram_block_enable_notify, mis)) { 1162 error_report("ram_block_enable_notify failed"); 1163 return -1; 1164 } 1165 1166 if (postcopy_temp_pages_setup(mis)) { 1167 /* Error dumped in the sub-function */ 1168 return -1; 1169 } 1170 1171 trace_postcopy_ram_enable_notify(); 1172 1173 return 0; 1174 } 1175 1176 static int qemu_ufd_copy_ioctl(MigrationIncomingState *mis, void *host_addr, 1177 void *from_addr, uint64_t pagesize, RAMBlock *rb) 1178 { 1179 int userfault_fd = mis->userfault_fd; 1180 int ret; 1181 1182 if (from_addr) { 1183 struct uffdio_copy copy_struct; 1184 copy_struct.dst = (uint64_t)(uintptr_t)host_addr; 1185 copy_struct.src = (uint64_t)(uintptr_t)from_addr; 1186 copy_struct.len = pagesize; 1187 copy_struct.mode = 0; 1188 ret = ioctl(userfault_fd, UFFDIO_COPY, ©_struct); 1189 } else { 1190 struct uffdio_zeropage zero_struct; 1191 zero_struct.range.start = (uint64_t)(uintptr_t)host_addr; 1192 zero_struct.range.len = pagesize; 1193 zero_struct.mode = 0; 1194 ret = ioctl(userfault_fd, UFFDIO_ZEROPAGE, &zero_struct); 1195 } 1196 if (!ret) { 1197 qemu_mutex_lock(&mis->page_request_mutex); 1198 ramblock_recv_bitmap_set_range(rb, host_addr, 1199 pagesize / qemu_target_page_size()); 1200 /* 1201 * If this page resolves a page fault for a previous recorded faulted 1202 * address, take a special note to maintain the requested page list. 1203 */ 1204 if (g_tree_lookup(mis->page_requested, host_addr)) { 1205 g_tree_remove(mis->page_requested, host_addr); 1206 mis->page_requested_count--; 1207 trace_postcopy_page_req_del(host_addr, mis->page_requested_count); 1208 } 1209 qemu_mutex_unlock(&mis->page_request_mutex); 1210 mark_postcopy_blocktime_end((uintptr_t)host_addr); 1211 } 1212 return ret; 1213 } 1214 1215 int postcopy_notify_shared_wake(RAMBlock *rb, uint64_t offset) 1216 { 1217 int i; 1218 MigrationIncomingState *mis = migration_incoming_get_current(); 1219 GArray *pcrfds = mis->postcopy_remote_fds; 1220 1221 for (i = 0; i < pcrfds->len; i++) { 1222 struct PostCopyFD *cur = &g_array_index(pcrfds, struct PostCopyFD, i); 1223 int ret = cur->waker(cur, rb, offset); 1224 if (ret) { 1225 return ret; 1226 } 1227 } 1228 return 0; 1229 } 1230 1231 /* 1232 * Place a host page (from) at (host) atomically 1233 * returns 0 on success 1234 */ 1235 int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from, 1236 RAMBlock *rb) 1237 { 1238 size_t pagesize = qemu_ram_pagesize(rb); 1239 1240 /* copy also acks to the kernel waking the stalled thread up 1241 * TODO: We can inhibit that ack and only do it if it was requested 1242 * which would be slightly cheaper, but we'd have to be careful 1243 * of the order of updating our page state. 1244 */ 1245 if (qemu_ufd_copy_ioctl(mis, host, from, pagesize, rb)) { 1246 int e = errno; 1247 error_report("%s: %s copy host: %p from: %p (size: %zd)", 1248 __func__, strerror(e), host, from, pagesize); 1249 1250 return -e; 1251 } 1252 1253 trace_postcopy_place_page(host); 1254 return postcopy_notify_shared_wake(rb, 1255 qemu_ram_block_host_offset(rb, host)); 1256 } 1257 1258 /* 1259 * Place a zero page at (host) atomically 1260 * returns 0 on success 1261 */ 1262 int postcopy_place_page_zero(MigrationIncomingState *mis, void *host, 1263 RAMBlock *rb) 1264 { 1265 size_t pagesize = qemu_ram_pagesize(rb); 1266 trace_postcopy_place_page_zero(host); 1267 1268 /* Normal RAMBlocks can zero a page using UFFDIO_ZEROPAGE 1269 * but it's not available for everything (e.g. hugetlbpages) 1270 */ 1271 if (qemu_ram_is_uf_zeroable(rb)) { 1272 if (qemu_ufd_copy_ioctl(mis, host, NULL, pagesize, rb)) { 1273 int e = errno; 1274 error_report("%s: %s zero host: %p", 1275 __func__, strerror(e), host); 1276 1277 return -e; 1278 } 1279 return postcopy_notify_shared_wake(rb, 1280 qemu_ram_block_host_offset(rb, 1281 host)); 1282 } else { 1283 return postcopy_place_page(mis, host, mis->postcopy_tmp_zero_page, rb); 1284 } 1285 } 1286 1287 #else 1288 /* No target OS support, stubs just fail */ 1289 void fill_destination_postcopy_migration_info(MigrationInfo *info) 1290 { 1291 } 1292 1293 bool postcopy_ram_supported_by_host(MigrationIncomingState *mis) 1294 { 1295 error_report("%s: No OS support", __func__); 1296 return false; 1297 } 1298 1299 int postcopy_ram_incoming_init(MigrationIncomingState *mis) 1300 { 1301 error_report("postcopy_ram_incoming_init: No OS support"); 1302 return -1; 1303 } 1304 1305 int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis) 1306 { 1307 assert(0); 1308 return -1; 1309 } 1310 1311 int postcopy_ram_prepare_discard(MigrationIncomingState *mis) 1312 { 1313 assert(0); 1314 return -1; 1315 } 1316 1317 int postcopy_request_shared_page(struct PostCopyFD *pcfd, RAMBlock *rb, 1318 uint64_t client_addr, uint64_t rb_offset) 1319 { 1320 assert(0); 1321 return -1; 1322 } 1323 1324 int postcopy_ram_incoming_setup(MigrationIncomingState *mis) 1325 { 1326 assert(0); 1327 return -1; 1328 } 1329 1330 int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from, 1331 RAMBlock *rb) 1332 { 1333 assert(0); 1334 return -1; 1335 } 1336 1337 int postcopy_place_page_zero(MigrationIncomingState *mis, void *host, 1338 RAMBlock *rb) 1339 { 1340 assert(0); 1341 return -1; 1342 } 1343 1344 int postcopy_wake_shared(struct PostCopyFD *pcfd, 1345 uint64_t client_addr, 1346 RAMBlock *rb) 1347 { 1348 assert(0); 1349 return -1; 1350 } 1351 #endif 1352 1353 /* ------------------------------------------------------------------------- */ 1354 1355 void postcopy_fault_thread_notify(MigrationIncomingState *mis) 1356 { 1357 uint64_t tmp64 = 1; 1358 1359 /* 1360 * Wakeup the fault_thread. It's an eventfd that should currently 1361 * be at 0, we're going to increment it to 1 1362 */ 1363 if (write(mis->userfault_event_fd, &tmp64, 8) != 8) { 1364 /* Not much we can do here, but may as well report it */ 1365 error_report("%s: incrementing failed: %s", __func__, 1366 strerror(errno)); 1367 } 1368 } 1369 1370 /** 1371 * postcopy_discard_send_init: Called at the start of each RAMBlock before 1372 * asking to discard individual ranges. 1373 * 1374 * @ms: The current migration state. 1375 * @offset: the bitmap offset of the named RAMBlock in the migration bitmap. 1376 * @name: RAMBlock that discards will operate on. 1377 */ 1378 static PostcopyDiscardState pds = {0}; 1379 void postcopy_discard_send_init(MigrationState *ms, const char *name) 1380 { 1381 pds.ramblock_name = name; 1382 pds.cur_entry = 0; 1383 pds.nsentwords = 0; 1384 pds.nsentcmds = 0; 1385 } 1386 1387 /** 1388 * postcopy_discard_send_range: Called by the bitmap code for each chunk to 1389 * discard. May send a discard message, may just leave it queued to 1390 * be sent later. 1391 * 1392 * @ms: Current migration state. 1393 * @start,@length: a range of pages in the migration bitmap in the 1394 * RAM block passed to postcopy_discard_send_init() (length=1 is one page) 1395 */ 1396 void postcopy_discard_send_range(MigrationState *ms, unsigned long start, 1397 unsigned long length) 1398 { 1399 size_t tp_size = qemu_target_page_size(); 1400 /* Convert to byte offsets within the RAM block */ 1401 pds.start_list[pds.cur_entry] = start * tp_size; 1402 pds.length_list[pds.cur_entry] = length * tp_size; 1403 trace_postcopy_discard_send_range(pds.ramblock_name, start, length); 1404 pds.cur_entry++; 1405 pds.nsentwords++; 1406 1407 if (pds.cur_entry == MAX_DISCARDS_PER_COMMAND) { 1408 /* Full set, ship it! */ 1409 qemu_savevm_send_postcopy_ram_discard(ms->to_dst_file, 1410 pds.ramblock_name, 1411 pds.cur_entry, 1412 pds.start_list, 1413 pds.length_list); 1414 pds.nsentcmds++; 1415 pds.cur_entry = 0; 1416 } 1417 } 1418 1419 /** 1420 * postcopy_discard_send_finish: Called at the end of each RAMBlock by the 1421 * bitmap code. Sends any outstanding discard messages, frees the PDS 1422 * 1423 * @ms: Current migration state. 1424 */ 1425 void postcopy_discard_send_finish(MigrationState *ms) 1426 { 1427 /* Anything unsent? */ 1428 if (pds.cur_entry) { 1429 qemu_savevm_send_postcopy_ram_discard(ms->to_dst_file, 1430 pds.ramblock_name, 1431 pds.cur_entry, 1432 pds.start_list, 1433 pds.length_list); 1434 pds.nsentcmds++; 1435 } 1436 1437 trace_postcopy_discard_send_finish(pds.ramblock_name, pds.nsentwords, 1438 pds.nsentcmds); 1439 } 1440 1441 /* 1442 * Current state of incoming postcopy; note this is not part of 1443 * MigrationIncomingState since it's state is used during cleanup 1444 * at the end as MIS is being freed. 1445 */ 1446 static PostcopyState incoming_postcopy_state; 1447 1448 PostcopyState postcopy_state_get(void) 1449 { 1450 return qatomic_mb_read(&incoming_postcopy_state); 1451 } 1452 1453 /* Set the state and return the old state */ 1454 PostcopyState postcopy_state_set(PostcopyState new_state) 1455 { 1456 return qatomic_xchg(&incoming_postcopy_state, new_state); 1457 } 1458 1459 /* Register a handler for external shared memory postcopy 1460 * called on the destination. 1461 */ 1462 void postcopy_register_shared_ufd(struct PostCopyFD *pcfd) 1463 { 1464 MigrationIncomingState *mis = migration_incoming_get_current(); 1465 1466 mis->postcopy_remote_fds = g_array_append_val(mis->postcopy_remote_fds, 1467 *pcfd); 1468 } 1469 1470 /* Unregister a handler for external shared memory postcopy 1471 */ 1472 void postcopy_unregister_shared_ufd(struct PostCopyFD *pcfd) 1473 { 1474 guint i; 1475 MigrationIncomingState *mis = migration_incoming_get_current(); 1476 GArray *pcrfds = mis->postcopy_remote_fds; 1477 1478 if (!pcrfds) { 1479 /* migration has already finished and freed the array */ 1480 return; 1481 } 1482 for (i = 0; i < pcrfds->len; i++) { 1483 struct PostCopyFD *cur = &g_array_index(pcrfds, struct PostCopyFD, i); 1484 if (cur->fd == pcfd->fd) { 1485 mis->postcopy_remote_fds = g_array_remove_index(pcrfds, i); 1486 return; 1487 } 1488 } 1489 } 1490