OSDN Git Service

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