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