master
c 1,728 lines 58.5 KB
Raw
1 /*
2 * Virtio MEM device
3 *
4 * Copyright (C) 2020 Red Hat, Inc.
5 *
6 * Authors:
7 * David Hildenbrand <david@redhat.com>
8 *
9 * This work is licensed under the terms of the GNU GPL, version 2.
10 * See the COPYING file in the top-level directory.
11 */
12
13 #include "qemu/osdep.h"
14 #include "qemu/iov.h"
15 #include "qemu/cutils.h"
16 #include "qemu/error-report.h"
17 #include "qemu/units.h"
18 #include "qemu/target-info-qapi.h"
19 #include "system/memory.h"
20 #include "system/numa.h"
21 #include "system/system.h"
22 #include "system/ramblock.h"
23 #include "system/reset.h"
24 #include "system/runstate.h"
25 #include "hw/virtio/virtio.h"
26 #include "hw/virtio/virtio-bus.h"
27 #include "hw/virtio/virtio-mem.h"
28 #include "qapi/error.h"
29 #include "qapi/visitor.h"
30 #include "migration/misc.h"
31 #include "hw/core/boards.h"
32 #include "hw/core/qdev-properties.h"
33 #include "hw/acpi/acpi.h"
34 #include "trace.h"
35
36 static const VMStateDescription vmstate_virtio_mem_device_early;
37
38 static bool virtio_mem_has_legacy_guests(void)
39 {
40 /*
41 * We only had legacy x86 guests that did not support
42 * VIRTIO_MEM_F_UNPLUGGED_INACCESSIBLE. Other targets don't have
43 * legacy guests.
44 */
45 switch (target_arch()) {
46 case SYS_EMU_TARGET_I386:
47 case SYS_EMU_TARGET_X86_64:
48 return true;
49 default:
50 return false;
51 }
52 }
53
54 /*
55 * Let's not allow blocks smaller than 1 MiB, for example, to keep the tracking
56 * bitmap small.
57 */
58 #define VIRTIO_MEM_MIN_BLOCK_SIZE ((uint32_t)(1 * MiB))
59
60 static uint32_t virtio_mem_default_thp_size(void)
61 {
62 uint32_t default_thp_size = VIRTIO_MEM_MIN_BLOCK_SIZE;
63
64 #if defined(__x86_64__) || defined(__powerpc64__)
65 default_thp_size = 2 * MiB;
66 #elif defined(__aarch64__)
67 if (qemu_real_host_page_size() == 4 * KiB) {
68 default_thp_size = 2 * MiB;
69 } else if (qemu_real_host_page_size() == 16 * KiB) {
70 default_thp_size = 32 * MiB;
71 } else if (qemu_real_host_page_size() == 64 * KiB) {
72 default_thp_size = 512 * MiB;
73 }
74 #elif defined(__s390x__)
75 default_thp_size = 1 * MiB;
76 #endif
77
78 return default_thp_size;
79 }
80
81 /*
82 * The minimum memslot size depends on this setting ("sane default"), the
83 * device block size, and the memory backend page size. The last (or single)
84 * memslot might be smaller than this constant.
85 */
86 #define VIRTIO_MEM_MIN_MEMSLOT_SIZE (1 * GiB)
87
88 /*
89 * We want to have a reasonable default block size such that
90 * 1. We avoid splitting THPs when unplugging memory, which degrades
91 * performance.
92 * 2. We avoid placing THPs for plugged blocks that also cover unplugged
93 * blocks.
94 *
95 * The actual THP size might differ between Linux kernels, so we try to probe
96 * it. In the future (if we ever run into issues regarding 2.), we might want
97 * to disable THP in case we fail to properly probe the THP size, or if the
98 * block size is configured smaller than the THP size.
99 */
100 static uint32_t thp_size;
101
102 #define HPAGE_PMD_SIZE_PATH "/sys/kernel/mm/transparent_hugepage/hpage_pmd_size"
103 #define HPAGE_PATH "/sys/kernel/mm/transparent_hugepage/"
104 static uint32_t virtio_mem_thp_size(void)
105 {
106 gchar *content = NULL;
107 const char *endptr;
108 uint64_t tmp;
109
110 if (thp_size) {
111 return thp_size;
112 }
113
114 /* No THP -> no restrictions. */
115 if (!g_file_test(HPAGE_PATH, G_FILE_TEST_EXISTS)) {
116 thp_size = VIRTIO_MEM_MIN_BLOCK_SIZE;
117 return thp_size;
118 }
119
120 /*
121 * Try to probe the actual THP size, fallback to (sane but eventually
122 * incorrect) default sizes.
123 */
124 if (g_file_get_contents(HPAGE_PMD_SIZE_PATH, &content, NULL, NULL) &&
125 !qemu_strtou64(content, &endptr, 0, &tmp) &&
126 (!endptr || *endptr == '\n')) {
127 /* Sanity-check the value and fallback to something reasonable. */
128 if (!tmp || !is_power_of_2(tmp)) {
129 warn_report("Read unsupported THP size: %" PRIx64, tmp);
130 } else {
131 thp_size = tmp;
132 }
133 }
134
135 if (!thp_size) {
136 thp_size = virtio_mem_default_thp_size();
137 warn_report("Could not detect THP size, falling back to %" PRIx64
138 " MiB.", thp_size / MiB);
139 }
140
141 g_free(content);
142 return thp_size;
143 }
144
145 static uint64_t virtio_mem_default_block_size(RAMBlock *rb)
146 {
147 const uint64_t page_size = qemu_ram_pagesize(rb);
148
149 /* We can have hugetlbfs with a page size smaller than the THP size. */
150 if (page_size == qemu_real_host_page_size()) {
151 return MAX(page_size, virtio_mem_thp_size());
152 }
153 return MAX(page_size, VIRTIO_MEM_MIN_BLOCK_SIZE);
154 }
155
156 static bool virtio_mem_has_shared_zeropage(RAMBlock *rb)
157 {
158 /*
159 * We only have a guaranteed shared zeropage on ordinary MAP_PRIVATE
160 * anonymous RAM. In any other case, reading unplugged *can* populate a
161 * fresh page, consuming actual memory.
162 */
163 return !qemu_ram_is_shared(rb) && qemu_ram_get_fd(rb) < 0 &&
164 qemu_ram_pagesize(rb) == qemu_real_host_page_size();
165 }
166
167 /*
168 * Size the usable region bigger than the requested size if possible. Esp.
169 * Linux guests will only add (aligned) memory blocks in case they fully
170 * fit into the usable region, but plug+online only a subset of the pages.
171 * The memory block size corresponds mostly to the section size.
172 *
173 * This allows e.g., to add 20MB with a section size of 128MB on x86_64, and
174 * a section size of 512MB on arm64 (as long as the start address is properly
175 * aligned, similar to ordinary DIMMs).
176 *
177 * We can change this at any time and maybe even make it configurable if
178 * necessary (as the section size can change). But it's more likely that the
179 * section size will rather get smaller and not bigger over time.
180 */
181 static uint64_t virtio_mem_usable_extent_size(void)
182 {
183 switch (target_arch()) {
184 case SYS_EMU_TARGET_I386:
185 case SYS_EMU_TARGET_X86_64:
186 case SYS_EMU_TARGET_S390X:
187 return 2 * 128 * MiB;
188 case SYS_EMU_TARGET_AARCH64:
189 case SYS_EMU_TARGET_ARM:
190 return 2 * 512 * MiB;
191 default:
192 g_assert_not_reached();
193 }
194 }
195
196 static bool virtio_mem_is_busy(void)
197 {
198 /*
199 * Postcopy cannot handle concurrent discards and we don't want to migrate
200 * pages on-demand with stale content when plugging new blocks.
201 *
202 * For precopy, we don't want unplugged blocks in our migration stream, and
203 * when plugging new blocks, the page content might differ between source
204 * and destination (observable by the guest when not initializing pages
205 * after plugging them) until we're running on the destination (as we didn't
206 * migrate these blocks when they were unplugged).
207 */
208 return migration_in_incoming_postcopy() || migration_is_running();
209 }
210
211 typedef int (*virtio_mem_range_cb)(VirtIOMEM *vmem, void *arg,
212 uint64_t offset, uint64_t size);
213
214 static int virtio_mem_for_each_unplugged_range(VirtIOMEM *vmem, void *arg,
215 virtio_mem_range_cb cb)
216 {
217 unsigned long first_zero_bit, last_zero_bit;
218 uint64_t offset, size;
219 int ret = 0;
220
221 first_zero_bit = find_first_zero_bit(vmem->bitmap, vmem->bitmap_size);
222 while (first_zero_bit < vmem->bitmap_size) {
223 offset = first_zero_bit * vmem->block_size;
224 last_zero_bit = find_next_bit(vmem->bitmap, vmem->bitmap_size,
225 first_zero_bit + 1) - 1;
226 size = (last_zero_bit - first_zero_bit + 1) * vmem->block_size;
227
228 ret = cb(vmem, arg, offset, size);
229 if (ret) {
230 break;
231 }
232 first_zero_bit = find_next_zero_bit(vmem->bitmap, vmem->bitmap_size,
233 last_zero_bit + 2);
234 }
235 return ret;
236 }
237
238 static int virtio_mem_for_each_plugged_range(VirtIOMEM *vmem, void *arg,
239 virtio_mem_range_cb cb)
240 {
241 unsigned long first_bit, last_bit;
242 uint64_t offset, size;
243 int ret = 0;
244
245 first_bit = find_first_bit(vmem->bitmap, vmem->bitmap_size);
246 while (first_bit < vmem->bitmap_size) {
247 offset = first_bit * vmem->block_size;
248 last_bit = find_next_zero_bit(vmem->bitmap, vmem->bitmap_size,
249 first_bit + 1) - 1;
250 size = (last_bit - first_bit + 1) * vmem->block_size;
251
252 ret = cb(vmem, arg, offset, size);
253 if (ret) {
254 break;
255 }
256 first_bit = find_next_bit(vmem->bitmap, vmem->bitmap_size,
257 last_bit + 2);
258 }
259 return ret;
260 }
261
262 static void virtio_mem_notify_unplug(VirtIOMEM *vmem, uint64_t offset,
263 uint64_t size)
264 {
265 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(&vmem->memdev->mr);
266
267 ram_discard_manager_notify_discard(rdm, RAM_DISCARD_SOURCE(vmem),
268 offset, size);
269 }
270
271 static int virtio_mem_notify_plug(VirtIOMEM *vmem, uint64_t offset,
272 uint64_t size)
273 {
274 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(&vmem->memdev->mr);
275
276 return ram_discard_manager_notify_populate(rdm, RAM_DISCARD_SOURCE(vmem),
277 offset, size);
278 }
279
280 static void virtio_mem_notify_unplug_all(VirtIOMEM *vmem)
281 {
282 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(&vmem->memdev->mr);
283
284 if (!vmem->size) {
285 return;
286 }
287
288 ram_discard_manager_notify_discard_all(rdm, RAM_DISCARD_SOURCE(vmem));
289 }
290
291 static bool virtio_mem_is_range_plugged(const VirtIOMEM *vmem,
292 uint64_t start_gpa, uint64_t size)
293 {
294 const unsigned long first_bit = (start_gpa - vmem->addr) / vmem->block_size;
295 const unsigned long last_bit = first_bit + (size / vmem->block_size) - 1;
296 unsigned long found_bit;
297
298 /* We fake a shorter bitmap to avoid searching too far. */
299 found_bit = find_next_zero_bit(vmem->bitmap, last_bit + 1, first_bit);
300 return found_bit > last_bit;
301 }
302
303 static bool virtio_mem_is_range_unplugged(const VirtIOMEM *vmem,
304 uint64_t start_gpa, uint64_t size)
305 {
306 const unsigned long first_bit = (start_gpa - vmem->addr) / vmem->block_size;
307 const unsigned long last_bit = first_bit + (size / vmem->block_size) - 1;
308 unsigned long found_bit;
309
310 /* We fake a shorter bitmap to avoid searching too far. */
311 found_bit = find_next_bit(vmem->bitmap, last_bit + 1, first_bit);
312 return found_bit > last_bit;
313 }
314
315 static void virtio_mem_set_range_plugged(VirtIOMEM *vmem, uint64_t start_gpa,
316 uint64_t size)
317 {
318 const unsigned long bit = (start_gpa - vmem->addr) / vmem->block_size;
319 const unsigned long nbits = size / vmem->block_size;
320
321 bitmap_set(vmem->bitmap, bit, nbits);
322 }
323
324 static void virtio_mem_set_range_unplugged(VirtIOMEM *vmem, uint64_t start_gpa,
325 uint64_t size)
326 {
327 const unsigned long bit = (start_gpa - vmem->addr) / vmem->block_size;
328 const unsigned long nbits = size / vmem->block_size;
329
330 bitmap_clear(vmem->bitmap, bit, nbits);
331 }
332
333 static void virtio_mem_send_response(VirtIOMEM *vmem, VirtQueueElement *elem,
334 struct virtio_mem_resp *resp)
335 {
336 VirtIODevice *vdev = VIRTIO_DEVICE(vmem);
337 VirtQueue *vq = vmem->vq;
338
339 trace_virtio_mem_send_response(le16_to_cpu(resp->type));
340 iov_from_buf(elem->in_sg, elem->in_num, 0, resp, sizeof(*resp));
341
342 virtqueue_push(vq, elem, sizeof(*resp));
343 virtio_notify(vdev, vq);
344 }
345
346 static void virtio_mem_send_response_simple(VirtIOMEM *vmem,
347 VirtQueueElement *elem,
348 uint16_t type)
349 {
350 struct virtio_mem_resp resp = {
351 .type = cpu_to_le16(type),
352 };
353
354 virtio_mem_send_response(vmem, elem, &resp);
355 }
356
357 static bool virtio_mem_valid_range(const VirtIOMEM *vmem, uint64_t gpa,
358 uint64_t size)
359 {
360 if (!QEMU_IS_ALIGNED(gpa, vmem->block_size)) {
361 return false;
362 }
363 if (gpa + size < gpa || !size) {
364 return false;
365 }
366 if (gpa < vmem->addr || gpa >= vmem->addr + vmem->usable_region_size) {
367 return false;
368 }
369 if (gpa + size > vmem->addr + vmem->usable_region_size) {
370 return false;
371 }
372 return true;
373 }
374
375 static void virtio_mem_activate_memslot(VirtIOMEM *vmem, unsigned int idx)
376 {
377 const uint64_t memslot_offset = idx * vmem->memslot_size;
378
379 assert(vmem->memslots);
380
381 /*
382 * Instead of enabling/disabling memslots, we add/remove them. This should
383 * make address space updates faster, because we don't have to loop over
384 * many disabled subregions.
385 */
386 if (memory_region_is_mapped(&vmem->memslots[idx])) {
387 return;
388 }
389 memory_region_add_subregion(vmem->mr, memslot_offset, &vmem->memslots[idx]);
390 }
391
392 static void virtio_mem_deactivate_memslot(VirtIOMEM *vmem, unsigned int idx)
393 {
394 assert(vmem->memslots);
395
396 if (!memory_region_is_mapped(&vmem->memslots[idx])) {
397 return;
398 }
399 memory_region_del_subregion(vmem->mr, &vmem->memslots[idx]);
400 }
401
402 static void virtio_mem_activate_memslots_to_plug(VirtIOMEM *vmem,
403 uint64_t offset, uint64_t size)
404 {
405 const unsigned int start_idx = offset / vmem->memslot_size;
406 const unsigned int end_idx = (offset + size + vmem->memslot_size - 1) /
407 vmem->memslot_size;
408 unsigned int idx;
409
410 assert(vmem->dynamic_memslots);
411
412 /* Activate all involved memslots in a single transaction. */
413 memory_region_transaction_begin();
414 for (idx = start_idx; idx < end_idx; idx++) {
415 virtio_mem_activate_memslot(vmem, idx);
416 }
417 memory_region_transaction_commit();
418 }
419
420 static void virtio_mem_deactivate_unplugged_memslots(VirtIOMEM *vmem,
421 uint64_t offset,
422 uint64_t size)
423 {
424 const uint64_t region_size = memory_region_size(&vmem->memdev->mr);
425 const unsigned int start_idx = offset / vmem->memslot_size;
426 const unsigned int end_idx = (offset + size + vmem->memslot_size - 1) /
427 vmem->memslot_size;
428 unsigned int idx;
429
430 assert(vmem->dynamic_memslots);
431
432 /* Deactivate all memslots with unplugged blocks in a single transaction. */
433 memory_region_transaction_begin();
434 for (idx = start_idx; idx < end_idx; idx++) {
435 const uint64_t memslot_offset = idx * vmem->memslot_size;
436 uint64_t memslot_size = vmem->memslot_size;
437
438 /* The size of the last memslot might be smaller. */
439 if (idx == vmem->nb_memslots - 1) {
440 memslot_size = region_size - memslot_offset;
441 }
442
443 /*
444 * Partially covered memslots might still have some blocks plugged and
445 * have to remain active if that's the case.
446 */
447 if (offset > memslot_offset ||
448 offset + size < memslot_offset + memslot_size) {
449 const uint64_t gpa = vmem->addr + memslot_offset;
450
451 if (!virtio_mem_is_range_unplugged(vmem, gpa, memslot_size)) {
452 continue;
453 }
454 }
455
456 virtio_mem_deactivate_memslot(vmem, idx);
457 }
458 memory_region_transaction_commit();
459 }
460
461 static int virtio_mem_set_block_state(VirtIOMEM *vmem, uint64_t start_gpa,
462 uint64_t size, bool plug)
463 {
464 const uint64_t offset = start_gpa - vmem->addr;
465 RAMBlock *rb = vmem->memdev->mr.ram_block;
466 int ret = 0;
467
468 if (virtio_mem_is_busy()) {
469 return -EBUSY;
470 }
471
472 if (!plug) {
473 if (ram_block_discard_range(rb, offset, size)) {
474 return -EBUSY;
475 }
476 virtio_mem_notify_unplug(vmem, offset, size);
477 virtio_mem_set_range_unplugged(vmem, start_gpa, size);
478 /* Deactivate completely unplugged memslots after updating the state. */
479 if (vmem->dynamic_memslots) {
480 virtio_mem_deactivate_unplugged_memslots(vmem, offset, size);
481 }
482 return 0;
483 }
484
485 if (vmem->prealloc) {
486 void *area = memory_region_get_ram_ptr(&vmem->memdev->mr) + offset;
487 int fd = memory_region_get_fd(&vmem->memdev->mr);
488 Error *local_err = NULL;
489
490 if (!qemu_prealloc_mem(fd, area, size, 1, NULL, false, &local_err)) {
491 warn_report_err_once(local_err);
492 ret = -EBUSY;
493 }
494 }
495
496 if (!ret) {
497 /*
498 * Activate before notifying and rollback in case of any errors.
499 *
500 * When activating a yet inactive memslot, memory notifiers will get
501 * notified about the added memory region and can register with the
502 * RamDiscardManager; this will traverse all plugged blocks and skip the
503 * blocks we are plugging here. The following notification will inform
504 * registered listeners about the blocks we're plugging.
505 */
506 if (vmem->dynamic_memslots) {
507 virtio_mem_activate_memslots_to_plug(vmem, offset, size);
508 }
509 ret = virtio_mem_notify_plug(vmem, offset, size);
510 if (ret && vmem->dynamic_memslots) {
511 virtio_mem_deactivate_unplugged_memslots(vmem, offset, size);
512 }
513 }
514 if (ret) {
515 /* Could be preallocation or a notifier populated memory. */
516 ram_block_discard_range(vmem->memdev->mr.ram_block, offset, size);
517 return -EBUSY;
518 }
519
520 virtio_mem_set_range_plugged(vmem, start_gpa, size);
521 return 0;
522 }
523
524 static int virtio_mem_state_change_request(VirtIOMEM *vmem, uint64_t gpa,
525 uint16_t nb_blocks, bool plug)
526 {
527 const uint64_t size = nb_blocks * vmem->block_size;
528 int ret;
529
530 if (!virtio_mem_valid_range(vmem, gpa, size)) {
531 return VIRTIO_MEM_RESP_ERROR;
532 }
533
534 if (plug && (vmem->size + size > vmem->requested_size)) {
535 return VIRTIO_MEM_RESP_NACK;
536 }
537
538 /* test if really all blocks are in the opposite state */
539 if ((plug && !virtio_mem_is_range_unplugged(vmem, gpa, size)) ||
540 (!plug && !virtio_mem_is_range_plugged(vmem, gpa, size))) {
541 return VIRTIO_MEM_RESP_ERROR;
542 }
543
544 ret = virtio_mem_set_block_state(vmem, gpa, size, plug);
545 if (ret) {
546 return VIRTIO_MEM_RESP_BUSY;
547 }
548 if (plug) {
549 vmem->size += size;
550 } else {
551 vmem->size -= size;
552 }
553 notifier_list_notify(&vmem->size_change_notifiers, &vmem->size);
554 return VIRTIO_MEM_RESP_ACK;
555 }
556
557 static void virtio_mem_plug_request(VirtIOMEM *vmem, VirtQueueElement *elem,
558 struct virtio_mem_req *req)
559 {
560 const uint64_t gpa = le64_to_cpu(req->u.plug.addr);
561 const uint16_t nb_blocks = le16_to_cpu(req->u.plug.nb_blocks);
562 uint16_t type;
563
564 trace_virtio_mem_plug_request(gpa, nb_blocks);
565 type = virtio_mem_state_change_request(vmem, gpa, nb_blocks, true);
566 virtio_mem_send_response_simple(vmem, elem, type);
567 }
568
569 static void virtio_mem_unplug_request(VirtIOMEM *vmem, VirtQueueElement *elem,
570 struct virtio_mem_req *req)
571 {
572 const uint64_t gpa = le64_to_cpu(req->u.unplug.addr);
573 const uint16_t nb_blocks = le16_to_cpu(req->u.unplug.nb_blocks);
574 uint16_t type;
575
576 trace_virtio_mem_unplug_request(gpa, nb_blocks);
577 type = virtio_mem_state_change_request(vmem, gpa, nb_blocks, false);
578 virtio_mem_send_response_simple(vmem, elem, type);
579 }
580
581 static void virtio_mem_resize_usable_region(VirtIOMEM *vmem,
582 uint64_t requested_size,
583 bool can_shrink)
584 {
585 uint64_t newsize = MIN(memory_region_size(&vmem->memdev->mr),
586 requested_size + virtio_mem_usable_extent_size());
587
588 /* The usable region size always has to be multiples of the block size. */
589 newsize = QEMU_ALIGN_UP(newsize, vmem->block_size);
590
591 if (!requested_size) {
592 newsize = 0;
593 }
594
595 if (newsize < vmem->usable_region_size && !can_shrink) {
596 return;
597 }
598
599 trace_virtio_mem_resized_usable_region(vmem->usable_region_size, newsize);
600 vmem->usable_region_size = newsize;
601 }
602
603 static int virtio_mem_unplug_all(VirtIOMEM *vmem)
604 {
605 const uint64_t region_size = memory_region_size(&vmem->memdev->mr);
606 RAMBlock *rb = vmem->memdev->mr.ram_block;
607
608 if (vmem->size) {
609 if (virtio_mem_is_busy()) {
610 return -EBUSY;
611 }
612 if (ram_block_discard_range(rb, 0, qemu_ram_get_used_length(rb))) {
613 return -EBUSY;
614 }
615 virtio_mem_notify_unplug_all(vmem);
616
617 bitmap_clear(vmem->bitmap, 0, vmem->bitmap_size);
618 vmem->size = 0;
619 notifier_list_notify(&vmem->size_change_notifiers, &vmem->size);
620
621 /* Deactivate all memslots after updating the state. */
622 if (vmem->dynamic_memslots) {
623 virtio_mem_deactivate_unplugged_memslots(vmem, 0, region_size);
624 }
625 }
626
627 trace_virtio_mem_unplugged_all();
628 virtio_mem_resize_usable_region(vmem, vmem->requested_size, true);
629 return 0;
630 }
631
632 static void virtio_mem_unplug_all_request(VirtIOMEM *vmem,
633 VirtQueueElement *elem)
634 {
635 trace_virtio_mem_unplug_all_request();
636 if (virtio_mem_unplug_all(vmem)) {
637 virtio_mem_send_response_simple(vmem, elem, VIRTIO_MEM_RESP_BUSY);
638 } else {
639 virtio_mem_send_response_simple(vmem, elem, VIRTIO_MEM_RESP_ACK);
640 }
641 }
642
643 static void virtio_mem_state_request(VirtIOMEM *vmem, VirtQueueElement *elem,
644 struct virtio_mem_req *req)
645 {
646 const uint16_t nb_blocks = le16_to_cpu(req->u.state.nb_blocks);
647 const uint64_t gpa = le64_to_cpu(req->u.state.addr);
648 const uint64_t size = nb_blocks * vmem->block_size;
649 struct virtio_mem_resp resp = {
650 .type = cpu_to_le16(VIRTIO_MEM_RESP_ACK),
651 };
652
653 trace_virtio_mem_state_request(gpa, nb_blocks);
654 if (!virtio_mem_valid_range(vmem, gpa, size)) {
655 virtio_mem_send_response_simple(vmem, elem, VIRTIO_MEM_RESP_ERROR);
656 return;
657 }
658
659 if (virtio_mem_is_range_plugged(vmem, gpa, size)) {
660 resp.u.state.state = cpu_to_le16(VIRTIO_MEM_STATE_PLUGGED);
661 } else if (virtio_mem_is_range_unplugged(vmem, gpa, size)) {
662 resp.u.state.state = cpu_to_le16(VIRTIO_MEM_STATE_UNPLUGGED);
663 } else {
664 resp.u.state.state = cpu_to_le16(VIRTIO_MEM_STATE_MIXED);
665 }
666 trace_virtio_mem_state_response(le16_to_cpu(resp.u.state.state));
667 virtio_mem_send_response(vmem, elem, &resp);
668 }
669
670 static void virtio_mem_handle_request(VirtIODevice *vdev, VirtQueue *vq)
671 {
672 const int len = sizeof(struct virtio_mem_req);
673 VirtIOMEM *vmem = VIRTIO_MEM(vdev);
674 VirtQueueElement *elem;
675 struct virtio_mem_req req;
676 uint16_t type;
677
678 while (true) {
679 elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
680 if (!elem) {
681 return;
682 }
683
684 if (iov_to_buf(elem->out_sg, elem->out_num, 0, &req, len) < len) {
685 virtio_error(vdev, "virtio-mem protocol violation: invalid request"
686 " size: %d", len);
687 virtqueue_detach_element(vq, elem, 0);
688 g_free(elem);
689 return;
690 }
691
692 if (iov_size(elem->in_sg, elem->in_num) <
693 sizeof(struct virtio_mem_resp)) {
694 virtio_error(vdev, "virtio-mem protocol violation: not enough space"
695 " for response: %zu",
696 iov_size(elem->in_sg, elem->in_num));
697 virtqueue_detach_element(vq, elem, 0);
698 g_free(elem);
699 return;
700 }
701
702 type = le16_to_cpu(req.type);
703 switch (type) {
704 case VIRTIO_MEM_REQ_PLUG:
705 virtio_mem_plug_request(vmem, elem, &req);
706 break;
707 case VIRTIO_MEM_REQ_UNPLUG:
708 virtio_mem_unplug_request(vmem, elem, &req);
709 break;
710 case VIRTIO_MEM_REQ_UNPLUG_ALL:
711 virtio_mem_unplug_all_request(vmem, elem);
712 break;
713 case VIRTIO_MEM_REQ_STATE:
714 virtio_mem_state_request(vmem, elem, &req);
715 break;
716 default:
717 virtio_error(vdev, "virtio-mem protocol violation: unknown request"
718 " type: %d", type);
719 virtqueue_detach_element(vq, elem, 0);
720 g_free(elem);
721 return;
722 }
723
724 g_free(elem);
725 }
726 }
727
728 static void virtio_mem_get_config(VirtIODevice *vdev, uint8_t *config_data)
729 {
730 VirtIOMEM *vmem = VIRTIO_MEM(vdev);
731 struct virtio_mem_config *config = (void *) config_data;
732
733 config->block_size = cpu_to_le64(vmem->block_size);
734 config->node_id = cpu_to_le16(vmem->node);
735 config->requested_size = cpu_to_le64(vmem->requested_size);
736 config->plugged_size = cpu_to_le64(vmem->size);
737 config->addr = cpu_to_le64(vmem->addr);
738 config->region_size = cpu_to_le64(memory_region_size(&vmem->memdev->mr));
739 config->usable_region_size = cpu_to_le64(vmem->usable_region_size);
740 }
741
742 static uint64_t virtio_mem_get_features(VirtIODevice *vdev, uint64_t features,
743 Error **errp)
744 {
745 MachineState *ms = MACHINE(qdev_get_machine());
746 VirtIOMEM *vmem = VIRTIO_MEM(vdev);
747
748 if (ms->numa_state && acpi_builtin()) {
749 virtio_add_feature(&features, VIRTIO_MEM_F_ACPI_PXM);
750 }
751 assert(vmem->unplugged_inaccessible != ON_OFF_AUTO_AUTO);
752 if (vmem->unplugged_inaccessible == ON_OFF_AUTO_ON) {
753 virtio_add_feature(&features, VIRTIO_MEM_F_UNPLUGGED_INACCESSIBLE);
754 }
755 if (qemu_wakeup_suspend_enabled()) {
756 virtio_add_feature(&features, VIRTIO_MEM_F_PERSISTENT_SUSPEND);
757 }
758 return features;
759 }
760
761 static int virtio_mem_validate_features(VirtIODevice *vdev)
762 {
763 if (virtio_host_has_feature(vdev, VIRTIO_MEM_F_UNPLUGGED_INACCESSIBLE) &&
764 !virtio_vdev_has_feature(vdev, VIRTIO_MEM_F_UNPLUGGED_INACCESSIBLE)) {
765 return -EFAULT;
766 }
767 return 0;
768 }
769
770 static void virtio_mem_prepare_mr(VirtIOMEM *vmem)
771 {
772 const uint64_t region_size = memory_region_size(&vmem->memdev->mr);
773
774 assert(!vmem->mr && vmem->dynamic_memslots);
775 vmem->mr = g_new0(MemoryRegion, 1);
776 memory_region_init(vmem->mr, OBJECT(vmem), "virtio-mem",
777 region_size);
778 vmem->mr->align = memory_region_get_alignment(&vmem->memdev->mr);
779 }
780
781 static void virtio_mem_prepare_memslots(VirtIOMEM *vmem)
782 {
783 const uint64_t region_size = memory_region_size(&vmem->memdev->mr);
784 unsigned int idx;
785
786 g_assert(!vmem->memslots && vmem->nb_memslots && vmem->dynamic_memslots);
787 vmem->memslots = g_new0(MemoryRegion, vmem->nb_memslots);
788
789 /* Initialize our memslots, but don't map them yet. */
790 for (idx = 0; idx < vmem->nb_memslots; idx++) {
791 const uint64_t memslot_offset = idx * vmem->memslot_size;
792 uint64_t memslot_size = vmem->memslot_size;
793 char name[20];
794
795 /* The size of the last memslot might be smaller. */
796 if (idx == vmem->nb_memslots - 1) {
797 memslot_size = region_size - memslot_offset;
798 }
799
800 snprintf(name, sizeof(name), "memslot-%u", idx);
801 memory_region_init_alias(&vmem->memslots[idx], OBJECT(vmem), name,
802 &vmem->memdev->mr, memslot_offset,
803 memslot_size);
804 /*
805 * We want to be able to atomically and efficiently activate/deactivate
806 * individual memslots without affecting adjacent memslots in memory
807 * notifiers.
808 */
809 memory_region_set_unmergeable(&vmem->memslots[idx], true);
810 }
811 }
812
813 static void virtio_mem_device_realize(DeviceState *dev, Error **errp)
814 {
815 MachineState *ms = MACHINE(qdev_get_machine());
816 int nb_numa_nodes = ms->numa_state ? ms->numa_state->num_nodes : 0;
817 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
818 VirtIOMEM *vmem = VIRTIO_MEM(dev);
819 uint64_t page_size;
820 RAMBlock *rb;
821 Object *obj;
822 int ret;
823
824 if (!vmem->memdev) {
825 error_setg(errp, "'%s' property is not set", VIRTIO_MEM_MEMDEV_PROP);
826 return;
827 } else if (host_memory_backend_is_mapped(vmem->memdev)) {
828 error_setg(errp, "'%s' property specifies a busy memdev: %s",
829 VIRTIO_MEM_MEMDEV_PROP,
830 object_get_canonical_path_component(OBJECT(vmem->memdev)));
831 return;
832 } else if (!memory_region_is_ram(&vmem->memdev->mr) ||
833 memory_region_is_rom(&vmem->memdev->mr) ||
834 !vmem->memdev->mr.ram_block) {
835 error_setg(errp, "'%s' property specifies an unsupported memdev",
836 VIRTIO_MEM_MEMDEV_PROP);
837 return;
838 } else if (vmem->memdev->prealloc) {
839 error_setg(errp, "'%s' property specifies a memdev with preallocation"
840 " enabled: %s. Instead, specify 'prealloc=on' for the"
841 " virtio-mem device. ", VIRTIO_MEM_MEMDEV_PROP,
842 object_get_canonical_path_component(OBJECT(vmem->memdev)));
843 return;
844 }
845
846 if ((nb_numa_nodes && vmem->node >= nb_numa_nodes) ||
847 (!nb_numa_nodes && vmem->node)) {
848 error_setg(errp, "'%s' property has value '%" PRIu32 "', which exceeds"
849 "the number of numa nodes: %d", VIRTIO_MEM_NODE_PROP,
850 vmem->node, nb_numa_nodes ? nb_numa_nodes : 1);
851 return;
852 }
853
854 if (should_mlock(mlock_state)) {
855 error_setg(errp, "Incompatible with mlock");
856 return;
857 }
858
859 rb = vmem->memdev->mr.ram_block;
860 page_size = qemu_ram_pagesize(rb);
861
862 if (virtio_mem_has_legacy_guests()) {
863 switch (vmem->unplugged_inaccessible) {
864 case ON_OFF_AUTO_AUTO:
865 if (virtio_mem_has_shared_zeropage(rb)) {
866 vmem->unplugged_inaccessible = ON_OFF_AUTO_OFF;
867 } else {
868 vmem->unplugged_inaccessible = ON_OFF_AUTO_ON;
869 }
870 break;
871 case ON_OFF_AUTO_OFF:
872 if (!virtio_mem_has_shared_zeropage(rb)) {
873 warn_report("'%s' property set to 'off' with a memdev that does"
874 " not support the shared zeropage.",
875 VIRTIO_MEM_UNPLUGGED_INACCESSIBLE_PROP);
876 }
877 break;
878 default:
879 break;
880 }
881 } else {
882 vmem->unplugged_inaccessible = ON_OFF_AUTO_ON;
883 }
884
885 if (vmem->dynamic_memslots &&
886 vmem->unplugged_inaccessible != ON_OFF_AUTO_ON) {
887 error_setg(errp, "'%s' property set to 'on' requires '%s' to be 'on'",
888 VIRTIO_MEM_DYNAMIC_MEMSLOTS_PROP,
889 VIRTIO_MEM_UNPLUGGED_INACCESSIBLE_PROP);
890 return;
891 }
892
893 /*
894 * If the block size wasn't configured by the user, use a sane default. This
895 * allows using hugetlbfs backends of any page size without manual
896 * intervention.
897 */
898 if (!vmem->block_size) {
899 vmem->block_size = virtio_mem_default_block_size(rb);
900 }
901
902 if (vmem->block_size < page_size) {
903 error_setg(errp, "'%s' property has to be at least the page size (0x%"
904 PRIx64 ")", VIRTIO_MEM_BLOCK_SIZE_PROP, page_size);
905 return;
906 } else if (vmem->block_size < virtio_mem_default_block_size(rb)) {
907 warn_report("'%s' property is smaller than the default block size (%"
908 PRIx64 " MiB)", VIRTIO_MEM_BLOCK_SIZE_PROP,
909 virtio_mem_default_block_size(rb) / MiB);
910 }
911 if (!QEMU_IS_ALIGNED(vmem->requested_size, vmem->block_size)) {
912 error_setg(errp, "'%s' property has to be multiples of '%s' (0x%" PRIx64
913 ")", VIRTIO_MEM_REQUESTED_SIZE_PROP,
914 VIRTIO_MEM_BLOCK_SIZE_PROP, vmem->block_size);
915 return;
916 } else if (!QEMU_IS_ALIGNED(vmem->addr, vmem->block_size)) {
917 error_setg(errp, "'%s' property has to be multiples of '%s' (0x%" PRIx64
918 ")", VIRTIO_MEM_ADDR_PROP, VIRTIO_MEM_BLOCK_SIZE_PROP,
919 vmem->block_size);
920 return;
921 } else if (!QEMU_IS_ALIGNED(memory_region_size(&vmem->memdev->mr),
922 vmem->block_size)) {
923 error_setg(errp, "'%s' property memdev size has to be multiples of"
924 "'%s' (0x%" PRIx64 ")", VIRTIO_MEM_MEMDEV_PROP,
925 VIRTIO_MEM_BLOCK_SIZE_PROP, vmem->block_size);
926 return;
927 }
928
929 if (ram_block_coordinated_discard_require(true)) {
930 error_setg(errp, "Discarding RAM is disabled");
931 return;
932 }
933
934 if (memory_region_add_ram_discard_source(&vmem->memdev->mr,
935 RAM_DISCARD_SOURCE(vmem))) {
936 error_setg(errp, "Failed to add RAM discard source");
937 ram_block_coordinated_discard_require(false);
938 return;
939 }
940
941 /*
942 * We don't know at this point whether shared RAM is migrated using
943 * QEMU or migrated using the file content. "x-ignore-shared" will be
944 * configured after realizing the device. So in case we have an
945 * incoming migration, simply always skip the discard step.
946 *
947 * Otherwise, make sure that we start with a clean slate: either the
948 * memory backend might get reused or the shared file might still have
949 * memory allocated.
950 */
951 if (!runstate_check(RUN_STATE_INMIGRATE)) {
952 ret = ram_block_discard_range(rb, 0, qemu_ram_get_used_length(rb));
953 if (ret) {
954 error_setg_errno(errp, -ret, "Unexpected error discarding RAM");
955 memory_region_del_ram_discard_source(&vmem->memdev->mr,
956 RAM_DISCARD_SOURCE(vmem));
957 ram_block_coordinated_discard_require(false);
958 return;
959 }
960 }
961
962 virtio_mem_resize_usable_region(vmem, vmem->requested_size, true);
963
964 vmem->bitmap_size = memory_region_size(&vmem->memdev->mr) /
965 vmem->block_size;
966 vmem->bitmap = bitmap_new(vmem->bitmap_size);
967
968 virtio_init(vdev, VIRTIO_ID_MEM, sizeof(struct virtio_mem_config));
969 vmem->vq = virtio_add_queue(vdev, 128, virtio_mem_handle_request);
970
971 /*
972 * With "dynamic-memslots=off" (old behavior) we always map the whole
973 * RAM memory region directly.
974 */
975 if (vmem->dynamic_memslots) {
976 if (!vmem->mr) {
977 virtio_mem_prepare_mr(vmem);
978 }
979 if (vmem->nb_memslots <= 1) {
980 vmem->nb_memslots = 1;
981 vmem->memslot_size = memory_region_size(&vmem->memdev->mr);
982 }
983 if (!vmem->memslots) {
984 virtio_mem_prepare_memslots(vmem);
985 }
986 } else {
987 assert(!vmem->mr && !vmem->nb_memslots && !vmem->memslots);
988 }
989
990 host_memory_backend_set_mapped(vmem->memdev, true);
991 vmstate_register_ram(&vmem->memdev->mr, DEVICE(vmem));
992 if (vmem->early_migration) {
993 vmstate_register_any(VMSTATE_IF(vmem),
994 &vmstate_virtio_mem_device_early, vmem);
995 }
996
997 /*
998 * We only want to unplug all memory to start with a clean slate when
999 * it is safe for the guest -- during system resets that call
1000 * qemu_devices_reset().
1001 *
1002 * We'll filter out selected qemu_devices_reset() calls used for other
1003 * purposes, like resetting all devices during wakeup from suspend on
1004 * x86 based on the reset type passed to qemu_devices_reset().
1005 *
1006 * Unplugging all memory during simple device resets can result in the VM
1007 * unexpectedly losing RAM, corrupting VM state.
1008 *
1009 * Simple device resets (or resets triggered by getting a parent device
1010 * reset) must not change the state of plugged memory blocks. Therefore,
1011 * we need a dedicated reset object that only gets called during
1012 * qemu_devices_reset().
1013 */
1014 obj = object_new(TYPE_VIRTIO_MEM_SYSTEM_RESET);
1015 vmem->system_reset = VIRTIO_MEM_SYSTEM_RESET(obj);
1016 vmem->system_reset->vmem = vmem;
1017 qemu_register_resettable(obj);
1018 }
1019
1020 static void virtio_mem_device_unrealize(DeviceState *dev)
1021 {
1022 VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1023 VirtIOMEM *vmem = VIRTIO_MEM(dev);
1024
1025 qemu_unregister_resettable(OBJECT(vmem->system_reset));
1026 object_unref(OBJECT(vmem->system_reset));
1027
1028 if (vmem->early_migration) {
1029 vmstate_unregister(VMSTATE_IF(vmem), &vmstate_virtio_mem_device_early,
1030 vmem);
1031 }
1032 vmstate_unregister_ram(&vmem->memdev->mr, DEVICE(vmem));
1033 host_memory_backend_set_mapped(vmem->memdev, false);
1034 virtio_del_queue(vdev, 0);
1035 virtio_cleanup(vdev);
1036 g_free(vmem->bitmap);
1037 /*
1038 * The unplug handler unmapped the memory region, it cannot be
1039 * found via an address space anymore. Unset ourselves.
1040 */
1041 memory_region_del_ram_discard_source(&vmem->memdev->mr, RAM_DISCARD_SOURCE(vmem));
1042 ram_block_coordinated_discard_require(false);
1043 }
1044
1045 static int virtio_mem_discard_range_cb(VirtIOMEM *vmem, void *arg,
1046 uint64_t offset, uint64_t size)
1047 {
1048 RAMBlock *rb = vmem->memdev->mr.ram_block;
1049
1050 return ram_block_discard_range(rb, offset, size) ? -EINVAL : 0;
1051 }
1052
1053 static int virtio_mem_restore_unplugged(VirtIOMEM *vmem)
1054 {
1055 /* Make sure all memory is really discarded after migration. */
1056 return virtio_mem_for_each_unplugged_range(vmem, NULL,
1057 virtio_mem_discard_range_cb);
1058 }
1059
1060 static int virtio_mem_activate_memslot_range_cb(VirtIOMEM *vmem, void *arg,
1061 uint64_t offset, uint64_t size)
1062 {
1063 virtio_mem_activate_memslots_to_plug(vmem, offset, size);
1064 return 0;
1065 }
1066
1067 static int virtio_mem_post_load_bitmap(VirtIOMEM *vmem)
1068 {
1069 RamDiscardManager *rdm = memory_region_get_ram_discard_manager(&vmem->memdev->mr);
1070 /*
1071 * We restored the bitmap and updated the requested size; activate all
1072 * memslots (so listeners register) before notifying about plugged blocks.
1073 */
1074 if (vmem->dynamic_memslots) {
1075 /*
1076 * We don't expect any active memslots at this point to deactivate: no
1077 * memory was plugged on the migration destination.
1078 */
1079 virtio_mem_for_each_plugged_range(vmem, NULL,
1080 virtio_mem_activate_memslot_range_cb);
1081 }
1082
1083 /*
1084 * We started out with all memory discarded and our memory region is mapped
1085 * into an address space. Replay, now that we updated the bitmap.
1086 */
1087 return ram_discard_manager_replay_populated_to_listeners(rdm);
1088 }
1089
1090 static int virtio_mem_post_load(void *opaque, int version_id)
1091 {
1092 VirtIOMEM *vmem = VIRTIO_MEM(opaque);
1093 int ret;
1094
1095 if (!vmem->early_migration) {
1096 ret = virtio_mem_post_load_bitmap(vmem);
1097 if (ret) {
1098 return ret;
1099 }
1100 }
1101
1102 /*
1103 * If shared RAM is migrated using the file content and not using QEMU,
1104 * don't mess with preallocation and postcopy.
1105 */
1106 if (migrate_ram_is_ignored(vmem->memdev->mr.ram_block)) {
1107 return 0;
1108 }
1109
1110 if (vmem->prealloc && !vmem->early_migration) {
1111 warn_report("Proper preallocation with migration requires a newer QEMU machine");
1112 }
1113
1114 if (migration_in_incoming_postcopy()) {
1115 return 0;
1116 }
1117
1118 return virtio_mem_restore_unplugged(vmem);
1119 }
1120
1121 static int virtio_mem_prealloc_range_cb(VirtIOMEM *vmem, void *arg,
1122 uint64_t offset, uint64_t size)
1123 {
1124 void *area = memory_region_get_ram_ptr(&vmem->memdev->mr) + offset;
1125 int fd = memory_region_get_fd(&vmem->memdev->mr);
1126 Error *local_err = NULL;
1127
1128 if (!qemu_prealloc_mem(fd, area, size, 1, NULL, false, &local_err)) {
1129 error_report_err(local_err);
1130 return -ENOMEM;
1131 }
1132 return 0;
1133 }
1134
1135 static int virtio_mem_post_load_early(void *opaque, int version_id)
1136 {
1137 VirtIOMEM *vmem = VIRTIO_MEM(opaque);
1138 RAMBlock *rb = vmem->memdev->mr.ram_block;
1139 int ret;
1140
1141 if (!vmem->prealloc) {
1142 goto post_load_bitmap;
1143 }
1144
1145 /*
1146 * If shared RAM is migrated using the file content and not using QEMU,
1147 * don't mess with preallocation and postcopy.
1148 */
1149 if (migrate_ram_is_ignored(rb)) {
1150 goto post_load_bitmap;
1151 }
1152
1153 /*
1154 * We restored the bitmap and verified that the basic properties
1155 * match on source and destination, so we can go ahead and preallocate
1156 * memory for all plugged memory blocks, before actual RAM migration starts
1157 * touching this memory.
1158 */
1159 ret = virtio_mem_for_each_plugged_range(vmem, NULL,
1160 virtio_mem_prealloc_range_cb);
1161 if (ret) {
1162 return ret;
1163 }
1164
1165 /*
1166 * This is tricky: postcopy wants to start with a clean slate. On
1167 * POSTCOPY_INCOMING_ADVISE, postcopy code discards all (ordinarily
1168 * preallocated) RAM such that postcopy will work as expected later.
1169 *
1170 * However, we run after POSTCOPY_INCOMING_ADVISE -- but before actual
1171 * RAM migration. So let's discard all memory again. This looks like an
1172 * expensive NOP, but actually serves a purpose: we made sure that we
1173 * were able to allocate all required backend memory once. We cannot
1174 * guarantee that the backend memory we will free will remain free
1175 * until we need it during postcopy, but at least we can catch the
1176 * obvious setup issues this way.
1177 */
1178 if (migration_incoming_postcopy_advised()) {
1179 if (ram_block_discard_range(rb, 0, qemu_ram_get_used_length(rb))) {
1180 return -EBUSY;
1181 }
1182 }
1183
1184 post_load_bitmap:
1185 /* Finally, update any other state to be consistent with the new bitmap. */
1186 return virtio_mem_post_load_bitmap(vmem);
1187 }
1188
1189 typedef struct VirtIOMEMMigSanityChecks {
1190 VirtIOMEM *parent;
1191 uint64_t addr;
1192 uint64_t region_size;
1193 uint64_t block_size;
1194 uint32_t node;
1195 } VirtIOMEMMigSanityChecks;
1196
1197 static int virtio_mem_mig_sanity_checks_pre_save(void *opaque)
1198 {
1199 VirtIOMEMMigSanityChecks *tmp = opaque;
1200 VirtIOMEM *vmem = tmp->parent;
1201
1202 tmp->addr = vmem->addr;
1203 tmp->region_size = memory_region_size(&vmem->memdev->mr);
1204 tmp->block_size = vmem->block_size;
1205 tmp->node = vmem->node;
1206 return 0;
1207 }
1208
1209 static int virtio_mem_mig_sanity_checks_post_load(void *opaque, int version_id)
1210 {
1211 VirtIOMEMMigSanityChecks *tmp = opaque;
1212 VirtIOMEM *vmem = tmp->parent;
1213 const uint64_t new_region_size = memory_region_size(&vmem->memdev->mr);
1214
1215 if (tmp->addr != vmem->addr) {
1216 error_report("Property '%s' changed from 0x%" PRIx64 " to 0x%" PRIx64,
1217 VIRTIO_MEM_ADDR_PROP, tmp->addr, vmem->addr);
1218 return -EINVAL;
1219 }
1220 /*
1221 * Note: Preparation for resizable memory regions. The maximum size
1222 * of the memory region must not change during migration.
1223 */
1224 if (tmp->region_size != new_region_size) {
1225 error_report("Property '%s' size changed from 0x%" PRIx64 " to 0x%"
1226 PRIx64, VIRTIO_MEM_MEMDEV_PROP, tmp->region_size,
1227 new_region_size);
1228 return -EINVAL;
1229 }
1230 if (tmp->block_size != vmem->block_size) {
1231 error_report("Property '%s' changed from 0x%" PRIx64 " to 0x%" PRIx64,
1232 VIRTIO_MEM_BLOCK_SIZE_PROP, tmp->block_size,
1233 vmem->block_size);
1234 return -EINVAL;
1235 }
1236 if (tmp->node != vmem->node) {
1237 error_report("Property '%s' changed from %" PRIu32 " to %" PRIu32,
1238 VIRTIO_MEM_NODE_PROP, tmp->node, vmem->node);
1239 return -EINVAL;
1240 }
1241 return 0;
1242 }
1243
1244 static const VMStateDescription vmstate_virtio_mem_sanity_checks = {
1245 .name = "virtio-mem-device/sanity-checks",
1246 .pre_save = virtio_mem_mig_sanity_checks_pre_save,
1247 .post_load = virtio_mem_mig_sanity_checks_post_load,
1248 .fields = (const VMStateField[]) {
1249 VMSTATE_UINT64(addr, VirtIOMEMMigSanityChecks),
1250 VMSTATE_UINT64(region_size, VirtIOMEMMigSanityChecks),
1251 VMSTATE_UINT64(block_size, VirtIOMEMMigSanityChecks),
1252 VMSTATE_UINT32(node, VirtIOMEMMigSanityChecks),
1253 VMSTATE_END_OF_LIST(),
1254 },
1255 };
1256
1257 static bool virtio_mem_vmstate_field_exists(void *opaque, int version_id)
1258 {
1259 const VirtIOMEM *vmem = VIRTIO_MEM(opaque);
1260
1261 /* With early migration, these fields were already migrated. */
1262 return !vmem->early_migration;
1263 }
1264
1265 static const VMStateDescription vmstate_virtio_mem_device = {
1266 .name = "virtio-mem-device",
1267 .minimum_version_id = 1,
1268 .version_id = 1,
1269 .priority = MIG_PRI_VIRTIO_MEM,
1270 .post_load = virtio_mem_post_load,
1271 .fields = (const VMStateField[]) {
1272 VMSTATE_WITH_TMP_TEST(VirtIOMEM, virtio_mem_vmstate_field_exists,
1273 VirtIOMEMMigSanityChecks,
1274 vmstate_virtio_mem_sanity_checks),
1275 VMSTATE_UINT64(usable_region_size, VirtIOMEM),
1276 VMSTATE_UINT64_TEST(size, VirtIOMEM, virtio_mem_vmstate_field_exists),
1277 VMSTATE_UINT64(requested_size, VirtIOMEM),
1278 VMSTATE_BITMAP_TEST(bitmap, VirtIOMEM, virtio_mem_vmstate_field_exists,
1279 0, bitmap_size),
1280 VMSTATE_END_OF_LIST()
1281 },
1282 };
1283
1284 /*
1285 * Transfer properties that are immutable while migration is active early,
1286 * such that we have have this information around before migrating any RAM
1287 * content.
1288 *
1289 * Note that virtio_mem_is_busy() makes sure these properties can no longer
1290 * change on the migration source until migration completed.
1291 *
1292 * With QEMU compat machines, we transmit these properties later, via
1293 * vmstate_virtio_mem_device instead -- see virtio_mem_vmstate_field_exists().
1294 */
1295 static const VMStateDescription vmstate_virtio_mem_device_early = {
1296 .name = "virtio-mem-device-early",
1297 .minimum_version_id = 1,
1298 .version_id = 1,
1299 .early_setup = true,
1300 .post_load = virtio_mem_post_load_early,
1301 .fields = (const VMStateField[]) {
1302 VMSTATE_WITH_TMP(VirtIOMEM, VirtIOMEMMigSanityChecks,
1303 vmstate_virtio_mem_sanity_checks),
1304 VMSTATE_UINT64(size, VirtIOMEM),
1305 VMSTATE_BITMAP(bitmap, VirtIOMEM, 0, bitmap_size),
1306 VMSTATE_END_OF_LIST()
1307 },
1308 };
1309
1310 static const VMStateDescription vmstate_virtio_mem = {
1311 .name = "virtio-mem",
1312 .minimum_version_id = 1,
1313 .version_id = 1,
1314 .fields = (const VMStateField[]) {
1315 VMSTATE_VIRTIO_DEVICE,
1316 VMSTATE_END_OF_LIST()
1317 },
1318 };
1319
1320 static void virtio_mem_fill_device_info(const VirtIOMEM *vmem,
1321 VirtioMEMDeviceInfo *vi)
1322 {
1323 vi->memaddr = vmem->addr;
1324 vi->node = vmem->node;
1325 vi->requested_size = vmem->requested_size;
1326 vi->size = vmem->size;
1327 vi->max_size = memory_region_size(&vmem->memdev->mr);
1328 vi->block_size = vmem->block_size;
1329 vi->memdev = object_get_canonical_path(OBJECT(vmem->memdev));
1330 }
1331
1332 static MemoryRegion *virtio_mem_get_memory_region(VirtIOMEM *vmem, Error **errp)
1333 {
1334 if (!vmem->memdev) {
1335 error_setg(errp, "'%s' property must be set", VIRTIO_MEM_MEMDEV_PROP);
1336 return NULL;
1337 } else if (vmem->dynamic_memslots) {
1338 if (!vmem->mr) {
1339 virtio_mem_prepare_mr(vmem);
1340 }
1341 return vmem->mr;
1342 }
1343
1344 return &vmem->memdev->mr;
1345 }
1346
1347 static void virtio_mem_decide_memslots(VirtIOMEM *vmem, unsigned int limit)
1348 {
1349 uint64_t region_size, memslot_size, min_memslot_size;
1350 unsigned int memslots;
1351 RAMBlock *rb;
1352
1353 if (!vmem->dynamic_memslots) {
1354 return;
1355 }
1356
1357 /* We're called exactly once, before realizing the device. */
1358 assert(!vmem->nb_memslots);
1359
1360 /* If realizing the device will fail, just assume a single memslot. */
1361 if (limit <= 1 || !vmem->memdev || !vmem->memdev->mr.ram_block) {
1362 vmem->nb_memslots = 1;
1363 return;
1364 }
1365
1366 rb = vmem->memdev->mr.ram_block;
1367 region_size = memory_region_size(&vmem->memdev->mr);
1368
1369 /*
1370 * Determine the default block size now, to determine the minimum memslot
1371 * size. We want the minimum slot size to be at least the device block size.
1372 */
1373 if (!vmem->block_size) {
1374 vmem->block_size = virtio_mem_default_block_size(rb);
1375 }
1376 /* If realizing the device will fail, just assume a single memslot. */
1377 if (vmem->block_size < qemu_ram_pagesize(rb) ||
1378 !QEMU_IS_ALIGNED(region_size, vmem->block_size)) {
1379 vmem->nb_memslots = 1;
1380 return;
1381 }
1382
1383 /*
1384 * All memslots except the last one have a reasonable minimum size, and
1385 * and all memslot sizes are aligned to the device block size.
1386 */
1387 memslot_size = QEMU_ALIGN_UP(region_size / limit, vmem->block_size);
1388 min_memslot_size = MAX(vmem->block_size, VIRTIO_MEM_MIN_MEMSLOT_SIZE);
1389 memslot_size = MAX(memslot_size, min_memslot_size);
1390
1391 memslots = QEMU_ALIGN_UP(region_size, memslot_size) / memslot_size;
1392 if (memslots != 1) {
1393 vmem->memslot_size = memslot_size;
1394 }
1395 vmem->nb_memslots = memslots;
1396 }
1397
1398 static unsigned int virtio_mem_get_memslots(VirtIOMEM *vmem)
1399 {
1400 if (!vmem->dynamic_memslots) {
1401 /* Exactly one static RAM memory region. */
1402 return 1;
1403 }
1404
1405 /* We're called after instructed to make a decision. */
1406 g_assert(vmem->nb_memslots);
1407 return vmem->nb_memslots;
1408 }
1409
1410 static void virtio_mem_add_size_change_notifier(VirtIOMEM *vmem,
1411 Notifier *notifier)
1412 {
1413 notifier_list_add(&vmem->size_change_notifiers, notifier);
1414 }
1415
1416 static void virtio_mem_remove_size_change_notifier(VirtIOMEM *vmem,
1417 Notifier *notifier)
1418 {
1419 notifier_remove(notifier);
1420 }
1421
1422 static void virtio_mem_get_size(Object *obj, Visitor *v, const char *name,
1423 void *opaque, Error **errp)
1424 {
1425 const VirtIOMEM *vmem = VIRTIO_MEM(obj);
1426 uint64_t value = vmem->size;
1427
1428 visit_type_size(v, name, &value, errp);
1429 }
1430
1431 static void virtio_mem_get_requested_size(Object *obj, Visitor *v,
1432 const char *name, void *opaque,
1433 Error **errp)
1434 {
1435 const VirtIOMEM *vmem = VIRTIO_MEM(obj);
1436 uint64_t value = vmem->requested_size;
1437
1438 visit_type_size(v, name, &value, errp);
1439 }
1440
1441 static void virtio_mem_set_requested_size(Object *obj, Visitor *v,
1442 const char *name, void *opaque,
1443 Error **errp)
1444 {
1445 VirtIOMEM *vmem = VIRTIO_MEM(obj);
1446 uint64_t value;
1447
1448 if (!visit_type_size(v, name, &value, errp)) {
1449 return;
1450 }
1451
1452 /*
1453 * The block size and memory backend are not fixed until the device was
1454 * realized. realize() will verify these properties then.
1455 */
1456 if (qdev_is_realized(DEVICE(obj))) {
1457 if (!QEMU_IS_ALIGNED(value, vmem->block_size)) {
1458 error_setg(errp, "'%s' has to be multiples of '%s' (0x%" PRIx64
1459 ")", name, VIRTIO_MEM_BLOCK_SIZE_PROP,
1460 vmem->block_size);
1461 return;
1462 } else if (value > memory_region_size(&vmem->memdev->mr)) {
1463 error_setg(errp, "'%s' cannot exceed the memory backend size"
1464 "(0x%" PRIx64 ")", name,
1465 memory_region_size(&vmem->memdev->mr));
1466 return;
1467 }
1468
1469 if (value != vmem->requested_size) {
1470 virtio_mem_resize_usable_region(vmem, value, false);
1471 vmem->requested_size = value;
1472 }
1473 /*
1474 * Trigger a config update so the guest gets notified. We trigger
1475 * even if the size didn't change (especially helpful for debugging).
1476 */
1477 virtio_notify_config(VIRTIO_DEVICE(vmem));
1478 } else {
1479 vmem->requested_size = value;
1480 }
1481 }
1482
1483 static void virtio_mem_get_block_size(Object *obj, Visitor *v, const char *name,
1484 void *opaque, Error **errp)
1485 {
1486 const VirtIOMEM *vmem = VIRTIO_MEM(obj);
1487 uint64_t value = vmem->block_size;
1488
1489 /*
1490 * If not configured by the user (and we're not realized yet), use the
1491 * default block size we would use with the current memory backend.
1492 */
1493 if (!value) {
1494 if (vmem->memdev && memory_region_is_ram(&vmem->memdev->mr)) {
1495 value = virtio_mem_default_block_size(vmem->memdev->mr.ram_block);
1496 } else {
1497 value = virtio_mem_thp_size();
1498 }
1499 }
1500
1501 visit_type_size(v, name, &value, errp);
1502 }
1503
1504 static void virtio_mem_set_block_size(Object *obj, Visitor *v, const char *name,
1505 void *opaque, Error **errp)
1506 {
1507 VirtIOMEM *vmem = VIRTIO_MEM(obj);
1508 uint64_t value;
1509
1510 if (qdev_is_realized(DEVICE(obj))) {
1511 error_setg(errp, "'%s' cannot be changed", name);
1512 return;
1513 }
1514
1515 if (!visit_type_size(v, name, &value, errp)) {
1516 return;
1517 }
1518
1519 if (value < VIRTIO_MEM_MIN_BLOCK_SIZE) {
1520 error_setg(errp, "'%s' property has to be at least 0x%" PRIx32, name,
1521 VIRTIO_MEM_MIN_BLOCK_SIZE);
1522 return;
1523 } else if (!is_power_of_2(value)) {
1524 error_setg(errp, "'%s' property has to be a power of two", name);
1525 return;
1526 }
1527 vmem->block_size = value;
1528 }
1529
1530 static void virtio_mem_instance_init(Object *obj)
1531 {
1532 VirtIOMEM *vmem = VIRTIO_MEM(obj);
1533
1534 notifier_list_init(&vmem->size_change_notifiers);
1535
1536 object_property_add(obj, VIRTIO_MEM_SIZE_PROP, "size", virtio_mem_get_size,
1537 NULL, NULL, NULL);
1538 object_property_add(obj, VIRTIO_MEM_REQUESTED_SIZE_PROP, "size",
1539 virtio_mem_get_requested_size,
1540 virtio_mem_set_requested_size, NULL, NULL);
1541 object_property_add(obj, VIRTIO_MEM_BLOCK_SIZE_PROP, "size",
1542 virtio_mem_get_block_size, virtio_mem_set_block_size,
1543 NULL, NULL);
1544 }
1545
1546 static void virtio_mem_instance_finalize(Object *obj)
1547 {
1548 VirtIOMEM *vmem = VIRTIO_MEM(obj);
1549
1550 /*
1551 * Note: the core already dropped the references on all memory regions
1552 * (it's passed as the owner to memory_region_init_*()) and finalized
1553 * these objects. We can simply free the memory.
1554 */
1555 g_free(vmem->memslots);
1556 vmem->memslots = NULL;
1557 g_free(vmem->mr);
1558 vmem->mr = NULL;
1559 }
1560
1561 static const Property virtio_mem_properties[] = {
1562 DEFINE_PROP_UINT64(VIRTIO_MEM_ADDR_PROP, VirtIOMEM, addr, 0),
1563 DEFINE_PROP_UINT32(VIRTIO_MEM_NODE_PROP, VirtIOMEM, node, 0),
1564 DEFINE_PROP_BOOL(VIRTIO_MEM_PREALLOC_PROP, VirtIOMEM, prealloc, false),
1565 DEFINE_PROP_LINK(VIRTIO_MEM_MEMDEV_PROP, VirtIOMEM, memdev,
1566 TYPE_MEMORY_BACKEND, HostMemoryBackend *),
1567 DEFINE_PROP_BOOL(VIRTIO_MEM_EARLY_MIGRATION_PROP, VirtIOMEM,
1568 early_migration, true),
1569 DEFINE_PROP_BOOL(VIRTIO_MEM_DYNAMIC_MEMSLOTS_PROP, VirtIOMEM,
1570 dynamic_memslots, false),
1571 };
1572
1573 static const Property virtio_mem_legacy_guests_properties[] = {
1574 DEFINE_PROP_ON_OFF_AUTO(VIRTIO_MEM_UNPLUGGED_INACCESSIBLE_PROP, VirtIOMEM,
1575 unplugged_inaccessible, ON_OFF_AUTO_ON),
1576 };
1577
1578 static uint64_t virtio_mem_rds_get_min_granularity(const RamDiscardSource *rds,
1579 const MemoryRegion *mr)
1580 {
1581 const VirtIOMEM *vmem = VIRTIO_MEM(rds);
1582
1583 g_assert(mr == &vmem->memdev->mr);
1584 return vmem->block_size;
1585 }
1586
1587 static bool virtio_mem_rds_is_populated(const RamDiscardSource *rds,
1588 const MemoryRegionSection *s)
1589 {
1590 const VirtIOMEM *vmem = VIRTIO_MEM(rds);
1591 uint64_t start_gpa = vmem->addr + s->offset_within_region;
1592 uint64_t end_gpa = start_gpa + int128_get64(s->size);
1593
1594 g_assert(s->mr == &vmem->memdev->mr);
1595
1596 start_gpa = QEMU_ALIGN_DOWN(start_gpa, vmem->block_size);
1597 end_gpa = QEMU_ALIGN_UP(end_gpa, vmem->block_size);
1598
1599 if (!virtio_mem_valid_range(vmem, start_gpa, end_gpa - start_gpa)) {
1600 return false;
1601 }
1602
1603 return virtio_mem_is_range_plugged(vmem, start_gpa, end_gpa - start_gpa);
1604 }
1605
1606 static void virtio_mem_unplug_request_check(VirtIOMEM *vmem, Error **errp)
1607 {
1608 if (vmem->unplugged_inaccessible == ON_OFF_AUTO_OFF) {
1609 /*
1610 * We could allow it with a usable region size of 0, but let's just
1611 * not care about that legacy setting.
1612 */
1613 error_setg(errp, "virtio-mem device cannot get unplugged while"
1614 " '" VIRTIO_MEM_UNPLUGGED_INACCESSIBLE_PROP "' != 'on'");
1615 return;
1616 }
1617
1618 if (vmem->size) {
1619 error_setg(errp, "virtio-mem device cannot get unplugged while some"
1620 " of its memory is still plugged");
1621 return;
1622 }
1623 if (vmem->requested_size) {
1624 error_setg(errp, "virtio-mem device cannot get unplugged while"
1625 " '" VIRTIO_MEM_REQUESTED_SIZE_PROP "' != '0'");
1626 return;
1627 }
1628 }
1629
1630 static void virtio_mem_class_init(ObjectClass *klass, const void *data)
1631 {
1632 DeviceClass *dc = DEVICE_CLASS(klass);
1633 VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
1634 VirtIOMEMClass *vmc = VIRTIO_MEM_CLASS(klass);
1635 RamDiscardSourceClass *rdsc = RAM_DISCARD_SOURCE_CLASS(klass);
1636
1637 device_class_set_props(dc, virtio_mem_properties);
1638 if (virtio_mem_has_legacy_guests()) {
1639 device_class_set_props(dc, virtio_mem_legacy_guests_properties);
1640 }
1641 dc->vmsd = &vmstate_virtio_mem;
1642
1643 set_bit(DEVICE_CATEGORY_MISC, dc->categories);
1644 vdc->realize = virtio_mem_device_realize;
1645 vdc->unrealize = virtio_mem_device_unrealize;
1646 vdc->get_config = virtio_mem_get_config;
1647 vdc->get_features = virtio_mem_get_features;
1648 vdc->validate_features = virtio_mem_validate_features;
1649 vdc->vmsd = &vmstate_virtio_mem_device;
1650
1651 vmc->fill_device_info = virtio_mem_fill_device_info;
1652 vmc->get_memory_region = virtio_mem_get_memory_region;
1653 vmc->decide_memslots = virtio_mem_decide_memslots;
1654 vmc->get_memslots = virtio_mem_get_memslots;
1655 vmc->add_size_change_notifier = virtio_mem_add_size_change_notifier;
1656 vmc->remove_size_change_notifier = virtio_mem_remove_size_change_notifier;
1657 vmc->unplug_request_check = virtio_mem_unplug_request_check;
1658
1659 rdsc->get_min_granularity = virtio_mem_rds_get_min_granularity;
1660 rdsc->is_populated = virtio_mem_rds_is_populated;
1661 }
1662
1663 static const TypeInfo virtio_mem_info = {
1664 .name = TYPE_VIRTIO_MEM,
1665 .parent = TYPE_VIRTIO_DEVICE,
1666 .instance_size = sizeof(VirtIOMEM),
1667 .instance_init = virtio_mem_instance_init,
1668 .instance_finalize = virtio_mem_instance_finalize,
1669 .class_init = virtio_mem_class_init,
1670 .class_size = sizeof(VirtIOMEMClass),
1671 .interfaces = (const InterfaceInfo[]) {
1672 { TYPE_RAM_DISCARD_SOURCE },
1673 { }
1674 },
1675 };
1676
1677 static void virtio_register_types(void)
1678 {
1679 type_register_static(&virtio_mem_info);
1680 }
1681
1682 type_init(virtio_register_types)
1683
1684 OBJECT_DEFINE_SIMPLE_TYPE_WITH_INTERFACES(VirtioMemSystemReset, virtio_mem_system_reset, VIRTIO_MEM_SYSTEM_RESET, OBJECT, { TYPE_RESETTABLE_INTERFACE }, { })
1685
1686 static void virtio_mem_system_reset_init(Object *obj)
1687 {
1688 }
1689
1690 static void virtio_mem_system_reset_finalize(Object *obj)
1691 {
1692 }
1693
1694 static ResettableState *virtio_mem_system_reset_get_state(Object *obj)
1695 {
1696 VirtioMemSystemReset *vmem_reset = VIRTIO_MEM_SYSTEM_RESET(obj);
1697
1698 return &vmem_reset->reset_state;
1699 }
1700
1701 static void virtio_mem_system_reset_hold(Object *obj, ResetType type)
1702 {
1703 VirtioMemSystemReset *vmem_reset = VIRTIO_MEM_SYSTEM_RESET(obj);
1704 VirtIOMEM *vmem = vmem_reset->vmem;
1705
1706 /*
1707 * When waking up from standby/suspend-to-ram, do not unplug any memory.
1708 */
1709 if (type == RESET_TYPE_WAKEUP) {
1710 return;
1711 }
1712
1713 /*
1714 * During usual resets, we will unplug all memory and shrink the usable
1715 * region size. This is, however, not possible in all scenarios. Then,
1716 * the guest has to deal with this manually (VIRTIO_MEM_REQ_UNPLUG_ALL).
1717 */
1718 virtio_mem_unplug_all(vmem);
1719 }
1720
1721 static void virtio_mem_system_reset_class_init(ObjectClass *klass,
1722 const void *data)
1723 {
1724 ResettableClass *rc = RESETTABLE_CLASS(klass);
1725
1726 rc->get_state = virtio_mem_system_reset_get_state;
1727 rc->phases.hold = virtio_mem_system_reset_hold;
1728 }