OSDN Git Service

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