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