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