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