xref: /linux-6.15/include/linux/kvm_host.h (revision 7f2b47f2)
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 #ifndef __KVM_HOST_H
3 #define __KVM_HOST_H
4 
5 
6 #include <linux/types.h>
7 #include <linux/hardirq.h>
8 #include <linux/list.h>
9 #include <linux/mutex.h>
10 #include <linux/spinlock.h>
11 #include <linux/signal.h>
12 #include <linux/sched.h>
13 #include <linux/sched/stat.h>
14 #include <linux/bug.h>
15 #include <linux/minmax.h>
16 #include <linux/mm.h>
17 #include <linux/mmu_notifier.h>
18 #include <linux/preempt.h>
19 #include <linux/msi.h>
20 #include <linux/slab.h>
21 #include <linux/vmalloc.h>
22 #include <linux/rcupdate.h>
23 #include <linux/ratelimit.h>
24 #include <linux/err.h>
25 #include <linux/irqflags.h>
26 #include <linux/context_tracking.h>
27 #include <linux/irqbypass.h>
28 #include <linux/rcuwait.h>
29 #include <linux/refcount.h>
30 #include <linux/nospec.h>
31 #include <linux/notifier.h>
32 #include <linux/ftrace.h>
33 #include <linux/hashtable.h>
34 #include <linux/instrumentation.h>
35 #include <linux/interval_tree.h>
36 #include <linux/rbtree.h>
37 #include <linux/xarray.h>
38 #include <asm/signal.h>
39 
40 #include <linux/kvm.h>
41 #include <linux/kvm_para.h>
42 
43 #include <linux/kvm_types.h>
44 
45 #include <asm/kvm_host.h>
46 #include <linux/kvm_dirty_ring.h>
47 
48 #ifndef KVM_MAX_VCPU_IDS
49 #define KVM_MAX_VCPU_IDS KVM_MAX_VCPUS
50 #endif
51 
52 /*
53  * The bit 16 ~ bit 31 of kvm_userspace_memory_region::flags are internally
54  * used in kvm, other bits are visible for userspace which are defined in
55  * include/linux/kvm_h.
56  */
57 #define KVM_MEMSLOT_INVALID	(1UL << 16)
58 
59 /*
60  * Bit 63 of the memslot generation number is an "update in-progress flag",
61  * e.g. is temporarily set for the duration of install_new_memslots().
62  * This flag effectively creates a unique generation number that is used to
63  * mark cached memslot data, e.g. MMIO accesses, as potentially being stale,
64  * i.e. may (or may not) have come from the previous memslots generation.
65  *
66  * This is necessary because the actual memslots update is not atomic with
67  * respect to the generation number update.  Updating the generation number
68  * first would allow a vCPU to cache a spte from the old memslots using the
69  * new generation number, and updating the generation number after switching
70  * to the new memslots would allow cache hits using the old generation number
71  * to reference the defunct memslots.
72  *
73  * This mechanism is used to prevent getting hits in KVM's caches while a
74  * memslot update is in-progress, and to prevent cache hits *after* updating
75  * the actual generation number against accesses that were inserted into the
76  * cache *before* the memslots were updated.
77  */
78 #define KVM_MEMSLOT_GEN_UPDATE_IN_PROGRESS	BIT_ULL(63)
79 
80 /* Two fragments for cross MMIO pages. */
81 #define KVM_MAX_MMIO_FRAGMENTS	2
82 
83 #ifndef KVM_ADDRESS_SPACE_NUM
84 #define KVM_ADDRESS_SPACE_NUM	1
85 #endif
86 
87 /*
88  * For the normal pfn, the highest 12 bits should be zero,
89  * so we can mask bit 62 ~ bit 52  to indicate the error pfn,
90  * mask bit 63 to indicate the noslot pfn.
91  */
92 #define KVM_PFN_ERR_MASK	(0x7ffULL << 52)
93 #define KVM_PFN_ERR_NOSLOT_MASK	(0xfffULL << 52)
94 #define KVM_PFN_NOSLOT		(0x1ULL << 63)
95 
96 #define KVM_PFN_ERR_FAULT	(KVM_PFN_ERR_MASK)
97 #define KVM_PFN_ERR_HWPOISON	(KVM_PFN_ERR_MASK + 1)
98 #define KVM_PFN_ERR_RO_FAULT	(KVM_PFN_ERR_MASK + 2)
99 #define KVM_PFN_ERR_SIGPENDING	(KVM_PFN_ERR_MASK + 3)
100 
101 /*
102  * error pfns indicate that the gfn is in slot but faild to
103  * translate it to pfn on host.
104  */
105 static inline bool is_error_pfn(kvm_pfn_t pfn)
106 {
107 	return !!(pfn & KVM_PFN_ERR_MASK);
108 }
109 
110 /*
111  * KVM_PFN_ERR_SIGPENDING indicates that fetching the PFN was interrupted
112  * by a pending signal.  Note, the signal may or may not be fatal.
113  */
114 static inline bool is_sigpending_pfn(kvm_pfn_t pfn)
115 {
116 	return pfn == KVM_PFN_ERR_SIGPENDING;
117 }
118 
119 /*
120  * error_noslot pfns indicate that the gfn can not be
121  * translated to pfn - it is not in slot or failed to
122  * translate it to pfn.
123  */
124 static inline bool is_error_noslot_pfn(kvm_pfn_t pfn)
125 {
126 	return !!(pfn & KVM_PFN_ERR_NOSLOT_MASK);
127 }
128 
129 /* noslot pfn indicates that the gfn is not in slot. */
130 static inline bool is_noslot_pfn(kvm_pfn_t pfn)
131 {
132 	return pfn == KVM_PFN_NOSLOT;
133 }
134 
135 /*
136  * architectures with KVM_HVA_ERR_BAD other than PAGE_OFFSET (e.g. s390)
137  * provide own defines and kvm_is_error_hva
138  */
139 #ifndef KVM_HVA_ERR_BAD
140 
141 #define KVM_HVA_ERR_BAD		(PAGE_OFFSET)
142 #define KVM_HVA_ERR_RO_BAD	(PAGE_OFFSET + PAGE_SIZE)
143 
144 static inline bool kvm_is_error_hva(unsigned long addr)
145 {
146 	return addr >= PAGE_OFFSET;
147 }
148 
149 #endif
150 
151 #define KVM_ERR_PTR_BAD_PAGE	(ERR_PTR(-ENOENT))
152 
153 static inline bool is_error_page(struct page *page)
154 {
155 	return IS_ERR(page);
156 }
157 
158 #define KVM_REQUEST_MASK           GENMASK(7,0)
159 #define KVM_REQUEST_NO_WAKEUP      BIT(8)
160 #define KVM_REQUEST_WAIT           BIT(9)
161 #define KVM_REQUEST_NO_ACTION      BIT(10)
162 /*
163  * Architecture-independent vcpu->requests bit members
164  * Bits 3-7 are reserved for more arch-independent bits.
165  */
166 #define KVM_REQ_TLB_FLUSH         (0 | KVM_REQUEST_WAIT | KVM_REQUEST_NO_WAKEUP)
167 #define KVM_REQ_VM_DEAD           (1 | KVM_REQUEST_WAIT | KVM_REQUEST_NO_WAKEUP)
168 #define KVM_REQ_UNBLOCK           2
169 #define KVM_REQUEST_ARCH_BASE     8
170 
171 /*
172  * KVM_REQ_OUTSIDE_GUEST_MODE exists is purely as way to force the vCPU to
173  * OUTSIDE_GUEST_MODE.  KVM_REQ_OUTSIDE_GUEST_MODE differs from a vCPU "kick"
174  * in that it ensures the vCPU has reached OUTSIDE_GUEST_MODE before continuing
175  * on.  A kick only guarantees that the vCPU is on its way out, e.g. a previous
176  * kick may have set vcpu->mode to EXITING_GUEST_MODE, and so there's no
177  * guarantee the vCPU received an IPI and has actually exited guest mode.
178  */
179 #define KVM_REQ_OUTSIDE_GUEST_MODE	(KVM_REQUEST_NO_ACTION | KVM_REQUEST_WAIT | KVM_REQUEST_NO_WAKEUP)
180 
181 #define KVM_ARCH_REQ_FLAGS(nr, flags) ({ \
182 	BUILD_BUG_ON((unsigned)(nr) >= (sizeof_field(struct kvm_vcpu, requests) * 8) - KVM_REQUEST_ARCH_BASE); \
183 	(unsigned)(((nr) + KVM_REQUEST_ARCH_BASE) | (flags)); \
184 })
185 #define KVM_ARCH_REQ(nr)           KVM_ARCH_REQ_FLAGS(nr, 0)
186 
187 bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
188 				 unsigned long *vcpu_bitmap);
189 bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req);
190 bool kvm_make_all_cpus_request_except(struct kvm *kvm, unsigned int req,
191 				      struct kvm_vcpu *except);
192 bool kvm_make_cpus_request_mask(struct kvm *kvm, unsigned int req,
193 				unsigned long *vcpu_bitmap);
194 
195 #define KVM_USERSPACE_IRQ_SOURCE_ID		0
196 #define KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID	1
197 
198 extern struct mutex kvm_lock;
199 extern struct list_head vm_list;
200 
201 struct kvm_io_range {
202 	gpa_t addr;
203 	int len;
204 	struct kvm_io_device *dev;
205 };
206 
207 #define NR_IOBUS_DEVS 1000
208 
209 struct kvm_io_bus {
210 	int dev_count;
211 	int ioeventfd_count;
212 	struct kvm_io_range range[];
213 };
214 
215 enum kvm_bus {
216 	KVM_MMIO_BUS,
217 	KVM_PIO_BUS,
218 	KVM_VIRTIO_CCW_NOTIFY_BUS,
219 	KVM_FAST_MMIO_BUS,
220 	KVM_NR_BUSES
221 };
222 
223 int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
224 		     int len, const void *val);
225 int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
226 			    gpa_t addr, int len, const void *val, long cookie);
227 int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
228 		    int len, void *val);
229 int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
230 			    int len, struct kvm_io_device *dev);
231 int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
232 			      struct kvm_io_device *dev);
233 struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
234 					 gpa_t addr);
235 
236 #ifdef CONFIG_KVM_ASYNC_PF
237 struct kvm_async_pf {
238 	struct work_struct work;
239 	struct list_head link;
240 	struct list_head queue;
241 	struct kvm_vcpu *vcpu;
242 	struct mm_struct *mm;
243 	gpa_t cr2_or_gpa;
244 	unsigned long addr;
245 	struct kvm_arch_async_pf arch;
246 	bool   wakeup_all;
247 	bool notpresent_injected;
248 };
249 
250 void kvm_clear_async_pf_completion_queue(struct kvm_vcpu *vcpu);
251 void kvm_check_async_pf_completion(struct kvm_vcpu *vcpu);
252 bool kvm_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
253 			unsigned long hva, struct kvm_arch_async_pf *arch);
254 int kvm_async_pf_wakeup_all(struct kvm_vcpu *vcpu);
255 #endif
256 
257 #ifdef KVM_ARCH_WANT_MMU_NOTIFIER
258 struct kvm_gfn_range {
259 	struct kvm_memory_slot *slot;
260 	gfn_t start;
261 	gfn_t end;
262 	pte_t pte;
263 	bool may_block;
264 };
265 bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range);
266 bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range);
267 bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range);
268 bool kvm_set_spte_gfn(struct kvm *kvm, struct kvm_gfn_range *range);
269 #endif
270 
271 enum {
272 	OUTSIDE_GUEST_MODE,
273 	IN_GUEST_MODE,
274 	EXITING_GUEST_MODE,
275 	READING_SHADOW_PAGE_TABLES,
276 };
277 
278 #define KVM_UNMAPPED_PAGE	((void *) 0x500 + POISON_POINTER_DELTA)
279 
280 struct kvm_host_map {
281 	/*
282 	 * Only valid if the 'pfn' is managed by the host kernel (i.e. There is
283 	 * a 'struct page' for it. When using mem= kernel parameter some memory
284 	 * can be used as guest memory but they are not managed by host
285 	 * kernel).
286 	 * If 'pfn' is not managed by the host kernel, this field is
287 	 * initialized to KVM_UNMAPPED_PAGE.
288 	 */
289 	struct page *page;
290 	void *hva;
291 	kvm_pfn_t pfn;
292 	kvm_pfn_t gfn;
293 };
294 
295 /*
296  * Used to check if the mapping is valid or not. Never use 'kvm_host_map'
297  * directly to check for that.
298  */
299 static inline bool kvm_vcpu_mapped(struct kvm_host_map *map)
300 {
301 	return !!map->hva;
302 }
303 
304 static inline bool kvm_vcpu_can_poll(ktime_t cur, ktime_t stop)
305 {
306 	return single_task_running() && !need_resched() && ktime_before(cur, stop);
307 }
308 
309 /*
310  * Sometimes a large or cross-page mmio needs to be broken up into separate
311  * exits for userspace servicing.
312  */
313 struct kvm_mmio_fragment {
314 	gpa_t gpa;
315 	void *data;
316 	unsigned len;
317 };
318 
319 struct kvm_vcpu {
320 	struct kvm *kvm;
321 #ifdef CONFIG_PREEMPT_NOTIFIERS
322 	struct preempt_notifier preempt_notifier;
323 #endif
324 	int cpu;
325 	int vcpu_id; /* id given by userspace at creation */
326 	int vcpu_idx; /* index in kvm->vcpus array */
327 	int ____srcu_idx; /* Don't use this directly.  You've been warned. */
328 #ifdef CONFIG_PROVE_RCU
329 	int srcu_depth;
330 #endif
331 	int mode;
332 	u64 requests;
333 	unsigned long guest_debug;
334 
335 	struct mutex mutex;
336 	struct kvm_run *run;
337 
338 #ifndef __KVM_HAVE_ARCH_WQP
339 	struct rcuwait wait;
340 #endif
341 	struct pid __rcu *pid;
342 	int sigset_active;
343 	sigset_t sigset;
344 	unsigned int halt_poll_ns;
345 	bool valid_wakeup;
346 
347 #ifdef CONFIG_HAS_IOMEM
348 	int mmio_needed;
349 	int mmio_read_completed;
350 	int mmio_is_write;
351 	int mmio_cur_fragment;
352 	int mmio_nr_fragments;
353 	struct kvm_mmio_fragment mmio_fragments[KVM_MAX_MMIO_FRAGMENTS];
354 #endif
355 
356 #ifdef CONFIG_KVM_ASYNC_PF
357 	struct {
358 		u32 queued;
359 		struct list_head queue;
360 		struct list_head done;
361 		spinlock_t lock;
362 	} async_pf;
363 #endif
364 
365 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
366 	/*
367 	 * Cpu relax intercept or pause loop exit optimization
368 	 * in_spin_loop: set when a vcpu does a pause loop exit
369 	 *  or cpu relax intercepted.
370 	 * dy_eligible: indicates whether vcpu is eligible for directed yield.
371 	 */
372 	struct {
373 		bool in_spin_loop;
374 		bool dy_eligible;
375 	} spin_loop;
376 #endif
377 	bool preempted;
378 	bool ready;
379 	struct kvm_vcpu_arch arch;
380 	struct kvm_vcpu_stat stat;
381 	char stats_id[KVM_STATS_NAME_SIZE];
382 	struct kvm_dirty_ring dirty_ring;
383 
384 	/*
385 	 * The most recently used memslot by this vCPU and the slots generation
386 	 * for which it is valid.
387 	 * No wraparound protection is needed since generations won't overflow in
388 	 * thousands of years, even assuming 1M memslot operations per second.
389 	 */
390 	struct kvm_memory_slot *last_used_slot;
391 	u64 last_used_slot_gen;
392 };
393 
394 /*
395  * Start accounting time towards a guest.
396  * Must be called before entering guest context.
397  */
398 static __always_inline void guest_timing_enter_irqoff(void)
399 {
400 	/*
401 	 * This is running in ioctl context so its safe to assume that it's the
402 	 * stime pending cputime to flush.
403 	 */
404 	instrumentation_begin();
405 	vtime_account_guest_enter();
406 	instrumentation_end();
407 }
408 
409 /*
410  * Enter guest context and enter an RCU extended quiescent state.
411  *
412  * Between guest_context_enter_irqoff() and guest_context_exit_irqoff() it is
413  * unsafe to use any code which may directly or indirectly use RCU, tracing
414  * (including IRQ flag tracing), or lockdep. All code in this period must be
415  * non-instrumentable.
416  */
417 static __always_inline void guest_context_enter_irqoff(void)
418 {
419 	/*
420 	 * KVM does not hold any references to rcu protected data when it
421 	 * switches CPU into a guest mode. In fact switching to a guest mode
422 	 * is very similar to exiting to userspace from rcu point of view. In
423 	 * addition CPU may stay in a guest mode for quite a long time (up to
424 	 * one time slice). Lets treat guest mode as quiescent state, just like
425 	 * we do with user-mode execution.
426 	 */
427 	if (!context_tracking_guest_enter()) {
428 		instrumentation_begin();
429 		rcu_virt_note_context_switch(smp_processor_id());
430 		instrumentation_end();
431 	}
432 }
433 
434 /*
435  * Deprecated. Architectures should move to guest_timing_enter_irqoff() and
436  * guest_state_enter_irqoff().
437  */
438 static __always_inline void guest_enter_irqoff(void)
439 {
440 	guest_timing_enter_irqoff();
441 	guest_context_enter_irqoff();
442 }
443 
444 /**
445  * guest_state_enter_irqoff - Fixup state when entering a guest
446  *
447  * Entry to a guest will enable interrupts, but the kernel state is interrupts
448  * disabled when this is invoked. Also tell RCU about it.
449  *
450  * 1) Trace interrupts on state
451  * 2) Invoke context tracking if enabled to adjust RCU state
452  * 3) Tell lockdep that interrupts are enabled
453  *
454  * Invoked from architecture specific code before entering a guest.
455  * Must be called with interrupts disabled and the caller must be
456  * non-instrumentable.
457  * The caller has to invoke guest_timing_enter_irqoff() before this.
458  *
459  * Note: this is analogous to exit_to_user_mode().
460  */
461 static __always_inline void guest_state_enter_irqoff(void)
462 {
463 	instrumentation_begin();
464 	trace_hardirqs_on_prepare();
465 	lockdep_hardirqs_on_prepare();
466 	instrumentation_end();
467 
468 	guest_context_enter_irqoff();
469 	lockdep_hardirqs_on(CALLER_ADDR0);
470 }
471 
472 /*
473  * Exit guest context and exit an RCU extended quiescent state.
474  *
475  * Between guest_context_enter_irqoff() and guest_context_exit_irqoff() it is
476  * unsafe to use any code which may directly or indirectly use RCU, tracing
477  * (including IRQ flag tracing), or lockdep. All code in this period must be
478  * non-instrumentable.
479  */
480 static __always_inline void guest_context_exit_irqoff(void)
481 {
482 	context_tracking_guest_exit();
483 }
484 
485 /*
486  * Stop accounting time towards a guest.
487  * Must be called after exiting guest context.
488  */
489 static __always_inline void guest_timing_exit_irqoff(void)
490 {
491 	instrumentation_begin();
492 	/* Flush the guest cputime we spent on the guest */
493 	vtime_account_guest_exit();
494 	instrumentation_end();
495 }
496 
497 /*
498  * Deprecated. Architectures should move to guest_state_exit_irqoff() and
499  * guest_timing_exit_irqoff().
500  */
501 static __always_inline void guest_exit_irqoff(void)
502 {
503 	guest_context_exit_irqoff();
504 	guest_timing_exit_irqoff();
505 }
506 
507 static inline void guest_exit(void)
508 {
509 	unsigned long flags;
510 
511 	local_irq_save(flags);
512 	guest_exit_irqoff();
513 	local_irq_restore(flags);
514 }
515 
516 /**
517  * guest_state_exit_irqoff - Establish state when returning from guest mode
518  *
519  * Entry from a guest disables interrupts, but guest mode is traced as
520  * interrupts enabled. Also with NO_HZ_FULL RCU might be idle.
521  *
522  * 1) Tell lockdep that interrupts are disabled
523  * 2) Invoke context tracking if enabled to reactivate RCU
524  * 3) Trace interrupts off state
525  *
526  * Invoked from architecture specific code after exiting a guest.
527  * Must be invoked with interrupts disabled and the caller must be
528  * non-instrumentable.
529  * The caller has to invoke guest_timing_exit_irqoff() after this.
530  *
531  * Note: this is analogous to enter_from_user_mode().
532  */
533 static __always_inline void guest_state_exit_irqoff(void)
534 {
535 	lockdep_hardirqs_off(CALLER_ADDR0);
536 	guest_context_exit_irqoff();
537 
538 	instrumentation_begin();
539 	trace_hardirqs_off_finish();
540 	instrumentation_end();
541 }
542 
543 static inline int kvm_vcpu_exiting_guest_mode(struct kvm_vcpu *vcpu)
544 {
545 	/*
546 	 * The memory barrier ensures a previous write to vcpu->requests cannot
547 	 * be reordered with the read of vcpu->mode.  It pairs with the general
548 	 * memory barrier following the write of vcpu->mode in VCPU RUN.
549 	 */
550 	smp_mb__before_atomic();
551 	return cmpxchg(&vcpu->mode, IN_GUEST_MODE, EXITING_GUEST_MODE);
552 }
553 
554 /*
555  * Some of the bitops functions do not support too long bitmaps.
556  * This number must be determined not to exceed such limits.
557  */
558 #define KVM_MEM_MAX_NR_PAGES ((1UL << 31) - 1)
559 
560 /*
561  * Since at idle each memslot belongs to two memslot sets it has to contain
562  * two embedded nodes for each data structure that it forms a part of.
563  *
564  * Two memslot sets (one active and one inactive) are necessary so the VM
565  * continues to run on one memslot set while the other is being modified.
566  *
567  * These two memslot sets normally point to the same set of memslots.
568  * They can, however, be desynchronized when performing a memslot management
569  * operation by replacing the memslot to be modified by its copy.
570  * After the operation is complete, both memslot sets once again point to
571  * the same, common set of memslot data.
572  *
573  * The memslots themselves are independent of each other so they can be
574  * individually added or deleted.
575  */
576 struct kvm_memory_slot {
577 	struct hlist_node id_node[2];
578 	struct interval_tree_node hva_node[2];
579 	struct rb_node gfn_node[2];
580 	gfn_t base_gfn;
581 	unsigned long npages;
582 	unsigned long *dirty_bitmap;
583 	struct kvm_arch_memory_slot arch;
584 	unsigned long userspace_addr;
585 	u32 flags;
586 	short id;
587 	u16 as_id;
588 };
589 
590 static inline bool kvm_slot_dirty_track_enabled(const struct kvm_memory_slot *slot)
591 {
592 	return slot->flags & KVM_MEM_LOG_DIRTY_PAGES;
593 }
594 
595 static inline unsigned long kvm_dirty_bitmap_bytes(struct kvm_memory_slot *memslot)
596 {
597 	return ALIGN(memslot->npages, BITS_PER_LONG) / 8;
598 }
599 
600 static inline unsigned long *kvm_second_dirty_bitmap(struct kvm_memory_slot *memslot)
601 {
602 	unsigned long len = kvm_dirty_bitmap_bytes(memslot);
603 
604 	return memslot->dirty_bitmap + len / sizeof(*memslot->dirty_bitmap);
605 }
606 
607 #ifndef KVM_DIRTY_LOG_MANUAL_CAPS
608 #define KVM_DIRTY_LOG_MANUAL_CAPS KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE
609 #endif
610 
611 struct kvm_s390_adapter_int {
612 	u64 ind_addr;
613 	u64 summary_addr;
614 	u64 ind_offset;
615 	u32 summary_offset;
616 	u32 adapter_id;
617 };
618 
619 struct kvm_hv_sint {
620 	u32 vcpu;
621 	u32 sint;
622 };
623 
624 struct kvm_xen_evtchn {
625 	u32 port;
626 	u32 vcpu_id;
627 	int vcpu_idx;
628 	u32 priority;
629 };
630 
631 struct kvm_kernel_irq_routing_entry {
632 	u32 gsi;
633 	u32 type;
634 	int (*set)(struct kvm_kernel_irq_routing_entry *e,
635 		   struct kvm *kvm, int irq_source_id, int level,
636 		   bool line_status);
637 	union {
638 		struct {
639 			unsigned irqchip;
640 			unsigned pin;
641 		} irqchip;
642 		struct {
643 			u32 address_lo;
644 			u32 address_hi;
645 			u32 data;
646 			u32 flags;
647 			u32 devid;
648 		} msi;
649 		struct kvm_s390_adapter_int adapter;
650 		struct kvm_hv_sint hv_sint;
651 		struct kvm_xen_evtchn xen_evtchn;
652 	};
653 	struct hlist_node link;
654 };
655 
656 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
657 struct kvm_irq_routing_table {
658 	int chip[KVM_NR_IRQCHIPS][KVM_IRQCHIP_NUM_PINS];
659 	u32 nr_rt_entries;
660 	/*
661 	 * Array indexed by gsi. Each entry contains list of irq chips
662 	 * the gsi is connected to.
663 	 */
664 	struct hlist_head map[];
665 };
666 #endif
667 
668 bool kvm_arch_irqchip_in_kernel(struct kvm *kvm);
669 
670 #ifndef KVM_INTERNAL_MEM_SLOTS
671 #define KVM_INTERNAL_MEM_SLOTS 0
672 #endif
673 
674 #define KVM_MEM_SLOTS_NUM SHRT_MAX
675 #define KVM_USER_MEM_SLOTS (KVM_MEM_SLOTS_NUM - KVM_INTERNAL_MEM_SLOTS)
676 
677 #ifndef __KVM_VCPU_MULTIPLE_ADDRESS_SPACE
678 static inline int kvm_arch_vcpu_memslots_id(struct kvm_vcpu *vcpu)
679 {
680 	return 0;
681 }
682 #endif
683 
684 struct kvm_memslots {
685 	u64 generation;
686 	atomic_long_t last_used_slot;
687 	struct rb_root_cached hva_tree;
688 	struct rb_root gfn_tree;
689 	/*
690 	 * The mapping table from slot id to memslot.
691 	 *
692 	 * 7-bit bucket count matches the size of the old id to index array for
693 	 * 512 slots, while giving good performance with this slot count.
694 	 * Higher bucket counts bring only small performance improvements but
695 	 * always result in higher memory usage (even for lower memslot counts).
696 	 */
697 	DECLARE_HASHTABLE(id_hash, 7);
698 	int node_idx;
699 };
700 
701 struct kvm {
702 #ifdef KVM_HAVE_MMU_RWLOCK
703 	rwlock_t mmu_lock;
704 #else
705 	spinlock_t mmu_lock;
706 #endif /* KVM_HAVE_MMU_RWLOCK */
707 
708 	struct mutex slots_lock;
709 
710 	/*
711 	 * Protects the arch-specific fields of struct kvm_memory_slots in
712 	 * use by the VM. To be used under the slots_lock (above) or in a
713 	 * kvm->srcu critical section where acquiring the slots_lock would
714 	 * lead to deadlock with the synchronize_srcu in
715 	 * install_new_memslots.
716 	 */
717 	struct mutex slots_arch_lock;
718 	struct mm_struct *mm; /* userspace tied to this vm */
719 	unsigned long nr_memslot_pages;
720 	/* The two memslot sets - active and inactive (per address space) */
721 	struct kvm_memslots __memslots[KVM_ADDRESS_SPACE_NUM][2];
722 	/* The current active memslot set for each address space */
723 	struct kvm_memslots __rcu *memslots[KVM_ADDRESS_SPACE_NUM];
724 	struct xarray vcpu_array;
725 	/*
726 	 * Protected by slots_lock, but can be read outside if an
727 	 * incorrect answer is acceptable.
728 	 */
729 	atomic_t nr_memslots_dirty_logging;
730 
731 	/* Used to wait for completion of MMU notifiers.  */
732 	spinlock_t mn_invalidate_lock;
733 	unsigned long mn_active_invalidate_count;
734 	struct rcuwait mn_memslots_update_rcuwait;
735 
736 	/* For management / invalidation of gfn_to_pfn_caches */
737 	spinlock_t gpc_lock;
738 	struct list_head gpc_list;
739 
740 	/*
741 	 * created_vcpus is protected by kvm->lock, and is incremented
742 	 * at the beginning of KVM_CREATE_VCPU.  online_vcpus is only
743 	 * incremented after storing the kvm_vcpu pointer in vcpus,
744 	 * and is accessed atomically.
745 	 */
746 	atomic_t online_vcpus;
747 	int max_vcpus;
748 	int created_vcpus;
749 	int last_boosted_vcpu;
750 	struct list_head vm_list;
751 	struct mutex lock;
752 	struct kvm_io_bus __rcu *buses[KVM_NR_BUSES];
753 #ifdef CONFIG_HAVE_KVM_EVENTFD
754 	struct {
755 		spinlock_t        lock;
756 		struct list_head  items;
757 		struct list_head  resampler_list;
758 		struct mutex      resampler_lock;
759 	} irqfds;
760 	struct list_head ioeventfds;
761 #endif
762 	struct kvm_vm_stat stat;
763 	struct kvm_arch arch;
764 	refcount_t users_count;
765 #ifdef CONFIG_KVM_MMIO
766 	struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
767 	spinlock_t ring_lock;
768 	struct list_head coalesced_zones;
769 #endif
770 
771 	struct mutex irq_lock;
772 #ifdef CONFIG_HAVE_KVM_IRQCHIP
773 	/*
774 	 * Update side is protected by irq_lock.
775 	 */
776 	struct kvm_irq_routing_table __rcu *irq_routing;
777 #endif
778 #ifdef CONFIG_HAVE_KVM_IRQFD
779 	struct hlist_head irq_ack_notifier_list;
780 #endif
781 
782 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
783 	struct mmu_notifier mmu_notifier;
784 	unsigned long mmu_invalidate_seq;
785 	long mmu_invalidate_in_progress;
786 	unsigned long mmu_invalidate_range_start;
787 	unsigned long mmu_invalidate_range_end;
788 #endif
789 	struct list_head devices;
790 	u64 manual_dirty_log_protect;
791 	struct dentry *debugfs_dentry;
792 	struct kvm_stat_data **debugfs_stat_data;
793 	struct srcu_struct srcu;
794 	struct srcu_struct irq_srcu;
795 	pid_t userspace_pid;
796 	unsigned int max_halt_poll_ns;
797 	u32 dirty_ring_size;
798 	bool vm_bugged;
799 	bool vm_dead;
800 
801 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
802 	struct notifier_block pm_notifier;
803 #endif
804 	char stats_id[KVM_STATS_NAME_SIZE];
805 };
806 
807 #define kvm_err(fmt, ...) \
808 	pr_err("kvm [%i]: " fmt, task_pid_nr(current), ## __VA_ARGS__)
809 #define kvm_info(fmt, ...) \
810 	pr_info("kvm [%i]: " fmt, task_pid_nr(current), ## __VA_ARGS__)
811 #define kvm_debug(fmt, ...) \
812 	pr_debug("kvm [%i]: " fmt, task_pid_nr(current), ## __VA_ARGS__)
813 #define kvm_debug_ratelimited(fmt, ...) \
814 	pr_debug_ratelimited("kvm [%i]: " fmt, task_pid_nr(current), \
815 			     ## __VA_ARGS__)
816 #define kvm_pr_unimpl(fmt, ...) \
817 	pr_err_ratelimited("kvm [%i]: " fmt, \
818 			   task_tgid_nr(current), ## __VA_ARGS__)
819 
820 /* The guest did something we don't support. */
821 #define vcpu_unimpl(vcpu, fmt, ...)					\
822 	kvm_pr_unimpl("vcpu%i, guest rIP: 0x%lx " fmt,			\
823 			(vcpu)->vcpu_id, kvm_rip_read(vcpu), ## __VA_ARGS__)
824 
825 #define vcpu_debug(vcpu, fmt, ...)					\
826 	kvm_debug("vcpu%i " fmt, (vcpu)->vcpu_id, ## __VA_ARGS__)
827 #define vcpu_debug_ratelimited(vcpu, fmt, ...)				\
828 	kvm_debug_ratelimited("vcpu%i " fmt, (vcpu)->vcpu_id,           \
829 			      ## __VA_ARGS__)
830 #define vcpu_err(vcpu, fmt, ...)					\
831 	kvm_err("vcpu%i " fmt, (vcpu)->vcpu_id, ## __VA_ARGS__)
832 
833 static inline void kvm_vm_dead(struct kvm *kvm)
834 {
835 	kvm->vm_dead = true;
836 	kvm_make_all_cpus_request(kvm, KVM_REQ_VM_DEAD);
837 }
838 
839 static inline void kvm_vm_bugged(struct kvm *kvm)
840 {
841 	kvm->vm_bugged = true;
842 	kvm_vm_dead(kvm);
843 }
844 
845 
846 #define KVM_BUG(cond, kvm, fmt...)				\
847 ({								\
848 	int __ret = (cond);					\
849 								\
850 	if (WARN_ONCE(__ret && !(kvm)->vm_bugged, fmt))		\
851 		kvm_vm_bugged(kvm);				\
852 	unlikely(__ret);					\
853 })
854 
855 #define KVM_BUG_ON(cond, kvm)					\
856 ({								\
857 	int __ret = (cond);					\
858 								\
859 	if (WARN_ON_ONCE(__ret && !(kvm)->vm_bugged))		\
860 		kvm_vm_bugged(kvm);				\
861 	unlikely(__ret);					\
862 })
863 
864 static inline void kvm_vcpu_srcu_read_lock(struct kvm_vcpu *vcpu)
865 {
866 #ifdef CONFIG_PROVE_RCU
867 	WARN_ONCE(vcpu->srcu_depth++,
868 		  "KVM: Illegal vCPU srcu_idx LOCK, depth=%d", vcpu->srcu_depth - 1);
869 #endif
870 	vcpu->____srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
871 }
872 
873 static inline void kvm_vcpu_srcu_read_unlock(struct kvm_vcpu *vcpu)
874 {
875 	srcu_read_unlock(&vcpu->kvm->srcu, vcpu->____srcu_idx);
876 
877 #ifdef CONFIG_PROVE_RCU
878 	WARN_ONCE(--vcpu->srcu_depth,
879 		  "KVM: Illegal vCPU srcu_idx UNLOCK, depth=%d", vcpu->srcu_depth);
880 #endif
881 }
882 
883 static inline bool kvm_dirty_log_manual_protect_and_init_set(struct kvm *kvm)
884 {
885 	return !!(kvm->manual_dirty_log_protect & KVM_DIRTY_LOG_INITIALLY_SET);
886 }
887 
888 static inline struct kvm_io_bus *kvm_get_bus(struct kvm *kvm, enum kvm_bus idx)
889 {
890 	return srcu_dereference_check(kvm->buses[idx], &kvm->srcu,
891 				      lockdep_is_held(&kvm->slots_lock) ||
892 				      !refcount_read(&kvm->users_count));
893 }
894 
895 static inline struct kvm_vcpu *kvm_get_vcpu(struct kvm *kvm, int i)
896 {
897 	int num_vcpus = atomic_read(&kvm->online_vcpus);
898 	i = array_index_nospec(i, num_vcpus);
899 
900 	/* Pairs with smp_wmb() in kvm_vm_ioctl_create_vcpu.  */
901 	smp_rmb();
902 	return xa_load(&kvm->vcpu_array, i);
903 }
904 
905 #define kvm_for_each_vcpu(idx, vcpup, kvm)		   \
906 	xa_for_each_range(&kvm->vcpu_array, idx, vcpup, 0, \
907 			  (atomic_read(&kvm->online_vcpus) - 1))
908 
909 static inline struct kvm_vcpu *kvm_get_vcpu_by_id(struct kvm *kvm, int id)
910 {
911 	struct kvm_vcpu *vcpu = NULL;
912 	unsigned long i;
913 
914 	if (id < 0)
915 		return NULL;
916 	if (id < KVM_MAX_VCPUS)
917 		vcpu = kvm_get_vcpu(kvm, id);
918 	if (vcpu && vcpu->vcpu_id == id)
919 		return vcpu;
920 	kvm_for_each_vcpu(i, vcpu, kvm)
921 		if (vcpu->vcpu_id == id)
922 			return vcpu;
923 	return NULL;
924 }
925 
926 void kvm_destroy_vcpus(struct kvm *kvm);
927 
928 void vcpu_load(struct kvm_vcpu *vcpu);
929 void vcpu_put(struct kvm_vcpu *vcpu);
930 
931 #ifdef __KVM_HAVE_IOAPIC
932 void kvm_arch_post_irq_ack_notifier_list_update(struct kvm *kvm);
933 void kvm_arch_post_irq_routing_update(struct kvm *kvm);
934 #else
935 static inline void kvm_arch_post_irq_ack_notifier_list_update(struct kvm *kvm)
936 {
937 }
938 static inline void kvm_arch_post_irq_routing_update(struct kvm *kvm)
939 {
940 }
941 #endif
942 
943 #ifdef CONFIG_HAVE_KVM_IRQFD
944 int kvm_irqfd_init(void);
945 void kvm_irqfd_exit(void);
946 #else
947 static inline int kvm_irqfd_init(void)
948 {
949 	return 0;
950 }
951 
952 static inline void kvm_irqfd_exit(void)
953 {
954 }
955 #endif
956 int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
957 		  struct module *module);
958 void kvm_exit(void);
959 
960 void kvm_get_kvm(struct kvm *kvm);
961 bool kvm_get_kvm_safe(struct kvm *kvm);
962 void kvm_put_kvm(struct kvm *kvm);
963 bool file_is_kvm(struct file *file);
964 void kvm_put_kvm_no_destroy(struct kvm *kvm);
965 
966 static inline struct kvm_memslots *__kvm_memslots(struct kvm *kvm, int as_id)
967 {
968 	as_id = array_index_nospec(as_id, KVM_ADDRESS_SPACE_NUM);
969 	return srcu_dereference_check(kvm->memslots[as_id], &kvm->srcu,
970 			lockdep_is_held(&kvm->slots_lock) ||
971 			!refcount_read(&kvm->users_count));
972 }
973 
974 static inline struct kvm_memslots *kvm_memslots(struct kvm *kvm)
975 {
976 	return __kvm_memslots(kvm, 0);
977 }
978 
979 static inline struct kvm_memslots *kvm_vcpu_memslots(struct kvm_vcpu *vcpu)
980 {
981 	int as_id = kvm_arch_vcpu_memslots_id(vcpu);
982 
983 	return __kvm_memslots(vcpu->kvm, as_id);
984 }
985 
986 static inline bool kvm_memslots_empty(struct kvm_memslots *slots)
987 {
988 	return RB_EMPTY_ROOT(&slots->gfn_tree);
989 }
990 
991 #define kvm_for_each_memslot(memslot, bkt, slots)			      \
992 	hash_for_each(slots->id_hash, bkt, memslot, id_node[slots->node_idx]) \
993 		if (WARN_ON_ONCE(!memslot->npages)) {			      \
994 		} else
995 
996 static inline
997 struct kvm_memory_slot *id_to_memslot(struct kvm_memslots *slots, int id)
998 {
999 	struct kvm_memory_slot *slot;
1000 	int idx = slots->node_idx;
1001 
1002 	hash_for_each_possible(slots->id_hash, slot, id_node[idx], id) {
1003 		if (slot->id == id)
1004 			return slot;
1005 	}
1006 
1007 	return NULL;
1008 }
1009 
1010 /* Iterator used for walking memslots that overlap a gfn range. */
1011 struct kvm_memslot_iter {
1012 	struct kvm_memslots *slots;
1013 	struct rb_node *node;
1014 	struct kvm_memory_slot *slot;
1015 };
1016 
1017 static inline void kvm_memslot_iter_next(struct kvm_memslot_iter *iter)
1018 {
1019 	iter->node = rb_next(iter->node);
1020 	if (!iter->node)
1021 		return;
1022 
1023 	iter->slot = container_of(iter->node, struct kvm_memory_slot, gfn_node[iter->slots->node_idx]);
1024 }
1025 
1026 static inline void kvm_memslot_iter_start(struct kvm_memslot_iter *iter,
1027 					  struct kvm_memslots *slots,
1028 					  gfn_t start)
1029 {
1030 	int idx = slots->node_idx;
1031 	struct rb_node *tmp;
1032 	struct kvm_memory_slot *slot;
1033 
1034 	iter->slots = slots;
1035 
1036 	/*
1037 	 * Find the so called "upper bound" of a key - the first node that has
1038 	 * its key strictly greater than the searched one (the start gfn in our case).
1039 	 */
1040 	iter->node = NULL;
1041 	for (tmp = slots->gfn_tree.rb_node; tmp; ) {
1042 		slot = container_of(tmp, struct kvm_memory_slot, gfn_node[idx]);
1043 		if (start < slot->base_gfn) {
1044 			iter->node = tmp;
1045 			tmp = tmp->rb_left;
1046 		} else {
1047 			tmp = tmp->rb_right;
1048 		}
1049 	}
1050 
1051 	/*
1052 	 * Find the slot with the lowest gfn that can possibly intersect with
1053 	 * the range, so we'll ideally have slot start <= range start
1054 	 */
1055 	if (iter->node) {
1056 		/*
1057 		 * A NULL previous node means that the very first slot
1058 		 * already has a higher start gfn.
1059 		 * In this case slot start > range start.
1060 		 */
1061 		tmp = rb_prev(iter->node);
1062 		if (tmp)
1063 			iter->node = tmp;
1064 	} else {
1065 		/* a NULL node below means no slots */
1066 		iter->node = rb_last(&slots->gfn_tree);
1067 	}
1068 
1069 	if (iter->node) {
1070 		iter->slot = container_of(iter->node, struct kvm_memory_slot, gfn_node[idx]);
1071 
1072 		/*
1073 		 * It is possible in the slot start < range start case that the
1074 		 * found slot ends before or at range start (slot end <= range start)
1075 		 * and so it does not overlap the requested range.
1076 		 *
1077 		 * In such non-overlapping case the next slot (if it exists) will
1078 		 * already have slot start > range start, otherwise the logic above
1079 		 * would have found it instead of the current slot.
1080 		 */
1081 		if (iter->slot->base_gfn + iter->slot->npages <= start)
1082 			kvm_memslot_iter_next(iter);
1083 	}
1084 }
1085 
1086 static inline bool kvm_memslot_iter_is_valid(struct kvm_memslot_iter *iter, gfn_t end)
1087 {
1088 	if (!iter->node)
1089 		return false;
1090 
1091 	/*
1092 	 * If this slot starts beyond or at the end of the range so does
1093 	 * every next one
1094 	 */
1095 	return iter->slot->base_gfn < end;
1096 }
1097 
1098 /* Iterate over each memslot at least partially intersecting [start, end) range */
1099 #define kvm_for_each_memslot_in_gfn_range(iter, slots, start, end)	\
1100 	for (kvm_memslot_iter_start(iter, slots, start);		\
1101 	     kvm_memslot_iter_is_valid(iter, end);			\
1102 	     kvm_memslot_iter_next(iter))
1103 
1104 /*
1105  * KVM_SET_USER_MEMORY_REGION ioctl allows the following operations:
1106  * - create a new memory slot
1107  * - delete an existing memory slot
1108  * - modify an existing memory slot
1109  *   -- move it in the guest physical memory space
1110  *   -- just change its flags
1111  *
1112  * Since flags can be changed by some of these operations, the following
1113  * differentiation is the best we can do for __kvm_set_memory_region():
1114  */
1115 enum kvm_mr_change {
1116 	KVM_MR_CREATE,
1117 	KVM_MR_DELETE,
1118 	KVM_MR_MOVE,
1119 	KVM_MR_FLAGS_ONLY,
1120 };
1121 
1122 int kvm_set_memory_region(struct kvm *kvm,
1123 			  const struct kvm_userspace_memory_region *mem);
1124 int __kvm_set_memory_region(struct kvm *kvm,
1125 			    const struct kvm_userspace_memory_region *mem);
1126 void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot);
1127 void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen);
1128 int kvm_arch_prepare_memory_region(struct kvm *kvm,
1129 				const struct kvm_memory_slot *old,
1130 				struct kvm_memory_slot *new,
1131 				enum kvm_mr_change change);
1132 void kvm_arch_commit_memory_region(struct kvm *kvm,
1133 				struct kvm_memory_slot *old,
1134 				const struct kvm_memory_slot *new,
1135 				enum kvm_mr_change change);
1136 /* flush all memory translations */
1137 void kvm_arch_flush_shadow_all(struct kvm *kvm);
1138 /* flush memory translations pointing to 'slot' */
1139 void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
1140 				   struct kvm_memory_slot *slot);
1141 
1142 int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
1143 			    struct page **pages, int nr_pages);
1144 
1145 struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn);
1146 unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn);
1147 unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable);
1148 unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot, gfn_t gfn);
1149 unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot, gfn_t gfn,
1150 				      bool *writable);
1151 void kvm_release_page_clean(struct page *page);
1152 void kvm_release_page_dirty(struct page *page);
1153 
1154 kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn);
1155 kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
1156 		      bool *writable);
1157 kvm_pfn_t gfn_to_pfn_memslot(const struct kvm_memory_slot *slot, gfn_t gfn);
1158 kvm_pfn_t gfn_to_pfn_memslot_atomic(const struct kvm_memory_slot *slot, gfn_t gfn);
1159 kvm_pfn_t __gfn_to_pfn_memslot(const struct kvm_memory_slot *slot, gfn_t gfn,
1160 			       bool atomic, bool interruptible, bool *async,
1161 			       bool write_fault, bool *writable, hva_t *hva);
1162 
1163 void kvm_release_pfn_clean(kvm_pfn_t pfn);
1164 void kvm_release_pfn_dirty(kvm_pfn_t pfn);
1165 void kvm_set_pfn_dirty(kvm_pfn_t pfn);
1166 void kvm_set_pfn_accessed(kvm_pfn_t pfn);
1167 
1168 void kvm_release_pfn(kvm_pfn_t pfn, bool dirty);
1169 int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
1170 			int len);
1171 int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len);
1172 int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1173 			   void *data, unsigned long len);
1174 int kvm_read_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1175 				 void *data, unsigned int offset,
1176 				 unsigned long len);
1177 int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, const void *data,
1178 			 int offset, int len);
1179 int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
1180 		    unsigned long len);
1181 int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1182 			   void *data, unsigned long len);
1183 int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1184 				  void *data, unsigned int offset,
1185 				  unsigned long len);
1186 int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
1187 			      gpa_t gpa, unsigned long len);
1188 
1189 #define __kvm_get_guest(kvm, gfn, offset, v)				\
1190 ({									\
1191 	unsigned long __addr = gfn_to_hva(kvm, gfn);			\
1192 	typeof(v) __user *__uaddr = (typeof(__uaddr))(__addr + offset);	\
1193 	int __ret = -EFAULT;						\
1194 									\
1195 	if (!kvm_is_error_hva(__addr))					\
1196 		__ret = get_user(v, __uaddr);				\
1197 	__ret;								\
1198 })
1199 
1200 #define kvm_get_guest(kvm, gpa, v)					\
1201 ({									\
1202 	gpa_t __gpa = gpa;						\
1203 	struct kvm *__kvm = kvm;					\
1204 									\
1205 	__kvm_get_guest(__kvm, __gpa >> PAGE_SHIFT,			\
1206 			offset_in_page(__gpa), v);			\
1207 })
1208 
1209 #define __kvm_put_guest(kvm, gfn, offset, v)				\
1210 ({									\
1211 	unsigned long __addr = gfn_to_hva(kvm, gfn);			\
1212 	typeof(v) __user *__uaddr = (typeof(__uaddr))(__addr + offset);	\
1213 	int __ret = -EFAULT;						\
1214 									\
1215 	if (!kvm_is_error_hva(__addr))					\
1216 		__ret = put_user(v, __uaddr);				\
1217 	if (!__ret)							\
1218 		mark_page_dirty(kvm, gfn);				\
1219 	__ret;								\
1220 })
1221 
1222 #define kvm_put_guest(kvm, gpa, v)					\
1223 ({									\
1224 	gpa_t __gpa = gpa;						\
1225 	struct kvm *__kvm = kvm;					\
1226 									\
1227 	__kvm_put_guest(__kvm, __gpa >> PAGE_SHIFT,			\
1228 			offset_in_page(__gpa), v);			\
1229 })
1230 
1231 int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len);
1232 struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn);
1233 bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn);
1234 bool kvm_vcpu_is_visible_gfn(struct kvm_vcpu *vcpu, gfn_t gfn);
1235 unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn);
1236 void mark_page_dirty_in_slot(struct kvm *kvm, const struct kvm_memory_slot *memslot, gfn_t gfn);
1237 void mark_page_dirty(struct kvm *kvm, gfn_t gfn);
1238 
1239 struct kvm_memslots *kvm_vcpu_memslots(struct kvm_vcpu *vcpu);
1240 struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn);
1241 kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn);
1242 kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn);
1243 int kvm_vcpu_map(struct kvm_vcpu *vcpu, gpa_t gpa, struct kvm_host_map *map);
1244 void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty);
1245 unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn);
1246 unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable);
1247 int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data, int offset,
1248 			     int len);
1249 int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa, void *data,
1250 			       unsigned long len);
1251 int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data,
1252 			unsigned long len);
1253 int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, const void *data,
1254 			      int offset, int len);
1255 int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
1256 			 unsigned long len);
1257 void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn);
1258 
1259 /**
1260  * kvm_gpc_init - initialize gfn_to_pfn_cache.
1261  *
1262  * @gpc:	   struct gfn_to_pfn_cache object.
1263  *
1264  * This sets up a gfn_to_pfn_cache by initializing locks.  Note, the cache must
1265  * be zero-allocated (or zeroed by the caller before init).
1266  */
1267 void kvm_gpc_init(struct gfn_to_pfn_cache *gpc);
1268 
1269 /**
1270  * kvm_gpc_activate - prepare a cached kernel mapping and HPA for a given guest
1271  *                    physical address.
1272  *
1273  * @kvm:	   pointer to kvm instance.
1274  * @gpc:	   struct gfn_to_pfn_cache object.
1275  * @vcpu:	   vCPU to be used for marking pages dirty and to be woken on
1276  *		   invalidation.
1277  * @usage:	   indicates if the resulting host physical PFN is used while
1278  *		   the @vcpu is IN_GUEST_MODE (in which case invalidation of
1279  *		   the cache from MMU notifiers---but not for KVM memslot
1280  *		   changes!---will also force @vcpu to exit the guest and
1281  *		   refresh the cache); and/or if the PFN used directly
1282  *		   by KVM (and thus needs a kernel virtual mapping).
1283  * @gpa:	   guest physical address to map.
1284  * @len:	   sanity check; the range being access must fit a single page.
1285  *
1286  * @return:	   0 for success.
1287  *		   -EINVAL for a mapping which would cross a page boundary.
1288  *                 -EFAULT for an untranslatable guest physical address.
1289  *
1290  * This primes a gfn_to_pfn_cache and links it into the @kvm's list for
1291  * invalidations to be processed.  Callers are required to use kvm_gpc_check()
1292  * to ensure that the cache is valid before accessing the target page.
1293  */
1294 int kvm_gpc_activate(struct kvm *kvm, struct gfn_to_pfn_cache *gpc,
1295 		     struct kvm_vcpu *vcpu, enum pfn_cache_usage usage,
1296 		     gpa_t gpa, unsigned long len);
1297 
1298 /**
1299  * kvm_gpc_check - check validity of a gfn_to_pfn_cache.
1300  *
1301  * @kvm:	   pointer to kvm instance.
1302  * @gpc:	   struct gfn_to_pfn_cache object.
1303  * @gpa:	   current guest physical address to map.
1304  * @len:	   sanity check; the range being access must fit a single page.
1305  *
1306  * @return:	   %true if the cache is still valid and the address matches.
1307  *		   %false if the cache is not valid.
1308  *
1309  * Callers outside IN_GUEST_MODE context should hold a read lock on @gpc->lock
1310  * while calling this function, and then continue to hold the lock until the
1311  * access is complete.
1312  *
1313  * Callers in IN_GUEST_MODE may do so without locking, although they should
1314  * still hold a read lock on kvm->scru for the memslot checks.
1315  */
1316 bool kvm_gpc_check(struct kvm *kvm, struct gfn_to_pfn_cache *gpc, gpa_t gpa,
1317 		   unsigned long len);
1318 
1319 /**
1320  * kvm_gpc_refresh - update a previously initialized cache.
1321  *
1322  * @kvm:	   pointer to kvm instance.
1323  * @gpc:	   struct gfn_to_pfn_cache object.
1324  * @gpa:	   updated guest physical address to map.
1325  * @len:	   sanity check; the range being access must fit a single page.
1326  *
1327  * @return:	   0 for success.
1328  *		   -EINVAL for a mapping which would cross a page boundary.
1329  *                 -EFAULT for an untranslatable guest physical address.
1330  *
1331  * This will attempt to refresh a gfn_to_pfn_cache. Note that a successful
1332  * returm from this function does not mean the page can be immediately
1333  * accessed because it may have raced with an invalidation. Callers must
1334  * still lock and check the cache status, as this function does not return
1335  * with the lock still held to permit access.
1336  */
1337 int kvm_gpc_refresh(struct kvm *kvm, struct gfn_to_pfn_cache *gpc, gpa_t gpa,
1338 		    unsigned long len);
1339 
1340 /**
1341  * kvm_gpc_unmap - temporarily unmap a gfn_to_pfn_cache.
1342  *
1343  * @kvm:	   pointer to kvm instance.
1344  * @gpc:	   struct gfn_to_pfn_cache object.
1345  *
1346  * This unmaps the referenced page. The cache is left in the invalid state
1347  * but at least the mapping from GPA to userspace HVA will remain cached
1348  * and can be reused on a subsequent refresh.
1349  */
1350 void kvm_gpc_unmap(struct kvm *kvm, struct gfn_to_pfn_cache *gpc);
1351 
1352 /**
1353  * kvm_gpc_deactivate - deactivate and unlink a gfn_to_pfn_cache.
1354  *
1355  * @kvm:	   pointer to kvm instance.
1356  * @gpc:	   struct gfn_to_pfn_cache object.
1357  *
1358  * This removes a cache from the @kvm's list to be processed on MMU notifier
1359  * invocation.
1360  */
1361 void kvm_gpc_deactivate(struct kvm *kvm, struct gfn_to_pfn_cache *gpc);
1362 
1363 void kvm_sigset_activate(struct kvm_vcpu *vcpu);
1364 void kvm_sigset_deactivate(struct kvm_vcpu *vcpu);
1365 
1366 void kvm_vcpu_halt(struct kvm_vcpu *vcpu);
1367 bool kvm_vcpu_block(struct kvm_vcpu *vcpu);
1368 void kvm_arch_vcpu_blocking(struct kvm_vcpu *vcpu);
1369 void kvm_arch_vcpu_unblocking(struct kvm_vcpu *vcpu);
1370 bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu);
1371 void kvm_vcpu_kick(struct kvm_vcpu *vcpu);
1372 int kvm_vcpu_yield_to(struct kvm_vcpu *target);
1373 void kvm_vcpu_on_spin(struct kvm_vcpu *vcpu, bool usermode_vcpu_not_eligible);
1374 
1375 void kvm_flush_remote_tlbs(struct kvm *kvm);
1376 
1377 #ifdef KVM_ARCH_NR_OBJS_PER_MEMORY_CACHE
1378 int kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int min);
1379 int __kvm_mmu_topup_memory_cache(struct kvm_mmu_memory_cache *mc, int capacity, int min);
1380 int kvm_mmu_memory_cache_nr_free_objects(struct kvm_mmu_memory_cache *mc);
1381 void kvm_mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc);
1382 void *kvm_mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc);
1383 #endif
1384 
1385 void kvm_mmu_invalidate_begin(struct kvm *kvm, unsigned long start,
1386 			      unsigned long end);
1387 void kvm_mmu_invalidate_end(struct kvm *kvm, unsigned long start,
1388 			    unsigned long end);
1389 
1390 long kvm_arch_dev_ioctl(struct file *filp,
1391 			unsigned int ioctl, unsigned long arg);
1392 long kvm_arch_vcpu_ioctl(struct file *filp,
1393 			 unsigned int ioctl, unsigned long arg);
1394 vm_fault_t kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf);
1395 
1396 int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext);
1397 
1398 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1399 					struct kvm_memory_slot *slot,
1400 					gfn_t gfn_offset,
1401 					unsigned long mask);
1402 void kvm_arch_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot);
1403 
1404 #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
1405 void kvm_arch_flush_remote_tlbs_memslot(struct kvm *kvm,
1406 					const struct kvm_memory_slot *memslot);
1407 #else /* !CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT */
1408 int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log);
1409 int kvm_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log,
1410 		      int *is_dirty, struct kvm_memory_slot **memslot);
1411 #endif
1412 
1413 int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_level,
1414 			bool line_status);
1415 int kvm_vm_ioctl_enable_cap(struct kvm *kvm,
1416 			    struct kvm_enable_cap *cap);
1417 long kvm_arch_vm_ioctl(struct file *filp,
1418 		       unsigned int ioctl, unsigned long arg);
1419 long kvm_arch_vm_compat_ioctl(struct file *filp, unsigned int ioctl,
1420 			      unsigned long arg);
1421 
1422 int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu);
1423 int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu);
1424 
1425 int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
1426 				    struct kvm_translation *tr);
1427 
1428 int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs);
1429 int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs);
1430 int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
1431 				  struct kvm_sregs *sregs);
1432 int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
1433 				  struct kvm_sregs *sregs);
1434 int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
1435 				    struct kvm_mp_state *mp_state);
1436 int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
1437 				    struct kvm_mp_state *mp_state);
1438 int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
1439 					struct kvm_guest_debug *dbg);
1440 int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu);
1441 
1442 int kvm_arch_init(void *opaque);
1443 void kvm_arch_exit(void);
1444 
1445 void kvm_arch_sched_in(struct kvm_vcpu *vcpu, int cpu);
1446 
1447 void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu);
1448 void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu);
1449 int kvm_arch_vcpu_precreate(struct kvm *kvm, unsigned int id);
1450 int kvm_arch_vcpu_create(struct kvm_vcpu *vcpu);
1451 void kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu);
1452 void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu);
1453 
1454 #ifdef CONFIG_HAVE_KVM_PM_NOTIFIER
1455 int kvm_arch_pm_notifier(struct kvm *kvm, unsigned long state);
1456 #endif
1457 
1458 #ifdef __KVM_HAVE_ARCH_VCPU_DEBUGFS
1459 void kvm_arch_create_vcpu_debugfs(struct kvm_vcpu *vcpu, struct dentry *debugfs_dentry);
1460 #else
1461 static inline void kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu) {}
1462 #endif
1463 
1464 int kvm_arch_hardware_enable(void);
1465 void kvm_arch_hardware_disable(void);
1466 int kvm_arch_hardware_setup(void *opaque);
1467 void kvm_arch_hardware_unsetup(void);
1468 int kvm_arch_check_processor_compat(void *opaque);
1469 int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu);
1470 bool kvm_arch_vcpu_in_kernel(struct kvm_vcpu *vcpu);
1471 int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu);
1472 bool kvm_arch_dy_runnable(struct kvm_vcpu *vcpu);
1473 bool kvm_arch_dy_has_pending_interrupt(struct kvm_vcpu *vcpu);
1474 int kvm_arch_post_init_vm(struct kvm *kvm);
1475 void kvm_arch_pre_destroy_vm(struct kvm *kvm);
1476 int kvm_arch_create_vm_debugfs(struct kvm *kvm);
1477 
1478 #ifndef __KVM_HAVE_ARCH_VM_ALLOC
1479 /*
1480  * All architectures that want to use vzalloc currently also
1481  * need their own kvm_arch_alloc_vm implementation.
1482  */
1483 static inline struct kvm *kvm_arch_alloc_vm(void)
1484 {
1485 	return kzalloc(sizeof(struct kvm), GFP_KERNEL);
1486 }
1487 #endif
1488 
1489 static inline void __kvm_arch_free_vm(struct kvm *kvm)
1490 {
1491 	kvfree(kvm);
1492 }
1493 
1494 #ifndef __KVM_HAVE_ARCH_VM_FREE
1495 static inline void kvm_arch_free_vm(struct kvm *kvm)
1496 {
1497 	__kvm_arch_free_vm(kvm);
1498 }
1499 #endif
1500 
1501 #ifndef __KVM_HAVE_ARCH_FLUSH_REMOTE_TLB
1502 static inline int kvm_arch_flush_remote_tlb(struct kvm *kvm)
1503 {
1504 	return -ENOTSUPP;
1505 }
1506 #endif
1507 
1508 #ifdef __KVM_HAVE_ARCH_NONCOHERENT_DMA
1509 void kvm_arch_register_noncoherent_dma(struct kvm *kvm);
1510 void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm);
1511 bool kvm_arch_has_noncoherent_dma(struct kvm *kvm);
1512 #else
1513 static inline void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
1514 {
1515 }
1516 
1517 static inline void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
1518 {
1519 }
1520 
1521 static inline bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
1522 {
1523 	return false;
1524 }
1525 #endif
1526 #ifdef __KVM_HAVE_ARCH_ASSIGNED_DEVICE
1527 void kvm_arch_start_assignment(struct kvm *kvm);
1528 void kvm_arch_end_assignment(struct kvm *kvm);
1529 bool kvm_arch_has_assigned_device(struct kvm *kvm);
1530 #else
1531 static inline void kvm_arch_start_assignment(struct kvm *kvm)
1532 {
1533 }
1534 
1535 static inline void kvm_arch_end_assignment(struct kvm *kvm)
1536 {
1537 }
1538 
1539 static __always_inline bool kvm_arch_has_assigned_device(struct kvm *kvm)
1540 {
1541 	return false;
1542 }
1543 #endif
1544 
1545 static inline struct rcuwait *kvm_arch_vcpu_get_wait(struct kvm_vcpu *vcpu)
1546 {
1547 #ifdef __KVM_HAVE_ARCH_WQP
1548 	return vcpu->arch.waitp;
1549 #else
1550 	return &vcpu->wait;
1551 #endif
1552 }
1553 
1554 /*
1555  * Wake a vCPU if necessary, but don't do any stats/metadata updates.  Returns
1556  * true if the vCPU was blocking and was awakened, false otherwise.
1557  */
1558 static inline bool __kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
1559 {
1560 	return !!rcuwait_wake_up(kvm_arch_vcpu_get_wait(vcpu));
1561 }
1562 
1563 static inline bool kvm_vcpu_is_blocking(struct kvm_vcpu *vcpu)
1564 {
1565 	return rcuwait_active(kvm_arch_vcpu_get_wait(vcpu));
1566 }
1567 
1568 #ifdef __KVM_HAVE_ARCH_INTC_INITIALIZED
1569 /*
1570  * returns true if the virtual interrupt controller is initialized and
1571  * ready to accept virtual IRQ. On some architectures the virtual interrupt
1572  * controller is dynamically instantiated and this is not always true.
1573  */
1574 bool kvm_arch_intc_initialized(struct kvm *kvm);
1575 #else
1576 static inline bool kvm_arch_intc_initialized(struct kvm *kvm)
1577 {
1578 	return true;
1579 }
1580 #endif
1581 
1582 #ifdef CONFIG_GUEST_PERF_EVENTS
1583 unsigned long kvm_arch_vcpu_get_ip(struct kvm_vcpu *vcpu);
1584 
1585 void kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void));
1586 void kvm_unregister_perf_callbacks(void);
1587 #else
1588 static inline void kvm_register_perf_callbacks(void *ign) {}
1589 static inline void kvm_unregister_perf_callbacks(void) {}
1590 #endif /* CONFIG_GUEST_PERF_EVENTS */
1591 
1592 int kvm_arch_init_vm(struct kvm *kvm, unsigned long type);
1593 void kvm_arch_destroy_vm(struct kvm *kvm);
1594 void kvm_arch_sync_events(struct kvm *kvm);
1595 
1596 int kvm_cpu_has_pending_timer(struct kvm_vcpu *vcpu);
1597 
1598 struct page *kvm_pfn_to_refcounted_page(kvm_pfn_t pfn);
1599 bool kvm_is_zone_device_page(struct page *page);
1600 
1601 struct kvm_irq_ack_notifier {
1602 	struct hlist_node link;
1603 	unsigned gsi;
1604 	void (*irq_acked)(struct kvm_irq_ack_notifier *kian);
1605 };
1606 
1607 int kvm_irq_map_gsi(struct kvm *kvm,
1608 		    struct kvm_kernel_irq_routing_entry *entries, int gsi);
1609 int kvm_irq_map_chip_pin(struct kvm *kvm, unsigned irqchip, unsigned pin);
1610 
1611 int kvm_set_irq(struct kvm *kvm, int irq_source_id, u32 irq, int level,
1612 		bool line_status);
1613 int kvm_set_msi(struct kvm_kernel_irq_routing_entry *irq_entry, struct kvm *kvm,
1614 		int irq_source_id, int level, bool line_status);
1615 int kvm_arch_set_irq_inatomic(struct kvm_kernel_irq_routing_entry *e,
1616 			       struct kvm *kvm, int irq_source_id,
1617 			       int level, bool line_status);
1618 bool kvm_irq_has_notifier(struct kvm *kvm, unsigned irqchip, unsigned pin);
1619 void kvm_notify_acked_gsi(struct kvm *kvm, int gsi);
1620 void kvm_notify_acked_irq(struct kvm *kvm, unsigned irqchip, unsigned pin);
1621 void kvm_register_irq_ack_notifier(struct kvm *kvm,
1622 				   struct kvm_irq_ack_notifier *kian);
1623 void kvm_unregister_irq_ack_notifier(struct kvm *kvm,
1624 				   struct kvm_irq_ack_notifier *kian);
1625 int kvm_request_irq_source_id(struct kvm *kvm);
1626 void kvm_free_irq_source_id(struct kvm *kvm, int irq_source_id);
1627 bool kvm_arch_irqfd_allowed(struct kvm *kvm, struct kvm_irqfd *args);
1628 
1629 /*
1630  * Returns a pointer to the memslot if it contains gfn.
1631  * Otherwise returns NULL.
1632  */
1633 static inline struct kvm_memory_slot *
1634 try_get_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
1635 {
1636 	if (!slot)
1637 		return NULL;
1638 
1639 	if (gfn >= slot->base_gfn && gfn < slot->base_gfn + slot->npages)
1640 		return slot;
1641 	else
1642 		return NULL;
1643 }
1644 
1645 /*
1646  * Returns a pointer to the memslot that contains gfn. Otherwise returns NULL.
1647  *
1648  * With "approx" set returns the memslot also when the address falls
1649  * in a hole. In that case one of the memslots bordering the hole is
1650  * returned.
1651  */
1652 static inline struct kvm_memory_slot *
1653 search_memslots(struct kvm_memslots *slots, gfn_t gfn, bool approx)
1654 {
1655 	struct kvm_memory_slot *slot;
1656 	struct rb_node *node;
1657 	int idx = slots->node_idx;
1658 
1659 	slot = NULL;
1660 	for (node = slots->gfn_tree.rb_node; node; ) {
1661 		slot = container_of(node, struct kvm_memory_slot, gfn_node[idx]);
1662 		if (gfn >= slot->base_gfn) {
1663 			if (gfn < slot->base_gfn + slot->npages)
1664 				return slot;
1665 			node = node->rb_right;
1666 		} else
1667 			node = node->rb_left;
1668 	}
1669 
1670 	return approx ? slot : NULL;
1671 }
1672 
1673 static inline struct kvm_memory_slot *
1674 ____gfn_to_memslot(struct kvm_memslots *slots, gfn_t gfn, bool approx)
1675 {
1676 	struct kvm_memory_slot *slot;
1677 
1678 	slot = (struct kvm_memory_slot *)atomic_long_read(&slots->last_used_slot);
1679 	slot = try_get_memslot(slot, gfn);
1680 	if (slot)
1681 		return slot;
1682 
1683 	slot = search_memslots(slots, gfn, approx);
1684 	if (slot) {
1685 		atomic_long_set(&slots->last_used_slot, (unsigned long)slot);
1686 		return slot;
1687 	}
1688 
1689 	return NULL;
1690 }
1691 
1692 /*
1693  * __gfn_to_memslot() and its descendants are here to allow arch code to inline
1694  * the lookups in hot paths.  gfn_to_memslot() itself isn't here as an inline
1695  * because that would bloat other code too much.
1696  */
1697 static inline struct kvm_memory_slot *
1698 __gfn_to_memslot(struct kvm_memslots *slots, gfn_t gfn)
1699 {
1700 	return ____gfn_to_memslot(slots, gfn, false);
1701 }
1702 
1703 static inline unsigned long
1704 __gfn_to_hva_memslot(const struct kvm_memory_slot *slot, gfn_t gfn)
1705 {
1706 	/*
1707 	 * The index was checked originally in search_memslots.  To avoid
1708 	 * that a malicious guest builds a Spectre gadget out of e.g. page
1709 	 * table walks, do not let the processor speculate loads outside
1710 	 * the guest's registered memslots.
1711 	 */
1712 	unsigned long offset = gfn - slot->base_gfn;
1713 	offset = array_index_nospec(offset, slot->npages);
1714 	return slot->userspace_addr + offset * PAGE_SIZE;
1715 }
1716 
1717 static inline int memslot_id(struct kvm *kvm, gfn_t gfn)
1718 {
1719 	return gfn_to_memslot(kvm, gfn)->id;
1720 }
1721 
1722 static inline gfn_t
1723 hva_to_gfn_memslot(unsigned long hva, struct kvm_memory_slot *slot)
1724 {
1725 	gfn_t gfn_offset = (hva - slot->userspace_addr) >> PAGE_SHIFT;
1726 
1727 	return slot->base_gfn + gfn_offset;
1728 }
1729 
1730 static inline gpa_t gfn_to_gpa(gfn_t gfn)
1731 {
1732 	return (gpa_t)gfn << PAGE_SHIFT;
1733 }
1734 
1735 static inline gfn_t gpa_to_gfn(gpa_t gpa)
1736 {
1737 	return (gfn_t)(gpa >> PAGE_SHIFT);
1738 }
1739 
1740 static inline hpa_t pfn_to_hpa(kvm_pfn_t pfn)
1741 {
1742 	return (hpa_t)pfn << PAGE_SHIFT;
1743 }
1744 
1745 static inline bool kvm_is_error_gpa(struct kvm *kvm, gpa_t gpa)
1746 {
1747 	unsigned long hva = gfn_to_hva(kvm, gpa_to_gfn(gpa));
1748 
1749 	return kvm_is_error_hva(hva);
1750 }
1751 
1752 enum kvm_stat_kind {
1753 	KVM_STAT_VM,
1754 	KVM_STAT_VCPU,
1755 };
1756 
1757 struct kvm_stat_data {
1758 	struct kvm *kvm;
1759 	const struct _kvm_stats_desc *desc;
1760 	enum kvm_stat_kind kind;
1761 };
1762 
1763 struct _kvm_stats_desc {
1764 	struct kvm_stats_desc desc;
1765 	char name[KVM_STATS_NAME_SIZE];
1766 };
1767 
1768 #define STATS_DESC_COMMON(type, unit, base, exp, sz, bsz)		       \
1769 	.flags = type | unit | base |					       \
1770 		 BUILD_BUG_ON_ZERO(type & ~KVM_STATS_TYPE_MASK) |	       \
1771 		 BUILD_BUG_ON_ZERO(unit & ~KVM_STATS_UNIT_MASK) |	       \
1772 		 BUILD_BUG_ON_ZERO(base & ~KVM_STATS_BASE_MASK),	       \
1773 	.exponent = exp,						       \
1774 	.size = sz,							       \
1775 	.bucket_size = bsz
1776 
1777 #define VM_GENERIC_STATS_DESC(stat, type, unit, base, exp, sz, bsz)	       \
1778 	{								       \
1779 		{							       \
1780 			STATS_DESC_COMMON(type, unit, base, exp, sz, bsz),     \
1781 			.offset = offsetof(struct kvm_vm_stat, generic.stat)   \
1782 		},							       \
1783 		.name = #stat,						       \
1784 	}
1785 #define VCPU_GENERIC_STATS_DESC(stat, type, unit, base, exp, sz, bsz)	       \
1786 	{								       \
1787 		{							       \
1788 			STATS_DESC_COMMON(type, unit, base, exp, sz, bsz),     \
1789 			.offset = offsetof(struct kvm_vcpu_stat, generic.stat) \
1790 		},							       \
1791 		.name = #stat,						       \
1792 	}
1793 #define VM_STATS_DESC(stat, type, unit, base, exp, sz, bsz)		       \
1794 	{								       \
1795 		{							       \
1796 			STATS_DESC_COMMON(type, unit, base, exp, sz, bsz),     \
1797 			.offset = offsetof(struct kvm_vm_stat, stat)	       \
1798 		},							       \
1799 		.name = #stat,						       \
1800 	}
1801 #define VCPU_STATS_DESC(stat, type, unit, base, exp, sz, bsz)		       \
1802 	{								       \
1803 		{							       \
1804 			STATS_DESC_COMMON(type, unit, base, exp, sz, bsz),     \
1805 			.offset = offsetof(struct kvm_vcpu_stat, stat)	       \
1806 		},							       \
1807 		.name = #stat,						       \
1808 	}
1809 /* SCOPE: VM, VM_GENERIC, VCPU, VCPU_GENERIC */
1810 #define STATS_DESC(SCOPE, stat, type, unit, base, exp, sz, bsz)		       \
1811 	SCOPE##_STATS_DESC(stat, type, unit, base, exp, sz, bsz)
1812 
1813 #define STATS_DESC_CUMULATIVE(SCOPE, name, unit, base, exponent)	       \
1814 	STATS_DESC(SCOPE, name, KVM_STATS_TYPE_CUMULATIVE,		       \
1815 		unit, base, exponent, 1, 0)
1816 #define STATS_DESC_INSTANT(SCOPE, name, unit, base, exponent)		       \
1817 	STATS_DESC(SCOPE, name, KVM_STATS_TYPE_INSTANT,			       \
1818 		unit, base, exponent, 1, 0)
1819 #define STATS_DESC_PEAK(SCOPE, name, unit, base, exponent)		       \
1820 	STATS_DESC(SCOPE, name, KVM_STATS_TYPE_PEAK,			       \
1821 		unit, base, exponent, 1, 0)
1822 #define STATS_DESC_LINEAR_HIST(SCOPE, name, unit, base, exponent, sz, bsz)     \
1823 	STATS_DESC(SCOPE, name, KVM_STATS_TYPE_LINEAR_HIST,		       \
1824 		unit, base, exponent, sz, bsz)
1825 #define STATS_DESC_LOG_HIST(SCOPE, name, unit, base, exponent, sz)	       \
1826 	STATS_DESC(SCOPE, name, KVM_STATS_TYPE_LOG_HIST,		       \
1827 		unit, base, exponent, sz, 0)
1828 
1829 /* Cumulative counter, read/write */
1830 #define STATS_DESC_COUNTER(SCOPE, name)					       \
1831 	STATS_DESC_CUMULATIVE(SCOPE, name, KVM_STATS_UNIT_NONE,		       \
1832 		KVM_STATS_BASE_POW10, 0)
1833 /* Instantaneous counter, read only */
1834 #define STATS_DESC_ICOUNTER(SCOPE, name)				       \
1835 	STATS_DESC_INSTANT(SCOPE, name, KVM_STATS_UNIT_NONE,		       \
1836 		KVM_STATS_BASE_POW10, 0)
1837 /* Peak counter, read/write */
1838 #define STATS_DESC_PCOUNTER(SCOPE, name)				       \
1839 	STATS_DESC_PEAK(SCOPE, name, KVM_STATS_UNIT_NONE,		       \
1840 		KVM_STATS_BASE_POW10, 0)
1841 
1842 /* Instantaneous boolean value, read only */
1843 #define STATS_DESC_IBOOLEAN(SCOPE, name)				       \
1844 	STATS_DESC_INSTANT(SCOPE, name, KVM_STATS_UNIT_BOOLEAN,		       \
1845 		KVM_STATS_BASE_POW10, 0)
1846 /* Peak (sticky) boolean value, read/write */
1847 #define STATS_DESC_PBOOLEAN(SCOPE, name)				       \
1848 	STATS_DESC_PEAK(SCOPE, name, KVM_STATS_UNIT_BOOLEAN,		       \
1849 		KVM_STATS_BASE_POW10, 0)
1850 
1851 /* Cumulative time in nanosecond */
1852 #define STATS_DESC_TIME_NSEC(SCOPE, name)				       \
1853 	STATS_DESC_CUMULATIVE(SCOPE, name, KVM_STATS_UNIT_SECONDS,	       \
1854 		KVM_STATS_BASE_POW10, -9)
1855 /* Linear histogram for time in nanosecond */
1856 #define STATS_DESC_LINHIST_TIME_NSEC(SCOPE, name, sz, bsz)		       \
1857 	STATS_DESC_LINEAR_HIST(SCOPE, name, KVM_STATS_UNIT_SECONDS,	       \
1858 		KVM_STATS_BASE_POW10, -9, sz, bsz)
1859 /* Logarithmic histogram for time in nanosecond */
1860 #define STATS_DESC_LOGHIST_TIME_NSEC(SCOPE, name, sz)			       \
1861 	STATS_DESC_LOG_HIST(SCOPE, name, KVM_STATS_UNIT_SECONDS,	       \
1862 		KVM_STATS_BASE_POW10, -9, sz)
1863 
1864 #define KVM_GENERIC_VM_STATS()						       \
1865 	STATS_DESC_COUNTER(VM_GENERIC, remote_tlb_flush),		       \
1866 	STATS_DESC_COUNTER(VM_GENERIC, remote_tlb_flush_requests)
1867 
1868 #define KVM_GENERIC_VCPU_STATS()					       \
1869 	STATS_DESC_COUNTER(VCPU_GENERIC, halt_successful_poll),		       \
1870 	STATS_DESC_COUNTER(VCPU_GENERIC, halt_attempted_poll),		       \
1871 	STATS_DESC_COUNTER(VCPU_GENERIC, halt_poll_invalid),		       \
1872 	STATS_DESC_COUNTER(VCPU_GENERIC, halt_wakeup),			       \
1873 	STATS_DESC_TIME_NSEC(VCPU_GENERIC, halt_poll_success_ns),	       \
1874 	STATS_DESC_TIME_NSEC(VCPU_GENERIC, halt_poll_fail_ns),		       \
1875 	STATS_DESC_TIME_NSEC(VCPU_GENERIC, halt_wait_ns),		       \
1876 	STATS_DESC_LOGHIST_TIME_NSEC(VCPU_GENERIC, halt_poll_success_hist,     \
1877 			HALT_POLL_HIST_COUNT),				       \
1878 	STATS_DESC_LOGHIST_TIME_NSEC(VCPU_GENERIC, halt_poll_fail_hist,	       \
1879 			HALT_POLL_HIST_COUNT),				       \
1880 	STATS_DESC_LOGHIST_TIME_NSEC(VCPU_GENERIC, halt_wait_hist,	       \
1881 			HALT_POLL_HIST_COUNT),				       \
1882 	STATS_DESC_IBOOLEAN(VCPU_GENERIC, blocking)
1883 
1884 extern struct dentry *kvm_debugfs_dir;
1885 
1886 ssize_t kvm_stats_read(char *id, const struct kvm_stats_header *header,
1887 		       const struct _kvm_stats_desc *desc,
1888 		       void *stats, size_t size_stats,
1889 		       char __user *user_buffer, size_t size, loff_t *offset);
1890 
1891 /**
1892  * kvm_stats_linear_hist_update() - Update bucket value for linear histogram
1893  * statistics data.
1894  *
1895  * @data: start address of the stats data
1896  * @size: the number of bucket of the stats data
1897  * @value: the new value used to update the linear histogram's bucket
1898  * @bucket_size: the size (width) of a bucket
1899  */
1900 static inline void kvm_stats_linear_hist_update(u64 *data, size_t size,
1901 						u64 value, size_t bucket_size)
1902 {
1903 	size_t index = div64_u64(value, bucket_size);
1904 
1905 	index = min(index, size - 1);
1906 	++data[index];
1907 }
1908 
1909 /**
1910  * kvm_stats_log_hist_update() - Update bucket value for logarithmic histogram
1911  * statistics data.
1912  *
1913  * @data: start address of the stats data
1914  * @size: the number of bucket of the stats data
1915  * @value: the new value used to update the logarithmic histogram's bucket
1916  */
1917 static inline void kvm_stats_log_hist_update(u64 *data, size_t size, u64 value)
1918 {
1919 	size_t index = fls64(value);
1920 
1921 	index = min(index, size - 1);
1922 	++data[index];
1923 }
1924 
1925 #define KVM_STATS_LINEAR_HIST_UPDATE(array, value, bsize)		       \
1926 	kvm_stats_linear_hist_update(array, ARRAY_SIZE(array), value, bsize)
1927 #define KVM_STATS_LOG_HIST_UPDATE(array, value)				       \
1928 	kvm_stats_log_hist_update(array, ARRAY_SIZE(array), value)
1929 
1930 
1931 extern const struct kvm_stats_header kvm_vm_stats_header;
1932 extern const struct _kvm_stats_desc kvm_vm_stats_desc[];
1933 extern const struct kvm_stats_header kvm_vcpu_stats_header;
1934 extern const struct _kvm_stats_desc kvm_vcpu_stats_desc[];
1935 
1936 #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
1937 static inline int mmu_invalidate_retry(struct kvm *kvm, unsigned long mmu_seq)
1938 {
1939 	if (unlikely(kvm->mmu_invalidate_in_progress))
1940 		return 1;
1941 	/*
1942 	 * Ensure the read of mmu_invalidate_in_progress happens before
1943 	 * the read of mmu_invalidate_seq.  This interacts with the
1944 	 * smp_wmb() in mmu_notifier_invalidate_range_end to make sure
1945 	 * that the caller either sees the old (non-zero) value of
1946 	 * mmu_invalidate_in_progress or the new (incremented) value of
1947 	 * mmu_invalidate_seq.
1948 	 *
1949 	 * PowerPC Book3s HV KVM calls this under a per-page lock rather
1950 	 * than under kvm->mmu_lock, for scalability, so can't rely on
1951 	 * kvm->mmu_lock to keep things ordered.
1952 	 */
1953 	smp_rmb();
1954 	if (kvm->mmu_invalidate_seq != mmu_seq)
1955 		return 1;
1956 	return 0;
1957 }
1958 
1959 static inline int mmu_invalidate_retry_hva(struct kvm *kvm,
1960 					   unsigned long mmu_seq,
1961 					   unsigned long hva)
1962 {
1963 	lockdep_assert_held(&kvm->mmu_lock);
1964 	/*
1965 	 * If mmu_invalidate_in_progress is non-zero, then the range maintained
1966 	 * by kvm_mmu_notifier_invalidate_range_start contains all addresses
1967 	 * that might be being invalidated. Note that it may include some false
1968 	 * positives, due to shortcuts when handing concurrent invalidations.
1969 	 */
1970 	if (unlikely(kvm->mmu_invalidate_in_progress) &&
1971 	    hva >= kvm->mmu_invalidate_range_start &&
1972 	    hva < kvm->mmu_invalidate_range_end)
1973 		return 1;
1974 	if (kvm->mmu_invalidate_seq != mmu_seq)
1975 		return 1;
1976 	return 0;
1977 }
1978 #endif
1979 
1980 #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
1981 
1982 #define KVM_MAX_IRQ_ROUTES 4096 /* might need extension/rework in the future */
1983 
1984 bool kvm_arch_can_set_irq_routing(struct kvm *kvm);
1985 int kvm_set_irq_routing(struct kvm *kvm,
1986 			const struct kvm_irq_routing_entry *entries,
1987 			unsigned nr,
1988 			unsigned flags);
1989 int kvm_set_routing_entry(struct kvm *kvm,
1990 			  struct kvm_kernel_irq_routing_entry *e,
1991 			  const struct kvm_irq_routing_entry *ue);
1992 void kvm_free_irq_routing(struct kvm *kvm);
1993 
1994 #else
1995 
1996 static inline void kvm_free_irq_routing(struct kvm *kvm) {}
1997 
1998 #endif
1999 
2000 int kvm_send_userspace_msi(struct kvm *kvm, struct kvm_msi *msi);
2001 
2002 #ifdef CONFIG_HAVE_KVM_EVENTFD
2003 
2004 void kvm_eventfd_init(struct kvm *kvm);
2005 int kvm_ioeventfd(struct kvm *kvm, struct kvm_ioeventfd *args);
2006 
2007 #ifdef CONFIG_HAVE_KVM_IRQFD
2008 int kvm_irqfd(struct kvm *kvm, struct kvm_irqfd *args);
2009 void kvm_irqfd_release(struct kvm *kvm);
2010 void kvm_irq_routing_update(struct kvm *);
2011 #else
2012 static inline int kvm_irqfd(struct kvm *kvm, struct kvm_irqfd *args)
2013 {
2014 	return -EINVAL;
2015 }
2016 
2017 static inline void kvm_irqfd_release(struct kvm *kvm) {}
2018 #endif
2019 
2020 #else
2021 
2022 static inline void kvm_eventfd_init(struct kvm *kvm) {}
2023 
2024 static inline int kvm_irqfd(struct kvm *kvm, struct kvm_irqfd *args)
2025 {
2026 	return -EINVAL;
2027 }
2028 
2029 static inline void kvm_irqfd_release(struct kvm *kvm) {}
2030 
2031 #ifdef CONFIG_HAVE_KVM_IRQCHIP
2032 static inline void kvm_irq_routing_update(struct kvm *kvm)
2033 {
2034 }
2035 #endif
2036 
2037 static inline int kvm_ioeventfd(struct kvm *kvm, struct kvm_ioeventfd *args)
2038 {
2039 	return -ENOSYS;
2040 }
2041 
2042 #endif /* CONFIG_HAVE_KVM_EVENTFD */
2043 
2044 void kvm_arch_irq_routing_update(struct kvm *kvm);
2045 
2046 static inline void __kvm_make_request(int req, struct kvm_vcpu *vcpu)
2047 {
2048 	/*
2049 	 * Ensure the rest of the request is published to kvm_check_request's
2050 	 * caller.  Paired with the smp_mb__after_atomic in kvm_check_request.
2051 	 */
2052 	smp_wmb();
2053 	set_bit(req & KVM_REQUEST_MASK, (void *)&vcpu->requests);
2054 }
2055 
2056 static __always_inline void kvm_make_request(int req, struct kvm_vcpu *vcpu)
2057 {
2058 	/*
2059 	 * Request that don't require vCPU action should never be logged in
2060 	 * vcpu->requests.  The vCPU won't clear the request, so it will stay
2061 	 * logged indefinitely and prevent the vCPU from entering the guest.
2062 	 */
2063 	BUILD_BUG_ON(!__builtin_constant_p(req) ||
2064 		     (req & KVM_REQUEST_NO_ACTION));
2065 
2066 	__kvm_make_request(req, vcpu);
2067 }
2068 
2069 static inline bool kvm_request_pending(struct kvm_vcpu *vcpu)
2070 {
2071 	return READ_ONCE(vcpu->requests);
2072 }
2073 
2074 static inline bool kvm_test_request(int req, struct kvm_vcpu *vcpu)
2075 {
2076 	return test_bit(req & KVM_REQUEST_MASK, (void *)&vcpu->requests);
2077 }
2078 
2079 static inline void kvm_clear_request(int req, struct kvm_vcpu *vcpu)
2080 {
2081 	clear_bit(req & KVM_REQUEST_MASK, (void *)&vcpu->requests);
2082 }
2083 
2084 static inline bool kvm_check_request(int req, struct kvm_vcpu *vcpu)
2085 {
2086 	if (kvm_test_request(req, vcpu)) {
2087 		kvm_clear_request(req, vcpu);
2088 
2089 		/*
2090 		 * Ensure the rest of the request is visible to kvm_check_request's
2091 		 * caller.  Paired with the smp_wmb in kvm_make_request.
2092 		 */
2093 		smp_mb__after_atomic();
2094 		return true;
2095 	} else {
2096 		return false;
2097 	}
2098 }
2099 
2100 extern bool kvm_rebooting;
2101 
2102 extern unsigned int halt_poll_ns;
2103 extern unsigned int halt_poll_ns_grow;
2104 extern unsigned int halt_poll_ns_grow_start;
2105 extern unsigned int halt_poll_ns_shrink;
2106 
2107 struct kvm_device {
2108 	const struct kvm_device_ops *ops;
2109 	struct kvm *kvm;
2110 	void *private;
2111 	struct list_head vm_node;
2112 };
2113 
2114 /* create, destroy, and name are mandatory */
2115 struct kvm_device_ops {
2116 	const char *name;
2117 
2118 	/*
2119 	 * create is called holding kvm->lock and any operations not suitable
2120 	 * to do while holding the lock should be deferred to init (see
2121 	 * below).
2122 	 */
2123 	int (*create)(struct kvm_device *dev, u32 type);
2124 
2125 	/*
2126 	 * init is called after create if create is successful and is called
2127 	 * outside of holding kvm->lock.
2128 	 */
2129 	void (*init)(struct kvm_device *dev);
2130 
2131 	/*
2132 	 * Destroy is responsible for freeing dev.
2133 	 *
2134 	 * Destroy may be called before or after destructors are called
2135 	 * on emulated I/O regions, depending on whether a reference is
2136 	 * held by a vcpu or other kvm component that gets destroyed
2137 	 * after the emulated I/O.
2138 	 */
2139 	void (*destroy)(struct kvm_device *dev);
2140 
2141 	/*
2142 	 * Release is an alternative method to free the device. It is
2143 	 * called when the device file descriptor is closed. Once
2144 	 * release is called, the destroy method will not be called
2145 	 * anymore as the device is removed from the device list of
2146 	 * the VM. kvm->lock is held.
2147 	 */
2148 	void (*release)(struct kvm_device *dev);
2149 
2150 	int (*set_attr)(struct kvm_device *dev, struct kvm_device_attr *attr);
2151 	int (*get_attr)(struct kvm_device *dev, struct kvm_device_attr *attr);
2152 	int (*has_attr)(struct kvm_device *dev, struct kvm_device_attr *attr);
2153 	long (*ioctl)(struct kvm_device *dev, unsigned int ioctl,
2154 		      unsigned long arg);
2155 	int (*mmap)(struct kvm_device *dev, struct vm_area_struct *vma);
2156 };
2157 
2158 void kvm_device_get(struct kvm_device *dev);
2159 void kvm_device_put(struct kvm_device *dev);
2160 struct kvm_device *kvm_device_from_filp(struct file *filp);
2161 int kvm_register_device_ops(const struct kvm_device_ops *ops, u32 type);
2162 void kvm_unregister_device_ops(u32 type);
2163 
2164 extern struct kvm_device_ops kvm_mpic_ops;
2165 extern struct kvm_device_ops kvm_arm_vgic_v2_ops;
2166 extern struct kvm_device_ops kvm_arm_vgic_v3_ops;
2167 
2168 #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
2169 
2170 static inline void kvm_vcpu_set_in_spin_loop(struct kvm_vcpu *vcpu, bool val)
2171 {
2172 	vcpu->spin_loop.in_spin_loop = val;
2173 }
2174 static inline void kvm_vcpu_set_dy_eligible(struct kvm_vcpu *vcpu, bool val)
2175 {
2176 	vcpu->spin_loop.dy_eligible = val;
2177 }
2178 
2179 #else /* !CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT */
2180 
2181 static inline void kvm_vcpu_set_in_spin_loop(struct kvm_vcpu *vcpu, bool val)
2182 {
2183 }
2184 
2185 static inline void kvm_vcpu_set_dy_eligible(struct kvm_vcpu *vcpu, bool val)
2186 {
2187 }
2188 #endif /* CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT */
2189 
2190 static inline bool kvm_is_visible_memslot(struct kvm_memory_slot *memslot)
2191 {
2192 	return (memslot && memslot->id < KVM_USER_MEM_SLOTS &&
2193 		!(memslot->flags & KVM_MEMSLOT_INVALID));
2194 }
2195 
2196 struct kvm_vcpu *kvm_get_running_vcpu(void);
2197 struct kvm_vcpu * __percpu *kvm_get_running_vcpus(void);
2198 
2199 #ifdef CONFIG_HAVE_KVM_IRQ_BYPASS
2200 bool kvm_arch_has_irq_bypass(void);
2201 int kvm_arch_irq_bypass_add_producer(struct irq_bypass_consumer *,
2202 			   struct irq_bypass_producer *);
2203 void kvm_arch_irq_bypass_del_producer(struct irq_bypass_consumer *,
2204 			   struct irq_bypass_producer *);
2205 void kvm_arch_irq_bypass_stop(struct irq_bypass_consumer *);
2206 void kvm_arch_irq_bypass_start(struct irq_bypass_consumer *);
2207 int kvm_arch_update_irqfd_routing(struct kvm *kvm, unsigned int host_irq,
2208 				  uint32_t guest_irq, bool set);
2209 bool kvm_arch_irqfd_route_changed(struct kvm_kernel_irq_routing_entry *,
2210 				  struct kvm_kernel_irq_routing_entry *);
2211 #endif /* CONFIG_HAVE_KVM_IRQ_BYPASS */
2212 
2213 #ifdef CONFIG_HAVE_KVM_INVALID_WAKEUPS
2214 /* If we wakeup during the poll time, was it a sucessful poll? */
2215 static inline bool vcpu_valid_wakeup(struct kvm_vcpu *vcpu)
2216 {
2217 	return vcpu->valid_wakeup;
2218 }
2219 
2220 #else
2221 static inline bool vcpu_valid_wakeup(struct kvm_vcpu *vcpu)
2222 {
2223 	return true;
2224 }
2225 #endif /* CONFIG_HAVE_KVM_INVALID_WAKEUPS */
2226 
2227 #ifdef CONFIG_HAVE_KVM_NO_POLL
2228 /* Callback that tells if we must not poll */
2229 bool kvm_arch_no_poll(struct kvm_vcpu *vcpu);
2230 #else
2231 static inline bool kvm_arch_no_poll(struct kvm_vcpu *vcpu)
2232 {
2233 	return false;
2234 }
2235 #endif /* CONFIG_HAVE_KVM_NO_POLL */
2236 
2237 #ifdef CONFIG_HAVE_KVM_VCPU_ASYNC_IOCTL
2238 long kvm_arch_vcpu_async_ioctl(struct file *filp,
2239 			       unsigned int ioctl, unsigned long arg);
2240 #else
2241 static inline long kvm_arch_vcpu_async_ioctl(struct file *filp,
2242 					     unsigned int ioctl,
2243 					     unsigned long arg)
2244 {
2245 	return -ENOIOCTLCMD;
2246 }
2247 #endif /* CONFIG_HAVE_KVM_VCPU_ASYNC_IOCTL */
2248 
2249 void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
2250 					    unsigned long start, unsigned long end);
2251 
2252 void kvm_arch_guest_memory_reclaimed(struct kvm *kvm);
2253 
2254 #ifdef CONFIG_HAVE_KVM_VCPU_RUN_PID_CHANGE
2255 int kvm_arch_vcpu_run_pid_change(struct kvm_vcpu *vcpu);
2256 #else
2257 static inline int kvm_arch_vcpu_run_pid_change(struct kvm_vcpu *vcpu)
2258 {
2259 	return 0;
2260 }
2261 #endif /* CONFIG_HAVE_KVM_VCPU_RUN_PID_CHANGE */
2262 
2263 typedef int (*kvm_vm_thread_fn_t)(struct kvm *kvm, uintptr_t data);
2264 
2265 int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
2266 				uintptr_t data, const char *name,
2267 				struct task_struct **thread_ptr);
2268 
2269 #ifdef CONFIG_KVM_XFER_TO_GUEST_WORK
2270 static inline void kvm_handle_signal_exit(struct kvm_vcpu *vcpu)
2271 {
2272 	vcpu->run->exit_reason = KVM_EXIT_INTR;
2273 	vcpu->stat.signal_exits++;
2274 }
2275 #endif /* CONFIG_KVM_XFER_TO_GUEST_WORK */
2276 
2277 /*
2278  * If more than one page is being (un)accounted, @virt must be the address of
2279  * the first page of a block of pages what were allocated together (i.e
2280  * accounted together).
2281  *
2282  * kvm_account_pgtable_pages() is thread-safe because mod_lruvec_page_state()
2283  * is thread-safe.
2284  */
2285 static inline void kvm_account_pgtable_pages(void *virt, int nr)
2286 {
2287 	mod_lruvec_page_state(virt_to_page(virt), NR_SECONDARY_PAGETABLE, nr);
2288 }
2289 
2290 /*
2291  * This defines how many reserved entries we want to keep before we
2292  * kick the vcpu to the userspace to avoid dirty ring full.  This
2293  * value can be tuned to higher if e.g. PML is enabled on the host.
2294  */
2295 #define  KVM_DIRTY_RING_RSVD_ENTRIES  64
2296 
2297 /* Max number of entries allowed for each kvm dirty ring */
2298 #define  KVM_DIRTY_RING_MAX_ENTRIES  65536
2299 
2300 #endif
2301