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