blob: 3e81b5d8b709a91cc68e3d516644e30c154b00d4 [file] [log] [blame]
Thomas Gleixner20c8ccb2019-06-04 10:11:32 +02001// SPDX-License-Identifier: GPL-2.0-only
Avi Kivity6aa8b732006-12-10 02:21:36 -08002/*
3 * Kernel-based Virtual Machine driver for Linux
4 *
5 * This module enables machines with Intel VT-x extensions to run virtual
6 * machines without emulation or binary translation.
7 *
8 * Copyright (C) 2006 Qumranet, Inc.
Nicolas Kaiser9611c182010-10-06 14:23:22 +02009 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
Avi Kivity6aa8b732006-12-10 02:21:36 -080010 *
11 * Authors:
12 * Avi Kivity <avi@qumranet.com>
13 * Yaniv Kamay <yaniv@qumranet.com>
Avi Kivity6aa8b732006-12-10 02:21:36 -080014 */
15
Andre Przywaraaf669ac2015-03-26 14:39:29 +000016#include <kvm/iodev.h>
Avi Kivity6aa8b732006-12-10 02:21:36 -080017
Avi Kivityedf88412007-12-16 11:02:48 +020018#include <linux/kvm_host.h>
Avi Kivity6aa8b732006-12-10 02:21:36 -080019#include <linux/kvm.h>
20#include <linux/module.h>
21#include <linux/errno.h>
Avi Kivity6aa8b732006-12-10 02:21:36 -080022#include <linux/percpu.h>
Avi Kivity6aa8b732006-12-10 02:21:36 -080023#include <linux/mm.h>
24#include <linux/miscdevice.h>
25#include <linux/vmalloc.h>
Avi Kivity6aa8b732006-12-10 02:21:36 -080026#include <linux/reboot.h>
Avi Kivity6aa8b732006-12-10 02:21:36 -080027#include <linux/debugfs.h>
28#include <linux/highmem.h>
29#include <linux/file.h>
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +010030#include <linux/syscore_ops.h>
Avi Kivity774c47f2007-02-12 00:54:47 -080031#include <linux/cpu.h>
Ingo Molnar174cd4b2017-02-02 19:15:33 +010032#include <linux/sched/signal.h>
Ingo Molnar6e84f312017-02-08 18:51:29 +010033#include <linux/sched/mm.h>
Ingo Molnar03441a32017-02-08 18:51:35 +010034#include <linux/sched/stat.h>
Avi Kivityd9e368d2007-06-07 19:18:30 +030035#include <linux/cpumask.h>
36#include <linux/smp.h>
Avi Kivityd6d28162007-06-28 08:38:16 -040037#include <linux/anon_inodes.h>
Avi Kivity04d2cc72007-09-10 18:10:54 +030038#include <linux/profile.h>
Anthony Liguori7aa81cc2007-09-17 14:57:50 -050039#include <linux/kvm_para.h>
Izik Eidus6fc138d2007-10-09 19:20:39 +020040#include <linux/pagemap.h>
Anthony Liguori8d4e1282007-10-18 09:59:34 -050041#include <linux/mman.h>
Anthony Liguori35149e22008-04-02 14:46:56 -050042#include <linux/swap.h>
Sheng Yange56d5322009-03-12 21:45:39 +080043#include <linux/bitops.h>
Marcelo Tosatti547de292009-05-07 17:55:13 -030044#include <linux/spinlock.h>
Arnd Bergmann6ff58942009-10-22 14:19:27 +020045#include <linux/compat.h>
Marcelo Tosattibc6678a2009-12-23 14:35:21 -020046#include <linux/srcu.h>
Joerg Roedel8f0b1ab2010-01-28 12:37:56 +010047#include <linux/hugetlb.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090048#include <linux/slab.h>
Sasha Levin743eeb02011-07-27 16:00:48 +030049#include <linux/sort.h>
50#include <linux/bsearch.h>
Paolo Bonzinic011d232019-05-17 14:08:53 +020051#include <linux/io.h>
Wanpeng Li2eb06c32019-05-17 16:49:49 +080052#include <linux/lockdep.h>
Junaid Shahidc57c8042019-11-04 12:22:02 +010053#include <linux/kthread.h>
Sergey Senozhatsky2fdef3a2021-06-06 11:10:44 +090054#include <linux/suspend.h>
Avi Kivity6aa8b732006-12-10 02:21:36 -080055
Avi Kivitye4956062007-06-28 14:15:57 -040056#include <asm/processor.h>
David Matlack2ea75be2014-09-19 16:03:25 -070057#include <asm/ioctl.h>
Linus Torvalds7c0f6ba2016-12-24 11:46:01 -080058#include <linux/uaccess.h>
Avi Kivity6aa8b732006-12-10 02:21:36 -080059
Laurent Vivier5f94c172008-05-30 16:05:54 +020060#include "coalesced_mmio.h"
Gleb Natapovaf585b92010-10-14 11:22:46 +020061#include "async_pf.h"
Ben Gardon531810c2021-02-02 10:57:24 -080062#include "mmu_lock.h"
Paolo Bonzini3c3c29f2014-09-24 13:02:46 +020063#include "vfio.h"
Laurent Vivier5f94c172008-05-30 16:05:54 +020064
Marcelo Tosatti229456f2009-06-17 09:22:14 -030065#define CREATE_TRACE_POINTS
66#include <trace/events/kvm.h>
67
Peter Xufb04a1e2020-09-30 21:22:22 -040068#include <linux/kvm_dirty_ring.h>
69
Janosch Frank536a6f82016-05-18 13:26:23 +020070/* Worst case buffer size needed for holding an integer. */
71#define ITOA_MAX_LEN 12
72
Avi Kivity6aa8b732006-12-10 02:21:36 -080073MODULE_AUTHOR("Qumranet");
74MODULE_LICENSE("GPL");
75
David Hildenbrand920552b2015-09-18 12:34:53 +020076/* Architectures should define their poll value according to the halt latency */
Suraj Jitindar Singhec76d812016-10-14 11:53:19 +110077unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
Roman Storozhenko039c5d12017-06-27 12:51:18 +030078module_param(halt_poll_ns, uint, 0644);
Suraj Jitindar Singhec76d812016-10-14 11:53:19 +110079EXPORT_SYMBOL_GPL(halt_poll_ns);
Paolo Bonzinif7819512015-02-04 18:20:58 +010080
Wanpeng Liaca6ff22015-09-03 22:07:38 +080081/* Default doubles per-vcpu halt_poll_ns. */
Suraj Jitindar Singhec76d812016-10-14 11:53:19 +110082unsigned int halt_poll_ns_grow = 2;
Roman Storozhenko039c5d12017-06-27 12:51:18 +030083module_param(halt_poll_ns_grow, uint, 0644);
Suraj Jitindar Singhec76d812016-10-14 11:53:19 +110084EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
Wanpeng Liaca6ff22015-09-03 22:07:38 +080085
Nir Weiner49113d32019-01-27 12:17:15 +020086/* The start value to grow halt_poll_ns from */
87unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
88module_param(halt_poll_ns_grow_start, uint, 0644);
89EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
90
Wanpeng Liaca6ff22015-09-03 22:07:38 +080091/* Default resets per-vcpu halt_poll_ns . */
Suraj Jitindar Singhec76d812016-10-14 11:53:19 +110092unsigned int halt_poll_ns_shrink;
Roman Storozhenko039c5d12017-06-27 12:51:18 +030093module_param(halt_poll_ns_shrink, uint, 0644);
Suraj Jitindar Singhec76d812016-10-14 11:53:19 +110094EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
Wanpeng Liaca6ff22015-09-03 22:07:38 +080095
Marcelo Tosattifa40a822009-06-04 15:08:24 -030096/*
97 * Ordering of locks:
98 *
Xiubo Lib7d409d2015-02-26 14:58:24 +080099 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
Marcelo Tosattifa40a822009-06-04 15:08:24 -0300100 */
101
Junaid Shahid0d9ce162019-01-03 17:14:28 -0800102DEFINE_MUTEX(kvm_lock);
Paolo Bonzini4a937f92013-09-10 12:58:35 +0200103static DEFINE_RAW_SPINLOCK(kvm_count_lock);
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +0800104LIST_HEAD(vm_list);
Avi Kivity133de902007-02-12 00:54:44 -0800105
Rusty Russell7f59f492008-12-07 21:25:45 +1030106static cpumask_var_t cpus_hardware_enabled;
Xiubo Lif4fee932015-02-26 14:58:21 +0800107static int kvm_usage_count;
Alexander Graf10474ae2009-09-15 11:37:46 +0200108static atomic_t hardware_enable_failed;
Avi Kivity1b6c0162007-05-24 13:03:52 +0300109
Sean Christophersonaaba2982019-12-18 13:55:16 -0800110static struct kmem_cache *kvm_vcpu_cache;
Avi Kivity1165f5f2007-04-19 17:27:43 +0300111
Avi Kivity15ad7142007-07-11 18:17:21 +0300112static __read_mostly struct preempt_ops kvm_preempt_ops;
Paolo Bonzini7495e222020-01-09 09:57:19 -0500113static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_running_vcpu);
Avi Kivity15ad7142007-07-11 18:17:21 +0300114
Hollis Blanchard76f7c872008-04-15 16:05:42 -0500115struct dentry *kvm_debugfs_dir;
Paul Mackerrase23a8082015-03-28 14:21:01 +1100116EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
Avi Kivity6aa8b732006-12-10 02:21:36 -0800117
Milan Pandurov09cbcef2019-12-13 14:07:21 +0100118static const struct file_operations stat_fops_per_vm;
Janosch Frank536a6f82016-05-18 13:26:23 +0200119
Avi Kivitybccf2152007-02-21 18:04:26 +0200120static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
121 unsigned long arg);
Christian Borntraegerde8e5d72015-02-03 09:35:15 +0100122#ifdef CONFIG_KVM_COMPAT
Alexander Graf1dda6062011-06-08 02:45:37 +0200123static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
124 unsigned long arg);
Marc Zyngier7ddfd3e2018-06-17 10:16:21 +0100125#define KVM_COMPAT(c) .compat_ioctl = (c)
126#else
Marc Zyngier9cb09e72019-11-14 13:17:39 +0000127/*
128 * For architectures that don't implement a compat infrastructure,
129 * adopt a double line of defense:
130 * - Prevent a compat task from opening /dev/kvm
131 * - If the open has been done by a 64bit task, and the KVM fd
132 * passed to a compat task, let the ioctls fail.
133 */
Marc Zyngier7ddfd3e2018-06-17 10:16:21 +0100134static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
135 unsigned long arg) { return -EINVAL; }
Marc Zyngierb9876e62019-11-13 16:05:23 +0000136
137static int kvm_no_compat_open(struct inode *inode, struct file *file)
138{
139 return is_compat_task() ? -ENODEV : 0;
140}
141#define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
142 .open = kvm_no_compat_open
Alexander Graf1dda6062011-06-08 02:45:37 +0200143#endif
Alexander Graf10474ae2009-09-15 11:37:46 +0200144static int hardware_enable_all(void);
145static void hardware_disable_all(void);
Avi Kivitybccf2152007-02-21 18:04:26 +0200146
Marcelo Tosattie93f8a02009-12-23 14:35:24 -0200147static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
Stephen Hemminger79408762013-12-29 12:12:29 -0800148
Andi Kleen52480132014-02-08 08:51:57 +0100149__visible bool kvm_rebooting;
Avi Kivityb7c41452010-12-02 17:52:50 +0200150EXPORT_SYMBOL_GPL(kvm_rebooting);
Avi Kivity4ecac3f2008-05-13 13:23:38 +0300151
Claudio Imbrenda286de8f2017-07-12 17:56:44 +0200152#define KVM_EVENT_CREATE_VM 0
153#define KVM_EVENT_DESTROY_VM 1
154static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
155static unsigned long long kvm_createvm_count;
156static unsigned long long kvm_active_vms;
157
Eiichi Tsukatae649b3f2020-06-06 13:26:27 +0900158__weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
159 unsigned long start, unsigned long end)
Radim Krčmářb1394e72017-11-30 19:05:45 +0100160{
161}
162
Sean Christophersona78986a2019-11-11 14:12:27 -0800163bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
164{
165 /*
166 * The metadata used by is_zone_device_page() to determine whether or
167 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
168 * the device has been pinned, e.g. by get_user_pages(). WARN if the
169 * page_count() is zero to help detect bad usage of this helper.
170 */
171 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
172 return false;
173
174 return is_zone_device_page(pfn_to_page(pfn));
175}
176
Dan Williamsba049e92016-01-15 16:56:11 -0800177bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
Ben-Ami Yassourcbff90a2008-07-28 19:26:24 +0300178{
Sean Christophersona78986a2019-11-11 14:12:27 -0800179 /*
180 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
181 * perspective they are "normal" pages, albeit with slightly different
182 * usage rules.
183 */
Andrea Arcangeli11feeb42013-07-25 03:04:38 +0200184 if (pfn_valid(pfn))
Sean Christophersona78986a2019-11-11 14:12:27 -0800185 return PageReserved(pfn_to_page(pfn)) &&
Zhuang Yanying7df003c2019-10-12 11:37:31 +0800186 !is_zero_pfn(pfn) &&
Sean Christophersona78986a2019-11-11 14:12:27 -0800187 !kvm_is_zone_device_pfn(pfn);
Ben-Ami Yassourcbff90a2008-07-28 19:26:24 +0300188
189 return true;
190}
191
Sean Christopherson005ba372020-01-08 12:24:36 -0800192bool kvm_is_transparent_hugepage(kvm_pfn_t pfn)
193{
194 struct page *page = pfn_to_page(pfn);
195
196 if (!PageTransCompoundMap(page))
197 return false;
198
199 return is_transparent_hugepage(compound_head(page));
200}
201
Avi Kivity6aa8b732006-12-10 02:21:36 -0800202/*
203 * Switches to specified vcpu, until a matching vcpu_put()
204 */
Christoffer Dallec7660c2017-12-04 21:35:23 +0100205void vcpu_load(struct kvm_vcpu *vcpu)
Avi Kivity6aa8b732006-12-10 02:21:36 -0800206{
Christoffer Dallec7660c2017-12-04 21:35:23 +0100207 int cpu = get_cpu();
Paolo Bonzini7495e222020-01-09 09:57:19 -0500208
209 __this_cpu_write(kvm_running_vcpu, vcpu);
Avi Kivity15ad7142007-07-11 18:17:21 +0300210 preempt_notifier_register(&vcpu->preempt_notifier);
Carsten Otte313a3dc2007-10-11 19:16:52 +0200211 kvm_arch_vcpu_load(vcpu, cpu);
Avi Kivity15ad7142007-07-11 18:17:21 +0300212 put_cpu();
Avi Kivitybccf2152007-02-21 18:04:26 +0200213}
Jim Mattson2f1fe812016-07-08 15:36:06 -0700214EXPORT_SYMBOL_GPL(vcpu_load);
Avi Kivitybccf2152007-02-21 18:04:26 +0200215
Carsten Otte313a3dc2007-10-11 19:16:52 +0200216void vcpu_put(struct kvm_vcpu *vcpu)
Avi Kivity6aa8b732006-12-10 02:21:36 -0800217{
Avi Kivity15ad7142007-07-11 18:17:21 +0300218 preempt_disable();
Carsten Otte313a3dc2007-10-11 19:16:52 +0200219 kvm_arch_vcpu_put(vcpu);
Avi Kivity15ad7142007-07-11 18:17:21 +0300220 preempt_notifier_unregister(&vcpu->preempt_notifier);
Paolo Bonzini7495e222020-01-09 09:57:19 -0500221 __this_cpu_write(kvm_running_vcpu, NULL);
Avi Kivity15ad7142007-07-11 18:17:21 +0300222 preempt_enable();
Avi Kivity6aa8b732006-12-10 02:21:36 -0800223}
Jim Mattson2f1fe812016-07-08 15:36:06 -0700224EXPORT_SYMBOL_GPL(vcpu_put);
Avi Kivity6aa8b732006-12-10 02:21:36 -0800225
Paolo Bonzini7a97cec2017-04-27 14:33:43 +0200226/* TODO: merge with kvm_arch_vcpu_should_kick */
227static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
228{
229 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
230
231 /*
232 * We need to wait for the VCPU to reenable interrupts and get out of
233 * READING_SHADOW_PAGE_TABLES mode.
234 */
235 if (req & KVM_REQUEST_WAIT)
236 return mode != OUTSIDE_GUEST_MODE;
237
238 /*
239 * Need to kick a running VCPU, but otherwise there is nothing to do.
240 */
241 return mode == IN_GUEST_MODE;
242}
243
Avi Kivityd9e368d2007-06-07 19:18:30 +0300244static void ack_flush(void *_completed)
245{
Avi Kivityd9e368d2007-06-07 19:18:30 +0300246}
247
Paolo Bonzinib49defe2017-06-30 13:25:45 +0200248static inline bool kvm_kick_many_cpus(const struct cpumask *cpus, bool wait)
249{
250 if (unlikely(!cpus))
251 cpus = cpu_online_mask;
252
253 if (cpumask_empty(cpus))
254 return false;
255
256 smp_call_function_many(cpus, ack_flush, NULL, wait);
257 return true;
258}
259
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200260bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
Suravee Suthikulpanit54163a32020-05-06 08:17:53 -0500261 struct kvm_vcpu *except,
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200262 unsigned long *vcpu_bitmap, cpumask_var_t tmp)
Avi Kivityd9e368d2007-06-07 19:18:30 +0300263{
Avi Kivity597a5f52008-07-20 14:24:22 +0300264 int i, cpu, me;
Avi Kivityd9e368d2007-06-07 19:18:30 +0300265 struct kvm_vcpu *vcpu;
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200266 bool called;
Rusty Russell6ef7a1b2008-12-08 20:28:04 +1030267
Xiao Guangrong3cba4132011-01-12 15:41:22 +0800268 me = get_cpu();
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200269
Gleb Natapov988a2ca2009-06-09 15:56:29 +0300270 kvm_for_each_vcpu(i, vcpu, kvm) {
Suravee Suthikulpanit54163a32020-05-06 08:17:53 -0500271 if ((vcpu_bitmap && !test_bit(i, vcpu_bitmap)) ||
272 vcpu == except)
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200273 continue;
274
Xiao Guangrong3cba4132011-01-12 15:41:22 +0800275 kvm_make_request(req, vcpu);
Avi Kivityd9e368d2007-06-07 19:18:30 +0300276 cpu = vcpu->cpu;
Xiao Guangrong6b7e2d02011-01-12 15:40:31 +0800277
Radim Krčmář178f02f2017-04-26 22:32:26 +0200278 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
279 continue;
Radim Krčmář6c6e8362017-04-26 22:32:23 +0200280
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200281 if (tmp != NULL && cpu != -1 && cpu != me &&
Paolo Bonzini7a97cec2017-04-27 14:33:43 +0200282 kvm_request_needs_ipi(vcpu, req))
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200283 __cpumask_set_cpu(cpu, tmp);
Avi Kivityd9e368d2007-06-07 19:18:30 +0300284 }
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200285
286 called = kvm_kick_many_cpus(tmp, !!(req & KVM_REQUEST_WAIT));
Xiao Guangrong3cba4132011-01-12 15:41:22 +0800287 put_cpu();
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200288
289 return called;
290}
291
Suravee Suthikulpanit54163a32020-05-06 08:17:53 -0500292bool kvm_make_all_cpus_request_except(struct kvm *kvm, unsigned int req,
293 struct kvm_vcpu *except)
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200294{
295 cpumask_var_t cpus;
296 bool called;
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200297
298 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
299
Suravee Suthikulpanit54163a32020-05-06 08:17:53 -0500300 called = kvm_make_vcpus_request_mask(kvm, req, except, NULL, cpus);
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200301
Rusty Russell6ef7a1b2008-12-08 20:28:04 +1030302 free_cpumask_var(cpus);
Rusty Russell49846892008-12-08 20:26:24 +1030303 return called;
304}
305
Suravee Suthikulpanit54163a32020-05-06 08:17:53 -0500306bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
307{
308 return kvm_make_all_cpus_request_except(kvm, req, NULL);
309}
Marcelo Tosattia2486022021-05-26 14:20:14 -0300310EXPORT_SYMBOL_GPL(kvm_make_all_cpus_request);
Suravee Suthikulpanit54163a32020-05-06 08:17:53 -0500311
Mario Smarducha6d51012015-01-15 15:58:52 -0800312#ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
Rusty Russell49846892008-12-08 20:26:24 +1030313void kvm_flush_remote_tlbs(struct kvm *kvm)
314{
Lan Tianyu4ae3cb32016-03-13 11:10:28 +0800315 /*
316 * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
317 * kvm_make_all_cpus_request.
318 */
319 long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
Xiao Guangronga086f6a2014-04-17 17:06:12 +0800320
Lan Tianyu4ae3cb32016-03-13 11:10:28 +0800321 /*
322 * We want to publish modifications to the page tables before reading
323 * mode. Pairs with a memory barrier in arch-specific code.
324 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
325 * and smp_mb in walk_shadow_page_lockless_begin/end.
326 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
327 *
328 * There is already an smp_mb__after_atomic() before
329 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
330 * barrier here.
331 */
Tianyu Lanb08660e2018-07-19 08:40:17 +0000332 if (!kvm_arch_flush_remote_tlb(kvm)
333 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
Jing Zhang0193cc92021-06-18 22:27:03 +0000334 ++kvm->stat.generic.remote_tlb_flush;
Xiao Guangronga086f6a2014-04-17 17:06:12 +0800335 cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
Avi Kivityd9e368d2007-06-07 19:18:30 +0300336}
Aneesh Kumar K.V2ba9f0d2013-10-07 22:17:59 +0530337EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
Mario Smarducha6d51012015-01-15 15:58:52 -0800338#endif
Avi Kivityd9e368d2007-06-07 19:18:30 +0300339
Marcelo Tosatti2e53d632008-02-20 14:47:24 -0500340void kvm_reload_remote_mmus(struct kvm *kvm)
341{
Tang Chen445b8232014-09-24 15:57:55 +0800342 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
Marcelo Tosatti2e53d632008-02-20 14:47:24 -0500343}
344
Sean Christopherson6926f952020-07-02 19:35:39 -0700345#ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
346static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
347 gfp_t gfp_flags)
348{
349 gfp_flags |= mc->gfp_zero;
350
351 if (mc->kmem_cache)
352 return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
353 else
354 return (void *)__get_free_page(gfp_flags);
355}
356
357int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min)
358{
359 void *obj;
360
361 if (mc->nobjs >= min)
362 return 0;
363 while (mc->nobjs < ARRAY_SIZE(mc->objects)) {
364 obj = mmu_memory_cache_alloc_obj(mc, GFP_KERNEL_ACCOUNT);
365 if (!obj)
366 return mc->nobjs >= min ? 0 : -ENOMEM;
367 mc->objects[mc->nobjs++] = obj;
368 }
369 return 0;
370}
371
372int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc)
373{
374 return mc->nobjs;
375}
376
377void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
378{
379 while (mc->nobjs) {
380 if (mc->kmem_cache)
381 kmem_cache_free(mc->kmem_cache, mc->objects[--mc->nobjs]);
382 else
383 free_page((unsigned long)mc->objects[--mc->nobjs]);
384 }
385}
386
387void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
388{
389 void *p;
390
391 if (WARN_ON(!mc->nobjs))
392 p = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT);
393 else
394 p = mc->objects[--mc->nobjs];
395 BUG_ON(!p);
396 return p;
397}
398#endif
399
Sean Christopherson8bd826d2019-12-18 13:55:30 -0800400static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
Rusty Russellfb3f0f52007-07-27 17:16:56 +1000401{
Rusty Russellfb3f0f52007-07-27 17:16:56 +1000402 mutex_init(&vcpu->mutex);
403 vcpu->cpu = -1;
Rusty Russellfb3f0f52007-07-27 17:16:56 +1000404 vcpu->kvm = kvm;
405 vcpu->vcpu_id = id;
Rik van Riel34bb10b2011-02-01 09:52:41 -0500406 vcpu->pid = NULL;
Davidlohr Buesoda4ad882020-04-23 22:48:37 -0700407 rcuwait_init(&vcpu->wait);
Gleb Natapovaf585b92010-10-14 11:22:46 +0200408 kvm_async_pf_vcpu_init(vcpu);
Rusty Russellfb3f0f52007-07-27 17:16:56 +1000409
Feng Wubf9f6ac2015-09-18 22:29:55 +0800410 vcpu->pre_pcpu = -1;
411 INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
412
Raghavendra K T4c088492012-07-18 19:07:46 +0530413 kvm_vcpu_set_in_spin_loop(vcpu, false);
414 kvm_vcpu_set_dy_eligible(vcpu, false);
Raghavendra K T3a08a8f2013-03-04 23:32:07 +0530415 vcpu->preempted = false;
Wanpeng Lid73eb572019-07-18 19:39:06 +0800416 vcpu->ready = false;
Sean Christophersond5c48de2019-12-18 13:55:17 -0800417 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
David Matlackfe22ed82021-08-04 22:28:40 +0000418 vcpu->last_used_slot = 0;
Rusty Russellfb3f0f52007-07-27 17:16:56 +1000419}
Rusty Russellfb3f0f52007-07-27 17:16:56 +1000420
Sean Christopherson4543bdc2019-12-18 13:55:14 -0800421void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
422{
Peter Xufb04a1e2020-09-30 21:22:22 -0400423 kvm_dirty_ring_free(&vcpu->dirty_ring);
Sean Christopherson4543bdc2019-12-18 13:55:14 -0800424 kvm_arch_vcpu_destroy(vcpu);
Sean Christophersone529ef62019-12-18 13:55:15 -0800425
Sean Christopherson9941d222019-12-18 13:55:29 -0800426 /*
427 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
428 * the vcpu->pid pointer, and at destruction time all file descriptors
429 * are already gone.
430 */
431 put_pid(rcu_dereference_protected(vcpu->pid, 1));
432
Sean Christopherson8bd826d2019-12-18 13:55:30 -0800433 free_page((unsigned long)vcpu->run);
Sean Christophersone529ef62019-12-18 13:55:15 -0800434 kmem_cache_free(kvm_vcpu_cache, vcpu);
Sean Christopherson4543bdc2019-12-18 13:55:14 -0800435}
436EXPORT_SYMBOL_GPL(kvm_vcpu_destroy);
437
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200438#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
439static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
440{
441 return container_of(mn, struct kvm, mmu_notifier);
442}
443
Eiichi Tsukatae649b3f2020-06-06 13:26:27 +0900444static void kvm_mmu_notifier_invalidate_range(struct mmu_notifier *mn,
445 struct mm_struct *mm,
446 unsigned long start, unsigned long end)
447{
448 struct kvm *kvm = mmu_notifier_to_kvm(mn);
449 int idx;
450
451 idx = srcu_read_lock(&kvm->srcu);
452 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
453 srcu_read_unlock(&kvm->srcu, idx);
454}
455
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700456typedef bool (*hva_handler_t)(struct kvm *kvm, struct kvm_gfn_range *range);
457
Sean Christophersonf922bd92021-04-01 17:56:55 -0700458typedef void (*on_lock_fn_t)(struct kvm *kvm, unsigned long start,
459 unsigned long end);
460
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700461struct kvm_hva_range {
462 unsigned long start;
463 unsigned long end;
464 pte_t pte;
465 hva_handler_t handler;
Sean Christophersonf922bd92021-04-01 17:56:55 -0700466 on_lock_fn_t on_lock;
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700467 bool flush_on_ret;
468 bool may_block;
469};
470
Sean Christophersonf922bd92021-04-01 17:56:55 -0700471/*
472 * Use a dedicated stub instead of NULL to indicate that there is no callback
473 * function/handler. The compiler technically can't guarantee that a real
474 * function will have a non-zero address, and so it will generate code to
475 * check for !NULL, whereas comparing against a stub will be elided at compile
476 * time (unless the compiler is getting long in the tooth, e.g. gcc 4.9).
477 */
478static void kvm_null_fn(void)
479{
480
481}
482#define IS_KVM_NULL_FN(fn) ((fn) == (void *)kvm_null_fn)
483
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700484static __always_inline int __kvm_handle_hva_range(struct kvm *kvm,
485 const struct kvm_hva_range *range)
486{
Sean Christopherson8931a452021-04-01 17:56:56 -0700487 bool ret = false, locked = false;
Sean Christophersonf922bd92021-04-01 17:56:55 -0700488 struct kvm_gfn_range gfn_range;
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700489 struct kvm_memory_slot *slot;
490 struct kvm_memslots *slots;
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700491 int i, idx;
492
Sean Christophersonf922bd92021-04-01 17:56:55 -0700493 /* A null handler is allowed if and only if on_lock() is provided. */
494 if (WARN_ON_ONCE(IS_KVM_NULL_FN(range->on_lock) &&
495 IS_KVM_NULL_FN(range->handler)))
496 return 0;
497
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700498 idx = srcu_read_lock(&kvm->srcu);
499
500 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
501 slots = __kvm_memslots(kvm, i);
502 kvm_for_each_memslot(slot, slots) {
503 unsigned long hva_start, hva_end;
504
505 hva_start = max(range->start, slot->userspace_addr);
506 hva_end = min(range->end, slot->userspace_addr +
507 (slot->npages << PAGE_SHIFT));
508 if (hva_start >= hva_end)
509 continue;
510
511 /*
512 * To optimize for the likely case where the address
513 * range is covered by zero or one memslots, don't
514 * bother making these conditional (to avoid writes on
515 * the second or later invocation of the handler).
516 */
517 gfn_range.pte = range->pte;
518 gfn_range.may_block = range->may_block;
519
520 /*
521 * {gfn(page) | page intersects with [hva_start, hva_end)} =
522 * {gfn_start, gfn_start+1, ..., gfn_end-1}.
523 */
524 gfn_range.start = hva_to_gfn_memslot(hva_start, slot);
525 gfn_range.end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, slot);
526 gfn_range.slot = slot;
527
Sean Christopherson8931a452021-04-01 17:56:56 -0700528 if (!locked) {
529 locked = true;
530 KVM_MMU_LOCK(kvm);
Paolo Bonzini071064f2021-08-03 03:45:41 -0400531 if (!IS_KVM_NULL_FN(range->on_lock))
532 range->on_lock(kvm, range->start, range->end);
533 if (IS_KVM_NULL_FN(range->handler))
534 break;
Sean Christopherson8931a452021-04-01 17:56:56 -0700535 }
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700536 ret |= range->handler(kvm, &gfn_range);
537 }
538 }
539
540 if (range->flush_on_ret && (ret || kvm->tlbs_dirty))
541 kvm_flush_remote_tlbs(kvm);
542
Sean Christopherson8931a452021-04-01 17:56:56 -0700543 if (locked)
544 KVM_MMU_UNLOCK(kvm);
Sean Christophersonf922bd92021-04-01 17:56:55 -0700545
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700546 srcu_read_unlock(&kvm->srcu, idx);
547
548 /* The notifiers are averse to booleans. :-( */
549 return (int)ret;
550}
551
552static __always_inline int kvm_handle_hva_range(struct mmu_notifier *mn,
553 unsigned long start,
554 unsigned long end,
555 pte_t pte,
556 hva_handler_t handler)
557{
558 struct kvm *kvm = mmu_notifier_to_kvm(mn);
559 const struct kvm_hva_range range = {
560 .start = start,
561 .end = end,
562 .pte = pte,
563 .handler = handler,
Sean Christophersonf922bd92021-04-01 17:56:55 -0700564 .on_lock = (void *)kvm_null_fn,
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700565 .flush_on_ret = true,
566 .may_block = false,
567 };
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700568
Sean Christophersonf922bd92021-04-01 17:56:55 -0700569 return __kvm_handle_hva_range(kvm, &range);
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700570}
571
572static __always_inline int kvm_handle_hva_range_no_flush(struct mmu_notifier *mn,
573 unsigned long start,
574 unsigned long end,
575 hva_handler_t handler)
576{
577 struct kvm *kvm = mmu_notifier_to_kvm(mn);
578 const struct kvm_hva_range range = {
579 .start = start,
580 .end = end,
581 .pte = __pte(0),
582 .handler = handler,
Sean Christophersonf922bd92021-04-01 17:56:55 -0700583 .on_lock = (void *)kvm_null_fn,
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700584 .flush_on_ret = false,
585 .may_block = false,
586 };
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700587
Sean Christophersonf922bd92021-04-01 17:56:55 -0700588 return __kvm_handle_hva_range(kvm, &range);
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700589}
Izik Eidus3da0dd42009-09-23 21:47:18 +0300590static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
591 struct mm_struct *mm,
592 unsigned long address,
593 pte_t pte)
594{
595 struct kvm *kvm = mmu_notifier_to_kvm(mn);
596
Sean Christopherson501b9182021-03-25 19:19:48 -0700597 trace_kvm_set_spte_hva(address);
598
Sean Christophersonc13fda22021-04-02 02:56:49 +0200599 /*
Paolo Bonzini52ac8b32021-05-27 08:09:15 -0400600 * .change_pte() must be surrounded by .invalidate_range_{start,end}().
Paolo Bonzini071064f2021-08-03 03:45:41 -0400601 * If mmu_notifier_count is zero, then no in-progress invalidations,
602 * including this one, found a relevant memslot at start(); rechecking
603 * memslots here is unnecessary. Note, a false positive (count elevated
604 * by a different invalidation) is sub-optimal but functionally ok.
Sean Christophersonc13fda22021-04-02 02:56:49 +0200605 */
Paolo Bonzini52ac8b32021-05-27 08:09:15 -0400606 WARN_ON_ONCE(!READ_ONCE(kvm->mn_active_invalidate_count));
Paolo Bonzini071064f2021-08-03 03:45:41 -0400607 if (!READ_ONCE(kvm->mmu_notifier_count))
608 return;
Sean Christophersonc13fda22021-04-02 02:56:49 +0200609
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700610 kvm_handle_hva_range(mn, address, address + 1, pte, kvm_set_spte_gfn);
Izik Eidus3da0dd42009-09-23 21:47:18 +0300611}
612
Sean Christophersonf922bd92021-04-01 17:56:55 -0700613static void kvm_inc_notifier_count(struct kvm *kvm, unsigned long start,
614 unsigned long end)
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200615{
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200616 /*
617 * The count increase must become visible at unlock time as no
618 * spte can be established without taking the mmu_lock and
619 * count is also read inside the mmu_lock critical section.
620 */
621 kvm->mmu_notifier_count++;
David Stevens4a42d842021-02-22 11:45:22 +0900622 if (likely(kvm->mmu_notifier_count == 1)) {
Sean Christophersonf922bd92021-04-01 17:56:55 -0700623 kvm->mmu_notifier_range_start = start;
624 kvm->mmu_notifier_range_end = end;
David Stevens4a42d842021-02-22 11:45:22 +0900625 } else {
626 /*
627 * Fully tracking multiple concurrent ranges has dimishing
628 * returns. Keep things simple and just find the minimal range
629 * which includes the current and new ranges. As there won't be
630 * enough information to subtract a range after its invalidate
631 * completes, any ranges invalidated concurrently will
632 * accumulate and persist until all outstanding invalidates
633 * complete.
634 */
635 kvm->mmu_notifier_range_start =
Sean Christophersonf922bd92021-04-01 17:56:55 -0700636 min(kvm->mmu_notifier_range_start, start);
David Stevens4a42d842021-02-22 11:45:22 +0900637 kvm->mmu_notifier_range_end =
Sean Christophersonf922bd92021-04-01 17:56:55 -0700638 max(kvm->mmu_notifier_range_end, end);
David Stevens4a42d842021-02-22 11:45:22 +0900639 }
Sean Christophersonf922bd92021-04-01 17:56:55 -0700640}
641
642static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
643 const struct mmu_notifier_range *range)
644{
645 struct kvm *kvm = mmu_notifier_to_kvm(mn);
646 const struct kvm_hva_range hva_range = {
647 .start = range->start,
648 .end = range->end,
649 .pte = __pte(0),
650 .handler = kvm_unmap_gfn_range,
651 .on_lock = kvm_inc_notifier_count,
652 .flush_on_ret = true,
653 .may_block = mmu_notifier_range_blockable(range),
654 };
655
656 trace_kvm_unmap_hva_range(range->start, range->end);
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700657
Paolo Bonzini52ac8b32021-05-27 08:09:15 -0400658 /*
659 * Prevent memslot modification between range_start() and range_end()
660 * so that conditionally locking provides the same result in both
661 * functions. Without that guarantee, the mmu_notifier_count
662 * adjustments will be imbalanced.
663 *
664 * Pairs with the decrement in range_end().
665 */
666 spin_lock(&kvm->mn_invalidate_lock);
667 kvm->mn_active_invalidate_count++;
668 spin_unlock(&kvm->mn_invalidate_lock);
669
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700670 __kvm_handle_hva_range(kvm, &hva_range);
Takuya Yoshikawa565f3be2012-02-10 15:28:31 +0900671
Eiichi Tsukatae649b3f2020-06-06 13:26:27 +0900672 return 0;
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200673}
674
Sean Christophersonf922bd92021-04-01 17:56:55 -0700675static void kvm_dec_notifier_count(struct kvm *kvm, unsigned long start,
676 unsigned long end)
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200677{
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200678 /*
679 * This sequence increase will notify the kvm page fault that
680 * the page that is going to be mapped in the spte could have
681 * been freed.
682 */
683 kvm->mmu_notifier_seq++;
Paul Mackerrasa355aa52011-12-12 12:37:21 +0000684 smp_wmb();
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200685 /*
686 * The above sequence increase must be visible before the
Paul Mackerrasa355aa52011-12-12 12:37:21 +0000687 * below count decrease, which is ensured by the smp_wmb above
688 * in conjunction with the smp_rmb in mmu_notifier_retry().
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200689 */
690 kvm->mmu_notifier_count--;
Sean Christophersonf922bd92021-04-01 17:56:55 -0700691}
692
693static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
694 const struct mmu_notifier_range *range)
695{
696 struct kvm *kvm = mmu_notifier_to_kvm(mn);
697 const struct kvm_hva_range hva_range = {
698 .start = range->start,
699 .end = range->end,
700 .pte = __pte(0),
701 .handler = (void *)kvm_null_fn,
702 .on_lock = kvm_dec_notifier_count,
703 .flush_on_ret = false,
704 .may_block = mmu_notifier_range_blockable(range),
705 };
Paolo Bonzini52ac8b32021-05-27 08:09:15 -0400706 bool wake;
Sean Christophersonf922bd92021-04-01 17:56:55 -0700707
708 __kvm_handle_hva_range(kvm, &hva_range);
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200709
Paolo Bonzini52ac8b32021-05-27 08:09:15 -0400710 /* Pairs with the increment in range_start(). */
711 spin_lock(&kvm->mn_invalidate_lock);
712 wake = (--kvm->mn_active_invalidate_count == 0);
713 spin_unlock(&kvm->mn_invalidate_lock);
714
715 /*
716 * There can only be one waiter, since the wait happens under
717 * slots_lock.
718 */
719 if (wake)
720 rcuwait_wake_up(&kvm->mn_memslots_update_rcuwait);
721
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200722 BUG_ON(kvm->mmu_notifier_count < 0);
723}
724
725static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
726 struct mm_struct *mm,
Andres Lagar-Cavilla57128462014-09-22 14:54:42 -0700727 unsigned long start,
728 unsigned long end)
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200729{
Sean Christopherson501b9182021-03-25 19:19:48 -0700730 trace_kvm_age_hva(start, end);
731
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700732 return kvm_handle_hva_range(mn, start, end, __pte(0), kvm_age_gfn);
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200733}
734
Vladimir Davydov1d7715c2015-09-09 15:35:41 -0700735static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
736 struct mm_struct *mm,
737 unsigned long start,
738 unsigned long end)
739{
Sean Christopherson501b9182021-03-25 19:19:48 -0700740 trace_kvm_age_hva(start, end);
741
Vladimir Davydov1d7715c2015-09-09 15:35:41 -0700742 /*
743 * Even though we do not flush TLB, this will still adversely
744 * affect performance on pre-Haswell Intel EPT, where there is
745 * no EPT Access Bit to clear so that we have to tear down EPT
746 * tables instead. If we find this unacceptable, we can always
747 * add a parameter to kvm_age_hva so that it effectively doesn't
748 * do anything on clear_young.
749 *
750 * Also note that currently we never issue secondary TLB flushes
751 * from clear_young, leaving this job up to the regular system
752 * cadence. If we find this inaccurate, we might come up with a
753 * more sophisticated heuristic later.
754 */
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700755 return kvm_handle_hva_range_no_flush(mn, start, end, kvm_age_gfn);
Vladimir Davydov1d7715c2015-09-09 15:35:41 -0700756}
757
Andrea Arcangeli8ee53822011-01-13 15:47:10 -0800758static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
759 struct mm_struct *mm,
760 unsigned long address)
761{
Sean Christopherson501b9182021-03-25 19:19:48 -0700762 trace_kvm_test_age_hva(address);
763
Sean Christopherson3039bcc2021-04-01 17:56:50 -0700764 return kvm_handle_hva_range_no_flush(mn, address, address + 1,
765 kvm_test_age_gfn);
Andrea Arcangeli8ee53822011-01-13 15:47:10 -0800766}
767
Marcelo Tosatti85db06e2008-12-10 21:23:26 +0100768static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
769 struct mm_struct *mm)
770{
771 struct kvm *kvm = mmu_notifier_to_kvm(mn);
Lai Jiangshaneda2bed2010-04-20 14:29:29 +0800772 int idx;
773
774 idx = srcu_read_lock(&kvm->srcu);
Marcelo Tosatti2df72e92012-08-24 15:54:57 -0300775 kvm_arch_flush_shadow_all(kvm);
Lai Jiangshaneda2bed2010-04-20 14:29:29 +0800776 srcu_read_unlock(&kvm->srcu, idx);
Marcelo Tosatti85db06e2008-12-10 21:23:26 +0100777}
778
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200779static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
Eiichi Tsukatae649b3f2020-06-06 13:26:27 +0900780 .invalidate_range = kvm_mmu_notifier_invalidate_range,
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200781 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
782 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
783 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
Vladimir Davydov1d7715c2015-09-09 15:35:41 -0700784 .clear_young = kvm_mmu_notifier_clear_young,
Andrea Arcangeli8ee53822011-01-13 15:47:10 -0800785 .test_young = kvm_mmu_notifier_test_young,
Izik Eidus3da0dd42009-09-23 21:47:18 +0300786 .change_pte = kvm_mmu_notifier_change_pte,
Marcelo Tosatti85db06e2008-12-10 21:23:26 +0100787 .release = kvm_mmu_notifier_release,
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200788};
Avi Kivity4c07b0a2009-12-20 14:54:04 +0200789
790static int kvm_init_mmu_notifier(struct kvm *kvm)
791{
792 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
793 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
794}
795
796#else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
797
798static int kvm_init_mmu_notifier(struct kvm *kvm)
799{
800 return 0;
801}
802
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200803#endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
804
Sergey Senozhatsky2fdef3a2021-06-06 11:10:44 +0900805#ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
806static int kvm_pm_notifier_call(struct notifier_block *bl,
807 unsigned long state,
808 void *unused)
809{
810 struct kvm *kvm = container_of(bl, struct kvm, pm_notifier);
811
812 return kvm_arch_pm_notifier(kvm, state);
813}
814
815static void kvm_init_pm_notifier(struct kvm *kvm)
816{
817 kvm->pm_notifier.notifier_call = kvm_pm_notifier_call;
818 /* Suspend KVM before we suspend ftrace, RCU, etc. */
819 kvm->pm_notifier.priority = INT_MAX;
820 register_pm_notifier(&kvm->pm_notifier);
821}
822
823static void kvm_destroy_pm_notifier(struct kvm *kvm)
824{
825 unregister_pm_notifier(&kvm->pm_notifier);
826}
827#else /* !CONFIG_HAVE_KVM_PM_NOTIFIER */
828static void kvm_init_pm_notifier(struct kvm *kvm)
829{
830}
831
832static void kvm_destroy_pm_notifier(struct kvm *kvm)
833{
834}
835#endif /* CONFIG_HAVE_KVM_PM_NOTIFIER */
836
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200837static struct kvm_memslots *kvm_alloc_memslots(void)
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +0800838{
839 int i;
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200840 struct kvm_memslots *slots;
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +0800841
Ben Gardonb12ce362019-02-11 11:02:49 -0800842 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL_ACCOUNT);
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200843 if (!slots)
844 return NULL;
845
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +0800846 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
Sean Christopherson36947252020-02-18 13:07:32 -0800847 slots->id_to_index[i] = -1;
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200848
849 return slots;
850}
851
852static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
853{
854 if (!memslot->dirty_bitmap)
855 return;
856
857 kvfree(memslot->dirty_bitmap);
858 memslot->dirty_bitmap = NULL;
859}
860
Sean Christophersone96c81e2020-02-18 13:07:27 -0800861static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200862{
Sean Christophersone96c81e2020-02-18 13:07:27 -0800863 kvm_destroy_dirty_bitmap(slot);
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200864
Sean Christophersone96c81e2020-02-18 13:07:27 -0800865 kvm_arch_free_memslot(kvm, slot);
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200866
Sean Christophersone96c81e2020-02-18 13:07:27 -0800867 slot->flags = 0;
868 slot->npages = 0;
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200869}
870
871static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
872{
873 struct kvm_memory_slot *memslot;
874
875 if (!slots)
876 return;
877
878 kvm_for_each_memslot(memslot, slots)
Sean Christophersone96c81e2020-02-18 13:07:27 -0800879 kvm_free_memslot(kvm, memslot);
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200880
881 kvfree(slots);
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +0800882}
883
Jing Zhangbc9e9e62021-06-23 17:28:46 -0400884static umode_t kvm_stats_debugfs_mode(const struct _kvm_stats_desc *pdesc)
885{
886 switch (pdesc->desc.flags & KVM_STATS_TYPE_MASK) {
887 case KVM_STATS_TYPE_INSTANT:
888 return 0444;
889 case KVM_STATS_TYPE_CUMULATIVE:
890 case KVM_STATS_TYPE_PEAK:
891 default:
892 return 0644;
893 }
894}
895
896
Janosch Frank536a6f82016-05-18 13:26:23 +0200897static void kvm_destroy_vm_debugfs(struct kvm *kvm)
898{
899 int i;
Jing Zhangbc9e9e62021-06-23 17:28:46 -0400900 int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
901 kvm_vcpu_stats_header.num_desc;
Janosch Frank536a6f82016-05-18 13:26:23 +0200902
903 if (!kvm->debugfs_dentry)
904 return;
905
906 debugfs_remove_recursive(kvm->debugfs_dentry);
907
Luiz Capitulino9d5a1dc2016-09-07 14:47:21 -0400908 if (kvm->debugfs_stat_data) {
909 for (i = 0; i < kvm_debugfs_num_entries; i++)
910 kfree(kvm->debugfs_stat_data[i]);
911 kfree(kvm->debugfs_stat_data);
912 }
Janosch Frank536a6f82016-05-18 13:26:23 +0200913}
914
915static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
916{
Paolo Bonzini85cd39a2021-08-04 05:28:52 -0400917 static DEFINE_MUTEX(kvm_debugfs_lock);
918 struct dentry *dent;
Janosch Frank536a6f82016-05-18 13:26:23 +0200919 char dir_name[ITOA_MAX_LEN * 2];
920 struct kvm_stat_data *stat_data;
Jing Zhangbc9e9e62021-06-23 17:28:46 -0400921 const struct _kvm_stats_desc *pdesc;
Peter Xu3165af72021-07-30 18:04:49 -0400922 int i, ret;
Jing Zhangbc9e9e62021-06-23 17:28:46 -0400923 int kvm_debugfs_num_entries = kvm_vm_stats_header.num_desc +
924 kvm_vcpu_stats_header.num_desc;
Janosch Frank536a6f82016-05-18 13:26:23 +0200925
926 if (!debugfs_initialized())
927 return 0;
928
929 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
Paolo Bonzini85cd39a2021-08-04 05:28:52 -0400930 mutex_lock(&kvm_debugfs_lock);
931 dent = debugfs_lookup(dir_name, kvm_debugfs_dir);
932 if (dent) {
933 pr_warn_ratelimited("KVM: debugfs: duplicate directory %s\n", dir_name);
934 dput(dent);
935 mutex_unlock(&kvm_debugfs_lock);
936 return 0;
937 }
938 dent = debugfs_create_dir(dir_name, kvm_debugfs_dir);
939 mutex_unlock(&kvm_debugfs_lock);
940 if (IS_ERR(dent))
941 return 0;
Janosch Frank536a6f82016-05-18 13:26:23 +0200942
Paolo Bonzini85cd39a2021-08-04 05:28:52 -0400943 kvm->debugfs_dentry = dent;
Janosch Frank536a6f82016-05-18 13:26:23 +0200944 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
945 sizeof(*kvm->debugfs_stat_data),
Ben Gardonb12ce362019-02-11 11:02:49 -0800946 GFP_KERNEL_ACCOUNT);
Janosch Frank536a6f82016-05-18 13:26:23 +0200947 if (!kvm->debugfs_stat_data)
948 return -ENOMEM;
949
Jing Zhangbc9e9e62021-06-23 17:28:46 -0400950 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
951 pdesc = &kvm_vm_stats_desc[i];
Ben Gardonb12ce362019-02-11 11:02:49 -0800952 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
Janosch Frank536a6f82016-05-18 13:26:23 +0200953 if (!stat_data)
954 return -ENOMEM;
955
956 stat_data->kvm = kvm;
Jing Zhangbc9e9e62021-06-23 17:28:46 -0400957 stat_data->desc = pdesc;
958 stat_data->kind = KVM_STAT_VM;
959 kvm->debugfs_stat_data[i] = stat_data;
960 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
961 kvm->debugfs_dentry, stat_data,
962 &stat_fops_per_vm);
963 }
964
965 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
966 pdesc = &kvm_vcpu_stats_desc[i];
967 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
968 if (!stat_data)
969 return -ENOMEM;
970
971 stat_data->kvm = kvm;
972 stat_data->desc = pdesc;
973 stat_data->kind = KVM_STAT_VCPU;
Pavel Skripkin004d62e2021-07-01 22:55:00 +0300974 kvm->debugfs_stat_data[i + kvm_vm_stats_header.num_desc] = stat_data;
Jing Zhangbc9e9e62021-06-23 17:28:46 -0400975 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
Milan Pandurov09cbcef2019-12-13 14:07:21 +0100976 kvm->debugfs_dentry, stat_data,
977 &stat_fops_per_vm);
Janosch Frank536a6f82016-05-18 13:26:23 +0200978 }
Peter Xu3165af72021-07-30 18:04:49 -0400979
980 ret = kvm_arch_create_vm_debugfs(kvm);
981 if (ret) {
982 kvm_destroy_vm_debugfs(kvm);
983 return i;
984 }
985
Janosch Frank536a6f82016-05-18 13:26:23 +0200986 return 0;
987}
988
Junaid Shahid1aa9b952019-11-04 20:26:00 +0100989/*
990 * Called after the VM is otherwise initialized, but just before adding it to
991 * the vm_list.
992 */
993int __weak kvm_arch_post_init_vm(struct kvm *kvm)
994{
995 return 0;
996}
997
998/*
999 * Called just after removing the VM from the vm_list, but before doing any
1000 * other destruction.
1001 */
1002void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
1003{
1004}
1005
Peter Xu3165af72021-07-30 18:04:49 -04001006/*
1007 * Called after per-vm debugfs created. When called kvm->debugfs_dentry should
1008 * be setup already, so we can create arch-specific debugfs entries under it.
1009 * Cleanup should be automatic done in kvm_destroy_vm_debugfs() recursively, so
1010 * a per-arch destroy interface is not needed.
1011 */
1012int __weak kvm_arch_create_vm_debugfs(struct kvm *kvm)
1013{
1014 return 0;
1015}
1016
Carsten Ottee08b9632012-01-04 10:25:20 +01001017static struct kvm *kvm_create_vm(unsigned long type)
Avi Kivity6aa8b732006-12-10 02:21:36 -08001018{
Jan Kiszkad89f5ef2010-11-09 17:02:49 +01001019 struct kvm *kvm = kvm_arch_alloc_vm();
Jim Mattson91219232019-10-24 16:03:26 -07001020 int r = -ENOMEM;
1021 int i;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001022
Jan Kiszkad89f5ef2010-11-09 17:02:49 +01001023 if (!kvm)
1024 return ERR_PTR(-ENOMEM);
1025
Ben Gardon531810c2021-02-02 10:57:24 -08001026 KVM_MMU_LOCK_INIT(kvm);
Vegard Nossumf1f10072017-02-27 14:30:07 -08001027 mmgrab(current->mm);
Paolo Bonzinie9ad4ec2016-03-21 10:15:25 +01001028 kvm->mm = current->mm;
1029 kvm_eventfd_init(kvm);
1030 mutex_init(&kvm->lock);
1031 mutex_init(&kvm->irq_lock);
1032 mutex_init(&kvm->slots_lock);
Ben Gardonb10a0382021-05-18 10:34:11 -07001033 mutex_init(&kvm->slots_arch_lock);
Paolo Bonzini52ac8b32021-05-27 08:09:15 -04001034 spin_lock_init(&kvm->mn_invalidate_lock);
1035 rcuwait_init(&kvm->mn_memslots_update_rcuwait);
1036
Paolo Bonzinie9ad4ec2016-03-21 10:15:25 +01001037 INIT_LIST_HEAD(&kvm->devices);
1038
Jim Mattson91219232019-10-24 16:03:26 -07001039 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
1040
Paolo Bonzini8a441192019-11-04 12:16:49 +01001041 if (init_srcu_struct(&kvm->srcu))
1042 goto out_err_no_srcu;
1043 if (init_srcu_struct(&kvm->irq_srcu))
1044 goto out_err_no_irq_srcu;
1045
Paolo Bonzinie2d3fca2019-11-04 13:23:53 +01001046 refcount_set(&kvm->users_count, 1);
Jim Mattson91219232019-10-24 16:03:26 -07001047 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1048 struct kvm_memslots *slots = kvm_alloc_memslots();
1049
1050 if (!slots)
Jim Mattsona97b0e72019-10-25 13:34:58 +02001051 goto out_err_no_arch_destroy_vm;
Jim Mattson91219232019-10-24 16:03:26 -07001052 /* Generations must be different for each address space. */
1053 slots->generation = i;
1054 rcu_assign_pointer(kvm->memslots[i], slots);
1055 }
1056
1057 for (i = 0; i < KVM_NR_BUSES; i++) {
1058 rcu_assign_pointer(kvm->buses[i],
1059 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
1060 if (!kvm->buses[i])
Jim Mattsona97b0e72019-10-25 13:34:58 +02001061 goto out_err_no_arch_destroy_vm;
Jim Mattson91219232019-10-24 16:03:26 -07001062 }
1063
David Matlackacd05782020-04-17 15:14:46 -07001064 kvm->max_halt_poll_ns = halt_poll_ns;
1065
Carsten Ottee08b9632012-01-04 10:25:20 +01001066 r = kvm_arch_init_vm(kvm, type);
Jan Kiszkad89f5ef2010-11-09 17:02:49 +01001067 if (r)
Jim Mattsona97b0e72019-10-25 13:34:58 +02001068 goto out_err_no_arch_destroy_vm;
Alexander Graf10474ae2009-09-15 11:37:46 +02001069
1070 r = hardware_enable_all();
1071 if (r)
Christian Borntraeger719d93c2014-01-16 13:44:20 +01001072 goto out_err_no_disable;
Alexander Graf10474ae2009-09-15 11:37:46 +02001073
Paolo Bonzinic77dcac2014-08-06 14:24:45 +02001074#ifdef CONFIG_HAVE_KVM_IRQFD
Gleb Natapov136bdfe2009-08-24 11:54:23 +03001075 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
Avi Kivity75858a82009-01-04 17:10:50 +02001076#endif
Avi Kivity6aa8b732006-12-10 02:21:36 -08001077
Mike Waychison74b5c5b2011-06-03 13:04:53 -07001078 r = kvm_init_mmu_notifier(kvm);
1079 if (r)
Junaid Shahid1aa9b952019-11-04 20:26:00 +01001080 goto out_err_no_mmu_notifier;
1081
1082 r = kvm_arch_post_init_vm(kvm);
1083 if (r)
Mike Waychison74b5c5b2011-06-03 13:04:53 -07001084 goto out_err;
1085
Junaid Shahid0d9ce162019-01-03 17:14:28 -08001086 mutex_lock(&kvm_lock);
Rusty Russell5e58cfe2007-07-23 17:08:21 +10001087 list_add(&kvm->vm_list, &vm_list);
Junaid Shahid0d9ce162019-01-03 17:14:28 -08001088 mutex_unlock(&kvm_lock);
Jan Kiszkad89f5ef2010-11-09 17:02:49 +01001089
Peter Zijlstra2ecd9d22015-07-03 18:53:58 +02001090 preempt_notifier_inc();
Sergey Senozhatsky2fdef3a2021-06-06 11:10:44 +09001091 kvm_init_pm_notifier(kvm);
Peter Zijlstra2ecd9d22015-07-03 18:53:58 +02001092
Avi Kivityf17abe92007-02-21 19:28:04 +02001093 return kvm;
Alexander Graf10474ae2009-09-15 11:37:46 +02001094
1095out_err:
Junaid Shahid1aa9b952019-11-04 20:26:00 +01001096#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1097 if (kvm->mmu_notifier.ops)
1098 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
1099#endif
1100out_err_no_mmu_notifier:
Alexander Graf10474ae2009-09-15 11:37:46 +02001101 hardware_disable_all();
Christian Borntraeger719d93c2014-01-16 13:44:20 +01001102out_err_no_disable:
Jim Mattsona97b0e72019-10-25 13:34:58 +02001103 kvm_arch_destroy_vm(kvm);
Jim Mattsona97b0e72019-10-25 13:34:58 +02001104out_err_no_arch_destroy_vm:
Paolo Bonzinie2d3fca2019-11-04 13:23:53 +01001105 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02001106 for (i = 0; i < KVM_NR_BUSES; i++)
Paolo Bonzini3898da92017-08-02 17:55:54 +02001107 kfree(kvm_get_bus(kvm, i));
Paolo Bonzinif481b062015-05-17 17:30:37 +02001108 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
Paolo Bonzini3898da92017-08-02 17:55:54 +02001109 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
Paolo Bonzini8a441192019-11-04 12:16:49 +01001110 cleanup_srcu_struct(&kvm->irq_srcu);
1111out_err_no_irq_srcu:
1112 cleanup_srcu_struct(&kvm->srcu);
1113out_err_no_srcu:
Jan Kiszkad89f5ef2010-11-09 17:02:49 +01001114 kvm_arch_free_vm(kvm);
Paolo Bonzinie9ad4ec2016-03-21 10:15:25 +01001115 mmdrop(current->mm);
Alexander Graf10474ae2009-09-15 11:37:46 +02001116 return ERR_PTR(r);
Avi Kivityf17abe92007-02-21 19:28:04 +02001117}
1118
Scott Wood07f0a7b2013-04-25 14:11:23 +00001119static void kvm_destroy_devices(struct kvm *kvm)
1120{
Geliang Tange6e3b5a2016-01-01 19:47:12 +08001121 struct kvm_device *dev, *tmp;
Scott Wood07f0a7b2013-04-25 14:11:23 +00001122
Christoffer Dalla28ebea2016-08-09 19:13:01 +02001123 /*
1124 * We do not need to take the kvm->lock here, because nobody else
1125 * has a reference to the struct kvm at this point and therefore
1126 * cannot access the devices list anyhow.
1127 */
Geliang Tange6e3b5a2016-01-01 19:47:12 +08001128 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
1129 list_del(&dev->vm_node);
Scott Wood07f0a7b2013-04-25 14:11:23 +00001130 dev->ops->destroy(dev);
1131 }
1132}
1133
Avi Kivityf17abe92007-02-21 19:28:04 +02001134static void kvm_destroy_vm(struct kvm *kvm)
1135{
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02001136 int i;
Avi Kivity6d4e4c42007-11-21 16:41:05 +02001137 struct mm_struct *mm = kvm->mm;
1138
Sergey Senozhatsky2fdef3a2021-06-06 11:10:44 +09001139 kvm_destroy_pm_notifier(kvm);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02001140 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
Janosch Frank536a6f82016-05-18 13:26:23 +02001141 kvm_destroy_vm_debugfs(kvm);
Sheng Yangad8ba2c2009-01-06 10:03:02 +08001142 kvm_arch_sync_events(kvm);
Junaid Shahid0d9ce162019-01-03 17:14:28 -08001143 mutex_lock(&kvm_lock);
Avi Kivity133de902007-02-12 00:54:44 -08001144 list_del(&kvm->vm_list);
Junaid Shahid0d9ce162019-01-03 17:14:28 -08001145 mutex_unlock(&kvm_lock);
Junaid Shahid1aa9b952019-11-04 20:26:00 +01001146 kvm_arch_pre_destroy_vm(kvm);
1147
Avi Kivity399ec802008-11-19 13:58:46 +02001148 kvm_free_irq_routing(kvm);
Peter Xudf630b82017-03-15 16:01:17 +08001149 for (i = 0; i < KVM_NR_BUSES; i++) {
Paolo Bonzini3898da92017-08-02 17:55:54 +02001150 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
Christian Borntraeger4a12f952017-07-07 10:51:38 +02001151
Christian Borntraeger4a12f952017-07-07 10:51:38 +02001152 if (bus)
1153 kvm_io_bus_destroy(bus);
Peter Xudf630b82017-03-15 16:01:17 +08001154 kvm->buses[i] = NULL;
1155 }
Avi Kivity980da6c2009-12-20 15:13:43 +02001156 kvm_coalesced_mmio_free(kvm);
Andrea Arcangelie930bff2008-07-25 16:24:52 +02001157#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1158 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
Paolo Bonzini52ac8b32021-05-27 08:09:15 -04001159 /*
1160 * At this point, pending calls to invalidate_range_start()
1161 * have completed but no more MMU notifiers will run, so
1162 * mn_active_invalidate_count may remain unbalanced.
1163 * No threads can be waiting in install_new_memslots as the
1164 * last reference on KVM has been dropped, but freeing
1165 * memslots would deadlock without this manual intervention.
1166 */
1167 WARN_ON(rcuwait_active(&kvm->mn_memslots_update_rcuwait));
1168 kvm->mn_active_invalidate_count = 0;
Gleb Natapovf00be0c2009-03-19 12:20:36 +02001169#else
Marcelo Tosatti2df72e92012-08-24 15:54:57 -03001170 kvm_arch_flush_shadow_all(kvm);
Andrea Arcangelie930bff2008-07-25 16:24:52 +02001171#endif
Zhang Xiantaod19a9cd2007-11-18 18:43:45 +08001172 kvm_arch_destroy_vm(kvm);
Scott Wood07f0a7b2013-04-25 14:11:23 +00001173 kvm_destroy_devices(kvm);
Paolo Bonzinif481b062015-05-17 17:30:37 +02001174 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
Paolo Bonzini3898da92017-08-02 17:55:54 +02001175 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
Paolo Bonzini820b3fc2014-06-03 13:44:17 +02001176 cleanup_srcu_struct(&kvm->irq_srcu);
Jan Kiszkad89f5ef2010-11-09 17:02:49 +01001177 cleanup_srcu_struct(&kvm->srcu);
1178 kvm_arch_free_vm(kvm);
Peter Zijlstra2ecd9d22015-07-03 18:53:58 +02001179 preempt_notifier_dec();
Alexander Graf10474ae2009-09-15 11:37:46 +02001180 hardware_disable_all();
Avi Kivity6d4e4c42007-11-21 16:41:05 +02001181 mmdrop(mm);
Avi Kivityf17abe92007-02-21 19:28:04 +02001182}
1183
Izik Eidusd39f13b2008-03-30 16:01:25 +03001184void kvm_get_kvm(struct kvm *kvm)
1185{
Elena Reshetovae3736c32017-02-20 13:06:21 +02001186 refcount_inc(&kvm->users_count);
Izik Eidusd39f13b2008-03-30 16:01:25 +03001187}
1188EXPORT_SYMBOL_GPL(kvm_get_kvm);
1189
Peter Xu605c7132021-06-25 11:32:07 -04001190/*
1191 * Make sure the vm is not during destruction, which is a safe version of
1192 * kvm_get_kvm(). Return true if kvm referenced successfully, false otherwise.
1193 */
1194bool kvm_get_kvm_safe(struct kvm *kvm)
1195{
1196 return refcount_inc_not_zero(&kvm->users_count);
1197}
1198EXPORT_SYMBOL_GPL(kvm_get_kvm_safe);
1199
Izik Eidusd39f13b2008-03-30 16:01:25 +03001200void kvm_put_kvm(struct kvm *kvm)
1201{
Elena Reshetovae3736c32017-02-20 13:06:21 +02001202 if (refcount_dec_and_test(&kvm->users_count))
Izik Eidusd39f13b2008-03-30 16:01:25 +03001203 kvm_destroy_vm(kvm);
1204}
1205EXPORT_SYMBOL_GPL(kvm_put_kvm);
1206
Sean Christopherson149487b2019-10-21 15:58:42 -07001207/*
1208 * Used to put a reference that was taken on behalf of an object associated
1209 * with a user-visible file descriptor, e.g. a vcpu or device, if installation
1210 * of the new file descriptor fails and the reference cannot be transferred to
1211 * its final owner. In such cases, the caller is still actively using @kvm and
1212 * will fail miserably if the refcount unexpectedly hits zero.
1213 */
1214void kvm_put_kvm_no_destroy(struct kvm *kvm)
1215{
1216 WARN_ON(refcount_dec_and_test(&kvm->users_count));
1217}
1218EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
Izik Eidusd39f13b2008-03-30 16:01:25 +03001219
Avi Kivityf17abe92007-02-21 19:28:04 +02001220static int kvm_vm_release(struct inode *inode, struct file *filp)
1221{
1222 struct kvm *kvm = filp->private_data;
1223
Gregory Haskins721eecbf2009-05-20 10:30:49 -04001224 kvm_irqfd_release(kvm);
1225
Izik Eidusd39f13b2008-03-30 16:01:25 +03001226 kvm_put_kvm(kvm);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001227 return 0;
1228}
1229
Takuya Yoshikawa515a0122010-10-27 18:23:54 +09001230/*
1231 * Allocation size is twice as large as the actual dirty bitmap size.
Sean Christopherson0dff0842020-02-18 13:07:29 -08001232 * See kvm_vm_ioctl_get_dirty_log() why this is needed.
Takuya Yoshikawa515a0122010-10-27 18:23:54 +09001233 */
Jay Zhou3c9bd402020-02-27 09:32:27 +08001234static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
Takuya Yoshikawaa36a57b12010-10-27 18:22:19 +09001235{
Takuya Yoshikawa515a0122010-10-27 18:23:54 +09001236 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
Takuya Yoshikawaa36a57b12010-10-27 18:22:19 +09001237
Ben Gardonb12ce362019-02-11 11:02:49 -08001238 memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL_ACCOUNT);
Takuya Yoshikawaa36a57b12010-10-27 18:22:19 +09001239 if (!memslot->dirty_bitmap)
1240 return -ENOMEM;
1241
Takuya Yoshikawaa36a57b12010-10-27 18:22:19 +09001242 return 0;
1243}
1244
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +08001245/*
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001246 * Delete a memslot by decrementing the number of used slots and shifting all
1247 * other entries in the array forward one spot.
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +08001248 */
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001249static inline void kvm_memslot_delete(struct kvm_memslots *slots,
1250 struct kvm_memory_slot *memslot)
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +08001251{
Igor Mammedov063584d2014-11-13 23:00:13 +00001252 struct kvm_memory_slot *mslots = slots->memslots;
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001253 int i;
Xiao Guangrongf85e2cb2011-11-24 17:41:54 +08001254
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001255 if (WARN_ON(slots->id_to_index[memslot->id] == -1))
1256 return;
Igor Mammedov0e60b072014-12-01 17:29:26 +00001257
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001258 slots->used_slots--;
1259
David Matlack87689272021-08-04 22:28:38 +00001260 if (atomic_read(&slots->last_used_slot) >= slots->used_slots)
1261 atomic_set(&slots->last_used_slot, 0);
Sean Christopherson0774a962020-03-20 13:55:40 -07001262
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001263 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots; i++) {
Igor Mammedov7f379cf2014-12-01 17:29:24 +00001264 mslots[i] = mslots[i + 1];
1265 slots->id_to_index[mslots[i].id] = i;
Igor Mammedov7f379cf2014-12-01 17:29:24 +00001266 }
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001267 mslots[i] = *memslot;
1268 slots->id_to_index[memslot->id] = -1;
1269}
1270
1271/*
1272 * "Insert" a new memslot by incrementing the number of used slots. Returns
1273 * the new slot's initial index into the memslots array.
1274 */
1275static inline int kvm_memslot_insert_back(struct kvm_memslots *slots)
1276{
1277 return slots->used_slots++;
1278}
1279
1280/*
1281 * Move a changed memslot backwards in the array by shifting existing slots
1282 * with a higher GFN toward the front of the array. Note, the changed memslot
1283 * itself is not preserved in the array, i.e. not swapped at this time, only
1284 * its new index into the array is tracked. Returns the changed memslot's
1285 * current index into the memslots array.
1286 */
1287static inline int kvm_memslot_move_backward(struct kvm_memslots *slots,
1288 struct kvm_memory_slot *memslot)
1289{
1290 struct kvm_memory_slot *mslots = slots->memslots;
1291 int i;
1292
1293 if (WARN_ON_ONCE(slots->id_to_index[memslot->id] == -1) ||
1294 WARN_ON_ONCE(!slots->used_slots))
1295 return -1;
Paolo Bonziniefbeec72014-12-27 18:01:00 +01001296
1297 /*
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001298 * Move the target memslot backward in the array by shifting existing
1299 * memslots with a higher GFN (than the target memslot) towards the
1300 * front of the array.
Paolo Bonziniefbeec72014-12-27 18:01:00 +01001301 */
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001302 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots - 1; i++) {
1303 if (memslot->base_gfn > mslots[i + 1].base_gfn)
1304 break;
Xiao Guangrongf85e2cb2011-11-24 17:41:54 +08001305
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001306 WARN_ON_ONCE(memslot->base_gfn == mslots[i + 1].base_gfn);
1307
1308 /* Shift the next memslot forward one and update its index. */
1309 mslots[i] = mslots[i + 1];
1310 slots->id_to_index[mslots[i].id] = i;
1311 }
1312 return i;
1313}
1314
1315/*
1316 * Move a changed memslot forwards in the array by shifting existing slots with
1317 * a lower GFN toward the back of the array. Note, the changed memslot itself
1318 * is not preserved in the array, i.e. not swapped at this time, only its new
1319 * index into the array is tracked. Returns the changed memslot's final index
1320 * into the memslots array.
1321 */
1322static inline int kvm_memslot_move_forward(struct kvm_memslots *slots,
1323 struct kvm_memory_slot *memslot,
1324 int start)
1325{
1326 struct kvm_memory_slot *mslots = slots->memslots;
1327 int i;
1328
1329 for (i = start; i > 0; i--) {
1330 if (memslot->base_gfn < mslots[i - 1].base_gfn)
1331 break;
1332
1333 WARN_ON_ONCE(memslot->base_gfn == mslots[i - 1].base_gfn);
1334
1335 /* Shift the next memslot back one and update its index. */
1336 mslots[i] = mslots[i - 1];
1337 slots->id_to_index[mslots[i].id] = i;
1338 }
1339 return i;
1340}
1341
1342/*
1343 * Re-sort memslots based on their GFN to account for an added, deleted, or
1344 * moved memslot. Sorting memslots by GFN allows using a binary search during
1345 * memslot lookup.
1346 *
1347 * IMPORTANT: Slots are sorted from highest GFN to lowest GFN! I.e. the entry
1348 * at memslots[0] has the highest GFN.
1349 *
1350 * The sorting algorithm takes advantage of having initially sorted memslots
1351 * and knowing the position of the changed memslot. Sorting is also optimized
1352 * by not swapping the updated memslot and instead only shifting other memslots
1353 * and tracking the new index for the update memslot. Only once its final
1354 * index is known is the updated memslot copied into its position in the array.
1355 *
1356 * - When deleting a memslot, the deleted memslot simply needs to be moved to
1357 * the end of the array.
1358 *
1359 * - When creating a memslot, the algorithm "inserts" the new memslot at the
1360 * end of the array and then it forward to its correct location.
1361 *
1362 * - When moving a memslot, the algorithm first moves the updated memslot
1363 * backward to handle the scenario where the memslot's GFN was changed to a
1364 * lower value. update_memslots() then falls through and runs the same flow
1365 * as creating a memslot to move the memslot forward to handle the scenario
1366 * where its GFN was changed to a higher value.
1367 *
1368 * Note, slots are sorted from highest->lowest instead of lowest->highest for
1369 * historical reasons. Originally, invalid memslots where denoted by having
1370 * GFN=0, thus sorting from highest->lowest naturally sorted invalid memslots
1371 * to the end of the array. The current algorithm uses dedicated logic to
1372 * delete a memslot and thus does not rely on invalid memslots having GFN=0.
1373 *
1374 * The other historical motiviation for highest->lowest was to improve the
1375 * performance of memslot lookup. KVM originally used a linear search starting
1376 * at memslots[0]. On x86, the largest memslot usually has one of the highest,
1377 * if not *the* highest, GFN, as the bulk of the guest's RAM is located in a
1378 * single memslot above the 4gb boundary. As the largest memslot is also the
1379 * most likely to be referenced, sorting it to the front of the array was
1380 * advantageous. The current binary search starts from the middle of the array
1381 * and uses an LRU pointer to improve performance for all memslots and GFNs.
1382 */
1383static void update_memslots(struct kvm_memslots *slots,
1384 struct kvm_memory_slot *memslot,
1385 enum kvm_mr_change change)
1386{
1387 int i;
1388
1389 if (change == KVM_MR_DELETE) {
1390 kvm_memslot_delete(slots, memslot);
1391 } else {
1392 if (change == KVM_MR_CREATE)
1393 i = kvm_memslot_insert_back(slots);
1394 else
1395 i = kvm_memslot_move_backward(slots, memslot);
1396 i = kvm_memslot_move_forward(slots, memslot, i);
1397
1398 /*
1399 * Copy the memslot to its new position in memslots and update
1400 * its index accordingly.
1401 */
1402 slots->memslots[i] = *memslot;
1403 slots->id_to_index[memslot->id] = i;
1404 }
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +08001405}
1406
Paolo Bonzini09170a42015-05-18 13:59:39 +02001407static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
Xiao Guangronga50d64d2012-08-21 10:58:13 +08001408{
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001409 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1410
Christoffer Dall0f8a4de2014-08-26 14:00:37 +02001411#ifdef __KVM_HAVE_READONLY_MEM
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001412 valid_flags |= KVM_MEM_READONLY;
1413#endif
1414
1415 if (mem->flags & ~valid_flags)
Xiao Guangronga50d64d2012-08-21 10:58:13 +08001416 return -EINVAL;
1417
1418 return 0;
1419}
1420
Gleb Natapov7ec4fb42012-12-24 17:49:30 +02001421static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
Paolo Bonzinif481b062015-05-17 17:30:37 +02001422 int as_id, struct kvm_memslots *slots)
Gleb Natapov7ec4fb42012-12-24 17:49:30 +02001423{
Paolo Bonzinif481b062015-05-17 17:30:37 +02001424 struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
Sean Christopherson361209e2019-02-05 13:01:14 -08001425 u64 gen = old_memslots->generation;
Gleb Natapov7ec4fb42012-12-24 17:49:30 +02001426
Sean Christopherson361209e2019-02-05 13:01:14 -08001427 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1428 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
David Matlackee3d1572014-08-18 15:46:06 -07001429
Paolo Bonzini52ac8b32021-05-27 08:09:15 -04001430 /*
1431 * Do not store the new memslots while there are invalidations in
Paolo Bonzini071064f2021-08-03 03:45:41 -04001432 * progress, otherwise the locking in invalidate_range_start and
1433 * invalidate_range_end will be unbalanced.
Paolo Bonzini52ac8b32021-05-27 08:09:15 -04001434 */
1435 spin_lock(&kvm->mn_invalidate_lock);
1436 prepare_to_rcuwait(&kvm->mn_memslots_update_rcuwait);
1437 while (kvm->mn_active_invalidate_count) {
1438 set_current_state(TASK_UNINTERRUPTIBLE);
1439 spin_unlock(&kvm->mn_invalidate_lock);
1440 schedule();
1441 spin_lock(&kvm->mn_invalidate_lock);
1442 }
1443 finish_rcuwait(&kvm->mn_memslots_update_rcuwait);
Paolo Bonzinif481b062015-05-17 17:30:37 +02001444 rcu_assign_pointer(kvm->memslots[as_id], slots);
Paolo Bonzini52ac8b32021-05-27 08:09:15 -04001445 spin_unlock(&kvm->mn_invalidate_lock);
Ben Gardonb10a0382021-05-18 10:34:11 -07001446
1447 /*
1448 * Acquired in kvm_set_memslot. Must be released before synchronize
1449 * SRCU below in order to avoid deadlock with another thread
1450 * acquiring the slots_arch_lock in an srcu critical section.
1451 */
1452 mutex_unlock(&kvm->slots_arch_lock);
1453
Gleb Natapov7ec4fb42012-12-24 17:49:30 +02001454 synchronize_srcu_expedited(&kvm->srcu);
Takuya Yoshikawae59dbe02013-07-04 13:40:29 +09001455
David Matlackee3d1572014-08-18 15:46:06 -07001456 /*
Sean Christopherson361209e2019-02-05 13:01:14 -08001457 * Increment the new memslot generation a second time, dropping the
Miaohe Lin00116792019-12-11 14:26:23 +08001458 * update in-progress flag and incrementing the generation based on
Sean Christopherson361209e2019-02-05 13:01:14 -08001459 * the number of address spaces. This provides a unique and easily
1460 * identifiable generation number while the memslots are in flux.
1461 */
1462 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1463
1464 /*
Paolo Bonzini4bd518f2017-02-03 20:44:51 -08001465 * Generations must be unique even across address spaces. We do not need
1466 * a global counter for that, instead the generation space is evenly split
1467 * across address spaces. For example, with two address spaces, address
Sean Christopherson164bf7e2019-02-05 13:01:18 -08001468 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1469 * use generations 1, 3, 5, ...
David Matlackee3d1572014-08-18 15:46:06 -07001470 */
Sean Christopherson164bf7e2019-02-05 13:01:18 -08001471 gen += KVM_ADDRESS_SPACE_NUM;
David Matlackee3d1572014-08-18 15:46:06 -07001472
Sean Christopherson15248252019-02-05 12:54:17 -08001473 kvm_arch_memslots_updated(kvm, gen);
1474
1475 slots->generation = gen;
Takuya Yoshikawae59dbe02013-07-04 13:40:29 +09001476
1477 return old_memslots;
Gleb Natapov7ec4fb42012-12-24 17:49:30 +02001478}
1479
Ben Gardonddc12f22021-05-18 10:34:10 -07001480static size_t kvm_memslots_size(int slots)
1481{
1482 return sizeof(struct kvm_memslots) +
1483 (sizeof(struct kvm_memory_slot) * slots);
1484}
1485
1486static void kvm_copy_memslots(struct kvm_memslots *to,
1487 struct kvm_memslots *from)
1488{
1489 memcpy(to, from, kvm_memslots_size(from->used_slots));
1490}
1491
Sean Christopherson36947252020-02-18 13:07:32 -08001492/*
1493 * Note, at a minimum, the current number of used slots must be allocated, even
1494 * when deleting a memslot, as we need a complete duplicate of the memslots for
1495 * use when invalidating a memslot prior to deleting/moving the memslot.
1496 */
1497static struct kvm_memslots *kvm_dup_memslots(struct kvm_memslots *old,
1498 enum kvm_mr_change change)
1499{
1500 struct kvm_memslots *slots;
Ben Gardonddc12f22021-05-18 10:34:10 -07001501 size_t new_size;
Sean Christopherson36947252020-02-18 13:07:32 -08001502
1503 if (change == KVM_MR_CREATE)
Ben Gardonddc12f22021-05-18 10:34:10 -07001504 new_size = kvm_memslots_size(old->used_slots + 1);
Sean Christopherson36947252020-02-18 13:07:32 -08001505 else
Ben Gardonddc12f22021-05-18 10:34:10 -07001506 new_size = kvm_memslots_size(old->used_slots);
Sean Christopherson36947252020-02-18 13:07:32 -08001507
1508 slots = kvzalloc(new_size, GFP_KERNEL_ACCOUNT);
1509 if (likely(slots))
Ben Gardonddc12f22021-05-18 10:34:10 -07001510 kvm_copy_memslots(slots, old);
Sean Christopherson36947252020-02-18 13:07:32 -08001511
1512 return slots;
1513}
1514
Sean Christophersoncf47f502020-02-18 13:07:23 -08001515static int kvm_set_memslot(struct kvm *kvm,
1516 const struct kvm_userspace_memory_region *mem,
Sean Christopherson9d4c1972020-02-18 13:07:24 -08001517 struct kvm_memory_slot *old,
Sean Christophersoncf47f502020-02-18 13:07:23 -08001518 struct kvm_memory_slot *new, int as_id,
1519 enum kvm_mr_change change)
1520{
1521 struct kvm_memory_slot *slot;
1522 struct kvm_memslots *slots;
1523 int r;
1524
Ben Gardonb10a0382021-05-18 10:34:11 -07001525 /*
1526 * Released in install_new_memslots.
1527 *
1528 * Must be held from before the current memslots are copied until
1529 * after the new memslots are installed with rcu_assign_pointer,
1530 * then released before the synchronize srcu in install_new_memslots.
1531 *
1532 * When modifying memslots outside of the slots_lock, must be held
1533 * before reading the pointer to the current memslots until after all
1534 * changes to those memslots are complete.
1535 *
1536 * These rules ensure that installing new memslots does not lose
1537 * changes made to the previous memslots.
1538 */
1539 mutex_lock(&kvm->slots_arch_lock);
1540
Sean Christopherson36947252020-02-18 13:07:32 -08001541 slots = kvm_dup_memslots(__kvm_memslots(kvm, as_id), change);
Ben Gardonb10a0382021-05-18 10:34:11 -07001542 if (!slots) {
1543 mutex_unlock(&kvm->slots_arch_lock);
Sean Christophersoncf47f502020-02-18 13:07:23 -08001544 return -ENOMEM;
Ben Gardonb10a0382021-05-18 10:34:11 -07001545 }
Sean Christophersoncf47f502020-02-18 13:07:23 -08001546
1547 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1548 /*
1549 * Note, the INVALID flag needs to be in the appropriate entry
1550 * in the freshly allocated memslots, not in @old or @new.
1551 */
1552 slot = id_to_memslot(slots, old->id);
1553 slot->flags |= KVM_MEMSLOT_INVALID;
1554
1555 /*
Ben Gardonb10a0382021-05-18 10:34:11 -07001556 * We can re-use the memory from the old memslots.
1557 * It will be overwritten with a copy of the new memslots
1558 * after reacquiring the slots_arch_lock below.
Sean Christophersoncf47f502020-02-18 13:07:23 -08001559 */
1560 slots = install_new_memslots(kvm, as_id, slots);
1561
1562 /* From this point no new shadow pages pointing to a deleted,
1563 * or moved, memslot will be created.
1564 *
1565 * validation of sp->gfn happens in:
1566 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1567 * - kvm_is_visible_gfn (mmu_check_root)
1568 */
1569 kvm_arch_flush_shadow_memslot(kvm, slot);
Ben Gardonb10a0382021-05-18 10:34:11 -07001570
1571 /* Released in install_new_memslots. */
1572 mutex_lock(&kvm->slots_arch_lock);
1573
1574 /*
1575 * The arch-specific fields of the memslots could have changed
1576 * between releasing the slots_arch_lock in
1577 * install_new_memslots and here, so get a fresh copy of the
1578 * slots.
1579 */
1580 kvm_copy_memslots(slots, __kvm_memslots(kvm, as_id));
Sean Christophersoncf47f502020-02-18 13:07:23 -08001581 }
1582
1583 r = kvm_arch_prepare_memory_region(kvm, new, mem, change);
1584 if (r)
1585 goto out_slots;
1586
1587 update_memslots(slots, new, change);
1588 slots = install_new_memslots(kvm, as_id, slots);
1589
1590 kvm_arch_commit_memory_region(kvm, mem, old, new, change);
1591
1592 kvfree(slots);
1593 return 0;
1594
1595out_slots:
Ben Gardonb10a0382021-05-18 10:34:11 -07001596 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1597 slot = id_to_memslot(slots, old->id);
1598 slot->flags &= ~KVM_MEMSLOT_INVALID;
Sean Christophersoncf47f502020-02-18 13:07:23 -08001599 slots = install_new_memslots(kvm, as_id, slots);
Ben Gardonb10a0382021-05-18 10:34:11 -07001600 } else {
1601 mutex_unlock(&kvm->slots_arch_lock);
1602 }
Sean Christophersoncf47f502020-02-18 13:07:23 -08001603 kvfree(slots);
1604 return r;
1605}
1606
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001607static int kvm_delete_memslot(struct kvm *kvm,
1608 const struct kvm_userspace_memory_region *mem,
1609 struct kvm_memory_slot *old, int as_id)
1610{
1611 struct kvm_memory_slot new;
1612 int r;
1613
1614 if (!old->npages)
1615 return -EINVAL;
1616
1617 memset(&new, 0, sizeof(new));
1618 new.id = old->id;
Peter Xu9e9eb222020-10-14 11:26:46 -07001619 /*
1620 * This is only for debugging purpose; it should never be referenced
1621 * for a removed memslot.
1622 */
1623 new.as_id = as_id;
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001624
1625 r = kvm_set_memslot(kvm, mem, old, &new, as_id, KVM_MR_DELETE);
1626 if (r)
1627 return r;
1628
Sean Christophersone96c81e2020-02-18 13:07:27 -08001629 kvm_free_memslot(kvm, old);
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001630 return 0;
1631}
1632
Avi Kivity6aa8b732006-12-10 02:21:36 -08001633/*
Avi Kivity6aa8b732006-12-10 02:21:36 -08001634 * Allocate some memory and give it an address in the guest physical address
1635 * space.
1636 *
1637 * Discontiguous memory is allowed, mostly for framebuffers.
Sheng Yangf78e0e22007-10-29 09:40:42 +08001638 *
Dominik Dingel02d5d552014-10-27 16:22:56 +01001639 * Must be called holding kvm->slots_lock for write.
Avi Kivity6aa8b732006-12-10 02:21:36 -08001640 */
Sheng Yangf78e0e22007-10-29 09:40:42 +08001641int __kvm_set_memory_region(struct kvm *kvm,
Paolo Bonzini09170a42015-05-18 13:59:39 +02001642 const struct kvm_userspace_memory_region *mem)
Avi Kivity6aa8b732006-12-10 02:21:36 -08001643{
Avi Kivity6aa8b732006-12-10 02:21:36 -08001644 struct kvm_memory_slot old, new;
Sean Christopherson163da372020-02-18 13:07:28 -08001645 struct kvm_memory_slot *tmp;
Takuya Yoshikawaf64c0392013-01-29 11:00:07 +09001646 enum kvm_mr_change change;
Sean Christopherson163da372020-02-18 13:07:28 -08001647 int as_id, id;
1648 int r;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001649
Xiao Guangronga50d64d2012-08-21 10:58:13 +08001650 r = check_memory_region_flags(mem);
1651 if (r)
Sean Christopherson71a4c302020-02-18 13:07:22 -08001652 return r;
Xiao Guangronga50d64d2012-08-21 10:58:13 +08001653
Paolo Bonzinif481b062015-05-17 17:30:37 +02001654 as_id = mem->slot >> 16;
1655 id = (u16)mem->slot;
1656
Avi Kivity6aa8b732006-12-10 02:21:36 -08001657 /* General sanity checks */
1658 if (mem->memory_size & (PAGE_SIZE - 1))
Sean Christopherson71a4c302020-02-18 13:07:22 -08001659 return -EINVAL;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001660 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
Sean Christopherson71a4c302020-02-18 13:07:22 -08001661 return -EINVAL;
Takuya Yoshikawafa3d3152011-05-07 16:35:38 +09001662 /* We can read the guest memory with __xxx_user() later on. */
Paolo Bonzini09d952c2020-06-01 04:17:45 -04001663 if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
Marc Zyngier139bc8a2021-01-21 12:08:15 +00001664 (mem->userspace_addr != untagged_addr(mem->userspace_addr)) ||
Linus Torvalds96d4f262019-01-03 18:57:57 -08001665 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
Paolo Bonzini09d952c2020-06-01 04:17:45 -04001666 mem->memory_size))
Sean Christopherson71a4c302020-02-18 13:07:22 -08001667 return -EINVAL;
Paolo Bonzinif481b062015-05-17 17:30:37 +02001668 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
Sean Christopherson71a4c302020-02-18 13:07:22 -08001669 return -EINVAL;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001670 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
Sean Christopherson71a4c302020-02-18 13:07:22 -08001671 return -EINVAL;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001672
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001673 /*
1674 * Make a full copy of the old memslot, the pointer will become stale
1675 * when the memslots are re-sorted by update_memslots(), and the old
1676 * memslot needs to be referenced after calling update_memslots(), e.g.
Sean Christopherson0dff0842020-02-18 13:07:29 -08001677 * to free its resources and for arch specific behavior.
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001678 */
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001679 tmp = id_to_memslot(__kvm_memslots(kvm, as_id), id);
1680 if (tmp) {
1681 old = *tmp;
1682 tmp = NULL;
1683 } else {
1684 memset(&old, 0, sizeof(old));
1685 old.id = id;
1686 }
Sean Christopherson163da372020-02-18 13:07:28 -08001687
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001688 if (!mem->memory_size)
1689 return kvm_delete_memslot(kvm, mem, &old, as_id);
1690
Peter Xu9e9eb222020-10-14 11:26:46 -07001691 new.as_id = as_id;
Paolo Bonzinif481b062015-05-17 17:30:37 +02001692 new.id = id;
Sean Christopherson163da372020-02-18 13:07:28 -08001693 new.base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
1694 new.npages = mem->memory_size >> PAGE_SHIFT;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001695 new.flags = mem->flags;
Sean Christopherson414de7ab2020-02-18 13:07:20 -08001696 new.userspace_addr = mem->userspace_addr;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001697
Sean Christopherson163da372020-02-18 13:07:28 -08001698 if (new.npages > KVM_MEM_MAX_NR_PAGES)
1699 return -EINVAL;
1700
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001701 if (!old.npages) {
1702 change = KVM_MR_CREATE;
Sean Christopherson163da372020-02-18 13:07:28 -08001703 new.dirty_bitmap = NULL;
1704 memset(&new.arch, 0, sizeof(new.arch));
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001705 } else { /* Modify an existing slot. */
1706 if ((new.userspace_addr != old.userspace_addr) ||
Sean Christopherson163da372020-02-18 13:07:28 -08001707 (new.npages != old.npages) ||
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001708 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
Sean Christopherson71a4c302020-02-18 13:07:22 -08001709 return -EINVAL;
Paolo Bonzini09170a42015-05-18 13:59:39 +02001710
Sean Christopherson163da372020-02-18 13:07:28 -08001711 if (new.base_gfn != old.base_gfn)
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001712 change = KVM_MR_MOVE;
1713 else if (new.flags != old.flags)
1714 change = KVM_MR_FLAGS_ONLY;
1715 else /* Nothing to change. */
1716 return 0;
Sean Christopherson163da372020-02-18 13:07:28 -08001717
1718 /* Copy dirty_bitmap and arch from the current memslot. */
1719 new.dirty_bitmap = old.dirty_bitmap;
1720 memcpy(&new.arch, &old.arch, sizeof(new.arch));
Paolo Bonzini09170a42015-05-18 13:59:39 +02001721 }
Avi Kivity6aa8b732006-12-10 02:21:36 -08001722
Takuya Yoshikawaf64c0392013-01-29 11:00:07 +09001723 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
Takuya Yoshikawa0a706be2013-01-11 18:26:55 +09001724 /* Check for overlaps */
Sean Christopherson163da372020-02-18 13:07:28 -08001725 kvm_for_each_memslot(tmp, __kvm_memslots(kvm, as_id)) {
1726 if (tmp->id == id)
Takuya Yoshikawa0a706be2013-01-11 18:26:55 +09001727 continue;
Sean Christopherson163da372020-02-18 13:07:28 -08001728 if (!((new.base_gfn + new.npages <= tmp->base_gfn) ||
1729 (new.base_gfn >= tmp->base_gfn + tmp->npages)))
Sean Christopherson71a4c302020-02-18 13:07:22 -08001730 return -EEXIST;
Takuya Yoshikawa0a706be2013-01-11 18:26:55 +09001731 }
Avi Kivity6aa8b732006-12-10 02:21:36 -08001732 }
Avi Kivity6aa8b732006-12-10 02:21:36 -08001733
Sean Christopherson414de7ab2020-02-18 13:07:20 -08001734 /* Allocate/free page dirty bitmap as needed */
Avi Kivity6aa8b732006-12-10 02:21:36 -08001735 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
Al Viro8b6d44c2007-02-09 16:38:40 +00001736 new.dirty_bitmap = NULL;
Peter Xu044c59c2020-09-30 21:22:26 -04001737 else if (!new.dirty_bitmap && !kvm->dirty_ring_size) {
Jay Zhou3c9bd402020-02-27 09:32:27 +08001738 r = kvm_alloc_dirty_bitmap(&new);
Sean Christopherson71a4c302020-02-18 13:07:22 -08001739 if (r)
1740 return r;
Jay Zhou3c9bd402020-02-27 09:32:27 +08001741
1742 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1743 bitmap_set(new.dirty_bitmap, 0, new.npages);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001744 }
1745
Sean Christophersoncf47f502020-02-18 13:07:23 -08001746 r = kvm_set_memslot(kvm, mem, &old, &new, as_id, change);
1747 if (r)
1748 goto out_bitmap;
Zhang Xiantao3ad82a72007-11-20 13:11:38 +08001749
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001750 if (old.dirty_bitmap && !new.dirty_bitmap)
1751 kvm_destroy_dirty_bitmap(&old);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001752 return 0;
1753
Sean Christophersonbd0e96f2020-02-18 13:07:21 -08001754out_bitmap:
1755 if (new.dirty_bitmap && !old.dirty_bitmap)
1756 kvm_destroy_dirty_bitmap(&new);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001757 return r;
Izik Eidus210c7c42007-10-24 23:52:57 +02001758}
Sheng Yangf78e0e22007-10-29 09:40:42 +08001759EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1760
1761int kvm_set_memory_region(struct kvm *kvm,
Paolo Bonzini09170a42015-05-18 13:59:39 +02001762 const struct kvm_userspace_memory_region *mem)
Sheng Yangf78e0e22007-10-29 09:40:42 +08001763{
1764 int r;
1765
Marcelo Tosatti79fac952009-12-23 14:35:26 -02001766 mutex_lock(&kvm->slots_lock);
Takuya Yoshikawa47ae31e2013-02-27 19:43:00 +09001767 r = __kvm_set_memory_region(kvm, mem);
Marcelo Tosatti79fac952009-12-23 14:35:26 -02001768 mutex_unlock(&kvm->slots_lock);
Sheng Yangf78e0e22007-10-29 09:40:42 +08001769 return r;
1770}
Izik Eidus210c7c42007-10-24 23:52:57 +02001771EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1772
Stephen Hemminger79408762013-12-29 12:12:29 -08001773static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1774 struct kvm_userspace_memory_region *mem)
Izik Eidus210c7c42007-10-24 23:52:57 +02001775{
Paolo Bonzinif481b062015-05-17 17:30:37 +02001776 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
Izik Eiduse0d62c72007-10-24 23:57:46 +02001777 return -EINVAL;
Paolo Bonzini09170a42015-05-18 13:59:39 +02001778
Takuya Yoshikawa47ae31e2013-02-27 19:43:00 +09001779 return kvm_set_memory_region(kvm, mem);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001780}
1781
Sean Christopherson0dff0842020-02-18 13:07:29 -08001782#ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
Sean Christopherson2a49f612020-02-18 13:07:30 -08001783/**
1784 * kvm_get_dirty_log - get a snapshot of dirty pages
1785 * @kvm: pointer to kvm instance
1786 * @log: slot id and address to which we copy the log
1787 * @is_dirty: set to '1' if any dirty pages were found
1788 * @memslot: set to the associated memslot, always valid on success
1789 */
1790int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1791 int *is_dirty, struct kvm_memory_slot **memslot)
Avi Kivity6aa8b732006-12-10 02:21:36 -08001792{
Paolo Bonzini9f6b8022015-05-17 16:20:07 +02001793 struct kvm_memslots *slots;
Markus Elfring843574a2017-01-22 17:41:07 +01001794 int i, as_id, id;
Takuya Yoshikawa87bf6e72010-04-12 19:35:35 +09001795 unsigned long n;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001796 unsigned long any = 0;
1797
Peter Xub2cc64c2020-09-30 21:22:24 -04001798 /* Dirty ring tracking is exclusive to dirty log tracking */
1799 if (kvm->dirty_ring_size)
1800 return -ENXIO;
1801
Sean Christopherson2a49f612020-02-18 13:07:30 -08001802 *memslot = NULL;
1803 *is_dirty = 0;
1804
Paolo Bonzinif481b062015-05-17 17:30:37 +02001805 as_id = log->slot >> 16;
1806 id = (u16)log->slot;
1807 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
Markus Elfring843574a2017-01-22 17:41:07 +01001808 return -EINVAL;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001809
Paolo Bonzinif481b062015-05-17 17:30:37 +02001810 slots = __kvm_memslots(kvm, as_id);
Sean Christopherson2a49f612020-02-18 13:07:30 -08001811 *memslot = id_to_memslot(slots, id);
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001812 if (!(*memslot) || !(*memslot)->dirty_bitmap)
Markus Elfring843574a2017-01-22 17:41:07 +01001813 return -ENOENT;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001814
Sean Christopherson2a49f612020-02-18 13:07:30 -08001815 kvm_arch_sync_dirty_log(kvm, *memslot);
1816
1817 n = kvm_dirty_bitmap_bytes(*memslot);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001818
Uri Lublincd1a4a92007-02-22 16:43:09 +02001819 for (i = 0; !any && i < n/sizeof(long); ++i)
Sean Christopherson2a49f612020-02-18 13:07:30 -08001820 any = (*memslot)->dirty_bitmap[i];
Avi Kivity6aa8b732006-12-10 02:21:36 -08001821
Sean Christopherson2a49f612020-02-18 13:07:30 -08001822 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
Markus Elfring843574a2017-01-22 17:41:07 +01001823 return -EFAULT;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001824
Zhang Xiantao5bb064d2007-11-18 20:29:43 +08001825 if (any)
1826 *is_dirty = 1;
Markus Elfring843574a2017-01-22 17:41:07 +01001827 return 0;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001828}
Aneesh Kumar K.V2ba9f0d2013-10-07 22:17:59 +05301829EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001830
Sean Christopherson0dff0842020-02-18 13:07:29 -08001831#else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
Mario Smarduchba0513b2015-01-15 15:58:53 -08001832/**
Jiang Biaob8b00222019-04-23 19:40:30 +08001833 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001834 * and reenable dirty page tracking for the corresponding pages.
Mario Smarduchba0513b2015-01-15 15:58:53 -08001835 * @kvm: pointer to kvm instance
1836 * @log: slot id and address to which we copy the log
Mario Smarduchba0513b2015-01-15 15:58:53 -08001837 *
1838 * We need to keep it in mind that VCPU threads can write to the bitmap
1839 * concurrently. So, to avoid losing track of dirty pages we keep the
1840 * following order:
1841 *
1842 * 1. Take a snapshot of the bit and clear it if needed.
1843 * 2. Write protect the corresponding page.
1844 * 3. Copy the snapshot to the userspace.
1845 * 4. Upon return caller flushes TLB's if needed.
1846 *
1847 * Between 2 and 4, the guest may write to the page using the remaining TLB
1848 * entry. This is not a problem because the page is reported dirty using
1849 * the snapshot taken before and step 4 ensures that writes done after
1850 * exiting to userspace will be logged for the next call.
1851 *
1852 */
Sean Christopherson0dff0842020-02-18 13:07:29 -08001853static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
Mario Smarduchba0513b2015-01-15 15:58:53 -08001854{
Paolo Bonzini9f6b8022015-05-17 16:20:07 +02001855 struct kvm_memslots *slots;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001856 struct kvm_memory_slot *memslot;
Markus Elfring58d6db32017-01-22 17:30:16 +01001857 int i, as_id, id;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001858 unsigned long n;
1859 unsigned long *dirty_bitmap;
1860 unsigned long *dirty_bitmap_buffer;
Sean Christopherson0dff0842020-02-18 13:07:29 -08001861 bool flush;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001862
Peter Xub2cc64c2020-09-30 21:22:24 -04001863 /* Dirty ring tracking is exclusive to dirty log tracking */
1864 if (kvm->dirty_ring_size)
1865 return -ENXIO;
1866
Paolo Bonzinif481b062015-05-17 17:30:37 +02001867 as_id = log->slot >> 16;
1868 id = (u16)log->slot;
1869 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
Markus Elfring58d6db32017-01-22 17:30:16 +01001870 return -EINVAL;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001871
Paolo Bonzinif481b062015-05-17 17:30:37 +02001872 slots = __kvm_memslots(kvm, as_id);
1873 memslot = id_to_memslot(slots, id);
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001874 if (!memslot || !memslot->dirty_bitmap)
1875 return -ENOENT;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001876
1877 dirty_bitmap = memslot->dirty_bitmap;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001878
Sean Christopherson0dff0842020-02-18 13:07:29 -08001879 kvm_arch_sync_dirty_log(kvm, memslot);
1880
Mario Smarduchba0513b2015-01-15 15:58:53 -08001881 n = kvm_dirty_bitmap_bytes(memslot);
Sean Christopherson0dff0842020-02-18 13:07:29 -08001882 flush = false;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001883 if (kvm->manual_dirty_log_protect) {
1884 /*
1885 * Unlike kvm_get_dirty_log, we always return false in *flush,
1886 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
1887 * is some code duplication between this function and
1888 * kvm_get_dirty_log, but hopefully all architecture
1889 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
1890 * can be eliminated.
1891 */
1892 dirty_bitmap_buffer = dirty_bitmap;
1893 } else {
1894 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1895 memset(dirty_bitmap_buffer, 0, n);
Mario Smarduchba0513b2015-01-15 15:58:53 -08001896
Ben Gardon531810c2021-02-02 10:57:24 -08001897 KVM_MMU_LOCK(kvm);
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001898 for (i = 0; i < n / sizeof(long); i++) {
1899 unsigned long mask;
1900 gfn_t offset;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001901
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001902 if (!dirty_bitmap[i])
1903 continue;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001904
Sean Christopherson0dff0842020-02-18 13:07:29 -08001905 flush = true;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001906 mask = xchg(&dirty_bitmap[i], 0);
1907 dirty_bitmap_buffer[i] = mask;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001908
Lan Tianyua67794c2019-02-02 17:20:27 +08001909 offset = i * BITS_PER_LONG;
1910 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1911 offset, mask);
Takuya Yoshikawa58d29302015-03-17 16:19:58 +09001912 }
Ben Gardon531810c2021-02-02 10:57:24 -08001913 KVM_MMU_UNLOCK(kvm);
Mario Smarduchba0513b2015-01-15 15:58:53 -08001914 }
1915
Sean Christopherson0dff0842020-02-18 13:07:29 -08001916 if (flush)
1917 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1918
Mario Smarduchba0513b2015-01-15 15:58:53 -08001919 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
Markus Elfring58d6db32017-01-22 17:30:16 +01001920 return -EFAULT;
1921 return 0;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001922}
Sean Christopherson0dff0842020-02-18 13:07:29 -08001923
1924
1925/**
1926 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
1927 * @kvm: kvm instance
1928 * @log: slot id and address to which we copy the log
1929 *
1930 * Steps 1-4 below provide general overview of dirty page logging. See
1931 * kvm_get_dirty_log_protect() function description for additional details.
1932 *
1933 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
1934 * always flush the TLB (step 4) even if previous step failed and the dirty
1935 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
1936 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
1937 * writes will be marked dirty for next log read.
1938 *
1939 * 1. Take a snapshot of the bit and clear it if needed.
1940 * 2. Write protect the corresponding page.
1941 * 3. Copy the snapshot to the userspace.
1942 * 4. Flush TLB's if needed.
1943 */
1944static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1945 struct kvm_dirty_log *log)
1946{
1947 int r;
1948
1949 mutex_lock(&kvm->slots_lock);
1950
1951 r = kvm_get_dirty_log_protect(kvm, log);
1952
1953 mutex_unlock(&kvm->slots_lock);
1954 return r;
1955}
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001956
1957/**
1958 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
1959 * and reenable dirty page tracking for the corresponding pages.
1960 * @kvm: pointer to kvm instance
1961 * @log: slot id and address from which to fetch the bitmap of dirty pages
1962 */
Sean Christopherson0dff0842020-02-18 13:07:29 -08001963static int kvm_clear_dirty_log_protect(struct kvm *kvm,
1964 struct kvm_clear_dirty_log *log)
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001965{
1966 struct kvm_memslots *slots;
1967 struct kvm_memory_slot *memslot;
Tomas Bortoli98938aa2019-01-02 18:29:37 +01001968 int as_id, id;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001969 gfn_t offset;
Tomas Bortoli98938aa2019-01-02 18:29:37 +01001970 unsigned long i, n;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001971 unsigned long *dirty_bitmap;
1972 unsigned long *dirty_bitmap_buffer;
Sean Christopherson0dff0842020-02-18 13:07:29 -08001973 bool flush;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001974
Peter Xub2cc64c2020-09-30 21:22:24 -04001975 /* Dirty ring tracking is exclusive to dirty log tracking */
1976 if (kvm->dirty_ring_size)
1977 return -ENXIO;
1978
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001979 as_id = log->slot >> 16;
1980 id = (u16)log->slot;
1981 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1982 return -EINVAL;
1983
Paolo Bonzini76d58e02019-04-17 15:28:44 +02001984 if (log->first_page & 63)
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001985 return -EINVAL;
1986
1987 slots = __kvm_memslots(kvm, as_id);
1988 memslot = id_to_memslot(slots, id);
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001989 if (!memslot || !memslot->dirty_bitmap)
1990 return -ENOENT;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001991
1992 dirty_bitmap = memslot->dirty_bitmap;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001993
Peter Xu4ddc9202019-05-08 17:15:45 +08001994 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
Tomas Bortoli98938aa2019-01-02 18:29:37 +01001995
1996 if (log->first_page > memslot->npages ||
Paolo Bonzini76d58e02019-04-17 15:28:44 +02001997 log->num_pages > memslot->npages - log->first_page ||
1998 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
1999 return -EINVAL;
Tomas Bortoli98938aa2019-01-02 18:29:37 +01002000
Sean Christopherson0dff0842020-02-18 13:07:29 -08002001 kvm_arch_sync_dirty_log(kvm, memslot);
2002
2003 flush = false;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02002004 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
2005 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
2006 return -EFAULT;
2007
Ben Gardon531810c2021-02-02 10:57:24 -08002008 KVM_MMU_LOCK(kvm);
Peter Xu53eac7a2019-05-08 17:15:46 +08002009 for (offset = log->first_page, i = offset / BITS_PER_LONG,
2010 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02002011 i++, offset += BITS_PER_LONG) {
2012 unsigned long mask = *dirty_bitmap_buffer++;
2013 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
2014 if (!mask)
2015 continue;
2016
2017 mask &= atomic_long_fetch_andnot(mask, p);
2018
2019 /*
2020 * mask contains the bits that really have been cleared. This
2021 * never includes any bits beyond the length of the memslot (if
2022 * the length is not aligned to 64 pages), therefore it is not
2023 * a problem if userspace sets them in log->dirty_bitmap.
2024 */
2025 if (mask) {
Sean Christopherson0dff0842020-02-18 13:07:29 -08002026 flush = true;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02002027 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
2028 offset, mask);
2029 }
2030 }
Ben Gardon531810c2021-02-02 10:57:24 -08002031 KVM_MMU_UNLOCK(kvm);
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02002032
Sean Christopherson0dff0842020-02-18 13:07:29 -08002033 if (flush)
2034 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
2035
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02002036 return 0;
2037}
Sean Christopherson0dff0842020-02-18 13:07:29 -08002038
2039static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
2040 struct kvm_clear_dirty_log *log)
2041{
2042 int r;
2043
2044 mutex_lock(&kvm->slots_lock);
2045
2046 r = kvm_clear_dirty_log_protect(kvm, log);
2047
2048 mutex_unlock(&kvm->slots_lock);
2049 return r;
2050}
2051#endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
Mario Smarduchba0513b2015-01-15 15:58:53 -08002052
Gleb Natapov49c77542010-10-18 15:22:23 +02002053struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
2054{
2055 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
2056}
Avi Kivitya1f4d3952010-06-21 11:44:20 +03002057EXPORT_SYMBOL_GPL(gfn_to_memslot);
Avi Kivity6aa8b732006-12-10 02:21:36 -08002058
Paolo Bonzini8e734852015-05-17 13:58:53 +02002059struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
2060{
David Matlackfe22ed82021-08-04 22:28:40 +00002061 struct kvm_memslots *slots = kvm_vcpu_memslots(vcpu);
2062 struct kvm_memory_slot *slot;
2063 int slot_index;
2064
2065 slot = try_get_memslot(slots, vcpu->last_used_slot, gfn);
2066 if (slot)
2067 return slot;
2068
2069 /*
2070 * Fall back to searching all memslots. We purposely use
2071 * search_memslots() instead of __gfn_to_memslot() to avoid
2072 * thrashing the VM-wide last_used_index in kvm_memslots.
2073 */
2074 slot = search_memslots(slots, gfn, &slot_index);
2075 if (slot) {
2076 vcpu->last_used_slot = slot_index;
2077 return slot;
2078 }
2079
2080 return NULL;
Paolo Bonzini8e734852015-05-17 13:58:53 +02002081}
Paolo Bonzinie72436b2020-04-17 12:21:06 -04002082EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_memslot);
Paolo Bonzini8e734852015-05-17 13:58:53 +02002083
Yaowei Bai33e94152015-11-14 11:21:06 +08002084bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
Izik Eiduse0d62c72007-10-24 23:57:46 +02002085{
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +08002086 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
Izik Eiduse0d62c72007-10-24 23:57:46 +02002087
Paolo Bonzinic36b7152020-04-16 09:48:07 -04002088 return kvm_is_visible_memslot(memslot);
Izik Eiduse0d62c72007-10-24 23:57:46 +02002089}
2090EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
2091
Vitaly Kuznetsov995decb2020-07-08 16:00:23 +02002092bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
2093{
2094 struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2095
2096 return kvm_is_visible_memslot(memslot);
2097}
2098EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn);
2099
Sean Christophersonf9b84e12020-01-08 12:24:37 -08002100unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
Joerg Roedel8f0b1ab2010-01-28 12:37:56 +01002101{
2102 struct vm_area_struct *vma;
2103 unsigned long addr, size;
2104
2105 size = PAGE_SIZE;
2106
Sean Christopherson42cde482020-01-08 12:24:38 -08002107 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
Joerg Roedel8f0b1ab2010-01-28 12:37:56 +01002108 if (kvm_is_error_hva(addr))
2109 return PAGE_SIZE;
2110
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07002111 mmap_read_lock(current->mm);
Joerg Roedel8f0b1ab2010-01-28 12:37:56 +01002112 vma = find_vma(current->mm, addr);
2113 if (!vma)
2114 goto out;
2115
2116 size = vma_kernel_pagesize(vma);
2117
2118out:
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07002119 mmap_read_unlock(current->mm);
Joerg Roedel8f0b1ab2010-01-28 12:37:56 +01002120
2121 return size;
2122}
2123
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08002124static bool memslot_is_readonly(struct kvm_memory_slot *slot)
2125{
2126 return slot->flags & KVM_MEM_READONLY;
2127}
2128
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08002129static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
2130 gfn_t *nr_pages, bool write)
Izik Eidus539cb662007-11-11 22:05:04 +02002131{
Marcelo Tosattibc6678a2009-12-23 14:35:21 -02002132 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
Xiao Guangrongca3a4902012-08-21 11:01:50 +08002133 return KVM_HVA_ERR_BAD;
Xiao Guangrong48987782010-08-22 19:11:43 +08002134
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08002135 if (memslot_is_readonly(slot) && write)
2136 return KVM_HVA_ERR_RO_BAD;
Xiao Guangrong48987782010-08-22 19:11:43 +08002137
2138 if (nr_pages)
2139 *nr_pages = slot->npages - (gfn - slot->base_gfn);
2140
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08002141 return __gfn_to_hva_memslot(slot, gfn);
Izik Eidus539cb662007-11-11 22:05:04 +02002142}
Xiao Guangrong48987782010-08-22 19:11:43 +08002143
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08002144static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
2145 gfn_t *nr_pages)
2146{
2147 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
2148}
2149
2150unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
Stephen Hemminger79408762013-12-29 12:12:29 -08002151 gfn_t gfn)
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08002152{
2153 return gfn_to_hva_many(slot, gfn, NULL);
2154}
2155EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
2156
Xiao Guangrong48987782010-08-22 19:11:43 +08002157unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
2158{
Gleb Natapov49c77542010-10-18 15:22:23 +02002159 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
Xiao Guangrong48987782010-08-22 19:11:43 +08002160}
Sheng Yang0d150292008-04-25 21:44:50 +08002161EXPORT_SYMBOL_GPL(gfn_to_hva);
Izik Eidus539cb662007-11-11 22:05:04 +02002162
Paolo Bonzini8e734852015-05-17 13:58:53 +02002163unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
2164{
2165 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
2166}
2167EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
2168
Xiao Guangrong86ab8cf2012-08-21 10:59:53 +08002169/*
Wei Yang970c0d42018-10-09 10:41:15 +08002170 * Return the hva of a @gfn and the R/W attribute if possible.
2171 *
2172 * @slot: the kvm_memory_slot which contains @gfn
2173 * @gfn: the gfn to be translated
2174 * @writable: used to return the read/write attribute of the @slot if the hva
2175 * is valid and @writable is not NULL
Xiao Guangrong86ab8cf2012-08-21 10:59:53 +08002176 */
Christoffer Dall64d83122014-08-19 12:15:00 +02002177unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
2178 gfn_t gfn, bool *writable)
Gleb Natapov80300892010-10-19 18:13:41 +02002179{
Gleb Natapova2ac07f2013-10-01 19:58:36 +03002180 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
2181
2182 if (!kvm_is_error_hva(hva) && writable)
Paolo Bonziniba6a3542013-09-09 13:52:33 +02002183 *writable = !memslot_is_readonly(slot);
2184
Gleb Natapova2ac07f2013-10-01 19:58:36 +03002185 return hva;
Xiao Guangrong86ab8cf2012-08-21 10:59:53 +08002186}
2187
Christoffer Dall64d83122014-08-19 12:15:00 +02002188unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
2189{
2190 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2191
2192 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2193}
2194
Paolo Bonzini8e734852015-05-17 13:58:53 +02002195unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
2196{
2197 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2198
2199 return gfn_to_hva_memslot_prot(slot, gfn, writable);
2200}
2201
Huang Yingfafc3db2011-01-30 11:15:49 +08002202static inline int check_user_page_hwpoison(unsigned long addr)
2203{
Lorenzo Stoakes0d731752016-10-24 10:57:25 +01002204 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
Huang Yingfafc3db2011-01-30 11:15:49 +08002205
Lorenzo Stoakes0d731752016-10-24 10:57:25 +01002206 rc = get_user_pages(addr, 1, flags, NULL, NULL);
Huang Yingfafc3db2011-01-30 11:15:49 +08002207 return rc == -EHWPOISON;
2208}
2209
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002210/*
Paolo Bonzinib9b33da2018-07-27 17:44:41 +02002211 * The fast path to get the writable pfn which will be stored in @pfn,
2212 * true indicates success, otherwise false is returned. It's also the
Miaohe Lin311497e2019-12-11 14:26:25 +08002213 * only part that runs if we can in atomic context.
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002214 */
Paolo Bonzinib9b33da2018-07-27 17:44:41 +02002215static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
2216 bool *writable, kvm_pfn_t *pfn)
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002217{
2218 struct page *page[1];
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002219
Xiao Guangrong12ce13f2012-08-21 11:00:49 +08002220 /*
2221 * Fast pin a writable pfn only if it is a write fault request
2222 * or the caller allows to map a writable pfn for a read fault
2223 * request.
2224 */
2225 if (!(write_fault || writable))
2226 return false;
2227
Souptick Joarderdadbb612020-06-07 21:40:55 -07002228 if (get_user_page_fast_only(addr, FOLL_WRITE, page)) {
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002229 *pfn = page_to_pfn(page[0]);
2230
2231 if (writable)
2232 *writable = true;
2233 return true;
2234 }
2235
2236 return false;
2237}
2238
2239/*
2240 * The slow path to get the pfn of the specified host virtual address,
2241 * 1 indicates success, -errno is returned if error is detected.
2242 */
2243static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
Dan Williamsba049e92016-01-15 16:56:11 -08002244 bool *writable, kvm_pfn_t *pfn)
Avi Kivity954bbbc2007-03-30 14:02:32 +03002245{
Al Viroce530532017-11-19 17:47:33 -05002246 unsigned int flags = FOLL_HWPOISON;
2247 struct page *page;
Gleb Natapovaf585b92010-10-14 11:22:46 +02002248 int npages = 0;
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002249
2250 might_sleep();
2251
2252 if (writable)
2253 *writable = write_fault;
2254
Al Viroce530532017-11-19 17:47:33 -05002255 if (write_fault)
2256 flags |= FOLL_WRITE;
2257 if (async)
2258 flags |= FOLL_NOWAIT;
Lorenzo Stoakesd4944b02016-10-13 01:20:12 +01002259
Al Viroce530532017-11-19 17:47:33 -05002260 npages = get_user_pages_unlocked(addr, 1, &page, flags);
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002261 if (npages != 1)
2262 return npages;
2263
2264 /* map read fault as writable if possible */
Xiao Guangrong12ce13f2012-08-21 11:00:49 +08002265 if (unlikely(!write_fault) && writable) {
Al Viroce530532017-11-19 17:47:33 -05002266 struct page *wpage;
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002267
Souptick Joarderdadbb612020-06-07 21:40:55 -07002268 if (get_user_page_fast_only(addr, FOLL_WRITE, &wpage)) {
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002269 *writable = true;
Al Viroce530532017-11-19 17:47:33 -05002270 put_page(page);
2271 page = wpage;
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002272 }
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002273 }
Al Viroce530532017-11-19 17:47:33 -05002274 *pfn = page_to_pfn(page);
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002275 return npages;
2276}
2277
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08002278static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
2279{
2280 if (unlikely(!(vma->vm_flags & VM_READ)))
2281 return false;
2282
2283 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
2284 return false;
2285
2286 return true;
2287}
2288
Nicholas Pigginf8be1562021-06-24 08:29:04 -04002289static int kvm_try_get_pfn(kvm_pfn_t pfn)
2290{
2291 if (kvm_is_reserved_pfn(pfn))
2292 return 1;
2293 return get_page_unless_zero(pfn_to_page(pfn));
2294}
2295
Paolo Bonzini92176a82016-06-07 16:22:47 +02002296static int hva_to_pfn_remapped(struct vm_area_struct *vma,
2297 unsigned long addr, bool *async,
KarimAllah Ahmeda340b3e2018-01-17 19:18:56 +01002298 bool write_fault, bool *writable,
2299 kvm_pfn_t *p_pfn)
Paolo Bonzini92176a82016-06-07 16:22:47 +02002300{
Sean Christophersona9545772021-02-08 12:19:40 -08002301 kvm_pfn_t pfn;
Paolo Bonzinibd2fae82021-02-01 05:12:11 -05002302 pte_t *ptep;
2303 spinlock_t *ptl;
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02002304 int r;
2305
Paolo Bonzini9fd6dad2021-02-05 05:07:11 -05002306 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02002307 if (r) {
2308 /*
2309 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
2310 * not call the fault handler, so do it here.
2311 */
2312 bool unlocked = false;
Peter Xu64019a22020-08-11 18:39:01 -07002313 r = fixup_user_fault(current->mm, addr,
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02002314 (write_fault ? FAULT_FLAG_WRITE : 0),
2315 &unlocked);
Paolo Bonzinia8387d02020-05-29 05:42:55 -04002316 if (unlocked)
2317 return -EAGAIN;
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02002318 if (r)
2319 return r;
2320
Paolo Bonzini9fd6dad2021-02-05 05:07:11 -05002321 r = follow_pte(vma->vm_mm, addr, &ptep, &ptl);
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02002322 if (r)
2323 return r;
Paolo Bonzinibd2fae82021-02-01 05:12:11 -05002324 }
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02002325
Paolo Bonzinibd2fae82021-02-01 05:12:11 -05002326 if (write_fault && !pte_write(*ptep)) {
2327 pfn = KVM_PFN_ERR_RO_FAULT;
2328 goto out;
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02002329 }
2330
KarimAllah Ahmeda340b3e2018-01-17 19:18:56 +01002331 if (writable)
Paolo Bonzinibd2fae82021-02-01 05:12:11 -05002332 *writable = pte_write(*ptep);
2333 pfn = pte_pfn(*ptep);
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02002334
2335 /*
2336 * Get a reference here because callers of *hva_to_pfn* and
2337 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
2338 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
2339 * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
2340 * simply do nothing for reserved pfns.
2341 *
2342 * Whoever called remap_pfn_range is also going to call e.g.
2343 * unmap_mapping_range before the underlying pages are freed,
2344 * causing a call to our MMU notifier.
Nicholas Pigginf8be1562021-06-24 08:29:04 -04002345 *
2346 * Certain IO or PFNMAP mappings can be backed with valid
2347 * struct pages, but be allocated without refcounting e.g.,
2348 * tail pages of non-compound higher order allocations, which
2349 * would then underflow the refcount when the caller does the
2350 * required put_page. Don't allow those pages here.
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02002351 */
Nicholas Pigginf8be1562021-06-24 08:29:04 -04002352 if (!kvm_try_get_pfn(pfn))
2353 r = -EFAULT;
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02002354
Paolo Bonzinibd2fae82021-02-01 05:12:11 -05002355out:
2356 pte_unmap_unlock(ptep, ptl);
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02002357 *p_pfn = pfn;
Nicholas Pigginf8be1562021-06-24 08:29:04 -04002358
2359 return r;
Paolo Bonzini92176a82016-06-07 16:22:47 +02002360}
2361
Xiao Guangrong12ce13f2012-08-21 11:00:49 +08002362/*
2363 * Pin guest page in memory and return its pfn.
2364 * @addr: host virtual address which maps memory to the guest
2365 * @atomic: whether this function can sleep
2366 * @async: whether this function need to wait IO complete if the
2367 * host page is not in the memory
2368 * @write_fault: whether we should get a writable host page
2369 * @writable: whether it allows to map a writable host page for !@write_fault
2370 *
2371 * The function will map a writable host page for these two cases:
2372 * 1): @write_fault = true
2373 * 2): @write_fault = false && @writable, @writable will tell the caller
2374 * whether the mapping is writable.
2375 */
Dan Williamsba049e92016-01-15 16:56:11 -08002376static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002377 bool write_fault, bool *writable)
2378{
2379 struct vm_area_struct *vma;
Dan Williamsba049e92016-01-15 16:56:11 -08002380 kvm_pfn_t pfn = 0;
Paolo Bonzini92176a82016-06-07 16:22:47 +02002381 int npages, r;
Avi Kivity954bbbc2007-03-30 14:02:32 +03002382
Gleb Natapovaf585b92010-10-14 11:22:46 +02002383 /* we can do it either atomically or asynchronously, not both */
2384 BUG_ON(atomic && async);
2385
Paolo Bonzinib9b33da2018-07-27 17:44:41 +02002386 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002387 return pfn;
Marcelo Tosatti612819c2010-10-22 14:18:18 -02002388
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002389 if (atomic)
2390 return KVM_PFN_ERR_FAULT;
Marcelo Tosatti612819c2010-10-22 14:18:18 -02002391
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002392 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
2393 if (npages == 1)
2394 return pfn;
Gleb Natapovaf585b92010-10-14 11:22:46 +02002395
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07002396 mmap_read_lock(current->mm);
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002397 if (npages == -EHWPOISON ||
2398 (!async && check_user_page_hwpoison(addr))) {
2399 pfn = KVM_PFN_ERR_HWPOISON;
2400 goto exit;
Xiao Guangrong887c08a2010-08-22 19:10:28 +08002401 }
Izik Eidus539cb662007-11-11 22:05:04 +02002402
Paolo Bonzinia8387d02020-05-29 05:42:55 -04002403retry:
Liam Howlettfc98c032021-06-28 19:39:17 -07002404 vma = vma_lookup(current->mm, addr);
Anthony Liguori8d4e1282007-10-18 09:59:34 -05002405
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002406 if (vma == NULL)
2407 pfn = KVM_PFN_ERR_FAULT;
Paolo Bonzini92176a82016-06-07 16:22:47 +02002408 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
KarimAllah Ahmeda340b3e2018-01-17 19:18:56 +01002409 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
Paolo Bonzinia8387d02020-05-29 05:42:55 -04002410 if (r == -EAGAIN)
2411 goto retry;
Paolo Bonzini92176a82016-06-07 16:22:47 +02002412 if (r < 0)
2413 pfn = KVM_PFN_ERR_FAULT;
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002414 } else {
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08002415 if (async && vma_is_valid(vma, write_fault))
Xiao Guangrong2fc84312012-08-21 11:00:22 +08002416 *async = true;
2417 pfn = KVM_PFN_ERR_FAULT;
2418 }
2419exit:
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07002420 mmap_read_unlock(current->mm);
Anthony Liguori2e2e3732008-04-30 15:37:07 -05002421 return pfn;
Anthony Liguori35149e22008-04-02 14:46:56 -05002422}
2423
Dan Williamsba049e92016-01-15 16:56:11 -08002424kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
2425 bool atomic, bool *async, bool write_fault,
David Stevens4a42d842021-02-22 11:45:22 +09002426 bool *writable, hva_t *hva)
Xiao Guangrong887c08a2010-08-22 19:10:28 +08002427{
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08002428 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
2429
David Stevens4a42d842021-02-22 11:45:22 +09002430 if (hva)
2431 *hva = addr;
2432
Paolo Bonzinib2740d32016-02-23 15:36:01 +01002433 if (addr == KVM_HVA_ERR_RO_BAD) {
2434 if (writable)
2435 *writable = false;
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08002436 return KVM_PFN_ERR_RO_FAULT;
Paolo Bonzinib2740d32016-02-23 15:36:01 +01002437 }
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08002438
Paolo Bonzinib2740d32016-02-23 15:36:01 +01002439 if (kvm_is_error_hva(addr)) {
2440 if (writable)
2441 *writable = false;
Xiao Guangrong81c52c52012-10-16 20:10:59 +08002442 return KVM_PFN_NOSLOT;
Paolo Bonzinib2740d32016-02-23 15:36:01 +01002443 }
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08002444
2445 /* Do not map writable pfn in the readonly memslot. */
2446 if (writable && memslot_is_readonly(slot)) {
2447 *writable = false;
2448 writable = NULL;
2449 }
2450
2451 return hva_to_pfn(addr, atomic, async, write_fault,
2452 writable);
Xiao Guangrong887c08a2010-08-22 19:10:28 +08002453}
Paolo Bonzini35204692015-04-02 11:20:48 +02002454EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
Xiao Guangrong887c08a2010-08-22 19:10:28 +08002455
Dan Williamsba049e92016-01-15 16:56:11 -08002456kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
Marcelo Tosatti612819c2010-10-22 14:18:18 -02002457 bool *writable)
2458{
Paolo Bonzinie37afc62015-05-19 16:09:04 +02002459 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
David Stevens4a42d842021-02-22 11:45:22 +09002460 write_fault, writable, NULL);
Marcelo Tosatti612819c2010-10-22 14:18:18 -02002461}
2462EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
2463
Dan Williamsba049e92016-01-15 16:56:11 -08002464kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
Marcelo Tosatti506f0d62009-12-23 14:35:19 -02002465{
David Stevens4a42d842021-02-22 11:45:22 +09002466 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL, NULL);
Marcelo Tosatti506f0d62009-12-23 14:35:19 -02002467}
Paolo Bonzinie37afc62015-05-19 16:09:04 +02002468EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
Marcelo Tosatti506f0d62009-12-23 14:35:19 -02002469
Dan Williamsba049e92016-01-15 16:56:11 -08002470kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
Xiao Guangrong037d92d2012-08-21 10:59:12 +08002471{
David Stevens4a42d842021-02-22 11:45:22 +09002472 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL, NULL);
Xiao Guangrong037d92d2012-08-21 10:59:12 +08002473}
2474EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
2475
Dan Williamsba049e92016-01-15 16:56:11 -08002476kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
Paolo Bonzini8e734852015-05-17 13:58:53 +02002477{
2478 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2479}
2480EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
2481
Dan Williamsba049e92016-01-15 16:56:11 -08002482kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
Paolo Bonzinie37afc62015-05-19 16:09:04 +02002483{
2484 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
2485}
2486EXPORT_SYMBOL_GPL(gfn_to_pfn);
2487
Dan Williamsba049e92016-01-15 16:56:11 -08002488kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
Paolo Bonzini8e734852015-05-17 13:58:53 +02002489{
2490 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2491}
2492EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
2493
Paolo Bonzinid9ef13c2015-05-19 16:01:50 +02002494int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2495 struct page **pages, int nr_pages)
Xiao Guangrong48987782010-08-22 19:11:43 +08002496{
2497 unsigned long addr;
Arnd Bergmann076b9252017-08-10 14:14:39 +02002498 gfn_t entry = 0;
Xiao Guangrong48987782010-08-22 19:11:43 +08002499
Paolo Bonzinid9ef13c2015-05-19 16:01:50 +02002500 addr = gfn_to_hva_many(slot, gfn, &entry);
Xiao Guangrong48987782010-08-22 19:11:43 +08002501 if (kvm_is_error_hva(addr))
2502 return -1;
2503
2504 if (entry < nr_pages)
2505 return 0;
2506
Souptick Joarderdadbb612020-06-07 21:40:55 -07002507 return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages);
Xiao Guangrong48987782010-08-22 19:11:43 +08002508}
2509EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
2510
Dan Williamsba049e92016-01-15 16:56:11 -08002511static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
Xiao Guangronga2766322012-07-26 11:58:59 +08002512{
Xiao Guangrong81c52c52012-10-16 20:10:59 +08002513 if (is_error_noslot_pfn(pfn))
Xiao Guangrong6cede2e2012-08-03 15:41:22 +08002514 return KVM_ERR_PTR_BAD_PAGE;
Xiao Guangronga2766322012-07-26 11:58:59 +08002515
Ard Biesheuvelbf4bea82014-11-10 08:33:56 +00002516 if (kvm_is_reserved_pfn(pfn)) {
Xiao Guangrongcb9aaa32012-08-03 15:42:10 +08002517 WARN_ON(1);
2518 return KVM_ERR_PTR_BAD_PAGE;
2519 }
2520
Xiao Guangronga2766322012-07-26 11:58:59 +08002521 return pfn_to_page(pfn);
2522}
2523
Anthony Liguori35149e22008-04-02 14:46:56 -05002524struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
2525{
Dan Williamsba049e92016-01-15 16:56:11 -08002526 kvm_pfn_t pfn;
Anthony Liguori2e2e3732008-04-30 15:37:07 -05002527
2528 pfn = gfn_to_pfn(kvm, gfn);
Anthony Liguori2e2e3732008-04-30 15:37:07 -05002529
Xiao Guangronga2766322012-07-26 11:58:59 +08002530 return kvm_pfn_to_page(pfn);
Avi Kivity954bbbc2007-03-30 14:02:32 +03002531}
2532EXPORT_SYMBOL_GPL(gfn_to_page);
2533
Boris Ostrovsky91724812019-12-05 01:30:51 +00002534void kvm_release_pfn(kvm_pfn_t pfn, bool dirty, struct gfn_to_pfn_cache *cache)
2535{
2536 if (pfn == 0)
2537 return;
2538
2539 if (cache)
2540 cache->pfn = cache->gfn = 0;
2541
2542 if (dirty)
2543 kvm_release_pfn_dirty(pfn);
2544 else
2545 kvm_release_pfn_clean(pfn);
2546}
2547
2548static void kvm_cache_gfn_to_pfn(struct kvm_memory_slot *slot, gfn_t gfn,
2549 struct gfn_to_pfn_cache *cache, u64 gen)
2550{
2551 kvm_release_pfn(cache->pfn, cache->dirty, cache);
2552
2553 cache->pfn = gfn_to_pfn_memslot(slot, gfn);
2554 cache->gfn = gfn;
2555 cache->dirty = false;
2556 cache->generation = gen;
2557}
2558
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002559static int __kvm_map_gfn(struct kvm_memslots *slots, gfn_t gfn,
Boris Ostrovsky91724812019-12-05 01:30:51 +00002560 struct kvm_host_map *map,
2561 struct gfn_to_pfn_cache *cache,
2562 bool atomic)
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002563{
2564 kvm_pfn_t pfn;
2565 void *hva = NULL;
2566 struct page *page = KVM_UNMAPPED_PAGE;
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002567 struct kvm_memory_slot *slot = __gfn_to_memslot(slots, gfn);
Boris Ostrovsky91724812019-12-05 01:30:51 +00002568 u64 gen = slots->generation;
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002569
2570 if (!map)
2571 return -EINVAL;
2572
Boris Ostrovsky91724812019-12-05 01:30:51 +00002573 if (cache) {
2574 if (!cache->pfn || cache->gfn != gfn ||
2575 cache->generation != gen) {
2576 if (atomic)
2577 return -EAGAIN;
2578 kvm_cache_gfn_to_pfn(slot, gfn, cache, gen);
2579 }
2580 pfn = cache->pfn;
2581 } else {
2582 if (atomic)
2583 return -EAGAIN;
2584 pfn = gfn_to_pfn_memslot(slot, gfn);
2585 }
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002586 if (is_error_noslot_pfn(pfn))
2587 return -EINVAL;
2588
2589 if (pfn_valid(pfn)) {
2590 page = pfn_to_page(pfn);
Boris Ostrovsky91724812019-12-05 01:30:51 +00002591 if (atomic)
2592 hva = kmap_atomic(page);
2593 else
2594 hva = kmap(page);
Paolo Bonzinid30b2142019-05-20 12:06:36 +02002595#ifdef CONFIG_HAS_IOMEM
Boris Ostrovsky91724812019-12-05 01:30:51 +00002596 } else if (!atomic) {
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002597 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
Boris Ostrovsky91724812019-12-05 01:30:51 +00002598 } else {
2599 return -EINVAL;
Paolo Bonzinid30b2142019-05-20 12:06:36 +02002600#endif
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002601 }
2602
2603 if (!hva)
2604 return -EFAULT;
2605
2606 map->page = page;
2607 map->hva = hva;
2608 map->pfn = pfn;
2609 map->gfn = gfn;
2610
2611 return 0;
2612}
2613
Boris Ostrovsky91724812019-12-05 01:30:51 +00002614int kvm_map_gfn(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map,
2615 struct gfn_to_pfn_cache *cache, bool atomic)
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002616{
Boris Ostrovsky91724812019-12-05 01:30:51 +00002617 return __kvm_map_gfn(kvm_memslots(vcpu->kvm), gfn, map,
2618 cache, atomic);
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002619}
2620EXPORT_SYMBOL_GPL(kvm_map_gfn);
2621
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002622int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
2623{
Boris Ostrovsky91724812019-12-05 01:30:51 +00002624 return __kvm_map_gfn(kvm_vcpu_memslots(vcpu), gfn, map,
2625 NULL, false);
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002626}
2627EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2628
Peter Xu28bd7262020-09-30 21:20:34 -04002629static void __kvm_unmap_gfn(struct kvm *kvm,
2630 struct kvm_memory_slot *memslot,
Boris Ostrovsky91724812019-12-05 01:30:51 +00002631 struct kvm_host_map *map,
2632 struct gfn_to_pfn_cache *cache,
2633 bool dirty, bool atomic)
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002634{
2635 if (!map)
2636 return;
2637
2638 if (!map->hva)
2639 return;
2640
Boris Ostrovsky91724812019-12-05 01:30:51 +00002641 if (map->page != KVM_UNMAPPED_PAGE) {
2642 if (atomic)
2643 kunmap_atomic(map->hva);
2644 else
2645 kunmap(map->page);
2646 }
Christian Borntraegereb1f2f32019-05-27 10:28:25 +02002647#ifdef CONFIG_HAS_IOMEM
Boris Ostrovsky91724812019-12-05 01:30:51 +00002648 else if (!atomic)
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002649 memunmap(map->hva);
Boris Ostrovsky91724812019-12-05 01:30:51 +00002650 else
2651 WARN_ONCE(1, "Unexpected unmapping in atomic context");
Christian Borntraegereb1f2f32019-05-27 10:28:25 +02002652#endif
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002653
Boris Ostrovsky91724812019-12-05 01:30:51 +00002654 if (dirty)
Peter Xu28bd7262020-09-30 21:20:34 -04002655 mark_page_dirty_in_slot(kvm, memslot, map->gfn);
Boris Ostrovsky91724812019-12-05 01:30:51 +00002656
2657 if (cache)
2658 cache->dirty |= dirty;
2659 else
2660 kvm_release_pfn(map->pfn, dirty, NULL);
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002661
2662 map->hva = NULL;
2663 map->page = NULL;
2664}
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002665
Boris Ostrovsky91724812019-12-05 01:30:51 +00002666int kvm_unmap_gfn(struct kvm_vcpu *vcpu, struct kvm_host_map *map,
2667 struct gfn_to_pfn_cache *cache, bool dirty, bool atomic)
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002668{
Peter Xu28bd7262020-09-30 21:20:34 -04002669 __kvm_unmap_gfn(vcpu->kvm, gfn_to_memslot(vcpu->kvm, map->gfn), map,
Boris Ostrovsky91724812019-12-05 01:30:51 +00002670 cache, dirty, atomic);
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002671 return 0;
2672}
2673EXPORT_SYMBOL_GPL(kvm_unmap_gfn);
2674
2675void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
2676{
Peter Xu28bd7262020-09-30 21:20:34 -04002677 __kvm_unmap_gfn(vcpu->kvm, kvm_vcpu_gfn_to_memslot(vcpu, map->gfn),
2678 map, NULL, dirty, false);
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002679}
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002680EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2681
Paolo Bonzini8e734852015-05-17 13:58:53 +02002682struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2683{
Dan Williamsba049e92016-01-15 16:56:11 -08002684 kvm_pfn_t pfn;
Paolo Bonzini8e734852015-05-17 13:58:53 +02002685
2686 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2687
2688 return kvm_pfn_to_page(pfn);
2689}
2690EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2691
Izik Eidusb4231d62007-11-20 11:49:33 +02002692void kvm_release_page_clean(struct page *page)
2693{
Xiao Guangrong32cad842012-08-03 15:42:52 +08002694 WARN_ON(is_error_page(page));
2695
Anthony Liguori35149e22008-04-02 14:46:56 -05002696 kvm_release_pfn_clean(page_to_pfn(page));
Izik Eidusb4231d62007-11-20 11:49:33 +02002697}
2698EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2699
Dan Williamsba049e92016-01-15 16:56:11 -08002700void kvm_release_pfn_clean(kvm_pfn_t pfn)
Anthony Liguori35149e22008-04-02 14:46:56 -05002701{
Ard Biesheuvelbf4bea82014-11-10 08:33:56 +00002702 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
Anthony Liguori2e2e3732008-04-30 15:37:07 -05002703 put_page(pfn_to_page(pfn));
Anthony Liguori35149e22008-04-02 14:46:56 -05002704}
2705EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2706
Izik Eidusb4231d62007-11-20 11:49:33 +02002707void kvm_release_page_dirty(struct page *page)
Izik Eidus8a7ae052007-10-18 11:09:33 +02002708{
Xiao Guangronga2766322012-07-26 11:58:59 +08002709 WARN_ON(is_error_page(page));
2710
Anthony Liguori35149e22008-04-02 14:46:56 -05002711 kvm_release_pfn_dirty(page_to_pfn(page));
Izik Eidus8a7ae052007-10-18 11:09:33 +02002712}
Izik Eidusb4231d62007-11-20 11:49:33 +02002713EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
Izik Eidus8a7ae052007-10-18 11:09:33 +02002714
David Hildenbrandf7a65092017-09-01 17:11:43 +02002715void kvm_release_pfn_dirty(kvm_pfn_t pfn)
Anthony Liguori35149e22008-04-02 14:46:56 -05002716{
2717 kvm_set_pfn_dirty(pfn);
2718 kvm_release_pfn_clean(pfn);
2719}
David Hildenbrandf7a65092017-09-01 17:11:43 +02002720EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
Anthony Liguori35149e22008-04-02 14:46:56 -05002721
Dan Williamsba049e92016-01-15 16:56:11 -08002722void kvm_set_pfn_dirty(kvm_pfn_t pfn)
Anthony Liguori35149e22008-04-02 14:46:56 -05002723{
Miaohe Lind29c03a2019-12-05 11:05:05 +08002724 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2725 SetPageDirty(pfn_to_page(pfn));
Anthony Liguori35149e22008-04-02 14:46:56 -05002726}
2727EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2728
Dan Williamsba049e92016-01-15 16:56:11 -08002729void kvm_set_pfn_accessed(kvm_pfn_t pfn)
Anthony Liguori35149e22008-04-02 14:46:56 -05002730{
Sean Christophersona78986a2019-11-11 14:12:27 -08002731 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
Anthony Liguori2e2e3732008-04-30 15:37:07 -05002732 mark_page_accessed(pfn_to_page(pfn));
Anthony Liguori35149e22008-04-02 14:46:56 -05002733}
2734EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2735
Dan Williamsba049e92016-01-15 16:56:11 -08002736void kvm_get_pfn(kvm_pfn_t pfn)
Anthony Liguori35149e22008-04-02 14:46:56 -05002737{
Ard Biesheuvelbf4bea82014-11-10 08:33:56 +00002738 if (!kvm_is_reserved_pfn(pfn))
Anthony Liguori2e2e3732008-04-30 15:37:07 -05002739 get_page(pfn_to_page(pfn));
Anthony Liguori35149e22008-04-02 14:46:56 -05002740}
2741EXPORT_SYMBOL_GPL(kvm_get_pfn);
2742
Izik Eidus195aefd2007-10-01 22:14:18 +02002743static int next_segment(unsigned long len, int offset)
2744{
2745 if (len > PAGE_SIZE - offset)
2746 return PAGE_SIZE - offset;
2747 else
2748 return len;
2749}
2750
Paolo Bonzini8e734852015-05-17 13:58:53 +02002751static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2752 void *data, int offset, int len)
Izik Eidus195aefd2007-10-01 22:14:18 +02002753{
Izik Eiduse0506bc2007-11-11 22:10:22 +02002754 int r;
2755 unsigned long addr;
Izik Eidus195aefd2007-10-01 22:14:18 +02002756
Paolo Bonzini8e734852015-05-17 13:58:53 +02002757 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
Izik Eiduse0506bc2007-11-11 22:10:22 +02002758 if (kvm_is_error_hva(addr))
Izik Eidus195aefd2007-10-01 22:14:18 +02002759 return -EFAULT;
Paolo Bonzini3180a7f2015-04-02 14:08:20 +02002760 r = __copy_from_user(data, (void __user *)addr + offset, len);
Izik Eiduse0506bc2007-11-11 22:10:22 +02002761 if (r)
2762 return -EFAULT;
Izik Eidus195aefd2007-10-01 22:14:18 +02002763 return 0;
2764}
Paolo Bonzini8e734852015-05-17 13:58:53 +02002765
2766int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2767 int len)
2768{
2769 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2770
2771 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2772}
Izik Eidus195aefd2007-10-01 22:14:18 +02002773EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2774
Paolo Bonzini8e734852015-05-17 13:58:53 +02002775int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2776 int offset, int len)
2777{
2778 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2779
2780 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2781}
2782EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2783
Izik Eidus195aefd2007-10-01 22:14:18 +02002784int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2785{
2786 gfn_t gfn = gpa >> PAGE_SHIFT;
2787 int seg;
2788 int offset = offset_in_page(gpa);
2789 int ret;
2790
2791 while ((seg = next_segment(len, offset)) != 0) {
2792 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2793 if (ret < 0)
2794 return ret;
2795 offset = 0;
2796 len -= seg;
2797 data += seg;
2798 ++gfn;
2799 }
2800 return 0;
2801}
2802EXPORT_SYMBOL_GPL(kvm_read_guest);
2803
Paolo Bonzini8e734852015-05-17 13:58:53 +02002804int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2805{
2806 gfn_t gfn = gpa >> PAGE_SHIFT;
2807 int seg;
2808 int offset = offset_in_page(gpa);
2809 int ret;
2810
2811 while ((seg = next_segment(len, offset)) != 0) {
2812 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2813 if (ret < 0)
2814 return ret;
2815 offset = 0;
2816 len -= seg;
2817 data += seg;
2818 ++gfn;
2819 }
2820 return 0;
2821}
2822EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2823
2824static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2825 void *data, int offset, unsigned long len)
Marcelo Tosatti7ec54582007-12-20 19:18:23 -05002826{
2827 int r;
2828 unsigned long addr;
Marcelo Tosatti7ec54582007-12-20 19:18:23 -05002829
Paolo Bonzini8e734852015-05-17 13:58:53 +02002830 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
Marcelo Tosatti7ec54582007-12-20 19:18:23 -05002831 if (kvm_is_error_hva(addr))
2832 return -EFAULT;
Andrea Arcangeli0aac03f2008-01-30 19:57:35 +01002833 pagefault_disable();
Paolo Bonzini3180a7f2015-04-02 14:08:20 +02002834 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
Andrea Arcangeli0aac03f2008-01-30 19:57:35 +01002835 pagefault_enable();
Marcelo Tosatti7ec54582007-12-20 19:18:23 -05002836 if (r)
2837 return -EFAULT;
2838 return 0;
2839}
Marcelo Tosatti7ec54582007-12-20 19:18:23 -05002840
Paolo Bonzini8e734852015-05-17 13:58:53 +02002841int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2842 void *data, unsigned long len)
2843{
2844 gfn_t gfn = gpa >> PAGE_SHIFT;
2845 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2846 int offset = offset_in_page(gpa);
2847
2848 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2849}
2850EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2851
Peter Xu28bd7262020-09-30 21:20:34 -04002852static int __kvm_write_guest_page(struct kvm *kvm,
2853 struct kvm_memory_slot *memslot, gfn_t gfn,
Paolo Bonzini8e734852015-05-17 13:58:53 +02002854 const void *data, int offset, int len)
Izik Eidus195aefd2007-10-01 22:14:18 +02002855{
Izik Eiduse0506bc2007-11-11 22:10:22 +02002856 int r;
2857 unsigned long addr;
Izik Eidus195aefd2007-10-01 22:14:18 +02002858
Radim Krčmář251eb842015-04-10 21:47:27 +02002859 addr = gfn_to_hva_memslot(memslot, gfn);
Izik Eiduse0506bc2007-11-11 22:10:22 +02002860 if (kvm_is_error_hva(addr))
Izik Eidus195aefd2007-10-01 22:14:18 +02002861 return -EFAULT;
Xiao Guangrong8b0cedf2011-05-15 23:22:04 +08002862 r = __copy_to_user((void __user *)addr + offset, data, len);
Izik Eiduse0506bc2007-11-11 22:10:22 +02002863 if (r)
2864 return -EFAULT;
Peter Xu28bd7262020-09-30 21:20:34 -04002865 mark_page_dirty_in_slot(kvm, memslot, gfn);
Izik Eidus195aefd2007-10-01 22:14:18 +02002866 return 0;
2867}
Paolo Bonzini8e734852015-05-17 13:58:53 +02002868
2869int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2870 const void *data, int offset, int len)
2871{
2872 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2873
Peter Xu28bd7262020-09-30 21:20:34 -04002874 return __kvm_write_guest_page(kvm, slot, gfn, data, offset, len);
Paolo Bonzini8e734852015-05-17 13:58:53 +02002875}
Izik Eidus195aefd2007-10-01 22:14:18 +02002876EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2877
Paolo Bonzini8e734852015-05-17 13:58:53 +02002878int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2879 const void *data, int offset, int len)
2880{
2881 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2882
Peter Xu28bd7262020-09-30 21:20:34 -04002883 return __kvm_write_guest_page(vcpu->kvm, slot, gfn, data, offset, len);
Paolo Bonzini8e734852015-05-17 13:58:53 +02002884}
2885EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
2886
Izik Eidus195aefd2007-10-01 22:14:18 +02002887int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
2888 unsigned long len)
2889{
2890 gfn_t gfn = gpa >> PAGE_SHIFT;
2891 int seg;
2892 int offset = offset_in_page(gpa);
2893 int ret;
2894
2895 while ((seg = next_segment(len, offset)) != 0) {
2896 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2897 if (ret < 0)
2898 return ret;
2899 offset = 0;
2900 len -= seg;
2901 data += seg;
2902 ++gfn;
2903 }
2904 return 0;
2905}
Wincy Vanff651cb2014-12-11 08:52:58 +03002906EXPORT_SYMBOL_GPL(kvm_write_guest);
Izik Eidus195aefd2007-10-01 22:14:18 +02002907
Paolo Bonzini8e734852015-05-17 13:58:53 +02002908int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2909 unsigned long len)
2910{
2911 gfn_t gfn = gpa >> PAGE_SHIFT;
2912 int seg;
2913 int offset = offset_in_page(gpa);
2914 int ret;
2915
2916 while ((seg = next_segment(len, offset)) != 0) {
2917 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2918 if (ret < 0)
2919 return ret;
2920 offset = 0;
2921 len -= seg;
2922 data += seg;
2923 ++gfn;
2924 }
2925 return 0;
2926}
2927EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2928
Paolo Bonzini5a2d4362017-02-03 20:32:28 -08002929static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
2930 struct gfn_to_hva_cache *ghc,
2931 gpa_t gpa, unsigned long len)
Gleb Natapov49c77542010-10-18 15:22:23 +02002932{
Gleb Natapov49c77542010-10-18 15:22:23 +02002933 int offset = offset_in_page(gpa);
Andrew Honig8f964522013-03-29 09:35:21 -07002934 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2935 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2936 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2937 gfn_t nr_pages_avail;
Gleb Natapov49c77542010-10-18 15:22:23 +02002938
Sean Christopherson6ad1e292020-01-09 14:58:55 -05002939 /* Update ghc->generation before performing any error checks. */
Gleb Natapov49c77542010-10-18 15:22:23 +02002940 ghc->generation = slots->generation;
Sean Christopherson6ad1e292020-01-09 14:58:55 -05002941
2942 if (start_gfn > end_gfn) {
2943 ghc->hva = KVM_HVA_ERR_BAD;
2944 return -EINVAL;
2945 }
Jim Mattsonf1b9dd52018-12-17 13:53:33 -08002946
2947 /*
2948 * If the requested region crosses two memslots, we still
2949 * verify that the entire region is valid here.
2950 */
Sean Christopherson6ad1e292020-01-09 14:58:55 -05002951 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
Jim Mattsonf1b9dd52018-12-17 13:53:33 -08002952 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2953 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2954 &nr_pages_avail);
2955 if (kvm_is_error_hva(ghc->hva))
Sean Christopherson6ad1e292020-01-09 14:58:55 -05002956 return -EFAULT;
Andrew Honig8f964522013-03-29 09:35:21 -07002957 }
Jim Mattsonf1b9dd52018-12-17 13:53:33 -08002958
2959 /* Use the slow path for cross page reads and writes. */
Sean Christopherson6ad1e292020-01-09 14:58:55 -05002960 if (nr_pages_needed == 1)
Jim Mattsonf1b9dd52018-12-17 13:53:33 -08002961 ghc->hva += offset;
2962 else
2963 ghc->memslot = NULL;
2964
Sean Christopherson6ad1e292020-01-09 14:58:55 -05002965 ghc->gpa = gpa;
2966 ghc->len = len;
2967 return 0;
Gleb Natapov49c77542010-10-18 15:22:23 +02002968}
Paolo Bonzini5a2d4362017-02-03 20:32:28 -08002969
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002970int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
Paolo Bonzini5a2d4362017-02-03 20:32:28 -08002971 gpa_t gpa, unsigned long len)
2972{
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002973 struct kvm_memslots *slots = kvm_memslots(kvm);
Paolo Bonzini5a2d4362017-02-03 20:32:28 -08002974 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
2975}
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002976EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
Gleb Natapov49c77542010-10-18 15:22:23 +02002977
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002978int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
Jim Mattson7a86dab2018-12-14 14:34:43 -08002979 void *data, unsigned int offset,
2980 unsigned long len)
Gleb Natapov49c77542010-10-18 15:22:23 +02002981{
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002982 struct kvm_memslots *slots = kvm_memslots(kvm);
Gleb Natapov49c77542010-10-18 15:22:23 +02002983 int r;
Pan Xinhui4ec6e862016-11-02 05:08:34 -04002984 gpa_t gpa = ghc->gpa + offset;
Gleb Natapov49c77542010-10-18 15:22:23 +02002985
Pan Xinhui4ec6e862016-11-02 05:08:34 -04002986 BUG_ON(len + offset > ghc->len);
Andrew Honig8f964522013-03-29 09:35:21 -07002987
Sean Christophersondc9ce712020-01-09 15:56:20 -08002988 if (slots->generation != ghc->generation) {
2989 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2990 return -EFAULT;
2991 }
Andrew Honig8f964522013-03-29 09:35:21 -07002992
Gleb Natapov49c77542010-10-18 15:22:23 +02002993 if (kvm_is_error_hva(ghc->hva))
2994 return -EFAULT;
2995
Sean Christophersonfcfbc612020-01-09 15:56:18 -08002996 if (unlikely(!ghc->memslot))
2997 return kvm_write_guest(kvm, gpa, data, len);
2998
Pan Xinhui4ec6e862016-11-02 05:08:34 -04002999 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
Gleb Natapov49c77542010-10-18 15:22:23 +02003000 if (r)
3001 return -EFAULT;
Peter Xu28bd7262020-09-30 21:20:34 -04003002 mark_page_dirty_in_slot(kvm, ghc->memslot, gpa >> PAGE_SHIFT);
Gleb Natapov49c77542010-10-18 15:22:23 +02003003
3004 return 0;
3005}
Paolo Bonzini4e335d92017-05-02 16:20:18 +02003006EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
Pan Xinhui4ec6e862016-11-02 05:08:34 -04003007
Paolo Bonzini4e335d92017-05-02 16:20:18 +02003008int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3009 void *data, unsigned long len)
Pan Xinhui4ec6e862016-11-02 05:08:34 -04003010{
Paolo Bonzini4e335d92017-05-02 16:20:18 +02003011 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
Pan Xinhui4ec6e862016-11-02 05:08:34 -04003012}
Paolo Bonzini4e335d92017-05-02 16:20:18 +02003013EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
Gleb Natapov49c77542010-10-18 15:22:23 +02003014
Vitaly Kuznetsov0958f0c2020-05-25 16:41:19 +02003015int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3016 void *data, unsigned int offset,
3017 unsigned long len)
Gleb Natapove03b6442011-07-11 15:28:11 -04003018{
Paolo Bonzini4e335d92017-05-02 16:20:18 +02003019 struct kvm_memslots *slots = kvm_memslots(kvm);
Gleb Natapove03b6442011-07-11 15:28:11 -04003020 int r;
Vitaly Kuznetsov0958f0c2020-05-25 16:41:19 +02003021 gpa_t gpa = ghc->gpa + offset;
Gleb Natapove03b6442011-07-11 15:28:11 -04003022
Vitaly Kuznetsov0958f0c2020-05-25 16:41:19 +02003023 BUG_ON(len + offset > ghc->len);
Andrew Honig8f964522013-03-29 09:35:21 -07003024
Sean Christophersondc9ce712020-01-09 15:56:20 -08003025 if (slots->generation != ghc->generation) {
3026 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
3027 return -EFAULT;
3028 }
Andrew Honig8f964522013-03-29 09:35:21 -07003029
Gleb Natapove03b6442011-07-11 15:28:11 -04003030 if (kvm_is_error_hva(ghc->hva))
3031 return -EFAULT;
3032
Sean Christophersonfcfbc612020-01-09 15:56:18 -08003033 if (unlikely(!ghc->memslot))
Vitaly Kuznetsov0958f0c2020-05-25 16:41:19 +02003034 return kvm_read_guest(kvm, gpa, data, len);
Sean Christophersonfcfbc612020-01-09 15:56:18 -08003035
Vitaly Kuznetsov0958f0c2020-05-25 16:41:19 +02003036 r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
Gleb Natapove03b6442011-07-11 15:28:11 -04003037 if (r)
3038 return -EFAULT;
3039
3040 return 0;
3041}
Vitaly Kuznetsov0958f0c2020-05-25 16:41:19 +02003042EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached);
3043
3044int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
3045 void *data, unsigned long len)
3046{
3047 return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len);
3048}
Paolo Bonzini4e335d92017-05-02 16:20:18 +02003049EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
Gleb Natapove03b6442011-07-11 15:28:11 -04003050
Izik Eidus195aefd2007-10-01 22:14:18 +02003051int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
3052{
Paolo Bonzini2f541442020-11-06 05:25:09 -05003053 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
Izik Eidus195aefd2007-10-01 22:14:18 +02003054 gfn_t gfn = gpa >> PAGE_SHIFT;
3055 int seg;
3056 int offset = offset_in_page(gpa);
3057 int ret;
3058
Kevin Mulveybfda0e82015-02-20 08:21:36 -05003059 while ((seg = next_segment(len, offset)) != 0) {
Paolo Bonzini2f541442020-11-06 05:25:09 -05003060 ret = kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
Izik Eidus195aefd2007-10-01 22:14:18 +02003061 if (ret < 0)
3062 return ret;
3063 offset = 0;
3064 len -= seg;
3065 ++gfn;
3066 }
3067 return 0;
3068}
3069EXPORT_SYMBOL_GPL(kvm_clear_guest);
3070
Peter Xu28bd7262020-09-30 21:20:34 -04003071void mark_page_dirty_in_slot(struct kvm *kvm,
3072 struct kvm_memory_slot *memslot,
3073 gfn_t gfn)
Avi Kivity6aa8b732006-12-10 02:21:36 -08003074{
Peter Xu044c59c2020-09-30 21:22:26 -04003075 if (memslot && kvm_slot_dirty_track_enabled(memslot)) {
Rusty Russell7e9d6192007-07-31 20:41:14 +10003076 unsigned long rel_gfn = gfn - memslot->base_gfn;
Peter Xufb04a1e2020-09-30 21:22:22 -04003077 u32 slot = (memslot->as_id << 16) | memslot->id;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003078
Peter Xufb04a1e2020-09-30 21:22:22 -04003079 if (kvm->dirty_ring_size)
3080 kvm_dirty_ring_push(kvm_dirty_ring_get(kvm),
3081 slot, rel_gfn);
3082 else
3083 set_bit_le(rel_gfn, memslot->dirty_bitmap);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003084 }
3085}
Ben Gardona6a0b052020-10-14 11:26:55 -07003086EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003087
Gleb Natapov49c77542010-10-18 15:22:23 +02003088void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
3089{
3090 struct kvm_memory_slot *memslot;
3091
3092 memslot = gfn_to_memslot(kvm, gfn);
Peter Xu28bd7262020-09-30 21:20:34 -04003093 mark_page_dirty_in_slot(kvm, memslot, gfn);
Gleb Natapov49c77542010-10-18 15:22:23 +02003094}
Aneesh Kumar K.V2ba9f0d2013-10-07 22:17:59 +05303095EXPORT_SYMBOL_GPL(mark_page_dirty);
Gleb Natapov49c77542010-10-18 15:22:23 +02003096
Paolo Bonzini8e734852015-05-17 13:58:53 +02003097void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
3098{
3099 struct kvm_memory_slot *memslot;
3100
3101 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
Peter Xu28bd7262020-09-30 21:20:34 -04003102 mark_page_dirty_in_slot(vcpu->kvm, memslot, gfn);
Paolo Bonzini8e734852015-05-17 13:58:53 +02003103}
3104EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
3105
Jan H. Schönherr20b70352017-11-24 22:39:01 +01003106void kvm_sigset_activate(struct kvm_vcpu *vcpu)
3107{
3108 if (!vcpu->sigset_active)
3109 return;
3110
3111 /*
3112 * This does a lockless modification of ->real_blocked, which is fine
3113 * because, only current can change ->real_blocked and all readers of
3114 * ->real_blocked don't care as long ->real_blocked is always a subset
3115 * of ->blocked.
3116 */
3117 sigprocmask(SIG_SETMASK, &vcpu->sigset, &current->real_blocked);
3118}
3119
3120void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
3121{
3122 if (!vcpu->sigset_active)
3123 return;
3124
3125 sigprocmask(SIG_SETMASK, &current->real_blocked, NULL);
3126 sigemptyset(&current->real_blocked);
3127}
3128
Wanpeng Liaca6ff22015-09-03 22:07:38 +08003129static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
3130{
Nir Weinerdee339b2019-01-27 12:17:16 +02003131 unsigned int old, val, grow, grow_start;
Wanpeng Liaca6ff22015-09-03 22:07:38 +08003132
Wanpeng Li2cbd7822015-09-03 22:07:39 +08003133 old = val = vcpu->halt_poll_ns;
Nir Weinerdee339b2019-01-27 12:17:16 +02003134 grow_start = READ_ONCE(halt_poll_ns_grow_start);
Christian Borntraeger6b6de682016-02-09 13:47:55 +01003135 grow = READ_ONCE(halt_poll_ns_grow);
Nir Weiner7fa08e72019-01-27 12:17:14 +02003136 if (!grow)
3137 goto out;
3138
Nir Weinerdee339b2019-01-27 12:17:16 +02003139 val *= grow;
3140 if (val < grow_start)
3141 val = grow_start;
Wanpeng Liaca6ff22015-09-03 22:07:38 +08003142
David Matlack258785e2021-05-06 15:24:43 +00003143 if (val > vcpu->kvm->max_halt_poll_ns)
3144 val = vcpu->kvm->max_halt_poll_ns;
David Matlack313f6362016-03-08 16:19:44 -08003145
Wanpeng Liaca6ff22015-09-03 22:07:38 +08003146 vcpu->halt_poll_ns = val;
Nir Weiner7fa08e72019-01-27 12:17:14 +02003147out:
Wanpeng Li2cbd7822015-09-03 22:07:39 +08003148 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
Wanpeng Liaca6ff22015-09-03 22:07:38 +08003149}
3150
3151static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
3152{
Christian Borntraeger6b6de682016-02-09 13:47:55 +01003153 unsigned int old, val, shrink;
Wanpeng Liaca6ff22015-09-03 22:07:38 +08003154
Wanpeng Li2cbd7822015-09-03 22:07:39 +08003155 old = val = vcpu->halt_poll_ns;
Christian Borntraeger6b6de682016-02-09 13:47:55 +01003156 shrink = READ_ONCE(halt_poll_ns_shrink);
3157 if (shrink == 0)
Wanpeng Liaca6ff22015-09-03 22:07:38 +08003158 val = 0;
3159 else
Christian Borntraeger6b6de682016-02-09 13:47:55 +01003160 val /= shrink;
Wanpeng Liaca6ff22015-09-03 22:07:38 +08003161
3162 vcpu->halt_poll_ns = val;
Wanpeng Li2cbd7822015-09-03 22:07:39 +08003163 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
Wanpeng Liaca6ff22015-09-03 22:07:38 +08003164}
3165
Paolo Bonzinif7819512015-02-04 18:20:58 +01003166static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
3167{
Junaid Shahid50c28f22018-06-27 14:59:11 -07003168 int ret = -EINTR;
3169 int idx = srcu_read_lock(&vcpu->kvm->srcu);
3170
Paolo Bonzinif7819512015-02-04 18:20:58 +01003171 if (kvm_arch_vcpu_runnable(vcpu)) {
3172 kvm_make_request(KVM_REQ_UNHALT, vcpu);
Junaid Shahid50c28f22018-06-27 14:59:11 -07003173 goto out;
Paolo Bonzinif7819512015-02-04 18:20:58 +01003174 }
3175 if (kvm_cpu_has_pending_timer(vcpu))
Junaid Shahid50c28f22018-06-27 14:59:11 -07003176 goto out;
Paolo Bonzinif7819512015-02-04 18:20:58 +01003177 if (signal_pending(current))
Junaid Shahid50c28f22018-06-27 14:59:11 -07003178 goto out;
Marcelo Tosatti084071d2021-05-25 10:41:17 -03003179 if (kvm_check_request(KVM_REQ_UNBLOCK, vcpu))
3180 goto out;
Paolo Bonzinif7819512015-02-04 18:20:58 +01003181
Junaid Shahid50c28f22018-06-27 14:59:11 -07003182 ret = 0;
3183out:
3184 srcu_read_unlock(&vcpu->kvm->srcu, idx);
3185 return ret;
Paolo Bonzinif7819512015-02-04 18:20:58 +01003186}
3187
David Matlackcb953122020-05-08 11:22:40 -07003188static inline void
3189update_halt_poll_stats(struct kvm_vcpu *vcpu, u64 poll_ns, bool waited)
3190{
3191 if (waited)
Jing Zhang0193cc92021-06-18 22:27:03 +00003192 vcpu->stat.generic.halt_poll_fail_ns += poll_ns;
David Matlackcb953122020-05-08 11:22:40 -07003193 else
Jing Zhang0193cc92021-06-18 22:27:03 +00003194 vcpu->stat.generic.halt_poll_success_ns += poll_ns;
David Matlackcb953122020-05-08 11:22:40 -07003195}
3196
Eddie Dongb6958ce2007-07-18 12:15:21 +03003197/*
3198 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
3199 */
Hollis Blanchard8776e512007-10-31 17:24:24 -05003200void kvm_vcpu_block(struct kvm_vcpu *vcpu)
Eddie Dongb6958ce2007-07-18 12:15:21 +03003201{
David Matlackcb953122020-05-08 11:22:40 -07003202 ktime_t start, cur, poll_end;
Paolo Bonzinif7819512015-02-04 18:20:58 +01003203 bool waited = false;
Wanpeng Liaca6ff22015-09-03 22:07:38 +08003204 u64 block_ns;
Paolo Bonzinif7819512015-02-04 18:20:58 +01003205
Marc Zyngier07ab0f82019-08-02 11:37:09 +01003206 kvm_arch_vcpu_blocking(vcpu);
3207
David Matlackcb953122020-05-08 11:22:40 -07003208 start = cur = poll_end = ktime_get();
Christian Borntraegercdd6ad32019-03-05 05:30:01 -05003209 if (vcpu->halt_poll_ns && !kvm_arch_no_poll(vcpu)) {
Wanpeng Li19020f82015-09-03 22:07:37 +08003210 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
Xiubo Lif95ef0cd2015-02-26 14:58:23 +08003211
Jing Zhang0193cc92021-06-18 22:27:03 +00003212 ++vcpu->stat.generic.halt_attempted_poll;
Paolo Bonzinif7819512015-02-04 18:20:58 +01003213 do {
3214 /*
3215 * This sets KVM_REQ_UNHALT if an interrupt
3216 * arrives.
3217 */
3218 if (kvm_vcpu_check_block(vcpu) < 0) {
Jing Zhang0193cc92021-06-18 22:27:03 +00003219 ++vcpu->stat.generic.halt_successful_poll;
Christian Borntraeger3491caf2016-05-13 12:16:35 +02003220 if (!vcpu_valid_wakeup(vcpu))
Jing Zhang0193cc92021-06-18 22:27:03 +00003221 ++vcpu->stat.generic.halt_poll_invalid;
Paolo Bonzinif7819512015-02-04 18:20:58 +01003222 goto out;
3223 }
Li RongQing74775652021-07-27 19:12:47 +08003224 cpu_relax();
David Matlackcb953122020-05-08 11:22:40 -07003225 poll_end = cur = ktime_get();
Wanpeng Li6bd5b742021-05-18 05:00:31 -07003226 } while (kvm_vcpu_can_poll(cur, stop));
Paolo Bonzinif7819512015-02-04 18:20:58 +01003227 }
Eddie Dongb6958ce2007-07-18 12:15:21 +03003228
Davidlohr Buesoda4ad882020-04-23 22:48:37 -07003229 prepare_to_rcuwait(&vcpu->wait);
Marcelo Tosattie5c239c2008-05-08 19:47:01 -03003230 for (;;) {
Davidlohr Buesoda4ad882020-04-23 22:48:37 -07003231 set_current_state(TASK_INTERRUPTIBLE);
Eddie Dongb6958ce2007-07-18 12:15:21 +03003232
Paolo Bonzinif7819512015-02-04 18:20:58 +01003233 if (kvm_vcpu_check_block(vcpu) < 0)
Marcelo Tosattie5c239c2008-05-08 19:47:01 -03003234 break;
3235
Paolo Bonzinif7819512015-02-04 18:20:58 +01003236 waited = true;
Eddie Dongb6958ce2007-07-18 12:15:21 +03003237 schedule();
Eddie Dongb6958ce2007-07-18 12:15:21 +03003238 }
Davidlohr Buesoda4ad882020-04-23 22:48:37 -07003239 finish_rcuwait(&vcpu->wait);
Paolo Bonzinif7819512015-02-04 18:20:58 +01003240 cur = ktime_get();
Paolo Bonzinif7819512015-02-04 18:20:58 +01003241out:
Marc Zyngier07ab0f82019-08-02 11:37:09 +01003242 kvm_arch_vcpu_unblocking(vcpu);
Wanpeng Liaca6ff22015-09-03 22:07:38 +08003243 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
3244
David Matlackcb953122020-05-08 11:22:40 -07003245 update_halt_poll_stats(
3246 vcpu, ktime_to_ns(ktime_sub(poll_end, start)), waited);
3247
Wanpeng Li44551b22019-09-29 09:06:56 +08003248 if (!kvm_arch_no_poll(vcpu)) {
3249 if (!vcpu_valid_wakeup(vcpu)) {
Wanpeng Liaca6ff22015-09-03 22:07:38 +08003250 shrink_halt_poll_ns(vcpu);
David Matlackacd05782020-04-17 15:14:46 -07003251 } else if (vcpu->kvm->max_halt_poll_ns) {
Wanpeng Li44551b22019-09-29 09:06:56 +08003252 if (block_ns <= vcpu->halt_poll_ns)
3253 ;
3254 /* we had a long block, shrink polling */
David Matlackacd05782020-04-17 15:14:46 -07003255 else if (vcpu->halt_poll_ns &&
3256 block_ns > vcpu->kvm->max_halt_poll_ns)
Wanpeng Li44551b22019-09-29 09:06:56 +08003257 shrink_halt_poll_ns(vcpu);
3258 /* we had a short halt and our poll time is too small */
David Matlackacd05782020-04-17 15:14:46 -07003259 else if (vcpu->halt_poll_ns < vcpu->kvm->max_halt_poll_ns &&
3260 block_ns < vcpu->kvm->max_halt_poll_ns)
Wanpeng Li44551b22019-09-29 09:06:56 +08003261 grow_halt_poll_ns(vcpu);
3262 } else {
3263 vcpu->halt_poll_ns = 0;
3264 }
3265 }
Wanpeng Liaca6ff22015-09-03 22:07:38 +08003266
Christian Borntraeger3491caf2016-05-13 12:16:35 +02003267 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
3268 kvm_arch_vcpu_block_finish(vcpu);
Eddie Dongb6958ce2007-07-18 12:15:21 +03003269}
Aneesh Kumar K.V2ba9f0d2013-10-07 22:17:59 +05303270EXPORT_SYMBOL_GPL(kvm_vcpu_block);
Eddie Dongb6958ce2007-07-18 12:15:21 +03003271
Radim Krčmář178f02f2017-04-26 22:32:26 +02003272bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
Christoffer Dallb6d33832012-03-08 16:44:24 -05003273{
Davidlohr Buesoda4ad882020-04-23 22:48:37 -07003274 struct rcuwait *waitp;
Christoffer Dallb6d33832012-03-08 16:44:24 -05003275
Davidlohr Buesoda4ad882020-04-23 22:48:37 -07003276 waitp = kvm_arch_vcpu_get_wait(vcpu);
3277 if (rcuwait_wake_up(waitp)) {
Wanpeng Lid73eb572019-07-18 19:39:06 +08003278 WRITE_ONCE(vcpu->ready, true);
Jing Zhang0193cc92021-06-18 22:27:03 +00003279 ++vcpu->stat.generic.halt_wakeup;
Radim Krčmář178f02f2017-04-26 22:32:26 +02003280 return true;
Christoffer Dallb6d33832012-03-08 16:44:24 -05003281 }
3282
Radim Krčmář178f02f2017-04-26 22:32:26 +02003283 return false;
Radim Krčmářdd1a4cc2016-05-04 14:09:44 -05003284}
3285EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
3286
Paolo Bonzini0266c892017-05-04 15:14:13 +02003287#ifndef CONFIG_S390
Radim Krčmářdd1a4cc2016-05-04 14:09:44 -05003288/*
3289 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
3290 */
3291void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
3292{
3293 int me;
3294 int cpu = vcpu->cpu;
3295
Radim Krčmář178f02f2017-04-26 22:32:26 +02003296 if (kvm_vcpu_wake_up(vcpu))
3297 return;
3298
Christoffer Dallb6d33832012-03-08 16:44:24 -05003299 me = get_cpu();
3300 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
3301 if (kvm_arch_vcpu_should_kick(vcpu))
3302 smp_send_reschedule(cpu);
3303 put_cpu();
3304}
Yang Zhanga20ed542013-04-11 19:25:15 +08003305EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
Paolo Bonzini0266c892017-05-04 15:14:13 +02003306#endif /* !CONFIG_S390 */
Christoffer Dallb6d33832012-03-08 16:44:24 -05003307
Dan Carpenterfa933842014-05-23 13:20:42 +03003308int kvm_vcpu_yield_to(struct kvm_vcpu *target)
Konstantin Weitz41628d32012-04-25 15:30:38 +02003309{
3310 struct pid *pid;
3311 struct task_struct *task = NULL;
Dan Carpenterfa933842014-05-23 13:20:42 +03003312 int ret = 0;
Konstantin Weitz41628d32012-04-25 15:30:38 +02003313
3314 rcu_read_lock();
3315 pid = rcu_dereference(target->pid);
3316 if (pid)
Sam Bobroff27fbe64b2014-09-19 09:40:41 +10003317 task = get_pid_task(pid, PIDTYPE_PID);
Konstantin Weitz41628d32012-04-25 15:30:38 +02003318 rcu_read_unlock();
3319 if (!task)
Raghavendra K Tc45c5282013-01-22 13:09:24 +05303320 return ret;
Raghavendra K Tc45c5282013-01-22 13:09:24 +05303321 ret = yield_to(task, 1);
Konstantin Weitz41628d32012-04-25 15:30:38 +02003322 put_task_struct(task);
Raghavendra K Tc45c5282013-01-22 13:09:24 +05303323
3324 return ret;
Konstantin Weitz41628d32012-04-25 15:30:38 +02003325}
3326EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
3327
Raghavendra K T06e48c52012-07-19 15:17:52 +05303328/*
3329 * Helper that checks whether a VCPU is eligible for directed yield.
3330 * Most eligible candidate to yield is decided by following heuristics:
3331 *
3332 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
3333 * (preempted lock holder), indicated by @in_spin_loop.
Fuad Tabba656012c2020-04-01 15:03:10 +01003334 * Set at the beginning and cleared at the end of interception/PLE handler.
Raghavendra K T06e48c52012-07-19 15:17:52 +05303335 *
3336 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
3337 * chance last time (mostly it has become eligible now since we have probably
3338 * yielded to lockholder in last iteration. This is done by toggling
3339 * @dy_eligible each time a VCPU checked for eligibility.)
3340 *
3341 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
3342 * to preempted lock-holder could result in wrong VCPU selection and CPU
3343 * burning. Giving priority for a potential lock-holder increases lock
3344 * progress.
3345 *
3346 * Since algorithm is based on heuristics, accessing another VCPU data without
3347 * locking does not harm. It may result in trying to yield to same VCPU, fail
3348 * and continue with next VCPU and so on.
3349 */
Stephen Hemminger79408762013-12-29 12:12:29 -08003350static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
Raghavendra K T06e48c52012-07-19 15:17:52 +05303351{
Scott Wood4a55dd72014-01-09 18:43:16 -06003352#ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
Raghavendra K T06e48c52012-07-19 15:17:52 +05303353 bool eligible;
3354
3355 eligible = !vcpu->spin_loop.in_spin_loop ||
Christian Borntraeger34656112014-09-04 21:13:31 +02003356 vcpu->spin_loop.dy_eligible;
Raghavendra K T06e48c52012-07-19 15:17:52 +05303357
3358 if (vcpu->spin_loop.in_spin_loop)
3359 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
3360
3361 return eligible;
Scott Wood4a55dd72014-01-09 18:43:16 -06003362#else
3363 return true;
Raghavendra K T06e48c52012-07-19 15:17:52 +05303364#endif
Scott Wood4a55dd72014-01-09 18:43:16 -06003365}
Raghavendra K Tc45c5282013-01-22 13:09:24 +05303366
Wanpeng Li17e433b2019-08-05 10:03:19 +08003367/*
3368 * Unlike kvm_arch_vcpu_runnable, this function is called outside
3369 * a vcpu_load/vcpu_put pair. However, for most architectures
3370 * kvm_arch_vcpu_runnable does not require vcpu_load.
3371 */
3372bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
3373{
3374 return kvm_arch_vcpu_runnable(vcpu);
3375}
3376
3377static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
3378{
3379 if (kvm_arch_dy_runnable(vcpu))
3380 return true;
3381
3382#ifdef CONFIG_KVM_ASYNC_PF
3383 if (!list_empty_careful(&vcpu->async_pf.done))
3384 return true;
3385#endif
3386
3387 return false;
3388}
3389
Wanpeng Li52acd222021-04-16 11:08:10 +08003390bool __weak kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu)
3391{
3392 return false;
3393}
3394
Longpeng(Mike)199b5762017-08-08 12:05:32 +08003395void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
Zhai, Edwind255f4f2009-10-09 18:03:20 +08003396{
Rik van Riel217ece62011-02-01 09:53:28 -05003397 struct kvm *kvm = me->kvm;
3398 struct kvm_vcpu *vcpu;
3399 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
3400 int yielded = 0;
Raghavendra K Tc45c5282013-01-22 13:09:24 +05303401 int try = 3;
Rik van Riel217ece62011-02-01 09:53:28 -05003402 int pass;
3403 int i;
Zhai, Edwind255f4f2009-10-09 18:03:20 +08003404
Raghavendra K T4c088492012-07-18 19:07:46 +05303405 kvm_vcpu_set_in_spin_loop(me, true);
Rik van Riel217ece62011-02-01 09:53:28 -05003406 /*
3407 * We boost the priority of a VCPU that is runnable but not
3408 * currently running, because it got preempted by something
3409 * else and called schedule in __vcpu_run. Hopefully that
3410 * VCPU is holding the lock that we need and will release it.
3411 * We approximate round-robin by starting at the last boosted VCPU.
3412 */
Raghavendra K Tc45c5282013-01-22 13:09:24 +05303413 for (pass = 0; pass < 2 && !yielded && try; pass++) {
Rik van Riel217ece62011-02-01 09:53:28 -05003414 kvm_for_each_vcpu(i, vcpu, kvm) {
Rik van Riel5cfc2aa2012-06-19 16:51:04 -04003415 if (!pass && i <= last_boosted_vcpu) {
Rik van Riel217ece62011-02-01 09:53:28 -05003416 i = last_boosted_vcpu;
3417 continue;
3418 } else if (pass && i > last_boosted_vcpu)
3419 break;
Wanpeng Lid73eb572019-07-18 19:39:06 +08003420 if (!READ_ONCE(vcpu->ready))
Raghavendra K T7bc7ae22013-03-04 23:32:27 +05303421 continue;
Rik van Riel217ece62011-02-01 09:53:28 -05003422 if (vcpu == me)
3423 continue;
Davidlohr Buesoda4ad882020-04-23 22:48:37 -07003424 if (rcuwait_active(&vcpu->wait) &&
3425 !vcpu_dy_runnable(vcpu))
Rik van Riel217ece62011-02-01 09:53:28 -05003426 continue;
Wanpeng Li046ddee2019-08-01 11:30:14 +08003427 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
Wanpeng Li52acd222021-04-16 11:08:10 +08003428 !kvm_arch_dy_has_pending_interrupt(vcpu) &&
3429 !kvm_arch_vcpu_in_kernel(vcpu))
Longpeng(Mike)199b5762017-08-08 12:05:32 +08003430 continue;
Raghavendra K T06e48c52012-07-19 15:17:52 +05303431 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
3432 continue;
Raghavendra K Tc45c5282013-01-22 13:09:24 +05303433
3434 yielded = kvm_vcpu_yield_to(vcpu);
3435 if (yielded > 0) {
Rik van Riel217ece62011-02-01 09:53:28 -05003436 kvm->last_boosted_vcpu = i;
Rik van Riel217ece62011-02-01 09:53:28 -05003437 break;
Raghavendra K Tc45c5282013-01-22 13:09:24 +05303438 } else if (yielded < 0) {
3439 try--;
3440 if (!try)
3441 break;
Rik van Riel217ece62011-02-01 09:53:28 -05003442 }
Rik van Riel217ece62011-02-01 09:53:28 -05003443 }
3444 }
Raghavendra K T4c088492012-07-18 19:07:46 +05303445 kvm_vcpu_set_in_spin_loop(me, false);
Raghavendra K T06e48c52012-07-19 15:17:52 +05303446
3447 /* Ensure vcpu is not eligible during next spinloop */
3448 kvm_vcpu_set_dy_eligible(me, false);
Zhai, Edwind255f4f2009-10-09 18:03:20 +08003449}
3450EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
3451
Peter Xufb04a1e2020-09-30 21:22:22 -04003452static bool kvm_page_in_dirty_ring(struct kvm *kvm, unsigned long pgoff)
3453{
3454#if KVM_DIRTY_LOG_PAGE_OFFSET > 0
3455 return (pgoff >= KVM_DIRTY_LOG_PAGE_OFFSET) &&
3456 (pgoff < KVM_DIRTY_LOG_PAGE_OFFSET +
3457 kvm->dirty_ring_size / PAGE_SIZE);
3458#else
3459 return false;
3460#endif
3461}
3462
Souptick Joarder1499fa82018-04-19 00:49:58 +05303463static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02003464{
Dave Jiang11bac802017-02-24 14:56:41 -08003465 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02003466 struct page *page;
3467
npiggin@suse.dee4a533a2007-12-05 18:15:52 +11003468 if (vmf->pgoff == 0)
Avi Kivity039576c2007-03-20 12:46:50 +02003469 page = virt_to_page(vcpu->run);
Avi Kivity09566762008-01-23 18:14:23 +02003470#ifdef CONFIG_X86
npiggin@suse.dee4a533a2007-12-05 18:15:52 +11003471 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
Zhang Xiantaoad312c72007-12-13 23:50:52 +08003472 page = virt_to_page(vcpu->arch.pio_data);
Avi Kivity09566762008-01-23 18:14:23 +02003473#endif
Paolo Bonzini4b4357e2017-03-31 13:53:23 +02003474#ifdef CONFIG_KVM_MMIO
Laurent Vivier5f94c172008-05-30 16:05:54 +02003475 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
3476 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
3477#endif
Peter Xufb04a1e2020-09-30 21:22:22 -04003478 else if (kvm_page_in_dirty_ring(vcpu->kvm, vmf->pgoff))
3479 page = kvm_dirty_ring_get_page(
3480 &vcpu->dirty_ring,
3481 vmf->pgoff - KVM_DIRTY_LOG_PAGE_OFFSET);
Avi Kivity039576c2007-03-20 12:46:50 +02003482 else
Carsten Otte5b1c1492012-01-04 10:25:23 +01003483 return kvm_arch_vcpu_fault(vcpu, vmf);
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02003484 get_page(page);
npiggin@suse.dee4a533a2007-12-05 18:15:52 +11003485 vmf->page = page;
3486 return 0;
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02003487}
3488
Alexey Dobriyanf0f37e2f2009-09-27 22:29:37 +04003489static const struct vm_operations_struct kvm_vcpu_vm_ops = {
npiggin@suse.dee4a533a2007-12-05 18:15:52 +11003490 .fault = kvm_vcpu_fault,
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02003491};
3492
3493static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
3494{
Peter Xufb04a1e2020-09-30 21:22:22 -04003495 struct kvm_vcpu *vcpu = file->private_data;
3496 unsigned long pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
3497
3498 if ((kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff) ||
3499 kvm_page_in_dirty_ring(vcpu->kvm, vma->vm_pgoff + pages - 1)) &&
3500 ((vma->vm_flags & VM_EXEC) || !(vma->vm_flags & VM_SHARED)))
3501 return -EINVAL;
3502
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02003503 vma->vm_ops = &kvm_vcpu_vm_ops;
3504 return 0;
3505}
3506
Avi Kivitybccf2152007-02-21 18:04:26 +02003507static int kvm_vcpu_release(struct inode *inode, struct file *filp)
3508{
3509 struct kvm_vcpu *vcpu = filp->private_data;
3510
Al Viro66c0b392008-04-19 20:33:56 +01003511 kvm_put_kvm(vcpu->kvm);
Avi Kivitybccf2152007-02-21 18:04:26 +02003512 return 0;
3513}
3514
Christian Borntraeger3d3aab12008-12-02 11:17:32 +01003515static struct file_operations kvm_vcpu_fops = {
Avi Kivitybccf2152007-02-21 18:04:26 +02003516 .release = kvm_vcpu_release,
3517 .unlocked_ioctl = kvm_vcpu_ioctl,
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02003518 .mmap = kvm_vcpu_mmap,
Arnd Bergmann6038f372010-08-15 18:52:59 +02003519 .llseek = noop_llseek,
Marc Zyngier7ddfd3e2018-06-17 10:16:21 +01003520 KVM_COMPAT(kvm_vcpu_compat_ioctl),
Avi Kivitybccf2152007-02-21 18:04:26 +02003521};
3522
3523/*
3524 * Allocates an inode for the vcpu.
3525 */
3526static int create_vcpu_fd(struct kvm_vcpu *vcpu)
3527{
Masatake YAMATOe46b4692018-01-20 04:04:22 +09003528 char name[8 + 1 + ITOA_MAX_LEN + 1];
3529
3530 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
3531 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
Avi Kivitybccf2152007-02-21 18:04:26 +02003532}
3533
Greg KH3e7093d2019-07-31 20:56:20 +02003534static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
Luiz Capitulino45b59392016-09-16 10:27:35 -04003535{
Paolo Bonzini741cbba2019-08-03 08:14:25 +02003536#ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
Paolo Bonzinid56f5132020-06-04 15:16:52 +02003537 struct dentry *debugfs_dentry;
Luiz Capitulino45b59392016-09-16 10:27:35 -04003538 char dir_name[ITOA_MAX_LEN * 2];
Luiz Capitulino45b59392016-09-16 10:27:35 -04003539
Luiz Capitulino45b59392016-09-16 10:27:35 -04003540 if (!debugfs_initialized())
Greg KH3e7093d2019-07-31 20:56:20 +02003541 return;
Luiz Capitulino45b59392016-09-16 10:27:35 -04003542
3543 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
Paolo Bonzinid56f5132020-06-04 15:16:52 +02003544 debugfs_dentry = debugfs_create_dir(dir_name,
3545 vcpu->kvm->debugfs_dentry);
Luiz Capitulino45b59392016-09-16 10:27:35 -04003546
Paolo Bonzinid56f5132020-06-04 15:16:52 +02003547 kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry);
Paolo Bonzini741cbba2019-08-03 08:14:25 +02003548#endif
Luiz Capitulino45b59392016-09-16 10:27:35 -04003549}
3550
Avi Kivityc5ea7662007-02-20 18:41:05 +02003551/*
3552 * Creates some virtual cpus. Good luck creating more than one.
3553 */
Gleb Natapov73880c82009-06-09 15:56:28 +03003554static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
Avi Kivityc5ea7662007-02-20 18:41:05 +02003555{
3556 int r;
David Hildenbrande09fefd2015-11-05 09:03:50 +01003557 struct kvm_vcpu *vcpu;
Sean Christopherson8bd826d2019-12-18 13:55:30 -08003558 struct page *page;
Avi Kivityc5ea7662007-02-20 18:41:05 +02003559
Greg Kurz0b1b1df2016-05-09 18:13:37 +02003560 if (id >= KVM_MAX_VCPU_ID)
Andy Honig338c7db2013-11-18 16:09:22 -08003561 return -EINVAL;
3562
Paolo Bonzini6c7caeb2016-06-13 14:48:25 +02003563 mutex_lock(&kvm->lock);
3564 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
3565 mutex_unlock(&kvm->lock);
3566 return -EINVAL;
3567 }
3568
3569 kvm->created_vcpus++;
3570 mutex_unlock(&kvm->lock);
3571
Sean Christopherson897cc382019-12-18 13:55:09 -08003572 r = kvm_arch_vcpu_precreate(kvm, id);
3573 if (r)
3574 goto vcpu_decrement;
3575
Sean Christopherson85f47932021-04-06 12:07:40 -07003576 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
Sean Christophersone529ef62019-12-18 13:55:15 -08003577 if (!vcpu) {
3578 r = -ENOMEM;
Paolo Bonzini6c7caeb2016-06-13 14:48:25 +02003579 goto vcpu_decrement;
3580 }
Avi Kivityc5ea7662007-02-20 18:41:05 +02003581
Peter Xufcd97ad2020-01-09 09:57:12 -05003582 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
Shakeel Butt93bb59c2020-12-18 14:01:38 -08003583 page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
Sean Christopherson8bd826d2019-12-18 13:55:30 -08003584 if (!page) {
3585 r = -ENOMEM;
Sean Christophersone529ef62019-12-18 13:55:15 -08003586 goto vcpu_free;
Sean Christopherson8bd826d2019-12-18 13:55:30 -08003587 }
3588 vcpu->run = page_address(page);
3589
3590 kvm_vcpu_init(vcpu, kvm, id);
Sean Christophersone529ef62019-12-18 13:55:15 -08003591
3592 r = kvm_arch_vcpu_create(vcpu);
3593 if (r)
Sean Christopherson8bd826d2019-12-18 13:55:30 -08003594 goto vcpu_free_run_page;
Sean Christophersone529ef62019-12-18 13:55:15 -08003595
Peter Xufb04a1e2020-09-30 21:22:22 -04003596 if (kvm->dirty_ring_size) {
3597 r = kvm_dirty_ring_alloc(&vcpu->dirty_ring,
3598 id, kvm->dirty_ring_size);
3599 if (r)
3600 goto arch_vcpu_destroy;
3601 }
3602
Shaohua Li11ec2802007-07-23 14:51:37 +08003603 mutex_lock(&kvm->lock);
David Hildenbrande09fefd2015-11-05 09:03:50 +01003604 if (kvm_get_vcpu_by_id(kvm, id)) {
3605 r = -EEXIST;
3606 goto unlock_vcpu_destroy;
3607 }
Gleb Natapov73880c82009-06-09 15:56:28 +03003608
Radim Krčmář8750e722019-11-07 07:53:42 -05003609 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
3610 BUG_ON(kvm->vcpus[vcpu->vcpu_idx]);
Rusty Russellfb3f0f52007-07-27 17:16:56 +10003611
Jing Zhangce55c042021-06-18 22:27:06 +00003612 /* Fill the stats id string for the vcpu */
3613 snprintf(vcpu->stats_id, sizeof(vcpu->stats_id), "kvm-%d/vcpu-%d",
3614 task_pid_nr(current), id);
3615
Rusty Russellfb3f0f52007-07-27 17:16:56 +10003616 /* Now it's all set up, let userspace reach it */
Al Viro66c0b392008-04-19 20:33:56 +01003617 kvm_get_kvm(kvm);
Avi Kivitybccf2152007-02-21 18:04:26 +02003618 r = create_vcpu_fd(vcpu);
Gleb Natapov73880c82009-06-09 15:56:28 +03003619 if (r < 0) {
Sean Christopherson149487b2019-10-21 15:58:42 -07003620 kvm_put_kvm_no_destroy(kvm);
Jan Kiszkad7805922011-05-23 10:33:05 +02003621 goto unlock_vcpu_destroy;
Gleb Natapov73880c82009-06-09 15:56:28 +03003622 }
3623
Radim Krčmář8750e722019-11-07 07:53:42 -05003624 kvm->vcpus[vcpu->vcpu_idx] = vcpu;
Paolo Bonzinidd489242015-07-29 11:32:20 +02003625
3626 /*
3627 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
3628 * before kvm->online_vcpu's incremented value.
3629 */
Gleb Natapov73880c82009-06-09 15:56:28 +03003630 smp_wmb();
3631 atomic_inc(&kvm->online_vcpus);
3632
Gleb Natapov73880c82009-06-09 15:56:28 +03003633 mutex_unlock(&kvm->lock);
Marcelo Tosatti42897d82012-11-27 23:29:02 -02003634 kvm_arch_vcpu_postcreate(vcpu);
Paolo Bonzini63d04342020-04-01 00:42:22 +02003635 kvm_create_vcpu_debugfs(vcpu);
Avi Kivitybccf2152007-02-21 18:04:26 +02003636 return r;
Avi Kivityc5ea7662007-02-20 18:41:05 +02003637
Jan Kiszkad7805922011-05-23 10:33:05 +02003638unlock_vcpu_destroy:
Glauber Costa7d8fece2008-09-17 23:16:59 -03003639 mutex_unlock(&kvm->lock);
Peter Xufb04a1e2020-09-30 21:22:22 -04003640 kvm_dirty_ring_free(&vcpu->dirty_ring);
3641arch_vcpu_destroy:
Hollis Blanchardd40ccc62007-11-19 14:04:43 -06003642 kvm_arch_vcpu_destroy(vcpu);
Sean Christopherson8bd826d2019-12-18 13:55:30 -08003643vcpu_free_run_page:
3644 free_page((unsigned long)vcpu->run);
Sean Christophersone529ef62019-12-18 13:55:15 -08003645vcpu_free:
3646 kmem_cache_free(kvm_vcpu_cache, vcpu);
Paolo Bonzini6c7caeb2016-06-13 14:48:25 +02003647vcpu_decrement:
3648 mutex_lock(&kvm->lock);
3649 kvm->created_vcpus--;
3650 mutex_unlock(&kvm->lock);
Avi Kivityc5ea7662007-02-20 18:41:05 +02003651 return r;
3652}
3653
Avi Kivity1961d272007-03-05 19:46:05 +02003654static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3655{
3656 if (sigset) {
3657 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3658 vcpu->sigset_active = 1;
3659 vcpu->sigset = *sigset;
3660 } else
3661 vcpu->sigset_active = 0;
3662 return 0;
3663}
3664
Jing Zhangce55c042021-06-18 22:27:06 +00003665static ssize_t kvm_vcpu_stats_read(struct file *file, char __user *user_buffer,
3666 size_t size, loff_t *offset)
3667{
3668 struct kvm_vcpu *vcpu = file->private_data;
3669
3670 return kvm_stats_read(vcpu->stats_id, &kvm_vcpu_stats_header,
3671 &kvm_vcpu_stats_desc[0], &vcpu->stat,
3672 sizeof(vcpu->stat), user_buffer, size, offset);
3673}
3674
3675static const struct file_operations kvm_vcpu_stats_fops = {
3676 .read = kvm_vcpu_stats_read,
3677 .llseek = noop_llseek,
3678};
3679
3680static int kvm_vcpu_ioctl_get_stats_fd(struct kvm_vcpu *vcpu)
3681{
3682 int fd;
3683 struct file *file;
3684 char name[15 + ITOA_MAX_LEN + 1];
3685
3686 snprintf(name, sizeof(name), "kvm-vcpu-stats:%d", vcpu->vcpu_id);
3687
3688 fd = get_unused_fd_flags(O_CLOEXEC);
3689 if (fd < 0)
3690 return fd;
3691
3692 file = anon_inode_getfile(name, &kvm_vcpu_stats_fops, vcpu, O_RDONLY);
3693 if (IS_ERR(file)) {
3694 put_unused_fd(fd);
3695 return PTR_ERR(file);
3696 }
3697 file->f_mode |= FMODE_PREAD;
3698 fd_install(fd, file);
3699
3700 return fd;
3701}
3702
Avi Kivitybccf2152007-02-21 18:04:26 +02003703static long kvm_vcpu_ioctl(struct file *filp,
3704 unsigned int ioctl, unsigned long arg)
Avi Kivity6aa8b732006-12-10 02:21:36 -08003705{
Avi Kivitybccf2152007-02-21 18:04:26 +02003706 struct kvm_vcpu *vcpu = filp->private_data;
Al Viro2f3669872007-02-09 16:38:35 +00003707 void __user *argp = (void __user *)arg;
Carsten Otte313a3dc2007-10-11 19:16:52 +02003708 int r;
Dave Hansenfa3795a2008-08-11 10:01:46 -07003709 struct kvm_fpu *fpu = NULL;
3710 struct kvm_sregs *kvm_sregs = NULL;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003711
Sean Christopherson0b8f1172021-07-02 15:04:23 -07003712 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_bugged)
Avi Kivity6d4e4c42007-11-21 16:41:05 +02003713 return -EIO;
Avi Kivity2122ff52010-05-13 11:25:04 +03003714
David Matlack2ea75be2014-09-19 16:03:25 -07003715 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
3716 return -EINVAL;
3717
Avi Kivity2122ff52010-05-13 11:25:04 +03003718 /*
Paolo Bonzini5cb09442017-12-12 17:41:34 +01003719 * Some architectures have vcpu ioctls that are asynchronous to vcpu
3720 * execution; mutex_lock() would break them.
Avi Kivity2122ff52010-05-13 11:25:04 +03003721 */
Paolo Bonzini5cb09442017-12-12 17:41:34 +01003722 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
3723 if (r != -ENOIOCTLCMD)
Michael S. Tsirkin9fc77442012-09-16 11:50:30 +03003724 return r;
Avi Kivity2122ff52010-05-13 11:25:04 +03003725
Christoffer Dallec7660c2017-12-04 21:35:23 +01003726 if (mutex_lock_killable(&vcpu->mutex))
3727 return -EINTR;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003728 switch (ioctl) {
Christian Borntraeger0e4524a2017-07-06 14:44:28 +02003729 case KVM_RUN: {
3730 struct pid *oldpid;
Avi Kivityf0fe5102007-03-07 13:11:17 +02003731 r = -EINVAL;
3732 if (arg)
3733 goto out;
Christian Borntraeger0e4524a2017-07-06 14:44:28 +02003734 oldpid = rcu_access_pointer(vcpu->pid);
Eric W. Biederman71dbc8a2017-07-16 21:39:32 -05003735 if (unlikely(oldpid != task_pid(current))) {
Christian Borntraeger7a72f7a2014-08-05 16:44:14 +02003736 /* The thread running this VCPU changed. */
Christoffer Dallbd2a6392018-02-23 17:23:57 +01003737 struct pid *newpid;
Xiubo Lif95ef0cd2015-02-26 14:58:23 +08003738
Christoffer Dallbd2a6392018-02-23 17:23:57 +01003739 r = kvm_arch_vcpu_run_pid_change(vcpu);
3740 if (r)
3741 break;
3742
3743 newpid = get_task_pid(current, PIDTYPE_PID);
Christian Borntraeger7a72f7a2014-08-05 16:44:14 +02003744 rcu_assign_pointer(vcpu->pid, newpid);
3745 if (oldpid)
3746 synchronize_rcu();
3747 put_pid(oldpid);
3748 }
Tianjia Zhang1b94f6f2020-04-16 13:10:57 +08003749 r = kvm_arch_vcpu_ioctl_run(vcpu);
Gleb Natapov64be5002010-10-24 16:49:08 +02003750 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003751 break;
Christian Borntraeger0e4524a2017-07-06 14:44:28 +02003752 }
Avi Kivity6aa8b732006-12-10 02:21:36 -08003753 case KVM_GET_REGS: {
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003754 struct kvm_regs *kvm_regs;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003755
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003756 r = -ENOMEM;
Ben Gardonb12ce362019-02-11 11:02:49 -08003757 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003758 if (!kvm_regs)
3759 goto out;
3760 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003761 if (r)
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003762 goto out_free1;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003763 r = -EFAULT;
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003764 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
3765 goto out_free1;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003766 r = 0;
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003767out_free1:
3768 kfree(kvm_regs);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003769 break;
3770 }
3771 case KVM_SET_REGS: {
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003772 struct kvm_regs *kvm_regs;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003773
Sasha Levinff5c2c02011-12-04 19:36:29 +02003774 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
3775 if (IS_ERR(kvm_regs)) {
3776 r = PTR_ERR(kvm_regs);
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003777 goto out;
Sasha Levinff5c2c02011-12-04 19:36:29 +02003778 }
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003779 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003780 kfree(kvm_regs);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003781 break;
3782 }
3783 case KVM_GET_SREGS: {
Ben Gardonb12ce362019-02-11 11:02:49 -08003784 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
3785 GFP_KERNEL_ACCOUNT);
Dave Hansenfa3795a2008-08-11 10:01:46 -07003786 r = -ENOMEM;
3787 if (!kvm_sregs)
3788 goto out;
3789 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003790 if (r)
3791 goto out;
3792 r = -EFAULT;
Dave Hansenfa3795a2008-08-11 10:01:46 -07003793 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
Avi Kivity6aa8b732006-12-10 02:21:36 -08003794 goto out;
3795 r = 0;
3796 break;
3797 }
3798 case KVM_SET_SREGS: {
Sasha Levinff5c2c02011-12-04 19:36:29 +02003799 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
3800 if (IS_ERR(kvm_sregs)) {
3801 r = PTR_ERR(kvm_sregs);
Guo Chao18595412012-11-02 18:33:21 +08003802 kvm_sregs = NULL;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003803 goto out;
Sasha Levinff5c2c02011-12-04 19:36:29 +02003804 }
Dave Hansenfa3795a2008-08-11 10:01:46 -07003805 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003806 break;
3807 }
Marcelo Tosatti62d9f0d2008-04-11 13:24:45 -03003808 case KVM_GET_MP_STATE: {
3809 struct kvm_mp_state mp_state;
3810
3811 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
3812 if (r)
3813 goto out;
3814 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003815 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
Marcelo Tosatti62d9f0d2008-04-11 13:24:45 -03003816 goto out;
3817 r = 0;
3818 break;
3819 }
3820 case KVM_SET_MP_STATE: {
3821 struct kvm_mp_state mp_state;
3822
3823 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003824 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
Marcelo Tosatti62d9f0d2008-04-11 13:24:45 -03003825 goto out;
3826 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
Marcelo Tosatti62d9f0d2008-04-11 13:24:45 -03003827 break;
3828 }
Avi Kivity6aa8b732006-12-10 02:21:36 -08003829 case KVM_TRANSLATE: {
3830 struct kvm_translation tr;
3831
3832 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003833 if (copy_from_user(&tr, argp, sizeof(tr)))
Avi Kivity6aa8b732006-12-10 02:21:36 -08003834 goto out;
Zhang Xiantao8b006792007-11-16 13:05:55 +08003835 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003836 if (r)
3837 goto out;
3838 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003839 if (copy_to_user(argp, &tr, sizeof(tr)))
Avi Kivity6aa8b732006-12-10 02:21:36 -08003840 goto out;
3841 r = 0;
3842 break;
3843 }
Jan Kiszkad0bfb942008-12-15 13:52:10 +01003844 case KVM_SET_GUEST_DEBUG: {
3845 struct kvm_guest_debug dbg;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003846
3847 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003848 if (copy_from_user(&dbg, argp, sizeof(dbg)))
Avi Kivity6aa8b732006-12-10 02:21:36 -08003849 goto out;
Jan Kiszkad0bfb942008-12-15 13:52:10 +01003850 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003851 break;
3852 }
Avi Kivity1961d272007-03-05 19:46:05 +02003853 case KVM_SET_SIGNAL_MASK: {
3854 struct kvm_signal_mask __user *sigmask_arg = argp;
3855 struct kvm_signal_mask kvm_sigmask;
3856 sigset_t sigset, *p;
3857
3858 p = NULL;
3859 if (argp) {
3860 r = -EFAULT;
3861 if (copy_from_user(&kvm_sigmask, argp,
Xiubo Li893bdbf2015-02-26 14:58:19 +08003862 sizeof(kvm_sigmask)))
Avi Kivity1961d272007-03-05 19:46:05 +02003863 goto out;
3864 r = -EINVAL;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003865 if (kvm_sigmask.len != sizeof(sigset))
Avi Kivity1961d272007-03-05 19:46:05 +02003866 goto out;
3867 r = -EFAULT;
3868 if (copy_from_user(&sigset, sigmask_arg->sigset,
Xiubo Li893bdbf2015-02-26 14:58:19 +08003869 sizeof(sigset)))
Avi Kivity1961d272007-03-05 19:46:05 +02003870 goto out;
3871 p = &sigset;
3872 }
Andi Kleen376d41f2010-06-10 13:10:47 +02003873 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
Avi Kivity1961d272007-03-05 19:46:05 +02003874 break;
3875 }
Avi Kivityb8836732007-04-01 16:34:31 +03003876 case KVM_GET_FPU: {
Ben Gardonb12ce362019-02-11 11:02:49 -08003877 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
Dave Hansenfa3795a2008-08-11 10:01:46 -07003878 r = -ENOMEM;
3879 if (!fpu)
3880 goto out;
3881 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
Avi Kivityb8836732007-04-01 16:34:31 +03003882 if (r)
3883 goto out;
3884 r = -EFAULT;
Dave Hansenfa3795a2008-08-11 10:01:46 -07003885 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
Avi Kivityb8836732007-04-01 16:34:31 +03003886 goto out;
3887 r = 0;
3888 break;
3889 }
3890 case KVM_SET_FPU: {
Sasha Levinff5c2c02011-12-04 19:36:29 +02003891 fpu = memdup_user(argp, sizeof(*fpu));
3892 if (IS_ERR(fpu)) {
3893 r = PTR_ERR(fpu);
Guo Chao18595412012-11-02 18:33:21 +08003894 fpu = NULL;
Avi Kivityb8836732007-04-01 16:34:31 +03003895 goto out;
Sasha Levinff5c2c02011-12-04 19:36:29 +02003896 }
Dave Hansenfa3795a2008-08-11 10:01:46 -07003897 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
Avi Kivityb8836732007-04-01 16:34:31 +03003898 break;
3899 }
Jing Zhangce55c042021-06-18 22:27:06 +00003900 case KVM_GET_STATS_FD: {
3901 r = kvm_vcpu_ioctl_get_stats_fd(vcpu);
3902 break;
3903 }
Avi Kivitybccf2152007-02-21 18:04:26 +02003904 default:
Carsten Otte313a3dc2007-10-11 19:16:52 +02003905 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
Avi Kivitybccf2152007-02-21 18:04:26 +02003906 }
3907out:
Christoffer Dallec7660c2017-12-04 21:35:23 +01003908 mutex_unlock(&vcpu->mutex);
Dave Hansenfa3795a2008-08-11 10:01:46 -07003909 kfree(fpu);
3910 kfree(kvm_sregs);
Avi Kivitybccf2152007-02-21 18:04:26 +02003911 return r;
3912}
3913
Christian Borntraegerde8e5d72015-02-03 09:35:15 +01003914#ifdef CONFIG_KVM_COMPAT
Alexander Graf1dda6062011-06-08 02:45:37 +02003915static long kvm_vcpu_compat_ioctl(struct file *filp,
3916 unsigned int ioctl, unsigned long arg)
3917{
3918 struct kvm_vcpu *vcpu = filp->private_data;
3919 void __user *argp = compat_ptr(arg);
3920 int r;
3921
Sean Christopherson0b8f1172021-07-02 15:04:23 -07003922 if (vcpu->kvm->mm != current->mm || vcpu->kvm->vm_bugged)
Alexander Graf1dda6062011-06-08 02:45:37 +02003923 return -EIO;
3924
3925 switch (ioctl) {
3926 case KVM_SET_SIGNAL_MASK: {
3927 struct kvm_signal_mask __user *sigmask_arg = argp;
3928 struct kvm_signal_mask kvm_sigmask;
Alexander Graf1dda6062011-06-08 02:45:37 +02003929 sigset_t sigset;
3930
3931 if (argp) {
3932 r = -EFAULT;
3933 if (copy_from_user(&kvm_sigmask, argp,
Xiubo Li893bdbf2015-02-26 14:58:19 +08003934 sizeof(kvm_sigmask)))
Alexander Graf1dda6062011-06-08 02:45:37 +02003935 goto out;
3936 r = -EINVAL;
Al Viro3968cf62017-09-03 21:45:17 -04003937 if (kvm_sigmask.len != sizeof(compat_sigset_t))
Alexander Graf1dda6062011-06-08 02:45:37 +02003938 goto out;
3939 r = -EFAULT;
Paolo Bonzini1393b4a2020-07-02 05:39:31 -04003940 if (get_compat_sigset(&sigset,
3941 (compat_sigset_t __user *)sigmask_arg->sigset))
Alexander Graf1dda6062011-06-08 02:45:37 +02003942 goto out;
Alan Cox760a9a32012-08-22 14:34:11 +01003943 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
3944 } else
3945 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
Alexander Graf1dda6062011-06-08 02:45:37 +02003946 break;
3947 }
3948 default:
3949 r = kvm_vcpu_ioctl(filp, ioctl, arg);
3950 }
3951
3952out:
3953 return r;
3954}
3955#endif
3956
Cédric Le Goatera1cd3f02019-04-18 12:39:36 +02003957static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
3958{
3959 struct kvm_device *dev = filp->private_data;
3960
3961 if (dev->ops->mmap)
3962 return dev->ops->mmap(dev, vma);
3963
3964 return -ENODEV;
3965}
3966
Scott Wood852b6d52013-04-12 14:08:42 +00003967static int kvm_device_ioctl_attr(struct kvm_device *dev,
3968 int (*accessor)(struct kvm_device *dev,
3969 struct kvm_device_attr *attr),
3970 unsigned long arg)
3971{
3972 struct kvm_device_attr attr;
3973
3974 if (!accessor)
3975 return -EPERM;
3976
3977 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
3978 return -EFAULT;
3979
3980 return accessor(dev, &attr);
3981}
3982
3983static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
3984 unsigned long arg)
3985{
3986 struct kvm_device *dev = filp->private_data;
3987
Sean Christopherson0b8f1172021-07-02 15:04:23 -07003988 if (dev->kvm->mm != current->mm || dev->kvm->vm_bugged)
Sean Christophersonddba9182019-02-15 12:48:39 -08003989 return -EIO;
3990
Scott Wood852b6d52013-04-12 14:08:42 +00003991 switch (ioctl) {
3992 case KVM_SET_DEVICE_ATTR:
3993 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
3994 case KVM_GET_DEVICE_ATTR:
3995 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
3996 case KVM_HAS_DEVICE_ATTR:
3997 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
3998 default:
3999 if (dev->ops->ioctl)
4000 return dev->ops->ioctl(dev, ioctl, arg);
4001
4002 return -ENOTTY;
4003 }
4004}
4005
Scott Wood852b6d52013-04-12 14:08:42 +00004006static int kvm_device_release(struct inode *inode, struct file *filp)
4007{
4008 struct kvm_device *dev = filp->private_data;
4009 struct kvm *kvm = dev->kvm;
4010
Cédric Le Goater2bde9b32019-04-18 12:39:41 +02004011 if (dev->ops->release) {
4012 mutex_lock(&kvm->lock);
4013 list_del(&dev->vm_node);
4014 dev->ops->release(dev);
4015 mutex_unlock(&kvm->lock);
4016 }
4017
Scott Wood852b6d52013-04-12 14:08:42 +00004018 kvm_put_kvm(kvm);
4019 return 0;
4020}
4021
4022static const struct file_operations kvm_device_fops = {
4023 .unlocked_ioctl = kvm_device_ioctl,
4024 .release = kvm_device_release,
Marc Zyngier7ddfd3e2018-06-17 10:16:21 +01004025 KVM_COMPAT(kvm_device_ioctl),
Cédric Le Goatera1cd3f02019-04-18 12:39:36 +02004026 .mmap = kvm_device_mmap,
Scott Wood852b6d52013-04-12 14:08:42 +00004027};
4028
4029struct kvm_device *kvm_device_from_filp(struct file *filp)
4030{
4031 if (filp->f_op != &kvm_device_fops)
4032 return NULL;
4033
4034 return filp->private_data;
4035}
4036
Steven Price8538cb22019-10-21 16:28:19 +01004037static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
Will Deacond60eacb2014-09-02 10:27:33 +01004038#ifdef CONFIG_KVM_MPIC
4039 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
4040 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
4041#endif
Will Deacond60eacb2014-09-02 10:27:33 +01004042};
4043
Steven Price8538cb22019-10-21 16:28:19 +01004044int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
Will Deacond60eacb2014-09-02 10:27:33 +01004045{
4046 if (type >= ARRAY_SIZE(kvm_device_ops_table))
4047 return -ENOSPC;
4048
4049 if (kvm_device_ops_table[type] != NULL)
4050 return -EEXIST;
4051
4052 kvm_device_ops_table[type] = ops;
4053 return 0;
4054}
4055
Wanpeng Li571ee1b2014-10-09 18:30:08 +08004056void kvm_unregister_device_ops(u32 type)
4057{
4058 if (kvm_device_ops_table[type] != NULL)
4059 kvm_device_ops_table[type] = NULL;
4060}
4061
Scott Wood852b6d52013-04-12 14:08:42 +00004062static int kvm_ioctl_create_device(struct kvm *kvm,
4063 struct kvm_create_device *cd)
4064{
Steven Price8538cb22019-10-21 16:28:19 +01004065 const struct kvm_device_ops *ops = NULL;
Scott Wood852b6d52013-04-12 14:08:42 +00004066 struct kvm_device *dev;
4067 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
Paolo Bonzini1d487e92019-04-11 11:16:47 +02004068 int type;
Scott Wood852b6d52013-04-12 14:08:42 +00004069 int ret;
4070
Will Deacond60eacb2014-09-02 10:27:33 +01004071 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
Scott Wood852b6d52013-04-12 14:08:42 +00004072 return -ENODEV;
Will Deacond60eacb2014-09-02 10:27:33 +01004073
Paolo Bonzini1d487e92019-04-11 11:16:47 +02004074 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
4075 ops = kvm_device_ops_table[type];
Will Deacond60eacb2014-09-02 10:27:33 +01004076 if (ops == NULL)
4077 return -ENODEV;
Scott Wood852b6d52013-04-12 14:08:42 +00004078
4079 if (test)
4080 return 0;
4081
Ben Gardonb12ce362019-02-11 11:02:49 -08004082 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
Scott Wood852b6d52013-04-12 14:08:42 +00004083 if (!dev)
4084 return -ENOMEM;
4085
4086 dev->ops = ops;
4087 dev->kvm = kvm;
Scott Wood852b6d52013-04-12 14:08:42 +00004088
Christoffer Dalla28ebea2016-08-09 19:13:01 +02004089 mutex_lock(&kvm->lock);
Paolo Bonzini1d487e92019-04-11 11:16:47 +02004090 ret = ops->create(dev, type);
Scott Wood852b6d52013-04-12 14:08:42 +00004091 if (ret < 0) {
Christoffer Dalla28ebea2016-08-09 19:13:01 +02004092 mutex_unlock(&kvm->lock);
Scott Wood852b6d52013-04-12 14:08:42 +00004093 kfree(dev);
4094 return ret;
4095 }
Christoffer Dalla28ebea2016-08-09 19:13:01 +02004096 list_add(&dev->vm_node, &kvm->devices);
4097 mutex_unlock(&kvm->lock);
Scott Wood852b6d52013-04-12 14:08:42 +00004098
Christoffer Dall023e9fd2016-08-09 19:13:00 +02004099 if (ops->init)
4100 ops->init(dev);
4101
Jann Horncfa39382019-01-26 01:54:33 +01004102 kvm_get_kvm(kvm);
Yann Droneaud24009b02013-08-24 22:14:07 +02004103 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
Scott Wood852b6d52013-04-12 14:08:42 +00004104 if (ret < 0) {
Sean Christopherson149487b2019-10-21 15:58:42 -07004105 kvm_put_kvm_no_destroy(kvm);
Christoffer Dalla28ebea2016-08-09 19:13:01 +02004106 mutex_lock(&kvm->lock);
4107 list_del(&dev->vm_node);
4108 mutex_unlock(&kvm->lock);
Dan Carpentera0f1d212016-11-30 22:21:05 +03004109 ops->destroy(dev);
Scott Wood852b6d52013-04-12 14:08:42 +00004110 return ret;
4111 }
4112
Scott Wood852b6d52013-04-12 14:08:42 +00004113 cd->fd = ret;
4114 return 0;
4115}
4116
Alexander Graf92b591a2014-07-14 18:33:08 +02004117static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
4118{
4119 switch (arg) {
4120 case KVM_CAP_USER_MEMORY:
4121 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
4122 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
Alexander Graf92b591a2014-07-14 18:33:08 +02004123 case KVM_CAP_INTERNAL_ERROR_DATA:
4124#ifdef CONFIG_HAVE_KVM_MSI
4125 case KVM_CAP_SIGNAL_MSI:
4126#endif
Paul Mackerras297e2102014-06-30 20:51:13 +10004127#ifdef CONFIG_HAVE_KVM_IRQFD
Paolo Bonzinidc9be0f2015-03-05 11:54:46 +01004128 case KVM_CAP_IRQFD:
Alexander Graf92b591a2014-07-14 18:33:08 +02004129 case KVM_CAP_IRQFD_RESAMPLE:
4130#endif
Jason Wange9ea5062015-09-15 14:41:59 +08004131 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
Alexander Graf92b591a2014-07-14 18:33:08 +02004132 case KVM_CAP_CHECK_EXTENSION_VM:
Paolo Bonzinie5d83c72017-02-16 10:40:56 +01004133 case KVM_CAP_ENABLE_CAP_VM:
David Matlackacd05782020-04-17 15:14:46 -07004134 case KVM_CAP_HALT_POLL:
Alexander Graf92b591a2014-07-14 18:33:08 +02004135 return 1;
Paolo Bonzini4b4357e2017-03-31 13:53:23 +02004136#ifdef CONFIG_KVM_MMIO
Paolo Bonzini30422552017-03-31 13:53:22 +02004137 case KVM_CAP_COALESCED_MMIO:
4138 return KVM_COALESCED_MMIO_PAGE_OFFSET;
Peng Hao0804c842018-10-14 07:09:55 +08004139 case KVM_CAP_COALESCED_PIO:
4140 return 1;
Paolo Bonzini30422552017-03-31 13:53:22 +02004141#endif
Jay Zhou3c9bd402020-02-27 09:32:27 +08004142#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4143 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
4144 return KVM_DIRTY_LOG_MANUAL_CAPS;
4145#endif
Alexander Graf92b591a2014-07-14 18:33:08 +02004146#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4147 case KVM_CAP_IRQ_ROUTING:
4148 return KVM_MAX_IRQ_ROUTES;
4149#endif
Paolo Bonzinif481b062015-05-17 17:30:37 +02004150#if KVM_ADDRESS_SPACE_NUM > 1
4151 case KVM_CAP_MULTI_ADDRESS_SPACE:
4152 return KVM_ADDRESS_SPACE_NUM;
4153#endif
Paolo Bonzinic110ae52019-03-28 17:24:03 +01004154 case KVM_CAP_NR_MEMSLOTS:
4155 return KVM_USER_MEM_SLOTS;
Peter Xufb04a1e2020-09-30 21:22:22 -04004156 case KVM_CAP_DIRTY_LOG_RING:
4157#if KVM_DIRTY_LOG_PAGE_OFFSET > 0
4158 return KVM_DIRTY_RING_MAX_ENTRIES * sizeof(struct kvm_dirty_gfn);
4159#else
4160 return 0;
4161#endif
Jing Zhangce55c042021-06-18 22:27:06 +00004162 case KVM_CAP_BINARY_STATS_FD:
4163 return 1;
Alexander Graf92b591a2014-07-14 18:33:08 +02004164 default:
4165 break;
4166 }
4167 return kvm_vm_ioctl_check_extension(kvm, arg);
4168}
4169
Peter Xufb04a1e2020-09-30 21:22:22 -04004170static int kvm_vm_ioctl_enable_dirty_log_ring(struct kvm *kvm, u32 size)
4171{
4172 int r;
4173
4174 if (!KVM_DIRTY_LOG_PAGE_OFFSET)
4175 return -EINVAL;
4176
4177 /* the size should be power of 2 */
4178 if (!size || (size & (size - 1)))
4179 return -EINVAL;
4180
4181 /* Should be bigger to keep the reserved entries, or a page */
4182 if (size < kvm_dirty_ring_get_rsvd_entries() *
4183 sizeof(struct kvm_dirty_gfn) || size < PAGE_SIZE)
4184 return -EINVAL;
4185
4186 if (size > KVM_DIRTY_RING_MAX_ENTRIES *
4187 sizeof(struct kvm_dirty_gfn))
4188 return -E2BIG;
4189
4190 /* We only allow it to set once */
4191 if (kvm->dirty_ring_size)
4192 return -EINVAL;
4193
4194 mutex_lock(&kvm->lock);
4195
4196 if (kvm->created_vcpus) {
4197 /* We don't allow to change this value after vcpu created */
4198 r = -EINVAL;
4199 } else {
4200 kvm->dirty_ring_size = size;
4201 r = 0;
4202 }
4203
4204 mutex_unlock(&kvm->lock);
4205 return r;
4206}
4207
4208static int kvm_vm_ioctl_reset_dirty_pages(struct kvm *kvm)
4209{
4210 int i;
4211 struct kvm_vcpu *vcpu;
4212 int cleared = 0;
4213
4214 if (!kvm->dirty_ring_size)
4215 return -EINVAL;
4216
4217 mutex_lock(&kvm->slots_lock);
4218
4219 kvm_for_each_vcpu(i, vcpu, kvm)
4220 cleared += kvm_dirty_ring_reset(vcpu->kvm, &vcpu->dirty_ring);
4221
4222 mutex_unlock(&kvm->slots_lock);
4223
4224 if (cleared)
4225 kvm_flush_remote_tlbs(kvm);
4226
4227 return cleared;
4228}
4229
Paolo Bonzinie5d83c72017-02-16 10:40:56 +01004230int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
4231 struct kvm_enable_cap *cap)
4232{
4233 return -EINVAL;
4234}
4235
4236static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
4237 struct kvm_enable_cap *cap)
4238{
4239 switch (cap->cap) {
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02004240#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
Jay Zhou3c9bd402020-02-27 09:32:27 +08004241 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
4242 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
4243
4244 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
4245 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
4246
4247 if (cap->flags || (cap->args[0] & ~allowed_options))
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02004248 return -EINVAL;
4249 kvm->manual_dirty_log_protect = cap->args[0];
4250 return 0;
Jay Zhou3c9bd402020-02-27 09:32:27 +08004251 }
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02004252#endif
David Matlackacd05782020-04-17 15:14:46 -07004253 case KVM_CAP_HALT_POLL: {
4254 if (cap->flags || cap->args[0] != (unsigned int)cap->args[0])
4255 return -EINVAL;
4256
4257 kvm->max_halt_poll_ns = cap->args[0];
4258 return 0;
4259 }
Peter Xufb04a1e2020-09-30 21:22:22 -04004260 case KVM_CAP_DIRTY_LOG_RING:
4261 return kvm_vm_ioctl_enable_dirty_log_ring(kvm, cap->args[0]);
Paolo Bonzinie5d83c72017-02-16 10:40:56 +01004262 default:
4263 return kvm_vm_ioctl_enable_cap(kvm, cap);
4264 }
4265}
4266
Jing Zhangfcfe1ba2021-06-18 22:27:05 +00004267static ssize_t kvm_vm_stats_read(struct file *file, char __user *user_buffer,
4268 size_t size, loff_t *offset)
4269{
4270 struct kvm *kvm = file->private_data;
4271
4272 return kvm_stats_read(kvm->stats_id, &kvm_vm_stats_header,
4273 &kvm_vm_stats_desc[0], &kvm->stat,
4274 sizeof(kvm->stat), user_buffer, size, offset);
4275}
4276
4277static const struct file_operations kvm_vm_stats_fops = {
4278 .read = kvm_vm_stats_read,
4279 .llseek = noop_llseek,
4280};
4281
4282static int kvm_vm_ioctl_get_stats_fd(struct kvm *kvm)
4283{
4284 int fd;
4285 struct file *file;
4286
4287 fd = get_unused_fd_flags(O_CLOEXEC);
4288 if (fd < 0)
4289 return fd;
4290
4291 file = anon_inode_getfile("kvm-vm-stats",
4292 &kvm_vm_stats_fops, kvm, O_RDONLY);
4293 if (IS_ERR(file)) {
4294 put_unused_fd(fd);
4295 return PTR_ERR(file);
4296 }
4297 file->f_mode |= FMODE_PREAD;
4298 fd_install(fd, file);
4299
4300 return fd;
4301}
4302
Avi Kivitybccf2152007-02-21 18:04:26 +02004303static long kvm_vm_ioctl(struct file *filp,
4304 unsigned int ioctl, unsigned long arg)
4305{
4306 struct kvm *kvm = filp->private_data;
4307 void __user *argp = (void __user *)arg;
Carsten Otte1fe779f2007-10-29 16:08:35 +01004308 int r;
Avi Kivitybccf2152007-02-21 18:04:26 +02004309
Sean Christopherson0b8f1172021-07-02 15:04:23 -07004310 if (kvm->mm != current->mm || kvm->vm_bugged)
Avi Kivity6d4e4c42007-11-21 16:41:05 +02004311 return -EIO;
Avi Kivitybccf2152007-02-21 18:04:26 +02004312 switch (ioctl) {
4313 case KVM_CREATE_VCPU:
4314 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
Avi Kivitybccf2152007-02-21 18:04:26 +02004315 break;
Paolo Bonzinie5d83c72017-02-16 10:40:56 +01004316 case KVM_ENABLE_CAP: {
4317 struct kvm_enable_cap cap;
4318
4319 r = -EFAULT;
4320 if (copy_from_user(&cap, argp, sizeof(cap)))
4321 goto out;
4322 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
4323 break;
4324 }
Izik Eidus6fc138d2007-10-09 19:20:39 +02004325 case KVM_SET_USER_MEMORY_REGION: {
4326 struct kvm_userspace_memory_region kvm_userspace_mem;
4327
4328 r = -EFAULT;
4329 if (copy_from_user(&kvm_userspace_mem, argp,
Xiubo Li893bdbf2015-02-26 14:58:19 +08004330 sizeof(kvm_userspace_mem)))
Izik Eidus6fc138d2007-10-09 19:20:39 +02004331 goto out;
4332
Takuya Yoshikawa47ae31e2013-02-27 19:43:00 +09004333 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
Avi Kivity6aa8b732006-12-10 02:21:36 -08004334 break;
4335 }
4336 case KVM_GET_DIRTY_LOG: {
4337 struct kvm_dirty_log log;
4338
4339 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08004340 if (copy_from_user(&log, argp, sizeof(log)))
Avi Kivity6aa8b732006-12-10 02:21:36 -08004341 goto out;
Avi Kivity2c6f5df2007-02-20 18:27:58 +02004342 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
Avi Kivity6aa8b732006-12-10 02:21:36 -08004343 break;
4344 }
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02004345#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4346 case KVM_CLEAR_DIRTY_LOG: {
4347 struct kvm_clear_dirty_log log;
4348
4349 r = -EFAULT;
4350 if (copy_from_user(&log, argp, sizeof(log)))
4351 goto out;
4352 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4353 break;
4354 }
4355#endif
Paolo Bonzini4b4357e2017-03-31 13:53:23 +02004356#ifdef CONFIG_KVM_MMIO
Laurent Vivier5f94c172008-05-30 16:05:54 +02004357 case KVM_REGISTER_COALESCED_MMIO: {
4358 struct kvm_coalesced_mmio_zone zone;
Xiubo Lif95ef0cd2015-02-26 14:58:23 +08004359
Laurent Vivier5f94c172008-05-30 16:05:54 +02004360 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08004361 if (copy_from_user(&zone, argp, sizeof(zone)))
Laurent Vivier5f94c172008-05-30 16:05:54 +02004362 goto out;
Laurent Vivier5f94c172008-05-30 16:05:54 +02004363 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
Laurent Vivier5f94c172008-05-30 16:05:54 +02004364 break;
4365 }
4366 case KVM_UNREGISTER_COALESCED_MMIO: {
4367 struct kvm_coalesced_mmio_zone zone;
Xiubo Lif95ef0cd2015-02-26 14:58:23 +08004368
Laurent Vivier5f94c172008-05-30 16:05:54 +02004369 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08004370 if (copy_from_user(&zone, argp, sizeof(zone)))
Laurent Vivier5f94c172008-05-30 16:05:54 +02004371 goto out;
Laurent Vivier5f94c172008-05-30 16:05:54 +02004372 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
Laurent Vivier5f94c172008-05-30 16:05:54 +02004373 break;
4374 }
4375#endif
Gregory Haskins721eecbf2009-05-20 10:30:49 -04004376 case KVM_IRQFD: {
4377 struct kvm_irqfd data;
4378
4379 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08004380 if (copy_from_user(&data, argp, sizeof(data)))
Gregory Haskins721eecbf2009-05-20 10:30:49 -04004381 goto out;
Alex Williamsond4db2932012-06-29 09:56:08 -06004382 r = kvm_irqfd(kvm, &data);
Gregory Haskins721eecbf2009-05-20 10:30:49 -04004383 break;
4384 }
Gregory Haskinsd34e6b12009-07-07 17:08:49 -04004385 case KVM_IOEVENTFD: {
4386 struct kvm_ioeventfd data;
4387
4388 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08004389 if (copy_from_user(&data, argp, sizeof(data)))
Gregory Haskinsd34e6b12009-07-07 17:08:49 -04004390 goto out;
4391 r = kvm_ioeventfd(kvm, &data);
4392 break;
4393 }
Jan Kiszka07975ad2012-03-29 21:14:12 +02004394#ifdef CONFIG_HAVE_KVM_MSI
4395 case KVM_SIGNAL_MSI: {
4396 struct kvm_msi msi;
4397
4398 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08004399 if (copy_from_user(&msi, argp, sizeof(msi)))
Jan Kiszka07975ad2012-03-29 21:14:12 +02004400 goto out;
4401 r = kvm_send_userspace_msi(kvm, &msi);
4402 break;
4403 }
4404#endif
Christoffer Dall23d43cf2012-07-24 08:51:20 -04004405#ifdef __KVM_HAVE_IRQ_LINE
4406 case KVM_IRQ_LINE_STATUS:
4407 case KVM_IRQ_LINE: {
4408 struct kvm_irq_level irq_event;
4409
4410 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08004411 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
Christoffer Dall23d43cf2012-07-24 08:51:20 -04004412 goto out;
4413
Yang Zhangaa2fbe62013-04-11 19:21:40 +08004414 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
4415 ioctl == KVM_IRQ_LINE_STATUS);
Christoffer Dall23d43cf2012-07-24 08:51:20 -04004416 if (r)
4417 goto out;
4418
4419 r = -EFAULT;
4420 if (ioctl == KVM_IRQ_LINE_STATUS) {
Xiubo Li893bdbf2015-02-26 14:58:19 +08004421 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
Christoffer Dall23d43cf2012-07-24 08:51:20 -04004422 goto out;
4423 }
4424
4425 r = 0;
4426 break;
4427 }
4428#endif
Alexander Grafaa8d5942013-04-15 21:12:53 +02004429#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
4430 case KVM_SET_GSI_ROUTING: {
4431 struct kvm_irq_routing routing;
4432 struct kvm_irq_routing __user *urouting;
Paolo Bonzinif8c1b852016-06-01 14:09:22 +02004433 struct kvm_irq_routing_entry *entries = NULL;
Alexander Grafaa8d5942013-04-15 21:12:53 +02004434
4435 r = -EFAULT;
4436 if (copy_from_user(&routing, argp, sizeof(routing)))
4437 goto out;
4438 r = -EINVAL;
David Hildenbrand5c0aea02017-04-28 17:06:20 +02004439 if (!kvm_arch_can_set_irq_routing(kvm))
4440 goto out;
Xiubo Licaf1ff22016-06-15 18:00:33 +08004441 if (routing.nr > KVM_MAX_IRQ_ROUTES)
Alexander Grafaa8d5942013-04-15 21:12:53 +02004442 goto out;
4443 if (routing.flags)
4444 goto out;
Paolo Bonzinif8c1b852016-06-01 14:09:22 +02004445 if (routing.nr) {
Paolo Bonzinif8c1b852016-06-01 14:09:22 +02004446 urouting = argp;
Denis Efremov7ec28e22020-06-03 13:11:31 +03004447 entries = vmemdup_user(urouting->entries,
4448 array_size(sizeof(*entries),
4449 routing.nr));
4450 if (IS_ERR(entries)) {
4451 r = PTR_ERR(entries);
4452 goto out;
4453 }
Paolo Bonzinif8c1b852016-06-01 14:09:22 +02004454 }
Alexander Grafaa8d5942013-04-15 21:12:53 +02004455 r = kvm_set_irq_routing(kvm, entries, routing.nr,
4456 routing.flags);
Denis Efremov7ec28e22020-06-03 13:11:31 +03004457 kvfree(entries);
Alexander Grafaa8d5942013-04-15 21:12:53 +02004458 break;
4459 }
4460#endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
Scott Wood852b6d52013-04-12 14:08:42 +00004461 case KVM_CREATE_DEVICE: {
4462 struct kvm_create_device cd;
4463
4464 r = -EFAULT;
4465 if (copy_from_user(&cd, argp, sizeof(cd)))
4466 goto out;
4467
4468 r = kvm_ioctl_create_device(kvm, &cd);
4469 if (r)
4470 goto out;
4471
4472 r = -EFAULT;
4473 if (copy_to_user(argp, &cd, sizeof(cd)))
4474 goto out;
4475
4476 r = 0;
4477 break;
4478 }
Alexander Graf92b591a2014-07-14 18:33:08 +02004479 case KVM_CHECK_EXTENSION:
4480 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
4481 break;
Peter Xufb04a1e2020-09-30 21:22:22 -04004482 case KVM_RESET_DIRTY_RINGS:
4483 r = kvm_vm_ioctl_reset_dirty_pages(kvm);
4484 break;
Jing Zhangfcfe1ba2021-06-18 22:27:05 +00004485 case KVM_GET_STATS_FD:
4486 r = kvm_vm_ioctl_get_stats_fd(kvm);
4487 break;
Avi Kivityf17abe92007-02-21 19:28:04 +02004488 default:
Carsten Otte1fe779f2007-10-29 16:08:35 +01004489 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
Avi Kivityf17abe92007-02-21 19:28:04 +02004490 }
4491out:
4492 return r;
4493}
4494
Christian Borntraegerde8e5d72015-02-03 09:35:15 +01004495#ifdef CONFIG_KVM_COMPAT
Arnd Bergmann6ff58942009-10-22 14:19:27 +02004496struct compat_kvm_dirty_log {
4497 __u32 slot;
4498 __u32 padding1;
4499 union {
4500 compat_uptr_t dirty_bitmap; /* one bit per page */
4501 __u64 padding2;
4502 };
4503};
4504
Paolo Bonzini8750f9b2021-07-27 08:43:10 -04004505struct compat_kvm_clear_dirty_log {
4506 __u32 slot;
4507 __u32 num_pages;
4508 __u64 first_page;
4509 union {
4510 compat_uptr_t dirty_bitmap; /* one bit per page */
4511 __u64 padding2;
4512 };
4513};
4514
Arnd Bergmann6ff58942009-10-22 14:19:27 +02004515static long kvm_vm_compat_ioctl(struct file *filp,
4516 unsigned int ioctl, unsigned long arg)
4517{
4518 struct kvm *kvm = filp->private_data;
4519 int r;
4520
Sean Christopherson0b8f1172021-07-02 15:04:23 -07004521 if (kvm->mm != current->mm || kvm->vm_bugged)
Arnd Bergmann6ff58942009-10-22 14:19:27 +02004522 return -EIO;
4523 switch (ioctl) {
Paolo Bonzini8750f9b2021-07-27 08:43:10 -04004524#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
4525 case KVM_CLEAR_DIRTY_LOG: {
4526 struct compat_kvm_clear_dirty_log compat_log;
4527 struct kvm_clear_dirty_log log;
4528
4529 if (copy_from_user(&compat_log, (void __user *)arg,
4530 sizeof(compat_log)))
4531 return -EFAULT;
4532 log.slot = compat_log.slot;
4533 log.num_pages = compat_log.num_pages;
4534 log.first_page = compat_log.first_page;
4535 log.padding2 = compat_log.padding2;
4536 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4537
4538 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
4539 break;
4540 }
4541#endif
Arnd Bergmann6ff58942009-10-22 14:19:27 +02004542 case KVM_GET_DIRTY_LOG: {
4543 struct compat_kvm_dirty_log compat_log;
4544 struct kvm_dirty_log log;
4545
Arnd Bergmann6ff58942009-10-22 14:19:27 +02004546 if (copy_from_user(&compat_log, (void __user *)arg,
4547 sizeof(compat_log)))
Markus Elfringf6a3b162017-01-22 11:30:21 +01004548 return -EFAULT;
Arnd Bergmann6ff58942009-10-22 14:19:27 +02004549 log.slot = compat_log.slot;
4550 log.padding1 = compat_log.padding1;
4551 log.padding2 = compat_log.padding2;
4552 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
4553
4554 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
Arnd Bergmann6ff58942009-10-22 14:19:27 +02004555 break;
4556 }
4557 default:
4558 r = kvm_vm_ioctl(filp, ioctl, arg);
4559 }
Arnd Bergmann6ff58942009-10-22 14:19:27 +02004560 return r;
4561}
4562#endif
4563
Christian Borntraeger3d3aab12008-12-02 11:17:32 +01004564static struct file_operations kvm_vm_fops = {
Avi Kivityf17abe92007-02-21 19:28:04 +02004565 .release = kvm_vm_release,
4566 .unlocked_ioctl = kvm_vm_ioctl,
Arnd Bergmann6038f372010-08-15 18:52:59 +02004567 .llseek = noop_llseek,
Marc Zyngier7ddfd3e2018-06-17 10:16:21 +01004568 KVM_COMPAT(kvm_vm_compat_ioctl),
Avi Kivityf17abe92007-02-21 19:28:04 +02004569};
4570
Nathan Tempelman54526d12021-04-08 22:32:14 +00004571bool file_is_kvm(struct file *file)
4572{
4573 return file && file->f_op == &kvm_vm_fops;
4574}
4575EXPORT_SYMBOL_GPL(file_is_kvm);
4576
Carsten Ottee08b9632012-01-04 10:25:20 +01004577static int kvm_dev_ioctl_create_vm(unsigned long type)
Avi Kivityf17abe92007-02-21 19:28:04 +02004578{
Heiko Carstensaac87632010-10-27 17:22:10 +02004579 int r;
Avi Kivityf17abe92007-02-21 19:28:04 +02004580 struct kvm *kvm;
Al Viro506cfba2016-07-14 18:54:17 +02004581 struct file *file;
Avi Kivityf17abe92007-02-21 19:28:04 +02004582
Carsten Ottee08b9632012-01-04 10:25:20 +01004583 kvm = kvm_create_vm(type);
Avi Kivityd6d28162007-06-28 08:38:16 -04004584 if (IS_ERR(kvm))
4585 return PTR_ERR(kvm);
Paolo Bonzini4b4357e2017-03-31 13:53:23 +02004586#ifdef CONFIG_KVM_MMIO
Takuya Yoshikawa6ce5a092010-03-15 22:13:30 +09004587 r = kvm_coalesced_mmio_init(kvm);
Markus Elfring78588332017-11-21 13:40:17 +01004588 if (r < 0)
4589 goto put_kvm;
Takuya Yoshikawa6ce5a092010-03-15 22:13:30 +09004590#endif
Al Viro506cfba2016-07-14 18:54:17 +02004591 r = get_unused_fd_flags(O_CLOEXEC);
Markus Elfring78588332017-11-21 13:40:17 +01004592 if (r < 0)
4593 goto put_kvm;
4594
Jing Zhangfcfe1ba2021-06-18 22:27:05 +00004595 snprintf(kvm->stats_id, sizeof(kvm->stats_id),
4596 "kvm-%d", task_pid_nr(current));
4597
Al Viro506cfba2016-07-14 18:54:17 +02004598 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
4599 if (IS_ERR(file)) {
4600 put_unused_fd(r);
Markus Elfring78588332017-11-21 13:40:17 +01004601 r = PTR_ERR(file);
4602 goto put_kvm;
Al Viro506cfba2016-07-14 18:54:17 +02004603 }
Janosch Frank536a6f82016-05-18 13:26:23 +02004604
Paolo Bonzini525df862017-06-27 15:45:09 +02004605 /*
4606 * Don't call kvm_put_kvm anymore at this point; file->f_op is
4607 * already set, with ->release() being kvm_vm_release(). In error
4608 * cases it will be called by the final fput(file) and will take
4609 * care of doing kvm_put_kvm(kvm).
4610 */
Janosch Frank536a6f82016-05-18 13:26:23 +02004611 if (kvm_create_vm_debugfs(kvm, r) < 0) {
Al Viro506cfba2016-07-14 18:54:17 +02004612 put_unused_fd(r);
4613 fput(file);
Janosch Frank536a6f82016-05-18 13:26:23 +02004614 return -ENOMEM;
4615 }
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004616 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
Avi Kivityf17abe92007-02-21 19:28:04 +02004617
Al Viro506cfba2016-07-14 18:54:17 +02004618 fd_install(r, file);
Heiko Carstensaac87632010-10-27 17:22:10 +02004619 return r;
Markus Elfring78588332017-11-21 13:40:17 +01004620
4621put_kvm:
4622 kvm_put_kvm(kvm);
4623 return r;
Avi Kivityf17abe92007-02-21 19:28:04 +02004624}
4625
4626static long kvm_dev_ioctl(struct file *filp,
4627 unsigned int ioctl, unsigned long arg)
4628{
Avi Kivity07c45a32007-03-07 13:05:38 +02004629 long r = -EINVAL;
Avi Kivityf17abe92007-02-21 19:28:04 +02004630
4631 switch (ioctl) {
4632 case KVM_GET_API_VERSION:
Avi Kivityf0fe5102007-03-07 13:11:17 +02004633 if (arg)
4634 goto out;
Avi Kivityf17abe92007-02-21 19:28:04 +02004635 r = KVM_API_VERSION;
4636 break;
4637 case KVM_CREATE_VM:
Carsten Ottee08b9632012-01-04 10:25:20 +01004638 r = kvm_dev_ioctl_create_vm(arg);
Avi Kivityf17abe92007-02-21 19:28:04 +02004639 break;
Zhang Xiantao018d00d2007-11-15 23:07:47 +08004640 case KVM_CHECK_EXTENSION:
Alexander Graf784aa3d2014-07-14 18:27:35 +02004641 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
Avi Kivity5d308f42007-03-01 17:56:20 +02004642 break;
Avi Kivity07c45a32007-03-07 13:05:38 +02004643 case KVM_GET_VCPU_MMAP_SIZE:
Avi Kivity07c45a32007-03-07 13:05:38 +02004644 if (arg)
4645 goto out;
Avi Kivityadb1ff42008-01-24 15:13:08 +02004646 r = PAGE_SIZE; /* struct kvm_run */
4647#ifdef CONFIG_X86
4648 r += PAGE_SIZE; /* pio data page */
4649#endif
Paolo Bonzini4b4357e2017-03-31 13:53:23 +02004650#ifdef CONFIG_KVM_MMIO
Laurent Vivier5f94c172008-05-30 16:05:54 +02004651 r += PAGE_SIZE; /* coalesced mmio ring page */
4652#endif
Avi Kivity07c45a32007-03-07 13:05:38 +02004653 break;
Feng(Eric) Liud4c9ff22008-04-10 08:47:53 -04004654 case KVM_TRACE_ENABLE:
4655 case KVM_TRACE_PAUSE:
4656 case KVM_TRACE_DISABLE:
Marcelo Tosatti2023a292009-06-18 11:47:28 -03004657 r = -EOPNOTSUPP;
Feng(Eric) Liud4c9ff22008-04-10 08:47:53 -04004658 break;
Avi Kivity6aa8b732006-12-10 02:21:36 -08004659 default:
Carsten Otte043405e2007-10-10 17:16:19 +02004660 return kvm_arch_dev_ioctl(filp, ioctl, arg);
Avi Kivity6aa8b732006-12-10 02:21:36 -08004661 }
4662out:
4663 return r;
4664}
4665
Avi Kivity6aa8b732006-12-10 02:21:36 -08004666static struct file_operations kvm_chardev_ops = {
Avi Kivity6aa8b732006-12-10 02:21:36 -08004667 .unlocked_ioctl = kvm_dev_ioctl,
Arnd Bergmann6038f372010-08-15 18:52:59 +02004668 .llseek = noop_llseek,
Marc Zyngier7ddfd3e2018-06-17 10:16:21 +01004669 KVM_COMPAT(kvm_dev_ioctl),
Avi Kivity6aa8b732006-12-10 02:21:36 -08004670};
4671
4672static struct miscdevice kvm_dev = {
Avi Kivitybbe44322007-03-04 13:27:36 +02004673 KVM_MINOR,
Avi Kivity6aa8b732006-12-10 02:21:36 -08004674 "kvm",
4675 &kvm_chardev_ops,
4676};
4677
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004678static void hardware_enable_nolock(void *junk)
Avi Kivity1b6c0162007-05-24 13:03:52 +03004679{
4680 int cpu = raw_smp_processor_id();
Alexander Graf10474ae2009-09-15 11:37:46 +02004681 int r;
Avi Kivity1b6c0162007-05-24 13:03:52 +03004682
Rusty Russell7f59f492008-12-07 21:25:45 +10304683 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
Avi Kivity1b6c0162007-05-24 13:03:52 +03004684 return;
Alexander Graf10474ae2009-09-15 11:37:46 +02004685
Rusty Russell7f59f492008-12-07 21:25:45 +10304686 cpumask_set_cpu(cpu, cpus_hardware_enabled);
Alexander Graf10474ae2009-09-15 11:37:46 +02004687
Radim Krčmář13a34e02014-08-28 15:13:03 +02004688 r = kvm_arch_hardware_enable();
Alexander Graf10474ae2009-09-15 11:37:46 +02004689
4690 if (r) {
4691 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4692 atomic_inc(&hardware_enable_failed);
Xiubo Li1170adc2015-02-26 14:58:26 +08004693 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
Alexander Graf10474ae2009-09-15 11:37:46 +02004694 }
Avi Kivity1b6c0162007-05-24 13:03:52 +03004695}
4696
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00004697static int kvm_starting_cpu(unsigned int cpu)
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004698{
Paolo Bonzini4a937f92013-09-10 12:58:35 +02004699 raw_spin_lock(&kvm_count_lock);
Paolo Bonzini4fa92fb2013-09-10 12:57:17 +02004700 if (kvm_usage_count)
4701 hardware_enable_nolock(NULL);
Paolo Bonzini4a937f92013-09-10 12:58:35 +02004702 raw_spin_unlock(&kvm_count_lock);
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00004703 return 0;
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004704}
4705
4706static void hardware_disable_nolock(void *junk)
Avi Kivity1b6c0162007-05-24 13:03:52 +03004707{
4708 int cpu = raw_smp_processor_id();
4709
Rusty Russell7f59f492008-12-07 21:25:45 +10304710 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
Avi Kivity1b6c0162007-05-24 13:03:52 +03004711 return;
Rusty Russell7f59f492008-12-07 21:25:45 +10304712 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
Radim Krčmář13a34e02014-08-28 15:13:03 +02004713 kvm_arch_hardware_disable();
Avi Kivity1b6c0162007-05-24 13:03:52 +03004714}
4715
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00004716static int kvm_dying_cpu(unsigned int cpu)
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004717{
Paolo Bonzini4a937f92013-09-10 12:58:35 +02004718 raw_spin_lock(&kvm_count_lock);
Paolo Bonzini4fa92fb2013-09-10 12:57:17 +02004719 if (kvm_usage_count)
4720 hardware_disable_nolock(NULL);
Paolo Bonzini4a937f92013-09-10 12:58:35 +02004721 raw_spin_unlock(&kvm_count_lock);
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00004722 return 0;
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004723}
4724
Alexander Graf10474ae2009-09-15 11:37:46 +02004725static void hardware_disable_all_nolock(void)
4726{
4727 BUG_ON(!kvm_usage_count);
4728
4729 kvm_usage_count--;
4730 if (!kvm_usage_count)
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004731 on_each_cpu(hardware_disable_nolock, NULL, 1);
Alexander Graf10474ae2009-09-15 11:37:46 +02004732}
4733
4734static void hardware_disable_all(void)
4735{
Paolo Bonzini4a937f92013-09-10 12:58:35 +02004736 raw_spin_lock(&kvm_count_lock);
Alexander Graf10474ae2009-09-15 11:37:46 +02004737 hardware_disable_all_nolock();
Paolo Bonzini4a937f92013-09-10 12:58:35 +02004738 raw_spin_unlock(&kvm_count_lock);
Alexander Graf10474ae2009-09-15 11:37:46 +02004739}
4740
4741static int hardware_enable_all(void)
4742{
4743 int r = 0;
4744
Paolo Bonzini4a937f92013-09-10 12:58:35 +02004745 raw_spin_lock(&kvm_count_lock);
Alexander Graf10474ae2009-09-15 11:37:46 +02004746
4747 kvm_usage_count++;
4748 if (kvm_usage_count == 1) {
4749 atomic_set(&hardware_enable_failed, 0);
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004750 on_each_cpu(hardware_enable_nolock, NULL, 1);
Alexander Graf10474ae2009-09-15 11:37:46 +02004751
4752 if (atomic_read(&hardware_enable_failed)) {
4753 hardware_disable_all_nolock();
4754 r = -EBUSY;
4755 }
4756 }
4757
Paolo Bonzini4a937f92013-09-10 12:58:35 +02004758 raw_spin_unlock(&kvm_count_lock);
Alexander Graf10474ae2009-09-15 11:37:46 +02004759
4760 return r;
4761}
4762
Rusty Russell9a2b85c2007-07-17 23:17:55 +10004763static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
Mike Dayd77c26f2007-10-08 09:02:08 -04004764 void *v)
Rusty Russell9a2b85c2007-07-17 23:17:55 +10004765{
Sheng Yang8e1c1812009-04-29 11:09:04 +08004766 /*
4767 * Some (well, at least mine) BIOSes hang on reboot if
4768 * in vmx root mode.
4769 *
4770 * And Intel TXT required VMX off for all cpu when system shutdown.
4771 */
Xiubo Li1170adc2015-02-26 14:58:26 +08004772 pr_info("kvm: exiting hardware virtualization\n");
Sheng Yang8e1c1812009-04-29 11:09:04 +08004773 kvm_rebooting = true;
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004774 on_each_cpu(hardware_disable_nolock, NULL, 1);
Rusty Russell9a2b85c2007-07-17 23:17:55 +10004775 return NOTIFY_OK;
4776}
4777
4778static struct notifier_block kvm_reboot_notifier = {
4779 .notifier_call = kvm_reboot,
4780 .priority = 0,
4781};
4782
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004783static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
Gregory Haskins2eeb2e92007-05-31 14:08:53 -04004784{
4785 int i;
4786
4787 for (i = 0; i < bus->dev_count; i++) {
Sasha Levin743eeb02011-07-27 16:00:48 +03004788 struct kvm_io_device *pos = bus->range[i].dev;
Gregory Haskins2eeb2e92007-05-31 14:08:53 -04004789
4790 kvm_iodevice_destructor(pos);
4791 }
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004792 kfree(bus);
Gregory Haskins2eeb2e92007-05-31 14:08:53 -04004793}
4794
Paolo Bonzinic21fbff2013-08-27 15:41:41 +02004795static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
Xiubo Li20e87b72015-02-26 14:58:25 +08004796 const struct kvm_io_range *r2)
Sasha Levin743eeb02011-07-27 16:00:48 +03004797{
Jason Wang8f4216c72015-09-15 14:41:57 +08004798 gpa_t addr1 = r1->addr;
4799 gpa_t addr2 = r2->addr;
4800
4801 if (addr1 < addr2)
Sasha Levin743eeb02011-07-27 16:00:48 +03004802 return -1;
Jason Wang8f4216c72015-09-15 14:41:57 +08004803
4804 /* If r2->len == 0, match the exact address. If r2->len != 0,
4805 * accept any overlapping write. Any order is acceptable for
4806 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
4807 * we process all of them.
4808 */
4809 if (r2->len) {
4810 addr1 += r1->len;
4811 addr2 += r2->len;
4812 }
4813
4814 if (addr1 > addr2)
Sasha Levin743eeb02011-07-27 16:00:48 +03004815 return 1;
Jason Wang8f4216c72015-09-15 14:41:57 +08004816
Sasha Levin743eeb02011-07-27 16:00:48 +03004817 return 0;
4818}
4819
Paolo Bonzinia343c9b2013-07-16 13:03:29 +02004820static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
4821{
Paolo Bonzinic21fbff2013-08-27 15:41:41 +02004822 return kvm_io_bus_cmp(p1, p2);
Paolo Bonzinia343c9b2013-07-16 13:03:29 +02004823}
4824
Geoff Levand39369f72013-04-05 19:20:30 +00004825static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
Sasha Levin743eeb02011-07-27 16:00:48 +03004826 gpa_t addr, int len)
4827{
4828 struct kvm_io_range *range, key;
4829 int off;
4830
4831 key = (struct kvm_io_range) {
4832 .addr = addr,
4833 .len = len,
4834 };
4835
4836 range = bsearch(&key, bus->range, bus->dev_count,
4837 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
4838 if (range == NULL)
4839 return -ENOENT;
4840
4841 off = range - bus->range;
4842
Paolo Bonzinic21fbff2013-08-27 15:41:41 +02004843 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
Sasha Levin743eeb02011-07-27 16:00:48 +03004844 off--;
4845
4846 return off;
4847}
4848
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004849static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
Cornelia Huck126a5af2013-07-03 16:30:53 +02004850 struct kvm_io_range *range, const void *val)
4851{
4852 int idx;
4853
4854 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4855 if (idx < 0)
4856 return -EOPNOTSUPP;
4857
4858 while (idx < bus->dev_count &&
Paolo Bonzinic21fbff2013-08-27 15:41:41 +02004859 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004860 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
Cornelia Huck126a5af2013-07-03 16:30:53 +02004861 range->len, val))
4862 return idx;
4863 idx++;
4864 }
4865
4866 return -EOPNOTSUPP;
4867}
4868
Michael S. Tsirkinbda90202009-06-29 22:24:32 +03004869/* kvm_io_bus_write - called under kvm->slots_lock */
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004870int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
Michael S. Tsirkinbda90202009-06-29 22:24:32 +03004871 int len, const void *val)
Gregory Haskins2eeb2e92007-05-31 14:08:53 -04004872{
Cornelia Huck126a5af2013-07-03 16:30:53 +02004873 struct kvm_io_bus *bus;
4874 struct kvm_io_range range;
4875 int r;
4876
4877 range = (struct kvm_io_range) {
4878 .addr = addr,
4879 .len = len,
4880 };
4881
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004882 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
David Hildenbrand90db1042017-03-23 18:24:19 +01004883 if (!bus)
4884 return -ENOMEM;
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004885 r = __kvm_io_bus_write(vcpu, bus, &range, val);
Cornelia Huck126a5af2013-07-03 16:30:53 +02004886 return r < 0 ? r : 0;
4887}
Leo Yana2420102019-02-22 16:10:09 +08004888EXPORT_SYMBOL_GPL(kvm_io_bus_write);
Cornelia Huck126a5af2013-07-03 16:30:53 +02004889
4890/* kvm_io_bus_write_cookie - called under kvm->slots_lock */
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004891int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
4892 gpa_t addr, int len, const void *val, long cookie)
Cornelia Huck126a5af2013-07-03 16:30:53 +02004893{
Lai Jiangshan90d83dc2010-04-19 17:41:23 +08004894 struct kvm_io_bus *bus;
Sasha Levin743eeb02011-07-27 16:00:48 +03004895 struct kvm_io_range range;
4896
4897 range = (struct kvm_io_range) {
4898 .addr = addr,
4899 .len = len,
4900 };
Lai Jiangshan90d83dc2010-04-19 17:41:23 +08004901
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004902 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
David Hildenbrand90db1042017-03-23 18:24:19 +01004903 if (!bus)
4904 return -ENOMEM;
Cornelia Huck126a5af2013-07-03 16:30:53 +02004905
4906 /* First try the device referenced by cookie. */
4907 if ((cookie >= 0) && (cookie < bus->dev_count) &&
Paolo Bonzinic21fbff2013-08-27 15:41:41 +02004908 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004909 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
Cornelia Huck126a5af2013-07-03 16:30:53 +02004910 val))
4911 return cookie;
4912
4913 /*
4914 * cookie contained garbage; fall back to search and return the
4915 * correct cookie value.
4916 */
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004917 return __kvm_io_bus_write(vcpu, bus, &range, val);
Cornelia Huck126a5af2013-07-03 16:30:53 +02004918}
4919
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004920static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4921 struct kvm_io_range *range, void *val)
Cornelia Huck126a5af2013-07-03 16:30:53 +02004922{
4923 int idx;
4924
4925 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
Sasha Levin743eeb02011-07-27 16:00:48 +03004926 if (idx < 0)
4927 return -EOPNOTSUPP;
4928
4929 while (idx < bus->dev_count &&
Paolo Bonzinic21fbff2013-08-27 15:41:41 +02004930 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004931 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
Cornelia Huck126a5af2013-07-03 16:30:53 +02004932 range->len, val))
4933 return idx;
Sasha Levin743eeb02011-07-27 16:00:48 +03004934 idx++;
4935 }
4936
Michael S. Tsirkinbda90202009-06-29 22:24:32 +03004937 return -EOPNOTSUPP;
4938}
Gregory Haskins2eeb2e92007-05-31 14:08:53 -04004939
Michael S. Tsirkinbda90202009-06-29 22:24:32 +03004940/* kvm_io_bus_read - called under kvm->slots_lock */
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004941int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004942 int len, void *val)
Michael S. Tsirkinbda90202009-06-29 22:24:32 +03004943{
Cornelia Huck126a5af2013-07-03 16:30:53 +02004944 struct kvm_io_bus *bus;
4945 struct kvm_io_range range;
4946 int r;
4947
4948 range = (struct kvm_io_range) {
4949 .addr = addr,
4950 .len = len,
4951 };
4952
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004953 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
David Hildenbrand90db1042017-03-23 18:24:19 +01004954 if (!bus)
4955 return -ENOMEM;
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004956 r = __kvm_io_bus_read(vcpu, bus, &range, val);
Cornelia Huck126a5af2013-07-03 16:30:53 +02004957 return r < 0 ? r : 0;
4958}
4959
Marcelo Tosatti79fac952009-12-23 14:35:26 -02004960/* Caller must hold slots_lock. */
Sasha Levin743eeb02011-07-27 16:00:48 +03004961int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
4962 int len, struct kvm_io_device *dev)
Michael S. Tsirkin6c474692009-06-29 22:24:26 +03004963{
Gal Hammerd4c67a72018-01-16 15:34:41 +02004964 int i;
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004965 struct kvm_io_bus *new_bus, *bus;
Gal Hammerd4c67a72018-01-16 15:34:41 +02004966 struct kvm_io_range range;
Gregory Haskins090b7af2009-07-07 17:08:44 -04004967
Christian Borntraeger4a12f952017-07-07 10:51:38 +02004968 bus = kvm_get_bus(kvm, bus_idx);
David Hildenbrand90db1042017-03-23 18:24:19 +01004969 if (!bus)
4970 return -ENOMEM;
4971
Amos Kong6ea34c92013-05-25 06:44:15 +08004972 /* exclude ioeventfd which is limited by maximum fd */
4973 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
Gregory Haskins090b7af2009-07-07 17:08:44 -04004974 return -ENOSPC;
4975
Gustavo A. R. Silva90952cd2019-01-30 17:07:47 +01004976 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
Ben Gardonb12ce362019-02-11 11:02:49 -08004977 GFP_KERNEL_ACCOUNT);
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004978 if (!new_bus)
4979 return -ENOMEM;
Gal Hammerd4c67a72018-01-16 15:34:41 +02004980
4981 range = (struct kvm_io_range) {
4982 .addr = addr,
4983 .len = len,
4984 .dev = dev,
4985 };
4986
4987 for (i = 0; i < bus->dev_count; i++)
4988 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
4989 break;
4990
4991 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
4992 new_bus->dev_count++;
4993 new_bus->range[i] = range;
4994 memcpy(new_bus->range + i + 1, bus->range + i,
4995 (bus->dev_count - i) * sizeof(struct kvm_io_range));
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004996 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4997 synchronize_srcu_expedited(&kvm->srcu);
4998 kfree(bus);
Gregory Haskins090b7af2009-07-07 17:08:44 -04004999
5000 return 0;
5001}
5002
Sean Christopherson5d3c4c7932021-04-12 15:20:49 -07005003int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5004 struct kvm_io_device *dev)
Gregory Haskins090b7af2009-07-07 17:08:44 -04005005{
Rustam Kovhaevf6588662020-09-07 11:55:35 -07005006 int i, j;
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02005007 struct kvm_io_bus *new_bus, *bus;
Michael S. Tsirkin6c474692009-06-29 22:24:26 +03005008
Sean Christopherson7c896d32021-04-12 15:20:50 -07005009 lockdep_assert_held(&kvm->slots_lock);
5010
Christian Borntraeger4a12f952017-07-07 10:51:38 +02005011 bus = kvm_get_bus(kvm, bus_idx);
Peter Xudf630b82017-03-15 16:01:17 +08005012 if (!bus)
Sean Christopherson5d3c4c7932021-04-12 15:20:49 -07005013 return 0;
Peter Xudf630b82017-03-15 16:01:17 +08005014
Sean Christopherson7c896d32021-04-12 15:20:50 -07005015 for (i = 0; i < bus->dev_count; i++) {
Amos Konga13007162012-03-09 12:17:32 +08005016 if (bus->range[i].dev == dev) {
Gregory Haskins090b7af2009-07-07 17:08:44 -04005017 break;
5018 }
Sean Christopherson7c896d32021-04-12 15:20:50 -07005019 }
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02005020
David Hildenbrand90db1042017-03-23 18:24:19 +01005021 if (i == bus->dev_count)
Sean Christopherson5d3c4c7932021-04-12 15:20:49 -07005022 return 0;
Amos Konga13007162012-03-09 12:17:32 +08005023
Gustavo A. R. Silva90952cd2019-01-30 17:07:47 +01005024 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
Ben Gardonb12ce362019-02-11 11:02:49 -08005025 GFP_KERNEL_ACCOUNT);
Rustam Kovhaevf6588662020-09-07 11:55:35 -07005026 if (new_bus) {
Rustam Kovhaev871c4332020-09-18 05:05:00 -07005027 memcpy(new_bus, bus, struct_size(bus, range, i));
Rustam Kovhaevf6588662020-09-07 11:55:35 -07005028 new_bus->dev_count--;
5029 memcpy(new_bus->range + i, bus->range + i + 1,
Rustam Kovhaev871c4332020-09-18 05:05:00 -07005030 flex_array_size(new_bus, range, new_bus->dev_count - i));
Sean Christopherson2ee37572021-04-12 15:20:48 -07005031 }
5032
5033 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
5034 synchronize_srcu_expedited(&kvm->srcu);
5035
5036 /* Destroy the old bus _after_ installing the (null) bus. */
5037 if (!new_bus) {
David Hildenbrand90db1042017-03-23 18:24:19 +01005038 pr_err("kvm: failed to shrink bus, removing it completely\n");
Rustam Kovhaevf6588662020-09-07 11:55:35 -07005039 for (j = 0; j < bus->dev_count; j++) {
5040 if (j == i)
5041 continue;
5042 kvm_iodevice_destructor(bus->range[j].dev);
5043 }
David Hildenbrand90db1042017-03-23 18:24:19 +01005044 }
Amos Konga13007162012-03-09 12:17:32 +08005045
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02005046 kfree(bus);
Sean Christopherson5d3c4c7932021-04-12 15:20:49 -07005047 return new_bus ? 0 : -ENOMEM;
Gregory Haskins2eeb2e92007-05-31 14:08:53 -04005048}
5049
Andre Przywara8a39d002016-07-15 12:43:26 +01005050struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
5051 gpa_t addr)
5052{
5053 struct kvm_io_bus *bus;
5054 int dev_idx, srcu_idx;
5055 struct kvm_io_device *iodev = NULL;
5056
5057 srcu_idx = srcu_read_lock(&kvm->srcu);
5058
5059 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
David Hildenbrand90db1042017-03-23 18:24:19 +01005060 if (!bus)
5061 goto out_unlock;
Andre Przywara8a39d002016-07-15 12:43:26 +01005062
5063 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
5064 if (dev_idx < 0)
5065 goto out_unlock;
5066
5067 iodev = bus->range[dev_idx].dev;
5068
5069out_unlock:
5070 srcu_read_unlock(&kvm->srcu, srcu_idx);
5071
5072 return iodev;
5073}
5074EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
5075
Janosch Frank536a6f82016-05-18 13:26:23 +02005076static int kvm_debugfs_open(struct inode *inode, struct file *file,
5077 int (*get)(void *, u64 *), int (*set)(void *, u64),
5078 const char *fmt)
5079{
5080 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5081 inode->i_private;
5082
Peter Xu605c7132021-06-25 11:32:07 -04005083 /*
5084 * The debugfs files are a reference to the kvm struct which
5085 * is still valid when kvm_destroy_vm is called. kvm_get_kvm_safe
5086 * avoids the race between open and the removal of the debugfs directory.
Janosch Frank536a6f82016-05-18 13:26:23 +02005087 */
Peter Xu605c7132021-06-25 11:32:07 -04005088 if (!kvm_get_kvm_safe(stat_data->kvm))
Janosch Frank536a6f82016-05-18 13:26:23 +02005089 return -ENOENT;
5090
Paolo Bonzini833b45d2019-09-30 18:48:44 +02005091 if (simple_attr_open(inode, file, get,
Jing Zhangbc9e9e62021-06-23 17:28:46 -04005092 kvm_stats_debugfs_mode(stat_data->desc) & 0222
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005093 ? set : NULL,
5094 fmt)) {
Janosch Frank536a6f82016-05-18 13:26:23 +02005095 kvm_put_kvm(stat_data->kvm);
5096 return -ENOMEM;
5097 }
5098
5099 return 0;
5100}
5101
5102static int kvm_debugfs_release(struct inode *inode, struct file *file)
5103{
5104 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
5105 inode->i_private;
5106
5107 simple_attr_release(inode, file);
5108 kvm_put_kvm(stat_data->kvm);
5109
5110 return 0;
5111}
5112
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005113static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
Janosch Frank536a6f82016-05-18 13:26:23 +02005114{
Jing Zhangbc9e9e62021-06-23 17:28:46 -04005115 *val = *(u64 *)((void *)(&kvm->stat) + offset);
Janosch Frank536a6f82016-05-18 13:26:23 +02005116
5117 return 0;
5118}
5119
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005120static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11005121{
Jing Zhangbc9e9e62021-06-23 17:28:46 -04005122 *(u64 *)((void *)(&kvm->stat) + offset) = 0;
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11005123
5124 return 0;
5125}
5126
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005127static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
Janosch Frank536a6f82016-05-18 13:26:23 +02005128{
5129 int i;
Janosch Frank536a6f82016-05-18 13:26:23 +02005130 struct kvm_vcpu *vcpu;
5131
5132 *val = 0;
5133
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005134 kvm_for_each_vcpu(i, vcpu, kvm)
Jing Zhangbc9e9e62021-06-23 17:28:46 -04005135 *val += *(u64 *)((void *)(&vcpu->stat) + offset);
Janosch Frank536a6f82016-05-18 13:26:23 +02005136
5137 return 0;
5138}
5139
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005140static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11005141{
5142 int i;
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11005143 struct kvm_vcpu *vcpu;
5144
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005145 kvm_for_each_vcpu(i, vcpu, kvm)
Jing Zhangbc9e9e62021-06-23 17:28:46 -04005146 *(u64 *)((void *)(&vcpu->stat) + offset) = 0;
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005147
5148 return 0;
5149}
5150
5151static int kvm_stat_data_get(void *data, u64 *val)
5152{
5153 int r = -EFAULT;
5154 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
5155
Jing Zhangbc9e9e62021-06-23 17:28:46 -04005156 switch (stat_data->kind) {
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005157 case KVM_STAT_VM:
5158 r = kvm_get_stat_per_vm(stat_data->kvm,
Jing Zhangbc9e9e62021-06-23 17:28:46 -04005159 stat_data->desc->desc.offset, val);
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005160 break;
5161 case KVM_STAT_VCPU:
5162 r = kvm_get_stat_per_vcpu(stat_data->kvm,
Jing Zhangbc9e9e62021-06-23 17:28:46 -04005163 stat_data->desc->desc.offset, val);
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005164 break;
5165 }
5166
5167 return r;
5168}
5169
5170static int kvm_stat_data_clear(void *data, u64 val)
5171{
5172 int r = -EFAULT;
5173 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
5174
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11005175 if (val)
5176 return -EINVAL;
5177
Jing Zhangbc9e9e62021-06-23 17:28:46 -04005178 switch (stat_data->kind) {
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005179 case KVM_STAT_VM:
5180 r = kvm_clear_stat_per_vm(stat_data->kvm,
Jing Zhangbc9e9e62021-06-23 17:28:46 -04005181 stat_data->desc->desc.offset);
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005182 break;
5183 case KVM_STAT_VCPU:
5184 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
Jing Zhangbc9e9e62021-06-23 17:28:46 -04005185 stat_data->desc->desc.offset);
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005186 break;
5187 }
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11005188
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005189 return r;
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11005190}
5191
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005192static int kvm_stat_data_open(struct inode *inode, struct file *file)
Janosch Frank536a6f82016-05-18 13:26:23 +02005193{
5194 __simple_attr_check_format("%llu\n", 0ull);
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005195 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
5196 kvm_stat_data_clear, "%llu\n");
Janosch Frank536a6f82016-05-18 13:26:23 +02005197}
5198
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005199static const struct file_operations stat_fops_per_vm = {
5200 .owner = THIS_MODULE,
5201 .open = kvm_stat_data_open,
Janosch Frank536a6f82016-05-18 13:26:23 +02005202 .release = kvm_debugfs_release,
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005203 .read = simple_attr_read,
5204 .write = simple_attr_write,
5205 .llseek = no_llseek,
Janosch Frank536a6f82016-05-18 13:26:23 +02005206};
5207
Christoph Hellwig8b88b092008-02-08 04:20:26 -08005208static int vm_stat_get(void *_offset, u64 *val)
Avi Kivityba1389b2007-11-18 16:24:12 +02005209{
5210 unsigned offset = (long)_offset;
Avi Kivityba1389b2007-11-18 16:24:12 +02005211 struct kvm *kvm;
Janosch Frank536a6f82016-05-18 13:26:23 +02005212 u64 tmp_val;
Avi Kivityba1389b2007-11-18 16:24:12 +02005213
Christoph Hellwig8b88b092008-02-08 04:20:26 -08005214 *val = 0;
Junaid Shahid0d9ce162019-01-03 17:14:28 -08005215 mutex_lock(&kvm_lock);
Janosch Frank536a6f82016-05-18 13:26:23 +02005216 list_for_each_entry(kvm, &vm_list, vm_list) {
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005217 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
Janosch Frank536a6f82016-05-18 13:26:23 +02005218 *val += tmp_val;
5219 }
Junaid Shahid0d9ce162019-01-03 17:14:28 -08005220 mutex_unlock(&kvm_lock);
Christoph Hellwig8b88b092008-02-08 04:20:26 -08005221 return 0;
Avi Kivityba1389b2007-11-18 16:24:12 +02005222}
5223
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11005224static int vm_stat_clear(void *_offset, u64 val)
5225{
5226 unsigned offset = (long)_offset;
5227 struct kvm *kvm;
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11005228
5229 if (val)
5230 return -EINVAL;
5231
Junaid Shahid0d9ce162019-01-03 17:14:28 -08005232 mutex_lock(&kvm_lock);
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11005233 list_for_each_entry(kvm, &vm_list, vm_list) {
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005234 kvm_clear_stat_per_vm(kvm, offset);
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11005235 }
Junaid Shahid0d9ce162019-01-03 17:14:28 -08005236 mutex_unlock(&kvm_lock);
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11005237
5238 return 0;
5239}
5240
5241DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
Jing Zhangbc9e9e62021-06-23 17:28:46 -04005242DEFINE_SIMPLE_ATTRIBUTE(vm_stat_readonly_fops, vm_stat_get, NULL, "%llu\n");
Avi Kivityba1389b2007-11-18 16:24:12 +02005243
Christoph Hellwig8b88b092008-02-08 04:20:26 -08005244static int vcpu_stat_get(void *_offset, u64 *val)
Avi Kivity1165f5f2007-04-19 17:27:43 +03005245{
5246 unsigned offset = (long)_offset;
Avi Kivity1165f5f2007-04-19 17:27:43 +03005247 struct kvm *kvm;
Janosch Frank536a6f82016-05-18 13:26:23 +02005248 u64 tmp_val;
Avi Kivity1165f5f2007-04-19 17:27:43 +03005249
Christoph Hellwig8b88b092008-02-08 04:20:26 -08005250 *val = 0;
Junaid Shahid0d9ce162019-01-03 17:14:28 -08005251 mutex_lock(&kvm_lock);
Janosch Frank536a6f82016-05-18 13:26:23 +02005252 list_for_each_entry(kvm, &vm_list, vm_list) {
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005253 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
Janosch Frank536a6f82016-05-18 13:26:23 +02005254 *val += tmp_val;
5255 }
Junaid Shahid0d9ce162019-01-03 17:14:28 -08005256 mutex_unlock(&kvm_lock);
Christoph Hellwig8b88b092008-02-08 04:20:26 -08005257 return 0;
Avi Kivity1165f5f2007-04-19 17:27:43 +03005258}
5259
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11005260static int vcpu_stat_clear(void *_offset, u64 val)
5261{
5262 unsigned offset = (long)_offset;
5263 struct kvm *kvm;
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11005264
5265 if (val)
5266 return -EINVAL;
5267
Junaid Shahid0d9ce162019-01-03 17:14:28 -08005268 mutex_lock(&kvm_lock);
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11005269 list_for_each_entry(kvm, &vm_list, vm_list) {
Milan Pandurov09cbcef2019-12-13 14:07:21 +01005270 kvm_clear_stat_per_vcpu(kvm, offset);
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11005271 }
Junaid Shahid0d9ce162019-01-03 17:14:28 -08005272 mutex_unlock(&kvm_lock);
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11005273
5274 return 0;
5275}
5276
5277DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
5278 "%llu\n");
Jing Zhangbc9e9e62021-06-23 17:28:46 -04005279DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_readonly_fops, vcpu_stat_get, NULL, "%llu\n");
Avi Kivity1165f5f2007-04-19 17:27:43 +03005280
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02005281static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
5282{
5283 struct kobj_uevent_env *env;
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02005284 unsigned long long created, active;
5285
5286 if (!kvm_dev.this_device || !kvm)
5287 return;
5288
Junaid Shahid0d9ce162019-01-03 17:14:28 -08005289 mutex_lock(&kvm_lock);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02005290 if (type == KVM_EVENT_CREATE_VM) {
5291 kvm_createvm_count++;
5292 kvm_active_vms++;
5293 } else if (type == KVM_EVENT_DESTROY_VM) {
5294 kvm_active_vms--;
5295 }
5296 created = kvm_createvm_count;
5297 active = kvm_active_vms;
Junaid Shahid0d9ce162019-01-03 17:14:28 -08005298 mutex_unlock(&kvm_lock);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02005299
Ben Gardonb12ce362019-02-11 11:02:49 -08005300 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02005301 if (!env)
5302 return;
5303
5304 add_uevent_var(env, "CREATED=%llu", created);
5305 add_uevent_var(env, "COUNT=%llu", active);
5306
Claudio Imbrendafdeaf7e2017-07-24 13:40:03 +02005307 if (type == KVM_EVENT_CREATE_VM) {
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02005308 add_uevent_var(env, "EVENT=create");
Claudio Imbrendafdeaf7e2017-07-24 13:40:03 +02005309 kvm->userspace_pid = task_pid_nr(current);
5310 } else if (type == KVM_EVENT_DESTROY_VM) {
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02005311 add_uevent_var(env, "EVENT=destroy");
Claudio Imbrendafdeaf7e2017-07-24 13:40:03 +02005312 }
5313 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02005314
Paolo Bonzini85cd39a2021-08-04 05:28:52 -04005315 if (kvm->debugfs_dentry) {
Ben Gardonb12ce362019-02-11 11:02:49 -08005316 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02005317
Claudio Imbrendafdeaf7e2017-07-24 13:40:03 +02005318 if (p) {
5319 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
5320 if (!IS_ERR(tmp))
5321 add_uevent_var(env, "STATS_PATH=%s", tmp);
5322 kfree(p);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02005323 }
5324 }
5325 /* no need for checks, since we are adding at most only 5 keys */
5326 env->envp[env->envp_idx++] = NULL;
5327 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
5328 kfree(env);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02005329}
5330
Greg Kroah-Hartman929f45e2018-05-29 18:22:04 +02005331static void kvm_init_debug(void)
Avi Kivity6aa8b732006-12-10 02:21:36 -08005332{
Jing Zhangbc9e9e62021-06-23 17:28:46 -04005333 const struct file_operations *fops;
5334 const struct _kvm_stats_desc *pdesc;
5335 int i;
Avi Kivity6aa8b732006-12-10 02:21:36 -08005336
Hollis Blanchard76f7c872008-04-15 16:05:42 -05005337 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
Hamo4f69b682011-12-15 14:23:16 +08005338
Jing Zhangbc9e9e62021-06-23 17:28:46 -04005339 for (i = 0; i < kvm_vm_stats_header.num_desc; ++i) {
5340 pdesc = &kvm_vm_stats_desc[i];
5341 if (kvm_stats_debugfs_mode(pdesc) & 0222)
5342 fops = &vm_stat_fops;
5343 else
5344 fops = &vm_stat_readonly_fops;
5345 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5346 kvm_debugfs_dir,
5347 (void *)(long)pdesc->desc.offset, fops);
5348 }
5349
5350 for (i = 0; i < kvm_vcpu_stats_header.num_desc; ++i) {
5351 pdesc = &kvm_vcpu_stats_desc[i];
5352 if (kvm_stats_debugfs_mode(pdesc) & 0222)
5353 fops = &vcpu_stat_fops;
5354 else
5355 fops = &vcpu_stat_readonly_fops;
5356 debugfs_create_file(pdesc->name, kvm_stats_debugfs_mode(pdesc),
5357 kvm_debugfs_dir,
5358 (void *)(long)pdesc->desc.offset, fops);
Hamo4f69b682011-12-15 14:23:16 +08005359 }
Avi Kivity6aa8b732006-12-10 02:21:36 -08005360}
5361
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +01005362static int kvm_suspend(void)
Avi Kivity59ae6c62007-02-12 00:54:48 -08005363{
Alexander Graf10474ae2009-09-15 11:37:46 +02005364 if (kvm_usage_count)
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09005365 hardware_disable_nolock(NULL);
Avi Kivity59ae6c62007-02-12 00:54:48 -08005366 return 0;
5367}
5368
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +01005369static void kvm_resume(void)
Avi Kivity59ae6c62007-02-12 00:54:48 -08005370{
Zachary Amsdenca84d1a2010-08-19 22:07:28 -10005371 if (kvm_usage_count) {
Wanpeng Li2eb06c32019-05-17 16:49:49 +08005372#ifdef CONFIG_LOCKDEP
5373 WARN_ON(lockdep_is_held(&kvm_count_lock));
5374#endif
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09005375 hardware_enable_nolock(NULL);
Zachary Amsdenca84d1a2010-08-19 22:07:28 -10005376 }
Avi Kivity59ae6c62007-02-12 00:54:48 -08005377}
5378
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +01005379static struct syscore_ops kvm_syscore_ops = {
Avi Kivity59ae6c62007-02-12 00:54:48 -08005380 .suspend = kvm_suspend,
5381 .resume = kvm_resume,
5382};
5383
Avi Kivity15ad7142007-07-11 18:17:21 +03005384static inline
5385struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
5386{
5387 return container_of(pn, struct kvm_vcpu, preempt_notifier);
5388}
5389
5390static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
5391{
5392 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
Xiubo Lif95ef0cd2015-02-26 14:58:23 +08005393
Wanpeng Li046ddee2019-08-01 11:30:14 +08005394 WRITE_ONCE(vcpu->preempted, false);
Wanpeng Lid73eb572019-07-18 19:39:06 +08005395 WRITE_ONCE(vcpu->ready, false);
Avi Kivity15ad7142007-07-11 18:17:21 +03005396
Paolo Bonzini7495e222020-01-09 09:57:19 -05005397 __this_cpu_write(kvm_running_vcpu, vcpu);
Radim Krčmáře790d9e2014-08-21 18:08:05 +02005398 kvm_arch_sched_in(vcpu, cpu);
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +08005399 kvm_arch_vcpu_load(vcpu, cpu);
Avi Kivity15ad7142007-07-11 18:17:21 +03005400}
5401
5402static void kvm_sched_out(struct preempt_notifier *pn,
5403 struct task_struct *next)
5404{
5405 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
5406
Peter Zijlstra3ba9f932021-06-11 10:28:13 +02005407 if (current->on_rq) {
Wanpeng Li046ddee2019-08-01 11:30:14 +08005408 WRITE_ONCE(vcpu->preempted, true);
Wanpeng Lid73eb572019-07-18 19:39:06 +08005409 WRITE_ONCE(vcpu->ready, true);
5410 }
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +08005411 kvm_arch_vcpu_put(vcpu);
Paolo Bonzini7495e222020-01-09 09:57:19 -05005412 __this_cpu_write(kvm_running_vcpu, NULL);
5413}
5414
5415/**
5416 * kvm_get_running_vcpu - get the vcpu running on the current CPU.
Marc Zyngier1f03b2b2020-02-07 16:34:10 +00005417 *
5418 * We can disable preemption locally around accessing the per-CPU variable,
5419 * and use the resolved vcpu pointer after enabling preemption again,
5420 * because even if the current thread is migrated to another CPU, reading
5421 * the per-CPU value later will give us the same value as we update the
5422 * per-CPU variable in the preempt notifier handlers.
Paolo Bonzini7495e222020-01-09 09:57:19 -05005423 */
5424struct kvm_vcpu *kvm_get_running_vcpu(void)
5425{
Marc Zyngier1f03b2b2020-02-07 16:34:10 +00005426 struct kvm_vcpu *vcpu;
5427
5428 preempt_disable();
5429 vcpu = __this_cpu_read(kvm_running_vcpu);
5430 preempt_enable();
5431
5432 return vcpu;
Paolo Bonzini7495e222020-01-09 09:57:19 -05005433}
Wanpeng Li379a3c82020-04-28 14:23:27 +08005434EXPORT_SYMBOL_GPL(kvm_get_running_vcpu);
Paolo Bonzini7495e222020-01-09 09:57:19 -05005435
5436/**
5437 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
5438 */
5439struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
5440{
5441 return &kvm_running_vcpu;
Avi Kivity15ad7142007-07-11 18:17:21 +03005442}
5443
Sean Christophersonb9904082020-03-21 13:25:55 -07005444struct kvm_cpu_compat_check {
5445 void *opaque;
5446 int *ret;
5447};
5448
5449static void check_processor_compat(void *data)
Sean Christophersonf257d6d2019-04-19 22:18:17 -07005450{
Sean Christophersonb9904082020-03-21 13:25:55 -07005451 struct kvm_cpu_compat_check *c = data;
5452
5453 *c->ret = kvm_arch_check_processor_compat(c->opaque);
Sean Christophersonf257d6d2019-04-19 22:18:17 -07005454}
5455
Avi Kivity0ee75be2010-04-28 15:39:01 +03005456int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
Rusty Russellc16f8622007-07-30 21:12:19 +10005457 struct module *module)
Avi Kivity6aa8b732006-12-10 02:21:36 -08005458{
Sean Christophersonb9904082020-03-21 13:25:55 -07005459 struct kvm_cpu_compat_check c;
Avi Kivity6aa8b732006-12-10 02:21:36 -08005460 int r;
Yang, Sheng002c7f72007-07-31 14:23:01 +03005461 int cpu;
Avi Kivity6aa8b732006-12-10 02:21:36 -08005462
Zhang Xiantaof8c16bb2007-11-14 20:40:21 +08005463 r = kvm_arch_init(opaque);
5464 if (r)
Zhang Xiantaod23087842007-11-29 15:35:39 +08005465 goto out_fail;
Zhang Xiantaocb498ea2007-11-14 20:39:31 +08005466
Asias He7dac16c2013-05-08 10:57:29 +08005467 /*
5468 * kvm_arch_init makes sure there's at most one caller
5469 * for architectures that support multiple implementations,
5470 * like intel and amd on x86.
Paolo Bonzini36343f62016-10-26 13:35:56 +02005471 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
5472 * conflicts in case kvm is already setup for another implementation.
Asias He7dac16c2013-05-08 10:57:29 +08005473 */
Paolo Bonzini36343f62016-10-26 13:35:56 +02005474 r = kvm_irqfd_init();
5475 if (r)
5476 goto out_irqfd;
Asias He7dac16c2013-05-08 10:57:29 +08005477
Avi Kivity8437a6172009-06-06 14:52:35 -07005478 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
Rusty Russell7f59f492008-12-07 21:25:45 +10305479 r = -ENOMEM;
5480 goto out_free_0;
5481 }
5482
Sean Christophersonb9904082020-03-21 13:25:55 -07005483 r = kvm_arch_hardware_setup(opaque);
Avi Kivity6aa8b732006-12-10 02:21:36 -08005484 if (r < 0)
Miaohe Linfaf0be22019-11-23 10:45:50 +08005485 goto out_free_1;
Avi Kivity6aa8b732006-12-10 02:21:36 -08005486
Sean Christophersonb9904082020-03-21 13:25:55 -07005487 c.ret = &r;
5488 c.opaque = opaque;
Yang, Sheng002c7f72007-07-31 14:23:01 +03005489 for_each_online_cpu(cpu) {
Sean Christophersonb9904082020-03-21 13:25:55 -07005490 smp_call_function_single(cpu, check_processor_compat, &c, 1);
Yang, Sheng002c7f72007-07-31 14:23:01 +03005491 if (r < 0)
Miaohe Linfaf0be22019-11-23 10:45:50 +08005492 goto out_free_2;
Yang, Sheng002c7f72007-07-31 14:23:01 +03005493 }
5494
Thomas Gleixner73c1b412016-12-21 20:19:54 +01005495 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00005496 kvm_starting_cpu, kvm_dying_cpu);
Avi Kivity774c47f2007-02-12 00:54:47 -08005497 if (r)
Zhang Xiantaod23087842007-11-29 15:35:39 +08005498 goto out_free_2;
Avi Kivity6aa8b732006-12-10 02:21:36 -08005499 register_reboot_notifier(&kvm_reboot_notifier);
5500
Rusty Russellc16f8622007-07-30 21:12:19 +10005501 /* A kmem cache lets us meet the alignment requirements of fx_save. */
Avi Kivity0ee75be2010-04-28 15:39:01 +03005502 if (!vcpu_align)
5503 vcpu_align = __alignof__(struct kvm_vcpu);
Paolo Bonzini46515732017-10-26 15:45:46 +02005504 kvm_vcpu_cache =
5505 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
5506 SLAB_ACCOUNT,
5507 offsetof(struct kvm_vcpu, arch),
Jing Zhangce55c042021-06-18 22:27:06 +00005508 offsetofend(struct kvm_vcpu, stats_id)
5509 - offsetof(struct kvm_vcpu, arch),
Paolo Bonzini46515732017-10-26 15:45:46 +02005510 NULL);
Rusty Russellc16f8622007-07-30 21:12:19 +10005511 if (!kvm_vcpu_cache) {
5512 r = -ENOMEM;
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +01005513 goto out_free_3;
Rusty Russellc16f8622007-07-30 21:12:19 +10005514 }
5515
Gleb Natapovaf585b92010-10-14 11:22:46 +02005516 r = kvm_async_pf_init();
5517 if (r)
5518 goto out_free;
5519
Avi Kivity6aa8b732006-12-10 02:21:36 -08005520 kvm_chardev_ops.owner = module;
Christian Borntraeger3d3aab12008-12-02 11:17:32 +01005521 kvm_vm_fops.owner = module;
5522 kvm_vcpu_fops.owner = module;
Avi Kivity6aa8b732006-12-10 02:21:36 -08005523
5524 r = misc_register(&kvm_dev);
5525 if (r) {
Xiubo Li1170adc2015-02-26 14:58:26 +08005526 pr_err("kvm: misc device register failed\n");
Gleb Natapovaf585b92010-10-14 11:22:46 +02005527 goto out_unreg;
Avi Kivity6aa8b732006-12-10 02:21:36 -08005528 }
5529
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +01005530 register_syscore_ops(&kvm_syscore_ops);
5531
Avi Kivity15ad7142007-07-11 18:17:21 +03005532 kvm_preempt_ops.sched_in = kvm_sched_in;
5533 kvm_preempt_ops.sched_out = kvm_sched_out;
5534
Greg Kroah-Hartman929f45e2018-05-29 18:22:04 +02005535 kvm_init_debug();
Darrick J. Wong0ea4ed82009-10-14 16:21:00 -07005536
Paolo Bonzini3c3c29f2014-09-24 13:02:46 +02005537 r = kvm_vfio_ops_init();
5538 WARN_ON(r);
5539
Avi Kivityc7addb92007-09-16 18:58:32 +02005540 return 0;
Avi Kivity6aa8b732006-12-10 02:21:36 -08005541
Gleb Natapovaf585b92010-10-14 11:22:46 +02005542out_unreg:
5543 kvm_async_pf_deinit();
Avi Kivity6aa8b732006-12-10 02:21:36 -08005544out_free:
Rusty Russellc16f8622007-07-30 21:12:19 +10005545 kmem_cache_destroy(kvm_vcpu_cache);
Zhang Xiantaod23087842007-11-29 15:35:39 +08005546out_free_3:
Avi Kivity6aa8b732006-12-10 02:21:36 -08005547 unregister_reboot_notifier(&kvm_reboot_notifier);
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00005548 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
Zhang Xiantaod23087842007-11-29 15:35:39 +08005549out_free_2:
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +08005550 kvm_arch_hardware_unsetup();
Miaohe Linfaf0be22019-11-23 10:45:50 +08005551out_free_1:
Rusty Russell7f59f492008-12-07 21:25:45 +10305552 free_cpumask_var(cpus_hardware_enabled);
Zhang Xiantaod23087842007-11-29 15:35:39 +08005553out_free_0:
Cornelia Hucka0f155e2013-02-28 12:33:18 +01005554 kvm_irqfd_exit();
Paolo Bonzini36343f62016-10-26 13:35:56 +02005555out_irqfd:
Asias He7dac16c2013-05-08 10:57:29 +08005556 kvm_arch_exit();
5557out_fail:
Avi Kivity6aa8b732006-12-10 02:21:36 -08005558 return r;
5559}
Zhang Xiantaocb498ea2007-11-14 20:39:31 +08005560EXPORT_SYMBOL_GPL(kvm_init);
Avi Kivity6aa8b732006-12-10 02:21:36 -08005561
Zhang Xiantaocb498ea2007-11-14 20:39:31 +08005562void kvm_exit(void)
Avi Kivity6aa8b732006-12-10 02:21:36 -08005563{
Janosch Frank4bd33b52015-10-14 12:37:35 +02005564 debugfs_remove_recursive(kvm_debugfs_dir);
Avi Kivity6aa8b732006-12-10 02:21:36 -08005565 misc_deregister(&kvm_dev);
Rusty Russellc16f8622007-07-30 21:12:19 +10005566 kmem_cache_destroy(kvm_vcpu_cache);
Gleb Natapovaf585b92010-10-14 11:22:46 +02005567 kvm_async_pf_deinit();
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +01005568 unregister_syscore_ops(&kvm_syscore_ops);
Avi Kivity6aa8b732006-12-10 02:21:36 -08005569 unregister_reboot_notifier(&kvm_reboot_notifier);
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00005570 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09005571 on_each_cpu(hardware_disable_nolock, NULL, 1);
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +08005572 kvm_arch_hardware_unsetup();
Zhang Xiantaof8c16bb2007-11-14 20:40:21 +08005573 kvm_arch_exit();
Cornelia Hucka0f155e2013-02-28 12:33:18 +01005574 kvm_irqfd_exit();
Rusty Russell7f59f492008-12-07 21:25:45 +10305575 free_cpumask_var(cpus_hardware_enabled);
Wanpeng Li571ee1b2014-10-09 18:30:08 +08005576 kvm_vfio_ops_exit();
Avi Kivity6aa8b732006-12-10 02:21:36 -08005577}
Zhang Xiantaocb498ea2007-11-14 20:39:31 +08005578EXPORT_SYMBOL_GPL(kvm_exit);
Junaid Shahidc57c8042019-11-04 12:22:02 +01005579
5580struct kvm_vm_worker_thread_context {
5581 struct kvm *kvm;
5582 struct task_struct *parent;
5583 struct completion init_done;
5584 kvm_vm_thread_fn_t thread_fn;
5585 uintptr_t data;
5586 int err;
5587};
5588
5589static int kvm_vm_worker_thread(void *context)
5590{
5591 /*
5592 * The init_context is allocated on the stack of the parent thread, so
5593 * we have to locally copy anything that is needed beyond initialization
5594 */
5595 struct kvm_vm_worker_thread_context *init_context = context;
5596 struct kvm *kvm = init_context->kvm;
5597 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
5598 uintptr_t data = init_context->data;
5599 int err;
5600
5601 err = kthread_park(current);
5602 /* kthread_park(current) is never supposed to return an error */
5603 WARN_ON(err != 0);
5604 if (err)
5605 goto init_complete;
5606
5607 err = cgroup_attach_task_all(init_context->parent, current);
5608 if (err) {
5609 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
5610 __func__, err);
5611 goto init_complete;
5612 }
5613
5614 set_user_nice(current, task_nice(init_context->parent));
5615
5616init_complete:
5617 init_context->err = err;
5618 complete(&init_context->init_done);
5619 init_context = NULL;
5620
5621 if (err)
5622 return err;
5623
5624 /* Wait to be woken up by the spawner before proceeding. */
5625 kthread_parkme();
5626
5627 if (!kthread_should_stop())
5628 err = thread_fn(kvm, data);
5629
5630 return err;
5631}
5632
5633int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
5634 uintptr_t data, const char *name,
5635 struct task_struct **thread_ptr)
5636{
5637 struct kvm_vm_worker_thread_context init_context = {};
5638 struct task_struct *thread;
5639
5640 *thread_ptr = NULL;
5641 init_context.kvm = kvm;
5642 init_context.parent = current;
5643 init_context.thread_fn = thread_fn;
5644 init_context.data = data;
5645 init_completion(&init_context.init_done);
5646
5647 thread = kthread_run(kvm_vm_worker_thread, &init_context,
5648 "%s-%d", name, task_pid_nr(current));
5649 if (IS_ERR(thread))
5650 return PTR_ERR(thread);
5651
5652 /* kthread_run is never supposed to return NULL */
5653 WARN_ON(thread == NULL);
5654
5655 wait_for_completion(&init_context.init_done);
5656
5657 if (!init_context.err)
5658 *thread_ptr = thread;
5659
5660 return init_context.err;
5661}