xref: /qemu/hw/virtio/virtio-balloon.c (revision b218a70e6ae882f52cc339ae965f515a36a9139f)
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/timer.h"
19 #include "qemu-common.h"
20 #include "hw/virtio/virtio.h"
21 #include "hw/mem/pc-dimm.h"
22 #include "sysemu/balloon.h"
23 #include "hw/virtio/virtio-balloon.h"
24 #include "exec/address-spaces.h"
25 #include "qapi/error.h"
26 #include "qapi/qapi-events-misc.h"
27 #include "qapi/visitor.h"
28 #include "trace.h"
29 #include "qemu/error-report.h"
30 
31 #include "hw/virtio/virtio-bus.h"
32 #include "hw/virtio/virtio-access.h"
33 
34 #define BALLOON_PAGE_SIZE  (1 << VIRTIO_BALLOON_PFN_SHIFT)
35 
36 static void balloon_page(void *addr, int deflate)
37 {
38     if (!qemu_balloon_is_inhibited() && !deflate) {
39         qemu_madvise(addr, BALLOON_PAGE_SIZE, QEMU_MADV_DONTNEED);
40     }
41 }
42 
43 static const char *balloon_stat_names[] = {
44    [VIRTIO_BALLOON_S_SWAP_IN] = "stat-swap-in",
45    [VIRTIO_BALLOON_S_SWAP_OUT] = "stat-swap-out",
46    [VIRTIO_BALLOON_S_MAJFLT] = "stat-major-faults",
47    [VIRTIO_BALLOON_S_MINFLT] = "stat-minor-faults",
48    [VIRTIO_BALLOON_S_MEMFREE] = "stat-free-memory",
49    [VIRTIO_BALLOON_S_MEMTOT] = "stat-total-memory",
50    [VIRTIO_BALLOON_S_AVAIL] = "stat-available-memory",
51    [VIRTIO_BALLOON_S_CACHES] = "stat-disk-caches",
52    [VIRTIO_BALLOON_S_HTLB_PGALLOC] = "stat-htlb-pgalloc",
53    [VIRTIO_BALLOON_S_HTLB_PGFAIL] = "stat-htlb-pgfail",
54    [VIRTIO_BALLOON_S_NR] = NULL
55 };
56 
57 /*
58  * reset_stats - Mark all items in the stats array as unset
59  *
60  * This function needs to be called at device initialization and before
61  * updating to a set of newly-generated stats.  This will ensure that no
62  * stale values stick around in case the guest reports a subset of the supported
63  * statistics.
64  */
65 static inline void reset_stats(VirtIOBalloon *dev)
66 {
67     int i;
68     for (i = 0; i < VIRTIO_BALLOON_S_NR; dev->stats[i++] = -1);
69 }
70 
71 static bool balloon_stats_supported(const VirtIOBalloon *s)
72 {
73     VirtIODevice *vdev = VIRTIO_DEVICE(s);
74     return virtio_vdev_has_feature(vdev, VIRTIO_BALLOON_F_STATS_VQ);
75 }
76 
77 static bool balloon_stats_enabled(const VirtIOBalloon *s)
78 {
79     return s->stats_poll_interval > 0;
80 }
81 
82 static void balloon_stats_destroy_timer(VirtIOBalloon *s)
83 {
84     if (balloon_stats_enabled(s)) {
85         timer_del(s->stats_timer);
86         timer_free(s->stats_timer);
87         s->stats_timer = NULL;
88         s->stats_poll_interval = 0;
89     }
90 }
91 
92 static void balloon_stats_change_timer(VirtIOBalloon *s, int64_t secs)
93 {
94     timer_mod(s->stats_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + secs * 1000);
95 }
96 
97 static void balloon_stats_poll_cb(void *opaque)
98 {
99     VirtIOBalloon *s = opaque;
100     VirtIODevice *vdev = VIRTIO_DEVICE(s);
101 
102     if (s->stats_vq_elem == NULL || !balloon_stats_supported(s)) {
103         /* re-schedule */
104         balloon_stats_change_timer(s, s->stats_poll_interval);
105         return;
106     }
107 
108     virtqueue_push(s->svq, s->stats_vq_elem, s->stats_vq_offset);
109     virtio_notify(vdev, s->svq);
110     g_free(s->stats_vq_elem);
111     s->stats_vq_elem = NULL;
112 }
113 
114 static void balloon_stats_get_all(Object *obj, Visitor *v, const char *name,
115                                   void *opaque, Error **errp)
116 {
117     Error *err = NULL;
118     VirtIOBalloon *s = opaque;
119     int i;
120 
121     visit_start_struct(v, name, NULL, 0, &err);
122     if (err) {
123         goto out;
124     }
125     visit_type_int(v, "last-update", &s->stats_last_update, &err);
126     if (err) {
127         goto out_end;
128     }
129 
130     visit_start_struct(v, "stats", NULL, 0, &err);
131     if (err) {
132         goto out_end;
133     }
134     for (i = 0; i < VIRTIO_BALLOON_S_NR; i++) {
135         visit_type_uint64(v, balloon_stat_names[i], &s->stats[i], &err);
136         if (err) {
137             goto out_nested;
138         }
139     }
140     visit_check_struct(v, &err);
141 out_nested:
142     visit_end_struct(v, NULL);
143 
144     if (!err) {
145         visit_check_struct(v, &err);
146     }
147 out_end:
148     visit_end_struct(v, NULL);
149 out:
150     error_propagate(errp, err);
151 }
152 
153 static void balloon_stats_get_poll_interval(Object *obj, Visitor *v,
154                                             const char *name, void *opaque,
155                                             Error **errp)
156 {
157     VirtIOBalloon *s = opaque;
158     visit_type_int(v, name, &s->stats_poll_interval, errp);
159 }
160 
161 static void balloon_stats_set_poll_interval(Object *obj, Visitor *v,
162                                             const char *name, void *opaque,
163                                             Error **errp)
164 {
165     VirtIOBalloon *s = opaque;
166     Error *local_err = NULL;
167     int64_t value;
168 
169     visit_type_int(v, name, &value, &local_err);
170     if (local_err) {
171         error_propagate(errp, local_err);
172         return;
173     }
174 
175     if (value < 0) {
176         error_setg(errp, "timer value must be greater than zero");
177         return;
178     }
179 
180     if (value > UINT32_MAX) {
181         error_setg(errp, "timer value is too big");
182         return;
183     }
184 
185     if (value == s->stats_poll_interval) {
186         return;
187     }
188 
189     if (value == 0) {
190         /* timer=0 disables the timer */
191         balloon_stats_destroy_timer(s);
192         return;
193     }
194 
195     if (balloon_stats_enabled(s)) {
196         /* timer interval change */
197         s->stats_poll_interval = value;
198         balloon_stats_change_timer(s, value);
199         return;
200     }
201 
202     /* create a new timer */
203     g_assert(s->stats_timer == NULL);
204     s->stats_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, balloon_stats_poll_cb, s);
205     s->stats_poll_interval = value;
206     balloon_stats_change_timer(s, 0);
207 }
208 
209 static void virtio_balloon_handle_output(VirtIODevice *vdev, VirtQueue *vq)
210 {
211     VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
212     VirtQueueElement *elem;
213     MemoryRegionSection section;
214 
215     for (;;) {
216         size_t offset = 0;
217         uint32_t pfn;
218         elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
219         if (!elem) {
220             return;
221         }
222 
223         while (iov_to_buf(elem->out_sg, elem->out_num, offset, &pfn, 4) == 4) {
224             hwaddr pa;
225             hwaddr addr;
226             int p = virtio_ldl_p(vdev, &pfn);
227 
228             pa = (hwaddr) p << VIRTIO_BALLOON_PFN_SHIFT;
229             offset += 4;
230 
231             section = memory_region_find(get_system_memory(), pa,
232                                          BALLOON_PAGE_SIZE);
233             if (!section.mr) {
234                 trace_virtio_balloon_bad_addr(pa);
235                 continue;
236             }
237             if (!memory_region_is_ram(section.mr) ||
238                 memory_region_is_rom(section.mr) ||
239                 memory_region_is_romd(section.mr)) {
240                 trace_virtio_balloon_bad_addr(pa);
241                 memory_region_unref(section.mr);
242                 continue;
243             }
244 
245             trace_virtio_balloon_handle_output(memory_region_name(section.mr),
246                                                pa);
247             /* Using memory_region_get_ram_ptr is bending the rules a bit, but
248                should be OK because we only want a single page.  */
249             addr = section.offset_within_region;
250             balloon_page(memory_region_get_ram_ptr(section.mr) + addr,
251                          !!(vq == s->dvq));
252             memory_region_unref(section.mr);
253         }
254 
255         virtqueue_push(vq, elem, offset);
256         virtio_notify(vdev, vq);
257         g_free(elem);
258     }
259 }
260 
261 static void virtio_balloon_receive_stats(VirtIODevice *vdev, VirtQueue *vq)
262 {
263     VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
264     VirtQueueElement *elem;
265     VirtIOBalloonStat stat;
266     size_t offset = 0;
267     qemu_timeval tv;
268 
269     elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
270     if (!elem) {
271         goto out;
272     }
273 
274     if (s->stats_vq_elem != NULL) {
275         /* This should never happen if the driver follows the spec. */
276         virtqueue_push(vq, s->stats_vq_elem, 0);
277         virtio_notify(vdev, vq);
278         g_free(s->stats_vq_elem);
279     }
280 
281     s->stats_vq_elem = elem;
282 
283     /* Initialize the stats to get rid of any stale values.  This is only
284      * needed to handle the case where a guest supports fewer stats than it
285      * used to (ie. it has booted into an old kernel).
286      */
287     reset_stats(s);
288 
289     while (iov_to_buf(elem->out_sg, elem->out_num, offset, &stat, sizeof(stat))
290            == sizeof(stat)) {
291         uint16_t tag = virtio_tswap16(vdev, stat.tag);
292         uint64_t val = virtio_tswap64(vdev, stat.val);
293 
294         offset += sizeof(stat);
295         if (tag < VIRTIO_BALLOON_S_NR)
296             s->stats[tag] = val;
297     }
298     s->stats_vq_offset = offset;
299 
300     if (qemu_gettimeofday(&tv) < 0) {
301         warn_report("%s: failed to get time of day", __func__);
302         goto out;
303     }
304 
305     s->stats_last_update = tv.tv_sec;
306 
307 out:
308     if (balloon_stats_enabled(s)) {
309         balloon_stats_change_timer(s, s->stats_poll_interval);
310     }
311 }
312 
313 static void virtio_balloon_get_config(VirtIODevice *vdev, uint8_t *config_data)
314 {
315     VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
316     struct virtio_balloon_config config = {};
317 
318     config.num_pages = cpu_to_le32(dev->num_pages);
319     config.actual = cpu_to_le32(dev->actual);
320 
321     trace_virtio_balloon_get_config(config.num_pages, config.actual);
322     memcpy(config_data, &config, sizeof(struct virtio_balloon_config));
323 }
324 
325 static int build_dimm_list(Object *obj, void *opaque)
326 {
327     GSList **list = opaque;
328 
329     if (object_dynamic_cast(obj, TYPE_PC_DIMM)) {
330         DeviceState *dev = DEVICE(obj);
331         if (dev->realized) { /* only realized DIMMs matter */
332             *list = g_slist_prepend(*list, dev);
333         }
334     }
335 
336     object_child_foreach(obj, build_dimm_list, opaque);
337     return 0;
338 }
339 
340 static ram_addr_t get_current_ram_size(void)
341 {
342     GSList *list = NULL, *item;
343     ram_addr_t size = ram_size;
344 
345     build_dimm_list(qdev_get_machine(), &list);
346     for (item = list; item; item = g_slist_next(item)) {
347         Object *obj = OBJECT(item->data);
348         if (!strcmp(object_get_typename(obj), TYPE_PC_DIMM)) {
349             size += object_property_get_int(obj, PC_DIMM_SIZE_PROP,
350                                             &error_abort);
351         }
352     }
353     g_slist_free(list);
354 
355     return size;
356 }
357 
358 static void virtio_balloon_set_config(VirtIODevice *vdev,
359                                       const uint8_t *config_data)
360 {
361     VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
362     struct virtio_balloon_config config;
363     uint32_t oldactual = dev->actual;
364     ram_addr_t vm_ram_size = get_current_ram_size();
365 
366     memcpy(&config, config_data, sizeof(struct virtio_balloon_config));
367     dev->actual = le32_to_cpu(config.actual);
368     if (dev->actual != oldactual) {
369         qapi_event_send_balloon_change(vm_ram_size -
370                         ((ram_addr_t) dev->actual << VIRTIO_BALLOON_PFN_SHIFT));
371     }
372     trace_virtio_balloon_set_config(dev->actual, oldactual);
373 }
374 
375 static uint64_t virtio_balloon_get_features(VirtIODevice *vdev, uint64_t f,
376                                             Error **errp)
377 {
378     VirtIOBalloon *dev = VIRTIO_BALLOON(vdev);
379     f |= dev->host_features;
380     virtio_add_feature(&f, VIRTIO_BALLOON_F_STATS_VQ);
381     return f;
382 }
383 
384 static void virtio_balloon_stat(void *opaque, BalloonInfo *info)
385 {
386     VirtIOBalloon *dev = opaque;
387     info->actual = get_current_ram_size() - ((uint64_t) dev->actual <<
388                                              VIRTIO_BALLOON_PFN_SHIFT);
389 }
390 
391 static void virtio_balloon_to_target(void *opaque, ram_addr_t target)
392 {
393     VirtIOBalloon *dev = VIRTIO_BALLOON(opaque);
394     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
395     ram_addr_t vm_ram_size = get_current_ram_size();
396 
397     if (target > vm_ram_size) {
398         target = vm_ram_size;
399     }
400     if (target) {
401         dev->num_pages = (vm_ram_size - target) >> VIRTIO_BALLOON_PFN_SHIFT;
402         virtio_notify_config(vdev);
403     }
404     trace_virtio_balloon_to_target(target, dev->num_pages);
405 }
406 
407 static int virtio_balloon_post_load_device(void *opaque, int version_id)
408 {
409     VirtIOBalloon *s = VIRTIO_BALLOON(opaque);
410 
411     if (balloon_stats_enabled(s)) {
412         balloon_stats_change_timer(s, s->stats_poll_interval);
413     }
414     return 0;
415 }
416 
417 static const VMStateDescription vmstate_virtio_balloon_device = {
418     .name = "virtio-balloon-device",
419     .version_id = 1,
420     .minimum_version_id = 1,
421     .post_load = virtio_balloon_post_load_device,
422     .fields = (VMStateField[]) {
423         VMSTATE_UINT32(num_pages, VirtIOBalloon),
424         VMSTATE_UINT32(actual, VirtIOBalloon),
425         VMSTATE_END_OF_LIST()
426     },
427 };
428 
429 static void virtio_balloon_device_realize(DeviceState *dev, Error **errp)
430 {
431     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
432     VirtIOBalloon *s = VIRTIO_BALLOON(dev);
433     int ret;
434 
435     virtio_init(vdev, "virtio-balloon", VIRTIO_ID_BALLOON,
436                 sizeof(struct virtio_balloon_config));
437 
438     ret = qemu_add_balloon_handler(virtio_balloon_to_target,
439                                    virtio_balloon_stat, s);
440 
441     if (ret < 0) {
442         error_setg(errp, "Only one balloon device is supported");
443         virtio_cleanup(vdev);
444         return;
445     }
446 
447     s->ivq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
448     s->dvq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);
449     s->svq = virtio_add_queue(vdev, 128, virtio_balloon_receive_stats);
450 
451     reset_stats(s);
452 }
453 
454 static void virtio_balloon_device_unrealize(DeviceState *dev, Error **errp)
455 {
456     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
457     VirtIOBalloon *s = VIRTIO_BALLOON(dev);
458 
459     balloon_stats_destroy_timer(s);
460     qemu_remove_balloon_handler(s);
461     virtio_cleanup(vdev);
462 }
463 
464 static void virtio_balloon_device_reset(VirtIODevice *vdev)
465 {
466     VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
467 
468     if (s->stats_vq_elem != NULL) {
469         virtqueue_unpop(s->svq, s->stats_vq_elem, 0);
470         g_free(s->stats_vq_elem);
471         s->stats_vq_elem = NULL;
472     }
473 }
474 
475 static void virtio_balloon_set_status(VirtIODevice *vdev, uint8_t status)
476 {
477     VirtIOBalloon *s = VIRTIO_BALLOON(vdev);
478 
479     if (!s->stats_vq_elem && vdev->vm_running &&
480         (status & VIRTIO_CONFIG_S_DRIVER_OK) && virtqueue_rewind(s->svq, 1)) {
481         /* poll stats queue for the element we have discarded when the VM
482          * was stopped */
483         virtio_balloon_receive_stats(vdev, s->svq);
484     }
485 }
486 
487 static void virtio_balloon_instance_init(Object *obj)
488 {
489     VirtIOBalloon *s = VIRTIO_BALLOON(obj);
490 
491     object_property_add(obj, "guest-stats", "guest statistics",
492                         balloon_stats_get_all, NULL, NULL, s, NULL);
493 
494     object_property_add(obj, "guest-stats-polling-interval", "int",
495                         balloon_stats_get_poll_interval,
496                         balloon_stats_set_poll_interval,
497                         NULL, s, NULL);
498 }
499 
500 static const VMStateDescription vmstate_virtio_balloon = {
501     .name = "virtio-balloon",
502     .minimum_version_id = 1,
503     .version_id = 1,
504     .fields = (VMStateField[]) {
505         VMSTATE_VIRTIO_DEVICE,
506         VMSTATE_END_OF_LIST()
507     },
508 };
509 
510 static Property virtio_balloon_properties[] = {
511     DEFINE_PROP_BIT("deflate-on-oom", VirtIOBalloon, host_features,
512                     VIRTIO_BALLOON_F_DEFLATE_ON_OOM, false),
513     DEFINE_PROP_END_OF_LIST(),
514 };
515 
516 static void virtio_balloon_class_init(ObjectClass *klass, void *data)
517 {
518     DeviceClass *dc = DEVICE_CLASS(klass);
519     VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
520 
521     dc->props = virtio_balloon_properties;
522     dc->vmsd = &vmstate_virtio_balloon;
523     set_bit(DEVICE_CATEGORY_MISC, dc->categories);
524     vdc->realize = virtio_balloon_device_realize;
525     vdc->unrealize = virtio_balloon_device_unrealize;
526     vdc->reset = virtio_balloon_device_reset;
527     vdc->get_config = virtio_balloon_get_config;
528     vdc->set_config = virtio_balloon_set_config;
529     vdc->get_features = virtio_balloon_get_features;
530     vdc->set_status = virtio_balloon_set_status;
531     vdc->vmsd = &vmstate_virtio_balloon_device;
532 }
533 
534 static const TypeInfo virtio_balloon_info = {
535     .name = TYPE_VIRTIO_BALLOON,
536     .parent = TYPE_VIRTIO_DEVICE,
537     .instance_size = sizeof(VirtIOBalloon),
538     .instance_init = virtio_balloon_instance_init,
539     .class_init = virtio_balloon_class_init,
540 };
541 
542 static void virtio_register_types(void)
543 {
544     type_register_static(&virtio_balloon_info);
545 }
546 
547 type_init(virtio_register_types)
548