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