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