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