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