xref: /openbmc/qemu/hw/virtio/virtio-balloon.c (revision 7cc25f6c)
1 /*
2  * Virtio Balloon Device
3  *
4  * Copyright IBM, Corp. 2008
5  * Copyright (C) 2011 Red Hat, Inc.
6  * Copyright (C) 2011 Amit Shah <amit.shah@redhat.com>
7  *
8  * Authors:
9  *  Anthony Liguori   <aliguori@us.ibm.com>
10  *
11  * This work is licensed under the terms of the GNU GPL, version 2.  See
12  * the COPYING file in the top-level directory.
13  *
14  */
15 
16 #include "qemu/osdep.h"
17 #include "qemu/iov.h"
18 #include "qemu/module.h"
19 #include "qemu/timer.h"
20 #include "hw/virtio/virtio.h"
21 #include "hw/mem/pc-dimm.h"
22 #include "hw/qdev-properties.h"
23 #include "hw/boards.h"
24 #include "sysemu/balloon.h"
25 #include "hw/virtio/virtio-balloon.h"
26 #include "exec/address-spaces.h"
27 #include "qapi/error.h"
28 #include "qapi/qapi-events-machine.h"
29 #include "qapi/visitor.h"
30 #include "trace.h"
31 #include "qemu/error-report.h"
32 #include "migration/misc.h"
33 
34 #include "hw/virtio/virtio-bus.h"
35 #include "hw/virtio/virtio-access.h"
36 
37 #define BALLOON_PAGE_SIZE  (1 << VIRTIO_BALLOON_PFN_SHIFT)
38 
39 typedef struct PartiallyBalloonedPage {
40     ram_addr_t base_gpa;
41     unsigned long *bitmap;
42 } PartiallyBalloonedPage;
43 
44 static void virtio_balloon_pbp_free(PartiallyBalloonedPage *pbp)
45 {
46     if (!pbp->bitmap) {
47         return;
48     }
49     g_free(pbp->bitmap);
50     pbp->bitmap = NULL;
51 }
52 
53 static void virtio_balloon_pbp_alloc(PartiallyBalloonedPage *pbp,
54                                      ram_addr_t base_gpa,
55                                      long subpages)
56 {
57     pbp->base_gpa = base_gpa;
58     pbp->bitmap = bitmap_new(subpages);
59 }
60 
61 static bool virtio_balloon_pbp_matches(PartiallyBalloonedPage *pbp,
62                                        ram_addr_t base_gpa)
63 {
64     return pbp->base_gpa == base_gpa;
65 }
66 
67 static bool virtio_balloon_inhibited(void)
68 {
69     /* Postcopy cannot deal with concurrent discards, so it's special. */
70     return ram_block_discard_is_disabled() || migration_in_incoming_postcopy();
71 }
72 
73 static void balloon_inflate_page(VirtIOBalloon *balloon,
74                                  MemoryRegion *mr, hwaddr mr_offset,
75                                  PartiallyBalloonedPage *pbp)
76 {
77     void *addr = memory_region_get_ram_ptr(mr) + mr_offset;
78     ram_addr_t rb_offset, rb_aligned_offset, base_gpa;
79     RAMBlock *rb;
80     size_t rb_page_size;
81     int subpages;
82 
83     /* XXX is there a better way to get to the RAMBlock than via a
84      * host address? */
85     rb = qemu_ram_block_from_host(addr, false, &rb_offset);
86     rb_page_size = qemu_ram_pagesize(rb);
87 
88     if (rb_page_size == BALLOON_PAGE_SIZE) {
89         /* Easy case */
90 
91         ram_block_discard_range(rb, rb_offset, rb_page_size);
92         /* We ignore errors from ram_block_discard_range(), because it
93          * has already reported them, and failing to discard a balloon
94          * page is not fatal */
95         return;
96     }
97 
98     /* Hard case
99      *
100      * We've put a piece of a larger host page into the balloon - we
101      * need to keep track until we have a whole host page to
102      * discard
103      */
104     warn_report_once(
105 "Balloon used with backing page size > 4kiB, this may not be reliable");
106 
107     rb_aligned_offset = QEMU_ALIGN_DOWN(rb_offset, rb_page_size);
108     subpages = rb_page_size / BALLOON_PAGE_SIZE;
109     base_gpa = memory_region_get_ram_addr(mr) + mr_offset -
110                (rb_offset - rb_aligned_offset);
111 
112     if (pbp->bitmap && !virtio_balloon_pbp_matches(pbp, base_gpa)) {
113         /* We've partially ballooned part of a host page, but now
114          * we're trying to balloon part of a different one.  Too hard,
115          * give up on the old partial page */
116         virtio_balloon_pbp_free(pbp);
117     }
118 
119     if (!pbp->bitmap) {
120         virtio_balloon_pbp_alloc(pbp, base_gpa, subpages);
121     }
122 
123     set_bit((rb_offset - rb_aligned_offset) / BALLOON_PAGE_SIZE,
124             pbp->bitmap);
125 
126     if (bitmap_full(pbp->bitmap, subpages)) {
127         /* We've accumulated a full host page, we can actually discard
128          * it now */
129 
130         ram_block_discard_range(rb, rb_aligned_offset, rb_page_size);
131         /* We ignore errors from ram_block_discard_range(), because it
132          * has already reported them, and failing to discard a balloon
133          * page is not fatal */
134         virtio_balloon_pbp_free(pbp);
135     }
136 }
137 
138 static void balloon_deflate_page(VirtIOBalloon *balloon,
139                                  MemoryRegion *mr, hwaddr mr_offset)
140 {
141     void *addr = memory_region_get_ram_ptr(mr) + mr_offset;
142     ram_addr_t rb_offset;
143     RAMBlock *rb;
144     size_t rb_page_size;
145     void *host_addr;
146     int ret;
147 
148     /* XXX is there a better way to get to the RAMBlock than via a
149      * host address? */
150     rb = qemu_ram_block_from_host(addr, false, &rb_offset);
151     rb_page_size = qemu_ram_pagesize(rb);
152 
153     host_addr = (void *)((uintptr_t)addr & ~(rb_page_size - 1));
154 
155     /* When a page is deflated, we hint the whole host page it lives
156      * on, since we can't do anything smaller */
157     ret = qemu_madvise(host_addr, rb_page_size, QEMU_MADV_WILLNEED);
158     if (ret != 0) {
159         warn_report("Couldn't MADV_WILLNEED on balloon deflate: %s",
160                     strerror(errno));
161         /* Otherwise ignore, failing to page hint shouldn't be fatal */
162     }
163 }
164 
165 static const char *balloon_stat_names[] = {
166    [VIRTIO_BALLOON_S_SWAP_IN] = "stat-swap-in",
167    [VIRTIO_BALLOON_S_SWAP_OUT] = "stat-swap-out",
168    [VIRTIO_BALLOON_S_MAJFLT] = "stat-major-faults",
169    [VIRTIO_BALLOON_S_MINFLT] = "stat-minor-faults",
170    [VIRTIO_BALLOON_S_MEMFREE] = "stat-free-memory",
171    [VIRTIO_BALLOON_S_MEMTOT] = "stat-total-memory",
172    [VIRTIO_BALLOON_S_AVAIL] = "stat-available-memory",
173    [VIRTIO_BALLOON_S_CACHES] = "stat-disk-caches",
174    [VIRTIO_BALLOON_S_HTLB_PGALLOC] = "stat-htlb-pgalloc",
175    [VIRTIO_BALLOON_S_HTLB_PGFAIL] = "stat-htlb-pgfail",
176    [VIRTIO_BALLOON_S_NR] = NULL
177 };
178 
179 /*
180  * reset_stats - Mark all items in the stats array as unset
181  *
182  * This function needs to be called at device initialization and before
183  * updating to a set of newly-generated stats.  This will ensure that no
184  * stale values stick around in case the guest reports a subset of the supported
185  * statistics.
186  */
187 static inline void reset_stats(VirtIOBalloon *dev)
188 {
189     int i;
190     for (i = 0; i < VIRTIO_BALLOON_S_NR; dev->stats[i++] = -1);
191 }
192 
193 static bool balloon_stats_supported(const VirtIOBalloon *s)
194 {
195     VirtIODevice *vdev = VIRTIO_DEVICE(s);
196     return virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_STATS_VQ);
197 }
198 
199 static bool balloon_stats_enabled(const VirtIOBalloon *s)
200 {
201     return s->stats_poll_interval > 0;
202 }
203 
204 static void balloon_stats_destroy_timer(VirtIOBalloon *s)
205 {
206     if (balloon_stats_enabled(s)) {
207         timer_del(s->stats_timer);
208         timer_free(s->stats_timer);
209         s->stats_timer = NULL;
210         s->stats_poll_interval = 0;
211     }
212 }
213 
214 static void balloon_stats_change_timer(VirtIOBalloon *s, int64_t secs)
215 {
216     timer_mod(s->stats_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + secs * 1000);
217 }
218 
219 static void balloon_stats_poll_cb(void *opaque)
220 {
221     VirtIOBalloon *s = opaque;
222     VirtIODevice *vdev = VIRTIO_DEVICE(s);
223 
224     if (s->stats_vq_elem == NULL || !balloon_stats_supported(s)) {
225         /* re-schedule */
226         balloon_stats_change_timer(s, s->stats_poll_interval);
227         return;
228     }
229 
230     virtqueue_push(s->svq, s->stats_vq_elem, s->stats_vq_offset);
231     virtio_notify(vdev, s->svq);
232     g_free(s->stats_vq_elem);
233     s->stats_vq_elem = NULL;
234 }
235 
236 static void balloon_stats_get_all(Object *obj, Visitor *v, const char *name,
237                                   void *opaque, Error **errp)
238 {
239     Error *err = NULL;
240     VirtIOBalloon *s = opaque;
241     int i;
242 
243     if (!visit_start_struct(v, name, NULL, 0, &err)) {
244         goto out;
245     }
246     if (!visit_type_int(v, "last-update", &s->stats_last_update, &err)) {
247         goto out_end;
248     }
249 
250     if (!visit_start_struct(v, "stats", NULL, 0, &err)) {
251         goto out_end;
252     }
253     for (i = 0; i < VIRTIO_BALLOON_S_NR; i++) {
254         if (!visit_type_uint64(v, balloon_stat_names[i], &s->stats[i], &err)) {
255             goto out_nested;
256         }
257     }
258     visit_check_struct(v, &err);
259 out_nested:
260     visit_end_struct(v, NULL);
261 
262     if (!err) {
263         visit_check_struct(v, &err);
264     }
265 out_end:
266     visit_end_struct(v, NULL);
267 out:
268     error_propagate(errp, err);
269 }
270 
271 static void balloon_stats_get_poll_interval(Object *obj, Visitor *v,
272                                             const char *name, void *opaque,
273                                             Error **errp)
274 {
275     VirtIOBalloon *s = opaque;
276     visit_type_int(v, name, &s->stats_poll_interval, errp);
277 }
278 
279 static void balloon_stats_set_poll_interval(Object *obj, Visitor *v,
280                                             const char *name, void *opaque,
281                                             Error **errp)
282 {
283     VirtIOBalloon *s = opaque;
284     int64_t value;
285 
286     if (!visit_type_int(v, name, &value, errp)) {
287         return;
288     }
289 
290     if (value < 0) {
291         error_setg(errp, "timer value must be greater than zero");
292         return;
293     }
294 
295     if (value > UINT32_MAX) {
296         error_setg(errp, "timer value is too big");
297         return;
298     }
299 
300     if (value == s->stats_poll_interval) {
301         return;
302     }
303 
304     if (value == 0) {
305         /* timer=0 disables the timer */
306         balloon_stats_destroy_timer(s);
307         return;
308     }
309 
310     if (balloon_stats_enabled(s)) {
311         /* timer interval change */
312         s->stats_poll_interval = value;
313         balloon_stats_change_timer(s, value);
314         return;
315     }
316 
317     /* create a new timer */
318     g_assert(s->stats_timer == NULL);
319     s->stats_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, balloon_stats_poll_cb, s);
320     s->stats_poll_interval = value;
321     balloon_stats_change_timer(s, 0);
322 }
323 
324 static void virtio_balloon_handle_report(VirtIODevice *vdev, VirtQueue *vq)
325 {
326     VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
327     VirtQueueElement *elem;
328 
329     while ((elem = virtqueue_pop(vq, sizeof(VirtQueueElement)))) {
330         unsigned int i;
331 
332         /*
333          * When we discard the page it has the effect of removing the page
334          * from the hypervisor itself and causing it to be zeroed when it
335          * is returned to us. So we must not discard the page if it is
336          * accessible by another device or process, or if the guest is
337          * expecting it to retain a non-zero value.
338          */
339         if (virtio_balloon_inhibited() || dev->poison_val) {
340             goto skip_element;
341         }
342 
343         for (i = 0; i < elem->in_num; i++) {
344             void *addr = elem->in_sg[i].iov_base;
345             size_t size = elem->in_sg[i].iov_len;
346             ram_addr_t ram_offset;
347             RAMBlock *rb;
348 
349             /*
350              * There is no need to check the memory section to see if
351              * it is ram/readonly/romd like there is for handle_output
352              * below. If the region is not meant to be written to then
353              * address_space_map will have allocated a bounce buffer
354              * and it will be freed in address_space_unmap and trigger
355              * and unassigned_mem_write before failing to copy over the
356              * buffer. If more than one bad descriptor is provided it
357              * will return NULL after the first bounce buffer and fail
358              * to map any resources.
359              */
360             rb = qemu_ram_block_from_host(addr, false, &ram_offset);
361             if (!rb) {
362                 trace_virtio_balloon_bad_addr(elem->in_addr[i]);
363                 continue;
364             }
365 
366             /*
367              * For now we will simply ignore unaligned memory regions, or
368              * regions that overrun the end of the RAMBlock.
369              */
370             if (!QEMU_IS_ALIGNED(ram_offset | size, qemu_ram_pagesize(rb)) ||
371                 (ram_offset + size) > qemu_ram_get_used_length(rb)) {
372                 continue;
373             }
374 
375             ram_block_discard_range(rb, ram_offset, size);
376         }
377 
378 skip_element:
379         virtqueue_push(vq, elem, 0);
380         virtio_notify(vdev, vq);
381         g_free(elem);
382     }
383 }
384 
385 static void virtio_balloon_handle_output(VirtIODevice *vdev, VirtQueue *vq)
386 {
387     VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
388     VirtQueueElement *elem;
389     MemoryRegionSection section;
390 
391     for (;;) {
392         PartiallyBalloonedPage pbp = {};
393         size_t offset = 0;
394         uint32_t pfn;
395 
396         elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
397         if (!elem) {
398             break;
399         }
400 
401         while (iov_to_buf(elem->out_sg, elem->out_num, offset, &pfn, 4) == 4) {
402             unsigned int p = virtio_ldl_p(vdev, &pfn);
403             hwaddr pa;
404 
405             pa = (hwaddr) p << VIRTIO_BALLOON_PFN_SHIFT;
406             offset += 4;
407 
408             section = memory_region_find(get_system_memory(), pa,
409                                          BALLOON_PAGE_SIZE);
410             if (!section.mr) {
411                 trace_virtio_balloon_bad_addr(pa);
412                 continue;
413             }
414             if (!memory_region_is_ram(section.mr) ||
415                 memory_region_is_rom(section.mr) ||
416                 memory_region_is_romd(section.mr)) {
417                 trace_virtio_balloon_bad_addr(pa);
418                 memory_region_unref(section.mr);
419                 continue;
420             }
421 
422             trace_virtio_balloon_handle_output(memory_region_name(section.mr),
423                                                pa);
424             if (!virtio_balloon_inhibited()) {
425                 if (vq == s->ivq) {
426                     balloon_inflate_page(s, section.mr,
427                                          section.offset_within_region, &pbp);
428                 } else if (vq == s->dvq) {
429                     balloon_deflate_page(s, section.mr, section.offset_within_region);
430                 } else {
431                     g_assert_not_reached();
432                 }
433             }
434             memory_region_unref(section.mr);
435         }
436 
437         virtqueue_push(vq, elem, offset);
438         virtio_notify(vdev, vq);
439         g_free(elem);
440         virtio_balloon_pbp_free(&pbp);
441     }
442 }
443 
444 static void virtio_balloon_receive_stats(VirtIODevice *vdev, VirtQueue *vq)
445 {
446     VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
447     VirtQueueElement *elem;
448     VirtIOBalloonStat stat;
449     size_t offset = 0;
450     qemu_timeval tv;
451 
452     elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
453     if (!elem) {
454         goto out;
455     }
456 
457     if (s->stats_vq_elem != NULL) {
458         /* This should never happen if the driver follows the spec. */
459         virtqueue_push(vq, s->stats_vq_elem, 0);
460         virtio_notify(vdev, vq);
461         g_free(s->stats_vq_elem);
462     }
463 
464     s->stats_vq_elem = elem;
465 
466     /* Initialize the stats to get rid of any stale values.  This is only
467      * needed to handle the case where a guest supports fewer stats than it
468      * used to (ie. it has booted into an old kernel).
469      */
470     reset_stats(s);
471 
472     while (iov_to_buf(elem->out_sg, elem->out_num, offset, &stat, sizeof(stat))
473            == sizeof(stat)) {
474         uint16_t tag = virtio_tswap16(vdev, stat.tag);
475         uint64_t val = virtio_tswap64(vdev, stat.val);
476 
477         offset += sizeof(stat);
478         if (tag < VIRTIO_BALLOON_S_NR)
479             s->stats[tag] = val;
480     }
481     s->stats_vq_offset = offset;
482 
483     if (qemu_gettimeofday(&tv) < 0) {
484         warn_report("%s: failed to get time of day", __func__);
485         goto out;
486     }
487 
488     s->stats_last_update = tv.tv_sec;
489 
490 out:
491     if (balloon_stats_enabled(s)) {
492         balloon_stats_change_timer(s, s->stats_poll_interval);
493     }
494 }
495 
496 static void virtio_balloon_handle_free_page_vq(VirtIODevice *vdev,
497                                                VirtQueue *vq)
498 {
499     VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
500     qemu_bh_schedule(s->free_page_bh);
501 }
502 
503 static bool get_free_page_hints(VirtIOBalloon *dev)
504 {
505     VirtQueueElement *elem;
506     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
507     VirtQueue *vq = dev->free_page_vq;
508     bool ret = true;
509 
510     while (dev->block_iothread) {
511         qemu_cond_wait(&dev->free_page_cond, &dev->free_page_lock);
512     }
513 
514     elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
515     if (!elem) {
516         return false;
517     }
518 
519     if (elem->out_num) {
520         uint32_t id;
521         size_t size = iov_to_buf(elem->out_sg, elem->out_num, 0,
522                                  &id, sizeof(id));
523 
524         virtio_tswap32s(vdev, &id);
525         if (unlikely(size != sizeof(id))) {
526             virtio_error(vdev, "received an incorrect cmd id");
527             ret = false;
528             goto out;
529         }
530         if (dev->free_page_hint_status == FREE_PAGE_HINT_S_REQUESTED &&
531             id == dev->free_page_hint_cmd_id) {
532             dev->free_page_hint_status = FREE_PAGE_HINT_S_START;
533         } else {
534             /*
535              * Stop the optimization only when it has started. This
536              * avoids a stale stop sign for the previous command.
537              */
538             if (dev->free_page_hint_status == FREE_PAGE_HINT_S_START) {
539                 dev->free_page_hint_status = FREE_PAGE_HINT_S_STOP;
540             }
541         }
542     }
543 
544     if (elem->in_num) {
545         if (dev->free_page_hint_status == FREE_PAGE_HINT_S_START) {
546             qemu_guest_free_page_hint(elem->in_sg[0].iov_base,
547                                       elem->in_sg[0].iov_len);
548         }
549     }
550 
551 out:
552     virtqueue_push(vq, elem, 1);
553     g_free(elem);
554     return ret;
555 }
556 
557 static void virtio_ballloon_get_free_page_hints(void *opaque)
558 {
559     VirtIOBalloon *dev = opaque;
560     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
561     VirtQueue *vq = dev->free_page_vq;
562     bool continue_to_get_hints;
563 
564     do {
565         qemu_mutex_lock(&dev->free_page_lock);
566         virtio_queue_set_notification(vq, 0);
567         continue_to_get_hints = get_free_page_hints(dev);
568         qemu_mutex_unlock(&dev->free_page_lock);
569         virtio_notify(vdev, vq);
570       /*
571        * Start to poll the vq once the hinting started. Otherwise, continue
572        * only when there are entries on the vq, which need to be given back.
573        */
574     } while (continue_to_get_hints ||
575              dev->free_page_hint_status == FREE_PAGE_HINT_S_START);
576     virtio_queue_set_notification(vq, 1);
577 }
578 
579 static bool virtio_balloon_free_page_support(void *opaque)
580 {
581     VirtIOBalloon *s = opaque;
582     VirtIODevice *vdev = VIRTIO_DEVICE(s);
583 
584     return virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_FREE_PAGE_HINT);
585 }
586 
587 static void virtio_balloon_free_page_start(VirtIOBalloon *s)
588 {
589     VirtIODevice *vdev = VIRTIO_DEVICE(s);
590 
591     /* For the stop and copy phase, we don't need to start the optimization */
592     if (!vdev->vm_running) {
593         return;
594     }
595 
596     qemu_mutex_lock(&s->free_page_lock);
597 
598     if (s->free_page_hint_cmd_id == UINT_MAX) {
599         s->free_page_hint_cmd_id =
600                        VIRTIO_BALLOON_FREE_PAGE_HINT_CMD_ID_MIN;
601     } else {
602         s->free_page_hint_cmd_id++;
603     }
604 
605     s->free_page_hint_status = FREE_PAGE_HINT_S_REQUESTED;
606     qemu_mutex_unlock(&s->free_page_lock);
607 
608     virtio_notify_config(vdev);
609 }
610 
611 static void virtio_balloon_free_page_stop(VirtIOBalloon *s)
612 {
613     VirtIODevice *vdev = VIRTIO_DEVICE(s);
614 
615     if (s->free_page_hint_status != FREE_PAGE_HINT_S_STOP) {
616         /*
617          * The lock also guarantees us that the
618          * virtio_ballloon_get_free_page_hints exits after the
619          * free_page_hint_status is set to S_STOP.
620          */
621         qemu_mutex_lock(&s->free_page_lock);
622         /*
623          * The guest isn't done hinting, so send a notification
624          * to the guest to actively stop the hinting.
625          */
626         s->free_page_hint_status = FREE_PAGE_HINT_S_STOP;
627         qemu_mutex_unlock(&s->free_page_lock);
628         virtio_notify_config(vdev);
629     }
630 }
631 
632 static void virtio_balloon_free_page_done(VirtIOBalloon *s)
633 {
634     VirtIODevice *vdev = VIRTIO_DEVICE(s);
635 
636     if (s->free_page_hint_status != FREE_PAGE_HINT_S_DONE) {
637         /* See virtio_balloon_free_page_stop() */
638         qemu_mutex_lock(&s->free_page_lock);
639         s->free_page_hint_status = FREE_PAGE_HINT_S_DONE;
640         qemu_mutex_unlock(&s->free_page_lock);
641         virtio_notify_config(vdev);
642     }
643 }
644 
645 static int
646 virtio_balloon_free_page_hint_notify(NotifierWithReturn *n, void *data)
647 {
648     VirtIOBalloon *dev = container_of(n, VirtIOBalloon,
649                                       free_page_hint_notify);
650     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
651     PrecopyNotifyData *pnd = data;
652 
653     if (!virtio_balloon_free_page_support(dev)) {
654         /*
655          * This is an optimization provided to migration, so just return 0 to
656          * have the normal migration process not affected when this feature is
657          * not supported.
658          */
659         return 0;
660     }
661 
662     switch (pnd->reason) {
663     case PRECOPY_NOTIFY_SETUP:
664         precopy_enable_free_page_optimization();
665         break;
666     case PRECOPY_NOTIFY_BEFORE_BITMAP_SYNC:
667         virtio_balloon_free_page_stop(dev);
668         break;
669     case PRECOPY_NOTIFY_AFTER_BITMAP_SYNC:
670         if (vdev->vm_running) {
671             virtio_balloon_free_page_start(dev);
672             break;
673         }
674         /*
675          * Set S_DONE before migrating the vmstate, so the guest will reuse
676          * all hinted pages once running on the destination. Fall through.
677          */
678     case PRECOPY_NOTIFY_CLEANUP:
679         /*
680          * Especially, if something goes wrong during precopy or if migration
681          * is canceled, we have to properly communicate S_DONE to the VM.
682          */
683         virtio_balloon_free_page_done(dev);
684         break;
685     case PRECOPY_NOTIFY_COMPLETE:
686         break;
687     default:
688         virtio_error(vdev, "%s: %d reason unknown", __func__, pnd->reason);
689     }
690 
691     return 0;
692 }
693 
694 static size_t virtio_balloon_config_size(VirtIOBalloon *s)
695 {
696     uint64_t features = s->host_features;
697 
698     if (s->qemu_4_0_config_size) {
699         return sizeof(struct virtio_balloon_config);
700     }
701     if (virtio_has_feature(features, VIRTIO_BALLOON_F_PAGE_POISON)) {
702         return sizeof(struct virtio_balloon_config);
703     }
704     if (virtio_has_feature(features, VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
705         return offsetof(struct virtio_balloon_config, poison_val);
706     }
707     return offsetof(struct virtio_balloon_config, free_page_hint_cmd_id);
708 }
709 
710 static void virtio_balloon_get_config(VirtIODevice *vdev, uint8_t *config_data)
711 {
712     VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
713     struct virtio_balloon_config config = {};
714 
715     config.num_pages = cpu_to_le32(dev->num_pages);
716     config.actual = cpu_to_le32(dev->actual);
717     config.poison_val = cpu_to_le32(dev->poison_val);
718 
719     if (dev->free_page_hint_status == FREE_PAGE_HINT_S_REQUESTED) {
720         config.free_page_hint_cmd_id =
721                        cpu_to_le32(dev->free_page_hint_cmd_id);
722     } else if (dev->free_page_hint_status == FREE_PAGE_HINT_S_STOP) {
723         config.free_page_hint_cmd_id =
724                        cpu_to_le32(VIRTIO_BALLOON_CMD_ID_STOP);
725     } else if (dev->free_page_hint_status == FREE_PAGE_HINT_S_DONE) {
726         config.free_page_hint_cmd_id =
727                        cpu_to_le32(VIRTIO_BALLOON_CMD_ID_DONE);
728     }
729 
730     trace_virtio_balloon_get_config(config.num_pages, config.actual);
731     memcpy(config_data, &config, virtio_balloon_config_size(dev));
732 }
733 
734 static int build_dimm_list(Object *obj, void *opaque)
735 {
736     GSList **list = opaque;
737 
738     if (object_dynamic_cast(obj, TYPE_PC_DIMM)) {
739         DeviceState *dev = DEVICE(obj);
740         if (dev->realized) { /* only realized DIMMs matter */
741             *list = g_slist_prepend(*list, dev);
742         }
743     }
744 
745     object_child_foreach(obj, build_dimm_list, opaque);
746     return 0;
747 }
748 
749 static ram_addr_t get_current_ram_size(void)
750 {
751     GSList *list = NULL, *item;
752     ram_addr_t size = current_machine->ram_size;
753 
754     build_dimm_list(qdev_get_machine(), &list);
755     for (item = list; item; item = g_slist_next(item)) {
756         Object *obj = OBJECT(item->data);
757         if (!strcmp(object_get_typename(obj), TYPE_PC_DIMM)) {
758             size += object_property_get_int(obj, PC_DIMM_SIZE_PROP,
759                                             &error_abort);
760         }
761     }
762     g_slist_free(list);
763 
764     return size;
765 }
766 
767 static bool virtio_balloon_page_poison_support(void *opaque)
768 {
769     VirtIOBalloon *s = opaque;
770     VirtIODevice *vdev = VIRTIO_DEVICE(s);
771 
772     return virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_PAGE_POISON);
773 }
774 
775 static void virtio_balloon_set_config(VirtIODevice *vdev,
776                                       const uint8_t *config_data)
777 {
778     VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
779     struct virtio_balloon_config config;
780     uint32_t oldactual = dev->actual;
781     ram_addr_t vm_ram_size = get_current_ram_size();
782 
783     memcpy(&config, config_data, virtio_balloon_config_size(dev));
784     dev->actual = le32_to_cpu(config.actual);
785     if (dev->actual != oldactual) {
786         qapi_event_send_balloon_change(vm_ram_size -
787                         ((ram_addr_t) dev->actual << VIRTIO_BALLOON_PFN_SHIFT));
788     }
789     dev->poison_val = 0;
790     if (virtio_balloon_page_poison_support(dev)) {
791         dev->poison_val = le32_to_cpu(config.poison_val);
792     }
793     trace_virtio_balloon_set_config(dev->actual, oldactual);
794 }
795 
796 static uint64_t virtio_balloon_get_features(VirtIODevice *vdev, uint64_t f,
797                                             Error **errp)
798 {
799     VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
800     f |= dev->host_features;
801     virtio_add_feature(&f, VIRTIO_BALLOON_F_STATS_VQ);
802 
803     return f;
804 }
805 
806 static void virtio_balloon_stat(void *opaque, BalloonInfo *info)
807 {
808     VirtIOBalloon *dev = opaque;
809     info->actual = get_current_ram_size() - ((uint64_t) dev->actual <<
810                                              VIRTIO_BALLOON_PFN_SHIFT);
811 }
812 
813 static void virtio_balloon_to_target(void *opaque, ram_addr_t target)
814 {
815     VirtIOBalloon *dev = VIRTIO_BALLOON(opaque);
816     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
817     ram_addr_t vm_ram_size = get_current_ram_size();
818 
819     if (target > vm_ram_size) {
820         target = vm_ram_size;
821     }
822     if (target) {
823         dev->num_pages = (vm_ram_size - target) >> VIRTIO_BALLOON_PFN_SHIFT;
824         virtio_notify_config(vdev);
825     }
826     trace_virtio_balloon_to_target(target, dev->num_pages);
827 }
828 
829 static int virtio_balloon_post_load_device(void *opaque, int version_id)
830 {
831     VirtIOBalloon *s = VIRTIO_BALLOON(opaque);
832 
833     if (balloon_stats_enabled(s)) {
834         balloon_stats_change_timer(s, s->stats_poll_interval);
835     }
836     return 0;
837 }
838 
839 static const VMStateDescription vmstate_virtio_balloon_free_page_hint = {
840     .name = "virtio-balloon-device/free-page-report",
841     .version_id = 1,
842     .minimum_version_id = 1,
843     .needed = virtio_balloon_free_page_support,
844     .fields = (VMStateField[]) {
845         VMSTATE_UINT32(free_page_hint_cmd_id, VirtIOBalloon),
846         VMSTATE_UINT32(free_page_hint_status, VirtIOBalloon),
847         VMSTATE_END_OF_LIST()
848     }
849 };
850 
851 static const VMStateDescription vmstate_virtio_balloon_page_poison = {
852     .name = "vitio-balloon-device/page-poison",
853     .version_id = 1,
854     .minimum_version_id = 1,
855     .needed = virtio_balloon_page_poison_support,
856     .fields = (VMStateField[]) {
857         VMSTATE_UINT32(poison_val, VirtIOBalloon),
858         VMSTATE_END_OF_LIST()
859     }
860 };
861 
862 static const VMStateDescription vmstate_virtio_balloon_device = {
863     .name = "virtio-balloon-device",
864     .version_id = 1,
865     .minimum_version_id = 1,
866     .post_load = virtio_balloon_post_load_device,
867     .fields = (VMStateField[]) {
868         VMSTATE_UINT32(num_pages, VirtIOBalloon),
869         VMSTATE_UINT32(actual, VirtIOBalloon),
870         VMSTATE_END_OF_LIST()
871     },
872     .subsections = (const VMStateDescription * []) {
873         &vmstate_virtio_balloon_free_page_hint,
874         &vmstate_virtio_balloon_page_poison,
875         NULL
876     }
877 };
878 
879 static void virtio_balloon_device_realize(DeviceState *dev, Error **errp)
880 {
881     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
882     VirtIOBalloon *s = VIRTIO_BALLOON(dev);
883     int ret;
884 
885     virtio_init(vdev, "virtio-balloon", VIRTIO_ID_BALLOON,
886                 virtio_balloon_config_size(s));
887 
888     ret = qemu_add_balloon_handler(virtio_balloon_to_target,
889                                    virtio_balloon_stat, s);
890 
891     if (ret < 0) {
892         error_setg(errp, "Only one balloon device is supported");
893         virtio_cleanup(vdev);
894         return;
895     }
896 
897     if (virtio_has_feature(s->host_features, VIRTIO_BALLOON_F_FREE_PAGE_HINT) &&
898         !s->iothread) {
899         error_setg(errp, "'free-page-hint' requires 'iothread' to be set");
900         virtio_cleanup(vdev);
901         return;
902     }
903 
904     s->ivq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
905     s->dvq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
906     s->svq = virtio_add_queue(vdev, 128, virtio_balloon_receive_stats);
907 
908     if (virtio_has_feature(s->host_features,
909                            VIRTIO_BALLOON_F_FREE_PAGE_HINT)) {
910         s->free_page_vq = virtio_add_queue(vdev, VIRTQUEUE_MAX_SIZE,
911                                            virtio_balloon_handle_free_page_vq);
912         precopy_add_notifier(&s->free_page_hint_notify);
913 
914         object_ref(OBJECT(s->iothread));
915         s->free_page_bh = aio_bh_new(iothread_get_aio_context(s->iothread),
916                                      virtio_ballloon_get_free_page_hints, s);
917     }
918 
919     if (virtio_has_feature(s->host_features, VIRTIO_BALLOON_F_REPORTING)) {
920         s->reporting_vq = virtio_add_queue(vdev, 32,
921                                            virtio_balloon_handle_report);
922     }
923 
924     reset_stats(s);
925 }
926 
927 static void virtio_balloon_device_unrealize(DeviceState *dev)
928 {
929     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
930     VirtIOBalloon *s = VIRTIO_BALLOON(dev);
931 
932     if (s->free_page_bh) {
933         qemu_bh_delete(s->free_page_bh);
934         object_unref(OBJECT(s->iothread));
935         virtio_balloon_free_page_stop(s);
936         precopy_remove_notifier(&s->free_page_hint_notify);
937     }
938     balloon_stats_destroy_timer(s);
939     qemu_remove_balloon_handler(s);
940 
941     virtio_delete_queue(s->ivq);
942     virtio_delete_queue(s->dvq);
943     virtio_delete_queue(s->svq);
944     if (s->free_page_vq) {
945         virtio_delete_queue(s->free_page_vq);
946     }
947     if (s->reporting_vq) {
948         virtio_delete_queue(s->reporting_vq);
949     }
950     virtio_cleanup(vdev);
951 }
952 
953 static void virtio_balloon_device_reset(VirtIODevice *vdev)
954 {
955     VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
956 
957     if (virtio_balloon_free_page_support(s)) {
958         virtio_balloon_free_page_stop(s);
959     }
960 
961     if (s->stats_vq_elem != NULL) {
962         virtqueue_unpop(s->svq, s->stats_vq_elem, 0);
963         g_free(s->stats_vq_elem);
964         s->stats_vq_elem = NULL;
965     }
966 
967     s->poison_val = 0;
968 }
969 
970 static void virtio_balloon_set_status(VirtIODevice *vdev, uint8_t status)
971 {
972     VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
973 
974     if (!s->stats_vq_elem && vdev->vm_running &&
975         (status & VIRTIO_CONFIG_S_DRIVER_OK) && virtqueue_rewind(s->svq, 1)) {
976         /* poll stats queue for the element we have discarded when the VM
977          * was stopped */
978         virtio_balloon_receive_stats(vdev, s->svq);
979     }
980 
981     if (virtio_balloon_free_page_support(s)) {
982         /*
983          * The VM is woken up and the iothread was blocked, so signal it to
984          * continue.
985          */
986         if (vdev->vm_running && s->block_iothread) {
987             qemu_mutex_lock(&s->free_page_lock);
988             s->block_iothread = false;
989             qemu_cond_signal(&s->free_page_cond);
990             qemu_mutex_unlock(&s->free_page_lock);
991         }
992 
993         /* The VM is stopped, block the iothread. */
994         if (!vdev->vm_running) {
995             qemu_mutex_lock(&s->free_page_lock);
996             s->block_iothread = true;
997             qemu_mutex_unlock(&s->free_page_lock);
998         }
999     }
1000 }
1001 
1002 static void virtio_balloon_instance_init(Object *obj)
1003 {
1004     VirtIOBalloon *s = VIRTIO_BALLOON(obj);
1005 
1006     qemu_mutex_init(&s->free_page_lock);
1007     qemu_cond_init(&s->free_page_cond);
1008     s->free_page_hint_cmd_id = VIRTIO_BALLOON_FREE_PAGE_HINT_CMD_ID_MIN;
1009     s->free_page_hint_notify.notify = virtio_balloon_free_page_hint_notify;
1010 
1011     object_property_add(obj, "guest-stats", "guest statistics",
1012                         balloon_stats_get_all, NULL, NULL, s);
1013 
1014     object_property_add(obj, "guest-stats-polling-interval", "int",
1015                         balloon_stats_get_poll_interval,
1016                         balloon_stats_set_poll_interval,
1017                         NULL, s);
1018 }
1019 
1020 static const VMStateDescription vmstate_virtio_balloon = {
1021     .name = "virtio-balloon",
1022     .minimum_version_id = 1,
1023     .version_id = 1,
1024     .fields = (VMStateField[]) {
1025         VMSTATE_VIRTIO_DEVICE,
1026         VMSTATE_END_OF_LIST()
1027     },
1028 };
1029 
1030 static Property virtio_balloon_properties[] = {
1031     DEFINE_PROP_BIT("deflate-on-oom", VirtIOBalloon, host_features,
1032                     VIRTIO_BALLOON_F_DEFLATE_ON_OOM, false),
1033     DEFINE_PROP_BIT("free-page-hint", VirtIOBalloon, host_features,
1034                     VIRTIO_BALLOON_F_FREE_PAGE_HINT, false),
1035     DEFINE_PROP_BIT("page-poison", VirtIOBalloon, host_features,
1036                     VIRTIO_BALLOON_F_PAGE_POISON, true),
1037     DEFINE_PROP_BIT("free-page-reporting", VirtIOBalloon, host_features,
1038                     VIRTIO_BALLOON_F_REPORTING, false),
1039     /* QEMU 4.0 accidentally changed the config size even when free-page-hint
1040      * is disabled, resulting in QEMU 3.1 migration incompatibility.  This
1041      * property retains this quirk for QEMU 4.1 machine types.
1042      */
1043     DEFINE_PROP_BOOL("qemu-4-0-config-size", VirtIOBalloon,
1044                      qemu_4_0_config_size, false),
1045     DEFINE_PROP_LINK("iothread", VirtIOBalloon, iothread, TYPE_IOTHREAD,
1046                      IOThread *),
1047     DEFINE_PROP_END_OF_LIST(),
1048 };
1049 
1050 static void virtio_balloon_class_init(ObjectClass *klass, void *data)
1051 {
1052     DeviceClass *dc = DEVICE_CLASS(klass);
1053     VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
1054 
1055     device_class_set_props(dc, virtio_balloon_properties);
1056     dc->vmsd = &vmstate_virtio_balloon;
1057     set_bit(DEVICE_CATEGORY_MISC, dc->categories);
1058     vdc->realize = virtio_balloon_device_realize;
1059     vdc->unrealize = virtio_balloon_device_unrealize;
1060     vdc->reset = virtio_balloon_device_reset;
1061     vdc->get_config = virtio_balloon_get_config;
1062     vdc->set_config = virtio_balloon_set_config;
1063     vdc->get_features = virtio_balloon_get_features;
1064     vdc->set_status = virtio_balloon_set_status;
1065     vdc->vmsd = &vmstate_virtio_balloon_device;
1066 }
1067 
1068 static const TypeInfo virtio_balloon_info = {
1069     .name = TYPE_VIRTIO_BALLOON,
1070     .parent = TYPE_VIRTIO_DEVICE,
1071     .instance_size = sizeof(VirtIOBalloon),
1072     .instance_init = virtio_balloon_instance_init,
1073     .class_init = virtio_balloon_class_init,
1074 };
1075 
1076 static void virtio_register_types(void)
1077 {
1078     type_register_static(&virtio_balloon_info);
1079 }
1080 
1081 type_init(virtio_register_types)
1082