blob: 62e45c64e4436974a8162bf61ede457d32eaeaf1 [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>
Izik Eidus3e021bf2007-11-19 11:16:57 +020058#include <asm/pgtable.h>
Avi Kivity6aa8b732006-12-10 02:21:36 -080059
Laurent Vivier5f94c172008-05-30 16:05:54 +020060#include "coalesced_mmio.h"
Gleb Natapovaf585b92010-10-14 11:22:46 +020061#include "async_pf.h"
Paolo Bonzini3c3c29f2014-09-24 13:02:46 +020062#include "vfio.h"
Laurent Vivier5f94c172008-05-30 16:05:54 +020063
Marcelo Tosatti229456f2009-06-17 09:22:14 -030064#define CREATE_TRACE_POINTS
65#include <trace/events/kvm.h>
66
Janosch Frank536a6f82016-05-18 13:26:23 +020067/* Worst case buffer size needed for holding an integer. */
68#define ITOA_MAX_LEN 12
69
Avi Kivity6aa8b732006-12-10 02:21:36 -080070MODULE_AUTHOR("Qumranet");
71MODULE_LICENSE("GPL");
72
David Hildenbrand920552b2015-09-18 12:34:53 +020073/* Architectures should define their poll value according to the halt latency */
Suraj Jitindar Singhec76d812016-10-14 11:53:19 +110074unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
Roman Storozhenko039c5d12017-06-27 12:51:18 +030075module_param(halt_poll_ns, uint, 0644);
Suraj Jitindar Singhec76d812016-10-14 11:53:19 +110076EXPORT_SYMBOL_GPL(halt_poll_ns);
Paolo Bonzinif7819512015-02-04 18:20:58 +010077
Wanpeng Liaca6ff22015-09-03 22:07:38 +080078/* Default doubles per-vcpu halt_poll_ns. */
Suraj Jitindar Singhec76d812016-10-14 11:53:19 +110079unsigned int halt_poll_ns_grow = 2;
Roman Storozhenko039c5d12017-06-27 12:51:18 +030080module_param(halt_poll_ns_grow, uint, 0644);
Suraj Jitindar Singhec76d812016-10-14 11:53:19 +110081EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
Wanpeng Liaca6ff22015-09-03 22:07:38 +080082
Nir Weiner49113d32019-01-27 12:17:15 +020083/* The start value to grow halt_poll_ns from */
84unsigned int halt_poll_ns_grow_start = 10000; /* 10us */
85module_param(halt_poll_ns_grow_start, uint, 0644);
86EXPORT_SYMBOL_GPL(halt_poll_ns_grow_start);
87
Wanpeng Liaca6ff22015-09-03 22:07:38 +080088/* Default resets per-vcpu halt_poll_ns . */
Suraj Jitindar Singhec76d812016-10-14 11:53:19 +110089unsigned int halt_poll_ns_shrink;
Roman Storozhenko039c5d12017-06-27 12:51:18 +030090module_param(halt_poll_ns_shrink, uint, 0644);
Suraj Jitindar Singhec76d812016-10-14 11:53:19 +110091EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
Wanpeng Liaca6ff22015-09-03 22:07:38 +080092
Marcelo Tosattifa40a822009-06-04 15:08:24 -030093/*
94 * Ordering of locks:
95 *
Xiubo Lib7d409d2015-02-26 14:58:24 +080096 * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
Marcelo Tosattifa40a822009-06-04 15:08:24 -030097 */
98
Junaid Shahid0d9ce162019-01-03 17:14:28 -080099DEFINE_MUTEX(kvm_lock);
Paolo Bonzini4a937f92013-09-10 12:58:35 +0200100static DEFINE_RAW_SPINLOCK(kvm_count_lock);
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +0800101LIST_HEAD(vm_list);
Avi Kivity133de902007-02-12 00:54:44 -0800102
Rusty Russell7f59f492008-12-07 21:25:45 +1030103static cpumask_var_t cpus_hardware_enabled;
Xiubo Lif4fee932015-02-26 14:58:21 +0800104static int kvm_usage_count;
Alexander Graf10474ae2009-09-15 11:37:46 +0200105static atomic_t hardware_enable_failed;
Avi Kivity1b6c0162007-05-24 13:03:52 +0300106
Sean Christophersonaaba2982019-12-18 13:55:16 -0800107static struct kmem_cache *kvm_vcpu_cache;
Avi Kivity1165f5f2007-04-19 17:27:43 +0300108
Avi Kivity15ad7142007-07-11 18:17:21 +0300109static __read_mostly struct preempt_ops kvm_preempt_ops;
Paolo Bonzini7495e222020-01-09 09:57:19 -0500110static DEFINE_PER_CPU(struct kvm_vcpu *, kvm_running_vcpu);
Avi Kivity15ad7142007-07-11 18:17:21 +0300111
Hollis Blanchard76f7c872008-04-15 16:05:42 -0500112struct dentry *kvm_debugfs_dir;
Paul Mackerrase23a8082015-03-28 14:21:01 +1100113EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
Avi Kivity6aa8b732006-12-10 02:21:36 -0800114
Janosch Frank536a6f82016-05-18 13:26:23 +0200115static int kvm_debugfs_num_entries;
Milan Pandurov09cbcef2019-12-13 14:07:21 +0100116static const struct file_operations stat_fops_per_vm;
Janosch Frank536a6f82016-05-18 13:26:23 +0200117
Avi Kivitybccf2152007-02-21 18:04:26 +0200118static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
119 unsigned long arg);
Christian Borntraegerde8e5d72015-02-03 09:35:15 +0100120#ifdef CONFIG_KVM_COMPAT
Alexander Graf1dda6062011-06-08 02:45:37 +0200121static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
122 unsigned long arg);
Marc Zyngier7ddfd3e2018-06-17 10:16:21 +0100123#define KVM_COMPAT(c) .compat_ioctl = (c)
124#else
Marc Zyngier9cb09e72019-11-14 13:17:39 +0000125/*
126 * For architectures that don't implement a compat infrastructure,
127 * adopt a double line of defense:
128 * - Prevent a compat task from opening /dev/kvm
129 * - If the open has been done by a 64bit task, and the KVM fd
130 * passed to a compat task, let the ioctls fail.
131 */
Marc Zyngier7ddfd3e2018-06-17 10:16:21 +0100132static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
133 unsigned long arg) { return -EINVAL; }
Marc Zyngierb9876e62019-11-13 16:05:23 +0000134
135static int kvm_no_compat_open(struct inode *inode, struct file *file)
136{
137 return is_compat_task() ? -ENODEV : 0;
138}
139#define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl, \
140 .open = kvm_no_compat_open
Alexander Graf1dda6062011-06-08 02:45:37 +0200141#endif
Alexander Graf10474ae2009-09-15 11:37:46 +0200142static int hardware_enable_all(void);
143static void hardware_disable_all(void);
Avi Kivitybccf2152007-02-21 18:04:26 +0200144
Marcelo Tosattie93f8a02009-12-23 14:35:24 -0200145static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
Stephen Hemminger79408762013-12-29 12:12:29 -0800146
Paolo Bonzinibc009e42015-05-26 12:43:41 +0200147static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot, gfn_t gfn);
Marcelo Tosattie93f8a02009-12-23 14:35:24 -0200148
Andi Kleen52480132014-02-08 08:51:57 +0100149__visible bool kvm_rebooting;
Avi Kivityb7c41452010-12-02 17:52:50 +0200150EXPORT_SYMBOL_GPL(kvm_rebooting);
Avi Kivity4ecac3f2008-05-13 13:23:38 +0300151
Marcelo Tosatti54dee992009-06-11 12:07:44 -0300152static bool largepages_enabled = true;
153
Claudio Imbrenda286de8f2017-07-12 17:56:44 +0200154#define KVM_EVENT_CREATE_VM 0
155#define KVM_EVENT_DESTROY_VM 1
156static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
157static unsigned long long kvm_createvm_count;
158static unsigned long long kvm_active_vms;
159
Michal Hocko93065ac2018-08-21 21:52:33 -0700160__weak int kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
161 unsigned long start, unsigned long end, bool blockable)
Radim Krčmářb1394e72017-11-30 19:05:45 +0100162{
Michal Hocko93065ac2018-08-21 21:52:33 -0700163 return 0;
Radim Krčmářb1394e72017-11-30 19:05:45 +0100164}
165
Sean Christophersona78986a2019-11-11 14:12:27 -0800166bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
167{
168 /*
169 * The metadata used by is_zone_device_page() to determine whether or
170 * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
171 * the device has been pinned, e.g. by get_user_pages(). WARN if the
172 * page_count() is zero to help detect bad usage of this helper.
173 */
174 if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
175 return false;
176
177 return is_zone_device_page(pfn_to_page(pfn));
178}
179
Dan Williamsba049e92016-01-15 16:56:11 -0800180bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
Ben-Ami Yassourcbff90a2008-07-28 19:26:24 +0300181{
Sean Christophersona78986a2019-11-11 14:12:27 -0800182 /*
183 * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
184 * perspective they are "normal" pages, albeit with slightly different
185 * usage rules.
186 */
Andrea Arcangeli11feeb42013-07-25 03:04:38 +0200187 if (pfn_valid(pfn))
Sean Christophersona78986a2019-11-11 14:12:27 -0800188 return PageReserved(pfn_to_page(pfn)) &&
Zhuang Yanying7df003c2019-10-12 11:37:31 +0800189 !is_zero_pfn(pfn) &&
Sean Christophersona78986a2019-11-11 14:12:27 -0800190 !kvm_is_zone_device_pfn(pfn);
Ben-Ami Yassourcbff90a2008-07-28 19:26:24 +0300191
192 return true;
193}
194
Sean Christopherson005ba372020-01-08 12:24:36 -0800195bool kvm_is_transparent_hugepage(kvm_pfn_t pfn)
196{
197 struct page *page = pfn_to_page(pfn);
198
199 if (!PageTransCompoundMap(page))
200 return false;
201
202 return is_transparent_hugepage(compound_head(page));
203}
204
Avi Kivity6aa8b732006-12-10 02:21:36 -0800205/*
206 * Switches to specified vcpu, until a matching vcpu_put()
207 */
Christoffer Dallec7660c2017-12-04 21:35:23 +0100208void vcpu_load(struct kvm_vcpu *vcpu)
Avi Kivity6aa8b732006-12-10 02:21:36 -0800209{
Christoffer Dallec7660c2017-12-04 21:35:23 +0100210 int cpu = get_cpu();
Paolo Bonzini7495e222020-01-09 09:57:19 -0500211
212 __this_cpu_write(kvm_running_vcpu, vcpu);
Avi Kivity15ad7142007-07-11 18:17:21 +0300213 preempt_notifier_register(&vcpu->preempt_notifier);
Carsten Otte313a3dc2007-10-11 19:16:52 +0200214 kvm_arch_vcpu_load(vcpu, cpu);
Avi Kivity15ad7142007-07-11 18:17:21 +0300215 put_cpu();
Avi Kivitybccf2152007-02-21 18:04:26 +0200216}
Jim Mattson2f1fe812016-07-08 15:36:06 -0700217EXPORT_SYMBOL_GPL(vcpu_load);
Avi Kivitybccf2152007-02-21 18:04:26 +0200218
Carsten Otte313a3dc2007-10-11 19:16:52 +0200219void vcpu_put(struct kvm_vcpu *vcpu)
Avi Kivity6aa8b732006-12-10 02:21:36 -0800220{
Avi Kivity15ad7142007-07-11 18:17:21 +0300221 preempt_disable();
Carsten Otte313a3dc2007-10-11 19:16:52 +0200222 kvm_arch_vcpu_put(vcpu);
Avi Kivity15ad7142007-07-11 18:17:21 +0300223 preempt_notifier_unregister(&vcpu->preempt_notifier);
Paolo Bonzini7495e222020-01-09 09:57:19 -0500224 __this_cpu_write(kvm_running_vcpu, NULL);
Avi Kivity15ad7142007-07-11 18:17:21 +0300225 preempt_enable();
Avi Kivity6aa8b732006-12-10 02:21:36 -0800226}
Jim Mattson2f1fe812016-07-08 15:36:06 -0700227EXPORT_SYMBOL_GPL(vcpu_put);
Avi Kivity6aa8b732006-12-10 02:21:36 -0800228
Paolo Bonzini7a97cec2017-04-27 14:33:43 +0200229/* TODO: merge with kvm_arch_vcpu_should_kick */
230static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
231{
232 int mode = kvm_vcpu_exiting_guest_mode(vcpu);
233
234 /*
235 * We need to wait for the VCPU to reenable interrupts and get out of
236 * READING_SHADOW_PAGE_TABLES mode.
237 */
238 if (req & KVM_REQUEST_WAIT)
239 return mode != OUTSIDE_GUEST_MODE;
240
241 /*
242 * Need to kick a running VCPU, but otherwise there is nothing to do.
243 */
244 return mode == IN_GUEST_MODE;
245}
246
Avi Kivityd9e368d2007-06-07 19:18:30 +0300247static void ack_flush(void *_completed)
248{
Avi Kivityd9e368d2007-06-07 19:18:30 +0300249}
250
Paolo Bonzinib49defe2017-06-30 13:25:45 +0200251static inline bool kvm_kick_many_cpus(const struct cpumask *cpus, bool wait)
252{
253 if (unlikely(!cpus))
254 cpus = cpu_online_mask;
255
256 if (cpumask_empty(cpus))
257 return false;
258
259 smp_call_function_many(cpus, ack_flush, NULL, wait);
260 return true;
261}
262
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200263bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
264 unsigned long *vcpu_bitmap, cpumask_var_t tmp)
Avi Kivityd9e368d2007-06-07 19:18:30 +0300265{
Avi Kivity597a5f52008-07-20 14:24:22 +0300266 int i, cpu, me;
Avi Kivityd9e368d2007-06-07 19:18:30 +0300267 struct kvm_vcpu *vcpu;
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200268 bool called;
Rusty Russell6ef7a1b2008-12-08 20:28:04 +1030269
Xiao Guangrong3cba4132011-01-12 15:41:22 +0800270 me = get_cpu();
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200271
Gleb Natapov988a2ca2009-06-09 15:56:29 +0300272 kvm_for_each_vcpu(i, vcpu, kvm) {
Vitaly Kuznetsova8122972018-08-22 12:18:29 +0200273 if (vcpu_bitmap && !test_bit(i, vcpu_bitmap))
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200274 continue;
275
Xiao Guangrong3cba4132011-01-12 15:41:22 +0800276 kvm_make_request(req, vcpu);
Avi Kivityd9e368d2007-06-07 19:18:30 +0300277 cpu = vcpu->cpu;
Xiao Guangrong6b7e2d02011-01-12 15:40:31 +0800278
Radim Krčmář178f02f2017-04-26 22:32:26 +0200279 if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
280 continue;
Radim Krčmář6c6e8362017-04-26 22:32:23 +0200281
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200282 if (tmp != NULL && cpu != -1 && cpu != me &&
Paolo Bonzini7a97cec2017-04-27 14:33:43 +0200283 kvm_request_needs_ipi(vcpu, req))
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200284 __cpumask_set_cpu(cpu, tmp);
Avi Kivityd9e368d2007-06-07 19:18:30 +0300285 }
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200286
287 called = kvm_kick_many_cpus(tmp, !!(req & KVM_REQUEST_WAIT));
Xiao Guangrong3cba4132011-01-12 15:41:22 +0800288 put_cpu();
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200289
290 return called;
291}
292
293bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
294{
295 cpumask_var_t cpus;
296 bool called;
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200297
298 zalloc_cpumask_var(&cpus, GFP_ATOMIC);
299
Vitaly Kuznetsova8122972018-08-22 12:18:29 +0200300 called = kvm_make_vcpus_request_mask(kvm, req, NULL, cpus);
Vitaly Kuznetsov7053df42018-05-16 17:21:28 +0200301
Rusty Russell6ef7a1b2008-12-08 20:28:04 +1030302 free_cpumask_var(cpus);
Rusty Russell49846892008-12-08 20:26:24 +1030303 return called;
304}
305
Mario Smarducha6d51012015-01-15 15:58:52 -0800306#ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
Rusty Russell49846892008-12-08 20:26:24 +1030307void kvm_flush_remote_tlbs(struct kvm *kvm)
308{
Lan Tianyu4ae3cb32016-03-13 11:10:28 +0800309 /*
310 * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
311 * kvm_make_all_cpus_request.
312 */
313 long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
Xiao Guangronga086f6a2014-04-17 17:06:12 +0800314
Lan Tianyu4ae3cb32016-03-13 11:10:28 +0800315 /*
316 * We want to publish modifications to the page tables before reading
317 * mode. Pairs with a memory barrier in arch-specific code.
318 * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
319 * and smp_mb in walk_shadow_page_lockless_begin/end.
320 * - powerpc: smp_mb in kvmppc_prepare_to_enter.
321 *
322 * There is already an smp_mb__after_atomic() before
323 * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
324 * barrier here.
325 */
Tianyu Lanb08660e2018-07-19 08:40:17 +0000326 if (!kvm_arch_flush_remote_tlb(kvm)
327 || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
Rusty Russell49846892008-12-08 20:26:24 +1030328 ++kvm->stat.remote_tlb_flush;
Xiao Guangronga086f6a2014-04-17 17:06:12 +0800329 cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
Avi Kivityd9e368d2007-06-07 19:18:30 +0300330}
Aneesh Kumar K.V2ba9f0d2013-10-07 22:17:59 +0530331EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
Mario Smarducha6d51012015-01-15 15:58:52 -0800332#endif
Avi Kivityd9e368d2007-06-07 19:18:30 +0300333
Marcelo Tosatti2e53d632008-02-20 14:47:24 -0500334void kvm_reload_remote_mmus(struct kvm *kvm)
335{
Tang Chen445b8232014-09-24 15:57:55 +0800336 kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
Marcelo Tosatti2e53d632008-02-20 14:47:24 -0500337}
338
Sean Christopherson8bd826d2019-12-18 13:55:30 -0800339static void kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
Rusty Russellfb3f0f52007-07-27 17:16:56 +1000340{
Rusty Russellfb3f0f52007-07-27 17:16:56 +1000341 mutex_init(&vcpu->mutex);
342 vcpu->cpu = -1;
Rusty Russellfb3f0f52007-07-27 17:16:56 +1000343 vcpu->kvm = kvm;
344 vcpu->vcpu_id = id;
Rik van Riel34bb10b2011-02-01 09:52:41 -0500345 vcpu->pid = NULL;
Marcelo Tosatti85773702016-02-19 09:46:39 +0100346 init_swait_queue_head(&vcpu->wq);
Gleb Natapovaf585b92010-10-14 11:22:46 +0200347 kvm_async_pf_vcpu_init(vcpu);
Rusty Russellfb3f0f52007-07-27 17:16:56 +1000348
Feng Wubf9f6ac2015-09-18 22:29:55 +0800349 vcpu->pre_pcpu = -1;
350 INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
351
Raghavendra K T4c088492012-07-18 19:07:46 +0530352 kvm_vcpu_set_in_spin_loop(vcpu, false);
353 kvm_vcpu_set_dy_eligible(vcpu, false);
Raghavendra K T3a08a8f2013-03-04 23:32:07 +0530354 vcpu->preempted = false;
Wanpeng Lid73eb572019-07-18 19:39:06 +0800355 vcpu->ready = false;
Sean Christophersond5c48de2019-12-18 13:55:17 -0800356 preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
Rusty Russellfb3f0f52007-07-27 17:16:56 +1000357}
Rusty Russellfb3f0f52007-07-27 17:16:56 +1000358
Sean Christopherson4543bdc2019-12-18 13:55:14 -0800359void kvm_vcpu_destroy(struct kvm_vcpu *vcpu)
360{
361 kvm_arch_vcpu_destroy(vcpu);
Sean Christophersone529ef62019-12-18 13:55:15 -0800362
Sean Christopherson9941d222019-12-18 13:55:29 -0800363 /*
364 * No need for rcu_read_lock as VCPU_RUN is the only place that changes
365 * the vcpu->pid pointer, and at destruction time all file descriptors
366 * are already gone.
367 */
368 put_pid(rcu_dereference_protected(vcpu->pid, 1));
369
Sean Christopherson8bd826d2019-12-18 13:55:30 -0800370 free_page((unsigned long)vcpu->run);
Sean Christophersone529ef62019-12-18 13:55:15 -0800371 kmem_cache_free(kvm_vcpu_cache, vcpu);
Sean Christopherson4543bdc2019-12-18 13:55:14 -0800372}
373EXPORT_SYMBOL_GPL(kvm_vcpu_destroy);
374
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200375#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
376static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
377{
378 return container_of(mn, struct kvm, mmu_notifier);
379}
380
Izik Eidus3da0dd42009-09-23 21:47:18 +0300381static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
382 struct mm_struct *mm,
383 unsigned long address,
384 pte_t pte)
385{
386 struct kvm *kvm = mmu_notifier_to_kvm(mn);
Marcelo Tosattibc6678a2009-12-23 14:35:21 -0200387 int idx;
Izik Eidus3da0dd42009-09-23 21:47:18 +0300388
Marcelo Tosattibc6678a2009-12-23 14:35:21 -0200389 idx = srcu_read_lock(&kvm->srcu);
Izik Eidus3da0dd42009-09-23 21:47:18 +0300390 spin_lock(&kvm->mmu_lock);
391 kvm->mmu_notifier_seq++;
Lan Tianyu0cf853c2018-12-06 21:21:11 +0800392
393 if (kvm_set_spte_hva(kvm, address, pte))
394 kvm_flush_remote_tlbs(kvm);
395
Izik Eidus3da0dd42009-09-23 21:47:18 +0300396 spin_unlock(&kvm->mmu_lock);
Marcelo Tosattibc6678a2009-12-23 14:35:21 -0200397 srcu_read_unlock(&kvm->srcu, idx);
Izik Eidus3da0dd42009-09-23 21:47:18 +0300398}
399
Michal Hocko93065ac2018-08-21 21:52:33 -0700400static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
Jérôme Glisse5d6527a2018-12-28 00:38:05 -0800401 const struct mmu_notifier_range *range)
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200402{
403 struct kvm *kvm = mmu_notifier_to_kvm(mn);
Marcelo Tosattibc6678a2009-12-23 14:35:21 -0200404 int need_tlb_flush = 0, idx;
Michal Hocko93065ac2018-08-21 21:52:33 -0700405 int ret;
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200406
Marcelo Tosattibc6678a2009-12-23 14:35:21 -0200407 idx = srcu_read_lock(&kvm->srcu);
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200408 spin_lock(&kvm->mmu_lock);
409 /*
410 * The count increase must become visible at unlock time as no
411 * spte can be established without taking the mmu_lock and
412 * count is also read inside the mmu_lock critical section.
413 */
414 kvm->mmu_notifier_count++;
Jérôme Glisse5d6527a2018-12-28 00:38:05 -0800415 need_tlb_flush = kvm_unmap_hva_range(kvm, range->start, range->end);
Xiao Guangronga4ee1ca2010-11-23 11:13:00 +0800416 need_tlb_flush |= kvm->tlbs_dirty;
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200417 /* we've to flush the tlb before the pages can be freed */
418 if (need_tlb_flush)
419 kvm_flush_remote_tlbs(kvm);
Takuya Yoshikawa565f3be2012-02-10 15:28:31 +0900420
421 spin_unlock(&kvm->mmu_lock);
Radim Krčmářb1394e72017-11-30 19:05:45 +0100422
Jérôme Glisse5d6527a2018-12-28 00:38:05 -0800423 ret = kvm_arch_mmu_notifier_invalidate_range(kvm, range->start,
Jérôme Glissedfcd6662019-05-13 17:20:38 -0700424 range->end,
425 mmu_notifier_range_blockable(range));
Radim Krčmářb1394e72017-11-30 19:05:45 +0100426
Takuya Yoshikawa565f3be2012-02-10 15:28:31 +0900427 srcu_read_unlock(&kvm->srcu, idx);
Michal Hocko93065ac2018-08-21 21:52:33 -0700428
429 return ret;
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200430}
431
432static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
Jérôme Glisse5d6527a2018-12-28 00:38:05 -0800433 const struct mmu_notifier_range *range)
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200434{
435 struct kvm *kvm = mmu_notifier_to_kvm(mn);
436
437 spin_lock(&kvm->mmu_lock);
438 /*
439 * This sequence increase will notify the kvm page fault that
440 * the page that is going to be mapped in the spte could have
441 * been freed.
442 */
443 kvm->mmu_notifier_seq++;
Paul Mackerrasa355aa52011-12-12 12:37:21 +0000444 smp_wmb();
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200445 /*
446 * The above sequence increase must be visible before the
Paul Mackerrasa355aa52011-12-12 12:37:21 +0000447 * below count decrease, which is ensured by the smp_wmb above
448 * in conjunction with the smp_rmb in mmu_notifier_retry().
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200449 */
450 kvm->mmu_notifier_count--;
451 spin_unlock(&kvm->mmu_lock);
452
453 BUG_ON(kvm->mmu_notifier_count < 0);
454}
455
456static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
457 struct mm_struct *mm,
Andres Lagar-Cavilla57128462014-09-22 14:54:42 -0700458 unsigned long start,
459 unsigned long end)
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200460{
461 struct kvm *kvm = mmu_notifier_to_kvm(mn);
Marcelo Tosattibc6678a2009-12-23 14:35:21 -0200462 int young, idx;
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200463
Marcelo Tosattibc6678a2009-12-23 14:35:21 -0200464 idx = srcu_read_lock(&kvm->srcu);
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200465 spin_lock(&kvm->mmu_lock);
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200466
Andres Lagar-Cavilla57128462014-09-22 14:54:42 -0700467 young = kvm_age_hva(kvm, start, end);
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200468 if (young)
469 kvm_flush_remote_tlbs(kvm);
470
Takuya Yoshikawa565f3be2012-02-10 15:28:31 +0900471 spin_unlock(&kvm->mmu_lock);
472 srcu_read_unlock(&kvm->srcu, idx);
473
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200474 return young;
475}
476
Vladimir Davydov1d7715c2015-09-09 15:35:41 -0700477static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
478 struct mm_struct *mm,
479 unsigned long start,
480 unsigned long end)
481{
482 struct kvm *kvm = mmu_notifier_to_kvm(mn);
483 int young, idx;
484
485 idx = srcu_read_lock(&kvm->srcu);
486 spin_lock(&kvm->mmu_lock);
487 /*
488 * Even though we do not flush TLB, this will still adversely
489 * affect performance on pre-Haswell Intel EPT, where there is
490 * no EPT Access Bit to clear so that we have to tear down EPT
491 * tables instead. If we find this unacceptable, we can always
492 * add a parameter to kvm_age_hva so that it effectively doesn't
493 * do anything on clear_young.
494 *
495 * Also note that currently we never issue secondary TLB flushes
496 * from clear_young, leaving this job up to the regular system
497 * cadence. If we find this inaccurate, we might come up with a
498 * more sophisticated heuristic later.
499 */
500 young = kvm_age_hva(kvm, start, end);
501 spin_unlock(&kvm->mmu_lock);
502 srcu_read_unlock(&kvm->srcu, idx);
503
504 return young;
505}
506
Andrea Arcangeli8ee53822011-01-13 15:47:10 -0800507static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
508 struct mm_struct *mm,
509 unsigned long address)
510{
511 struct kvm *kvm = mmu_notifier_to_kvm(mn);
512 int young, idx;
513
514 idx = srcu_read_lock(&kvm->srcu);
515 spin_lock(&kvm->mmu_lock);
516 young = kvm_test_age_hva(kvm, address);
517 spin_unlock(&kvm->mmu_lock);
518 srcu_read_unlock(&kvm->srcu, idx);
519
520 return young;
521}
522
Marcelo Tosatti85db06e2008-12-10 21:23:26 +0100523static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
524 struct mm_struct *mm)
525{
526 struct kvm *kvm = mmu_notifier_to_kvm(mn);
Lai Jiangshaneda2bed2010-04-20 14:29:29 +0800527 int idx;
528
529 idx = srcu_read_lock(&kvm->srcu);
Marcelo Tosatti2df72e92012-08-24 15:54:57 -0300530 kvm_arch_flush_shadow_all(kvm);
Lai Jiangshaneda2bed2010-04-20 14:29:29 +0800531 srcu_read_unlock(&kvm->srcu, idx);
Marcelo Tosatti85db06e2008-12-10 21:23:26 +0100532}
533
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200534static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200535 .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
536 .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
537 .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
Vladimir Davydov1d7715c2015-09-09 15:35:41 -0700538 .clear_young = kvm_mmu_notifier_clear_young,
Andrea Arcangeli8ee53822011-01-13 15:47:10 -0800539 .test_young = kvm_mmu_notifier_test_young,
Izik Eidus3da0dd42009-09-23 21:47:18 +0300540 .change_pte = kvm_mmu_notifier_change_pte,
Marcelo Tosatti85db06e2008-12-10 21:23:26 +0100541 .release = kvm_mmu_notifier_release,
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200542};
Avi Kivity4c07b0a2009-12-20 14:54:04 +0200543
544static int kvm_init_mmu_notifier(struct kvm *kvm)
545{
546 kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
547 return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
548}
549
550#else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
551
552static int kvm_init_mmu_notifier(struct kvm *kvm)
553{
554 return 0;
555}
556
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200557#endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
558
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200559static struct kvm_memslots *kvm_alloc_memslots(void)
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +0800560{
561 int i;
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200562 struct kvm_memslots *slots;
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +0800563
Ben Gardonb12ce362019-02-11 11:02:49 -0800564 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL_ACCOUNT);
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200565 if (!slots)
566 return NULL;
567
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +0800568 for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800569 slots->id_to_index[i] = slots->memslots[i].id = -1;
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200570
571 return slots;
572}
573
574static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
575{
576 if (!memslot->dirty_bitmap)
577 return;
578
579 kvfree(memslot->dirty_bitmap);
580 memslot->dirty_bitmap = NULL;
581}
582
Sean Christophersone96c81e2020-02-18 13:07:27 -0800583static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200584{
Sean Christophersone96c81e2020-02-18 13:07:27 -0800585 kvm_destroy_dirty_bitmap(slot);
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200586
Sean Christophersone96c81e2020-02-18 13:07:27 -0800587 kvm_arch_free_memslot(kvm, slot);
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200588
Sean Christophersone96c81e2020-02-18 13:07:27 -0800589 slot->flags = 0;
590 slot->npages = 0;
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200591}
592
593static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
594{
595 struct kvm_memory_slot *memslot;
596
597 if (!slots)
598 return;
599
600 kvm_for_each_memslot(memslot, slots)
Sean Christophersone96c81e2020-02-18 13:07:27 -0800601 kvm_free_memslot(kvm, memslot);
Paolo Bonzinia47d2b02015-05-17 11:41:37 +0200602
603 kvfree(slots);
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +0800604}
605
Janosch Frank536a6f82016-05-18 13:26:23 +0200606static void kvm_destroy_vm_debugfs(struct kvm *kvm)
607{
608 int i;
609
610 if (!kvm->debugfs_dentry)
611 return;
612
613 debugfs_remove_recursive(kvm->debugfs_dentry);
614
Luiz Capitulino9d5a1dc2016-09-07 14:47:21 -0400615 if (kvm->debugfs_stat_data) {
616 for (i = 0; i < kvm_debugfs_num_entries; i++)
617 kfree(kvm->debugfs_stat_data[i]);
618 kfree(kvm->debugfs_stat_data);
619 }
Janosch Frank536a6f82016-05-18 13:26:23 +0200620}
621
622static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
623{
624 char dir_name[ITOA_MAX_LEN * 2];
625 struct kvm_stat_data *stat_data;
626 struct kvm_stats_debugfs_item *p;
627
628 if (!debugfs_initialized())
629 return 0;
630
631 snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
Greg Kroah-Hartman929f45e2018-05-29 18:22:04 +0200632 kvm->debugfs_dentry = debugfs_create_dir(dir_name, kvm_debugfs_dir);
Janosch Frank536a6f82016-05-18 13:26:23 +0200633
634 kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
635 sizeof(*kvm->debugfs_stat_data),
Ben Gardonb12ce362019-02-11 11:02:49 -0800636 GFP_KERNEL_ACCOUNT);
Janosch Frank536a6f82016-05-18 13:26:23 +0200637 if (!kvm->debugfs_stat_data)
638 return -ENOMEM;
639
640 for (p = debugfs_entries; p->name; p++) {
Ben Gardonb12ce362019-02-11 11:02:49 -0800641 stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL_ACCOUNT);
Janosch Frank536a6f82016-05-18 13:26:23 +0200642 if (!stat_data)
643 return -ENOMEM;
644
645 stat_data->kvm = kvm;
Milan Pandurov09cbcef2019-12-13 14:07:21 +0100646 stat_data->dbgfs_item = p;
Janosch Frank536a6f82016-05-18 13:26:23 +0200647 kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
Milan Pandurov09cbcef2019-12-13 14:07:21 +0100648 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
649 kvm->debugfs_dentry, stat_data,
650 &stat_fops_per_vm);
Janosch Frank536a6f82016-05-18 13:26:23 +0200651 }
652 return 0;
653}
654
Junaid Shahid1aa9b952019-11-04 20:26:00 +0100655/*
656 * Called after the VM is otherwise initialized, but just before adding it to
657 * the vm_list.
658 */
659int __weak kvm_arch_post_init_vm(struct kvm *kvm)
660{
661 return 0;
662}
663
664/*
665 * Called just after removing the VM from the vm_list, but before doing any
666 * other destruction.
667 */
668void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
669{
670}
671
Carsten Ottee08b9632012-01-04 10:25:20 +0100672static struct kvm *kvm_create_vm(unsigned long type)
Avi Kivity6aa8b732006-12-10 02:21:36 -0800673{
Jan Kiszkad89f5ef2010-11-09 17:02:49 +0100674 struct kvm *kvm = kvm_arch_alloc_vm();
Jim Mattson91219232019-10-24 16:03:26 -0700675 int r = -ENOMEM;
676 int i;
Avi Kivity6aa8b732006-12-10 02:21:36 -0800677
Jan Kiszkad89f5ef2010-11-09 17:02:49 +0100678 if (!kvm)
679 return ERR_PTR(-ENOMEM);
680
Paolo Bonzinie9ad4ec2016-03-21 10:15:25 +0100681 spin_lock_init(&kvm->mmu_lock);
Vegard Nossumf1f10072017-02-27 14:30:07 -0800682 mmgrab(current->mm);
Paolo Bonzinie9ad4ec2016-03-21 10:15:25 +0100683 kvm->mm = current->mm;
684 kvm_eventfd_init(kvm);
685 mutex_init(&kvm->lock);
686 mutex_init(&kvm->irq_lock);
687 mutex_init(&kvm->slots_lock);
Paolo Bonzinie9ad4ec2016-03-21 10:15:25 +0100688 INIT_LIST_HEAD(&kvm->devices);
689
Jim Mattson91219232019-10-24 16:03:26 -0700690 BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
691
Paolo Bonzini8a441192019-11-04 12:16:49 +0100692 if (init_srcu_struct(&kvm->srcu))
693 goto out_err_no_srcu;
694 if (init_srcu_struct(&kvm->irq_srcu))
695 goto out_err_no_irq_srcu;
696
Paolo Bonzinie2d3fca2019-11-04 13:23:53 +0100697 refcount_set(&kvm->users_count, 1);
Jim Mattson91219232019-10-24 16:03:26 -0700698 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
699 struct kvm_memslots *slots = kvm_alloc_memslots();
700
701 if (!slots)
Jim Mattsona97b0e72019-10-25 13:34:58 +0200702 goto out_err_no_arch_destroy_vm;
Jim Mattson91219232019-10-24 16:03:26 -0700703 /* Generations must be different for each address space. */
704 slots->generation = i;
705 rcu_assign_pointer(kvm->memslots[i], slots);
706 }
707
708 for (i = 0; i < KVM_NR_BUSES; i++) {
709 rcu_assign_pointer(kvm->buses[i],
710 kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL_ACCOUNT));
711 if (!kvm->buses[i])
Jim Mattsona97b0e72019-10-25 13:34:58 +0200712 goto out_err_no_arch_destroy_vm;
Jim Mattson91219232019-10-24 16:03:26 -0700713 }
714
Carsten Ottee08b9632012-01-04 10:25:20 +0100715 r = kvm_arch_init_vm(kvm, type);
Jan Kiszkad89f5ef2010-11-09 17:02:49 +0100716 if (r)
Jim Mattsona97b0e72019-10-25 13:34:58 +0200717 goto out_err_no_arch_destroy_vm;
Alexander Graf10474ae2009-09-15 11:37:46 +0200718
719 r = hardware_enable_all();
720 if (r)
Christian Borntraeger719d93c2014-01-16 13:44:20 +0100721 goto out_err_no_disable;
Alexander Graf10474ae2009-09-15 11:37:46 +0200722
Paolo Bonzinic77dcac2014-08-06 14:24:45 +0200723#ifdef CONFIG_HAVE_KVM_IRQFD
Gleb Natapov136bdfe2009-08-24 11:54:23 +0300724 INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
Avi Kivity75858a82009-01-04 17:10:50 +0200725#endif
Avi Kivity6aa8b732006-12-10 02:21:36 -0800726
Mike Waychison74b5c5b2011-06-03 13:04:53 -0700727 r = kvm_init_mmu_notifier(kvm);
728 if (r)
Junaid Shahid1aa9b952019-11-04 20:26:00 +0100729 goto out_err_no_mmu_notifier;
730
731 r = kvm_arch_post_init_vm(kvm);
732 if (r)
Mike Waychison74b5c5b2011-06-03 13:04:53 -0700733 goto out_err;
734
Junaid Shahid0d9ce162019-01-03 17:14:28 -0800735 mutex_lock(&kvm_lock);
Rusty Russell5e58cfe2007-07-23 17:08:21 +1000736 list_add(&kvm->vm_list, &vm_list);
Junaid Shahid0d9ce162019-01-03 17:14:28 -0800737 mutex_unlock(&kvm_lock);
Jan Kiszkad89f5ef2010-11-09 17:02:49 +0100738
Peter Zijlstra2ecd9d22015-07-03 18:53:58 +0200739 preempt_notifier_inc();
740
Avi Kivityf17abe92007-02-21 19:28:04 +0200741 return kvm;
Alexander Graf10474ae2009-09-15 11:37:46 +0200742
743out_err:
Junaid Shahid1aa9b952019-11-04 20:26:00 +0100744#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
745 if (kvm->mmu_notifier.ops)
746 mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
747#endif
748out_err_no_mmu_notifier:
Alexander Graf10474ae2009-09-15 11:37:46 +0200749 hardware_disable_all();
Christian Borntraeger719d93c2014-01-16 13:44:20 +0100750out_err_no_disable:
Jim Mattsona97b0e72019-10-25 13:34:58 +0200751 kvm_arch_destroy_vm(kvm);
Jim Mattsona97b0e72019-10-25 13:34:58 +0200752out_err_no_arch_destroy_vm:
Paolo Bonzinie2d3fca2019-11-04 13:23:53 +0100753 WARN_ON_ONCE(!refcount_dec_and_test(&kvm->users_count));
Marcelo Tosattie93f8a02009-12-23 14:35:24 -0200754 for (i = 0; i < KVM_NR_BUSES; i++)
Paolo Bonzini3898da92017-08-02 17:55:54 +0200755 kfree(kvm_get_bus(kvm, i));
Paolo Bonzinif481b062015-05-17 17:30:37 +0200756 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
Paolo Bonzini3898da92017-08-02 17:55:54 +0200757 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
Paolo Bonzini8a441192019-11-04 12:16:49 +0100758 cleanup_srcu_struct(&kvm->irq_srcu);
759out_err_no_irq_srcu:
760 cleanup_srcu_struct(&kvm->srcu);
761out_err_no_srcu:
Jan Kiszkad89f5ef2010-11-09 17:02:49 +0100762 kvm_arch_free_vm(kvm);
Paolo Bonzinie9ad4ec2016-03-21 10:15:25 +0100763 mmdrop(current->mm);
Alexander Graf10474ae2009-09-15 11:37:46 +0200764 return ERR_PTR(r);
Avi Kivityf17abe92007-02-21 19:28:04 +0200765}
766
Scott Wood07f0a7b2013-04-25 14:11:23 +0000767static void kvm_destroy_devices(struct kvm *kvm)
768{
Geliang Tange6e3b5a2016-01-01 19:47:12 +0800769 struct kvm_device *dev, *tmp;
Scott Wood07f0a7b2013-04-25 14:11:23 +0000770
Christoffer Dalla28ebea2016-08-09 19:13:01 +0200771 /*
772 * We do not need to take the kvm->lock here, because nobody else
773 * has a reference to the struct kvm at this point and therefore
774 * cannot access the devices list anyhow.
775 */
Geliang Tange6e3b5a2016-01-01 19:47:12 +0800776 list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
777 list_del(&dev->vm_node);
Scott Wood07f0a7b2013-04-25 14:11:23 +0000778 dev->ops->destroy(dev);
779 }
780}
781
Avi Kivityf17abe92007-02-21 19:28:04 +0200782static void kvm_destroy_vm(struct kvm *kvm)
783{
Marcelo Tosattie93f8a02009-12-23 14:35:24 -0200784 int i;
Avi Kivity6d4e4c42007-11-21 16:41:05 +0200785 struct mm_struct *mm = kvm->mm;
786
Claudio Imbrenda286de8f2017-07-12 17:56:44 +0200787 kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
Janosch Frank536a6f82016-05-18 13:26:23 +0200788 kvm_destroy_vm_debugfs(kvm);
Sheng Yangad8ba2c2009-01-06 10:03:02 +0800789 kvm_arch_sync_events(kvm);
Junaid Shahid0d9ce162019-01-03 17:14:28 -0800790 mutex_lock(&kvm_lock);
Avi Kivity133de902007-02-12 00:54:44 -0800791 list_del(&kvm->vm_list);
Junaid Shahid0d9ce162019-01-03 17:14:28 -0800792 mutex_unlock(&kvm_lock);
Junaid Shahid1aa9b952019-11-04 20:26:00 +0100793 kvm_arch_pre_destroy_vm(kvm);
794
Avi Kivity399ec802008-11-19 13:58:46 +0200795 kvm_free_irq_routing(kvm);
Peter Xudf630b82017-03-15 16:01:17 +0800796 for (i = 0; i < KVM_NR_BUSES; i++) {
Paolo Bonzini3898da92017-08-02 17:55:54 +0200797 struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
Christian Borntraeger4a12f952017-07-07 10:51:38 +0200798
Christian Borntraeger4a12f952017-07-07 10:51:38 +0200799 if (bus)
800 kvm_io_bus_destroy(bus);
Peter Xudf630b82017-03-15 16:01:17 +0800801 kvm->buses[i] = NULL;
802 }
Avi Kivity980da6c2009-12-20 15:13:43 +0200803 kvm_coalesced_mmio_free(kvm);
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200804#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
805 mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
Gleb Natapovf00be0c2009-03-19 12:20:36 +0200806#else
Marcelo Tosatti2df72e92012-08-24 15:54:57 -0300807 kvm_arch_flush_shadow_all(kvm);
Andrea Arcangelie930bff2008-07-25 16:24:52 +0200808#endif
Zhang Xiantaod19a9cd2007-11-18 18:43:45 +0800809 kvm_arch_destroy_vm(kvm);
Scott Wood07f0a7b2013-04-25 14:11:23 +0000810 kvm_destroy_devices(kvm);
Paolo Bonzinif481b062015-05-17 17:30:37 +0200811 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
Paolo Bonzini3898da92017-08-02 17:55:54 +0200812 kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
Paolo Bonzini820b3fc2014-06-03 13:44:17 +0200813 cleanup_srcu_struct(&kvm->irq_srcu);
Jan Kiszkad89f5ef2010-11-09 17:02:49 +0100814 cleanup_srcu_struct(&kvm->srcu);
815 kvm_arch_free_vm(kvm);
Peter Zijlstra2ecd9d22015-07-03 18:53:58 +0200816 preempt_notifier_dec();
Alexander Graf10474ae2009-09-15 11:37:46 +0200817 hardware_disable_all();
Avi Kivity6d4e4c42007-11-21 16:41:05 +0200818 mmdrop(mm);
Avi Kivityf17abe92007-02-21 19:28:04 +0200819}
820
Izik Eidusd39f13b2008-03-30 16:01:25 +0300821void kvm_get_kvm(struct kvm *kvm)
822{
Elena Reshetovae3736c32017-02-20 13:06:21 +0200823 refcount_inc(&kvm->users_count);
Izik Eidusd39f13b2008-03-30 16:01:25 +0300824}
825EXPORT_SYMBOL_GPL(kvm_get_kvm);
826
827void kvm_put_kvm(struct kvm *kvm)
828{
Elena Reshetovae3736c32017-02-20 13:06:21 +0200829 if (refcount_dec_and_test(&kvm->users_count))
Izik Eidusd39f13b2008-03-30 16:01:25 +0300830 kvm_destroy_vm(kvm);
831}
832EXPORT_SYMBOL_GPL(kvm_put_kvm);
833
Sean Christopherson149487b2019-10-21 15:58:42 -0700834/*
835 * Used to put a reference that was taken on behalf of an object associated
836 * with a user-visible file descriptor, e.g. a vcpu or device, if installation
837 * of the new file descriptor fails and the reference cannot be transferred to
838 * its final owner. In such cases, the caller is still actively using @kvm and
839 * will fail miserably if the refcount unexpectedly hits zero.
840 */
841void kvm_put_kvm_no_destroy(struct kvm *kvm)
842{
843 WARN_ON(refcount_dec_and_test(&kvm->users_count));
844}
845EXPORT_SYMBOL_GPL(kvm_put_kvm_no_destroy);
Izik Eidusd39f13b2008-03-30 16:01:25 +0300846
Avi Kivityf17abe92007-02-21 19:28:04 +0200847static int kvm_vm_release(struct inode *inode, struct file *filp)
848{
849 struct kvm *kvm = filp->private_data;
850
Gregory Haskins721eecbf2009-05-20 10:30:49 -0400851 kvm_irqfd_release(kvm);
852
Izik Eidusd39f13b2008-03-30 16:01:25 +0300853 kvm_put_kvm(kvm);
Avi Kivity6aa8b732006-12-10 02:21:36 -0800854 return 0;
855}
856
Takuya Yoshikawa515a0122010-10-27 18:23:54 +0900857/*
858 * Allocation size is twice as large as the actual dirty bitmap size.
Sean Christopherson0dff0842020-02-18 13:07:29 -0800859 * See kvm_vm_ioctl_get_dirty_log() why this is needed.
Takuya Yoshikawa515a0122010-10-27 18:23:54 +0900860 */
Takuya Yoshikawaa36a57b12010-10-27 18:22:19 +0900861static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
862{
Takuya Yoshikawa515a0122010-10-27 18:23:54 +0900863 unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
Takuya Yoshikawaa36a57b12010-10-27 18:22:19 +0900864
Ben Gardonb12ce362019-02-11 11:02:49 -0800865 memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL_ACCOUNT);
Takuya Yoshikawaa36a57b12010-10-27 18:22:19 +0900866 if (!memslot->dirty_bitmap)
867 return -ENOMEM;
868
Takuya Yoshikawaa36a57b12010-10-27 18:22:19 +0900869 return 0;
870}
871
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +0800872/*
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800873 * Delete a memslot by decrementing the number of used slots and shifting all
874 * other entries in the array forward one spot.
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +0800875 */
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800876static inline void kvm_memslot_delete(struct kvm_memslots *slots,
877 struct kvm_memory_slot *memslot)
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +0800878{
Igor Mammedov063584d2014-11-13 23:00:13 +0000879 struct kvm_memory_slot *mslots = slots->memslots;
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800880 int i;
Xiao Guangrongf85e2cb2011-11-24 17:41:54 +0800881
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800882 if (WARN_ON(slots->id_to_index[memslot->id] == -1))
883 return;
Igor Mammedov0e60b072014-12-01 17:29:26 +0000884
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800885 slots->used_slots--;
886
887 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots; i++) {
Igor Mammedov7f379cf2014-12-01 17:29:24 +0000888 mslots[i] = mslots[i + 1];
889 slots->id_to_index[mslots[i].id] = i;
Igor Mammedov7f379cf2014-12-01 17:29:24 +0000890 }
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800891 mslots[i] = *memslot;
892 slots->id_to_index[memslot->id] = -1;
893}
894
895/*
896 * "Insert" a new memslot by incrementing the number of used slots. Returns
897 * the new slot's initial index into the memslots array.
898 */
899static inline int kvm_memslot_insert_back(struct kvm_memslots *slots)
900{
901 return slots->used_slots++;
902}
903
904/*
905 * Move a changed memslot backwards in the array by shifting existing slots
906 * with a higher GFN toward the front of the array. Note, the changed memslot
907 * itself is not preserved in the array, i.e. not swapped at this time, only
908 * its new index into the array is tracked. Returns the changed memslot's
909 * current index into the memslots array.
910 */
911static inline int kvm_memslot_move_backward(struct kvm_memslots *slots,
912 struct kvm_memory_slot *memslot)
913{
914 struct kvm_memory_slot *mslots = slots->memslots;
915 int i;
916
917 if (WARN_ON_ONCE(slots->id_to_index[memslot->id] == -1) ||
918 WARN_ON_ONCE(!slots->used_slots))
919 return -1;
Paolo Bonziniefbeec72014-12-27 18:01:00 +0100920
921 /*
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800922 * Move the target memslot backward in the array by shifting existing
923 * memslots with a higher GFN (than the target memslot) towards the
924 * front of the array.
Paolo Bonziniefbeec72014-12-27 18:01:00 +0100925 */
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800926 for (i = slots->id_to_index[memslot->id]; i < slots->used_slots - 1; i++) {
927 if (memslot->base_gfn > mslots[i + 1].base_gfn)
928 break;
Xiao Guangrongf85e2cb2011-11-24 17:41:54 +0800929
Sean Christopherson0577d1a2020-02-18 13:07:31 -0800930 WARN_ON_ONCE(memslot->base_gfn == mslots[i + 1].base_gfn);
931
932 /* Shift the next memslot forward one and update its index. */
933 mslots[i] = mslots[i + 1];
934 slots->id_to_index[mslots[i].id] = i;
935 }
936 return i;
937}
938
939/*
940 * Move a changed memslot forwards in the array by shifting existing slots with
941 * a lower GFN toward the back of the array. Note, the changed memslot itself
942 * is not preserved in the array, i.e. not swapped at this time, only its new
943 * index into the array is tracked. Returns the changed memslot's final index
944 * into the memslots array.
945 */
946static inline int kvm_memslot_move_forward(struct kvm_memslots *slots,
947 struct kvm_memory_slot *memslot,
948 int start)
949{
950 struct kvm_memory_slot *mslots = slots->memslots;
951 int i;
952
953 for (i = start; i > 0; i--) {
954 if (memslot->base_gfn < mslots[i - 1].base_gfn)
955 break;
956
957 WARN_ON_ONCE(memslot->base_gfn == mslots[i - 1].base_gfn);
958
959 /* Shift the next memslot back one and update its index. */
960 mslots[i] = mslots[i - 1];
961 slots->id_to_index[mslots[i].id] = i;
962 }
963 return i;
964}
965
966/*
967 * Re-sort memslots based on their GFN to account for an added, deleted, or
968 * moved memslot. Sorting memslots by GFN allows using a binary search during
969 * memslot lookup.
970 *
971 * IMPORTANT: Slots are sorted from highest GFN to lowest GFN! I.e. the entry
972 * at memslots[0] has the highest GFN.
973 *
974 * The sorting algorithm takes advantage of having initially sorted memslots
975 * and knowing the position of the changed memslot. Sorting is also optimized
976 * by not swapping the updated memslot and instead only shifting other memslots
977 * and tracking the new index for the update memslot. Only once its final
978 * index is known is the updated memslot copied into its position in the array.
979 *
980 * - When deleting a memslot, the deleted memslot simply needs to be moved to
981 * the end of the array.
982 *
983 * - When creating a memslot, the algorithm "inserts" the new memslot at the
984 * end of the array and then it forward to its correct location.
985 *
986 * - When moving a memslot, the algorithm first moves the updated memslot
987 * backward to handle the scenario where the memslot's GFN was changed to a
988 * lower value. update_memslots() then falls through and runs the same flow
989 * as creating a memslot to move the memslot forward to handle the scenario
990 * where its GFN was changed to a higher value.
991 *
992 * Note, slots are sorted from highest->lowest instead of lowest->highest for
993 * historical reasons. Originally, invalid memslots where denoted by having
994 * GFN=0, thus sorting from highest->lowest naturally sorted invalid memslots
995 * to the end of the array. The current algorithm uses dedicated logic to
996 * delete a memslot and thus does not rely on invalid memslots having GFN=0.
997 *
998 * The other historical motiviation for highest->lowest was to improve the
999 * performance of memslot lookup. KVM originally used a linear search starting
1000 * at memslots[0]. On x86, the largest memslot usually has one of the highest,
1001 * if not *the* highest, GFN, as the bulk of the guest's RAM is located in a
1002 * single memslot above the 4gb boundary. As the largest memslot is also the
1003 * most likely to be referenced, sorting it to the front of the array was
1004 * advantageous. The current binary search starts from the middle of the array
1005 * and uses an LRU pointer to improve performance for all memslots and GFNs.
1006 */
1007static void update_memslots(struct kvm_memslots *slots,
1008 struct kvm_memory_slot *memslot,
1009 enum kvm_mr_change change)
1010{
1011 int i;
1012
1013 if (change == KVM_MR_DELETE) {
1014 kvm_memslot_delete(slots, memslot);
1015 } else {
1016 if (change == KVM_MR_CREATE)
1017 i = kvm_memslot_insert_back(slots);
1018 else
1019 i = kvm_memslot_move_backward(slots, memslot);
1020 i = kvm_memslot_move_forward(slots, memslot, i);
1021
1022 /*
1023 * Copy the memslot to its new position in memslots and update
1024 * its index accordingly.
1025 */
1026 slots->memslots[i] = *memslot;
1027 slots->id_to_index[memslot->id] = i;
1028 }
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +08001029}
1030
Paolo Bonzini09170a42015-05-18 13:59:39 +02001031static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
Xiao Guangronga50d64d2012-08-21 10:58:13 +08001032{
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001033 u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
1034
Christoffer Dall0f8a4de2014-08-26 14:00:37 +02001035#ifdef __KVM_HAVE_READONLY_MEM
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001036 valid_flags |= KVM_MEM_READONLY;
1037#endif
1038
1039 if (mem->flags & ~valid_flags)
Xiao Guangronga50d64d2012-08-21 10:58:13 +08001040 return -EINVAL;
1041
1042 return 0;
1043}
1044
Gleb Natapov7ec4fb42012-12-24 17:49:30 +02001045static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
Paolo Bonzinif481b062015-05-17 17:30:37 +02001046 int as_id, struct kvm_memslots *slots)
Gleb Natapov7ec4fb42012-12-24 17:49:30 +02001047{
Paolo Bonzinif481b062015-05-17 17:30:37 +02001048 struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
Sean Christopherson361209e2019-02-05 13:01:14 -08001049 u64 gen = old_memslots->generation;
Gleb Natapov7ec4fb42012-12-24 17:49:30 +02001050
Sean Christopherson361209e2019-02-05 13:01:14 -08001051 WARN_ON(gen & KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS);
1052 slots->generation = gen | KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
David Matlackee3d1572014-08-18 15:46:06 -07001053
Paolo Bonzinif481b062015-05-17 17:30:37 +02001054 rcu_assign_pointer(kvm->memslots[as_id], slots);
Gleb Natapov7ec4fb42012-12-24 17:49:30 +02001055 synchronize_srcu_expedited(&kvm->srcu);
Takuya Yoshikawae59dbe02013-07-04 13:40:29 +09001056
David Matlackee3d1572014-08-18 15:46:06 -07001057 /*
Sean Christopherson361209e2019-02-05 13:01:14 -08001058 * Increment the new memslot generation a second time, dropping the
Miaohe Lin00116792019-12-11 14:26:23 +08001059 * update in-progress flag and incrementing the generation based on
Sean Christopherson361209e2019-02-05 13:01:14 -08001060 * the number of address spaces. This provides a unique and easily
1061 * identifiable generation number while the memslots are in flux.
1062 */
1063 gen = slots->generation & ~KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS;
1064
1065 /*
Paolo Bonzini4bd518f2017-02-03 20:44:51 -08001066 * Generations must be unique even across address spaces. We do not need
1067 * a global counter for that, instead the generation space is evenly split
1068 * across address spaces. For example, with two address spaces, address
Sean Christopherson164bf7e2019-02-05 13:01:18 -08001069 * space 0 will use generations 0, 2, 4, ... while address space 1 will
1070 * use generations 1, 3, 5, ...
David Matlackee3d1572014-08-18 15:46:06 -07001071 */
Sean Christopherson164bf7e2019-02-05 13:01:18 -08001072 gen += KVM_ADDRESS_SPACE_NUM;
David Matlackee3d1572014-08-18 15:46:06 -07001073
Sean Christopherson15248252019-02-05 12:54:17 -08001074 kvm_arch_memslots_updated(kvm, gen);
1075
1076 slots->generation = gen;
Takuya Yoshikawae59dbe02013-07-04 13:40:29 +09001077
1078 return old_memslots;
Gleb Natapov7ec4fb42012-12-24 17:49:30 +02001079}
1080
Sean Christophersoncf47f502020-02-18 13:07:23 -08001081static int kvm_set_memslot(struct kvm *kvm,
1082 const struct kvm_userspace_memory_region *mem,
Sean Christopherson9d4c1972020-02-18 13:07:24 -08001083 struct kvm_memory_slot *old,
Sean Christophersoncf47f502020-02-18 13:07:23 -08001084 struct kvm_memory_slot *new, int as_id,
1085 enum kvm_mr_change change)
1086{
1087 struct kvm_memory_slot *slot;
1088 struct kvm_memslots *slots;
1089 int r;
1090
1091 slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL_ACCOUNT);
1092 if (!slots)
1093 return -ENOMEM;
1094 memcpy(slots, __kvm_memslots(kvm, as_id), sizeof(struct kvm_memslots));
1095
1096 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE) {
1097 /*
1098 * Note, the INVALID flag needs to be in the appropriate entry
1099 * in the freshly allocated memslots, not in @old or @new.
1100 */
1101 slot = id_to_memslot(slots, old->id);
1102 slot->flags |= KVM_MEMSLOT_INVALID;
1103
1104 /*
1105 * We can re-use the old memslots, the only difference from the
1106 * newly installed memslots is the invalid flag, which will get
1107 * dropped by update_memslots anyway. We'll also revert to the
1108 * old memslots if preparing the new memory region fails.
1109 */
1110 slots = install_new_memslots(kvm, as_id, slots);
1111
1112 /* From this point no new shadow pages pointing to a deleted,
1113 * or moved, memslot will be created.
1114 *
1115 * validation of sp->gfn happens in:
1116 * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
1117 * - kvm_is_visible_gfn (mmu_check_root)
1118 */
1119 kvm_arch_flush_shadow_memslot(kvm, slot);
1120 }
1121
1122 r = kvm_arch_prepare_memory_region(kvm, new, mem, change);
1123 if (r)
1124 goto out_slots;
1125
1126 update_memslots(slots, new, change);
1127 slots = install_new_memslots(kvm, as_id, slots);
1128
1129 kvm_arch_commit_memory_region(kvm, mem, old, new, change);
1130
1131 kvfree(slots);
1132 return 0;
1133
1134out_slots:
1135 if (change == KVM_MR_DELETE || change == KVM_MR_MOVE)
1136 slots = install_new_memslots(kvm, as_id, slots);
1137 kvfree(slots);
1138 return r;
1139}
1140
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001141static int kvm_delete_memslot(struct kvm *kvm,
1142 const struct kvm_userspace_memory_region *mem,
1143 struct kvm_memory_slot *old, int as_id)
1144{
1145 struct kvm_memory_slot new;
1146 int r;
1147
1148 if (!old->npages)
1149 return -EINVAL;
1150
1151 memset(&new, 0, sizeof(new));
1152 new.id = old->id;
1153
1154 r = kvm_set_memslot(kvm, mem, old, &new, as_id, KVM_MR_DELETE);
1155 if (r)
1156 return r;
1157
Sean Christophersone96c81e2020-02-18 13:07:27 -08001158 kvm_free_memslot(kvm, old);
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001159 return 0;
1160}
1161
Avi Kivity6aa8b732006-12-10 02:21:36 -08001162/*
Avi Kivity6aa8b732006-12-10 02:21:36 -08001163 * Allocate some memory and give it an address in the guest physical address
1164 * space.
1165 *
1166 * Discontiguous memory is allowed, mostly for framebuffers.
Sheng Yangf78e0e22007-10-29 09:40:42 +08001167 *
Dominik Dingel02d5d552014-10-27 16:22:56 +01001168 * Must be called holding kvm->slots_lock for write.
Avi Kivity6aa8b732006-12-10 02:21:36 -08001169 */
Sheng Yangf78e0e22007-10-29 09:40:42 +08001170int __kvm_set_memory_region(struct kvm *kvm,
Paolo Bonzini09170a42015-05-18 13:59:39 +02001171 const struct kvm_userspace_memory_region *mem)
Avi Kivity6aa8b732006-12-10 02:21:36 -08001172{
Avi Kivity6aa8b732006-12-10 02:21:36 -08001173 struct kvm_memory_slot old, new;
Sean Christopherson163da372020-02-18 13:07:28 -08001174 struct kvm_memory_slot *tmp;
Takuya Yoshikawaf64c0392013-01-29 11:00:07 +09001175 enum kvm_mr_change change;
Sean Christopherson163da372020-02-18 13:07:28 -08001176 int as_id, id;
1177 int r;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001178
Xiao Guangronga50d64d2012-08-21 10:58:13 +08001179 r = check_memory_region_flags(mem);
1180 if (r)
Sean Christopherson71a4c302020-02-18 13:07:22 -08001181 return r;
Xiao Guangronga50d64d2012-08-21 10:58:13 +08001182
Paolo Bonzinif481b062015-05-17 17:30:37 +02001183 as_id = mem->slot >> 16;
1184 id = (u16)mem->slot;
1185
Avi Kivity6aa8b732006-12-10 02:21:36 -08001186 /* General sanity checks */
1187 if (mem->memory_size & (PAGE_SIZE - 1))
Sean Christopherson71a4c302020-02-18 13:07:22 -08001188 return -EINVAL;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001189 if (mem->guest_phys_addr & (PAGE_SIZE - 1))
Sean Christopherson71a4c302020-02-18 13:07:22 -08001190 return -EINVAL;
Takuya Yoshikawafa3d3152011-05-07 16:35:38 +09001191 /* We can read the guest memory with __xxx_user() later on. */
Paolo Bonzinif481b062015-05-17 17:30:37 +02001192 if ((id < KVM_USER_MEM_SLOTS) &&
Takuya Yoshikawafa3d3152011-05-07 16:35:38 +09001193 ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
Linus Torvalds96d4f262019-01-03 18:57:57 -08001194 !access_ok((void __user *)(unsigned long)mem->userspace_addr,
Heiko Carstens9e3bb6b2011-05-24 07:51:27 +02001195 mem->memory_size)))
Sean Christopherson71a4c302020-02-18 13:07:22 -08001196 return -EINVAL;
Paolo Bonzinif481b062015-05-17 17:30:37 +02001197 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
Sean Christopherson71a4c302020-02-18 13:07:22 -08001198 return -EINVAL;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001199 if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
Sean Christopherson71a4c302020-02-18 13:07:22 -08001200 return -EINVAL;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001201
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001202 /*
1203 * Make a full copy of the old memslot, the pointer will become stale
1204 * when the memslots are re-sorted by update_memslots(), and the old
1205 * memslot needs to be referenced after calling update_memslots(), e.g.
Sean Christopherson0dff0842020-02-18 13:07:29 -08001206 * to free its resources and for arch specific behavior.
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001207 */
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001208 tmp = id_to_memslot(__kvm_memslots(kvm, as_id), id);
1209 if (tmp) {
1210 old = *tmp;
1211 tmp = NULL;
1212 } else {
1213 memset(&old, 0, sizeof(old));
1214 old.id = id;
1215 }
Sean Christopherson163da372020-02-18 13:07:28 -08001216
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001217 if (!mem->memory_size)
1218 return kvm_delete_memslot(kvm, mem, &old, as_id);
1219
Paolo Bonzinif481b062015-05-17 17:30:37 +02001220 new.id = id;
Sean Christopherson163da372020-02-18 13:07:28 -08001221 new.base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
1222 new.npages = mem->memory_size >> PAGE_SHIFT;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001223 new.flags = mem->flags;
Sean Christopherson414de7ab2020-02-18 13:07:20 -08001224 new.userspace_addr = mem->userspace_addr;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001225
Sean Christopherson163da372020-02-18 13:07:28 -08001226 if (new.npages > KVM_MEM_MAX_NR_PAGES)
1227 return -EINVAL;
1228
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001229 if (!old.npages) {
1230 change = KVM_MR_CREATE;
Sean Christopherson163da372020-02-18 13:07:28 -08001231 new.dirty_bitmap = NULL;
1232 memset(&new.arch, 0, sizeof(new.arch));
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001233 } else { /* Modify an existing slot. */
1234 if ((new.userspace_addr != old.userspace_addr) ||
Sean Christopherson163da372020-02-18 13:07:28 -08001235 (new.npages != old.npages) ||
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001236 ((new.flags ^ old.flags) & KVM_MEM_READONLY))
Sean Christopherson71a4c302020-02-18 13:07:22 -08001237 return -EINVAL;
Paolo Bonzini09170a42015-05-18 13:59:39 +02001238
Sean Christopherson163da372020-02-18 13:07:28 -08001239 if (new.base_gfn != old.base_gfn)
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001240 change = KVM_MR_MOVE;
1241 else if (new.flags != old.flags)
1242 change = KVM_MR_FLAGS_ONLY;
1243 else /* Nothing to change. */
1244 return 0;
Sean Christopherson163da372020-02-18 13:07:28 -08001245
1246 /* Copy dirty_bitmap and arch from the current memslot. */
1247 new.dirty_bitmap = old.dirty_bitmap;
1248 memcpy(&new.arch, &old.arch, sizeof(new.arch));
Paolo Bonzini09170a42015-05-18 13:59:39 +02001249 }
Avi Kivity6aa8b732006-12-10 02:21:36 -08001250
Takuya Yoshikawaf64c0392013-01-29 11:00:07 +09001251 if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
Takuya Yoshikawa0a706be2013-01-11 18:26:55 +09001252 /* Check for overlaps */
Sean Christopherson163da372020-02-18 13:07:28 -08001253 kvm_for_each_memslot(tmp, __kvm_memslots(kvm, as_id)) {
1254 if (tmp->id == id)
Takuya Yoshikawa0a706be2013-01-11 18:26:55 +09001255 continue;
Sean Christopherson163da372020-02-18 13:07:28 -08001256 if (!((new.base_gfn + new.npages <= tmp->base_gfn) ||
1257 (new.base_gfn >= tmp->base_gfn + tmp->npages)))
Sean Christopherson71a4c302020-02-18 13:07:22 -08001258 return -EEXIST;
Takuya Yoshikawa0a706be2013-01-11 18:26:55 +09001259 }
Avi Kivity6aa8b732006-12-10 02:21:36 -08001260 }
Avi Kivity6aa8b732006-12-10 02:21:36 -08001261
Sean Christopherson414de7ab2020-02-18 13:07:20 -08001262 /* Allocate/free page dirty bitmap as needed */
Avi Kivity6aa8b732006-12-10 02:21:36 -08001263 if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
Al Viro8b6d44c2007-02-09 16:38:40 +00001264 new.dirty_bitmap = NULL;
Sean Christopherson414de7ab2020-02-18 13:07:20 -08001265 else if (!new.dirty_bitmap) {
Sean Christopherson71a4c302020-02-18 13:07:22 -08001266 r = kvm_create_dirty_bitmap(&new);
1267 if (r)
1268 return r;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001269 }
1270
Sean Christophersoncf47f502020-02-18 13:07:23 -08001271 r = kvm_set_memslot(kvm, mem, &old, &new, as_id, change);
1272 if (r)
1273 goto out_bitmap;
Zhang Xiantao3ad82a72007-11-20 13:11:38 +08001274
Sean Christopherson5c0b4f32020-02-18 13:07:26 -08001275 if (old.dirty_bitmap && !new.dirty_bitmap)
1276 kvm_destroy_dirty_bitmap(&old);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001277 return 0;
1278
Sean Christophersonbd0e96f2020-02-18 13:07:21 -08001279out_bitmap:
1280 if (new.dirty_bitmap && !old.dirty_bitmap)
1281 kvm_destroy_dirty_bitmap(&new);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001282 return r;
Izik Eidus210c7c42007-10-24 23:52:57 +02001283}
Sheng Yangf78e0e22007-10-29 09:40:42 +08001284EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
1285
1286int kvm_set_memory_region(struct kvm *kvm,
Paolo Bonzini09170a42015-05-18 13:59:39 +02001287 const struct kvm_userspace_memory_region *mem)
Sheng Yangf78e0e22007-10-29 09:40:42 +08001288{
1289 int r;
1290
Marcelo Tosatti79fac952009-12-23 14:35:26 -02001291 mutex_lock(&kvm->slots_lock);
Takuya Yoshikawa47ae31e2013-02-27 19:43:00 +09001292 r = __kvm_set_memory_region(kvm, mem);
Marcelo Tosatti79fac952009-12-23 14:35:26 -02001293 mutex_unlock(&kvm->slots_lock);
Sheng Yangf78e0e22007-10-29 09:40:42 +08001294 return r;
1295}
Izik Eidus210c7c42007-10-24 23:52:57 +02001296EXPORT_SYMBOL_GPL(kvm_set_memory_region);
1297
Stephen Hemminger79408762013-12-29 12:12:29 -08001298static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
1299 struct kvm_userspace_memory_region *mem)
Izik Eidus210c7c42007-10-24 23:52:57 +02001300{
Paolo Bonzinif481b062015-05-17 17:30:37 +02001301 if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
Izik Eiduse0d62c72007-10-24 23:57:46 +02001302 return -EINVAL;
Paolo Bonzini09170a42015-05-18 13:59:39 +02001303
Takuya Yoshikawa47ae31e2013-02-27 19:43:00 +09001304 return kvm_set_memory_region(kvm, mem);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001305}
1306
Sean Christopherson0dff0842020-02-18 13:07:29 -08001307#ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
Sean Christopherson2a49f612020-02-18 13:07:30 -08001308/**
1309 * kvm_get_dirty_log - get a snapshot of dirty pages
1310 * @kvm: pointer to kvm instance
1311 * @log: slot id and address to which we copy the log
1312 * @is_dirty: set to '1' if any dirty pages were found
1313 * @memslot: set to the associated memslot, always valid on success
1314 */
1315int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1316 int *is_dirty, struct kvm_memory_slot **memslot)
Avi Kivity6aa8b732006-12-10 02:21:36 -08001317{
Paolo Bonzini9f6b8022015-05-17 16:20:07 +02001318 struct kvm_memslots *slots;
Markus Elfring843574a2017-01-22 17:41:07 +01001319 int i, as_id, id;
Takuya Yoshikawa87bf6e72010-04-12 19:35:35 +09001320 unsigned long n;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001321 unsigned long any = 0;
1322
Sean Christopherson2a49f612020-02-18 13:07:30 -08001323 *memslot = NULL;
1324 *is_dirty = 0;
1325
Paolo Bonzinif481b062015-05-17 17:30:37 +02001326 as_id = log->slot >> 16;
1327 id = (u16)log->slot;
1328 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
Markus Elfring843574a2017-01-22 17:41:07 +01001329 return -EINVAL;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001330
Paolo Bonzinif481b062015-05-17 17:30:37 +02001331 slots = __kvm_memslots(kvm, as_id);
Sean Christopherson2a49f612020-02-18 13:07:30 -08001332 *memslot = id_to_memslot(slots, id);
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001333 if (!(*memslot) || !(*memslot)->dirty_bitmap)
Markus Elfring843574a2017-01-22 17:41:07 +01001334 return -ENOENT;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001335
Sean Christopherson2a49f612020-02-18 13:07:30 -08001336 kvm_arch_sync_dirty_log(kvm, *memslot);
1337
1338 n = kvm_dirty_bitmap_bytes(*memslot);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001339
Uri Lublincd1a4a92007-02-22 16:43:09 +02001340 for (i = 0; !any && i < n/sizeof(long); ++i)
Sean Christopherson2a49f612020-02-18 13:07:30 -08001341 any = (*memslot)->dirty_bitmap[i];
Avi Kivity6aa8b732006-12-10 02:21:36 -08001342
Sean Christopherson2a49f612020-02-18 13:07:30 -08001343 if (copy_to_user(log->dirty_bitmap, (*memslot)->dirty_bitmap, n))
Markus Elfring843574a2017-01-22 17:41:07 +01001344 return -EFAULT;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001345
Zhang Xiantao5bb064d2007-11-18 20:29:43 +08001346 if (any)
1347 *is_dirty = 1;
Markus Elfring843574a2017-01-22 17:41:07 +01001348 return 0;
Avi Kivity6aa8b732006-12-10 02:21:36 -08001349}
Aneesh Kumar K.V2ba9f0d2013-10-07 22:17:59 +05301350EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001351
Sean Christopherson0dff0842020-02-18 13:07:29 -08001352#else /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
Mario Smarduchba0513b2015-01-15 15:58:53 -08001353/**
Jiang Biaob8b00222019-04-23 19:40:30 +08001354 * kvm_get_dirty_log_protect - get a snapshot of dirty pages
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001355 * and reenable dirty page tracking for the corresponding pages.
Mario Smarduchba0513b2015-01-15 15:58:53 -08001356 * @kvm: pointer to kvm instance
1357 * @log: slot id and address to which we copy the log
Mario Smarduchba0513b2015-01-15 15:58:53 -08001358 *
1359 * We need to keep it in mind that VCPU threads can write to the bitmap
1360 * concurrently. So, to avoid losing track of dirty pages we keep the
1361 * following order:
1362 *
1363 * 1. Take a snapshot of the bit and clear it if needed.
1364 * 2. Write protect the corresponding page.
1365 * 3. Copy the snapshot to the userspace.
1366 * 4. Upon return caller flushes TLB's if needed.
1367 *
1368 * Between 2 and 4, the guest may write to the page using the remaining TLB
1369 * entry. This is not a problem because the page is reported dirty using
1370 * the snapshot taken before and step 4 ensures that writes done after
1371 * exiting to userspace will be logged for the next call.
1372 *
1373 */
Sean Christopherson0dff0842020-02-18 13:07:29 -08001374static int kvm_get_dirty_log_protect(struct kvm *kvm, struct kvm_dirty_log *log)
Mario Smarduchba0513b2015-01-15 15:58:53 -08001375{
Paolo Bonzini9f6b8022015-05-17 16:20:07 +02001376 struct kvm_memslots *slots;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001377 struct kvm_memory_slot *memslot;
Markus Elfring58d6db32017-01-22 17:30:16 +01001378 int i, as_id, id;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001379 unsigned long n;
1380 unsigned long *dirty_bitmap;
1381 unsigned long *dirty_bitmap_buffer;
Sean Christopherson0dff0842020-02-18 13:07:29 -08001382 bool flush;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001383
Paolo Bonzinif481b062015-05-17 17:30:37 +02001384 as_id = log->slot >> 16;
1385 id = (u16)log->slot;
1386 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
Markus Elfring58d6db32017-01-22 17:30:16 +01001387 return -EINVAL;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001388
Paolo Bonzinif481b062015-05-17 17:30:37 +02001389 slots = __kvm_memslots(kvm, as_id);
1390 memslot = id_to_memslot(slots, id);
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001391 if (!memslot || !memslot->dirty_bitmap)
1392 return -ENOENT;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001393
1394 dirty_bitmap = memslot->dirty_bitmap;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001395
Sean Christopherson0dff0842020-02-18 13:07:29 -08001396 kvm_arch_sync_dirty_log(kvm, memslot);
1397
Mario Smarduchba0513b2015-01-15 15:58:53 -08001398 n = kvm_dirty_bitmap_bytes(memslot);
Sean Christopherson0dff0842020-02-18 13:07:29 -08001399 flush = false;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001400 if (kvm->manual_dirty_log_protect) {
1401 /*
1402 * Unlike kvm_get_dirty_log, we always return false in *flush,
1403 * because no flush is needed until KVM_CLEAR_DIRTY_LOG. There
1404 * is some code duplication between this function and
1405 * kvm_get_dirty_log, but hopefully all architecture
1406 * transition to kvm_get_dirty_log_protect and kvm_get_dirty_log
1407 * can be eliminated.
1408 */
1409 dirty_bitmap_buffer = dirty_bitmap;
1410 } else {
1411 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1412 memset(dirty_bitmap_buffer, 0, n);
Mario Smarduchba0513b2015-01-15 15:58:53 -08001413
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001414 spin_lock(&kvm->mmu_lock);
1415 for (i = 0; i < n / sizeof(long); i++) {
1416 unsigned long mask;
1417 gfn_t offset;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001418
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001419 if (!dirty_bitmap[i])
1420 continue;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001421
Sean Christopherson0dff0842020-02-18 13:07:29 -08001422 flush = true;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001423 mask = xchg(&dirty_bitmap[i], 0);
1424 dirty_bitmap_buffer[i] = mask;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001425
Lan Tianyua67794c2019-02-02 17:20:27 +08001426 offset = i * BITS_PER_LONG;
1427 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1428 offset, mask);
Takuya Yoshikawa58d29302015-03-17 16:19:58 +09001429 }
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001430 spin_unlock(&kvm->mmu_lock);
Mario Smarduchba0513b2015-01-15 15:58:53 -08001431 }
1432
Sean Christopherson0dff0842020-02-18 13:07:29 -08001433 if (flush)
1434 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1435
Mario Smarduchba0513b2015-01-15 15:58:53 -08001436 if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
Markus Elfring58d6db32017-01-22 17:30:16 +01001437 return -EFAULT;
1438 return 0;
Mario Smarduchba0513b2015-01-15 15:58:53 -08001439}
Sean Christopherson0dff0842020-02-18 13:07:29 -08001440
1441
1442/**
1443 * kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
1444 * @kvm: kvm instance
1445 * @log: slot id and address to which we copy the log
1446 *
1447 * Steps 1-4 below provide general overview of dirty page logging. See
1448 * kvm_get_dirty_log_protect() function description for additional details.
1449 *
1450 * We call kvm_get_dirty_log_protect() to handle steps 1-3, upon return we
1451 * always flush the TLB (step 4) even if previous step failed and the dirty
1452 * bitmap may be corrupt. Regardless of previous outcome the KVM logging API
1453 * does not preclude user space subsequent dirty log read. Flushing TLB ensures
1454 * writes will be marked dirty for next log read.
1455 *
1456 * 1. Take a snapshot of the bit and clear it if needed.
1457 * 2. Write protect the corresponding page.
1458 * 3. Copy the snapshot to the userspace.
1459 * 4. Flush TLB's if needed.
1460 */
1461static int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm,
1462 struct kvm_dirty_log *log)
1463{
1464 int r;
1465
1466 mutex_lock(&kvm->slots_lock);
1467
1468 r = kvm_get_dirty_log_protect(kvm, log);
1469
1470 mutex_unlock(&kvm->slots_lock);
1471 return r;
1472}
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001473
1474/**
1475 * kvm_clear_dirty_log_protect - clear dirty bits in the bitmap
1476 * and reenable dirty page tracking for the corresponding pages.
1477 * @kvm: pointer to kvm instance
1478 * @log: slot id and address from which to fetch the bitmap of dirty pages
1479 */
Sean Christopherson0dff0842020-02-18 13:07:29 -08001480static int kvm_clear_dirty_log_protect(struct kvm *kvm,
1481 struct kvm_clear_dirty_log *log)
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001482{
1483 struct kvm_memslots *slots;
1484 struct kvm_memory_slot *memslot;
Tomas Bortoli98938aa2019-01-02 18:29:37 +01001485 int as_id, id;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001486 gfn_t offset;
Tomas Bortoli98938aa2019-01-02 18:29:37 +01001487 unsigned long i, n;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001488 unsigned long *dirty_bitmap;
1489 unsigned long *dirty_bitmap_buffer;
Sean Christopherson0dff0842020-02-18 13:07:29 -08001490 bool flush;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001491
1492 as_id = log->slot >> 16;
1493 id = (u16)log->slot;
1494 if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
1495 return -EINVAL;
1496
Paolo Bonzini76d58e02019-04-17 15:28:44 +02001497 if (log->first_page & 63)
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001498 return -EINVAL;
1499
1500 slots = __kvm_memslots(kvm, as_id);
1501 memslot = id_to_memslot(slots, id);
Sean Christopherson0577d1a2020-02-18 13:07:31 -08001502 if (!memslot || !memslot->dirty_bitmap)
1503 return -ENOENT;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001504
1505 dirty_bitmap = memslot->dirty_bitmap;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001506
Peter Xu4ddc9202019-05-08 17:15:45 +08001507 n = ALIGN(log->num_pages, BITS_PER_LONG) / 8;
Tomas Bortoli98938aa2019-01-02 18:29:37 +01001508
1509 if (log->first_page > memslot->npages ||
Paolo Bonzini76d58e02019-04-17 15:28:44 +02001510 log->num_pages > memslot->npages - log->first_page ||
1511 (log->num_pages < memslot->npages - log->first_page && (log->num_pages & 63)))
1512 return -EINVAL;
Tomas Bortoli98938aa2019-01-02 18:29:37 +01001513
Sean Christopherson0dff0842020-02-18 13:07:29 -08001514 kvm_arch_sync_dirty_log(kvm, memslot);
1515
1516 flush = false;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001517 dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
1518 if (copy_from_user(dirty_bitmap_buffer, log->dirty_bitmap, n))
1519 return -EFAULT;
1520
1521 spin_lock(&kvm->mmu_lock);
Peter Xu53eac7a2019-05-08 17:15:46 +08001522 for (offset = log->first_page, i = offset / BITS_PER_LONG,
1523 n = DIV_ROUND_UP(log->num_pages, BITS_PER_LONG); n--;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001524 i++, offset += BITS_PER_LONG) {
1525 unsigned long mask = *dirty_bitmap_buffer++;
1526 atomic_long_t *p = (atomic_long_t *) &dirty_bitmap[i];
1527 if (!mask)
1528 continue;
1529
1530 mask &= atomic_long_fetch_andnot(mask, p);
1531
1532 /*
1533 * mask contains the bits that really have been cleared. This
1534 * never includes any bits beyond the length of the memslot (if
1535 * the length is not aligned to 64 pages), therefore it is not
1536 * a problem if userspace sets them in log->dirty_bitmap.
1537 */
1538 if (mask) {
Sean Christopherson0dff0842020-02-18 13:07:29 -08001539 flush = true;
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001540 kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
1541 offset, mask);
1542 }
1543 }
1544 spin_unlock(&kvm->mmu_lock);
1545
Sean Christopherson0dff0842020-02-18 13:07:29 -08001546 if (flush)
1547 kvm_arch_flush_remote_tlbs_memslot(kvm, memslot);
1548
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02001549 return 0;
1550}
Sean Christopherson0dff0842020-02-18 13:07:29 -08001551
1552static int kvm_vm_ioctl_clear_dirty_log(struct kvm *kvm,
1553 struct kvm_clear_dirty_log *log)
1554{
1555 int r;
1556
1557 mutex_lock(&kvm->slots_lock);
1558
1559 r = kvm_clear_dirty_log_protect(kvm, log);
1560
1561 mutex_unlock(&kvm->slots_lock);
1562 return r;
1563}
1564#endif /* CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
Mario Smarduchba0513b2015-01-15 15:58:53 -08001565
Takuya Yoshikawadb3fe4e2012-02-08 13:02:18 +09001566bool kvm_largepages_enabled(void)
1567{
1568 return largepages_enabled;
1569}
1570
Marcelo Tosatti54dee992009-06-11 12:07:44 -03001571void kvm_disable_largepages(void)
1572{
1573 largepages_enabled = false;
1574}
1575EXPORT_SYMBOL_GPL(kvm_disable_largepages);
1576
Gleb Natapov49c77542010-10-18 15:22:23 +02001577struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
1578{
1579 return __gfn_to_memslot(kvm_memslots(kvm), gfn);
1580}
Avi Kivitya1f4d3952010-06-21 11:44:20 +03001581EXPORT_SYMBOL_GPL(gfn_to_memslot);
Avi Kivity6aa8b732006-12-10 02:21:36 -08001582
Paolo Bonzini8e734852015-05-17 13:58:53 +02001583struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
1584{
1585 return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
1586}
1587
Yaowei Bai33e94152015-11-14 11:21:06 +08001588bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
Izik Eiduse0d62c72007-10-24 23:57:46 +02001589{
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +08001590 struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
Izik Eiduse0d62c72007-10-24 23:57:46 +02001591
Alex Williamsonbbacc0c2012-12-10 10:33:09 -07001592 if (!memslot || memslot->id >= KVM_USER_MEM_SLOTS ||
Xiao Guangrongbf3e05b2011-11-24 17:40:57 +08001593 memslot->flags & KVM_MEMSLOT_INVALID)
Yaowei Bai33e94152015-11-14 11:21:06 +08001594 return false;
Izik Eiduse0d62c72007-10-24 23:57:46 +02001595
Yaowei Bai33e94152015-11-14 11:21:06 +08001596 return true;
Izik Eiduse0d62c72007-10-24 23:57:46 +02001597}
1598EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
1599
Sean Christophersonf9b84e12020-01-08 12:24:37 -08001600unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
Joerg Roedel8f0b1ab2010-01-28 12:37:56 +01001601{
1602 struct vm_area_struct *vma;
1603 unsigned long addr, size;
1604
1605 size = PAGE_SIZE;
1606
Sean Christopherson42cde482020-01-08 12:24:38 -08001607 addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
Joerg Roedel8f0b1ab2010-01-28 12:37:56 +01001608 if (kvm_is_error_hva(addr))
1609 return PAGE_SIZE;
1610
1611 down_read(&current->mm->mmap_sem);
1612 vma = find_vma(current->mm, addr);
1613 if (!vma)
1614 goto out;
1615
1616 size = vma_kernel_pagesize(vma);
1617
1618out:
1619 up_read(&current->mm->mmap_sem);
1620
1621 return size;
1622}
1623
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001624static bool memslot_is_readonly(struct kvm_memory_slot *slot)
1625{
1626 return slot->flags & KVM_MEM_READONLY;
1627}
1628
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001629static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1630 gfn_t *nr_pages, bool write)
Izik Eidus539cb662007-11-11 22:05:04 +02001631{
Marcelo Tosattibc6678a2009-12-23 14:35:21 -02001632 if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
Xiao Guangrongca3a4902012-08-21 11:01:50 +08001633 return KVM_HVA_ERR_BAD;
Xiao Guangrong48987782010-08-22 19:11:43 +08001634
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001635 if (memslot_is_readonly(slot) && write)
1636 return KVM_HVA_ERR_RO_BAD;
Xiao Guangrong48987782010-08-22 19:11:43 +08001637
1638 if (nr_pages)
1639 *nr_pages = slot->npages - (gfn - slot->base_gfn);
1640
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001641 return __gfn_to_hva_memslot(slot, gfn);
Izik Eidus539cb662007-11-11 22:05:04 +02001642}
Xiao Guangrong48987782010-08-22 19:11:43 +08001643
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001644static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
1645 gfn_t *nr_pages)
1646{
1647 return __gfn_to_hva_many(slot, gfn, nr_pages, true);
1648}
1649
1650unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
Stephen Hemminger79408762013-12-29 12:12:29 -08001651 gfn_t gfn)
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001652{
1653 return gfn_to_hva_many(slot, gfn, NULL);
1654}
1655EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
1656
Xiao Guangrong48987782010-08-22 19:11:43 +08001657unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
1658{
Gleb Natapov49c77542010-10-18 15:22:23 +02001659 return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
Xiao Guangrong48987782010-08-22 19:11:43 +08001660}
Sheng Yang0d150292008-04-25 21:44:50 +08001661EXPORT_SYMBOL_GPL(gfn_to_hva);
Izik Eidus539cb662007-11-11 22:05:04 +02001662
Paolo Bonzini8e734852015-05-17 13:58:53 +02001663unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
1664{
1665 return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
1666}
1667EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
1668
Xiao Guangrong86ab8cf2012-08-21 10:59:53 +08001669/*
Wei Yang970c0d42018-10-09 10:41:15 +08001670 * Return the hva of a @gfn and the R/W attribute if possible.
1671 *
1672 * @slot: the kvm_memory_slot which contains @gfn
1673 * @gfn: the gfn to be translated
1674 * @writable: used to return the read/write attribute of the @slot if the hva
1675 * is valid and @writable is not NULL
Xiao Guangrong86ab8cf2012-08-21 10:59:53 +08001676 */
Christoffer Dall64d83122014-08-19 12:15:00 +02001677unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
1678 gfn_t gfn, bool *writable)
Gleb Natapov80300892010-10-19 18:13:41 +02001679{
Gleb Natapova2ac07f2013-10-01 19:58:36 +03001680 unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
1681
1682 if (!kvm_is_error_hva(hva) && writable)
Paolo Bonziniba6a3542013-09-09 13:52:33 +02001683 *writable = !memslot_is_readonly(slot);
1684
Gleb Natapova2ac07f2013-10-01 19:58:36 +03001685 return hva;
Xiao Guangrong86ab8cf2012-08-21 10:59:53 +08001686}
1687
Christoffer Dall64d83122014-08-19 12:15:00 +02001688unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
1689{
1690 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
1691
1692 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1693}
1694
Paolo Bonzini8e734852015-05-17 13:58:53 +02001695unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
1696{
1697 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1698
1699 return gfn_to_hva_memslot_prot(slot, gfn, writable);
1700}
1701
Huang Yingfafc3db2011-01-30 11:15:49 +08001702static inline int check_user_page_hwpoison(unsigned long addr)
1703{
Lorenzo Stoakes0d731752016-10-24 10:57:25 +01001704 int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
Huang Yingfafc3db2011-01-30 11:15:49 +08001705
Lorenzo Stoakes0d731752016-10-24 10:57:25 +01001706 rc = get_user_pages(addr, 1, flags, NULL, NULL);
Huang Yingfafc3db2011-01-30 11:15:49 +08001707 return rc == -EHWPOISON;
1708}
1709
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001710/*
Paolo Bonzinib9b33da2018-07-27 17:44:41 +02001711 * The fast path to get the writable pfn which will be stored in @pfn,
1712 * true indicates success, otherwise false is returned. It's also the
Miaohe Lin311497e2019-12-11 14:26:25 +08001713 * only part that runs if we can in atomic context.
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001714 */
Paolo Bonzinib9b33da2018-07-27 17:44:41 +02001715static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
1716 bool *writable, kvm_pfn_t *pfn)
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001717{
1718 struct page *page[1];
1719 int npages;
1720
Xiao Guangrong12ce13f2012-08-21 11:00:49 +08001721 /*
1722 * Fast pin a writable pfn only if it is a write fault request
1723 * or the caller allows to map a writable pfn for a read fault
1724 * request.
1725 */
1726 if (!(write_fault || writable))
1727 return false;
1728
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001729 npages = __get_user_pages_fast(addr, 1, 1, page);
1730 if (npages == 1) {
1731 *pfn = page_to_pfn(page[0]);
1732
1733 if (writable)
1734 *writable = true;
1735 return true;
1736 }
1737
1738 return false;
1739}
1740
1741/*
1742 * The slow path to get the pfn of the specified host virtual address,
1743 * 1 indicates success, -errno is returned if error is detected.
1744 */
1745static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
Dan Williamsba049e92016-01-15 16:56:11 -08001746 bool *writable, kvm_pfn_t *pfn)
Avi Kivity954bbbc2007-03-30 14:02:32 +03001747{
Al Viroce530532017-11-19 17:47:33 -05001748 unsigned int flags = FOLL_HWPOISON;
1749 struct page *page;
Gleb Natapovaf585b92010-10-14 11:22:46 +02001750 int npages = 0;
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001751
1752 might_sleep();
1753
1754 if (writable)
1755 *writable = write_fault;
1756
Al Viroce530532017-11-19 17:47:33 -05001757 if (write_fault)
1758 flags |= FOLL_WRITE;
1759 if (async)
1760 flags |= FOLL_NOWAIT;
Lorenzo Stoakesd4944b02016-10-13 01:20:12 +01001761
Al Viroce530532017-11-19 17:47:33 -05001762 npages = get_user_pages_unlocked(addr, 1, &page, flags);
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001763 if (npages != 1)
1764 return npages;
1765
1766 /* map read fault as writable if possible */
Xiao Guangrong12ce13f2012-08-21 11:00:49 +08001767 if (unlikely(!write_fault) && writable) {
Al Viroce530532017-11-19 17:47:33 -05001768 struct page *wpage;
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001769
Al Viroce530532017-11-19 17:47:33 -05001770 if (__get_user_pages_fast(addr, 1, 1, &wpage) == 1) {
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001771 *writable = true;
Al Viroce530532017-11-19 17:47:33 -05001772 put_page(page);
1773 page = wpage;
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001774 }
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001775 }
Al Viroce530532017-11-19 17:47:33 -05001776 *pfn = page_to_pfn(page);
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001777 return npages;
1778}
1779
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001780static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
1781{
1782 if (unlikely(!(vma->vm_flags & VM_READ)))
1783 return false;
1784
1785 if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
1786 return false;
1787
1788 return true;
1789}
1790
Paolo Bonzini92176a82016-06-07 16:22:47 +02001791static int hva_to_pfn_remapped(struct vm_area_struct *vma,
1792 unsigned long addr, bool *async,
KarimAllah Ahmeda340b3e2018-01-17 19:18:56 +01001793 bool write_fault, bool *writable,
1794 kvm_pfn_t *p_pfn)
Paolo Bonzini92176a82016-06-07 16:22:47 +02001795{
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02001796 unsigned long pfn;
1797 int r;
1798
1799 r = follow_pfn(vma, addr, &pfn);
1800 if (r) {
1801 /*
1802 * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
1803 * not call the fault handler, so do it here.
1804 */
1805 bool unlocked = false;
1806 r = fixup_user_fault(current, current->mm, addr,
1807 (write_fault ? FAULT_FLAG_WRITE : 0),
1808 &unlocked);
1809 if (unlocked)
1810 return -EAGAIN;
1811 if (r)
1812 return r;
1813
1814 r = follow_pfn(vma, addr, &pfn);
1815 if (r)
1816 return r;
1817
1818 }
1819
KarimAllah Ahmeda340b3e2018-01-17 19:18:56 +01001820 if (writable)
1821 *writable = true;
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02001822
1823 /*
1824 * Get a reference here because callers of *hva_to_pfn* and
1825 * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
1826 * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
1827 * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
1828 * simply do nothing for reserved pfns.
1829 *
1830 * Whoever called remap_pfn_range is also going to call e.g.
1831 * unmap_mapping_range before the underlying pages are freed,
1832 * causing a call to our MMU notifier.
1833 */
1834 kvm_get_pfn(pfn);
1835
1836 *p_pfn = pfn;
Paolo Bonzini92176a82016-06-07 16:22:47 +02001837 return 0;
1838}
1839
Xiao Guangrong12ce13f2012-08-21 11:00:49 +08001840/*
1841 * Pin guest page in memory and return its pfn.
1842 * @addr: host virtual address which maps memory to the guest
1843 * @atomic: whether this function can sleep
1844 * @async: whether this function need to wait IO complete if the
1845 * host page is not in the memory
1846 * @write_fault: whether we should get a writable host page
1847 * @writable: whether it allows to map a writable host page for !@write_fault
1848 *
1849 * The function will map a writable host page for these two cases:
1850 * 1): @write_fault = true
1851 * 2): @write_fault = false && @writable, @writable will tell the caller
1852 * whether the mapping is writable.
1853 */
Dan Williamsba049e92016-01-15 16:56:11 -08001854static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001855 bool write_fault, bool *writable)
1856{
1857 struct vm_area_struct *vma;
Dan Williamsba049e92016-01-15 16:56:11 -08001858 kvm_pfn_t pfn = 0;
Paolo Bonzini92176a82016-06-07 16:22:47 +02001859 int npages, r;
Avi Kivity954bbbc2007-03-30 14:02:32 +03001860
Gleb Natapovaf585b92010-10-14 11:22:46 +02001861 /* we can do it either atomically or asynchronously, not both */
1862 BUG_ON(atomic && async);
1863
Paolo Bonzinib9b33da2018-07-27 17:44:41 +02001864 if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001865 return pfn;
Marcelo Tosatti612819c2010-10-22 14:18:18 -02001866
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001867 if (atomic)
1868 return KVM_PFN_ERR_FAULT;
Marcelo Tosatti612819c2010-10-22 14:18:18 -02001869
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001870 npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
1871 if (npages == 1)
1872 return pfn;
Gleb Natapovaf585b92010-10-14 11:22:46 +02001873
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001874 down_read(&current->mm->mmap_sem);
1875 if (npages == -EHWPOISON ||
1876 (!async && check_user_page_hwpoison(addr))) {
1877 pfn = KVM_PFN_ERR_HWPOISON;
1878 goto exit;
Xiao Guangrong887c08a2010-08-22 19:10:28 +08001879 }
Izik Eidus539cb662007-11-11 22:05:04 +02001880
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02001881retry:
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001882 vma = find_vma_intersection(current->mm, addr, addr + 1);
Anthony Liguori8d4e1282007-10-18 09:59:34 -05001883
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001884 if (vma == NULL)
1885 pfn = KVM_PFN_ERR_FAULT;
Paolo Bonzini92176a82016-06-07 16:22:47 +02001886 else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
KarimAllah Ahmeda340b3e2018-01-17 19:18:56 +01001887 r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
Paolo Bonziniadd6a0c2016-06-07 17:51:18 +02001888 if (r == -EAGAIN)
1889 goto retry;
Paolo Bonzini92176a82016-06-07 16:22:47 +02001890 if (r < 0)
1891 pfn = KVM_PFN_ERR_FAULT;
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001892 } else {
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001893 if (async && vma_is_valid(vma, write_fault))
Xiao Guangrong2fc84312012-08-21 11:00:22 +08001894 *async = true;
1895 pfn = KVM_PFN_ERR_FAULT;
1896 }
1897exit:
1898 up_read(&current->mm->mmap_sem);
Anthony Liguori2e2e3732008-04-30 15:37:07 -05001899 return pfn;
Anthony Liguori35149e22008-04-02 14:46:56 -05001900}
1901
Dan Williamsba049e92016-01-15 16:56:11 -08001902kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
1903 bool atomic, bool *async, bool write_fault,
1904 bool *writable)
Xiao Guangrong887c08a2010-08-22 19:10:28 +08001905{
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001906 unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
1907
Paolo Bonzinib2740d32016-02-23 15:36:01 +01001908 if (addr == KVM_HVA_ERR_RO_BAD) {
1909 if (writable)
1910 *writable = false;
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001911 return KVM_PFN_ERR_RO_FAULT;
Paolo Bonzinib2740d32016-02-23 15:36:01 +01001912 }
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001913
Paolo Bonzinib2740d32016-02-23 15:36:01 +01001914 if (kvm_is_error_hva(addr)) {
1915 if (writable)
1916 *writable = false;
Xiao Guangrong81c52c52012-10-16 20:10:59 +08001917 return KVM_PFN_NOSLOT;
Paolo Bonzinib2740d32016-02-23 15:36:01 +01001918 }
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001919
1920 /* Do not map writable pfn in the readonly memslot. */
1921 if (writable && memslot_is_readonly(slot)) {
1922 *writable = false;
1923 writable = NULL;
1924 }
1925
1926 return hva_to_pfn(addr, atomic, async, write_fault,
1927 writable);
Xiao Guangrong887c08a2010-08-22 19:10:28 +08001928}
Paolo Bonzini35204692015-04-02 11:20:48 +02001929EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
Xiao Guangrong887c08a2010-08-22 19:10:28 +08001930
Dan Williamsba049e92016-01-15 16:56:11 -08001931kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
Marcelo Tosatti612819c2010-10-22 14:18:18 -02001932 bool *writable)
1933{
Paolo Bonzinie37afc62015-05-19 16:09:04 +02001934 return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
1935 write_fault, writable);
Marcelo Tosatti612819c2010-10-22 14:18:18 -02001936}
1937EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
1938
Dan Williamsba049e92016-01-15 16:56:11 -08001939kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
Marcelo Tosatti506f0d62009-12-23 14:35:19 -02001940{
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001941 return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
Marcelo Tosatti506f0d62009-12-23 14:35:19 -02001942}
Paolo Bonzinie37afc62015-05-19 16:09:04 +02001943EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
Marcelo Tosatti506f0d62009-12-23 14:35:19 -02001944
Dan Williamsba049e92016-01-15 16:56:11 -08001945kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
Xiao Guangrong037d92d2012-08-21 10:59:12 +08001946{
Xiao Guangrong4d8b81a2012-08-21 11:02:51 +08001947 return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
Xiao Guangrong037d92d2012-08-21 10:59:12 +08001948}
1949EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
1950
Dan Williamsba049e92016-01-15 16:56:11 -08001951kvm_pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
Paolo Bonzinie37afc62015-05-19 16:09:04 +02001952{
1953 return gfn_to_pfn_memslot_atomic(gfn_to_memslot(kvm, gfn), gfn);
1954}
1955EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
1956
Dan Williamsba049e92016-01-15 16:56:11 -08001957kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
Paolo Bonzini8e734852015-05-17 13:58:53 +02001958{
1959 return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1960}
1961EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
1962
Dan Williamsba049e92016-01-15 16:56:11 -08001963kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
Paolo Bonzinie37afc62015-05-19 16:09:04 +02001964{
1965 return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
1966}
1967EXPORT_SYMBOL_GPL(gfn_to_pfn);
1968
Dan Williamsba049e92016-01-15 16:56:11 -08001969kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
Paolo Bonzini8e734852015-05-17 13:58:53 +02001970{
1971 return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
1972}
1973EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
1974
Paolo Bonzinid9ef13c2015-05-19 16:01:50 +02001975int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1976 struct page **pages, int nr_pages)
Xiao Guangrong48987782010-08-22 19:11:43 +08001977{
1978 unsigned long addr;
Arnd Bergmann076b9252017-08-10 14:14:39 +02001979 gfn_t entry = 0;
Xiao Guangrong48987782010-08-22 19:11:43 +08001980
Paolo Bonzinid9ef13c2015-05-19 16:01:50 +02001981 addr = gfn_to_hva_many(slot, gfn, &entry);
Xiao Guangrong48987782010-08-22 19:11:43 +08001982 if (kvm_is_error_hva(addr))
1983 return -1;
1984
1985 if (entry < nr_pages)
1986 return 0;
1987
1988 return __get_user_pages_fast(addr, nr_pages, 1, pages);
1989}
1990EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
1991
Dan Williamsba049e92016-01-15 16:56:11 -08001992static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
Xiao Guangronga2766322012-07-26 11:58:59 +08001993{
Xiao Guangrong81c52c52012-10-16 20:10:59 +08001994 if (is_error_noslot_pfn(pfn))
Xiao Guangrong6cede2e2012-08-03 15:41:22 +08001995 return KVM_ERR_PTR_BAD_PAGE;
Xiao Guangronga2766322012-07-26 11:58:59 +08001996
Ard Biesheuvelbf4bea82014-11-10 08:33:56 +00001997 if (kvm_is_reserved_pfn(pfn)) {
Xiao Guangrongcb9aaa32012-08-03 15:42:10 +08001998 WARN_ON(1);
1999 return KVM_ERR_PTR_BAD_PAGE;
2000 }
2001
Xiao Guangronga2766322012-07-26 11:58:59 +08002002 return pfn_to_page(pfn);
2003}
2004
Anthony Liguori35149e22008-04-02 14:46:56 -05002005struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
2006{
Dan Williamsba049e92016-01-15 16:56:11 -08002007 kvm_pfn_t pfn;
Anthony Liguori2e2e3732008-04-30 15:37:07 -05002008
2009 pfn = gfn_to_pfn(kvm, gfn);
Anthony Liguori2e2e3732008-04-30 15:37:07 -05002010
Xiao Guangronga2766322012-07-26 11:58:59 +08002011 return kvm_pfn_to_page(pfn);
Avi Kivity954bbbc2007-03-30 14:02:32 +03002012}
2013EXPORT_SYMBOL_GPL(gfn_to_page);
2014
Boris Ostrovsky91724812019-12-05 01:30:51 +00002015void kvm_release_pfn(kvm_pfn_t pfn, bool dirty, struct gfn_to_pfn_cache *cache)
2016{
2017 if (pfn == 0)
2018 return;
2019
2020 if (cache)
2021 cache->pfn = cache->gfn = 0;
2022
2023 if (dirty)
2024 kvm_release_pfn_dirty(pfn);
2025 else
2026 kvm_release_pfn_clean(pfn);
2027}
2028
2029static void kvm_cache_gfn_to_pfn(struct kvm_memory_slot *slot, gfn_t gfn,
2030 struct gfn_to_pfn_cache *cache, u64 gen)
2031{
2032 kvm_release_pfn(cache->pfn, cache->dirty, cache);
2033
2034 cache->pfn = gfn_to_pfn_memslot(slot, gfn);
2035 cache->gfn = gfn;
2036 cache->dirty = false;
2037 cache->generation = gen;
2038}
2039
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002040static int __kvm_map_gfn(struct kvm_memslots *slots, gfn_t gfn,
Boris Ostrovsky91724812019-12-05 01:30:51 +00002041 struct kvm_host_map *map,
2042 struct gfn_to_pfn_cache *cache,
2043 bool atomic)
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002044{
2045 kvm_pfn_t pfn;
2046 void *hva = NULL;
2047 struct page *page = KVM_UNMAPPED_PAGE;
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002048 struct kvm_memory_slot *slot = __gfn_to_memslot(slots, gfn);
Boris Ostrovsky91724812019-12-05 01:30:51 +00002049 u64 gen = slots->generation;
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002050
2051 if (!map)
2052 return -EINVAL;
2053
Boris Ostrovsky91724812019-12-05 01:30:51 +00002054 if (cache) {
2055 if (!cache->pfn || cache->gfn != gfn ||
2056 cache->generation != gen) {
2057 if (atomic)
2058 return -EAGAIN;
2059 kvm_cache_gfn_to_pfn(slot, gfn, cache, gen);
2060 }
2061 pfn = cache->pfn;
2062 } else {
2063 if (atomic)
2064 return -EAGAIN;
2065 pfn = gfn_to_pfn_memslot(slot, gfn);
2066 }
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002067 if (is_error_noslot_pfn(pfn))
2068 return -EINVAL;
2069
2070 if (pfn_valid(pfn)) {
2071 page = pfn_to_page(pfn);
Boris Ostrovsky91724812019-12-05 01:30:51 +00002072 if (atomic)
2073 hva = kmap_atomic(page);
2074 else
2075 hva = kmap(page);
Paolo Bonzinid30b2142019-05-20 12:06:36 +02002076#ifdef CONFIG_HAS_IOMEM
Boris Ostrovsky91724812019-12-05 01:30:51 +00002077 } else if (!atomic) {
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002078 hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
Boris Ostrovsky91724812019-12-05 01:30:51 +00002079 } else {
2080 return -EINVAL;
Paolo Bonzinid30b2142019-05-20 12:06:36 +02002081#endif
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002082 }
2083
2084 if (!hva)
2085 return -EFAULT;
2086
2087 map->page = page;
2088 map->hva = hva;
2089 map->pfn = pfn;
2090 map->gfn = gfn;
2091
2092 return 0;
2093}
2094
Boris Ostrovsky91724812019-12-05 01:30:51 +00002095int kvm_map_gfn(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map,
2096 struct gfn_to_pfn_cache *cache, bool atomic)
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002097{
Boris Ostrovsky91724812019-12-05 01:30:51 +00002098 return __kvm_map_gfn(kvm_memslots(vcpu->kvm), gfn, map,
2099 cache, atomic);
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002100}
2101EXPORT_SYMBOL_GPL(kvm_map_gfn);
2102
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002103int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
2104{
Boris Ostrovsky91724812019-12-05 01:30:51 +00002105 return __kvm_map_gfn(kvm_vcpu_memslots(vcpu), gfn, map,
2106 NULL, false);
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002107}
2108EXPORT_SYMBOL_GPL(kvm_vcpu_map);
2109
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002110static void __kvm_unmap_gfn(struct kvm_memory_slot *memslot,
Boris Ostrovsky91724812019-12-05 01:30:51 +00002111 struct kvm_host_map *map,
2112 struct gfn_to_pfn_cache *cache,
2113 bool dirty, bool atomic)
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002114{
2115 if (!map)
2116 return;
2117
2118 if (!map->hva)
2119 return;
2120
Boris Ostrovsky91724812019-12-05 01:30:51 +00002121 if (map->page != KVM_UNMAPPED_PAGE) {
2122 if (atomic)
2123 kunmap_atomic(map->hva);
2124 else
2125 kunmap(map->page);
2126 }
Christian Borntraegereb1f2f32019-05-27 10:28:25 +02002127#ifdef CONFIG_HAS_IOMEM
Boris Ostrovsky91724812019-12-05 01:30:51 +00002128 else if (!atomic)
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002129 memunmap(map->hva);
Boris Ostrovsky91724812019-12-05 01:30:51 +00002130 else
2131 WARN_ONCE(1, "Unexpected unmapping in atomic context");
Christian Borntraegereb1f2f32019-05-27 10:28:25 +02002132#endif
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002133
Boris Ostrovsky91724812019-12-05 01:30:51 +00002134 if (dirty)
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002135 mark_page_dirty_in_slot(memslot, map->gfn);
Boris Ostrovsky91724812019-12-05 01:30:51 +00002136
2137 if (cache)
2138 cache->dirty |= dirty;
2139 else
2140 kvm_release_pfn(map->pfn, dirty, NULL);
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002141
2142 map->hva = NULL;
2143 map->page = NULL;
2144}
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002145
Boris Ostrovsky91724812019-12-05 01:30:51 +00002146int kvm_unmap_gfn(struct kvm_vcpu *vcpu, struct kvm_host_map *map,
2147 struct gfn_to_pfn_cache *cache, bool dirty, bool atomic)
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002148{
Boris Ostrovsky91724812019-12-05 01:30:51 +00002149 __kvm_unmap_gfn(gfn_to_memslot(vcpu->kvm, map->gfn), map,
2150 cache, dirty, atomic);
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002151 return 0;
2152}
2153EXPORT_SYMBOL_GPL(kvm_unmap_gfn);
2154
2155void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
2156{
Boris Ostrovsky91724812019-12-05 01:30:51 +00002157 __kvm_unmap_gfn(kvm_vcpu_gfn_to_memslot(vcpu, map->gfn), map, NULL,
2158 dirty, false);
Boris Ostrovsky1eff70a2019-11-12 16:35:06 +00002159}
KarimAllah Ahmede45adf62019-01-31 21:24:34 +01002160EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
2161
Paolo Bonzini8e734852015-05-17 13:58:53 +02002162struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
2163{
Dan Williamsba049e92016-01-15 16:56:11 -08002164 kvm_pfn_t pfn;
Paolo Bonzini8e734852015-05-17 13:58:53 +02002165
2166 pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
2167
2168 return kvm_pfn_to_page(pfn);
2169}
2170EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
2171
Izik Eidusb4231d62007-11-20 11:49:33 +02002172void kvm_release_page_clean(struct page *page)
2173{
Xiao Guangrong32cad842012-08-03 15:42:52 +08002174 WARN_ON(is_error_page(page));
2175
Anthony Liguori35149e22008-04-02 14:46:56 -05002176 kvm_release_pfn_clean(page_to_pfn(page));
Izik Eidusb4231d62007-11-20 11:49:33 +02002177}
2178EXPORT_SYMBOL_GPL(kvm_release_page_clean);
2179
Dan Williamsba049e92016-01-15 16:56:11 -08002180void kvm_release_pfn_clean(kvm_pfn_t pfn)
Anthony Liguori35149e22008-04-02 14:46:56 -05002181{
Ard Biesheuvelbf4bea82014-11-10 08:33:56 +00002182 if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
Anthony Liguori2e2e3732008-04-30 15:37:07 -05002183 put_page(pfn_to_page(pfn));
Anthony Liguori35149e22008-04-02 14:46:56 -05002184}
2185EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
2186
Izik Eidusb4231d62007-11-20 11:49:33 +02002187void kvm_release_page_dirty(struct page *page)
Izik Eidus8a7ae052007-10-18 11:09:33 +02002188{
Xiao Guangronga2766322012-07-26 11:58:59 +08002189 WARN_ON(is_error_page(page));
2190
Anthony Liguori35149e22008-04-02 14:46:56 -05002191 kvm_release_pfn_dirty(page_to_pfn(page));
Izik Eidus8a7ae052007-10-18 11:09:33 +02002192}
Izik Eidusb4231d62007-11-20 11:49:33 +02002193EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
Izik Eidus8a7ae052007-10-18 11:09:33 +02002194
David Hildenbrandf7a65092017-09-01 17:11:43 +02002195void kvm_release_pfn_dirty(kvm_pfn_t pfn)
Anthony Liguori35149e22008-04-02 14:46:56 -05002196{
2197 kvm_set_pfn_dirty(pfn);
2198 kvm_release_pfn_clean(pfn);
2199}
David Hildenbrandf7a65092017-09-01 17:11:43 +02002200EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
Anthony Liguori35149e22008-04-02 14:46:56 -05002201
Dan Williamsba049e92016-01-15 16:56:11 -08002202void kvm_set_pfn_dirty(kvm_pfn_t pfn)
Anthony Liguori35149e22008-04-02 14:46:56 -05002203{
Miaohe Lind29c03a2019-12-05 11:05:05 +08002204 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
2205 SetPageDirty(pfn_to_page(pfn));
Anthony Liguori35149e22008-04-02 14:46:56 -05002206}
2207EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
2208
Dan Williamsba049e92016-01-15 16:56:11 -08002209void kvm_set_pfn_accessed(kvm_pfn_t pfn)
Anthony Liguori35149e22008-04-02 14:46:56 -05002210{
Sean Christophersona78986a2019-11-11 14:12:27 -08002211 if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
Anthony Liguori2e2e3732008-04-30 15:37:07 -05002212 mark_page_accessed(pfn_to_page(pfn));
Anthony Liguori35149e22008-04-02 14:46:56 -05002213}
2214EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
2215
Dan Williamsba049e92016-01-15 16:56:11 -08002216void kvm_get_pfn(kvm_pfn_t pfn)
Anthony Liguori35149e22008-04-02 14:46:56 -05002217{
Ard Biesheuvelbf4bea82014-11-10 08:33:56 +00002218 if (!kvm_is_reserved_pfn(pfn))
Anthony Liguori2e2e3732008-04-30 15:37:07 -05002219 get_page(pfn_to_page(pfn));
Anthony Liguori35149e22008-04-02 14:46:56 -05002220}
2221EXPORT_SYMBOL_GPL(kvm_get_pfn);
2222
Izik Eidus195aefd2007-10-01 22:14:18 +02002223static int next_segment(unsigned long len, int offset)
2224{
2225 if (len > PAGE_SIZE - offset)
2226 return PAGE_SIZE - offset;
2227 else
2228 return len;
2229}
2230
Paolo Bonzini8e734852015-05-17 13:58:53 +02002231static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
2232 void *data, int offset, int len)
Izik Eidus195aefd2007-10-01 22:14:18 +02002233{
Izik Eiduse0506bc2007-11-11 22:10:22 +02002234 int r;
2235 unsigned long addr;
Izik Eidus195aefd2007-10-01 22:14:18 +02002236
Paolo Bonzini8e734852015-05-17 13:58:53 +02002237 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
Izik Eiduse0506bc2007-11-11 22:10:22 +02002238 if (kvm_is_error_hva(addr))
Izik Eidus195aefd2007-10-01 22:14:18 +02002239 return -EFAULT;
Paolo Bonzini3180a7f2015-04-02 14:08:20 +02002240 r = __copy_from_user(data, (void __user *)addr + offset, len);
Izik Eiduse0506bc2007-11-11 22:10:22 +02002241 if (r)
2242 return -EFAULT;
Izik Eidus195aefd2007-10-01 22:14:18 +02002243 return 0;
2244}
Paolo Bonzini8e734852015-05-17 13:58:53 +02002245
2246int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
2247 int len)
2248{
2249 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2250
2251 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2252}
Izik Eidus195aefd2007-10-01 22:14:18 +02002253EXPORT_SYMBOL_GPL(kvm_read_guest_page);
2254
Paolo Bonzini8e734852015-05-17 13:58:53 +02002255int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
2256 int offset, int len)
2257{
2258 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2259
2260 return __kvm_read_guest_page(slot, gfn, data, offset, len);
2261}
2262EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
2263
Izik Eidus195aefd2007-10-01 22:14:18 +02002264int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
2265{
2266 gfn_t gfn = gpa >> PAGE_SHIFT;
2267 int seg;
2268 int offset = offset_in_page(gpa);
2269 int ret;
2270
2271 while ((seg = next_segment(len, offset)) != 0) {
2272 ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
2273 if (ret < 0)
2274 return ret;
2275 offset = 0;
2276 len -= seg;
2277 data += seg;
2278 ++gfn;
2279 }
2280 return 0;
2281}
2282EXPORT_SYMBOL_GPL(kvm_read_guest);
2283
Paolo Bonzini8e734852015-05-17 13:58:53 +02002284int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
2285{
2286 gfn_t gfn = gpa >> PAGE_SHIFT;
2287 int seg;
2288 int offset = offset_in_page(gpa);
2289 int ret;
2290
2291 while ((seg = next_segment(len, offset)) != 0) {
2292 ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
2293 if (ret < 0)
2294 return ret;
2295 offset = 0;
2296 len -= seg;
2297 data += seg;
2298 ++gfn;
2299 }
2300 return 0;
2301}
2302EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
2303
2304static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
2305 void *data, int offset, unsigned long len)
Marcelo Tosatti7ec54582007-12-20 19:18:23 -05002306{
2307 int r;
2308 unsigned long addr;
Marcelo Tosatti7ec54582007-12-20 19:18:23 -05002309
Paolo Bonzini8e734852015-05-17 13:58:53 +02002310 addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
Marcelo Tosatti7ec54582007-12-20 19:18:23 -05002311 if (kvm_is_error_hva(addr))
2312 return -EFAULT;
Andrea Arcangeli0aac03f2008-01-30 19:57:35 +01002313 pagefault_disable();
Paolo Bonzini3180a7f2015-04-02 14:08:20 +02002314 r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
Andrea Arcangeli0aac03f2008-01-30 19:57:35 +01002315 pagefault_enable();
Marcelo Tosatti7ec54582007-12-20 19:18:23 -05002316 if (r)
2317 return -EFAULT;
2318 return 0;
2319}
Marcelo Tosatti7ec54582007-12-20 19:18:23 -05002320
Paolo Bonzini8e734852015-05-17 13:58:53 +02002321int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
2322 void *data, unsigned long len)
2323{
2324 gfn_t gfn = gpa >> PAGE_SHIFT;
2325 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2326 int offset = offset_in_page(gpa);
2327
2328 return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
2329}
2330EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
2331
2332static int __kvm_write_guest_page(struct kvm_memory_slot *memslot, gfn_t gfn,
2333 const void *data, int offset, int len)
Izik Eidus195aefd2007-10-01 22:14:18 +02002334{
Izik Eiduse0506bc2007-11-11 22:10:22 +02002335 int r;
2336 unsigned long addr;
Izik Eidus195aefd2007-10-01 22:14:18 +02002337
Radim Krčmář251eb842015-04-10 21:47:27 +02002338 addr = gfn_to_hva_memslot(memslot, gfn);
Izik Eiduse0506bc2007-11-11 22:10:22 +02002339 if (kvm_is_error_hva(addr))
Izik Eidus195aefd2007-10-01 22:14:18 +02002340 return -EFAULT;
Xiao Guangrong8b0cedf2011-05-15 23:22:04 +08002341 r = __copy_to_user((void __user *)addr + offset, data, len);
Izik Eiduse0506bc2007-11-11 22:10:22 +02002342 if (r)
2343 return -EFAULT;
Paolo Bonzinibc009e42015-05-26 12:43:41 +02002344 mark_page_dirty_in_slot(memslot, gfn);
Izik Eidus195aefd2007-10-01 22:14:18 +02002345 return 0;
2346}
Paolo Bonzini8e734852015-05-17 13:58:53 +02002347
2348int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
2349 const void *data, int offset, int len)
2350{
2351 struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
2352
2353 return __kvm_write_guest_page(slot, gfn, data, offset, len);
2354}
Izik Eidus195aefd2007-10-01 22:14:18 +02002355EXPORT_SYMBOL_GPL(kvm_write_guest_page);
2356
Paolo Bonzini8e734852015-05-17 13:58:53 +02002357int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
2358 const void *data, int offset, int len)
2359{
2360 struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2361
2362 return __kvm_write_guest_page(slot, gfn, data, offset, len);
2363}
2364EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
2365
Izik Eidus195aefd2007-10-01 22:14:18 +02002366int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
2367 unsigned long len)
2368{
2369 gfn_t gfn = gpa >> PAGE_SHIFT;
2370 int seg;
2371 int offset = offset_in_page(gpa);
2372 int ret;
2373
2374 while ((seg = next_segment(len, offset)) != 0) {
2375 ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
2376 if (ret < 0)
2377 return ret;
2378 offset = 0;
2379 len -= seg;
2380 data += seg;
2381 ++gfn;
2382 }
2383 return 0;
2384}
Wincy Vanff651cb2014-12-11 08:52:58 +03002385EXPORT_SYMBOL_GPL(kvm_write_guest);
Izik Eidus195aefd2007-10-01 22:14:18 +02002386
Paolo Bonzini8e734852015-05-17 13:58:53 +02002387int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
2388 unsigned long len)
2389{
2390 gfn_t gfn = gpa >> PAGE_SHIFT;
2391 int seg;
2392 int offset = offset_in_page(gpa);
2393 int ret;
2394
2395 while ((seg = next_segment(len, offset)) != 0) {
2396 ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
2397 if (ret < 0)
2398 return ret;
2399 offset = 0;
2400 len -= seg;
2401 data += seg;
2402 ++gfn;
2403 }
2404 return 0;
2405}
2406EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
2407
Paolo Bonzini5a2d4362017-02-03 20:32:28 -08002408static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
2409 struct gfn_to_hva_cache *ghc,
2410 gpa_t gpa, unsigned long len)
Gleb Natapov49c77542010-10-18 15:22:23 +02002411{
Gleb Natapov49c77542010-10-18 15:22:23 +02002412 int offset = offset_in_page(gpa);
Andrew Honig8f964522013-03-29 09:35:21 -07002413 gfn_t start_gfn = gpa >> PAGE_SHIFT;
2414 gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
2415 gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
2416 gfn_t nr_pages_avail;
Gleb Natapov49c77542010-10-18 15:22:23 +02002417
Sean Christopherson6ad1e292020-01-09 14:58:55 -05002418 /* Update ghc->generation before performing any error checks. */
Gleb Natapov49c77542010-10-18 15:22:23 +02002419 ghc->generation = slots->generation;
Sean Christopherson6ad1e292020-01-09 14:58:55 -05002420
2421 if (start_gfn > end_gfn) {
2422 ghc->hva = KVM_HVA_ERR_BAD;
2423 return -EINVAL;
2424 }
Jim Mattsonf1b9dd52018-12-17 13:53:33 -08002425
2426 /*
2427 * If the requested region crosses two memslots, we still
2428 * verify that the entire region is valid here.
2429 */
Sean Christopherson6ad1e292020-01-09 14:58:55 -05002430 for ( ; start_gfn <= end_gfn; start_gfn += nr_pages_avail) {
Jim Mattsonf1b9dd52018-12-17 13:53:33 -08002431 ghc->memslot = __gfn_to_memslot(slots, start_gfn);
2432 ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
2433 &nr_pages_avail);
2434 if (kvm_is_error_hva(ghc->hva))
Sean Christopherson6ad1e292020-01-09 14:58:55 -05002435 return -EFAULT;
Andrew Honig8f964522013-03-29 09:35:21 -07002436 }
Jim Mattsonf1b9dd52018-12-17 13:53:33 -08002437
2438 /* Use the slow path for cross page reads and writes. */
Sean Christopherson6ad1e292020-01-09 14:58:55 -05002439 if (nr_pages_needed == 1)
Jim Mattsonf1b9dd52018-12-17 13:53:33 -08002440 ghc->hva += offset;
2441 else
2442 ghc->memslot = NULL;
2443
Sean Christopherson6ad1e292020-01-09 14:58:55 -05002444 ghc->gpa = gpa;
2445 ghc->len = len;
2446 return 0;
Gleb Natapov49c77542010-10-18 15:22:23 +02002447}
Paolo Bonzini5a2d4362017-02-03 20:32:28 -08002448
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002449int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
Paolo Bonzini5a2d4362017-02-03 20:32:28 -08002450 gpa_t gpa, unsigned long len)
2451{
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002452 struct kvm_memslots *slots = kvm_memslots(kvm);
Paolo Bonzini5a2d4362017-02-03 20:32:28 -08002453 return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
2454}
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002455EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
Gleb Natapov49c77542010-10-18 15:22:23 +02002456
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002457int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
Jim Mattson7a86dab2018-12-14 14:34:43 -08002458 void *data, unsigned int offset,
2459 unsigned long len)
Gleb Natapov49c77542010-10-18 15:22:23 +02002460{
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002461 struct kvm_memslots *slots = kvm_memslots(kvm);
Gleb Natapov49c77542010-10-18 15:22:23 +02002462 int r;
Pan Xinhui4ec6e862016-11-02 05:08:34 -04002463 gpa_t gpa = ghc->gpa + offset;
Gleb Natapov49c77542010-10-18 15:22:23 +02002464
Pan Xinhui4ec6e862016-11-02 05:08:34 -04002465 BUG_ON(len + offset > ghc->len);
Andrew Honig8f964522013-03-29 09:35:21 -07002466
Sean Christophersondc9ce712020-01-09 15:56:20 -08002467 if (slots->generation != ghc->generation) {
2468 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2469 return -EFAULT;
2470 }
Andrew Honig8f964522013-03-29 09:35:21 -07002471
Gleb Natapov49c77542010-10-18 15:22:23 +02002472 if (kvm_is_error_hva(ghc->hva))
2473 return -EFAULT;
2474
Sean Christophersonfcfbc612020-01-09 15:56:18 -08002475 if (unlikely(!ghc->memslot))
2476 return kvm_write_guest(kvm, gpa, data, len);
2477
Pan Xinhui4ec6e862016-11-02 05:08:34 -04002478 r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
Gleb Natapov49c77542010-10-18 15:22:23 +02002479 if (r)
2480 return -EFAULT;
Pan Xinhui4ec6e862016-11-02 05:08:34 -04002481 mark_page_dirty_in_slot(ghc->memslot, gpa >> PAGE_SHIFT);
Gleb Natapov49c77542010-10-18 15:22:23 +02002482
2483 return 0;
2484}
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002485EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
Pan Xinhui4ec6e862016-11-02 05:08:34 -04002486
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002487int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2488 void *data, unsigned long len)
Pan Xinhui4ec6e862016-11-02 05:08:34 -04002489{
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002490 return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
Pan Xinhui4ec6e862016-11-02 05:08:34 -04002491}
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002492EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
Gleb Natapov49c77542010-10-18 15:22:23 +02002493
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002494int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
2495 void *data, unsigned long len)
Gleb Natapove03b6442011-07-11 15:28:11 -04002496{
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002497 struct kvm_memslots *slots = kvm_memslots(kvm);
Gleb Natapove03b6442011-07-11 15:28:11 -04002498 int r;
2499
Andrew Honig8f964522013-03-29 09:35:21 -07002500 BUG_ON(len > ghc->len);
2501
Sean Christophersondc9ce712020-01-09 15:56:20 -08002502 if (slots->generation != ghc->generation) {
2503 if (__kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len))
2504 return -EFAULT;
2505 }
Andrew Honig8f964522013-03-29 09:35:21 -07002506
Gleb Natapove03b6442011-07-11 15:28:11 -04002507 if (kvm_is_error_hva(ghc->hva))
2508 return -EFAULT;
2509
Sean Christophersonfcfbc612020-01-09 15:56:18 -08002510 if (unlikely(!ghc->memslot))
2511 return kvm_read_guest(kvm, ghc->gpa, data, len);
2512
Gleb Natapove03b6442011-07-11 15:28:11 -04002513 r = __copy_from_user(data, (void __user *)ghc->hva, len);
2514 if (r)
2515 return -EFAULT;
2516
2517 return 0;
2518}
Paolo Bonzini4e335d92017-05-02 16:20:18 +02002519EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
Gleb Natapove03b6442011-07-11 15:28:11 -04002520
Izik Eidus195aefd2007-10-01 22:14:18 +02002521int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
2522{
Heiko Carstens8a3caa62013-11-18 10:35:55 +01002523 const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
2524
2525 return kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
Izik Eidus195aefd2007-10-01 22:14:18 +02002526}
2527EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
2528
2529int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
2530{
2531 gfn_t gfn = gpa >> PAGE_SHIFT;
2532 int seg;
2533 int offset = offset_in_page(gpa);
2534 int ret;
2535
Kevin Mulveybfda0e82015-02-20 08:21:36 -05002536 while ((seg = next_segment(len, offset)) != 0) {
Izik Eidus195aefd2007-10-01 22:14:18 +02002537 ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
2538 if (ret < 0)
2539 return ret;
2540 offset = 0;
2541 len -= seg;
2542 ++gfn;
2543 }
2544 return 0;
2545}
2546EXPORT_SYMBOL_GPL(kvm_clear_guest);
2547
Paolo Bonzinibc009e42015-05-26 12:43:41 +02002548static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot,
Stephen Hemminger79408762013-12-29 12:12:29 -08002549 gfn_t gfn)
Avi Kivity6aa8b732006-12-10 02:21:36 -08002550{
Rusty Russell7e9d6192007-07-31 20:41:14 +10002551 if (memslot && memslot->dirty_bitmap) {
2552 unsigned long rel_gfn = gfn - memslot->base_gfn;
Avi Kivity6aa8b732006-12-10 02:21:36 -08002553
Takuya Yoshikawab74ca3b2012-10-04 17:13:12 -07002554 set_bit_le(rel_gfn, memslot->dirty_bitmap);
Avi Kivity6aa8b732006-12-10 02:21:36 -08002555 }
2556}
2557
Gleb Natapov49c77542010-10-18 15:22:23 +02002558void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
2559{
2560 struct kvm_memory_slot *memslot;
2561
2562 memslot = gfn_to_memslot(kvm, gfn);
Paolo Bonzinibc009e42015-05-26 12:43:41 +02002563 mark_page_dirty_in_slot(memslot, gfn);
Gleb Natapov49c77542010-10-18 15:22:23 +02002564}
Aneesh Kumar K.V2ba9f0d2013-10-07 22:17:59 +05302565EXPORT_SYMBOL_GPL(mark_page_dirty);
Gleb Natapov49c77542010-10-18 15:22:23 +02002566
Paolo Bonzini8e734852015-05-17 13:58:53 +02002567void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
2568{
2569 struct kvm_memory_slot *memslot;
2570
2571 memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
2572 mark_page_dirty_in_slot(memslot, gfn);
2573}
2574EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
2575
Jan H. Schönherr20b70352017-11-24 22:39:01 +01002576void kvm_sigset_activate(struct kvm_vcpu *vcpu)
2577{
2578 if (!vcpu->sigset_active)
2579 return;
2580
2581 /*
2582 * This does a lockless modification of ->real_blocked, which is fine
2583 * because, only current can change ->real_blocked and all readers of
2584 * ->real_blocked don't care as long ->real_blocked is always a subset
2585 * of ->blocked.
2586 */
2587 sigprocmask(SIG_SETMASK, &vcpu->sigset, &current->real_blocked);
2588}
2589
2590void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
2591{
2592 if (!vcpu->sigset_active)
2593 return;
2594
2595 sigprocmask(SIG_SETMASK, &current->real_blocked, NULL);
2596 sigemptyset(&current->real_blocked);
2597}
2598
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002599static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
2600{
Nir Weinerdee339b2019-01-27 12:17:16 +02002601 unsigned int old, val, grow, grow_start;
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002602
Wanpeng Li2cbd7822015-09-03 22:07:39 +08002603 old = val = vcpu->halt_poll_ns;
Nir Weinerdee339b2019-01-27 12:17:16 +02002604 grow_start = READ_ONCE(halt_poll_ns_grow_start);
Christian Borntraeger6b6de682016-02-09 13:47:55 +01002605 grow = READ_ONCE(halt_poll_ns_grow);
Nir Weiner7fa08e72019-01-27 12:17:14 +02002606 if (!grow)
2607 goto out;
2608
Nir Weinerdee339b2019-01-27 12:17:16 +02002609 val *= grow;
2610 if (val < grow_start)
2611 val = grow_start;
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002612
David Matlack313f6362016-03-08 16:19:44 -08002613 if (val > halt_poll_ns)
2614 val = halt_poll_ns;
2615
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002616 vcpu->halt_poll_ns = val;
Nir Weiner7fa08e72019-01-27 12:17:14 +02002617out:
Wanpeng Li2cbd7822015-09-03 22:07:39 +08002618 trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002619}
2620
2621static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
2622{
Christian Borntraeger6b6de682016-02-09 13:47:55 +01002623 unsigned int old, val, shrink;
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002624
Wanpeng Li2cbd7822015-09-03 22:07:39 +08002625 old = val = vcpu->halt_poll_ns;
Christian Borntraeger6b6de682016-02-09 13:47:55 +01002626 shrink = READ_ONCE(halt_poll_ns_shrink);
2627 if (shrink == 0)
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002628 val = 0;
2629 else
Christian Borntraeger6b6de682016-02-09 13:47:55 +01002630 val /= shrink;
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002631
2632 vcpu->halt_poll_ns = val;
Wanpeng Li2cbd7822015-09-03 22:07:39 +08002633 trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002634}
2635
Paolo Bonzinif7819512015-02-04 18:20:58 +01002636static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
2637{
Junaid Shahid50c28f22018-06-27 14:59:11 -07002638 int ret = -EINTR;
2639 int idx = srcu_read_lock(&vcpu->kvm->srcu);
2640
Paolo Bonzinif7819512015-02-04 18:20:58 +01002641 if (kvm_arch_vcpu_runnable(vcpu)) {
2642 kvm_make_request(KVM_REQ_UNHALT, vcpu);
Junaid Shahid50c28f22018-06-27 14:59:11 -07002643 goto out;
Paolo Bonzinif7819512015-02-04 18:20:58 +01002644 }
2645 if (kvm_cpu_has_pending_timer(vcpu))
Junaid Shahid50c28f22018-06-27 14:59:11 -07002646 goto out;
Paolo Bonzinif7819512015-02-04 18:20:58 +01002647 if (signal_pending(current))
Junaid Shahid50c28f22018-06-27 14:59:11 -07002648 goto out;
Paolo Bonzinif7819512015-02-04 18:20:58 +01002649
Junaid Shahid50c28f22018-06-27 14:59:11 -07002650 ret = 0;
2651out:
2652 srcu_read_unlock(&vcpu->kvm->srcu, idx);
2653 return ret;
Paolo Bonzinif7819512015-02-04 18:20:58 +01002654}
2655
Eddie Dongb6958ce2007-07-18 12:15:21 +03002656/*
2657 * The vCPU has executed a HLT instruction with in-kernel mode enabled.
2658 */
Hollis Blanchard8776e512007-10-31 17:24:24 -05002659void kvm_vcpu_block(struct kvm_vcpu *vcpu)
Eddie Dongb6958ce2007-07-18 12:15:21 +03002660{
Paolo Bonzinif7819512015-02-04 18:20:58 +01002661 ktime_t start, cur;
Marcelo Tosatti85773702016-02-19 09:46:39 +01002662 DECLARE_SWAITQUEUE(wait);
Paolo Bonzinif7819512015-02-04 18:20:58 +01002663 bool waited = false;
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002664 u64 block_ns;
Paolo Bonzinif7819512015-02-04 18:20:58 +01002665
Marc Zyngier07ab0f82019-08-02 11:37:09 +01002666 kvm_arch_vcpu_blocking(vcpu);
2667
Paolo Bonzinif7819512015-02-04 18:20:58 +01002668 start = cur = ktime_get();
Christian Borntraegercdd6ad32019-03-05 05:30:01 -05002669 if (vcpu->halt_poll_ns && !kvm_arch_no_poll(vcpu)) {
Wanpeng Li19020f82015-09-03 22:07:37 +08002670 ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
Xiubo Lif95ef0cd2015-02-26 14:58:23 +08002671
Paolo Bonzini62bea5b2015-09-15 18:27:57 +02002672 ++vcpu->stat.halt_attempted_poll;
Paolo Bonzinif7819512015-02-04 18:20:58 +01002673 do {
2674 /*
2675 * This sets KVM_REQ_UNHALT if an interrupt
2676 * arrives.
2677 */
2678 if (kvm_vcpu_check_block(vcpu) < 0) {
2679 ++vcpu->stat.halt_successful_poll;
Christian Borntraeger3491caf2016-05-13 12:16:35 +02002680 if (!vcpu_valid_wakeup(vcpu))
2681 ++vcpu->stat.halt_poll_invalid;
Paolo Bonzinif7819512015-02-04 18:20:58 +01002682 goto out;
2683 }
2684 cur = ktime_get();
2685 } while (single_task_running() && ktime_before(cur, stop));
2686 }
Eddie Dongb6958ce2007-07-18 12:15:21 +03002687
Marcelo Tosattie5c239c2008-05-08 19:47:01 -03002688 for (;;) {
Peter Zijlstrab3dae102018-06-12 10:34:52 +02002689 prepare_to_swait_exclusive(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
Eddie Dongb6958ce2007-07-18 12:15:21 +03002690
Paolo Bonzinif7819512015-02-04 18:20:58 +01002691 if (kvm_vcpu_check_block(vcpu) < 0)
Marcelo Tosattie5c239c2008-05-08 19:47:01 -03002692 break;
2693
Paolo Bonzinif7819512015-02-04 18:20:58 +01002694 waited = true;
Eddie Dongb6958ce2007-07-18 12:15:21 +03002695 schedule();
Eddie Dongb6958ce2007-07-18 12:15:21 +03002696 }
2697
Marcelo Tosatti85773702016-02-19 09:46:39 +01002698 finish_swait(&vcpu->wq, &wait);
Paolo Bonzinif7819512015-02-04 18:20:58 +01002699 cur = ktime_get();
Paolo Bonzinif7819512015-02-04 18:20:58 +01002700out:
Marc Zyngier07ab0f82019-08-02 11:37:09 +01002701 kvm_arch_vcpu_unblocking(vcpu);
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002702 block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
2703
Wanpeng Li44551b22019-09-29 09:06:56 +08002704 if (!kvm_arch_no_poll(vcpu)) {
2705 if (!vcpu_valid_wakeup(vcpu)) {
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002706 shrink_halt_poll_ns(vcpu);
Wanpeng Li44551b22019-09-29 09:06:56 +08002707 } else if (halt_poll_ns) {
2708 if (block_ns <= vcpu->halt_poll_ns)
2709 ;
2710 /* we had a long block, shrink polling */
2711 else if (vcpu->halt_poll_ns && block_ns > halt_poll_ns)
2712 shrink_halt_poll_ns(vcpu);
2713 /* we had a short halt and our poll time is too small */
2714 else if (vcpu->halt_poll_ns < halt_poll_ns &&
2715 block_ns < halt_poll_ns)
2716 grow_halt_poll_ns(vcpu);
2717 } else {
2718 vcpu->halt_poll_ns = 0;
2719 }
2720 }
Wanpeng Liaca6ff22015-09-03 22:07:38 +08002721
Christian Borntraeger3491caf2016-05-13 12:16:35 +02002722 trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
2723 kvm_arch_vcpu_block_finish(vcpu);
Eddie Dongb6958ce2007-07-18 12:15:21 +03002724}
Aneesh Kumar K.V2ba9f0d2013-10-07 22:17:59 +05302725EXPORT_SYMBOL_GPL(kvm_vcpu_block);
Eddie Dongb6958ce2007-07-18 12:15:21 +03002726
Radim Krčmář178f02f2017-04-26 22:32:26 +02002727bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
Christoffer Dallb6d33832012-03-08 16:44:24 -05002728{
Marcelo Tosatti85773702016-02-19 09:46:39 +01002729 struct swait_queue_head *wqp;
Christoffer Dallb6d33832012-03-08 16:44:24 -05002730
2731 wqp = kvm_arch_vcpu_wq(vcpu);
Davidlohr Bueso5e0018b2017-09-13 13:08:22 -07002732 if (swq_has_sleeper(wqp)) {
Peter Zijlstrab3dae102018-06-12 10:34:52 +02002733 swake_up_one(wqp);
Wanpeng Lid73eb572019-07-18 19:39:06 +08002734 WRITE_ONCE(vcpu->ready, true);
Christoffer Dallb6d33832012-03-08 16:44:24 -05002735 ++vcpu->stat.halt_wakeup;
Radim Krčmář178f02f2017-04-26 22:32:26 +02002736 return true;
Christoffer Dallb6d33832012-03-08 16:44:24 -05002737 }
2738
Radim Krčmář178f02f2017-04-26 22:32:26 +02002739 return false;
Radim Krčmářdd1a4cc2016-05-04 14:09:44 -05002740}
2741EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
2742
Paolo Bonzini0266c892017-05-04 15:14:13 +02002743#ifndef CONFIG_S390
Radim Krčmářdd1a4cc2016-05-04 14:09:44 -05002744/*
2745 * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
2746 */
2747void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
2748{
2749 int me;
2750 int cpu = vcpu->cpu;
2751
Radim Krčmář178f02f2017-04-26 22:32:26 +02002752 if (kvm_vcpu_wake_up(vcpu))
2753 return;
2754
Christoffer Dallb6d33832012-03-08 16:44:24 -05002755 me = get_cpu();
2756 if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
2757 if (kvm_arch_vcpu_should_kick(vcpu))
2758 smp_send_reschedule(cpu);
2759 put_cpu();
2760}
Yang Zhanga20ed542013-04-11 19:25:15 +08002761EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
Paolo Bonzini0266c892017-05-04 15:14:13 +02002762#endif /* !CONFIG_S390 */
Christoffer Dallb6d33832012-03-08 16:44:24 -05002763
Dan Carpenterfa933842014-05-23 13:20:42 +03002764int kvm_vcpu_yield_to(struct kvm_vcpu *target)
Konstantin Weitz41628d32012-04-25 15:30:38 +02002765{
2766 struct pid *pid;
2767 struct task_struct *task = NULL;
Dan Carpenterfa933842014-05-23 13:20:42 +03002768 int ret = 0;
Konstantin Weitz41628d32012-04-25 15:30:38 +02002769
2770 rcu_read_lock();
2771 pid = rcu_dereference(target->pid);
2772 if (pid)
Sam Bobroff27fbe64b2014-09-19 09:40:41 +10002773 task = get_pid_task(pid, PIDTYPE_PID);
Konstantin Weitz41628d32012-04-25 15:30:38 +02002774 rcu_read_unlock();
2775 if (!task)
Raghavendra K Tc45c5282013-01-22 13:09:24 +05302776 return ret;
Raghavendra K Tc45c5282013-01-22 13:09:24 +05302777 ret = yield_to(task, 1);
Konstantin Weitz41628d32012-04-25 15:30:38 +02002778 put_task_struct(task);
Raghavendra K Tc45c5282013-01-22 13:09:24 +05302779
2780 return ret;
Konstantin Weitz41628d32012-04-25 15:30:38 +02002781}
2782EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
2783
Raghavendra K T06e48c52012-07-19 15:17:52 +05302784/*
2785 * Helper that checks whether a VCPU is eligible for directed yield.
2786 * Most eligible candidate to yield is decided by following heuristics:
2787 *
2788 * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
2789 * (preempted lock holder), indicated by @in_spin_loop.
2790 * Set at the beiginning and cleared at the end of interception/PLE handler.
2791 *
2792 * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
2793 * chance last time (mostly it has become eligible now since we have probably
2794 * yielded to lockholder in last iteration. This is done by toggling
2795 * @dy_eligible each time a VCPU checked for eligibility.)
2796 *
2797 * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
2798 * to preempted lock-holder could result in wrong VCPU selection and CPU
2799 * burning. Giving priority for a potential lock-holder increases lock
2800 * progress.
2801 *
2802 * Since algorithm is based on heuristics, accessing another VCPU data without
2803 * locking does not harm. It may result in trying to yield to same VCPU, fail
2804 * and continue with next VCPU and so on.
2805 */
Stephen Hemminger79408762013-12-29 12:12:29 -08002806static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
Raghavendra K T06e48c52012-07-19 15:17:52 +05302807{
Scott Wood4a55dd72014-01-09 18:43:16 -06002808#ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
Raghavendra K T06e48c52012-07-19 15:17:52 +05302809 bool eligible;
2810
2811 eligible = !vcpu->spin_loop.in_spin_loop ||
Christian Borntraeger34656112014-09-04 21:13:31 +02002812 vcpu->spin_loop.dy_eligible;
Raghavendra K T06e48c52012-07-19 15:17:52 +05302813
2814 if (vcpu->spin_loop.in_spin_loop)
2815 kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
2816
2817 return eligible;
Scott Wood4a55dd72014-01-09 18:43:16 -06002818#else
2819 return true;
Raghavendra K T06e48c52012-07-19 15:17:52 +05302820#endif
Scott Wood4a55dd72014-01-09 18:43:16 -06002821}
Raghavendra K Tc45c5282013-01-22 13:09:24 +05302822
Wanpeng Li17e433b2019-08-05 10:03:19 +08002823/*
2824 * Unlike kvm_arch_vcpu_runnable, this function is called outside
2825 * a vcpu_load/vcpu_put pair. However, for most architectures
2826 * kvm_arch_vcpu_runnable does not require vcpu_load.
2827 */
2828bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
2829{
2830 return kvm_arch_vcpu_runnable(vcpu);
2831}
2832
2833static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
2834{
2835 if (kvm_arch_dy_runnable(vcpu))
2836 return true;
2837
2838#ifdef CONFIG_KVM_ASYNC_PF
2839 if (!list_empty_careful(&vcpu->async_pf.done))
2840 return true;
2841#endif
2842
2843 return false;
2844}
2845
Longpeng(Mike)199b5762017-08-08 12:05:32 +08002846void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
Zhai, Edwind255f4f2009-10-09 18:03:20 +08002847{
Rik van Riel217ece62011-02-01 09:53:28 -05002848 struct kvm *kvm = me->kvm;
2849 struct kvm_vcpu *vcpu;
2850 int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
2851 int yielded = 0;
Raghavendra K Tc45c5282013-01-22 13:09:24 +05302852 int try = 3;
Rik van Riel217ece62011-02-01 09:53:28 -05002853 int pass;
2854 int i;
Zhai, Edwind255f4f2009-10-09 18:03:20 +08002855
Raghavendra K T4c088492012-07-18 19:07:46 +05302856 kvm_vcpu_set_in_spin_loop(me, true);
Rik van Riel217ece62011-02-01 09:53:28 -05002857 /*
2858 * We boost the priority of a VCPU that is runnable but not
2859 * currently running, because it got preempted by something
2860 * else and called schedule in __vcpu_run. Hopefully that
2861 * VCPU is holding the lock that we need and will release it.
2862 * We approximate round-robin by starting at the last boosted VCPU.
2863 */
Raghavendra K Tc45c5282013-01-22 13:09:24 +05302864 for (pass = 0; pass < 2 && !yielded && try; pass++) {
Rik van Riel217ece62011-02-01 09:53:28 -05002865 kvm_for_each_vcpu(i, vcpu, kvm) {
Rik van Riel5cfc2aa2012-06-19 16:51:04 -04002866 if (!pass && i <= last_boosted_vcpu) {
Rik van Riel217ece62011-02-01 09:53:28 -05002867 i = last_boosted_vcpu;
2868 continue;
2869 } else if (pass && i > last_boosted_vcpu)
2870 break;
Wanpeng Lid73eb572019-07-18 19:39:06 +08002871 if (!READ_ONCE(vcpu->ready))
Raghavendra K T7bc7ae22013-03-04 23:32:27 +05302872 continue;
Rik van Riel217ece62011-02-01 09:53:28 -05002873 if (vcpu == me)
2874 continue;
Wanpeng Li17e433b2019-08-05 10:03:19 +08002875 if (swait_active(&vcpu->wq) && !vcpu_dy_runnable(vcpu))
Rik van Riel217ece62011-02-01 09:53:28 -05002876 continue;
Wanpeng Li046ddee2019-08-01 11:30:14 +08002877 if (READ_ONCE(vcpu->preempted) && yield_to_kernel_mode &&
2878 !kvm_arch_vcpu_in_kernel(vcpu))
Longpeng(Mike)199b5762017-08-08 12:05:32 +08002879 continue;
Raghavendra K T06e48c52012-07-19 15:17:52 +05302880 if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
2881 continue;
Raghavendra K Tc45c5282013-01-22 13:09:24 +05302882
2883 yielded = kvm_vcpu_yield_to(vcpu);
2884 if (yielded > 0) {
Rik van Riel217ece62011-02-01 09:53:28 -05002885 kvm->last_boosted_vcpu = i;
Rik van Riel217ece62011-02-01 09:53:28 -05002886 break;
Raghavendra K Tc45c5282013-01-22 13:09:24 +05302887 } else if (yielded < 0) {
2888 try--;
2889 if (!try)
2890 break;
Rik van Riel217ece62011-02-01 09:53:28 -05002891 }
Rik van Riel217ece62011-02-01 09:53:28 -05002892 }
2893 }
Raghavendra K T4c088492012-07-18 19:07:46 +05302894 kvm_vcpu_set_in_spin_loop(me, false);
Raghavendra K T06e48c52012-07-19 15:17:52 +05302895
2896 /* Ensure vcpu is not eligible during next spinloop */
2897 kvm_vcpu_set_dy_eligible(me, false);
Zhai, Edwind255f4f2009-10-09 18:03:20 +08002898}
2899EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
2900
Souptick Joarder1499fa82018-04-19 00:49:58 +05302901static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02002902{
Dave Jiang11bac802017-02-24 14:56:41 -08002903 struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02002904 struct page *page;
2905
npiggin@suse.dee4a533a2007-12-05 18:15:52 +11002906 if (vmf->pgoff == 0)
Avi Kivity039576c2007-03-20 12:46:50 +02002907 page = virt_to_page(vcpu->run);
Avi Kivity09566762008-01-23 18:14:23 +02002908#ifdef CONFIG_X86
npiggin@suse.dee4a533a2007-12-05 18:15:52 +11002909 else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
Zhang Xiantaoad312c72007-12-13 23:50:52 +08002910 page = virt_to_page(vcpu->arch.pio_data);
Avi Kivity09566762008-01-23 18:14:23 +02002911#endif
Paolo Bonzini4b4357e2017-03-31 13:53:23 +02002912#ifdef CONFIG_KVM_MMIO
Laurent Vivier5f94c172008-05-30 16:05:54 +02002913 else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
2914 page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
2915#endif
Avi Kivity039576c2007-03-20 12:46:50 +02002916 else
Carsten Otte5b1c1492012-01-04 10:25:23 +01002917 return kvm_arch_vcpu_fault(vcpu, vmf);
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02002918 get_page(page);
npiggin@suse.dee4a533a2007-12-05 18:15:52 +11002919 vmf->page = page;
2920 return 0;
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02002921}
2922
Alexey Dobriyanf0f37e2f2009-09-27 22:29:37 +04002923static const struct vm_operations_struct kvm_vcpu_vm_ops = {
npiggin@suse.dee4a533a2007-12-05 18:15:52 +11002924 .fault = kvm_vcpu_fault,
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02002925};
2926
2927static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
2928{
2929 vma->vm_ops = &kvm_vcpu_vm_ops;
2930 return 0;
2931}
2932
Avi Kivitybccf2152007-02-21 18:04:26 +02002933static int kvm_vcpu_release(struct inode *inode, struct file *filp)
2934{
2935 struct kvm_vcpu *vcpu = filp->private_data;
2936
Luiz Capitulino45b59392016-09-16 10:27:35 -04002937 debugfs_remove_recursive(vcpu->debugfs_dentry);
Al Viro66c0b392008-04-19 20:33:56 +01002938 kvm_put_kvm(vcpu->kvm);
Avi Kivitybccf2152007-02-21 18:04:26 +02002939 return 0;
2940}
2941
Christian Borntraeger3d3aab12008-12-02 11:17:32 +01002942static struct file_operations kvm_vcpu_fops = {
Avi Kivitybccf2152007-02-21 18:04:26 +02002943 .release = kvm_vcpu_release,
2944 .unlocked_ioctl = kvm_vcpu_ioctl,
Avi Kivity9a2bb7f2007-02-22 12:58:31 +02002945 .mmap = kvm_vcpu_mmap,
Arnd Bergmann6038f372010-08-15 18:52:59 +02002946 .llseek = noop_llseek,
Marc Zyngier7ddfd3e2018-06-17 10:16:21 +01002947 KVM_COMPAT(kvm_vcpu_compat_ioctl),
Avi Kivitybccf2152007-02-21 18:04:26 +02002948};
2949
2950/*
2951 * Allocates an inode for the vcpu.
2952 */
2953static int create_vcpu_fd(struct kvm_vcpu *vcpu)
2954{
Masatake YAMATOe46b4692018-01-20 04:04:22 +09002955 char name[8 + 1 + ITOA_MAX_LEN + 1];
2956
2957 snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
2958 return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
Avi Kivitybccf2152007-02-21 18:04:26 +02002959}
2960
Greg KH3e7093d2019-07-31 20:56:20 +02002961static void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
Luiz Capitulino45b59392016-09-16 10:27:35 -04002962{
Paolo Bonzini741cbba2019-08-03 08:14:25 +02002963#ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
Luiz Capitulino45b59392016-09-16 10:27:35 -04002964 char dir_name[ITOA_MAX_LEN * 2];
Luiz Capitulino45b59392016-09-16 10:27:35 -04002965
Luiz Capitulino45b59392016-09-16 10:27:35 -04002966 if (!debugfs_initialized())
Greg KH3e7093d2019-07-31 20:56:20 +02002967 return;
Luiz Capitulino45b59392016-09-16 10:27:35 -04002968
2969 snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
2970 vcpu->debugfs_dentry = debugfs_create_dir(dir_name,
Greg KH3e7093d2019-07-31 20:56:20 +02002971 vcpu->kvm->debugfs_dentry);
Luiz Capitulino45b59392016-09-16 10:27:35 -04002972
Greg KH3e7093d2019-07-31 20:56:20 +02002973 kvm_arch_create_vcpu_debugfs(vcpu);
Paolo Bonzini741cbba2019-08-03 08:14:25 +02002974#endif
Luiz Capitulino45b59392016-09-16 10:27:35 -04002975}
2976
Avi Kivityc5ea7662007-02-20 18:41:05 +02002977/*
2978 * Creates some virtual cpus. Good luck creating more than one.
2979 */
Gleb Natapov73880c82009-06-09 15:56:28 +03002980static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
Avi Kivityc5ea7662007-02-20 18:41:05 +02002981{
2982 int r;
David Hildenbrande09fefd2015-11-05 09:03:50 +01002983 struct kvm_vcpu *vcpu;
Sean Christopherson8bd826d2019-12-18 13:55:30 -08002984 struct page *page;
Avi Kivityc5ea7662007-02-20 18:41:05 +02002985
Greg Kurz0b1b1df2016-05-09 18:13:37 +02002986 if (id >= KVM_MAX_VCPU_ID)
Andy Honig338c7db2013-11-18 16:09:22 -08002987 return -EINVAL;
2988
Paolo Bonzini6c7caeb2016-06-13 14:48:25 +02002989 mutex_lock(&kvm->lock);
2990 if (kvm->created_vcpus == KVM_MAX_VCPUS) {
2991 mutex_unlock(&kvm->lock);
2992 return -EINVAL;
2993 }
2994
2995 kvm->created_vcpus++;
2996 mutex_unlock(&kvm->lock);
2997
Sean Christopherson897cc382019-12-18 13:55:09 -08002998 r = kvm_arch_vcpu_precreate(kvm, id);
2999 if (r)
3000 goto vcpu_decrement;
3001
Sean Christophersone529ef62019-12-18 13:55:15 -08003002 vcpu = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
3003 if (!vcpu) {
3004 r = -ENOMEM;
Paolo Bonzini6c7caeb2016-06-13 14:48:25 +02003005 goto vcpu_decrement;
3006 }
Avi Kivityc5ea7662007-02-20 18:41:05 +02003007
Peter Xufcd97ad2020-01-09 09:57:12 -05003008 BUILD_BUG_ON(sizeof(struct kvm_run) > PAGE_SIZE);
Sean Christopherson8bd826d2019-12-18 13:55:30 -08003009 page = alloc_page(GFP_KERNEL | __GFP_ZERO);
3010 if (!page) {
3011 r = -ENOMEM;
Sean Christophersone529ef62019-12-18 13:55:15 -08003012 goto vcpu_free;
Sean Christopherson8bd826d2019-12-18 13:55:30 -08003013 }
3014 vcpu->run = page_address(page);
3015
3016 kvm_vcpu_init(vcpu, kvm, id);
Sean Christophersone529ef62019-12-18 13:55:15 -08003017
3018 r = kvm_arch_vcpu_create(vcpu);
3019 if (r)
Sean Christopherson8bd826d2019-12-18 13:55:30 -08003020 goto vcpu_free_run_page;
Sean Christophersone529ef62019-12-18 13:55:15 -08003021
Greg KH3e7093d2019-07-31 20:56:20 +02003022 kvm_create_vcpu_debugfs(vcpu);
Luiz Capitulino45b59392016-09-16 10:27:35 -04003023
Shaohua Li11ec2802007-07-23 14:51:37 +08003024 mutex_lock(&kvm->lock);
David Hildenbrande09fefd2015-11-05 09:03:50 +01003025 if (kvm_get_vcpu_by_id(kvm, id)) {
3026 r = -EEXIST;
3027 goto unlock_vcpu_destroy;
3028 }
Gleb Natapov73880c82009-06-09 15:56:28 +03003029
Radim Krčmář8750e722019-11-07 07:53:42 -05003030 vcpu->vcpu_idx = atomic_read(&kvm->online_vcpus);
3031 BUG_ON(kvm->vcpus[vcpu->vcpu_idx]);
Rusty Russellfb3f0f52007-07-27 17:16:56 +10003032
3033 /* Now it's all set up, let userspace reach it */
Al Viro66c0b392008-04-19 20:33:56 +01003034 kvm_get_kvm(kvm);
Avi Kivitybccf2152007-02-21 18:04:26 +02003035 r = create_vcpu_fd(vcpu);
Gleb Natapov73880c82009-06-09 15:56:28 +03003036 if (r < 0) {
Sean Christopherson149487b2019-10-21 15:58:42 -07003037 kvm_put_kvm_no_destroy(kvm);
Jan Kiszkad7805922011-05-23 10:33:05 +02003038 goto unlock_vcpu_destroy;
Gleb Natapov73880c82009-06-09 15:56:28 +03003039 }
3040
Radim Krčmář8750e722019-11-07 07:53:42 -05003041 kvm->vcpus[vcpu->vcpu_idx] = vcpu;
Paolo Bonzinidd489242015-07-29 11:32:20 +02003042
3043 /*
3044 * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
3045 * before kvm->online_vcpu's incremented value.
3046 */
Gleb Natapov73880c82009-06-09 15:56:28 +03003047 smp_wmb();
3048 atomic_inc(&kvm->online_vcpus);
3049
Gleb Natapov73880c82009-06-09 15:56:28 +03003050 mutex_unlock(&kvm->lock);
Marcelo Tosatti42897d82012-11-27 23:29:02 -02003051 kvm_arch_vcpu_postcreate(vcpu);
Avi Kivitybccf2152007-02-21 18:04:26 +02003052 return r;
Avi Kivityc5ea7662007-02-20 18:41:05 +02003053
Jan Kiszkad7805922011-05-23 10:33:05 +02003054unlock_vcpu_destroy:
Glauber Costa7d8fece2008-09-17 23:16:59 -03003055 mutex_unlock(&kvm->lock);
Luiz Capitulino45b59392016-09-16 10:27:35 -04003056 debugfs_remove_recursive(vcpu->debugfs_dentry);
Hollis Blanchardd40ccc62007-11-19 14:04:43 -06003057 kvm_arch_vcpu_destroy(vcpu);
Sean Christopherson8bd826d2019-12-18 13:55:30 -08003058vcpu_free_run_page:
3059 free_page((unsigned long)vcpu->run);
Sean Christophersone529ef62019-12-18 13:55:15 -08003060vcpu_free:
3061 kmem_cache_free(kvm_vcpu_cache, vcpu);
Paolo Bonzini6c7caeb2016-06-13 14:48:25 +02003062vcpu_decrement:
3063 mutex_lock(&kvm->lock);
3064 kvm->created_vcpus--;
3065 mutex_unlock(&kvm->lock);
Avi Kivityc5ea7662007-02-20 18:41:05 +02003066 return r;
3067}
3068
Avi Kivity1961d272007-03-05 19:46:05 +02003069static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
3070{
3071 if (sigset) {
3072 sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
3073 vcpu->sigset_active = 1;
3074 vcpu->sigset = *sigset;
3075 } else
3076 vcpu->sigset_active = 0;
3077 return 0;
3078}
3079
Avi Kivitybccf2152007-02-21 18:04:26 +02003080static long kvm_vcpu_ioctl(struct file *filp,
3081 unsigned int ioctl, unsigned long arg)
Avi Kivity6aa8b732006-12-10 02:21:36 -08003082{
Avi Kivitybccf2152007-02-21 18:04:26 +02003083 struct kvm_vcpu *vcpu = filp->private_data;
Al Viro2f3669872007-02-09 16:38:35 +00003084 void __user *argp = (void __user *)arg;
Carsten Otte313a3dc2007-10-11 19:16:52 +02003085 int r;
Dave Hansenfa3795a2008-08-11 10:01:46 -07003086 struct kvm_fpu *fpu = NULL;
3087 struct kvm_sregs *kvm_sregs = NULL;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003088
Avi Kivity6d4e4c42007-11-21 16:41:05 +02003089 if (vcpu->kvm->mm != current->mm)
3090 return -EIO;
Avi Kivity2122ff52010-05-13 11:25:04 +03003091
David Matlack2ea75be2014-09-19 16:03:25 -07003092 if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
3093 return -EINVAL;
3094
Avi Kivity2122ff52010-05-13 11:25:04 +03003095 /*
Paolo Bonzini5cb09442017-12-12 17:41:34 +01003096 * Some architectures have vcpu ioctls that are asynchronous to vcpu
3097 * execution; mutex_lock() would break them.
Avi Kivity2122ff52010-05-13 11:25:04 +03003098 */
Paolo Bonzini5cb09442017-12-12 17:41:34 +01003099 r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
3100 if (r != -ENOIOCTLCMD)
Michael S. Tsirkin9fc77442012-09-16 11:50:30 +03003101 return r;
Avi Kivity2122ff52010-05-13 11:25:04 +03003102
Christoffer Dallec7660c2017-12-04 21:35:23 +01003103 if (mutex_lock_killable(&vcpu->mutex))
3104 return -EINTR;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003105 switch (ioctl) {
Christian Borntraeger0e4524a2017-07-06 14:44:28 +02003106 case KVM_RUN: {
3107 struct pid *oldpid;
Avi Kivityf0fe5102007-03-07 13:11:17 +02003108 r = -EINVAL;
3109 if (arg)
3110 goto out;
Christian Borntraeger0e4524a2017-07-06 14:44:28 +02003111 oldpid = rcu_access_pointer(vcpu->pid);
Eric W. Biederman71dbc8a2017-07-16 21:39:32 -05003112 if (unlikely(oldpid != task_pid(current))) {
Christian Borntraeger7a72f7a2014-08-05 16:44:14 +02003113 /* The thread running this VCPU changed. */
Christoffer Dallbd2a6392018-02-23 17:23:57 +01003114 struct pid *newpid;
Xiubo Lif95ef0cd2015-02-26 14:58:23 +08003115
Christoffer Dallbd2a6392018-02-23 17:23:57 +01003116 r = kvm_arch_vcpu_run_pid_change(vcpu);
3117 if (r)
3118 break;
3119
3120 newpid = get_task_pid(current, PIDTYPE_PID);
Christian Borntraeger7a72f7a2014-08-05 16:44:14 +02003121 rcu_assign_pointer(vcpu->pid, newpid);
3122 if (oldpid)
3123 synchronize_rcu();
3124 put_pid(oldpid);
3125 }
Hollis Blanchardb6c7a5d2007-11-01 14:16:10 -05003126 r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
Gleb Natapov64be5002010-10-24 16:49:08 +02003127 trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003128 break;
Christian Borntraeger0e4524a2017-07-06 14:44:28 +02003129 }
Avi Kivity6aa8b732006-12-10 02:21:36 -08003130 case KVM_GET_REGS: {
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003131 struct kvm_regs *kvm_regs;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003132
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003133 r = -ENOMEM;
Ben Gardonb12ce362019-02-11 11:02:49 -08003134 kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL_ACCOUNT);
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003135 if (!kvm_regs)
3136 goto out;
3137 r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003138 if (r)
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003139 goto out_free1;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003140 r = -EFAULT;
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003141 if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
3142 goto out_free1;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003143 r = 0;
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003144out_free1:
3145 kfree(kvm_regs);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003146 break;
3147 }
3148 case KVM_SET_REGS: {
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003149 struct kvm_regs *kvm_regs;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003150
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003151 r = -ENOMEM;
Sasha Levinff5c2c02011-12-04 19:36:29 +02003152 kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
3153 if (IS_ERR(kvm_regs)) {
3154 r = PTR_ERR(kvm_regs);
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003155 goto out;
Sasha Levinff5c2c02011-12-04 19:36:29 +02003156 }
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003157 r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
Xiantao Zhang3e4bb3a2008-02-25 18:52:20 +08003158 kfree(kvm_regs);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003159 break;
3160 }
3161 case KVM_GET_SREGS: {
Ben Gardonb12ce362019-02-11 11:02:49 -08003162 kvm_sregs = kzalloc(sizeof(struct kvm_sregs),
3163 GFP_KERNEL_ACCOUNT);
Dave Hansenfa3795a2008-08-11 10:01:46 -07003164 r = -ENOMEM;
3165 if (!kvm_sregs)
3166 goto out;
3167 r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003168 if (r)
3169 goto out;
3170 r = -EFAULT;
Dave Hansenfa3795a2008-08-11 10:01:46 -07003171 if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
Avi Kivity6aa8b732006-12-10 02:21:36 -08003172 goto out;
3173 r = 0;
3174 break;
3175 }
3176 case KVM_SET_SREGS: {
Sasha Levinff5c2c02011-12-04 19:36:29 +02003177 kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
3178 if (IS_ERR(kvm_sregs)) {
3179 r = PTR_ERR(kvm_sregs);
Guo Chao18595412012-11-02 18:33:21 +08003180 kvm_sregs = NULL;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003181 goto out;
Sasha Levinff5c2c02011-12-04 19:36:29 +02003182 }
Dave Hansenfa3795a2008-08-11 10:01:46 -07003183 r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003184 break;
3185 }
Marcelo Tosatti62d9f0d2008-04-11 13:24:45 -03003186 case KVM_GET_MP_STATE: {
3187 struct kvm_mp_state mp_state;
3188
3189 r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
3190 if (r)
3191 goto out;
3192 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003193 if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
Marcelo Tosatti62d9f0d2008-04-11 13:24:45 -03003194 goto out;
3195 r = 0;
3196 break;
3197 }
3198 case KVM_SET_MP_STATE: {
3199 struct kvm_mp_state mp_state;
3200
3201 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003202 if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
Marcelo Tosatti62d9f0d2008-04-11 13:24:45 -03003203 goto out;
3204 r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
Marcelo Tosatti62d9f0d2008-04-11 13:24:45 -03003205 break;
3206 }
Avi Kivity6aa8b732006-12-10 02:21:36 -08003207 case KVM_TRANSLATE: {
3208 struct kvm_translation tr;
3209
3210 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003211 if (copy_from_user(&tr, argp, sizeof(tr)))
Avi Kivity6aa8b732006-12-10 02:21:36 -08003212 goto out;
Zhang Xiantao8b006792007-11-16 13:05:55 +08003213 r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003214 if (r)
3215 goto out;
3216 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003217 if (copy_to_user(argp, &tr, sizeof(tr)))
Avi Kivity6aa8b732006-12-10 02:21:36 -08003218 goto out;
3219 r = 0;
3220 break;
3221 }
Jan Kiszkad0bfb942008-12-15 13:52:10 +01003222 case KVM_SET_GUEST_DEBUG: {
3223 struct kvm_guest_debug dbg;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003224
3225 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003226 if (copy_from_user(&dbg, argp, sizeof(dbg)))
Avi Kivity6aa8b732006-12-10 02:21:36 -08003227 goto out;
Jan Kiszkad0bfb942008-12-15 13:52:10 +01003228 r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003229 break;
3230 }
Avi Kivity1961d272007-03-05 19:46:05 +02003231 case KVM_SET_SIGNAL_MASK: {
3232 struct kvm_signal_mask __user *sigmask_arg = argp;
3233 struct kvm_signal_mask kvm_sigmask;
3234 sigset_t sigset, *p;
3235
3236 p = NULL;
3237 if (argp) {
3238 r = -EFAULT;
3239 if (copy_from_user(&kvm_sigmask, argp,
Xiubo Li893bdbf2015-02-26 14:58:19 +08003240 sizeof(kvm_sigmask)))
Avi Kivity1961d272007-03-05 19:46:05 +02003241 goto out;
3242 r = -EINVAL;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003243 if (kvm_sigmask.len != sizeof(sigset))
Avi Kivity1961d272007-03-05 19:46:05 +02003244 goto out;
3245 r = -EFAULT;
3246 if (copy_from_user(&sigset, sigmask_arg->sigset,
Xiubo Li893bdbf2015-02-26 14:58:19 +08003247 sizeof(sigset)))
Avi Kivity1961d272007-03-05 19:46:05 +02003248 goto out;
3249 p = &sigset;
3250 }
Andi Kleen376d41f2010-06-10 13:10:47 +02003251 r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
Avi Kivity1961d272007-03-05 19:46:05 +02003252 break;
3253 }
Avi Kivityb8836732007-04-01 16:34:31 +03003254 case KVM_GET_FPU: {
Ben Gardonb12ce362019-02-11 11:02:49 -08003255 fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL_ACCOUNT);
Dave Hansenfa3795a2008-08-11 10:01:46 -07003256 r = -ENOMEM;
3257 if (!fpu)
3258 goto out;
3259 r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
Avi Kivityb8836732007-04-01 16:34:31 +03003260 if (r)
3261 goto out;
3262 r = -EFAULT;
Dave Hansenfa3795a2008-08-11 10:01:46 -07003263 if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
Avi Kivityb8836732007-04-01 16:34:31 +03003264 goto out;
3265 r = 0;
3266 break;
3267 }
3268 case KVM_SET_FPU: {
Sasha Levinff5c2c02011-12-04 19:36:29 +02003269 fpu = memdup_user(argp, sizeof(*fpu));
3270 if (IS_ERR(fpu)) {
3271 r = PTR_ERR(fpu);
Guo Chao18595412012-11-02 18:33:21 +08003272 fpu = NULL;
Avi Kivityb8836732007-04-01 16:34:31 +03003273 goto out;
Sasha Levinff5c2c02011-12-04 19:36:29 +02003274 }
Dave Hansenfa3795a2008-08-11 10:01:46 -07003275 r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
Avi Kivityb8836732007-04-01 16:34:31 +03003276 break;
3277 }
Avi Kivitybccf2152007-02-21 18:04:26 +02003278 default:
Carsten Otte313a3dc2007-10-11 19:16:52 +02003279 r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
Avi Kivitybccf2152007-02-21 18:04:26 +02003280 }
3281out:
Christoffer Dallec7660c2017-12-04 21:35:23 +01003282 mutex_unlock(&vcpu->mutex);
Dave Hansenfa3795a2008-08-11 10:01:46 -07003283 kfree(fpu);
3284 kfree(kvm_sregs);
Avi Kivitybccf2152007-02-21 18:04:26 +02003285 return r;
3286}
3287
Christian Borntraegerde8e5d72015-02-03 09:35:15 +01003288#ifdef CONFIG_KVM_COMPAT
Alexander Graf1dda6062011-06-08 02:45:37 +02003289static long kvm_vcpu_compat_ioctl(struct file *filp,
3290 unsigned int ioctl, unsigned long arg)
3291{
3292 struct kvm_vcpu *vcpu = filp->private_data;
3293 void __user *argp = compat_ptr(arg);
3294 int r;
3295
3296 if (vcpu->kvm->mm != current->mm)
3297 return -EIO;
3298
3299 switch (ioctl) {
3300 case KVM_SET_SIGNAL_MASK: {
3301 struct kvm_signal_mask __user *sigmask_arg = argp;
3302 struct kvm_signal_mask kvm_sigmask;
Alexander Graf1dda6062011-06-08 02:45:37 +02003303 sigset_t sigset;
3304
3305 if (argp) {
3306 r = -EFAULT;
3307 if (copy_from_user(&kvm_sigmask, argp,
Xiubo Li893bdbf2015-02-26 14:58:19 +08003308 sizeof(kvm_sigmask)))
Alexander Graf1dda6062011-06-08 02:45:37 +02003309 goto out;
3310 r = -EINVAL;
Al Viro3968cf62017-09-03 21:45:17 -04003311 if (kvm_sigmask.len != sizeof(compat_sigset_t))
Alexander Graf1dda6062011-06-08 02:45:37 +02003312 goto out;
3313 r = -EFAULT;
Al Viro3968cf62017-09-03 21:45:17 -04003314 if (get_compat_sigset(&sigset, (void *)sigmask_arg->sigset))
Alexander Graf1dda6062011-06-08 02:45:37 +02003315 goto out;
Alan Cox760a9a32012-08-22 14:34:11 +01003316 r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
3317 } else
3318 r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
Alexander Graf1dda6062011-06-08 02:45:37 +02003319 break;
3320 }
3321 default:
3322 r = kvm_vcpu_ioctl(filp, ioctl, arg);
3323 }
3324
3325out:
3326 return r;
3327}
3328#endif
3329
Cédric Le Goatera1cd3f02019-04-18 12:39:36 +02003330static int kvm_device_mmap(struct file *filp, struct vm_area_struct *vma)
3331{
3332 struct kvm_device *dev = filp->private_data;
3333
3334 if (dev->ops->mmap)
3335 return dev->ops->mmap(dev, vma);
3336
3337 return -ENODEV;
3338}
3339
Scott Wood852b6d52013-04-12 14:08:42 +00003340static int kvm_device_ioctl_attr(struct kvm_device *dev,
3341 int (*accessor)(struct kvm_device *dev,
3342 struct kvm_device_attr *attr),
3343 unsigned long arg)
3344{
3345 struct kvm_device_attr attr;
3346
3347 if (!accessor)
3348 return -EPERM;
3349
3350 if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
3351 return -EFAULT;
3352
3353 return accessor(dev, &attr);
3354}
3355
3356static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
3357 unsigned long arg)
3358{
3359 struct kvm_device *dev = filp->private_data;
3360
Sean Christophersonddba9182019-02-15 12:48:39 -08003361 if (dev->kvm->mm != current->mm)
3362 return -EIO;
3363
Scott Wood852b6d52013-04-12 14:08:42 +00003364 switch (ioctl) {
3365 case KVM_SET_DEVICE_ATTR:
3366 return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
3367 case KVM_GET_DEVICE_ATTR:
3368 return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
3369 case KVM_HAS_DEVICE_ATTR:
3370 return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
3371 default:
3372 if (dev->ops->ioctl)
3373 return dev->ops->ioctl(dev, ioctl, arg);
3374
3375 return -ENOTTY;
3376 }
3377}
3378
Scott Wood852b6d52013-04-12 14:08:42 +00003379static int kvm_device_release(struct inode *inode, struct file *filp)
3380{
3381 struct kvm_device *dev = filp->private_data;
3382 struct kvm *kvm = dev->kvm;
3383
Cédric Le Goater2bde9b32019-04-18 12:39:41 +02003384 if (dev->ops->release) {
3385 mutex_lock(&kvm->lock);
3386 list_del(&dev->vm_node);
3387 dev->ops->release(dev);
3388 mutex_unlock(&kvm->lock);
3389 }
3390
Scott Wood852b6d52013-04-12 14:08:42 +00003391 kvm_put_kvm(kvm);
3392 return 0;
3393}
3394
3395static const struct file_operations kvm_device_fops = {
3396 .unlocked_ioctl = kvm_device_ioctl,
3397 .release = kvm_device_release,
Marc Zyngier7ddfd3e2018-06-17 10:16:21 +01003398 KVM_COMPAT(kvm_device_ioctl),
Cédric Le Goatera1cd3f02019-04-18 12:39:36 +02003399 .mmap = kvm_device_mmap,
Scott Wood852b6d52013-04-12 14:08:42 +00003400};
3401
3402struct kvm_device *kvm_device_from_filp(struct file *filp)
3403{
3404 if (filp->f_op != &kvm_device_fops)
3405 return NULL;
3406
3407 return filp->private_data;
3408}
3409
Steven Price8538cb22019-10-21 16:28:19 +01003410static const struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
Will Deacond60eacb2014-09-02 10:27:33 +01003411#ifdef CONFIG_KVM_MPIC
3412 [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
3413 [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
3414#endif
Will Deacond60eacb2014-09-02 10:27:33 +01003415};
3416
Steven Price8538cb22019-10-21 16:28:19 +01003417int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type)
Will Deacond60eacb2014-09-02 10:27:33 +01003418{
3419 if (type >= ARRAY_SIZE(kvm_device_ops_table))
3420 return -ENOSPC;
3421
3422 if (kvm_device_ops_table[type] != NULL)
3423 return -EEXIST;
3424
3425 kvm_device_ops_table[type] = ops;
3426 return 0;
3427}
3428
Wanpeng Li571ee1b2014-10-09 18:30:08 +08003429void kvm_unregister_device_ops(u32 type)
3430{
3431 if (kvm_device_ops_table[type] != NULL)
3432 kvm_device_ops_table[type] = NULL;
3433}
3434
Scott Wood852b6d52013-04-12 14:08:42 +00003435static int kvm_ioctl_create_device(struct kvm *kvm,
3436 struct kvm_create_device *cd)
3437{
Steven Price8538cb22019-10-21 16:28:19 +01003438 const struct kvm_device_ops *ops = NULL;
Scott Wood852b6d52013-04-12 14:08:42 +00003439 struct kvm_device *dev;
3440 bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
Paolo Bonzini1d487e92019-04-11 11:16:47 +02003441 int type;
Scott Wood852b6d52013-04-12 14:08:42 +00003442 int ret;
3443
Will Deacond60eacb2014-09-02 10:27:33 +01003444 if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
Scott Wood852b6d52013-04-12 14:08:42 +00003445 return -ENODEV;
Will Deacond60eacb2014-09-02 10:27:33 +01003446
Paolo Bonzini1d487e92019-04-11 11:16:47 +02003447 type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
3448 ops = kvm_device_ops_table[type];
Will Deacond60eacb2014-09-02 10:27:33 +01003449 if (ops == NULL)
3450 return -ENODEV;
Scott Wood852b6d52013-04-12 14:08:42 +00003451
3452 if (test)
3453 return 0;
3454
Ben Gardonb12ce362019-02-11 11:02:49 -08003455 dev = kzalloc(sizeof(*dev), GFP_KERNEL_ACCOUNT);
Scott Wood852b6d52013-04-12 14:08:42 +00003456 if (!dev)
3457 return -ENOMEM;
3458
3459 dev->ops = ops;
3460 dev->kvm = kvm;
Scott Wood852b6d52013-04-12 14:08:42 +00003461
Christoffer Dalla28ebea2016-08-09 19:13:01 +02003462 mutex_lock(&kvm->lock);
Paolo Bonzini1d487e92019-04-11 11:16:47 +02003463 ret = ops->create(dev, type);
Scott Wood852b6d52013-04-12 14:08:42 +00003464 if (ret < 0) {
Christoffer Dalla28ebea2016-08-09 19:13:01 +02003465 mutex_unlock(&kvm->lock);
Scott Wood852b6d52013-04-12 14:08:42 +00003466 kfree(dev);
3467 return ret;
3468 }
Christoffer Dalla28ebea2016-08-09 19:13:01 +02003469 list_add(&dev->vm_node, &kvm->devices);
3470 mutex_unlock(&kvm->lock);
Scott Wood852b6d52013-04-12 14:08:42 +00003471
Christoffer Dall023e9fd2016-08-09 19:13:00 +02003472 if (ops->init)
3473 ops->init(dev);
3474
Jann Horncfa39382019-01-26 01:54:33 +01003475 kvm_get_kvm(kvm);
Yann Droneaud24009b02013-08-24 22:14:07 +02003476 ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
Scott Wood852b6d52013-04-12 14:08:42 +00003477 if (ret < 0) {
Sean Christopherson149487b2019-10-21 15:58:42 -07003478 kvm_put_kvm_no_destroy(kvm);
Christoffer Dalla28ebea2016-08-09 19:13:01 +02003479 mutex_lock(&kvm->lock);
3480 list_del(&dev->vm_node);
3481 mutex_unlock(&kvm->lock);
Dan Carpentera0f1d212016-11-30 22:21:05 +03003482 ops->destroy(dev);
Scott Wood852b6d52013-04-12 14:08:42 +00003483 return ret;
3484 }
3485
Scott Wood852b6d52013-04-12 14:08:42 +00003486 cd->fd = ret;
3487 return 0;
3488}
3489
Alexander Graf92b591a2014-07-14 18:33:08 +02003490static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
3491{
3492 switch (arg) {
3493 case KVM_CAP_USER_MEMORY:
3494 case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
3495 case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
Alexander Graf92b591a2014-07-14 18:33:08 +02003496 case KVM_CAP_INTERNAL_ERROR_DATA:
3497#ifdef CONFIG_HAVE_KVM_MSI
3498 case KVM_CAP_SIGNAL_MSI:
3499#endif
Paul Mackerras297e2102014-06-30 20:51:13 +10003500#ifdef CONFIG_HAVE_KVM_IRQFD
Paolo Bonzinidc9be0f2015-03-05 11:54:46 +01003501 case KVM_CAP_IRQFD:
Alexander Graf92b591a2014-07-14 18:33:08 +02003502 case KVM_CAP_IRQFD_RESAMPLE:
3503#endif
Jason Wange9ea5062015-09-15 14:41:59 +08003504 case KVM_CAP_IOEVENTFD_ANY_LENGTH:
Alexander Graf92b591a2014-07-14 18:33:08 +02003505 case KVM_CAP_CHECK_EXTENSION_VM:
Paolo Bonzinie5d83c72017-02-16 10:40:56 +01003506 case KVM_CAP_ENABLE_CAP_VM:
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02003507#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
Peter Xud7547c52019-05-08 17:15:47 +08003508 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02003509#endif
Alexander Graf92b591a2014-07-14 18:33:08 +02003510 return 1;
Paolo Bonzini4b4357e2017-03-31 13:53:23 +02003511#ifdef CONFIG_KVM_MMIO
Paolo Bonzini30422552017-03-31 13:53:22 +02003512 case KVM_CAP_COALESCED_MMIO:
3513 return KVM_COALESCED_MMIO_PAGE_OFFSET;
Peng Hao0804c842018-10-14 07:09:55 +08003514 case KVM_CAP_COALESCED_PIO:
3515 return 1;
Paolo Bonzini30422552017-03-31 13:53:22 +02003516#endif
Alexander Graf92b591a2014-07-14 18:33:08 +02003517#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3518 case KVM_CAP_IRQ_ROUTING:
3519 return KVM_MAX_IRQ_ROUTES;
3520#endif
Paolo Bonzinif481b062015-05-17 17:30:37 +02003521#if KVM_ADDRESS_SPACE_NUM > 1
3522 case KVM_CAP_MULTI_ADDRESS_SPACE:
3523 return KVM_ADDRESS_SPACE_NUM;
3524#endif
Paolo Bonzinic110ae52019-03-28 17:24:03 +01003525 case KVM_CAP_NR_MEMSLOTS:
3526 return KVM_USER_MEM_SLOTS;
Alexander Graf92b591a2014-07-14 18:33:08 +02003527 default:
3528 break;
3529 }
3530 return kvm_vm_ioctl_check_extension(kvm, arg);
3531}
3532
Paolo Bonzinie5d83c72017-02-16 10:40:56 +01003533int __attribute__((weak)) kvm_vm_ioctl_enable_cap(struct kvm *kvm,
3534 struct kvm_enable_cap *cap)
3535{
3536 return -EINVAL;
3537}
3538
3539static int kvm_vm_ioctl_enable_cap_generic(struct kvm *kvm,
3540 struct kvm_enable_cap *cap)
3541{
3542 switch (cap->cap) {
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02003543#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
Peter Xud7547c52019-05-08 17:15:47 +08003544 case KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2:
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02003545 if (cap->flags || (cap->args[0] & ~1))
3546 return -EINVAL;
3547 kvm->manual_dirty_log_protect = cap->args[0];
3548 return 0;
3549#endif
Paolo Bonzinie5d83c72017-02-16 10:40:56 +01003550 default:
3551 return kvm_vm_ioctl_enable_cap(kvm, cap);
3552 }
3553}
3554
Avi Kivitybccf2152007-02-21 18:04:26 +02003555static long kvm_vm_ioctl(struct file *filp,
3556 unsigned int ioctl, unsigned long arg)
3557{
3558 struct kvm *kvm = filp->private_data;
3559 void __user *argp = (void __user *)arg;
Carsten Otte1fe779f2007-10-29 16:08:35 +01003560 int r;
Avi Kivitybccf2152007-02-21 18:04:26 +02003561
Avi Kivity6d4e4c42007-11-21 16:41:05 +02003562 if (kvm->mm != current->mm)
3563 return -EIO;
Avi Kivitybccf2152007-02-21 18:04:26 +02003564 switch (ioctl) {
3565 case KVM_CREATE_VCPU:
3566 r = kvm_vm_ioctl_create_vcpu(kvm, arg);
Avi Kivitybccf2152007-02-21 18:04:26 +02003567 break;
Paolo Bonzinie5d83c72017-02-16 10:40:56 +01003568 case KVM_ENABLE_CAP: {
3569 struct kvm_enable_cap cap;
3570
3571 r = -EFAULT;
3572 if (copy_from_user(&cap, argp, sizeof(cap)))
3573 goto out;
3574 r = kvm_vm_ioctl_enable_cap_generic(kvm, &cap);
3575 break;
3576 }
Izik Eidus6fc138d2007-10-09 19:20:39 +02003577 case KVM_SET_USER_MEMORY_REGION: {
3578 struct kvm_userspace_memory_region kvm_userspace_mem;
3579
3580 r = -EFAULT;
3581 if (copy_from_user(&kvm_userspace_mem, argp,
Xiubo Li893bdbf2015-02-26 14:58:19 +08003582 sizeof(kvm_userspace_mem)))
Izik Eidus6fc138d2007-10-09 19:20:39 +02003583 goto out;
3584
Takuya Yoshikawa47ae31e2013-02-27 19:43:00 +09003585 r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003586 break;
3587 }
3588 case KVM_GET_DIRTY_LOG: {
3589 struct kvm_dirty_log log;
3590
3591 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003592 if (copy_from_user(&log, argp, sizeof(log)))
Avi Kivity6aa8b732006-12-10 02:21:36 -08003593 goto out;
Avi Kivity2c6f5df2007-02-20 18:27:58 +02003594 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003595 break;
3596 }
Paolo Bonzini2a31b9d2018-10-23 02:36:47 +02003597#ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
3598 case KVM_CLEAR_DIRTY_LOG: {
3599 struct kvm_clear_dirty_log log;
3600
3601 r = -EFAULT;
3602 if (copy_from_user(&log, argp, sizeof(log)))
3603 goto out;
3604 r = kvm_vm_ioctl_clear_dirty_log(kvm, &log);
3605 break;
3606 }
3607#endif
Paolo Bonzini4b4357e2017-03-31 13:53:23 +02003608#ifdef CONFIG_KVM_MMIO
Laurent Vivier5f94c172008-05-30 16:05:54 +02003609 case KVM_REGISTER_COALESCED_MMIO: {
3610 struct kvm_coalesced_mmio_zone zone;
Xiubo Lif95ef0cd2015-02-26 14:58:23 +08003611
Laurent Vivier5f94c172008-05-30 16:05:54 +02003612 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003613 if (copy_from_user(&zone, argp, sizeof(zone)))
Laurent Vivier5f94c172008-05-30 16:05:54 +02003614 goto out;
Laurent Vivier5f94c172008-05-30 16:05:54 +02003615 r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
Laurent Vivier5f94c172008-05-30 16:05:54 +02003616 break;
3617 }
3618 case KVM_UNREGISTER_COALESCED_MMIO: {
3619 struct kvm_coalesced_mmio_zone zone;
Xiubo Lif95ef0cd2015-02-26 14:58:23 +08003620
Laurent Vivier5f94c172008-05-30 16:05:54 +02003621 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003622 if (copy_from_user(&zone, argp, sizeof(zone)))
Laurent Vivier5f94c172008-05-30 16:05:54 +02003623 goto out;
Laurent Vivier5f94c172008-05-30 16:05:54 +02003624 r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
Laurent Vivier5f94c172008-05-30 16:05:54 +02003625 break;
3626 }
3627#endif
Gregory Haskins721eecbf2009-05-20 10:30:49 -04003628 case KVM_IRQFD: {
3629 struct kvm_irqfd data;
3630
3631 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003632 if (copy_from_user(&data, argp, sizeof(data)))
Gregory Haskins721eecbf2009-05-20 10:30:49 -04003633 goto out;
Alex Williamsond4db2932012-06-29 09:56:08 -06003634 r = kvm_irqfd(kvm, &data);
Gregory Haskins721eecbf2009-05-20 10:30:49 -04003635 break;
3636 }
Gregory Haskinsd34e6b12009-07-07 17:08:49 -04003637 case KVM_IOEVENTFD: {
3638 struct kvm_ioeventfd data;
3639
3640 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003641 if (copy_from_user(&data, argp, sizeof(data)))
Gregory Haskinsd34e6b12009-07-07 17:08:49 -04003642 goto out;
3643 r = kvm_ioeventfd(kvm, &data);
3644 break;
3645 }
Jan Kiszka07975ad2012-03-29 21:14:12 +02003646#ifdef CONFIG_HAVE_KVM_MSI
3647 case KVM_SIGNAL_MSI: {
3648 struct kvm_msi msi;
3649
3650 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003651 if (copy_from_user(&msi, argp, sizeof(msi)))
Jan Kiszka07975ad2012-03-29 21:14:12 +02003652 goto out;
3653 r = kvm_send_userspace_msi(kvm, &msi);
3654 break;
3655 }
3656#endif
Christoffer Dall23d43cf2012-07-24 08:51:20 -04003657#ifdef __KVM_HAVE_IRQ_LINE
3658 case KVM_IRQ_LINE_STATUS:
3659 case KVM_IRQ_LINE: {
3660 struct kvm_irq_level irq_event;
3661
3662 r = -EFAULT;
Xiubo Li893bdbf2015-02-26 14:58:19 +08003663 if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
Christoffer Dall23d43cf2012-07-24 08:51:20 -04003664 goto out;
3665
Yang Zhangaa2fbe62013-04-11 19:21:40 +08003666 r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
3667 ioctl == KVM_IRQ_LINE_STATUS);
Christoffer Dall23d43cf2012-07-24 08:51:20 -04003668 if (r)
3669 goto out;
3670
3671 r = -EFAULT;
3672 if (ioctl == KVM_IRQ_LINE_STATUS) {
Xiubo Li893bdbf2015-02-26 14:58:19 +08003673 if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
Christoffer Dall23d43cf2012-07-24 08:51:20 -04003674 goto out;
3675 }
3676
3677 r = 0;
3678 break;
3679 }
3680#endif
Alexander Grafaa8d5942013-04-15 21:12:53 +02003681#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
3682 case KVM_SET_GSI_ROUTING: {
3683 struct kvm_irq_routing routing;
3684 struct kvm_irq_routing __user *urouting;
Paolo Bonzinif8c1b852016-06-01 14:09:22 +02003685 struct kvm_irq_routing_entry *entries = NULL;
Alexander Grafaa8d5942013-04-15 21:12:53 +02003686
3687 r = -EFAULT;
3688 if (copy_from_user(&routing, argp, sizeof(routing)))
3689 goto out;
3690 r = -EINVAL;
David Hildenbrand5c0aea02017-04-28 17:06:20 +02003691 if (!kvm_arch_can_set_irq_routing(kvm))
3692 goto out;
Xiubo Licaf1ff22016-06-15 18:00:33 +08003693 if (routing.nr > KVM_MAX_IRQ_ROUTES)
Alexander Grafaa8d5942013-04-15 21:12:53 +02003694 goto out;
3695 if (routing.flags)
3696 goto out;
Paolo Bonzinif8c1b852016-06-01 14:09:22 +02003697 if (routing.nr) {
3698 r = -ENOMEM;
Kees Cook42bc47b2018-06-12 14:27:11 -07003699 entries = vmalloc(array_size(sizeof(*entries),
3700 routing.nr));
Paolo Bonzinif8c1b852016-06-01 14:09:22 +02003701 if (!entries)
3702 goto out;
3703 r = -EFAULT;
3704 urouting = argp;
3705 if (copy_from_user(entries, urouting->entries,
3706 routing.nr * sizeof(*entries)))
3707 goto out_free_irq_routing;
3708 }
Alexander Grafaa8d5942013-04-15 21:12:53 +02003709 r = kvm_set_irq_routing(kvm, entries, routing.nr,
3710 routing.flags);
Xiubo Lia642a172015-02-26 14:58:20 +08003711out_free_irq_routing:
Alexander Grafaa8d5942013-04-15 21:12:53 +02003712 vfree(entries);
3713 break;
3714 }
3715#endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
Scott Wood852b6d52013-04-12 14:08:42 +00003716 case KVM_CREATE_DEVICE: {
3717 struct kvm_create_device cd;
3718
3719 r = -EFAULT;
3720 if (copy_from_user(&cd, argp, sizeof(cd)))
3721 goto out;
3722
3723 r = kvm_ioctl_create_device(kvm, &cd);
3724 if (r)
3725 goto out;
3726
3727 r = -EFAULT;
3728 if (copy_to_user(argp, &cd, sizeof(cd)))
3729 goto out;
3730
3731 r = 0;
3732 break;
3733 }
Alexander Graf92b591a2014-07-14 18:33:08 +02003734 case KVM_CHECK_EXTENSION:
3735 r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
3736 break;
Avi Kivityf17abe92007-02-21 19:28:04 +02003737 default:
Carsten Otte1fe779f2007-10-29 16:08:35 +01003738 r = kvm_arch_vm_ioctl(filp, ioctl, arg);
Avi Kivityf17abe92007-02-21 19:28:04 +02003739 }
3740out:
3741 return r;
3742}
3743
Christian Borntraegerde8e5d72015-02-03 09:35:15 +01003744#ifdef CONFIG_KVM_COMPAT
Arnd Bergmann6ff58942009-10-22 14:19:27 +02003745struct compat_kvm_dirty_log {
3746 __u32 slot;
3747 __u32 padding1;
3748 union {
3749 compat_uptr_t dirty_bitmap; /* one bit per page */
3750 __u64 padding2;
3751 };
3752};
3753
3754static long kvm_vm_compat_ioctl(struct file *filp,
3755 unsigned int ioctl, unsigned long arg)
3756{
3757 struct kvm *kvm = filp->private_data;
3758 int r;
3759
3760 if (kvm->mm != current->mm)
3761 return -EIO;
3762 switch (ioctl) {
3763 case KVM_GET_DIRTY_LOG: {
3764 struct compat_kvm_dirty_log compat_log;
3765 struct kvm_dirty_log log;
3766
Arnd Bergmann6ff58942009-10-22 14:19:27 +02003767 if (copy_from_user(&compat_log, (void __user *)arg,
3768 sizeof(compat_log)))
Markus Elfringf6a3b162017-01-22 11:30:21 +01003769 return -EFAULT;
Arnd Bergmann6ff58942009-10-22 14:19:27 +02003770 log.slot = compat_log.slot;
3771 log.padding1 = compat_log.padding1;
3772 log.padding2 = compat_log.padding2;
3773 log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
3774
3775 r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
Arnd Bergmann6ff58942009-10-22 14:19:27 +02003776 break;
3777 }
3778 default:
3779 r = kvm_vm_ioctl(filp, ioctl, arg);
3780 }
Arnd Bergmann6ff58942009-10-22 14:19:27 +02003781 return r;
3782}
3783#endif
3784
Christian Borntraeger3d3aab12008-12-02 11:17:32 +01003785static struct file_operations kvm_vm_fops = {
Avi Kivityf17abe92007-02-21 19:28:04 +02003786 .release = kvm_vm_release,
3787 .unlocked_ioctl = kvm_vm_ioctl,
Arnd Bergmann6038f372010-08-15 18:52:59 +02003788 .llseek = noop_llseek,
Marc Zyngier7ddfd3e2018-06-17 10:16:21 +01003789 KVM_COMPAT(kvm_vm_compat_ioctl),
Avi Kivityf17abe92007-02-21 19:28:04 +02003790};
3791
Carsten Ottee08b9632012-01-04 10:25:20 +01003792static int kvm_dev_ioctl_create_vm(unsigned long type)
Avi Kivityf17abe92007-02-21 19:28:04 +02003793{
Heiko Carstensaac87632010-10-27 17:22:10 +02003794 int r;
Avi Kivityf17abe92007-02-21 19:28:04 +02003795 struct kvm *kvm;
Al Viro506cfba2016-07-14 18:54:17 +02003796 struct file *file;
Avi Kivityf17abe92007-02-21 19:28:04 +02003797
Carsten Ottee08b9632012-01-04 10:25:20 +01003798 kvm = kvm_create_vm(type);
Avi Kivityd6d28162007-06-28 08:38:16 -04003799 if (IS_ERR(kvm))
3800 return PTR_ERR(kvm);
Paolo Bonzini4b4357e2017-03-31 13:53:23 +02003801#ifdef CONFIG_KVM_MMIO
Takuya Yoshikawa6ce5a092010-03-15 22:13:30 +09003802 r = kvm_coalesced_mmio_init(kvm);
Markus Elfring78588332017-11-21 13:40:17 +01003803 if (r < 0)
3804 goto put_kvm;
Takuya Yoshikawa6ce5a092010-03-15 22:13:30 +09003805#endif
Al Viro506cfba2016-07-14 18:54:17 +02003806 r = get_unused_fd_flags(O_CLOEXEC);
Markus Elfring78588332017-11-21 13:40:17 +01003807 if (r < 0)
3808 goto put_kvm;
3809
Al Viro506cfba2016-07-14 18:54:17 +02003810 file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
3811 if (IS_ERR(file)) {
3812 put_unused_fd(r);
Markus Elfring78588332017-11-21 13:40:17 +01003813 r = PTR_ERR(file);
3814 goto put_kvm;
Al Viro506cfba2016-07-14 18:54:17 +02003815 }
Janosch Frank536a6f82016-05-18 13:26:23 +02003816
Paolo Bonzini525df862017-06-27 15:45:09 +02003817 /*
3818 * Don't call kvm_put_kvm anymore at this point; file->f_op is
3819 * already set, with ->release() being kvm_vm_release(). In error
3820 * cases it will be called by the final fput(file) and will take
3821 * care of doing kvm_put_kvm(kvm).
3822 */
Janosch Frank536a6f82016-05-18 13:26:23 +02003823 if (kvm_create_vm_debugfs(kvm, r) < 0) {
Al Viro506cfba2016-07-14 18:54:17 +02003824 put_unused_fd(r);
3825 fput(file);
Janosch Frank536a6f82016-05-18 13:26:23 +02003826 return -ENOMEM;
3827 }
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02003828 kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
Avi Kivityf17abe92007-02-21 19:28:04 +02003829
Al Viro506cfba2016-07-14 18:54:17 +02003830 fd_install(r, file);
Heiko Carstensaac87632010-10-27 17:22:10 +02003831 return r;
Markus Elfring78588332017-11-21 13:40:17 +01003832
3833put_kvm:
3834 kvm_put_kvm(kvm);
3835 return r;
Avi Kivityf17abe92007-02-21 19:28:04 +02003836}
3837
3838static long kvm_dev_ioctl(struct file *filp,
3839 unsigned int ioctl, unsigned long arg)
3840{
Avi Kivity07c45a32007-03-07 13:05:38 +02003841 long r = -EINVAL;
Avi Kivityf17abe92007-02-21 19:28:04 +02003842
3843 switch (ioctl) {
3844 case KVM_GET_API_VERSION:
Avi Kivityf0fe5102007-03-07 13:11:17 +02003845 if (arg)
3846 goto out;
Avi Kivityf17abe92007-02-21 19:28:04 +02003847 r = KVM_API_VERSION;
3848 break;
3849 case KVM_CREATE_VM:
Carsten Ottee08b9632012-01-04 10:25:20 +01003850 r = kvm_dev_ioctl_create_vm(arg);
Avi Kivityf17abe92007-02-21 19:28:04 +02003851 break;
Zhang Xiantao018d00d2007-11-15 23:07:47 +08003852 case KVM_CHECK_EXTENSION:
Alexander Graf784aa3d2014-07-14 18:27:35 +02003853 r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
Avi Kivity5d308f42007-03-01 17:56:20 +02003854 break;
Avi Kivity07c45a32007-03-07 13:05:38 +02003855 case KVM_GET_VCPU_MMAP_SIZE:
Avi Kivity07c45a32007-03-07 13:05:38 +02003856 if (arg)
3857 goto out;
Avi Kivityadb1ff42008-01-24 15:13:08 +02003858 r = PAGE_SIZE; /* struct kvm_run */
3859#ifdef CONFIG_X86
3860 r += PAGE_SIZE; /* pio data page */
3861#endif
Paolo Bonzini4b4357e2017-03-31 13:53:23 +02003862#ifdef CONFIG_KVM_MMIO
Laurent Vivier5f94c172008-05-30 16:05:54 +02003863 r += PAGE_SIZE; /* coalesced mmio ring page */
3864#endif
Avi Kivity07c45a32007-03-07 13:05:38 +02003865 break;
Feng(Eric) Liud4c9ff22008-04-10 08:47:53 -04003866 case KVM_TRACE_ENABLE:
3867 case KVM_TRACE_PAUSE:
3868 case KVM_TRACE_DISABLE:
Marcelo Tosatti2023a292009-06-18 11:47:28 -03003869 r = -EOPNOTSUPP;
Feng(Eric) Liud4c9ff22008-04-10 08:47:53 -04003870 break;
Avi Kivity6aa8b732006-12-10 02:21:36 -08003871 default:
Carsten Otte043405e2007-10-10 17:16:19 +02003872 return kvm_arch_dev_ioctl(filp, ioctl, arg);
Avi Kivity6aa8b732006-12-10 02:21:36 -08003873 }
3874out:
3875 return r;
3876}
3877
Avi Kivity6aa8b732006-12-10 02:21:36 -08003878static struct file_operations kvm_chardev_ops = {
Avi Kivity6aa8b732006-12-10 02:21:36 -08003879 .unlocked_ioctl = kvm_dev_ioctl,
Arnd Bergmann6038f372010-08-15 18:52:59 +02003880 .llseek = noop_llseek,
Marc Zyngier7ddfd3e2018-06-17 10:16:21 +01003881 KVM_COMPAT(kvm_dev_ioctl),
Avi Kivity6aa8b732006-12-10 02:21:36 -08003882};
3883
3884static struct miscdevice kvm_dev = {
Avi Kivitybbe44322007-03-04 13:27:36 +02003885 KVM_MINOR,
Avi Kivity6aa8b732006-12-10 02:21:36 -08003886 "kvm",
3887 &kvm_chardev_ops,
3888};
3889
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09003890static void hardware_enable_nolock(void *junk)
Avi Kivity1b6c0162007-05-24 13:03:52 +03003891{
3892 int cpu = raw_smp_processor_id();
Alexander Graf10474ae2009-09-15 11:37:46 +02003893 int r;
Avi Kivity1b6c0162007-05-24 13:03:52 +03003894
Rusty Russell7f59f492008-12-07 21:25:45 +10303895 if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
Avi Kivity1b6c0162007-05-24 13:03:52 +03003896 return;
Alexander Graf10474ae2009-09-15 11:37:46 +02003897
Rusty Russell7f59f492008-12-07 21:25:45 +10303898 cpumask_set_cpu(cpu, cpus_hardware_enabled);
Alexander Graf10474ae2009-09-15 11:37:46 +02003899
Radim Krčmář13a34e02014-08-28 15:13:03 +02003900 r = kvm_arch_hardware_enable();
Alexander Graf10474ae2009-09-15 11:37:46 +02003901
3902 if (r) {
3903 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
3904 atomic_inc(&hardware_enable_failed);
Xiubo Li1170adc2015-02-26 14:58:26 +08003905 pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
Alexander Graf10474ae2009-09-15 11:37:46 +02003906 }
Avi Kivity1b6c0162007-05-24 13:03:52 +03003907}
3908
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00003909static int kvm_starting_cpu(unsigned int cpu)
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09003910{
Paolo Bonzini4a937f92013-09-10 12:58:35 +02003911 raw_spin_lock(&kvm_count_lock);
Paolo Bonzini4fa92fb2013-09-10 12:57:17 +02003912 if (kvm_usage_count)
3913 hardware_enable_nolock(NULL);
Paolo Bonzini4a937f92013-09-10 12:58:35 +02003914 raw_spin_unlock(&kvm_count_lock);
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00003915 return 0;
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09003916}
3917
3918static void hardware_disable_nolock(void *junk)
Avi Kivity1b6c0162007-05-24 13:03:52 +03003919{
3920 int cpu = raw_smp_processor_id();
3921
Rusty Russell7f59f492008-12-07 21:25:45 +10303922 if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
Avi Kivity1b6c0162007-05-24 13:03:52 +03003923 return;
Rusty Russell7f59f492008-12-07 21:25:45 +10303924 cpumask_clear_cpu(cpu, cpus_hardware_enabled);
Radim Krčmář13a34e02014-08-28 15:13:03 +02003925 kvm_arch_hardware_disable();
Avi Kivity1b6c0162007-05-24 13:03:52 +03003926}
3927
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00003928static int kvm_dying_cpu(unsigned int cpu)
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09003929{
Paolo Bonzini4a937f92013-09-10 12:58:35 +02003930 raw_spin_lock(&kvm_count_lock);
Paolo Bonzini4fa92fb2013-09-10 12:57:17 +02003931 if (kvm_usage_count)
3932 hardware_disable_nolock(NULL);
Paolo Bonzini4a937f92013-09-10 12:58:35 +02003933 raw_spin_unlock(&kvm_count_lock);
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00003934 return 0;
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09003935}
3936
Alexander Graf10474ae2009-09-15 11:37:46 +02003937static void hardware_disable_all_nolock(void)
3938{
3939 BUG_ON(!kvm_usage_count);
3940
3941 kvm_usage_count--;
3942 if (!kvm_usage_count)
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09003943 on_each_cpu(hardware_disable_nolock, NULL, 1);
Alexander Graf10474ae2009-09-15 11:37:46 +02003944}
3945
3946static void hardware_disable_all(void)
3947{
Paolo Bonzini4a937f92013-09-10 12:58:35 +02003948 raw_spin_lock(&kvm_count_lock);
Alexander Graf10474ae2009-09-15 11:37:46 +02003949 hardware_disable_all_nolock();
Paolo Bonzini4a937f92013-09-10 12:58:35 +02003950 raw_spin_unlock(&kvm_count_lock);
Alexander Graf10474ae2009-09-15 11:37:46 +02003951}
3952
3953static int hardware_enable_all(void)
3954{
3955 int r = 0;
3956
Paolo Bonzini4a937f92013-09-10 12:58:35 +02003957 raw_spin_lock(&kvm_count_lock);
Alexander Graf10474ae2009-09-15 11:37:46 +02003958
3959 kvm_usage_count++;
3960 if (kvm_usage_count == 1) {
3961 atomic_set(&hardware_enable_failed, 0);
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09003962 on_each_cpu(hardware_enable_nolock, NULL, 1);
Alexander Graf10474ae2009-09-15 11:37:46 +02003963
3964 if (atomic_read(&hardware_enable_failed)) {
3965 hardware_disable_all_nolock();
3966 r = -EBUSY;
3967 }
3968 }
3969
Paolo Bonzini4a937f92013-09-10 12:58:35 +02003970 raw_spin_unlock(&kvm_count_lock);
Alexander Graf10474ae2009-09-15 11:37:46 +02003971
3972 return r;
3973}
3974
Rusty Russell9a2b85c2007-07-17 23:17:55 +10003975static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
Mike Dayd77c26f2007-10-08 09:02:08 -04003976 void *v)
Rusty Russell9a2b85c2007-07-17 23:17:55 +10003977{
Sheng Yang8e1c1812009-04-29 11:09:04 +08003978 /*
3979 * Some (well, at least mine) BIOSes hang on reboot if
3980 * in vmx root mode.
3981 *
3982 * And Intel TXT required VMX off for all cpu when system shutdown.
3983 */
Xiubo Li1170adc2015-02-26 14:58:26 +08003984 pr_info("kvm: exiting hardware virtualization\n");
Sheng Yang8e1c1812009-04-29 11:09:04 +08003985 kvm_rebooting = true;
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09003986 on_each_cpu(hardware_disable_nolock, NULL, 1);
Rusty Russell9a2b85c2007-07-17 23:17:55 +10003987 return NOTIFY_OK;
3988}
3989
3990static struct notifier_block kvm_reboot_notifier = {
3991 .notifier_call = kvm_reboot,
3992 .priority = 0,
3993};
3994
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02003995static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
Gregory Haskins2eeb2e92007-05-31 14:08:53 -04003996{
3997 int i;
3998
3999 for (i = 0; i < bus->dev_count; i++) {
Sasha Levin743eeb02011-07-27 16:00:48 +03004000 struct kvm_io_device *pos = bus->range[i].dev;
Gregory Haskins2eeb2e92007-05-31 14:08:53 -04004001
4002 kvm_iodevice_destructor(pos);
4003 }
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004004 kfree(bus);
Gregory Haskins2eeb2e92007-05-31 14:08:53 -04004005}
4006
Paolo Bonzinic21fbff2013-08-27 15:41:41 +02004007static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
Xiubo Li20e87b72015-02-26 14:58:25 +08004008 const struct kvm_io_range *r2)
Sasha Levin743eeb02011-07-27 16:00:48 +03004009{
Jason Wang8f4216c72015-09-15 14:41:57 +08004010 gpa_t addr1 = r1->addr;
4011 gpa_t addr2 = r2->addr;
4012
4013 if (addr1 < addr2)
Sasha Levin743eeb02011-07-27 16:00:48 +03004014 return -1;
Jason Wang8f4216c72015-09-15 14:41:57 +08004015
4016 /* If r2->len == 0, match the exact address. If r2->len != 0,
4017 * accept any overlapping write. Any order is acceptable for
4018 * overlapping ranges, because kvm_io_bus_get_first_dev ensures
4019 * we process all of them.
4020 */
4021 if (r2->len) {
4022 addr1 += r1->len;
4023 addr2 += r2->len;
4024 }
4025
4026 if (addr1 > addr2)
Sasha Levin743eeb02011-07-27 16:00:48 +03004027 return 1;
Jason Wang8f4216c72015-09-15 14:41:57 +08004028
Sasha Levin743eeb02011-07-27 16:00:48 +03004029 return 0;
4030}
4031
Paolo Bonzinia343c9b2013-07-16 13:03:29 +02004032static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
4033{
Paolo Bonzinic21fbff2013-08-27 15:41:41 +02004034 return kvm_io_bus_cmp(p1, p2);
Paolo Bonzinia343c9b2013-07-16 13:03:29 +02004035}
4036
Geoff Levand39369f72013-04-05 19:20:30 +00004037static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
Sasha Levin743eeb02011-07-27 16:00:48 +03004038 gpa_t addr, int len)
4039{
4040 struct kvm_io_range *range, key;
4041 int off;
4042
4043 key = (struct kvm_io_range) {
4044 .addr = addr,
4045 .len = len,
4046 };
4047
4048 range = bsearch(&key, bus->range, bus->dev_count,
4049 sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
4050 if (range == NULL)
4051 return -ENOENT;
4052
4053 off = range - bus->range;
4054
Paolo Bonzinic21fbff2013-08-27 15:41:41 +02004055 while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
Sasha Levin743eeb02011-07-27 16:00:48 +03004056 off--;
4057
4058 return off;
4059}
4060
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004061static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
Cornelia Huck126a5af2013-07-03 16:30:53 +02004062 struct kvm_io_range *range, const void *val)
4063{
4064 int idx;
4065
4066 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
4067 if (idx < 0)
4068 return -EOPNOTSUPP;
4069
4070 while (idx < bus->dev_count &&
Paolo Bonzinic21fbff2013-08-27 15:41:41 +02004071 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004072 if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
Cornelia Huck126a5af2013-07-03 16:30:53 +02004073 range->len, val))
4074 return idx;
4075 idx++;
4076 }
4077
4078 return -EOPNOTSUPP;
4079}
4080
Michael S. Tsirkinbda90202009-06-29 22:24:32 +03004081/* kvm_io_bus_write - called under kvm->slots_lock */
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004082int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
Michael S. Tsirkinbda90202009-06-29 22:24:32 +03004083 int len, const void *val)
Gregory Haskins2eeb2e92007-05-31 14:08:53 -04004084{
Cornelia Huck126a5af2013-07-03 16:30:53 +02004085 struct kvm_io_bus *bus;
4086 struct kvm_io_range range;
4087 int r;
4088
4089 range = (struct kvm_io_range) {
4090 .addr = addr,
4091 .len = len,
4092 };
4093
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004094 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
David Hildenbrand90db1042017-03-23 18:24:19 +01004095 if (!bus)
4096 return -ENOMEM;
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004097 r = __kvm_io_bus_write(vcpu, bus, &range, val);
Cornelia Huck126a5af2013-07-03 16:30:53 +02004098 return r < 0 ? r : 0;
4099}
Leo Yana2420102019-02-22 16:10:09 +08004100EXPORT_SYMBOL_GPL(kvm_io_bus_write);
Cornelia Huck126a5af2013-07-03 16:30:53 +02004101
4102/* kvm_io_bus_write_cookie - called under kvm->slots_lock */
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004103int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
4104 gpa_t addr, int len, const void *val, long cookie)
Cornelia Huck126a5af2013-07-03 16:30:53 +02004105{
Lai Jiangshan90d83dc2010-04-19 17:41:23 +08004106 struct kvm_io_bus *bus;
Sasha Levin743eeb02011-07-27 16:00:48 +03004107 struct kvm_io_range range;
4108
4109 range = (struct kvm_io_range) {
4110 .addr = addr,
4111 .len = len,
4112 };
Lai Jiangshan90d83dc2010-04-19 17:41:23 +08004113
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004114 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
David Hildenbrand90db1042017-03-23 18:24:19 +01004115 if (!bus)
4116 return -ENOMEM;
Cornelia Huck126a5af2013-07-03 16:30:53 +02004117
4118 /* First try the device referenced by cookie. */
4119 if ((cookie >= 0) && (cookie < bus->dev_count) &&
Paolo Bonzinic21fbff2013-08-27 15:41:41 +02004120 (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004121 if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
Cornelia Huck126a5af2013-07-03 16:30:53 +02004122 val))
4123 return cookie;
4124
4125 /*
4126 * cookie contained garbage; fall back to search and return the
4127 * correct cookie value.
4128 */
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004129 return __kvm_io_bus_write(vcpu, bus, &range, val);
Cornelia Huck126a5af2013-07-03 16:30:53 +02004130}
4131
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004132static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
4133 struct kvm_io_range *range, void *val)
Cornelia Huck126a5af2013-07-03 16:30:53 +02004134{
4135 int idx;
4136
4137 idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
Sasha Levin743eeb02011-07-27 16:00:48 +03004138 if (idx < 0)
4139 return -EOPNOTSUPP;
4140
4141 while (idx < bus->dev_count &&
Paolo Bonzinic21fbff2013-08-27 15:41:41 +02004142 kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004143 if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
Cornelia Huck126a5af2013-07-03 16:30:53 +02004144 range->len, val))
4145 return idx;
Sasha Levin743eeb02011-07-27 16:00:48 +03004146 idx++;
4147 }
4148
Michael S. Tsirkinbda90202009-06-29 22:24:32 +03004149 return -EOPNOTSUPP;
4150}
Gregory Haskins2eeb2e92007-05-31 14:08:53 -04004151
Michael S. Tsirkinbda90202009-06-29 22:24:32 +03004152/* kvm_io_bus_read - called under kvm->slots_lock */
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004153int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004154 int len, void *val)
Michael S. Tsirkinbda90202009-06-29 22:24:32 +03004155{
Cornelia Huck126a5af2013-07-03 16:30:53 +02004156 struct kvm_io_bus *bus;
4157 struct kvm_io_range range;
4158 int r;
4159
4160 range = (struct kvm_io_range) {
4161 .addr = addr,
4162 .len = len,
4163 };
4164
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004165 bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
David Hildenbrand90db1042017-03-23 18:24:19 +01004166 if (!bus)
4167 return -ENOMEM;
Nikolay Nikolaeve32edf42015-03-26 14:39:28 +00004168 r = __kvm_io_bus_read(vcpu, bus, &range, val);
Cornelia Huck126a5af2013-07-03 16:30:53 +02004169 return r < 0 ? r : 0;
4170}
4171
Marcelo Tosatti79fac952009-12-23 14:35:26 -02004172/* Caller must hold slots_lock. */
Sasha Levin743eeb02011-07-27 16:00:48 +03004173int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
4174 int len, struct kvm_io_device *dev)
Michael S. Tsirkin6c474692009-06-29 22:24:26 +03004175{
Gal Hammerd4c67a72018-01-16 15:34:41 +02004176 int i;
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004177 struct kvm_io_bus *new_bus, *bus;
Gal Hammerd4c67a72018-01-16 15:34:41 +02004178 struct kvm_io_range range;
Gregory Haskins090b7af2009-07-07 17:08:44 -04004179
Christian Borntraeger4a12f952017-07-07 10:51:38 +02004180 bus = kvm_get_bus(kvm, bus_idx);
David Hildenbrand90db1042017-03-23 18:24:19 +01004181 if (!bus)
4182 return -ENOMEM;
4183
Amos Kong6ea34c92013-05-25 06:44:15 +08004184 /* exclude ioeventfd which is limited by maximum fd */
4185 if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
Gregory Haskins090b7af2009-07-07 17:08:44 -04004186 return -ENOSPC;
4187
Gustavo A. R. Silva90952cd2019-01-30 17:07:47 +01004188 new_bus = kmalloc(struct_size(bus, range, bus->dev_count + 1),
Ben Gardonb12ce362019-02-11 11:02:49 -08004189 GFP_KERNEL_ACCOUNT);
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004190 if (!new_bus)
4191 return -ENOMEM;
Gal Hammerd4c67a72018-01-16 15:34:41 +02004192
4193 range = (struct kvm_io_range) {
4194 .addr = addr,
4195 .len = len,
4196 .dev = dev,
4197 };
4198
4199 for (i = 0; i < bus->dev_count; i++)
4200 if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
4201 break;
4202
4203 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
4204 new_bus->dev_count++;
4205 new_bus->range[i] = range;
4206 memcpy(new_bus->range + i + 1, bus->range + i,
4207 (bus->dev_count - i) * sizeof(struct kvm_io_range));
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004208 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4209 synchronize_srcu_expedited(&kvm->srcu);
4210 kfree(bus);
Gregory Haskins090b7af2009-07-07 17:08:44 -04004211
4212 return 0;
4213}
4214
Marcelo Tosatti79fac952009-12-23 14:35:26 -02004215/* Caller must hold slots_lock. */
David Hildenbrand90db1042017-03-23 18:24:19 +01004216void kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4217 struct kvm_io_device *dev)
Gregory Haskins090b7af2009-07-07 17:08:44 -04004218{
David Hildenbrand90db1042017-03-23 18:24:19 +01004219 int i;
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004220 struct kvm_io_bus *new_bus, *bus;
Michael S. Tsirkin6c474692009-06-29 22:24:26 +03004221
Christian Borntraeger4a12f952017-07-07 10:51:38 +02004222 bus = kvm_get_bus(kvm, bus_idx);
Peter Xudf630b82017-03-15 16:01:17 +08004223 if (!bus)
David Hildenbrand90db1042017-03-23 18:24:19 +01004224 return;
Peter Xudf630b82017-03-15 16:01:17 +08004225
Amos Konga13007162012-03-09 12:17:32 +08004226 for (i = 0; i < bus->dev_count; i++)
4227 if (bus->range[i].dev == dev) {
Gregory Haskins090b7af2009-07-07 17:08:44 -04004228 break;
4229 }
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004230
David Hildenbrand90db1042017-03-23 18:24:19 +01004231 if (i == bus->dev_count)
4232 return;
Amos Konga13007162012-03-09 12:17:32 +08004233
Gustavo A. R. Silva90952cd2019-01-30 17:07:47 +01004234 new_bus = kmalloc(struct_size(bus, range, bus->dev_count - 1),
Ben Gardonb12ce362019-02-11 11:02:49 -08004235 GFP_KERNEL_ACCOUNT);
David Hildenbrand90db1042017-03-23 18:24:19 +01004236 if (!new_bus) {
4237 pr_err("kvm: failed to shrink bus, removing it completely\n");
4238 goto broken;
4239 }
Amos Konga13007162012-03-09 12:17:32 +08004240
4241 memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
4242 new_bus->dev_count--;
4243 memcpy(new_bus->range + i, bus->range + i + 1,
4244 (new_bus->dev_count - i) * sizeof(struct kvm_io_range));
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004245
David Hildenbrand90db1042017-03-23 18:24:19 +01004246broken:
Marcelo Tosattie93f8a02009-12-23 14:35:24 -02004247 rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
4248 synchronize_srcu_expedited(&kvm->srcu);
4249 kfree(bus);
David Hildenbrand90db1042017-03-23 18:24:19 +01004250 return;
Gregory Haskins2eeb2e92007-05-31 14:08:53 -04004251}
4252
Andre Przywara8a39d002016-07-15 12:43:26 +01004253struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
4254 gpa_t addr)
4255{
4256 struct kvm_io_bus *bus;
4257 int dev_idx, srcu_idx;
4258 struct kvm_io_device *iodev = NULL;
4259
4260 srcu_idx = srcu_read_lock(&kvm->srcu);
4261
4262 bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
David Hildenbrand90db1042017-03-23 18:24:19 +01004263 if (!bus)
4264 goto out_unlock;
Andre Przywara8a39d002016-07-15 12:43:26 +01004265
4266 dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
4267 if (dev_idx < 0)
4268 goto out_unlock;
4269
4270 iodev = bus->range[dev_idx].dev;
4271
4272out_unlock:
4273 srcu_read_unlock(&kvm->srcu, srcu_idx);
4274
4275 return iodev;
4276}
4277EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
4278
Janosch Frank536a6f82016-05-18 13:26:23 +02004279static int kvm_debugfs_open(struct inode *inode, struct file *file,
4280 int (*get)(void *, u64 *), int (*set)(void *, u64),
4281 const char *fmt)
4282{
4283 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4284 inode->i_private;
4285
4286 /* The debugfs files are a reference to the kvm struct which
4287 * is still valid when kvm_destroy_vm is called.
4288 * To avoid the race between open and the removal of the debugfs
4289 * directory we test against the users count.
4290 */
Elena Reshetovae3736c32017-02-20 13:06:21 +02004291 if (!refcount_inc_not_zero(&stat_data->kvm->users_count))
Janosch Frank536a6f82016-05-18 13:26:23 +02004292 return -ENOENT;
4293
Paolo Bonzini833b45d2019-09-30 18:48:44 +02004294 if (simple_attr_open(inode, file, get,
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004295 KVM_DBGFS_GET_MODE(stat_data->dbgfs_item) & 0222
4296 ? set : NULL,
4297 fmt)) {
Janosch Frank536a6f82016-05-18 13:26:23 +02004298 kvm_put_kvm(stat_data->kvm);
4299 return -ENOMEM;
4300 }
4301
4302 return 0;
4303}
4304
4305static int kvm_debugfs_release(struct inode *inode, struct file *file)
4306{
4307 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
4308 inode->i_private;
4309
4310 simple_attr_release(inode, file);
4311 kvm_put_kvm(stat_data->kvm);
4312
4313 return 0;
4314}
4315
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004316static int kvm_get_stat_per_vm(struct kvm *kvm, size_t offset, u64 *val)
Janosch Frank536a6f82016-05-18 13:26:23 +02004317{
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004318 *val = *(ulong *)((void *)kvm + offset);
Janosch Frank536a6f82016-05-18 13:26:23 +02004319
4320 return 0;
4321}
4322
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004323static int kvm_clear_stat_per_vm(struct kvm *kvm, size_t offset)
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004324{
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004325 *(ulong *)((void *)kvm + offset) = 0;
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004326
4327 return 0;
4328}
4329
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004330static int kvm_get_stat_per_vcpu(struct kvm *kvm, size_t offset, u64 *val)
Janosch Frank536a6f82016-05-18 13:26:23 +02004331{
4332 int i;
Janosch Frank536a6f82016-05-18 13:26:23 +02004333 struct kvm_vcpu *vcpu;
4334
4335 *val = 0;
4336
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004337 kvm_for_each_vcpu(i, vcpu, kvm)
4338 *val += *(u64 *)((void *)vcpu + offset);
Janosch Frank536a6f82016-05-18 13:26:23 +02004339
4340 return 0;
4341}
4342
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004343static int kvm_clear_stat_per_vcpu(struct kvm *kvm, size_t offset)
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004344{
4345 int i;
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004346 struct kvm_vcpu *vcpu;
4347
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004348 kvm_for_each_vcpu(i, vcpu, kvm)
4349 *(u64 *)((void *)vcpu + offset) = 0;
4350
4351 return 0;
4352}
4353
4354static int kvm_stat_data_get(void *data, u64 *val)
4355{
4356 int r = -EFAULT;
4357 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4358
4359 switch (stat_data->dbgfs_item->kind) {
4360 case KVM_STAT_VM:
4361 r = kvm_get_stat_per_vm(stat_data->kvm,
4362 stat_data->dbgfs_item->offset, val);
4363 break;
4364 case KVM_STAT_VCPU:
4365 r = kvm_get_stat_per_vcpu(stat_data->kvm,
4366 stat_data->dbgfs_item->offset, val);
4367 break;
4368 }
4369
4370 return r;
4371}
4372
4373static int kvm_stat_data_clear(void *data, u64 val)
4374{
4375 int r = -EFAULT;
4376 struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
4377
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004378 if (val)
4379 return -EINVAL;
4380
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004381 switch (stat_data->dbgfs_item->kind) {
4382 case KVM_STAT_VM:
4383 r = kvm_clear_stat_per_vm(stat_data->kvm,
4384 stat_data->dbgfs_item->offset);
4385 break;
4386 case KVM_STAT_VCPU:
4387 r = kvm_clear_stat_per_vcpu(stat_data->kvm,
4388 stat_data->dbgfs_item->offset);
4389 break;
4390 }
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004391
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004392 return r;
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004393}
4394
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004395static int kvm_stat_data_open(struct inode *inode, struct file *file)
Janosch Frank536a6f82016-05-18 13:26:23 +02004396{
4397 __simple_attr_check_format("%llu\n", 0ull);
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004398 return kvm_debugfs_open(inode, file, kvm_stat_data_get,
4399 kvm_stat_data_clear, "%llu\n");
Janosch Frank536a6f82016-05-18 13:26:23 +02004400}
4401
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004402static const struct file_operations stat_fops_per_vm = {
4403 .owner = THIS_MODULE,
4404 .open = kvm_stat_data_open,
Janosch Frank536a6f82016-05-18 13:26:23 +02004405 .release = kvm_debugfs_release,
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004406 .read = simple_attr_read,
4407 .write = simple_attr_write,
4408 .llseek = no_llseek,
Janosch Frank536a6f82016-05-18 13:26:23 +02004409};
4410
Christoph Hellwig8b88b092008-02-08 04:20:26 -08004411static int vm_stat_get(void *_offset, u64 *val)
Avi Kivityba1389b2007-11-18 16:24:12 +02004412{
4413 unsigned offset = (long)_offset;
Avi Kivityba1389b2007-11-18 16:24:12 +02004414 struct kvm *kvm;
Janosch Frank536a6f82016-05-18 13:26:23 +02004415 u64 tmp_val;
Avi Kivityba1389b2007-11-18 16:24:12 +02004416
Christoph Hellwig8b88b092008-02-08 04:20:26 -08004417 *val = 0;
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004418 mutex_lock(&kvm_lock);
Janosch Frank536a6f82016-05-18 13:26:23 +02004419 list_for_each_entry(kvm, &vm_list, vm_list) {
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004420 kvm_get_stat_per_vm(kvm, offset, &tmp_val);
Janosch Frank536a6f82016-05-18 13:26:23 +02004421 *val += tmp_val;
4422 }
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004423 mutex_unlock(&kvm_lock);
Christoph Hellwig8b88b092008-02-08 04:20:26 -08004424 return 0;
Avi Kivityba1389b2007-11-18 16:24:12 +02004425}
4426
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004427static int vm_stat_clear(void *_offset, u64 val)
4428{
4429 unsigned offset = (long)_offset;
4430 struct kvm *kvm;
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004431
4432 if (val)
4433 return -EINVAL;
4434
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004435 mutex_lock(&kvm_lock);
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004436 list_for_each_entry(kvm, &vm_list, vm_list) {
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004437 kvm_clear_stat_per_vm(kvm, offset);
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004438 }
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004439 mutex_unlock(&kvm_lock);
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004440
4441 return 0;
4442}
4443
4444DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
Avi Kivityba1389b2007-11-18 16:24:12 +02004445
Christoph Hellwig8b88b092008-02-08 04:20:26 -08004446static int vcpu_stat_get(void *_offset, u64 *val)
Avi Kivity1165f5f2007-04-19 17:27:43 +03004447{
4448 unsigned offset = (long)_offset;
Avi Kivity1165f5f2007-04-19 17:27:43 +03004449 struct kvm *kvm;
Janosch Frank536a6f82016-05-18 13:26:23 +02004450 u64 tmp_val;
Avi Kivity1165f5f2007-04-19 17:27:43 +03004451
Christoph Hellwig8b88b092008-02-08 04:20:26 -08004452 *val = 0;
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004453 mutex_lock(&kvm_lock);
Janosch Frank536a6f82016-05-18 13:26:23 +02004454 list_for_each_entry(kvm, &vm_list, vm_list) {
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004455 kvm_get_stat_per_vcpu(kvm, offset, &tmp_val);
Janosch Frank536a6f82016-05-18 13:26:23 +02004456 *val += tmp_val;
4457 }
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004458 mutex_unlock(&kvm_lock);
Christoph Hellwig8b88b092008-02-08 04:20:26 -08004459 return 0;
Avi Kivity1165f5f2007-04-19 17:27:43 +03004460}
4461
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004462static int vcpu_stat_clear(void *_offset, u64 val)
4463{
4464 unsigned offset = (long)_offset;
4465 struct kvm *kvm;
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004466
4467 if (val)
4468 return -EINVAL;
4469
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004470 mutex_lock(&kvm_lock);
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004471 list_for_each_entry(kvm, &vm_list, vm_list) {
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004472 kvm_clear_stat_per_vcpu(kvm, offset);
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004473 }
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004474 mutex_unlock(&kvm_lock);
Suraj Jitindar Singhce35ef22016-10-19 13:49:47 +11004475
4476 return 0;
4477}
4478
4479DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
4480 "%llu\n");
Avi Kivityba1389b2007-11-18 16:24:12 +02004481
Alexey Dobriyan828c0952009-10-01 15:43:56 -07004482static const struct file_operations *stat_fops[] = {
Avi Kivityba1389b2007-11-18 16:24:12 +02004483 [KVM_STAT_VCPU] = &vcpu_stat_fops,
4484 [KVM_STAT_VM] = &vm_stat_fops,
4485};
Avi Kivity1165f5f2007-04-19 17:27:43 +03004486
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004487static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
4488{
4489 struct kobj_uevent_env *env;
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004490 unsigned long long created, active;
4491
4492 if (!kvm_dev.this_device || !kvm)
4493 return;
4494
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004495 mutex_lock(&kvm_lock);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004496 if (type == KVM_EVENT_CREATE_VM) {
4497 kvm_createvm_count++;
4498 kvm_active_vms++;
4499 } else if (type == KVM_EVENT_DESTROY_VM) {
4500 kvm_active_vms--;
4501 }
4502 created = kvm_createvm_count;
4503 active = kvm_active_vms;
Junaid Shahid0d9ce162019-01-03 17:14:28 -08004504 mutex_unlock(&kvm_lock);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004505
Ben Gardonb12ce362019-02-11 11:02:49 -08004506 env = kzalloc(sizeof(*env), GFP_KERNEL_ACCOUNT);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004507 if (!env)
4508 return;
4509
4510 add_uevent_var(env, "CREATED=%llu", created);
4511 add_uevent_var(env, "COUNT=%llu", active);
4512
Claudio Imbrendafdeaf7e2017-07-24 13:40:03 +02004513 if (type == KVM_EVENT_CREATE_VM) {
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004514 add_uevent_var(env, "EVENT=create");
Claudio Imbrendafdeaf7e2017-07-24 13:40:03 +02004515 kvm->userspace_pid = task_pid_nr(current);
4516 } else if (type == KVM_EVENT_DESTROY_VM) {
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004517 add_uevent_var(env, "EVENT=destroy");
Claudio Imbrendafdeaf7e2017-07-24 13:40:03 +02004518 }
4519 add_uevent_var(env, "PID=%d", kvm->userspace_pid);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004520
Greg Kroah-Hartman8ed05792019-02-28 16:34:37 +01004521 if (!IS_ERR_OR_NULL(kvm->debugfs_dentry)) {
Ben Gardonb12ce362019-02-11 11:02:49 -08004522 char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL_ACCOUNT);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004523
Claudio Imbrendafdeaf7e2017-07-24 13:40:03 +02004524 if (p) {
4525 tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
4526 if (!IS_ERR(tmp))
4527 add_uevent_var(env, "STATS_PATH=%s", tmp);
4528 kfree(p);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004529 }
4530 }
4531 /* no need for checks, since we are adding at most only 5 keys */
4532 env->envp[env->envp_idx++] = NULL;
4533 kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
4534 kfree(env);
Claudio Imbrenda286de8f2017-07-12 17:56:44 +02004535}
4536
Greg Kroah-Hartman929f45e2018-05-29 18:22:04 +02004537static void kvm_init_debug(void)
Avi Kivity6aa8b732006-12-10 02:21:36 -08004538{
4539 struct kvm_stats_debugfs_item *p;
4540
Hollis Blanchard76f7c872008-04-15 16:05:42 -05004541 kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
Hamo4f69b682011-12-15 14:23:16 +08004542
Janosch Frank536a6f82016-05-18 13:26:23 +02004543 kvm_debugfs_num_entries = 0;
4544 for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
Milan Pandurov09cbcef2019-12-13 14:07:21 +01004545 debugfs_create_file(p->name, KVM_DBGFS_GET_MODE(p),
4546 kvm_debugfs_dir, (void *)(long)p->offset,
Greg Kroah-Hartman929f45e2018-05-29 18:22:04 +02004547 stat_fops[p->kind]);
Hamo4f69b682011-12-15 14:23:16 +08004548 }
Avi Kivity6aa8b732006-12-10 02:21:36 -08004549}
4550
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +01004551static int kvm_suspend(void)
Avi Kivity59ae6c62007-02-12 00:54:48 -08004552{
Alexander Graf10474ae2009-09-15 11:37:46 +02004553 if (kvm_usage_count)
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004554 hardware_disable_nolock(NULL);
Avi Kivity59ae6c62007-02-12 00:54:48 -08004555 return 0;
4556}
4557
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +01004558static void kvm_resume(void)
Avi Kivity59ae6c62007-02-12 00:54:48 -08004559{
Zachary Amsdenca84d1a2010-08-19 22:07:28 -10004560 if (kvm_usage_count) {
Wanpeng Li2eb06c32019-05-17 16:49:49 +08004561#ifdef CONFIG_LOCKDEP
4562 WARN_ON(lockdep_is_held(&kvm_count_lock));
4563#endif
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004564 hardware_enable_nolock(NULL);
Zachary Amsdenca84d1a2010-08-19 22:07:28 -10004565 }
Avi Kivity59ae6c62007-02-12 00:54:48 -08004566}
4567
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +01004568static struct syscore_ops kvm_syscore_ops = {
Avi Kivity59ae6c62007-02-12 00:54:48 -08004569 .suspend = kvm_suspend,
4570 .resume = kvm_resume,
4571};
4572
Avi Kivity15ad7142007-07-11 18:17:21 +03004573static inline
4574struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
4575{
4576 return container_of(pn, struct kvm_vcpu, preempt_notifier);
4577}
4578
4579static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
4580{
4581 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
Xiubo Lif95ef0cd2015-02-26 14:58:23 +08004582
Wanpeng Li046ddee2019-08-01 11:30:14 +08004583 WRITE_ONCE(vcpu->preempted, false);
Wanpeng Lid73eb572019-07-18 19:39:06 +08004584 WRITE_ONCE(vcpu->ready, false);
Avi Kivity15ad7142007-07-11 18:17:21 +03004585
Paolo Bonzini7495e222020-01-09 09:57:19 -05004586 __this_cpu_write(kvm_running_vcpu, vcpu);
Radim Krčmáře790d9e2014-08-21 18:08:05 +02004587 kvm_arch_sched_in(vcpu, cpu);
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +08004588 kvm_arch_vcpu_load(vcpu, cpu);
Avi Kivity15ad7142007-07-11 18:17:21 +03004589}
4590
4591static void kvm_sched_out(struct preempt_notifier *pn,
4592 struct task_struct *next)
4593{
4594 struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
4595
Wanpeng Lid73eb572019-07-18 19:39:06 +08004596 if (current->state == TASK_RUNNING) {
Wanpeng Li046ddee2019-08-01 11:30:14 +08004597 WRITE_ONCE(vcpu->preempted, true);
Wanpeng Lid73eb572019-07-18 19:39:06 +08004598 WRITE_ONCE(vcpu->ready, true);
4599 }
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +08004600 kvm_arch_vcpu_put(vcpu);
Paolo Bonzini7495e222020-01-09 09:57:19 -05004601 __this_cpu_write(kvm_running_vcpu, NULL);
4602}
4603
4604/**
4605 * kvm_get_running_vcpu - get the vcpu running on the current CPU.
Marc Zyngier1f03b2b2020-02-07 16:34:10 +00004606 *
4607 * We can disable preemption locally around accessing the per-CPU variable,
4608 * and use the resolved vcpu pointer after enabling preemption again,
4609 * because even if the current thread is migrated to another CPU, reading
4610 * the per-CPU value later will give us the same value as we update the
4611 * per-CPU variable in the preempt notifier handlers.
Paolo Bonzini7495e222020-01-09 09:57:19 -05004612 */
4613struct kvm_vcpu *kvm_get_running_vcpu(void)
4614{
Marc Zyngier1f03b2b2020-02-07 16:34:10 +00004615 struct kvm_vcpu *vcpu;
4616
4617 preempt_disable();
4618 vcpu = __this_cpu_read(kvm_running_vcpu);
4619 preempt_enable();
4620
4621 return vcpu;
Paolo Bonzini7495e222020-01-09 09:57:19 -05004622}
4623
4624/**
4625 * kvm_get_running_vcpus - get the per-CPU array of currently running vcpus.
4626 */
4627struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void)
4628{
4629 return &kvm_running_vcpu;
Avi Kivity15ad7142007-07-11 18:17:21 +03004630}
4631
Sean Christophersonf257d6d2019-04-19 22:18:17 -07004632static void check_processor_compat(void *rtn)
4633{
4634 *(int *)rtn = kvm_arch_check_processor_compat();
4635}
4636
Avi Kivity0ee75be2010-04-28 15:39:01 +03004637int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
Rusty Russellc16f8622007-07-30 21:12:19 +10004638 struct module *module)
Avi Kivity6aa8b732006-12-10 02:21:36 -08004639{
4640 int r;
Yang, Sheng002c7f72007-07-31 14:23:01 +03004641 int cpu;
Avi Kivity6aa8b732006-12-10 02:21:36 -08004642
Zhang Xiantaof8c16bb2007-11-14 20:40:21 +08004643 r = kvm_arch_init(opaque);
4644 if (r)
Zhang Xiantaod23087842007-11-29 15:35:39 +08004645 goto out_fail;
Zhang Xiantaocb498ea2007-11-14 20:39:31 +08004646
Asias He7dac16c2013-05-08 10:57:29 +08004647 /*
4648 * kvm_arch_init makes sure there's at most one caller
4649 * for architectures that support multiple implementations,
4650 * like intel and amd on x86.
Paolo Bonzini36343f62016-10-26 13:35:56 +02004651 * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
4652 * conflicts in case kvm is already setup for another implementation.
Asias He7dac16c2013-05-08 10:57:29 +08004653 */
Paolo Bonzini36343f62016-10-26 13:35:56 +02004654 r = kvm_irqfd_init();
4655 if (r)
4656 goto out_irqfd;
Asias He7dac16c2013-05-08 10:57:29 +08004657
Avi Kivity8437a6172009-06-06 14:52:35 -07004658 if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
Rusty Russell7f59f492008-12-07 21:25:45 +10304659 r = -ENOMEM;
4660 goto out_free_0;
4661 }
4662
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +08004663 r = kvm_arch_hardware_setup();
Avi Kivity6aa8b732006-12-10 02:21:36 -08004664 if (r < 0)
Miaohe Linfaf0be22019-11-23 10:45:50 +08004665 goto out_free_1;
Avi Kivity6aa8b732006-12-10 02:21:36 -08004666
Yang, Sheng002c7f72007-07-31 14:23:01 +03004667 for_each_online_cpu(cpu) {
Sean Christophersonf257d6d2019-04-19 22:18:17 -07004668 smp_call_function_single(cpu, check_processor_compat, &r, 1);
Yang, Sheng002c7f72007-07-31 14:23:01 +03004669 if (r < 0)
Miaohe Linfaf0be22019-11-23 10:45:50 +08004670 goto out_free_2;
Yang, Sheng002c7f72007-07-31 14:23:01 +03004671 }
4672
Thomas Gleixner73c1b412016-12-21 20:19:54 +01004673 r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00004674 kvm_starting_cpu, kvm_dying_cpu);
Avi Kivity774c47f2007-02-12 00:54:47 -08004675 if (r)
Zhang Xiantaod23087842007-11-29 15:35:39 +08004676 goto out_free_2;
Avi Kivity6aa8b732006-12-10 02:21:36 -08004677 register_reboot_notifier(&kvm_reboot_notifier);
4678
Rusty Russellc16f8622007-07-30 21:12:19 +10004679 /* A kmem cache lets us meet the alignment requirements of fx_save. */
Avi Kivity0ee75be2010-04-28 15:39:01 +03004680 if (!vcpu_align)
4681 vcpu_align = __alignof__(struct kvm_vcpu);
Paolo Bonzini46515732017-10-26 15:45:46 +02004682 kvm_vcpu_cache =
4683 kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
4684 SLAB_ACCOUNT,
4685 offsetof(struct kvm_vcpu, arch),
4686 sizeof_field(struct kvm_vcpu, arch),
4687 NULL);
Rusty Russellc16f8622007-07-30 21:12:19 +10004688 if (!kvm_vcpu_cache) {
4689 r = -ENOMEM;
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +01004690 goto out_free_3;
Rusty Russellc16f8622007-07-30 21:12:19 +10004691 }
4692
Gleb Natapovaf585b92010-10-14 11:22:46 +02004693 r = kvm_async_pf_init();
4694 if (r)
4695 goto out_free;
4696
Avi Kivity6aa8b732006-12-10 02:21:36 -08004697 kvm_chardev_ops.owner = module;
Christian Borntraeger3d3aab12008-12-02 11:17:32 +01004698 kvm_vm_fops.owner = module;
4699 kvm_vcpu_fops.owner = module;
Avi Kivity6aa8b732006-12-10 02:21:36 -08004700
4701 r = misc_register(&kvm_dev);
4702 if (r) {
Xiubo Li1170adc2015-02-26 14:58:26 +08004703 pr_err("kvm: misc device register failed\n");
Gleb Natapovaf585b92010-10-14 11:22:46 +02004704 goto out_unreg;
Avi Kivity6aa8b732006-12-10 02:21:36 -08004705 }
4706
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +01004707 register_syscore_ops(&kvm_syscore_ops);
4708
Avi Kivity15ad7142007-07-11 18:17:21 +03004709 kvm_preempt_ops.sched_in = kvm_sched_in;
4710 kvm_preempt_ops.sched_out = kvm_sched_out;
4711
Greg Kroah-Hartman929f45e2018-05-29 18:22:04 +02004712 kvm_init_debug();
Darrick J. Wong0ea4ed82009-10-14 16:21:00 -07004713
Paolo Bonzini3c3c29f2014-09-24 13:02:46 +02004714 r = kvm_vfio_ops_init();
4715 WARN_ON(r);
4716
Avi Kivityc7addb92007-09-16 18:58:32 +02004717 return 0;
Avi Kivity6aa8b732006-12-10 02:21:36 -08004718
Gleb Natapovaf585b92010-10-14 11:22:46 +02004719out_unreg:
4720 kvm_async_pf_deinit();
Avi Kivity6aa8b732006-12-10 02:21:36 -08004721out_free:
Rusty Russellc16f8622007-07-30 21:12:19 +10004722 kmem_cache_destroy(kvm_vcpu_cache);
Zhang Xiantaod23087842007-11-29 15:35:39 +08004723out_free_3:
Avi Kivity6aa8b732006-12-10 02:21:36 -08004724 unregister_reboot_notifier(&kvm_reboot_notifier);
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00004725 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
Zhang Xiantaod23087842007-11-29 15:35:39 +08004726out_free_2:
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +08004727 kvm_arch_hardware_unsetup();
Miaohe Linfaf0be22019-11-23 10:45:50 +08004728out_free_1:
Rusty Russell7f59f492008-12-07 21:25:45 +10304729 free_cpumask_var(cpus_hardware_enabled);
Zhang Xiantaod23087842007-11-29 15:35:39 +08004730out_free_0:
Cornelia Hucka0f155e2013-02-28 12:33:18 +01004731 kvm_irqfd_exit();
Paolo Bonzini36343f62016-10-26 13:35:56 +02004732out_irqfd:
Asias He7dac16c2013-05-08 10:57:29 +08004733 kvm_arch_exit();
4734out_fail:
Avi Kivity6aa8b732006-12-10 02:21:36 -08004735 return r;
4736}
Zhang Xiantaocb498ea2007-11-14 20:39:31 +08004737EXPORT_SYMBOL_GPL(kvm_init);
Avi Kivity6aa8b732006-12-10 02:21:36 -08004738
Zhang Xiantaocb498ea2007-11-14 20:39:31 +08004739void kvm_exit(void)
Avi Kivity6aa8b732006-12-10 02:21:36 -08004740{
Janosch Frank4bd33b52015-10-14 12:37:35 +02004741 debugfs_remove_recursive(kvm_debugfs_dir);
Avi Kivity6aa8b732006-12-10 02:21:36 -08004742 misc_deregister(&kvm_dev);
Rusty Russellc16f8622007-07-30 21:12:19 +10004743 kmem_cache_destroy(kvm_vcpu_cache);
Gleb Natapovaf585b92010-10-14 11:22:46 +02004744 kvm_async_pf_deinit();
Rafael J. Wysockifb3600c2011-03-23 22:16:23 +01004745 unregister_syscore_ops(&kvm_syscore_ops);
Avi Kivity6aa8b732006-12-10 02:21:36 -08004746 unregister_reboot_notifier(&kvm_reboot_notifier);
Thomas Gleixner8c18b2d2016-07-13 17:16:37 +00004747 cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
Takuya Yoshikawa75b71272010-11-16 17:37:41 +09004748 on_each_cpu(hardware_disable_nolock, NULL, 1);
Zhang Xiantaoe9b11c12007-11-14 20:38:21 +08004749 kvm_arch_hardware_unsetup();
Zhang Xiantaof8c16bb2007-11-14 20:40:21 +08004750 kvm_arch_exit();
Cornelia Hucka0f155e2013-02-28 12:33:18 +01004751 kvm_irqfd_exit();
Rusty Russell7f59f492008-12-07 21:25:45 +10304752 free_cpumask_var(cpus_hardware_enabled);
Wanpeng Li571ee1b2014-10-09 18:30:08 +08004753 kvm_vfio_ops_exit();
Avi Kivity6aa8b732006-12-10 02:21:36 -08004754}
Zhang Xiantaocb498ea2007-11-14 20:39:31 +08004755EXPORT_SYMBOL_GPL(kvm_exit);
Junaid Shahidc57c8042019-11-04 12:22:02 +01004756
4757struct kvm_vm_worker_thread_context {
4758 struct kvm *kvm;
4759 struct task_struct *parent;
4760 struct completion init_done;
4761 kvm_vm_thread_fn_t thread_fn;
4762 uintptr_t data;
4763 int err;
4764};
4765
4766static int kvm_vm_worker_thread(void *context)
4767{
4768 /*
4769 * The init_context is allocated on the stack of the parent thread, so
4770 * we have to locally copy anything that is needed beyond initialization
4771 */
4772 struct kvm_vm_worker_thread_context *init_context = context;
4773 struct kvm *kvm = init_context->kvm;
4774 kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
4775 uintptr_t data = init_context->data;
4776 int err;
4777
4778 err = kthread_park(current);
4779 /* kthread_park(current) is never supposed to return an error */
4780 WARN_ON(err != 0);
4781 if (err)
4782 goto init_complete;
4783
4784 err = cgroup_attach_task_all(init_context->parent, current);
4785 if (err) {
4786 kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
4787 __func__, err);
4788 goto init_complete;
4789 }
4790
4791 set_user_nice(current, task_nice(init_context->parent));
4792
4793init_complete:
4794 init_context->err = err;
4795 complete(&init_context->init_done);
4796 init_context = NULL;
4797
4798 if (err)
4799 return err;
4800
4801 /* Wait to be woken up by the spawner before proceeding. */
4802 kthread_parkme();
4803
4804 if (!kthread_should_stop())
4805 err = thread_fn(kvm, data);
4806
4807 return err;
4808}
4809
4810int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
4811 uintptr_t data, const char *name,
4812 struct task_struct **thread_ptr)
4813{
4814 struct kvm_vm_worker_thread_context init_context = {};
4815 struct task_struct *thread;
4816
4817 *thread_ptr = NULL;
4818 init_context.kvm = kvm;
4819 init_context.parent = current;
4820 init_context.thread_fn = thread_fn;
4821 init_context.data = data;
4822 init_completion(&init_context.init_done);
4823
4824 thread = kthread_run(kvm_vm_worker_thread, &init_context,
4825 "%s-%d", name, task_pid_nr(current));
4826 if (IS_ERR(thread))
4827 return PTR_ERR(thread);
4828
4829 /* kthread_run is never supposed to return NULL */
4830 WARN_ON(thread == NULL);
4831
4832 wait_for_completion(&init_context.init_done);
4833
4834 if (!init_context.err)
4835 *thread_ptr = thread;
4836
4837 return init_context.err;
4838}