~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/fs/hugetlbfs/inode.c

Version: ~ [ linux-6.11-rc3 ] ~ [ linux-6.10.4 ] ~ [ linux-6.9.12 ] ~ [ linux-6.8.12 ] ~ [ linux-6.7.12 ] ~ [ linux-6.6.45 ] ~ [ linux-6.5.13 ] ~ [ linux-6.4.16 ] ~ [ linux-6.3.13 ] ~ [ linux-6.2.16 ] ~ [ linux-6.1.104 ] ~ [ linux-6.0.19 ] ~ [ linux-5.19.17 ] ~ [ linux-5.18.19 ] ~ [ linux-5.17.15 ] ~ [ linux-5.16.20 ] ~ [ linux-5.15.164 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.223 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.281 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.319 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.336 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.337 ] ~ [ linux-4.4.302 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.9 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

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

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

sflogo.php