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