571 lines · c
1// SPDX-License-Identifier: GPL-2.0-only2/*3 * linux/fs/file_table.c4 *5 * Copyright (C) 1991, 1992 Linus Torvalds6 * Copyright (C) 1997 David S. Miller (davem@caip.rutgers.edu)7 */8 9#include <linux/string.h>10#include <linux/slab.h>11#include <linux/file.h>12#include <linux/fdtable.h>13#include <linux/init.h>14#include <linux/module.h>15#include <linux/fs.h>16#include <linux/filelock.h>17#include <linux/security.h>18#include <linux/cred.h>19#include <linux/eventpoll.h>20#include <linux/rcupdate.h>21#include <linux/mount.h>22#include <linux/capability.h>23#include <linux/cdev.h>24#include <linux/fsnotify.h>25#include <linux/sysctl.h>26#include <linux/percpu_counter.h>27#include <linux/percpu.h>28#include <linux/task_work.h>29#include <linux/swap.h>30#include <linux/kmemleak.h>31 32#include <linux/atomic.h>33 34#include "internal.h"35 36/* sysctl tunables... */37static struct files_stat_struct files_stat = {38 .max_files = NR_FILE39};40 41/* SLAB cache for file structures */42static struct kmem_cache *filp_cachep __ro_after_init;43 44static struct percpu_counter nr_files __cacheline_aligned_in_smp;45 46/* Container for backing file with optional user path */47struct backing_file {48 struct file file;49 struct path user_path;50};51 52static inline struct backing_file *backing_file(struct file *f)53{54 return container_of(f, struct backing_file, file);55}56 57struct path *backing_file_user_path(struct file *f)58{59 return &backing_file(f)->user_path;60}61EXPORT_SYMBOL_GPL(backing_file_user_path);62 63static inline void file_free(struct file *f)64{65 security_file_free(f);66 if (likely(!(f->f_mode & FMODE_NOACCOUNT)))67 percpu_counter_dec(&nr_files);68 put_cred(f->f_cred);69 if (unlikely(f->f_mode & FMODE_BACKING)) {70 path_put(backing_file_user_path(f));71 kfree(backing_file(f));72 } else {73 kmem_cache_free(filp_cachep, f);74 }75}76 77/*78 * Return the total number of open files in the system79 */80static long get_nr_files(void)81{82 return percpu_counter_read_positive(&nr_files);83}84 85/*86 * Return the maximum number of open files in the system87 */88unsigned long get_max_files(void)89{90 return files_stat.max_files;91}92EXPORT_SYMBOL_GPL(get_max_files);93 94#if defined(CONFIG_SYSCTL) && defined(CONFIG_PROC_FS)95 96/*97 * Handle nr_files sysctl98 */99static int proc_nr_files(const struct ctl_table *table, int write, void *buffer,100 size_t *lenp, loff_t *ppos)101{102 files_stat.nr_files = get_nr_files();103 return proc_doulongvec_minmax(table, write, buffer, lenp, ppos);104}105 106static struct ctl_table fs_stat_sysctls[] = {107 {108 .procname = "file-nr",109 .data = &files_stat,110 .maxlen = sizeof(files_stat),111 .mode = 0444,112 .proc_handler = proc_nr_files,113 },114 {115 .procname = "file-max",116 .data = &files_stat.max_files,117 .maxlen = sizeof(files_stat.max_files),118 .mode = 0644,119 .proc_handler = proc_doulongvec_minmax,120 .extra1 = SYSCTL_LONG_ZERO,121 .extra2 = SYSCTL_LONG_MAX,122 },123 {124 .procname = "nr_open",125 .data = &sysctl_nr_open,126 .maxlen = sizeof(unsigned int),127 .mode = 0644,128 .proc_handler = proc_dointvec_minmax,129 .extra1 = &sysctl_nr_open_min,130 .extra2 = &sysctl_nr_open_max,131 },132};133 134static int __init init_fs_stat_sysctls(void)135{136 register_sysctl_init("fs", fs_stat_sysctls);137 if (IS_ENABLED(CONFIG_BINFMT_MISC)) {138 struct ctl_table_header *hdr;139 140 hdr = register_sysctl_mount_point("fs/binfmt_misc");141 kmemleak_not_leak(hdr);142 }143 return 0;144}145fs_initcall(init_fs_stat_sysctls);146#endif147 148static int init_file(struct file *f, int flags, const struct cred *cred)149{150 int error;151 152 f->f_cred = get_cred(cred);153 error = security_file_alloc(f);154 if (unlikely(error)) {155 put_cred(f->f_cred);156 return error;157 }158 159 spin_lock_init(&f->f_lock);160 /*161 * Note that f_pos_lock is only used for files raising162 * FMODE_ATOMIC_POS and directories. Other files such as pipes163 * don't need it and since f_pos_lock is in a union may reuse164 * the space for other purposes. They are expected to initialize165 * the respective member when opening the file.166 */167 mutex_init(&f->f_pos_lock);168 f->f_flags = flags;169 f->f_mode = OPEN_FMODE(flags);170 /* f->f_version: 0 */171 172 /*173 * We're SLAB_TYPESAFE_BY_RCU so initialize f_count last. While174 * fget-rcu pattern users need to be able to handle spurious175 * refcount bumps we should reinitialize the reused file first.176 */177 atomic_long_set(&f->f_count, 1);178 return 0;179}180 181/* Find an unused file structure and return a pointer to it.182 * Returns an error pointer if some error happend e.g. we over file183 * structures limit, run out of memory or operation is not permitted.184 *185 * Be very careful using this. You are responsible for186 * getting write access to any mount that you might assign187 * to this filp, if it is opened for write. If this is not188 * done, you will imbalance int the mount's writer count189 * and a warning at __fput() time.190 */191struct file *alloc_empty_file(int flags, const struct cred *cred)192{193 static long old_max;194 struct file *f;195 int error;196 197 /*198 * Privileged users can go above max_files199 */200 if (get_nr_files() >= files_stat.max_files && !capable(CAP_SYS_ADMIN)) {201 /*202 * percpu_counters are inaccurate. Do an expensive check before203 * we go and fail.204 */205 if (percpu_counter_sum_positive(&nr_files) >= files_stat.max_files)206 goto over;207 }208 209 f = kmem_cache_zalloc(filp_cachep, GFP_KERNEL);210 if (unlikely(!f))211 return ERR_PTR(-ENOMEM);212 213 error = init_file(f, flags, cred);214 if (unlikely(error)) {215 kmem_cache_free(filp_cachep, f);216 return ERR_PTR(error);217 }218 219 percpu_counter_inc(&nr_files);220 221 return f;222 223over:224 /* Ran out of filps - report that */225 if (get_nr_files() > old_max) {226 pr_info("VFS: file-max limit %lu reached\n", get_max_files());227 old_max = get_nr_files();228 }229 return ERR_PTR(-ENFILE);230}231 232/*233 * Variant of alloc_empty_file() that doesn't check and modify nr_files.234 *235 * This is only for kernel internal use, and the allocate file must not be236 * installed into file tables or such.237 */238struct file *alloc_empty_file_noaccount(int flags, const struct cred *cred)239{240 struct file *f;241 int error;242 243 f = kmem_cache_zalloc(filp_cachep, GFP_KERNEL);244 if (unlikely(!f))245 return ERR_PTR(-ENOMEM);246 247 error = init_file(f, flags, cred);248 if (unlikely(error)) {249 kmem_cache_free(filp_cachep, f);250 return ERR_PTR(error);251 }252 253 f->f_mode |= FMODE_NOACCOUNT;254 255 return f;256}257 258/*259 * Variant of alloc_empty_file() that allocates a backing_file container260 * and doesn't check and modify nr_files.261 *262 * This is only for kernel internal use, and the allocate file must not be263 * installed into file tables or such.264 */265struct file *alloc_empty_backing_file(int flags, const struct cred *cred)266{267 struct backing_file *ff;268 int error;269 270 ff = kzalloc(sizeof(struct backing_file), GFP_KERNEL);271 if (unlikely(!ff))272 return ERR_PTR(-ENOMEM);273 274 error = init_file(&ff->file, flags, cred);275 if (unlikely(error)) {276 kfree(ff);277 return ERR_PTR(error);278 }279 280 ff->file.f_mode |= FMODE_BACKING | FMODE_NOACCOUNT;281 return &ff->file;282}283 284/**285 * file_init_path - initialize a 'struct file' based on path286 *287 * @file: the file to set up288 * @path: the (dentry, vfsmount) pair for the new file289 * @fop: the 'struct file_operations' for the new file290 */291static void file_init_path(struct file *file, const struct path *path,292 const struct file_operations *fop)293{294 file->f_path = *path;295 file->f_inode = path->dentry->d_inode;296 file->f_mapping = path->dentry->d_inode->i_mapping;297 file->f_wb_err = filemap_sample_wb_err(file->f_mapping);298 file->f_sb_err = file_sample_sb_err(file);299 if (fop->llseek)300 file->f_mode |= FMODE_LSEEK;301 if ((file->f_mode & FMODE_READ) &&302 likely(fop->read || fop->read_iter))303 file->f_mode |= FMODE_CAN_READ;304 if ((file->f_mode & FMODE_WRITE) &&305 likely(fop->write || fop->write_iter))306 file->f_mode |= FMODE_CAN_WRITE;307 file->f_iocb_flags = iocb_flags(file);308 file->f_mode |= FMODE_OPENED;309 file->f_op = fop;310 if ((file->f_mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ)311 i_readcount_inc(path->dentry->d_inode);312}313 314/**315 * alloc_file - allocate and initialize a 'struct file'316 *317 * @path: the (dentry, vfsmount) pair for the new file318 * @flags: O_... flags with which the new file will be opened319 * @fop: the 'struct file_operations' for the new file320 */321static struct file *alloc_file(const struct path *path, int flags,322 const struct file_operations *fop)323{324 struct file *file;325 326 file = alloc_empty_file(flags, current_cred());327 if (!IS_ERR(file))328 file_init_path(file, path, fop);329 return file;330}331 332static inline int alloc_path_pseudo(const char *name, struct inode *inode,333 struct vfsmount *mnt, struct path *path)334{335 struct qstr this = QSTR_INIT(name, strlen(name));336 337 path->dentry = d_alloc_pseudo(mnt->mnt_sb, &this);338 if (!path->dentry)339 return -ENOMEM;340 path->mnt = mntget(mnt);341 d_instantiate(path->dentry, inode);342 return 0;343}344 345struct file *alloc_file_pseudo(struct inode *inode, struct vfsmount *mnt,346 const char *name, int flags,347 const struct file_operations *fops)348{349 int ret;350 struct path path;351 struct file *file;352 353 ret = alloc_path_pseudo(name, inode, mnt, &path);354 if (ret)355 return ERR_PTR(ret);356 357 file = alloc_file(&path, flags, fops);358 if (IS_ERR(file)) {359 ihold(inode);360 path_put(&path);361 }362 return file;363}364EXPORT_SYMBOL(alloc_file_pseudo);365 366struct file *alloc_file_pseudo_noaccount(struct inode *inode,367 struct vfsmount *mnt, const char *name,368 int flags,369 const struct file_operations *fops)370{371 int ret;372 struct path path;373 struct file *file;374 375 ret = alloc_path_pseudo(name, inode, mnt, &path);376 if (ret)377 return ERR_PTR(ret);378 379 file = alloc_empty_file_noaccount(flags, current_cred());380 if (IS_ERR(file)) {381 ihold(inode);382 path_put(&path);383 return file;384 }385 file_init_path(file, &path, fops);386 return file;387}388EXPORT_SYMBOL_GPL(alloc_file_pseudo_noaccount);389 390struct file *alloc_file_clone(struct file *base, int flags,391 const struct file_operations *fops)392{393 struct file *f;394 395 f = alloc_file(&base->f_path, flags, fops);396 if (!IS_ERR(f)) {397 path_get(&f->f_path);398 f->f_mapping = base->f_mapping;399 }400 return f;401}402 403/* the real guts of fput() - releasing the last reference to file404 */405static HWJS_SUSPENDS void __fput(struct file *file)406{407 struct dentry *dentry = file->f_path.dentry;408 struct vfsmount *mnt = file->f_path.mnt;409 struct inode *inode = file->f_inode;410 fmode_t mode = file->f_mode;411 412 if (unlikely(!(file->f_mode & FMODE_OPENED)))413 goto out;414 415 might_sleep();416 417 fsnotify_close(file);418 /*419 * The function eventpoll_release() should be the first called420 * in the file cleanup chain.421 */422 eventpoll_release(file);423 locks_remove_file(file);424 425 security_file_release(file);426 if (unlikely(file->f_flags & FASYNC)) {427 if (file->f_op->fasync)428 file->f_op->fasync(-1, file, 0);429 }430 if (file->f_op->release)431 file->f_op->release(inode, file);432 if (unlikely(S_ISCHR(inode->i_mode) && inode->i_cdev != NULL &&433 !(mode & FMODE_PATH))) {434 cdev_put(inode->i_cdev);435 }436 fops_put(file->f_op);437 file_f_owner_release(file);438 put_file_access(file);439 dput(dentry);440 if (unlikely(mode & FMODE_NEED_UNMOUNT))441 dissolve_on_fput(mnt);442 mntput(mnt);443out:444 file_free(file);445}446 447static LLIST_HEAD(delayed_fput_list);448static HWJS_SUSPENDS void delayed_fput(struct work_struct *unused)449{450 struct llist_node *node = llist_del_all(&delayed_fput_list);451 struct file *f, *t;452 453 llist_for_each_entry_safe(f, t, node, f_llist)454 __fput(f);455}456 457static void ____fput(struct callback_head *work)458{459 __fput(container_of(work, struct file, f_task_work));460}461 462/*463 * If kernel thread really needs to have the final fput() it has done464 * to complete, call this. The only user right now is the boot - we465 * *do* need to make sure our writes to binaries on initramfs has466 * not left us with opened struct file waiting for __fput() - execve()467 * won't work without that. Please, don't add more callers without468 * very good reasons; in particular, never call that with locks469 * held and never call that from a thread that might need to do470 * some work on any kind of umount.471 */472void flush_delayed_fput(void)473{474 delayed_fput(NULL);475}476EXPORT_SYMBOL_GPL(flush_delayed_fput);477 478static DECLARE_DELAYED_WORK(delayed_fput_work, delayed_fput);479 480void fput(struct file *file)481{482 if (atomic_long_dec_and_test(&file->f_count)) {483#ifndef CONFIG_WASM32484 struct task_struct *task = current;485#endif486 487 if (unlikely(!(file->f_mode & (FMODE_BACKING | FMODE_OPENED)))) {488 file_free(file);489 return;490 }491#ifdef CONFIG_WASM32492 /*493 * K13-D: the wasm32 cooperative kernel has NO drain site for494 * deferred fput — there is no exit-to-user-mode task_work_run495 * on the syscall return path, and no scheduler tick to fire the496 * delayed_fput workqueue while every Worker is parked. Deferring497 * __fput would therefore strand the file's ->release() forever,498 * which is fatal for a pipe: pipe_release() is what decrements499 * pipe->writers and wakes a reader blocked in another Worker500 * (the `cmd1 | cmd2` last-writer-close EOF). Run __fput inline,501 * exactly like __fput_sync(), so the close side effect (EOF /502 * EPIPE / hangup / inode eviction) is observed synchronously.503 * Safe here because the wasm32 model is cooperative and never504 * fputs from hard IRQ context.505 */506 __fput(file);507 return;508#else509 if (likely(!in_interrupt() && !(task->flags & PF_KTHREAD))) {510 init_task_work(&file->f_task_work, ____fput);511 if (!task_work_add(task, &file->f_task_work, TWA_RESUME))512 return;513 /*514 * After this task has run exit_task_work(),515 * task_work_add() will fail. Fall through to delayed516 * fput to avoid leaking *file.517 */518 }519 520 if (llist_add(&file->f_llist, &delayed_fput_list))521 schedule_delayed_work(&delayed_fput_work, 1);522#endif /* CONFIG_WASM32 */523 }524}525 526/*527 * synchronous analog of fput(); for kernel threads that might be needed528 * in some umount() (and thus can't use flush_delayed_fput() without529 * risking deadlocks), need to wait for completion of __fput() and know530 * for this specific struct file it won't involve anything that would531 * need them. Use only if you really need it - at the very least,532 * don't blindly convert fput() by kernel thread to that.533 */534void __fput_sync(struct file *file)535{536 if (atomic_long_dec_and_test(&file->f_count))537 __fput(file);538}539 540EXPORT_SYMBOL(fput);541EXPORT_SYMBOL(__fput_sync);542 543void __init files_init(void)544{545 struct kmem_cache_args args = {546 .use_freeptr_offset = true,547 .freeptr_offset = offsetof(struct file, f_freeptr),548 };549 550 filp_cachep = kmem_cache_create("filp", sizeof(struct file), &args,551 SLAB_HWCACHE_ALIGN | SLAB_PANIC |552 SLAB_ACCOUNT | SLAB_TYPESAFE_BY_RCU);553 percpu_counter_init(&nr_files, 0, GFP_KERNEL);554}555 556/*557 * One file with associated inode and dcache is very roughly 1K. Per default558 * do not use more than 10% of our memory for files.559 */560void __init files_maxfiles_init(void)561{562 unsigned long n;563 unsigned long nr_pages = totalram_pages();564 unsigned long memreserve = (nr_pages - nr_free_pages()) * 3/2;565 566 memreserve = min(memreserve, nr_pages - 1);567 n = ((nr_pages - memreserve) * (PAGE_SIZE / 1024)) / 10;568 569 files_stat.max_files = max_t(unsigned long, n, NR_FILE);570}571