xref: /linux/virt/kvm/guest_memfd.c (revision 56070f00d07e30caa9a66c3660045f5f2956a629)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/anon_inodes.h>
3 #include <linux/backing-dev.h>
4 #include <linux/falloc.h>
5 #include <linux/fs.h>
6 #include <linux/kvm_host.h>
7 #include <linux/maple_tree.h>
8 #include <linux/mempolicy.h>
9 #include <linux/pseudo_fs.h>
10 #include <linux/pagemap.h>
11 #include <linux/swap.h>
12 
13 #include "kvm_mm.h"
14 #include "guest_memfd.h"
15 
16 static struct vfsmount *kvm_gmem_mnt;
17 
18 /*
19  * A guest_memfd instance can be associated multiple VMs, each with its own
20  * "view" of the underlying physical memory.
21  *
22  * The gmem's inode is effectively the raw underlying physical storage, and is
23  * used to track properties of the physical memory, while each gmem file is
24  * effectively a single VM's view of that storage, and is used to track assets
25  * specific to its associated VM, e.g. memslots=>gmem bindings.
26  */
27 struct gmem_file {
28 	struct kvm *kvm;
29 	struct xarray bindings;
30 	struct list_head entry;
31 };
32 
33 struct gmem_inode {
34 	struct shared_policy policy;
35 	struct inode vfs_inode;
36 	struct list_head gmem_file_list;
37 
38 	u64 flags;
39 	/*
40 	 * Every index in this inode, whether memory is populated or
41 	 * not, is tracked in attributes. The entire range of indices,
42 	 * corresponding to the size of this inode, is represented in
43 	 * this maple tree.
44 	 */
45 	struct maple_tree attributes;
46 };
47 
48 static __always_inline struct gmem_inode *GMEM_I(struct inode *inode)
49 {
50 	return container_of(inode, struct gmem_inode, vfs_inode);
51 }
52 
53 #define kvm_gmem_for_each_file(f, inode) \
54 	list_for_each_entry(f, &GMEM_I(inode)->gmem_file_list, entry)
55 
56 /**
57  * folio_file_pfn - like folio_file_page, but return a pfn.
58  * @folio: The folio which contains this index.
59  * @index: The index we want to look up.
60  *
61  * Return: The pfn for this index.
62  */
63 static inline kvm_pfn_t folio_file_pfn(struct folio *folio, pgoff_t index)
64 {
65 	return folio_pfn(folio) + (index & (folio_nr_pages(folio) - 1));
66 }
67 
68 static pgoff_t kvm_gmem_get_index(struct kvm_memory_slot *slot, gfn_t gfn)
69 {
70 	return gfn - slot->base_gfn + slot->gmem.pgoff;
71 }
72 
73 static u64 kvm_gmem_get_default_attributes(struct inode *inode)
74 {
75 	bool init_shared = GMEM_I(inode)->flags & GUEST_MEMFD_FLAG_INIT_SHARED;
76 
77 	return init_shared ? 0 : KVM_MEMORY_ATTRIBUTE_PRIVATE;
78 }
79 
80 static u64 kvm_gmem_get_attributes(struct inode *inode, void *entry)
81 {
82 	if (WARN_ON_ONCE(!entry))
83 		return kvm_gmem_get_default_attributes(inode);
84 
85 	return xa_to_value(entry);
86 }
87 
88 static bool kvm_gmem_is_private_mem(struct inode *inode, pgoff_t index)
89 {
90 	struct maple_tree *mt = &GMEM_I(inode)->attributes;
91 	void *entry = mtree_load(mt, index);
92 
93 	return kvm_gmem_get_attributes(inode, entry) &
94 	       KVM_MEMORY_ATTRIBUTE_PRIVATE;
95 }
96 
97 static bool kvm_gmem_is_shared_mem(struct inode *inode, pgoff_t index)
98 {
99 	return !kvm_gmem_is_private_mem(inode, index);
100 }
101 
102 static bool kvm_gmem_range_has_attributes(struct inode *inode,
103 					  pgoff_t index, size_t nr_pages,
104 					  u64 attributes)
105 {
106 	struct maple_tree *mt = &GMEM_I(inode)->attributes;
107 	pgoff_t end = index + nr_pages - 1;
108 	void *entry;
109 
110 	lockdep_assert(mt_lock_is_held(mt));
111 
112 	mt_for_each(mt, entry, index, end) {
113 		if (kvm_gmem_get_attributes(inode, entry) != attributes)
114 			return false;
115 	}
116 
117 	return true;
118 }
119 
120 /*
121  * Returns a locked folio on success.  The caller is responsible for
122  * setting the up-to-date flag before the memory is mapped into the guest.
123  * There is no backing storage for the memory, so the folio will remain
124  * up-to-date until it's removed.
125  *
126  * Ignore accessed, referenced, and dirty flags.  The memory is
127  * unevictable and there is no storage to write back to.
128  */
129 static struct folio *kvm_gmem_get_folio(struct inode *inode, pgoff_t index)
130 {
131 	/* TODO: Support huge pages. */
132 	struct mempolicy *policy;
133 	struct folio *folio;
134 
135 	/*
136 	 * Fast-path: See if folio is already present in mapping to avoid
137 	 * policy_lookup.
138 	 */
139 	folio = filemap_lock_folio(inode->i_mapping, index);
140 	if (!IS_ERR(folio))
141 		return folio;
142 
143 	policy = mpol_shared_policy_lookup(&GMEM_I(inode)->policy, index);
144 	folio = __filemap_get_folio_mpol(inode->i_mapping, index,
145 					 FGP_LOCK | FGP_CREAT,
146 					 mapping_gfp_mask(inode->i_mapping), policy);
147 	mpol_cond_put(policy);
148 
149 	/*
150 	 * External interfaces like kvm_gmem_get_pfn() support dealing
151 	 * with hugepages to a degree, but internally, guest_memfd currently
152 	 * assumes that all folios are order-0 and handling would need
153 	 * to be updated for anything otherwise (e.g. page-clearing
154 	 * operations).
155 	 */
156 	WARN_ON_ONCE(!IS_ERR(folio) && folio_order(folio));
157 
158 	return folio;
159 }
160 
161 static enum kvm_gfn_range_filter kvm_gmem_get_all_gfns_filter(struct inode *inode)
162 {
163 	if (gmem_in_place_conversion)
164 		return KVM_FILTER_SHARED | KVM_FILTER_PRIVATE;
165 
166 	if (GMEM_I(inode)->flags & GUEST_MEMFD_FLAG_INIT_SHARED)
167 		return KVM_FILTER_SHARED;
168 
169 	return KVM_FILTER_PRIVATE;
170 }
171 
172 static void __kvm_gmem_invalidate_start(struct gmem_file *f, pgoff_t start,
173 					pgoff_t end,
174 					enum kvm_gfn_range_filter attr_filter)
175 {
176 	bool flush = false, found_memslot = false;
177 	struct kvm_memory_slot *slot;
178 	struct kvm *kvm = f->kvm;
179 	unsigned long index;
180 
181 	xa_for_each_range(&f->bindings, index, slot, start, end - 1) {
182 		pgoff_t pgoff = slot->gmem.pgoff;
183 
184 		struct kvm_gfn_range gfn_range = {
185 			.start = slot->base_gfn + max(pgoff, start) - pgoff,
186 			.end = slot->base_gfn + min(pgoff + slot->npages, end) - pgoff,
187 			.slot = slot,
188 			.may_block = true,
189 			.attr_filter = attr_filter,
190 		};
191 
192 		if (!found_memslot) {
193 			found_memslot = true;
194 
195 			KVM_MMU_LOCK(kvm);
196 			kvm_mmu_invalidate_start(kvm);
197 		}
198 
199 		flush |= kvm_mmu_unmap_gfn_range(kvm, &gfn_range);
200 
201 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_INVALIDATE
202 		kvm_arch_gmem_invalidate_range(kvm, &gfn_range);
203 #endif
204 	}
205 
206 	if (flush)
207 		kvm_flush_remote_tlbs(kvm);
208 
209 	if (found_memslot)
210 		KVM_MMU_UNLOCK(kvm);
211 }
212 
213 static void kvm_gmem_invalidate_start(struct inode *inode, pgoff_t start,
214 				      pgoff_t end,
215 				      enum kvm_gfn_range_filter filter)
216 {
217 	struct gmem_file *f;
218 
219 	kvm_gmem_for_each_file(f, inode)
220 		__kvm_gmem_invalidate_start(f, start, end, filter);
221 }
222 
223 static void __kvm_gmem_invalidate_end(struct gmem_file *f, pgoff_t start,
224 				      pgoff_t end)
225 {
226 	struct kvm *kvm = f->kvm;
227 
228 	if (xa_find(&f->bindings, &start, end - 1, XA_PRESENT)) {
229 		KVM_MMU_LOCK(kvm);
230 		kvm_mmu_invalidate_end(kvm);
231 		KVM_MMU_UNLOCK(kvm);
232 	}
233 }
234 
235 static void kvm_gmem_invalidate_end(struct inode *inode, pgoff_t start,
236 				    pgoff_t end)
237 {
238 	struct gmem_file *f;
239 
240 	kvm_gmem_for_each_file(f, inode)
241 		__kvm_gmem_invalidate_end(f, start, end);
242 }
243 
244 static long kvm_gmem_punch_hole(struct inode *inode, loff_t offset, loff_t len)
245 {
246 	enum kvm_gfn_range_filter filter = kvm_gmem_get_all_gfns_filter(inode);
247 	pgoff_t start = offset >> PAGE_SHIFT;
248 	pgoff_t end = (offset + len) >> PAGE_SHIFT;
249 
250 	/*
251 	 * Bindings must be stable across invalidation to ensure the start+end
252 	 * are balanced.
253 	 */
254 	filemap_invalidate_lock(inode->i_mapping);
255 
256 	kvm_gmem_invalidate_start(inode, start, end, filter);
257 
258 	truncate_inode_pages_range(inode->i_mapping, offset, offset + len - 1);
259 
260 	kvm_gmem_invalidate_end(inode, start, end);
261 
262 	filemap_invalidate_unlock(inode->i_mapping);
263 
264 	return 0;
265 }
266 
267 static long kvm_gmem_allocate(struct inode *inode, loff_t offset, loff_t len)
268 {
269 	struct address_space *mapping = inode->i_mapping;
270 	pgoff_t start, index, end;
271 	int r;
272 
273 	/* Dedicated guest is immutable by default. */
274 	if (offset + len > i_size_read(inode))
275 		return -EINVAL;
276 
277 	filemap_invalidate_lock_shared(mapping);
278 
279 	start = offset >> PAGE_SHIFT;
280 	end = (offset + len) >> PAGE_SHIFT;
281 
282 	r = 0;
283 	for (index = start; index < end; ) {
284 		struct folio *folio;
285 
286 		if (signal_pending(current)) {
287 			r = -EINTR;
288 			break;
289 		}
290 
291 		folio = kvm_gmem_get_folio(inode, index);
292 		if (IS_ERR(folio)) {
293 			r = PTR_ERR(folio);
294 			break;
295 		}
296 
297 		index = folio_next_index(folio);
298 
299 		folio_unlock(folio);
300 		folio_put(folio);
301 
302 		/* 64-bit only, wrapping the index should be impossible. */
303 		if (WARN_ON_ONCE(!index))
304 			break;
305 
306 		cond_resched();
307 	}
308 
309 	filemap_invalidate_unlock_shared(mapping);
310 
311 	return r;
312 }
313 
314 static long kvm_gmem_fallocate(struct file *file, int mode, loff_t offset,
315 			       loff_t len)
316 {
317 	int ret;
318 
319 	if (!(mode & FALLOC_FL_KEEP_SIZE))
320 		return -EOPNOTSUPP;
321 
322 	if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
323 		return -EOPNOTSUPP;
324 
325 	if (!PAGE_ALIGNED(offset) || !PAGE_ALIGNED(len))
326 		return -EINVAL;
327 
328 	if (mode & FALLOC_FL_PUNCH_HOLE)
329 		ret = kvm_gmem_punch_hole(file_inode(file), offset, len);
330 	else
331 		ret = kvm_gmem_allocate(file_inode(file), offset, len);
332 
333 	if (!ret)
334 		file_modified(file);
335 	return ret;
336 }
337 
338 static int kvm_gmem_release(struct inode *inode, struct file *file)
339 {
340 	struct gmem_file *f = file->private_data;
341 	struct kvm_memory_slot *slot;
342 	struct kvm *kvm = f->kvm;
343 	unsigned long index;
344 
345 	/*
346 	 * Prevent concurrent attempts to *unbind* a memslot.  This is the last
347 	 * reference to the file and thus no new bindings can be created, but
348 	 * dereferencing the slot for existing bindings needs to be protected
349 	 * against memslot updates, specifically so that unbind doesn't race
350 	 * and free the memslot (kvm_gmem_get_file() will return NULL).
351 	 */
352 	mutex_lock(&kvm->slots_lock);
353 
354 	filemap_invalidate_lock(inode->i_mapping);
355 
356 	/*
357 	 * Note!  synchronize_srcu() is _not_ needed after nullifying memslot
358 	 * bindings as slot->gmem.file cannot be set back to a non-null value
359 	 * without the memslot first being deleted.  I.e. this relies on the
360 	 * synchronize_srcu_expedited() in kvm_swap_active_memslots() to ensure
361 	 * kvm_gmem_get_pfn() (which runs with kvm->srcu held for read) can't
362 	 * grab a reference to slot->gmem.file even if the struct file object
363 	 * is reallocated (for use as a different file).
364 	 *
365 	 * file_ref_put() provides a full barrier, and __get_file_rcu() the
366 	 * matching acquire barrier, to ensure that kvm_gmem_get_file() (via
367 	 * __get_file_rcu()) sees refcount==0 or fails the "file reloaded"
368 	 * check (file != NULL due to nullifying the file pointer here).
369 	 *
370 	 * Unlike most other users of get_file_rcu(), where callers don't care
371 	 * if they race with a write, only that they have a reference to _a_
372 	 * live file, kvm_gmem_get_pfn() needs to get the exact file that is
373 	 * associated with the memslot.  Without the aforementioned SRCU
374 	 * synchronization, the following could happen:
375 	 *
376 	 *  CPU0				CPU1
377 	 *  kvm_gmem_get_pfn()
378 	 *    slot->gmem.file == A
379 	 *					kvm_gmem_release())
380 	 *					  slot->gmem.file = NULL
381 	 *
382 	 *					kvm_set_memory_region()
383 	 *					  slot deleted
384 	 *
385 	 *					kvm_set_memory_region()
386 	 *					  slot created
387 	 *					  slot->gmem.file = B (alloc the same object)
388 	 *
389 	 *  get_file_active()
390 	 *    file = B
391 	 *    file_reloaded = B
392 	 *
393 	 * <KVM does weird things with an old memslot + new file>
394 	 *
395 	 * Obviously KVM would be broken in many places if the synchronization
396 	 * were omitted, but it's important to note that get_file_active() does
397 	 * NOT guarantee a reference to the "original" file was obtained, only
398 	 * that it grabbed a reference for the returned file, i.e. didn't grab
399 	 * a reference for file A, but then returned a pointer to file B.
400 	 */
401 	xa_for_each(&f->bindings, index, slot)
402 		WRITE_ONCE(slot->gmem.file, NULL);
403 
404 	/*
405 	 * All in-flight operations are gone and new bindings can be created.
406 	 * Zap all SPTEs pointed at by this file.  Do not free the backing
407 	 * memory, as its lifetime is associated with the inode, not the file.
408 	 */
409 	__kvm_gmem_invalidate_start(f, 0, -1ul,
410 				    kvm_gmem_get_all_gfns_filter(inode));
411 	__kvm_gmem_invalidate_end(f, 0, -1ul);
412 
413 	list_del(&f->entry);
414 
415 	filemap_invalidate_unlock(inode->i_mapping);
416 
417 	mutex_unlock(&kvm->slots_lock);
418 
419 	xa_destroy(&f->bindings);
420 	kfree(f);
421 
422 	kvm_put_kvm(kvm);
423 
424 	return 0;
425 }
426 
427 static inline struct file *kvm_gmem_get_file(struct kvm_memory_slot *slot)
428 {
429 	/*
430 	 * Do not return slot->gmem.file if it has already been closed;
431 	 * there might be some time between the last fput() and when
432 	 * kvm_gmem_release() clears slot->gmem.file.
433 	 */
434 	return get_file_active(&slot->gmem.file);
435 }
436 
437 DEFINE_CLASS(gmem_get_file, struct file *, if (_T) fput(_T),
438 	     kvm_gmem_get_file(slot), struct kvm_memory_slot *slot);
439 
440 static bool kvm_gmem_supports_mmap(struct inode *inode)
441 {
442 	return GMEM_I(inode)->flags & GUEST_MEMFD_FLAG_MMAP;
443 }
444 
445 static vm_fault_t kvm_gmem_fault_user_mapping(struct vm_fault *vmf)
446 {
447 	struct inode *inode = file_inode(vmf->vma->vm_file);
448 	struct folio *folio;
449 	vm_fault_t ret = VM_FAULT_LOCKED;
450 
451 	if (((loff_t)vmf->pgoff << PAGE_SHIFT) >= i_size_read(inode))
452 		return VM_FAULT_SIGBUS;
453 
454 	filemap_invalidate_lock_shared(inode->i_mapping);
455 	if (kvm_gmem_is_shared_mem(inode, vmf->pgoff))
456 		folio = kvm_gmem_get_folio(inode, vmf->pgoff);
457 	else
458 		folio = ERR_PTR(-EACCES);
459 	filemap_invalidate_unlock_shared(inode->i_mapping);
460 
461 	if (IS_ERR(folio)) {
462 		if (PTR_ERR(folio) == -EAGAIN)
463 			return VM_FAULT_RETRY;
464 
465 		return vmf_error(PTR_ERR(folio));
466 	}
467 
468 	if (WARN_ON_ONCE(folio_test_large(folio))) {
469 		ret = VM_FAULT_SIGBUS;
470 		goto out_folio;
471 	}
472 
473 	if (!folio_test_uptodate(folio)) {
474 		clear_highpage(folio_page(folio, 0));
475 		folio_mark_uptodate(folio);
476 	}
477 
478 	vmf->page = folio_file_page(folio, vmf->pgoff);
479 
480 out_folio:
481 	if (ret != VM_FAULT_LOCKED) {
482 		folio_unlock(folio);
483 		folio_put(folio);
484 	}
485 
486 	return ret;
487 }
488 
489 #ifdef CONFIG_NUMA
490 static int kvm_gmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol)
491 {
492 	struct inode *inode = file_inode(vma->vm_file);
493 
494 	return mpol_set_shared_policy(&GMEM_I(inode)->policy, vma, mpol);
495 }
496 
497 static struct mempolicy *kvm_gmem_get_policy(struct vm_area_struct *vma,
498 					     unsigned long addr, pgoff_t *ilx)
499 {
500 	pgoff_t pgoff = linear_page_index(vma, addr);
501 	struct inode *inode = file_inode(vma->vm_file);
502 
503 	*ilx = inode->i_ino;
504 
505 	/*
506 	 * Return the memory policy for this index, or NULL if none is set.
507 	 *
508 	 * Returning NULL, e.g. instead of the current task's memory policy, is
509 	 * important for the .get_policy kernel ABI: it indicates that no
510 	 * explicit policy has been set via mbind() for this memory. The caller
511 	 * can then replace NULL with the default memory policy instead of the
512 	 * current task's memory policy.
513 	 */
514 	return mpol_shared_policy_lookup(&GMEM_I(inode)->policy, pgoff);
515 }
516 #endif /* CONFIG_NUMA */
517 
518 static const struct vm_operations_struct kvm_gmem_vm_ops = {
519 	.fault		= kvm_gmem_fault_user_mapping,
520 #ifdef CONFIG_NUMA
521 	.get_policy	= kvm_gmem_get_policy,
522 	.set_policy	= kvm_gmem_set_policy,
523 #endif
524 };
525 
526 static int kvm_gmem_mmap(struct file *file, struct vm_area_struct *vma)
527 {
528 	if (!kvm_gmem_supports_mmap(file_inode(file)))
529 		return -ENODEV;
530 
531 	if ((vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) !=
532 	    (VM_SHARED | VM_MAYSHARE)) {
533 		return -EINVAL;
534 	}
535 
536 	vma->vm_ops = &kvm_gmem_vm_ops;
537 
538 	return 0;
539 }
540 
541 bool kvm_gmem_is_private_gfn(struct kvm *kvm, gfn_t gfn)
542 {
543 	struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
544 	struct inode *inode;
545 
546 	if (!slot)
547 		return 0;
548 
549 	CLASS(gmem_get_file, file)(slot);
550 	if (!file)
551 		return 0;
552 
553 	inode = file_inode(file);
554 
555 	/*
556 	 * Rely on the maple tree's internal RCU lock to ensure a stable result.
557 	 * This result can become stale as soon as the lock is dropped, so the
558 	 * caller _must_ protect consumption of private vs. shared either by
559 	 * holding guest_memfd's invalidate lock for the entire duration, or by
560 	 * checking mmu_invalidate_retry_gfn() under mmu_lock to serialize
561 	 * against concurrent attribute updates.
562 	 */
563 	return kvm_gmem_is_private_mem(inode, kvm_gmem_get_index(slot, gfn));
564 }
565 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_gmem_is_private_gfn);
566 
567 /*
568  * Preallocate memory for attributes to be stored on a maple tree, pointed to
569  * by mas.  Adjacent ranges with attributes identical to the new attributes
570  * will be merged.  Also sets mas's bounds up for storing attributes.
571  *
572  * This maintains the invariant that ranges with the same attributes will
573  * always be merged.
574  */
575 static int kvm_gmem_mas_preallocate(struct ma_state *mas, u64 attributes,
576 				    pgoff_t start, size_t nr_pages)
577 {
578 	pgoff_t end = start + nr_pages;
579 	pgoff_t last = end - 1;
580 	void *entry;
581 
582 	/* Try extending range. entry is NULL on overflow/wrap-around. */
583 	mas_set(mas, end);
584 	entry = mas_find(mas, end);
585 	if (entry && xa_to_value(entry) == attributes)
586 		last = mas->last;
587 
588 	if (start > 0) {
589 		mas_set(mas, start - 1);
590 		entry = mas_find(mas, start - 1);
591 		if (entry && xa_to_value(entry) == attributes)
592 			start = mas->index;
593 	}
594 
595 	mas_set_range(mas, start, last);
596 	return mas_preallocate(mas, xa_mk_value(attributes), GFP_KERNEL);
597 }
598 
599 static bool __folio_has_outstanding_references(struct folio *folio,
600 					       enum lru_cache_drained *drained)
601 {
602 	if (folio_maybe_dma_pinned(folio) || folio_mapped(folio))
603 		return true;
604 
605 	/* 1 reference held by filemap_get_folios() in the folio batch. */
606 	lru_cache_drain_for_folio(folio, 1, drained);
607 
608 	/*
609 	 * Outstanding references are anything other than those from the page
610 	 * cache, plus 1 temporary reference held by filemap_get_folios() in the
611 	 * folio batch.
612 	 */
613 	return folio_ref_count(folio) != folio_nr_pages(folio) + 1;
614 }
615 
616 static bool kvm_gmem_has_outstanding_references(struct inode *inode,
617 						pgoff_t start, size_t nr_pages,
618 						pgoff_t *err_index)
619 {
620 	enum lru_cache_drained drained = LRU_CACHE_NOT_DRAINED;
621 	struct address_space *mapping = inode->i_mapping;
622 	pgoff_t last = start + nr_pages - 1;
623 	struct folio_batch fbatch;
624 	pgoff_t next;
625 	int i;
626 
627 	folio_batch_init(&fbatch);
628 
629 	next = start;
630 	while (filemap_get_folios(mapping, &next, last, &fbatch)) {
631 		for (i = 0; i < folio_batch_count(&fbatch); ++i) {
632 			struct folio *folio = fbatch.folios[i];
633 
634 			if (__folio_has_outstanding_references(folio, &drained)) {
635 				*err_index = max(start, folio->index);
636 				folio_batch_release(&fbatch);
637 				return true;
638 			}
639 		}
640 
641 		folio_batch_release(&fbatch);
642 		cond_resched();
643 	}
644 
645 	return false;
646 }
647 
648 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_CONVERT
649 static void kvm_gmem_make_shared(struct inode *inode, pgoff_t start, pgoff_t end)
650 {
651 	struct folio_batch fbatch;
652 	pgoff_t next = start;
653 	int i;
654 
655 	folio_batch_init(&fbatch);
656 	while (filemap_get_folios(inode->i_mapping, &next, end - 1, &fbatch)) {
657 		for (i = 0; i < folio_batch_count(&fbatch); ++i) {
658 			struct folio *folio = fbatch.folios[i];
659 			pgoff_t start_index, end_index;
660 			kvm_pfn_t start_pfn;
661 			kvm_pfn_t nr_pages;
662 
663 			start_index = max(start, folio->index);
664 			end_index = min(end, folio_next_index(folio));
665 			/*
666 			 * end_index is either in folio or points to
667 			 * the first page of the next folio. Hence,
668 			 * all pages in range [start_index, end_index)
669 			 * are contiguous.
670 			 */
671 			start_pfn = folio_file_pfn(folio, start_index);
672 			nr_pages = end_index - start_index;
673 
674 			kvm_arch_gmem_make_shared(start_pfn, nr_pages);
675 		}
676 
677 		folio_batch_release(&fbatch);
678 		cond_resched();
679 	}
680 }
681 #else
682 static void kvm_gmem_make_shared(struct inode *inode, pgoff_t start, pgoff_t end) {}
683 #endif
684 
685 static int __kvm_gmem_set_attributes(struct inode *inode, pgoff_t start,
686 				     size_t nr_pages, uint64_t attrs,
687 				     pgoff_t *err_index)
688 {
689 	bool to_private = attrs & KVM_MEMORY_ATTRIBUTE_PRIVATE;
690 	struct address_space *mapping = inode->i_mapping;
691 	struct gmem_inode *gi = GMEM_I(inode);
692 	enum kvm_gfn_range_filter filter;
693 	pgoff_t end = start + nr_pages;
694 	struct maple_tree *mt;
695 	struct ma_state mas;
696 	int r = 0;
697 
698 	mt = &gi->attributes;
699 
700 	filemap_invalidate_lock(mapping);
701 
702 	if (kvm_gmem_range_has_attributes(inode, start, nr_pages, attrs))
703 		goto out;
704 
705 	mas_init(&mas, mt, start);
706 	r = kvm_gmem_mas_preallocate(&mas, attrs, start, nr_pages);
707 	if (r) {
708 		*err_index = start;
709 		goto out;
710 	}
711 
712 	if (to_private) {
713 		/*
714 		 * Forcefully unmap the pages from all userspace page tables,
715 		 * and then verify there are no outstanding references, e.g.
716 		 * acquired via GUP or similar.  Tell userspace to try again if
717 		 * there are outstanding references and hope that whatever has
718 		 * pinned the page will put its reference "soon".
719 		 */
720 		unmap_mapping_pages(mapping, start, nr_pages, false);
721 
722 		if (kvm_gmem_has_outstanding_references(inode, start, nr_pages,
723 							err_index)) {
724 			mas_destroy(&mas);
725 			r = -EAGAIN;
726 			goto out;
727 		}
728 	}
729 
730 	/*
731 	 * From this point on guest_memfd has performed necessary
732 	 * checks and can proceed to do guest-breaking changes.
733 	 */
734 
735 	filter = to_private ? KVM_FILTER_SHARED : KVM_FILTER_PRIVATE;
736 	kvm_gmem_invalidate_start(inode, start, end, filter);
737 
738 	if (!to_private && kvm_arch_has_gmem_convert())
739 		kvm_gmem_make_shared(inode, start, end);
740 
741 	mas_store_prealloc(&mas, xa_mk_value(attrs));
742 
743 	kvm_gmem_invalidate_end(inode, start, end);
744 out:
745 	filemap_invalidate_unlock(mapping);
746 	return r;
747 }
748 
749 static long kvm_gmem_set_attributes(struct file *file, void __user *argp)
750 {
751 	struct gmem_file *f = file->private_data;
752 	struct inode *inode = file_inode(file);
753 	struct kvm_memory_attributes2 attrs;
754 	pgoff_t err_index;
755 	size_t nr_pages;
756 	pgoff_t index;
757 	int i, r;
758 
759 	if (copy_from_user(&attrs, argp, sizeof(attrs)))
760 		return -EFAULT;
761 
762 	if (attrs.flags)
763 		return -EINVAL;
764 	for (i = 0; i < ARRAY_SIZE(attrs.reserved); i++) {
765 		if (attrs.reserved[i])
766 			return -EINVAL;
767 	}
768 	if (!kvm_arch_has_private_mem(f->kvm))
769 		return -EINVAL;
770 	if (attrs.attributes & ~KVM_MEMORY_ATTRIBUTE_PRIVATE)
771 		return -EINVAL;
772 	if (attrs.size == 0 || attrs.offset + attrs.size < attrs.offset)
773 		return -EINVAL;
774 	if (!PAGE_ALIGNED(attrs.offset) || !PAGE_ALIGNED(attrs.size))
775 		return -EINVAL;
776 
777 	if (attrs.offset >= i_size_read(inode) ||
778 	    attrs.offset + attrs.size > i_size_read(inode))
779 		return -EINVAL;
780 
781 	nr_pages = attrs.size >> PAGE_SHIFT;
782 	index = attrs.offset >> PAGE_SHIFT;
783 	r = __kvm_gmem_set_attributes(inode, index, nr_pages, attrs.attributes,
784 				      &err_index);
785 	if (r) {
786 		attrs.error_offset = ((uint64_t)err_index) << PAGE_SHIFT;
787 
788 		if (copy_to_user(argp, &attrs, sizeof(attrs)))
789 			return -EFAULT;
790 	}
791 
792 	return r;
793 }
794 
795 static long kvm_gmem_ioctl(struct file *file, unsigned int ioctl,
796 			   unsigned long arg)
797 {
798 	switch (ioctl) {
799 	case KVM_SET_MEMORY_ATTRIBUTES2:
800 		if (!gmem_in_place_conversion)
801 			return -ENOTTY;
802 
803 		return kvm_gmem_set_attributes(file, (void __user *)arg);
804 	default:
805 		return -ENOTTY;
806 	}
807 }
808 
809 static struct file_operations kvm_gmem_fops = {
810 	.mmap		= kvm_gmem_mmap,
811 	.open		= generic_file_open,
812 	.release	= kvm_gmem_release,
813 	.fallocate	= kvm_gmem_fallocate,
814 	.unlocked_ioctl	= kvm_gmem_ioctl,
815 };
816 
817 static int kvm_gmem_migrate_folio(struct address_space *mapping,
818 				  struct folio *dst, struct folio *src,
819 				  enum migrate_mode mode)
820 {
821 	WARN_ON_ONCE(1);
822 	return -EINVAL;
823 }
824 
825 static int kvm_gmem_error_folio(struct address_space *mapping, struct folio *folio)
826 {
827 	struct inode *inode = mapping->host;
828 	enum kvm_gfn_range_filter filter;
829 	pgoff_t start, end;
830 
831 	/*
832 	 * memory_failure() invokes ->error_remove_folio() while holding the
833 	 * poisoned folio lock.  Do not block on mapping->invalidate_lock, as
834 	 * a writer that already holds the invalidate lock can be waiting for
835 	 * the same folio, e.g. truncation from MADV_REMOVE/FALLOC_FL_PUNCH_HOLE.
836 	 *
837 	 * If the invalidate lock is contended, fail the recovery instead of
838 	 * risking a deadlock in the memory-failure path.
839 	 */
840 	if (!filemap_invalidate_trylock_shared(mapping))
841 		return -EBUSY;
842 
843 	start = folio->index;
844 	end = start + folio_nr_pages(folio);
845 
846 	filter = kvm_gmem_get_all_gfns_filter(inode);
847 	kvm_gmem_invalidate_start(inode, start, end, filter);
848 
849 	/*
850 	 * Do not truncate the range, what action is taken in response to the
851 	 * error is userspace's decision (assuming the architecture supports
852 	 * gracefully handling memory errors).  If/when the guest attempts to
853 	 * access a poisoned page, kvm_gmem_get_pfn() will return -EHWPOISON,
854 	 * at which point KVM can either terminate the VM or propagate the
855 	 * error to userspace.
856 	 */
857 
858 	kvm_gmem_invalidate_end(mapping->host, start, end);
859 
860 	filemap_invalidate_unlock_shared(mapping);
861 
862 	return MF_DELAYED;
863 }
864 
865 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_RECLAIM
866 static void kvm_gmem_free_folio(struct folio *folio)
867 {
868 	kvm_arch_gmem_reclaim(folio_file_pfn(folio, 0), folio_nr_pages(folio));
869 }
870 #endif
871 
872 static const struct address_space_operations kvm_gmem_aops = {
873 	.dirty_folio = noop_dirty_folio,
874 	.migrate_folio	= kvm_gmem_migrate_folio,
875 	.error_remove_folio = kvm_gmem_error_folio,
876 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_RECLAIM
877 	.free_folio = kvm_gmem_free_folio,
878 #endif
879 };
880 
881 static int kvm_gmem_setattr(const struct mnt_idmap *idmap, struct dentry *dentry,
882 			    struct iattr *attr)
883 {
884 	return -EINVAL;
885 }
886 static const struct inode_operations kvm_gmem_iops = {
887 	.setattr	= kvm_gmem_setattr,
888 };
889 
890 bool __weak kvm_arch_supports_gmem_init_shared(struct kvm *kvm)
891 {
892 	return true;
893 }
894 
895 static int kvm_gmem_init_inode(struct inode *inode, loff_t size, u64 flags)
896 {
897 	struct gmem_inode *gi = GMEM_I(inode);
898 	MA_STATE(mas, &gi->attributes, 0, (size >> PAGE_SHIFT) - 1);
899 	u64 attrs;
900 	int r;
901 
902 	inode->i_op = &kvm_gmem_iops;
903 	inode->i_mapping->a_ops = &kvm_gmem_aops;
904 	inode->i_mode |= S_IFREG;
905 	inode->i_size = size;
906 	mapping_set_gfp_mask(inode->i_mapping, GFP_HIGHUSER);
907 
908 	/*
909 	 * guest_memfd memory is neither migratable nor swappable: set
910 	 * inaccessible to gate off both.
911 	 */
912 	mapping_set_inaccessible(inode->i_mapping);
913 	WARN_ON_ONCE(!mapping_unevictable(inode->i_mapping));
914 
915 	gi->flags = flags;
916 
917 	mt_set_external_lock(&gi->attributes,
918 			     &inode->i_mapping->invalidate_lock);
919 
920 	/*
921 	 * Store default attributes for the entire gmem instance. Ensuring every
922 	 * index is represented in the maple tree at all times simplifies the
923 	 * conversion and merging logic.
924 	 */
925 	attrs = kvm_gmem_get_default_attributes(inode);
926 
927 	/*
928 	 * Acquire the invalidation lock purely to make lockdep happy.  The
929 	 * maple tree library expects all stores to be protected via the lock,
930 	 * and the library can't know when the tree is reachable only by the
931 	 * caller, as is the case here.
932 	 */
933 	filemap_invalidate_lock(inode->i_mapping);
934 	r = mas_store_gfp(&mas, xa_mk_value(attrs), GFP_KERNEL);
935 	filemap_invalidate_unlock(inode->i_mapping);
936 
937 	return r;
938 }
939 
940 static int __kvm_gmem_create(struct kvm *kvm, loff_t size, u64 flags)
941 {
942 	static const char *name = "[kvm-gmem]";
943 	struct gmem_file *f;
944 	struct inode *inode;
945 	struct file *file;
946 	int fd, err;
947 
948 	fd = get_unused_fd_flags(0);
949 	if (fd < 0)
950 		return fd;
951 
952 	f = kzalloc_obj(*f);
953 	if (!f) {
954 		err = -ENOMEM;
955 		goto err_fd;
956 	}
957 
958 	/* __fput() will take care of fops_put(). */
959 	if (!fops_get(&kvm_gmem_fops)) {
960 		err = -ENOENT;
961 		goto err_gmem;
962 	}
963 
964 	inode = anon_inode_make_secure_inode(kvm_gmem_mnt->mnt_sb, name, NULL);
965 	if (IS_ERR(inode)) {
966 		err = PTR_ERR(inode);
967 		goto err_fops;
968 	}
969 
970 	err = kvm_gmem_init_inode(inode, size, flags);
971 	if (err)
972 		goto err_inode;
973 
974 	file = alloc_file_pseudo(inode, kvm_gmem_mnt, name, O_RDWR, &kvm_gmem_fops);
975 	if (IS_ERR(file)) {
976 		err = PTR_ERR(file);
977 		goto err_inode;
978 	}
979 
980 	file->f_flags |= O_LARGEFILE;
981 	file->private_data = f;
982 
983 	kvm_get_kvm(kvm);
984 	f->kvm = kvm;
985 	xa_init(&f->bindings);
986 	list_add(&f->entry, &GMEM_I(inode)->gmem_file_list);
987 
988 	fd_install(fd, file);
989 	return fd;
990 
991 err_inode:
992 	iput(inode);
993 err_fops:
994 	fops_put(&kvm_gmem_fops);
995 err_gmem:
996 	kfree(f);
997 err_fd:
998 	put_unused_fd(fd);
999 	return err;
1000 }
1001 
1002 int kvm_gmem_create(struct kvm *kvm, struct kvm_create_guest_memfd *args)
1003 {
1004 	loff_t size = args->size;
1005 	u64 flags = args->flags;
1006 
1007 	if (flags & ~kvm_gmem_get_supported_flags(kvm))
1008 		return -EINVAL;
1009 
1010 	if (size <= 0 || !PAGE_ALIGNED(size))
1011 		return -EINVAL;
1012 
1013 	return __kvm_gmem_create(kvm, size, flags);
1014 }
1015 
1016 int kvm_gmem_prepare_memory_region(struct kvm *kvm, struct kvm_memory_slot *slot,
1017 				   unsigned int fd, uoff_t offset)
1018 {
1019 	uoff_t size = slot->npages << PAGE_SHIFT;
1020 	struct gmem_file *f;
1021 	struct inode *inode;
1022 	struct file *file;
1023 
1024 
1025 	BUILD_BUG_ON(sizeof(gpa_t) != sizeof(offset));
1026 	BUILD_BUG_ON(sizeof(gfn_t) != sizeof(slot->gmem.pgoff));
1027 
1028 	if (WARN_ON_ONCE(slot->flags & KVM_MEMSLOT_GMEM_ONLY))
1029 		return -EINVAL;
1030 
1031 	file = fget(fd);
1032 	if (!file)
1033 		return -EBADF;
1034 
1035 	if (file->f_op != &kvm_gmem_fops)
1036 		goto err;
1037 
1038 	f = file->private_data;
1039 	if (f->kvm != kvm)
1040 		goto err;
1041 
1042 	inode = file_inode(file);
1043 
1044 	if (!PAGE_ALIGNED(offset) || offset + size > i_size_read(inode))
1045 		goto err;
1046 
1047 	/*
1048 	 * memslots of flag KVM_MEM_GUEST_MEMFD are immutable to change, so
1049 	 * kvm_gmem_bind() must occur on a new memslot.  Because the memslot
1050 	 * is not visible yet, kvm_gmem_get_pfn() is guaranteed to see the file.
1051 	 */
1052 	slot->gmem.file = file;
1053 	slot->gmem.pgoff = offset >> PAGE_SHIFT;
1054 	if (gmem_in_place_conversion || kvm_gmem_supports_mmap(inode))
1055 		slot->flags |= KVM_MEMSLOT_GMEM_ONLY;
1056 
1057 	/*
1058 	 * Gift the caller a reference to the file.  The reference will be
1059 	 * dropped after bindings are established, or if installing the new
1060 	 * memslot ultimately fails.
1061 	 */
1062 	return 0;
1063 
1064 err:
1065 	fput(file);
1066 	return -EINVAL;
1067 }
1068 
1069 int kvm_gmem_commit_memory_region(struct kvm *kvm, struct kvm_memory_slot *slot)
1070 {
1071 	struct gmem_file *f = slot->gmem.file->private_data;
1072 	struct inode *inode = file_inode(slot->gmem.file);
1073 	unsigned long start, end;
1074 	int r;
1075 
1076 	if (WARN_ON_ONCE(slot->gmem.file->f_op != &kvm_gmem_fops))
1077 		return -EIO;
1078 
1079 	filemap_invalidate_lock(inode->i_mapping);
1080 
1081 	start = slot->gmem.pgoff;
1082 	end = start + slot->npages;
1083 
1084 	if (!xa_empty(&f->bindings) &&
1085 	    xa_find(&f->bindings, &start, end - 1, XA_PRESENT)) {
1086 		filemap_invalidate_unlock(inode->i_mapping);
1087 		return -EEXIST;
1088 	}
1089 
1090 	r = xa_err(xa_store_range(&f->bindings, start, end - 1, slot, GFP_KERNEL));
1091 	if (r)
1092 		xa_store_range(&f->bindings, start, end - 1, NULL, GFP_KERNEL);
1093 
1094 	filemap_invalidate_unlock(inode->i_mapping);
1095 
1096 	return r;
1097 }
1098 
1099 void kvm_gmem_unbind(struct kvm_memory_slot *slot)
1100 {
1101 	struct file *file = slot->gmem.file;
1102 	unsigned long start = slot->gmem.pgoff;
1103 	unsigned long end = start + slot->npages;
1104 	struct gmem_file *f;
1105 
1106 	/*
1107 	 * Nothing to do if the underlying file was _already_ closed, as
1108 	 * kvm_gmem_release() invalidates and nullifies all bindings.
1109 	 */
1110 	if (!file)
1111 		return;
1112 
1113 	/*
1114 	 * However, if the file is _being_ closed, then the bindings need to be
1115 	 * removed as kvm_gmem_release() might not run until after the memslot
1116 	 * is freed.  Modifying the bindings is safe even if the file is dying
1117 	 * as kvm_gmem_release() nullifies slot->gmem.file under slots_lock,
1118 	 * and only puts its reference to KVM after destroying all bindings.
1119 	 * I.e. reaching this point means kvm_gmem_release() hasn't destroyed
1120 	 * the bindings or freed the gmem_file and can't do so until the caller
1121 	 * drops slots_lock, so there's no need to verify the file is live.
1122 	 */
1123 	f = file->private_data;
1124 
1125 	filemap_invalidate_lock(file->f_mapping);
1126 	xa_store_range(&f->bindings, start, end - 1, NULL, GFP_KERNEL);
1127 
1128 	/*
1129 	 * Note, the caller is responsible for ensuring the slot is unreachable
1130 	 * before unbinding, e.g. by synchronizing SRCU after deleting the slot,
1131 	 * to guarantee kvm_gmem_get_pfn() can't see the slot+file.
1132 	 */
1133 	WRITE_ONCE(slot->gmem.file, NULL);
1134 	filemap_invalidate_unlock(file->f_mapping);
1135 }
1136 
1137 /* Returns a locked folio on success.  */
1138 static struct folio *__kvm_gmem_get_pfn(struct file *file,
1139 					struct kvm_memory_slot *slot,
1140 					pgoff_t index, kvm_pfn_t *pfn,
1141 					int *max_order)
1142 {
1143 	struct file *slot_file = READ_ONCE(slot->gmem.file);
1144 	struct gmem_file *f = file->private_data;
1145 	struct folio *folio;
1146 
1147 	if (file != slot_file) {
1148 		WARN_ON_ONCE(slot_file);
1149 		return ERR_PTR(-EFAULT);
1150 	}
1151 
1152 	if (xa_load(&f->bindings, index) != slot) {
1153 		WARN_ON_ONCE(xa_load(&f->bindings, index));
1154 		return ERR_PTR(-EIO);
1155 	}
1156 
1157 	folio = kvm_gmem_get_folio(file_inode(file), index);
1158 	if (IS_ERR(folio))
1159 		return folio;
1160 
1161 	if (folio_test_hwpoison(folio)) {
1162 		folio_unlock(folio);
1163 		folio_put(folio);
1164 		return ERR_PTR(-EHWPOISON);
1165 	}
1166 
1167 	if (!folio_test_uptodate(folio)) {
1168 		clear_highpage(folio_page(folio, 0));
1169 		folio_mark_uptodate(folio);
1170 	}
1171 
1172 	*pfn = folio_file_pfn(folio, index);
1173 	if (max_order)
1174 		*max_order = 0;
1175 
1176 	return folio;
1177 }
1178 
1179 int kvm_gmem_get_pfn(struct kvm *kvm, struct kvm_memory_slot *slot,
1180 		     gfn_t gfn, kvm_pfn_t *pfn, int *max_order)
1181 {
1182 	pgoff_t index = kvm_gmem_get_index(slot, gfn);
1183 	struct folio *folio;
1184 	int r = 0, __order;
1185 
1186 	max_order = max_order ?: &__order;
1187 
1188 	CLASS(gmem_get_file, file)(slot);
1189 	if (!file)
1190 		return -EFAULT;
1191 
1192 	filemap_invalidate_lock_shared(file_inode(file)->i_mapping);
1193 
1194 	folio = __kvm_gmem_get_pfn(file, slot, index, pfn, max_order);
1195 	if (IS_ERR(folio)) {
1196 		r = PTR_ERR(folio);
1197 		goto out;
1198 	}
1199 
1200 	if (kvm_arch_has_gmem_convert() &&
1201 	    kvm_gmem_is_private_mem(file_inode(file), index))
1202 		r = kvm_arch_gmem_make_private(kvm, gfn, *pfn,
1203 					       (kvm_pfn_t)1 << *max_order);
1204 
1205 	folio_unlock(folio);
1206 	folio_put(folio);
1207 
1208 out:
1209 	filemap_invalidate_unlock_shared(file_inode(file)->i_mapping);
1210 	return r;
1211 }
1212 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_gmem_get_pfn);
1213 
1214 #ifdef CONFIG_HAVE_KVM_ARCH_GMEM_POPULATE
1215 
1216 static long __kvm_gmem_populate(struct kvm *kvm, struct kvm_memory_slot *slot,
1217 				struct file *file, gfn_t gfn, struct page *src_page,
1218 				kvm_gmem_populate_cb post_populate, void *opaque)
1219 {
1220 	pgoff_t index = kvm_gmem_get_index(slot, gfn);
1221 	struct folio *folio;
1222 	kvm_pfn_t pfn;
1223 	int ret;
1224 
1225 	filemap_invalidate_lock(file->f_mapping);
1226 
1227 	folio = __kvm_gmem_get_pfn(file, slot, index, &pfn, NULL);
1228 	if (IS_ERR(folio)) {
1229 		ret = PTR_ERR(folio);
1230 		goto out_unlock;
1231 	}
1232 
1233 	folio_unlock(folio);
1234 
1235 	if (!kvm_is_private_gfn(kvm, gfn)) {
1236 		ret = -EINVAL;
1237 		goto out_put_folio;
1238 	}
1239 
1240 	ret = post_populate(kvm, gfn, pfn, src_page, opaque);
1241 
1242 out_put_folio:
1243 	folio_put(folio);
1244 out_unlock:
1245 	filemap_invalidate_unlock(file->f_mapping);
1246 	return ret;
1247 }
1248 
1249 long kvm_gmem_populate(struct kvm *kvm, gfn_t start_gfn, void __user *src,
1250 		       long npages, bool may_writeback_src,
1251 		       kvm_gmem_populate_cb post_populate, void *opaque)
1252 {
1253 	struct kvm_memory_slot *slot;
1254 	int ret = 0;
1255 	long i;
1256 
1257 	lockdep_assert_held(&kvm->slots_lock);
1258 
1259 	if (WARN_ON_ONCE(npages <= 0))
1260 		return -EINVAL;
1261 
1262 	if (WARN_ON_ONCE(!PAGE_ALIGNED(src)))
1263 		return -EINVAL;
1264 
1265 	slot = gfn_to_memslot(kvm, start_gfn);
1266 	if (!kvm_slot_has_gmem(slot))
1267 		return -EINVAL;
1268 
1269 	CLASS(gmem_get_file, file)(slot);
1270 	if (!file)
1271 		return -EFAULT;
1272 
1273 	npages = min_t(ulong, slot->npages - (start_gfn - slot->base_gfn), npages);
1274 	for (i = 0; i < npages; i++) {
1275 		struct page *src_page = NULL;
1276 
1277 		if (signal_pending(current)) {
1278 			ret = -EINTR;
1279 			break;
1280 		}
1281 
1282 		if (src) {
1283 			unsigned long uaddr = (unsigned long)src + i * PAGE_SIZE;
1284 			unsigned int flags = may_writeback_src ? FOLL_WRITE : 0;
1285 
1286 			ret = get_user_pages_fast(uaddr, 1, flags, &src_page);
1287 			if (ret < 0)
1288 				break;
1289 			if (ret != 1) {
1290 				ret = -ENOMEM;
1291 				break;
1292 			}
1293 		}
1294 
1295 		ret = __kvm_gmem_populate(kvm, slot, file, start_gfn + i, src_page,
1296 					  post_populate, opaque);
1297 
1298 		if (src_page)
1299 			put_page(src_page);
1300 
1301 		if (ret)
1302 			break;
1303 	}
1304 
1305 	return ret && !i ? ret : i;
1306 }
1307 EXPORT_SYMBOL_FOR_KVM_INTERNAL(kvm_gmem_populate);
1308 #endif
1309 
1310 static struct kmem_cache *kvm_gmem_inode_cachep;
1311 
1312 static void kvm_gmem_init_inode_once(void *__gi)
1313 {
1314 	struct gmem_inode *gi = __gi;
1315 
1316 	/*
1317 	 * Note!  Don't initialize the inode with anything specific to the
1318 	 * guest_memfd instance, or that might be specific to how the inode is
1319 	 * used (from the VFS-layer's perspective).  This hook is called only
1320 	 * during the initial slab allocation, i.e. only fields/state that are
1321 	 * idempotent across _all_ use of the inode _object_ can be initialized
1322 	 * at this time!
1323 	 */
1324 	inode_init_once(&gi->vfs_inode);
1325 }
1326 
1327 static struct inode *kvm_gmem_alloc_inode(struct super_block *sb)
1328 {
1329 	struct gmem_inode *gi;
1330 
1331 	gi = alloc_inode_sb(sb, kvm_gmem_inode_cachep, GFP_KERNEL);
1332 	if (!gi)
1333 		return NULL;
1334 
1335 	mpol_shared_policy_init(&gi->policy, NULL);
1336 
1337 	/*
1338 	 * Memory attributes are protected by the filemap invalidation lock, but
1339 	 * the lock structure isn't available at this time.  Immediately mark
1340 	 * maple tree as using external locking so that accessing the tree
1341 	 * before it's fully initialized results in NULL pointer dereferences
1342 	 * and not more subtle bugs.
1343 	 */
1344 	mt_init_flags(&gi->attributes, MT_FLAGS_LOCK_EXTERN | MT_FLAGS_USE_RCU);
1345 
1346 	gi->flags = 0;
1347 	INIT_LIST_HEAD(&gi->gmem_file_list);
1348 	return &gi->vfs_inode;
1349 }
1350 
1351 static void kvm_gmem_destroy_inode(struct inode *inode)
1352 {
1353 	struct gmem_inode *gi = GMEM_I(inode);
1354 
1355 	mpol_free_shared_policy(&gi->policy);
1356 
1357 	/*
1358 	 * Note!  Checking for an empty tree is functionally necessary
1359 	 * to avoid explosions if the tree hasn't been fully
1360 	 * initialized, i.e. if the inode is being destroyed before
1361 	 * guest_memfd can set the external lock, lockdep would find
1362 	 * that the tree's internal ma_lock was not held.
1363 	 */
1364 	if (!mtree_empty(&gi->attributes)) {
1365 		/*
1366 		 * Acquire the invalidation lock purely to make lockdep happy,
1367 		 * the inode is unreachable at this point.
1368 		 */
1369 		filemap_invalidate_lock(inode->i_mapping);
1370 		__mt_destroy(&gi->attributes);
1371 		filemap_invalidate_unlock(inode->i_mapping);
1372 	}
1373 }
1374 
1375 static void kvm_gmem_free_inode(struct inode *inode)
1376 {
1377 	kmem_cache_free(kvm_gmem_inode_cachep, GMEM_I(inode));
1378 }
1379 
1380 static const struct super_operations kvm_gmem_super_operations = {
1381 	.statfs		= simple_statfs,
1382 	.alloc_inode	= kvm_gmem_alloc_inode,
1383 	.destroy_inode	= kvm_gmem_destroy_inode,
1384 	.free_inode	= kvm_gmem_free_inode,
1385 };
1386 
1387 static int kvm_gmem_init_fs_context(struct fs_context *fc)
1388 {
1389 	struct pseudo_fs_context *ctx;
1390 
1391 	if (!init_pseudo(fc, GUEST_MEMFD_MAGIC))
1392 		return -ENOMEM;
1393 
1394 	ctx = fc->fs_private;
1395 	ctx->ops = &kvm_gmem_super_operations;
1396 
1397 	return 0;
1398 }
1399 
1400 static struct file_system_type kvm_gmem_fs = {
1401 	.name		 = "guest_memfd",
1402 	.init_fs_context = kvm_gmem_init_fs_context,
1403 	.kill_sb	 = kill_anon_super,
1404 };
1405 
1406 static int kvm_gmem_init_mount(void)
1407 {
1408 	kvm_gmem_mnt = kern_mount(&kvm_gmem_fs);
1409 
1410 	if (IS_ERR(kvm_gmem_mnt))
1411 		return PTR_ERR(kvm_gmem_mnt);
1412 
1413 	kvm_gmem_mnt->mnt_flags |= MNT_NOEXEC;
1414 	return 0;
1415 }
1416 
1417 int kvm_gmem_init(struct module *module)
1418 {
1419 	struct kmem_cache_args args = {
1420 		.align = 0,
1421 		.ctor = kvm_gmem_init_inode_once,
1422 	};
1423 	int ret;
1424 
1425 	kvm_gmem_fops.owner = module;
1426 	kvm_gmem_inode_cachep = kmem_cache_create("kvm_gmem_inode_cache",
1427 						  sizeof(struct gmem_inode),
1428 						  &args, SLAB_ACCOUNT);
1429 	if (!kvm_gmem_inode_cachep)
1430 		return -ENOMEM;
1431 
1432 	ret = kvm_gmem_init_mount();
1433 	if (ret) {
1434 		kmem_cache_destroy(kvm_gmem_inode_cachep);
1435 		return ret;
1436 	}
1437 	return 0;
1438 }
1439 
1440 void kvm_gmem_exit(void)
1441 {
1442 	kern_unmount(kvm_gmem_mnt);
1443 	kvm_gmem_mnt = NULL;
1444 	rcu_barrier();
1445 	kmem_cache_destroy(kvm_gmem_inode_cachep);
1446 }
1447