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