GNU Linux-libre 4.19.245-gnu1
[releases.git] / arch / x86 / kvm / mmu.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * This module enables machines with Intel VT-x extensions to run virtual
5  * machines without emulation or binary translation.
6  *
7  * MMU support
8  *
9  * Copyright (C) 2006 Qumranet, Inc.
10  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
11  *
12  * Authors:
13  *   Yaniv Kamay  <yaniv@qumranet.com>
14  *   Avi Kivity   <avi@qumranet.com>
15  *
16  * This work is licensed under the terms of the GNU GPL, version 2.  See
17  * the COPYING file in the top-level directory.
18  *
19  */
20
21 #include "irq.h"
22 #include "mmu.h"
23 #include "x86.h"
24 #include "kvm_cache_regs.h"
25 #include "cpuid.h"
26
27 #include <linux/kvm_host.h>
28 #include <linux/types.h>
29 #include <linux/string.h>
30 #include <linux/mm.h>
31 #include <linux/highmem.h>
32 #include <linux/moduleparam.h>
33 #include <linux/export.h>
34 #include <linux/swap.h>
35 #include <linux/hugetlb.h>
36 #include <linux/compiler.h>
37 #include <linux/srcu.h>
38 #include <linux/slab.h>
39 #include <linux/sched/signal.h>
40 #include <linux/uaccess.h>
41 #include <linux/hash.h>
42 #include <linux/kern_levels.h>
43 #include <linux/kthread.h>
44
45 #include <asm/page.h>
46 #include <asm/pat.h>
47 #include <asm/cmpxchg.h>
48 #include <asm/io.h>
49 #include <asm/vmx.h>
50 #include <asm/kvm_page_track.h>
51 #include "trace.h"
52
53 extern bool itlb_multihit_kvm_mitigation;
54
55 static int __read_mostly nx_huge_pages = -1;
56 static uint __read_mostly nx_huge_pages_recovery_ratio = 60;
57
58 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp);
59 static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp);
60
61 static struct kernel_param_ops nx_huge_pages_ops = {
62         .set = set_nx_huge_pages,
63         .get = param_get_bool,
64 };
65
66 static struct kernel_param_ops nx_huge_pages_recovery_ratio_ops = {
67         .set = set_nx_huge_pages_recovery_ratio,
68         .get = param_get_uint,
69 };
70
71 module_param_cb(nx_huge_pages, &nx_huge_pages_ops, &nx_huge_pages, 0644);
72 __MODULE_PARM_TYPE(nx_huge_pages, "bool");
73 module_param_cb(nx_huge_pages_recovery_ratio, &nx_huge_pages_recovery_ratio_ops,
74                 &nx_huge_pages_recovery_ratio, 0644);
75 __MODULE_PARM_TYPE(nx_huge_pages_recovery_ratio, "uint");
76
77 /*
78  * When setting this variable to true it enables Two-Dimensional-Paging
79  * where the hardware walks 2 page tables:
80  * 1. the guest-virtual to guest-physical
81  * 2. while doing 1. it walks guest-physical to host-physical
82  * If the hardware supports that we don't need to do shadow paging.
83  */
84 bool tdp_enabled = false;
85
86 enum {
87         AUDIT_PRE_PAGE_FAULT,
88         AUDIT_POST_PAGE_FAULT,
89         AUDIT_PRE_PTE_WRITE,
90         AUDIT_POST_PTE_WRITE,
91         AUDIT_PRE_SYNC,
92         AUDIT_POST_SYNC
93 };
94
95 #undef MMU_DEBUG
96
97 #ifdef MMU_DEBUG
98 static bool dbg = 0;
99 module_param(dbg, bool, 0644);
100
101 #define pgprintk(x...) do { if (dbg) printk(x); } while (0)
102 #define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
103 #define MMU_WARN_ON(x) WARN_ON(x)
104 #else
105 #define pgprintk(x...) do { } while (0)
106 #define rmap_printk(x...) do { } while (0)
107 #define MMU_WARN_ON(x) do { } while (0)
108 #endif
109
110 #define PTE_PREFETCH_NUM                8
111
112 #define PT_FIRST_AVAIL_BITS_SHIFT 10
113 #define PT64_SECOND_AVAIL_BITS_SHIFT 52
114
115 #define PT64_LEVEL_BITS 9
116
117 #define PT64_LEVEL_SHIFT(level) \
118                 (PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
119
120 #define PT64_INDEX(address, level)\
121         (((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
122
123
124 #define PT32_LEVEL_BITS 10
125
126 #define PT32_LEVEL_SHIFT(level) \
127                 (PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
128
129 #define PT32_LVL_OFFSET_MASK(level) \
130         (PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
131                                                 * PT32_LEVEL_BITS))) - 1))
132
133 #define PT32_INDEX(address, level)\
134         (((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
135
136
137 #define PT64_BASE_ADDR_MASK __sme_clr((((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1)))
138 #define PT64_DIR_BASE_ADDR_MASK \
139         (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + PT64_LEVEL_BITS)) - 1))
140 #define PT64_LVL_ADDR_MASK(level) \
141         (PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
142                                                 * PT64_LEVEL_BITS))) - 1))
143 #define PT64_LVL_OFFSET_MASK(level) \
144         (PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
145                                                 * PT64_LEVEL_BITS))) - 1))
146
147 #define PT32_BASE_ADDR_MASK PAGE_MASK
148 #define PT32_DIR_BASE_ADDR_MASK \
149         (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
150 #define PT32_LVL_ADDR_MASK(level) \
151         (PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
152                                             * PT32_LEVEL_BITS))) - 1))
153
154 #define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
155                         | shadow_x_mask | shadow_nx_mask | shadow_me_mask)
156
157 #define ACC_EXEC_MASK    1
158 #define ACC_WRITE_MASK   PT_WRITABLE_MASK
159 #define ACC_USER_MASK    PT_USER_MASK
160 #define ACC_ALL          (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
161
162 /* The mask for the R/X bits in EPT PTEs */
163 #define PT64_EPT_READABLE_MASK                  0x1ull
164 #define PT64_EPT_EXECUTABLE_MASK                0x4ull
165
166 #include <trace/events/kvm.h>
167
168 #define SPTE_HOST_WRITEABLE     (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
169 #define SPTE_MMU_WRITEABLE      (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
170
171 #define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
172
173 /* make pte_list_desc fit well in cache line */
174 #define PTE_LIST_EXT 3
175
176 /*
177  * Return values of handle_mmio_page_fault and mmu.page_fault:
178  * RET_PF_RETRY: let CPU fault again on the address.
179  * RET_PF_EMULATE: mmio page fault, emulate the instruction directly.
180  *
181  * For handle_mmio_page_fault only:
182  * RET_PF_INVALID: the spte is invalid, let the real page fault path update it.
183  */
184 enum {
185         RET_PF_RETRY = 0,
186         RET_PF_EMULATE = 1,
187         RET_PF_INVALID = 2,
188 };
189
190 struct pte_list_desc {
191         u64 *sptes[PTE_LIST_EXT];
192         struct pte_list_desc *more;
193 };
194
195 struct kvm_shadow_walk_iterator {
196         u64 addr;
197         hpa_t shadow_addr;
198         u64 *sptep;
199         int level;
200         unsigned index;
201 };
202
203 static const union kvm_mmu_page_role mmu_base_role_mask = {
204         .cr0_wp = 1,
205         .cr4_pae = 1,
206         .nxe = 1,
207         .smep_andnot_wp = 1,
208         .smap_andnot_wp = 1,
209         .smm = 1,
210         .guest_mode = 1,
211         .ad_disabled = 1,
212 };
213
214 #define for_each_shadow_entry_using_root(_vcpu, _root, _addr, _walker)     \
215         for (shadow_walk_init_using_root(&(_walker), (_vcpu),              \
216                                          (_root), (_addr));                \
217              shadow_walk_okay(&(_walker));                                 \
218              shadow_walk_next(&(_walker)))
219
220 #define for_each_shadow_entry(_vcpu, _addr, _walker)            \
221         for (shadow_walk_init(&(_walker), _vcpu, _addr);        \
222              shadow_walk_okay(&(_walker));                      \
223              shadow_walk_next(&(_walker)))
224
225 #define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte)     \
226         for (shadow_walk_init(&(_walker), _vcpu, _addr);                \
227              shadow_walk_okay(&(_walker)) &&                            \
228                 ({ spte = mmu_spte_get_lockless(_walker.sptep); 1; });  \
229              __shadow_walk_next(&(_walker), spte))
230
231 static struct kmem_cache *pte_list_desc_cache;
232 static struct kmem_cache *mmu_page_header_cache;
233 static struct percpu_counter kvm_total_used_mmu_pages;
234
235 static u64 __read_mostly shadow_nx_mask;
236 static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
237 static u64 __read_mostly shadow_user_mask;
238 static u64 __read_mostly shadow_accessed_mask;
239 static u64 __read_mostly shadow_dirty_mask;
240 static u64 __read_mostly shadow_mmio_mask;
241 static u64 __read_mostly shadow_mmio_value;
242 static u64 __read_mostly shadow_present_mask;
243 static u64 __read_mostly shadow_me_mask;
244
245 /*
246  * SPTEs used by MMUs without A/D bits are marked with shadow_acc_track_value.
247  * Non-present SPTEs with shadow_acc_track_value set are in place for access
248  * tracking.
249  */
250 static u64 __read_mostly shadow_acc_track_mask;
251 static const u64 shadow_acc_track_value = SPTE_SPECIAL_MASK;
252
253 /*
254  * The mask/shift to use for saving the original R/X bits when marking the PTE
255  * as not-present for access tracking purposes. We do not save the W bit as the
256  * PTEs being access tracked also need to be dirty tracked, so the W bit will be
257  * restored only when a write is attempted to the page.
258  */
259 static const u64 shadow_acc_track_saved_bits_mask = PT64_EPT_READABLE_MASK |
260                                                     PT64_EPT_EXECUTABLE_MASK;
261 static const u64 shadow_acc_track_saved_bits_shift = PT64_SECOND_AVAIL_BITS_SHIFT;
262
263 /*
264  * This mask must be set on all non-zero Non-Present or Reserved SPTEs in order
265  * to guard against L1TF attacks.
266  */
267 static u64 __read_mostly shadow_nonpresent_or_rsvd_mask;
268
269 /*
270  * The number of high-order 1 bits to use in the mask above.
271  */
272 static const u64 shadow_nonpresent_or_rsvd_mask_len = 5;
273
274 /*
275  * In some cases, we need to preserve the GFN of a non-present or reserved
276  * SPTE when we usurp the upper five bits of the physical address space to
277  * defend against L1TF, e.g. for MMIO SPTEs.  To preserve the GFN, we'll
278  * shift bits of the GFN that overlap with shadow_nonpresent_or_rsvd_mask
279  * left into the reserved bits, i.e. the GFN in the SPTE will be split into
280  * high and low parts.  This mask covers the lower bits of the GFN.
281  */
282 static u64 __read_mostly shadow_nonpresent_or_rsvd_lower_gfn_mask;
283
284 /*
285  * The number of non-reserved physical address bits irrespective of features
286  * that repurpose legal bits, e.g. MKTME.
287  */
288 static u8 __read_mostly shadow_phys_bits;
289
290 static void mmu_spte_set(u64 *sptep, u64 spte);
291 static bool is_executable_pte(u64 spte);
292 static union kvm_mmu_page_role
293 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu);
294
295 #define CREATE_TRACE_POINTS
296 #include "mmutrace.h"
297
298
299 void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask, u64 mmio_value)
300 {
301         BUG_ON((mmio_mask & mmio_value) != mmio_value);
302         WARN_ON(mmio_value & (shadow_nonpresent_or_rsvd_mask << shadow_nonpresent_or_rsvd_mask_len));
303         WARN_ON(mmio_value & shadow_nonpresent_or_rsvd_lower_gfn_mask);
304         shadow_mmio_value = mmio_value | SPTE_SPECIAL_MASK;
305         shadow_mmio_mask = mmio_mask | SPTE_SPECIAL_MASK;
306 }
307 EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
308
309 static bool is_mmio_spte(u64 spte)
310 {
311         return (spte & shadow_mmio_mask) == shadow_mmio_value;
312 }
313
314 static inline bool sp_ad_disabled(struct kvm_mmu_page *sp)
315 {
316         return sp->role.ad_disabled;
317 }
318
319 static inline bool spte_ad_enabled(u64 spte)
320 {
321         MMU_WARN_ON(is_mmio_spte(spte));
322         return !(spte & shadow_acc_track_value);
323 }
324
325 static bool is_nx_huge_page_enabled(void)
326 {
327         return READ_ONCE(nx_huge_pages);
328 }
329
330 static inline u64 spte_shadow_accessed_mask(u64 spte)
331 {
332         MMU_WARN_ON(is_mmio_spte(spte));
333         return spte_ad_enabled(spte) ? shadow_accessed_mask : 0;
334 }
335
336 static inline u64 spte_shadow_dirty_mask(u64 spte)
337 {
338         MMU_WARN_ON(is_mmio_spte(spte));
339         return spte_ad_enabled(spte) ? shadow_dirty_mask : 0;
340 }
341
342 static inline bool is_access_track_spte(u64 spte)
343 {
344         return !spte_ad_enabled(spte) && (spte & shadow_acc_track_mask) == 0;
345 }
346
347 /*
348  * the low bit of the generation number is always presumed to be zero.
349  * This disables mmio caching during memslot updates.  The concept is
350  * similar to a seqcount but instead of retrying the access we just punt
351  * and ignore the cache.
352  *
353  * spte bits 3-11 are used as bits 1-9 of the generation number,
354  * the bits 52-61 are used as bits 10-19 of the generation number.
355  */
356 #define MMIO_SPTE_GEN_LOW_SHIFT         2
357 #define MMIO_SPTE_GEN_HIGH_SHIFT        52
358
359 #define MMIO_GEN_SHIFT                  20
360 #define MMIO_GEN_LOW_SHIFT              10
361 #define MMIO_GEN_LOW_MASK               ((1 << MMIO_GEN_LOW_SHIFT) - 2)
362 #define MMIO_GEN_MASK                   ((1 << MMIO_GEN_SHIFT) - 1)
363
364 static u64 generation_mmio_spte_mask(unsigned int gen)
365 {
366         u64 mask;
367
368         WARN_ON(gen & ~MMIO_GEN_MASK);
369
370         mask = (gen & MMIO_GEN_LOW_MASK) << MMIO_SPTE_GEN_LOW_SHIFT;
371         mask |= ((u64)gen >> MMIO_GEN_LOW_SHIFT) << MMIO_SPTE_GEN_HIGH_SHIFT;
372         return mask;
373 }
374
375 static unsigned int get_mmio_spte_generation(u64 spte)
376 {
377         unsigned int gen;
378
379         spte &= ~shadow_mmio_mask;
380
381         gen = (spte >> MMIO_SPTE_GEN_LOW_SHIFT) & MMIO_GEN_LOW_MASK;
382         gen |= (spte >> MMIO_SPTE_GEN_HIGH_SHIFT) << MMIO_GEN_LOW_SHIFT;
383         return gen;
384 }
385
386 static unsigned int kvm_current_mmio_generation(struct kvm_vcpu *vcpu)
387 {
388         return kvm_vcpu_memslots(vcpu)->generation & MMIO_GEN_MASK;
389 }
390
391 static void mark_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 gfn,
392                            unsigned access)
393 {
394         unsigned int gen = kvm_current_mmio_generation(vcpu);
395         u64 mask = generation_mmio_spte_mask(gen);
396         u64 gpa = gfn << PAGE_SHIFT;
397
398         access &= ACC_WRITE_MASK | ACC_USER_MASK;
399         mask |= shadow_mmio_value | access;
400         mask |= gpa | shadow_nonpresent_or_rsvd_mask;
401         mask |= (gpa & shadow_nonpresent_or_rsvd_mask)
402                 << shadow_nonpresent_or_rsvd_mask_len;
403
404         trace_mark_mmio_spte(sptep, gfn, access, gen);
405         mmu_spte_set(sptep, mask);
406 }
407
408 static gfn_t get_mmio_spte_gfn(u64 spte)
409 {
410         u64 gpa = spte & shadow_nonpresent_or_rsvd_lower_gfn_mask;
411
412         gpa |= (spte >> shadow_nonpresent_or_rsvd_mask_len)
413                & shadow_nonpresent_or_rsvd_mask;
414
415         return gpa >> PAGE_SHIFT;
416 }
417
418 static unsigned get_mmio_spte_access(u64 spte)
419 {
420         u64 mask = generation_mmio_spte_mask(MMIO_GEN_MASK) | shadow_mmio_mask;
421         return (spte & ~mask) & ~PAGE_MASK;
422 }
423
424 static bool set_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
425                           kvm_pfn_t pfn, unsigned access)
426 {
427         if (unlikely(is_noslot_pfn(pfn))) {
428                 mark_mmio_spte(vcpu, sptep, gfn, access);
429                 return true;
430         }
431
432         return false;
433 }
434
435 static bool check_mmio_spte(struct kvm_vcpu *vcpu, u64 spte)
436 {
437         unsigned int kvm_gen, spte_gen;
438
439         kvm_gen = kvm_current_mmio_generation(vcpu);
440         spte_gen = get_mmio_spte_generation(spte);
441
442         trace_check_mmio_spte(spte, kvm_gen, spte_gen);
443         return likely(kvm_gen == spte_gen);
444 }
445
446 /*
447  * Sets the shadow PTE masks used by the MMU.
448  *
449  * Assumptions:
450  *  - Setting either @accessed_mask or @dirty_mask requires setting both
451  *  - At least one of @accessed_mask or @acc_track_mask must be set
452  */
453 void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
454                 u64 dirty_mask, u64 nx_mask, u64 x_mask, u64 p_mask,
455                 u64 acc_track_mask, u64 me_mask)
456 {
457         BUG_ON(!dirty_mask != !accessed_mask);
458         BUG_ON(!accessed_mask && !acc_track_mask);
459         BUG_ON(acc_track_mask & shadow_acc_track_value);
460
461         shadow_user_mask = user_mask;
462         shadow_accessed_mask = accessed_mask;
463         shadow_dirty_mask = dirty_mask;
464         shadow_nx_mask = nx_mask;
465         shadow_x_mask = x_mask;
466         shadow_present_mask = p_mask;
467         shadow_acc_track_mask = acc_track_mask;
468         shadow_me_mask = me_mask;
469 }
470 EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
471
472 static u8 kvm_get_shadow_phys_bits(void)
473 {
474         /*
475          * boot_cpu_data.x86_phys_bits is reduced when MKTME is detected
476          * in CPU detection code, but MKTME treats those reduced bits as
477          * 'keyID' thus they are not reserved bits. Therefore for MKTME
478          * we should still return physical address bits reported by CPUID.
479          */
480         if (!boot_cpu_has(X86_FEATURE_TME) ||
481             WARN_ON_ONCE(boot_cpu_data.extended_cpuid_level < 0x80000008))
482                 return boot_cpu_data.x86_phys_bits;
483
484         return cpuid_eax(0x80000008) & 0xff;
485 }
486
487 static void kvm_mmu_reset_all_pte_masks(void)
488 {
489         u8 low_phys_bits;
490
491         shadow_user_mask = 0;
492         shadow_accessed_mask = 0;
493         shadow_dirty_mask = 0;
494         shadow_nx_mask = 0;
495         shadow_x_mask = 0;
496         shadow_mmio_mask = 0;
497         shadow_present_mask = 0;
498         shadow_acc_track_mask = 0;
499
500         shadow_phys_bits = kvm_get_shadow_phys_bits();
501
502         /*
503          * If the CPU has 46 or less physical address bits, then set an
504          * appropriate mask to guard against L1TF attacks. Otherwise, it is
505          * assumed that the CPU is not vulnerable to L1TF.
506          *
507          * Some Intel CPUs address the L1 cache using more PA bits than are
508          * reported by CPUID. Use the PA width of the L1 cache when possible
509          * to achieve more effective mitigation, e.g. if system RAM overlaps
510          * the most significant bits of legal physical address space.
511          */
512         shadow_nonpresent_or_rsvd_mask = 0;
513         low_phys_bits = boot_cpu_data.x86_phys_bits;
514         if (boot_cpu_has_bug(X86_BUG_L1TF) &&
515             !WARN_ON_ONCE(boot_cpu_data.x86_cache_bits >=
516                           52 - shadow_nonpresent_or_rsvd_mask_len)) {
517                 low_phys_bits = boot_cpu_data.x86_cache_bits
518                         - shadow_nonpresent_or_rsvd_mask_len;
519                 shadow_nonpresent_or_rsvd_mask =
520                         rsvd_bits(low_phys_bits, boot_cpu_data.x86_cache_bits - 1);
521         }
522
523         shadow_nonpresent_or_rsvd_lower_gfn_mask =
524                 GENMASK_ULL(low_phys_bits - 1, PAGE_SHIFT);
525 }
526
527 static int is_cpuid_PSE36(void)
528 {
529         return 1;
530 }
531
532 static int is_nx(struct kvm_vcpu *vcpu)
533 {
534         return vcpu->arch.efer & EFER_NX;
535 }
536
537 static int is_shadow_present_pte(u64 pte)
538 {
539         return (pte != 0) && !is_mmio_spte(pte);
540 }
541
542 static int is_large_pte(u64 pte)
543 {
544         return pte & PT_PAGE_SIZE_MASK;
545 }
546
547 static int is_last_spte(u64 pte, int level)
548 {
549         if (level == PT_PAGE_TABLE_LEVEL)
550                 return 1;
551         if (is_large_pte(pte))
552                 return 1;
553         return 0;
554 }
555
556 static bool is_executable_pte(u64 spte)
557 {
558         return (spte & (shadow_x_mask | shadow_nx_mask)) == shadow_x_mask;
559 }
560
561 static kvm_pfn_t spte_to_pfn(u64 pte)
562 {
563         return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
564 }
565
566 static gfn_t pse36_gfn_delta(u32 gpte)
567 {
568         int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
569
570         return (gpte & PT32_DIR_PSE36_MASK) << shift;
571 }
572
573 #ifdef CONFIG_X86_64
574 static void __set_spte(u64 *sptep, u64 spte)
575 {
576         WRITE_ONCE(*sptep, spte);
577 }
578
579 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
580 {
581         WRITE_ONCE(*sptep, spte);
582 }
583
584 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
585 {
586         return xchg(sptep, spte);
587 }
588
589 static u64 __get_spte_lockless(u64 *sptep)
590 {
591         return READ_ONCE(*sptep);
592 }
593 #else
594 union split_spte {
595         struct {
596                 u32 spte_low;
597                 u32 spte_high;
598         };
599         u64 spte;
600 };
601
602 static void count_spte_clear(u64 *sptep, u64 spte)
603 {
604         struct kvm_mmu_page *sp =  page_header(__pa(sptep));
605
606         if (is_shadow_present_pte(spte))
607                 return;
608
609         /* Ensure the spte is completely set before we increase the count */
610         smp_wmb();
611         sp->clear_spte_count++;
612 }
613
614 static void __set_spte(u64 *sptep, u64 spte)
615 {
616         union split_spte *ssptep, sspte;
617
618         ssptep = (union split_spte *)sptep;
619         sspte = (union split_spte)spte;
620
621         ssptep->spte_high = sspte.spte_high;
622
623         /*
624          * If we map the spte from nonpresent to present, We should store
625          * the high bits firstly, then set present bit, so cpu can not
626          * fetch this spte while we are setting the spte.
627          */
628         smp_wmb();
629
630         WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
631 }
632
633 static void __update_clear_spte_fast(u64 *sptep, u64 spte)
634 {
635         union split_spte *ssptep, sspte;
636
637         ssptep = (union split_spte *)sptep;
638         sspte = (union split_spte)spte;
639
640         WRITE_ONCE(ssptep->spte_low, sspte.spte_low);
641
642         /*
643          * If we map the spte from present to nonpresent, we should clear
644          * present bit firstly to avoid vcpu fetch the old high bits.
645          */
646         smp_wmb();
647
648         ssptep->spte_high = sspte.spte_high;
649         count_spte_clear(sptep, spte);
650 }
651
652 static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
653 {
654         union split_spte *ssptep, sspte, orig;
655
656         ssptep = (union split_spte *)sptep;
657         sspte = (union split_spte)spte;
658
659         /* xchg acts as a barrier before the setting of the high bits */
660         orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
661         orig.spte_high = ssptep->spte_high;
662         ssptep->spte_high = sspte.spte_high;
663         count_spte_clear(sptep, spte);
664
665         return orig.spte;
666 }
667
668 /*
669  * The idea using the light way get the spte on x86_32 guest is from
670  * gup_get_pte(arch/x86/mm/gup.c).
671  *
672  * An spte tlb flush may be pending, because kvm_set_pte_rmapp
673  * coalesces them and we are running out of the MMU lock.  Therefore
674  * we need to protect against in-progress updates of the spte.
675  *
676  * Reading the spte while an update is in progress may get the old value
677  * for the high part of the spte.  The race is fine for a present->non-present
678  * change (because the high part of the spte is ignored for non-present spte),
679  * but for a present->present change we must reread the spte.
680  *
681  * All such changes are done in two steps (present->non-present and
682  * non-present->present), hence it is enough to count the number of
683  * present->non-present updates: if it changed while reading the spte,
684  * we might have hit the race.  This is done using clear_spte_count.
685  */
686 static u64 __get_spte_lockless(u64 *sptep)
687 {
688         struct kvm_mmu_page *sp =  page_header(__pa(sptep));
689         union split_spte spte, *orig = (union split_spte *)sptep;
690         int count;
691
692 retry:
693         count = sp->clear_spte_count;
694         smp_rmb();
695
696         spte.spte_low = orig->spte_low;
697         smp_rmb();
698
699         spte.spte_high = orig->spte_high;
700         smp_rmb();
701
702         if (unlikely(spte.spte_low != orig->spte_low ||
703               count != sp->clear_spte_count))
704                 goto retry;
705
706         return spte.spte;
707 }
708 #endif
709
710 static bool spte_can_locklessly_be_made_writable(u64 spte)
711 {
712         return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
713                 (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
714 }
715
716 static bool spte_has_volatile_bits(u64 spte)
717 {
718         if (!is_shadow_present_pte(spte))
719                 return false;
720
721         /*
722          * Always atomically update spte if it can be updated
723          * out of mmu-lock, it can ensure dirty bit is not lost,
724          * also, it can help us to get a stable is_writable_pte()
725          * to ensure tlb flush is not missed.
726          */
727         if (spte_can_locklessly_be_made_writable(spte) ||
728             is_access_track_spte(spte))
729                 return true;
730
731         if (spte_ad_enabled(spte)) {
732                 if ((spte & shadow_accessed_mask) == 0 ||
733                     (is_writable_pte(spte) && (spte & shadow_dirty_mask) == 0))
734                         return true;
735         }
736
737         return false;
738 }
739
740 static bool is_accessed_spte(u64 spte)
741 {
742         u64 accessed_mask = spte_shadow_accessed_mask(spte);
743
744         return accessed_mask ? spte & accessed_mask
745                              : !is_access_track_spte(spte);
746 }
747
748 static bool is_dirty_spte(u64 spte)
749 {
750         u64 dirty_mask = spte_shadow_dirty_mask(spte);
751
752         return dirty_mask ? spte & dirty_mask : spte & PT_WRITABLE_MASK;
753 }
754
755 /* Rules for using mmu_spte_set:
756  * Set the sptep from nonpresent to present.
757  * Note: the sptep being assigned *must* be either not present
758  * or in a state where the hardware will not attempt to update
759  * the spte.
760  */
761 static void mmu_spte_set(u64 *sptep, u64 new_spte)
762 {
763         WARN_ON(is_shadow_present_pte(*sptep));
764         __set_spte(sptep, new_spte);
765 }
766
767 /*
768  * Update the SPTE (excluding the PFN), but do not track changes in its
769  * accessed/dirty status.
770  */
771 static u64 mmu_spte_update_no_track(u64 *sptep, u64 new_spte)
772 {
773         u64 old_spte = *sptep;
774
775         WARN_ON(!is_shadow_present_pte(new_spte));
776
777         if (!is_shadow_present_pte(old_spte)) {
778                 mmu_spte_set(sptep, new_spte);
779                 return old_spte;
780         }
781
782         if (!spte_has_volatile_bits(old_spte))
783                 __update_clear_spte_fast(sptep, new_spte);
784         else
785                 old_spte = __update_clear_spte_slow(sptep, new_spte);
786
787         WARN_ON(spte_to_pfn(old_spte) != spte_to_pfn(new_spte));
788
789         return old_spte;
790 }
791
792 /* Rules for using mmu_spte_update:
793  * Update the state bits, it means the mapped pfn is not changed.
794  *
795  * Whenever we overwrite a writable spte with a read-only one we
796  * should flush remote TLBs. Otherwise rmap_write_protect
797  * will find a read-only spte, even though the writable spte
798  * might be cached on a CPU's TLB, the return value indicates this
799  * case.
800  *
801  * Returns true if the TLB needs to be flushed
802  */
803 static bool mmu_spte_update(u64 *sptep, u64 new_spte)
804 {
805         bool flush = false;
806         u64 old_spte = mmu_spte_update_no_track(sptep, new_spte);
807
808         if (!is_shadow_present_pte(old_spte))
809                 return false;
810
811         /*
812          * For the spte updated out of mmu-lock is safe, since
813          * we always atomically update it, see the comments in
814          * spte_has_volatile_bits().
815          */
816         if (spte_can_locklessly_be_made_writable(old_spte) &&
817               !is_writable_pte(new_spte))
818                 flush = true;
819
820         /*
821          * Flush TLB when accessed/dirty states are changed in the page tables,
822          * to guarantee consistency between TLB and page tables.
823          */
824
825         if (is_accessed_spte(old_spte) && !is_accessed_spte(new_spte)) {
826                 flush = true;
827                 kvm_set_pfn_accessed(spte_to_pfn(old_spte));
828         }
829
830         if (is_dirty_spte(old_spte) && !is_dirty_spte(new_spte)) {
831                 flush = true;
832                 kvm_set_pfn_dirty(spte_to_pfn(old_spte));
833         }
834
835         return flush;
836 }
837
838 /*
839  * Rules for using mmu_spte_clear_track_bits:
840  * It sets the sptep from present to nonpresent, and track the
841  * state bits, it is used to clear the last level sptep.
842  * Returns non-zero if the PTE was previously valid.
843  */
844 static int mmu_spte_clear_track_bits(u64 *sptep)
845 {
846         kvm_pfn_t pfn;
847         u64 old_spte = *sptep;
848
849         if (!spte_has_volatile_bits(old_spte))
850                 __update_clear_spte_fast(sptep, 0ull);
851         else
852                 old_spte = __update_clear_spte_slow(sptep, 0ull);
853
854         if (!is_shadow_present_pte(old_spte))
855                 return 0;
856
857         pfn = spte_to_pfn(old_spte);
858
859         /*
860          * KVM does not hold the refcount of the page used by
861          * kvm mmu, before reclaiming the page, we should
862          * unmap it from mmu first.
863          */
864         WARN_ON(!kvm_is_reserved_pfn(pfn) && !page_count(pfn_to_page(pfn)));
865
866         if (is_accessed_spte(old_spte))
867                 kvm_set_pfn_accessed(pfn);
868
869         if (is_dirty_spte(old_spte))
870                 kvm_set_pfn_dirty(pfn);
871
872         return 1;
873 }
874
875 /*
876  * Rules for using mmu_spte_clear_no_track:
877  * Directly clear spte without caring the state bits of sptep,
878  * it is used to set the upper level spte.
879  */
880 static void mmu_spte_clear_no_track(u64 *sptep)
881 {
882         __update_clear_spte_fast(sptep, 0ull);
883 }
884
885 static u64 mmu_spte_get_lockless(u64 *sptep)
886 {
887         return __get_spte_lockless(sptep);
888 }
889
890 static u64 mark_spte_for_access_track(u64 spte)
891 {
892         if (spte_ad_enabled(spte))
893                 return spte & ~shadow_accessed_mask;
894
895         if (is_access_track_spte(spte))
896                 return spte;
897
898         /*
899          * Making an Access Tracking PTE will result in removal of write access
900          * from the PTE. So, verify that we will be able to restore the write
901          * access in the fast page fault path later on.
902          */
903         WARN_ONCE((spte & PT_WRITABLE_MASK) &&
904                   !spte_can_locklessly_be_made_writable(spte),
905                   "kvm: Writable SPTE is not locklessly dirty-trackable\n");
906
907         WARN_ONCE(spte & (shadow_acc_track_saved_bits_mask <<
908                           shadow_acc_track_saved_bits_shift),
909                   "kvm: Access Tracking saved bit locations are not zero\n");
910
911         spte |= (spte & shadow_acc_track_saved_bits_mask) <<
912                 shadow_acc_track_saved_bits_shift;
913         spte &= ~shadow_acc_track_mask;
914
915         return spte;
916 }
917
918 /* Restore an acc-track PTE back to a regular PTE */
919 static u64 restore_acc_track_spte(u64 spte)
920 {
921         u64 new_spte = spte;
922         u64 saved_bits = (spte >> shadow_acc_track_saved_bits_shift)
923                          & shadow_acc_track_saved_bits_mask;
924
925         WARN_ON_ONCE(spte_ad_enabled(spte));
926         WARN_ON_ONCE(!is_access_track_spte(spte));
927
928         new_spte &= ~shadow_acc_track_mask;
929         new_spte &= ~(shadow_acc_track_saved_bits_mask <<
930                       shadow_acc_track_saved_bits_shift);
931         new_spte |= saved_bits;
932
933         return new_spte;
934 }
935
936 /* Returns the Accessed status of the PTE and resets it at the same time. */
937 static bool mmu_spte_age(u64 *sptep)
938 {
939         u64 spte = mmu_spte_get_lockless(sptep);
940
941         if (!is_accessed_spte(spte))
942                 return false;
943
944         if (spte_ad_enabled(spte)) {
945                 clear_bit((ffs(shadow_accessed_mask) - 1),
946                           (unsigned long *)sptep);
947         } else {
948                 /*
949                  * Capture the dirty status of the page, so that it doesn't get
950                  * lost when the SPTE is marked for access tracking.
951                  */
952                 if (is_writable_pte(spte))
953                         kvm_set_pfn_dirty(spte_to_pfn(spte));
954
955                 spte = mark_spte_for_access_track(spte);
956                 mmu_spte_update_no_track(sptep, spte);
957         }
958
959         return true;
960 }
961
962 static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
963 {
964         /*
965          * Prevent page table teardown by making any free-er wait during
966          * kvm_flush_remote_tlbs() IPI to all active vcpus.
967          */
968         local_irq_disable();
969
970         /*
971          * Make sure a following spte read is not reordered ahead of the write
972          * to vcpu->mode.
973          */
974         smp_store_mb(vcpu->mode, READING_SHADOW_PAGE_TABLES);
975 }
976
977 static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
978 {
979         /*
980          * Make sure the write to vcpu->mode is not reordered in front of
981          * reads to sptes.  If it does, kvm_mmu_commit_zap_page() can see us
982          * OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
983          */
984         smp_store_release(&vcpu->mode, OUTSIDE_GUEST_MODE);
985         local_irq_enable();
986 }
987
988 static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
989                                   struct kmem_cache *base_cache, int min)
990 {
991         void *obj;
992
993         if (cache->nobjs >= min)
994                 return 0;
995         while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
996                 obj = kmem_cache_zalloc(base_cache, GFP_KERNEL);
997                 if (!obj)
998                         return -ENOMEM;
999                 cache->objects[cache->nobjs++] = obj;
1000         }
1001         return 0;
1002 }
1003
1004 static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
1005 {
1006         return cache->nobjs;
1007 }
1008
1009 static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
1010                                   struct kmem_cache *cache)
1011 {
1012         while (mc->nobjs)
1013                 kmem_cache_free(cache, mc->objects[--mc->nobjs]);
1014 }
1015
1016 static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
1017                                        int min)
1018 {
1019         void *page;
1020
1021         if (cache->nobjs >= min)
1022                 return 0;
1023         while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
1024                 page = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
1025                 if (!page)
1026                         return -ENOMEM;
1027                 cache->objects[cache->nobjs++] = page;
1028         }
1029         return 0;
1030 }
1031
1032 static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
1033 {
1034         while (mc->nobjs)
1035                 free_page((unsigned long)mc->objects[--mc->nobjs]);
1036 }
1037
1038 static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
1039 {
1040         int r;
1041
1042         r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1043                                    pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
1044         if (r)
1045                 goto out;
1046         r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
1047         if (r)
1048                 goto out;
1049         r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
1050                                    mmu_page_header_cache, 4);
1051 out:
1052         return r;
1053 }
1054
1055 static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
1056 {
1057         mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
1058                                 pte_list_desc_cache);
1059         mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
1060         mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
1061                                 mmu_page_header_cache);
1062 }
1063
1064 static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
1065 {
1066         void *p;
1067
1068         BUG_ON(!mc->nobjs);
1069         p = mc->objects[--mc->nobjs];
1070         return p;
1071 }
1072
1073 static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
1074 {
1075         return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
1076 }
1077
1078 static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
1079 {
1080         kmem_cache_free(pte_list_desc_cache, pte_list_desc);
1081 }
1082
1083 static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
1084 {
1085         if (!sp->role.direct)
1086                 return sp->gfns[index];
1087
1088         return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
1089 }
1090
1091 static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
1092 {
1093         if (!sp->role.direct) {
1094                 sp->gfns[index] = gfn;
1095                 return;
1096         }
1097
1098         if (WARN_ON(gfn != kvm_mmu_page_get_gfn(sp, index)))
1099                 pr_err_ratelimited("gfn mismatch under direct page %llx "
1100                                    "(expected %llx, got %llx)\n",
1101                                    sp->gfn,
1102                                    kvm_mmu_page_get_gfn(sp, index), gfn);
1103 }
1104
1105 /*
1106  * Return the pointer to the large page information for a given gfn,
1107  * handling slots that are not large page aligned.
1108  */
1109 static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
1110                                               struct kvm_memory_slot *slot,
1111                                               int level)
1112 {
1113         unsigned long idx;
1114
1115         idx = gfn_to_index(gfn, slot->base_gfn, level);
1116         return &slot->arch.lpage_info[level - 2][idx];
1117 }
1118
1119 static void update_gfn_disallow_lpage_count(struct kvm_memory_slot *slot,
1120                                             gfn_t gfn, int count)
1121 {
1122         struct kvm_lpage_info *linfo;
1123         int i;
1124
1125         for (i = PT_DIRECTORY_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1126                 linfo = lpage_info_slot(gfn, slot, i);
1127                 linfo->disallow_lpage += count;
1128                 WARN_ON(linfo->disallow_lpage < 0);
1129         }
1130 }
1131
1132 void kvm_mmu_gfn_disallow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1133 {
1134         update_gfn_disallow_lpage_count(slot, gfn, 1);
1135 }
1136
1137 void kvm_mmu_gfn_allow_lpage(struct kvm_memory_slot *slot, gfn_t gfn)
1138 {
1139         update_gfn_disallow_lpage_count(slot, gfn, -1);
1140 }
1141
1142 static void account_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1143 {
1144         struct kvm_memslots *slots;
1145         struct kvm_memory_slot *slot;
1146         gfn_t gfn;
1147
1148         kvm->arch.indirect_shadow_pages++;
1149         gfn = sp->gfn;
1150         slots = kvm_memslots_for_spte_role(kvm, sp->role);
1151         slot = __gfn_to_memslot(slots, gfn);
1152
1153         /* the non-leaf shadow pages are keeping readonly. */
1154         if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1155                 return kvm_slot_page_track_add_page(kvm, slot, gfn,
1156                                                     KVM_PAGE_TRACK_WRITE);
1157
1158         kvm_mmu_gfn_disallow_lpage(slot, gfn);
1159 }
1160
1161 static void account_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1162 {
1163         if (sp->lpage_disallowed)
1164                 return;
1165
1166         ++kvm->stat.nx_lpage_splits;
1167         list_add_tail(&sp->lpage_disallowed_link,
1168                       &kvm->arch.lpage_disallowed_mmu_pages);
1169         sp->lpage_disallowed = true;
1170 }
1171
1172 static void unaccount_shadowed(struct kvm *kvm, struct kvm_mmu_page *sp)
1173 {
1174         struct kvm_memslots *slots;
1175         struct kvm_memory_slot *slot;
1176         gfn_t gfn;
1177
1178         kvm->arch.indirect_shadow_pages--;
1179         gfn = sp->gfn;
1180         slots = kvm_memslots_for_spte_role(kvm, sp->role);
1181         slot = __gfn_to_memslot(slots, gfn);
1182         if (sp->role.level > PT_PAGE_TABLE_LEVEL)
1183                 return kvm_slot_page_track_remove_page(kvm, slot, gfn,
1184                                                        KVM_PAGE_TRACK_WRITE);
1185
1186         kvm_mmu_gfn_allow_lpage(slot, gfn);
1187 }
1188
1189 static void unaccount_huge_nx_page(struct kvm *kvm, struct kvm_mmu_page *sp)
1190 {
1191         --kvm->stat.nx_lpage_splits;
1192         sp->lpage_disallowed = false;
1193         list_del(&sp->lpage_disallowed_link);
1194 }
1195
1196 static bool __mmu_gfn_lpage_is_disallowed(gfn_t gfn, int level,
1197                                           struct kvm_memory_slot *slot)
1198 {
1199         struct kvm_lpage_info *linfo;
1200
1201         if (slot) {
1202                 linfo = lpage_info_slot(gfn, slot, level);
1203                 return !!linfo->disallow_lpage;
1204         }
1205
1206         return true;
1207 }
1208
1209 static bool mmu_gfn_lpage_is_disallowed(struct kvm_vcpu *vcpu, gfn_t gfn,
1210                                         int level)
1211 {
1212         struct kvm_memory_slot *slot;
1213
1214         slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1215         return __mmu_gfn_lpage_is_disallowed(gfn, level, slot);
1216 }
1217
1218 static int host_mapping_level(struct kvm_vcpu *vcpu, gfn_t gfn)
1219 {
1220         unsigned long page_size;
1221         int i, ret = 0;
1222
1223         page_size = kvm_host_page_size(vcpu, gfn);
1224
1225         for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1226                 if (page_size >= KVM_HPAGE_SIZE(i))
1227                         ret = i;
1228                 else
1229                         break;
1230         }
1231
1232         return ret;
1233 }
1234
1235 static inline bool memslot_valid_for_gpte(struct kvm_memory_slot *slot,
1236                                           bool no_dirty_log)
1237 {
1238         if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
1239                 return false;
1240         if (no_dirty_log && slot->dirty_bitmap)
1241                 return false;
1242
1243         return true;
1244 }
1245
1246 static struct kvm_memory_slot *
1247 gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
1248                             bool no_dirty_log)
1249 {
1250         struct kvm_memory_slot *slot;
1251
1252         slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1253         if (!memslot_valid_for_gpte(slot, no_dirty_log))
1254                 slot = NULL;
1255
1256         return slot;
1257 }
1258
1259 static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn,
1260                          bool *force_pt_level)
1261 {
1262         int host_level, level, max_level;
1263         struct kvm_memory_slot *slot;
1264
1265         if (unlikely(*force_pt_level))
1266                 return PT_PAGE_TABLE_LEVEL;
1267
1268         slot = kvm_vcpu_gfn_to_memslot(vcpu, large_gfn);
1269         *force_pt_level = !memslot_valid_for_gpte(slot, true);
1270         if (unlikely(*force_pt_level))
1271                 return PT_PAGE_TABLE_LEVEL;
1272
1273         host_level = host_mapping_level(vcpu, large_gfn);
1274
1275         if (host_level == PT_PAGE_TABLE_LEVEL)
1276                 return host_level;
1277
1278         max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
1279
1280         for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
1281                 if (__mmu_gfn_lpage_is_disallowed(large_gfn, level, slot))
1282                         break;
1283
1284         return level - 1;
1285 }
1286
1287 /*
1288  * About rmap_head encoding:
1289  *
1290  * If the bit zero of rmap_head->val is clear, then it points to the only spte
1291  * in this rmap chain. Otherwise, (rmap_head->val & ~1) points to a struct
1292  * pte_list_desc containing more mappings.
1293  */
1294
1295 /*
1296  * Returns the number of pointers in the rmap chain, not counting the new one.
1297  */
1298 static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
1299                         struct kvm_rmap_head *rmap_head)
1300 {
1301         struct pte_list_desc *desc;
1302         int i, count = 0;
1303
1304         if (!rmap_head->val) {
1305                 rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
1306                 rmap_head->val = (unsigned long)spte;
1307         } else if (!(rmap_head->val & 1)) {
1308                 rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
1309                 desc = mmu_alloc_pte_list_desc(vcpu);
1310                 desc->sptes[0] = (u64 *)rmap_head->val;
1311                 desc->sptes[1] = spte;
1312                 rmap_head->val = (unsigned long)desc | 1;
1313                 ++count;
1314         } else {
1315                 rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
1316                 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1317                 while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
1318                         desc = desc->more;
1319                         count += PTE_LIST_EXT;
1320                 }
1321                 if (desc->sptes[PTE_LIST_EXT-1]) {
1322                         desc->more = mmu_alloc_pte_list_desc(vcpu);
1323                         desc = desc->more;
1324                 }
1325                 for (i = 0; desc->sptes[i]; ++i)
1326                         ++count;
1327                 desc->sptes[i] = spte;
1328         }
1329         return count;
1330 }
1331
1332 static void
1333 pte_list_desc_remove_entry(struct kvm_rmap_head *rmap_head,
1334                            struct pte_list_desc *desc, int i,
1335                            struct pte_list_desc *prev_desc)
1336 {
1337         int j;
1338
1339         for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
1340                 ;
1341         desc->sptes[i] = desc->sptes[j];
1342         desc->sptes[j] = NULL;
1343         if (j != 0)
1344                 return;
1345         if (!prev_desc && !desc->more)
1346                 rmap_head->val = (unsigned long)desc->sptes[0];
1347         else
1348                 if (prev_desc)
1349                         prev_desc->more = desc->more;
1350                 else
1351                         rmap_head->val = (unsigned long)desc->more | 1;
1352         mmu_free_pte_list_desc(desc);
1353 }
1354
1355 static void pte_list_remove(u64 *spte, struct kvm_rmap_head *rmap_head)
1356 {
1357         struct pte_list_desc *desc;
1358         struct pte_list_desc *prev_desc;
1359         int i;
1360
1361         if (!rmap_head->val) {
1362                 printk(KERN_ERR "pte_list_remove: %p 0->BUG\n", spte);
1363                 BUG();
1364         } else if (!(rmap_head->val & 1)) {
1365                 rmap_printk("pte_list_remove:  %p 1->0\n", spte);
1366                 if ((u64 *)rmap_head->val != spte) {
1367                         printk(KERN_ERR "pte_list_remove:  %p 1->BUG\n", spte);
1368                         BUG();
1369                 }
1370                 rmap_head->val = 0;
1371         } else {
1372                 rmap_printk("pte_list_remove:  %p many->many\n", spte);
1373                 desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1374                 prev_desc = NULL;
1375                 while (desc) {
1376                         for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i) {
1377                                 if (desc->sptes[i] == spte) {
1378                                         pte_list_desc_remove_entry(rmap_head,
1379                                                         desc, i, prev_desc);
1380                                         return;
1381                                 }
1382                         }
1383                         prev_desc = desc;
1384                         desc = desc->more;
1385                 }
1386                 pr_err("pte_list_remove: %p many->many\n", spte);
1387                 BUG();
1388         }
1389 }
1390
1391 static struct kvm_rmap_head *__gfn_to_rmap(gfn_t gfn, int level,
1392                                            struct kvm_memory_slot *slot)
1393 {
1394         unsigned long idx;
1395
1396         idx = gfn_to_index(gfn, slot->base_gfn, level);
1397         return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
1398 }
1399
1400 static struct kvm_rmap_head *gfn_to_rmap(struct kvm *kvm, gfn_t gfn,
1401                                          struct kvm_mmu_page *sp)
1402 {
1403         struct kvm_memslots *slots;
1404         struct kvm_memory_slot *slot;
1405
1406         slots = kvm_memslots_for_spte_role(kvm, sp->role);
1407         slot = __gfn_to_memslot(slots, gfn);
1408         return __gfn_to_rmap(gfn, sp->role.level, slot);
1409 }
1410
1411 static bool rmap_can_add(struct kvm_vcpu *vcpu)
1412 {
1413         struct kvm_mmu_memory_cache *cache;
1414
1415         cache = &vcpu->arch.mmu_pte_list_desc_cache;
1416         return mmu_memory_cache_free_objects(cache);
1417 }
1418
1419 static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
1420 {
1421         struct kvm_mmu_page *sp;
1422         struct kvm_rmap_head *rmap_head;
1423
1424         sp = page_header(__pa(spte));
1425         kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
1426         rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
1427         return pte_list_add(vcpu, spte, rmap_head);
1428 }
1429
1430 static void rmap_remove(struct kvm *kvm, u64 *spte)
1431 {
1432         struct kvm_mmu_page *sp;
1433         gfn_t gfn;
1434         struct kvm_rmap_head *rmap_head;
1435
1436         sp = page_header(__pa(spte));
1437         gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
1438         rmap_head = gfn_to_rmap(kvm, gfn, sp);
1439         pte_list_remove(spte, rmap_head);
1440 }
1441
1442 /*
1443  * Used by the following functions to iterate through the sptes linked by a
1444  * rmap.  All fields are private and not assumed to be used outside.
1445  */
1446 struct rmap_iterator {
1447         /* private fields */
1448         struct pte_list_desc *desc;     /* holds the sptep if not NULL */
1449         int pos;                        /* index of the sptep */
1450 };
1451
1452 /*
1453  * Iteration must be started by this function.  This should also be used after
1454  * removing/dropping sptes from the rmap link because in such cases the
1455  * information in the itererator may not be valid.
1456  *
1457  * Returns sptep if found, NULL otherwise.
1458  */
1459 static u64 *rmap_get_first(struct kvm_rmap_head *rmap_head,
1460                            struct rmap_iterator *iter)
1461 {
1462         u64 *sptep;
1463
1464         if (!rmap_head->val)
1465                 return NULL;
1466
1467         if (!(rmap_head->val & 1)) {
1468                 iter->desc = NULL;
1469                 sptep = (u64 *)rmap_head->val;
1470                 goto out;
1471         }
1472
1473         iter->desc = (struct pte_list_desc *)(rmap_head->val & ~1ul);
1474         iter->pos = 0;
1475         sptep = iter->desc->sptes[iter->pos];
1476 out:
1477         BUG_ON(!is_shadow_present_pte(*sptep));
1478         return sptep;
1479 }
1480
1481 /*
1482  * Must be used with a valid iterator: e.g. after rmap_get_first().
1483  *
1484  * Returns sptep if found, NULL otherwise.
1485  */
1486 static u64 *rmap_get_next(struct rmap_iterator *iter)
1487 {
1488         u64 *sptep;
1489
1490         if (iter->desc) {
1491                 if (iter->pos < PTE_LIST_EXT - 1) {
1492                         ++iter->pos;
1493                         sptep = iter->desc->sptes[iter->pos];
1494                         if (sptep)
1495                                 goto out;
1496                 }
1497
1498                 iter->desc = iter->desc->more;
1499
1500                 if (iter->desc) {
1501                         iter->pos = 0;
1502                         /* desc->sptes[0] cannot be NULL */
1503                         sptep = iter->desc->sptes[iter->pos];
1504                         goto out;
1505                 }
1506         }
1507
1508         return NULL;
1509 out:
1510         BUG_ON(!is_shadow_present_pte(*sptep));
1511         return sptep;
1512 }
1513
1514 #define for_each_rmap_spte(_rmap_head_, _iter_, _spte_)                 \
1515         for (_spte_ = rmap_get_first(_rmap_head_, _iter_);              \
1516              _spte_; _spte_ = rmap_get_next(_iter_))
1517
1518 static void drop_spte(struct kvm *kvm, u64 *sptep)
1519 {
1520         if (mmu_spte_clear_track_bits(sptep))
1521                 rmap_remove(kvm, sptep);
1522 }
1523
1524
1525 static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
1526 {
1527         if (is_large_pte(*sptep)) {
1528                 WARN_ON(page_header(__pa(sptep))->role.level ==
1529                         PT_PAGE_TABLE_LEVEL);
1530                 drop_spte(kvm, sptep);
1531                 --kvm->stat.lpages;
1532                 return true;
1533         }
1534
1535         return false;
1536 }
1537
1538 static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
1539 {
1540         if (__drop_large_spte(vcpu->kvm, sptep))
1541                 kvm_flush_remote_tlbs(vcpu->kvm);
1542 }
1543
1544 /*
1545  * Write-protect on the specified @sptep, @pt_protect indicates whether
1546  * spte write-protection is caused by protecting shadow page table.
1547  *
1548  * Note: write protection is difference between dirty logging and spte
1549  * protection:
1550  * - for dirty logging, the spte can be set to writable at anytime if
1551  *   its dirty bitmap is properly set.
1552  * - for spte protection, the spte can be writable only after unsync-ing
1553  *   shadow page.
1554  *
1555  * Return true if tlb need be flushed.
1556  */
1557 static bool spte_write_protect(u64 *sptep, bool pt_protect)
1558 {
1559         u64 spte = *sptep;
1560
1561         if (!is_writable_pte(spte) &&
1562               !(pt_protect && spte_can_locklessly_be_made_writable(spte)))
1563                 return false;
1564
1565         rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
1566
1567         if (pt_protect)
1568                 spte &= ~SPTE_MMU_WRITEABLE;
1569         spte = spte & ~PT_WRITABLE_MASK;
1570
1571         return mmu_spte_update(sptep, spte);
1572 }
1573
1574 static bool __rmap_write_protect(struct kvm *kvm,
1575                                  struct kvm_rmap_head *rmap_head,
1576                                  bool pt_protect)
1577 {
1578         u64 *sptep;
1579         struct rmap_iterator iter;
1580         bool flush = false;
1581
1582         for_each_rmap_spte(rmap_head, &iter, sptep)
1583                 flush |= spte_write_protect(sptep, pt_protect);
1584
1585         return flush;
1586 }
1587
1588 static bool spte_clear_dirty(u64 *sptep)
1589 {
1590         u64 spte = *sptep;
1591
1592         rmap_printk("rmap_clear_dirty: spte %p %llx\n", sptep, *sptep);
1593
1594         spte &= ~shadow_dirty_mask;
1595
1596         return mmu_spte_update(sptep, spte);
1597 }
1598
1599 static bool wrprot_ad_disabled_spte(u64 *sptep)
1600 {
1601         bool was_writable = test_and_clear_bit(PT_WRITABLE_SHIFT,
1602                                                (unsigned long *)sptep);
1603         if (was_writable)
1604                 kvm_set_pfn_dirty(spte_to_pfn(*sptep));
1605
1606         return was_writable;
1607 }
1608
1609 /*
1610  * Gets the GFN ready for another round of dirty logging by clearing the
1611  *      - D bit on ad-enabled SPTEs, and
1612  *      - W bit on ad-disabled SPTEs.
1613  * Returns true iff any D or W bits were cleared.
1614  */
1615 static bool __rmap_clear_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1616 {
1617         u64 *sptep;
1618         struct rmap_iterator iter;
1619         bool flush = false;
1620
1621         for_each_rmap_spte(rmap_head, &iter, sptep)
1622                 if (spte_ad_enabled(*sptep))
1623                         flush |= spte_clear_dirty(sptep);
1624                 else
1625                         flush |= wrprot_ad_disabled_spte(sptep);
1626
1627         return flush;
1628 }
1629
1630 static bool spte_set_dirty(u64 *sptep)
1631 {
1632         u64 spte = *sptep;
1633
1634         rmap_printk("rmap_set_dirty: spte %p %llx\n", sptep, *sptep);
1635
1636         spte |= shadow_dirty_mask;
1637
1638         return mmu_spte_update(sptep, spte);
1639 }
1640
1641 static bool __rmap_set_dirty(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1642 {
1643         u64 *sptep;
1644         struct rmap_iterator iter;
1645         bool flush = false;
1646
1647         for_each_rmap_spte(rmap_head, &iter, sptep)
1648                 if (spte_ad_enabled(*sptep))
1649                         flush |= spte_set_dirty(sptep);
1650
1651         return flush;
1652 }
1653
1654 /**
1655  * kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
1656  * @kvm: kvm instance
1657  * @slot: slot to protect
1658  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1659  * @mask: indicates which pages we should protect
1660  *
1661  * Used when we do not need to care about huge page mappings: e.g. during dirty
1662  * logging we do not have any such mappings.
1663  */
1664 static void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
1665                                      struct kvm_memory_slot *slot,
1666                                      gfn_t gfn_offset, unsigned long mask)
1667 {
1668         struct kvm_rmap_head *rmap_head;
1669
1670         while (mask) {
1671                 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1672                                           PT_PAGE_TABLE_LEVEL, slot);
1673                 __rmap_write_protect(kvm, rmap_head, false);
1674
1675                 /* clear the first set bit */
1676                 mask &= mask - 1;
1677         }
1678 }
1679
1680 /**
1681  * kvm_mmu_clear_dirty_pt_masked - clear MMU D-bit for PT level pages, or write
1682  * protect the page if the D-bit isn't supported.
1683  * @kvm: kvm instance
1684  * @slot: slot to clear D-bit
1685  * @gfn_offset: start of the BITS_PER_LONG pages we care about
1686  * @mask: indicates which pages we should clear D-bit
1687  *
1688  * Used for PML to re-log the dirty GPAs after userspace querying dirty_bitmap.
1689  */
1690 void kvm_mmu_clear_dirty_pt_masked(struct kvm *kvm,
1691                                      struct kvm_memory_slot *slot,
1692                                      gfn_t gfn_offset, unsigned long mask)
1693 {
1694         struct kvm_rmap_head *rmap_head;
1695
1696         while (mask) {
1697                 rmap_head = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
1698                                           PT_PAGE_TABLE_LEVEL, slot);
1699                 __rmap_clear_dirty(kvm, rmap_head);
1700
1701                 /* clear the first set bit */
1702                 mask &= mask - 1;
1703         }
1704 }
1705 EXPORT_SYMBOL_GPL(kvm_mmu_clear_dirty_pt_masked);
1706
1707 /**
1708  * kvm_arch_mmu_enable_log_dirty_pt_masked - enable dirty logging for selected
1709  * PT level pages.
1710  *
1711  * It calls kvm_mmu_write_protect_pt_masked to write protect selected pages to
1712  * enable dirty logging for them.
1713  *
1714  * Used when we do not need to care about huge page mappings: e.g. during dirty
1715  * logging we do not have any such mappings.
1716  */
1717 void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
1718                                 struct kvm_memory_slot *slot,
1719                                 gfn_t gfn_offset, unsigned long mask)
1720 {
1721         if (kvm_x86_ops->enable_log_dirty_pt_masked)
1722                 kvm_x86_ops->enable_log_dirty_pt_masked(kvm, slot, gfn_offset,
1723                                 mask);
1724         else
1725                 kvm_mmu_write_protect_pt_masked(kvm, slot, gfn_offset, mask);
1726 }
1727
1728 /**
1729  * kvm_arch_write_log_dirty - emulate dirty page logging
1730  * @vcpu: Guest mode vcpu
1731  *
1732  * Emulate arch specific page modification logging for the
1733  * nested hypervisor
1734  */
1735 int kvm_arch_write_log_dirty(struct kvm_vcpu *vcpu, gpa_t l2_gpa)
1736 {
1737         if (kvm_x86_ops->write_log_dirty)
1738                 return kvm_x86_ops->write_log_dirty(vcpu, l2_gpa);
1739
1740         return 0;
1741 }
1742
1743 bool kvm_mmu_slot_gfn_write_protect(struct kvm *kvm,
1744                                     struct kvm_memory_slot *slot, u64 gfn)
1745 {
1746         struct kvm_rmap_head *rmap_head;
1747         int i;
1748         bool write_protected = false;
1749
1750         for (i = PT_PAGE_TABLE_LEVEL; i <= PT_MAX_HUGEPAGE_LEVEL; ++i) {
1751                 rmap_head = __gfn_to_rmap(gfn, i, slot);
1752                 write_protected |= __rmap_write_protect(kvm, rmap_head, true);
1753         }
1754
1755         return write_protected;
1756 }
1757
1758 static bool rmap_write_protect(struct kvm_vcpu *vcpu, u64 gfn)
1759 {
1760         struct kvm_memory_slot *slot;
1761
1762         slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
1763         return kvm_mmu_slot_gfn_write_protect(vcpu->kvm, slot, gfn);
1764 }
1765
1766 static bool kvm_zap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head)
1767 {
1768         u64 *sptep;
1769         struct rmap_iterator iter;
1770         bool flush = false;
1771
1772         while ((sptep = rmap_get_first(rmap_head, &iter))) {
1773                 rmap_printk("%s: spte %p %llx.\n", __func__, sptep, *sptep);
1774
1775                 drop_spte(kvm, sptep);
1776                 flush = true;
1777         }
1778
1779         return flush;
1780 }
1781
1782 static int kvm_unmap_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1783                            struct kvm_memory_slot *slot, gfn_t gfn, int level,
1784                            unsigned long data)
1785 {
1786         return kvm_zap_rmapp(kvm, rmap_head);
1787 }
1788
1789 static int kvm_set_pte_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1790                              struct kvm_memory_slot *slot, gfn_t gfn, int level,
1791                              unsigned long data)
1792 {
1793         u64 *sptep;
1794         struct rmap_iterator iter;
1795         int need_flush = 0;
1796         u64 new_spte;
1797         pte_t *ptep = (pte_t *)data;
1798         kvm_pfn_t new_pfn;
1799
1800         WARN_ON(pte_huge(*ptep));
1801         new_pfn = pte_pfn(*ptep);
1802
1803 restart:
1804         for_each_rmap_spte(rmap_head, &iter, sptep) {
1805                 rmap_printk("kvm_set_pte_rmapp: spte %p %llx gfn %llx (%d)\n",
1806                             sptep, *sptep, gfn, level);
1807
1808                 need_flush = 1;
1809
1810                 if (pte_write(*ptep)) {
1811                         drop_spte(kvm, sptep);
1812                         goto restart;
1813                 } else {
1814                         new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
1815                         new_spte |= (u64)new_pfn << PAGE_SHIFT;
1816
1817                         new_spte &= ~PT_WRITABLE_MASK;
1818                         new_spte &= ~SPTE_HOST_WRITEABLE;
1819
1820                         new_spte = mark_spte_for_access_track(new_spte);
1821
1822                         mmu_spte_clear_track_bits(sptep);
1823                         mmu_spte_set(sptep, new_spte);
1824                 }
1825         }
1826
1827         if (need_flush)
1828                 kvm_flush_remote_tlbs(kvm);
1829
1830         return 0;
1831 }
1832
1833 struct slot_rmap_walk_iterator {
1834         /* input fields. */
1835         struct kvm_memory_slot *slot;
1836         gfn_t start_gfn;
1837         gfn_t end_gfn;
1838         int start_level;
1839         int end_level;
1840
1841         /* output fields. */
1842         gfn_t gfn;
1843         struct kvm_rmap_head *rmap;
1844         int level;
1845
1846         /* private field. */
1847         struct kvm_rmap_head *end_rmap;
1848 };
1849
1850 static void
1851 rmap_walk_init_level(struct slot_rmap_walk_iterator *iterator, int level)
1852 {
1853         iterator->level = level;
1854         iterator->gfn = iterator->start_gfn;
1855         iterator->rmap = __gfn_to_rmap(iterator->gfn, level, iterator->slot);
1856         iterator->end_rmap = __gfn_to_rmap(iterator->end_gfn, level,
1857                                            iterator->slot);
1858 }
1859
1860 static void
1861 slot_rmap_walk_init(struct slot_rmap_walk_iterator *iterator,
1862                     struct kvm_memory_slot *slot, int start_level,
1863                     int end_level, gfn_t start_gfn, gfn_t end_gfn)
1864 {
1865         iterator->slot = slot;
1866         iterator->start_level = start_level;
1867         iterator->end_level = end_level;
1868         iterator->start_gfn = start_gfn;
1869         iterator->end_gfn = end_gfn;
1870
1871         rmap_walk_init_level(iterator, iterator->start_level);
1872 }
1873
1874 static bool slot_rmap_walk_okay(struct slot_rmap_walk_iterator *iterator)
1875 {
1876         return !!iterator->rmap;
1877 }
1878
1879 static void slot_rmap_walk_next(struct slot_rmap_walk_iterator *iterator)
1880 {
1881         if (++iterator->rmap <= iterator->end_rmap) {
1882                 iterator->gfn += (1UL << KVM_HPAGE_GFN_SHIFT(iterator->level));
1883                 return;
1884         }
1885
1886         if (++iterator->level > iterator->end_level) {
1887                 iterator->rmap = NULL;
1888                 return;
1889         }
1890
1891         rmap_walk_init_level(iterator, iterator->level);
1892 }
1893
1894 #define for_each_slot_rmap_range(_slot_, _start_level_, _end_level_,    \
1895            _start_gfn, _end_gfn, _iter_)                                \
1896         for (slot_rmap_walk_init(_iter_, _slot_, _start_level_,         \
1897                                  _end_level_, _start_gfn, _end_gfn);    \
1898              slot_rmap_walk_okay(_iter_);                               \
1899              slot_rmap_walk_next(_iter_))
1900
1901 static int kvm_handle_hva_range(struct kvm *kvm,
1902                                 unsigned long start,
1903                                 unsigned long end,
1904                                 unsigned long data,
1905                                 int (*handler)(struct kvm *kvm,
1906                                                struct kvm_rmap_head *rmap_head,
1907                                                struct kvm_memory_slot *slot,
1908                                                gfn_t gfn,
1909                                                int level,
1910                                                unsigned long data))
1911 {
1912         struct kvm_memslots *slots;
1913         struct kvm_memory_slot *memslot;
1914         struct slot_rmap_walk_iterator iterator;
1915         int ret = 0;
1916         int i;
1917
1918         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
1919                 slots = __kvm_memslots(kvm, i);
1920                 kvm_for_each_memslot(memslot, slots) {
1921                         unsigned long hva_start, hva_end;
1922                         gfn_t gfn_start, gfn_end;
1923
1924                         hva_start = max(start, memslot->userspace_addr);
1925                         hva_end = min(end, memslot->userspace_addr +
1926                                       (memslot->npages << PAGE_SHIFT));
1927                         if (hva_start >= hva_end)
1928                                 continue;
1929                         /*
1930                          * {gfn(page) | page intersects with [hva_start, hva_end)} =
1931                          * {gfn_start, gfn_start+1, ..., gfn_end-1}.
1932                          */
1933                         gfn_start = hva_to_gfn_memslot(hva_start, memslot);
1934                         gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
1935
1936                         for_each_slot_rmap_range(memslot, PT_PAGE_TABLE_LEVEL,
1937                                                  PT_MAX_HUGEPAGE_LEVEL,
1938                                                  gfn_start, gfn_end - 1,
1939                                                  &iterator)
1940                                 ret |= handler(kvm, iterator.rmap, memslot,
1941                                                iterator.gfn, iterator.level, data);
1942                 }
1943         }
1944
1945         return ret;
1946 }
1947
1948 static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
1949                           unsigned long data,
1950                           int (*handler)(struct kvm *kvm,
1951                                          struct kvm_rmap_head *rmap_head,
1952                                          struct kvm_memory_slot *slot,
1953                                          gfn_t gfn, int level,
1954                                          unsigned long data))
1955 {
1956         return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
1957 }
1958
1959 int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end,
1960                         bool blockable)
1961 {
1962         return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
1963 }
1964
1965 void kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
1966 {
1967         kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
1968 }
1969
1970 static int kvm_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1971                          struct kvm_memory_slot *slot, gfn_t gfn, int level,
1972                          unsigned long data)
1973 {
1974         u64 *sptep;
1975         struct rmap_iterator uninitialized_var(iter);
1976         int young = 0;
1977
1978         for_each_rmap_spte(rmap_head, &iter, sptep)
1979                 young |= mmu_spte_age(sptep);
1980
1981         trace_kvm_age_page(gfn, level, slot, young);
1982         return young;
1983 }
1984
1985 static int kvm_test_age_rmapp(struct kvm *kvm, struct kvm_rmap_head *rmap_head,
1986                               struct kvm_memory_slot *slot, gfn_t gfn,
1987                               int level, unsigned long data)
1988 {
1989         u64 *sptep;
1990         struct rmap_iterator iter;
1991
1992         for_each_rmap_spte(rmap_head, &iter, sptep)
1993                 if (is_accessed_spte(*sptep))
1994                         return 1;
1995         return 0;
1996 }
1997
1998 #define RMAP_RECYCLE_THRESHOLD 1000
1999
2000 static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
2001 {
2002         struct kvm_rmap_head *rmap_head;
2003         struct kvm_mmu_page *sp;
2004
2005         sp = page_header(__pa(spte));
2006
2007         rmap_head = gfn_to_rmap(vcpu->kvm, gfn, sp);
2008
2009         kvm_unmap_rmapp(vcpu->kvm, rmap_head, NULL, gfn, sp->role.level, 0);
2010         kvm_flush_remote_tlbs(vcpu->kvm);
2011 }
2012
2013 int kvm_age_hva(struct kvm *kvm, unsigned long start, unsigned long end)
2014 {
2015         return kvm_handle_hva_range(kvm, start, end, 0, kvm_age_rmapp);
2016 }
2017
2018 int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
2019 {
2020         return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
2021 }
2022
2023 #ifdef MMU_DEBUG
2024 static int is_empty_shadow_page(u64 *spt)
2025 {
2026         u64 *pos;
2027         u64 *end;
2028
2029         for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
2030                 if (is_shadow_present_pte(*pos)) {
2031                         printk(KERN_ERR "%s: %p %llx\n", __func__,
2032                                pos, *pos);
2033                         return 0;
2034                 }
2035         return 1;
2036 }
2037 #endif
2038
2039 /*
2040  * This value is the sum of all of the kvm instances's
2041  * kvm->arch.n_used_mmu_pages values.  We need a global,
2042  * aggregate version in order to make the slab shrinker
2043  * faster
2044  */
2045 static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, long nr)
2046 {
2047         kvm->arch.n_used_mmu_pages += nr;
2048         percpu_counter_add(&kvm_total_used_mmu_pages, nr);
2049 }
2050
2051 static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
2052 {
2053         MMU_WARN_ON(!is_empty_shadow_page(sp->spt));
2054         hlist_del(&sp->hash_link);
2055         list_del(&sp->link);
2056         free_page((unsigned long)sp->spt);
2057         if (!sp->role.direct)
2058                 free_page((unsigned long)sp->gfns);
2059         kmem_cache_free(mmu_page_header_cache, sp);
2060 }
2061
2062 static unsigned kvm_page_table_hashfn(gfn_t gfn)
2063 {
2064         return hash_64(gfn, KVM_MMU_HASH_SHIFT);
2065 }
2066
2067 static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
2068                                     struct kvm_mmu_page *sp, u64 *parent_pte)
2069 {
2070         if (!parent_pte)
2071                 return;
2072
2073         pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
2074 }
2075
2076 static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
2077                                        u64 *parent_pte)
2078 {
2079         pte_list_remove(parent_pte, &sp->parent_ptes);
2080 }
2081
2082 static void drop_parent_pte(struct kvm_mmu_page *sp,
2083                             u64 *parent_pte)
2084 {
2085         mmu_page_remove_parent_pte(sp, parent_pte);
2086         mmu_spte_clear_no_track(parent_pte);
2087 }
2088
2089 static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu, int direct)
2090 {
2091         struct kvm_mmu_page *sp;
2092
2093         sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
2094         sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2095         if (!direct)
2096                 sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
2097         set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
2098
2099         /*
2100          * The active_mmu_pages list is the FIFO list, do not move the
2101          * page until it is zapped. kvm_zap_obsolete_pages depends on
2102          * this feature. See the comments in kvm_zap_obsolete_pages().
2103          */
2104         list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
2105         kvm_mod_used_mmu_pages(vcpu->kvm, +1);
2106         return sp;
2107 }
2108
2109 static void mark_unsync(u64 *spte);
2110 static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
2111 {
2112         u64 *sptep;
2113         struct rmap_iterator iter;
2114
2115         for_each_rmap_spte(&sp->parent_ptes, &iter, sptep) {
2116                 mark_unsync(sptep);
2117         }
2118 }
2119
2120 static void mark_unsync(u64 *spte)
2121 {
2122         struct kvm_mmu_page *sp;
2123         unsigned int index;
2124
2125         sp = page_header(__pa(spte));
2126         index = spte - sp->spt;
2127         if (__test_and_set_bit(index, sp->unsync_child_bitmap))
2128                 return;
2129         if (sp->unsync_children++)
2130                 return;
2131         kvm_mmu_mark_parents_unsync(sp);
2132 }
2133
2134 static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
2135                                struct kvm_mmu_page *sp)
2136 {
2137         return 0;
2138 }
2139
2140 static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva, hpa_t root)
2141 {
2142 }
2143
2144 static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
2145                                  struct kvm_mmu_page *sp, u64 *spte,
2146                                  const void *pte)
2147 {
2148         WARN_ON(1);
2149 }
2150
2151 #define KVM_PAGE_ARRAY_NR 16
2152
2153 struct kvm_mmu_pages {
2154         struct mmu_page_and_offset {
2155                 struct kvm_mmu_page *sp;
2156                 unsigned int idx;
2157         } page[KVM_PAGE_ARRAY_NR];
2158         unsigned int nr;
2159 };
2160
2161 static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
2162                          int idx)
2163 {
2164         int i;
2165
2166         if (sp->unsync)
2167                 for (i=0; i < pvec->nr; i++)
2168                         if (pvec->page[i].sp == sp)
2169                                 return 0;
2170
2171         pvec->page[pvec->nr].sp = sp;
2172         pvec->page[pvec->nr].idx = idx;
2173         pvec->nr++;
2174         return (pvec->nr == KVM_PAGE_ARRAY_NR);
2175 }
2176
2177 static inline void clear_unsync_child_bit(struct kvm_mmu_page *sp, int idx)
2178 {
2179         --sp->unsync_children;
2180         WARN_ON((int)sp->unsync_children < 0);
2181         __clear_bit(idx, sp->unsync_child_bitmap);
2182 }
2183
2184 static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
2185                            struct kvm_mmu_pages *pvec)
2186 {
2187         int i, ret, nr_unsync_leaf = 0;
2188
2189         for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
2190                 struct kvm_mmu_page *child;
2191                 u64 ent = sp->spt[i];
2192
2193                 if (!is_shadow_present_pte(ent) || is_large_pte(ent)) {
2194                         clear_unsync_child_bit(sp, i);
2195                         continue;
2196                 }
2197
2198                 child = page_header(ent & PT64_BASE_ADDR_MASK);
2199
2200                 if (child->unsync_children) {
2201                         if (mmu_pages_add(pvec, child, i))
2202                                 return -ENOSPC;
2203
2204                         ret = __mmu_unsync_walk(child, pvec);
2205                         if (!ret) {
2206                                 clear_unsync_child_bit(sp, i);
2207                                 continue;
2208                         } else if (ret > 0) {
2209                                 nr_unsync_leaf += ret;
2210                         } else
2211                                 return ret;
2212                 } else if (child->unsync) {
2213                         nr_unsync_leaf++;
2214                         if (mmu_pages_add(pvec, child, i))
2215                                 return -ENOSPC;
2216                 } else
2217                         clear_unsync_child_bit(sp, i);
2218         }
2219
2220         return nr_unsync_leaf;
2221 }
2222
2223 #define INVALID_INDEX (-1)
2224
2225 static int mmu_unsync_walk(struct kvm_mmu_page *sp,
2226                            struct kvm_mmu_pages *pvec)
2227 {
2228         pvec->nr = 0;
2229         if (!sp->unsync_children)
2230                 return 0;
2231
2232         mmu_pages_add(pvec, sp, INVALID_INDEX);
2233         return __mmu_unsync_walk(sp, pvec);
2234 }
2235
2236 static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
2237 {
2238         WARN_ON(!sp->unsync);
2239         trace_kvm_mmu_sync_page(sp);
2240         sp->unsync = 0;
2241         --kvm->stat.mmu_unsync;
2242 }
2243
2244 static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2245                                     struct list_head *invalid_list);
2246 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2247                                     struct list_head *invalid_list);
2248
2249 /*
2250  * NOTE: we should pay more attention on the zapped-obsolete page
2251  * (is_obsolete_sp(sp) && sp->role.invalid) when you do hash list walk
2252  * since it has been deleted from active_mmu_pages but still can be found
2253  * at hast list.
2254  *
2255  * for_each_valid_sp() has skipped that kind of pages.
2256  */
2257 #define for_each_valid_sp(_kvm, _sp, _gfn)                              \
2258         hlist_for_each_entry(_sp,                                       \
2259           &(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
2260                 if (is_obsolete_sp((_kvm), (_sp)) || (_sp)->role.invalid) {    \
2261                 } else
2262
2263 #define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn)                 \
2264         for_each_valid_sp(_kvm, _sp, _gfn)                              \
2265                 if ((_sp)->gfn != (_gfn) || (_sp)->role.direct) {} else
2266
2267 /* @sp->gfn should be write-protected at the call site */
2268 static bool __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2269                             struct list_head *invalid_list)
2270 {
2271         if (sp->role.cr4_pae != !!is_pae(vcpu)
2272             || vcpu->arch.mmu.sync_page(vcpu, sp) == 0) {
2273                 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
2274                 return false;
2275         }
2276
2277         return true;
2278 }
2279
2280 static void kvm_mmu_flush_or_zap(struct kvm_vcpu *vcpu,
2281                                  struct list_head *invalid_list,
2282                                  bool remote_flush, bool local_flush)
2283 {
2284         if (!list_empty(invalid_list)) {
2285                 kvm_mmu_commit_zap_page(vcpu->kvm, invalid_list);
2286                 return;
2287         }
2288
2289         if (remote_flush)
2290                 kvm_flush_remote_tlbs(vcpu->kvm);
2291         else if (local_flush)
2292                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2293 }
2294
2295 #ifdef CONFIG_KVM_MMU_AUDIT
2296 #include "mmu_audit.c"
2297 #else
2298 static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
2299 static void mmu_audit_disable(void) { }
2300 #endif
2301
2302 static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
2303 {
2304         return unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
2305 }
2306
2307 static bool kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
2308                          struct list_head *invalid_list)
2309 {
2310         kvm_unlink_unsync_page(vcpu->kvm, sp);
2311         return __kvm_sync_page(vcpu, sp, invalid_list);
2312 }
2313
2314 /* @gfn should be write-protected at the call site */
2315 static bool kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn,
2316                            struct list_head *invalid_list)
2317 {
2318         struct kvm_mmu_page *s;
2319         bool ret = false;
2320
2321         for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
2322                 if (!s->unsync)
2323                         continue;
2324
2325                 WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
2326                 ret |= kvm_sync_page(vcpu, s, invalid_list);
2327         }
2328
2329         return ret;
2330 }
2331
2332 struct mmu_page_path {
2333         struct kvm_mmu_page *parent[PT64_ROOT_MAX_LEVEL];
2334         unsigned int idx[PT64_ROOT_MAX_LEVEL];
2335 };
2336
2337 #define for_each_sp(pvec, sp, parents, i)                       \
2338                 for (i = mmu_pages_first(&pvec, &parents);      \
2339                         i < pvec.nr && ({ sp = pvec.page[i].sp; 1;});   \
2340                         i = mmu_pages_next(&pvec, &parents, i))
2341
2342 static int mmu_pages_next(struct kvm_mmu_pages *pvec,
2343                           struct mmu_page_path *parents,
2344                           int i)
2345 {
2346         int n;
2347
2348         for (n = i+1; n < pvec->nr; n++) {
2349                 struct kvm_mmu_page *sp = pvec->page[n].sp;
2350                 unsigned idx = pvec->page[n].idx;
2351                 int level = sp->role.level;
2352
2353                 parents->idx[level-1] = idx;
2354                 if (level == PT_PAGE_TABLE_LEVEL)
2355                         break;
2356
2357                 parents->parent[level-2] = sp;
2358         }
2359
2360         return n;
2361 }
2362
2363 static int mmu_pages_first(struct kvm_mmu_pages *pvec,
2364                            struct mmu_page_path *parents)
2365 {
2366         struct kvm_mmu_page *sp;
2367         int level;
2368
2369         if (pvec->nr == 0)
2370                 return 0;
2371
2372         WARN_ON(pvec->page[0].idx != INVALID_INDEX);
2373
2374         sp = pvec->page[0].sp;
2375         level = sp->role.level;
2376         WARN_ON(level == PT_PAGE_TABLE_LEVEL);
2377
2378         parents->parent[level-2] = sp;
2379
2380         /* Also set up a sentinel.  Further entries in pvec are all
2381          * children of sp, so this element is never overwritten.
2382          */
2383         parents->parent[level-1] = NULL;
2384         return mmu_pages_next(pvec, parents, 0);
2385 }
2386
2387 static void mmu_pages_clear_parents(struct mmu_page_path *parents)
2388 {
2389         struct kvm_mmu_page *sp;
2390         unsigned int level = 0;
2391
2392         do {
2393                 unsigned int idx = parents->idx[level];
2394                 sp = parents->parent[level];
2395                 if (!sp)
2396                         return;
2397
2398                 WARN_ON(idx == INVALID_INDEX);
2399                 clear_unsync_child_bit(sp, idx);
2400                 level++;
2401         } while (!sp->unsync_children);
2402 }
2403
2404 static void mmu_sync_children(struct kvm_vcpu *vcpu,
2405                               struct kvm_mmu_page *parent)
2406 {
2407         int i;
2408         struct kvm_mmu_page *sp;
2409         struct mmu_page_path parents;
2410         struct kvm_mmu_pages pages;
2411         LIST_HEAD(invalid_list);
2412         bool flush = false;
2413
2414         while (mmu_unsync_walk(parent, &pages)) {
2415                 bool protected = false;
2416
2417                 for_each_sp(pages, sp, parents, i)
2418                         protected |= rmap_write_protect(vcpu, sp->gfn);
2419
2420                 if (protected) {
2421                         kvm_flush_remote_tlbs(vcpu->kvm);
2422                         flush = false;
2423                 }
2424
2425                 for_each_sp(pages, sp, parents, i) {
2426                         flush |= kvm_sync_page(vcpu, sp, &invalid_list);
2427                         mmu_pages_clear_parents(&parents);
2428                 }
2429                 if (need_resched() || spin_needbreak(&vcpu->kvm->mmu_lock)) {
2430                         kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2431                         cond_resched_lock(&vcpu->kvm->mmu_lock);
2432                         flush = false;
2433                 }
2434         }
2435
2436         kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2437 }
2438
2439 static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
2440 {
2441         atomic_set(&sp->write_flooding_count,  0);
2442 }
2443
2444 static void clear_sp_write_flooding_count(u64 *spte)
2445 {
2446         struct kvm_mmu_page *sp =  page_header(__pa(spte));
2447
2448         __clear_sp_write_flooding_count(sp);
2449 }
2450
2451 static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
2452                                              gfn_t gfn,
2453                                              gva_t gaddr,
2454                                              unsigned level,
2455                                              int direct,
2456                                              unsigned access)
2457 {
2458         union kvm_mmu_page_role role;
2459         unsigned quadrant;
2460         struct kvm_mmu_page *sp;
2461         bool need_sync = false;
2462         bool flush = false;
2463         int collisions = 0;
2464         LIST_HEAD(invalid_list);
2465
2466         role = vcpu->arch.mmu.base_role;
2467         role.level = level;
2468         role.direct = direct;
2469         if (role.direct)
2470                 role.cr4_pae = 0;
2471         role.access = access;
2472         if (!vcpu->arch.mmu.direct_map
2473             && vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) {
2474                 quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
2475                 quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
2476                 role.quadrant = quadrant;
2477         }
2478         for_each_valid_sp(vcpu->kvm, sp, gfn) {
2479                 if (sp->gfn != gfn) {
2480                         collisions++;
2481                         continue;
2482                 }
2483
2484                 if (!need_sync && sp->unsync)
2485                         need_sync = true;
2486
2487                 if (sp->role.word != role.word)
2488                         continue;
2489
2490                 if (sp->unsync) {
2491                         /* The page is good, but __kvm_sync_page might still end
2492                          * up zapping it.  If so, break in order to rebuild it.
2493                          */
2494                         if (!__kvm_sync_page(vcpu, sp, &invalid_list))
2495                                 break;
2496
2497                         WARN_ON(!list_empty(&invalid_list));
2498                         kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
2499                 }
2500
2501                 if (sp->unsync_children)
2502                         kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
2503
2504                 __clear_sp_write_flooding_count(sp);
2505                 trace_kvm_mmu_get_page(sp, false);
2506                 goto out;
2507         }
2508
2509         ++vcpu->kvm->stat.mmu_cache_miss;
2510
2511         sp = kvm_mmu_alloc_page(vcpu, direct);
2512
2513         sp->gfn = gfn;
2514         sp->role = role;
2515         hlist_add_head(&sp->hash_link,
2516                 &vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
2517         if (!direct) {
2518                 /*
2519                  * we should do write protection before syncing pages
2520                  * otherwise the content of the synced shadow page may
2521                  * be inconsistent with guest page table.
2522                  */
2523                 account_shadowed(vcpu->kvm, sp);
2524                 if (level == PT_PAGE_TABLE_LEVEL &&
2525                       rmap_write_protect(vcpu, gfn))
2526                         kvm_flush_remote_tlbs(vcpu->kvm);
2527
2528                 if (level > PT_PAGE_TABLE_LEVEL && need_sync)
2529                         flush |= kvm_sync_pages(vcpu, gfn, &invalid_list);
2530         }
2531         sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
2532         clear_page(sp->spt);
2533         trace_kvm_mmu_get_page(sp, true);
2534
2535         kvm_mmu_flush_or_zap(vcpu, &invalid_list, false, flush);
2536 out:
2537         if (collisions > vcpu->kvm->stat.max_mmu_page_hash_collisions)
2538                 vcpu->kvm->stat.max_mmu_page_hash_collisions = collisions;
2539         return sp;
2540 }
2541
2542 static void shadow_walk_init_using_root(struct kvm_shadow_walk_iterator *iterator,
2543                                         struct kvm_vcpu *vcpu, hpa_t root,
2544                                         u64 addr)
2545 {
2546         iterator->addr = addr;
2547         iterator->shadow_addr = root;
2548         iterator->level = vcpu->arch.mmu.shadow_root_level;
2549
2550         if (iterator->level == PT64_ROOT_4LEVEL &&
2551             vcpu->arch.mmu.root_level < PT64_ROOT_4LEVEL &&
2552             !vcpu->arch.mmu.direct_map)
2553                 --iterator->level;
2554
2555         if (iterator->level == PT32E_ROOT_LEVEL) {
2556                 /*
2557                  * prev_root is currently only used for 64-bit hosts. So only
2558                  * the active root_hpa is valid here.
2559                  */
2560                 BUG_ON(root != vcpu->arch.mmu.root_hpa);
2561
2562                 iterator->shadow_addr
2563                         = vcpu->arch.mmu.pae_root[(addr >> 30) & 3];
2564                 iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
2565                 --iterator->level;
2566                 if (!iterator->shadow_addr)
2567                         iterator->level = 0;
2568         }
2569 }
2570
2571 static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
2572                              struct kvm_vcpu *vcpu, u64 addr)
2573 {
2574         shadow_walk_init_using_root(iterator, vcpu, vcpu->arch.mmu.root_hpa,
2575                                     addr);
2576 }
2577
2578 static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
2579 {
2580         if (iterator->level < PT_PAGE_TABLE_LEVEL)
2581                 return false;
2582
2583         iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
2584         iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
2585         return true;
2586 }
2587
2588 static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
2589                                u64 spte)
2590 {
2591         if (is_last_spte(spte, iterator->level)) {
2592                 iterator->level = 0;
2593                 return;
2594         }
2595
2596         iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
2597         --iterator->level;
2598 }
2599
2600 static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
2601 {
2602         __shadow_walk_next(iterator, *iterator->sptep);
2603 }
2604
2605 static void link_shadow_page(struct kvm_vcpu *vcpu, u64 *sptep,
2606                              struct kvm_mmu_page *sp)
2607 {
2608         u64 spte;
2609
2610         BUILD_BUG_ON(VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
2611
2612         spte = __pa(sp->spt) | shadow_present_mask | PT_WRITABLE_MASK |
2613                shadow_user_mask | shadow_x_mask | shadow_me_mask;
2614
2615         if (sp_ad_disabled(sp))
2616                 spte |= shadow_acc_track_value;
2617         else
2618                 spte |= shadow_accessed_mask;
2619
2620         mmu_spte_set(sptep, spte);
2621
2622         mmu_page_add_parent_pte(vcpu, sp, sptep);
2623
2624         if (sp->unsync_children || sp->unsync)
2625                 mark_unsync(sptep);
2626 }
2627
2628 static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2629                                    unsigned direct_access)
2630 {
2631         if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
2632                 struct kvm_mmu_page *child;
2633
2634                 /*
2635                  * For the direct sp, if the guest pte's dirty bit
2636                  * changed form clean to dirty, it will corrupt the
2637                  * sp's access: allow writable in the read-only sp,
2638                  * so we should update the spte at this point to get
2639                  * a new sp with the correct access.
2640                  */
2641                 child = page_header(*sptep & PT64_BASE_ADDR_MASK);
2642                 if (child->role.access == direct_access)
2643                         return;
2644
2645                 drop_parent_pte(child, sptep);
2646                 kvm_flush_remote_tlbs(vcpu->kvm);
2647         }
2648 }
2649
2650 static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
2651                              u64 *spte)
2652 {
2653         u64 pte;
2654         struct kvm_mmu_page *child;
2655
2656         pte = *spte;
2657         if (is_shadow_present_pte(pte)) {
2658                 if (is_last_spte(pte, sp->role.level)) {
2659                         drop_spte(kvm, spte);
2660                         if (is_large_pte(pte))
2661                                 --kvm->stat.lpages;
2662                 } else {
2663                         child = page_header(pte & PT64_BASE_ADDR_MASK);
2664                         drop_parent_pte(child, spte);
2665                 }
2666                 return true;
2667         }
2668
2669         if (is_mmio_spte(pte))
2670                 mmu_spte_clear_no_track(spte);
2671
2672         return false;
2673 }
2674
2675 static void kvm_mmu_page_unlink_children(struct kvm *kvm,
2676                                          struct kvm_mmu_page *sp)
2677 {
2678         unsigned i;
2679
2680         for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
2681                 mmu_page_zap_pte(kvm, sp, sp->spt + i);
2682 }
2683
2684 static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
2685 {
2686         u64 *sptep;
2687         struct rmap_iterator iter;
2688
2689         while ((sptep = rmap_get_first(&sp->parent_ptes, &iter)))
2690                 drop_parent_pte(sp, sptep);
2691 }
2692
2693 static int mmu_zap_unsync_children(struct kvm *kvm,
2694                                    struct kvm_mmu_page *parent,
2695                                    struct list_head *invalid_list)
2696 {
2697         int i, zapped = 0;
2698         struct mmu_page_path parents;
2699         struct kvm_mmu_pages pages;
2700
2701         if (parent->role.level == PT_PAGE_TABLE_LEVEL)
2702                 return 0;
2703
2704         while (mmu_unsync_walk(parent, &pages)) {
2705                 struct kvm_mmu_page *sp;
2706
2707                 for_each_sp(pages, sp, parents, i) {
2708                         kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2709                         mmu_pages_clear_parents(&parents);
2710                         zapped++;
2711                 }
2712         }
2713
2714         return zapped;
2715 }
2716
2717 static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
2718                                     struct list_head *invalid_list)
2719 {
2720         int ret;
2721
2722         trace_kvm_mmu_prepare_zap_page(sp);
2723         ++kvm->stat.mmu_shadow_zapped;
2724         ret = mmu_zap_unsync_children(kvm, sp, invalid_list);
2725         kvm_mmu_page_unlink_children(kvm, sp);
2726         kvm_mmu_unlink_parents(kvm, sp);
2727
2728         if (!sp->role.invalid && !sp->role.direct)
2729                 unaccount_shadowed(kvm, sp);
2730
2731         if (sp->unsync)
2732                 kvm_unlink_unsync_page(kvm, sp);
2733         if (!sp->root_count) {
2734                 /* Count self */
2735                 ret++;
2736                 list_move(&sp->link, invalid_list);
2737                 kvm_mod_used_mmu_pages(kvm, -1);
2738         } else {
2739                 list_move(&sp->link, &kvm->arch.active_mmu_pages);
2740
2741                 /*
2742                  * The obsolete pages can not be used on any vcpus.
2743                  * See the comments in kvm_mmu_invalidate_zap_all_pages().
2744                  */
2745                 if (!sp->role.invalid && !is_obsolete_sp(kvm, sp))
2746                         kvm_reload_remote_mmus(kvm);
2747         }
2748
2749         if (sp->lpage_disallowed)
2750                 unaccount_huge_nx_page(kvm, sp);
2751
2752         sp->role.invalid = 1;
2753         return ret;
2754 }
2755
2756 static void kvm_mmu_commit_zap_page(struct kvm *kvm,
2757                                     struct list_head *invalid_list)
2758 {
2759         struct kvm_mmu_page *sp, *nsp;
2760
2761         if (list_empty(invalid_list))
2762                 return;
2763
2764         /*
2765          * We need to make sure everyone sees our modifications to
2766          * the page tables and see changes to vcpu->mode here. The barrier
2767          * in the kvm_flush_remote_tlbs() achieves this. This pairs
2768          * with vcpu_enter_guest and walk_shadow_page_lockless_begin/end.
2769          *
2770          * In addition, kvm_flush_remote_tlbs waits for all vcpus to exit
2771          * guest mode and/or lockless shadow page table walks.
2772          */
2773         kvm_flush_remote_tlbs(kvm);
2774
2775         list_for_each_entry_safe(sp, nsp, invalid_list, link) {
2776                 WARN_ON(!sp->role.invalid || sp->root_count);
2777                 kvm_mmu_free_page(sp);
2778         }
2779 }
2780
2781 static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
2782                                         struct list_head *invalid_list)
2783 {
2784         struct kvm_mmu_page *sp;
2785
2786         if (list_empty(&kvm->arch.active_mmu_pages))
2787                 return false;
2788
2789         sp = list_last_entry(&kvm->arch.active_mmu_pages,
2790                              struct kvm_mmu_page, link);
2791         return kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
2792 }
2793
2794 /*
2795  * Changing the number of mmu pages allocated to the vm
2796  * Note: if goal_nr_mmu_pages is too small, you will get dead lock
2797  */
2798 void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned long goal_nr_mmu_pages)
2799 {
2800         LIST_HEAD(invalid_list);
2801
2802         spin_lock(&kvm->mmu_lock);
2803
2804         if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
2805                 /* Need to free some mmu pages to achieve the goal. */
2806                 while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
2807                         if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
2808                                 break;
2809
2810                 kvm_mmu_commit_zap_page(kvm, &invalid_list);
2811                 goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
2812         }
2813
2814         kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
2815
2816         spin_unlock(&kvm->mmu_lock);
2817 }
2818
2819 int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
2820 {
2821         struct kvm_mmu_page *sp;
2822         LIST_HEAD(invalid_list);
2823         int r;
2824
2825         pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
2826         r = 0;
2827         spin_lock(&kvm->mmu_lock);
2828         for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
2829                 pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
2830                          sp->role.word);
2831                 r = 1;
2832                 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
2833         }
2834         kvm_mmu_commit_zap_page(kvm, &invalid_list);
2835         spin_unlock(&kvm->mmu_lock);
2836
2837         return r;
2838 }
2839 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
2840
2841 static void kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
2842 {
2843         trace_kvm_mmu_unsync_page(sp);
2844         ++vcpu->kvm->stat.mmu_unsync;
2845         sp->unsync = 1;
2846
2847         kvm_mmu_mark_parents_unsync(sp);
2848 }
2849
2850 static bool mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
2851                                    bool can_unsync)
2852 {
2853         struct kvm_mmu_page *sp;
2854
2855         if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
2856                 return true;
2857
2858         for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
2859                 if (!can_unsync)
2860                         return true;
2861
2862                 if (sp->unsync)
2863                         continue;
2864
2865                 WARN_ON(sp->role.level != PT_PAGE_TABLE_LEVEL);
2866                 kvm_unsync_page(vcpu, sp);
2867         }
2868
2869         /*
2870          * We need to ensure that the marking of unsync pages is visible
2871          * before the SPTE is updated to allow writes because
2872          * kvm_mmu_sync_roots() checks the unsync flags without holding
2873          * the MMU lock and so can race with this. If the SPTE was updated
2874          * before the page had been marked as unsync-ed, something like the
2875          * following could happen:
2876          *
2877          * CPU 1                    CPU 2
2878          * ---------------------------------------------------------------------
2879          * 1.2 Host updates SPTE
2880          *     to be writable
2881          *                      2.1 Guest writes a GPTE for GVA X.
2882          *                          (GPTE being in the guest page table shadowed
2883          *                           by the SP from CPU 1.)
2884          *                          This reads SPTE during the page table walk.
2885          *                          Since SPTE.W is read as 1, there is no
2886          *                          fault.
2887          *
2888          *                      2.2 Guest issues TLB flush.
2889          *                          That causes a VM Exit.
2890          *
2891          *                      2.3 kvm_mmu_sync_pages() reads sp->unsync.
2892          *                          Since it is false, so it just returns.
2893          *
2894          *                      2.4 Guest accesses GVA X.
2895          *                          Since the mapping in the SP was not updated,
2896          *                          so the old mapping for GVA X incorrectly
2897          *                          gets used.
2898          * 1.1 Host marks SP
2899          *     as unsync
2900          *     (sp->unsync = true)
2901          *
2902          * The write barrier below ensures that 1.1 happens before 1.2 and thus
2903          * the situation in 2.4 does not arise. The implicit barrier in 2.2
2904          * pairs with this write barrier.
2905          */
2906         smp_wmb();
2907
2908         return false;
2909 }
2910
2911 static bool kvm_is_mmio_pfn(kvm_pfn_t pfn)
2912 {
2913         if (pfn_valid(pfn))
2914                 return !is_zero_pfn(pfn) && PageReserved(pfn_to_page(pfn)) &&
2915                         /*
2916                          * Some reserved pages, such as those from NVDIMM
2917                          * DAX devices, are not for MMIO, and can be mapped
2918                          * with cached memory type for better performance.
2919                          * However, the above check misconceives those pages
2920                          * as MMIO, and results in KVM mapping them with UC
2921                          * memory type, which would hurt the performance.
2922                          * Therefore, we check the host memory type in addition
2923                          * and only treat UC/UC-/WC pages as MMIO.
2924                          */
2925                         (!pat_enabled() || pat_pfn_immune_to_uc_mtrr(pfn));
2926
2927         return true;
2928 }
2929
2930 /* Bits which may be returned by set_spte() */
2931 #define SET_SPTE_WRITE_PROTECTED_PT     BIT(0)
2932 #define SET_SPTE_NEED_REMOTE_TLB_FLUSH  BIT(1)
2933
2934 static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
2935                     unsigned pte_access, int level,
2936                     gfn_t gfn, kvm_pfn_t pfn, bool speculative,
2937                     bool can_unsync, bool host_writable)
2938 {
2939         u64 spte = 0;
2940         int ret = 0;
2941         struct kvm_mmu_page *sp;
2942
2943         if (set_mmio_spte(vcpu, sptep, gfn, pfn, pte_access))
2944                 return 0;
2945
2946         sp = page_header(__pa(sptep));
2947         if (sp_ad_disabled(sp))
2948                 spte |= shadow_acc_track_value;
2949
2950         /*
2951          * For the EPT case, shadow_present_mask is 0 if hardware
2952          * supports exec-only page table entries.  In that case,
2953          * ACC_USER_MASK and shadow_user_mask are used to represent
2954          * read access.  See FNAME(gpte_access) in paging_tmpl.h.
2955          */
2956         spte |= shadow_present_mask;
2957         if (!speculative)
2958                 spte |= spte_shadow_accessed_mask(spte);
2959
2960         if (level > PT_PAGE_TABLE_LEVEL && (pte_access & ACC_EXEC_MASK) &&
2961             is_nx_huge_page_enabled()) {
2962                 pte_access &= ~ACC_EXEC_MASK;
2963         }
2964
2965         if (pte_access & ACC_EXEC_MASK)
2966                 spte |= shadow_x_mask;
2967         else
2968                 spte |= shadow_nx_mask;
2969
2970         if (pte_access & ACC_USER_MASK)
2971                 spte |= shadow_user_mask;
2972
2973         if (level > PT_PAGE_TABLE_LEVEL)
2974                 spte |= PT_PAGE_SIZE_MASK;
2975         if (tdp_enabled)
2976                 spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
2977                         kvm_is_mmio_pfn(pfn));
2978
2979         if (host_writable)
2980                 spte |= SPTE_HOST_WRITEABLE;
2981         else
2982                 pte_access &= ~ACC_WRITE_MASK;
2983
2984         if (!kvm_is_mmio_pfn(pfn))
2985                 spte |= shadow_me_mask;
2986
2987         spte |= (u64)pfn << PAGE_SHIFT;
2988
2989         if (pte_access & ACC_WRITE_MASK) {
2990
2991                 /*
2992                  * Other vcpu creates new sp in the window between
2993                  * mapping_level() and acquiring mmu-lock. We can
2994                  * allow guest to retry the access, the mapping can
2995                  * be fixed if guest refault.
2996                  */
2997                 if (level > PT_PAGE_TABLE_LEVEL &&
2998                     mmu_gfn_lpage_is_disallowed(vcpu, gfn, level))
2999                         goto done;
3000
3001                 spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
3002
3003                 /*
3004                  * Optimization: for pte sync, if spte was writable the hash
3005                  * lookup is unnecessary (and expensive). Write protection
3006                  * is responsibility of mmu_get_page / kvm_sync_page.
3007                  * Same reasoning can be applied to dirty page accounting.
3008                  */
3009                 if (!can_unsync && is_writable_pte(*sptep))
3010                         goto set_pte;
3011
3012                 if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
3013                         pgprintk("%s: found shadow page for %llx, marking ro\n",
3014                                  __func__, gfn);
3015                         ret |= SET_SPTE_WRITE_PROTECTED_PT;
3016                         pte_access &= ~ACC_WRITE_MASK;
3017                         spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
3018                 }
3019         }
3020
3021         if (pte_access & ACC_WRITE_MASK) {
3022                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3023                 spte |= spte_shadow_dirty_mask(spte);
3024         }
3025
3026         if (speculative)
3027                 spte = mark_spte_for_access_track(spte);
3028
3029 set_pte:
3030         if (mmu_spte_update(sptep, spte))
3031                 ret |= SET_SPTE_NEED_REMOTE_TLB_FLUSH;
3032 done:
3033         return ret;
3034 }
3035
3036 static int mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep, unsigned pte_access,
3037                         int write_fault, int level, gfn_t gfn, kvm_pfn_t pfn,
3038                         bool speculative, bool host_writable)
3039 {
3040         int was_rmapped = 0;
3041         int rmap_count;
3042         int set_spte_ret;
3043         int ret = RET_PF_RETRY;
3044         bool flush = false;
3045
3046         pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
3047                  *sptep, write_fault, gfn);
3048
3049         if (is_shadow_present_pte(*sptep)) {
3050                 /*
3051                  * If we overwrite a PTE page pointer with a 2MB PMD, unlink
3052                  * the parent of the now unreachable PTE.
3053                  */
3054                 if (level > PT_PAGE_TABLE_LEVEL &&
3055                     !is_large_pte(*sptep)) {
3056                         struct kvm_mmu_page *child;
3057                         u64 pte = *sptep;
3058
3059                         child = page_header(pte & PT64_BASE_ADDR_MASK);
3060                         drop_parent_pte(child, sptep);
3061                         flush = true;
3062                 } else if (pfn != spte_to_pfn(*sptep)) {
3063                         pgprintk("hfn old %llx new %llx\n",
3064                                  spte_to_pfn(*sptep), pfn);
3065                         drop_spte(vcpu->kvm, sptep);
3066                         flush = true;
3067                 } else
3068                         was_rmapped = 1;
3069         }
3070
3071         set_spte_ret = set_spte(vcpu, sptep, pte_access, level, gfn, pfn,
3072                                 speculative, true, host_writable);
3073         if (set_spte_ret & SET_SPTE_WRITE_PROTECTED_PT) {
3074                 if (write_fault)
3075                         ret = RET_PF_EMULATE;
3076                 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
3077         }
3078         if (set_spte_ret & SET_SPTE_NEED_REMOTE_TLB_FLUSH || flush)
3079                 kvm_flush_remote_tlbs(vcpu->kvm);
3080
3081         if (unlikely(is_mmio_spte(*sptep)))
3082                 ret = RET_PF_EMULATE;
3083
3084         pgprintk("%s: setting spte %llx\n", __func__, *sptep);
3085         trace_kvm_mmu_set_spte(level, gfn, sptep);
3086         if (!was_rmapped && is_large_pte(*sptep))
3087                 ++vcpu->kvm->stat.lpages;
3088
3089         if (is_shadow_present_pte(*sptep)) {
3090                 if (!was_rmapped) {
3091                         rmap_count = rmap_add(vcpu, sptep, gfn);
3092                         if (rmap_count > RMAP_RECYCLE_THRESHOLD)
3093                                 rmap_recycle(vcpu, sptep, gfn);
3094                 }
3095         }
3096
3097         return ret;
3098 }
3099
3100 static kvm_pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
3101                                      bool no_dirty_log)
3102 {
3103         struct kvm_memory_slot *slot;
3104
3105         slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
3106         if (!slot)
3107                 return KVM_PFN_ERR_FAULT;
3108
3109         return gfn_to_pfn_memslot_atomic(slot, gfn);
3110 }
3111
3112 static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
3113                                     struct kvm_mmu_page *sp,
3114                                     u64 *start, u64 *end)
3115 {
3116         struct page *pages[PTE_PREFETCH_NUM];
3117         struct kvm_memory_slot *slot;
3118         unsigned access = sp->role.access;
3119         int i, ret;
3120         gfn_t gfn;
3121
3122         gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
3123         slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK);
3124         if (!slot)
3125                 return -1;
3126
3127         ret = gfn_to_page_many_atomic(slot, gfn, pages, end - start);
3128         if (ret <= 0)
3129                 return -1;
3130
3131         for (i = 0; i < ret; i++, gfn++, start++) {
3132                 mmu_set_spte(vcpu, start, access, 0, sp->role.level, gfn,
3133                              page_to_pfn(pages[i]), true, true);
3134                 put_page(pages[i]);
3135         }
3136
3137         return 0;
3138 }
3139
3140 static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
3141                                   struct kvm_mmu_page *sp, u64 *sptep)
3142 {
3143         u64 *spte, *start = NULL;
3144         int i;
3145
3146         WARN_ON(!sp->role.direct);
3147
3148         i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
3149         spte = sp->spt + i;
3150
3151         for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
3152                 if (is_shadow_present_pte(*spte) || spte == sptep) {
3153                         if (!start)
3154                                 continue;
3155                         if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
3156                                 break;
3157                         start = NULL;
3158                 } else if (!start)
3159                         start = spte;
3160         }
3161 }
3162
3163 static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
3164 {
3165         struct kvm_mmu_page *sp;
3166
3167         sp = page_header(__pa(sptep));
3168
3169         /*
3170          * Without accessed bits, there's no way to distinguish between
3171          * actually accessed translations and prefetched, so disable pte
3172          * prefetch if accessed bits aren't available.
3173          */
3174         if (sp_ad_disabled(sp))
3175                 return;
3176
3177         if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3178                 return;
3179
3180         __direct_pte_prefetch(vcpu, sp, sptep);
3181 }
3182
3183 static void disallowed_hugepage_adjust(struct kvm_shadow_walk_iterator it,
3184                                        gfn_t gfn, kvm_pfn_t *pfnp, int *levelp)
3185 {
3186         int level = *levelp;
3187         u64 spte = *it.sptep;
3188
3189         if (it.level == level && level > PT_PAGE_TABLE_LEVEL &&
3190             is_nx_huge_page_enabled() &&
3191             is_shadow_present_pte(spte) &&
3192             !is_large_pte(spte)) {
3193                 /*
3194                  * A small SPTE exists for this pfn, but FNAME(fetch)
3195                  * and __direct_map would like to create a large PTE
3196                  * instead: just force them to go down another level,
3197                  * patching back for them into pfn the next 9 bits of
3198                  * the address.
3199                  */
3200                 u64 page_mask = KVM_PAGES_PER_HPAGE(level) - KVM_PAGES_PER_HPAGE(level - 1);
3201                 *pfnp |= gfn & page_mask;
3202                 (*levelp)--;
3203         }
3204 }
3205
3206 static int __direct_map(struct kvm_vcpu *vcpu, gpa_t gpa, int write,
3207                         int map_writable, int level, kvm_pfn_t pfn,
3208                         bool prefault, bool lpage_disallowed)
3209 {
3210         struct kvm_shadow_walk_iterator it;
3211         struct kvm_mmu_page *sp;
3212         int ret;
3213         gfn_t gfn = gpa >> PAGE_SHIFT;
3214         gfn_t base_gfn = gfn;
3215
3216         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3217                 return RET_PF_RETRY;
3218
3219         trace_kvm_mmu_spte_requested(gpa, level, pfn);
3220         for_each_shadow_entry(vcpu, gpa, it) {
3221                 /*
3222                  * We cannot overwrite existing page tables with an NX
3223                  * large page, as the leaf could be executable.
3224                  */
3225                 disallowed_hugepage_adjust(it, gfn, &pfn, &level);
3226
3227                 base_gfn = gfn & ~(KVM_PAGES_PER_HPAGE(it.level) - 1);
3228                 if (it.level == level)
3229                         break;
3230
3231                 drop_large_spte(vcpu, it.sptep);
3232                 if (!is_shadow_present_pte(*it.sptep)) {
3233                         sp = kvm_mmu_get_page(vcpu, base_gfn, it.addr,
3234                                               it.level - 1, true, ACC_ALL);
3235
3236                         link_shadow_page(vcpu, it.sptep, sp);
3237                         if (lpage_disallowed)
3238                                 account_huge_nx_page(vcpu->kvm, sp);
3239                 }
3240         }
3241
3242         ret = mmu_set_spte(vcpu, it.sptep, ACC_ALL,
3243                            write, level, base_gfn, pfn, prefault,
3244                            map_writable);
3245         direct_pte_prefetch(vcpu, it.sptep);
3246         ++vcpu->stat.pf_fixed;
3247         return ret;
3248 }
3249
3250 static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
3251 {
3252         siginfo_t info;
3253
3254         clear_siginfo(&info);
3255         info.si_signo   = SIGBUS;
3256         info.si_errno   = 0;
3257         info.si_code    = BUS_MCEERR_AR;
3258         info.si_addr    = (void __user *)address;
3259         info.si_addr_lsb = PAGE_SHIFT;
3260
3261         send_sig_info(SIGBUS, &info, tsk);
3262 }
3263
3264 static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, kvm_pfn_t pfn)
3265 {
3266         /*
3267          * Do not cache the mmio info caused by writing the readonly gfn
3268          * into the spte otherwise read access on readonly gfn also can
3269          * caused mmio page fault and treat it as mmio access.
3270          */
3271         if (pfn == KVM_PFN_ERR_RO_FAULT)
3272                 return RET_PF_EMULATE;
3273
3274         if (pfn == KVM_PFN_ERR_HWPOISON) {
3275                 kvm_send_hwpoison_signal(kvm_vcpu_gfn_to_hva(vcpu, gfn), current);
3276                 return RET_PF_RETRY;
3277         }
3278
3279         return -EFAULT;
3280 }
3281
3282 static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
3283                                         gfn_t gfn, kvm_pfn_t *pfnp,
3284                                         int *levelp)
3285 {
3286         kvm_pfn_t pfn = *pfnp;
3287         int level = *levelp;
3288
3289         /*
3290          * Check if it's a transparent hugepage. If this would be an
3291          * hugetlbfs page, level wouldn't be set to
3292          * PT_PAGE_TABLE_LEVEL and there would be no adjustment done
3293          * here.
3294          */
3295         if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn) &&
3296             !kvm_is_zone_device_pfn(pfn) && level == PT_PAGE_TABLE_LEVEL &&
3297             PageTransCompoundMap(pfn_to_page(pfn)) &&
3298             !mmu_gfn_lpage_is_disallowed(vcpu, gfn, PT_DIRECTORY_LEVEL)) {
3299                 unsigned long mask;
3300                 /*
3301                  * mmu_notifier_retry was successful and we hold the
3302                  * mmu_lock here, so the pmd can't become splitting
3303                  * from under us, and in turn
3304                  * __split_huge_page_refcount() can't run from under
3305                  * us and we can safely transfer the refcount from
3306                  * PG_tail to PG_head as we switch the pfn to tail to
3307                  * head.
3308                  */
3309                 *levelp = level = PT_DIRECTORY_LEVEL;
3310                 mask = KVM_PAGES_PER_HPAGE(level) - 1;
3311                 VM_BUG_ON((gfn & mask) != (pfn & mask));
3312                 if (pfn & mask) {
3313                         kvm_release_pfn_clean(pfn);
3314                         pfn &= ~mask;
3315                         kvm_get_pfn(pfn);
3316                         *pfnp = pfn;
3317                 }
3318         }
3319 }
3320
3321 static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
3322                                 kvm_pfn_t pfn, unsigned access, int *ret_val)
3323 {
3324         /* The pfn is invalid, report the error! */
3325         if (unlikely(is_error_pfn(pfn))) {
3326                 *ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
3327                 return true;
3328         }
3329
3330         if (unlikely(is_noslot_pfn(pfn)))
3331                 vcpu_cache_mmio_info(vcpu, gva, gfn, access);
3332
3333         return false;
3334 }
3335
3336 static bool page_fault_can_be_fast(u32 error_code)
3337 {
3338         /*
3339          * Do not fix the mmio spte with invalid generation number which
3340          * need to be updated by slow page fault path.
3341          */
3342         if (unlikely(error_code & PFERR_RSVD_MASK))
3343                 return false;
3344
3345         /* See if the page fault is due to an NX violation */
3346         if (unlikely(((error_code & (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))
3347                       == (PFERR_FETCH_MASK | PFERR_PRESENT_MASK))))
3348                 return false;
3349
3350         /*
3351          * #PF can be fast if:
3352          * 1. The shadow page table entry is not present, which could mean that
3353          *    the fault is potentially caused by access tracking (if enabled).
3354          * 2. The shadow page table entry is present and the fault
3355          *    is caused by write-protect, that means we just need change the W
3356          *    bit of the spte which can be done out of mmu-lock.
3357          *
3358          * However, if access tracking is disabled we know that a non-present
3359          * page must be a genuine page fault where we have to create a new SPTE.
3360          * So, if access tracking is disabled, we return true only for write
3361          * accesses to a present page.
3362          */
3363
3364         return shadow_acc_track_mask != 0 ||
3365                ((error_code & (PFERR_WRITE_MASK | PFERR_PRESENT_MASK))
3366                 == (PFERR_WRITE_MASK | PFERR_PRESENT_MASK));
3367 }
3368
3369 /*
3370  * Returns true if the SPTE was fixed successfully. Otherwise,
3371  * someone else modified the SPTE from its original value.
3372  */
3373 static bool
3374 fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
3375                         u64 *sptep, u64 old_spte, u64 new_spte)
3376 {
3377         gfn_t gfn;
3378
3379         WARN_ON(!sp->role.direct);
3380
3381         /*
3382          * Theoretically we could also set dirty bit (and flush TLB) here in
3383          * order to eliminate unnecessary PML logging. See comments in
3384          * set_spte. But fast_page_fault is very unlikely to happen with PML
3385          * enabled, so we do not do this. This might result in the same GPA
3386          * to be logged in PML buffer again when the write really happens, and
3387          * eventually to be called by mark_page_dirty twice. But it's also no
3388          * harm. This also avoids the TLB flush needed after setting dirty bit
3389          * so non-PML cases won't be impacted.
3390          *
3391          * Compare with set_spte where instead shadow_dirty_mask is set.
3392          */
3393         if (cmpxchg64(sptep, old_spte, new_spte) != old_spte)
3394                 return false;
3395
3396         if (is_writable_pte(new_spte) && !is_writable_pte(old_spte)) {
3397                 /*
3398                  * The gfn of direct spte is stable since it is
3399                  * calculated by sp->gfn.
3400                  */
3401                 gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
3402                 kvm_vcpu_mark_page_dirty(vcpu, gfn);
3403         }
3404
3405         return true;
3406 }
3407
3408 static bool is_access_allowed(u32 fault_err_code, u64 spte)
3409 {
3410         if (fault_err_code & PFERR_FETCH_MASK)
3411                 return is_executable_pte(spte);
3412
3413         if (fault_err_code & PFERR_WRITE_MASK)
3414                 return is_writable_pte(spte);
3415
3416         /* Fault was on Read access */
3417         return spte & PT_PRESENT_MASK;
3418 }
3419
3420 /*
3421  * Return value:
3422  * - true: let the vcpu to access on the same address again.
3423  * - false: let the real page fault path to fix it.
3424  */
3425 static bool fast_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, int level,
3426                             u32 error_code)
3427 {
3428         struct kvm_shadow_walk_iterator iterator;
3429         struct kvm_mmu_page *sp;
3430         bool fault_handled = false;
3431         u64 spte = 0ull;
3432         uint retry_count = 0;
3433
3434         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3435                 return false;
3436
3437         if (!page_fault_can_be_fast(error_code))
3438                 return false;
3439
3440         walk_shadow_page_lockless_begin(vcpu);
3441
3442         do {
3443                 u64 new_spte;
3444
3445                 for_each_shadow_entry_lockless(vcpu, cr2_or_gpa, iterator, spte)
3446                         if (!is_shadow_present_pte(spte) ||
3447                             iterator.level < level)
3448                                 break;
3449
3450                 sp = page_header(__pa(iterator.sptep));
3451                 if (!is_last_spte(spte, sp->role.level))
3452                         break;
3453
3454                 /*
3455                  * Check whether the memory access that caused the fault would
3456                  * still cause it if it were to be performed right now. If not,
3457                  * then this is a spurious fault caused by TLB lazily flushed,
3458                  * or some other CPU has already fixed the PTE after the
3459                  * current CPU took the fault.
3460                  *
3461                  * Need not check the access of upper level table entries since
3462                  * they are always ACC_ALL.
3463                  */
3464                 if (is_access_allowed(error_code, spte)) {
3465                         fault_handled = true;
3466                         break;
3467                 }
3468
3469                 new_spte = spte;
3470
3471                 if (is_access_track_spte(spte))
3472                         new_spte = restore_acc_track_spte(new_spte);
3473
3474                 /*
3475                  * Currently, to simplify the code, write-protection can
3476                  * be removed in the fast path only if the SPTE was
3477                  * write-protected for dirty-logging or access tracking.
3478                  */
3479                 if ((error_code & PFERR_WRITE_MASK) &&
3480                     spte_can_locklessly_be_made_writable(spte))
3481                 {
3482                         new_spte |= PT_WRITABLE_MASK;
3483
3484                         /*
3485                          * Do not fix write-permission on the large spte.  Since
3486                          * we only dirty the first page into the dirty-bitmap in
3487                          * fast_pf_fix_direct_spte(), other pages are missed
3488                          * if its slot has dirty logging enabled.
3489                          *
3490                          * Instead, we let the slow page fault path create a
3491                          * normal spte to fix the access.
3492                          *
3493                          * See the comments in kvm_arch_commit_memory_region().
3494                          */
3495                         if (sp->role.level > PT_PAGE_TABLE_LEVEL)
3496                                 break;
3497                 }
3498
3499                 /* Verify that the fault can be handled in the fast path */
3500                 if (new_spte == spte ||
3501                     !is_access_allowed(error_code, new_spte))
3502                         break;
3503
3504                 /*
3505                  * Currently, fast page fault only works for direct mapping
3506                  * since the gfn is not stable for indirect shadow page. See
3507                  * Documentation/virtual/kvm/locking.txt to get more detail.
3508                  */
3509                 fault_handled = fast_pf_fix_direct_spte(vcpu, sp,
3510                                                         iterator.sptep, spte,
3511                                                         new_spte);
3512                 if (fault_handled)
3513                         break;
3514
3515                 if (++retry_count > 4) {
3516                         printk_once(KERN_WARNING
3517                                 "kvm: Fast #PF retrying more than 4 times.\n");
3518                         break;
3519                 }
3520
3521         } while (true);
3522
3523         trace_fast_page_fault(vcpu, cr2_or_gpa, error_code, iterator.sptep,
3524                               spte, fault_handled);
3525         walk_shadow_page_lockless_end(vcpu);
3526
3527         return fault_handled;
3528 }
3529
3530 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3531                          gpa_t cr2_or_gpa, kvm_pfn_t *pfn, bool write,
3532                          bool *writable);
3533 static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
3534
3535 static int nonpaging_map(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
3536                          gfn_t gfn, bool prefault)
3537 {
3538         int r;
3539         int level;
3540         bool force_pt_level;
3541         kvm_pfn_t pfn;
3542         unsigned long mmu_seq;
3543         bool map_writable, write = error_code & PFERR_WRITE_MASK;
3544         bool lpage_disallowed = (error_code & PFERR_FETCH_MASK) &&
3545                                 is_nx_huge_page_enabled();
3546
3547         force_pt_level = lpage_disallowed;
3548         level = mapping_level(vcpu, gfn, &force_pt_level);
3549         if (likely(!force_pt_level)) {
3550                 /*
3551                  * This path builds a PAE pagetable - so we can map
3552                  * 2mb pages at maximum. Therefore check if the level
3553                  * is larger than that.
3554                  */
3555                 if (level > PT_DIRECTORY_LEVEL)
3556                         level = PT_DIRECTORY_LEVEL;
3557
3558                 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3559         }
3560
3561         if (fast_page_fault(vcpu, gpa, level, error_code))
3562                 return RET_PF_RETRY;
3563
3564         mmu_seq = vcpu->kvm->mmu_notifier_seq;
3565         smp_rmb();
3566
3567         if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
3568                 return RET_PF_RETRY;
3569
3570         if (handle_abnormal_pfn(vcpu, gpa, gfn, pfn, ACC_ALL, &r))
3571                 return r;
3572
3573         r = RET_PF_RETRY;
3574         spin_lock(&vcpu->kvm->mmu_lock);
3575         if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3576                 goto out_unlock;
3577         if (make_mmu_pages_available(vcpu) < 0)
3578                 goto out_unlock;
3579         if (likely(!force_pt_level))
3580                 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
3581         r = __direct_map(vcpu, gpa, write, map_writable, level, pfn,
3582                          prefault, false);
3583 out_unlock:
3584         spin_unlock(&vcpu->kvm->mmu_lock);
3585         kvm_release_pfn_clean(pfn);
3586         return r;
3587 }
3588
3589 static void mmu_free_root_page(struct kvm *kvm, hpa_t *root_hpa,
3590                                struct list_head *invalid_list)
3591 {
3592         struct kvm_mmu_page *sp;
3593
3594         if (!VALID_PAGE(*root_hpa))
3595                 return;
3596
3597         sp = page_header(*root_hpa & PT64_BASE_ADDR_MASK);
3598         --sp->root_count;
3599         if (!sp->root_count && sp->role.invalid)
3600                 kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
3601
3602         *root_hpa = INVALID_PAGE;
3603 }
3604
3605 /* roots_to_free must be some combination of the KVM_MMU_ROOT_* flags */
3606 void kvm_mmu_free_roots(struct kvm_vcpu *vcpu, ulong roots_to_free)
3607 {
3608         int i;
3609         LIST_HEAD(invalid_list);
3610         struct kvm_mmu *mmu = &vcpu->arch.mmu;
3611         bool free_active_root = roots_to_free & KVM_MMU_ROOT_CURRENT;
3612
3613         BUILD_BUG_ON(KVM_MMU_NUM_PREV_ROOTS >= BITS_PER_LONG);
3614
3615         /* Before acquiring the MMU lock, see if we need to do any real work. */
3616         if (!(free_active_root && VALID_PAGE(mmu->root_hpa))) {
3617                 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3618                         if ((roots_to_free & KVM_MMU_ROOT_PREVIOUS(i)) &&
3619                             VALID_PAGE(mmu->prev_roots[i].hpa))
3620                                 break;
3621
3622                 if (i == KVM_MMU_NUM_PREV_ROOTS)
3623                         return;
3624         }
3625
3626         spin_lock(&vcpu->kvm->mmu_lock);
3627
3628         for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
3629                 if (roots_to_free & KVM_MMU_ROOT_PREVIOUS(i))
3630                         mmu_free_root_page(vcpu->kvm, &mmu->prev_roots[i].hpa,
3631                                            &invalid_list);
3632
3633         if (free_active_root) {
3634                 if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
3635                     (mmu->root_level >= PT64_ROOT_4LEVEL || mmu->direct_map)) {
3636                         mmu_free_root_page(vcpu->kvm, &mmu->root_hpa,
3637                                            &invalid_list);
3638                 } else {
3639                         for (i = 0; i < 4; ++i)
3640                                 if (mmu->pae_root[i] != 0)
3641                                         mmu_free_root_page(vcpu->kvm,
3642                                                            &mmu->pae_root[i],
3643                                                            &invalid_list);
3644                         mmu->root_hpa = INVALID_PAGE;
3645                 }
3646         }
3647
3648         kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3649         spin_unlock(&vcpu->kvm->mmu_lock);
3650 }
3651 EXPORT_SYMBOL_GPL(kvm_mmu_free_roots);
3652
3653 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3654 {
3655         int ret = 0;
3656
3657         if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3658                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3659                 ret = 1;
3660         }
3661
3662         return ret;
3663 }
3664
3665 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3666 {
3667         struct kvm_mmu_page *sp;
3668         unsigned i;
3669
3670         if (vcpu->arch.mmu.shadow_root_level >= PT64_ROOT_4LEVEL) {
3671                 spin_lock(&vcpu->kvm->mmu_lock);
3672                 if(make_mmu_pages_available(vcpu) < 0) {
3673                         spin_unlock(&vcpu->kvm->mmu_lock);
3674                         return -ENOSPC;
3675                 }
3676                 sp = kvm_mmu_get_page(vcpu, 0, 0,
3677                                 vcpu->arch.mmu.shadow_root_level, 1, ACC_ALL);
3678                 ++sp->root_count;
3679                 spin_unlock(&vcpu->kvm->mmu_lock);
3680                 vcpu->arch.mmu.root_hpa = __pa(sp->spt);
3681         } else if (vcpu->arch.mmu.shadow_root_level == PT32E_ROOT_LEVEL) {
3682                 for (i = 0; i < 4; ++i) {
3683                         hpa_t root = vcpu->arch.mmu.pae_root[i];
3684
3685                         MMU_WARN_ON(VALID_PAGE(root));
3686                         spin_lock(&vcpu->kvm->mmu_lock);
3687                         if (make_mmu_pages_available(vcpu) < 0) {
3688                                 spin_unlock(&vcpu->kvm->mmu_lock);
3689                                 return -ENOSPC;
3690                         }
3691                         sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3692                                         i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3693                         root = __pa(sp->spt);
3694                         ++sp->root_count;
3695                         spin_unlock(&vcpu->kvm->mmu_lock);
3696                         vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
3697                 }
3698                 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
3699         } else
3700                 BUG();
3701
3702         return 0;
3703 }
3704
3705 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3706 {
3707         struct kvm_mmu_page *sp;
3708         u64 pdptr, pm_mask;
3709         gfn_t root_gfn;
3710         int i;
3711
3712         root_gfn = vcpu->arch.mmu.get_cr3(vcpu) >> PAGE_SHIFT;
3713
3714         if (mmu_check_root(vcpu, root_gfn))
3715                 return 1;
3716
3717         /*
3718          * Do we shadow a long mode page table? If so we need to
3719          * write-protect the guests page table root.
3720          */
3721         if (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL) {
3722                 hpa_t root = vcpu->arch.mmu.root_hpa;
3723
3724                 MMU_WARN_ON(VALID_PAGE(root));
3725
3726                 spin_lock(&vcpu->kvm->mmu_lock);
3727                 if (make_mmu_pages_available(vcpu) < 0) {
3728                         spin_unlock(&vcpu->kvm->mmu_lock);
3729                         return -ENOSPC;
3730                 }
3731                 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3732                                 vcpu->arch.mmu.shadow_root_level, 0, ACC_ALL);
3733                 root = __pa(sp->spt);
3734                 ++sp->root_count;
3735                 spin_unlock(&vcpu->kvm->mmu_lock);
3736                 vcpu->arch.mmu.root_hpa = root;
3737                 return 0;
3738         }
3739
3740         /*
3741          * We shadow a 32 bit page table. This may be a legacy 2-level
3742          * or a PAE 3-level page table. In either case we need to be aware that
3743          * the shadow page table may be a PAE or a long mode page table.
3744          */
3745         pm_mask = PT_PRESENT_MASK;
3746         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_4LEVEL)
3747                 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3748
3749         for (i = 0; i < 4; ++i) {
3750                 hpa_t root = vcpu->arch.mmu.pae_root[i];
3751
3752                 MMU_WARN_ON(VALID_PAGE(root));
3753                 if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
3754                         pdptr = vcpu->arch.mmu.get_pdptr(vcpu, i);
3755                         if (!(pdptr & PT_PRESENT_MASK)) {
3756                                 vcpu->arch.mmu.pae_root[i] = 0;
3757                                 continue;
3758                         }
3759                         root_gfn = pdptr >> PAGE_SHIFT;
3760                         if (mmu_check_root(vcpu, root_gfn))
3761                                 return 1;
3762                 }
3763                 spin_lock(&vcpu->kvm->mmu_lock);
3764                 if (make_mmu_pages_available(vcpu) < 0) {
3765                         spin_unlock(&vcpu->kvm->mmu_lock);
3766                         return -ENOSPC;
3767                 }
3768                 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3769                                       0, ACC_ALL);
3770                 root = __pa(sp->spt);
3771                 ++sp->root_count;
3772                 spin_unlock(&vcpu->kvm->mmu_lock);
3773
3774                 vcpu->arch.mmu.pae_root[i] = root | pm_mask;
3775         }
3776         vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
3777
3778         /*
3779          * If we shadow a 32 bit page table with a long mode page
3780          * table we enter this path.
3781          */
3782         if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_4LEVEL) {
3783                 if (vcpu->arch.mmu.lm_root == NULL) {
3784                         /*
3785                          * The additional page necessary for this is only
3786                          * allocated on demand.
3787                          */
3788
3789                         u64 *lm_root;
3790
3791                         lm_root = (void*)get_zeroed_page(GFP_KERNEL);
3792                         if (lm_root == NULL)
3793                                 return 1;
3794
3795                         lm_root[0] = __pa(vcpu->arch.mmu.pae_root) | pm_mask;
3796
3797                         vcpu->arch.mmu.lm_root = lm_root;
3798                 }
3799
3800                 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.lm_root);
3801         }
3802
3803         return 0;
3804 }
3805
3806 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3807 {
3808         if (vcpu->arch.mmu.direct_map)
3809                 return mmu_alloc_direct_roots(vcpu);
3810         else
3811                 return mmu_alloc_shadow_roots(vcpu);
3812 }
3813
3814 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3815 {
3816         int i;
3817         struct kvm_mmu_page *sp;
3818
3819         if (vcpu->arch.mmu.direct_map)
3820                 return;
3821
3822         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3823                 return;
3824
3825         vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3826
3827         if (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL) {
3828                 hpa_t root = vcpu->arch.mmu.root_hpa;
3829
3830                 sp = page_header(root);
3831
3832                 /*
3833                  * Even if another CPU was marking the SP as unsync-ed
3834                  * simultaneously, any guest page table changes are not
3835                  * guaranteed to be visible anyway until this VCPU issues a TLB
3836                  * flush strictly after those changes are made. We only need to
3837                  * ensure that the other CPU sets these flags before any actual
3838                  * changes to the page tables are made. The comments in
3839                  * mmu_need_write_protect() describe what could go wrong if this
3840                  * requirement isn't satisfied.
3841                  */
3842                 if (!smp_load_acquire(&sp->unsync) &&
3843                     !smp_load_acquire(&sp->unsync_children))
3844                         return;
3845
3846                 spin_lock(&vcpu->kvm->mmu_lock);
3847                 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3848
3849                 mmu_sync_children(vcpu, sp);
3850
3851                 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3852                 spin_unlock(&vcpu->kvm->mmu_lock);
3853                 return;
3854         }
3855
3856         spin_lock(&vcpu->kvm->mmu_lock);
3857         kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3858
3859         for (i = 0; i < 4; ++i) {
3860                 hpa_t root = vcpu->arch.mmu.pae_root[i];
3861
3862                 if (root && VALID_PAGE(root)) {
3863                         root &= PT64_BASE_ADDR_MASK;
3864                         sp = page_header(root);
3865                         mmu_sync_children(vcpu, sp);
3866                 }
3867         }
3868
3869         kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3870         spin_unlock(&vcpu->kvm->mmu_lock);
3871 }
3872 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3873
3874 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gpa_t vaddr,
3875                                   u32 access, struct x86_exception *exception)
3876 {
3877         if (exception)
3878                 exception->error_code = 0;
3879         return vaddr;
3880 }
3881
3882 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gpa_t vaddr,
3883                                          u32 access,
3884                                          struct x86_exception *exception)
3885 {
3886         if (exception)
3887                 exception->error_code = 0;
3888         return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3889 }
3890
3891 static bool
3892 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3893 {
3894         int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3895
3896         return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3897                 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3898 }
3899
3900 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3901 {
3902         return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3903 }
3904
3905 static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3906 {
3907         return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3908 }
3909
3910 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3911 {
3912         /*
3913          * A nested guest cannot use the MMIO cache if it is using nested
3914          * page tables, because cr2 is a nGPA while the cache stores GPAs.
3915          */
3916         if (mmu_is_nested(vcpu))
3917                 return false;
3918
3919         if (direct)
3920                 return vcpu_match_mmio_gpa(vcpu, addr);
3921
3922         return vcpu_match_mmio_gva(vcpu, addr);
3923 }
3924
3925 /* return true if reserved bit is detected on spte. */
3926 static bool
3927 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3928 {
3929         struct kvm_shadow_walk_iterator iterator;
3930         u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3931         int root, leaf;
3932         bool reserved = false;
3933
3934         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3935                 goto exit;
3936
3937         walk_shadow_page_lockless_begin(vcpu);
3938
3939         for (shadow_walk_init(&iterator, vcpu, addr),
3940                  leaf = root = iterator.level;
3941              shadow_walk_okay(&iterator);
3942              __shadow_walk_next(&iterator, spte)) {
3943                 spte = mmu_spte_get_lockless(iterator.sptep);
3944
3945                 sptes[leaf - 1] = spte;
3946                 leaf--;
3947
3948                 if (!is_shadow_present_pte(spte))
3949                         break;
3950
3951                 reserved |= is_shadow_zero_bits_set(&vcpu->arch.mmu, spte,
3952                                                     iterator.level);
3953         }
3954
3955         walk_shadow_page_lockless_end(vcpu);
3956
3957         if (reserved) {
3958                 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3959                        __func__, addr);
3960                 while (root > leaf) {
3961                         pr_err("------ spte 0x%llx level %d.\n",
3962                                sptes[root - 1], root);
3963                         root--;
3964                 }
3965         }
3966 exit:
3967         *sptep = spte;
3968         return reserved;
3969 }
3970
3971 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3972 {
3973         u64 spte;
3974         bool reserved;
3975
3976         if (mmio_info_in_cache(vcpu, addr, direct))
3977                 return RET_PF_EMULATE;
3978
3979         reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3980         if (WARN_ON(reserved))
3981                 return -EINVAL;
3982
3983         if (is_mmio_spte(spte)) {
3984                 gfn_t gfn = get_mmio_spte_gfn(spte);
3985                 unsigned access = get_mmio_spte_access(spte);
3986
3987                 if (!check_mmio_spte(vcpu, spte))
3988                         return RET_PF_INVALID;
3989
3990                 if (direct)
3991                         addr = 0;
3992
3993                 trace_handle_mmio_page_fault(addr, gfn, access);
3994                 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3995                 return RET_PF_EMULATE;
3996         }
3997
3998         /*
3999          * If the page table is zapped by other cpus, let CPU fault again on
4000          * the address.
4001          */
4002         return RET_PF_RETRY;
4003 }
4004
4005 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
4006                                          u32 error_code, gfn_t gfn)
4007 {
4008         if (unlikely(error_code & PFERR_RSVD_MASK))
4009                 return false;
4010
4011         if (!(error_code & PFERR_PRESENT_MASK) ||
4012               !(error_code & PFERR_WRITE_MASK))
4013                 return false;
4014
4015         /*
4016          * guest is writing the page which is write tracked which can
4017          * not be fixed by page fault handler.
4018          */
4019         if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
4020                 return true;
4021
4022         return false;
4023 }
4024
4025 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
4026 {
4027         struct kvm_shadow_walk_iterator iterator;
4028         u64 spte;
4029
4030         if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
4031                 return;
4032
4033         walk_shadow_page_lockless_begin(vcpu);
4034         for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
4035                 clear_sp_write_flooding_count(iterator.sptep);
4036                 if (!is_shadow_present_pte(spte))
4037                         break;
4038         }
4039         walk_shadow_page_lockless_end(vcpu);
4040 }
4041
4042 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa,
4043                                 u32 error_code, bool prefault)
4044 {
4045         gfn_t gfn = gpa >> PAGE_SHIFT;
4046         int r;
4047
4048         /* Note, paging is disabled, ergo gva == gpa. */
4049         pgprintk("%s: gva %lx error %x\n", __func__, gpa, error_code);
4050
4051         if (page_fault_handle_page_track(vcpu, error_code, gfn))
4052                 return RET_PF_EMULATE;
4053
4054         r = mmu_topup_memory_caches(vcpu);
4055         if (r)
4056                 return r;
4057
4058         MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
4059
4060
4061         return nonpaging_map(vcpu, gpa & PAGE_MASK,
4062                              error_code, gfn, prefault);
4063 }
4064
4065 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa,
4066                                    gfn_t gfn)
4067 {
4068         struct kvm_arch_async_pf arch;
4069
4070         arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
4071         arch.gfn = gfn;
4072         arch.direct_map = vcpu->arch.mmu.direct_map;
4073         arch.cr3 = vcpu->arch.mmu.get_cr3(vcpu);
4074
4075         return kvm_setup_async_pf(vcpu, cr2_or_gpa,
4076                                   kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
4077 }
4078
4079 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
4080 {
4081         if (unlikely(!lapic_in_kernel(vcpu) ||
4082                      kvm_event_needs_reinjection(vcpu) ||
4083                      vcpu->arch.exception.pending))
4084                 return false;
4085
4086         if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
4087                 return false;
4088
4089         return kvm_x86_ops->interrupt_allowed(vcpu);
4090 }
4091
4092 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
4093                          gpa_t cr2_or_gpa, kvm_pfn_t *pfn, bool write,
4094                          bool *writable)
4095 {
4096         struct kvm_memory_slot *slot;
4097         bool async;
4098
4099         /*
4100          * Don't expose private memslots to L2.
4101          */
4102         if (is_guest_mode(vcpu) && !kvm_is_visible_gfn(vcpu->kvm, gfn)) {
4103                 *pfn = KVM_PFN_NOSLOT;
4104                 return false;
4105         }
4106
4107         slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
4108         async = false;
4109         *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
4110         if (!async)
4111                 return false; /* *pfn has correct page already */
4112
4113         if (!prefault && kvm_can_do_async_pf(vcpu)) {
4114                 trace_kvm_try_async_get_page(cr2_or_gpa, gfn);
4115                 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
4116                         trace_kvm_async_pf_doublefault(cr2_or_gpa, gfn);
4117                         kvm_make_request(KVM_REQ_APF_HALT, vcpu);
4118                         return true;
4119                 } else if (kvm_arch_setup_async_pf(vcpu, cr2_or_gpa, gfn))
4120                         return true;
4121         }
4122
4123         *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
4124         return false;
4125 }
4126
4127 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
4128                                 u64 fault_address, char *insn, int insn_len)
4129 {
4130         int r = 1;
4131
4132 #ifndef CONFIG_X86_64
4133         /* A 64-bit CR2 should be impossible on 32-bit KVM. */
4134         if (WARN_ON_ONCE(fault_address >> 32))
4135                 return -EFAULT;
4136 #endif
4137
4138         vcpu->arch.l1tf_flush_l1d = true;
4139         switch (vcpu->arch.apf.host_apf_reason) {
4140         default:
4141                 trace_kvm_page_fault(fault_address, error_code);
4142
4143                 if (kvm_event_needs_reinjection(vcpu))
4144                         kvm_mmu_unprotect_page_virt(vcpu, fault_address);
4145                 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
4146                                 insn_len);
4147                 break;
4148         case KVM_PV_REASON_PAGE_NOT_PRESENT:
4149                 vcpu->arch.apf.host_apf_reason = 0;
4150                 local_irq_disable();
4151                 kvm_async_pf_task_wait(fault_address, 0);
4152                 local_irq_enable();
4153                 break;
4154         case KVM_PV_REASON_PAGE_READY:
4155                 vcpu->arch.apf.host_apf_reason = 0;
4156                 local_irq_disable();
4157                 kvm_async_pf_task_wake(fault_address);
4158                 local_irq_enable();
4159                 break;
4160         }
4161         return r;
4162 }
4163 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4164
4165 static bool
4166 check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
4167 {
4168         int page_num = KVM_PAGES_PER_HPAGE(level);
4169
4170         gfn &= ~(page_num - 1);
4171
4172         return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
4173 }
4174
4175 static int tdp_page_fault(struct kvm_vcpu *vcpu, gpa_t gpa, u32 error_code,
4176                           bool prefault)
4177 {
4178         kvm_pfn_t pfn;
4179         int r;
4180         int level;
4181         bool force_pt_level;
4182         gfn_t gfn = gpa >> PAGE_SHIFT;
4183         unsigned long mmu_seq;
4184         int write = error_code & PFERR_WRITE_MASK;
4185         bool map_writable;
4186         bool lpage_disallowed = (error_code & PFERR_FETCH_MASK) &&
4187                                 is_nx_huge_page_enabled();
4188
4189         MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
4190
4191         if (page_fault_handle_page_track(vcpu, error_code, gfn))
4192                 return RET_PF_EMULATE;
4193
4194         r = mmu_topup_memory_caches(vcpu);
4195         if (r)
4196                 return r;
4197
4198         force_pt_level =
4199                 lpage_disallowed ||
4200                 !check_hugepage_cache_consistency(vcpu, gfn, PT_DIRECTORY_LEVEL);
4201         level = mapping_level(vcpu, gfn, &force_pt_level);
4202         if (likely(!force_pt_level)) {
4203                 if (level > PT_DIRECTORY_LEVEL &&
4204                     !check_hugepage_cache_consistency(vcpu, gfn, level))
4205                         level = PT_DIRECTORY_LEVEL;
4206                 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
4207         }
4208
4209         if (fast_page_fault(vcpu, gpa, level, error_code))
4210                 return RET_PF_RETRY;
4211
4212         mmu_seq = vcpu->kvm->mmu_notifier_seq;
4213         smp_rmb();
4214
4215         if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4216                 return RET_PF_RETRY;
4217
4218         if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
4219                 return r;
4220
4221         r = RET_PF_RETRY;
4222         spin_lock(&vcpu->kvm->mmu_lock);
4223         if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4224                 goto out_unlock;
4225         if (make_mmu_pages_available(vcpu) < 0)
4226                 goto out_unlock;
4227         if (likely(!force_pt_level))
4228                 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
4229         r = __direct_map(vcpu, gpa, write, map_writable, level, pfn,
4230                          prefault, lpage_disallowed);
4231 out_unlock:
4232         spin_unlock(&vcpu->kvm->mmu_lock);
4233         kvm_release_pfn_clean(pfn);
4234         return r;
4235 }
4236
4237 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4238                                    struct kvm_mmu *context)
4239 {
4240         context->page_fault = nonpaging_page_fault;
4241         context->gva_to_gpa = nonpaging_gva_to_gpa;
4242         context->sync_page = nonpaging_sync_page;
4243         context->invlpg = nonpaging_invlpg;
4244         context->update_pte = nonpaging_update_pte;
4245         context->root_level = 0;
4246         context->shadow_root_level = PT32E_ROOT_LEVEL;
4247         context->direct_map = true;
4248         context->nx = false;
4249 }
4250
4251 /*
4252  * Find out if a previously cached root matching the new CR3/role is available.
4253  * The current root is also inserted into the cache.
4254  * If a matching root was found, it is assigned to kvm_mmu->root_hpa and true is
4255  * returned.
4256  * Otherwise, the LRU root from the cache is assigned to kvm_mmu->root_hpa and
4257  * false is returned. This root should now be freed by the caller.
4258  */
4259 static bool cached_root_available(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4260                                   union kvm_mmu_page_role new_role)
4261 {
4262         uint i;
4263         struct kvm_mmu_root_info root;
4264         struct kvm_mmu *mmu = &vcpu->arch.mmu;
4265
4266         root.cr3 = mmu->get_cr3(vcpu);
4267         root.hpa = mmu->root_hpa;
4268
4269         for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
4270                 swap(root, mmu->prev_roots[i]);
4271
4272                 if (new_cr3 == root.cr3 && VALID_PAGE(root.hpa) &&
4273                     page_header(root.hpa) != NULL &&
4274                     new_role.word == page_header(root.hpa)->role.word)
4275                         break;
4276         }
4277
4278         mmu->root_hpa = root.hpa;
4279
4280         return i < KVM_MMU_NUM_PREV_ROOTS;
4281 }
4282
4283 static bool fast_cr3_switch(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4284                             union kvm_mmu_page_role new_role,
4285                             bool skip_tlb_flush)
4286 {
4287         struct kvm_mmu *mmu = &vcpu->arch.mmu;
4288
4289         /*
4290          * For now, limit the fast switch to 64-bit hosts+VMs in order to avoid
4291          * having to deal with PDPTEs. We may add support for 32-bit hosts/VMs
4292          * later if necessary.
4293          */
4294         if (mmu->shadow_root_level >= PT64_ROOT_4LEVEL &&
4295             mmu->root_level >= PT64_ROOT_4LEVEL) {
4296                 if (mmu_check_root(vcpu, new_cr3 >> PAGE_SHIFT))
4297                         return false;
4298
4299                 if (cached_root_available(vcpu, new_cr3, new_role)) {
4300                         /*
4301                          * It is possible that the cached previous root page is
4302                          * obsolete because of a change in the MMU
4303                          * generation number. However, that is accompanied by
4304                          * KVM_REQ_MMU_RELOAD, which will free the root that we
4305                          * have set here and allocate a new one.
4306                          */
4307
4308                         kvm_make_request(KVM_REQ_LOAD_CR3, vcpu);
4309                         if (!skip_tlb_flush) {
4310                                 kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
4311                                 kvm_x86_ops->tlb_flush(vcpu, true);
4312                         }
4313
4314                         /*
4315                          * The last MMIO access's GVA and GPA are cached in the
4316                          * VCPU. When switching to a new CR3, that GVA->GPA
4317                          * mapping may no longer be valid. So clear any cached
4318                          * MMIO info even when we don't need to sync the shadow
4319                          * page tables.
4320                          */
4321                         vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
4322
4323                         __clear_sp_write_flooding_count(
4324                                 page_header(mmu->root_hpa));
4325
4326                         return true;
4327                 }
4328         }
4329
4330         return false;
4331 }
4332
4333 static void __kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3,
4334                               union kvm_mmu_page_role new_role,
4335                               bool skip_tlb_flush)
4336 {
4337         if (!fast_cr3_switch(vcpu, new_cr3, new_role, skip_tlb_flush))
4338                 kvm_mmu_free_roots(vcpu, KVM_MMU_ROOT_CURRENT);
4339 }
4340
4341 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu, gpa_t new_cr3, bool skip_tlb_flush)
4342 {
4343         __kvm_mmu_new_cr3(vcpu, new_cr3, kvm_mmu_calc_root_page_role(vcpu),
4344                           skip_tlb_flush);
4345 }
4346 EXPORT_SYMBOL_GPL(kvm_mmu_new_cr3);
4347
4348 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4349 {
4350         return kvm_read_cr3(vcpu);
4351 }
4352
4353 static void inject_page_fault(struct kvm_vcpu *vcpu,
4354                               struct x86_exception *fault)
4355 {
4356         vcpu->arch.mmu.inject_page_fault(vcpu, fault);
4357 }
4358
4359 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4360                            unsigned access, int *nr_present)
4361 {
4362         if (unlikely(is_mmio_spte(*sptep))) {
4363                 if (gfn != get_mmio_spte_gfn(*sptep)) {
4364                         mmu_spte_clear_no_track(sptep);
4365                         return true;
4366                 }
4367
4368                 (*nr_present)++;
4369                 mark_mmio_spte(vcpu, sptep, gfn, access);
4370                 return true;
4371         }
4372
4373         return false;
4374 }
4375
4376 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4377                                 unsigned level, unsigned gpte)
4378 {
4379         /*
4380          * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4381          * If it is clear, there are no large pages at this level, so clear
4382          * PT_PAGE_SIZE_MASK in gpte if that is the case.
4383          */
4384         gpte &= level - mmu->last_nonleaf_level;
4385
4386         /*
4387          * PT_PAGE_TABLE_LEVEL always terminates.  The RHS has bit 7 set
4388          * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4389          * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4390          */
4391         gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4392
4393         return gpte & PT_PAGE_SIZE_MASK;
4394 }
4395
4396 #define PTTYPE_EPT 18 /* arbitrary */
4397 #define PTTYPE PTTYPE_EPT
4398 #include "paging_tmpl.h"
4399 #undef PTTYPE
4400
4401 #define PTTYPE 64
4402 #include "paging_tmpl.h"
4403 #undef PTTYPE
4404
4405 #define PTTYPE 32
4406 #include "paging_tmpl.h"
4407 #undef PTTYPE
4408
4409 static void
4410 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4411                         struct rsvd_bits_validate *rsvd_check,
4412                         int maxphyaddr, int level, bool nx, bool gbpages,
4413                         bool pse, bool amd)
4414 {
4415         u64 exb_bit_rsvd = 0;
4416         u64 gbpages_bit_rsvd = 0;
4417         u64 nonleaf_bit8_rsvd = 0;
4418
4419         rsvd_check->bad_mt_xwr = 0;
4420
4421         if (!nx)
4422                 exb_bit_rsvd = rsvd_bits(63, 63);
4423         if (!gbpages)
4424                 gbpages_bit_rsvd = rsvd_bits(7, 7);
4425
4426         /*
4427          * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4428          * leaf entries) on AMD CPUs only.
4429          */
4430         if (amd)
4431                 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4432
4433         switch (level) {
4434         case PT32_ROOT_LEVEL:
4435                 /* no rsvd bits for 2 level 4K page table entries */
4436                 rsvd_check->rsvd_bits_mask[0][1] = 0;
4437                 rsvd_check->rsvd_bits_mask[0][0] = 0;
4438                 rsvd_check->rsvd_bits_mask[1][0] =
4439                         rsvd_check->rsvd_bits_mask[0][0];
4440
4441                 if (!pse) {
4442                         rsvd_check->rsvd_bits_mask[1][1] = 0;
4443                         break;
4444                 }
4445
4446                 if (is_cpuid_PSE36())
4447                         /* 36bits PSE 4MB page */
4448                         rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4449                 else
4450                         /* 32 bits PSE 4MB page */
4451                         rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4452                 break;
4453         case PT32E_ROOT_LEVEL:
4454                 rsvd_check->rsvd_bits_mask[0][2] =
4455                         rsvd_bits(maxphyaddr, 63) |
4456                         rsvd_bits(5, 8) | rsvd_bits(1, 2);      /* PDPTE */
4457                 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4458                         rsvd_bits(maxphyaddr, 62);      /* PDE */
4459                 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4460                         rsvd_bits(maxphyaddr, 62);      /* PTE */
4461                 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4462                         rsvd_bits(maxphyaddr, 62) |
4463                         rsvd_bits(13, 20);              /* large page */
4464                 rsvd_check->rsvd_bits_mask[1][0] =
4465                         rsvd_check->rsvd_bits_mask[0][0];
4466                 break;
4467         case PT64_ROOT_5LEVEL:
4468                 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4469                         nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4470                         rsvd_bits(maxphyaddr, 51);
4471                 rsvd_check->rsvd_bits_mask[1][4] =
4472                         rsvd_check->rsvd_bits_mask[0][4];
4473         case PT64_ROOT_4LEVEL:
4474                 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4475                         nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4476                         rsvd_bits(maxphyaddr, 51);
4477                 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4478                         gbpages_bit_rsvd |
4479                         rsvd_bits(maxphyaddr, 51);
4480                 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4481                         rsvd_bits(maxphyaddr, 51);
4482                 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4483                         rsvd_bits(maxphyaddr, 51);
4484                 rsvd_check->rsvd_bits_mask[1][3] =
4485                         rsvd_check->rsvd_bits_mask[0][3];
4486                 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4487                         gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4488                         rsvd_bits(13, 29);
4489                 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4490                         rsvd_bits(maxphyaddr, 51) |
4491                         rsvd_bits(13, 20);              /* large page */
4492                 rsvd_check->rsvd_bits_mask[1][0] =
4493                         rsvd_check->rsvd_bits_mask[0][0];
4494                 break;
4495         }
4496 }
4497
4498 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4499                                   struct kvm_mmu *context)
4500 {
4501         __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4502                                 cpuid_maxphyaddr(vcpu), context->root_level,
4503                                 context->nx,
4504                                 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4505                                 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4506 }
4507
4508 static void
4509 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4510                             int maxphyaddr, bool execonly)
4511 {
4512         u64 bad_mt_xwr;
4513
4514         rsvd_check->rsvd_bits_mask[0][4] =
4515                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4516         rsvd_check->rsvd_bits_mask[0][3] =
4517                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4518         rsvd_check->rsvd_bits_mask[0][2] =
4519                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4520         rsvd_check->rsvd_bits_mask[0][1] =
4521                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4522         rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4523
4524         /* large page */
4525         rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4526         rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4527         rsvd_check->rsvd_bits_mask[1][2] =
4528                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4529         rsvd_check->rsvd_bits_mask[1][1] =
4530                 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4531         rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4532
4533         bad_mt_xwr = 0xFFull << (2 * 8);        /* bits 3..5 must not be 2 */
4534         bad_mt_xwr |= 0xFFull << (3 * 8);       /* bits 3..5 must not be 3 */
4535         bad_mt_xwr |= 0xFFull << (7 * 8);       /* bits 3..5 must not be 7 */
4536         bad_mt_xwr |= REPEAT_BYTE(1ull << 2);   /* bits 0..2 must not be 010 */
4537         bad_mt_xwr |= REPEAT_BYTE(1ull << 6);   /* bits 0..2 must not be 110 */
4538         if (!execonly) {
4539                 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4540                 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4541         }
4542         rsvd_check->bad_mt_xwr = bad_mt_xwr;
4543 }
4544
4545 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4546                 struct kvm_mmu *context, bool execonly)
4547 {
4548         __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4549                                     cpuid_maxphyaddr(vcpu), execonly);
4550 }
4551
4552 /*
4553  * the page table on host is the shadow page table for the page
4554  * table in guest or amd nested guest, its mmu features completely
4555  * follow the features in guest.
4556  */
4557 void
4558 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4559 {
4560         /*
4561          * KVM uses NX when TDP is disabled to handle a variety of scenarios,
4562          * notably for huge SPTEs if iTLB multi-hit mitigation is enabled and
4563          * to generate correct permissions for CR0.WP=0/CR4.SMEP=1/EFER.NX=0.
4564          * The iTLB multi-hit workaround can be toggled at any time, so assume
4565          * NX can be used by any non-nested shadow MMU to avoid having to reset
4566          * MMU contexts.  Note, KVM forces EFER.NX=1 when TDP is disabled.
4567          */
4568         bool uses_nx = context->nx || !tdp_enabled ||
4569                 context->base_role.smep_andnot_wp;
4570         struct rsvd_bits_validate *shadow_zero_check;
4571         int i;
4572
4573         /*
4574          * Passing "true" to the last argument is okay; it adds a check
4575          * on bit 8 of the SPTEs which KVM doesn't use anyway.
4576          */
4577         shadow_zero_check = &context->shadow_zero_check;
4578         __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4579                                 shadow_phys_bits,
4580                                 context->shadow_root_level, uses_nx,
4581                                 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4582                                 is_pse(vcpu), true);
4583
4584         if (!shadow_me_mask)
4585                 return;
4586
4587         for (i = context->shadow_root_level; --i >= 0;) {
4588                 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4589                 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4590         }
4591
4592 }
4593 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4594
4595 static inline bool boot_cpu_is_amd(void)
4596 {
4597         WARN_ON_ONCE(!tdp_enabled);
4598         return shadow_x_mask == 0;
4599 }
4600
4601 /*
4602  * the direct page table on host, use as much mmu features as
4603  * possible, however, kvm currently does not do execution-protection.
4604  */
4605 static void
4606 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4607                                 struct kvm_mmu *context)
4608 {
4609         struct rsvd_bits_validate *shadow_zero_check;
4610         int i;
4611
4612         shadow_zero_check = &context->shadow_zero_check;
4613
4614         if (boot_cpu_is_amd())
4615                 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4616                                         shadow_phys_bits,
4617                                         context->shadow_root_level, false,
4618                                         boot_cpu_has(X86_FEATURE_GBPAGES),
4619                                         true, true);
4620         else
4621                 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4622                                             shadow_phys_bits,
4623                                             false);
4624
4625         if (!shadow_me_mask)
4626                 return;
4627
4628         for (i = context->shadow_root_level; --i >= 0;) {
4629                 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4630                 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4631         }
4632 }
4633
4634 /*
4635  * as the comments in reset_shadow_zero_bits_mask() except it
4636  * is the shadow page table for intel nested guest.
4637  */
4638 static void
4639 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4640                                 struct kvm_mmu *context, bool execonly)
4641 {
4642         __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4643                                     shadow_phys_bits, execonly);
4644 }
4645
4646 #define BYTE_MASK(access) \
4647         ((1 & (access) ? 2 : 0) | \
4648          (2 & (access) ? 4 : 0) | \
4649          (3 & (access) ? 8 : 0) | \
4650          (4 & (access) ? 16 : 0) | \
4651          (5 & (access) ? 32 : 0) | \
4652          (6 & (access) ? 64 : 0) | \
4653          (7 & (access) ? 128 : 0))
4654
4655
4656 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4657                                       struct kvm_mmu *mmu, bool ept)
4658 {
4659         unsigned byte;
4660
4661         const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4662         const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4663         const u8 u = BYTE_MASK(ACC_USER_MASK);
4664
4665         bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4666         bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4667         bool cr0_wp = is_write_protection(vcpu);
4668
4669         for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4670                 unsigned pfec = byte << 1;
4671
4672                 /*
4673                  * Each "*f" variable has a 1 bit for each UWX value
4674                  * that causes a fault with the given PFEC.
4675                  */
4676
4677                 /* Faults from writes to non-writable pages */
4678                 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4679                 /* Faults from user mode accesses to supervisor pages */
4680                 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4681                 /* Faults from fetches of non-executable pages*/
4682                 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4683                 /* Faults from kernel mode fetches of user pages */
4684                 u8 smepf = 0;
4685                 /* Faults from kernel mode accesses of user pages */
4686                 u8 smapf = 0;
4687
4688                 if (!ept) {
4689                         /* Faults from kernel mode accesses to user pages */
4690                         u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4691
4692                         /* Not really needed: !nx will cause pte.nx to fault */
4693                         if (!mmu->nx)
4694                                 ff = 0;
4695
4696                         /* Allow supervisor writes if !cr0.wp */
4697                         if (!cr0_wp)
4698                                 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4699
4700                         /* Disallow supervisor fetches of user code if cr4.smep */
4701                         if (cr4_smep)
4702                                 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4703
4704                         /*
4705                          * SMAP:kernel-mode data accesses from user-mode
4706                          * mappings should fault. A fault is considered
4707                          * as a SMAP violation if all of the following
4708                          * conditions are ture:
4709                          *   - X86_CR4_SMAP is set in CR4
4710                          *   - A user page is accessed
4711                          *   - The access is not a fetch
4712                          *   - Page fault in kernel mode
4713                          *   - if CPL = 3 or X86_EFLAGS_AC is clear
4714                          *
4715                          * Here, we cover the first three conditions.
4716                          * The fourth is computed dynamically in permission_fault();
4717                          * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4718                          * *not* subject to SMAP restrictions.
4719                          */
4720                         if (cr4_smap)
4721                                 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4722                 }
4723
4724                 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4725         }
4726 }
4727
4728 /*
4729 * PKU is an additional mechanism by which the paging controls access to
4730 * user-mode addresses based on the value in the PKRU register.  Protection
4731 * key violations are reported through a bit in the page fault error code.
4732 * Unlike other bits of the error code, the PK bit is not known at the
4733 * call site of e.g. gva_to_gpa; it must be computed directly in
4734 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4735 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4736 *
4737 * In particular the following conditions come from the error code, the
4738 * page tables and the machine state:
4739 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4740 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4741 * - PK is always zero if U=0 in the page tables
4742 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4743 *
4744 * The PKRU bitmask caches the result of these four conditions.  The error
4745 * code (minus the P bit) and the page table's U bit form an index into the
4746 * PKRU bitmask.  Two bits of the PKRU bitmask are then extracted and ANDed
4747 * with the two bits of the PKRU register corresponding to the protection key.
4748 * For the first three conditions above the bits will be 00, thus masking
4749 * away both AD and WD.  For all reads or if the last condition holds, WD
4750 * only will be masked away.
4751 */
4752 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4753                                 bool ept)
4754 {
4755         unsigned bit;
4756         bool wp;
4757
4758         if (ept) {
4759                 mmu->pkru_mask = 0;
4760                 return;
4761         }
4762
4763         /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4764         if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4765                 mmu->pkru_mask = 0;
4766                 return;
4767         }
4768
4769         wp = is_write_protection(vcpu);
4770
4771         for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4772                 unsigned pfec, pkey_bits;
4773                 bool check_pkey, check_write, ff, uf, wf, pte_user;
4774
4775                 pfec = bit << 1;
4776                 ff = pfec & PFERR_FETCH_MASK;
4777                 uf = pfec & PFERR_USER_MASK;
4778                 wf = pfec & PFERR_WRITE_MASK;
4779
4780                 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4781                 pte_user = pfec & PFERR_RSVD_MASK;
4782
4783                 /*
4784                  * Only need to check the access which is not an
4785                  * instruction fetch and is to a user page.
4786                  */
4787                 check_pkey = (!ff && pte_user);
4788                 /*
4789                  * write access is controlled by PKRU if it is a
4790                  * user access or CR0.WP = 1.
4791                  */
4792                 check_write = check_pkey && wf && (uf || wp);
4793
4794                 /* PKRU.AD stops both read and write access. */
4795                 pkey_bits = !!check_pkey;
4796                 /* PKRU.WD stops write access. */
4797                 pkey_bits |= (!!check_write) << 1;
4798
4799                 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4800         }
4801 }
4802
4803 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4804 {
4805         unsigned root_level = mmu->root_level;
4806
4807         mmu->last_nonleaf_level = root_level;
4808         if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4809                 mmu->last_nonleaf_level++;
4810 }
4811
4812 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4813                                          struct kvm_mmu *context,
4814                                          int level)
4815 {
4816         context->nx = is_nx(vcpu);
4817         context->root_level = level;
4818
4819         reset_rsvds_bits_mask(vcpu, context);
4820         update_permission_bitmask(vcpu, context, false);
4821         update_pkru_bitmask(vcpu, context, false);
4822         update_last_nonleaf_level(vcpu, context);
4823
4824         MMU_WARN_ON(!is_pae(vcpu));
4825         context->page_fault = paging64_page_fault;
4826         context->gva_to_gpa = paging64_gva_to_gpa;
4827         context->sync_page = paging64_sync_page;
4828         context->invlpg = paging64_invlpg;
4829         context->update_pte = paging64_update_pte;
4830         context->shadow_root_level = level;
4831         context->direct_map = false;
4832 }
4833
4834 static void paging64_init_context(struct kvm_vcpu *vcpu,
4835                                   struct kvm_mmu *context)
4836 {
4837         int root_level = is_la57_mode(vcpu) ?
4838                          PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4839
4840         paging64_init_context_common(vcpu, context, root_level);
4841 }
4842
4843 static void paging32_init_context(struct kvm_vcpu *vcpu,
4844                                   struct kvm_mmu *context)
4845 {
4846         context->nx = false;
4847         context->root_level = PT32_ROOT_LEVEL;
4848
4849         reset_rsvds_bits_mask(vcpu, context);
4850         update_permission_bitmask(vcpu, context, false);
4851         update_pkru_bitmask(vcpu, context, false);
4852         update_last_nonleaf_level(vcpu, context);
4853
4854         context->page_fault = paging32_page_fault;
4855         context->gva_to_gpa = paging32_gva_to_gpa;
4856         context->sync_page = paging32_sync_page;
4857         context->invlpg = paging32_invlpg;
4858         context->update_pte = paging32_update_pte;
4859         context->shadow_root_level = PT32E_ROOT_LEVEL;
4860         context->direct_map = false;
4861 }
4862
4863 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4864                                    struct kvm_mmu *context)
4865 {
4866         paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4867 }
4868
4869 static union kvm_mmu_page_role
4870 kvm_calc_tdp_mmu_root_page_role(struct kvm_vcpu *vcpu)
4871 {
4872         union kvm_mmu_page_role role = {0};
4873
4874         role.guest_mode = is_guest_mode(vcpu);
4875         role.smm = is_smm(vcpu);
4876         role.ad_disabled = (shadow_accessed_mask == 0);
4877         role.level = kvm_x86_ops->get_tdp_level(vcpu);
4878         role.direct = true;
4879         role.access = ACC_ALL;
4880
4881         return role;
4882 }
4883
4884 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4885 {
4886         struct kvm_mmu *context = &vcpu->arch.mmu;
4887
4888         context->base_role.word = mmu_base_role_mask.word &
4889                                   kvm_calc_tdp_mmu_root_page_role(vcpu).word;
4890         context->page_fault = tdp_page_fault;
4891         context->sync_page = nonpaging_sync_page;
4892         context->invlpg = nonpaging_invlpg;
4893         context->update_pte = nonpaging_update_pte;
4894         context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
4895         context->direct_map = true;
4896         context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
4897         context->get_cr3 = get_cr3;
4898         context->get_pdptr = kvm_pdptr_read;
4899         context->inject_page_fault = kvm_inject_page_fault;
4900
4901         if (!is_paging(vcpu)) {
4902                 context->nx = false;
4903                 context->gva_to_gpa = nonpaging_gva_to_gpa;
4904                 context->root_level = 0;
4905         } else if (is_long_mode(vcpu)) {
4906                 context->nx = is_nx(vcpu);
4907                 context->root_level = is_la57_mode(vcpu) ?
4908                                 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4909                 reset_rsvds_bits_mask(vcpu, context);
4910                 context->gva_to_gpa = paging64_gva_to_gpa;
4911         } else if (is_pae(vcpu)) {
4912                 context->nx = is_nx(vcpu);
4913                 context->root_level = PT32E_ROOT_LEVEL;
4914                 reset_rsvds_bits_mask(vcpu, context);
4915                 context->gva_to_gpa = paging64_gva_to_gpa;
4916         } else {
4917                 context->nx = false;
4918                 context->root_level = PT32_ROOT_LEVEL;
4919                 reset_rsvds_bits_mask(vcpu, context);
4920                 context->gva_to_gpa = paging32_gva_to_gpa;
4921         }
4922
4923         update_permission_bitmask(vcpu, context, false);
4924         update_pkru_bitmask(vcpu, context, false);
4925         update_last_nonleaf_level(vcpu, context);
4926         reset_tdp_shadow_zero_bits_mask(vcpu, context);
4927 }
4928
4929 static union kvm_mmu_page_role
4930 kvm_calc_shadow_mmu_root_page_role(struct kvm_vcpu *vcpu)
4931 {
4932         union kvm_mmu_page_role role = {0};
4933         bool smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4934         bool smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4935
4936         role.nxe = is_nx(vcpu);
4937         role.cr4_pae = !!is_pae(vcpu);
4938         role.cr0_wp  = is_write_protection(vcpu);
4939         role.smep_andnot_wp = smep && !is_write_protection(vcpu);
4940         role.smap_andnot_wp = smap && !is_write_protection(vcpu);
4941         role.guest_mode = is_guest_mode(vcpu);
4942         role.smm = is_smm(vcpu);
4943         role.direct = !is_paging(vcpu);
4944         role.access = ACC_ALL;
4945
4946         if (!is_long_mode(vcpu))
4947                 role.level = PT32E_ROOT_LEVEL;
4948         else if (is_la57_mode(vcpu))
4949                 role.level = PT64_ROOT_5LEVEL;
4950         else
4951                 role.level = PT64_ROOT_4LEVEL;
4952
4953         return role;
4954 }
4955
4956 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4957 {
4958         struct kvm_mmu *context = &vcpu->arch.mmu;
4959
4960         if (!is_paging(vcpu))
4961                 nonpaging_init_context(vcpu, context);
4962         else if (is_long_mode(vcpu))
4963                 paging64_init_context(vcpu, context);
4964         else if (is_pae(vcpu))
4965                 paging32E_init_context(vcpu, context);
4966         else
4967                 paging32_init_context(vcpu, context);
4968
4969         context->base_role.word = mmu_base_role_mask.word &
4970                                   kvm_calc_shadow_mmu_root_page_role(vcpu).word;
4971         reset_shadow_zero_bits_mask(vcpu, context);
4972 }
4973 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4974
4975 static union kvm_mmu_page_role
4976 kvm_calc_shadow_ept_root_page_role(struct kvm_vcpu *vcpu, bool accessed_dirty)
4977 {
4978         union kvm_mmu_page_role role = vcpu->arch.mmu.base_role;
4979
4980         role.level = PT64_ROOT_4LEVEL;
4981         role.direct = false;
4982         role.ad_disabled = !accessed_dirty;
4983         role.guest_mode = true;
4984         role.access = ACC_ALL;
4985
4986         return role;
4987 }
4988
4989 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4990                              bool accessed_dirty, gpa_t new_eptp)
4991 {
4992         struct kvm_mmu *context = &vcpu->arch.mmu;
4993         union kvm_mmu_page_role root_page_role =
4994                 kvm_calc_shadow_ept_root_page_role(vcpu, accessed_dirty);
4995
4996         __kvm_mmu_new_cr3(vcpu, new_eptp, root_page_role, false);
4997         context->shadow_root_level = PT64_ROOT_4LEVEL;
4998
4999         context->nx = true;
5000         context->ept_ad = accessed_dirty;
5001         context->page_fault = ept_page_fault;
5002         context->gva_to_gpa = ept_gva_to_gpa;
5003         context->sync_page = ept_sync_page;
5004         context->invlpg = ept_invlpg;
5005         context->update_pte = ept_update_pte;
5006         context->root_level = PT64_ROOT_4LEVEL;
5007         context->direct_map = false;
5008         context->base_role.word = root_page_role.word & mmu_base_role_mask.word;
5009         update_permission_bitmask(vcpu, context, true);
5010         update_pkru_bitmask(vcpu, context, true);
5011         update_last_nonleaf_level(vcpu, context);
5012         reset_rsvds_bits_mask_ept(vcpu, context, execonly);
5013         reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
5014 }
5015 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
5016
5017 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
5018 {
5019         struct kvm_mmu *context = &vcpu->arch.mmu;
5020
5021         kvm_init_shadow_mmu(vcpu);
5022         context->set_cr3           = kvm_x86_ops->set_cr3;
5023         context->get_cr3           = get_cr3;
5024         context->get_pdptr         = kvm_pdptr_read;
5025         context->inject_page_fault = kvm_inject_page_fault;
5026 }
5027
5028 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
5029 {
5030         struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
5031
5032         g_context->get_cr3           = get_cr3;
5033         g_context->get_pdptr         = kvm_pdptr_read;
5034         g_context->inject_page_fault = kvm_inject_page_fault;
5035
5036         /*
5037          * Note that arch.mmu.gva_to_gpa translates l2_gpa to l1_gpa using
5038          * L1's nested page tables (e.g. EPT12). The nested translation
5039          * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
5040          * L2's page tables as the first level of translation and L1's
5041          * nested page tables as the second level of translation. Basically
5042          * the gva_to_gpa functions between mmu and nested_mmu are swapped.
5043          */
5044         if (!is_paging(vcpu)) {
5045                 g_context->nx = false;
5046                 g_context->root_level = 0;
5047                 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
5048         } else if (is_long_mode(vcpu)) {
5049                 g_context->nx = is_nx(vcpu);
5050                 g_context->root_level = is_la57_mode(vcpu) ?
5051                                         PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
5052                 reset_rsvds_bits_mask(vcpu, g_context);
5053                 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5054         } else if (is_pae(vcpu)) {
5055                 g_context->nx = is_nx(vcpu);
5056                 g_context->root_level = PT32E_ROOT_LEVEL;
5057                 reset_rsvds_bits_mask(vcpu, g_context);
5058                 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
5059         } else {
5060                 g_context->nx = false;
5061                 g_context->root_level = PT32_ROOT_LEVEL;
5062                 reset_rsvds_bits_mask(vcpu, g_context);
5063                 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
5064         }
5065
5066         update_permission_bitmask(vcpu, g_context, false);
5067         update_pkru_bitmask(vcpu, g_context, false);
5068         update_last_nonleaf_level(vcpu, g_context);
5069 }
5070
5071 void kvm_init_mmu(struct kvm_vcpu *vcpu, bool reset_roots)
5072 {
5073         if (reset_roots) {
5074                 uint i;
5075
5076                 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
5077
5078                 for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5079                         vcpu->arch.mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5080         }
5081
5082         if (mmu_is_nested(vcpu))
5083                 init_kvm_nested_mmu(vcpu);
5084         else if (tdp_enabled)
5085                 init_kvm_tdp_mmu(vcpu);
5086         else
5087                 init_kvm_softmmu(vcpu);
5088 }
5089 EXPORT_SYMBOL_GPL(kvm_init_mmu);
5090
5091 static union kvm_mmu_page_role
5092 kvm_mmu_calc_root_page_role(struct kvm_vcpu *vcpu)
5093 {
5094         if (tdp_enabled)
5095                 return kvm_calc_tdp_mmu_root_page_role(vcpu);
5096         else
5097                 return kvm_calc_shadow_mmu_root_page_role(vcpu);
5098 }
5099
5100 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
5101 {
5102         kvm_mmu_unload(vcpu);
5103         kvm_init_mmu(vcpu, true);
5104 }
5105 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
5106
5107 int kvm_mmu_load(struct kvm_vcpu *vcpu)
5108 {
5109         int r;
5110
5111         r = mmu_topup_memory_caches(vcpu);
5112         if (r)
5113                 goto out;
5114         r = mmu_alloc_roots(vcpu);
5115         kvm_mmu_sync_roots(vcpu);
5116         if (r)
5117                 goto out;
5118         kvm_mmu_load_cr3(vcpu);
5119         kvm_x86_ops->tlb_flush(vcpu, true);
5120 out:
5121         return r;
5122 }
5123 EXPORT_SYMBOL_GPL(kvm_mmu_load);
5124
5125 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
5126 {
5127         kvm_mmu_free_roots(vcpu, KVM_MMU_ROOTS_ALL);
5128         WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
5129 }
5130 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
5131
5132 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
5133                                   struct kvm_mmu_page *sp, u64 *spte,
5134                                   const void *new)
5135 {
5136         if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
5137                 ++vcpu->kvm->stat.mmu_pde_zapped;
5138                 return;
5139         }
5140
5141         ++vcpu->kvm->stat.mmu_pte_updated;
5142         vcpu->arch.mmu.update_pte(vcpu, sp, spte, new);
5143 }
5144
5145 static bool need_remote_flush(u64 old, u64 new)
5146 {
5147         if (!is_shadow_present_pte(old))
5148                 return false;
5149         if (!is_shadow_present_pte(new))
5150                 return true;
5151         if ((old ^ new) & PT64_BASE_ADDR_MASK)
5152                 return true;
5153         old ^= shadow_nx_mask;
5154         new ^= shadow_nx_mask;
5155         return (old & ~new & PT64_PERM_MASK) != 0;
5156 }
5157
5158 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
5159                                     int *bytes)
5160 {
5161         u64 gentry = 0;
5162         int r;
5163
5164         /*
5165          * Assume that the pte write on a page table of the same type
5166          * as the current vcpu paging mode since we update the sptes only
5167          * when they have the same mode.
5168          */
5169         if (is_pae(vcpu) && *bytes == 4) {
5170                 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
5171                 *gpa &= ~(gpa_t)7;
5172                 *bytes = 8;
5173         }
5174
5175         if (*bytes == 4 || *bytes == 8) {
5176                 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
5177                 if (r)
5178                         gentry = 0;
5179         }
5180
5181         return gentry;
5182 }
5183
5184 /*
5185  * If we're seeing too many writes to a page, it may no longer be a page table,
5186  * or we may be forking, in which case it is better to unmap the page.
5187  */
5188 static bool detect_write_flooding(struct kvm_mmu_page *sp)
5189 {
5190         /*
5191          * Skip write-flooding detected for the sp whose level is 1, because
5192          * it can become unsync, then the guest page is not write-protected.
5193          */
5194         if (sp->role.level == PT_PAGE_TABLE_LEVEL)
5195                 return false;
5196
5197         atomic_inc(&sp->write_flooding_count);
5198         return atomic_read(&sp->write_flooding_count) >= 3;
5199 }
5200
5201 /*
5202  * Misaligned accesses are too much trouble to fix up; also, they usually
5203  * indicate a page is not used as a page table.
5204  */
5205 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
5206                                     int bytes)
5207 {
5208         unsigned offset, pte_size, misaligned;
5209
5210         pgprintk("misaligned: gpa %llx bytes %d role %x\n",
5211                  gpa, bytes, sp->role.word);
5212
5213         offset = offset_in_page(gpa);
5214         pte_size = sp->role.cr4_pae ? 8 : 4;
5215
5216         /*
5217          * Sometimes, the OS only writes the last one bytes to update status
5218          * bits, for example, in linux, andb instruction is used in clear_bit().
5219          */
5220         if (!(offset & (pte_size - 1)) && bytes == 1)
5221                 return false;
5222
5223         misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
5224         misaligned |= bytes < 4;
5225
5226         return misaligned;
5227 }
5228
5229 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
5230 {
5231         unsigned page_offset, quadrant;
5232         u64 *spte;
5233         int level;
5234
5235         page_offset = offset_in_page(gpa);
5236         level = sp->role.level;
5237         *nspte = 1;
5238         if (!sp->role.cr4_pae) {
5239                 page_offset <<= 1;      /* 32->64 */
5240                 /*
5241                  * A 32-bit pde maps 4MB while the shadow pdes map
5242                  * only 2MB.  So we need to double the offset again
5243                  * and zap two pdes instead of one.
5244                  */
5245                 if (level == PT32_ROOT_LEVEL) {
5246                         page_offset &= ~7; /* kill rounding error */
5247                         page_offset <<= 1;
5248                         *nspte = 2;
5249                 }
5250                 quadrant = page_offset >> PAGE_SHIFT;
5251                 page_offset &= ~PAGE_MASK;
5252                 if (quadrant != sp->role.quadrant)
5253                         return NULL;
5254         }
5255
5256         spte = &sp->spt[page_offset / sizeof(*spte)];
5257         return spte;
5258 }
5259
5260 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
5261                               const u8 *new, int bytes,
5262                               struct kvm_page_track_notifier_node *node)
5263 {
5264         gfn_t gfn = gpa >> PAGE_SHIFT;
5265         struct kvm_mmu_page *sp;
5266         LIST_HEAD(invalid_list);
5267         u64 entry, gentry, *spte;
5268         int npte;
5269         bool remote_flush, local_flush;
5270
5271         /*
5272          * If we don't have indirect shadow pages, it means no page is
5273          * write-protected, so we can exit simply.
5274          */
5275         if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
5276                 return;
5277
5278         remote_flush = local_flush = false;
5279
5280         pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
5281
5282         /*
5283          * No need to care whether allocation memory is successful
5284          * or not since pte prefetch is skiped if it does not have
5285          * enough objects in the cache.
5286          */
5287         mmu_topup_memory_caches(vcpu);
5288
5289         spin_lock(&vcpu->kvm->mmu_lock);
5290
5291         gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
5292
5293         ++vcpu->kvm->stat.mmu_pte_write;
5294         kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
5295
5296         for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
5297                 if (detect_write_misaligned(sp, gpa, bytes) ||
5298                       detect_write_flooding(sp)) {
5299                         kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
5300                         ++vcpu->kvm->stat.mmu_flooded;
5301                         continue;
5302                 }
5303
5304                 spte = get_written_sptes(sp, gpa, &npte);
5305                 if (!spte)
5306                         continue;
5307
5308                 local_flush = true;
5309                 while (npte--) {
5310                         entry = *spte;
5311                         mmu_page_zap_pte(vcpu->kvm, sp, spte);
5312                         if (gentry &&
5313                               !((sp->role.word ^ vcpu->arch.mmu.base_role.word)
5314                               & mmu_base_role_mask.word) && rmap_can_add(vcpu))
5315                                 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5316                         if (need_remote_flush(entry, *spte))
5317                                 remote_flush = true;
5318                         ++spte;
5319                 }
5320         }
5321         kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5322         kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5323         spin_unlock(&vcpu->kvm->mmu_lock);
5324 }
5325
5326 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5327 {
5328         gpa_t gpa;
5329         int r;
5330
5331         if (vcpu->arch.mmu.direct_map)
5332                 return 0;
5333
5334         gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5335
5336         r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5337
5338         return r;
5339 }
5340 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5341
5342 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
5343 {
5344         LIST_HEAD(invalid_list);
5345
5346         if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
5347                 return 0;
5348
5349         while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
5350                 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
5351                         break;
5352
5353                 ++vcpu->kvm->stat.mmu_recycled;
5354         }
5355         kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
5356
5357         if (!kvm_mmu_available_pages(vcpu->kvm))
5358                 return -ENOSPC;
5359         return 0;
5360 }
5361
5362 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gpa_t cr2_or_gpa, u64 error_code,
5363                        void *insn, int insn_len)
5364 {
5365         int r, emulation_type = 0;
5366         enum emulation_result er;
5367         bool direct = vcpu->arch.mmu.direct_map;
5368
5369         /* With shadow page tables, fault_address contains a GVA or nGPA.  */
5370         if (vcpu->arch.mmu.direct_map) {
5371                 vcpu->arch.gpa_available = true;
5372                 vcpu->arch.gpa_val = cr2_or_gpa;
5373         }
5374
5375         r = RET_PF_INVALID;
5376         if (unlikely(error_code & PFERR_RSVD_MASK)) {
5377                 r = handle_mmio_page_fault(vcpu, cr2_or_gpa, direct);
5378                 if (r == RET_PF_EMULATE)
5379                         goto emulate;
5380         }
5381
5382         if (r == RET_PF_INVALID) {
5383                 r = vcpu->arch.mmu.page_fault(vcpu, cr2_or_gpa,
5384                                                lower_32_bits(error_code),
5385                                                false);
5386                 WARN_ON(r == RET_PF_INVALID);
5387         }
5388
5389         if (r == RET_PF_RETRY)
5390                 return 1;
5391         if (r < 0)
5392                 return r;
5393
5394         /*
5395          * Before emulating the instruction, check if the error code
5396          * was due to a RO violation while translating the guest page.
5397          * This can occur when using nested virtualization with nested
5398          * paging in both guests. If true, we simply unprotect the page
5399          * and resume the guest.
5400          */
5401         if (vcpu->arch.mmu.direct_map &&
5402             (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5403                 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2_or_gpa));
5404                 return 1;
5405         }
5406
5407         /*
5408          * vcpu->arch.mmu.page_fault returned RET_PF_EMULATE, but we can still
5409          * optimistically try to just unprotect the page and let the processor
5410          * re-execute the instruction that caused the page fault.  Do not allow
5411          * retrying MMIO emulation, as it's not only pointless but could also
5412          * cause us to enter an infinite loop because the processor will keep
5413          * faulting on the non-existent MMIO address.  Retrying an instruction
5414          * from a nested guest is also pointless and dangerous as we are only
5415          * explicitly shadowing L1's page tables, i.e. unprotecting something
5416          * for L1 isn't going to magically fix whatever issue cause L2 to fail.
5417          */
5418         if (!mmio_info_in_cache(vcpu, cr2_or_gpa, direct) && !is_guest_mode(vcpu))
5419                 emulation_type = EMULTYPE_ALLOW_RETRY;
5420 emulate:
5421         /*
5422          * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5423          * This can happen if a guest gets a page-fault on data access but the HW
5424          * table walker is not able to read the instruction page (e.g instruction
5425          * page is not present in memory). In those cases we simply restart the
5426          * guest.
5427          */
5428         if (unlikely(insn && !insn_len))
5429                 return 1;
5430
5431         er = x86_emulate_instruction(vcpu, cr2_or_gpa, emulation_type, insn, insn_len);
5432
5433         switch (er) {
5434         case EMULATE_DONE:
5435                 return 1;
5436         case EMULATE_USER_EXIT:
5437                 ++vcpu->stat.mmio_exits;
5438                 /* fall through */
5439         case EMULATE_FAIL:
5440                 return 0;
5441         default:
5442                 BUG();
5443         }
5444 }
5445 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5446
5447 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5448 {
5449         struct kvm_mmu *mmu = &vcpu->arch.mmu;
5450         int i;
5451
5452         /* INVLPG on a * non-canonical address is a NOP according to the SDM.  */
5453         if (is_noncanonical_address(gva, vcpu))
5454                 return;
5455
5456         mmu->invlpg(vcpu, gva, mmu->root_hpa);
5457
5458         /*
5459          * INVLPG is required to invalidate any global mappings for the VA,
5460          * irrespective of PCID. Since it would take us roughly similar amount
5461          * of work to determine whether any of the prev_root mappings of the VA
5462          * is marked global, or to just sync it blindly, so we might as well
5463          * just always sync it.
5464          *
5465          * Mappings not reachable via the current cr3 or the prev_roots will be
5466          * synced when switching to that cr3, so nothing needs to be done here
5467          * for them.
5468          */
5469         for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5470                 if (VALID_PAGE(mmu->prev_roots[i].hpa))
5471                         mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5472
5473         kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5474         ++vcpu->stat.invlpg;
5475 }
5476 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5477
5478 void kvm_mmu_invpcid_gva(struct kvm_vcpu *vcpu, gva_t gva, unsigned long pcid)
5479 {
5480         struct kvm_mmu *mmu = &vcpu->arch.mmu;
5481         bool tlb_flush = false;
5482         uint i;
5483
5484         if (pcid == kvm_get_active_pcid(vcpu)) {
5485                 mmu->invlpg(vcpu, gva, mmu->root_hpa);
5486                 tlb_flush = true;
5487         }
5488
5489         for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++) {
5490                 if (VALID_PAGE(mmu->prev_roots[i].hpa) &&
5491                     pcid == kvm_get_pcid(vcpu, mmu->prev_roots[i].cr3)) {
5492                         mmu->invlpg(vcpu, gva, mmu->prev_roots[i].hpa);
5493                         tlb_flush = true;
5494                 }
5495         }
5496
5497         if (tlb_flush)
5498                 kvm_x86_ops->tlb_flush_gva(vcpu, gva);
5499
5500         ++vcpu->stat.invlpg;
5501
5502         /*
5503          * Mappings not reachable via the current cr3 or the prev_roots will be
5504          * synced when switching to that cr3, so nothing needs to be done here
5505          * for them.
5506          */
5507 }
5508 EXPORT_SYMBOL_GPL(kvm_mmu_invpcid_gva);
5509
5510 void kvm_enable_tdp(void)
5511 {
5512         tdp_enabled = true;
5513 }
5514 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5515
5516 void kvm_disable_tdp(void)
5517 {
5518         tdp_enabled = false;
5519 }
5520 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5521
5522 static void free_mmu_pages(struct kvm_vcpu *vcpu)
5523 {
5524         free_page((unsigned long)vcpu->arch.mmu.pae_root);
5525         free_page((unsigned long)vcpu->arch.mmu.lm_root);
5526 }
5527
5528 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
5529 {
5530         struct page *page;
5531         int i;
5532
5533         /*
5534          * When using PAE paging, the four PDPTEs are treated as 'root' pages,
5535          * while the PDP table is a per-vCPU construct that's allocated at MMU
5536          * creation.  When emulating 32-bit mode, cr3 is only 32 bits even on
5537          * x86_64.  Therefore we need to allocate the PDP table in the first
5538          * 4GB of memory, which happens to fit the DMA32 zone.  Except for
5539          * SVM's 32-bit NPT support, TDP paging doesn't use PAE paging and can
5540          * skip allocating the PDP table.
5541          */
5542         if (tdp_enabled && kvm_x86_ops->get_tdp_level(vcpu) > PT32E_ROOT_LEVEL)
5543                 return 0;
5544
5545         /*
5546          * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
5547          * Therefore we need to allocate shadow page tables in the first
5548          * 4GB of memory, which happens to fit the DMA32 zone.
5549          */
5550         page = alloc_page(GFP_KERNEL | __GFP_DMA32);
5551         if (!page)
5552                 return -ENOMEM;
5553
5554         vcpu->arch.mmu.pae_root = page_address(page);
5555         for (i = 0; i < 4; ++i)
5556                 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
5557
5558         return 0;
5559 }
5560
5561 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5562 {
5563         uint i;
5564
5565         vcpu->arch.walk_mmu = &vcpu->arch.mmu;
5566         vcpu->arch.mmu.root_hpa = INVALID_PAGE;
5567         vcpu->arch.mmu.translate_gpa = translate_gpa;
5568         vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5569
5570         for (i = 0; i < KVM_MMU_NUM_PREV_ROOTS; i++)
5571                 vcpu->arch.mmu.prev_roots[i] = KVM_MMU_ROOT_INFO_INVALID;
5572
5573         return alloc_mmu_pages(vcpu);
5574 }
5575
5576 void kvm_mmu_setup(struct kvm_vcpu *vcpu)
5577 {
5578         MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
5579
5580         /*
5581          * kvm_mmu_setup() is called only on vCPU initialization.  
5582          * Therefore, no need to reset mmu roots as they are not yet
5583          * initialized.
5584          */
5585         kvm_init_mmu(vcpu, false);
5586 }
5587
5588 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5589                         struct kvm_memory_slot *slot,
5590                         struct kvm_page_track_notifier_node *node)
5591 {
5592         kvm_mmu_invalidate_zap_all_pages(kvm);
5593 }
5594
5595 void kvm_mmu_init_vm(struct kvm *kvm)
5596 {
5597         struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5598
5599         node->track_write = kvm_mmu_pte_write;
5600         node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5601         kvm_page_track_register_notifier(kvm, node);
5602 }
5603
5604 void kvm_mmu_uninit_vm(struct kvm *kvm)
5605 {
5606         struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5607
5608         kvm_page_track_unregister_notifier(kvm, node);
5609 }
5610
5611 /* The return value indicates if tlb flush on all vcpus is needed. */
5612 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5613
5614 /* The caller should hold mmu-lock before calling this function. */
5615 static __always_inline bool
5616 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5617                         slot_level_handler fn, int start_level, int end_level,
5618                         gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5619 {
5620         struct slot_rmap_walk_iterator iterator;
5621         bool flush = false;
5622
5623         for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5624                         end_gfn, &iterator) {
5625                 if (iterator.rmap)
5626                         flush |= fn(kvm, iterator.rmap);
5627
5628                 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5629                         if (flush && lock_flush_tlb) {
5630                                 kvm_flush_remote_tlbs(kvm);
5631                                 flush = false;
5632                         }
5633                         cond_resched_lock(&kvm->mmu_lock);
5634                 }
5635         }
5636
5637         if (flush && lock_flush_tlb) {
5638                 kvm_flush_remote_tlbs(kvm);
5639                 flush = false;
5640         }
5641
5642         return flush;
5643 }
5644
5645 static __always_inline bool
5646 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5647                   slot_level_handler fn, int start_level, int end_level,
5648                   bool lock_flush_tlb)
5649 {
5650         return slot_handle_level_range(kvm, memslot, fn, start_level,
5651                         end_level, memslot->base_gfn,
5652                         memslot->base_gfn + memslot->npages - 1,
5653                         lock_flush_tlb);
5654 }
5655
5656 static __always_inline bool
5657 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5658                       slot_level_handler fn, bool lock_flush_tlb)
5659 {
5660         return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5661                                  PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5662 }
5663
5664 static __always_inline bool
5665 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5666                         slot_level_handler fn, bool lock_flush_tlb)
5667 {
5668         return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5669                                  PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5670 }
5671
5672 static __always_inline bool
5673 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5674                  slot_level_handler fn, bool lock_flush_tlb)
5675 {
5676         return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5677                                  PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5678 }
5679
5680 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5681 {
5682         struct kvm_memslots *slots;
5683         struct kvm_memory_slot *memslot;
5684         int i;
5685
5686         spin_lock(&kvm->mmu_lock);
5687         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5688                 slots = __kvm_memslots(kvm, i);
5689                 kvm_for_each_memslot(memslot, slots) {
5690                         gfn_t start, end;
5691
5692                         start = max(gfn_start, memslot->base_gfn);
5693                         end = min(gfn_end, memslot->base_gfn + memslot->npages);
5694                         if (start >= end)
5695                                 continue;
5696
5697                         slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5698                                                 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
5699                                                 start, end - 1, true);
5700                 }
5701         }
5702
5703         spin_unlock(&kvm->mmu_lock);
5704 }
5705
5706 static bool slot_rmap_write_protect(struct kvm *kvm,
5707                                     struct kvm_rmap_head *rmap_head)
5708 {
5709         return __rmap_write_protect(kvm, rmap_head, false);
5710 }
5711
5712 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5713                                       struct kvm_memory_slot *memslot)
5714 {
5715         bool flush;
5716
5717         spin_lock(&kvm->mmu_lock);
5718         flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5719                                       false);
5720         spin_unlock(&kvm->mmu_lock);
5721
5722         /*
5723          * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5724          * which do tlb flush out of mmu-lock should be serialized by
5725          * kvm->slots_lock otherwise tlb flush would be missed.
5726          */
5727         lockdep_assert_held(&kvm->slots_lock);
5728
5729         /*
5730          * We can flush all the TLBs out of the mmu lock without TLB
5731          * corruption since we just change the spte from writable to
5732          * readonly so that we only need to care the case of changing
5733          * spte from present to present (changing the spte from present
5734          * to nonpresent will flush all the TLBs immediately), in other
5735          * words, the only case we care is mmu_spte_update() where we
5736          * haved checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5737          * instead of PT_WRITABLE_MASK, that means it does not depend
5738          * on PT_WRITABLE_MASK anymore.
5739          */
5740         if (flush)
5741                 kvm_flush_remote_tlbs(kvm);
5742 }
5743
5744 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5745                                          struct kvm_rmap_head *rmap_head)
5746 {
5747         u64 *sptep;
5748         struct rmap_iterator iter;
5749         int need_tlb_flush = 0;
5750         kvm_pfn_t pfn;
5751         struct kvm_mmu_page *sp;
5752
5753 restart:
5754         for_each_rmap_spte(rmap_head, &iter, sptep) {
5755                 sp = page_header(__pa(sptep));
5756                 pfn = spte_to_pfn(*sptep);
5757
5758                 /*
5759                  * We cannot do huge page mapping for indirect shadow pages,
5760                  * which are found on the last rmap (level = 1) when not using
5761                  * tdp; such shadow pages are synced with the page table in
5762                  * the guest, and the guest page table is using 4K page size
5763                  * mapping if the indirect sp has level = 1.
5764                  */
5765                 if (sp->role.direct && !kvm_is_reserved_pfn(pfn) &&
5766                     !kvm_is_zone_device_pfn(pfn) &&
5767                     PageTransCompoundMap(pfn_to_page(pfn))) {
5768                         drop_spte(kvm, sptep);
5769                         need_tlb_flush = 1;
5770                         goto restart;
5771                 }
5772         }
5773
5774         return need_tlb_flush;
5775 }
5776
5777 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5778                                    const struct kvm_memory_slot *memslot)
5779 {
5780         /* FIXME: const-ify all uses of struct kvm_memory_slot.  */
5781         spin_lock(&kvm->mmu_lock);
5782         slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5783                          kvm_mmu_zap_collapsible_spte, true);
5784         spin_unlock(&kvm->mmu_lock);
5785 }
5786
5787 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5788                                    struct kvm_memory_slot *memslot)
5789 {
5790         bool flush;
5791
5792         spin_lock(&kvm->mmu_lock);
5793         flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5794         spin_unlock(&kvm->mmu_lock);
5795
5796         lockdep_assert_held(&kvm->slots_lock);
5797
5798         /*
5799          * It's also safe to flush TLBs out of mmu lock here as currently this
5800          * function is only used for dirty logging, in which case flushing TLB
5801          * out of mmu lock also guarantees no dirty pages will be lost in
5802          * dirty_bitmap.
5803          */
5804         if (flush)
5805                 kvm_flush_remote_tlbs(kvm);
5806 }
5807 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5808
5809 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5810                                         struct kvm_memory_slot *memslot)
5811 {
5812         bool flush;
5813
5814         spin_lock(&kvm->mmu_lock);
5815         flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5816                                         false);
5817         spin_unlock(&kvm->mmu_lock);
5818
5819         /* see kvm_mmu_slot_remove_write_access */
5820         lockdep_assert_held(&kvm->slots_lock);
5821
5822         if (flush)
5823                 kvm_flush_remote_tlbs(kvm);
5824 }
5825 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5826
5827 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5828                             struct kvm_memory_slot *memslot)
5829 {
5830         bool flush;
5831
5832         spin_lock(&kvm->mmu_lock);
5833         flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
5834         spin_unlock(&kvm->mmu_lock);
5835
5836         lockdep_assert_held(&kvm->slots_lock);
5837
5838         /* see kvm_mmu_slot_leaf_clear_dirty */
5839         if (flush)
5840                 kvm_flush_remote_tlbs(kvm);
5841 }
5842 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
5843
5844 #define BATCH_ZAP_PAGES 10
5845 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5846 {
5847         struct kvm_mmu_page *sp, *node;
5848         int batch = 0;
5849
5850 restart:
5851         list_for_each_entry_safe_reverse(sp, node,
5852               &kvm->arch.active_mmu_pages, link) {
5853                 int ret;
5854
5855                 /*
5856                  * No obsolete page exists before new created page since
5857                  * active_mmu_pages is the FIFO list.
5858                  */
5859                 if (!is_obsolete_sp(kvm, sp))
5860                         break;
5861
5862                 /*
5863                  * Since we are reversely walking the list and the invalid
5864                  * list will be moved to the head, skip the invalid page
5865                  * can help us to avoid the infinity list walking.
5866                  */
5867                 if (sp->role.invalid)
5868                         continue;
5869
5870                 /*
5871                  * Need not flush tlb since we only zap the sp with invalid
5872                  * generation number.
5873                  */
5874                 if (batch >= BATCH_ZAP_PAGES &&
5875                       cond_resched_lock(&kvm->mmu_lock)) {
5876                         batch = 0;
5877                         goto restart;
5878                 }
5879
5880                 ret = kvm_mmu_prepare_zap_page(kvm, sp,
5881                                 &kvm->arch.zapped_obsolete_pages);
5882                 batch += ret;
5883
5884                 if (ret)
5885                         goto restart;
5886         }
5887
5888         /*
5889          * Should flush tlb before free page tables since lockless-walking
5890          * may use the pages.
5891          */
5892         kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5893 }
5894
5895 /*
5896  * Fast invalidate all shadow pages and use lock-break technique
5897  * to zap obsolete pages.
5898  *
5899  * It's required when memslot is being deleted or VM is being
5900  * destroyed, in these cases, we should ensure that KVM MMU does
5901  * not use any resource of the being-deleted slot or all slots
5902  * after calling the function.
5903  */
5904 void kvm_mmu_invalidate_zap_all_pages(struct kvm *kvm)
5905 {
5906         spin_lock(&kvm->mmu_lock);
5907         trace_kvm_mmu_invalidate_zap_all_pages(kvm);
5908         kvm->arch.mmu_valid_gen++;
5909
5910         /*
5911          * Notify all vcpus to reload its shadow page table
5912          * and flush TLB. Then all vcpus will switch to new
5913          * shadow page table with the new mmu_valid_gen.
5914          *
5915          * Note: we should do this under the protection of
5916          * mmu-lock, otherwise, vcpu would purge shadow page
5917          * but miss tlb flush.
5918          */
5919         kvm_reload_remote_mmus(kvm);
5920
5921         kvm_zap_obsolete_pages(kvm);
5922         spin_unlock(&kvm->mmu_lock);
5923 }
5924
5925 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5926 {
5927         return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5928 }
5929
5930 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
5931 {
5932         gen &= MMIO_GEN_MASK;
5933
5934         /*
5935          * Shift to eliminate the "update in-progress" flag, which isn't
5936          * included in the spte's generation number.
5937          */
5938         gen >>= 1;
5939
5940         /*
5941          * Generation numbers are incremented in multiples of the number of
5942          * address spaces in order to provide unique generations across all
5943          * address spaces.  Strip what is effectively the address space
5944          * modifier prior to checking for a wrap of the MMIO generation so
5945          * that a wrap in any address space is detected.
5946          */
5947         gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
5948
5949         /*
5950          * The very rare case: if the MMIO generation number has wrapped,
5951          * zap all shadow pages.
5952          */
5953         if (unlikely(gen == 0)) {
5954                 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
5955                 kvm_mmu_invalidate_zap_all_pages(kvm);
5956         }
5957 }
5958
5959 static unsigned long
5960 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
5961 {
5962         struct kvm *kvm;
5963         int nr_to_scan = sc->nr_to_scan;
5964         unsigned long freed = 0;
5965
5966         mutex_lock(&kvm_lock);
5967
5968         list_for_each_entry(kvm, &vm_list, vm_list) {
5969                 int idx;
5970                 LIST_HEAD(invalid_list);
5971
5972                 /*
5973                  * Never scan more than sc->nr_to_scan VM instances.
5974                  * Will not hit this condition practically since we do not try
5975                  * to shrink more than one VM and it is very unlikely to see
5976                  * !n_used_mmu_pages so many times.
5977                  */
5978                 if (!nr_to_scan--)
5979                         break;
5980                 /*
5981                  * n_used_mmu_pages is accessed without holding kvm->mmu_lock
5982                  * here. We may skip a VM instance errorneosly, but we do not
5983                  * want to shrink a VM that only started to populate its MMU
5984                  * anyway.
5985                  */
5986                 if (!kvm->arch.n_used_mmu_pages &&
5987                       !kvm_has_zapped_obsolete_pages(kvm))
5988                         continue;
5989
5990                 idx = srcu_read_lock(&kvm->srcu);
5991                 spin_lock(&kvm->mmu_lock);
5992
5993                 if (kvm_has_zapped_obsolete_pages(kvm)) {
5994                         kvm_mmu_commit_zap_page(kvm,
5995                               &kvm->arch.zapped_obsolete_pages);
5996                         goto unlock;
5997                 }
5998
5999                 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
6000                         freed++;
6001                 kvm_mmu_commit_zap_page(kvm, &invalid_list);
6002
6003 unlock:
6004                 spin_unlock(&kvm->mmu_lock);
6005                 srcu_read_unlock(&kvm->srcu, idx);
6006
6007                 /*
6008                  * unfair on small ones
6009                  * per-vm shrinkers cry out
6010                  * sadness comes quickly
6011                  */
6012                 list_move_tail(&kvm->vm_list, &vm_list);
6013                 break;
6014         }
6015
6016         mutex_unlock(&kvm_lock);
6017         return freed;
6018 }
6019
6020 static unsigned long
6021 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
6022 {
6023         return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
6024 }
6025
6026 static struct shrinker mmu_shrinker = {
6027         .count_objects = mmu_shrink_count,
6028         .scan_objects = mmu_shrink_scan,
6029         .seeks = DEFAULT_SEEKS * 10,
6030 };
6031
6032 static void mmu_destroy_caches(void)
6033 {
6034         kmem_cache_destroy(pte_list_desc_cache);
6035         kmem_cache_destroy(mmu_page_header_cache);
6036 }
6037
6038 static bool get_nx_auto_mode(void)
6039 {
6040         /* Return true when CPU has the bug, and mitigations are ON */
6041         return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
6042 }
6043
6044 static void __set_nx_huge_pages(bool val)
6045 {
6046         nx_huge_pages = itlb_multihit_kvm_mitigation = val;
6047 }
6048
6049 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
6050 {
6051         bool old_val = nx_huge_pages;
6052         bool new_val;
6053
6054         /* In "auto" mode deploy workaround only if CPU has the bug. */
6055         if (sysfs_streq(val, "off"))
6056                 new_val = 0;
6057         else if (sysfs_streq(val, "force"))
6058                 new_val = 1;
6059         else if (sysfs_streq(val, "auto"))
6060                 new_val = get_nx_auto_mode();
6061         else if (strtobool(val, &new_val) < 0)
6062                 return -EINVAL;
6063
6064         __set_nx_huge_pages(new_val);
6065
6066         if (new_val != old_val) {
6067                 struct kvm *kvm;
6068                 int idx;
6069
6070                 mutex_lock(&kvm_lock);
6071
6072                 list_for_each_entry(kvm, &vm_list, vm_list) {
6073                         idx = srcu_read_lock(&kvm->srcu);
6074                         kvm_mmu_invalidate_zap_all_pages(kvm);
6075                         srcu_read_unlock(&kvm->srcu, idx);
6076
6077                         wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6078                 }
6079                 mutex_unlock(&kvm_lock);
6080         }
6081
6082         return 0;
6083 }
6084
6085 static void kvm_set_mmio_spte_mask(void)
6086 {
6087         u64 mask;
6088
6089         /*
6090          * Set a reserved PA bit in MMIO SPTEs to generate page faults with
6091          * PFEC.RSVD=1 on MMIO accesses.  64-bit PTEs (PAE, x86-64, and EPT
6092          * paging) support a maximum of 52 bits of PA, i.e. if the CPU supports
6093          * 52-bit physical addresses then there are no reserved PA bits in the
6094          * PTEs and so the reserved PA approach must be disabled.
6095          */
6096         if (shadow_phys_bits < 52)
6097                 mask = BIT_ULL(51) | PT_PRESENT_MASK;
6098         else
6099                 mask = 0;
6100
6101         kvm_mmu_set_mmio_spte_mask(mask, mask);
6102 }
6103
6104 int kvm_mmu_module_init(void)
6105 {
6106         int ret = -ENOMEM;
6107
6108         if (nx_huge_pages == -1)
6109                 __set_nx_huge_pages(get_nx_auto_mode());
6110
6111         kvm_mmu_reset_all_pte_masks();
6112
6113         kvm_set_mmio_spte_mask();
6114
6115         pte_list_desc_cache = kmem_cache_create("pte_list_desc",
6116                                             sizeof(struct pte_list_desc),
6117                                             0, SLAB_ACCOUNT, NULL);
6118         if (!pte_list_desc_cache)
6119                 goto out;
6120
6121         mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
6122                                                   sizeof(struct kvm_mmu_page),
6123                                                   0, SLAB_ACCOUNT, NULL);
6124         if (!mmu_page_header_cache)
6125                 goto out;
6126
6127         if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
6128                 goto out;
6129
6130         ret = register_shrinker(&mmu_shrinker);
6131         if (ret)
6132                 goto out;
6133
6134         return 0;
6135
6136 out:
6137         mmu_destroy_caches();
6138         return ret;
6139 }
6140
6141 /*
6142  * Caculate mmu pages needed for kvm.
6143  */
6144 unsigned long kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
6145 {
6146         unsigned long nr_mmu_pages;
6147         unsigned long nr_pages = 0;
6148         struct kvm_memslots *slots;
6149         struct kvm_memory_slot *memslot;
6150         int i;
6151
6152         for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
6153                 slots = __kvm_memslots(kvm, i);
6154
6155                 kvm_for_each_memslot(memslot, slots)
6156                         nr_pages += memslot->npages;
6157         }
6158
6159         nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
6160         nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
6161
6162         return nr_mmu_pages;
6163 }
6164
6165 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
6166 {
6167         kvm_mmu_unload(vcpu);
6168         free_mmu_pages(vcpu);
6169         mmu_free_memory_caches(vcpu);
6170 }
6171
6172 void kvm_mmu_module_exit(void)
6173 {
6174         mmu_destroy_caches();
6175         percpu_counter_destroy(&kvm_total_used_mmu_pages);
6176         unregister_shrinker(&mmu_shrinker);
6177         mmu_audit_disable();
6178 }
6179
6180 static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp)
6181 {
6182         unsigned int old_val;
6183         int err;
6184
6185         old_val = nx_huge_pages_recovery_ratio;
6186         err = param_set_uint(val, kp);
6187         if (err)
6188                 return err;
6189
6190         if (READ_ONCE(nx_huge_pages) &&
6191             !old_val && nx_huge_pages_recovery_ratio) {
6192                 struct kvm *kvm;
6193
6194                 mutex_lock(&kvm_lock);
6195
6196                 list_for_each_entry(kvm, &vm_list, vm_list)
6197                         wake_up_process(kvm->arch.nx_lpage_recovery_thread);
6198
6199                 mutex_unlock(&kvm_lock);
6200         }
6201
6202         return err;
6203 }
6204
6205 static void kvm_recover_nx_lpages(struct kvm *kvm)
6206 {
6207         int rcu_idx;
6208         struct kvm_mmu_page *sp;
6209         unsigned int ratio;
6210         LIST_HEAD(invalid_list);
6211         ulong to_zap;
6212
6213         rcu_idx = srcu_read_lock(&kvm->srcu);
6214         spin_lock(&kvm->mmu_lock);
6215
6216         ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
6217         to_zap = ratio ? DIV_ROUND_UP(kvm->stat.nx_lpage_splits, ratio) : 0;
6218         while (to_zap && !list_empty(&kvm->arch.lpage_disallowed_mmu_pages)) {
6219                 /*
6220                  * We use a separate list instead of just using active_mmu_pages
6221                  * because the number of lpage_disallowed pages is expected to
6222                  * be relatively small compared to the total.
6223                  */
6224                 sp = list_first_entry(&kvm->arch.lpage_disallowed_mmu_pages,
6225                                       struct kvm_mmu_page,
6226                                       lpage_disallowed_link);
6227                 WARN_ON_ONCE(!sp->lpage_disallowed);
6228                 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
6229                 WARN_ON_ONCE(sp->lpage_disallowed);
6230
6231                 if (!--to_zap || need_resched() || spin_needbreak(&kvm->mmu_lock)) {
6232                         kvm_mmu_commit_zap_page(kvm, &invalid_list);
6233                         if (to_zap)
6234                                 cond_resched_lock(&kvm->mmu_lock);
6235                 }
6236         }
6237         kvm_mmu_commit_zap_page(kvm, &invalid_list);
6238
6239         spin_unlock(&kvm->mmu_lock);
6240         srcu_read_unlock(&kvm->srcu, rcu_idx);
6241 }
6242
6243 static long get_nx_lpage_recovery_timeout(u64 start_time)
6244 {
6245         return READ_ONCE(nx_huge_pages) && READ_ONCE(nx_huge_pages_recovery_ratio)
6246                 ? start_time + 60 * HZ - get_jiffies_64()
6247                 : MAX_SCHEDULE_TIMEOUT;
6248 }
6249
6250 static int kvm_nx_lpage_recovery_worker(struct kvm *kvm, uintptr_t data)
6251 {
6252         u64 start_time;
6253         long remaining_time;
6254
6255         while (true) {
6256                 start_time = get_jiffies_64();
6257                 remaining_time = get_nx_lpage_recovery_timeout(start_time);
6258
6259                 set_current_state(TASK_INTERRUPTIBLE);
6260                 while (!kthread_should_stop() && remaining_time > 0) {
6261                         schedule_timeout(remaining_time);
6262                         remaining_time = get_nx_lpage_recovery_timeout(start_time);
6263                         set_current_state(TASK_INTERRUPTIBLE);
6264                 }
6265
6266                 set_current_state(TASK_RUNNING);
6267
6268                 if (kthread_should_stop())
6269                         return 0;
6270
6271                 kvm_recover_nx_lpages(kvm);
6272         }
6273 }
6274
6275 int kvm_mmu_post_init_vm(struct kvm *kvm)
6276 {
6277         int err;
6278
6279         err = kvm_vm_create_worker_thread(kvm, kvm_nx_lpage_recovery_worker, 0,
6280                                           "kvm-nx-lpage-recovery",
6281                                           &kvm->arch.nx_lpage_recovery_thread);
6282         if (!err)
6283                 kthread_unpark(kvm->arch.nx_lpage_recovery_thread);
6284
6285         return err;
6286 }
6287
6288 void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
6289 {
6290         if (kvm->arch.nx_lpage_recovery_thread)
6291                 kthread_stop(kvm->arch.nx_lpage_recovery_thread);
6292 }