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