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 if (WARN_ON_ONCE(map->hva)) 3123 kvm_vcpu_unmap(vcpu, map); 3124 3125 map->pinned_page = NULL; 3126 map->page = NULL; 3127 map->hva = NULL; 3128 map->gfn = gfn; 3129 map->writable = writable; 3130 3131 map->pfn = kvm_follow_pfn(&kfp); 3132 if (is_error_noslot_pfn(map->pfn)) 3133 return -EINVAL; 3134 3135 if (pfn_valid(map->pfn)) { 3136 map->page = pfn_to_page(map->pfn); 3137 map->hva = kmap(map->page); 3138 #ifdef CONFIG_HAS_IOMEM 3139 } else { 3140 map->hva = memremap(pfn_to_hpa(map->pfn), PAGE_SIZE, MEMREMAP_WB); 3141 #endif 3142 } 3143 3144 return map->hva ? 0 : -EFAULT; 3145 } 3146 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_vcpu_map); 3147 3148 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map) 3149 { 3150 if (!map->hva) 3151 return; 3152 3153 if (map->page) 3154 kunmap(map->page); 3155 #ifdef CONFIG_HAS_IOMEM 3156 else 3157 memunmap(map->hva); 3158 #endif 3159 3160 if (map->writable) 3161 kvm_vcpu_mark_page_dirty(vcpu, map->gfn); 3162 3163 if (map->pinned_page) { 3164 if (map->writable) 3165 kvm_set_page_dirty(map->pinned_page); 3166 kvm_set_page_accessed(map->pinned_page); 3167 unpin_user_page(map->pinned_page); 3168 } 3169 3170 map->hva = NULL; 3171 map->page = NULL; 3172 map->pinned_page = NULL; 3173 } 3174 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_unmap); 3175 3176 static int next_segment(unsigned long len, int offset) 3177 { 3178 if (len > PAGE_SIZE - offset) 3179 return PAGE_SIZE - offset; 3180 else 3181 return len; 3182 } 3183 3184 /* Copy @len bytes from guest memory at '(@gfn * PAGE_SIZE) + @offset' to @data */ 3185 static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn, 3186 void *data, int offset, int len) 3187 { 3188 int r; 3189 unsigned long addr; 3190 3191 if (WARN_ON_ONCE(offset + len > PAGE_SIZE)) 3192 return -EFAULT; 3193 3194 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL); 3195 if (kvm_is_error_hva(addr)) 3196 return -EFAULT; 3197 r = __copy_from_user(data, (void __user *)addr + offset, len); 3198 if (r) 3199 return -EFAULT; 3200 return 0; 3201 } 3202 3203 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset, 3204 int len) 3205 { 3206 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn); 3207 3208 return __kvm_read_guest_page(slot, gfn, data, offset, len); 3209 } 3210 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_read_guest_page); 3211 3212 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data, 3213 int offset, int len) 3214 { 3215 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn); 3216 3217 return __kvm_read_guest_page(slot, gfn, data, offset, len); 3218 } 3219 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_read_guest_page); 3220 3221 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len) 3222 { 3223 gfn_t gfn = gpa >> PAGE_SHIFT; 3224 int seg; 3225 int offset = offset_in_page(gpa); 3226 int ret; 3227 3228 while ((seg = next_segment(len, offset)) != 0) { 3229 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg); 3230 if (ret < 0) 3231 return ret; 3232 offset = 0; 3233 len -= seg; 3234 data += seg; 3235 ++gfn; 3236 } 3237 return 0; 3238 } 3239 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_read_guest); 3240 3241 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len) 3242 { 3243 gfn_t gfn = gpa >> PAGE_SHIFT; 3244 int seg; 3245 int offset = offset_in_page(gpa); 3246 int ret; 3247 3248 while ((seg = next_segment(len, offset)) != 0) { 3249 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg); 3250 if (ret < 0) 3251 return ret; 3252 offset = 0; 3253 len -= seg; 3254 data += seg; 3255 ++gfn; 3256 } 3257 return 0; 3258 } 3259 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_read_guest); 3260 3261 static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn, 3262 void *data, int offset, unsigned long len) 3263 { 3264 int r; 3265 unsigned long addr; 3266 3267 if (WARN_ON_ONCE(offset + len > PAGE_SIZE)) 3268 return -EFAULT; 3269 3270 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL); 3271 if (kvm_is_error_hva(addr)) 3272 return -EFAULT; 3273 pagefault_disable(); 3274 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len); 3275 pagefault_enable(); 3276 if (r) 3277 return -EFAULT; 3278 return 0; 3279 } 3280 3281 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa, 3282 void *data, unsigned long len) 3283 { 3284 gfn_t gfn = gpa >> PAGE_SHIFT; 3285 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn); 3286 int offset = offset_in_page(gpa); 3287 3288 return __kvm_read_guest_atomic(slot, gfn, data, offset, len); 3289 } 3290 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_read_guest_atomic); 3291 3292 /* Copy @len bytes from @data into guest memory at '(@gfn * PAGE_SIZE) + @offset' */ 3293 static int __kvm_write_guest_page(struct kvm *kvm, 3294 struct kvm_memory_slot *memslot, gfn_t gfn, 3295 const void *data, int offset, int len) 3296 { 3297 int r; 3298 unsigned long addr; 3299 3300 if (WARN_ON_ONCE(offset + len > PAGE_SIZE)) 3301 return -EFAULT; 3302 3303 addr = gfn_to_hva_memslot(memslot, gfn); 3304 if (kvm_is_error_hva(addr)) 3305 return -EFAULT; 3306 r = __copy_to_user((void __user *)addr + offset, data, len); 3307 if (r) 3308 return -EFAULT; 3309 mark_page_dirty_in_slot(kvm, memslot, gfn); 3310 return 0; 3311 } 3312 3313 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, 3314 const void *data, int offset, int len) 3315 { 3316 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn); 3317 3318 return __kvm_write_guest_page(kvm, slot, gfn, data, offset, len); 3319 } 3320 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_write_guest_page); 3321 3322 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, 3323 const void *data, int offset, int len) 3324 { 3325 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn); 3326 3327 return __kvm_write_guest_page(vcpu->kvm, slot, gfn, data, offset, len); 3328 } 3329 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_write_guest_page); 3330 3331 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data, 3332 unsigned long len) 3333 { 3334 gfn_t gfn = gpa >> PAGE_SHIFT; 3335 int seg; 3336 int offset = offset_in_page(gpa); 3337 int ret; 3338 3339 while ((seg = next_segment(len, offset)) != 0) { 3340 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg); 3341 if (ret < 0) 3342 return ret; 3343 offset = 0; 3344 len -= seg; 3345 data += seg; 3346 ++gfn; 3347 } 3348 return 0; 3349 } 3350 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_write_guest); 3351 3352 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data, 3353 unsigned long len) 3354 { 3355 gfn_t gfn = gpa >> PAGE_SHIFT; 3356 int seg; 3357 int offset = offset_in_page(gpa); 3358 int ret; 3359 3360 while ((seg = next_segment(len, offset)) != 0) { 3361 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg); 3362 if (ret < 0) 3363 return ret; 3364 offset = 0; 3365 len -= seg; 3366 data += seg; 3367 ++gfn; 3368 } 3369 return 0; 3370 } 3371 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_write_guest); 3372 3373 static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots, 3374 struct gfn_to_hva_cache *ghc, 3375 gpa_t gpa, unsigned long len) 3376 { 3377 int offset = offset_in_page(gpa); 3378 gfn_t start_gfn = gpa >> PAGE_SHIFT; 3379 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT; 3380 gfn_t nr_pages_needed = end_gfn - start_gfn + 1; 3381 gfn_t nr_pages_avail; 3382 3383 /* Update ghc->generation before performing any error checks. */ 3384 ghc->generation = slots->generation; 3385 3386 if (start_gfn > end_gfn) { 3387 ghc->hva = KVM_HVA_ERR_BAD; 3388 return -EINVAL; 3389 } 3390 3391 /* 3392 * If the requested region crosses two memslots, we still 3393 * verify that the entire region is valid here. 3394 */ 3395 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) { 3396 ghc->memslot = __gfn_to_memslot(slots, start_gfn); 3397 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn, 3398 &nr_pages_avail); 3399 if (kvm_is_error_hva(ghc->hva)) 3400 return -EFAULT; 3401 } 3402 3403 /* Use the slow path for cross page reads and writes. */ 3404 if (nr_pages_needed == 1) 3405 ghc->hva += offset; 3406 else 3407 ghc->memslot = NULL; 3408 3409 ghc->gpa = gpa; 3410 ghc->len = len; 3411 return 0; 3412 } 3413 3414 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc, 3415 gpa_t gpa, unsigned long len) 3416 { 3417 struct kvm_memslots *slots = kvm_memslots(kvm); 3418 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len); 3419 } 3420 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_gfn_to_hva_cache_init); 3421 3422 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc, 3423 void *data, unsigned int offset, 3424 unsigned long len) 3425 { 3426 struct kvm_memslots *slots = kvm_memslots(kvm); 3427 int r; 3428 gpa_t gpa = ghc->gpa + offset; 3429 3430 if (WARN_ON_ONCE(len + offset > ghc->len)) 3431 return -EINVAL; 3432 3433 if (slots->generation != ghc->generation) { 3434 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len)) 3435 return -EFAULT; 3436 } 3437 3438 if (kvm_is_error_hva(ghc->hva)) 3439 return -EFAULT; 3440 3441 if (unlikely(!ghc->memslot)) 3442 return kvm_write_guest(kvm, gpa, data, len); 3443 3444 r = __copy_to_user((void __user *)ghc->hva + offset, data, len); 3445 if (r) 3446 return -EFAULT; 3447 mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT); 3448 3449 return 0; 3450 } 3451 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_write_guest_offset_cached); 3452 3453 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc, 3454 void *data, unsigned long len) 3455 { 3456 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len); 3457 } 3458 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_write_guest_cached); 3459 3460 int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc, 3461 void *data, unsigned int offset, 3462 unsigned long len) 3463 { 3464 struct kvm_memslots *slots = kvm_memslots(kvm); 3465 int r; 3466 gpa_t gpa = ghc->gpa + offset; 3467 3468 if (WARN_ON_ONCE(len + offset > ghc->len)) 3469 return -EINVAL; 3470 3471 if (slots->generation != ghc->generation) { 3472 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len)) 3473 return -EFAULT; 3474 } 3475 3476 if (kvm_is_error_hva(ghc->hva)) 3477 return -EFAULT; 3478 3479 if (unlikely(!ghc->memslot)) 3480 return kvm_read_guest(kvm, gpa, data, len); 3481 3482 r = __copy_from_user(data, (void __user *)ghc->hva + offset, len); 3483 if (r) 3484 return -EFAULT; 3485 3486 return 0; 3487 } 3488 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_read_guest_offset_cached); 3489 3490 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc, 3491 void *data, unsigned long len) 3492 { 3493 return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len); 3494 } 3495 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_read_guest_cached); 3496 3497 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len) 3498 { 3499 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0))); 3500 gfn_t gfn = gpa >> PAGE_SHIFT; 3501 int seg; 3502 int offset = offset_in_page(gpa); 3503 int ret; 3504 3505 while ((seg = next_segment(len, offset)) != 0) { 3506 ret = kvm_write_guest_page(kvm, gfn, zero_page, offset, seg); 3507 if (ret < 0) 3508 return ret; 3509 offset = 0; 3510 len -= seg; 3511 ++gfn; 3512 } 3513 return 0; 3514 } 3515 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_clear_guest); 3516 3517 void mark_page_dirty_in_slot(struct kvm *kvm, 3518 const struct kvm_memory_slot *memslot, 3519 gfn_t gfn) 3520 { 3521 struct kvm_vcpu *vcpu = kvm_get_running_vcpu(); 3522 3523 #ifdef CONFIG_HAVE_KVM_DIRTY_RING 3524 if (WARN_ON_ONCE(vcpu && vcpu->kvm != kvm)) 3525 return; 3526 3527 WARN_ON_ONCE(!vcpu && refcount_read(&kvm->users_count) && 3528 !kvm_arch_allow_write_without_running_vcpu(kvm)); 3529 #endif 3530 3531 if (memslot && kvm_slot_dirty_track_enabled(memslot)) { 3532 unsigned long rel_gfn = gfn - memslot->base_gfn; 3533 u32 slot = (memslot->as_id << 16) | memslot->id; 3534 3535 if (kvm->dirty_ring_size && vcpu) 3536 kvm_dirty_ring_push(vcpu, slot, rel_gfn); 3537 else if (memslot->dirty_bitmap) 3538 set_bit_le(rel_gfn, memslot->dirty_bitmap); 3539 } 3540 } 3541 EXPORT_SYMBOL_FOR_KVM_INTERNAL(mark_page_dirty_in_slot); 3542 3543 void mark_page_dirty(struct kvm *kvm, gfn_t gfn) 3544 { 3545 struct kvm_memory_slot *memslot; 3546 3547 memslot = gfn_to_memslot(kvm, gfn); 3548 mark_page_dirty_in_slot(kvm, memslot, gfn); 3549 } 3550 EXPORT_SYMBOL_FOR_KVM_INTERNAL(mark_page_dirty); 3551 3552 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn) 3553 { 3554 struct kvm_memory_slot *memslot; 3555 3556 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn); 3557 mark_page_dirty_in_slot(vcpu->kvm, memslot, gfn); 3558 } 3559 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_mark_page_dirty); 3560 3561 void kvm_sigset_activate(struct kvm_vcpu *vcpu) 3562 { 3563 if (!vcpu->sigset_active) 3564 return; 3565 3566 /* 3567 * This does a lockless modification of ->real_blocked, which is fine 3568 * because, only current can change ->real_blocked and all readers of 3569 * ->real_blocked don't care as long ->real_blocked is always a subset 3570 * of ->blocked. 3571 */ 3572 sigprocmask(SIG_SETMASK, &vcpu->sigset, ¤t->real_blocked); 3573 } 3574 3575 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu) 3576 { 3577 if (!vcpu->sigset_active) 3578 return; 3579 3580 sigprocmask(SIG_SETMASK, ¤t->real_blocked, NULL); 3581 sigemptyset(¤t->real_blocked); 3582 } 3583 3584 static void grow_halt_poll_ns(struct kvm_vcpu *vcpu) 3585 { 3586 unsigned int old, val, grow, grow_start; 3587 3588 old = val = vcpu->halt_poll_ns; 3589 grow_start = READ_ONCE(halt_poll_ns_grow_start); 3590 grow = READ_ONCE(halt_poll_ns_grow); 3591 if (!grow) 3592 goto out; 3593 3594 val *= grow; 3595 if (val < grow_start) 3596 val = grow_start; 3597 3598 vcpu->halt_poll_ns = val; 3599 out: 3600 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old); 3601 } 3602 3603 static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu) 3604 { 3605 unsigned int old, val, shrink, grow_start; 3606 3607 old = val = vcpu->halt_poll_ns; 3608 shrink = READ_ONCE(halt_poll_ns_shrink); 3609 grow_start = READ_ONCE(halt_poll_ns_grow_start); 3610 if (shrink == 0) 3611 val = 0; 3612 else 3613 val /= shrink; 3614 3615 if (val < grow_start) 3616 val = 0; 3617 3618 vcpu->halt_poll_ns = val; 3619 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old); 3620 } 3621 3622 static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu) 3623 { 3624 int ret = -EINTR; 3625 int idx = srcu_read_lock(&vcpu->kvm->srcu); 3626 3627 if (kvm_arch_vcpu_runnable(vcpu)) 3628 goto out; 3629 if (kvm_cpu_has_pending_timer(vcpu)) 3630 goto out; 3631 if (signal_pending(current)) 3632 goto out; 3633 if (kvm_check_request(KVM_REQ_UNBLOCK, vcpu)) 3634 goto out; 3635 3636 ret = 0; 3637 out: 3638 srcu_read_unlock(&vcpu->kvm->srcu, idx); 3639 return ret; 3640 } 3641 3642 /* 3643 * Block the vCPU until the vCPU is runnable, an event arrives, or a signal is 3644 * pending. This is mostly used when halting a vCPU, but may also be used 3645 * directly for other vCPU non-runnable states, e.g. x86's Wait-For-SIPI. 3646 */ 3647 bool kvm_vcpu_block(struct kvm_vcpu *vcpu) 3648 { 3649 struct rcuwait *wait = kvm_arch_vcpu_get_wait(vcpu); 3650 bool waited = false; 3651 3652 vcpu->stat.generic.blocking = 1; 3653 3654 preempt_disable(); 3655 kvm_arch_vcpu_blocking(vcpu); 3656 prepare_to_rcuwait(wait); 3657 preempt_enable(); 3658 3659 for (;;) { 3660 set_current_state(TASK_INTERRUPTIBLE); 3661 3662 if (kvm_vcpu_check_block(vcpu) < 0) 3663 break; 3664 3665 waited = true; 3666 schedule(); 3667 } 3668 3669 preempt_disable(); 3670 finish_rcuwait(wait); 3671 kvm_arch_vcpu_unblocking(vcpu); 3672 preempt_enable(); 3673 3674 vcpu->stat.generic.blocking = 0; 3675 3676 return waited; 3677 } 3678 3679 static inline void update_halt_poll_stats(struct kvm_vcpu *vcpu, ktime_t start, 3680 ktime_t end, bool success) 3681 { 3682 struct kvm_vcpu_stat_generic *stats = &vcpu->stat.generic; 3683 u64 poll_ns = ktime_to_ns(ktime_sub(end, start)); 3684 3685 ++vcpu->stat.generic.halt_attempted_poll; 3686 3687 if (success) { 3688 ++vcpu->stat.generic.halt_successful_poll; 3689 3690 if (!vcpu_valid_wakeup(vcpu)) 3691 ++vcpu->stat.generic.halt_poll_invalid; 3692 3693 stats->halt_poll_success_ns += poll_ns; 3694 KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_success_hist, poll_ns); 3695 } else { 3696 stats->halt_poll_fail_ns += poll_ns; 3697 KVM_STATS_LOG_HIST_UPDATE(stats->halt_poll_fail_hist, poll_ns); 3698 } 3699 } 3700 3701 static unsigned int kvm_vcpu_max_halt_poll_ns(struct kvm_vcpu *vcpu) 3702 { 3703 struct kvm *kvm = vcpu->kvm; 3704 3705 if (kvm->override_halt_poll_ns) { 3706 /* 3707 * Ensure kvm->max_halt_poll_ns is not read before 3708 * kvm->override_halt_poll_ns. 3709 * 3710 * Pairs with the smp_wmb() when enabling KVM_CAP_HALT_POLL. 3711 */ 3712 smp_rmb(); 3713 return READ_ONCE(kvm->max_halt_poll_ns); 3714 } 3715 3716 return READ_ONCE(halt_poll_ns); 3717 } 3718 3719 /* 3720 * Emulate a vCPU halt condition, e.g. HLT on x86, WFI on arm, etc... If halt 3721 * polling is enabled, busy wait for a short time before blocking to avoid the 3722 * expensive block+unblock sequence if a wake event arrives soon after the vCPU 3723 * is halted. 3724 */ 3725 void kvm_vcpu_halt(struct kvm_vcpu *vcpu) 3726 { 3727 unsigned int max_halt_poll_ns = kvm_vcpu_max_halt_poll_ns(vcpu); 3728 bool halt_poll_allowed = !kvm_arch_no_poll(vcpu); 3729 ktime_t start, cur, poll_end; 3730 bool waited = false; 3731 bool do_halt_poll; 3732 u64 halt_ns; 3733 3734 if (vcpu->halt_poll_ns > max_halt_poll_ns) 3735 vcpu->halt_poll_ns = max_halt_poll_ns; 3736 3737 do_halt_poll = halt_poll_allowed && vcpu->halt_poll_ns; 3738 3739 start = cur = poll_end = ktime_get(); 3740 if (do_halt_poll) { 3741 ktime_t stop = ktime_add_ns(start, vcpu->halt_poll_ns); 3742 3743 do { 3744 if (kvm_vcpu_check_block(vcpu) < 0) 3745 goto out; 3746 cpu_relax(); 3747 poll_end = cur = ktime_get(); 3748 } while (kvm_vcpu_can_poll(cur, stop)); 3749 } 3750 3751 waited = kvm_vcpu_block(vcpu); 3752 3753 cur = ktime_get(); 3754 if (waited) { 3755 vcpu->stat.generic.halt_wait_ns += 3756 ktime_to_ns(cur) - ktime_to_ns(poll_end); 3757 KVM_STATS_LOG_HIST_UPDATE(vcpu->stat.generic.halt_wait_hist, 3758 ktime_to_ns(cur) - ktime_to_ns(poll_end)); 3759 } 3760 out: 3761 /* The total time the vCPU was "halted", including polling time. */ 3762 halt_ns = ktime_to_ns(cur) - ktime_to_ns(start); 3763 3764 /* 3765 * Note, halt-polling is considered successful so long as the vCPU was 3766 * never actually scheduled out, i.e. even if the wake event arrived 3767 * after of the halt-polling loop itself, but before the full wait. 3768 */ 3769 if (do_halt_poll) 3770 update_halt_poll_stats(vcpu, start, poll_end, !waited); 3771 3772 if (halt_poll_allowed) { 3773 /* Recompute the max halt poll time in case it changed. */ 3774 max_halt_poll_ns = kvm_vcpu_max_halt_poll_ns(vcpu); 3775 3776 if (!vcpu_valid_wakeup(vcpu)) { 3777 shrink_halt_poll_ns(vcpu); 3778 } else if (max_halt_poll_ns) { 3779 if (halt_ns <= vcpu->halt_poll_ns) 3780 ; 3781 /* we had a long block, shrink polling */ 3782 else if (vcpu->halt_poll_ns && 3783 halt_ns > max_halt_poll_ns) 3784 shrink_halt_poll_ns(vcpu); 3785 /* we had a short halt and our poll time is too small */ 3786 else if (vcpu->halt_poll_ns < max_halt_poll_ns && 3787 halt_ns < max_halt_poll_ns) 3788 grow_halt_poll_ns(vcpu); 3789 } else { 3790 vcpu->halt_poll_ns = 0; 3791 } 3792 } 3793 3794 trace_kvm_vcpu_wakeup(halt_ns, waited, vcpu_valid_wakeup(vcpu)); 3795 } 3796 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_halt); 3797 3798 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu) 3799 { 3800 if (__kvm_vcpu_wake_up(vcpu)) { 3801 WRITE_ONCE(vcpu->ready, true); 3802 ++vcpu->stat.generic.halt_wakeup; 3803 return true; 3804 } 3805 3806 return false; 3807 } 3808 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_wake_up); 3809 3810 #ifndef CONFIG_S390 3811 /* 3812 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode. 3813 */ 3814 void __kvm_vcpu_kick(struct kvm_vcpu *vcpu, bool wait) 3815 { 3816 int me, cpu; 3817 3818 if (kvm_vcpu_wake_up(vcpu)) 3819 return; 3820 3821 me = get_cpu(); 3822 /* 3823 * The only state change done outside the vcpu mutex is IN_GUEST_MODE 3824 * to EXITING_GUEST_MODE. Therefore the moderately expensive "should 3825 * kick" check does not need atomic operations if kvm_vcpu_kick is used 3826 * within the vCPU thread itself. 3827 */ 3828 if (vcpu == __this_cpu_read(kvm_running_vcpu)) { 3829 if (vcpu->mode == IN_GUEST_MODE) 3830 WRITE_ONCE(vcpu->mode, EXITING_GUEST_MODE); 3831 goto out; 3832 } 3833 3834 /* 3835 * Note, the vCPU could get migrated to a different pCPU at any point 3836 * after kvm_arch_vcpu_should_kick(), which could result in sending an 3837 * IPI to the previous pCPU. But, that's ok because the purpose of the 3838 * IPI is to force the vCPU to leave IN_GUEST_MODE, and migrating the 3839 * vCPU also requires it to leave IN_GUEST_MODE. 3840 */ 3841 if (kvm_arch_vcpu_should_kick(vcpu)) { 3842 cpu = READ_ONCE(vcpu->cpu); 3843 if (cpu != me && (unsigned int)cpu < nr_cpu_ids && cpu_online(cpu)) { 3844 /* 3845 * Use a reschedule IPI to kick the vCPU if the caller 3846 * doesn't need to wait for a response, as KVM allows 3847 * kicking vCPUs while IRQs are disabled, but using the 3848 * SMP function call framework with IRQs disabled can 3849 * deadlock due to taking cross-CPU locks. 3850 */ 3851 if (wait) 3852 smp_call_function_single(cpu, ack_kick, NULL, wait); 3853 else 3854 smp_send_reschedule(cpu); 3855 } 3856 } 3857 out: 3858 put_cpu(); 3859 } 3860 EXPORT_SYMBOL_FOR_KVM_INTERNAL(__kvm_vcpu_kick); 3861 #endif /* !CONFIG_S390 */ 3862 3863 int kvm_vcpu_yield_to(struct kvm_vcpu *target) 3864 { 3865 struct task_struct *task = NULL; 3866 int ret; 3867 3868 if (!read_trylock(&target->pid_lock)) 3869 return 0; 3870 3871 if (target->pid) 3872 task = get_pid_task(target->pid, PIDTYPE_PID); 3873 3874 read_unlock(&target->pid_lock); 3875 3876 if (!task) 3877 return 0; 3878 ret = yield_to(task, 1); 3879 put_task_struct(task); 3880 3881 return ret; 3882 } 3883 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_yield_to); 3884 3885 /* 3886 * Helper that checks whether a VCPU is eligible for directed yield. 3887 * Most eligible candidate to yield is decided by following heuristics: 3888 * 3889 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently 3890 * (preempted lock holder), indicated by @in_spin_loop. 3891 * Set at the beginning and cleared at the end of interception/PLE handler. 3892 * 3893 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get 3894 * chance last time (mostly it has become eligible now since we have probably 3895 * yielded to lockholder in last iteration. This is done by toggling 3896 * @dy_eligible each time a VCPU checked for eligibility.) 3897 * 3898 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding 3899 * to preempted lock-holder could result in wrong VCPU selection and CPU 3900 * burning. Giving priority for a potential lock-holder increases lock 3901 * progress. 3902 * 3903 * Since algorithm is based on heuristics, accessing another VCPU data without 3904 * locking does not harm. It may result in trying to yield to same VCPU, fail 3905 * and continue with next VCPU and so on. 3906 */ 3907 static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu) 3908 { 3909 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT 3910 bool eligible; 3911 3912 eligible = !vcpu->spin_loop.in_spin_loop || 3913 vcpu->spin_loop.dy_eligible; 3914 3915 if (vcpu->spin_loop.in_spin_loop) 3916 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible); 3917 3918 return eligible; 3919 #else 3920 return true; 3921 #endif 3922 } 3923 3924 /* 3925 * Unlike kvm_arch_vcpu_runnable, this function is called outside 3926 * a vcpu_load/vcpu_put pair. However, for most architectures 3927 * kvm_arch_vcpu_runnable does not require vcpu_load. 3928 */ 3929 bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu) 3930 { 3931 return kvm_arch_vcpu_runnable(vcpu); 3932 } 3933 3934 static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu) 3935 { 3936 if (kvm_arch_dy_runnable(vcpu)) 3937 return true; 3938 3939 #ifdef CONFIG_KVM_ASYNC_PF 3940 if (!list_empty_careful(&vcpu->async_pf.done)) 3941 return true; 3942 #endif 3943 3944 return false; 3945 } 3946 3947 /* 3948 * By default, simply query the target vCPU's current mode when checking if a 3949 * vCPU was preempted in kernel mode. All architectures except x86 (or more 3950 * specifical, except VMX) allow querying whether or not a vCPU is in kernel 3951 * mode even if the vCPU is NOT loaded, i.e. using kvm_arch_vcpu_in_kernel() 3952 * directly for cross-vCPU checks is functionally correct and accurate. 3953 */ 3954 bool __weak kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu) 3955 { 3956 return kvm_arch_vcpu_in_kernel(vcpu); 3957 } 3958 3959 bool __weak kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu) 3960 { 3961 return false; 3962 } 3963 3964 void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode) 3965 { 3966 int nr_vcpus, start, i, idx, yielded; 3967 struct kvm *kvm = me->kvm; 3968 struct kvm_vcpu *vcpu; 3969 int try = 3; 3970 3971 nr_vcpus = atomic_read(&kvm->online_vcpus); 3972 if (nr_vcpus < 2) 3973 return; 3974 3975 /* Pairs with the smp_wmb() in kvm_vm_ioctl_create_vcpu(). */ 3976 smp_rmb(); 3977 3978 kvm_vcpu_set_in_spin_loop(me, true); 3979 3980 /* 3981 * The current vCPU ("me") is spinning in kernel mode, i.e. is likely 3982 * waiting for a resource to become available. Attempt to yield to a 3983 * vCPU that is runnable, but not currently running, e.g. because the 3984 * vCPU was preempted by a higher priority task. With luck, the vCPU 3985 * that was preempted is holding a lock or some other resource that the 3986 * current vCPU is waiting to acquire, and yielding to the other vCPU 3987 * will allow it to make forward progress and release the lock (or kick 3988 * the spinning vCPU, etc). 3989 * 3990 * Since KVM has no insight into what exactly the guest is doing, 3991 * approximate a round-robin selection by iterating over all vCPUs, 3992 * starting at the last boosted vCPU. I.e. if N=kvm->last_boosted_vcpu, 3993 * iterate over vCPU[N+1]..vCPU[N-1], wrapping as needed. 3994 * 3995 * Note, this is inherently racy, e.g. if multiple vCPUs are spinning, 3996 * they may all try to yield to the same vCPU(s). But as above, this 3997 * is all best effort due to KVM's lack of visibility into the guest. 3998 */ 3999 start = READ_ONCE(kvm->last_boosted_vcpu) + 1; 4000 for (i = 0; i < nr_vcpus; i++) { 4001 idx = (start + i) % nr_vcpus; 4002 if (idx == me->vcpu_idx) 4003 continue; 4004 4005 vcpu = xa_load(&kvm->vcpu_array, idx); 4006 if (!READ_ONCE(vcpu->ready)) 4007 continue; 4008 if (kvm_vcpu_is_blocking(vcpu) && !vcpu_dy_runnable(vcpu)) 4009 continue; 4010 4011 /* 4012 * Treat the target vCPU as being in-kernel if it has a pending 4013 * interrupt, as the vCPU trying to yield may be spinning 4014 * waiting on IPI delivery, i.e. the target vCPU is in-kernel 4015 * for the purposes of directed yield. 4016 */ 4017 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode && 4018 !kvm_arch_dy_has_pending_interrupt(vcpu) && 4019 !kvm_arch_vcpu_preempted_in_kernel(vcpu)) 4020 continue; 4021 4022 if (!kvm_vcpu_eligible_for_directed_yield(vcpu)) 4023 continue; 4024 4025 yielded = kvm_vcpu_yield_to(vcpu); 4026 if (yielded > 0) { 4027 WRITE_ONCE(kvm->last_boosted_vcpu, idx); 4028 break; 4029 } else if (yielded < 0 && !--try) { 4030 break; 4031 } 4032 } 4033 kvm_vcpu_set_in_spin_loop(me, false); 4034 4035 /* Ensure vcpu is not eligible during next spinloop */ 4036 kvm_vcpu_set_dy_eligible(me, false); 4037 } 4038 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_vcpu_on_spin); 4039 4040 static bool kvm_page_in_dirty_ring(struct kvm *kvm, unsigned long pgoff) 4041 { 4042 #ifdef CONFIG_HAVE_KVM_DIRTY_RING 4043 return (pgoff >= KVM_DIRTY_LOG_PAGE_OFFSET) && 4044 (pgoff < KVM_DIRTY_LOG_PAGE_OFFSET + 4045 kvm->dirty_ring_size / PAGE_SIZE); 4046 #else 4047 return false; 4048 #endif 4049 } 4050 4051 static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf) 4052 { 4053 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data; 4054 struct page *page; 4055 4056 if (vmf->pgoff == 0) 4057 page = virt_to_page(vcpu->run); 4058 #ifdef CONFIG_X86 4059 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET) 4060 page = virt_to_page(vcpu->arch.pio_data); 4061 #endif 4062 #ifdef CONFIG_KVM_MMIO 4063 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET) 4064 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring); 4065 #endif 4066 else if (kvm_page_in_dirty_ring(vcpu->kvm, vmf->pgoff)) 4067 page = kvm_dirty_ring_get_page( 4068 &vcpu->dirty_ring, 4069 vmf->pgoff - KVM_DIRTY_LOG_PAGE_OFFSET); 4070 else 4071 return kvm_arch_vcpu_fault(vcpu, vmf); 4072 get_page(page); 4073 vmf->page = page; 4074 return 0; 4075 } 4076 4077 static const struct vm_operations_struct kvm_vcpu_vm_ops = { 4078 .fault = kvm_vcpu_fault, 4079 }; 4080 4081 static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma) 4082 { 4083 struct kvm_vcpu *vcpu = file->private_data; 4084 unsigned long pages = vma_pages(vma); 4085 4086 if ((kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff) || 4087 kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff + pages - 1)) && 4088 ((vma->vm_flags & VM_EXEC) || !(vma->vm_flags & VM_SHARED))) 4089 return -EINVAL; 4090 4091 vma->vm_ops = &kvm_vcpu_vm_ops; 4092 return 0; 4093 } 4094 4095 static int kvm_vcpu_release(struct inode *inode, struct file *filp) 4096 { 4097 struct kvm_vcpu *vcpu = filp->private_data; 4098 4099 kvm_put_kvm(vcpu->kvm); 4100 return 0; 4101 } 4102 4103 static struct file_operations kvm_vcpu_fops = { 4104 .release = kvm_vcpu_release, 4105 .unlocked_ioctl = kvm_vcpu_ioctl, 4106 .mmap = kvm_vcpu_mmap, 4107 .llseek = noop_llseek, 4108 KVM_COMPAT(kvm_vcpu_compat_ioctl), 4109 }; 4110 4111 /* 4112 * Allocates an inode for the vcpu. 4113 */ 4114 static int create_vcpu_fd(struct kvm_vcpu *vcpu) 4115 { 4116 char name[8 + 1 + ITOA_MAX_LEN + 1]; 4117 4118 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id); 4119 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC); 4120 } 4121 4122 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS 4123 static int vcpu_get_pid(void *data, u64 *val) 4124 { 4125 struct kvm_vcpu *vcpu = data; 4126 4127 read_lock(&vcpu->pid_lock); 4128 *val = pid_nr(vcpu->pid); 4129 read_unlock(&vcpu->pid_lock); 4130 return 0; 4131 } 4132 4133 DEFINE_SIMPLE_ATTRIBUTE(vcpu_get_pid_fops, vcpu_get_pid, NULL, "%llu\n"); 4134 4135 static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu) 4136 { 4137 struct dentry *debugfs_dentry; 4138 char dir_name[ITOA_MAX_LEN * 2]; 4139 4140 if (!debugfs_initialized()) 4141 return; 4142 4143 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id); 4144 debugfs_dentry = debugfs_create_dir(dir_name, 4145 vcpu->kvm->debugfs_dentry); 4146 debugfs_create_file("pid", 0444, debugfs_dentry, vcpu, 4147 &vcpu_get_pid_fops); 4148 4149 kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry); 4150 } 4151 #endif 4152 4153 /* 4154 * Creates some virtual cpus. Good luck creating more than one. 4155 */ 4156 static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, unsigned long id) 4157 { 4158 int r; 4159 struct kvm_vcpu *vcpu; 4160 struct page *page; 4161 4162 /* 4163 * KVM tracks vCPU IDs as 'int', be kind to userspace and reject 4164 * too-large values instead of silently truncating. 4165 * 4166 * Ensure KVM_MAX_VCPU_IDS isn't pushed above INT_MAX without first 4167 * changing the storage type (at the very least, IDs should be tracked 4168 * as unsigned ints). 4169 */ 4170 BUILD_BUG_ON(KVM_MAX_VCPU_IDS > INT_MAX); 4171 if (id >= KVM_MAX_VCPU_IDS) 4172 return -EINVAL; 4173 4174 mutex_lock(&kvm->lock); 4175 if (kvm->created_vcpus >= kvm->max_vcpus) { 4176 mutex_unlock(&kvm->lock); 4177 return -EINVAL; 4178 } 4179 4180 if (test_bit(id, kvm->vcpu_ids)) { 4181 mutex_unlock(&kvm->lock); 4182 return -EEXIST; 4183 } 4184 4185 r = kvm_arch_vcpu_precreate(kvm, id); 4186 if (r) { 4187 mutex_unlock(&kvm->lock); 4188 return r; 4189 } 4190 4191 kvm->created_vcpus++; 4192 __set_bit(id, kvm->vcpu_ids); 4193 mutex_unlock(&kvm->lock); 4194 4195 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT); 4196 if (!vcpu) { 4197 r = -ENOMEM; 4198 goto vcpu_decrement; 4199 } 4200 4201 vcpu->vcpu_idx = -1; 4202 4203 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE); 4204 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO); 4205 if (!page) { 4206 r = -ENOMEM; 4207 goto vcpu_free; 4208 } 4209 vcpu->run = page_address(page); 4210 4211 kvm_vcpu_init(vcpu, kvm, id); 4212 4213 r = kvm_arch_vcpu_create(vcpu); 4214 if (r) 4215 goto vcpu_free_run_page; 4216 4217 if (kvm->dirty_ring_size) { 4218 r = kvm_dirty_ring_alloc(kvm, &vcpu->dirty_ring, 4219 id, kvm->dirty_ring_size); 4220 if (r) 4221 goto arch_vcpu_destroy; 4222 } 4223 4224 mutex_lock(&kvm->lock); 4225 4226 if (WARN_ON_ONCE(kvm_get_vcpu_by_id(kvm, id))) { 4227 r = -EEXIST; 4228 goto unlock_vcpu_destroy; 4229 } 4230 4231 /* 4232 * Set the vCPU's index *before* the vCPU is reachable by other tasks. 4233 * Unwind the index back to -1 on failure so that KVM can use the index 4234 * to detect that the vCPU is unreachable, e.g. for lockdep asserts. 4235 */ 4236 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus); 4237 r = xa_insert(&kvm->vcpu_array, vcpu->vcpu_idx, vcpu, GFP_KERNEL_ACCOUNT); 4238 WARN_ON_ONCE(r == -EBUSY); 4239 if (r) 4240 goto unlock_vcpu_destroy; 4241 4242 /* 4243 * Now it's all set up, let userspace reach it. Grab the vCPU's mutex 4244 * so that userspace can't invoke vCPU ioctl()s until the vCPU is fully 4245 * visible (per online_vcpus), e.g. so that KVM doesn't get tricked 4246 * into a NULL-pointer dereference because KVM thinks the _current_ 4247 * vCPU doesn't exist. As a bonus, taking vcpu->mutex ensures lockdep 4248 * knows it's taken *inside* kvm->lock. 4249 */ 4250 mutex_lock(&vcpu->mutex); 4251 kvm_get_kvm(kvm); 4252 r = create_vcpu_fd(vcpu); 4253 if (r < 0) 4254 goto kvm_put_xa_erase; 4255 4256 /* 4257 * Pairs with smp_rmb() in kvm_get_vcpu. Store the vcpu 4258 * pointer before kvm->online_vcpu's incremented value. 4259 */ 4260 smp_wmb(); 4261 atomic_inc(&kvm->online_vcpus); 4262 mutex_unlock(&vcpu->mutex); 4263 4264 mutex_unlock(&kvm->lock); 4265 kvm_arch_vcpu_postcreate(vcpu); 4266 kvm_create_vcpu_debugfs(vcpu); 4267 return r; 4268 4269 kvm_put_xa_erase: 4270 mutex_unlock(&vcpu->mutex); 4271 kvm_put_kvm_no_destroy(kvm); 4272 xa_erase(&kvm->vcpu_array, vcpu->vcpu_idx); 4273 unlock_vcpu_destroy: 4274 vcpu->vcpu_idx = -1; 4275 mutex_unlock(&kvm->lock); 4276 kvm_dirty_ring_free(&vcpu->dirty_ring); 4277 arch_vcpu_destroy: 4278 kvm_arch_vcpu_destroy(vcpu); 4279 vcpu_free_run_page: 4280 free_page((unsigned long)vcpu->run); 4281 vcpu_free: 4282 kmem_cache_free(kvm_vcpu_cache, vcpu); 4283 vcpu_decrement: 4284 mutex_lock(&kvm->lock); 4285 kvm->created_vcpus--; 4286 __clear_bit(id, kvm->vcpu_ids); 4287 mutex_unlock(&kvm->lock); 4288 return r; 4289 } 4290 4291 static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset) 4292 { 4293 if (sigset) { 4294 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP)); 4295 vcpu->sigset_active = 1; 4296 vcpu->sigset = *sigset; 4297 } else 4298 vcpu->sigset_active = 0; 4299 return 0; 4300 } 4301 4302 static ssize_t kvm_vcpu_stats_read(struct file *file, char __user *user_buffer, 4303 size_t size, loff_t *offset) 4304 { 4305 struct kvm_vcpu *vcpu = file->private_data; 4306 4307 return kvm_stats_read(vcpu->stats_id, &kvm_vcpu_stats_header, 4308 &kvm_vcpu_stats_desc[0], &vcpu->stat, 4309 sizeof(vcpu->stat), user_buffer, size, offset); 4310 } 4311 4312 static int kvm_vcpu_stats_release(struct inode *inode, struct file *file) 4313 { 4314 struct kvm_vcpu *vcpu = file->private_data; 4315 4316 kvm_put_kvm(vcpu->kvm); 4317 return 0; 4318 } 4319 4320 static const struct file_operations kvm_vcpu_stats_fops = { 4321 .owner = THIS_MODULE, 4322 .read = kvm_vcpu_stats_read, 4323 .release = kvm_vcpu_stats_release, 4324 .llseek = noop_llseek, 4325 }; 4326 4327 static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu) 4328 { 4329 int fd; 4330 struct file *file; 4331 char name[15 + ITOA_MAX_LEN + 1]; 4332 4333 snprintf(name, sizeof(name), "kvm-vcpu-stats:%d", vcpu->vcpu_id); 4334 4335 fd = get_unused_fd_flags(O_CLOEXEC); 4336 if (fd < 0) 4337 return fd; 4338 4339 file = anon_inode_getfile_fmode(name, &kvm_vcpu_stats_fops, vcpu, 4340 O_RDONLY, FMODE_PREAD); 4341 if (IS_ERR(file)) { 4342 put_unused_fd(fd); 4343 return PTR_ERR(file); 4344 } 4345 4346 kvm_get_kvm(vcpu->kvm); 4347 fd_install(fd, file); 4348 4349 return fd; 4350 } 4351 4352 #ifdef CONFIG_KVM_GENERIC_PRE_FAULT_MEMORY 4353 static int kvm_vcpu_pre_fault_memory(struct kvm_vcpu *vcpu, 4354 struct kvm_pre_fault_memory *range) 4355 { 4356 int idx; 4357 long r; 4358 u64 full_size; 4359 4360 if (range->flags) 4361 return -EINVAL; 4362 4363 if (!PAGE_ALIGNED(range->gpa) || 4364 !PAGE_ALIGNED(range->size) || 4365 range->gpa + range->size <= range->gpa) 4366 return -EINVAL; 4367 4368 vcpu_load(vcpu); 4369 idx = srcu_read_lock(&vcpu->kvm->srcu); 4370 4371 full_size = range->size; 4372 do { 4373 if (signal_pending(current)) { 4374 r = -EINTR; 4375 break; 4376 } 4377 4378 r = kvm_arch_vcpu_pre_fault_memory(vcpu, range); 4379 if (WARN_ON_ONCE(r == 0 || r == -EIO)) 4380 break; 4381 4382 if (r < 0) 4383 break; 4384 4385 range->size -= r; 4386 range->gpa += r; 4387 cond_resched(); 4388 } while (range->size); 4389 4390 srcu_read_unlock(&vcpu->kvm->srcu, idx); 4391 vcpu_put(vcpu); 4392 4393 /* Return success if at least one page was mapped successfully. */ 4394 return full_size == range->size ? r : 0; 4395 } 4396 #endif 4397 4398 static int kvm_wait_for_vcpu_online(struct kvm_vcpu *vcpu) 4399 { 4400 struct kvm *kvm = vcpu->kvm; 4401 4402 /* 4403 * In practice, this happy path will always be taken, as a well-behaved 4404 * VMM will never invoke a vCPU ioctl() before KVM_CREATE_VCPU returns. 4405 */ 4406 if (likely(vcpu->vcpu_idx < atomic_read(&kvm->online_vcpus))) 4407 return 0; 4408 4409 /* 4410 * Acquire and release the vCPU's mutex to wait for vCPU creation to 4411 * complete (kvm_vm_ioctl_create_vcpu() holds the mutex until the vCPU 4412 * is fully online). 4413 */ 4414 if (mutex_lock_killable(&vcpu->mutex)) 4415 return -EINTR; 4416 4417 mutex_unlock(&vcpu->mutex); 4418 4419 if (WARN_ON_ONCE(!kvm_get_vcpu(kvm, vcpu->vcpu_idx))) 4420 return -EIO; 4421 4422 return 0; 4423 } 4424 4425 static long kvm_vcpu_ioctl(struct file *filp, 4426 unsigned int ioctl, unsigned long arg) 4427 { 4428 struct kvm_vcpu *vcpu = filp->private_data; 4429 void __user *argp = (void __user *)arg; 4430 int r; 4431 struct kvm_fpu *fpu = NULL; 4432 struct kvm_sregs *kvm_sregs = NULL; 4433 4434 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead) 4435 return -EIO; 4436 4437 if (unlikely(_IOC_TYPE(ioctl) != KVMIO)) 4438 return -EINVAL; 4439 4440 /* 4441 * Wait for the vCPU to be online before handling the ioctl(), as KVM 4442 * assumes the vCPU is reachable via vcpu_array, i.e. may dereference 4443 * a NULL pointer if userspace invokes an ioctl() before KVM is ready. 4444 */ 4445 r = kvm_wait_for_vcpu_online(vcpu); 4446 if (r) 4447 return r; 4448 4449 /* 4450 * Let arch code handle select vCPU ioctls without holding vcpu->mutex, 4451 * e.g. to support ioctls that can run asynchronous to vCPU execution. 4452 */ 4453 r = kvm_arch_vcpu_unlocked_ioctl(filp, ioctl, arg); 4454 if (r != -ENOIOCTLCMD) 4455 return r; 4456 4457 if (mutex_lock_killable(&vcpu->mutex)) 4458 return -EINTR; 4459 switch (ioctl) { 4460 case KVM_RUN: { 4461 struct pid *oldpid; 4462 r = -EINVAL; 4463 if (arg) 4464 goto out; 4465 4466 /* 4467 * Note, vcpu->pid is primarily protected by vcpu->mutex. The 4468 * dedicated r/w lock allows other tasks, e.g. other vCPUs, to 4469 * read vcpu->pid while this vCPU is in KVM_RUN, e.g. to yield 4470 * directly to this vCPU 4471 */ 4472 oldpid = vcpu->pid; 4473 if (unlikely(oldpid != task_pid(current))) { 4474 /* The thread running this VCPU changed. */ 4475 struct pid *newpid; 4476 4477 r = kvm_arch_vcpu_run_pid_change(vcpu); 4478 if (r) 4479 break; 4480 4481 newpid = get_task_pid(current, PIDTYPE_PID); 4482 write_lock(&vcpu->pid_lock); 4483 vcpu->pid = newpid; 4484 write_unlock(&vcpu->pid_lock); 4485 4486 put_pid(oldpid); 4487 } 4488 vcpu->wants_to_run = !READ_ONCE(vcpu->run->immediate_exit__unsafe); 4489 r = kvm_arch_vcpu_ioctl_run(vcpu); 4490 vcpu->wants_to_run = false; 4491 4492 /* 4493 * FIXME: Remove this hack once all KVM architectures 4494 * support the generic TIF bits, i.e. a dedicated TIF_RSEQ. 4495 */ 4496 rseq_virt_userspace_exit(); 4497 4498 trace_kvm_userspace_exit(vcpu->run->exit_reason, r); 4499 break; 4500 } 4501 case KVM_GET_REGS: { 4502 struct kvm_regs *kvm_regs; 4503 4504 r = -ENOMEM; 4505 kvm_regs = kzalloc_obj(struct kvm_regs); 4506 if (!kvm_regs) 4507 goto out; 4508 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs); 4509 if (r) 4510 goto out_free1; 4511 r = -EFAULT; 4512 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs))) 4513 goto out_free1; 4514 r = 0; 4515 out_free1: 4516 kfree(kvm_regs); 4517 break; 4518 } 4519 case KVM_SET_REGS: { 4520 struct kvm_regs *kvm_regs; 4521 4522 kvm_regs = memdup_user(argp, sizeof(*kvm_regs)); 4523 if (IS_ERR(kvm_regs)) { 4524 r = PTR_ERR(kvm_regs); 4525 goto out; 4526 } 4527 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs); 4528 kfree(kvm_regs); 4529 break; 4530 } 4531 case KVM_GET_SREGS: { 4532 kvm_sregs = kzalloc_obj(struct kvm_sregs); 4533 r = -ENOMEM; 4534 if (!kvm_sregs) 4535 goto out; 4536 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs); 4537 if (r) 4538 goto out; 4539 r = -EFAULT; 4540 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs))) 4541 goto out; 4542 r = 0; 4543 break; 4544 } 4545 case KVM_SET_SREGS: { 4546 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs)); 4547 if (IS_ERR(kvm_sregs)) { 4548 r = PTR_ERR(kvm_sregs); 4549 kvm_sregs = NULL; 4550 goto out; 4551 } 4552 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs); 4553 break; 4554 } 4555 case KVM_GET_MP_STATE: { 4556 struct kvm_mp_state mp_state; 4557 4558 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state); 4559 if (r) 4560 goto out; 4561 r = -EFAULT; 4562 if (copy_to_user(argp, &mp_state, sizeof(mp_state))) 4563 goto out; 4564 r = 0; 4565 break; 4566 } 4567 case KVM_SET_MP_STATE: { 4568 struct kvm_mp_state mp_state; 4569 4570 r = -EFAULT; 4571 if (copy_from_user(&mp_state, argp, sizeof(mp_state))) 4572 goto out; 4573 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state); 4574 break; 4575 } 4576 case KVM_TRANSLATE: { 4577 struct kvm_translation tr; 4578 4579 r = -EFAULT; 4580 if (copy_from_user(&tr, argp, sizeof(tr))) 4581 goto out; 4582 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr); 4583 if (r) 4584 goto out; 4585 r = -EFAULT; 4586 if (copy_to_user(argp, &tr, sizeof(tr))) 4587 goto out; 4588 r = 0; 4589 break; 4590 } 4591 case KVM_SET_GUEST_DEBUG: { 4592 struct kvm_guest_debug dbg; 4593 4594 r = -EFAULT; 4595 if (copy_from_user(&dbg, argp, sizeof(dbg))) 4596 goto out; 4597 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg); 4598 break; 4599 } 4600 case KVM_SET_SIGNAL_MASK: { 4601 struct kvm_signal_mask __user *sigmask_arg = argp; 4602 struct kvm_signal_mask kvm_sigmask; 4603 sigset_t sigset, *p; 4604 4605 p = NULL; 4606 if (argp) { 4607 r = -EFAULT; 4608 if (copy_from_user(&kvm_sigmask, argp, 4609 sizeof(kvm_sigmask))) 4610 goto out; 4611 r = -EINVAL; 4612 if (kvm_sigmask.len != sizeof(sigset)) 4613 goto out; 4614 r = -EFAULT; 4615 if (copy_from_user(&sigset, sigmask_arg->sigset, 4616 sizeof(sigset))) 4617 goto out; 4618 p = &sigset; 4619 } 4620 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p); 4621 break; 4622 } 4623 case KVM_GET_FPU: { 4624 fpu = kzalloc_obj(struct kvm_fpu); 4625 r = -ENOMEM; 4626 if (!fpu) 4627 goto out; 4628 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu); 4629 if (r) 4630 goto out; 4631 r = -EFAULT; 4632 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu))) 4633 goto out; 4634 r = 0; 4635 break; 4636 } 4637 case KVM_SET_FPU: { 4638 fpu = memdup_user(argp, sizeof(*fpu)); 4639 if (IS_ERR(fpu)) { 4640 r = PTR_ERR(fpu); 4641 fpu = NULL; 4642 goto out; 4643 } 4644 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu); 4645 break; 4646 } 4647 case KVM_GET_STATS_FD: { 4648 r = kvm_vcpu_ioctl_get_stats_fd(vcpu); 4649 break; 4650 } 4651 #ifdef CONFIG_KVM_GENERIC_PRE_FAULT_MEMORY 4652 case KVM_PRE_FAULT_MEMORY: { 4653 struct kvm_pre_fault_memory range; 4654 4655 r = -EFAULT; 4656 if (copy_from_user(&range, argp, sizeof(range))) 4657 break; 4658 r = kvm_vcpu_pre_fault_memory(vcpu, &range); 4659 /* Pass back leftover range. */ 4660 if (copy_to_user(argp, &range, sizeof(range))) 4661 r = -EFAULT; 4662 break; 4663 } 4664 #endif 4665 default: 4666 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg); 4667 } 4668 out: 4669 mutex_unlock(&vcpu->mutex); 4670 kfree(fpu); 4671 kfree(kvm_sregs); 4672 return r; 4673 } 4674 4675 #ifdef CONFIG_KVM_COMPAT 4676 static long kvm_vcpu_compat_ioctl(struct file *filp, 4677 unsigned int ioctl, unsigned long arg) 4678 { 4679 struct kvm_vcpu *vcpu = filp->private_data; 4680 void __user *argp = compat_ptr(arg); 4681 int r; 4682 4683 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_dead) 4684 return -EIO; 4685 4686 switch (ioctl) { 4687 case KVM_SET_SIGNAL_MASK: { 4688 struct kvm_signal_mask __user *sigmask_arg = argp; 4689 struct kvm_signal_mask kvm_sigmask; 4690 sigset_t sigset; 4691 4692 if (argp) { 4693 r = -EFAULT; 4694 if (copy_from_user(&kvm_sigmask, argp, 4695 sizeof(kvm_sigmask))) 4696 goto out; 4697 r = -EINVAL; 4698 if (kvm_sigmask.len != sizeof(compat_sigset_t)) 4699 goto out; 4700 r = -EFAULT; 4701 if (get_compat_sigset(&sigset, 4702 (compat_sigset_t __user *)sigmask_arg->sigset)) 4703 goto out; 4704 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset); 4705 } else 4706 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL); 4707 break; 4708 } 4709 default: 4710 r = kvm_vcpu_ioctl(filp, ioctl, arg); 4711 } 4712 4713 out: 4714 return r; 4715 } 4716 #endif 4717 4718 static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma) 4719 { 4720 struct kvm_device *dev = filp->private_data; 4721 4722 if (dev->ops->mmap) 4723 return dev->ops->mmap(dev, vma); 4724 4725 return -ENODEV; 4726 } 4727 4728 static int kvm_device_ioctl_attr(struct kvm_device *dev, 4729 int (*accessor)(struct kvm_device *dev, 4730 struct kvm_device_attr *attr), 4731 unsigned long arg) 4732 { 4733 struct kvm_device_attr attr; 4734 4735 if (!accessor) 4736 return -EPERM; 4737 4738 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr))) 4739 return -EFAULT; 4740 4741 return accessor(dev, &attr); 4742 } 4743 4744 static long kvm_device_ioctl(struct file *filp, unsigned int ioctl, 4745 unsigned long arg) 4746 { 4747 struct kvm_device *dev = filp->private_data; 4748 4749 if (dev->kvm->mm != current->mm || dev->kvm->vm_dead) 4750 return -EIO; 4751 4752 switch (ioctl) { 4753 case KVM_SET_DEVICE_ATTR: 4754 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg); 4755 case KVM_GET_DEVICE_ATTR: 4756 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg); 4757 case KVM_HAS_DEVICE_ATTR: 4758 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg); 4759 default: 4760 if (dev->ops->ioctl) 4761 return dev->ops->ioctl(dev, ioctl, arg); 4762 4763 return -ENOTTY; 4764 } 4765 } 4766 4767 static int kvm_device_release(struct inode *inode, struct file *filp) 4768 { 4769 struct kvm_device *dev = filp->private_data; 4770 struct kvm *kvm = dev->kvm; 4771 4772 if (dev->ops->release) { 4773 mutex_lock(&kvm->lock); 4774 list_del_rcu(&dev->vm_node); 4775 synchronize_rcu(); 4776 dev->ops->release(dev); 4777 mutex_unlock(&kvm->lock); 4778 } 4779 4780 kvm_put_kvm(kvm); 4781 return 0; 4782 } 4783 4784 static struct file_operations kvm_device_fops = { 4785 .unlocked_ioctl = kvm_device_ioctl, 4786 .release = kvm_device_release, 4787 KVM_COMPAT(kvm_device_ioctl), 4788 .mmap = kvm_device_mmap, 4789 }; 4790 4791 struct kvm_device *kvm_device_from_filp(struct file *filp) 4792 { 4793 if (filp->f_op != &kvm_device_fops) 4794 return NULL; 4795 4796 return filp->private_data; 4797 } 4798 4799 static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = { 4800 #ifdef CONFIG_KVM_MPIC 4801 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops, 4802 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops, 4803 #endif 4804 }; 4805 4806 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type) 4807 { 4808 if (type >= ARRAY_SIZE(kvm_device_ops_table)) 4809 return -ENOSPC; 4810 4811 if (kvm_device_ops_table[type] != NULL) 4812 return -EEXIST; 4813 4814 kvm_device_ops_table[type] = ops; 4815 return 0; 4816 } 4817 4818 void kvm_unregister_device_ops(u32 type) 4819 { 4820 if (kvm_device_ops_table[type] != NULL) 4821 kvm_device_ops_table[type] = NULL; 4822 } 4823 4824 static int kvm_ioctl_create_device(struct kvm *kvm, 4825 struct kvm_create_device *cd) 4826 { 4827 const struct kvm_device_ops *ops; 4828 struct kvm_device *dev; 4829 bool test = cd->flags & KVM_CREATE_DEVICE_TEST; 4830 int type; 4831 int ret; 4832 4833 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table)) 4834 return -ENODEV; 4835 4836 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table)); 4837 ops = kvm_device_ops_table[type]; 4838 if (ops == NULL) 4839 return -ENODEV; 4840 4841 if (test) 4842 return 0; 4843 4844 dev = kzalloc_obj(*dev, GFP_KERNEL_ACCOUNT); 4845 if (!dev) 4846 return -ENOMEM; 4847 4848 dev->ops = ops; 4849 dev->kvm = kvm; 4850 4851 mutex_lock(&kvm->lock); 4852 ret = ops->create(dev, type); 4853 if (ret < 0) { 4854 mutex_unlock(&kvm->lock); 4855 kfree(dev); 4856 return ret; 4857 } 4858 list_add_rcu(&dev->vm_node, &kvm->devices); 4859 mutex_unlock(&kvm->lock); 4860 4861 if (ops->init) 4862 ops->init(dev); 4863 4864 kvm_get_kvm(kvm); 4865 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC); 4866 if (ret < 0) { 4867 kvm_put_kvm_no_destroy(kvm); 4868 mutex_lock(&kvm->lock); 4869 list_del_rcu(&dev->vm_node); 4870 synchronize_rcu(); 4871 if (ops->release) 4872 ops->release(dev); 4873 mutex_unlock(&kvm->lock); 4874 if (ops->destroy) 4875 ops->destroy(dev); 4876 return ret; 4877 } 4878 4879 cd->fd = ret; 4880 return 0; 4881 } 4882 4883 static int kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg) 4884 { 4885 switch (arg) { 4886 case KVM_CAP_SYNC_MMU: 4887 case KVM_CAP_USER_MEMORY: 4888 case KVM_CAP_USER_MEMORY2: 4889 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS: 4890 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS: 4891 case KVM_CAP_INTERNAL_ERROR_DATA: 4892 #ifdef CONFIG_HAVE_KVM_MSI 4893 case KVM_CAP_SIGNAL_MSI: 4894 #endif 4895 #ifdef CONFIG_HAVE_KVM_IRQCHIP 4896 case KVM_CAP_IRQFD: 4897 #endif 4898 case KVM_CAP_IOEVENTFD_ANY_LENGTH: 4899 case KVM_CAP_CHECK_EXTENSION_VM: 4900 case KVM_CAP_ENABLE_CAP_VM: 4901 case KVM_CAP_HALT_POLL: 4902 return 1; 4903 #ifdef CONFIG_KVM_MMIO 4904 case KVM_CAP_COALESCED_MMIO: 4905 return KVM_COALESCED_MMIO_PAGE_OFFSET; 4906 case KVM_CAP_COALESCED_PIO: 4907 return 1; 4908 #endif 4909 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT 4910 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: 4911 return KVM_DIRTY_LOG_MANUAL_CAPS; 4912 #endif 4913 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING 4914 case KVM_CAP_IRQ_ROUTING: 4915 return KVM_MAX_IRQ_ROUTES; 4916 #endif 4917 #if KVM_MAX_NR_ADDRESS_SPACES > 1 4918 case KVM_CAP_MULTI_ADDRESS_SPACE: 4919 if (kvm) 4920 return kvm_arch_nr_memslot_as_ids(kvm); 4921 return KVM_MAX_NR_ADDRESS_SPACES; 4922 #endif 4923 case KVM_CAP_NR_MEMSLOTS: 4924 return KVM_USER_MEM_SLOTS; 4925 case KVM_CAP_DIRTY_LOG_RING: 4926 #ifdef CONFIG_HAVE_KVM_DIRTY_RING_TSO 4927 return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn); 4928 #else 4929 return 0; 4930 #endif 4931 case KVM_CAP_DIRTY_LOG_RING_ACQ_REL: 4932 #ifdef CONFIG_HAVE_KVM_DIRTY_RING_ACQ_REL 4933 return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn); 4934 #else 4935 return 0; 4936 #endif 4937 #ifdef CONFIG_NEED_KVM_DIRTY_RING_WITH_BITMAP 4938 case KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP: 4939 #endif 4940 case KVM_CAP_BINARY_STATS_FD: 4941 case KVM_CAP_SYSTEM_EVENT_DATA: 4942 case KVM_CAP_DEVICE_CTRL: 4943 return 1; 4944 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES 4945 case KVM_CAP_MEMORY_ATTRIBUTES: 4946 return kvm_supported_mem_attributes(kvm); 4947 #endif 4948 #ifdef CONFIG_KVM_GUEST_MEMFD 4949 case KVM_CAP_GUEST_MEMFD: 4950 return 1; 4951 case KVM_CAP_GUEST_MEMFD_FLAGS: 4952 return kvm_gmem_get_supported_flags(kvm); 4953 #endif 4954 default: 4955 break; 4956 } 4957 return kvm_vm_ioctl_check_extension(kvm, arg); 4958 } 4959 4960 static int kvm_vm_ioctl_enable_dirty_log_ring(struct kvm *kvm, u32 size) 4961 { 4962 int r; 4963 4964 if (!KVM_DIRTY_LOG_PAGE_OFFSET) 4965 return -EINVAL; 4966 4967 /* the size should be power of 2 */ 4968 if (!size || (size & (size - 1))) 4969 return -EINVAL; 4970 4971 /* Should be bigger to keep the reserved entries, or a page */ 4972 if (size < kvm_dirty_ring_get_rsvd_entries(kvm) * 4973 sizeof(struct kvm_dirty_gfn) || size < PAGE_SIZE) 4974 return -EINVAL; 4975 4976 if (size > KVM_DIRTY_RING_MAX_ENTRIES * 4977 sizeof(struct kvm_dirty_gfn)) 4978 return -E2BIG; 4979 4980 /* We only allow it to set once */ 4981 if (kvm->dirty_ring_size) 4982 return -EINVAL; 4983 4984 mutex_lock(&kvm->lock); 4985 4986 if (kvm->created_vcpus) { 4987 /* We don't allow to change this value after vcpu created */ 4988 r = -EINVAL; 4989 } else { 4990 kvm->dirty_ring_size = size; 4991 r = 0; 4992 } 4993 4994 mutex_unlock(&kvm->lock); 4995 return r; 4996 } 4997 4998 static int kvm_vm_ioctl_reset_dirty_pages(struct kvm *kvm) 4999 { 5000 unsigned long i; 5001 struct kvm_vcpu *vcpu; 5002 int cleared = 0, r; 5003 5004 if (!kvm->dirty_ring_size) 5005 return -EINVAL; 5006 5007 mutex_lock(&kvm->slots_lock); 5008 5009 kvm_for_each_vcpu(i, vcpu, kvm) { 5010 r = kvm_dirty_ring_reset(vcpu->kvm, &vcpu->dirty_ring, &cleared); 5011 if (r) 5012 break; 5013 } 5014 5015 mutex_unlock(&kvm->slots_lock); 5016 5017 if (cleared) 5018 kvm_flush_remote_tlbs(kvm); 5019 5020 return cleared; 5021 } 5022 5023 int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm, 5024 struct kvm_enable_cap *cap) 5025 { 5026 return -EINVAL; 5027 } 5028 5029 bool kvm_are_all_memslots_empty(struct kvm *kvm) 5030 { 5031 int i; 5032 5033 lockdep_assert_held(&kvm->slots_lock); 5034 5035 for (i = 0; i < kvm_arch_nr_memslot_as_ids(kvm); i++) { 5036 if (!kvm_memslots_empty(__kvm_memslots(kvm, i))) 5037 return false; 5038 } 5039 5040 return true; 5041 } 5042 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_are_all_memslots_empty); 5043 5044 static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm, 5045 struct kvm_enable_cap *cap) 5046 { 5047 switch (cap->cap) { 5048 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT 5049 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: { 5050 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE; 5051 5052 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE) 5053 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS; 5054 5055 if (cap->flags || (cap->args[0] & ~allowed_options)) 5056 return -EINVAL; 5057 kvm->manual_dirty_log_protect = cap->args[0]; 5058 return 0; 5059 } 5060 #endif 5061 case KVM_CAP_HALT_POLL: { 5062 if (cap->flags || cap->args[0] != (unsigned int)cap->args[0]) 5063 return -EINVAL; 5064 5065 kvm->max_halt_poll_ns = cap->args[0]; 5066 5067 /* 5068 * Ensure kvm->override_halt_poll_ns does not become visible 5069 * before kvm->max_halt_poll_ns. 5070 * 5071 * Pairs with the smp_rmb() in kvm_vcpu_max_halt_poll_ns(). 5072 */ 5073 smp_wmb(); 5074 kvm->override_halt_poll_ns = true; 5075 5076 return 0; 5077 } 5078 case KVM_CAP_DIRTY_LOG_RING: 5079 case KVM_CAP_DIRTY_LOG_RING_ACQ_REL: 5080 if (!kvm_vm_ioctl_check_extension_generic(kvm, cap->cap)) 5081 return -EINVAL; 5082 5083 return kvm_vm_ioctl_enable_dirty_log_ring(kvm, cap->args[0]); 5084 case KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP: { 5085 int r = -EINVAL; 5086 5087 if (!IS_ENABLED(CONFIG_NEED_KVM_DIRTY_RING_WITH_BITMAP) || 5088 !kvm->dirty_ring_size || cap->flags) 5089 return r; 5090 5091 mutex_lock(&kvm->slots_lock); 5092 5093 /* 5094 * For simplicity, allow enabling ring+bitmap if and only if 5095 * there are no memslots, e.g. to ensure all memslots allocate 5096 * a bitmap after the capability is enabled. 5097 */ 5098 if (kvm_are_all_memslots_empty(kvm)) { 5099 kvm->dirty_ring_with_bitmap = true; 5100 r = 0; 5101 } 5102 5103 mutex_unlock(&kvm->slots_lock); 5104 5105 return r; 5106 } 5107 default: 5108 return kvm_vm_ioctl_enable_cap(kvm, cap); 5109 } 5110 } 5111 5112 static ssize_t kvm_vm_stats_read(struct file *file, char __user *user_buffer, 5113 size_t size, loff_t *offset) 5114 { 5115 struct kvm *kvm = file->private_data; 5116 5117 return kvm_stats_read(kvm->stats_id, &kvm_vm_stats_header, 5118 &kvm_vm_stats_desc[0], &kvm->stat, 5119 sizeof(kvm->stat), user_buffer, size, offset); 5120 } 5121 5122 static int kvm_vm_stats_release(struct inode *inode, struct file *file) 5123 { 5124 struct kvm *kvm = file->private_data; 5125 5126 kvm_put_kvm(kvm); 5127 return 0; 5128 } 5129 5130 static const struct file_operations kvm_vm_stats_fops = { 5131 .owner = THIS_MODULE, 5132 .read = kvm_vm_stats_read, 5133 .release = kvm_vm_stats_release, 5134 .llseek = noop_llseek, 5135 }; 5136 5137 static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm) 5138 { 5139 int fd; 5140 struct file *file; 5141 5142 fd = get_unused_fd_flags(O_CLOEXEC); 5143 if (fd < 0) 5144 return fd; 5145 5146 file = anon_inode_getfile_fmode("kvm-vm-stats", 5147 &kvm_vm_stats_fops, kvm, O_RDONLY, FMODE_PREAD); 5148 if (IS_ERR(file)) { 5149 put_unused_fd(fd); 5150 return PTR_ERR(file); 5151 } 5152 5153 kvm_get_kvm(kvm); 5154 fd_install(fd, file); 5155 5156 return fd; 5157 } 5158 5159 #define SANITY_CHECK_MEM_REGION_FIELD(field) \ 5160 do { \ 5161 BUILD_BUG_ON(offsetof(struct kvm_userspace_memory_region, field) != \ 5162 offsetof(struct kvm_userspace_memory_region2, field)); \ 5163 BUILD_BUG_ON(sizeof_field(struct kvm_userspace_memory_region, field) != \ 5164 sizeof_field(struct kvm_userspace_memory_region2, field)); \ 5165 } while (0) 5166 5167 static long kvm_vm_ioctl(struct file *filp, 5168 unsigned int ioctl, unsigned long arg) 5169 { 5170 struct kvm *kvm = filp->private_data; 5171 void __user *argp = (void __user *)arg; 5172 int r; 5173 5174 if (kvm->mm != current->mm || kvm->vm_dead) 5175 return -EIO; 5176 switch (ioctl) { 5177 case KVM_CREATE_VCPU: 5178 r = kvm_vm_ioctl_create_vcpu(kvm, arg); 5179 break; 5180 case KVM_ENABLE_CAP: { 5181 struct kvm_enable_cap cap; 5182 5183 r = -EFAULT; 5184 if (copy_from_user(&cap, argp, sizeof(cap))) 5185 goto out; 5186 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap); 5187 break; 5188 } 5189 case KVM_SET_USER_MEMORY_REGION2: 5190 case KVM_SET_USER_MEMORY_REGION: { 5191 struct kvm_userspace_memory_region2 mem; 5192 unsigned long size; 5193 5194 if (ioctl == KVM_SET_USER_MEMORY_REGION) { 5195 /* 5196 * Fields beyond struct kvm_userspace_memory_region shouldn't be 5197 * accessed, but avoid leaking kernel memory in case of a bug. 5198 */ 5199 memset(&mem, 0, sizeof(mem)); 5200 size = sizeof(struct kvm_userspace_memory_region); 5201 } else { 5202 size = sizeof(struct kvm_userspace_memory_region2); 5203 } 5204 5205 /* Ensure the common parts of the two structs are identical. */ 5206 SANITY_CHECK_MEM_REGION_FIELD(slot); 5207 SANITY_CHECK_MEM_REGION_FIELD(flags); 5208 SANITY_CHECK_MEM_REGION_FIELD(guest_phys_addr); 5209 SANITY_CHECK_MEM_REGION_FIELD(memory_size); 5210 SANITY_CHECK_MEM_REGION_FIELD(userspace_addr); 5211 5212 r = -EFAULT; 5213 if (copy_from_user(&mem, argp, size)) 5214 goto out; 5215 5216 r = -EINVAL; 5217 if (ioctl == KVM_SET_USER_MEMORY_REGION && 5218 (mem.flags & ~KVM_SET_USER_MEMORY_REGION_V1_FLAGS)) 5219 goto out; 5220 5221 r = kvm_vm_ioctl_set_memory_region(kvm, &mem); 5222 break; 5223 } 5224 case KVM_GET_DIRTY_LOG: { 5225 struct kvm_dirty_log log; 5226 5227 r = -EFAULT; 5228 if (copy_from_user(&log, argp, sizeof(log))) 5229 goto out; 5230 r = kvm_vm_ioctl_get_dirty_log(kvm, &log); 5231 break; 5232 } 5233 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT 5234 case KVM_CLEAR_DIRTY_LOG: { 5235 struct kvm_clear_dirty_log log; 5236 5237 r = -EFAULT; 5238 if (copy_from_user(&log, argp, sizeof(log))) 5239 goto out; 5240 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log); 5241 break; 5242 } 5243 #endif 5244 #ifdef CONFIG_KVM_MMIO 5245 case KVM_REGISTER_COALESCED_MMIO: { 5246 struct kvm_coalesced_mmio_zone zone; 5247 5248 r = -EFAULT; 5249 if (copy_from_user(&zone, argp, sizeof(zone))) 5250 goto out; 5251 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone); 5252 break; 5253 } 5254 case KVM_UNREGISTER_COALESCED_MMIO: { 5255 struct kvm_coalesced_mmio_zone zone; 5256 5257 r = -EFAULT; 5258 if (copy_from_user(&zone, argp, sizeof(zone))) 5259 goto out; 5260 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone); 5261 break; 5262 } 5263 #endif 5264 case KVM_IRQFD: { 5265 struct kvm_irqfd data; 5266 5267 r = -EFAULT; 5268 if (copy_from_user(&data, argp, sizeof(data))) 5269 goto out; 5270 r = kvm_irqfd(kvm, &data); 5271 break; 5272 } 5273 case KVM_IOEVENTFD: { 5274 struct kvm_ioeventfd data; 5275 5276 r = -EFAULT; 5277 if (copy_from_user(&data, argp, sizeof(data))) 5278 goto out; 5279 r = kvm_ioeventfd(kvm, &data); 5280 break; 5281 } 5282 #ifdef CONFIG_HAVE_KVM_MSI 5283 case KVM_SIGNAL_MSI: { 5284 struct kvm_msi msi; 5285 5286 r = -EFAULT; 5287 if (copy_from_user(&msi, argp, sizeof(msi))) 5288 goto out; 5289 r = kvm_send_userspace_msi(kvm, &msi); 5290 break; 5291 } 5292 #endif 5293 #ifdef __KVM_HAVE_IRQ_LINE 5294 case KVM_IRQ_LINE_STATUS: 5295 case KVM_IRQ_LINE: { 5296 struct kvm_irq_level irq_event; 5297 5298 r = -EFAULT; 5299 if (copy_from_user(&irq_event, argp, sizeof(irq_event))) 5300 goto out; 5301 5302 r = kvm_vm_ioctl_irq_line(kvm, &irq_event, 5303 ioctl == KVM_IRQ_LINE_STATUS); 5304 if (r) 5305 goto out; 5306 5307 r = -EFAULT; 5308 if (ioctl == KVM_IRQ_LINE_STATUS) { 5309 if (copy_to_user(argp, &irq_event, sizeof(irq_event))) 5310 goto out; 5311 } 5312 5313 r = 0; 5314 break; 5315 } 5316 #endif 5317 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING 5318 case KVM_SET_GSI_ROUTING: { 5319 struct kvm_irq_routing routing; 5320 struct kvm_irq_routing __user *urouting; 5321 struct kvm_irq_routing_entry *entries = NULL; 5322 5323 r = -EFAULT; 5324 if (copy_from_user(&routing, argp, sizeof(routing))) 5325 goto out; 5326 r = -EINVAL; 5327 if (!kvm_arch_can_set_irq_routing(kvm)) 5328 goto out; 5329 if (routing.nr > KVM_MAX_IRQ_ROUTES) 5330 goto out; 5331 if (routing.flags) 5332 goto out; 5333 if (routing.nr) { 5334 urouting = argp; 5335 entries = vmemdup_array_user(urouting->entries, 5336 routing.nr, sizeof(*entries)); 5337 if (IS_ERR(entries)) { 5338 r = PTR_ERR(entries); 5339 goto out; 5340 } 5341 } 5342 r = kvm_set_irq_routing(kvm, entries, routing.nr, 5343 routing.flags); 5344 kvfree(entries); 5345 break; 5346 } 5347 #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */ 5348 #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES 5349 case KVM_SET_MEMORY_ATTRIBUTES: { 5350 struct kvm_memory_attributes attrs; 5351 5352 r = -EFAULT; 5353 if (copy_from_user(&attrs, argp, sizeof(attrs))) 5354 goto out; 5355 5356 r = kvm_vm_ioctl_set_mem_attributes(kvm, &attrs); 5357 break; 5358 } 5359 #endif /* CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES */ 5360 case KVM_CREATE_DEVICE: { 5361 struct kvm_create_device cd; 5362 5363 r = -EFAULT; 5364 if (copy_from_user(&cd, argp, sizeof(cd))) 5365 goto out; 5366 5367 r = kvm_ioctl_create_device(kvm, &cd); 5368 if (r) 5369 goto out; 5370 5371 r = -EFAULT; 5372 if (copy_to_user(argp, &cd, sizeof(cd))) 5373 goto out; 5374 5375 r = 0; 5376 break; 5377 } 5378 case KVM_CHECK_EXTENSION: 5379 r = kvm_vm_ioctl_check_extension_generic(kvm, arg); 5380 break; 5381 case KVM_RESET_DIRTY_RINGS: 5382 r = kvm_vm_ioctl_reset_dirty_pages(kvm); 5383 break; 5384 case KVM_GET_STATS_FD: 5385 r = kvm_vm_ioctl_get_stats_fd(kvm); 5386 break; 5387 #ifdef CONFIG_KVM_GUEST_MEMFD 5388 case KVM_CREATE_GUEST_MEMFD: { 5389 struct kvm_create_guest_memfd guest_memfd; 5390 5391 r = -EFAULT; 5392 if (copy_from_user(&guest_memfd, argp, sizeof(guest_memfd))) 5393 goto out; 5394 5395 r = kvm_gmem_create(kvm, &guest_memfd); 5396 break; 5397 } 5398 #endif 5399 default: 5400 r = kvm_arch_vm_ioctl(filp, ioctl, arg); 5401 } 5402 out: 5403 return r; 5404 } 5405 5406 #ifdef CONFIG_KVM_COMPAT 5407 struct compat_kvm_dirty_log { 5408 __u32 slot; 5409 __u32 padding1; 5410 union { 5411 compat_uptr_t dirty_bitmap; /* one bit per page */ 5412 __u64 padding2; 5413 }; 5414 }; 5415 5416 struct compat_kvm_clear_dirty_log { 5417 __u32 slot; 5418 __u32 num_pages; 5419 __u64 first_page; 5420 union { 5421 compat_uptr_t dirty_bitmap; /* one bit per page */ 5422 __u64 padding2; 5423 }; 5424 }; 5425 5426 long __weak kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl, 5427 unsigned long arg) 5428 { 5429 return -ENOTTY; 5430 } 5431 5432 static long kvm_vm_compat_ioctl(struct file *filp, 5433 unsigned int ioctl, unsigned long arg) 5434 { 5435 struct kvm *kvm = filp->private_data; 5436 int r; 5437 5438 if (kvm->mm != current->mm || kvm->vm_dead) 5439 return -EIO; 5440 5441 r = kvm_arch_vm_compat_ioctl(filp, ioctl, arg); 5442 if (r != -ENOTTY) 5443 return r; 5444 5445 switch (ioctl) { 5446 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT 5447 case KVM_CLEAR_DIRTY_LOG: { 5448 struct compat_kvm_clear_dirty_log compat_log; 5449 struct kvm_clear_dirty_log log; 5450 5451 if (copy_from_user(&compat_log, (void __user *)arg, 5452 sizeof(compat_log))) 5453 return -EFAULT; 5454 log.slot = compat_log.slot; 5455 log.num_pages = compat_log.num_pages; 5456 log.first_page = compat_log.first_page; 5457 log.padding2 = compat_log.padding2; 5458 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap); 5459 5460 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log); 5461 break; 5462 } 5463 #endif 5464 case KVM_GET_DIRTY_LOG: { 5465 struct compat_kvm_dirty_log compat_log; 5466 struct kvm_dirty_log log; 5467 5468 if (copy_from_user(&compat_log, (void __user *)arg, 5469 sizeof(compat_log))) 5470 return -EFAULT; 5471 log.slot = compat_log.slot; 5472 log.padding1 = compat_log.padding1; 5473 log.padding2 = compat_log.padding2; 5474 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap); 5475 5476 r = kvm_vm_ioctl_get_dirty_log(kvm, &log); 5477 break; 5478 } 5479 default: 5480 r = kvm_vm_ioctl(filp, ioctl, arg); 5481 } 5482 return r; 5483 } 5484 #endif 5485 5486 static struct file_operations kvm_vm_fops = { 5487 .release = kvm_vm_release, 5488 .unlocked_ioctl = kvm_vm_ioctl, 5489 .llseek = noop_llseek, 5490 KVM_COMPAT(kvm_vm_compat_ioctl), 5491 }; 5492 5493 bool file_is_kvm(struct file *file) 5494 { 5495 return file && file->f_op == &kvm_vm_fops; 5496 } 5497 EXPORT_SYMBOL_FOR_KVM_INTERNAL(file_is_kvm); 5498 5499 static int kvm_dev_ioctl_create_vm(unsigned long type) 5500 { 5501 char fdname[ITOA_MAX_LEN + 1]; 5502 int r, fd; 5503 struct kvm *kvm; 5504 struct file *file; 5505 5506 fd = get_unused_fd_flags(O_CLOEXEC); 5507 if (fd < 0) 5508 return fd; 5509 5510 snprintf(fdname, sizeof(fdname), "%d", fd); 5511 5512 kvm = kvm_create_vm(type, fdname); 5513 if (IS_ERR(kvm)) { 5514 r = PTR_ERR(kvm); 5515 goto put_fd; 5516 } 5517 5518 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR); 5519 if (IS_ERR(file)) { 5520 r = PTR_ERR(file); 5521 goto put_kvm; 5522 } 5523 5524 /* 5525 * Don't call kvm_put_kvm anymore at this point; file->f_op is 5526 * already set, with ->release() being kvm_vm_release(). In error 5527 * cases it will be called by the final fput(file) and will take 5528 * care of doing kvm_put_kvm(kvm). 5529 */ 5530 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm); 5531 5532 fd_install(fd, file); 5533 return fd; 5534 5535 put_kvm: 5536 kvm_put_kvm(kvm); 5537 put_fd: 5538 put_unused_fd(fd); 5539 return r; 5540 } 5541 5542 static long kvm_dev_ioctl(struct file *filp, 5543 unsigned int ioctl, unsigned long arg) 5544 { 5545 int r = -EINVAL; 5546 5547 switch (ioctl) { 5548 case KVM_GET_API_VERSION: 5549 if (arg) 5550 goto out; 5551 r = KVM_API_VERSION; 5552 break; 5553 case KVM_CREATE_VM: 5554 r = kvm_dev_ioctl_create_vm(arg); 5555 break; 5556 case KVM_CHECK_EXTENSION: 5557 r = kvm_vm_ioctl_check_extension_generic(NULL, arg); 5558 break; 5559 case KVM_GET_VCPU_MMAP_SIZE: 5560 if (arg) 5561 goto out; 5562 r = PAGE_SIZE; /* struct kvm_run */ 5563 #ifdef CONFIG_X86 5564 r += PAGE_SIZE; /* pio data page */ 5565 #endif 5566 #ifdef CONFIG_KVM_MMIO 5567 r += PAGE_SIZE; /* coalesced mmio ring page */ 5568 #endif 5569 break; 5570 default: 5571 return kvm_arch_dev_ioctl(filp, ioctl, arg); 5572 } 5573 out: 5574 return r; 5575 } 5576 5577 static struct file_operations kvm_chardev_ops = { 5578 .unlocked_ioctl = kvm_dev_ioctl, 5579 .llseek = noop_llseek, 5580 KVM_COMPAT(kvm_dev_ioctl), 5581 }; 5582 5583 static struct miscdevice kvm_dev = { 5584 KVM_MINOR, 5585 "kvm", 5586 &kvm_chardev_ops, 5587 }; 5588 5589 #ifdef CONFIG_KVM_GENERIC_HARDWARE_ENABLING 5590 bool __ro_after_init enable_virt_at_load = true; 5591 module_param(enable_virt_at_load, bool, 0444); 5592 EXPORT_SYMBOL_FOR_KVM_INTERNAL(enable_virt_at_load); 5593 5594 static DEFINE_PER_CPU(bool, virtualization_enabled); 5595 static DEFINE_MUTEX(kvm_usage_lock); 5596 static int kvm_usage_count; 5597 5598 __weak void kvm_arch_shutdown(void) 5599 { 5600 5601 } 5602 5603 __weak void kvm_arch_enable_virtualization(void) 5604 { 5605 5606 } 5607 5608 __weak void kvm_arch_disable_virtualization(void) 5609 { 5610 5611 } 5612 5613 static int kvm_enable_virtualization_cpu(void) 5614 { 5615 if (__this_cpu_read(virtualization_enabled)) 5616 return 0; 5617 5618 if (kvm_arch_enable_virtualization_cpu()) { 5619 pr_info("kvm: enabling virtualization on CPU%d failed\n", 5620 raw_smp_processor_id()); 5621 return -EIO; 5622 } 5623 5624 __this_cpu_write(virtualization_enabled, true); 5625 return 0; 5626 } 5627 5628 static int kvm_online_cpu(unsigned int cpu) 5629 { 5630 /* 5631 * Abort the CPU online process if hardware virtualization cannot 5632 * be enabled. Otherwise running VMs would encounter unrecoverable 5633 * errors when scheduled to this CPU. 5634 */ 5635 return kvm_enable_virtualization_cpu(); 5636 } 5637 5638 static void kvm_disable_virtualization_cpu(void *ign) 5639 { 5640 if (!__this_cpu_read(virtualization_enabled)) 5641 return; 5642 5643 kvm_arch_disable_virtualization_cpu(); 5644 5645 __this_cpu_write(virtualization_enabled, false); 5646 } 5647 5648 static int kvm_offline_cpu(unsigned int cpu) 5649 { 5650 kvm_disable_virtualization_cpu(NULL); 5651 return 0; 5652 } 5653 5654 static void kvm_shutdown(void *data) 5655 { 5656 kvm_arch_shutdown(); 5657 5658 /* 5659 * Some flavors of hardware virtualization need to be disabled before 5660 * transferring control to firmware (to perform shutdown/reboot), e.g. 5661 * on x86, virtualization can block INIT interrupts, which are used by 5662 * firmware to pull APs back under firmware control. Note, this path 5663 * is used for both shutdown and reboot scenarios, i.e. neither name is 5664 * 100% comprehensive. 5665 */ 5666 pr_info("kvm: exiting hardware virtualization\n"); 5667 on_each_cpu(kvm_disable_virtualization_cpu, NULL, 1); 5668 } 5669 5670 static int kvm_suspend(void *data) 5671 { 5672 /* 5673 * Secondary CPUs and CPU hotplug are disabled across the suspend/resume 5674 * callbacks, i.e. no need to acquire kvm_usage_lock to ensure the usage 5675 * count is stable. Assert that kvm_usage_lock is not held to ensure 5676 * the system isn't suspended while KVM is enabling hardware. Hardware 5677 * enabling can be preempted, but the task cannot be frozen until it has 5678 * dropped all locks (userspace tasks are frozen via a fake signal). 5679 */ 5680 lockdep_assert_not_held(&kvm_usage_lock); 5681 lockdep_assert_irqs_disabled(); 5682 5683 kvm_disable_virtualization_cpu(NULL); 5684 return 0; 5685 } 5686 5687 static void kvm_resume(void *data) 5688 { 5689 lockdep_assert_not_held(&kvm_usage_lock); 5690 lockdep_assert_irqs_disabled(); 5691 5692 WARN_ON_ONCE(kvm_enable_virtualization_cpu()); 5693 } 5694 5695 static const struct syscore_ops kvm_syscore_ops = { 5696 .suspend = kvm_suspend, 5697 .resume = kvm_resume, 5698 .shutdown = kvm_shutdown, 5699 }; 5700 5701 static struct syscore kvm_syscore = { 5702 .ops = &kvm_syscore_ops, 5703 }; 5704 5705 static int kvm_enable_virtualization(void) 5706 { 5707 int r; 5708 5709 guard(mutex)(&kvm_usage_lock); 5710 5711 if (kvm_usage_count++) 5712 return 0; 5713 5714 kvm_arch_enable_virtualization(); 5715 5716 r = cpuhp_setup_state(CPUHP_AP_KVM_ONLINE, "kvm/cpu:online", 5717 kvm_online_cpu, kvm_offline_cpu); 5718 if (r) 5719 goto err_cpuhp; 5720 5721 register_syscore(&kvm_syscore); 5722 5723 /* 5724 * Undo virtualization enabling and bail if the system is going down. 5725 * If userspace initiated a forced reboot, e.g. reboot -f, then it's 5726 * possible for an in-flight operation to enable virtualization after 5727 * syscore_shutdown() is called, i.e. without kvm_shutdown() being 5728 * invoked. Note, this relies on system_state being set _before_ 5729 * kvm_shutdown(), e.g. to ensure either kvm_shutdown() is invoked 5730 * or this CPU observes the impending shutdown. Which is why KVM uses 5731 * a syscore ops hook instead of registering a dedicated reboot 5732 * notifier (the latter runs before system_state is updated). 5733 */ 5734 if (system_state == SYSTEM_HALT || system_state == SYSTEM_POWER_OFF || 5735 system_state == SYSTEM_RESTART) { 5736 r = -EBUSY; 5737 goto err_rebooting; 5738 } 5739 5740 return 0; 5741 5742 err_rebooting: 5743 unregister_syscore(&kvm_syscore); 5744 cpuhp_remove_state(CPUHP_AP_KVM_ONLINE); 5745 err_cpuhp: 5746 kvm_arch_disable_virtualization(); 5747 --kvm_usage_count; 5748 return r; 5749 } 5750 5751 static void kvm_disable_virtualization(void) 5752 { 5753 guard(mutex)(&kvm_usage_lock); 5754 5755 if (--kvm_usage_count) 5756 return; 5757 5758 unregister_syscore(&kvm_syscore); 5759 cpuhp_remove_state(CPUHP_AP_KVM_ONLINE); 5760 kvm_arch_disable_virtualization(); 5761 } 5762 5763 static int kvm_init_virtualization(void) 5764 { 5765 if (enable_virt_at_load) 5766 return kvm_enable_virtualization(); 5767 5768 return 0; 5769 } 5770 5771 static void kvm_uninit_virtualization(void) 5772 { 5773 if (enable_virt_at_load) 5774 kvm_disable_virtualization(); 5775 } 5776 #else /* CONFIG_KVM_GENERIC_HARDWARE_ENABLING */ 5777 static int kvm_enable_virtualization(void) 5778 { 5779 return 0; 5780 } 5781 static void kvm_disable_virtualization(void) 5782 { 5783 5784 } 5785 static int kvm_init_virtualization(void) 5786 { 5787 return 0; 5788 } 5789 5790 static void kvm_uninit_virtualization(void) 5791 { 5792 5793 } 5794 #endif /* CONFIG_KVM_GENERIC_HARDWARE_ENABLING */ 5795 5796 static void kvm_iodevice_destructor(struct kvm_io_device *dev) 5797 { 5798 if (dev->ops->destructor) 5799 dev->ops->destructor(dev); 5800 } 5801 5802 static void kvm_io_bus_destroy(struct kvm_io_bus *bus) 5803 { 5804 int i; 5805 5806 for (i = 0; i < bus->dev_count; i++) { 5807 struct kvm_io_device *pos = bus->range[i].dev; 5808 5809 kvm_iodevice_destructor(pos); 5810 } 5811 kfree(bus); 5812 } 5813 5814 static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1, 5815 const struct kvm_io_range *r2) 5816 { 5817 gpa_t addr1 = r1->addr; 5818 gpa_t addr2 = r2->addr; 5819 5820 if (addr1 < addr2) 5821 return -1; 5822 5823 /* If r2->len == 0, match the exact address. If r2->len != 0, 5824 * accept any overlapping write. Any order is acceptable for 5825 * overlapping ranges, because kvm_io_bus_get_first_dev ensures 5826 * we process all of them. 5827 */ 5828 if (r2->len) { 5829 addr1 += r1->len; 5830 addr2 += r2->len; 5831 } 5832 5833 if (addr1 > addr2) 5834 return 1; 5835 5836 return 0; 5837 } 5838 5839 static int kvm_io_bus_sort_cmp(const void *p1, const void *p2) 5840 { 5841 return kvm_io_bus_cmp(p1, p2); 5842 } 5843 5844 static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus, 5845 gpa_t addr, int len) 5846 { 5847 struct kvm_io_range *range, key; 5848 int off; 5849 5850 key = (struct kvm_io_range) { 5851 .addr = addr, 5852 .len = len, 5853 }; 5854 5855 range = bsearch(&key, bus->range, bus->dev_count, 5856 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp); 5857 if (range == NULL) 5858 return -ENOENT; 5859 5860 off = range - bus->range; 5861 5862 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0) 5863 off--; 5864 5865 return off; 5866 } 5867 5868 static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus, 5869 struct kvm_io_range *range, const void *val) 5870 { 5871 int idx; 5872 5873 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len); 5874 if (idx < 0) 5875 return -EOPNOTSUPP; 5876 5877 while (idx < bus->dev_count && 5878 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) { 5879 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr, 5880 range->len, val)) 5881 return idx; 5882 idx++; 5883 } 5884 5885 return -EOPNOTSUPP; 5886 } 5887 5888 static struct kvm_io_bus *kvm_get_bus_srcu(struct kvm *kvm, enum kvm_bus idx) 5889 { 5890 /* 5891 * Ensure that any updates to kvm_buses[] observed by the previous vCPU 5892 * machine instruction are also visible to the vCPU machine instruction 5893 * that triggered this call. 5894 */ 5895 smp_mb__after_srcu_read_lock(); 5896 5897 return srcu_dereference(kvm->buses[idx], &kvm->srcu); 5898 } 5899 5900 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr, 5901 int len, const void *val) 5902 { 5903 struct kvm_io_bus *bus; 5904 struct kvm_io_range range; 5905 int r; 5906 5907 range = (struct kvm_io_range) { 5908 .addr = addr, 5909 .len = len, 5910 }; 5911 5912 bus = kvm_get_bus_srcu(vcpu->kvm, bus_idx); 5913 if (!bus) 5914 return -ENOMEM; 5915 r = __kvm_io_bus_write(vcpu, bus, &range, val); 5916 return r < 0 ? r : 0; 5917 } 5918 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_io_bus_write); 5919 5920 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, 5921 gpa_t addr, int len, const void *val, long cookie) 5922 { 5923 struct kvm_io_bus *bus; 5924 struct kvm_io_range range; 5925 5926 range = (struct kvm_io_range) { 5927 .addr = addr, 5928 .len = len, 5929 }; 5930 5931 bus = kvm_get_bus_srcu(vcpu->kvm, bus_idx); 5932 if (!bus) 5933 return -ENOMEM; 5934 5935 /* First try the device referenced by cookie. */ 5936 if ((cookie >= 0) && (cookie < bus->dev_count) && 5937 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0)) 5938 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len, 5939 val)) 5940 return cookie; 5941 5942 /* 5943 * cookie contained garbage; fall back to search and return the 5944 * correct cookie value. 5945 */ 5946 return __kvm_io_bus_write(vcpu, bus, &range, val); 5947 } 5948 5949 static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus, 5950 struct kvm_io_range *range, void *val) 5951 { 5952 int idx; 5953 5954 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len); 5955 if (idx < 0) 5956 return -EOPNOTSUPP; 5957 5958 while (idx < bus->dev_count && 5959 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) { 5960 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr, 5961 range->len, val)) 5962 return idx; 5963 idx++; 5964 } 5965 5966 return -EOPNOTSUPP; 5967 } 5968 5969 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr, 5970 int len, void *val) 5971 { 5972 struct kvm_io_bus *bus; 5973 struct kvm_io_range range; 5974 int r; 5975 5976 range = (struct kvm_io_range) { 5977 .addr = addr, 5978 .len = len, 5979 }; 5980 5981 bus = kvm_get_bus_srcu(vcpu->kvm, bus_idx); 5982 if (!bus) 5983 return -ENOMEM; 5984 r = __kvm_io_bus_read(vcpu, bus, &range, val); 5985 return r < 0 ? r : 0; 5986 } 5987 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_io_bus_read); 5988 5989 static void __free_bus(struct rcu_head *rcu) 5990 { 5991 struct kvm_io_bus *bus = container_of(rcu, struct kvm_io_bus, rcu); 5992 5993 kfree(bus); 5994 } 5995 5996 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr, 5997 int len, struct kvm_io_device *dev) 5998 { 5999 int i; 6000 struct kvm_io_bus *new_bus, *bus; 6001 struct kvm_io_range range; 6002 6003 lockdep_assert_held(&kvm->slots_lock); 6004 6005 bus = kvm_get_bus(kvm, bus_idx); 6006 if (!bus) 6007 return -ENOMEM; 6008 6009 /* exclude ioeventfd which is limited by maximum fd */ 6010 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1) 6011 return -ENOSPC; 6012 6013 new_bus = kmalloc_flex(*bus, range, bus->dev_count + 1, 6014 GFP_KERNEL_ACCOUNT); 6015 if (!new_bus) 6016 return -ENOMEM; 6017 6018 range = (struct kvm_io_range) { 6019 .addr = addr, 6020 .len = len, 6021 .dev = dev, 6022 }; 6023 6024 for (i = 0; i < bus->dev_count; i++) 6025 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0) 6026 break; 6027 6028 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range)); 6029 new_bus->dev_count++; 6030 new_bus->range[i] = range; 6031 memcpy(new_bus->range + i + 1, bus->range + i, 6032 (bus->dev_count - i) * sizeof(struct kvm_io_range)); 6033 rcu_assign_pointer(kvm->buses[bus_idx], new_bus); 6034 call_srcu(&kvm->srcu, &bus->rcu, __free_bus); 6035 6036 return 0; 6037 } 6038 6039 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx, 6040 struct kvm_io_device *dev) 6041 { 6042 int i; 6043 struct kvm_io_bus *new_bus, *bus; 6044 6045 lockdep_assert_held(&kvm->slots_lock); 6046 6047 bus = kvm_get_bus(kvm, bus_idx); 6048 if (!bus) 6049 return 0; 6050 6051 for (i = 0; i < bus->dev_count; i++) { 6052 if (bus->range[i].dev == dev) { 6053 break; 6054 } 6055 } 6056 6057 if (i == bus->dev_count) 6058 return 0; 6059 6060 new_bus = kmalloc_flex(*bus, range, bus->dev_count - 1, 6061 GFP_KERNEL_ACCOUNT); 6062 if (new_bus) { 6063 memcpy(new_bus, bus, struct_size(bus, range, i)); 6064 new_bus->dev_count--; 6065 memcpy(new_bus->range + i, bus->range + i + 1, 6066 flex_array_size(new_bus, range, new_bus->dev_count - i)); 6067 } 6068 6069 rcu_assign_pointer(kvm->buses[bus_idx], new_bus); 6070 synchronize_srcu_expedited(&kvm->srcu); 6071 6072 /* 6073 * If NULL bus is installed, destroy the old bus, including all the 6074 * attached devices. Otherwise, destroy the caller's device only. 6075 */ 6076 if (!new_bus) { 6077 pr_err("kvm: failed to shrink bus, removing it completely\n"); 6078 kvm_io_bus_destroy(bus); 6079 return -ENOMEM; 6080 } 6081 6082 kvm_iodevice_destructor(dev); 6083 kfree(bus); 6084 return 0; 6085 } 6086 6087 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx, 6088 gpa_t addr) 6089 { 6090 struct kvm_io_bus *bus; 6091 int dev_idx; 6092 6093 lockdep_assert_held(&kvm->srcu); 6094 6095 bus = kvm_get_bus_srcu(kvm, bus_idx); 6096 if (!bus) 6097 return NULL; 6098 6099 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1); 6100 if (dev_idx < 0) 6101 return NULL; 6102 6103 return bus->range[dev_idx].dev; 6104 } 6105 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_io_bus_get_dev); 6106 6107 static int kvm_debugfs_open(struct inode *inode, struct file *file, 6108 int (*get)(void *, u64 *), int (*set)(void *, u64), 6109 const char *fmt) 6110 { 6111 int ret; 6112 struct kvm_stat_data *stat_data = inode->i_private; 6113 6114 /* 6115 * The debugfs files are a reference to the kvm struct which 6116 * is still valid when kvm_destroy_vm is called. kvm_get_kvm_safe 6117 * avoids the race between open and the removal of the debugfs directory. 6118 */ 6119 if (!kvm_get_kvm_safe(stat_data->kvm)) 6120 return -ENOENT; 6121 6122 ret = simple_attr_open(inode, file, get, 6123 kvm_stats_debugfs_mode(stat_data->desc) & 0222 6124 ? set : NULL, fmt); 6125 if (ret) 6126 kvm_put_kvm(stat_data->kvm); 6127 6128 return ret; 6129 } 6130 6131 static int kvm_debugfs_release(struct inode *inode, struct file *file) 6132 { 6133 struct kvm_stat_data *stat_data = inode->i_private; 6134 6135 simple_attr_release(inode, file); 6136 kvm_put_kvm(stat_data->kvm); 6137 6138 return 0; 6139 } 6140 6141 static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val) 6142 { 6143 *val = *(u64 *)((void *)(&kvm->stat) + offset); 6144 6145 return 0; 6146 } 6147 6148 static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset) 6149 { 6150 *(u64 *)((void *)(&kvm->stat) + offset) = 0; 6151 6152 return 0; 6153 } 6154 6155 static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val) 6156 { 6157 unsigned long i; 6158 struct kvm_vcpu *vcpu; 6159 6160 *val = 0; 6161 6162 kvm_for_each_vcpu(i, vcpu, kvm) 6163 *val += *(u64 *)((void *)(&vcpu->stat) + offset); 6164 6165 return 0; 6166 } 6167 6168 static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset) 6169 { 6170 unsigned long i; 6171 struct kvm_vcpu *vcpu; 6172 6173 kvm_for_each_vcpu(i, vcpu, kvm) 6174 *(u64 *)((void *)(&vcpu->stat) + offset) = 0; 6175 6176 return 0; 6177 } 6178 6179 static int kvm_stat_data_get(void *data, u64 *val) 6180 { 6181 int r = -EFAULT; 6182 struct kvm_stat_data *stat_data = data; 6183 6184 switch (stat_data->kind) { 6185 case KVM_STAT_VM: 6186 r = kvm_get_stat_per_vm(stat_data->kvm, 6187 stat_data->desc->offset, val); 6188 break; 6189 case KVM_STAT_VCPU: 6190 r = kvm_get_stat_per_vcpu(stat_data->kvm, 6191 stat_data->desc->offset, val); 6192 break; 6193 } 6194 6195 return r; 6196 } 6197 6198 static int kvm_stat_data_clear(void *data, u64 val) 6199 { 6200 int r = -EFAULT; 6201 struct kvm_stat_data *stat_data = data; 6202 6203 if (val) 6204 return -EINVAL; 6205 6206 switch (stat_data->kind) { 6207 case KVM_STAT_VM: 6208 r = kvm_clear_stat_per_vm(stat_data->kvm, 6209 stat_data->desc->offset); 6210 break; 6211 case KVM_STAT_VCPU: 6212 r = kvm_clear_stat_per_vcpu(stat_data->kvm, 6213 stat_data->desc->offset); 6214 break; 6215 } 6216 6217 return r; 6218 } 6219 6220 static int kvm_stat_data_open(struct inode *inode, struct file *file) 6221 { 6222 __simple_attr_check_format("%llu\n", 0ull); 6223 return kvm_debugfs_open(inode, file, kvm_stat_data_get, 6224 kvm_stat_data_clear, "%llu\n"); 6225 } 6226 6227 static const struct file_operations stat_fops_per_vm = { 6228 .owner = THIS_MODULE, 6229 .open = kvm_stat_data_open, 6230 .release = kvm_debugfs_release, 6231 .read = simple_attr_read, 6232 .write = simple_attr_write, 6233 }; 6234 6235 static int vm_stat_get(void *_offset, u64 *val) 6236 { 6237 unsigned offset = (long)_offset; 6238 struct kvm *kvm; 6239 u64 tmp_val; 6240 6241 *val = 0; 6242 mutex_lock(&kvm_lock); 6243 list_for_each_entry(kvm, &vm_list, vm_list) { 6244 kvm_get_stat_per_vm(kvm, offset, &tmp_val); 6245 *val += tmp_val; 6246 } 6247 mutex_unlock(&kvm_lock); 6248 return 0; 6249 } 6250 6251 static int vm_stat_clear(void *_offset, u64 val) 6252 { 6253 unsigned offset = (long)_offset; 6254 struct kvm *kvm; 6255 6256 if (val) 6257 return -EINVAL; 6258 6259 mutex_lock(&kvm_lock); 6260 list_for_each_entry(kvm, &vm_list, vm_list) { 6261 kvm_clear_stat_per_vm(kvm, offset); 6262 } 6263 mutex_unlock(&kvm_lock); 6264 6265 return 0; 6266 } 6267 6268 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n"); 6269 DEFINE_SIMPLE_ATTRIBUTE(vm_stat_readonly_fops, vm_stat_get, NULL, "%llu\n"); 6270 6271 static int vcpu_stat_get(void *_offset, u64 *val) 6272 { 6273 unsigned offset = (long)_offset; 6274 struct kvm *kvm; 6275 u64 tmp_val; 6276 6277 *val = 0; 6278 mutex_lock(&kvm_lock); 6279 list_for_each_entry(kvm, &vm_list, vm_list) { 6280 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val); 6281 *val += tmp_val; 6282 } 6283 mutex_unlock(&kvm_lock); 6284 return 0; 6285 } 6286 6287 static int vcpu_stat_clear(void *_offset, u64 val) 6288 { 6289 unsigned offset = (long)_offset; 6290 struct kvm *kvm; 6291 6292 if (val) 6293 return -EINVAL; 6294 6295 mutex_lock(&kvm_lock); 6296 list_for_each_entry(kvm, &vm_list, vm_list) { 6297 kvm_clear_stat_per_vcpu(kvm, offset); 6298 } 6299 mutex_unlock(&kvm_lock); 6300 6301 return 0; 6302 } 6303 6304 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear, 6305 "%llu\n"); 6306 DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_readonly_fops, vcpu_stat_get, NULL, "%llu\n"); 6307 6308 static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm) 6309 { 6310 struct kobj_uevent_env *env; 6311 unsigned long long created, active; 6312 6313 if (!kvm_dev.this_device || !kvm) 6314 return; 6315 6316 mutex_lock(&kvm_lock); 6317 if (type == KVM_EVENT_CREATE_VM) { 6318 kvm_createvm_count++; 6319 kvm_active_vms++; 6320 } else if (type == KVM_EVENT_DESTROY_VM) { 6321 kvm_active_vms--; 6322 } 6323 created = kvm_createvm_count; 6324 active = kvm_active_vms; 6325 mutex_unlock(&kvm_lock); 6326 6327 env = kzalloc_obj(*env); 6328 if (!env) 6329 return; 6330 6331 add_uevent_var(env, "CREATED=%llu", created); 6332 add_uevent_var(env, "COUNT=%llu", active); 6333 6334 if (type == KVM_EVENT_CREATE_VM) { 6335 add_uevent_var(env, "EVENT=create"); 6336 kvm->userspace_pid = task_pid_nr(current); 6337 } else if (type == KVM_EVENT_DESTROY_VM) { 6338 add_uevent_var(env, "EVENT=destroy"); 6339 } 6340 add_uevent_var(env, "PID=%d", kvm->userspace_pid); 6341 6342 if (!IS_ERR(kvm->debugfs_dentry)) { 6343 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL); 6344 6345 if (p) { 6346 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX); 6347 if (!IS_ERR(tmp)) 6348 add_uevent_var(env, "STATS_PATH=%s", tmp); 6349 kfree(p); 6350 } 6351 } 6352 /* no need for checks, since we are adding at most only 5 keys */ 6353 env->envp[env->envp_idx++] = NULL; 6354 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp); 6355 kfree(env); 6356 } 6357 6358 static void kvm_init_debug(void) 6359 { 6360 const struct file_operations *fops; 6361 const struct kvm_stats_desc *pdesc; 6362 int i; 6363 6364 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL); 6365 6366 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) { 6367 pdesc = &kvm_vm_stats_desc[i]; 6368 if (kvm_stats_debugfs_mode(pdesc) & 0222) 6369 fops = &vm_stat_fops; 6370 else 6371 fops = &vm_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 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) { 6378 pdesc = &kvm_vcpu_stats_desc[i]; 6379 if (kvm_stats_debugfs_mode(pdesc) & 0222) 6380 fops = &vcpu_stat_fops; 6381 else 6382 fops = &vcpu_stat_readonly_fops; 6383 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc), 6384 kvm_debugfs_dir, 6385 (void *)(long)pdesc->offset, fops); 6386 } 6387 } 6388 6389 static inline 6390 struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn) 6391 { 6392 return container_of(pn, struct kvm_vcpu, preempt_notifier); 6393 } 6394 6395 static void kvm_sched_in(struct preempt_notifier *pn, int cpu) 6396 { 6397 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn); 6398 6399 WRITE_ONCE(vcpu->preempted, false); 6400 WRITE_ONCE(vcpu->ready, false); 6401 6402 __this_cpu_write(kvm_running_vcpu, vcpu); 6403 kvm_arch_vcpu_load(vcpu, cpu); 6404 6405 WRITE_ONCE(vcpu->scheduled_out, false); 6406 } 6407 6408 static void kvm_sched_out(struct preempt_notifier *pn, 6409 struct task_struct *next) 6410 { 6411 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn); 6412 6413 WRITE_ONCE(vcpu->scheduled_out, true); 6414 6415 if (task_is_runnable(current) && vcpu->wants_to_run) { 6416 WRITE_ONCE(vcpu->preempted, true); 6417 WRITE_ONCE(vcpu->ready, true); 6418 } 6419 kvm_arch_vcpu_put(vcpu); 6420 __this_cpu_write(kvm_running_vcpu, NULL); 6421 } 6422 6423 /** 6424 * kvm_get_running_vcpu - get the vcpu running on the current CPU. 6425 * 6426 * We can disable preemption locally around accessing the per-CPU variable, 6427 * and use the resolved vcpu pointer after enabling preemption again, 6428 * because even if the current thread is migrated to another CPU, reading 6429 * the per-CPU value later will give us the same value as we update the 6430 * per-CPU variable in the preempt notifier handlers. 6431 */ 6432 struct kvm_vcpu *kvm_get_running_vcpu(void) 6433 { 6434 struct kvm_vcpu *vcpu; 6435 6436 preempt_disable(); 6437 vcpu = __this_cpu_read(kvm_running_vcpu); 6438 preempt_enable(); 6439 6440 return vcpu; 6441 } 6442 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_get_running_vcpu); 6443 6444 /** 6445 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus. 6446 */ 6447 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void) 6448 { 6449 return &kvm_running_vcpu; 6450 } 6451 6452 #ifdef CONFIG_GUEST_PERF_EVENTS 6453 static unsigned int kvm_guest_state(void) 6454 { 6455 struct kvm_vcpu *vcpu = kvm_get_running_vcpu(); 6456 unsigned int state; 6457 6458 if (!kvm_arch_pmi_in_guest(vcpu)) 6459 return 0; 6460 6461 state = PERF_GUEST_ACTIVE; 6462 if (!kvm_arch_vcpu_in_kernel(vcpu)) 6463 state |= PERF_GUEST_USER; 6464 6465 return state; 6466 } 6467 6468 static unsigned long kvm_guest_get_ip(void) 6469 { 6470 struct kvm_vcpu *vcpu = kvm_get_running_vcpu(); 6471 6472 /* Retrieving the IP must be guarded by a call to kvm_guest_state(). */ 6473 if (WARN_ON_ONCE(!kvm_arch_pmi_in_guest(vcpu))) 6474 return 0; 6475 6476 return kvm_arch_vcpu_get_ip(vcpu); 6477 } 6478 6479 static struct perf_guest_info_callbacks kvm_guest_cbs = { 6480 .state = kvm_guest_state, 6481 .get_ip = kvm_guest_get_ip, 6482 .handle_intel_pt_intr = NULL, 6483 .handle_mediated_pmi = NULL, 6484 }; 6485 6486 void __kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void), 6487 void (*mediated_pmi_handler)(void)) 6488 { 6489 kvm_guest_cbs.handle_intel_pt_intr = pt_intr_handler; 6490 kvm_guest_cbs.handle_mediated_pmi = mediated_pmi_handler; 6491 6492 perf_register_guest_info_callbacks(&kvm_guest_cbs); 6493 } 6494 void kvm_unregister_perf_callbacks(void) 6495 { 6496 perf_unregister_guest_info_callbacks(&kvm_guest_cbs); 6497 } 6498 #endif 6499 6500 int kvm_init(unsigned vcpu_size, unsigned vcpu_align, struct module *module) 6501 { 6502 int r; 6503 int cpu; 6504 6505 /* A kmem cache lets us meet the alignment requirements of fx_save. */ 6506 if (!vcpu_align) 6507 vcpu_align = __alignof__(struct kvm_vcpu); 6508 kvm_vcpu_cache = 6509 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align, 6510 SLAB_ACCOUNT, 6511 offsetof(struct kvm_vcpu, arch), 6512 offsetofend(struct kvm_vcpu, stats_id) 6513 - offsetof(struct kvm_vcpu, arch), 6514 NULL); 6515 if (!kvm_vcpu_cache) 6516 return -ENOMEM; 6517 6518 for_each_possible_cpu(cpu) { 6519 if (!alloc_cpumask_var_node(&per_cpu(cpu_kick_mask, cpu), 6520 GFP_KERNEL, cpu_to_node(cpu))) { 6521 r = -ENOMEM; 6522 goto err_cpu_kick_mask; 6523 } 6524 } 6525 6526 r = kvm_irqfd_init(); 6527 if (r) 6528 goto err_irqfd; 6529 6530 r = kvm_async_pf_init(); 6531 if (r) 6532 goto err_async_pf; 6533 6534 kvm_chardev_ops.owner = module; 6535 kvm_vm_fops.owner = module; 6536 kvm_vcpu_fops.owner = module; 6537 kvm_device_fops.owner = module; 6538 6539 kvm_preempt_ops.sched_in = kvm_sched_in; 6540 kvm_preempt_ops.sched_out = kvm_sched_out; 6541 6542 kvm_init_debug(); 6543 6544 r = kvm_vfio_ops_init(); 6545 if (WARN_ON_ONCE(r)) 6546 goto err_vfio; 6547 6548 r = kvm_gmem_init(module); 6549 if (r) 6550 goto err_gmem; 6551 6552 r = kvm_init_virtualization(); 6553 if (r) 6554 goto err_virt; 6555 6556 /* 6557 * Registration _must_ be the very last thing done, as this exposes 6558 * /dev/kvm to userspace, i.e. all infrastructure must be setup! 6559 */ 6560 r = misc_register(&kvm_dev); 6561 if (r) { 6562 pr_err("kvm: misc device register failed\n"); 6563 goto err_register; 6564 } 6565 6566 return 0; 6567 6568 err_register: 6569 kvm_uninit_virtualization(); 6570 err_virt: 6571 kvm_gmem_exit(); 6572 err_gmem: 6573 kvm_vfio_ops_exit(); 6574 err_vfio: 6575 debugfs_remove_recursive(kvm_debugfs_dir); 6576 kvm_async_pf_deinit(); 6577 err_async_pf: 6578 kvm_irqfd_exit(); 6579 err_irqfd: 6580 err_cpu_kick_mask: 6581 for_each_possible_cpu(cpu) 6582 free_cpumask_var(per_cpu(cpu_kick_mask, cpu)); 6583 kmem_cache_destroy(kvm_vcpu_cache); 6584 return r; 6585 } 6586 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_init); 6587 6588 void kvm_exit(void) 6589 { 6590 int cpu; 6591 6592 /* 6593 * Note, unregistering /dev/kvm doesn't strictly need to come first, 6594 * fops_get(), a.k.a. try_module_get(), prevents acquiring references 6595 * to KVM while the module is being stopped. 6596 */ 6597 misc_deregister(&kvm_dev); 6598 6599 kvm_uninit_virtualization(); 6600 6601 debugfs_remove_recursive(kvm_debugfs_dir); 6602 for_each_possible_cpu(cpu) 6603 free_cpumask_var(per_cpu(cpu_kick_mask, cpu)); 6604 kmem_cache_destroy(kvm_vcpu_cache); 6605 kvm_gmem_exit(); 6606 kvm_vfio_ops_exit(); 6607 kvm_async_pf_deinit(); 6608 kvm_irqfd_exit(); 6609 } 6610 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_exit); 6611