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