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