]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blob - arch/x86/kvm/mmu.c
c000e35feccef79a786380e825a5fb5d61f28a94
[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, gva_t gva, 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, gva, 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, gva, 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 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable);
3428 static int make_mmu_pages_available(struct kvm_vcpu *vcpu);
3429
3430 static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
3431 gfn_t gfn, bool prefault)
3432 {
3433 int r;
3434 int level;
3435 bool force_pt_level;
3436 kvm_pfn_t pfn;
3437 unsigned long mmu_seq;
3438 bool map_writable, write = error_code & PFERR_WRITE_MASK;
3439 bool lpage_disallowed = (error_code & PFERR_FETCH_MASK) &&
3440 is_nx_huge_page_enabled();
3441
3442 force_pt_level = lpage_disallowed;
3443 level = mapping_level(vcpu, gfn, &force_pt_level);
3444 if (likely(!force_pt_level)) {
3445 /*
3446 * This path builds a PAE pagetable - so we can map
3447 * 2mb pages at maximum. Therefore check if the level
3448 * is larger than that.
3449 */
3450 if (level > PT_DIRECTORY_LEVEL)
3451 level = PT_DIRECTORY_LEVEL;
3452
3453 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
3454 }
3455
3456 if (fast_page_fault(vcpu, v, level, error_code))
3457 return RET_PF_RETRY;
3458
3459 mmu_seq = vcpu->kvm->mmu_notifier_seq;
3460 smp_rmb();
3461
3462 if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
3463 return RET_PF_RETRY;
3464
3465 if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
3466 return r;
3467
3468 r = RET_PF_RETRY;
3469 spin_lock(&vcpu->kvm->mmu_lock);
3470 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
3471 goto out_unlock;
3472 if (make_mmu_pages_available(vcpu) < 0)
3473 goto out_unlock;
3474 if (likely(!force_pt_level))
3475 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
3476 r = __direct_map(vcpu, v, write, map_writable, level, pfn,
3477 prefault, false);
3478 out_unlock:
3479 spin_unlock(&vcpu->kvm->mmu_lock);
3480 kvm_release_pfn_clean(pfn);
3481 return r;
3482 }
3483
3484
3485 static void mmu_free_roots(struct kvm_vcpu *vcpu)
3486 {
3487 int i;
3488 struct kvm_mmu_page *sp;
3489 LIST_HEAD(invalid_list);
3490
3491 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3492 return;
3493
3494 if (vcpu->arch.mmu.shadow_root_level >= PT64_ROOT_4LEVEL &&
3495 (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL ||
3496 vcpu->arch.mmu.direct_map)) {
3497 hpa_t root = vcpu->arch.mmu.root_hpa;
3498
3499 spin_lock(&vcpu->kvm->mmu_lock);
3500 sp = page_header(root);
3501 --sp->root_count;
3502 if (!sp->root_count && sp->role.invalid) {
3503 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
3504 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3505 }
3506 spin_unlock(&vcpu->kvm->mmu_lock);
3507 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
3508 return;
3509 }
3510
3511 spin_lock(&vcpu->kvm->mmu_lock);
3512 for (i = 0; i < 4; ++i) {
3513 hpa_t root = vcpu->arch.mmu.pae_root[i];
3514
3515 if (root) {
3516 root &= PT64_BASE_ADDR_MASK;
3517 sp = page_header(root);
3518 --sp->root_count;
3519 if (!sp->root_count && sp->role.invalid)
3520 kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
3521 &invalid_list);
3522 }
3523 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
3524 }
3525 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
3526 spin_unlock(&vcpu->kvm->mmu_lock);
3527 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
3528 }
3529
3530 static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
3531 {
3532 int ret = 0;
3533
3534 if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
3535 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
3536 ret = 1;
3537 }
3538
3539 return ret;
3540 }
3541
3542 static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
3543 {
3544 struct kvm_mmu_page *sp;
3545 unsigned i;
3546
3547 if (vcpu->arch.mmu.shadow_root_level >= PT64_ROOT_4LEVEL) {
3548 spin_lock(&vcpu->kvm->mmu_lock);
3549 if(make_mmu_pages_available(vcpu) < 0) {
3550 spin_unlock(&vcpu->kvm->mmu_lock);
3551 return -ENOSPC;
3552 }
3553 sp = kvm_mmu_get_page(vcpu, 0, 0,
3554 vcpu->arch.mmu.shadow_root_level, 1, ACC_ALL);
3555 ++sp->root_count;
3556 spin_unlock(&vcpu->kvm->mmu_lock);
3557 vcpu->arch.mmu.root_hpa = __pa(sp->spt);
3558 } else if (vcpu->arch.mmu.shadow_root_level == PT32E_ROOT_LEVEL) {
3559 for (i = 0; i < 4; ++i) {
3560 hpa_t root = vcpu->arch.mmu.pae_root[i];
3561
3562 MMU_WARN_ON(VALID_PAGE(root));
3563 spin_lock(&vcpu->kvm->mmu_lock);
3564 if (make_mmu_pages_available(vcpu) < 0) {
3565 spin_unlock(&vcpu->kvm->mmu_lock);
3566 return -ENOSPC;
3567 }
3568 sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
3569 i << 30, PT32_ROOT_LEVEL, 1, ACC_ALL);
3570 root = __pa(sp->spt);
3571 ++sp->root_count;
3572 spin_unlock(&vcpu->kvm->mmu_lock);
3573 vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
3574 }
3575 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
3576 } else
3577 BUG();
3578
3579 return 0;
3580 }
3581
3582 static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
3583 {
3584 struct kvm_mmu_page *sp;
3585 u64 pdptr, pm_mask;
3586 gfn_t root_gfn;
3587 int i;
3588
3589 root_gfn = vcpu->arch.mmu.get_cr3(vcpu) >> PAGE_SHIFT;
3590
3591 if (mmu_check_root(vcpu, root_gfn))
3592 return 1;
3593
3594 /*
3595 * Do we shadow a long mode page table? If so we need to
3596 * write-protect the guests page table root.
3597 */
3598 if (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL) {
3599 hpa_t root = vcpu->arch.mmu.root_hpa;
3600
3601 MMU_WARN_ON(VALID_PAGE(root));
3602
3603 spin_lock(&vcpu->kvm->mmu_lock);
3604 if (make_mmu_pages_available(vcpu) < 0) {
3605 spin_unlock(&vcpu->kvm->mmu_lock);
3606 return -ENOSPC;
3607 }
3608 sp = kvm_mmu_get_page(vcpu, root_gfn, 0,
3609 vcpu->arch.mmu.shadow_root_level, 0, ACC_ALL);
3610 root = __pa(sp->spt);
3611 ++sp->root_count;
3612 spin_unlock(&vcpu->kvm->mmu_lock);
3613 vcpu->arch.mmu.root_hpa = root;
3614 return 0;
3615 }
3616
3617 /*
3618 * We shadow a 32 bit page table. This may be a legacy 2-level
3619 * or a PAE 3-level page table. In either case we need to be aware that
3620 * the shadow page table may be a PAE or a long mode page table.
3621 */
3622 pm_mask = PT_PRESENT_MASK;
3623 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_4LEVEL)
3624 pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
3625
3626 for (i = 0; i < 4; ++i) {
3627 hpa_t root = vcpu->arch.mmu.pae_root[i];
3628
3629 MMU_WARN_ON(VALID_PAGE(root));
3630 if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
3631 pdptr = vcpu->arch.mmu.get_pdptr(vcpu, i);
3632 if (!(pdptr & PT_PRESENT_MASK)) {
3633 vcpu->arch.mmu.pae_root[i] = 0;
3634 continue;
3635 }
3636 root_gfn = pdptr >> PAGE_SHIFT;
3637 if (mmu_check_root(vcpu, root_gfn))
3638 return 1;
3639 }
3640 spin_lock(&vcpu->kvm->mmu_lock);
3641 if (make_mmu_pages_available(vcpu) < 0) {
3642 spin_unlock(&vcpu->kvm->mmu_lock);
3643 return -ENOSPC;
3644 }
3645 sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30, PT32_ROOT_LEVEL,
3646 0, ACC_ALL);
3647 root = __pa(sp->spt);
3648 ++sp->root_count;
3649 spin_unlock(&vcpu->kvm->mmu_lock);
3650
3651 vcpu->arch.mmu.pae_root[i] = root | pm_mask;
3652 }
3653 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
3654
3655 /*
3656 * If we shadow a 32 bit page table with a long mode page
3657 * table we enter this path.
3658 */
3659 if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_4LEVEL) {
3660 if (vcpu->arch.mmu.lm_root == NULL) {
3661 /*
3662 * The additional page necessary for this is only
3663 * allocated on demand.
3664 */
3665
3666 u64 *lm_root;
3667
3668 lm_root = (void*)get_zeroed_page(GFP_KERNEL);
3669 if (lm_root == NULL)
3670 return 1;
3671
3672 lm_root[0] = __pa(vcpu->arch.mmu.pae_root) | pm_mask;
3673
3674 vcpu->arch.mmu.lm_root = lm_root;
3675 }
3676
3677 vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.lm_root);
3678 }
3679
3680 return 0;
3681 }
3682
3683 static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
3684 {
3685 if (vcpu->arch.mmu.direct_map)
3686 return mmu_alloc_direct_roots(vcpu);
3687 else
3688 return mmu_alloc_shadow_roots(vcpu);
3689 }
3690
3691 static void mmu_sync_roots(struct kvm_vcpu *vcpu)
3692 {
3693 int i;
3694 struct kvm_mmu_page *sp;
3695
3696 if (vcpu->arch.mmu.direct_map)
3697 return;
3698
3699 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3700 return;
3701
3702 vcpu_clear_mmio_info(vcpu, MMIO_GVA_ANY);
3703 kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
3704 if (vcpu->arch.mmu.root_level >= PT64_ROOT_4LEVEL) {
3705 hpa_t root = vcpu->arch.mmu.root_hpa;
3706 sp = page_header(root);
3707 mmu_sync_children(vcpu, sp);
3708 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3709 return;
3710 }
3711 for (i = 0; i < 4; ++i) {
3712 hpa_t root = vcpu->arch.mmu.pae_root[i];
3713
3714 if (root && VALID_PAGE(root)) {
3715 root &= PT64_BASE_ADDR_MASK;
3716 sp = page_header(root);
3717 mmu_sync_children(vcpu, sp);
3718 }
3719 }
3720 kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
3721 }
3722
3723 void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
3724 {
3725 spin_lock(&vcpu->kvm->mmu_lock);
3726 mmu_sync_roots(vcpu);
3727 spin_unlock(&vcpu->kvm->mmu_lock);
3728 }
3729 EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
3730
3731 static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
3732 u32 access, struct x86_exception *exception)
3733 {
3734 if (exception)
3735 exception->error_code = 0;
3736 return vaddr;
3737 }
3738
3739 static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
3740 u32 access,
3741 struct x86_exception *exception)
3742 {
3743 if (exception)
3744 exception->error_code = 0;
3745 return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access, exception);
3746 }
3747
3748 static bool
3749 __is_rsvd_bits_set(struct rsvd_bits_validate *rsvd_check, u64 pte, int level)
3750 {
3751 int bit7 = (pte >> 7) & 1, low6 = pte & 0x3f;
3752
3753 return (pte & rsvd_check->rsvd_bits_mask[bit7][level-1]) |
3754 ((rsvd_check->bad_mt_xwr & (1ull << low6)) != 0);
3755 }
3756
3757 static bool is_rsvd_bits_set(struct kvm_mmu *mmu, u64 gpte, int level)
3758 {
3759 return __is_rsvd_bits_set(&mmu->guest_rsvd_check, gpte, level);
3760 }
3761
3762 static bool is_shadow_zero_bits_set(struct kvm_mmu *mmu, u64 spte, int level)
3763 {
3764 return __is_rsvd_bits_set(&mmu->shadow_zero_check, spte, level);
3765 }
3766
3767 static bool mmio_info_in_cache(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3768 {
3769 /*
3770 * A nested guest cannot use the MMIO cache if it is using nested
3771 * page tables, because cr2 is a nGPA while the cache stores GPAs.
3772 */
3773 if (mmu_is_nested(vcpu))
3774 return false;
3775
3776 if (direct)
3777 return vcpu_match_mmio_gpa(vcpu, addr);
3778
3779 return vcpu_match_mmio_gva(vcpu, addr);
3780 }
3781
3782 /* return true if reserved bit is detected on spte. */
3783 static bool
3784 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr, u64 *sptep)
3785 {
3786 struct kvm_shadow_walk_iterator iterator;
3787 u64 sptes[PT64_ROOT_MAX_LEVEL], spte = 0ull;
3788 int root, leaf;
3789 bool reserved = false;
3790
3791 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3792 goto exit;
3793
3794 walk_shadow_page_lockless_begin(vcpu);
3795
3796 for (shadow_walk_init(&iterator, vcpu, addr),
3797 leaf = root = iterator.level;
3798 shadow_walk_okay(&iterator);
3799 __shadow_walk_next(&iterator, spte)) {
3800 spte = mmu_spte_get_lockless(iterator.sptep);
3801
3802 sptes[leaf - 1] = spte;
3803 leaf--;
3804
3805 if (!is_shadow_present_pte(spte))
3806 break;
3807
3808 reserved |= is_shadow_zero_bits_set(&vcpu->arch.mmu, spte,
3809 iterator.level);
3810 }
3811
3812 walk_shadow_page_lockless_end(vcpu);
3813
3814 if (reserved) {
3815 pr_err("%s: detect reserved bits on spte, addr 0x%llx, dump hierarchy:\n",
3816 __func__, addr);
3817 while (root > leaf) {
3818 pr_err("------ spte 0x%llx level %d.\n",
3819 sptes[root - 1], root);
3820 root--;
3821 }
3822 }
3823 exit:
3824 *sptep = spte;
3825 return reserved;
3826 }
3827
3828 static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr, bool direct)
3829 {
3830 u64 spte;
3831 bool reserved;
3832
3833 if (mmio_info_in_cache(vcpu, addr, direct))
3834 return RET_PF_EMULATE;
3835
3836 reserved = walk_shadow_page_get_mmio_spte(vcpu, addr, &spte);
3837 if (WARN_ON(reserved))
3838 return -EINVAL;
3839
3840 if (is_mmio_spte(spte)) {
3841 gfn_t gfn = get_mmio_spte_gfn(spte);
3842 unsigned access = get_mmio_spte_access(spte);
3843
3844 if (!check_mmio_spte(vcpu, spte))
3845 return RET_PF_INVALID;
3846
3847 if (direct)
3848 addr = 0;
3849
3850 trace_handle_mmio_page_fault(addr, gfn, access);
3851 vcpu_cache_mmio_info(vcpu, addr, gfn, access);
3852 return RET_PF_EMULATE;
3853 }
3854
3855 /*
3856 * If the page table is zapped by other cpus, let CPU fault again on
3857 * the address.
3858 */
3859 return RET_PF_RETRY;
3860 }
3861 EXPORT_SYMBOL_GPL(handle_mmio_page_fault);
3862
3863 static bool page_fault_handle_page_track(struct kvm_vcpu *vcpu,
3864 u32 error_code, gfn_t gfn)
3865 {
3866 if (unlikely(error_code & PFERR_RSVD_MASK))
3867 return false;
3868
3869 if (!(error_code & PFERR_PRESENT_MASK) ||
3870 !(error_code & PFERR_WRITE_MASK))
3871 return false;
3872
3873 /*
3874 * guest is writing the page which is write tracked which can
3875 * not be fixed by page fault handler.
3876 */
3877 if (kvm_page_track_is_active(vcpu, gfn, KVM_PAGE_TRACK_WRITE))
3878 return true;
3879
3880 return false;
3881 }
3882
3883 static void shadow_page_table_clear_flood(struct kvm_vcpu *vcpu, gva_t addr)
3884 {
3885 struct kvm_shadow_walk_iterator iterator;
3886 u64 spte;
3887
3888 if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
3889 return;
3890
3891 walk_shadow_page_lockless_begin(vcpu);
3892 for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
3893 clear_sp_write_flooding_count(iterator.sptep);
3894 if (!is_shadow_present_pte(spte))
3895 break;
3896 }
3897 walk_shadow_page_lockless_end(vcpu);
3898 }
3899
3900 static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
3901 u32 error_code, bool prefault)
3902 {
3903 gfn_t gfn = gva >> PAGE_SHIFT;
3904 int r;
3905
3906 pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
3907
3908 if (page_fault_handle_page_track(vcpu, error_code, gfn))
3909 return RET_PF_EMULATE;
3910
3911 r = mmu_topup_memory_caches(vcpu);
3912 if (r)
3913 return r;
3914
3915 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
3916
3917
3918 return nonpaging_map(vcpu, gva & PAGE_MASK,
3919 error_code, gfn, prefault);
3920 }
3921
3922 static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
3923 {
3924 struct kvm_arch_async_pf arch;
3925
3926 arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
3927 arch.gfn = gfn;
3928 arch.direct_map = vcpu->arch.mmu.direct_map;
3929 arch.cr3 = vcpu->arch.mmu.get_cr3(vcpu);
3930
3931 return kvm_setup_async_pf(vcpu, gva, kvm_vcpu_gfn_to_hva(vcpu, gfn), &arch);
3932 }
3933
3934 bool kvm_can_do_async_pf(struct kvm_vcpu *vcpu)
3935 {
3936 if (unlikely(!lapic_in_kernel(vcpu) ||
3937 kvm_event_needs_reinjection(vcpu) ||
3938 vcpu->arch.exception.pending))
3939 return false;
3940
3941 if (!vcpu->arch.apf.delivery_as_pf_vmexit && is_guest_mode(vcpu))
3942 return false;
3943
3944 return kvm_x86_ops->interrupt_allowed(vcpu);
3945 }
3946
3947 static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
3948 gva_t gva, kvm_pfn_t *pfn, bool write, bool *writable)
3949 {
3950 struct kvm_memory_slot *slot;
3951 bool async;
3952
3953 slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
3954 async = false;
3955 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, &async, write, writable);
3956 if (!async)
3957 return false; /* *pfn has correct page already */
3958
3959 if (!prefault && kvm_can_do_async_pf(vcpu)) {
3960 trace_kvm_try_async_get_page(gva, gfn);
3961 if (kvm_find_async_pf_gfn(vcpu, gfn)) {
3962 trace_kvm_async_pf_doublefault(gva, gfn);
3963 kvm_make_request(KVM_REQ_APF_HALT, vcpu);
3964 return true;
3965 } else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
3966 return true;
3967 }
3968
3969 *pfn = __gfn_to_pfn_memslot(slot, gfn, false, NULL, write, writable);
3970 return false;
3971 }
3972
3973 int kvm_handle_page_fault(struct kvm_vcpu *vcpu, u64 error_code,
3974 u64 fault_address, char *insn, int insn_len)
3975 {
3976 int r = 1;
3977
3978 vcpu->arch.l1tf_flush_l1d = true;
3979 switch (vcpu->arch.apf.host_apf_reason) {
3980 default:
3981 trace_kvm_page_fault(fault_address, error_code);
3982
3983 if (kvm_event_needs_reinjection(vcpu))
3984 kvm_mmu_unprotect_page_virt(vcpu, fault_address);
3985 r = kvm_mmu_page_fault(vcpu, fault_address, error_code, insn,
3986 insn_len);
3987 break;
3988 case KVM_PV_REASON_PAGE_NOT_PRESENT:
3989 vcpu->arch.apf.host_apf_reason = 0;
3990 local_irq_disable();
3991 kvm_async_pf_task_wait(fault_address, 0);
3992 local_irq_enable();
3993 break;
3994 case KVM_PV_REASON_PAGE_READY:
3995 vcpu->arch.apf.host_apf_reason = 0;
3996 local_irq_disable();
3997 kvm_async_pf_task_wake(fault_address);
3998 local_irq_enable();
3999 break;
4000 }
4001 return r;
4002 }
4003 EXPORT_SYMBOL_GPL(kvm_handle_page_fault);
4004
4005 static bool
4006 check_hugepage_cache_consistency(struct kvm_vcpu *vcpu, gfn_t gfn, int level)
4007 {
4008 int page_num = KVM_PAGES_PER_HPAGE(level);
4009
4010 gfn &= ~(page_num - 1);
4011
4012 return kvm_mtrr_check_gfn_range_consistency(vcpu, gfn, page_num);
4013 }
4014
4015 static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
4016 bool prefault)
4017 {
4018 kvm_pfn_t pfn;
4019 int r;
4020 int level;
4021 bool force_pt_level;
4022 gfn_t gfn = gpa >> PAGE_SHIFT;
4023 unsigned long mmu_seq;
4024 int write = error_code & PFERR_WRITE_MASK;
4025 bool map_writable;
4026 bool lpage_disallowed = (error_code & PFERR_FETCH_MASK) &&
4027 is_nx_huge_page_enabled();
4028
4029 MMU_WARN_ON(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
4030
4031 if (page_fault_handle_page_track(vcpu, error_code, gfn))
4032 return RET_PF_EMULATE;
4033
4034 r = mmu_topup_memory_caches(vcpu);
4035 if (r)
4036 return r;
4037
4038 force_pt_level =
4039 lpage_disallowed ||
4040 !check_hugepage_cache_consistency(vcpu, gfn, PT_DIRECTORY_LEVEL);
4041 level = mapping_level(vcpu, gfn, &force_pt_level);
4042 if (likely(!force_pt_level)) {
4043 if (level > PT_DIRECTORY_LEVEL &&
4044 !check_hugepage_cache_consistency(vcpu, gfn, level))
4045 level = PT_DIRECTORY_LEVEL;
4046 gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
4047 }
4048
4049 if (fast_page_fault(vcpu, gpa, level, error_code))
4050 return RET_PF_RETRY;
4051
4052 mmu_seq = vcpu->kvm->mmu_notifier_seq;
4053 smp_rmb();
4054
4055 if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
4056 return RET_PF_RETRY;
4057
4058 if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
4059 return r;
4060
4061 r = RET_PF_RETRY;
4062 spin_lock(&vcpu->kvm->mmu_lock);
4063 if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
4064 goto out_unlock;
4065 if (make_mmu_pages_available(vcpu) < 0)
4066 goto out_unlock;
4067 if (likely(!force_pt_level))
4068 transparent_hugepage_adjust(vcpu, gfn, &pfn, &level);
4069 r = __direct_map(vcpu, gpa, write, map_writable, level, pfn,
4070 prefault, lpage_disallowed);
4071 out_unlock:
4072 spin_unlock(&vcpu->kvm->mmu_lock);
4073 kvm_release_pfn_clean(pfn);
4074 return r;
4075 }
4076
4077 static void nonpaging_init_context(struct kvm_vcpu *vcpu,
4078 struct kvm_mmu *context)
4079 {
4080 context->page_fault = nonpaging_page_fault;
4081 context->gva_to_gpa = nonpaging_gva_to_gpa;
4082 context->sync_page = nonpaging_sync_page;
4083 context->invlpg = nonpaging_invlpg;
4084 context->update_pte = nonpaging_update_pte;
4085 context->root_level = 0;
4086 context->shadow_root_level = PT32E_ROOT_LEVEL;
4087 context->root_hpa = INVALID_PAGE;
4088 context->direct_map = true;
4089 context->nx = false;
4090 }
4091
4092 void kvm_mmu_new_cr3(struct kvm_vcpu *vcpu)
4093 {
4094 mmu_free_roots(vcpu);
4095 }
4096
4097 static unsigned long get_cr3(struct kvm_vcpu *vcpu)
4098 {
4099 return kvm_read_cr3(vcpu);
4100 }
4101
4102 static void inject_page_fault(struct kvm_vcpu *vcpu,
4103 struct x86_exception *fault)
4104 {
4105 vcpu->arch.mmu.inject_page_fault(vcpu, fault);
4106 }
4107
4108 static bool sync_mmio_spte(struct kvm_vcpu *vcpu, u64 *sptep, gfn_t gfn,
4109 unsigned access, int *nr_present)
4110 {
4111 if (unlikely(is_mmio_spte(*sptep))) {
4112 if (gfn != get_mmio_spte_gfn(*sptep)) {
4113 mmu_spte_clear_no_track(sptep);
4114 return true;
4115 }
4116
4117 (*nr_present)++;
4118 mark_mmio_spte(vcpu, sptep, gfn, access);
4119 return true;
4120 }
4121
4122 return false;
4123 }
4124
4125 static inline bool is_last_gpte(struct kvm_mmu *mmu,
4126 unsigned level, unsigned gpte)
4127 {
4128 /*
4129 * The RHS has bit 7 set iff level < mmu->last_nonleaf_level.
4130 * If it is clear, there are no large pages at this level, so clear
4131 * PT_PAGE_SIZE_MASK in gpte if that is the case.
4132 */
4133 gpte &= level - mmu->last_nonleaf_level;
4134
4135 /*
4136 * PT_PAGE_TABLE_LEVEL always terminates. The RHS has bit 7 set
4137 * iff level <= PT_PAGE_TABLE_LEVEL, which for our purpose means
4138 * level == PT_PAGE_TABLE_LEVEL; set PT_PAGE_SIZE_MASK in gpte then.
4139 */
4140 gpte |= level - PT_PAGE_TABLE_LEVEL - 1;
4141
4142 return gpte & PT_PAGE_SIZE_MASK;
4143 }
4144
4145 #define PTTYPE_EPT 18 /* arbitrary */
4146 #define PTTYPE PTTYPE_EPT
4147 #include "paging_tmpl.h"
4148 #undef PTTYPE
4149
4150 #define PTTYPE 64
4151 #include "paging_tmpl.h"
4152 #undef PTTYPE
4153
4154 #define PTTYPE 32
4155 #include "paging_tmpl.h"
4156 #undef PTTYPE
4157
4158 static void
4159 __reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4160 struct rsvd_bits_validate *rsvd_check,
4161 int maxphyaddr, int level, bool nx, bool gbpages,
4162 bool pse, bool amd)
4163 {
4164 u64 exb_bit_rsvd = 0;
4165 u64 gbpages_bit_rsvd = 0;
4166 u64 nonleaf_bit8_rsvd = 0;
4167
4168 rsvd_check->bad_mt_xwr = 0;
4169
4170 if (!nx)
4171 exb_bit_rsvd = rsvd_bits(63, 63);
4172 if (!gbpages)
4173 gbpages_bit_rsvd = rsvd_bits(7, 7);
4174
4175 /*
4176 * Non-leaf PML4Es and PDPEs reserve bit 8 (which would be the G bit for
4177 * leaf entries) on AMD CPUs only.
4178 */
4179 if (amd)
4180 nonleaf_bit8_rsvd = rsvd_bits(8, 8);
4181
4182 switch (level) {
4183 case PT32_ROOT_LEVEL:
4184 /* no rsvd bits for 2 level 4K page table entries */
4185 rsvd_check->rsvd_bits_mask[0][1] = 0;
4186 rsvd_check->rsvd_bits_mask[0][0] = 0;
4187 rsvd_check->rsvd_bits_mask[1][0] =
4188 rsvd_check->rsvd_bits_mask[0][0];
4189
4190 if (!pse) {
4191 rsvd_check->rsvd_bits_mask[1][1] = 0;
4192 break;
4193 }
4194
4195 if (is_cpuid_PSE36())
4196 /* 36bits PSE 4MB page */
4197 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
4198 else
4199 /* 32 bits PSE 4MB page */
4200 rsvd_check->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
4201 break;
4202 case PT32E_ROOT_LEVEL:
4203 rsvd_check->rsvd_bits_mask[0][2] =
4204 rsvd_bits(maxphyaddr, 63) |
4205 rsvd_bits(5, 8) | rsvd_bits(1, 2); /* PDPTE */
4206 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4207 rsvd_bits(maxphyaddr, 62); /* PDE */
4208 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4209 rsvd_bits(maxphyaddr, 62); /* PTE */
4210 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4211 rsvd_bits(maxphyaddr, 62) |
4212 rsvd_bits(13, 20); /* large page */
4213 rsvd_check->rsvd_bits_mask[1][0] =
4214 rsvd_check->rsvd_bits_mask[0][0];
4215 break;
4216 case PT64_ROOT_5LEVEL:
4217 rsvd_check->rsvd_bits_mask[0][4] = exb_bit_rsvd |
4218 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4219 rsvd_bits(maxphyaddr, 51);
4220 rsvd_check->rsvd_bits_mask[1][4] =
4221 rsvd_check->rsvd_bits_mask[0][4];
4222 case PT64_ROOT_4LEVEL:
4223 rsvd_check->rsvd_bits_mask[0][3] = exb_bit_rsvd |
4224 nonleaf_bit8_rsvd | rsvd_bits(7, 7) |
4225 rsvd_bits(maxphyaddr, 51);
4226 rsvd_check->rsvd_bits_mask[0][2] = exb_bit_rsvd |
4227 nonleaf_bit8_rsvd | gbpages_bit_rsvd |
4228 rsvd_bits(maxphyaddr, 51);
4229 rsvd_check->rsvd_bits_mask[0][1] = exb_bit_rsvd |
4230 rsvd_bits(maxphyaddr, 51);
4231 rsvd_check->rsvd_bits_mask[0][0] = exb_bit_rsvd |
4232 rsvd_bits(maxphyaddr, 51);
4233 rsvd_check->rsvd_bits_mask[1][3] =
4234 rsvd_check->rsvd_bits_mask[0][3];
4235 rsvd_check->rsvd_bits_mask[1][2] = exb_bit_rsvd |
4236 gbpages_bit_rsvd | rsvd_bits(maxphyaddr, 51) |
4237 rsvd_bits(13, 29);
4238 rsvd_check->rsvd_bits_mask[1][1] = exb_bit_rsvd |
4239 rsvd_bits(maxphyaddr, 51) |
4240 rsvd_bits(13, 20); /* large page */
4241 rsvd_check->rsvd_bits_mask[1][0] =
4242 rsvd_check->rsvd_bits_mask[0][0];
4243 break;
4244 }
4245 }
4246
4247 static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
4248 struct kvm_mmu *context)
4249 {
4250 __reset_rsvds_bits_mask(vcpu, &context->guest_rsvd_check,
4251 cpuid_maxphyaddr(vcpu), context->root_level,
4252 context->nx,
4253 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4254 is_pse(vcpu), guest_cpuid_is_amd(vcpu));
4255 }
4256
4257 static void
4258 __reset_rsvds_bits_mask_ept(struct rsvd_bits_validate *rsvd_check,
4259 int maxphyaddr, bool execonly)
4260 {
4261 u64 bad_mt_xwr;
4262
4263 rsvd_check->rsvd_bits_mask[0][4] =
4264 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4265 rsvd_check->rsvd_bits_mask[0][3] =
4266 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
4267 rsvd_check->rsvd_bits_mask[0][2] =
4268 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4269 rsvd_check->rsvd_bits_mask[0][1] =
4270 rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
4271 rsvd_check->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
4272
4273 /* large page */
4274 rsvd_check->rsvd_bits_mask[1][4] = rsvd_check->rsvd_bits_mask[0][4];
4275 rsvd_check->rsvd_bits_mask[1][3] = rsvd_check->rsvd_bits_mask[0][3];
4276 rsvd_check->rsvd_bits_mask[1][2] =
4277 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
4278 rsvd_check->rsvd_bits_mask[1][1] =
4279 rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
4280 rsvd_check->rsvd_bits_mask[1][0] = rsvd_check->rsvd_bits_mask[0][0];
4281
4282 bad_mt_xwr = 0xFFull << (2 * 8); /* bits 3..5 must not be 2 */
4283 bad_mt_xwr |= 0xFFull << (3 * 8); /* bits 3..5 must not be 3 */
4284 bad_mt_xwr |= 0xFFull << (7 * 8); /* bits 3..5 must not be 7 */
4285 bad_mt_xwr |= REPEAT_BYTE(1ull << 2); /* bits 0..2 must not be 010 */
4286 bad_mt_xwr |= REPEAT_BYTE(1ull << 6); /* bits 0..2 must not be 110 */
4287 if (!execonly) {
4288 /* bits 0..2 must not be 100 unless VMX capabilities allow it */
4289 bad_mt_xwr |= REPEAT_BYTE(1ull << 4);
4290 }
4291 rsvd_check->bad_mt_xwr = bad_mt_xwr;
4292 }
4293
4294 static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
4295 struct kvm_mmu *context, bool execonly)
4296 {
4297 __reset_rsvds_bits_mask_ept(&context->guest_rsvd_check,
4298 cpuid_maxphyaddr(vcpu), execonly);
4299 }
4300
4301 /*
4302 * the page table on host is the shadow page table for the page
4303 * table in guest or amd nested guest, its mmu features completely
4304 * follow the features in guest.
4305 */
4306 void
4307 reset_shadow_zero_bits_mask(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
4308 {
4309 bool uses_nx = context->nx || context->base_role.smep_andnot_wp;
4310 struct rsvd_bits_validate *shadow_zero_check;
4311 int i;
4312
4313 /*
4314 * Passing "true" to the last argument is okay; it adds a check
4315 * on bit 8 of the SPTEs which KVM doesn't use anyway.
4316 */
4317 shadow_zero_check = &context->shadow_zero_check;
4318 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4319 boot_cpu_data.x86_phys_bits,
4320 context->shadow_root_level, uses_nx,
4321 guest_cpuid_has(vcpu, X86_FEATURE_GBPAGES),
4322 is_pse(vcpu), true);
4323
4324 if (!shadow_me_mask)
4325 return;
4326
4327 for (i = context->shadow_root_level; --i >= 0;) {
4328 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4329 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4330 }
4331
4332 }
4333 EXPORT_SYMBOL_GPL(reset_shadow_zero_bits_mask);
4334
4335 static inline bool boot_cpu_is_amd(void)
4336 {
4337 WARN_ON_ONCE(!tdp_enabled);
4338 return shadow_x_mask == 0;
4339 }
4340
4341 /*
4342 * the direct page table on host, use as much mmu features as
4343 * possible, however, kvm currently does not do execution-protection.
4344 */
4345 static void
4346 reset_tdp_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4347 struct kvm_mmu *context)
4348 {
4349 struct rsvd_bits_validate *shadow_zero_check;
4350 int i;
4351
4352 shadow_zero_check = &context->shadow_zero_check;
4353
4354 if (boot_cpu_is_amd())
4355 __reset_rsvds_bits_mask(vcpu, shadow_zero_check,
4356 boot_cpu_data.x86_phys_bits,
4357 context->shadow_root_level, false,
4358 boot_cpu_has(X86_FEATURE_GBPAGES),
4359 true, true);
4360 else
4361 __reset_rsvds_bits_mask_ept(shadow_zero_check,
4362 boot_cpu_data.x86_phys_bits,
4363 false);
4364
4365 if (!shadow_me_mask)
4366 return;
4367
4368 for (i = context->shadow_root_level; --i >= 0;) {
4369 shadow_zero_check->rsvd_bits_mask[0][i] &= ~shadow_me_mask;
4370 shadow_zero_check->rsvd_bits_mask[1][i] &= ~shadow_me_mask;
4371 }
4372 }
4373
4374 /*
4375 * as the comments in reset_shadow_zero_bits_mask() except it
4376 * is the shadow page table for intel nested guest.
4377 */
4378 static void
4379 reset_ept_shadow_zero_bits_mask(struct kvm_vcpu *vcpu,
4380 struct kvm_mmu *context, bool execonly)
4381 {
4382 __reset_rsvds_bits_mask_ept(&context->shadow_zero_check,
4383 boot_cpu_data.x86_phys_bits, execonly);
4384 }
4385
4386 #define BYTE_MASK(access) \
4387 ((1 & (access) ? 2 : 0) | \
4388 (2 & (access) ? 4 : 0) | \
4389 (3 & (access) ? 8 : 0) | \
4390 (4 & (access) ? 16 : 0) | \
4391 (5 & (access) ? 32 : 0) | \
4392 (6 & (access) ? 64 : 0) | \
4393 (7 & (access) ? 128 : 0))
4394
4395
4396 static void update_permission_bitmask(struct kvm_vcpu *vcpu,
4397 struct kvm_mmu *mmu, bool ept)
4398 {
4399 unsigned byte;
4400
4401 const u8 x = BYTE_MASK(ACC_EXEC_MASK);
4402 const u8 w = BYTE_MASK(ACC_WRITE_MASK);
4403 const u8 u = BYTE_MASK(ACC_USER_MASK);
4404
4405 bool cr4_smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP) != 0;
4406 bool cr4_smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP) != 0;
4407 bool cr0_wp = is_write_protection(vcpu);
4408
4409 for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
4410 unsigned pfec = byte << 1;
4411
4412 /*
4413 * Each "*f" variable has a 1 bit for each UWX value
4414 * that causes a fault with the given PFEC.
4415 */
4416
4417 /* Faults from writes to non-writable pages */
4418 u8 wf = (pfec & PFERR_WRITE_MASK) ? (u8)~w : 0;
4419 /* Faults from user mode accesses to supervisor pages */
4420 u8 uf = (pfec & PFERR_USER_MASK) ? (u8)~u : 0;
4421 /* Faults from fetches of non-executable pages*/
4422 u8 ff = (pfec & PFERR_FETCH_MASK) ? (u8)~x : 0;
4423 /* Faults from kernel mode fetches of user pages */
4424 u8 smepf = 0;
4425 /* Faults from kernel mode accesses of user pages */
4426 u8 smapf = 0;
4427
4428 if (!ept) {
4429 /* Faults from kernel mode accesses to user pages */
4430 u8 kf = (pfec & PFERR_USER_MASK) ? 0 : u;
4431
4432 /* Not really needed: !nx will cause pte.nx to fault */
4433 if (!mmu->nx)
4434 ff = 0;
4435
4436 /* Allow supervisor writes if !cr0.wp */
4437 if (!cr0_wp)
4438 wf = (pfec & PFERR_USER_MASK) ? wf : 0;
4439
4440 /* Disallow supervisor fetches of user code if cr4.smep */
4441 if (cr4_smep)
4442 smepf = (pfec & PFERR_FETCH_MASK) ? kf : 0;
4443
4444 /*
4445 * SMAP:kernel-mode data accesses from user-mode
4446 * mappings should fault. A fault is considered
4447 * as a SMAP violation if all of the following
4448 * conditions are ture:
4449 * - X86_CR4_SMAP is set in CR4
4450 * - A user page is accessed
4451 * - The access is not a fetch
4452 * - Page fault in kernel mode
4453 * - if CPL = 3 or X86_EFLAGS_AC is clear
4454 *
4455 * Here, we cover the first three conditions.
4456 * The fourth is computed dynamically in permission_fault();
4457 * PFERR_RSVD_MASK bit will be set in PFEC if the access is
4458 * *not* subject to SMAP restrictions.
4459 */
4460 if (cr4_smap)
4461 smapf = (pfec & (PFERR_RSVD_MASK|PFERR_FETCH_MASK)) ? 0 : kf;
4462 }
4463
4464 mmu->permissions[byte] = ff | uf | wf | smepf | smapf;
4465 }
4466 }
4467
4468 /*
4469 * PKU is an additional mechanism by which the paging controls access to
4470 * user-mode addresses based on the value in the PKRU register. Protection
4471 * key violations are reported through a bit in the page fault error code.
4472 * Unlike other bits of the error code, the PK bit is not known at the
4473 * call site of e.g. gva_to_gpa; it must be computed directly in
4474 * permission_fault based on two bits of PKRU, on some machine state (CR4,
4475 * CR0, EFER, CPL), and on other bits of the error code and the page tables.
4476 *
4477 * In particular the following conditions come from the error code, the
4478 * page tables and the machine state:
4479 * - PK is always zero unless CR4.PKE=1 and EFER.LMA=1
4480 * - PK is always zero if RSVD=1 (reserved bit set) or F=1 (instruction fetch)
4481 * - PK is always zero if U=0 in the page tables
4482 * - PKRU.WD is ignored if CR0.WP=0 and the access is a supervisor access.
4483 *
4484 * The PKRU bitmask caches the result of these four conditions. The error
4485 * code (minus the P bit) and the page table's U bit form an index into the
4486 * PKRU bitmask. Two bits of the PKRU bitmask are then extracted and ANDed
4487 * with the two bits of the PKRU register corresponding to the protection key.
4488 * For the first three conditions above the bits will be 00, thus masking
4489 * away both AD and WD. For all reads or if the last condition holds, WD
4490 * only will be masked away.
4491 */
4492 static void update_pkru_bitmask(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
4493 bool ept)
4494 {
4495 unsigned bit;
4496 bool wp;
4497
4498 if (ept) {
4499 mmu->pkru_mask = 0;
4500 return;
4501 }
4502
4503 /* PKEY is enabled only if CR4.PKE and EFER.LMA are both set. */
4504 if (!kvm_read_cr4_bits(vcpu, X86_CR4_PKE) || !is_long_mode(vcpu)) {
4505 mmu->pkru_mask = 0;
4506 return;
4507 }
4508
4509 wp = is_write_protection(vcpu);
4510
4511 for (bit = 0; bit < ARRAY_SIZE(mmu->permissions); ++bit) {
4512 unsigned pfec, pkey_bits;
4513 bool check_pkey, check_write, ff, uf, wf, pte_user;
4514
4515 pfec = bit << 1;
4516 ff = pfec & PFERR_FETCH_MASK;
4517 uf = pfec & PFERR_USER_MASK;
4518 wf = pfec & PFERR_WRITE_MASK;
4519
4520 /* PFEC.RSVD is replaced by ACC_USER_MASK. */
4521 pte_user = pfec & PFERR_RSVD_MASK;
4522
4523 /*
4524 * Only need to check the access which is not an
4525 * instruction fetch and is to a user page.
4526 */
4527 check_pkey = (!ff && pte_user);
4528 /*
4529 * write access is controlled by PKRU if it is a
4530 * user access or CR0.WP = 1.
4531 */
4532 check_write = check_pkey && wf && (uf || wp);
4533
4534 /* PKRU.AD stops both read and write access. */
4535 pkey_bits = !!check_pkey;
4536 /* PKRU.WD stops write access. */
4537 pkey_bits |= (!!check_write) << 1;
4538
4539 mmu->pkru_mask |= (pkey_bits & 3) << pfec;
4540 }
4541 }
4542
4543 static void update_last_nonleaf_level(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
4544 {
4545 unsigned root_level = mmu->root_level;
4546
4547 mmu->last_nonleaf_level = root_level;
4548 if (root_level == PT32_ROOT_LEVEL && is_pse(vcpu))
4549 mmu->last_nonleaf_level++;
4550 }
4551
4552 static void paging64_init_context_common(struct kvm_vcpu *vcpu,
4553 struct kvm_mmu *context,
4554 int level)
4555 {
4556 context->nx = is_nx(vcpu);
4557 context->root_level = level;
4558
4559 reset_rsvds_bits_mask(vcpu, context);
4560 update_permission_bitmask(vcpu, context, false);
4561 update_pkru_bitmask(vcpu, context, false);
4562 update_last_nonleaf_level(vcpu, context);
4563
4564 MMU_WARN_ON(!is_pae(vcpu));
4565 context->page_fault = paging64_page_fault;
4566 context->gva_to_gpa = paging64_gva_to_gpa;
4567 context->sync_page = paging64_sync_page;
4568 context->invlpg = paging64_invlpg;
4569 context->update_pte = paging64_update_pte;
4570 context->shadow_root_level = level;
4571 context->root_hpa = INVALID_PAGE;
4572 context->direct_map = false;
4573 }
4574
4575 static void paging64_init_context(struct kvm_vcpu *vcpu,
4576 struct kvm_mmu *context)
4577 {
4578 int root_level = is_la57_mode(vcpu) ?
4579 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4580
4581 paging64_init_context_common(vcpu, context, root_level);
4582 }
4583
4584 static void paging32_init_context(struct kvm_vcpu *vcpu,
4585 struct kvm_mmu *context)
4586 {
4587 context->nx = false;
4588 context->root_level = PT32_ROOT_LEVEL;
4589
4590 reset_rsvds_bits_mask(vcpu, context);
4591 update_permission_bitmask(vcpu, context, false);
4592 update_pkru_bitmask(vcpu, context, false);
4593 update_last_nonleaf_level(vcpu, context);
4594
4595 context->page_fault = paging32_page_fault;
4596 context->gva_to_gpa = paging32_gva_to_gpa;
4597 context->sync_page = paging32_sync_page;
4598 context->invlpg = paging32_invlpg;
4599 context->update_pte = paging32_update_pte;
4600 context->shadow_root_level = PT32E_ROOT_LEVEL;
4601 context->root_hpa = INVALID_PAGE;
4602 context->direct_map = false;
4603 }
4604
4605 static void paging32E_init_context(struct kvm_vcpu *vcpu,
4606 struct kvm_mmu *context)
4607 {
4608 paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
4609 }
4610
4611 static void init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
4612 {
4613 struct kvm_mmu *context = &vcpu->arch.mmu;
4614
4615 context->base_role.word = 0;
4616 context->base_role.smm = is_smm(vcpu);
4617 context->base_role.ad_disabled = (shadow_accessed_mask == 0);
4618 context->page_fault = tdp_page_fault;
4619 context->sync_page = nonpaging_sync_page;
4620 context->invlpg = nonpaging_invlpg;
4621 context->update_pte = nonpaging_update_pte;
4622 context->shadow_root_level = kvm_x86_ops->get_tdp_level(vcpu);
4623 context->root_hpa = INVALID_PAGE;
4624 context->direct_map = true;
4625 context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
4626 context->get_cr3 = get_cr3;
4627 context->get_pdptr = kvm_pdptr_read;
4628 context->inject_page_fault = kvm_inject_page_fault;
4629
4630 if (!is_paging(vcpu)) {
4631 context->nx = false;
4632 context->gva_to_gpa = nonpaging_gva_to_gpa;
4633 context->root_level = 0;
4634 } else if (is_long_mode(vcpu)) {
4635 context->nx = is_nx(vcpu);
4636 context->root_level = is_la57_mode(vcpu) ?
4637 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4638 reset_rsvds_bits_mask(vcpu, context);
4639 context->gva_to_gpa = paging64_gva_to_gpa;
4640 } else if (is_pae(vcpu)) {
4641 context->nx = is_nx(vcpu);
4642 context->root_level = PT32E_ROOT_LEVEL;
4643 reset_rsvds_bits_mask(vcpu, context);
4644 context->gva_to_gpa = paging64_gva_to_gpa;
4645 } else {
4646 context->nx = false;
4647 context->root_level = PT32_ROOT_LEVEL;
4648 reset_rsvds_bits_mask(vcpu, context);
4649 context->gva_to_gpa = paging32_gva_to_gpa;
4650 }
4651
4652 update_permission_bitmask(vcpu, context, false);
4653 update_pkru_bitmask(vcpu, context, false);
4654 update_last_nonleaf_level(vcpu, context);
4655 reset_tdp_shadow_zero_bits_mask(vcpu, context);
4656 }
4657
4658 void kvm_init_shadow_mmu(struct kvm_vcpu *vcpu)
4659 {
4660 bool smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
4661 bool smap = kvm_read_cr4_bits(vcpu, X86_CR4_SMAP);
4662 struct kvm_mmu *context = &vcpu->arch.mmu;
4663
4664 MMU_WARN_ON(VALID_PAGE(context->root_hpa));
4665
4666 if (!is_paging(vcpu))
4667 nonpaging_init_context(vcpu, context);
4668 else if (is_long_mode(vcpu))
4669 paging64_init_context(vcpu, context);
4670 else if (is_pae(vcpu))
4671 paging32E_init_context(vcpu, context);
4672 else
4673 paging32_init_context(vcpu, context);
4674
4675 context->base_role.nxe = is_nx(vcpu);
4676 context->base_role.cr4_pae = !!is_pae(vcpu);
4677 context->base_role.cr0_wp = is_write_protection(vcpu);
4678 context->base_role.smep_andnot_wp
4679 = smep && !is_write_protection(vcpu);
4680 context->base_role.smap_andnot_wp
4681 = smap && !is_write_protection(vcpu);
4682 context->base_role.smm = is_smm(vcpu);
4683 reset_shadow_zero_bits_mask(vcpu, context);
4684 }
4685 EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
4686
4687 void kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, bool execonly,
4688 bool accessed_dirty)
4689 {
4690 struct kvm_mmu *context = &vcpu->arch.mmu;
4691
4692 MMU_WARN_ON(VALID_PAGE(context->root_hpa));
4693
4694 context->shadow_root_level = PT64_ROOT_4LEVEL;
4695
4696 context->nx = true;
4697 context->ept_ad = accessed_dirty;
4698 context->page_fault = ept_page_fault;
4699 context->gva_to_gpa = ept_gva_to_gpa;
4700 context->sync_page = ept_sync_page;
4701 context->invlpg = ept_invlpg;
4702 context->update_pte = ept_update_pte;
4703 context->root_level = PT64_ROOT_4LEVEL;
4704 context->root_hpa = INVALID_PAGE;
4705 context->direct_map = false;
4706 context->base_role.ad_disabled = !accessed_dirty;
4707
4708 update_permission_bitmask(vcpu, context, true);
4709 update_pkru_bitmask(vcpu, context, true);
4710 update_last_nonleaf_level(vcpu, context);
4711 reset_rsvds_bits_mask_ept(vcpu, context, execonly);
4712 reset_ept_shadow_zero_bits_mask(vcpu, context, execonly);
4713 }
4714 EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
4715
4716 static void init_kvm_softmmu(struct kvm_vcpu *vcpu)
4717 {
4718 struct kvm_mmu *context = &vcpu->arch.mmu;
4719
4720 kvm_init_shadow_mmu(vcpu);
4721 context->set_cr3 = kvm_x86_ops->set_cr3;
4722 context->get_cr3 = get_cr3;
4723 context->get_pdptr = kvm_pdptr_read;
4724 context->inject_page_fault = kvm_inject_page_fault;
4725 }
4726
4727 static void init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
4728 {
4729 struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
4730
4731 g_context->get_cr3 = get_cr3;
4732 g_context->get_pdptr = kvm_pdptr_read;
4733 g_context->inject_page_fault = kvm_inject_page_fault;
4734
4735 /*
4736 * Note that arch.mmu.gva_to_gpa translates l2_gpa to l1_gpa using
4737 * L1's nested page tables (e.g. EPT12). The nested translation
4738 * of l2_gva to l1_gpa is done by arch.nested_mmu.gva_to_gpa using
4739 * L2's page tables as the first level of translation and L1's
4740 * nested page tables as the second level of translation. Basically
4741 * the gva_to_gpa functions between mmu and nested_mmu are swapped.
4742 */
4743 if (!is_paging(vcpu)) {
4744 g_context->nx = false;
4745 g_context->root_level = 0;
4746 g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
4747 } else if (is_long_mode(vcpu)) {
4748 g_context->nx = is_nx(vcpu);
4749 g_context->root_level = is_la57_mode(vcpu) ?
4750 PT64_ROOT_5LEVEL : PT64_ROOT_4LEVEL;
4751 reset_rsvds_bits_mask(vcpu, g_context);
4752 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
4753 } else if (is_pae(vcpu)) {
4754 g_context->nx = is_nx(vcpu);
4755 g_context->root_level = PT32E_ROOT_LEVEL;
4756 reset_rsvds_bits_mask(vcpu, g_context);
4757 g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
4758 } else {
4759 g_context->nx = false;
4760 g_context->root_level = PT32_ROOT_LEVEL;
4761 reset_rsvds_bits_mask(vcpu, g_context);
4762 g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
4763 }
4764
4765 update_permission_bitmask(vcpu, g_context, false);
4766 update_pkru_bitmask(vcpu, g_context, false);
4767 update_last_nonleaf_level(vcpu, g_context);
4768 }
4769
4770 static void init_kvm_mmu(struct kvm_vcpu *vcpu)
4771 {
4772 if (mmu_is_nested(vcpu))
4773 init_kvm_nested_mmu(vcpu);
4774 else if (tdp_enabled)
4775 init_kvm_tdp_mmu(vcpu);
4776 else
4777 init_kvm_softmmu(vcpu);
4778 }
4779
4780 void kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
4781 {
4782 kvm_mmu_unload(vcpu);
4783 init_kvm_mmu(vcpu);
4784 }
4785 EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
4786
4787 int kvm_mmu_load(struct kvm_vcpu *vcpu)
4788 {
4789 int r;
4790
4791 r = mmu_topup_memory_caches(vcpu);
4792 if (r)
4793 goto out;
4794 r = mmu_alloc_roots(vcpu);
4795 kvm_mmu_sync_roots(vcpu);
4796 if (r)
4797 goto out;
4798 /* set_cr3() should ensure TLB has been flushed */
4799 vcpu->arch.mmu.set_cr3(vcpu, vcpu->arch.mmu.root_hpa);
4800 out:
4801 return r;
4802 }
4803 EXPORT_SYMBOL_GPL(kvm_mmu_load);
4804
4805 void kvm_mmu_unload(struct kvm_vcpu *vcpu)
4806 {
4807 mmu_free_roots(vcpu);
4808 WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
4809 }
4810 EXPORT_SYMBOL_GPL(kvm_mmu_unload);
4811
4812 static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
4813 struct kvm_mmu_page *sp, u64 *spte,
4814 const void *new)
4815 {
4816 if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
4817 ++vcpu->kvm->stat.mmu_pde_zapped;
4818 return;
4819 }
4820
4821 ++vcpu->kvm->stat.mmu_pte_updated;
4822 vcpu->arch.mmu.update_pte(vcpu, sp, spte, new);
4823 }
4824
4825 static bool need_remote_flush(u64 old, u64 new)
4826 {
4827 if (!is_shadow_present_pte(old))
4828 return false;
4829 if (!is_shadow_present_pte(new))
4830 return true;
4831 if ((old ^ new) & PT64_BASE_ADDR_MASK)
4832 return true;
4833 old ^= shadow_nx_mask;
4834 new ^= shadow_nx_mask;
4835 return (old & ~new & PT64_PERM_MASK) != 0;
4836 }
4837
4838 static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
4839 int *bytes)
4840 {
4841 u64 gentry = 0;
4842 int r;
4843
4844 /*
4845 * Assume that the pte write on a page table of the same type
4846 * as the current vcpu paging mode since we update the sptes only
4847 * when they have the same mode.
4848 */
4849 if (is_pae(vcpu) && *bytes == 4) {
4850 /* Handle a 32-bit guest writing two halves of a 64-bit gpte */
4851 *gpa &= ~(gpa_t)7;
4852 *bytes = 8;
4853 }
4854
4855 if (*bytes == 4 || *bytes == 8) {
4856 r = kvm_vcpu_read_guest_atomic(vcpu, *gpa, &gentry, *bytes);
4857 if (r)
4858 gentry = 0;
4859 }
4860
4861 return gentry;
4862 }
4863
4864 /*
4865 * If we're seeing too many writes to a page, it may no longer be a page table,
4866 * or we may be forking, in which case it is better to unmap the page.
4867 */
4868 static bool detect_write_flooding(struct kvm_mmu_page *sp)
4869 {
4870 /*
4871 * Skip write-flooding detected for the sp whose level is 1, because
4872 * it can become unsync, then the guest page is not write-protected.
4873 */
4874 if (sp->role.level == PT_PAGE_TABLE_LEVEL)
4875 return false;
4876
4877 atomic_inc(&sp->write_flooding_count);
4878 return atomic_read(&sp->write_flooding_count) >= 3;
4879 }
4880
4881 /*
4882 * Misaligned accesses are too much trouble to fix up; also, they usually
4883 * indicate a page is not used as a page table.
4884 */
4885 static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
4886 int bytes)
4887 {
4888 unsigned offset, pte_size, misaligned;
4889
4890 pgprintk("misaligned: gpa %llx bytes %d role %x\n",
4891 gpa, bytes, sp->role.word);
4892
4893 offset = offset_in_page(gpa);
4894 pte_size = sp->role.cr4_pae ? 8 : 4;
4895
4896 /*
4897 * Sometimes, the OS only writes the last one bytes to update status
4898 * bits, for example, in linux, andb instruction is used in clear_bit().
4899 */
4900 if (!(offset & (pte_size - 1)) && bytes == 1)
4901 return false;
4902
4903 misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
4904 misaligned |= bytes < 4;
4905
4906 return misaligned;
4907 }
4908
4909 static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
4910 {
4911 unsigned page_offset, quadrant;
4912 u64 *spte;
4913 int level;
4914
4915 page_offset = offset_in_page(gpa);
4916 level = sp->role.level;
4917 *nspte = 1;
4918 if (!sp->role.cr4_pae) {
4919 page_offset <<= 1; /* 32->64 */
4920 /*
4921 * A 32-bit pde maps 4MB while the shadow pdes map
4922 * only 2MB. So we need to double the offset again
4923 * and zap two pdes instead of one.
4924 */
4925 if (level == PT32_ROOT_LEVEL) {
4926 page_offset &= ~7; /* kill rounding error */
4927 page_offset <<= 1;
4928 *nspte = 2;
4929 }
4930 quadrant = page_offset >> PAGE_SHIFT;
4931 page_offset &= ~PAGE_MASK;
4932 if (quadrant != sp->role.quadrant)
4933 return NULL;
4934 }
4935
4936 spte = &sp->spt[page_offset / sizeof(*spte)];
4937 return spte;
4938 }
4939
4940 static void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
4941 const u8 *new, int bytes,
4942 struct kvm_page_track_notifier_node *node)
4943 {
4944 gfn_t gfn = gpa >> PAGE_SHIFT;
4945 struct kvm_mmu_page *sp;
4946 LIST_HEAD(invalid_list);
4947 u64 entry, gentry, *spte;
4948 int npte;
4949 bool remote_flush, local_flush;
4950 union kvm_mmu_page_role mask = { };
4951
4952 mask.cr0_wp = 1;
4953 mask.cr4_pae = 1;
4954 mask.nxe = 1;
4955 mask.smep_andnot_wp = 1;
4956 mask.smap_andnot_wp = 1;
4957 mask.smm = 1;
4958 mask.ad_disabled = 1;
4959
4960 /*
4961 * If we don't have indirect shadow pages, it means no page is
4962 * write-protected, so we can exit simply.
4963 */
4964 if (!READ_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
4965 return;
4966
4967 remote_flush = local_flush = false;
4968
4969 pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
4970
4971 /*
4972 * No need to care whether allocation memory is successful
4973 * or not since pte prefetch is skiped if it does not have
4974 * enough objects in the cache.
4975 */
4976 mmu_topup_memory_caches(vcpu);
4977
4978 spin_lock(&vcpu->kvm->mmu_lock);
4979
4980 gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, &bytes);
4981
4982 ++vcpu->kvm->stat.mmu_pte_write;
4983 kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
4984
4985 for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
4986 if (detect_write_misaligned(sp, gpa, bytes) ||
4987 detect_write_flooding(sp)) {
4988 kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
4989 ++vcpu->kvm->stat.mmu_flooded;
4990 continue;
4991 }
4992
4993 spte = get_written_sptes(sp, gpa, &npte);
4994 if (!spte)
4995 continue;
4996
4997 local_flush = true;
4998 while (npte--) {
4999 entry = *spte;
5000 mmu_page_zap_pte(vcpu->kvm, sp, spte);
5001 if (gentry &&
5002 !((sp->role.word ^ vcpu->arch.mmu.base_role.word)
5003 & mask.word) && rmap_can_add(vcpu))
5004 mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
5005 if (need_remote_flush(entry, *spte))
5006 remote_flush = true;
5007 ++spte;
5008 }
5009 }
5010 kvm_mmu_flush_or_zap(vcpu, &invalid_list, remote_flush, local_flush);
5011 kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
5012 spin_unlock(&vcpu->kvm->mmu_lock);
5013 }
5014
5015 int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
5016 {
5017 gpa_t gpa;
5018 int r;
5019
5020 if (vcpu->arch.mmu.direct_map)
5021 return 0;
5022
5023 gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
5024
5025 r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
5026
5027 return r;
5028 }
5029 EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
5030
5031 static int make_mmu_pages_available(struct kvm_vcpu *vcpu)
5032 {
5033 LIST_HEAD(invalid_list);
5034
5035 if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
5036 return 0;
5037
5038 while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
5039 if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
5040 break;
5041
5042 ++vcpu->kvm->stat.mmu_recycled;
5043 }
5044 kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
5045
5046 if (!kvm_mmu_available_pages(vcpu->kvm))
5047 return -ENOSPC;
5048 return 0;
5049 }
5050
5051 int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u64 error_code,
5052 void *insn, int insn_len)
5053 {
5054 int r, emulation_type = EMULTYPE_RETRY;
5055 enum emulation_result er;
5056 bool direct = vcpu->arch.mmu.direct_map;
5057
5058 /* With shadow page tables, fault_address contains a GVA or nGPA. */
5059 if (vcpu->arch.mmu.direct_map) {
5060 vcpu->arch.gpa_available = true;
5061 vcpu->arch.gpa_val = cr2;
5062 }
5063
5064 r = RET_PF_INVALID;
5065 if (unlikely(error_code & PFERR_RSVD_MASK)) {
5066 r = handle_mmio_page_fault(vcpu, cr2, direct);
5067 if (r == RET_PF_EMULATE) {
5068 emulation_type = 0;
5069 goto emulate;
5070 }
5071 }
5072
5073 if (r == RET_PF_INVALID) {
5074 r = vcpu->arch.mmu.page_fault(vcpu, cr2, lower_32_bits(error_code),
5075 false);
5076 WARN_ON(r == RET_PF_INVALID);
5077 }
5078
5079 if (r == RET_PF_RETRY)
5080 return 1;
5081 if (r < 0)
5082 return r;
5083
5084 /*
5085 * Before emulating the instruction, check if the error code
5086 * was due to a RO violation while translating the guest page.
5087 * This can occur when using nested virtualization with nested
5088 * paging in both guests. If true, we simply unprotect the page
5089 * and resume the guest.
5090 */
5091 if (vcpu->arch.mmu.direct_map &&
5092 (error_code & PFERR_NESTED_GUEST_PAGE) == PFERR_NESTED_GUEST_PAGE) {
5093 kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(cr2));
5094 return 1;
5095 }
5096
5097 if (mmio_info_in_cache(vcpu, cr2, direct))
5098 emulation_type = 0;
5099 emulate:
5100 /*
5101 * On AMD platforms, under certain conditions insn_len may be zero on #NPF.
5102 * This can happen if a guest gets a page-fault on data access but the HW
5103 * table walker is not able to read the instruction page (e.g instruction
5104 * page is not present in memory). In those cases we simply restart the
5105 * guest.
5106 */
5107 if (unlikely(insn && !insn_len))
5108 return 1;
5109
5110 er = x86_emulate_instruction(vcpu, cr2, emulation_type, insn, insn_len);
5111
5112 switch (er) {
5113 case EMULATE_DONE:
5114 return 1;
5115 case EMULATE_USER_EXIT:
5116 ++vcpu->stat.mmio_exits;
5117 /* fall through */
5118 case EMULATE_FAIL:
5119 return 0;
5120 default:
5121 BUG();
5122 }
5123 }
5124 EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
5125
5126 void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
5127 {
5128 vcpu->arch.mmu.invlpg(vcpu, gva);
5129 kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
5130 ++vcpu->stat.invlpg;
5131 }
5132 EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
5133
5134 void kvm_enable_tdp(void)
5135 {
5136 tdp_enabled = true;
5137 }
5138 EXPORT_SYMBOL_GPL(kvm_enable_tdp);
5139
5140 void kvm_disable_tdp(void)
5141 {
5142 tdp_enabled = false;
5143 }
5144 EXPORT_SYMBOL_GPL(kvm_disable_tdp);
5145
5146 static void free_mmu_pages(struct kvm_vcpu *vcpu)
5147 {
5148 free_page((unsigned long)vcpu->arch.mmu.pae_root);
5149 free_page((unsigned long)vcpu->arch.mmu.lm_root);
5150 }
5151
5152 static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
5153 {
5154 struct page *page;
5155 int i;
5156
5157 /*
5158 * When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
5159 * Therefore we need to allocate shadow page tables in the first
5160 * 4GB of memory, which happens to fit the DMA32 zone.
5161 */
5162 page = alloc_page(GFP_KERNEL | __GFP_DMA32);
5163 if (!page)
5164 return -ENOMEM;
5165
5166 vcpu->arch.mmu.pae_root = page_address(page);
5167 for (i = 0; i < 4; ++i)
5168 vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
5169
5170 return 0;
5171 }
5172
5173 int kvm_mmu_create(struct kvm_vcpu *vcpu)
5174 {
5175 vcpu->arch.walk_mmu = &vcpu->arch.mmu;
5176 vcpu->arch.mmu.root_hpa = INVALID_PAGE;
5177 vcpu->arch.mmu.translate_gpa = translate_gpa;
5178 vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
5179
5180 return alloc_mmu_pages(vcpu);
5181 }
5182
5183 void kvm_mmu_setup(struct kvm_vcpu *vcpu)
5184 {
5185 MMU_WARN_ON(VALID_PAGE(vcpu->arch.mmu.root_hpa));
5186
5187 init_kvm_mmu(vcpu);
5188 }
5189
5190 static void kvm_mmu_invalidate_zap_pages_in_memslot(struct kvm *kvm,
5191 struct kvm_memory_slot *slot,
5192 struct kvm_page_track_notifier_node *node)
5193 {
5194 kvm_mmu_invalidate_zap_all_pages(kvm);
5195 }
5196
5197 void kvm_mmu_init_vm(struct kvm *kvm)
5198 {
5199 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5200
5201 node->track_write = kvm_mmu_pte_write;
5202 node->track_flush_slot = kvm_mmu_invalidate_zap_pages_in_memslot;
5203 kvm_page_track_register_notifier(kvm, node);
5204 }
5205
5206 void kvm_mmu_uninit_vm(struct kvm *kvm)
5207 {
5208 struct kvm_page_track_notifier_node *node = &kvm->arch.mmu_sp_tracker;
5209
5210 kvm_page_track_unregister_notifier(kvm, node);
5211 }
5212
5213 /* The return value indicates if tlb flush on all vcpus is needed. */
5214 typedef bool (*slot_level_handler) (struct kvm *kvm, struct kvm_rmap_head *rmap_head);
5215
5216 /* The caller should hold mmu-lock before calling this function. */
5217 static __always_inline bool
5218 slot_handle_level_range(struct kvm *kvm, struct kvm_memory_slot *memslot,
5219 slot_level_handler fn, int start_level, int end_level,
5220 gfn_t start_gfn, gfn_t end_gfn, bool lock_flush_tlb)
5221 {
5222 struct slot_rmap_walk_iterator iterator;
5223 bool flush = false;
5224
5225 for_each_slot_rmap_range(memslot, start_level, end_level, start_gfn,
5226 end_gfn, &iterator) {
5227 if (iterator.rmap)
5228 flush |= fn(kvm, iterator.rmap);
5229
5230 if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5231 if (flush && lock_flush_tlb) {
5232 kvm_flush_remote_tlbs(kvm);
5233 flush = false;
5234 }
5235 cond_resched_lock(&kvm->mmu_lock);
5236 }
5237 }
5238
5239 if (flush && lock_flush_tlb) {
5240 kvm_flush_remote_tlbs(kvm);
5241 flush = false;
5242 }
5243
5244 return flush;
5245 }
5246
5247 static __always_inline bool
5248 slot_handle_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5249 slot_level_handler fn, int start_level, int end_level,
5250 bool lock_flush_tlb)
5251 {
5252 return slot_handle_level_range(kvm, memslot, fn, start_level,
5253 end_level, memslot->base_gfn,
5254 memslot->base_gfn + memslot->npages - 1,
5255 lock_flush_tlb);
5256 }
5257
5258 static __always_inline bool
5259 slot_handle_all_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5260 slot_level_handler fn, bool lock_flush_tlb)
5261 {
5262 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5263 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5264 }
5265
5266 static __always_inline bool
5267 slot_handle_large_level(struct kvm *kvm, struct kvm_memory_slot *memslot,
5268 slot_level_handler fn, bool lock_flush_tlb)
5269 {
5270 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL + 1,
5271 PT_MAX_HUGEPAGE_LEVEL, lock_flush_tlb);
5272 }
5273
5274 static __always_inline bool
5275 slot_handle_leaf(struct kvm *kvm, struct kvm_memory_slot *memslot,
5276 slot_level_handler fn, bool lock_flush_tlb)
5277 {
5278 return slot_handle_level(kvm, memslot, fn, PT_PAGE_TABLE_LEVEL,
5279 PT_PAGE_TABLE_LEVEL, lock_flush_tlb);
5280 }
5281
5282 void kvm_zap_gfn_range(struct kvm *kvm, gfn_t gfn_start, gfn_t gfn_end)
5283 {
5284 struct kvm_memslots *slots;
5285 struct kvm_memory_slot *memslot;
5286 int i;
5287
5288 spin_lock(&kvm->mmu_lock);
5289 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5290 slots = __kvm_memslots(kvm, i);
5291 kvm_for_each_memslot(memslot, slots) {
5292 gfn_t start, end;
5293
5294 start = max(gfn_start, memslot->base_gfn);
5295 end = min(gfn_end, memslot->base_gfn + memslot->npages);
5296 if (start >= end)
5297 continue;
5298
5299 slot_handle_level_range(kvm, memslot, kvm_zap_rmapp,
5300 PT_PAGE_TABLE_LEVEL, PT_MAX_HUGEPAGE_LEVEL,
5301 start, end - 1, true);
5302 }
5303 }
5304
5305 spin_unlock(&kvm->mmu_lock);
5306 }
5307
5308 static bool slot_rmap_write_protect(struct kvm *kvm,
5309 struct kvm_rmap_head *rmap_head)
5310 {
5311 return __rmap_write_protect(kvm, rmap_head, false);
5312 }
5313
5314 void kvm_mmu_slot_remove_write_access(struct kvm *kvm,
5315 struct kvm_memory_slot *memslot)
5316 {
5317 bool flush;
5318
5319 spin_lock(&kvm->mmu_lock);
5320 flush = slot_handle_all_level(kvm, memslot, slot_rmap_write_protect,
5321 false);
5322 spin_unlock(&kvm->mmu_lock);
5323
5324 /*
5325 * kvm_mmu_slot_remove_write_access() and kvm_vm_ioctl_get_dirty_log()
5326 * which do tlb flush out of mmu-lock should be serialized by
5327 * kvm->slots_lock otherwise tlb flush would be missed.
5328 */
5329 lockdep_assert_held(&kvm->slots_lock);
5330
5331 /*
5332 * We can flush all the TLBs out of the mmu lock without TLB
5333 * corruption since we just change the spte from writable to
5334 * readonly so that we only need to care the case of changing
5335 * spte from present to present (changing the spte from present
5336 * to nonpresent will flush all the TLBs immediately), in other
5337 * words, the only case we care is mmu_spte_update() where we
5338 * haved checked SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE
5339 * instead of PT_WRITABLE_MASK, that means it does not depend
5340 * on PT_WRITABLE_MASK anymore.
5341 */
5342 if (flush)
5343 kvm_flush_remote_tlbs(kvm);
5344 }
5345
5346 static bool kvm_mmu_zap_collapsible_spte(struct kvm *kvm,
5347 struct kvm_rmap_head *rmap_head)
5348 {
5349 u64 *sptep;
5350 struct rmap_iterator iter;
5351 int need_tlb_flush = 0;
5352 kvm_pfn_t pfn;
5353 struct kvm_mmu_page *sp;
5354
5355 restart:
5356 for_each_rmap_spte(rmap_head, &iter, sptep) {
5357 sp = page_header(__pa(sptep));
5358 pfn = spte_to_pfn(*sptep);
5359
5360 /*
5361 * We cannot do huge page mapping for indirect shadow pages,
5362 * which are found on the last rmap (level = 1) when not using
5363 * tdp; such shadow pages are synced with the page table in
5364 * the guest, and the guest page table is using 4K page size
5365 * mapping if the indirect sp has level = 1.
5366 */
5367 if (sp->role.direct && !kvm_is_reserved_pfn(pfn) &&
5368 !kvm_is_zone_device_pfn(pfn) &&
5369 PageTransCompoundMap(pfn_to_page(pfn))) {
5370 drop_spte(kvm, sptep);
5371 need_tlb_flush = 1;
5372 goto restart;
5373 }
5374 }
5375
5376 return need_tlb_flush;
5377 }
5378
5379 void kvm_mmu_zap_collapsible_sptes(struct kvm *kvm,
5380 const struct kvm_memory_slot *memslot)
5381 {
5382 /* FIXME: const-ify all uses of struct kvm_memory_slot. */
5383 spin_lock(&kvm->mmu_lock);
5384 slot_handle_leaf(kvm, (struct kvm_memory_slot *)memslot,
5385 kvm_mmu_zap_collapsible_spte, true);
5386 spin_unlock(&kvm->mmu_lock);
5387 }
5388
5389 void kvm_mmu_slot_leaf_clear_dirty(struct kvm *kvm,
5390 struct kvm_memory_slot *memslot)
5391 {
5392 bool flush;
5393
5394 spin_lock(&kvm->mmu_lock);
5395 flush = slot_handle_leaf(kvm, memslot, __rmap_clear_dirty, false);
5396 spin_unlock(&kvm->mmu_lock);
5397
5398 lockdep_assert_held(&kvm->slots_lock);
5399
5400 /*
5401 * It's also safe to flush TLBs out of mmu lock here as currently this
5402 * function is only used for dirty logging, in which case flushing TLB
5403 * out of mmu lock also guarantees no dirty pages will be lost in
5404 * dirty_bitmap.
5405 */
5406 if (flush)
5407 kvm_flush_remote_tlbs(kvm);
5408 }
5409 EXPORT_SYMBOL_GPL(kvm_mmu_slot_leaf_clear_dirty);
5410
5411 void kvm_mmu_slot_largepage_remove_write_access(struct kvm *kvm,
5412 struct kvm_memory_slot *memslot)
5413 {
5414 bool flush;
5415
5416 spin_lock(&kvm->mmu_lock);
5417 flush = slot_handle_large_level(kvm, memslot, slot_rmap_write_protect,
5418 false);
5419 spin_unlock(&kvm->mmu_lock);
5420
5421 /* see kvm_mmu_slot_remove_write_access */
5422 lockdep_assert_held(&kvm->slots_lock);
5423
5424 if (flush)
5425 kvm_flush_remote_tlbs(kvm);
5426 }
5427 EXPORT_SYMBOL_GPL(kvm_mmu_slot_largepage_remove_write_access);
5428
5429 void kvm_mmu_slot_set_dirty(struct kvm *kvm,
5430 struct kvm_memory_slot *memslot)
5431 {
5432 bool flush;
5433
5434 spin_lock(&kvm->mmu_lock);
5435 flush = slot_handle_all_level(kvm, memslot, __rmap_set_dirty, false);
5436 spin_unlock(&kvm->mmu_lock);
5437
5438 lockdep_assert_held(&kvm->slots_lock);
5439
5440 /* see kvm_mmu_slot_leaf_clear_dirty */
5441 if (flush)
5442 kvm_flush_remote_tlbs(kvm);
5443 }
5444 EXPORT_SYMBOL_GPL(kvm_mmu_slot_set_dirty);
5445
5446 #define BATCH_ZAP_PAGES 10
5447 static void kvm_zap_obsolete_pages(struct kvm *kvm)
5448 {
5449 struct kvm_mmu_page *sp, *node;
5450 int batch = 0;
5451
5452 restart:
5453 list_for_each_entry_safe_reverse(sp, node,
5454 &kvm->arch.active_mmu_pages, link) {
5455 int ret;
5456
5457 /*
5458 * No obsolete page exists before new created page since
5459 * active_mmu_pages is the FIFO list.
5460 */
5461 if (!is_obsolete_sp(kvm, sp))
5462 break;
5463
5464 /*
5465 * Since we are reversely walking the list and the invalid
5466 * list will be moved to the head, skip the invalid page
5467 * can help us to avoid the infinity list walking.
5468 */
5469 if (sp->role.invalid)
5470 continue;
5471
5472 /*
5473 * Need not flush tlb since we only zap the sp with invalid
5474 * generation number.
5475 */
5476 if (batch >= BATCH_ZAP_PAGES &&
5477 cond_resched_lock(&kvm->mmu_lock)) {
5478 batch = 0;
5479 goto restart;
5480 }
5481
5482 ret = kvm_mmu_prepare_zap_page(kvm, sp,
5483 &kvm->arch.zapped_obsolete_pages);
5484 batch += ret;
5485
5486 if (ret)
5487 goto restart;
5488 }
5489
5490 /*
5491 * Should flush tlb before free page tables since lockless-walking
5492 * may use the pages.
5493 */
5494 kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
5495 }
5496
5497 /*
5498 * Fast invalidate all shadow pages and use lock-break technique
5499 * to zap obsolete pages.
5500 *
5501 * It's required when memslot is being deleted or VM is being
5502 * destroyed, in these cases, we should ensure that KVM MMU does
5503 * not use any resource of the being-deleted slot or all slots
5504 * after calling the function.
5505 */
5506 void kvm_mmu_invalidate_zap_all_pages(struct kvm *kvm)
5507 {
5508 spin_lock(&kvm->mmu_lock);
5509 trace_kvm_mmu_invalidate_zap_all_pages(kvm);
5510 kvm->arch.mmu_valid_gen++;
5511
5512 /*
5513 * Notify all vcpus to reload its shadow page table
5514 * and flush TLB. Then all vcpus will switch to new
5515 * shadow page table with the new mmu_valid_gen.
5516 *
5517 * Note: we should do this under the protection of
5518 * mmu-lock, otherwise, vcpu would purge shadow page
5519 * but miss tlb flush.
5520 */
5521 kvm_reload_remote_mmus(kvm);
5522
5523 kvm_zap_obsolete_pages(kvm);
5524 spin_unlock(&kvm->mmu_lock);
5525 }
5526
5527 static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
5528 {
5529 return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
5530 }
5531
5532 void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm, u64 gen)
5533 {
5534 gen &= MMIO_GEN_MASK;
5535
5536 /*
5537 * Shift to eliminate the "update in-progress" flag, which isn't
5538 * included in the spte's generation number.
5539 */
5540 gen >>= 1;
5541
5542 /*
5543 * Generation numbers are incremented in multiples of the number of
5544 * address spaces in order to provide unique generations across all
5545 * address spaces. Strip what is effectively the address space
5546 * modifier prior to checking for a wrap of the MMIO generation so
5547 * that a wrap in any address space is detected.
5548 */
5549 gen &= ~((u64)KVM_ADDRESS_SPACE_NUM - 1);
5550
5551 /*
5552 * The very rare case: if the MMIO generation number has wrapped,
5553 * zap all shadow pages.
5554 */
5555 if (unlikely(gen == 0)) {
5556 kvm_debug_ratelimited("kvm: zapping shadow pages for mmio generation wraparound\n");
5557 kvm_mmu_invalidate_zap_all_pages(kvm);
5558 }
5559 }
5560
5561 static unsigned long
5562 mmu_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
5563 {
5564 struct kvm *kvm;
5565 int nr_to_scan = sc->nr_to_scan;
5566 unsigned long freed = 0;
5567
5568 mutex_lock(&kvm_lock);
5569
5570 list_for_each_entry(kvm, &vm_list, vm_list) {
5571 int idx;
5572 LIST_HEAD(invalid_list);
5573
5574 /*
5575 * Never scan more than sc->nr_to_scan VM instances.
5576 * Will not hit this condition practically since we do not try
5577 * to shrink more than one VM and it is very unlikely to see
5578 * !n_used_mmu_pages so many times.
5579 */
5580 if (!nr_to_scan--)
5581 break;
5582 /*
5583 * n_used_mmu_pages is accessed without holding kvm->mmu_lock
5584 * here. We may skip a VM instance errorneosly, but we do not
5585 * want to shrink a VM that only started to populate its MMU
5586 * anyway.
5587 */
5588 if (!kvm->arch.n_used_mmu_pages &&
5589 !kvm_has_zapped_obsolete_pages(kvm))
5590 continue;
5591
5592 idx = srcu_read_lock(&kvm->srcu);
5593 spin_lock(&kvm->mmu_lock);
5594
5595 if (kvm_has_zapped_obsolete_pages(kvm)) {
5596 kvm_mmu_commit_zap_page(kvm,
5597 &kvm->arch.zapped_obsolete_pages);
5598 goto unlock;
5599 }
5600
5601 if (prepare_zap_oldest_mmu_page(kvm, &invalid_list))
5602 freed++;
5603 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5604
5605 unlock:
5606 spin_unlock(&kvm->mmu_lock);
5607 srcu_read_unlock(&kvm->srcu, idx);
5608
5609 /*
5610 * unfair on small ones
5611 * per-vm shrinkers cry out
5612 * sadness comes quickly
5613 */
5614 list_move_tail(&kvm->vm_list, &vm_list);
5615 break;
5616 }
5617
5618 mutex_unlock(&kvm_lock);
5619 return freed;
5620 }
5621
5622 static unsigned long
5623 mmu_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
5624 {
5625 return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
5626 }
5627
5628 static struct shrinker mmu_shrinker = {
5629 .count_objects = mmu_shrink_count,
5630 .scan_objects = mmu_shrink_scan,
5631 .seeks = DEFAULT_SEEKS * 10,
5632 };
5633
5634 static void mmu_destroy_caches(void)
5635 {
5636 kmem_cache_destroy(pte_list_desc_cache);
5637 kmem_cache_destroy(mmu_page_header_cache);
5638 }
5639
5640 static bool get_nx_auto_mode(void)
5641 {
5642 /* Return true when CPU has the bug, and mitigations are ON */
5643 return boot_cpu_has_bug(X86_BUG_ITLB_MULTIHIT) && !cpu_mitigations_off();
5644 }
5645
5646 static void __set_nx_huge_pages(bool val)
5647 {
5648 nx_huge_pages = itlb_multihit_kvm_mitigation = val;
5649 }
5650
5651 static int set_nx_huge_pages(const char *val, const struct kernel_param *kp)
5652 {
5653 bool old_val = nx_huge_pages;
5654 bool new_val;
5655
5656 /* In "auto" mode deploy workaround only if CPU has the bug. */
5657 if (sysfs_streq(val, "off"))
5658 new_val = 0;
5659 else if (sysfs_streq(val, "force"))
5660 new_val = 1;
5661 else if (sysfs_streq(val, "auto"))
5662 new_val = get_nx_auto_mode();
5663 else if (strtobool(val, &new_val) < 0)
5664 return -EINVAL;
5665
5666 __set_nx_huge_pages(new_val);
5667
5668 if (new_val != old_val) {
5669 struct kvm *kvm;
5670 int idx;
5671
5672 mutex_lock(&kvm_lock);
5673
5674 list_for_each_entry(kvm, &vm_list, vm_list) {
5675 idx = srcu_read_lock(&kvm->srcu);
5676 kvm_mmu_invalidate_zap_all_pages(kvm);
5677 srcu_read_unlock(&kvm->srcu, idx);
5678
5679 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
5680 }
5681 mutex_unlock(&kvm_lock);
5682 }
5683
5684 return 0;
5685 }
5686
5687 int kvm_mmu_module_init(void)
5688 {
5689 int ret = -ENOMEM;
5690
5691 if (nx_huge_pages == -1)
5692 __set_nx_huge_pages(get_nx_auto_mode());
5693
5694 kvm_mmu_reset_all_pte_masks();
5695
5696 pte_list_desc_cache = kmem_cache_create("pte_list_desc",
5697 sizeof(struct pte_list_desc),
5698 0, SLAB_ACCOUNT, NULL);
5699 if (!pte_list_desc_cache)
5700 goto out;
5701
5702 mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
5703 sizeof(struct kvm_mmu_page),
5704 0, SLAB_ACCOUNT, NULL);
5705 if (!mmu_page_header_cache)
5706 goto out;
5707
5708 if (percpu_counter_init(&kvm_total_used_mmu_pages, 0, GFP_KERNEL))
5709 goto out;
5710
5711 ret = register_shrinker(&mmu_shrinker);
5712 if (ret)
5713 goto out;
5714
5715 return 0;
5716
5717 out:
5718 mmu_destroy_caches();
5719 return ret;
5720 }
5721
5722 /*
5723 * Caculate mmu pages needed for kvm.
5724 */
5725 unsigned long kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
5726 {
5727 unsigned long nr_mmu_pages;
5728 unsigned long nr_pages = 0;
5729 struct kvm_memslots *slots;
5730 struct kvm_memory_slot *memslot;
5731 int i;
5732
5733 for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
5734 slots = __kvm_memslots(kvm, i);
5735
5736 kvm_for_each_memslot(memslot, slots)
5737 nr_pages += memslot->npages;
5738 }
5739
5740 nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
5741 nr_mmu_pages = max(nr_mmu_pages, KVM_MIN_ALLOC_MMU_PAGES);
5742
5743 return nr_mmu_pages;
5744 }
5745
5746 void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
5747 {
5748 kvm_mmu_unload(vcpu);
5749 free_mmu_pages(vcpu);
5750 mmu_free_memory_caches(vcpu);
5751 }
5752
5753 void kvm_mmu_module_exit(void)
5754 {
5755 mmu_destroy_caches();
5756 percpu_counter_destroy(&kvm_total_used_mmu_pages);
5757 unregister_shrinker(&mmu_shrinker);
5758 mmu_audit_disable();
5759 }
5760
5761 static int set_nx_huge_pages_recovery_ratio(const char *val, const struct kernel_param *kp)
5762 {
5763 unsigned int old_val;
5764 int err;
5765
5766 old_val = nx_huge_pages_recovery_ratio;
5767 err = param_set_uint(val, kp);
5768 if (err)
5769 return err;
5770
5771 if (READ_ONCE(nx_huge_pages) &&
5772 !old_val && nx_huge_pages_recovery_ratio) {
5773 struct kvm *kvm;
5774
5775 mutex_lock(&kvm_lock);
5776
5777 list_for_each_entry(kvm, &vm_list, vm_list)
5778 wake_up_process(kvm->arch.nx_lpage_recovery_thread);
5779
5780 mutex_unlock(&kvm_lock);
5781 }
5782
5783 return err;
5784 }
5785
5786 static void kvm_recover_nx_lpages(struct kvm *kvm)
5787 {
5788 int rcu_idx;
5789 struct kvm_mmu_page *sp;
5790 unsigned int ratio;
5791 LIST_HEAD(invalid_list);
5792 ulong to_zap;
5793
5794 rcu_idx = srcu_read_lock(&kvm->srcu);
5795 spin_lock(&kvm->mmu_lock);
5796
5797 ratio = READ_ONCE(nx_huge_pages_recovery_ratio);
5798 to_zap = ratio ? DIV_ROUND_UP(kvm->stat.nx_lpage_splits, ratio) : 0;
5799 while (to_zap && !list_empty(&kvm->arch.lpage_disallowed_mmu_pages)) {
5800 /*
5801 * We use a separate list instead of just using active_mmu_pages
5802 * because the number of lpage_disallowed pages is expected to
5803 * be relatively small compared to the total.
5804 */
5805 sp = list_first_entry(&kvm->arch.lpage_disallowed_mmu_pages,
5806 struct kvm_mmu_page,
5807 lpage_disallowed_link);
5808 WARN_ON_ONCE(!sp->lpage_disallowed);
5809 kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
5810 WARN_ON_ONCE(sp->lpage_disallowed);
5811
5812 if (!--to_zap || need_resched() || spin_needbreak(&kvm->mmu_lock)) {
5813 kvm_mmu_commit_zap_page(kvm, &invalid_list);
5814 if (to_zap)
5815 cond_resched_lock(&kvm->mmu_lock);
5816 }
5817 }
5818
5819 spin_unlock(&kvm->mmu_lock);
5820 srcu_read_unlock(&kvm->srcu, rcu_idx);
5821 }
5822
5823 static long get_nx_lpage_recovery_timeout(u64 start_time)
5824 {
5825 return READ_ONCE(nx_huge_pages) && READ_ONCE(nx_huge_pages_recovery_ratio)
5826 ? start_time + 60 * HZ - get_jiffies_64()
5827 : MAX_SCHEDULE_TIMEOUT;
5828 }
5829
5830 static int kvm_nx_lpage_recovery_worker(struct kvm *kvm, uintptr_t data)
5831 {
5832 u64 start_time;
5833 long remaining_time;
5834
5835 while (true) {
5836 start_time = get_jiffies_64();
5837 remaining_time = get_nx_lpage_recovery_timeout(start_time);
5838
5839 set_current_state(TASK_INTERRUPTIBLE);
5840 while (!kthread_should_stop() && remaining_time > 0) {
5841 schedule_timeout(remaining_time);
5842 remaining_time = get_nx_lpage_recovery_timeout(start_time);
5843 set_current_state(TASK_INTERRUPTIBLE);
5844 }
5845
5846 set_current_state(TASK_RUNNING);
5847
5848 if (kthread_should_stop())
5849 return 0;
5850
5851 kvm_recover_nx_lpages(kvm);
5852 }
5853 }
5854
5855 int kvm_mmu_post_init_vm(struct kvm *kvm)
5856 {
5857 int err;
5858
5859 err = kvm_vm_create_worker_thread(kvm, kvm_nx_lpage_recovery_worker, 0,
5860 "kvm-nx-lpage-recovery",
5861 &kvm->arch.nx_lpage_recovery_thread);
5862 if (!err)
5863 kthread_unpark(kvm->arch.nx_lpage_recovery_thread);
5864
5865 return err;
5866 }
5867
5868 void kvm_mmu_pre_destroy_vm(struct kvm *kvm)
5869 {
5870 if (kvm->arch.nx_lpage_recovery_thread)
5871 kthread_stop(kvm->arch.nx_lpage_recovery_thread);
5872 }