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 static __always_inline __must_check bool kvm_can_do_uaccess(struct kvm *kvm) 1357 { 1358 return current->mm == kvm->mm; 1359 } 1360 1361 #define BUILD_KVM_COPY_USER_WRAPPER(fn, to_user, from_user) \ 1362 static __always_inline __must_check unsigned long kvm_##fn(struct kvm *kvm, \ 1363 void to_user *to, \ 1364 const void from_user *from, \ 1365 unsigned long n) \ 1366 { \ 1367 if (!kvm_can_do_uaccess(kvm)) \ 1368 return n; \ 1369 \ 1370 return __##fn(to, from, n); \ 1371 } 1372 BUILD_KVM_COPY_USER_WRAPPER(copy_from_user, , __user) 1373 BUILD_KVM_COPY_USER_WRAPPER(copy_from_user_inatomic, , __user) 1374 BUILD_KVM_COPY_USER_WRAPPER(copy_to_user, __user, ) 1375 BUILD_KVM_COPY_USER_WRAPPER(copy_to_user_inatomic, __user, ) 1376 1377 #define __kvm_get_guest(kvm, gfn, offset, v) \ 1378 ({ \ 1379 unsigned long __addr = gfn_to_hva(kvm, gfn); \ 1380 typeof(v) __user *__uaddr = (typeof(__uaddr))(__addr + offset); \ 1381 int __ret = -EFAULT; \ 1382 \ 1383 if (!kvm_is_error_hva(__addr) && kvm_can_do_uaccess(kvm)) \ 1384 __ret = get_user(v, __uaddr); \ 1385 __ret; \ 1386 }) 1387 1388 #define kvm_get_guest(kvm, gpa, v) \ 1389 ({ \ 1390 gpa_t __gpa = gpa; \ 1391 struct kvm *__kvm = kvm; \ 1392 \ 1393 __kvm_get_guest(__kvm, __gpa >> PAGE_SHIFT, \ 1394 offset_in_page(__gpa), v); \ 1395 }) 1396 1397 #define __kvm_put_guest(kvm, gfn, offset, v) \ 1398 ({ \ 1399 unsigned long __addr = gfn_to_hva(kvm, gfn); \ 1400 typeof(v) __user *__uaddr = (typeof(__uaddr))(__addr + offset); \ 1401 int __ret = -EFAULT; \ 1402 \ 1403 if (!kvm_is_error_hva(__addr) && kvm_can_do_uaccess(kvm)) \ 1404 __ret = put_user(v, __uaddr); \ 1405 if (!__ret) \ 1406 mark_page_dirty(kvm, gfn); \ 1407 __ret; \ 1408 }) 1409 1410 #define kvm_put_guest(kvm, gpa, v) \ 1411 ({ \ 1412 gpa_t __gpa = gpa; \ 1413 struct kvm *__kvm = kvm; \ 1414 \ 1415 __kvm_put_guest(__kvm, __gpa >> PAGE_SHIFT, \ 1416 offset_in_page(__gpa), v); \ 1417 }) 1418 1419 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len); 1420 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn); 1421 bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn); 1422 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn); 1423 void mark_page_dirty_in_slot(struct kvm *kvm, const struct kvm_memory_slot *memslot, gfn_t gfn); 1424 void mark_page_dirty(struct kvm *kvm, gfn_t gfn); 1425 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn); 1426 1427 int __kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map, 1428 bool writable); 1429 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map); 1430 1431 static inline int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, 1432 struct kvm_host_map *map) 1433 { 1434 return __kvm_vcpu_map(vcpu, gfn, map, true); 1435 } 1436 1437 static inline int kvm_vcpu_map_readonly(struct kvm_vcpu *vcpu, gfn_t gfn, 1438 struct kvm_host_map *map) 1439 { 1440 return __kvm_vcpu_map(vcpu, gfn, map, false); 1441 } 1442 1443 static inline void kvm_vcpu_map_mark_dirty(struct kvm_vcpu *vcpu, 1444 struct kvm_host_map *map) 1445 { 1446 if (kvm_vcpu_mapped(map)) 1447 kvm_vcpu_mark_page_dirty(vcpu, map->gfn); 1448 } 1449 1450 typedef struct { 1451 struct kvm_vcpu *vcpu; 1452 struct kvm_host_map map; 1453 int ret; 1454 } kvm_vcpu_local_map_t; 1455 1456 #define DEFINE_VCPU_MAP_CLASS(ro) \ 1457 DEFINE_CLASS(kvm_vcpu_map_local##ro, kvm_vcpu_local_map_t, \ 1458 if (!_T.ret) kvm_vcpu_unmap(_T.vcpu, &_T.map), \ 1459 ({ \ 1460 kvm_vcpu_local_map_t m = { .vcpu = vcpu }; \ 1461 \ 1462 m.ret = kvm_vcpu_map##ro(vcpu, gfn, &m.map); \ 1463 \ 1464 m; \ 1465 }), struct kvm_vcpu *vcpu, gfn_t gfn); 1466 DEFINE_VCPU_MAP_CLASS(); 1467 DEFINE_VCPU_MAP_CLASS(_readonly); 1468 1469 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn); 1470 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable); 1471 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data, int offset, 1472 int len); 1473 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, 1474 unsigned long len); 1475 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, 1476 unsigned long len); 1477 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, const void *data, 1478 int offset, int len); 1479 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data, 1480 unsigned long len); 1481 1482 /** 1483 * kvm_gpc_init - initialize gfn_to_pfn_cache. 1484 * 1485 * @gpc: struct gfn_to_pfn_cache object. 1486 * @kvm: pointer to kvm instance. 1487 * 1488 * This sets up a gfn_to_pfn_cache by initializing locks and assigning the 1489 * immutable attributes. Note, the cache must be zero-allocated (or zeroed by 1490 * the caller before init). 1491 */ 1492 void kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm); 1493 1494 /** 1495 * kvm_gpc_activate - prepare a cached kernel mapping and HPA for a given guest 1496 * physical address. 1497 * 1498 * @gpc: struct gfn_to_pfn_cache object. 1499 * @gpa: guest physical address to map. 1500 * @len: sanity check; the range being access must fit a single page. 1501 * 1502 * @return: 0 for success. 1503 * -EINVAL for a mapping which would cross a page boundary. 1504 * -EFAULT for an untranslatable guest physical address. 1505 * 1506 * This primes a gfn_to_pfn_cache and links it into the @gpc->kvm's list for 1507 * invalidations to be processed. Callers are required to use kvm_gpc_check() 1508 * to ensure that the cache is valid before accessing the target page. 1509 */ 1510 int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len); 1511 1512 /** 1513 * kvm_gpc_activate_hva - prepare a cached kernel mapping and HPA for a given HVA. 1514 * 1515 * @gpc: struct gfn_to_pfn_cache object. 1516 * @hva: userspace virtual address to map. 1517 * @len: sanity check; the range being access must fit a single page. 1518 * 1519 * @return: 0 for success. 1520 * -EINVAL for a mapping which would cross a page boundary. 1521 * -EFAULT for an untranslatable guest physical address. 1522 * 1523 * The semantics of this function are the same as those of kvm_gpc_activate(). It 1524 * merely bypasses a layer of address translation. 1525 */ 1526 int kvm_gpc_activate_hva(struct gfn_to_pfn_cache *gpc, unsigned long hva, unsigned long len); 1527 1528 /** 1529 * kvm_gpc_check - check validity of a gfn_to_pfn_cache. 1530 * 1531 * @gpc: struct gfn_to_pfn_cache object. 1532 * @len: sanity check; the range being access must fit a single page. 1533 * 1534 * @return: %true if the cache is still valid and the address matches. 1535 * %false if the cache is not valid. 1536 * 1537 * Callers outside IN_GUEST_MODE context should hold a read lock on @gpc->lock 1538 * while calling this function, and then continue to hold the lock until the 1539 * access is complete. 1540 * 1541 * Callers in IN_GUEST_MODE may do so without locking, although they should 1542 * still hold a read lock on kvm->scru for the memslot checks. 1543 */ 1544 bool kvm_gpc_check(struct gfn_to_pfn_cache *gpc, unsigned long len); 1545 1546 /** 1547 * kvm_gpc_refresh - update a previously initialized cache. 1548 * 1549 * @gpc: struct gfn_to_pfn_cache object. 1550 * @len: sanity check; the range being access must fit a single page. 1551 * 1552 * @return: 0 for success. 1553 * -EINVAL for a mapping which would cross a page boundary. 1554 * -EFAULT for an untranslatable guest physical address. 1555 * 1556 * This will attempt to refresh a gfn_to_pfn_cache. Note that a successful 1557 * return from this function does not mean the page can be immediately 1558 * accessed because it may have raced with an invalidation. Callers must 1559 * still lock and check the cache status, as this function does not return 1560 * with the lock still held to permit access. 1561 */ 1562 int kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, unsigned long len); 1563 1564 /** 1565 * kvm_gpc_deactivate - deactivate and unlink a gfn_to_pfn_cache. 1566 * 1567 * @gpc: struct gfn_to_pfn_cache object. 1568 * 1569 * This removes a cache from the VM's list to be processed on MMU notifier 1570 * invocation. 1571 */ 1572 void kvm_gpc_deactivate(struct gfn_to_pfn_cache *gpc); 1573 1574 static inline bool kvm_gpc_is_gpa_active(struct gfn_to_pfn_cache *gpc) 1575 { 1576 return gpc->active && !kvm_is_error_gpa(gpc->gpa); 1577 } 1578 1579 static inline bool kvm_gpc_is_hva_active(struct gfn_to_pfn_cache *gpc) 1580 { 1581 return gpc->active && kvm_is_error_gpa(gpc->gpa); 1582 } 1583 1584 void kvm_sigset_activate(struct kvm_vcpu *vcpu); 1585 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu); 1586 1587 void kvm_vcpu_halt(struct kvm_vcpu *vcpu); 1588 bool kvm_vcpu_block(struct kvm_vcpu *vcpu); 1589 void kvm_arch_vcpu_blocking(struct kvm_vcpu *vcpu); 1590 void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu); 1591 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu); 1592 1593 #ifndef CONFIG_S390 1594 void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, int request, bool force); 1595 1596 static inline void kvm_vcpu_kick(struct kvm_vcpu *vcpu) 1597 { 1598 __kvm_vcpu_kick(vcpu, 0, false); 1599 } 1600 #endif 1601 1602 int kvm_vcpu_yield_to(struct kvm_vcpu *target); 1603 void kvm_vcpu_on_spin(struct kvm_vcpu *vcpu, bool yield_to_kernel_mode); 1604 1605 void kvm_flush_remote_tlbs(struct kvm *kvm); 1606 void kvm_flush_remote_tlbs_range(struct kvm *kvm, gfn_t gfn, u64 nr_pages); 1607 void kvm_flush_remote_tlbs_memslot(struct kvm *kvm, 1608 const struct kvm_memory_slot *memslot); 1609 1610 #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE 1611 int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min); 1612 int __kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int capacity, int min); 1613 int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc); 1614 void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc); 1615 void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc); 1616 #endif 1617 1618 void kvm_mmu_invalidate_start(struct kvm *kvm); 1619 void kvm_mmu_invalidate_range_add(struct kvm *kvm, gfn_t start, gfn_t end); 1620 void kvm_mmu_invalidate_end(struct kvm *kvm); 1621 bool kvm_mmu_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range); 1622 1623 long kvm_arch_dev_ioctl(struct file *filp, 1624 unsigned int ioctl, unsigned long arg); 1625 long kvm_arch_vcpu_ioctl(struct file *filp, 1626 unsigned int ioctl, unsigned long arg); 1627 long kvm_arch_vcpu_unlocked_ioctl(struct file *filp, 1628 unsigned int ioctl, unsigned long arg); 1629 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf); 1630 1631 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext); 1632 1633 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm, 1634 struct kvm_memory_slot *slot, 1635 gfn_t gfn_offset, 1636 unsigned long mask); 1637 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot); 1638 1639 #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT 1640 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log); 1641 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log, 1642 int *is_dirty, struct kvm_memory_slot **memslot); 1643 #endif 1644 1645 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_level, 1646 bool line_status); 1647 int kvm_vm_ioctl_enable_cap(struct kvm *kvm, 1648 struct kvm_enable_cap *cap); 1649 int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg); 1650 long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl, 1651 unsigned long arg); 1652 1653 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu); 1654 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu); 1655 1656 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu, 1657 struct kvm_translation *tr); 1658 1659 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs); 1660 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs); 1661 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu, 1662 struct kvm_sregs *sregs); 1663 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu, 1664 struct kvm_sregs *sregs); 1665 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu, 1666 struct kvm_mp_state *mp_state); 1667 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu, 1668 struct kvm_mp_state *mp_state); 1669 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu, 1670 struct kvm_guest_debug *dbg); 1671 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu); 1672 1673 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu); 1674 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu); 1675 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id); 1676 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu); 1677 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu); 1678 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu); 1679 1680 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER 1681 int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state); 1682 #endif 1683 1684 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS 1685 void kvm_arch_create_vcpu_debugfs(struct kvm_vcpu *vcpu, struct dentry *debugfs_dentry); 1686 #else 1687 static inline void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu) {} 1688 #endif 1689 1690 #ifdef CONFIG_KVM_GENERIC_HARDWARE_ENABLING 1691 /* 1692 * kvm_arch_shutdown() is invoked immediately prior to forcefully disabling 1693 * hardware virtualization on all CPUs via IPI function calls (in preparation 1694 * for shutdown or reboot), e.g. to allow arch code to prepare for disabling 1695 * virtualization while KVM may be actively running vCPUs. 1696 */ 1697 void kvm_arch_shutdown(void); 1698 /* 1699 * kvm_arch_{enable,disable}_virtualization() are called on one CPU, under 1700 * kvm_usage_lock, immediately after/before 0=>1 and 1=>0 transitions of 1701 * kvm_usage_count, i.e. at the beginning of the generic hardware enabling 1702 * sequence, and at the end of the generic hardware disabling sequence. 1703 */ 1704 void kvm_arch_enable_virtualization(void); 1705 void kvm_arch_disable_virtualization(void); 1706 /* 1707 * kvm_arch_{enable,disable}_virtualization_cpu() are called on "every" CPU to 1708 * do the actual twiddling of hardware bits. The hooks are called on all 1709 * online CPUs when KVM enables/disabled virtualization, and on a single CPU 1710 * when that CPU is onlined/offlined (including for Resume/Suspend). 1711 */ 1712 int kvm_arch_enable_virtualization_cpu(void); 1713 void kvm_arch_disable_virtualization_cpu(void); 1714 #endif 1715 bool kvm_vcpu_has_events(struct kvm_vcpu *vcpu); 1716 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu); 1717 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu); 1718 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu); 1719 bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu); 1720 bool kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu); 1721 void kvm_arch_pre_destroy_vm(struct kvm *kvm); 1722 void kvm_arch_create_vm_debugfs(struct kvm *kvm); 1723 1724 #ifndef __KVM_HAVE_ARCH_VM_ALLOC 1725 /* 1726 * All architectures that want to use vzalloc currently also 1727 * need their own kvm_arch_alloc_vm implementation. 1728 */ 1729 static inline struct kvm *kvm_arch_alloc_vm(void) 1730 { 1731 return kzalloc_obj(struct kvm, GFP_KERNEL_ACCOUNT); 1732 } 1733 #endif 1734 1735 static inline void __kvm_arch_free_vm(struct kvm *kvm) 1736 { 1737 kvfree(kvm); 1738 } 1739 1740 #ifndef __KVM_HAVE_ARCH_VM_FREE 1741 static inline void kvm_arch_free_vm(struct kvm *kvm) 1742 { 1743 __kvm_arch_free_vm(kvm); 1744 } 1745 #endif 1746 1747 #ifndef __KVM_HAVE_ARCH_FLUSH_REMOTE_TLBS 1748 static inline int kvm_arch_flush_remote_tlbs(struct kvm *kvm) 1749 { 1750 return -ENOTSUPP; 1751 } 1752 #else 1753 int kvm_arch_flush_remote_tlbs(struct kvm *kvm); 1754 #endif 1755 1756 #ifndef __KVM_HAVE_ARCH_FLUSH_REMOTE_TLBS_RANGE 1757 static inline int kvm_arch_flush_remote_tlbs_range(struct kvm *kvm, 1758 gfn_t gfn, u64 nr_pages) 1759 { 1760 return -EOPNOTSUPP; 1761 } 1762 #else 1763 int kvm_arch_flush_remote_tlbs_range(struct kvm *kvm, gfn_t gfn, u64 nr_pages); 1764 #endif 1765 1766 #ifdef __KVM_HAVE_ARCH_NONCOHERENT_DMA 1767 void kvm_arch_register_noncoherent_dma(struct kvm *kvm); 1768 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm); 1769 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm); 1770 #else 1771 static inline void kvm_arch_register_noncoherent_dma(struct kvm *kvm) 1772 { 1773 } 1774 1775 static inline void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm) 1776 { 1777 } 1778 1779 static inline bool kvm_arch_has_noncoherent_dma(struct kvm *kvm) 1780 { 1781 return false; 1782 } 1783 #endif 1784 1785 static inline struct rcuwait *kvm_arch_vcpu_get_wait(struct kvm_vcpu *vcpu) 1786 { 1787 #ifdef __KVM_HAVE_ARCH_WQP 1788 return vcpu->arch.waitp; 1789 #else 1790 return &vcpu->wait; 1791 #endif 1792 } 1793 1794 /* 1795 * Wake a vCPU if necessary, but don't do any stats/metadata updates. Returns 1796 * true if the vCPU was blocking and was awakened, false otherwise. 1797 */ 1798 static inline bool __kvm_vcpu_wake_up(struct kvm_vcpu *vcpu) 1799 { 1800 return !!rcuwait_wake_up(kvm_arch_vcpu_get_wait(vcpu)); 1801 } 1802 1803 static inline bool kvm_vcpu_is_blocking(struct kvm_vcpu *vcpu) 1804 { 1805 return rcuwait_active(kvm_arch_vcpu_get_wait(vcpu)); 1806 } 1807 1808 #ifdef __KVM_HAVE_ARCH_INTC_INITIALIZED 1809 /* 1810 * returns true if the virtual interrupt controller is initialized and 1811 * ready to accept virtual IRQ. On some architectures the virtual interrupt 1812 * controller is dynamically instantiated and this is not always true. 1813 */ 1814 bool kvm_arch_intc_initialized(struct kvm *kvm); 1815 #else 1816 static inline bool kvm_arch_intc_initialized(struct kvm *kvm) 1817 { 1818 return true; 1819 } 1820 #endif 1821 1822 #ifdef CONFIG_GUEST_PERF_EVENTS 1823 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu); 1824 1825 void __kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void), 1826 void (*mediated_pmi_handler)(void)); 1827 1828 static inline void kvm_register_perf_callbacks(void) 1829 { 1830 __kvm_register_perf_callbacks(NULL, NULL); 1831 } 1832 1833 void kvm_unregister_perf_callbacks(void); 1834 #else 1835 static inline void kvm_register_perf_callbacks(void) {} 1836 static inline void kvm_unregister_perf_callbacks(void) {} 1837 #endif /* CONFIG_GUEST_PERF_EVENTS */ 1838 1839 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type); 1840 void kvm_arch_destroy_vm(struct kvm *kvm); 1841 1842 int kvm_cpu_has_pending_timer(struct kvm_vcpu *vcpu); 1843 1844 struct kvm_irq_ack_notifier { 1845 struct hlist_node link; 1846 unsigned gsi; 1847 void (*irq_acked)(struct kvm_irq_ack_notifier *kian); 1848 }; 1849 1850 int kvm_irq_map_gsi(struct kvm *kvm, 1851 struct kvm_kernel_irq_routing_entry *entries, int gsi); 1852 int kvm_irq_map_chip_pin(struct kvm *kvm, unsigned irqchip, unsigned pin); 1853 1854 int kvm_set_irq(struct kvm *kvm, int irq_source_id, u32 irq, int level, 1855 bool line_status); 1856 int kvm_set_msi(struct kvm_kernel_irq_routing_entry *irq_entry, struct kvm *kvm, 1857 int irq_source_id, int level, bool line_status); 1858 int kvm_arch_set_irq_inatomic(struct kvm_kernel_irq_routing_entry *e, 1859 struct kvm *kvm, int irq_source_id, 1860 int level, bool line_status); 1861 bool kvm_irq_has_notifier(struct kvm *kvm, unsigned irqchip, unsigned pin); 1862 void kvm_notify_acked_gsi(struct kvm *kvm, int gsi); 1863 void kvm_notify_acked_irq(struct kvm *kvm, unsigned irqchip, unsigned pin); 1864 void kvm_register_irq_ack_notifier(struct kvm *kvm, 1865 struct kvm_irq_ack_notifier *kian); 1866 void kvm_unregister_irq_ack_notifier(struct kvm *kvm, 1867 struct kvm_irq_ack_notifier *kian); 1868 bool kvm_arch_irqfd_allowed(struct kvm *kvm, struct kvm_irqfd *args); 1869 1870 static inline bool is_gfn_in_memslot(const struct kvm_memory_slot *slot, gfn_t gfn) 1871 { 1872 return gfn >= slot->base_gfn && gfn < slot->base_gfn + slot->npages; 1873 } 1874 1875 /* 1876 * Returns a pointer to the memslot if it contains gfn. 1877 * Otherwise returns NULL. 1878 */ 1879 static inline struct kvm_memory_slot * 1880 try_get_memslot(struct kvm_memory_slot *slot, gfn_t gfn) 1881 { 1882 if (!slot) 1883 return NULL; 1884 1885 if (is_gfn_in_memslot(slot, gfn)) 1886 return slot; 1887 else 1888 return NULL; 1889 } 1890 1891 /* 1892 * Returns a pointer to the memslot that contains gfn. Otherwise returns NULL. 1893 * 1894 * With "approx" set returns the memslot also when the address falls 1895 * in a hole. In that case one of the memslots bordering the hole is 1896 * returned. 1897 */ 1898 static inline struct kvm_memory_slot * 1899 search_memslots(struct kvm_memslots *slots, gfn_t gfn, bool approx) 1900 { 1901 struct kvm_memory_slot *slot; 1902 struct rb_node *node; 1903 int idx = slots->node_idx; 1904 1905 slot = NULL; 1906 for (node = slots->gfn_tree.rb_node; node; ) { 1907 slot = container_of(node, struct kvm_memory_slot, gfn_node[idx]); 1908 if (gfn >= slot->base_gfn) { 1909 if (gfn < slot->base_gfn + slot->npages) 1910 return slot; 1911 node = node->rb_right; 1912 } else 1913 node = node->rb_left; 1914 } 1915 1916 return approx ? slot : NULL; 1917 } 1918 1919 static inline struct kvm_memory_slot * 1920 ____gfn_to_memslot(struct kvm_memslots *slots, gfn_t gfn, bool approx) 1921 { 1922 struct kvm_memory_slot *slot; 1923 1924 slot = (struct kvm_memory_slot *)atomic_long_read(&slots->last_used_slot); 1925 slot = try_get_memslot(slot, gfn); 1926 if (slot) 1927 return slot; 1928 1929 slot = search_memslots(slots, gfn, approx); 1930 if (slot) { 1931 atomic_long_set(&slots->last_used_slot, (unsigned long)slot); 1932 return slot; 1933 } 1934 1935 return NULL; 1936 } 1937 1938 /* 1939 * __gfn_to_memslot() and its descendants are here to allow arch code to inline 1940 * the lookups in hot paths. gfn_to_memslot() itself isn't here as an inline 1941 * because that would bloat other code too much. 1942 */ 1943 static inline struct kvm_memory_slot * 1944 __gfn_to_memslot(struct kvm_memslots *slots, gfn_t gfn) 1945 { 1946 return ____gfn_to_memslot(slots, gfn, false); 1947 } 1948 1949 static inline unsigned long 1950 __gfn_to_hva_memslot(const struct kvm_memory_slot *slot, gfn_t gfn) 1951 { 1952 /* 1953 * The index was checked originally in search_memslots. To avoid 1954 * that a malicious guest builds a Spectre gadget out of e.g. page 1955 * table walks, do not let the processor speculate loads outside 1956 * the guest's registered memslots. 1957 */ 1958 unsigned long offset = gfn - slot->base_gfn; 1959 offset = array_index_nospec(offset, slot->npages); 1960 return slot->userspace_addr + offset * PAGE_SIZE; 1961 } 1962 1963 static inline int memslot_id(struct kvm *kvm, gfn_t gfn) 1964 { 1965 return gfn_to_memslot(kvm, gfn)->id; 1966 } 1967 1968 static inline gfn_t 1969 hva_to_gfn_memslot(unsigned long hva, struct kvm_memory_slot *slot) 1970 { 1971 gfn_t gfn_offset = (hva - slot->userspace_addr) >> PAGE_SHIFT; 1972 1973 return slot->base_gfn + gfn_offset; 1974 } 1975 1976 static inline gpa_t gfn_to_gpa(gfn_t gfn) 1977 { 1978 return (gpa_t)gfn << PAGE_SHIFT; 1979 } 1980 1981 static inline gfn_t gpa_to_gfn(gpa_t gpa) 1982 { 1983 return (gfn_t)(gpa >> PAGE_SHIFT); 1984 } 1985 1986 static inline hpa_t pfn_to_hpa(kvm_pfn_t pfn) 1987 { 1988 return (hpa_t)pfn << PAGE_SHIFT; 1989 } 1990 1991 static inline bool kvm_is_gpa_in_memslot(struct kvm *kvm, gpa_t gpa) 1992 { 1993 unsigned long hva = gfn_to_hva(kvm, gpa_to_gfn(gpa)); 1994 1995 return !kvm_is_error_hva(hva); 1996 } 1997 1998 static inline void kvm_gpc_mark_dirty_in_slot(struct gfn_to_pfn_cache *gpc) 1999 { 2000 lockdep_assert_held(&gpc->lock); 2001 2002 if (!gpc->memslot) 2003 return; 2004 2005 mark_page_dirty_in_slot(gpc->kvm, gpc->memslot, gpa_to_gfn(gpc->gpa)); 2006 } 2007 2008 enum kvm_stat_kind { 2009 KVM_STAT_VM, 2010 KVM_STAT_VCPU, 2011 }; 2012 2013 struct kvm_stat_data { 2014 struct kvm *kvm; 2015 const struct kvm_stats_desc *desc; 2016 enum kvm_stat_kind kind; 2017 }; 2018 2019 #define STATS_DESC_COMMON(type, unit, base, exp, sz, bsz) \ 2020 .flags = type | unit | base | \ 2021 BUILD_BUG_ON_ZERO(type & ~KVM_STATS_TYPE_MASK) | \ 2022 BUILD_BUG_ON_ZERO(unit & ~KVM_STATS_UNIT_MASK) | \ 2023 BUILD_BUG_ON_ZERO(base & ~KVM_STATS_BASE_MASK), \ 2024 .exponent = exp, \ 2025 .size = sz, \ 2026 .bucket_size = bsz 2027 2028 #define VM_GENERIC_STATS_DESC(stat, type, unit, base, exp, sz, bsz) \ 2029 { \ 2030 STATS_DESC_COMMON(type, unit, base, exp, sz, bsz), \ 2031 .offset = offsetof(struct kvm_vm_stat, generic.stat), \ 2032 .name = #stat, \ 2033 } 2034 #define VCPU_GENERIC_STATS_DESC(stat, type, unit, base, exp, sz, bsz) \ 2035 { \ 2036 STATS_DESC_COMMON(type, unit, base, exp, sz, bsz), \ 2037 .offset = offsetof(struct kvm_vcpu_stat, generic.stat), \ 2038 .name = #stat, \ 2039 } 2040 #define VM_STATS_DESC(stat, type, unit, base, exp, sz, bsz) \ 2041 { \ 2042 STATS_DESC_COMMON(type, unit, base, exp, sz, bsz), \ 2043 .offset = offsetof(struct kvm_vm_stat, stat), \ 2044 .name = #stat, \ 2045 } 2046 #define VCPU_STATS_DESC(stat, type, unit, base, exp, sz, bsz) \ 2047 { \ 2048 STATS_DESC_COMMON(type, unit, base, exp, sz, bsz), \ 2049 .offset = offsetof(struct kvm_vcpu_stat, stat), \ 2050 .name = #stat, \ 2051 } 2052 /* SCOPE: VM, VM_GENERIC, VCPU, VCPU_GENERIC */ 2053 #define STATS_DESC(SCOPE, stat, type, unit, base, exp, sz, bsz) \ 2054 SCOPE##_STATS_DESC(stat, type, unit, base, exp, sz, bsz) 2055 2056 #define STATS_DESC_CUMULATIVE(SCOPE, name, unit, base, exponent) \ 2057 STATS_DESC(SCOPE, name, KVM_STATS_TYPE_CUMULATIVE, \ 2058 unit, base, exponent, 1, 0) 2059 #define STATS_DESC_INSTANT(SCOPE, name, unit, base, exponent) \ 2060 STATS_DESC(SCOPE, name, KVM_STATS_TYPE_INSTANT, \ 2061 unit, base, exponent, 1, 0) 2062 #define STATS_DESC_PEAK(SCOPE, name, unit, base, exponent) \ 2063 STATS_DESC(SCOPE, name, KVM_STATS_TYPE_PEAK, \ 2064 unit, base, exponent, 1, 0) 2065 #define STATS_DESC_LINEAR_HIST(SCOPE, name, unit, base, exponent, sz, bsz) \ 2066 STATS_DESC(SCOPE, name, KVM_STATS_TYPE_LINEAR_HIST, \ 2067 unit, base, exponent, sz, bsz) 2068 #define STATS_DESC_LOG_HIST(SCOPE, name, unit, base, exponent, sz) \ 2069 STATS_DESC(SCOPE, name, KVM_STATS_TYPE_LOG_HIST, \ 2070 unit, base, exponent, sz, 0) 2071 2072 /* Cumulative counter, read/write */ 2073 #define STATS_DESC_COUNTER(SCOPE, name) \ 2074 STATS_DESC_CUMULATIVE(SCOPE, name, KVM_STATS_UNIT_NONE, \ 2075 KVM_STATS_BASE_POW10, 0) 2076 /* Instantaneous counter, read only */ 2077 #define STATS_DESC_ICOUNTER(SCOPE, name) \ 2078 STATS_DESC_INSTANT(SCOPE, name, KVM_STATS_UNIT_NONE, \ 2079 KVM_STATS_BASE_POW10, 0) 2080 /* Peak counter, read/write */ 2081 #define STATS_DESC_PCOUNTER(SCOPE, name) \ 2082 STATS_DESC_PEAK(SCOPE, name, KVM_STATS_UNIT_NONE, \ 2083 KVM_STATS_BASE_POW10, 0) 2084 2085 /* Instantaneous boolean value, read only */ 2086 #define STATS_DESC_IBOOLEAN(SCOPE, name) \ 2087 STATS_DESC_INSTANT(SCOPE, name, KVM_STATS_UNIT_BOOLEAN, \ 2088 KVM_STATS_BASE_POW10, 0) 2089 /* Peak (sticky) boolean value, read/write */ 2090 #define STATS_DESC_PBOOLEAN(SCOPE, name) \ 2091 STATS_DESC_PEAK(SCOPE, name, KVM_STATS_UNIT_BOOLEAN, \ 2092 KVM_STATS_BASE_POW10, 0) 2093 2094 /* Cumulative time in nanosecond */ 2095 #define STATS_DESC_TIME_NSEC(SCOPE, name) \ 2096 STATS_DESC_CUMULATIVE(SCOPE, name, KVM_STATS_UNIT_SECONDS, \ 2097 KVM_STATS_BASE_POW10, -9) 2098 /* Linear histogram for time in nanosecond */ 2099 #define STATS_DESC_LINHIST_TIME_NSEC(SCOPE, name, sz, bsz) \ 2100 STATS_DESC_LINEAR_HIST(SCOPE, name, KVM_STATS_UNIT_SECONDS, \ 2101 KVM_STATS_BASE_POW10, -9, sz, bsz) 2102 /* Logarithmic histogram for time in nanosecond */ 2103 #define STATS_DESC_LOGHIST_TIME_NSEC(SCOPE, name, sz) \ 2104 STATS_DESC_LOG_HIST(SCOPE, name, KVM_STATS_UNIT_SECONDS, \ 2105 KVM_STATS_BASE_POW10, -9, sz) 2106 2107 #define KVM_GENERIC_VM_STATS() \ 2108 STATS_DESC_COUNTER(VM_GENERIC, remote_tlb_flush), \ 2109 STATS_DESC_COUNTER(VM_GENERIC, remote_tlb_flush_requests) 2110 2111 #define KVM_GENERIC_VCPU_STATS() \ 2112 STATS_DESC_COUNTER(VCPU_GENERIC, halt_successful_poll), \ 2113 STATS_DESC_COUNTER(VCPU_GENERIC, halt_attempted_poll), \ 2114 STATS_DESC_COUNTER(VCPU_GENERIC, halt_poll_invalid), \ 2115 STATS_DESC_COUNTER(VCPU_GENERIC, halt_wakeup), \ 2116 STATS_DESC_TIME_NSEC(VCPU_GENERIC, halt_poll_success_ns), \ 2117 STATS_DESC_TIME_NSEC(VCPU_GENERIC, halt_poll_fail_ns), \ 2118 STATS_DESC_TIME_NSEC(VCPU_GENERIC, halt_wait_ns), \ 2119 STATS_DESC_LOGHIST_TIME_NSEC(VCPU_GENERIC, halt_poll_success_hist, \ 2120 HALT_POLL_HIST_COUNT), \ 2121 STATS_DESC_LOGHIST_TIME_NSEC(VCPU_GENERIC, halt_poll_fail_hist, \ 2122 HALT_POLL_HIST_COUNT), \ 2123 STATS_DESC_LOGHIST_TIME_NSEC(VCPU_GENERIC, halt_wait_hist, \ 2124 HALT_POLL_HIST_COUNT), \ 2125 STATS_DESC_IBOOLEAN(VCPU_GENERIC, blocking) 2126 2127 ssize_t kvm_stats_read(char *id, const struct kvm_stats_header *header, 2128 const struct kvm_stats_desc *desc, 2129 void *stats, size_t size_stats, 2130 char __user *user_buffer, size_t size, loff_t *offset); 2131 2132 /** 2133 * kvm_stats_linear_hist_update() - Update bucket value for linear histogram 2134 * statistics data. 2135 * 2136 * @data: start address of the stats data 2137 * @size: the number of bucket of the stats data 2138 * @value: the new value used to update the linear histogram's bucket 2139 * @bucket_size: the size (width) of a bucket 2140 */ 2141 static inline void kvm_stats_linear_hist_update(u64 *data, size_t size, 2142 u64 value, size_t bucket_size) 2143 { 2144 size_t index = div64_u64(value, bucket_size); 2145 2146 index = min(index, size - 1); 2147 ++data[index]; 2148 } 2149 2150 /** 2151 * kvm_stats_log_hist_update() - Update bucket value for logarithmic histogram 2152 * statistics data. 2153 * 2154 * @data: start address of the stats data 2155 * @size: the number of bucket of the stats data 2156 * @value: the new value used to update the logarithmic histogram's bucket 2157 */ 2158 static inline void kvm_stats_log_hist_update(u64 *data, size_t size, u64 value) 2159 { 2160 size_t index = fls64(value); 2161 2162 index = min(index, size - 1); 2163 ++data[index]; 2164 } 2165 2166 #define KVM_STATS_LINEAR_HIST_UPDATE(array, value, bsize) \ 2167 kvm_stats_linear_hist_update(array, ARRAY_SIZE(array), value, bsize) 2168 #define KVM_STATS_LOG_HIST_UPDATE(array, value) \ 2169 kvm_stats_log_hist_update(array, ARRAY_SIZE(array), value) 2170 2171 2172 extern const struct kvm_stats_header kvm_vm_stats_header; 2173 extern const struct kvm_stats_desc kvm_vm_stats_desc[]; 2174 extern const struct kvm_stats_header kvm_vcpu_stats_header; 2175 extern const struct kvm_stats_desc kvm_vcpu_stats_desc[]; 2176 2177 static inline int mmu_invalidate_retry(struct kvm *kvm, unsigned long mmu_seq) 2178 { 2179 if (unlikely(kvm->mmu_invalidate_in_progress)) 2180 return 1; 2181 /* 2182 * Ensure the read of mmu_invalidate_in_progress happens before 2183 * the read of mmu_invalidate_seq. This interacts with the 2184 * smp_wmb() in mmu_notifier_invalidate_range_end to make sure 2185 * that the caller either sees the old (non-zero) value of 2186 * mmu_invalidate_in_progress or the new (incremented) value of 2187 * mmu_invalidate_seq. 2188 * 2189 * PowerPC Book3s HV KVM calls this under a per-page lock rather 2190 * than under kvm->mmu_lock, for scalability, so can't rely on 2191 * kvm->mmu_lock to keep things ordered. 2192 */ 2193 smp_rmb(); 2194 if (kvm->mmu_invalidate_seq != mmu_seq) 2195 return 1; 2196 return 0; 2197 } 2198 2199 static inline int mmu_invalidate_retry_gfn(struct kvm *kvm, 2200 unsigned long mmu_seq, 2201 gfn_t gfn) 2202 { 2203 lockdep_assert_held(&kvm->mmu_lock); 2204 /* 2205 * If mmu_invalidate_in_progress is non-zero, then the range maintained 2206 * by kvm_mmu_notifier_invalidate_range_start contains all addresses 2207 * that might be being invalidated. Note that it may include some false 2208 * positives, due to shortcuts when handing concurrent invalidations. 2209 */ 2210 if (unlikely(kvm->mmu_invalidate_in_progress)) { 2211 /* 2212 * Dropping mmu_lock after bumping mmu_invalidate_in_progress 2213 * but before updating the range is a KVM bug. 2214 */ 2215 if (WARN_ON_ONCE(kvm->mmu_invalidate_range_start == INVALID_GPA || 2216 kvm->mmu_invalidate_range_end == INVALID_GPA)) 2217 return 1; 2218 2219 if (gfn >= kvm->mmu_invalidate_range_start && 2220 gfn < kvm->mmu_invalidate_range_end) 2221 return 1; 2222 } 2223 2224 if (kvm->mmu_invalidate_seq != mmu_seq) 2225 return 1; 2226 return 0; 2227 } 2228 2229 /* 2230 * This lockless version of the range-based retry check *must* be paired with a 2231 * call to the locked version after acquiring mmu_lock, i.e. this is safe to 2232 * use only as a pre-check to avoid contending mmu_lock. This version *will* 2233 * get false negatives and false positives. 2234 */ 2235 static inline bool mmu_invalidate_retry_gfn_unsafe(struct kvm *kvm, 2236 unsigned long mmu_seq, 2237 gfn_t gfn) 2238 { 2239 /* 2240 * Use READ_ONCE() to ensure the in-progress flag and sequence counter 2241 * are always read from memory, e.g. so that checking for retry in a 2242 * loop won't result in an infinite retry loop. Don't force loads for 2243 * start+end, as the key to avoiding infinite retry loops is observing 2244 * the 1=>0 transition of in-progress, i.e. getting false negatives 2245 * due to stale start+end values is acceptable. 2246 */ 2247 if (unlikely(READ_ONCE(kvm->mmu_invalidate_in_progress)) && 2248 gfn >= kvm->mmu_invalidate_range_start && 2249 gfn < kvm->mmu_invalidate_range_end) 2250 return true; 2251 2252 return READ_ONCE(kvm->mmu_invalidate_seq) != mmu_seq; 2253 } 2254 2255 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING 2256 2257 #define KVM_MAX_IRQ_ROUTES 4096 /* might need extension/rework in the future */ 2258 2259 bool kvm_arch_can_set_irq_routing(struct kvm *kvm); 2260 int kvm_set_irq_routing(struct kvm *kvm, 2261 const struct kvm_irq_routing_entry *entries, 2262 unsigned nr, 2263 unsigned flags); 2264 int kvm_init_irq_routing(struct kvm *kvm); 2265 int kvm_set_routing_entry(struct kvm *kvm, 2266 struct kvm_kernel_irq_routing_entry *e, 2267 const struct kvm_irq_routing_entry *ue); 2268 void kvm_free_irq_routing(struct kvm *kvm); 2269 2270 #else 2271 2272 static inline void kvm_free_irq_routing(struct kvm *kvm) {} 2273 2274 static inline int kvm_init_irq_routing(struct kvm *kvm) 2275 { 2276 return 0; 2277 } 2278 2279 #endif 2280 2281 int kvm_send_userspace_msi(struct kvm *kvm, struct kvm_msi *msi); 2282 2283 void kvm_eventfd_init(struct kvm *kvm); 2284 int kvm_ioeventfd(struct kvm *kvm, struct kvm_ioeventfd *args); 2285 2286 #ifdef CONFIG_HAVE_KVM_IRQCHIP 2287 int kvm_irqfd(struct kvm *kvm, struct kvm_irqfd *args); 2288 void kvm_irqfd_release(struct kvm *kvm); 2289 bool kvm_notify_irqfd_resampler(struct kvm *kvm, 2290 unsigned int irqchip, 2291 unsigned int pin); 2292 void kvm_irq_routing_update(struct kvm *); 2293 #else 2294 static inline int kvm_irqfd(struct kvm *kvm, struct kvm_irqfd *args) 2295 { 2296 return -EINVAL; 2297 } 2298 2299 static inline void kvm_irqfd_release(struct kvm *kvm) {} 2300 2301 static inline bool kvm_notify_irqfd_resampler(struct kvm *kvm, 2302 unsigned int irqchip, 2303 unsigned int pin) 2304 { 2305 return false; 2306 } 2307 #endif /* CONFIG_HAVE_KVM_IRQCHIP */ 2308 2309 void kvm_arch_irq_routing_update(struct kvm *kvm); 2310 2311 static inline void __kvm_make_request(int req, struct kvm_vcpu *vcpu) 2312 { 2313 /* 2314 * Ensure the rest of the request is published to kvm_check_request's 2315 * caller. Paired with the smp_mb__after_atomic in kvm_check_request. 2316 */ 2317 smp_wmb(); 2318 set_bit(req & KVM_REQUEST_MASK, (void *)&vcpu->requests); 2319 } 2320 2321 static __always_inline void kvm_make_request(int req, struct kvm_vcpu *vcpu) 2322 { 2323 /* 2324 * Request that don't require vCPU action should never be logged in 2325 * vcpu->requests. The vCPU won't clear the request, so it will stay 2326 * logged indefinitely and prevent the vCPU from entering the guest. 2327 */ 2328 BUILD_BUG_ON(!__builtin_constant_p(req) || 2329 (req & KVM_REQUEST_NO_ACTION)); 2330 2331 __kvm_make_request(req, vcpu); 2332 } 2333 2334 #ifndef CONFIG_S390 2335 static inline void kvm_make_request_and_kick(int req, struct kvm_vcpu *vcpu) 2336 { 2337 kvm_make_request(req, vcpu); 2338 __kvm_vcpu_kick(vcpu, req, false); 2339 } 2340 #endif 2341 2342 static inline bool kvm_request_pending(struct kvm_vcpu *vcpu) 2343 { 2344 return READ_ONCE(vcpu->requests); 2345 } 2346 2347 static inline bool kvm_test_request(int req, struct kvm_vcpu *vcpu) 2348 { 2349 return test_bit(req & KVM_REQUEST_MASK, (void *)&vcpu->requests); 2350 } 2351 2352 static __always_inline void kvm_clear_request(int req, struct kvm_vcpu *vcpu) 2353 { 2354 BUILD_BUG_ON(req == KVM_REQ_VM_DEAD); 2355 2356 clear_bit(req & KVM_REQUEST_MASK, (void *)&vcpu->requests); 2357 } 2358 2359 static __always_inline bool kvm_check_request(int req, struct kvm_vcpu *vcpu) 2360 { 2361 /* Once a VM is dead, it needs to stay dead. */ 2362 BUILD_BUG_ON(req == KVM_REQ_VM_DEAD); 2363 2364 if (kvm_test_request(req, vcpu)) { 2365 kvm_clear_request(req, vcpu); 2366 2367 /* 2368 * Ensure the rest of the request is visible to kvm_check_request's 2369 * caller. Paired with the smp_wmb in kvm_make_request. 2370 */ 2371 smp_mb__after_atomic(); 2372 return true; 2373 } else { 2374 return false; 2375 } 2376 } 2377 2378 #ifdef CONFIG_KVM_GENERIC_HARDWARE_ENABLING 2379 extern bool enable_virt_at_load; 2380 #endif 2381 2382 extern unsigned int halt_poll_ns; 2383 extern unsigned int halt_poll_ns_grow; 2384 extern unsigned int halt_poll_ns_grow_start; 2385 extern unsigned int halt_poll_ns_shrink; 2386 2387 struct kvm_device { 2388 const struct kvm_device_ops *ops; 2389 struct kvm *kvm; 2390 void *private; 2391 struct list_head vm_node; 2392 }; 2393 2394 /* create, destroy, and name are mandatory */ 2395 struct kvm_device_ops { 2396 const char *name; 2397 2398 /* 2399 * create is called holding kvm->lock and any operations not suitable 2400 * to do while holding the lock should be deferred to init (see 2401 * below). 2402 */ 2403 int (*create)(struct kvm_device *dev, u32 type); 2404 2405 /* 2406 * init is called after create if create is successful and is called 2407 * outside of holding kvm->lock. 2408 */ 2409 void (*init)(struct kvm_device *dev); 2410 2411 /* 2412 * Destroy is responsible for freeing dev. 2413 * 2414 * Destroy may be called before or after destructors are called 2415 * on emulated I/O regions, depending on whether a reference is 2416 * held by a vcpu or other kvm component that gets destroyed 2417 * after the emulated I/O. 2418 */ 2419 void (*destroy)(struct kvm_device *dev); 2420 2421 /* 2422 * Release is an alternative method to free the device. It is 2423 * called when the device file descriptor is closed. Once 2424 * release is called, the destroy method will not be called 2425 * anymore as the device is removed from the device list of 2426 * the VM. kvm->lock is held. 2427 */ 2428 void (*release)(struct kvm_device *dev); 2429 2430 int (*set_attr)(struct kvm_device *dev, struct kvm_device_attr *attr); 2431 int (*get_attr)(struct kvm_device *dev, struct kvm_device_attr *attr); 2432 int (*has_attr)(struct kvm_device *dev, struct kvm_device_attr *attr); 2433 long (*ioctl)(struct kvm_device *dev, unsigned int ioctl, 2434 unsigned long arg); 2435 int (*mmap)(struct kvm_device *dev, struct vm_area_struct *vma); 2436 }; 2437 2438 struct kvm_device *kvm_device_from_filp(struct file *filp); 2439 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type); 2440 void kvm_unregister_device_ops(u32 type); 2441 2442 extern struct kvm_device_ops kvm_mpic_ops; 2443 extern struct kvm_device_ops kvm_arm_vgic_v2_ops; 2444 extern struct kvm_device_ops kvm_arm_vgic_v3_ops; 2445 extern struct kvm_device_ops kvm_arm_vgic_v5_ops; 2446 2447 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT 2448 2449 static inline void kvm_vcpu_set_in_spin_loop(struct kvm_vcpu *vcpu, bool val) 2450 { 2451 vcpu->spin_loop.in_spin_loop = val; 2452 } 2453 static inline void kvm_vcpu_set_dy_eligible(struct kvm_vcpu *vcpu, bool val) 2454 { 2455 vcpu->spin_loop.dy_eligible = val; 2456 } 2457 2458 #else /* !CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT */ 2459 2460 static inline void kvm_vcpu_set_in_spin_loop(struct kvm_vcpu *vcpu, bool val) 2461 { 2462 } 2463 2464 static inline void kvm_vcpu_set_dy_eligible(struct kvm_vcpu *vcpu, bool val) 2465 { 2466 } 2467 #endif /* CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT */ 2468 2469 static inline bool kvm_is_visible_memslot(struct kvm_memory_slot *memslot) 2470 { 2471 return (memslot && memslot->id < KVM_USER_MEM_SLOTS && 2472 !(memslot->flags & KVM_MEMSLOT_INVALID)); 2473 } 2474 2475 struct kvm_vcpu *kvm_get_running_vcpu(void); 2476 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void); 2477 2478 #if IS_ENABLED(CONFIG_HAVE_KVM_IRQ_BYPASS) 2479 struct kvm_kernel_irqfd; 2480 2481 bool kvm_arch_has_irq_bypass(void); 2482 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *, 2483 struct irq_bypass_producer *); 2484 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *, 2485 struct irq_bypass_producer *); 2486 void kvm_arch_irq_bypass_stop(struct irq_bypass_consumer *); 2487 void kvm_arch_irq_bypass_start(struct irq_bypass_consumer *); 2488 void kvm_arch_update_irqfd_routing(struct kvm_kernel_irqfd *irqfd, 2489 struct kvm_kernel_irq_routing_entry *old, 2490 struct kvm_kernel_irq_routing_entry *new); 2491 #endif /* CONFIG_HAVE_KVM_IRQ_BYPASS */ 2492 2493 #ifdef __KVM_HAVE_INVALID_WAKEUPS 2494 /* If we wakeup during the poll time, was it a sucessful poll? */ 2495 static inline bool vcpu_valid_wakeup(struct kvm_vcpu *vcpu) 2496 { 2497 return vcpu->valid_wakeup; 2498 } 2499 2500 #else 2501 static inline bool vcpu_valid_wakeup(struct kvm_vcpu *vcpu) 2502 { 2503 return true; 2504 } 2505 #endif /* __KVM_HAVE_INVALID_WAKEUPS */ 2506 2507 #ifdef __KVM_HAVE_NO_POLL 2508 /* Callback that tells if we must not poll */ 2509 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu); 2510 #else 2511 static inline bool kvm_arch_no_poll(struct kvm_vcpu *vcpu) 2512 { 2513 return false; 2514 } 2515 #endif /* __KVM_HAVE_NO_POLL */ 2516 2517 void kvm_arch_guest_memory_reclaimed(struct kvm *kvm); 2518 2519 #ifdef __KVM_HAVE_VCPU_RUN_PID_CHANGE 2520 int kvm_arch_vcpu_run_pid_change(struct kvm_vcpu *vcpu); 2521 #else 2522 static inline int kvm_arch_vcpu_run_pid_change(struct kvm_vcpu *vcpu) 2523 { 2524 return 0; 2525 } 2526 #endif /* __KVM_HAVE_VCPU_RUN_PID_CHANGE */ 2527 2528 #ifdef CONFIG_VIRT_XFER_TO_GUEST_WORK 2529 static inline void kvm_handle_signal_exit(struct kvm_vcpu *vcpu) 2530 { 2531 vcpu->run->exit_reason = KVM_EXIT_INTR; 2532 vcpu->stat.signal_exits++; 2533 } 2534 2535 static inline int kvm_xfer_to_guest_mode_handle_work(struct kvm_vcpu *vcpu) 2536 { 2537 int r = xfer_to_guest_mode_handle_work(); 2538 2539 if (r) { 2540 WARN_ON_ONCE(r != -EINTR); 2541 kvm_handle_signal_exit(vcpu); 2542 } 2543 return r; 2544 } 2545 #endif /* CONFIG_VIRT_XFER_TO_GUEST_WORK */ 2546 2547 /* 2548 * If more than one page is being (un)accounted, @virt must be the address of 2549 * the first page of a block of pages what were allocated together (i.e 2550 * accounted together). 2551 * 2552 * kvm_account_pgtable_pages() is thread-safe because mod_lruvec_page_state() 2553 * is thread-safe. 2554 */ 2555 static inline void kvm_account_pgtable_pages(void *virt, int nr) 2556 { 2557 mod_lruvec_page_state(virt_to_page(virt), NR_SECONDARY_PAGETABLE, nr); 2558 } 2559 2560 /* 2561 * This defines how many reserved entries we want to keep before we 2562 * kick the vcpu to the userspace to avoid dirty ring full. This 2563 * value can be tuned to higher if e.g. PML is enabled on the host. 2564 */ 2565 #define KVM_DIRTY_RING_RSVD_ENTRIES 64 2566 2567 /* Max number of entries allowed for each kvm dirty ring */ 2568 #define KVM_DIRTY_RING_MAX_ENTRIES 65536 2569 2570 static inline void kvm_prepare_memory_fault_exit(struct kvm_vcpu *vcpu, 2571 gpa_t gpa, gpa_t size, 2572 bool is_write, bool is_exec, 2573 bool is_private) 2574 { 2575 vcpu->run->exit_reason = KVM_EXIT_MEMORY_FAULT; 2576 vcpu->run->memory_fault.gpa = gpa; 2577 vcpu->run->memory_fault.size = size; 2578 2579 /* RWX flags are not (yet) defined or communicated to userspace. */ 2580 vcpu->run->memory_fault.flags = 0; 2581 if (is_private) 2582 vcpu->run->memory_fault.flags |= KVM_MEMORY_EXIT_FLAG_PRIVATE; 2583 } 2584 2585 static inline bool kvm_memslot_is_gmem_only(const struct kvm_memory_slot *slot) 2586 { 2587 if (!IS_ENABLED(CONFIG_KVM_GUEST_MEMFD)) 2588 return false; 2589 2590 return slot->flags & KVM_MEMSLOT_GMEM_ONLY; 2591 } 2592 2593 #ifdef CONFIG_KVM_VM_MEMORY_ATTRIBUTES 2594 static inline unsigned long kvm_get_vm_memory_attributes(struct kvm *kvm, gfn_t gfn) 2595 { 2596 return xa_to_value(xa_load(&kvm->mem_attr_array, gfn)); 2597 } 2598 2599 bool kvm_range_has_vm_memory_attributes(struct kvm *kvm, gfn_t start, gfn_t end, 2600 unsigned long mask, unsigned long attrs); 2601 bool kvm_arch_pre_set_vm_memory_attributes(struct kvm *kvm, 2602 struct kvm_gfn_range *range); 2603 bool kvm_arch_post_set_vm_memory_attributes(struct kvm *kvm, 2604 struct kvm_gfn_range *range); 2605 #endif /* CONFIG_KVM_VM_MEMORY_ATTRIBUTES */ 2606 2607 #ifdef CONFIG_KVM_PRIVATE_MEMATTR_VM 2608 extern bool gmem_in_place_conversion; 2609 typedef bool (kvm_is_private_gfn_t)(struct kvm *kvm, gfn_t gfn); 2610 DECLARE_STATIC_CALL(__kvm_is_private_gfn, kvm_is_private_gfn_t); 2611 2612 static inline bool kvm_is_private_gfn(struct kvm *kvm, gfn_t gfn) 2613 { 2614 return static_call(__kvm_is_private_gfn)(kvm, gfn); 2615 } 2616 2617 #elif defined kvm_arch_has_private_mem 2618 #define gmem_in_place_conversion true 2619 #define kvm_is_private_gfn kvm_gmem_is_private_gfn 2620 2621 #else 2622 #define gmem_in_place_conversion false 2623 2624 static inline bool kvm_arch_has_private_mem(struct kvm *kvm) 2625 { 2626 return false; 2627 } 2628 2629 static inline bool kvm_is_private_gfn(struct kvm *kvm, gfn_t gfn) 2630 { 2631 return false; 2632 } 2633 #endif /* kvm_arch_has_private_mem */ 2634 2635 #ifdef CONFIG_KVM_GUEST_MEMFD 2636 bool kvm_gmem_is_private_gfn(struct kvm *kvm, gfn_t gfn); 2637 bool kvm_arch_supports_gmem_init_shared(struct kvm *kvm); 2638 2639 static inline u64 kvm_gmem_get_supported_flags(struct kvm *kvm) 2640 { 2641 u64 flags = GUEST_MEMFD_FLAG_MMAP; 2642 2643 if (!kvm || kvm_arch_supports_gmem_init_shared(kvm)) 2644 flags |= GUEST_MEMFD_FLAG_INIT_SHARED; 2645 2646 return flags; 2647 } 2648 2649 int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot, 2650 gfn_t gfn, kvm_pfn_t *pfn, int *max_order); 2651 #else 2652 static inline int kvm_gmem_get_pfn(struct kvm *kvm, 2653 struct kvm_memory_slot *slot, gfn_t gfn, 2654 kvm_pfn_t *pfn, int *max_order) 2655 { 2656 KVM_BUG_ON(1, kvm); 2657 return -EIO; 2658 } 2659 #endif /* CONFIG_KVM_GUEST_MEMFD */ 2660 2661 int kvm_arch_gmem_make_private(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, 2662 kvm_pfn_t nr_pages); 2663 void kvm_arch_gmem_make_shared(kvm_pfn_t pfn, kvm_pfn_t nr_pages); 2664 #ifndef CONFIG_HAVE_KVM_ARCH_GMEM_CONVERT 2665 #define kvm_arch_has_gmem_convert() false 2666 #endif 2667 2668 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_POPULATE 2669 /** 2670 * kvm_gmem_populate() - Populate/prepare a GPA range with guest data 2671 * 2672 * @kvm: KVM instance 2673 * @gfn: starting GFN to be populated 2674 * @src: userspace-provided buffer containing data to copy into GFN range 2675 * (passed to @post_populate, and incremented on each iteration 2676 * if not NULL). Must be page-aligned. 2677 * @npages: number of pages to copy from userspace-buffer 2678 * @post_populate: callback to issue for each gmem page that backs the GPA 2679 * range 2680 * @opaque: opaque data to pass to @post_populate callback 2681 * 2682 * This is primarily intended for cases where a gmem-backed GPA range needs 2683 * to be initialized with userspace-provided data prior to being mapped into 2684 * the guest as a private page. This should be called with the slots->lock 2685 * held so that caller-enforced invariants regarding the expected memory 2686 * attributes of the GPA range do not race with KVM_SET_MEMORY_ATTRIBUTES. 2687 * 2688 * Returns the number of pages that were populated. 2689 */ 2690 typedef int (*kvm_gmem_populate_cb)(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, 2691 struct page *page, void *opaque); 2692 2693 long kvm_gmem_populate(struct kvm *kvm, gfn_t start_gfn, void __user *src, 2694 long npages, bool may_writeback_src, 2695 kvm_gmem_populate_cb post_populate, void *opaque); 2696 #endif 2697 2698 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_RECLAIM 2699 void kvm_arch_gmem_reclaim(kvm_pfn_t pfn, kvm_pfn_t nr_pages); 2700 #endif 2701 2702 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE 2703 void kvm_arch_gmem_invalidate_range(struct kvm *kvm, struct kvm_gfn_range *range); 2704 #endif 2705 2706 #ifdef CONFIG_KVM_GENERIC_PRE_FAULT_MEMORY 2707 int kvm_arch_pre_fault_allowed(struct kvm_vcpu *vcpu); 2708 long kvm_arch_vcpu_pre_fault_memory(struct kvm_vcpu *vcpu, 2709 struct kvm_pre_fault_memory *range); 2710 #endif 2711 2712 #endif 2713