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