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