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