]> Git Repo - qemu.git/blame - migration/postcopy-ram.c
Postcopy; Handle userfault requests
[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
19#include <glib.h>
20#include <stdio.h>
21#include <unistd.h>
22
23#include "qemu-common.h"
24#include "migration/migration.h"
25#include "migration/postcopy-ram.h"
26#include "sysemu/sysemu.h"
27#include "qemu/error-report.h"
28#include "trace.h"
29
e0b266f0
DDAG
30/* Arbitrary limit on size of each discard command,
31 * keeps them around ~200 bytes
32 */
33#define MAX_DISCARDS_PER_COMMAND 12
34
35struct PostcopyDiscardState {
36 const char *ramblock_name;
37 uint64_t offset; /* Bitmap entry for the 1st bit of this RAMBlock */
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
eb59db53
DDAG
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
c4faeed2
DDAG
54#include <poll.h>
55#include <sys/eventfd.h>
eb59db53
DDAG
56#include <sys/mman.h>
57#include <sys/ioctl.h>
58#include <sys/syscall.h>
59#include <sys/types.h>
60#include <asm/types.h> /* for __u64 */
61#endif
62
63#if defined(__linux__) && defined(__NR_userfaultfd)
64#include <linux/userfaultfd.h>
65
66static bool ufd_version_check(int ufd)
67{
68 struct uffdio_api api_struct;
69 uint64_t ioctl_mask;
70
71 api_struct.api = UFFD_API;
72 api_struct.features = 0;
73 if (ioctl(ufd, UFFDIO_API, &api_struct)) {
74 error_report("postcopy_ram_supported_by_host: UFFDIO_API failed: %s",
75 strerror(errno));
76 return false;
77 }
78
79 ioctl_mask = (__u64)1 << _UFFDIO_REGISTER |
80 (__u64)1 << _UFFDIO_UNREGISTER;
81 if ((api_struct.ioctls & ioctl_mask) != ioctl_mask) {
82 error_report("Missing userfault features: %" PRIx64,
83 (uint64_t)(~api_struct.ioctls & ioctl_mask));
84 return false;
85 }
86
87 return true;
88}
89
90bool postcopy_ram_supported_by_host(void)
91{
92 long pagesize = getpagesize();
93 int ufd = -1;
94 bool ret = false; /* Error unless we change it */
95 void *testarea = NULL;
96 struct uffdio_register reg_struct;
97 struct uffdio_range range_struct;
98 uint64_t feature_mask;
99
100 if ((1ul << qemu_target_page_bits()) > pagesize) {
101 error_report("Target page size bigger than host page size");
102 goto out;
103 }
104
105 ufd = syscall(__NR_userfaultfd, O_CLOEXEC);
106 if (ufd == -1) {
107 error_report("%s: userfaultfd not available: %s", __func__,
108 strerror(errno));
109 goto out;
110 }
111
112 /* Version and features check */
113 if (!ufd_version_check(ufd)) {
114 goto out;
115 }
116
117 /*
118 * We need to check that the ops we need are supported on anon memory
119 * To do that we need to register a chunk and see the flags that
120 * are returned.
121 */
122 testarea = mmap(NULL, pagesize, PROT_READ | PROT_WRITE, MAP_PRIVATE |
123 MAP_ANONYMOUS, -1, 0);
124 if (testarea == MAP_FAILED) {
125 error_report("%s: Failed to map test area: %s", __func__,
126 strerror(errno));
127 goto out;
128 }
129 g_assert(((size_t)testarea & (pagesize-1)) == 0);
130
131 reg_struct.range.start = (uintptr_t)testarea;
132 reg_struct.range.len = pagesize;
133 reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING;
134
135 if (ioctl(ufd, UFFDIO_REGISTER, &reg_struct)) {
136 error_report("%s userfault register: %s", __func__, strerror(errno));
137 goto out;
138 }
139
140 range_struct.start = (uintptr_t)testarea;
141 range_struct.len = pagesize;
142 if (ioctl(ufd, UFFDIO_UNREGISTER, &range_struct)) {
143 error_report("%s userfault unregister: %s", __func__, strerror(errno));
144 goto out;
145 }
146
147 feature_mask = (__u64)1 << _UFFDIO_WAKE |
148 (__u64)1 << _UFFDIO_COPY |
149 (__u64)1 << _UFFDIO_ZEROPAGE;
150 if ((reg_struct.ioctls & feature_mask) != feature_mask) {
151 error_report("Missing userfault map features: %" PRIx64,
152 (uint64_t)(~reg_struct.ioctls & feature_mask));
153 goto out;
154 }
155
156 /* Success! */
157 ret = true;
158out:
159 if (testarea) {
160 munmap(testarea, pagesize);
161 }
162 if (ufd != -1) {
163 close(ufd);
164 }
165 return ret;
166}
167
e0b266f0
DDAG
168/**
169 * postcopy_ram_discard_range: Discard a range of memory.
170 * We can assume that if we've been called postcopy_ram_hosttest returned true.
171 *
172 * @mis: Current incoming migration state.
173 * @start, @length: range of memory to discard.
174 *
175 * returns: 0 on success.
176 */
177int postcopy_ram_discard_range(MigrationIncomingState *mis, uint8_t *start,
178 size_t length)
179{
180 trace_postcopy_ram_discard_range(start, length);
181 if (madvise(start, length, MADV_DONTNEED)) {
182 error_report("%s MADV_DONTNEED: %s", __func__, strerror(errno));
183 return -1;
184 }
185
186 return 0;
187}
188
1caddf8a
DDAG
189/*
190 * Setup an area of RAM so that it *can* be used for postcopy later; this
191 * must be done right at the start prior to pre-copy.
192 * opaque should be the MIS.
193 */
194static int init_range(const char *block_name, void *host_addr,
195 ram_addr_t offset, ram_addr_t length, void *opaque)
196{
197 MigrationIncomingState *mis = opaque;
198
199 trace_postcopy_init_range(block_name, host_addr, offset, length);
200
201 /*
202 * We need the whole of RAM to be truly empty for postcopy, so things
203 * like ROMs and any data tables built during init must be zero'd
204 * - we're going to get the copy from the source anyway.
205 * (Precopy will just overwrite this data, so doesn't need the discard)
206 */
207 if (postcopy_ram_discard_range(mis, host_addr, length)) {
208 return -1;
209 }
210
211 return 0;
212}
213
214/*
215 * At the end of migration, undo the effects of init_range
216 * opaque should be the MIS.
217 */
218static int cleanup_range(const char *block_name, void *host_addr,
219 ram_addr_t offset, ram_addr_t length, void *opaque)
220{
221 MigrationIncomingState *mis = opaque;
222 struct uffdio_range range_struct;
223 trace_postcopy_cleanup_range(block_name, host_addr, offset, length);
224
225 /*
226 * We turned off hugepage for the precopy stage with postcopy enabled
227 * we can turn it back on now.
228 */
229#ifdef MADV_HUGEPAGE
230 if (madvise(host_addr, length, MADV_HUGEPAGE)) {
231 error_report("%s HUGEPAGE: %s", __func__, strerror(errno));
232 return -1;
233 }
234#endif
235
236 /*
237 * We can also turn off userfault now since we should have all the
238 * pages. It can be useful to leave it on to debug postcopy
239 * if you're not sure it's always getting every page.
240 */
241 range_struct.start = (uintptr_t)host_addr;
242 range_struct.len = length;
243
244 if (ioctl(mis->userfault_fd, UFFDIO_UNREGISTER, &range_struct)) {
245 error_report("%s: userfault unregister %s", __func__, strerror(errno));
246
247 return -1;
248 }
249
250 return 0;
251}
252
253/*
254 * Initialise postcopy-ram, setting the RAM to a state where we can go into
255 * postcopy later; must be called prior to any precopy.
256 * called from arch_init's similarly named ram_postcopy_incoming_init
257 */
258int postcopy_ram_incoming_init(MigrationIncomingState *mis, size_t ram_pages)
259{
260 if (qemu_ram_foreach_block(init_range, mis)) {
261 return -1;
262 }
263
264 return 0;
265}
266
267/*
268 * At the end of a migration where postcopy_ram_incoming_init was called.
269 */
270int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
271{
c4faeed2
DDAG
272 trace_postcopy_ram_incoming_cleanup_entry();
273
274 if (mis->have_fault_thread) {
275 uint64_t tmp64;
276
277 if (qemu_ram_foreach_block(cleanup_range, mis)) {
278 return -1;
279 }
280 /*
281 * Tell the fault_thread to exit, it's an eventfd that should
282 * currently be at 0, we're going to increment it to 1
283 */
284 tmp64 = 1;
285 if (write(mis->userfault_quit_fd, &tmp64, 8) == 8) {
286 trace_postcopy_ram_incoming_cleanup_join();
287 qemu_thread_join(&mis->fault_thread);
288 } else {
289 /* Not much we can do here, but may as well report it */
290 error_report("%s: incrementing userfault_quit_fd: %s", __func__,
291 strerror(errno));
292 }
293 trace_postcopy_ram_incoming_cleanup_closeuf();
294 close(mis->userfault_fd);
295 close(mis->userfault_quit_fd);
296 mis->have_fault_thread = false;
1caddf8a
DDAG
297 }
298
c4faeed2
DDAG
299 postcopy_state_set(POSTCOPY_INCOMING_END);
300 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
301
696ed9a9
DDAG
302 if (mis->postcopy_tmp_page) {
303 munmap(mis->postcopy_tmp_page, getpagesize());
304 mis->postcopy_tmp_page = NULL;
305 }
c4faeed2 306 trace_postcopy_ram_incoming_cleanup_exit();
1caddf8a
DDAG
307 return 0;
308}
309
f0a227ad
DDAG
310/*
311 * Mark the given area of RAM as requiring notification to unwritten areas
312 * Used as a callback on qemu_ram_foreach_block.
313 * host_addr: Base of area to mark
314 * offset: Offset in the whole ram arena
315 * length: Length of the section
316 * opaque: MigrationIncomingState pointer
317 * Returns 0 on success
318 */
319static int ram_block_enable_notify(const char *block_name, void *host_addr,
320 ram_addr_t offset, ram_addr_t length,
321 void *opaque)
322{
323 MigrationIncomingState *mis = opaque;
324 struct uffdio_register reg_struct;
325
326 reg_struct.range.start = (uintptr_t)host_addr;
327 reg_struct.range.len = length;
328 reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING;
329
330 /* Now tell our userfault_fd that it's responsible for this area */
331 if (ioctl(mis->userfault_fd, UFFDIO_REGISTER, &reg_struct)) {
332 error_report("%s userfault register: %s", __func__, strerror(errno));
333 return -1;
334 }
335
336 return 0;
337}
338
339/*
340 * Handle faults detected by the USERFAULT markings
341 */
342static void *postcopy_ram_fault_thread(void *opaque)
343{
344 MigrationIncomingState *mis = opaque;
c4faeed2
DDAG
345 struct uffd_msg msg;
346 int ret;
347 size_t hostpagesize = getpagesize();
348 RAMBlock *rb = NULL;
349 RAMBlock *last_rb = NULL; /* last RAMBlock we sent part of */
f0a227ad 350
c4faeed2 351 trace_postcopy_ram_fault_thread_entry();
f0a227ad 352 qemu_sem_post(&mis->fault_thread_sem);
f0a227ad 353
c4faeed2
DDAG
354 while (true) {
355 ram_addr_t rb_offset;
356 ram_addr_t in_raspace;
357 struct pollfd pfd[2];
358
359 /*
360 * We're mainly waiting for the kernel to give us a faulting HVA,
361 * however we can be told to quit via userfault_quit_fd which is
362 * an eventfd
363 */
364 pfd[0].fd = mis->userfault_fd;
365 pfd[0].events = POLLIN;
366 pfd[0].revents = 0;
367 pfd[1].fd = mis->userfault_quit_fd;
368 pfd[1].events = POLLIN; /* Waiting for eventfd to go positive */
369 pfd[1].revents = 0;
370
371 if (poll(pfd, 2, -1 /* Wait forever */) == -1) {
372 error_report("%s: userfault poll: %s", __func__, strerror(errno));
373 break;
374 }
375
376 if (pfd[1].revents) {
377 trace_postcopy_ram_fault_thread_quit();
378 break;
379 }
380
381 ret = read(mis->userfault_fd, &msg, sizeof(msg));
382 if (ret != sizeof(msg)) {
383 if (errno == EAGAIN) {
384 /*
385 * if a wake up happens on the other thread just after
386 * the poll, there is nothing to read.
387 */
388 continue;
389 }
390 if (ret < 0) {
391 error_report("%s: Failed to read full userfault message: %s",
392 __func__, strerror(errno));
393 break;
394 } else {
395 error_report("%s: Read %d bytes from userfaultfd expected %zd",
396 __func__, ret, sizeof(msg));
397 break; /* Lost alignment, don't know what we'd read next */
398 }
399 }
400 if (msg.event != UFFD_EVENT_PAGEFAULT) {
401 error_report("%s: Read unexpected event %ud from userfaultfd",
402 __func__, msg.event);
403 continue; /* It's not a page fault, shouldn't happen */
404 }
405
406 rb = qemu_ram_block_from_host(
407 (void *)(uintptr_t)msg.arg.pagefault.address,
408 true, &in_raspace, &rb_offset);
409 if (!rb) {
410 error_report("postcopy_ram_fault_thread: Fault outside guest: %"
411 PRIx64, (uint64_t)msg.arg.pagefault.address);
412 break;
413 }
414
415 rb_offset &= ~(hostpagesize - 1);
416 trace_postcopy_ram_fault_thread_request(msg.arg.pagefault.address,
417 qemu_ram_get_idstr(rb),
418 rb_offset);
419
420 /*
421 * Send the request to the source - we want to request one
422 * of our host page sizes (which is >= TPS)
423 */
424 if (rb != last_rb) {
425 last_rb = rb;
426 migrate_send_rp_req_pages(mis, qemu_ram_get_idstr(rb),
427 rb_offset, hostpagesize);
428 } else {
429 /* Save some space */
430 migrate_send_rp_req_pages(mis, NULL,
431 rb_offset, hostpagesize);
432 }
433 }
434 trace_postcopy_ram_fault_thread_exit();
f0a227ad
DDAG
435 return NULL;
436}
437
438int postcopy_ram_enable_notify(MigrationIncomingState *mis)
439{
c4faeed2
DDAG
440 /* Open the fd for the kernel to give us userfaults */
441 mis->userfault_fd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
442 if (mis->userfault_fd == -1) {
443 error_report("%s: Failed to open userfault fd: %s", __func__,
444 strerror(errno));
445 return -1;
446 }
447
448 /*
449 * Although the host check already tested the API, we need to
450 * do the check again as an ABI handshake on the new fd.
451 */
452 if (!ufd_version_check(mis->userfault_fd)) {
453 return -1;
454 }
455
456 /* Now an eventfd we use to tell the fault-thread to quit */
457 mis->userfault_quit_fd = eventfd(0, EFD_CLOEXEC);
458 if (mis->userfault_quit_fd == -1) {
459 error_report("%s: Opening userfault_quit_fd: %s", __func__,
460 strerror(errno));
461 close(mis->userfault_fd);
462 return -1;
463 }
464
f0a227ad
DDAG
465 qemu_sem_init(&mis->fault_thread_sem, 0);
466 qemu_thread_create(&mis->fault_thread, "postcopy/fault",
467 postcopy_ram_fault_thread, mis, QEMU_THREAD_JOINABLE);
468 qemu_sem_wait(&mis->fault_thread_sem);
469 qemu_sem_destroy(&mis->fault_thread_sem);
c4faeed2 470 mis->have_fault_thread = true;
f0a227ad
DDAG
471
472 /* Mark so that we get notified of accesses to unwritten areas */
473 if (qemu_ram_foreach_block(ram_block_enable_notify, mis)) {
474 return -1;
475 }
476
c4faeed2
DDAG
477 trace_postcopy_ram_enable_notify();
478
f0a227ad
DDAG
479 return 0;
480}
481
696ed9a9
DDAG
482/*
483 * Place a host page (from) at (host) atomically
484 * returns 0 on success
485 */
486int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from)
487{
488 struct uffdio_copy copy_struct;
489
490 copy_struct.dst = (uint64_t)(uintptr_t)host;
491 copy_struct.src = (uint64_t)(uintptr_t)from;
492 copy_struct.len = getpagesize();
493 copy_struct.mode = 0;
494
495 /* copy also acks to the kernel waking the stalled thread up
496 * TODO: We can inhibit that ack and only do it if it was requested
497 * which would be slightly cheaper, but we'd have to be careful
498 * of the order of updating our page state.
499 */
500 if (ioctl(mis->userfault_fd, UFFDIO_COPY, &copy_struct)) {
501 int e = errno;
502 error_report("%s: %s copy host: %p from: %p",
503 __func__, strerror(e), host, from);
504
505 return -e;
506 }
507
508 trace_postcopy_place_page(host);
509 return 0;
510}
511
512/*
513 * Place a zero page at (host) atomically
514 * returns 0 on success
515 */
516int postcopy_place_page_zero(MigrationIncomingState *mis, void *host)
517{
518 struct uffdio_zeropage zero_struct;
519
520 zero_struct.range.start = (uint64_t)(uintptr_t)host;
521 zero_struct.range.len = getpagesize();
522 zero_struct.mode = 0;
523
524 if (ioctl(mis->userfault_fd, UFFDIO_ZEROPAGE, &zero_struct)) {
525 int e = errno;
526 error_report("%s: %s zero host: %p",
527 __func__, strerror(e), host);
528
529 return -e;
530 }
531
532 trace_postcopy_place_page_zero(host);
533 return 0;
534}
535
536/*
537 * Returns a target page of memory that can be mapped at a later point in time
538 * using postcopy_place_page
539 * The same address is used repeatedly, postcopy_place_page just takes the
540 * backing page away.
541 * Returns: Pointer to allocated page
542 *
543 */
544void *postcopy_get_tmp_page(MigrationIncomingState *mis)
545{
546 if (!mis->postcopy_tmp_page) {
547 mis->postcopy_tmp_page = mmap(NULL, getpagesize(),
548 PROT_READ | PROT_WRITE, MAP_PRIVATE |
549 MAP_ANONYMOUS, -1, 0);
550 if (!mis->postcopy_tmp_page) {
551 error_report("%s: %s", __func__, strerror(errno));
552 return NULL;
553 }
554 }
555
556 return mis->postcopy_tmp_page;
557}
558
eb59db53
DDAG
559#else
560/* No target OS support, stubs just fail */
561bool postcopy_ram_supported_by_host(void)
562{
563 error_report("%s: No OS support", __func__);
564 return false;
565}
566
1caddf8a
DDAG
567int postcopy_ram_incoming_init(MigrationIncomingState *mis, size_t ram_pages)
568{
569 error_report("postcopy_ram_incoming_init: No OS support");
570 return -1;
571}
572
573int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
574{
575 assert(0);
576 return -1;
577}
578
e0b266f0
DDAG
579int postcopy_ram_discard_range(MigrationIncomingState *mis, uint8_t *start,
580 size_t length)
581{
582 assert(0);
1caddf8a 583 return -1;
e0b266f0 584}
f0a227ad
DDAG
585
586int postcopy_ram_enable_notify(MigrationIncomingState *mis)
587{
588 assert(0);
589 return -1;
590}
696ed9a9
DDAG
591
592int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from)
593{
594 assert(0);
595 return -1;
596}
597
598int postcopy_place_page_zero(MigrationIncomingState *mis, void *host)
599{
600 assert(0);
601 return -1;
602}
603
604void *postcopy_get_tmp_page(MigrationIncomingState *mis)
605{
606 assert(0);
607 return NULL;
608}
609
eb59db53
DDAG
610#endif
611
e0b266f0
DDAG
612/* ------------------------------------------------------------------------- */
613
614/**
615 * postcopy_discard_send_init: Called at the start of each RAMBlock before
616 * asking to discard individual ranges.
617 *
618 * @ms: The current migration state.
619 * @offset: the bitmap offset of the named RAMBlock in the migration
620 * bitmap.
621 * @name: RAMBlock that discards will operate on.
622 *
623 * returns: a new PDS.
624 */
625PostcopyDiscardState *postcopy_discard_send_init(MigrationState *ms,
626 unsigned long offset,
627 const char *name)
628{
629 PostcopyDiscardState *res = g_malloc0(sizeof(PostcopyDiscardState));
630
631 if (res) {
632 res->ramblock_name = name;
633 res->offset = offset;
634 }
635
636 return res;
637}
638
639/**
640 * postcopy_discard_send_range: Called by the bitmap code for each chunk to
641 * discard. May send a discard message, may just leave it queued to
642 * be sent later.
643 *
644 * @ms: Current migration state.
645 * @pds: Structure initialised by postcopy_discard_send_init().
646 * @start,@length: a range of pages in the migration bitmap in the
647 * RAM block passed to postcopy_discard_send_init() (length=1 is one page)
648 */
649void postcopy_discard_send_range(MigrationState *ms, PostcopyDiscardState *pds,
650 unsigned long start, unsigned long length)
651{
652 size_t tp_bits = qemu_target_page_bits();
653 /* Convert to byte offsets within the RAM block */
654 pds->start_list[pds->cur_entry] = (start - pds->offset) << tp_bits;
655 pds->length_list[pds->cur_entry] = length << tp_bits;
656 trace_postcopy_discard_send_range(pds->ramblock_name, start, length);
657 pds->cur_entry++;
658 pds->nsentwords++;
659
660 if (pds->cur_entry == MAX_DISCARDS_PER_COMMAND) {
661 /* Full set, ship it! */
662 qemu_savevm_send_postcopy_ram_discard(ms->file, pds->ramblock_name,
663 pds->cur_entry,
664 pds->start_list,
665 pds->length_list);
666 pds->nsentcmds++;
667 pds->cur_entry = 0;
668 }
669}
670
671/**
672 * postcopy_discard_send_finish: Called at the end of each RAMBlock by the
673 * bitmap code. Sends any outstanding discard messages, frees the PDS
674 *
675 * @ms: Current migration state.
676 * @pds: Structure initialised by postcopy_discard_send_init().
677 */
678void postcopy_discard_send_finish(MigrationState *ms, PostcopyDiscardState *pds)
679{
680 /* Anything unsent? */
681 if (pds->cur_entry) {
682 qemu_savevm_send_postcopy_ram_discard(ms->file, pds->ramblock_name,
683 pds->cur_entry,
684 pds->start_list,
685 pds->length_list);
686 pds->nsentcmds++;
687 }
688
689 trace_postcopy_discard_send_finish(pds->ramblock_name, pds->nsentwords,
690 pds->nsentcmds);
691
692 g_free(pds);
693}
This page took 0.092947 seconds and 4 git commands to generate.