blob: 2541a17ff1c45394e5de176ac52669b4785f5420 [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>
Avi Kivity6aa8b732006-12-10 02:21:36 -080054
Avi Kivitye4956062007-06-28 14:15:57 -040055#include <asm/processor.h>
David Matlack2ea75be2014-09-19 16:03:25 -070056#include <asm/ioctl.h>
Linus Torvalds7c0f6ba2016-12-24 11:46:01 -080057#include <linux/uaccess.h>
Avi Kivity6aa8b732006-12-10 02:21:36 -080058
Laurent Vivier5f94c172008-05-30 16:05:54 +020059#include "coalesced_mmio.h"
Gleb Natapovaf585b92010-10-14 11:22:46 +020060#include "async_pf.h"
Paolo Bonzini3c3c29f2014-09-24 13:02:46 +020061#include "vfio.h"
Laurent Vivier5f94c172008-05-30 16:05:54 +020062
Marcelo Tosatti229456f2009-06-17 09:22:14 -030063#define CREATE_TRACE_POINTS
64#include <trace/events/kvm.h>
65
Janosch Frank536a6f82016-05-18 13:26:23 +020066/* Worst case buffer size needed for holding an integer. */
67#define ITOA_MAX_LEN 12
68
Avi Kivity6aa8b732006-12-10 02:21:36 -080069MODULE_AUTHOR("Qumranet");
70MODULE_LICENSE("GPL");
71
David Hildenbrand920552b2015-09-18 12:34:53 +020072/* Architectures should define their poll value according to the halt latency */
Suraj Jitindar Singhec76d812016-10-14 11:53:19 +110073unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
Roman Storozhenko039c5d12017-06-27 12:51:18 +030074module_param(halt_poll_ns, uint, 0644);
Suraj Jitindar Singhec76d812016-10-14 11:53:19 +110075EXPORT_SYMBOL_GPL(halt_poll_ns);
Paolo Bonzinif7819512015-02-04 18:20:58 +010076
Wanpeng Liaca6ff22015-09-03 22:07:38 +080077/* Default doubles per-vcpu halt_poll_ns. */
Suraj Jitindar Singhec76d812016-10-14 11:53:19 +110078unsigned int halt_poll_ns_grow = 2;
Roman Storozhenko039c5d12017-06-27 12:51:18 +030079module_param(halt_poll_ns_grow, uint, 0644);
Suraj Jitindar Singhec76d812016-10-14 11:53:19 +110080EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
Wanpeng Liaca6ff22015-09-03 22:07:38 +080081
Nir Weiner49113d32019-01-27 12:17:15 +020082/* The start value to grow halt_poll_ns from */
83unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
84module_param(halt_poll_ns_grow_start, uint, 0644);
85EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
86
Wanpeng Liaca6ff22015-09-03 22:07:38 +080087/* Default resets per-vcpu halt_poll_ns . */
Suraj Jitindar Singhec76d812016-10-14 11:53:19 +110088unsigned int halt_poll_ns_shrink;
Roman Storozhenko039c5d12017-06-27 12:51:18 +030089module_param(halt_poll_ns_shrink, uint, 0644);
Suraj Jitindar Singhec76d812016-10-14 11:53:19 +110090EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
Wanpeng Liaca6ff22015-09-03 22:07:38 +080091
Marcelo Tosattifa40a822009-06-04 15:08:24 -030092/*
93 * Ordering of locks:
94 *
Xiubo Lib7d409d2015-02-26 14:58:24 +080095 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
Marcelo Tosattifa40a822009-06-04 15:08:24 -030096 */
97
Junaid Shahid0d9ce162019-01-03 17:14:28 -080098DEFINE_MUTEX(kvm_lock);
Paolo Bonzini4a937f92013-09-10 12:58:35 +020099static DEFINE_RAW_SPINLOCK(kvm_count_lock);
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +0800100LIST_HEAD(vm_list);
Avi Kivity133de902007-02-12 00:54:44 -0800101
Rusty Russell7f59f492008-12-07 21:25:45 +1030102static cpumask_var_t cpus_hardware_enabled;
Xiubo Lif4fee932015-02-26 14:58:21 +0800103static int kvm_usage_count;
Alexander Graf10474ae2009-09-15 11:37:46 +0200104static atomic_t hardware_enable_failed;
Avi Kivity1b6c0162007-05-24 13:03:52 +0300105
Sean Christophersonaaba2982019-12-18 13:55:16 -0800106static struct kmem_cache *kvm_vcpu_cache;
Avi Kivity1165f5f2007-04-19 17:27:43 +0300107
Avi Kivity15ad7142007-07-11 18:17:21 +0300108static __read_mostly struct preempt_ops kvm_preempt_ops;
Paolo Bonzini7495e222020-01-09 09:57:19 -0500109static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_running_vcpu);
Avi Kivity15ad7142007-07-11 18:17:21 +0300110
Hollis Blanchard76f7c872008-04-15 16:05:42 -0500111struct dentry *kvm_debugfs_dir;
Paul Mackerrase23a8082015-03-28 14:21:01 +1100112EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
Avi Kivity6aa8b732006-12-10 02:21:36 -0800113
Janosch Frank536a6f82016-05-18 13:26:23 +0200114static int kvm_debugfs_num_entries;
Milan Pandurov09cbcef2019-12-13 14:07:21 +0100115static const struct file_operations stat_fops_per_vm;
Janosch Frank536a6f82016-05-18 13:26:23 +0200116
Avi Kivitybccf2152007-02-21 18:04:26 +0200117static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
118 unsigned long arg);
Christian Borntraegerde8e5d72015-02-03 09:35:15 +0100119#ifdef CONFIG_KVM_COMPAT
Alexander Graf1dda6062011-06-08 02:45:37 +0200120static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
121 unsigned long arg);
Marc Zyngier7ddfd3e2018-06-17 10:16:21 +0100122#define KVM_COMPAT(c) .compat_ioctl = (c)
123#else
Marc Zyngier9cb09e72019-11-14 13:17:39 +0000124/*
125 * For architectures that don't implement a compat infrastructure,
126 * adopt a double line of defense:
127 * - Prevent a compat task from opening /dev/kvm
128 * - If the open has been done by a 64bit task, and the KVM fd
129 * passed to a compat task, let the ioctls fail.
130 */
Marc Zyngier7ddfd3e2018-06-17 10:16:21 +0100131static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
132 unsigned long arg) { return -EINVAL; }
Marc Zyngierb9876e62019-11-13 16:05:23 +0000133
134static int kvm_no_compat_open(struct inode *inode, struct file *file)
135{
136 return is_compat_task() ? -ENODEV : 0;
137}
138#define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
139 .open = kvm_no_compat_open
Alexander Graf1dda6062011-06-08 02:45:37 +0200140#endif
Alexander Graf10474ae2009-09-15 11:37:46 +0200141static int hardware_enable_all(void);
142static void hardware_disable_all(void);
Avi Kivitybccf2152007-02-21 18:04:26 +0200143
Marcelo Tosattie93f8a02009-12-23 14:35:24 -0200144static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
Stephen Hemminger79408762013-12-29 12:12:29 -0800145
Andi Kleen52480132014-02-08 08:51:57 +0100146__visible bool kvm_rebooting;
Avi Kivityb7c41452010-12-02 17:52:50 +0200147EXPORT_SYMBOL_GPL(kvm_rebooting);
Avi Kivity4ecac3f2008-05-13 13:23:38 +0300148
Claudio Imbrenda286de8f2017-07-12 17:56:44 +0200149#define KVM_EVENT_CREATE_VM 0
150#define KVM_EVENT_DESTROY_VM 1
151static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
152static unsigned long long kvm_createvm_count;
153static unsigned long long kvm_active_vms;
154
Eiichi Tsukatae649b3f2020-06-06 13:26:27 +0900155__weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
156 unsigned long start, unsigned long end)
Radim Krčmářb1394e72017-11-30 19:05:45 +0100157{
158}
159
Sean Christophersona78986a2019-11-11 14:12:27 -0800160bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
161{
162 /*
163 * The metadata used by is_zone_device_page() to determine whether or
164 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
165 * the device has been pinned, e.g. by get_user_pages(). WARN if the
166 * page_count() is zero to help detect bad usage of this helper.
167 */
168 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
169 return false;
170
171 return is_zone_device_page(pfn_to_page(pfn));
172}
173
Dan Williamsba049e92016-01-15 16:56:11 -0800174bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
Ben-Ami Yassourcbff90a2008-07-28 19:26:24 +0300175{
Sean Christophersona78986a2019-11-11 14:12:27 -0800176 /*
177 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
178 * perspective they are "normal" pages, albeit with slightly different
179 * usage rules.
180 */
Andrea Arcangeli11feeb42013-07-25 03:04:38 +0200181 if (pfn_valid(pfn))
Sean Christophersona78986a2019-11-11 14:12:27 -0800182 return PageReserved(pfn_to_page(pfn)) &&
Zhuang Yanying7df003c2019-10-12 11:37:31 +0800183 !is_zero_pfn(pfn) &&
Sean Christophersona78986a2019-11-11 14:12:27 -0800184 !kvm_is_zone_device_pfn(pfn);
Ben-Ami Yassourcbff90a2008-07-28 19:26:24 +0300185
186 return true;
187}
188
Sean Christopherson005ba372020-01-08 12:24:36 -0800189bool kvm_is_transparent_hugepage(kvm_pfn_t pfn)
190{
191 struct page *page = pfn_to_page(pfn);
192
193 if (!PageTransCompoundMap(page))
194 return false;
195
196 return is_transparent_hugepage(compound_head(page));
197}
198
Avi Kivity6aa8b732006-12-10 02:21:36 -0800199/*
200 * Switches to specified vcpu, until a matching vcpu_put()
201 */
Christoffer Dallec7660c2017-12-04 21:35:23 +0100202void vcpu_load(struct kvm_vcpu *vcpu)
Avi Kivity6aa8b732006-12-10 02:21:36 -0800203{
Christoffer Dallec7660c2017-12-04 21:35:23 +0100204 int cpu = get_cpu();
Paolo Bonzini7495e222020-01-09 09:57:19 -0500205
206 __this_cpu_write(kvm_running_vcpu, vcpu);
Avi Kivity15ad7142007-07-11 18:17:21 +0300207 preempt_notifier_register(&vcpu->preempt_notifier);
Carsten Otte313a3dc2007-10-11 19:16:52 +0200208 kvm_arch_vcpu_load(vcpu, cpu);
Avi Kivity15ad7142007-07-11 18:17:21 +0300209 put_cpu();
Avi Kivitybccf2152007-02-21 18:04:26 +0200210}
Jim Mattson2f1fe812016-07-08 15:36:06 -0700211EXPORT_SYMBOL_GPL(vcpu_load);
Avi Kivitybccf2152007-02-21 18:04:26 +0200212
Carsten Otte313a3dc2007-10-11 19:16:52 +0200213void vcpu_put(struct kvm_vcpu *vcpu)
Avi Kivity6aa8b732006-12-10 02:21:36 -0800214{
Avi Kivity15ad7142007-07-11 18:17:21 +0300215 preempt_disable();
Carsten Otte313a3dc2007-10-11 19:16:52 +0200216 kvm_arch_vcpu_put(vcpu);
Avi Kivity15ad7142007-07-11 18:17:21 +0300217 preempt_notifier_unregister(&vcpu->preempt_notifier);
Paolo Bonzini7495e222020-01-09 09:57:19 -0500218 __this_cpu_write(kvm_running_vcpu, NULL);
Avi Kivity15ad7142007-07-11 18:17:21 +0300219 preempt_enable();
Avi Kivity6aa8b732006-12-10 02:21:36 -0800220}
Jim Mattson2f1fe812016-07-08 15:36:06 -0700221EXPORT_SYMBOL_GPL(vcpu_put);
Avi Kivity6aa8b732006-12-10 02:21:36 -0800222
Paolo Bonzini7a97cec2017-04-27 14:33:43 +0200223/* TODO: merge with kvm_arch_vcpu_should_kick */
224static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
225{
226 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
227
228 /*
229 * We need to wait for the VCPU to reenable interrupts and get out of
230 * READING_SHADOW_PAGE_TABLES mode.
231 */
232 if (req & KVM_REQUEST_WAIT)
233 return mode != OUTSIDE_GUEST_MODE;
234
235 /*
236 * Need to kick a running VCPU, but otherwise there is nothing to do.
237 */
238 return mode == IN_GUEST_MODE;
239}
240
Avi Kivityd9e368d2007-06-07 19:18:30 +0300241static void ack_flush(void *_completed)
242{
Avi Kivityd9e368d2007-06-07 19:18:30 +0300243}
244
Paolo Bonzinib49defe2017-06-30 13:25:45 +0200245static inline bool kvm_kick_many_cpus(const struct cpumask *cpus, bool wait)
246{
247 if (unlikely(!cpus))
248 cpus = cpu_online_mask;
249
250 if (cpumask_empty(cpus))
251 return false;
252
253 smp_call_function_many(cpus, ack_flush, NULL, wait);
254 return true;
255}
256
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200257bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
Suravee Suthikulpanit54163a32020-05-06 08:17:53 -0500258 struct kvm_vcpu *except,
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200259 unsigned long *vcpu_bitmap, cpumask_var_t tmp)
Avi Kivityd9e368d2007-06-07 19:18:30 +0300260{
Avi Kivity597a5f52008-07-20 14:24:22 +0300261 int i, cpu, me;
Avi Kivityd9e368d2007-06-07 19:18:30 +0300262 struct kvm_vcpu *vcpu;
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200263 bool called;
Rusty Russell6ef7a1b2008-12-08 20:28:04 +1030264
Xiao Guangrong3cba4132011-01-12 15:41:22 +0800265 me = get_cpu();
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200266
Gleb Natapov988a2ca2009-06-09 15:56:29 +0300267 kvm_for_each_vcpu(i, vcpu, kvm) {
Suravee Suthikulpanit54163a32020-05-06 08:17:53 -0500268 if ((vcpu_bitmap && !test_bit(i, vcpu_bitmap)) ||
269 vcpu == except)
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200270 continue;
271
Xiao Guangrong3cba4132011-01-12 15:41:22 +0800272 kvm_make_request(req, vcpu);
Avi Kivityd9e368d2007-06-07 19:18:30 +0300273 cpu = vcpu->cpu;
Xiao Guangrong6b7e2d02011-01-12 15:40:31 +0800274
Radim Krčmář178f02f2017-04-26 22:32:26 +0200275 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
276 continue;
Radim Krčmář6c6e8362017-04-26 22:32:23 +0200277
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200278 if (tmp != NULL && cpu != -1 && cpu != me &&
Paolo Bonzini7a97cec2017-04-27 14:33:43 +0200279 kvm_request_needs_ipi(vcpu, req))
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200280 __cpumask_set_cpu(cpu, tmp);
Avi Kivityd9e368d2007-06-07 19:18:30 +0300281 }
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200282
283 called = kvm_kick_many_cpus(tmp, !!(req & KVM_REQUEST_WAIT));
Xiao Guangrong3cba4132011-01-12 15:41:22 +0800284 put_cpu();
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200285
286 return called;
287}
288
Suravee Suthikulpanit54163a32020-05-06 08:17:53 -0500289bool kvm_make_all_cpus_request_except(struct kvm *kvm, unsigned int req,
290 struct kvm_vcpu *except)
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200291{
292 cpumask_var_t cpus;
293 bool called;
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200294
295 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
296
Suravee Suthikulpanit54163a32020-05-06 08:17:53 -0500297 called = kvm_make_vcpus_request_mask(kvm, req, except, NULL, cpus);
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200298
Rusty Russell6ef7a1b2008-12-08 20:28:04 +1030299 free_cpumask_var(cpus);
Rusty Russell49846892008-12-08 20:26:24 +1030300 return called;
301}
302
Suravee Suthikulpanit54163a32020-05-06 08:17:53 -0500303bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
304{
305 return kvm_make_all_cpus_request_except(kvm, req, NULL);
306}
307
Mario Smarducha6d51012015-01-15 15:58:52 -0800308#ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
Rusty Russell49846892008-12-08 20:26:24 +1030309void kvm_flush_remote_tlbs(struct kvm *kvm)
310{
Lan Tianyu4ae3cb32016-03-13 11:10:28 +0800311 /*
312 * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
313 * kvm_make_all_cpus_request.
314 */
315 long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
Xiao Guangronga086f6a2014-04-17 17:06:12 +0800316
Lan Tianyu4ae3cb32016-03-13 11:10:28 +0800317 /*
318 * We want to publish modifications to the page tables before reading
319 * mode. Pairs with a memory barrier in arch-specific code.
320 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
321 * and smp_mb in walk_shadow_page_lockless_begin/end.
322 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
323 *
324 * There is already an smp_mb__after_atomic() before
325 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
326 * barrier here.
327 */
Tianyu Lanb08660e2018-07-19 08:40:17 +0000328 if (!kvm_arch_flush_remote_tlb(kvm)
329 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
Rusty Russell49846892008-12-08 20:26:24 +1030330 ++kvm->stat.remote_tlb_flush;
Xiao Guangronga086f6a2014-04-17 17:06:12 +0800331 cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
Avi Kivityd9e368d2007-06-07 19:18:30 +0300332}
Aneesh Kumar K.V2ba9f0d2013-10-07 22:17:59 +0530333EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
Mario Smarducha6d51012015-01-15 15:58:52 -0800334#endif
Avi Kivityd9e368d2007-06-07 19:18:30 +0300335
Marcelo Tosatti2e53d632008-02-20 14:47:24 -0500336void kvm_reload_remote_mmus(struct kvm *kvm)
337{
Tang Chen445b8232014-09-24 15:57:55 +0800338 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
Marcelo Tosatti2e53d632008-02-20 14:47:24 -0500339}
340
Sean Christopherson6926f952020-07-02 19:35:39 -0700341#ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
342static inline void *mmu_memory_cache_alloc_obj(struct kvm_mmu_memory_cache *mc,
343 gfp_t gfp_flags)
344{
345 gfp_flags |= mc->gfp_zero;
346
347 if (mc->kmem_cache)
348 return kmem_cache_alloc(mc->kmem_cache, gfp_flags);
349 else
350 return (void *)__get_free_page(gfp_flags);
351}
352
353int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min)
354{
355 void *obj;
356
357 if (mc->nobjs >= min)
358 return 0;
359 while (mc->nobjs < ARRAY_SIZE(mc->objects)) {
360 obj = mmu_memory_cache_alloc_obj(mc, GFP_KERNEL_ACCOUNT);
361 if (!obj)
362 return mc->nobjs >= min ? 0 : -ENOMEM;
363 mc->objects[mc->nobjs++] = obj;
364 }
365 return 0;
366}
367
368int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc)
369{
370 return mc->nobjs;
371}
372
373void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc)
374{
375 while (mc->nobjs) {
376 if (mc->kmem_cache)
377 kmem_cache_free(mc->kmem_cache, mc->objects[--mc->nobjs]);
378 else
379 free_page((unsigned long)mc->objects[--mc->nobjs]);
380 }
381}
382
383void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
384{
385 void *p;
386
387 if (WARN_ON(!mc->nobjs))
388 p = mmu_memory_cache_alloc_obj(mc, GFP_ATOMIC | __GFP_ACCOUNT);
389 else
390 p = mc->objects[--mc->nobjs];
391 BUG_ON(!p);
392 return p;
393}
394#endif
395
Sean Christopherson8bd826d2019-12-18 13:55:30 -0800396static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
Rusty Russellfb3f0f52007-07-27 17:16:56 +1000397{
Rusty Russellfb3f0f52007-07-27 17:16:56 +1000398 mutex_init(&vcpu->mutex);
399 vcpu->cpu = -1;
Rusty Russellfb3f0f52007-07-27 17:16:56 +1000400 vcpu->kvm = kvm;
401 vcpu->vcpu_id = id;
Rik van Riel34bb10b2011-02-01 09:52:41 -0500402 vcpu->pid = NULL;
Davidlohr Buesoda4ad882020-04-23 22:48:37 -0700403 rcuwait_init(&vcpu->wait);
Gleb Natapovaf585b92010-10-14 11:22:46 +0200404 kvm_async_pf_vcpu_init(vcpu);
Rusty Russellfb3f0f52007-07-27 17:16:56 +1000405
Feng Wubf9f6ac2015-09-18 22:29:55 +0800406 vcpu->pre_pcpu = -1;
407 INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
408
Raghavendra K T4c088492012-07-18 19:07:46 +0530409 kvm_vcpu_set_in_spin_loop(vcpu, false);
410 kvm_vcpu_set_dy_eligible(vcpu, false);
Raghavendra K T3a08a8f2013-03-04 23:32:07 +0530411 vcpu->preempted = false;
Wanpeng Lid73eb572019-07-18 19:39:06 +0800412 vcpu->ready = false;
Sean Christophersond5c48de2019-12-18 13:55:17 -0800413 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
Rusty Russellfb3f0f52007-07-27 17:16:56 +1000414}
Rusty Russellfb3f0f52007-07-27 17:16:56 +1000415
Sean Christopherson4543bdc2019-12-18 13:55:14 -0800416void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
417{
418 kvm_arch_vcpu_destroy(vcpu);
Sean Christophersone529ef62019-12-18 13:55:15 -0800419
Sean Christopherson9941d222019-12-18 13:55:29 -0800420 /*
421 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
422 * the vcpu->pid pointer, and at destruction time all file descriptors
423 * are already gone.
424 */
425 put_pid(rcu_dereference_protected(vcpu->pid, 1));
426
Sean Christopherson8bd826d2019-12-18 13:55:30 -0800427 free_page((unsigned long)vcpu->run);
Sean Christophersone529ef62019-12-18 13:55:15 -0800428 kmem_cache_free(kvm_vcpu_cache, vcpu);
Sean Christopherson4543bdc2019-12-18 13:55:14 -0800429}
430EXPORT_SYMBOL_GPL(kvm_vcpu_destroy);
431
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200432#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
433static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
434{
435 return container_of(mn, struct kvm, mmu_notifier);
436}
437
Eiichi Tsukatae649b3f2020-06-06 13:26:27 +0900438static void kvm_mmu_notifier_invalidate_range(struct mmu_notifier *mn,
439 struct mm_struct *mm,
440 unsigned long start, unsigned long end)
441{
442 struct kvm *kvm = mmu_notifier_to_kvm(mn);
443 int idx;
444
445 idx = srcu_read_lock(&kvm->srcu);
446 kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
447 srcu_read_unlock(&kvm->srcu, idx);
448}
449
Izik Eidus3da0dd42009-09-23 21:47:18 +0300450static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
451 struct mm_struct *mm,
452 unsigned long address,
453 pte_t pte)
454{
455 struct kvm *kvm = mmu_notifier_to_kvm(mn);
Marcelo Tosattibc6678a2009-12-23 14:35:21 -0200456 int idx;
Izik Eidus3da0dd42009-09-23 21:47:18 +0300457
Marcelo Tosattibc6678a2009-12-23 14:35:21 -0200458 idx = srcu_read_lock(&kvm->srcu);
Izik Eidus3da0dd42009-09-23 21:47:18 +0300459 spin_lock(&kvm->mmu_lock);
460 kvm->mmu_notifier_seq++;
Lan Tianyu0cf853c2018-12-06 21:21:11 +0800461
462 if (kvm_set_spte_hva(kvm, address, pte))
463 kvm_flush_remote_tlbs(kvm);
464
Izik Eidus3da0dd42009-09-23 21:47:18 +0300465 spin_unlock(&kvm->mmu_lock);
Marcelo Tosattibc6678a2009-12-23 14:35:21 -0200466 srcu_read_unlock(&kvm->srcu, idx);
Izik Eidus3da0dd42009-09-23 21:47:18 +0300467}
468
Michal Hocko93065ac2018-08-21 21:52:33 -0700469static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
Jérôme Glisse5d6527a2018-12-28 00:38:05 -0800470 const struct mmu_notifier_range *range)
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200471{
472 struct kvm *kvm = mmu_notifier_to_kvm(mn);
Marcelo Tosattibc6678a2009-12-23 14:35:21 -0200473 int need_tlb_flush = 0, idx;
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200474
Marcelo Tosattibc6678a2009-12-23 14:35:21 -0200475 idx = srcu_read_lock(&kvm->srcu);
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200476 spin_lock(&kvm->mmu_lock);
477 /*
478 * The count increase must become visible at unlock time as no
479 * spte can be established without taking the mmu_lock and
480 * count is also read inside the mmu_lock critical section.
481 */
482 kvm->mmu_notifier_count++;
Will Deaconfdfe7cb2020-08-11 11:27:24 +0100483 need_tlb_flush = kvm_unmap_hva_range(kvm, range->start, range->end,
484 range->flags);
Xiao Guangronga4ee1ca2010-11-23 11:13:00 +0800485 need_tlb_flush |= kvm->tlbs_dirty;
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200486 /* we've to flush the tlb before the pages can be freed */
487 if (need_tlb_flush)
488 kvm_flush_remote_tlbs(kvm);
Takuya Yoshikawa565f3be2012-02-10 15:28:31 +0900489
490 spin_unlock(&kvm->mmu_lock);
491 srcu_read_unlock(&kvm->srcu, idx);
Michal Hocko93065ac2018-08-21 21:52:33 -0700492
Eiichi Tsukatae649b3f2020-06-06 13:26:27 +0900493 return 0;
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200494}
495
496static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
Jérôme Glisse5d6527a2018-12-28 00:38:05 -0800497 const struct mmu_notifier_range *range)
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200498{
499 struct kvm *kvm = mmu_notifier_to_kvm(mn);
500
501 spin_lock(&kvm->mmu_lock);
502 /*
503 * This sequence increase will notify the kvm page fault that
504 * the page that is going to be mapped in the spte could have
505 * been freed.
506 */
507 kvm->mmu_notifier_seq++;
Paul Mackerrasa355aa52011-12-12 12:37:21 +0000508 smp_wmb();
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200509 /*
510 * The above sequence increase must be visible before the
Paul Mackerrasa355aa52011-12-12 12:37:21 +0000511 * below count decrease, which is ensured by the smp_wmb above
512 * in conjunction with the smp_rmb in mmu_notifier_retry().
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200513 */
514 kvm->mmu_notifier_count--;
515 spin_unlock(&kvm->mmu_lock);
516
517 BUG_ON(kvm->mmu_notifier_count < 0);
518}
519
520static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
521 struct mm_struct *mm,
Andres Lagar-Cavilla57128462014-09-22 14:54:42 -0700522 unsigned long start,
523 unsigned long end)
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200524{
525 struct kvm *kvm = mmu_notifier_to_kvm(mn);
Marcelo Tosattibc6678a2009-12-23 14:35:21 -0200526 int young, idx;
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200527
Marcelo Tosattibc6678a2009-12-23 14:35:21 -0200528 idx = srcu_read_lock(&kvm->srcu);
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200529 spin_lock(&kvm->mmu_lock);
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200530
Andres Lagar-Cavilla57128462014-09-22 14:54:42 -0700531 young = kvm_age_hva(kvm, start, end);
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200532 if (young)
533 kvm_flush_remote_tlbs(kvm);
534
Takuya Yoshikawa565f3be2012-02-10 15:28:31 +0900535 spin_unlock(&kvm->mmu_lock);
536 srcu_read_unlock(&kvm->srcu, idx);
537
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200538 return young;
539}
540
Vladimir Davydov1d7715c2015-09-09 15:35:41 -0700541static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
542 struct mm_struct *mm,
543 unsigned long start,
544 unsigned long end)
545{
546 struct kvm *kvm = mmu_notifier_to_kvm(mn);
547 int young, idx;
548
549 idx = srcu_read_lock(&kvm->srcu);
550 spin_lock(&kvm->mmu_lock);
551 /*
552 * Even though we do not flush TLB, this will still adversely
553 * affect performance on pre-Haswell Intel EPT, where there is
554 * no EPT Access Bit to clear so that we have to tear down EPT
555 * tables instead. If we find this unacceptable, we can always
556 * add a parameter to kvm_age_hva so that it effectively doesn't
557 * do anything on clear_young.
558 *
559 * Also note that currently we never issue secondary TLB flushes
560 * from clear_young, leaving this job up to the regular system
561 * cadence. If we find this inaccurate, we might come up with a
562 * more sophisticated heuristic later.
563 */
564 young = kvm_age_hva(kvm, start, end);
565 spin_unlock(&kvm->mmu_lock);
566 srcu_read_unlock(&kvm->srcu, idx);
567
568 return young;
569}
570
Andrea Arcangeli8ee53822011-01-13 15:47:10 -0800571static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
572 struct mm_struct *mm,
573 unsigned long address)
574{
575 struct kvm *kvm = mmu_notifier_to_kvm(mn);
576 int young, idx;
577
578 idx = srcu_read_lock(&kvm->srcu);
579 spin_lock(&kvm->mmu_lock);
580 young = kvm_test_age_hva(kvm, address);
581 spin_unlock(&kvm->mmu_lock);
582 srcu_read_unlock(&kvm->srcu, idx);
583
584 return young;
585}
586
Marcelo Tosatti85db06e2008-12-10 21:23:26 +0100587static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
588 struct mm_struct *mm)
589{
590 struct kvm *kvm = mmu_notifier_to_kvm(mn);
Lai Jiangshaneda2bed2010-04-20 14:29:29 +0800591 int idx;
592
593 idx = srcu_read_lock(&kvm->srcu);
Marcelo Tosatti2df72e92012-08-24 15:54:57 -0300594 kvm_arch_flush_shadow_all(kvm);
Lai Jiangshaneda2bed2010-04-20 14:29:29 +0800595 srcu_read_unlock(&kvm->srcu, idx);
Marcelo Tosatti85db06e2008-12-10 21:23:26 +0100596}
597
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200598static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
Eiichi Tsukatae649b3f2020-06-06 13:26:27 +0900599 .invalidate_range = kvm_mmu_notifier_invalidate_range,
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200600 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
601 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
602 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
Vladimir Davydov1d7715c2015-09-09 15:35:41 -0700603 .clear_young = kvm_mmu_notifier_clear_young,
Andrea Arcangeli8ee53822011-01-13 15:47:10 -0800604 .test_young = kvm_mmu_notifier_test_young,
Izik Eidus3da0dd42009-09-23 21:47:18 +0300605 .change_pte = kvm_mmu_notifier_change_pte,
Marcelo Tosatti85db06e2008-12-10 21:23:26 +0100606 .release = kvm_mmu_notifier_release,
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200607};
Avi Kivity4c07b0a2009-12-20 14:54:04 +0200608
609static int kvm_init_mmu_notifier(struct kvm *kvm)
610{
611 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
612 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
613}
614
615#else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
616
617static int kvm_init_mmu_notifier(struct kvm *kvm)
618{
619 return 0;
620}
621
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200622#endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
623
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200624static struct kvm_memslots *kvm_alloc_memslots(void)
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +0800625{
626 int i;
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200627 struct kvm_memslots *slots;
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +0800628
Ben Gardonb12ce362019-02-11 11:02:49 -0800629 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL_ACCOUNT);
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200630 if (!slots)
631 return NULL;
632
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +0800633 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
Sean Christopherson36947252020-02-18 13:07:32 -0800634 slots->id_to_index[i] = -1;
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200635
636 return slots;
637}
638
639static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
640{
641 if (!memslot->dirty_bitmap)
642 return;
643
644 kvfree(memslot->dirty_bitmap);
645 memslot->dirty_bitmap = NULL;
646}
647
Sean Christophersone96c81e2020-02-18 13:07:27 -0800648static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200649{
Sean Christophersone96c81e2020-02-18 13:07:27 -0800650 kvm_destroy_dirty_bitmap(slot);
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200651
Sean Christophersone96c81e2020-02-18 13:07:27 -0800652 kvm_arch_free_memslot(kvm, slot);
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200653
Sean Christophersone96c81e2020-02-18 13:07:27 -0800654 slot->flags = 0;
655 slot->npages = 0;
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200656}
657
658static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
659{
660 struct kvm_memory_slot *memslot;
661
662 if (!slots)
663 return;
664
665 kvm_for_each_memslot(memslot, slots)
Sean Christophersone96c81e2020-02-18 13:07:27 -0800666 kvm_free_memslot(kvm, memslot);
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200667
668 kvfree(slots);
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +0800669}
670
Janosch Frank536a6f82016-05-18 13:26:23 +0200671static void kvm_destroy_vm_debugfs(struct kvm *kvm)
672{
673 int i;
674
675 if (!kvm->debugfs_dentry)
676 return;
677
678 debugfs_remove_recursive(kvm->debugfs_dentry);
679
Luiz Capitulino9d5a1dc2016-09-07 14:47:21 -0400680 if (kvm->debugfs_stat_data) {
681 for (i = 0; i < kvm_debugfs_num_entries; i++)
682 kfree(kvm->debugfs_stat_data[i]);
683 kfree(kvm->debugfs_stat_data);
684 }
Janosch Frank536a6f82016-05-18 13:26:23 +0200685}
686
687static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
688{
689 char dir_name[ITOA_MAX_LEN * 2];
690 struct kvm_stat_data *stat_data;
691 struct kvm_stats_debugfs_item *p;
692
693 if (!debugfs_initialized())
694 return 0;
695
696 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
Greg Kroah-Hartman929f45e2018-05-29 18:22:04 +0200697 kvm->debugfs_dentry = debugfs_create_dir(dir_name, kvm_debugfs_dir);
Janosch Frank536a6f82016-05-18 13:26:23 +0200698
699 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
700 sizeof(*kvm->debugfs_stat_data),
Ben Gardonb12ce362019-02-11 11:02:49 -0800701 GFP_KERNEL_ACCOUNT);
Janosch Frank536a6f82016-05-18 13:26:23 +0200702 if (!kvm->debugfs_stat_data)
703 return -ENOMEM;
704
705 for (p = debugfs_entries; p->name; p++) {
Ben Gardonb12ce362019-02-11 11:02:49 -0800706 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
Janosch Frank536a6f82016-05-18 13:26:23 +0200707 if (!stat_data)
708 return -ENOMEM;
709
710 stat_data->kvm = kvm;
Milan Pandurov09cbcef2019-12-13 14:07:21 +0100711 stat_data->dbgfs_item = p;
Janosch Frank536a6f82016-05-18 13:26:23 +0200712 kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
Milan Pandurov09cbcef2019-12-13 14:07:21 +0100713 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
714 kvm->debugfs_dentry, stat_data,
715 &stat_fops_per_vm);
Janosch Frank536a6f82016-05-18 13:26:23 +0200716 }
717 return 0;
718}
719
Junaid Shahid1aa9b952019-11-04 20:26:00 +0100720/*
721 * Called after the VM is otherwise initialized, but just before adding it to
722 * the vm_list.
723 */
724int __weak kvm_arch_post_init_vm(struct kvm *kvm)
725{
726 return 0;
727}
728
729/*
730 * Called just after removing the VM from the vm_list, but before doing any
731 * other destruction.
732 */
733void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
734{
735}
736
Carsten Ottee08b9632012-01-04 10:25:20 +0100737static struct kvm *kvm_create_vm(unsigned long type)
Avi Kivity6aa8b732006-12-10 02:21:36 -0800738{
Jan Kiszkad89f5ef2010-11-09 17:02:49 +0100739 struct kvm *kvm = kvm_arch_alloc_vm();
Jim Mattson91219232019-10-24 16:03:26 -0700740 int r = -ENOMEM;
741 int i;
Avi Kivity6aa8b732006-12-10 02:21:36 -0800742
Jan Kiszkad89f5ef2010-11-09 17:02:49 +0100743 if (!kvm)
744 return ERR_PTR(-ENOMEM);
745
Paolo Bonzinie9ad4ec2016-03-21 10:15:25 +0100746 spin_lock_init(&kvm->mmu_lock);
Vegard Nossumf1f10072017-02-27 14:30:07 -0800747 mmgrab(current->mm);
Paolo Bonzinie9ad4ec2016-03-21 10:15:25 +0100748 kvm->mm = current->mm;
749 kvm_eventfd_init(kvm);
750 mutex_init(&kvm->lock);
751 mutex_init(&kvm->irq_lock);
752 mutex_init(&kvm->slots_lock);
Paolo Bonzinie9ad4ec2016-03-21 10:15:25 +0100753 INIT_LIST_HEAD(&kvm->devices);
754
Jim Mattson91219232019-10-24 16:03:26 -0700755 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
756
Paolo Bonzini8a441192019-11-04 12:16:49 +0100757 if (init_srcu_struct(&kvm->srcu))
758 goto out_err_no_srcu;
759 if (init_srcu_struct(&kvm->irq_srcu))
760 goto out_err_no_irq_srcu;
761
Paolo Bonzinie2d3fca2019-11-04 13:23:53 +0100762 refcount_set(&kvm->users_count, 1);
Jim Mattson91219232019-10-24 16:03:26 -0700763 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
764 struct kvm_memslots *slots = kvm_alloc_memslots();
765
766 if (!slots)
Jim Mattsona97b0e72019-10-25 13:34:58 +0200767 goto out_err_no_arch_destroy_vm;
Jim Mattson91219232019-10-24 16:03:26 -0700768 /* Generations must be different for each address space. */
769 slots->generation = i;
770 rcu_assign_pointer(kvm->memslots[i], slots);
771 }
772
773 for (i = 0; i < KVM_NR_BUSES; i++) {
774 rcu_assign_pointer(kvm->buses[i],
775 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
776 if (!kvm->buses[i])
Jim Mattsona97b0e72019-10-25 13:34:58 +0200777 goto out_err_no_arch_destroy_vm;
Jim Mattson91219232019-10-24 16:03:26 -0700778 }
779
David Matlackacd05782020-04-17 15:14:46 -0700780 kvm->max_halt_poll_ns = halt_poll_ns;
781
Carsten Ottee08b9632012-01-04 10:25:20 +0100782 r = kvm_arch_init_vm(kvm, type);
Jan Kiszkad89f5ef2010-11-09 17:02:49 +0100783 if (r)
Jim Mattsona97b0e72019-10-25 13:34:58 +0200784 goto out_err_no_arch_destroy_vm;
Alexander Graf10474ae2009-09-15 11:37:46 +0200785
786 r = hardware_enable_all();
787 if (r)
Christian Borntraeger719d93c2014-01-16 13:44:20 +0100788 goto out_err_no_disable;
Alexander Graf10474ae2009-09-15 11:37:46 +0200789
Paolo Bonzinic77dcac2014-08-06 14:24:45 +0200790#ifdef CONFIG_HAVE_KVM_IRQFD
Gleb Natapov136bdfe2009-08-24 11:54:23 +0300791 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
Avi Kivity75858a82009-01-04 17:10:50 +0200792#endif
Avi Kivity6aa8b732006-12-10 02:21:36 -0800793
Mike Waychison74b5c5b2011-06-03 13:04:53 -0700794 r = kvm_init_mmu_notifier(kvm);
795 if (r)
Junaid Shahid1aa9b952019-11-04 20:26:00 +0100796 goto out_err_no_mmu_notifier;
797
798 r = kvm_arch_post_init_vm(kvm);
799 if (r)
Mike Waychison74b5c5b2011-06-03 13:04:53 -0700800 goto out_err;
801
Junaid Shahid0d9ce162019-01-03 17:14:28 -0800802 mutex_lock(&kvm_lock);
Rusty Russell5e58cfe2007-07-23 17:08:21 +1000803 list_add(&kvm->vm_list, &vm_list);
Junaid Shahid0d9ce162019-01-03 17:14:28 -0800804 mutex_unlock(&kvm_lock);
Jan Kiszkad89f5ef2010-11-09 17:02:49 +0100805
Peter Zijlstra2ecd9d22015-07-03 18:53:58 +0200806 preempt_notifier_inc();
807
Avi Kivityf17abe92007-02-21 19:28:04 +0200808 return kvm;
Alexander Graf10474ae2009-09-15 11:37:46 +0200809
810out_err:
Junaid Shahid1aa9b952019-11-04 20:26:00 +0100811#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
812 if (kvm->mmu_notifier.ops)
813 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
814#endif
815out_err_no_mmu_notifier:
Alexander Graf10474ae2009-09-15 11:37:46 +0200816 hardware_disable_all();
Christian Borntraeger719d93c2014-01-16 13:44:20 +0100817out_err_no_disable:
Jim Mattsona97b0e72019-10-25 13:34:58 +0200818 kvm_arch_destroy_vm(kvm);
Jim Mattsona97b0e72019-10-25 13:34:58 +0200819out_err_no_arch_destroy_vm:
Paolo Bonzinie2d3fca2019-11-04 13:23:53 +0100820 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
Marcelo Tosattie93f8a02009-12-23 14:35:24 -0200821 for (i = 0; i < KVM_NR_BUSES; i++)
Paolo Bonzini3898da92017-08-02 17:55:54 +0200822 kfree(kvm_get_bus(kvm, i));
Paolo Bonzinif481b062015-05-17 17:30:37 +0200823 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
Paolo Bonzini3898da92017-08-02 17:55:54 +0200824 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
Paolo Bonzini8a441192019-11-04 12:16:49 +0100825 cleanup_srcu_struct(&kvm->irq_srcu);
826out_err_no_irq_srcu:
827 cleanup_srcu_struct(&kvm->srcu);
828out_err_no_srcu:
Jan Kiszkad89f5ef2010-11-09 17:02:49 +0100829 kvm_arch_free_vm(kvm);
Paolo Bonzinie9ad4ec2016-03-21 10:15:25 +0100830 mmdrop(current->mm);
Alexander Graf10474ae2009-09-15 11:37:46 +0200831 return ERR_PTR(r);
Avi Kivityf17abe92007-02-21 19:28:04 +0200832}
833
Scott Wood07f0a7b2013-04-25 14:11:23 +0000834static void kvm_destroy_devices(struct kvm *kvm)
835{
Geliang Tange6e3b5a2016-01-01 19:47:12 +0800836 struct kvm_device *dev, *tmp;
Scott Wood07f0a7b2013-04-25 14:11:23 +0000837
Christoffer Dalla28ebea2016-08-09 19:13:01 +0200838 /*
839 * We do not need to take the kvm->lock here, because nobody else
840 * has a reference to the struct kvm at this point and therefore
841 * cannot access the devices list anyhow.
842 */
Geliang Tange6e3b5a2016-01-01 19:47:12 +0800843 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
844 list_del(&dev->vm_node);
Scott Wood07f0a7b2013-04-25 14:11:23 +0000845 dev->ops->destroy(dev);
846 }
847}
848
Avi Kivityf17abe92007-02-21 19:28:04 +0200849static void kvm_destroy_vm(struct kvm *kvm)
850{
Marcelo Tosattie93f8a02009-12-23 14:35:24 -0200851 int i;
Avi Kivity6d4e4c42007-11-21 16:41:05 +0200852 struct mm_struct *mm = kvm->mm;
853
Claudio Imbrenda286de8f2017-07-12 17:56:44 +0200854 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
Janosch Frank536a6f82016-05-18 13:26:23 +0200855 kvm_destroy_vm_debugfs(kvm);
Sheng Yangad8ba2c2009-01-06 10:03:02 +0800856 kvm_arch_sync_events(kvm);
Junaid Shahid0d9ce162019-01-03 17:14:28 -0800857 mutex_lock(&kvm_lock);
Avi Kivity133de902007-02-12 00:54:44 -0800858 list_del(&kvm->vm_list);
Junaid Shahid0d9ce162019-01-03 17:14:28 -0800859 mutex_unlock(&kvm_lock);
Junaid Shahid1aa9b952019-11-04 20:26:00 +0100860 kvm_arch_pre_destroy_vm(kvm);
861
Avi Kivity399ec802008-11-19 13:58:46 +0200862 kvm_free_irq_routing(kvm);
Peter Xudf630b82017-03-15 16:01:17 +0800863 for (i = 0; i < KVM_NR_BUSES; i++) {
Paolo Bonzini3898da92017-08-02 17:55:54 +0200864 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
Christian Borntraeger4a12f952017-07-07 10:51:38 +0200865
Christian Borntraeger4a12f952017-07-07 10:51:38 +0200866 if (bus)
867 kvm_io_bus_destroy(bus);
Peter Xudf630b82017-03-15 16:01:17 +0800868 kvm->buses[i] = NULL;
869 }
Avi Kivity980da6c2009-12-20 15:13:43 +0200870 kvm_coalesced_mmio_free(kvm);
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200871#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
872 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
Gleb Natapovf00be0c2009-03-19 12:20:36 +0200873#else
Marcelo Tosatti2df72e92012-08-24 15:54:57 -0300874 kvm_arch_flush_shadow_all(kvm);
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200875#endif
Zhang Xiantaod19a9cd2007-11-18 18:43:45 +0800876 kvm_arch_destroy_vm(kvm);
Scott Wood07f0a7b2013-04-25 14:11:23 +0000877 kvm_destroy_devices(kvm);
Paolo Bonzinif481b062015-05-17 17:30:37 +0200878 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
Paolo Bonzini3898da92017-08-02 17:55:54 +0200879 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
Paolo Bonzini820b3fc2014-06-03 13:44:17 +0200880 cleanup_srcu_struct(&kvm->irq_srcu);
Jan Kiszkad89f5ef2010-11-09 17:02:49 +0100881 cleanup_srcu_struct(&kvm->srcu);
882 kvm_arch_free_vm(kvm);
Peter Zijlstra2ecd9d22015-07-03 18:53:58 +0200883 preempt_notifier_dec();
Alexander Graf10474ae2009-09-15 11:37:46 +0200884 hardware_disable_all();
Avi Kivity6d4e4c42007-11-21 16:41:05 +0200885 mmdrop(mm);
Avi Kivityf17abe92007-02-21 19:28:04 +0200886}
887
Izik Eidusd39f13b2008-03-30 16:01:25 +0300888void kvm_get_kvm(struct kvm *kvm)
889{
Elena Reshetovae3736c32017-02-20 13:06:21 +0200890 refcount_inc(&kvm->users_count);
Izik Eidusd39f13b2008-03-30 16:01:25 +0300891}
892EXPORT_SYMBOL_GPL(kvm_get_kvm);
893
894void kvm_put_kvm(struct kvm *kvm)
895{
Elena Reshetovae3736c32017-02-20 13:06:21 +0200896 if (refcount_dec_and_test(&kvm->users_count))
Izik Eidusd39f13b2008-03-30 16:01:25 +0300897 kvm_destroy_vm(kvm);
898}
899EXPORT_SYMBOL_GPL(kvm_put_kvm);
900
Sean Christopherson149487b2019-10-21 15:58:42 -0700901/*
902 * Used to put a reference that was taken on behalf of an object associated
903 * with a user-visible file descriptor, e.g. a vcpu or device, if installation
904 * of the new file descriptor fails and the reference cannot be transferred to
905 * its final owner. In such cases, the caller is still actively using @kvm and
906 * will fail miserably if the refcount unexpectedly hits zero.
907 */
908void kvm_put_kvm_no_destroy(struct kvm *kvm)
909{
910 WARN_ON(refcount_dec_and_test(&kvm->users_count));
911}
912EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
Izik Eidusd39f13b2008-03-30 16:01:25 +0300913
Avi Kivityf17abe92007-02-21 19:28:04 +0200914static int kvm_vm_release(struct inode *inode, struct file *filp)
915{
916 struct kvm *kvm = filp->private_data;
917
Gregory Haskins721eecbf2009-05-20 10:30:49 -0400918 kvm_irqfd_release(kvm);
919
Izik Eidusd39f13b2008-03-30 16:01:25 +0300920 kvm_put_kvm(kvm);
Avi Kivity6aa8b732006-12-10 02:21:36 -0800921 return 0;
922}
923
Takuya Yoshikawa515a0122010-10-27 18:23:54 +0900924/*
925 * Allocation size is twice as large as the actual dirty bitmap size.
Sean Christopherson0dff0842020-02-18 13:07:29 -0800926 * See kvm_vm_ioctl_get_dirty_log() why this is needed.
Takuya Yoshikawa515a0122010-10-27 18:23:54 +0900927 */
Jay Zhou3c9bd402020-02-27 09:32:27 +0800928static int kvm_alloc_dirty_bitmap(struct kvm_memory_slot *memslot)
Takuya Yoshikawaa36a57b12010-10-27 18:22:19 +0900929{
Takuya Yoshikawa515a0122010-10-27 18:23:54 +0900930 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
Takuya Yoshikawaa36a57b12010-10-27 18:22:19 +0900931
Ben Gardonb12ce362019-02-11 11:02:49 -0800932 memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL_ACCOUNT);
Takuya Yoshikawaa36a57b12010-10-27 18:22:19 +0900933 if (!memslot->dirty_bitmap)
934 return -ENOMEM;
935
Takuya Yoshikawaa36a57b12010-10-27 18:22:19 +0900936 return 0;
937}
938
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +0800939/*
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800940 * Delete a memslot by decrementing the number of used slots and shifting all
941 * other entries in the array forward one spot.
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +0800942 */
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800943static inline void kvm_memslot_delete(struct kvm_memslots *slots,
944 struct kvm_memory_slot *memslot)
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +0800945{
Igor Mammedov063584d2014-11-13 23:00:13 +0000946 struct kvm_memory_slot *mslots = slots->memslots;
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800947 int i;
Xiao Guangrongf85e2cb2011-11-24 17:41:54 +0800948
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800949 if (WARN_ON(slots->id_to_index[memslot->id] == -1))
950 return;
Igor Mammedov0e60b072014-12-01 17:29:26 +0000951
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800952 slots->used_slots--;
953
Sean Christopherson0774a962020-03-20 13:55:40 -0700954 if (atomic_read(&slots->lru_slot) >= slots->used_slots)
955 atomic_set(&slots->lru_slot, 0);
956
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800957 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots; i++) {
Igor Mammedov7f379cf2014-12-01 17:29:24 +0000958 mslots[i] = mslots[i + 1];
959 slots->id_to_index[mslots[i].id] = i;
Igor Mammedov7f379cf2014-12-01 17:29:24 +0000960 }
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800961 mslots[i] = *memslot;
962 slots->id_to_index[memslot->id] = -1;
963}
964
965/*
966 * "Insert" a new memslot by incrementing the number of used slots. Returns
967 * the new slot's initial index into the memslots array.
968 */
969static inline int kvm_memslot_insert_back(struct kvm_memslots *slots)
970{
971 return slots->used_slots++;
972}
973
974/*
975 * Move a changed memslot backwards in the array by shifting existing slots
976 * with a higher GFN toward the front of the array. Note, the changed memslot
977 * itself is not preserved in the array, i.e. not swapped at this time, only
978 * its new index into the array is tracked. Returns the changed memslot's
979 * current index into the memslots array.
980 */
981static inline int kvm_memslot_move_backward(struct kvm_memslots *slots,
982 struct kvm_memory_slot *memslot)
983{
984 struct kvm_memory_slot *mslots = slots->memslots;
985 int i;
986
987 if (WARN_ON_ONCE(slots->id_to_index[memslot->id] == -1) ||
988 WARN_ON_ONCE(!slots->used_slots))
989 return -1;
Paolo Bonziniefbeec72014-12-27 18:01:00 +0100990
991 /*
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800992 * Move the target memslot backward in the array by shifting existing
993 * memslots with a higher GFN (than the target memslot) towards the
994 * front of the array.
Paolo Bonziniefbeec72014-12-27 18:01:00 +0100995 */
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800996 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots - 1; i++) {
997 if (memslot->base_gfn > mslots[i + 1].base_gfn)
998 break;
Xiao Guangrongf85e2cb2011-11-24 17:41:54 +0800999
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001000 WARN_ON_ONCE(memslot->base_gfn == mslots[i + 1].base_gfn);
1001
1002 /* Shift the next memslot forward one and update its index. */
1003 mslots[i] = mslots[i + 1];
1004 slots->id_to_index[mslots[i].id] = i;
1005 }
1006 return i;
1007}
1008
1009/*
1010 * Move a changed memslot forwards in the array by shifting existing slots with
1011 * a lower GFN toward the back of the array. Note, the changed memslot itself
1012 * is not preserved in the array, i.e. not swapped at this time, only its new
1013 * index into the array is tracked. Returns the changed memslot's final index
1014 * into the memslots array.
1015 */
1016static inline int kvm_memslot_move_forward(struct kvm_memslots *slots,
1017 struct kvm_memory_slot *memslot,
1018 int start)
1019{
1020 struct kvm_memory_slot *mslots = slots->memslots;
1021 int i;
1022
1023 for (i = start; i > 0; i--) {
1024 if (memslot->base_gfn < mslots[i - 1].base_gfn)
1025 break;
1026
1027 WARN_ON_ONCE(memslot->base_gfn == mslots[i - 1].base_gfn);
1028
1029 /* Shift the next memslot back one and update its index. */
1030 mslots[i] = mslots[i - 1];
1031 slots->id_to_index[mslots[i].id] = i;
1032 }
1033 return i;
1034}
1035
1036/*
1037 * Re-sort memslots based on their GFN to account for an added, deleted, or
1038 * moved memslot. Sorting memslots by GFN allows using a binary search during
1039 * memslot lookup.
1040 *
1041 * IMPORTANT: Slots are sorted from highest GFN to lowest GFN! I.e. the entry
1042 * at memslots[0] has the highest GFN.
1043 *
1044 * The sorting algorithm takes advantage of having initially sorted memslots
1045 * and knowing the position of the changed memslot. Sorting is also optimized
1046 * by not swapping the updated memslot and instead only shifting other memslots
1047 * and tracking the new index for the update memslot. Only once its final
1048 * index is known is the updated memslot copied into its position in the array.
1049 *
1050 * - When deleting a memslot, the deleted memslot simply needs to be moved to
1051 * the end of the array.
1052 *
1053 * - When creating a memslot, the algorithm "inserts" the new memslot at the
1054 * end of the array and then it forward to its correct location.
1055 *
1056 * - When moving a memslot, the algorithm first moves the updated memslot
1057 * backward to handle the scenario where the memslot's GFN was changed to a
1058 * lower value. update_memslots() then falls through and runs the same flow
1059 * as creating a memslot to move the memslot forward to handle the scenario
1060 * where its GFN was changed to a higher value.
1061 *
1062 * Note, slots are sorted from highest->lowest instead of lowest->highest for
1063 * historical reasons. Originally, invalid memslots where denoted by having
1064 * GFN=0, thus sorting from highest->lowest naturally sorted invalid memslots
1065 * to the end of the array. The current algorithm uses dedicated logic to
1066 * delete a memslot and thus does not rely on invalid memslots having GFN=0.
1067 *
1068 * The other historical motiviation for highest->lowest was to improve the
1069 * performance of memslot lookup. KVM originally used a linear search starting
1070 * at memslots[0]. On x86, the largest memslot usually has one of the highest,
1071 * if not *the* highest, GFN, as the bulk of the guest's RAM is located in a
1072 * single memslot above the 4gb boundary. As the largest memslot is also the
1073 * most likely to be referenced, sorting it to the front of the array was
1074 * advantageous. The current binary search starts from the middle of the array
1075 * and uses an LRU pointer to improve performance for all memslots and GFNs.
1076 */
1077static void update_memslots(struct kvm_memslots *slots,
1078 struct kvm_memory_slot *memslot,
1079 enum kvm_mr_change change)
1080{
1081 int i;
1082
1083 if (change == KVM_MR_DELETE) {
1084 kvm_memslot_delete(slots, memslot);
1085 } else {
1086 if (change == KVM_MR_CREATE)
1087 i = kvm_memslot_insert_back(slots);
1088 else
1089 i = kvm_memslot_move_backward(slots, memslot);
1090 i = kvm_memslot_move_forward(slots, memslot, i);
1091
1092 /*
1093 * Copy the memslot to its new position in memslots and update
1094 * its index accordingly.
1095 */
1096 slots->memslots[i] = *memslot;
1097 slots->id_to_index[memslot->id] = i;
1098 }
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +08001099}
1100
Paolo Bonzini09170a42015-05-18 13:59:39 +02001101static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
Xiao Guangronga50d64d2012-08-21 10:58:13 +08001102{
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001103 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1104
Christoffer Dall0f8a4de2014-08-26 14:00:37 +02001105#ifdef __KVM_HAVE_READONLY_MEM
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001106 valid_flags |= KVM_MEM_READONLY;
1107#endif
1108
1109 if (mem->flags & ~valid_flags)
Xiao Guangronga50d64d2012-08-21 10:58:13 +08001110 return -EINVAL;
1111
1112 return 0;
1113}
1114
Gleb Natapov7ec4fb42012-12-24 17:49:30 +02001115static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
Paolo Bonzinif481b062015-05-17 17:30:37 +02001116 int as_id, struct kvm_memslots *slots)
Gleb Natapov7ec4fb42012-12-24 17:49:30 +02001117{
Paolo Bonzinif481b062015-05-17 17:30:37 +02001118 struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
Sean Christopherson361209e2019-02-05 13:01:14 -08001119 u64 gen = old_memslots->generation;
Gleb Natapov7ec4fb42012-12-24 17:49:30 +02001120
Sean Christopherson361209e2019-02-05 13:01:14 -08001121 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1122 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
David Matlackee3d1572014-08-18 15:46:06 -07001123
Paolo Bonzinif481b062015-05-17 17:30:37 +02001124 rcu_assign_pointer(kvm->memslots[as_id], slots);
Gleb Natapov7ec4fb42012-12-24 17:49:30 +02001125 synchronize_srcu_expedited(&kvm->srcu);
Takuya Yoshikawae59dbe02013-07-04 13:40:29 +09001126
David Matlackee3d1572014-08-18 15:46:06 -07001127 /*
Sean Christopherson361209e2019-02-05 13:01:14 -08001128 * Increment the new memslot generation a second time, dropping the
Miaohe Lin00116792019-12-11 14:26:23 +08001129 * update in-progress flag and incrementing the generation based on
Sean Christopherson361209e2019-02-05 13:01:14 -08001130 * the number of address spaces. This provides a unique and easily
1131 * identifiable generation number while the memslots are in flux.
1132 */
1133 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1134
1135 /*
Paolo Bonzini4bd518f2017-02-03 20:44:51 -08001136 * Generations must be unique even across address spaces. We do not need
1137 * a global counter for that, instead the generation space is evenly split
1138 * across address spaces. For example, with two address spaces, address
Sean Christopherson164bf7e2019-02-05 13:01:18 -08001139 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1140 * use generations 1, 3, 5, ...
David Matlackee3d1572014-08-18 15:46:06 -07001141 */
Sean Christopherson164bf7e2019-02-05 13:01:18 -08001142 gen += KVM_ADDRESS_SPACE_NUM;
David Matlackee3d1572014-08-18 15:46:06 -07001143
Sean Christopherson15248252019-02-05 12:54:17 -08001144 kvm_arch_memslots_updated(kvm, gen);
1145
1146 slots->generation = gen;
Takuya Yoshikawae59dbe02013-07-04 13:40:29 +09001147
1148 return old_memslots;
Gleb Natapov7ec4fb42012-12-24 17:49:30 +02001149}
1150
Sean Christopherson36947252020-02-18 13:07:32 -08001151/*
1152 * Note, at a minimum, the current number of used slots must be allocated, even
1153 * when deleting a memslot, as we need a complete duplicate of the memslots for
1154 * use when invalidating a memslot prior to deleting/moving the memslot.
1155 */
1156static struct kvm_memslots *kvm_dup_memslots(struct kvm_memslots *old,
1157 enum kvm_mr_change change)
1158{
1159 struct kvm_memslots *slots;
1160 size_t old_size, new_size;
1161
1162 old_size = sizeof(struct kvm_memslots) +
1163 (sizeof(struct kvm_memory_slot) * old->used_slots);
1164
1165 if (change == KVM_MR_CREATE)
1166 new_size = old_size + sizeof(struct kvm_memory_slot);
1167 else
1168 new_size = old_size;
1169
1170 slots = kvzalloc(new_size, GFP_KERNEL_ACCOUNT);
1171 if (likely(slots))
1172 memcpy(slots, old, old_size);
1173
1174 return slots;
1175}
1176
Sean Christophersoncf47f502020-02-18 13:07:23 -08001177static int kvm_set_memslot(struct kvm *kvm,
1178 const struct kvm_userspace_memory_region *mem,
Sean Christopherson9d4c1972020-02-18 13:07:24 -08001179 struct kvm_memory_slot *old,
Sean Christophersoncf47f502020-02-18 13:07:23 -08001180 struct kvm_memory_slot *new, int as_id,
1181 enum kvm_mr_change change)
1182{
1183 struct kvm_memory_slot *slot;
1184 struct kvm_memslots *slots;
1185 int r;
1186
Sean Christopherson36947252020-02-18 13:07:32 -08001187 slots = kvm_dup_memslots(__kvm_memslots(kvm, as_id), change);
Sean Christophersoncf47f502020-02-18 13:07:23 -08001188 if (!slots)
1189 return -ENOMEM;
Sean Christophersoncf47f502020-02-18 13:07:23 -08001190
1191 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1192 /*
1193 * Note, the INVALID flag needs to be in the appropriate entry
1194 * in the freshly allocated memslots, not in @old or @new.
1195 */
1196 slot = id_to_memslot(slots, old->id);
1197 slot->flags |= KVM_MEMSLOT_INVALID;
1198
1199 /*
1200 * We can re-use the old memslots, the only difference from the
1201 * newly installed memslots is the invalid flag, which will get
1202 * dropped by update_memslots anyway. We'll also revert to the
1203 * old memslots if preparing the new memory region fails.
1204 */
1205 slots = install_new_memslots(kvm, as_id, slots);
1206
1207 /* From this point no new shadow pages pointing to a deleted,
1208 * or moved, memslot will be created.
1209 *
1210 * validation of sp->gfn happens in:
1211 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1212 * - kvm_is_visible_gfn (mmu_check_root)
1213 */
1214 kvm_arch_flush_shadow_memslot(kvm, slot);
1215 }
1216
1217 r = kvm_arch_prepare_memory_region(kvm, new, mem, change);
1218 if (r)
1219 goto out_slots;
1220
1221 update_memslots(slots, new, change);
1222 slots = install_new_memslots(kvm, as_id, slots);
1223
1224 kvm_arch_commit_memory_region(kvm, mem, old, new, change);
1225
1226 kvfree(slots);
1227 return 0;
1228
1229out_slots:
1230 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE)
1231 slots = install_new_memslots(kvm, as_id, slots);
1232 kvfree(slots);
1233 return r;
1234}
1235
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001236static int kvm_delete_memslot(struct kvm *kvm,
1237 const struct kvm_userspace_memory_region *mem,
1238 struct kvm_memory_slot *old, int as_id)
1239{
1240 struct kvm_memory_slot new;
1241 int r;
1242
1243 if (!old->npages)
1244 return -EINVAL;
1245
1246 memset(&new, 0, sizeof(new));
1247 new.id = old->id;
Peter Xu9e9eb222020-10-14 11:26:46 -07001248 /*
1249 * This is only for debugging purpose; it should never be referenced
1250 * for a removed memslot.
1251 */
1252 new.as_id = as_id;
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001253
1254 r = kvm_set_memslot(kvm, mem, old, &new, as_id, KVM_MR_DELETE);
1255 if (r)
1256 return r;
1257
Sean Christophersone96c81e2020-02-18 13:07:27 -08001258 kvm_free_memslot(kvm, old);
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001259 return 0;
1260}
1261
Avi Kivity6aa8b732006-12-10 02:21:36 -08001262/*
Avi Kivity6aa8b732006-12-10 02:21:36 -08001263 * Allocate some memory and give it an address in the guest physical address
1264 * space.
1265 *
1266 * Discontiguous memory is allowed, mostly for framebuffers.
Sheng Yangf78e0e22007-10-29 09:40:42 +08001267 *
Dominik Dingel02d5d552014-10-27 16:22:56 +01001268 * Must be called holding kvm->slots_lock for write.
Avi Kivity6aa8b732006-12-10 02:21:36 -08001269 */
Sheng Yangf78e0e22007-10-29 09:40:42 +08001270int __kvm_set_memory_region(struct kvm *kvm,
Paolo Bonzini09170a42015-05-18 13:59:39 +02001271 const struct kvm_userspace_memory_region *mem)
Avi Kivity6aa8b732006-12-10 02:21:36 -08001272{
Avi Kivity6aa8b732006-12-10 02:21:36 -08001273 struct kvm_memory_slot old, new;
Sean Christopherson163da372020-02-18 13:07:28 -08001274 struct kvm_memory_slot *tmp;
Takuya Yoshikawaf64c0392013-01-29 11:00:07 +09001275 enum kvm_mr_change change;
Sean Christopherson163da372020-02-18 13:07:28 -08001276 int as_id, id;
1277 int r;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001278
Xiao Guangronga50d64d2012-08-21 10:58:13 +08001279 r = check_memory_region_flags(mem);
1280 if (r)
Sean Christopherson71a4c302020-02-18 13:07:22 -08001281 return r;
Xiao Guangronga50d64d2012-08-21 10:58:13 +08001282
Paolo Bonzinif481b062015-05-17 17:30:37 +02001283 as_id = mem->slot >> 16;
1284 id = (u16)mem->slot;
1285
Avi Kivity6aa8b732006-12-10 02:21:36 -08001286 /* General sanity checks */
1287 if (mem->memory_size & (PAGE_SIZE - 1))
Sean Christopherson71a4c302020-02-18 13:07:22 -08001288 return -EINVAL;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001289 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
Sean Christopherson71a4c302020-02-18 13:07:22 -08001290 return -EINVAL;
Takuya Yoshikawafa3d3152011-05-07 16:35:38 +09001291 /* We can read the guest memory with __xxx_user() later on. */
Paolo Bonzini09d952c2020-06-01 04:17:45 -04001292 if ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
Linus Torvalds96d4f262019-01-03 18:57:57 -08001293 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
Paolo Bonzini09d952c2020-06-01 04:17:45 -04001294 mem->memory_size))
Sean Christopherson71a4c302020-02-18 13:07:22 -08001295 return -EINVAL;
Paolo Bonzinif481b062015-05-17 17:30:37 +02001296 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
Sean Christopherson71a4c302020-02-18 13:07:22 -08001297 return -EINVAL;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001298 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
Sean Christopherson71a4c302020-02-18 13:07:22 -08001299 return -EINVAL;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001300
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001301 /*
1302 * Make a full copy of the old memslot, the pointer will become stale
1303 * when the memslots are re-sorted by update_memslots(), and the old
1304 * memslot needs to be referenced after calling update_memslots(), e.g.
Sean Christopherson0dff0842020-02-18 13:07:29 -08001305 * to free its resources and for arch specific behavior.
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001306 */
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001307 tmp = id_to_memslot(__kvm_memslots(kvm, as_id), id);
1308 if (tmp) {
1309 old = *tmp;
1310 tmp = NULL;
1311 } else {
1312 memset(&old, 0, sizeof(old));
1313 old.id = id;
1314 }
Sean Christopherson163da372020-02-18 13:07:28 -08001315
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001316 if (!mem->memory_size)
1317 return kvm_delete_memslot(kvm, mem, &old, as_id);
1318
Peter Xu9e9eb222020-10-14 11:26:46 -07001319 new.as_id = as_id;
Paolo Bonzinif481b062015-05-17 17:30:37 +02001320 new.id = id;
Sean Christopherson163da372020-02-18 13:07:28 -08001321 new.base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
1322 new.npages = mem->memory_size >> PAGE_SHIFT;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001323 new.flags = mem->flags;
Sean Christopherson414de7ab2020-02-18 13:07:20 -08001324 new.userspace_addr = mem->userspace_addr;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001325
Sean Christopherson163da372020-02-18 13:07:28 -08001326 if (new.npages > KVM_MEM_MAX_NR_PAGES)
1327 return -EINVAL;
1328
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001329 if (!old.npages) {
1330 change = KVM_MR_CREATE;
Sean Christopherson163da372020-02-18 13:07:28 -08001331 new.dirty_bitmap = NULL;
1332 memset(&new.arch, 0, sizeof(new.arch));
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001333 } else { /* Modify an existing slot. */
1334 if ((new.userspace_addr != old.userspace_addr) ||
Sean Christopherson163da372020-02-18 13:07:28 -08001335 (new.npages != old.npages) ||
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001336 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
Sean Christopherson71a4c302020-02-18 13:07:22 -08001337 return -EINVAL;
Paolo Bonzini09170a42015-05-18 13:59:39 +02001338
Sean Christopherson163da372020-02-18 13:07:28 -08001339 if (new.base_gfn != old.base_gfn)
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001340 change = KVM_MR_MOVE;
1341 else if (new.flags != old.flags)
1342 change = KVM_MR_FLAGS_ONLY;
1343 else /* Nothing to change. */
1344 return 0;
Sean Christopherson163da372020-02-18 13:07:28 -08001345
1346 /* Copy dirty_bitmap and arch from the current memslot. */
1347 new.dirty_bitmap = old.dirty_bitmap;
1348 memcpy(&new.arch, &old.arch, sizeof(new.arch));
Paolo Bonzini09170a42015-05-18 13:59:39 +02001349 }
Avi Kivity6aa8b732006-12-10 02:21:36 -08001350
Takuya Yoshikawaf64c0392013-01-29 11:00:07 +09001351 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
Takuya Yoshikawa0a706be2013-01-11 18:26:55 +09001352 /* Check for overlaps */
Sean Christopherson163da372020-02-18 13:07:28 -08001353 kvm_for_each_memslot(tmp, __kvm_memslots(kvm, as_id)) {
1354 if (tmp->id == id)
Takuya Yoshikawa0a706be2013-01-11 18:26:55 +09001355 continue;
Sean Christopherson163da372020-02-18 13:07:28 -08001356 if (!((new.base_gfn + new.npages <= tmp->base_gfn) ||
1357 (new.base_gfn >= tmp->base_gfn + tmp->npages)))
Sean Christopherson71a4c302020-02-18 13:07:22 -08001358 return -EEXIST;
Takuya Yoshikawa0a706be2013-01-11 18:26:55 +09001359 }
Avi Kivity6aa8b732006-12-10 02:21:36 -08001360 }
Avi Kivity6aa8b732006-12-10 02:21:36 -08001361
Sean Christopherson414de7ab2020-02-18 13:07:20 -08001362 /* Allocate/free page dirty bitmap as needed */
Avi Kivity6aa8b732006-12-10 02:21:36 -08001363 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
Al Viro8b6d44c2007-02-09 16:38:40 +00001364 new.dirty_bitmap = NULL;
Sean Christopherson414de7ab2020-02-18 13:07:20 -08001365 else if (!new.dirty_bitmap) {
Jay Zhou3c9bd402020-02-27 09:32:27 +08001366 r = kvm_alloc_dirty_bitmap(&new);
Sean Christopherson71a4c302020-02-18 13:07:22 -08001367 if (r)
1368 return r;
Jay Zhou3c9bd402020-02-27 09:32:27 +08001369
1370 if (kvm_dirty_log_manual_protect_and_init_set(kvm))
1371 bitmap_set(new.dirty_bitmap, 0, new.npages);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001372 }
1373
Sean Christophersoncf47f502020-02-18 13:07:23 -08001374 r = kvm_set_memslot(kvm, mem, &old, &new, as_id, change);
1375 if (r)
1376 goto out_bitmap;
Zhang Xiantao3ad82a72007-11-20 13:11:38 +08001377
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001378 if (old.dirty_bitmap && !new.dirty_bitmap)
1379 kvm_destroy_dirty_bitmap(&old);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001380 return 0;
1381
Sean Christophersonbd0e96f2020-02-18 13:07:21 -08001382out_bitmap:
1383 if (new.dirty_bitmap && !old.dirty_bitmap)
1384 kvm_destroy_dirty_bitmap(&new);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001385 return r;
Izik Eidus210c7c42007-10-24 23:52:57 +02001386}
Sheng Yangf78e0e22007-10-29 09:40:42 +08001387EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1388
1389int kvm_set_memory_region(struct kvm *kvm,
Paolo Bonzini09170a42015-05-18 13:59:39 +02001390 const struct kvm_userspace_memory_region *mem)
Sheng Yangf78e0e22007-10-29 09:40:42 +08001391{
1392 int r;
1393
Marcelo Tosatti79fac952009-12-23 14:35:26 -02001394 mutex_lock(&kvm->slots_lock);
Takuya Yoshikawa47ae31e2013-02-27 19:43:00 +09001395 r = __kvm_set_memory_region(kvm, mem);
Marcelo Tosatti79fac952009-12-23 14:35:26 -02001396 mutex_unlock(&kvm->slots_lock);
Sheng Yangf78e0e22007-10-29 09:40:42 +08001397 return r;
1398}
Izik Eidus210c7c42007-10-24 23:52:57 +02001399EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1400
Stephen Hemminger79408762013-12-29 12:12:29 -08001401static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1402 struct kvm_userspace_memory_region *mem)
Izik Eidus210c7c42007-10-24 23:52:57 +02001403{
Paolo Bonzinif481b062015-05-17 17:30:37 +02001404 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
Izik Eiduse0d62c72007-10-24 23:57:46 +02001405 return -EINVAL;
Paolo Bonzini09170a42015-05-18 13:59:39 +02001406
Takuya Yoshikawa47ae31e2013-02-27 19:43:00 +09001407 return kvm_set_memory_region(kvm, mem);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001408}
1409
Sean Christopherson0dff0842020-02-18 13:07:29 -08001410#ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
Sean Christopherson2a49f612020-02-18 13:07:30 -08001411/**
1412 * kvm_get_dirty_log - get a snapshot of dirty pages
1413 * @kvm: pointer to kvm instance
1414 * @log: slot id and address to which we copy the log
1415 * @is_dirty: set to '1' if any dirty pages were found
1416 * @memslot: set to the associated memslot, always valid on success
1417 */
1418int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1419 int *is_dirty, struct kvm_memory_slot **memslot)
Avi Kivity6aa8b732006-12-10 02:21:36 -08001420{
Paolo Bonzini9f6b8022015-05-17 16:20:07 +02001421 struct kvm_memslots *slots;
Markus Elfring843574a2017-01-22 17:41:07 +01001422 int i, as_id, id;
Takuya Yoshikawa87bf6e72010-04-12 19:35:35 +09001423 unsigned long n;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001424 unsigned long any = 0;
1425
Sean Christopherson2a49f612020-02-18 13:07:30 -08001426 *memslot = NULL;
1427 *is_dirty = 0;
1428
Paolo Bonzinif481b062015-05-17 17:30:37 +02001429 as_id = log->slot >> 16;
1430 id = (u16)log->slot;
1431 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
Markus Elfring843574a2017-01-22 17:41:07 +01001432 return -EINVAL;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001433
Paolo Bonzinif481b062015-05-17 17:30:37 +02001434 slots = __kvm_memslots(kvm, as_id);
Sean Christopherson2a49f612020-02-18 13:07:30 -08001435 *memslot = id_to_memslot(slots, id);
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001436 if (!(*memslot) || !(*memslot)->dirty_bitmap)
Markus Elfring843574a2017-01-22 17:41:07 +01001437 return -ENOENT;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001438
Sean Christopherson2a49f612020-02-18 13:07:30 -08001439 kvm_arch_sync_dirty_log(kvm, *memslot);
1440
1441 n = kvm_dirty_bitmap_bytes(*memslot);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001442
Uri Lublincd1a4a92007-02-22 16:43:09 +02001443 for (i = 0; !any && i < n/sizeof(long); ++i)
Sean Christopherson2a49f612020-02-18 13:07:30 -08001444 any = (*memslot)->dirty_bitmap[i];
Avi Kivity6aa8b732006-12-10 02:21:36 -08001445
Sean Christopherson2a49f612020-02-18 13:07:30 -08001446 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
Markus Elfring843574a2017-01-22 17:41:07 +01001447 return -EFAULT;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001448
Zhang Xiantao5bb064d2007-11-18 20:29:43 +08001449 if (any)
1450 *is_dirty = 1;
Markus Elfring843574a2017-01-22 17:41:07 +01001451 return 0;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001452}
Aneesh Kumar K.V2ba9f0d2013-10-07 22:17:59 +05301453EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001454
Sean Christopherson0dff0842020-02-18 13:07:29 -08001455#else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
Mario Smarduchba0513b2015-01-15 15:58:53 -08001456/**
Jiang Biaob8b00222019-04-23 19:40:30 +08001457 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001458 * and reenable dirty page tracking for the corresponding pages.
Mario Smarduchba0513b2015-01-15 15:58:53 -08001459 * @kvm: pointer to kvm instance
1460 * @log: slot id and address to which we copy the log
Mario Smarduchba0513b2015-01-15 15:58:53 -08001461 *
1462 * We need to keep it in mind that VCPU threads can write to the bitmap
1463 * concurrently. So, to avoid losing track of dirty pages we keep the
1464 * following order:
1465 *
1466 * 1. Take a snapshot of the bit and clear it if needed.
1467 * 2. Write protect the corresponding page.
1468 * 3. Copy the snapshot to the userspace.
1469 * 4. Upon return caller flushes TLB's if needed.
1470 *
1471 * Between 2 and 4, the guest may write to the page using the remaining TLB
1472 * entry. This is not a problem because the page is reported dirty using
1473 * the snapshot taken before and step 4 ensures that writes done after
1474 * exiting to userspace will be logged for the next call.
1475 *
1476 */
Sean Christopherson0dff0842020-02-18 13:07:29 -08001477static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
Mario Smarduchba0513b2015-01-15 15:58:53 -08001478{
Paolo Bonzini9f6b8022015-05-17 16:20:07 +02001479 struct kvm_memslots *slots;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001480 struct kvm_memory_slot *memslot;
Markus Elfring58d6db32017-01-22 17:30:16 +01001481 int i, as_id, id;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001482 unsigned long n;
1483 unsigned long *dirty_bitmap;
1484 unsigned long *dirty_bitmap_buffer;
Sean Christopherson0dff0842020-02-18 13:07:29 -08001485 bool flush;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001486
Paolo Bonzinif481b062015-05-17 17:30:37 +02001487 as_id = log->slot >> 16;
1488 id = (u16)log->slot;
1489 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
Markus Elfring58d6db32017-01-22 17:30:16 +01001490 return -EINVAL;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001491
Paolo Bonzinif481b062015-05-17 17:30:37 +02001492 slots = __kvm_memslots(kvm, as_id);
1493 memslot = id_to_memslot(slots, id);
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001494 if (!memslot || !memslot->dirty_bitmap)
1495 return -ENOENT;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001496
1497 dirty_bitmap = memslot->dirty_bitmap;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001498
Sean Christopherson0dff0842020-02-18 13:07:29 -08001499 kvm_arch_sync_dirty_log(kvm, memslot);
1500
Mario Smarduchba0513b2015-01-15 15:58:53 -08001501 n = kvm_dirty_bitmap_bytes(memslot);
Sean Christopherson0dff0842020-02-18 13:07:29 -08001502 flush = false;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001503 if (kvm->manual_dirty_log_protect) {
1504 /*
1505 * Unlike kvm_get_dirty_log, we always return false in *flush,
1506 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
1507 * is some code duplication between this function and
1508 * kvm_get_dirty_log, but hopefully all architecture
1509 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
1510 * can be eliminated.
1511 */
1512 dirty_bitmap_buffer = dirty_bitmap;
1513 } else {
1514 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1515 memset(dirty_bitmap_buffer, 0, n);
Mario Smarduchba0513b2015-01-15 15:58:53 -08001516
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001517 spin_lock(&kvm->mmu_lock);
1518 for (i = 0; i < n / sizeof(long); i++) {
1519 unsigned long mask;
1520 gfn_t offset;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001521
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001522 if (!dirty_bitmap[i])
1523 continue;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001524
Sean Christopherson0dff0842020-02-18 13:07:29 -08001525 flush = true;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001526 mask = xchg(&dirty_bitmap[i], 0);
1527 dirty_bitmap_buffer[i] = mask;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001528
Lan Tianyua67794c2019-02-02 17:20:27 +08001529 offset = i * BITS_PER_LONG;
1530 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1531 offset, mask);
Takuya Yoshikawa58d29302015-03-17 16:19:58 +09001532 }
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001533 spin_unlock(&kvm->mmu_lock);
Mario Smarduchba0513b2015-01-15 15:58:53 -08001534 }
1535
Sean Christopherson0dff0842020-02-18 13:07:29 -08001536 if (flush)
1537 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1538
Mario Smarduchba0513b2015-01-15 15:58:53 -08001539 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
Markus Elfring58d6db32017-01-22 17:30:16 +01001540 return -EFAULT;
1541 return 0;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001542}
Sean Christopherson0dff0842020-02-18 13:07:29 -08001543
1544
1545/**
1546 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
1547 * @kvm: kvm instance
1548 * @log: slot id and address to which we copy the log
1549 *
1550 * Steps 1-4 below provide general overview of dirty page logging. See
1551 * kvm_get_dirty_log_protect() function description for additional details.
1552 *
1553 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
1554 * always flush the TLB (step 4) even if previous step failed and the dirty
1555 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
1556 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
1557 * writes will be marked dirty for next log read.
1558 *
1559 * 1. Take a snapshot of the bit and clear it if needed.
1560 * 2. Write protect the corresponding page.
1561 * 3. Copy the snapshot to the userspace.
1562 * 4. Flush TLB's if needed.
1563 */
1564static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1565 struct kvm_dirty_log *log)
1566{
1567 int r;
1568
1569 mutex_lock(&kvm->slots_lock);
1570
1571 r = kvm_get_dirty_log_protect(kvm, log);
1572
1573 mutex_unlock(&kvm->slots_lock);
1574 return r;
1575}
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001576
1577/**
1578 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
1579 * and reenable dirty page tracking for the corresponding pages.
1580 * @kvm: pointer to kvm instance
1581 * @log: slot id and address from which to fetch the bitmap of dirty pages
1582 */
Sean Christopherson0dff0842020-02-18 13:07:29 -08001583static int kvm_clear_dirty_log_protect(struct kvm *kvm,
1584 struct kvm_clear_dirty_log *log)
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001585{
1586 struct kvm_memslots *slots;
1587 struct kvm_memory_slot *memslot;
Tomas Bortoli98938aa2019-01-02 18:29:37 +01001588 int as_id, id;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001589 gfn_t offset;
Tomas Bortoli98938aa2019-01-02 18:29:37 +01001590 unsigned long i, n;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001591 unsigned long *dirty_bitmap;
1592 unsigned long *dirty_bitmap_buffer;
Sean Christopherson0dff0842020-02-18 13:07:29 -08001593 bool flush;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001594
1595 as_id = log->slot >> 16;
1596 id = (u16)log->slot;
1597 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1598 return -EINVAL;
1599
Paolo Bonzini76d58e02019-04-17 15:28:44 +02001600 if (log->first_page & 63)
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001601 return -EINVAL;
1602
1603 slots = __kvm_memslots(kvm, as_id);
1604 memslot = id_to_memslot(slots, id);
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001605 if (!memslot || !memslot->dirty_bitmap)
1606 return -ENOENT;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001607
1608 dirty_bitmap = memslot->dirty_bitmap;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001609
Peter Xu4ddc9202019-05-08 17:15:45 +08001610 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
Tomas Bortoli98938aa2019-01-02 18:29:37 +01001611
1612 if (log->first_page > memslot->npages ||
Paolo Bonzini76d58e02019-04-17 15:28:44 +02001613 log->num_pages > memslot->npages - log->first_page ||
1614 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
1615 return -EINVAL;
Tomas Bortoli98938aa2019-01-02 18:29:37 +01001616
Sean Christopherson0dff0842020-02-18 13:07:29 -08001617 kvm_arch_sync_dirty_log(kvm, memslot);
1618
1619 flush = false;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001620 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1621 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
1622 return -EFAULT;
1623
1624 spin_lock(&kvm->mmu_lock);
Peter Xu53eac7a2019-05-08 17:15:46 +08001625 for (offset = log->first_page, i = offset / BITS_PER_LONG,
1626 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001627 i++, offset += BITS_PER_LONG) {
1628 unsigned long mask = *dirty_bitmap_buffer++;
1629 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
1630 if (!mask)
1631 continue;
1632
1633 mask &= atomic_long_fetch_andnot(mask, p);
1634
1635 /*
1636 * mask contains the bits that really have been cleared. This
1637 * never includes any bits beyond the length of the memslot (if
1638 * the length is not aligned to 64 pages), therefore it is not
1639 * a problem if userspace sets them in log->dirty_bitmap.
1640 */
1641 if (mask) {
Sean Christopherson0dff0842020-02-18 13:07:29 -08001642 flush = true;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001643 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1644 offset, mask);
1645 }
1646 }
1647 spin_unlock(&kvm->mmu_lock);
1648
Sean Christopherson0dff0842020-02-18 13:07:29 -08001649 if (flush)
1650 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1651
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001652 return 0;
1653}
Sean Christopherson0dff0842020-02-18 13:07:29 -08001654
1655static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
1656 struct kvm_clear_dirty_log *log)
1657{
1658 int r;
1659
1660 mutex_lock(&kvm->slots_lock);
1661
1662 r = kvm_clear_dirty_log_protect(kvm, log);
1663
1664 mutex_unlock(&kvm->slots_lock);
1665 return r;
1666}
1667#endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
Mario Smarduchba0513b2015-01-15 15:58:53 -08001668
Gleb Natapov49c77542010-10-18 15:22:23 +02001669struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1670{
1671 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1672}
Avi Kivitya1f4d3952010-06-21 11:44:20 +03001673EXPORT_SYMBOL_GPL(gfn_to_memslot);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001674
Paolo Bonzini8e734852015-05-17 13:58:53 +02001675struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1676{
1677 return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1678}
Paolo Bonzinie72436b2020-04-17 12:21:06 -04001679EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_memslot);
Paolo Bonzini8e734852015-05-17 13:58:53 +02001680
Yaowei Bai33e94152015-11-14 11:21:06 +08001681bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
Izik Eiduse0d62c72007-10-24 23:57:46 +02001682{
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +08001683 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
Izik Eiduse0d62c72007-10-24 23:57:46 +02001684
Paolo Bonzinic36b7152020-04-16 09:48:07 -04001685 return kvm_is_visible_memslot(memslot);
Izik Eiduse0d62c72007-10-24 23:57:46 +02001686}
1687EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1688
Vitaly Kuznetsov995decb2020-07-08 16:00:23 +02001689bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
1690{
1691 struct kvm_memory_slot *memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1692
1693 return kvm_is_visible_memslot(memslot);
1694}
1695EXPORT_SYMBOL_GPL(kvm_vcpu_is_visible_gfn);
1696
Sean Christophersonf9b84e12020-01-08 12:24:37 -08001697unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
Joerg Roedel8f0b1ab2010-01-28 12:37:56 +01001698{
1699 struct vm_area_struct *vma;
1700 unsigned long addr, size;
1701
1702 size = PAGE_SIZE;
1703
Sean Christopherson42cde482020-01-08 12:24:38 -08001704 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
Joerg Roedel8f0b1ab2010-01-28 12:37:56 +01001705 if (kvm_is_error_hva(addr))
1706 return PAGE_SIZE;
1707
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07001708 mmap_read_lock(current->mm);
Joerg Roedel8f0b1ab2010-01-28 12:37:56 +01001709 vma = find_vma(current->mm, addr);
1710 if (!vma)
1711 goto out;
1712
1713 size = vma_kernel_pagesize(vma);
1714
1715out:
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07001716 mmap_read_unlock(current->mm);
Joerg Roedel8f0b1ab2010-01-28 12:37:56 +01001717
1718 return size;
1719}
1720
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001721static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1722{
1723 return slot->flags & KVM_MEM_READONLY;
1724}
1725
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001726static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1727 gfn_t *nr_pages, bool write)
Izik Eidus539cb662007-11-11 22:05:04 +02001728{
Marcelo Tosattibc6678a2009-12-23 14:35:21 -02001729 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
Xiao Guangrongca3a4902012-08-21 11:01:50 +08001730 return KVM_HVA_ERR_BAD;
Xiao Guangrong48987782010-08-22 19:11:43 +08001731
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001732 if (memslot_is_readonly(slot) && write)
1733 return KVM_HVA_ERR_RO_BAD;
Xiao Guangrong48987782010-08-22 19:11:43 +08001734
1735 if (nr_pages)
1736 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1737
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001738 return __gfn_to_hva_memslot(slot, gfn);
Izik Eidus539cb662007-11-11 22:05:04 +02001739}
Xiao Guangrong48987782010-08-22 19:11:43 +08001740
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001741static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1742 gfn_t *nr_pages)
1743{
1744 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
1745}
1746
1747unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
Stephen Hemminger79408762013-12-29 12:12:29 -08001748 gfn_t gfn)
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001749{
1750 return gfn_to_hva_many(slot, gfn, NULL);
1751}
1752EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1753
Xiao Guangrong48987782010-08-22 19:11:43 +08001754unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1755{
Gleb Natapov49c77542010-10-18 15:22:23 +02001756 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
Xiao Guangrong48987782010-08-22 19:11:43 +08001757}
Sheng Yang0d150292008-04-25 21:44:50 +08001758EXPORT_SYMBOL_GPL(gfn_to_hva);
Izik Eidus539cb662007-11-11 22:05:04 +02001759
Paolo Bonzini8e734852015-05-17 13:58:53 +02001760unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1761{
1762 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
1763}
1764EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1765
Xiao Guangrong86ab8cf2012-08-21 10:59:53 +08001766/*
Wei Yang970c0d42018-10-09 10:41:15 +08001767 * Return the hva of a @gfn and the R/W attribute if possible.
1768 *
1769 * @slot: the kvm_memory_slot which contains @gfn
1770 * @gfn: the gfn to be translated
1771 * @writable: used to return the read/write attribute of the @slot if the hva
1772 * is valid and @writable is not NULL
Xiao Guangrong86ab8cf2012-08-21 10:59:53 +08001773 */
Christoffer Dall64d83122014-08-19 12:15:00 +02001774unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1775 gfn_t gfn, bool *writable)
Gleb Natapov80300892010-10-19 18:13:41 +02001776{
Gleb Natapova2ac07f2013-10-01 19:58:36 +03001777 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
1778
1779 if (!kvm_is_error_hva(hva) && writable)
Paolo Bonziniba6a3542013-09-09 13:52:33 +02001780 *writable = !memslot_is_readonly(slot);
1781
Gleb Natapova2ac07f2013-10-01 19:58:36 +03001782 return hva;
Xiao Guangrong86ab8cf2012-08-21 10:59:53 +08001783}
1784
Christoffer Dall64d83122014-08-19 12:15:00 +02001785unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
1786{
1787 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1788
1789 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1790}
1791
Paolo Bonzini8e734852015-05-17 13:58:53 +02001792unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
1793{
1794 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1795
1796 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1797}
1798
Huang Yingfafc3db2011-01-30 11:15:49 +08001799static inline int check_user_page_hwpoison(unsigned long addr)
1800{
Lorenzo Stoakes0d731752016-10-24 10:57:25 +01001801 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
Huang Yingfafc3db2011-01-30 11:15:49 +08001802
Lorenzo Stoakes0d731752016-10-24 10:57:25 +01001803 rc = get_user_pages(addr, 1, flags, NULL, NULL);
Huang Yingfafc3db2011-01-30 11:15:49 +08001804 return rc == -EHWPOISON;
1805}
1806
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001807/*
Paolo Bonzinib9b33da2018-07-27 17:44:41 +02001808 * The fast path to get the writable pfn which will be stored in @pfn,
1809 * true indicates success, otherwise false is returned. It's also the
Miaohe Lin311497e2019-12-11 14:26:25 +08001810 * only part that runs if we can in atomic context.
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001811 */
Paolo Bonzinib9b33da2018-07-27 17:44:41 +02001812static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
1813 bool *writable, kvm_pfn_t *pfn)
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001814{
1815 struct page *page[1];
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001816
Xiao Guangrong12ce13f2012-08-21 11:00:49 +08001817 /*
1818 * Fast pin a writable pfn only if it is a write fault request
1819 * or the caller allows to map a writable pfn for a read fault
1820 * request.
1821 */
1822 if (!(write_fault || writable))
1823 return false;
1824
Souptick Joarderdadbb612020-06-07 21:40:55 -07001825 if (get_user_page_fast_only(addr, FOLL_WRITE, page)) {
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001826 *pfn = page_to_pfn(page[0]);
1827
1828 if (writable)
1829 *writable = true;
1830 return true;
1831 }
1832
1833 return false;
1834}
1835
1836/*
1837 * The slow path to get the pfn of the specified host virtual address,
1838 * 1 indicates success, -errno is returned if error is detected.
1839 */
1840static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
Dan Williamsba049e92016-01-15 16:56:11 -08001841 bool *writable, kvm_pfn_t *pfn)
Avi Kivity954bbbc2007-03-30 14:02:32 +03001842{
Al Viroce530532017-11-19 17:47:33 -05001843 unsigned int flags = FOLL_HWPOISON;
1844 struct page *page;
Gleb Natapovaf585b92010-10-14 11:22:46 +02001845 int npages = 0;
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001846
1847 might_sleep();
1848
1849 if (writable)
1850 *writable = write_fault;
1851
Al Viroce530532017-11-19 17:47:33 -05001852 if (write_fault)
1853 flags |= FOLL_WRITE;
1854 if (async)
1855 flags |= FOLL_NOWAIT;
Lorenzo Stoakesd4944b02016-10-13 01:20:12 +01001856
Al Viroce530532017-11-19 17:47:33 -05001857 npages = get_user_pages_unlocked(addr, 1, &page, flags);
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001858 if (npages != 1)
1859 return npages;
1860
1861 /* map read fault as writable if possible */
Xiao Guangrong12ce13f2012-08-21 11:00:49 +08001862 if (unlikely(!write_fault) && writable) {
Al Viroce530532017-11-19 17:47:33 -05001863 struct page *wpage;
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001864
Souptick Joarderdadbb612020-06-07 21:40:55 -07001865 if (get_user_page_fast_only(addr, FOLL_WRITE, &wpage)) {
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001866 *writable = true;
Al Viroce530532017-11-19 17:47:33 -05001867 put_page(page);
1868 page = wpage;
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001869 }
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001870 }
Al Viroce530532017-11-19 17:47:33 -05001871 *pfn = page_to_pfn(page);
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001872 return npages;
1873}
1874
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001875static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
1876{
1877 if (unlikely(!(vma->vm_flags & VM_READ)))
1878 return false;
1879
1880 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
1881 return false;
1882
1883 return true;
1884}
1885
Paolo Bonzini92176a82016-06-07 16:22:47 +02001886static int hva_to_pfn_remapped(struct vm_area_struct *vma,
1887 unsigned long addr, bool *async,
KarimAllah Ahmeda340b3e2018-01-17 19:18:56 +01001888 bool write_fault, bool *writable,
1889 kvm_pfn_t *p_pfn)
Paolo Bonzini92176a82016-06-07 16:22:47 +02001890{
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02001891 unsigned long pfn;
1892 int r;
1893
1894 r = follow_pfn(vma, addr, &pfn);
1895 if (r) {
1896 /*
1897 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
1898 * not call the fault handler, so do it here.
1899 */
1900 bool unlocked = false;
Peter Xu64019a22020-08-11 18:39:01 -07001901 r = fixup_user_fault(current->mm, addr,
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02001902 (write_fault ? FAULT_FLAG_WRITE : 0),
1903 &unlocked);
Paolo Bonzinia8387d02020-05-29 05:42:55 -04001904 if (unlocked)
1905 return -EAGAIN;
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02001906 if (r)
1907 return r;
1908
1909 r = follow_pfn(vma, addr, &pfn);
1910 if (r)
1911 return r;
1912
1913 }
1914
KarimAllah Ahmeda340b3e2018-01-17 19:18:56 +01001915 if (writable)
1916 *writable = true;
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02001917
1918 /*
1919 * Get a reference here because callers of *hva_to_pfn* and
1920 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
1921 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
1922 * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
1923 * simply do nothing for reserved pfns.
1924 *
1925 * Whoever called remap_pfn_range is also going to call e.g.
1926 * unmap_mapping_range before the underlying pages are freed,
1927 * causing a call to our MMU notifier.
1928 */
1929 kvm_get_pfn(pfn);
1930
1931 *p_pfn = pfn;
Paolo Bonzini92176a82016-06-07 16:22:47 +02001932 return 0;
1933}
1934
Xiao Guangrong12ce13f2012-08-21 11:00:49 +08001935/*
1936 * Pin guest page in memory and return its pfn.
1937 * @addr: host virtual address which maps memory to the guest
1938 * @atomic: whether this function can sleep
1939 * @async: whether this function need to wait IO complete if the
1940 * host page is not in the memory
1941 * @write_fault: whether we should get a writable host page
1942 * @writable: whether it allows to map a writable host page for !@write_fault
1943 *
1944 * The function will map a writable host page for these two cases:
1945 * 1): @write_fault = true
1946 * 2): @write_fault = false && @writable, @writable will tell the caller
1947 * whether the mapping is writable.
1948 */
Dan Williamsba049e92016-01-15 16:56:11 -08001949static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001950 bool write_fault, bool *writable)
1951{
1952 struct vm_area_struct *vma;
Dan Williamsba049e92016-01-15 16:56:11 -08001953 kvm_pfn_t pfn = 0;
Paolo Bonzini92176a82016-06-07 16:22:47 +02001954 int npages, r;
Avi Kivity954bbbc2007-03-30 14:02:32 +03001955
Gleb Natapovaf585b92010-10-14 11:22:46 +02001956 /* we can do it either atomically or asynchronously, not both */
1957 BUG_ON(atomic && async);
1958
Paolo Bonzinib9b33da2018-07-27 17:44:41 +02001959 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001960 return pfn;
Marcelo Tosatti612819c2010-10-22 14:18:18 -02001961
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001962 if (atomic)
1963 return KVM_PFN_ERR_FAULT;
Marcelo Tosatti612819c2010-10-22 14:18:18 -02001964
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001965 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
1966 if (npages == 1)
1967 return pfn;
Gleb Natapovaf585b92010-10-14 11:22:46 +02001968
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07001969 mmap_read_lock(current->mm);
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001970 if (npages == -EHWPOISON ||
1971 (!async && check_user_page_hwpoison(addr))) {
1972 pfn = KVM_PFN_ERR_HWPOISON;
1973 goto exit;
Xiao Guangrong887c08a2010-08-22 19:10:28 +08001974 }
Izik Eidus539cb662007-11-11 22:05:04 +02001975
Paolo Bonzinia8387d02020-05-29 05:42:55 -04001976retry:
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001977 vma = find_vma_intersection(current->mm, addr, addr + 1);
Anthony Liguori8d4e1282007-10-18 09:59:34 -05001978
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001979 if (vma == NULL)
1980 pfn = KVM_PFN_ERR_FAULT;
Paolo Bonzini92176a82016-06-07 16:22:47 +02001981 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
KarimAllah Ahmeda340b3e2018-01-17 19:18:56 +01001982 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
Paolo Bonzinia8387d02020-05-29 05:42:55 -04001983 if (r == -EAGAIN)
1984 goto retry;
Paolo Bonzini92176a82016-06-07 16:22:47 +02001985 if (r < 0)
1986 pfn = KVM_PFN_ERR_FAULT;
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001987 } else {
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001988 if (async && vma_is_valid(vma, write_fault))
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001989 *async = true;
1990 pfn = KVM_PFN_ERR_FAULT;
1991 }
1992exit:
Michel Lespinassed8ed45c2020-06-08 21:33:25 -07001993 mmap_read_unlock(current->mm);
Anthony Liguori2e2e3732008-04-30 15:37:07 -05001994 return pfn;
Anthony Liguori35149e22008-04-02 14:46:56 -05001995}
1996
Dan Williamsba049e92016-01-15 16:56:11 -08001997kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
1998 bool atomic, bool *async, bool write_fault,
1999 bool *writable)
Xiao Guangrong887c08a2010-08-22 19:10:28 +08002000{
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08002001 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
2002
Paolo Bonzinib2740d32016-02-23 15:36:01 +01002003 if (addr == KVM_HVA_ERR_RO_BAD) {
2004 if (writable)
2005 *writable = false;
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08002006 return KVM_PFN_ERR_RO_FAULT;
Paolo Bonzinib2740d32016-02-23 15:36:01 +01002007 }
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08002008
Paolo Bonzinib2740d32016-02-23 15:36:01 +01002009 if (kvm_is_error_hva(addr)) {
2010 if (writable)
2011 *writable = false;
Xiao Guangrong81c52c52012-10-16 20:10:59 +08002012 return KVM_PFN_NOSLOT;
Paolo Bonzinib2740d32016-02-23 15:36:01 +01002013 }
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08002014
2015 /* Do not map writable pfn in the readonly memslot. */
2016 if (writable && memslot_is_readonly(slot)) {
2017 *writable = false;
2018 writable = NULL;
2019 }
2020
2021 return hva_to_pfn(addr, atomic, async, write_fault,
2022 writable);
Xiao Guangrong887c08a2010-08-22 19:10:28 +08002023}
Paolo Bonzini35204692015-04-02 11:20:48 +02002024EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
Xiao Guangrong887c08a2010-08-22 19:10:28 +08002025
Dan Williamsba049e92016-01-15 16:56:11 -08002026kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
Marcelo Tosatti612819c2010-10-22 14:18:18 -02002027 bool *writable)
2028{
Paolo Bonzinie37afc62015-05-19 16:09:04 +02002029 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
2030 write_fault, writable);
Marcelo Tosatti612819c2010-10-22 14:18:18 -02002031}
2032EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
2033
Dan Williamsba049e92016-01-15 16:56:11 -08002034kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
Marcelo Tosatti506f0d62009-12-23 14:35:19 -02002035{
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08002036 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
Marcelo Tosatti506f0d62009-12-23 14:35:19 -02002037}
Paolo Bonzinie37afc62015-05-19 16:09:04 +02002038EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
Marcelo Tosatti506f0d62009-12-23 14:35:19 -02002039
Dan Williamsba049e92016-01-15 16:56:11 -08002040kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
Xiao Guangrong037d92d2012-08-21 10:59:12 +08002041{
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08002042 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
Xiao Guangrong037d92d2012-08-21 10:59:12 +08002043}
2044EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
2045
Dan Williamsba049e92016-01-15 16:56:11 -08002046kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
Paolo Bonzini8e734852015-05-17 13:58:53 +02002047{
2048 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2049}
2050EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
2051
Dan Williamsba049e92016-01-15 16:56:11 -08002052kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
Paolo Bonzinie37afc62015-05-19 16:09:04 +02002053{
2054 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
2055}
2056EXPORT_SYMBOL_GPL(gfn_to_pfn);
2057
Dan Williamsba049e92016-01-15 16:56:11 -08002058kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
Paolo Bonzini8e734852015-05-17 13:58:53 +02002059{
2060 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
2061}
2062EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
2063
Paolo Bonzinid9ef13c2015-05-19 16:01:50 +02002064int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2065 struct page **pages, int nr_pages)
Xiao Guangrong48987782010-08-22 19:11:43 +08002066{
2067 unsigned long addr;
Arnd Bergmann076b9252017-08-10 14:14:39 +02002068 gfn_t entry = 0;
Xiao Guangrong48987782010-08-22 19:11:43 +08002069
Paolo Bonzinid9ef13c2015-05-19 16:01:50 +02002070 addr = gfn_to_hva_many(slot, gfn, &entry);
Xiao Guangrong48987782010-08-22 19:11:43 +08002071 if (kvm_is_error_hva(addr))
2072 return -1;
2073
2074 if (entry < nr_pages)
2075 return 0;
2076
Souptick Joarderdadbb612020-06-07 21:40:55 -07002077 return get_user_pages_fast_only(addr, nr_pages, FOLL_WRITE, pages);
Xiao Guangrong48987782010-08-22 19:11:43 +08002078}
2079EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
2080
Dan Williamsba049e92016-01-15 16:56:11 -08002081static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
Xiao Guangronga2766322012-07-26 11:58:59 +08002082{
Xiao Guangrong81c52c52012-10-16 20:10:59 +08002083 if (is_error_noslot_pfn(pfn))
Xiao Guangrong6cede2e2012-08-03 15:41:22 +08002084 return KVM_ERR_PTR_BAD_PAGE;
Xiao Guangronga2766322012-07-26 11:58:59 +08002085
Ard Biesheuvelbf4bea82014-11-10 08:33:56 +00002086 if (kvm_is_reserved_pfn(pfn)) {
Xiao Guangrongcb9aaa32012-08-03 15:42:10 +08002087 WARN_ON(1);
2088 return KVM_ERR_PTR_BAD_PAGE;
2089 }
2090
Xiao Guangronga2766322012-07-26 11:58:59 +08002091 return pfn_to_page(pfn);
2092}
2093
Anthony Liguori35149e22008-04-02 14:46:56 -05002094struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
2095{
Dan Williamsba049e92016-01-15 16:56:11 -08002096 kvm_pfn_t pfn;
Anthony Liguori2e2e3732008-04-30 15:37:07 -05002097
2098 pfn = gfn_to_pfn(kvm, gfn);
Anthony Liguori2e2e3732008-04-30 15:37:07 -05002099
Xiao Guangronga2766322012-07-26 11:58:59 +08002100 return kvm_pfn_to_page(pfn);
Avi Kivity954bbbc2007-03-30 14:02:32 +03002101}
2102EXPORT_SYMBOL_GPL(gfn_to_page);
2103
Boris Ostrovsky91724812019-12-05 01:30:51 +00002104void kvm_release_pfn(kvm_pfn_t pfn, bool dirty, struct gfn_to_pfn_cache *cache)
2105{
2106 if (pfn == 0)
2107 return;
2108
2109 if (cache)
2110 cache->pfn = cache->gfn = 0;
2111
2112 if (dirty)
2113 kvm_release_pfn_dirty(pfn);
2114 else
2115 kvm_release_pfn_clean(pfn);
2116}
2117
2118static void kvm_cache_gfn_to_pfn(struct kvm_memory_slot *slot, gfn_t gfn,
2119 struct gfn_to_pfn_cache *cache, u64 gen)
2120{
2121 kvm_release_pfn(cache->pfn, cache->dirty, cache);
2122
2123 cache->pfn = gfn_to_pfn_memslot(slot, gfn);
2124 cache->gfn = gfn;
2125 cache->dirty = false;
2126 cache->generation = gen;
2127}
2128
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002129static int __kvm_map_gfn(struct kvm_memslots *slots, gfn_t gfn,
Boris Ostrovsky91724812019-12-05 01:30:51 +00002130 struct kvm_host_map *map,
2131 struct gfn_to_pfn_cache *cache,
2132 bool atomic)
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002133{
2134 kvm_pfn_t pfn;
2135 void *hva = NULL;
2136 struct page *page = KVM_UNMAPPED_PAGE;
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002137 struct kvm_memory_slot *slot = __gfn_to_memslot(slots, gfn);
Boris Ostrovsky91724812019-12-05 01:30:51 +00002138 u64 gen = slots->generation;
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002139
2140 if (!map)
2141 return -EINVAL;
2142
Boris Ostrovsky91724812019-12-05 01:30:51 +00002143 if (cache) {
2144 if (!cache->pfn || cache->gfn != gfn ||
2145 cache->generation != gen) {
2146 if (atomic)
2147 return -EAGAIN;
2148 kvm_cache_gfn_to_pfn(slot, gfn, cache, gen);
2149 }
2150 pfn = cache->pfn;
2151 } else {
2152 if (atomic)
2153 return -EAGAIN;
2154 pfn = gfn_to_pfn_memslot(slot, gfn);
2155 }
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002156 if (is_error_noslot_pfn(pfn))
2157 return -EINVAL;
2158
2159 if (pfn_valid(pfn)) {
2160 page = pfn_to_page(pfn);
Boris Ostrovsky91724812019-12-05 01:30:51 +00002161 if (atomic)
2162 hva = kmap_atomic(page);
2163 else
2164 hva = kmap(page);
Paolo Bonzinid30b2142019-05-20 12:06:36 +02002165#ifdef CONFIG_HAS_IOMEM
Boris Ostrovsky91724812019-12-05 01:30:51 +00002166 } else if (!atomic) {
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002167 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
Boris Ostrovsky91724812019-12-05 01:30:51 +00002168 } else {
2169 return -EINVAL;
Paolo Bonzinid30b2142019-05-20 12:06:36 +02002170#endif
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002171 }
2172
2173 if (!hva)
2174 return -EFAULT;
2175
2176 map->page = page;
2177 map->hva = hva;
2178 map->pfn = pfn;
2179 map->gfn = gfn;
2180
2181 return 0;
2182}
2183
Boris Ostrovsky91724812019-12-05 01:30:51 +00002184int kvm_map_gfn(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map,
2185 struct gfn_to_pfn_cache *cache, bool atomic)
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002186{
Boris Ostrovsky91724812019-12-05 01:30:51 +00002187 return __kvm_map_gfn(kvm_memslots(vcpu->kvm), gfn, map,
2188 cache, atomic);
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002189}
2190EXPORT_SYMBOL_GPL(kvm_map_gfn);
2191
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002192int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
2193{
Boris Ostrovsky91724812019-12-05 01:30:51 +00002194 return __kvm_map_gfn(kvm_vcpu_memslots(vcpu), gfn, map,
2195 NULL, false);
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002196}
2197EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2198
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002199static void __kvm_unmap_gfn(struct kvm_memory_slot *memslot,
Boris Ostrovsky91724812019-12-05 01:30:51 +00002200 struct kvm_host_map *map,
2201 struct gfn_to_pfn_cache *cache,
2202 bool dirty, bool atomic)
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002203{
2204 if (!map)
2205 return;
2206
2207 if (!map->hva)
2208 return;
2209
Boris Ostrovsky91724812019-12-05 01:30:51 +00002210 if (map->page != KVM_UNMAPPED_PAGE) {
2211 if (atomic)
2212 kunmap_atomic(map->hva);
2213 else
2214 kunmap(map->page);
2215 }
Christian Borntraegereb1f2f32019-05-27 10:28:25 +02002216#ifdef CONFIG_HAS_IOMEM
Boris Ostrovsky91724812019-12-05 01:30:51 +00002217 else if (!atomic)
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002218 memunmap(map->hva);
Boris Ostrovsky91724812019-12-05 01:30:51 +00002219 else
2220 WARN_ONCE(1, "Unexpected unmapping in atomic context");
Christian Borntraegereb1f2f32019-05-27 10:28:25 +02002221#endif
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002222
Boris Ostrovsky91724812019-12-05 01:30:51 +00002223 if (dirty)
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002224 mark_page_dirty_in_slot(memslot, map->gfn);
Boris Ostrovsky91724812019-12-05 01:30:51 +00002225
2226 if (cache)
2227 cache->dirty |= dirty;
2228 else
2229 kvm_release_pfn(map->pfn, dirty, NULL);
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002230
2231 map->hva = NULL;
2232 map->page = NULL;
2233}
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002234
Boris Ostrovsky91724812019-12-05 01:30:51 +00002235int kvm_unmap_gfn(struct kvm_vcpu *vcpu, struct kvm_host_map *map,
2236 struct gfn_to_pfn_cache *cache, bool dirty, bool atomic)
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002237{
Boris Ostrovsky91724812019-12-05 01:30:51 +00002238 __kvm_unmap_gfn(gfn_to_memslot(vcpu->kvm, map->gfn), map,
2239 cache, dirty, atomic);
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002240 return 0;
2241}
2242EXPORT_SYMBOL_GPL(kvm_unmap_gfn);
2243
2244void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
2245{
Boris Ostrovsky91724812019-12-05 01:30:51 +00002246 __kvm_unmap_gfn(kvm_vcpu_gfn_to_memslot(vcpu, map->gfn), map, NULL,
2247 dirty, false);
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002248}
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002249EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2250
Paolo Bonzini8e734852015-05-17 13:58:53 +02002251struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2252{
Dan Williamsba049e92016-01-15 16:56:11 -08002253 kvm_pfn_t pfn;
Paolo Bonzini8e734852015-05-17 13:58:53 +02002254
2255 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2256
2257 return kvm_pfn_to_page(pfn);
2258}
2259EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2260
Izik Eidusb4231d62007-11-20 11:49:33 +02002261void kvm_release_page_clean(struct page *page)
2262{
Xiao Guangrong32cad842012-08-03 15:42:52 +08002263 WARN_ON(is_error_page(page));
2264
Anthony Liguori35149e22008-04-02 14:46:56 -05002265 kvm_release_pfn_clean(page_to_pfn(page));
Izik Eidusb4231d62007-11-20 11:49:33 +02002266}
2267EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2268
Dan Williamsba049e92016-01-15 16:56:11 -08002269void kvm_release_pfn_clean(kvm_pfn_t pfn)
Anthony Liguori35149e22008-04-02 14:46:56 -05002270{
Ard Biesheuvelbf4bea82014-11-10 08:33:56 +00002271 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
Anthony Liguori2e2e3732008-04-30 15:37:07 -05002272 put_page(pfn_to_page(pfn));
Anthony Liguori35149e22008-04-02 14:46:56 -05002273}
2274EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2275
Izik Eidusb4231d62007-11-20 11:49:33 +02002276void kvm_release_page_dirty(struct page *page)
Izik Eidus8a7ae052007-10-18 11:09:33 +02002277{
Xiao Guangronga2766322012-07-26 11:58:59 +08002278 WARN_ON(is_error_page(page));
2279
Anthony Liguori35149e22008-04-02 14:46:56 -05002280 kvm_release_pfn_dirty(page_to_pfn(page));
Izik Eidus8a7ae052007-10-18 11:09:33 +02002281}
Izik Eidusb4231d62007-11-20 11:49:33 +02002282EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
Izik Eidus8a7ae052007-10-18 11:09:33 +02002283
David Hildenbrandf7a65092017-09-01 17:11:43 +02002284void kvm_release_pfn_dirty(kvm_pfn_t pfn)
Anthony Liguori35149e22008-04-02 14:46:56 -05002285{
2286 kvm_set_pfn_dirty(pfn);
2287 kvm_release_pfn_clean(pfn);
2288}
David Hildenbrandf7a65092017-09-01 17:11:43 +02002289EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
Anthony Liguori35149e22008-04-02 14:46:56 -05002290
Dan Williamsba049e92016-01-15 16:56:11 -08002291void kvm_set_pfn_dirty(kvm_pfn_t pfn)
Anthony Liguori35149e22008-04-02 14:46:56 -05002292{
Miaohe Lind29c03a2019-12-05 11:05:05 +08002293 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2294 SetPageDirty(pfn_to_page(pfn));
Anthony Liguori35149e22008-04-02 14:46:56 -05002295}
2296EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2297
Dan Williamsba049e92016-01-15 16:56:11 -08002298void kvm_set_pfn_accessed(kvm_pfn_t pfn)
Anthony Liguori35149e22008-04-02 14:46:56 -05002299{
Sean Christophersona78986a2019-11-11 14:12:27 -08002300 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
Anthony Liguori2e2e3732008-04-30 15:37:07 -05002301 mark_page_accessed(pfn_to_page(pfn));
Anthony Liguori35149e22008-04-02 14:46:56 -05002302}
2303EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2304
Dan Williamsba049e92016-01-15 16:56:11 -08002305void kvm_get_pfn(kvm_pfn_t pfn)
Anthony Liguori35149e22008-04-02 14:46:56 -05002306{
Ard Biesheuvelbf4bea82014-11-10 08:33:56 +00002307 if (!kvm_is_reserved_pfn(pfn))
Anthony Liguori2e2e3732008-04-30 15:37:07 -05002308 get_page(pfn_to_page(pfn));
Anthony Liguori35149e22008-04-02 14:46:56 -05002309}
2310EXPORT_SYMBOL_GPL(kvm_get_pfn);
2311
Izik Eidus195aefd2007-10-01 22:14:18 +02002312static int next_segment(unsigned long len, int offset)
2313{
2314 if (len > PAGE_SIZE - offset)
2315 return PAGE_SIZE - offset;
2316 else
2317 return len;
2318}
2319
Paolo Bonzini8e734852015-05-17 13:58:53 +02002320static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2321 void *data, int offset, int len)
Izik Eidus195aefd2007-10-01 22:14:18 +02002322{
Izik Eiduse0506bc2007-11-11 22:10:22 +02002323 int r;
2324 unsigned long addr;
Izik Eidus195aefd2007-10-01 22:14:18 +02002325
Paolo Bonzini8e734852015-05-17 13:58:53 +02002326 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
Izik Eiduse0506bc2007-11-11 22:10:22 +02002327 if (kvm_is_error_hva(addr))
Izik Eidus195aefd2007-10-01 22:14:18 +02002328 return -EFAULT;
Paolo Bonzini3180a7f2015-04-02 14:08:20 +02002329 r = __copy_from_user(data, (void __user *)addr + offset, len);
Izik Eiduse0506bc2007-11-11 22:10:22 +02002330 if (r)
2331 return -EFAULT;
Izik Eidus195aefd2007-10-01 22:14:18 +02002332 return 0;
2333}
Paolo Bonzini8e734852015-05-17 13:58:53 +02002334
2335int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2336 int len)
2337{
2338 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2339
2340 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2341}
Izik Eidus195aefd2007-10-01 22:14:18 +02002342EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2343
Paolo Bonzini8e734852015-05-17 13:58:53 +02002344int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2345 int offset, int len)
2346{
2347 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2348
2349 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2350}
2351EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2352
Izik Eidus195aefd2007-10-01 22:14:18 +02002353int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2354{
2355 gfn_t gfn = gpa >> PAGE_SHIFT;
2356 int seg;
2357 int offset = offset_in_page(gpa);
2358 int ret;
2359
2360 while ((seg = next_segment(len, offset)) != 0) {
2361 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2362 if (ret < 0)
2363 return ret;
2364 offset = 0;
2365 len -= seg;
2366 data += seg;
2367 ++gfn;
2368 }
2369 return 0;
2370}
2371EXPORT_SYMBOL_GPL(kvm_read_guest);
2372
Paolo Bonzini8e734852015-05-17 13:58:53 +02002373int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2374{
2375 gfn_t gfn = gpa >> PAGE_SHIFT;
2376 int seg;
2377 int offset = offset_in_page(gpa);
2378 int ret;
2379
2380 while ((seg = next_segment(len, offset)) != 0) {
2381 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2382 if (ret < 0)
2383 return ret;
2384 offset = 0;
2385 len -= seg;
2386 data += seg;
2387 ++gfn;
2388 }
2389 return 0;
2390}
2391EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2392
2393static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2394 void *data, int offset, unsigned long len)
Marcelo Tosatti7ec54582007-12-20 19:18:23 -05002395{
2396 int r;
2397 unsigned long addr;
Marcelo Tosatti7ec54582007-12-20 19:18:23 -05002398
Paolo Bonzini8e734852015-05-17 13:58:53 +02002399 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
Marcelo Tosatti7ec54582007-12-20 19:18:23 -05002400 if (kvm_is_error_hva(addr))
2401 return -EFAULT;
Andrea Arcangeli0aac03f2008-01-30 19:57:35 +01002402 pagefault_disable();
Paolo Bonzini3180a7f2015-04-02 14:08:20 +02002403 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
Andrea Arcangeli0aac03f2008-01-30 19:57:35 +01002404 pagefault_enable();
Marcelo Tosatti7ec54582007-12-20 19:18:23 -05002405 if (r)
2406 return -EFAULT;
2407 return 0;
2408}
Marcelo Tosatti7ec54582007-12-20 19:18:23 -05002409
Paolo Bonzini8e734852015-05-17 13:58:53 +02002410int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2411 void *data, unsigned long len)
2412{
2413 gfn_t gfn = gpa >> PAGE_SHIFT;
2414 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2415 int offset = offset_in_page(gpa);
2416
2417 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2418}
2419EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2420
2421static int __kvm_write_guest_page(struct kvm_memory_slot *memslot, gfn_t gfn,
2422 const void *data, int offset, int len)
Izik Eidus195aefd2007-10-01 22:14:18 +02002423{
Izik Eiduse0506bc2007-11-11 22:10:22 +02002424 int r;
2425 unsigned long addr;
Izik Eidus195aefd2007-10-01 22:14:18 +02002426
Radim Krčmář251eb842015-04-10 21:47:27 +02002427 addr = gfn_to_hva_memslot(memslot, gfn);
Izik Eiduse0506bc2007-11-11 22:10:22 +02002428 if (kvm_is_error_hva(addr))
Izik Eidus195aefd2007-10-01 22:14:18 +02002429 return -EFAULT;
Xiao Guangrong8b0cedf2011-05-15 23:22:04 +08002430 r = __copy_to_user((void __user *)addr + offset, data, len);
Izik Eiduse0506bc2007-11-11 22:10:22 +02002431 if (r)
2432 return -EFAULT;
Paolo Bonzinibc009e42015-05-26 12:43:41 +02002433 mark_page_dirty_in_slot(memslot, gfn);
Izik Eidus195aefd2007-10-01 22:14:18 +02002434 return 0;
2435}
Paolo Bonzini8e734852015-05-17 13:58:53 +02002436
2437int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2438 const void *data, int offset, int len)
2439{
2440 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2441
2442 return __kvm_write_guest_page(slot, gfn, data, offset, len);
2443}
Izik Eidus195aefd2007-10-01 22:14:18 +02002444EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2445
Paolo Bonzini8e734852015-05-17 13:58:53 +02002446int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2447 const void *data, int offset, int len)
2448{
2449 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2450
2451 return __kvm_write_guest_page(slot, gfn, data, offset, len);
2452}
2453EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
2454
Izik Eidus195aefd2007-10-01 22:14:18 +02002455int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
2456 unsigned long len)
2457{
2458 gfn_t gfn = gpa >> PAGE_SHIFT;
2459 int seg;
2460 int offset = offset_in_page(gpa);
2461 int ret;
2462
2463 while ((seg = next_segment(len, offset)) != 0) {
2464 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2465 if (ret < 0)
2466 return ret;
2467 offset = 0;
2468 len -= seg;
2469 data += seg;
2470 ++gfn;
2471 }
2472 return 0;
2473}
Wincy Vanff651cb2014-12-11 08:52:58 +03002474EXPORT_SYMBOL_GPL(kvm_write_guest);
Izik Eidus195aefd2007-10-01 22:14:18 +02002475
Paolo Bonzini8e734852015-05-17 13:58:53 +02002476int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2477 unsigned long len)
2478{
2479 gfn_t gfn = gpa >> PAGE_SHIFT;
2480 int seg;
2481 int offset = offset_in_page(gpa);
2482 int ret;
2483
2484 while ((seg = next_segment(len, offset)) != 0) {
2485 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2486 if (ret < 0)
2487 return ret;
2488 offset = 0;
2489 len -= seg;
2490 data += seg;
2491 ++gfn;
2492 }
2493 return 0;
2494}
2495EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2496
Paolo Bonzini5a2d4362017-02-03 20:32:28 -08002497static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
2498 struct gfn_to_hva_cache *ghc,
2499 gpa_t gpa, unsigned long len)
Gleb Natapov49c77542010-10-18 15:22:23 +02002500{
Gleb Natapov49c77542010-10-18 15:22:23 +02002501 int offset = offset_in_page(gpa);
Andrew Honig8f964522013-03-29 09:35:21 -07002502 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2503 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2504 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2505 gfn_t nr_pages_avail;
Gleb Natapov49c77542010-10-18 15:22:23 +02002506
Sean Christopherson6ad1e292020-01-09 14:58:55 -05002507 /* Update ghc->generation before performing any error checks. */
Gleb Natapov49c77542010-10-18 15:22:23 +02002508 ghc->generation = slots->generation;
Sean Christopherson6ad1e292020-01-09 14:58:55 -05002509
2510 if (start_gfn > end_gfn) {
2511 ghc->hva = KVM_HVA_ERR_BAD;
2512 return -EINVAL;
2513 }
Jim Mattsonf1b9dd52018-12-17 13:53:33 -08002514
2515 /*
2516 * If the requested region crosses two memslots, we still
2517 * verify that the entire region is valid here.
2518 */
Sean Christopherson6ad1e292020-01-09 14:58:55 -05002519 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
Jim Mattsonf1b9dd52018-12-17 13:53:33 -08002520 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2521 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2522 &nr_pages_avail);
2523 if (kvm_is_error_hva(ghc->hva))
Sean Christopherson6ad1e292020-01-09 14:58:55 -05002524 return -EFAULT;
Andrew Honig8f964522013-03-29 09:35:21 -07002525 }
Jim Mattsonf1b9dd52018-12-17 13:53:33 -08002526
2527 /* Use the slow path for cross page reads and writes. */
Sean Christopherson6ad1e292020-01-09 14:58:55 -05002528 if (nr_pages_needed == 1)
Jim Mattsonf1b9dd52018-12-17 13:53:33 -08002529 ghc->hva += offset;
2530 else
2531 ghc->memslot = NULL;
2532
Sean Christopherson6ad1e292020-01-09 14:58:55 -05002533 ghc->gpa = gpa;
2534 ghc->len = len;
2535 return 0;
Gleb Natapov49c77542010-10-18 15:22:23 +02002536}
Paolo Bonzini5a2d4362017-02-03 20:32:28 -08002537
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002538int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
Paolo Bonzini5a2d4362017-02-03 20:32:28 -08002539 gpa_t gpa, unsigned long len)
2540{
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002541 struct kvm_memslots *slots = kvm_memslots(kvm);
Paolo Bonzini5a2d4362017-02-03 20:32:28 -08002542 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
2543}
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002544EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
Gleb Natapov49c77542010-10-18 15:22:23 +02002545
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002546int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
Jim Mattson7a86dab2018-12-14 14:34:43 -08002547 void *data, unsigned int offset,
2548 unsigned long len)
Gleb Natapov49c77542010-10-18 15:22:23 +02002549{
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002550 struct kvm_memslots *slots = kvm_memslots(kvm);
Gleb Natapov49c77542010-10-18 15:22:23 +02002551 int r;
Pan Xinhui4ec6e862016-11-02 05:08:34 -04002552 gpa_t gpa = ghc->gpa + offset;
Gleb Natapov49c77542010-10-18 15:22:23 +02002553
Pan Xinhui4ec6e862016-11-02 05:08:34 -04002554 BUG_ON(len + offset > ghc->len);
Andrew Honig8f964522013-03-29 09:35:21 -07002555
Sean Christophersondc9ce712020-01-09 15:56:20 -08002556 if (slots->generation != ghc->generation) {
2557 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2558 return -EFAULT;
2559 }
Andrew Honig8f964522013-03-29 09:35:21 -07002560
Gleb Natapov49c77542010-10-18 15:22:23 +02002561 if (kvm_is_error_hva(ghc->hva))
2562 return -EFAULT;
2563
Sean Christophersonfcfbc612020-01-09 15:56:18 -08002564 if (unlikely(!ghc->memslot))
2565 return kvm_write_guest(kvm, gpa, data, len);
2566
Pan Xinhui4ec6e862016-11-02 05:08:34 -04002567 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
Gleb Natapov49c77542010-10-18 15:22:23 +02002568 if (r)
2569 return -EFAULT;
Pan Xinhui4ec6e862016-11-02 05:08:34 -04002570 mark_page_dirty_in_slot(ghc->memslot, gpa >> PAGE_SHIFT);
Gleb Natapov49c77542010-10-18 15:22:23 +02002571
2572 return 0;
2573}
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002574EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
Pan Xinhui4ec6e862016-11-02 05:08:34 -04002575
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002576int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2577 void *data, unsigned long len)
Pan Xinhui4ec6e862016-11-02 05:08:34 -04002578{
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002579 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
Pan Xinhui4ec6e862016-11-02 05:08:34 -04002580}
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002581EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
Gleb Natapov49c77542010-10-18 15:22:23 +02002582
Vitaly Kuznetsov0958f0c2020-05-25 16:41:19 +02002583int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2584 void *data, unsigned int offset,
2585 unsigned long len)
Gleb Natapove03b6442011-07-11 15:28:11 -04002586{
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002587 struct kvm_memslots *slots = kvm_memslots(kvm);
Gleb Natapove03b6442011-07-11 15:28:11 -04002588 int r;
Vitaly Kuznetsov0958f0c2020-05-25 16:41:19 +02002589 gpa_t gpa = ghc->gpa + offset;
Gleb Natapove03b6442011-07-11 15:28:11 -04002590
Vitaly Kuznetsov0958f0c2020-05-25 16:41:19 +02002591 BUG_ON(len + offset > ghc->len);
Andrew Honig8f964522013-03-29 09:35:21 -07002592
Sean Christophersondc9ce712020-01-09 15:56:20 -08002593 if (slots->generation != ghc->generation) {
2594 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2595 return -EFAULT;
2596 }
Andrew Honig8f964522013-03-29 09:35:21 -07002597
Gleb Natapove03b6442011-07-11 15:28:11 -04002598 if (kvm_is_error_hva(ghc->hva))
2599 return -EFAULT;
2600
Sean Christophersonfcfbc612020-01-09 15:56:18 -08002601 if (unlikely(!ghc->memslot))
Vitaly Kuznetsov0958f0c2020-05-25 16:41:19 +02002602 return kvm_read_guest(kvm, gpa, data, len);
Sean Christophersonfcfbc612020-01-09 15:56:18 -08002603
Vitaly Kuznetsov0958f0c2020-05-25 16:41:19 +02002604 r = __copy_from_user(data, (void __user *)ghc->hva + offset, len);
Gleb Natapove03b6442011-07-11 15:28:11 -04002605 if (r)
2606 return -EFAULT;
2607
2608 return 0;
2609}
Vitaly Kuznetsov0958f0c2020-05-25 16:41:19 +02002610EXPORT_SYMBOL_GPL(kvm_read_guest_offset_cached);
2611
2612int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2613 void *data, unsigned long len)
2614{
2615 return kvm_read_guest_offset_cached(kvm, ghc, data, 0, len);
2616}
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002617EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
Gleb Natapove03b6442011-07-11 15:28:11 -04002618
Izik Eidus195aefd2007-10-01 22:14:18 +02002619int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
2620{
Heiko Carstens8a3caa62013-11-18 10:35:55 +01002621 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
2622
2623 return kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
Izik Eidus195aefd2007-10-01 22:14:18 +02002624}
2625EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
2626
2627int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
2628{
2629 gfn_t gfn = gpa >> PAGE_SHIFT;
2630 int seg;
2631 int offset = offset_in_page(gpa);
2632 int ret;
2633
Kevin Mulveybfda0e82015-02-20 08:21:36 -05002634 while ((seg = next_segment(len, offset)) != 0) {
Izik Eidus195aefd2007-10-01 22:14:18 +02002635 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
2636 if (ret < 0)
2637 return ret;
2638 offset = 0;
2639 len -= seg;
2640 ++gfn;
2641 }
2642 return 0;
2643}
2644EXPORT_SYMBOL_GPL(kvm_clear_guest);
2645
Ben Gardona6a0b052020-10-14 11:26:55 -07002646void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot, gfn_t gfn)
Avi Kivity6aa8b732006-12-10 02:21:36 -08002647{
Rusty Russell7e9d6192007-07-31 20:41:14 +10002648 if (memslot && memslot->dirty_bitmap) {
2649 unsigned long rel_gfn = gfn - memslot->base_gfn;
Avi Kivity6aa8b732006-12-10 02:21:36 -08002650
Takuya Yoshikawab74ca3b2012-10-04 17:13:12 -07002651 set_bit_le(rel_gfn, memslot->dirty_bitmap);
Avi Kivity6aa8b732006-12-10 02:21:36 -08002652 }
2653}
Ben Gardona6a0b052020-10-14 11:26:55 -07002654EXPORT_SYMBOL_GPL(mark_page_dirty_in_slot);
Avi Kivity6aa8b732006-12-10 02:21:36 -08002655
Gleb Natapov49c77542010-10-18 15:22:23 +02002656void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2657{
2658 struct kvm_memory_slot *memslot;
2659
2660 memslot = gfn_to_memslot(kvm, gfn);
Paolo Bonzinibc009e42015-05-26 12:43:41 +02002661 mark_page_dirty_in_slot(memslot, gfn);
Gleb Natapov49c77542010-10-18 15:22:23 +02002662}
Aneesh Kumar K.V2ba9f0d2013-10-07 22:17:59 +05302663EXPORT_SYMBOL_GPL(mark_page_dirty);
Gleb Natapov49c77542010-10-18 15:22:23 +02002664
Paolo Bonzini8e734852015-05-17 13:58:53 +02002665void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2666{
2667 struct kvm_memory_slot *memslot;
2668
2669 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2670 mark_page_dirty_in_slot(memslot, gfn);
2671}
2672EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2673
Jan H. Schönherr20b70352017-11-24 22:39:01 +01002674void kvm_sigset_activate(struct kvm_vcpu *vcpu)
2675{
2676 if (!vcpu->sigset_active)
2677 return;
2678
2679 /*
2680 * This does a lockless modification of ->real_blocked, which is fine
2681 * because, only current can change ->real_blocked and all readers of
2682 * ->real_blocked don't care as long ->real_blocked is always a subset
2683 * of ->blocked.
2684 */
2685 sigprocmask(SIG_SETMASK, &vcpu->sigset, &current->real_blocked);
2686}
2687
2688void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
2689{
2690 if (!vcpu->sigset_active)
2691 return;
2692
2693 sigprocmask(SIG_SETMASK, &current->real_blocked, NULL);
2694 sigemptyset(&current->real_blocked);
2695}
2696
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002697static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2698{
Nir Weinerdee339b2019-01-27 12:17:16 +02002699 unsigned int old, val, grow, grow_start;
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002700
Wanpeng Li2cbd7822015-09-03 22:07:39 +08002701 old = val = vcpu->halt_poll_ns;
Nir Weinerdee339b2019-01-27 12:17:16 +02002702 grow_start = READ_ONCE(halt_poll_ns_grow_start);
Christian Borntraeger6b6de682016-02-09 13:47:55 +01002703 grow = READ_ONCE(halt_poll_ns_grow);
Nir Weiner7fa08e72019-01-27 12:17:14 +02002704 if (!grow)
2705 goto out;
2706
Nir Weinerdee339b2019-01-27 12:17:16 +02002707 val *= grow;
2708 if (val < grow_start)
2709 val = grow_start;
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002710
David Matlack313f6362016-03-08 16:19:44 -08002711 if (val > halt_poll_ns)
2712 val = halt_poll_ns;
2713
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002714 vcpu->halt_poll_ns = val;
Nir Weiner7fa08e72019-01-27 12:17:14 +02002715out:
Wanpeng Li2cbd7822015-09-03 22:07:39 +08002716 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002717}
2718
2719static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2720{
Christian Borntraeger6b6de682016-02-09 13:47:55 +01002721 unsigned int old, val, shrink;
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002722
Wanpeng Li2cbd7822015-09-03 22:07:39 +08002723 old = val = vcpu->halt_poll_ns;
Christian Borntraeger6b6de682016-02-09 13:47:55 +01002724 shrink = READ_ONCE(halt_poll_ns_shrink);
2725 if (shrink == 0)
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002726 val = 0;
2727 else
Christian Borntraeger6b6de682016-02-09 13:47:55 +01002728 val /= shrink;
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002729
2730 vcpu->halt_poll_ns = val;
Wanpeng Li2cbd7822015-09-03 22:07:39 +08002731 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002732}
2733
Paolo Bonzinif7819512015-02-04 18:20:58 +01002734static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
2735{
Junaid Shahid50c28f22018-06-27 14:59:11 -07002736 int ret = -EINTR;
2737 int idx = srcu_read_lock(&vcpu->kvm->srcu);
2738
Paolo Bonzinif7819512015-02-04 18:20:58 +01002739 if (kvm_arch_vcpu_runnable(vcpu)) {
2740 kvm_make_request(KVM_REQ_UNHALT, vcpu);
Junaid Shahid50c28f22018-06-27 14:59:11 -07002741 goto out;
Paolo Bonzinif7819512015-02-04 18:20:58 +01002742 }
2743 if (kvm_cpu_has_pending_timer(vcpu))
Junaid Shahid50c28f22018-06-27 14:59:11 -07002744 goto out;
Paolo Bonzinif7819512015-02-04 18:20:58 +01002745 if (signal_pending(current))
Junaid Shahid50c28f22018-06-27 14:59:11 -07002746 goto out;
Paolo Bonzinif7819512015-02-04 18:20:58 +01002747
Junaid Shahid50c28f22018-06-27 14:59:11 -07002748 ret = 0;
2749out:
2750 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2751 return ret;
Paolo Bonzinif7819512015-02-04 18:20:58 +01002752}
2753
David Matlackcb953122020-05-08 11:22:40 -07002754static inline void
2755update_halt_poll_stats(struct kvm_vcpu *vcpu, u64 poll_ns, bool waited)
2756{
2757 if (waited)
2758 vcpu->stat.halt_poll_fail_ns += poll_ns;
2759 else
2760 vcpu->stat.halt_poll_success_ns += poll_ns;
2761}
2762
Eddie Dongb6958ce2007-07-18 12:15:21 +03002763/*
2764 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
2765 */
Hollis Blanchard8776e512007-10-31 17:24:24 -05002766void kvm_vcpu_block(struct kvm_vcpu *vcpu)
Eddie Dongb6958ce2007-07-18 12:15:21 +03002767{
David Matlackcb953122020-05-08 11:22:40 -07002768 ktime_t start, cur, poll_end;
Paolo Bonzinif7819512015-02-04 18:20:58 +01002769 bool waited = false;
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002770 u64 block_ns;
Paolo Bonzinif7819512015-02-04 18:20:58 +01002771
Marc Zyngier07ab0f82019-08-02 11:37:09 +01002772 kvm_arch_vcpu_blocking(vcpu);
2773
David Matlackcb953122020-05-08 11:22:40 -07002774 start = cur = poll_end = ktime_get();
Christian Borntraegercdd6ad32019-03-05 05:30:01 -05002775 if (vcpu->halt_poll_ns && !kvm_arch_no_poll(vcpu)) {
Wanpeng Li19020f82015-09-03 22:07:37 +08002776 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
Xiubo Lif95ef0cd2015-02-26 14:58:23 +08002777
Paolo Bonzini62bea5b2015-09-15 18:27:57 +02002778 ++vcpu->stat.halt_attempted_poll;
Paolo Bonzinif7819512015-02-04 18:20:58 +01002779 do {
2780 /*
2781 * This sets KVM_REQ_UNHALT if an interrupt
2782 * arrives.
2783 */
2784 if (kvm_vcpu_check_block(vcpu) < 0) {
2785 ++vcpu->stat.halt_successful_poll;
Christian Borntraeger3491caf2016-05-13 12:16:35 +02002786 if (!vcpu_valid_wakeup(vcpu))
2787 ++vcpu->stat.halt_poll_invalid;
Paolo Bonzinif7819512015-02-04 18:20:58 +01002788 goto out;
2789 }
David Matlackcb953122020-05-08 11:22:40 -07002790 poll_end = cur = ktime_get();
Paolo Bonzinif7819512015-02-04 18:20:58 +01002791 } while (single_task_running() && ktime_before(cur, stop));
2792 }
Eddie Dongb6958ce2007-07-18 12:15:21 +03002793
Davidlohr Buesoda4ad882020-04-23 22:48:37 -07002794 prepare_to_rcuwait(&vcpu->wait);
Marcelo Tosattie5c239c2008-05-08 19:47:01 -03002795 for (;;) {
Davidlohr Buesoda4ad882020-04-23 22:48:37 -07002796 set_current_state(TASK_INTERRUPTIBLE);
Eddie Dongb6958ce2007-07-18 12:15:21 +03002797
Paolo Bonzinif7819512015-02-04 18:20:58 +01002798 if (kvm_vcpu_check_block(vcpu) < 0)
Marcelo Tosattie5c239c2008-05-08 19:47:01 -03002799 break;
2800
Paolo Bonzinif7819512015-02-04 18:20:58 +01002801 waited = true;
Eddie Dongb6958ce2007-07-18 12:15:21 +03002802 schedule();
Eddie Dongb6958ce2007-07-18 12:15:21 +03002803 }
Davidlohr Buesoda4ad882020-04-23 22:48:37 -07002804 finish_rcuwait(&vcpu->wait);
Paolo Bonzinif7819512015-02-04 18:20:58 +01002805 cur = ktime_get();
Paolo Bonzinif7819512015-02-04 18:20:58 +01002806out:
Marc Zyngier07ab0f82019-08-02 11:37:09 +01002807 kvm_arch_vcpu_unblocking(vcpu);
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002808 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
2809
David Matlackcb953122020-05-08 11:22:40 -07002810 update_halt_poll_stats(
2811 vcpu, ktime_to_ns(ktime_sub(poll_end, start)), waited);
2812
Wanpeng Li44551b22019-09-29 09:06:56 +08002813 if (!kvm_arch_no_poll(vcpu)) {
2814 if (!vcpu_valid_wakeup(vcpu)) {
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002815 shrink_halt_poll_ns(vcpu);
David Matlackacd05782020-04-17 15:14:46 -07002816 } else if (vcpu->kvm->max_halt_poll_ns) {
Wanpeng Li44551b22019-09-29 09:06:56 +08002817 if (block_ns <= vcpu->halt_poll_ns)
2818 ;
2819 /* we had a long block, shrink polling */
David Matlackacd05782020-04-17 15:14:46 -07002820 else if (vcpu->halt_poll_ns &&
2821 block_ns > vcpu->kvm->max_halt_poll_ns)
Wanpeng Li44551b22019-09-29 09:06:56 +08002822 shrink_halt_poll_ns(vcpu);
2823 /* we had a short halt and our poll time is too small */
David Matlackacd05782020-04-17 15:14:46 -07002824 else if (vcpu->halt_poll_ns < vcpu->kvm->max_halt_poll_ns &&
2825 block_ns < vcpu->kvm->max_halt_poll_ns)
Wanpeng Li44551b22019-09-29 09:06:56 +08002826 grow_halt_poll_ns(vcpu);
2827 } else {
2828 vcpu->halt_poll_ns = 0;
2829 }
2830 }
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002831
Christian Borntraeger3491caf2016-05-13 12:16:35 +02002832 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
2833 kvm_arch_vcpu_block_finish(vcpu);
Eddie Dongb6958ce2007-07-18 12:15:21 +03002834}
Aneesh Kumar K.V2ba9f0d2013-10-07 22:17:59 +05302835EXPORT_SYMBOL_GPL(kvm_vcpu_block);
Eddie Dongb6958ce2007-07-18 12:15:21 +03002836
Radim Krčmář178f02f2017-04-26 22:32:26 +02002837bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
Christoffer Dallb6d33832012-03-08 16:44:24 -05002838{
Davidlohr Buesoda4ad882020-04-23 22:48:37 -07002839 struct rcuwait *waitp;
Christoffer Dallb6d33832012-03-08 16:44:24 -05002840
Davidlohr Buesoda4ad882020-04-23 22:48:37 -07002841 waitp = kvm_arch_vcpu_get_wait(vcpu);
2842 if (rcuwait_wake_up(waitp)) {
Wanpeng Lid73eb572019-07-18 19:39:06 +08002843 WRITE_ONCE(vcpu->ready, true);
Christoffer Dallb6d33832012-03-08 16:44:24 -05002844 ++vcpu->stat.halt_wakeup;
Radim Krčmář178f02f2017-04-26 22:32:26 +02002845 return true;
Christoffer Dallb6d33832012-03-08 16:44:24 -05002846 }
2847
Radim Krčmář178f02f2017-04-26 22:32:26 +02002848 return false;
Radim Krčmářdd1a4cc2016-05-04 14:09:44 -05002849}
2850EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
2851
Paolo Bonzini0266c892017-05-04 15:14:13 +02002852#ifndef CONFIG_S390
Radim Krčmářdd1a4cc2016-05-04 14:09:44 -05002853/*
2854 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
2855 */
2856void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
2857{
2858 int me;
2859 int cpu = vcpu->cpu;
2860
Radim Krčmář178f02f2017-04-26 22:32:26 +02002861 if (kvm_vcpu_wake_up(vcpu))
2862 return;
2863
Christoffer Dallb6d33832012-03-08 16:44:24 -05002864 me = get_cpu();
2865 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
2866 if (kvm_arch_vcpu_should_kick(vcpu))
2867 smp_send_reschedule(cpu);
2868 put_cpu();
2869}
Yang Zhanga20ed542013-04-11 19:25:15 +08002870EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
Paolo Bonzini0266c892017-05-04 15:14:13 +02002871#endif /* !CONFIG_S390 */
Christoffer Dallb6d33832012-03-08 16:44:24 -05002872
Dan Carpenterfa933842014-05-23 13:20:42 +03002873int kvm_vcpu_yield_to(struct kvm_vcpu *target)
Konstantin Weitz41628d32012-04-25 15:30:38 +02002874{
2875 struct pid *pid;
2876 struct task_struct *task = NULL;
Dan Carpenterfa933842014-05-23 13:20:42 +03002877 int ret = 0;
Konstantin Weitz41628d32012-04-25 15:30:38 +02002878
2879 rcu_read_lock();
2880 pid = rcu_dereference(target->pid);
2881 if (pid)
Sam Bobroff27fbe64b2014-09-19 09:40:41 +10002882 task = get_pid_task(pid, PIDTYPE_PID);
Konstantin Weitz41628d32012-04-25 15:30:38 +02002883 rcu_read_unlock();
2884 if (!task)
Raghavendra K Tc45c5282013-01-22 13:09:24 +05302885 return ret;
Raghavendra K Tc45c5282013-01-22 13:09:24 +05302886 ret = yield_to(task, 1);
Konstantin Weitz41628d32012-04-25 15:30:38 +02002887 put_task_struct(task);
Raghavendra K Tc45c5282013-01-22 13:09:24 +05302888
2889 return ret;
Konstantin Weitz41628d32012-04-25 15:30:38 +02002890}
2891EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
2892
Raghavendra K T06e48c52012-07-19 15:17:52 +05302893/*
2894 * Helper that checks whether a VCPU is eligible for directed yield.
2895 * Most eligible candidate to yield is decided by following heuristics:
2896 *
2897 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
2898 * (preempted lock holder), indicated by @in_spin_loop.
Fuad Tabba656012c2020-04-01 15:03:10 +01002899 * Set at the beginning and cleared at the end of interception/PLE handler.
Raghavendra K T06e48c52012-07-19 15:17:52 +05302900 *
2901 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
2902 * chance last time (mostly it has become eligible now since we have probably
2903 * yielded to lockholder in last iteration. This is done by toggling
2904 * @dy_eligible each time a VCPU checked for eligibility.)
2905 *
2906 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
2907 * to preempted lock-holder could result in wrong VCPU selection and CPU
2908 * burning. Giving priority for a potential lock-holder increases lock
2909 * progress.
2910 *
2911 * Since algorithm is based on heuristics, accessing another VCPU data without
2912 * locking does not harm. It may result in trying to yield to same VCPU, fail
2913 * and continue with next VCPU and so on.
2914 */
Stephen Hemminger79408762013-12-29 12:12:29 -08002915static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
Raghavendra K T06e48c52012-07-19 15:17:52 +05302916{
Scott Wood4a55dd72014-01-09 18:43:16 -06002917#ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
Raghavendra K T06e48c52012-07-19 15:17:52 +05302918 bool eligible;
2919
2920 eligible = !vcpu->spin_loop.in_spin_loop ||
Christian Borntraeger34656112014-09-04 21:13:31 +02002921 vcpu->spin_loop.dy_eligible;
Raghavendra K T06e48c52012-07-19 15:17:52 +05302922
2923 if (vcpu->spin_loop.in_spin_loop)
2924 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
2925
2926 return eligible;
Scott Wood4a55dd72014-01-09 18:43:16 -06002927#else
2928 return true;
Raghavendra K T06e48c52012-07-19 15:17:52 +05302929#endif
Scott Wood4a55dd72014-01-09 18:43:16 -06002930}
Raghavendra K Tc45c5282013-01-22 13:09:24 +05302931
Wanpeng Li17e433b2019-08-05 10:03:19 +08002932/*
2933 * Unlike kvm_arch_vcpu_runnable, this function is called outside
2934 * a vcpu_load/vcpu_put pair. However, for most architectures
2935 * kvm_arch_vcpu_runnable does not require vcpu_load.
2936 */
2937bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
2938{
2939 return kvm_arch_vcpu_runnable(vcpu);
2940}
2941
2942static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
2943{
2944 if (kvm_arch_dy_runnable(vcpu))
2945 return true;
2946
2947#ifdef CONFIG_KVM_ASYNC_PF
2948 if (!list_empty_careful(&vcpu->async_pf.done))
2949 return true;
2950#endif
2951
2952 return false;
2953}
2954
Longpeng(Mike)199b5762017-08-08 12:05:32 +08002955void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
Zhai, Edwind255f4f2009-10-09 18:03:20 +08002956{
Rik van Riel217ece62011-02-01 09:53:28 -05002957 struct kvm *kvm = me->kvm;
2958 struct kvm_vcpu *vcpu;
2959 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
2960 int yielded = 0;
Raghavendra K Tc45c5282013-01-22 13:09:24 +05302961 int try = 3;
Rik van Riel217ece62011-02-01 09:53:28 -05002962 int pass;
2963 int i;
Zhai, Edwind255f4f2009-10-09 18:03:20 +08002964
Raghavendra K T4c088492012-07-18 19:07:46 +05302965 kvm_vcpu_set_in_spin_loop(me, true);
Rik van Riel217ece62011-02-01 09:53:28 -05002966 /*
2967 * We boost the priority of a VCPU that is runnable but not
2968 * currently running, because it got preempted by something
2969 * else and called schedule in __vcpu_run. Hopefully that
2970 * VCPU is holding the lock that we need and will release it.
2971 * We approximate round-robin by starting at the last boosted VCPU.
2972 */
Raghavendra K Tc45c5282013-01-22 13:09:24 +05302973 for (pass = 0; pass < 2 && !yielded && try; pass++) {
Rik van Riel217ece62011-02-01 09:53:28 -05002974 kvm_for_each_vcpu(i, vcpu, kvm) {
Rik van Riel5cfc2aa2012-06-19 16:51:04 -04002975 if (!pass && i <= last_boosted_vcpu) {
Rik van Riel217ece62011-02-01 09:53:28 -05002976 i = last_boosted_vcpu;
2977 continue;
2978 } else if (pass && i > last_boosted_vcpu)
2979 break;
Wanpeng Lid73eb572019-07-18 19:39:06 +08002980 if (!READ_ONCE(vcpu->ready))
Raghavendra K T7bc7ae22013-03-04 23:32:27 +05302981 continue;
Rik van Riel217ece62011-02-01 09:53:28 -05002982 if (vcpu == me)
2983 continue;
Davidlohr Buesoda4ad882020-04-23 22:48:37 -07002984 if (rcuwait_active(&vcpu->wait) &&
2985 !vcpu_dy_runnable(vcpu))
Rik van Riel217ece62011-02-01 09:53:28 -05002986 continue;
Wanpeng Li046ddee2019-08-01 11:30:14 +08002987 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
2988 !kvm_arch_vcpu_in_kernel(vcpu))
Longpeng(Mike)199b5762017-08-08 12:05:32 +08002989 continue;
Raghavendra K T06e48c52012-07-19 15:17:52 +05302990 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
2991 continue;
Raghavendra K Tc45c5282013-01-22 13:09:24 +05302992
2993 yielded = kvm_vcpu_yield_to(vcpu);
2994 if (yielded > 0) {
Rik van Riel217ece62011-02-01 09:53:28 -05002995 kvm->last_boosted_vcpu = i;
Rik van Riel217ece62011-02-01 09:53:28 -05002996 break;
Raghavendra K Tc45c5282013-01-22 13:09:24 +05302997 } else if (yielded < 0) {
2998 try--;
2999 if (!try)
3000 break;
Rik van Riel217ece62011-02-01 09:53:28 -05003001 }
Rik van Riel217ece62011-02-01 09:53:28 -05003002 }
3003 }
Raghavendra K T4c088492012-07-18 19:07:46 +05303004 kvm_vcpu_set_in_spin_loop(me, false);
Raghavendra K T06e48c52012-07-19 15:17:52 +05303005
3006 /* Ensure vcpu is not eligible during next spinloop */
3007 kvm_vcpu_set_dy_eligible(me, false);
Zhai, Edwind255f4f2009-10-09 18:03:20 +08003008}
3009EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
3010
Souptick Joarder1499fa82018-04-19 00:49:58 +05303011static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02003012{
Dave Jiang11bac802017-02-24 14:56:41 -08003013 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02003014 struct page *page;
3015
npiggin@suse.dee4a533a2007-12-05 18:15:52 +11003016 if (vmf->pgoff == 0)
Avi Kivity039576c2007-03-20 12:46:50 +02003017 page = virt_to_page(vcpu->run);
Avi Kivity09566762008-01-23 18:14:23 +02003018#ifdef CONFIG_X86
npiggin@suse.dee4a533a2007-12-05 18:15:52 +11003019 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
Zhang Xiantaoad312c72007-12-13 23:50:52 +08003020 page = virt_to_page(vcpu->arch.pio_data);
Avi Kivity09566762008-01-23 18:14:23 +02003021#endif
Paolo Bonzini4b4357e2017-03-31 13:53:23 +02003022#ifdef CONFIG_KVM_MMIO
Laurent Vivier5f94c172008-05-30 16:05:54 +02003023 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
3024 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
3025#endif
Avi Kivity039576c2007-03-20 12:46:50 +02003026 else
Carsten Otte5b1c1492012-01-04 10:25:23 +01003027 return kvm_arch_vcpu_fault(vcpu, vmf);
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02003028 get_page(page);
npiggin@suse.dee4a533a2007-12-05 18:15:52 +11003029 vmf->page = page;
3030 return 0;
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02003031}
3032
Alexey Dobriyanf0f37e2f2009-09-27 22:29:37 +04003033static const struct vm_operations_struct kvm_vcpu_vm_ops = {
npiggin@suse.dee4a533a2007-12-05 18:15:52 +11003034 .fault = kvm_vcpu_fault,
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02003035};
3036
3037static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
3038{
3039 vma->vm_ops = &kvm_vcpu_vm_ops;
3040 return 0;
3041}
3042
Avi Kivitybccf2152007-02-21 18:04:26 +02003043static int kvm_vcpu_release(struct inode *inode, struct file *filp)
3044{
3045 struct kvm_vcpu *vcpu = filp->private_data;
3046
Al Viro66c0b392008-04-19 20:33:56 +01003047 kvm_put_kvm(vcpu->kvm);
Avi Kivitybccf2152007-02-21 18:04:26 +02003048 return 0;
3049}
3050
Christian Borntraeger3d3aab12008-12-02 11:17:32 +01003051static struct file_operations kvm_vcpu_fops = {
Avi Kivitybccf2152007-02-21 18:04:26 +02003052 .release = kvm_vcpu_release,
3053 .unlocked_ioctl = kvm_vcpu_ioctl,
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02003054 .mmap = kvm_vcpu_mmap,
Arnd Bergmann6038f372010-08-15 18:52:59 +02003055 .llseek = noop_llseek,
Marc Zyngier7ddfd3e2018-06-17 10:16:21 +01003056 KVM_COMPAT(kvm_vcpu_compat_ioctl),
Avi Kivitybccf2152007-02-21 18:04:26 +02003057};
3058
3059/*
3060 * Allocates an inode for the vcpu.
3061 */
3062static int create_vcpu_fd(struct kvm_vcpu *vcpu)
3063{
Masatake YAMATOe46b4692018-01-20 04:04:22 +09003064 char name[8 + 1 + ITOA_MAX_LEN + 1];
3065
3066 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
3067 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
Avi Kivitybccf2152007-02-21 18:04:26 +02003068}
3069
Greg KH3e7093d2019-07-31 20:56:20 +02003070static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
Luiz Capitulino45b59392016-09-16 10:27:35 -04003071{
Paolo Bonzini741cbba2019-08-03 08:14:25 +02003072#ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
Paolo Bonzinid56f5132020-06-04 15:16:52 +02003073 struct dentry *debugfs_dentry;
Luiz Capitulino45b59392016-09-16 10:27:35 -04003074 char dir_name[ITOA_MAX_LEN * 2];
Luiz Capitulino45b59392016-09-16 10:27:35 -04003075
Luiz Capitulino45b59392016-09-16 10:27:35 -04003076 if (!debugfs_initialized())
Greg KH3e7093d2019-07-31 20:56:20 +02003077 return;
Luiz Capitulino45b59392016-09-16 10:27:35 -04003078
3079 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
Paolo Bonzinid56f5132020-06-04 15:16:52 +02003080 debugfs_dentry = debugfs_create_dir(dir_name,
3081 vcpu->kvm->debugfs_dentry);
Luiz Capitulino45b59392016-09-16 10:27:35 -04003082
Paolo Bonzinid56f5132020-06-04 15:16:52 +02003083 kvm_arch_create_vcpu_debugfs(vcpu, debugfs_dentry);
Paolo Bonzini741cbba2019-08-03 08:14:25 +02003084#endif
Luiz Capitulino45b59392016-09-16 10:27:35 -04003085}
3086
Avi Kivityc5ea7662007-02-20 18:41:05 +02003087/*
3088 * Creates some virtual cpus. Good luck creating more than one.
3089 */
Gleb Natapov73880c82009-06-09 15:56:28 +03003090static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
Avi Kivityc5ea7662007-02-20 18:41:05 +02003091{
3092 int r;
David Hildenbrande09fefd2015-11-05 09:03:50 +01003093 struct kvm_vcpu *vcpu;
Sean Christopherson8bd826d2019-12-18 13:55:30 -08003094 struct page *page;
Avi Kivityc5ea7662007-02-20 18:41:05 +02003095
Greg Kurz0b1b1df2016-05-09 18:13:37 +02003096 if (id >= KVM_MAX_VCPU_ID)
Andy Honig338c7db2013-11-18 16:09:22 -08003097 return -EINVAL;
3098
Paolo Bonzini6c7caeb2016-06-13 14:48:25 +02003099 mutex_lock(&kvm->lock);
3100 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
3101 mutex_unlock(&kvm->lock);
3102 return -EINVAL;
3103 }
3104
3105 kvm->created_vcpus++;
3106 mutex_unlock(&kvm->lock);
3107
Sean Christopherson897cc382019-12-18 13:55:09 -08003108 r = kvm_arch_vcpu_precreate(kvm, id);
3109 if (r)
3110 goto vcpu_decrement;
3111
Sean Christophersone529ef62019-12-18 13:55:15 -08003112 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
3113 if (!vcpu) {
3114 r = -ENOMEM;
Paolo Bonzini6c7caeb2016-06-13 14:48:25 +02003115 goto vcpu_decrement;
3116 }
Avi Kivityc5ea7662007-02-20 18:41:05 +02003117
Peter Xufcd97ad2020-01-09 09:57:12 -05003118 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
Sean Christopherson8bd826d2019-12-18 13:55:30 -08003119 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
3120 if (!page) {
3121 r = -ENOMEM;
Sean Christophersone529ef62019-12-18 13:55:15 -08003122 goto vcpu_free;
Sean Christopherson8bd826d2019-12-18 13:55:30 -08003123 }
3124 vcpu->run = page_address(page);
3125
3126 kvm_vcpu_init(vcpu, kvm, id);
Sean Christophersone529ef62019-12-18 13:55:15 -08003127
3128 r = kvm_arch_vcpu_create(vcpu);
3129 if (r)
Sean Christopherson8bd826d2019-12-18 13:55:30 -08003130 goto vcpu_free_run_page;
Sean Christophersone529ef62019-12-18 13:55:15 -08003131
Shaohua Li11ec2802007-07-23 14:51:37 +08003132 mutex_lock(&kvm->lock);
David Hildenbrande09fefd2015-11-05 09:03:50 +01003133 if (kvm_get_vcpu_by_id(kvm, id)) {
3134 r = -EEXIST;
3135 goto unlock_vcpu_destroy;
3136 }
Gleb Natapov73880c82009-06-09 15:56:28 +03003137
Radim Krčmář8750e722019-11-07 07:53:42 -05003138 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
3139 BUG_ON(kvm->vcpus[vcpu->vcpu_idx]);
Rusty Russellfb3f0f52007-07-27 17:16:56 +10003140
3141 /* Now it's all set up, let userspace reach it */
Al Viro66c0b392008-04-19 20:33:56 +01003142 kvm_get_kvm(kvm);
Avi Kivitybccf2152007-02-21 18:04:26 +02003143 r = create_vcpu_fd(vcpu);
Gleb Natapov73880c82009-06-09 15:56:28 +03003144 if (r < 0) {
Sean Christopherson149487b2019-10-21 15:58:42 -07003145 kvm_put_kvm_no_destroy(kvm);
Jan Kiszkad7805922011-05-23 10:33:05 +02003146 goto unlock_vcpu_destroy;
Gleb Natapov73880c82009-06-09 15:56:28 +03003147 }
3148
Radim Krčmář8750e722019-11-07 07:53:42 -05003149 kvm->vcpus[vcpu->vcpu_idx] = vcpu;
Paolo Bonzinidd489242015-07-29 11:32:20 +02003150
3151 /*
3152 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
3153 * before kvm->online_vcpu's incremented value.
3154 */
Gleb Natapov73880c82009-06-09 15:56:28 +03003155 smp_wmb();
3156 atomic_inc(&kvm->online_vcpus);
3157
Gleb Natapov73880c82009-06-09 15:56:28 +03003158 mutex_unlock(&kvm->lock);
Marcelo Tosatti42897d82012-11-27 23:29:02 -02003159 kvm_arch_vcpu_postcreate(vcpu);
Paolo Bonzini63d04342020-04-01 00:42:22 +02003160 kvm_create_vcpu_debugfs(vcpu);
Avi Kivitybccf2152007-02-21 18:04:26 +02003161 return r;
Avi Kivityc5ea7662007-02-20 18:41:05 +02003162
Jan Kiszkad7805922011-05-23 10:33:05 +02003163unlock_vcpu_destroy:
Glauber Costa7d8fece2008-09-17 23:16:59 -03003164 mutex_unlock(&kvm->lock);
Hollis Blanchardd40ccc62007-11-19 14:04:43 -06003165 kvm_arch_vcpu_destroy(vcpu);
Sean Christopherson8bd826d2019-12-18 13:55:30 -08003166vcpu_free_run_page:
3167 free_page((unsigned long)vcpu->run);
Sean Christophersone529ef62019-12-18 13:55:15 -08003168vcpu_free:
3169 kmem_cache_free(kvm_vcpu_cache, vcpu);
Paolo Bonzini6c7caeb2016-06-13 14:48:25 +02003170vcpu_decrement:
3171 mutex_lock(&kvm->lock);
3172 kvm->created_vcpus--;
3173 mutex_unlock(&kvm->lock);
Avi Kivityc5ea7662007-02-20 18:41:05 +02003174 return r;
3175}
3176
Avi Kivity1961d272007-03-05 19:46:05 +02003177static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3178{
3179 if (sigset) {
3180 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3181 vcpu->sigset_active = 1;
3182 vcpu->sigset = *sigset;
3183 } else
3184 vcpu->sigset_active = 0;
3185 return 0;
3186}
3187
Avi Kivitybccf2152007-02-21 18:04:26 +02003188static long kvm_vcpu_ioctl(struct file *filp,
3189 unsigned int ioctl, unsigned long arg)
Avi Kivity6aa8b732006-12-10 02:21:36 -08003190{
Avi Kivitybccf2152007-02-21 18:04:26 +02003191 struct kvm_vcpu *vcpu = filp->private_data;
Al Viro2f3669872007-02-09 16:38:35 +00003192 void __user *argp = (void __user *)arg;
Carsten Otte313a3dc2007-10-11 19:16:52 +02003193 int r;
Dave Hansenfa3795a2008-08-11 10:01:46 -07003194 struct kvm_fpu *fpu = NULL;
3195 struct kvm_sregs *kvm_sregs = NULL;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003196
Avi Kivity6d4e4c42007-11-21 16:41:05 +02003197 if (vcpu->kvm->mm != current->mm)
3198 return -EIO;
Avi Kivity2122ff52010-05-13 11:25:04 +03003199
David Matlack2ea75be2014-09-19 16:03:25 -07003200 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
3201 return -EINVAL;
3202
Avi Kivity2122ff52010-05-13 11:25:04 +03003203 /*
Paolo Bonzini5cb09442017-12-12 17:41:34 +01003204 * Some architectures have vcpu ioctls that are asynchronous to vcpu
3205 * execution; mutex_lock() would break them.
Avi Kivity2122ff52010-05-13 11:25:04 +03003206 */
Paolo Bonzini5cb09442017-12-12 17:41:34 +01003207 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
3208 if (r != -ENOIOCTLCMD)
Michael S. Tsirkin9fc77442012-09-16 11:50:30 +03003209 return r;
Avi Kivity2122ff52010-05-13 11:25:04 +03003210
Christoffer Dallec7660c2017-12-04 21:35:23 +01003211 if (mutex_lock_killable(&vcpu->mutex))
3212 return -EINTR;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003213 switch (ioctl) {
Christian Borntraeger0e4524a2017-07-06 14:44:28 +02003214 case KVM_RUN: {
3215 struct pid *oldpid;
Avi Kivityf0fe5102007-03-07 13:11:17 +02003216 r = -EINVAL;
3217 if (arg)
3218 goto out;
Christian Borntraeger0e4524a2017-07-06 14:44:28 +02003219 oldpid = rcu_access_pointer(vcpu->pid);
Eric W. Biederman71dbc8a2017-07-16 21:39:32 -05003220 if (unlikely(oldpid != task_pid(current))) {
Christian Borntraeger7a72f7a2014-08-05 16:44:14 +02003221 /* The thread running this VCPU changed. */
Christoffer Dallbd2a6392018-02-23 17:23:57 +01003222 struct pid *newpid;
Xiubo Lif95ef0cd2015-02-26 14:58:23 +08003223
Christoffer Dallbd2a6392018-02-23 17:23:57 +01003224 r = kvm_arch_vcpu_run_pid_change(vcpu);
3225 if (r)
3226 break;
3227
3228 newpid = get_task_pid(current, PIDTYPE_PID);
Christian Borntraeger7a72f7a2014-08-05 16:44:14 +02003229 rcu_assign_pointer(vcpu->pid, newpid);
3230 if (oldpid)
3231 synchronize_rcu();
3232 put_pid(oldpid);
3233 }
Tianjia Zhang1b94f6f2020-04-16 13:10:57 +08003234 r = kvm_arch_vcpu_ioctl_run(vcpu);
Gleb Natapov64be5002010-10-24 16:49:08 +02003235 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003236 break;
Christian Borntraeger0e4524a2017-07-06 14:44:28 +02003237 }
Avi Kivity6aa8b732006-12-10 02:21:36 -08003238 case KVM_GET_REGS: {
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003239 struct kvm_regs *kvm_regs;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003240
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003241 r = -ENOMEM;
Ben Gardonb12ce362019-02-11 11:02:49 -08003242 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003243 if (!kvm_regs)
3244 goto out;
3245 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003246 if (r)
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003247 goto out_free1;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003248 r = -EFAULT;
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003249 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
3250 goto out_free1;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003251 r = 0;
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003252out_free1:
3253 kfree(kvm_regs);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003254 break;
3255 }
3256 case KVM_SET_REGS: {
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003257 struct kvm_regs *kvm_regs;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003258
Sasha Levinff5c2c02011-12-04 19:36:29 +02003259 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
3260 if (IS_ERR(kvm_regs)) {
3261 r = PTR_ERR(kvm_regs);
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003262 goto out;
Sasha Levinff5c2c02011-12-04 19:36:29 +02003263 }
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003264 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003265 kfree(kvm_regs);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003266 break;
3267 }
3268 case KVM_GET_SREGS: {
Ben Gardonb12ce362019-02-11 11:02:49 -08003269 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
3270 GFP_KERNEL_ACCOUNT);
Dave Hansenfa3795a2008-08-11 10:01:46 -07003271 r = -ENOMEM;
3272 if (!kvm_sregs)
3273 goto out;
3274 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003275 if (r)
3276 goto out;
3277 r = -EFAULT;
Dave Hansenfa3795a2008-08-11 10:01:46 -07003278 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
Avi Kivity6aa8b732006-12-10 02:21:36 -08003279 goto out;
3280 r = 0;
3281 break;
3282 }
3283 case KVM_SET_SREGS: {
Sasha Levinff5c2c02011-12-04 19:36:29 +02003284 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
3285 if (IS_ERR(kvm_sregs)) {
3286 r = PTR_ERR(kvm_sregs);
Guo Chao18595412012-11-02 18:33:21 +08003287 kvm_sregs = NULL;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003288 goto out;
Sasha Levinff5c2c02011-12-04 19:36:29 +02003289 }
Dave Hansenfa3795a2008-08-11 10:01:46 -07003290 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003291 break;
3292 }
Marcelo Tosatti62d9f0d2008-04-11 13:24:45 -03003293 case KVM_GET_MP_STATE: {
3294 struct kvm_mp_state mp_state;
3295
3296 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
3297 if (r)
3298 goto out;
3299 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003300 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
Marcelo Tosatti62d9f0d2008-04-11 13:24:45 -03003301 goto out;
3302 r = 0;
3303 break;
3304 }
3305 case KVM_SET_MP_STATE: {
3306 struct kvm_mp_state mp_state;
3307
3308 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003309 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
Marcelo Tosatti62d9f0d2008-04-11 13:24:45 -03003310 goto out;
3311 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
Marcelo Tosatti62d9f0d2008-04-11 13:24:45 -03003312 break;
3313 }
Avi Kivity6aa8b732006-12-10 02:21:36 -08003314 case KVM_TRANSLATE: {
3315 struct kvm_translation tr;
3316
3317 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003318 if (copy_from_user(&tr, argp, sizeof(tr)))
Avi Kivity6aa8b732006-12-10 02:21:36 -08003319 goto out;
Zhang Xiantao8b006792007-11-16 13:05:55 +08003320 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003321 if (r)
3322 goto out;
3323 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003324 if (copy_to_user(argp, &tr, sizeof(tr)))
Avi Kivity6aa8b732006-12-10 02:21:36 -08003325 goto out;
3326 r = 0;
3327 break;
3328 }
Jan Kiszkad0bfb942008-12-15 13:52:10 +01003329 case KVM_SET_GUEST_DEBUG: {
3330 struct kvm_guest_debug dbg;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003331
3332 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003333 if (copy_from_user(&dbg, argp, sizeof(dbg)))
Avi Kivity6aa8b732006-12-10 02:21:36 -08003334 goto out;
Jan Kiszkad0bfb942008-12-15 13:52:10 +01003335 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003336 break;
3337 }
Avi Kivity1961d272007-03-05 19:46:05 +02003338 case KVM_SET_SIGNAL_MASK: {
3339 struct kvm_signal_mask __user *sigmask_arg = argp;
3340 struct kvm_signal_mask kvm_sigmask;
3341 sigset_t sigset, *p;
3342
3343 p = NULL;
3344 if (argp) {
3345 r = -EFAULT;
3346 if (copy_from_user(&kvm_sigmask, argp,
Xiubo Li893bdbf2015-02-26 14:58:19 +08003347 sizeof(kvm_sigmask)))
Avi Kivity1961d272007-03-05 19:46:05 +02003348 goto out;
3349 r = -EINVAL;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003350 if (kvm_sigmask.len != sizeof(sigset))
Avi Kivity1961d272007-03-05 19:46:05 +02003351 goto out;
3352 r = -EFAULT;
3353 if (copy_from_user(&sigset, sigmask_arg->sigset,
Xiubo Li893bdbf2015-02-26 14:58:19 +08003354 sizeof(sigset)))
Avi Kivity1961d272007-03-05 19:46:05 +02003355 goto out;
3356 p = &sigset;
3357 }
Andi Kleen376d41f2010-06-10 13:10:47 +02003358 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
Avi Kivity1961d272007-03-05 19:46:05 +02003359 break;
3360 }
Avi Kivityb8836732007-04-01 16:34:31 +03003361 case KVM_GET_FPU: {
Ben Gardonb12ce362019-02-11 11:02:49 -08003362 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
Dave Hansenfa3795a2008-08-11 10:01:46 -07003363 r = -ENOMEM;
3364 if (!fpu)
3365 goto out;
3366 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
Avi Kivityb8836732007-04-01 16:34:31 +03003367 if (r)
3368 goto out;
3369 r = -EFAULT;
Dave Hansenfa3795a2008-08-11 10:01:46 -07003370 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
Avi Kivityb8836732007-04-01 16:34:31 +03003371 goto out;
3372 r = 0;
3373 break;
3374 }
3375 case KVM_SET_FPU: {
Sasha Levinff5c2c02011-12-04 19:36:29 +02003376 fpu = memdup_user(argp, sizeof(*fpu));
3377 if (IS_ERR(fpu)) {
3378 r = PTR_ERR(fpu);
Guo Chao18595412012-11-02 18:33:21 +08003379 fpu = NULL;
Avi Kivityb8836732007-04-01 16:34:31 +03003380 goto out;
Sasha Levinff5c2c02011-12-04 19:36:29 +02003381 }
Dave Hansenfa3795a2008-08-11 10:01:46 -07003382 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
Avi Kivityb8836732007-04-01 16:34:31 +03003383 break;
3384 }
Avi Kivitybccf2152007-02-21 18:04:26 +02003385 default:
Carsten Otte313a3dc2007-10-11 19:16:52 +02003386 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
Avi Kivitybccf2152007-02-21 18:04:26 +02003387 }
3388out:
Christoffer Dallec7660c2017-12-04 21:35:23 +01003389 mutex_unlock(&vcpu->mutex);
Dave Hansenfa3795a2008-08-11 10:01:46 -07003390 kfree(fpu);
3391 kfree(kvm_sregs);
Avi Kivitybccf2152007-02-21 18:04:26 +02003392 return r;
3393}
3394
Christian Borntraegerde8e5d72015-02-03 09:35:15 +01003395#ifdef CONFIG_KVM_COMPAT
Alexander Graf1dda6062011-06-08 02:45:37 +02003396static long kvm_vcpu_compat_ioctl(struct file *filp,
3397 unsigned int ioctl, unsigned long arg)
3398{
3399 struct kvm_vcpu *vcpu = filp->private_data;
3400 void __user *argp = compat_ptr(arg);
3401 int r;
3402
3403 if (vcpu->kvm->mm != current->mm)
3404 return -EIO;
3405
3406 switch (ioctl) {
3407 case KVM_SET_SIGNAL_MASK: {
3408 struct kvm_signal_mask __user *sigmask_arg = argp;
3409 struct kvm_signal_mask kvm_sigmask;
Alexander Graf1dda6062011-06-08 02:45:37 +02003410 sigset_t sigset;
3411
3412 if (argp) {
3413 r = -EFAULT;
3414 if (copy_from_user(&kvm_sigmask, argp,
Xiubo Li893bdbf2015-02-26 14:58:19 +08003415 sizeof(kvm_sigmask)))
Alexander Graf1dda6062011-06-08 02:45:37 +02003416 goto out;
3417 r = -EINVAL;
Al Viro3968cf62017-09-03 21:45:17 -04003418 if (kvm_sigmask.len != sizeof(compat_sigset_t))
Alexander Graf1dda6062011-06-08 02:45:37 +02003419 goto out;
3420 r = -EFAULT;
Paolo Bonzini1393b4a2020-07-02 05:39:31 -04003421 if (get_compat_sigset(&sigset,
3422 (compat_sigset_t __user *)sigmask_arg->sigset))
Alexander Graf1dda6062011-06-08 02:45:37 +02003423 goto out;
Alan Cox760a9a32012-08-22 14:34:11 +01003424 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
3425 } else
3426 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
Alexander Graf1dda6062011-06-08 02:45:37 +02003427 break;
3428 }
3429 default:
3430 r = kvm_vcpu_ioctl(filp, ioctl, arg);
3431 }
3432
3433out:
3434 return r;
3435}
3436#endif
3437
Cédric Le Goatera1cd3f02019-04-18 12:39:36 +02003438static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
3439{
3440 struct kvm_device *dev = filp->private_data;
3441
3442 if (dev->ops->mmap)
3443 return dev->ops->mmap(dev, vma);
3444
3445 return -ENODEV;
3446}
3447
Scott Wood852b6d52013-04-12 14:08:42 +00003448static int kvm_device_ioctl_attr(struct kvm_device *dev,
3449 int (*accessor)(struct kvm_device *dev,
3450 struct kvm_device_attr *attr),
3451 unsigned long arg)
3452{
3453 struct kvm_device_attr attr;
3454
3455 if (!accessor)
3456 return -EPERM;
3457
3458 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
3459 return -EFAULT;
3460
3461 return accessor(dev, &attr);
3462}
3463
3464static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
3465 unsigned long arg)
3466{
3467 struct kvm_device *dev = filp->private_data;
3468
Sean Christophersonddba9182019-02-15 12:48:39 -08003469 if (dev->kvm->mm != current->mm)
3470 return -EIO;
3471
Scott Wood852b6d52013-04-12 14:08:42 +00003472 switch (ioctl) {
3473 case KVM_SET_DEVICE_ATTR:
3474 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
3475 case KVM_GET_DEVICE_ATTR:
3476 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
3477 case KVM_HAS_DEVICE_ATTR:
3478 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
3479 default:
3480 if (dev->ops->ioctl)
3481 return dev->ops->ioctl(dev, ioctl, arg);
3482
3483 return -ENOTTY;
3484 }
3485}
3486
Scott Wood852b6d52013-04-12 14:08:42 +00003487static int kvm_device_release(struct inode *inode, struct file *filp)
3488{
3489 struct kvm_device *dev = filp->private_data;
3490 struct kvm *kvm = dev->kvm;
3491
Cédric Le Goater2bde9b32019-04-18 12:39:41 +02003492 if (dev->ops->release) {
3493 mutex_lock(&kvm->lock);
3494 list_del(&dev->vm_node);
3495 dev->ops->release(dev);
3496 mutex_unlock(&kvm->lock);
3497 }
3498
Scott Wood852b6d52013-04-12 14:08:42 +00003499 kvm_put_kvm(kvm);
3500 return 0;
3501}
3502
3503static const struct file_operations kvm_device_fops = {
3504 .unlocked_ioctl = kvm_device_ioctl,
3505 .release = kvm_device_release,
Marc Zyngier7ddfd3e2018-06-17 10:16:21 +01003506 KVM_COMPAT(kvm_device_ioctl),
Cédric Le Goatera1cd3f02019-04-18 12:39:36 +02003507 .mmap = kvm_device_mmap,
Scott Wood852b6d52013-04-12 14:08:42 +00003508};
3509
3510struct kvm_device *kvm_device_from_filp(struct file *filp)
3511{
3512 if (filp->f_op != &kvm_device_fops)
3513 return NULL;
3514
3515 return filp->private_data;
3516}
3517
Steven Price8538cb22019-10-21 16:28:19 +01003518static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
Will Deacond60eacb2014-09-02 10:27:33 +01003519#ifdef CONFIG_KVM_MPIC
3520 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
3521 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
3522#endif
Will Deacond60eacb2014-09-02 10:27:33 +01003523};
3524
Steven Price8538cb22019-10-21 16:28:19 +01003525int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
Will Deacond60eacb2014-09-02 10:27:33 +01003526{
3527 if (type >= ARRAY_SIZE(kvm_device_ops_table))
3528 return -ENOSPC;
3529
3530 if (kvm_device_ops_table[type] != NULL)
3531 return -EEXIST;
3532
3533 kvm_device_ops_table[type] = ops;
3534 return 0;
3535}
3536
Wanpeng Li571ee1b2014-10-09 18:30:08 +08003537void kvm_unregister_device_ops(u32 type)
3538{
3539 if (kvm_device_ops_table[type] != NULL)
3540 kvm_device_ops_table[type] = NULL;
3541}
3542
Scott Wood852b6d52013-04-12 14:08:42 +00003543static int kvm_ioctl_create_device(struct kvm *kvm,
3544 struct kvm_create_device *cd)
3545{
Steven Price8538cb22019-10-21 16:28:19 +01003546 const struct kvm_device_ops *ops = NULL;
Scott Wood852b6d52013-04-12 14:08:42 +00003547 struct kvm_device *dev;
3548 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
Paolo Bonzini1d487e92019-04-11 11:16:47 +02003549 int type;
Scott Wood852b6d52013-04-12 14:08:42 +00003550 int ret;
3551
Will Deacond60eacb2014-09-02 10:27:33 +01003552 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
Scott Wood852b6d52013-04-12 14:08:42 +00003553 return -ENODEV;
Will Deacond60eacb2014-09-02 10:27:33 +01003554
Paolo Bonzini1d487e92019-04-11 11:16:47 +02003555 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
3556 ops = kvm_device_ops_table[type];
Will Deacond60eacb2014-09-02 10:27:33 +01003557 if (ops == NULL)
3558 return -ENODEV;
Scott Wood852b6d52013-04-12 14:08:42 +00003559
3560 if (test)
3561 return 0;
3562
Ben Gardonb12ce362019-02-11 11:02:49 -08003563 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
Scott Wood852b6d52013-04-12 14:08:42 +00003564 if (!dev)
3565 return -ENOMEM;
3566
3567 dev->ops = ops;
3568 dev->kvm = kvm;
Scott Wood852b6d52013-04-12 14:08:42 +00003569
Christoffer Dalla28ebea2016-08-09 19:13:01 +02003570 mutex_lock(&kvm->lock);
Paolo Bonzini1d487e92019-04-11 11:16:47 +02003571 ret = ops->create(dev, type);
Scott Wood852b6d52013-04-12 14:08:42 +00003572 if (ret < 0) {
Christoffer Dalla28ebea2016-08-09 19:13:01 +02003573 mutex_unlock(&kvm->lock);
Scott Wood852b6d52013-04-12 14:08:42 +00003574 kfree(dev);
3575 return ret;
3576 }
Christoffer Dalla28ebea2016-08-09 19:13:01 +02003577 list_add(&dev->vm_node, &kvm->devices);
3578 mutex_unlock(&kvm->lock);
Scott Wood852b6d52013-04-12 14:08:42 +00003579
Christoffer Dall023e9fd2016-08-09 19:13:00 +02003580 if (ops->init)
3581 ops->init(dev);
3582
Jann Horncfa39382019-01-26 01:54:33 +01003583 kvm_get_kvm(kvm);
Yann Droneaud24009b02013-08-24 22:14:07 +02003584 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
Scott Wood852b6d52013-04-12 14:08:42 +00003585 if (ret < 0) {
Sean Christopherson149487b2019-10-21 15:58:42 -07003586 kvm_put_kvm_no_destroy(kvm);
Christoffer Dalla28ebea2016-08-09 19:13:01 +02003587 mutex_lock(&kvm->lock);
3588 list_del(&dev->vm_node);
3589 mutex_unlock(&kvm->lock);
Dan Carpentera0f1d212016-11-30 22:21:05 +03003590 ops->destroy(dev);
Scott Wood852b6d52013-04-12 14:08:42 +00003591 return ret;
3592 }
3593
Scott Wood852b6d52013-04-12 14:08:42 +00003594 cd->fd = ret;
3595 return 0;
3596}
3597
Alexander Graf92b591a2014-07-14 18:33:08 +02003598static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
3599{
3600 switch (arg) {
3601 case KVM_CAP_USER_MEMORY:
3602 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
3603 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
Alexander Graf92b591a2014-07-14 18:33:08 +02003604 case KVM_CAP_INTERNAL_ERROR_DATA:
3605#ifdef CONFIG_HAVE_KVM_MSI
3606 case KVM_CAP_SIGNAL_MSI:
3607#endif
Paul Mackerras297e2102014-06-30 20:51:13 +10003608#ifdef CONFIG_HAVE_KVM_IRQFD
Paolo Bonzinidc9be0f2015-03-05 11:54:46 +01003609 case KVM_CAP_IRQFD:
Alexander Graf92b591a2014-07-14 18:33:08 +02003610 case KVM_CAP_IRQFD_RESAMPLE:
3611#endif
Jason Wange9ea5062015-09-15 14:41:59 +08003612 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
Alexander Graf92b591a2014-07-14 18:33:08 +02003613 case KVM_CAP_CHECK_EXTENSION_VM:
Paolo Bonzinie5d83c72017-02-16 10:40:56 +01003614 case KVM_CAP_ENABLE_CAP_VM:
David Matlackacd05782020-04-17 15:14:46 -07003615 case KVM_CAP_HALT_POLL:
Alexander Graf92b591a2014-07-14 18:33:08 +02003616 return 1;
Paolo Bonzini4b4357e2017-03-31 13:53:23 +02003617#ifdef CONFIG_KVM_MMIO
Paolo Bonzini30422552017-03-31 13:53:22 +02003618 case KVM_CAP_COALESCED_MMIO:
3619 return KVM_COALESCED_MMIO_PAGE_OFFSET;
Peng Hao0804c842018-10-14 07:09:55 +08003620 case KVM_CAP_COALESCED_PIO:
3621 return 1;
Paolo Bonzini30422552017-03-31 13:53:22 +02003622#endif
Jay Zhou3c9bd402020-02-27 09:32:27 +08003623#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3624 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
3625 return KVM_DIRTY_LOG_MANUAL_CAPS;
3626#endif
Alexander Graf92b591a2014-07-14 18:33:08 +02003627#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3628 case KVM_CAP_IRQ_ROUTING:
3629 return KVM_MAX_IRQ_ROUTES;
3630#endif
Paolo Bonzinif481b062015-05-17 17:30:37 +02003631#if KVM_ADDRESS_SPACE_NUM > 1
3632 case KVM_CAP_MULTI_ADDRESS_SPACE:
3633 return KVM_ADDRESS_SPACE_NUM;
3634#endif
Paolo Bonzinic110ae52019-03-28 17:24:03 +01003635 case KVM_CAP_NR_MEMSLOTS:
3636 return KVM_USER_MEM_SLOTS;
Alexander Graf92b591a2014-07-14 18:33:08 +02003637 default:
3638 break;
3639 }
3640 return kvm_vm_ioctl_check_extension(kvm, arg);
3641}
3642
Paolo Bonzinie5d83c72017-02-16 10:40:56 +01003643int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3644 struct kvm_enable_cap *cap)
3645{
3646 return -EINVAL;
3647}
3648
3649static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
3650 struct kvm_enable_cap *cap)
3651{
3652 switch (cap->cap) {
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02003653#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
Jay Zhou3c9bd402020-02-27 09:32:27 +08003654 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2: {
3655 u64 allowed_options = KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE;
3656
3657 if (cap->args[0] & KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE)
3658 allowed_options = KVM_DIRTY_LOG_MANUAL_CAPS;
3659
3660 if (cap->flags || (cap->args[0] & ~allowed_options))
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02003661 return -EINVAL;
3662 kvm->manual_dirty_log_protect = cap->args[0];
3663 return 0;
Jay Zhou3c9bd402020-02-27 09:32:27 +08003664 }
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02003665#endif
David Matlackacd05782020-04-17 15:14:46 -07003666 case KVM_CAP_HALT_POLL: {
3667 if (cap->flags || cap->args[0] != (unsigned int)cap->args[0])
3668 return -EINVAL;
3669
3670 kvm->max_halt_poll_ns = cap->args[0];
3671 return 0;
3672 }
Paolo Bonzinie5d83c72017-02-16 10:40:56 +01003673 default:
3674 return kvm_vm_ioctl_enable_cap(kvm, cap);
3675 }
3676}
3677
Avi Kivitybccf2152007-02-21 18:04:26 +02003678static long kvm_vm_ioctl(struct file *filp,
3679 unsigned int ioctl, unsigned long arg)
3680{
3681 struct kvm *kvm = filp->private_data;
3682 void __user *argp = (void __user *)arg;
Carsten Otte1fe779f2007-10-29 16:08:35 +01003683 int r;
Avi Kivitybccf2152007-02-21 18:04:26 +02003684
Avi Kivity6d4e4c42007-11-21 16:41:05 +02003685 if (kvm->mm != current->mm)
3686 return -EIO;
Avi Kivitybccf2152007-02-21 18:04:26 +02003687 switch (ioctl) {
3688 case KVM_CREATE_VCPU:
3689 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
Avi Kivitybccf2152007-02-21 18:04:26 +02003690 break;
Paolo Bonzinie5d83c72017-02-16 10:40:56 +01003691 case KVM_ENABLE_CAP: {
3692 struct kvm_enable_cap cap;
3693
3694 r = -EFAULT;
3695 if (copy_from_user(&cap, argp, sizeof(cap)))
3696 goto out;
3697 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
3698 break;
3699 }
Izik Eidus6fc138d2007-10-09 19:20:39 +02003700 case KVM_SET_USER_MEMORY_REGION: {
3701 struct kvm_userspace_memory_region kvm_userspace_mem;
3702
3703 r = -EFAULT;
3704 if (copy_from_user(&kvm_userspace_mem, argp,
Xiubo Li893bdbf2015-02-26 14:58:19 +08003705 sizeof(kvm_userspace_mem)))
Izik Eidus6fc138d2007-10-09 19:20:39 +02003706 goto out;
3707
Takuya Yoshikawa47ae31e2013-02-27 19:43:00 +09003708 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003709 break;
3710 }
3711 case KVM_GET_DIRTY_LOG: {
3712 struct kvm_dirty_log log;
3713
3714 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003715 if (copy_from_user(&log, argp, sizeof(log)))
Avi Kivity6aa8b732006-12-10 02:21:36 -08003716 goto out;
Avi Kivity2c6f5df2007-02-20 18:27:58 +02003717 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003718 break;
3719 }
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02003720#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3721 case KVM_CLEAR_DIRTY_LOG: {
3722 struct kvm_clear_dirty_log log;
3723
3724 r = -EFAULT;
3725 if (copy_from_user(&log, argp, sizeof(log)))
3726 goto out;
3727 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
3728 break;
3729 }
3730#endif
Paolo Bonzini4b4357e2017-03-31 13:53:23 +02003731#ifdef CONFIG_KVM_MMIO
Laurent Vivier5f94c172008-05-30 16:05:54 +02003732 case KVM_REGISTER_COALESCED_MMIO: {
3733 struct kvm_coalesced_mmio_zone zone;
Xiubo Lif95ef0cd2015-02-26 14:58:23 +08003734
Laurent Vivier5f94c172008-05-30 16:05:54 +02003735 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003736 if (copy_from_user(&zone, argp, sizeof(zone)))
Laurent Vivier5f94c172008-05-30 16:05:54 +02003737 goto out;
Laurent Vivier5f94c172008-05-30 16:05:54 +02003738 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
Laurent Vivier5f94c172008-05-30 16:05:54 +02003739 break;
3740 }
3741 case KVM_UNREGISTER_COALESCED_MMIO: {
3742 struct kvm_coalesced_mmio_zone zone;
Xiubo Lif95ef0cd2015-02-26 14:58:23 +08003743
Laurent Vivier5f94c172008-05-30 16:05:54 +02003744 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003745 if (copy_from_user(&zone, argp, sizeof(zone)))
Laurent Vivier5f94c172008-05-30 16:05:54 +02003746 goto out;
Laurent Vivier5f94c172008-05-30 16:05:54 +02003747 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
Laurent Vivier5f94c172008-05-30 16:05:54 +02003748 break;
3749 }
3750#endif
Gregory Haskins721eecbf2009-05-20 10:30:49 -04003751 case KVM_IRQFD: {
3752 struct kvm_irqfd data;
3753
3754 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003755 if (copy_from_user(&data, argp, sizeof(data)))
Gregory Haskins721eecbf2009-05-20 10:30:49 -04003756 goto out;
Alex Williamsond4db2932012-06-29 09:56:08 -06003757 r = kvm_irqfd(kvm, &data);
Gregory Haskins721eecbf2009-05-20 10:30:49 -04003758 break;
3759 }
Gregory Haskinsd34e6b12009-07-07 17:08:49 -04003760 case KVM_IOEVENTFD: {
3761 struct kvm_ioeventfd data;
3762
3763 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003764 if (copy_from_user(&data, argp, sizeof(data)))
Gregory Haskinsd34e6b12009-07-07 17:08:49 -04003765 goto out;
3766 r = kvm_ioeventfd(kvm, &data);
3767 break;
3768 }
Jan Kiszka07975ad2012-03-29 21:14:12 +02003769#ifdef CONFIG_HAVE_KVM_MSI
3770 case KVM_SIGNAL_MSI: {
3771 struct kvm_msi msi;
3772
3773 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003774 if (copy_from_user(&msi, argp, sizeof(msi)))
Jan Kiszka07975ad2012-03-29 21:14:12 +02003775 goto out;
3776 r = kvm_send_userspace_msi(kvm, &msi);
3777 break;
3778 }
3779#endif
Christoffer Dall23d43cf2012-07-24 08:51:20 -04003780#ifdef __KVM_HAVE_IRQ_LINE
3781 case KVM_IRQ_LINE_STATUS:
3782 case KVM_IRQ_LINE: {
3783 struct kvm_irq_level irq_event;
3784
3785 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003786 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
Christoffer Dall23d43cf2012-07-24 08:51:20 -04003787 goto out;
3788
Yang Zhangaa2fbe62013-04-11 19:21:40 +08003789 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
3790 ioctl == KVM_IRQ_LINE_STATUS);
Christoffer Dall23d43cf2012-07-24 08:51:20 -04003791 if (r)
3792 goto out;
3793
3794 r = -EFAULT;
3795 if (ioctl == KVM_IRQ_LINE_STATUS) {
Xiubo Li893bdbf2015-02-26 14:58:19 +08003796 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
Christoffer Dall23d43cf2012-07-24 08:51:20 -04003797 goto out;
3798 }
3799
3800 r = 0;
3801 break;
3802 }
3803#endif
Alexander Grafaa8d5942013-04-15 21:12:53 +02003804#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3805 case KVM_SET_GSI_ROUTING: {
3806 struct kvm_irq_routing routing;
3807 struct kvm_irq_routing __user *urouting;
Paolo Bonzinif8c1b852016-06-01 14:09:22 +02003808 struct kvm_irq_routing_entry *entries = NULL;
Alexander Grafaa8d5942013-04-15 21:12:53 +02003809
3810 r = -EFAULT;
3811 if (copy_from_user(&routing, argp, sizeof(routing)))
3812 goto out;
3813 r = -EINVAL;
David Hildenbrand5c0aea02017-04-28 17:06:20 +02003814 if (!kvm_arch_can_set_irq_routing(kvm))
3815 goto out;
Xiubo Licaf1ff22016-06-15 18:00:33 +08003816 if (routing.nr > KVM_MAX_IRQ_ROUTES)
Alexander Grafaa8d5942013-04-15 21:12:53 +02003817 goto out;
3818 if (routing.flags)
3819 goto out;
Paolo Bonzinif8c1b852016-06-01 14:09:22 +02003820 if (routing.nr) {
Paolo Bonzinif8c1b852016-06-01 14:09:22 +02003821 urouting = argp;
Denis Efremov7ec28e22020-06-03 13:11:31 +03003822 entries = vmemdup_user(urouting->entries,
3823 array_size(sizeof(*entries),
3824 routing.nr));
3825 if (IS_ERR(entries)) {
3826 r = PTR_ERR(entries);
3827 goto out;
3828 }
Paolo Bonzinif8c1b852016-06-01 14:09:22 +02003829 }
Alexander Grafaa8d5942013-04-15 21:12:53 +02003830 r = kvm_set_irq_routing(kvm, entries, routing.nr,
3831 routing.flags);
Denis Efremov7ec28e22020-06-03 13:11:31 +03003832 kvfree(entries);
Alexander Grafaa8d5942013-04-15 21:12:53 +02003833 break;
3834 }
3835#endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
Scott Wood852b6d52013-04-12 14:08:42 +00003836 case KVM_CREATE_DEVICE: {
3837 struct kvm_create_device cd;
3838
3839 r = -EFAULT;
3840 if (copy_from_user(&cd, argp, sizeof(cd)))
3841 goto out;
3842
3843 r = kvm_ioctl_create_device(kvm, &cd);
3844 if (r)
3845 goto out;
3846
3847 r = -EFAULT;
3848 if (copy_to_user(argp, &cd, sizeof(cd)))
3849 goto out;
3850
3851 r = 0;
3852 break;
3853 }
Alexander Graf92b591a2014-07-14 18:33:08 +02003854 case KVM_CHECK_EXTENSION:
3855 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
3856 break;
Avi Kivityf17abe92007-02-21 19:28:04 +02003857 default:
Carsten Otte1fe779f2007-10-29 16:08:35 +01003858 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
Avi Kivityf17abe92007-02-21 19:28:04 +02003859 }
3860out:
3861 return r;
3862}
3863
Christian Borntraegerde8e5d72015-02-03 09:35:15 +01003864#ifdef CONFIG_KVM_COMPAT
Arnd Bergmann6ff58942009-10-22 14:19:27 +02003865struct compat_kvm_dirty_log {
3866 __u32 slot;
3867 __u32 padding1;
3868 union {
3869 compat_uptr_t dirty_bitmap; /* one bit per page */
3870 __u64 padding2;
3871 };
3872};
3873
3874static long kvm_vm_compat_ioctl(struct file *filp,
3875 unsigned int ioctl, unsigned long arg)
3876{
3877 struct kvm *kvm = filp->private_data;
3878 int r;
3879
3880 if (kvm->mm != current->mm)
3881 return -EIO;
3882 switch (ioctl) {
3883 case KVM_GET_DIRTY_LOG: {
3884 struct compat_kvm_dirty_log compat_log;
3885 struct kvm_dirty_log log;
3886
Arnd Bergmann6ff58942009-10-22 14:19:27 +02003887 if (copy_from_user(&compat_log, (void __user *)arg,
3888 sizeof(compat_log)))
Markus Elfringf6a3b162017-01-22 11:30:21 +01003889 return -EFAULT;
Arnd Bergmann6ff58942009-10-22 14:19:27 +02003890 log.slot = compat_log.slot;
3891 log.padding1 = compat_log.padding1;
3892 log.padding2 = compat_log.padding2;
3893 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
3894
3895 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
Arnd Bergmann6ff58942009-10-22 14:19:27 +02003896 break;
3897 }
3898 default:
3899 r = kvm_vm_ioctl(filp, ioctl, arg);
3900 }
Arnd Bergmann6ff58942009-10-22 14:19:27 +02003901 return r;
3902}
3903#endif
3904
Christian Borntraeger3d3aab12008-12-02 11:17:32 +01003905static struct file_operations kvm_vm_fops = {
Avi Kivityf17abe92007-02-21 19:28:04 +02003906 .release = kvm_vm_release,
3907 .unlocked_ioctl = kvm_vm_ioctl,
Arnd Bergmann6038f372010-08-15 18:52:59 +02003908 .llseek = noop_llseek,
Marc Zyngier7ddfd3e2018-06-17 10:16:21 +01003909 KVM_COMPAT(kvm_vm_compat_ioctl),
Avi Kivityf17abe92007-02-21 19:28:04 +02003910};
3911
Carsten Ottee08b9632012-01-04 10:25:20 +01003912static int kvm_dev_ioctl_create_vm(unsigned long type)
Avi Kivityf17abe92007-02-21 19:28:04 +02003913{
Heiko Carstensaac87632010-10-27 17:22:10 +02003914 int r;
Avi Kivityf17abe92007-02-21 19:28:04 +02003915 struct kvm *kvm;
Al Viro506cfba2016-07-14 18:54:17 +02003916 struct file *file;
Avi Kivityf17abe92007-02-21 19:28:04 +02003917
Carsten Ottee08b9632012-01-04 10:25:20 +01003918 kvm = kvm_create_vm(type);
Avi Kivityd6d28162007-06-28 08:38:16 -04003919 if (IS_ERR(kvm))
3920 return PTR_ERR(kvm);
Paolo Bonzini4b4357e2017-03-31 13:53:23 +02003921#ifdef CONFIG_KVM_MMIO
Takuya Yoshikawa6ce5a092010-03-15 22:13:30 +09003922 r = kvm_coalesced_mmio_init(kvm);
Markus Elfring78588332017-11-21 13:40:17 +01003923 if (r < 0)
3924 goto put_kvm;
Takuya Yoshikawa6ce5a092010-03-15 22:13:30 +09003925#endif
Al Viro506cfba2016-07-14 18:54:17 +02003926 r = get_unused_fd_flags(O_CLOEXEC);
Markus Elfring78588332017-11-21 13:40:17 +01003927 if (r < 0)
3928 goto put_kvm;
3929
Al Viro506cfba2016-07-14 18:54:17 +02003930 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
3931 if (IS_ERR(file)) {
3932 put_unused_fd(r);
Markus Elfring78588332017-11-21 13:40:17 +01003933 r = PTR_ERR(file);
3934 goto put_kvm;
Al Viro506cfba2016-07-14 18:54:17 +02003935 }
Janosch Frank536a6f82016-05-18 13:26:23 +02003936
Paolo Bonzini525df862017-06-27 15:45:09 +02003937 /*
3938 * Don't call kvm_put_kvm anymore at this point; file->f_op is
3939 * already set, with ->release() being kvm_vm_release(). In error
3940 * cases it will be called by the final fput(file) and will take
3941 * care of doing kvm_put_kvm(kvm).
3942 */
Janosch Frank536a6f82016-05-18 13:26:23 +02003943 if (kvm_create_vm_debugfs(kvm, r) < 0) {
Al Viro506cfba2016-07-14 18:54:17 +02003944 put_unused_fd(r);
3945 fput(file);
Janosch Frank536a6f82016-05-18 13:26:23 +02003946 return -ENOMEM;
3947 }
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02003948 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
Avi Kivityf17abe92007-02-21 19:28:04 +02003949
Al Viro506cfba2016-07-14 18:54:17 +02003950 fd_install(r, file);
Heiko Carstensaac87632010-10-27 17:22:10 +02003951 return r;
Markus Elfring78588332017-11-21 13:40:17 +01003952
3953put_kvm:
3954 kvm_put_kvm(kvm);
3955 return r;
Avi Kivityf17abe92007-02-21 19:28:04 +02003956}
3957
3958static long kvm_dev_ioctl(struct file *filp,
3959 unsigned int ioctl, unsigned long arg)
3960{
Avi Kivity07c45a32007-03-07 13:05:38 +02003961 long r = -EINVAL;
Avi Kivityf17abe92007-02-21 19:28:04 +02003962
3963 switch (ioctl) {
3964 case KVM_GET_API_VERSION:
Avi Kivityf0fe5102007-03-07 13:11:17 +02003965 if (arg)
3966 goto out;
Avi Kivityf17abe92007-02-21 19:28:04 +02003967 r = KVM_API_VERSION;
3968 break;
3969 case KVM_CREATE_VM:
Carsten Ottee08b9632012-01-04 10:25:20 +01003970 r = kvm_dev_ioctl_create_vm(arg);
Avi Kivityf17abe92007-02-21 19:28:04 +02003971 break;
Zhang Xiantao018d00d2007-11-15 23:07:47 +08003972 case KVM_CHECK_EXTENSION:
Alexander Graf784aa3d2014-07-14 18:27:35 +02003973 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
Avi Kivity5d308f42007-03-01 17:56:20 +02003974 break;
Avi Kivity07c45a32007-03-07 13:05:38 +02003975 case KVM_GET_VCPU_MMAP_SIZE:
Avi Kivity07c45a32007-03-07 13:05:38 +02003976 if (arg)
3977 goto out;
Avi Kivityadb1ff42008-01-24 15:13:08 +02003978 r = PAGE_SIZE; /* struct kvm_run */
3979#ifdef CONFIG_X86
3980 r += PAGE_SIZE; /* pio data page */
3981#endif
Paolo Bonzini4b4357e2017-03-31 13:53:23 +02003982#ifdef CONFIG_KVM_MMIO
Laurent Vivier5f94c172008-05-30 16:05:54 +02003983 r += PAGE_SIZE; /* coalesced mmio ring page */
3984#endif
Avi Kivity07c45a32007-03-07 13:05:38 +02003985 break;
Feng(Eric) Liud4c9ff22008-04-10 08:47:53 -04003986 case KVM_TRACE_ENABLE:
3987 case KVM_TRACE_PAUSE:
3988 case KVM_TRACE_DISABLE:
Marcelo Tosatti2023a292009-06-18 11:47:28 -03003989 r = -EOPNOTSUPP;
Feng(Eric) Liud4c9ff22008-04-10 08:47:53 -04003990 break;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003991 default:
Carsten Otte043405e2007-10-10 17:16:19 +02003992 return kvm_arch_dev_ioctl(filp, ioctl, arg);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003993 }
3994out:
3995 return r;
3996}
3997
Avi Kivity6aa8b732006-12-10 02:21:36 -08003998static struct file_operations kvm_chardev_ops = {
Avi Kivity6aa8b732006-12-10 02:21:36 -08003999 .unlocked_ioctl = kvm_dev_ioctl,
Arnd Bergmann6038f372010-08-15 18:52:59 +02004000 .llseek = noop_llseek,
Marc Zyngier7ddfd3e2018-06-17 10:16:21 +01004001 KVM_COMPAT(kvm_dev_ioctl),
Avi Kivity6aa8b732006-12-10 02:21:36 -08004002};
4003
4004static struct miscdevice kvm_dev = {
Avi Kivitybbe44322007-03-04 13:27:36 +02004005 KVM_MINOR,
Avi Kivity6aa8b732006-12-10 02:21:36 -08004006 "kvm",
4007 &kvm_chardev_ops,
4008};
4009
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004010static void hardware_enable_nolock(void *junk)
Avi Kivity1b6c0162007-05-24 13:03:52 +03004011{
4012 int cpu = raw_smp_processor_id();
Alexander Graf10474ae2009-09-15 11:37:46 +02004013 int r;
Avi Kivity1b6c0162007-05-24 13:03:52 +03004014
Rusty Russell7f59f492008-12-07 21:25:45 +10304015 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
Avi Kivity1b6c0162007-05-24 13:03:52 +03004016 return;
Alexander Graf10474ae2009-09-15 11:37:46 +02004017
Rusty Russell7f59f492008-12-07 21:25:45 +10304018 cpumask_set_cpu(cpu, cpus_hardware_enabled);
Alexander Graf10474ae2009-09-15 11:37:46 +02004019
Radim Krčmář13a34e02014-08-28 15:13:03 +02004020 r = kvm_arch_hardware_enable();
Alexander Graf10474ae2009-09-15 11:37:46 +02004021
4022 if (r) {
4023 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
4024 atomic_inc(&hardware_enable_failed);
Xiubo Li1170adc2015-02-26 14:58:26 +08004025 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
Alexander Graf10474ae2009-09-15 11:37:46 +02004026 }
Avi Kivity1b6c0162007-05-24 13:03:52 +03004027}
4028
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00004029static int kvm_starting_cpu(unsigned int cpu)
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004030{
Paolo Bonzini4a937f92013-09-10 12:58:35 +02004031 raw_spin_lock(&kvm_count_lock);
Paolo Bonzini4fa92fb2013-09-10 12:57:17 +02004032 if (kvm_usage_count)
4033 hardware_enable_nolock(NULL);
Paolo Bonzini4a937f92013-09-10 12:58:35 +02004034 raw_spin_unlock(&kvm_count_lock);
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00004035 return 0;
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004036}
4037
4038static void hardware_disable_nolock(void *junk)
Avi Kivity1b6c0162007-05-24 13:03:52 +03004039{
4040 int cpu = raw_smp_processor_id();
4041
Rusty Russell7f59f492008-12-07 21:25:45 +10304042 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
Avi Kivity1b6c0162007-05-24 13:03:52 +03004043 return;
Rusty Russell7f59f492008-12-07 21:25:45 +10304044 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
Radim Krčmář13a34e02014-08-28 15:13:03 +02004045 kvm_arch_hardware_disable();
Avi Kivity1b6c0162007-05-24 13:03:52 +03004046}
4047
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00004048static int kvm_dying_cpu(unsigned int cpu)
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004049{
Paolo Bonzini4a937f92013-09-10 12:58:35 +02004050 raw_spin_lock(&kvm_count_lock);
Paolo Bonzini4fa92fb2013-09-10 12:57:17 +02004051 if (kvm_usage_count)
4052 hardware_disable_nolock(NULL);
Paolo Bonzini4a937f92013-09-10 12:58:35 +02004053 raw_spin_unlock(&kvm_count_lock);
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00004054 return 0;
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004055}
4056
Alexander Graf10474ae2009-09-15 11:37:46 +02004057static void hardware_disable_all_nolock(void)
4058{
4059 BUG_ON(!kvm_usage_count);
4060
4061 kvm_usage_count--;
4062 if (!kvm_usage_count)
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004063 on_each_cpu(hardware_disable_nolock, NULL, 1);
Alexander Graf10474ae2009-09-15 11:37:46 +02004064}
4065
4066static void hardware_disable_all(void)
4067{
Paolo Bonzini4a937f92013-09-10 12:58:35 +02004068 raw_spin_lock(&kvm_count_lock);
Alexander Graf10474ae2009-09-15 11:37:46 +02004069 hardware_disable_all_nolock();
Paolo Bonzini4a937f92013-09-10 12:58:35 +02004070 raw_spin_unlock(&kvm_count_lock);
Alexander Graf10474ae2009-09-15 11:37:46 +02004071}
4072
4073static int hardware_enable_all(void)
4074{
4075 int r = 0;
4076
Paolo Bonzini4a937f92013-09-10 12:58:35 +02004077 raw_spin_lock(&kvm_count_lock);
Alexander Graf10474ae2009-09-15 11:37:46 +02004078
4079 kvm_usage_count++;
4080 if (kvm_usage_count == 1) {
4081 atomic_set(&hardware_enable_failed, 0);
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004082 on_each_cpu(hardware_enable_nolock, NULL, 1);
Alexander Graf10474ae2009-09-15 11:37:46 +02004083
4084 if (atomic_read(&hardware_enable_failed)) {
4085 hardware_disable_all_nolock();
4086 r = -EBUSY;
4087 }
4088 }
4089
Paolo Bonzini4a937f92013-09-10 12:58:35 +02004090 raw_spin_unlock(&kvm_count_lock);
Alexander Graf10474ae2009-09-15 11:37:46 +02004091
4092 return r;
4093}
4094
Rusty Russell9a2b85c2007-07-17 23:17:55 +10004095static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
Mike Dayd77c26f2007-10-08 09:02:08 -04004096 void *v)
Rusty Russell9a2b85c2007-07-17 23:17:55 +10004097{
Sheng Yang8e1c1812009-04-29 11:09:04 +08004098 /*
4099 * Some (well, at least mine) BIOSes hang on reboot if
4100 * in vmx root mode.
4101 *
4102 * And Intel TXT required VMX off for all cpu when system shutdown.
4103 */
Xiubo Li1170adc2015-02-26 14:58:26 +08004104 pr_info("kvm: exiting hardware virtualization\n");
Sheng Yang8e1c1812009-04-29 11:09:04 +08004105 kvm_rebooting = true;
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004106 on_each_cpu(hardware_disable_nolock, NULL, 1);
Rusty Russell9a2b85c2007-07-17 23:17:55 +10004107 return NOTIFY_OK;
4108}
4109
4110static struct notifier_block kvm_reboot_notifier = {
4111 .notifier_call = kvm_reboot,
4112 .priority = 0,
4113};
4114
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004115static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
Gregory Haskins2eeb2e92007-05-31 14:08:53 -04004116{
4117 int i;
4118
4119 for (i = 0; i < bus->dev_count; i++) {
Sasha Levin743eeb02011-07-27 16:00:48 +03004120 struct kvm_io_device *pos = bus->range[i].dev;
Gregory Haskins2eeb2e92007-05-31 14:08:53 -04004121
4122 kvm_iodevice_destructor(pos);
4123 }
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004124 kfree(bus);
Gregory Haskins2eeb2e92007-05-31 14:08:53 -04004125}
4126
Paolo Bonzinic21fbff2013-08-27 15:41:41 +02004127static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
Xiubo Li20e87b72015-02-26 14:58:25 +08004128 const struct kvm_io_range *r2)
Sasha Levin743eeb02011-07-27 16:00:48 +03004129{
Jason Wang8f4216c72015-09-15 14:41:57 +08004130 gpa_t addr1 = r1->addr;
4131 gpa_t addr2 = r2->addr;
4132
4133 if (addr1 < addr2)
Sasha Levin743eeb02011-07-27 16:00:48 +03004134 return -1;
Jason Wang8f4216c72015-09-15 14:41:57 +08004135
4136 /* If r2->len == 0, match the exact address. If r2->len != 0,
4137 * accept any overlapping write. Any order is acceptable for
4138 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
4139 * we process all of them.
4140 */
4141 if (r2->len) {
4142 addr1 += r1->len;
4143 addr2 += r2->len;
4144 }
4145
4146 if (addr1 > addr2)
Sasha Levin743eeb02011-07-27 16:00:48 +03004147 return 1;
Jason Wang8f4216c72015-09-15 14:41:57 +08004148
Sasha Levin743eeb02011-07-27 16:00:48 +03004149 return 0;
4150}
4151
Paolo Bonzinia343c9b2013-07-16 13:03:29 +02004152static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
4153{
Paolo Bonzinic21fbff2013-08-27 15:41:41 +02004154 return kvm_io_bus_cmp(p1, p2);
Paolo Bonzinia343c9b2013-07-16 13:03:29 +02004155}
4156
Geoff Levand39369f72013-04-05 19:20:30 +00004157static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
Sasha Levin743eeb02011-07-27 16:00:48 +03004158 gpa_t addr, int len)
4159{
4160 struct kvm_io_range *range, key;
4161 int off;
4162
4163 key = (struct kvm_io_range) {
4164 .addr = addr,
4165 .len = len,
4166 };
4167
4168 range = bsearch(&key, bus->range, bus->dev_count,
4169 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
4170 if (range == NULL)
4171 return -ENOENT;
4172
4173 off = range - bus->range;
4174
Paolo Bonzinic21fbff2013-08-27 15:41:41 +02004175 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
Sasha Levin743eeb02011-07-27 16:00:48 +03004176 off--;
4177
4178 return off;
4179}
4180
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004181static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
Cornelia Huck126a5af2013-07-03 16:30:53 +02004182 struct kvm_io_range *range, const void *val)
4183{
4184 int idx;
4185
4186 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4187 if (idx < 0)
4188 return -EOPNOTSUPP;
4189
4190 while (idx < bus->dev_count &&
Paolo Bonzinic21fbff2013-08-27 15:41:41 +02004191 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004192 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
Cornelia Huck126a5af2013-07-03 16:30:53 +02004193 range->len, val))
4194 return idx;
4195 idx++;
4196 }
4197
4198 return -EOPNOTSUPP;
4199}
4200
Michael S. Tsirkinbda90202009-06-29 22:24:32 +03004201/* kvm_io_bus_write - called under kvm->slots_lock */
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004202int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
Michael S. Tsirkinbda90202009-06-29 22:24:32 +03004203 int len, const void *val)
Gregory Haskins2eeb2e92007-05-31 14:08:53 -04004204{
Cornelia Huck126a5af2013-07-03 16:30:53 +02004205 struct kvm_io_bus *bus;
4206 struct kvm_io_range range;
4207 int r;
4208
4209 range = (struct kvm_io_range) {
4210 .addr = addr,
4211 .len = len,
4212 };
4213
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004214 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
David Hildenbrand90db1042017-03-23 18:24:19 +01004215 if (!bus)
4216 return -ENOMEM;
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004217 r = __kvm_io_bus_write(vcpu, bus, &range, val);
Cornelia Huck126a5af2013-07-03 16:30:53 +02004218 return r < 0 ? r : 0;
4219}
Leo Yana2420102019-02-22 16:10:09 +08004220EXPORT_SYMBOL_GPL(kvm_io_bus_write);
Cornelia Huck126a5af2013-07-03 16:30:53 +02004221
4222/* kvm_io_bus_write_cookie - called under kvm->slots_lock */
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004223int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
4224 gpa_t addr, int len, const void *val, long cookie)
Cornelia Huck126a5af2013-07-03 16:30:53 +02004225{
Lai Jiangshan90d83dc2010-04-19 17:41:23 +08004226 struct kvm_io_bus *bus;
Sasha Levin743eeb02011-07-27 16:00:48 +03004227 struct kvm_io_range range;
4228
4229 range = (struct kvm_io_range) {
4230 .addr = addr,
4231 .len = len,
4232 };
Lai Jiangshan90d83dc2010-04-19 17:41:23 +08004233
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004234 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
David Hildenbrand90db1042017-03-23 18:24:19 +01004235 if (!bus)
4236 return -ENOMEM;
Cornelia Huck126a5af2013-07-03 16:30:53 +02004237
4238 /* First try the device referenced by cookie. */
4239 if ((cookie >= 0) && (cookie < bus->dev_count) &&
Paolo Bonzinic21fbff2013-08-27 15:41:41 +02004240 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004241 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
Cornelia Huck126a5af2013-07-03 16:30:53 +02004242 val))
4243 return cookie;
4244
4245 /*
4246 * cookie contained garbage; fall back to search and return the
4247 * correct cookie value.
4248 */
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004249 return __kvm_io_bus_write(vcpu, bus, &range, val);
Cornelia Huck126a5af2013-07-03 16:30:53 +02004250}
4251
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004252static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4253 struct kvm_io_range *range, void *val)
Cornelia Huck126a5af2013-07-03 16:30:53 +02004254{
4255 int idx;
4256
4257 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
Sasha Levin743eeb02011-07-27 16:00:48 +03004258 if (idx < 0)
4259 return -EOPNOTSUPP;
4260
4261 while (idx < bus->dev_count &&
Paolo Bonzinic21fbff2013-08-27 15:41:41 +02004262 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004263 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
Cornelia Huck126a5af2013-07-03 16:30:53 +02004264 range->len, val))
4265 return idx;
Sasha Levin743eeb02011-07-27 16:00:48 +03004266 idx++;
4267 }
4268
Michael S. Tsirkinbda90202009-06-29 22:24:32 +03004269 return -EOPNOTSUPP;
4270}
Gregory Haskins2eeb2e92007-05-31 14:08:53 -04004271
Michael S. Tsirkinbda90202009-06-29 22:24:32 +03004272/* kvm_io_bus_read - called under kvm->slots_lock */
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004273int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004274 int len, void *val)
Michael S. Tsirkinbda90202009-06-29 22:24:32 +03004275{
Cornelia Huck126a5af2013-07-03 16:30:53 +02004276 struct kvm_io_bus *bus;
4277 struct kvm_io_range range;
4278 int r;
4279
4280 range = (struct kvm_io_range) {
4281 .addr = addr,
4282 .len = len,
4283 };
4284
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004285 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
David Hildenbrand90db1042017-03-23 18:24:19 +01004286 if (!bus)
4287 return -ENOMEM;
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004288 r = __kvm_io_bus_read(vcpu, bus, &range, val);
Cornelia Huck126a5af2013-07-03 16:30:53 +02004289 return r < 0 ? r : 0;
4290}
4291
Marcelo Tosatti79fac952009-12-23 14:35:26 -02004292/* Caller must hold slots_lock. */
Sasha Levin743eeb02011-07-27 16:00:48 +03004293int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
4294 int len, struct kvm_io_device *dev)
Michael S. Tsirkin6c474692009-06-29 22:24:26 +03004295{
Gal Hammerd4c67a72018-01-16 15:34:41 +02004296 int i;
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004297 struct kvm_io_bus *new_bus, *bus;
Gal Hammerd4c67a72018-01-16 15:34:41 +02004298 struct kvm_io_range range;
Gregory Haskins090b7af2009-07-07 17:08:44 -04004299
Christian Borntraeger4a12f952017-07-07 10:51:38 +02004300 bus = kvm_get_bus(kvm, bus_idx);
David Hildenbrand90db1042017-03-23 18:24:19 +01004301 if (!bus)
4302 return -ENOMEM;
4303
Amos Kong6ea34c92013-05-25 06:44:15 +08004304 /* exclude ioeventfd which is limited by maximum fd */
4305 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
Gregory Haskins090b7af2009-07-07 17:08:44 -04004306 return -ENOSPC;
4307
Gustavo A. R. Silva90952cd2019-01-30 17:07:47 +01004308 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
Ben Gardonb12ce362019-02-11 11:02:49 -08004309 GFP_KERNEL_ACCOUNT);
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004310 if (!new_bus)
4311 return -ENOMEM;
Gal Hammerd4c67a72018-01-16 15:34:41 +02004312
4313 range = (struct kvm_io_range) {
4314 .addr = addr,
4315 .len = len,
4316 .dev = dev,
4317 };
4318
4319 for (i = 0; i < bus->dev_count; i++)
4320 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
4321 break;
4322
4323 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
4324 new_bus->dev_count++;
4325 new_bus->range[i] = range;
4326 memcpy(new_bus->range + i + 1, bus->range + i,
4327 (bus->dev_count - i) * sizeof(struct kvm_io_range));
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004328 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4329 synchronize_srcu_expedited(&kvm->srcu);
4330 kfree(bus);
Gregory Haskins090b7af2009-07-07 17:08:44 -04004331
4332 return 0;
4333}
4334
Marcelo Tosatti79fac952009-12-23 14:35:26 -02004335/* Caller must hold slots_lock. */
David Hildenbrand90db1042017-03-23 18:24:19 +01004336void kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4337 struct kvm_io_device *dev)
Gregory Haskins090b7af2009-07-07 17:08:44 -04004338{
Rustam Kovhaevf6588662020-09-07 11:55:35 -07004339 int i, j;
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004340 struct kvm_io_bus *new_bus, *bus;
Michael S. Tsirkin6c474692009-06-29 22:24:26 +03004341
Christian Borntraeger4a12f952017-07-07 10:51:38 +02004342 bus = kvm_get_bus(kvm, bus_idx);
Peter Xudf630b82017-03-15 16:01:17 +08004343 if (!bus)
David Hildenbrand90db1042017-03-23 18:24:19 +01004344 return;
Peter Xudf630b82017-03-15 16:01:17 +08004345
Amos Konga13007162012-03-09 12:17:32 +08004346 for (i = 0; i < bus->dev_count; i++)
4347 if (bus->range[i].dev == dev) {
Gregory Haskins090b7af2009-07-07 17:08:44 -04004348 break;
4349 }
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004350
David Hildenbrand90db1042017-03-23 18:24:19 +01004351 if (i == bus->dev_count)
4352 return;
Amos Konga13007162012-03-09 12:17:32 +08004353
Gustavo A. R. Silva90952cd2019-01-30 17:07:47 +01004354 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
Ben Gardonb12ce362019-02-11 11:02:49 -08004355 GFP_KERNEL_ACCOUNT);
Rustam Kovhaevf6588662020-09-07 11:55:35 -07004356 if (new_bus) {
Rustam Kovhaev871c4332020-09-18 05:05:00 -07004357 memcpy(new_bus, bus, struct_size(bus, range, i));
Rustam Kovhaevf6588662020-09-07 11:55:35 -07004358 new_bus->dev_count--;
4359 memcpy(new_bus->range + i, bus->range + i + 1,
Rustam Kovhaev871c4332020-09-18 05:05:00 -07004360 flex_array_size(new_bus, range, new_bus->dev_count - i));
Rustam Kovhaevf6588662020-09-07 11:55:35 -07004361 } else {
David Hildenbrand90db1042017-03-23 18:24:19 +01004362 pr_err("kvm: failed to shrink bus, removing it completely\n");
Rustam Kovhaevf6588662020-09-07 11:55:35 -07004363 for (j = 0; j < bus->dev_count; j++) {
4364 if (j == i)
4365 continue;
4366 kvm_iodevice_destructor(bus->range[j].dev);
4367 }
David Hildenbrand90db1042017-03-23 18:24:19 +01004368 }
Amos Konga13007162012-03-09 12:17:32 +08004369
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004370 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4371 synchronize_srcu_expedited(&kvm->srcu);
4372 kfree(bus);
David Hildenbrand90db1042017-03-23 18:24:19 +01004373 return;
Gregory Haskins2eeb2e92007-05-31 14:08:53 -04004374}
4375
Andre Przywara8a39d002016-07-15 12:43:26 +01004376struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4377 gpa_t addr)
4378{
4379 struct kvm_io_bus *bus;
4380 int dev_idx, srcu_idx;
4381 struct kvm_io_device *iodev = NULL;
4382
4383 srcu_idx = srcu_read_lock(&kvm->srcu);
4384
4385 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
David Hildenbrand90db1042017-03-23 18:24:19 +01004386 if (!bus)
4387 goto out_unlock;
Andre Przywara8a39d002016-07-15 12:43:26 +01004388
4389 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
4390 if (dev_idx < 0)
4391 goto out_unlock;
4392
4393 iodev = bus->range[dev_idx].dev;
4394
4395out_unlock:
4396 srcu_read_unlock(&kvm->srcu, srcu_idx);
4397
4398 return iodev;
4399}
4400EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
4401
Janosch Frank536a6f82016-05-18 13:26:23 +02004402static int kvm_debugfs_open(struct inode *inode, struct file *file,
4403 int (*get)(void *, u64 *), int (*set)(void *, u64),
4404 const char *fmt)
4405{
4406 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4407 inode->i_private;
4408
4409 /* The debugfs files are a reference to the kvm struct which
4410 * is still valid when kvm_destroy_vm is called.
4411 * To avoid the race between open and the removal of the debugfs
4412 * directory we test against the users count.
4413 */
Elena Reshetovae3736c32017-02-20 13:06:21 +02004414 if (!refcount_inc_not_zero(&stat_data->kvm->users_count))
Janosch Frank536a6f82016-05-18 13:26:23 +02004415 return -ENOENT;
4416
Paolo Bonzini833b45d2019-09-30 18:48:44 +02004417 if (simple_attr_open(inode, file, get,
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004418 KVM_DBGFS_GET_MODE(stat_data->dbgfs_item) & 0222
4419 ? set : NULL,
4420 fmt)) {
Janosch Frank536a6f82016-05-18 13:26:23 +02004421 kvm_put_kvm(stat_data->kvm);
4422 return -ENOMEM;
4423 }
4424
4425 return 0;
4426}
4427
4428static int kvm_debugfs_release(struct inode *inode, struct file *file)
4429{
4430 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4431 inode->i_private;
4432
4433 simple_attr_release(inode, file);
4434 kvm_put_kvm(stat_data->kvm);
4435
4436 return 0;
4437}
4438
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004439static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
Janosch Frank536a6f82016-05-18 13:26:23 +02004440{
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004441 *val = *(ulong *)((void *)kvm + offset);
Janosch Frank536a6f82016-05-18 13:26:23 +02004442
4443 return 0;
4444}
4445
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004446static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004447{
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004448 *(ulong *)((void *)kvm + offset) = 0;
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004449
4450 return 0;
4451}
4452
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004453static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
Janosch Frank536a6f82016-05-18 13:26:23 +02004454{
4455 int i;
Janosch Frank536a6f82016-05-18 13:26:23 +02004456 struct kvm_vcpu *vcpu;
4457
4458 *val = 0;
4459
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004460 kvm_for_each_vcpu(i, vcpu, kvm)
4461 *val += *(u64 *)((void *)vcpu + offset);
Janosch Frank536a6f82016-05-18 13:26:23 +02004462
4463 return 0;
4464}
4465
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004466static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004467{
4468 int i;
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004469 struct kvm_vcpu *vcpu;
4470
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004471 kvm_for_each_vcpu(i, vcpu, kvm)
4472 *(u64 *)((void *)vcpu + offset) = 0;
4473
4474 return 0;
4475}
4476
4477static int kvm_stat_data_get(void *data, u64 *val)
4478{
4479 int r = -EFAULT;
4480 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4481
4482 switch (stat_data->dbgfs_item->kind) {
4483 case KVM_STAT_VM:
4484 r = kvm_get_stat_per_vm(stat_data->kvm,
4485 stat_data->dbgfs_item->offset, val);
4486 break;
4487 case KVM_STAT_VCPU:
4488 r = kvm_get_stat_per_vcpu(stat_data->kvm,
4489 stat_data->dbgfs_item->offset, val);
4490 break;
4491 }
4492
4493 return r;
4494}
4495
4496static int kvm_stat_data_clear(void *data, u64 val)
4497{
4498 int r = -EFAULT;
4499 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4500
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004501 if (val)
4502 return -EINVAL;
4503
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004504 switch (stat_data->dbgfs_item->kind) {
4505 case KVM_STAT_VM:
4506 r = kvm_clear_stat_per_vm(stat_data->kvm,
4507 stat_data->dbgfs_item->offset);
4508 break;
4509 case KVM_STAT_VCPU:
4510 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
4511 stat_data->dbgfs_item->offset);
4512 break;
4513 }
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004514
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004515 return r;
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004516}
4517
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004518static int kvm_stat_data_open(struct inode *inode, struct file *file)
Janosch Frank536a6f82016-05-18 13:26:23 +02004519{
4520 __simple_attr_check_format("%llu\n", 0ull);
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004521 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
4522 kvm_stat_data_clear, "%llu\n");
Janosch Frank536a6f82016-05-18 13:26:23 +02004523}
4524
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004525static const struct file_operations stat_fops_per_vm = {
4526 .owner = THIS_MODULE,
4527 .open = kvm_stat_data_open,
Janosch Frank536a6f82016-05-18 13:26:23 +02004528 .release = kvm_debugfs_release,
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004529 .read = simple_attr_read,
4530 .write = simple_attr_write,
4531 .llseek = no_llseek,
Janosch Frank536a6f82016-05-18 13:26:23 +02004532};
4533
Christoph Hellwig8b88b092008-02-08 04:20:26 -08004534static int vm_stat_get(void *_offset, u64 *val)
Avi Kivityba1389b2007-11-18 16:24:12 +02004535{
4536 unsigned offset = (long)_offset;
Avi Kivityba1389b2007-11-18 16:24:12 +02004537 struct kvm *kvm;
Janosch Frank536a6f82016-05-18 13:26:23 +02004538 u64 tmp_val;
Avi Kivityba1389b2007-11-18 16:24:12 +02004539
Christoph Hellwig8b88b092008-02-08 04:20:26 -08004540 *val = 0;
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004541 mutex_lock(&kvm_lock);
Janosch Frank536a6f82016-05-18 13:26:23 +02004542 list_for_each_entry(kvm, &vm_list, vm_list) {
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004543 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
Janosch Frank536a6f82016-05-18 13:26:23 +02004544 *val += tmp_val;
4545 }
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004546 mutex_unlock(&kvm_lock);
Christoph Hellwig8b88b092008-02-08 04:20:26 -08004547 return 0;
Avi Kivityba1389b2007-11-18 16:24:12 +02004548}
4549
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004550static int vm_stat_clear(void *_offset, u64 val)
4551{
4552 unsigned offset = (long)_offset;
4553 struct kvm *kvm;
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004554
4555 if (val)
4556 return -EINVAL;
4557
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004558 mutex_lock(&kvm_lock);
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004559 list_for_each_entry(kvm, &vm_list, vm_list) {
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004560 kvm_clear_stat_per_vm(kvm, offset);
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004561 }
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004562 mutex_unlock(&kvm_lock);
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004563
4564 return 0;
4565}
4566
4567DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
Avi Kivityba1389b2007-11-18 16:24:12 +02004568
Christoph Hellwig8b88b092008-02-08 04:20:26 -08004569static int vcpu_stat_get(void *_offset, u64 *val)
Avi Kivity1165f5f2007-04-19 17:27:43 +03004570{
4571 unsigned offset = (long)_offset;
Avi Kivity1165f5f2007-04-19 17:27:43 +03004572 struct kvm *kvm;
Janosch Frank536a6f82016-05-18 13:26:23 +02004573 u64 tmp_val;
Avi Kivity1165f5f2007-04-19 17:27:43 +03004574
Christoph Hellwig8b88b092008-02-08 04:20:26 -08004575 *val = 0;
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004576 mutex_lock(&kvm_lock);
Janosch Frank536a6f82016-05-18 13:26:23 +02004577 list_for_each_entry(kvm, &vm_list, vm_list) {
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004578 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
Janosch Frank536a6f82016-05-18 13:26:23 +02004579 *val += tmp_val;
4580 }
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004581 mutex_unlock(&kvm_lock);
Christoph Hellwig8b88b092008-02-08 04:20:26 -08004582 return 0;
Avi Kivity1165f5f2007-04-19 17:27:43 +03004583}
4584
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004585static int vcpu_stat_clear(void *_offset, u64 val)
4586{
4587 unsigned offset = (long)_offset;
4588 struct kvm *kvm;
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004589
4590 if (val)
4591 return -EINVAL;
4592
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004593 mutex_lock(&kvm_lock);
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004594 list_for_each_entry(kvm, &vm_list, vm_list) {
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004595 kvm_clear_stat_per_vcpu(kvm, offset);
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004596 }
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004597 mutex_unlock(&kvm_lock);
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004598
4599 return 0;
4600}
4601
4602DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
4603 "%llu\n");
Avi Kivityba1389b2007-11-18 16:24:12 +02004604
Alexey Dobriyan828c0952009-10-01 15:43:56 -07004605static const struct file_operations *stat_fops[] = {
Avi Kivityba1389b2007-11-18 16:24:12 +02004606 [KVM_STAT_VCPU] = &vcpu_stat_fops,
4607 [KVM_STAT_VM] = &vm_stat_fops,
4608};
Avi Kivity1165f5f2007-04-19 17:27:43 +03004609
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004610static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
4611{
4612 struct kobj_uevent_env *env;
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004613 unsigned long long created, active;
4614
4615 if (!kvm_dev.this_device || !kvm)
4616 return;
4617
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004618 mutex_lock(&kvm_lock);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004619 if (type == KVM_EVENT_CREATE_VM) {
4620 kvm_createvm_count++;
4621 kvm_active_vms++;
4622 } else if (type == KVM_EVENT_DESTROY_VM) {
4623 kvm_active_vms--;
4624 }
4625 created = kvm_createvm_count;
4626 active = kvm_active_vms;
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004627 mutex_unlock(&kvm_lock);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004628
Ben Gardonb12ce362019-02-11 11:02:49 -08004629 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004630 if (!env)
4631 return;
4632
4633 add_uevent_var(env, "CREATED=%llu", created);
4634 add_uevent_var(env, "COUNT=%llu", active);
4635
Claudio Imbrendafdeaf7e2017-07-24 13:40:03 +02004636 if (type == KVM_EVENT_CREATE_VM) {
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004637 add_uevent_var(env, "EVENT=create");
Claudio Imbrendafdeaf7e2017-07-24 13:40:03 +02004638 kvm->userspace_pid = task_pid_nr(current);
4639 } else if (type == KVM_EVENT_DESTROY_VM) {
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004640 add_uevent_var(env, "EVENT=destroy");
Claudio Imbrendafdeaf7e2017-07-24 13:40:03 +02004641 }
4642 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004643
Greg Kroah-Hartman8ed05792019-02-28 16:34:37 +01004644 if (!IS_ERR_OR_NULL(kvm->debugfs_dentry)) {
Ben Gardonb12ce362019-02-11 11:02:49 -08004645 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004646
Claudio Imbrendafdeaf7e2017-07-24 13:40:03 +02004647 if (p) {
4648 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
4649 if (!IS_ERR(tmp))
4650 add_uevent_var(env, "STATS_PATH=%s", tmp);
4651 kfree(p);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004652 }
4653 }
4654 /* no need for checks, since we are adding at most only 5 keys */
4655 env->envp[env->envp_idx++] = NULL;
4656 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
4657 kfree(env);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004658}
4659
Greg Kroah-Hartman929f45e2018-05-29 18:22:04 +02004660static void kvm_init_debug(void)
Avi Kivity6aa8b732006-12-10 02:21:36 -08004661{
4662 struct kvm_stats_debugfs_item *p;
4663
Hollis Blanchard76f7c872008-04-15 16:05:42 -05004664 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
Hamo4f69b682011-12-15 14:23:16 +08004665
Janosch Frank536a6f82016-05-18 13:26:23 +02004666 kvm_debugfs_num_entries = 0;
4667 for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004668 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
4669 kvm_debugfs_dir, (void *)(long)p->offset,
Greg Kroah-Hartman929f45e2018-05-29 18:22:04 +02004670 stat_fops[p->kind]);
Hamo4f69b682011-12-15 14:23:16 +08004671 }
Avi Kivity6aa8b732006-12-10 02:21:36 -08004672}
4673
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +01004674static int kvm_suspend(void)
Avi Kivity59ae6c62007-02-12 00:54:48 -08004675{
Alexander Graf10474ae2009-09-15 11:37:46 +02004676 if (kvm_usage_count)
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004677 hardware_disable_nolock(NULL);
Avi Kivity59ae6c62007-02-12 00:54:48 -08004678 return 0;
4679}
4680
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +01004681static void kvm_resume(void)
Avi Kivity59ae6c62007-02-12 00:54:48 -08004682{
Zachary Amsdenca84d1a2010-08-19 22:07:28 -10004683 if (kvm_usage_count) {
Wanpeng Li2eb06c32019-05-17 16:49:49 +08004684#ifdef CONFIG_LOCKDEP
4685 WARN_ON(lockdep_is_held(&kvm_count_lock));
4686#endif
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004687 hardware_enable_nolock(NULL);
Zachary Amsdenca84d1a2010-08-19 22:07:28 -10004688 }
Avi Kivity59ae6c62007-02-12 00:54:48 -08004689}
4690
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +01004691static struct syscore_ops kvm_syscore_ops = {
Avi Kivity59ae6c62007-02-12 00:54:48 -08004692 .suspend = kvm_suspend,
4693 .resume = kvm_resume,
4694};
4695
Avi Kivity15ad7142007-07-11 18:17:21 +03004696static inline
4697struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
4698{
4699 return container_of(pn, struct kvm_vcpu, preempt_notifier);
4700}
4701
4702static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
4703{
4704 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
Xiubo Lif95ef0cd2015-02-26 14:58:23 +08004705
Wanpeng Li046ddee2019-08-01 11:30:14 +08004706 WRITE_ONCE(vcpu->preempted, false);
Wanpeng Lid73eb572019-07-18 19:39:06 +08004707 WRITE_ONCE(vcpu->ready, false);
Avi Kivity15ad7142007-07-11 18:17:21 +03004708
Paolo Bonzini7495e222020-01-09 09:57:19 -05004709 __this_cpu_write(kvm_running_vcpu, vcpu);
Radim Krčmáře790d9e2014-08-21 18:08:05 +02004710 kvm_arch_sched_in(vcpu, cpu);
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +08004711 kvm_arch_vcpu_load(vcpu, cpu);
Avi Kivity15ad7142007-07-11 18:17:21 +03004712}
4713
4714static void kvm_sched_out(struct preempt_notifier *pn,
4715 struct task_struct *next)
4716{
4717 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4718
Wanpeng Lid73eb572019-07-18 19:39:06 +08004719 if (current->state == TASK_RUNNING) {
Wanpeng Li046ddee2019-08-01 11:30:14 +08004720 WRITE_ONCE(vcpu->preempted, true);
Wanpeng Lid73eb572019-07-18 19:39:06 +08004721 WRITE_ONCE(vcpu->ready, true);
4722 }
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +08004723 kvm_arch_vcpu_put(vcpu);
Paolo Bonzini7495e222020-01-09 09:57:19 -05004724 __this_cpu_write(kvm_running_vcpu, NULL);
4725}
4726
4727/**
4728 * kvm_get_running_vcpu - get the vcpu running on the current CPU.
Marc Zyngier1f03b2b2020-02-07 16:34:10 +00004729 *
4730 * We can disable preemption locally around accessing the per-CPU variable,
4731 * and use the resolved vcpu pointer after enabling preemption again,
4732 * because even if the current thread is migrated to another CPU, reading
4733 * the per-CPU value later will give us the same value as we update the
4734 * per-CPU variable in the preempt notifier handlers.
Paolo Bonzini7495e222020-01-09 09:57:19 -05004735 */
4736struct kvm_vcpu *kvm_get_running_vcpu(void)
4737{
Marc Zyngier1f03b2b2020-02-07 16:34:10 +00004738 struct kvm_vcpu *vcpu;
4739
4740 preempt_disable();
4741 vcpu = __this_cpu_read(kvm_running_vcpu);
4742 preempt_enable();
4743
4744 return vcpu;
Paolo Bonzini7495e222020-01-09 09:57:19 -05004745}
Wanpeng Li379a3c82020-04-28 14:23:27 +08004746EXPORT_SYMBOL_GPL(kvm_get_running_vcpu);
Paolo Bonzini7495e222020-01-09 09:57:19 -05004747
4748/**
4749 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
4750 */
4751struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
4752{
4753 return &kvm_running_vcpu;
Avi Kivity15ad7142007-07-11 18:17:21 +03004754}
4755
Sean Christophersonb9904082020-03-21 13:25:55 -07004756struct kvm_cpu_compat_check {
4757 void *opaque;
4758 int *ret;
4759};
4760
4761static void check_processor_compat(void *data)
Sean Christophersonf257d6d2019-04-19 22:18:17 -07004762{
Sean Christophersonb9904082020-03-21 13:25:55 -07004763 struct kvm_cpu_compat_check *c = data;
4764
4765 *c->ret = kvm_arch_check_processor_compat(c->opaque);
Sean Christophersonf257d6d2019-04-19 22:18:17 -07004766}
4767
Avi Kivity0ee75be2010-04-28 15:39:01 +03004768int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
Rusty Russellc16f8622007-07-30 21:12:19 +10004769 struct module *module)
Avi Kivity6aa8b732006-12-10 02:21:36 -08004770{
Sean Christophersonb9904082020-03-21 13:25:55 -07004771 struct kvm_cpu_compat_check c;
Avi Kivity6aa8b732006-12-10 02:21:36 -08004772 int r;
Yang, Sheng002c7f72007-07-31 14:23:01 +03004773 int cpu;
Avi Kivity6aa8b732006-12-10 02:21:36 -08004774
Zhang Xiantaof8c16bb2007-11-14 20:40:21 +08004775 r = kvm_arch_init(opaque);
4776 if (r)
Zhang Xiantaod23087842007-11-29 15:35:39 +08004777 goto out_fail;
Zhang Xiantaocb498ea2007-11-14 20:39:31 +08004778
Asias He7dac16c2013-05-08 10:57:29 +08004779 /*
4780 * kvm_arch_init makes sure there's at most one caller
4781 * for architectures that support multiple implementations,
4782 * like intel and amd on x86.
Paolo Bonzini36343f62016-10-26 13:35:56 +02004783 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
4784 * conflicts in case kvm is already setup for another implementation.
Asias He7dac16c2013-05-08 10:57:29 +08004785 */
Paolo Bonzini36343f62016-10-26 13:35:56 +02004786 r = kvm_irqfd_init();
4787 if (r)
4788 goto out_irqfd;
Asias He7dac16c2013-05-08 10:57:29 +08004789
Avi Kivity8437a6172009-06-06 14:52:35 -07004790 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
Rusty Russell7f59f492008-12-07 21:25:45 +10304791 r = -ENOMEM;
4792 goto out_free_0;
4793 }
4794
Sean Christophersonb9904082020-03-21 13:25:55 -07004795 r = kvm_arch_hardware_setup(opaque);
Avi Kivity6aa8b732006-12-10 02:21:36 -08004796 if (r < 0)
Miaohe Linfaf0be22019-11-23 10:45:50 +08004797 goto out_free_1;
Avi Kivity6aa8b732006-12-10 02:21:36 -08004798
Sean Christophersonb9904082020-03-21 13:25:55 -07004799 c.ret = &r;
4800 c.opaque = opaque;
Yang, Sheng002c7f72007-07-31 14:23:01 +03004801 for_each_online_cpu(cpu) {
Sean Christophersonb9904082020-03-21 13:25:55 -07004802 smp_call_function_single(cpu, check_processor_compat, &c, 1);
Yang, Sheng002c7f72007-07-31 14:23:01 +03004803 if (r < 0)
Miaohe Linfaf0be22019-11-23 10:45:50 +08004804 goto out_free_2;
Yang, Sheng002c7f72007-07-31 14:23:01 +03004805 }
4806
Thomas Gleixner73c1b412016-12-21 20:19:54 +01004807 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00004808 kvm_starting_cpu, kvm_dying_cpu);
Avi Kivity774c47f2007-02-12 00:54:47 -08004809 if (r)
Zhang Xiantaod23087842007-11-29 15:35:39 +08004810 goto out_free_2;
Avi Kivity6aa8b732006-12-10 02:21:36 -08004811 register_reboot_notifier(&kvm_reboot_notifier);
4812
Rusty Russellc16f8622007-07-30 21:12:19 +10004813 /* A kmem cache lets us meet the alignment requirements of fx_save. */
Avi Kivity0ee75be2010-04-28 15:39:01 +03004814 if (!vcpu_align)
4815 vcpu_align = __alignof__(struct kvm_vcpu);
Paolo Bonzini46515732017-10-26 15:45:46 +02004816 kvm_vcpu_cache =
4817 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
4818 SLAB_ACCOUNT,
4819 offsetof(struct kvm_vcpu, arch),
4820 sizeof_field(struct kvm_vcpu, arch),
4821 NULL);
Rusty Russellc16f8622007-07-30 21:12:19 +10004822 if (!kvm_vcpu_cache) {
4823 r = -ENOMEM;
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +01004824 goto out_free_3;
Rusty Russellc16f8622007-07-30 21:12:19 +10004825 }
4826
Gleb Natapovaf585b92010-10-14 11:22:46 +02004827 r = kvm_async_pf_init();
4828 if (r)
4829 goto out_free;
4830
Avi Kivity6aa8b732006-12-10 02:21:36 -08004831 kvm_chardev_ops.owner = module;
Christian Borntraeger3d3aab12008-12-02 11:17:32 +01004832 kvm_vm_fops.owner = module;
4833 kvm_vcpu_fops.owner = module;
Avi Kivity6aa8b732006-12-10 02:21:36 -08004834
4835 r = misc_register(&kvm_dev);
4836 if (r) {
Xiubo Li1170adc2015-02-26 14:58:26 +08004837 pr_err("kvm: misc device register failed\n");
Gleb Natapovaf585b92010-10-14 11:22:46 +02004838 goto out_unreg;
Avi Kivity6aa8b732006-12-10 02:21:36 -08004839 }
4840
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +01004841 register_syscore_ops(&kvm_syscore_ops);
4842
Avi Kivity15ad7142007-07-11 18:17:21 +03004843 kvm_preempt_ops.sched_in = kvm_sched_in;
4844 kvm_preempt_ops.sched_out = kvm_sched_out;
4845
Greg Kroah-Hartman929f45e2018-05-29 18:22:04 +02004846 kvm_init_debug();
Darrick J. Wong0ea4ed82009-10-14 16:21:00 -07004847
Paolo Bonzini3c3c29f2014-09-24 13:02:46 +02004848 r = kvm_vfio_ops_init();
4849 WARN_ON(r);
4850
Avi Kivityc7addb92007-09-16 18:58:32 +02004851 return 0;
Avi Kivity6aa8b732006-12-10 02:21:36 -08004852
Gleb Natapovaf585b92010-10-14 11:22:46 +02004853out_unreg:
4854 kvm_async_pf_deinit();
Avi Kivity6aa8b732006-12-10 02:21:36 -08004855out_free:
Rusty Russellc16f8622007-07-30 21:12:19 +10004856 kmem_cache_destroy(kvm_vcpu_cache);
Zhang Xiantaod23087842007-11-29 15:35:39 +08004857out_free_3:
Avi Kivity6aa8b732006-12-10 02:21:36 -08004858 unregister_reboot_notifier(&kvm_reboot_notifier);
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00004859 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
Zhang Xiantaod23087842007-11-29 15:35:39 +08004860out_free_2:
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +08004861 kvm_arch_hardware_unsetup();
Miaohe Linfaf0be22019-11-23 10:45:50 +08004862out_free_1:
Rusty Russell7f59f492008-12-07 21:25:45 +10304863 free_cpumask_var(cpus_hardware_enabled);
Zhang Xiantaod23087842007-11-29 15:35:39 +08004864out_free_0:
Cornelia Hucka0f155e2013-02-28 12:33:18 +01004865 kvm_irqfd_exit();
Paolo Bonzini36343f62016-10-26 13:35:56 +02004866out_irqfd:
Asias He7dac16c2013-05-08 10:57:29 +08004867 kvm_arch_exit();
4868out_fail:
Avi Kivity6aa8b732006-12-10 02:21:36 -08004869 return r;
4870}
Zhang Xiantaocb498ea2007-11-14 20:39:31 +08004871EXPORT_SYMBOL_GPL(kvm_init);
Avi Kivity6aa8b732006-12-10 02:21:36 -08004872
Zhang Xiantaocb498ea2007-11-14 20:39:31 +08004873void kvm_exit(void)
Avi Kivity6aa8b732006-12-10 02:21:36 -08004874{
Janosch Frank4bd33b52015-10-14 12:37:35 +02004875 debugfs_remove_recursive(kvm_debugfs_dir);
Avi Kivity6aa8b732006-12-10 02:21:36 -08004876 misc_deregister(&kvm_dev);
Rusty Russellc16f8622007-07-30 21:12:19 +10004877 kmem_cache_destroy(kvm_vcpu_cache);
Gleb Natapovaf585b92010-10-14 11:22:46 +02004878 kvm_async_pf_deinit();
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +01004879 unregister_syscore_ops(&kvm_syscore_ops);
Avi Kivity6aa8b732006-12-10 02:21:36 -08004880 unregister_reboot_notifier(&kvm_reboot_notifier);
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00004881 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004882 on_each_cpu(hardware_disable_nolock, NULL, 1);
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +08004883 kvm_arch_hardware_unsetup();
Zhang Xiantaof8c16bb2007-11-14 20:40:21 +08004884 kvm_arch_exit();
Cornelia Hucka0f155e2013-02-28 12:33:18 +01004885 kvm_irqfd_exit();
Rusty Russell7f59f492008-12-07 21:25:45 +10304886 free_cpumask_var(cpus_hardware_enabled);
Wanpeng Li571ee1b2014-10-09 18:30:08 +08004887 kvm_vfio_ops_exit();
Avi Kivity6aa8b732006-12-10 02:21:36 -08004888}
Zhang Xiantaocb498ea2007-11-14 20:39:31 +08004889EXPORT_SYMBOL_GPL(kvm_exit);
Junaid Shahidc57c8042019-11-04 12:22:02 +01004890
4891struct kvm_vm_worker_thread_context {
4892 struct kvm *kvm;
4893 struct task_struct *parent;
4894 struct completion init_done;
4895 kvm_vm_thread_fn_t thread_fn;
4896 uintptr_t data;
4897 int err;
4898};
4899
4900static int kvm_vm_worker_thread(void *context)
4901{
4902 /*
4903 * The init_context is allocated on the stack of the parent thread, so
4904 * we have to locally copy anything that is needed beyond initialization
4905 */
4906 struct kvm_vm_worker_thread_context *init_context = context;
4907 struct kvm *kvm = init_context->kvm;
4908 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
4909 uintptr_t data = init_context->data;
4910 int err;
4911
4912 err = kthread_park(current);
4913 /* kthread_park(current) is never supposed to return an error */
4914 WARN_ON(err != 0);
4915 if (err)
4916 goto init_complete;
4917
4918 err = cgroup_attach_task_all(init_context->parent, current);
4919 if (err) {
4920 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
4921 __func__, err);
4922 goto init_complete;
4923 }
4924
4925 set_user_nice(current, task_nice(init_context->parent));
4926
4927init_complete:
4928 init_context->err = err;
4929 complete(&init_context->init_done);
4930 init_context = NULL;
4931
4932 if (err)
4933 return err;
4934
4935 /* Wait to be woken up by the spawner before proceeding. */
4936 kthread_parkme();
4937
4938 if (!kthread_should_stop())
4939 err = thread_fn(kvm, data);
4940
4941 return err;
4942}
4943
4944int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
4945 uintptr_t data, const char *name,
4946 struct task_struct **thread_ptr)
4947{
4948 struct kvm_vm_worker_thread_context init_context = {};
4949 struct task_struct *thread;
4950
4951 *thread_ptr = NULL;
4952 init_context.kvm = kvm;
4953 init_context.parent = current;
4954 init_context.thread_fn = thread_fn;
4955 init_context.data = data;
4956 init_completion(&init_context.init_done);
4957
4958 thread = kthread_run(kvm_vm_worker_thread, &init_context,
4959 "%s-%d", name, task_pid_nr(current));
4960 if (IS_ERR(thread))
4961 return PTR_ERR(thread);
4962
4963 /* kthread_run is never supposed to return NULL */
4964 WARN_ON(thread == NULL);
4965
4966 wait_for_completion(&init_context.init_done);
4967
4968 if (!init_context.err)
4969 *thread_ptr = thread;
4970
4971 return init_context.err;
4972}