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