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 __ro_after_init;
45 static struct percpu_counter nr_files __cacheline_aligned_in_smp;
47 /* Container for backing file with optional user path */
50 struct path user_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_user_path(struct file *f)
60 return &backing_file(f)->user_path;
62 EXPORT_SYMBOL_GPL(backing_file_user_path);
64 static inline void file_free(struct file *f)
66 security_file_free(f);
67 if (likely(!(f->f_mode & FMODE_NOACCOUNT)))
68 percpu_counter_dec(&nr_files);
70 if (unlikely(f->f_mode & FMODE_BACKING)) {
71 path_put(backing_file_user_path(f));
72 kfree(backing_file(f));
74 kmem_cache_free(filp_cachep, f);
78 void release_empty_file(struct file *f)
80 WARN_ON_ONCE(f->f_mode & (FMODE_BACKING | FMODE_OPENED));
81 if (atomic_long_dec_and_test(&f->f_count)) {
82 security_file_free(f);
84 if (likely(!(f->f_mode & FMODE_NOACCOUNT)))
85 percpu_counter_dec(&nr_files);
86 kmem_cache_free(filp_cachep, f);
91 * Return the total number of open files in the system
93 static long get_nr_files(void)
95 return percpu_counter_read_positive(&nr_files);
99 * Return the maximum number of open files in the system
101 unsigned long get_max_files(void)
103 return files_stat.max_files;
105 EXPORT_SYMBOL_GPL(get_max_files);
107 #if defined(CONFIG_SYSCTL) && defined(CONFIG_PROC_FS)
110 * Handle nr_files sysctl
112 static int proc_nr_files(struct ctl_table *table, int write, void *buffer,
113 size_t *lenp, loff_t *ppos)
115 files_stat.nr_files = get_nr_files();
116 return proc_doulongvec_minmax(table, write, buffer, lenp, ppos);
119 static struct ctl_table fs_stat_sysctls[] = {
121 .procname = "file-nr",
123 .maxlen = sizeof(files_stat),
125 .proc_handler = proc_nr_files,
128 .procname = "file-max",
129 .data = &files_stat.max_files,
130 .maxlen = sizeof(files_stat.max_files),
132 .proc_handler = proc_doulongvec_minmax,
133 .extra1 = SYSCTL_LONG_ZERO,
134 .extra2 = SYSCTL_LONG_MAX,
137 .procname = "nr_open",
138 .data = &sysctl_nr_open,
139 .maxlen = sizeof(unsigned int),
141 .proc_handler = proc_dointvec_minmax,
142 .extra1 = &sysctl_nr_open_min,
143 .extra2 = &sysctl_nr_open_max,
148 static int __init init_fs_stat_sysctls(void)
150 register_sysctl_init("fs", fs_stat_sysctls);
151 if (IS_ENABLED(CONFIG_BINFMT_MISC)) {
152 struct ctl_table_header *hdr;
153 hdr = register_sysctl_mount_point("fs/binfmt_misc");
154 kmemleak_not_leak(hdr);
158 fs_initcall(init_fs_stat_sysctls);
161 static int init_file(struct file *f, int flags, const struct cred *cred)
165 f->f_cred = get_cred(cred);
166 error = security_file_alloc(f);
167 if (unlikely(error)) {
172 rwlock_init(&f->f_owner.lock);
173 spin_lock_init(&f->f_lock);
174 mutex_init(&f->f_pos_lock);
176 f->f_mode = OPEN_FMODE(flags);
177 /* f->f_version: 0 */
180 * We're SLAB_TYPESAFE_BY_RCU so initialize f_count last. While
181 * fget-rcu pattern users need to be able to handle spurious
182 * refcount bumps we should reinitialize the reused file first.
184 atomic_long_set(&f->f_count, 1);
188 /* Find an unused file structure and return a pointer to it.
189 * Returns an error pointer if some error happend e.g. we over file
190 * structures limit, run out of memory or operation is not permitted.
192 * Be very careful using this. You are responsible for
193 * getting write access to any mount that you might assign
194 * to this filp, if it is opened for write. If this is not
195 * done, you will imbalance int the mount's writer count
196 * and a warning at __fput() time.
198 struct file *alloc_empty_file(int flags, const struct cred *cred)
205 * Privileged users can go above max_files
207 if (get_nr_files() >= files_stat.max_files && !capable(CAP_SYS_ADMIN)) {
209 * percpu_counters are inaccurate. Do an expensive check before
212 if (percpu_counter_sum_positive(&nr_files) >= files_stat.max_files)
216 f = kmem_cache_zalloc(filp_cachep, GFP_KERNEL);
218 return ERR_PTR(-ENOMEM);
220 error = init_file(f, flags, cred);
221 if (unlikely(error)) {
222 kmem_cache_free(filp_cachep, f);
223 return ERR_PTR(error);
226 percpu_counter_inc(&nr_files);
231 /* Ran out of filps - report that */
232 if (get_nr_files() > old_max) {
233 pr_info("VFS: file-max limit %lu reached\n", get_max_files());
234 old_max = get_nr_files();
236 return ERR_PTR(-ENFILE);
240 * Variant of alloc_empty_file() that doesn't check and modify nr_files.
242 * This is only for kernel internal use, and the allocate file must not be
243 * installed into file tables or such.
245 struct file *alloc_empty_file_noaccount(int flags, const struct cred *cred)
250 f = kmem_cache_zalloc(filp_cachep, GFP_KERNEL);
252 return ERR_PTR(-ENOMEM);
254 error = init_file(f, flags, cred);
255 if (unlikely(error)) {
256 kmem_cache_free(filp_cachep, f);
257 return ERR_PTR(error);
260 f->f_mode |= FMODE_NOACCOUNT;
266 * Variant of alloc_empty_file() that allocates a backing_file container
267 * and doesn't check and modify nr_files.
269 * This is only for kernel internal use, and the allocate file must not be
270 * installed into file tables or such.
272 struct file *alloc_empty_backing_file(int flags, const struct cred *cred)
274 struct backing_file *ff;
277 ff = kzalloc(sizeof(struct backing_file), GFP_KERNEL);
279 return ERR_PTR(-ENOMEM);
281 error = init_file(&ff->file, flags, cred);
282 if (unlikely(error)) {
284 return ERR_PTR(error);
287 ff->file.f_mode |= FMODE_BACKING | FMODE_NOACCOUNT;
292 * alloc_file - allocate and initialize a 'struct file'
294 * @path: the (dentry, vfsmount) pair for the new file
295 * @flags: O_... flags with which the new file will be opened
296 * @fop: the 'struct file_operations' for the new file
298 static struct file *alloc_file(const struct path *path, int flags,
299 const struct file_operations *fop)
303 file = alloc_empty_file(flags, current_cred());
307 file->f_path = *path;
308 file->f_inode = path->dentry->d_inode;
309 file->f_mapping = path->dentry->d_inode->i_mapping;
310 file->f_wb_err = filemap_sample_wb_err(file->f_mapping);
311 file->f_sb_err = file_sample_sb_err(file);
313 file->f_mode |= FMODE_LSEEK;
314 if ((file->f_mode & FMODE_READ) &&
315 likely(fop->read || fop->read_iter))
316 file->f_mode |= FMODE_CAN_READ;
317 if ((file->f_mode & FMODE_WRITE) &&
318 likely(fop->write || fop->write_iter))
319 file->f_mode |= FMODE_CAN_WRITE;
320 file->f_iocb_flags = iocb_flags(file);
321 file->f_mode |= FMODE_OPENED;
323 if ((file->f_mode & (FMODE_READ | FMODE_WRITE)) == FMODE_READ)
324 i_readcount_inc(path->dentry->d_inode);
328 struct file *alloc_file_pseudo(struct inode *inode, struct vfsmount *mnt,
329 const char *name, int flags,
330 const struct file_operations *fops)
332 static const struct dentry_operations anon_ops = {
333 .d_dname = simple_dname
335 struct qstr this = QSTR_INIT(name, strlen(name));
339 path.dentry = d_alloc_pseudo(mnt->mnt_sb, &this);
341 return ERR_PTR(-ENOMEM);
342 if (!mnt->mnt_sb->s_d_op)
343 d_set_d_op(path.dentry, &anon_ops);
344 path.mnt = mntget(mnt);
345 d_instantiate(path.dentry, inode);
346 file = alloc_file(&path, flags, fops);
353 EXPORT_SYMBOL(alloc_file_pseudo);
355 struct file *alloc_file_clone(struct file *base, int flags,
356 const struct file_operations *fops)
358 struct file *f = alloc_file(&base->f_path, flags, fops);
360 path_get(&f->f_path);
361 f->f_mapping = base->f_mapping;
366 /* the real guts of fput() - releasing the last reference to file
368 static void __fput(struct file *file)
370 struct dentry *dentry = file->f_path.dentry;
371 struct vfsmount *mnt = file->f_path.mnt;
372 struct inode *inode = file->f_inode;
373 fmode_t mode = file->f_mode;
375 if (unlikely(!(file->f_mode & FMODE_OPENED)))
380 fsnotify_close(file);
382 * The function eventpoll_release() should be the first called
383 * in the file cleanup chain.
385 eventpoll_release(file);
386 locks_remove_file(file);
389 if (unlikely(file->f_flags & FASYNC)) {
390 if (file->f_op->fasync)
391 file->f_op->fasync(-1, file, 0);
393 if (file->f_op->release)
394 file->f_op->release(inode, file);
395 if (unlikely(S_ISCHR(inode->i_mode) && inode->i_cdev != NULL &&
396 !(mode & FMODE_PATH))) {
397 cdev_put(inode->i_cdev);
399 fops_put(file->f_op);
400 put_pid(file->f_owner.pid);
401 put_file_access(file);
403 if (unlikely(mode & FMODE_NEED_UNMOUNT))
404 dissolve_on_fput(mnt);
410 static LLIST_HEAD(delayed_fput_list);
411 static void delayed_fput(struct work_struct *unused)
413 struct llist_node *node = llist_del_all(&delayed_fput_list);
416 llist_for_each_entry_safe(f, t, node, f_llist)
420 static void ____fput(struct callback_head *work)
422 __fput(container_of(work, struct file, f_rcuhead));
426 * If kernel thread really needs to have the final fput() it has done
427 * to complete, call this. The only user right now is the boot - we
428 * *do* need to make sure our writes to binaries on initramfs has
429 * not left us with opened struct file waiting for __fput() - execve()
430 * won't work without that. Please, don't add more callers without
431 * very good reasons; in particular, never call that with locks
432 * held and never call that from a thread that might need to do
433 * some work on any kind of umount.
435 void flush_delayed_fput(void)
439 EXPORT_SYMBOL_GPL(flush_delayed_fput);
441 static DECLARE_DELAYED_WORK(delayed_fput_work, delayed_fput);
443 void fput(struct file *file)
445 if (atomic_long_dec_and_test(&file->f_count)) {
446 struct task_struct *task = current;
448 if (likely(!in_interrupt() && !(task->flags & PF_KTHREAD))) {
449 init_task_work(&file->f_rcuhead, ____fput);
450 if (!task_work_add(task, &file->f_rcuhead, TWA_RESUME))
453 * After this task has run exit_task_work(),
454 * task_work_add() will fail. Fall through to delayed
455 * fput to avoid leaking *file.
459 if (llist_add(&file->f_llist, &delayed_fput_list))
460 schedule_delayed_work(&delayed_fput_work, 1);
465 * synchronous analog of fput(); for kernel threads that might be needed
466 * in some umount() (and thus can't use flush_delayed_fput() without
467 * risking deadlocks), need to wait for completion of __fput() and know
468 * for this specific struct file it won't involve anything that would
469 * need them. Use only if you really need it - at the very least,
470 * don't blindly convert fput() by kernel thread to that.
472 void __fput_sync(struct file *file)
474 if (atomic_long_dec_and_test(&file->f_count))
479 EXPORT_SYMBOL(__fput_sync);
481 void __init files_init(void)
483 filp_cachep = kmem_cache_create("filp", sizeof(struct file), 0,
484 SLAB_TYPESAFE_BY_RCU | SLAB_HWCACHE_ALIGN |
485 SLAB_PANIC | SLAB_ACCOUNT, NULL);
486 percpu_counter_init(&nr_files, 0, GFP_KERNEL);
490 * One file with associated inode and dcache is very roughly 1K. Per default
491 * do not use more than 10% of our memory for files.
493 void __init files_maxfiles_init(void)
496 unsigned long nr_pages = totalram_pages();
497 unsigned long memreserve = (nr_pages - nr_free_pages()) * 3/2;
499 memreserve = min(memreserve, nr_pages - 1);
500 n = ((nr_pages - memreserve) * (PAGE_SIZE / 1024)) / 10;
502 files_stat.max_files = max_t(unsigned long, n, NR_FILE);