1 // SPDX-License-Identifier: GPL-2.0-only
3 * linux/fs/file_table.c
5 * Copyright (C) 1991, 1992 Linus Torvalds
6 * Copyright (C) 1997 David S. Miller (davem@caip.rutgers.edu)
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>
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/ima.h>
30 #include <linux/swap.h>
31 #include <linux/kmemleak.h>
33 #include <linux/atomic.h>
37 /* sysctl tunables... */
38 static struct files_stat_struct files_stat = {
42 /* SLAB cache for file structures */
43 static struct kmem_cache *filp_cachep __read_mostly;
45 static struct percpu_counter nr_files __cacheline_aligned_in_smp;
47 /* Container for backing file with optional real path */
50 struct path real_path;
53 static inline struct backing_file *backing_file(struct file *f)
55 return container_of(f, struct backing_file, file);
58 struct path *backing_file_real_path(struct file *f)
60 return &backing_file(f)->real_path;
62 EXPORT_SYMBOL_GPL(backing_file_real_path);
64 static void file_free_rcu(struct rcu_head *head)
66 struct file *f = container_of(head, struct file, f_rcuhead);
69 if (unlikely(f->f_mode & FMODE_BACKING))
70 kfree(backing_file(f));
72 kmem_cache_free(filp_cachep, f);
75 static inline void file_free(struct file *f)
77 security_file_free(f);
78 if (unlikely(f->f_mode & FMODE_BACKING))
79 path_put(backing_file_real_path(f));
80 if (likely(!(f->f_mode & FMODE_NOACCOUNT)))
81 percpu_counter_dec(&nr_files);
82 call_rcu(&f->f_rcuhead, file_free_rcu);
86 * Return the total number of open files in the system
88 static long get_nr_files(void)
90 return percpu_counter_read_positive(&nr_files);
94 * Return the maximum number of open files in the system
96 unsigned long get_max_files(void)
98 return files_stat.max_files;
100 EXPORT_SYMBOL_GPL(get_max_files);
102 #if defined(CONFIG_SYSCTL) && defined(CONFIG_PROC_FS)
105 * Handle nr_files sysctl
107 static int proc_nr_files(struct ctl_table *table, int write, void *buffer,
108 size_t *lenp, loff_t *ppos)
110 files_stat.nr_files = get_nr_files();
111 return proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
114 static struct ctl_table fs_stat_sysctls[] = {
116 .procname = "file-nr",
118 .maxlen = sizeof(files_stat),
120 .proc_handler = proc_nr_files,
123 .procname = "file-max",
124 .data = &files_stat.max_files,
125 .maxlen = sizeof(files_stat.max_files),
127 .proc_handler = proc_doulongvec_minmax,
128 .extra1 = SYSCTL_LONG_ZERO,
129 .extra2 = SYSCTL_LONG_MAX,
132 .procname = "nr_open",
133 .data = &sysctl_nr_open,
134 .maxlen = sizeof(unsigned int),
136 .proc_handler = proc_dointvec_minmax,
137 .extra1 = &sysctl_nr_open_min,
138 .extra2 = &sysctl_nr_open_max,
143 static int __init init_fs_stat_sysctls(void)
145 register_sysctl_init("fs", fs_stat_sysctls);
146 if (IS_ENABLED(CONFIG_BINFMT_MISC)) {
147 struct ctl_table_header *hdr;
148 hdr = register_sysctl_mount_point("fs/binfmt_misc");
149 kmemleak_not_leak(hdr);
153 fs_initcall(init_fs_stat_sysctls);
156 static int init_file(struct file *f, int flags, const struct cred *cred)
160 f->f_cred = get_cred(cred);
161 error = security_file_alloc(f);
162 if (unlikely(error)) {
163 file_free_rcu(&f->f_rcuhead);
167 atomic_long_set(&f->f_count, 1);
168 rwlock_init(&f->f_owner.lock);
169 spin_lock_init(&f->f_lock);
170 mutex_init(&f->f_pos_lock);
172 f->f_mode = OPEN_FMODE(flags);
173 /* f->f_version: 0 */
178 /* Find an unused file structure and return a pointer to it.
179 * Returns an error pointer if some error happend e.g. we over file
180 * structures limit, run out of memory or operation is not permitted.
182 * Be very careful using this. You are responsible for
183 * getting write access to any mount that you might assign
184 * to this filp, if it is opened for write. If this is not
185 * done, you will imbalance int the mount's writer count
186 * and a warning at __fput() time.
188 struct file *alloc_empty_file(int flags, const struct cred *cred)
195 * Privileged users can go above max_files
197 if (get_nr_files() >= files_stat.max_files && !capable(CAP_SYS_ADMIN)) {
199 * percpu_counters are inaccurate. Do an expensive check before
202 if (percpu_counter_sum_positive(&nr_files) >= files_stat.max_files)
206 f = kmem_cache_zalloc(filp_cachep, GFP_KERNEL);
208 return ERR_PTR(-ENOMEM);
210 error = init_file(f, flags, cred);
212 return ERR_PTR(error);
214 percpu_counter_inc(&nr_files);
219 /* Ran out of filps - report that */
220 if (get_nr_files() > old_max) {
221 pr_info("VFS: file-max limit %lu reached\n", get_max_files());
222 old_max = get_nr_files();
224 return ERR_PTR(-ENFILE);
228 * Variant of alloc_empty_file() that doesn't check and modify nr_files.
230 * This is only for kernel internal use, and the allocate file must not be
231 * installed into file tables or such.
233 struct file *alloc_empty_file_noaccount(int flags, const struct cred *cred)
238 f = kmem_cache_zalloc(filp_cachep, GFP_KERNEL);
240 return ERR_PTR(-ENOMEM);
242 error = init_file(f, flags, cred);
244 return ERR_PTR(error);
246 f->f_mode |= FMODE_NOACCOUNT;
252 * Variant of alloc_empty_file() that allocates a backing_file container
253 * and doesn't check and modify nr_files.
255 * This is only for kernel internal use, and the allocate file must not be
256 * installed into file tables or such.
258 struct file *alloc_empty_backing_file(int flags, const struct cred *cred)
260 struct backing_file *ff;
263 ff = kzalloc(sizeof(struct backing_file), GFP_KERNEL);
265 return ERR_PTR(-ENOMEM);
267 error = init_file(&ff->file, flags, cred);
269 return ERR_PTR(error);
271 ff->file.f_mode |= FMODE_BACKING | FMODE_NOACCOUNT;
276 * alloc_file - allocate and initialize a 'struct file'
278 * @path: the (dentry, vfsmount) pair for the new file
279 * @flags: O_... flags with which the new file will be opened
280 * @fop: the 'struct file_operations' for the new file
282 static struct file *alloc_file(const struct path *path, int flags,
283 const struct file_operations *fop)
287 file = alloc_empty_file(flags, current_cred());
291 file->f_path = *path;
292 file->f_inode = path->dentry->d_inode;
293 file->f_mapping = path->dentry->d_inode->i_mapping;
294 file->f_wb_err = filemap_sample_wb_err(file->f_mapping);
295 file->f_sb_err = file_sample_sb_err(file);
297 file->f_mode |= FMODE_LSEEK;
298 if ((file->f_mode & FMODE_READ) &&
299 likely(fop->read || fop->read_iter))
300 file->f_mode |= FMODE_CAN_READ;
301 if ((file->f_mode & FMODE_WRITE) &&
302 likely(fop->write || fop->write_iter))
303 file->f_mode |= FMODE_CAN_WRITE;
304 file->f_iocb_flags = iocb_flags(file);
305 file->f_mode |= FMODE_OPENED;
307 if ((file->f_mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ)
308 i_readcount_inc(path->dentry->d_inode);
312 struct file *alloc_file_pseudo(struct inode *inode, struct vfsmount *mnt,
313 const char *name, int flags,
314 const struct file_operations *fops)
316 static const struct dentry_operations anon_ops = {
317 .d_dname = simple_dname
319 struct qstr this = QSTR_INIT(name, strlen(name));
323 path.dentry = d_alloc_pseudo(mnt->mnt_sb, &this);
325 return ERR_PTR(-ENOMEM);
326 if (!mnt->mnt_sb->s_d_op)
327 d_set_d_op(path.dentry, &anon_ops);
328 path.mnt = mntget(mnt);
329 d_instantiate(path.dentry, inode);
330 file = alloc_file(&path, flags, fops);
337 EXPORT_SYMBOL(alloc_file_pseudo);
339 struct file *alloc_file_clone(struct file *base, int flags,
340 const struct file_operations *fops)
342 struct file *f = alloc_file(&base->f_path, flags, fops);
344 path_get(&f->f_path);
345 f->f_mapping = base->f_mapping;
350 /* the real guts of fput() - releasing the last reference to file
352 static void __fput(struct file *file)
354 struct dentry *dentry = file->f_path.dentry;
355 struct vfsmount *mnt = file->f_path.mnt;
356 struct inode *inode = file->f_inode;
357 fmode_t mode = file->f_mode;
359 if (unlikely(!(file->f_mode & FMODE_OPENED)))
364 fsnotify_close(file);
366 * The function eventpoll_release() should be the first called
367 * in the file cleanup chain.
369 eventpoll_release(file);
370 locks_remove_file(file);
373 if (unlikely(file->f_flags & FASYNC)) {
374 if (file->f_op->fasync)
375 file->f_op->fasync(-1, file, 0);
377 if (file->f_op->release)
378 file->f_op->release(inode, file);
379 if (unlikely(S_ISCHR(inode->i_mode) && inode->i_cdev != NULL &&
380 !(mode & FMODE_PATH))) {
381 cdev_put(inode->i_cdev);
383 fops_put(file->f_op);
384 put_pid(file->f_owner.pid);
385 put_file_access(file);
387 if (unlikely(mode & FMODE_NEED_UNMOUNT))
388 dissolve_on_fput(mnt);
394 static LLIST_HEAD(delayed_fput_list);
395 static void delayed_fput(struct work_struct *unused)
397 struct llist_node *node = llist_del_all(&delayed_fput_list);
400 llist_for_each_entry_safe(f, t, node, f_llist)
404 static void ____fput(struct callback_head *work)
406 __fput(container_of(work, struct file, f_rcuhead));
410 * If kernel thread really needs to have the final fput() it has done
411 * to complete, call this. The only user right now is the boot - we
412 * *do* need to make sure our writes to binaries on initramfs has
413 * not left us with opened struct file waiting for __fput() - execve()
414 * won't work without that. Please, don't add more callers without
415 * very good reasons; in particular, never call that with locks
416 * held and never call that from a thread that might need to do
417 * some work on any kind of umount.
419 void flush_delayed_fput(void)
423 EXPORT_SYMBOL_GPL(flush_delayed_fput);
425 static DECLARE_DELAYED_WORK(delayed_fput_work, delayed_fput);
427 void fput(struct file *file)
429 if (atomic_long_dec_and_test(&file->f_count)) {
430 struct task_struct *task = current;
432 if (likely(!in_interrupt() && !(task->flags & PF_KTHREAD))) {
433 init_task_work(&file->f_rcuhead, ____fput);
434 if (!task_work_add(task, &file->f_rcuhead, TWA_RESUME))
437 * After this task has run exit_task_work(),
438 * task_work_add() will fail. Fall through to delayed
439 * fput to avoid leaking *file.
443 if (llist_add(&file->f_llist, &delayed_fput_list))
444 schedule_delayed_work(&delayed_fput_work, 1);
449 * synchronous analog of fput(); for kernel threads that might be needed
450 * in some umount() (and thus can't use flush_delayed_fput() without
451 * risking deadlocks), need to wait for completion of __fput() and know
452 * for this specific struct file it won't involve anything that would
453 * need them. Use only if you really need it - at the very least,
454 * don't blindly convert fput() by kernel thread to that.
456 void __fput_sync(struct file *file)
458 if (atomic_long_dec_and_test(&file->f_count)) {
459 struct task_struct *task = current;
460 BUG_ON(!(task->flags & PF_KTHREAD));
466 EXPORT_SYMBOL(__fput_sync);
468 void __init files_init(void)
470 filp_cachep = kmem_cache_create("filp", sizeof(struct file), 0,
471 SLAB_HWCACHE_ALIGN | SLAB_PANIC | SLAB_ACCOUNT, NULL);
472 percpu_counter_init(&nr_files, 0, GFP_KERNEL);
476 * One file with associated inode and dcache is very roughly 1K. Per default
477 * do not use more than 10% of our memory for files.
479 void __init files_maxfiles_init(void)
482 unsigned long nr_pages = totalram_pages();
483 unsigned long memreserve = (nr_pages - nr_free_pages()) * 3/2;
485 memreserve = min(memreserve, nr_pages - 1);
486 n = ((nr_pages - memreserve) * (PAGE_SIZE / 1024)) / 10;
488 files_stat.max_files = max_t(unsigned long, n, NR_FILE);