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