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