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