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