1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * Kernel-based Virtual Machine (KVM) Hypervisor 4 * 5 * Copyright (C) 2006 Qumranet, Inc. 6 * Copyright 2010 Red Hat, Inc. and/or its affiliates. 7 * 8 * Authors: 9 * Avi Kivity <avi@qumranet.com> 10 * Yaniv Kamay <yaniv@qumranet.com> 11 */ 12 13 #include <kvm/iodev.h> 14 15 #include <linux/kvm_host.h> 16 #include <linux/kvm.h> 17 #include <linux/module.h> 18 #include <linux/errno.h> 19 #include <linux/percpu.h> 20 #include <linux/mm.h> 21 #include <linux/miscdevice.h> 22 #include <linux/vmalloc.h> 23 #include <linux/reboot.h> 24 #include <linux/debugfs.h> 25 #include <linux/highmem.h> 26 #include <linux/file.h> 27 #include <linux/syscore_ops.h> 28 #include <linux/cpu.h> 29 #include <linux/sched/signal.h> 30 #include <linux/sched/mm.h> 31 #include <linux/sched/stat.h> 32 #include <linux/cpumask.h> 33 #include <linux/smp.h> 34 #include <linux/anon_inodes.h> 35 #include <linux/profile.h> 36 #include <linux/kvm_para.h> 37 #include <linux/pagemap.h> 38 #include <linux/mman.h> 39 #include <linux/swap.h> 40 #include <linux/bitops.h> 41 #include <linux/spinlock.h> 42 #include <linux/compat.h> 43 #include <linux/srcu.h> 44 #include <linux/hugetlb.h> 45 #include <linux/slab.h> 46 #include <linux/sort.h> 47 #include <linux/bsearch.h> 48 #include <linux/io.h> 49 #include <linux/lockdep.h> 50 #include <linux/kthread.h> 51 #include <linux/suspend.h> 52 53 #include <asm/processor.h> 54 #include <asm/ioctl.h> 55 #include <linux/uaccess.h> 56 57 #include "coalesced_mmio.h" 58 #include "async_pf.h" 59 #include "kvm_mm.h" 60 #include "vfio.h" 61 62 #include <trace/events/ipi.h> 63 64 #define CREATE_TRACE_POINTS 65 #include <trace/events/kvm.h> 66 67 #include <linux/kvm_dirty_ring.h> 68 69 70 /* Worst case buffer size needed for holding an integer. */ 71 #define ITOA_MAX_LEN 12 72 73 MODULE_AUTHOR("Qumranet"); 74 MODULE_DESCRIPTION("Kernel-based Virtual Machine (KVM) Hypervisor"); 75 MODULE_LICENSE("GPL"); 76 77 /* Architectures should define their poll value according to the halt latency */ 78 unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT; 79 module_param(halt_poll_ns, uint, 0644); 80 EXPORT_SYMBOL_GPL(halt_poll_ns); 81 82 /* Default doubles per-vcpu halt_poll_ns. */ 83 unsigned int halt_poll_ns_grow = 2; 84 module_param(halt_poll_ns_grow, uint, 0644); 85 EXPORT_SYMBOL_GPL(halt_poll_ns_grow); 86 87 /* The start value to grow halt_poll_ns from */ 88 unsigned int halt_poll_ns_grow_start = 10000; /* 10us */ 89 module_param(halt_poll_ns_grow_start, uint, 0644); 90 EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start); 91 92 /* Default halves per-vcpu halt_poll_ns. */ 93 unsigned int halt_poll_ns_shrink = 2; 94 module_param(halt_poll_ns_shrink, uint, 0644); 95 EXPORT_SYMBOL_GPL(halt_poll_ns_shrink); 96 97 /* 98 * Allow direct access (from KVM or the CPU) without MMU notifier protection 99 * to unpinned pages. 100 */ 101 static bool allow_unsafe_mappings; 102 module_param(allow_unsafe_mappings, bool, 0444); 103 104 /* 105 * Ordering of locks: 106 * 107 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock 108 */ 109 110 DEFINE_MUTEX(kvm_lock); 111 LIST_HEAD(vm_list); 112 113 static struct kmem_cache *kvm_vcpu_cache; 114 115 static __read_mostly struct preempt_ops kvm_preempt_ops; 116 static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_running_vcpu); 117 118 static struct dentry *kvm_debugfs_dir; 119 120 static const struct file_operations stat_fops_per_vm; 121 122 static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl, 123 unsigned long arg); 124 #ifdef CONFIG_KVM_COMPAT 125 static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl, 126 unsigned long arg); 127 #define KVM_COMPAT(c) .compat_ioctl = (c) 128 #else 129 /* 130 * For architectures that don't implement a compat infrastructure, 131 * adopt a double line of defense: 132 * - Prevent a compat task from opening /dev/kvm 133 * - If the open has been done by a 64bit task, and the KVM fd 134 * passed to a compat task, let the ioctls fail. 135 */ 136 static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl, 137 unsigned long arg) { return -EINVAL; } 138 139 static int kvm_no_compat_open(struct inode *inode, struct file *file) 140 { 141 return is_compat_task() ? -ENODEV : 0; 142 } 143 #define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \ 144 .open = kvm_no_compat_open 145 #endif 146 147 static void kvm_io_bus_destroy(struct kvm_io_bus *bus); 148 149 #define KVM_EVENT_CREATE_VM 0 150 #define KVM_EVENT_DESTROY_VM 1 151 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm); 152 static unsigned long long kvm_createvm_count; 153 static unsigned long long kvm_active_vms; 154 155 static DEFINE_PER_CPU(cpumask_var_t, cpu_kick_mask); 156 157 __weak void kvm_arch_guest_memory_reclaimed(struct kvm *kvm) 158 { 159 } 160 161 /* 162 * Switches to specified vcpu, until a matching vcpu_put() 163 */ 164 void vcpu_load(struct kvm_vcpu *vcpu) 165 { 166 int cpu = get_cpu(); 167 168 __this_cpu_write(kvm_running_vcpu, vcpu); 169 preempt_notifier_register(&vcpu->preempt_notifier); 170 kvm_arch_vcpu_load(vcpu, cpu); 171 put_cpu(); 172 } 173 EXPORT_SYMBOL_GPL(vcpu_load); 174 175 void vcpu_put(struct kvm_vcpu *vcpu) 176 { 177 preempt_disable(); 178 kvm_arch_vcpu_put(vcpu); 179 preempt_notifier_unregister(&vcpu->preempt_notifier); 180 __this_cpu_write(kvm_running_vcpu, NULL); 181 preempt_enable(); 182 } 183 EXPORT_SYMBOL_GPL(vcpu_put); 184 185 /* TODO: merge with kvm_arch_vcpu_should_kick */ 186 static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req) 187 { 188 int mode = kvm_vcpu_exiting_guest_mode(vcpu); 189 190 /* 191 * We need to wait for the VCPU to reenable interrupts and get out of 192 * READING_SHADOW_PAGE_TABLES mode. 193 */ 194 if (req & KVM_REQUEST_WAIT) 195 return mode != OUTSIDE_GUEST_MODE; 196 197 /* 198 * Need to kick a running VCPU, but otherwise there is nothing to do. 199 */ 200 return mode == IN_GUEST_MODE; 201 } 202 203 static void ack_kick(void *_completed) 204 { 205 } 206 207 static inline bool kvm_kick_many_cpus(struct cpumask *cpus, bool wait) 208 { 209 if (cpumask_empty(cpus)) 210 return false; 211 212 smp_call_function_many(cpus, ack_kick, NULL, wait); 213 return true; 214 } 215 216 static void kvm_make_vcpu_request(struct kvm_vcpu *vcpu, unsigned int req, 217 struct cpumask *tmp, int current_cpu) 218 { 219 int cpu; 220 221 if (likely(!(req & KVM_REQUEST_NO_ACTION))) 222 __kvm_make_request(req, vcpu); 223 224 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu)) 225 return; 226 227 /* 228 * Note, the vCPU could get migrated to a different pCPU at any point 229 * after kvm_request_needs_ipi(), which could result in sending an IPI 230 * to the previous pCPU. But, that's OK because the purpose of the IPI 231 * is to ensure the vCPU returns to OUTSIDE_GUEST_MODE, which is 232 * satisfied if the vCPU migrates. Entering READING_SHADOW_PAGE_TABLES 233 * after this point is also OK, as the requirement is only that KVM wait 234 * for vCPUs that were reading SPTEs _before_ any changes were 235 * finalized. See kvm_vcpu_kick() for more details on handling requests. 236 */ 237 if (kvm_request_needs_ipi(vcpu, req)) { 238 cpu = READ_ONCE(vcpu->cpu); 239 if (cpu != -1 && cpu != current_cpu) 240 __cpumask_set_cpu(cpu, tmp); 241 } 242 } 243 244 bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req, 245 unsigned long *vcpu_bitmap) 246 { 247 struct kvm_vcpu *vcpu; 248 struct cpumask *cpus; 249 int i, me; 250 bool called; 251 252 me = get_cpu(); 253 254 cpus = this_cpu_cpumask_var_ptr(cpu_kick_mask); 255 cpumask_clear(cpus); 256 257 for_each_set_bit(i, vcpu_bitmap, KVM_MAX_VCPUS) { 258 vcpu = kvm_get_vcpu(kvm, i); 259 if (!vcpu) 260 continue; 261 kvm_make_vcpu_request(vcpu, req, cpus, me); 262 } 263 264 called = kvm_kick_many_cpus(cpus, !!(req & KVM_REQUEST_WAIT)); 265 put_cpu(); 266 267 return called; 268 } 269 270 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req) 271 { 272 struct kvm_vcpu *vcpu; 273 struct cpumask *cpus; 274 unsigned long i; 275 bool called; 276 int me; 277 278 me = get_cpu(); 279 280 cpus = this_cpu_cpumask_var_ptr(cpu_kick_mask); 281 cpumask_clear(cpus); 282 283 kvm_for_each_vcpu(i, vcpu, kvm) 284 kvm_make_vcpu_request(vcpu, req, cpus, me); 285 286 called = kvm_kick_many_cpus(cpus, !!(req & KVM_REQUEST_WAIT)); 287 put_cpu(); 288 289 return called; 290 } 291 EXPORT_SYMBOL_GPL(kvm_make_all_cpus_request); 292 293 void kvm_flush_remote_tlbs(struct kvm *kvm) 294 { 295 ++kvm->stat.generic.remote_tlb_flush_requests; 296 297 /* 298 * We want to publish modifications to the page tables before reading 299 * mode. Pairs with a memory barrier in arch-specific code. 300 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest 301 * and smp_mb in walk_shadow_page_lockless_begin/end. 302 * - powerpc: smp_mb in kvmppc_prepare_to_enter. 303 * 304 * There is already an smp_mb__after_atomic() before 305 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that 306 * barrier here. 307 */ 308 if (!kvm_arch_flush_remote_tlbs(kvm) 309 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH)) 310 ++kvm->stat.generic.remote_tlb_flush; 311 } 312 EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs); 313 314 void kvm_flush_remote_tlbs_range(struct kvm *kvm, gfn_t gfn, u64 nr_pages) 315 { 316 if (!kvm_arch_flush_remote_tlbs_range(kvm, gfn, nr_pages)) 317 return; 318 319 /* 320 * Fall back to a flushing entire TLBs if the architecture range-based 321 * TLB invalidation is unsupported or can't be performed for whatever 322 * reason. 323 */ 324 kvm_flush_remote_tlbs(kvm); 325 } 326 327 void kvm_flush_remote_tlbs_memslot(struct kvm *kvm, 328 const struct kvm_memory_slot *memslot) 329 { 330 /* 331 * All current use cases for flushing the TLBs for a specific memslot 332 * are related to dirty logging, and many do the TLB flush out of 333 * mmu_lock. The interaction between the various operations on memslot 334 * must be serialized by slots_locks to ensure the TLB flush from one 335 * operation is observed by any other operation on the same memslot. 336 */ 337 lockdep_assert_held(&kvm->slots_lock); 338 kvm_flush_remote_tlbs_range(kvm, memslot->base_gfn, memslot->npages); 339 } 340 341 static void kvm_flush_shadow_all(struct kvm *kvm) 342 { 343 kvm_arch_flush_shadow_all(kvm); 344 kvm_arch_guest_memory_reclaimed(kvm); 345 } 346 347 #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE 348 static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc, 349 gfp_t gfp_flags) 350 { 351 void *page; 352 353 gfp_flags |= mc->gfp_zero; 354 355 if (mc->kmem_cache) 356 return kmem_cache_alloc(mc->kmem_cache, gfp_flags); 357 358 page = (void *)__get_free_page(gfp_flags); 359 if (page && mc->init_value) 360 memset64(page, mc->init_value, PAGE_SIZE / sizeof(u64)); 361 return page; 362 } 363 364 int __kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int capacity, int min) 365 { 366 gfp_t gfp = mc->gfp_custom ? mc->gfp_custom : GFP_KERNEL_ACCOUNT; 367 void *obj; 368 369 if (mc->nobjs >= min) 370 return 0; 371 372 if (unlikely(!mc->objects)) { 373 if (WARN_ON_ONCE(!capacity)) 374 return -EIO; 375 376 /* 377 * Custom init values can be used only for page allocations, 378 * and obviously conflict with __GFP_ZERO. 379 */ 380 if (WARN_ON_ONCE(mc->init_value && (mc->kmem_cache || mc->gfp_zero))) 381 return -EIO; 382 383 mc->objects = kvmalloc_array(capacity, sizeof(void *), gfp); 384 if (!mc->objects) 385 return -ENOMEM; 386 387 mc->capacity = capacity; 388 } 389 390 /* It is illegal to request a different capacity across topups. */ 391 if (WARN_ON_ONCE(mc->capacity != capacity)) 392 return -EIO; 393 394 while (mc->nobjs < mc->capacity) { 395 obj = mmu_memory_cache_alloc_obj(mc, gfp); 396 if (!obj) 397 return mc->nobjs >= min ? 0 : -ENOMEM; 398 mc->objects[mc->nobjs++] = obj; 399 } 400 return 0; 401 } 402 403 int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min) 404 { 405 return __kvm_mmu_topup_memory_cache(mc, KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE, min); 406 } 407 408 int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc) 409 { 410 return mc->nobjs; 411 } 412 413 void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc) 414 { 415 while (mc->nobjs) { 416 if (mc->kmem_cache) 417 kmem_cache_free(mc->kmem_cache, mc->objects[--mc->nobjs]); 418 else 419 free_page((unsigned long)mc->objects[--mc->nobjs]); 420 } 421 422 kvfree(mc->objects); 423 424 mc->objects = NULL; 425 mc->capacity = 0; 426 } 427 428 void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc) 429 { 430 void *p; 431 432 if (WARN_ON(!mc->nobjs)) 433 p = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT); 434 else 435 p = mc->objects[--mc->nobjs]; 436 BUG_ON(!p); 437 return p; 438 } 439 #endif 440 441 static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id) 442 { 443 mutex_init(&vcpu->mutex); 444 vcpu->cpu = -1; 445 vcpu->kvm = kvm; 446 vcpu->vcpu_id = id; 447 vcpu->pid = NULL; 448 rwlock_init(&vcpu->pid_lock); 449 #ifndef __KVM_HAVE_ARCH_WQP 450 rcuwait_init(&vcpu->wait); 451 #endif 452 kvm_async_pf_vcpu_init(vcpu); 453 454 kvm_vcpu_set_in_spin_loop(vcpu, false); 455 kvm_vcpu_set_dy_eligible(vcpu, false); 456 vcpu->preempted = false; 457 vcpu->ready = false; 458 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops); 459 vcpu->last_used_slot = NULL; 460 461 /* Fill the stats id string for the vcpu */ 462 snprintf(vcpu->stats_id, sizeof(vcpu->stats_id), "kvm-%d/vcpu-%d", 463 task_pid_nr(current), id); 464 } 465 466 static void kvm_vcpu_destroy(struct kvm_vcpu *vcpu) 467 { 468 kvm_arch_vcpu_destroy(vcpu); 469 kvm_dirty_ring_free(&vcpu->dirty_ring); 470 471 /* 472 * No need for rcu_read_lock as VCPU_RUN is the only place that changes 473 * the vcpu->pid pointer, and at destruction time all file descriptors 474 * are already gone. 475 */ 476 put_pid(vcpu->pid); 477 478 free_page((unsigned long)vcpu->run); 479 kmem_cache_free(kvm_vcpu_cache, vcpu); 480 } 481 482 void kvm_destroy_vcpus(struct kvm *kvm) 483 { 484 unsigned long i; 485 struct kvm_vcpu *vcpu; 486 487 kvm_for_each_vcpu(i, vcpu, kvm) { 488 kvm_vcpu_destroy(vcpu); 489 xa_erase(&kvm->vcpu_array, i); 490 491 /* 492 * Assert that the vCPU isn't visible in any way, to ensure KVM 493 * doesn't trigger a use-after-free if destroying vCPUs results 494 * in VM-wide request, e.g. to flush remote TLBs when tearing 495 * down MMUs, or to mark the VM dead if a KVM_BUG_ON() fires. 496 */ 497 WARN_ON_ONCE(xa_load(&kvm->vcpu_array, i) || kvm_get_vcpu(kvm, i)); 498 } 499 500 atomic_set(&kvm->online_vcpus, 0); 501 } 502 EXPORT_SYMBOL_GPL(kvm_destroy_vcpus); 503 504 #ifdef CONFIG_KVM_GENERIC_MMU_NOTIFIER 505 static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn) 506 { 507 return container_of(mn, struct kvm, mmu_notifier); 508 } 509 510 typedef bool (*gfn_handler_t)(struct kvm *kvm, struct kvm_gfn_range *range); 511 512 typedef void (*on_lock_fn_t)(struct kvm *kvm); 513 514 struct kvm_mmu_notifier_range { 515 /* 516 * 64-bit addresses, as KVM notifiers can operate on host virtual 517 * addresses (unsigned long) and guest physical addresses (64-bit). 518 */ 519 u64 start; 520 u64 end; 521 union kvm_mmu_notifier_arg arg; 522 gfn_handler_t handler; 523 on_lock_fn_t on_lock; 524 bool flush_on_ret; 525 bool may_block; 526 bool lockless; 527 }; 528 529 /* 530 * The inner-most helper returns a tuple containing the return value from the 531 * arch- and action-specific handler, plus a flag indicating whether or not at 532 * least one memslot was found, i.e. if the handler found guest memory. 533 * 534 * Note, most notifiers are averse to booleans, so even though KVM tracks the 535 * return from arch code as a bool, outer helpers will cast it to an int. :-( 536 */ 537 typedef struct kvm_mmu_notifier_return { 538 bool ret; 539 bool found_memslot; 540 } kvm_mn_ret_t; 541 542 /* 543 * Use a dedicated stub instead of NULL to indicate that there is no callback 544 * function/handler. The compiler technically can't guarantee that a real 545 * function will have a non-zero address, and so it will generate code to 546 * check for !NULL, whereas comparing against a stub will be elided at compile 547 * time (unless the compiler is getting long in the tooth, e.g. gcc 4.9). 548 */ 549 static void kvm_null_fn(void) 550 { 551 552 } 553 #define IS_KVM_NULL_FN(fn) ((fn) == (void *)kvm_null_fn) 554 555 /* Iterate over each memslot intersecting [start, last] (inclusive) range */ 556 #define kvm_for_each_memslot_in_hva_range(node, slots, start, last) \ 557 for (node = interval_tree_iter_first(&slots->hva_tree, start, last); \ 558 node; \ 559 node = interval_tree_iter_next(node, start, last)) \ 560 561 static __always_inline kvm_mn_ret_t kvm_handle_hva_range(struct kvm *kvm, 562 const struct kvm_mmu_notifier_range *range) 563 { 564 struct kvm_mmu_notifier_return r = { 565 .ret = false, 566 .found_memslot = false, 567 }; 568 struct kvm_gfn_range gfn_range; 569 struct kvm_memory_slot *slot; 570 struct kvm_memslots *slots; 571 int i, idx; 572 573 if (WARN_ON_ONCE(range->end <= range->start)) 574 return r; 575 576 /* A null handler is allowed if and only if on_lock() is provided. */ 577 if (WARN_ON_ONCE(IS_KVM_NULL_FN(range->on_lock) && 578 IS_KVM_NULL_FN(range->handler))) 579 return r; 580 581 /* on_lock will never be called for lockless walks */ 582 if (WARN_ON_ONCE(range->lockless && !IS_KVM_NULL_FN(range->on_lock))) 583 return r; 584 585 idx = srcu_read_lock(&kvm->srcu); 586 587 for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) { 588 struct interval_tree_node *node; 589 590 slots = __kvm_memslots(kvm, i); 591 kvm_for_each_memslot_in_hva_range(node, slots, 592 range->start, range->end - 1) { 593 unsigned long hva_start, hva_end; 594 595 slot = container_of(node, struct kvm_memory_slot, hva_node[slots->node_idx]); 596 hva_start = max_t(unsigned long, range->start, slot->userspace_addr); 597 hva_end = min_t(unsigned long, range->end, 598 slot->userspace_addr + (slot->npages << PAGE_SHIFT)); 599 600 /* 601 * To optimize for the likely case where the address 602 * range is covered by zero or one memslots, don't 603 * bother making these conditional (to avoid writes on 604 * the second or later invocation of the handler). 605 */ 606 gfn_range.arg = range->arg; 607 gfn_range.may_block = range->may_block; 608 /* 609 * HVA-based notifications aren't relevant to private 610 * mappings as they don't have a userspace mapping. 611 */ 612 gfn_range.attr_filter = KVM_FILTER_SHARED; 613 614 /* 615 * {gfn(page) | page intersects with [hva_start, hva_end)} = 616 * {gfn_start, gfn_start+1, ..., gfn_end-1}. 617 */ 618 gfn_range.start = hva_to_gfn_memslot(hva_start, slot); 619 gfn_range.end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, slot); 620 gfn_range.slot = slot; 621 gfn_range.lockless = range->lockless; 622 623 if (!r.found_memslot) { 624 r.found_memslot = true; 625 if (!range->lockless) { 626 KVM_MMU_LOCK(kvm); 627 if (!IS_KVM_NULL_FN(range->on_lock)) 628 range->on_lock(kvm); 629 630 if (IS_KVM_NULL_FN(range->handler)) 631 goto mmu_unlock; 632 } 633 } 634 r.ret |= range->handler(kvm, &gfn_range); 635 } 636 } 637 638 if (range->flush_on_ret && r.ret) 639 kvm_flush_remote_tlbs(kvm); 640 641 mmu_unlock: 642 if (r.found_memslot && !range->lockless) 643 KVM_MMU_UNLOCK(kvm); 644 645 srcu_read_unlock(&kvm->srcu, idx); 646 647 return r; 648 } 649 650 static __always_inline int kvm_age_hva_range(struct mmu_notifier *mn, 651 unsigned long start, 652 unsigned long end, 653 gfn_handler_t handler, 654 bool flush_on_ret) 655 { 656 struct kvm *kvm = mmu_notifier_to_kvm(mn); 657 const struct kvm_mmu_notifier_range range = { 658 .start = start, 659 .end = end, 660 .handler = handler, 661 .on_lock = (void *)kvm_null_fn, 662 .flush_on_ret = flush_on_ret, 663 .may_block = false, 664 .lockless = IS_ENABLED(CONFIG_KVM_MMU_LOCKLESS_AGING), 665 }; 666 667 return kvm_handle_hva_range(kvm, &range).ret; 668 } 669 670 static __always_inline int kvm_age_hva_range_no_flush(struct mmu_notifier *mn, 671 unsigned long start, 672 unsigned long end, 673 gfn_handler_t handler) 674 { 675 return kvm_age_hva_range(mn, start, end, handler, false); 676 } 677 678 void kvm_mmu_invalidate_begin(struct kvm *kvm) 679 { 680 lockdep_assert_held_write(&kvm->mmu_lock); 681 /* 682 * The count increase must become visible at unlock time as no 683 * spte can be established without taking the mmu_lock and 684 * count is also read inside the mmu_lock critical section. 685 */ 686 kvm->mmu_invalidate_in_progress++; 687 688 if (likely(kvm->mmu_invalidate_in_progress == 1)) { 689 kvm->mmu_invalidate_range_start = INVALID_GPA; 690 kvm->mmu_invalidate_range_end = INVALID_GPA; 691 } 692 } 693 694 void kvm_mmu_invalidate_range_add(struct kvm *kvm, gfn_t start, gfn_t end) 695 { 696 lockdep_assert_held_write(&kvm->mmu_lock); 697 698 WARN_ON_ONCE(!kvm->mmu_invalidate_in_progress); 699 700 if (likely(kvm->mmu_invalidate_range_start == INVALID_GPA)) { 701 kvm->mmu_invalidate_range_start = start; 702 kvm->mmu_invalidate_range_end = end; 703 } else { 704 /* 705 * Fully tracking multiple concurrent ranges has diminishing 706 * returns. Keep things simple and just find the minimal range 707 * which includes the current and new ranges. As there won't be 708 * enough information to subtract a range after its invalidate 709 * completes, any ranges invalidated concurrently will 710 * accumulate and persist until all outstanding invalidates 711 * complete. 712 */ 713 kvm->mmu_invalidate_range_start = 714 min(kvm->mmu_invalidate_range_start, start); 715 kvm->mmu_invalidate_range_end = 716 max(kvm->mmu_invalidate_range_end, end); 717 } 718 } 719 720 bool kvm_mmu_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range) 721 { 722 kvm_mmu_invalidate_range_add(kvm, range->start, range->end); 723 return kvm_unmap_gfn_range(kvm, range); 724 } 725 726 static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn, 727 const struct mmu_notifier_range *range) 728 { 729 struct kvm *kvm = mmu_notifier_to_kvm(mn); 730 const struct kvm_mmu_notifier_range hva_range = { 731 .start = range->start, 732 .end = range->end, 733 .handler = kvm_mmu_unmap_gfn_range, 734 .on_lock = kvm_mmu_invalidate_begin, 735 .flush_on_ret = true, 736 .may_block = mmu_notifier_range_blockable(range), 737 }; 738 739 trace_kvm_unmap_hva_range(range->start, range->end); 740 741 /* 742 * Prevent memslot modification between range_start() and range_end() 743 * so that conditionally locking provides the same result in both 744 * functions. Without that guarantee, the mmu_invalidate_in_progress 745 * adjustments will be imbalanced. 746 * 747 * Pairs with the decrement in range_end(). 748 */ 749 spin_lock(&kvm->mn_invalidate_lock); 750 kvm->mn_active_invalidate_count++; 751 spin_unlock(&kvm->mn_invalidate_lock); 752 753 /* 754 * Invalidate pfn caches _before_ invalidating the secondary MMUs, i.e. 755 * before acquiring mmu_lock, to avoid holding mmu_lock while acquiring 756 * each cache's lock. There are relatively few caches in existence at 757 * any given time, and the caches themselves can check for hva overlap, 758 * i.e. don't need to rely on memslot overlap checks for performance. 759 * Because this runs without holding mmu_lock, the pfn caches must use 760 * mn_active_invalidate_count (see above) instead of 761 * mmu_invalidate_in_progress. 762 */ 763 gfn_to_pfn_cache_invalidate_start(kvm, range->start, range->end); 764 765 /* 766 * If one or more memslots were found and thus zapped, notify arch code 767 * that guest memory has been reclaimed. This needs to be done *after* 768 * dropping mmu_lock, as x86's reclaim path is slooooow. 769 */ 770 if (kvm_handle_hva_range(kvm, &hva_range).found_memslot) 771 kvm_arch_guest_memory_reclaimed(kvm); 772 773 return 0; 774 } 775 776 void kvm_mmu_invalidate_end(struct kvm *kvm) 777 { 778 lockdep_assert_held_write(&kvm->mmu_lock); 779 780 /* 781 * This sequence increase will notify the kvm page fault that 782 * the page that is going to be mapped in the spte could have 783 * been freed. 784 */ 785 kvm->mmu_invalidate_seq++; 786 smp_wmb(); 787 /* 788 * The above sequence increase must be visible before the 789 * below count decrease, which is ensured by the smp_wmb above 790 * in conjunction with the smp_rmb in mmu_invalidate_retry(). 791 */ 792 kvm->mmu_invalidate_in_progress--; 793 KVM_BUG_ON(kvm->mmu_invalidate_in_progress < 0, kvm); 794 795 /* 796 * Assert that at least one range was added between start() and end(). 797 * Not adding a range isn't fatal, but it is a KVM bug. 798 */ 799 WARN_ON_ONCE(kvm->mmu_invalidate_range_start == INVALID_GPA); 800 } 801 802 static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn, 803 const struct mmu_notifier_range *range) 804 { 805 struct kvm *kvm = mmu_notifier_to_kvm(mn); 806 const struct kvm_mmu_notifier_range hva_range = { 807 .start = range->start, 808 .end = range->end, 809 .handler = (void *)kvm_null_fn, 810 .on_lock = kvm_mmu_invalidate_end, 811 .flush_on_ret = false, 812 .may_block = mmu_notifier_range_blockable(range), 813 }; 814 bool wake; 815 816 kvm_handle_hva_range(kvm, &hva_range); 817 818 /* Pairs with the increment in range_start(). */ 819 spin_lock(&kvm->mn_invalidate_lock); 820 if (!WARN_ON_ONCE(!kvm->mn_active_invalidate_count)) 821 --kvm->mn_active_invalidate_count; 822 wake = !kvm->mn_active_invalidate_count; 823 spin_unlock(&kvm->mn_invalidate_lock); 824 825 /* 826 * There can only be one waiter, since the wait happens under 827 * slots_lock. 828 */ 829 if (wake) 830 rcuwait_wake_up(&kvm->mn_memslots_update_rcuwait); 831 } 832 833 static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn, 834 struct mm_struct *mm, 835 unsigned long start, 836 unsigned long end) 837 { 838 trace_kvm_age_hva(start, end); 839 840 return kvm_age_hva_range(mn, start, end, kvm_age_gfn, 841 !IS_ENABLED(CONFIG_KVM_ELIDE_TLB_FLUSH_IF_YOUNG)); 842 } 843 844 static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn, 845 struct mm_struct *mm, 846 unsigned long start, 847 unsigned long end) 848 { 849 trace_kvm_age_hva(start, end); 850 851 /* 852 * Even though we do not flush TLB, this will still adversely 853 * affect performance on pre-Haswell Intel EPT, where there is 854 * no EPT Access Bit to clear so that we have to tear down EPT 855 * tables instead. If we find this unacceptable, we can always 856 * add a parameter to kvm_age_hva so that it effectively doesn't 857 * do anything on clear_young. 858 * 859 * Also note that currently we never issue secondary TLB flushes 860 * from clear_young, leaving this job up to the regular system 861 * cadence. If we find this inaccurate, we might come up with a 862 * more sophisticated heuristic later. 863 */ 864 return kvm_age_hva_range_no_flush(mn, start, end, kvm_age_gfn); 865 } 866 867 static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn, 868 struct mm_struct *mm, 869 unsigned long address) 870 { 871 trace_kvm_test_age_hva(address); 872 873 return kvm_age_hva_range_no_flush(mn, address, address + 1, 874 kvm_test_age_gfn); 875 } 876 877 static void kvm_mmu_notifier_release(struct mmu_notifier *mn, 878 struct mm_struct *mm) 879 { 880 struct kvm *kvm = mmu_notifier_to_kvm(mn); 881 int idx; 882 883 idx = srcu_read_lock(&kvm->srcu); 884 kvm_flush_shadow_all(kvm); 885 srcu_read_unlock(&kvm->srcu, idx); 886 } 887 888 static const struct mmu_notifier_ops kvm_mmu_notifier_ops = { 889 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start, 890 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end, 891 .clear_flush_young = kvm_mmu_notifier_clear_flush_young, 892 .clear_young = kvm_mmu_notifier_clear_young, 893 .test_young = kvm_mmu_notifier_test_young, 894 .release = kvm_mmu_notifier_release, 895 }; 896 897 static int kvm_init_mmu_notifier(struct kvm *kvm) 898 { 899 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops; 900 return mmu_notifier_register(&kvm->mmu_notifier, current->mm); 901 } 902 903 #else /* !CONFIG_KVM_GENERIC_MMU_NOTIFIER */ 904 905 static int kvm_init_mmu_notifier(struct kvm *kvm) 906 { 907 return 0; 908 } 909 910 #endif /* CONFIG_KVM_GENERIC_MMU_NOTIFIER */ 911 912 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER 913 static int kvm_pm_notifier_call(struct notifier_block *bl, 914 unsigned long state, 915 void *unused) 916 { 917 struct kvm *kvm = container_of(bl, struct kvm, pm_notifier); 918 919 return kvm_arch_pm_notifier(kvm, state); 920 } 921 922 static void kvm_init_pm_notifier(struct kvm *kvm) 923 { 924 kvm->pm_notifier.notifier_call = kvm_pm_notifier_call; 925 /* Suspend KVM before we suspend ftrace, RCU, etc. */ 926 kvm->pm_notifier.priority = INT_MAX; 927 register_pm_notifier(&kvm->pm_notifier); 928 } 929 930 static void kvm_destroy_pm_notifier(struct kvm *kvm) 931 { 932 unregister_pm_notifier(&kvm->pm_notifier); 933 } 934 #else /* !CONFIG_HAVE_KVM_PM_NOTIFIER */ 935 static void kvm_init_pm_notifier(struct kvm *kvm) 936 { 937 } 938 939 static void kvm_destroy_pm_notifier(struct kvm *kvm) 940 { 941 } 942 #endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */ 943 944 static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot) 945 { 946 if (!memslot->dirty_bitmap) 947 return; 948 949 vfree(memslot->dirty_bitmap); 950 memslot->dirty_bitmap = NULL; 951 } 952 953 /* This does not remove the slot from struct kvm_memslots data structures */ 954 static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot) 955 { 956 if (slot->flags & KVM_MEM_GUEST_MEMFD) 957 kvm_gmem_unbind(slot); 958 959 kvm_destroy_dirty_bitmap(slot); 960 961 kvm_arch_free_memslot(kvm, slot); 962 963 kfree(slot); 964 } 965 966 static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots) 967 { 968 struct hlist_node *idnode; 969 struct kvm_memory_slot *memslot; 970 int bkt; 971 972 /* 973 * The same memslot objects live in both active and inactive sets, 974 * arbitrarily free using index '1' so the second invocation of this 975 * function isn't operating over a structure with dangling pointers 976 * (even though this function isn't actually touching them). 977 */ 978 if (!slots->node_idx) 979 return; 980 981 hash_for_each_safe(slots->id_hash, bkt, idnode, memslot, id_node[1]) 982 kvm_free_memslot(kvm, memslot); 983 } 984 985 static umode_t kvm_stats_debugfs_mode(const struct _kvm_stats_desc *pdesc) 986 { 987 switch (pdesc->desc.flags & KVM_STATS_TYPE_MASK) { 988 case KVM_STATS_TYPE_INSTANT: 989 return 0444; 990 case KVM_STATS_TYPE_CUMULATIVE: 991 case KVM_STATS_TYPE_PEAK: 992 default: 993 return 0644; 994 } 995 } 996 997 998 static void kvm_destroy_vm_debugfs(struct kvm *kvm) 999 { 1000 int i; 1001 int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc + 1002 kvm_vcpu_stats_header.num_desc; 1003 1004 if (IS_ERR(kvm->debugfs_dentry)) 1005 return; 1006 1007 debugfs_remove_recursive(kvm->debugfs_dentry); 1008 1009 if (kvm->debugfs_stat_data) { 1010 for (i = 0; i < kvm_debugfs_num_entries; i++) 1011 kfree(kvm->debugfs_stat_data[i]); 1012 kfree(kvm->debugfs_stat_data); 1013 } 1014 } 1015 1016 static int kvm_create_vm_debugfs(struct kvm *kvm, const char *fdname) 1017 { 1018 static DEFINE_MUTEX(kvm_debugfs_lock); 1019 struct dentry *dent; 1020 char dir_name[ITOA_MAX_LEN * 2]; 1021 struct kvm_stat_data *stat_data; 1022 const struct _kvm_stats_desc *pdesc; 1023 int i, ret = -ENOMEM; 1024 int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc + 1025 kvm_vcpu_stats_header.num_desc; 1026 1027 if (!debugfs_initialized()) 1028 return 0; 1029 1030 snprintf(dir_name, sizeof(dir_name), "%d-%s", task_pid_nr(current), fdname); 1031 mutex_lock(&kvm_debugfs_lock); 1032 dent = debugfs_lookup(dir_name, kvm_debugfs_dir); 1033 if (dent) { 1034 pr_warn_ratelimited("KVM: debugfs: duplicate directory %s\n", dir_name); 1035 dput(dent); 1036 mutex_unlock(&kvm_debugfs_lock); 1037 return 0; 1038 } 1039 dent = debugfs_create_dir(dir_name, kvm_debugfs_dir); 1040 mutex_unlock(&kvm_debugfs_lock); 1041 if (IS_ERR(dent)) 1042 return 0; 1043 1044 kvm->debugfs_dentry = dent; 1045 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries, 1046 sizeof(*kvm->debugfs_stat_data), 1047 GFP_KERNEL_ACCOUNT); 1048 if (!kvm->debugfs_stat_data) 1049 goto out_err; 1050 1051 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) { 1052 pdesc = &kvm_vm_stats_desc[i]; 1053 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT); 1054 if (!stat_data) 1055 goto out_err; 1056 1057 stat_data->kvm = kvm; 1058 stat_data->desc = pdesc; 1059 stat_data->kind = KVM_STAT_VM; 1060 kvm->debugfs_stat_data[i] = stat_data; 1061 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc), 1062 kvm->debugfs_dentry, stat_data, 1063 &stat_fops_per_vm); 1064 } 1065 1066 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) { 1067 pdesc = &kvm_vcpu_stats_desc[i]; 1068 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT); 1069 if (!stat_data) 1070 goto out_err; 1071 1072 stat_data->kvm = kvm; 1073 stat_data->desc = pdesc; 1074 stat_data->kind = KVM_STAT_VCPU; 1075 kvm->debugfs_stat_data[i + kvm_vm_stats_header.num_desc] = stat_data; 1076 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc), 1077 kvm->debugfs_dentry, stat_data, 1078 &stat_fops_per_vm); 1079 } 1080 1081 kvm_arch_create_vm_debugfs(kvm); 1082 return 0; 1083 out_err: 1084 kvm_destroy_vm_debugfs(kvm); 1085 return ret; 1086 } 1087 1088 /* 1089 * Called just after removing the VM from the vm_list, but before doing any 1090 * other destruction. 1091 */ 1092 void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm) 1093 { 1094 } 1095 1096 /* 1097 * Called after per-vm debugfs created. When called kvm->debugfs_dentry should 1098 * be setup already, so we can create arch-specific debugfs entries under it. 1099 * Cleanup should be automatic done in kvm_destroy_vm_debugfs() recursively, so 1100 * a per-arch destroy interface is not needed. 1101 */ 1102 void __weak kvm_arch_create_vm_debugfs(struct kvm *kvm) 1103 { 1104 } 1105 1106 static struct kvm *kvm_create_vm(unsigned long type, const char *fdname) 1107 { 1108 struct kvm *kvm = kvm_arch_alloc_vm(); 1109 struct kvm_memslots *slots; 1110 int r, i, j; 1111 1112 if (!kvm) 1113 return ERR_PTR(-ENOMEM); 1114 1115 KVM_MMU_LOCK_INIT(kvm); 1116 mmgrab(current->mm); 1117 kvm->mm = current->mm; 1118 kvm_eventfd_init(kvm); 1119 mutex_init(&kvm->lock); 1120 mutex_init(&kvm->irq_lock); 1121 mutex_init(&kvm->slots_lock); 1122 mutex_init(&kvm->slots_arch_lock); 1123 spin_lock_init(&kvm->mn_invalidate_lock); 1124 rcuwait_init(&kvm->mn_memslots_update_rcuwait); 1125 xa_init(&kvm->vcpu_array); 1126 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES 1127 xa_init(&kvm->mem_attr_array); 1128 #endif 1129 1130 INIT_LIST_HEAD(&kvm->gpc_list); 1131 spin_lock_init(&kvm->gpc_lock); 1132 1133 INIT_LIST_HEAD(&kvm->devices); 1134 kvm->max_vcpus = KVM_MAX_VCPUS; 1135 1136 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX); 1137 1138 /* 1139 * Force subsequent debugfs file creations to fail if the VM directory 1140 * is not created (by kvm_create_vm_debugfs()). 1141 */ 1142 kvm->debugfs_dentry = ERR_PTR(-ENOENT); 1143 1144 snprintf(kvm->stats_id, sizeof(kvm->stats_id), "kvm-%d", 1145 task_pid_nr(current)); 1146 1147 r = -ENOMEM; 1148 if (init_srcu_struct(&kvm->srcu)) 1149 goto out_err_no_srcu; 1150 if (init_srcu_struct(&kvm->irq_srcu)) 1151 goto out_err_no_irq_srcu; 1152 1153 r = kvm_init_irq_routing(kvm); 1154 if (r) 1155 goto out_err_no_irq_routing; 1156 1157 refcount_set(&kvm->users_count, 1); 1158 1159 for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) { 1160 for (j = 0; j < 2; j++) { 1161 slots = &kvm->__memslots[i][j]; 1162 1163 atomic_long_set(&slots->last_used_slot, (unsigned long)NULL); 1164 slots->hva_tree = RB_ROOT_CACHED; 1165 slots->gfn_tree = RB_ROOT; 1166 hash_init(slots->id_hash); 1167 slots->node_idx = j; 1168 1169 /* Generations must be different for each address space. */ 1170 slots->generation = i; 1171 } 1172 1173 rcu_assign_pointer(kvm->memslots[i], &kvm->__memslots[i][0]); 1174 } 1175 1176 r = -ENOMEM; 1177 for (i = 0; i < KVM_NR_BUSES; i++) { 1178 rcu_assign_pointer(kvm->buses[i], 1179 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT)); 1180 if (!kvm->buses[i]) 1181 goto out_err_no_arch_destroy_vm; 1182 } 1183 1184 r = kvm_arch_init_vm(kvm, type); 1185 if (r) 1186 goto out_err_no_arch_destroy_vm; 1187 1188 r = kvm_enable_virtualization(); 1189 if (r) 1190 goto out_err_no_disable; 1191 1192 #ifdef CONFIG_HAVE_KVM_IRQCHIP 1193 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list); 1194 #endif 1195 1196 r = kvm_init_mmu_notifier(kvm); 1197 if (r) 1198 goto out_err_no_mmu_notifier; 1199 1200 r = kvm_coalesced_mmio_init(kvm); 1201 if (r < 0) 1202 goto out_no_coalesced_mmio; 1203 1204 r = kvm_create_vm_debugfs(kvm, fdname); 1205 if (r) 1206 goto out_err_no_debugfs; 1207 1208 mutex_lock(&kvm_lock); 1209 list_add(&kvm->vm_list, &vm_list); 1210 mutex_unlock(&kvm_lock); 1211 1212 preempt_notifier_inc(); 1213 kvm_init_pm_notifier(kvm); 1214 1215 return kvm; 1216 1217 out_err_no_debugfs: 1218 kvm_coalesced_mmio_free(kvm); 1219 out_no_coalesced_mmio: 1220 #ifdef CONFIG_KVM_GENERIC_MMU_NOTIFIER 1221 if (kvm->mmu_notifier.ops) 1222 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm); 1223 #endif 1224 out_err_no_mmu_notifier: 1225 kvm_disable_virtualization(); 1226 out_err_no_disable: 1227 kvm_arch_destroy_vm(kvm); 1228 out_err_no_arch_destroy_vm: 1229 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count)); 1230 for (i = 0; i < KVM_NR_BUSES; i++) 1231 kfree(kvm_get_bus(kvm, i)); 1232 kvm_free_irq_routing(kvm); 1233 out_err_no_irq_routing: 1234 cleanup_srcu_struct(&kvm->irq_srcu); 1235 out_err_no_irq_srcu: 1236 cleanup_srcu_struct(&kvm->srcu); 1237 out_err_no_srcu: 1238 kvm_arch_free_vm(kvm); 1239 mmdrop(current->mm); 1240 return ERR_PTR(r); 1241 } 1242 1243 static void kvm_destroy_devices(struct kvm *kvm) 1244 { 1245 struct kvm_device *dev, *tmp; 1246 1247 /* 1248 * We do not need to take the kvm->lock here, because nobody else 1249 * has a reference to the struct kvm at this point and therefore 1250 * cannot access the devices list anyhow. 1251 * 1252 * The device list is generally managed as an rculist, but list_del() 1253 * is used intentionally here. If a bug in KVM introduced a reader that 1254 * was not backed by a reference on the kvm struct, the hope is that 1255 * it'd consume the poisoned forward pointer instead of suffering a 1256 * use-after-free, even though this cannot be guaranteed. 1257 */ 1258 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) { 1259 list_del(&dev->vm_node); 1260 dev->ops->destroy(dev); 1261 } 1262 } 1263 1264 static void kvm_destroy_vm(struct kvm *kvm) 1265 { 1266 int i; 1267 struct mm_struct *mm = kvm->mm; 1268 1269 kvm_destroy_pm_notifier(kvm); 1270 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm); 1271 kvm_destroy_vm_debugfs(kvm); 1272 mutex_lock(&kvm_lock); 1273 list_del(&kvm->vm_list); 1274 mutex_unlock(&kvm_lock); 1275 kvm_arch_pre_destroy_vm(kvm); 1276 1277 kvm_free_irq_routing(kvm); 1278 for (i = 0; i < KVM_NR_BUSES; i++) { 1279 struct kvm_io_bus *bus = kvm_get_bus(kvm, i); 1280 1281 if (bus) 1282 kvm_io_bus_destroy(bus); 1283 kvm->buses[i] = NULL; 1284 } 1285 kvm_coalesced_mmio_free(kvm); 1286 #ifdef CONFIG_KVM_GENERIC_MMU_NOTIFIER 1287 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm); 1288 /* 1289 * At this point, pending calls to invalidate_range_start() 1290 * have completed but no more MMU notifiers will run, so 1291 * mn_active_invalidate_count may remain unbalanced. 1292 * No threads can be waiting in kvm_swap_active_memslots() as the 1293 * last reference on KVM has been dropped, but freeing 1294 * memslots would deadlock without this manual intervention. 1295 * 1296 * If the count isn't unbalanced, i.e. KVM did NOT unregister its MMU 1297 * notifier between a start() and end(), then there shouldn't be any 1298 * in-progress invalidations. 1299 */ 1300 WARN_ON(rcuwait_active(&kvm->mn_memslots_update_rcuwait)); 1301 if (kvm->mn_active_invalidate_count) 1302 kvm->mn_active_invalidate_count = 0; 1303 else 1304 WARN_ON(kvm->mmu_invalidate_in_progress); 1305 #else 1306 kvm_flush_shadow_all(kvm); 1307 #endif 1308 kvm_arch_destroy_vm(kvm); 1309 kvm_destroy_devices(kvm); 1310 for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) { 1311 kvm_free_memslots(kvm, &kvm->__memslots[i][0]); 1312 kvm_free_memslots(kvm, &kvm->__memslots[i][1]); 1313 } 1314 cleanup_srcu_struct(&kvm->irq_srcu); 1315 cleanup_srcu_struct(&kvm->srcu); 1316 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES 1317 xa_destroy(&kvm->mem_attr_array); 1318 #endif 1319 kvm_arch_free_vm(kvm); 1320 preempt_notifier_dec(); 1321 kvm_disable_virtualization(); 1322 mmdrop(mm); 1323 } 1324 1325 void kvm_get_kvm(struct kvm *kvm) 1326 { 1327 refcount_inc(&kvm->users_count); 1328 } 1329 EXPORT_SYMBOL_GPL(kvm_get_kvm); 1330 1331 /* 1332 * Make sure the vm is not during destruction, which is a safe version of 1333 * kvm_get_kvm(). Return true if kvm referenced successfully, false otherwise. 1334 */ 1335 bool kvm_get_kvm_safe(struct kvm *kvm) 1336 { 1337 return refcount_inc_not_zero(&kvm->users_count); 1338 } 1339 EXPORT_SYMBOL_GPL(kvm_get_kvm_safe); 1340 1341 void kvm_put_kvm(struct kvm *kvm) 1342 { 1343 if (refcount_dec_and_test(&kvm->users_count)) 1344 kvm_destroy_vm(kvm); 1345 } 1346 EXPORT_SYMBOL_GPL(kvm_put_kvm); 1347 1348 /* 1349 * Used to put a reference that was taken on behalf of an object associated 1350 * with a user-visible file descriptor, e.g. a vcpu or device, if installation 1351 * of the new file descriptor fails and the reference cannot be transferred to 1352 * its final owner. In such cases, the caller is still actively using @kvm and 1353 * will fail miserably if the refcount unexpectedly hits zero. 1354 */ 1355 void kvm_put_kvm_no_destroy(struct kvm *kvm) 1356 { 1357 WARN_ON(refcount_dec_and_test(&kvm->users_count)); 1358 } 1359 EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy); 1360 1361 static int kvm_vm_release(struct inode *inode, struct file *filp) 1362 { 1363 struct kvm *kvm = filp->private_data; 1364 1365 kvm_irqfd_release(kvm); 1366 1367 kvm_put_kvm(kvm); 1368 return 0; 1369 } 1370 1371 /* 1372 * Allocation size is twice as large as the actual dirty bitmap size. 1373 * See kvm_vm_ioctl_get_dirty_log() why this is needed. 1374 */ 1375 static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot) 1376 { 1377 unsigned long dirty_bytes = kvm_dirty_bitmap_bytes(memslot); 1378 1379 memslot->dirty_bitmap = __vcalloc(2, dirty_bytes, GFP_KERNEL_ACCOUNT); 1380 if (!memslot->dirty_bitmap) 1381 return -ENOMEM; 1382 1383 return 0; 1384 } 1385 1386 static struct kvm_memslots *kvm_get_inactive_memslots(struct kvm *kvm, int as_id) 1387 { 1388 struct kvm_memslots *active = __kvm_memslots(kvm, as_id); 1389 int node_idx_inactive = active->node_idx ^ 1; 1390 1391 return &kvm->__memslots[as_id][node_idx_inactive]; 1392 } 1393 1394 /* 1395 * Helper to get the address space ID when one of memslot pointers may be NULL. 1396 * This also serves as a sanity that at least one of the pointers is non-NULL, 1397 * and that their address space IDs don't diverge. 1398 */ 1399 static int kvm_memslots_get_as_id(struct kvm_memory_slot *a, 1400 struct kvm_memory_slot *b) 1401 { 1402 if (WARN_ON_ONCE(!a && !b)) 1403 return 0; 1404 1405 if (!a) 1406 return b->as_id; 1407 if (!b) 1408 return a->as_id; 1409 1410 WARN_ON_ONCE(a->as_id != b->as_id); 1411 return a->as_id; 1412 } 1413 1414 static void kvm_insert_gfn_node(struct kvm_memslots *slots, 1415 struct kvm_memory_slot *slot) 1416 { 1417 struct rb_root *gfn_tree = &slots->gfn_tree; 1418 struct rb_node **node, *parent; 1419 int idx = slots->node_idx; 1420 1421 parent = NULL; 1422 for (node = &gfn_tree->rb_node; *node; ) { 1423 struct kvm_memory_slot *tmp; 1424 1425 tmp = container_of(*node, struct kvm_memory_slot, gfn_node[idx]); 1426 parent = *node; 1427 if (slot->base_gfn < tmp->base_gfn) 1428 node = &(*node)->rb_left; 1429 else if (slot->base_gfn > tmp->base_gfn) 1430 node = &(*node)->rb_right; 1431 else 1432 BUG(); 1433 } 1434 1435 rb_link_node(&slot->gfn_node[idx], parent, node); 1436 rb_insert_color(&slot->gfn_node[idx], gfn_tree); 1437 } 1438 1439 static void kvm_erase_gfn_node(struct kvm_memslots *slots, 1440 struct kvm_memory_slot *slot) 1441 { 1442 rb_erase(&slot->gfn_node[slots->node_idx], &slots->gfn_tree); 1443 } 1444 1445 static void kvm_replace_gfn_node(struct kvm_memslots *slots, 1446 struct kvm_memory_slot *old, 1447 struct kvm_memory_slot *new) 1448 { 1449 int idx = slots->node_idx; 1450 1451 WARN_ON_ONCE(old->base_gfn != new->base_gfn); 1452 1453 rb_replace_node(&old->gfn_node[idx], &new->gfn_node[idx], 1454 &slots->gfn_tree); 1455 } 1456 1457 /* 1458 * Replace @old with @new in the inactive memslots. 1459 * 1460 * With NULL @old this simply adds @new. 1461 * With NULL @new this simply removes @old. 1462 * 1463 * If @new is non-NULL its hva_node[slots_idx] range has to be set 1464 * appropriately. 1465 */ 1466 static void kvm_replace_memslot(struct kvm *kvm, 1467 struct kvm_memory_slot *old, 1468 struct kvm_memory_slot *new) 1469 { 1470 int as_id = kvm_memslots_get_as_id(old, new); 1471 struct kvm_memslots *slots = kvm_get_inactive_memslots(kvm, as_id); 1472 int idx = slots->node_idx; 1473 1474 if (old) { 1475 hash_del(&old->id_node[idx]); 1476 interval_tree_remove(&old->hva_node[idx], &slots->hva_tree); 1477 1478 if ((long)old == atomic_long_read(&slots->last_used_slot)) 1479 atomic_long_set(&slots->last_used_slot, (long)new); 1480 1481 if (!new) { 1482 kvm_erase_gfn_node(slots, old); 1483 return; 1484 } 1485 } 1486 1487 /* 1488 * Initialize @new's hva range. Do this even when replacing an @old 1489 * slot, kvm_copy_memslot() deliberately does not touch node data. 1490 */ 1491 new->hva_node[idx].start = new->userspace_addr; 1492 new->hva_node[idx].last = new->userspace_addr + 1493 (new->npages << PAGE_SHIFT) - 1; 1494 1495 /* 1496 * (Re)Add the new memslot. There is no O(1) interval_tree_replace(), 1497 * hva_node needs to be swapped with remove+insert even though hva can't 1498 * change when replacing an existing slot. 1499 */ 1500 hash_add(slots->id_hash, &new->id_node[idx], new->id); 1501 interval_tree_insert(&new->hva_node[idx], &slots->hva_tree); 1502 1503 /* 1504 * If the memslot gfn is unchanged, rb_replace_node() can be used to 1505 * switch the node in the gfn tree instead of removing the old and 1506 * inserting the new as two separate operations. Replacement is a 1507 * single O(1) operation versus two O(log(n)) operations for 1508 * remove+insert. 1509 */ 1510 if (old && old->base_gfn == new->base_gfn) { 1511 kvm_replace_gfn_node(slots, old, new); 1512 } else { 1513 if (old) 1514 kvm_erase_gfn_node(slots, old); 1515 kvm_insert_gfn_node(slots, new); 1516 } 1517 } 1518 1519 /* 1520 * Flags that do not access any of the extra space of struct 1521 * kvm_userspace_memory_region2. KVM_SET_USER_MEMORY_REGION_V1_FLAGS 1522 * only allows these. 1523 */ 1524 #define KVM_SET_USER_MEMORY_REGION_V1_FLAGS \ 1525 (KVM_MEM_LOG_DIRTY_PAGES | KVM_MEM_READONLY) 1526 1527 static int check_memory_region_flags(struct kvm *kvm, 1528 const struct kvm_userspace_memory_region2 *mem) 1529 { 1530 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES; 1531 1532 if (kvm_arch_has_private_mem(kvm)) 1533 valid_flags |= KVM_MEM_GUEST_MEMFD; 1534 1535 /* Dirty logging private memory is not currently supported. */ 1536 if (mem->flags & KVM_MEM_GUEST_MEMFD) 1537 valid_flags &= ~KVM_MEM_LOG_DIRTY_PAGES; 1538 1539 /* 1540 * GUEST_MEMFD is incompatible with read-only memslots, as writes to 1541 * read-only memslots have emulated MMIO, not page fault, semantics, 1542 * and KVM doesn't allow emulated MMIO for private memory. 1543 */ 1544 if (kvm_arch_has_readonly_mem(kvm) && 1545 !(mem->flags & KVM_MEM_GUEST_MEMFD)) 1546 valid_flags |= KVM_MEM_READONLY; 1547 1548 if (mem->flags & ~valid_flags) 1549 return -EINVAL; 1550 1551 return 0; 1552 } 1553 1554 static void kvm_swap_active_memslots(struct kvm *kvm, int as_id) 1555 { 1556 struct kvm_memslots *slots = kvm_get_inactive_memslots(kvm, as_id); 1557 1558 /* Grab the generation from the activate memslots. */ 1559 u64 gen = __kvm_memslots(kvm, as_id)->generation; 1560 1561 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS); 1562 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS; 1563 1564 /* 1565 * Do not store the new memslots while there are invalidations in 1566 * progress, otherwise the locking in invalidate_range_start and 1567 * invalidate_range_end will be unbalanced. 1568 */ 1569 spin_lock(&kvm->mn_invalidate_lock); 1570 prepare_to_rcuwait(&kvm->mn_memslots_update_rcuwait); 1571 while (kvm->mn_active_invalidate_count) { 1572 set_current_state(TASK_UNINTERRUPTIBLE); 1573 spin_unlock(&kvm->mn_invalidate_lock); 1574 schedule(); 1575 spin_lock(&kvm->mn_invalidate_lock); 1576 } 1577 finish_rcuwait(&kvm->mn_memslots_update_rcuwait); 1578 rcu_assign_pointer(kvm->memslots[as_id], slots); 1579 spin_unlock(&kvm->mn_invalidate_lock); 1580 1581 /* 1582 * Acquired in kvm_set_memslot. Must be released before synchronize 1583 * SRCU below in order to avoid deadlock with another thread 1584 * acquiring the slots_arch_lock in an srcu critical section. 1585 */ 1586 mutex_unlock(&kvm->slots_arch_lock); 1587 1588 synchronize_srcu_expedited(&kvm->srcu); 1589 1590 /* 1591 * Increment the new memslot generation a second time, dropping the 1592 * update in-progress flag and incrementing the generation based on 1593 * the number of address spaces. This provides a unique and easily 1594 * identifiable generation number while the memslots are in flux. 1595 */ 1596 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS; 1597 1598 /* 1599 * Generations must be unique even across address spaces. We do not need 1600 * a global counter for that, instead the generation space is evenly split 1601 * across address spaces. For example, with two address spaces, address 1602 * space 0 will use generations 0, 2, 4, ... while address space 1 will 1603 * use generations 1, 3, 5, ... 1604 */ 1605 gen += kvm_arch_nr_memslot_as_ids(kvm); 1606 1607 kvm_arch_memslots_updated(kvm, gen); 1608 1609 slots->generation = gen; 1610 } 1611 1612 static int kvm_prepare_memory_region(struct kvm *kvm, 1613 const struct kvm_memory_slot *old, 1614 struct kvm_memory_slot *new, 1615 enum kvm_mr_change change) 1616 { 1617 int r; 1618 1619 /* 1620 * If dirty logging is disabled, nullify the bitmap; the old bitmap 1621 * will be freed on "commit". If logging is enabled in both old and 1622 * new, reuse the existing bitmap. If logging is enabled only in the 1623 * new and KVM isn't using a ring buffer, allocate and initialize a 1624 * new bitmap. 1625 */ 1626 if (change != KVM_MR_DELETE) { 1627 if (!(new->flags & KVM_MEM_LOG_DIRTY_PAGES)) 1628 new->dirty_bitmap = NULL; 1629 else if (old && old->dirty_bitmap) 1630 new->dirty_bitmap = old->dirty_bitmap; 1631 else if (kvm_use_dirty_bitmap(kvm)) { 1632 r = kvm_alloc_dirty_bitmap(new); 1633 if (r) 1634 return r; 1635 1636 if (kvm_dirty_log_manual_protect_and_init_set(kvm)) 1637 bitmap_set(new->dirty_bitmap, 0, new->npages); 1638 } 1639 } 1640 1641 r = kvm_arch_prepare_memory_region(kvm, old, new, change); 1642 1643 /* Free the bitmap on failure if it was allocated above. */ 1644 if (r && new && new->dirty_bitmap && (!old || !old->dirty_bitmap)) 1645 kvm_destroy_dirty_bitmap(new); 1646 1647 return r; 1648 } 1649 1650 static void kvm_commit_memory_region(struct kvm *kvm, 1651 struct kvm_memory_slot *old, 1652 const struct kvm_memory_slot *new, 1653 enum kvm_mr_change change) 1654 { 1655 int old_flags = old ? old->flags : 0; 1656 int new_flags = new ? new->flags : 0; 1657 /* 1658 * Update the total number of memslot pages before calling the arch 1659 * hook so that architectures can consume the result directly. 1660 */ 1661 if (change == KVM_MR_DELETE) 1662 kvm->nr_memslot_pages -= old->npages; 1663 else if (change == KVM_MR_CREATE) 1664 kvm->nr_memslot_pages += new->npages; 1665 1666 if ((old_flags ^ new_flags) & KVM_MEM_LOG_DIRTY_PAGES) { 1667 int change = (new_flags & KVM_MEM_LOG_DIRTY_PAGES) ? 1 : -1; 1668 atomic_set(&kvm->nr_memslots_dirty_logging, 1669 atomic_read(&kvm->nr_memslots_dirty_logging) + change); 1670 } 1671 1672 kvm_arch_commit_memory_region(kvm, old, new, change); 1673 1674 switch (change) { 1675 case KVM_MR_CREATE: 1676 /* Nothing more to do. */ 1677 break; 1678 case KVM_MR_DELETE: 1679 /* Free the old memslot and all its metadata. */ 1680 kvm_free_memslot(kvm, old); 1681 break; 1682 case KVM_MR_MOVE: 1683 case KVM_MR_FLAGS_ONLY: 1684 /* 1685 * Free the dirty bitmap as needed; the below check encompasses 1686 * both the flags and whether a ring buffer is being used) 1687 */ 1688 if (old->dirty_bitmap && !new->dirty_bitmap) 1689 kvm_destroy_dirty_bitmap(old); 1690 1691 /* 1692 * The final quirk. Free the detached, old slot, but only its 1693 * memory, not any metadata. Metadata, including arch specific 1694 * data, may be reused by @new. 1695 */ 1696 kfree(old); 1697 break; 1698 default: 1699 BUG(); 1700 } 1701 } 1702 1703 /* 1704 * Activate @new, which must be installed in the inactive slots by the caller, 1705 * by swapping the active slots and then propagating @new to @old once @old is 1706 * unreachable and can be safely modified. 1707 * 1708 * With NULL @old this simply adds @new to @active (while swapping the sets). 1709 * With NULL @new this simply removes @old from @active and frees it 1710 * (while also swapping the sets). 1711 */ 1712 static void kvm_activate_memslot(struct kvm *kvm, 1713 struct kvm_memory_slot *old, 1714 struct kvm_memory_slot *new) 1715 { 1716 int as_id = kvm_memslots_get_as_id(old, new); 1717 1718 kvm_swap_active_memslots(kvm, as_id); 1719 1720 /* Propagate the new memslot to the now inactive memslots. */ 1721 kvm_replace_memslot(kvm, old, new); 1722 } 1723 1724 static void kvm_copy_memslot(struct kvm_memory_slot *dest, 1725 const struct kvm_memory_slot *src) 1726 { 1727 dest->base_gfn = src->base_gfn; 1728 dest->npages = src->npages; 1729 dest->dirty_bitmap = src->dirty_bitmap; 1730 dest->arch = src->arch; 1731 dest->userspace_addr = src->userspace_addr; 1732 dest->flags = src->flags; 1733 dest->id = src->id; 1734 dest->as_id = src->as_id; 1735 } 1736 1737 static void kvm_invalidate_memslot(struct kvm *kvm, 1738 struct kvm_memory_slot *old, 1739 struct kvm_memory_slot *invalid_slot) 1740 { 1741 /* 1742 * Mark the current slot INVALID. As with all memslot modifications, 1743 * this must be done on an unreachable slot to avoid modifying the 1744 * current slot in the active tree. 1745 */ 1746 kvm_copy_memslot(invalid_slot, old); 1747 invalid_slot->flags |= KVM_MEMSLOT_INVALID; 1748 kvm_replace_memslot(kvm, old, invalid_slot); 1749 1750 /* 1751 * Activate the slot that is now marked INVALID, but don't propagate 1752 * the slot to the now inactive slots. The slot is either going to be 1753 * deleted or recreated as a new slot. 1754 */ 1755 kvm_swap_active_memslots(kvm, old->as_id); 1756 1757 /* 1758 * From this point no new shadow pages pointing to a deleted, or moved, 1759 * memslot will be created. Validation of sp->gfn happens in: 1760 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn) 1761 * - kvm_is_visible_gfn (mmu_check_root) 1762 */ 1763 kvm_arch_flush_shadow_memslot(kvm, old); 1764 kvm_arch_guest_memory_reclaimed(kvm); 1765 1766 /* Was released by kvm_swap_active_memslots(), reacquire. */ 1767 mutex_lock(&kvm->slots_arch_lock); 1768 1769 /* 1770 * Copy the arch-specific field of the newly-installed slot back to the 1771 * old slot as the arch data could have changed between releasing 1772 * slots_arch_lock in kvm_swap_active_memslots() and re-acquiring the lock 1773 * above. Writers are required to retrieve memslots *after* acquiring 1774 * slots_arch_lock, thus the active slot's data is guaranteed to be fresh. 1775 */ 1776 old->arch = invalid_slot->arch; 1777 } 1778 1779 static void kvm_create_memslot(struct kvm *kvm, 1780 struct kvm_memory_slot *new) 1781 { 1782 /* Add the new memslot to the inactive set and activate. */ 1783 kvm_replace_memslot(kvm, NULL, new); 1784 kvm_activate_memslot(kvm, NULL, new); 1785 } 1786 1787 static void kvm_delete_memslot(struct kvm *kvm, 1788 struct kvm_memory_slot *old, 1789 struct kvm_memory_slot *invalid_slot) 1790 { 1791 /* 1792 * Remove the old memslot (in the inactive memslots) by passing NULL as 1793 * the "new" slot, and for the invalid version in the active slots. 1794 */ 1795 kvm_replace_memslot(kvm, old, NULL); 1796 kvm_activate_memslot(kvm, invalid_slot, NULL); 1797 } 1798 1799 static void kvm_move_memslot(struct kvm *kvm, 1800 struct kvm_memory_slot *old, 1801 struct kvm_memory_slot *new, 1802 struct kvm_memory_slot *invalid_slot) 1803 { 1804 /* 1805 * Replace the old memslot in the inactive slots, and then swap slots 1806 * and replace the current INVALID with the new as well. 1807 */ 1808 kvm_replace_memslot(kvm, old, new); 1809 kvm_activate_memslot(kvm, invalid_slot, new); 1810 } 1811 1812 static void kvm_update_flags_memslot(struct kvm *kvm, 1813 struct kvm_memory_slot *old, 1814 struct kvm_memory_slot *new) 1815 { 1816 /* 1817 * Similar to the MOVE case, but the slot doesn't need to be zapped as 1818 * an intermediate step. Instead, the old memslot is simply replaced 1819 * with a new, updated copy in both memslot sets. 1820 */ 1821 kvm_replace_memslot(kvm, old, new); 1822 kvm_activate_memslot(kvm, old, new); 1823 } 1824 1825 static int kvm_set_memslot(struct kvm *kvm, 1826 struct kvm_memory_slot *old, 1827 struct kvm_memory_slot *new, 1828 enum kvm_mr_change change) 1829 { 1830 struct kvm_memory_slot *invalid_slot; 1831 int r; 1832 1833 /* 1834 * Released in kvm_swap_active_memslots(). 1835 * 1836 * Must be held from before the current memslots are copied until after 1837 * the new memslots are installed with rcu_assign_pointer, then 1838 * released before the synchronize srcu in kvm_swap_active_memslots(). 1839 * 1840 * When modifying memslots outside of the slots_lock, must be held 1841 * before reading the pointer to the current memslots until after all 1842 * changes to those memslots are complete. 1843 * 1844 * These rules ensure that installing new memslots does not lose 1845 * changes made to the previous memslots. 1846 */ 1847 mutex_lock(&kvm->slots_arch_lock); 1848 1849 /* 1850 * Invalidate the old slot if it's being deleted or moved. This is 1851 * done prior to actually deleting/moving the memslot to allow vCPUs to 1852 * continue running by ensuring there are no mappings or shadow pages 1853 * for the memslot when it is deleted/moved. Without pre-invalidation 1854 * (and without a lock), a window would exist between effecting the 1855 * delete/move and committing the changes in arch code where KVM or a 1856 * guest could access a non-existent memslot. 1857 * 1858 * Modifications are done on a temporary, unreachable slot. The old 1859 * slot needs to be preserved in case a later step fails and the 1860 * invalidation needs to be reverted. 1861 */ 1862 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) { 1863 invalid_slot = kzalloc(sizeof(*invalid_slot), GFP_KERNEL_ACCOUNT); 1864 if (!invalid_slot) { 1865 mutex_unlock(&kvm->slots_arch_lock); 1866 return -ENOMEM; 1867 } 1868 kvm_invalidate_memslot(kvm, old, invalid_slot); 1869 } 1870 1871 r = kvm_prepare_memory_region(kvm, old, new, change); 1872 if (r) { 1873 /* 1874 * For DELETE/MOVE, revert the above INVALID change. No 1875 * modifications required since the original slot was preserved 1876 * in the inactive slots. Changing the active memslots also 1877 * release slots_arch_lock. 1878 */ 1879 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) { 1880 kvm_activate_memslot(kvm, invalid_slot, old); 1881 kfree(invalid_slot); 1882 } else { 1883 mutex_unlock(&kvm->slots_arch_lock); 1884 } 1885 return r; 1886 } 1887 1888 /* 1889 * For DELETE and MOVE, the working slot is now active as the INVALID 1890 * version of the old slot. MOVE is particularly special as it reuses 1891 * the old slot and returns a copy of the old slot (in working_slot). 1892 * For CREATE, there is no old slot. For DELETE and FLAGS_ONLY, the 1893 * old slot is detached but otherwise preserved. 1894 */ 1895 if (change == KVM_MR_CREATE) 1896 kvm_create_memslot(kvm, new); 1897 else if (change == KVM_MR_DELETE) 1898 kvm_delete_memslot(kvm, old, invalid_slot); 1899 else if (change == KVM_MR_MOVE) 1900 kvm_move_memslot(kvm, old, new, invalid_slot); 1901 else if (change == KVM_MR_FLAGS_ONLY) 1902 kvm_update_flags_memslot(kvm, old, new); 1903 else 1904 BUG(); 1905 1906 /* Free the temporary INVALID slot used for DELETE and MOVE. */ 1907 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) 1908 kfree(invalid_slot); 1909 1910 /* 1911 * No need to refresh new->arch, changes after dropping slots_arch_lock 1912 * will directly hit the final, active memslot. Architectures are 1913 * responsible for knowing that new->arch may be stale. 1914 */ 1915 kvm_commit_memory_region(kvm, old, new, change); 1916 1917 return 0; 1918 } 1919 1920 static bool kvm_check_memslot_overlap(struct kvm_memslots *slots, int id, 1921 gfn_t start, gfn_t end) 1922 { 1923 struct kvm_memslot_iter iter; 1924 1925 kvm_for_each_memslot_in_gfn_range(&iter, slots, start, end) { 1926 if (iter.slot->id != id) 1927 return true; 1928 } 1929 1930 return false; 1931 } 1932 1933 static int kvm_set_memory_region(struct kvm *kvm, 1934 const struct kvm_userspace_memory_region2 *mem) 1935 { 1936 struct kvm_memory_slot *old, *new; 1937 struct kvm_memslots *slots; 1938 enum kvm_mr_change change; 1939 unsigned long npages; 1940 gfn_t base_gfn; 1941 int as_id, id; 1942 int r; 1943 1944 lockdep_assert_held(&kvm->slots_lock); 1945 1946 r = check_memory_region_flags(kvm, mem); 1947 if (r) 1948 return r; 1949 1950 as_id = mem->slot >> 16; 1951 id = (u16)mem->slot; 1952 1953 /* General sanity checks */ 1954 if ((mem->memory_size & (PAGE_SIZE - 1)) || 1955 (mem->memory_size != (unsigned long)mem->memory_size)) 1956 return -EINVAL; 1957 if (mem->guest_phys_addr & (PAGE_SIZE - 1)) 1958 return -EINVAL; 1959 /* We can read the guest memory with __xxx_user() later on. */ 1960 if ((mem->userspace_addr & (PAGE_SIZE - 1)) || 1961 (mem->userspace_addr != untagged_addr(mem->userspace_addr)) || 1962 !access_ok((void __user *)(unsigned long)mem->userspace_addr, 1963 mem->memory_size)) 1964 return -EINVAL; 1965 if (mem->flags & KVM_MEM_GUEST_MEMFD && 1966 (mem->guest_memfd_offset & (PAGE_SIZE - 1) || 1967 mem->guest_memfd_offset + mem->memory_size < mem->guest_memfd_offset)) 1968 return -EINVAL; 1969 if (as_id >= kvm_arch_nr_memslot_as_ids(kvm) || id >= KVM_MEM_SLOTS_NUM) 1970 return -EINVAL; 1971 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr) 1972 return -EINVAL; 1973 1974 /* 1975 * The size of userspace-defined memory regions is restricted in order 1976 * to play nice with dirty bitmap operations, which are indexed with an 1977 * "unsigned int". KVM's internal memory regions don't support dirty 1978 * logging, and so are exempt. 1979 */ 1980 if (id < KVM_USER_MEM_SLOTS && 1981 (mem->memory_size >> PAGE_SHIFT) > KVM_MEM_MAX_NR_PAGES) 1982 return -EINVAL; 1983 1984 slots = __kvm_memslots(kvm, as_id); 1985 1986 /* 1987 * Note, the old memslot (and the pointer itself!) may be invalidated 1988 * and/or destroyed by kvm_set_memslot(). 1989 */ 1990 old = id_to_memslot(slots, id); 1991 1992 if (!mem->memory_size) { 1993 if (!old || !old->npages) 1994 return -EINVAL; 1995 1996 if (WARN_ON_ONCE(kvm->nr_memslot_pages < old->npages)) 1997 return -EIO; 1998 1999 return kvm_set_memslot(kvm, old, NULL, KVM_MR_DELETE); 2000 } 2001 2002 base_gfn = (mem->guest_phys_addr >> PAGE_SHIFT); 2003 npages = (mem->memory_size >> PAGE_SHIFT); 2004 2005 if (!old || !old->npages) { 2006 change = KVM_MR_CREATE; 2007 2008 /* 2009 * To simplify KVM internals, the total number of pages across 2010 * all memslots must fit in an unsigned long. 2011 */ 2012 if ((kvm->nr_memslot_pages + npages) < kvm->nr_memslot_pages) 2013 return -EINVAL; 2014 } else { /* Modify an existing slot. */ 2015 /* Private memslots are immutable, they can only be deleted. */ 2016 if (mem->flags & KVM_MEM_GUEST_MEMFD) 2017 return -EINVAL; 2018 if ((mem->userspace_addr != old->userspace_addr) || 2019 (npages != old->npages) || 2020 ((mem->flags ^ old->flags) & KVM_MEM_READONLY)) 2021 return -EINVAL; 2022 2023 if (base_gfn != old->base_gfn) 2024 change = KVM_MR_MOVE; 2025 else if (mem->flags != old->flags) 2026 change = KVM_MR_FLAGS_ONLY; 2027 else /* Nothing to change. */ 2028 return 0; 2029 } 2030 2031 if ((change == KVM_MR_CREATE || change == KVM_MR_MOVE) && 2032 kvm_check_memslot_overlap(slots, id, base_gfn, base_gfn + npages)) 2033 return -EEXIST; 2034 2035 /* Allocate a slot that will persist in the memslot. */ 2036 new = kzalloc(sizeof(*new), GFP_KERNEL_ACCOUNT); 2037 if (!new) 2038 return -ENOMEM; 2039 2040 new->as_id = as_id; 2041 new->id = id; 2042 new->base_gfn = base_gfn; 2043 new->npages = npages; 2044 new->flags = mem->flags; 2045 new->userspace_addr = mem->userspace_addr; 2046 if (mem->flags & KVM_MEM_GUEST_MEMFD) { 2047 r = kvm_gmem_bind(kvm, new, mem->guest_memfd, mem->guest_memfd_offset); 2048 if (r) 2049 goto out; 2050 } 2051 2052 r = kvm_set_memslot(kvm, old, new, change); 2053 if (r) 2054 goto out_unbind; 2055 2056 return 0; 2057 2058 out_unbind: 2059 if (mem->flags & KVM_MEM_GUEST_MEMFD) 2060 kvm_gmem_unbind(new); 2061 out: 2062 kfree(new); 2063 return r; 2064 } 2065 2066 int kvm_set_internal_memslot(struct kvm *kvm, 2067 const struct kvm_userspace_memory_region2 *mem) 2068 { 2069 if (WARN_ON_ONCE(mem->slot < KVM_USER_MEM_SLOTS)) 2070 return -EINVAL; 2071 2072 if (WARN_ON_ONCE(mem->flags)) 2073 return -EINVAL; 2074 2075 return kvm_set_memory_region(kvm, mem); 2076 } 2077 EXPORT_SYMBOL_GPL(kvm_set_internal_memslot); 2078 2079 static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm, 2080 struct kvm_userspace_memory_region2 *mem) 2081 { 2082 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS) 2083 return -EINVAL; 2084 2085 guard(mutex)(&kvm->slots_lock); 2086 return kvm_set_memory_region(kvm, mem); 2087 } 2088 2089 #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT 2090 /** 2091 * kvm_get_dirty_log - get a snapshot of dirty pages 2092 * @kvm: pointer to kvm instance 2093 * @log: slot id and address to which we copy the log 2094 * @is_dirty: set to '1' if any dirty pages were found 2095 * @memslot: set to the associated memslot, always valid on success 2096 */ 2097 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log, 2098 int *is_dirty, struct kvm_memory_slot **memslot) 2099 { 2100 struct kvm_memslots *slots; 2101 int i, as_id, id; 2102 unsigned long n; 2103 unsigned long any = 0; 2104 2105 /* Dirty ring tracking may be exclusive to dirty log tracking */ 2106 if (!kvm_use_dirty_bitmap(kvm)) 2107 return -ENXIO; 2108 2109 *memslot = NULL; 2110 *is_dirty = 0; 2111 2112 as_id = log->slot >> 16; 2113 id = (u16)log->slot; 2114 if (as_id >= kvm_arch_nr_memslot_as_ids(kvm) || id >= KVM_USER_MEM_SLOTS) 2115 return -EINVAL; 2116 2117 slots = __kvm_memslots(kvm, as_id); 2118 *memslot = id_to_memslot(slots, id); 2119 if (!(*memslot) || !(*memslot)->dirty_bitmap) 2120 return -ENOENT; 2121 2122 kvm_arch_sync_dirty_log(kvm, *memslot); 2123 2124 n = kvm_dirty_bitmap_bytes(*memslot); 2125 2126 for (i = 0; !any && i < n/sizeof(long); ++i) 2127 any = (*memslot)->dirty_bitmap[i]; 2128 2129 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n)) 2130 return -EFAULT; 2131 2132 if (any) 2133 *is_dirty = 1; 2134 return 0; 2135 } 2136 EXPORT_SYMBOL_GPL(kvm_get_dirty_log); 2137 2138 #else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */ 2139 /** 2140 * kvm_get_dirty_log_protect - get a snapshot of dirty pages 2141 * and reenable dirty page tracking for the corresponding pages. 2142 * @kvm: pointer to kvm instance 2143 * @log: slot id and address to which we copy the log 2144 * 2145 * We need to keep it in mind that VCPU threads can write to the bitmap 2146 * concurrently. So, to avoid losing track of dirty pages we keep the 2147 * following order: 2148 * 2149 * 1. Take a snapshot of the bit and clear it if needed. 2150 * 2. Write protect the corresponding page. 2151 * 3. Copy the snapshot to the userspace. 2152 * 4. Upon return caller flushes TLB's if needed. 2153 * 2154 * Between 2 and 4, the guest may write to the page using the remaining TLB 2155 * entry. This is not a problem because the page is reported dirty using 2156 * the snapshot taken before and step 4 ensures that writes done after 2157 * exiting to userspace will be logged for the next call. 2158 * 2159 */ 2160 static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log) 2161 { 2162 struct kvm_memslots *slots; 2163 struct kvm_memory_slot *memslot; 2164 int i, as_id, id; 2165 unsigned long n; 2166 unsigned long *dirty_bitmap; 2167 unsigned long *dirty_bitmap_buffer; 2168 bool flush; 2169 2170 /* Dirty ring tracking may be exclusive to dirty log tracking */ 2171 if (!kvm_use_dirty_bitmap(kvm)) 2172 return -ENXIO; 2173 2174 as_id = log->slot >> 16; 2175 id = (u16)log->slot; 2176 if (as_id >= kvm_arch_nr_memslot_as_ids(kvm) || id >= KVM_USER_MEM_SLOTS) 2177 return -EINVAL; 2178 2179 slots = __kvm_memslots(kvm, as_id); 2180 memslot = id_to_memslot(slots, id); 2181 if (!memslot || !memslot->dirty_bitmap) 2182 return -ENOENT; 2183 2184 dirty_bitmap = memslot->dirty_bitmap; 2185 2186 kvm_arch_sync_dirty_log(kvm, memslot); 2187 2188 n = kvm_dirty_bitmap_bytes(memslot); 2189 flush = false; 2190 if (kvm->manual_dirty_log_protect) { 2191 /* 2192 * Unlike kvm_get_dirty_log, we always return false in *flush, 2193 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There 2194 * is some code duplication between this function and 2195 * kvm_get_dirty_log, but hopefully all architecture 2196 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log 2197 * can be eliminated. 2198 */ 2199 dirty_bitmap_buffer = dirty_bitmap; 2200 } else { 2201 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot); 2202 memset(dirty_bitmap_buffer, 0, n); 2203 2204 KVM_MMU_LOCK(kvm); 2205 for (i = 0; i < n / sizeof(long); i++) { 2206 unsigned long mask; 2207 gfn_t offset; 2208 2209 if (!dirty_bitmap[i]) 2210 continue; 2211 2212 flush = true; 2213 mask = xchg(&dirty_bitmap[i], 0); 2214 dirty_bitmap_buffer[i] = mask; 2215 2216 offset = i * BITS_PER_LONG; 2217 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot, 2218 offset, mask); 2219 } 2220 KVM_MMU_UNLOCK(kvm); 2221 } 2222 2223 if (flush) 2224 kvm_flush_remote_tlbs_memslot(kvm, memslot); 2225 2226 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n)) 2227 return -EFAULT; 2228 return 0; 2229 } 2230 2231 2232 /** 2233 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot 2234 * @kvm: kvm instance 2235 * @log: slot id and address to which we copy the log 2236 * 2237 * Steps 1-4 below provide general overview of dirty page logging. See 2238 * kvm_get_dirty_log_protect() function description for additional details. 2239 * 2240 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we 2241 * always flush the TLB (step 4) even if previous step failed and the dirty 2242 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API 2243 * does not preclude user space subsequent dirty log read. Flushing TLB ensures 2244 * writes will be marked dirty for next log read. 2245 * 2246 * 1. Take a snapshot of the bit and clear it if needed. 2247 * 2. Write protect the corresponding page. 2248 * 3. Copy the snapshot to the userspace. 2249 * 4. Flush TLB's if needed. 2250 */ 2251 static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, 2252 struct kvm_dirty_log *log) 2253 { 2254 int r; 2255 2256 mutex_lock(&kvm->slots_lock); 2257 2258 r = kvm_get_dirty_log_protect(kvm, log); 2259 2260 mutex_unlock(&kvm->slots_lock); 2261 return r; 2262 } 2263 2264 /** 2265 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap 2266 * and reenable dirty page tracking for the corresponding pages. 2267 * @kvm: pointer to kvm instance 2268 * @log: slot id and address from which to fetch the bitmap of dirty pages 2269 */ 2270 static int kvm_clear_dirty_log_protect(struct kvm *kvm, 2271 struct kvm_clear_dirty_log *log) 2272 { 2273 struct kvm_memslots *slots; 2274 struct kvm_memory_slot *memslot; 2275 int as_id, id; 2276 gfn_t offset; 2277 unsigned long i, n; 2278 unsigned long *dirty_bitmap; 2279 unsigned long *dirty_bitmap_buffer; 2280 bool flush; 2281 2282 /* Dirty ring tracking may be exclusive to dirty log tracking */ 2283 if (!kvm_use_dirty_bitmap(kvm)) 2284 return -ENXIO; 2285 2286 as_id = log->slot >> 16; 2287 id = (u16)log->slot; 2288 if (as_id >= kvm_arch_nr_memslot_as_ids(kvm) || id >= KVM_USER_MEM_SLOTS) 2289 return -EINVAL; 2290 2291 if (log->first_page & 63) 2292 return -EINVAL; 2293 2294 slots = __kvm_memslots(kvm, as_id); 2295 memslot = id_to_memslot(slots, id); 2296 if (!memslot || !memslot->dirty_bitmap) 2297 return -ENOENT; 2298 2299 dirty_bitmap = memslot->dirty_bitmap; 2300 2301 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8; 2302 2303 if (log->first_page > memslot->npages || 2304 log->num_pages > memslot->npages - log->first_page || 2305 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63))) 2306 return -EINVAL; 2307 2308 kvm_arch_sync_dirty_log(kvm, memslot); 2309 2310 flush = false; 2311 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot); 2312 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n)) 2313 return -EFAULT; 2314 2315 KVM_MMU_LOCK(kvm); 2316 for (offset = log->first_page, i = offset / BITS_PER_LONG, 2317 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--; 2318 i++, offset += BITS_PER_LONG) { 2319 unsigned long mask = *dirty_bitmap_buffer++; 2320 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i]; 2321 if (!mask) 2322 continue; 2323 2324 mask &= atomic_long_fetch_andnot(mask, p); 2325 2326 /* 2327 * mask contains the bits that really have been cleared. This 2328 * never includes any bits beyond the length of the memslot (if 2329 * the length is not aligned to 64 pages), therefore it is not 2330 * a problem if userspace sets them in log->dirty_bitmap. 2331 */ 2332 if (mask) { 2333 flush = true; 2334 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot, 2335 offset, mask); 2336 } 2337 } 2338 KVM_MMU_UNLOCK(kvm); 2339 2340 if (flush) 2341 kvm_flush_remote_tlbs_memslot(kvm, memslot); 2342 2343 return 0; 2344 } 2345 2346 static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm, 2347 struct kvm_clear_dirty_log *log) 2348 { 2349 int r; 2350 2351 mutex_lock(&kvm->slots_lock); 2352 2353 r = kvm_clear_dirty_log_protect(kvm, log); 2354 2355 mutex_unlock(&kvm->slots_lock); 2356 return r; 2357 } 2358 #endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */ 2359 2360 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES 2361 static u64 kvm_supported_mem_attributes(struct kvm *kvm) 2362 { 2363 if (!kvm || kvm_arch_has_private_mem(kvm)) 2364 return KVM_MEMORY_ATTRIBUTE_PRIVATE; 2365 2366 return 0; 2367 } 2368 2369 /* 2370 * Returns true if _all_ gfns in the range [@start, @end) have attributes 2371 * such that the bits in @mask match @attrs. 2372 */ 2373 bool kvm_range_has_memory_attributes(struct kvm *kvm, gfn_t start, gfn_t end, 2374 unsigned long mask, unsigned long attrs) 2375 { 2376 XA_STATE(xas, &kvm->mem_attr_array, start); 2377 unsigned long index; 2378 void *entry; 2379 2380 mask &= kvm_supported_mem_attributes(kvm); 2381 if (attrs & ~mask) 2382 return false; 2383 2384 if (end == start + 1) 2385 return (kvm_get_memory_attributes(kvm, start) & mask) == attrs; 2386 2387 guard(rcu)(); 2388 if (!attrs) 2389 return !xas_find(&xas, end - 1); 2390 2391 for (index = start; index < end; index++) { 2392 do { 2393 entry = xas_next(&xas); 2394 } while (xas_retry(&xas, entry)); 2395 2396 if (xas.xa_index != index || 2397 (xa_to_value(entry) & mask) != attrs) 2398 return false; 2399 } 2400 2401 return true; 2402 } 2403 2404 static __always_inline void kvm_handle_gfn_range(struct kvm *kvm, 2405 struct kvm_mmu_notifier_range *range) 2406 { 2407 struct kvm_gfn_range gfn_range; 2408 struct kvm_memory_slot *slot; 2409 struct kvm_memslots *slots; 2410 struct kvm_memslot_iter iter; 2411 bool found_memslot = false; 2412 bool ret = false; 2413 int i; 2414 2415 gfn_range.arg = range->arg; 2416 gfn_range.may_block = range->may_block; 2417 2418 /* 2419 * If/when KVM supports more attributes beyond private .vs shared, this 2420 * _could_ set KVM_FILTER_{SHARED,PRIVATE} appropriately if the entire target 2421 * range already has the desired private vs. shared state (it's unclear 2422 * if that is a net win). For now, KVM reaches this point if and only 2423 * if the private flag is being toggled, i.e. all mappings are in play. 2424 */ 2425 2426 for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) { 2427 slots = __kvm_memslots(kvm, i); 2428 2429 kvm_for_each_memslot_in_gfn_range(&iter, slots, range->start, range->end) { 2430 slot = iter.slot; 2431 gfn_range.slot = slot; 2432 2433 gfn_range.start = max(range->start, slot->base_gfn); 2434 gfn_range.end = min(range->end, slot->base_gfn + slot->npages); 2435 if (gfn_range.start >= gfn_range.end) 2436 continue; 2437 2438 if (!found_memslot) { 2439 found_memslot = true; 2440 KVM_MMU_LOCK(kvm); 2441 if (!IS_KVM_NULL_FN(range->on_lock)) 2442 range->on_lock(kvm); 2443 } 2444 2445 ret |= range->handler(kvm, &gfn_range); 2446 } 2447 } 2448 2449 if (range->flush_on_ret && ret) 2450 kvm_flush_remote_tlbs(kvm); 2451 2452 if (found_memslot) 2453 KVM_MMU_UNLOCK(kvm); 2454 } 2455 2456 static bool kvm_pre_set_memory_attributes(struct kvm *kvm, 2457 struct kvm_gfn_range *range) 2458 { 2459 /* 2460 * Unconditionally add the range to the invalidation set, regardless of 2461 * whether or not the arch callback actually needs to zap SPTEs. E.g. 2462 * if KVM supports RWX attributes in the future and the attributes are 2463 * going from R=>RW, zapping isn't strictly necessary. Unconditionally 2464 * adding the range allows KVM to require that MMU invalidations add at 2465 * least one range between begin() and end(), e.g. allows KVM to detect 2466 * bugs where the add() is missed. Relaxing the rule *might* be safe, 2467 * but it's not obvious that allowing new mappings while the attributes 2468 * are in flux is desirable or worth the complexity. 2469 */ 2470 kvm_mmu_invalidate_range_add(kvm, range->start, range->end); 2471 2472 return kvm_arch_pre_set_memory_attributes(kvm, range); 2473 } 2474 2475 /* Set @attributes for the gfn range [@start, @end). */ 2476 static int kvm_vm_set_mem_attributes(struct kvm *kvm, gfn_t start, gfn_t end, 2477 unsigned long attributes) 2478 { 2479 struct kvm_mmu_notifier_range pre_set_range = { 2480 .start = start, 2481 .end = end, 2482 .arg.attributes = attributes, 2483 .handler = kvm_pre_set_memory_attributes, 2484 .on_lock = kvm_mmu_invalidate_begin, 2485 .flush_on_ret = true, 2486 .may_block = true, 2487 }; 2488 struct kvm_mmu_notifier_range post_set_range = { 2489 .start = start, 2490 .end = end, 2491 .arg.attributes = attributes, 2492 .handler = kvm_arch_post_set_memory_attributes, 2493 .on_lock = kvm_mmu_invalidate_end, 2494 .may_block = true, 2495 }; 2496 unsigned long i; 2497 void *entry; 2498 int r = 0; 2499 2500 entry = attributes ? xa_mk_value(attributes) : NULL; 2501 2502 mutex_lock(&kvm->slots_lock); 2503 2504 /* Nothing to do if the entire range as the desired attributes. */ 2505 if (kvm_range_has_memory_attributes(kvm, start, end, ~0, attributes)) 2506 goto out_unlock; 2507 2508 /* 2509 * Reserve memory ahead of time to avoid having to deal with failures 2510 * partway through setting the new attributes. 2511 */ 2512 for (i = start; i < end; i++) { 2513 r = xa_reserve(&kvm->mem_attr_array, i, GFP_KERNEL_ACCOUNT); 2514 if (r) 2515 goto out_unlock; 2516 } 2517 2518 kvm_handle_gfn_range(kvm, &pre_set_range); 2519 2520 for (i = start; i < end; i++) { 2521 r = xa_err(xa_store(&kvm->mem_attr_array, i, entry, 2522 GFP_KERNEL_ACCOUNT)); 2523 KVM_BUG_ON(r, kvm); 2524 } 2525 2526 kvm_handle_gfn_range(kvm, &post_set_range); 2527 2528 out_unlock: 2529 mutex_unlock(&kvm->slots_lock); 2530 2531 return r; 2532 } 2533 static int kvm_vm_ioctl_set_mem_attributes(struct kvm *kvm, 2534 struct kvm_memory_attributes *attrs) 2535 { 2536 gfn_t start, end; 2537 2538 /* flags is currently not used. */ 2539 if (attrs->flags) 2540 return -EINVAL; 2541 if (attrs->attributes & ~kvm_supported_mem_attributes(kvm)) 2542 return -EINVAL; 2543 if (attrs->size == 0 || attrs->address + attrs->size < attrs->address) 2544 return -EINVAL; 2545 if (!PAGE_ALIGNED(attrs->address) || !PAGE_ALIGNED(attrs->size)) 2546 return -EINVAL; 2547 2548 start = attrs->address >> PAGE_SHIFT; 2549 end = (attrs->address + attrs->size) >> PAGE_SHIFT; 2550 2551 /* 2552 * xarray tracks data using "unsigned long", and as a result so does 2553 * KVM. For simplicity, supports generic attributes only on 64-bit 2554 * architectures. 2555 */ 2556 BUILD_BUG_ON(sizeof(attrs->attributes) != sizeof(unsigned long)); 2557 2558 return kvm_vm_set_mem_attributes(kvm, start, end, attrs->attributes); 2559 } 2560 #endif /* CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES */ 2561 2562 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn) 2563 { 2564 return __gfn_to_memslot(kvm_memslots(kvm), gfn); 2565 } 2566 EXPORT_SYMBOL_GPL(gfn_to_memslot); 2567 2568 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn) 2569 { 2570 struct kvm_memslots *slots = kvm_vcpu_memslots(vcpu); 2571 u64 gen = slots->generation; 2572 struct kvm_memory_slot *slot; 2573 2574 /* 2575 * This also protects against using a memslot from a different address space, 2576 * since different address spaces have different generation numbers. 2577 */ 2578 if (unlikely(gen != vcpu->last_used_slot_gen)) { 2579 vcpu->last_used_slot = NULL; 2580 vcpu->last_used_slot_gen = gen; 2581 } 2582 2583 slot = try_get_memslot(vcpu->last_used_slot, gfn); 2584 if (slot) 2585 return slot; 2586 2587 /* 2588 * Fall back to searching all memslots. We purposely use 2589 * search_memslots() instead of __gfn_to_memslot() to avoid 2590 * thrashing the VM-wide last_used_slot in kvm_memslots. 2591 */ 2592 slot = search_memslots(slots, gfn, false); 2593 if (slot) { 2594 vcpu->last_used_slot = slot; 2595 return slot; 2596 } 2597 2598 return NULL; 2599 } 2600 2601 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn) 2602 { 2603 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn); 2604 2605 return kvm_is_visible_memslot(memslot); 2606 } 2607 EXPORT_SYMBOL_GPL(kvm_is_visible_gfn); 2608 2609 bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn) 2610 { 2611 struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn); 2612 2613 return kvm_is_visible_memslot(memslot); 2614 } 2615 EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn); 2616 2617 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn) 2618 { 2619 struct vm_area_struct *vma; 2620 unsigned long addr, size; 2621 2622 size = PAGE_SIZE; 2623 2624 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL); 2625 if (kvm_is_error_hva(addr)) 2626 return PAGE_SIZE; 2627 2628 mmap_read_lock(current->mm); 2629 vma = find_vma(current->mm, addr); 2630 if (!vma) 2631 goto out; 2632 2633 size = vma_kernel_pagesize(vma); 2634 2635 out: 2636 mmap_read_unlock(current->mm); 2637 2638 return size; 2639 } 2640 2641 static bool memslot_is_readonly(const struct kvm_memory_slot *slot) 2642 { 2643 return slot->flags & KVM_MEM_READONLY; 2644 } 2645 2646 static unsigned long __gfn_to_hva_many(const struct kvm_memory_slot *slot, gfn_t gfn, 2647 gfn_t *nr_pages, bool write) 2648 { 2649 if (!slot || slot->flags & KVM_MEMSLOT_INVALID) 2650 return KVM_HVA_ERR_BAD; 2651 2652 if (memslot_is_readonly(slot) && write) 2653 return KVM_HVA_ERR_RO_BAD; 2654 2655 if (nr_pages) 2656 *nr_pages = slot->npages - (gfn - slot->base_gfn); 2657 2658 return __gfn_to_hva_memslot(slot, gfn); 2659 } 2660 2661 static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn, 2662 gfn_t *nr_pages) 2663 { 2664 return __gfn_to_hva_many(slot, gfn, nr_pages, true); 2665 } 2666 2667 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot, 2668 gfn_t gfn) 2669 { 2670 return gfn_to_hva_many(slot, gfn, NULL); 2671 } 2672 EXPORT_SYMBOL_GPL(gfn_to_hva_memslot); 2673 2674 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn) 2675 { 2676 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL); 2677 } 2678 EXPORT_SYMBOL_GPL(gfn_to_hva); 2679 2680 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn) 2681 { 2682 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL); 2683 } 2684 EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva); 2685 2686 /* 2687 * Return the hva of a @gfn and the R/W attribute if possible. 2688 * 2689 * @slot: the kvm_memory_slot which contains @gfn 2690 * @gfn: the gfn to be translated 2691 * @writable: used to return the read/write attribute of the @slot if the hva 2692 * is valid and @writable is not NULL 2693 */ 2694 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot, 2695 gfn_t gfn, bool *writable) 2696 { 2697 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false); 2698 2699 if (!kvm_is_error_hva(hva) && writable) 2700 *writable = !memslot_is_readonly(slot); 2701 2702 return hva; 2703 } 2704 2705 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable) 2706 { 2707 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn); 2708 2709 return gfn_to_hva_memslot_prot(slot, gfn, writable); 2710 } 2711 2712 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable) 2713 { 2714 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn); 2715 2716 return gfn_to_hva_memslot_prot(slot, gfn, writable); 2717 } 2718 2719 static bool kvm_is_ad_tracked_page(struct page *page) 2720 { 2721 /* 2722 * Per page-flags.h, pages tagged PG_reserved "should in general not be 2723 * touched (e.g. set dirty) except by its owner". 2724 */ 2725 return !PageReserved(page); 2726 } 2727 2728 static void kvm_set_page_dirty(struct page *page) 2729 { 2730 if (kvm_is_ad_tracked_page(page)) 2731 SetPageDirty(page); 2732 } 2733 2734 static void kvm_set_page_accessed(struct page *page) 2735 { 2736 if (kvm_is_ad_tracked_page(page)) 2737 mark_page_accessed(page); 2738 } 2739 2740 void kvm_release_page_clean(struct page *page) 2741 { 2742 if (!page) 2743 return; 2744 2745 kvm_set_page_accessed(page); 2746 put_page(page); 2747 } 2748 EXPORT_SYMBOL_GPL(kvm_release_page_clean); 2749 2750 void kvm_release_page_dirty(struct page *page) 2751 { 2752 if (!page) 2753 return; 2754 2755 kvm_set_page_dirty(page); 2756 kvm_release_page_clean(page); 2757 } 2758 EXPORT_SYMBOL_GPL(kvm_release_page_dirty); 2759 2760 static kvm_pfn_t kvm_resolve_pfn(struct kvm_follow_pfn *kfp, struct page *page, 2761 struct follow_pfnmap_args *map, bool writable) 2762 { 2763 kvm_pfn_t pfn; 2764 2765 WARN_ON_ONCE(!!page == !!map); 2766 2767 if (kfp->map_writable) 2768 *kfp->map_writable = writable; 2769 2770 if (map) 2771 pfn = map->pfn; 2772 else 2773 pfn = page_to_pfn(page); 2774 2775 *kfp->refcounted_page = page; 2776 2777 return pfn; 2778 } 2779 2780 /* 2781 * The fast path to get the writable pfn which will be stored in @pfn, 2782 * true indicates success, otherwise false is returned. 2783 */ 2784 static bool hva_to_pfn_fast(struct kvm_follow_pfn *kfp, kvm_pfn_t *pfn) 2785 { 2786 struct page *page; 2787 bool r; 2788 2789 /* 2790 * Try the fast-only path when the caller wants to pin/get the page for 2791 * writing. If the caller only wants to read the page, KVM must go 2792 * down the full, slow path in order to avoid racing an operation that 2793 * breaks Copy-on-Write (CoW), e.g. so that KVM doesn't end up pointing 2794 * at the old, read-only page while mm/ points at a new, writable page. 2795 */ 2796 if (!((kfp->flags & FOLL_WRITE) || kfp->map_writable)) 2797 return false; 2798 2799 if (kfp->pin) 2800 r = pin_user_pages_fast(kfp->hva, 1, FOLL_WRITE, &page) == 1; 2801 else 2802 r = get_user_page_fast_only(kfp->hva, FOLL_WRITE, &page); 2803 2804 if (r) { 2805 *pfn = kvm_resolve_pfn(kfp, page, NULL, true); 2806 return true; 2807 } 2808 2809 return false; 2810 } 2811 2812 /* 2813 * The slow path to get the pfn of the specified host virtual address, 2814 * 1 indicates success, -errno is returned if error is detected. 2815 */ 2816 static int hva_to_pfn_slow(struct kvm_follow_pfn *kfp, kvm_pfn_t *pfn) 2817 { 2818 /* 2819 * When a VCPU accesses a page that is not mapped into the secondary 2820 * MMU, we lookup the page using GUP to map it, so the guest VCPU can 2821 * make progress. We always want to honor NUMA hinting faults in that 2822 * case, because GUP usage corresponds to memory accesses from the VCPU. 2823 * Otherwise, we'd not trigger NUMA hinting faults once a page is 2824 * mapped into the secondary MMU and gets accessed by a VCPU. 2825 * 2826 * Note that get_user_page_fast_only() and FOLL_WRITE for now 2827 * implicitly honor NUMA hinting faults and don't need this flag. 2828 */ 2829 unsigned int flags = FOLL_HWPOISON | FOLL_HONOR_NUMA_FAULT | kfp->flags; 2830 struct page *page, *wpage; 2831 int npages; 2832 2833 if (kfp->pin) 2834 npages = pin_user_pages_unlocked(kfp->hva, 1, &page, flags); 2835 else 2836 npages = get_user_pages_unlocked(kfp->hva, 1, &page, flags); 2837 if (npages != 1) 2838 return npages; 2839 2840 /* 2841 * Pinning is mutually exclusive with opportunistically mapping a read 2842 * fault as writable, as KVM should never pin pages when mapping memory 2843 * into the guest (pinning is only for direct accesses from KVM). 2844 */ 2845 if (WARN_ON_ONCE(kfp->map_writable && kfp->pin)) 2846 goto out; 2847 2848 /* map read fault as writable if possible */ 2849 if (!(flags & FOLL_WRITE) && kfp->map_writable && 2850 get_user_page_fast_only(kfp->hva, FOLL_WRITE, &wpage)) { 2851 put_page(page); 2852 page = wpage; 2853 flags |= FOLL_WRITE; 2854 } 2855 2856 out: 2857 *pfn = kvm_resolve_pfn(kfp, page, NULL, flags & FOLL_WRITE); 2858 return npages; 2859 } 2860 2861 static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault) 2862 { 2863 if (unlikely(!(vma->vm_flags & VM_READ))) 2864 return false; 2865 2866 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE)))) 2867 return false; 2868 2869 return true; 2870 } 2871 2872 static int hva_to_pfn_remapped(struct vm_area_struct *vma, 2873 struct kvm_follow_pfn *kfp, kvm_pfn_t *p_pfn) 2874 { 2875 struct follow_pfnmap_args args = { .vma = vma, .address = kfp->hva }; 2876 bool write_fault = kfp->flags & FOLL_WRITE; 2877 int r; 2878 2879 /* 2880 * Remapped memory cannot be pinned in any meaningful sense. Bail if 2881 * the caller wants to pin the page, i.e. access the page outside of 2882 * MMU notifier protection, and unsafe umappings are disallowed. 2883 */ 2884 if (kfp->pin && !allow_unsafe_mappings) 2885 return -EINVAL; 2886 2887 r = follow_pfnmap_start(&args); 2888 if (r) { 2889 /* 2890 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does 2891 * not call the fault handler, so do it here. 2892 */ 2893 bool unlocked = false; 2894 r = fixup_user_fault(current->mm, kfp->hva, 2895 (write_fault ? FAULT_FLAG_WRITE : 0), 2896 &unlocked); 2897 if (unlocked) 2898 return -EAGAIN; 2899 if (r) 2900 return r; 2901 2902 r = follow_pfnmap_start(&args); 2903 if (r) 2904 return r; 2905 } 2906 2907 if (write_fault && !args.writable) { 2908 *p_pfn = KVM_PFN_ERR_RO_FAULT; 2909 goto out; 2910 } 2911 2912 *p_pfn = kvm_resolve_pfn(kfp, NULL, &args, args.writable); 2913 out: 2914 follow_pfnmap_end(&args); 2915 return r; 2916 } 2917 2918 kvm_pfn_t hva_to_pfn(struct kvm_follow_pfn *kfp) 2919 { 2920 struct vm_area_struct *vma; 2921 kvm_pfn_t pfn; 2922 int npages, r; 2923 2924 might_sleep(); 2925 2926 if (WARN_ON_ONCE(!kfp->refcounted_page)) 2927 return KVM_PFN_ERR_FAULT; 2928 2929 if (hva_to_pfn_fast(kfp, &pfn)) 2930 return pfn; 2931 2932 npages = hva_to_pfn_slow(kfp, &pfn); 2933 if (npages == 1) 2934 return pfn; 2935 if (npages == -EINTR || npages == -EAGAIN) 2936 return KVM_PFN_ERR_SIGPENDING; 2937 if (npages == -EHWPOISON) 2938 return KVM_PFN_ERR_HWPOISON; 2939 2940 mmap_read_lock(current->mm); 2941 retry: 2942 vma = vma_lookup(current->mm, kfp->hva); 2943 2944 if (vma == NULL) 2945 pfn = KVM_PFN_ERR_FAULT; 2946 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) { 2947 r = hva_to_pfn_remapped(vma, kfp, &pfn); 2948 if (r == -EAGAIN) 2949 goto retry; 2950 if (r < 0) 2951 pfn = KVM_PFN_ERR_FAULT; 2952 } else { 2953 if ((kfp->flags & FOLL_NOWAIT) && 2954 vma_is_valid(vma, kfp->flags & FOLL_WRITE)) 2955 pfn = KVM_PFN_ERR_NEEDS_IO; 2956 else 2957 pfn = KVM_PFN_ERR_FAULT; 2958 } 2959 mmap_read_unlock(current->mm); 2960 return pfn; 2961 } 2962 2963 static kvm_pfn_t kvm_follow_pfn(struct kvm_follow_pfn *kfp) 2964 { 2965 kfp->hva = __gfn_to_hva_many(kfp->slot, kfp->gfn, NULL, 2966 kfp->flags & FOLL_WRITE); 2967 2968 if (kfp->hva == KVM_HVA_ERR_RO_BAD) 2969 return KVM_PFN_ERR_RO_FAULT; 2970 2971 if (kvm_is_error_hva(kfp->hva)) 2972 return KVM_PFN_NOSLOT; 2973 2974 if (memslot_is_readonly(kfp->slot) && kfp->map_writable) { 2975 *kfp->map_writable = false; 2976 kfp->map_writable = NULL; 2977 } 2978 2979 return hva_to_pfn(kfp); 2980 } 2981 2982 kvm_pfn_t __kvm_faultin_pfn(const struct kvm_memory_slot *slot, gfn_t gfn, 2983 unsigned int foll, bool *writable, 2984 struct page **refcounted_page) 2985 { 2986 struct kvm_follow_pfn kfp = { 2987 .slot = slot, 2988 .gfn = gfn, 2989 .flags = foll, 2990 .map_writable = writable, 2991 .refcounted_page = refcounted_page, 2992 }; 2993 2994 if (WARN_ON_ONCE(!writable || !refcounted_page)) 2995 return KVM_PFN_ERR_FAULT; 2996 2997 *writable = false; 2998 *refcounted_page = NULL; 2999 3000 return kvm_follow_pfn(&kfp); 3001 } 3002 EXPORT_SYMBOL_GPL(__kvm_faultin_pfn); 3003 3004 int kvm_prefetch_pages(struct kvm_memory_slot *slot, gfn_t gfn, 3005 struct page **pages, int nr_pages) 3006 { 3007 unsigned long addr; 3008 gfn_t entry = 0; 3009 3010 addr = gfn_to_hva_many(slot, gfn, &entry); 3011 if (kvm_is_error_hva(addr)) 3012 return -1; 3013 3014 if (entry < nr_pages) 3015 return 0; 3016 3017 return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages); 3018 } 3019 EXPORT_SYMBOL_GPL(kvm_prefetch_pages); 3020 3021 /* 3022 * Don't use this API unless you are absolutely, positively certain that KVM 3023 * needs to get a struct page, e.g. to pin the page for firmware DMA. 3024 * 3025 * FIXME: Users of this API likely need to FOLL_PIN the page, not just elevate 3026 * its refcount. 3027 */ 3028 struct page *__gfn_to_page(struct kvm *kvm, gfn_t gfn, bool write) 3029 { 3030 struct page *refcounted_page = NULL; 3031 struct kvm_follow_pfn kfp = { 3032 .slot = gfn_to_memslot(kvm, gfn), 3033 .gfn = gfn, 3034 .flags = write ? FOLL_WRITE : 0, 3035 .refcounted_page = &refcounted_page, 3036 }; 3037 3038 (void)kvm_follow_pfn(&kfp); 3039 return refcounted_page; 3040 } 3041 EXPORT_SYMBOL_GPL(__gfn_to_page); 3042 3043 int __kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map, 3044 bool writable) 3045 { 3046 struct kvm_follow_pfn kfp = { 3047 .slot = gfn_to_memslot(vcpu->kvm, gfn), 3048 .gfn = gfn, 3049 .flags = writable ? FOLL_WRITE : 0, 3050 .refcounted_page = &map->pinned_page, 3051 .pin = true, 3052 }; 3053 3054 map->pinned_page = NULL; 3055 map->page = NULL; 3056 map->hva = NULL; 3057 map->gfn = gfn; 3058 map->writable = writable; 3059 3060 map->pfn = kvm_follow_pfn(&kfp); 3061 if (is_error_noslot_pfn(map->pfn)) 3062 return -EINVAL; 3063 3064 if (pfn_valid(map->pfn)) { 3065 map->page = pfn_to_page(map->pfn); 3066 map->hva = kmap(map->page); 3067 #ifdef CONFIG_HAS_IOMEM 3068 } else { 3069 map->hva = memremap(pfn_to_hpa(map->pfn), PAGE_SIZE, MEMREMAP_WB); 3070 #endif 3071 } 3072 3073 return map->hva ? 0 : -EFAULT; 3074 } 3075 EXPORT_SYMBOL_GPL(__kvm_vcpu_map); 3076 3077 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map) 3078 { 3079 if (!map->hva) 3080 return; 3081 3082 if (map->page) 3083 kunmap(map->page); 3084 #ifdef CONFIG_HAS_IOMEM 3085 else 3086 memunmap(map->hva); 3087 #endif 3088 3089 if (map->writable) 3090 kvm_vcpu_mark_page_dirty(vcpu, map->gfn); 3091 3092 if (map->pinned_page) { 3093 if (map->writable) 3094 kvm_set_page_dirty(map->pinned_page); 3095 kvm_set_page_accessed(map->pinned_page); 3096 unpin_user_page(map->pinned_page); 3097 } 3098 3099 map->hva = NULL; 3100 map->page = NULL; 3101 map->pinned_page = NULL; 3102 } 3103 EXPORT_SYMBOL_GPL(kvm_vcpu_unmap); 3104 3105 static int next_segment(unsigned long len, int offset) 3106 { 3107 if (len > PAGE_SIZE - offset) 3108 return PAGE_SIZE - offset; 3109 else 3110 return len; 3111 } 3112 3113 /* Copy @len bytes from guest memory at '(@gfn * PAGE_SIZE) + @offset' to @data */ 3114 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn, 3115 void *data, int offset, int len) 3116 { 3117 int r; 3118 unsigned long addr; 3119 3120 if (WARN_ON_ONCE(offset + len > PAGE_SIZE)) 3121 return -EFAULT; 3122 3123 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL); 3124 if (kvm_is_error_hva(addr)) 3125 return -EFAULT; 3126 r = __copy_from_user(data, (void __user *)addr + offset, len); 3127 if (r) 3128 return -EFAULT; 3129 return 0; 3130 } 3131 3132 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset, 3133 int len) 3134 { 3135 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn); 3136 3137 return __kvm_read_guest_page(slot, gfn, data, offset, len); 3138 } 3139 EXPORT_SYMBOL_GPL(kvm_read_guest_page); 3140 3141 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data, 3142 int offset, int len) 3143 { 3144 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn); 3145 3146 return __kvm_read_guest_page(slot, gfn, data, offset, len); 3147 } 3148 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page); 3149 3150 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len) 3151 { 3152 gfn_t gfn = gpa >> PAGE_SHIFT; 3153 int seg; 3154 int offset = offset_in_page(gpa); 3155 int ret; 3156 3157 while ((seg = next_segment(len, offset)) != 0) { 3158 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg); 3159 if (ret < 0) 3160 return ret; 3161 offset = 0; 3162 len -= seg; 3163 data += seg; 3164 ++gfn; 3165 } 3166 return 0; 3167 } 3168 EXPORT_SYMBOL_GPL(kvm_read_guest); 3169 3170 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len) 3171 { 3172 gfn_t gfn = gpa >> PAGE_SHIFT; 3173 int seg; 3174 int offset = offset_in_page(gpa); 3175 int ret; 3176 3177 while ((seg = next_segment(len, offset)) != 0) { 3178 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg); 3179 if (ret < 0) 3180 return ret; 3181 offset = 0; 3182 len -= seg; 3183 data += seg; 3184 ++gfn; 3185 } 3186 return 0; 3187 } 3188 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest); 3189 3190 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn, 3191 void *data, int offset, unsigned long len) 3192 { 3193 int r; 3194 unsigned long addr; 3195 3196 if (WARN_ON_ONCE(offset + len > PAGE_SIZE)) 3197 return -EFAULT; 3198 3199 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL); 3200 if (kvm_is_error_hva(addr)) 3201 return -EFAULT; 3202 pagefault_disable(); 3203 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len); 3204 pagefault_enable(); 3205 if (r) 3206 return -EFAULT; 3207 return 0; 3208 } 3209 3210 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa, 3211 void *data, unsigned long len) 3212 { 3213 gfn_t gfn = gpa >> PAGE_SHIFT; 3214 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn); 3215 int offset = offset_in_page(gpa); 3216 3217 return __kvm_read_guest_atomic(slot, gfn, data, offset, len); 3218 } 3219 EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic); 3220 3221 /* Copy @len bytes from @data into guest memory at '(@gfn * PAGE_SIZE) + @offset' */ 3222 static int __kvm_write_guest_page(struct kvm *kvm, 3223 struct kvm_memory_slot *memslot, gfn_t gfn, 3224 const void *data, int offset, int len) 3225 { 3226 int r; 3227 unsigned long addr; 3228 3229 if (WARN_ON_ONCE(offset + len > PAGE_SIZE)) 3230 return -EFAULT; 3231 3232 addr = gfn_to_hva_memslot(memslot, gfn); 3233 if (kvm_is_error_hva(addr)) 3234 return -EFAULT; 3235 r = __copy_to_user((void __user *)addr + offset, data, len); 3236 if (r) 3237 return -EFAULT; 3238 mark_page_dirty_in_slot(kvm, memslot, gfn); 3239 return 0; 3240 } 3241 3242 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, 3243 const void *data, int offset, int len) 3244 { 3245 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn); 3246 3247 return __kvm_write_guest_page(kvm, slot, gfn, data, offset, len); 3248 } 3249 EXPORT_SYMBOL_GPL(kvm_write_guest_page); 3250 3251 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, 3252 const void *data, int offset, int len) 3253 { 3254 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn); 3255 3256 return __kvm_write_guest_page(vcpu->kvm, slot, gfn, data, offset, len); 3257 } 3258 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page); 3259 3260 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data, 3261 unsigned long len) 3262 { 3263 gfn_t gfn = gpa >> PAGE_SHIFT; 3264 int seg; 3265 int offset = offset_in_page(gpa); 3266 int ret; 3267 3268 while ((seg = next_segment(len, offset)) != 0) { 3269 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg); 3270 if (ret < 0) 3271 return ret; 3272 offset = 0; 3273 len -= seg; 3274 data += seg; 3275 ++gfn; 3276 } 3277 return 0; 3278 } 3279 EXPORT_SYMBOL_GPL(kvm_write_guest); 3280 3281 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data, 3282 unsigned long len) 3283 { 3284 gfn_t gfn = gpa >> PAGE_SHIFT; 3285 int seg; 3286 int offset = offset_in_page(gpa); 3287 int ret; 3288 3289 while ((seg = next_segment(len, offset)) != 0) { 3290 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg); 3291 if (ret < 0) 3292 return ret; 3293 offset = 0; 3294 len -= seg; 3295 data += seg; 3296 ++gfn; 3297 } 3298 return 0; 3299 } 3300 EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest); 3301 3302 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots, 3303 struct gfn_to_hva_cache *ghc, 3304 gpa_t gpa, unsigned long len) 3305 { 3306 int offset = offset_in_page(gpa); 3307 gfn_t start_gfn = gpa >> PAGE_SHIFT; 3308 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT; 3309 gfn_t nr_pages_needed = end_gfn - start_gfn + 1; 3310 gfn_t nr_pages_avail; 3311 3312 /* Update ghc->generation before performing any error checks. */ 3313 ghc->generation = slots->generation; 3314 3315 if (start_gfn > end_gfn) { 3316 ghc->hva = KVM_HVA_ERR_BAD; 3317 return -EINVAL; 3318 } 3319 3320 /* 3321 * If the requested region crosses two memslots, we still 3322 * verify that the entire region is valid here. 3323 */ 3324 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) { 3325 ghc->memslot = __gfn_to_memslot(slots, start_gfn); 3326 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn, 3327 &nr_pages_avail); 3328 if (kvm_is_error_hva(ghc->hva)) 3329 return -EFAULT; 3330 } 3331 3332 /* Use the slow path for cross page reads and writes. */ 3333 if (nr_pages_needed == 1) 3334 ghc->hva += offset; 3335 else 3336 ghc->memslot = NULL; 3337 3338 ghc->gpa = gpa; 3339 ghc->len = len; 3340 return 0; 3341 } 3342 3343 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc, 3344 gpa_t gpa, unsigned long len) 3345 { 3346 struct kvm_memslots *slots = kvm_memslots(kvm); 3347 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len); 3348 } 3349 EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init); 3350 3351 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc, 3352 void *data, unsigned int offset, 3353 unsigned long len) 3354 { 3355 struct kvm_memslots *slots = kvm_memslots(kvm); 3356 int r; 3357 gpa_t gpa = ghc->gpa + offset; 3358 3359 if (WARN_ON_ONCE(len + offset > ghc->len)) 3360 return -EINVAL; 3361 3362 if (slots->generation != ghc->generation) { 3363 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len)) 3364 return -EFAULT; 3365 } 3366 3367 if (kvm_is_error_hva(ghc->hva)) 3368 return -EFAULT; 3369 3370 if (unlikely(!ghc->memslot)) 3371 return kvm_write_guest(kvm, gpa, data, len); 3372 3373 r = __copy_to_user((void __user *)ghc->hva + offset, data, len); 3374 if (r) 3375 return -EFAULT; 3376 mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT); 3377 3378 return 0; 3379 } 3380 EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached); 3381 3382 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc, 3383 void *data, unsigned long len) 3384 { 3385 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len); 3386 } 3387 EXPORT_SYMBOL_GPL(kvm_write_guest_cached); 3388 3389 int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc, 3390 void *data, unsigned int offset, 3391 unsigned long len) 3392 { 3393 struct kvm_memslots *slots = kvm_memslots(kvm); 3394 int r; 3395 gpa_t gpa = ghc->gpa + offset; 3396 3397 if (WARN_ON_ONCE(len + offset > ghc->len)) 3398 return -EINVAL; 3399 3400 if (slots->generation != ghc->generation) { 3401 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len)) 3402 return -EFAULT; 3403 } 3404 3405 if (kvm_is_error_hva(ghc->hva)) 3406 return -EFAULT; 3407 3408 if (unlikely(!ghc->memslot)) 3409 return kvm_read_guest(kvm, gpa, data, len); 3410 3411 r = __copy_from_user(data, (void __user *)ghc->hva + offset, len); 3412 if (r) 3413 return -EFAULT; 3414 3415 return 0; 3416 } 3417 EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached); 3418 3419 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc, 3420 void *data, unsigned long len) 3421 { 3422 return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len); 3423 } 3424 EXPORT_SYMBOL_GPL(kvm_read_guest_cached); 3425 3426 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len) 3427 { 3428 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0))); 3429 gfn_t gfn = gpa >> PAGE_SHIFT; 3430 int seg; 3431 int offset = offset_in_page(gpa); 3432 int ret; 3433 3434 while ((seg = next_segment(len, offset)) != 0) { 3435 ret = kvm_write_guest_page(kvm, gfn, zero_page, offset, seg); 3436 if (ret < 0) 3437 return ret; 3438 offset = 0; 3439 len -= seg; 3440 ++gfn; 3441 } 3442 return 0; 3443 } 3444 EXPORT_SYMBOL_GPL(kvm_clear_guest); 3445 3446 void mark_page_dirty_in_slot(struct kvm *kvm, 3447 const struct kvm_memory_slot *memslot, 3448 gfn_t gfn) 3449 { 3450 struct kvm_vcpu *vcpu = kvm_get_running_vcpu(); 3451 3452 #ifdef CONFIG_HAVE_KVM_DIRTY_RING 3453 if (WARN_ON_ONCE(vcpu && vcpu->kvm != kvm)) 3454 return; 3455 3456 WARN_ON_ONCE(!vcpu && !kvm_arch_allow_write_without_running_vcpu(kvm)); 3457 #endif 3458 3459 if (memslot && kvm_slot_dirty_track_enabled(memslot)) { 3460 unsigned long rel_gfn = gfn - memslot->base_gfn; 3461 u32 slot = (memslot->as_id << 16) | memslot->id; 3462 3463 if (kvm->dirty_ring_size && vcpu) 3464 kvm_dirty_ring_push(vcpu, slot, rel_gfn); 3465 else if (memslot->dirty_bitmap) 3466 set_bit_le(rel_gfn, memslot->dirty_bitmap); 3467 } 3468 } 3469 EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot); 3470 3471 void mark_page_dirty(struct kvm *kvm, gfn_t gfn) 3472 { 3473 struct kvm_memory_slot *memslot; 3474 3475 memslot = gfn_to_memslot(kvm, gfn); 3476 mark_page_dirty_in_slot(kvm, memslot, gfn); 3477 } 3478 EXPORT_SYMBOL_GPL(mark_page_dirty); 3479 3480 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn) 3481 { 3482 struct kvm_memory_slot *memslot; 3483 3484 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn); 3485 mark_page_dirty_in_slot(vcpu->kvm, memslot, gfn); 3486 } 3487 EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty); 3488 3489 void kvm_sigset_activate(struct kvm_vcpu *vcpu) 3490 { 3491 if (!vcpu->sigset_active) 3492 return; 3493 3494 /* 3495 * This does a lockless modification of ->real_blocked, which is fine 3496 * because, only current can change ->real_blocked and all readers of 3497 * ->real_blocked don't care as long ->real_blocked is always a subset 3498 * of ->blocked. 3499 */ 3500 sigprocmask(SIG_SETMASK, &vcpu->sigset, ¤t->real_blocked); 3501 } 3502 3503 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu) 3504 { 3505 if (!vcpu->sigset_active) 3506 return; 3507 3508 sigprocmask(SIG_SETMASK, ¤t->real_blocked, NULL); 3509 sigemptyset(¤t->real_blocked); 3510 } 3511 3512 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu) 3513 { 3514 unsigned int old, val, grow, grow_start; 3515 3516 old = val = vcpu->halt_poll_ns; 3517 grow_start = READ_ONCE(halt_poll_ns_grow_start); 3518 grow = READ_ONCE(halt_poll_ns_grow); 3519 if (!grow) 3520 goto out; 3521 3522 val *= grow; 3523 if (val < grow_start) 3524 val = grow_start; 3525 3526 vcpu->halt_poll_ns = val; 3527 out: 3528 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old); 3529 } 3530 3531 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu) 3532 { 3533 unsigned int old, val, shrink, grow_start; 3534 3535 old = val = vcpu->halt_poll_ns; 3536 shrink = READ_ONCE(halt_poll_ns_shrink); 3537 grow_start = READ_ONCE(halt_poll_ns_grow_start); 3538 if (shrink == 0) 3539 val = 0; 3540 else 3541 val /= shrink; 3542 3543 if (val < grow_start) 3544 val = 0; 3545 3546 vcpu->halt_poll_ns = val; 3547 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old); 3548 } 3549 3550 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu) 3551 { 3552 int ret = -EINTR; 3553 int idx = srcu_read_lock(&vcpu->kvm->srcu); 3554 3555 if (kvm_arch_vcpu_runnable(vcpu)) 3556 goto out; 3557 if (kvm_cpu_has_pending_timer(vcpu)) 3558 goto out; 3559 if (signal_pending(current)) 3560 goto out; 3561 if (kvm_check_request(KVM_REQ_UNBLOCK, vcpu)) 3562 goto out; 3563 3564 ret = 0; 3565 out: 3566 srcu_read_unlock(&vcpu->kvm->srcu, idx); 3567 return ret; 3568 } 3569 3570 /* 3571 * Block the vCPU until the vCPU is runnable, an event arrives, or a signal is 3572 * pending. This is mostly used when halting a vCPU, but may also be used 3573 * directly for other vCPU non-runnable states, e.g. x86's Wait-For-SIPI. 3574 */ 3575 bool kvm_vcpu_block(struct kvm_vcpu *vcpu) 3576 { 3577 struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu); 3578 bool waited = false; 3579 3580 vcpu->stat.generic.blocking = 1; 3581 3582 preempt_disable(); 3583 kvm_arch_vcpu_blocking(vcpu); 3584 prepare_to_rcuwait(wait); 3585 preempt_enable(); 3586 3587 for (;;) { 3588 set_current_state(TASK_INTERRUPTIBLE); 3589 3590 if (kvm_vcpu_check_block(vcpu) < 0) 3591 break; 3592 3593 waited = true; 3594 schedule(); 3595 } 3596 3597 preempt_disable(); 3598 finish_rcuwait(wait); 3599 kvm_arch_vcpu_unblocking(vcpu); 3600 preempt_enable(); 3601 3602 vcpu->stat.generic.blocking = 0; 3603 3604 return waited; 3605 } 3606 3607 static inline void update_halt_poll_stats(struct kvm_vcpu *vcpu, ktime_t start, 3608 ktime_t end, bool success) 3609 { 3610 struct kvm_vcpu_stat_generic *stats = &vcpu->stat.generic; 3611 u64 poll_ns = ktime_to_ns(ktime_sub(end, start)); 3612 3613 ++vcpu->stat.generic.halt_attempted_poll; 3614 3615 if (success) { 3616 ++vcpu->stat.generic.halt_successful_poll; 3617 3618 if (!vcpu_valid_wakeup(vcpu)) 3619 ++vcpu->stat.generic.halt_poll_invalid; 3620 3621 stats->halt_poll_success_ns += poll_ns; 3622 KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_success_hist, poll_ns); 3623 } else { 3624 stats->halt_poll_fail_ns += poll_ns; 3625 KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_fail_hist, poll_ns); 3626 } 3627 } 3628 3629 static unsigned int kvm_vcpu_max_halt_poll_ns(struct kvm_vcpu *vcpu) 3630 { 3631 struct kvm *kvm = vcpu->kvm; 3632 3633 if (kvm->override_halt_poll_ns) { 3634 /* 3635 * Ensure kvm->max_halt_poll_ns is not read before 3636 * kvm->override_halt_poll_ns. 3637 * 3638 * Pairs with the smp_wmb() when enabling KVM_CAP_HALT_POLL. 3639 */ 3640 smp_rmb(); 3641 return READ_ONCE(kvm->max_halt_poll_ns); 3642 } 3643 3644 return READ_ONCE(halt_poll_ns); 3645 } 3646 3647 /* 3648 * Emulate a vCPU halt condition, e.g. HLT on x86, WFI on arm, etc... If halt 3649 * polling is enabled, busy wait for a short time before blocking to avoid the 3650 * expensive block+unblock sequence if a wake event arrives soon after the vCPU 3651 * is halted. 3652 */ 3653 void kvm_vcpu_halt(struct kvm_vcpu *vcpu) 3654 { 3655 unsigned int max_halt_poll_ns = kvm_vcpu_max_halt_poll_ns(vcpu); 3656 bool halt_poll_allowed = !kvm_arch_no_poll(vcpu); 3657 ktime_t start, cur, poll_end; 3658 bool waited = false; 3659 bool do_halt_poll; 3660 u64 halt_ns; 3661 3662 if (vcpu->halt_poll_ns > max_halt_poll_ns) 3663 vcpu->halt_poll_ns = max_halt_poll_ns; 3664 3665 do_halt_poll = halt_poll_allowed && vcpu->halt_poll_ns; 3666 3667 start = cur = poll_end = ktime_get(); 3668 if (do_halt_poll) { 3669 ktime_t stop = ktime_add_ns(start, vcpu->halt_poll_ns); 3670 3671 do { 3672 if (kvm_vcpu_check_block(vcpu) < 0) 3673 goto out; 3674 cpu_relax(); 3675 poll_end = cur = ktime_get(); 3676 } while (kvm_vcpu_can_poll(cur, stop)); 3677 } 3678 3679 waited = kvm_vcpu_block(vcpu); 3680 3681 cur = ktime_get(); 3682 if (waited) { 3683 vcpu->stat.generic.halt_wait_ns += 3684 ktime_to_ns(cur) - ktime_to_ns(poll_end); 3685 KVM_STATS_LOG_HIST_UPDATE(vcpu->stat.generic.halt_wait_hist, 3686 ktime_to_ns(cur) - ktime_to_ns(poll_end)); 3687 } 3688 out: 3689 /* The total time the vCPU was "halted", including polling time. */ 3690 halt_ns = ktime_to_ns(cur) - ktime_to_ns(start); 3691 3692 /* 3693 * Note, halt-polling is considered successful so long as the vCPU was 3694 * never actually scheduled out, i.e. even if the wake event arrived 3695 * after of the halt-polling loop itself, but before the full wait. 3696 */ 3697 if (do_halt_poll) 3698 update_halt_poll_stats(vcpu, start, poll_end, !waited); 3699 3700 if (halt_poll_allowed) { 3701 /* Recompute the max halt poll time in case it changed. */ 3702 max_halt_poll_ns = kvm_vcpu_max_halt_poll_ns(vcpu); 3703 3704 if (!vcpu_valid_wakeup(vcpu)) { 3705 shrink_halt_poll_ns(vcpu); 3706 } else if (max_halt_poll_ns) { 3707 if (halt_ns <= vcpu->halt_poll_ns) 3708 ; 3709 /* we had a long block, shrink polling */ 3710 else if (vcpu->halt_poll_ns && 3711 halt_ns > max_halt_poll_ns) 3712 shrink_halt_poll_ns(vcpu); 3713 /* we had a short halt and our poll time is too small */ 3714 else if (vcpu->halt_poll_ns < max_halt_poll_ns && 3715 halt_ns < max_halt_poll_ns) 3716 grow_halt_poll_ns(vcpu); 3717 } else { 3718 vcpu->halt_poll_ns = 0; 3719 } 3720 } 3721 3722 trace_kvm_vcpu_wakeup(halt_ns, waited, vcpu_valid_wakeup(vcpu)); 3723 } 3724 EXPORT_SYMBOL_GPL(kvm_vcpu_halt); 3725 3726 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu) 3727 { 3728 if (__kvm_vcpu_wake_up(vcpu)) { 3729 WRITE_ONCE(vcpu->ready, true); 3730 ++vcpu->stat.generic.halt_wakeup; 3731 return true; 3732 } 3733 3734 return false; 3735 } 3736 EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up); 3737 3738 #ifndef CONFIG_S390 3739 /* 3740 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode. 3741 */ 3742 void kvm_vcpu_kick(struct kvm_vcpu *vcpu) 3743 { 3744 int me, cpu; 3745 3746 if (kvm_vcpu_wake_up(vcpu)) 3747 return; 3748 3749 me = get_cpu(); 3750 /* 3751 * The only state change done outside the vcpu mutex is IN_GUEST_MODE 3752 * to EXITING_GUEST_MODE. Therefore the moderately expensive "should 3753 * kick" check does not need atomic operations if kvm_vcpu_kick is used 3754 * within the vCPU thread itself. 3755 */ 3756 if (vcpu == __this_cpu_read(kvm_running_vcpu)) { 3757 if (vcpu->mode == IN_GUEST_MODE) 3758 WRITE_ONCE(vcpu->mode, EXITING_GUEST_MODE); 3759 goto out; 3760 } 3761 3762 /* 3763 * Note, the vCPU could get migrated to a different pCPU at any point 3764 * after kvm_arch_vcpu_should_kick(), which could result in sending an 3765 * IPI to the previous pCPU. But, that's ok because the purpose of the 3766 * IPI is to force the vCPU to leave IN_GUEST_MODE, and migrating the 3767 * vCPU also requires it to leave IN_GUEST_MODE. 3768 */ 3769 if (kvm_arch_vcpu_should_kick(vcpu)) { 3770 cpu = READ_ONCE(vcpu->cpu); 3771 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu)) 3772 smp_send_reschedule(cpu); 3773 } 3774 out: 3775 put_cpu(); 3776 } 3777 EXPORT_SYMBOL_GPL(kvm_vcpu_kick); 3778 #endif /* !CONFIG_S390 */ 3779 3780 int kvm_vcpu_yield_to(struct kvm_vcpu *target) 3781 { 3782 struct task_struct *task = NULL; 3783 int ret; 3784 3785 if (!read_trylock(&target->pid_lock)) 3786 return 0; 3787 3788 if (target->pid) 3789 task = get_pid_task(target->pid, PIDTYPE_PID); 3790 3791 read_unlock(&target->pid_lock); 3792 3793 if (!task) 3794 return 0; 3795 ret = yield_to(task, 1); 3796 put_task_struct(task); 3797 3798 return ret; 3799 } 3800 EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to); 3801 3802 /* 3803 * Helper that checks whether a VCPU is eligible for directed yield. 3804 * Most eligible candidate to yield is decided by following heuristics: 3805 * 3806 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently 3807 * (preempted lock holder), indicated by @in_spin_loop. 3808 * Set at the beginning and cleared at the end of interception/PLE handler. 3809 * 3810 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get 3811 * chance last time (mostly it has become eligible now since we have probably 3812 * yielded to lockholder in last iteration. This is done by toggling 3813 * @dy_eligible each time a VCPU checked for eligibility.) 3814 * 3815 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding 3816 * to preempted lock-holder could result in wrong VCPU selection and CPU 3817 * burning. Giving priority for a potential lock-holder increases lock 3818 * progress. 3819 * 3820 * Since algorithm is based on heuristics, accessing another VCPU data without 3821 * locking does not harm. It may result in trying to yield to same VCPU, fail 3822 * and continue with next VCPU and so on. 3823 */ 3824 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu) 3825 { 3826 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT 3827 bool eligible; 3828 3829 eligible = !vcpu->spin_loop.in_spin_loop || 3830 vcpu->spin_loop.dy_eligible; 3831 3832 if (vcpu->spin_loop.in_spin_loop) 3833 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible); 3834 3835 return eligible; 3836 #else 3837 return true; 3838 #endif 3839 } 3840 3841 /* 3842 * Unlike kvm_arch_vcpu_runnable, this function is called outside 3843 * a vcpu_load/vcpu_put pair. However, for most architectures 3844 * kvm_arch_vcpu_runnable does not require vcpu_load. 3845 */ 3846 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu) 3847 { 3848 return kvm_arch_vcpu_runnable(vcpu); 3849 } 3850 3851 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu) 3852 { 3853 if (kvm_arch_dy_runnable(vcpu)) 3854 return true; 3855 3856 #ifdef CONFIG_KVM_ASYNC_PF 3857 if (!list_empty_careful(&vcpu->async_pf.done)) 3858 return true; 3859 #endif 3860 3861 return false; 3862 } 3863 3864 /* 3865 * By default, simply query the target vCPU's current mode when checking if a 3866 * vCPU was preempted in kernel mode. All architectures except x86 (or more 3867 * specifical, except VMX) allow querying whether or not a vCPU is in kernel 3868 * mode even if the vCPU is NOT loaded, i.e. using kvm_arch_vcpu_in_kernel() 3869 * directly for cross-vCPU checks is functionally correct and accurate. 3870 */ 3871 bool __weak kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu) 3872 { 3873 return kvm_arch_vcpu_in_kernel(vcpu); 3874 } 3875 3876 bool __weak kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu) 3877 { 3878 return false; 3879 } 3880 3881 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode) 3882 { 3883 int nr_vcpus, start, i, idx, yielded; 3884 struct kvm *kvm = me->kvm; 3885 struct kvm_vcpu *vcpu; 3886 int try = 3; 3887 3888 nr_vcpus = atomic_read(&kvm->online_vcpus); 3889 if (nr_vcpus < 2) 3890 return; 3891 3892 /* Pairs with the smp_wmb() in kvm_vm_ioctl_create_vcpu(). */ 3893 smp_rmb(); 3894 3895 kvm_vcpu_set_in_spin_loop(me, true); 3896 3897 /* 3898 * The current vCPU ("me") is spinning in kernel mode, i.e. is likely 3899 * waiting for a resource to become available. Attempt to yield to a 3900 * vCPU that is runnable, but not currently running, e.g. because the 3901 * vCPU was preempted by a higher priority task. With luck, the vCPU 3902 * that was preempted is holding a lock or some other resource that the 3903 * current vCPU is waiting to acquire, and yielding to the other vCPU 3904 * will allow it to make forward progress and release the lock (or kick 3905 * the spinning vCPU, etc). 3906 * 3907 * Since KVM has no insight into what exactly the guest is doing, 3908 * approximate a round-robin selection by iterating over all vCPUs, 3909 * starting at the last boosted vCPU. I.e. if N=kvm->last_boosted_vcpu, 3910 * iterate over vCPU[N+1]..vCPU[N-1], wrapping as needed. 3911 * 3912 * Note, this is inherently racy, e.g. if multiple vCPUs are spinning, 3913 * they may all try to yield to the same vCPU(s). But as above, this 3914 * is all best effort due to KVM's lack of visibility into the guest. 3915 */ 3916 start = READ_ONCE(kvm->last_boosted_vcpu) + 1; 3917 for (i = 0; i < nr_vcpus; i++) { 3918 idx = (start + i) % nr_vcpus; 3919 if (idx == me->vcpu_idx) 3920 continue; 3921 3922 vcpu = xa_load(&kvm->vcpu_array, idx); 3923 if (!READ_ONCE(vcpu->ready)) 3924 continue; 3925 if (kvm_vcpu_is_blocking(vcpu) && !vcpu_dy_runnable(vcpu)) 3926 continue; 3927 3928 /* 3929 * Treat the target vCPU as being in-kernel if it has a pending 3930 * interrupt, as the vCPU trying to yield may be spinning 3931 * waiting on IPI delivery, i.e. the target vCPU is in-kernel 3932 * for the purposes of directed yield. 3933 */ 3934 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode && 3935 !kvm_arch_dy_has_pending_interrupt(vcpu) && 3936 !kvm_arch_vcpu_preempted_in_kernel(vcpu)) 3937 continue; 3938 3939 if (!kvm_vcpu_eligible_for_directed_yield(vcpu)) 3940 continue; 3941 3942 yielded = kvm_vcpu_yield_to(vcpu); 3943 if (yielded > 0) { 3944 WRITE_ONCE(kvm->last_boosted_vcpu, i); 3945 break; 3946 } else if (yielded < 0 && !--try) { 3947 break; 3948 } 3949 } 3950 kvm_vcpu_set_in_spin_loop(me, false); 3951 3952 /* Ensure vcpu is not eligible during next spinloop */ 3953 kvm_vcpu_set_dy_eligible(me, false); 3954 } 3955 EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin); 3956 3957 static bool kvm_page_in_dirty_ring(struct kvm *kvm, unsigned long pgoff) 3958 { 3959 #ifdef CONFIG_HAVE_KVM_DIRTY_RING 3960 return (pgoff >= KVM_DIRTY_LOG_PAGE_OFFSET) && 3961 (pgoff < KVM_DIRTY_LOG_PAGE_OFFSET + 3962 kvm->dirty_ring_size / PAGE_SIZE); 3963 #else 3964 return false; 3965 #endif 3966 } 3967 3968 static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf) 3969 { 3970 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data; 3971 struct page *page; 3972 3973 if (vmf->pgoff == 0) 3974 page = virt_to_page(vcpu->run); 3975 #ifdef CONFIG_X86 3976 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET) 3977 page = virt_to_page(vcpu->arch.pio_data); 3978 #endif 3979 #ifdef CONFIG_KVM_MMIO 3980 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET) 3981 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring); 3982 #endif 3983 else if (kvm_page_in_dirty_ring(vcpu->kvm, vmf->pgoff)) 3984 page = kvm_dirty_ring_get_page( 3985 &vcpu->dirty_ring, 3986 vmf->pgoff - KVM_DIRTY_LOG_PAGE_OFFSET); 3987 else 3988 return kvm_arch_vcpu_fault(vcpu, vmf); 3989 get_page(page); 3990 vmf->page = page; 3991 return 0; 3992 } 3993 3994 static const struct vm_operations_struct kvm_vcpu_vm_ops = { 3995 .fault = kvm_vcpu_fault, 3996 }; 3997 3998 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma) 3999 { 4000 struct kvm_vcpu *vcpu = file->private_data; 4001 unsigned long pages = vma_pages(vma); 4002 4003 if ((kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff) || 4004 kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff + pages - 1)) && 4005 ((vma->vm_flags & VM_EXEC) || !(vma->vm_flags & VM_SHARED))) 4006 return -EINVAL; 4007 4008 vma->vm_ops = &kvm_vcpu_vm_ops; 4009 return 0; 4010 } 4011 4012 static int kvm_vcpu_release(struct inode *inode, struct file *filp) 4013 { 4014 struct kvm_vcpu *vcpu = filp->private_data; 4015 4016 kvm_put_kvm(vcpu->kvm); 4017 return 0; 4018 } 4019 4020 static struct file_operations kvm_vcpu_fops = { 4021 .release = kvm_vcpu_release, 4022 .unlocked_ioctl = kvm_vcpu_ioctl, 4023 .mmap = kvm_vcpu_mmap, 4024 .llseek = noop_llseek, 4025 KVM_COMPAT(kvm_vcpu_compat_ioctl), 4026 }; 4027 4028 /* 4029 * Allocates an inode for the vcpu. 4030 */ 4031 static int create_vcpu_fd(struct kvm_vcpu *vcpu) 4032 { 4033 char name[8 + 1 + ITOA_MAX_LEN + 1]; 4034 4035 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id); 4036 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC); 4037 } 4038 4039 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS 4040 static int vcpu_get_pid(void *data, u64 *val) 4041 { 4042 struct kvm_vcpu *vcpu = data; 4043 4044 read_lock(&vcpu->pid_lock); 4045 *val = pid_nr(vcpu->pid); 4046 read_unlock(&vcpu->pid_lock); 4047 return 0; 4048 } 4049 4050 DEFINE_SIMPLE_ATTRIBUTE(vcpu_get_pid_fops, vcpu_get_pid, NULL, "%llu\n"); 4051 4052 static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu) 4053 { 4054 struct dentry *debugfs_dentry; 4055 char dir_name[ITOA_MAX_LEN * 2]; 4056 4057 if (!debugfs_initialized()) 4058 return; 4059 4060 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id); 4061 debugfs_dentry = debugfs_create_dir(dir_name, 4062 vcpu->kvm->debugfs_dentry); 4063 debugfs_create_file("pid", 0444, debugfs_dentry, vcpu, 4064 &vcpu_get_pid_fops); 4065 4066 kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry); 4067 } 4068 #endif 4069 4070 /* 4071 * Creates some virtual cpus. Good luck creating more than one. 4072 */ 4073 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, unsigned long id) 4074 { 4075 int r; 4076 struct kvm_vcpu *vcpu; 4077 struct page *page; 4078 4079 /* 4080 * KVM tracks vCPU IDs as 'int', be kind to userspace and reject 4081 * too-large values instead of silently truncating. 4082 * 4083 * Ensure KVM_MAX_VCPU_IDS isn't pushed above INT_MAX without first 4084 * changing the storage type (at the very least, IDs should be tracked 4085 * as unsigned ints). 4086 */ 4087 BUILD_BUG_ON(KVM_MAX_VCPU_IDS > INT_MAX); 4088 if (id >= KVM_MAX_VCPU_IDS) 4089 return -EINVAL; 4090 4091 mutex_lock(&kvm->lock); 4092 if (kvm->created_vcpus >= kvm->max_vcpus) { 4093 mutex_unlock(&kvm->lock); 4094 return -EINVAL; 4095 } 4096 4097 r = kvm_arch_vcpu_precreate(kvm, id); 4098 if (r) { 4099 mutex_unlock(&kvm->lock); 4100 return r; 4101 } 4102 4103 kvm->created_vcpus++; 4104 mutex_unlock(&kvm->lock); 4105 4106 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT); 4107 if (!vcpu) { 4108 r = -ENOMEM; 4109 goto vcpu_decrement; 4110 } 4111 4112 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE); 4113 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO); 4114 if (!page) { 4115 r = -ENOMEM; 4116 goto vcpu_free; 4117 } 4118 vcpu->run = page_address(page); 4119 4120 kvm_vcpu_init(vcpu, kvm, id); 4121 4122 r = kvm_arch_vcpu_create(vcpu); 4123 if (r) 4124 goto vcpu_free_run_page; 4125 4126 if (kvm->dirty_ring_size) { 4127 r = kvm_dirty_ring_alloc(kvm, &vcpu->dirty_ring, 4128 id, kvm->dirty_ring_size); 4129 if (r) 4130 goto arch_vcpu_destroy; 4131 } 4132 4133 mutex_lock(&kvm->lock); 4134 4135 if (kvm_get_vcpu_by_id(kvm, id)) { 4136 r = -EEXIST; 4137 goto unlock_vcpu_destroy; 4138 } 4139 4140 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus); 4141 r = xa_insert(&kvm->vcpu_array, vcpu->vcpu_idx, vcpu, GFP_KERNEL_ACCOUNT); 4142 WARN_ON_ONCE(r == -EBUSY); 4143 if (r) 4144 goto unlock_vcpu_destroy; 4145 4146 /* 4147 * Now it's all set up, let userspace reach it. Grab the vCPU's mutex 4148 * so that userspace can't invoke vCPU ioctl()s until the vCPU is fully 4149 * visible (per online_vcpus), e.g. so that KVM doesn't get tricked 4150 * into a NULL-pointer dereference because KVM thinks the _current_ 4151 * vCPU doesn't exist. As a bonus, taking vcpu->mutex ensures lockdep 4152 * knows it's taken *inside* kvm->lock. 4153 */ 4154 mutex_lock(&vcpu->mutex); 4155 kvm_get_kvm(kvm); 4156 r = create_vcpu_fd(vcpu); 4157 if (r < 0) 4158 goto kvm_put_xa_erase; 4159 4160 /* 4161 * Pairs with smp_rmb() in kvm_get_vcpu. Store the vcpu 4162 * pointer before kvm->online_vcpu's incremented value. 4163 */ 4164 smp_wmb(); 4165 atomic_inc(&kvm->online_vcpus); 4166 mutex_unlock(&vcpu->mutex); 4167 4168 mutex_unlock(&kvm->lock); 4169 kvm_arch_vcpu_postcreate(vcpu); 4170 kvm_create_vcpu_debugfs(vcpu); 4171 return r; 4172 4173 kvm_put_xa_erase: 4174 mutex_unlock(&vcpu->mutex); 4175 kvm_put_kvm_no_destroy(kvm); 4176 xa_erase(&kvm->vcpu_array, vcpu->vcpu_idx); 4177 unlock_vcpu_destroy: 4178 mutex_unlock(&kvm->lock); 4179 kvm_dirty_ring_free(&vcpu->dirty_ring); 4180 arch_vcpu_destroy: 4181 kvm_arch_vcpu_destroy(vcpu); 4182 vcpu_free_run_page: 4183 free_page((unsigned long)vcpu->run); 4184 vcpu_free: 4185 kmem_cache_free(kvm_vcpu_cache, vcpu); 4186 vcpu_decrement: 4187 mutex_lock(&kvm->lock); 4188 kvm->created_vcpus--; 4189 mutex_unlock(&kvm->lock); 4190 return r; 4191 } 4192 4193 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset) 4194 { 4195 if (sigset) { 4196 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP)); 4197 vcpu->sigset_active = 1; 4198 vcpu->sigset = *sigset; 4199 } else 4200 vcpu->sigset_active = 0; 4201 return 0; 4202 } 4203 4204 static ssize_t kvm_vcpu_stats_read(struct file *file, char __user *user_buffer, 4205 size_t size, loff_t *offset) 4206 { 4207 struct kvm_vcpu *vcpu = file->private_data; 4208 4209 return kvm_stats_read(vcpu->stats_id, &kvm_vcpu_stats_header, 4210 &kvm_vcpu_stats_desc[0], &vcpu->stat, 4211 sizeof(vcpu->stat), user_buffer, size, offset); 4212 } 4213 4214 static int kvm_vcpu_stats_release(struct inode *inode, struct file *file) 4215 { 4216 struct kvm_vcpu *vcpu = file->private_data; 4217 4218 kvm_put_kvm(vcpu->kvm); 4219 return 0; 4220 } 4221 4222 static const struct file_operations kvm_vcpu_stats_fops = { 4223 .owner = THIS_MODULE, 4224 .read = kvm_vcpu_stats_read, 4225 .release = kvm_vcpu_stats_release, 4226 .llseek = noop_llseek, 4227 }; 4228 4229 static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu) 4230 { 4231 int fd; 4232 struct file *file; 4233 char name[15 + ITOA_MAX_LEN + 1]; 4234 4235 snprintf(name, sizeof(name), "kvm-vcpu-stats:%d", vcpu->vcpu_id); 4236 4237 fd = get_unused_fd_flags(O_CLOEXEC); 4238 if (fd < 0) 4239 return fd; 4240 4241 file = anon_inode_getfile_fmode(name, &kvm_vcpu_stats_fops, vcpu, 4242 O_RDONLY, FMODE_PREAD); 4243 if (IS_ERR(file)) { 4244 put_unused_fd(fd); 4245 return PTR_ERR(file); 4246 } 4247 4248 kvm_get_kvm(vcpu->kvm); 4249 fd_install(fd, file); 4250 4251 return fd; 4252 } 4253 4254 #ifdef CONFIG_KVM_GENERIC_PRE_FAULT_MEMORY 4255 static int kvm_vcpu_pre_fault_memory(struct kvm_vcpu *vcpu, 4256 struct kvm_pre_fault_memory *range) 4257 { 4258 int idx; 4259 long r; 4260 u64 full_size; 4261 4262 if (range->flags) 4263 return -EINVAL; 4264 4265 if (!PAGE_ALIGNED(range->gpa) || 4266 !PAGE_ALIGNED(range->size) || 4267 range->gpa + range->size <= range->gpa) 4268 return -EINVAL; 4269 4270 vcpu_load(vcpu); 4271 idx = srcu_read_lock(&vcpu->kvm->srcu); 4272 4273 full_size = range->size; 4274 do { 4275 if (signal_pending(current)) { 4276 r = -EINTR; 4277 break; 4278 } 4279 4280 r = kvm_arch_vcpu_pre_fault_memory(vcpu, range); 4281 if (WARN_ON_ONCE(r == 0 || r == -EIO)) 4282 break; 4283 4284 if (r < 0) 4285 break; 4286 4287 range->size -= r; 4288 range->gpa += r; 4289 cond_resched(); 4290 } while (range->size); 4291 4292 srcu_read_unlock(&vcpu->kvm->srcu, idx); 4293 vcpu_put(vcpu); 4294 4295 /* Return success if at least one page was mapped successfully. */ 4296 return full_size == range->size ? r : 0; 4297 } 4298 #endif 4299 4300 static int kvm_wait_for_vcpu_online(struct kvm_vcpu *vcpu) 4301 { 4302 struct kvm *kvm = vcpu->kvm; 4303 4304 /* 4305 * In practice, this happy path will always be taken, as a well-behaved 4306 * VMM will never invoke a vCPU ioctl() before KVM_CREATE_VCPU returns. 4307 */ 4308 if (likely(vcpu->vcpu_idx < atomic_read(&kvm->online_vcpus))) 4309 return 0; 4310 4311 /* 4312 * Acquire and release the vCPU's mutex to wait for vCPU creation to 4313 * complete (kvm_vm_ioctl_create_vcpu() holds the mutex until the vCPU 4314 * is fully online). 4315 */ 4316 if (mutex_lock_killable(&vcpu->mutex)) 4317 return -EINTR; 4318 4319 mutex_unlock(&vcpu->mutex); 4320 4321 if (WARN_ON_ONCE(!kvm_get_vcpu(kvm, vcpu->vcpu_idx))) 4322 return -EIO; 4323 4324 return 0; 4325 } 4326 4327 static long kvm_vcpu_ioctl(struct file *filp, 4328 unsigned int ioctl, unsigned long arg) 4329 { 4330 struct kvm_vcpu *vcpu = filp->private_data; 4331 void __user *argp = (void __user *)arg; 4332 int r; 4333 struct kvm_fpu *fpu = NULL; 4334 struct kvm_sregs *kvm_sregs = NULL; 4335 4336 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead) 4337 return -EIO; 4338 4339 if (unlikely(_IOC_TYPE(ioctl) != KVMIO)) 4340 return -EINVAL; 4341 4342 /* 4343 * Wait for the vCPU to be online before handling the ioctl(), as KVM 4344 * assumes the vCPU is reachable via vcpu_array, i.e. may dereference 4345 * a NULL pointer if userspace invokes an ioctl() before KVM is ready. 4346 */ 4347 r = kvm_wait_for_vcpu_online(vcpu); 4348 if (r) 4349 return r; 4350 4351 /* 4352 * Some architectures have vcpu ioctls that are asynchronous to vcpu 4353 * execution; mutex_lock() would break them. 4354 */ 4355 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg); 4356 if (r != -ENOIOCTLCMD) 4357 return r; 4358 4359 if (mutex_lock_killable(&vcpu->mutex)) 4360 return -EINTR; 4361 switch (ioctl) { 4362 case KVM_RUN: { 4363 struct pid *oldpid; 4364 r = -EINVAL; 4365 if (arg) 4366 goto out; 4367 4368 /* 4369 * Note, vcpu->pid is primarily protected by vcpu->mutex. The 4370 * dedicated r/w lock allows other tasks, e.g. other vCPUs, to 4371 * read vcpu->pid while this vCPU is in KVM_RUN, e.g. to yield 4372 * directly to this vCPU 4373 */ 4374 oldpid = vcpu->pid; 4375 if (unlikely(oldpid != task_pid(current))) { 4376 /* The thread running this VCPU changed. */ 4377 struct pid *newpid; 4378 4379 r = kvm_arch_vcpu_run_pid_change(vcpu); 4380 if (r) 4381 break; 4382 4383 newpid = get_task_pid(current, PIDTYPE_PID); 4384 write_lock(&vcpu->pid_lock); 4385 vcpu->pid = newpid; 4386 write_unlock(&vcpu->pid_lock); 4387 4388 put_pid(oldpid); 4389 } 4390 vcpu->wants_to_run = !READ_ONCE(vcpu->run->immediate_exit__unsafe); 4391 r = kvm_arch_vcpu_ioctl_run(vcpu); 4392 vcpu->wants_to_run = false; 4393 4394 trace_kvm_userspace_exit(vcpu->run->exit_reason, r); 4395 break; 4396 } 4397 case KVM_GET_REGS: { 4398 struct kvm_regs *kvm_regs; 4399 4400 r = -ENOMEM; 4401 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL); 4402 if (!kvm_regs) 4403 goto out; 4404 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs); 4405 if (r) 4406 goto out_free1; 4407 r = -EFAULT; 4408 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs))) 4409 goto out_free1; 4410 r = 0; 4411 out_free1: 4412 kfree(kvm_regs); 4413 break; 4414 } 4415 case KVM_SET_REGS: { 4416 struct kvm_regs *kvm_regs; 4417 4418 kvm_regs = memdup_user(argp, sizeof(*kvm_regs)); 4419 if (IS_ERR(kvm_regs)) { 4420 r = PTR_ERR(kvm_regs); 4421 goto out; 4422 } 4423 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs); 4424 kfree(kvm_regs); 4425 break; 4426 } 4427 case KVM_GET_SREGS: { 4428 kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL); 4429 r = -ENOMEM; 4430 if (!kvm_sregs) 4431 goto out; 4432 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs); 4433 if (r) 4434 goto out; 4435 r = -EFAULT; 4436 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs))) 4437 goto out; 4438 r = 0; 4439 break; 4440 } 4441 case KVM_SET_SREGS: { 4442 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs)); 4443 if (IS_ERR(kvm_sregs)) { 4444 r = PTR_ERR(kvm_sregs); 4445 kvm_sregs = NULL; 4446 goto out; 4447 } 4448 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs); 4449 break; 4450 } 4451 case KVM_GET_MP_STATE: { 4452 struct kvm_mp_state mp_state; 4453 4454 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state); 4455 if (r) 4456 goto out; 4457 r = -EFAULT; 4458 if (copy_to_user(argp, &mp_state, sizeof(mp_state))) 4459 goto out; 4460 r = 0; 4461 break; 4462 } 4463 case KVM_SET_MP_STATE: { 4464 struct kvm_mp_state mp_state; 4465 4466 r = -EFAULT; 4467 if (copy_from_user(&mp_state, argp, sizeof(mp_state))) 4468 goto out; 4469 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state); 4470 break; 4471 } 4472 case KVM_TRANSLATE: { 4473 struct kvm_translation tr; 4474 4475 r = -EFAULT; 4476 if (copy_from_user(&tr, argp, sizeof(tr))) 4477 goto out; 4478 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr); 4479 if (r) 4480 goto out; 4481 r = -EFAULT; 4482 if (copy_to_user(argp, &tr, sizeof(tr))) 4483 goto out; 4484 r = 0; 4485 break; 4486 } 4487 case KVM_SET_GUEST_DEBUG: { 4488 struct kvm_guest_debug dbg; 4489 4490 r = -EFAULT; 4491 if (copy_from_user(&dbg, argp, sizeof(dbg))) 4492 goto out; 4493 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg); 4494 break; 4495 } 4496 case KVM_SET_SIGNAL_MASK: { 4497 struct kvm_signal_mask __user *sigmask_arg = argp; 4498 struct kvm_signal_mask kvm_sigmask; 4499 sigset_t sigset, *p; 4500 4501 p = NULL; 4502 if (argp) { 4503 r = -EFAULT; 4504 if (copy_from_user(&kvm_sigmask, argp, 4505 sizeof(kvm_sigmask))) 4506 goto out; 4507 r = -EINVAL; 4508 if (kvm_sigmask.len != sizeof(sigset)) 4509 goto out; 4510 r = -EFAULT; 4511 if (copy_from_user(&sigset, sigmask_arg->sigset, 4512 sizeof(sigset))) 4513 goto out; 4514 p = &sigset; 4515 } 4516 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p); 4517 break; 4518 } 4519 case KVM_GET_FPU: { 4520 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL); 4521 r = -ENOMEM; 4522 if (!fpu) 4523 goto out; 4524 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu); 4525 if (r) 4526 goto out; 4527 r = -EFAULT; 4528 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu))) 4529 goto out; 4530 r = 0; 4531 break; 4532 } 4533 case KVM_SET_FPU: { 4534 fpu = memdup_user(argp, sizeof(*fpu)); 4535 if (IS_ERR(fpu)) { 4536 r = PTR_ERR(fpu); 4537 fpu = NULL; 4538 goto out; 4539 } 4540 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu); 4541 break; 4542 } 4543 case KVM_GET_STATS_FD: { 4544 r = kvm_vcpu_ioctl_get_stats_fd(vcpu); 4545 break; 4546 } 4547 #ifdef CONFIG_KVM_GENERIC_PRE_FAULT_MEMORY 4548 case KVM_PRE_FAULT_MEMORY: { 4549 struct kvm_pre_fault_memory range; 4550 4551 r = -EFAULT; 4552 if (copy_from_user(&range, argp, sizeof(range))) 4553 break; 4554 r = kvm_vcpu_pre_fault_memory(vcpu, &range); 4555 /* Pass back leftover range. */ 4556 if (copy_to_user(argp, &range, sizeof(range))) 4557 r = -EFAULT; 4558 break; 4559 } 4560 #endif 4561 default: 4562 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg); 4563 } 4564 out: 4565 mutex_unlock(&vcpu->mutex); 4566 kfree(fpu); 4567 kfree(kvm_sregs); 4568 return r; 4569 } 4570 4571 #ifdef CONFIG_KVM_COMPAT 4572 static long kvm_vcpu_compat_ioctl(struct file *filp, 4573 unsigned int ioctl, unsigned long arg) 4574 { 4575 struct kvm_vcpu *vcpu = filp->private_data; 4576 void __user *argp = compat_ptr(arg); 4577 int r; 4578 4579 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead) 4580 return -EIO; 4581 4582 switch (ioctl) { 4583 case KVM_SET_SIGNAL_MASK: { 4584 struct kvm_signal_mask __user *sigmask_arg = argp; 4585 struct kvm_signal_mask kvm_sigmask; 4586 sigset_t sigset; 4587 4588 if (argp) { 4589 r = -EFAULT; 4590 if (copy_from_user(&kvm_sigmask, argp, 4591 sizeof(kvm_sigmask))) 4592 goto out; 4593 r = -EINVAL; 4594 if (kvm_sigmask.len != sizeof(compat_sigset_t)) 4595 goto out; 4596 r = -EFAULT; 4597 if (get_compat_sigset(&sigset, 4598 (compat_sigset_t __user *)sigmask_arg->sigset)) 4599 goto out; 4600 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset); 4601 } else 4602 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL); 4603 break; 4604 } 4605 default: 4606 r = kvm_vcpu_ioctl(filp, ioctl, arg); 4607 } 4608 4609 out: 4610 return r; 4611 } 4612 #endif 4613 4614 static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma) 4615 { 4616 struct kvm_device *dev = filp->private_data; 4617 4618 if (dev->ops->mmap) 4619 return dev->ops->mmap(dev, vma); 4620 4621 return -ENODEV; 4622 } 4623 4624 static int kvm_device_ioctl_attr(struct kvm_device *dev, 4625 int (*accessor)(struct kvm_device *dev, 4626 struct kvm_device_attr *attr), 4627 unsigned long arg) 4628 { 4629 struct kvm_device_attr attr; 4630 4631 if (!accessor) 4632 return -EPERM; 4633 4634 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr))) 4635 return -EFAULT; 4636 4637 return accessor(dev, &attr); 4638 } 4639 4640 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl, 4641 unsigned long arg) 4642 { 4643 struct kvm_device *dev = filp->private_data; 4644 4645 if (dev->kvm->mm != current->mm || dev->kvm->vm_dead) 4646 return -EIO; 4647 4648 switch (ioctl) { 4649 case KVM_SET_DEVICE_ATTR: 4650 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg); 4651 case KVM_GET_DEVICE_ATTR: 4652 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg); 4653 case KVM_HAS_DEVICE_ATTR: 4654 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg); 4655 default: 4656 if (dev->ops->ioctl) 4657 return dev->ops->ioctl(dev, ioctl, arg); 4658 4659 return -ENOTTY; 4660 } 4661 } 4662 4663 static int kvm_device_release(struct inode *inode, struct file *filp) 4664 { 4665 struct kvm_device *dev = filp->private_data; 4666 struct kvm *kvm = dev->kvm; 4667 4668 if (dev->ops->release) { 4669 mutex_lock(&kvm->lock); 4670 list_del_rcu(&dev->vm_node); 4671 synchronize_rcu(); 4672 dev->ops->release(dev); 4673 mutex_unlock(&kvm->lock); 4674 } 4675 4676 kvm_put_kvm(kvm); 4677 return 0; 4678 } 4679 4680 static struct file_operations kvm_device_fops = { 4681 .unlocked_ioctl = kvm_device_ioctl, 4682 .release = kvm_device_release, 4683 KVM_COMPAT(kvm_device_ioctl), 4684 .mmap = kvm_device_mmap, 4685 }; 4686 4687 struct kvm_device *kvm_device_from_filp(struct file *filp) 4688 { 4689 if (filp->f_op != &kvm_device_fops) 4690 return NULL; 4691 4692 return filp->private_data; 4693 } 4694 4695 static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = { 4696 #ifdef CONFIG_KVM_MPIC 4697 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops, 4698 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops, 4699 #endif 4700 }; 4701 4702 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type) 4703 { 4704 if (type >= ARRAY_SIZE(kvm_device_ops_table)) 4705 return -ENOSPC; 4706 4707 if (kvm_device_ops_table[type] != NULL) 4708 return -EEXIST; 4709 4710 kvm_device_ops_table[type] = ops; 4711 return 0; 4712 } 4713 4714 void kvm_unregister_device_ops(u32 type) 4715 { 4716 if (kvm_device_ops_table[type] != NULL) 4717 kvm_device_ops_table[type] = NULL; 4718 } 4719 4720 static int kvm_ioctl_create_device(struct kvm *kvm, 4721 struct kvm_create_device *cd) 4722 { 4723 const struct kvm_device_ops *ops; 4724 struct kvm_device *dev; 4725 bool test = cd->flags & KVM_CREATE_DEVICE_TEST; 4726 int type; 4727 int ret; 4728 4729 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table)) 4730 return -ENODEV; 4731 4732 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table)); 4733 ops = kvm_device_ops_table[type]; 4734 if (ops == NULL) 4735 return -ENODEV; 4736 4737 if (test) 4738 return 0; 4739 4740 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT); 4741 if (!dev) 4742 return -ENOMEM; 4743 4744 dev->ops = ops; 4745 dev->kvm = kvm; 4746 4747 mutex_lock(&kvm->lock); 4748 ret = ops->create(dev, type); 4749 if (ret < 0) { 4750 mutex_unlock(&kvm->lock); 4751 kfree(dev); 4752 return ret; 4753 } 4754 list_add_rcu(&dev->vm_node, &kvm->devices); 4755 mutex_unlock(&kvm->lock); 4756 4757 if (ops->init) 4758 ops->init(dev); 4759 4760 kvm_get_kvm(kvm); 4761 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC); 4762 if (ret < 0) { 4763 kvm_put_kvm_no_destroy(kvm); 4764 mutex_lock(&kvm->lock); 4765 list_del_rcu(&dev->vm_node); 4766 synchronize_rcu(); 4767 if (ops->release) 4768 ops->release(dev); 4769 mutex_unlock(&kvm->lock); 4770 if (ops->destroy) 4771 ops->destroy(dev); 4772 return ret; 4773 } 4774 4775 cd->fd = ret; 4776 return 0; 4777 } 4778 4779 static int kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg) 4780 { 4781 switch (arg) { 4782 case KVM_CAP_USER_MEMORY: 4783 case KVM_CAP_USER_MEMORY2: 4784 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS: 4785 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS: 4786 case KVM_CAP_INTERNAL_ERROR_DATA: 4787 #ifdef CONFIG_HAVE_KVM_MSI 4788 case KVM_CAP_SIGNAL_MSI: 4789 #endif 4790 #ifdef CONFIG_HAVE_KVM_IRQCHIP 4791 case KVM_CAP_IRQFD: 4792 #endif 4793 case KVM_CAP_IOEVENTFD_ANY_LENGTH: 4794 case KVM_CAP_CHECK_EXTENSION_VM: 4795 case KVM_CAP_ENABLE_CAP_VM: 4796 case KVM_CAP_HALT_POLL: 4797 return 1; 4798 #ifdef CONFIG_KVM_MMIO 4799 case KVM_CAP_COALESCED_MMIO: 4800 return KVM_COALESCED_MMIO_PAGE_OFFSET; 4801 case KVM_CAP_COALESCED_PIO: 4802 return 1; 4803 #endif 4804 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT 4805 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: 4806 return KVM_DIRTY_LOG_MANUAL_CAPS; 4807 #endif 4808 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING 4809 case KVM_CAP_IRQ_ROUTING: 4810 return KVM_MAX_IRQ_ROUTES; 4811 #endif 4812 #if KVM_MAX_NR_ADDRESS_SPACES > 1 4813 case KVM_CAP_MULTI_ADDRESS_SPACE: 4814 if (kvm) 4815 return kvm_arch_nr_memslot_as_ids(kvm); 4816 return KVM_MAX_NR_ADDRESS_SPACES; 4817 #endif 4818 case KVM_CAP_NR_MEMSLOTS: 4819 return KVM_USER_MEM_SLOTS; 4820 case KVM_CAP_DIRTY_LOG_RING: 4821 #ifdef CONFIG_HAVE_KVM_DIRTY_RING_TSO 4822 return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn); 4823 #else 4824 return 0; 4825 #endif 4826 case KVM_CAP_DIRTY_LOG_RING_ACQ_REL: 4827 #ifdef CONFIG_HAVE_KVM_DIRTY_RING_ACQ_REL 4828 return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn); 4829 #else 4830 return 0; 4831 #endif 4832 #ifdef CONFIG_NEED_KVM_DIRTY_RING_WITH_BITMAP 4833 case KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP: 4834 #endif 4835 case KVM_CAP_BINARY_STATS_FD: 4836 case KVM_CAP_SYSTEM_EVENT_DATA: 4837 case KVM_CAP_DEVICE_CTRL: 4838 return 1; 4839 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES 4840 case KVM_CAP_MEMORY_ATTRIBUTES: 4841 return kvm_supported_mem_attributes(kvm); 4842 #endif 4843 #ifdef CONFIG_KVM_PRIVATE_MEM 4844 case KVM_CAP_GUEST_MEMFD: 4845 return !kvm || kvm_arch_has_private_mem(kvm); 4846 #endif 4847 default: 4848 break; 4849 } 4850 return kvm_vm_ioctl_check_extension(kvm, arg); 4851 } 4852 4853 static int kvm_vm_ioctl_enable_dirty_log_ring(struct kvm *kvm, u32 size) 4854 { 4855 int r; 4856 4857 if (!KVM_DIRTY_LOG_PAGE_OFFSET) 4858 return -EINVAL; 4859 4860 /* the size should be power of 2 */ 4861 if (!size || (size & (size - 1))) 4862 return -EINVAL; 4863 4864 /* Should be bigger to keep the reserved entries, or a page */ 4865 if (size < kvm_dirty_ring_get_rsvd_entries(kvm) * 4866 sizeof(struct kvm_dirty_gfn) || size < PAGE_SIZE) 4867 return -EINVAL; 4868 4869 if (size > KVM_DIRTY_RING_MAX_ENTRIES * 4870 sizeof(struct kvm_dirty_gfn)) 4871 return -E2BIG; 4872 4873 /* We only allow it to set once */ 4874 if (kvm->dirty_ring_size) 4875 return -EINVAL; 4876 4877 mutex_lock(&kvm->lock); 4878 4879 if (kvm->created_vcpus) { 4880 /* We don't allow to change this value after vcpu created */ 4881 r = -EINVAL; 4882 } else { 4883 kvm->dirty_ring_size = size; 4884 r = 0; 4885 } 4886 4887 mutex_unlock(&kvm->lock); 4888 return r; 4889 } 4890 4891 static int kvm_vm_ioctl_reset_dirty_pages(struct kvm *kvm) 4892 { 4893 unsigned long i; 4894 struct kvm_vcpu *vcpu; 4895 int cleared = 0; 4896 4897 if (!kvm->dirty_ring_size) 4898 return -EINVAL; 4899 4900 mutex_lock(&kvm->slots_lock); 4901 4902 kvm_for_each_vcpu(i, vcpu, kvm) 4903 cleared += kvm_dirty_ring_reset(vcpu->kvm, &vcpu->dirty_ring); 4904 4905 mutex_unlock(&kvm->slots_lock); 4906 4907 if (cleared) 4908 kvm_flush_remote_tlbs(kvm); 4909 4910 return cleared; 4911 } 4912 4913 int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm, 4914 struct kvm_enable_cap *cap) 4915 { 4916 return -EINVAL; 4917 } 4918 4919 bool kvm_are_all_memslots_empty(struct kvm *kvm) 4920 { 4921 int i; 4922 4923 lockdep_assert_held(&kvm->slots_lock); 4924 4925 for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) { 4926 if (!kvm_memslots_empty(__kvm_memslots(kvm, i))) 4927 return false; 4928 } 4929 4930 return true; 4931 } 4932 EXPORT_SYMBOL_GPL(kvm_are_all_memslots_empty); 4933 4934 static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm, 4935 struct kvm_enable_cap *cap) 4936 { 4937 switch (cap->cap) { 4938 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT 4939 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: { 4940 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE; 4941 4942 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE) 4943 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS; 4944 4945 if (cap->flags || (cap->args[0] & ~allowed_options)) 4946 return -EINVAL; 4947 kvm->manual_dirty_log_protect = cap->args[0]; 4948 return 0; 4949 } 4950 #endif 4951 case KVM_CAP_HALT_POLL: { 4952 if (cap->flags || cap->args[0] != (unsigned int)cap->args[0]) 4953 return -EINVAL; 4954 4955 kvm->max_halt_poll_ns = cap->args[0]; 4956 4957 /* 4958 * Ensure kvm->override_halt_poll_ns does not become visible 4959 * before kvm->max_halt_poll_ns. 4960 * 4961 * Pairs with the smp_rmb() in kvm_vcpu_max_halt_poll_ns(). 4962 */ 4963 smp_wmb(); 4964 kvm->override_halt_poll_ns = true; 4965 4966 return 0; 4967 } 4968 case KVM_CAP_DIRTY_LOG_RING: 4969 case KVM_CAP_DIRTY_LOG_RING_ACQ_REL: 4970 if (!kvm_vm_ioctl_check_extension_generic(kvm, cap->cap)) 4971 return -EINVAL; 4972 4973 return kvm_vm_ioctl_enable_dirty_log_ring(kvm, cap->args[0]); 4974 case KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP: { 4975 int r = -EINVAL; 4976 4977 if (!IS_ENABLED(CONFIG_NEED_KVM_DIRTY_RING_WITH_BITMAP) || 4978 !kvm->dirty_ring_size || cap->flags) 4979 return r; 4980 4981 mutex_lock(&kvm->slots_lock); 4982 4983 /* 4984 * For simplicity, allow enabling ring+bitmap if and only if 4985 * there are no memslots, e.g. to ensure all memslots allocate 4986 * a bitmap after the capability is enabled. 4987 */ 4988 if (kvm_are_all_memslots_empty(kvm)) { 4989 kvm->dirty_ring_with_bitmap = true; 4990 r = 0; 4991 } 4992 4993 mutex_unlock(&kvm->slots_lock); 4994 4995 return r; 4996 } 4997 default: 4998 return kvm_vm_ioctl_enable_cap(kvm, cap); 4999 } 5000 } 5001 5002 static ssize_t kvm_vm_stats_read(struct file *file, char __user *user_buffer, 5003 size_t size, loff_t *offset) 5004 { 5005 struct kvm *kvm = file->private_data; 5006 5007 return kvm_stats_read(kvm->stats_id, &kvm_vm_stats_header, 5008 &kvm_vm_stats_desc[0], &kvm->stat, 5009 sizeof(kvm->stat), user_buffer, size, offset); 5010 } 5011 5012 static int kvm_vm_stats_release(struct inode *inode, struct file *file) 5013 { 5014 struct kvm *kvm = file->private_data; 5015 5016 kvm_put_kvm(kvm); 5017 return 0; 5018 } 5019 5020 static const struct file_operations kvm_vm_stats_fops = { 5021 .owner = THIS_MODULE, 5022 .read = kvm_vm_stats_read, 5023 .release = kvm_vm_stats_release, 5024 .llseek = noop_llseek, 5025 }; 5026 5027 static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm) 5028 { 5029 int fd; 5030 struct file *file; 5031 5032 fd = get_unused_fd_flags(O_CLOEXEC); 5033 if (fd < 0) 5034 return fd; 5035 5036 file = anon_inode_getfile_fmode("kvm-vm-stats", 5037 &kvm_vm_stats_fops, kvm, O_RDONLY, FMODE_PREAD); 5038 if (IS_ERR(file)) { 5039 put_unused_fd(fd); 5040 return PTR_ERR(file); 5041 } 5042 5043 kvm_get_kvm(kvm); 5044 fd_install(fd, file); 5045 5046 return fd; 5047 } 5048 5049 #define SANITY_CHECK_MEM_REGION_FIELD(field) \ 5050 do { \ 5051 BUILD_BUG_ON(offsetof(struct kvm_userspace_memory_region, field) != \ 5052 offsetof(struct kvm_userspace_memory_region2, field)); \ 5053 BUILD_BUG_ON(sizeof_field(struct kvm_userspace_memory_region, field) != \ 5054 sizeof_field(struct kvm_userspace_memory_region2, field)); \ 5055 } while (0) 5056 5057 static long kvm_vm_ioctl(struct file *filp, 5058 unsigned int ioctl, unsigned long arg) 5059 { 5060 struct kvm *kvm = filp->private_data; 5061 void __user *argp = (void __user *)arg; 5062 int r; 5063 5064 if (kvm->mm != current->mm || kvm->vm_dead) 5065 return -EIO; 5066 switch (ioctl) { 5067 case KVM_CREATE_VCPU: 5068 r = kvm_vm_ioctl_create_vcpu(kvm, arg); 5069 break; 5070 case KVM_ENABLE_CAP: { 5071 struct kvm_enable_cap cap; 5072 5073 r = -EFAULT; 5074 if (copy_from_user(&cap, argp, sizeof(cap))) 5075 goto out; 5076 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap); 5077 break; 5078 } 5079 case KVM_SET_USER_MEMORY_REGION2: 5080 case KVM_SET_USER_MEMORY_REGION: { 5081 struct kvm_userspace_memory_region2 mem; 5082 unsigned long size; 5083 5084 if (ioctl == KVM_SET_USER_MEMORY_REGION) { 5085 /* 5086 * Fields beyond struct kvm_userspace_memory_region shouldn't be 5087 * accessed, but avoid leaking kernel memory in case of a bug. 5088 */ 5089 memset(&mem, 0, sizeof(mem)); 5090 size = sizeof(struct kvm_userspace_memory_region); 5091 } else { 5092 size = sizeof(struct kvm_userspace_memory_region2); 5093 } 5094 5095 /* Ensure the common parts of the two structs are identical. */ 5096 SANITY_CHECK_MEM_REGION_FIELD(slot); 5097 SANITY_CHECK_MEM_REGION_FIELD(flags); 5098 SANITY_CHECK_MEM_REGION_FIELD(guest_phys_addr); 5099 SANITY_CHECK_MEM_REGION_FIELD(memory_size); 5100 SANITY_CHECK_MEM_REGION_FIELD(userspace_addr); 5101 5102 r = -EFAULT; 5103 if (copy_from_user(&mem, argp, size)) 5104 goto out; 5105 5106 r = -EINVAL; 5107 if (ioctl == KVM_SET_USER_MEMORY_REGION && 5108 (mem.flags & ~KVM_SET_USER_MEMORY_REGION_V1_FLAGS)) 5109 goto out; 5110 5111 r = kvm_vm_ioctl_set_memory_region(kvm, &mem); 5112 break; 5113 } 5114 case KVM_GET_DIRTY_LOG: { 5115 struct kvm_dirty_log log; 5116 5117 r = -EFAULT; 5118 if (copy_from_user(&log, argp, sizeof(log))) 5119 goto out; 5120 r = kvm_vm_ioctl_get_dirty_log(kvm, &log); 5121 break; 5122 } 5123 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT 5124 case KVM_CLEAR_DIRTY_LOG: { 5125 struct kvm_clear_dirty_log log; 5126 5127 r = -EFAULT; 5128 if (copy_from_user(&log, argp, sizeof(log))) 5129 goto out; 5130 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log); 5131 break; 5132 } 5133 #endif 5134 #ifdef CONFIG_KVM_MMIO 5135 case KVM_REGISTER_COALESCED_MMIO: { 5136 struct kvm_coalesced_mmio_zone zone; 5137 5138 r = -EFAULT; 5139 if (copy_from_user(&zone, argp, sizeof(zone))) 5140 goto out; 5141 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone); 5142 break; 5143 } 5144 case KVM_UNREGISTER_COALESCED_MMIO: { 5145 struct kvm_coalesced_mmio_zone zone; 5146 5147 r = -EFAULT; 5148 if (copy_from_user(&zone, argp, sizeof(zone))) 5149 goto out; 5150 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone); 5151 break; 5152 } 5153 #endif 5154 case KVM_IRQFD: { 5155 struct kvm_irqfd data; 5156 5157 r = -EFAULT; 5158 if (copy_from_user(&data, argp, sizeof(data))) 5159 goto out; 5160 r = kvm_irqfd(kvm, &data); 5161 break; 5162 } 5163 case KVM_IOEVENTFD: { 5164 struct kvm_ioeventfd data; 5165 5166 r = -EFAULT; 5167 if (copy_from_user(&data, argp, sizeof(data))) 5168 goto out; 5169 r = kvm_ioeventfd(kvm, &data); 5170 break; 5171 } 5172 #ifdef CONFIG_HAVE_KVM_MSI 5173 case KVM_SIGNAL_MSI: { 5174 struct kvm_msi msi; 5175 5176 r = -EFAULT; 5177 if (copy_from_user(&msi, argp, sizeof(msi))) 5178 goto out; 5179 r = kvm_send_userspace_msi(kvm, &msi); 5180 break; 5181 } 5182 #endif 5183 #ifdef __KVM_HAVE_IRQ_LINE 5184 case KVM_IRQ_LINE_STATUS: 5185 case KVM_IRQ_LINE: { 5186 struct kvm_irq_level irq_event; 5187 5188 r = -EFAULT; 5189 if (copy_from_user(&irq_event, argp, sizeof(irq_event))) 5190 goto out; 5191 5192 r = kvm_vm_ioctl_irq_line(kvm, &irq_event, 5193 ioctl == KVM_IRQ_LINE_STATUS); 5194 if (r) 5195 goto out; 5196 5197 r = -EFAULT; 5198 if (ioctl == KVM_IRQ_LINE_STATUS) { 5199 if (copy_to_user(argp, &irq_event, sizeof(irq_event))) 5200 goto out; 5201 } 5202 5203 r = 0; 5204 break; 5205 } 5206 #endif 5207 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING 5208 case KVM_SET_GSI_ROUTING: { 5209 struct kvm_irq_routing routing; 5210 struct kvm_irq_routing __user *urouting; 5211 struct kvm_irq_routing_entry *entries = NULL; 5212 5213 r = -EFAULT; 5214 if (copy_from_user(&routing, argp, sizeof(routing))) 5215 goto out; 5216 r = -EINVAL; 5217 if (!kvm_arch_can_set_irq_routing(kvm)) 5218 goto out; 5219 if (routing.nr > KVM_MAX_IRQ_ROUTES) 5220 goto out; 5221 if (routing.flags) 5222 goto out; 5223 if (routing.nr) { 5224 urouting = argp; 5225 entries = vmemdup_array_user(urouting->entries, 5226 routing.nr, sizeof(*entries)); 5227 if (IS_ERR(entries)) { 5228 r = PTR_ERR(entries); 5229 goto out; 5230 } 5231 } 5232 r = kvm_set_irq_routing(kvm, entries, routing.nr, 5233 routing.flags); 5234 kvfree(entries); 5235 break; 5236 } 5237 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */ 5238 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES 5239 case KVM_SET_MEMORY_ATTRIBUTES: { 5240 struct kvm_memory_attributes attrs; 5241 5242 r = -EFAULT; 5243 if (copy_from_user(&attrs, argp, sizeof(attrs))) 5244 goto out; 5245 5246 r = kvm_vm_ioctl_set_mem_attributes(kvm, &attrs); 5247 break; 5248 } 5249 #endif /* CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES */ 5250 case KVM_CREATE_DEVICE: { 5251 struct kvm_create_device cd; 5252 5253 r = -EFAULT; 5254 if (copy_from_user(&cd, argp, sizeof(cd))) 5255 goto out; 5256 5257 r = kvm_ioctl_create_device(kvm, &cd); 5258 if (r) 5259 goto out; 5260 5261 r = -EFAULT; 5262 if (copy_to_user(argp, &cd, sizeof(cd))) 5263 goto out; 5264 5265 r = 0; 5266 break; 5267 } 5268 case KVM_CHECK_EXTENSION: 5269 r = kvm_vm_ioctl_check_extension_generic(kvm, arg); 5270 break; 5271 case KVM_RESET_DIRTY_RINGS: 5272 r = kvm_vm_ioctl_reset_dirty_pages(kvm); 5273 break; 5274 case KVM_GET_STATS_FD: 5275 r = kvm_vm_ioctl_get_stats_fd(kvm); 5276 break; 5277 #ifdef CONFIG_KVM_PRIVATE_MEM 5278 case KVM_CREATE_GUEST_MEMFD: { 5279 struct kvm_create_guest_memfd guest_memfd; 5280 5281 r = -EFAULT; 5282 if (copy_from_user(&guest_memfd, argp, sizeof(guest_memfd))) 5283 goto out; 5284 5285 r = kvm_gmem_create(kvm, &guest_memfd); 5286 break; 5287 } 5288 #endif 5289 default: 5290 r = kvm_arch_vm_ioctl(filp, ioctl, arg); 5291 } 5292 out: 5293 return r; 5294 } 5295 5296 #ifdef CONFIG_KVM_COMPAT 5297 struct compat_kvm_dirty_log { 5298 __u32 slot; 5299 __u32 padding1; 5300 union { 5301 compat_uptr_t dirty_bitmap; /* one bit per page */ 5302 __u64 padding2; 5303 }; 5304 }; 5305 5306 struct compat_kvm_clear_dirty_log { 5307 __u32 slot; 5308 __u32 num_pages; 5309 __u64 first_page; 5310 union { 5311 compat_uptr_t dirty_bitmap; /* one bit per page */ 5312 __u64 padding2; 5313 }; 5314 }; 5315 5316 long __weak kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl, 5317 unsigned long arg) 5318 { 5319 return -ENOTTY; 5320 } 5321 5322 static long kvm_vm_compat_ioctl(struct file *filp, 5323 unsigned int ioctl, unsigned long arg) 5324 { 5325 struct kvm *kvm = filp->private_data; 5326 int r; 5327 5328 if (kvm->mm != current->mm || kvm->vm_dead) 5329 return -EIO; 5330 5331 r = kvm_arch_vm_compat_ioctl(filp, ioctl, arg); 5332 if (r != -ENOTTY) 5333 return r; 5334 5335 switch (ioctl) { 5336 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT 5337 case KVM_CLEAR_DIRTY_LOG: { 5338 struct compat_kvm_clear_dirty_log compat_log; 5339 struct kvm_clear_dirty_log log; 5340 5341 if (copy_from_user(&compat_log, (void __user *)arg, 5342 sizeof(compat_log))) 5343 return -EFAULT; 5344 log.slot = compat_log.slot; 5345 log.num_pages = compat_log.num_pages; 5346 log.first_page = compat_log.first_page; 5347 log.padding2 = compat_log.padding2; 5348 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap); 5349 5350 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log); 5351 break; 5352 } 5353 #endif 5354 case KVM_GET_DIRTY_LOG: { 5355 struct compat_kvm_dirty_log compat_log; 5356 struct kvm_dirty_log log; 5357 5358 if (copy_from_user(&compat_log, (void __user *)arg, 5359 sizeof(compat_log))) 5360 return -EFAULT; 5361 log.slot = compat_log.slot; 5362 log.padding1 = compat_log.padding1; 5363 log.padding2 = compat_log.padding2; 5364 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap); 5365 5366 r = kvm_vm_ioctl_get_dirty_log(kvm, &log); 5367 break; 5368 } 5369 default: 5370 r = kvm_vm_ioctl(filp, ioctl, arg); 5371 } 5372 return r; 5373 } 5374 #endif 5375 5376 static struct file_operations kvm_vm_fops = { 5377 .release = kvm_vm_release, 5378 .unlocked_ioctl = kvm_vm_ioctl, 5379 .llseek = noop_llseek, 5380 KVM_COMPAT(kvm_vm_compat_ioctl), 5381 }; 5382 5383 bool file_is_kvm(struct file *file) 5384 { 5385 return file && file->f_op == &kvm_vm_fops; 5386 } 5387 EXPORT_SYMBOL_GPL(file_is_kvm); 5388 5389 static int kvm_dev_ioctl_create_vm(unsigned long type) 5390 { 5391 char fdname[ITOA_MAX_LEN + 1]; 5392 int r, fd; 5393 struct kvm *kvm; 5394 struct file *file; 5395 5396 fd = get_unused_fd_flags(O_CLOEXEC); 5397 if (fd < 0) 5398 return fd; 5399 5400 snprintf(fdname, sizeof(fdname), "%d", fd); 5401 5402 kvm = kvm_create_vm(type, fdname); 5403 if (IS_ERR(kvm)) { 5404 r = PTR_ERR(kvm); 5405 goto put_fd; 5406 } 5407 5408 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR); 5409 if (IS_ERR(file)) { 5410 r = PTR_ERR(file); 5411 goto put_kvm; 5412 } 5413 5414 /* 5415 * Don't call kvm_put_kvm anymore at this point; file->f_op is 5416 * already set, with ->release() being kvm_vm_release(). In error 5417 * cases it will be called by the final fput(file) and will take 5418 * care of doing kvm_put_kvm(kvm). 5419 */ 5420 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm); 5421 5422 fd_install(fd, file); 5423 return fd; 5424 5425 put_kvm: 5426 kvm_put_kvm(kvm); 5427 put_fd: 5428 put_unused_fd(fd); 5429 return r; 5430 } 5431 5432 static long kvm_dev_ioctl(struct file *filp, 5433 unsigned int ioctl, unsigned long arg) 5434 { 5435 int r = -EINVAL; 5436 5437 switch (ioctl) { 5438 case KVM_GET_API_VERSION: 5439 if (arg) 5440 goto out; 5441 r = KVM_API_VERSION; 5442 break; 5443 case KVM_CREATE_VM: 5444 r = kvm_dev_ioctl_create_vm(arg); 5445 break; 5446 case KVM_CHECK_EXTENSION: 5447 r = kvm_vm_ioctl_check_extension_generic(NULL, arg); 5448 break; 5449 case KVM_GET_VCPU_MMAP_SIZE: 5450 if (arg) 5451 goto out; 5452 r = PAGE_SIZE; /* struct kvm_run */ 5453 #ifdef CONFIG_X86 5454 r += PAGE_SIZE; /* pio data page */ 5455 #endif 5456 #ifdef CONFIG_KVM_MMIO 5457 r += PAGE_SIZE; /* coalesced mmio ring page */ 5458 #endif 5459 break; 5460 default: 5461 return kvm_arch_dev_ioctl(filp, ioctl, arg); 5462 } 5463 out: 5464 return r; 5465 } 5466 5467 static struct file_operations kvm_chardev_ops = { 5468 .unlocked_ioctl = kvm_dev_ioctl, 5469 .llseek = noop_llseek, 5470 KVM_COMPAT(kvm_dev_ioctl), 5471 }; 5472 5473 static struct miscdevice kvm_dev = { 5474 KVM_MINOR, 5475 "kvm", 5476 &kvm_chardev_ops, 5477 }; 5478 5479 #ifdef CONFIG_KVM_GENERIC_HARDWARE_ENABLING 5480 bool enable_virt_at_load = true; 5481 module_param(enable_virt_at_load, bool, 0444); 5482 EXPORT_SYMBOL_GPL(enable_virt_at_load); 5483 5484 __visible bool kvm_rebooting; 5485 EXPORT_SYMBOL_GPL(kvm_rebooting); 5486 5487 static DEFINE_PER_CPU(bool, virtualization_enabled); 5488 static DEFINE_MUTEX(kvm_usage_lock); 5489 static int kvm_usage_count; 5490 5491 __weak void kvm_arch_enable_virtualization(void) 5492 { 5493 5494 } 5495 5496 __weak void kvm_arch_disable_virtualization(void) 5497 { 5498 5499 } 5500 5501 static int kvm_enable_virtualization_cpu(void) 5502 { 5503 if (__this_cpu_read(virtualization_enabled)) 5504 return 0; 5505 5506 if (kvm_arch_enable_virtualization_cpu()) { 5507 pr_info("kvm: enabling virtualization on CPU%d failed\n", 5508 raw_smp_processor_id()); 5509 return -EIO; 5510 } 5511 5512 __this_cpu_write(virtualization_enabled, true); 5513 return 0; 5514 } 5515 5516 static int kvm_online_cpu(unsigned int cpu) 5517 { 5518 /* 5519 * Abort the CPU online process if hardware virtualization cannot 5520 * be enabled. Otherwise running VMs would encounter unrecoverable 5521 * errors when scheduled to this CPU. 5522 */ 5523 return kvm_enable_virtualization_cpu(); 5524 } 5525 5526 static void kvm_disable_virtualization_cpu(void *ign) 5527 { 5528 if (!__this_cpu_read(virtualization_enabled)) 5529 return; 5530 5531 kvm_arch_disable_virtualization_cpu(); 5532 5533 __this_cpu_write(virtualization_enabled, false); 5534 } 5535 5536 static int kvm_offline_cpu(unsigned int cpu) 5537 { 5538 kvm_disable_virtualization_cpu(NULL); 5539 return 0; 5540 } 5541 5542 static void kvm_shutdown(void) 5543 { 5544 /* 5545 * Disable hardware virtualization and set kvm_rebooting to indicate 5546 * that KVM has asynchronously disabled hardware virtualization, i.e. 5547 * that relevant errors and exceptions aren't entirely unexpected. 5548 * Some flavors of hardware virtualization need to be disabled before 5549 * transferring control to firmware (to perform shutdown/reboot), e.g. 5550 * on x86, virtualization can block INIT interrupts, which are used by 5551 * firmware to pull APs back under firmware control. Note, this path 5552 * is used for both shutdown and reboot scenarios, i.e. neither name is 5553 * 100% comprehensive. 5554 */ 5555 pr_info("kvm: exiting hardware virtualization\n"); 5556 kvm_rebooting = true; 5557 on_each_cpu(kvm_disable_virtualization_cpu, NULL, 1); 5558 } 5559 5560 static int kvm_suspend(void) 5561 { 5562 /* 5563 * Secondary CPUs and CPU hotplug are disabled across the suspend/resume 5564 * callbacks, i.e. no need to acquire kvm_usage_lock to ensure the usage 5565 * count is stable. Assert that kvm_usage_lock is not held to ensure 5566 * the system isn't suspended while KVM is enabling hardware. Hardware 5567 * enabling can be preempted, but the task cannot be frozen until it has 5568 * dropped all locks (userspace tasks are frozen via a fake signal). 5569 */ 5570 lockdep_assert_not_held(&kvm_usage_lock); 5571 lockdep_assert_irqs_disabled(); 5572 5573 kvm_disable_virtualization_cpu(NULL); 5574 return 0; 5575 } 5576 5577 static void kvm_resume(void) 5578 { 5579 lockdep_assert_not_held(&kvm_usage_lock); 5580 lockdep_assert_irqs_disabled(); 5581 5582 WARN_ON_ONCE(kvm_enable_virtualization_cpu()); 5583 } 5584 5585 static struct syscore_ops kvm_syscore_ops = { 5586 .suspend = kvm_suspend, 5587 .resume = kvm_resume, 5588 .shutdown = kvm_shutdown, 5589 }; 5590 5591 int kvm_enable_virtualization(void) 5592 { 5593 int r; 5594 5595 guard(mutex)(&kvm_usage_lock); 5596 5597 if (kvm_usage_count++) 5598 return 0; 5599 5600 kvm_arch_enable_virtualization(); 5601 5602 r = cpuhp_setup_state(CPUHP_AP_KVM_ONLINE, "kvm/cpu:online", 5603 kvm_online_cpu, kvm_offline_cpu); 5604 if (r) 5605 goto err_cpuhp; 5606 5607 register_syscore_ops(&kvm_syscore_ops); 5608 5609 /* 5610 * Undo virtualization enabling and bail if the system is going down. 5611 * If userspace initiated a forced reboot, e.g. reboot -f, then it's 5612 * possible for an in-flight operation to enable virtualization after 5613 * syscore_shutdown() is called, i.e. without kvm_shutdown() being 5614 * invoked. Note, this relies on system_state being set _before_ 5615 * kvm_shutdown(), e.g. to ensure either kvm_shutdown() is invoked 5616 * or this CPU observes the impending shutdown. Which is why KVM uses 5617 * a syscore ops hook instead of registering a dedicated reboot 5618 * notifier (the latter runs before system_state is updated). 5619 */ 5620 if (system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF || 5621 system_state == SYSTEM_RESTART) { 5622 r = -EBUSY; 5623 goto err_rebooting; 5624 } 5625 5626 return 0; 5627 5628 err_rebooting: 5629 unregister_syscore_ops(&kvm_syscore_ops); 5630 cpuhp_remove_state(CPUHP_AP_KVM_ONLINE); 5631 err_cpuhp: 5632 kvm_arch_disable_virtualization(); 5633 --kvm_usage_count; 5634 return r; 5635 } 5636 EXPORT_SYMBOL_GPL(kvm_enable_virtualization); 5637 5638 void kvm_disable_virtualization(void) 5639 { 5640 guard(mutex)(&kvm_usage_lock); 5641 5642 if (--kvm_usage_count) 5643 return; 5644 5645 unregister_syscore_ops(&kvm_syscore_ops); 5646 cpuhp_remove_state(CPUHP_AP_KVM_ONLINE); 5647 kvm_arch_disable_virtualization(); 5648 } 5649 EXPORT_SYMBOL_GPL(kvm_disable_virtualization); 5650 5651 static int kvm_init_virtualization(void) 5652 { 5653 if (enable_virt_at_load) 5654 return kvm_enable_virtualization(); 5655 5656 return 0; 5657 } 5658 5659 static void kvm_uninit_virtualization(void) 5660 { 5661 if (enable_virt_at_load) 5662 kvm_disable_virtualization(); 5663 } 5664 #else /* CONFIG_KVM_GENERIC_HARDWARE_ENABLING */ 5665 static int kvm_init_virtualization(void) 5666 { 5667 return 0; 5668 } 5669 5670 static void kvm_uninit_virtualization(void) 5671 { 5672 5673 } 5674 #endif /* CONFIG_KVM_GENERIC_HARDWARE_ENABLING */ 5675 5676 static void kvm_iodevice_destructor(struct kvm_io_device *dev) 5677 { 5678 if (dev->ops->destructor) 5679 dev->ops->destructor(dev); 5680 } 5681 5682 static void kvm_io_bus_destroy(struct kvm_io_bus *bus) 5683 { 5684 int i; 5685 5686 for (i = 0; i < bus->dev_count; i++) { 5687 struct kvm_io_device *pos = bus->range[i].dev; 5688 5689 kvm_iodevice_destructor(pos); 5690 } 5691 kfree(bus); 5692 } 5693 5694 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1, 5695 const struct kvm_io_range *r2) 5696 { 5697 gpa_t addr1 = r1->addr; 5698 gpa_t addr2 = r2->addr; 5699 5700 if (addr1 < addr2) 5701 return -1; 5702 5703 /* If r2->len == 0, match the exact address. If r2->len != 0, 5704 * accept any overlapping write. Any order is acceptable for 5705 * overlapping ranges, because kvm_io_bus_get_first_dev ensures 5706 * we process all of them. 5707 */ 5708 if (r2->len) { 5709 addr1 += r1->len; 5710 addr2 += r2->len; 5711 } 5712 5713 if (addr1 > addr2) 5714 return 1; 5715 5716 return 0; 5717 } 5718 5719 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2) 5720 { 5721 return kvm_io_bus_cmp(p1, p2); 5722 } 5723 5724 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus, 5725 gpa_t addr, int len) 5726 { 5727 struct kvm_io_range *range, key; 5728 int off; 5729 5730 key = (struct kvm_io_range) { 5731 .addr = addr, 5732 .len = len, 5733 }; 5734 5735 range = bsearch(&key, bus->range, bus->dev_count, 5736 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp); 5737 if (range == NULL) 5738 return -ENOENT; 5739 5740 off = range - bus->range; 5741 5742 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0) 5743 off--; 5744 5745 return off; 5746 } 5747 5748 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus, 5749 struct kvm_io_range *range, const void *val) 5750 { 5751 int idx; 5752 5753 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len); 5754 if (idx < 0) 5755 return -EOPNOTSUPP; 5756 5757 while (idx < bus->dev_count && 5758 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) { 5759 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr, 5760 range->len, val)) 5761 return idx; 5762 idx++; 5763 } 5764 5765 return -EOPNOTSUPP; 5766 } 5767 5768 /* kvm_io_bus_write - called under kvm->slots_lock */ 5769 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr, 5770 int len, const void *val) 5771 { 5772 struct kvm_io_bus *bus; 5773 struct kvm_io_range range; 5774 int r; 5775 5776 range = (struct kvm_io_range) { 5777 .addr = addr, 5778 .len = len, 5779 }; 5780 5781 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu); 5782 if (!bus) 5783 return -ENOMEM; 5784 r = __kvm_io_bus_write(vcpu, bus, &range, val); 5785 return r < 0 ? r : 0; 5786 } 5787 EXPORT_SYMBOL_GPL(kvm_io_bus_write); 5788 5789 /* kvm_io_bus_write_cookie - called under kvm->slots_lock */ 5790 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, 5791 gpa_t addr, int len, const void *val, long cookie) 5792 { 5793 struct kvm_io_bus *bus; 5794 struct kvm_io_range range; 5795 5796 range = (struct kvm_io_range) { 5797 .addr = addr, 5798 .len = len, 5799 }; 5800 5801 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu); 5802 if (!bus) 5803 return -ENOMEM; 5804 5805 /* First try the device referenced by cookie. */ 5806 if ((cookie >= 0) && (cookie < bus->dev_count) && 5807 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0)) 5808 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len, 5809 val)) 5810 return cookie; 5811 5812 /* 5813 * cookie contained garbage; fall back to search and return the 5814 * correct cookie value. 5815 */ 5816 return __kvm_io_bus_write(vcpu, bus, &range, val); 5817 } 5818 5819 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus, 5820 struct kvm_io_range *range, void *val) 5821 { 5822 int idx; 5823 5824 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len); 5825 if (idx < 0) 5826 return -EOPNOTSUPP; 5827 5828 while (idx < bus->dev_count && 5829 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) { 5830 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr, 5831 range->len, val)) 5832 return idx; 5833 idx++; 5834 } 5835 5836 return -EOPNOTSUPP; 5837 } 5838 5839 /* kvm_io_bus_read - called under kvm->slots_lock */ 5840 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr, 5841 int len, void *val) 5842 { 5843 struct kvm_io_bus *bus; 5844 struct kvm_io_range range; 5845 int r; 5846 5847 range = (struct kvm_io_range) { 5848 .addr = addr, 5849 .len = len, 5850 }; 5851 5852 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu); 5853 if (!bus) 5854 return -ENOMEM; 5855 r = __kvm_io_bus_read(vcpu, bus, &range, val); 5856 return r < 0 ? r : 0; 5857 } 5858 EXPORT_SYMBOL_GPL(kvm_io_bus_read); 5859 5860 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr, 5861 int len, struct kvm_io_device *dev) 5862 { 5863 int i; 5864 struct kvm_io_bus *new_bus, *bus; 5865 struct kvm_io_range range; 5866 5867 lockdep_assert_held(&kvm->slots_lock); 5868 5869 bus = kvm_get_bus(kvm, bus_idx); 5870 if (!bus) 5871 return -ENOMEM; 5872 5873 /* exclude ioeventfd which is limited by maximum fd */ 5874 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1) 5875 return -ENOSPC; 5876 5877 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1), 5878 GFP_KERNEL_ACCOUNT); 5879 if (!new_bus) 5880 return -ENOMEM; 5881 5882 range = (struct kvm_io_range) { 5883 .addr = addr, 5884 .len = len, 5885 .dev = dev, 5886 }; 5887 5888 for (i = 0; i < bus->dev_count; i++) 5889 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0) 5890 break; 5891 5892 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range)); 5893 new_bus->dev_count++; 5894 new_bus->range[i] = range; 5895 memcpy(new_bus->range + i + 1, bus->range + i, 5896 (bus->dev_count - i) * sizeof(struct kvm_io_range)); 5897 rcu_assign_pointer(kvm->buses[bus_idx], new_bus); 5898 synchronize_srcu_expedited(&kvm->srcu); 5899 kfree(bus); 5900 5901 return 0; 5902 } 5903 5904 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx, 5905 struct kvm_io_device *dev) 5906 { 5907 int i; 5908 struct kvm_io_bus *new_bus, *bus; 5909 5910 lockdep_assert_held(&kvm->slots_lock); 5911 5912 bus = kvm_get_bus(kvm, bus_idx); 5913 if (!bus) 5914 return 0; 5915 5916 for (i = 0; i < bus->dev_count; i++) { 5917 if (bus->range[i].dev == dev) { 5918 break; 5919 } 5920 } 5921 5922 if (i == bus->dev_count) 5923 return 0; 5924 5925 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1), 5926 GFP_KERNEL_ACCOUNT); 5927 if (new_bus) { 5928 memcpy(new_bus, bus, struct_size(bus, range, i)); 5929 new_bus->dev_count--; 5930 memcpy(new_bus->range + i, bus->range + i + 1, 5931 flex_array_size(new_bus, range, new_bus->dev_count - i)); 5932 } 5933 5934 rcu_assign_pointer(kvm->buses[bus_idx], new_bus); 5935 synchronize_srcu_expedited(&kvm->srcu); 5936 5937 /* 5938 * If NULL bus is installed, destroy the old bus, including all the 5939 * attached devices. Otherwise, destroy the caller's device only. 5940 */ 5941 if (!new_bus) { 5942 pr_err("kvm: failed to shrink bus, removing it completely\n"); 5943 kvm_io_bus_destroy(bus); 5944 return -ENOMEM; 5945 } 5946 5947 kvm_iodevice_destructor(dev); 5948 kfree(bus); 5949 return 0; 5950 } 5951 5952 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx, 5953 gpa_t addr) 5954 { 5955 struct kvm_io_bus *bus; 5956 int dev_idx, srcu_idx; 5957 struct kvm_io_device *iodev = NULL; 5958 5959 srcu_idx = srcu_read_lock(&kvm->srcu); 5960 5961 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu); 5962 if (!bus) 5963 goto out_unlock; 5964 5965 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1); 5966 if (dev_idx < 0) 5967 goto out_unlock; 5968 5969 iodev = bus->range[dev_idx].dev; 5970 5971 out_unlock: 5972 srcu_read_unlock(&kvm->srcu, srcu_idx); 5973 5974 return iodev; 5975 } 5976 EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev); 5977 5978 static int kvm_debugfs_open(struct inode *inode, struct file *file, 5979 int (*get)(void *, u64 *), int (*set)(void *, u64), 5980 const char *fmt) 5981 { 5982 int ret; 5983 struct kvm_stat_data *stat_data = inode->i_private; 5984 5985 /* 5986 * The debugfs files are a reference to the kvm struct which 5987 * is still valid when kvm_destroy_vm is called. kvm_get_kvm_safe 5988 * avoids the race between open and the removal of the debugfs directory. 5989 */ 5990 if (!kvm_get_kvm_safe(stat_data->kvm)) 5991 return -ENOENT; 5992 5993 ret = simple_attr_open(inode, file, get, 5994 kvm_stats_debugfs_mode(stat_data->desc) & 0222 5995 ? set : NULL, fmt); 5996 if (ret) 5997 kvm_put_kvm(stat_data->kvm); 5998 5999 return ret; 6000 } 6001 6002 static int kvm_debugfs_release(struct inode *inode, struct file *file) 6003 { 6004 struct kvm_stat_data *stat_data = inode->i_private; 6005 6006 simple_attr_release(inode, file); 6007 kvm_put_kvm(stat_data->kvm); 6008 6009 return 0; 6010 } 6011 6012 static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val) 6013 { 6014 *val = *(u64 *)((void *)(&kvm->stat) + offset); 6015 6016 return 0; 6017 } 6018 6019 static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset) 6020 { 6021 *(u64 *)((void *)(&kvm->stat) + offset) = 0; 6022 6023 return 0; 6024 } 6025 6026 static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val) 6027 { 6028 unsigned long i; 6029 struct kvm_vcpu *vcpu; 6030 6031 *val = 0; 6032 6033 kvm_for_each_vcpu(i, vcpu, kvm) 6034 *val += *(u64 *)((void *)(&vcpu->stat) + offset); 6035 6036 return 0; 6037 } 6038 6039 static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset) 6040 { 6041 unsigned long i; 6042 struct kvm_vcpu *vcpu; 6043 6044 kvm_for_each_vcpu(i, vcpu, kvm) 6045 *(u64 *)((void *)(&vcpu->stat) + offset) = 0; 6046 6047 return 0; 6048 } 6049 6050 static int kvm_stat_data_get(void *data, u64 *val) 6051 { 6052 int r = -EFAULT; 6053 struct kvm_stat_data *stat_data = data; 6054 6055 switch (stat_data->kind) { 6056 case KVM_STAT_VM: 6057 r = kvm_get_stat_per_vm(stat_data->kvm, 6058 stat_data->desc->desc.offset, val); 6059 break; 6060 case KVM_STAT_VCPU: 6061 r = kvm_get_stat_per_vcpu(stat_data->kvm, 6062 stat_data->desc->desc.offset, val); 6063 break; 6064 } 6065 6066 return r; 6067 } 6068 6069 static int kvm_stat_data_clear(void *data, u64 val) 6070 { 6071 int r = -EFAULT; 6072 struct kvm_stat_data *stat_data = data; 6073 6074 if (val) 6075 return -EINVAL; 6076 6077 switch (stat_data->kind) { 6078 case KVM_STAT_VM: 6079 r = kvm_clear_stat_per_vm(stat_data->kvm, 6080 stat_data->desc->desc.offset); 6081 break; 6082 case KVM_STAT_VCPU: 6083 r = kvm_clear_stat_per_vcpu(stat_data->kvm, 6084 stat_data->desc->desc.offset); 6085 break; 6086 } 6087 6088 return r; 6089 } 6090 6091 static int kvm_stat_data_open(struct inode *inode, struct file *file) 6092 { 6093 __simple_attr_check_format("%llu\n", 0ull); 6094 return kvm_debugfs_open(inode, file, kvm_stat_data_get, 6095 kvm_stat_data_clear, "%llu\n"); 6096 } 6097 6098 static const struct file_operations stat_fops_per_vm = { 6099 .owner = THIS_MODULE, 6100 .open = kvm_stat_data_open, 6101 .release = kvm_debugfs_release, 6102 .read = simple_attr_read, 6103 .write = simple_attr_write, 6104 }; 6105 6106 static int vm_stat_get(void *_offset, u64 *val) 6107 { 6108 unsigned offset = (long)_offset; 6109 struct kvm *kvm; 6110 u64 tmp_val; 6111 6112 *val = 0; 6113 mutex_lock(&kvm_lock); 6114 list_for_each_entry(kvm, &vm_list, vm_list) { 6115 kvm_get_stat_per_vm(kvm, offset, &tmp_val); 6116 *val += tmp_val; 6117 } 6118 mutex_unlock(&kvm_lock); 6119 return 0; 6120 } 6121 6122 static int vm_stat_clear(void *_offset, u64 val) 6123 { 6124 unsigned offset = (long)_offset; 6125 struct kvm *kvm; 6126 6127 if (val) 6128 return -EINVAL; 6129 6130 mutex_lock(&kvm_lock); 6131 list_for_each_entry(kvm, &vm_list, vm_list) { 6132 kvm_clear_stat_per_vm(kvm, offset); 6133 } 6134 mutex_unlock(&kvm_lock); 6135 6136 return 0; 6137 } 6138 6139 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n"); 6140 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_readonly_fops, vm_stat_get, NULL, "%llu\n"); 6141 6142 static int vcpu_stat_get(void *_offset, u64 *val) 6143 { 6144 unsigned offset = (long)_offset; 6145 struct kvm *kvm; 6146 u64 tmp_val; 6147 6148 *val = 0; 6149 mutex_lock(&kvm_lock); 6150 list_for_each_entry(kvm, &vm_list, vm_list) { 6151 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val); 6152 *val += tmp_val; 6153 } 6154 mutex_unlock(&kvm_lock); 6155 return 0; 6156 } 6157 6158 static int vcpu_stat_clear(void *_offset, u64 val) 6159 { 6160 unsigned offset = (long)_offset; 6161 struct kvm *kvm; 6162 6163 if (val) 6164 return -EINVAL; 6165 6166 mutex_lock(&kvm_lock); 6167 list_for_each_entry(kvm, &vm_list, vm_list) { 6168 kvm_clear_stat_per_vcpu(kvm, offset); 6169 } 6170 mutex_unlock(&kvm_lock); 6171 6172 return 0; 6173 } 6174 6175 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear, 6176 "%llu\n"); 6177 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_readonly_fops, vcpu_stat_get, NULL, "%llu\n"); 6178 6179 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm) 6180 { 6181 struct kobj_uevent_env *env; 6182 unsigned long long created, active; 6183 6184 if (!kvm_dev.this_device || !kvm) 6185 return; 6186 6187 mutex_lock(&kvm_lock); 6188 if (type == KVM_EVENT_CREATE_VM) { 6189 kvm_createvm_count++; 6190 kvm_active_vms++; 6191 } else if (type == KVM_EVENT_DESTROY_VM) { 6192 kvm_active_vms--; 6193 } 6194 created = kvm_createvm_count; 6195 active = kvm_active_vms; 6196 mutex_unlock(&kvm_lock); 6197 6198 env = kzalloc(sizeof(*env), GFP_KERNEL); 6199 if (!env) 6200 return; 6201 6202 add_uevent_var(env, "CREATED=%llu", created); 6203 add_uevent_var(env, "COUNT=%llu", active); 6204 6205 if (type == KVM_EVENT_CREATE_VM) { 6206 add_uevent_var(env, "EVENT=create"); 6207 kvm->userspace_pid = task_pid_nr(current); 6208 } else if (type == KVM_EVENT_DESTROY_VM) { 6209 add_uevent_var(env, "EVENT=destroy"); 6210 } 6211 add_uevent_var(env, "PID=%d", kvm->userspace_pid); 6212 6213 if (!IS_ERR(kvm->debugfs_dentry)) { 6214 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL); 6215 6216 if (p) { 6217 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX); 6218 if (!IS_ERR(tmp)) 6219 add_uevent_var(env, "STATS_PATH=%s", tmp); 6220 kfree(p); 6221 } 6222 } 6223 /* no need for checks, since we are adding at most only 5 keys */ 6224 env->envp[env->envp_idx++] = NULL; 6225 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp); 6226 kfree(env); 6227 } 6228 6229 static void kvm_init_debug(void) 6230 { 6231 const struct file_operations *fops; 6232 const struct _kvm_stats_desc *pdesc; 6233 int i; 6234 6235 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL); 6236 6237 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) { 6238 pdesc = &kvm_vm_stats_desc[i]; 6239 if (kvm_stats_debugfs_mode(pdesc) & 0222) 6240 fops = &vm_stat_fops; 6241 else 6242 fops = &vm_stat_readonly_fops; 6243 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc), 6244 kvm_debugfs_dir, 6245 (void *)(long)pdesc->desc.offset, fops); 6246 } 6247 6248 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) { 6249 pdesc = &kvm_vcpu_stats_desc[i]; 6250 if (kvm_stats_debugfs_mode(pdesc) & 0222) 6251 fops = &vcpu_stat_fops; 6252 else 6253 fops = &vcpu_stat_readonly_fops; 6254 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc), 6255 kvm_debugfs_dir, 6256 (void *)(long)pdesc->desc.offset, fops); 6257 } 6258 } 6259 6260 static inline 6261 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn) 6262 { 6263 return container_of(pn, struct kvm_vcpu, preempt_notifier); 6264 } 6265 6266 static void kvm_sched_in(struct preempt_notifier *pn, int cpu) 6267 { 6268 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn); 6269 6270 WRITE_ONCE(vcpu->preempted, false); 6271 WRITE_ONCE(vcpu->ready, false); 6272 6273 __this_cpu_write(kvm_running_vcpu, vcpu); 6274 kvm_arch_vcpu_load(vcpu, cpu); 6275 6276 WRITE_ONCE(vcpu->scheduled_out, false); 6277 } 6278 6279 static void kvm_sched_out(struct preempt_notifier *pn, 6280 struct task_struct *next) 6281 { 6282 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn); 6283 6284 WRITE_ONCE(vcpu->scheduled_out, true); 6285 6286 if (task_is_runnable(current) && vcpu->wants_to_run) { 6287 WRITE_ONCE(vcpu->preempted, true); 6288 WRITE_ONCE(vcpu->ready, true); 6289 } 6290 kvm_arch_vcpu_put(vcpu); 6291 __this_cpu_write(kvm_running_vcpu, NULL); 6292 } 6293 6294 /** 6295 * kvm_get_running_vcpu - get the vcpu running on the current CPU. 6296 * 6297 * We can disable preemption locally around accessing the per-CPU variable, 6298 * and use the resolved vcpu pointer after enabling preemption again, 6299 * because even if the current thread is migrated to another CPU, reading 6300 * the per-CPU value later will give us the same value as we update the 6301 * per-CPU variable in the preempt notifier handlers. 6302 */ 6303 struct kvm_vcpu *kvm_get_running_vcpu(void) 6304 { 6305 struct kvm_vcpu *vcpu; 6306 6307 preempt_disable(); 6308 vcpu = __this_cpu_read(kvm_running_vcpu); 6309 preempt_enable(); 6310 6311 return vcpu; 6312 } 6313 EXPORT_SYMBOL_GPL(kvm_get_running_vcpu); 6314 6315 /** 6316 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus. 6317 */ 6318 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void) 6319 { 6320 return &kvm_running_vcpu; 6321 } 6322 6323 #ifdef CONFIG_GUEST_PERF_EVENTS 6324 static unsigned int kvm_guest_state(void) 6325 { 6326 struct kvm_vcpu *vcpu = kvm_get_running_vcpu(); 6327 unsigned int state; 6328 6329 if (!kvm_arch_pmi_in_guest(vcpu)) 6330 return 0; 6331 6332 state = PERF_GUEST_ACTIVE; 6333 if (!kvm_arch_vcpu_in_kernel(vcpu)) 6334 state |= PERF_GUEST_USER; 6335 6336 return state; 6337 } 6338 6339 static unsigned long kvm_guest_get_ip(void) 6340 { 6341 struct kvm_vcpu *vcpu = kvm_get_running_vcpu(); 6342 6343 /* Retrieving the IP must be guarded by a call to kvm_guest_state(). */ 6344 if (WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu))) 6345 return 0; 6346 6347 return kvm_arch_vcpu_get_ip(vcpu); 6348 } 6349 6350 static struct perf_guest_info_callbacks kvm_guest_cbs = { 6351 .state = kvm_guest_state, 6352 .get_ip = kvm_guest_get_ip, 6353 .handle_intel_pt_intr = NULL, 6354 }; 6355 6356 void kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void)) 6357 { 6358 kvm_guest_cbs.handle_intel_pt_intr = pt_intr_handler; 6359 perf_register_guest_info_callbacks(&kvm_guest_cbs); 6360 } 6361 void kvm_unregister_perf_callbacks(void) 6362 { 6363 perf_unregister_guest_info_callbacks(&kvm_guest_cbs); 6364 } 6365 #endif 6366 6367 int kvm_init(unsigned vcpu_size, unsigned vcpu_align, struct module *module) 6368 { 6369 int r; 6370 int cpu; 6371 6372 /* A kmem cache lets us meet the alignment requirements of fx_save. */ 6373 if (!vcpu_align) 6374 vcpu_align = __alignof__(struct kvm_vcpu); 6375 kvm_vcpu_cache = 6376 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align, 6377 SLAB_ACCOUNT, 6378 offsetof(struct kvm_vcpu, arch), 6379 offsetofend(struct kvm_vcpu, stats_id) 6380 - offsetof(struct kvm_vcpu, arch), 6381 NULL); 6382 if (!kvm_vcpu_cache) 6383 return -ENOMEM; 6384 6385 for_each_possible_cpu(cpu) { 6386 if (!alloc_cpumask_var_node(&per_cpu(cpu_kick_mask, cpu), 6387 GFP_KERNEL, cpu_to_node(cpu))) { 6388 r = -ENOMEM; 6389 goto err_cpu_kick_mask; 6390 } 6391 } 6392 6393 r = kvm_irqfd_init(); 6394 if (r) 6395 goto err_irqfd; 6396 6397 r = kvm_async_pf_init(); 6398 if (r) 6399 goto err_async_pf; 6400 6401 kvm_chardev_ops.owner = module; 6402 kvm_vm_fops.owner = module; 6403 kvm_vcpu_fops.owner = module; 6404 kvm_device_fops.owner = module; 6405 6406 kvm_preempt_ops.sched_in = kvm_sched_in; 6407 kvm_preempt_ops.sched_out = kvm_sched_out; 6408 6409 kvm_init_debug(); 6410 6411 r = kvm_vfio_ops_init(); 6412 if (WARN_ON_ONCE(r)) 6413 goto err_vfio; 6414 6415 kvm_gmem_init(module); 6416 6417 r = kvm_init_virtualization(); 6418 if (r) 6419 goto err_virt; 6420 6421 /* 6422 * Registration _must_ be the very last thing done, as this exposes 6423 * /dev/kvm to userspace, i.e. all infrastructure must be setup! 6424 */ 6425 r = misc_register(&kvm_dev); 6426 if (r) { 6427 pr_err("kvm: misc device register failed\n"); 6428 goto err_register; 6429 } 6430 6431 return 0; 6432 6433 err_register: 6434 kvm_uninit_virtualization(); 6435 err_virt: 6436 kvm_vfio_ops_exit(); 6437 err_vfio: 6438 kvm_async_pf_deinit(); 6439 err_async_pf: 6440 kvm_irqfd_exit(); 6441 err_irqfd: 6442 err_cpu_kick_mask: 6443 for_each_possible_cpu(cpu) 6444 free_cpumask_var(per_cpu(cpu_kick_mask, cpu)); 6445 kmem_cache_destroy(kvm_vcpu_cache); 6446 return r; 6447 } 6448 EXPORT_SYMBOL_GPL(kvm_init); 6449 6450 void kvm_exit(void) 6451 { 6452 int cpu; 6453 6454 /* 6455 * Note, unregistering /dev/kvm doesn't strictly need to come first, 6456 * fops_get(), a.k.a. try_module_get(), prevents acquiring references 6457 * to KVM while the module is being stopped. 6458 */ 6459 misc_deregister(&kvm_dev); 6460 6461 kvm_uninit_virtualization(); 6462 6463 debugfs_remove_recursive(kvm_debugfs_dir); 6464 for_each_possible_cpu(cpu) 6465 free_cpumask_var(per_cpu(cpu_kick_mask, cpu)); 6466 kmem_cache_destroy(kvm_vcpu_cache); 6467 kvm_vfio_ops_exit(); 6468 kvm_async_pf_deinit(); 6469 kvm_irqfd_exit(); 6470 } 6471 EXPORT_SYMBOL_GPL(kvm_exit); 6472