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