xref: /openbmc/linux/virt/kvm/pfncache.c (revision 7a7621df)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  *
5  * This module enables kernel and guest-mode vCPU access to guest physical
6  * memory with suitable invalidation mechanisms.
7  *
8  * Copyright © 2021 Amazon.com, Inc. or its affiliates.
9  *
10  * Authors:
11  *   David Woodhouse <dwmw2@infradead.org>
12  */
13 
14 #include <linux/kvm_host.h>
15 #include <linux/kvm.h>
16 #include <linux/highmem.h>
17 #include <linux/module.h>
18 #include <linux/errno.h>
19 
20 #include "kvm_mm.h"
21 
22 /*
23  * MMU notifier 'invalidate_range_start' hook.
24  */
25 void gfn_to_pfn_cache_invalidate_start(struct kvm *kvm, unsigned long start,
26 				       unsigned long end, bool may_block)
27 {
28 	DECLARE_BITMAP(vcpu_bitmap, KVM_MAX_VCPUS);
29 	struct gfn_to_pfn_cache *gpc;
30 	bool evict_vcpus = false;
31 
32 	spin_lock(&kvm->gpc_lock);
33 	list_for_each_entry(gpc, &kvm->gpc_list, list) {
34 		write_lock_irq(&gpc->lock);
35 
36 		/* Only a single page so no need to care about length */
37 		if (gpc->valid && !is_error_noslot_pfn(gpc->pfn) &&
38 		    gpc->uhva >= start && gpc->uhva < end) {
39 			gpc->valid = false;
40 
41 			/*
42 			 * If a guest vCPU could be using the physical address,
43 			 * it needs to be forced out of guest mode.
44 			 */
45 			if (gpc->usage & KVM_GUEST_USES_PFN) {
46 				if (!evict_vcpus) {
47 					evict_vcpus = true;
48 					bitmap_zero(vcpu_bitmap, KVM_MAX_VCPUS);
49 				}
50 				__set_bit(gpc->vcpu->vcpu_idx, vcpu_bitmap);
51 			}
52 		}
53 		write_unlock_irq(&gpc->lock);
54 	}
55 	spin_unlock(&kvm->gpc_lock);
56 
57 	if (evict_vcpus) {
58 		/*
59 		 * KVM needs to ensure the vCPU is fully out of guest context
60 		 * before allowing the invalidation to continue.
61 		 */
62 		unsigned int req = KVM_REQ_OUTSIDE_GUEST_MODE;
63 		bool called;
64 
65 		/*
66 		 * If the OOM reaper is active, then all vCPUs should have
67 		 * been stopped already, so perform the request without
68 		 * KVM_REQUEST_WAIT and be sad if any needed to be IPI'd.
69 		 */
70 		if (!may_block)
71 			req &= ~KVM_REQUEST_WAIT;
72 
73 		called = kvm_make_vcpus_request_mask(kvm, req, vcpu_bitmap);
74 
75 		WARN_ON_ONCE(called && !may_block);
76 	}
77 }
78 
79 bool kvm_gfn_to_pfn_cache_check(struct kvm *kvm, struct gfn_to_pfn_cache *gpc,
80 				gpa_t gpa, unsigned long len)
81 {
82 	struct kvm_memslots *slots = kvm_memslots(kvm);
83 
84 	if ((gpa & ~PAGE_MASK) + len > PAGE_SIZE)
85 		return false;
86 
87 	if (gpc->gpa != gpa || gpc->generation != slots->generation ||
88 	    kvm_is_error_hva(gpc->uhva))
89 		return false;
90 
91 	if (!gpc->valid)
92 		return false;
93 
94 	return true;
95 }
96 EXPORT_SYMBOL_GPL(kvm_gfn_to_pfn_cache_check);
97 
98 static void gpc_unmap_khva(struct kvm *kvm, kvm_pfn_t pfn, void *khva)
99 {
100 	/* Unmap the old pfn/page if it was mapped before. */
101 	if (!is_error_noslot_pfn(pfn) && khva) {
102 		if (pfn_valid(pfn))
103 			kunmap(pfn_to_page(pfn));
104 #ifdef CONFIG_HAS_IOMEM
105 		else
106 			memunmap(khva);
107 #endif
108 	}
109 }
110 
111 static inline bool mmu_notifier_retry_cache(struct kvm *kvm, unsigned long mmu_seq)
112 {
113 	/*
114 	 * mn_active_invalidate_count acts for all intents and purposes
115 	 * like mmu_notifier_count here; but the latter cannot be used
116 	 * here because the invalidation of caches in the mmu_notifier
117 	 * event occurs _before_ mmu_notifier_count is elevated.
118 	 *
119 	 * Note, it does not matter that mn_active_invalidate_count
120 	 * is not protected by gpc->lock.  It is guaranteed to
121 	 * be elevated before the mmu_notifier acquires gpc->lock, and
122 	 * isn't dropped until after mmu_notifier_seq is updated.
123 	 */
124 	if (kvm->mn_active_invalidate_count)
125 		return true;
126 
127 	/*
128 	 * Ensure mn_active_invalidate_count is read before
129 	 * mmu_notifier_seq.  This pairs with the smp_wmb() in
130 	 * mmu_notifier_invalidate_range_end() to guarantee either the
131 	 * old (non-zero) value of mn_active_invalidate_count or the
132 	 * new (incremented) value of mmu_notifier_seq is observed.
133 	 */
134 	smp_rmb();
135 	return kvm->mmu_notifier_seq != mmu_seq;
136 }
137 
138 static kvm_pfn_t hva_to_pfn_retry(struct kvm *kvm, struct gfn_to_pfn_cache *gpc)
139 {
140 	/* Note, the new page offset may be different than the old! */
141 	void *old_khva = gpc->khva - offset_in_page(gpc->khva);
142 	kvm_pfn_t new_pfn = KVM_PFN_ERR_FAULT;
143 	void *new_khva = NULL;
144 	unsigned long mmu_seq;
145 
146 	lockdep_assert_held(&gpc->refresh_lock);
147 
148 	lockdep_assert_held_write(&gpc->lock);
149 
150 	/*
151 	 * Invalidate the cache prior to dropping gpc->lock, the gpa=>uhva
152 	 * assets have already been updated and so a concurrent check() from a
153 	 * different task may not fail the gpa/uhva/generation checks.
154 	 */
155 	gpc->valid = false;
156 
157 	do {
158 		mmu_seq = kvm->mmu_notifier_seq;
159 		smp_rmb();
160 
161 		write_unlock_irq(&gpc->lock);
162 
163 		/*
164 		 * If the previous iteration "failed" due to an mmu_notifier
165 		 * event, release the pfn and unmap the kernel virtual address
166 		 * from the previous attempt.  Unmapping might sleep, so this
167 		 * needs to be done after dropping the lock.  Opportunistically
168 		 * check for resched while the lock isn't held.
169 		 */
170 		if (new_pfn != KVM_PFN_ERR_FAULT) {
171 			/*
172 			 * Keep the mapping if the previous iteration reused
173 			 * the existing mapping and didn't create a new one.
174 			 */
175 			if (new_khva != old_khva)
176 				gpc_unmap_khva(kvm, new_pfn, new_khva);
177 
178 			kvm_release_pfn_clean(new_pfn);
179 
180 			cond_resched();
181 		}
182 
183 		/* We always request a writeable mapping */
184 		new_pfn = hva_to_pfn(gpc->uhva, false, NULL, true, NULL);
185 		if (is_error_noslot_pfn(new_pfn))
186 			goto out_error;
187 
188 		/*
189 		 * Obtain a new kernel mapping if KVM itself will access the
190 		 * pfn.  Note, kmap() and memremap() can both sleep, so this
191 		 * too must be done outside of gpc->lock!
192 		 */
193 		if (gpc->usage & KVM_HOST_USES_PFN) {
194 			if (new_pfn == gpc->pfn) {
195 				new_khva = old_khva;
196 			} else if (pfn_valid(new_pfn)) {
197 				new_khva = kmap(pfn_to_page(new_pfn));
198 #ifdef CONFIG_HAS_IOMEM
199 			} else {
200 				new_khva = memremap(pfn_to_hpa(new_pfn), PAGE_SIZE, MEMREMAP_WB);
201 #endif
202 			}
203 			if (!new_khva) {
204 				kvm_release_pfn_clean(new_pfn);
205 				goto out_error;
206 			}
207 		}
208 
209 		write_lock_irq(&gpc->lock);
210 
211 		/*
212 		 * Other tasks must wait for _this_ refresh to complete before
213 		 * attempting to refresh.
214 		 */
215 		WARN_ON_ONCE(gpc->valid);
216 	} while (mmu_notifier_retry_cache(kvm, mmu_seq));
217 
218 	gpc->valid = true;
219 	gpc->pfn = new_pfn;
220 	gpc->khva = new_khva + (gpc->gpa & ~PAGE_MASK);
221 
222 	/*
223 	 * Put the reference to the _new_ pfn.  The pfn is now tracked by the
224 	 * cache and can be safely migrated, swapped, etc... as the cache will
225 	 * invalidate any mappings in response to relevant mmu_notifier events.
226 	 */
227 	kvm_release_pfn_clean(new_pfn);
228 
229 	return 0;
230 
231 out_error:
232 	write_lock_irq(&gpc->lock);
233 
234 	return -EFAULT;
235 }
236 
237 int kvm_gfn_to_pfn_cache_refresh(struct kvm *kvm, struct gfn_to_pfn_cache *gpc,
238 				 gpa_t gpa, unsigned long len)
239 {
240 	struct kvm_memslots *slots = kvm_memslots(kvm);
241 	unsigned long page_offset = gpa & ~PAGE_MASK;
242 	kvm_pfn_t old_pfn, new_pfn;
243 	unsigned long old_uhva;
244 	void *old_khva;
245 	int ret = 0;
246 
247 	/*
248 	 * If must fit within a single page. The 'len' argument is
249 	 * only to enforce that.
250 	 */
251 	if (page_offset + len > PAGE_SIZE)
252 		return -EINVAL;
253 
254 	/*
255 	 * If another task is refreshing the cache, wait for it to complete.
256 	 * There is no guarantee that concurrent refreshes will see the same
257 	 * gpa, memslots generation, etc..., so they must be fully serialized.
258 	 */
259 	mutex_lock(&gpc->refresh_lock);
260 
261 	write_lock_irq(&gpc->lock);
262 
263 	old_pfn = gpc->pfn;
264 	old_khva = gpc->khva - offset_in_page(gpc->khva);
265 	old_uhva = gpc->uhva;
266 
267 	/* If the userspace HVA is invalid, refresh that first */
268 	if (gpc->gpa != gpa || gpc->generation != slots->generation ||
269 	    kvm_is_error_hva(gpc->uhva)) {
270 		gfn_t gfn = gpa_to_gfn(gpa);
271 
272 		gpc->gpa = gpa;
273 		gpc->generation = slots->generation;
274 		gpc->memslot = __gfn_to_memslot(slots, gfn);
275 		gpc->uhva = gfn_to_hva_memslot(gpc->memslot, gfn);
276 
277 		if (kvm_is_error_hva(gpc->uhva)) {
278 			ret = -EFAULT;
279 			goto out;
280 		}
281 	}
282 
283 	/*
284 	 * If the userspace HVA changed or the PFN was already invalid,
285 	 * drop the lock and do the HVA to PFN lookup again.
286 	 */
287 	if (!gpc->valid || old_uhva != gpc->uhva) {
288 		ret = hva_to_pfn_retry(kvm, gpc);
289 	} else {
290 		/* If the HVA→PFN mapping was already valid, don't unmap it. */
291 		old_pfn = KVM_PFN_ERR_FAULT;
292 		old_khva = NULL;
293 	}
294 
295  out:
296 	/*
297 	 * Invalidate the cache and purge the pfn/khva if the refresh failed.
298 	 * Some/all of the uhva, gpa, and memslot generation info may still be
299 	 * valid, leave it as is.
300 	 */
301 	if (ret) {
302 		gpc->valid = false;
303 		gpc->pfn = KVM_PFN_ERR_FAULT;
304 		gpc->khva = NULL;
305 	}
306 
307 	/* Snapshot the new pfn before dropping the lock! */
308 	new_pfn = gpc->pfn;
309 
310 	write_unlock_irq(&gpc->lock);
311 
312 	mutex_unlock(&gpc->refresh_lock);
313 
314 	if (old_pfn != new_pfn)
315 		gpc_unmap_khva(kvm, old_pfn, old_khva);
316 
317 	return ret;
318 }
319 EXPORT_SYMBOL_GPL(kvm_gfn_to_pfn_cache_refresh);
320 
321 void kvm_gfn_to_pfn_cache_unmap(struct kvm *kvm, struct gfn_to_pfn_cache *gpc)
322 {
323 	void *old_khva;
324 	kvm_pfn_t old_pfn;
325 
326 	mutex_lock(&gpc->refresh_lock);
327 	write_lock_irq(&gpc->lock);
328 
329 	gpc->valid = false;
330 
331 	old_khva = gpc->khva - offset_in_page(gpc->khva);
332 	old_pfn = gpc->pfn;
333 
334 	/*
335 	 * We can leave the GPA → uHVA map cache intact but the PFN
336 	 * lookup will need to be redone even for the same page.
337 	 */
338 	gpc->khva = NULL;
339 	gpc->pfn = KVM_PFN_ERR_FAULT;
340 
341 	write_unlock_irq(&gpc->lock);
342 	mutex_unlock(&gpc->refresh_lock);
343 
344 	gpc_unmap_khva(kvm, old_pfn, old_khva);
345 }
346 EXPORT_SYMBOL_GPL(kvm_gfn_to_pfn_cache_unmap);
347 
348 
349 int kvm_gfn_to_pfn_cache_init(struct kvm *kvm, struct gfn_to_pfn_cache *gpc,
350 			      struct kvm_vcpu *vcpu, enum pfn_cache_usage usage,
351 			      gpa_t gpa, unsigned long len)
352 {
353 	WARN_ON_ONCE(!usage || (usage & KVM_GUEST_AND_HOST_USE_PFN) != usage);
354 
355 	if (!gpc->active) {
356 		rwlock_init(&gpc->lock);
357 		mutex_init(&gpc->refresh_lock);
358 
359 		gpc->khva = NULL;
360 		gpc->pfn = KVM_PFN_ERR_FAULT;
361 		gpc->uhva = KVM_HVA_ERR_BAD;
362 		gpc->vcpu = vcpu;
363 		gpc->usage = usage;
364 		gpc->valid = false;
365 		gpc->active = true;
366 
367 		spin_lock(&kvm->gpc_lock);
368 		list_add(&gpc->list, &kvm->gpc_list);
369 		spin_unlock(&kvm->gpc_lock);
370 	}
371 	return kvm_gfn_to_pfn_cache_refresh(kvm, gpc, gpa, len);
372 }
373 EXPORT_SYMBOL_GPL(kvm_gfn_to_pfn_cache_init);
374 
375 void kvm_gfn_to_pfn_cache_destroy(struct kvm *kvm, struct gfn_to_pfn_cache *gpc)
376 {
377 	if (gpc->active) {
378 		spin_lock(&kvm->gpc_lock);
379 		list_del(&gpc->list);
380 		spin_unlock(&kvm->gpc_lock);
381 
382 		kvm_gfn_to_pfn_cache_unmap(kvm, gpc);
383 		gpc->active = false;
384 	}
385 }
386 EXPORT_SYMBOL_GPL(kvm_gfn_to_pfn_cache_destroy);
387