1 /* SPDX-License-Identifier: GPL-2.0-only */ 2 #ifndef __KVM_HOST_H 3 #define __KVM_HOST_H 4 5 #include <linux/entry-virt.h> 6 #include <linux/types.h> 7 #include <linux/hardirq.h> 8 #include <linux/list.h> 9 #include <linux/mutex.h> 10 #include <linux/spinlock.h> 11 #include <linux/signal.h> 12 #include <linux/sched.h> 13 #include <linux/sched/stat.h> 14 #include <linux/bug.h> 15 #include <linux/minmax.h> 16 #include <linux/mm.h> 17 #include <linux/mmu_notifier.h> 18 #include <linux/preempt.h> 19 #include <linux/msi.h> 20 #include <linux/slab.h> 21 #include <linux/vmalloc.h> 22 #include <linux/rcupdate.h> 23 #include <linux/ratelimit.h> 24 #include <linux/err.h> 25 #include <linux/irqflags.h> 26 #include <linux/context_tracking.h> 27 #include <linux/irqbypass.h> 28 #include <linux/rcuwait.h> 29 #include <linux/refcount.h> 30 #include <linux/nospec.h> 31 #include <linux/notifier.h> 32 #include <linux/ftrace.h> 33 #include <linux/hashtable.h> 34 #include <linux/instrumentation.h> 35 #include <linux/interval_tree.h> 36 #include <linux/rbtree.h> 37 #include <linux/xarray.h> 38 #include <asm/signal.h> 39 40 #include <linux/kvm.h> 41 #include <linux/kvm_para.h> 42 43 #include <linux/kvm_types.h> 44 45 #include <asm/kvm_host.h> 46 #include <linux/kvm_dirty_ring.h> 47 48 #define __KVM_DEV_STRING(name, x) __stringify(name ## _ ## x) 49 #define _KVM_DEV_STRING(name, x) __KVM_DEV_STRING(name, x) 50 #define KVM_DEV_STRING(x) _KVM_DEV_STRING(KVM_DEV_NAME, x) 51 52 #ifndef KVM_MAX_VCPU_IDS 53 #define KVM_MAX_VCPU_IDS KVM_MAX_VCPUS 54 #endif 55 56 /* 57 * The bit 16 ~ bit 31 of kvm_userspace_memory_region::flags are internally 58 * used in kvm, other bits are visible for userspace which are defined in 59 * include/uapi/linux/kvm.h. 60 */ 61 #define KVM_MEMSLOT_INVALID (1UL << 16) 62 #define KVM_MEMSLOT_GMEM_ONLY (1UL << 17) 63 64 /* 65 * Bit 63 of the memslot generation number is an "update in-progress flag", 66 * e.g. is temporarily set for the duration of kvm_swap_active_memslots(). 67 * This flag effectively creates a unique generation number that is used to 68 * mark cached memslot data, e.g. MMIO accesses, as potentially being stale, 69 * i.e. may (or may not) have come from the previous memslots generation. 70 * 71 * This is necessary because the actual memslots update is not atomic with 72 * respect to the generation number update. Updating the generation number 73 * first would allow a vCPU to cache a spte from the old memslots using the 74 * new generation number, and updating the generation number after switching 75 * to the new memslots would allow cache hits using the old generation number 76 * to reference the defunct memslots. 77 * 78 * This mechanism is used to prevent getting hits in KVM's caches while a 79 * memslot update is in-progress, and to prevent cache hits *after* updating 80 * the actual generation number against accesses that were inserted into the 81 * cache *before* the memslots were updated. 82 */ 83 #define KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS BIT_ULL(63) 84 85 /* Two fragments for cross MMIO pages. */ 86 #define KVM_MAX_MMIO_FRAGMENTS 2 87 88 #ifndef KVM_MAX_NR_ADDRESS_SPACES 89 #define KVM_MAX_NR_ADDRESS_SPACES 1 90 #endif 91 92 /* 93 * For the normal pfn, the highest 12 bits should be zero, 94 * so we can mask bit 62 ~ bit 52 to indicate the error pfn, 95 * mask bit 63 to indicate the noslot pfn. 96 */ 97 #define KVM_PFN_ERR_MASK (0x7ffULL << 52) 98 #define KVM_PFN_ERR_NOSLOT_MASK (0xfffULL << 52) 99 #define KVM_PFN_NOSLOT (0x1ULL << 63) 100 101 #define KVM_PFN_ERR_FAULT (KVM_PFN_ERR_MASK) 102 #define KVM_PFN_ERR_HWPOISON (KVM_PFN_ERR_MASK + 1) 103 #define KVM_PFN_ERR_RO_FAULT (KVM_PFN_ERR_MASK + 2) 104 #define KVM_PFN_ERR_SIGPENDING (KVM_PFN_ERR_MASK + 3) 105 #define KVM_PFN_ERR_NEEDS_IO (KVM_PFN_ERR_MASK + 4) 106 107 /* 108 * error pfns indicate that the gfn is in slot but faild to 109 * translate it to pfn on host. 110 */ 111 static inline bool is_error_pfn(kvm_pfn_t pfn) 112 { 113 return !!(pfn & KVM_PFN_ERR_MASK); 114 } 115 116 /* 117 * KVM_PFN_ERR_SIGPENDING indicates that fetching the PFN was interrupted 118 * by a pending signal. Note, the signal may or may not be fatal. 119 */ 120 static inline bool is_sigpending_pfn(kvm_pfn_t pfn) 121 { 122 return pfn == KVM_PFN_ERR_SIGPENDING; 123 } 124 125 /* 126 * error_noslot pfns indicate that the gfn can not be 127 * translated to pfn - it is not in slot or failed to 128 * translate it to pfn. 129 */ 130 static inline bool is_error_noslot_pfn(kvm_pfn_t pfn) 131 { 132 return !!(pfn & KVM_PFN_ERR_NOSLOT_MASK); 133 } 134 135 /* noslot pfn indicates that the gfn is not in slot. */ 136 static inline bool is_noslot_pfn(kvm_pfn_t pfn) 137 { 138 return pfn == KVM_PFN_NOSLOT; 139 } 140 141 /* 142 * architectures with KVM_HVA_ERR_BAD other than PAGE_OFFSET (e.g. s390) 143 * provide own defines and kvm_is_error_hva 144 */ 145 #ifndef KVM_HVA_ERR_BAD 146 147 #define KVM_HVA_ERR_BAD (PAGE_OFFSET) 148 #define KVM_HVA_ERR_RO_BAD (PAGE_OFFSET + PAGE_SIZE) 149 150 static inline bool kvm_is_error_hva(unsigned long addr) 151 { 152 return addr >= PAGE_OFFSET; 153 } 154 155 #endif 156 157 static inline bool kvm_is_error_gpa(gpa_t gpa) 158 { 159 return gpa == INVALID_GPA; 160 } 161 162 #define KVM_REQUEST_MASK GENMASK(7,0) 163 #define KVM_REQUEST_NO_WAKEUP BIT(8) 164 #define KVM_REQUEST_WAIT BIT(9) 165 #define KVM_REQUEST_NO_ACTION BIT(10) 166 /* 167 * Architecture-independent vcpu->requests bit members 168 * Bits 3-7 are reserved for more arch-independent bits. 169 */ 170 #define KVM_REQ_TLB_FLUSH (0 | KVM_REQUEST_WAIT | KVM_REQUEST_NO_WAKEUP) 171 #define KVM_REQ_VM_DEAD (1 | KVM_REQUEST_WAIT | KVM_REQUEST_NO_WAKEUP) 172 #define KVM_REQ_UNBLOCK 2 173 #define KVM_REQ_DIRTY_RING_SOFT_FULL 3 174 #define KVM_REQUEST_ARCH_BASE 8 175 176 /* 177 * KVM_REQ_OUTSIDE_GUEST_MODE exists is purely as way to force the vCPU to 178 * OUTSIDE_GUEST_MODE. KVM_REQ_OUTSIDE_GUEST_MODE differs from a vCPU "kick" 179 * in that it ensures the vCPU has reached OUTSIDE_GUEST_MODE before continuing 180 * on. A kick only guarantees that the vCPU is on its way out, e.g. a previous 181 * kick may have set vcpu->mode to EXITING_GUEST_MODE, and so there's no 182 * guarantee the vCPU received an IPI and has actually exited guest mode. 183 */ 184 #define KVM_REQ_OUTSIDE_GUEST_MODE (KVM_REQUEST_NO_ACTION | KVM_REQUEST_WAIT | KVM_REQUEST_NO_WAKEUP) 185 186 #define KVM_ARCH_REQ_FLAGS(nr, flags) ({ \ 187 BUILD_BUG_ON((unsigned)(nr) >= (sizeof_field(struct kvm_vcpu, requests) * 8) - KVM_REQUEST_ARCH_BASE); \ 188 (unsigned)(((nr) + KVM_REQUEST_ARCH_BASE) | (flags)); \ 189 }) 190 #define KVM_ARCH_REQ(nr) KVM_ARCH_REQ_FLAGS(nr, 0) 191 192 bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req, 193 unsigned long *vcpu_bitmap); 194 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req); 195 196 #define KVM_USERSPACE_IRQ_SOURCE_ID 0 197 #define KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID 1 198 #define KVM_PIT_IRQ_SOURCE_ID 2 199 200 extern struct mutex kvm_lock; 201 extern struct list_head vm_list; 202 203 struct kvm_io_range { 204 gpa_t addr; 205 int len; 206 struct kvm_io_device *dev; 207 }; 208 209 #define NR_IOBUS_DEVS 1000 210 211 struct kvm_io_bus { 212 int dev_count; 213 int ioeventfd_count; 214 struct rcu_head rcu; 215 struct kvm_io_range range[]; 216 }; 217 218 enum kvm_bus { 219 KVM_MMIO_BUS, 220 KVM_PIO_BUS, 221 KVM_VIRTIO_CCW_NOTIFY_BUS, 222 KVM_FAST_MMIO_BUS, 223 KVM_IOCSR_BUS, 224 KVM_NR_BUSES 225 }; 226 227 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr, 228 int len, const void *val); 229 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, 230 gpa_t addr, int len, const void *val, long cookie); 231 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr, 232 int len, void *val); 233 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr, 234 int len, struct kvm_io_device *dev); 235 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx, 236 struct kvm_io_device *dev); 237 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx, 238 gpa_t addr); 239 240 #ifdef CONFIG_KVM_ASYNC_PF 241 struct kvm_async_pf { 242 struct work_struct work; 243 struct list_head link; 244 struct list_head queue; 245 struct kvm_vcpu *vcpu; 246 gpa_t cr2_or_gpa; 247 unsigned long addr; 248 struct kvm_arch_async_pf arch; 249 bool wakeup_all; 250 bool notpresent_injected; 251 }; 252 253 void kvm_clear_async_pf_completion_queue(struct kvm_vcpu *vcpu); 254 void kvm_check_async_pf_completion(struct kvm_vcpu *vcpu); 255 bool kvm_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, 256 unsigned long hva, struct kvm_arch_async_pf *arch); 257 int kvm_async_pf_wakeup_all(struct kvm_vcpu *vcpu); 258 #endif 259 260 union kvm_mmu_notifier_arg { 261 unsigned long attributes; 262 }; 263 264 enum kvm_gfn_range_filter { 265 KVM_FILTER_SHARED = BIT(0), 266 KVM_FILTER_PRIVATE = BIT(1), 267 }; 268 269 struct kvm_gfn_range { 270 struct kvm_memory_slot *slot; 271 gfn_t start; 272 gfn_t end; 273 union kvm_mmu_notifier_arg arg; 274 enum kvm_gfn_range_filter attr_filter; 275 bool may_block; 276 bool lockless; 277 }; 278 bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range); 279 bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range); 280 bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range); 281 282 enum { 283 OUTSIDE_GUEST_MODE, 284 IN_GUEST_MODE, 285 EXITING_GUEST_MODE, 286 READING_SHADOW_PAGE_TABLES, 287 }; 288 289 struct kvm_host_map { 290 /* 291 * Only valid if the 'pfn' is managed by the host kernel (i.e. There is 292 * a 'struct page' for it. When using mem= kernel parameter some memory 293 * can be used as guest memory but they are not managed by host 294 * kernel). 295 */ 296 struct page *pinned_page; 297 struct page *page; 298 void *hva; 299 kvm_pfn_t pfn; 300 kvm_pfn_t gfn; 301 bool writable; 302 }; 303 304 /* 305 * Used to check if the mapping is valid or not. Never use 'kvm_host_map' 306 * directly to check for that. 307 */ 308 static inline bool kvm_vcpu_mapped(struct kvm_host_map *map) 309 { 310 return !!map->hva; 311 } 312 313 static inline bool kvm_vcpu_can_poll(ktime_t cur, ktime_t stop) 314 { 315 return single_task_running() && !need_resched() && ktime_before(cur, stop); 316 } 317 318 /* 319 * Sometimes a large or cross-page mmio needs to be broken up into separate 320 * exits for userspace servicing. 321 */ 322 struct kvm_mmio_fragment { 323 gpa_t gpa; 324 void *data; 325 u64 val; 326 unsigned int len; 327 }; 328 329 struct kvm_vcpu { 330 struct kvm *kvm; 331 #ifdef CONFIG_PREEMPT_NOTIFIERS 332 struct preempt_notifier preempt_notifier; 333 #endif 334 int cpu; 335 int vcpu_id; /* id given by userspace at creation */ 336 int vcpu_idx; /* index into kvm->vcpu_array */ 337 int ____srcu_idx; /* Don't use this directly. You've been warned. */ 338 #ifdef CONFIG_PROVE_RCU 339 int srcu_depth; 340 #endif 341 int mode; 342 u64 requests; 343 unsigned long guest_debug; 344 345 struct mutex mutex; 346 struct kvm_run *run; 347 348 #ifndef __KVM_HAVE_ARCH_WQP 349 struct rcuwait wait; 350 #endif 351 struct pid *pid; 352 rwlock_t pid_lock; 353 int sigset_active; 354 sigset_t sigset; 355 unsigned int halt_poll_ns; 356 bool valid_wakeup; 357 358 #ifdef CONFIG_HAS_IOMEM 359 int mmio_needed; 360 int mmio_read_completed; 361 int mmio_is_write; 362 int mmio_cur_fragment; 363 int mmio_nr_fragments; 364 struct kvm_mmio_fragment mmio_fragments[KVM_MAX_MMIO_FRAGMENTS]; 365 #endif 366 367 #ifdef CONFIG_KVM_ASYNC_PF 368 struct { 369 u32 queued; 370 struct list_head queue; 371 struct list_head done; 372 spinlock_t lock; 373 } async_pf; 374 #endif 375 376 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT 377 /* 378 * Cpu relax intercept or pause loop exit optimization 379 * in_spin_loop: set when a vcpu does a pause loop exit 380 * or cpu relax intercepted. 381 * dy_eligible: indicates whether vcpu is eligible for directed yield. 382 */ 383 struct { 384 bool in_spin_loop; 385 bool dy_eligible; 386 } spin_loop; 387 #endif 388 bool wants_to_run; 389 bool preempted; 390 bool ready; 391 bool scheduled_out; 392 struct kvm_vcpu_arch arch; 393 struct kvm_vcpu_stat stat; 394 char stats_id[KVM_STATS_NAME_SIZE]; 395 struct kvm_dirty_ring dirty_ring; 396 397 /* 398 * The most recently used memslot by this vCPU and the slots generation 399 * for which it is valid. 400 * No wraparound protection is needed since generations won't overflow in 401 * thousands of years, even assuming 1M memslot operations per second. 402 */ 403 struct kvm_memory_slot *last_used_slot; 404 u64 last_used_slot_gen; 405 }; 406 407 /* 408 * Start accounting time towards a guest. 409 * Must be called before entering guest context. 410 */ 411 static __always_inline void guest_timing_enter_irqoff(void) 412 { 413 /* 414 * This is running in ioctl context so its safe to assume that it's the 415 * stime pending cputime to flush. 416 */ 417 instrumentation_begin(); 418 vtime_account_guest_enter(); 419 instrumentation_end(); 420 } 421 422 /* 423 * Enter guest context and enter an RCU extended quiescent state. 424 * 425 * Between guest_context_enter_irqoff() and guest_context_exit_irqoff() it is 426 * unsafe to use any code which may directly or indirectly use RCU, tracing 427 * (including IRQ flag tracing), or lockdep. All code in this period must be 428 * non-instrumentable. 429 */ 430 static __always_inline void guest_context_enter_irqoff(void) 431 { 432 /* 433 * KVM does not hold any references to rcu protected data when it 434 * switches CPU into a guest mode. In fact switching to a guest mode 435 * is very similar to exiting to userspace from rcu point of view. In 436 * addition CPU may stay in a guest mode for quite a long time (up to 437 * one time slice). Lets treat guest mode as quiescent state, just like 438 * we do with user-mode execution. 439 */ 440 if (!context_tracking_guest_enter()) { 441 instrumentation_begin(); 442 rcu_virt_note_context_switch(); 443 instrumentation_end(); 444 } 445 } 446 447 /* 448 * Deprecated. Architectures should move to guest_timing_enter_irqoff() and 449 * guest_state_enter_irqoff(). 450 */ 451 static __always_inline void guest_enter_irqoff(void) 452 { 453 guest_timing_enter_irqoff(); 454 guest_context_enter_irqoff(); 455 } 456 457 /** 458 * guest_state_enter_irqoff - Fixup state when entering a guest 459 * 460 * Entry to a guest will enable interrupts, but the kernel state is interrupts 461 * disabled when this is invoked. Also tell RCU about it. 462 * 463 * 1) Trace interrupts on state 464 * 2) Invoke context tracking if enabled to adjust RCU state 465 * 3) Tell lockdep that interrupts are enabled 466 * 467 * Invoked from architecture specific code before entering a guest. 468 * Must be called with interrupts disabled and the caller must be 469 * non-instrumentable. 470 * The caller has to invoke guest_timing_enter_irqoff() before this. 471 * 472 * Note: this is analogous to exit_to_user_mode(). 473 */ 474 static __always_inline void guest_state_enter_irqoff(void) 475 { 476 instrumentation_begin(); 477 trace_hardirqs_on_prepare(); 478 lockdep_hardirqs_on_prepare(); 479 instrumentation_end(); 480 481 guest_context_enter_irqoff(); 482 lockdep_hardirqs_on(CALLER_ADDR0); 483 } 484 485 /* 486 * Exit guest context and exit an RCU extended quiescent state. 487 * 488 * Between guest_context_enter_irqoff() and guest_context_exit_irqoff() it is 489 * unsafe to use any code which may directly or indirectly use RCU, tracing 490 * (including IRQ flag tracing), or lockdep. All code in this period must be 491 * non-instrumentable. 492 */ 493 static __always_inline void guest_context_exit_irqoff(void) 494 { 495 /* 496 * Guest mode is treated as a quiescent state, see 497 * guest_context_enter_irqoff() for more details. 498 */ 499 if (!context_tracking_guest_exit()) { 500 instrumentation_begin(); 501 rcu_virt_note_context_switch(); 502 instrumentation_end(); 503 } 504 } 505 506 /* 507 * Stop accounting time towards a guest. 508 * Must be called after exiting guest context. 509 */ 510 static __always_inline void guest_timing_exit_irqoff(void) 511 { 512 instrumentation_begin(); 513 /* Flush the guest cputime we spent on the guest */ 514 vtime_account_guest_exit(); 515 instrumentation_end(); 516 } 517 518 /* 519 * Deprecated. Architectures should move to guest_state_exit_irqoff() and 520 * guest_timing_exit_irqoff(). 521 */ 522 static __always_inline void guest_exit_irqoff(void) 523 { 524 guest_context_exit_irqoff(); 525 guest_timing_exit_irqoff(); 526 } 527 528 static inline void guest_exit(void) 529 { 530 unsigned long flags; 531 532 local_irq_save(flags); 533 guest_exit_irqoff(); 534 local_irq_restore(flags); 535 } 536 537 /** 538 * guest_state_exit_irqoff - Establish state when returning from guest mode 539 * 540 * Entry from a guest disables interrupts, but guest mode is traced as 541 * interrupts enabled. Also with NO_HZ_FULL RCU might be idle. 542 * 543 * 1) Tell lockdep that interrupts are disabled 544 * 2) Invoke context tracking if enabled to reactivate RCU 545 * 3) Trace interrupts off state 546 * 547 * Invoked from architecture specific code after exiting a guest. 548 * Must be invoked with interrupts disabled and the caller must be 549 * non-instrumentable. 550 * The caller has to invoke guest_timing_exit_irqoff() after this. 551 * 552 * Note: this is analogous to enter_from_user_mode(). 553 */ 554 static __always_inline void guest_state_exit_irqoff(void) 555 { 556 lockdep_hardirqs_off(CALLER_ADDR0); 557 guest_context_exit_irqoff(); 558 559 instrumentation_begin(); 560 trace_hardirqs_off_finish(); 561 instrumentation_end(); 562 } 563 564 static inline int kvm_vcpu_exiting_guest_mode(struct kvm_vcpu *vcpu) 565 { 566 /* 567 * The memory barrier ensures a previous write to vcpu->requests cannot 568 * be reordered with the read of vcpu->mode. It pairs with the general 569 * memory barrier following the write of vcpu->mode in KVM_RUN. 570 */ 571 smp_mb__before_atomic(); 572 return cmpxchg(&vcpu->mode, IN_GUEST_MODE, EXITING_GUEST_MODE); 573 } 574 575 /* 576 * Some of the bitops functions do not support too long bitmaps. 577 * This number must be determined not to exceed such limits. 578 */ 579 #define KVM_MEM_MAX_NR_PAGES ((1UL << 31) - 1) 580 581 /* 582 * Since at idle each memslot belongs to two memslot sets it has to contain 583 * two embedded nodes for each data structure that it forms a part of. 584 * 585 * Two memslot sets (one active and one inactive) are necessary so the VM 586 * continues to run on one memslot set while the other is being modified. 587 * 588 * These two memslot sets normally point to the same set of memslots. 589 * They can, however, be desynchronized when performing a memslot management 590 * operation by replacing the memslot to be modified by its copy. 591 * After the operation is complete, both memslot sets once again point to 592 * the same, common set of memslot data. 593 * 594 * The memslots themselves are independent of each other so they can be 595 * individually added or deleted. 596 */ 597 struct kvm_memory_slot { 598 struct hlist_node id_node[2]; 599 struct interval_tree_node hva_node[2]; 600 struct rb_node gfn_node[2]; 601 gfn_t base_gfn; 602 unsigned long npages; 603 unsigned long *dirty_bitmap; 604 struct kvm_arch_memory_slot arch; 605 unsigned long userspace_addr; 606 u32 flags; 607 short id; 608 u16 as_id; 609 610 #ifdef CONFIG_KVM_GUEST_MEMFD 611 struct { 612 /* 613 * Writes protected by kvm->slots_lock. Acquiring a 614 * reference via kvm_gmem_get_file() is protected by 615 * either kvm->slots_lock or kvm->srcu. 616 */ 617 struct file *file; 618 pgoff_t pgoff; 619 } gmem; 620 #endif 621 }; 622 623 static inline bool kvm_slot_has_gmem(const struct kvm_memory_slot *slot) 624 { 625 return slot && (slot->flags & KVM_MEM_GUEST_MEMFD); 626 } 627 628 static inline bool kvm_slot_dirty_track_enabled(const struct kvm_memory_slot *slot) 629 { 630 return slot->flags & KVM_MEM_LOG_DIRTY_PAGES; 631 } 632 633 static inline unsigned long kvm_dirty_bitmap_bytes(struct kvm_memory_slot *memslot) 634 { 635 return ALIGN(memslot->npages, BITS_PER_LONG) / 8; 636 } 637 638 static inline unsigned long *kvm_second_dirty_bitmap(struct kvm_memory_slot *memslot) 639 { 640 unsigned long len = kvm_dirty_bitmap_bytes(memslot); 641 642 return memslot->dirty_bitmap + len / sizeof(*memslot->dirty_bitmap); 643 } 644 645 #ifndef KVM_DIRTY_LOG_MANUAL_CAPS 646 #define KVM_DIRTY_LOG_MANUAL_CAPS KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE 647 #endif 648 649 struct kvm_s390_adapter_int { 650 u64 ind_addr; 651 u64 ind_gaddr; 652 u64 summary_addr; 653 u64 summary_gaddr; 654 u64 ind_offset; 655 u32 summary_offset; 656 u32 adapter_id; 657 }; 658 659 struct kvm_hv_sint { 660 u32 vcpu; 661 u32 sint; 662 }; 663 664 struct kvm_xen_evtchn { 665 u32 port; 666 u32 vcpu_id; 667 int vcpu_idx; 668 u32 priority; 669 }; 670 671 struct kvm_kernel_irq_routing_entry { 672 u32 gsi; 673 u32 type; 674 int (*set)(struct kvm_kernel_irq_routing_entry *e, 675 struct kvm *kvm, int irq_source_id, int level, 676 bool line_status); 677 union { 678 struct { 679 unsigned irqchip; 680 unsigned pin; 681 } irqchip; 682 struct { 683 u32 address_lo; 684 u32 address_hi; 685 u32 data; 686 u32 flags; 687 u32 devid; 688 } msi; 689 struct kvm_s390_adapter_int adapter; 690 struct kvm_hv_sint hv_sint; 691 struct kvm_xen_evtchn xen_evtchn; 692 }; 693 struct hlist_node link; 694 }; 695 696 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING 697 struct kvm_irq_routing_table { 698 int chip[KVM_NR_IRQCHIPS][KVM_IRQCHIP_NUM_PINS]; 699 u32 nr_rt_entries; 700 /* 701 * Array indexed by gsi. Each entry contains list of irq chips 702 * the gsi is connected to. 703 */ 704 struct hlist_head map[] __counted_by(nr_rt_entries); 705 }; 706 #endif 707 708 bool kvm_arch_irqchip_in_kernel(struct kvm *kvm); 709 710 #ifndef KVM_INTERNAL_MEM_SLOTS 711 #define KVM_INTERNAL_MEM_SLOTS 0 712 #endif 713 714 #define KVM_MEM_SLOTS_NUM SHRT_MAX 715 #define KVM_USER_MEM_SLOTS (KVM_MEM_SLOTS_NUM - KVM_INTERNAL_MEM_SLOTS) 716 717 #if KVM_MAX_NR_ADDRESS_SPACES == 1 718 static inline int kvm_arch_nr_memslot_as_ids(struct kvm *kvm) 719 { 720 return KVM_MAX_NR_ADDRESS_SPACES; 721 } 722 723 static inline int kvm_arch_vcpu_memslots_id(struct kvm_vcpu *vcpu) 724 { 725 return 0; 726 } 727 #endif 728 729 #ifndef kvm_arch_has_readonly_mem 730 static inline bool kvm_arch_has_readonly_mem(struct kvm *kvm) 731 { 732 #ifdef __KVM_HAVE_READONLY_MEM 733 return true; 734 #else 735 return false; 736 #endif 737 } 738 #endif 739 740 struct kvm_memslots { 741 u64 generation; 742 atomic_long_t last_used_slot; 743 struct rb_root_cached hva_tree; 744 struct rb_root gfn_tree; 745 /* 746 * The mapping table from slot id to memslot. 747 * 748 * 7-bit bucket count matches the size of the old id to index array for 749 * 512 slots, while giving good performance with this slot count. 750 * Higher bucket counts bring only small performance improvements but 751 * always result in higher memory usage (even for lower memslot counts). 752 */ 753 DECLARE_HASHTABLE(id_hash, 7); 754 int node_idx; 755 }; 756 757 struct kvm { 758 #ifdef KVM_HAVE_MMU_RWLOCK 759 rwlock_t mmu_lock; 760 #else 761 spinlock_t mmu_lock; 762 #endif /* KVM_HAVE_MMU_RWLOCK */ 763 764 struct mutex slots_lock; 765 766 /* 767 * Protects the arch-specific fields of struct kvm_memory_slots in 768 * use by the VM. To be used under the slots_lock (above) or in a 769 * kvm->srcu critical section where acquiring the slots_lock would 770 * lead to deadlock with the synchronize_srcu in 771 * kvm_swap_active_memslots(). 772 */ 773 struct mutex slots_arch_lock; 774 /* 775 * Back-reference to the VM file for subsystems (e.g., VFIO). Holds no 776 * reference to avoid pinning the VM. Callers storing the file must 777 * take their own reference. 778 */ 779 struct file *file; 780 struct mm_struct *mm; /* userspace tied to this vm */ 781 unsigned long nr_memslot_pages; 782 /* The two memslot sets - active and inactive (per address space) */ 783 struct kvm_memslots __memslots[KVM_MAX_NR_ADDRESS_SPACES][2]; 784 /* The current active memslot set for each address space */ 785 struct kvm_memslots __rcu *memslots[KVM_MAX_NR_ADDRESS_SPACES]; 786 struct xarray vcpu_array; 787 /* 788 * Protected by slots_lock, but can be read outside if an 789 * incorrect answer is acceptable. 790 */ 791 atomic_t nr_memslots_dirty_logging; 792 793 /* Used to wait for completion of MMU notifiers. */ 794 spinlock_t mn_invalidate_lock; 795 unsigned long mn_active_invalidate_count; 796 struct rcuwait mn_memslots_update_rcuwait; 797 798 /* For management / invalidation of gfn_to_pfn_caches */ 799 spinlock_t gpc_lock; 800 struct list_head gpc_list; 801 802 /* 803 * created_vcpus is protected by kvm->lock, and is incremented 804 * at the beginning of KVM_CREATE_VCPU. online_vcpus is only 805 * incremented after storing the kvm_vcpu pointer in vcpus, 806 * and is accessed atomically. 807 */ 808 atomic_t online_vcpus; 809 int max_vcpus; 810 int created_vcpus; 811 int last_boosted_vcpu; 812 struct list_head vm_list; 813 struct mutex lock; 814 struct kvm_io_bus __rcu *buses[KVM_NR_BUSES]; 815 #ifdef CONFIG_HAVE_KVM_IRQCHIP 816 struct { 817 spinlock_t lock; 818 struct list_head items; 819 /* resampler_list update side is protected by resampler_lock. */ 820 struct list_head resampler_list; 821 struct mutex resampler_lock; 822 } irqfds; 823 #endif 824 struct list_head ioeventfds; 825 struct kvm_vm_stat stat; 826 struct kvm_arch arch; 827 refcount_t users_count; 828 #ifndef __KVM_NO_MMIO 829 struct kvm_coalesced_mmio_ring *coalesced_mmio_ring; 830 spinlock_t ring_lock; 831 struct list_head coalesced_zones; 832 #endif 833 834 struct mutex irq_lock; 835 #ifdef CONFIG_HAVE_KVM_IRQCHIP 836 /* 837 * Update side is protected by irq_lock. 838 */ 839 struct kvm_irq_routing_table __rcu *irq_routing; 840 841 struct hlist_head irq_ack_notifier_list; 842 #endif 843 844 struct mmu_notifier mmu_notifier; 845 unsigned long mmu_invalidate_seq; 846 long mmu_invalidate_in_progress; 847 gfn_t mmu_invalidate_range_start; 848 gfn_t mmu_invalidate_range_end; 849 850 unsigned long gpc_invalidate_seq; 851 852 struct list_head devices; 853 u64 manual_dirty_log_protect; 854 struct dentry *debugfs_dentry; 855 struct kvm_stat_data **debugfs_stat_data; 856 struct srcu_struct srcu; 857 struct srcu_struct irq_srcu; 858 pid_t userspace_pid; 859 bool override_halt_poll_ns; 860 unsigned int max_halt_poll_ns; 861 u32 dirty_ring_size; 862 bool dirty_ring_with_bitmap; 863 bool vm_bugged; 864 bool vm_dead; 865 866 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER 867 struct notifier_block pm_notifier; 868 #endif 869 #ifdef CONFIG_KVM_VM_MEMORY_ATTRIBUTES 870 /* Protected by slots_lock (for writes) and RCU (for reads) */ 871 struct xarray mem_attr_array; 872 #endif 873 char stats_id[KVM_STATS_NAME_SIZE]; 874 }; 875 876 #define kvm_err(fmt, ...) \ 877 pr_err("kvm [%i]: " fmt, task_pid_nr(current), ## __VA_ARGS__) 878 #define kvm_info(fmt, ...) \ 879 pr_info("kvm [%i]: " fmt, task_pid_nr(current), ## __VA_ARGS__) 880 #define kvm_debug(fmt, ...) \ 881 pr_debug("kvm [%i]: " fmt, task_pid_nr(current), ## __VA_ARGS__) 882 #define kvm_debug_ratelimited(fmt, ...) \ 883 pr_debug_ratelimited("kvm [%i]: " fmt, task_pid_nr(current), \ 884 ## __VA_ARGS__) 885 #define kvm_pr_unimpl(fmt, ...) \ 886 pr_err_ratelimited("kvm [%i]: " fmt, \ 887 task_tgid_nr(current), ## __VA_ARGS__) 888 889 /* The guest did something we don't support. */ 890 #define vcpu_unimpl(vcpu, fmt, ...) \ 891 kvm_pr_unimpl("vcpu%i, guest rIP: 0x%lx " fmt, \ 892 (vcpu)->vcpu_id, kvm_rip_read(vcpu), ## __VA_ARGS__) 893 894 #define vcpu_debug(vcpu, fmt, ...) \ 895 kvm_debug("vcpu%i " fmt, (vcpu)->vcpu_id, ## __VA_ARGS__) 896 #define vcpu_debug_ratelimited(vcpu, fmt, ...) \ 897 kvm_debug_ratelimited("vcpu%i " fmt, (vcpu)->vcpu_id, \ 898 ## __VA_ARGS__) 899 #define vcpu_err(vcpu, fmt, ...) \ 900 kvm_err("vcpu%i " fmt, (vcpu)->vcpu_id, ## __VA_ARGS__) 901 902 static inline void kvm_vm_dead(struct kvm *kvm) 903 { 904 kvm->vm_dead = true; 905 kvm_make_all_cpus_request(kvm, KVM_REQ_VM_DEAD); 906 } 907 908 static inline void kvm_vm_bugged(struct kvm *kvm) 909 { 910 kvm->vm_bugged = true; 911 kvm_vm_dead(kvm); 912 } 913 914 915 #define KVM_BUG(cond, kvm, fmt...) \ 916 ({ \ 917 bool __ret = !!(cond); \ 918 \ 919 if (WARN_ONCE(__ret && !(kvm)->vm_bugged, fmt)) \ 920 kvm_vm_bugged(kvm); \ 921 unlikely(__ret); \ 922 }) 923 924 #define KVM_BUG_ON(cond, kvm) \ 925 ({ \ 926 bool __ret = !!(cond); \ 927 \ 928 if (WARN_ON_ONCE(__ret && !(kvm)->vm_bugged)) \ 929 kvm_vm_bugged(kvm); \ 930 unlikely(__ret); \ 931 }) 932 933 /* 934 * Note, "data corruption" refers to corruption of host kernel data structures, 935 * not guest data. Guest data corruption, suspected or confirmed, that is tied 936 * and contained to a single VM should *never* BUG() and potentially panic the 937 * host, i.e. use this variant of KVM_BUG() if and only if a KVM data structure 938 * is corrupted and that corruption can have a cascading effect to other parts 939 * of the hosts and/or to other VMs. 940 */ 941 #define KVM_BUG_ON_DATA_CORRUPTION(cond, kvm) \ 942 ({ \ 943 bool __ret = !!(cond); \ 944 \ 945 if (IS_ENABLED(CONFIG_BUG_ON_DATA_CORRUPTION)) \ 946 BUG_ON(__ret); \ 947 else if (WARN_ON_ONCE(__ret && !(kvm)->vm_bugged)) \ 948 kvm_vm_bugged(kvm); \ 949 unlikely(__ret); \ 950 }) 951 952 static inline void kvm_vcpu_srcu_read_lock(struct kvm_vcpu *vcpu) 953 { 954 #ifdef CONFIG_PROVE_RCU 955 WARN_ONCE(vcpu->srcu_depth++, 956 "KVM: Illegal vCPU srcu_idx LOCK, depth=%d", vcpu->srcu_depth - 1); 957 #endif 958 vcpu->____srcu_idx = srcu_read_lock(&vcpu->kvm->srcu); 959 } 960 961 static inline void kvm_vcpu_srcu_read_unlock(struct kvm_vcpu *vcpu) 962 { 963 srcu_read_unlock(&vcpu->kvm->srcu, vcpu->____srcu_idx); 964 965 #ifdef CONFIG_PROVE_RCU 966 WARN_ONCE(--vcpu->srcu_depth, 967 "KVM: Illegal vCPU srcu_idx UNLOCK, depth=%d", vcpu->srcu_depth); 968 #endif 969 } 970 971 static inline bool kvm_dirty_log_manual_protect_and_init_set(struct kvm *kvm) 972 { 973 return !!(kvm->manual_dirty_log_protect & KVM_DIRTY_LOG_INITIALLY_SET); 974 } 975 976 /* 977 * Get a bus reference under the update-side lock. No long-term SRCU reader 978 * references are permitted, to avoid stale reads vs concurrent IO 979 * registrations. 980 */ 981 static inline struct kvm_io_bus *kvm_get_bus(struct kvm *kvm, enum kvm_bus idx) 982 { 983 return rcu_dereference_protected(kvm->buses[idx], 984 lockdep_is_held(&kvm->slots_lock)); 985 } 986 987 static inline void kvm_lockdep_assert_vcpu_is_locked_or_unreachable(struct kvm_vcpu *vcpu) 988 { 989 lockdep_assert_once(lockdep_is_held(&vcpu->mutex) || 990 vcpu->vcpu_idx < 0 || 991 !refcount_read(&vcpu->kvm->users_count)); 992 } 993 994 static inline struct kvm_vcpu *kvm_get_vcpu(struct kvm *kvm, int i) 995 { 996 int num_vcpus = atomic_read(&kvm->online_vcpus); 997 998 /* 999 * Explicitly verify the target vCPU is online, as the anti-speculation 1000 * logic only limits the CPU's ability to speculate, e.g. given a "bad" 1001 * index, clamping the index to 0 would return vCPU0, not NULL. 1002 */ 1003 if (i >= num_vcpus) 1004 return NULL; 1005 1006 i = array_index_nospec(i, num_vcpus); 1007 1008 /* Pairs with smp_wmb() in kvm_vm_ioctl_create_vcpu. */ 1009 smp_rmb(); 1010 return xa_load(&kvm->vcpu_array, i); 1011 } 1012 1013 #define kvm_for_each_vcpu(idx, vcpup, kvm) \ 1014 if (atomic_read(&kvm->online_vcpus)) \ 1015 xa_for_each_range(&kvm->vcpu_array, idx, vcpup, 0, \ 1016 (atomic_read(&kvm->online_vcpus) - 1)) 1017 1018 static inline struct kvm_vcpu *kvm_get_vcpu_by_id(struct kvm *kvm, int id) 1019 { 1020 struct kvm_vcpu *vcpu = NULL; 1021 unsigned long i; 1022 1023 if (id < 0) 1024 return NULL; 1025 if (id < KVM_MAX_VCPUS) 1026 vcpu = kvm_get_vcpu(kvm, id); 1027 if (vcpu && vcpu->vcpu_id == id) 1028 return vcpu; 1029 kvm_for_each_vcpu(i, vcpu, kvm) 1030 if (vcpu->vcpu_id == id) 1031 return vcpu; 1032 return NULL; 1033 } 1034 1035 static inline bool kvm_is_vcpu_creation_in_progress(struct kvm *kvm) 1036 { 1037 lockdep_assert_held(&kvm->lock); 1038 1039 return kvm->created_vcpus != atomic_read(&kvm->online_vcpus); 1040 } 1041 1042 void kvm_destroy_vcpus(struct kvm *kvm); 1043 1044 int kvm_trylock_all_vcpus(struct kvm *kvm); 1045 int kvm_lock_all_vcpus(struct kvm *kvm); 1046 void kvm_unlock_all_vcpus(struct kvm *kvm); 1047 1048 void vcpu_load(struct kvm_vcpu *vcpu); 1049 void vcpu_put(struct kvm_vcpu *vcpu); 1050 1051 #ifdef CONFIG_KVM_IOAPIC 1052 void kvm_arch_post_irq_ack_notifier_list_update(struct kvm *kvm); 1053 #else 1054 static inline void kvm_arch_post_irq_ack_notifier_list_update(struct kvm *kvm) 1055 { 1056 } 1057 #endif 1058 1059 #ifdef CONFIG_HAVE_KVM_IRQCHIP 1060 int kvm_irqfd_init(void); 1061 void kvm_irqfd_exit(void); 1062 #else 1063 static inline int kvm_irqfd_init(void) 1064 { 1065 return 0; 1066 } 1067 1068 static inline void kvm_irqfd_exit(void) 1069 { 1070 } 1071 #endif 1072 int kvm_init(unsigned vcpu_size, unsigned vcpu_align, struct module *module); 1073 void kvm_exit(void); 1074 1075 void kvm_get_kvm(struct kvm *kvm); 1076 bool kvm_get_kvm_safe(struct kvm *kvm); 1077 void kvm_put_kvm(struct kvm *kvm); 1078 1079 /* 1080 * Architectures define kvm_file_to_kvm_arch to <arch> 1081 * to get a typed, arch-namespaced helper: 1082 * 1083 * struct kvm *file_to_kvm_<arch>(struct file *file) 1084 */ 1085 #ifdef kvm_file_to_kvm_arch 1086 #define kvm_file_to_kvm_fn CONCATENATE(file_to_kvm_, kvm_file_to_kvm_arch) 1087 struct kvm *kvm_file_to_kvm_fn(struct file *file); 1088 #endif /* kvm_file_to_kvm_arch */ 1089 1090 void kvm_put_kvm_no_destroy(struct kvm *kvm); 1091 1092 static inline struct kvm_memslots *__kvm_memslots(struct kvm *kvm, int as_id) 1093 { 1094 as_id = array_index_nospec(as_id, KVM_MAX_NR_ADDRESS_SPACES); 1095 return srcu_dereference_check(kvm->memslots[as_id], &kvm->srcu, 1096 lockdep_is_held(&kvm->slots_lock) || 1097 !refcount_read(&kvm->users_count)); 1098 } 1099 1100 static inline struct kvm_memslots *kvm_memslots(struct kvm *kvm) 1101 { 1102 return __kvm_memslots(kvm, 0); 1103 } 1104 1105 static inline struct kvm_memslots *kvm_vcpu_memslots(struct kvm_vcpu *vcpu) 1106 { 1107 int as_id = kvm_arch_vcpu_memslots_id(vcpu); 1108 1109 return __kvm_memslots(vcpu->kvm, as_id); 1110 } 1111 1112 static inline bool kvm_memslots_empty(struct kvm_memslots *slots) 1113 { 1114 return RB_EMPTY_ROOT(&slots->gfn_tree); 1115 } 1116 1117 bool kvm_are_all_memslots_empty(struct kvm *kvm); 1118 1119 #define kvm_for_each_memslot(memslot, bkt, slots) \ 1120 hash_for_each(slots->id_hash, bkt, memslot, id_node[slots->node_idx]) \ 1121 if (WARN_ON_ONCE(!memslot->npages)) { \ 1122 } else 1123 1124 static inline 1125 struct kvm_memory_slot *id_to_memslot(struct kvm_memslots *slots, int id) 1126 { 1127 struct kvm_memory_slot *slot; 1128 int idx = slots->node_idx; 1129 1130 hash_for_each_possible(slots->id_hash, slot, id_node[idx], id) { 1131 if (slot->id == id) 1132 return slot; 1133 } 1134 1135 return NULL; 1136 } 1137 1138 /* Iterator used for walking memslots that overlap a gfn range. */ 1139 struct kvm_memslot_iter { 1140 struct kvm_memslots *slots; 1141 struct rb_node *node; 1142 struct kvm_memory_slot *slot; 1143 }; 1144 1145 static inline void kvm_memslot_iter_next(struct kvm_memslot_iter *iter) 1146 { 1147 iter->node = rb_next(iter->node); 1148 if (!iter->node) 1149 return; 1150 1151 iter->slot = container_of(iter->node, struct kvm_memory_slot, gfn_node[iter->slots->node_idx]); 1152 } 1153 1154 static inline void kvm_memslot_iter_start(struct kvm_memslot_iter *iter, 1155 struct kvm_memslots *slots, 1156 gfn_t start) 1157 { 1158 int idx = slots->node_idx; 1159 struct rb_node *tmp; 1160 struct kvm_memory_slot *slot; 1161 1162 iter->slots = slots; 1163 1164 /* 1165 * Find the so called "upper bound" of a key - the first node that has 1166 * its key strictly greater than the searched one (the start gfn in our case). 1167 */ 1168 iter->node = NULL; 1169 for (tmp = slots->gfn_tree.rb_node; tmp; ) { 1170 slot = container_of(tmp, struct kvm_memory_slot, gfn_node[idx]); 1171 if (start < slot->base_gfn) { 1172 iter->node = tmp; 1173 tmp = tmp->rb_left; 1174 } else { 1175 tmp = tmp->rb_right; 1176 } 1177 } 1178 1179 /* 1180 * Find the slot with the lowest gfn that can possibly intersect with 1181 * the range, so we'll ideally have slot start <= range start 1182 */ 1183 if (iter->node) { 1184 /* 1185 * A NULL previous node means that the very first slot 1186 * already has a higher start gfn. 1187 * In this case slot start > range start. 1188 */ 1189 tmp = rb_prev(iter->node); 1190 if (tmp) 1191 iter->node = tmp; 1192 } else { 1193 /* a NULL node below means no slots */ 1194 iter->node = rb_last(&slots->gfn_tree); 1195 } 1196 1197 if (iter->node) { 1198 iter->slot = container_of(iter->node, struct kvm_memory_slot, gfn_node[idx]); 1199 1200 /* 1201 * It is possible in the slot start < range start case that the 1202 * found slot ends before or at range start (slot end <= range start) 1203 * and so it does not overlap the requested range. 1204 * 1205 * In such non-overlapping case the next slot (if it exists) will 1206 * already have slot start > range start, otherwise the logic above 1207 * would have found it instead of the current slot. 1208 */ 1209 if (iter->slot->base_gfn + iter->slot->npages <= start) 1210 kvm_memslot_iter_next(iter); 1211 } 1212 } 1213 1214 static inline bool kvm_memslot_iter_is_valid(struct kvm_memslot_iter *iter, gfn_t end) 1215 { 1216 if (!iter->node) 1217 return false; 1218 1219 /* 1220 * If this slot starts beyond or at the end of the range so does 1221 * every next one 1222 */ 1223 return iter->slot->base_gfn < end; 1224 } 1225 1226 /* Iterate over each memslot at least partially intersecting [start, end) range */ 1227 #define kvm_for_each_memslot_in_gfn_range(iter, slots, start, end) \ 1228 for (kvm_memslot_iter_start(iter, slots, start); \ 1229 kvm_memslot_iter_is_valid(iter, end); \ 1230 kvm_memslot_iter_next(iter)) 1231 1232 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn); 1233 struct kvm_memslots *kvm_vcpu_memslots(struct kvm_vcpu *vcpu); 1234 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn); 1235 1236 /* 1237 * KVM_SET_USER_MEMORY_REGION ioctl allows the following operations: 1238 * - create a new memory slot 1239 * - delete an existing memory slot 1240 * - modify an existing memory slot 1241 * -- move it in the guest physical memory space 1242 * -- just change its flags 1243 * 1244 * Since flags can be changed by some of these operations, the following 1245 * differentiation is the best we can do for kvm_set_memory_region(): 1246 */ 1247 enum kvm_mr_change { 1248 KVM_MR_CREATE, 1249 KVM_MR_DELETE, 1250 KVM_MR_MOVE, 1251 KVM_MR_FLAGS_ONLY, 1252 }; 1253 1254 int kvm_set_internal_memslot(struct kvm *kvm, 1255 const struct kvm_userspace_memory_region2 *mem); 1256 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot); 1257 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen); 1258 int kvm_arch_prepare_memory_region(struct kvm *kvm, 1259 const struct kvm_memory_slot *old, 1260 struct kvm_memory_slot *new, 1261 enum kvm_mr_change change); 1262 void kvm_arch_commit_memory_region(struct kvm *kvm, 1263 struct kvm_memory_slot *old, 1264 const struct kvm_memory_slot *new, 1265 enum kvm_mr_change change); 1266 /* flush all memory translations */ 1267 void kvm_arch_flush_shadow_all(struct kvm *kvm); 1268 /* flush memory translations pointing to 'slot' */ 1269 void kvm_arch_flush_shadow_memslot(struct kvm *kvm, 1270 struct kvm_memory_slot *slot); 1271 1272 int kvm_prefetch_pages(struct kvm_memory_slot *slot, gfn_t gfn, 1273 struct page **pages, int nr_pages); 1274 1275 struct page *__gfn_to_page(struct kvm *kvm, gfn_t gfn, bool write); 1276 static inline struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn) 1277 { 1278 return __gfn_to_page(kvm, gfn, true); 1279 } 1280 1281 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn); 1282 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable); 1283 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot, gfn_t gfn); 1284 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot, gfn_t gfn, 1285 bool *writable); 1286 1287 static inline void kvm_release_page_unused(struct page *page) 1288 { 1289 if (!page) 1290 return; 1291 1292 put_page(page); 1293 } 1294 1295 void kvm_release_page_clean(struct page *page); 1296 void kvm_release_page_dirty(struct page *page); 1297 1298 static inline void kvm_release_faultin_page(struct kvm *kvm, struct page *page, 1299 bool unused, bool dirty) 1300 { 1301 lockdep_assert_once(lockdep_is_held(&kvm->mmu_lock) || unused); 1302 1303 if (!page) 1304 return; 1305 1306 /* 1307 * If the page that KVM got from the *primary MMU* is writable, and KVM 1308 * installed or reused a SPTE, mark the page/folio dirty. Note, this 1309 * may mark a folio dirty even if KVM created a read-only SPTE, e.g. if 1310 * the GFN is write-protected. Folios can't be safely marked dirty 1311 * outside of mmu_lock as doing so could race with writeback on the 1312 * folio. As a result, KVM can't mark folios dirty in the fast page 1313 * fault handler, and so KVM must (somewhat) speculatively mark the 1314 * folio dirty if KVM could locklessly make the SPTE writable. 1315 */ 1316 if (unused) 1317 kvm_release_page_unused(page); 1318 else if (dirty) 1319 kvm_release_page_dirty(page); 1320 else 1321 kvm_release_page_clean(page); 1322 } 1323 1324 kvm_pfn_t __kvm_faultin_pfn(const struct kvm_memory_slot *slot, gfn_t gfn, 1325 unsigned int foll, bool *writable, 1326 struct page **refcounted_page); 1327 1328 static inline kvm_pfn_t kvm_faultin_pfn(struct kvm_vcpu *vcpu, gfn_t gfn, 1329 bool write, bool *writable, 1330 struct page **refcounted_page) 1331 { 1332 return __kvm_faultin_pfn(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, 1333 write ? FOLL_WRITE : 0, writable, refcounted_page); 1334 } 1335 1336 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset, 1337 int len); 1338 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len); 1339 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc, 1340 void *data, unsigned long len); 1341 int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc, 1342 void *data, unsigned int offset, 1343 unsigned long len); 1344 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, const void *data, 1345 int offset, int len); 1346 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data, 1347 unsigned long len); 1348 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc, 1349 void *data, unsigned long len); 1350 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc, 1351 void *data, unsigned int offset, 1352 unsigned long len); 1353 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc, 1354 gpa_t gpa, unsigned long len); 1355 1356 #define __kvm_get_guest(kvm, gfn, offset, v) \ 1357 ({ \ 1358 unsigned long __addr = gfn_to_hva(kvm, gfn); \ 1359 typeof(v) __user *__uaddr = (typeof(__uaddr))(__addr + offset); \ 1360 int __ret = -EFAULT; \ 1361 \ 1362 if (!kvm_is_error_hva(__addr)) \ 1363 __ret = get_user(v, __uaddr); \ 1364 __ret; \ 1365 }) 1366 1367 #define kvm_get_guest(kvm, gpa, v) \ 1368 ({ \ 1369 gpa_t __gpa = gpa; \ 1370 struct kvm *__kvm = kvm; \ 1371 \ 1372 __kvm_get_guest(__kvm, __gpa >> PAGE_SHIFT, \ 1373 offset_in_page(__gpa), v); \ 1374 }) 1375 1376 #define __kvm_put_guest(kvm, gfn, offset, v) \ 1377 ({ \ 1378 unsigned long __addr = gfn_to_hva(kvm, gfn); \ 1379 typeof(v) __user *__uaddr = (typeof(__uaddr))(__addr + offset); \ 1380 int __ret = -EFAULT; \ 1381 \ 1382 if (!kvm_is_error_hva(__addr)) \ 1383 __ret = put_user(v, __uaddr); \ 1384 if (!__ret) \ 1385 mark_page_dirty(kvm, gfn); \ 1386 __ret; \ 1387 }) 1388 1389 #define kvm_put_guest(kvm, gpa, v) \ 1390 ({ \ 1391 gpa_t __gpa = gpa; \ 1392 struct kvm *__kvm = kvm; \ 1393 \ 1394 __kvm_put_guest(__kvm, __gpa >> PAGE_SHIFT, \ 1395 offset_in_page(__gpa), v); \ 1396 }) 1397 1398 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len); 1399 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn); 1400 bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn); 1401 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn); 1402 void mark_page_dirty_in_slot(struct kvm *kvm, const struct kvm_memory_slot *memslot, gfn_t gfn); 1403 void mark_page_dirty(struct kvm *kvm, gfn_t gfn); 1404 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn); 1405 1406 int __kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map, 1407 bool writable); 1408 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map); 1409 1410 static inline int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, 1411 struct kvm_host_map *map) 1412 { 1413 return __kvm_vcpu_map(vcpu, gfn, map, true); 1414 } 1415 1416 static inline int kvm_vcpu_map_readonly(struct kvm_vcpu *vcpu, gfn_t gfn, 1417 struct kvm_host_map *map) 1418 { 1419 return __kvm_vcpu_map(vcpu, gfn, map, false); 1420 } 1421 1422 static inline void kvm_vcpu_map_mark_dirty(struct kvm_vcpu *vcpu, 1423 struct kvm_host_map *map) 1424 { 1425 if (kvm_vcpu_mapped(map)) 1426 kvm_vcpu_mark_page_dirty(vcpu, map->gfn); 1427 } 1428 1429 typedef struct { 1430 struct kvm_vcpu *vcpu; 1431 struct kvm_host_map map; 1432 int ret; 1433 } kvm_vcpu_local_map_t; 1434 1435 #define DEFINE_VCPU_MAP_CLASS(ro) \ 1436 DEFINE_CLASS(kvm_vcpu_map_local##ro, kvm_vcpu_local_map_t, \ 1437 if (!_T.ret) kvm_vcpu_unmap(_T.vcpu, &_T.map), \ 1438 ({ \ 1439 kvm_vcpu_local_map_t m = { .vcpu = vcpu }; \ 1440 \ 1441 m.ret = kvm_vcpu_map##ro(vcpu, gfn, &m.map); \ 1442 \ 1443 m; \ 1444 }), struct kvm_vcpu *vcpu, gfn_t gfn); 1445 DEFINE_VCPU_MAP_CLASS(); 1446 DEFINE_VCPU_MAP_CLASS(_readonly); 1447 1448 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn); 1449 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable); 1450 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data, int offset, 1451 int len); 1452 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, 1453 unsigned long len); 1454 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, 1455 unsigned long len); 1456 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, const void *data, 1457 int offset, int len); 1458 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data, 1459 unsigned long len); 1460 1461 /** 1462 * kvm_gpc_init - initialize gfn_to_pfn_cache. 1463 * 1464 * @gpc: struct gfn_to_pfn_cache object. 1465 * @kvm: pointer to kvm instance. 1466 * 1467 * This sets up a gfn_to_pfn_cache by initializing locks and assigning the 1468 * immutable attributes. Note, the cache must be zero-allocated (or zeroed by 1469 * the caller before init). 1470 */ 1471 void kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm); 1472 1473 /** 1474 * kvm_gpc_activate - prepare a cached kernel mapping and HPA for a given guest 1475 * physical address. 1476 * 1477 * @gpc: struct gfn_to_pfn_cache object. 1478 * @gpa: guest physical address to map. 1479 * @len: sanity check; the range being access must fit a single page. 1480 * 1481 * @return: 0 for success. 1482 * -EINVAL for a mapping which would cross a page boundary. 1483 * -EFAULT for an untranslatable guest physical address. 1484 * 1485 * This primes a gfn_to_pfn_cache and links it into the @gpc->kvm's list for 1486 * invalidations to be processed. Callers are required to use kvm_gpc_check() 1487 * to ensure that the cache is valid before accessing the target page. 1488 */ 1489 int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len); 1490 1491 /** 1492 * kvm_gpc_activate_hva - prepare a cached kernel mapping and HPA for a given HVA. 1493 * 1494 * @gpc: struct gfn_to_pfn_cache object. 1495 * @hva: userspace virtual address to map. 1496 * @len: sanity check; the range being access must fit a single page. 1497 * 1498 * @return: 0 for success. 1499 * -EINVAL for a mapping which would cross a page boundary. 1500 * -EFAULT for an untranslatable guest physical address. 1501 * 1502 * The semantics of this function are the same as those of kvm_gpc_activate(). It 1503 * merely bypasses a layer of address translation. 1504 */ 1505 int kvm_gpc_activate_hva(struct gfn_to_pfn_cache *gpc, unsigned long hva, unsigned long len); 1506 1507 /** 1508 * kvm_gpc_check - check validity of a gfn_to_pfn_cache. 1509 * 1510 * @gpc: struct gfn_to_pfn_cache object. 1511 * @len: sanity check; the range being access must fit a single page. 1512 * 1513 * @return: %true if the cache is still valid and the address matches. 1514 * %false if the cache is not valid. 1515 * 1516 * Callers outside IN_GUEST_MODE context should hold a read lock on @gpc->lock 1517 * while calling this function, and then continue to hold the lock until the 1518 * access is complete. 1519 * 1520 * Callers in IN_GUEST_MODE may do so without locking, although they should 1521 * still hold a read lock on kvm->scru for the memslot checks. 1522 */ 1523 bool kvm_gpc_check(struct gfn_to_pfn_cache *gpc, unsigned long len); 1524 1525 /** 1526 * kvm_gpc_refresh - update a previously initialized cache. 1527 * 1528 * @gpc: struct gfn_to_pfn_cache object. 1529 * @len: sanity check; the range being access must fit a single page. 1530 * 1531 * @return: 0 for success. 1532 * -EINVAL for a mapping which would cross a page boundary. 1533 * -EFAULT for an untranslatable guest physical address. 1534 * 1535 * This will attempt to refresh a gfn_to_pfn_cache. Note that a successful 1536 * return from this function does not mean the page can be immediately 1537 * accessed because it may have raced with an invalidation. Callers must 1538 * still lock and check the cache status, as this function does not return 1539 * with the lock still held to permit access. 1540 */ 1541 int kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, unsigned long len); 1542 1543 /** 1544 * kvm_gpc_deactivate - deactivate and unlink a gfn_to_pfn_cache. 1545 * 1546 * @gpc: struct gfn_to_pfn_cache object. 1547 * 1548 * This removes a cache from the VM's list to be processed on MMU notifier 1549 * invocation. 1550 */ 1551 void kvm_gpc_deactivate(struct gfn_to_pfn_cache *gpc); 1552 1553 static inline bool kvm_gpc_is_gpa_active(struct gfn_to_pfn_cache *gpc) 1554 { 1555 return gpc->active && !kvm_is_error_gpa(gpc->gpa); 1556 } 1557 1558 static inline bool kvm_gpc_is_hva_active(struct gfn_to_pfn_cache *gpc) 1559 { 1560 return gpc->active && kvm_is_error_gpa(gpc->gpa); 1561 } 1562 1563 void kvm_sigset_activate(struct kvm_vcpu *vcpu); 1564 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu); 1565 1566 void kvm_vcpu_halt(struct kvm_vcpu *vcpu); 1567 bool kvm_vcpu_block(struct kvm_vcpu *vcpu); 1568 void kvm_arch_vcpu_blocking(struct kvm_vcpu *vcpu); 1569 void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu); 1570 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu); 1571 1572 #ifndef CONFIG_S390 1573 void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, bool wait); 1574 1575 static inline void kvm_vcpu_kick(struct kvm_vcpu *vcpu) 1576 { 1577 __kvm_vcpu_kick(vcpu, false); 1578 } 1579 #endif 1580 1581 int kvm_vcpu_yield_to(struct kvm_vcpu *target); 1582 void kvm_vcpu_on_spin(struct kvm_vcpu *vcpu, bool yield_to_kernel_mode); 1583 1584 void kvm_flush_remote_tlbs(struct kvm *kvm); 1585 void kvm_flush_remote_tlbs_range(struct kvm *kvm, gfn_t gfn, u64 nr_pages); 1586 void kvm_flush_remote_tlbs_memslot(struct kvm *kvm, 1587 const struct kvm_memory_slot *memslot); 1588 1589 #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE 1590 int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min); 1591 int __kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int capacity, int min); 1592 int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc); 1593 void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc); 1594 void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc); 1595 #endif 1596 1597 void kvm_mmu_invalidate_start(struct kvm *kvm); 1598 void kvm_mmu_invalidate_range_add(struct kvm *kvm, gfn_t start, gfn_t end); 1599 void kvm_mmu_invalidate_end(struct kvm *kvm); 1600 bool kvm_mmu_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range); 1601 1602 long kvm_arch_dev_ioctl(struct file *filp, 1603 unsigned int ioctl, unsigned long arg); 1604 long kvm_arch_vcpu_ioctl(struct file *filp, 1605 unsigned int ioctl, unsigned long arg); 1606 long kvm_arch_vcpu_unlocked_ioctl(struct file *filp, 1607 unsigned int ioctl, unsigned long arg); 1608 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf); 1609 1610 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext); 1611 1612 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm, 1613 struct kvm_memory_slot *slot, 1614 gfn_t gfn_offset, 1615 unsigned long mask); 1616 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot); 1617 1618 #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT 1619 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log); 1620 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log, 1621 int *is_dirty, struct kvm_memory_slot **memslot); 1622 #endif 1623 1624 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_level, 1625 bool line_status); 1626 int kvm_vm_ioctl_enable_cap(struct kvm *kvm, 1627 struct kvm_enable_cap *cap); 1628 int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg); 1629 long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl, 1630 unsigned long arg); 1631 1632 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu); 1633 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu); 1634 1635 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu, 1636 struct kvm_translation *tr); 1637 1638 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs); 1639 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs); 1640 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu, 1641 struct kvm_sregs *sregs); 1642 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu, 1643 struct kvm_sregs *sregs); 1644 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu, 1645 struct kvm_mp_state *mp_state); 1646 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu, 1647 struct kvm_mp_state *mp_state); 1648 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu, 1649 struct kvm_guest_debug *dbg); 1650 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu); 1651 1652 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu); 1653 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu); 1654 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id); 1655 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu); 1656 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu); 1657 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu); 1658 1659 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER 1660 int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state); 1661 #endif 1662 1663 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS 1664 void kvm_arch_create_vcpu_debugfs(struct kvm_vcpu *vcpu, struct dentry *debugfs_dentry); 1665 #else 1666 static inline void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu) {} 1667 #endif 1668 1669 #ifdef CONFIG_KVM_GENERIC_HARDWARE_ENABLING 1670 /* 1671 * kvm_arch_shutdown() is invoked immediately prior to forcefully disabling 1672 * hardware virtualization on all CPUs via IPI function calls (in preparation 1673 * for shutdown or reboot), e.g. to allow arch code to prepare for disabling 1674 * virtualization while KVM may be actively running vCPUs. 1675 */ 1676 void kvm_arch_shutdown(void); 1677 /* 1678 * kvm_arch_{enable,disable}_virtualization() are called on one CPU, under 1679 * kvm_usage_lock, immediately after/before 0=>1 and 1=>0 transitions of 1680 * kvm_usage_count, i.e. at the beginning of the generic hardware enabling 1681 * sequence, and at the end of the generic hardware disabling sequence. 1682 */ 1683 void kvm_arch_enable_virtualization(void); 1684 void kvm_arch_disable_virtualization(void); 1685 /* 1686 * kvm_arch_{enable,disable}_virtualization_cpu() are called on "every" CPU to 1687 * do the actual twiddling of hardware bits. The hooks are called on all 1688 * online CPUs when KVM enables/disabled virtualization, and on a single CPU 1689 * when that CPU is onlined/offlined (including for Resume/Suspend). 1690 */ 1691 int kvm_arch_enable_virtualization_cpu(void); 1692 void kvm_arch_disable_virtualization_cpu(void); 1693 #endif 1694 bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu); 1695 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu); 1696 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu); 1697 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu); 1698 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu); 1699 bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu); 1700 bool kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu); 1701 void kvm_arch_pre_destroy_vm(struct kvm *kvm); 1702 void kvm_arch_create_vm_debugfs(struct kvm *kvm); 1703 1704 #ifndef __KVM_HAVE_ARCH_VM_ALLOC 1705 /* 1706 * All architectures that want to use vzalloc currently also 1707 * need their own kvm_arch_alloc_vm implementation. 1708 */ 1709 static inline struct kvm *kvm_arch_alloc_vm(void) 1710 { 1711 return kzalloc_obj(struct kvm, GFP_KERNEL_ACCOUNT); 1712 } 1713 #endif 1714 1715 static inline void __kvm_arch_free_vm(struct kvm *kvm) 1716 { 1717 kvfree(kvm); 1718 } 1719 1720 #ifndef __KVM_HAVE_ARCH_VM_FREE 1721 static inline void kvm_arch_free_vm(struct kvm *kvm) 1722 { 1723 __kvm_arch_free_vm(kvm); 1724 } 1725 #endif 1726 1727 #ifndef __KVM_HAVE_ARCH_FLUSH_REMOTE_TLBS 1728 static inline int kvm_arch_flush_remote_tlbs(struct kvm *kvm) 1729 { 1730 return -ENOTSUPP; 1731 } 1732 #else 1733 int kvm_arch_flush_remote_tlbs(struct kvm *kvm); 1734 #endif 1735 1736 #ifndef __KVM_HAVE_ARCH_FLUSH_REMOTE_TLBS_RANGE 1737 static inline int kvm_arch_flush_remote_tlbs_range(struct kvm *kvm, 1738 gfn_t gfn, u64 nr_pages) 1739 { 1740 return -EOPNOTSUPP; 1741 } 1742 #else 1743 int kvm_arch_flush_remote_tlbs_range(struct kvm *kvm, gfn_t gfn, u64 nr_pages); 1744 #endif 1745 1746 #ifdef __KVM_HAVE_ARCH_NONCOHERENT_DMA 1747 void kvm_arch_register_noncoherent_dma(struct kvm *kvm); 1748 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm); 1749 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm); 1750 #else 1751 static inline void kvm_arch_register_noncoherent_dma(struct kvm *kvm) 1752 { 1753 } 1754 1755 static inline void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm) 1756 { 1757 } 1758 1759 static inline bool kvm_arch_has_noncoherent_dma(struct kvm *kvm) 1760 { 1761 return false; 1762 } 1763 #endif 1764 1765 static inline struct rcuwait *kvm_arch_vcpu_get_wait(struct kvm_vcpu *vcpu) 1766 { 1767 #ifdef __KVM_HAVE_ARCH_WQP 1768 return vcpu->arch.waitp; 1769 #else 1770 return &vcpu->wait; 1771 #endif 1772 } 1773 1774 /* 1775 * Wake a vCPU if necessary, but don't do any stats/metadata updates. Returns 1776 * true if the vCPU was blocking and was awakened, false otherwise. 1777 */ 1778 static inline bool __kvm_vcpu_wake_up(struct kvm_vcpu *vcpu) 1779 { 1780 return !!rcuwait_wake_up(kvm_arch_vcpu_get_wait(vcpu)); 1781 } 1782 1783 static inline bool kvm_vcpu_is_blocking(struct kvm_vcpu *vcpu) 1784 { 1785 return rcuwait_active(kvm_arch_vcpu_get_wait(vcpu)); 1786 } 1787 1788 #ifdef __KVM_HAVE_ARCH_INTC_INITIALIZED 1789 /* 1790 * returns true if the virtual interrupt controller is initialized and 1791 * ready to accept virtual IRQ. On some architectures the virtual interrupt 1792 * controller is dynamically instantiated and this is not always true. 1793 */ 1794 bool kvm_arch_intc_initialized(struct kvm *kvm); 1795 #else 1796 static inline bool kvm_arch_intc_initialized(struct kvm *kvm) 1797 { 1798 return true; 1799 } 1800 #endif 1801 1802 #ifdef CONFIG_GUEST_PERF_EVENTS 1803 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu); 1804 1805 void __kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void), 1806 void (*mediated_pmi_handler)(void)); 1807 1808 static inline void kvm_register_perf_callbacks(void) 1809 { 1810 __kvm_register_perf_callbacks(NULL, NULL); 1811 } 1812 1813 void kvm_unregister_perf_callbacks(void); 1814 #else 1815 static inline void kvm_register_perf_callbacks(void) {} 1816 static inline void kvm_unregister_perf_callbacks(void) {} 1817 #endif /* CONFIG_GUEST_PERF_EVENTS */ 1818 1819 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type); 1820 void kvm_arch_destroy_vm(struct kvm *kvm); 1821 1822 int kvm_cpu_has_pending_timer(struct kvm_vcpu *vcpu); 1823 1824 struct kvm_irq_ack_notifier { 1825 struct hlist_node link; 1826 unsigned gsi; 1827 void (*irq_acked)(struct kvm_irq_ack_notifier *kian); 1828 }; 1829 1830 int kvm_irq_map_gsi(struct kvm *kvm, 1831 struct kvm_kernel_irq_routing_entry *entries, int gsi); 1832 int kvm_irq_map_chip_pin(struct kvm *kvm, unsigned irqchip, unsigned pin); 1833 1834 int kvm_set_irq(struct kvm *kvm, int irq_source_id, u32 irq, int level, 1835 bool line_status); 1836 int kvm_set_msi(struct kvm_kernel_irq_routing_entry *irq_entry, struct kvm *kvm, 1837 int irq_source_id, int level, bool line_status); 1838 int kvm_arch_set_irq_inatomic(struct kvm_kernel_irq_routing_entry *e, 1839 struct kvm *kvm, int irq_source_id, 1840 int level, bool line_status); 1841 bool kvm_irq_has_notifier(struct kvm *kvm, unsigned irqchip, unsigned pin); 1842 void kvm_notify_acked_gsi(struct kvm *kvm, int gsi); 1843 void kvm_notify_acked_irq(struct kvm *kvm, unsigned irqchip, unsigned pin); 1844 void kvm_register_irq_ack_notifier(struct kvm *kvm, 1845 struct kvm_irq_ack_notifier *kian); 1846 void kvm_unregister_irq_ack_notifier(struct kvm *kvm, 1847 struct kvm_irq_ack_notifier *kian); 1848 bool kvm_arch_irqfd_allowed(struct kvm *kvm, struct kvm_irqfd *args); 1849 1850 static inline bool is_gfn_in_memslot(const struct kvm_memory_slot *slot, gfn_t gfn) 1851 { 1852 return gfn >= slot->base_gfn && gfn < slot->base_gfn + slot->npages; 1853 } 1854 1855 /* 1856 * Returns a pointer to the memslot if it contains gfn. 1857 * Otherwise returns NULL. 1858 */ 1859 static inline struct kvm_memory_slot * 1860 try_get_memslot(struct kvm_memory_slot *slot, gfn_t gfn) 1861 { 1862 if (!slot) 1863 return NULL; 1864 1865 if (is_gfn_in_memslot(slot, gfn)) 1866 return slot; 1867 else 1868 return NULL; 1869 } 1870 1871 /* 1872 * Returns a pointer to the memslot that contains gfn. Otherwise returns NULL. 1873 * 1874 * With "approx" set returns the memslot also when the address falls 1875 * in a hole. In that case one of the memslots bordering the hole is 1876 * returned. 1877 */ 1878 static inline struct kvm_memory_slot * 1879 search_memslots(struct kvm_memslots *slots, gfn_t gfn, bool approx) 1880 { 1881 struct kvm_memory_slot *slot; 1882 struct rb_node *node; 1883 int idx = slots->node_idx; 1884 1885 slot = NULL; 1886 for (node = slots->gfn_tree.rb_node; node; ) { 1887 slot = container_of(node, struct kvm_memory_slot, gfn_node[idx]); 1888 if (gfn >= slot->base_gfn) { 1889 if (gfn < slot->base_gfn + slot->npages) 1890 return slot; 1891 node = node->rb_right; 1892 } else 1893 node = node->rb_left; 1894 } 1895 1896 return approx ? slot : NULL; 1897 } 1898 1899 static inline struct kvm_memory_slot * 1900 ____gfn_to_memslot(struct kvm_memslots *slots, gfn_t gfn, bool approx) 1901 { 1902 struct kvm_memory_slot *slot; 1903 1904 slot = (struct kvm_memory_slot *)atomic_long_read(&slots->last_used_slot); 1905 slot = try_get_memslot(slot, gfn); 1906 if (slot) 1907 return slot; 1908 1909 slot = search_memslots(slots, gfn, approx); 1910 if (slot) { 1911 atomic_long_set(&slots->last_used_slot, (unsigned long)slot); 1912 return slot; 1913 } 1914 1915 return NULL; 1916 } 1917 1918 /* 1919 * __gfn_to_memslot() and its descendants are here to allow arch code to inline 1920 * the lookups in hot paths. gfn_to_memslot() itself isn't here as an inline 1921 * because that would bloat other code too much. 1922 */ 1923 static inline struct kvm_memory_slot * 1924 __gfn_to_memslot(struct kvm_memslots *slots, gfn_t gfn) 1925 { 1926 return ____gfn_to_memslot(slots, gfn, false); 1927 } 1928 1929 static inline unsigned long 1930 __gfn_to_hva_memslot(const struct kvm_memory_slot *slot, gfn_t gfn) 1931 { 1932 /* 1933 * The index was checked originally in search_memslots. To avoid 1934 * that a malicious guest builds a Spectre gadget out of e.g. page 1935 * table walks, do not let the processor speculate loads outside 1936 * the guest's registered memslots. 1937 */ 1938 unsigned long offset = gfn - slot->base_gfn; 1939 offset = array_index_nospec(offset, slot->npages); 1940 return slot->userspace_addr + offset * PAGE_SIZE; 1941 } 1942 1943 static inline int memslot_id(struct kvm *kvm, gfn_t gfn) 1944 { 1945 return gfn_to_memslot(kvm, gfn)->id; 1946 } 1947 1948 static inline gfn_t 1949 hva_to_gfn_memslot(unsigned long hva, struct kvm_memory_slot *slot) 1950 { 1951 gfn_t gfn_offset = (hva - slot->userspace_addr) >> PAGE_SHIFT; 1952 1953 return slot->base_gfn + gfn_offset; 1954 } 1955 1956 static inline gpa_t gfn_to_gpa(gfn_t gfn) 1957 { 1958 return (gpa_t)gfn << PAGE_SHIFT; 1959 } 1960 1961 static inline gfn_t gpa_to_gfn(gpa_t gpa) 1962 { 1963 return (gfn_t)(gpa >> PAGE_SHIFT); 1964 } 1965 1966 static inline hpa_t pfn_to_hpa(kvm_pfn_t pfn) 1967 { 1968 return (hpa_t)pfn << PAGE_SHIFT; 1969 } 1970 1971 static inline bool kvm_is_gpa_in_memslot(struct kvm *kvm, gpa_t gpa) 1972 { 1973 unsigned long hva = gfn_to_hva(kvm, gpa_to_gfn(gpa)); 1974 1975 return !kvm_is_error_hva(hva); 1976 } 1977 1978 static inline void kvm_gpc_mark_dirty_in_slot(struct gfn_to_pfn_cache *gpc) 1979 { 1980 lockdep_assert_held(&gpc->lock); 1981 1982 if (!gpc->memslot) 1983 return; 1984 1985 mark_page_dirty_in_slot(gpc->kvm, gpc->memslot, gpa_to_gfn(gpc->gpa)); 1986 } 1987 1988 enum kvm_stat_kind { 1989 KVM_STAT_VM, 1990 KVM_STAT_VCPU, 1991 }; 1992 1993 struct kvm_stat_data { 1994 struct kvm *kvm; 1995 const struct kvm_stats_desc *desc; 1996 enum kvm_stat_kind kind; 1997 }; 1998 1999 #define STATS_DESC_COMMON(type, unit, base, exp, sz, bsz) \ 2000 .flags = type | unit | base | \ 2001 BUILD_BUG_ON_ZERO(type & ~KVM_STATS_TYPE_MASK) | \ 2002 BUILD_BUG_ON_ZERO(unit & ~KVM_STATS_UNIT_MASK) | \ 2003 BUILD_BUG_ON_ZERO(base & ~KVM_STATS_BASE_MASK), \ 2004 .exponent = exp, \ 2005 .size = sz, \ 2006 .bucket_size = bsz 2007 2008 #define VM_GENERIC_STATS_DESC(stat, type, unit, base, exp, sz, bsz) \ 2009 { \ 2010 STATS_DESC_COMMON(type, unit, base, exp, sz, bsz), \ 2011 .offset = offsetof(struct kvm_vm_stat, generic.stat), \ 2012 .name = #stat, \ 2013 } 2014 #define VCPU_GENERIC_STATS_DESC(stat, type, unit, base, exp, sz, bsz) \ 2015 { \ 2016 STATS_DESC_COMMON(type, unit, base, exp, sz, bsz), \ 2017 .offset = offsetof(struct kvm_vcpu_stat, generic.stat), \ 2018 .name = #stat, \ 2019 } 2020 #define VM_STATS_DESC(stat, type, unit, base, exp, sz, bsz) \ 2021 { \ 2022 STATS_DESC_COMMON(type, unit, base, exp, sz, bsz), \ 2023 .offset = offsetof(struct kvm_vm_stat, stat), \ 2024 .name = #stat, \ 2025 } 2026 #define VCPU_STATS_DESC(stat, type, unit, base, exp, sz, bsz) \ 2027 { \ 2028 STATS_DESC_COMMON(type, unit, base, exp, sz, bsz), \ 2029 .offset = offsetof(struct kvm_vcpu_stat, stat), \ 2030 .name = #stat, \ 2031 } 2032 /* SCOPE: VM, VM_GENERIC, VCPU, VCPU_GENERIC */ 2033 #define STATS_DESC(SCOPE, stat, type, unit, base, exp, sz, bsz) \ 2034 SCOPE##_STATS_DESC(stat, type, unit, base, exp, sz, bsz) 2035 2036 #define STATS_DESC_CUMULATIVE(SCOPE, name, unit, base, exponent) \ 2037 STATS_DESC(SCOPE, name, KVM_STATS_TYPE_CUMULATIVE, \ 2038 unit, base, exponent, 1, 0) 2039 #define STATS_DESC_INSTANT(SCOPE, name, unit, base, exponent) \ 2040 STATS_DESC(SCOPE, name, KVM_STATS_TYPE_INSTANT, \ 2041 unit, base, exponent, 1, 0) 2042 #define STATS_DESC_PEAK(SCOPE, name, unit, base, exponent) \ 2043 STATS_DESC(SCOPE, name, KVM_STATS_TYPE_PEAK, \ 2044 unit, base, exponent, 1, 0) 2045 #define STATS_DESC_LINEAR_HIST(SCOPE, name, unit, base, exponent, sz, bsz) \ 2046 STATS_DESC(SCOPE, name, KVM_STATS_TYPE_LINEAR_HIST, \ 2047 unit, base, exponent, sz, bsz) 2048 #define STATS_DESC_LOG_HIST(SCOPE, name, unit, base, exponent, sz) \ 2049 STATS_DESC(SCOPE, name, KVM_STATS_TYPE_LOG_HIST, \ 2050 unit, base, exponent, sz, 0) 2051 2052 /* Cumulative counter, read/write */ 2053 #define STATS_DESC_COUNTER(SCOPE, name) \ 2054 STATS_DESC_CUMULATIVE(SCOPE, name, KVM_STATS_UNIT_NONE, \ 2055 KVM_STATS_BASE_POW10, 0) 2056 /* Instantaneous counter, read only */ 2057 #define STATS_DESC_ICOUNTER(SCOPE, name) \ 2058 STATS_DESC_INSTANT(SCOPE, name, KVM_STATS_UNIT_NONE, \ 2059 KVM_STATS_BASE_POW10, 0) 2060 /* Peak counter, read/write */ 2061 #define STATS_DESC_PCOUNTER(SCOPE, name) \ 2062 STATS_DESC_PEAK(SCOPE, name, KVM_STATS_UNIT_NONE, \ 2063 KVM_STATS_BASE_POW10, 0) 2064 2065 /* Instantaneous boolean value, read only */ 2066 #define STATS_DESC_IBOOLEAN(SCOPE, name) \ 2067 STATS_DESC_INSTANT(SCOPE, name, KVM_STATS_UNIT_BOOLEAN, \ 2068 KVM_STATS_BASE_POW10, 0) 2069 /* Peak (sticky) boolean value, read/write */ 2070 #define STATS_DESC_PBOOLEAN(SCOPE, name) \ 2071 STATS_DESC_PEAK(SCOPE, name, KVM_STATS_UNIT_BOOLEAN, \ 2072 KVM_STATS_BASE_POW10, 0) 2073 2074 /* Cumulative time in nanosecond */ 2075 #define STATS_DESC_TIME_NSEC(SCOPE, name) \ 2076 STATS_DESC_CUMULATIVE(SCOPE, name, KVM_STATS_UNIT_SECONDS, \ 2077 KVM_STATS_BASE_POW10, -9) 2078 /* Linear histogram for time in nanosecond */ 2079 #define STATS_DESC_LINHIST_TIME_NSEC(SCOPE, name, sz, bsz) \ 2080 STATS_DESC_LINEAR_HIST(SCOPE, name, KVM_STATS_UNIT_SECONDS, \ 2081 KVM_STATS_BASE_POW10, -9, sz, bsz) 2082 /* Logarithmic histogram for time in nanosecond */ 2083 #define STATS_DESC_LOGHIST_TIME_NSEC(SCOPE, name, sz) \ 2084 STATS_DESC_LOG_HIST(SCOPE, name, KVM_STATS_UNIT_SECONDS, \ 2085 KVM_STATS_BASE_POW10, -9, sz) 2086 2087 #define KVM_GENERIC_VM_STATS() \ 2088 STATS_DESC_COUNTER(VM_GENERIC, remote_tlb_flush), \ 2089 STATS_DESC_COUNTER(VM_GENERIC, remote_tlb_flush_requests) 2090 2091 #define KVM_GENERIC_VCPU_STATS() \ 2092 STATS_DESC_COUNTER(VCPU_GENERIC, halt_successful_poll), \ 2093 STATS_DESC_COUNTER(VCPU_GENERIC, halt_attempted_poll), \ 2094 STATS_DESC_COUNTER(VCPU_GENERIC, halt_poll_invalid), \ 2095 STATS_DESC_COUNTER(VCPU_GENERIC, halt_wakeup), \ 2096 STATS_DESC_TIME_NSEC(VCPU_GENERIC, halt_poll_success_ns), \ 2097 STATS_DESC_TIME_NSEC(VCPU_GENERIC, halt_poll_fail_ns), \ 2098 STATS_DESC_TIME_NSEC(VCPU_GENERIC, halt_wait_ns), \ 2099 STATS_DESC_LOGHIST_TIME_NSEC(VCPU_GENERIC, halt_poll_success_hist, \ 2100 HALT_POLL_HIST_COUNT), \ 2101 STATS_DESC_LOGHIST_TIME_NSEC(VCPU_GENERIC, halt_poll_fail_hist, \ 2102 HALT_POLL_HIST_COUNT), \ 2103 STATS_DESC_LOGHIST_TIME_NSEC(VCPU_GENERIC, halt_wait_hist, \ 2104 HALT_POLL_HIST_COUNT), \ 2105 STATS_DESC_IBOOLEAN(VCPU_GENERIC, blocking) 2106 2107 ssize_t kvm_stats_read(char *id, const struct kvm_stats_header *header, 2108 const struct kvm_stats_desc *desc, 2109 void *stats, size_t size_stats, 2110 char __user *user_buffer, size_t size, loff_t *offset); 2111 2112 /** 2113 * kvm_stats_linear_hist_update() - Update bucket value for linear histogram 2114 * statistics data. 2115 * 2116 * @data: start address of the stats data 2117 * @size: the number of bucket of the stats data 2118 * @value: the new value used to update the linear histogram's bucket 2119 * @bucket_size: the size (width) of a bucket 2120 */ 2121 static inline void kvm_stats_linear_hist_update(u64 *data, size_t size, 2122 u64 value, size_t bucket_size) 2123 { 2124 size_t index = div64_u64(value, bucket_size); 2125 2126 index = min(index, size - 1); 2127 ++data[index]; 2128 } 2129 2130 /** 2131 * kvm_stats_log_hist_update() - Update bucket value for logarithmic histogram 2132 * statistics data. 2133 * 2134 * @data: start address of the stats data 2135 * @size: the number of bucket of the stats data 2136 * @value: the new value used to update the logarithmic histogram's bucket 2137 */ 2138 static inline void kvm_stats_log_hist_update(u64 *data, size_t size, u64 value) 2139 { 2140 size_t index = fls64(value); 2141 2142 index = min(index, size - 1); 2143 ++data[index]; 2144 } 2145 2146 #define KVM_STATS_LINEAR_HIST_UPDATE(array, value, bsize) \ 2147 kvm_stats_linear_hist_update(array, ARRAY_SIZE(array), value, bsize) 2148 #define KVM_STATS_LOG_HIST_UPDATE(array, value) \ 2149 kvm_stats_log_hist_update(array, ARRAY_SIZE(array), value) 2150 2151 2152 extern const struct kvm_stats_header kvm_vm_stats_header; 2153 extern const struct kvm_stats_desc kvm_vm_stats_desc[]; 2154 extern const struct kvm_stats_header kvm_vcpu_stats_header; 2155 extern const struct kvm_stats_desc kvm_vcpu_stats_desc[]; 2156 2157 static inline int mmu_invalidate_retry(struct kvm *kvm, unsigned long mmu_seq) 2158 { 2159 if (unlikely(kvm->mmu_invalidate_in_progress)) 2160 return 1; 2161 /* 2162 * Ensure the read of mmu_invalidate_in_progress happens before 2163 * the read of mmu_invalidate_seq. This interacts with the 2164 * smp_wmb() in mmu_notifier_invalidate_range_end to make sure 2165 * that the caller either sees the old (non-zero) value of 2166 * mmu_invalidate_in_progress or the new (incremented) value of 2167 * mmu_invalidate_seq. 2168 * 2169 * PowerPC Book3s HV KVM calls this under a per-page lock rather 2170 * than under kvm->mmu_lock, for scalability, so can't rely on 2171 * kvm->mmu_lock to keep things ordered. 2172 */ 2173 smp_rmb(); 2174 if (kvm->mmu_invalidate_seq != mmu_seq) 2175 return 1; 2176 return 0; 2177 } 2178 2179 static inline int mmu_invalidate_retry_gfn(struct kvm *kvm, 2180 unsigned long mmu_seq, 2181 gfn_t gfn) 2182 { 2183 lockdep_assert_held(&kvm->mmu_lock); 2184 /* 2185 * If mmu_invalidate_in_progress is non-zero, then the range maintained 2186 * by kvm_mmu_notifier_invalidate_range_start contains all addresses 2187 * that might be being invalidated. Note that it may include some false 2188 * positives, due to shortcuts when handing concurrent invalidations. 2189 */ 2190 if (unlikely(kvm->mmu_invalidate_in_progress)) { 2191 /* 2192 * Dropping mmu_lock after bumping mmu_invalidate_in_progress 2193 * but before updating the range is a KVM bug. 2194 */ 2195 if (WARN_ON_ONCE(kvm->mmu_invalidate_range_start == INVALID_GPA || 2196 kvm->mmu_invalidate_range_end == INVALID_GPA)) 2197 return 1; 2198 2199 if (gfn >= kvm->mmu_invalidate_range_start && 2200 gfn < kvm->mmu_invalidate_range_end) 2201 return 1; 2202 } 2203 2204 if (kvm->mmu_invalidate_seq != mmu_seq) 2205 return 1; 2206 return 0; 2207 } 2208 2209 /* 2210 * This lockless version of the range-based retry check *must* be paired with a 2211 * call to the locked version after acquiring mmu_lock, i.e. this is safe to 2212 * use only as a pre-check to avoid contending mmu_lock. This version *will* 2213 * get false negatives and false positives. 2214 */ 2215 static inline bool mmu_invalidate_retry_gfn_unsafe(struct kvm *kvm, 2216 unsigned long mmu_seq, 2217 gfn_t gfn) 2218 { 2219 /* 2220 * Use READ_ONCE() to ensure the in-progress flag and sequence counter 2221 * are always read from memory, e.g. so that checking for retry in a 2222 * loop won't result in an infinite retry loop. Don't force loads for 2223 * start+end, as the key to avoiding infinite retry loops is observing 2224 * the 1=>0 transition of in-progress, i.e. getting false negatives 2225 * due to stale start+end values is acceptable. 2226 */ 2227 if (unlikely(READ_ONCE(kvm->mmu_invalidate_in_progress)) && 2228 gfn >= kvm->mmu_invalidate_range_start && 2229 gfn < kvm->mmu_invalidate_range_end) 2230 return true; 2231 2232 return READ_ONCE(kvm->mmu_invalidate_seq) != mmu_seq; 2233 } 2234 2235 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING 2236 2237 #define KVM_MAX_IRQ_ROUTES 4096 /* might need extension/rework in the future */ 2238 2239 bool kvm_arch_can_set_irq_routing(struct kvm *kvm); 2240 int kvm_set_irq_routing(struct kvm *kvm, 2241 const struct kvm_irq_routing_entry *entries, 2242 unsigned nr, 2243 unsigned flags); 2244 int kvm_init_irq_routing(struct kvm *kvm); 2245 int kvm_set_routing_entry(struct kvm *kvm, 2246 struct kvm_kernel_irq_routing_entry *e, 2247 const struct kvm_irq_routing_entry *ue); 2248 void kvm_free_irq_routing(struct kvm *kvm); 2249 2250 #else 2251 2252 static inline void kvm_free_irq_routing(struct kvm *kvm) {} 2253 2254 static inline int kvm_init_irq_routing(struct kvm *kvm) 2255 { 2256 return 0; 2257 } 2258 2259 #endif 2260 2261 int kvm_send_userspace_msi(struct kvm *kvm, struct kvm_msi *msi); 2262 2263 void kvm_eventfd_init(struct kvm *kvm); 2264 int kvm_ioeventfd(struct kvm *kvm, struct kvm_ioeventfd *args); 2265 2266 #ifdef CONFIG_HAVE_KVM_IRQCHIP 2267 int kvm_irqfd(struct kvm *kvm, struct kvm_irqfd *args); 2268 void kvm_irqfd_release(struct kvm *kvm); 2269 bool kvm_notify_irqfd_resampler(struct kvm *kvm, 2270 unsigned int irqchip, 2271 unsigned int pin); 2272 void kvm_irq_routing_update(struct kvm *); 2273 #else 2274 static inline int kvm_irqfd(struct kvm *kvm, struct kvm_irqfd *args) 2275 { 2276 return -EINVAL; 2277 } 2278 2279 static inline void kvm_irqfd_release(struct kvm *kvm) {} 2280 2281 static inline bool kvm_notify_irqfd_resampler(struct kvm *kvm, 2282 unsigned int irqchip, 2283 unsigned int pin) 2284 { 2285 return false; 2286 } 2287 #endif /* CONFIG_HAVE_KVM_IRQCHIP */ 2288 2289 void kvm_arch_irq_routing_update(struct kvm *kvm); 2290 2291 static inline void __kvm_make_request(int req, struct kvm_vcpu *vcpu) 2292 { 2293 /* 2294 * Ensure the rest of the request is published to kvm_check_request's 2295 * caller. Paired with the smp_mb__after_atomic in kvm_check_request. 2296 */ 2297 smp_wmb(); 2298 set_bit(req & KVM_REQUEST_MASK, (void *)&vcpu->requests); 2299 } 2300 2301 static __always_inline void kvm_make_request(int req, struct kvm_vcpu *vcpu) 2302 { 2303 /* 2304 * Request that don't require vCPU action should never be logged in 2305 * vcpu->requests. The vCPU won't clear the request, so it will stay 2306 * logged indefinitely and prevent the vCPU from entering the guest. 2307 */ 2308 BUILD_BUG_ON(!__builtin_constant_p(req) || 2309 (req & KVM_REQUEST_NO_ACTION)); 2310 2311 __kvm_make_request(req, vcpu); 2312 } 2313 2314 #ifndef CONFIG_S390 2315 static inline void kvm_make_request_and_kick(int req, struct kvm_vcpu *vcpu) 2316 { 2317 kvm_make_request(req, vcpu); 2318 __kvm_vcpu_kick(vcpu, req & KVM_REQUEST_WAIT); 2319 } 2320 #endif 2321 2322 static inline bool kvm_request_pending(struct kvm_vcpu *vcpu) 2323 { 2324 return READ_ONCE(vcpu->requests); 2325 } 2326 2327 static inline bool kvm_test_request(int req, struct kvm_vcpu *vcpu) 2328 { 2329 return test_bit(req & KVM_REQUEST_MASK, (void *)&vcpu->requests); 2330 } 2331 2332 static __always_inline void kvm_clear_request(int req, struct kvm_vcpu *vcpu) 2333 { 2334 BUILD_BUG_ON(req == KVM_REQ_VM_DEAD); 2335 2336 clear_bit(req & KVM_REQUEST_MASK, (void *)&vcpu->requests); 2337 } 2338 2339 static __always_inline bool kvm_check_request(int req, struct kvm_vcpu *vcpu) 2340 { 2341 /* Once a VM is dead, it needs to stay dead. */ 2342 BUILD_BUG_ON(req == KVM_REQ_VM_DEAD); 2343 2344 if (kvm_test_request(req, vcpu)) { 2345 kvm_clear_request(req, vcpu); 2346 2347 /* 2348 * Ensure the rest of the request is visible to kvm_check_request's 2349 * caller. Paired with the smp_wmb in kvm_make_request. 2350 */ 2351 smp_mb__after_atomic(); 2352 return true; 2353 } else { 2354 return false; 2355 } 2356 } 2357 2358 #ifdef CONFIG_KVM_GENERIC_HARDWARE_ENABLING 2359 extern bool enable_virt_at_load; 2360 #endif 2361 2362 extern unsigned int halt_poll_ns; 2363 extern unsigned int halt_poll_ns_grow; 2364 extern unsigned int halt_poll_ns_grow_start; 2365 extern unsigned int halt_poll_ns_shrink; 2366 2367 struct kvm_device { 2368 const struct kvm_device_ops *ops; 2369 struct kvm *kvm; 2370 void *private; 2371 struct list_head vm_node; 2372 }; 2373 2374 /* create, destroy, and name are mandatory */ 2375 struct kvm_device_ops { 2376 const char *name; 2377 2378 /* 2379 * create is called holding kvm->lock and any operations not suitable 2380 * to do while holding the lock should be deferred to init (see 2381 * below). 2382 */ 2383 int (*create)(struct kvm_device *dev, u32 type); 2384 2385 /* 2386 * init is called after create if create is successful and is called 2387 * outside of holding kvm->lock. 2388 */ 2389 void (*init)(struct kvm_device *dev); 2390 2391 /* 2392 * Destroy is responsible for freeing dev. 2393 * 2394 * Destroy may be called before or after destructors are called 2395 * on emulated I/O regions, depending on whether a reference is 2396 * held by a vcpu or other kvm component that gets destroyed 2397 * after the emulated I/O. 2398 */ 2399 void (*destroy)(struct kvm_device *dev); 2400 2401 /* 2402 * Release is an alternative method to free the device. It is 2403 * called when the device file descriptor is closed. Once 2404 * release is called, the destroy method will not be called 2405 * anymore as the device is removed from the device list of 2406 * the VM. kvm->lock is held. 2407 */ 2408 void (*release)(struct kvm_device *dev); 2409 2410 int (*set_attr)(struct kvm_device *dev, struct kvm_device_attr *attr); 2411 int (*get_attr)(struct kvm_device *dev, struct kvm_device_attr *attr); 2412 int (*has_attr)(struct kvm_device *dev, struct kvm_device_attr *attr); 2413 long (*ioctl)(struct kvm_device *dev, unsigned int ioctl, 2414 unsigned long arg); 2415 int (*mmap)(struct kvm_device *dev, struct vm_area_struct *vma); 2416 }; 2417 2418 struct kvm_device *kvm_device_from_filp(struct file *filp); 2419 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type); 2420 void kvm_unregister_device_ops(u32 type); 2421 2422 extern struct kvm_device_ops kvm_mpic_ops; 2423 extern struct kvm_device_ops kvm_arm_vgic_v2_ops; 2424 extern struct kvm_device_ops kvm_arm_vgic_v3_ops; 2425 extern struct kvm_device_ops kvm_arm_vgic_v5_ops; 2426 2427 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT 2428 2429 static inline void kvm_vcpu_set_in_spin_loop(struct kvm_vcpu *vcpu, bool val) 2430 { 2431 vcpu->spin_loop.in_spin_loop = val; 2432 } 2433 static inline void kvm_vcpu_set_dy_eligible(struct kvm_vcpu *vcpu, bool val) 2434 { 2435 vcpu->spin_loop.dy_eligible = val; 2436 } 2437 2438 #else /* !CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT */ 2439 2440 static inline void kvm_vcpu_set_in_spin_loop(struct kvm_vcpu *vcpu, bool val) 2441 { 2442 } 2443 2444 static inline void kvm_vcpu_set_dy_eligible(struct kvm_vcpu *vcpu, bool val) 2445 { 2446 } 2447 #endif /* CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT */ 2448 2449 static inline bool kvm_is_visible_memslot(struct kvm_memory_slot *memslot) 2450 { 2451 return (memslot && memslot->id < KVM_USER_MEM_SLOTS && 2452 !(memslot->flags & KVM_MEMSLOT_INVALID)); 2453 } 2454 2455 struct kvm_vcpu *kvm_get_running_vcpu(void); 2456 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void); 2457 2458 #if IS_ENABLED(CONFIG_HAVE_KVM_IRQ_BYPASS) 2459 struct kvm_kernel_irqfd; 2460 2461 bool kvm_arch_has_irq_bypass(void); 2462 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *, 2463 struct irq_bypass_producer *); 2464 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *, 2465 struct irq_bypass_producer *); 2466 void kvm_arch_irq_bypass_stop(struct irq_bypass_consumer *); 2467 void kvm_arch_irq_bypass_start(struct irq_bypass_consumer *); 2468 void kvm_arch_update_irqfd_routing(struct kvm_kernel_irqfd *irqfd, 2469 struct kvm_kernel_irq_routing_entry *old, 2470 struct kvm_kernel_irq_routing_entry *new); 2471 #endif /* CONFIG_HAVE_KVM_IRQ_BYPASS */ 2472 2473 #ifdef __KVM_HAVE_INVALID_WAKEUPS 2474 /* If we wakeup during the poll time, was it a sucessful poll? */ 2475 static inline bool vcpu_valid_wakeup(struct kvm_vcpu *vcpu) 2476 { 2477 return vcpu->valid_wakeup; 2478 } 2479 2480 #else 2481 static inline bool vcpu_valid_wakeup(struct kvm_vcpu *vcpu) 2482 { 2483 return true; 2484 } 2485 #endif /* __KVM_HAVE_INVALID_WAKEUPS */ 2486 2487 #ifdef __KVM_HAVE_NO_POLL 2488 /* Callback that tells if we must not poll */ 2489 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu); 2490 #else 2491 static inline bool kvm_arch_no_poll(struct kvm_vcpu *vcpu) 2492 { 2493 return false; 2494 } 2495 #endif /* __KVM_HAVE_NO_POLL */ 2496 2497 void kvm_arch_guest_memory_reclaimed(struct kvm *kvm); 2498 2499 #ifdef __KVM_HAVE_VCPU_RUN_PID_CHANGE 2500 int kvm_arch_vcpu_run_pid_change(struct kvm_vcpu *vcpu); 2501 #else 2502 static inline int kvm_arch_vcpu_run_pid_change(struct kvm_vcpu *vcpu) 2503 { 2504 return 0; 2505 } 2506 #endif /* __KVM_HAVE_VCPU_RUN_PID_CHANGE */ 2507 2508 #ifdef CONFIG_VIRT_XFER_TO_GUEST_WORK 2509 static inline void kvm_handle_signal_exit(struct kvm_vcpu *vcpu) 2510 { 2511 vcpu->run->exit_reason = KVM_EXIT_INTR; 2512 vcpu->stat.signal_exits++; 2513 } 2514 2515 static inline int kvm_xfer_to_guest_mode_handle_work(struct kvm_vcpu *vcpu) 2516 { 2517 int r = xfer_to_guest_mode_handle_work(); 2518 2519 if (r) { 2520 WARN_ON_ONCE(r != -EINTR); 2521 kvm_handle_signal_exit(vcpu); 2522 } 2523 return r; 2524 } 2525 #endif /* CONFIG_VIRT_XFER_TO_GUEST_WORK */ 2526 2527 /* 2528 * If more than one page is being (un)accounted, @virt must be the address of 2529 * the first page of a block of pages what were allocated together (i.e 2530 * accounted together). 2531 * 2532 * kvm_account_pgtable_pages() is thread-safe because mod_lruvec_page_state() 2533 * is thread-safe. 2534 */ 2535 static inline void kvm_account_pgtable_pages(void *virt, int nr) 2536 { 2537 mod_lruvec_page_state(virt_to_page(virt), NR_SECONDARY_PAGETABLE, nr); 2538 } 2539 2540 /* 2541 * This defines how many reserved entries we want to keep before we 2542 * kick the vcpu to the userspace to avoid dirty ring full. This 2543 * value can be tuned to higher if e.g. PML is enabled on the host. 2544 */ 2545 #define KVM_DIRTY_RING_RSVD_ENTRIES 64 2546 2547 /* Max number of entries allowed for each kvm dirty ring */ 2548 #define KVM_DIRTY_RING_MAX_ENTRIES 65536 2549 2550 static inline void kvm_prepare_memory_fault_exit(struct kvm_vcpu *vcpu, 2551 gpa_t gpa, gpa_t size, 2552 bool is_write, bool is_exec, 2553 bool is_private) 2554 { 2555 vcpu->run->exit_reason = KVM_EXIT_MEMORY_FAULT; 2556 vcpu->run->memory_fault.gpa = gpa; 2557 vcpu->run->memory_fault.size = size; 2558 2559 /* RWX flags are not (yet) defined or communicated to userspace. */ 2560 vcpu->run->memory_fault.flags = 0; 2561 if (is_private) 2562 vcpu->run->memory_fault.flags |= KVM_MEMORY_EXIT_FLAG_PRIVATE; 2563 } 2564 2565 static inline bool kvm_memslot_is_gmem_only(const struct kvm_memory_slot *slot) 2566 { 2567 if (!IS_ENABLED(CONFIG_KVM_GUEST_MEMFD)) 2568 return false; 2569 2570 return slot->flags & KVM_MEMSLOT_GMEM_ONLY; 2571 } 2572 2573 #ifdef CONFIG_KVM_VM_MEMORY_ATTRIBUTES 2574 static inline unsigned long kvm_get_vm_memory_attributes(struct kvm *kvm, gfn_t gfn) 2575 { 2576 return xa_to_value(xa_load(&kvm->mem_attr_array, gfn)); 2577 } 2578 2579 bool kvm_range_has_vm_memory_attributes(struct kvm *kvm, gfn_t start, gfn_t end, 2580 unsigned long mask, unsigned long attrs); 2581 bool kvm_arch_pre_set_vm_memory_attributes(struct kvm *kvm, 2582 struct kvm_gfn_range *range); 2583 bool kvm_arch_post_set_vm_memory_attributes(struct kvm *kvm, 2584 struct kvm_gfn_range *range); 2585 #endif /* CONFIG_KVM_VM_MEMORY_ATTRIBUTES */ 2586 2587 #ifdef CONFIG_KVM_PRIVATE_MEMATTR_VM 2588 extern bool gmem_in_place_conversion; 2589 typedef bool (kvm_is_private_gfn_t)(struct kvm *kvm, gfn_t gfn); 2590 DECLARE_STATIC_CALL(__kvm_is_private_gfn, kvm_is_private_gfn_t); 2591 2592 static inline bool kvm_is_private_gfn(struct kvm *kvm, gfn_t gfn) 2593 { 2594 return static_call(__kvm_is_private_gfn)(kvm, gfn); 2595 } 2596 2597 #elif defined kvm_arch_has_private_mem 2598 #define gmem_in_place_conversion true 2599 #define kvm_is_private_gfn kvm_gmem_is_private_gfn 2600 2601 #else 2602 #define gmem_in_place_conversion false 2603 2604 static inline bool kvm_arch_has_private_mem(struct kvm *kvm) 2605 { 2606 return false; 2607 } 2608 2609 static inline bool kvm_is_private_gfn(struct kvm *kvm, gfn_t gfn) 2610 { 2611 return false; 2612 } 2613 #endif /* kvm_arch_has_private_mem */ 2614 2615 #ifdef CONFIG_KVM_GUEST_MEMFD 2616 bool kvm_gmem_is_private_gfn(struct kvm *kvm, gfn_t gfn); 2617 bool kvm_arch_supports_gmem_init_shared(struct kvm *kvm); 2618 2619 static inline u64 kvm_gmem_get_supported_flags(struct kvm *kvm) 2620 { 2621 u64 flags = GUEST_MEMFD_FLAG_MMAP; 2622 2623 if (!kvm || kvm_arch_supports_gmem_init_shared(kvm)) 2624 flags |= GUEST_MEMFD_FLAG_INIT_SHARED; 2625 2626 return flags; 2627 } 2628 2629 int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, 2630 gfn_t gfn, kvm_pfn_t *pfn, int *max_order); 2631 #else 2632 static inline int kvm_gmem_get_pfn(struct kvm *kvm, 2633 struct kvm_memory_slot *slot, gfn_t gfn, 2634 kvm_pfn_t *pfn, int *max_order) 2635 { 2636 KVM_BUG_ON(1, kvm); 2637 return -EIO; 2638 } 2639 #endif /* CONFIG_KVM_GUEST_MEMFD */ 2640 2641 int kvm_arch_gmem_make_private(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, 2642 kvm_pfn_t nr_pages); 2643 void kvm_arch_gmem_make_shared(kvm_pfn_t pfn, kvm_pfn_t nr_pages); 2644 #ifndef CONFIG_HAVE_KVM_ARCH_GMEM_CONVERT 2645 #define kvm_arch_has_gmem_convert() false 2646 #endif 2647 2648 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_POPULATE 2649 /** 2650 * kvm_gmem_populate() - Populate/prepare a GPA range with guest data 2651 * 2652 * @kvm: KVM instance 2653 * @gfn: starting GFN to be populated 2654 * @src: userspace-provided buffer containing data to copy into GFN range 2655 * (passed to @post_populate, and incremented on each iteration 2656 * if not NULL). Must be page-aligned. 2657 * @npages: number of pages to copy from userspace-buffer 2658 * @post_populate: callback to issue for each gmem page that backs the GPA 2659 * range 2660 * @opaque: opaque data to pass to @post_populate callback 2661 * 2662 * This is primarily intended for cases where a gmem-backed GPA range needs 2663 * to be initialized with userspace-provided data prior to being mapped into 2664 * the guest as a private page. This should be called with the slots->lock 2665 * held so that caller-enforced invariants regarding the expected memory 2666 * attributes of the GPA range do not race with KVM_SET_MEMORY_ATTRIBUTES. 2667 * 2668 * Returns the number of pages that were populated. 2669 */ 2670 typedef int (*kvm_gmem_populate_cb)(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, 2671 struct page *page, void *opaque); 2672 2673 long kvm_gmem_populate(struct kvm *kvm, gfn_t start_gfn, void __user *src, 2674 long npages, bool may_writeback_src, 2675 kvm_gmem_populate_cb post_populate, void *opaque); 2676 #endif 2677 2678 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_RECLAIM 2679 void kvm_arch_gmem_reclaim(kvm_pfn_t pfn, kvm_pfn_t nr_pages); 2680 #endif 2681 2682 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE 2683 void kvm_arch_gmem_invalidate_range(struct kvm *kvm, struct kvm_gfn_range *range); 2684 #endif 2685 2686 #ifdef CONFIG_KVM_GENERIC_PRE_FAULT_MEMORY 2687 int kvm_arch_pre_fault_allowed(struct kvm_vcpu *vcpu); 2688 long kvm_arch_vcpu_pre_fault_memory(struct kvm_vcpu *vcpu, 2689 struct kvm_pre_fault_memory *range); 2690 #endif 2691 2692 #endif 2693