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