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