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