xref: /linux-6.15/include/linux/kvm_host.h (revision 459a3511)
120c8ccb1SThomas Gleixner /* SPDX-License-Identifier: GPL-2.0-only */
2edf88417SAvi Kivity #ifndef __KVM_HOST_H
3edf88417SAvi Kivity #define __KVM_HOST_H
4edf88417SAvi Kivity 
5edf88417SAvi Kivity 
6edf88417SAvi Kivity #include <linux/types.h>
7edf88417SAvi Kivity #include <linux/hardirq.h>
8edf88417SAvi Kivity #include <linux/list.h>
9edf88417SAvi Kivity #include <linux/mutex.h>
10edf88417SAvi Kivity #include <linux/spinlock.h>
11edf88417SAvi Kivity #include <linux/signal.h>
12edf88417SAvi Kivity #include <linux/sched.h>
136bd5b743SWanpeng Li #include <linux/sched/stat.h>
14187f1882SPaul Gortmaker #include <linux/bug.h>
154a42d848SDavid Stevens #include <linux/minmax.h>
16edf88417SAvi Kivity #include <linux/mm.h>
17b297e672SEric B Munson #include <linux/mmu_notifier.h>
18edf88417SAvi Kivity #include <linux/preempt.h>
190937c48dSSheng Yang #include <linux/msi.h>
20d89f5effSJan Kiszka #include <linux/slab.h>
21d1e5b0e9SMarc Orr #include <linux/vmalloc.h>
22bd2b53b2SMichael S. Tsirkin #include <linux/rcupdate.h>
23bd80158aSJan Kiszka #include <linux/ratelimit.h>
2483f09228SXiao Guangrong #include <linux/err.h>
25c11f11fcSFrederic Weisbecker #include <linux/irqflags.h>
26521921baSFrederic Weisbecker #include <linux/context_tracking.h>
271a02b270SEric Auger #include <linux/irqbypass.h>
28da4ad88cSDavidlohr Bueso #include <linux/rcuwait.h>
29e3736c3eSElena Reshetova #include <linux/refcount.h>
301d487e9bSPaolo Bonzini #include <linux/nospec.h>
312fdef3a2SSergey Senozhatsky #include <linux/notifier.h>
32ef9989afSMark Rutland #include <linux/ftrace.h>
3326b8345aSMaciej S. Szmigiero #include <linux/hashtable.h>
34ef9989afSMark Rutland #include <linux/instrumentation.h>
35ed922739SMaciej S. Szmigiero #include <linux/interval_tree.h>
36a54d8066SMaciej S. Szmigiero #include <linux/rbtree.h>
37c5b07754SMarc Zyngier #include <linux/xarray.h>
38edf88417SAvi Kivity #include <asm/signal.h>
39edf88417SAvi Kivity 
40edf88417SAvi Kivity #include <linux/kvm.h>
41edf88417SAvi Kivity #include <linux/kvm_para.h>
42edf88417SAvi Kivity 
43edf88417SAvi Kivity #include <linux/kvm_types.h>
44edf88417SAvi Kivity 
45edf88417SAvi Kivity #include <asm/kvm_host.h>
46fb04a1edSPeter Xu #include <linux/kvm_dirty_ring.h>
47edf88417SAvi Kivity 
48a1c42ddeSJuergen Gross #ifndef KVM_MAX_VCPU_IDS
49a1c42ddeSJuergen Gross #define KVM_MAX_VCPU_IDS KVM_MAX_VCPUS
500b1b1dfdSGreg Kurz #endif
510b1b1dfdSGreg Kurz 
52edf88417SAvi Kivity /*
5330ee198cSJavier Martinez Canillas  * The bit 16 ~ bit 31 of kvm_userspace_memory_region::flags are internally
5430ee198cSJavier Martinez Canillas  * used in kvm, other bits are visible for userspace which are defined in
5567b29204SXiao Guangrong  * include/linux/kvm_h.
5667b29204SXiao Guangrong  */
5767b29204SXiao Guangrong #define KVM_MEMSLOT_INVALID	(1UL << 16)
5867b29204SXiao Guangrong 
59361209e0SSean Christopherson /*
60164bf7e5SSean Christopherson  * Bit 63 of the memslot generation number is an "update in-progress flag",
61b0d23708SJun Miao  * e.g. is temporarily set for the duration of kvm_swap_active_memslots().
62361209e0SSean Christopherson  * This flag effectively creates a unique generation number that is used to
63361209e0SSean Christopherson  * mark cached memslot data, e.g. MMIO accesses, as potentially being stale,
64361209e0SSean Christopherson  * i.e. may (or may not) have come from the previous memslots generation.
65361209e0SSean Christopherson  *
66361209e0SSean Christopherson  * This is necessary because the actual memslots update is not atomic with
67361209e0SSean Christopherson  * respect to the generation number update.  Updating the generation number
68361209e0SSean Christopherson  * first would allow a vCPU to cache a spte from the old memslots using the
69361209e0SSean Christopherson  * new generation number, and updating the generation number after switching
70361209e0SSean Christopherson  * to the new memslots would allow cache hits using the old generation number
71361209e0SSean Christopherson  * to reference the defunct memslots.
72361209e0SSean Christopherson  *
73361209e0SSean Christopherson  * This mechanism is used to prevent getting hits in KVM's caches while a
74361209e0SSean Christopherson  * memslot update is in-progress, and to prevent cache hits *after* updating
75361209e0SSean Christopherson  * the actual generation number against accesses that were inserted into the
76361209e0SSean Christopherson  * cache *before* the memslots were updated.
77361209e0SSean Christopherson  */
78164bf7e5SSean Christopherson #define KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS	BIT_ULL(63)
79361209e0SSean Christopherson 
8087da7e66SXiao Guangrong /* Two fragments for cross MMIO pages. */
8187da7e66SXiao Guangrong #define KVM_MAX_MMIO_FRAGMENTS	2
82f78146b0SAvi Kivity 
83eed52e43SSean Christopherson #ifndef KVM_MAX_NR_ADDRESS_SPACES
84eed52e43SSean Christopherson #define KVM_MAX_NR_ADDRESS_SPACES	1
85f481b069SPaolo Bonzini #endif
86f481b069SPaolo Bonzini 
87f78146b0SAvi Kivity /*
889c5b1172SXiao Guangrong  * For the normal pfn, the highest 12 bits should be zero,
8981c52c56SXiao Guangrong  * so we can mask bit 62 ~ bit 52  to indicate the error pfn,
9081c52c56SXiao Guangrong  * mask bit 63 to indicate the noslot pfn.
919c5b1172SXiao Guangrong  */
9281c52c56SXiao Guangrong #define KVM_PFN_ERR_MASK	(0x7ffULL << 52)
9381c52c56SXiao Guangrong #define KVM_PFN_ERR_NOSLOT_MASK	(0xfffULL << 52)
9481c52c56SXiao Guangrong #define KVM_PFN_NOSLOT		(0x1ULL << 63)
956c8ee57bSXiao Guangrong 
969c5b1172SXiao Guangrong #define KVM_PFN_ERR_FAULT	(KVM_PFN_ERR_MASK)
979c5b1172SXiao Guangrong #define KVM_PFN_ERR_HWPOISON	(KVM_PFN_ERR_MASK + 1)
9881c52c56SXiao Guangrong #define KVM_PFN_ERR_RO_FAULT	(KVM_PFN_ERR_MASK + 2)
99fe5ed56cSPeter Xu #define KVM_PFN_ERR_SIGPENDING	(KVM_PFN_ERR_MASK + 3)
1006769d1bcSDavid Stevens #define KVM_PFN_ERR_NEEDS_IO	(KVM_PFN_ERR_MASK + 4)
1019c5b1172SXiao Guangrong 
10281c52c56SXiao Guangrong /*
10381c52c56SXiao Guangrong  * error pfns indicate that the gfn is in slot but faild to
10481c52c56SXiao Guangrong  * translate it to pfn on host.
10581c52c56SXiao Guangrong  */
is_error_pfn(kvm_pfn_t pfn)106ba049e93SDan Williams static inline bool is_error_pfn(kvm_pfn_t pfn)
10783f09228SXiao Guangrong {
1089c5b1172SXiao Guangrong 	return !!(pfn & KVM_PFN_ERR_MASK);
10983f09228SXiao Guangrong }
11083f09228SXiao Guangrong 
11181c52c56SXiao Guangrong /*
112fe5ed56cSPeter Xu  * KVM_PFN_ERR_SIGPENDING indicates that fetching the PFN was interrupted
113fe5ed56cSPeter Xu  * by a pending signal.  Note, the signal may or may not be fatal.
114fe5ed56cSPeter Xu  */
is_sigpending_pfn(kvm_pfn_t pfn)115fe5ed56cSPeter Xu static inline bool is_sigpending_pfn(kvm_pfn_t pfn)
116fe5ed56cSPeter Xu {
117fe5ed56cSPeter Xu 	return pfn == KVM_PFN_ERR_SIGPENDING;
118fe5ed56cSPeter Xu }
119fe5ed56cSPeter Xu 
120fe5ed56cSPeter Xu /*
12181c52c56SXiao Guangrong  * error_noslot pfns indicate that the gfn can not be
12281c52c56SXiao Guangrong  * translated to pfn - it is not in slot or failed to
12381c52c56SXiao Guangrong  * translate it to pfn.
12481c52c56SXiao Guangrong  */
is_error_noslot_pfn(kvm_pfn_t pfn)125ba049e93SDan Williams static inline bool is_error_noslot_pfn(kvm_pfn_t pfn)
12683f09228SXiao Guangrong {
12781c52c56SXiao Guangrong 	return !!(pfn & KVM_PFN_ERR_NOSLOT_MASK);
12883f09228SXiao Guangrong }
12983f09228SXiao Guangrong 
13081c52c56SXiao Guangrong /* noslot pfn indicates that the gfn is not in slot. */
is_noslot_pfn(kvm_pfn_t pfn)131ba049e93SDan Williams static inline bool is_noslot_pfn(kvm_pfn_t pfn)
13283f09228SXiao Guangrong {
13381c52c56SXiao Guangrong 	return pfn == KVM_PFN_NOSLOT;
13483f09228SXiao Guangrong }
13583f09228SXiao Guangrong 
136bf640876SDominik Dingel /*
137bf640876SDominik Dingel  * architectures with KVM_HVA_ERR_BAD other than PAGE_OFFSET (e.g. s390)
138bf640876SDominik Dingel  * provide own defines and kvm_is_error_hva
139bf640876SDominik Dingel  */
140bf640876SDominik Dingel #ifndef KVM_HVA_ERR_BAD
141bf640876SDominik Dingel 
142ca3a490cSXiao Guangrong #define KVM_HVA_ERR_BAD		(PAGE_OFFSET)
1437068d097SXiao Guangrong #define KVM_HVA_ERR_RO_BAD	(PAGE_OFFSET + PAGE_SIZE)
144ca3a490cSXiao Guangrong 
kvm_is_error_hva(unsigned long addr)145ca3a490cSXiao Guangrong static inline bool kvm_is_error_hva(unsigned long addr)
146ca3a490cSXiao Guangrong {
1477068d097SXiao Guangrong 	return addr >= PAGE_OFFSET;
148ca3a490cSXiao Guangrong }
149ca3a490cSXiao Guangrong 
150bf640876SDominik Dingel #endif
151bf640876SDominik Dingel 
kvm_is_error_gpa(gpa_t gpa)152721f5b0dSPaul Durrant static inline bool kvm_is_error_gpa(gpa_t gpa)
153721f5b0dSPaul Durrant {
154721f5b0dSPaul Durrant 	return gpa == INVALID_GPA;
155721f5b0dSPaul Durrant }
156721f5b0dSPaul Durrant 
157930f7fd6SRadim Krčmář #define KVM_REQUEST_MASK           GENMASK(7,0)
158930f7fd6SRadim Krčmář #define KVM_REQUEST_NO_WAKEUP      BIT(8)
1597a97cec2SPaolo Bonzini #define KVM_REQUEST_WAIT           BIT(9)
160df06dae3SSean Christopherson #define KVM_REQUEST_NO_ACTION      BIT(10)
161edf88417SAvi Kivity /*
1622860c4b1SPaolo Bonzini  * Architecture-independent vcpu->requests bit members
163c59fb127SPaolo Bonzini  * Bits 3-7 are reserved for more arch-independent bits.
164edf88417SAvi Kivity  */
1657a97cec2SPaolo Bonzini #define KVM_REQ_TLB_FLUSH		(0 | KVM_REQUEST_WAIT | KVM_REQUEST_NO_WAKEUP)
166e65a3b46SSean Christopherson #define KVM_REQ_VM_DEAD			(1 | KVM_REQUEST_WAIT | KVM_REQUEST_NO_WAKEUP)
167084071d5SMarcelo Tosatti #define KVM_REQ_UNBLOCK			2
168cf87ac73SGavin Shan #define KVM_REQ_DIRTY_RING_SOFT_FULL	3
1692387149eSAndrew Jones #define KVM_REQUEST_ARCH_BASE		8
1702387149eSAndrew Jones 
171df06dae3SSean Christopherson /*
172df06dae3SSean Christopherson  * KVM_REQ_OUTSIDE_GUEST_MODE exists is purely as way to force the vCPU to
173df06dae3SSean Christopherson  * OUTSIDE_GUEST_MODE.  KVM_REQ_OUTSIDE_GUEST_MODE differs from a vCPU "kick"
174df06dae3SSean Christopherson  * in that it ensures the vCPU has reached OUTSIDE_GUEST_MODE before continuing
175df06dae3SSean Christopherson  * on.  A kick only guarantees that the vCPU is on its way out, e.g. a previous
176df06dae3SSean Christopherson  * kick may have set vcpu->mode to EXITING_GUEST_MODE, and so there's no
177df06dae3SSean Christopherson  * guarantee the vCPU received an IPI and has actually exited guest mode.
178df06dae3SSean Christopherson  */
179df06dae3SSean Christopherson #define KVM_REQ_OUTSIDE_GUEST_MODE	(KVM_REQUEST_NO_ACTION | KVM_REQUEST_WAIT | KVM_REQUEST_NO_WAKEUP)
180df06dae3SSean Christopherson 
1812387149eSAndrew Jones #define KVM_ARCH_REQ_FLAGS(nr, flags) ({ \
182c593642cSPankaj Bharadiya 	BUILD_BUG_ON((unsigned)(nr) >= (sizeof_field(struct kvm_vcpu, requests) * 8) - KVM_REQUEST_ARCH_BASE); \
1832387149eSAndrew Jones 	(unsigned)(((nr) + KVM_REQUEST_ARCH_BASE) | (flags)); \
1842387149eSAndrew Jones })
1852387149eSAndrew Jones #define KVM_ARCH_REQ(nr)           KVM_ARCH_REQ_FLAGS(nr, 0)
1860cd31043SPaolo Bonzini 
1877ee3e8c3SSean Christopherson bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
188620b2438SVitaly Kuznetsov 				 unsigned long *vcpu_bitmap);
1897ee3e8c3SSean Christopherson bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req);
1907ee3e8c3SSean Christopherson 
1915550af4dSSheng Yang #define KVM_USERSPACE_IRQ_SOURCE_ID		0
1927a84428aSAlex Williamson #define KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID	1
1935550af4dSSheng Yang 
1940d9ce162SJunaid Shahid extern struct mutex kvm_lock;
195fc1b7492SGeoff Levand extern struct list_head vm_list;
196fc1b7492SGeoff Levand 
197743eeb0bSSasha Levin struct kvm_io_range {
198743eeb0bSSasha Levin 	gpa_t addr;
199743eeb0bSSasha Levin 	int len;
200743eeb0bSSasha Levin 	struct kvm_io_device *dev;
201743eeb0bSSasha Levin };
202743eeb0bSSasha Levin 
203786a9f88SAmos Kong #define NR_IOBUS_DEVS 1000
204a1300716SAmos Kong 
205edf88417SAvi Kivity struct kvm_io_bus {
206edf88417SAvi Kivity 	int dev_count;
2076ea34c9bSAmos Kong 	int ioeventfd_count;
208a1300716SAmos Kong 	struct kvm_io_range range[];
209edf88417SAvi Kivity };
210edf88417SAvi Kivity 
211e93f8a0fSMarcelo Tosatti enum kvm_bus {
212e93f8a0fSMarcelo Tosatti 	KVM_MMIO_BUS,
213e93f8a0fSMarcelo Tosatti 	KVM_PIO_BUS,
214060f0ce6SCornelia Huck 	KVM_VIRTIO_CCW_NOTIFY_BUS,
21568c3b4d1SMichael S. Tsirkin 	KVM_FAST_MMIO_BUS,
216948ccbd9SXianglai Li 	KVM_IOCSR_BUS,
217e93f8a0fSMarcelo Tosatti 	KVM_NR_BUSES
218e93f8a0fSMarcelo Tosatti };
219e93f8a0fSMarcelo Tosatti 
220e32edf4fSNikolay Nikolaev int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
221e93f8a0fSMarcelo Tosatti 		     int len, const void *val);
222e32edf4fSNikolay Nikolaev int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
223e32edf4fSNikolay Nikolaev 			    gpa_t addr, int len, const void *val, long cookie);
224e32edf4fSNikolay Nikolaev int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
225e32edf4fSNikolay Nikolaev 		    int len, void *val);
226743eeb0bSSasha Levin int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
227743eeb0bSSasha Levin 			    int len, struct kvm_io_device *dev);
2285d3c4c79SSean Christopherson int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
229edf88417SAvi Kivity 			      struct kvm_io_device *dev);
2308a39d006SAndre Przywara struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
2318a39d006SAndre Przywara 					 gpa_t addr);
232edf88417SAvi Kivity 
233af585b92SGleb Natapov #ifdef CONFIG_KVM_ASYNC_PF
234af585b92SGleb Natapov struct kvm_async_pf {
235af585b92SGleb Natapov 	struct work_struct work;
236af585b92SGleb Natapov 	struct list_head link;
237af585b92SGleb Natapov 	struct list_head queue;
238af585b92SGleb Natapov 	struct kvm_vcpu *vcpu;
239736c291cSSean Christopherson 	gpa_t cr2_or_gpa;
240af585b92SGleb Natapov 	unsigned long addr;
241af585b92SGleb Natapov 	struct kvm_arch_async_pf arch;
242f2e10669Schai wen 	bool   wakeup_all;
2432a18b7e7SVitaly Kuznetsov 	bool notpresent_injected;
244af585b92SGleb Natapov };
245af585b92SGleb Natapov 
246af585b92SGleb Natapov void kvm_clear_async_pf_completion_queue(struct kvm_vcpu *vcpu);
247af585b92SGleb Natapov void kvm_check_async_pf_completion(struct kvm_vcpu *vcpu);
248e8c22266SVitaly Kuznetsov bool kvm_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
249736c291cSSean Christopherson 			unsigned long hva, struct kvm_arch_async_pf *arch);
250344d9588SGleb Natapov int kvm_async_pf_wakeup_all(struct kvm_vcpu *vcpu);
251af585b92SGleb Natapov #endif
252af585b92SGleb Natapov 
253f128cf8cSSean Christopherson #ifdef CONFIG_KVM_GENERIC_MMU_NOTIFIER
2543e1efe2bSSean Christopherson union kvm_mmu_notifier_arg {
2555a475554SChao Peng 	unsigned long attributes;
2563e1efe2bSSean Christopherson };
2573e1efe2bSSean Christopherson 
258dca6c885SIsaku Yamahata enum kvm_gfn_range_filter {
259dca6c885SIsaku Yamahata 	KVM_FILTER_SHARED		= BIT(0),
260dca6c885SIsaku Yamahata 	KVM_FILTER_PRIVATE		= BIT(1),
261dca6c885SIsaku Yamahata };
262dca6c885SIsaku Yamahata 
2633039bcc7SSean Christopherson struct kvm_gfn_range {
2643039bcc7SSean Christopherson 	struct kvm_memory_slot *slot;
2653039bcc7SSean Christopherson 	gfn_t start;
2663039bcc7SSean Christopherson 	gfn_t end;
2673e1efe2bSSean Christopherson 	union kvm_mmu_notifier_arg arg;
268dca6c885SIsaku Yamahata 	enum kvm_gfn_range_filter attr_filter;
2693039bcc7SSean Christopherson 	bool may_block;
270aa34b811SJames Houghton 	bool lockless;
2713039bcc7SSean Christopherson };
2723039bcc7SSean Christopherson bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range);
2733039bcc7SSean Christopherson bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range);
2743039bcc7SSean Christopherson bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range);
2755f7c292bSSean Christopherson #endif
2765f7c292bSSean Christopherson 
2776b7e2d09SXiao Guangrong enum {
2786b7e2d09SXiao Guangrong 	OUTSIDE_GUEST_MODE,
2796b7e2d09SXiao Guangrong 	IN_GUEST_MODE,
280c142786cSAvi Kivity 	EXITING_GUEST_MODE,
281c142786cSAvi Kivity 	READING_SHADOW_PAGE_TABLES,
2826b7e2d09SXiao Guangrong };
2836b7e2d09SXiao Guangrong 
284e45adf66SKarimAllah Ahmed struct kvm_host_map {
285e45adf66SKarimAllah Ahmed 	/*
286e45adf66SKarimAllah Ahmed 	 * Only valid if the 'pfn' is managed by the host kernel (i.e. There is
287e45adf66SKarimAllah Ahmed 	 * a 'struct page' for it. When using mem= kernel parameter some memory
288e45adf66SKarimAllah Ahmed 	 * can be used as guest memory but they are not managed by host
289e45adf66SKarimAllah Ahmed 	 * kernel).
290e45adf66SKarimAllah Ahmed 	 */
2912bcb52a3SSean Christopherson 	struct page *pinned_page;
292e45adf66SKarimAllah Ahmed 	struct page *page;
293e45adf66SKarimAllah Ahmed 	void *hva;
294e45adf66SKarimAllah Ahmed 	kvm_pfn_t pfn;
295e45adf66SKarimAllah Ahmed 	kvm_pfn_t gfn;
296365e3192SSean Christopherson 	bool writable;
297e45adf66SKarimAllah Ahmed };
298e45adf66SKarimAllah Ahmed 
299e45adf66SKarimAllah Ahmed /*
300e45adf66SKarimAllah Ahmed  * Used to check if the mapping is valid or not. Never use 'kvm_host_map'
301e45adf66SKarimAllah Ahmed  * directly to check for that.
302e45adf66SKarimAllah Ahmed  */
kvm_vcpu_mapped(struct kvm_host_map * map)303e45adf66SKarimAllah Ahmed static inline bool kvm_vcpu_mapped(struct kvm_host_map *map)
304e45adf66SKarimAllah Ahmed {
305e45adf66SKarimAllah Ahmed 	return !!map->hva;
306e45adf66SKarimAllah Ahmed }
307e45adf66SKarimAllah Ahmed 
kvm_vcpu_can_poll(ktime_t cur,ktime_t stop)3086bd5b743SWanpeng Li static inline bool kvm_vcpu_can_poll(ktime_t cur, ktime_t stop)
3096bd5b743SWanpeng Li {
3106bd5b743SWanpeng Li 	return single_task_running() && !need_resched() && ktime_before(cur, stop);
3116bd5b743SWanpeng Li }
3126bd5b743SWanpeng Li 
313f78146b0SAvi Kivity /*
314f78146b0SAvi Kivity  * Sometimes a large or cross-page mmio needs to be broken up into separate
315f78146b0SAvi Kivity  * exits for userspace servicing.
316f78146b0SAvi Kivity  */
317f78146b0SAvi Kivity struct kvm_mmio_fragment {
318f78146b0SAvi Kivity 	gpa_t gpa;
319f78146b0SAvi Kivity 	void *data;
320f78146b0SAvi Kivity 	unsigned len;
321f78146b0SAvi Kivity };
322f78146b0SAvi Kivity 
323edf88417SAvi Kivity struct kvm_vcpu {
324edf88417SAvi Kivity 	struct kvm *kvm;
32531bb117eSHollis Blanchard #ifdef CONFIG_PREEMPT_NOTIFIERS
326edf88417SAvi Kivity 	struct preempt_notifier preempt_notifier;
32731bb117eSHollis Blanchard #endif
328edf88417SAvi Kivity 	int cpu;
3298750e72aSRadim Krčmář 	int vcpu_id; /* id given by userspace at creation */
3305bad5d55SWang Yong 	int vcpu_idx; /* index into kvm->vcpu_array */
3312031f287SSean Christopherson 	int ____srcu_idx; /* Don't use this directly.  You've been warned. */
3322031f287SSean Christopherson #ifdef CONFIG_PROVE_RCU
3332031f287SSean Christopherson 	int srcu_depth;
3342031f287SSean Christopherson #endif
3356b7e2d09SXiao Guangrong 	int mode;
33686dafed5SKarimAllah Ahmed 	u64 requests;
337d0bfb940SJan Kiszka 	unsigned long guest_debug;
3386b7e2d09SXiao Guangrong 
3396b7e2d09SXiao Guangrong 	struct mutex mutex;
3406b7e2d09SXiao Guangrong 	struct kvm_run *run;
341f656ce01SMarcelo Tosatti 
342510958e9SSean Christopherson #ifndef __KVM_HAVE_ARCH_WQP
343da4ad88cSDavidlohr Bueso 	struct rcuwait wait;
344510958e9SSean Christopherson #endif
3453e7f4318SSean Christopherson 	struct pid *pid;
3463e7f4318SSean Christopherson 	rwlock_t pid_lock;
347edf88417SAvi Kivity 	int sigset_active;
348edf88417SAvi Kivity 	sigset_t sigset;
34919020f8aSWanpeng Li 	unsigned int halt_poll_ns;
3503491caf2SChristian Borntraeger 	bool valid_wakeup;
351edf88417SAvi Kivity 
352edf88417SAvi Kivity #ifdef CONFIG_HAS_IOMEM
353edf88417SAvi Kivity 	int mmio_needed;
354edf88417SAvi Kivity 	int mmio_read_completed;
355edf88417SAvi Kivity 	int mmio_is_write;
356f78146b0SAvi Kivity 	int mmio_cur_fragment;
357f78146b0SAvi Kivity 	int mmio_nr_fragments;
358f78146b0SAvi Kivity 	struct kvm_mmio_fragment mmio_fragments[KVM_MAX_MMIO_FRAGMENTS];
359edf88417SAvi Kivity #endif
360edf88417SAvi Kivity 
361af585b92SGleb Natapov #ifdef CONFIG_KVM_ASYNC_PF
362af585b92SGleb Natapov 	struct {
363af585b92SGleb Natapov 		u32 queued;
364af585b92SGleb Natapov 		struct list_head queue;
365af585b92SGleb Natapov 		struct list_head done;
366af585b92SGleb Natapov 		spinlock_t lock;
367af585b92SGleb Natapov 	} async_pf;
368af585b92SGleb Natapov #endif
369af585b92SGleb Natapov 
3704c088493SRaghavendra K T #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
3714c088493SRaghavendra K T 	/*
3724c088493SRaghavendra K T 	 * Cpu relax intercept or pause loop exit optimization
3734c088493SRaghavendra K T 	 * in_spin_loop: set when a vcpu does a pause loop exit
3744c088493SRaghavendra K T 	 *  or cpu relax intercepted.
3754c088493SRaghavendra K T 	 * dy_eligible: indicates whether vcpu is eligible for directed yield.
3764c088493SRaghavendra K T 	 */
3774c088493SRaghavendra K T 	struct {
3784c088493SRaghavendra K T 		bool in_spin_loop;
3794c088493SRaghavendra K T 		bool dy_eligible;
3804c088493SRaghavendra K T 	} spin_loop;
3814c088493SRaghavendra K T #endif
382a6816314SDavid Matlack 	bool wants_to_run;
3833a08a8f9SRaghavendra K T 	bool preempted;
384d73eb57bSWanpeng Li 	bool ready;
385d1ae567fSSean Christopherson 	bool scheduled_out;
386edf88417SAvi Kivity 	struct kvm_vcpu_arch arch;
387ce55c049SJing Zhang 	struct kvm_vcpu_stat stat;
388ce55c049SJing Zhang 	char stats_id[KVM_STATS_NAME_SIZE];
389fb04a1edSPeter Xu 	struct kvm_dirty_ring dirty_ring;
390fe22ed82SDavid Matlack 
391fe22ed82SDavid Matlack 	/*
392a54d8066SMaciej S. Szmigiero 	 * The most recently used memslot by this vCPU and the slots generation
393a54d8066SMaciej S. Szmigiero 	 * for which it is valid.
394a54d8066SMaciej S. Szmigiero 	 * No wraparound protection is needed since generations won't overflow in
395a54d8066SMaciej S. Szmigiero 	 * thousands of years, even assuming 1M memslot operations per second.
396fe22ed82SDavid Matlack 	 */
397a54d8066SMaciej S. Szmigiero 	struct kvm_memory_slot *last_used_slot;
398a54d8066SMaciej S. Szmigiero 	u64 last_used_slot_gen;
399edf88417SAvi Kivity };
400edf88417SAvi Kivity 
401ef9989afSMark Rutland /*
402ef9989afSMark Rutland  * Start accounting time towards a guest.
403ef9989afSMark Rutland  * Must be called before entering guest context.
404ef9989afSMark Rutland  */
guest_timing_enter_irqoff(void)405ef9989afSMark Rutland static __always_inline void guest_timing_enter_irqoff(void)
4061ca0016cSSean Christopherson {
4071ca0016cSSean Christopherson 	/*
4081ca0016cSSean Christopherson 	 * This is running in ioctl context so its safe to assume that it's the
4091ca0016cSSean Christopherson 	 * stime pending cputime to flush.
4101ca0016cSSean Christopherson 	 */
4111ca0016cSSean Christopherson 	instrumentation_begin();
4121ca0016cSSean Christopherson 	vtime_account_guest_enter();
4131ca0016cSSean Christopherson 	instrumentation_end();
414ef9989afSMark Rutland }
4151ca0016cSSean Christopherson 
4161ca0016cSSean Christopherson /*
417ef9989afSMark Rutland  * Enter guest context and enter an RCU extended quiescent state.
418ef9989afSMark Rutland  *
419ef9989afSMark Rutland  * Between guest_context_enter_irqoff() and guest_context_exit_irqoff() it is
420ef9989afSMark Rutland  * unsafe to use any code which may directly or indirectly use RCU, tracing
421ef9989afSMark Rutland  * (including IRQ flag tracing), or lockdep. All code in this period must be
422ef9989afSMark Rutland  * non-instrumentable.
423ef9989afSMark Rutland  */
guest_context_enter_irqoff(void)424ef9989afSMark Rutland static __always_inline void guest_context_enter_irqoff(void)
425ef9989afSMark Rutland {
426ef9989afSMark Rutland 	/*
4271ca0016cSSean Christopherson 	 * KVM does not hold any references to rcu protected data when it
4281ca0016cSSean Christopherson 	 * switches CPU into a guest mode. In fact switching to a guest mode
4291ca0016cSSean Christopherson 	 * is very similar to exiting to userspace from rcu point of view. In
4301ca0016cSSean Christopherson 	 * addition CPU may stay in a guest mode for quite a long time (up to
4311ca0016cSSean Christopherson 	 * one time slice). Lets treat guest mode as quiescent state, just like
4321ca0016cSSean Christopherson 	 * we do with user-mode execution.
4331ca0016cSSean Christopherson 	 */
4341ca0016cSSean Christopherson 	if (!context_tracking_guest_enter()) {
4351ca0016cSSean Christopherson 		instrumentation_begin();
436b5ad0d2eSZeng Heng 		rcu_virt_note_context_switch();
4371ca0016cSSean Christopherson 		instrumentation_end();
4381ca0016cSSean Christopherson 	}
4391ca0016cSSean Christopherson }
4401ca0016cSSean Christopherson 
441ef9989afSMark Rutland /*
442ef9989afSMark Rutland  * Deprecated. Architectures should move to guest_timing_enter_irqoff() and
443ef9989afSMark Rutland  * guest_state_enter_irqoff().
444ef9989afSMark Rutland  */
guest_enter_irqoff(void)445ef9989afSMark Rutland static __always_inline void guest_enter_irqoff(void)
446ef9989afSMark Rutland {
447ef9989afSMark Rutland 	guest_timing_enter_irqoff();
448ef9989afSMark Rutland 	guest_context_enter_irqoff();
449ef9989afSMark Rutland }
450ef9989afSMark Rutland 
451ef9989afSMark Rutland /**
452ef9989afSMark Rutland  * guest_state_enter_irqoff - Fixup state when entering a guest
453ef9989afSMark Rutland  *
454ef9989afSMark Rutland  * Entry to a guest will enable interrupts, but the kernel state is interrupts
455ef9989afSMark Rutland  * disabled when this is invoked. Also tell RCU about it.
456ef9989afSMark Rutland  *
457ef9989afSMark Rutland  * 1) Trace interrupts on state
458ef9989afSMark Rutland  * 2) Invoke context tracking if enabled to adjust RCU state
459ef9989afSMark Rutland  * 3) Tell lockdep that interrupts are enabled
460ef9989afSMark Rutland  *
461ef9989afSMark Rutland  * Invoked from architecture specific code before entering a guest.
462ef9989afSMark Rutland  * Must be called with interrupts disabled and the caller must be
463ef9989afSMark Rutland  * non-instrumentable.
464ef9989afSMark Rutland  * The caller has to invoke guest_timing_enter_irqoff() before this.
465ef9989afSMark Rutland  *
466ef9989afSMark Rutland  * Note: this is analogous to exit_to_user_mode().
467ef9989afSMark Rutland  */
guest_state_enter_irqoff(void)468ef9989afSMark Rutland static __always_inline void guest_state_enter_irqoff(void)
469ef9989afSMark Rutland {
470ef9989afSMark Rutland 	instrumentation_begin();
471ef9989afSMark Rutland 	trace_hardirqs_on_prepare();
4728b023accSNick Desaulniers 	lockdep_hardirqs_on_prepare();
473ef9989afSMark Rutland 	instrumentation_end();
474ef9989afSMark Rutland 
475ef9989afSMark Rutland 	guest_context_enter_irqoff();
476ef9989afSMark Rutland 	lockdep_hardirqs_on(CALLER_ADDR0);
477ef9989afSMark Rutland }
478ef9989afSMark Rutland 
479ef9989afSMark Rutland /*
480ef9989afSMark Rutland  * Exit guest context and exit an RCU extended quiescent state.
481ef9989afSMark Rutland  *
482ef9989afSMark Rutland  * Between guest_context_enter_irqoff() and guest_context_exit_irqoff() it is
483ef9989afSMark Rutland  * unsafe to use any code which may directly or indirectly use RCU, tracing
484ef9989afSMark Rutland  * (including IRQ flag tracing), or lockdep. All code in this period must be
485ef9989afSMark Rutland  * non-instrumentable.
486ef9989afSMark Rutland  */
guest_context_exit_irqoff(void)487ef9989afSMark Rutland static __always_inline void guest_context_exit_irqoff(void)
4881ca0016cSSean Christopherson {
48959337703SLeonardo Bras 	/*
49059337703SLeonardo Bras 	 * Guest mode is treated as a quiescent state, see
49159337703SLeonardo Bras 	 * guest_context_enter_irqoff() for more details.
49259337703SLeonardo Bras 	 */
49359337703SLeonardo Bras 	if (!context_tracking_guest_exit()) {
49459337703SLeonardo Bras 		instrumentation_begin();
49559337703SLeonardo Bras 		rcu_virt_note_context_switch();
49659337703SLeonardo Bras 		instrumentation_end();
49759337703SLeonardo Bras 	}
498ef9989afSMark Rutland }
4991ca0016cSSean Christopherson 
500ef9989afSMark Rutland /*
501ef9989afSMark Rutland  * Stop accounting time towards a guest.
502ef9989afSMark Rutland  * Must be called after exiting guest context.
503ef9989afSMark Rutland  */
guest_timing_exit_irqoff(void)504ef9989afSMark Rutland static __always_inline void guest_timing_exit_irqoff(void)
505ef9989afSMark Rutland {
5061ca0016cSSean Christopherson 	instrumentation_begin();
5071ca0016cSSean Christopherson 	/* Flush the guest cputime we spent on the guest */
5081ca0016cSSean Christopherson 	vtime_account_guest_exit();
5091ca0016cSSean Christopherson 	instrumentation_end();
5101ca0016cSSean Christopherson }
5111ca0016cSSean Christopherson 
512ef9989afSMark Rutland /*
513ef9989afSMark Rutland  * Deprecated. Architectures should move to guest_state_exit_irqoff() and
514ef9989afSMark Rutland  * guest_timing_exit_irqoff().
515ef9989afSMark Rutland  */
guest_exit_irqoff(void)516ef9989afSMark Rutland static __always_inline void guest_exit_irqoff(void)
517ef9989afSMark Rutland {
518ef9989afSMark Rutland 	guest_context_exit_irqoff();
519ef9989afSMark Rutland 	guest_timing_exit_irqoff();
520ef9989afSMark Rutland }
521ef9989afSMark Rutland 
guest_exit(void)5221ca0016cSSean Christopherson static inline void guest_exit(void)
5231ca0016cSSean Christopherson {
5241ca0016cSSean Christopherson 	unsigned long flags;
5251ca0016cSSean Christopherson 
5261ca0016cSSean Christopherson 	local_irq_save(flags);
5271ca0016cSSean Christopherson 	guest_exit_irqoff();
5281ca0016cSSean Christopherson 	local_irq_restore(flags);
5291ca0016cSSean Christopherson }
5301ca0016cSSean Christopherson 
531ef9989afSMark Rutland /**
532ef9989afSMark Rutland  * guest_state_exit_irqoff - Establish state when returning from guest mode
533ef9989afSMark Rutland  *
534ef9989afSMark Rutland  * Entry from a guest disables interrupts, but guest mode is traced as
535ef9989afSMark Rutland  * interrupts enabled. Also with NO_HZ_FULL RCU might be idle.
536ef9989afSMark Rutland  *
537ef9989afSMark Rutland  * 1) Tell lockdep that interrupts are disabled
538ef9989afSMark Rutland  * 2) Invoke context tracking if enabled to reactivate RCU
539ef9989afSMark Rutland  * 3) Trace interrupts off state
540ef9989afSMark Rutland  *
541ef9989afSMark Rutland  * Invoked from architecture specific code after exiting a guest.
542ef9989afSMark Rutland  * Must be invoked with interrupts disabled and the caller must be
543ef9989afSMark Rutland  * non-instrumentable.
544ef9989afSMark Rutland  * The caller has to invoke guest_timing_exit_irqoff() after this.
545ef9989afSMark Rutland  *
546ef9989afSMark Rutland  * Note: this is analogous to enter_from_user_mode().
547ef9989afSMark Rutland  */
guest_state_exit_irqoff(void)548ef9989afSMark Rutland static __always_inline void guest_state_exit_irqoff(void)
549ef9989afSMark Rutland {
550ef9989afSMark Rutland 	lockdep_hardirqs_off(CALLER_ADDR0);
551ef9989afSMark Rutland 	guest_context_exit_irqoff();
552ef9989afSMark Rutland 
553ef9989afSMark Rutland 	instrumentation_begin();
554ef9989afSMark Rutland 	trace_hardirqs_off_finish();
555ef9989afSMark Rutland 	instrumentation_end();
556ef9989afSMark Rutland }
557ef9989afSMark Rutland 
kvm_vcpu_exiting_guest_mode(struct kvm_vcpu * vcpu)5586b7e2d09SXiao Guangrong static inline int kvm_vcpu_exiting_guest_mode(struct kvm_vcpu *vcpu)
5596b7e2d09SXiao Guangrong {
560cde9af6eSAndrew Jones 	/*
561cde9af6eSAndrew Jones 	 * The memory barrier ensures a previous write to vcpu->requests cannot
562cde9af6eSAndrew Jones 	 * be reordered with the read of vcpu->mode.  It pairs with the general
563cde9af6eSAndrew Jones 	 * memory barrier following the write of vcpu->mode in VCPU RUN.
564cde9af6eSAndrew Jones 	 */
565cde9af6eSAndrew Jones 	smp_mb__before_atomic();
5666b7e2d09SXiao Guangrong 	return cmpxchg(&vcpu->mode, IN_GUEST_MODE, EXITING_GUEST_MODE);
5676b7e2d09SXiao Guangrong }
5686b7e2d09SXiao Guangrong 
569660c22c4STakuya Yoshikawa /*
570660c22c4STakuya Yoshikawa  * Some of the bitops functions do not support too long bitmaps.
571660c22c4STakuya Yoshikawa  * This number must be determined not to exceed such limits.
572660c22c4STakuya Yoshikawa  */
573660c22c4STakuya Yoshikawa #define KVM_MEM_MAX_NR_PAGES ((1UL << 31) - 1)
574660c22c4STakuya Yoshikawa 
575a54d8066SMaciej S. Szmigiero /*
576a54d8066SMaciej S. Szmigiero  * Since at idle each memslot belongs to two memslot sets it has to contain
577a54d8066SMaciej S. Szmigiero  * two embedded nodes for each data structure that it forms a part of.
578a54d8066SMaciej S. Szmigiero  *
579a54d8066SMaciej S. Szmigiero  * Two memslot sets (one active and one inactive) are necessary so the VM
580a54d8066SMaciej S. Szmigiero  * continues to run on one memslot set while the other is being modified.
581a54d8066SMaciej S. Szmigiero  *
582a54d8066SMaciej S. Szmigiero  * These two memslot sets normally point to the same set of memslots.
583a54d8066SMaciej S. Szmigiero  * They can, however, be desynchronized when performing a memslot management
584a54d8066SMaciej S. Szmigiero  * operation by replacing the memslot to be modified by its copy.
585a54d8066SMaciej S. Szmigiero  * After the operation is complete, both memslot sets once again point to
586a54d8066SMaciej S. Szmigiero  * the same, common set of memslot data.
587a54d8066SMaciej S. Szmigiero  *
588a54d8066SMaciej S. Szmigiero  * The memslots themselves are independent of each other so they can be
589a54d8066SMaciej S. Szmigiero  * individually added or deleted.
590a54d8066SMaciej S. Szmigiero  */
591edf88417SAvi Kivity struct kvm_memory_slot {
592a54d8066SMaciej S. Szmigiero 	struct hlist_node id_node[2];
593a54d8066SMaciej S. Szmigiero 	struct interval_tree_node hva_node[2];
594a54d8066SMaciej S. Szmigiero 	struct rb_node gfn_node[2];
595edf88417SAvi Kivity 	gfn_t base_gfn;
596edf88417SAvi Kivity 	unsigned long npages;
597edf88417SAvi Kivity 	unsigned long *dirty_bitmap;
598db3fe4ebSTakuya Yoshikawa 	struct kvm_arch_memory_slot arch;
599edf88417SAvi Kivity 	unsigned long userspace_addr;
6006104f472SAlex Williamson 	u32 flags;
6011e702d9aSAlex Williamson 	short id;
6029e9eb226SPeter Xu 	u16 as_id;
603a7800aa8SSean Christopherson 
604a7800aa8SSean Christopherson #ifdef CONFIG_KVM_PRIVATE_MEM
605a7800aa8SSean Christopherson 	struct {
60667b43038SYan Zhao 		/*
60767b43038SYan Zhao 		 * Writes protected by kvm->slots_lock.  Acquiring a
60867b43038SYan Zhao 		 * reference via kvm_gmem_get_file() is protected by
60967b43038SYan Zhao 		 * either kvm->slots_lock or kvm->srcu.
61067b43038SYan Zhao 		 */
61167b43038SYan Zhao 		struct file *file;
612a7800aa8SSean Christopherson 		pgoff_t pgoff;
613a7800aa8SSean Christopherson 	} gmem;
614a7800aa8SSean Christopherson #endif
615edf88417SAvi Kivity };
616edf88417SAvi Kivity 
kvm_slot_can_be_private(const struct kvm_memory_slot * slot)617a7800aa8SSean Christopherson static inline bool kvm_slot_can_be_private(const struct kvm_memory_slot *slot)
618a7800aa8SSean Christopherson {
619a7800aa8SSean Christopherson 	return slot && (slot->flags & KVM_MEM_GUEST_MEMFD);
620a7800aa8SSean Christopherson }
621a7800aa8SSean Christopherson 
kvm_slot_dirty_track_enabled(const struct kvm_memory_slot * slot)6228283e36aSBen Gardon static inline bool kvm_slot_dirty_track_enabled(const struct kvm_memory_slot *slot)
623044c59c4SPeter Xu {
624044c59c4SPeter Xu 	return slot->flags & KVM_MEM_LOG_DIRTY_PAGES;
625044c59c4SPeter Xu }
626044c59c4SPeter Xu 
kvm_dirty_bitmap_bytes(struct kvm_memory_slot * memslot)62787bf6e7dSTakuya Yoshikawa static inline unsigned long kvm_dirty_bitmap_bytes(struct kvm_memory_slot *memslot)
62887bf6e7dSTakuya Yoshikawa {
62987bf6e7dSTakuya Yoshikawa 	return ALIGN(memslot->npages, BITS_PER_LONG) / 8;
63087bf6e7dSTakuya Yoshikawa }
63187bf6e7dSTakuya Yoshikawa 
kvm_second_dirty_bitmap(struct kvm_memory_slot * memslot)63203133347SClaudio Imbrenda static inline unsigned long *kvm_second_dirty_bitmap(struct kvm_memory_slot *memslot)
63303133347SClaudio Imbrenda {
63403133347SClaudio Imbrenda 	unsigned long len = kvm_dirty_bitmap_bytes(memslot);
63503133347SClaudio Imbrenda 
63603133347SClaudio Imbrenda 	return memslot->dirty_bitmap + len / sizeof(*memslot->dirty_bitmap);
63703133347SClaudio Imbrenda }
63803133347SClaudio Imbrenda 
6393c9bd400SJay Zhou #ifndef KVM_DIRTY_LOG_MANUAL_CAPS
6403c9bd400SJay Zhou #define KVM_DIRTY_LOG_MANUAL_CAPS KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE
6413c9bd400SJay Zhou #endif
6423c9bd400SJay Zhou 
64384223598SCornelia Huck struct kvm_s390_adapter_int {
64484223598SCornelia Huck 	u64 ind_addr;
64584223598SCornelia Huck 	u64 summary_addr;
64684223598SCornelia Huck 	u64 ind_offset;
64784223598SCornelia Huck 	u32 summary_offset;
64884223598SCornelia Huck 	u32 adapter_id;
64984223598SCornelia Huck };
65084223598SCornelia Huck 
6515c919412SAndrey Smetanin struct kvm_hv_sint {
6525c919412SAndrey Smetanin 	u32 vcpu;
6535c919412SAndrey Smetanin 	u32 sint;
6545c919412SAndrey Smetanin };
6555c919412SAndrey Smetanin 
65614243b38SDavid Woodhouse struct kvm_xen_evtchn {
65714243b38SDavid Woodhouse 	u32 port;
6588733068bSDavid Woodhouse 	u32 vcpu_id;
6598733068bSDavid Woodhouse 	int vcpu_idx;
66014243b38SDavid Woodhouse 	u32 priority;
66114243b38SDavid Woodhouse };
66214243b38SDavid Woodhouse 
663399ec807SAvi Kivity struct kvm_kernel_irq_routing_entry {
664399ec807SAvi Kivity 	u32 gsi;
6655116d8f6SMichael S. Tsirkin 	u32 type;
6664925663aSGleb Natapov 	int (*set)(struct kvm_kernel_irq_routing_entry *e,
667aa2fbe6dSYang Zhang 		   struct kvm *kvm, int irq_source_id, int level,
668aa2fbe6dSYang Zhang 		   bool line_status);
669399ec807SAvi Kivity 	union {
670399ec807SAvi Kivity 		struct {
671399ec807SAvi Kivity 			unsigned irqchip;
672399ec807SAvi Kivity 			unsigned pin;
673399ec807SAvi Kivity 		} irqchip;
6740455e72cSEric Auger 		struct {
6750455e72cSEric Auger 			u32 address_lo;
6760455e72cSEric Auger 			u32 address_hi;
6770455e72cSEric Auger 			u32 data;
6780455e72cSEric Auger 			u32 flags;
6790455e72cSEric Auger 			u32 devid;
6800455e72cSEric Auger 		} msi;
68184223598SCornelia Huck 		struct kvm_s390_adapter_int adapter;
6825c919412SAndrey Smetanin 		struct kvm_hv_sint hv_sint;
68314243b38SDavid Woodhouse 		struct kvm_xen_evtchn xen_evtchn;
684399ec807SAvi Kivity 	};
68546e624b9SGleb Natapov 	struct hlist_node link;
68646e624b9SGleb Natapov };
68746e624b9SGleb Natapov 
688b053b2aeSSteve Rutherford #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
689b053b2aeSSteve Rutherford struct kvm_irq_routing_table {
690b053b2aeSSteve Rutherford 	int chip[KVM_NR_IRQCHIPS][KVM_IRQCHIP_NUM_PINS];
691b053b2aeSSteve Rutherford 	u32 nr_rt_entries;
692b053b2aeSSteve Rutherford 	/*
693b053b2aeSSteve Rutherford 	 * Array indexed by gsi. Each entry contains list of irq chips
694b053b2aeSSteve Rutherford 	 * the gsi is connected to.
695b053b2aeSSteve Rutherford 	 */
696a48e1f65SKees Cook 	struct hlist_head map[] __counted_by(nr_rt_entries);
697b053b2aeSSteve Rutherford };
698b053b2aeSSteve Rutherford #endif
699b053b2aeSSteve Rutherford 
700d663b8a2SPaolo Bonzini bool kvm_arch_irqchip_in_kernel(struct kvm *kvm);
70146e624b9SGleb Natapov 
702bdd1c37aSChao Peng #ifndef KVM_INTERNAL_MEM_SLOTS
703bdd1c37aSChao Peng #define KVM_INTERNAL_MEM_SLOTS 0
7040743247fSAlex Williamson #endif
7050743247fSAlex Williamson 
7064fc096a9SVitaly Kuznetsov #define KVM_MEM_SLOTS_NUM SHRT_MAX
707bdd1c37aSChao Peng #define KVM_USER_MEM_SLOTS (KVM_MEM_SLOTS_NUM - KVM_INTERNAL_MEM_SLOTS)
70893a5cef0SXiao Guangrong 
709eed52e43SSean Christopherson #if KVM_MAX_NR_ADDRESS_SPACES == 1
kvm_arch_nr_memslot_as_ids(struct kvm * kvm)710eed52e43SSean Christopherson static inline int kvm_arch_nr_memslot_as_ids(struct kvm *kvm)
711eed52e43SSean Christopherson {
712eed52e43SSean Christopherson 	return KVM_MAX_NR_ADDRESS_SPACES;
713eed52e43SSean Christopherson }
714eed52e43SSean Christopherson 
kvm_arch_vcpu_memslots_id(struct kvm_vcpu * vcpu)715f481b069SPaolo Bonzini static inline int kvm_arch_vcpu_memslots_id(struct kvm_vcpu *vcpu)
716f481b069SPaolo Bonzini {
717f481b069SPaolo Bonzini 	return 0;
718f481b069SPaolo Bonzini }
719f481b069SPaolo Bonzini #endif
720f481b069SPaolo Bonzini 
721a7800aa8SSean Christopherson /*
722a7800aa8SSean Christopherson  * Arch code must define kvm_arch_has_private_mem if support for private memory
723a7800aa8SSean Christopherson  * is enabled.
724a7800aa8SSean Christopherson  */
725a7800aa8SSean Christopherson #if !defined(kvm_arch_has_private_mem) && !IS_ENABLED(CONFIG_KVM_PRIVATE_MEM)
kvm_arch_has_private_mem(struct kvm * kvm)726a7800aa8SSean Christopherson static inline bool kvm_arch_has_private_mem(struct kvm *kvm)
727a7800aa8SSean Christopherson {
728a7800aa8SSean Christopherson 	return false;
729a7800aa8SSean Christopherson }
730a7800aa8SSean Christopherson #endif
731a7800aa8SSean Christopherson 
73266155de9SSean Christopherson #ifndef kvm_arch_has_readonly_mem
kvm_arch_has_readonly_mem(struct kvm * kvm)73366155de9SSean Christopherson static inline bool kvm_arch_has_readonly_mem(struct kvm *kvm)
73466155de9SSean Christopherson {
73566155de9SSean Christopherson 	return IS_ENABLED(CONFIG_HAVE_KVM_READONLY_MEM);
73666155de9SSean Christopherson }
73766155de9SSean Christopherson #endif
73866155de9SSean Christopherson 
73946a26bf5SMarcelo Tosatti struct kvm_memslots {
74049c7754cSGleb Natapov 	u64 generation;
741a54d8066SMaciej S. Szmigiero 	atomic_long_t last_used_slot;
742ed922739SMaciej S. Szmigiero 	struct rb_root_cached hva_tree;
743a54d8066SMaciej S. Szmigiero 	struct rb_root gfn_tree;
74426b8345aSMaciej S. Szmigiero 	/*
745a54d8066SMaciej S. Szmigiero 	 * The mapping table from slot id to memslot.
74626b8345aSMaciej S. Szmigiero 	 *
74726b8345aSMaciej S. Szmigiero 	 * 7-bit bucket count matches the size of the old id to index array for
74826b8345aSMaciej S. Szmigiero 	 * 512 slots, while giving good performance with this slot count.
74926b8345aSMaciej S. Szmigiero 	 * Higher bucket counts bring only small performance improvements but
75026b8345aSMaciej S. Szmigiero 	 * always result in higher memory usage (even for lower memslot counts).
75126b8345aSMaciej S. Szmigiero 	 */
75226b8345aSMaciej S. Szmigiero 	DECLARE_HASHTABLE(id_hash, 7);
753a54d8066SMaciej S. Szmigiero 	int node_idx;
75446a26bf5SMarcelo Tosatti };
75546a26bf5SMarcelo Tosatti 
756edf88417SAvi Kivity struct kvm {
757531810caSBen Gardon #ifdef KVM_HAVE_MMU_RWLOCK
758531810caSBen Gardon 	rwlock_t mmu_lock;
759531810caSBen Gardon #else
760aaee2c94SMarcelo Tosatti 	spinlock_t mmu_lock;
761531810caSBen Gardon #endif /* KVM_HAVE_MMU_RWLOCK */
762531810caSBen Gardon 
76379fac95eSMarcelo Tosatti 	struct mutex slots_lock;
764b10a038eSBen Gardon 
765b10a038eSBen Gardon 	/*
766b10a038eSBen Gardon 	 * Protects the arch-specific fields of struct kvm_memory_slots in
767b10a038eSBen Gardon 	 * use by the VM. To be used under the slots_lock (above) or in a
768b10a038eSBen Gardon 	 * kvm->srcu critical section where acquiring the slots_lock would
769b10a038eSBen Gardon 	 * lead to deadlock with the synchronize_srcu in
770b0d23708SJun Miao 	 * kvm_swap_active_memslots().
771b10a038eSBen Gardon 	 */
772b10a038eSBen Gardon 	struct mutex slots_arch_lock;
773edf88417SAvi Kivity 	struct mm_struct *mm; /* userspace tied to this vm */
774afa319a5SSean Christopherson 	unsigned long nr_memslot_pages;
775a54d8066SMaciej S. Szmigiero 	/* The two memslot sets - active and inactive (per address space) */
776eed52e43SSean Christopherson 	struct kvm_memslots __memslots[KVM_MAX_NR_ADDRESS_SPACES][2];
777a54d8066SMaciej S. Szmigiero 	/* The current active memslot set for each address space */
778eed52e43SSean Christopherson 	struct kvm_memslots __rcu *memslots[KVM_MAX_NR_ADDRESS_SPACES];
779c5b07754SMarc Zyngier 	struct xarray vcpu_array;
7806c7b2202SPaolo Bonzini 	/*
7816c7b2202SPaolo Bonzini 	 * Protected by slots_lock, but can be read outside if an
7826c7b2202SPaolo Bonzini 	 * incorrect answer is acceptable.
7836c7b2202SPaolo Bonzini 	 */
7846c7b2202SPaolo Bonzini 	atomic_t nr_memslots_dirty_logging;
7856c7caebcSPaolo Bonzini 
78652ac8b35SPaolo Bonzini 	/* Used to wait for completion of MMU notifiers.  */
78752ac8b35SPaolo Bonzini 	spinlock_t mn_invalidate_lock;
78852ac8b35SPaolo Bonzini 	unsigned long mn_active_invalidate_count;
78952ac8b35SPaolo Bonzini 	struct rcuwait mn_memslots_update_rcuwait;
79052ac8b35SPaolo Bonzini 
791982ed0deSDavid Woodhouse 	/* For management / invalidation of gfn_to_pfn_caches */
792982ed0deSDavid Woodhouse 	spinlock_t gpc_lock;
793982ed0deSDavid Woodhouse 	struct list_head gpc_list;
794982ed0deSDavid Woodhouse 
7956c7caebcSPaolo Bonzini 	/*
7966c7caebcSPaolo Bonzini 	 * created_vcpus is protected by kvm->lock, and is incremented
7976c7caebcSPaolo Bonzini 	 * at the beginning of KVM_CREATE_VCPU.  online_vcpus is only
7986c7caebcSPaolo Bonzini 	 * incremented after storing the kvm_vcpu pointer in vcpus,
7996c7caebcSPaolo Bonzini 	 * and is accessed atomically.
8006c7caebcSPaolo Bonzini 	 */
80173880c80SGleb Natapov 	atomic_t online_vcpus;
802f502cc56SSean Christopherson 	int max_vcpus;
8036c7caebcSPaolo Bonzini 	int created_vcpus;
804217ece61SRik van Riel 	int last_boosted_vcpu;
805edf88417SAvi Kivity 	struct list_head vm_list;
80660eead79SMarcelo Tosatti 	struct mutex lock;
8074a12f951SChristian Borntraeger 	struct kvm_io_bus __rcu *buses[KVM_NR_BUSES];
8088ed26ab8SPaolo Bonzini #ifdef CONFIG_HAVE_KVM_IRQCHIP
809721eecbfSGregory Haskins 	struct {
810721eecbfSGregory Haskins 		spinlock_t        lock;
811721eecbfSGregory Haskins 		struct list_head  items;
812d583fbd7SDmytro Maluka 		/* resampler_list update side is protected by resampler_lock. */
8137a84428aSAlex Williamson 		struct list_head  resampler_list;
8147a84428aSAlex Williamson 		struct mutex      resampler_lock;
815721eecbfSGregory Haskins 	} irqfds;
8168ed26ab8SPaolo Bonzini #endif
817d34e6b17SGregory Haskins 	struct list_head ioeventfds;
818edf88417SAvi Kivity 	struct kvm_vm_stat stat;
819edf88417SAvi Kivity 	struct kvm_arch arch;
820e3736c3eSElena Reshetova 	refcount_t users_count;
8214b4357e0SPaolo Bonzini #ifdef CONFIG_KVM_MMIO
8225f94c174SLaurent Vivier 	struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
8232b3c246aSSasha Levin 	spinlock_t ring_lock;
8242b3c246aSSasha Levin 	struct list_head coalesced_zones;
8255f94c174SLaurent Vivier #endif
826e930bffeSAndrea Arcangeli 
82760eead79SMarcelo Tosatti 	struct mutex irq_lock;
82875858a84SAvi Kivity #ifdef CONFIG_HAVE_KVM_IRQCHIP
829bd2b53b2SMichael S. Tsirkin 	/*
8309957c86dSPaul Mackerras 	 * Update side is protected by irq_lock.
831bd2b53b2SMichael S. Tsirkin 	 */
8324b6a2872SArnd Bergmann 	struct kvm_irq_routing_table __rcu *irq_routing;
833c5b31cc2SPaolo Bonzini 
834136bdfeeSGleb Natapov 	struct hlist_head irq_ack_notifier_list;
83575858a84SAvi Kivity #endif
83675858a84SAvi Kivity 
837f128cf8cSSean Christopherson #ifdef CONFIG_KVM_GENERIC_MMU_NOTIFIER
838e930bffeSAndrea Arcangeli 	struct mmu_notifier mmu_notifier;
83920ec3ebdSChao Peng 	unsigned long mmu_invalidate_seq;
84020ec3ebdSChao Peng 	long mmu_invalidate_in_progress;
8418569992dSChao Peng 	gfn_t mmu_invalidate_range_start;
8428569992dSChao Peng 	gfn_t mmu_invalidate_range_end;
843e930bffeSAndrea Arcangeli #endif
84407f0a7bdSScott Wood 	struct list_head devices;
8453c9bd400SJay Zhou 	u64 manual_dirty_log_protect;
846536a6f88SJanosch Frank 	struct dentry *debugfs_dentry;
847536a6f88SJanosch Frank 	struct kvm_stat_data **debugfs_stat_data;
8486ade8694SPaul E. McKenney 	struct srcu_struct srcu;
8496ade8694SPaul E. McKenney 	struct srcu_struct irq_srcu;
850fdeaf7e3SClaudio Imbrenda 	pid_t userspace_pid;
8519eb8ca04SDavid Matlack 	bool override_halt_poll_ns;
852acd05785SDavid Matlack 	unsigned int max_halt_poll_ns;
853fb04a1edSPeter Xu 	u32 dirty_ring_size;
85486bdf3ebSGavin Shan 	bool dirty_ring_with_bitmap;
8550b8f1173SSean Christopherson 	bool vm_bugged;
856f4d31653SPaolo Bonzini 	bool vm_dead;
8572fdef3a2SSergey Senozhatsky 
8582fdef3a2SSergey Senozhatsky #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
8592fdef3a2SSergey Senozhatsky 	struct notifier_block pm_notifier;
8602fdef3a2SSergey Senozhatsky #endif
8615a475554SChao Peng #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
8625a475554SChao Peng 	/* Protected by slots_locks (for writes) and RCU (for reads) */
8635a475554SChao Peng 	struct xarray mem_attr_array;
8645a475554SChao Peng #endif
865fcfe1baeSJing Zhang 	char stats_id[KVM_STATS_NAME_SIZE];
866edf88417SAvi Kivity };
867edf88417SAvi Kivity 
868a737f256SChristoffer Dall #define kvm_err(fmt, ...) \
869a737f256SChristoffer Dall 	pr_err("kvm [%i]: " fmt, task_pid_nr(current), ## __VA_ARGS__)
870a737f256SChristoffer Dall #define kvm_info(fmt, ...) \
871a737f256SChristoffer Dall 	pr_info("kvm [%i]: " fmt, task_pid_nr(current), ## __VA_ARGS__)
872a737f256SChristoffer Dall #define kvm_debug(fmt, ...) \
873a737f256SChristoffer Dall 	pr_debug("kvm [%i]: " fmt, task_pid_nr(current), ## __VA_ARGS__)
874ae0f5499SBandan Das #define kvm_debug_ratelimited(fmt, ...) \
875ae0f5499SBandan Das 	pr_debug_ratelimited("kvm [%i]: " fmt, task_pid_nr(current), \
876ae0f5499SBandan Das 			     ## __VA_ARGS__)
877a737f256SChristoffer Dall #define kvm_pr_unimpl(fmt, ...) \
878a737f256SChristoffer Dall 	pr_err_ratelimited("kvm [%i]: " fmt, \
879a737f256SChristoffer Dall 			   task_tgid_nr(current), ## __VA_ARGS__)
880edf88417SAvi Kivity 
881a737f256SChristoffer Dall /* The guest did something we don't support. */
882a737f256SChristoffer Dall #define vcpu_unimpl(vcpu, fmt, ...)					\
883671d9ab3SBorislav Petkov 	kvm_pr_unimpl("vcpu%i, guest rIP: 0x%lx " fmt,			\
884671d9ab3SBorislav Petkov 			(vcpu)->vcpu_id, kvm_rip_read(vcpu), ## __VA_ARGS__)
885edf88417SAvi Kivity 
886ee86dbc6SAndrey Smetanin #define vcpu_debug(vcpu, fmt, ...)					\
887ee86dbc6SAndrey Smetanin 	kvm_debug("vcpu%i " fmt, (vcpu)->vcpu_id, ## __VA_ARGS__)
888ae0f5499SBandan Das #define vcpu_debug_ratelimited(vcpu, fmt, ...)				\
889ae0f5499SBandan Das 	kvm_debug_ratelimited("vcpu%i " fmt, (vcpu)->vcpu_id,           \
890ae0f5499SBandan Das 			      ## __VA_ARGS__)
891765eaa0fSAndrey Smetanin #define vcpu_err(vcpu, fmt, ...)					\
892765eaa0fSAndrey Smetanin 	kvm_err("vcpu%i " fmt, (vcpu)->vcpu_id, ## __VA_ARGS__)
893ee86dbc6SAndrey Smetanin 
kvm_vm_dead(struct kvm * kvm)894f4d31653SPaolo Bonzini static inline void kvm_vm_dead(struct kvm *kvm)
895f4d31653SPaolo Bonzini {
896f4d31653SPaolo Bonzini 	kvm->vm_dead = true;
897f4d31653SPaolo Bonzini 	kvm_make_all_cpus_request(kvm, KVM_REQ_VM_DEAD);
898f4d31653SPaolo Bonzini }
899f4d31653SPaolo Bonzini 
kvm_vm_bugged(struct kvm * kvm)9000b8f1173SSean Christopherson static inline void kvm_vm_bugged(struct kvm *kvm)
9010b8f1173SSean Christopherson {
9020b8f1173SSean Christopherson 	kvm->vm_bugged = true;
903f4d31653SPaolo Bonzini 	kvm_vm_dead(kvm);
9040b8f1173SSean Christopherson }
9050b8f1173SSean Christopherson 
906f4d31653SPaolo Bonzini 
9070b8f1173SSean Christopherson #define KVM_BUG(cond, kvm, fmt...)				\
9080b8f1173SSean Christopherson ({								\
909c9d60154SWei Wang 	bool __ret = !!(cond);					\
9100b8f1173SSean Christopherson 								\
9110b8f1173SSean Christopherson 	if (WARN_ONCE(__ret && !(kvm)->vm_bugged, fmt))		\
9120b8f1173SSean Christopherson 		kvm_vm_bugged(kvm);				\
9130b8f1173SSean Christopherson 	unlikely(__ret);					\
9140b8f1173SSean Christopherson })
9150b8f1173SSean Christopherson 
9160b8f1173SSean Christopherson #define KVM_BUG_ON(cond, kvm)					\
9170b8f1173SSean Christopherson ({								\
918c9d60154SWei Wang 	bool __ret = !!(cond);					\
9190b8f1173SSean Christopherson 								\
9200b8f1173SSean Christopherson 	if (WARN_ON_ONCE(__ret && !(kvm)->vm_bugged))		\
9210b8f1173SSean Christopherson 		kvm_vm_bugged(kvm);				\
9220b8f1173SSean Christopherson 	unlikely(__ret);					\
9230b8f1173SSean Christopherson })
9240b8f1173SSean Christopherson 
92552e322edSSean Christopherson /*
92652e322edSSean Christopherson  * Note, "data corruption" refers to corruption of host kernel data structures,
92752e322edSSean Christopherson  * not guest data.  Guest data corruption, suspected or confirmed, that is tied
92852e322edSSean Christopherson  * and contained to a single VM should *never* BUG() and potentially panic the
92952e322edSSean Christopherson  * host, i.e. use this variant of KVM_BUG() if and only if a KVM data structure
93052e322edSSean Christopherson  * is corrupted and that corruption can have a cascading effect to other parts
93152e322edSSean Christopherson  * of the hosts and/or to other VMs.
93252e322edSSean Christopherson  */
93352e322edSSean Christopherson #define KVM_BUG_ON_DATA_CORRUPTION(cond, kvm)			\
93452e322edSSean Christopherson ({								\
93552e322edSSean Christopherson 	bool __ret = !!(cond);					\
93652e322edSSean Christopherson 								\
93752e322edSSean Christopherson 	if (IS_ENABLED(CONFIG_BUG_ON_DATA_CORRUPTION))		\
93852e322edSSean Christopherson 		BUG_ON(__ret);					\
93952e322edSSean Christopherson 	else if (WARN_ON_ONCE(__ret && !(kvm)->vm_bugged))	\
94052e322edSSean Christopherson 		kvm_vm_bugged(kvm);				\
94152e322edSSean Christopherson 	unlikely(__ret);					\
94252e322edSSean Christopherson })
94352e322edSSean Christopherson 
kvm_vcpu_srcu_read_lock(struct kvm_vcpu * vcpu)9442031f287SSean Christopherson static inline void kvm_vcpu_srcu_read_lock(struct kvm_vcpu *vcpu)
9452031f287SSean Christopherson {
9462031f287SSean Christopherson #ifdef CONFIG_PROVE_RCU
9472031f287SSean Christopherson 	WARN_ONCE(vcpu->srcu_depth++,
9482031f287SSean Christopherson 		  "KVM: Illegal vCPU srcu_idx LOCK, depth=%d", vcpu->srcu_depth - 1);
9492031f287SSean Christopherson #endif
9502031f287SSean Christopherson 	vcpu->____srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
9512031f287SSean Christopherson }
9522031f287SSean Christopherson 
kvm_vcpu_srcu_read_unlock(struct kvm_vcpu * vcpu)9532031f287SSean Christopherson static inline void kvm_vcpu_srcu_read_unlock(struct kvm_vcpu *vcpu)
9542031f287SSean Christopherson {
9552031f287SSean Christopherson 	srcu_read_unlock(&vcpu->kvm->srcu, vcpu->____srcu_idx);
9562031f287SSean Christopherson 
9572031f287SSean Christopherson #ifdef CONFIG_PROVE_RCU
9582031f287SSean Christopherson 	WARN_ONCE(--vcpu->srcu_depth,
9592031f287SSean Christopherson 		  "KVM: Illegal vCPU srcu_idx UNLOCK, depth=%d", vcpu->srcu_depth);
9602031f287SSean Christopherson #endif
9612031f287SSean Christopherson }
9622031f287SSean Christopherson 
kvm_dirty_log_manual_protect_and_init_set(struct kvm * kvm)9633c9bd400SJay Zhou static inline bool kvm_dirty_log_manual_protect_and_init_set(struct kvm *kvm)
9643c9bd400SJay Zhou {
9653c9bd400SJay Zhou 	return !!(kvm->manual_dirty_log_protect & KVM_DIRTY_LOG_INITIALLY_SET);
9663c9bd400SJay Zhou }
9673c9bd400SJay Zhou 
kvm_get_bus(struct kvm * kvm,enum kvm_bus idx)9684a12f951SChristian Borntraeger static inline struct kvm_io_bus *kvm_get_bus(struct kvm *kvm, enum kvm_bus idx)
9694a12f951SChristian Borntraeger {
9704a12f951SChristian Borntraeger 	return srcu_dereference_check(kvm->buses[idx], &kvm->srcu,
9713898da94SPaolo Bonzini 				      lockdep_is_held(&kvm->slots_lock) ||
9723898da94SPaolo Bonzini 				      !refcount_read(&kvm->users_count));
9734a12f951SChristian Borntraeger }
9744a12f951SChristian Borntraeger 
kvm_get_vcpu(struct kvm * kvm,int i)975988a2caeSGleb Natapov static inline struct kvm_vcpu *kvm_get_vcpu(struct kvm *kvm, int i)
976988a2caeSGleb Natapov {
9771d487e9bSPaolo Bonzini 	int num_vcpus = atomic_read(&kvm->online_vcpus);
9781e7381f3SSean Christopherson 
9791e7381f3SSean Christopherson 	/*
9801e7381f3SSean Christopherson 	 * Explicitly verify the target vCPU is online, as the anti-speculation
9811e7381f3SSean Christopherson 	 * logic only limits the CPU's ability to speculate, e.g. given a "bad"
9821e7381f3SSean Christopherson 	 * index, clamping the index to 0 would return vCPU0, not NULL.
9831e7381f3SSean Christopherson 	 */
9841e7381f3SSean Christopherson 	if (i >= num_vcpus)
9851e7381f3SSean Christopherson 		return NULL;
9861e7381f3SSean Christopherson 
9871d487e9bSPaolo Bonzini 	i = array_index_nospec(i, num_vcpus);
9881d487e9bSPaolo Bonzini 
9891d487e9bSPaolo Bonzini 	/* Pairs with smp_wmb() in kvm_vm_ioctl_create_vcpu.  */
990988a2caeSGleb Natapov 	smp_rmb();
991c5b07754SMarc Zyngier 	return xa_load(&kvm->vcpu_array, i);
992988a2caeSGleb Natapov }
993988a2caeSGleb Natapov 
994988a2caeSGleb Natapov #define kvm_for_each_vcpu(idx, vcpup, kvm)				\
9950664dc74SSean Christopherson 	if (atomic_read(&kvm->online_vcpus))				\
996214bd3a6SMarc Zyngier 		xa_for_each_range(&kvm->vcpu_array, idx, vcpup, 0,	\
997214bd3a6SMarc Zyngier 				  (atomic_read(&kvm->online_vcpus) - 1))
998988a2caeSGleb Natapov 
kvm_get_vcpu_by_id(struct kvm * kvm,int id)999db27a7a3SDavid Hildenbrand static inline struct kvm_vcpu *kvm_get_vcpu_by_id(struct kvm *kvm, int id)
1000db27a7a3SDavid Hildenbrand {
10019b9e3fc4SGreg Kurz 	struct kvm_vcpu *vcpu = NULL;
100246808a4cSMarc Zyngier 	unsigned long i;
1003db27a7a3SDavid Hildenbrand 
10049b9e3fc4SGreg Kurz 	if (id < 0)
1005c896939fSDavid Hildenbrand 		return NULL;
10069b9e3fc4SGreg Kurz 	if (id < KVM_MAX_VCPUS)
1007c896939fSDavid Hildenbrand 		vcpu = kvm_get_vcpu(kvm, id);
1008c896939fSDavid Hildenbrand 	if (vcpu && vcpu->vcpu_id == id)
1009c896939fSDavid Hildenbrand 		return vcpu;
1010db27a7a3SDavid Hildenbrand 	kvm_for_each_vcpu(i, vcpu, kvm)
1011db27a7a3SDavid Hildenbrand 		if (vcpu->vcpu_id == id)
1012db27a7a3SDavid Hildenbrand 			return vcpu;
1013db27a7a3SDavid Hildenbrand 	return NULL;
1014db27a7a3SDavid Hildenbrand }
1015db27a7a3SDavid Hildenbrand 
101627592ae8SMarc Zyngier void kvm_destroy_vcpus(struct kvm *kvm);
1017edf88417SAvi Kivity 
1018ec7660ccSChristoffer Dall void vcpu_load(struct kvm_vcpu *vcpu);
1019edf88417SAvi Kivity void vcpu_put(struct kvm_vcpu *vcpu);
1020edf88417SAvi Kivity 
10216ef768faSPaolo Bonzini #ifdef __KVM_HAVE_IOAPIC
1022993225adSDavid Hildenbrand void kvm_arch_post_irq_ack_notifier_list_update(struct kvm *kvm);
1023abdb080fSAndrey Smetanin void kvm_arch_post_irq_routing_update(struct kvm *kvm);
10246ef768faSPaolo Bonzini #else
kvm_arch_post_irq_ack_notifier_list_update(struct kvm * kvm)1025993225adSDavid Hildenbrand static inline void kvm_arch_post_irq_ack_notifier_list_update(struct kvm *kvm)
10266ef768faSPaolo Bonzini {
10276ef768faSPaolo Bonzini }
kvm_arch_post_irq_routing_update(struct kvm * kvm)1028abdb080fSAndrey Smetanin static inline void kvm_arch_post_irq_routing_update(struct kvm *kvm)
1029b053b2aeSSteve Rutherford {
1030b053b2aeSSteve Rutherford }
10316ef768faSPaolo Bonzini #endif
10326ef768faSPaolo Bonzini 
1033c5b31cc2SPaolo Bonzini #ifdef CONFIG_HAVE_KVM_IRQCHIP
1034a0f155e9SCornelia Huck int kvm_irqfd_init(void);
1035a0f155e9SCornelia Huck void kvm_irqfd_exit(void);
1036a0f155e9SCornelia Huck #else
kvm_irqfd_init(void)1037a0f155e9SCornelia Huck static inline int kvm_irqfd_init(void)
1038a0f155e9SCornelia Huck {
1039a0f155e9SCornelia Huck 	return 0;
1040a0f155e9SCornelia Huck }
1041a0f155e9SCornelia Huck 
kvm_irqfd_exit(void)1042a0f155e9SCornelia Huck static inline void kvm_irqfd_exit(void)
1043a0f155e9SCornelia Huck {
1044a0f155e9SCornelia Huck }
1045a0f155e9SCornelia Huck #endif
104681a1cf9fSSean Christopherson int kvm_init(unsigned vcpu_size, unsigned vcpu_align, struct module *module);
1047edf88417SAvi Kivity void kvm_exit(void);
1048edf88417SAvi Kivity 
1049d39f13b0SIzik Eidus void kvm_get_kvm(struct kvm *kvm);
1050605c7130SPeter Xu bool kvm_get_kvm_safe(struct kvm *kvm);
1051d39f13b0SIzik Eidus void kvm_put_kvm(struct kvm *kvm);
105254526d1fSNathan Tempelman bool file_is_kvm(struct file *file);
1053149487bdSSean Christopherson void kvm_put_kvm_no_destroy(struct kvm *kvm);
1054d39f13b0SIzik Eidus 
__kvm_memslots(struct kvm * kvm,int as_id)1055f481b069SPaolo Bonzini static inline struct kvm_memslots *__kvm_memslots(struct kvm *kvm, int as_id)
105690d83dc3SLai Jiangshan {
1057eed52e43SSean Christopherson 	as_id = array_index_nospec(as_id, KVM_MAX_NR_ADDRESS_SPACES);
10587e988b10SChristian Borntraeger 	return srcu_dereference_check(kvm->memslots[as_id], &kvm->srcu,
10593898da94SPaolo Bonzini 			lockdep_is_held(&kvm->slots_lock) ||
10603898da94SPaolo Bonzini 			!refcount_read(&kvm->users_count));
106190d83dc3SLai Jiangshan }
106290d83dc3SLai Jiangshan 
kvm_memslots(struct kvm * kvm)1063f481b069SPaolo Bonzini static inline struct kvm_memslots *kvm_memslots(struct kvm *kvm)
1064f481b069SPaolo Bonzini {
1065f481b069SPaolo Bonzini 	return __kvm_memslots(kvm, 0);
1066f481b069SPaolo Bonzini }
1067f481b069SPaolo Bonzini 
kvm_vcpu_memslots(struct kvm_vcpu * vcpu)10688e73485cSPaolo Bonzini static inline struct kvm_memslots *kvm_vcpu_memslots(struct kvm_vcpu *vcpu)
10698e73485cSPaolo Bonzini {
1070f481b069SPaolo Bonzini 	int as_id = kvm_arch_vcpu_memslots_id(vcpu);
1071f481b069SPaolo Bonzini 
1072f481b069SPaolo Bonzini 	return __kvm_memslots(vcpu->kvm, as_id);
10738e73485cSPaolo Bonzini }
10748e73485cSPaolo Bonzini 
kvm_memslots_empty(struct kvm_memslots * slots)1075a54d8066SMaciej S. Szmigiero static inline bool kvm_memslots_empty(struct kvm_memslots *slots)
1076a54d8066SMaciej S. Szmigiero {
1077a54d8066SMaciej S. Szmigiero 	return RB_EMPTY_ROOT(&slots->gfn_tree);
1078a54d8066SMaciej S. Szmigiero }
1079a54d8066SMaciej S. Szmigiero 
108026f45714SRicardo Koller bool kvm_are_all_memslots_empty(struct kvm *kvm);
108126f45714SRicardo Koller 
1082a54d8066SMaciej S. Szmigiero #define kvm_for_each_memslot(memslot, bkt, slots)			      \
1083a54d8066SMaciej S. Szmigiero 	hash_for_each(slots->id_hash, bkt, memslot, id_node[slots->node_idx]) \
1084a54d8066SMaciej S. Szmigiero 		if (WARN_ON_ONCE(!memslot->npages)) {			      \
1085a54d8066SMaciej S. Szmigiero 		} else
1086a54d8066SMaciej S. Szmigiero 
10870577d1abSSean Christopherson static inline
id_to_memslot(struct kvm_memslots * slots,int id)10880577d1abSSean Christopherson struct kvm_memory_slot *id_to_memslot(struct kvm_memslots *slots, int id)
108928a37544SXiao Guangrong {
1090f85e2cb5SXiao Guangrong 	struct kvm_memory_slot *slot;
1091a54d8066SMaciej S. Szmigiero 	int idx = slots->node_idx;
1092bf3e05bcSXiao Guangrong 
1093a54d8066SMaciej S. Szmigiero 	hash_for_each_possible(slots->id_hash, slot, id_node[idx], id) {
109426b8345aSMaciej S. Szmigiero 		if (slot->id == id)
1095f85e2cb5SXiao Guangrong 			return slot;
109628a37544SXiao Guangrong 	}
109728a37544SXiao Guangrong 
109826b8345aSMaciej S. Szmigiero 	return NULL;
109926b8345aSMaciej S. Szmigiero }
110026b8345aSMaciej S. Szmigiero 
1101f4209439SMaciej S. Szmigiero /* Iterator used for walking memslots that overlap a gfn range. */
1102f4209439SMaciej S. Szmigiero struct kvm_memslot_iter {
1103f4209439SMaciej S. Szmigiero 	struct kvm_memslots *slots;
1104f4209439SMaciej S. Szmigiero 	struct rb_node *node;
1105f4209439SMaciej S. Szmigiero 	struct kvm_memory_slot *slot;
1106f4209439SMaciej S. Szmigiero };
1107f4209439SMaciej S. Szmigiero 
kvm_memslot_iter_next(struct kvm_memslot_iter * iter)1108f4209439SMaciej S. Szmigiero static inline void kvm_memslot_iter_next(struct kvm_memslot_iter *iter)
1109f4209439SMaciej S. Szmigiero {
1110f4209439SMaciej S. Szmigiero 	iter->node = rb_next(iter->node);
1111f4209439SMaciej S. Szmigiero 	if (!iter->node)
1112f4209439SMaciej S. Szmigiero 		return;
1113f4209439SMaciej S. Szmigiero 
1114f4209439SMaciej S. Szmigiero 	iter->slot = container_of(iter->node, struct kvm_memory_slot, gfn_node[iter->slots->node_idx]);
1115f4209439SMaciej S. Szmigiero }
1116f4209439SMaciej S. Szmigiero 
kvm_memslot_iter_start(struct kvm_memslot_iter * iter,struct kvm_memslots * slots,gfn_t start)1117f4209439SMaciej S. Szmigiero static inline void kvm_memslot_iter_start(struct kvm_memslot_iter *iter,
1118f4209439SMaciej S. Szmigiero 					  struct kvm_memslots *slots,
1119f4209439SMaciej S. Szmigiero 					  gfn_t start)
1120f4209439SMaciej S. Szmigiero {
1121f4209439SMaciej S. Szmigiero 	int idx = slots->node_idx;
1122f4209439SMaciej S. Szmigiero 	struct rb_node *tmp;
1123f4209439SMaciej S. Szmigiero 	struct kvm_memory_slot *slot;
1124f4209439SMaciej S. Szmigiero 
1125f4209439SMaciej S. Szmigiero 	iter->slots = slots;
1126f4209439SMaciej S. Szmigiero 
1127f4209439SMaciej S. Szmigiero 	/*
1128f4209439SMaciej S. Szmigiero 	 * Find the so called "upper bound" of a key - the first node that has
1129f4209439SMaciej S. Szmigiero 	 * its key strictly greater than the searched one (the start gfn in our case).
1130f4209439SMaciej S. Szmigiero 	 */
1131f4209439SMaciej S. Szmigiero 	iter->node = NULL;
1132f4209439SMaciej S. Szmigiero 	for (tmp = slots->gfn_tree.rb_node; tmp; ) {
1133f4209439SMaciej S. Szmigiero 		slot = container_of(tmp, struct kvm_memory_slot, gfn_node[idx]);
1134f4209439SMaciej S. Szmigiero 		if (start < slot->base_gfn) {
1135f4209439SMaciej S. Szmigiero 			iter->node = tmp;
1136f4209439SMaciej S. Szmigiero 			tmp = tmp->rb_left;
1137f4209439SMaciej S. Szmigiero 		} else {
1138f4209439SMaciej S. Szmigiero 			tmp = tmp->rb_right;
1139f4209439SMaciej S. Szmigiero 		}
1140f4209439SMaciej S. Szmigiero 	}
1141f4209439SMaciej S. Szmigiero 
1142f4209439SMaciej S. Szmigiero 	/*
1143f4209439SMaciej S. Szmigiero 	 * Find the slot with the lowest gfn that can possibly intersect with
1144f4209439SMaciej S. Szmigiero 	 * the range, so we'll ideally have slot start <= range start
1145f4209439SMaciej S. Szmigiero 	 */
1146f4209439SMaciej S. Szmigiero 	if (iter->node) {
1147f4209439SMaciej S. Szmigiero 		/*
1148f4209439SMaciej S. Szmigiero 		 * A NULL previous node means that the very first slot
1149f4209439SMaciej S. Szmigiero 		 * already has a higher start gfn.
1150f4209439SMaciej S. Szmigiero 		 * In this case slot start > range start.
1151f4209439SMaciej S. Szmigiero 		 */
1152f4209439SMaciej S. Szmigiero 		tmp = rb_prev(iter->node);
1153f4209439SMaciej S. Szmigiero 		if (tmp)
1154f4209439SMaciej S. Szmigiero 			iter->node = tmp;
1155f4209439SMaciej S. Szmigiero 	} else {
1156f4209439SMaciej S. Szmigiero 		/* a NULL node below means no slots */
1157f4209439SMaciej S. Szmigiero 		iter->node = rb_last(&slots->gfn_tree);
1158f4209439SMaciej S. Szmigiero 	}
1159f4209439SMaciej S. Szmigiero 
1160f4209439SMaciej S. Szmigiero 	if (iter->node) {
1161f4209439SMaciej S. Szmigiero 		iter->slot = container_of(iter->node, struct kvm_memory_slot, gfn_node[idx]);
1162f4209439SMaciej S. Szmigiero 
1163f4209439SMaciej S. Szmigiero 		/*
1164f4209439SMaciej S. Szmigiero 		 * It is possible in the slot start < range start case that the
1165f4209439SMaciej S. Szmigiero 		 * found slot ends before or at range start (slot end <= range start)
1166f4209439SMaciej S. Szmigiero 		 * and so it does not overlap the requested range.
1167f4209439SMaciej S. Szmigiero 		 *
1168f4209439SMaciej S. Szmigiero 		 * In such non-overlapping case the next slot (if it exists) will
1169f4209439SMaciej S. Szmigiero 		 * already have slot start > range start, otherwise the logic above
1170f4209439SMaciej S. Szmigiero 		 * would have found it instead of the current slot.
1171f4209439SMaciej S. Szmigiero 		 */
1172f4209439SMaciej S. Szmigiero 		if (iter->slot->base_gfn + iter->slot->npages <= start)
1173f4209439SMaciej S. Szmigiero 			kvm_memslot_iter_next(iter);
1174f4209439SMaciej S. Szmigiero 	}
1175f4209439SMaciej S. Szmigiero }
1176f4209439SMaciej S. Szmigiero 
kvm_memslot_iter_is_valid(struct kvm_memslot_iter * iter,gfn_t end)1177f4209439SMaciej S. Szmigiero static inline bool kvm_memslot_iter_is_valid(struct kvm_memslot_iter *iter, gfn_t end)
1178f4209439SMaciej S. Szmigiero {
1179f4209439SMaciej S. Szmigiero 	if (!iter->node)
1180f4209439SMaciej S. Szmigiero 		return false;
1181f4209439SMaciej S. Szmigiero 
1182f4209439SMaciej S. Szmigiero 	/*
1183f4209439SMaciej S. Szmigiero 	 * If this slot starts beyond or at the end of the range so does
1184f4209439SMaciej S. Szmigiero 	 * every next one
1185f4209439SMaciej S. Szmigiero 	 */
1186f4209439SMaciej S. Szmigiero 	return iter->slot->base_gfn < end;
1187f4209439SMaciej S. Szmigiero }
1188f4209439SMaciej S. Szmigiero 
1189f4209439SMaciej S. Szmigiero /* Iterate over each memslot at least partially intersecting [start, end) range */
1190f4209439SMaciej S. Szmigiero #define kvm_for_each_memslot_in_gfn_range(iter, slots, start, end)	\
1191f4209439SMaciej S. Szmigiero 	for (kvm_memslot_iter_start(iter, slots, start);		\
1192f4209439SMaciej S. Szmigiero 	     kvm_memslot_iter_is_valid(iter, end);			\
1193f4209439SMaciej S. Szmigiero 	     kvm_memslot_iter_next(iter))
1194f4209439SMaciej S. Szmigiero 
119521dd8770SSean Christopherson struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn);
119621dd8770SSean Christopherson struct kvm_memslots *kvm_vcpu_memslots(struct kvm_vcpu *vcpu);
119721dd8770SSean Christopherson struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn);
119821dd8770SSean Christopherson 
119974d0727cSTakuya Yoshikawa /*
120074d0727cSTakuya Yoshikawa  * KVM_SET_USER_MEMORY_REGION ioctl allows the following operations:
120174d0727cSTakuya Yoshikawa  * - create a new memory slot
120274d0727cSTakuya Yoshikawa  * - delete an existing memory slot
120374d0727cSTakuya Yoshikawa  * - modify an existing memory slot
120474d0727cSTakuya Yoshikawa  *   -- move it in the guest physical memory space
120574d0727cSTakuya Yoshikawa  *   -- just change its flags
120674d0727cSTakuya Yoshikawa  *
120774d0727cSTakuya Yoshikawa  * Since flags can be changed by some of these operations, the following
1208344315e9SSean Christopherson  * differentiation is the best we can do for kvm_set_memory_region():
120974d0727cSTakuya Yoshikawa  */
121074d0727cSTakuya Yoshikawa enum kvm_mr_change {
121174d0727cSTakuya Yoshikawa 	KVM_MR_CREATE,
121274d0727cSTakuya Yoshikawa 	KVM_MR_DELETE,
121374d0727cSTakuya Yoshikawa 	KVM_MR_MOVE,
121474d0727cSTakuya Yoshikawa 	KVM_MR_FLAGS_ONLY,
121574d0727cSTakuya Yoshikawa };
121674d0727cSTakuya Yoshikawa 
1217156bffdbSSean Christopherson int kvm_set_internal_memslot(struct kvm *kvm,
1218bb58b90bSSean Christopherson 			     const struct kvm_userspace_memory_region2 *mem);
1219e96c81eeSSean Christopherson void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot);
122015248258SSean Christopherson void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen);
1221f7784b8eSMarcelo Tosatti int kvm_arch_prepare_memory_region(struct kvm *kvm,
1222537a17b3SSean Christopherson 				const struct kvm_memory_slot *old,
1223537a17b3SSean Christopherson 				struct kvm_memory_slot *new,
12247b6195a9STakuya Yoshikawa 				enum kvm_mr_change change);
1225f7784b8eSMarcelo Tosatti void kvm_arch_commit_memory_region(struct kvm *kvm,
12269d4c197cSSean Christopherson 				struct kvm_memory_slot *old,
1227f36f3f28SPaolo Bonzini 				const struct kvm_memory_slot *new,
12288482644aSTakuya Yoshikawa 				enum kvm_mr_change change);
12292df72e9bSMarcelo Tosatti /* flush all memory translations */
12302df72e9bSMarcelo Tosatti void kvm_arch_flush_shadow_all(struct kvm *kvm);
12312df72e9bSMarcelo Tosatti /* flush memory translations pointing to 'slot' */
12322df72e9bSMarcelo Tosatti void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
12332df72e9bSMarcelo Tosatti 				   struct kvm_memory_slot *slot);
1234a983fb23SMarcelo Tosatti 
12356419bc52SSean Christopherson int kvm_prefetch_pages(struct kvm_memory_slot *slot, gfn_t gfn,
1236d9ef13c2SPaolo Bonzini 		       struct page **pages, int nr_pages);
123748987781SXiao Guangrong 
1238f42e289aSSean Christopherson struct page *__gfn_to_page(struct kvm *kvm, gfn_t gfn, bool write);
gfn_to_page(struct kvm * kvm,gfn_t gfn)1239f42e289aSSean Christopherson static inline struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
1240f42e289aSSean Christopherson {
1241f42e289aSSean Christopherson 	return __gfn_to_page(kvm, gfn, true);
1242f42e289aSSean Christopherson }
1243f42e289aSSean Christopherson 
124405da4558SMarcelo Tosatti unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn);
1245ba6a3541SPaolo Bonzini unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable);
12464d8b81abSXiao Guangrong unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot, gfn_t gfn);
124764d83126SChristoffer Dall unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot, gfn_t gfn,
124864d83126SChristoffer Dall 				      bool *writable);
12493af91068SSean Christopherson 
kvm_release_page_unused(struct page * page)12503af91068SSean Christopherson static inline void kvm_release_page_unused(struct page *page)
12513af91068SSean Christopherson {
12523af91068SSean Christopherson 	if (!page)
12533af91068SSean Christopherson 		return;
12543af91068SSean Christopherson 
12553af91068SSean Christopherson 	put_page(page);
12563af91068SSean Christopherson }
12573af91068SSean Christopherson 
1258edf88417SAvi Kivity void kvm_release_page_clean(struct page *page);
1259edf88417SAvi Kivity void kvm_release_page_dirty(struct page *page);
126035149e21SAnthony Liguori 
kvm_release_faultin_page(struct kvm * kvm,struct page * page,bool unused,bool dirty)1261dc061935SSean Christopherson static inline void kvm_release_faultin_page(struct kvm *kvm, struct page *page,
1262dc061935SSean Christopherson 					    bool unused, bool dirty)
1263dc061935SSean Christopherson {
1264dc061935SSean Christopherson 	lockdep_assert_once(lockdep_is_held(&kvm->mmu_lock) || unused);
1265dc061935SSean Christopherson 
1266dc061935SSean Christopherson 	if (!page)
1267dc061935SSean Christopherson 		return;
1268dc061935SSean Christopherson 
1269dc061935SSean Christopherson 	/*
1270dc061935SSean Christopherson 	 * If the page that KVM got from the *primary MMU* is writable, and KVM
1271dc061935SSean Christopherson 	 * installed or reused a SPTE, mark the page/folio dirty.  Note, this
1272dc061935SSean Christopherson 	 * may mark a folio dirty even if KVM created a read-only SPTE, e.g. if
1273dc061935SSean Christopherson 	 * the GFN is write-protected.  Folios can't be safely marked dirty
1274dc061935SSean Christopherson 	 * outside of mmu_lock as doing so could race with writeback on the
1275dc061935SSean Christopherson 	 * folio.  As a result, KVM can't mark folios dirty in the fast page
1276dc061935SSean Christopherson 	 * fault handler, and so KVM must (somewhat) speculatively mark the
1277dc061935SSean Christopherson 	 * folio dirty if KVM could locklessly make the SPTE writable.
1278dc061935SSean Christopherson 	 */
1279dc061935SSean Christopherson 	if (unused)
1280dc061935SSean Christopherson 		kvm_release_page_unused(page);
1281dc061935SSean Christopherson 	else if (dirty)
1282dc061935SSean Christopherson 		kvm_release_page_dirty(page);
1283dc061935SSean Christopherson 	else
1284dc061935SSean Christopherson 		kvm_release_page_clean(page);
1285dc061935SSean Christopherson }
1286dc061935SSean Christopherson 
12871c7b627eSSean Christopherson kvm_pfn_t __kvm_faultin_pfn(const struct kvm_memory_slot *slot, gfn_t gfn,
12881c7b627eSSean Christopherson 			    unsigned int foll, bool *writable,
12891c7b627eSSean Christopherson 			    struct page **refcounted_page);
12901c7b627eSSean Christopherson 
kvm_faultin_pfn(struct kvm_vcpu * vcpu,gfn_t gfn,bool write,bool * writable,struct page ** refcounted_page)12911c7b627eSSean Christopherson static inline kvm_pfn_t kvm_faultin_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
12921c7b627eSSean Christopherson 					bool write, bool *writable,
12931c7b627eSSean Christopherson 					struct page **refcounted_page)
12941c7b627eSSean Christopherson {
12951c7b627eSSean Christopherson 	return __kvm_faultin_pfn(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn,
12961c7b627eSSean Christopherson 				 write ? FOLL_WRITE : 0, writable, refcounted_page);
12971c7b627eSSean Christopherson }
12981c7b627eSSean Christopherson 
1299edf88417SAvi Kivity int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
1300edf88417SAvi Kivity 			int len);
1301edf88417SAvi Kivity int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len);
13024e335d9eSPaolo Bonzini int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1303e03b644fSGleb Natapov 			   void *data, unsigned long len);
13040958f0ceSVitaly Kuznetsov int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
13050958f0ceSVitaly Kuznetsov 				 void *data, unsigned int offset,
13060958f0ceSVitaly Kuznetsov 				 unsigned long len);
1307edf88417SAvi Kivity int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, const void *data,
1308edf88417SAvi Kivity 			 int offset, int len);
1309edf88417SAvi Kivity int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
1310edf88417SAvi Kivity 		    unsigned long len);
13114e335d9eSPaolo Bonzini int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
131249c7754cSGleb Natapov 			   void *data, unsigned long len);
13134e335d9eSPaolo Bonzini int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
13147a86dab8SJim Mattson 				  void *data, unsigned int offset,
13157a86dab8SJim Mattson 				  unsigned long len);
13164e335d9eSPaolo Bonzini int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
13178f964525SAndrew Honig 			      gpa_t gpa, unsigned long len);
1318cac0f1b7SSteven Price 
131953f98558SAndrew Jones #define __kvm_get_guest(kvm, gfn, offset, v)				\
132053f98558SAndrew Jones ({									\
132153f98558SAndrew Jones 	unsigned long __addr = gfn_to_hva(kvm, gfn);			\
132253f98558SAndrew Jones 	typeof(v) __user *__uaddr = (typeof(__uaddr))(__addr + offset);	\
132353f98558SAndrew Jones 	int __ret = -EFAULT;						\
132453f98558SAndrew Jones 									\
132553f98558SAndrew Jones 	if (!kvm_is_error_hva(__addr))					\
132653f98558SAndrew Jones 		__ret = get_user(v, __uaddr);				\
132753f98558SAndrew Jones 	__ret;								\
132853f98558SAndrew Jones })
132953f98558SAndrew Jones 
133053f98558SAndrew Jones #define kvm_get_guest(kvm, gpa, v)					\
133153f98558SAndrew Jones ({									\
133253f98558SAndrew Jones 	gpa_t __gpa = gpa;						\
133353f98558SAndrew Jones 	struct kvm *__kvm = kvm;					\
133453f98558SAndrew Jones 									\
133553f98558SAndrew Jones 	__kvm_get_guest(__kvm, __gpa >> PAGE_SHIFT,			\
133653f98558SAndrew Jones 			offset_in_page(__gpa), v);			\
133753f98558SAndrew Jones })
133853f98558SAndrew Jones 
13394d2d4ce0SAndrew Jones #define __kvm_put_guest(kvm, gfn, offset, v)				\
1340cac0f1b7SSteven Price ({									\
1341cac0f1b7SSteven Price 	unsigned long __addr = gfn_to_hva(kvm, gfn);			\
13424d2d4ce0SAndrew Jones 	typeof(v) __user *__uaddr = (typeof(__uaddr))(__addr + offset);	\
1343cac0f1b7SSteven Price 	int __ret = -EFAULT;						\
1344cac0f1b7SSteven Price 									\
1345cac0f1b7SSteven Price 	if (!kvm_is_error_hva(__addr))					\
13464d2d4ce0SAndrew Jones 		__ret = put_user(v, __uaddr);				\
1347cac0f1b7SSteven Price 	if (!__ret)							\
1348cac0f1b7SSteven Price 		mark_page_dirty(kvm, gfn);				\
1349cac0f1b7SSteven Price 	__ret;								\
1350cac0f1b7SSteven Price })
1351cac0f1b7SSteven Price 
13524d2d4ce0SAndrew Jones #define kvm_put_guest(kvm, gpa, v)					\
1353cac0f1b7SSteven Price ({									\
1354cac0f1b7SSteven Price 	gpa_t __gpa = gpa;						\
1355cac0f1b7SSteven Price 	struct kvm *__kvm = kvm;					\
13564d2d4ce0SAndrew Jones 									\
1357cac0f1b7SSteven Price 	__kvm_put_guest(__kvm, __gpa >> PAGE_SHIFT,			\
13584d2d4ce0SAndrew Jones 			offset_in_page(__gpa), v);			\
1359cac0f1b7SSteven Price })
1360cac0f1b7SSteven Price 
1361edf88417SAvi Kivity int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len);
136233e94154SYaowei Bai bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn);
1363995decb6SVitaly Kuznetsov bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn);
1364f9b84e19SSean Christopherson unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn);
13658283e36aSBen Gardon void mark_page_dirty_in_slot(struct kvm *kvm, const struct kvm_memory_slot *memslot, gfn_t gfn);
1366edf88417SAvi Kivity void mark_page_dirty(struct kvm *kvm, gfn_t gfn);
1367edf88417SAvi Kivity 
1368365e3192SSean Christopherson int __kvm_vcpu_map(struct kvm_vcpu *vcpu, gpa_t gpa, struct kvm_host_map *map,
1369365e3192SSean Christopherson 		   bool writable);
1370365e3192SSean Christopherson void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map);
1371365e3192SSean Christopherson 
kvm_vcpu_map(struct kvm_vcpu * vcpu,gpa_t gpa,struct kvm_host_map * map)1372365e3192SSean Christopherson static inline int kvm_vcpu_map(struct kvm_vcpu *vcpu, gpa_t gpa,
1373365e3192SSean Christopherson 			       struct kvm_host_map *map)
1374365e3192SSean Christopherson {
1375365e3192SSean Christopherson 	return __kvm_vcpu_map(vcpu, gpa, map, true);
1376365e3192SSean Christopherson }
1377365e3192SSean Christopherson 
kvm_vcpu_map_readonly(struct kvm_vcpu * vcpu,gpa_t gpa,struct kvm_host_map * map)1378365e3192SSean Christopherson static inline int kvm_vcpu_map_readonly(struct kvm_vcpu *vcpu, gpa_t gpa,
1379365e3192SSean Christopherson 					struct kvm_host_map *map)
1380365e3192SSean Christopherson {
1381365e3192SSean Christopherson 	return __kvm_vcpu_map(vcpu, gpa, map, false);
1382365e3192SSean Christopherson }
1383365e3192SSean Christopherson 
13848e73485cSPaolo Bonzini unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn);
13858e73485cSPaolo Bonzini unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable);
13868e73485cSPaolo Bonzini int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data, int offset,
13878e73485cSPaolo Bonzini 			     int len);
13888e73485cSPaolo Bonzini int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa, void *data,
13898e73485cSPaolo Bonzini 			       unsigned long len);
13908e73485cSPaolo Bonzini int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data,
13918e73485cSPaolo Bonzini 			unsigned long len);
13928e73485cSPaolo Bonzini int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, const void *data,
13938e73485cSPaolo Bonzini 			      int offset, int len);
13948e73485cSPaolo Bonzini int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
13958e73485cSPaolo Bonzini 			 unsigned long len);
13968e73485cSPaolo Bonzini void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn);
13978e73485cSPaolo Bonzini 
1398982ed0deSDavid Woodhouse /**
139952491a38SMichal Luczaj  * kvm_gpc_init - initialize gfn_to_pfn_cache.
140052491a38SMichal Luczaj  *
140152491a38SMichal Luczaj  * @gpc:	   struct gfn_to_pfn_cache object.
1402982ed0deSDavid Woodhouse  * @kvm:	   pointer to kvm instance.
14038c82a0b3SMichal Luczaj  *
14048c82a0b3SMichal Luczaj  * This sets up a gfn_to_pfn_cache by initializing locks and assigning the
14058c82a0b3SMichal Luczaj  * immutable attributes.  Note, the cache must be zero-allocated (or zeroed by
14068c82a0b3SMichal Luczaj  * the caller before init).
14078c82a0b3SMichal Luczaj  */
1408a4bff3dfSPaul Durrant void kvm_gpc_init(struct gfn_to_pfn_cache *gpc, struct kvm *kvm);
14098c82a0b3SMichal Luczaj 
14108c82a0b3SMichal Luczaj /**
14118c82a0b3SMichal Luczaj  * kvm_gpc_activate - prepare a cached kernel mapping and HPA for a given guest
14128c82a0b3SMichal Luczaj  *                    physical address.
14138c82a0b3SMichal Luczaj  *
14148c82a0b3SMichal Luczaj  * @gpc:	   struct gfn_to_pfn_cache object.
1415982ed0deSDavid Woodhouse  * @gpa:	   guest physical address to map.
1416982ed0deSDavid Woodhouse  * @len:	   sanity check; the range being access must fit a single page.
1417982ed0deSDavid Woodhouse  *
1418982ed0deSDavid Woodhouse  * @return:	   0 for success.
1419982ed0deSDavid Woodhouse  *		   -EINVAL for a mapping which would cross a page boundary.
1420982ed0deSDavid Woodhouse  *		   -EFAULT for an untranslatable guest physical address.
1421982ed0deSDavid Woodhouse  *
14228c82a0b3SMichal Luczaj  * This primes a gfn_to_pfn_cache and links it into the @gpc->kvm's list for
1423aba3caefSMichal Luczaj  * invalidations to be processed.  Callers are required to use kvm_gpc_check()
1424aba3caefSMichal Luczaj  * to ensure that the cache is valid before accessing the target page.
1425982ed0deSDavid Woodhouse  */
14268c82a0b3SMichal Luczaj int kvm_gpc_activate(struct gfn_to_pfn_cache *gpc, gpa_t gpa, unsigned long len);
1427982ed0deSDavid Woodhouse 
1428982ed0deSDavid Woodhouse /**
1429721f5b0dSPaul Durrant  * kvm_gpc_activate_hva - prepare a cached kernel mapping and HPA for a given HVA.
1430721f5b0dSPaul Durrant  *
1431721f5b0dSPaul Durrant  * @gpc:          struct gfn_to_pfn_cache object.
1432721f5b0dSPaul Durrant  * @hva:          userspace virtual address to map.
1433721f5b0dSPaul Durrant  * @len:          sanity check; the range being access must fit a single page.
1434721f5b0dSPaul Durrant  *
1435721f5b0dSPaul Durrant  * @return:       0 for success.
1436721f5b0dSPaul Durrant  *                -EINVAL for a mapping which would cross a page boundary.
1437721f5b0dSPaul Durrant  *                -EFAULT for an untranslatable guest physical address.
1438721f5b0dSPaul Durrant  *
1439721f5b0dSPaul Durrant  * The semantics of this function are the same as those of kvm_gpc_activate(). It
1440721f5b0dSPaul Durrant  * merely bypasses a layer of address translation.
1441721f5b0dSPaul Durrant  */
1442721f5b0dSPaul Durrant int kvm_gpc_activate_hva(struct gfn_to_pfn_cache *gpc, unsigned long hva, unsigned long len);
1443721f5b0dSPaul Durrant 
1444721f5b0dSPaul Durrant /**
1445aba3caefSMichal Luczaj  * kvm_gpc_check - check validity of a gfn_to_pfn_cache.
1446982ed0deSDavid Woodhouse  *
1447982ed0deSDavid Woodhouse  * @gpc:	   struct gfn_to_pfn_cache object.
1448982ed0deSDavid Woodhouse  * @len:	   sanity check; the range being access must fit a single page.
1449982ed0deSDavid Woodhouse  *
1450982ed0deSDavid Woodhouse  * @return:	   %true if the cache is still valid and the address matches.
1451982ed0deSDavid Woodhouse  *		   %false if the cache is not valid.
1452982ed0deSDavid Woodhouse  *
1453982ed0deSDavid Woodhouse  * Callers outside IN_GUEST_MODE context should hold a read lock on @gpc->lock
1454982ed0deSDavid Woodhouse  * while calling this function, and then continue to hold the lock until the
1455982ed0deSDavid Woodhouse  * access is complete.
1456982ed0deSDavid Woodhouse  *
1457982ed0deSDavid Woodhouse  * Callers in IN_GUEST_MODE may do so without locking, although they should
1458982ed0deSDavid Woodhouse  * still hold a read lock on kvm->scru for the memslot checks.
1459982ed0deSDavid Woodhouse  */
146058f5ee5fSSean Christopherson bool kvm_gpc_check(struct gfn_to_pfn_cache *gpc, unsigned long len);
1461982ed0deSDavid Woodhouse 
1462982ed0deSDavid Woodhouse /**
1463aba3caefSMichal Luczaj  * kvm_gpc_refresh - update a previously initialized cache.
1464982ed0deSDavid Woodhouse  *
1465982ed0deSDavid Woodhouse  * @gpc:	   struct gfn_to_pfn_cache object.
1466982ed0deSDavid Woodhouse  * @len:	   sanity check; the range being access must fit a single page.
1467982ed0deSDavid Woodhouse  *
1468982ed0deSDavid Woodhouse  * @return:	   0 for success.
1469982ed0deSDavid Woodhouse  *		   -EINVAL for a mapping which would cross a page boundary.
1470982ed0deSDavid Woodhouse  *		   -EFAULT for an untranslatable guest physical address.
1471982ed0deSDavid Woodhouse  *
1472982ed0deSDavid Woodhouse  * This will attempt to refresh a gfn_to_pfn_cache. Note that a successful
14730318f207SMichal Luczaj  * return from this function does not mean the page can be immediately
1474982ed0deSDavid Woodhouse  * accessed because it may have raced with an invalidation. Callers must
1475982ed0deSDavid Woodhouse  * still lock and check the cache status, as this function does not return
1476982ed0deSDavid Woodhouse  * with the lock still held to permit access.
1477982ed0deSDavid Woodhouse  */
147858f5ee5fSSean Christopherson int kvm_gpc_refresh(struct gfn_to_pfn_cache *gpc, unsigned long len);
1479982ed0deSDavid Woodhouse 
1480982ed0deSDavid Woodhouse /**
148152491a38SMichal Luczaj  * kvm_gpc_deactivate - deactivate and unlink a gfn_to_pfn_cache.
1482982ed0deSDavid Woodhouse  *
1483982ed0deSDavid Woodhouse  * @gpc:	   struct gfn_to_pfn_cache object.
1484982ed0deSDavid Woodhouse  *
14858c82a0b3SMichal Luczaj  * This removes a cache from the VM's list to be processed on MMU notifier
1486982ed0deSDavid Woodhouse  * invocation.
1487982ed0deSDavid Woodhouse  */
14888c82a0b3SMichal Luczaj void kvm_gpc_deactivate(struct gfn_to_pfn_cache *gpc);
1489982ed0deSDavid Woodhouse 
kvm_gpc_is_gpa_active(struct gfn_to_pfn_cache * gpc)1490721f5b0dSPaul Durrant static inline bool kvm_gpc_is_gpa_active(struct gfn_to_pfn_cache *gpc)
1491721f5b0dSPaul Durrant {
1492721f5b0dSPaul Durrant 	return gpc->active && !kvm_is_error_gpa(gpc->gpa);
1493721f5b0dSPaul Durrant }
1494721f5b0dSPaul Durrant 
kvm_gpc_is_hva_active(struct gfn_to_pfn_cache * gpc)1495721f5b0dSPaul Durrant static inline bool kvm_gpc_is_hva_active(struct gfn_to_pfn_cache *gpc)
1496721f5b0dSPaul Durrant {
1497721f5b0dSPaul Durrant 	return gpc->active && kvm_is_error_gpa(gpc->gpa);
1498721f5b0dSPaul Durrant }
1499721f5b0dSPaul Durrant 
150020b7035cSJan H. Schönherr void kvm_sigset_activate(struct kvm_vcpu *vcpu);
150120b7035cSJan H. Schönherr void kvm_sigset_deactivate(struct kvm_vcpu *vcpu);
150220b7035cSJan H. Schönherr 
150391b99ea7SSean Christopherson void kvm_vcpu_halt(struct kvm_vcpu *vcpu);
1504fac42688SSean Christopherson bool kvm_vcpu_block(struct kvm_vcpu *vcpu);
15053217f7c2SChristoffer Dall void kvm_arch_vcpu_blocking(struct kvm_vcpu *vcpu);
15063217f7c2SChristoffer Dall void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu);
1507178f02ffSRadim Krčmář bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu);
1508b6d33834SChristoffer Dall void kvm_vcpu_kick(struct kvm_vcpu *vcpu);
1509fa93384fSDan Carpenter int kvm_vcpu_yield_to(struct kvm_vcpu *target);
1510b9926482SWang Liang void kvm_vcpu_on_spin(struct kvm_vcpu *vcpu, bool yield_to_kernel_mode);
1511a4ee1ca4SXiao Guangrong 
1512edf88417SAvi Kivity void kvm_flush_remote_tlbs(struct kvm *kvm);
1513d4788996SDavid Matlack void kvm_flush_remote_tlbs_range(struct kvm *kvm, gfn_t gfn, u64 nr_pages);
1514619b5072SDavid Matlack void kvm_flush_remote_tlbs_memslot(struct kvm *kvm,
1515619b5072SDavid Matlack 				   const struct kvm_memory_slot *memslot);
15167053df4eSVitaly Kuznetsov 
15176926f95aSSean Christopherson #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
15186926f95aSSean Christopherson int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min);
1519837f66c7SDavid Matlack int __kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int capacity, int min);
15206926f95aSSean Christopherson int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc);
15216926f95aSSean Christopherson void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc);
15226926f95aSSean Christopherson void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc);
15236926f95aSSean Christopherson #endif
15246926f95aSSean Christopherson 
15258569992dSChao Peng void kvm_mmu_invalidate_begin(struct kvm *kvm);
15268569992dSChao Peng void kvm_mmu_invalidate_range_add(struct kvm *kvm, gfn_t start, gfn_t end);
15278569992dSChao Peng void kvm_mmu_invalidate_end(struct kvm *kvm);
1528a7800aa8SSean Christopherson bool kvm_mmu_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range);
1529edb298c6SMaxim Levitsky 
1530edf88417SAvi Kivity long kvm_arch_dev_ioctl(struct file *filp,
1531edf88417SAvi Kivity 			unsigned int ioctl, unsigned long arg);
1532edf88417SAvi Kivity long kvm_arch_vcpu_ioctl(struct file *filp,
1533edf88417SAvi Kivity 			 unsigned int ioctl, unsigned long arg);
15341499fa80SSouptick Joarder vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf);
1535edf88417SAvi Kivity 
1536784aa3d7SAlexander Graf int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext);
1537edf88417SAvi Kivity 
15383b0f1d01SKai Huang void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1539ba0513b5SMario Smarduch 					struct kvm_memory_slot *slot,
1540ba0513b5SMario Smarduch 					gfn_t gfn_offset,
1541ba0513b5SMario Smarduch 					unsigned long mask);
15420dff0846SSean Christopherson void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot);
1543ba0513b5SMario Smarduch 
1544619b5072SDavid Matlack #ifndef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
15450dff0846SSean Christopherson int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log);
15460dff0846SSean Christopherson int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
15472a49f61dSSean Christopherson 		      int *is_dirty, struct kvm_memory_slot **memslot);
15480dff0846SSean Christopherson #endif
1549edf88417SAvi Kivity 
1550aa2fbe6dSYang Zhang int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_level,
1551aa2fbe6dSYang Zhang 			bool line_status);
1552e5d83c74SPaolo Bonzini int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
1553e5d83c74SPaolo Bonzini 			    struct kvm_enable_cap *cap);
1554d8708b80SThomas Huth int kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg);
1555ed51862fSAlexander Graf long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
1556ed51862fSAlexander Graf 			      unsigned long arg);
1557edf88417SAvi Kivity 
1558edf88417SAvi Kivity int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu);
1559edf88417SAvi Kivity int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu);
1560edf88417SAvi Kivity 
1561edf88417SAvi Kivity int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
1562edf88417SAvi Kivity 				    struct kvm_translation *tr);
1563edf88417SAvi Kivity 
1564edf88417SAvi Kivity int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs);
1565edf88417SAvi Kivity int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs);
1566edf88417SAvi Kivity int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
1567edf88417SAvi Kivity 				  struct kvm_sregs *sregs);
1568edf88417SAvi Kivity int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
1569edf88417SAvi Kivity 				  struct kvm_sregs *sregs);
157062d9f0dbSMarcelo Tosatti int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
157162d9f0dbSMarcelo Tosatti 				    struct kvm_mp_state *mp_state);
157262d9f0dbSMarcelo Tosatti int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
157362d9f0dbSMarcelo Tosatti 				    struct kvm_mp_state *mp_state);
1574d0bfb940SJan Kiszka int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
1575d0bfb940SJan Kiszka 					struct kvm_guest_debug *dbg);
15761b94f6f8STianjia Zhang int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu);
1577edf88417SAvi Kivity 
1578edf88417SAvi Kivity void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu);
1579edf88417SAvi Kivity void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu);
1580897cc38eSSean Christopherson int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id);
1581e529ef66SSean Christopherson int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu);
158231928aa5SDominik Dingel void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu);
1583edf88417SAvi Kivity void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu);
1584edf88417SAvi Kivity 
15852fdef3a2SSergey Senozhatsky #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
15862fdef3a2SSergey Senozhatsky int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state);
15872fdef3a2SSergey Senozhatsky #endif
15882fdef3a2SSergey Senozhatsky 
1589741cbbaeSPaolo Bonzini #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
1590d56f5136SPaolo Bonzini void kvm_arch_create_vcpu_debugfs(struct kvm_vcpu *vcpu, struct dentry *debugfs_dentry);
1591e36de87dSVineeth Pillai #else
kvm_create_vcpu_debugfs(struct kvm_vcpu * vcpu)1592e36de87dSVineeth Pillai static inline void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu) {}
1593741cbbaeSPaolo Bonzini #endif
1594235539b4SLuiz Capitulino 
1595441f7bfaSSean Christopherson #ifdef CONFIG_KVM_GENERIC_HARDWARE_ENABLING
1596b67107a2SSean Christopherson /*
1597b67107a2SSean Christopherson  * kvm_arch_{enable,disable}_virtualization() are called on one CPU, under
1598b67107a2SSean Christopherson  * kvm_usage_lock, immediately after/before 0=>1 and 1=>0 transitions of
1599b67107a2SSean Christopherson  * kvm_usage_count, i.e. at the beginning of the generic hardware enabling
1600b67107a2SSean Christopherson  * sequence, and at the end of the generic hardware disabling sequence.
1601b67107a2SSean Christopherson  */
1602b67107a2SSean Christopherson void kvm_arch_enable_virtualization(void);
1603b67107a2SSean Christopherson void kvm_arch_disable_virtualization(void);
1604b67107a2SSean Christopherson /*
1605b67107a2SSean Christopherson  * kvm_arch_{enable,disable}_virtualization_cpu() are called on "every" CPU to
1606b67107a2SSean Christopherson  * do the actual twiddling of hardware bits.  The hooks are called on all
1607b67107a2SSean Christopherson  * online CPUs when KVM enables/disabled virtualization, and on a single CPU
1608b67107a2SSean Christopherson  * when that CPU is onlined/offlined (including for Resume/Suspend).
1609b67107a2SSean Christopherson  */
1610071f24adSSean Christopherson int kvm_arch_enable_virtualization_cpu(void);
1611071f24adSSean Christopherson void kvm_arch_disable_virtualization_cpu(void);
1612441f7bfaSSean Christopherson #endif
1613edf88417SAvi Kivity int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu);
1614199b5763SLongpeng(Mike) bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu);
1615b6d33834SChristoffer Dall int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu);
161617e433b5SWanpeng Li bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu);
161752acd22fSWanpeng Li bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu);
161877bcd9e6SSean Christopherson bool kvm_arch_vcpu_preempted_in_kernel(struct kvm_vcpu *vcpu);
1619d970a325SPaolo Bonzini void kvm_arch_pre_destroy_vm(struct kvm *kvm);
1620284851eeSOliver Upton void kvm_arch_create_vm_debugfs(struct kvm *kvm);
1621edf88417SAvi Kivity 
1622d89f5effSJan Kiszka #ifndef __KVM_HAVE_ARCH_VM_ALLOC
1623d1e5b0e9SMarc Orr /*
1624d1e5b0e9SMarc Orr  * All architectures that want to use vzalloc currently also
1625d1e5b0e9SMarc Orr  * need their own kvm_arch_alloc_vm implementation.
1626d1e5b0e9SMarc Orr  */
kvm_arch_alloc_vm(void)1627d89f5effSJan Kiszka static inline struct kvm *kvm_arch_alloc_vm(void)
1628d89f5effSJan Kiszka {
1629b1cd1633SAlexey Dobriyan 	return kzalloc(sizeof(struct kvm), GFP_KERNEL_ACCOUNT);
1630d89f5effSJan Kiszka }
163178b497f2SJuergen Gross #endif
1632d89f5effSJan Kiszka 
__kvm_arch_free_vm(struct kvm * kvm)163378b497f2SJuergen Gross static inline void __kvm_arch_free_vm(struct kvm *kvm)
163478b497f2SJuergen Gross {
163578b497f2SJuergen Gross 	kvfree(kvm);
163678b497f2SJuergen Gross }
163778b497f2SJuergen Gross 
163878b497f2SJuergen Gross #ifndef __KVM_HAVE_ARCH_VM_FREE
kvm_arch_free_vm(struct kvm * kvm)1639d89f5effSJan Kiszka static inline void kvm_arch_free_vm(struct kvm *kvm)
1640d89f5effSJan Kiszka {
164178b497f2SJuergen Gross 	__kvm_arch_free_vm(kvm);
1642d89f5effSJan Kiszka }
1643d89f5effSJan Kiszka #endif
1644d89f5effSJan Kiszka 
1645a1342c80SDavid Matlack #ifndef __KVM_HAVE_ARCH_FLUSH_REMOTE_TLBS
kvm_arch_flush_remote_tlbs(struct kvm * kvm)1646a1342c80SDavid Matlack static inline int kvm_arch_flush_remote_tlbs(struct kvm *kvm)
1647b08660e5STianyu Lan {
1648b08660e5STianyu Lan 	return -ENOTSUPP;
1649b08660e5STianyu Lan }
1650cfb0c08eSRaghavendra Rao Ananta #else
1651cfb0c08eSRaghavendra Rao Ananta int kvm_arch_flush_remote_tlbs(struct kvm *kvm);
1652b08660e5STianyu Lan #endif
1653b08660e5STianyu Lan 
1654d4788996SDavid Matlack #ifndef __KVM_HAVE_ARCH_FLUSH_REMOTE_TLBS_RANGE
kvm_arch_flush_remote_tlbs_range(struct kvm * kvm,gfn_t gfn,u64 nr_pages)1655d4788996SDavid Matlack static inline int kvm_arch_flush_remote_tlbs_range(struct kvm *kvm,
1656d4788996SDavid Matlack 						    gfn_t gfn, u64 nr_pages)
1657d4788996SDavid Matlack {
1658d4788996SDavid Matlack 	return -EOPNOTSUPP;
1659d4788996SDavid Matlack }
1660d4788996SDavid Matlack #else
1661d4788996SDavid Matlack int kvm_arch_flush_remote_tlbs_range(struct kvm *kvm, gfn_t gfn, u64 nr_pages);
1662d4788996SDavid Matlack #endif
1663d4788996SDavid Matlack 
1664e0f0bbc5SAlex Williamson #ifdef __KVM_HAVE_ARCH_NONCOHERENT_DMA
1665e0f0bbc5SAlex Williamson void kvm_arch_register_noncoherent_dma(struct kvm *kvm);
1666e0f0bbc5SAlex Williamson void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm);
1667e0f0bbc5SAlex Williamson bool kvm_arch_has_noncoherent_dma(struct kvm *kvm);
1668e0f0bbc5SAlex Williamson #else
kvm_arch_register_noncoherent_dma(struct kvm * kvm)1669e0f0bbc5SAlex Williamson static inline void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
1670e0f0bbc5SAlex Williamson {
1671e0f0bbc5SAlex Williamson }
1672e0f0bbc5SAlex Williamson 
kvm_arch_unregister_noncoherent_dma(struct kvm * kvm)1673e0f0bbc5SAlex Williamson static inline void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
1674e0f0bbc5SAlex Williamson {
1675e0f0bbc5SAlex Williamson }
1676e0f0bbc5SAlex Williamson 
kvm_arch_has_noncoherent_dma(struct kvm * kvm)1677e0f0bbc5SAlex Williamson static inline bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
1678e0f0bbc5SAlex Williamson {
1679e0f0bbc5SAlex Williamson 	return false;
1680e0f0bbc5SAlex Williamson }
1681e0f0bbc5SAlex Williamson #endif
16825544eb9bSPaolo Bonzini #ifdef __KVM_HAVE_ARCH_ASSIGNED_DEVICE
16835544eb9bSPaolo Bonzini void kvm_arch_start_assignment(struct kvm *kvm);
16845544eb9bSPaolo Bonzini void kvm_arch_end_assignment(struct kvm *kvm);
16855544eb9bSPaolo Bonzini bool kvm_arch_has_assigned_device(struct kvm *kvm);
16865544eb9bSPaolo Bonzini #else
kvm_arch_start_assignment(struct kvm * kvm)16875544eb9bSPaolo Bonzini static inline void kvm_arch_start_assignment(struct kvm *kvm)
16885544eb9bSPaolo Bonzini {
16895544eb9bSPaolo Bonzini }
16905544eb9bSPaolo Bonzini 
kvm_arch_end_assignment(struct kvm * kvm)16915544eb9bSPaolo Bonzini static inline void kvm_arch_end_assignment(struct kvm *kvm)
16925544eb9bSPaolo Bonzini {
16935544eb9bSPaolo Bonzini }
16945544eb9bSPaolo Bonzini 
kvm_arch_has_assigned_device(struct kvm * kvm)1695742ab6dfSPeter Zijlstra static __always_inline bool kvm_arch_has_assigned_device(struct kvm *kvm)
16965544eb9bSPaolo Bonzini {
16975544eb9bSPaolo Bonzini 	return false;
16985544eb9bSPaolo Bonzini }
16995544eb9bSPaolo Bonzini #endif
1700e0f0bbc5SAlex Williamson 
kvm_arch_vcpu_get_wait(struct kvm_vcpu * vcpu)1701da4ad88cSDavidlohr Bueso static inline struct rcuwait *kvm_arch_vcpu_get_wait(struct kvm_vcpu *vcpu)
1702b6d33834SChristoffer Dall {
17032246f8b5SAlexander Graf #ifdef __KVM_HAVE_ARCH_WQP
1704da4ad88cSDavidlohr Bueso 	return vcpu->arch.waitp;
17052246f8b5SAlexander Graf #else
1706da4ad88cSDavidlohr Bueso 	return &vcpu->wait;
1707b6d33834SChristoffer Dall #endif
17082246f8b5SAlexander Graf }
1709b6d33834SChristoffer Dall 
1710d92a5d1cSSean Christopherson /*
1711d92a5d1cSSean Christopherson  * Wake a vCPU if necessary, but don't do any stats/metadata updates.  Returns
1712d92a5d1cSSean Christopherson  * true if the vCPU was blocking and was awakened, false otherwise.
1713d92a5d1cSSean Christopherson  */
__kvm_vcpu_wake_up(struct kvm_vcpu * vcpu)1714d92a5d1cSSean Christopherson static inline bool __kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
1715d92a5d1cSSean Christopherson {
1716d92a5d1cSSean Christopherson 	return !!rcuwait_wake_up(kvm_arch_vcpu_get_wait(vcpu));
1717d92a5d1cSSean Christopherson }
1718d92a5d1cSSean Christopherson 
kvm_vcpu_is_blocking(struct kvm_vcpu * vcpu)1719d92a5d1cSSean Christopherson static inline bool kvm_vcpu_is_blocking(struct kvm_vcpu *vcpu)
1720d92a5d1cSSean Christopherson {
1721d92a5d1cSSean Christopherson 	return rcuwait_active(kvm_arch_vcpu_get_wait(vcpu));
1722d92a5d1cSSean Christopherson }
1723d92a5d1cSSean Christopherson 
172401c94e64SEric Auger #ifdef __KVM_HAVE_ARCH_INTC_INITIALIZED
172501c94e64SEric Auger /*
172601c94e64SEric Auger  * returns true if the virtual interrupt controller is initialized and
172701c94e64SEric Auger  * ready to accept virtual IRQ. On some architectures the virtual interrupt
172801c94e64SEric Auger  * controller is dynamically instantiated and this is not always true.
172901c94e64SEric Auger  */
173001c94e64SEric Auger bool kvm_arch_intc_initialized(struct kvm *kvm);
173101c94e64SEric Auger #else
kvm_arch_intc_initialized(struct kvm * kvm)173201c94e64SEric Auger static inline bool kvm_arch_intc_initialized(struct kvm *kvm)
173301c94e64SEric Auger {
173401c94e64SEric Auger 	return true;
173501c94e64SEric Auger }
173601c94e64SEric Auger #endif
173701c94e64SEric Auger 
1738e1bfc245SSean Christopherson #ifdef CONFIG_GUEST_PERF_EVENTS
1739e1bfc245SSean Christopherson unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu);
1740e1bfc245SSean Christopherson 
1741e1bfc245SSean Christopherson void kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void));
1742e1bfc245SSean Christopherson void kvm_unregister_perf_callbacks(void);
1743e1bfc245SSean Christopherson #else
kvm_register_perf_callbacks(void * ign)1744e1bfc245SSean Christopherson static inline void kvm_register_perf_callbacks(void *ign) {}
kvm_unregister_perf_callbacks(void)1745e1bfc245SSean Christopherson static inline void kvm_unregister_perf_callbacks(void) {}
1746e1bfc245SSean Christopherson #endif /* CONFIG_GUEST_PERF_EVENTS */
1747e1bfc245SSean Christopherson 
1748e08b9637SCarsten Otte int kvm_arch_init_vm(struct kvm *kvm, unsigned long type);
1749edf88417SAvi Kivity void kvm_arch_destroy_vm(struct kvm *kvm);
1750edf88417SAvi Kivity 
17513d80840dSMarcelo Tosatti int kvm_cpu_has_pending_timer(struct kvm_vcpu *vcpu);
1752edf88417SAvi Kivity 
175362c476c7SBen-Ami Yassour struct kvm_irq_ack_notifier {
175462c476c7SBen-Ami Yassour 	struct hlist_node link;
175562c476c7SBen-Ami Yassour 	unsigned gsi;
175662c476c7SBen-Ami Yassour 	void (*irq_acked)(struct kvm_irq_ack_notifier *kian);
175762c476c7SBen-Ami Yassour };
175862c476c7SBen-Ami Yassour 
17599957c86dSPaul Mackerras int kvm_irq_map_gsi(struct kvm *kvm,
17609957c86dSPaul Mackerras 		    struct kvm_kernel_irq_routing_entry *entries, int gsi);
17619957c86dSPaul Mackerras int kvm_irq_map_chip_pin(struct kvm *kvm, unsigned irqchip, unsigned pin);
17628ba918d4SPaul Mackerras 
1763aa2fbe6dSYang Zhang int kvm_set_irq(struct kvm *kvm, int irq_source_id, u32 irq, int level,
1764aa2fbe6dSYang Zhang 		bool line_status);
1765bd2b53b2SMichael S. Tsirkin int kvm_set_msi(struct kvm_kernel_irq_routing_entry *irq_entry, struct kvm *kvm,
1766aa2fbe6dSYang Zhang 		int irq_source_id, int level, bool line_status);
1767b97e6de9SPaolo Bonzini int kvm_arch_set_irq_inatomic(struct kvm_kernel_irq_routing_entry *e,
1768b97e6de9SPaolo Bonzini 			       struct kvm *kvm, int irq_source_id,
1769b97e6de9SPaolo Bonzini 			       int level, bool line_status);
1770c7c9c56cSYang Zhang bool kvm_irq_has_notifier(struct kvm *kvm, unsigned irqchip, unsigned pin);
1771ba1aefcdSAndrey Smetanin void kvm_notify_acked_gsi(struct kvm *kvm, int gsi);
177244882eedSMarcelo Tosatti void kvm_notify_acked_irq(struct kvm *kvm, unsigned irqchip, unsigned pin);
17733de42dc0SXiantao Zhang void kvm_register_irq_ack_notifier(struct kvm *kvm,
17743de42dc0SXiantao Zhang 				   struct kvm_irq_ack_notifier *kian);
1775fa40a821SMarcelo Tosatti void kvm_unregister_irq_ack_notifier(struct kvm *kvm,
1776fa40a821SMarcelo Tosatti 				   struct kvm_irq_ack_notifier *kian);
17775550af4dSSheng Yang int kvm_request_irq_source_id(struct kvm *kvm);
17785550af4dSSheng Yang void kvm_free_irq_source_id(struct kvm *kvm, int irq_source_id);
1779cdc238ebSYi Wang bool kvm_arch_irqfd_allowed(struct kvm *kvm, struct kvm_irqfd *args);
178062c476c7SBen-Ami Yassour 
17819d4cba7fSPaul Mackerras /*
1782a54d8066SMaciej S. Szmigiero  * Returns a pointer to the memslot if it contains gfn.
17830f22af94SDavid Matlack  * Otherwise returns NULL.
17840f22af94SDavid Matlack  */
17850f22af94SDavid Matlack static inline struct kvm_memory_slot *
try_get_memslot(struct kvm_memory_slot * slot,gfn_t gfn)1786a54d8066SMaciej S. Szmigiero try_get_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
17870f22af94SDavid Matlack {
1788a54d8066SMaciej S. Szmigiero 	if (!slot)
17890f22af94SDavid Matlack 		return NULL;
17900f22af94SDavid Matlack 
17910f22af94SDavid Matlack 	if (gfn >= slot->base_gfn && gfn < slot->base_gfn + slot->npages)
17920f22af94SDavid Matlack 		return slot;
17930f22af94SDavid Matlack 	else
17940f22af94SDavid Matlack 		return NULL;
17950f22af94SDavid Matlack }
17960f22af94SDavid Matlack 
17970f22af94SDavid Matlack /*
1798a54d8066SMaciej S. Szmigiero  * Returns a pointer to the memslot that contains gfn. Otherwise returns NULL.
17990577d1abSSean Christopherson  *
1800c928bfc2SMaciej S. Szmigiero  * With "approx" set returns the memslot also when the address falls
1801c928bfc2SMaciej S. Szmigiero  * in a hole. In that case one of the memslots bordering the hole is
1802c928bfc2SMaciej S. Szmigiero  * returned.
18039d4cba7fSPaul Mackerras  */
18049d4cba7fSPaul Mackerras static inline struct kvm_memory_slot *
search_memslots(struct kvm_memslots * slots,gfn_t gfn,bool approx)1805a54d8066SMaciej S. Szmigiero search_memslots(struct kvm_memslots *slots, gfn_t gfn, bool approx)
18069d4cba7fSPaul Mackerras {
18070f22af94SDavid Matlack 	struct kvm_memory_slot *slot;
1808a54d8066SMaciej S. Szmigiero 	struct rb_node *node;
1809a54d8066SMaciej S. Szmigiero 	int idx = slots->node_idx;
18109d4cba7fSPaul Mackerras 
1811a54d8066SMaciej S. Szmigiero 	slot = NULL;
1812a54d8066SMaciej S. Szmigiero 	for (node = slots->gfn_tree.rb_node; node; ) {
1813a54d8066SMaciej S. Szmigiero 		slot = container_of(node, struct kvm_memory_slot, gfn_node[idx]);
1814a54d8066SMaciej S. Szmigiero 		if (gfn >= slot->base_gfn) {
1815a54d8066SMaciej S. Szmigiero 			if (gfn < slot->base_gfn + slot->npages)
18160f22af94SDavid Matlack 				return slot;
1817a54d8066SMaciej S. Szmigiero 			node = node->rb_right;
1818a54d8066SMaciej S. Szmigiero 		} else
1819a54d8066SMaciej S. Szmigiero 			node = node->rb_left;
1820c928bfc2SMaciej S. Szmigiero 	}
1821d4ae84a0SIgor Mammedov 
1822a54d8066SMaciej S. Szmigiero 	return approx ? slot : NULL;
18239d4cba7fSPaul Mackerras }
18249d4cba7fSPaul Mackerras 
18259d4cba7fSPaul Mackerras static inline struct kvm_memory_slot *
____gfn_to_memslot(struct kvm_memslots * slots,gfn_t gfn,bool approx)1826c928bfc2SMaciej S. Szmigiero ____gfn_to_memslot(struct kvm_memslots *slots, gfn_t gfn, bool approx)
18279d4cba7fSPaul Mackerras {
18280f22af94SDavid Matlack 	struct kvm_memory_slot *slot;
18290f22af94SDavid Matlack 
1830a54d8066SMaciej S. Szmigiero 	slot = (struct kvm_memory_slot *)atomic_long_read(&slots->last_used_slot);
1831a54d8066SMaciej S. Szmigiero 	slot = try_get_memslot(slot, gfn);
18320f22af94SDavid Matlack 	if (slot)
18330f22af94SDavid Matlack 		return slot;
18340f22af94SDavid Matlack 
1835a54d8066SMaciej S. Szmigiero 	slot = search_memslots(slots, gfn, approx);
18360f22af94SDavid Matlack 	if (slot) {
1837a54d8066SMaciej S. Szmigiero 		atomic_long_set(&slots->last_used_slot, (unsigned long)slot);
18380f22af94SDavid Matlack 		return slot;
18390f22af94SDavid Matlack 	}
18400f22af94SDavid Matlack 
18410f22af94SDavid Matlack 	return NULL;
18429d4cba7fSPaul Mackerras }
18439d4cba7fSPaul Mackerras 
1844c928bfc2SMaciej S. Szmigiero /*
1845c928bfc2SMaciej S. Szmigiero  * __gfn_to_memslot() and its descendants are here to allow arch code to inline
1846c928bfc2SMaciej S. Szmigiero  * the lookups in hot paths.  gfn_to_memslot() itself isn't here as an inline
1847c928bfc2SMaciej S. Szmigiero  * because that would bloat other code too much.
1848c928bfc2SMaciej S. Szmigiero  */
1849c928bfc2SMaciej S. Szmigiero static inline struct kvm_memory_slot *
__gfn_to_memslot(struct kvm_memslots * slots,gfn_t gfn)1850c928bfc2SMaciej S. Szmigiero __gfn_to_memslot(struct kvm_memslots *slots, gfn_t gfn)
1851c928bfc2SMaciej S. Szmigiero {
1852c928bfc2SMaciej S. Szmigiero 	return ____gfn_to_memslot(slots, gfn, false);
1853c928bfc2SMaciej S. Szmigiero }
1854c928bfc2SMaciej S. Szmigiero 
185566a03505SGavin Shan static inline unsigned long
__gfn_to_hva_memslot(const struct kvm_memory_slot * slot,gfn_t gfn)18568ca6f063SBen Gardon __gfn_to_hva_memslot(const struct kvm_memory_slot *slot, gfn_t gfn)
185766a03505SGavin Shan {
1858da27a83fSPaolo Bonzini 	/*
1859da27a83fSPaolo Bonzini 	 * The index was checked originally in search_memslots.  To avoid
1860da27a83fSPaolo Bonzini 	 * that a malicious guest builds a Spectre gadget out of e.g. page
1861da27a83fSPaolo Bonzini 	 * table walks, do not let the processor speculate loads outside
1862da27a83fSPaolo Bonzini 	 * the guest's registered memslots.
1863da27a83fSPaolo Bonzini 	 */
18644422829eSPaolo Bonzini 	unsigned long offset = gfn - slot->base_gfn;
18654422829eSPaolo Bonzini 	offset = array_index_nospec(offset, slot->npages);
1866da27a83fSPaolo Bonzini 	return slot->userspace_addr + offset * PAGE_SIZE;
186766a03505SGavin Shan }
186866a03505SGavin Shan 
memslot_id(struct kvm * kvm,gfn_t gfn)18690ee8dcb8SXiao Guangrong static inline int memslot_id(struct kvm *kvm, gfn_t gfn)
18700ee8dcb8SXiao Guangrong {
18710ee8dcb8SXiao Guangrong 	return gfn_to_memslot(kvm, gfn)->id;
18720ee8dcb8SXiao Guangrong }
18730ee8dcb8SXiao Guangrong 
1874d19a748bSTakuya Yoshikawa static inline gfn_t
hva_to_gfn_memslot(unsigned long hva,struct kvm_memory_slot * slot)1875d19a748bSTakuya Yoshikawa hva_to_gfn_memslot(unsigned long hva, struct kvm_memory_slot *slot)
1876887c08acSXiao Guangrong {
1877d19a748bSTakuya Yoshikawa 	gfn_t gfn_offset = (hva - slot->userspace_addr) >> PAGE_SHIFT;
1878d19a748bSTakuya Yoshikawa 
1879d19a748bSTakuya Yoshikawa 	return slot->base_gfn + gfn_offset;
1880887c08acSXiao Guangrong }
1881887c08acSXiao Guangrong 
gfn_to_gpa(gfn_t gfn)1882edf88417SAvi Kivity static inline gpa_t gfn_to_gpa(gfn_t gfn)
1883edf88417SAvi Kivity {
1884edf88417SAvi Kivity 	return (gpa_t)gfn << PAGE_SHIFT;
1885edf88417SAvi Kivity }
1886edf88417SAvi Kivity 
gpa_to_gfn(gpa_t gpa)1887c30a358dSJoerg Roedel static inline gfn_t gpa_to_gfn(gpa_t gpa)
1888c30a358dSJoerg Roedel {
1889c30a358dSJoerg Roedel 	return (gfn_t)(gpa >> PAGE_SHIFT);
1890c30a358dSJoerg Roedel }
1891c30a358dSJoerg Roedel 
pfn_to_hpa(kvm_pfn_t pfn)1892ba049e93SDan Williams static inline hpa_t pfn_to_hpa(kvm_pfn_t pfn)
189362c476c7SBen-Ami Yassour {
189462c476c7SBen-Ami Yassour 	return (hpa_t)pfn << PAGE_SHIFT;
189562c476c7SBen-Ami Yassour }
189662c476c7SBen-Ami Yassour 
kvm_is_gpa_in_memslot(struct kvm * kvm,gpa_t gpa)18979e7325acSSean Christopherson static inline bool kvm_is_gpa_in_memslot(struct kvm *kvm, gpa_t gpa)
1898dfeec843SHeiko Carstens {
1899dfeec843SHeiko Carstens 	unsigned long hva = gfn_to_hva(kvm, gpa_to_gfn(gpa));
1900dfeec843SHeiko Carstens 
19019e7325acSSean Christopherson 	return !kvm_is_error_hva(hva);
1902dfeec843SHeiko Carstens }
1903dfeec843SHeiko Carstens 
kvm_gpc_mark_dirty_in_slot(struct gfn_to_pfn_cache * gpc)190478b74638SPaul Durrant static inline void kvm_gpc_mark_dirty_in_slot(struct gfn_to_pfn_cache *gpc)
190578b74638SPaul Durrant {
190678b74638SPaul Durrant 	lockdep_assert_held(&gpc->lock);
190778b74638SPaul Durrant 
190878b74638SPaul Durrant 	if (!gpc->memslot)
190978b74638SPaul Durrant 		return;
191078b74638SPaul Durrant 
191178b74638SPaul Durrant 	mark_page_dirty_in_slot(gpc->kvm, gpc->memslot, gpa_to_gfn(gpc->gpa));
1912edf88417SAvi Kivity }
1913edf88417SAvi Kivity 
1914edf88417SAvi Kivity enum kvm_stat_kind {
1915edf88417SAvi Kivity 	KVM_STAT_VM,
1916edf88417SAvi Kivity 	KVM_STAT_VCPU,
1917edf88417SAvi Kivity };
1918edf88417SAvi Kivity 
1919536a6f88SJanosch Frank struct kvm_stat_data {
1920536a6f88SJanosch Frank 	struct kvm *kvm;
1921bc9e9e67SJing Zhang 	const struct _kvm_stats_desc *desc;
1922edf88417SAvi Kivity 	enum kvm_stat_kind kind;
1923edf88417SAvi Kivity };
192409cbcef6SMilan Pandurov 
1925cb082bfaSJing Zhang struct _kvm_stats_desc {
1926cb082bfaSJing Zhang 	struct kvm_stats_desc desc;
1927cb082bfaSJing Zhang 	char name[KVM_STATS_NAME_SIZE];
1928cb082bfaSJing Zhang };
1929cb082bfaSJing Zhang 
1930f95937ccSJing Zhang #define STATS_DESC_COMMON(type, unit, base, exp, sz, bsz)		       \
1931cb082bfaSJing Zhang 	.flags = type | unit | base |					       \
1932cb082bfaSJing Zhang 		 BUILD_BUG_ON_ZERO(type & ~KVM_STATS_TYPE_MASK) |	       \
1933cb082bfaSJing Zhang 		 BUILD_BUG_ON_ZERO(unit & ~KVM_STATS_UNIT_MASK) |	       \
1934cb082bfaSJing Zhang 		 BUILD_BUG_ON_ZERO(base & ~KVM_STATS_BASE_MASK),	       \
1935cb082bfaSJing Zhang 	.exponent = exp,						       \
1936f95937ccSJing Zhang 	.size = sz,							       \
1937f95937ccSJing Zhang 	.bucket_size = bsz
1938cb082bfaSJing Zhang 
1939f95937ccSJing Zhang #define VM_GENERIC_STATS_DESC(stat, type, unit, base, exp, sz, bsz)	       \
1940cb082bfaSJing Zhang 	{								       \
1941cb082bfaSJing Zhang 		{							       \
1942f95937ccSJing Zhang 			STATS_DESC_COMMON(type, unit, base, exp, sz, bsz),     \
1943cb082bfaSJing Zhang 			.offset = offsetof(struct kvm_vm_stat, generic.stat)   \
1944cb082bfaSJing Zhang 		},							       \
1945cb082bfaSJing Zhang 		.name = #stat,						       \
1946cb082bfaSJing Zhang 	}
1947f95937ccSJing Zhang #define VCPU_GENERIC_STATS_DESC(stat, type, unit, base, exp, sz, bsz)	       \
1948cb082bfaSJing Zhang 	{								       \
1949cb082bfaSJing Zhang 		{							       \
1950f95937ccSJing Zhang 			STATS_DESC_COMMON(type, unit, base, exp, sz, bsz),     \
1951cb082bfaSJing Zhang 			.offset = offsetof(struct kvm_vcpu_stat, generic.stat) \
1952cb082bfaSJing Zhang 		},							       \
1953cb082bfaSJing Zhang 		.name = #stat,						       \
1954cb082bfaSJing Zhang 	}
1955f95937ccSJing Zhang #define VM_STATS_DESC(stat, type, unit, base, exp, sz, bsz)		       \
1956cb082bfaSJing Zhang 	{								       \
1957cb082bfaSJing Zhang 		{							       \
1958f95937ccSJing Zhang 			STATS_DESC_COMMON(type, unit, base, exp, sz, bsz),     \
1959cb082bfaSJing Zhang 			.offset = offsetof(struct kvm_vm_stat, stat)	       \
1960cb082bfaSJing Zhang 		},							       \
1961cb082bfaSJing Zhang 		.name = #stat,						       \
1962cb082bfaSJing Zhang 	}
1963f95937ccSJing Zhang #define VCPU_STATS_DESC(stat, type, unit, base, exp, sz, bsz)		       \
1964cb082bfaSJing Zhang 	{								       \
1965cb082bfaSJing Zhang 		{							       \
1966f95937ccSJing Zhang 			STATS_DESC_COMMON(type, unit, base, exp, sz, bsz),     \
1967cb082bfaSJing Zhang 			.offset = offsetof(struct kvm_vcpu_stat, stat)	       \
1968cb082bfaSJing Zhang 		},							       \
1969cb082bfaSJing Zhang 		.name = #stat,						       \
1970cb082bfaSJing Zhang 	}
1971cb082bfaSJing Zhang /* SCOPE: VM, VM_GENERIC, VCPU, VCPU_GENERIC */
1972f95937ccSJing Zhang #define STATS_DESC(SCOPE, stat, type, unit, base, exp, sz, bsz)		       \
1973f95937ccSJing Zhang 	SCOPE##_STATS_DESC(stat, type, unit, base, exp, sz, bsz)
1974cb082bfaSJing Zhang 
1975cb082bfaSJing Zhang #define STATS_DESC_CUMULATIVE(SCOPE, name, unit, base, exponent)	       \
1976f95937ccSJing Zhang 	STATS_DESC(SCOPE, name, KVM_STATS_TYPE_CUMULATIVE,		       \
1977f95937ccSJing Zhang 		unit, base, exponent, 1, 0)
1978cb082bfaSJing Zhang #define STATS_DESC_INSTANT(SCOPE, name, unit, base, exponent)		       \
1979f95937ccSJing Zhang 	STATS_DESC(SCOPE, name, KVM_STATS_TYPE_INSTANT,			       \
1980f95937ccSJing Zhang 		unit, base, exponent, 1, 0)
1981cb082bfaSJing Zhang #define STATS_DESC_PEAK(SCOPE, name, unit, base, exponent)		       \
1982f95937ccSJing Zhang 	STATS_DESC(SCOPE, name, KVM_STATS_TYPE_PEAK,			       \
1983f95937ccSJing Zhang 		unit, base, exponent, 1, 0)
1984f95937ccSJing Zhang #define STATS_DESC_LINEAR_HIST(SCOPE, name, unit, base, exponent, sz, bsz)     \
1985f95937ccSJing Zhang 	STATS_DESC(SCOPE, name, KVM_STATS_TYPE_LINEAR_HIST,		       \
1986f95937ccSJing Zhang 		unit, base, exponent, sz, bsz)
1987f95937ccSJing Zhang #define STATS_DESC_LOG_HIST(SCOPE, name, unit, base, exponent, sz)	       \
1988f95937ccSJing Zhang 	STATS_DESC(SCOPE, name, KVM_STATS_TYPE_LOG_HIST,		       \
1989f95937ccSJing Zhang 		unit, base, exponent, sz, 0)
1990cb082bfaSJing Zhang 
1991cb082bfaSJing Zhang /* Cumulative counter, read/write */
1992cb082bfaSJing Zhang #define STATS_DESC_COUNTER(SCOPE, name)					       \
1993cb082bfaSJing Zhang 	STATS_DESC_CUMULATIVE(SCOPE, name, KVM_STATS_UNIT_NONE,		       \
1994cb082bfaSJing Zhang 		KVM_STATS_BASE_POW10, 0)
1995cb082bfaSJing Zhang /* Instantaneous counter, read only */
1996cb082bfaSJing Zhang #define STATS_DESC_ICOUNTER(SCOPE, name)				       \
1997cb082bfaSJing Zhang 	STATS_DESC_INSTANT(SCOPE, name, KVM_STATS_UNIT_NONE,		       \
1998cb082bfaSJing Zhang 		KVM_STATS_BASE_POW10, 0)
1999cb082bfaSJing Zhang /* Peak counter, read/write */
2000cb082bfaSJing Zhang #define STATS_DESC_PCOUNTER(SCOPE, name)				       \
2001cb082bfaSJing Zhang 	STATS_DESC_PEAK(SCOPE, name, KVM_STATS_UNIT_NONE,		       \
2002cb082bfaSJing Zhang 		KVM_STATS_BASE_POW10, 0)
2003cb082bfaSJing Zhang 
20041b870fa5SPaolo Bonzini /* Instantaneous boolean value, read only */
20051b870fa5SPaolo Bonzini #define STATS_DESC_IBOOLEAN(SCOPE, name)				       \
20061b870fa5SPaolo Bonzini 	STATS_DESC_INSTANT(SCOPE, name, KVM_STATS_UNIT_BOOLEAN,		       \
20071b870fa5SPaolo Bonzini 		KVM_STATS_BASE_POW10, 0)
20081b870fa5SPaolo Bonzini /* Peak (sticky) boolean value, read/write */
20091b870fa5SPaolo Bonzini #define STATS_DESC_PBOOLEAN(SCOPE, name)				       \
20101b870fa5SPaolo Bonzini 	STATS_DESC_PEAK(SCOPE, name, KVM_STATS_UNIT_BOOLEAN,		       \
20111b870fa5SPaolo Bonzini 		KVM_STATS_BASE_POW10, 0)
20121b870fa5SPaolo Bonzini 
2013cb082bfaSJing Zhang /* Cumulative time in nanosecond */
2014cb082bfaSJing Zhang #define STATS_DESC_TIME_NSEC(SCOPE, name)				       \
2015cb082bfaSJing Zhang 	STATS_DESC_CUMULATIVE(SCOPE, name, KVM_STATS_UNIT_SECONDS,	       \
2016cb082bfaSJing Zhang 		KVM_STATS_BASE_POW10, -9)
2017f95937ccSJing Zhang /* Linear histogram for time in nanosecond */
2018f95937ccSJing Zhang #define STATS_DESC_LINHIST_TIME_NSEC(SCOPE, name, sz, bsz)		       \
2019f95937ccSJing Zhang 	STATS_DESC_LINEAR_HIST(SCOPE, name, KVM_STATS_UNIT_SECONDS,	       \
2020f95937ccSJing Zhang 		KVM_STATS_BASE_POW10, -9, sz, bsz)
2021f95937ccSJing Zhang /* Logarithmic histogram for time in nanosecond */
2022f95937ccSJing Zhang #define STATS_DESC_LOGHIST_TIME_NSEC(SCOPE, name, sz)			       \
2023f95937ccSJing Zhang 	STATS_DESC_LOG_HIST(SCOPE, name, KVM_STATS_UNIT_SECONDS,	       \
2024f95937ccSJing Zhang 		KVM_STATS_BASE_POW10, -9, sz)
2025cb082bfaSJing Zhang 
2026fcfe1baeSJing Zhang #define KVM_GENERIC_VM_STATS()						       \
20273cc4e148SJing Zhang 	STATS_DESC_COUNTER(VM_GENERIC, remote_tlb_flush),		       \
20283cc4e148SJing Zhang 	STATS_DESC_COUNTER(VM_GENERIC, remote_tlb_flush_requests)
2029fcfe1baeSJing Zhang 
2030ce55c049SJing Zhang #define KVM_GENERIC_VCPU_STATS()					       \
2031ce55c049SJing Zhang 	STATS_DESC_COUNTER(VCPU_GENERIC, halt_successful_poll),		       \
2032ce55c049SJing Zhang 	STATS_DESC_COUNTER(VCPU_GENERIC, halt_attempted_poll),		       \
2033ce55c049SJing Zhang 	STATS_DESC_COUNTER(VCPU_GENERIC, halt_poll_invalid),		       \
2034ce55c049SJing Zhang 	STATS_DESC_COUNTER(VCPU_GENERIC, halt_wakeup),			       \
2035ce55c049SJing Zhang 	STATS_DESC_TIME_NSEC(VCPU_GENERIC, halt_poll_success_ns),	       \
203687bcc5faSJing Zhang 	STATS_DESC_TIME_NSEC(VCPU_GENERIC, halt_poll_fail_ns),		       \
20378ccba534SJing Zhang 	STATS_DESC_TIME_NSEC(VCPU_GENERIC, halt_wait_ns),		       \
20388ccba534SJing Zhang 	STATS_DESC_LOGHIST_TIME_NSEC(VCPU_GENERIC, halt_poll_success_hist,     \
20398ccba534SJing Zhang 			HALT_POLL_HIST_COUNT),				       \
20408ccba534SJing Zhang 	STATS_DESC_LOGHIST_TIME_NSEC(VCPU_GENERIC, halt_poll_fail_hist,	       \
20418ccba534SJing Zhang 			HALT_POLL_HIST_COUNT),				       \
20428ccba534SJing Zhang 	STATS_DESC_LOGHIST_TIME_NSEC(VCPU_GENERIC, halt_wait_hist,	       \
2043c3858335SJing Zhang 			HALT_POLL_HIST_COUNT),				       \
20441b870fa5SPaolo Bonzini 	STATS_DESC_IBOOLEAN(VCPU_GENERIC, blocking)
2045ce55c049SJing Zhang 
2046cb082bfaSJing Zhang ssize_t kvm_stats_read(char *id, const struct kvm_stats_header *header,
2047cb082bfaSJing Zhang 		       const struct _kvm_stats_desc *desc,
2048cb082bfaSJing Zhang 		       void *stats, size_t size_stats,
2049cb082bfaSJing Zhang 		       char __user *user_buffer, size_t size, loff_t *offset);
2050f95937ccSJing Zhang 
2051f95937ccSJing Zhang /**
2052f95937ccSJing Zhang  * kvm_stats_linear_hist_update() - Update bucket value for linear histogram
2053f95937ccSJing Zhang  * statistics data.
2054f95937ccSJing Zhang  *
2055f95937ccSJing Zhang  * @data: start address of the stats data
2056f95937ccSJing Zhang  * @size: the number of bucket of the stats data
2057f95937ccSJing Zhang  * @value: the new value used to update the linear histogram's bucket
2058f95937ccSJing Zhang  * @bucket_size: the size (width) of a bucket
2059f95937ccSJing Zhang  */
kvm_stats_linear_hist_update(u64 * data,size_t size,u64 value,size_t bucket_size)2060f95937ccSJing Zhang static inline void kvm_stats_linear_hist_update(u64 *data, size_t size,
2061f95937ccSJing Zhang 						u64 value, size_t bucket_size)
2062f95937ccSJing Zhang {
2063f95937ccSJing Zhang 	size_t index = div64_u64(value, bucket_size);
2064f95937ccSJing Zhang 
2065f95937ccSJing Zhang 	index = min(index, size - 1);
2066f95937ccSJing Zhang 	++data[index];
2067f95937ccSJing Zhang }
2068f95937ccSJing Zhang 
2069f95937ccSJing Zhang /**
2070f95937ccSJing Zhang  * kvm_stats_log_hist_update() - Update bucket value for logarithmic histogram
2071f95937ccSJing Zhang  * statistics data.
2072f95937ccSJing Zhang  *
2073f95937ccSJing Zhang  * @data: start address of the stats data
2074f95937ccSJing Zhang  * @size: the number of bucket of the stats data
2075f95937ccSJing Zhang  * @value: the new value used to update the logarithmic histogram's bucket
2076f95937ccSJing Zhang  */
kvm_stats_log_hist_update(u64 * data,size_t size,u64 value)2077f95937ccSJing Zhang static inline void kvm_stats_log_hist_update(u64 *data, size_t size, u64 value)
2078f95937ccSJing Zhang {
2079f95937ccSJing Zhang 	size_t index = fls64(value);
2080f95937ccSJing Zhang 
2081f95937ccSJing Zhang 	index = min(index, size - 1);
2082f95937ccSJing Zhang 	++data[index];
2083f95937ccSJing Zhang }
2084f95937ccSJing Zhang 
2085f95937ccSJing Zhang #define KVM_STATS_LINEAR_HIST_UPDATE(array, value, bsize)		       \
2086f95937ccSJing Zhang 	kvm_stats_linear_hist_update(array, ARRAY_SIZE(array), value, bsize)
2087f95937ccSJing Zhang #define KVM_STATS_LOG_HIST_UPDATE(array, value)				       \
2088f95937ccSJing Zhang 	kvm_stats_log_hist_update(array, ARRAY_SIZE(array), value)
2089f95937ccSJing Zhang 
2090f95937ccSJing Zhang 
2091fcfe1baeSJing Zhang extern const struct kvm_stats_header kvm_vm_stats_header;
2092fcfe1baeSJing Zhang extern const struct _kvm_stats_desc kvm_vm_stats_desc[];
2093ce55c049SJing Zhang extern const struct kvm_stats_header kvm_vcpu_stats_header;
2094ce55c049SJing Zhang extern const struct _kvm_stats_desc kvm_vcpu_stats_desc[];
2095d4c9ff2dSFeng(Eric) Liu 
2096f128cf8cSSean Christopherson #ifdef CONFIG_KVM_GENERIC_MMU_NOTIFIER
mmu_invalidate_retry(struct kvm * kvm,unsigned long mmu_seq)209720ec3ebdSChao Peng static inline int mmu_invalidate_retry(struct kvm *kvm, unsigned long mmu_seq)
2098e930bffeSAndrea Arcangeli {
209920ec3ebdSChao Peng 	if (unlikely(kvm->mmu_invalidate_in_progress))
2100e930bffeSAndrea Arcangeli 		return 1;
2101e930bffeSAndrea Arcangeli 	/*
210220ec3ebdSChao Peng 	 * Ensure the read of mmu_invalidate_in_progress happens before
210320ec3ebdSChao Peng 	 * the read of mmu_invalidate_seq.  This interacts with the
210420ec3ebdSChao Peng 	 * smp_wmb() in mmu_notifier_invalidate_range_end to make sure
210520ec3ebdSChao Peng 	 * that the caller either sees the old (non-zero) value of
210620ec3ebdSChao Peng 	 * mmu_invalidate_in_progress or the new (incremented) value of
210720ec3ebdSChao Peng 	 * mmu_invalidate_seq.
210820ec3ebdSChao Peng 	 *
210920ec3ebdSChao Peng 	 * PowerPC Book3s HV KVM calls this under a per-page lock rather
211020ec3ebdSChao Peng 	 * than under kvm->mmu_lock, for scalability, so can't rely on
211120ec3ebdSChao Peng 	 * kvm->mmu_lock to keep things ordered.
2112e930bffeSAndrea Arcangeli 	 */
2113a355aa54SPaul Mackerras 	smp_rmb();
211420ec3ebdSChao Peng 	if (kvm->mmu_invalidate_seq != mmu_seq)
2115e930bffeSAndrea Arcangeli 		return 1;
2116e930bffeSAndrea Arcangeli 	return 0;
2117e930bffeSAndrea Arcangeli }
21184a42d848SDavid Stevens 
mmu_invalidate_retry_gfn(struct kvm * kvm,unsigned long mmu_seq,gfn_t gfn)21198569992dSChao Peng static inline int mmu_invalidate_retry_gfn(struct kvm *kvm,
21204a42d848SDavid Stevens 					   unsigned long mmu_seq,
21218569992dSChao Peng 					   gfn_t gfn)
21224a42d848SDavid Stevens {
21234a42d848SDavid Stevens 	lockdep_assert_held(&kvm->mmu_lock);
21244a42d848SDavid Stevens 	/*
212520ec3ebdSChao Peng 	 * If mmu_invalidate_in_progress is non-zero, then the range maintained
212620ec3ebdSChao Peng 	 * by kvm_mmu_notifier_invalidate_range_start contains all addresses
212720ec3ebdSChao Peng 	 * that might be being invalidated. Note that it may include some false
21284a42d848SDavid Stevens 	 * positives, due to shortcuts when handing concurrent invalidations.
21294a42d848SDavid Stevens 	 */
21308569992dSChao Peng 	if (unlikely(kvm->mmu_invalidate_in_progress)) {
21318569992dSChao Peng 		/*
21328569992dSChao Peng 		 * Dropping mmu_lock after bumping mmu_invalidate_in_progress
21338569992dSChao Peng 		 * but before updating the range is a KVM bug.
21348569992dSChao Peng 		 */
21358569992dSChao Peng 		if (WARN_ON_ONCE(kvm->mmu_invalidate_range_start == INVALID_GPA ||
21368569992dSChao Peng 				 kvm->mmu_invalidate_range_end == INVALID_GPA))
21374a42d848SDavid Stevens 			return 1;
21388569992dSChao Peng 
21398569992dSChao Peng 		if (gfn >= kvm->mmu_invalidate_range_start &&
21408569992dSChao Peng 		    gfn < kvm->mmu_invalidate_range_end)
21418569992dSChao Peng 			return 1;
21428569992dSChao Peng 	}
21438569992dSChao Peng 
214420ec3ebdSChao Peng 	if (kvm->mmu_invalidate_seq != mmu_seq)
21454a42d848SDavid Stevens 		return 1;
21464a42d848SDavid Stevens 	return 0;
21474a42d848SDavid Stevens }
2148d02c357eSSean Christopherson 
2149d02c357eSSean Christopherson /*
2150d02c357eSSean Christopherson  * This lockless version of the range-based retry check *must* be paired with a
2151d02c357eSSean Christopherson  * call to the locked version after acquiring mmu_lock, i.e. this is safe to
2152d02c357eSSean Christopherson  * use only as a pre-check to avoid contending mmu_lock.  This version *will*
2153d02c357eSSean Christopherson  * get false negatives and false positives.
2154d02c357eSSean Christopherson  */
mmu_invalidate_retry_gfn_unsafe(struct kvm * kvm,unsigned long mmu_seq,gfn_t gfn)2155d02c357eSSean Christopherson static inline bool mmu_invalidate_retry_gfn_unsafe(struct kvm *kvm,
2156d02c357eSSean Christopherson 						   unsigned long mmu_seq,
2157d02c357eSSean Christopherson 						   gfn_t gfn)
2158d02c357eSSean Christopherson {
2159d02c357eSSean Christopherson 	/*
2160d02c357eSSean Christopherson 	 * Use READ_ONCE() to ensure the in-progress flag and sequence counter
2161d02c357eSSean Christopherson 	 * are always read from memory, e.g. so that checking for retry in a
2162d02c357eSSean Christopherson 	 * loop won't result in an infinite retry loop.  Don't force loads for
2163d02c357eSSean Christopherson 	 * start+end, as the key to avoiding infinite retry loops is observing
2164d02c357eSSean Christopherson 	 * the 1=>0 transition of in-progress, i.e. getting false negatives
2165d02c357eSSean Christopherson 	 * due to stale start+end values is acceptable.
2166d02c357eSSean Christopherson 	 */
2167d02c357eSSean Christopherson 	if (unlikely(READ_ONCE(kvm->mmu_invalidate_in_progress)) &&
2168d02c357eSSean Christopherson 	    gfn >= kvm->mmu_invalidate_range_start &&
2169d02c357eSSean Christopherson 	    gfn < kvm->mmu_invalidate_range_end)
2170d02c357eSSean Christopherson 		return true;
2171d02c357eSSean Christopherson 
2172d02c357eSSean Christopherson 	return READ_ONCE(kvm->mmu_invalidate_seq) != mmu_seq;
2173d02c357eSSean Christopherson }
2174e930bffeSAndrea Arcangeli #endif
2175e930bffeSAndrea Arcangeli 
2176a725d56aSAlexander Graf #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
2177399ec807SAvi Kivity 
2178ddc9cfb7SWanpeng Li #define KVM_MAX_IRQ_ROUTES 4096 /* might need extension/rework in the future */
2179399ec807SAvi Kivity 
21805c0aea0eSDavid Hildenbrand bool kvm_arch_can_set_irq_routing(struct kvm *kvm);
2181399ec807SAvi Kivity int kvm_set_irq_routing(struct kvm *kvm,
2182399ec807SAvi Kivity 			const struct kvm_irq_routing_entry *entries,
2183399ec807SAvi Kivity 			unsigned nr,
2184399ec807SAvi Kivity 			unsigned flags);
2185fbe4a7e8SYi Wang int kvm_init_irq_routing(struct kvm *kvm);
2186c63cf538SRadim Krčmář int kvm_set_routing_entry(struct kvm *kvm,
2187c63cf538SRadim Krčmář 			  struct kvm_kernel_irq_routing_entry *e,
2188e8cde093SAlexander Graf 			  const struct kvm_irq_routing_entry *ue);
2189399ec807SAvi Kivity void kvm_free_irq_routing(struct kvm *kvm);
2190399ec807SAvi Kivity 
2191399ec807SAvi Kivity #else
2192399ec807SAvi Kivity 
kvm_free_irq_routing(struct kvm * kvm)2193399ec807SAvi Kivity static inline void kvm_free_irq_routing(struct kvm *kvm) {}
2194399ec807SAvi Kivity 
kvm_init_irq_routing(struct kvm * kvm)2195fbe4a7e8SYi Wang static inline int kvm_init_irq_routing(struct kvm *kvm)
2196fbe4a7e8SYi Wang {
2197fbe4a7e8SYi Wang 	return 0;
2198fbe4a7e8SYi Wang }
2199fbe4a7e8SYi Wang 
2200399ec807SAvi Kivity #endif
2201399ec807SAvi Kivity 
2202297e2105SPaul Mackerras int kvm_send_userspace_msi(struct kvm *kvm, struct kvm_msi *msi);
2203297e2105SPaul Mackerras 
2204d34e6b17SGregory Haskins void kvm_eventfd_init(struct kvm *kvm);
2205914daba8SAlexander Graf int kvm_ioeventfd(struct kvm *kvm, struct kvm_ioeventfd *args);
2206914daba8SAlexander Graf 
2207c5b31cc2SPaolo Bonzini #ifdef CONFIG_HAVE_KVM_IRQCHIP
2208d4db2935SAlex Williamson int kvm_irqfd(struct kvm *kvm, struct kvm_irqfd *args);
2209721eecbfSGregory Haskins void kvm_irqfd_release(struct kvm *kvm);
2210fef8f2b9SDmytro Maluka bool kvm_notify_irqfd_resampler(struct kvm *kvm,
2211fef8f2b9SDmytro Maluka 				unsigned int irqchip,
2212fef8f2b9SDmytro Maluka 				unsigned int pin);
22139957c86dSPaul Mackerras void kvm_irq_routing_update(struct kvm *);
2214914daba8SAlexander Graf #else
kvm_irqfd(struct kvm * kvm,struct kvm_irqfd * args)2215914daba8SAlexander Graf static inline int kvm_irqfd(struct kvm *kvm, struct kvm_irqfd *args)
2216914daba8SAlexander Graf {
2217914daba8SAlexander Graf 	return -EINVAL;
2218914daba8SAlexander Graf }
2219914daba8SAlexander Graf 
kvm_irqfd_release(struct kvm * kvm)2220914daba8SAlexander Graf static inline void kvm_irqfd_release(struct kvm *kvm) {}
2221fef8f2b9SDmytro Maluka 
kvm_notify_irqfd_resampler(struct kvm * kvm,unsigned int irqchip,unsigned int pin)2222fef8f2b9SDmytro Maluka static inline bool kvm_notify_irqfd_resampler(struct kvm *kvm,
2223fef8f2b9SDmytro Maluka 					      unsigned int irqchip,
2224fef8f2b9SDmytro Maluka 					      unsigned int pin)
2225fef8f2b9SDmytro Maluka {
2226fef8f2b9SDmytro Maluka 	return false;
2227fef8f2b9SDmytro Maluka }
2228c5b31cc2SPaolo Bonzini #endif /* CONFIG_HAVE_KVM_IRQCHIP */
2229721eecbfSGregory Haskins 
223007646749SSebastian Ott void kvm_arch_irq_routing_update(struct kvm *kvm);
223107646749SSebastian Ott 
__kvm_make_request(int req,struct kvm_vcpu * vcpu)2232df06dae3SSean Christopherson static inline void __kvm_make_request(int req, struct kvm_vcpu *vcpu)
2233a8eeb04aSAvi Kivity {
22342e4682baSPaolo Bonzini 	/*
22352e4682baSPaolo Bonzini 	 * Ensure the rest of the request is published to kvm_check_request's
22362e4682baSPaolo Bonzini 	 * caller.  Paired with the smp_mb__after_atomic in kvm_check_request.
22372e4682baSPaolo Bonzini 	 */
22382e4682baSPaolo Bonzini 	smp_wmb();
223986dafed5SKarimAllah Ahmed 	set_bit(req & KVM_REQUEST_MASK, (void *)&vcpu->requests);
2240a8eeb04aSAvi Kivity }
2241a8eeb04aSAvi Kivity 
kvm_make_request(int req,struct kvm_vcpu * vcpu)2242df06dae3SSean Christopherson static __always_inline void kvm_make_request(int req, struct kvm_vcpu *vcpu)
2243df06dae3SSean Christopherson {
2244df06dae3SSean Christopherson 	/*
2245df06dae3SSean Christopherson 	 * Request that don't require vCPU action should never be logged in
2246df06dae3SSean Christopherson 	 * vcpu->requests.  The vCPU won't clear the request, so it will stay
2247df06dae3SSean Christopherson 	 * logged indefinitely and prevent the vCPU from entering the guest.
2248df06dae3SSean Christopherson 	 */
2249df06dae3SSean Christopherson 	BUILD_BUG_ON(!__builtin_constant_p(req) ||
2250df06dae3SSean Christopherson 		     (req & KVM_REQUEST_NO_ACTION));
2251df06dae3SSean Christopherson 
2252df06dae3SSean Christopherson 	__kvm_make_request(req, vcpu);
2253df06dae3SSean Christopherson }
2254df06dae3SSean Christopherson 
kvm_request_pending(struct kvm_vcpu * vcpu)22552fa6e1e1SRadim Krčmář static inline bool kvm_request_pending(struct kvm_vcpu *vcpu)
22562fa6e1e1SRadim Krčmář {
22572fa6e1e1SRadim Krčmář 	return READ_ONCE(vcpu->requests);
22582fa6e1e1SRadim Krčmář }
22592fa6e1e1SRadim Krčmář 
kvm_test_request(int req,struct kvm_vcpu * vcpu)226072875d8aSRadim Krčmář static inline bool kvm_test_request(int req, struct kvm_vcpu *vcpu)
226172875d8aSRadim Krčmář {
226286dafed5SKarimAllah Ahmed 	return test_bit(req & KVM_REQUEST_MASK, (void *)&vcpu->requests);
226372875d8aSRadim Krčmář }
226472875d8aSRadim Krčmář 
kvm_clear_request(int req,struct kvm_vcpu * vcpu)226572875d8aSRadim Krčmář static inline void kvm_clear_request(int req, struct kvm_vcpu *vcpu)
226672875d8aSRadim Krčmář {
226786dafed5SKarimAllah Ahmed 	clear_bit(req & KVM_REQUEST_MASK, (void *)&vcpu->requests);
226872875d8aSRadim Krčmář }
226972875d8aSRadim Krčmář 
kvm_check_request(int req,struct kvm_vcpu * vcpu)2270a8eeb04aSAvi Kivity static inline bool kvm_check_request(int req, struct kvm_vcpu *vcpu)
2271a8eeb04aSAvi Kivity {
227272875d8aSRadim Krčmář 	if (kvm_test_request(req, vcpu)) {
227372875d8aSRadim Krčmář 		kvm_clear_request(req, vcpu);
22742e4682baSPaolo Bonzini 
22752e4682baSPaolo Bonzini 		/*
22762e4682baSPaolo Bonzini 		 * Ensure the rest of the request is visible to kvm_check_request's
22772e4682baSPaolo Bonzini 		 * caller.  Paired with the smp_wmb in kvm_make_request.
22782e4682baSPaolo Bonzini 		 */
22792e4682baSPaolo Bonzini 		smp_mb__after_atomic();
22800719837cSAvi Kivity 		return true;
22810719837cSAvi Kivity 	} else {
22820719837cSAvi Kivity 		return false;
22830719837cSAvi Kivity 	}
2284a8eeb04aSAvi Kivity }
2285a8eeb04aSAvi Kivity 
2286441f7bfaSSean Christopherson #ifdef CONFIG_KVM_GENERIC_HARDWARE_ENABLING
22878b415dcdSGeoff Levand extern bool kvm_rebooting;
2288441f7bfaSSean Christopherson #endif
22898b415dcdSGeoff Levand 
2290ec76d819SSuraj Jitindar Singh extern unsigned int halt_poll_ns;
2291ec76d819SSuraj Jitindar Singh extern unsigned int halt_poll_ns_grow;
229249113d36SNir Weiner extern unsigned int halt_poll_ns_grow_start;
2293ec76d819SSuraj Jitindar Singh extern unsigned int halt_poll_ns_shrink;
2294ec76d819SSuraj Jitindar Singh 
2295852b6d57SScott Wood struct kvm_device {
22968538cb22SSteven Price 	const struct kvm_device_ops *ops;
2297852b6d57SScott Wood 	struct kvm *kvm;
2298852b6d57SScott Wood 	void *private;
229907f0a7bdSScott Wood 	struct list_head vm_node;
2300852b6d57SScott Wood };
2301852b6d57SScott Wood 
2302852b6d57SScott Wood /* create, destroy, and name are mandatory */
2303852b6d57SScott Wood struct kvm_device_ops {
2304852b6d57SScott Wood 	const char *name;
2305a28ebea2SChristoffer Dall 
2306a28ebea2SChristoffer Dall 	/*
2307a28ebea2SChristoffer Dall 	 * create is called holding kvm->lock and any operations not suitable
2308a28ebea2SChristoffer Dall 	 * to do while holding the lock should be deferred to init (see
2309a28ebea2SChristoffer Dall 	 * below).
2310a28ebea2SChristoffer Dall 	 */
2311852b6d57SScott Wood 	int (*create)(struct kvm_device *dev, u32 type);
2312852b6d57SScott Wood 
2313852b6d57SScott Wood 	/*
2314023e9fddSChristoffer Dall 	 * init is called after create if create is successful and is called
2315023e9fddSChristoffer Dall 	 * outside of holding kvm->lock.
2316023e9fddSChristoffer Dall 	 */
2317023e9fddSChristoffer Dall 	void (*init)(struct kvm_device *dev);
2318023e9fddSChristoffer Dall 
2319023e9fddSChristoffer Dall 	/*
2320852b6d57SScott Wood 	 * Destroy is responsible for freeing dev.
2321852b6d57SScott Wood 	 *
2322852b6d57SScott Wood 	 * Destroy may be called before or after destructors are called
2323852b6d57SScott Wood 	 * on emulated I/O regions, depending on whether a reference is
2324852b6d57SScott Wood 	 * held by a vcpu or other kvm component that gets destroyed
2325852b6d57SScott Wood 	 * after the emulated I/O.
2326852b6d57SScott Wood 	 */
2327852b6d57SScott Wood 	void (*destroy)(struct kvm_device *dev);
2328852b6d57SScott Wood 
23292bde9b3eSCédric Le Goater 	/*
23302bde9b3eSCédric Le Goater 	 * Release is an alternative method to free the device. It is
23312bde9b3eSCédric Le Goater 	 * called when the device file descriptor is closed. Once
23322bde9b3eSCédric Le Goater 	 * release is called, the destroy method will not be called
23332bde9b3eSCédric Le Goater 	 * anymore as the device is removed from the device list of
23342bde9b3eSCédric Le Goater 	 * the VM. kvm->lock is held.
23352bde9b3eSCédric Le Goater 	 */
23362bde9b3eSCédric Le Goater 	void (*release)(struct kvm_device *dev);
23372bde9b3eSCédric Le Goater 
2338852b6d57SScott Wood 	int (*set_attr)(struct kvm_device *dev, struct kvm_device_attr *attr);
2339852b6d57SScott Wood 	int (*get_attr)(struct kvm_device *dev, struct kvm_device_attr *attr);
2340852b6d57SScott Wood 	int (*has_attr)(struct kvm_device *dev, struct kvm_device_attr *attr);
2341852b6d57SScott Wood 	long (*ioctl)(struct kvm_device *dev, unsigned int ioctl,
2342852b6d57SScott Wood 		      unsigned long arg);
2343a1cd3f08SCédric Le Goater 	int (*mmap)(struct kvm_device *dev, struct vm_area_struct *vma);
2344852b6d57SScott Wood };
2345852b6d57SScott Wood 
2346852b6d57SScott Wood struct kvm_device *kvm_device_from_filp(struct file *filp);
23478538cb22SSteven Price int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type);
2348571ee1b6SWanpeng Li void kvm_unregister_device_ops(u32 type);
2349852b6d57SScott Wood 
23505df554adSScott Wood extern struct kvm_device_ops kvm_mpic_ops;
2351ea2f83a7SAndre Przywara extern struct kvm_device_ops kvm_arm_vgic_v2_ops;
2352a0675c25SAndre Przywara extern struct kvm_device_ops kvm_arm_vgic_v3_ops;
23535df554adSScott Wood 
23544c088493SRaghavendra K T #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
23554c088493SRaghavendra K T 
kvm_vcpu_set_in_spin_loop(struct kvm_vcpu * vcpu,bool val)23564c088493SRaghavendra K T static inline void kvm_vcpu_set_in_spin_loop(struct kvm_vcpu *vcpu, bool val)
23574c088493SRaghavendra K T {
23584c088493SRaghavendra K T 	vcpu->spin_loop.in_spin_loop = val;
23594c088493SRaghavendra K T }
kvm_vcpu_set_dy_eligible(struct kvm_vcpu * vcpu,bool val)23604c088493SRaghavendra K T static inline void kvm_vcpu_set_dy_eligible(struct kvm_vcpu *vcpu, bool val)
23614c088493SRaghavendra K T {
23624c088493SRaghavendra K T 	vcpu->spin_loop.dy_eligible = val;
23634c088493SRaghavendra K T }
23644c088493SRaghavendra K T 
23654c088493SRaghavendra K T #else /* !CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT */
23664c088493SRaghavendra K T 
kvm_vcpu_set_in_spin_loop(struct kvm_vcpu * vcpu,bool val)23674c088493SRaghavendra K T static inline void kvm_vcpu_set_in_spin_loop(struct kvm_vcpu *vcpu, bool val)
23684c088493SRaghavendra K T {
23694c088493SRaghavendra K T }
23704c088493SRaghavendra K T 
kvm_vcpu_set_dy_eligible(struct kvm_vcpu * vcpu,bool val)23714c088493SRaghavendra K T static inline void kvm_vcpu_set_dy_eligible(struct kvm_vcpu *vcpu, bool val)
23724c088493SRaghavendra K T {
23734c088493SRaghavendra K T }
23744c088493SRaghavendra K T #endif /* CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT */
23751a02b270SEric Auger 
kvm_is_visible_memslot(struct kvm_memory_slot * memslot)2376c36b7150SPaolo Bonzini static inline bool kvm_is_visible_memslot(struct kvm_memory_slot *memslot)
2377c36b7150SPaolo Bonzini {
2378c36b7150SPaolo Bonzini 	return (memslot && memslot->id < KVM_USER_MEM_SLOTS &&
2379c36b7150SPaolo Bonzini 		!(memslot->flags & KVM_MEMSLOT_INVALID));
2380c36b7150SPaolo Bonzini }
2381c36b7150SPaolo Bonzini 
23827495e22bSPaolo Bonzini struct kvm_vcpu *kvm_get_running_vcpu(void);
2383fcd07f9aSChristian Borntraeger struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void);
23847495e22bSPaolo Bonzini 
2385*459a3511SSean Christopherson #if IS_ENABLED(CONFIG_HAVE_KVM_IRQ_BYPASS)
238614717e20SAlex Williamson bool kvm_arch_has_irq_bypass(void);
23871a02b270SEric Auger int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *,
23881a02b270SEric Auger 			   struct irq_bypass_producer *);
23891a02b270SEric Auger void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *,
23901a02b270SEric Auger 			   struct irq_bypass_producer *);
23911a02b270SEric Auger void kvm_arch_irq_bypass_stop(struct irq_bypass_consumer *);
23921a02b270SEric Auger void kvm_arch_irq_bypass_start(struct irq_bypass_consumer *);
2393f70c20aaSFeng Wu int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
2394f70c20aaSFeng Wu 				  uint32_t guest_irq, bool set);
2395515a0c79SLongpeng(Mike) bool kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry *,
2396515a0c79SLongpeng(Mike) 				  struct kvm_kernel_irq_routing_entry *);
23971a02b270SEric Auger #endif /* CONFIG_HAVE_KVM_IRQ_BYPASS */
239835181e86SHaozhong Zhang 
23993491caf2SChristian Borntraeger #ifdef CONFIG_HAVE_KVM_INVALID_WAKEUPS
24003491caf2SChristian Borntraeger /* If we wakeup during the poll time, was it a sucessful poll? */
vcpu_valid_wakeup(struct kvm_vcpu * vcpu)24013491caf2SChristian Borntraeger static inline bool vcpu_valid_wakeup(struct kvm_vcpu *vcpu)
24023491caf2SChristian Borntraeger {
24033491caf2SChristian Borntraeger 	return vcpu->valid_wakeup;
24043491caf2SChristian Borntraeger }
24053491caf2SChristian Borntraeger 
24063491caf2SChristian Borntraeger #else
vcpu_valid_wakeup(struct kvm_vcpu * vcpu)24073491caf2SChristian Borntraeger static inline bool vcpu_valid_wakeup(struct kvm_vcpu *vcpu)
24083491caf2SChristian Borntraeger {
24093491caf2SChristian Borntraeger 	return true;
24103491caf2SChristian Borntraeger }
24113491caf2SChristian Borntraeger #endif /* CONFIG_HAVE_KVM_INVALID_WAKEUPS */
24123491caf2SChristian Borntraeger 
2413cdd6ad3aSChristian Borntraeger #ifdef CONFIG_HAVE_KVM_NO_POLL
2414cdd6ad3aSChristian Borntraeger /* Callback that tells if we must not poll */
2415cdd6ad3aSChristian Borntraeger bool kvm_arch_no_poll(struct kvm_vcpu *vcpu);
2416cdd6ad3aSChristian Borntraeger #else
kvm_arch_no_poll(struct kvm_vcpu * vcpu)2417cdd6ad3aSChristian Borntraeger static inline bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
2418cdd6ad3aSChristian Borntraeger {
2419cdd6ad3aSChristian Borntraeger 	return false;
2420cdd6ad3aSChristian Borntraeger }
2421cdd6ad3aSChristian Borntraeger #endif /* CONFIG_HAVE_KVM_NO_POLL */
2422cdd6ad3aSChristian Borntraeger 
24235cb0944cSPaolo Bonzini #ifdef CONFIG_HAVE_KVM_VCPU_ASYNC_IOCTL
24245cb0944cSPaolo Bonzini long kvm_arch_vcpu_async_ioctl(struct file *filp,
24255cb0944cSPaolo Bonzini 			       unsigned int ioctl, unsigned long arg);
24265cb0944cSPaolo Bonzini #else
kvm_arch_vcpu_async_ioctl(struct file * filp,unsigned int ioctl,unsigned long arg)24275cb0944cSPaolo Bonzini static inline long kvm_arch_vcpu_async_ioctl(struct file *filp,
24285cb0944cSPaolo Bonzini 					     unsigned int ioctl,
24295cb0944cSPaolo Bonzini 					     unsigned long arg)
24305cb0944cSPaolo Bonzini {
24315cb0944cSPaolo Bonzini 	return -ENOIOCTLCMD;
24325cb0944cSPaolo Bonzini }
24335cb0944cSPaolo Bonzini #endif /* CONFIG_HAVE_KVM_VCPU_ASYNC_IOCTL */
24345cb0944cSPaolo Bonzini 
2435683412ccSMingwei Zhang void kvm_arch_guest_memory_reclaimed(struct kvm *kvm);
2436683412ccSMingwei Zhang 
2437bd2a6394SChristoffer Dall #ifdef CONFIG_HAVE_KVM_VCPU_RUN_PID_CHANGE
2438bd2a6394SChristoffer Dall int kvm_arch_vcpu_run_pid_change(struct kvm_vcpu *vcpu);
2439bd2a6394SChristoffer Dall #else
kvm_arch_vcpu_run_pid_change(struct kvm_vcpu * vcpu)2440bd2a6394SChristoffer Dall static inline int kvm_arch_vcpu_run_pid_change(struct kvm_vcpu *vcpu)
2441bd2a6394SChristoffer Dall {
2442bd2a6394SChristoffer Dall 	return 0;
2443bd2a6394SChristoffer Dall }
2444bd2a6394SChristoffer Dall #endif /* CONFIG_HAVE_KVM_VCPU_RUN_PID_CHANGE */
2445bd2a6394SChristoffer Dall 
2446935ace2fSThomas Gleixner #ifdef CONFIG_KVM_XFER_TO_GUEST_WORK
kvm_handle_signal_exit(struct kvm_vcpu * vcpu)2447935ace2fSThomas Gleixner static inline void kvm_handle_signal_exit(struct kvm_vcpu *vcpu)
2448935ace2fSThomas Gleixner {
2449935ace2fSThomas Gleixner 	vcpu->run->exit_reason = KVM_EXIT_INTR;
2450935ace2fSThomas Gleixner 	vcpu->stat.signal_exits++;
2451935ace2fSThomas Gleixner }
2452935ace2fSThomas Gleixner #endif /* CONFIG_KVM_XFER_TO_GUEST_WORK */
2453935ace2fSThomas Gleixner 
2454fb04a1edSPeter Xu /*
245543a063caSYosry Ahmed  * If more than one page is being (un)accounted, @virt must be the address of
245643a063caSYosry Ahmed  * the first page of a block of pages what were allocated together (i.e
245743a063caSYosry Ahmed  * accounted together).
245843a063caSYosry Ahmed  *
245943a063caSYosry Ahmed  * kvm_account_pgtable_pages() is thread-safe because mod_lruvec_page_state()
246043a063caSYosry Ahmed  * is thread-safe.
246143a063caSYosry Ahmed  */
kvm_account_pgtable_pages(void * virt,int nr)246243a063caSYosry Ahmed static inline void kvm_account_pgtable_pages(void *virt, int nr)
246343a063caSYosry Ahmed {
246443a063caSYosry Ahmed 	mod_lruvec_page_state(virt_to_page(virt), NR_SECONDARY_PAGETABLE, nr);
246543a063caSYosry Ahmed }
246643a063caSYosry Ahmed 
246743a063caSYosry Ahmed /*
2468fb04a1edSPeter Xu  * This defines how many reserved entries we want to keep before we
2469fb04a1edSPeter Xu  * kick the vcpu to the userspace to avoid dirty ring full.  This
2470fb04a1edSPeter Xu  * value can be tuned to higher if e.g. PML is enabled on the host.
2471fb04a1edSPeter Xu  */
2472fb04a1edSPeter Xu #define  KVM_DIRTY_RING_RSVD_ENTRIES  64
2473fb04a1edSPeter Xu 
2474fb04a1edSPeter Xu /* Max number of entries allowed for each kvm dirty ring */
2475fb04a1edSPeter Xu #define  KVM_DIRTY_RING_MAX_ENTRIES  65536
2476fb04a1edSPeter Xu 
kvm_prepare_memory_fault_exit(struct kvm_vcpu * vcpu,gpa_t gpa,gpa_t size,bool is_write,bool is_exec,bool is_private)247716f95f3bSChao Peng static inline void kvm_prepare_memory_fault_exit(struct kvm_vcpu *vcpu,
24788dd2eee9SChao Peng 						 gpa_t gpa, gpa_t size,
24798dd2eee9SChao Peng 						 bool is_write, bool is_exec,
24808dd2eee9SChao Peng 						 bool is_private)
248116f95f3bSChao Peng {
248216f95f3bSChao Peng 	vcpu->run->exit_reason = KVM_EXIT_MEMORY_FAULT;
248316f95f3bSChao Peng 	vcpu->run->memory_fault.gpa = gpa;
248416f95f3bSChao Peng 	vcpu->run->memory_fault.size = size;
248516f95f3bSChao Peng 
24868dd2eee9SChao Peng 	/* RWX flags are not (yet) defined or communicated to userspace. */
248716f95f3bSChao Peng 	vcpu->run->memory_fault.flags = 0;
24888dd2eee9SChao Peng 	if (is_private)
24898dd2eee9SChao Peng 		vcpu->run->memory_fault.flags |= KVM_MEMORY_EXIT_FLAG_PRIVATE;
249016f95f3bSChao Peng }
249116f95f3bSChao Peng 
24925a475554SChao Peng #ifdef CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES
kvm_get_memory_attributes(struct kvm * kvm,gfn_t gfn)24935a475554SChao Peng static inline unsigned long kvm_get_memory_attributes(struct kvm *kvm, gfn_t gfn)
24945a475554SChao Peng {
24955a475554SChao Peng 	return xa_to_value(xa_load(&kvm->mem_attr_array, gfn));
24965a475554SChao Peng }
24975a475554SChao Peng 
24985a475554SChao Peng bool kvm_range_has_memory_attributes(struct kvm *kvm, gfn_t start, gfn_t end,
24994b5f6712SPaolo Bonzini 				     unsigned long mask, unsigned long attrs);
25005a475554SChao Peng bool kvm_arch_pre_set_memory_attributes(struct kvm *kvm,
25015a475554SChao Peng 					struct kvm_gfn_range *range);
25025a475554SChao Peng bool kvm_arch_post_set_memory_attributes(struct kvm *kvm,
25035a475554SChao Peng 					 struct kvm_gfn_range *range);
2504a7800aa8SSean Christopherson 
kvm_mem_is_private(struct kvm * kvm,gfn_t gfn)2505a7800aa8SSean Christopherson static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn)
2506a7800aa8SSean Christopherson {
2507a7800aa8SSean Christopherson 	return IS_ENABLED(CONFIG_KVM_PRIVATE_MEM) &&
2508a7800aa8SSean Christopherson 	       kvm_get_memory_attributes(kvm, gfn) & KVM_MEMORY_ATTRIBUTE_PRIVATE;
2509a7800aa8SSean Christopherson }
2510a7800aa8SSean Christopherson #else
kvm_mem_is_private(struct kvm * kvm,gfn_t gfn)2511a7800aa8SSean Christopherson static inline bool kvm_mem_is_private(struct kvm *kvm, gfn_t gfn)
2512a7800aa8SSean Christopherson {
2513a7800aa8SSean Christopherson 	return false;
2514a7800aa8SSean Christopherson }
25155a475554SChao Peng #endif /* CONFIG_KVM_GENERIC_MEMORY_ATTRIBUTES */
25165a475554SChao Peng 
2517a7800aa8SSean Christopherson #ifdef CONFIG_KVM_PRIVATE_MEM
2518a7800aa8SSean Christopherson int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
25191fbee5b0SSean Christopherson 		     gfn_t gfn, kvm_pfn_t *pfn, struct page **page,
25201fbee5b0SSean Christopherson 		     int *max_order);
2521a7800aa8SSean Christopherson #else
kvm_gmem_get_pfn(struct kvm * kvm,struct kvm_memory_slot * slot,gfn_t gfn,kvm_pfn_t * pfn,struct page ** page,int * max_order)2522a7800aa8SSean Christopherson static inline int kvm_gmem_get_pfn(struct kvm *kvm,
2523a7800aa8SSean Christopherson 				   struct kvm_memory_slot *slot, gfn_t gfn,
25241fbee5b0SSean Christopherson 				   kvm_pfn_t *pfn, struct page **page,
25251fbee5b0SSean Christopherson 				   int *max_order)
2526a7800aa8SSean Christopherson {
2527a7800aa8SSean Christopherson 	KVM_BUG_ON(1, kvm);
2528a7800aa8SSean Christopherson 	return -EIO;
2529a7800aa8SSean Christopherson }
2530a7800aa8SSean Christopherson #endif /* CONFIG_KVM_PRIVATE_MEM */
2531a7800aa8SSean Christopherson 
2532564429a6SPaolo Bonzini #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_PREPARE
25333bb2531eSPaolo Bonzini int kvm_arch_gmem_prepare(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn, int max_order);
25343bb2531eSPaolo Bonzini #endif
25353bb2531eSPaolo Bonzini 
2536e4ee5447SPaolo Bonzini #ifdef CONFIG_KVM_GENERIC_PRIVATE_MEM
25371f6c06b1SPaolo Bonzini /**
25381f6c06b1SPaolo Bonzini  * kvm_gmem_populate() - Populate/prepare a GPA range with guest data
25391f6c06b1SPaolo Bonzini  *
25401f6c06b1SPaolo Bonzini  * @kvm: KVM instance
25411f6c06b1SPaolo Bonzini  * @gfn: starting GFN to be populated
25421f6c06b1SPaolo Bonzini  * @src: userspace-provided buffer containing data to copy into GFN range
25431f6c06b1SPaolo Bonzini  *       (passed to @post_populate, and incremented on each iteration
25441f6c06b1SPaolo Bonzini  *       if not NULL)
25451f6c06b1SPaolo Bonzini  * @npages: number of pages to copy from userspace-buffer
25461f6c06b1SPaolo Bonzini  * @post_populate: callback to issue for each gmem page that backs the GPA
25471f6c06b1SPaolo Bonzini  *                 range
25481f6c06b1SPaolo Bonzini  * @opaque: opaque data to pass to @post_populate callback
25491f6c06b1SPaolo Bonzini  *
25501f6c06b1SPaolo Bonzini  * This is primarily intended for cases where a gmem-backed GPA range needs
25511f6c06b1SPaolo Bonzini  * to be initialized with userspace-provided data prior to being mapped into
25521f6c06b1SPaolo Bonzini  * the guest as a private page. This should be called with the slots->lock
25531f6c06b1SPaolo Bonzini  * held so that caller-enforced invariants regarding the expected memory
25541f6c06b1SPaolo Bonzini  * attributes of the GPA range do not race with KVM_SET_MEMORY_ATTRIBUTES.
25551f6c06b1SPaolo Bonzini  *
25561f6c06b1SPaolo Bonzini  * Returns the number of pages that were populated.
25571f6c06b1SPaolo Bonzini  */
25581f6c06b1SPaolo Bonzini typedef int (*kvm_gmem_populate_cb)(struct kvm *kvm, gfn_t gfn, kvm_pfn_t pfn,
25591f6c06b1SPaolo Bonzini 				    void __user *src, int order, void *opaque);
25601f6c06b1SPaolo Bonzini 
25611f6c06b1SPaolo Bonzini long kvm_gmem_populate(struct kvm *kvm, gfn_t gfn, void __user *src, long npages,
25621f6c06b1SPaolo Bonzini 		       kvm_gmem_populate_cb post_populate, void *opaque);
2563e4ee5447SPaolo Bonzini #endif
25641f6c06b1SPaolo Bonzini 
2565564429a6SPaolo Bonzini #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE
2566a90764f0SMichael Roth void kvm_arch_gmem_invalidate(kvm_pfn_t start, kvm_pfn_t end);
2567a90764f0SMichael Roth #endif
2568a90764f0SMichael Roth 
2569bc1a5cd0SIsaku Yamahata #ifdef CONFIG_KVM_GENERIC_PRE_FAULT_MEMORY
2570bc1a5cd0SIsaku Yamahata long kvm_arch_vcpu_pre_fault_memory(struct kvm_vcpu *vcpu,
2571bc1a5cd0SIsaku Yamahata 				    struct kvm_pre_fault_memory *range);
2572bc1a5cd0SIsaku Yamahata #endif
2573bc1a5cd0SIsaku Yamahata 
2574bfd99ff5SAvi Kivity #endif
2575