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