xref: /linux/fs/hugetlbfs/inode.c (revision a514e6f8f5caa24413731bed54b322bd34d918dd)
1 /*
2  * hugetlbpage-backed filesystem.  Based on ramfs.
3  *
4  * Nadia Yvette Chambers, 2002
5  *
6  * Copyright (C) 2002 Linus Torvalds.
7  * License: GPL
8  */
9 
10 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
11 
12 #include <linux/thread_info.h>
13 #include <asm/current.h>
14 #include <linux/falloc.h>
15 #include <linux/fs.h>
16 #include <linux/mount.h>
17 #include <linux/file.h>
18 #include <linux/kernel.h>
19 #include <linux/writeback.h>
20 #include <linux/pagemap.h>
21 #include <linux/highmem.h>
22 #include <linux/init.h>
23 #include <linux/string.h>
24 #include <linux/capability.h>
25 #include <linux/ctype.h>
26 #include <linux/backing-dev.h>
27 #include <linux/hugetlb.h>
28 #include <linux/pagevec.h>
29 #include <linux/fs_parser.h>
30 #include <linux/mman.h>
31 #include <linux/slab.h>
32 #include <linux/dnotify.h>
33 #include <linux/statfs.h>
34 #include <linux/security.h>
35 #include <linux/magic.h>
36 #include <linux/migrate.h>
37 #include <linux/uio.h>
38 
39 #include <linux/uaccess.h>
40 #include <linux/sched/mm.h>
41 
42 #define CREATE_TRACE_POINTS
43 #include <trace/events/hugetlbfs.h>
44 
45 static const struct address_space_operations hugetlbfs_aops;
46 static const struct file_operations hugetlbfs_file_operations;
47 static const struct inode_operations hugetlbfs_dir_inode_operations;
48 static const struct inode_operations hugetlbfs_inode_operations;
49 
50 enum hugetlbfs_size_type { NO_SIZE, SIZE_STD, SIZE_PERCENT };
51 
52 struct hugetlbfs_fs_context {
53 	struct hstate		*hstate;
54 	unsigned long long	max_size_opt;
55 	unsigned long long	min_size_opt;
56 	long			max_hpages;
57 	long			nr_inodes;
58 	long			min_hpages;
59 	enum hugetlbfs_size_type max_val_type;
60 	enum hugetlbfs_size_type min_val_type;
61 	kuid_t			uid;
62 	kgid_t			gid;
63 	umode_t			mode;
64 };
65 
66 int sysctl_hugetlb_shm_group;
67 
68 enum hugetlb_param {
69 	Opt_gid,
70 	Opt_min_size,
71 	Opt_mode,
72 	Opt_nr_inodes,
73 	Opt_pagesize,
74 	Opt_size,
75 	Opt_uid,
76 };
77 
78 static const struct fs_parameter_spec hugetlb_fs_parameters[] = {
79 	fsparam_gid   ("gid",		Opt_gid),
80 	fsparam_string("min_size",	Opt_min_size),
81 	fsparam_u32oct("mode",		Opt_mode),
82 	fsparam_string("nr_inodes",	Opt_nr_inodes),
83 	fsparam_string("pagesize",	Opt_pagesize),
84 	fsparam_string("size",		Opt_size),
85 	fsparam_uid   ("uid",		Opt_uid),
86 	{}
87 };
88 
89 /*
90  * Mask used when checking the page offset value passed in via system
91  * calls.  This value will be converted to a loff_t which is signed.
92  * Therefore, we want to check the upper PAGE_SHIFT + 1 bits of the
93  * value.  The extra bit (- 1 in the shift value) is to take the sign
94  * bit into account.
95  */
96 #define PGOFF_LOFFT_MAX \
97 	(((1UL << (PAGE_SHIFT + 1)) - 1) <<  (BITS_PER_LONG - (PAGE_SHIFT + 1)))
98 
99 static int hugetlbfs_file_mmap(struct file *file, struct vm_area_struct *vma)
100 {
101 	struct inode *inode = file_inode(file);
102 	struct hugetlbfs_inode_info *info = HUGETLBFS_I(inode);
103 	loff_t len, vma_len;
104 	int ret;
105 	struct hstate *h = hstate_file(file);
106 	vm_flags_t vm_flags;
107 
108 	/*
109 	 * vma address alignment (but not the pgoff alignment) has
110 	 * already been checked by prepare_hugepage_range.  If you add
111 	 * any error returns here, do so after setting VM_HUGETLB, so
112 	 * is_vm_hugetlb_page tests below unmap_region go the right
113 	 * way when do_mmap unwinds (may be important on powerpc
114 	 * and ia64).
115 	 */
116 	vm_flags_set(vma, VM_HUGETLB | VM_DONTEXPAND | VM_MTE_ALLOWED);
117 	vma->vm_ops = &hugetlb_vm_ops;
118 
119 	ret = seal_check_write(info->seals, vma);
120 	if (ret)
121 		return ret;
122 
123 	/*
124 	 * page based offset in vm_pgoff could be sufficiently large to
125 	 * overflow a loff_t when converted to byte offset.  This can
126 	 * only happen on architectures where sizeof(loff_t) ==
127 	 * sizeof(unsigned long).  So, only check in those instances.
128 	 */
129 	if (sizeof(unsigned long) == sizeof(loff_t)) {
130 		if (vma->vm_pgoff & PGOFF_LOFFT_MAX)
131 			return -EINVAL;
132 	}
133 
134 	/* must be huge page aligned */
135 	if (vma->vm_pgoff & (~huge_page_mask(h) >> PAGE_SHIFT))
136 		return -EINVAL;
137 
138 	vma_len = (loff_t)(vma->vm_end - vma->vm_start);
139 	len = vma_len + ((loff_t)vma->vm_pgoff << PAGE_SHIFT);
140 	/* check for overflow */
141 	if (len < vma_len)
142 		return -EINVAL;
143 
144 	inode_lock(inode);
145 	file_accessed(file);
146 
147 	ret = -ENOMEM;
148 
149 	vm_flags = vma->vm_flags;
150 	/*
151 	 * for SHM_HUGETLB, the pages are reserved in the shmget() call so skip
152 	 * reserving here. Note: only for SHM hugetlbfs file, the inode
153 	 * flag S_PRIVATE is set.
154 	 */
155 	if (inode->i_flags & S_PRIVATE)
156 		vm_flags |= VM_NORESERVE;
157 
158 	if (!hugetlb_reserve_pages(inode,
159 				vma->vm_pgoff >> huge_page_order(h),
160 				len >> huge_page_shift(h), vma,
161 				vm_flags))
162 		goto out;
163 
164 	ret = 0;
165 	if (vma->vm_flags & VM_WRITE && inode->i_size < len)
166 		i_size_write(inode, len);
167 out:
168 	inode_unlock(inode);
169 
170 	return ret;
171 }
172 
173 /*
174  * Called under mmap_write_lock(mm).
175  */
176 
177 static unsigned long
178 hugetlb_get_unmapped_area_bottomup(struct file *file, unsigned long addr,
179 		unsigned long len, unsigned long pgoff, unsigned long flags)
180 {
181 	struct hstate *h = hstate_file(file);
182 	struct vm_unmapped_area_info info = {};
183 
184 	info.length = len;
185 	info.low_limit = current->mm->mmap_base;
186 	info.high_limit = arch_get_mmap_end(addr, len, flags);
187 	info.align_mask = PAGE_MASK & ~huge_page_mask(h);
188 	return vm_unmapped_area(&info);
189 }
190 
191 static unsigned long
192 hugetlb_get_unmapped_area_topdown(struct file *file, unsigned long addr,
193 		unsigned long len, unsigned long pgoff, unsigned long flags)
194 {
195 	struct hstate *h = hstate_file(file);
196 	struct vm_unmapped_area_info info = {};
197 
198 	info.flags = VM_UNMAPPED_AREA_TOPDOWN;
199 	info.length = len;
200 	info.low_limit = PAGE_SIZE;
201 	info.high_limit = arch_get_mmap_base(addr, current->mm->mmap_base);
202 	info.align_mask = PAGE_MASK & ~huge_page_mask(h);
203 	addr = vm_unmapped_area(&info);
204 
205 	/*
206 	 * A failed mmap() very likely causes application failure,
207 	 * so fall back to the bottom-up function here. This scenario
208 	 * can happen with large stack limits and large mmap()
209 	 * allocations.
210 	 */
211 	if (unlikely(offset_in_page(addr))) {
212 		VM_BUG_ON(addr != -ENOMEM);
213 		info.flags = 0;
214 		info.low_limit = current->mm->mmap_base;
215 		info.high_limit = arch_get_mmap_end(addr, len, flags);
216 		addr = vm_unmapped_area(&info);
217 	}
218 
219 	return addr;
220 }
221 
222 unsigned long
223 generic_hugetlb_get_unmapped_area(struct file *file, unsigned long addr,
224 				  unsigned long len, unsigned long pgoff,
225 				  unsigned long flags)
226 {
227 	struct mm_struct *mm = current->mm;
228 	struct vm_area_struct *vma, *prev;
229 	struct hstate *h = hstate_file(file);
230 	const unsigned long mmap_end = arch_get_mmap_end(addr, len, flags);
231 
232 	if (len & ~huge_page_mask(h))
233 		return -EINVAL;
234 	if (len > mmap_end - mmap_min_addr)
235 		return -ENOMEM;
236 
237 	if (flags & MAP_FIXED) {
238 		if (prepare_hugepage_range(file, addr, len))
239 			return -EINVAL;
240 		return addr;
241 	}
242 
243 	if (addr) {
244 		addr = ALIGN(addr, huge_page_size(h));
245 		vma = find_vma_prev(mm, addr, &prev);
246 		if (mmap_end - len >= addr && addr >= mmap_min_addr &&
247 		    (!vma || addr + len <= vm_start_gap(vma)) &&
248 		    (!prev || addr >= vm_end_gap(prev)))
249 			return addr;
250 	}
251 
252 	/*
253 	 * Use MMF_TOPDOWN flag as a hint to use topdown routine.
254 	 * If architectures have special needs, they should define their own
255 	 * version of hugetlb_get_unmapped_area.
256 	 */
257 	if (test_bit(MMF_TOPDOWN, &mm->flags))
258 		return hugetlb_get_unmapped_area_topdown(file, addr, len,
259 				pgoff, flags);
260 	return hugetlb_get_unmapped_area_bottomup(file, addr, len,
261 			pgoff, flags);
262 }
263 
264 #ifndef HAVE_ARCH_HUGETLB_UNMAPPED_AREA
265 static unsigned long
266 hugetlb_get_unmapped_area(struct file *file, unsigned long addr,
267 			  unsigned long len, unsigned long pgoff,
268 			  unsigned long flags)
269 {
270 	return generic_hugetlb_get_unmapped_area(file, addr, len, pgoff, flags);
271 }
272 #endif
273 
274 /*
275  * Someone wants to read @bytes from a HWPOISON hugetlb @page from @offset.
276  * Returns the maximum number of bytes one can read without touching the 1st raw
277  * HWPOISON subpage.
278  *
279  * The implementation borrows the iteration logic from copy_page_to_iter*.
280  */
281 static size_t adjust_range_hwpoison(struct page *page, size_t offset, size_t bytes)
282 {
283 	size_t n = 0;
284 	size_t res = 0;
285 
286 	/* First subpage to start the loop. */
287 	page = nth_page(page, offset / PAGE_SIZE);
288 	offset %= PAGE_SIZE;
289 	while (1) {
290 		if (is_raw_hwpoison_page_in_hugepage(page))
291 			break;
292 
293 		/* Safe to read n bytes without touching HWPOISON subpage. */
294 		n = min(bytes, (size_t)PAGE_SIZE - offset);
295 		res += n;
296 		bytes -= n;
297 		if (!bytes || !n)
298 			break;
299 		offset += n;
300 		if (offset == PAGE_SIZE) {
301 			page = nth_page(page, 1);
302 			offset = 0;
303 		}
304 	}
305 
306 	return res;
307 }
308 
309 /*
310  * Support for read() - Find the page attached to f_mapping and copy out the
311  * data. This provides functionality similar to filemap_read().
312  */
313 static ssize_t hugetlbfs_read_iter(struct kiocb *iocb, struct iov_iter *to)
314 {
315 	struct file *file = iocb->ki_filp;
316 	struct hstate *h = hstate_file(file);
317 	struct address_space *mapping = file->f_mapping;
318 	struct inode *inode = mapping->host;
319 	unsigned long index = iocb->ki_pos >> huge_page_shift(h);
320 	unsigned long offset = iocb->ki_pos & ~huge_page_mask(h);
321 	unsigned long end_index;
322 	loff_t isize;
323 	ssize_t retval = 0;
324 
325 	while (iov_iter_count(to)) {
326 		struct folio *folio;
327 		size_t nr, copied, want;
328 
329 		/* nr is the maximum number of bytes to copy from this page */
330 		nr = huge_page_size(h);
331 		isize = i_size_read(inode);
332 		if (!isize)
333 			break;
334 		end_index = (isize - 1) >> huge_page_shift(h);
335 		if (index > end_index)
336 			break;
337 		if (index == end_index) {
338 			nr = ((isize - 1) & ~huge_page_mask(h)) + 1;
339 			if (nr <= offset)
340 				break;
341 		}
342 		nr = nr - offset;
343 
344 		/* Find the folio */
345 		folio = filemap_lock_hugetlb_folio(h, mapping, index);
346 		if (IS_ERR(folio)) {
347 			/*
348 			 * We have a HOLE, zero out the user-buffer for the
349 			 * length of the hole or request.
350 			 */
351 			copied = iov_iter_zero(nr, to);
352 		} else {
353 			folio_unlock(folio);
354 
355 			if (!folio_test_hwpoison(folio))
356 				want = nr;
357 			else {
358 				/*
359 				 * Adjust how many bytes safe to read without
360 				 * touching the 1st raw HWPOISON subpage after
361 				 * offset.
362 				 */
363 				want = adjust_range_hwpoison(&folio->page, offset, nr);
364 				if (want == 0) {
365 					folio_put(folio);
366 					retval = -EIO;
367 					break;
368 				}
369 			}
370 
371 			/*
372 			 * We have the folio, copy it to user space buffer.
373 			 */
374 			copied = copy_folio_to_iter(folio, offset, want, to);
375 			folio_put(folio);
376 		}
377 		offset += copied;
378 		retval += copied;
379 		if (copied != nr && iov_iter_count(to)) {
380 			if (!retval)
381 				retval = -EFAULT;
382 			break;
383 		}
384 		index += offset >> huge_page_shift(h);
385 		offset &= ~huge_page_mask(h);
386 	}
387 	iocb->ki_pos = ((loff_t)index << huge_page_shift(h)) + offset;
388 	return retval;
389 }
390 
391 static int hugetlbfs_write_begin(struct file *file,
392 			struct address_space *mapping,
393 			loff_t pos, unsigned len,
394 			struct folio **foliop, void **fsdata)
395 {
396 	return -EINVAL;
397 }
398 
399 static int hugetlbfs_write_end(struct file *file, struct address_space *mapping,
400 			loff_t pos, unsigned len, unsigned copied,
401 			struct folio *folio, void *fsdata)
402 {
403 	BUG();
404 	return -EINVAL;
405 }
406 
407 static void hugetlb_delete_from_page_cache(struct folio *folio)
408 {
409 	folio_clear_dirty(folio);
410 	folio_clear_uptodate(folio);
411 	filemap_remove_folio(folio);
412 }
413 
414 /*
415  * Called with i_mmap_rwsem held for inode based vma maps.  This makes
416  * sure vma (and vm_mm) will not go away.  We also hold the hugetlb fault
417  * mutex for the page in the mapping.  So, we can not race with page being
418  * faulted into the vma.
419  */
420 static bool hugetlb_vma_maps_page(struct vm_area_struct *vma,
421 				unsigned long addr, struct page *page)
422 {
423 	pte_t *ptep, pte;
424 
425 	ptep = hugetlb_walk(vma, addr, huge_page_size(hstate_vma(vma)));
426 	if (!ptep)
427 		return false;
428 
429 	pte = huge_ptep_get(vma->vm_mm, addr, ptep);
430 	if (huge_pte_none(pte) || !pte_present(pte))
431 		return false;
432 
433 	if (pte_page(pte) == page)
434 		return true;
435 
436 	return false;
437 }
438 
439 /*
440  * Can vma_offset_start/vma_offset_end overflow on 32-bit arches?
441  * No, because the interval tree returns us only those vmas
442  * which overlap the truncated area starting at pgoff,
443  * and no vma on a 32-bit arch can span beyond the 4GB.
444  */
445 static unsigned long vma_offset_start(struct vm_area_struct *vma, pgoff_t start)
446 {
447 	unsigned long offset = 0;
448 
449 	if (vma->vm_pgoff < start)
450 		offset = (start - vma->vm_pgoff) << PAGE_SHIFT;
451 
452 	return vma->vm_start + offset;
453 }
454 
455 static unsigned long vma_offset_end(struct vm_area_struct *vma, pgoff_t end)
456 {
457 	unsigned long t_end;
458 
459 	if (!end)
460 		return vma->vm_end;
461 
462 	t_end = ((end - vma->vm_pgoff) << PAGE_SHIFT) + vma->vm_start;
463 	if (t_end > vma->vm_end)
464 		t_end = vma->vm_end;
465 	return t_end;
466 }
467 
468 /*
469  * Called with hugetlb fault mutex held.  Therefore, no more mappings to
470  * this folio can be created while executing the routine.
471  */
472 static void hugetlb_unmap_file_folio(struct hstate *h,
473 					struct address_space *mapping,
474 					struct folio *folio, pgoff_t index)
475 {
476 	struct rb_root_cached *root = &mapping->i_mmap;
477 	struct hugetlb_vma_lock *vma_lock;
478 	struct page *page = &folio->page;
479 	struct vm_area_struct *vma;
480 	unsigned long v_start;
481 	unsigned long v_end;
482 	pgoff_t start, end;
483 
484 	start = index * pages_per_huge_page(h);
485 	end = (index + 1) * pages_per_huge_page(h);
486 
487 	i_mmap_lock_write(mapping);
488 retry:
489 	vma_lock = NULL;
490 	vma_interval_tree_foreach(vma, root, start, end - 1) {
491 		v_start = vma_offset_start(vma, start);
492 		v_end = vma_offset_end(vma, end);
493 
494 		if (!hugetlb_vma_maps_page(vma, v_start, page))
495 			continue;
496 
497 		if (!hugetlb_vma_trylock_write(vma)) {
498 			vma_lock = vma->vm_private_data;
499 			/*
500 			 * If we can not get vma lock, we need to drop
501 			 * immap_sema and take locks in order.  First,
502 			 * take a ref on the vma_lock structure so that
503 			 * we can be guaranteed it will not go away when
504 			 * dropping immap_sema.
505 			 */
506 			kref_get(&vma_lock->refs);
507 			break;
508 		}
509 
510 		unmap_hugepage_range(vma, v_start, v_end, NULL,
511 				     ZAP_FLAG_DROP_MARKER);
512 		hugetlb_vma_unlock_write(vma);
513 	}
514 
515 	i_mmap_unlock_write(mapping);
516 
517 	if (vma_lock) {
518 		/*
519 		 * Wait on vma_lock.  We know it is still valid as we have
520 		 * a reference.  We must 'open code' vma locking as we do
521 		 * not know if vma_lock is still attached to vma.
522 		 */
523 		down_write(&vma_lock->rw_sema);
524 		i_mmap_lock_write(mapping);
525 
526 		vma = vma_lock->vma;
527 		if (!vma) {
528 			/*
529 			 * If lock is no longer attached to vma, then just
530 			 * unlock, drop our reference and retry looking for
531 			 * other vmas.
532 			 */
533 			up_write(&vma_lock->rw_sema);
534 			kref_put(&vma_lock->refs, hugetlb_vma_lock_release);
535 			goto retry;
536 		}
537 
538 		/*
539 		 * vma_lock is still attached to vma.  Check to see if vma
540 		 * still maps page and if so, unmap.
541 		 */
542 		v_start = vma_offset_start(vma, start);
543 		v_end = vma_offset_end(vma, end);
544 		if (hugetlb_vma_maps_page(vma, v_start, page))
545 			unmap_hugepage_range(vma, v_start, v_end, NULL,
546 					     ZAP_FLAG_DROP_MARKER);
547 
548 		kref_put(&vma_lock->refs, hugetlb_vma_lock_release);
549 		hugetlb_vma_unlock_write(vma);
550 
551 		goto retry;
552 	}
553 }
554 
555 static void
556 hugetlb_vmdelete_list(struct rb_root_cached *root, pgoff_t start, pgoff_t end,
557 		      zap_flags_t zap_flags)
558 {
559 	struct vm_area_struct *vma;
560 
561 	/*
562 	 * end == 0 indicates that the entire range after start should be
563 	 * unmapped.  Note, end is exclusive, whereas the interval tree takes
564 	 * an inclusive "last".
565 	 */
566 	vma_interval_tree_foreach(vma, root, start, end ? end - 1 : ULONG_MAX) {
567 		unsigned long v_start;
568 		unsigned long v_end;
569 
570 		if (!hugetlb_vma_trylock_write(vma))
571 			continue;
572 
573 		v_start = vma_offset_start(vma, start);
574 		v_end = vma_offset_end(vma, end);
575 
576 		unmap_hugepage_range(vma, v_start, v_end, NULL, zap_flags);
577 
578 		/*
579 		 * Note that vma lock only exists for shared/non-private
580 		 * vmas.  Therefore, lock is not held when calling
581 		 * unmap_hugepage_range for private vmas.
582 		 */
583 		hugetlb_vma_unlock_write(vma);
584 	}
585 }
586 
587 /*
588  * Called with hugetlb fault mutex held.
589  * Returns true if page was actually removed, false otherwise.
590  */
591 static bool remove_inode_single_folio(struct hstate *h, struct inode *inode,
592 					struct address_space *mapping,
593 					struct folio *folio, pgoff_t index,
594 					bool truncate_op)
595 {
596 	bool ret = false;
597 
598 	/*
599 	 * If folio is mapped, it was faulted in after being
600 	 * unmapped in caller.  Unmap (again) while holding
601 	 * the fault mutex.  The mutex will prevent faults
602 	 * until we finish removing the folio.
603 	 */
604 	if (unlikely(folio_mapped(folio)))
605 		hugetlb_unmap_file_folio(h, mapping, folio, index);
606 
607 	folio_lock(folio);
608 	/*
609 	 * We must remove the folio from page cache before removing
610 	 * the region/ reserve map (hugetlb_unreserve_pages).  In
611 	 * rare out of memory conditions, removal of the region/reserve
612 	 * map could fail.  Correspondingly, the subpool and global
613 	 * reserve usage count can need to be adjusted.
614 	 */
615 	VM_BUG_ON_FOLIO(folio_test_hugetlb_restore_reserve(folio), folio);
616 	hugetlb_delete_from_page_cache(folio);
617 	ret = true;
618 	if (!truncate_op) {
619 		if (unlikely(hugetlb_unreserve_pages(inode, index,
620 							index + 1, 1)))
621 			hugetlb_fix_reserve_counts(inode);
622 	}
623 
624 	folio_unlock(folio);
625 	return ret;
626 }
627 
628 /*
629  * remove_inode_hugepages handles two distinct cases: truncation and hole
630  * punch.  There are subtle differences in operation for each case.
631  *
632  * truncation is indicated by end of range being LLONG_MAX
633  *	In this case, we first scan the range and release found pages.
634  *	After releasing pages, hugetlb_unreserve_pages cleans up region/reserve
635  *	maps and global counts.  Page faults can race with truncation.
636  *	During faults, hugetlb_no_page() checks i_size before page allocation,
637  *	and again after obtaining page table lock.  It will 'back out'
638  *	allocations in the truncated range.
639  * hole punch is indicated if end is not LLONG_MAX
640  *	In the hole punch case we scan the range and release found pages.
641  *	Only when releasing a page is the associated region/reserve map
642  *	deleted.  The region/reserve map for ranges without associated
643  *	pages are not modified.  Page faults can race with hole punch.
644  *	This is indicated if we find a mapped page.
645  * Note: If the passed end of range value is beyond the end of file, but
646  * not LLONG_MAX this routine still performs a hole punch operation.
647  */
648 static void remove_inode_hugepages(struct inode *inode, loff_t lstart,
649 				   loff_t lend)
650 {
651 	struct hstate *h = hstate_inode(inode);
652 	struct address_space *mapping = &inode->i_data;
653 	const pgoff_t end = lend >> PAGE_SHIFT;
654 	struct folio_batch fbatch;
655 	pgoff_t next, index;
656 	int i, freed = 0;
657 	bool truncate_op = (lend == LLONG_MAX);
658 
659 	folio_batch_init(&fbatch);
660 	next = lstart >> PAGE_SHIFT;
661 	while (filemap_get_folios(mapping, &next, end - 1, &fbatch)) {
662 		for (i = 0; i < folio_batch_count(&fbatch); ++i) {
663 			struct folio *folio = fbatch.folios[i];
664 			u32 hash = 0;
665 
666 			index = folio->index >> huge_page_order(h);
667 			hash = hugetlb_fault_mutex_hash(mapping, index);
668 			mutex_lock(&hugetlb_fault_mutex_table[hash]);
669 
670 			/*
671 			 * Remove folio that was part of folio_batch.
672 			 */
673 			if (remove_inode_single_folio(h, inode, mapping, folio,
674 							index, truncate_op))
675 				freed++;
676 
677 			mutex_unlock(&hugetlb_fault_mutex_table[hash]);
678 		}
679 		folio_batch_release(&fbatch);
680 		cond_resched();
681 	}
682 
683 	if (truncate_op)
684 		(void)hugetlb_unreserve_pages(inode,
685 				lstart >> huge_page_shift(h),
686 				LONG_MAX, freed);
687 }
688 
689 static void hugetlbfs_evict_inode(struct inode *inode)
690 {
691 	struct resv_map *resv_map;
692 
693 	trace_hugetlbfs_evict_inode(inode);
694 	remove_inode_hugepages(inode, 0, LLONG_MAX);
695 
696 	/*
697 	 * Get the resv_map from the address space embedded in the inode.
698 	 * This is the address space which points to any resv_map allocated
699 	 * at inode creation time.  If this is a device special inode,
700 	 * i_mapping may not point to the original address space.
701 	 */
702 	resv_map = (struct resv_map *)(&inode->i_data)->i_private_data;
703 	/* Only regular and link inodes have associated reserve maps */
704 	if (resv_map)
705 		resv_map_release(&resv_map->refs);
706 	clear_inode(inode);
707 }
708 
709 static void hugetlb_vmtruncate(struct inode *inode, loff_t offset)
710 {
711 	pgoff_t pgoff;
712 	struct address_space *mapping = inode->i_mapping;
713 	struct hstate *h = hstate_inode(inode);
714 
715 	BUG_ON(offset & ~huge_page_mask(h));
716 	pgoff = offset >> PAGE_SHIFT;
717 
718 	i_size_write(inode, offset);
719 	i_mmap_lock_write(mapping);
720 	if (!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root))
721 		hugetlb_vmdelete_list(&mapping->i_mmap, pgoff, 0,
722 				      ZAP_FLAG_DROP_MARKER);
723 	i_mmap_unlock_write(mapping);
724 	remove_inode_hugepages(inode, offset, LLONG_MAX);
725 }
726 
727 static void hugetlbfs_zero_partial_page(struct hstate *h,
728 					struct address_space *mapping,
729 					loff_t start,
730 					loff_t end)
731 {
732 	pgoff_t idx = start >> huge_page_shift(h);
733 	struct folio *folio;
734 
735 	folio = filemap_lock_hugetlb_folio(h, mapping, idx);
736 	if (IS_ERR(folio))
737 		return;
738 
739 	start = start & ~huge_page_mask(h);
740 	end = end & ~huge_page_mask(h);
741 	if (!end)
742 		end = huge_page_size(h);
743 
744 	folio_zero_segment(folio, (size_t)start, (size_t)end);
745 
746 	folio_unlock(folio);
747 	folio_put(folio);
748 }
749 
750 static long hugetlbfs_punch_hole(struct inode *inode, loff_t offset, loff_t len)
751 {
752 	struct hugetlbfs_inode_info *info = HUGETLBFS_I(inode);
753 	struct address_space *mapping = inode->i_mapping;
754 	struct hstate *h = hstate_inode(inode);
755 	loff_t hpage_size = huge_page_size(h);
756 	loff_t hole_start, hole_end;
757 
758 	/*
759 	 * hole_start and hole_end indicate the full pages within the hole.
760 	 */
761 	hole_start = round_up(offset, hpage_size);
762 	hole_end = round_down(offset + len, hpage_size);
763 
764 	inode_lock(inode);
765 
766 	/* protected by i_rwsem */
767 	if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) {
768 		inode_unlock(inode);
769 		return -EPERM;
770 	}
771 
772 	i_mmap_lock_write(mapping);
773 
774 	/* If range starts before first full page, zero partial page. */
775 	if (offset < hole_start)
776 		hugetlbfs_zero_partial_page(h, mapping,
777 				offset, min(offset + len, hole_start));
778 
779 	/* Unmap users of full pages in the hole. */
780 	if (hole_end > hole_start) {
781 		if (!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root))
782 			hugetlb_vmdelete_list(&mapping->i_mmap,
783 					      hole_start >> PAGE_SHIFT,
784 					      hole_end >> PAGE_SHIFT, 0);
785 	}
786 
787 	/* If range extends beyond last full page, zero partial page. */
788 	if ((offset + len) > hole_end && (offset + len) > hole_start)
789 		hugetlbfs_zero_partial_page(h, mapping,
790 				hole_end, offset + len);
791 
792 	i_mmap_unlock_write(mapping);
793 
794 	/* Remove full pages from the file. */
795 	if (hole_end > hole_start)
796 		remove_inode_hugepages(inode, hole_start, hole_end);
797 
798 	inode_unlock(inode);
799 
800 	return 0;
801 }
802 
803 static long hugetlbfs_fallocate(struct file *file, int mode, loff_t offset,
804 				loff_t len)
805 {
806 	struct inode *inode = file_inode(file);
807 	struct hugetlbfs_inode_info *info = HUGETLBFS_I(inode);
808 	struct address_space *mapping = inode->i_mapping;
809 	struct hstate *h = hstate_inode(inode);
810 	struct vm_area_struct pseudo_vma;
811 	struct mm_struct *mm = current->mm;
812 	loff_t hpage_size = huge_page_size(h);
813 	unsigned long hpage_shift = huge_page_shift(h);
814 	pgoff_t start, index, end;
815 	int error;
816 	u32 hash;
817 
818 	if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
819 		return -EOPNOTSUPP;
820 
821 	if (mode & FALLOC_FL_PUNCH_HOLE) {
822 		error = hugetlbfs_punch_hole(inode, offset, len);
823 		goto out_nolock;
824 	}
825 
826 	/*
827 	 * Default preallocate case.
828 	 * For this range, start is rounded down and end is rounded up
829 	 * as well as being converted to page offsets.
830 	 */
831 	start = offset >> hpage_shift;
832 	end = (offset + len + hpage_size - 1) >> hpage_shift;
833 
834 	inode_lock(inode);
835 
836 	/* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
837 	error = inode_newsize_ok(inode, offset + len);
838 	if (error)
839 		goto out;
840 
841 	if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) {
842 		error = -EPERM;
843 		goto out;
844 	}
845 
846 	/*
847 	 * Initialize a pseudo vma as this is required by the huge page
848 	 * allocation routines.
849 	 */
850 	vma_init(&pseudo_vma, mm);
851 	vm_flags_init(&pseudo_vma, VM_HUGETLB | VM_MAYSHARE | VM_SHARED);
852 	pseudo_vma.vm_file = file;
853 
854 	for (index = start; index < end; index++) {
855 		/*
856 		 * This is supposed to be the vaddr where the page is being
857 		 * faulted in, but we have no vaddr here.
858 		 */
859 		struct folio *folio;
860 		unsigned long addr;
861 
862 		cond_resched();
863 
864 		/*
865 		 * fallocate(2) manpage permits EINTR; we may have been
866 		 * interrupted because we are using up too much memory.
867 		 */
868 		if (signal_pending(current)) {
869 			error = -EINTR;
870 			break;
871 		}
872 
873 		/* addr is the offset within the file (zero based) */
874 		addr = index * hpage_size;
875 
876 		/* mutex taken here, fault path and hole punch */
877 		hash = hugetlb_fault_mutex_hash(mapping, index);
878 		mutex_lock(&hugetlb_fault_mutex_table[hash]);
879 
880 		/* See if already present in mapping to avoid alloc/free */
881 		folio = filemap_get_folio(mapping, index << huge_page_order(h));
882 		if (!IS_ERR(folio)) {
883 			folio_put(folio);
884 			mutex_unlock(&hugetlb_fault_mutex_table[hash]);
885 			continue;
886 		}
887 
888 		/*
889 		 * Allocate folio without setting the avoid_reserve argument.
890 		 * There certainly are no reserves associated with the
891 		 * pseudo_vma.  However, there could be shared mappings with
892 		 * reserves for the file at the inode level.  If we fallocate
893 		 * folios in these areas, we need to consume the reserves
894 		 * to keep reservation accounting consistent.
895 		 */
896 		folio = alloc_hugetlb_folio(&pseudo_vma, addr, 0);
897 		if (IS_ERR(folio)) {
898 			mutex_unlock(&hugetlb_fault_mutex_table[hash]);
899 			error = PTR_ERR(folio);
900 			goto out;
901 		}
902 		folio_zero_user(folio, ALIGN_DOWN(addr, hpage_size));
903 		__folio_mark_uptodate(folio);
904 		error = hugetlb_add_to_page_cache(folio, mapping, index);
905 		if (unlikely(error)) {
906 			restore_reserve_on_error(h, &pseudo_vma, addr, folio);
907 			folio_put(folio);
908 			mutex_unlock(&hugetlb_fault_mutex_table[hash]);
909 			goto out;
910 		}
911 
912 		mutex_unlock(&hugetlb_fault_mutex_table[hash]);
913 
914 		folio_set_hugetlb_migratable(folio);
915 		/*
916 		 * folio_unlock because locked by hugetlb_add_to_page_cache()
917 		 * folio_put() due to reference from alloc_hugetlb_folio()
918 		 */
919 		folio_unlock(folio);
920 		folio_put(folio);
921 	}
922 
923 	if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size)
924 		i_size_write(inode, offset + len);
925 	inode_set_ctime_current(inode);
926 out:
927 	inode_unlock(inode);
928 
929 out_nolock:
930 	trace_hugetlbfs_fallocate(inode, mode, offset, len, error);
931 	return error;
932 }
933 
934 static int hugetlbfs_setattr(struct mnt_idmap *idmap,
935 			     struct dentry *dentry, struct iattr *attr)
936 {
937 	struct inode *inode = d_inode(dentry);
938 	struct hstate *h = hstate_inode(inode);
939 	int error;
940 	unsigned int ia_valid = attr->ia_valid;
941 	struct hugetlbfs_inode_info *info = HUGETLBFS_I(inode);
942 
943 	error = setattr_prepare(idmap, dentry, attr);
944 	if (error)
945 		return error;
946 
947 	trace_hugetlbfs_setattr(inode, dentry, attr);
948 
949 	if (ia_valid & ATTR_SIZE) {
950 		loff_t oldsize = inode->i_size;
951 		loff_t newsize = attr->ia_size;
952 
953 		if (newsize & ~huge_page_mask(h))
954 			return -EINVAL;
955 		/* protected by i_rwsem */
956 		if ((newsize < oldsize && (info->seals & F_SEAL_SHRINK)) ||
957 		    (newsize > oldsize && (info->seals & F_SEAL_GROW)))
958 			return -EPERM;
959 		hugetlb_vmtruncate(inode, newsize);
960 	}
961 
962 	setattr_copy(idmap, inode, attr);
963 	mark_inode_dirty(inode);
964 	return 0;
965 }
966 
967 static struct inode *hugetlbfs_get_root(struct super_block *sb,
968 					struct hugetlbfs_fs_context *ctx)
969 {
970 	struct inode *inode;
971 
972 	inode = new_inode(sb);
973 	if (inode) {
974 		inode->i_ino = get_next_ino();
975 		inode->i_mode = S_IFDIR | ctx->mode;
976 		inode->i_uid = ctx->uid;
977 		inode->i_gid = ctx->gid;
978 		simple_inode_init_ts(inode);
979 		inode->i_op = &hugetlbfs_dir_inode_operations;
980 		inode->i_fop = &simple_dir_operations;
981 		/* directory inodes start off with i_nlink == 2 (for "." entry) */
982 		inc_nlink(inode);
983 		lockdep_annotate_inode_mutex_key(inode);
984 	}
985 	return inode;
986 }
987 
988 /*
989  * Hugetlbfs is not reclaimable; therefore its i_mmap_rwsem will never
990  * be taken from reclaim -- unlike regular filesystems. This needs an
991  * annotation because huge_pmd_share() does an allocation under hugetlb's
992  * i_mmap_rwsem.
993  */
994 static struct lock_class_key hugetlbfs_i_mmap_rwsem_key;
995 
996 static struct inode *hugetlbfs_get_inode(struct super_block *sb,
997 					struct mnt_idmap *idmap,
998 					struct inode *dir,
999 					umode_t mode, dev_t dev)
1000 {
1001 	struct inode *inode;
1002 	struct resv_map *resv_map = NULL;
1003 
1004 	/*
1005 	 * Reserve maps are only needed for inodes that can have associated
1006 	 * page allocations.
1007 	 */
1008 	if (S_ISREG(mode) || S_ISLNK(mode)) {
1009 		resv_map = resv_map_alloc();
1010 		if (!resv_map)
1011 			return NULL;
1012 	}
1013 
1014 	inode = new_inode(sb);
1015 	if (inode) {
1016 		struct hugetlbfs_inode_info *info = HUGETLBFS_I(inode);
1017 
1018 		inode->i_ino = get_next_ino();
1019 		inode_init_owner(idmap, inode, dir, mode);
1020 		lockdep_set_class(&inode->i_mapping->i_mmap_rwsem,
1021 				&hugetlbfs_i_mmap_rwsem_key);
1022 		inode->i_mapping->a_ops = &hugetlbfs_aops;
1023 		simple_inode_init_ts(inode);
1024 		inode->i_mapping->i_private_data = resv_map;
1025 		info->seals = F_SEAL_SEAL;
1026 		switch (mode & S_IFMT) {
1027 		default:
1028 			init_special_inode(inode, mode, dev);
1029 			break;
1030 		case S_IFREG:
1031 			inode->i_op = &hugetlbfs_inode_operations;
1032 			inode->i_fop = &hugetlbfs_file_operations;
1033 			break;
1034 		case S_IFDIR:
1035 			inode->i_op = &hugetlbfs_dir_inode_operations;
1036 			inode->i_fop = &simple_dir_operations;
1037 
1038 			/* directory inodes start off with i_nlink == 2 (for "." entry) */
1039 			inc_nlink(inode);
1040 			break;
1041 		case S_IFLNK:
1042 			inode->i_op = &page_symlink_inode_operations;
1043 			inode_nohighmem(inode);
1044 			break;
1045 		}
1046 		lockdep_annotate_inode_mutex_key(inode);
1047 		trace_hugetlbfs_alloc_inode(inode, dir, mode);
1048 	} else {
1049 		if (resv_map)
1050 			kref_put(&resv_map->refs, resv_map_release);
1051 	}
1052 
1053 	return inode;
1054 }
1055 
1056 /*
1057  * File creation. Allocate an inode, and we're done..
1058  */
1059 static int hugetlbfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
1060 			   struct dentry *dentry, umode_t mode, dev_t dev)
1061 {
1062 	struct inode *inode;
1063 
1064 	inode = hugetlbfs_get_inode(dir->i_sb, idmap, dir, mode, dev);
1065 	if (!inode)
1066 		return -ENOSPC;
1067 	inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir));
1068 	d_instantiate(dentry, inode);
1069 	dget(dentry);/* Extra count - pin the dentry in core */
1070 	return 0;
1071 }
1072 
1073 static int hugetlbfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
1074 			   struct dentry *dentry, umode_t mode)
1075 {
1076 	int retval = hugetlbfs_mknod(idmap, dir, dentry,
1077 				     mode | S_IFDIR, 0);
1078 	if (!retval)
1079 		inc_nlink(dir);
1080 	return retval;
1081 }
1082 
1083 static int hugetlbfs_create(struct mnt_idmap *idmap,
1084 			    struct inode *dir, struct dentry *dentry,
1085 			    umode_t mode, bool excl)
1086 {
1087 	return hugetlbfs_mknod(idmap, dir, dentry, mode | S_IFREG, 0);
1088 }
1089 
1090 static int hugetlbfs_tmpfile(struct mnt_idmap *idmap,
1091 			     struct inode *dir, struct file *file,
1092 			     umode_t mode)
1093 {
1094 	struct inode *inode;
1095 
1096 	inode = hugetlbfs_get_inode(dir->i_sb, idmap, dir, mode | S_IFREG, 0);
1097 	if (!inode)
1098 		return -ENOSPC;
1099 	inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir));
1100 	d_tmpfile(file, inode);
1101 	return finish_open_simple(file, 0);
1102 }
1103 
1104 static int hugetlbfs_symlink(struct mnt_idmap *idmap,
1105 			     struct inode *dir, struct dentry *dentry,
1106 			     const char *symname)
1107 {
1108 	const umode_t mode = S_IFLNK|S_IRWXUGO;
1109 	struct inode *inode;
1110 	int error = -ENOSPC;
1111 
1112 	inode = hugetlbfs_get_inode(dir->i_sb, idmap, dir, mode, 0);
1113 	if (inode) {
1114 		int l = strlen(symname)+1;
1115 		error = page_symlink(inode, symname, l);
1116 		if (!error) {
1117 			d_instantiate(dentry, inode);
1118 			dget(dentry);
1119 		} else
1120 			iput(inode);
1121 	}
1122 	inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir));
1123 
1124 	return error;
1125 }
1126 
1127 #ifdef CONFIG_MIGRATION
1128 static int hugetlbfs_migrate_folio(struct address_space *mapping,
1129 				struct folio *dst, struct folio *src,
1130 				enum migrate_mode mode)
1131 {
1132 	int rc;
1133 
1134 	rc = migrate_huge_page_move_mapping(mapping, dst, src);
1135 	if (rc != MIGRATEPAGE_SUCCESS)
1136 		return rc;
1137 
1138 	if (hugetlb_folio_subpool(src)) {
1139 		hugetlb_set_folio_subpool(dst,
1140 					hugetlb_folio_subpool(src));
1141 		hugetlb_set_folio_subpool(src, NULL);
1142 	}
1143 
1144 	folio_migrate_flags(dst, src);
1145 
1146 	return MIGRATEPAGE_SUCCESS;
1147 }
1148 #else
1149 #define hugetlbfs_migrate_folio NULL
1150 #endif
1151 
1152 static int hugetlbfs_error_remove_folio(struct address_space *mapping,
1153 				struct folio *folio)
1154 {
1155 	return 0;
1156 }
1157 
1158 /*
1159  * Display the mount options in /proc/mounts.
1160  */
1161 static int hugetlbfs_show_options(struct seq_file *m, struct dentry *root)
1162 {
1163 	struct hugetlbfs_sb_info *sbinfo = HUGETLBFS_SB(root->d_sb);
1164 	struct hugepage_subpool *spool = sbinfo->spool;
1165 	unsigned long hpage_size = huge_page_size(sbinfo->hstate);
1166 	unsigned hpage_shift = huge_page_shift(sbinfo->hstate);
1167 	char mod;
1168 
1169 	if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID))
1170 		seq_printf(m, ",uid=%u",
1171 			   from_kuid_munged(&init_user_ns, sbinfo->uid));
1172 	if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID))
1173 		seq_printf(m, ",gid=%u",
1174 			   from_kgid_munged(&init_user_ns, sbinfo->gid));
1175 	if (sbinfo->mode != 0755)
1176 		seq_printf(m, ",mode=%o", sbinfo->mode);
1177 	if (sbinfo->max_inodes != -1)
1178 		seq_printf(m, ",nr_inodes=%lu", sbinfo->max_inodes);
1179 
1180 	hpage_size /= 1024;
1181 	mod = 'K';
1182 	if (hpage_size >= 1024) {
1183 		hpage_size /= 1024;
1184 		mod = 'M';
1185 	}
1186 	seq_printf(m, ",pagesize=%lu%c", hpage_size, mod);
1187 	if (spool) {
1188 		if (spool->max_hpages != -1)
1189 			seq_printf(m, ",size=%llu",
1190 				   (unsigned long long)spool->max_hpages << hpage_shift);
1191 		if (spool->min_hpages != -1)
1192 			seq_printf(m, ",min_size=%llu",
1193 				   (unsigned long long)spool->min_hpages << hpage_shift);
1194 	}
1195 	return 0;
1196 }
1197 
1198 static int hugetlbfs_statfs(struct dentry *dentry, struct kstatfs *buf)
1199 {
1200 	struct hugetlbfs_sb_info *sbinfo = HUGETLBFS_SB(dentry->d_sb);
1201 	struct hstate *h = hstate_inode(d_inode(dentry));
1202 	u64 id = huge_encode_dev(dentry->d_sb->s_dev);
1203 
1204 	buf->f_fsid = u64_to_fsid(id);
1205 	buf->f_type = HUGETLBFS_MAGIC;
1206 	buf->f_bsize = huge_page_size(h);
1207 	if (sbinfo) {
1208 		spin_lock(&sbinfo->stat_lock);
1209 		/* If no limits set, just report 0 or -1 for max/free/used
1210 		 * blocks, like simple_statfs() */
1211 		if (sbinfo->spool) {
1212 			long free_pages;
1213 
1214 			spin_lock_irq(&sbinfo->spool->lock);
1215 			buf->f_blocks = sbinfo->spool->max_hpages;
1216 			free_pages = sbinfo->spool->max_hpages
1217 				- sbinfo->spool->used_hpages;
1218 			buf->f_bavail = buf->f_bfree = free_pages;
1219 			spin_unlock_irq(&sbinfo->spool->lock);
1220 			buf->f_files = sbinfo->max_inodes;
1221 			buf->f_ffree = sbinfo->free_inodes;
1222 		}
1223 		spin_unlock(&sbinfo->stat_lock);
1224 	}
1225 	buf->f_namelen = NAME_MAX;
1226 	return 0;
1227 }
1228 
1229 static void hugetlbfs_put_super(struct super_block *sb)
1230 {
1231 	struct hugetlbfs_sb_info *sbi = HUGETLBFS_SB(sb);
1232 
1233 	if (sbi) {
1234 		sb->s_fs_info = NULL;
1235 
1236 		if (sbi->spool)
1237 			hugepage_put_subpool(sbi->spool);
1238 
1239 		kfree(sbi);
1240 	}
1241 }
1242 
1243 static inline int hugetlbfs_dec_free_inodes(struct hugetlbfs_sb_info *sbinfo)
1244 {
1245 	if (sbinfo->free_inodes >= 0) {
1246 		spin_lock(&sbinfo->stat_lock);
1247 		if (unlikely(!sbinfo->free_inodes)) {
1248 			spin_unlock(&sbinfo->stat_lock);
1249 			return 0;
1250 		}
1251 		sbinfo->free_inodes--;
1252 		spin_unlock(&sbinfo->stat_lock);
1253 	}
1254 
1255 	return 1;
1256 }
1257 
1258 static void hugetlbfs_inc_free_inodes(struct hugetlbfs_sb_info *sbinfo)
1259 {
1260 	if (sbinfo->free_inodes >= 0) {
1261 		spin_lock(&sbinfo->stat_lock);
1262 		sbinfo->free_inodes++;
1263 		spin_unlock(&sbinfo->stat_lock);
1264 	}
1265 }
1266 
1267 
1268 static struct kmem_cache *hugetlbfs_inode_cachep;
1269 
1270 static struct inode *hugetlbfs_alloc_inode(struct super_block *sb)
1271 {
1272 	struct hugetlbfs_sb_info *sbinfo = HUGETLBFS_SB(sb);
1273 	struct hugetlbfs_inode_info *p;
1274 
1275 	if (unlikely(!hugetlbfs_dec_free_inodes(sbinfo)))
1276 		return NULL;
1277 	p = alloc_inode_sb(sb, hugetlbfs_inode_cachep, GFP_KERNEL);
1278 	if (unlikely(!p)) {
1279 		hugetlbfs_inc_free_inodes(sbinfo);
1280 		return NULL;
1281 	}
1282 	return &p->vfs_inode;
1283 }
1284 
1285 static void hugetlbfs_free_inode(struct inode *inode)
1286 {
1287 	trace_hugetlbfs_free_inode(inode);
1288 	kmem_cache_free(hugetlbfs_inode_cachep, HUGETLBFS_I(inode));
1289 }
1290 
1291 static void hugetlbfs_destroy_inode(struct inode *inode)
1292 {
1293 	hugetlbfs_inc_free_inodes(HUGETLBFS_SB(inode->i_sb));
1294 }
1295 
1296 static const struct address_space_operations hugetlbfs_aops = {
1297 	.write_begin	= hugetlbfs_write_begin,
1298 	.write_end	= hugetlbfs_write_end,
1299 	.dirty_folio	= noop_dirty_folio,
1300 	.migrate_folio  = hugetlbfs_migrate_folio,
1301 	.error_remove_folio	= hugetlbfs_error_remove_folio,
1302 };
1303 
1304 
1305 static void init_once(void *foo)
1306 {
1307 	struct hugetlbfs_inode_info *ei = foo;
1308 
1309 	inode_init_once(&ei->vfs_inode);
1310 }
1311 
1312 static const struct file_operations hugetlbfs_file_operations = {
1313 	.read_iter		= hugetlbfs_read_iter,
1314 	.mmap			= hugetlbfs_file_mmap,
1315 	.fsync			= noop_fsync,
1316 	.get_unmapped_area	= hugetlb_get_unmapped_area,
1317 	.llseek			= default_llseek,
1318 	.fallocate		= hugetlbfs_fallocate,
1319 	.fop_flags		= FOP_HUGE_PAGES,
1320 };
1321 
1322 static const struct inode_operations hugetlbfs_dir_inode_operations = {
1323 	.create		= hugetlbfs_create,
1324 	.lookup		= simple_lookup,
1325 	.link		= simple_link,
1326 	.unlink		= simple_unlink,
1327 	.symlink	= hugetlbfs_symlink,
1328 	.mkdir		= hugetlbfs_mkdir,
1329 	.rmdir		= simple_rmdir,
1330 	.mknod		= hugetlbfs_mknod,
1331 	.rename		= simple_rename,
1332 	.setattr	= hugetlbfs_setattr,
1333 	.tmpfile	= hugetlbfs_tmpfile,
1334 };
1335 
1336 static const struct inode_operations hugetlbfs_inode_operations = {
1337 	.setattr	= hugetlbfs_setattr,
1338 };
1339 
1340 static const struct super_operations hugetlbfs_ops = {
1341 	.alloc_inode    = hugetlbfs_alloc_inode,
1342 	.free_inode     = hugetlbfs_free_inode,
1343 	.destroy_inode  = hugetlbfs_destroy_inode,
1344 	.evict_inode	= hugetlbfs_evict_inode,
1345 	.statfs		= hugetlbfs_statfs,
1346 	.put_super	= hugetlbfs_put_super,
1347 	.show_options	= hugetlbfs_show_options,
1348 };
1349 
1350 /*
1351  * Convert size option passed from command line to number of huge pages
1352  * in the pool specified by hstate.  Size option could be in bytes
1353  * (val_type == SIZE_STD) or percentage of the pool (val_type == SIZE_PERCENT).
1354  */
1355 static long
1356 hugetlbfs_size_to_hpages(struct hstate *h, unsigned long long size_opt,
1357 			 enum hugetlbfs_size_type val_type)
1358 {
1359 	if (val_type == NO_SIZE)
1360 		return -1;
1361 
1362 	if (val_type == SIZE_PERCENT) {
1363 		size_opt <<= huge_page_shift(h);
1364 		size_opt *= h->max_huge_pages;
1365 		do_div(size_opt, 100);
1366 	}
1367 
1368 	size_opt >>= huge_page_shift(h);
1369 	return size_opt;
1370 }
1371 
1372 /*
1373  * Parse one mount parameter.
1374  */
1375 static int hugetlbfs_parse_param(struct fs_context *fc, struct fs_parameter *param)
1376 {
1377 	struct hugetlbfs_fs_context *ctx = fc->fs_private;
1378 	struct fs_parse_result result;
1379 	struct hstate *h;
1380 	char *rest;
1381 	unsigned long ps;
1382 	int opt;
1383 
1384 	opt = fs_parse(fc, hugetlb_fs_parameters, param, &result);
1385 	if (opt < 0)
1386 		return opt;
1387 
1388 	switch (opt) {
1389 	case Opt_uid:
1390 		ctx->uid = result.uid;
1391 		return 0;
1392 
1393 	case Opt_gid:
1394 		ctx->gid = result.gid;
1395 		return 0;
1396 
1397 	case Opt_mode:
1398 		ctx->mode = result.uint_32 & 01777U;
1399 		return 0;
1400 
1401 	case Opt_size:
1402 		/* memparse() will accept a K/M/G without a digit */
1403 		if (!param->string || !isdigit(param->string[0]))
1404 			goto bad_val;
1405 		ctx->max_size_opt = memparse(param->string, &rest);
1406 		ctx->max_val_type = SIZE_STD;
1407 		if (*rest == '%')
1408 			ctx->max_val_type = SIZE_PERCENT;
1409 		return 0;
1410 
1411 	case Opt_nr_inodes:
1412 		/* memparse() will accept a K/M/G without a digit */
1413 		if (!param->string || !isdigit(param->string[0]))
1414 			goto bad_val;
1415 		ctx->nr_inodes = memparse(param->string, &rest);
1416 		return 0;
1417 
1418 	case Opt_pagesize:
1419 		ps = memparse(param->string, &rest);
1420 		h = size_to_hstate(ps);
1421 		if (!h) {
1422 			pr_err("Unsupported page size %lu MB\n", ps / SZ_1M);
1423 			return -EINVAL;
1424 		}
1425 		ctx->hstate = h;
1426 		return 0;
1427 
1428 	case Opt_min_size:
1429 		/* memparse() will accept a K/M/G without a digit */
1430 		if (!param->string || !isdigit(param->string[0]))
1431 			goto bad_val;
1432 		ctx->min_size_opt = memparse(param->string, &rest);
1433 		ctx->min_val_type = SIZE_STD;
1434 		if (*rest == '%')
1435 			ctx->min_val_type = SIZE_PERCENT;
1436 		return 0;
1437 
1438 	default:
1439 		return -EINVAL;
1440 	}
1441 
1442 bad_val:
1443 	return invalfc(fc, "Bad value '%s' for mount option '%s'\n",
1444 		      param->string, param->key);
1445 }
1446 
1447 /*
1448  * Validate the parsed options.
1449  */
1450 static int hugetlbfs_validate(struct fs_context *fc)
1451 {
1452 	struct hugetlbfs_fs_context *ctx = fc->fs_private;
1453 
1454 	/*
1455 	 * Use huge page pool size (in hstate) to convert the size
1456 	 * options to number of huge pages.  If NO_SIZE, -1 is returned.
1457 	 */
1458 	ctx->max_hpages = hugetlbfs_size_to_hpages(ctx->hstate,
1459 						   ctx->max_size_opt,
1460 						   ctx->max_val_type);
1461 	ctx->min_hpages = hugetlbfs_size_to_hpages(ctx->hstate,
1462 						   ctx->min_size_opt,
1463 						   ctx->min_val_type);
1464 
1465 	/*
1466 	 * If max_size was specified, then min_size must be smaller
1467 	 */
1468 	if (ctx->max_val_type > NO_SIZE &&
1469 	    ctx->min_hpages > ctx->max_hpages) {
1470 		pr_err("Minimum size can not be greater than maximum size\n");
1471 		return -EINVAL;
1472 	}
1473 
1474 	return 0;
1475 }
1476 
1477 static int
1478 hugetlbfs_fill_super(struct super_block *sb, struct fs_context *fc)
1479 {
1480 	struct hugetlbfs_fs_context *ctx = fc->fs_private;
1481 	struct hugetlbfs_sb_info *sbinfo;
1482 
1483 	sbinfo = kmalloc(sizeof(struct hugetlbfs_sb_info), GFP_KERNEL);
1484 	if (!sbinfo)
1485 		return -ENOMEM;
1486 	sb->s_fs_info = sbinfo;
1487 	spin_lock_init(&sbinfo->stat_lock);
1488 	sbinfo->hstate		= ctx->hstate;
1489 	sbinfo->max_inodes	= ctx->nr_inodes;
1490 	sbinfo->free_inodes	= ctx->nr_inodes;
1491 	sbinfo->spool		= NULL;
1492 	sbinfo->uid		= ctx->uid;
1493 	sbinfo->gid		= ctx->gid;
1494 	sbinfo->mode		= ctx->mode;
1495 
1496 	/*
1497 	 * Allocate and initialize subpool if maximum or minimum size is
1498 	 * specified.  Any needed reservations (for minimum size) are taken
1499 	 * when the subpool is created.
1500 	 */
1501 	if (ctx->max_hpages != -1 || ctx->min_hpages != -1) {
1502 		sbinfo->spool = hugepage_new_subpool(ctx->hstate,
1503 						     ctx->max_hpages,
1504 						     ctx->min_hpages);
1505 		if (!sbinfo->spool)
1506 			goto out_free;
1507 	}
1508 	sb->s_maxbytes = MAX_LFS_FILESIZE;
1509 	sb->s_blocksize = huge_page_size(ctx->hstate);
1510 	sb->s_blocksize_bits = huge_page_shift(ctx->hstate);
1511 	sb->s_magic = HUGETLBFS_MAGIC;
1512 	sb->s_op = &hugetlbfs_ops;
1513 	sb->s_time_gran = 1;
1514 
1515 	/*
1516 	 * Due to the special and limited functionality of hugetlbfs, it does
1517 	 * not work well as a stacking filesystem.
1518 	 */
1519 	sb->s_stack_depth = FILESYSTEM_MAX_STACK_DEPTH;
1520 	sb->s_root = d_make_root(hugetlbfs_get_root(sb, ctx));
1521 	if (!sb->s_root)
1522 		goto out_free;
1523 	return 0;
1524 out_free:
1525 	kfree(sbinfo->spool);
1526 	kfree(sbinfo);
1527 	return -ENOMEM;
1528 }
1529 
1530 static int hugetlbfs_get_tree(struct fs_context *fc)
1531 {
1532 	int err = hugetlbfs_validate(fc);
1533 	if (err)
1534 		return err;
1535 	return get_tree_nodev(fc, hugetlbfs_fill_super);
1536 }
1537 
1538 static void hugetlbfs_fs_context_free(struct fs_context *fc)
1539 {
1540 	kfree(fc->fs_private);
1541 }
1542 
1543 static const struct fs_context_operations hugetlbfs_fs_context_ops = {
1544 	.free		= hugetlbfs_fs_context_free,
1545 	.parse_param	= hugetlbfs_parse_param,
1546 	.get_tree	= hugetlbfs_get_tree,
1547 };
1548 
1549 static int hugetlbfs_init_fs_context(struct fs_context *fc)
1550 {
1551 	struct hugetlbfs_fs_context *ctx;
1552 
1553 	ctx = kzalloc(sizeof(struct hugetlbfs_fs_context), GFP_KERNEL);
1554 	if (!ctx)
1555 		return -ENOMEM;
1556 
1557 	ctx->max_hpages	= -1; /* No limit on size by default */
1558 	ctx->nr_inodes	= -1; /* No limit on number of inodes by default */
1559 	ctx->uid	= current_fsuid();
1560 	ctx->gid	= current_fsgid();
1561 	ctx->mode	= 0755;
1562 	ctx->hstate	= &default_hstate;
1563 	ctx->min_hpages	= -1; /* No default minimum size */
1564 	ctx->max_val_type = NO_SIZE;
1565 	ctx->min_val_type = NO_SIZE;
1566 	fc->fs_private = ctx;
1567 	fc->ops	= &hugetlbfs_fs_context_ops;
1568 	return 0;
1569 }
1570 
1571 static struct file_system_type hugetlbfs_fs_type = {
1572 	.name			= "hugetlbfs",
1573 	.init_fs_context	= hugetlbfs_init_fs_context,
1574 	.parameters		= hugetlb_fs_parameters,
1575 	.kill_sb		= kill_litter_super,
1576 	.fs_flags               = FS_ALLOW_IDMAP,
1577 };
1578 
1579 static struct vfsmount *hugetlbfs_vfsmount[HUGE_MAX_HSTATE];
1580 
1581 static int can_do_hugetlb_shm(void)
1582 {
1583 	kgid_t shm_group;
1584 	shm_group = make_kgid(&init_user_ns, sysctl_hugetlb_shm_group);
1585 	return capable(CAP_IPC_LOCK) || in_group_p(shm_group);
1586 }
1587 
1588 static int get_hstate_idx(int page_size_log)
1589 {
1590 	struct hstate *h = hstate_sizelog(page_size_log);
1591 
1592 	if (!h)
1593 		return -1;
1594 	return hstate_index(h);
1595 }
1596 
1597 /*
1598  * Note that size should be aligned to proper hugepage size in caller side,
1599  * otherwise hugetlb_reserve_pages reserves one less hugepages than intended.
1600  */
1601 struct file *hugetlb_file_setup(const char *name, size_t size,
1602 				vm_flags_t acctflag, int creat_flags,
1603 				int page_size_log)
1604 {
1605 	struct inode *inode;
1606 	struct vfsmount *mnt;
1607 	int hstate_idx;
1608 	struct file *file;
1609 
1610 	hstate_idx = get_hstate_idx(page_size_log);
1611 	if (hstate_idx < 0)
1612 		return ERR_PTR(-ENODEV);
1613 
1614 	mnt = hugetlbfs_vfsmount[hstate_idx];
1615 	if (!mnt)
1616 		return ERR_PTR(-ENOENT);
1617 
1618 	if (creat_flags == HUGETLB_SHMFS_INODE && !can_do_hugetlb_shm()) {
1619 		struct ucounts *ucounts = current_ucounts();
1620 
1621 		if (user_shm_lock(size, ucounts)) {
1622 			pr_warn_once("%s (%d): Using mlock ulimits for SHM_HUGETLB is obsolete\n",
1623 				current->comm, current->pid);
1624 			user_shm_unlock(size, ucounts);
1625 		}
1626 		return ERR_PTR(-EPERM);
1627 	}
1628 
1629 	file = ERR_PTR(-ENOSPC);
1630 	/* hugetlbfs_vfsmount[] mounts do not use idmapped mounts.  */
1631 	inode = hugetlbfs_get_inode(mnt->mnt_sb, &nop_mnt_idmap, NULL,
1632 				    S_IFREG | S_IRWXUGO, 0);
1633 	if (!inode)
1634 		goto out;
1635 	if (creat_flags == HUGETLB_SHMFS_INODE)
1636 		inode->i_flags |= S_PRIVATE;
1637 
1638 	inode->i_size = size;
1639 	clear_nlink(inode);
1640 
1641 	if (!hugetlb_reserve_pages(inode, 0,
1642 			size >> huge_page_shift(hstate_inode(inode)), NULL,
1643 			acctflag))
1644 		file = ERR_PTR(-ENOMEM);
1645 	else
1646 		file = alloc_file_pseudo(inode, mnt, name, O_RDWR,
1647 					&hugetlbfs_file_operations);
1648 	if (!IS_ERR(file))
1649 		return file;
1650 
1651 	iput(inode);
1652 out:
1653 	return file;
1654 }
1655 
1656 static struct vfsmount *__init mount_one_hugetlbfs(struct hstate *h)
1657 {
1658 	struct fs_context *fc;
1659 	struct vfsmount *mnt;
1660 
1661 	fc = fs_context_for_mount(&hugetlbfs_fs_type, SB_KERNMOUNT);
1662 	if (IS_ERR(fc)) {
1663 		mnt = ERR_CAST(fc);
1664 	} else {
1665 		struct hugetlbfs_fs_context *ctx = fc->fs_private;
1666 		ctx->hstate = h;
1667 		mnt = fc_mount(fc);
1668 		put_fs_context(fc);
1669 	}
1670 	if (IS_ERR(mnt))
1671 		pr_err("Cannot mount internal hugetlbfs for page size %luK",
1672 		       huge_page_size(h) / SZ_1K);
1673 	return mnt;
1674 }
1675 
1676 static int __init init_hugetlbfs_fs(void)
1677 {
1678 	struct vfsmount *mnt;
1679 	struct hstate *h;
1680 	int error;
1681 	int i;
1682 
1683 	if (!hugepages_supported()) {
1684 		pr_info("disabling because there are no supported hugepage sizes\n");
1685 		return -ENOTSUPP;
1686 	}
1687 
1688 	error = -ENOMEM;
1689 	hugetlbfs_inode_cachep = kmem_cache_create("hugetlbfs_inode_cache",
1690 					sizeof(struct hugetlbfs_inode_info),
1691 					0, SLAB_ACCOUNT, init_once);
1692 	if (hugetlbfs_inode_cachep == NULL)
1693 		goto out;
1694 
1695 	error = register_filesystem(&hugetlbfs_fs_type);
1696 	if (error)
1697 		goto out_free;
1698 
1699 	/* default hstate mount is required */
1700 	mnt = mount_one_hugetlbfs(&default_hstate);
1701 	if (IS_ERR(mnt)) {
1702 		error = PTR_ERR(mnt);
1703 		goto out_unreg;
1704 	}
1705 	hugetlbfs_vfsmount[default_hstate_idx] = mnt;
1706 
1707 	/* other hstates are optional */
1708 	i = 0;
1709 	for_each_hstate(h) {
1710 		if (i == default_hstate_idx) {
1711 			i++;
1712 			continue;
1713 		}
1714 
1715 		mnt = mount_one_hugetlbfs(h);
1716 		if (IS_ERR(mnt))
1717 			hugetlbfs_vfsmount[i] = NULL;
1718 		else
1719 			hugetlbfs_vfsmount[i] = mnt;
1720 		i++;
1721 	}
1722 
1723 	return 0;
1724 
1725  out_unreg:
1726 	(void)unregister_filesystem(&hugetlbfs_fs_type);
1727  out_free:
1728 	kmem_cache_destroy(hugetlbfs_inode_cachep);
1729  out:
1730 	return error;
1731 }
1732 fs_initcall(init_hugetlbfs_fs)
1733