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