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