]> git.proxmox.com Git - mirror_qemu.git/blob - migration/postcopy-ram.c
postcopy: Add notifier chain
[mirror_qemu.git] / migration / postcopy-ram.c
1 /*
2 * Postcopy migration for RAM
3 *
4 * Copyright 2013-2015 Red Hat, Inc. and/or its affiliates
5 *
6 * Authors:
7 * Dave Gilbert <dgilbert@redhat.com>
8 *
9 * This work is licensed under the terms of the GNU GPL, version 2 or later.
10 * See the COPYING file in the top-level directory.
11 *
12 */
13
14 /*
15 * Postcopy is a migration technique where the execution flips from the
16 * source to the destination before all the data has been copied.
17 */
18
19 #include "qemu/osdep.h"
20 #include "exec/target_page.h"
21 #include "migration.h"
22 #include "qemu-file.h"
23 #include "savevm.h"
24 #include "postcopy-ram.h"
25 #include "ram.h"
26 #include "qapi/error.h"
27 #include "qemu/notify.h"
28 #include "sysemu/sysemu.h"
29 #include "sysemu/balloon.h"
30 #include "qemu/error-report.h"
31 #include "trace.h"
32
33 /* Arbitrary limit on size of each discard command,
34 * keeps them around ~200 bytes
35 */
36 #define MAX_DISCARDS_PER_COMMAND 12
37
38 struct PostcopyDiscardState {
39 const char *ramblock_name;
40 uint16_t cur_entry;
41 /*
42 * Start and length of a discard range (bytes)
43 */
44 uint64_t start_list[MAX_DISCARDS_PER_COMMAND];
45 uint64_t length_list[MAX_DISCARDS_PER_COMMAND];
46 unsigned int nsentwords;
47 unsigned int nsentcmds;
48 };
49
50 static NotifierWithReturnList postcopy_notifier_list;
51
52 void postcopy_infrastructure_init(void)
53 {
54 notifier_with_return_list_init(&postcopy_notifier_list);
55 }
56
57 void postcopy_add_notifier(NotifierWithReturn *nn)
58 {
59 notifier_with_return_list_add(&postcopy_notifier_list, nn);
60 }
61
62 void postcopy_remove_notifier(NotifierWithReturn *n)
63 {
64 notifier_with_return_remove(n);
65 }
66
67 int postcopy_notify(enum PostcopyNotifyReason reason, Error **errp)
68 {
69 struct PostcopyNotifyData pnd;
70 pnd.reason = reason;
71 pnd.errp = errp;
72
73 return notifier_with_return_list_notify(&postcopy_notifier_list,
74 &pnd);
75 }
76
77 /* Postcopy needs to detect accesses to pages that haven't yet been copied
78 * across, and efficiently map new pages in, the techniques for doing this
79 * are target OS specific.
80 */
81 #if defined(__linux__)
82
83 #include <poll.h>
84 #include <sys/ioctl.h>
85 #include <sys/syscall.h>
86 #include <asm/types.h> /* for __u64 */
87 #endif
88
89 #if defined(__linux__) && defined(__NR_userfaultfd) && defined(CONFIG_EVENTFD)
90 #include <sys/eventfd.h>
91 #include <linux/userfaultfd.h>
92
93
94 /**
95 * receive_ufd_features: check userfault fd features, to request only supported
96 * features in the future.
97 *
98 * Returns: true on success
99 *
100 * __NR_userfaultfd - should be checked before
101 * @features: out parameter will contain uffdio_api.features provided by kernel
102 * in case of success
103 */
104 static bool receive_ufd_features(uint64_t *features)
105 {
106 struct uffdio_api api_struct = {0};
107 int ufd;
108 bool ret = true;
109
110 /* if we are here __NR_userfaultfd should exists */
111 ufd = syscall(__NR_userfaultfd, O_CLOEXEC);
112 if (ufd == -1) {
113 error_report("%s: syscall __NR_userfaultfd failed: %s", __func__,
114 strerror(errno));
115 return false;
116 }
117
118 /* ask features */
119 api_struct.api = UFFD_API;
120 api_struct.features = 0;
121 if (ioctl(ufd, UFFDIO_API, &api_struct)) {
122 error_report("%s: UFFDIO_API failed: %s", __func__,
123 strerror(errno));
124 ret = false;
125 goto release_ufd;
126 }
127
128 *features = api_struct.features;
129
130 release_ufd:
131 close(ufd);
132 return ret;
133 }
134
135 /**
136 * request_ufd_features: this function should be called only once on a newly
137 * opened ufd, subsequent calls will lead to error.
138 *
139 * Returns: true on succes
140 *
141 * @ufd: fd obtained from userfaultfd syscall
142 * @features: bit mask see UFFD_API_FEATURES
143 */
144 static bool request_ufd_features(int ufd, uint64_t features)
145 {
146 struct uffdio_api api_struct = {0};
147 uint64_t ioctl_mask;
148
149 api_struct.api = UFFD_API;
150 api_struct.features = features;
151 if (ioctl(ufd, UFFDIO_API, &api_struct)) {
152 error_report("%s failed: UFFDIO_API failed: %s", __func__,
153 strerror(errno));
154 return false;
155 }
156
157 ioctl_mask = (__u64)1 << _UFFDIO_REGISTER |
158 (__u64)1 << _UFFDIO_UNREGISTER;
159 if ((api_struct.ioctls & ioctl_mask) != ioctl_mask) {
160 error_report("Missing userfault features: %" PRIx64,
161 (uint64_t)(~api_struct.ioctls & ioctl_mask));
162 return false;
163 }
164
165 return true;
166 }
167
168 static bool ufd_check_and_apply(int ufd, MigrationIncomingState *mis)
169 {
170 uint64_t asked_features = 0;
171 static uint64_t supported_features;
172
173 /*
174 * it's not possible to
175 * request UFFD_API twice per one fd
176 * userfault fd features is persistent
177 */
178 if (!supported_features) {
179 if (!receive_ufd_features(&supported_features)) {
180 error_report("%s failed", __func__);
181 return false;
182 }
183 }
184
185 /*
186 * request features, even if asked_features is 0, due to
187 * kernel expects UFFD_API before UFFDIO_REGISTER, per
188 * userfault file descriptor
189 */
190 if (!request_ufd_features(ufd, asked_features)) {
191 error_report("%s failed: features %" PRIu64, __func__,
192 asked_features);
193 return false;
194 }
195
196 if (getpagesize() != ram_pagesize_summary()) {
197 bool have_hp = false;
198 /* We've got a huge page */
199 #ifdef UFFD_FEATURE_MISSING_HUGETLBFS
200 have_hp = supported_features & UFFD_FEATURE_MISSING_HUGETLBFS;
201 #endif
202 if (!have_hp) {
203 error_report("Userfault on this host does not support huge pages");
204 return false;
205 }
206 }
207 return true;
208 }
209
210 /* Callback from postcopy_ram_supported_by_host block iterator.
211 */
212 static int test_ramblock_postcopiable(const char *block_name, void *host_addr,
213 ram_addr_t offset, ram_addr_t length, void *opaque)
214 {
215 RAMBlock *rb = qemu_ram_block_by_name(block_name);
216 size_t pagesize = qemu_ram_pagesize(rb);
217
218 if (qemu_ram_is_shared(rb)) {
219 error_report("Postcopy on shared RAM (%s) is not yet supported",
220 block_name);
221 return 1;
222 }
223
224 if (length % pagesize) {
225 error_report("Postcopy requires RAM blocks to be a page size multiple,"
226 " block %s is 0x" RAM_ADDR_FMT " bytes with a "
227 "page size of 0x%zx", block_name, length, pagesize);
228 return 1;
229 }
230 return 0;
231 }
232
233 /*
234 * Note: This has the side effect of munlock'ing all of RAM, that's
235 * normally fine since if the postcopy succeeds it gets turned back on at the
236 * end.
237 */
238 bool postcopy_ram_supported_by_host(MigrationIncomingState *mis)
239 {
240 long pagesize = getpagesize();
241 int ufd = -1;
242 bool ret = false; /* Error unless we change it */
243 void *testarea = NULL;
244 struct uffdio_register reg_struct;
245 struct uffdio_range range_struct;
246 uint64_t feature_mask;
247 Error *local_err = NULL;
248
249 if (qemu_target_page_size() > pagesize) {
250 error_report("Target page size bigger than host page size");
251 goto out;
252 }
253
254 ufd = syscall(__NR_userfaultfd, O_CLOEXEC);
255 if (ufd == -1) {
256 error_report("%s: userfaultfd not available: %s", __func__,
257 strerror(errno));
258 goto out;
259 }
260
261 /* Give devices a chance to object */
262 if (postcopy_notify(POSTCOPY_NOTIFY_PROBE, &local_err)) {
263 error_report_err(local_err);
264 goto out;
265 }
266
267 /* Version and features check */
268 if (!ufd_check_and_apply(ufd, mis)) {
269 goto out;
270 }
271
272 /* We don't support postcopy with shared RAM yet */
273 if (qemu_ram_foreach_block(test_ramblock_postcopiable, NULL)) {
274 goto out;
275 }
276
277 /*
278 * userfault and mlock don't go together; we'll put it back later if
279 * it was enabled.
280 */
281 if (munlockall()) {
282 error_report("%s: munlockall: %s", __func__, strerror(errno));
283 return -1;
284 }
285
286 /*
287 * We need to check that the ops we need are supported on anon memory
288 * To do that we need to register a chunk and see the flags that
289 * are returned.
290 */
291 testarea = mmap(NULL, pagesize, PROT_READ | PROT_WRITE, MAP_PRIVATE |
292 MAP_ANONYMOUS, -1, 0);
293 if (testarea == MAP_FAILED) {
294 error_report("%s: Failed to map test area: %s", __func__,
295 strerror(errno));
296 goto out;
297 }
298 g_assert(((size_t)testarea & (pagesize-1)) == 0);
299
300 reg_struct.range.start = (uintptr_t)testarea;
301 reg_struct.range.len = pagesize;
302 reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING;
303
304 if (ioctl(ufd, UFFDIO_REGISTER, &reg_struct)) {
305 error_report("%s userfault register: %s", __func__, strerror(errno));
306 goto out;
307 }
308
309 range_struct.start = (uintptr_t)testarea;
310 range_struct.len = pagesize;
311 if (ioctl(ufd, UFFDIO_UNREGISTER, &range_struct)) {
312 error_report("%s userfault unregister: %s", __func__, strerror(errno));
313 goto out;
314 }
315
316 feature_mask = (__u64)1 << _UFFDIO_WAKE |
317 (__u64)1 << _UFFDIO_COPY |
318 (__u64)1 << _UFFDIO_ZEROPAGE;
319 if ((reg_struct.ioctls & feature_mask) != feature_mask) {
320 error_report("Missing userfault map features: %" PRIx64,
321 (uint64_t)(~reg_struct.ioctls & feature_mask));
322 goto out;
323 }
324
325 /* Success! */
326 ret = true;
327 out:
328 if (testarea) {
329 munmap(testarea, pagesize);
330 }
331 if (ufd != -1) {
332 close(ufd);
333 }
334 return ret;
335 }
336
337 /*
338 * Setup an area of RAM so that it *can* be used for postcopy later; this
339 * must be done right at the start prior to pre-copy.
340 * opaque should be the MIS.
341 */
342 static int init_range(const char *block_name, void *host_addr,
343 ram_addr_t offset, ram_addr_t length, void *opaque)
344 {
345 trace_postcopy_init_range(block_name, host_addr, offset, length);
346
347 /*
348 * We need the whole of RAM to be truly empty for postcopy, so things
349 * like ROMs and any data tables built during init must be zero'd
350 * - we're going to get the copy from the source anyway.
351 * (Precopy will just overwrite this data, so doesn't need the discard)
352 */
353 if (ram_discard_range(block_name, 0, length)) {
354 return -1;
355 }
356
357 return 0;
358 }
359
360 /*
361 * At the end of migration, undo the effects of init_range
362 * opaque should be the MIS.
363 */
364 static int cleanup_range(const char *block_name, void *host_addr,
365 ram_addr_t offset, ram_addr_t length, void *opaque)
366 {
367 MigrationIncomingState *mis = opaque;
368 struct uffdio_range range_struct;
369 trace_postcopy_cleanup_range(block_name, host_addr, offset, length);
370
371 /*
372 * We turned off hugepage for the precopy stage with postcopy enabled
373 * we can turn it back on now.
374 */
375 qemu_madvise(host_addr, length, QEMU_MADV_HUGEPAGE);
376
377 /*
378 * We can also turn off userfault now since we should have all the
379 * pages. It can be useful to leave it on to debug postcopy
380 * if you're not sure it's always getting every page.
381 */
382 range_struct.start = (uintptr_t)host_addr;
383 range_struct.len = length;
384
385 if (ioctl(mis->userfault_fd, UFFDIO_UNREGISTER, &range_struct)) {
386 error_report("%s: userfault unregister %s", __func__, strerror(errno));
387
388 return -1;
389 }
390
391 return 0;
392 }
393
394 /*
395 * Initialise postcopy-ram, setting the RAM to a state where we can go into
396 * postcopy later; must be called prior to any precopy.
397 * called from arch_init's similarly named ram_postcopy_incoming_init
398 */
399 int postcopy_ram_incoming_init(MigrationIncomingState *mis, size_t ram_pages)
400 {
401 if (qemu_ram_foreach_block(init_range, NULL)) {
402 return -1;
403 }
404
405 return 0;
406 }
407
408 /*
409 * At the end of a migration where postcopy_ram_incoming_init was called.
410 */
411 int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
412 {
413 trace_postcopy_ram_incoming_cleanup_entry();
414
415 if (mis->have_fault_thread) {
416 if (qemu_ram_foreach_block(cleanup_range, mis)) {
417 return -1;
418 }
419 /* Let the fault thread quit */
420 atomic_set(&mis->fault_thread_quit, 1);
421 postcopy_fault_thread_notify(mis);
422 trace_postcopy_ram_incoming_cleanup_join();
423 qemu_thread_join(&mis->fault_thread);
424
425 trace_postcopy_ram_incoming_cleanup_closeuf();
426 close(mis->userfault_fd);
427 close(mis->userfault_event_fd);
428 mis->have_fault_thread = false;
429 }
430
431 qemu_balloon_inhibit(false);
432
433 if (enable_mlock) {
434 if (os_mlock() < 0) {
435 error_report("mlock: %s", strerror(errno));
436 /*
437 * It doesn't feel right to fail at this point, we have a valid
438 * VM state.
439 */
440 }
441 }
442
443 postcopy_state_set(POSTCOPY_INCOMING_END);
444
445 if (mis->postcopy_tmp_page) {
446 munmap(mis->postcopy_tmp_page, mis->largest_page_size);
447 mis->postcopy_tmp_page = NULL;
448 }
449 if (mis->postcopy_tmp_zero_page) {
450 munmap(mis->postcopy_tmp_zero_page, mis->largest_page_size);
451 mis->postcopy_tmp_zero_page = NULL;
452 }
453 trace_postcopy_ram_incoming_cleanup_exit();
454 return 0;
455 }
456
457 /*
458 * Disable huge pages on an area
459 */
460 static int nhp_range(const char *block_name, void *host_addr,
461 ram_addr_t offset, ram_addr_t length, void *opaque)
462 {
463 trace_postcopy_nhp_range(block_name, host_addr, offset, length);
464
465 /*
466 * Before we do discards we need to ensure those discards really
467 * do delete areas of the page, even if THP thinks a hugepage would
468 * be a good idea, so force hugepages off.
469 */
470 qemu_madvise(host_addr, length, QEMU_MADV_NOHUGEPAGE);
471
472 return 0;
473 }
474
475 /*
476 * Userfault requires us to mark RAM as NOHUGEPAGE prior to discard
477 * however leaving it until after precopy means that most of the precopy
478 * data is still THPd
479 */
480 int postcopy_ram_prepare_discard(MigrationIncomingState *mis)
481 {
482 if (qemu_ram_foreach_block(nhp_range, mis)) {
483 return -1;
484 }
485
486 postcopy_state_set(POSTCOPY_INCOMING_DISCARD);
487
488 return 0;
489 }
490
491 /*
492 * Mark the given area of RAM as requiring notification to unwritten areas
493 * Used as a callback on qemu_ram_foreach_block.
494 * host_addr: Base of area to mark
495 * offset: Offset in the whole ram arena
496 * length: Length of the section
497 * opaque: MigrationIncomingState pointer
498 * Returns 0 on success
499 */
500 static int ram_block_enable_notify(const char *block_name, void *host_addr,
501 ram_addr_t offset, ram_addr_t length,
502 void *opaque)
503 {
504 MigrationIncomingState *mis = opaque;
505 struct uffdio_register reg_struct;
506
507 reg_struct.range.start = (uintptr_t)host_addr;
508 reg_struct.range.len = length;
509 reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING;
510
511 /* Now tell our userfault_fd that it's responsible for this area */
512 if (ioctl(mis->userfault_fd, UFFDIO_REGISTER, &reg_struct)) {
513 error_report("%s userfault register: %s", __func__, strerror(errno));
514 return -1;
515 }
516 if (!(reg_struct.ioctls & ((__u64)1 << _UFFDIO_COPY))) {
517 error_report("%s userfault: Region doesn't support COPY", __func__);
518 return -1;
519 }
520 if (reg_struct.ioctls & ((__u64)1 << _UFFDIO_ZEROPAGE)) {
521 RAMBlock *rb = qemu_ram_block_by_name(block_name);
522 qemu_ram_set_uf_zeroable(rb);
523 }
524
525 return 0;
526 }
527
528 /*
529 * Handle faults detected by the USERFAULT markings
530 */
531 static void *postcopy_ram_fault_thread(void *opaque)
532 {
533 MigrationIncomingState *mis = opaque;
534 struct uffd_msg msg;
535 int ret;
536 RAMBlock *rb = NULL;
537 RAMBlock *last_rb = NULL; /* last RAMBlock we sent part of */
538
539 trace_postcopy_ram_fault_thread_entry();
540 qemu_sem_post(&mis->fault_thread_sem);
541
542 while (true) {
543 ram_addr_t rb_offset;
544 struct pollfd pfd[2];
545
546 /*
547 * We're mainly waiting for the kernel to give us a faulting HVA,
548 * however we can be told to quit via userfault_quit_fd which is
549 * an eventfd
550 */
551 pfd[0].fd = mis->userfault_fd;
552 pfd[0].events = POLLIN;
553 pfd[0].revents = 0;
554 pfd[1].fd = mis->userfault_event_fd;
555 pfd[1].events = POLLIN; /* Waiting for eventfd to go positive */
556 pfd[1].revents = 0;
557
558 if (poll(pfd, 2, -1 /* Wait forever */) == -1) {
559 error_report("%s: userfault poll: %s", __func__, strerror(errno));
560 break;
561 }
562
563 if (pfd[1].revents) {
564 uint64_t tmp64 = 0;
565
566 /* Consume the signal */
567 if (read(mis->userfault_event_fd, &tmp64, 8) != 8) {
568 /* Nothing obviously nicer than posting this error. */
569 error_report("%s: read() failed", __func__);
570 }
571
572 if (atomic_read(&mis->fault_thread_quit)) {
573 trace_postcopy_ram_fault_thread_quit();
574 break;
575 }
576 }
577
578 ret = read(mis->userfault_fd, &msg, sizeof(msg));
579 if (ret != sizeof(msg)) {
580 if (errno == EAGAIN) {
581 /*
582 * if a wake up happens on the other thread just after
583 * the poll, there is nothing to read.
584 */
585 continue;
586 }
587 if (ret < 0) {
588 error_report("%s: Failed to read full userfault message: %s",
589 __func__, strerror(errno));
590 break;
591 } else {
592 error_report("%s: Read %d bytes from userfaultfd expected %zd",
593 __func__, ret, sizeof(msg));
594 break; /* Lost alignment, don't know what we'd read next */
595 }
596 }
597 if (msg.event != UFFD_EVENT_PAGEFAULT) {
598 error_report("%s: Read unexpected event %ud from userfaultfd",
599 __func__, msg.event);
600 continue; /* It's not a page fault, shouldn't happen */
601 }
602
603 rb = qemu_ram_block_from_host(
604 (void *)(uintptr_t)msg.arg.pagefault.address,
605 true, &rb_offset);
606 if (!rb) {
607 error_report("postcopy_ram_fault_thread: Fault outside guest: %"
608 PRIx64, (uint64_t)msg.arg.pagefault.address);
609 break;
610 }
611
612 rb_offset &= ~(qemu_ram_pagesize(rb) - 1);
613 trace_postcopy_ram_fault_thread_request(msg.arg.pagefault.address,
614 qemu_ram_get_idstr(rb),
615 rb_offset);
616
617 /*
618 * Send the request to the source - we want to request one
619 * of our host page sizes (which is >= TPS)
620 */
621 if (rb != last_rb) {
622 last_rb = rb;
623 migrate_send_rp_req_pages(mis, qemu_ram_get_idstr(rb),
624 rb_offset, qemu_ram_pagesize(rb));
625 } else {
626 /* Save some space */
627 migrate_send_rp_req_pages(mis, NULL,
628 rb_offset, qemu_ram_pagesize(rb));
629 }
630 }
631 trace_postcopy_ram_fault_thread_exit();
632 return NULL;
633 }
634
635 int postcopy_ram_enable_notify(MigrationIncomingState *mis)
636 {
637 /* Open the fd for the kernel to give us userfaults */
638 mis->userfault_fd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
639 if (mis->userfault_fd == -1) {
640 error_report("%s: Failed to open userfault fd: %s", __func__,
641 strerror(errno));
642 return -1;
643 }
644
645 /*
646 * Although the host check already tested the API, we need to
647 * do the check again as an ABI handshake on the new fd.
648 */
649 if (!ufd_check_and_apply(mis->userfault_fd, mis)) {
650 return -1;
651 }
652
653 /* Now an eventfd we use to tell the fault-thread to quit */
654 mis->userfault_event_fd = eventfd(0, EFD_CLOEXEC);
655 if (mis->userfault_event_fd == -1) {
656 error_report("%s: Opening userfault_event_fd: %s", __func__,
657 strerror(errno));
658 close(mis->userfault_fd);
659 return -1;
660 }
661
662 qemu_sem_init(&mis->fault_thread_sem, 0);
663 qemu_thread_create(&mis->fault_thread, "postcopy/fault",
664 postcopy_ram_fault_thread, mis, QEMU_THREAD_JOINABLE);
665 qemu_sem_wait(&mis->fault_thread_sem);
666 qemu_sem_destroy(&mis->fault_thread_sem);
667 mis->have_fault_thread = true;
668
669 /* Mark so that we get notified of accesses to unwritten areas */
670 if (qemu_ram_foreach_block(ram_block_enable_notify, mis)) {
671 return -1;
672 }
673
674 /*
675 * Ballooning can mark pages as absent while we're postcopying
676 * that would cause false userfaults.
677 */
678 qemu_balloon_inhibit(true);
679
680 trace_postcopy_ram_enable_notify();
681
682 return 0;
683 }
684
685 static int qemu_ufd_copy_ioctl(int userfault_fd, void *host_addr,
686 void *from_addr, uint64_t pagesize, RAMBlock *rb)
687 {
688 int ret;
689 if (from_addr) {
690 struct uffdio_copy copy_struct;
691 copy_struct.dst = (uint64_t)(uintptr_t)host_addr;
692 copy_struct.src = (uint64_t)(uintptr_t)from_addr;
693 copy_struct.len = pagesize;
694 copy_struct.mode = 0;
695 ret = ioctl(userfault_fd, UFFDIO_COPY, &copy_struct);
696 } else {
697 struct uffdio_zeropage zero_struct;
698 zero_struct.range.start = (uint64_t)(uintptr_t)host_addr;
699 zero_struct.range.len = pagesize;
700 zero_struct.mode = 0;
701 ret = ioctl(userfault_fd, UFFDIO_ZEROPAGE, &zero_struct);
702 }
703 if (!ret) {
704 ramblock_recv_bitmap_set_range(rb, host_addr,
705 pagesize / qemu_target_page_size());
706 }
707 return ret;
708 }
709
710 /*
711 * Place a host page (from) at (host) atomically
712 * returns 0 on success
713 */
714 int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
715 RAMBlock *rb)
716 {
717 size_t pagesize = qemu_ram_pagesize(rb);
718
719 /* copy also acks to the kernel waking the stalled thread up
720 * TODO: We can inhibit that ack and only do it if it was requested
721 * which would be slightly cheaper, but we'd have to be careful
722 * of the order of updating our page state.
723 */
724 if (qemu_ufd_copy_ioctl(mis->userfault_fd, host, from, pagesize, rb)) {
725 int e = errno;
726 error_report("%s: %s copy host: %p from: %p (size: %zd)",
727 __func__, strerror(e), host, from, pagesize);
728
729 return -e;
730 }
731
732 trace_postcopy_place_page(host);
733 return 0;
734 }
735
736 /*
737 * Place a zero page at (host) atomically
738 * returns 0 on success
739 */
740 int postcopy_place_page_zero(MigrationIncomingState *mis, void *host,
741 RAMBlock *rb)
742 {
743 size_t pagesize = qemu_ram_pagesize(rb);
744 trace_postcopy_place_page_zero(host);
745
746 /* Normal RAMBlocks can zero a page using UFFDIO_ZEROPAGE
747 * but it's not available for everything (e.g. hugetlbpages)
748 */
749 if (qemu_ram_is_uf_zeroable(rb)) {
750 if (qemu_ufd_copy_ioctl(mis->userfault_fd, host, NULL, pagesize, rb)) {
751 int e = errno;
752 error_report("%s: %s zero host: %p",
753 __func__, strerror(e), host);
754
755 return -e;
756 }
757 } else {
758 /* The kernel can't use UFFDIO_ZEROPAGE for hugepages */
759 if (!mis->postcopy_tmp_zero_page) {
760 mis->postcopy_tmp_zero_page = mmap(NULL, mis->largest_page_size,
761 PROT_READ | PROT_WRITE,
762 MAP_PRIVATE | MAP_ANONYMOUS,
763 -1, 0);
764 if (mis->postcopy_tmp_zero_page == MAP_FAILED) {
765 int e = errno;
766 mis->postcopy_tmp_zero_page = NULL;
767 error_report("%s: %s mapping large zero page",
768 __func__, strerror(e));
769 return -e;
770 }
771 memset(mis->postcopy_tmp_zero_page, '\0', mis->largest_page_size);
772 }
773 return postcopy_place_page(mis, host, mis->postcopy_tmp_zero_page,
774 rb);
775 }
776
777 return 0;
778 }
779
780 /*
781 * Returns a target page of memory that can be mapped at a later point in time
782 * using postcopy_place_page
783 * The same address is used repeatedly, postcopy_place_page just takes the
784 * backing page away.
785 * Returns: Pointer to allocated page
786 *
787 */
788 void *postcopy_get_tmp_page(MigrationIncomingState *mis)
789 {
790 if (!mis->postcopy_tmp_page) {
791 mis->postcopy_tmp_page = mmap(NULL, mis->largest_page_size,
792 PROT_READ | PROT_WRITE, MAP_PRIVATE |
793 MAP_ANONYMOUS, -1, 0);
794 if (mis->postcopy_tmp_page == MAP_FAILED) {
795 mis->postcopy_tmp_page = NULL;
796 error_report("%s: %s", __func__, strerror(errno));
797 return NULL;
798 }
799 }
800
801 return mis->postcopy_tmp_page;
802 }
803
804 #else
805 /* No target OS support, stubs just fail */
806 bool postcopy_ram_supported_by_host(MigrationIncomingState *mis)
807 {
808 error_report("%s: No OS support", __func__);
809 return false;
810 }
811
812 int postcopy_ram_incoming_init(MigrationIncomingState *mis, size_t ram_pages)
813 {
814 error_report("postcopy_ram_incoming_init: No OS support");
815 return -1;
816 }
817
818 int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
819 {
820 assert(0);
821 return -1;
822 }
823
824 int postcopy_ram_prepare_discard(MigrationIncomingState *mis)
825 {
826 assert(0);
827 return -1;
828 }
829
830 int postcopy_ram_enable_notify(MigrationIncomingState *mis)
831 {
832 assert(0);
833 return -1;
834 }
835
836 int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
837 RAMBlock *rb)
838 {
839 assert(0);
840 return -1;
841 }
842
843 int postcopy_place_page_zero(MigrationIncomingState *mis, void *host,
844 RAMBlock *rb)
845 {
846 assert(0);
847 return -1;
848 }
849
850 void *postcopy_get_tmp_page(MigrationIncomingState *mis)
851 {
852 assert(0);
853 return NULL;
854 }
855
856 #endif
857
858 /* ------------------------------------------------------------------------- */
859
860 void postcopy_fault_thread_notify(MigrationIncomingState *mis)
861 {
862 uint64_t tmp64 = 1;
863
864 /*
865 * Wakeup the fault_thread. It's an eventfd that should currently
866 * be at 0, we're going to increment it to 1
867 */
868 if (write(mis->userfault_event_fd, &tmp64, 8) != 8) {
869 /* Not much we can do here, but may as well report it */
870 error_report("%s: incrementing failed: %s", __func__,
871 strerror(errno));
872 }
873 }
874
875 /**
876 * postcopy_discard_send_init: Called at the start of each RAMBlock before
877 * asking to discard individual ranges.
878 *
879 * @ms: The current migration state.
880 * @offset: the bitmap offset of the named RAMBlock in the migration
881 * bitmap.
882 * @name: RAMBlock that discards will operate on.
883 *
884 * returns: a new PDS.
885 */
886 PostcopyDiscardState *postcopy_discard_send_init(MigrationState *ms,
887 const char *name)
888 {
889 PostcopyDiscardState *res = g_malloc0(sizeof(PostcopyDiscardState));
890
891 if (res) {
892 res->ramblock_name = name;
893 }
894
895 return res;
896 }
897
898 /**
899 * postcopy_discard_send_range: Called by the bitmap code for each chunk to
900 * discard. May send a discard message, may just leave it queued to
901 * be sent later.
902 *
903 * @ms: Current migration state.
904 * @pds: Structure initialised by postcopy_discard_send_init().
905 * @start,@length: a range of pages in the migration bitmap in the
906 * RAM block passed to postcopy_discard_send_init() (length=1 is one page)
907 */
908 void postcopy_discard_send_range(MigrationState *ms, PostcopyDiscardState *pds,
909 unsigned long start, unsigned long length)
910 {
911 size_t tp_size = qemu_target_page_size();
912 /* Convert to byte offsets within the RAM block */
913 pds->start_list[pds->cur_entry] = start * tp_size;
914 pds->length_list[pds->cur_entry] = length * tp_size;
915 trace_postcopy_discard_send_range(pds->ramblock_name, start, length);
916 pds->cur_entry++;
917 pds->nsentwords++;
918
919 if (pds->cur_entry == MAX_DISCARDS_PER_COMMAND) {
920 /* Full set, ship it! */
921 qemu_savevm_send_postcopy_ram_discard(ms->to_dst_file,
922 pds->ramblock_name,
923 pds->cur_entry,
924 pds->start_list,
925 pds->length_list);
926 pds->nsentcmds++;
927 pds->cur_entry = 0;
928 }
929 }
930
931 /**
932 * postcopy_discard_send_finish: Called at the end of each RAMBlock by the
933 * bitmap code. Sends any outstanding discard messages, frees the PDS
934 *
935 * @ms: Current migration state.
936 * @pds: Structure initialised by postcopy_discard_send_init().
937 */
938 void postcopy_discard_send_finish(MigrationState *ms, PostcopyDiscardState *pds)
939 {
940 /* Anything unsent? */
941 if (pds->cur_entry) {
942 qemu_savevm_send_postcopy_ram_discard(ms->to_dst_file,
943 pds->ramblock_name,
944 pds->cur_entry,
945 pds->start_list,
946 pds->length_list);
947 pds->nsentcmds++;
948 }
949
950 trace_postcopy_discard_send_finish(pds->ramblock_name, pds->nsentwords,
951 pds->nsentcmds);
952
953 g_free(pds);
954 }
955
956 /*
957 * Current state of incoming postcopy; note this is not part of
958 * MigrationIncomingState since it's state is used during cleanup
959 * at the end as MIS is being freed.
960 */
961 static PostcopyState incoming_postcopy_state;
962
963 PostcopyState postcopy_state_get(void)
964 {
965 return atomic_mb_read(&incoming_postcopy_state);
966 }
967
968 /* Set the state and return the old state */
969 PostcopyState postcopy_state_set(PostcopyState new_state)
970 {
971 return atomic_xchg(&incoming_postcopy_state, new_state);
972 }