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