hw/intc/arm_gicv3_its: Use address_space_map() to access command queue packets
[qemu/rayw.git] / migration / postcopy-ram.c
blobe662dd05ccfbd40622cfb8866273fbe079e76e9a
1 /*
2 * Postcopy migration for RAM
4 * Copyright 2013-2015 Red Hat, Inc. and/or its affiliates
6 * Authors:
7 * Dave Gilbert <dgilbert@redhat.com>
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.
15 * Postcopy is a migration technique where the execution flips from the
16 * source to the destination before all the data has been copied.
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"
36 /* Arbitrary limit on size of each discard command,
37 * keeps them around ~200 bytes
39 #define MAX_DISCARDS_PER_COMMAND 12
41 struct PostcopyDiscardState {
42 const char *ramblock_name;
43 uint16_t cur_entry;
45 * Start and length of a discard range (bytes)
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;
53 static NotifierWithReturnList postcopy_notifier_list;
55 void postcopy_infrastructure_init(void)
57 notifier_with_return_list_init(&postcopy_notifier_list);
60 void postcopy_add_notifier(NotifierWithReturn *nn)
62 notifier_with_return_list_add(&postcopy_notifier_list, nn);
65 void postcopy_remove_notifier(NotifierWithReturn *n)
67 notifier_with_return_remove(n);
70 int postcopy_notify(enum PostcopyNotifyReason reason, Error **errp)
72 struct PostcopyNotifyData pnd;
73 pnd.reason = reason;
74 pnd.errp = errp;
76 return notifier_with_return_list_notify(&postcopy_notifier_list,
77 &pnd);
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.
84 #if defined(__linux__)
86 #include <poll.h>
87 #include <sys/ioctl.h>
88 #include <sys/syscall.h>
89 #include <asm/types.h> /* for __u64 */
90 #endif
92 #if defined(__linux__) && defined(__NR_userfaultfd) && defined(CONFIG_EVENTFD)
93 #include <sys/eventfd.h>
94 #include <linux/userfaultfd.h>
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;
111 * Handler for exit event, necessary for
112 * releasing whole blocktime_ctx
114 Notifier exit_notifier;
115 } PostcopyBlocktimeContext;
117 static void destroy_blocktime_context(struct PostcopyBlocktimeContext *ctx)
119 g_free(ctx->page_fault_vcpu_time);
120 g_free(ctx->vcpu_addr);
121 g_free(ctx->vcpu_blocktime);
122 g_free(ctx);
125 static void migration_exit_cb(Notifier *n, void *data)
127 PostcopyBlocktimeContext *ctx = container_of(n, PostcopyBlocktimeContext,
128 exit_notifier);
129 destroy_blocktime_context(ctx);
132 static struct PostcopyBlocktimeContext *blocktime_context_new(void)
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);
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;
147 static uint32List *get_vcpu_blocktime_list(PostcopyBlocktimeContext *ctx)
149 MachineState *ms = MACHINE(qdev_get_machine());
150 uint32List *list = NULL;
151 int i;
153 for (i = ms->smp.cpus - 1; i >= 0; i--) {
154 QAPI_LIST_PREPEND(list, ctx->vcpu_blocktime[i]);
157 return list;
161 * This function just populates MigrationInfo from postcopy's
162 * blocktime context. It will not populate MigrationInfo,
163 * unless postcopy-blocktime capability was set.
165 * @info: pointer to MigrationInfo to populate
167 void fill_destination_postcopy_migration_info(MigrationInfo *info)
169 MigrationIncomingState *mis = migration_incoming_get_current();
170 PostcopyBlocktimeContext *bc = mis->blocktime_ctx;
172 if (!bc) {
173 return;
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);
182 static uint32_t get_postcopy_total_blocktime(void)
184 MigrationIncomingState *mis = migration_incoming_get_current();
185 PostcopyBlocktimeContext *bc = mis->blocktime_ctx;
187 if (!bc) {
188 return 0;
191 return bc->total_blocktime;
195 * receive_ufd_features: check userfault fd features, to request only supported
196 * features in the future.
198 * Returns: true on success
200 * __NR_userfaultfd - should be checked before
201 * @features: out parameter will contain uffdio_api.features provided by kernel
202 * in case of success
204 static bool receive_ufd_features(uint64_t *features)
206 struct uffdio_api api_struct = {0};
207 int ufd;
208 bool ret = true;
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;
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;
228 *features = api_struct.features;
230 release_ufd:
231 close(ufd);
232 return ret;
236 * request_ufd_features: this function should be called only once on a newly
237 * opened ufd, subsequent calls will lead to error.
239 * Returns: true on success
241 * @ufd: fd obtained from userfaultfd syscall
242 * @features: bit mask see UFFD_API_FEATURES
244 static bool request_ufd_features(int ufd, uint64_t features)
246 struct uffdio_api api_struct = {0};
247 uint64_t ioctl_mask;
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;
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;
265 return true;
268 static bool ufd_check_and_apply(int ufd, MigrationIncomingState *mis)
270 uint64_t asked_features = 0;
271 static uint64_t supported_features;
274 * it's not possible to
275 * request UFFD_API twice per one fd
276 * userfault fd features is persistent
278 if (!supported_features) {
279 if (!receive_ufd_features(&supported_features)) {
280 error_report("%s failed", __func__);
281 return false;
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();
294 #endif
297 * request features, even if asked_features is 0, due to
298 * kernel expects UFFD_API before UFFDIO_REGISTER, per
299 * userfault file descriptor
301 if (!request_ufd_features(ufd, asked_features)) {
302 error_report("%s failed: features %" PRIu64, __func__,
303 asked_features);
304 return false;
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;
318 return true;
321 /* Callback from postcopy_ram_supported_by_host block iterator.
323 static int test_ramblock_postcopiable(RAMBlock *rb, void *opaque)
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);
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;
335 return 0;
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.
343 bool postcopy_ram_supported_by_host(MigrationIncomingState *mis)
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;
354 if (qemu_target_page_size() > pagesize) {
355 error_report("Target page size bigger than host page size");
356 goto out;
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;
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;
372 /* Version and features check */
373 if (!ufd_check_and_apply(ufd, mis)) {
374 goto out;
377 /* We don't support postcopy with shared RAM yet */
378 if (foreach_not_ignored_block(test_ramblock_postcopiable, NULL)) {
379 goto out;
383 * userfault and mlock don't go together; we'll put it back later if
384 * it was enabled.
386 if (munlockall()) {
387 error_report("%s: munlockall: %s", __func__, strerror(errno));
388 goto out;
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.
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;
403 g_assert(QEMU_PTR_IS_ALIGNED(testarea, pagesize));
405 reg_struct.range.start = (uintptr_t)testarea;
406 reg_struct.range.len = pagesize;
407 reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING;
409 if (ioctl(ufd, UFFDIO_REGISTER, &reg_struct)) {
410 error_report("%s userfault register: %s", __func__, strerror(errno));
411 goto out;
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;
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;
430 /* Success! */
431 ret = true;
432 out:
433 if (testarea) {
434 munmap(testarea, pagesize);
436 if (ufd != -1) {
437 close(ufd);
439 return ret;
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.
447 static int init_range(RAMBlock *rb, void *opaque)
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);
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.
460 rb->postcopy_length = length;
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)
468 if (ram_discard_range(block_name, 0, length)) {
469 return -1;
472 return 0;
476 * At the end of migration, undo the effects of init_range
477 * opaque should be the MIS.
479 static int cleanup_range(RAMBlock *rb, void *opaque)
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);
490 * We turned off hugepage for the precopy stage with postcopy enabled
491 * we can turn it back on now.
493 qemu_madvise(host_addr, length, QEMU_MADV_HUGEPAGE);
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.
500 range_struct.start = (uintptr_t)host_addr;
501 range_struct.len = length;
503 if (ioctl(mis->userfault_fd, UFFDIO_UNREGISTER, &range_struct)) {
504 error_report("%s: userfault unregister %s", __func__, strerror(errno));
506 return -1;
509 return 0;
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
517 int postcopy_ram_incoming_init(MigrationIncomingState *mis)
519 if (foreach_not_ignored_block(init_range, NULL)) {
520 return -1;
523 return 0;
526 static void postcopy_temp_pages_cleanup(MigrationIncomingState *mis)
528 if (mis->postcopy_tmp_page) {
529 munmap(mis->postcopy_tmp_page, mis->largest_page_size);
530 mis->postcopy_tmp_page = NULL;
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;
540 * At the end of a migration where postcopy_ram_incoming_init was called.
542 int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
544 trace_postcopy_ram_incoming_cleanup_entry();
546 if (mis->have_fault_thread) {
547 Error *local_err = NULL;
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);
555 if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_END, &local_err)) {
556 error_report_err(local_err);
557 return -1;
560 if (foreach_not_ignored_block(cleanup_range, mis)) {
561 return -1;
564 trace_postcopy_ram_incoming_cleanup_closeuf();
565 close(mis->userfault_fd);
566 close(mis->userfault_event_fd);
567 mis->have_fault_thread = false;
570 if (enable_mlock) {
571 if (os_mlock() < 0) {
572 error_report("mlock: %s", strerror(errno));
574 * It doesn't feel right to fail at this point, we have a valid
575 * VM state.
580 postcopy_temp_pages_cleanup(mis);
582 trace_postcopy_ram_incoming_cleanup_blocktime(
583 get_postcopy_total_blocktime());
585 trace_postcopy_ram_incoming_cleanup_exit();
586 return 0;
590 * Disable huge pages on an area
592 static int nhp_range(RAMBlock *rb, void *opaque)
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);
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.
605 qemu_madvise(host_addr, length, QEMU_MADV_NOHUGEPAGE);
607 return 0;
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
615 int postcopy_ram_prepare_discard(MigrationIncomingState *mis)
617 if (foreach_not_ignored_block(nhp_range, mis)) {
618 return -1;
621 postcopy_state_set(POSTCOPY_INCOMING_DISCARD);
623 return 0;
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
635 static int ram_block_enable_notify(RAMBlock *rb, void *opaque)
637 MigrationIncomingState *mis = opaque;
638 struct uffdio_register reg_struct;
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;
644 /* Now tell our userfault_fd that it's responsible for this area */
645 if (ioctl(mis->userfault_fd, UFFDIO_REGISTER, &reg_struct)) {
646 error_report("%s userfault register: %s", __func__, strerror(errno));
647 return -1;
649 if (!(reg_struct.ioctls & ((__u64)1 << _UFFDIO_COPY))) {
650 error_report("%s userfault: Region doesn't support COPY", __func__);
651 return -1;
653 if (reg_struct.ioctls & ((__u64)1 << _UFFDIO_ZEROPAGE)) {
654 qemu_ram_set_uf_zeroable(rb);
657 return 0;
660 int postcopy_wake_shared(struct PostCopyFD *pcfd,
661 uint64_t client_addr,
662 RAMBlock *rb)
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));
676 return ret;
679 static int postcopy_request_page(MigrationIncomingState *mis, RAMBlock *rb,
680 ram_addr_t start, uint64_t haddr)
682 void *aligned = (void *)(uintptr_t)ROUND_DOWN(haddr, qemu_ram_pagesize(rb));
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.
689 * Checking a single bit is sufficient to handle pagesize > TPS as either
690 * all relevant bits are set or not.
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);
696 return received ? 0 : postcopy_place_page_zero(mis, aligned, rb);
699 return migrate_send_rp_req_pages(mis, rb, start, haddr);
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)
707 int postcopy_request_shared_page(struct PostCopyFD *pcfd, RAMBlock *rb,
708 uint64_t client_addr, uint64_t rb_offset)
710 uint64_t aligned_rbo = ROUND_DOWN(rb_offset, qemu_ram_pagesize(rb));
711 MigrationIncomingState *mis = migration_incoming_get_current();
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);
720 postcopy_request_page(mis, rb, aligned_rbo, client_addr);
721 return 0;
724 static int get_mem_fault_cpu_index(uint32_t pid)
726 CPUState *cpu_iter;
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;
734 trace_get_mem_fault_cpu_index(-1, pid);
735 return -1;
738 static uint32_t get_low_time_offset(PostcopyBlocktimeContext *dc)
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;
746 * This function is being called when pagefault occurs. It
747 * tracks down vCPU blocking time.
749 * @addr: faulted host virtual address
750 * @ptid: faulted process thread id
751 * @rb: ramblock appropriate to addr
753 static void mark_postcopy_blocktime_begin(uintptr_t addr, uint32_t ptid,
754 RAMBlock *rb)
756 int cpu, already_received;
757 MigrationIncomingState *mis = migration_incoming_get_current();
758 PostcopyBlocktimeContext *dc = mis->blocktime_ctx;
759 uint32_t low_time_offset;
761 if (!dc || ptid == 0) {
762 return;
764 cpu = get_mem_fault_cpu_index(ptid);
765 if (cpu < 0) {
766 return;
769 low_time_offset = get_low_time_offset(dc);
770 if (dc->vcpu_addr[cpu] == 0) {
771 qatomic_inc(&dc->smp_cpus_down);
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);
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
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);
789 trace_mark_postcopy_blocktime_begin(addr, dc, dc->page_fault_vcpu_time[cpu],
790 cpu, already_received);
794 * This function just provide calculated blocktime per cpu and trace it.
795 * Total blocktime is calculated in mark_postcopy_blocktime_end.
798 * Assume we have 3 CPU
800 * S1 E1 S1 E1
801 * -----***********------------xxx***************------------------------> CPU1
803 * S2 E2
804 * ------------****************xxx---------------------------------------> CPU2
806 * S3 E3
807 * ------------------------****xxx********-------------------------------> CPU3
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)
818 * @addr: host virtual address
820 static void mark_postcopy_blocktime_end(uintptr_t addr)
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;
830 if (!dc) {
831 return;
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;
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;
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;
857 /* continue cycle, due to one page could affect several vCPUs */
858 dc->vcpu_blocktime[i] += vcpu_blocktime;
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);
866 trace_mark_postcopy_blocktime_end(addr, dc, dc->total_blocktime,
867 affected_cpu);
870 static bool postcopy_pause_fault_thread(MigrationIncomingState *mis)
872 trace_postcopy_pause_fault_thread();
874 qemu_sem_wait(&mis->postcopy_pause_sem_fault);
876 trace_postcopy_pause_fault_thread_continued();
878 return true;
882 * Handle faults detected by the USERFAULT markings
884 static void *postcopy_ram_fault_thread(void *opaque)
886 MigrationIncomingState *mis = opaque;
887 struct uffd_msg msg;
888 int ret;
889 size_t index;
890 RAMBlock *rb = NULL;
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);
897 struct pollfd *pfd;
898 size_t pfd_len = 2 + mis->postcopy_remote_fds->len;
900 pfd = g_new0(struct pollfd, pfd_len);
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);
916 while (true) {
917 ram_addr_t rb_offset;
918 int poll_result;
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
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;
932 if (!mis->to_src_file) {
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.
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;
947 if (pfd[1].revents) {
948 uint64_t tmp64 = 0;
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__);
956 if (qatomic_read(&mis->fault_thread_quit)) {
957 trace_postcopy_ram_fault_thread_quit();
958 break;
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) {
968 * if a wake up happens on the other thread just after
969 * the poll, there is nothing to read.
971 continue;
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 */
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 */
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;
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);
1009 retry:
1011 * Send the request to the source - we want to request one
1012 * of our host page sizes (which is >= TPS)
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;
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);
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;
1046 ret = read(pcfd->fd, &msg, sizeof(msg));
1047 if (ret != sizeof(msg)) {
1048 if (errno == EAGAIN) {
1050 * if a wake up happens on the other thread just after
1051 * the poll, there is nothing to read.
1053 continue;
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*/
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 */
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? */
1086 rcu_unregister_thread();
1087 trace_postcopy_ram_fault_thread_exit();
1088 g_free(pfd);
1089 return NULL;
1092 static int postcopy_temp_pages_setup(MigrationIncomingState *mis)
1094 int err;
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;
1108 * Map large zero page when kernel can't use UFFDIO_ZEROPAGE for hugepages
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;
1121 memset(mis->postcopy_tmp_zero_page, '\0', mis->largest_page_size);
1123 return 0;
1126 int postcopy_ram_incoming_setup(MigrationIncomingState *mis)
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;
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.
1140 if (!ufd_check_and_apply(mis->userfault_fd, mis)) {
1141 return -1;
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;
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;
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;
1166 if (postcopy_temp_pages_setup(mis)) {
1167 /* Error dumped in the sub-function */
1168 return -1;
1171 trace_postcopy_ram_enable_notify();
1173 return 0;
1176 static int qemu_ufd_copy_ioctl(MigrationIncomingState *mis, void *host_addr,
1177 void *from_addr, uint64_t pagesize, RAMBlock *rb)
1179 int userfault_fd = mis->userfault_fd;
1180 int ret;
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, &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);
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());
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.
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);
1209 qemu_mutex_unlock(&mis->page_request_mutex);
1210 mark_postcopy_blocktime_end((uintptr_t)host_addr);
1212 return ret;
1215 int postcopy_notify_shared_wake(RAMBlock *rb, uint64_t offset)
1217 int i;
1218 MigrationIncomingState *mis = migration_incoming_get_current();
1219 GArray *pcrfds = mis->postcopy_remote_fds;
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;
1228 return 0;
1232 * Place a host page (from) at (host) atomically
1233 * returns 0 on success
1235 int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
1236 RAMBlock *rb)
1238 size_t pagesize = qemu_ram_pagesize(rb);
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.
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);
1250 return -e;
1253 trace_postcopy_place_page(host);
1254 return postcopy_notify_shared_wake(rb,
1255 qemu_ram_block_host_offset(rb, host));
1259 * Place a zero page at (host) atomically
1260 * returns 0 on success
1262 int postcopy_place_page_zero(MigrationIncomingState *mis, void *host,
1263 RAMBlock *rb)
1265 size_t pagesize = qemu_ram_pagesize(rb);
1266 trace_postcopy_place_page_zero(host);
1268 /* Normal RAMBlocks can zero a page using UFFDIO_ZEROPAGE
1269 * but it's not available for everything (e.g. hugetlbpages)
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);
1277 return -e;
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);
1287 #else
1288 /* No target OS support, stubs just fail */
1289 void fill_destination_postcopy_migration_info(MigrationInfo *info)
1293 bool postcopy_ram_supported_by_host(MigrationIncomingState *mis)
1295 error_report("%s: No OS support", __func__);
1296 return false;
1299 int postcopy_ram_incoming_init(MigrationIncomingState *mis)
1301 error_report("postcopy_ram_incoming_init: No OS support");
1302 return -1;
1305 int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
1307 assert(0);
1308 return -1;
1311 int postcopy_ram_prepare_discard(MigrationIncomingState *mis)
1313 assert(0);
1314 return -1;
1317 int postcopy_request_shared_page(struct PostCopyFD *pcfd, RAMBlock *rb,
1318 uint64_t client_addr, uint64_t rb_offset)
1320 assert(0);
1321 return -1;
1324 int postcopy_ram_incoming_setup(MigrationIncomingState *mis)
1326 assert(0);
1327 return -1;
1330 int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
1331 RAMBlock *rb)
1333 assert(0);
1334 return -1;
1337 int postcopy_place_page_zero(MigrationIncomingState *mis, void *host,
1338 RAMBlock *rb)
1340 assert(0);
1341 return -1;
1344 int postcopy_wake_shared(struct PostCopyFD *pcfd,
1345 uint64_t client_addr,
1346 RAMBlock *rb)
1348 assert(0);
1349 return -1;
1351 #endif
1353 /* ------------------------------------------------------------------------- */
1355 void postcopy_fault_thread_notify(MigrationIncomingState *mis)
1357 uint64_t tmp64 = 1;
1360 * Wakeup the fault_thread. It's an eventfd that should currently
1361 * be at 0, we're going to increment it to 1
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));
1371 * postcopy_discard_send_init: Called at the start of each RAMBlock before
1372 * asking to discard individual ranges.
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.
1378 static PostcopyDiscardState pds = {0};
1379 void postcopy_discard_send_init(MigrationState *ms, const char *name)
1381 pds.ramblock_name = name;
1382 pds.cur_entry = 0;
1383 pds.nsentwords = 0;
1384 pds.nsentcmds = 0;
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.
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)
1396 void postcopy_discard_send_range(MigrationState *ms, unsigned long start,
1397 unsigned long length)
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++;
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;
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
1423 * @ms: Current migration state.
1425 void postcopy_discard_send_finish(MigrationState *ms)
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++;
1437 trace_postcopy_discard_send_finish(pds.ramblock_name, pds.nsentwords,
1438 pds.nsentcmds);
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.
1446 static PostcopyState incoming_postcopy_state;
1448 PostcopyState postcopy_state_get(void)
1450 return qatomic_mb_read(&incoming_postcopy_state);
1453 /* Set the state and return the old state */
1454 PostcopyState postcopy_state_set(PostcopyState new_state)
1456 return qatomic_xchg(&incoming_postcopy_state, new_state);
1459 /* Register a handler for external shared memory postcopy
1460 * called on the destination.
1462 void postcopy_register_shared_ufd(struct PostCopyFD *pcfd)
1464 MigrationIncomingState *mis = migration_incoming_get_current();
1466 mis->postcopy_remote_fds = g_array_append_val(mis->postcopy_remote_fds,
1467 *pcfd);
1470 /* Unregister a handler for external shared memory postcopy
1472 void postcopy_unregister_shared_ufd(struct PostCopyFD *pcfd)
1474 guint i;
1475 MigrationIncomingState *mis = migration_incoming_get_current();
1476 GArray *pcrfds = mis->postcopy_remote_fds;
1478 if (!pcrfds) {
1479 /* migration has already finished and freed the array */
1480 return;
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;